diff --git a/RESOURCES.md b/RESOURCES.md index 3ec81f5..aec7a25 100644 --- a/RESOURCES.md +++ b/RESOURCES.md @@ -135,8 +135,8 @@ TLS 证书、缓存容量、访问日志和服务条款由服主负责。公网 `` 和 `` 必须分别等于客户端包内 `versions.json` 的 `bundle_version` 与 `game_data_version`。例如当前发布版本对应: ```text -ServerData/StandaloneWindows64/HD/20261007175947/ -GameData/20261008155037/ +ServerData/StandaloneWindows64/HD/20261022174708/ +GameData/20261021182514/ ``` 准备完成后,在 `bd2client` 中选择“本地已下载资源”,并选中最外层的 `<本地资源根目录>`,不要直接选择 `ServerData`、`GameData` 或某个版本号目录。客户端会验证目录结构和版本,然后由 LI 插件在游戏进程内把该目录作为仅监听 loopback 的本机资源源提供给游戏。校验失败时需要玩家自行修正或重新准备资源,客户端不会跨版本拼接或自动从网络补齐缺失文件。 diff --git a/go/internal/server/app/achievement_level_mission_integration_test.go b/go/internal/server/app/achievement_level_mission_integration_test.go new file mode 100644 index 0000000..0c90777 --- /dev/null +++ b/go/internal/server/app/achievement_level_mission_integration_test.go @@ -0,0 +1,131 @@ +//go:build integration + +package app + +import ( + "encoding/json" + "testing" + + "bd2server/internal/server/domain/command" +) + +func guideStepOne(t *testing.T, g *missionGameplay) (map[uint64]bool, uint64) { + t.Helper() + design := g.factory.design.eventTasksDesign + groups := map[uint64]bool{} + var passID uint64 + for id, pass := range design.Passes { + if pass.ScheduleType != 0 || pass.NewbieGroup == 0 || pass.NewbieStep != 1 { + continue + } + if passID == 0 { + passID = id + } + for _, group := range design.MissionGroups[pass.MissionGroup].Groups { + groups[group] = true + } + } + if passID == 0 || len(groups) == 0 { + t.Fatal("GameData has no guide pass step 1") + } + return groups, passID +} + +func guideConditionMission(t *testing.T, g *missionGameplay, groups map[uint64]bool, condition, subtype uint64) ([]byte, uint64) { + t.Helper() + design := g.factory.design.eventTasksDesign + for _, row := range appRows(g.call("/EventMissionInfo", nil), 1) { + task, found := design.Missions[appValue(row, 3)] + if found && groups[task.Group] && task.Type == condition && task.SubType == subtype { + return row, task.ID + } + } + return nil, 0 +} + +// clearEventMissions keeps durable reward claims but removes every derived +// mission value, reproducing an account that claimed before the pass existed. +func clearEventMissions(t *testing.T, g *missionGameplay) { + t.Helper() + s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account} + s.run(t, true, func(ctx command.Context, p *playerAssembly) { + raw, err := p.gameplayStore.Load(ctx.State, "eventtasks") + if err != nil { + t.Fatal(err) + } + var state map[string]json.RawMessage + if err := json.Unmarshal(raw, &state); err != nil { + t.Fatal(err) + } + state["Missions"] = json.RawMessage(`{}`) + raw, err = json.Marshal(state) + if err != nil { + t.Fatal(err) + } + if err := p.gameplayStore.Save(ctx.State, "eventtasks", raw); err != nil { + t.Fatal(err) + } + }) + g.reopen() +} + +func missionTarget(t *testing.T, g *missionGameplay, id uint64) uint64 { + t.Helper() + target := g.factory.design.eventTasksDesign.Missions[id].Target + if target == 0 { + return 1 + } + return target +} + +// Define_MissionConditionType.McRewardToAchievementLevel is condition 221. +func TestGuidePassAchievementLevelMissionDerivesFromClaimedReward(t *testing.T) { + g := newMissionGameplay(t) + groups, _ := guideStepOne(t, g) + row, id := guideConditionMission(t, g, groups, 221, 1) + if row == nil { + t.Fatal("achievement level mission missing from EventMissionInfo") + } + want := missionTarget(t, g, id) + if got := appValue(row, 4); got != 0 { + t.Fatalf("achievement level mission started at %d, want 0", got) + } + g.call("/UserLevelReward", appScalar(2, 1)) + clearEventMissions(t, g) + row, _ = guideConditionMission(t, g, groups, 221, 1) + if row == nil { + t.Fatal("achievement level mission disappeared after claiming") + } + if got := appValue(row, 4); got != want { + t.Fatalf("achievement level mission value=%d, want %d", got, want) + } + if again, _ := guideConditionMission(t, g, groups, 221, 1); appValue(again, 4) != want { + t.Fatalf("repeated reconciliation changed mission value to %d", appValue(again, 4)) + } +} + +// Define_MissionConditionType.McRewardToPassLevel is condition 223. +func TestGuidePassPassLevelMissionDerivesFromClaimedReward(t *testing.T) { + g := newMissionGameplay(t) + groups, passID := guideStepOne(t, g) + row, id := guideConditionMission(t, g, groups, 223, 1) + if row == nil { + t.Fatal("pass level mission missing from EventMissionInfo") + } + want := missionTarget(t, g, id) + if got := appValue(row, 4); got != 0 { + t.Fatalf("pass level mission started at %d, want 0", got) + } + g.call("/PassReward", append(appScalar(3, passID), appScalar(4, 1)...)) + clearEventMissions(t, g) + row, _ = guideConditionMission(t, g, groups, 223, 1) + if row == nil { + t.Fatal("pass level mission disappeared after claiming") + } + if got := appValue(row, 4); got != want { + t.Fatalf("pass level mission value=%d, want %d", got, want) + } + if again, _ := guideConditionMission(t, g, groups, 223, 1); appValue(again, 4) != want { + t.Fatalf("repeated reconciliation changed mission value to %d", appValue(again, 4)) + } +} diff --git a/go/internal/server/app/achievement_reconcile_integration_test.go b/go/internal/server/app/achievement_reconcile_integration_test.go index b4398b4..dd7c2d5 100644 --- a/go/internal/server/app/achievement_reconcile_integration_test.go +++ b/go/internal/server/app/achievement_reconcile_integration_test.go @@ -50,7 +50,7 @@ func TestAchievementReconcileHistoricalCompoundTitleRequiresClaim(t *testing.T) t.Fatal(err) } defer func() { _ = tx.Rollback() }() - c := command.Context{State: tx} + c := command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()} var costume roster.Costume for _, owned := range p.collection.Costumes() { if p.design.costumePotentialDesign.CostumeUnique[owned.ID] == 1 { @@ -180,7 +180,7 @@ func TestAchievementReconcilePreservesLargerHistoryAndCountsNewGrantOnce(t *test t.Fatal(err) } defer func() { _ = tx.Rollback() }() - c := command.Context{Identity: command.Identity{AccountID: g.account, SessionID: "history-grant"}, State: tx} + c := command.Context{Identity: command.Identity{AccountID: g.account, SessionID: "history-grant"}, State: tx, InstanceIDs: g.factory.instanceIDs()} request := wire.AppendVarint(nil, 1, 77) observer := g.owner.assembly.achievementObserver if err := observer.BeforeDispatch(c, "/GachaBuy", request); err != nil { diff --git a/go/internal/server/app/avatar_profile_integration_test.go b/go/internal/server/app/avatar_profile_integration_test.go index 5d369d6..60088ea 100644 --- a/go/internal/server/app/avatar_profile_integration_test.go +++ b/go/internal/server/app/avatar_profile_integration_test.go @@ -13,10 +13,11 @@ import ( "bd2server/internal/server/protocol/wire" ) -func TestPurchasedAvatarAndPartsBecomePersistentProfileEquipment(t *testing.T) { +func TestFirstAvatarChoiceAndPartsBecomePersistentProfileEquipment(t *testing.T) { // AvatarPacket buys a character and its authored outfit before AvatarSave. - // Current GameData: shop 1 costs 1000 type44 and grants char 1 with - // hair 10001, outfit 40001, head accessory 20001. Motion 100001 is free. + // Current GameData: shop 1's nominal price is 1000 type44 and grants char1 + // with hair10001, outfit40001, head20001. The server's first-choice policy + // waives that price once; later purchases retain the authored prices. factory, accounts := newIntegrationFactory(t) owner, err := factory.open(accounts[0]) if err != nil { @@ -34,7 +35,7 @@ func TestPurchasedAvatarAndPartsBecomePersistentProfileEquipment(t *testing.T) { if err != nil { t.Fatal(err) } - ctx := command.Context{State: tx} + ctx := command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()} if _, err = g.owner.assembly.eventEconomy.Apply(ctx, "avatar-test-budget", nil, []gamedata.Reward{{Type: 44, Count: 2500}}); err != nil { _ = tx.Rollback() t.Fatal(err) @@ -49,8 +50,8 @@ func TestPurchasedAvatarAndPartsBecomePersistentProfileEquipment(t *testing.T) { product = wire.AppendBytes(product, 2, price) buy := g.request("/AvatarShopBuy", wire.AppendBytes(nil, 2, product)) g.execute(buy, false) - if got := g.wordCurrency(); got != budget-1000 { - t.Fatalf("avatar purchase balance=%d want %d", got, budget-1000) + if got := g.wordCurrency(); got != budget { + t.Fatalf("first choice changed balance=%d want %d", got, budget) } for _, asset := range [][2]uint64{{61, 1}, {49, 10001}, {49, 20001}, {49, 40001}} { if g.itemCount(asset[0], asset[1]) != 1 { @@ -58,7 +59,7 @@ func TestPurchasedAvatarAndPartsBecomePersistentProfileEquipment(t *testing.T) { } } g.execute(buy, false) - if g.wordCurrency() != budget-1000 || g.itemCount(61, 1) != 1 { + if g.wordCurrency() != budget || g.itemCount(61, 1) != 1 { t.Fatal("replayed avatar purchase charged or granted again") } unowned := wire.AppendVarint(nil, 1, 1) @@ -70,11 +71,11 @@ func TestPurchasedAvatarAndPartsBecomePersistentProfileEquipment(t *testing.T) { use = wire.AppendVarint(use, 5, 40001) g.call("/AvatarSave", wire.AppendBytes(nil, 2, use)) g.call("/AvatarMotionShopBuy", wire.AppendVarint(nil, 2, 100001)) - if g.itemCount(50, 100001) != 1 || g.wordCurrency() != budget-1000 { + if g.itemCount(50, 100001) != 1 || g.wordCurrency() != budget { t.Fatal("free motion was not granted without currency consumption") } g.execute(g.request("/AvatarMotionShopBuy", wire.AppendVarint(nil, 2, 100001)), true) - if g.itemCount(50, 100001) != 1 || g.wordCurrency() != budget-1000 { + if g.itemCount(50, 100001) != 1 || g.wordCurrency() != budget { t.Fatal("repeated free motion changed ownership or charged currency") } wishlist := wire.AppendVarint(nil, 2, 40015) @@ -150,7 +151,7 @@ func TestPurchasedAvatarAndPartsBecomePersistentProfileEquipment(t *testing.T) { if len(decodeWishlist(list)) != 0 { t.Fatal("wishlist removal did not clear the persisted list") } - if g.wordCurrency() != budget-1000 || g.itemCount(61, 1) != 1 || g.itemCount(50, 100001) != 1 { + if g.wordCurrency() != budget || g.itemCount(61, 1) != 1 || g.itemCount(50, 100001) != 1 { t.Fatal("reopening or profile queries changed purchased assets") } } @@ -211,7 +212,7 @@ func TestAvatarDiamondPurchaseAndInvalidEquipmentBatchRemainAtomic(t *testing.T) if err != nil { t.Fatal(err) } - if _, err = g.owner.assembly.eventEconomy.Apply(command.Context{State: tx}, "avatar-batch-and-collab-budget", nil, []gamedata.Reward{{Type: 44, Count: 2000}, {Type: 61, ID: 18, Count: 1}, {Type: 49, ID: 40015, Count: 1}}); err != nil { + if _, err = g.owner.assembly.eventEconomy.Apply(command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}, "avatar-batch-and-collab-budget", nil, []gamedata.Reward{{Type: 44, Count: 2000}, {Type: 61, ID: 18, Count: 1}, {Type: 49, ID: 40015, Count: 1}}); err != nil { _ = tx.Rollback() t.Fatal(err) } diff --git a/go/internal/server/app/cafeteria_step_integration_test.go b/go/internal/server/app/cafeteria_step_integration_test.go new file mode 100644 index 0000000..b96f6a4 --- /dev/null +++ b/go/internal/server/app/cafeteria_step_integration_test.go @@ -0,0 +1,127 @@ +//go:build integration + +package app + +import ( + "encoding/json" + "testing" + + "bd2server/internal/server/domain/command" +) + +// GameFieldManager.IEnteredCafeteriaPackField claims the introduction on every +// cafeteria entry while ContentUnlockDating (ContentOpenTable group19/detail1) +// lacks its ticket. Current GameData: CafeteriaDefaultTable rewards RandomBox +// 1400001, whose dropType1 RewardGroup holds that ticket (3007) and LobbyDeco 26. +func TestCafeteriaIntroductionDeliversTheDatingTicketOnce(t *testing.T) { + g := newMissionGameplay(t) + ticket := g.owner.assembly.design.contentOpeningDesign.Dating.TicketID + if ticket == 0 { + t.Fatal("GameData dating opening rule has no ticket") + } + if got := g.itemCount(19, ticket); got != 0 { + t.Fatalf("dating ticket owned before the introduction: %d", got) + } + g.call("/CafeteriaIntroductionStoryReward", nil) + if got := g.itemCount(19, ticket); got != 1 { + t.Fatalf("introduction delivered dating ticket count %d, want 1", got) + } + if got := g.itemCount(25, 26); got != 1 { + t.Fatalf("introduction delivered lobby decoration count %d, want 1", got) + } + g.call("/CafeteriaIntroductionStoryReward", nil) + if got, deco := g.itemCount(19, ticket), g.itemCount(25, 26); got != 1 || deco != 1 { + t.Fatalf("repeated introduction claim changed rewards: ticket %d decoration %d", got, deco) + } +} + +// Accounts whose introduction was recorded without the ticket regain it at +// login exactly once; the introduction box is not granted a second time. +func TestCafeteriaLoginRestoresAMissingDatingTicketOnce(t *testing.T) { + g := newMissionGameplay(t) + ticket := g.owner.assembly.design.contentOpeningDesign.Dating.TicketID + g.call("/CafeteriaInfo", nil) + s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account} + s.run(t, true, func(ctx command.Context, p *playerAssembly) { + raw, err := p.gameplayStore.Load(ctx.State, "cafeteria") + if err != nil || raw == nil { + t.Fatalf("cafeteria state missing: %v", err) + } + var state map[string]json.RawMessage + if err := json.Unmarshal(raw, &state); err != nil { + t.Fatal(err) + } + state["Introduction"] = json.RawMessage("true") + if raw, err = json.Marshal(state); err != nil { + t.Fatal(err) + } + if err := p.gameplayStore.Save(ctx.State, "cafeteria", raw); err != nil { + t.Fatal(err) + } + }) + g.reopen() + if got := g.itemCount(19, ticket); got != 0 { + t.Fatalf("ticket restored before login: %d", got) + } + g.call("/LoginUser", nil) + if got := g.itemCount(19, ticket); got != 1 { + t.Fatalf("login restored dating ticket count %d, want 1", got) + } + if got := g.itemCount(25, 26); got != 0 { + t.Fatalf("login restoration regranted the introduction box: decoration %d", got) + } + // Spend the restored ticket: the restoration identity must not grant again. + s = &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account} + s.run(t, true, func(ctx command.Context, p *playerAssembly) { + items, err := p.ownedItems.SelectMutable(ctx, 19, ticket, 1) + if err != nil { + t.Fatal(err) + } + if err := p.ownedItems.Consume(ctx, items); err != nil { + t.Fatal(err) + } + }) + g.reopen() + g.call("/LoginUser", nil) + g.call("/CafeteriaIntroductionStoryReward", nil) + if got, deco := g.itemCount(19, ticket), g.itemCount(25, 26); got != 0 || deco != 0 { + t.Fatalf("restoration repeated or regranted the box: ticket %d decoration %d", got, deco) + } +} + +// MissionTable 301/3012 is guide STEP McPackQuestIdClear for pack1 quest3 +// (subType=pack, params=quest). A quest cleared without any live event, as +// before this task existed, must still let the step be claimed. +func TestStepQuestClearMissionCountsAlreadyClearedQuests(t *testing.T) { + g := newMissionGameplay(t) + claim := append(appScalar(3, 2), appScalar(4, 301)...) + claim = append(claim, appScalar(5, 3012)...) + claim = append(claim, appScalar(6, 7001)...) // guide schedule, as in guide_pass_integration_test.go + if _, err := g.execute("/MissionClear", claim); err == nil { + t.Fatal("step claimed before pack1 quest3 was cleared") + } + s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account} + // The same quest number in another pack, and another pack1 quest, are not it. + s.run(t, true, func(ctx command.Context, p *playerAssembly) { + if err := p.progressState.ClearQuest(ctx, 3, 2, 0); err != nil { + t.Fatal(err) + } + if err := p.progressState.ClearQuest(ctx, 4, 1, 0); err != nil { + t.Fatal(err) + } + }) + if _, err := g.execute("/MissionClear", claim); err == nil { + t.Fatal("step claimed from a quest other than pack1 quest3") + } + s.run(t, true, func(ctx command.Context, p *playerAssembly) { + if err := p.progressState.ClearQuest(ctx, 3, 1, 0); err != nil { + t.Fatal(err) + } + }) + if _, err := g.execute("/MissionClear", claim); err != nil { + t.Fatalf("step not claimable after pack1 quest3 was cleared: %v", err) + } + if _, err := g.execute("/MissionClear", claim); err == nil { + t.Fatal("step claimed twice") + } +} diff --git a/go/internal/server/app/cash_package_layout_integration_test.go b/go/internal/server/app/cash_package_layout_integration_test.go new file mode 100644 index 0000000..b9f5eed --- /dev/null +++ b/go/internal/server/app/cash_package_layout_integration_test.go @@ -0,0 +1,74 @@ +//go:build integration + +package app + +import ( + "fmt" + "strings" + "testing" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/protocol/wire" +) + +// Current official PackageUI148.prefab uses BundleGroupPackageUI, whose +// per-product buttons only check availability and that product's own limit. +// Its contentsGroup91 sort3 product236 can be bought before sort2 product235. +// PackageUI132 uses BundleGroupRelayPackageUI and does enforce stage order. +func TestIndependentCashPackageCanBeBoughtBeforeEarlierDisplayItems(t *testing.T) { + g := profileGameplay(t) + profileGrant(g, gamedata.Reward{Type: 2, Count: 1000000}) + before := g.owner.assembly.wallet.Snapshot(command.Context{}).Jewelry + key := gamedata.CashProductKey{GroupID: 310001, ProductID: 236} + quote, err := g.owner.assembly.cashCatalog.Quote(key, 1) + if err != nil { + t.Fatal(err) + } + line := wire.AppendVarint(wire.AppendVarint(nil, 1, key.ProductID), 3, 1) + pay := "98236" + billing := wire.AppendString(wire.AppendString(nil, 1, pay), 2, fmt.Sprintf("bd2-local-commerce-v1:%s:%d:%d", pay, quote.ItemType, quote.Cost)) + request := wire.AppendBytes(wire.AppendBytes(wire.AppendVarint(nil, 3, key.GroupID), 4, line), 7, billing) + g.call("/CashShopBuy", request) + assertPurchase := func() { + t.Helper() + if got := g.owner.assembly.wallet.Snapshot(command.Context{}).Jewelry; got != before-quote.Cost { + t.Fatalf("independent package did not debit its accepted quote once: got %d", got) + } + var bought, prior uint64 + for _, row := range appRows(g.call("/CashShopPurchaseCountInfo", nil), 1) { + if appValue(row, 1) == 310001 && appValue(row, 3) == 0 { + switch appValue(row, 2) { + case 236: + bought = appValue(row, 4) + case 235: + prior = appValue(row, 4) + } + } + } + if bought != 1 || prior != 0 { + t.Fatalf("purchase counts changed another display tier: bought=%d prior=%d", bought, prior) + } + } + assertPurchase() + g.reopen() + assertPurchase() + // A real relay's later stage remains unavailable; no quote or debit is + // attempted until its predecessor is owned. + var relay gamedata.CashPackageDesign + for _, pack := range g.factory.design.cashDesign.Packages { + if pack.ResourceName == "PackageUI132" && pack.ContentsSortID == 2 { + relay = pack + break + } + } + if relay.ID == 0 { + t.Fatal("official relay fixture absent") + } + relayLine := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, relay.ID), 2, relay.SaleGroup), 3, 1) + failure := g.execute(g.request("/CashShopBuy", wire.AppendBytes(wire.AppendVarint(nil, 3, relay.GroupID), 4, relayLine)), true) + if !strings.Contains(string(failure), "preceding package purchase required") { + t.Fatalf("real relay order was not enforced: %s", failure) + } + assertPurchase() +} diff --git a/go/internal/server/app/castle_battle_integration_test.go b/go/internal/server/app/castle_battle_integration_test.go index 5ff96f4..888705c 100644 --- a/go/internal/server/app/castle_battle_integration_test.go +++ b/go/internal/server/app/castle_battle_integration_test.go @@ -15,7 +15,7 @@ import ( "bd2server/internal/server/protocol/wire" ) -// Current 20261012190548 GameData binds Greed floor 1 to pack3003 deck10001. +// GameData 20261021182514 binds Greed floor 1 to pack3003 deck10001. // Its win/no-death/8-turn challenges award material1000 x1, gold30000 and // bonus hunting AP5. These expectations come from the read-only GameData query, // independently of the castle loader and the runtime reward response. diff --git a/go/internal/server/app/chat_http_integration_test.go b/go/internal/server/app/chat_http_integration_test.go index 8cf7d4c..b150c32 100644 --- a/go/internal/server/app/chat_http_integration_test.go +++ b/go/internal/server/app/chat_http_integration_test.go @@ -184,7 +184,7 @@ func TestChatReportQuotaResetsAtNextServerDay(t *testing.T) { if err != nil { t.Fatal(err) } - ctx := command.Context{State: tx, Identity: command.Identity{AccountID: accounts[0]}, Emit: func(command.Event) error { return nil }} + ctx := command.Context{State: tx, Identity: command.Identity{AccountID: accounts[0]}, Emit: func(command.Event) error { return nil }, InstanceIDs: factory.instanceIDs()} _, body, handled, err := owner.assembly.chatService.Handle(ctx, path, append(appScalar(1, 1), fields...)) if err != nil || !handled { _ = tx.Rollback() diff --git a/go/internal/server/app/clear_package_integration_test.go b/go/internal/server/app/clear_package_integration_test.go index 4ab2ed1..52d2ca2 100644 --- a/go/internal/server/app/clear_package_integration_test.go +++ b/go/internal/server/app/clear_package_integration_test.go @@ -117,7 +117,7 @@ func TestClearPackageClaimsSurviveSessionAndDayChanges(t *testing.T) { t.Fatal(err) } defer func() { _ = tx.Rollback() }() - ctx := command.Context{Identity: command.Identity{AccountID: account}, State: tx} + ctx := command.Context{Identity: command.Identity{AccountID: account}, State: tx, InstanceIDs: factory.instanceIDs()} for _, quest := range factory.design.world.Story.Packs[1].MainQuestIDs { if err := owner.assembly.progressState.ClearQuest(ctx, quest, 1, 0); err != nil { t.Fatal(err) diff --git a/go/internal/server/app/design.go b/go/internal/server/app/design.go index bee4ff2..7ce7bbf 100644 --- a/go/internal/server/app/design.go +++ b/go/internal/server/app/design.go @@ -347,6 +347,17 @@ func loadDesign(c *configuration, seeds *seedCatalog) (*designCatalog, error) { if err != nil { return nil, fmt.Errorf("load cash products: %w", err) } + for i := range d.cashDesign.Packages { + pack := &d.cashDesign.Packages[i] + if pack.ResourceName == "" || pack.ContentsGroupID == 0 || pack.PackageType != 2 && pack.PackageType != 8 { + continue + } + layout, found := seeds.packageLayouts.Layouts[pack.ResourceName] + if !found { + return nil, fmt.Errorf("missing cash package layout %q", pack.ResourceName) + } + pack.Sequential = layout == "relay" + } d.cashEntitlementDesign, err = gamedata.LoadCashEntitlementDesign(gameData, gameDataVersion) if err != nil { return nil, fmt.Errorf("load cash entitlement design: %w", err) diff --git a/go/internal/server/app/field_pack_types_integration_test.go b/go/internal/server/app/field_pack_types_integration_test.go new file mode 100644 index 0000000..2689ee6 --- /dev/null +++ b/go/internal/server/app/field_pack_types_integration_test.go @@ -0,0 +1,22 @@ +//go:build integration + +package app + +import "testing" + +// PackTable in GameData 20261021182514 (tools/python/gamedata_db.py): 1001 is +// Define_PackType 1 (Char), 2001 is 6 (Event), 3009 is 11 (Square), 3012 is +// 14 (Life). All four open with the Edge of Dimensions ticket. +func TestFieldPacksIncludeTicketGatedContentCards(t *testing.T) { + g := newMissionGameplay(t) + packs := g.owner.assembly.design.world.FieldPacks + for id, want := range map[int]uint64{1001: 1, 2001: 6, 3009: 11, 3012: 14} { + pack, found := packs[id] + if !found || pack.Type != want { + t.Fatalf("pack %d = %+v (found %v), want type %d", id, pack, found, want) + } + if !pack.HasOpenRule || pack.TicketID != 11 { + t.Fatalf("pack %d open rule = %+v, want ticket 11", id, pack) + } + } +} diff --git a/go/internal/server/app/field_traps_integration_test.go b/go/internal/server/app/field_traps_integration_test.go index 5dbfd0e..8c59265 100644 --- a/go/internal/server/app/field_traps_integration_test.go +++ b/go/internal/server/app/field_traps_integration_test.go @@ -123,7 +123,7 @@ func (s *trapPlayerScenario) run(t *testing.T, commit bool, action func(command. t.Fatal(err) } defer func() { _ = tx.Rollback() }() - ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "trap-client"}, State: tx} + ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "trap-client"}, State: tx, InstanceIDs: s.factory.instanceIDs()} action(ctx, s.owner.assembly) problems, err := tx.Validate() if err != nil || len(problems) != 0 { diff --git a/go/internal/server/app/friend_presence_integration_test.go b/go/internal/server/app/friend_presence_integration_test.go new file mode 100644 index 0000000..ed36aa2 --- /dev/null +++ b/go/internal/server/app/friend_presence_integration_test.go @@ -0,0 +1,57 @@ +//go:build integration + +package app + +import ( + "context" + "testing" + "time" +) + +// FriendDBInfo field8 and GuildMemberDBInfo field10 use the same last-login +// time. Presence is a response projection; publishing a future display time +// must never overwrite the actual persisted login time. +func TestFriendPresenceChangesWithoutChangingStoredLoginTime(t *testing.T) { + factory, accounts := newIntegrationFactory(t) + shared, err := openSharedRuntime(context.Background(), factory.options, factory.design) + if err != nil { + t.Fatal(err) + } + factory.shared, factory.pvpSource = shared, shared.pvp + registry := newPlayerRegistry(factory, time.Minute) + t.Cleanup(func() { + if err := registry.Close(context.Background()); err != nil { + t.Error(err) + } + if err := shared.store.Close(); err != nil { + t.Error(err) + } + }) + a, b := friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1]) + drainFriendPublications(t, registry, shared, accounts[0]) + drainFriendPublications(t, registry, shared, accounts[1]) + a.send("/FriendSend", appScalar(2, b.owner), 205, 0) + b.send("/FriendAccept", appScalar(2, a.owner), 206, 0) + stored, err := shared.friends.Profile(context.Background(), b.owner) + if err != nil { + t.Fatal(err) + } + online := true + shared.friends.AttachPresence(func(account string) bool { return online && account == accounts[1] }) + rows := appRows(a.send("/FriendInfoList", nil, 204, 0), 1) + if len(rows) != 1 || appValue(rows[0], 1) != b.owner || int64(appValue(rows[0], 8)) <= time.Now().UnixMilli() { + t.Fatal("online friend did not receive native online display marker") + } + persisted, err := shared.friends.Profile(context.Background(), b.owner) + if err != nil { + t.Fatal(err) + } + if persisted.LastLoginMS != stored.LastLoginMS { + t.Fatal("online projection overwrote actual last-login time") + } + online = false + rows = appRows(a.send("/FriendInfoList", nil, 204, 0), 1) + if len(rows) != 1 || int64(appValue(rows[0], 8)) != stored.LastLoginMS { + t.Fatal("offline friend retained online marker or lost last-login time") + } +} diff --git a/go/internal/server/app/friends_integration_test.go b/go/internal/server/app/friends_integration_test.go index d882e2f..20713ee 100644 --- a/go/internal/server/app/friends_integration_test.go +++ b/go/internal/server/app/friends_integration_test.go @@ -114,7 +114,7 @@ func TestNativeFriendRequestsAreBilateralDurableAndRetrySafe(t *testing.T) { t.Fatal(err) } costumeID := []uint64{101, 201}[i] - if _, err := owner.assembly.collection.GrantCostumes(command.Context{State: tx}, "friend-supporter-fixture", []uint64{costumeID}, factory.design.rewardCostumes); err != nil { + if _, err := owner.assembly.collection.GrantCostumes(command.Context{State: tx, InstanceIDs: factory.instanceIDs()}, "friend-supporter-fixture", []uint64{costumeID}, factory.design.rewardCostumes); err != nil { _ = tx.Rollback() t.Fatal(err) } @@ -380,7 +380,7 @@ func TestNativeFriendRequestsAreBilateralDurableAndRetrySafe(t *testing.T) { for range 2 { a.send("/SupporterBorrow", append(appScalar(2, b.owner), appScalar(3, 1)...), 437, 0) } - a.send("/SupporterBorrow", append(appScalar(2, b.owner), appScalar(3, 1)...), 437, 9003) + a.send("/SupporterBorrow", append(appScalar(2, b.owner), appScalar(3, 1)...), 437, 3) status = b.send("/SupporterStatus", appScalar(2, 50), 438, 0) history = appRows(status, 1) if len(history) != 3 { diff --git a/go/internal/server/app/guide_pass_integration_test.go b/go/internal/server/app/guide_pass_integration_test.go index 6156e00..a4c2185 100644 --- a/go/internal/server/app/guide_pass_integration_test.go +++ b/go/internal/server/app/guide_pass_integration_test.go @@ -51,7 +51,7 @@ func TestGuidePassClaimsAndExperienceSurviveWithoutEventCalendarEntry(t *testing assertExperience(10) // Reproduce the previous server's missing derived pass ledger while retaining // the mission reward receipt that independently proves the earned EXP. - s := &trapPlayerScenario{owner: g.owner, account: g.account} + s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account} s.run(t, true, func(ctx command.Context, p *playerAssembly) { raw, err := p.gameplayStore.Load(ctx.State, "eventtasks") if err != nil { diff --git a/go/internal/server/app/guild_intro_checkpoint_integration_test.go b/go/internal/server/app/guild_intro_checkpoint_integration_test.go new file mode 100644 index 0000000..2277e1c --- /dev/null +++ b/go/internal/server/app/guild_intro_checkpoint_integration_test.go @@ -0,0 +1,92 @@ +//go:build integration + +package app + +import ( + "errors" + "testing" + + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/world" +) + +// Current QuestTable3006 has one introduction: quest1 / Quest_Main_00. +// GameFieldManager.CoCheckGuildRaidIntroTimelineAndOpenUI completes this +// presentation with a local watched flag, without QuestAccept or QuestClear. +func TestGuildRaidIntroCheckpointRestartsAndCompletesWithoutQuestProgress(t *testing.T) { + factory, accounts := newIntegrationFactory(t) + s := &trapPlayerScenario{factory: factory, account: accounts[0]} + s.owner = openNicknamePlayer(t, factory, s.account) + t.Cleanup(func() { closeNicknamePlayer(t, s.owner) }) + checkpoint := world.StoryCheckpoint{ID: "guild-intro-first", PackID: 3006, QuestID: 1, Phase: "accept", Timeline: "Quest_Main_00", MapID: 300603} + if intro := factory.design.world.FieldPacks[3006].IntroQuest; intro == nil || intro.ID != 1 || intro.AcceptCinemaName != "Quest_Main_00" { + t.Fatalf("current GameData field introduction is missing: %+v", intro) + } + for _, id := range []int{1001, 2001, 3001, 3003, 3004, 3005} { + if intro := factory.design.world.FieldPacks[id].IntroQuest; intro != nil { + t.Fatalf("ordinary field quest chain %d was misclassified as a standalone introduction: %+v", id, intro) + } + } + s.run(t, false, func(ctx command.Context, p *playerAssembly) { + if _, err := p.worldService.StoryCheckpoint(ctx, world.StoryCheckpointRequest{StoryCheckpoint: checkpoint, Operation: "begin"}); !errors.Is(err, world.ErrInvalidRequest) { + t.Fatalf("guild introduction allowed before entering its pack: %v", err) + } + }) + s.protocol(t, "/PackInGameInfo", trapRequest(100, 3006)) + s.position(t, 3006, 300603) + beforeGold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold + for name, mutate := range map[string]func(*world.StoryCheckpoint){ + "quest": func(c *world.StoryCheckpoint) { c.QuestID = 2 }, + "difficulty": func(c *world.StoryCheckpoint) { c.Difficulty = 1 }, + "map": func(c *world.StoryCheckpoint) { c.MapID = 51 }, + "timeline": func(c *world.StoryCheckpoint) { c.Timeline = "Quest_Main_01" }, + "completion-phase": func(c *world.StoryCheckpoint) { c.Phase = "complete" }, + "object": func(c *world.StoryCheckpoint) { c.ObjectID = 1 }, + "talk": func(c *world.StoryCheckpoint) { c.SimpleTalkGroupID = 1 }, + "unknown-pack": func(c *world.StoryCheckpoint) { c.PackID = 999999 }, + } { + t.Run(name, func(t *testing.T) { + candidate := checkpoint + mutate(&candidate) + s.run(t, false, func(ctx command.Context, p *playerAssembly) { + _, err := p.worldService.StoryCheckpoint(ctx, world.StoryCheckpointRequest{StoryCheckpoint: candidate, Operation: "begin"}) + if !errors.Is(err, world.ErrInvalidRequest) { + t.Fatalf("invalid guild introduction accepted: %v", err) + } + }) + }) + } + if pending := storyCheckpointCall(t, s.owner, "begin", checkpoint).Checkpoint; pending == nil || *pending != checkpoint { + t.Fatalf("authored guild introduction failed to begin: %+v", pending) + } + closeNicknamePlayer(t, s.owner) + s.owner = openNicknamePlayer(t, factory, s.account) + if pending := storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint; pending == nil || *pending != checkpoint { + t.Fatalf("unfinished guild introduction did not survive reconnect: %+v", pending) + } + // Native entry restarts the cinema with a fresh request identity. It must + // reuse the existing checkpoint rather than conflict or skip playback. + restarted := checkpoint + restarted.ID = "guild-intro-reconnected" + if pending := storyCheckpointCall(t, s.owner, "begin", restarted).Checkpoint; pending == nil || *pending != checkpoint { + t.Fatalf("restarted introduction did not reuse its pending checkpoint: %+v", pending) + } + if pending := storyCheckpointCall(t, s.owner, "complete", world.StoryCheckpoint{ID: checkpoint.ID}).Checkpoint; pending != nil { + t.Fatalf("cinema completion left the guild introduction pending: %+v", pending) + } + storyCheckpointCall(t, s.owner, "complete", world.StoryCheckpoint{ID: checkpoint.ID}) + closeNicknamePlayer(t, s.owner) + s.owner = openNicknamePlayer(t, factory, s.account) + if pending := storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint; pending != nil { + t.Fatalf("completed guild introduction returned after reconnect: %+v", pending) + } + if s.owner.assembly.progressState.QuestCleared(1, 3006, 0) || s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold { + t.Fatal("introduction completion advanced a quest or granted rewards") + } + s.run(t, false, func(ctx command.Context, p *playerAssembly) { + request := append(trapRequest(101, 1), appScalar(3, 3006)...) + if _, _, _, err := p.worldService.Handle(ctx, "/QuestClear", request); !errors.Is(err, world.ErrInvalidRequest) { + t.Fatalf("field introduction became a claimable story quest: %v", err) + } + }) +} diff --git a/go/internal/server/app/ib_lifecycle_integration_test.go b/go/internal/server/app/ib_lifecycle_integration_test.go index b43331d..adc9041 100644 --- a/go/internal/server/app/ib_lifecycle_integration_test.go +++ b/go/internal/server/app/ib_lifecycle_integration_test.go @@ -15,7 +15,7 @@ import ( "bd2server/internal/server/runtime/player" ) -// GameData 20261012190548 LocalText 7900026 promises a single reward per +// GameData 20261021182514 LocalText 7900026 promises a single reward per // board first clear; 7900084 requires every stage win; 7900122 resets run items. // IbStageEndResponse and RewardDBInfoBundle field numbers are from the current // extracted Proto.Net classes. This exercises the actual account transaction, diff --git a/go/internal/server/app/instance_identity_integration_test.go b/go/internal/server/app/instance_identity_integration_test.go new file mode 100644 index 0000000..603d3ce --- /dev/null +++ b/go/internal/server/app/instance_identity_integration_test.go @@ -0,0 +1,207 @@ +//go:build integration + +package app + +import ( + "context" + "fmt" + "maps" + "slices" + "testing" + "time" + + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/roster" +) + +// CommonPacket.GetCharInfo(long) consults supporter caches before owned characters. +// CharDBInfo/CostumeDBInfo/EquipDBInfo link by instance index, not design ID. +func TestTwoAccountsKeepDistinctOwnedIdentitiesWhenBorrowingSameCharacter(t *testing.T) { + factory, accounts := newIntegrationFactory(t) + type supporter struct{ character, costume, equipment uint64 } + var supporters [2]supporter + var snapshots [2]map[uint64]string + owners := map[string]*playerInstance{} + t.Cleanup(func() { + for _, owner := range owners { + closeNicknamePlayer(t, owner) + } + }) + closeOwner := func(account string) { + closeNicknamePlayer(t, owners[account]) + delete(owners, account) + } + weaponIDs := make([]uint64, 0) + for id, slot := range factory.design.equipmentSlots { + if slot == 1 { + weaponIDs = append(weaponIDs, id) + } + } + slices.Sort(weaponIDs) + if len(weaponIDs) == 0 { + t.Fatal("selected GameData has no weapon") + } + // Current GameData CostumeTable 101 belongs to UniqueCharId 1; the selected + // starter seed owns neither this costume nor its permanent character. + const costumeID = 101 + design, found := factory.design.rewardCostumes.Character(costumeID) + if !found { + t.Fatal("selected GameData has no grantable costume", costumeID) + } + for i, account := range accounts { + owner := openNicknamePlayer(t, factory, account) + owners[account] = owner + initial := inventoryIdentitySnapshot(t, owner) + if i > 0 { + assertInventoryIdentityDisjoint(t, snapshots[0], initial) + } + tx, err := owner.repository.BeginCommand(context.Background()) + if err != nil { + t.Fatal(err) + } + ctx := command.Context{State: tx, InstanceIDs: factory.instanceIDs()} + grant, err := owner.assembly.collection.GrantCostumes(ctx, "same-character-award", []uint64{costumeID}, factory.design.rewardCostumes) + if err != nil { + _ = tx.Rollback() + t.Fatal(err) + } + if len(grant.CharacterIndices) != 1 || len(grant.CostumeIndices) != 1 { + _ = tx.Rollback() + t.Fatal("first costume acquisition did not create its character and costume") + } + character, found := owner.assembly.collection.FindCharacter(grant.CharacterIndices[0]) + if !found || character.ID != design.ID || character.CostumeID != costumeID || character.UseCostume != grant.CostumeIndices[0] { + _ = tx.Rollback() + t.Fatal("acquired character does not reference its actual owned costume") + } + equipment, err := owner.assembly.ownedEquipment.GrantOnce(ctx, "same-weapon-award", weaponIDs[0]) + if err != nil { + _ = tx.Rollback() + t.Fatal(err) + } + request := append(append(appScalar(1, 1), appScalar(2, equipment.InvenIndex)...), appScalar(3, character.InvenIndex)...) + if _, _, handled, err := owner.assembly.ownedEquipment.Handle(ctx, "/EquipUse", request); err != nil || !handled { + _ = tx.Rollback() + t.Fatalf("equip actual owned weapon: handled=%t error=%v", handled, err) + } + if err := tx.Commit(); err != nil { + t.Fatal(err) + } + supporters[i] = supporter{character.InvenIndex, character.UseCostume, equipment.InvenIndex} + snapshots[i] = inventoryIdentitySnapshot(t, owner) + for index, identity := range initial { + if snapshots[i][index] != identity { + t.Fatalf("grant changed an existing starter identity: %d", index) + } + } + closeOwner(account) + } + assertInventoryIdentityDisjoint(t, snapshots[0], snapshots[1]) + + // Recreate the allocator and application against the same SQLite account files. + factory = &PlayerFactory{options: factory.options, seeds: factory.seeds, design: factory.design, profiles: factory.profiles} + for i, account := range accounts { + owner := openNicknamePlayer(t, factory, account) + owners[account] = owner + if !maps.Equal(snapshots[i], inventoryIdentitySnapshot(t, owner)) { + t.Fatal("account reopen changed inventory identities or ownership links") + } + closeOwner(account) + } + shared, err := openSharedRuntime(context.Background(), factory.options, factory.design) + if err != nil { + t.Fatal(err) + } + factory.shared, factory.pvpSource = shared, shared.pvp + registry := newPlayerRegistry(factory, time.Minute) + t.Cleanup(func() { + if err := registry.Close(context.Background()); err != nil { + t.Error(err) + } + if err := shared.store.Close(); err != nil { + t.Error(err) + } + }) + clients := []*friendHTTPClient{friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])} + for i, client := range clients { + fields := append(append(appScalar(2, 1), appScalar(3, supporters[i].character)...), appScalar(4, supporters[i].costume)...) + client.send("/SupporterRegister", fields, 435, 0) + drainFriendPublications(t, registry, shared, accounts[i]) + } + borrower, lender := clients[0], clients[1] + borrower.send("/FriendSend", appScalar(2, lender.owner), 205, 0) + lender.send("/FriendAccept", appScalar(2, borrower.owner), 206, 0) + borrower.send("/SupporterBattleInfo", appScalar(2, 1), 439, 0) + borrowed := borrower.send("/SupporterBorrow", append(appScalar(2, lender.owner), appScalar(3, 1)...), 437, 0) + bundles := appRows(borrowed, 3) + if len(bundles) != 1 { + t.Fatal("borrow omitted the native supporter bundle") + } + characters, costumes, equipment := appRows(bundles[0], 1), appRows(bundles[0], 2), appRows(bundles[0], 3) + if len(characters) != 1 || appValue(characters[0], 1) != supporters[1].character || appValue(characters[0], 2) != design.ID || appValue(characters[0], 7) != supporters[1].costume { + t.Fatal("borrowed character does not preserve lender ownership and costume references") + } + if len(costumes) != 1 || appValue(costumes[0], 1) != supporters[1].costume || appValue(costumes[0], 2) != costumeID || appValue(costumes[0], 4) != supporters[1].character { + t.Fatal("borrowed costume does not point to lender's actual character") + } + if len(equipment) != 1 || appValue(equipment[0], 1) != supporters[1].equipment || appValue(equipment[0], 2) != supporters[1].character { + t.Fatal("borrowed equipment does not point to lender's actual character") + } + for _, rows := range [][][]byte{characters, costumes, equipment} { + for _, row := range rows { + if _, own := snapshots[0][appValue(row, 1)]; own { + t.Fatal("supporter cache would shadow borrower's owned inventory") + } + } + } +} + +func inventoryIdentitySnapshot(t *testing.T, owner *playerInstance) map[uint64]string { + t.Helper() + tx, err := owner.repository.BeginCommand(context.Background()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback() }() + ctx := command.Context{State: tx} + identities := map[uint64]string{} + add := func(index uint64, identity string) { + t.Helper() + if index == 0 { + t.Fatal("owned instance has no identity", identity) + } + if previous, exists := identities[index]; exists { + t.Fatalf("instance %d resolves to both %s and %s", index, previous, identity) + } + identities[index] = identity + } + for _, character := range owner.assembly.worldService.CharacterService().RawAll() { + if !roster.IsStoryCharacter(character) && !roster.IsCharmCharacter(character) { + add(character.InvenIndex, fmt.Sprintf("character:%d:costume:%d", character.ID, character.UseCostume)) + } + } + for _, costume := range owner.assembly.collection.Costumes() { + add(costume.InvenIndex, fmt.Sprintf("costume:%d:character:%d", costume.ID, costume.UseChar)) + } + for _, item := range owner.assembly.ownedItems.All(ctx) { + if item.InvenIndex != 0 { + add(item.InvenIndex, fmt.Sprintf("item:%d:%d", item.Type, item.ID)) + } + } + for _, equipment := range owner.assembly.ownedEquipment.All(ctx) { + add(equipment.InvenIndex, fmt.Sprintf("equipment:%d:character:%d", equipment.ID, equipment.UseChar)) + } + if len(identities) == 0 { + t.Fatal("new account has no inventory") + } + return identities +} + +func assertInventoryIdentityDisjoint(t *testing.T, left, right map[uint64]string) { + t.Helper() + for id, leftIdentity := range left { + if rightIdentity, exists := right[id]; exists { + t.Fatalf("accounts share instance %d: %s and %s", id, leftIdentity, rightIdentity) + } + } +} diff --git a/go/internal/server/app/inventory_operations_integration_test.go b/go/internal/server/app/inventory_operations_integration_test.go index 5f9f240..fd5ab30 100644 --- a/go/internal/server/app/inventory_operations_integration_test.go +++ b/go/internal/server/app/inventory_operations_integration_test.go @@ -39,7 +39,7 @@ func inventorySetup(t *testing.T, g *puzzleGameplay, fn func(command.Context, *p t.Fatal(err) } defer func() { _ = tx.Rollback() }() - fn(command.Context{Identity: command.Identity{AccountID: g.account, SessionID: "setup"}, State: tx}, g.owner.assembly) + fn(command.Context{Identity: command.Identity{AccountID: g.account, SessionID: "setup"}, State: tx, InstanceIDs: g.factory.instanceIDs()}, g.owner.assembly) if err := tx.Commit(); err != nil { t.Fatal(err) } diff --git a/go/internal/server/app/mission_condition_integration_test.go b/go/internal/server/app/mission_condition_integration_test.go new file mode 100644 index 0000000..155c084 --- /dev/null +++ b/go/internal/server/app/mission_condition_integration_test.go @@ -0,0 +1,339 @@ +//go:build integration + +package app + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "strings" + "testing" + "time" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + assets "bd2server/internal/server/domain/inventory" + "bd2server/internal/server/domain/progression/conditions" + "bd2server/internal/server/domain/roster" +) + +func missionGrant(t *testing.T, g *missionGameplay, rewards ...gamedata.Reward) { + t.Helper() + tx, err := g.owner.repository.BeginCommand(context.Background()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback() }() + ctx := command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()} + if _, err := g.owner.assembly.eventEconomy.Apply(ctx, "mission-condition:"+t.Name(), nil, rewards); err != nil { + t.Fatal(err) + } + if err := tx.Commit(); err != nil { + t.Fatal(err) + } +} + +// persistedEventMissionValue reads the saved event mission without asking the +// service, whose own reconciliation would hide whether login did the work. +func persistedEventMissionValue(t *testing.T, g *missionGameplay, taskID uint64) uint64 { + t.Helper() + tx, err := g.owner.repository.BeginCommand(context.Background()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback() }() + raw, err := g.owner.assembly.gameplayStore.Load(tx, "eventtasks") + if err != nil { + t.Fatal(err) + } + if raw == nil { + return 0 + } + var state struct { + Missions map[string]struct{ Value uint64 } + } + if err := json.Unmarshal(raw, &state); err != nil { + t.Fatal(err) + } + suffix := "/" + strconv.FormatUint(taskID, 10) + var matches []uint64 + for key, mission := range state.Missions { + if strings.HasSuffix(key, suffix) { + matches = append(matches, mission.Value) + } + } + if len(matches) > 1 { + t.Fatalf("mission %d appears under %d schedules", taskID, len(matches)) + } + if len(matches) == 0 { + return 0 + } + return matches[0] +} + +// persistedRegularMissionValue reads a zero-valued regular mission, which +// MissionInfo omits until its progress is non-zero. +func persistedRegularMissionValue(t *testing.T, g *missionGameplay, groupType, group, id uint64) uint64 { + t.Helper() + tx, err := g.owner.repository.BeginCommand(context.Background()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback() }() + raw, err := g.owner.assembly.scope.Load(tx, "missions") + if err != nil { + t.Fatal(err) + } + if raw == nil { + return 0 + } + var state struct{ Progress map[string]uint64 } + if err := json.Unmarshal(raw, &state); err != nil { + t.Fatal(err) + } + return state.Progress[fmt.Sprintf("%d/%d/%d", groupType, group, id)] +} + +// guideTask finds a step-one guide mission without querying EventMissionInfo, +// which would reconcile the very progress under test. +func guideTask(t *testing.T, g *missionGameplay, groups map[uint64]bool, condition, subtype uint64) uint64 { + t.Helper() + for _, task := range g.factory.design.eventTasksDesign.Missions { + if groups[task.Group] && task.Type == condition && task.SubType == subtype { + return task.ID + } + } + t.Fatalf("no guide step mission with condition %d subtype %d", condition, subtype) + return 0 +} + +// setPermanentCharacterLevel rewrites one saved permanent character, emulating +// progress that predates the guide step. +func setPermanentCharacterLevel(t *testing.T, g *missionGameplay, level uint64) { + t.Helper() + s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account} + s.run(t, true, func(ctx command.Context, p *playerAssembly) { + var target roster.Character + for _, character := range p.worldService.CharacterService().RawAll() { + if !roster.IsStoryCharacter(character) && !roster.IsCharmCharacter(character) { + target = character + break + } + } + if target.InvenIndex == 0 { + t.Fatal("fixture has no permanent character") + } + key := strconv.FormatUint(target.InvenIndex, 10) + raw, found, err := p.scope.LoadEntry(ctx.State, "characters", "characters", key) + if err != nil || !found { + t.Fatalf("character entry %s: found=%v err=%v", key, found, err) + } + if err := json.Unmarshal(raw, &target); err != nil { + t.Fatal(err) + } + target.Level = level + payload, err := json.Marshal(target) + if err != nil { + t.Fatal(err) + } + if err := p.scope.PutEntry(ctx.State, "characters", "characters", key, payload); err != nil { + t.Fatal(err) + } + }) + g.reopen() +} + +// MissionTable 303/3035 is guide step McCharTargetLevelUp: "reach character +// level 20 or above". The level boundary must include 20, and the saved value +// stays zero until login reconciles it. +func TestGuidePassCharacterLevelMissionBackfillsAtLogin(t *testing.T) { + for _, test := range []struct{ level, complete uint64 }{{1, 0}, {19, 0}, {20, 1}, {21, 1}} { + t.Run(fmt.Sprintf("level%d", test.level), func(t *testing.T) { + g := newMissionGameplay(t) + groups, _ := guideStepOne(t, g) + id := guideTask(t, g, groups, 207, 20) + if test.level > 1 { + setPermanentCharacterLevel(t, g, test.level) + } + if got := persistedEventMissionValue(t, g, id); got != 0 { + t.Fatalf("mission advanced before login: %d", got) + } + g.call("/LoginUser", nil) + want := missionTarget(t, g, id) * test.complete + if got := persistedEventMissionValue(t, g, id); got != want { + t.Fatalf("character level mission value=%d, want %d", got, want) + } + }) + } +} + +// MissionTable 303/3039 is guide step McPlatformConnectOrLogin. Every session +// belongs to an authenticated account, so login completes it. +func TestGuidePassPlatformLoginMissionCompletesAtLogin(t *testing.T) { + g := newMissionGameplay(t) + groups, _ := guideStepOne(t, g) + id := guideTask(t, g, groups, 231, 0) + if got := persistedEventMissionValue(t, g, id); got != 0 { + t.Fatalf("platform login mission started at %d, want 0", got) + } + g.call("/LoginUser", nil) + if got, want := persistedEventMissionValue(t, g, id), missionTarget(t, g, id); got != want { + t.Fatalf("platform login mission value=%d, want %d", got, want) + } + row, _ := guideConditionMission(t, g, groups, 231, 0) + if got, want := appValue(row, 4), missionTarget(t, g, id); got != want { + t.Fatalf("platform login mission served value=%d, want %d", got, want) + } +} + +// A roguelike battle reports McPackBattle with the GameData roguelike pack and +// the ROGUE_LIKE battle mode, which completes the generic daily pack-battle +// mission. +func TestRogueLikeBattleReportsPackAndMode(t *testing.T) { + g := newMissionGameplay(t) + // GameData mission 1/112 is inside its 1999-01-01..2024-05-13 window. + g.now = time.Date(2024, time.May, 1, 12, 0, 0, 0, time.UTC) + event := g.owner.assembly.rogueLikeBattleEvent() + if event.Type != conditions.PackBattle || event.Sub != g.factory.design.roguelike.Pack || event.Param != battleModeRogueLike || event.Count != 1 { + t.Fatalf("roguelike battle event = %+v", event) + } + if battleModeRogueLike != 21 { + t.Fatalf("roguelike battle mode = %d, want ROGUE_LIKE 21", battleModeRogueLike) + } + g.call("/LoginUser", nil) + if got := persistedRegularMissionValue(t, g, 0, 1, 112); got != 0 { + t.Fatalf("pack battle mission started at %d, want 0", got) + } + s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account} + s.run(t, true, func(ctx command.Context, p *playerAssembly) { + if err := p.recordRogueLikeBattle(ctx); err != nil { + t.Fatal(err) + } + }) + g.reopen() + if got := persistedRegularMissionValue(t, g, 0, 1, 112); got != 1 { + t.Fatalf("pack battle mission value=%d, want 1", got) + } +} + +// MissionTable 2/208 is McTalentSkillUse with SubType 9 +// (Define_TalentSkillType TS_EQUIPMENT_MAKING): one successful equipment +// making request completes it. +func TestEquipmentMakingCompletesTalentSkillMission(t *testing.T) { + g := newMissionGameplay(t) + g.call("/LoginUser", nil) + var character uint64 + var materials []byte + s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account} + s.run(t, true, func(ctx command.Context, p *playerAssembly) { + if _, err := p.collection.GrantCostumes(ctx, "talent-skill-mission", []uint64{1401}, p.design.regularGacha); err != nil { + t.Fatal(err) + } + for _, c := range p.worldService.CharacterService().EquipmentCharacters() { + if _, ok := p.design.equipmentCraft.CharTalent[c.ID]; ok { + character = c.InvenIndex + break + } + } + if character == 0 { + t.Fatal("fixture needs a crafting character") + } + rewards := []gamedata.BattleReward{{Type: 8, ID: 204, Count: 50}, {Type: 8, ID: 201, Count: 50}} + if _, err := p.ownedItems.GrantOnce(ctx, "talent-skill-materials", rewards); err != nil { + t.Fatal(err) + } + if err := p.wallet.ExchangeOnce(ctx, "talent-skill-wallet", nil, []gamedata.Reward{{Type: 4, Count: 1000000}, {Type: 12, Count: 100}}); err != nil { + t.Fatal(err) + } + for _, id := range []uint64{204, 201} { + items, err := p.ownedItems.SelectMutable(ctx, 8, id, 3) + if err != nil { + t.Fatal(err) + } + for _, item := range items { + materials = append(materials, appMessage(4, assets.ItemWire(item))...) + } + } + }) + g.reopen() + if got := persistedRegularMissionValue(t, g, 1, 2, 208); got != 0 { + t.Fatalf("talent skill mission started at %d, want 0", got) + } + request := append(appScalar(2, character), appScalar(3, 1)...) + request = append(request, materials...) + request = append(request, appScalar(5, 0)...) + request = append(request, appScalar(7, 1)...) + request = append(request, appScalar(8, 3)...) + g.call("/EquipFromMakingToUpgrade", request) + if got := persistedRegularMissionValue(t, g, 1, 2, 208); got != 1 { + t.Fatalf("talent skill mission value=%d, want 1", got) + } +} + +// MissionTable 1/110 is McSamGroupIdMissionUpdateCompleteCount (SubType 0): +// completing any other daily mission in group 1 completes it, while a weekly +// completion must not count. +func TestSameGroupDailyMissionCountsCompletedDailyMissions(t *testing.T) { + g := newMissionGameplay(t) + g.call("/LoginUser", nil) + g.assertMission(0, 1, 101, 1, false) + g.assertMission(0, 1, 110, 1, false) + g.assertMission(1, 2, 210, 2, false) +} + +// MissionTable 1/111 and 302/3029 are McgachaBuy: one regular draw completes +// both the daily mission and the guide step, and further draws do not exceed +// their targets. +func TestGachaMissionsProgressFromOneDraw(t *testing.T) { + g := newMissionGameplay(t) + groups, _ := guideStepOne(t, g) + row, guideID := guideConditionMission(t, g, groups, 9, 0) + if row == nil { + t.Fatal("guide gacha mission missing from EventMissionInfo") + } + if got := appValue(row, 4); got != 0 { + t.Fatalf("guide gacha mission started at %d, want 0", got) + } + g.call("/LoginUser", nil) + if got := persistedRegularMissionValue(t, g, 0, 1, 111); got != 0 { + t.Fatalf("daily gacha mission started at %d, want 0", got) + } + // Pick a plain single draw paid with free jewelry, not a step-up, limited, + // selection or first-gacha group, so two identical draws stay valid. + catalog := g.factory.design.regularGacha + var groupID, gachaID, price uint64 + for _, group := range catalog.Groups() { + design, found := catalog.Gacha(group.OneTimeGachaID) + if !found || design.Count != 1 || design.PriceType != 3 || design.Price == 0 { + continue + } + if group.BuyLimitCount != 0 || group.SelectCount != 0 || group.GachaSubType != 0 { + continue + } + if _, stepUp := catalog.StepForGacha(group.OneTimeGachaID); stepUp { + continue + } + if g.factory.design.firstGacha != nil && g.factory.design.firstGacha.GachaID == group.OneTimeGachaID { + continue + } + groupID, gachaID, price = group.ID, group.OneTimeGachaID, design.Price + break + } + if groupID == 0 { + t.Fatal("GameData has no single-draw gacha paid with free jewelry") + } + missionGrant(t, g, gamedata.Reward{Type: 3, ID: 0, Count: price * 2}) + g.call("/GachaBuy", append(appScalar(2, gachaID), appScalar(3, 1)...)) + g.assertMission(0, 1, 111, 1, false) + row, _ = guideConditionMission(t, g, groups, 9, 0) + if got, want := appValue(row, 4), missionTarget(t, g, guideID); got != want { + t.Fatalf("guide gacha mission value=%d, want %d", got, want) + } + g.call("/GachaBuy", append(appScalar(2, gachaID), appScalar(3, 1)...)) + g.assertMission(0, 1, 111, 1, false) + row, _ = guideConditionMission(t, g, groups, 9, 0) + if got, want := appValue(row, 4), missionTarget(t, g, guideID); got != want { + t.Fatalf("second draw inflated guide gacha mission to %d, want %d", got, want) + } +} diff --git a/go/internal/server/app/mission_period_integration_test.go b/go/internal/server/app/mission_period_integration_test.go index 3616dbb..67a5d29 100644 --- a/go/internal/server/app/mission_period_integration_test.go +++ b/go/internal/server/app/mission_period_integration_test.go @@ -3,6 +3,7 @@ package app import ( + "bd2server/internal/server/domain/progression/conditions" "context" "fmt" "testing" @@ -111,11 +112,15 @@ func (g *missionGameplay) itemCount(typ, id uint64) uint64 { func (g *missionGameplay) assertMission(groupType, group, id, value uint64, claimed bool) { g.t.Helper() var row []byte + found := false for _, candidate := range appRows(g.call("/MissionInfo", nil), 1) { if appValue(candidate, 1) == group && appValue(candidate, 2) == id && appValue(candidate, 3) == groupType { - row = candidate + row, found = candidate, true } } + if !found { + g.t.Fatalf("mission %d/%d/%d missing from MissionInfo", groupType, group, id) + } if appValue(row, 4) != value || (appValue(row, 5) == 1) != claimed { g.t.Fatalf("mission %d/%d/%d: value=%d claimed=%v, want value=%d claimed=%v", groupType, group, id, appValue(row, 4), appValue(row, 5) == 1, value, claimed) } @@ -287,7 +292,7 @@ func TestMissionExpiredRowCannotReceiveCurrentGameplayEvents(t *testing.T) { } defer func() { _ = tx.Rollback() }() ctx := command.Context{State: tx} - if err := g.owner.assembly.missionService.RecordEvent(ctx, 3, 0, 1, g.owner.assembly.worldService.MissionsUnlocked); err != nil { + if err := g.owner.assembly.missionService.RecordEvent(ctx, conditions.Event{Type: 3, Count: 1}, g.owner.assembly.worldService.MissionsUnlocked); err != nil { t.Fatal(err) } if err := tx.Commit(); err != nil { diff --git a/go/internal/server/app/monster_hunt_integration_test.go b/go/internal/server/app/monster_hunt_integration_test.go index 6e3e02d..92a2f75 100644 --- a/go/internal/server/app/monster_hunt_integration_test.go +++ b/go/internal/server/app/monster_hunt_integration_test.go @@ -161,7 +161,7 @@ func (s *monsterHuntScenario) command(t *testing.T, action func(command.Context) t.Fatal(err) } defer func() { _ = tx.Rollback() }() - response, err := action(command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "hunt-client"}, State: tx}) + response, err := action(command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "hunt-client"}, State: tx, InstanceIDs: s.factory.instanceIDs()}) if err != nil { t.Fatal(err) } diff --git a/go/internal/server/app/nickname_integration_test.go b/go/internal/server/app/nickname_integration_test.go index f5b4296..453de87 100644 --- a/go/internal/server/app/nickname_integration_test.go +++ b/go/internal/server/app/nickname_integration_test.go @@ -294,7 +294,7 @@ func seedNicknameTickets(t *testing.T, owner *playerInstance, count uint64) { t.Fatal(err) } defer func() { _ = tx.Rollback() }() - ctx := command.Context{State: tx, Identity: command.Identity{AccountID: owner.accountID}} + ctx := command.Context{State: tx, InstanceIDs: owner.factory.instanceIDs(), Identity: command.Identity{AccountID: owner.accountID}} if _, err = owner.assembly.ownedItems.GrantOnce(ctx, "nickname-ticket-fixture", []gamedata.BattleReward{{Type: 14, ID: 1, Count: count}}); err != nil { t.Fatal(err) } diff --git a/go/internal/server/app/player_assets.go b/go/internal/server/app/player_assets.go index dccbf2e..535a768 100644 --- a/go/internal/server/app/player_assets.go +++ b/go/internal/server/app/player_assets.go @@ -18,6 +18,9 @@ func (p *playerAssembly) assets(ctx command.Context) error { if err != nil { return fmt.Errorf("server starting chapter policy: %w", err) } + if err := p.seedInstances(ctx); err != nil { + return fmt.Errorf("initialize account instance identities: %w", err) + } p.progressState, err = progress.OpenStore(ctx, p.scope) if err != nil { return err @@ -39,12 +42,14 @@ func (p *playerAssembly) assets(ctx command.Context) error { if err := p.ownedItems.AttachItemStacks(p.design.itemStacks); err != nil { return err } - p.ownedItems.AttachPrestigeIllustrations(p.design.prestigeCatalog.Illustrations) if p.initializeAccount { if err := p.ownedItems.InitializeItems(ctx, p.starter.OwnedItems); err != nil { return fmt.Errorf("initialize owned item seed: %w", err) } } + if err := p.ownedItems.AttachPrestigeIllustrations(ctx, p.design.prestigeCatalog.Illustrations); err != nil { + return fmt.Errorf("attach prestige illustration instances: %w", err) + } p.recipeService, err = assets.NewRecipeService(p.design.recipeDesign, p.starter.CookingRecipes, p.ownedItems) if err != nil { return fmt.Errorf("load learned recipes: %w", err) diff --git a/go/internal/server/app/player_avatar.go b/go/internal/server/app/player_avatar.go index a59178e..69ee2a5 100644 --- a/go/internal/server/app/player_avatar.go +++ b/go/internal/server/app/player_avatar.go @@ -5,6 +5,7 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/events" assets "bd2server/internal/server/domain/inventory" "bd2server/internal/server/domain/profile" ) @@ -21,6 +22,13 @@ func (p *playerAssembly) AvatarItems(ctx command.Context) []assets.Item { return func (p *playerAssembly) AvatarCurrency(ctx command.Context) assets.Currency { return p.wallet.Snapshot(ctx) } +func (p *playerAssembly) AvatarPriceBalance(ctx command.Context, price gamedata.Reward) (uint64, error) { + if field, found := events.AdditionalCurrencyFields[price.Type]; found && price.ID == 0 { + balances, err := p.eventEconomy.AdditionalCurrencies(ctx) + return balances[field], err + } + return 0, fmt.Errorf("avatar: unsupported initial selection currency %d/%d", price.Type, price.ID) +} func (p *playerAssembly) AvatarUnlocked(ctx command.Context, product gamedata.AvatarProduct) (bool, error) { if product.UnlockValue == 0 { return true, nil diff --git a/go/internal/server/app/player_battle_completion.go b/go/internal/server/app/player_battle_completion.go index 3cc6166..9536c3c 100644 --- a/go/internal/server/app/player_battle_completion.go +++ b/go/internal/server/app/player_battle_completion.go @@ -9,6 +9,9 @@ import ( ) func (p *playerAssembly) prepareBattle(ctx command.Context, result battle.Completion) error { + if err := p.recordBattleStart(ctx, result); err != nil { + return err + } if len(result.Deck) == 0 { return nil } @@ -22,6 +25,9 @@ func (p *playerAssembly) prepareBattle(ctx command.Context, result battle.Comple } func (p *playerAssembly) completeBattle(ctx command.Context, result battle.Completion) ([]byte, error) { + if err := p.recordBattleEnd(ctx, result); err != nil { + return nil, err + } partners, err := p.rosterProgressService.ApplyBattlePartners(ctx, result.Identity, result.Participants, result.Win) if err != nil { return nil, err @@ -34,6 +40,9 @@ func (p *playerAssembly) completeBattle(ctx command.Context, result battle.Compl } func (p *playerAssembly) completePVP(ctx command.Context, mode pvp.Mode, identity string, win bool, enteredDeck [][]byte) ([]byte, error) { + if err := p.recordPVPEnd(ctx, mode, win); err != nil { + return nil, err + } if mode != pvp.Mirror { return nil, nil } diff --git a/go/internal/server/app/player_commerce.go b/go/internal/server/app/player_commerce.go index 87c3431..1cda361 100644 --- a/go/internal/server/app/player_commerce.go +++ b/go/internal/server/app/player_commerce.go @@ -92,8 +92,8 @@ func (p *playerAssembly) commerce(ctx command.Context) error { if err != nil { return fmt.Errorf("load event tasks state: %w", err) } - if err := p.mailService.AttachAttendanceRewardEconomy(ctx, p.eventEconomy); err != nil { - return fmt.Errorf("attach attendance mail rewards: %w", err) + if err := p.mailService.AttachAttachmentRewardEconomy(ctx, p.eventEconomy); err != nil { + return fmt.Errorf("attach mail attachment rewards: %w", err) } p.eventTasksService.AttachAttendanceMail(p.mailService) newbieStep, _, err := wire.Varint(p.login.UserInfo, 39) @@ -135,6 +135,9 @@ func (p *playerAssembly) commerce(ctx command.Context) error { } p.loginPasses.SetClock(time.Now, p.design.eventAPReset.ResetSeconds-9*3600) p.eventTasksService.AttachUnlockResolver(p.worldService.MissionsUnlocked) + p.eventTasksService.AttachProgress(p.recordMission) + p.eventTasksService.AttachAccountState(p.missionAccountState) + p.ownedEquipment.AttachMissionProgress(p.recordMission, func(id uint64) uint64 { return p.design.achievementGrades.Equipment[id] }) if err = p.missionService.AttachEventHandler(ctx, p.eventTasksService); err != nil { return fmt.Errorf("attach mission event handler: %w", err) } diff --git a/go/internal/server/app/player_events.go b/go/internal/server/app/player_events.go index f55ee3c..2747bcf 100644 --- a/go/internal/server/app/player_events.go +++ b/go/internal/server/app/player_events.go @@ -12,7 +12,7 @@ import ( "bd2server/internal/server/domain/events/tasks" "bd2server/internal/server/domain/fishing" "bd2server/internal/server/domain/progression/achievements" - "bd2server/internal/server/domain/progression/missions" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/domain/roster" loginprotocol "bd2server/internal/server/protocol/login" "fmt" @@ -64,6 +64,7 @@ func (p *playerAssembly) events(ctx command.Context) error { if err != nil { return fmt.Errorf("load fishing state: %w", err) } + p.fishingService.AttachProgress(p.recordMission) if err := p.login.AttachFishing(func() loginprotocol.FishingState { state := p.fishingService.Profile() return loginprotocol.FishingState{AP: state.MultiAP, FishSlots: state.FishSlots, RodSlots: state.RodSlots, ItemSlots: state.ItemSlots} @@ -111,12 +112,8 @@ func (p *playerAssembly) events(ctx command.Context) error { } return rows, nil }) - p.eventActionsService.AttachProgress(func(ctx command.Context, condition, sub, count uint64) error { - return p.missionService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked) - }) - p.eventPlayService.AttachProgress(func(ctx command.Context, condition, sub, count uint64) error { - return p.missionService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked) - }) + p.eventActionsService.AttachProgress(p.recordMission) + p.eventPlayService.AttachProgress(p.recordMission) p.eventPlayService.AttachRhythmResult(p.eventTasksService.RecordRhythmResult) p.eventTasksService.AttachAssociatedMissionGroup(func(schedule events.Schedule) uint64 { if group := p.eventActionsService.AssociatedMissionGroup(schedule); group != 0 { @@ -131,6 +128,7 @@ func (p *playerAssembly) events(ctx command.Context) error { p.battleService.AttachEventBattle(p.eventActionsService) p.battleService.AttachCurrentDifficulty(p.worldService.CurrentQuestDifficulty) p.battleService.AttachQuestBattleValidation(p.worldService.ValidateQuestBattle) + p.worldService.AttachQuestVictory(p.battleService.HasWonQuest) p.battleService.AttachRewards(func(ctx command.Context, identity string, rewards []gamedata.Reward) ([]byte, error) { return p.eventEconomy.Apply(ctx, identity, nil, rewards) }) @@ -186,7 +184,7 @@ func (p *playerAssembly) events(ctx command.Context) error { return err } p.battleService.AttachMonsterWinMission(func(ctx command.Context) error { - return p.missionService.CompleteSingleTargetEvent(ctx, missions.ConditionMonsterKill, p.worldService.MissionsUnlocked) + return p.recordMission(ctx, conditions.Event{Type: conditions.MonsterKill, Count: 1}) }) p.battleService.AttachPictorialBuffs(func(ctx command.Context) ([]gamedata.PictorialBuffStat, error) { _, buffs, err := p.pictorialService.Snapshot(ctx) @@ -200,8 +198,10 @@ func (p *playerAssembly) events(ctx command.Context) error { return fmt.Errorf("attach achievement completion validation: %w", err) } p.commissionService.CompleteAchievement = func(ctx command.Context, identity string) error { - _, err := p.achievementCounters.RecordEvent(ctx, identity, 17, 0, 1) - return err + if _, err := p.achievementCounters.RecordEvent(ctx, identity, 17, 0, 1); err != nil { + return err + } + return p.recordMission(ctx, conditions.Event{Type: conditions.TodayQuestClear, Count: 1}) } if err := p.login.AttachAchievementExperience(p.missionService); err != nil { return fmt.Errorf("attach persisted achievement experience: %w", err) @@ -215,11 +215,18 @@ func (p *playerAssembly) events(ctx command.Context) error { return fmt.Errorf("initialize achievement gameplay observer: %w", err) } p.eventTasksService.AttachInventoryProvider(&eventtasks.InventoryProjection{Items: p.ownedItems, Equipment: p.ownedEquipment, Costumes: p.collection, StateVersion: p.stateRepository.ObservationVersion}) + p.eventTasksService.AttachGachaHistory(p.collection.GachaHistory) + p.eventTasksService.AttachAchievementLevelReward(p.missionService.LevelRewardCount) p.worldService.AttachSkyWayProgress(p.eventTasksService.RecordSkyWayClear, func(ctx command.Context, group uint64) error { - return p.missionService.RecordEvent(ctx, 227, group, 1, p.worldService.MissionsUnlocked) + return p.recordMission(ctx, conditions.Event{Type: conditions.SkywayGroupBattle, Sub: group, Count: 1}) + }) + p.worldService.AttachMissionProgress(p.recordMission) + p.eventEconomy.AttachProgress(p.recordMission) + p.huntingService.AttachAPSpent(func(ctx command.Context, cost uint64) error { + return p.recordMission(ctx, conditions.Event{Type: conditions.ItemCurrencyUse, Sub: 21, Count: cost}) // EElementType FreeHuntingAP }) p.huntingService.AttachDispatchProgress(func(ctx command.Context, count uint64) error { - return p.missionService.RecordEvent(ctx, 23, 0, count, p.worldService.MissionsUnlocked) + return p.recordMission(ctx, conditions.Event{Type: conditions.HuntDispatch, Count: count}) }) return nil } diff --git a/go/internal/server/app/player_executor.go b/go/internal/server/app/player_executor.go index 0671368..6bc27e3 100644 --- a/go/internal/server/app/player_executor.go +++ b/go/internal/server/app/player_executor.go @@ -112,7 +112,7 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r } }() - identity := command.Context{Identity: request.Identity, Cancellation: request.Cancellation, State: tx} + identity := command.Context{Identity: request.Identity, Cancellation: request.Cancellation, State: tx, InstanceIDs: p.factory.instanceIDs()} published := false var chatPolicyPayload []byte identity.Emit = func(event command.Event) error { @@ -346,6 +346,15 @@ func (p *playerAssembly) beginLogin(ctx command.Context) error { if err := p.eventTasksService.ReconcileRhythmResults(ctx, p.eventPlayService.CompletedRhythmResults()); err != nil { return err } + if err := p.eventTasksService.ReconcileAccountState(ctx); err != nil { + return err + } + if err := p.cafeteriaService.ReconcileIntroduction(ctx); err != nil { + return err + } + if err := p.worldService.ClaimOpenFieldPacks(ctx); err != nil { + return err + } return p.missionService.RecordLogin(ctx, p.worldService.MissionsUnlocked) } diff --git a/go/internal/server/app/player_factory.go b/go/internal/server/app/player_factory.go index 22949c3..767089d 100644 --- a/go/internal/server/app/player_factory.go +++ b/go/internal/server/app/player_factory.go @@ -1,6 +1,7 @@ package app import ( + "bd2server/internal/common/util" "bd2server/internal/server/domain/battle" "bd2server/internal/server/domain/battle/castle" "bd2server/internal/server/domain/battle/hunting" @@ -41,6 +42,7 @@ import ( "bd2server/internal/server/protocol/wire" "bd2server/internal/server/storage/account" identitystore "bd2server/internal/server/storage/identity" + "bd2server/internal/server/storage/instanceid" "bd2server/internal/server/storage/stateio" "context" "errors" @@ -48,23 +50,33 @@ import ( "os" "path/filepath" "slices" + "sync" "time" ) type PlayerFactory struct { - roomResults *roomResults - shared *sharedRuntime - pvpSource pvp.Source - wakeOutbox func(string) - options *configuration - design *designCatalog - seeds *seedCatalog - profiles interface { + instanceOnce sync.Once + instanceSource util.InstanceIDSource + roomResults *roomResults + shared *sharedRuntime + pvpSource pvp.Source + wakeOutbox func(string) + options *configuration + design *designCatalog + seeds *seedCatalog + profiles interface { GameIdentity(context.Context, string) (identitystore.GameProfile, error) RecordGameLogin(context.Context, string, time.Time) error } } +func (f *PlayerFactory) instanceIDs() util.InstanceIDSource { + f.instanceOnce.Do(func() { + f.instanceSource = instanceid.New(filepath.Join(f.options.stateDirectory, "instance-ids.db")) + }) + return f.instanceSource +} + type playerAssembly struct { cafeteriaService *cafeteria.Service datingService *dating.Service @@ -236,7 +248,7 @@ func (f *PlayerFactory) assemble(ctx context.Context, accountID string, reposito } }() - identity := command.Context{Identity: command.Identity{AccountID: accountID, SessionID: "startup", RequestID: "initialize"}, Cancellation: ctx, State: startupTransaction} + identity := command.Context{Identity: command.Identity{AccountID: accountID, SessionID: "startup", RequestID: "initialize"}, Cancellation: ctx, State: startupTransaction, InstanceIDs: f.instanceIDs()} for _, assemble := range []func(command.Context) error{p.assets, p.worldRoster, p.gameplay, p.commerce, p.events, p.optionalGameplay, p.openIB, p.rogueLike, p.session} { if err := assemble(identity); err != nil { return nil, err diff --git a/go/internal/server/app/player_isolation_test.go b/go/internal/server/app/player_isolation_test.go index 70e4b55..586fd9b 100644 --- a/go/internal/server/app/player_isolation_test.go +++ b/go/internal/server/app/player_isolation_test.go @@ -9,6 +9,7 @@ import ( "bd2server/internal/server/domain/command" "bd2server/internal/server/domain/events/calendar" "bd2server/internal/server/domain/identity" + "bd2server/internal/server/domain/mail" "bd2server/internal/server/domain/roster" "bd2server/internal/server/platform/textmoderation" "bd2server/internal/server/runtime/player" @@ -208,6 +209,27 @@ func appItemTotals(body []byte) map[[2]uint64]uint64 { } func TestTwoRealPlayerBundlesKeepEquipmentFormationAndWorldSeparate(t *testing.T) { factory, accounts := newIntegrationFactory(t) + // The captured starter mailbox has fixed expirations; keep one resource + // gift claimable so this isolation test does not become time-dependent. + isResourceMail := func(entry *mail.MailDBInfo) bool { + if len(entry.RewardTypes) == 0 { + return false + } + for i, kind := range entry.RewardTypes { + if kind != 8 || entry.RewardIDs[i] == 0 { + return false + } + } + return true + } + now := uint64(time.Now().UnixMilli()) + for i := range factory.seeds.mailbox.Mails { + entry := &factory.seeds.mailbox.Mails[i] + if isResourceMail(entry) && entry.ExpiresAt <= now { + entry.ExpiresAt = now + 24*60*60*1000 + break + } + } aID, bID := accounts[0], accounts[1] instances := map[string]*playerInstance{} runtimes := map[string]*player.Runtime{} @@ -231,13 +253,12 @@ func TestTwoRealPlayerBundlesKeepEquipmentFormationAndWorldSeparate(t *testing.T t.Fatal("assemble actual account", accountID, err) } instances[accountID] = instance - // Establish one owned weapon as an explicit test grant before the actor is - // exposed. Both players may legitimately use equal inventory numbers. + // Establish one owned weapon as an explicit grant before exposing the actor. tx, err := instance.repository.BeginCommand(context.Background()) if err != nil { t.Fatal(err) } - ctx := command.Context{Identity: command.Identity{AccountID: accountID, SessionID: "fixture", RequestID: "weapon"}, State: tx} + ctx := command.Context{Identity: command.Identity{AccountID: accountID, SessionID: "fixture", RequestID: "weapon"}, State: tx, InstanceIDs: factory.instanceIDs()} equipment, err := instance.assembly.ownedEquipment.GrantOnce(ctx, "test-owned-weapon", equipmentID) if err != nil { _ = tx.Rollback() @@ -385,13 +406,7 @@ func TestTwoRealPlayerBundlesKeepEquipmentFormationAndWorldSeparate(t *testing.T var starterMail uint64 expectedItems := map[[2]uint64]uint64{} for _, entry := range factory.seeds.mailbox.Mails { - valid := len(entry.RewardTypes) > 0 - for i, kind := range entry.RewardTypes { - if kind != 8 || entry.RewardIDs[i] == 0 { - valid = false - } - } - if valid && entry.ExpiresAt > uint64(time.Now().UnixMilli()) { + if isResourceMail(&entry) && entry.ExpiresAt > now { starterMail = entry.MailID for i, kind := range entry.RewardTypes { expectedItems[[2]uint64{kind, entry.RewardIDs[i]}] += entry.RewardCounts[i] @@ -470,7 +485,7 @@ func TestTwoRealPlayerBundlesKeepEquipmentFormationAndWorldSeparate(t *testing.T } bEquipment := appRows(query(bID, "/EquipInfo", 21), 1) if len(bEquipment) != 1 || appValue(bEquipment[0], 2) != 0 { - t.Fatal("A equipped B's equal-index weapon") + t.Fatal("A equipped B's weapon") } aEquipment := appRows(query(aID, "/EquipInfo", 22), 1) if len(aEquipment) != 1 || appValue(aEquipment[0], 2) != characterIndex[aID] { diff --git a/go/internal/server/app/player_mission_actions.go b/go/internal/server/app/player_mission_actions.go new file mode 100644 index 0000000..141b498 --- /dev/null +++ b/go/internal/server/app/player_mission_actions.go @@ -0,0 +1,43 @@ +package app + +import ( + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" + "bd2server/internal/server/protocol/wire" +) + +// missionActionObserver counts mission conditions whose action is one +// successful request with no richer domain event. It runs before the event +// mission observer, so that observer's notification includes the progress. +type missionActionObserver struct{ player *playerAssembly } + +// missionActionPaths maps a request to the Define_MissionConditionType it +// performs once. +var missionActionPaths = map[string]uint64{ + "/CafeteriaCumulativeReward": conditions.CafeteriaCumulativeReward, + "/MyRoomItemInfo": conditions.MyRoomVisit, + "/MyRoomLike": conditions.MyRoomLike, + "/ShopBuy": conditions.BuyItemInShop, + "/SquareReward": conditions.SquareReward, + "/MercenaryScout": conditions.CharScoutToTargetGrade, + "/CharSpecialScoutBuy": conditions.CharScoutToTargetGrade, +} + +func (o missionActionObserver) BeforeDispatch(command.Context, string, []byte) error { return nil } + +func (o missionActionObserver) AfterDispatch(ctx command.Context, path string, request, _ []byte) ([]byte, error) { + condition, ok := missionActionPaths[path] + if path == "/MyRoomUserInfo" { + // Field 2 is the room owner; the account's own room is a visit. + owner, err := o.player.ProfileOwner(ctx) + if err != nil { + return nil, err + } + target, _, _ := wire.Varint(request, 2) + condition, ok = conditions.MyRoomVisit, target == owner + } + if !ok { + return nil, nil + } + return nil, o.player.recordMission(ctx, conditions.Event{Type: condition, Count: 1}) +} diff --git a/go/internal/server/app/player_mission_state.go b/go/internal/server/app/player_mission_state.go new file mode 100644 index 0000000..f2da16a --- /dev/null +++ b/go/internal/server/app/player_mission_state.go @@ -0,0 +1,262 @@ +package app + +import ( + "strconv" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/battle" + "bd2server/internal/server/domain/battle/castle" + "bd2server/internal/server/domain/battle/pvp" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" + "bd2server/internal/server/domain/roster" +) + +// recordMission applies one authoritative occurrence to the regular missions +// and, through their event handler, to the scheduled event missions. +func (p *playerAssembly) recordMission(ctx command.Context, event conditions.Event) error { + return p.missionService.RecordEvent(ctx, event, p.worldService.MissionsUnlocked) +} + +// missionAccountState derives the progress of conditions that describe +// account state rather than an occurrence, so progress made before a mission +// opened, or before the server recorded the action, still counts. Values are +// raised only; the event mission service never lowers recorded progress. +func (p *playerAssembly) missionAccountState(ctx command.Context, specs []conditions.Spec) ([]uint64, error) { + values := make([]uint64, len(specs)) + var castleProgress *castle.MissionProgress + loadCastle := func() (*castle.MissionProgress, error) { + if castleProgress == nil { + progress, err := p.castleService.MissionProgress(ctx) + if err != nil { + return nil, err + } + castleProgress = &progress + } + return castleProgress, nil + } + var bestRank *uint64 + for i, spec := range specs { + switch spec.Type { + case conditions.PlatformConnectOrLogin: + // Every session belongs to an authenticated platform account, so + // the account is always bound. + values[i] = 1 + case conditions.PackQuestIDClear: // pack = SubType, quests = Params + for _, quest := range spec.Params { + if quest != 0 && p.worldService.MissionsUnlocked(ctx, spec.SubType, quest) { + values[i]++ + } + } + case conditions.CharTargetLevelUp: + values[i] = p.countCharacters(spec, func(c roster.Character) uint64 { return c.Level }) + case conditions.CharTargetGradeUp: + values[i] = p.countCharacters(spec, func(c roster.Character) uint64 { return p.design.achievementGrades.CharacterGrowth[c.ID] }) + case conditions.CostumePotentialNodeKind: // SubType = CostumeNodeTable NodeType + for _, costume := range p.collection.Costumes() { + for _, id := range costume.PotentialIDs { + if node, ok := p.design.costumePotentialDesign.Nodes[costume.ID][id]; ok && node.NodeType == spec.SubType { + values[i]++ + } + } + } + case conditions.PvpRankGoal: // SubType = MirrorRankTable ID; lower IDs rank higher + if p.pvpService == nil { + continue + } + if bestRank == nil { + best, err := p.pvpService.BestMirrorRankID(ctx) + if err != nil { + return nil, err + } + bestRank = &best + } + if *bestRank != 0 && *bestRank <= spec.SubType { + values[i] = 1 + } + case conditions.TalentSkillUpgrade: // SubType = talent class, Params = level + for _, c := range p.permanentCharacters() { + character, ok := p.design.talentUseDesign.Characters[c.ID] + rule, known := p.design.talentUseDesign.Rules[[2]uint64{character.Group, c.TalentLevel}] + if ok && known && rule.Class == spec.SubType && (conditions.AnyParam(spec.Params) || c.TalentLevel >= spec.Params[0]) { + values[i]++ + } + } + case conditions.OtherGroupMissionComplete: // SubType = regular GroupId + values[i] = p.missionService.CompletedMissionCount(spec.SubType) + case conditions.DatingEpisodeClear: + if p.datingService != nil { + values[i] = p.datingService.ClearedEpisodeGroups() + } + case conditions.CharImprintLevelUp: + for _, awake := range p.collection.CharAwakeStates() { + for _, level := range awake.ImprintLevels { + values[i] += level + } + } + case conditions.CharAwakeActive: + for _, awake := range p.collection.CharAwakeStates() { + if awake.IsAwake { + values[i]++ + } + } + case conditions.EvilCastleRageTowerClear, conditions.EvilCastleEnvyTowerClear, conditions.EvilCastleGreedTowerClear: // SubType = floor + if p.castleService == nil { + continue + } + progress, err := loadCastle() + if err != nil { + return nil, err + } + // Define_BattleModeType: 19 RAGE, 20 ENVY, 16 GREED. + mode := map[uint64]uint64{conditions.EvilCastleRageTowerClear: 19, conditions.EvilCastleEnvyTowerClear: 20, conditions.EvilCastleGreedTowerClear: 16}[spec.Type] + if progress.Towers[mode][spec.SubType] { + values[i] = 1 + } + case conditions.EvilCastleFloorBattle, conditions.EvilCastleFloorClear: // SubType = Pride floor + if p.castleService == nil { + continue + } + progress, err := loadCastle() + if err != nil { + return nil, err + } + reached := progress.PrideCleared + if spec.Type == conditions.EvilCastleFloorBattle { + reached = progress.PrideFought + } + if reached[spec.SubType] { + values[i] = 1 + } + case conditions.TotalWarResultScore: + if p.castleService == nil { + continue + } + progress, err := loadCastle() + if err != nil { + return nil, err + } + if spec.SubTypeReached(progress.TotalWarBest) { + values[i] = 1 + } + case conditions.EquipmentUpgradeToLevel: + for _, equipment := range p.ownedEquipment.All(ctx) { + if equipment.Level >= spec.SubType { + values[i]++ + } + } + case conditions.FishingBoatUpgrade: // SubType = boat level + if p.fishingService != nil && p.fishingService.Profile().BoatLevel >= spec.SubType { + values[i] = 1 + } + case conditions.FriendshipTargetLevelUp: // SubType = friendship level + for _, entry := range p.collection.FriendshipEntries() { + if entry.State != nil && entry.State.Level >= spec.SubType { + values[i]++ + } + } + case conditions.FriendshipCostumeLevelUp: // SubType = costume; value = its friendship level + if entry, ok := p.collection.FriendshipEntries()["costume:"+strconv.FormatUint(spec.SubType, 10)]; ok && entry.State != nil { + values[i] = entry.State.Level + } + } + } + return values, nil +} + +// permanentCharacters excludes temporary charm and story characters, which +// do not belong to the account roster. +func (p *playerAssembly) permanentCharacters() []roster.Character { + var out []roster.Character + for _, c := range p.worldService.CharacterService().RawAll() { + if !roster.IsCharmCharacter(c) && !roster.IsStoryCharacter(c) { + out = append(out, c) + } + } + return out +} + +// countCharacters counts the permanent characters whose value reached the +// SubType and whose UniqueCharId is listed in Params. Reaching a higher level +// or grade includes the lower one the mission names. +func (p *playerAssembly) countCharacters(spec conditions.Spec, value func(roster.Character) uint64) uint64 { + var count uint64 + for _, c := range p.permanentCharacters() { + if value(c) >= spec.SubType && spec.ParamAccepts(p.design.costumePotentialDesign.CharacterUnique[c.ID]) { + count++ + } + } + return count +} + +// Define_BattleModeType values the battle mission conditions name. +const ( + battleModeHuntingGround uint64 = 5 // HUNTING_GROUND + battleModePVP uint64 = 6 // PVP + battleModeMonsterHunt uint64 = 8 // MONSTER_HUNT + battleModeMonsterHuntPractice uint64 = 24 // MONSTER_HUNT_PRACTICE + battleModeRogueLike uint64 = 21 // ROGUE_LIKE + packTypePVP uint64 = 3 // Define_PackType PVP +) + +// recordBattleStart counts the first round of an encounter. +func (p *playerAssembly) recordBattleStart(ctx command.Context, result battle.Completion) error { + mode := result.Context.BattleMode + events := []conditions.Event{{Type: conditions.BattleModeStartTry, Sub: mode, Count: 1}} + seen := map[uint64]bool{} + for _, index := range result.Participants { + character, owned := p.worldService.CharacterService().Find(ctx, index) + unique := p.design.costumePotentialDesign.CharacterUnique[character.ID] + if owned && unique != 0 && !seen[unique] { + seen[unique] = true + events = append(events, conditions.Event{Type: conditions.BattleStartWithUniqueChar, Sub: unique, Count: 1}) + } + } + if mode == battleModeMonsterHunt || mode == battleModeMonsterHuntPractice { + events = append(events, conditions.Event{Type: conditions.MonsterHuntBattleWithTraining, Count: 1}) + } + if mode == battleModeMonsterHunt { + events = append(events, conditions.Event{Type: conditions.MonsterHuntBattle, Count: 1}) + } + return p.recordMissions(ctx, events) +} + +// recordBattleEnd counts a settled encounter. McPackBattle names the pack as +// SubType and the battle mode as its param. +func (p *playerAssembly) recordBattleEnd(ctx command.Context, result battle.Completion) error { + mode := result.Context.BattleMode + events := []conditions.Event{{Type: conditions.PackBattle, Sub: result.Context.PackID, Param: mode, Count: 1}} + if mode == battleModeHuntingGround || gamedata.IsSkyWayMode(mode) { + events = append(events, conditions.Event{Type: conditions.HuntingBattle, Count: 1}) + } + if mode == battleModeMonsterHunt && result.Win { + events = append(events, conditions.Event{Type: conditions.MonsterHuntWin, Count: 1}) + } + return p.recordMissions(ctx, events) +} + +// recordPVPEnd counts a settled Mirror battle in the PVP pack, and a +// Colosseum victory. +func (p *playerAssembly) recordPVPEnd(ctx command.Context, mode pvp.Mode, win bool) error { + if mode == pvp.Colosseum { + if !win { + return nil + } + return p.recordMission(ctx, conditions.Event{Type: conditions.ColosseumBattleWin, Count: 1}) + } + for id, pack := range p.design.world.FieldPacks { + if pack.Type == packTypePVP { + return p.recordMission(ctx, conditions.Event{Type: conditions.PackBattle, Sub: uint64(id), Param: battleModePVP, Count: 1}) + } + } + return nil +} + +func (p *playerAssembly) recordMissions(ctx command.Context, events []conditions.Event) error { + for _, event := range events { + if err := p.recordMission(ctx, event); err != nil { + return err + } + } + return nil +} diff --git a/go/internal/server/app/player_optional_gameplay.go b/go/internal/server/app/player_optional_gameplay.go index a50f481..2d400af 100644 --- a/go/internal/server/app/player_optional_gameplay.go +++ b/go/internal/server/app/player_optional_gameplay.go @@ -1,6 +1,7 @@ package app import ( + "bd2server/internal/server/domain/progression/conditions" "encoding/json" "fmt" "slices" @@ -41,6 +42,14 @@ func (p *playerAssembly) optionalGameplay(ctx command.Context) error { } p.datingService.SetResetSeconds(p.design.eventAPReset.ResetSeconds) p.cafeteriaService.SetResetSeconds(p.design.eventAPReset.ResetSeconds) + p.cafeteriaService.AttachDatingTicket(p.design.contentOpeningDesign.Dating.TicketID, func(ctx command.Context, ticket uint64) bool { + for _, item := range p.ownedItems.All(ctx) { + if item.Type == 19 && item.ID == ticket && item.Count > 0 { + return true + } + } + return false + }) p.cafeteriaService.AttachOwnedCostumes(func() []uint64 { var ids []uint64 for _, costume := range p.collection.Costumes() { @@ -49,6 +58,7 @@ func (p *playerAssembly) optionalGameplay(ctx command.Context) error { return ids }) p.cafeteriaService.AttachDatingHasEpisode(p.datingService.HasEpisode) + p.worldService.AttachFieldPackEconomy(p.eventEconomy) p.datingService.AttachFirstMeeting(p.cafeteriaService.CanMeet) p.castleService = castle.NewService(p.design.castle) p.castleService.AttachTotalWarTextCheck(p.checkProfileText) @@ -69,6 +79,9 @@ func (p *playerAssembly) optionalGameplay(ctx command.Context) error { } return ctx.Publish(command.Event{ID: "totalwar:" + identity, Topic: deck.PopularityTopic, Payload: payload}) }) + p.castleService.AttachTotalWarSettled(func(ctx command.Context, total uint64) error { + return p.recordMissions(ctx, []conditions.Event{{Type: conditions.TotalWarTryCount, Count: 1}, {Type: conditions.TotalWarResultScore, Sub: total, Count: 1}}) + }) p.castleService.AttachCurrentPack(p.worldService.CurrentPackID) p.castleService.AttachEvidence(p.battleService.SettlementEvidence) p.castleService.AttachRewards(func(ctx command.Context, identity string, rewards []gamedata.Reward) ([]byte, error) { diff --git a/go/internal/server/app/player_pvp.go b/go/internal/server/app/player_pvp.go index 0ce12cf..60f849a 100644 --- a/go/internal/server/app/player_pvp.go +++ b/go/internal/server/app/player_pvp.go @@ -5,7 +5,10 @@ import ( "bd2server/internal/server/domain/battle/pvp" "bd2server/internal/server/domain/command" "bd2server/internal/server/domain/events" + "bd2server/internal/server/storage/shared" + "context" "fmt" + "time" ) func (p *playerAssembly) multiplayerPVP(ctx command.Context) error { @@ -29,7 +32,8 @@ func (p *playerAssembly) multiplayerPVP(ctx command.Context) error { Buffs: func(ctx command.Context) ([]gamedata.PictorialBuffStat, error) { _, buffs, err := p.pictorialService.Snapshot(ctx) return buffs, err - }} + }, + CostumeCosts: p.colosseumCostumeCosts} p.pvpService, err = pvp.Open(ctx, p.design.pvp, public, p.pvpSource, builder, func(ctx command.Context, id string, cost []gamedata.BattleReward) error { _, err := p.eventEconomy.Apply(ctx, id, pvpRewards(cost), nil) @@ -84,3 +88,19 @@ func pvpRewards(in []gamedata.BattleReward) []gamedata.Reward { } return out } + +func (p *playerAssembly) colosseumCostumeCosts(ctx command.Context) (map[uint64]uint64, error) { + cancel := ctx.Cancellation + if cancel == nil { + cancel = context.Background() + } + costs := map[uint64]uint64{} + err := p.shared.store.View(cancel, func(tx *shared.Tx) error { + table, err := p.shared.colosseumCosts(tx, uint64(time.Now().UnixMilli())) + for _, row := range table.Costumes { + costs[row.ID] = row.Cost + } + return err + }) + return costs, err +} diff --git a/go/internal/server/app/player_roguelike.go b/go/internal/server/app/player_roguelike.go index a0173b7..12bd4a8 100644 --- a/go/internal/server/app/player_roguelike.go +++ b/go/internal/server/app/player_roguelike.go @@ -5,6 +5,7 @@ import ( "bd2server/internal/server/design/schedule" "bd2server/internal/server/domain/battle/roguelike" "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/domain/roster" "bd2server/internal/server/protocol/wire" "bd2server/internal/server/storage/outbox" @@ -26,6 +27,17 @@ func (s *sharedRuntime) consumeRogueRanking(ctx context.Context, event outbox.Pe } return s.rogueRanks.Publish(ctx, p) } + +// rogueLikeBattleEvent names the roguelike pack from GameData and the +// ROGUE_LIKE battle mode for McPackBattle. +func (p *playerAssembly) rogueLikeBattleEvent() conditions.Event { + return conditions.Event{Type: conditions.PackBattle, Sub: p.design.roguelike.Pack, Param: battleModeRogueLike, Count: 1} +} + +func (p *playerAssembly) recordRogueLikeBattle(ctx command.Context) error { + return p.recordMission(ctx, p.rogueLikeBattleEvent()) +} + func (p *playerAssembly) rogueLike(ctx command.Context) error { owner, e := p.ProfileOwner(ctx) if e != nil { @@ -131,7 +143,8 @@ func (p *playerAssembly) rogueLike(ctx command.Context) error { hp := gamedata.AggregateStats(gamedata.BaseStats{Health: float64(c.Health)}, contributions).Health return uint64(hp), nil }, - Ranking: p.rogueRanking(), + Ranking: p.rogueRanking(), + OnBattle: p.recordRogueLikeBattle, Publish: func(ctx command.Context, season, score, damage, version uint64) error { profile, e := p.PublicProfile(ctx, owner) if e != nil { diff --git a/go/internal/server/app/player_session.go b/go/internal/server/app/player_session.go index 3ab8a12..8b8cf17 100644 --- a/go/internal/server/app/player_session.go +++ b/go/internal/server/app/player_session.go @@ -4,7 +4,6 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" "bd2server/internal/server/domain/commerce" - "bd2server/internal/server/domain/commerce/gacha" "bd2server/internal/server/domain/events" "bd2server/internal/server/domain/notice" "bd2server/internal/server/domain/profile" @@ -17,7 +16,6 @@ import ( "bd2server/internal/server/storage/account" "context" "fmt" - "time" ) func (p *playerAssembly) session(ctx command.Context) error { @@ -32,6 +30,11 @@ func (p *playerAssembly) session(ctx command.Context) error { if err := p.nickname(ctx); err != nil { return err } + masterTitle, err := roster.OpenMasterTitleService(ctx, p.scope, p.nicknameService.CurrentNickname()) + if err != nil { + return fmt.Errorf("load master title: %w", err) + } + p.masterTitleService = masterTitle if err := p.avatar(ctx); err != nil { return err } @@ -126,19 +129,9 @@ func (p *playerAssembly) session(ctx command.Context) error { if p.pvpService != nil { p.handlers = append([]session.Handler{p.pvpService}, p.handlers...) } - p.observers = []session.ResponseObserver{p.achievementObserver, p.eventTasksService, p.mailService} - featured := gacha.ActivePickupCostumes(p.design.regularGacha, p.options.calendars.GachaSeed, uint64(time.Now().UTC().UnixMilli())) - limitedIDs := p.design.limitedCostumes.Excluding(featured) - if len(limitedIDs) != 0 { - if err := p.mailService.EnsureStarterLimitedCostumes(ctx, limitedIDs, time.Now().UTC()); err != nil { - return fmt.Errorf("ensure account limited-costume entitlement: %w", err) - } - } - prestigeIDs := p.design.prestigeCatalog.Giftable(func(key gamedata.CashProductKey) bool { return p.cashService.IsAvailable(ctx, key) }) - if len(prestigeIDs) != 0 { - if err := p.mailService.EnsureStarterPrestigeSkins(ctx, prestigeIDs, time.Now().UTC()); err != nil { - return fmt.Errorf("ensure account prestige-skin entitlement: %w", err) - } + p.observers = []session.ResponseObserver{p.achievementObserver, missionActionObserver{p}, p.eventTasksService, p.mailService} + if err := p.mailService.AttachStarterGifts(ctx, p.starterGifts); err != nil { + return fmt.Errorf("ensure account starter gifts: %w", err) } if p.initializeAccount { if err := ensureAccountStateInitialized(ctx, diff --git a/go/internal/server/app/player_starter_gifts.go b/go/internal/server/app/player_starter_gifts.go new file mode 100644 index 0000000..6373140 --- /dev/null +++ b/go/internal/server/app/player_starter_gifts.go @@ -0,0 +1,25 @@ +package app + +import ( + "time" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/commerce/gacha" + "bd2server/internal/server/domain/startergift" +) + +func (p *playerAssembly) starterGifts(ctx command.Context) ([]startergift.Gift, error) { + owned := map[uint64]bool{} + for _, item := range p.ownedItems.All(ctx) { + if item.Type == 45 && item.Count != 0 { + owned[item.ID] = true + } + } + return p.seeds.starterGifts.Resolve(startergift.Selection{ + Limited: p.design.limitedCostumes, Prestige: p.design.prestigeCatalog, Avatars: p.design.avatarProfile, + Featured: gacha.ActivePickupCostumes(p.design.regularGacha, p.options.calendars.GachaSeed, uint64(time.Now().UTC().UnixMilli())), + CashAvailable: func(key gamedata.CashProductKey) bool { return p.cashService.IsAvailable(ctx, key) }, + OwnedPrestige: owned, + }) +} diff --git a/go/internal/server/app/player_world_roster.go b/go/internal/server/app/player_world_roster.go index b4fe5c1..9b75618 100644 --- a/go/internal/server/app/player_world_roster.go +++ b/go/internal/server/app/player_world_roster.go @@ -4,13 +4,11 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" "bd2server/internal/server/domain/commerce/gacha" - "bd2server/internal/server/domain/progression/missions" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/domain/progression/pictorial" "bd2server/internal/server/domain/roster" "bd2server/internal/server/domain/roster/deck" "bd2server/internal/server/domain/world" - "bd2server/internal/server/protocol/wire" - "errors" "fmt" ) @@ -71,8 +69,11 @@ func (p *playerAssembly) worldRoster(ctx command.Context) error { if err := p.gachaService.AttachStatistics(p.design.collectionStatistics); err != nil { return err } - p.gachaService.AttachDrawMission(func(ctx command.Context, count uint64) error { - return p.missionService.RecordEvent(ctx, missions.ConditionGachaBuy, 0, count, p.worldService.MissionsUnlocked) + p.gachaService.AttachDrawMission(func(ctx command.Context, groupID, count uint64) error { + if err := p.recordMission(ctx, conditions.Event{Type: conditions.GachaBuy, Count: count}); err != nil { + return err + } + return p.recordMission(ctx, conditions.Event{Type: conditions.GachaGroupTry, Sub: groupID, Count: count}) }) var permanentBaseCharacters []roster.Character for _, c := range p.worldService.CharacterService().RawAll() { @@ -184,13 +185,5 @@ func (p *playerAssembly) worldRoster(ctx command.Context) error { if err := p.login.AttachFriendshipAP(p.friendshipService); err != nil { return err } - accountName, found, err := wire.Bytes(p.login.UserInfo, 2) - if err != nil || !found || len(accountName) == 0 { - return errors.New("account seed requires its existing display name for master title") - } - p.masterTitleService, err = roster.OpenMasterTitleService(ctx, p.scope, string(accountName)) - if err != nil { - return fmt.Errorf("load master title: %w", err) - } return nil } diff --git a/go/internal/server/app/prestige_illustration_integration_test.go b/go/internal/server/app/prestige_illustration_integration_test.go index c8daea0..da4a494 100644 --- a/go/internal/server/app/prestige_illustration_integration_test.go +++ b/go/internal/server/app/prestige_illustration_integration_test.go @@ -21,7 +21,9 @@ func TestOwnedPrestigeUnlocksInteractionOnLoginAndWhenClaimed(t *testing.T) { s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])} var sourceTime uint64 s.run(t, true, func(ctx command.Context, p *playerAssembly) { - p.ownedItems.AttachPrestigeIllustrations(nil) + if err := p.ownedItems.AttachPrestigeIllustrations(ctx, nil); err != nil { + t.Fatal(err) + } items, err := p.ownedItems.GrantOnce(ctx, "historical-prestige", []gamedata.BattleReward{{Type: 45, ID: 65193, Count: 1}}) if err != nil || len(items) != 1 { t.Fatalf("seed historical external ownership: %v", err) diff --git a/go/internal/server/app/prestige_snapshot_integration_test.go b/go/internal/server/app/prestige_snapshot_integration_test.go new file mode 100644 index 0000000..e116461 --- /dev/null +++ b/go/internal/server/app/prestige_snapshot_integration_test.go @@ -0,0 +1,136 @@ +//go:build integration + +package app + +import ( + "bytes" + "encoding/json" + "strconv" + "testing" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + assets "bd2server/internal/server/domain/inventory" + "bd2server/internal/server/protocol/wire" +) + +// GameData 20261021182514 maps prestige4091 to costume4001. Native ItemInfo +// calls AddPrestigeSkinInfo without clearing its cache; PrestigeSkinInfo clears +// that cache and restores IsSet. Historical mission and mail grants can coexist. +func TestPrestigeLoginSnapshotPreservesSelectionWithHistoricalDuplicateItems(t *testing.T) { + factory, accounts := newIntegrationFactory(t) + s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])} + t.Cleanup(func() { closeNicknamePlayer(t, s.owner) }) + var skin assets.Item + s.run(t, true, func(ctx command.Context, p *playerAssembly) { + items, err := p.ownedItems.GrantOnce(ctx, "historical-mission-skin", []gamedata.BattleReward{{Type: 45, ID: 4091, Count: 1}}) + if err != nil || len(items) != 1 || items[0].Type != 45 || items[0].Count != 1 { + t.Fatalf("initial skin acquisition: %v %v", items, err) + } + skin = items[0] + info := appScalar(1, 4001) + info = append(info, appScalar(2, 4091)...) + info = append(info, appScalar(3, 1)...) + info = append(info, appScalar(4, skin.TimeValue)...) + request := wire.AppendBytes(appScalar(1, 1), 2, info) + if _, _, handled, err := p.eventEconomy.Handle(ctx, "/PrestigeSkinSet", request); !handled || err != nil { + t.Fatalf("select owned skin: handled=%v error=%v", handled, err) + } + duplicate := skin + duplicate.InvenIndex, err = ctx.NewInstanceID() + if err != nil { + t.Fatal(err) + } + duplicate.TimeValue++ + raw, err := json.Marshal(duplicate) + if err != nil { + t.Fatal(err) + } + if err := ctx.State.PutEntry("items", "items", strconv.FormatUint(duplicate.InvenIndex, 10), raw); err != nil { + t.Fatal(err) + } + }) + s.reopen(t) + s.run(t, false, func(ctx command.Context, p *playerAssembly) { + skinCount := 0 + for _, item := range p.ownedItems.All(ctx) { + if item.Type == 45 && item.ID == 4091 { + skinCount++ + } + } + if skinCount != 2 { + t.Fatalf("historical duplicate fixture was not reopened: %d", skinCount) + } + var previous []byte + for i := range 2 { + _, snapshot, handled, err := p.eventEconomy.Handle(ctx, "/PrestigeSkinInfo", appScalar(1, uint64(i+2))) + if err != nil || !handled { + t.Fatalf("skin snapshot: handled=%v error=%v", handled, err) + } + rows := appRows(snapshot, 1) + if len(rows) != 1 || appValue(rows[0], 1) != 4001 || appValue(rows[0], 2) != 4091 || appValue(rows[0], 3) != 1 || appValue(rows[0], 4) != skin.TimeValue { + t.Fatalf("snapshot lost unique ownership, selection, or acquisition time: %x", snapshot) + } + if i > 0 && !bytes.Equal(previous, snapshot) { + t.Fatal("repeated snapshot changed skin state") + } + previous = snapshot + _, inventory, handled, err := p.ownedItems.Handle(ctx, "/ItemInfo", appScalar(1, uint64(i+4))) + if err != nil || !handled { + t.Fatalf("inventory snapshot: handled=%v error=%v", handled, err) + } + ordinaryIllustration := false + for _, row := range appRows(inventory, 1) { + if appValue(row, 3) == 45 { + t.Fatal("inventory snapshot replays a prestige acquisition") + } + if appValue(row, 3) == 25 && appValue(row, 2) == 181 { + ordinaryIllustration = true + } + } + if !ordinaryIllustration { + t.Fatal("inventory snapshot lost ordinary lobby ownership") + } + } + }) + s.run(t, true, func(ctx command.Context, p *playerAssembly) { + items, err := p.ownedItems.GrantOnce(ctx, "another-mail-same-skin", []gamedata.BattleReward{{Type: 45, ID: 4091, Count: 1}}) + if err != nil || len(items) != 0 { + t.Fatalf("owned skin replayed acquisition: %v %v", items, err) + } + items, err = p.ownedItems.GrantOnce(ctx, "new-mail-skin", []gamedata.BattleReward{{Type: 45, ID: 3892, Count: 2}, {Type: 45, ID: 3892, Count: 1}}) + if err != nil { + t.Fatal(err) + } + skins := 0 + for _, item := range items { + if item.Type == 45 { + skins++ + if item.ID != 3892 || item.Count != 1 { + t.Fatalf("invalid unique acquisition: %+v", item) + } + } + } + if skins != 1 { + t.Fatalf("new skin must emit one acquisition: %v", items) + } + if retry, err := p.ownedItems.GrantOnce(ctx, "new-mail-skin", []gamedata.BattleReward{{Type: 45, ID: 3892, Count: 2}, {Type: 45, ID: 3892, Count: 1}}); err != nil || len(retry) != 0 { + t.Fatalf("retry replayed acquisition: %v %v", retry, err) + } + }) + s.reopen(t) + s.run(t, false, func(ctx command.Context, p *playerAssembly) { + skinCount := 0 + for _, item := range p.ownedItems.All(ctx) { + if item.Type == 45 && item.ID == 3892 { + skinCount++ + if item.Count != 1 { + t.Fatalf("persisted skin count is %d", item.Count) + } + } + } + if skinCount != 1 { + t.Fatalf("new skin ownership was not persisted once: %d", skinCount) + } + }) +} diff --git a/go/internal/server/app/profile_editing_integration_test.go b/go/internal/server/app/profile_editing_integration_test.go index 2806b2f..2a11d10 100644 --- a/go/internal/server/app/profile_editing_integration_test.go +++ b/go/internal/server/app/profile_editing_integration_test.go @@ -43,7 +43,7 @@ func profileGrant(g *puzzleGameplay, rewards ...gamedata.Reward) { g.t.Fatal(err) } defer func() { _ = tx.Rollback() }() - if _, err := g.owner.assembly.eventEconomy.Apply(command.Context{State: tx}, fmt.Sprintf("profile-test:%d", g.seq), nil, rewards); err != nil { + if _, err := g.owner.assembly.eventEconomy.Apply(command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}, fmt.Sprintf("profile-test:%d", g.seq), nil, rewards); err != nil { g.t.Fatal(err) } if err := tx.Commit(); err != nil { @@ -416,7 +416,7 @@ func TestSupporterRegistrationPreservesSlotsAndReturnsOwnedBattleCharacter(t *te } // Current CostumeTable101 is permanent character UniqueChar1. The // integration starter only has story characters, so grant actual ownership. - if _, err := g.owner.assembly.collection.GrantCostumes(command.Context{State: tx}, "profile-supporter-fixture", []uint64{101}, g.factory.design.rewardCostumes); err != nil { + if _, err := g.owner.assembly.collection.GrantCostumes(command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}, "profile-supporter-fixture", []uint64{101}, g.factory.design.rewardCostumes); err != nil { _ = tx.Rollback() t.Fatal(err) } diff --git a/go/internal/server/app/puzzle_integration_test.go b/go/internal/server/app/puzzle_integration_test.go index bd12058..ee11250 100644 --- a/go/internal/server/app/puzzle_integration_test.go +++ b/go/internal/server/app/puzzle_integration_test.go @@ -3,18 +3,13 @@ package app import ( - "bytes" "context" "encoding/binary" "fmt" - "slices" - "strings" "testing" - "time" "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" - "bd2server/internal/server/domain/events" "bd2server/internal/server/protocol/wire" "bd2server/internal/server/runtime/player" ) @@ -108,7 +103,7 @@ func (g *puzzleGameplay) grantTokens(count uint64) { g.t.Fatal(err) } defer func() { _ = tx.Rollback() }() - ctx := command.Context{State: tx} + ctx := command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()} if _, err := g.owner.assembly.ownedItems.GrantOnce(ctx, fmt.Sprintf("puzzle-budget-%d", g.seq), []gamedata.BattleReward{{Type: 8, ID: 2021, Count: count}}); err != nil { g.t.Fatal(err) } @@ -124,7 +119,7 @@ func (g *puzzleGameplay) cost(field int, count uint64) []byte { g.t.Fatal(err) } defer func() { _ = tx.Rollback() }() - items, err := g.owner.assembly.ownedItems.SelectMutable(command.Context{State: tx}, 8, 2021, count) + items, err := g.owner.assembly.ownedItems.SelectMutable(command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}, 8, 2021, count) if err != nil { g.t.Fatal(err) } @@ -202,274 +197,3 @@ func puzzleWordReward(t *testing.T, response []byte, itemType, id, count uint64) // currency 44 x 500, stage-2 material 8/113 x 600, and a terminal stage 12. // This exercises actual client requests, the production reward economy and // the account SQLite transaction rather than an isolated imitation of play. -func TestPuzzleMaximumOpenWordsRenewalAndPersistence(t *testing.T) { - factory, accounts := newIntegrationFactory(t) - owner, err := factory.open(accounts[0]) - if err != nil { - t.Fatal(err) - } - g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner} - t.Cleanup(func() { - if g.owner != nil { - if err := g.owner.Close(); err != nil { - t.Error(err) - } - } - }) - var schedule events.Schedule - for _, candidate := range owner.assembly.eventRegistry.List() { - if candidate.Type == 17 && candidate.ID == 10 && candidate.Start <= time.Now().UnixMilli() && candidate.End > time.Now().UnixMilli() { - schedule = candidate - break - } - } - if schedule.UID == 0 { - t.Fatal("current puzzle event 10 schedule required") - } - uid := appScalar(2, schedule.UID) - g.call("/LoginUser", nil) - var loginTask []byte - for _, row := range appRows(g.call("/EventMissionInfo", nil), 1) { - if appValue(row, 1) == 30030 && appValue(row, 3) == 300301 { - loginTask = row - } - } - if appValue(loginTask, 4) != 1 || appValue(loginTask, 5) != 0 { - t.Fatalf("puzzle login token mission did not complete: %x", loginTask) - } - mission := append(appScalar(3, 2), appScalar(4, 30030)...) - mission = append(mission, appScalar(5, 300301)...) - mission = append(mission, appScalar(6, 30030)...) - claimRequest := g.request("/MissionClear", mission) - beforeTokens := g.itemCount(8, 2021) - g.execute(claimRequest, false) - if got := g.itemCount(8, 2021); got != beforeTokens+2 { - t.Fatalf("puzzle login mission delivered %d tokens, want %d", got, beforeTokens+2) - } - claimRequest.Identity.RequestID += "-replay" - g.execute(claimRequest, false) - if got := g.itemCount(8, 2021); got != beforeTokens+2 { - t.Fatal("mission replay delivered tokens twice") - } - if beforeTokens != 0 { - t.Fatal("fresh account unexpectedly contains puzzle tokens") - } - g.grantTokens(2) - first := g.info(schedule.UID) - board := puzzleNumbers(t, first, 3) - sorted := slices.Clone(board) - slices.Sort(sorted) - if appValue(first, 2) != 1 || len(sorted) != 25 || sorted[0] != 1 || sorted[24] != 25 || len(slices.Compact(sorted)) != 25 { - t.Fatalf("fresh stage has an invalid client board: %x", first) - } - bad := g.execute(g.request("/MiniPuzzleAllOpen", append(uid, g.cost(3, 3)...)), true) - for _, detail := range []string{"/MiniPuzzleAllOpen", fmt.Sprintf("uid=%d", schedule.UID), "submitted=3", "expected=4", "unit_cost=1"} { - if !strings.Contains(string(bad), detail) { - t.Fatalf("cost diagnostic missing %q: %s", detail, bad) - } - } - if !bytes.Equal(first, g.info(schedule.UID)) || g.itemCount(8, 2021) != 4 { - t.Fatal("invalid maximum-open cost changed progress or inventory") - } - forged := append(appScalar(1, 1), appScalar(2, 2021)...) - forged = append(forged, appScalar(3, 8)...) - forged = append(forged, appScalar(4, 1)...) - fields := append(slices.Clone(uid), appScalar(3, board[0])...) - g.execute(g.request("/MiniPuzzleOpen", append(fields, appMessage(4, forged)...)), true) - if !bytes.Equal(first, g.info(schedule.UID)) || g.itemCount(8, 2021) != 4 { - t.Fatal("forged stack consumption changed puzzle progress or inventory") - } - maximum := g.request("/MiniPuzzleAllOpen", append(uid, g.cost(3, 4)...)) - response := g.execute(maximum, false) - after := puzzleResponseState(t, response, 2) - opened := puzzleNumbers(t, after, 4) - if appValue(after, 2) != 1 || len(opened) != 4 || len(slices.Compact(slices.Sorted(slices.Values(opened)))) != 4 || g.itemCount(8, 2021) != 0 { - t.Fatalf("four-token maximum-open did not open and charge four cells: %x", response) - } - if !bytes.Equal(first, puzzleResponseState(t, response, 1)) || !slices.Equal(board, puzzleNumbers(t, after, 3)) { - t.Fatal("maximum-open rearranged the current board or lost its before snapshot") - } - g.reopen() - if !bytes.Equal(after, g.info(schedule.UID)) { - t.Fatal("restart lost partial puzzle progress") - } - maximum.Identity.RequestID += "-reopened-domain-replay" - if got := g.execute(maximum, false); !bytes.Equal(got, response) || g.itemCount(8, 2021) != 0 { - t.Fatal("restart replay changed the response or charged twice") - } - g.grantTokens(400) - beforeWordCurrency := g.wordCurrency() - var completed []byte - for id := uint64(1); id <= 7; id++ { - if slices.Contains(opened, id) { - continue - } - fields := append(slices.Clone(uid), appScalar(3, id)...) - fields = append(fields, g.cost(4, 1)...) - result := g.call("/MiniPuzzleOpen", fields) - opened = puzzleNumbers(t, puzzleResponseState(t, result, 2), 4) - if len(appRows(result, 5)) > 0 { - completed = result - } - } - puzzleWordReward(t, completed, 44, 0, 500) - if g.wordCurrency() != beforeWordCurrency+500 { - t.Fatal("word completion did not credit its currency to durable account state") - } - if len(opened) >= 25 { - t.Fatal("word-only fixture unexpectedly opened the entire board") - } - tokens := g.itemCount(8, 2021) - renewed := g.call("/MiniPuzzleRenew", uid) - if appValue(puzzleResponseState(t, renewed, 1), 2) != 1 || appValue(puzzleResponseState(t, renewed, 2), 2) != 2 || len(puzzleNumbers(t, puzzleResponseState(t, renewed, 2), 4)) != 0 || g.itemCount(8, 2021) != tokens { - t.Fatal("word-complete renewal did not abandon incidental cells without charging") - } - beforeMaterial := g.itemCount(8, 113) - fullRequest := g.request("/MiniPuzzleAllOpen", append(slices.Clone(uid), g.cost(3, 25)...)) - full := g.execute(fullRequest, false) - puzzleWordReward(t, full, 8, 113, 600) - if appValue(puzzleResponseState(t, full, 1), 2) != 2 || appValue(puzzleResponseState(t, full, 2), 2) != 3 || g.itemCount(8, 2021) != tokens-25 || g.itemCount(8, 113) != beforeMaterial+600 { - t.Fatal("full second board did not settle its word reward and automatically advance") - } - g.reopen() - fullRequest.Identity.RequestID += "-domain-reward-replay" - if replay := g.execute(fullRequest, false); !bytes.Equal(replay, full) || g.itemCount(8, 2021) != tokens-25 || g.itemCount(8, 113) != beforeMaterial+600 || g.wordCurrency() != beforeWordCurrency+500 { - t.Fatal("full-board replay after restart duplicated a cost or reward") - } - for stage := uint64(3); stage <= 12; stage++ { - beforeTickets := g.itemCount(8, 1000) - full = g.call("/MiniPuzzleAllOpen", append(slices.Clone(uid), g.cost(3, 25)...)) - wantStage := min(stage+1, uint64(12)) - if appValue(puzzleResponseState(t, full, 1), 2) != stage || appValue(puzzleResponseState(t, full, 2), 2) != wantStage { - t.Fatalf("stage %d did not advance correctly: %x", stage, full) - } - if stage == 7 { - puzzleWordReward(t, full, 8, 1000, 10) - if g.itemCount(8, 1000) != beforeTickets+10 { - t.Fatal("stage-seven word tickets were not credited to inventory") - } - } - } - puzzleWordReward(t, full, 4, 0, 100000) - final := g.info(schedule.UID) - if appValue(final, 2) != 12 || len(puzzleNumbers(t, final, 4)) != 25 { - t.Fatal("terminal puzzle did not retain all completed cells") - } - tokens = g.itemCount(8, 2021) - g.execute(g.request("/MiniPuzzleRenew", uid), true) - g.execute(g.request("/MiniPuzzleAllOpen", uid), true) - if !bytes.Equal(final, g.info(schedule.UID)) || g.itemCount(8, 2021) != tokens { - t.Fatal("terminal operations changed assets or advanced beyond the final stage") - } - g.reopen() - if !bytes.Equal(final, g.info(schedule.UID)) || g.itemCount(8, 2021) != tokens { - t.Fatal("terminal puzzle progress or token balance changed after reopening SQLite") - } - calendar := g.owner.assembly.eventRegistry.List() - for index := range calendar { - if calendar[index].UID == schedule.UID { - calendar[index].End = time.Now().Add(-time.Minute).UnixMilli() - } - } - if err := g.owner.assembly.eventRegistry.Replace(calendar); err != nil { - t.Fatal(err) - } - if !bytes.Equal(final, g.info(schedule.UID)) { - t.Fatal("expired info query erased previously completed progress") - } - closed := g.execute(g.request("/MiniPuzzleRenew", uid), true) - if !strings.Contains(string(closed), "event is closed") || g.itemCount(8, 2021) != tokens { - t.Fatal("expired puzzle allowed mutation or charged resources") - } -} - -// ResourceTable 2021's current stack limit is 9999. A real grant of 10001 -// creates two stacks; consuming 9997 leaves two tokens in each. The native -// maximum-open request must sum both concrete stacks while each schedule -// retains its own board and open-cell history. -func TestPuzzleMaximumOpenUsesSplitStacksAndSeparateSchedules(t *testing.T) { - factory, accounts := newIntegrationFactory(t) - owner, err := factory.open(accounts[0]) - if err != nil { - t.Fatal(err) - } - g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner} - t.Cleanup(func() { - if g.owner != nil { - if err := g.owner.Close(); err != nil { - t.Error(err) - } - } - }) - calendar := owner.assembly.eventRegistry.List() - var schedule events.Schedule - for _, candidate := range calendar { - if candidate.Type == 17 && candidate.ID == 10 { - schedule = candidate - break - } - } - if schedule.UID == 0 { - t.Fatal("current puzzle schedule required") - } - second := schedule - second.UID = 2000000010 - calendar = append(calendar, second) - if err := owner.assembly.eventRegistry.Replace(calendar); err != nil { - t.Fatal(err) - } - uid := appScalar(2, schedule.UID) - firstBoard, secondBoard := g.info(schedule.UID), g.info(second.UID) - g.grantTokens(10001) - tx, err := owner.repository.BeginCommand(context.Background()) - if err != nil { - t.Fatal(err) - } - ctx := command.Context{State: tx} - spent, err := owner.assembly.ownedItems.SelectMutable(ctx, 8, 2021, 9997) - if err == nil { - err = owner.assembly.ownedItems.Consume(ctx, spent) - } - if err != nil { - _ = tx.Rollback() - t.Fatal(err) - } - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - cost := g.cost(3, 4) - stacks := appRows(cost, 3) - if len(stacks) != 2 || appValue(stacks[0], 4) != 2 || appValue(stacks[1], 4) != 2 { - t.Fatalf("split-stack fixture is not two independent two-token entries: %x", cost) - } - duplicate := append(appMessage(3, stacks[0]), appMessage(3, stacks[0])...) - g.execute(g.request("/MiniPuzzleAllOpen", append(slices.Clone(uid), duplicate...)), true) - if !bytes.Equal(firstBoard, g.info(schedule.UID)) || g.itemCount(8, 2021) != 4 { - t.Fatal("duplicate submitted stack changed progress or token balance") - } - // A failed request rebuilds the production assembly from SQLite and its - // configured calendar; reinstall only the second test schedule afterward. - if err := g.owner.assembly.eventRegistry.Replace(calendar); err != nil { - t.Fatal(err) - } - result := g.call("/MiniPuzzleAllOpen", append(slices.Clone(uid), cost...)) - if len(puzzleNumbers(t, puzzleResponseState(t, result, 2), 4)) != 4 || g.itemCount(8, 2021) != 0 || !bytes.Equal(secondBoard, g.info(second.UID)) { - t.Fatal("maximum-open did not consume both stacks or mixed the two schedule states") - } - firstAfter := g.info(schedule.UID) - g.grantTokens(1) - board := puzzleNumbers(t, secondBoard, 3) - fields := append(appScalar(2, second.UID), appScalar(3, board[0])...) - fields = append(fields, g.cost(4, 1)...) - result = g.call("/MiniPuzzleOpen", fields) - if len(puzzleNumbers(t, puzzleResponseState(t, result, 2), 4)) != 1 || !bytes.Equal(firstAfter, g.info(schedule.UID)) || g.itemCount(8, 2021) != 0 { - t.Fatal("single-open used another schedule's cells or did not charge its token") - } - g.reopen() - if err := g.owner.assembly.eventRegistry.Replace(calendar); err != nil { - t.Fatal(err) - } - if !bytes.Equal(firstAfter, g.info(schedule.UID)) || len(puzzleNumbers(t, g.info(second.UID), 4)) != 1 { - t.Fatal("SQLite restart merged independent puzzle schedule progress") - } -} diff --git a/go/internal/server/app/quest_replay_integration_test.go b/go/internal/server/app/quest_replay_integration_test.go new file mode 100644 index 0000000..44c2786 --- /dev/null +++ b/go/internal/server/app/quest_replay_integration_test.go @@ -0,0 +1,156 @@ +//go:build integration + +package app + +import ( + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/world/progress" + "bd2server/internal/server/runtime/player" + "context" + "fmt" + "maps" + "testing" +) + +// QuestReplayPopupUI accepts PackTable main quest 1 with is_retry once hard (2) +// is complete; QuestPopupUI hides rewards while QuestPacket replaces the active +// quest with QuestRetryDBInfo from accept/clear/give-up and PackInfo field 7. +func TestMainQuestReplayTracksProgressWithoutRewardsAndRestoresSelection(t *testing.T) { + factory, accounts := newIntegrationFactory(t) + mainQuests := factory.design.world.Story.Packs[1].MainQuestIDs + owner, err := factory.open(accounts[0]) + if err != nil { + t.Fatal(err) + } + tx, err := owner.repository.BeginCommand(context.Background()) + if err != nil { + t.Fatal(err) + } + ctx := command.Context{Identity: command.Identity{AccountID: accounts[0], SessionID: "fixture"}, State: tx} + state := owner.assembly.progressState + for difficulty := 0; difficulty <= 2; difficulty++ { + for _, id := range mainQuests { + if err := state.ClearQuest(ctx, id, 1, difficulty); err != nil { + t.Fatal(err) + } + } + } + completed := progress.QuestSelection{Difficulty: 2} + if err := state.SelectQuest(ctx, 1, completed); err != nil { + t.Fatal(err) + } + if err := tx.Commit(); err != nil { + t.Fatal(err) + } + if err := owner.Recover(context.Background()); err != nil { + t.Fatal(err) + } + runtime, err := player.New(accounts[0], owner, player.Limits{CompletedReceipts: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := runtime.Close(context.Background()); err != nil { + t.Error(err) + } + }) + seq := uint64(0) + request := func(path string, fields ...uint64) player.Command { + seq++ + body := appScalar(1, seq) + for i := 0; i+1 < len(fields); i += 2 { + body = append(body, appScalar(int(fields[i]), fields[i+1])...) + } + c := registryCommand(accounts[0], fmt.Sprintf("replay-%d%s", seq, path), path, body) + c.Identity.SessionID = "replay" + return c + } + run := func(path string, fields ...uint64) []byte { + t.Helper() + return registryExecute(t, runtime, request(path, fields...)).Responses[0].Body + } + rejected := func(path string, fields ...uint64) { + t.Helper() + future, err := runtime.Submit(context.Background(), request(path, fields...)) + if err != nil { + t.Fatal(err) + } + if _, err := future.Wait(context.Background()); err == nil { + t.Fatalf("%s %v was accepted", path, fields) + } + } + packReplay := func() (retrying bool, replays [][]byte) { + t.Helper() + info := run("/PackInfo") + for _, row := range appRows(info, 1) { + if appValue(row, 1) == 1 { + retrying = appValue(row, 9) == 1 + } + } + return retrying, appRows(info, 7) + } + if retrying, replays := packReplay(); retrying || len(replays) != 0 { + t.Fatal("a pack without a replay reported one") + } + first, second := uint64(mainQuests[0]), uint64(mainQuests[1]) + rejected("/QuestAccept", 2, second, 3, 1, 4, 1, 6, 1) + accepted := appRows(run("/QuestAccept", 2, first, 3, 1, 4, 1, 6, 1, 7, 1), 5) + if len(accepted) != 1 || appValue(accepted[0], 1) != 1 || appValue(accepted[0], 2) != 1 || appValue(accepted[0], 3) != first || appValue(accepted[0], 6) != 1 { + t.Fatalf("accept did not start a hard replay with battle skip: %x", accepted) + } + run("/QuestUpdate", 2, first, 3, 1, 4, 3) + run("/QuestRetryBattleSkipSave", 2, 1, 3, 0) + retrying, replays := packReplay() + if !retrying || len(replays) != 1 || appValue(replays[0], 3) != first || appValue(replays[0], 5) != 3 || appValue(replays[0], 6) != 0 { + t.Fatalf("relogin lost replay progress or battle skip toggle: retry=%v %x", retrying, replays) + } + continued := appRows(run("/QuestAccept", 2, first, 3, 1, 4, 1, 6, 1), 5) + if len(continued) != 1 || appValue(continued[0], 5) != 3 { + t.Fatalf("continuing the replay discarded its progress: %x", continued) + } + + gold := owner.assembly.wallet.Snapshot(command.Context{}).Gold + items := appItemTotals(run("/ItemInfo")) + clear := run("/QuestClear", 2, first, 3, 1) + next := appRows(clear, 16) + if len(appRows(clear, 1)) != 1 || len(appRows(clear, 1)[0]) != 0 || len(next) != 1 || appValue(next[0], 3) != second || appValue(next[0], 2) != 1 { + t.Fatalf("replay clear paid rewards or did not advance: %x", clear) + } + if owner.assembly.wallet.Snapshot(command.Context{}).Gold != gold || !maps.Equal(appItemTotals(run("/ItemInfo")), items) { + t.Fatal("replay clear changed owned rewards") + } + rejected("/QuestClear", 2, first, 3, 1) + + ended := appRows(run("/QuestGiveUp", 2, second, 3, 1), 5) + if len(ended) != 1 || appValue(ended[0], 1) != 1 || appValue(ended[0], 3) != 0 { + t.Fatalf("give up did not end the client replay: %x", ended) + } + if retrying, replays := packReplay(); retrying || len(replays) != 0 { + t.Fatal("abandoned replay survived") + } + if selection, _ := state.Selection(1); selection != completed { + t.Fatalf("give up left replay selection %+v", selection) + } + rejected("/QuestRetryBattleSkipSave", 2, 1, 3, 1) + + run("/QuestAccept", 2, first, 3, 1, 6, 1) + quest := first + for range mainQuests { + retry := appRows(run("/QuestClear", 2, quest, 3, 1), 16) + if len(retry) != 1 { + t.Fatalf("replay clear of quest %d omitted QuestRetryInfo", quest) + } + if quest = appValue(retry[0], 3); quest == 0 { + break + } + } + if quest != 0 { + t.Fatal("replay did not end after the final main quest") + } + if retrying, replays := packReplay(); retrying || len(replays) != 0 { + t.Fatal("finished replay survived") + } + if selection, _ := state.Selection(1); selection != completed { + t.Fatalf("finished replay left selection %+v", selection) + } +} diff --git a/go/internal/server/app/realtime_profiles.go b/go/internal/server/app/realtime_profiles.go index 7ae6432..bb769bc 100644 --- a/go/internal/server/app/realtime_profiles.go +++ b/go/internal/server/app/realtime_profiles.go @@ -126,5 +126,11 @@ func (p *playerAssembly) roomProfile(ctx command.Context) ([]byte, error) { use = wire.AppendVarint(use, index+3, value) } fish := p.fishingService.Profile() - return json.Marshal(room.Profile{UserInfo: user, AvatarUseInfo: use, RodID: int64(fish.RodID), BoatLevel: int64(fish.BoatLevel), BoatSkinID: int64(fish.BoatSkinID), FishingMaps: fish.Maps}) + var motions []uint64 + for _, item := range p.ownedItems.All(ctx) { + if item.Type == 50 && item.Count > 0 { + motions = append(motions, item.ID) + } + } + return json.Marshal(room.Profile{UserInfo: user, AvatarUseInfo: use, AvatarMotions: motions, SquareUnlocked: p.worldService.CanEnterFieldPackType(ctx, 11), RodID: int64(fish.RodID), BoatLevel: int64(fish.BoatLevel), BoatSkinID: int64(fish.BoatSkinID), FishingMaps: fish.Maps}) } diff --git a/go/internal/server/app/realtime_runtime.go b/go/internal/server/app/realtime_runtime.go index fc8a02c..080aab9 100644 --- a/go/internal/server/app/realtime_runtime.go +++ b/go/internal/server/app/realtime_runtime.go @@ -35,6 +35,7 @@ func openRealtime(c *configuration, registry *playerRegistry, game *session.Serv results.endpoints = []eventplay.RelayEndpoint{{Region: "1", Host: config.PublicHost, TCPPort: strconv.Itoa(config.TCPPort)}} var transport atomic.Pointer[realtime.Server] rooms, err := room.New(room.Config{AdvertisedHost: config.PublicHost, TCPPort: config.TCPPort, UDPPort: config.UDPPort, + SquareChannels: int(registry.factory.design.avatarProfile.SquareChannels), SquareChannelCapacity: int(registry.factory.design.avatarProfile.SquareChannelCapacity), Publish: func(frames []room.Delivery) { if server := transport.Load(); server != nil { server.Deliver(frames) diff --git a/go/internal/server/app/realtime_tickets.go b/go/internal/server/app/realtime_tickets.go index 102a40d..c969d8b 100644 --- a/go/internal/server/app/realtime_tickets.go +++ b/go/internal/server/app/realtime_tickets.go @@ -70,7 +70,7 @@ func (t *realtimeTickets) ServeHTTP(w http.ResponseWriter, r *http.Request) { http.Error(w, "invalid ticket request", http.StatusBadRequest) return } - if request.Channel != room.Matching && request.Channel != room.Action && request.Channel != room.Defense && request.Channel != room.Fishing { + if request.Channel != room.Matching && request.Channel != room.Action && request.Channel != room.Defense && request.Channel != room.Fishing && request.Channel != room.Square { http.Error(w, "invalid channel", http.StatusBadRequest) return } @@ -182,3 +182,7 @@ func (t *realtimeTickets) Consume(ctx context.Context, token, channel, instance func (t *realtimeTickets) Validate(ctx context.Context, p room.Principal) error { return t.game.ValidatePrincipal(ctx, session.Principal{AccountID: p.AccountID, SessionID: p.SessionID, Generation: p.Generation}) } + +func (t *realtimeTickets) RecordActivity(p room.Principal) { + t.game.RecordActivity(session.Principal{AccountID: p.AccountID, SessionID: p.SessionID, Generation: p.Generation}) +} diff --git a/go/internal/server/app/reward_state_integration_test.go b/go/internal/server/app/reward_state_integration_test.go index 7738639..94605d7 100644 --- a/go/internal/server/app/reward_state_integration_test.go +++ b/go/internal/server/app/reward_state_integration_test.go @@ -17,7 +17,9 @@ import ( func TestCostumeOverflowPaysCompensationWithoutRepeatingCollectionNotice(t *testing.T) { factory, accounts := newIntegrationFactory(t) - for _, scenario := range []struct { + // Each scenario owns its account: trap commands restart their request IDs, + // so sharing one account would replay the previous scenario's receipts. + for i, scenario := range []struct { name string costume uint64 goldThreadPerCopy uint64 @@ -26,7 +28,7 @@ func TestCostumeOverflowPaysCompensationWithoutRepeatingCollectionNotice(t *test {"earned", 1401, 2}, } { t.Run(scenario.name, func(t *testing.T) { - s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])} + s := &trapPlayerScenario{factory: factory, account: accounts[i], owner: openNicknamePlayer(t, factory, accounts[i])} t.Cleanup(func() { closeNicknamePlayer(t, s.owner) }) grant := func(key string, count uint64) []byte { t.Helper() @@ -114,7 +116,7 @@ func TestCommunityRewardCreditsOnceAndRestoresPerAccountClaims(t *testing.T) { displayed += appValue(reward, 4) } } - // CommunityWebLinkTable 0 in GameData 20261012190548 advertises 100 free diamonds. + // CommunityWebLinkTable 0 in GameData 20261021182514 advertises 100 free diamonds. if displayed != 100 || a.owner.assembly.wallet.Snapshot(command.Context{}).FreeJewelry != before+100 { t.Fatal("community reward shown by the client was not credited to spendable diamonds") } diff --git a/go/internal/server/app/room_social_integration_test.go b/go/internal/server/app/room_social_integration_test.go index 5f03652..d6c768a 100644 --- a/go/internal/server/app/room_social_integration_test.go +++ b/go/internal/server/app/room_social_integration_test.go @@ -20,11 +20,11 @@ func TestNativeRoomVisitPrivacyOwnedLayoutAndPopularityAreDurable(t *testing.T) if err != nil { t.Fatal(err) } - if _, err := actor.assembly.collection.GrantCostumes(command.Context{State: tx}, "room-costume-fixture", []uint64{101}, factory.design.rewardCostumes); err != nil { + if _, err := actor.assembly.collection.GrantCostumes(command.Context{State: tx, InstanceIDs: factory.instanceIDs()}, "room-costume-fixture", []uint64{101}, factory.design.rewardCostumes); err != nil { _ = tx.Rollback() t.Fatal(err) } - items, err := actor.assembly.ownedItems.GrantOnce(command.Context{State: tx}, "room-decoration-fixture", []gamedata.BattleReward{{Type: 27, ID: 101, Count: 1}}) + items, err := actor.assembly.ownedItems.GrantOnce(command.Context{State: tx, InstanceIDs: factory.instanceIDs()}, "room-decoration-fixture", []gamedata.BattleReward{{Type: 27, ID: 101, Count: 1}}) if err != nil { _ = tx.Rollback() t.Fatal(err) diff --git a/go/internal/server/app/seed_instances.go b/go/internal/server/app/seed_instances.go new file mode 100644 index 0000000..8223e06 --- /dev/null +++ b/go/internal/server/app/seed_instances.go @@ -0,0 +1,178 @@ +package app + +import ( + "encoding/json" + "errors" + "fmt" + + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/roster" + "bd2server/internal/server/storage/stateio" +) + +type seedInstanceIDs struct { + Characters map[uint64]uint64 `json:"characters"` + Costumes map[uint64]uint64 `json:"costumes"` + Items map[uint64]uint64 `json:"items"` +} + +func (p *playerAssembly) seedInstances(ctx command.Context) error { + raw, found, err := ctx.State.LoadEntry("bootstrap", "instances", "seeds") + if err != nil { + return err + } + ids := seedInstanceIDs{Characters: map[uint64]uint64{}, Costumes: map[uint64]uint64{}, Items: map[uint64]uint64{}} + if found { + if err := stateio.RequireExactJSONObject(raw, "characters", "costumes", "items"); err != nil { + return err + } + if err := json.Unmarshal(raw, &ids); err != nil { + return err + } + if ids.Characters == nil || ids.Costumes == nil || ids.Items == nil { + return errors.New("account seed: invalid instance mapping") + } + } else if !p.initializeAccount { + return errors.New("account seed: global instance mapping missing; offline migration required") + } + register := func(values map[uint64]uint64, old, class uint64) error { + if old == 0 { + return nil + } + if id, exists := values[old]; exists { + if id&(roster.CharmCharacterIndexBase-1) == 0 || id&^(roster.CharmCharacterIndexBase-1) != class { + return fmt.Errorf("account seed: invalid instance %d", old) + } + return nil + } + if found { + return fmt.Errorf("account seed: unmapped instance %d", old) + } + id, err := ctx.NewInstanceID() + if err != nil { + return err + } + values[old] = id | class + return nil + } + for _, character := range p.starter.Characters { + if err := register(ids.Characters, character.InvenIndex, 0); err != nil { + return err + } + } + if err := register(ids.Characters, p.worldSeed.RewardCharacter.InvenIndex, 0); err != nil { + return err + } + for _, character := range p.worldSeed.StoryCharacters { + if err := register(ids.Characters, character.InvenIndex, roster.StoryCharacterIndexBase); err != nil { + return err + } + } + for _, costume := range p.starter.Costumes { + if err := register(ids.Costumes, costume.InvenIndex, 0); err != nil { + return err + } + } + if err := register(ids.Costumes, p.worldSeed.RewardCostume.InvenIndex, 0); err != nil { + return err + } + for _, item := range p.starter.Items { + if err := register(ids.Items, item.InvenIndex, 0); err != nil { + return err + } + } + for _, item := range p.starter.OwnedItems { + if err := register(ids.Items, item.InvenIndex, 0); err != nil { + return err + } + } + seen := make(map[uint64]bool) + for _, values := range []map[uint64]uint64{ids.Characters, ids.Costumes, ids.Items} { + for _, id := range values { + if seen[id] { + return fmt.Errorf("account seed: duplicate instance %d", id) + } + seen[id] = true + } + } + if !found { + raw, err = json.Marshal(ids) + if err != nil { + return err + } + if err := ctx.State.PutEntry("bootstrap", "instances", "seeds", raw); err != nil { + return err + } + } + remap := func(values map[uint64]uint64, old uint64) (uint64, error) { + if old == 0 { + return 0, nil + } + id, exists := values[old] + if !exists || id == 0 { + return 0, fmt.Errorf("account seed: unresolved instance reference %d", old) + } + return id, nil + } + character := func(value *roster.Character) error { + value.InvenIndex, err = remap(ids.Characters, value.InvenIndex) + if err != nil { + return err + } + value.UseCostume, err = remap(ids.Costumes, value.UseCostume) + return err + } + costume := func(value *roster.Costume) error { + value.InvenIndex, err = remap(ids.Costumes, value.InvenIndex) + if err != nil { + return err + } + value.UseChar, err = remap(ids.Characters, value.UseChar) + return err + } + for i := range p.starter.Characters { + if err := character(&p.starter.Characters[i]); err != nil { + return err + } + } + if err := character(&p.worldSeed.RewardCharacter); err != nil { + return err + } + for i := range p.worldSeed.StoryCharacters { + if err := character(&p.worldSeed.StoryCharacters[i]); err != nil { + return err + } + } + for i := range p.starter.Costumes { + if err := costume(&p.starter.Costumes[i]); err != nil { + return err + } + } + if err := costume(&p.worldSeed.RewardCostume); err != nil { + return err + } + for i := range p.starter.Items { + p.starter.Items[i].InvenIndex, err = remap(ids.Items, p.starter.Items[i].InvenIndex) + if err != nil { + return err + } + } + for i := range p.starter.OwnedItems { + p.starter.OwnedItems[i].InvenIndex, err = remap(ids.Items, p.starter.OwnedItems[i].InvenIndex) + if err != nil { + return err + } + } + for i := range p.deckSeed.FieldDeck { + entry := &p.deckSeed.FieldDeck[i] + entry.CharacterInvenIndex, err = remap(ids.Characters, entry.CharacterInvenIndex) + if err != nil { + return err + } + entry.CostumeInvenIndex, err = remap(ids.Costumes, entry.CostumeInvenIndex) + if err != nil { + return err + } + } + return nil +} diff --git a/go/internal/server/app/seeds.go b/go/internal/server/app/seeds.go index eb4f134..fde08b2 100644 --- a/go/internal/server/app/seeds.go +++ b/go/internal/server/app/seeds.go @@ -1,23 +1,35 @@ package app import ( + commonconfig "bd2server/internal/common/config" "bd2server/internal/server/domain/mail" "bd2server/internal/server/domain/roster" "bd2server/internal/server/domain/roster/deck" + "bd2server/internal/server/domain/startergift" "bd2server/internal/server/domain/world" calendaradapter "bd2server/internal/server/protocol/calendar" loginprotocol "bd2server/internal/server/protocol/login" "bd2server/internal/server/protocol/staticdata" "encoding/json" + "fmt" + "path/filepath" ) +type cashPackageLayouts struct { + Version string `json:"version"` + BundleVersion string `json:"bundle_version"` + Layouts map[string]string `json:"layouts"` +} + type seedCatalog struct { - login *loginprotocol.LoginSeed - starter *roster.Starter - defaults *readonly.Seed - mailbox *mail.Starter - deck deck.Seed - world world.Seed + login *loginprotocol.LoginSeed + starter *roster.Starter + defaults *readonly.Seed + mailbox *mail.Starter + deck deck.Seed + world world.Seed + packageLayouts cashPackageLayouts + starterGifts startergift.Catalog } func loadSeeds(c *configuration) (*seedCatalog, error) { @@ -52,7 +64,29 @@ func loadSeeds(c *configuration) (*seedCatalog, error) { if err != nil { return nil, err } - return &seedCatalog{login: login, starter: starter, defaults: defaults, mailbox: mailbox, deck: deckSeed, world: worldSeed}, nil + layouts, err := commonconfig.Load(filepath.Join(filepath.Dir(c.worldSeed), "cash_package_layouts.json"), cashPackageLayouts{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true}) + if err != nil { + return nil, fmt.Errorf("load cash package layouts: %w", err) + } + if layouts.Version != c.versions.GameVersion { + return nil, fmt.Errorf("cash package layout game version mismatch: got %s, want %s", layouts.Version, c.versions.GameVersion) + } + if layouts.BundleVersion != c.versions.BundleVersion { + return nil, fmt.Errorf("cash package layout bundle version mismatch: got %s, want %s", layouts.BundleVersion, c.versions.BundleVersion) + } + for resource, layout := range layouts.Layouts { + if resource == "" || layout != "independent" && layout != "relay" { + return nil, fmt.Errorf("invalid cash package layout %q: %q", resource, layout) + } + } + gifts, err := commonconfig.Load(filepath.Join(filepath.Dir(c.worldSeed), "starter_gifts.json"), startergift.Catalog{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true}) + if err != nil { + return nil, fmt.Errorf("load starter gifts: %w", err) + } + if gifts.Version != c.versions.GameVersion || gifts.GameDataVersion != c.gameDataVersion { + return nil, fmt.Errorf("starter gift game or GameData version mismatch") + } + return &seedCatalog{login: login, starter: starter, defaults: defaults, mailbox: mailbox, deck: deckSeed, world: worldSeed, packageLayouts: layouts, starterGifts: gifts}, nil } func cloneSeed[T any](source *T) (*T, error) { diff --git a/go/internal/server/app/serve.go b/go/internal/server/app/serve.go index 4f16777..073823a 100644 --- a/go/internal/server/app/serve.go +++ b/go/internal/server/app/serve.go @@ -102,6 +102,7 @@ func Serve(args []string) (serveErr error) { if err != nil { return err } + shared.friends.AttachPresence(game.AccountOnline) var authHandler http.Handler if authService != nil { diff --git a/go/internal/server/app/shared_colosseum_cost.go b/go/internal/server/app/shared_colosseum_cost.go new file mode 100644 index 0000000..54199b6 --- /dev/null +++ b/go/internal/server/app/shared_colosseum_cost.go @@ -0,0 +1,156 @@ +package app + +import ( + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/battle/pvp" + "bd2server/internal/server/protocol/wire" + "bd2server/internal/server/storage/shared" + "encoding/json" + "fmt" + "slices" + "strconv" + "strings" +) + +// Colosseum costume costs (LocalText 40030034): costumes used by attackers of +// Diamond III to Champion during the previous season are ranked by usage, and +// ColosseumDefaultTable prices each rank bracket. The tally is per season. + +const colosseumBattleTotal = "total" + +func colosseumPopularityPrefix(season uint64) string { + return fmt.Sprintf("colosseum:%020d:", season) +} + +type colosseumCostume struct { + ID, Count, Rank, Cost uint64 +} + +// colosseumCostTable is one previous-season tally; costumes absent from it use +// ColosseumDefaults.CostDefault. +type colosseumCostTable struct { + Battles uint64 + Costumes []colosseumCostume +} + +func (t colosseumCostTable) cost(defaults gamedata.ColosseumDefaults, costume uint64) uint64 { + for _, row := range t.Costumes { + if row.ID == costume { + return row.Cost + } + } + return defaults.CostDefault +} + +func (s *sharedRuntime) applyColosseumPopularity(tx *shared.Tx, battle pvp.BattleSettled) error { + attacker := battle.Attacker + if attacker.Rank == 0 { + return nil + } + rank, err := s.pvpDesign.ColosseumRank(battle.Season, attacker.TopPercent) + if err != nil { + return err + } + if rank.RankGroup == 0 || rank.RankGroup > s.pvpDesign.Colosseum.PopularCostumeMinimumRankGroup { + return nil + } + prefix := colosseumPopularityPrefix(battle.Season) + used := map[uint64]bool{} + if err = wire.Walk(attacker.Snapshot.FullDeck, func(f wire.Field) error { + if f.Number != 2 { + return nil + } + // FullDeck field 2 is the deck character with its selected costume id. + costume, _, err := wire.Varint(f.Value, 5) + if err != nil || costume == 0 { + return fmt.Errorf("invalid colosseum deck costume") + } + used[costume] = true + return nil + }); err != nil { + return err + } + if len(used) == 0 { + return fmt.Errorf("colosseum battle without deck costumes") + } + for costume := range used { + if err = popularityCount(tx, "popularity_counts", prefix+fmt.Sprintf("%010d", costume), 1); err != nil { + return err + } + } + return popularityCount(tx, "popularity_counts", prefix+colosseumBattleTotal, 1) +} + +// previousColosseumSeason is the latest colosseum season already ended at. +func (s *sharedRuntime) previousColosseumSeason(at uint64) (uint64, bool) { + var best pvp.Season + for _, season := range s.pvpSeasons { + if season.Mode == pvp.Colosseum && season.End <= at && season.End > best.End { + best = season + } + } + return best.ID, best.ID != 0 +} + +func (s *sharedRuntime) colosseumCosts(tx *shared.Tx, at uint64) (colosseumCostTable, error) { + var table colosseumCostTable + season, found := s.previousColosseumSeason(at) + if !found { + return table, nil + } + prefix := colosseumPopularityPrefix(season) + if err := scanPopularity(tx, "popularity_counts", prefix, func(row shared.Entry) error { + var count uint64 + if json.Unmarshal(row.Value, &count) != nil || count == 0 { + return fmt.Errorf("invalid colosseum popularity") + } + key := strings.TrimPrefix(row.Key, prefix) + if key == colosseumBattleTotal { + table.Battles = count + return nil + } + id, err := strconv.ParseUint(key, 10, 64) + if err != nil || id == 0 { + return fmt.Errorf("invalid colosseum popularity key") + } + table.Costumes = append(table.Costumes, colosseumCostume{ID: id, Count: count}) + return nil + }); err != nil { + return table, err + } + slices.SortFunc(table.Costumes, func(a, b colosseumCostume) int { + if a.Count != b.Count { + if a.Count > b.Count { + return -1 + } + return 1 + } + if a.ID < b.ID { + return -1 + } + return 1 + }) + for i := range table.Costumes { + table.Costumes[i].Rank = uint64(i + 1) + table.Costumes[i].Cost = s.pvpDesign.Colosseum.CostumeCost(table.Costumes[i].Rank) + } + return table, nil +} + +// colosseumPopularityBody encodes PopularCostumeInfoResponse for PCC_COLOSSEUM: +// count_type0 is the previous season, which the client shows beside the cost. +func colosseumPopularityBody(table colosseumCostTable) []byte { + var body []byte + for _, row := range table.Costumes { + b := wire.AppendVarint(nil, 1, row.ID) + b = wire.AppendVarint(b, 2, row.Count) + b = wire.AppendVarint(b, 5, row.Rank) + b = wire.AppendVarint(b, 6, row.Cost) + body = wire.AppendBytes(body, 1, b) + } + var total []byte + if table.Battles != 0 { + total = wire.AppendVarint(nil, 2, table.Battles) + } + return wire.AppendBytes(body, 2, total) +} diff --git a/go/internal/server/app/shared_colosseum_cost_test.go b/go/internal/server/app/shared_colosseum_cost_test.go new file mode 100644 index 0000000..ff19a5d --- /dev/null +++ b/go/internal/server/app/shared_colosseum_cost_test.go @@ -0,0 +1,129 @@ +package app + +import ( + "context" + "testing" + "time" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/battle/pvp" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/protocol/wire" + "bd2server/internal/server/storage/shared" +) + +// Values from GameData 20261021182514 via gamedata_db.py: ColosseumDefaultTable +// costDefault 30, rank boundaries 5/10/15/20 cost 50/45/40/35, +// popularCostumeMinRankGroupId 6; ColosseumRankTable group 1 places Champion +// (rankGroup 1) at top 0.1% and Diamond III (rankGroup 6) at top 30%, Ruby I +// (rankGroup 7) at top 35%. +func colosseumCostFixture(t *testing.T) *sharedRuntime { + t.Helper() + store, err := shared.Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := store.Close(); err != nil { + t.Error(err) + } + }) + design := &gamedata.PvpDesign{ + Colosseum: gamedata.ColosseumDefaults{CostDefault: 30, CostRankBoundaries: [4]uint64{5, 10, 15, 20}, CostRankValues: [4]uint64{50, 45, 40, 35}, PopularCostumeMinimumRankGroup: 6}, + ColosseumRankGroups: map[uint64]uint64{47: 1, 48: 1}, + ColosseumRanks: map[uint64][]gamedata.ColosseumRank{1: { + {Group: 1, ID: 1, RankGroup: 1, TopPercent: 0.1}, + {Group: 1, ID: 16, RankGroup: 6, TopPercent: 30}, + {Group: 1, ID: 17, RankGroup: 7, TopPercent: 35}, + }}, + } + seasons := []pvp.Season{{Mode: pvp.Colosseum, ID: 47, Start: 1000, End: 2000}, {Mode: pvp.Colosseum, ID: 48, Start: 2000, End: 3000}, {Mode: pvp.Mirror, ID: 9, Start: 0, End: 2500}} + return &sharedRuntime{store: store, statistics: &gamedata.CollectionStatisticsDesign{}, pvpDesign: design, pvpSeasons: seasons} +} + +func colosseumAttack(season, rank uint64, percent float64, costumes ...uint64) pvp.BattleSettled { + var deck []byte + for _, costume := range costumes { + deck = wire.AppendBytes(deck, 2, wire.AppendVarint(nil, 5, costume)) + } + attacker := pvp.PublishedSnapshot{Mode: pvp.Colosseum, Season: season, Rank: rank, TopPercent: percent, Snapshot: pvp.FullSnapshot{FullDeck: deck}} + return pvp.BattleSettled{Mode: pvp.Colosseum, Season: season, Attacker: attacker} +} + +func TestColosseumCostsRankPreviousSeasonDiamondAttackers(t *testing.T) { + s := colosseumCostFixture(t) + battles := []pvp.BattleSettled{ + colosseumAttack(47, 1, 0.1, 101, 102), + colosseumAttack(47, 40, 30, 102, 103), + colosseumAttack(47, 41, 30, 102), + colosseumAttack(47, 90, 35, 104, 104), + colosseumAttack(47, 0, 0, 105), + colosseumAttack(48, 1, 0.1, 106), + } + for i := range 20 { + battles = append(battles, colosseumAttack(47, 2, 0.1, 200+uint64(i))) + } + if err := s.store.Update(context.Background(), func(tx *shared.Tx) error { + for _, battle := range battles { + if err := s.applyColosseumPopularity(tx, battle); err != nil { + return err + } + } + return nil + }); err != nil { + t.Fatal(err) + } + var during, after colosseumCostTable + if err := s.store.View(context.Background(), func(tx *shared.Tx) error { + var err error + if during, err = s.colosseumCosts(tx, 2500); err != nil { + return err + } + after, err = s.colosseumCosts(tx, 3000) + return err + }); err != nil { + t.Fatal(err) + } + if during.Battles != 23 || len(during.Costumes) != 23 { + t.Fatalf("season 47 tally counted ineligible or other-season battles: %+v", during) + } + want := map[uint64][2]uint64{102: {3, 1}, 101: {1, 2}, 103: {1, 3}, 200: {1, 4}, 201: {1, 5}, 202: {1, 6}, 216: {1, 20}, 217: {1, 21}} + for _, row := range during.Costumes { + if expected, checked := want[row.ID]; checked && (row.Count != expected[0] || row.Rank != expected[1]) { + t.Fatalf("costume %d count/rank %d/%d, want %v", row.ID, row.Count, row.Rank, expected) + } + } + defaults := s.pvpDesign.Colosseum + for costume, cost := range map[uint64]uint64{102: 50, 201: 50, 202: 45, 216: 35, 217: 30, 104: 30, 105: 30} { + if got := during.cost(defaults, costume); got != cost { + t.Fatalf("costume %d costs %d, want %d", costume, got, cost) + } + } + if after.Battles != 1 || len(after.Costumes) != 1 || after.Costumes[0].ID != 106 { + t.Fatalf("season 48 did not become the previous season: %+v", after) + } + + _, body, err := s.popularInfo(command.Context{}, "/PopularCostumeInfo", wire.AppendVarint(wire.AppendVarint(nil, 1, 1), 2, 6), time.UnixMilli(2500)) + if err != nil { + t.Fatal(err) + } + var rows, totals [][]byte + if err := wire.Walk(body, func(f wire.Field) error { + switch f.Number { + case 1: + rows = append(rows, f.Value) + case 2: + totals = append(totals, f.Value) + } + return nil + }); err != nil { + t.Fatal(err) + } + field := func(raw []byte, number int) uint64 { + v, _, _ := wire.Varint(raw, number) + return v + } + if len(rows) != 23 || len(totals) != 1 || field(totals[0], 2) != 23 || field(rows[0], 1) != 102 || field(rows[0], 2) != 3 || field(rows[0], 5) != 1 || field(rows[0], 6) != 50 { + t.Fatalf("PCC_COLOSSEUM response: %x", body) + } +} diff --git a/go/internal/server/app/shared_gameplay_integration_test.go b/go/internal/server/app/shared_gameplay_integration_test.go index bbcf99a..75498b8 100644 --- a/go/internal/server/app/shared_gameplay_integration_test.go +++ b/go/internal/server/app/shared_gameplay_integration_test.go @@ -161,7 +161,7 @@ func seedGuildQualification(t *testing.T, owner *playerInstance) { t.Error(err) } }() - c := command.Context{Identity: command.Identity{AccountID: owner.accountID}, State: tx} + c := command.Context{Identity: command.Identity{AccountID: owner.accountID}, State: tx, InstanceIDs: owner.factory.instanceIDs()} rule := owner.factory.design.guild.Open grant := owner.factory.design.guild.Guild.CreateCost grant.Count *= 4 @@ -578,6 +578,38 @@ func (g *guildGameplay) ownedPVPDeck() ([]byte, uint64) { } func TestNativePVPGameplayUsesOwnedSnapshotsAndTickets(t *testing.T) { factory, accounts := newIntegrationFactory(t) + // Mirror seasons are calendar-driven and may be between rotations. Use an + // already-active season when the captured calendar has one; otherwise keep + // a single Mirror season and move its window to now so it cannot overlap. + now := time.Now() + nowMS := uint64(now.UnixMilli()) + active := false + var kept pvp.Season + found := false + seasons := make([]pvp.Season, 0, len(factory.design.pvp.Seasons)) + for _, season := range factory.design.pvp.Seasons { + if season.Mode != pvp.Mirror { + seasons = append(seasons, season) + continue + } + active = active || season.Start <= nowMS && nowMS < season.End + kept, found = season, true + } + if !found { + t.Fatal("GameData has no Mirror season") + } + if !active { + kept.Start = nowMS - uint64(time.Hour/time.Millisecond) + kept.End = nowMS + uint64(time.Hour/time.Millisecond) + kept.CalculateEnd = kept.End + factory.options.calendars.RegularService.CalculateMilliseconds + seasons = append(seasons, kept) + factory.design.pvp.Seasons = seasons + rules, err := pvp.NewRules(factory.design.pvp.Design, factory.design.pvp.Seasons, factory.design.pvp.Policy) + if err != nil { + t.Fatal(err) + } + factory.design.pvp = rules + } state, err := openSharedRuntime(context.Background(), factory.options, factory.design) if err != nil { t.Fatal(err) diff --git a/go/internal/server/app/shared_popularity.go b/go/internal/server/app/shared_popularity.go index ec1add8..25d22ba 100644 --- a/go/internal/server/app/shared_popularity.go +++ b/go/internal/server/app/shared_popularity.go @@ -375,7 +375,7 @@ func (s *sharedRuntime) popularInfo(ctx command.Context, path string, raw []byte if s.statistics == nil { return code, nil, fmt.Errorf("missing popularity design") } - if path == "/PopularCostumeInfo" && (v[2] > 5 || v[3] > 1 || v[4] > 4) { + if path == "/PopularCostumeInfo" && (v[2] > 6 || v[3] > 1 || v[4] > 4) { return code, nil, fmt.Errorf("invalid popularity filter") } if path == "/PopularEquipInfo" { @@ -393,6 +393,11 @@ func (s *sharedRuntime) popularInfo(ctx command.Context, path string, raw []byte } var body []byte e = s.store.View(cancel, func(tx *shared.Tx) error { + if path == "/PopularCostumeInfo" && v[2] == 6 { + table, e := s.colosseumCosts(tx, uint64(now.UnixMilli())) + body = colosseumPopularityBody(table) + return e + } if path == "/PopularEquipInfo" { prefix := fmt.Sprintf("equip:%010d:", v[2]) type winner struct{ id, count uint64 } diff --git a/go/internal/server/app/shared_pvp.go b/go/internal/server/app/shared_pvp.go index cd3601b..58c3724 100644 --- a/go/internal/server/app/shared_pvp.go +++ b/go/internal/server/app/shared_pvp.go @@ -47,6 +47,11 @@ func (s *sharedRuntime) consumePVP(ctx context.Context, event outbox.Pending) er if e := json.Unmarshal(event.Envelope.Event.Payload, &battle); e != nil { return e } + if battle.Mode == pvp.Colosseum { + return s.store.Consume(ctx, event, func(tx *shared.Tx, envelope outbox.Envelope) error { + return s.applyColosseumPopularity(tx, battle) + }) + } if battle.Mode != pvp.Mirror { return nil } diff --git a/go/internal/server/app/shared_runtime.go b/go/internal/server/app/shared_runtime.go index ba1cd16..c316c09 100644 --- a/go/internal/server/app/shared_runtime.go +++ b/go/internal/server/app/shared_runtime.go @@ -12,6 +12,7 @@ import ( "time" "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/battle/pvp" "bd2server/internal/server/domain/ranking" "bd2server/internal/server/domain/social" "bd2server/internal/server/runtime/delivery" @@ -26,6 +27,8 @@ type sharedRuntime struct { rooms *roomResults store *shared.Store pvp *ranking.PVP + pvpDesign *gamedata.PvpDesign + pvpSeasons []pvp.Season huntRanks *ranking.MonsterHunt castleRanks *ranking.Castle rogueRanks *ranking.RogueLike @@ -78,7 +81,7 @@ func openSharedRuntime(ctx context.Context, c *configuration, design *designCata if err != nil { return nil, errors.Join(err, store.Close()) } - return &sharedRuntime{statistics: design.collectionStatistics, store: store, pvp: pvp, huntRanks: huntRanks, castleRanks: castleRanks, rogueRanks: rogueRanks, arcadeRanks: arcadeRanks, guild: guild, friends: friends, rooms: rooms, directory: directory}, nil + return &sharedRuntime{statistics: design.collectionStatistics, store: store, pvp: pvp, pvpDesign: design.pvp.Design, pvpSeasons: design.pvp.Seasons, huntRanks: huntRanks, castleRanks: castleRanks, rogueRanks: rogueRanks, arcadeRanks: arcadeRanks, guild: guild, friends: friends, rooms: rooms, directory: directory}, nil } func (s *sharedRuntime) wake(account string) { diff --git a/go/internal/server/app/skyway_integration_test.go b/go/internal/server/app/skyway_integration_test.go index c7726ac..9653d25 100644 --- a/go/internal/server/app/skyway_integration_test.go +++ b/go/internal/server/app/skyway_integration_test.go @@ -49,7 +49,7 @@ func newSkyWayPlayerScenario(t *testing.T) *skyWayPlayerScenario { t.Fatal(err) } defer func() { _ = tx.Rollback() }() - ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "skyway-client"}, State: tx} + ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "skyway-client"}, State: tx, InstanceIDs: s.factory.instanceIDs()} for _, character := range owner.assembly.worldService.CharacterService().RawAll() { costume, owned := owner.assembly.collection.CostumeByIndex(character.UseCostume) if !owned || costume.UseChar != character.InvenIndex || character.HP == 0 { @@ -157,7 +157,7 @@ func (s *skyWayPlayerScenario) assets(t *testing.T) skyWayAssets { t.Fatal(err) } defer func() { _ = tx.Rollback() }() - ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "skyway-client"}, State: tx} + ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "skyway-client"}, State: tx, InstanceIDs: s.factory.instanceIDs()} free, bonus, err := s.owner.assembly.huntingService.HuntingAP(ctx) if err != nil { t.Fatal(err) diff --git a/go/internal/server/app/spine_recordings_integration_test.go b/go/internal/server/app/spine_recordings_integration_test.go index 6ec5b07..c323949 100644 --- a/go/internal/server/app/spine_recordings_integration_test.go +++ b/go/internal/server/app/spine_recordings_integration_test.go @@ -24,7 +24,7 @@ import ( // This encodes the 2.36.7 client's RecordData.Serialize/Compress format, // independently of the server parser: click events on prestige illustration -// 1065193, point 1/1, tool 0 from GameData 20261012190548. +// 1065193, point 1/1, tool 0 from GameData 20261021182514. func nativeInteractionRecording(t *testing.T, delays ...int32) []byte { t.Helper() raw := binary.LittleEndian.AppendUint32(nil, uint32(len(delays))) diff --git a/go/internal/server/app/square_onboarding_integration_test.go b/go/internal/server/app/square_onboarding_integration_test.go new file mode 100644 index 0000000..748b5d3 --- /dev/null +++ b/go/internal/server/app/square_onboarding_integration_test.go @@ -0,0 +1,304 @@ +//go:build integration + +package app + +import ( + "context" + "fmt" + "path/filepath" + "testing" + "time" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/mail" + "bd2server/internal/server/protocol/wire" +) + +// PackTable's missed field-card rewards include currencies in UserDBInfo, +// ordinary content tickets and AvatarMotion ownership. MailOpen must apply +// all three domains together and retain its one-claim receipt after restart. +func TestPackRewardCompensationMailClaimsAllRewardDomainsOnce(t *testing.T) { + g := profileGameplay(t) + goldBefore := g.owner.assembly.wallet.Snapshot(command.Context{}).Gold + beforeUser, _, err := wire.Bytes(g.call("/LoginUser", nil), 1) + if err != nil { + t.Fatal(err) + } + spool := filepath.Join(t.TempDir(), "grants.json") + grant := mail.Grant{AccountID: g.account, Identity: "pack-reward-compensation", Title: "Card rewards", Body: "Previously missed card rewards", SentAt: time.Now().UnixMilli(), Rewards: []mail.GrantReward{ + {Type: 4, Count: 2000}, {Type: 15, Count: 10}, {Type: 16, Count: 100}, {Type: 18, Count: 50}, + {Type: 19, ID: 3009, Count: 1}, {Type: 19, ID: 3012, Count: 1}, {Type: 50, ID: 1, Count: 1}, + }} + if err := mail.AppendGrant(spool, grant); err != nil { + t.Fatal(err) + } + g.factory.options.mailGrantSpool = spool + g.reopen() + mailbox := g.call("/MailInfo", nil) + var id uint64 + for _, entry := range appRows(mailbox, 1) { + title, _, err := wire.Bytes(entry, 5) + if err == nil && string(title) == grant.Title { + id = appValue(entry, 1) + } + } + if id == 0 { + t.Fatal("targeted compensation did not appear in the normal mailbox") + } + userAfterIssue, _, err := wire.Bytes(g.call("/LoginUser", nil), 1) + if err != nil { + t.Fatal(err) + } + if g.owner.assembly.wallet.Snapshot(command.Context{}).Gold != goldBefore { + t.Fatal("mail creation granted gold before claim") + } + for _, field := range []int{16, 17, 18} { + if appValue(userAfterIssue, field) != appValue(beforeUser, field) { + t.Fatalf("mail creation granted currency field %d before claim", field) + } + } + for _, reward := range grant.Rewards[4:] { + if got := g.itemCount(reward.Type, reward.ID); got != 0 { + t.Fatalf("mail creation granted attachment before claim: %v count=%d", reward, got) + } + } + g.call("/MailOpen", wire.AppendVarint(nil, 2, id)) + check := func() { + t.Helper() + if got := g.owner.assembly.wallet.Snapshot(command.Context{}).Gold; got != goldBefore+2000 { + t.Fatalf("gold changed incorrectly after claim/retry: %d", got) + } + tx, err := g.owner.repository.BeginCommand(context.Background()) + if err != nil { + t.Fatal(err) + } + balances, balanceErr := g.owner.assembly.eventEconomy.AdditionalCurrencies(command.Context{State: tx}) + _ = tx.Rollback() + if balanceErr != nil { + t.Fatal(balanceErr) + } + for _, currency := range []struct { + field int + amount uint64 + }{{16, 10}, {17, 100}, {18, 50}} { + if got := balances[currency.field]; got != appValue(beforeUser, currency.field)+currency.amount { + t.Fatalf("currency field %d: got %d", currency.field, got) + } + } + for _, reward := range grant.Rewards[4:] { + if got := g.itemCount(reward.Type, reward.ID); got != 1 { + t.Fatalf("attachment missing or duplicated after claim/retry: %v count=%d", reward, got) + } + } + } + check() + g.reopen() + g.call("/MailInfo", nil) + g.call("/MailOpen", wire.AppendVarint(nil, 2, id)) + check() +} + +func avatarChoiceRequest(shop uint64) []byte { + price := wire.AppendVarint(wire.AppendVarint(nil, 3, 44), 4, 1000) + return wire.AppendBytes(nil, 2, wire.AppendBytes(wire.AppendVarint(nil, 1, shop), 2, price)) +} + +// AvatarSelectUI -> SendFirstBuyAvatarCharRequest submits shop1's nominal +// price without a funds check. AvatarPacket first clamps the local debit to +// zero, then adds the response bundle. First choice is free by server policy. +func TestSquareFirstChoiceWorksWithoutFundsAndKeepsClientBalanceConsistent(t *testing.T) { + for _, initial := range []uint64{0, 500, 2500} { + t.Run(fmt.Sprint(initial), func(t *testing.T) { + g := profileGameplay(t) + if initial > 0 { + profileGrant(g, gamedata.Reward{Type: 44, Count: initial}) + } + before := g.wordCurrency() + response := g.call("/AvatarShopBuy", avatarChoiceRequest(1)) + bundle, _, err := wire.Bytes(response, 1) + if err != nil { + t.Fatal(err) + } + localAfterDebit := before - min(before, uint64(1000)) + for _, item := range appRows(bundle, 1) { + if appValue(item, 3) == 44 { + localAfterDebit += appValue(item, 4) + } + } + if localAfterDebit != before || g.wordCurrency() != before { + t.Fatalf("free choice desynchronized native/server currency: native=%d server=%d before=%d", localAfterDebit, g.wordCurrency(), before) + } + for _, asset := range [][2]uint64{{61, 1}, {49, 10001}, {49, 20001}, {49, 40001}, {19, 3010}, {19, 3011}} { + if g.itemCount(asset[0], asset[1]) != 1 { + t.Fatalf("first choice failed to deliver avatar or SquareDefault unlock %v", asset) + } + } + use := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, 1), 2, 10001), 3, 20001), 5, 40001) + g.call("/AvatarSave", wire.AppendBytes(nil, 2, use)) + g.reopen() + avatar := g.call("/AvatarInfo", nil) + current, _, err := wire.Bytes(avatar, 1) + if err != nil || appValue(current, 1) != 1 || appValue(current, 5) != 40001 { + t.Fatalf("equipped initial avatar did not survive reopening: %v", err) + } + login := g.call("/LoginUser", nil) + user, _, err := wire.Bytes(login, 1) + if err != nil || appValue(user, 56) != 1 { + t.Fatalf("login lost consumed first-choice eligibility: %v", err) + } + if before < 1000 { + g.execute(g.request("/AvatarShopBuy", avatarChoiceRequest(2)), true) + if g.itemCount(61, 2) != 0 || g.wordCurrency() != before { + t.Fatal("second character bypassed ordinary purchase price") + } + } else { + g.call("/AvatarShopBuy", avatarChoiceRequest(2)) + if g.itemCount(61, 2) != 1 || g.wordCurrency() != before-1000 { + t.Fatal("second character was not charged at the authored price") + } + } + if g.itemCount(19, 3010) != 1 || g.itemCount(19, 3011) != 1 { + t.Fatal("later purchase duplicated setup unlocks") + } + // CommonPacket.EnterPack uses the shared card endpoints for both + // Fishing(12) and Life(13), after their domain initialization calls. + for _, entry := range []struct { + id uint64 + info string + }{{3010, "/FishingInfo"}, {3011, "/LifeInfo"}} { + fields := wire.AppendVarint(nil, 2, entry.id) + g.call("/PackPreviewInfo", fields) + g.call(entry.info, nil) + g.call("/PackInGameInfo", fields) + } + }) + } +} + +func TestFailedInitialAvatarBatchDoesNotConsumeTheFreeChoice(t *testing.T) { + g := profileGameplay(t) + profileGrant(g, gamedata.Reward{Type: 44, Count: 500}) + buy := g.request("/AvatarShopBuy", avatarChoiceRequest(1)) + unowned := wire.AppendBytes(nil, 2, wire.AppendVarint(nil, 1, 18)) + invalid := g.request("/AvatarSave", unowned) + buy.Requests = append(buy.Requests, invalid.Requests...) + g.execute(buy, true) + g.reopen() + if g.wordCurrency() != 500 || g.itemCount(61, 1) != 0 || g.itemCount(19, 3010) != 0 || g.itemCount(19, 3011) != 0 { + t.Fatal("rejected initial setup retained some purchase/entitlement state") + } + g.call("/AvatarShopBuy", avatarChoiceRequest(2)) + if g.wordCurrency() != 500 || g.itemCount(61, 2) != 1 || g.itemCount(19, 3010) != 1 || g.itemCount(19, 3011) != 1 { + t.Fatal("rolled-back setup consumed the one free choice") + } +} + +// Pack3009 BuyRewardType/Id/Count and RandomBox930000 -> RewardGroup930000 +// supply ticket3009 plus all32 authored motions. Opening/previewing a card is +// not a purchase; purchase receipts must survive reopening without regranting. +func TestSquareCardPurchaseDeliversItsAuthoredRewardsOnce(t *testing.T) { + g := profileGameplay(t) + profileGrant(g, gamedata.Reward{Type: 19, ID: 11, Count: 1}) + request := wire.AppendVarint(nil, 2, 3009) + before := g.itemCount(19, 3009) + g.call("/PackPreviewInfo", request) + if g.itemCount(19, 3009) != before { + t.Fatal("card preview granted purchase rewards") + } + response := g.call("/PackBuy", request) + info, _, err := wire.Bytes(response, 1) + if err != nil || appValue(info, 1) != 3009 || appValue(info, 8) != 1 { + t.Fatalf("purchase did not mark the plaza card as owned: %v", err) + } + if g.itemCount(19, 3009) != before+1 { + t.Fatal("plaza purchase omitted its content ticket") + } + var motions []uint64 + for id := uint64(1); id <= 17; id++ { + motions = append(motions, id) + } + for id := uint64(100001); id <= 100015; id++ { + motions = append(motions, id) + } + for _, id := range motions { + if g.itemCount(50, id) != 1 { + t.Fatalf("authored plaza entry motion %d not granted", id) + } + } + g.reopen() + g.call("/PackBuy", request) + g.call("/PackInGameInfo", request) + for _, id := range motions { + if g.itemCount(50, id) != 1 { + t.Fatalf("reopening/reentry duplicated motion %d", id) + } + } + if g.itemCount(19, 3009) != before+1 { + t.Fatal("reopening/reentry duplicated plaza ticket") + } +} + +// GameData 20261021182514 Pack3006 is PackGuildRaid (8), with maps30061+ +// and a one-time purchase reward of 1000 gold. CommonPacket buys it through +// the same PackBuy callback as other field cards before GuildRaid entry. +func TestGuildRaidCardPurchasePersistsAndCannotRepeatItsReward(t *testing.T) { + g := profileGameplay(t) + request := wire.AppendVarint(nil, 2, 3006) + // Exercise the domain transaction without the login observer purchasing + // unrelated open cards and adding their gold to the same command. + call := func(path string, body []byte) []byte { + t.Helper() + tx, err := g.owner.repository.BeginCommand(context.Background()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback() }() + ctx := command.Context{Identity: command.Identity{AccountID: g.account}, State: tx, InstanceIDs: g.factory.instanceIDs()} + _, response, handled, err := g.owner.assembly.worldService.Handle(ctx, path, append(wire.AppendVarint(nil, 1, 1), body...)) + if err != nil || !handled { + t.Fatalf("%s: handled=%v error=%v", path, handled, err) + } + if err := tx.Commit(); err != nil { + t.Fatal(err) + } + return response + } + goldBefore := g.owner.assembly.wallet.Snapshot(command.Context{}).Gold + response := call("/PackBuy", request) + info, _, err := wire.Bytes(response, 1) + if err != nil || appValue(info, 1) != 3006 || appValue(info, 8) != 1 { + t.Fatalf("guild raid card purchase did not return owned card: %v", err) + } + bundle, _, err := wire.Bytes(response, 2) + if err != nil { + t.Fatal(err) + } + var gold uint64 + for _, item := range appRows(bundle, 1) { + if appValue(item, 3) == 4 { + gold += appValue(item, 4) + } + } + if gold != 1000 { + t.Fatalf("guild raid card purchase omitted authored gold reward: %d", gold) + } + if g.owner.assembly.wallet.Snapshot(command.Context{}).Gold != goldBefore+1000 { + t.Fatal("guild raid purchase returned gold without crediting the wallet") + } + g.reopen() + call("/PackBuy", request) + call("/PackPreviewInfo", request) + if g.owner.assembly.wallet.Snapshot(command.Context{}).Gold != goldBefore+1000 { + t.Fatal("reopening or previewing guild raid card repeated its purchase reward") + } + var owned bool + for _, row := range appRows(call("/PackInfo", nil), 1) { + if appValue(row, 1) == 3006 && appValue(row, 8) == 1 { + owned = true + } + } + if !owned { + t.Fatal("guild raid card ownership lost after reopening") + } +} diff --git a/go/internal/server/app/starter_gifts_integration_test.go b/go/internal/server/app/starter_gifts_integration_test.go new file mode 100644 index 0000000..301c0e7 --- /dev/null +++ b/go/internal/server/app/starter_gifts_integration_test.go @@ -0,0 +1,254 @@ +//go:build integration + +package app + +import ( + "bytes" + "context" + "encoding/json" + "slices" + "testing" + "time" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/startergift" +) + +func TestStarterGiftCurrentSourcesExcludeDefaultsAndAchievements(t *testing.T) { + factory, _ := newIntegrationFactory(t) + gifts, err := factory.seeds.starterGifts.Resolve(startergift.Selection{ + Limited: factory.design.limitedCostumes, Prestige: factory.design.prestigeCatalog, + Avatars: factory.design.avatarProfile, OwnedPrestige: map[uint64]bool{65193: true}, + }) + if err != nil { + t.Fatal(err) + } + var external, linked []gamedata.Reward + for _, gift := range gifts { + switch gift.Identity { + case startergift.LimitedAvatars: + external = gift.Rewards + case "starter:prestige-avatar:65193:v1": + linked = gift.Rewards + } + } + // Current AvatarItemTable unlock texts: April Fools dice, Valentine roulette, + // artbook code, and coffee-truck voucher. None is a default or title reward. + want := []gamedata.Reward{{Type: 49, ID: 20018, Count: 1}, {Type: 49, ID: 50007, Count: 1}, {Type: 49, ID: 60015, Count: 1}, {Type: 49, ID: 60018, Count: 1}} + if !slices.Equal(external, want) { + t.Fatalf("external gift=%v, want only audited external sources %v", external, want) + } + // AvatarSetTable 2001 links PrestigeSkin 65193 to these three pieces. + want = []gamedata.Reward{{Type: 49, ID: 10025, Count: 1}, {Type: 49, ID: 20033, Count: 1}, {Type: 49, ID: 40048, Count: 1}} + if !slices.Equal(linked, want) { + t.Fatalf("owned prestige attachment=%v want %v", linked, want) + } + for _, gift := range gifts { + if startergift.IsAvatarGift(gift.Identity) && gift.Identity != startergift.LimitedAvatars && gift.Identity != "starter:prestige-avatar:65193:v1" { + t.Fatalf("unowned prestige skin received an outfit: %s", gift.Identity) + } + for _, reward := range gift.Rewards { + if startergift.IsAvatarGift(gift.Identity) && (reward.Type != 49 || slices.Contains([]uint64{10001, 40001, 50013, 50014, 10030, 40055}, reward.ID)) { + t.Fatalf("default, collaboration body, or title reward was included: %v", reward) + } + } + } +} + +func TestStarterGiftUpgradePreservesIssuedMailAndFiltersOwnedAccessories(t *testing.T) { + factory, accounts := newIntegrationFactory(t) + current := factory.seeds.starterGifts + legacy, err := cloneSeed(¤t) + if err != nil { + t.Fatal(err) + } + for i := range legacy.Gifts { + legacy.Gifts[i].Parts = nil + } + factory.seeds.starterGifts = *legacy + owner, err := factory.open(accounts[0]) + if err != nil { + t.Fatal(err) + } + g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner} + t.Cleanup(func() { + if g.owner != nil { + if err := g.owner.Close(); err != nil { + t.Error(err) + } + } + }) + readMail := func() (map[string]uint64, map[string][]byte) { + t.Helper() + tx, err := g.owner.repository.BeginCommand(context.Background()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback() }() + ids := map[string]uint64{} + records := map[string][]byte{} + for _, bucket := range []string{"issued", "dynamic", "history"} { + rows, err := g.owner.assembly.scope.ListEntries(tx, "mail", bucket) + if err != nil { + t.Fatal(err) + } + for key, raw := range rows { + records[bucket+":"+key] = append([]byte(nil), raw...) + if bucket == "issued" { + var id uint64 + if err := json.Unmarshal(raw, &id); err != nil { + t.Fatal(err) + } + ids[key] = id + } + } + } + return ids, records + } + ids, _ := readMail() + if ids[startergift.LimitedCostumes] == 0 || ids[startergift.PrestigeSkins] == 0 || ids[startergift.LimitedAvatars] != 0 { + t.Fatal("old account fixture must have only the two historical gifts") + } + // Leave the limited costume gift unclaimed and claim the prestige gift. + g.call("/MailOpen", appScalar(2, ids[startergift.PrestigeSkins])) + _, before := readMail() + factory.seeds.starterGifts = current + g.reopen() + g.call("/MailInfo", nil) + ids, after := readMail() + for key, raw := range before { + if !bytes.Equal(raw, after[key]) { + t.Fatalf("upgrading the gift catalog changed historical %s", key) + } + } + accessoryMail := ids[startergift.LimitedAvatars] + if accessoryMail == 0 { + t.Fatal("existing account did not receive the new external accessory gift") + } + // This piece is acquired after delivery; claiming must omit its new-item row. + scenario := &trapPlayerScenario{factory: factory, owner: g.owner, account: accounts[0]} + scenario.run(t, true, func(ctx command.Context, p *playerAssembly) { + if _, err := p.eventEconomy.Apply(ctx, "other-accessory-source", nil, []gamedata.Reward{{Type: 49, ID: 20018, Count: 1}}); err != nil { + t.Fatal(err) + } + }) + request := g.request("/MailOpen", appScalar(2, accessoryMail)) + claim := g.execute(request, false) + if retry := g.execute(request, false); !bytes.Equal(retry, claim) { + t.Fatal("same-request retry changed the filtered acquisition bundle") + } + for _, bundle := range appRows(claim, 1) { + for _, row := range appRows(bundle, 1) { + if appValue(row, 3) == 49 && appValue(row, 2) == 20018 { + t.Fatal("already-owned accessory was returned as newly acquired") + } + } + } + for _, id := range []uint64{20018, 50007, 60015, 60018} { + if g.itemCount(49, id) != 1 { + t.Fatalf("external accessory %d was missing or duplicated", id) + } + } + reopenedClaim := g.call("/MailOpen", appScalar(2, accessoryMail)) + for _, bundle := range appRows(reopenedClaim, 1) { + if len(bundle) != 0 { + t.Fatal("a new request to an opened accessory mail returned an acquisition bundle") + } + } + for _, id := range []uint64{20018, 50007, 60015, 60018} { + if g.itemCount(49, id) != 1 { + t.Fatalf("new claim request duplicated external accessory %d", id) + } + } + _, stable := readMail() + g.reopen() + g.call("/MailInfo", nil) + _, reopened := readMail() + if len(stable) != len(reopened) { + t.Fatal("relogin issued the same gifts again") + } + for key, raw := range stable { + if !bytes.Equal(raw, reopened[key]) { + t.Fatalf("relogin changed gift record %s", key) + } + } + for _, id := range []uint64{20018, 50007, 60015, 60018} { + if g.itemCount(49, id) != 1 { + t.Fatalf("relogin duplicated or lost external accessory %d", id) + } + } +} + +func TestNewlyOwnedPrestigeCreatesLinkedGiftOnMailInfoWithoutDuplicatingSharedPieces(t *testing.T) { + factory, accounts := newIntegrationFactory(t) + owner, err := factory.open(accounts[0]) + if err != nil { + t.Fatal(err) + } + g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner} + t.Cleanup(func() { _ = g.owner.Close() }) + scenario := &trapPlayerScenario{factory: factory, owner: owner, account: accounts[0]} + var linkedMail uint64 + readLinked := func() { + t.Helper() + scenario.run(t, false, func(ctx command.Context, p *playerAssembly) { + rows, err := p.scope.ListEntries(ctx.State, "mail", "issued") + if err != nil { + t.Fatal(err) + } + if raw := rows["starter:prestige-avatar:65193:v1"]; raw != nil { + if err := json.Unmarshal(raw, &linkedMail); err != nil { + t.Fatal(err) + } + } + }) + } + readLinked() + if linkedMail != 0 { + t.Fatal("unowned prestige skin received an attachment gift") + } + scenario.run(t, true, func(ctx command.Context, p *playerAssembly) { + if _, err := p.eventEconomy.Apply(ctx, "new-owned-prestige", nil, []gamedata.Reward{{Type: 45, ID: 65193, Count: 1}}); err != nil { + t.Fatal(err) + } + // Another legitimate mail rewards one shared piece before the linked gift. + if err := p.mailService.EnqueueCompensation(ctx, "shared-piece-source", "Shared piece", "Another source of the same piece", []gamedata.Reward{{Type: 49, ID: 10025, Count: 1}}, time.Now()); err != nil { + t.Fatal(err) + } + }) + g.call("/MailInfo", nil) + readLinked() + if linkedMail == 0 { + t.Fatal("new ownership did not produce its linked outfit in the current session") + } + var sharedMail uint64 + scenario.run(t, false, func(ctx command.Context, p *playerAssembly) { + rows, err := p.scope.ListEntries(ctx.State, "mail", "issued") + if err != nil || json.Unmarshal(rows["shared-piece-source"], &sharedMail) != nil { + t.Fatal("shared-piece source mail missing", err) + } + }) + g.call("/MailOpen", appScalar(2, sharedMail)) + claim := g.call("/MailOpen", appScalar(2, linkedMail)) + var newlyAcquired []uint64 + for _, bundle := range appRows(claim, 1) { + for _, row := range appRows(bundle, 1) { + if appValue(row, 3) == 49 { + newlyAcquired = append(newlyAcquired, appValue(row, 2)) + } + } + } + slices.Sort(newlyAcquired) + if !slices.Equal(newlyAcquired, []uint64{20033, 40048}) { + t.Fatalf("linked gift returned unexpected new pieces: %v", newlyAcquired) + } + for _, id := range []uint64{10025, 20033, 40048} { + if g.itemCount(49, id) != 1 { + t.Fatalf("linked piece %d duplicated or missing", id) + } + } + if g.itemCount(61, 15) != 0 || g.itemCount(49, 10023) != 0 || g.itemCount(49, 50013) != 0 { + t.Fatal("linked prestige gift granted a default avatar, default outfit, or title reward") + } +} diff --git a/go/internal/server/app/user_profile_integration_test.go b/go/internal/server/app/user_profile_integration_test.go index 817c6db..8034fe9 100644 --- a/go/internal/server/app/user_profile_integration_test.go +++ b/go/internal/server/app/user_profile_integration_test.go @@ -211,7 +211,7 @@ func TestUserContentsInfoReflectsCommittedProfileAndRejectsOtherOwners(t *testin t.Fatal(err) } defer func() { _ = tx.Rollback() }() - if _, err := action(command.Context{Identity: command.Identity{AccountID: accounts[0], SessionID: "profile-combat"}, State: tx}); err != nil { + if _, err := action(command.Context{Identity: command.Identity{AccountID: accounts[0], SessionID: "profile-combat"}, State: tx, InstanceIDs: factory.instanceIDs()}); err != nil { t.Fatal(err) } if err := tx.Commit(); err != nil { diff --git a/go/internal/server/design/gamedata/cash_products.go b/go/internal/server/design/gamedata/cash_products.go index a410133..414fd84 100644 --- a/go/internal/server/design/gamedata/cash_products.go +++ b/go/internal/server/design/gamedata/cash_products.go @@ -23,7 +23,11 @@ type CashProductDesign struct { } type CashShopDesign struct{ GroupID, ID, ProductGroupID, BulkOrderShow uint64 } type EventShopDesign struct{ ID, ProductGroupID uint64 } -type CashPackageDesign struct{ GroupID, ID, SaleGroup, PackageType, PaidShopGroupID, PaidShopID, ContentsGroupID, ContentsSortID uint64 } +type CashPackageDesign struct { + GroupID, ID, SaleGroup, PackageType, PaidShopGroupID, PaidShopID, ContentsGroupID, ContentsSortID uint64 + ResourceName string + Sequential bool +} type CashCatalog struct { Products []CashProductDesign Shops []CashShopDesign @@ -111,7 +115,15 @@ func loadCashCatalog(db *sql.DB) (*CashCatalog, error) { if e != nil { return e } - c.Packages = append(c.Packages, CashPackageDesign{v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]}) + resource, _, e := wire.Bytes(raw, 16) + if e != nil { + return e + } + c.Packages = append(c.Packages, CashPackageDesign{ + GroupID: v[0], ID: v[1], SaleGroup: v[2], PackageType: v[3], + PaidShopGroupID: v[4], PaidShopID: v[5], ContentsGroupID: v[6], ContentsSortID: v[7], + ResourceName: string(resource), + }) return nil }); err != nil { return nil, err diff --git a/go/internal/server/design/gamedata/content_open.go b/go/internal/server/design/gamedata/content_open.go index ce217af..0166729 100644 --- a/go/internal/server/design/gamedata/content_open.go +++ b/go/internal/server/design/gamedata/content_open.go @@ -6,10 +6,12 @@ import ( ) // ContentOpeningDesign describes the rapport prologue's prerequisite and -// completion marker. The client maps ContentOpenRequest type 1 to group 23, -// detail 2; ticket identities and level requirements remain version data. +// completion marker, and the dating unlock. The client maps ContentOpenRequest +// type 1 to group 23, detail 2, and checks Define_ContentOpenType +// ContentUnlockDating (group 19, detail 1) before granting the cafeteria +// introduction; ticket identities and level requirements remain version data. type ContentOpeningDesign struct { - Prerequisite, Completion ContentOpenRule + Prerequisite, Completion, Dating ContentOpenRule } func LoadContentOpeningDesign(root, version string) (*ContentOpeningDesign, error) { @@ -83,13 +85,20 @@ func loadContentOpeningDesign(db *sql.DB) (*ContentOpeningDesign, error) { return nil, fmt.Errorf("gamedata: invalid content opening %d/%d identity or ticket", group, id) } seen[key] = true + rule := ContentOpenRule{TutorialID: values[3], SquadLevel: values[4], TicketID: ticket} + if key == [2]uint64{19, 1} { + if tickets[ticket] != 1 { + return nil, fmt.Errorf("gamedata: dating opening requires permanent content ticket") + } + d.Dating = rule + continue + } if group != 23 || (id != 1 && id != 2) { continue } if tickets[ticket] != 1 { return nil, fmt.Errorf("gamedata: rapport opening %d requires permanent content ticket", id) } - rule := ContentOpenRule{TutorialID: values[3], SquadLevel: values[4], TicketID: ticket} if id == 1 { d.Prerequisite = rule } else { @@ -99,6 +108,9 @@ func loadContentOpeningDesign(db *sql.DB) (*ContentOpeningDesign, error) { if err := rows.Err(); err != nil { return nil, err } + if !seen[[2]uint64{19, 1}] { + return nil, fmt.Errorf("gamedata: missing dating opening rule") + } if !seen[[2]uint64{23, 1}] || !seen[[2]uint64{23, 2}] || d.Prerequisite.TicketID == d.Completion.TicketID { return nil, fmt.Errorf("gamedata: missing or indistinguishable rapport opening rules") } diff --git a/go/internal/server/design/gamedata/equipment_gacha.go b/go/internal/server/design/gamedata/equipment_gacha.go index 16cc933..a5f8a9d 100644 --- a/go/internal/server/design/gamedata/equipment_gacha.go +++ b/go/internal/server/design/gamedata/equipment_gacha.go @@ -21,14 +21,15 @@ type EquipmentGachaCatalog struct { equipment map[uint64]EquipmentDesign } type EquipmentGacha struct { - ID uint64 - Count int - FreeCountDay uint64 - PriceType, Price uint64 - TicketIDs []uint64 - Pool []WeightedEquipment - TicketOnly bool - Grades map[uint64]uint64 + ID uint64 + Count int + FreeCountDay uint64 + DailyPayGachaCount, DailyPayGachaPriceCount uint64 + PriceType, Price uint64 + TicketIDs []uint64 + Pool []WeightedEquipment + TicketOnly bool + Grades map[uint64]uint64 } type EquipmentGachaGroup struct { ID, FixedID, PointCount, OneTimeGachaID, TenTimeGachaID uint64 @@ -280,6 +281,14 @@ func loadEquipmentGacha(db *sql.DB, id uint64) (EquipmentGacha, error) { if len(freeCounts) == 1 { freeCount = freeCounts[0] } + dailyPayCount, err := optionalScalar(raw, 1) + if err != nil { + return EquipmentGacha{}, fmt.Errorf("gamedata: equipment paid allowance %d: %w", id, err) + } + dailyPayPrice, err := optionalScalar(raw, 2) + if err != nil || (dailyPayCount == 0) != (dailyPayPrice == 0) { + return EquipmentGacha{}, fmt.Errorf("gamedata: malformed equipment paid discount %d", id) + } // Partial ticket consumption bills remaining draws individually; the local // billing path currently requires an integral price per draw. if len(count) != 1 || len(reward) != 1 || len(price) != 1 || len(kind) != 1 || kind[0] != 3 || count[0] == 0 || price[0] == 0 || price[0]%count[0] != 0 { @@ -289,7 +298,7 @@ func loadEquipmentGacha(db *sql.DB, id uint64) (EquipmentGacha, error) { if err != nil { return EquipmentGacha{}, fmt.Errorf("gamedata: equipment gacha %d: %w", id, err) } - return EquipmentGacha{ID: id, Count: int(count[0]), FreeCountDay: freeCount, PriceType: kind[0], Price: price[0], TicketIDs: append([]uint64(nil), tickets...), Pool: pool}, nil + return EquipmentGacha{ID: id, Count: int(count[0]), FreeCountDay: freeCount, DailyPayGachaCount: dailyPayCount, DailyPayGachaPriceCount: dailyPayPrice, PriceType: kind[0], Price: price[0], TicketIDs: append([]uint64(nil), tickets...), Pool: pool}, nil } func loadEquipmentRewardPool(db *sql.DB, groupID uint64) ([]WeightedEquipment, error) { var raw []byte diff --git a/go/internal/server/design/gamedata/event_tasks.go b/go/internal/server/design/gamedata/event_tasks.go index cf49c16..0f3db41 100644 --- a/go/internal/server/design/gamedata/event_tasks.go +++ b/go/internal/server/design/gamedata/event_tasks.go @@ -17,9 +17,9 @@ type EventMissionGroup struct { Groups []uint64 } type EventTask struct { - ID, Group, Type, SubType, Target, PassExp, UnlockPack, UnlockQuest uint64 - Params []uint64 - Rewards []Reward + ID, Group, Type, SubType, SubTypeMoreCheck, Target, PassExp, UnlockPack, UnlockQuest uint64 + Params []uint64 + Rewards []Reward } type EventPass struct { ID, MissionGroup, LevelGroup, Type, ScheduleType, NewbieGroup, NewbieStep uint64 @@ -153,7 +153,7 @@ func loadEventTasksDesign(db *sql.DB) (*EventTasksDesign, error) { return nil } r := EventTask{} - if e = read(p, map[int]*uint64{8: &r.ID, 6: &r.Group, 3: &r.Type, 1: &r.SubType, 4: &r.Target, 12: &r.PassExp, 19: &r.UnlockPack, 20: &r.UnlockQuest}); e != nil { + if e = read(p, map[int]*uint64{8: &r.ID, 6: &r.Group, 3: &r.Type, 1: &r.SubType, 9: &r.SubTypeMoreCheck, 4: &r.Target, 12: &r.PassExp, 19: &r.UnlockPack, 20: &r.UnlockQuest}); e != nil { return e } r.Params, e = packedInts(p, 2) diff --git a/go/internal/server/design/gamedata/field_monster_maps.go b/go/internal/server/design/gamedata/field_monster_maps.go index d4afde0..f6b274b 100644 --- a/go/internal/server/design/gamedata/field_monster_maps.go +++ b/go/internal/server/design/gamedata/field_monster_maps.go @@ -58,7 +58,8 @@ func LoadFieldMonsterMaps(root, version string, pack int) (map[int][]int, error) } mapID, ok := maps[string(scene)] if !ok { - return nil, fmt.Errorf("gamedata: monster scene without map") + // A scene with no MapTable row is unreachable, so it places nothing. + continue } out[int(id)] = append(out[int(id)], mapID) } diff --git a/go/internal/server/design/gamedata/field_pack.go b/go/internal/server/design/gamedata/field_pack.go index 0495c4b..a2b05e5 100644 --- a/go/internal/server/design/gamedata/field_pack.go +++ b/go/internal/server/design/gamedata/field_pack.go @@ -9,9 +9,12 @@ import ( // enum; IDs and entry restrictions come from the installed GameData tables. type FieldPack struct { ID, Type, BuyPrice, UseSchedule uint64 + BuyType uint64 + BuyRewards []Reward TicketID, SquadLevel uint64 HasOpenRule bool MapIDs map[int]bool + IntroQuest *QuestDesign } func LoadFieldPacks(root, version string) (map[int]FieldPack, error) { @@ -23,6 +26,11 @@ func LoadFieldPacks(root, version string) (map[int]FieldPack, error) { return loadFieldPacks(db) } +// fieldPackTypes are the Define_PackType values served as field packs: 1 Char, +// 3 PVP, 4 EvilCastle, 5 SkyWay, 6 Event, 7 TotalWar, 8 GuildRaid, 9 Cafeteria, 10 Colosseum, +// 11 Square, 12 Fishing, 13 Life, 14 Ib. +var fieldPackTypes = map[uint64]bool{1: true, 3: true, 4: true, 5: true, 6: true, 7: true, 8: true, 9: true, 10: true, 11: true, 12: true, 13: true, 14: true} + func loadFieldPacks(db *sql.DB) (map[int]FieldPack, error) { result := map[int]FieldPack{} rows, err := db.Query("SELECT id,ProtoBuf FROM PackTable ORDER BY id") @@ -37,7 +45,7 @@ func loadFieldPacks(db *sql.DB) (map[int]FieldPack, error) { return nil, err } values := map[int]uint64{} - for _, field := range []int{7, 25, 55, 65} { + for _, field := range []int{7, 11, 25, 55, 65} { v, e := packedInts(raw, field) if e != nil || len(v) > 1 { _ = rows.Close() @@ -47,14 +55,23 @@ func loadFieldPacks(db *sql.DB) (map[int]FieldPack, error) { values[field] = v[0] } } - if values[55] != 3 && values[55] != 4 && values[55] != 5 && values[55] != 7 && values[55] != 10 { + if !fieldPackTypes[values[55]] { continue } if id <= 0 || values[25] != uint64(id) { _ = rows.Close() return nil, fmt.Errorf("gamedata: invalid field pack identity %d", id) } - result[id] = FieldPack{ID: uint64(id), Type: values[55], BuyPrice: values[7], UseSchedule: values[65], MapIDs: map[int]bool{}} + pack := FieldPack{ID: uint64(id), Type: values[55], BuyPrice: values[7], BuyType: values[11], UseSchedule: values[65], MapIDs: map[int]bool{}} + rewards, err := eventGameRewards(raw, 10, 9, 8) + if err != nil { + _ = rows.Close() + return nil, err + } + for _, reward := range rewards { + pack.BuyRewards = append(pack.BuyRewards, Reward(reward)) + } + result[id] = pack } if err := rows.Err(); err != nil { _ = rows.Close() @@ -123,6 +140,41 @@ func loadFieldPacks(db *sql.DB) (map[int]FieldPack, error) { if len(pack.MapIDs) == 0 { return nil, fmt.Errorf("gamedata: arena pack %d has no map", id) } + intro, err := loadFieldIntroduction(db, id) + if err != nil { + return nil, err + } + pack.IntroQuest = intro + result[id] = pack } return result, nil } + +// Standalone field introductions have one accept movie and no quest chain, +// completion movie or rewards. Ordinary field quest chains retain their own +// acceptance and settlement rules, even when their first quest has a movie. +func loadFieldIntroduction(db *sql.DB, packID int) (*QuestDesign, error) { + var exists bool + if err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)", fmt.Sprintf("QuestTable%d", packID)).Scan(&exists); err != nil { + return nil, err + } + if !exists { + return nil, nil + } + quests, err := loadQuestDesignDB(db, packID) + if err != nil || len(quests) != 1 { + return nil, err + } + for _, quest := range quests { + if quest.Type != 0 || quest.PriorQuestID != 0 || quest.NextQuestID != 0 || quest.AcceptCinemaName == "" || quest.CompleteCinemaName != "" || len(quest.GiveQuestItemIDs) != 0 || len(quest.CollectionRewards) != 0 { + return nil, nil + } + for _, rewards := range quest.Rewards { + if len(rewards) != 0 { + return nil, nil + } + } + return &quest, nil + } + return nil, nil +} diff --git a/go/internal/server/design/gamedata/gacha.go b/go/internal/server/design/gamedata/gacha.go index 8e69533..5d177f2 100644 --- a/go/internal/server/design/gamedata/gacha.go +++ b/go/internal/server/design/gamedata/gacha.go @@ -143,15 +143,16 @@ type GachaFixedRoll struct { } type RegularGachaCatalog struct { - Gachas map[uint64]RegularGacha - gachaEventAddFreeCount uint64 - characters map[uint64]CharacterDesign - groups map[uint64]GachaGroupDesign - byGacha map[uint64]uint64 - fixed map[uint64]GachaFixedDesign - grades map[uint64]uint64 - stepUps map[uint64]GachaStepUpDesign - stepByGacha map[uint64]GachaStepDesign + Gachas map[uint64]RegularGacha + gachaEventAddFreeCount uint64 + gachaEventAddDailyPayCount uint64 + characters map[uint64]CharacterDesign + groups map[uint64]GachaGroupDesign + byGacha map[uint64]uint64 + fixed map[uint64]GachaFixedDesign + grades map[uint64]uint64 + stepUps map[uint64]GachaStepUpDesign + stepByGacha map[uint64]GachaStepDesign } func (c *RegularGachaCatalog) GachaEventAddFreeCount() uint64 { @@ -161,6 +162,13 @@ func (c *RegularGachaCatalog) GachaEventAddFreeCount() uint64 { return c.gachaEventAddFreeCount } +func (c *RegularGachaCatalog) GachaEventAddDailyPayCount() uint64 { + if c == nil { + return 0 + } + return c.gachaEventAddDailyPayCount +} + func (c *RegularGachaCatalog) SetGachaEventAddFreeCount(count uint64) error { if c == nil || count > 256 { return errors.New("gamedata: invalid gacha event free-count bonus") @@ -983,6 +991,11 @@ func LoadRegularCostumeGachaGroups(root, version string, groupIDs, stepUpGroupID return nil, err } } + paidBonus, err := optionalScalar(defaults, 47) + if err != nil || paidBonus > 256 { + return nil, errors.New("gamedata: malformed GachaEventAddDailyPayGachaCount") + } + catalog.gachaEventAddDailyPayCount = paidBonus gachaIDs := make(map[uint64]struct{}) for _, groupID := range groupIDs { var raw []byte diff --git a/go/internal/server/design/gamedata/guild.go b/go/internal/server/design/gamedata/guild.go index 77f76b2..c94684d 100644 --- a/go/internal/server/design/gamedata/guild.go +++ b/go/internal/server/design/gamedata/guild.go @@ -21,9 +21,11 @@ type GuildRaidRules struct { FlagVersions []GuildRaidFlagVersion TurnAddScore, TurnScoreValue, SupportScore float64 DailySupporterUses, BasicSupportReward, RentalSupportReward, RewardMailID uint64 - Bosses map[uint64]map[uint64]GuildRaidBoss - ScoreRewards []GuildRaidScoreReward - RankRewards []GuildRaidRankReward + // OverkillLevel 0 disables overkill, matching BattleProcessor.IsOverKillMode. + OverkillLevel, OverkillMemberCount uint64 + Bosses map[uint64]map[uint64]GuildRaidBoss + ScoreRewards []GuildRaidScoreReward + RankRewards []GuildRaidRankReward } type GuildRaidFlagVersion struct{ GroupID, MinSeason, MaxSeason uint64 } @@ -130,18 +132,19 @@ func LoadGuildDesign(root, version string) (*GuildDesign, error) { if err = db.QueryRow("SELECT ProtoBuf FROM GuildRaidDefaultTable WHERE id=0").Scan(&raw); err != nil { return nil, err } - v, err = cashScalars(raw, 3, 21, 22, 15) + v, err = cashScalars(raw, 3, 23, 24, 15, 17, 18) if err != nil { return nil, err } d.Raid.DailySupporterUses, d.Raid.BasicSupportReward, d.Raid.RentalSupportReward, d.Raid.RewardMailID = v[0], v[1], v[2], v[3] - if d.Raid.TurnAddScore, err = optionalDouble(raw, 24); err != nil { + d.Raid.OverkillLevel, d.Raid.OverkillMemberCount = v[4], v[5] + if d.Raid.TurnAddScore, err = optionalDouble(raw, 26); err != nil { return nil, err } - if d.Raid.TurnScoreValue, err = optionalDouble(raw, 25); err != nil { + if d.Raid.TurnScoreValue, err = optionalDouble(raw, 27); err != nil { return nil, err } - if d.Raid.SupportScore, err = optionalDouble(raw, 23); err != nil { + if d.Raid.SupportScore, err = optionalDouble(raw, 25); err != nil { return nil, err } if err = db.QueryRow("SELECT ProtoBuf FROM SupportCharacterDefaultTable WHERE id=0").Scan(&raw); err != nil { diff --git a/go/internal/server/design/gamedata/mail_catalog.go b/go/internal/server/design/gamedata/mail_catalog.go index d33f0db..1938f70 100644 --- a/go/internal/server/design/gamedata/mail_catalog.go +++ b/go/internal/server/design/gamedata/mail_catalog.go @@ -57,6 +57,16 @@ var mailItemSources = []mailItemSource{ // directly; their reward ID is zero. var MailCurrencyTypes = []uint64{2, 3, 4, 12, 20} +// MailEconomyCurrencyTypes are the other currencies a compensation mail can +// carry: their claim is credited by the event economy (wallet hope powder and +// refining traces, action points and the gameplay-entry balances such as the +// Cafeteria and decoration coins). Their reward ID is zero as well. +var MailEconomyCurrencyTypes = []uint64{15, 16, 18, 21, 22, 23, 24, 30, 31, 32, 33, 35, 38, 39, 40, 41, 42, 43, 44, 52, 53, 54, 60, 68, 70, 72} + +func mailCurrency(elementType uint64) bool { + return slices.Contains(MailCurrencyTypes, elementType) || slices.Contains(MailEconomyCurrencyTypes, elementType) +} + // LoadMailCatalog returns every safe direct-mail attachment in GameData. func LoadMailCatalog(root, version string) ([]MailCatalogItem, error) { var items []MailCatalogItem @@ -101,7 +111,7 @@ func loadMailCatalog(db *sql.DB) ([]MailCatalogItem, error) { if elementType == 0 { elementType = rowID } - if slices.Contains(MailCurrencyTypes, elementType) { + if mailCurrency(elementType) { items = append(items, MailCatalogItem{ElementType: elementType, Category: "currency", Name: names["NameTextTable"][singleVarint(proto, 5)]}) } return nil @@ -154,7 +164,7 @@ func fixedRandomBoxes(db *sql.DB, items []MailCatalogItem) (map[uint64]boxReward if len(ids) != 1 || len(types) != 1 || len(counts) != 1 || types[0] == 0 || counts[0] == 0 { return nil } - currency := slices.Contains(MailCurrencyTypes, types[0]) + currency := mailCurrency(types[0]) if currency != (ids[0] == 0) { return nil } diff --git a/go/internal/server/design/gamedata/profile_avatar.go b/go/internal/server/design/gamedata/profile_avatar.go index d7dad59..666417e 100644 --- a/go/internal/server/design/gamedata/profile_avatar.go +++ b/go/internal/server/design/gamedata/profile_avatar.go @@ -1,8 +1,11 @@ package gamedata -import "fmt" +import ( + "fmt" + "slices" +) -type AvatarPartRule struct{ Category, Character, Maximum uint64 } +type AvatarPartRule struct{ Category, Character, Maximum, UnlockTextID uint64 } type AvatarCharacterRule struct { Maximum uint64 Collaboration bool @@ -15,11 +18,14 @@ type AvatarProduct struct { Visibility, UnlockType, UnlockValue, UnlockSub uint64 } type AvatarProfileDesign struct { - Characters map[uint64]AvatarCharacterRule - Parts map[uint64]AvatarPartRule - MotionMaximum map[uint64]uint64 - Shop, MotionShop map[uint64]AvatarProduct - Bundles *AvatarRewardDesign + InitialUnlockTickets []uint64 + SquareChannels, SquareChannelCapacity uint64 + Characters map[uint64]AvatarCharacterRule + Parts map[uint64]AvatarPartRule + MotionMaximum map[uint64]uint64 + Shop, MotionShop map[uint64]AvatarProduct + Bundles *AvatarRewardDesign + PrestigeSets map[uint64][]Reward } func LoadAvatarProfileDesign(root, version string) (*AvatarProfileDesign, error) { @@ -33,6 +39,51 @@ func LoadAvatarProfileDesign(root, version string) (*AvatarProfileDesign, error) if err != nil { return nil, err } + d.PrestigeSets = map[uint64][]Reward{} + if err := readCashMetadata(db, "AvatarSetTable", func(raw []byte) error { + skin, err := optionalScalar(raw, 1) + if err != nil || skin == 0 { + return err + } + id, err := optionalScalar(raw, 6) + if err != nil { + return err + } + if len(d.PrestigeSets[skin]) != 0 { + return fmt.Errorf("gamedata: duplicate prestige avatar set for skin %d", skin) + } + for _, reward := range d.Bundles.Sets[id] { + if reward.Type != 49 || reward.Count != 1 { + return fmt.Errorf("gamedata: invalid prestige avatar member") + } + d.PrestigeSets[skin] = append(d.PrestigeSets[skin], Reward(reward)) + } + return nil + }); err != nil { + return nil, err + } + if err := readCashMetadata(db, "SquareDefaultTable", func(raw []byte) error { + channels, err := optionalScalar(raw, 2) + if err != nil { + return err + } + capacity, err := optionalScalar(raw, 5) + if err != nil || channels == 0 || channels > 10000 || capacity == 0 || capacity > 1000 { + return fmt.Errorf("gamedata: invalid square channel rules") + } + d.SquareChannels, d.SquareChannelCapacity = channels, capacity + tickets, err := packedInts(raw, 1) + if err != nil { + return err + } + if slices.Contains(tickets, uint64(0)) { + return fmt.Errorf("gamedata: invalid avatar setup ticket") + } + d.InitialUnlockTickets = append(d.InitialUnlockTickets, tickets...) + return nil + }); err != nil { + return nil, err + } if err = readCashMetadata(db, "AvatarCharTable", func(raw []byte) error { id, err := optionalScalar(raw, 6) if err != nil || id == 0 { @@ -84,7 +135,11 @@ func LoadAvatarProfileDesign(root, version string) (*AvatarProfileDesign, error) if err != nil { return err } - d.Parts[id] = AvatarPartRule{category, character, maximum} + unlockText, err := optionalScalar(raw, 8) + if err != nil { + return err + } + d.Parts[id] = AvatarPartRule{Category: category, Character: character, Maximum: maximum, UnlockTextID: unlockText} return nil }); err != nil { return nil, err diff --git a/go/internal/server/design/gamedata/pvp.go b/go/internal/server/design/gamedata/pvp.go index de14573..f071a02 100644 --- a/go/internal/server/design/gamedata/pvp.go +++ b/go/internal/server/design/gamedata/pvp.go @@ -24,10 +24,28 @@ type ColosseumDefaults struct { HistoryHours, HistoryLimit, TicketBuyType, TicketBuyID, TicketBuyCost uint64 MatchExclude, CandidateCount uint64 MatchRanges []uint64 + // Costume cost brackets: popularity ranks up to CostRankBoundaries[i] + // cost CostRankValues[i]; other costumes cost CostDefault. + CostDefault uint64 + CostRankBoundaries [4]uint64 + CostRankValues [4]uint64 + PopularCostumeMinimumRankGroup uint64 +} + +// CostumeCost prices a costume by its 1-based colosseum popularity rank; +// zero means the costume was not ranked. +func (c ColosseumDefaults) CostumeCost(rank uint64) uint64 { + for i, boundary := range c.CostRankBoundaries { + if rank != 0 && rank <= boundary { + return c.CostRankValues[i] + } + } + return c.CostDefault } type ColosseumRank struct { Group, ID uint64 + RankGroup uint64 TopPercent float64 Rewards []BattleReward } @@ -161,10 +179,12 @@ func LoadPvpDesign(root, version string) (*PvpDesign, error) { }}, {"ColosseumDefaultTable", func(raw []byte) error { m := &d.Colosseum - if err := pvpScalars(raw, map[int]*uint64{3: &m.MinimumVP, 4: &m.TicketBuyCost, 5: &m.TicketBuyID, 6: &m.TicketBuyType, 8: &m.HistoryHours, 9: &m.HistoryLimit, 16: &m.DefaultChange, 17: &m.MaximumChange, 18: &m.MinimumChange, 19: &m.VariableChange, 22: &m.MatchExclude, 30: &m.CandidateCount}); err != nil { + if err := pvpScalars(raw, map[int]*uint64{3: &m.MinimumVP, 4: &m.TicketBuyCost, 5: &m.TicketBuyID, 6: &m.TicketBuyType, 8: &m.HistoryHours, 9: &m.HistoryLimit, 16: &m.DefaultChange, 17: &m.MaximumChange, 18: &m.MinimumChange, 19: &m.VariableChange, 31: &m.MatchExclude, 40: &m.CandidateCount, + 20: &m.CostDefault, 21: &m.CostRankBoundaries[0], 22: &m.CostRankBoundaries[1], 23: &m.CostRankBoundaries[2], 24: &m.CostRankBoundaries[3], + 25: &m.CostRankValues[0], 26: &m.CostRankValues[1], 27: &m.CostRankValues[2], 28: &m.CostRankValues[3], 34: &m.PopularCostumeMinimumRankGroup}); err != nil { return err } - m.MatchRanges, err = packedInts(raw, 23) + m.MatchRanges, err = packedInts(raw, 32) return err }}, {"ColosseumSeasonTable", func(raw []byte) error { @@ -200,7 +220,7 @@ func LoadPvpDesign(root, version string) (*PvpDesign, error) { }}, {"ColosseumRankTable", func(raw []byte) error { var r ColosseumRank - if err := pvpScalars(raw, map[int]*uint64{1: &r.Group, 3: &r.ID}); err != nil { + if err := pvpScalars(raw, map[int]*uint64{1: &r.Group, 3: &r.ID, 4: &r.RankGroup}); err != nil { return err } if r.TopPercent, err = optionalDouble(raw, 10); err != nil { @@ -226,7 +246,7 @@ func LoadPvpDesign(root, version string) (*PvpDesign, error) { return nil, err } } - if d.Mirror.StartVP == 0 || d.Mirror.TicketCost == 0 || len(d.MirrorRanks) == 0 || len(d.ColosseumRules) == 0 { + if d.Mirror.StartVP == 0 || d.Mirror.TicketCost == 0 || len(d.MirrorRanks) == 0 || len(d.ColosseumRules) == 0 || d.Colosseum.CostDefault == 0 || d.Colosseum.PopularCostumeMinimumRankGroup == 0 { return nil, fmt.Errorf("gamedata: incomplete PVP design") } for group := range d.MirrorRanks { @@ -284,7 +304,7 @@ func (d *PvpDesign) ColosseumRule(season, kind uint64) ([]uint64, error) { } values, ok := d.ColosseumRules[group][kind] if !ok { - if kind == 30 || kind == 31 { + if kind == 30 || kind == 31 || kind == 32 { return nil, nil } return nil, fmt.Errorf("gamedata: missing colosseum rule %d", kind) diff --git a/go/internal/server/design/gamedata/quest_difficulty.go b/go/internal/server/design/gamedata/quest_difficulty.go index 8a7d1f9..c0a58ef 100644 --- a/go/internal/server/design/gamedata/quest_difficulty.go +++ b/go/internal/server/design/gamedata/quest_difficulty.go @@ -6,7 +6,7 @@ import ( ) // LoadQuestDifficulties reads the pack-specific selectable difficulties; -// normal (zero) is the base story chain and is absent from this table. +// normal (zero) is the base story chain and is selectable in every listed pack. func LoadQuestDifficulties(root, version string) (map[int]map[int]bool, error) { db, release, err := OpenDatabase(root, version, "common") if err != nil { @@ -27,7 +27,7 @@ func loadQuestDifficultiesDB(db *sql.DB) (map[int]map[int]bool, error) { if err := rows.Scan(&pack, &level); err != nil { return nil, err } - if pack <= 0 || level < 1 || level > 4 { + if pack <= 0 || level < 0 || level > 4 { return nil, fmt.Errorf("gamedata: invalid difficulty pack%d level%d", pack, level) } if result[pack] == nil { diff --git a/go/internal/server/design/gamedata/quests.go b/go/internal/server/design/gamedata/quests.go index 20d92fe..497a364 100644 --- a/go/internal/server/design/gamedata/quests.go +++ b/go/internal/server/design/gamedata/quests.go @@ -14,6 +14,8 @@ import ( type QuestDesign struct { ID int Type int + ConditionType int + ConditionCount int PriorQuestID int NextQuestID int AcceptCinemaName string @@ -101,7 +103,7 @@ func loadQuestDesignDB(db *sql.DB, packID int) (map[int]QuestDesign, error) { if err != nil { return nil, fmt.Errorf("gamedata: quest%d give items: %w", id, err) } - for field, dst := range map[int]*int{63: &entry.Type, 37: &entry.PriorQuestID, 35: &entry.NextQuestID, 62: &entry.TimelineStartMapID} { + for field, dst := range map[int]*int{63: &entry.Type, 11: &entry.ConditionType, 10: &entry.ConditionCount, 37: &entry.PriorQuestID, 35: &entry.NextQuestID, 62: &entry.TimelineStartMapID} { values, err := packedInts(proto, field) if err != nil || len(values) > 1 || (len(values) == 1 && values[0] > uint64(^uint32(0)>>1)) { return nil, fmt.Errorf("gamedata: invalid quest %d field%d", id, field) diff --git a/go/internal/server/design/gamedata/spine_interaction.go b/go/internal/server/design/gamedata/spine_interaction.go index f9458f7..c2765f9 100644 --- a/go/internal/server/design/gamedata/spine_interaction.go +++ b/go/internal/server/design/gamedata/spine_interaction.go @@ -74,7 +74,8 @@ func LoadSpineInteractionDesign(root, version string) (*SpineInteractionDesign, if err := read("SpineInteractionPointTable", func(raw []byte) error { v := func(field int) uint64 { n, _, _ := wire.Varint(raw, field); return n } key := InteractionPointKey{v(8), v(5), v(6)} - if key[0] == 0 || key[1] == 0 || key[2] == 0 { + // GameData 20261021182514 has point 16/2/0: proto3 omits a zero point id. + if key[0] == 0 || key[1] == 0 { return fmt.Errorf("gamedata: invalid interaction point") } d.Points[key] = InteractionPoint{Achievement: v(1) != 0, Connected: InteractionPointKey{key[0], v(3), v(4)}, RewardGroup: v(21), Motions: map[uint64]bool{}} diff --git a/go/internal/server/domain/battle/castle/mission_progress.go b/go/internal/server/domain/battle/castle/mission_progress.go new file mode 100644 index 0000000..f9b4c2a --- /dev/null +++ b/go/internal/server/domain/battle/castle/mission_progress.go @@ -0,0 +1,58 @@ +package castle + +import ( + "encoding/json" + "fmt" + + "bd2server/internal/server/domain/command" +) + +// MissionProgress is the saved castle progress mission conditions derive +// from. Pride floors include every archived season. +type MissionProgress struct { + // Towers maps a battle mode to its cleared tower floors. + Towers map[uint64]map[uint64]bool + PrideFought, PrideCleared map[uint64]bool + TotalWarBest uint64 +} + +// MissionProgress reads the castle save without rolling its season over. +func (s *Service) MissionProgress(ctx command.Context) (MissionProgress, error) { + out := MissionProgress{Towers: map[uint64]map[uint64]bool{}, PrideFought: map[uint64]bool{}, PrideCleared: map[uint64]bool{}} + v := state{} + raw, ok, err := ctx.State.LoadEntry("missions", "castle_state", "progress") + if err != nil { + return out, err + } + if ok && json.Unmarshal(raw, &v) != nil { + return out, fmt.Errorf("castle: invalid saved progress") + } + for _, t := range v.Towers { + if out.Towers[t.Mode] == nil { + out.Towers[t.Mode] = map[uint64]bool{} + } + out.Towers[t.Mode][t.ID] = true + } + seasons := []map[uint64]floor{v.Floors} + archived, err := ctx.State.ListEntries("missions", "castle_seasons") + if err != nil { + return out, err + } + for key, raw := range archived { + floors := map[uint64]floor{} + if err := json.Unmarshal(raw, &floors); err != nil { + return out, fmt.Errorf("castle: invalid archived season %s", key) + } + seasons = append(seasons, floors) + } + for _, floors := range seasons { + for id, f := range floors { + out.PrideFought[id] = true + if f.Highest > 0 { + out.PrideCleared[id] = true + } + } + } + out.TotalWarBest = sum(v.TotalWarScores) + return out, nil +} diff --git a/go/internal/server/domain/battle/castle/service.go b/go/internal/server/domain/battle/castle/service.go index 1b271ac..d3ee9cd 100644 --- a/go/internal/server/domain/battle/castle/service.go +++ b/go/internal/server/domain/battle/castle/service.go @@ -36,6 +36,7 @@ type Service struct { equipment *assets.EquipmentInventory wallet *assets.Wallet totalWarCompletion func(command.Context, string, uint64, []uint64) error + totalWarSettled func(command.Context, uint64) error totalWarTextCheck func(command.Context, string, string) error } diff --git a/go/internal/server/domain/battle/castle/totalwar.go b/go/internal/server/domain/battle/castle/totalwar.go index a12f98e..154aa8f 100644 --- a/go/internal/server/domain/battle/castle/totalwar.go +++ b/go/internal/server/domain/battle/castle/totalwar.go @@ -104,6 +104,11 @@ func (s *Service) totalWarEnd(ctx command.Context, v *state, req []byte) ([]byte if len(items) != 0 && len(items) != len(v.TotalWarRun.Costumes) { return nil, fmt.Errorf("castle: missing total war attacker score") } + if len(scores) > 0 && s.totalWarSettled != nil { + if e = s.totalWarSettled(ctx, total); e != nil { + return nil, e + } + } if len(scores) > 0 && (len(v.TotalWarScores) == 0 || total > sum(v.TotalWarScores)) { if s.totalWarCompletion != nil { if e = s.totalWarCompletion(ctx, v.TotalWarRun.Identity, total, v.TotalWarRun.Costumes); e != nil { @@ -207,6 +212,11 @@ func (s *Service) validateSavedTotalWarBattle(ctx command.Context, v *state, blu return nil } +// AttachTotalWarSettled observes every settled attempt with its total damage. +func (s *Service) AttachTotalWarSettled(f func(command.Context, uint64) error) { + s.totalWarSettled = f +} + func (s *Service) AttachTotalWarCompletion(f func(command.Context, string, uint64, []uint64) error) { s.totalWarCompletion = f } diff --git a/go/internal/server/domain/battle/castle/totalwar_deck_test.go b/go/internal/server/domain/battle/castle/totalwar_deck_test.go index a30f60c..1d45254 100644 --- a/go/internal/server/domain/battle/castle/totalwar_deck_test.go +++ b/go/internal/server/domain/battle/castle/totalwar_deck_test.go @@ -7,6 +7,7 @@ import ( "bd2server/internal/server/domain/roster" "bd2server/internal/server/protocol/wire" accountstate "bd2server/internal/server/storage/account" + "bd2server/internal/server/storage/instanceid" "bd2server/internal/server/storage/stateio" "bytes" "context" @@ -139,7 +140,7 @@ func (f *totalWarFixture) command(t *testing.T, run func(command.Context, totalW if e != nil { t.Fatal(e) } - ctx := command.Context{Identity: command.Identity{AccountID: "total-war-account", SessionID: "login"}, State: tx} + ctx := command.Context{Identity: command.Identity{AccountID: "total-war-account", SessionID: "login"}, State: tx, InstanceIDs: instanceid.New(filepath.Join(filepath.Dir(f.path), "instance-ids.db"))} rt := f.open(t, ctx) e = run(ctx, rt) if wantError { diff --git a/go/internal/server/domain/battle/hunting/dispatch.go b/go/internal/server/domain/battle/hunting/dispatch.go index 5246fd0..7964f67 100644 --- a/go/internal/server/domain/battle/hunting/dispatch.go +++ b/go/internal/server/domain/battle/hunting/dispatch.go @@ -33,6 +33,19 @@ func (s *Service) AttachDispatchProgress(progress func(command.Context, uint64) s.dispatchProgress = progress } +// AttachAPSpent observes hunting AP a battle or a dispatch spends directly; +// exchanges through the event economy report their own costs. +func (s *Service) AttachAPSpent(spent func(command.Context, uint64) error) { + s.apSpent = spent +} + +func (s *Service) recordAPSpent(ctx command.Context, cost uint64) error { + if s.apSpent == nil || cost == 0 { + return nil + } + return s.apSpent(ctx, cost) +} + func dispatchPlayed(j dispatchJob, seconds uint64) uint64 { if seconds == 0 { return j.Count diff --git a/go/internal/server/domain/battle/hunting/hunting.go b/go/internal/server/domain/battle/hunting/hunting.go index 8246728..8964d87 100644 --- a/go/internal/server/domain/battle/hunting/hunting.go +++ b/go/internal/server/domain/battle/hunting/hunting.go @@ -52,6 +52,7 @@ type Service struct { dispatchExchange func(command.Context, string, []gamedata.Reward, []gamedata.Reward) ([]byte, error) dispatchBonus func(*gamedata.DispatchDesign, []gamedata.BattleReward) ([]gamedata.BattleReward, error) dispatchProgress func(command.Context, uint64) error + apSpent func(command.Context, uint64) error eligibility func(ctx command.Context, _ int, _ uint64) error grant func(command.Context, string, []gamedata.Reward) ([]byte, error) apDesign *gamedata.HuntingAPDesign diff --git a/go/internal/server/domain/battle/hunting/progress.go b/go/internal/server/domain/battle/hunting/progress.go index 68725ba..c62b9fd 100644 --- a/go/internal/server/domain/battle/hunting/progress.go +++ b/go/internal/server/domain/battle/hunting/progress.go @@ -100,10 +100,13 @@ func (s *Service) exchangeAP(costs, rewards []gamedata.Reward) (snapshot, error) p = &st.Bonus } if cost { - if *p < r.Count { + // The client spends free AP first and takes the rest from bonus AP, + // whichever of the two the cost names. + if st.Free+st.Bonus < r.Count { return fmt.Errorf("hunting: insufficient AP") } - *p -= r.Count + fromFree := min(st.Free, r.Count) + st.Free, st.Bonus = st.Free-fromFree, st.Bonus-(r.Count-fromFree) } else { if r.Count > 2147483647-*p { return fmt.Errorf("hunting: AP overflow") diff --git a/go/internal/server/domain/battle/hunting/protocol_adapter.go b/go/internal/server/domain/battle/hunting/protocol_adapter.go index cdff59e..9f53753 100644 --- a/go/internal/server/domain/battle/hunting/protocol_adapter.go +++ b/go/internal/server/domain/battle/hunting/protocol_adapter.go @@ -221,6 +221,9 @@ func (s *Service) CompleteBattle(ctx command.Context, pack int, mode, monster, d next.Bonus -= cost - next.Free next.Free = 0 } + if err := s.recordAPSpent(ctx, cost); err != nil { + return nil, nil, err + } st := next.Packs[strconv.Itoa(pack)] if monster == g.BossID { if st.Highest < g.ID { @@ -547,6 +550,9 @@ func (s *Service) handleDispatch(ctx command.Context, path string, req []byte, s } else { next.Free -= free next.Bonus -= bonus + if e = s.recordAPSpent(ctx, free+bonus); e != nil { + return code, nil, true, e + } } if path == "/HuntDispatchStart" { now := uint64(time.Now().UnixMilli()) diff --git a/go/internal/server/domain/battle/ib/service_test.go b/go/internal/server/domain/battle/ib/service_test.go index 2d76b46..1e14e1c 100644 --- a/go/internal/server/domain/battle/ib/service_test.go +++ b/go/internal/server/domain/battle/ib/service_test.go @@ -73,7 +73,7 @@ func assertReservedOffer(t *testing.T, response, expected []byte) { } // LocalTextTable 7900025/26/84 and 7900122/23/29 (queried with gamedata_db.py, -// 20261012190548) define loss retries, one first-clear reward, run inventory, +// 20261021182514) define loss retries, one first-clear reward, run inventory, // post-battle shop refresh, and reservations. Request/response fields and base64 // process payload are independently specified by 2.36.7 Proto.Net and IBPacket. func TestBoardLifecyclePreservesBattleReservationAndFirstClear(t *testing.T) { diff --git a/go/internal/server/domain/battle/protocol_adapter.go b/go/internal/server/domain/battle/protocol_adapter.go index aa060ca..e313e01 100644 --- a/go/internal/server/domain/battle/protocol_adapter.go +++ b/go/internal/server/domain/battle/protocol_adapter.go @@ -390,6 +390,8 @@ func (s *Service) handle(ctx command.Context, path string, request []byte) (int, var resultCharacters [][]byte finishedHealth := make(map[uint64]uint64) participants := make(map[uint64]bool) + borrowed := make(map[uint64]bool) + seenResult := make(map[uint64]bool) if s.commitHealth != nil { for _, character := range state.InitialBlue { Index, _, err := wire.Varint(character, 2) @@ -398,6 +400,7 @@ func (s *Service) handle(ctx command.Context, path string, request []byte) (int, } if Index != 0 { participants[Index] = true + borrowed[Index] = value(character, 38) != 0 } } } @@ -408,13 +411,17 @@ func (s *Service) handle(ctx command.Context, path string, request []byte) (int, if err != nil || !present || !participants[Index] { return errors.New("battle: result character was not a battle participant") } - if _, duplicate := finishedHealth[Index]; duplicate { + if seenResult[Index] { return errors.New("battle: duplicate result character") } + seenResult[Index] = true hp, _, err := wire.Varint(field.Value, 3) if err != nil || hp > math.MaxInt64 { return errors.New("battle: invalid result health") } + if borrowed[Index] { + return nil + } finishedHealth[Index] = hp } resultCharacters = append(resultCharacters, field.Value) diff --git a/go/internal/server/domain/battle/pvp/mission_progress.go b/go/internal/server/domain/battle/pvp/mission_progress.go new file mode 100644 index 0000000..7f635c4 --- /dev/null +++ b/go/internal/server/domain/battle/pvp/mission_progress.go @@ -0,0 +1,56 @@ +package pvp + +import ( + "strconv" + "strings" + + "bd2server/internal/server/domain/command" +) + +// BestMirrorRankID is the best (lowest) MirrorRankTable ID the account has +// reached: every recorded promotion claim plus the current season rank once +// the account has fought this season. Zero means no rank was reached. +func (s *Service) BestMirrorRankID(ctx command.Context) (uint64, error) { + var best uint64 + reach := func(id uint64) { + if id != 0 && (best == 0 || id < best) { + best = id + } + } + entries, err := ctx.State.ListEntries("pvp", "promotion_claims") + if err != nil { + return 0, err + } + for key := range entries { + _, raw, found := strings.Cut(key, ":") + if !found { + continue + } + id, err := strconv.ParseUint(raw, 10, 64) + if err != nil { + return 0, err + } + reach(id) + } + season, err := s.current(Mirror) + if err != nil { + return best, nil + } + p, err := s.progress(Mirror, season.ID) + if err != nil { + return 0, err + } + if p.Attacks == 0 { + return best, nil + } + entry, err := s.rank(Mirror, season.ID) + if err != nil { + return 0, err + } + rank, err := s.rules.Design.MirrorRank(season.ID, p.VP, entry.Rank) + if err != nil { + return 0, err + } + reach(rank.ID) + return best, nil +} diff --git a/go/internal/server/domain/battle/pvp/snapshot.go b/go/internal/server/domain/battle/pvp/snapshot.go index 104d13a..d858f12 100644 --- a/go/internal/server/domain/battle/pvp/snapshot.go +++ b/go/internal/server/domain/battle/pvp/snapshot.go @@ -18,11 +18,14 @@ type OwnedSnapshotBuilder struct { Collection *roster.CollectionStore Equipment *assets.EquipmentInventory Buffs func(command.Context) ([]gamedata.PictorialBuffStat, error) - OwnerIndex uint64 + // CostumeCosts returns the current colosseum price of every ranked + // costume; unranked costumes cost ColosseumDefaults.CostDefault. + CostumeCosts func(command.Context) (map[uint64]uint64, error) + OwnerIndex uint64 } func (b *OwnedSnapshotBuilder) Freeze(ctx command.Context, r FreezeRequest) (FullSnapshot, error) { - if b.Design == nil || b.Characters == nil || b.Collection == nil || b.Equipment == nil || b.Buffs == nil || b.OwnerIndex == 0 { + if b.Design == nil || b.Characters == nil || b.Collection == nil || b.Equipment == nil || b.Buffs == nil || b.CostumeCosts == nil || b.OwnerIndex == 0 { return FullSnapshot{}, fmt.Errorf("pvp: incomplete snapshot builder") } previousContents := map[uint64][]byte{} @@ -62,13 +65,23 @@ func (b *OwnedSnapshotBuilder) Freeze(ctx command.Context, r FreezeRequest) (Ful for _, item := range allCostumes { costumeByIndex[item.InvenIndex] = item } - var banned []uint64 + var banned, costLimit []uint64 + var costs map[uint64]uint64 if r.Mode == Colosseum { banned, e = b.Design.ColosseumRule(r.Season, 30) if e != nil { return FullSnapshot{}, e } + if costLimit, e = b.Design.ColosseumRule(r.Season, 32); e != nil { + return FullSnapshot{}, e + } + if len(costLimit) != 0 { + if costs, e = b.CostumeCosts(ctx); e != nil { + return FullSnapshot{}, e + } + } } + var totalCost uint64 var result FullSnapshot var bindings []assets.PresetEquipmentBinding usedEquipment := map[uint64]bool{} @@ -95,6 +108,11 @@ func (b *OwnedSnapshotBuilder) Freeze(ctx command.Context, r FreezeRequest) (Ful if slices.Contains(banned, costume.ID) { return result, fmt.Errorf("pvp: selected costume banned this season") } + if cost, ranked := costs[costume.ID]; ranked { + totalCost += cost + } else { + totalCost += b.Design.Colosseum.CostDefault + } if e = b.validateSkills(index, entry, costumeByIndex); e != nil { return result, e } @@ -188,6 +206,9 @@ func (b *OwnedSnapshotBuilder) Freeze(ctx command.Context, r FreezeRequest) (Ful } } } + if len(costLimit) != 0 && totalCost > costLimit[0] { + return result, fmt.Errorf("pvp: costume cost %d exceeds season limit %d", totalCost, costLimit[0]) + } for index := range requested { if !deckCharacters[index] { return result, fmt.Errorf("pvp: saved equipment references a character outside formation") diff --git a/go/internal/server/domain/battle/pvp/snapshot_cost_test.go b/go/internal/server/domain/battle/pvp/snapshot_cost_test.go new file mode 100644 index 0000000..05d397b --- /dev/null +++ b/go/internal/server/domain/battle/pvp/snapshot_cost_test.go @@ -0,0 +1,82 @@ +package pvp + +import ( + "strings" + "testing" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + assets "bd2server/internal/server/domain/inventory" + "bd2server/internal/server/domain/roster" + "bd2server/internal/server/protocol/wire" + "bd2server/internal/server/storage/stateio" +) + +// GameData 20261021182514: ColosseumSeasonTable gives season 47 rule group 25 +// and season 46 group 24; only groups 25/26 carry rule 32 +// (C_RULE_COSTUME_COST_LIMIT) with value 160. Unranked costumes cost 30. +func TestColosseumFormationRejectsCostumeCostAboveSeasonLimit(t *testing.T) { + ctx := command.Context{Identity: command.Identity{AccountID: "a"}, State: stateio.NewMemory()} + var characters []roster.Character + var costumes []roster.Costume + for i := uint64(1); i <= 4; i++ { + characters = append(characters, roster.Character{InvenIndex: i, ID: 100 + i, Level: 1}) + costumes = append(costumes, roster.Costume{InvenIndex: 10 + i, ID: 1000 + i, UseChar: i}) + } + inventory, err := assets.OpenInventory(ctx, stateio.RootStore{}, nil) + if err != nil { + t.Fatal(err) + } + characterStore, err := roster.OpenCharacterStore(ctx, stateio.RootStore{}, characters, inventory, "", "") + if err != nil { + t.Fatal(err) + } + collection, err := roster.OpenCollectionStore(ctx, stateio.RootStore{}, costumes) + if err != nil { + t.Fatal(err) + } + equipment, err := assets.OpenEquipmentInventory(ctx, stateio.RootStore{}) + if err != nil { + t.Fatal(err) + } + if err = characterStore.AttachCollection(ctx, collection); err != nil { + t.Fatal(err) + } + if err = collection.BindBaseCharacters(ctx, characters); err != nil { + t.Fatal(err) + } + if err = equipment.AttachCharacters(ctx, characterStore); err != nil { + t.Fatal(err) + } + if err = equipment.AttachSlots(ctx, map[uint64]uint64{700: 0}); err != nil { + t.Fatal(err) + } + builder := &OwnedSnapshotBuilder{ + Design: &gamedata.PvpDesign{ + Colosseum: gamedata.ColosseumDefaults{CostDefault: 30}, + ColosseumSeasons: map[uint64]uint64{46: 24, 47: 25}, + ColosseumRules: map[uint64]map[uint64][]uint64{24: {}, 25: {32: {160}}}, + }, + Characters: characterStore, Collection: collection, Equipment: equipment, OwnerIndex: 1, + Buffs: func(command.Context) ([]gamedata.PictorialBuffStat, error) { return nil, nil }, + CostumeCosts: func(command.Context) (map[uint64]uint64, error) { + return map[uint64]uint64{1001: 50, 1002: 50, 1003: 50}, nil + }, + } + deck := func(indices ...uint64) [][]byte { + var out [][]byte + for _, index := range indices { + out = append(out, wire.AppendVarint(wire.AppendVarint(nil, 1, index), 4, 10+index)) + } + return out + } + if _, err := builder.Freeze(ctx, FreezeRequest{Mode: Colosseum, Season: 47, Deck: deck(1, 2, 4)}); err != nil { + t.Fatalf("cost 130 within limit 160 rejected: %v", err) + } + if _, err := builder.Freeze(ctx, FreezeRequest{Mode: Colosseum, Season: 47, Deck: deck(1, 2, 3, 4)}); err == nil || !strings.Contains(err.Error(), "exceeds season limit") { + t.Fatalf("cost 180 above limit 160 accepted: %v", err) + } + if _, err := builder.Freeze(ctx, FreezeRequest{Mode: Colosseum, Season: 46, Deck: deck(1, 2, 3, 4)}); err != nil { + t.Fatalf("season without cost rule enforced a limit: %v", err) + } +} diff --git a/go/internal/server/domain/battle/quest_victory.go b/go/internal/server/domain/battle/quest_victory.go new file mode 100644 index 0000000..f6e83e9 --- /dev/null +++ b/go/internal/server/domain/battle/quest_victory.go @@ -0,0 +1,49 @@ +package battle + +import ( + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + "fmt" + "slices" +) + +func questVictoryKey(pack int, quest, difficulty uint64) string { + return fmt.Sprintf("%d:%d:%d", pack, difficulty, quest) +} + +func (s *Service) HasWonQuest(ctx command.Context, pack, quest, difficulty int) (bool, error) { + if ctx.State == nil || pack <= 0 || quest <= 0 || difficulty < 0 || difficulty > 2 { + return false, nil + } + receipt, found, err := ctx.State.LoadEntry("battle", "quest_victory", questVictoryKey(pack, uint64(quest), uint64(difficulty))) + return found && len(receipt) != 0, err +} + +func (s *Service) recordQuestVictory(ctx command.Context, state *battleState) error { + if ctx.State == nil || state.Mode != 1 || state.Quest == 0 || state.Pack <= 0 { + return nil + } + if s.currentDifficulty == nil { + return fmt.Errorf("battle: quest victory difficulty unavailable") + } + difficulty, err := s.currentDifficulty(ctx) + if err != nil { + return err + } + loader := s.loadDifficultyDeck + if loader == nil { + loader = gamedata.ResolveQuestBattleDeck + } + enteredDeck := value(state.EntryResponse, 2) + if enteredDeck == 0 { + return fmt.Errorf("battle: quest victory entry deck unavailable") + } + resolved, err := loader(s.gameDataRoot, s.gameDataVersion, state.Pack, state.Monster, enteredDeck, difficulty) + if err != nil { + return fmt.Errorf("battle: verify quest victory difficulty: %w", err) + } + if resolved.DeckID != enteredDeck || !slices.Contains(resolved.QuestIDs, state.Quest) || state.EnterReceipt == "" { + return fmt.Errorf("battle: quest victory differs from entered encounter") + } + return ctx.State.PutEntry("battle", "quest_victory", questVictoryKey(state.Pack, state.Quest, difficulty), []byte(state.EnterReceipt)) +} diff --git a/go/internal/server/domain/battle/roguelike/battle.go b/go/internal/server/domain/battle/roguelike/battle.go index 18b9607..4dced29 100644 --- a/go/internal/server/domain/battle/roguelike/battle.go +++ b/go/internal/server/domain/battle/roguelike/battle.go @@ -271,6 +271,11 @@ func (s *Service) CompleteBattle(ctx command.Context, b []byte, key string) ([]b out = wire.AppendVarint(out, 23, f) out = wire.AppendBytes(out, 24, roomWire(*cleared)) } + if s.options.OnBattle != nil { + if e = s.options.OnBattle(ctx); e != nil { + return nil, e + } + } if e = s.save(ctx, v); e != nil { return nil, e } diff --git a/go/internal/server/domain/battle/roguelike/lifecycle_test.go b/go/internal/server/domain/battle/roguelike/lifecycle_test.go index 7c30eb8..2beaa43 100644 --- a/go/internal/server/domain/battle/roguelike/lifecycle_test.go +++ b/go/internal/server/domain/battle/roguelike/lifecycle_test.go @@ -81,9 +81,10 @@ func TestRunReopenBattleSettlementAndFirstClearCannotPayTwice(t *testing.T) { period := Period{Season: 1, Regular: 1, Active: true} economy := &testEconomy{} tickets := uint64(0) + battles := 0 proof := battle.SettlementEvidence{} open := func() *Service { - s, e := Open(stateio.EntrySnapshotStore{Domain: "battle", Bucket: "gameplay"}, d, Options{Access: func(command.Context) error { return nil }, Economy: economy, Owner: 1, Period: func(command.Context) (Period, error) { return period, nil }, Tickets: func(_ command.Context, _ string, count uint64) error { tickets += count; return nil }, Evidence: func(command.Context) battle.SettlementEvidence { return proof }}) + s, e := Open(stateio.EntrySnapshotStore{Domain: "battle", Bucket: "gameplay"}, d, Options{Access: func(command.Context) error { return nil }, Economy: economy, Owner: 1, Period: func(command.Context) (Period, error) { return period, nil }, Tickets: func(_ command.Context, _ string, count uint64) error { tickets += count; return nil }, Evidence: func(command.Context) battle.SettlementEvidence { return proof }, OnBattle: func(command.Context) error { battles++; return nil }}) if e != nil { t.Fatal(e) } @@ -197,9 +198,13 @@ func TestRunReopenBattleSettlementAndFirstClearCannotPayTwice(t *testing.T) { proof = battle.SettlementEvidence{Receipt: identity, Mode: mode, Deck: deck, Round: 0} end := req(seq, 1) seq++ + beforeBattles := battles if _, e = s.CompleteBattle(ctx, end, identity); e == nil { t.Fatal("settled a room without any started battle") } + if battles != beforeBattles { + t.Fatal("rejected settlement counted a battle") + } var blue [][]byte for i, c := range r.Characters { var costume costume @@ -226,9 +231,15 @@ func TestRunReopenBattleSettlementAndFirstClearCannotPayTwice(t *testing.T) { if e != nil { t.Fatal(e) } + if battles != beforeBattles+1 { + t.Fatalf("settled battle reported %d times", battles-beforeBattles) + } if _, e = s.CompleteBattle(ctx, end, identity); e == nil { t.Fatal("domain paid a settled room twice") } + if battles != beforeBattles+1 { + t.Fatal("settled room reported a battle twice") + } if len(out) == 0 { t.Fatal("battle omitted client state") } diff --git a/go/internal/server/domain/battle/roguelike/service.go b/go/internal/server/domain/battle/roguelike/service.go index dd7e022..9a77d25 100644 --- a/go/internal/server/domain/battle/roguelike/service.go +++ b/go/internal/server/domain/battle/roguelike/service.go @@ -48,6 +48,7 @@ type Options struct { Evidence func(command.Context) battle.SettlementEvidence Ranking Ranking Publish func(command.Context, uint64, uint64, uint64, uint64) error + OnBattle func(command.Context) error Owner uint64 } type Service struct { diff --git a/go/internal/server/domain/battle/session.go b/go/internal/server/domain/battle/session.go index 3b61af6..1a7e90b 100644 --- a/go/internal/server/domain/battle/session.go +++ b/go/internal/server/domain/battle/session.go @@ -242,6 +242,11 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (resu return code, nil, true, err } } + if path == "/BattleEnd" && value(request, 2) == 1 { + if err = s.recordQuestVictory(ctx, &before); err != nil { + return code, nil, true, err + } + } if s.completion != nil { completion := before.completion(value(request, 2) == 1) var extra []byte @@ -353,6 +358,8 @@ func (s *Service) resume(ctx command.Context) (int, []byte, bool, error) { out = wire.AppendVarint(out, 13, value(user, 4)) out = wire.AppendVarint(out, 14, value(user, 4)) out = wire.AppendVarint(out, 17, value(user, 1)) + // The client opens the armor-break gate at battle start; proto3 would otherwise read false. + out = wire.AppendVarint(out, 36, 1) } if (state.Mode == 23 || state.Mode == 26) && s.externalResume != nil { extra, err := s.externalResume(ctx, state.Mode, state.EnterReceipt) @@ -397,7 +404,7 @@ func (s *Service) previous(ctx command.Context, request []byte) (int, []byte, bo } snapshot := state.previousSnapshot() var out []byte - for from, to := range map[int]int{8: 1, 9: 2, 10: 3, 12: 4, 15: 5, 16: 6, 28: 9, 29: 10, 30: 11, 31: 12, 32: 13} { + for from, to := range map[int]int{8: 1, 9: 2, 10: 3, 12: 4, 15: 5, 16: 6, 28: 9, 29: 10, 30: 11, 31: 12, 32: 13, 35: 15, 36: 16} { if err := wire.Walk(snapshot, func(f wire.Field) error { if f.Number != from { return nil diff --git a/go/internal/server/domain/battle/session_test.go b/go/internal/server/domain/battle/session_test.go index 15d532f..8771759 100644 --- a/go/internal/server/domain/battle/session_test.go +++ b/go/internal/server/domain/battle/session_test.go @@ -42,6 +42,8 @@ func startPacket(seq, turn, hp, sp uint64, blue bool) ([]byte, []byte) { checkpoint = wire.AppendVarint(checkpoint, 10, 13) checkpoint = wire.AppendVarint(checkpoint, 28, turn+20) checkpoint = wire.AppendBytes(checkpoint, 29, wire.AppendVarint(nil, 1, turn+700)) + checkpoint = wire.AppendVarint(checkpoint, 35, turn+30) + checkpoint = wire.AppendVarint(checkpoint, 36, boolNumber(turn == 1)) checkpoint = wire.AppendVarint(checkpoint, 101, boolNumber(blue)) req := wire.AppendVarint(packet(seq), 2, 80) deck := wire.AppendVarint(nil, 1, 9001) @@ -85,7 +87,7 @@ func TestCheckpointReopenResumesAndRetriesPreviousBlueTurn(t *testing.T) { if err != nil { t.Fatal(err) } - if string(one(body, 1)) != base64.StdEncoding.EncodeToString(first) || value(body, 2) != 5 || value(body, 9) != 21 || value(one(body, 10), 1) != 701 || value(body, 7) != 0 { + if string(one(body, 1)) != base64.StdEncoding.EncodeToString(first) || value(body, 2) != 5 || value(body, 9) != 21 || value(one(body, 10), 1) != 701 || value(body, 7) != 0 || value(body, 15) != 31 || value(body, 16) != 1 { t.Fatalf("retry did not restore previous BLUE boundary: %x", body) } play(t, s, ctx, 3, 1, 100, 5, true) diff --git a/go/internal/server/domain/cafeteria/service.go b/go/internal/server/domain/cafeteria/service.go index 2de4174..2a48b7f 100644 --- a/go/internal/server/domain/cafeteria/service.go +++ b/go/internal/server/domain/cafeteria/service.go @@ -49,6 +49,8 @@ type Service struct { resetSeconds int64 owned func() []uint64 hasEpisode func(uint64) bool + datingTicket uint64 + holdsTicket func(command.Context, uint64) bool } func Open(ctx command.Context, store stateio.Store, d *gamedata.CafeteriaDesign, e Economy) (*Service, error) { @@ -94,7 +96,14 @@ func Open(ctx command.Context, store stateio.Store, d *gamedata.CafeteriaDesign, } func (s *Service) AttachOwnedCostumes(f func() []uint64) { s.owned = f } func (s *Service) AttachDatingHasEpisode(f func(uint64) bool) { s.hasEpisode = f } -func (s *Service) SetResetSeconds(v int64) { s.resetSeconds = v } + +// AttachDatingTicket names the content ticket the client checks before +// claiming the introduction (ContentUnlockDating) and how to test ownership. +func (s *Service) AttachDatingTicket(ticket uint64, holds func(command.Context, uint64) bool) { + s.datingTicket, s.holdsTicket = ticket, holds +} + +func (s *Service) SetResetSeconds(v int64) { s.resetSeconds = v } func (s *Service) day() string { return s.now().UTC().Add(time.Duration(9*3600-s.resetSeconds) * time.Second).Format("2006-01-02") } @@ -181,6 +190,9 @@ func noteWire(n *note) []byte { } func val(b []byte, n int) uint64 { v, _, _ := wire.Varint(b, n); return v } +// contentTicketType is EElementType.ContentTicket. +const contentTicketType = 19 + var codes = map[string]int{"/CafeteriaInfo": 351, "/CafeteriaSpawnReset": 352, "/CafeteriaLevelUp": 353, "/CafeteriaManageItemAdd": 354, "/CafeteriaRegularCostumeInteractionReward": 355, "/CafeteriaRegularCostumeInteractionAllReward": 356, "/CafeteriaCumulativeReward": 357, "/CafeteriaRegularCostumeNoteInfo": 358, "/CafeteriaRegularCostumeNoteReward": 359, "/CafeteriaRegularCostumeNoteAllReward": 360, "/CafeteriaIntroductionStoryReward": 371, "/CafeteriaDailyConnectionCostumeRefresh": 376, "/CafeteriaRareNpcInteractionReward": 413, "/CafeteriaEventNpcInteractionReward": 414} func (s *Service) Handle(ctx command.Context, path string, b []byte) (int, []byte, bool, error) { @@ -266,14 +278,16 @@ func (s *Service) handle(ctx command.Context, path string, b []byte, identity st return out, nil case "/CafeteriaIntroductionStoryReward": if s.state.Introduction { - return nil, nil + bundle, e := s.restoreDatingTicket(ctx) + if e != nil || bundle == nil { + return nil, e + } + return wire.AppendBytes(nil, 1, bundle), nil } - d := s.design.Default - bundle, e := s.economy.Apply(ctx, identity, nil, []gamedata.Reward{{Type: d.V(31), ID: d.V(30), Count: d.V(29)}}) + bundle, e := s.grantIntroduction(ctx, identity) if e != nil { return nil, e } - s.state.Introduction = true return wire.AppendBytes(nil, 1, bundle), nil case "/CafeteriaManageItemAdd": id := s.state.Manage + 1 @@ -505,3 +519,37 @@ func sortedNotes(m map[uint64]*note) []uint64 { slices.Sort(ids) return ids } + +// restoreDatingTicket grants the dating unlock ticket to a player whose +// introduction is complete but who does not hold it. The client claims the +// introduction on every cafeteria entry until the ticket exists, so ownership, +// not the introduction flag, decides; the fixed identity grants it once. +func (s *Service) restoreDatingTicket(ctx command.Context) ([]byte, error) { + if s.datingTicket == 0 || s.holdsTicket == nil || s.holdsTicket(ctx, s.datingTicket) { + return nil, nil + } + return s.economy.Apply(ctx, fmt.Sprintf("cafeteria:introduction-ticket:%d", s.datingTicket), nil, []gamedata.Reward{{Type: contentTicketType, ID: s.datingTicket, Count: 1}}) +} + +// grantIntroduction pays the CafeteriaDefaultTable visual-novel end reward and +// records the introduction as finished. +func (s *Service) grantIntroduction(ctx command.Context, identity string) ([]byte, error) { + d := s.design.Default + bundle, err := s.economy.Apply(ctx, identity, nil, []gamedata.Reward{{Type: d.V(31), ID: d.V(30), Count: d.V(29)}}) + if err != nil { + return nil, err + } + s.state.Introduction = true + return bundle, nil +} + +// ReconcileIntroduction runs at login: a finished introduction regains a +// missing dating ticket. Unfinished ones wait for the client's claim on the +// first entry into the cafeteria game card. +func (s *Service) ReconcileIntroduction(ctx command.Context) error { + if !s.state.Introduction { + return nil + } + _, err := s.restoreDatingTicket(ctx) + return err +} diff --git a/go/internal/server/domain/cafeteria/service_test.go b/go/internal/server/domain/cafeteria/service_test.go index 6cd9d35..3f0d8b9 100644 --- a/go/internal/server/domain/cafeteria/service_test.go +++ b/go/internal/server/domain/cafeteria/service_test.go @@ -221,3 +221,45 @@ func TestCafeteriaInteractionCapIsSharedAndResets(t *testing.T) { t.Fatal("missed days generated retroactive rewards") } } + +// Login never pays an unfinished introduction: it belongs to the first entry +// into the cafeteria game card. A finished one only regains a spent ticket. +func TestCafeteriaLoginOnlyRestoresTheTicketOfAFinishedIntroduction(t *testing.T) { + d := liveDesign(t) + store := stateio.NewMemory() + ctx := command.Context{Identity: command.Identity{SessionID: "introduction"}, State: store} + money := &ledger{balances: map[[2]uint64]uint64{}} + intro := [2]uint64{d.Default.V(31), d.Default.V(30)} + const ticket = 3007 // ContentOpenTable group19/detail1 (dating) ticket in current GameData + held := false + open := func() *Service { + t.Helper() + s, e := Open(ctx, stateio.RootStore{}, d, money) + if e != nil { + t.Fatal(e) + } + s.AttachDatingTicket(ticket, func(command.Context, uint64) bool { return held }) + s.AttachOwnedCostumes(func() []uint64 { return []uint64{d.Costumes.Groups[0][0]} }) + s.AttachDatingHasEpisode(func(uint64) bool { return true }) + return s + } + if e := open().ReconcileIntroduction(ctx); e != nil { + t.Fatal(e) + } + if money.balances[intro] != 0 || money.balances[[2]uint64{19, ticket}] != 0 { + t.Fatalf("login paid an unfinished introduction: introduction %d ticket %d", money.balances[intro], money.balances[[2]uint64{19, ticket}]) + } + if _, _, _, e := open().Handle(ctx, "/CafeteriaIntroductionStoryReward", wire.AppendVarint(nil, 1, 1)); e != nil { + t.Fatal(e) + } + if money.balances[intro] != d.Default.V(29) { + t.Fatalf("introduction reward %d, want %d", money.balances[intro], d.Default.V(29)) + } + // The ledger does not expand the box, so the ticket counts as spent. + if e := open().ReconcileIntroduction(ctx); e != nil { + t.Fatal(e) + } + if money.balances[intro] != d.Default.V(29) || money.balances[[2]uint64{19, ticket}] != 1 { + t.Fatalf("finished introduction login: introduction %d ticket %d, want %d and 1", money.balances[intro], money.balances[[2]uint64{19, ticket}], d.Default.V(29)) + } +} diff --git a/go/internal/server/domain/commerce/gacha/gacha.go b/go/internal/server/domain/commerce/gacha/gacha.go index 0670504..dc4d986 100644 --- a/go/internal/server/domain/commerce/gacha/gacha.go +++ b/go/internal/server/domain/commerce/gacha/gacha.go @@ -28,7 +28,7 @@ type Service struct { equipmentCatalog *gamedata.EquipmentGachaCatalog equipmentInventory *assets.EquipmentInventory onPreview func(ctx command.Context) error - onDraw func(ctx command.Context, _ uint64) error + onDraw func(ctx command.Context, groupID, count uint64) error schedule *ScheduleSeed previewEventIndex uint64 @@ -42,7 +42,7 @@ func (s *Service) TransientVersion() uint64 { return s.transientVersion } -func (s *Service) AttachDrawMission(callback func(ctx command.Context, _ uint64) error) { +func (s *Service) AttachDrawMission(callback func(ctx command.Context, groupID, count uint64) error) { s.onDraw = callback } @@ -96,7 +96,7 @@ func NewService(design *gamedata.InfiniteGachaDesign, regular *gamedata.RegularG return &Service{design: design, regular: regular, collection: collection, wallet: wallet, now: time.Now}, nil } -func (s *Service) dailyFreeAllowance(groupID, base uint64) (uint64, bool, error) { +func (s *Service) dailyAllowance(groupID, base uint64, paid bool) (uint64, bool, error) { if s.schedule == nil { return 0, false, nil } @@ -105,10 +105,15 @@ func (s *Service) dailyFreeAllowance(groupID, base uint64) (uint64, bool, error) if entry.GroupID != groupID || now < 0 || uint64(now) < entry.StartTime || uint64(now) > entry.EndTime { continue } - if entry.FreeCountBonus { - bonus := s.regular.GachaEventAddFreeCount() + bonus := uint64(0) + if paid && entry.CashCountBonus { + bonus = s.regular.GachaEventAddDailyPayCount() + } else if !paid && entry.FreeCountBonus { + bonus = s.regular.GachaEventAddFreeCount() + } + if bonus != 0 { if ^uint64(0)-base < bonus { - return 0, false, errors.New("gacha: daily free allowance overflows") + return 0, false, errors.New("gacha: daily allowance overflows") } base += bonus } diff --git a/go/internal/server/domain/commerce/gacha/history_test.go b/go/internal/server/domain/commerce/gacha/history_test.go index 4aea711..0352920 100644 --- a/go/internal/server/domain/commerce/gacha/history_test.go +++ b/go/internal/server/domain/commerce/gacha/history_test.go @@ -11,6 +11,7 @@ import ( "bd2server/internal/server/domain/roster" "bd2server/internal/server/protocol/wire" accountstate "bd2server/internal/server/storage/account" + "bd2server/internal/server/storage/instanceid" "bd2server/internal/server/storage/stateio" ) @@ -68,7 +69,7 @@ func (a *historyAccount) call(t *testing.T, path string, raw []byte) ([]byte, er t.Fatal(e) } defer func() { _ = tx.Rollback() }() - ctx := command.Context{Identity: command.Identity{AccountID: a.name, SessionID: "draw-session"}, State: tx} + ctx := command.Context{Identity: command.Identity{AccountID: a.name, SessionID: "draw-session"}, State: tx, InstanceIDs: instanceid.New(filepath.Join(filepath.Dir(a.path), "instance-ids.db"))} collection, e := roster.OpenCollectionStore(ctx, stateio.RootStore{}, nil) if e != nil { t.Fatal(e) diff --git a/go/internal/server/domain/commerce/gacha/protocol_adapter.go b/go/internal/server/domain/commerce/gacha/protocol_adapter.go index e5bd886..09b7adb 100644 --- a/go/internal/server/domain/commerce/gacha/protocol_adapter.go +++ b/go/internal/server/domain/commerce/gacha/protocol_adapter.go @@ -251,7 +251,7 @@ func (s *Service) multiBuy(ctx command.Context, request []byte, seq uint64) (int } var open bool var allowanceErr error - allowance, open, allowanceErr = s.dailyFreeAllowance(groupID, allowance) + allowance, open, allowanceErr = s.dailyAllowance(groupID, allowance, false) if allowanceErr != nil { return 146, nil, true, allowanceErr } @@ -362,11 +362,15 @@ func (s *Service) buyWithIdentity(ctx command.Context, request []byte, seq uint6 if !knownGroup { group = gamedata.GachaGroupDesign{ID: id, PointCount: 1} } + if identity == "" { + identity = s.requestIdentity(ctx, id, seq) + } + grant, already := s.collection.Grant(identity) isDailyFree := buyType == 0 && design.Count == 1 && design.FreeCountDay != 0 && knownGroup var freeDailyLimit uint64 - if isDailyFree { + if isDailyFree && !already { var open bool - freeDailyLimit, open, err = s.dailyFreeAllowance(group.ID, design.FreeCountDay) + freeDailyLimit, open, err = s.dailyAllowance(group.ID, design.FreeCountDay, false) if err != nil { return 146, nil, true, err } @@ -375,6 +379,17 @@ func (s *Service) buyWithIdentity(ctx command.Context, request []byte, seq uint6 } } isDailyPaid := buyType == 2 && design.Count == 1 && design.DailyPayGachaCount != 0 && design.DailyPayGachaPriceCount != 0 && knownGroup + var paidDailyLimit uint64 + if isDailyPaid && !already { + var open bool + paidDailyLimit, open, err = s.dailyAllowance(group.ID, design.DailyPayGachaCount, true) + if err != nil { + return 146, nil, true, err + } + if !open { + return 146, nil, true, fmt.Errorf("gacha: daily paid schedule is closed for group %d", group.ID) + } + } isMoonrise := buyType == 3 && design.PriceType == 19 && design.PriceID != 0 && knownGroup && group.GachaSubType == 1 && group.SelectCount != 0 && group.CashProductID != 0 completionGrant := fmt.Sprintf("special-gacha:%d:%d", group.ID, id) validOrdinary := buyType == 1 && (design.PriceType == 2 || design.PriceType == 3) @@ -392,10 +407,6 @@ func (s *Service) buyWithIdentity(ctx command.Context, request []byte, seq uint6 return 146, nil, true, fmt.Errorf("gacha: ticket %d is not valid for gacha %d", ticket.ID, id) } } - if identity == "" { - identity = s.requestIdentity(ctx, id, seq) - } - grant, already := s.collection.Grant(identity) if isMoonrise && !already { if _, completed := s.collection.Grant(completionGrant); completed { return 146, nil, true, errors.New("gacha: Moonrise product already drawn") @@ -429,13 +440,16 @@ func (s *Service) buyWithIdentity(ctx command.Context, request []byte, seq uint6 if isDailyFree { dailyLimit = freeDailyLimit } else if isDailyPaid { - dailyLimit = design.DailyPayGachaCount + dailyLimit = paidDailyLimit } if dailyLimit != 0 && s.collection.GachaDailyCount(day, group.ID, buyType) >= dailyLimit { return 146, nil, true, fmt.Errorf("gacha: daily draw exhausted group=%d buyType=%d", group.ID, buyType) } var ticketCount uint64 for _, ticket := range tickets { + if ticket.Count > uint64(design.Count)-ticketCount { + return 146, nil, true, errors.New("gacha: invalid ticket count") + } ticketCount += ticket.Count } if ticketCount > uint64(design.Count) || (buyType != 1 && ticketCount != 0) || (design.PriceType != 3 && ticketCount != 0) { @@ -509,13 +523,20 @@ func (s *Service) buyWithIdentity(ctx command.Context, request []byte, seq uint6 charge = design.Price / uint64(design.Count) * remaining chargePaid = design.PriceType == 2 } + var freeCharge, paidCharge uint64 if charge != 0 { currency := s.wallet.Snapshot(ctx) if chargePaid && currency.Jewelry < charge { return 146, nil, true, errors.New("gacha: insufficient paid jewelry") } - if !chargePaid && currency.FreeJewelry < charge { - return 146, nil, true, errors.New("gacha: insufficient free jewelry") + if chargePaid { + paidCharge = charge + } else { + freeCharge = min(currency.FreeJewelry, charge) + paidCharge = charge - freeCharge + if currency.Jewelry < paidCharge { + return 146, nil, true, errors.New("gacha: insufficient jewelry") + } } } if len(tickets) != 0 { @@ -541,19 +562,18 @@ func (s *Service) buyWithIdentity(ctx command.Context, request []byte, seq uint6 return 146, nil, true, err } } else { - if _, err := s.wallet.SpendFreeJewelryOnce(ctx, identity, charge); err != nil { + if _, err := s.wallet.SpendTotalJewelryOnce(ctx, identity, charge); err != nil { return 146, nil, true, err } } } } historyCost = append(historyConsumedTickets(tickets), historyConsumedTickets(moonriseCost)...) - if charge != 0 { - kind := uint64(3) - if chargePaid { - kind = 2 - } - historyCost = append(historyCost, historyConsumedTickets([]assets.Item{{Type: kind, Count: charge}})...) + if freeCharge != 0 { + historyCost = append(historyCost, historyConsumedTickets([]assets.Item{{Type: 3, Count: freeCharge}})...) + } + if paidCharge != 0 { + historyCost = append(historyCost, historyConsumedTickets([]assets.Item{{Type: 2, Count: paidCharge}})...) } purchase := roster.GachaPurchase{Group: group, BuyType: buyType, Fixed: fixedStates, SelectionApplySortIDs: selectionApplySortIDs} if isMoonrise { @@ -589,7 +609,7 @@ func (s *Service) buyWithIdentity(ctx command.Context, request []byte, seq uint6 } } if !already && s.onDraw != nil { - if err := s.onDraw(ctx, uint64(design.Count)); err != nil { + if err := s.onDraw(ctx, group.ID, uint64(design.Count)); err != nil { return 146, nil, true, fmt.Errorf("gacha: draw mission: %w", err) } } @@ -604,7 +624,8 @@ func (s *Service) buyEquipmentWithIdentity(ctx command.Context, seq, buyType uin return 146, nil, true, errors.New("gacha: equipment inventory not attached") } isDailyFree := buyType == 0 && !design.TicketOnly && design.Count == 1 && design.FreeCountDay != 0 - if (buyType != 1 && !isDailyFree) || (!design.TicketOnly && design.PriceType != 3) { + isDailyPaid := buyType == 2 && !design.TicketOnly && design.Count == 1 && design.DailyPayGachaCount != 0 && design.DailyPayGachaPriceCount != 0 + if (buyType != 1 && !isDailyFree && !isDailyPaid) || (!design.TicketOnly && design.PriceType != 3) { return 146, nil, true, fmt.Errorf("gacha: unsupported equipment buy type %d", buyType) } if design.TicketOnly && len(tickets) == 0 { @@ -620,26 +641,30 @@ func (s *Service) buyEquipmentWithIdentity(ctx command.Context, seq, buyType uin if !hasGroup && !design.TicketOnly { return 146, nil, true, fmt.Errorf("gacha: equipment gacha %d has no group", design.ID) } - if isDailyFree && len(tickets) != 0 { - return 146, nil, true, errors.New("gacha: daily free equipment draw cannot use tickets") - } - var freeDailyLimit uint64 - if isDailyFree { - var open bool - var err error - freeDailyLimit, open, err = s.dailyFreeAllowance(group.ID, design.FreeCountDay) - if err != nil { - return 146, nil, true, err - } - if !open { - return 146, nil, true, fmt.Errorf("gacha: daily free equipment schedule is closed for group %d", group.ID) - } + if (isDailyFree || isDailyPaid) && len(tickets) != 0 { + return 146, nil, true, errors.New("gacha: discounted equipment draw cannot use tickets") } if identity == "" { identity = s.requestIdentity(ctx, design.ID, seq) } - historyCost := historyConsumedTickets(tickets) grant, already := s.collection.Grant(identity) + var dailyLimit uint64 + if (isDailyFree || isDailyPaid) && !already { + var open bool + var err error + base := design.FreeCountDay + if isDailyPaid { + base = design.DailyPayGachaCount + } + dailyLimit, open, err = s.dailyAllowance(group.ID, base, isDailyPaid) + if err != nil { + return 146, nil, true, err + } + if !open { + return 146, nil, true, fmt.Errorf("gacha: daily equipment schedule is closed for group %d", group.ID) + } + } + historyCost := historyConsumedTickets(tickets) var entries []assets.Equipment if already { for sort := 0; sort < design.Count; sort++ { @@ -650,11 +675,14 @@ func (s *Service) buyEquipmentWithIdentity(ctx command.Context, seq, buyType uin entries = append(entries, entry) } } else { - if isDailyFree && s.collection.GachaDailyCount(dailyResetKey(s.now()), group.ID, 0) >= freeDailyLimit { + if dailyLimit != 0 && s.collection.GachaDailyCount(dailyResetKey(s.now()), group.ID, buyType) >= dailyLimit { return 146, nil, true, fmt.Errorf("gacha: daily equipment draw exhausted group=%d", group.ID) } var ticketCount uint64 for _, ticket := range tickets { + if ticket.Count > uint64(design.Count)-ticketCount { + return 146, nil, true, errors.New("gacha: invalid equipment ticket count") + } ticketCount += ticket.Count } if ticketCount > uint64(design.Count) || (design.TicketOnly && ticketCount != uint64(design.Count)) { @@ -672,10 +700,25 @@ func (s *Service) buyEquipmentWithIdentity(ctx command.Context, seq, buyType uin if design.TicketOnly { return 146, nil, true, errors.New("gacha: ticket-only equipment draw cannot use diamonds") } - if _, err := s.wallet.SpendFreeJewelryOnce(ctx, identity, design.Price/uint64(design.Count)*remain); err != nil { - return 146, nil, true, err + charge := design.Price / uint64(design.Count) * remain + var freeCharge uint64 + if isDailyPaid { + charge = design.DailyPayGachaPriceCount + if _, err := s.wallet.SpendJewelryOnce(ctx, identity, charge); err != nil { + return 146, nil, true, err + } + } else { + freeCharge = min(s.wallet.Snapshot(ctx).FreeJewelry, charge) + if _, err := s.wallet.SpendTotalJewelryOnce(ctx, identity, charge); err != nil { + return 146, nil, true, err + } + } + if freeCharge != 0 { + historyCost = append(historyCost, historyConsumedTickets([]assets.Item{{Type: 3, Count: freeCharge}})...) + } + if paidCharge := charge - freeCharge; paidCharge != 0 { + historyCost = append(historyCost, historyConsumedTickets([]assets.Item{{Type: 2, Count: paidCharge}})...) } - historyCost = append(historyCost, historyConsumedTickets([]assets.Item{{Type: 3, Count: design.Price / uint64(design.Count) * remain}})...) } var fixed gamedata.EquipmentFixedDesign var priorSR, priorUR uint64 @@ -725,8 +768,8 @@ func (s *Service) buyEquipmentWithIdentity(ctx command.Context, seq, buyType uin grant, err = s.collection.GrantEquipmentDraw(ctx, identity) } else { purchase := roster.GachaPurchase{Group: gamedata.GachaGroupDesign{ID: group.ID, PointCount: group.PointCount}, BuyType: buyType, Fixed: fixedStates} - if isDailyFree { - purchase.DailyKey, purchase.DailyLimit = dailyResetKey(s.now()), freeDailyLimit + if dailyLimit != 0 { + purchase.DailyKey, purchase.DailyLimit = dailyResetKey(s.now()), dailyLimit } grant, err = s.collection.GrantEquipmentPurchase(ctx, identity, uint64(len(entries)), purchase) } @@ -749,7 +792,7 @@ func (s *Service) buyEquipmentWithIdentity(ctx command.Context, seq, buyType uin } } if !already && s.onDraw != nil { - if err := s.onDraw(ctx, uint64(design.Count)); err != nil { + if err := s.onDraw(ctx, group.ID, uint64(design.Count)); err != nil { return 146, nil, true, fmt.Errorf("gacha: equipment draw mission: %w", err) } } @@ -1004,6 +1047,7 @@ func (s *Service) confirm(ctx command.Context, request []byte) (int, []byte, boo if s.design == nil || group != s.design.ProductGroupID || productID != s.design.ProductID || saleGroup != s.design.SaleGroup { return 0, nil, true, fmt.Errorf("gacha: unsupported cash product group=%d product=%d", group, productID) } + _, already := s.collection.Grant(s.infiniteGrant()) grant, err := s.collection.ConfirmInfinite(ctx, s.infiniteGrant(), s.design) if err != nil { return 0, nil, true, err @@ -1015,6 +1059,11 @@ func (s *Service) confirm(ctx command.Context, request []byte) (int, []byte, boo if err := s.recordHistory(ctx, s.infiniteGrant(), s.design.GroupID, s.design.GachaID, 1, uint64(s.design.Count), 1, 0, response, grant, nil); err != nil { return 61, nil, true, err } + if !already && s.onDraw != nil { + if err := s.onDraw(ctx, s.design.GroupID, uint64(s.design.Count)); err != nil { + return 61, nil, true, fmt.Errorf("gacha: draw mission: %w", err) + } + } return 61, response, true, nil } @@ -1307,6 +1356,11 @@ func (s *Service) confirmFirstGacha(ctx command.Context, _ []byte, seq, buyType if err := s.collection.RecordGachaBatch(ctx, responseIdentity, firstGachaResponseDigest, response); err != nil { return 146, nil, true, err } + if s.onDraw != nil { + if err := s.onDraw(ctx, s.first.Group.ID, uint64(s.first.Count)); err != nil { + return 146, nil, true, fmt.Errorf("gacha: draw mission: %w", err) + } + } if s.onPreview != nil { if err := s.onPreview(ctx); err != nil { return 146, nil, true, fmt.Errorf("gacha: update first gacha mission: %w", err) diff --git a/go/internal/server/domain/commerce/gacha/selection_integration_test.go b/go/internal/server/domain/commerce/gacha/selection_integration_test.go index 58a5eab..6525a2c 100644 --- a/go/internal/server/domain/commerce/gacha/selection_integration_test.go +++ b/go/internal/server/domain/commerce/gacha/selection_integration_test.go @@ -11,7 +11,7 @@ import ( "bd2server/internal/server/domain/roster" ) -// GameData 20261012190548: group 10001 -> Gacha 100/101 -> RewardGroup +// GameData 20261021182514: group 10001 -> Gacha 100/101 -> RewardGroup // 100/101 -> five-star group 70011 contains costume 806. The live rejected // request on 2026-10-17 used group=10001, slot=0, item=806. func TestCurrentGameDataTwelvePickAcceptsReportedCostume(t *testing.T) { diff --git a/go/internal/server/domain/commerce/protocol_adapter.go b/go/internal/server/domain/commerce/protocol_adapter.go index 3e3ddaa..dc039ca 100644 --- a/go/internal/server/domain/commerce/protocol_adapter.go +++ b/go/internal/server/domain/commerce/protocol_adapter.go @@ -279,7 +279,8 @@ func (s *Service) buy(ctx command.Context, session string, request []byte) (int, quotes := make([]Product, len(lines)) for i, l := range lines { if !s.predecessorBought(ctx, v, l.Key) { - return 61, nil, true, fmt.Errorf("commerce: preceding package purchase required") + return 61, nil, true, fmt.Errorf("commerce: preceding package purchase required: product=%d:%d:%d predecessors=%v", + l.Key.GroupID, l.Key.ProductID, l.Key.SaleGroup, s.predecessors[l.Key]) } d, ok := s.catalog.Design(l.Key) if !ok { diff --git a/go/internal/server/domain/commerce/service.go b/go/internal/server/domain/commerce/service.go index fb39efd..1f1f4bb 100644 --- a/go/internal/server/domain/commerce/service.go +++ b/go/internal/server/domain/commerce/service.go @@ -66,18 +66,18 @@ func (s *Service) AttachDelegate(d PurchaseDelegate) { s.delegate = d } func (s *Service) AttachPurchaseHook(h PurchaseHook) { s.hook = h } func (s *Service) AttachLegacyCounts(p CountProvider) { s.legacy = p } -// AttachPackageRules enforces the client's type-2/type-8 step and relay -// ordering using versioned contentsGroupId/contentsSortId, never SKU numbers. +// Only the relay prefab enforces an order. BundleGroupPackageUI uses the +// contents sort index for display and allows each product independently. func (s *Service) AttachPackageRules(packages []gamedata.CashPackageDesign) error { rules := map[gamedata.CashProductKey][]gamedata.CashProductKey{} for _, p := range packages { - if (p.PackageType != 2 && p.PackageType != 8) || p.ContentsGroupID == 0 || p.ContentsSortID <= 1 { + if !p.Sequential || p.ContentsGroupID == 0 || p.ContentsSortID <= 1 { continue } key := gamedata.CashProductKey{GroupID: p.GroupID, ProductID: p.ID, SaleGroup: p.SaleGroup} var prior []gamedata.CashProductKey for _, q := range packages { - if q.PackageType == p.PackageType && q.ContentsGroupID == p.ContentsGroupID && q.ContentsSortID == p.ContentsSortID-1 { + if q.GroupID == p.GroupID && q.PackageType == p.PackageType && q.ContentsGroupID == p.ContentsGroupID && q.ContentsSortID == p.ContentsSortID-1 { prior = append(prior, gamedata.CashProductKey{GroupID: q.GroupID, ProductID: q.ID, SaleGroup: q.SaleGroup}) } } diff --git a/go/internal/server/domain/dating/service.go b/go/internal/server/domain/dating/service.go index 2c3dab8..a1b10e3 100644 --- a/go/internal/server/domain/dating/service.go +++ b/go/internal/server/domain/dating/service.go @@ -90,6 +90,17 @@ func (s *Service) LastClear(group uint64) uint64 { } return 0 } + +// ClearedEpisodeGroups counts the dating groups with a cleared episode. +func (s *Service) ClearedEpisodeGroups() uint64 { + var count uint64 + for _, p := range s.state.Episodes { + if p.Clear > 0 { + count++ + } + } + return count +} func (s *Service) day() string { return s.now().UTC().Add(time.Duration(9*3600-s.resetSeconds) * time.Second).Format("2006-01-02") } @@ -248,7 +259,14 @@ func (s *Service) handle(ctx command.Context, path string, b []byte, identity st } text := val(b, 4) if r.V(5) == 1 && r.V(9) == 1 { - if text == 0 || (text != r.V(3) && text != r.V(4)) { + // The client acknowledges a message with one text option using text + // id zero: its answer button reports zero when either option is + // empty (DatingChatOwnSelectAnswer.isSingleSelectOption). + if r.V(3) == 0 || r.V(4) == 0 { + if text != 0 { + return nil, errors.New("dating: invalid answer") + } + } else if text == 0 || (text != r.V(3) && text != r.V(4)) { return nil, errors.New("dating: invalid answer") } } else if text != 0 { diff --git a/go/internal/server/domain/dating/service_test.go b/go/internal/server/domain/dating/service_test.go index 22d663e..5cb4cbd 100644 --- a/go/internal/server/domain/dating/service_test.go +++ b/go/internal/server/domain/dating/service_test.go @@ -136,8 +136,9 @@ func TestDatingFullConversationPurchaseAndReconnect(t *testing.T) { t.Helper() for _, id := range d.Messages.Groups[messageGroup] { r, _ := d.Messages.Row(messageGroup, id) + // The client sends zero when either answer text id is empty. text := uint64(0) - if r.V(5) == 1 && r.V(9) == 1 { + if r.V(5) == 1 && r.V(9) == 1 && r.V(3) != 0 && r.V(4) != 0 { text = r.V(3) } must("/DatingMessageUpdate", messageGroup, id, text) @@ -303,8 +304,9 @@ func TestNewRelationshipRejectsPurchasedEncounterAP(t *testing.T) { } for _, id := range d.Messages.Groups[msg] { m, _ := d.Messages.Row(msg, id) + // The client sends zero when either answer text id is empty. text := uint64(0) - if m.V(5) == 1 && m.V(9) == 1 { + if m.V(5) == 1 && m.V(9) == 1 && m.V(3) != 0 && m.V(4) != 0 { text = m.V(3) } must("/DatingMessageUpdate", msg, id, text) diff --git a/go/internal/server/domain/events/actions/protocol_adapter.go b/go/internal/server/domain/events/actions/protocol_adapter.go index f278f16..8d9c6b8 100644 --- a/go/internal/server/domain/events/actions/protocol_adapter.go +++ b/go/internal/server/domain/events/actions/protocol_adapter.go @@ -4,6 +4,7 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" "bd2server/internal/server/domain/events" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/protocol/wire" "crypto/sha256" "encoding/hex" @@ -565,7 +566,7 @@ func (s *Service) handle(ctx command.Context, path string, b []byte, identity st s.state.DailyNormal++ } if s.progress != nil { - if e = s.progress(ctx, 349, r.V(2), 1); e != nil { + if e = s.progress(ctx, conditions.Event{Type: conditions.FieldSpawnEventReward, Sub: r.V(2), Count: 1}); e != nil { return nil, e } } @@ -864,13 +865,13 @@ func (s *Service) CompleteBattle(ctx command.Context, req []byte, receipt string priorLines := s.tacticsLines(uid) s.state.Tactics[uid] = append(s.state.Tactics[uid], stage) if s.progress != nil { - if e := s.progress(ctx, 346, stage, 1); e != nil { + if e := s.progress(ctx, conditions.Event{Type: conditions.TacticsBingoBattleWin, Sub: stage, Count: 1}); e != nil { _ = json.Unmarshal(before, &s.state) return nil, e } lines := s.tacticsLines(uid) if lines > priorLines { - if e := s.progress(ctx, 347, 0, lines-priorLines); e != nil { + if e := s.progress(ctx, conditions.Event{Type: conditions.TacticsBingoLineClear, Count: lines - priorLines}); e != nil { _ = json.Unmarshal(before, &s.state) return nil, e } @@ -879,7 +880,7 @@ func (s *Service) CompleteBattle(ctx command.Context, req []byte, receipt string g, _ := s.design.Row("TacticsBingoGroupTable", 3, v.ID) n := uint64(5) - g.V(4) if uint64(len(s.state.Tactics[uid])) == n*n { - if e := s.progress(ctx, 348, 0, 1); e != nil { + if e := s.progress(ctx, conditions.Event{Type: conditions.TacticsBingoAllClear, Count: 1}); e != nil { _ = json.Unmarshal(before, &s.state) return nil, e } diff --git a/go/internal/server/domain/events/actions/service.go b/go/internal/server/domain/events/actions/service.go index a818d9b..4db55fc 100644 --- a/go/internal/server/domain/events/actions/service.go +++ b/go/internal/server/domain/events/actions/service.go @@ -7,6 +7,7 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" "bd2server/internal/server/domain/events" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/storage/stateio" "encoding/json" "errors" @@ -57,7 +58,7 @@ type Service struct { friendship func(uint64) uint64 chargeInfo func(ctx command.Context) ([]byte, error) - progress func(ctx command.Context, _ uint64, _ uint64, _ uint64) error + progress func(command.Context, conditions.Event) error voteTotals func(uint64, uint64) (map[uint64]uint64, error) miniContent MiniContentResolver miniDesign *gamedata.MiniContentDesign @@ -131,7 +132,7 @@ func (s *Service) init() { func (s *Service) AttachFriendshipLevel(f func(uint64) uint64) { s.friendship = f } func (s *Service) AttachChargeInfo(f func(ctx command.Context) ([]byte, error)) { s.chargeInfo = f } -func (s *Service) AttachProgress(f func(ctx command.Context, _ uint64, _ uint64, _ uint64) error) { +func (s *Service) AttachProgress(f func(command.Context, conditions.Event) error) { s.progress = f } diff --git a/go/internal/server/domain/events/ap_refresh.go b/go/internal/server/domain/events/ap_refresh.go index 911a948..00d55d0 100644 --- a/go/internal/server/domain/events/ap_refresh.go +++ b/go/internal/server/domain/events/ap_refresh.go @@ -96,6 +96,7 @@ func (e *Economy) CanApply(ctx command.Context, costs []gamedata.Reward) error { } var wallet, ap, life []gamedata.Reward var items []assets.Item + balances := maps.Clone(s.Balances) totals := map[[2]uint64]uint64{} for _, r := range costs { k := [2]uint64{r.Type, r.ID} @@ -114,8 +115,8 @@ func (e *Economy) CanApply(ctx command.Context, costs []gamedata.Reward) error { case apCurrency(r.Type): ap = append(ap, r) case extraCurrency(r.Type): - if r.ID != 0 || s.Balances[r.Type] < n { - return fmt.Errorf("events: insufficient currency") + if r.ID != 0 || !spendCurrency(balances, r.Type, n) { + return fmt.Errorf("events: insufficient currency %d", r.Type) } case inventoryType(r.Type): selected, err := e.items.SelectMutable(ctx, r.Type, r.ID, n) diff --git a/go/internal/server/domain/events/economy.go b/go/internal/server/domain/events/economy.go index 80a4158..a8ac474 100644 --- a/go/internal/server/domain/events/economy.go +++ b/go/internal/server/domain/events/economy.go @@ -4,6 +4,7 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" assets "bd2server/internal/server/domain/inventory" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/domain/roster" "bd2server/internal/server/storage/stateio" "crypto/sha256" @@ -51,6 +52,7 @@ type Economy struct { graph rewardResolver hunting HuntingAP prestige map[uint64]uint64 + progress func(command.Context, conditions.Event) error prestigePortrait func() uint64 datingCap uint64 apCaps map[uint64]uint64 @@ -152,3 +154,35 @@ func (e *Economy) resolveGranted(rewards []gamedata.BattleReward) ([]gamedata.Ba } return e.graph.Resolve(rewards) } + +// freeStackPairs pairs each free AP currency with its stacked counterpart. +// The client spends either one from the free balance first and takes the rest +// from the stack (CommonPacket's currency subtraction and +// GetHavePayPriceElementCount). +var freeStackPairs = map[uint64][2]uint64{ + 30: {30, 31}, 31: {30, 31}, // event AP + 32: {32, 33}, 33: {32, 33}, // torch light AP + 35: {35, 38}, 38: {35, 38}, // roguelike tickets + 41: {41, 42}, 42: {41, 42}, // dating AP + 52: {52, 53}, 53: {52, 53}, // colosseum tickets +} + +// spendCurrency deducts n of typ the way the client does and reports whether +// the balances covered it; balances are unchanged when they did not. +func spendCurrency(balances map[uint64]uint64, typ, n uint64) bool { + pair, ok := freeStackPairs[typ] + if !ok { + if balances[typ] < n { + return false + } + balances[typ] -= n + return true + } + free, stack := balances[pair[0]], balances[pair[1]] + if free+stack < n { + return false + } + fromFree := min(free, n) + balances[pair[0]], balances[pair[1]] = free-fromFree, stack-(n-fromFree) + return true +} diff --git a/go/internal/server/domain/events/mission_progress.go b/go/internal/server/domain/events/mission_progress.go new file mode 100644 index 0000000..59d58be --- /dev/null +++ b/go/internal/server/domain/events/mission_progress.go @@ -0,0 +1,53 @@ +package events + +import ( + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + assets "bd2server/internal/server/domain/inventory" + "bd2server/internal/server/domain/progression/conditions" +) + +// AttachProgress reports currency spends and gains to mission conditions. +func (e *Economy) AttachProgress(record func(command.Context, conditions.Event) error) { + e.progress = record +} + +// MissionCurrency folds the currencies the client spends as one balance into +// the EElementType mission conditions name: a stacked AP into its free AP, +// and BonusHuntingAP (23) into FreeHuntingAP (21). +func MissionCurrency(t uint64) uint64 { + if pair, ok := freeStackPairs[t]; ok { + return pair[0] + } + if t == 23 { + return 21 + } + return t +} + +func currency(t uint64) bool { return walletCurrency(t) || extraCurrency(t) || apCurrency(t) } + +// recordCurrencies reports one applied exchange. Items are observed by the +// event mission inventory projection instead. +func (e *Economy) recordCurrencies(ctx command.Context, consumed []assets.Item, granted []gamedata.BattleReward) error { + if e.progress == nil { + return nil + } + var events []conditions.Event + for _, c := range consumed { + if currency(c.Type) && c.Count != 0 { + events = append(events, conditions.Event{Type: conditions.ItemCurrencyUse, Sub: MissionCurrency(c.Type), Count: c.Count}) + } + } + for _, r := range granted { + if currency(r.Type) && r.Count != 0 { + events = append(events, conditions.Event{Type: conditions.ItemCurrencyGet, Sub: MissionCurrency(r.Type), Count: r.Count}) + } + } + for _, event := range events { + if err := e.progress(ctx, event); err != nil { + return err + } + } + return nil +} diff --git a/go/internal/server/domain/events/play/achievement_progress_test.go b/go/internal/server/domain/events/play/achievement_progress_test.go index e00e3ab..2effda3 100644 --- a/go/internal/server/domain/events/play/achievement_progress_test.go +++ b/go/internal/server/domain/events/play/achievement_progress_test.go @@ -14,7 +14,7 @@ func TestRhythmAchievementsRequireCompletedHardAndAllChallengeSongs(t *testing.T testRow(5, 2, 8, 30000, 2, 30000, 1, 30000, 10, 1, 4, 1), } h.design.Tables["RhythmGameCharTable"] = [][]byte{testRow(2, 1)} - // GameData 20261012190548 groups 2006/2014 require a HARD clear/all CHALLENGE + // GameData 20261021182514 groups 2006/2014 require a HARD clear/all CHALLENGE // songs; groups 2023/2024 require a score of 30000/50000 in any difficulty. design := &gamedata.AchievementCounterDesign{Conditions: map[int]gamedata.AchievementCondition{ 2006: {Type: 125, SubType: 1}, 2014: {Type: 125, SubType: 2}, @@ -70,7 +70,7 @@ func TestHopscotchAchievementsCountClearsWithoutCountingPartialRunsOrRetries(t * h := newPlayHarness(t) h.design.Tables["HopscotchDefaultTable"] = [][]byte{testRow(4, 80, 9, 300)} h.design.Tables["HopscotchStageTable"] = [][]byte{testRow(6, 1)} - // GameData 20261012190548 groups 2025..2028 count clear/full-completion/ + // GameData 20261021182514 groups 2025..2028 count clear/full-completion/ // no-continue clears; a partial run after an earlier clear proves no new clear. design := &gamedata.AchievementCounterDesign{Conditions: map[int]gamedata.AchievementCondition{ 2025: {Type: 158}, 2026: {Type: 159}, 2027: {Type: 160}, diff --git a/go/internal/server/domain/events/play/field_run.go b/go/internal/server/domain/events/play/field_run.go index 88897d0..79ba7c2 100644 --- a/go/internal/server/domain/events/play/field_run.go +++ b/go/internal/server/domain/events/play/field_run.go @@ -4,6 +4,7 @@ import ( "bd2server/internal/common/util" "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/domain/ranking" "bd2server/internal/server/protocol/wire" "encoding/json" @@ -131,10 +132,10 @@ func (s *Service) fieldRunGame(ctx command.Context, path string, req []byte, st } st.Runs[f] = a if s.onProgress != nil { - if err := s.onProgress(ctx, 343, c.ID, 1); err != nil { + if err := s.onProgress(ctx, conditions.Event{Type: conditions.MiniGamePlay, Sub: c.ID, Count: 1}); err != nil { return nil, err } - if err := s.onProgress(ctx, 315, c.ID, 1); err != nil { + if err := s.onProgress(ctx, conditions.Event{Type: conditions.EventFieldMiniGamePlay, Sub: c.ID, Count: 1}); err != nil { return nil, err } } diff --git a/go/internal/server/domain/events/play/packman.go b/go/internal/server/domain/events/play/packman.go index 903961f..6c87ac3 100644 --- a/go/internal/server/domain/events/play/packman.go +++ b/go/internal/server/domain/events/play/packman.go @@ -2,6 +2,7 @@ package eventplay import ( "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/protocol/wire" "fmt" "math" @@ -159,23 +160,23 @@ func (s *Service) endPackMan(ctx command.Context, req []byte, a Run, st *snapsho } st.Records[recKey(a.UID, 0, a.Mode, a.Family)] = r if s.onProgress != nil { - if err := s.onProgress(ctx, 364, a.Game, 1); err != nil { - return nil, err - } - condition := uint64(360) - if a.Mode == 2 { - condition = 362 - } - if err := s.onProgress(ctx, condition, a.Game, 1); err != nil { - return nil, err + events := []conditions.Event{{Type: conditions.PackManPlayCount, Count: 1}} + // Request field 3 is the chaser that caught the player; zero otherwise. + if chaser := num(req, 3); chaser > 0 { + caught := conditions.PackManNormalGameOver + if a.Mode == 2 { + caught = conditions.PackManChallengeGameOver + } + events = append(events, conditions.Event{Type: caught, Sub: chaser, Count: 1}) } if endType == 3 { - if err := s.onProgress(ctx, 361, a.Game, 1); err != nil { - return nil, err - } + events = append(events, conditions.Event{Type: conditions.PackManNormalClear, Count: 1}) } if a.Mode == 2 && endType == 2 { - if err := s.onProgress(ctx, 363, a.Game, score); err != nil { + events = append(events, conditions.Event{Type: conditions.PackManChallengeTimeoutScore, Sub: score, Count: 1}) + } + for _, event := range events { + if err := s.onProgress(ctx, event); err != nil { return nil, err } } diff --git a/go/internal/server/domain/events/play/play.go b/go/internal/server/domain/events/play/play.go index ea0fd02..a31013d 100644 --- a/go/internal/server/domain/events/play/play.go +++ b/go/internal/server/domain/events/play/play.go @@ -5,6 +5,7 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" "bd2server/internal/server/domain/events" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/domain/ranking" "bd2server/internal/server/protocol/staticdata" "bd2server/internal/server/storage/stateio" @@ -79,7 +80,7 @@ type Service struct { arcadeRanks *ranking.Arcade arcadeProfile func(command.Context) (ranking.ArcadeProfile, error) arcadeGuilds func(command.Context, []uint64) (map[uint64][]byte, error) - onProgress func(command.Context, uint64, uint64, uint64) error + onProgress func(command.Context, conditions.Event) error onRhythmResult func(command.Context, events.RhythmResult) error achievementDesign *gamedata.AchievementCounterDesign achievementProgress map[[2]uint64]uint64 diff --git a/go/internal/server/domain/events/play/progress.go b/go/internal/server/domain/events/play/progress.go index e5ddc22..4d0a9ae 100644 --- a/go/internal/server/domain/events/play/progress.go +++ b/go/internal/server/domain/events/play/progress.go @@ -3,9 +3,10 @@ package eventplay import ( "bd2server/internal/server/domain/command" "bd2server/internal/server/domain/events" + "bd2server/internal/server/domain/progression/conditions" ) -func (s *Service) AttachProgress(fn func(ctx command.Context, condition, sub, count uint64) error) { +func (s *Service) AttachProgress(fn func(command.Context, conditions.Event) error) { s.onProgress = fn } diff --git a/go/internal/server/domain/events/play/protocol_adapter.go b/go/internal/server/domain/events/play/protocol_adapter.go index 33fee70..24c8bfb 100644 --- a/go/internal/server/domain/events/play/protocol_adapter.go +++ b/go/internal/server/domain/events/play/protocol_adapter.go @@ -4,6 +4,7 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" "bd2server/internal/server/domain/events" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/protocol/wire" "bytes" "encoding/binary" @@ -170,9 +171,9 @@ func (s *Service) progress(ctx command.Context, path string, req []byte, rk stri for _, count := range a.Killed { total += count } - total -= previousKills - if total > 0 { - if e = s.onProgress(ctx, 319, a.Game, total); e != nil { + // McMiniGameSurvivalKillMonsterCount compares the kills of one run. + if total > previousKills { + if e = s.onProgress(ctx, conditions.Event{Type: conditions.MiniGameSurvivalKillCount, Sub: total, Count: 1}); e != nil { return nil, e } } @@ -712,10 +713,10 @@ func (s *Service) game(ctx command.Context, path string, req []byte, session str } next.Runs[runKey] = a if s.onProgress != nil { - if e = s.onProgress(ctx, 343, c.ID, 1); e != nil { + if e = s.onProgress(ctx, conditions.Event{Type: conditions.MiniGamePlay, Sub: c.ID, Count: 1}); e != nil { return nil, e } - if e = s.onProgress(ctx, 315, c.ID, 1); e != nil { + if e = s.onProgress(ctx, conditions.Event{Type: conditions.EventFieldMiniGamePlay, Sub: c.ID, Count: 1}); e != nil { return nil, e } } @@ -774,30 +775,32 @@ func (s *Service) game(ctx command.Context, path string, req []byte, session str if s.onProgress != nil { switch f { case "Survival": - for condition, count := range map[uint64]uint64{316: a.Level, 317: score} { - if count == 0 { - continue - } - if e = s.onProgress(ctx, condition, c.ID, count); e != nil { - return nil, e - } - } mapRow, err := s.survivalMap(a.MapGroup, a.Stage) if err != nil { return nil, err } + // FieldMiniGameMapTable field 10 is the difficulty that + // McMiniGameSurvivalMapClear lists in its params; the survived + // seconds are the score McMiniGameSurvivalLifeTime compares. + events := []conditions.Event{ + {Type: conditions.MiniGameSurvivalCharLevel, Sub: a.Level, Count: 1}, + {Type: conditions.MiniGameSurvivalLifeTime, Sub: a.MapGroup, Param: score, Count: 1}, + } if num(req, 2) == 0 && score >= num(mapRow, 9) { - if e = s.onProgress(ctx, 320, a.Stage, 1); e != nil { + events = append(events, conditions.Event{Type: conditions.MiniGameSurvivalMapClear, Sub: a.MapGroup, Param: num(mapRow, 10), Count: 1}) + } + for _, event := range events { + if e = s.onProgress(ctx, event); e != nil { return nil, e } } case "Defense": - if e = s.onProgress(ctx, 322, c.ID, score); e != nil { + if e = s.onProgress(ctx, conditions.Event{Type: conditions.MiniGameDefenseWaveClear, Sub: score, Count: 1}); e != nil { return nil, e } case "Action": if nativeResult.Clear { - if e = s.onProgress(ctx, 323, a.Char, 1); e != nil { + if e = s.onProgress(ctx, conditions.Event{Type: conditions.MiniGameActionMonster, Sub: a.Char, Count: 1}); e != nil { return nil, e } } diff --git a/go/internal/server/domain/events/play/single_player.go b/go/internal/server/domain/events/play/single_player.go index 57ec054..257731b 100644 --- a/go/internal/server/domain/events/play/single_player.go +++ b/go/internal/server/domain/events/play/single_player.go @@ -5,6 +5,7 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" "bd2server/internal/server/domain/events" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/protocol/wire" "fmt" "math" @@ -141,10 +142,10 @@ func (s *Service) singlePlayerGame(ctx command.Context, path string, req []byte, } st.Runs[f] = a if s.onProgress != nil { - if err := s.onProgress(ctx, 343, c.ID, 1); err != nil { + if err := s.onProgress(ctx, conditions.Event{Type: conditions.MiniGamePlay, Sub: c.ID, Count: 1}); err != nil { return nil, err } - if err := s.onProgress(ctx, 315, c.ID, 1); err != nil { + if err := s.onProgress(ctx, conditions.Event{Type: conditions.EventFieldMiniGamePlay, Sub: c.ID, Count: 1}); err != nil { return nil, err } } diff --git a/go/internal/server/domain/events/play/survival.go b/go/internal/server/domain/events/play/survival.go index c4d053c..9cf8776 100644 --- a/go/internal/server/domain/events/play/survival.go +++ b/go/internal/server/domain/events/play/survival.go @@ -4,6 +4,7 @@ import ( "bd2server/internal/common/util" "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/protocol/wire" "crypto/sha256" "encoding/binary" @@ -548,10 +549,14 @@ func (s *Service) survivalSkillUp(ctx command.Context, req []byte, a *Run, st *s s.collectSurvival(st, *a, 0, id) s.collectSurvival(st, *a, 1, id) if a.SkillLevels[id] == num(group, 2) && s.onProgress != nil { - if err := s.onProgress(ctx, 318, a.Game, 1); err != nil { + maxed, err := s.maxedSurvivalSkills(*a) + if err != nil { return nil, err } - if err := s.onProgress(ctx, 321, id, 1); err != nil { + if err := s.onProgress(ctx, conditions.Event{Type: conditions.MiniGameSurvivalSkillMaxCount, Sub: maxed, Count: 1}); err != nil { + return nil, err + } + if err := s.onProgress(ctx, conditions.Event{Type: conditions.MiniGameSurvivalSkillMax, Sub: id, Count: 1}); err != nil { return nil, err } } @@ -643,3 +648,19 @@ func (s *Service) survivalFallback(a *Run, group []byte) ([]byte, error) { a.HP += heal return wire.AppendVarint(nil, 3, heal), nil } + +// maxedSurvivalSkills counts the skills of one run at their configured +// FieldMiniGameSkillGroupTable maximum level. +func (s *Service) maxedSurvivalSkills(a Run) (uint64, error) { + var maxed uint64 + for id, level := range a.SkillLevels { + group, err := s.design.Row("FieldMiniGameSkillGroupTable", 1, id) + if err != nil { + return 0, err + } + if level >= num(group, 2) { + maxed++ + } + } + return maxed, nil +} diff --git a/go/internal/server/domain/events/protocol_adapter.go b/go/internal/server/domain/events/protocol_adapter.go index eb65295..a95a313 100644 --- a/go/internal/server/domain/events/protocol_adapter.go +++ b/go/internal/server/domain/events/protocol_adapter.go @@ -276,10 +276,9 @@ func (e *Economy) consumeAndGrant(ctx command.Context, identity string, consumed } apCosts = append(apCosts, r) case extraCurrency(c.Type): - if c.ID != 0 || c.InvenIndex != 0 || s.Balances[c.Type] < c.Count { + if c.ID != 0 || c.InvenIndex != 0 || !spendCurrency(s.Balances, c.Type, c.Count) { return nil, fmt.Errorf("events: insufficient currency %d", c.Type) } - s.Balances[c.Type] -= c.Count default: if !inventoryType(c.Type) { return nil, fmt.Errorf("events: unsupported consumed item type %d", c.Type) @@ -487,6 +486,9 @@ func (e *Economy) consumeAndGrant(ctx command.Context, identity string, consumed if err = e.store.Save(ctx.State, "event_economy", data); err != nil { return nil, err } + if err = e.recordCurrencies(ctx, consumed, expanded); err != nil { + return nil, err + } return bundle, nil } diff --git a/go/internal/server/domain/events/resource_items_test.go b/go/internal/server/domain/events/resource_items_test.go index 89ec6a7..bf1dbbb 100644 --- a/go/internal/server/domain/events/resource_items_test.go +++ b/go/internal/server/domain/events/resource_items_test.go @@ -43,7 +43,7 @@ type resourceRuntime struct { func openResourceRuntime(t *testing.T, state stateio.AtomicEntryStore, initial bool) resourceRuntime { t.Helper() - ctx := command.Context{Identity: command.Identity{AccountID: "selector", SessionID: "login"}, State: state} + ctx := command.Context{Identity: command.Identity{AccountID: "selector", SessionID: "login"}, State: state, InstanceIDs: stateio.NewMemory()} store := stateio.RootStore{} items, err := assets.OpenInventory(ctx, store, nil) if err != nil { diff --git a/go/internal/server/domain/events/tasks/account_state.go b/go/internal/server/domain/events/tasks/account_state.go new file mode 100644 index 0000000..b15dc6d --- /dev/null +++ b/go/internal/server/domain/events/tasks/account_state.go @@ -0,0 +1,75 @@ +package eventtasks + +import ( + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/events" + "bd2server/internal/server/domain/progression/conditions" +) + +// AccountState reports, for each condition, the progress durable account +// state already proves (character levels, cleared quests, castle floors, ...). +// Conditions that state cannot prove report zero. +type AccountState func(ctx command.Context, specs []conditions.Spec) ([]uint64, error) + +// AttachAccountState supplies the state-derived progress source. Such tasks +// complete from state rather than from live events only, so progress made +// before a task's schedule existed, or while it was locked, still counts. +func (s *Service) AttachAccountState(source AccountState) { s.accountState = source } + +// ReconcileAccountState backfills every active state-derived task and persists +// only when progress changed. Values never decrease and never exceed targets. +func (s *Service) ReconcileAccountState(ctx command.Context) error { + changed, err := s.reconcileAccountState(ctx) + if err != nil || !changed { + return err + } + return s.save(ctx) +} + +func (s *Service) reconcileAccountState(ctx command.Context) (bool, error) { + if s.accountState == nil { + return false, nil + } + type pending struct { + schedule events.Schedule + task gamedata.EventTask + } + var tasks []pending + var specs []conditions.Spec + for _, schedule := range s.taskSchedules() { + if schedule.Type != 4 || !s.active(schedule) { + continue + } + period := s.missionPeriod(schedule) + for _, task := range s.design.Missions { + if !s.availableTask(ctx, schedule, task) { + continue + } + if m := s.state.Missions[scheduleKey(schedule)+"/"+key(task.ID)]; m != nil && m.Period == period && (m.Claimed || m.Value >= missionTarget(task)) { + continue + } + tasks = append(tasks, pending{schedule, task}) + specs = append(specs, taskSpec(task)) + } + } + if len(tasks) == 0 { + return false, nil + } + values, err := s.accountState(ctx, specs) + if err != nil { + return false, err + } + changed := false + for i, p := range tasks { + if i >= len(values) || values[i] == 0 { + continue + } + m := s.mission(p.schedule, p.task.ID) + if value := min(values[i], missionTarget(p.task)); value > m.Value { + m.Value = value + changed = true + } + } + return changed, nil +} diff --git a/go/internal/server/domain/events/tasks/gacha_progress.go b/go/internal/server/domain/events/tasks/gacha_progress.go new file mode 100644 index 0000000..df3e241 --- /dev/null +++ b/go/internal/server/domain/events/tasks/gacha_progress.go @@ -0,0 +1,132 @@ +package eventtasks + +import ( + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/events" + "bd2server/internal/server/protocol/wire" + "encoding/json" + "fmt" + "slices" + "time" +) + +func (s *Service) AttachGachaHistory(source func(command.Context, uint64) ([]byte, error)) { + s.gachaHistory = source +} + +// Reconstruct missing progress from durable ownership and successful draw history. +func (s *Service) reconcileGachaProgress(ctx command.Context, inventory *InventorySnapshot, history bool) error { + type progress struct { + schedule events.Schedule + task gamedata.EventTask + start int64 + value uint64 + } + var pending []progress + needCostumes := false + earliest := int64(-1) + for _, v := range s.taskSchedules() { + if v.Type != 4 || !s.active(v) { + continue + } + for _, t := range s.design.Missions { + if (t.Type != 103 && t.Type != 104 && (t.Type != 105 || !history || s.gachaHistory == nil)) || !s.availableTask(ctx, v, t) { + continue + } + start := v.Start + now := s.now().UTC() + period := "" + switch s.design.MissionGroups[v.ID].Type { + case 1: + start = max(start, now.Truncate(24*time.Hour).UnixMilli()) + period = s.day() + case 2: + days := (int(now.Weekday()) + 6) % 7 + start = max(start, now.Truncate(24*time.Hour).AddDate(0, 0, -days).UnixMilli()) + year, week := now.ISOWeek() + period = fmt.Sprintf("%d-%d", year, week) + } + if m := s.state.Missions[scheduleKey(v)+"/"+key(t.ID)]; m != nil && m.Period == period && (m.Claimed || m.Value >= t.Target) { + continue + } + pending = append(pending, progress{schedule: v, task: t, start: start}) + if t.Type == 105 { + if earliest < 0 || start < earliest { + earliest = start + } + } else { + needCostumes = true + } + } + } + if len(pending) == 0 { + return nil + } + if needCostumes && inventory == nil && s.provider != nil { + snapshot, err := s.inventorySnapshot(ctx) + if err != nil { + return err + } + inventory = &snapshot + } + for i := range pending { + p := &pending[i] + if p.task.Type == 105 || inventory == nil { + continue + } + for _, costume := range inventory.Costumes { + if p.task.SubType != 0 && p.task.SubType != costume.ID || len(p.task.Params) != 0 && !slices.Contains(p.task.Params, costume.ID) { + continue + } + if p.task.Type == 103 { + p.value = min(p.task.Target, p.value+1) + } else { + p.value = min(p.task.Target, p.value+min(costume.Level, p.task.Target)) + } + } + } + if earliest >= 0 { + raw, err := s.gachaHistory(ctx, uint64(max(0, earliest-1))) + if err != nil { + return err + } + if err = wire.Walk(raw, func(f wire.Field) error { + if f.Number != 1 || f.Type != 2 { + return nil + } + group, count, at := scalar(f.Value, 1), scalar(f.Value, 4), scalar(f.Value, 13) + for i := range pending { + p := &pending[i] + if p.task.Type == 105 && (p.task.SubType == 0 || p.task.SubType == group) && (len(p.task.Params) == 0 || slices.Contains(p.task.Params, group)) && at >= uint64(p.start) && at < uint64(p.schedule.End) && at <= uint64(s.now().UnixMilli()) { + p.value += min(count, p.task.Target-p.value) + } + } + return nil + }); err != nil { + return err + } + } + before, err := json.Marshal(s.state) + if err != nil { + return err + } + changed := false + for _, p := range pending { + if p.value == 0 { + continue + } + m := s.mission(p.schedule, p.task.ID) + if p.value > m.Value { + m.Value = p.value + changed = true + } + } + if !changed { + return nil + } + if err = s.save(ctx); err != nil { + _ = json.Unmarshal(before, &s.state) + } + return err +} diff --git a/go/internal/server/domain/events/tasks/inventory_deltas_test.go b/go/internal/server/domain/events/tasks/inventory_deltas_test.go new file mode 100644 index 0000000..6788793 --- /dev/null +++ b/go/internal/server/domain/events/tasks/inventory_deltas_test.go @@ -0,0 +1,42 @@ +package eventtasks + +import ( + "testing" + + "bd2server/internal/server/domain/progression/conditions" +) + +func TestInventoryDeltas(t *testing.T) { + service := &Service{before: InventorySnapshot{ + Items: map[[2]uint64]uint64{{8, 5}: 10, {9, 7}: 5}, + Equipment: map[uint64]InventoryEquipment{1: {Level: 2}}, + Costumes: map[uint64]InventoryCostume{3: {ID: 7, Level: 1}}, + }} + after := InventorySnapshot{ + Items: map[[2]uint64]uint64{{8, 5}: 4, {9, 6}: 2, {9, 7}: 3}, + Equipment: map[uint64]InventoryEquipment{1: {Level: 3}}, + Costumes: map[uint64]InventoryCostume{3: {ID: 7, Level: 2}}, + } + got := map[conditions.Event]bool{} + for _, event := range service.inventoryDeltas(after) { + got[event] = true + } + want := []conditions.Event{ + {Type: conditions.ResourceUse, Sub: 5, Count: 6}, + {Type: conditions.ItemCurrencyGet, Sub: 9, Count: 2}, + {Type: conditions.EquipmentUpgrade, Count: 1}, + {Type: conditions.CostumeUpgrade, Sub: 7, Count: 1}, + } + for _, event := range want { + if !got[event] { + t.Fatalf("missing event %+v in %v", event, got) + } + } + nonResource := conditions.Event{Type: conditions.ResourceUse, Sub: 7, Count: 2} + if got[nonResource] { + t.Fatalf("non-resource spend reported as McResourceUse: %v", got) + } + if len(got) != len(want) { + t.Fatalf("inventory deltas = %v, want %v", got, want) + } +} diff --git a/go/internal/server/domain/events/tasks/observer.go b/go/internal/server/domain/events/tasks/observer.go index ba3b90e..19db5e2 100644 --- a/go/internal/server/domain/events/tasks/observer.go +++ b/go/internal/server/domain/events/tasks/observer.go @@ -2,7 +2,7 @@ package eventtasks import ( "bd2server/internal/server/domain/command" - "encoding/json" + "bd2server/internal/server/domain/progression/conditions" ) func (s *Service) BeginLogin(ctx command.Context) { @@ -21,6 +21,9 @@ func (s *Service) inventorySnapshot(ctx command.Context) (InventorySnapshot, err } func (s *Service) BeforeDispatch(ctx command.Context, _ string, _ []byte) error { + if err := s.reconcileRewardLevelProgress(ctx); err != nil { + return err + } s.beforeMissions = s.visibleMissionValues(ctx) if s.provider == nil { @@ -41,26 +44,15 @@ func (s *Service) BeforeDispatch(ctx command.Context, _ string, _ []byte) error } func (s *Service) AttachInventoryProvider(p InventoryProvider) { s.provider = p } -func (s *Service) CompleteSingleTargetEvent(ctx command.Context, condition uint64, unlocked func(command.Context, uint64, uint64) bool) error { +// AttachProgress routes observed inventory deltas through the account-wide +// mission recorder, so regular daily/weekly missions see them as well. +func (s *Service) AttachProgress(record func(command.Context, conditions.Event) error) { + s.progress = record +} - before, _ := json.Marshal(s.state) - for _, v := range s.taskSchedules() { - if !s.active(v) { - continue - } - for _, t := range s.design.Missions { - if t.Type != condition || t.SubType != 0 || t.Target != 1 || len(t.Params) != 0 || !s.availableTask(ctx, v, t) { - continue - } - if (t.UnlockPack > 0 || t.UnlockQuest > 0) && (unlocked == nil || !unlocked(ctx, t.UnlockPack, t.UnlockQuest)) { - continue - } - s.mission(v, t.ID).Value = 1 - } +func (s *Service) record(ctx command.Context, event conditions.Event) error { + if s.progress != nil { + return s.progress(ctx, event) } - if e := s.save(ctx); e != nil { - _ = json.Unmarshal(before, &s.state) - return e - } - return nil + return s.RecordEvent(ctx, event, s.unlocked) } diff --git a/go/internal/server/domain/events/tasks/protocol_adapter.go b/go/internal/server/domain/events/tasks/protocol_adapter.go index 97f740c..5a7233a 100644 --- a/go/internal/server/domain/events/tasks/protocol_adapter.go +++ b/go/internal/server/domain/events/tasks/protocol_adapter.go @@ -3,6 +3,7 @@ package eventtasks import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/protocol/wire" "crypto/sha256" "encoding/hex" @@ -16,6 +17,9 @@ import ( "time" ) +// Define_ElementType _TYPE_RESOURCE; McResourceUse counts only this type. +const resourceItemType uint64 = 8 + func (s *Service) Handle(ctx command.Context, path string, req []byte) (int, []byte, bool, error) { codes := map[string]int{"/Attendance": 0, "/AttendanceInfo": 0, "/EventRewardHistory": 0, "/EventReward": 151, "/EventMissionInfo": 127, "/MissionClear": 120, "/MissionUpdate": 119, "/PassInfo": 124, "/PassReward": 126, "/PassBuy": 129, "/LoginEvent": 0} code, found := codes[path] @@ -73,6 +77,17 @@ func (s *Service) Handle(ctx command.Context, path string, req []byte) (int, []b func scalar(b []byte, n int) uint64 { v, _, _ := wire.Varint(b, n); return v } func (s *Service) handle(ctx command.Context, path string, b []byte, identity string) ([]byte, error) { + if path == "/EventMissionInfo" || path == "/MissionUpdate" || path == "/MissionClear" { + if err := s.reconcileGachaProgress(ctx, nil, true); err != nil { + return nil, err + } + if err := s.reconcileRewardLevelProgress(ctx); err != nil { + return nil, err + } + if _, err := s.reconcileAccountState(ctx); err != nil { + return nil, err + } + } switch path { case "/Attendance", "/LoginEvent": today := s.day() @@ -286,9 +301,9 @@ func (s *Service) handle(ctx command.Context, path string, b []byte, identity st } m := s.mission(v, id) progress := min(value, t.Target) - // Homescreen slots are saved in ClientLocalInfo; MissionUpdate is - // the native client's only server notification of this UI action. - if t.Type == 39 && t.SubType == 0 && (len(t.Params) == 0 || slices.Contains(t.Params, uint64(0))) { + // These UI actions (e.g. homescreen slots saved in ClientLocalInfo) + // reach the server only through the client's MissionUpdate. + if slices.Contains(conditions.ClientReported, t.Type) && t.SubType == 0 && conditions.AnyParam(t.Params) { m.Value = max(m.Value, progress) } else if progress > m.Value { return fmt.Errorf("eventtasks: client progress exceeds authoritative gameplay event=%d group=%d mission=%d condition=%d subtype=%d client=%d authoritative=%d target=%d", event, t.Group, id, t.Type, t.SubType, value, m.Value, t.Target) @@ -555,6 +570,15 @@ func (s *Service) handle(ctx command.Context, path string, b []byte, identity st } func (s *Service) Notify(ctx command.Context) ([]byte, error) { + if err := s.reconcileGachaProgress(ctx, nil, true); err != nil { + return nil, err + } + if err := s.reconcileRewardLevelProgress(ctx); err != nil { + return nil, err + } + if err := s.ReconcileAccountState(ctx); err != nil { + return nil, err + } var out []byte for _, v := range s.taskSchedules() { @@ -587,7 +611,7 @@ func (s *Service) Notify(ctx command.Context) ([]byte, error) { return out, nil } -func (s *Service) AfterDispatch(ctx command.Context, path string, request, response []byte) ([]byte, error) { +func (s *Service) AfterDispatch(ctx command.Context, _ string, _, _ []byte) ([]byte, error) { if s.provider != nil { version := s.inventoryObservationVersion() if s.inventoryReady && version != "" && version == s.observationVersion { @@ -598,66 +622,28 @@ func (s *Service) AfterDispatch(ctx command.Context, path string, request, respo if e != nil { return nil, e } - rk := fmt.Sprintf("observer:%s:%s:%d", ctx.SessionID, path, scalar(request, 1)) - - _, seen := s.state.Receipts[rk] - - if !seen { - type delta struct{ condition, sub, count uint64 } - var deltas []delta - for kind, old := range s.before.Items { - current := after.Items[kind] - if current < old { - condition := uint64(12) - if kind[1] == 0 { - condition = 11 - } - deltas = append(deltas, delta{condition, kind[0], old - current}) + // Deltas come from the before/after views of this request, so a cached + // replay that changes nothing records nothing. + deltas := s.inventoryDeltas(after) + if len(deltas) > 0 { + before, e := json.Marshal(s.state) + if e != nil { + return nil, e + } + for _, d := range deltas { + if e = s.record(ctx, d); e != nil { + break } } - for kind, current := range after.Items { - old := s.before.Items[kind] - if current > old { - deltas = append(deltas, delta{32, kind[0], current - old}) - } - } - for idx, current := range after.Equipment { - old, ok := s.before.Equipment[idx] - if ok && current.Level > old.Level { - deltas = append(deltas, delta{14, 0, current.Level - old.Level}) - } - } - for idx, current := range after.Costumes { - old, ok := s.before.Costumes[idx] - if ok && current.Level > old.Level { - deltas = append(deltas, delta{104, current.ID, current.Level - old.Level}) - } - } - if len(deltas) > 0 { - - before, e := json.Marshal(s.state) - if e != nil { - - return nil, e - } - changed := false - for _, d := range deltas { - changed = s.recordEventLocked(ctx, d.condition, d.sub, d.count, s.unlocked) || changed - } - if changed { - s.state.Receipts[rk] = receipt{Digest: "observer"} - e = s.save(ctx) - } - if e != nil { - s.state = snapshot{} - _ = json.Unmarshal(before, &s.state) - } - - if e != nil { - return nil, e - } + if e != nil { + s.state = snapshot{} + _ = json.Unmarshal(before, &s.state) + return nil, e } } + if err := s.reconcileGachaProgress(ctx, &after, false); err != nil { + return nil, err + } s.before = after s.observationVersion = s.inventoryObservationVersion() s.inventoryReady = true @@ -665,8 +651,45 @@ func (s *Service) AfterDispatch(ctx command.Context, path string, request, respo return s.notifyMissionChanges(ctx) } -func (s *Service) notifyMissionChanges(ctx command.Context) ([]byte, error) { +// inventoryDeltas turns one request's inventory changes into mission events. +func (s *Service) inventoryDeltas(after InventorySnapshot) []conditions.Event { + var deltas []conditions.Event + for kind, old := range s.before.Items { + current := after.Items[kind] + // McResourceUse names a Resource item; currencies are not inventory + // items and the event economy reports their spends. + if current < old && kind[0] == resourceItemType { + deltas = append(deltas, conditions.Event{Type: conditions.ResourceUse, Sub: kind[1], Count: old - current}) + } + } + for kind, current := range after.Items { + old := s.before.Items[kind] + if current > old { + deltas = append(deltas, conditions.Event{Type: conditions.ItemCurrencyGet, Sub: kind[0], Count: current - old}) + } + } + for idx, current := range after.Equipment { + old, ok := s.before.Equipment[idx] + if ok && current.Level > old.Level { + deltas = append(deltas, conditions.Event{Type: conditions.EquipmentUpgrade, Count: current.Level - old.Level}) + } + } + for idx, current := range after.Costumes { + old, ok := s.before.Costumes[idx] + if ok && current.Level > old.Level { + deltas = append(deltas, conditions.Event{Type: conditions.CostumeUpgrade, Sub: current.ID, Count: current.Level - old.Level}) + } + } + return deltas +} +func (s *Service) notifyMissionChanges(ctx command.Context) ([]byte, error) { + if err := s.reconcileRewardLevelProgress(ctx); err != nil { + return nil, err + } + if err := s.ReconcileAccountState(ctx); err != nil { + return nil, err + } if s.beforeMissions == nil { return nil, nil } diff --git a/go/internal/server/domain/events/tasks/reward_level_progress.go b/go/internal/server/domain/events/tasks/reward_level_progress.go new file mode 100644 index 0000000..ff50fee --- /dev/null +++ b/go/internal/server/domain/events/tasks/reward_level_progress.go @@ -0,0 +1,164 @@ +package eventtasks + +import ( + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/events" + "encoding/json" + "strconv" + "strings" +) + +// Define_MissionConditionType values. Both conditions complete when the +// player has obtained a reward for the required reward level; they are not +// client-reported actions. +const ( + conditionRewardToAchievementLevel uint64 = 221 + conditionRewardToPassLevel uint64 = 223 +) + +// AttachAchievementLevelReward supplies the highest achievement level whose +// reward has been claimed. Reward claims are sequential, so that durable value +// also proves every lower level reward was claimed. +func (s *Service) AttachAchievementLevelReward(source func() (uint64, error)) { + s.achievementLevel = source +} + +// reconcileRewardLevelProgress derives reward-level mission progress from +// durable claim state. The claim may predate the pass or happen while the pass +// is inactive, so action-only events are not enough. +func (s *Service) reconcileRewardLevelProgress(ctx command.Context) error { + type pending struct { + schedule events.Schedule + task gamedata.EventTask + } + var tasks []pending + needAchievement, needPass := false, false + for _, v := range s.taskSchedules() { + if v.Type != 4 || !s.active(v) { + continue + } + period := s.missionPeriod(v) + for _, t := range s.design.Missions { + if t.Type != conditionRewardToAchievementLevel && t.Type != conditionRewardToPassLevel || !s.availableTask(ctx, v, t) { + continue + } + target := missionTarget(t) + if m := s.state.Missions[scheduleKey(v)+"/"+key(t.ID)]; m != nil && m.Period == period && (m.Claimed || m.Value >= target) { + continue + } + tasks = append(tasks, pending{schedule: v, task: t}) + if t.Type == conditionRewardToAchievementLevel { + needAchievement = true + } else { + needPass = true + } + } + } + if len(tasks) == 0 { + return nil + } + var achievementLevel uint64 + if needAchievement && s.achievementLevel != nil { + var err error + achievementLevel, err = s.achievementLevel() + if err != nil { + return err + } + } + passLevels := map[uint64]bool{} + if needPass { + passLevels = s.claimedPassLevels() + } + before, err := json.Marshal(s.state) + if err != nil { + return err + } + changed := false + for _, p := range tasks { + reached := false + switch p.task.Type { + case conditionRewardToAchievementLevel: + if s.achievementLevel != nil { + reached = achievementLevelRewardReached(achievementLevel, p.task) + } + case conditionRewardToPassLevel: + reached = passLevelRewardReached(passLevels, p.task) + } + if !reached { + continue + } + m := s.mission(p.schedule, p.task.ID) + if target := missionTarget(p.task); m.Value < target { + m.Value = target + changed = true + } + } + if !changed { + return nil + } + if err := s.save(ctx); err != nil { + _ = json.Unmarshal(before, &s.state) + return err + } + return nil +} + +func missionTarget(t gamedata.EventTask) uint64 { + if t.Target == 0 { + return 1 + } + return t.Target +} + +// achievementLevelRewardReached follows MissionTable.IsConditionSubTypeMoreCheck, +// mirroring MissionPassPacket.UpdateMissionUnit on the client. +func achievementLevelRewardReached(claimed uint64, t gamedata.EventTask) bool { + if t.SubType == 0 { + return claimed > 0 + } + if t.SubTypeMoreCheck != 0 { + return claimed >= t.SubType + } + return claimed == t.SubType +} + +// claimedPassLevels collects levels with a basic or premium reward claim from +// every pass the account has used. Pass rewards are not claimed sequentially, +// so the exact claimed level matters. +func (s *Service) claimedPassLevels() map[uint64]bool { + levels := map[uint64]bool{} + for _, p := range s.state.Passes { + if p == nil { + continue + } + for claimed := range p.Claimed { + level, _, ok := strings.Cut(claimed, "/") + if !ok { + continue + } + value, err := strconv.ParseUint(level, 10, 64) + if err == nil && value > 0 { + levels[value] = true + } + } + } + return levels +} + +// passLevelRewardReached uses the same ConditionSubType comparison as the +// client. Condition 223's Params is a zero placeholder and not a filter. +func passLevelRewardReached(claimed map[uint64]bool, t gamedata.EventTask) bool { + if t.SubType == 0 { + return len(claimed) > 0 + } + if t.SubTypeMoreCheck != 0 { + for level := range claimed { + if level >= t.SubType { + return true + } + } + return false + } + return claimed[t.SubType] +} diff --git a/go/internal/server/domain/events/tasks/service.go b/go/internal/server/domain/events/tasks/service.go index 8086ca1..6bb9335 100644 --- a/go/internal/server/domain/events/tasks/service.go +++ b/go/internal/server/domain/events/tasks/service.go @@ -8,6 +8,7 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" "bd2server/internal/server/domain/events" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/storage/stateio" "encoding/json" "errors" @@ -59,6 +60,8 @@ type snapshot struct { } type Service struct { provider InventoryProvider + gachaHistory func(command.Context, uint64) ([]byte, error) + achievementLevel func() (uint64, error) before InventorySnapshot observationVersion string inventoryReady bool @@ -78,6 +81,8 @@ type Service struct { attendancePremium func(command.Context, uint64) bool attendanceMail AttendanceMailIssuer associated func(events.Schedule) uint64 + progress func(command.Context, conditions.Event) error + accountState AccountState } func Open(ctx command.Context, store stateio.Store, d *gamedata.EventTasksDesign, r events.Resolver, e Economy) (*Service, error) { @@ -324,6 +329,18 @@ func (s *Service) pass(v events.Schedule) *pass { } return p } +func (s *Service) missionPeriod(v events.Schedule) string { + switch s.design.MissionGroups[v.ID].Type { + case 1: + return s.day() + case 2: + y, w := s.now().UTC().ISOWeek() + return fmt.Sprintf("%d-%d", y, w) + default: + return "" + } +} + func (s *Service) mission(v events.Schedule, id uint64) *mission { k := scheduleKey(v) + "/" + key(id) m := s.state.Missions[k] @@ -331,15 +348,7 @@ func (s *Service) mission(v events.Schedule, id uint64) *mission { m = &mission{} s.state.Missions[k] = m } - g := s.design.MissionGroups[v.ID] - period := "" - if g.Type == 1 { - period = s.day() - } - if g.Type == 2 { - y, w := s.now().UTC().ISOWeek() - period = fmt.Sprintf("%d-%d", y, w) - } + period := s.missionPeriod(v) if m.Period != period { *m = mission{Period: period} } @@ -360,42 +369,44 @@ func (s *Service) availableTask(ctx command.Context, v events.Schedule, t gameda // RecordEvent is called by authoritative gameplay. It returns no rewards and // caps every matching task at its design threshold. -func (s *Service) RecordEvent(ctx command.Context, condition, sub, count uint64, unlocked func(command.Context, uint64, uint64) bool) error { - - if !s.recordEventLocked(ctx, condition, sub, count, unlocked) { +func (s *Service) RecordEvent(ctx command.Context, event conditions.Event, unlocked func(command.Context, uint64, uint64) bool) error { + if !s.recordEventLocked(ctx, event, unlocked) { return nil } return s.save(ctx) } +func taskSpec(t gamedata.EventTask) conditions.Spec { + return conditions.Spec{Type: t.Type, SubType: t.SubType, SubTypeMoreCheck: t.SubTypeMoreCheck, Params: t.Params} +} + // recordEventLocked reports every persistent mutation, including initializing // a matching task or rolling its period. Irrelevant and already capped events // leave the account snapshot untouched. -func (s *Service) recordEventLocked(ctx command.Context, condition, sub, count uint64, unlocked func(command.Context, uint64, uint64) bool) bool { +func (s *Service) recordEventLocked(ctx command.Context, event conditions.Event, unlocked func(command.Context, uint64, uint64) bool) bool { changed := false - if count == 0 { + if event.Count == 0 { return false } + if unlocked == nil { + unlocked = s.unlocked + } for _, v := range s.taskSchedules() { if v.Type != 4 || !s.active(v) { continue } for _, t := range s.design.Missions { - if t.Type != condition || t.SubType != 0 && t.SubType != sub || condition == 349 && t.SubType != sub || !s.availableTask(ctx, v, t) { + // McSamGroupIdMissionUpdateCompleteCount only counts completed + // missions in the same group. + if event.Type == conditions.SameGroupMissionComplete && t.Group != event.Sub { + continue + } + if !taskSpec(t).Matches(event) || !s.availableTask(ctx, v, t) { continue } if (t.UnlockPack > 0 || t.UnlockQuest > 0) && (unlocked == nil || !unlocked(ctx, t.UnlockPack, t.UnlockQuest)) { continue } - match := len(t.Params) == 0 - for _, n := range t.Params { - if n == sub { - match = true - } - } - if !match { - continue - } previous := s.state.Missions[scheduleKey(v)+"/"+key(t.ID)] var prior mission if previous != nil { @@ -408,14 +419,11 @@ func (s *Service) recordEventLocked(ctx command.Context, condition, sub, count u if m.Claimed { continue } - if m.Value >= t.Target { + target := missionTarget(t) + if m.Value >= target { continue } - if count >= t.Target-m.Value { - m.Value = t.Target - } else { - m.Value += count - } + m.Value += min(event.Count, target-m.Value) changed = true } } @@ -426,13 +434,10 @@ func (s *Service) recordEventLocked(ctx command.Context, condition, sub, count u // reconnects from inflating event login tasks. Main should invoke this once // through the regular mission observer before serving attendance queries. func (s *Service) RecordLogin(ctx command.Context, unlocked func(command.Context, uint64, uint64) bool) error { - marker := "mission-login:" + s.day() if _, ok := s.state.LoginDays[marker]; ok { - return nil } s.state.LoginDays[marker] = s.now().UnixMilli() - - return s.RecordEvent(ctx, 0, 0, 1, unlocked) + return s.RecordEvent(ctx, conditions.Event{Type: conditions.Connect, Count: 1}, unlocked) } diff --git a/go/internal/server/domain/events/tasks/skyway.go b/go/internal/server/domain/events/tasks/skyway.go index df74d6b..2be0e2c 100644 --- a/go/internal/server/domain/events/tasks/skyway.go +++ b/go/internal/server/domain/events/tasks/skyway.go @@ -2,6 +2,7 @@ package eventtasks import ( "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" "slices" ) @@ -12,7 +13,7 @@ func (s *Service) RecordSkyWayClear(ctx command.Context, positionGroup, difficul continue } for _, task := range s.design.Missions { - if task.Type != 24 || task.SubType != positionGroup || !slices.Contains(task.Params, difficulty) || !s.availableTask(ctx, schedule, task) { + if task.Type != conditions.SkywayPositionGroupClear || task.SubType != positionGroup || !slices.Contains(task.Params, difficulty) || !s.availableTask(ctx, schedule, task) { continue } previous := s.state.Missions[scheduleKey(schedule)+"/"+key(task.ID)] diff --git a/go/internal/server/domain/fishing/fishing.go b/go/internal/server/domain/fishing/fishing.go index 99eb09c..5adfcc6 100644 --- a/go/internal/server/domain/fishing/fishing.go +++ b/go/internal/server/domain/fishing/fishing.go @@ -2,6 +2,7 @@ package fishing import ( "bd2server/internal/common/util" + "bd2server/internal/server/domain/progression/conditions" "bytes" "encoding/binary" "encoding/json" @@ -91,6 +92,19 @@ type Service struct { now func() time.Time sample func(uint64) (uint64, error) publicProfile PublicProfileLookup + progress func(command.Context, conditions.Event) error +} + +// AttachProgress reports fishing actions to mission conditions. +func (s *Service) AttachProgress(record func(command.Context, conditions.Event) error) { + s.progress = record +} + +func (s *Service) recordProgress(ctx command.Context, event conditions.Event) error { + if s.progress == nil { + return nil + } + return s.progress(ctx, event) } func (s *Service) NativeRuns() []eventplay.NativeRun { @@ -494,6 +508,16 @@ func (s *Service) apply(ctx command.Context, path string, req []byte, n *snapsho return nil, err } } + if s.progress != nil { + // McFishingVoyageStart names the FishingMapTable group (region). + mapRow, err := s.design.Row("FishingMapTable", 1, mapID) + if err != nil { + return nil, err + } + if err := s.progress(ctx, conditions.Event{Type: conditions.FishingVoyageStart, Sub: num(mapRow, 2), Count: 1}); err != nil { + return nil, err + } + } n.Map = mapID n.VoyageStarted = now n.Cast = 0 @@ -520,6 +544,9 @@ func (s *Service) apply(ctx command.Context, path string, req []byte, n *snapsho n.MultiAP-- out = wire.AppendVarint(nil, 1, 1) } + if err := s.recordProgress(ctx, conditions.Event{Type: conditions.FishingMultiParticipation, Count: 1}); err != nil { + return nil, err + } } } d, _ := s.design.Row("FishingDefaultTable", 25, 0) @@ -607,6 +634,11 @@ func (s *Service) apply(ctx command.Context, path string, req []byte, n *snapsho c.Max = it.Size } n.Collection[it.ID] = c + if path == "/FishingBiteEnd" { + if err := s.recordProgress(ctx, conditions.Event{Type: conditions.FishingFishBiteEnd, Sub: it.ID, Count: 1}); err != nil { + return nil, err + } + } fish, err := s.design.Row("FishingFishTable", 12, it.ID) if err != nil { return nil, err diff --git a/go/internal/server/domain/fishing/shop.go b/go/internal/server/domain/fishing/shop.go index 8071568..8b0421b 100644 --- a/go/internal/server/domain/fishing/shop.go +++ b/go/internal/server/domain/fishing/shop.go @@ -3,6 +3,7 @@ package fishing import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/protocol/wire" "encoding/binary" "fmt" @@ -115,6 +116,10 @@ func (s *Service) shop(ctx command.Context, path string, req []byte, n *snapshot if e != nil { return nil, e } + // McFishingShopBuy names the FishingBuyItemTable shop and the bought item. + if e = s.recordProgress(ctx, conditions.Event{Type: conditions.FishingShopBuy, Sub: num(req, 2), Param: id, Count: count}); e != nil { + return nil, e + } if typ == 57 { for range quantity { it := Item{Index: n.Next, ID: id, Count: 1, Time: s.now().Unix()} diff --git a/go/internal/server/domain/inventory/commerce_items.go b/go/internal/server/domain/inventory/commerce_items.go index b99cd3d..2059f67 100644 --- a/go/internal/server/domain/inventory/commerce_items.go +++ b/go/internal/server/domain/inventory/commerce_items.go @@ -27,7 +27,7 @@ func (s *Inventory) GrantCommerceOnce(ctx command.Context, identity string, rewa next := cloneOwnedSnapshot(s.owned) var out []Item for _, r := range rewards { - if r.ID == 0 || (r.Type != 62 && r.Type != 19) || r.Count == 0 || r.Count > math.MaxInt32 || r.Type == 19 && r.ExpiryTime == 0 || next.NextIndex == math.MaxUint64 { + if r.ID == 0 || (r.Type != 62 && r.Type != 19) || r.Count == 0 || r.Count > math.MaxInt32 || r.Type == 19 && r.ExpiryTime == 0 { return nil, fmt.Errorf("player: invalid commerce item") } if r.Type == 19 { @@ -48,8 +48,11 @@ func (s *Inventory) GrantCommerceOnce(ctx command.Context, identity string, rewa } r.Count = 1 } - r.InvenIndex = next.NextIndex - next.NextIndex++ + index, err := ctx.NewInstanceID() + if err != nil { + return nil, err + } + r.InvenIndex = index next.Items = append(next.Items, r) next.GrantItems[identity] = append(next.GrantItems[identity], r.InvenIndex) out = append(out, r) diff --git a/go/internal/server/domain/inventory/equipment.go b/go/internal/server/domain/inventory/equipment.go index fb15535..d926de3 100644 --- a/go/internal/server/domain/inventory/equipment.go +++ b/go/internal/server/domain/inventory/equipment.go @@ -4,6 +4,7 @@ import ( "bd2server/internal/common/versionconfig" "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/storage/stateio" "encoding/json" "errors" @@ -45,7 +46,6 @@ type EquipmentOption struct { type equipmentSnapshot struct { Version string `json:"version"` - NextIndex uint64 `json:"next_index"` Equipment []Equipment `json:"-"` Storage []Equipment `json:"-"` Granted map[string]uint64 `json:"-"` @@ -71,9 +71,12 @@ type EquipmentInventory struct { wallet *Wallet inventory *Inventory - smeltCache map[string]smeltingReply - pendingReroll *equipmentOptionRerollPending - presets map[equipmentPresetKey]equipmentPreset + smeltCache map[string]smeltingReply + // missionProgress and missionGrade report actions to mission conditions. + missionProgress func(command.Context, conditions.Event) error + missionGrade func(uint64) uint64 + pendingReroll *equipmentOptionRerollPending + presets map[equipmentPresetKey]equipmentPreset } type smeltingReply struct { @@ -177,7 +180,7 @@ func OpenEquipmentInventory(ctx command.Context, store stateio.Store) (*Equipmen return nil, errors.New("player: nil equipment store") } s := &EquipmentInventory{store: entries, smeltCache: make(map[string]smeltingReply), presets: make(map[equipmentPresetKey]equipmentPreset), owned: equipmentSnapshot{ - Version: versionconfig.State(), NextIndex: 910000001, Granted: map[string]uint64{}, + Version: versionconfig.State(), Granted: map[string]uint64{}, }} data, err := store.Load(ctx.State, "equipment") if err != nil { @@ -185,7 +188,7 @@ func OpenEquipmentInventory(ctx command.Context, store stateio.Store) (*Equipmen } if data != nil { s.corePresent = true - if err := stateio.RequireExactJSONObject(data, "version", "next_index"); err != nil { + if err := stateio.RequireExactJSONObject(data, "version"); err != nil { return nil, fmt.Errorf("player: incompatible equipment layout: %w", err) } var shape map[string]json.RawMessage @@ -203,7 +206,7 @@ func OpenEquipmentInventory(ctx command.Context, store stateio.Store) (*Equipmen } else if err := stateio.RequireNoEntries(entries, ctx.State, "equipment", "equipment", "granted", "reroll_pending", "presets", "storage"); err != nil { return nil, fmt.Errorf("player: invalid equipment storage: %w", err) } - if s.owned.Version != versionconfig.State() || s.owned.NextIndex < 910000001 { + if s.owned.Version != versionconfig.State() { return nil, errors.New("player: invalid saved equipment") } s.owned.Granted, err = loadUintEntries(ctx, entries, "equipment", "granted") @@ -321,12 +324,12 @@ func (s *EquipmentInventory) grantLocked(ctx command.Context, identity string, e if len(entry.Rank) != 3 { return Equipment{}, errors.New("player: equipment requires exactly three rank slots") } - if s.owned.NextIndex == math.MaxUint64 { - return Equipment{}, errors.New("inventory: equipment index exhausted") + index, err := ctx.NewInstanceID() + if err != nil { + return Equipment{}, err } - entry.InvenIndex = s.owned.NextIndex + entry.InvenIndex = index next := cloneEquipmentSnapshot(s.owned) - next.NextIndex++ next.Equipment = append(next.Equipment, entry) next.Granted[identity] = entry.InvenIndex if err := s.commitLocked(ctx, next, "grant"); err != nil { @@ -776,7 +779,7 @@ func validEquipmentMark(raw []byte) bool { } func cloneEquipmentSnapshot(current equipmentSnapshot) equipmentSnapshot { - next := equipmentSnapshot{Version: current.Version, NextIndex: current.NextIndex, + next := equipmentSnapshot{Version: current.Version, Equipment: append([]Equipment(nil), current.Equipment...), Storage: append([]Equipment(nil), current.Storage...), Granted: make(map[string]uint64, len(current.Granted))} for i := range next.Equipment { next.Equipment[i] = cloneEquipment(next.Equipment[i]) @@ -916,7 +919,7 @@ func (s *EquipmentInventory) persistEquipmentState(ctx command.Context, next equ } changes = append(changes, change) } - if s.corePresent && next.Version == s.persisted.Version && next.NextIndex == s.persisted.NextIndex { + if s.corePresent && next.Version == s.persisted.Version { data = nil } if err := s.store.SaveWithEntries(ctx.State, "equipment", data, changes); err != nil { diff --git a/go/internal/server/domain/inventory/equipment_conversion.go b/go/internal/server/domain/inventory/equipment_conversion.go index 52883b8..2d7582d 100644 --- a/go/internal/server/domain/inventory/equipment_conversion.go +++ b/go/internal/server/domain/inventory/equipment_conversion.go @@ -2,6 +2,7 @@ package inventory import ( "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/protocol/wire" "errors" "fmt" @@ -138,6 +139,9 @@ func (s *EquipmentInventory) fromMakingOrUpgrade(ctx command.Context, path strin return 0, nil, true, err } index = created[0].InvenIndex + if err := s.recordMade(ctx, created); err != nil { + return 0, nil, true, err + } if experience != 0 { if _, err := s.characters.AddEquipmentTalentExperience(ctx, character, experience, maximum); err != nil { return 0, nil, true, err @@ -161,6 +165,9 @@ func (s *EquipmentInventory) fromMakingOrUpgrade(ctx command.Context, path strin if err := s.commitLocked(ctx, next, "conversion break"); err != nil { return 0, nil, true, err } + if err := s.recordMission(ctx, conditions.BreakEquipmentItem, 1); err != nil { + return 0, nil, true, err + } identity := fmt.Sprintf("equipment-conversion-break:%s:%s:%s:%d", ctx.SessionID, ctx.RequestID, path, seq) result.Granted, err = s.inventory.GrantOnce(ctx, identity, rewards) if err != nil { diff --git a/go/internal/server/domain/inventory/equipment_craft.go b/go/internal/server/domain/inventory/equipment_craft.go index 4a34c19..19abf50 100644 --- a/go/internal/server/domain/inventory/equipment_craft.go +++ b/go/internal/server/domain/inventory/equipment_craft.go @@ -131,9 +131,6 @@ func (s *EquipmentInventory) grantGeneratedBatch(ctx command.Context, identityPr return existing, nil } } - if uint64(len(entries)) > math.MaxUint64-s.owned.NextIndex { - return nil, errors.New("inventory: equipment batch indices exhausted") - } next := cloneEquipmentSnapshot(s.owned) created := make([]Equipment, 0, len(entries)) for i, source := range entries { @@ -141,8 +138,11 @@ func (s *EquipmentInventory) grantGeneratedBatch(ctx command.Context, identityPr if entry.ID == 0 || len(entry.Rank) != 3 { return nil, errors.New("player: invalid generated equipment in batch") } - entry.InvenIndex = next.NextIndex - next.NextIndex++ + index, err := ctx.NewInstanceID() + if err != nil { + return nil, err + } + entry.InvenIndex = index next.Equipment = append(next.Equipment, entry) created = append(created, cloneEquipment(entry)) if trackReplay { diff --git a/go/internal/server/domain/inventory/equipment_missions.go b/go/internal/server/domain/inventory/equipment_missions.go new file mode 100644 index 0000000..87f9bc8 --- /dev/null +++ b/go/internal/server/domain/inventory/equipment_missions.go @@ -0,0 +1,39 @@ +package inventory + +import ( + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" +) + +// Define_TalentSkillType TS_EQUIPMENT_MAKING, the SubType of McTalentSkillUse. +const talentSkillEquipmentMaking uint64 = 9 + +// AttachMissionProgress reports equipment actions to mission conditions. +// grade resolves the EquipmentTable grade McEquipMakeGrade compares. +func (s *EquipmentInventory) AttachMissionProgress(record func(command.Context, conditions.Event) error, grade func(equipmentID uint64) uint64) { + s.missionProgress, s.missionGrade = record, grade +} + +func (s *EquipmentInventory) recordMission(ctx command.Context, condition, count uint64) error { + if s.missionProgress == nil || count == 0 { + return nil + } + return s.missionProgress(ctx, conditions.Event{Type: condition, Count: count}) +} + +func (s *EquipmentInventory) recordMade(ctx command.Context, created []Equipment) error { + if s.missionProgress == nil { + return nil + } + for _, entry := range created { + if err := s.missionProgress(ctx, conditions.Event{Type: conditions.EquipMakeGrade, Sub: s.missionGrade(entry.ID), Count: 1}); err != nil { + return err + } + } + if len(created) == 0 { + return nil + } + // Equipment making is the TS_EQUIPMENT_MAKING talent skill, used once per + // request regardless of how many results the recipe produced. + return s.missionProgress(ctx, conditions.Event{Type: conditions.TalentSkillUse, Sub: talentSkillEquipmentMaking, Count: 1}) +} diff --git a/go/internal/server/domain/inventory/equipment_storage.go b/go/internal/server/domain/inventory/equipment_storage.go index cb69ee2..135db61 100644 --- a/go/internal/server/domain/inventory/equipment_storage.go +++ b/go/internal/server/domain/inventory/equipment_storage.go @@ -49,7 +49,7 @@ func (s *EquipmentInventory) loadEquipmentStorage(ctx command.Context) error { for key, payload := range raw { var entry Equipment index, err := strconv.ParseUint(key, 10, 64) - if err != nil || json.Unmarshal(payload, &entry) != nil || entry.InvenIndex != index || index == 0 || index >= s.owned.NextIndex || seen[index] || entry.ID == 0 || entry.UseChar != 0 || len(entry.Rank) != 3 { + if err != nil || json.Unmarshal(payload, &entry) != nil || entry.InvenIndex != index || index == 0 || index >= 1<<59 || seen[index] || entry.ID == 0 || entry.UseChar != 0 || len(entry.Rank) != 3 { return fmt.Errorf("inventory: invalid stored equipment %q", key) } for _, rank := range entry.Rank { diff --git a/go/internal/server/domain/inventory/initial_items.go b/go/internal/server/domain/inventory/initial_items.go index 5b2db97..66c8354 100644 --- a/go/internal/server/domain/inventory/initial_items.go +++ b/go/internal/server/domain/inventory/initial_items.go @@ -2,7 +2,6 @@ package inventory import ( "fmt" - "math" "bd2server/internal/server/domain/command" ) @@ -19,12 +18,11 @@ func (s *Inventory) InitializeItems(ctx command.Context, items []Item) error { } } for _, item := range items { - if item.InvenIndex == 0 || item.InvenIndex == math.MaxUint64 || item.Type == 0 || item.ID == 0 || item.Count == 0 || seen[item.InvenIndex] { + if item.InvenIndex == 0 || item.InvenIndex >= 1<<59 || item.Type == 0 || item.ID == 0 || item.Count == 0 || seen[item.InvenIndex] { return fmt.Errorf("inventory: invalid initial owned item") } seen[item.InvenIndex] = true next.Items = append(next.Items, item) - next.NextIndex = max(next.NextIndex, item.InvenIndex+1) } if err := s.commitOwned(ctx, next); err != nil { return err diff --git a/go/internal/server/domain/inventory/item_operations.go b/go/internal/server/domain/inventory/item_operations.go index ec598f4..33bc30b 100644 --- a/go/internal/server/domain/inventory/item_operations.go +++ b/go/internal/server/domain/inventory/item_operations.go @@ -61,7 +61,7 @@ func (s *Inventory) loadItemStorage(ctx command.Context) error { for key, payload := range raw { var item Item index, err := strconv.ParseUint(key, 10, 64) - if err != nil || json.Unmarshal(payload, &item) != nil || index != item.InvenIndex || index == 0 || seen[index] || index >= s.owned.NextIndex || item.ID == 0 || item.Type == 0 || item.Count == 0 || item.KeepFlag > 1 { + if err != nil || json.Unmarshal(payload, &item) != nil || index != item.InvenIndex || index == 0 || seen[index] || index >= 1<<59 || item.ID == 0 || item.Type == 0 || item.Count == 0 || item.KeepFlag > 1 { return fmt.Errorf("inventory: invalid storage item %q", key) } seen[index] = true @@ -228,8 +228,8 @@ func (s *Inventory) itemStorageMove(ctx command.Context, path string, want Item) } // The destination has its own stack identity. Replies are count deltas, // consumed by CommonPacket.AddKeepItem and AddItemInfo. - destination := ownedSnapshot{Items: *target, NextIndex: next.NextIndex} - deltas, err := s.addItems(&destination, moved) + destination := ownedSnapshot{Items: *target} + deltas, err := s.addItems(ctx, &destination, moved) if err != nil { return 0, nil, true, err } @@ -241,7 +241,6 @@ func (s *Inventory) itemStorageMove(ctx command.Context, path string, want Item) return 0, nil, true, errors.New("inventory: destination capacity exceeded") } *target = destination.Items - next.NextIndex = destination.NextIndex if err := s.commitOwned(ctx, next); err != nil { return 0, nil, true, err } diff --git a/go/internal/server/domain/inventory/item_stacks.go b/go/internal/server/domain/inventory/item_stacks.go index 225c5a4..b9d7ccb 100644 --- a/go/internal/server/domain/inventory/item_stacks.go +++ b/go/internal/server/domain/inventory/item_stacks.go @@ -2,6 +2,7 @@ package inventory import ( "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" "errors" "math" ) @@ -16,10 +17,23 @@ func (s *Inventory) AttachItemStacks(design *gamedata.ItemStackDesign) error { // Reward ItemDBInfo.Count is a delta: CommonPacket.AddItemInfo adds it to an // existing instance. Inventory state holds totals; replies hold only this grant. -func (s *Inventory) addItems(next *ownedSnapshot, reward Item) ([]Item, error) { +func (s *Inventory) addItems(ctx command.Context, next *ownedSnapshot, reward Item) ([]Item, error) { if reward.ID == 0 || reward.Type == 0 || reward.Count == 0 || reward.Count > math.MaxInt32 { return nil, errors.New("inventory: invalid item reward") } + if reward.Type == 45 { + for _, items := range [][]Item{s.starter, next.Items} { + for _, item := range items { + if item.Type == 45 && item.ID == reward.ID && item.Count > 0 { + return nil, nil + } + } + } + reward.Count = 1 + } + if err := s.ensurePrestigeIllustrations(ctx, next, []Item{reward}); err != nil { + return nil, err + } limit := uint64(math.MaxInt32) stackable := reward.Type == 5 || reward.Type == 8 || reward.Type == 9 || reward.Type == 14 if stackable { @@ -53,13 +67,13 @@ func (s *Inventory) addItems(next *ownedSnapshot, reward Item) ([]Item, error) { } } for remaining > 0 { - if next.NextIndex == math.MaxUint64 { - return nil, errors.New("inventory: item index exhausted") + index, err := ctx.NewInstanceID() + if err != nil { + return nil, err } item := reward - item.InvenIndex = next.NextIndex + item.InvenIndex = index item.Count = min(remaining, limit) - next.NextIndex++ next.Items = append(next.Items, item) deltas = append(deltas, item) remaining -= item.Count diff --git a/go/internal/server/domain/inventory/owned.go b/go/internal/server/domain/inventory/owned.go index a1797db..2dde1e6 100644 --- a/go/internal/server/domain/inventory/owned.go +++ b/go/internal/server/domain/inventory/owned.go @@ -32,13 +32,13 @@ type Inventory struct { } type ownedSnapshot struct { - Version string `json:"version"` - NextIndex uint64 `json:"next_index"` - Items []Item `json:"-"` - Storage []Item `json:"-"` - Granted map[string]bool `json:"-"` - GrantItems map[string][]uint64 `json:"-"` - GrantRewards map[string][]Item `json:"-"` + Version string `json:"version"` + Items []Item `json:"-"` + Storage []Item `json:"-"` + Granted map[string]bool `json:"-"` + GrantItems map[string][]uint64 `json:"-"` + GrantRewards map[string][]Item `json:"-"` + PrestigeIllustrations map[uint64]uint64 `json:"-"` } func OpenInventory(ctx command.Context, store stateio.Store, starter []Item) (*Inventory, error) { @@ -46,14 +46,15 @@ func OpenInventory(ctx command.Context, store stateio.Store, starter []Item) (*I if !ok { return nil, errors.New("player: invalid inventory configuration") } - s := &Inventory{store: entries, starter: append([]Item(nil), starter...), owned: ownedSnapshot{Version: versionconfig.State(), NextIndex: 900000001, Granted: map[string]bool{}, GrantItems: map[string][]uint64{}, GrantRewards: map[string][]Item{}}} + s := &Inventory{store: entries, starter: append([]Item(nil), starter...), owned: ownedSnapshot{Version: versionconfig.State(), Granted: map[string]bool{}, GrantItems: map[string][]uint64{}, GrantRewards: map[string][]Item{}}} + s.owned.PrestigeIllustrations = make(map[uint64]uint64) data, err := store.Load(ctx.State, "items") if err != nil { return nil, err } if data != nil { s.corePresent = true - if err := stateio.RequireExactJSONObject(data, "version", "next_index"); err != nil { + if err := stateio.RequireExactJSONObject(data, "version"); err != nil { return nil, fmt.Errorf("player: incompatible inventory layout: %w", err) } var shape map[string]json.RawMessage @@ -68,10 +69,10 @@ func OpenInventory(ctx command.Context, store stateio.Store, starter []Item) (*I if err := json.Unmarshal(data, &s.owned); err != nil { return nil, fmt.Errorf("player: decode inventory: %w", err) } - } else if err := stateio.RequireNoEntries(entries, ctx.State, "items", "items", "granted", "grant_items", "grant_rewards", "storage"); err != nil { + } else if err := stateio.RequireNoEntries(entries, ctx.State, "items", "items", "granted", "grant_items", "grant_rewards", "storage", "prestige_illustrations"); err != nil { return nil, fmt.Errorf("player: invalid inventory storage: %w", err) } - if s.owned.Version != versionconfig.State() || s.owned.NextIndex < 900000001 { + if s.owned.Version != versionconfig.State() { return nil, errors.New("player: invalid saved inventory") } s.owned.Granted, err = loadBoolEntries(ctx, entries, "items", "granted") @@ -117,6 +118,9 @@ func OpenInventory(ctx command.Context, store stateio.Store, starter []Item) (*I if err := s.loadItemStorage(ctx); err != nil { return nil, err } + if err := s.loadPrestigeIllustrations(ctx); err != nil { + return nil, err + } s.persisted = cloneOwnedSnapshot(s.owned) return s, nil } @@ -189,27 +193,11 @@ func (s *Inventory) GrantOnce(ctx command.Context, identity string, rewards []ga } next := cloneOwnedSnapshot(s.owned) newItems := make([]Item, 0, len(rewards)) - // Skin rewards represent ownership; returning an existing skin would also - // replay the client's acquisition UI. Include the immutable starter seed. - ownedSkins := make(map[uint64]bool) - for _, items := range [][]Item{s.starter, next.Items} { - for _, item := range items { - if item.Type == 45 && item.Count > 0 { - ownedSkins[item.ID] = true - } - } - } for _, r := range rewards { if r.ID == 0 || r.Type == 0 || r.Count == 0 { return nil, errors.New("player: invalid battle reward") } - if r.Type == 45 { - if ownedSkins[r.ID] { - continue - } - ownedSkins[r.ID] = true - } - items, err := s.addItems(&next, Item{ID: r.ID, Type: r.Type, Count: r.Count, TimeValue: uint64(time.Now().UnixMilli())}) + items, err := s.addItems(ctx, &next, Item{ID: r.ID, Type: r.Type, Count: r.Count, TimeValue: uint64(time.Now().UnixMilli())}) if err != nil { return nil, err } @@ -225,8 +213,9 @@ func (s *Inventory) GrantOnce(ctx command.Context, identity string, rewards []ga } func cloneOwnedSnapshot(current ownedSnapshot) ownedSnapshot { - next := ownedSnapshot{Version: current.Version, NextIndex: current.NextIndex, + next := ownedSnapshot{Version: current.Version, Items: append([]Item(nil), current.Items...), Storage: append([]Item(nil), current.Storage...), Granted: make(map[string]bool, len(current.Granted)+1), GrantItems: make(map[string][]uint64, len(current.GrantItems)+1), GrantRewards: make(map[string][]Item, len(current.GrantRewards)+1)} + next.PrestigeIllustrations = maps.Clone(current.PrestigeIllustrations) maps.Copy(next.Granted, current.Granted) for k, v := range current.GrantItems { next.GrantItems[k] = append([]uint64(nil), v...) @@ -244,6 +233,16 @@ func (s *Inventory) commitOwned(ctx command.Context, next ownedSnapshot) error { return err } changes := make([]stateio.EntryMutation, 0) + for id, index := range next.PrestigeIllustrations { + if s.persisted.PrestigeIllustrations[id] == index { + continue + } + payload, err := json.Marshal(index) + if err != nil { + return err + } + changes = append(changes, stateio.EntryMutation{Bucket: "prestige_illustrations", Key: strconv.FormatUint(id, 10), Payload: payload}) + } for key, value := range next.Granted { if value && !s.persisted.Granted[key] { changes = append(changes, stateio.EntryMutation{Bucket: "granted", Key: key, Payload: []byte("true")}) @@ -291,7 +290,7 @@ func (s *Inventory) commitOwned(ctx command.Context, next ownedSnapshot) error { return err } changes = append(changes, storageChanges...) - if s.corePresent && next.Version == s.persisted.Version && next.NextIndex == s.persisted.NextIndex { + if s.corePresent && next.Version == s.persisted.Version { data = nil } if err := s.store.SaveWithEntries(ctx.State, "items", data, changes); err != nil { @@ -411,7 +410,7 @@ func (s *Inventory) ConsumeAndRefund(ctx command.Context, requested []Item, refu if refund.ID == 0 || refund.Count == 0 { return nil, errors.New("player: invalid growth refund") } - items, err := s.addItems(&next, Item{ID: refund.ID, Type: 8, Count: refund.Count, TimeValue: uint64(time.Now().UnixMilli())}) + items, err := s.addItems(ctx, &next, Item{ID: refund.ID, Type: 8, Count: refund.Count, TimeValue: uint64(time.Now().UnixMilli())}) if err != nil { return nil, err } diff --git a/go/internal/server/domain/inventory/prestige_illustrations.go b/go/internal/server/domain/inventory/prestige_illustrations.go index 84c8129..3416d53 100644 --- a/go/internal/server/domain/inventory/prestige_illustrations.go +++ b/go/internal/server/domain/inventory/prestige_illustrations.go @@ -1,7 +1,71 @@ package inventory -func (s *Inventory) AttachPrestigeIllustrations(illustrations map[uint64]uint64) { +import ( + "encoding/json" + "fmt" + "maps" + "slices" + "strconv" + + "bd2server/internal/server/domain/command" +) + +func (s *Inventory) AttachPrestigeIllustrations(ctx command.Context, illustrations map[uint64]uint64) error { s.prestigeIllustrations = illustrations + next := cloneOwnedSnapshot(s.owned) + if err := s.ensurePrestigeIllustrations(ctx, &next, s.All(ctx)); err != nil { + return err + } + if maps.Equal(next.PrestigeIllustrations, s.owned.PrestigeIllustrations) { + return nil + } + if err := s.commitOwned(ctx, next); err != nil { + return err + } + s.owned = next + return nil +} + +func (s *Inventory) loadPrestigeIllustrations(ctx command.Context) error { + rows, err := s.store.ListEntries(ctx.State, "items", "prestige_illustrations") + if err != nil { + return err + } + used := make(map[uint64]bool, len(rows)) + for key, raw := range rows { + id, err := strconv.ParseUint(key, 10, 64) + var index uint64 + if err != nil || id == 0 || key != strconv.FormatUint(id, 10) || json.Unmarshal(raw, &index) != nil || index == 0 || index >= 1<<59 || used[index] { + return fmt.Errorf("inventory: invalid prestige illustration identity %q", key) + } + s.owned.PrestigeIllustrations[id] = index + used[index] = true + } + return nil +} + +func (s *Inventory) ensurePrestigeIllustrations(ctx command.Context, next *ownedSnapshot, items []Item) error { + if next.PrestigeIllustrations == nil { + next.PrestigeIllustrations = make(map[uint64]uint64) + } + var missing []uint64 + for _, item := range items { + if item.Type != 45 || item.Count == 0 { + continue + } + if id := s.prestigeIllustrations[item.ID]; id != 0 && next.PrestigeIllustrations[id] == 0 { + missing = append(missing, id) + } + } + slices.Sort(missing) + for _, id := range slices.Compact(missing) { + index, err := ctx.NewInstanceID() + if err != nil { + return err + } + next.PrestigeIllustrations[id] = index + } + return nil } func (s *Inventory) withPrestigeIllustrations(items []Item) []Item { @@ -24,8 +88,7 @@ func (s *Inventory) withPrestigeIllustrations(items []Item) []Item { continue } seen[id] = true - // Linked illustrations are immutable ownership views, outside mutable item indices. - attached = append(attached, Item{InvenIndex: 1<<62 | id, ID: id, Type: 25, Count: 1, TimeValue: item.TimeValue}) + attached = append(attached, Item{InvenIndex: s.owned.PrestigeIllustrations[id], ID: id, Type: 25, Count: 1, TimeValue: item.TimeValue}) } return append(items, attached...) } diff --git a/go/internal/server/domain/inventory/protocol_equipment_adapter.go b/go/internal/server/domain/inventory/protocol_equipment_adapter.go index 647ec25..65a67d7 100644 --- a/go/internal/server/domain/inventory/protocol_equipment_adapter.go +++ b/go/internal/server/domain/inventory/protocol_equipment_adapter.go @@ -3,6 +3,7 @@ package inventory import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/protocol/ownership" "bd2server/internal/server/protocol/wire" "encoding/binary" @@ -300,6 +301,9 @@ func (s *EquipmentInventory) makeEquipment(ctx command.Context, request []byte) if err != nil { return 0, nil, true, fmt.Errorf("player: persist made equipment: %w", err) } + if err := s.recordMade(ctx, created); err != nil { + return 0, nil, true, err + } if gain > 0 { if _, err := s.characters.AddEquipmentTalentExperience(ctx, characterIndex, gain, maximum); err != nil { return 0, nil, true, err @@ -373,6 +377,9 @@ func (s *EquipmentInventory) breakEquipment(ctx command.Context, request []byte) if granted == nil { granted = s.inventory.GrantedItems(identity) } + if err := s.recordMission(ctx, conditions.BreakEquipmentItem, uint64(len(indices))); err != nil { + return 0, nil, true, err + } response := wire.AppendBytes(nil, 1, rewardItemBundle(granted)) s.cacheEquipmentReply(cacheKey, 56, response) return 56, response, true, nil @@ -396,6 +403,9 @@ func (s *EquipmentInventory) upgradeToBreakAuto(ctx command.Context, request []b if err != nil { return 0, nil, true, err } + if err := s.recordMission(ctx, conditions.BreakEquipmentItem, uint64(len(result.Equipment))); err != nil { + return 0, nil, true, err + } response := encodeUpgradeBreakResponse(result, 1, 2, 3, 4, 5, 6, 7) s.cacheEquipmentReply(cacheKey, 516, response) return 516, response, true, nil @@ -444,6 +454,9 @@ func (s *EquipmentInventory) makeToBreakAuto(ctx command.Context, request []byte if err != nil { return 0, nil, true, fmt.Errorf("player: persist auto-break made equipment: %w", err) } + if err := s.recordMade(ctx, created); err != nil { + return 0, nil, true, err + } indices := make([]uint64, 0, len(created)) for _, entry := range created { indices = append(indices, entry.InvenIndex) @@ -457,6 +470,9 @@ func (s *EquipmentInventory) makeToBreakAuto(ctx command.Context, request []byte if err != nil { return 0, nil, true, err } + if err := s.recordMission(ctx, conditions.BreakEquipmentItem, uint64(len(result.Equipment))); err != nil { + return 0, nil, true, err + } var response []byte if gain != 0 { response = wire.AppendVarint(response, 1, gain) @@ -601,6 +617,9 @@ func (s *EquipmentInventory) batchUse(ctx command.Context, request []byte) (int, return 0, nil, true, err } + if err := s.recordMission(ctx, conditions.EquipEquipmentItem, 1); err != nil { + return 0, nil, true, err + } characterIndices := make([]uint64, 0, len(affected)) for index := range affected { @@ -995,6 +1014,9 @@ func (s *EquipmentInventory) optionRerollRequest(ctx command.Context, request [] for _, option := range candidate.SubOption { response = wire.AppendBytes(response, 2, equipmentOptionWire(option)) } + if err := s.recordMission(ctx, conditions.EquipSmelting, 1); err != nil { + return 0, nil, true, err + } s.smeltCache[cacheKey] = smeltingReply{code: 192, body: append([]byte(nil), response...)} return 192, response, true, nil } @@ -1330,6 +1352,9 @@ func (s *EquipmentInventory) smeltOnce(ctx command.Context, request []byte) (int } response = appendSmeltingMileage(response, 5, 6, currency.EquipMileageExchangeGage, s.smelting.Mileage, earned) + if err := s.recordMission(ctx, conditions.SmeltEquipmentItem, 1); err != nil { + return 0, nil, true, err + } s.smeltCache[cacheKey] = smeltingReply{code: 105, body: append([]byte(nil), response...)} return 105, response, true, nil @@ -1468,6 +1493,9 @@ func (s *EquipmentInventory) smeltSequence(ctx command.Context, request []byte) response = wire.AppendVarint(response, 9, successes) } + if err := s.recordMission(ctx, conditions.SmeltEquipmentItem, attempts); err != nil { + return 0, nil, true, err + } s.smeltCache[cacheKey] = smeltingReply{code: 177, body: append([]byte(nil), response...)} return 177, response, true, nil @@ -1666,6 +1694,9 @@ func (s *EquipmentInventory) change(ctx command.Context, request []byte) (int, [ return 0, nil, true, err } + if err := s.recordMission(ctx, conditions.ChangeEquipmentItem, 1); err != nil { + return 0, nil, true, err + } // Max HP depends on the now-current equipment set, so build CharInfo only // after the atomic equipment save is visible to the shared stat calculator. @@ -1711,5 +1742,8 @@ func (s *EquipmentInventory) use(ctx command.Context, request []byte) (int, []by if err := s.commitLocked(ctx, next, "use"); err != nil { return 0, nil, true, fmt.Errorf("player: persist equipment use: %w", err) } + if err := s.recordMission(ctx, conditions.EquipEquipmentItem, 1); err != nil { + return 0, nil, true, err + } return 35, wire.AppendBytes(nil, 1, character.Response), true, nil } diff --git a/go/internal/server/domain/inventory/protocol_items_adapter.go b/go/internal/server/domain/inventory/protocol_items_adapter.go index f1f1fd5..54ae0d9 100644 --- a/go/internal/server/domain/inventory/protocol_items_adapter.go +++ b/go/internal/server/domain/inventory/protocol_items_adapter.go @@ -79,6 +79,10 @@ func (s *Inventory) Handle(ctx command.Context, path string, request []byte) (in } var response []byte for _, item := range items { + // PrestigeSkinInfo owns the login snapshot; Type45 item rows are acquisition deltas. + if item.Type == 45 { + continue + } response = wire.AppendBytes(response, 1, ItemWire(item)) } return 21, response, true, nil @@ -144,7 +148,7 @@ func (s *Inventory) useRandomBox(ctx command.Context, request []byte) (int, []by if reward.Type == 0 || reward.ID == 0 || reward.Count == 0 { return 0, nil, true, errors.New("player: UseRandomBox invalid GameData reward") } - items, err := s.addItems(&next, Item{ID: reward.ID, Type: reward.Type, Count: reward.Count, TimeValue: uint64(time.Now().UnixMilli())}) + items, err := s.addItems(ctx, &next, Item{ID: reward.ID, Type: reward.Type, Count: reward.Count, TimeValue: uint64(time.Now().UnixMilli())}) if err != nil { return 0, nil, true, err } diff --git a/go/internal/server/domain/inventory/wallet.go b/go/internal/server/domain/inventory/wallet.go index f21b2a7..d903257 100644 --- a/go/internal/server/domain/inventory/wallet.go +++ b/go/internal/server/domain/inventory/wallet.go @@ -150,6 +150,28 @@ func (s *Wallet) SpendJewelryOnce(ctx command.Context, identity string, amount u return s.spendJewelryOnce(ctx, identity, amount, true) } +func (s *Wallet) SpendTotalJewelryOnce(ctx command.Context, identity string, amount uint64) (Currency, error) { + if identity == "" || amount == 0 { + return Currency{}, errors.New("player: invalid wallet spend") + } + if s.state.Spent[identity] { + return s.state.Currency, nil + } + next := cloneWallet(s.state) + free := min(next.FreeJewelry, amount) + paid := amount - free + if next.Jewelry < paid { + return Currency{}, errors.New("player: insufficient jewelry") + } + next.FreeJewelry -= free + next.Jewelry -= paid + next.Spent[identity] = true + if err := s.commit(ctx, next, entry("spent", identity, []byte("true"))...); err != nil { + return Currency{}, err + } + return next.Currency, nil +} + func (s *Wallet) spendJewelryOnce(ctx command.Context, identity string, amount uint64, paid bool) (Currency, error) { if identity == "" || amount == 0 { return Currency{}, errors.New("player: invalid wallet spend") diff --git a/go/internal/server/domain/mail/attendance.go b/go/internal/server/domain/mail/attendance.go index 798f08e..faf4926 100644 --- a/go/internal/server/domain/mail/attendance.go +++ b/go/internal/server/domain/mail/attendance.go @@ -12,18 +12,18 @@ import ( "bd2server/internal/server/domain/command" ) -// AttendanceRewardEconomy resolves attachment wrappers only when claimed and +// AttachmentRewardEconomy resolves attachment wrappers only when claimed and // applies every reward to its owning domain under the account transaction. -type AttendanceRewardEconomy interface { +type AttachmentRewardEconomy interface { Apply(ctx command.Context, _ string, _ []gamedata.Reward, _ []gamedata.Reward) ([]byte, error) } -func (s *Service) AttachAttendanceRewardEconomy(ctx command.Context, e AttendanceRewardEconomy) error { +func (s *Service) AttachAttachmentRewardEconomy(ctx command.Context, e AttachmentRewardEconomy) error { if s == nil || e == nil { - return errors.New("mail: invalid attendance reward economy") + return errors.New("mail: invalid attachment reward economy") } - s.attendanceEconomy = e + s.attachmentEconomy = e return nil } @@ -34,7 +34,7 @@ func (s *Service) IssueAttachmentsOnce(ctx command.Context, identity, title, bod return errors.New("mail: attendance issuer unavailable") } - if s.attendanceEconomy == nil { + if s.attachmentEconomy == nil { return errors.New("mail: attendance reward economy unavailable") } if strings.TrimSpace(identity) == "" || identity != strings.TrimSpace(identity) || len(identity) > 450 || strings.TrimSpace(title) == "" || len(title) > 2000 || strings.TrimSpace(body) == "" || len(body) > 20000 || sentAt.UnixMilli() <= 0 || sentAt.UnixMilli() > math.MaxInt64-int64(30*24*time.Hour/time.Millisecond) { diff --git a/go/internal/server/domain/mail/grant_spool.go b/go/internal/server/domain/mail/grant_spool.go index 934172c..7d3ca5f 100644 --- a/go/internal/server/domain/mail/grant_spool.go +++ b/go/internal/server/domain/mail/grant_spool.go @@ -60,14 +60,36 @@ func (g compensation) validate() error { } for _, reward := range g.rewards { costumeReward := reward.Type == 11 && reward.ID != 0 && reward.Count <= 6 - if reward.Count == 0 || reward.Count > math.MaxInt32 || reward.ID > math.MaxInt32 || (!currencyRewardTypes[reward.Type] && !supportedItemDBInfoReward(reward) && !costumeReward) || - (currencyRewardTypes[reward.Type] && reward.ID != 0) { + if reward.Count == 0 || reward.Count > math.MaxInt32 || reward.ID > math.MaxInt32 || (!currencyRewardTypes[reward.Type] && !supportedItemDBInfoReward(reward) && !costumeReward && !extendedCompensationReward(reward)) || + ((currencyRewardTypes[reward.Type] || compensationCurrencies[reward.Type]) && reward.ID != 0) { return fmt.Errorf("mail: compensation %q has unsupported reward type=%d id=%d count=%d", g.identity, reward.Type, reward.ID, reward.Count) } } return nil } +var compensationCurrencies = func() map[uint64]bool { + out := map[uint64]bool{} + for _, t := range gamedata.MailEconomyCurrencyTypes { + out[t] = true + } + return out +}() + +func extendedCompensationReward(reward gamedata.Reward) bool { + return compensationCurrencies[reward.Type] && reward.ID == 0 || + (reward.Type == 49 || reward.Type == 50) && reward.ID != 0 && reward.Count == 1 +} + +func (s *Service) requiresAttachmentEconomy(entry MailDBInfo) bool { + for _, reward := range mailAttachments(entry) { + if extendedCompensationReward(reward) || reward.Type == 19 && !s.supportedItemDBInfoReward(reward) { + return true + } + } + return false +} + // AttachGrantSpoolPath enables reads before each /MailInfo. An absent file is // an empty queue, allowing an operator to create it after server startup. // Existing malformed input is rejected immediately without issuing mail. diff --git a/go/internal/server/domain/mail/mail.go b/go/internal/server/domain/mail/mail.go index 587b2fb..8d2807a 100644 --- a/go/internal/server/domain/mail/mail.go +++ b/go/internal/server/domain/mail/mail.go @@ -25,10 +25,8 @@ const openPacketCode = 132 const historyPacketCode = 138 const ( - mailHistoryPeriod = 30 * 24 * time.Hour - mailHistoryPageMax = 100 - starterLimitedCostumeIdentity = "starter:limited-costumes:not-current-pickup:v1" - starterPrestigeSkinIdentity = "starter:prestige-skins:not-current-purchase:v1" + mailHistoryPeriod = 30 * 24 * time.Hour + mailHistoryPageMax = 100 ) // itemDBInfoTypes are ElementType values whose successful mail claim is @@ -161,7 +159,7 @@ type stateSnapshot struct { // state alongside the bounded core snapshot. type Service struct { contentTickets *gamedata.GachaContentTicketDesign - attendanceEconomy AttendanceRewardEconomy + attachmentEconomy AttachmentRewardEconomy cashEconomy CashRewardEconomy cashTemplates map[uint64]bool beforeMailID uint64 @@ -170,6 +168,7 @@ type Service struct { seedPath string seedStamp fileStamp grantSpoolPath string + starterGifts starterGiftProvider storage stateio.ScopedEntryStore inventory *assets.Inventory wallet *assets.Wallet @@ -262,15 +261,8 @@ func OpenService(ctx command.Context, storage stateio.Store, starter *Starter, i } s.issued[identity] = id } - if id, exists := s.issued[starterLimitedCostumeIdentity]; exists { - if err := validateStarterLimitedCostumeMail(s.dynamic[id], nil); err != nil { - return nil, fmt.Errorf("mail: invalid persisted starter limited-costume gift: %w", err) - } - } - if id, exists := s.issued[starterPrestigeSkinIdentity]; exists { - if err := validateStarterPrestigeSkinMail(s.dynamic[id]); err != nil { - return nil, fmt.Errorf("mail: invalid persisted starter prestige-skin gift: %w", err) - } + if err := s.validateStarterGifts(); err != nil { + return nil, err } rawHistory, err := entries.ListEntries(ctx.State, "mail", "history") if err != nil { @@ -441,111 +433,6 @@ func (s *Service) EnqueueCompensation(ctx command.Context, identity, title, body return s.enqueueCompensations(ctx, []compensation{grant}) } -// EnsureStarterLimitedCostumes issues the new-player limited-costume gift at -// most once for this account. The durable issued-identity row is written in the -// same transaction as the mail, so retries and restarts return without -// allocating another mail ID. Six copies mean one acquisition plus five -// duplicate upgrades, producing enhancement +5 when claimed. -func (s *Service) EnsureStarterLimitedCostumes(ctx command.Context, costumeIDs []uint64, sentAt time.Time) error { - if s == nil { - return errors.New("mail: unavailable starter limited-costume service") - } - - if id, issued := s.issued[starterLimitedCostumeIdentity]; issued { - return validateStarterLimitedCostumeMail(s.dynamic[id], s.costumeDesign) - } - if len(costumeIDs) == 0 || s.costumeDesign == nil { - return errors.New("mail: starter limited-costume gift is empty or unavailable") - } - seen := make(map[uint64]bool, len(costumeIDs)) - rewards := make([]gamedata.Reward, 0, len(costumeIDs)) - for _, costumeID := range costumeIDs { - design, ok := s.costumeDesign.Character(costumeID) - if costumeID == 0 || seen[costumeID] || !ok || design.CostumeMaxLevel != 5 { - return fmt.Errorf("mail: invalid starter limited costume %d", costumeID) - } - seen[costumeID] = true - rewards = append(rewards, gamedata.Reward{Type: 11, ID: costumeID, Count: 6}) - } - grant := compensation{ - identity: starterLimitedCostumeIdentity, - title: "New Player Limited Costumes", - body: "Limited costumes not featured in the current pickup banners. Each costume is enhanced to +5 when claimed.", - rewards: rewards, - sentAt: sentAt, - } - if err := grant.validate(); err != nil { - return err - } - return s.enqueueCompensations(ctx, []compensation{grant}) -} - -func validateStarterLimitedCostumeMail(entry MailDBInfo, design roster.CostumeDesignSource) error { - if entry.MailID == 0 || len(entry.RewardTypes) == 0 || len(entry.RewardTypes) != len(entry.RewardIDs) || len(entry.RewardTypes) != len(entry.RewardCounts) { - return errors.New("invalid starter gift reward arrays") - } - seen := make(map[uint64]bool, len(entry.RewardTypes)) - for i, typ := range entry.RewardTypes { - id := entry.RewardIDs[i] - if typ != 11 || id == 0 || entry.RewardCounts[i] != 6 || seen[id] { - return errors.New("starter gift must contain unique six-copy costumes") - } - seen[id] = true - if design != nil { - costume, ok := design.Character(id) - if !ok || costume.CostumeMaxLevel != 5 { - return fmt.Errorf("starter gift costume %d is unavailable or not enhancement +5", id) - } - } - } - return nil -} - -// EnsureStarterPrestigeSkins gives an account its prestige-skin gift if it has -// never been issued. Existing and new accounts use the same durable identity; -// unclaimed or claimed mail never causes a second gift on restart. -func (s *Service) EnsureStarterPrestigeSkins(ctx command.Context, designIDs []uint64, sentAt time.Time) error { - if s == nil { - return errors.New("mail: unavailable starter prestige-skin service") - } - - if id, issued := s.issued[starterPrestigeSkinIdentity]; issued { - return validateStarterPrestigeSkinMail(s.dynamic[id]) - } - if len(designIDs) == 0 { - return errors.New("mail: starter prestige-skin gift is empty") - } - seen := make(map[uint64]bool, len(designIDs)) - rewards := make([]gamedata.Reward, 0, len(designIDs)) - for _, designID := range designIDs { - if designID == 0 || seen[designID] { - return fmt.Errorf("mail: invalid starter prestige skin %d", designID) - } - seen[designID] = true - rewards = append(rewards, gamedata.Reward{Type: 45, ID: designID, Count: 1}) - } - grant := compensation{identity: starterPrestigeSkinIdentity, title: "Prestige Skin Gift", body: "Prestige skins not currently available on the cash purchase page.", rewards: rewards, sentAt: sentAt} - if err := grant.validate(); err != nil { - return err - } - return s.enqueueCompensations(ctx, []compensation{grant}) -} - -func validateStarterPrestigeSkinMail(entry MailDBInfo) error { - if entry.MailID == 0 || len(entry.RewardTypes) == 0 || len(entry.RewardTypes) != len(entry.RewardIDs) || len(entry.RewardTypes) != len(entry.RewardCounts) { - return errors.New("invalid starter prestige-skin reward arrays") - } - seen := make(map[uint64]bool, len(entry.RewardTypes)) - for i, typ := range entry.RewardTypes { - id := entry.RewardIDs[i] - if typ != 45 || id == 0 || entry.RewardCounts[i] != 1 || seen[id] { - return errors.New("starter prestige-skin gift must contain unique Type45 designs") - } - seen[id] = true - } - return nil -} - // enqueueCompensations shares the EnqueueCompensation allocator and durable // identity ledger. The entire batch is prepared before a single atomic write; // neither storage nor memory can retain a partially imported grant spool. diff --git a/go/internal/server/domain/mail/protocol_adapter.go b/go/internal/server/domain/mail/protocol_adapter.go index b139381..726e4ae 100644 --- a/go/internal/server/domain/mail/protocol_adapter.go +++ b/go/internal/server/domain/mail/protocol_adapter.go @@ -126,6 +126,9 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int, } if path == "/MailInfo" { + if err := s.refreshStarterGifts(ctx); err != nil { + return 0, nil, true, err + } grants, err := readGrantSpool(s.grantSpoolPath, ctx.AccountID) if err != nil { return 0, nil, true, err @@ -223,7 +226,7 @@ func (s *Service) open(ctx command.Context, request []byte) ([]byte, error) { } } if s.isAttendanceMail(entry.MailID) { - if s.attendanceEconomy == nil { + if s.attachmentEconomy == nil { return nil, errors.New("mail: attendance reward economy unavailable") } if !containsID(s.state.Opened, entry.MailID) && uint64(s.now().UnixMilli()) >= entry.ExpiresAt { @@ -233,6 +236,14 @@ func (s *Service) open(ctx command.Context, request []byte) ([]byte, error) { return nil, err } } + if !entry.IsCash && s.requiresAttachmentEconomy(entry) { + if s.attachmentEconomy == nil { + return nil, errors.New("mail: attachment reward economy unavailable") + } + if !containsID(s.state.Opened, entry.MailID) && uint64(s.now().UnixMilli()) >= entry.ExpiresAt { + return nil, errors.New("mail: compensation mail expired") + } + } } var bundle []byte @@ -242,6 +253,9 @@ func (s *Service) open(ctx command.Context, request []byte) ([]byte, error) { newHistory := make([]MailDBInfo, 0, len(selected)) for _, entry := range selected { identity := fmt.Sprintf("mail:%d", entry.MailID) + if containsID(next.Opened, entry.MailID) && s.isStarterAvatarGift(entry.MailID) { + continue + } if entry.IsCash { granted, err := s.cashEconomy.ApplyResolved(ctx, identity+":cash", nil, mailAttachments(entry)) if err != nil { @@ -249,7 +263,13 @@ func (s *Service) open(ctx command.Context, request []byte) ([]byte, error) { } bundle = append(bundle, granted...) } else if s.isAttendanceMail(entry.MailID) { - granted, err := s.attendanceEconomy.Apply(ctx, identity+":attendance", nil, mailAttachments(entry)) + granted, err := s.attachmentEconomy.Apply(ctx, identity+":attendance", nil, mailAttachments(entry)) + if err != nil { + return nil, err + } + bundle = append(bundle, granted...) + } else if s.requiresAttachmentEconomy(entry) { + granted, err := s.attachmentEconomy.Apply(ctx, identity+":compensation", nil, s.unownedStarterAttachments(ctx, entry)) if err != nil { return nil, err } diff --git a/go/internal/server/domain/mail/starter_gifts.go b/go/internal/server/domain/mail/starter_gifts.go new file mode 100644 index 0000000..33bbb66 --- /dev/null +++ b/go/internal/server/domain/mail/starter_gifts.go @@ -0,0 +1,106 @@ +package mail + +import ( + "fmt" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/startergift" +) + +type starterGiftProvider func(command.Context) ([]startergift.Gift, error) + +func (s *Service) AttachStarterGifts(ctx command.Context, provider func(command.Context) ([]startergift.Gift, error)) error { + if s == nil || provider == nil { + return fmt.Errorf("mail: unavailable starter gift provider") + } + s.starterGifts = provider + return s.refreshStarterGifts(ctx) +} + +func (s *Service) refreshStarterGifts(ctx command.Context) error { + if s.starterGifts == nil { + return nil + } + gifts, err := s.starterGifts(ctx) + if err != nil { + return err + } + if err := s.validateStarterGifts(); err != nil { + return err + } + seen := map[string]bool{} + var grants []compensation + for _, gift := range gifts { + if seen[gift.Identity] { + return fmt.Errorf("mail: duplicate starter gift %q", gift.Identity) + } + seen[gift.Identity] = true + if err := startergift.ValidateRewards(gift.Identity, gift.Rewards); err != nil { + return err + } + if _, issued := s.issued[gift.Identity]; issued { + continue + } + grant := compensation{identity: gift.Identity, title: gift.Title, body: gift.Body, rewards: gift.Rewards, sentAt: s.now().UTC()} + if err := grant.validate(); err != nil { + return err + } + grants = append(grants, grant) + } + return s.enqueueCompensations(ctx, grants) +} + +func (s *Service) validateStarterGifts() error { + for identity, id := range s.issued { + if identity != startergift.LimitedCostumes && identity != startergift.PrestigeSkins && !startergift.IsAvatarGift(identity) { + continue + } + entry := s.dynamic[id] + if entry.MailID == 0 || len(entry.RewardTypes) != len(entry.RewardIDs) || len(entry.RewardTypes) != len(entry.RewardCounts) { + return fmt.Errorf("mail: invalid saved starter gift %q", identity) + } + rewards := mailAttachments(entry) + if err := startergift.ValidateRewards(identity, rewards); err != nil { + return err + } + if identity == startergift.LimitedCostumes && s.costumeDesign != nil { + for _, reward := range rewards { + costume, ok := s.costumeDesign.Character(reward.ID) + if !ok || costume.CostumeMaxLevel != 5 { + return fmt.Errorf("mail: saved starter costume %d does not support +5", reward.ID) + } + } + } + } + return nil +} + +func (s *Service) unownedStarterAttachments(ctx command.Context, entry MailDBInfo) []gamedata.Reward { + rewards := mailAttachments(entry) + if !s.isStarterAvatarGift(entry.MailID) { + return rewards + } + owned := map[uint64]bool{} + for _, item := range s.inventory.All(ctx) { + if item.Type == 49 && item.Count != 0 { + owned[item.ID] = true + } + } + var missing []gamedata.Reward + for _, reward := range rewards { + if !owned[reward.ID] { + missing = append(missing, reward) + } + } + return missing +} + +func (s *Service) isStarterAvatarGift(mailID uint64) bool { + for identity, id := range s.issued { + if id == mailID && startergift.IsAvatarGift(identity) { + return true + } + } + return false +} diff --git a/go/internal/server/domain/profile/avatar.go b/go/internal/server/domain/profile/avatar.go index a709b42..c3cb922 100644 --- a/go/internal/server/domain/profile/avatar.go +++ b/go/internal/server/domain/profile/avatar.go @@ -27,6 +27,7 @@ type avatarState struct { type AvatarSource interface { AvatarItems(command.Context) []assets.Item AvatarCurrency(command.Context) assets.Currency + AvatarPriceBalance(command.Context, gamedata.Reward) (uint64, error) AvatarUnlocked(command.Context, gamedata.AvatarProduct) (bool, error) } type AvatarEconomy interface { @@ -187,6 +188,7 @@ func (s *AvatarService) buy(ctx command.Context, st *avatarState, products []ava } var costs, rewards []gamedata.Reward var diamondCost uint64 + var clientPriceRefund gamedata.Reward seen := map[uint64]bool{} for _, purchase := range products { if seen[purchase.ID] { @@ -246,7 +248,22 @@ func (s *AvatarService) buy(ctx command.Context, st *avatarState, products []ava return nil, fmt.Errorf("avatar: purchase count overflow") } price.Count *= count - if price.Count > 0 { + firstSelection := !st.FirstChosen && product.Initial && product.Reward.Type == 61 && !purchase.Motion + if firstSelection && len(products) != 1 { + return nil, fmt.Errorf("avatar: initial selection requires one character") + } + freeSelection := firstSelection && count == 1 && purchase.Cost == product.Price + if freeSelection && price.Count > 0 { + balance, err := s.source.AvatarPriceBalance(ctx, price) + if err != nil { + return nil, err + } + // The native first-choice callback still subtracts the nominal price, + // clamping at zero. Restore that predicted debit in its response only. + clientPriceRefund = price + clientPriceRefund.Count = min(balance, price.Count) + } + if price.Count > 0 && !freeSelection { if price.Type == 2 || price.Type == 3 { if price.ID != 0 || price.Count > math.MaxInt32-diamondCost { return nil, fmt.Errorf("avatar: combined diamond price overflow") @@ -269,7 +286,10 @@ func (s *AvatarService) buy(ctx command.Context, st *avatarState, products []ava owned[key] += r.Count rewards = append(rewards, r) } - if product.Initial && product.Reward.Type == 61 { + if firstSelection { + for _, id := range s.design.InitialUnlockTickets { + rewards = append(rewards, gamedata.Reward{Type: 19, ID: id, Count: 1}) + } st.FirstChosen = true } } @@ -298,6 +318,14 @@ func (s *AvatarService) buy(ctx command.Context, st *avatarState, products []ava if err = s.save(ctx, *st); err != nil { return nil, err } + if clientPriceRefund.Count != 0 { + item := wire.AppendVarint(nil, 3, clientPriceRefund.Type) + if clientPriceRefund.ID != 0 { + item = wire.AppendVarint(item, 2, clientPriceRefund.ID) + } + item = wire.AppendVarint(item, 4, clientPriceRefund.Count) + bundle = wire.AppendBytes(bundle, 1, item) + } return wire.AppendBytes(nil, 1, bundle), nil } func (s *AvatarService) applyUse(ctx command.Context, st *avatarState, use AvatarUse) error { diff --git a/go/internal/server/domain/progression/conditions/conditions.go b/go/internal/server/domain/progression/conditions/conditions.go new file mode 100644 index 0000000..b9129c4 --- /dev/null +++ b/go/internal/server/domain/progression/conditions/conditions.go @@ -0,0 +1,202 @@ +// Package conditions holds the MissionTable condition semantics shared by the +// regular (daily/weekly) and the scheduled event mission services. Values are +// Define_MissionConditionType protocol enums, never mission IDs. +package conditions + +import "slices" + +// Define_MissionConditionType values recorded by the server. +const ( + Connect uint64 = 0 // McConnect + TodayQuestClear uint64 = 1 // McTodayQuestClear + MonsterKill uint64 = 2 // McMonsterKill + CollectionGet uint64 = 3 // McCollectionGet + FieldRewardMonsterCatch uint64 = 5 // McFieldRewardMonsterCatch + TalentSkillUse uint64 = 6 // McTalentSkillUse + HuntingBattle uint64 = 7 // McHuntingBattle + GachaBuy uint64 = 9 // McGachaBuy + PackBattle uint64 = 10 // McPackBattle + ItemCurrencyUse uint64 = 11 // McItemCurrencyUse + ResourceUse uint64 = 12 // McResourceUse + EquipmentUpgrade uint64 = 14 // McEquipmentUpgrade + BattleModeStartTry uint64 = 18 // McBattleModeStartTry + BattleStartWithUniqueChar uint64 = 19 // McBattleModeStartTryWithUniqueCharId + EquipMakeGrade uint64 = 20 // McEquipMakeGrade + EquipSmelting uint64 = 21 // McEquipSmelting (gear option refinement) + HuntDispatch uint64 = 23 // McHuntDispatch + SkywayPositionGroupClear uint64 = 24 // McSkyWayDungeonPositionGroupLevelClear + CostumePotentialNodeKind uint64 = 26 // McCostumePotentialActivateNodeKind + PvpRankGoal uint64 = 27 // McPvpRankIdGoal + TalentSkillUpgrade uint64 = 29 // McTalentSkillUpgrade + SameGroupMissionComplete uint64 = 30 // McSamGroupIdMissionUpdateCompleteCount + OtherGroupMissionComplete uint64 = 31 // McOtherGroupIdMissionUpdateCompleteCount + ItemCurrencyGet uint64 = 32 // McItemCurrencyGet + CafeteriaCumulativeReward uint64 = 33 // McCafeteriaCumulativeReward + MyRoomVisit uint64 = 34 // McMyRoomVisit + MyRoomLike uint64 = 36 // McMyRoomLike + ArcadeMenuVisit uint64 = 37 // McArcadeMenuVisit + PackQuestIDClear uint64 = 38 // McPackQuestIdClear + LobbyItemSettingChange uint64 = 39 // McLobbyItemSettingChange + DatingEpisodeClear uint64 = 40 // McDatingEpisodeClear + GuildLobbyUIEnter uint64 = 41 // McGuildLobbyUiEnter + CharImprintLevelUp uint64 = 42 // McCharImprintLevelUp + CharAwakeActive uint64 = 43 // McCharAwakeActive + EquipMakingUIEnter uint64 = 44 // McEquipMakingUiEnter + EquipUpgradeUIEnter uint64 = 45 // McEquipUpgradeUiEnter + MonsterHuntBattleWithTraining uint64 = 46 // McTryToBattleInMonsterHuntIncludeTraining + EvilCastleRageTowerClear uint64 = 47 // McEvilCastleRageTowerClear + EvilCastleEnvyTowerClear uint64 = 48 // McEvilCastleEnvyTowerClear + CostumeUpgrade uint64 = 104 // McCostumeUpgrade + GachaGroupTry uint64 = 105 // McTryToGachaToTargetGachaGroup + EnterPackInField uint64 = 204 // McEnterPackInField + CharTargetLevelUp uint64 = 207 // McCharTargetLevelUp + CharTargetGradeUp uint64 = 208 // McCharTargetGradeUp + CharScoutToTargetGrade uint64 = 209 // McTryToCharScoutToTargetGrade + BuyItemInShop uint64 = 211 // McBuyItemINShop + EquipmentUpgradeToLevel uint64 = 213 // McSuccessEquipmentUpgradeToTargetLevel + EquipEquipmentItem uint64 = 214 // McTryToEquipEquipmentItem + ChangeEquipmentItem uint64 = 215 // McTryToChangeEquipmentItem + BreakEquipmentItem uint64 = 216 // McTryToBreakEquipmentItem + SmeltEquipmentItem uint64 = 217 // McTryToSmeltEquipmentItem + UseAutoHunting uint64 = 224 // McTryToUseAutoHunting + ChangeCostumeInBattle uint64 = 226 // McTryToChangeCostumeInBattle + SkywayGroupBattle uint64 = 227 // McTryToBattleInSkywayDungeonGroupId + EvilCastleFloorBattle uint64 = 228 // McTryToBattleInEvilCastleToTargetFloor + EvilCastleFloorClear uint64 = 229 // McClearInEvilCastleToTargetFloor + MonsterHuntBattle uint64 = 230 // McTryToBattleInMonsterHunt + PlatformConnectOrLogin uint64 = 231 // McPlatformConnectOrLogin + EvilCastleGreedTowerClear uint64 = 233 // McEvilCastleGreedTowerClear + MonsterHuntWin uint64 = 240 // McWinToBattleInMonsterHunt + TotalWarTryCount uint64 = 280 // McTotalWarTryCount + TotalWarResultScore uint64 = 281 // McTotalWarResultScore + MyRoomVisitAnotherUser uint64 = 312 // McMyRoomVisitAnotherUser + EventFieldMiniGamePlay uint64 = 315 // McEventFieldMiniGamePlay + MiniGameSurvivalCharLevel uint64 = 316 // McMiniGameSurvivalCharLevel + MiniGameSurvivalLifeTime uint64 = 317 // McMiniGameSurvivalLifeTime + MiniGameSurvivalSkillMaxCount uint64 = 318 // McMiniGameSurvivalSkillMaxLevelCount + MiniGameSurvivalKillCount uint64 = 319 // McMiniGameSurvivalKillMonsterCount + MiniGameSurvivalMapClear uint64 = 320 // McMiniGameSurvivalMapClear + MiniGameSurvivalSkillMax uint64 = 321 // McMiniGameSurvivalSpecificSkillMaxLevel + MiniGameDefenseWaveClear uint64 = 322 // McMiniGameDefenseWaveClear + MiniGameActionMonster uint64 = 323 // McMiniGameActionMonster + FishingShopBuy uint64 = 337 // McFishingShopBuy + FishingMultiParticipation uint64 = 338 // McFishingMultiParticipation + FishingVoyageStart uint64 = 340 // McFishingVoyageStart + FishingFishBiteEnd uint64 = 341 // McFishingFishBiteEnd + FishingBoatUpgrade uint64 = 342 // McFishingBoatUpgrade + MiniGamePlay uint64 = 343 // McMiniGamePlay + SquareReward uint64 = 344 // McSquareReward + ColosseumBattleWin uint64 = 345 // McColosseumBattleWin + TacticsBingoBattleWin uint64 = 346 // McTacticsBingoBattleWin + TacticsBingoLineClear uint64 = 347 // McTacticsBingoLineClear + TacticsBingoAllClear uint64 = 348 // McTacticsBingoAllClear + FieldSpawnEventReward uint64 = 349 // McFieldSpawnEventReward + FriendshipTargetLevelUp uint64 = 350 // McFriendshipTargetLevelUp + FriendshipCostumeLevelUp uint64 = 351 // McFriendshipCostumeLevelUp + PackManNormalGameOver uint64 = 360 // McMiniGamePackManNormalGameOver + PackManNormalClear uint64 = 361 // McMiniGamePackManNormalClear + PackManChallengeGameOver uint64 = 362 // McMiniGamePackManChallengeGameOver + PackManChallengeTimeoutScore uint64 = 363 // McMiniGamePackManChallengeTimeoutScore + PackManPlayCount uint64 = 364 // McMiniGamePackManPlayCount +) + +// ClientReported lists the UI-only conditions the native client reports +// itself through MissionUpdate (MissionPassPacket.UpdateMission call sites); +// no server request observes these actions. +var ClientReported = []uint64{ArcadeMenuVisit, LobbyItemSettingChange, GuildLobbyUIEnter, EquipMakingUIEnter, EquipUpgradeUIEnter, UseAutoHunting, ChangeCostumeInBattle, MyRoomVisitAnotherUser} + +// Spec is one MissionTable condition. +type Spec struct { + Type, SubType, SubTypeMoreCheck uint64 + // Params is ConditionSubTypeParams; empty or all zero accepts any value. + Params []uint64 +} + +// Event is one authoritative occurrence. Sub is compared with ConditionSubType +// and Param with ConditionSubTypeParams. +type Event struct { + Type, Sub, Param, Count uint64 +} + +// comparison selects between exact and at-least matching. +type comparison uint8 + +const ( + // compareDefault follows GameData: zero SubType accepts any sub; otherwise + // IsConditionSubTypeMoreCheck selects at-least, and Params are membership. + compareDefault comparison = iota + compareExact + compareAtLeast +) + +// conditionRule overrides the GameData comparison for one condition type. +// A forced comparison also applies to SubType zero instead of treating it as +// a wildcard. +type conditionRule struct { + sub comparison // compareDefault keeps SubTypeMoreCheck + param comparison // compareDefault is membership; compareAtLeast uses Params[0] +} + +// conditionRules covers types whose mission text compares at least while +// IsConditionSubTypeMoreCheck is zero, and McFieldSpawnEventReward, whose +// zero SubType names the normal spawn rather than any sub. +var conditionRules = map[uint64]conditionRule{ + EquipMakeGrade: {sub: compareAtLeast}, + TotalWarResultScore: {sub: compareAtLeast}, + MiniGameSurvivalCharLevel: {sub: compareAtLeast}, + MiniGameSurvivalSkillMaxCount: {sub: compareAtLeast}, + MiniGameSurvivalKillCount: {sub: compareAtLeast}, + MiniGameDefenseWaveClear: {sub: compareAtLeast}, + PackManChallengeTimeoutScore: {sub: compareAtLeast}, + MiniGameSurvivalLifeTime: {param: compareAtLeast}, + FieldSpawnEventReward: {sub: compareExact}, +} + +// Matches reports whether e advances a mission with this condition. +func (s Spec) Matches(e Event) bool { + return s.Type == e.Type && s.SubTypeReached(e.Sub) && s.ParamAccepts(e.Param) +} + +// AnyParam reports whether ConditionSubTypeParams places no restriction. +// GameData writes "no restriction" as either no value or a single zero. +func AnyParam(params []uint64) bool { + for _, p := range params { + if p != 0 { + return false + } + } + return true +} + +// SubTypeReached applies the ConditionSubType comparison to an achieved value. +func (s Spec) SubTypeReached(value uint64) bool { + switch conditionRules[s.Type].sub { + case compareAtLeast: + return value >= s.SubType + case compareExact: + return value == s.SubType + } + if s.SubType == 0 { + return true + } + if s.SubTypeMoreCheck != 0 { + return value >= s.SubType + } + return value == s.SubType +} + +// ParamAccepts applies the ConditionSubTypeParams filter to one value. +func (s Spec) ParamAccepts(value uint64) bool { + if AnyParam(s.Params) { + return true + } + if conditionRules[s.Type].param == compareAtLeast { + return value >= s.Params[0] + } + return slices.Contains(s.Params, value) +} + +// Target is ConditionValue; a zero value still requires one occurrence. +func Target(value uint64) uint64 { + return max(value, 1) +} diff --git a/go/internal/server/domain/progression/conditions/conditions_test.go b/go/internal/server/domain/progression/conditions/conditions_test.go new file mode 100644 index 0000000..3a0e114 --- /dev/null +++ b/go/internal/server/domain/progression/conditions/conditions_test.go @@ -0,0 +1,142 @@ +package conditions + +import ( + "maps" + "testing" +) + +func TestMatches(t *testing.T) { + tests := []struct { + name string + spec Spec + event Event + want bool + }{ + {"different type", Spec{Type: MonsterKill}, Event{Type: HuntingBattle}, false}, + {"exact sub", Spec{Type: EquipmentUpgrade, SubType: 2}, Event{Type: EquipmentUpgrade, Sub: 2}, true}, + {"exact sub differs", Spec{Type: EquipmentUpgrade, SubType: 2}, Event{Type: EquipmentUpgrade, Sub: 3}, false}, + {"more check accepts higher", Spec{Type: EquipmentUpgrade, SubType: 2, SubTypeMoreCheck: 1}, Event{Type: EquipmentUpgrade, Sub: 3}, true}, + {"more check accepts equal", Spec{Type: EquipmentUpgrade, SubType: 2, SubTypeMoreCheck: 1}, Event{Type: EquipmentUpgrade, Sub: 2}, true}, + {"more check rejects lower", Spec{Type: EquipmentUpgrade, SubType: 2, SubTypeMoreCheck: 1}, Event{Type: EquipmentUpgrade, Sub: 1}, false}, + {"zero sub accepts any", Spec{Type: MonsterKill}, Event{Type: MonsterKill, Sub: 7}, true}, + {"rule accepts higher", Spec{Type: EquipMakeGrade, SubType: 2}, Event{Type: EquipMakeGrade, Sub: 3}, true}, + {"rule accepts equal", Spec{Type: EquipMakeGrade, SubType: 2}, Event{Type: EquipMakeGrade, Sub: 2}, true}, + {"rule rejects lower", Spec{Type: EquipMakeGrade, SubType: 2}, Event{Type: EquipMakeGrade, Sub: 1}, false}, + {"rule zero sub accepts any", Spec{Type: EquipMakeGrade}, Event{Type: EquipMakeGrade, Sub: 4}, true}, + {"exact rule distinguishes zero", Spec{Type: FieldSpawnEventReward}, Event{Type: FieldSpawnEventReward, Sub: 0}, true}, + {"exact rule rejects other sub", Spec{Type: FieldSpawnEventReward}, Event{Type: FieldSpawnEventReward, Sub: 1}, false}, + {"no params accepts any", Spec{Type: BuyItemInShop}, Event{Type: BuyItemInShop, Param: 9}, true}, + {"zero params accept any", Spec{Type: BuyItemInShop, Params: []uint64{0}}, Event{Type: BuyItemInShop, Param: 9}, true}, + {"params membership", Spec{Type: BuyItemInShop, Params: []uint64{3, 7}}, Event{Type: BuyItemInShop, Param: 7}, true}, + {"params rejects others", Spec{Type: BuyItemInShop, Params: []uint64{3, 7}}, Event{Type: BuyItemInShop, Param: 5}, false}, + {"param threshold accepts higher", Spec{Type: MiniGameSurvivalLifeTime, Params: []uint64{300}}, Event{Type: MiniGameSurvivalLifeTime, Param: 600}, true}, + {"param threshold rejects lower", Spec{Type: MiniGameSurvivalLifeTime, Params: []uint64{300}}, Event{Type: MiniGameSurvivalLifeTime, Param: 299}, false}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := test.spec.Matches(test.event); got != test.want { + t.Fatalf("Matches(%+v, %+v) = %v, want %v", test.spec, test.event, got, test.want) + } + }) + } +} + +func TestSubTypeReached(t *testing.T) { + tests := []struct { + name string + spec Spec + value uint64 + want bool + }{ + {"zero sub accepts any", Spec{Type: MonsterKill}, 9, true}, + {"exact", Spec{Type: EquipmentUpgrade, SubType: 2}, 2, true}, + {"exact rejects higher", Spec{Type: EquipmentUpgrade, SubType: 2}, 3, false}, + {"more check", Spec{Type: EquipmentUpgrade, SubType: 2, SubTypeMoreCheck: 1}, 3, true}, + {"more check equal", Spec{Type: EquipmentUpgrade, SubType: 2, SubTypeMoreCheck: 1}, 2, true}, + {"rule threshold", Spec{Type: MiniGameSurvivalKillCount, SubType: 1000}, 1500, true}, + {"rule threshold equal", Spec{Type: MiniGameSurvivalKillCount, SubType: 1000}, 1000, true}, + {"rule threshold rejects lower", Spec{Type: MiniGameSurvivalKillCount, SubType: 1000}, 999, false}, + {"exact rule zero", Spec{Type: FieldSpawnEventReward}, 0, true}, + {"exact rule rejects one", Spec{Type: FieldSpawnEventReward}, 1, false}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := test.spec.SubTypeReached(test.value); got != test.want { + t.Fatalf("SubTypeReached(%+v, %d) = %v, want %v", test.spec, test.value, got, test.want) + } + }) + } +} + +func TestParamAccepts(t *testing.T) { + tests := []struct { + name string + spec Spec + value uint64 + want bool + }{ + {"empty", Spec{Type: BuyItemInShop}, 5, true}, + {"all zero", Spec{Type: BuyItemInShop, Params: []uint64{0, 0}}, 5, true}, + {"membership", Spec{Type: BuyItemInShop, Params: []uint64{5, 6}}, 5, true}, + {"not member", Spec{Type: BuyItemInShop, Params: []uint64{5, 6}}, 7, false}, + {"threshold", Spec{Type: MiniGameSurvivalLifeTime, Params: []uint64{300}}, 300, true}, + {"threshold higher", Spec{Type: MiniGameSurvivalLifeTime, Params: []uint64{300}}, 600, true}, + {"threshold lower", Spec{Type: MiniGameSurvivalLifeTime, Params: []uint64{300}}, 299, false}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := test.spec.ParamAccepts(test.value); got != test.want { + t.Fatalf("ParamAccepts(%+v, %d) = %v, want %v", test.spec, test.value, got, test.want) + } + }) + } +} + +var expectedConditionRules = map[uint64]conditionRule{ + EquipMakeGrade: {sub: compareAtLeast}, + TotalWarResultScore: {sub: compareAtLeast}, + MiniGameSurvivalCharLevel: {sub: compareAtLeast}, + MiniGameSurvivalSkillMaxCount: {sub: compareAtLeast}, + MiniGameSurvivalKillCount: {sub: compareAtLeast}, + MiniGameDefenseWaveClear: {sub: compareAtLeast}, + PackManChallengeTimeoutScore: {sub: compareAtLeast}, + MiniGameSurvivalLifeTime: {param: compareAtLeast}, + FieldSpawnEventReward: {sub: compareExact}, +} + +// TestConditionRules pins the forced comparisons and checks each one, so a +// removed or mistyped table entry cannot hide behind the hand-picked cases. +func TestConditionRules(t *testing.T) { + if !maps.Equal(conditionRules, expectedConditionRules) { + t.Fatalf("condition rules = %v, want %v", conditionRules, expectedConditionRules) + } + for conditionType, rule := range conditionRules { + switch rule.sub { + case compareAtLeast: + spec := Spec{Type: conditionType, SubType: 5} + if !spec.SubTypeReached(5) || !spec.SubTypeReached(6) || spec.SubTypeReached(4) { + t.Fatalf("condition %d at-least rule does not compare >= 5", conditionType) + } + case compareExact: + spec := Spec{Type: conditionType, SubType: 0} + if !spec.SubTypeReached(0) || spec.SubTypeReached(1) { + t.Fatalf("condition %d exact rule does not keep zero a value", conditionType) + } + } + if rule.param == compareAtLeast { + spec := Spec{Type: conditionType, Params: []uint64{5}} + if !spec.ParamAccepts(5) || !spec.ParamAccepts(6) || spec.ParamAccepts(4) { + t.Fatalf("condition %d param rule does not compare >= 5", conditionType) + } + } + } +} + +func TestTarget(t *testing.T) { + if got := Target(0); got != 1 { + t.Fatalf("Target(0) = %d, want 1", got) + } + if got := Target(7); got != 7 { + t.Fatalf("Target(7) = %d, want 7", got) + } +} diff --git a/go/internal/server/domain/progression/missions/events.go b/go/internal/server/domain/progression/missions/events.go index 0ead87a..e873535 100644 --- a/go/internal/server/domain/progression/missions/events.go +++ b/go/internal/server/domain/progression/missions/events.go @@ -6,23 +6,17 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" ) -// These values are Define_MissionConditionType protocol enums, not mission IDs. -const ( - ConditionConnect uint64 = 0 - ConditionMonsterKill uint64 = 2 - ConditionGachaBuy uint64 = 9 -) - -// RecordEvent applies an authoritative gameplay count to every matching regular -// mission. The caller supplies quest unlock state; locked and scheduled event -// missions cannot become eligible merely because they share the condition. -func (s *Service) RecordEvent(ctx command.Context, conditionType, subType, count uint64, unlocked func(command.Context, uint64, uint64) bool) error { +// RecordEvent applies an authoritative gameplay occurrence to every matching +// regular mission. The caller supplies quest unlock state; locked and scheduled +// event missions cannot become eligible merely because they share the condition. +func (s *Service) RecordEvent(ctx command.Context, event conditions.Event, unlocked func(command.Context, uint64, uint64) bool) error { if observer, ok := s.eventHandler.(interface { - RecordEvent(ctx command.Context, _ uint64, _ uint64, _ uint64, _ func(command.Context, uint64, uint64) bool) error + RecordEvent(command.Context, conditions.Event, func(command.Context, uint64, uint64) bool) error }); ok { - if err := observer.RecordEvent(ctx, conditionType, subType, count, unlocked); err != nil { + if err := observer.RecordEvent(ctx, event, unlocked); err != nil { return err } } @@ -30,7 +24,7 @@ func (s *Service) RecordEvent(ctx command.Context, conditionType, subType, count if err := s.rolloverLocked(ctx); err != nil { return err } - return s.recordEventLocked(ctx, conditionType, subType, count, unlocked) + return s.recordEventLocked(ctx, event, unlocked) } // RecordLogin records at most one connection per daily period. The existing @@ -51,52 +45,21 @@ func (s *Service) RecordLogin(ctx command.Context, unlocked func(command.Context if s.state.Progress["0/event/connect"] != 0 { return nil } - return s.recordEventLocked(ctx, ConditionConnect, 0, 1, unlocked) + return s.recordEventLocked(ctx, conditions.Event{Type: conditions.Connect, Count: 1}, unlocked) } -// CompleteSingleTargetEvent covers evidence of at least one occurrence, without -// inventing a count or subtype for richer missions (e.g. a monster encounter win). -func (s *Service) CompleteSingleTargetEvent(ctx command.Context, conditionType uint64, unlocked func(command.Context, uint64, uint64) bool) error { - if observer, ok := s.eventHandler.(interface { - CompleteSingleTargetEvent(ctx command.Context, _ uint64, _ func(command.Context, uint64, uint64) bool) error - }); ok { - if err := observer.CompleteSingleTargetEvent(ctx, conditionType, unlocked); err != nil { - return err - } - } - - if err := s.rolloverLocked(ctx); err != nil { - return err - } - next := cloneSnapshot(s.state) - for key, c := range s.design.Conditions { - if key.GroupType > 1 || !s.missionActive(key) || c.Type != conditionType || c.SubType != 0 || c.TargetValue != 1 || len(c.Params) != 0 { - continue - } - if (c.UnlockPack != 0 || c.UnlockQuest != 0) && (unlocked == nil || !unlocked(ctx, c.UnlockPack, c.UnlockQuest)) { - continue - } - name := missionName(key) - if next.Progress[name] >= 1 { - continue - } - next.Progress[name] = 1 - s.applyCompletionDependencies(&next, key) - } - return s.commit(ctx, next) +func conditionSpec(c gamedata.MissionCondition) conditions.Spec { + return conditions.Spec{Type: c.Type, SubType: c.SubType, SubTypeMoreCheck: c.SubTypeComparison, Params: c.Params} } -func (s *Service) recordEventLocked(ctx command.Context, conditionType, subType, count uint64, unlocked func(command.Context, uint64, uint64) bool) error { - if count == 0 { +func (s *Service) recordEventLocked(ctx command.Context, event conditions.Event, unlocked func(command.Context, uint64, uint64) bool) error { + if event.Count == 0 { return errors.New("missions: event count is zero") } next := cloneSnapshot(s.state) var keys []gamedata.MissionKey for key, condition := range s.design.Conditions { - if key.GroupType > 1 || !s.missionActive(key) || condition.Type != conditionType || len(condition.Params) != 0 { - continue - } - if condition.SubType != 0 && ((condition.SubTypeComparison == 0 && condition.SubType != subType) || (condition.SubTypeComparison == 1 && subType < condition.SubType)) { + if key.GroupType > 1 || !s.missionActive(key) || !conditionSpec(condition).Matches(event) { continue } if (condition.UnlockPack != 0 || condition.UnlockQuest != 0) && (unlocked == nil || !unlocked(ctx, condition.UnlockPack, condition.UnlockQuest)) { @@ -116,21 +79,18 @@ func (s *Service) recordEventLocked(ctx command.Context, conditionType, subType, }) for _, key := range keys { name := missionName(key) - target := s.design.Conditions[key].TargetValue - if target == 0 { - target = 1 - } + target := conditions.Target(s.design.Conditions[key].TargetValue) before := next.Progress[name] if before >= target { continue } - increment := min(count, target-before) + increment := min(event.Count, target-before) next.Progress[name] = before + increment if next.Progress[name] == target { s.applyCompletionDependencies(&next, key) } } - if conditionType == ConditionConnect { + if event.Type == conditions.Connect { next.Progress["0/event/connect"] = 1 } return s.commit(ctx, next) diff --git a/go/internal/server/domain/progression/missions/missions.go b/go/internal/server/domain/progression/missions/missions.go index f37b5b8..43f23bd 100644 --- a/go/internal/server/domain/progression/missions/missions.go +++ b/go/internal/server/domain/progression/missions/missions.go @@ -9,6 +9,7 @@ import ( "bd2server/internal/server/domain/command" assets "bd2server/internal/server/domain/inventory" "bd2server/internal/server/domain/mail" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/storage/stateio" "encoding/json" "errors" @@ -556,7 +557,72 @@ func (s *Service) commit(ctx command.Context, next snapshot) error { if next.DailyPeriod == s.state.DailyPeriod && next.WeeklyPeriod == s.state.WeeklyPeriod && equalStrings(next.Completed, s.state.Completed) && equalStrings(next.Claimed, s.state.Claimed) && equalProgress(next.Progress, s.state.Progress) { return nil } - return s.persist(ctx, next) + completed := s.newlyCompletedGroups(next) + if err := s.persist(ctx, next); err != nil { + return err + } + return s.forwardCompletions(ctx, completed) +} + +// newlyCompletedGroups counts, per regular GroupId, the missions that next +// completes for the first time in the current period. +func (s *Service) newlyCompletedGroups(next snapshot) map[uint64]uint64 { + completed := map[uint64]uint64{} + for name, value := range next.Progress { + var key gamedata.MissionKey + if _, err := fmt.Sscanf(name, "%d/%d/%d", &key.GroupType, &key.GroupID, &key.ID); err != nil { + continue + } + condition, ok := s.design.Conditions[key] + if !ok || key.GroupType > 1 { + continue + } + target := conditions.Target(condition.TargetValue) + if s.state.Progress[name] < target && value >= target { + completed[key.GroupID]++ + } + } + return completed +} + +// forwardCompletions lets regular and scheduled missions count completed +// missions in the same group (McSamGroupIdMissionUpdateCompleteCount) or in +// another group (McOtherGroupIdMissionUpdateCompleteCount, SubType = GroupId). +func (s *Service) forwardCompletions(ctx command.Context, completed map[uint64]uint64) error { + observer, ok := s.eventHandler.(interface { + RecordEvent(command.Context, conditions.Event, func(command.Context, uint64, uint64) bool) error + }) + if !ok { + return nil + } + groups := slices.Sorted(maps.Keys(completed)) + for _, group := range groups { + events := []conditions.Event{ + {Type: conditions.SameGroupMissionComplete, Sub: group, Count: completed[group]}, + {Type: conditions.OtherGroupMissionComplete, Sub: group, Count: completed[group]}, + } + for _, event := range events { + if err := observer.RecordEvent(ctx, event, nil); err != nil { + return err + } + } + } + return nil +} + +// CompletedMissionCount is the number of regular missions of a GroupId whose +// current-period progress reached its target. +func (s *Service) CompletedMissionCount(groupID uint64) uint64 { + var count uint64 + for key, condition := range s.design.Conditions { + if key.GroupType > 1 || key.GroupID != groupID || !s.missionActive(key) { + continue + } + if s.state.Progress[missionName(key)] >= conditions.Target(condition.TargetValue) { + count++ + } + } + return count } func (s *Service) persist(ctx command.Context, next snapshot) error { diff --git a/go/internal/server/domain/progression/missions/missions_test.go b/go/internal/server/domain/progression/missions/missions_test.go new file mode 100644 index 0000000..4bb1d1c --- /dev/null +++ b/go/internal/server/domain/progression/missions/missions_test.go @@ -0,0 +1,129 @@ +package missions + +import ( + "testing" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + assets "bd2server/internal/server/domain/inventory" + "bd2server/internal/server/domain/progression/conditions" + "bd2server/internal/server/storage/stateio" +) + +type recordingHandler struct{ events []conditions.Event } + +func (h *recordingHandler) Handle(command.Context, string, []byte) (int, []byte, bool, error) { + return 0, nil, false, nil +} + +func (h *recordingHandler) RecordEvent(_ command.Context, event conditions.Event, _ func(command.Context, uint64, uint64) bool) error { + h.events = append(h.events, event) + return nil +} + +func newTestService(t *testing.T, design *gamedata.MissionDesign) (command.Context, *Service) { + t.Helper() + ctx := command.Context{State: stateio.NewMemory()} + inventory, err := assets.OpenInventory(ctx, stateio.RootStore{}, nil) + if err != nil { + t.Fatal(err) + } + service, err := Open(ctx, stateio.RootStore{}, design, inventory) + if err != nil { + t.Fatal(err) + } + return ctx, service +} + +// Completed regular missions must reach scheduled event missions as same-group +// and other-group completion events, while a completion in another group does +// not advance the other-group counter. +func TestCompletionsForwardGroupEvents(t *testing.T) { + daily := gamedata.MissionKey{GroupType: 0, GroupID: 1, ID: 1} + weekly := gamedata.MissionKey{GroupType: 1, GroupID: 2, ID: 2} + victory := gamedata.MissionKey{GroupType: 1, GroupID: 2, ID: 4} + design := &gamedata.MissionDesign{ + Missions: map[gamedata.MissionKey][]gamedata.Reward{daily: nil, weekly: nil, victory: nil}, + Conditions: map[gamedata.MissionKey]gamedata.MissionCondition{ + daily: {Type: conditions.MonsterKill, TargetValue: 1}, + weekly: {Type: conditions.OtherGroupMissionComplete, SubType: 1, TargetValue: 5}, + victory: {Type: conditions.HuntingBattle, TargetValue: 1}, + }, + } + ctx, service := newTestService(t, design) + handler := &recordingHandler{} + if err := service.AttachEventHandler(ctx, handler); err != nil { + t.Fatal(err) + } + assertEvents := func(want ...conditions.Event) { + t.Helper() + if len(handler.events) != len(want) { + t.Fatalf("events = %+v, want %+v", handler.events, want) + } + for i := range want { + if handler.events[i] != want[i] { + t.Fatalf("event %d = %+v, want %+v", i, handler.events[i], want[i]) + } + } + } + if err := service.RecordEvent(ctx, conditions.Event{Type: conditions.MonsterKill, Count: 1}, nil); err != nil { + t.Fatal(err) + } + assertEvents( + conditions.Event{Type: conditions.MonsterKill, Count: 1}, + conditions.Event{Type: conditions.SameGroupMissionComplete, Sub: 1, Count: 1}, + conditions.Event{Type: conditions.OtherGroupMissionComplete, Sub: 1, Count: 1}, + ) + if got := service.state.Progress["1/2/2"]; got != 1 { + t.Fatalf("other-group counter = %d, want 1", got) + } + handler.events = nil + if err := service.RecordEvent(ctx, conditions.Event{Type: conditions.HuntingBattle, Count: 1}, nil); err != nil { + t.Fatal(err) + } + assertEvents( + conditions.Event{Type: conditions.HuntingBattle, Count: 1}, + conditions.Event{Type: conditions.SameGroupMissionComplete, Sub: 2, Count: 1}, + conditions.Event{Type: conditions.OtherGroupMissionComplete, Sub: 2, Count: 1}, + ) + if got := service.state.Progress["1/2/2"]; got != 1 { + t.Fatalf("group 2 completion advanced the group 1 counter to %d", got) + } +} + +// CompletedMissionCount counts only the requested group's reached missions. +func TestCompletedMissionCountFiltersByGroup(t *testing.T) { + first := gamedata.MissionKey{GroupType: 0, GroupID: 1, ID: 1} + second := gamedata.MissionKey{GroupType: 0, GroupID: 1, ID: 2} + other := gamedata.MissionKey{GroupType: 0, GroupID: 2, ID: 3} + design := &gamedata.MissionDesign{ + Missions: map[gamedata.MissionKey][]gamedata.Reward{first: nil, second: nil, other: nil}, + Conditions: map[gamedata.MissionKey]gamedata.MissionCondition{ + first: {Type: conditions.MonsterKill, TargetValue: 1}, + second: {Type: conditions.HuntingBattle, TargetValue: 1}, + other: {Type: conditions.GachaBuy, TargetValue: 1}, + }, + } + ctx, service := newTestService(t, design) + if err := service.RecordEvent(ctx, conditions.Event{Type: conditions.MonsterKill, Count: 1}, nil); err != nil { + t.Fatal(err) + } + if got := service.CompletedMissionCount(1); got != 1 { + t.Fatalf("group 1 count after one mission = %d, want 1", got) + } + if err := service.RecordEvent(ctx, conditions.Event{Type: conditions.HuntingBattle, Count: 1}, nil); err != nil { + t.Fatal(err) + } + if err := service.RecordEvent(ctx, conditions.Event{Type: conditions.GachaBuy, Count: 1}, nil); err != nil { + t.Fatal(err) + } + if got := service.CompletedMissionCount(1); got != 2 { + t.Fatalf("group 1 count = %d, want 2", got) + } + if got := service.CompletedMissionCount(2); got != 1 { + t.Fatalf("group 2 count = %d, want 1", got) + } + if got := service.CompletedMissionCount(3); got != 0 { + t.Fatalf("unknown group count = %d, want 0", got) + } +} diff --git a/go/internal/server/domain/roster/collection.go b/go/internal/server/domain/roster/collection.go index 71bee96..f662a08 100644 --- a/go/internal/server/domain/roster/collection.go +++ b/go/internal/server/domain/roster/collection.go @@ -135,8 +135,6 @@ const FirstGachaCompletedIdentity = "account:first-gacha-completed" type collectionSnapshot struct { Version string `json:"version"` - NextCharacterIndex uint64 `json:"next_character_index"` - NextCostumeIndex uint64 `json:"next_costume_index"` LatestPreview []uint64 `json:"latest_preview"` PreviewEventIndex uint64 `json:"preview_event_index"` PreviewLocked bool `json:"preview_locked"` @@ -624,11 +622,15 @@ func (s *CollectionStore) grantCostumesSorted(ctx command.Context, identity stri if err != nil { return CollectionGrant{}, err } - costumeIndex := next.NextCostumeIndex - next.NextCostumeIndex++ + costumeIndex, err := ctx.NewInstanceID() + if err != nil { + return CollectionGrant{}, err + } if !characterExists { - characterIndex = next.NextCharacterIndex - next.NextCharacterIndex++ + characterIndex, err = ctx.NewInstanceID() + if err != nil { + return CollectionGrant{}, err + } ownedCharacter := Character{InvenIndex: characterIndex, ID: characterDesign.ID, HP: characterDesign.HP, Level: 1, CostumeID: costumeID, UseCostume: costumeIndex, TalentLevel: 1, SolidarityReward: 1, ExpiryTime: ^uint64(0) - 32399999, ConnectPotentialCostume: costumeID} diff --git a/go/internal/server/domain/roster/collection_entries.go b/go/internal/server/domain/roster/collection_entries.go index db82460..07e2c00 100644 --- a/go/internal/server/domain/roster/collection_entries.go +++ b/go/internal/server/domain/roster/collection_entries.go @@ -23,7 +23,7 @@ var collectionEntryBuckets = [...]string{ } func rejectInlineCollectionEntries(raw []byte) error { - if err := stateio.RequireExactJSONObject(raw, "version", "next_character_index", "next_costume_index", "latest_preview", "preview_event_index", "preview_locked", "base_costume_levels", "gacha_count_corrected"); err != nil { + if err := stateio.RequireExactJSONObject(raw, "version", "latest_preview", "preview_event_index", "preview_locked", "base_costume_levels", "gacha_count_corrected"); err != nil { return fmt.Errorf("player: incompatible collection core: %w", err) } var fields map[string]json.RawMessage diff --git a/go/internal/server/domain/roster/protocol_costume_adapter.go b/go/internal/server/domain/roster/protocol_costume_adapter.go index 9a497c4..8bfb5f6 100644 --- a/go/internal/server/domain/roster/protocol_costume_adapter.go +++ b/go/internal/server/domain/roster/protocol_costume_adapter.go @@ -1061,7 +1061,7 @@ func OpenCollectionStore(ctx command.Context, store stateio.Store, base []Costum return nil, errors.New("player: collection store requires atomic entry storage") } s := &CollectionStore{store: entries, base: append([]Costume(nil), base...), data: collectionSnapshot{ - Version: versionconfig.State(), NextCharacterIndex: 920000001, NextCostumeIndex: 930000001, + Version: versionconfig.State(), BaseCostumeLevels: map[string]uint64{}, GachaSelections: map[string][]GachaSelection{}, GachaSelectionChanges: map[string]uint64{}, CostumePotential: map[string][]uint64{}, CostumePotentialLocks: map[string][]uint64{}, CostumeBurstLevels: map[string]uint64{}, CostumeBurstUpgrades: map[string]CostumeBurstUpgradeRecord{}, @@ -1090,7 +1090,7 @@ func OpenCollectionStore(ctx command.Context, store stateio.Store, base []Costum if err := loadCollectionEntries(ctx, entries, &s.data); err != nil { return nil, err } - if s.data.Version != versionconfig.State() || s.data.NextCharacterIndex < 920000001 || s.data.NextCostumeIndex < 930000001 { + if s.data.Version != versionconfig.State() { return nil, errors.New("player: invalid collection save") } if s.data.BaseCostumeLevels == nil { diff --git a/go/internal/server/domain/roster/protocol_talent_adapter.go b/go/internal/server/domain/roster/protocol_talent_adapter.go index 7199834..8568581 100644 --- a/go/internal/server/domain/roster/protocol_talent_adapter.go +++ b/go/internal/server/domain/roster/protocol_talent_adapter.go @@ -1117,10 +1117,13 @@ func (s *TalentUseService) applyCharm(ctx command.Context, _ string, _ Character if d.CharacterID == 0 || d.CostumeID == 0 || d.HP == 0 { return nil, fmt.Errorf("player: invalid charm companion design") } - if pack <= 0 || pack >= 65536 || d.CharacterID >= 1<<32 { - return nil, fmt.Errorf("player: charm instance namespace overflow") + if pack <= 0 { + return nil, fmt.Errorf("player: invalid charm pack") + } + index, err := s.characters.CharmCharacterIndex(ctx, uint64(pack), d.CharacterID) + if err != nil { + return nil, err } - index := CharmCharacterIndexBase | uint64(pack)<<32 | d.CharacterID chars = append(chars, Character{InvenIndex: index, ID: d.CharacterID, Level: d.Level, HP: d.HP, CostumeID: d.CostumeID, TalentLevel: 1, ExpiryTime: expiry}) } if err = s.characters.ensureCharmCharacters(ctx, chars); err != nil { diff --git a/go/internal/server/domain/roster/roster_progress_test.go b/go/internal/server/domain/roster/roster_progress_test.go index a12fdb1..828929a 100644 --- a/go/internal/server/domain/roster/roster_progress_test.go +++ b/go/internal/server/domain/roster/roster_progress_test.go @@ -11,6 +11,7 @@ import ( "bd2server/internal/server/domain/roster/deck" "bd2server/internal/server/protocol/wire" accountstate "bd2server/internal/server/storage/account" + "bd2server/internal/server/storage/instanceid" "bd2server/internal/server/storage/outbox" "bd2server/internal/server/storage/stateio" "context" @@ -43,7 +44,7 @@ func openProgress(t *testing.T, path string, d *gamedata.RosterProgressDesign, p t.Fatal(e) } t.Cleanup(func() { _ = tx.Rollback(); _ = r.Close() }) - ctx := command.Context{Identity: command.Identity{AccountID: "roster-contract", SessionID: "session"}, State: tx} + ctx := command.Context{Identity: command.Identity{AccountID: "roster-contract", SessionID: "session"}, State: tx, InstanceIDs: instanceid.New(filepath.Join(filepath.Dir(path), "instance-ids.db"))} ctx.Emit = func(event command.Event) error { return outbox.Publish(tx, ctx.AccountID, event) } scope := stateio.RootStore{} i, e := assets.OpenInventory(ctx, scope, nil) diff --git a/go/internal/server/domain/roster/story_characters.go b/go/internal/server/domain/roster/story_characters.go index 76fd916..9bb55d0 100644 --- a/go/internal/server/domain/roster/story_characters.go +++ b/go/internal/server/domain/roster/story_characters.go @@ -2,13 +2,54 @@ package roster import ( "bd2server/internal/server/domain/command" + "bd2server/internal/server/storage/stateio" + "encoding/json" "fmt" - // StoryCharacterIndexBase reserves local instances for temporary quest parties. - // These are not collection rewards and never receive a collection grant. ) +// StoryCharacterIndexBase marks temporary quest parties, not collection rewards. const StoryCharacterIndexBase uint64 = 1 << 60 +func (s *CharacterStore) StoryCharacterIndex(ctx command.Context, pack, character, level uint64) (uint64, error) { + if pack == 0 || character == 0 || level == 0 { + return 0, fmt.Errorf("player: invalid story character identity") + } + return s.temporaryCharacterIndex(ctx, StoryCharacterIndexBase, fmt.Sprintf("story:%d:%d:%d", pack, character, level)) +} + +func (s *CharacterStore) CharmCharacterIndex(ctx command.Context, pack, character uint64) (uint64, error) { + if pack == 0 || character == 0 { + return 0, fmt.Errorf("player: invalid charm character identity") + } + return s.temporaryCharacterIndex(ctx, CharmCharacterIndexBase, fmt.Sprintf("charm:%d:%d", pack, character)) +} + +func (s *CharacterStore) temporaryCharacterIndex(ctx command.Context, namespace uint64, key string) (uint64, error) { + raw, found, err := s.store.LoadEntry(ctx.State, "characters", "temporary_instances", key) + if err != nil { + return 0, err + } + var index uint64 + if found { + if json.Unmarshal(raw, &index) != nil || index == 0 || index >= CharmCharacterIndexBase { + return 0, fmt.Errorf("player: invalid temporary instance identity %q", key) + } + } else { + index, err = ctx.NewInstanceID() + if err != nil { + return 0, err + } + payload, err := json.Marshal(index) + if err != nil { + return 0, err + } + if err := s.store.SaveWithEntries(ctx.State, "characters", nil, []stateio.EntryMutation{{Bucket: "temporary_instances", Key: key, Payload: payload}}); err != nil { + return 0, err + } + } + return namespace | index, nil +} + func IsStoryCharacter(c Character) bool { return c.InvenIndex >= StoryCharacterIndexBase } // EnsureStoryCharacters saves new authored temporary characters atomically. diff --git a/go/internal/server/domain/social/friend_supporters.go b/go/internal/server/domain/social/friend_supporters.go index 2024be1..11e8c8a 100644 --- a/go/internal/server/domain/social/friend_supporters.go +++ b/go/internal/server/domain/social/friend_supporters.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "encoding/json" + "fmt" "math" "slices" @@ -70,7 +71,7 @@ func supporterRelation(tx Tx, a, b uint64) (bool, error) { return rel.Accepted, err } -func supporterDeck(tx Tx, p FriendProfile, borrower uint64, day string, content uint64) ([]byte, error) { +func (f *Friends) supporterDeck(tx Tx, p FriendProfile, borrower uint64, day string, content uint64) ([]byte, error) { friends, err := supporterRelation(tx, borrower, p.OwnerIndex) if err != nil { return nil, err @@ -87,7 +88,7 @@ func supporterDeck(tx Tx, p FriendProfile, borrower uint64, day string, content if friends { out = wire.AppendVarint(out, 6, 1) } - base, err := friendWire(tx, p, 0) + base, err := f.friendWire(tx, p, 0) if err != nil { return nil, err } @@ -209,7 +210,7 @@ func (f *Friends) supporter(tx Tx, self FriendProfile, path string, p packet, no if err != nil { return nil, err } - allowed := (content == 0 || content == 1 || content == 5 || content == 6 || content == 1000) && (mode >= 1 && mode <= 5 || mode >= 9 && mode <= 15 || mode == 17) + allowed := (content == 0 || content == 1 || content == 5 || content == 6 || content == 1000) && (mode <= 5 || mode >= 9 && mode <= 15 || mode == 17) selection := supporterSelection{Content: content, Allowed: allowed} if err := save(tx, "friend.supporter_selection", accountPrefix(self.AccountID)+session, selection); err != nil { return nil, err @@ -248,7 +249,7 @@ func (f *Friends) supporter(tx Tx, self FriendProfile, path string, p packet, no field = 2 count++ } - deck, err := supporterDeck(tx, v, self.OwnerIndex, day, content) + deck, err := f.supporterDeck(tx, v, self.OwnerIndex, day, content) if err != nil { return nil, err } @@ -263,7 +264,7 @@ func (f *Friends) supporter(tx Tx, self FriendProfile, path string, p packet, no return nil, err } if !found || !selection.Allowed || selection.Content != content { - return nil, friendError(437, 9003, "Supporter selection is unavailable for this content") + return nil, friendError(437, 1, fmt.Sprintf("Supporter selection is unavailable: owner=%d content=%d selected_content=%d found=%t allowed=%t", self.OwnerIndex, content, selection.Content, found, selection.Allowed)) } lender, err := p.integer(2) if err != nil || lender == 0 || lender == self.OwnerIndex { @@ -279,11 +280,11 @@ func (f *Friends) supporter(tx Tx, self FriendProfile, path string, p packet, no return nil, err } if !found { - return nil, friendError(437, 9003, "Player not found") + return nil, friendError(437, 2, fmt.Sprintf("Supporter owner not found: lender=%d", lender)) } row, found, err := wire.Bytes(other.SupporterDetails[slot], 1) if err != nil || !found { - return nil, friendError(437, 9003, "Supporter slot is unavailable") + return nil, friendError(437, 1, fmt.Sprintf("Supporter slot is unavailable: lender=%d slot=%d", lender, slot)) } bundle, found, err := wire.Bytes(row, 6) if err != nil || !found { @@ -309,7 +310,11 @@ func (f *Friends) supporter(tx Tx, self FriendProfile, path string, p packet, no return nil, err } if count >= limit { - return nil, friendError(437, 9003, "Daily supporter uses exhausted") + code := 5 + if friends { + code = 3 + } + return nil, friendError(437, code, fmt.Sprintf("Daily supporter uses exhausted: borrower=%d lender=%d content=%d used=%d limit=%d friend=%t", self.OwnerIndex, lender, content, count, limit, friends)) } if err := save(tx, "friend.supporter_uses", useKey, count+1); err != nil { return nil, err @@ -355,7 +360,7 @@ func (f *Friends) supporter(tx Tx, self FriendProfile, path string, p packet, no if err := addGameplayCount(tx, self.OwnerIndex, 1, 0); err != nil { return nil, err } - deck, err := supporterDeck(tx, other, self.OwnerIndex, day, content) + deck, err := f.supporterDeck(tx, other, self.OwnerIndex, day, content) if err != nil { return nil, err } diff --git a/go/internal/server/domain/social/friends.go b/go/internal/server/domain/social/friends.go index 91ca757..213aca4 100644 --- a/go/internal/server/domain/social/friends.go +++ b/go/internal/server/domain/social/friends.go @@ -50,8 +50,11 @@ type Friends struct { now func() time.Time rooms *gamedata.RoomDesign supporters gamedata.SupporterRules + online func(string) bool } +func (f *Friends) AttachPresence(online func(string) bool) { f.online = online } + func NewFriends(store Store, rules gamedata.FriendRules, supporters gamedata.SupporterRules, rooms *gamedata.RoomDesign, now func() time.Time) (*Friends, error) { if store == nil || rules.Friends == 0 || rules.Sent == 0 || rules.Received == 0 || rules.Recommended == 0 || rules.ExpireDays == 0 { return nil, ErrInvalid @@ -99,7 +102,7 @@ func (f *Friends) Profile(ctx context.Context, owner uint64) (FriendProfile, err if _, err = load(tx, "friend.like_counts", numberKey(owner), &out.Snapshot.LikeCount); err != nil { return err } - row, err := friendWire(tx, out, 0) + row, err := f.friendWire(tx, out, 0) if err != nil { return err } @@ -181,7 +184,7 @@ func deleteFriend(tx Tx, a, b uint64) error { } return remove(tx, "friend.relations", key) } -func friendWire(tx Tx, p FriendProfile, date int64) ([]byte, error) { +func (f *Friends) friendWire(tx Tx, p FriendProfile, date int64) ([]byte, error) { out := wire.AppendVarint(nil, 1, p.OwnerIndex) out = wire.AppendVarint(out, 2, p.Snapshot.PortraitCostumeID) out = wire.AppendVarint(out, 3, p.Snapshot.PortraitDesignID) @@ -203,7 +206,11 @@ func friendWire(tx Tx, p FriendProfile, date int64) ([]byte, error) { base = wire.AppendString(base, 4, guild.IconColor) out = wire.AppendBytes(out, 7, base) } - out = wire.AppendVarint(out, 8, uint64(p.LastLoginMS)) + lastLogin := p.LastLoginMS + if f.online != nil && f.online(p.AccountID) { + lastLogin = f.now().Add(90 * time.Second).UnixMilli() + } + out = wire.AppendVarint(out, 8, uint64(lastLogin)) for _, costume := range p.Snapshot.Supporters { b := wire.AppendVarint(nil, 1, costume.ID) b = wire.AppendVarint(b, 2, costume.Level) @@ -336,7 +343,7 @@ func (f *Friends) Execute(ctx context.Context, identity command.Identity, owner if !found { return ErrNotFound } - row, err := friendWire(tx, profile, rel.CreatedMS) + row, err := f.friendWire(tx, profile, rel.CreatedMS) if err != nil { return err } @@ -367,7 +374,7 @@ func (f *Friends) Execute(ctx context.Context, identity command.Identity, owner if excluded[profile.OwnerIndex] { continue } - friend, err := friendWire(tx, profile, 0) + friend, err := f.friendWire(tx, profile, 0) if err != nil { return err } @@ -392,7 +399,7 @@ func (f *Friends) Execute(ctx context.Context, identity command.Identity, owner return friendError(code, 1, "Player not found") } if path == "/FriendSearch" { - row, err := friendWire(tx, other, 0) + row, err := f.friendWire(tx, other, 0) if err != nil { return err } @@ -469,7 +476,7 @@ func (f *Friends) Execute(ctx context.Context, identity command.Identity, owner return err } } - row, err := friendWire(tx, other, relation.CreatedMS) + row, err := f.friendWire(tx, other, relation.CreatedMS) if err != nil { return err } diff --git a/go/internal/server/domain/social/raid_overkill_test.go b/go/internal/server/domain/social/raid_overkill_test.go new file mode 100644 index 0000000..cfa1c42 --- /dev/null +++ b/go/internal/server/domain/social/raid_overkill_test.go @@ -0,0 +1,68 @@ +package social_test + +import ( + "context" + "encoding/json" + "fmt" + "testing" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/social" +) + +// LocalText 2001674/30061021: a guild's overkill score sums the overkill of +// its overkillMemberCount highest-scoring members and breaks score ties. +func TestGuildStandingsBreakTiesWithOverkillOfTopScoringMembers(t *testing.T) { + store := &memoryStore{rows: map[string]map[string][]byte{}} + design := &gamedata.GuildDesign{Guild: gamedata.GuildRules{MaxMembers: 30}, Raid: gamedata.GuildRaidRules{OverkillMemberCount: 10}} + owner, err := social.New(store, design) + if err != nil { + t.Fatal(err) + } + const season = 5 + key := func(v uint64) string { return fmt.Sprintf("%020d", v) } + put := func(tx social.Tx, bucket, k string, v any) { + raw, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + if err = tx.Put(bucket, k, raw); err != nil { + t.Fatal(err) + } + } + members := map[uint64][]social.MemberBest{ + // The lowest scorer's large overkill must not count: only the top ten by score do. + 1: {{AccountID: "low", OwnerIndex: 11, Score: 90, Overkill: 1000}}, + 2: {{AccountID: "x", OwnerIndex: 1, Score: 50, Overkill: 20}, {AccountID: "y", OwnerIndex: 2, Score: 40, Overkill: 30}}, + } + for i := range uint64(10) { + members[1] = append(members[1], social.MemberBest{AccountID: fmt.Sprintf("top%d", i), OwnerIndex: i + 1, Score: 100 - i, Overkill: 1}) + } + if err = store.Update(context.Background(), func(tx social.Tx) error { + for guild, rows := range members { + put(tx, "social.season_guilds", key(season)+":"+key(guild), guild) + put(tx, "social.seasons", key(guild)+":"+key(season), social.Season{GuildID: guild, ID: season, TotalScore: 1000, GuildView: social.Guild{ID: guild}}) + for _, m := range rows { + m.GuildID, m.Season = guild, season + put(tx, "social.member_best", key(guild)+":"+key(season)+":"+m.AccountID, m) + } + } + return nil + }); err != nil { + t.Fatal(err) + } + standings, err := owner.Standings(context.Background(), season) + if err != nil { + t.Fatal(err) + } + if len(standings) != 2 { + t.Fatalf("standings=%d, want 2", len(standings)) + } + got := map[uint64][2]uint64{} + for _, s := range standings { + got[s.Guild.ID] = [2]uint64{s.Overkill, s.Rank} + } + if got[2] != [2]uint64{50, 1} || got[1] != [2]uint64{10, 2} { + t.Fatalf("guild overkill/rank = %v, want guild 2 {50 1}, guild 1 {10 2}", got) + } +} diff --git a/go/internal/server/domain/social/raid_runtime.go b/go/internal/server/domain/social/raid_runtime.go index bd99688..1735aab 100644 --- a/go/internal/server/domain/social/raid_runtime.go +++ b/go/internal/server/domain/social/raid_runtime.go @@ -535,7 +535,8 @@ func (s *Service) CompleteBattle(ctx command.Context, request []byte, receipt st } } overkill := uint64(0) - if result == 1 && level == 10 { + // LocalText 2001675: only clears at overkillLevel or above record damage beyond the boss HP. + if threshold := s.config.Owner.design.Raid.OverkillLevel; result == 1 && threshold > 0 && level >= threshold { total, e := raidTotalDamage(p) if e != nil { return nil, e diff --git a/go/internal/server/domain/social/standings.go b/go/internal/server/domain/social/standings.go index 762263e..47561ee 100644 --- a/go/internal/server/domain/social/standings.go +++ b/go/internal/server/domain/social/standings.go @@ -32,7 +32,22 @@ func memberBests(tx Tx, guild, season uint64) ([]MemberBest, error) { } return out, nil } -func standingRows(tx Tx, season uint64) ([]GuildStanding, error) { +func sortMembers(members []MemberBest) { + sort.Slice(members, func(i, j int) bool { + a, b := members[i], members[j] + if a.Score != b.Score { + return a.Score > b.Score + } + if a.Overkill != b.Overkill { + return a.Overkill > b.Overkill + } + return a.OwnerIndex < b.OwnerIndex + }) +} + +// standingRows ranks guilds by score; LocalText 2001674/30061021 break ties by +// the overkill sum of the guild's overkillMembers highest-scoring members. +func standingRows(tx Tx, season, overkillMembers uint64) ([]GuildStanding, error) { var rows []GuildStanding for after := ""; ; { page, e := tx.Scan(seasonGuildBucket, numberKey(season)+":", after, 256) @@ -64,10 +79,10 @@ func standingRows(tx Tx, season uint64) ([]GuildStanding, error) { if e != nil { return nil, e } - sort.Slice(members, func(i, j int) bool { return members[i].Overkill > members[j].Overkill }) + sortMembers(members) overkill := uint64(0) for i, m := range members { - if i >= 3 { + if uint64(i) >= overkillMembers { break } if overkill > math.MaxUint64-m.Overkill { @@ -117,7 +132,7 @@ func (o *Owner) Standings(ctx context.Context, season uint64) ([]GuildStanding, if e != nil || found { return e } - out, e = standingRows(tx, season) + out, e = standingRows(tx, season, o.design.Raid.OverkillMemberCount) return e }) return out, e @@ -156,16 +171,7 @@ func (o *Owner) StatueRanking(ctx context.Context) (uint64, []GuildStanding, err func (o *Owner) MemberStandings(ctx context.Context, guild, season uint64) ([]MemberBest, error) { var out []MemberBest e := o.store.View(ctx, func(tx Tx) error { var e error; out, e = memberBests(tx, guild, season); return e }) - sort.Slice(out, func(i, j int) bool { - a, b := out[i], out[j] - if a.Score != b.Score { - return a.Score > b.Score - } - if a.Overkill != b.Overkill { - return a.Overkill > b.Overkill - } - return a.OwnerIndex < b.OwnerIndex - }) + sortMembers(out) return out, e } func (o *Owner) Entitlements(ctx context.Context, account string) ([]Entitlement, error) { @@ -213,7 +219,7 @@ func (o *Owner) FinalizeSeason(ctx context.Context, season uint64, at int64) err if found, e := load(tx, boardBucket, numberKey(season), &prior); e != nil || found { return e } - rows, e := standingRows(tx, season) + rows, e := standingRows(tx, season, o.design.Raid.OverkillMemberCount) if e != nil { return e } diff --git a/go/internal/server/domain/startergift/catalog.go b/go/internal/server/domain/startergift/catalog.go new file mode 100644 index 0000000..94e97a3 --- /dev/null +++ b/go/internal/server/domain/startergift/catalog.go @@ -0,0 +1,229 @@ +// Package startergift selects onboarding gifts from versioned policy and design +// data. Issued mail remains an immutable account record. +package startergift + +import ( + "fmt" + "slices" + "strconv" + "strings" + + "bd2server/internal/server/design/gamedata" +) + +const ( + LimitedCostumes = "starter:limited-costumes:not-current-pickup:v1" + PrestigeSkins = "starter:prestige-skins:not-current-purchase:v1" + LimitedAvatars = "starter:limited-avatars:external-sources:v1" + PrestigeAvatars = "starter:prestige-avatar:" +) + +type PartSource struct { + ID uint64 `json:"id"` + UnlockTextID uint64 `json:"unlock_text_id"` + Source string `json:"source"` +} + +type Definition struct { + Identity string `json:"identity"` + Title string `json:"title"` + Body string `json:"body"` + Parts []PartSource `json:"external_avatar_parts,omitempty"` +} + +type Catalog struct { + Version string `json:"version"` + GameDataVersion string `json:"gamedata_version"` + Gifts []Definition `json:"gifts"` +} + +type Gift struct { + Identity, Title, Body string + Rewards []gamedata.Reward +} + +type Selection struct { + Limited *gamedata.LimitedCostumeCatalog + Prestige *gamedata.PrestigeSkinCatalog + Avatars *gamedata.AvatarProfileDesign + Featured map[uint64]bool + CashAvailable func(gamedata.CashProductKey) bool + OwnedPrestige map[uint64]bool +} + +func (c Catalog) Resolve(selection Selection) ([]Gift, error) { + if len(c.Gifts) != 4 || selection.Limited == nil || selection.Prestige == nil || selection.Avatars == nil || selection.Avatars.Bundles == nil { + return nil, fmt.Errorf("startergift: incomplete catalog or design") + } + seen := map[string]bool{} + var gifts []Gift + for _, definition := range c.Gifts { + if seen[definition.Identity] || definition.Title == "" || definition.Body == "" { + return nil, fmt.Errorf("startergift: invalid gift definition %q", definition.Identity) + } + seen[definition.Identity] = true + gift := Gift{Identity: definition.Identity, Title: definition.Title, Body: definition.Body} + switch definition.Identity { + case LimitedCostumes: + for _, id := range selection.Limited.Excluding(selection.Featured) { + costume, ok := selection.Limited.Character(id) + if !ok || costume.CostumeMaxLevel != 5 { + return nil, fmt.Errorf("startergift: limited costume %d does not support +5", id) + } + gift.Rewards = append(gift.Rewards, gamedata.Reward{Type: 11, ID: id, Count: 6}) + } + case PrestigeSkins: + for _, id := range selection.Prestige.Giftable(selection.CashAvailable) { + gift.Rewards = append(gift.Rewards, gamedata.Reward{Type: 45, ID: id, Count: 1}) + } + case LimitedAvatars: + var err error + gift.Rewards, err = avatarRewards(definition.Parts, selection) + if err != nil { + return nil, err + } + case PrestigeAvatars: + defaults := defaultAvatarParts(selection.Avatars) + ids := make([]uint64, 0, len(selection.OwnedPrestige)) + for id, owned := range selection.OwnedPrestige { + if owned && len(selection.Avatars.PrestigeSets[id]) != 0 { + ids = append(ids, id) + } + } + slices.Sort(ids) + for _, id := range ids { + if selection.Prestige.Skins[id] == 0 { + return nil, fmt.Errorf("startergift: unknown owned prestige skin %d", id) + } + linked := Gift{Identity: PrestigeAvatars + strconv.FormatUint(id, 10) + ":v1", Title: gift.Title, Body: gift.Body} + for _, reward := range selection.Avatars.PrestigeSets[id] { + if !defaults[reward.ID] { + linked.Rewards = append(linked.Rewards, reward) + } + } + if len(linked.Rewards) == 0 { + continue + } + if err := ValidateRewards(linked.Identity, linked.Rewards); err != nil { + return nil, err + } + gifts = append(gifts, linked) + } + default: + return nil, fmt.Errorf("startergift: unknown gift identity %q", definition.Identity) + } + if definition.Identity != LimitedAvatars && len(definition.Parts) != 0 { + return nil, fmt.Errorf("startergift: avatar sources on unrelated gift") + } + if len(gift.Rewards) != 0 { + if err := ValidateRewards(gift.Identity, gift.Rewards); err != nil { + return nil, err + } + gifts = append(gifts, gift) + } + } + return gifts, nil +} + +func avatarRewards(sources []PartSource, selection Selection) ([]gamedata.Reward, error) { + design := selection.Avatars + unique := map[[2]uint64]bool{} + add := func(reward gamedata.Reward) error { + if reward.Count != 1 || reward.Type != 49 || !design.Bundles.Items[reward.Type][reward.ID] { + return fmt.Errorf("startergift: invalid limited avatar member %d:%d", reward.Type, reward.ID) + } + unique[[2]uint64{reward.Type, reward.ID}] = true + return nil + } + seen := map[uint64]bool{} + for _, source := range sources { + part, ok := design.Parts[source.ID] + product, exists := design.Shop[source.ID] + if !ok || !exists || source.ID == 0 || seen[source.ID] || source.Source == "" || source.UnlockTextID == 0 || + part.UnlockTextID != source.UnlockTextID || part.Character != 0 || part.Maximum != 1 || product.Purchasable || + product.UnlockValue != 0 || product.Reward != (gamedata.Reward{Type: 49, ID: source.ID, Count: 1}) { + return nil, fmt.Errorf("startergift: external avatar source %d does not match current design", source.ID) + } + seen[source.ID] = true + if err := add(product.Reward); err != nil { + return nil, err + } + } + keys := make([][2]uint64, 0, len(unique)) + for key := range unique { + keys = append(keys, key) + } + slices.SortFunc(keys, func(a, b [2]uint64) int { + if a[0] != b[0] { + return int(a[0]) - int(b[0]) + } + return int(a[1]) - int(b[1]) + }) + rewards := make([]gamedata.Reward, 0, len(keys)) + for _, key := range keys { + rewards = append(rewards, gamedata.Reward{Type: key[0], ID: key[1], Count: 1}) + } + return rewards, nil +} + +func defaultAvatarParts(design *gamedata.AvatarProfileDesign) map[uint64]bool { + defaults := map[uint64]bool{} + for _, character := range design.Characters { + for _, id := range character.Defaults { + defaults[id] = true + } + for _, reward := range character.Rewards { + if reward.Type == 49 { + defaults[reward.ID] = true + } + } + } + for _, product := range design.Shop { + if !product.Initial { + continue + } + if product.Reward.Type == 49 { + defaults[product.Reward.ID] = true + } + if product.Reward.Type == 62 { + for _, reward := range design.Bundles.Sets[product.Reward.ID] { + if reward.Type == 49 { + defaults[reward.ID] = true + } + } + } + } + return defaults +} + +// Saved attachments need not match today's selection: issuing and claiming a +// gift freezes its reward list even when shop availability later changes. +func ValidateRewards(identity string, rewards []gamedata.Reward) error { + seen := map[[2]uint64]bool{} + if len(rewards) == 0 { + return fmt.Errorf("startergift: empty gift %q", identity) + } + for _, reward := range rewards { + key := [2]uint64{reward.Type, reward.ID} + valid := identity == LimitedCostumes && reward.Type == 11 && reward.Count == 6 || + identity == PrestigeSkins && reward.Type == 45 && reward.Count == 1 || + IsAvatarGift(identity) && reward.Type == 49 && reward.Count == 1 + if !valid || reward.ID == 0 || seen[key] { + return fmt.Errorf("startergift: invalid saved gift %q reward %d:%d", identity, reward.Type, reward.ID) + } + seen[key] = true + } + return nil +} + +func IsAvatarGift(identity string) bool { + if identity == LimitedAvatars { + return true + } + if !strings.HasPrefix(identity, PrestigeAvatars) || !strings.HasSuffix(identity, ":v1") { + return false + } + id := strings.TrimSuffix(strings.TrimPrefix(identity, PrestigeAvatars), ":v1") + n, err := strconv.ParseUint(id, 10, 64) + return err == nil && n != 0 && strconv.FormatUint(n, 10) == id +} diff --git a/go/internal/server/domain/world/event_field_pack.go b/go/internal/server/domain/world/event_field_pack.go index 541713d..ea40a5a 100644 --- a/go/internal/server/domain/world/event_field_pack.go +++ b/go/internal/server/domain/world/event_field_pack.go @@ -36,11 +36,3 @@ func (s *Service) resolveEventFieldPack(ctx command.Context, id int) (gamedata.E } return s.eventFieldPacks.ResolveEventFieldPack(ctx, id) } - -func (s *Service) eventPackPurchased(id int) bool { - if s.collection == nil { - return false - } - _, found := s.collection.Grant(packPurchaseIdentity(id)) - return found -} diff --git a/go/internal/server/domain/world/field_monster_events.go b/go/internal/server/domain/world/field_monster_events.go index 2112f91..989fa2e 100644 --- a/go/internal/server/domain/world/field_monster_events.go +++ b/go/internal/server/domain/world/field_monster_events.go @@ -3,6 +3,7 @@ package world import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" "fmt" ) @@ -25,5 +26,12 @@ func (s *Service) grantFieldMonster(ctx command.Context, pack int, m gamedata.Fi rewards = append(rewards, gamedata.Reward{Type: r.Type, ID: r.ID, Count: r.Count}) //nolint:staticcheck // S1016 } } - return s.researchEconomy.Apply(ctx, identity, nil, rewards) + bundle, err := s.researchEconomy.Apply(ctx, identity, nil, rewards) + if err != nil { + return nil, err + } + if err := s.recordMission(ctx, conditions.Event{Type: conditions.FieldRewardMonsterCatch, Count: 1}); err != nil { + return nil, err + } + return bundle, nil } diff --git a/go/internal/server/domain/world/field_pack.go b/go/internal/server/domain/world/field_pack.go index 347693d..40fd102 100644 --- a/go/internal/server/domain/world/field_pack.go +++ b/go/internal/server/domain/world/field_pack.go @@ -2,38 +2,122 @@ package world import ( "errors" + "slices" "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/world/progress" + "bd2server/internal/server/protocol/wire" ) -// LastPlayedPackID prevents LoginUser from selecting a field that this server -// cannot restore. A fresh account keeps the versioned login seed's pack. +type FieldPackEconomy interface { + Apply(command.Context, string, []gamedata.Reward, []gamedata.Reward) ([]byte, error) +} + +func (s *Service) AttachFieldPackEconomy(economy FieldPackEconomy) { + s.fieldPackEconomy = economy +} + +func (s *Service) fieldPackDBInfo(pack gamedata.FieldPack) []byte { + row := wire.AppendVarint(nil, 1, pack.ID) + if s.collection != nil { + if _, purchased := s.collection.Grant(packPurchaseIdentity(int(pack.ID))); purchased { + row = wire.AppendVarint(row, 8, 1) + } + } + return row +} + +// LastPlayedPackID returns the pack LoginUser should restore. ActivePackID +// records the last selected content, but only a saved position proves that the +// scene can be restored; an arena entered without save can therefore fall back +// to the field that owns the position. Login falls back to the entry chapter +// instead of failing when no selected pack can restore the saved scene. func (s *Service) LastPlayedPackID(ctx command.Context) (uint64, error) { id := uint64(s.state.ActivePackID()) if id == 0 { - var err error - id, err = s.state.LastPlayedPackID(ctx) - if err != nil { - return id, err + if saved, found := s.state.Position(); found && saved.PackID > 0 { + id = uint64(saved.PackID) } } if id == 0 { id = uint64(s.startingPack()) } - if !s.packUnlocked(ctx, int(id)) { - return 0, errors.New("world: saved login pack is unavailable") + if s.packResumable(ctx, int(id)) { + return id, nil } - if pack, field := s.fieldPacks[int(id)]; field { + if saved, found := s.state.Position(); found && saved.PackID > 0 && uint64(saved.PackID) != id && s.packResumable(ctx, saved.PackID) { + return uint64(saved.PackID), nil + } + if start := s.startingPack(); start > 0 && uint64(start) != id && s.packResumable(ctx, start) { + return uint64(start), nil + } + return 0, errors.New("world: saved login pack is unavailable") +} + +// packResumable reports whether login can restore this pack. A field pack +// other than a hunting ground needs a saved position of its own because the +// scene cannot be reconstructed otherwise. +func (s *Service) packResumable(ctx command.Context, id int) bool { + if id <= 0 || !s.packUnlocked(ctx, id) { + return false + } + if s.storyCatalog != nil { + if _, story := s.storyCatalog.Packs[id]; story { + return true + } + } + if pack, field := s.fieldPacks[id]; field { if pack.Type == 5 { - return id, nil + return true } - saved, _ := s.state.Position() - if !pack.MapIDs[saved.Position.MapID] { - return 0, errors.New("world: saved arena map does not belong to pack") + saved, found := s.state.Position() + return found && fieldPackAcceptsMap(pack, saved) + } + return true +} + +// fieldPackAcceptsMap reports whether a saved position belongs to the pack. +func fieldPackAcceptsMap(pack gamedata.FieldPack, saved progress.SavedPosition) bool { + return saved.PackID == int(pack.ID) && pack.MapIDs[saved.Position.MapID] +} + +// ClaimOpenFieldPacks completes the free purchase of field content packs once +// their ContentOpen rule is satisfied. The client cannot buy a pack it does not +// list yet, so without this the pack card stays locked after the main quests +// that grant its ticket. The cafeteria card opens through its introduction. +func (s *Service) ClaimOpenFieldPacks(ctx command.Context) error { + if s.collection == nil { + return nil + } + ids := make([]int, 0, len(s.fieldPacks)) + for id := range s.fieldPacks { + ids = append(ids, id) + } + slices.Sort(ids) + for _, id := range ids { + pack := s.fieldPacks[id] + if pack.BuyPrice != 0 || pack.Type == 9 { + continue + } + if s.packPurchased(id) { + continue + } + definition, err := s.resolvePack(ctx, id) + if err != nil { + return err + } + if definition.kind != fieldCard || !s.packRequirementsMet(ctx, definition) { + continue + } + if pack.Type == 5 && s.skyway == nil || pack.Type != 5 && s.fieldPackEconomy == nil { + continue + } + if _, err := s.purchaseResolvedPack(ctx, definition, false); err != nil { + return err } } - return id, nil + return nil } func (s *Service) AttachSquadLevel(ctx command.Context, provider func() (uint64, error)) error { @@ -44,16 +128,17 @@ func (s *Service) AttachSquadLevel(ctx command.Context, provider func() (uint64, return nil } -func (s *Service) fieldPackUnlocked(ctx command.Context, pack gamedata.FieldPack) bool { +func (s *Service) fieldPackRequirementsMet(ctx command.Context, pack gamedata.FieldPack) bool { + // A static scheduled card needs authorization from the active calendar. + // A saved position must never reopen a card after that calendar expires. + if pack.UseSchedule != 0 { + return false + } // A valid committed field position is the existing account's entry marker. // Restoration does not repeat a purchase or an unlock check. if saved, found := s.state.Position(); found && saved.PackID == int(pack.ID) && pack.MapIDs[saved.Position.MapID] { return true } - // Scheduled arena availability needs its own persisted event domain. - if pack.UseSchedule != 0 { - return false - } if pack.SquadLevel != 0 { if s.squadLevel == nil { return false @@ -78,10 +163,5 @@ func (s *Service) fieldPackUnlocked(ctx command.Context, pack gamedata.FieldPack return false } } - // Paid packs require a durable purchase marker. An existing saved position - // proves this account already entered it; this does not implement purchase. - if pack.BuyPrice != 0 { - return false - } return true } diff --git a/go/internal/server/domain/world/field_pack_claim_integration_test.go b/go/internal/server/domain/world/field_pack_claim_integration_test.go new file mode 100644 index 0000000..5001e29 --- /dev/null +++ b/go/internal/server/domain/world/field_pack_claim_integration_test.go @@ -0,0 +1,180 @@ +//go:build integration + +package world + +import ( + "testing" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + assets "bd2server/internal/server/domain/inventory" + "bd2server/internal/server/domain/roster" + "bd2server/internal/server/domain/world/progress" + "bd2server/internal/server/protocol/wire" + "bd2server/internal/server/storage/stateio" +) + +type fieldPackLedger struct{ grants []string } + +func (l *fieldPackLedger) Apply(_ command.Context, identity string, _ []gamedata.Reward, _ []gamedata.Reward) ([]byte, error) { + l.grants = append(l.grants, identity) + return nil, nil +} + +func openCombatPackService(t *testing.T) (*Service, command.Context, *fieldPackLedger) { + t.Helper() + ctx := command.Context{State: stateio.NewMemory()} + collection, err := roster.OpenCollectionStore(ctx, stateio.RootStore{}, nil) + if err != nil { + t.Fatal(err) + } + var tickets []assets.Item + for i, id := range []uint64{13001, 13003, 13002, 14, 17, 3007} { + tickets = append(tickets, assets.Item{InvenIndex: uint64(i + 1), Type: 19, ID: id, Count: 1}) + } + inventory, err := assets.OpenInventory(ctx, stateio.RootStore{}, tickets) + if err != nil { + t.Fatal(err) + } + ledger := &fieldPackLedger{} + service := &Service{ + state: progress.NewStore(), + collection: collection, + inventory: inventory, + fieldPackEconomy: ledger, + storyCatalog: &gamedata.StoryCatalog{Packs: map[int]gamedata.StoryPack{}}, + fieldPacks: map[int]gamedata.FieldPack{ + 3001: {ID: 3001, Type: 3, HasOpenRule: true, TicketID: 13001, BuyRewards: []gamedata.Reward{{Type: 4, Count: 10}}}, + 3003: {ID: 3003, Type: 4, HasOpenRule: true, TicketID: 13003, BuyRewards: []gamedata.Reward{{Type: 18, Count: 5}}}, + 3005: {ID: 3005, Type: 7, HasOpenRule: true, TicketID: 14}, + 3008: {ID: 3008, Type: 10, HasOpenRule: true, TicketID: 17}, + 3007: {ID: 3007, Type: 9, HasOpenRule: true, TicketID: 3007}, + 3002: {ID: 3002, Type: 3, HasOpenRule: true, TicketID: 13002, BuyPrice: 100}, + }, + } + return service, ctx, ledger +} + +func packRowsBought(t *testing.T, service *Service, ctx command.Context) map[uint64]bool { + t.Helper() + rows, err := service.storyPackDBInfoRows(ctx) + if err != nil { + t.Fatal(err) + } + out := make(map[uint64]bool, len(rows)) + for _, row := range rows { + id, _, _ := wire.Varint(row, 1) + bought, _, _ := wire.Varint(row, 8) + out[id] = bought == 1 + } + return out +} + +// A free combat pack becomes owned once its ContentOpen ticket exists. The +// client only lists purchased packs, so the login claim is the only way the +// pack card and its advertised buy rewards can appear. +func TestClaimOpenFieldPacksOwnsUnlockedCombatPacks(t *testing.T) { + service, ctx, ledger := openCombatPackService(t) + if err := service.ClaimOpenFieldPacks(ctx); err != nil { + t.Fatal(err) + } + for _, id := range []int{3001, 3003, 3005, 3008} { + if _, owned := service.collection.Grant(packPurchaseIdentity(id)); !owned { + t.Fatalf("pack %d was not claimed", id) + } + } + for _, id := range []int{3002, 3007} { + if _, owned := service.collection.Grant(packPurchaseIdentity(id)); owned { + t.Fatalf("pack %d must not be claimed", id) + } + } + if len(ledger.grants) != 4 { + t.Fatalf("claimed packs = %v, want the four combat packs", ledger.grants) + } + if err := service.ClaimOpenFieldPacks(ctx); err != nil { + t.Fatal(err) + } + if len(ledger.grants) != 4 { + t.Fatalf("second login claimed again: %v", ledger.grants) + } + rows := packRowsBought(t, service, ctx) + for _, id := range []uint64{3001, 3003, 3005, 3008} { + if !rows[id] { + t.Fatalf("pack %d missing purchased row: %v", id, rows) + } + } + for _, id := range []uint64{3002, 3007} { + if _, listed := rows[id]; listed { + t.Fatalf("pack %d must stay unlisted: %v", id, rows) + } + } +} + +// The client can also ask to buy an unlocked combat pack directly; the same +// purchase path must record it and its rewards. +func TestPackBuyClaimsUnlockedCombatFieldPack(t *testing.T) { + service, ctx, ledger := openCombatPackService(t) + request := wire.AppendVarint(wire.AppendVarint(nil, 1, 1), 2, 3001) + code, _, handled, err := service.Handle(ctx, "/PackBuy", request) + if err != nil || !handled { + t.Fatalf("PackBuy: handled=%v err=%v", handled, err) + } + if code != 6 { + t.Fatalf("PackBuy code = %d, want 6", code) + } + if _, owned := service.collection.Grant(packPurchaseIdentity(3001)); !owned { + t.Fatal("PackBuy did not record the purchase") + } + if len(ledger.grants) != 1 || ledger.grants[0] != packPurchaseIdentity(3001) { + t.Fatalf("PackBuy rewards = %v", ledger.grants) + } + if _, _, _, err := service.Handle(ctx, "/PackBuy", request); err != nil { + t.Fatal(err) + } + if len(ledger.grants) != 1 { + t.Fatalf("repeated PackBuy granted again: %v", ledger.grants) + } +} + +// Character, event, square and life cards (Define_PackType 1, 6, 11, 14) open +// with the ticket granted by clearing Edge of Dimensions; unscheduled ones are +// claimed like the combat packs, a scheduled event card is not. +func TestClaimOpenFieldPacksOwnsTicketGatedContentCards(t *testing.T) { + service, ctx, ledger := openCombatPackService(t) + inventory, err := assets.OpenInventory(ctx, stateio.RootStore{}, []assets.Item{{InvenIndex: 1, Type: 19, ID: 11, Count: 1}}) + if err != nil { + t.Fatal(err) + } + service.inventory = inventory + service.fieldPacks = map[int]gamedata.FieldPack{ + 1001: {ID: 1001, Type: 1, HasOpenRule: true, TicketID: 11}, + 2001: {ID: 2001, Type: 6, HasOpenRule: true, TicketID: 11}, + 2004: {ID: 2004, Type: 6, HasOpenRule: true, TicketID: 11, UseSchedule: 1}, + 3009: {ID: 3009, Type: 11, HasOpenRule: true, TicketID: 11}, + 3012: {ID: 3012, Type: 14, HasOpenRule: true, TicketID: 11}, + 3013: {ID: 3013, Type: 14, HasOpenRule: true, TicketID: 99}, + } + if err := service.ClaimOpenFieldPacks(ctx); err != nil { + t.Fatal(err) + } + rows := packRowsBought(t, service, ctx) + for _, id := range []uint64{1001, 2001, 3009, 3012} { + if !rows[id] { + t.Fatalf("content card %d missing purchased row: %v", id, rows) + } + } + for _, id := range []uint64{2004, 3013} { + if _, listed := rows[id]; listed { + t.Fatalf("pack %d must stay unlisted: %v", id, rows) + } + } + if len(ledger.grants) != 4 { + t.Fatalf("claimed = %v, want four cards", ledger.grants) + } + if err := service.ClaimOpenFieldPacks(ctx); err != nil { + t.Fatal(err) + } + if len(ledger.grants) != 4 { + t.Fatalf("second login claimed again: %v", ledger.grants) + } +} diff --git a/go/internal/server/domain/world/field_quest_difficulty_test.go b/go/internal/server/domain/world/field_quest_difficulty_test.go index d430d8b..949ca94 100644 --- a/go/internal/server/domain/world/field_quest_difficulty_test.go +++ b/go/internal/server/domain/world/field_quest_difficulty_test.go @@ -14,6 +14,7 @@ import ( "bd2server/internal/server/domain/world/progress" "bd2server/internal/server/protocol/wire" accountstate "bd2server/internal/server/storage/account" + "bd2server/internal/server/storage/instanceid" "bd2server/internal/server/storage/stateio" ) @@ -33,7 +34,8 @@ func fieldQuestIntegration(t *testing.T, pack int) (command.Context, *Service, * if err != nil { t.Fatal(err) } - repo, err := accountstate.Open(filepath.Join(t.TempDir(), "state.db")) + statePath := filepath.Join(t.TempDir(), "state.db") + repo, err := accountstate.Open(statePath) if err != nil { t.Fatal(err) } @@ -51,7 +53,7 @@ func fieldQuestIntegration(t *testing.T, pack int) (command.Context, *Service, * t.Error(err) } }) - ctx := command.Context{Identity: command.Identity{AccountID: t.Name(), SessionID: "authenticated"}, State: tx} + ctx := command.Context{Identity: command.Identity{AccountID: t.Name(), SessionID: "authenticated"}, State: tx, InstanceIDs: instanceid.New(filepath.Join(filepath.Dir(statePath), "instance-ids.db"))} state, err := progress.OpenStore(ctx, stateio.RootStore{}) if err != nil { t.Fatal(err) diff --git a/go/internal/server/domain/world/field_reward_claim_integration_test.go b/go/internal/server/domain/world/field_reward_claim_integration_test.go index ed1ac49..69c3c70 100644 --- a/go/internal/server/domain/world/field_reward_claim_integration_test.go +++ b/go/internal/server/domain/world/field_reward_claim_integration_test.go @@ -13,7 +13,7 @@ import ( ) // Native FieldPacket addresses rewards by pack/group/object, not current map. -// GameData 20261012190548: pack9 green pot33011/group303 has buff19, +// GameData 20261021182514: pack9 green pot33011/group303 has buff19, // restoring 30% of maximum HP; its map92 metadata is also used by the HUD. func TestGreenPotClaimAfterMapChangeHealsOnlyOnce(t *testing.T) { ctx, service, items, setMap := eventMonsterIntegration(t, 9) diff --git a/go/internal/server/domain/world/mission_progress.go b/go/internal/server/domain/world/mission_progress.go new file mode 100644 index 0000000..04eae1f --- /dev/null +++ b/go/internal/server/domain/world/mission_progress.go @@ -0,0 +1,18 @@ +package world + +import ( + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" +) + +// AttachMissionProgress reports field actions to mission conditions. +func (s *Service) AttachMissionProgress(record func(command.Context, conditions.Event) error) { + s.missionProgress = record +} + +func (s *Service) recordMission(ctx command.Context, event conditions.Event) error { + if s.missionProgress == nil { + return nil + } + return s.missionProgress(ctx, event) +} diff --git a/go/internal/server/domain/world/mission_progress_integration_test.go b/go/internal/server/domain/world/mission_progress_integration_test.go new file mode 100644 index 0000000..842d00f --- /dev/null +++ b/go/internal/server/domain/world/mission_progress_integration_test.go @@ -0,0 +1,146 @@ +//go:build integration + +package world + +import ( + "testing" + + "bd2server/internal/common/versionconfig" + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" + "bd2server/internal/server/domain/world/progress" + "bd2server/internal/server/protocol/wire" + "bd2server/internal/server/storage/stateio" +) + +type stubEconomy struct{} + +func (stubEconomy) Apply(command.Context, string, []gamedata.Reward, []gamedata.Reward) ([]byte, error) { + return nil, nil +} + +type stubEventFieldPacks struct{} + +func (stubEventFieldPacks) ResolveEventFieldPack(command.Context, int) (gamedata.EventFieldPack, bool, error) { + return gamedata.EventFieldPack{}, false, nil +} +func (stubEventFieldPacks) ListEventFieldPacks(command.Context) ([]gamedata.EventFieldPack, error) { + return nil, nil +} +func (stubEventFieldPacks) FieldObjectEventPeriod(int) (string, int64, error) { + return "test", 0, nil +} + +func recordMissionEvents(service *Service) *[]conditions.Event { + events := []conditions.Event{} + service.AttachMissionProgress(func(_ command.Context, event conditions.Event) error { + events = append(events, event) + return nil + }) + return &events +} + +func fieldObjectMissionScenario(t *testing.T, pack int) (command.Context, *Service, gamedata.FieldObjectDesign) { + t.Helper() + ctx, service, _, _ := eventMonsterIntegration(t, pack) + versions, err := versionconfig.Find() + if err != nil { + t.Fatal(err) + } + source := gamedata.NewSource(versions.Resolve("data/resources/GameData"), versions.GameDataVersion) + if err := service.AttachFieldObjectRuntime(source, service.fieldReset); err != nil { + t.Fatal(err) + } + service.packs = map[int]map[int]gamedata.QuestDesign{pack: service.storyCatalog.Packs[pack].Quests} + design, err := source.FieldObjects(pack) + if err != nil { + t.Fatal(err) + } + return ctx, service, design +} + +func claimFieldObject(t *testing.T, ctx command.Context, service *Service, pack, seq uint64, obj gamedata.FieldRewardObject) { + t.Helper() + request := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, seq), 2, pack), 3, uint64(obj.GroupID)), 4, uint64(obj.ID)) + code, _, handled, err := service.Handle(ctx, "/FieldObjectReward", request) + if err != nil || !handled || code != 29 { + t.Fatalf("field object claim %d: handled=%v code=%d err=%v", obj.ID, handled, code, err) + } +} + +// GameData pack9 green pot33011/group303 has a buff and no loot group, so it +// takes the buff branch of openFieldObjectResponse. The claim must still count +// as one McCollectionGet and must not count again after the state reloads. +func TestFieldObjectClaimReportsCollectionOnce(t *testing.T) { + ctx, service, design := fieldObjectMissionScenario(t, 9) + obj, found := design.Objects[33011] + if !found || obj.BuffID == 0 { + t.Fatalf("green pot fixture changed: found=%v object=%+v", found, obj) + } + events := recordMissionEvents(service) + claimFieldObject(t, ctx, service, 9, 1, obj) + if len(*events) != 1 || (*events)[0].Type != conditions.CollectionGet || (*events)[0].Count != 1 { + t.Fatalf("claim events = %+v, want one McCollectionGet", *events) + } + var err error + service.state, err = progress.OpenStore(ctx, stateio.RootStore{}) + if err != nil { + t.Fatal(err) + } + claimFieldObject(t, ctx, service, 9, 2, obj) + if len(*events) != 1 { + t.Fatalf("repeated claim added events: %+v", *events) + } +} + +// GameData pack2 type5 objects have no buff, monster or loot, so they take +// openFieldObject's empty-loot branch, which must report the same +// McCollectionGet. +func TestFieldObjectWithoutLootReportsCollection(t *testing.T) { + ctx, service, design := fieldObjectMissionScenario(t, 2) + service.eventFieldPacks = stubEventFieldPacks{} + var candidate gamedata.FieldRewardObject + for _, obj := range design.Objects { + if len(obj.Rewards) == 0 && obj.BuffID == 0 && obj.MonsterID == 0 && (obj.QuestID != 0 || obj.Type == 5 || obj.Type == 6) { + candidate = obj + break + } + } + if candidate.ID == 0 { + t.Fatal("GameData has no non-buff field object without loot") + } + events := recordMissionEvents(service) + claimFieldObject(t, ctx, service, 2, 1, candidate) + if len(*events) != 1 || (*events)[0].Type != conditions.CollectionGet || (*events)[0].Count != 1 { + t.Fatalf("claim events = %+v, want one McCollectionGet", *events) + } +} + +// grantFieldMonster reports one catch regardless of the reward item count. +func TestGrantFieldMonsterRecordsFieldRewardMonsterCatch(t *testing.T) { + ctx, service, _, _ := eventMonsterIntegration(t, 9) + service.researchEconomy = stubEconomy{} + events := recordMissionEvents(service) + monster := gamedata.FieldMonsterDesign{ID: 1, Reward: gamedata.Reward{Type: 4, Count: 5}} + if _, err := service.grantFieldMonster(ctx, 9, monster, "mission-catch"); err != nil { + t.Fatal(err) + } + if len(*events) != 1 || (*events)[0].Type != conditions.FieldRewardMonsterCatch || (*events)[0].Count != 1 { + t.Fatalf("catch events = %+v, want one McFieldRewardMonsterCatch", *events) + } +} + +func TestPackEntryReportsCondition(t *testing.T) { + ctx, service, items, _ := eventMonsterIntegration(t, 9) + service.packs = map[int]map[int]gamedata.QuestDesign{9: service.storyCatalog.Packs[9].Quests} + service.inventory = items + events := recordMissionEvents(service) + request := wire.AppendVarint(wire.AppendVarint(nil, 1, 1), 2, 9) + if _, _, handled, err := service.Handle(ctx, "/PackInGameInfo", request); err != nil || !handled { + t.Fatalf("pack entry: handled=%v err=%v", handled, err) + } + if len(*events) != 1 || (*events)[0].Type != conditions.EnterPackInField || (*events)[0].Sub != 9 || (*events)[0].Count != 1 { + t.Fatalf("pack entry events = %+v, want one McEnterPackInField for pack 9", *events) + } +} diff --git a/go/internal/server/domain/world/pack_catalog.go b/go/internal/server/domain/world/pack_catalog.go new file mode 100644 index 0000000..fa1d6f8 --- /dev/null +++ b/go/internal/server/domain/world/pack_catalog.go @@ -0,0 +1,96 @@ +package world + +import ( + "fmt" + + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" +) + +type packKind uint8 + +const ( + storyCard packKind = iota + fieldCard + eventCard +) + +// A card is resolved once per operation. Calendar-authorized hidden cards +// take precedence over static field and story catalogs. +type packDefinition struct { + id int + kind packKind + story gamedata.StoryPack + field gamedata.FieldPack + event gamedata.EventFieldPack +} + +func (s *Service) resolvePack(ctx command.Context, id int) (packDefinition, error) { + if event, found, err := s.resolveEventFieldPack(ctx, id); err != nil { + return packDefinition{}, fmt.Errorf("world: resolve pack %d calendar: %w", id, err) + } else if found { + return packDefinition{id: id, kind: eventCard, event: event}, nil + } + if field, found := s.fieldPacks[id]; found { + return packDefinition{id: id, kind: fieldCard, field: field}, nil + } + if s.storyCatalog != nil { + if story, found := s.storyCatalog.Packs[id]; found { + return packDefinition{id: id, kind: storyCard, story: story}, nil + } + } + return packDefinition{}, fmt.Errorf("%w: unknown pack %d", ErrInvalidRequest, id) +} + +func (s *Service) packPurchased(id int) bool { + if s.collection == nil { + return false + } + _, found := s.collection.Grant(packPurchaseIdentity(id)) + return found +} + +func (s *Service) CanEnterFieldPackType(ctx command.Context, packType uint64) bool { + for id, pack := range s.fieldPacks { + if pack.Type == packType && s.packPurchased(id) && s.packAccessible(ctx, packDefinition{id: id, kind: fieldCard, field: pack}) { + return true + } + } + return false +} + +func (s *Service) packRequirementsMet(ctx command.Context, pack packDefinition) bool { + switch pack.kind { + case eventCard: + return true // The resolver already checked the calendar. + case fieldCard: + return s.fieldPackRequirementsMet(ctx, pack.field) + default: + return s.storyPackUnlocked(ctx, pack.id) + } +} + +func (s *Service) packAccessible(ctx command.Context, pack packDefinition) bool { + if !s.packRequirementsMet(ctx, pack) { + return false + } + switch pack.kind { + case eventCard: + return s.packPurchased(pack.id) + case fieldCard: + return pack.field.BuyPrice == 0 || s.packPurchased(pack.id) + default: + return true + } +} + +func (p packDefinition) purchaseTerms() (uint64, uint64, []gamedata.Reward) { + switch p.kind { + case eventCard: + return p.event.BuyType, p.event.BuyPrice, p.event.BuyRewards + case fieldCard: + return p.field.BuyType, p.field.BuyPrice, p.field.BuyRewards + default: + return p.story.BuyType, p.story.BuyPrice, p.story.BuyRewards + } +} diff --git a/go/internal/server/domain/world/pack_docking.go b/go/internal/server/domain/world/pack_docking.go new file mode 100644 index 0000000..4916344 --- /dev/null +++ b/go/internal/server/domain/world/pack_docking.go @@ -0,0 +1,58 @@ +package world + +import ( + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/protocol/wire" + "fmt" +) + +func (s *Service) handlePackDocking(ctx command.Context, path string, request []byte) (int, []byte, bool, error) { + packID, err := requestPack(request) + if err != nil { + return 0, nil, true, err + } + pack, err := s.resolvePack(ctx, packID) + if err != nil { + return 0, nil, true, err + } + if !s.packAccessible(ctx, pack) { + return 0, nil, true, fmt.Errorf("%w: unavailable docking pack %d", ErrInvalidRequest, packID) + } + identity := packJamIdentity(packID) + if path == "/PackPreviewInfo" { + var response []byte + titles, err := s.questTitleInfo(packID) + if err != nil { + return 0, nil, true, err + } + for _, title := range titles { + response = wire.AppendBytes(response, 2, title) + } + if active := s.firstUnclearedQuestFor(packID); active != 0 { + quest := wire.AppendVarint(nil, 1, uint64(active)) + quest = wire.AppendVarint(quest, 6, uint64(packID)) + response = wire.AppendBytes(response, 1, quest) + } + if s.wallet != nil && s.wallet.WasGranted(identity) { + response = wire.AppendVarint(response, 3, 1) + } + return 104, response, true, nil + } + if s.wallet == nil || s.packJamDesign == nil { + return 0, nil, true, fmt.Errorf("world: pack jam design or wallet unavailable") + } + if s.wallet.WasGranted(identity) { + return 72, nil, true, nil + } + reward := s.packJamDesign.Reward + if s.packJamDesign.ValidateReward() != nil { + return 0, nil, true, fmt.Errorf("world: unsupported pack jam reward") + } + if _, err := s.wallet.GrantQuestOnce(ctx, identity, []gamedata.Reward{reward}); err != nil { + return 0, nil, true, fmt.Errorf("world: grant pack jam reward: %w", err) + } + item := wire.AppendVarint(nil, 3, reward.Type) + item = wire.AppendVarint(item, 4, reward.Count) + return 72, wire.AppendBytes(nil, 1, item), true, nil +} diff --git a/go/internal/server/domain/world/pack_entry.go b/go/internal/server/domain/world/pack_entry.go new file mode 100644 index 0000000..2496be2 --- /dev/null +++ b/go/internal/server/domain/world/pack_entry.go @@ -0,0 +1,140 @@ +package world + +import ( + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/domain/progression/conditions" + "bd2server/internal/server/protocol/wire" + "fmt" + "slices" +) + +func (s *Service) handlePackEntry(ctx command.Context, request []byte) (int, []byte, bool, error) { + id, err := requestPack(request) + if err != nil { + return 5, nil, true, err + } + pack, err := s.resolvePack(ctx, id) + if err != nil { + return 5, nil, true, err + } + if !s.packAccessible(ctx, pack) { + return 5, nil, true, fmt.Errorf("%w: unavailable entry pack %d", ErrInvalidRequest, id) + } + activeBattle := s.battleActive != nil && s.battleActive(ctx) + if activeBattle { + current, err := s.CurrentPackID(ctx) + if err != nil { + return 5, nil, true, err + } + if id != current { + return 5, nil, true, fmt.Errorf("%w: cannot change pack during active battle", ErrInvalidRequest) + } + } + if err := s.ResumeFieldTime(ctx); err != nil { + return 5, nil, true, err + } + var body []byte + if pack.kind == eventCard { + body, err = s.enterEventFieldPack(ctx, pack.event) + } else { + body, err = s.enterPersistentPack(ctx, pack, activeBattle) + } + if err != nil { + return 5, nil, true, err + } + if s.talentPackInfo != nil { + extra, err := s.talentPackInfo(ctx, id) + if err != nil { + return 5, nil, true, err + } + body = append(body, extra...) + } + if activeBattle { + body = wire.AppendVarint(body, 17, 1) + } + // Hidden events keep the outside login destination and saved position. + if pack.kind != eventCard { + if err := s.state.SetActivePackID(ctx, id); err != nil { + return 5, nil, true, err + } + if pack.kind == storyCard && pack.story.Type == 0 && pack.story.BuyPrice == 0 && s.collection != nil { + if err := s.collection.RecordGrantMarker(ctx, packEntryIdentity(id)); err != nil { + return 5, nil, true, err + } + } + } + s.setCurrentPack(id) + if err := s.recordMission(ctx, conditions.Event{Type: conditions.EnterPackInField, Sub: uint64(id), Count: 1}); err != nil { + return 5, nil, true, err + } + return 5, body, true, nil +} + +func (s *Service) enterPersistentPack(ctx command.Context, pack packDefinition, activeBattle bool) ([]byte, error) { + if pack.kind == fieldCard && pack.field.Type == 5 { + if s.skyway == nil || !s.packPurchased(pack.id) { + return nil, fmt.Errorf("world: SkyWay pack is not purchased") + } + v, err := s.skyway.load(ctx) + if err != nil { + return nil, err + } + if !activeBattle { + v.Run = skyWayRun{Generation: v.Run.Generation} + if err := s.skyway.save(ctx, v); err != nil { + return nil, err + } + } + } + if active := s.firstUnclearedQuestFor(pack.id); active != 0 { + if _, err := s.ensureQuestItems(ctx, pack.id, active); err != nil { + return nil, err + } + } + return s.packInfoFor(ctx, pack.id) +} + +func (s *Service) enterEventFieldPack(ctx command.Context, pack gamedata.EventFieldPack) ([]byte, error) { + if !s.packPurchased(pack.ID) { + return nil, fmt.Errorf("%w: event pack %d is not purchased", ErrInvalidRequest, pack.ID) + } + position := pack.InitialPosition + if position == "" { + return nil, fmt.Errorf("world: missing event pack initial position") + } + if saved, found := s.state.Position(); found && saved.PackID == pack.ID { + if !slices.Contains(pack.MapIDs, saved.Position.MapID) { + return nil, fmt.Errorf("%w: map outside event pack", ErrInvalidRequest) + } + position = saved.RawJSON + } + response := wire.AppendString(nil, 4, position) + exploration, err := s.mapExplorationWire(ctx, pack.ID) + if err != nil { + return nil, err + } + response = append(response, exploration...) + buffs, err := s.fieldBuffInfo(ctx) + if err != nil { + return nil, err + } + response = append(response, buffs...) + // The common callback dereferences HuntingGroundInfo even in hidden packs. + // Use the domain-generated empty/current snapshot; never borrow the outside + // map's monsters or story progress. + var hunting []byte + if s.huntingGround != nil { + var err error + hunting, err = s.huntingGround.EnsureForPack(ctx, pack.ID) + if err != nil { + return nil, err + } + } + response = wire.AppendBytes(response, 12, hunting) + // Hidden-pack entry must retain the outside field position: the client + // intentionally suppresses SaveUserPosition while playing these packs. The + // persistent active pack also stays outside, so relogin cannot be stranded + // in a hidden scene after its calendar closes. + return response, nil +} diff --git a/go/internal/server/domain/world/pack_exploration.go b/go/internal/server/domain/world/pack_exploration.go new file mode 100644 index 0000000..214ea8e --- /dev/null +++ b/go/internal/server/domain/world/pack_exploration.go @@ -0,0 +1,179 @@ +package world + +import ( + "bd2server/internal/server/domain/command" + "bd2server/internal/server/protocol/wire" + "fmt" +) + +func (s *Service) handlePackSummary(ctx command.Context, request []byte) (int, []byte, bool, error) { + seq, found, err := wire.Varint(request, 1) + if err != nil || !found || seq == 0 || seq > 0x7fffffff { + return 0, nil, true, fmt.Errorf("%w: PackSummaryInfoList missing or invalid sequence", ErrInvalidRequest) + } + rows, err := s.packDBInfoRows(ctx) + if err != nil { + return 0, nil, true, err + } + var response []byte + for _, row := range rows { + id, found, err := wire.Varint(row, 1) + if err != nil || !found { + return 0, nil, true, fmt.Errorf("world: invalid account pack row") + } + if !s.packSummaryTargets[int(id)] { + continue + } + once, regen, research, err := s.packRewardCounts(ctx, int(id)) + if err != nil { + return 0, nil, true, err + } + row := wire.AppendVarint(nil, 1, id) + if once > 0 { + row = wire.AppendVarint(row, 2, once) + } + if regen > 0 { + row = wire.AppendVarint(row, 3, regen) + } + defeated, err := s.packMonsterDefeatedCount(ctx, int(id)) + if err != nil { + return 0, nil, true, err + } + if defeated > 0 { + row = wire.AppendVarint(row, 4, defeated) + } + if research > 0 { + row = wire.AppendVarint(row, 5, research) + } + response = wire.AppendBytes(response, 1, row) + } + return 625, response, true, nil +} + +func (s *Service) handlePackRewardCounts(ctx command.Context, request []byte) (int, []byte, bool, error) { + seq, present, err := wire.Varint(request, 1) + if err != nil || !present || seq == 0 { + return 226, nil, true, ErrInvalidRequest + } + packs, err := intsRequest(request, 2) + if err != nil || len(packs) == 0 { + return 226, nil, true, ErrInvalidRequest + } + types, err := intsRequest(request, 3) + if err != nil { + return 226, nil, true, err + } + if len(types) == 0 { + types = []uint64{1, 2, 3, 4} + } + var out []byte + seen := map[[2]uint64]bool{} + for _, p := range packs { + pack := int(p) + if pack <= 0 || !s.packUnlocked(ctx, pack) { + return 226, nil, true, ErrInvalidRequest + } + for _, t := range types { + if t < 1 || t > 4 { + return 226, nil, true, ErrInvalidRequest + } + key := [2]uint64{p, t} + if seen[key] { + continue + } + seen[key] = true + var count, max uint64 + if t == 1 { + d, e := s.researchDesign(pack) + if e != nil { + return 226, nil, true, e + } + ids, e := s.state.ResearchObjects(ctx, pack) + if e != nil { + return 226, nil, true, e + } + for _, o := range d.Objects { + if o.CollectionID > 0 || o.Reward.Type > 0 { + max++ + } + } + for _, id := range ids { + if o, ok := d.Objects[id]; ok && (o.CollectionID > 0 || o.Reward.Type > 0) { + count++ + } + } + } else { + d, e := s.fieldObjectDesign(ctx, pack) + if e != nil { + return 226, nil, true, e + } + for _, o := range d.Objects { + if !matchesFieldCount(o, t) { + continue + } + period, e := s.fieldObjectPeriodFor(pack, o) + if t != 4 || e == nil { + max++ + } + if e != nil { + continue + } + opened, e := s.state.FieldRewardOpened(ctx, pack, o.ID, period) + if e != nil { + return 226, nil, true, e + } + if opened { + count++ + } + } + } + info := wire.AppendVarint(nil, 1, t) + info = wire.AppendVarint(info, 2, p) + info = wire.AppendVarint(info, 3, count) + info = wire.AppendVarint(info, 4, max) + out = wire.AppendBytes(out, 1, info) + } + } + return 226, out, true, nil +} + +// EnsureInitialPackPurchase is called only by new-account initialization. It +// awards the bootstrap pack's real purchase rewards, not a recovery inference +// from a saved position or from the former seed-only unlock chain. + +func (s *Service) handlePackDetail(ctx command.Context, request []byte) (int, []byte, bool, error) { + seq, found, err := wire.Varint(request, 1) + if err != nil || !found || seq == 0 || seq > 0x7fffffff { + return 0, nil, true, fmt.Errorf("%w: PackDetailInfo invalid sequence", ErrInvalidRequest) + } + packID, err := requestPack(request) + if err != nil { + return 0, nil, true, err + } + if !s.packUnlocked(ctx, packID) || !s.packSummaryTargets[packID] { + return 0, nil, true, fmt.Errorf("%w: PackDetailInfo unavailable pack %d", ErrInvalidRequest, packID) + } + ids, err := s.openedFieldObjects(ctx, packID) + if err != nil { + return 0, nil, true, err + } + response := []byte{} + rows, err := s.packMonsterRows(ctx, packID) + if err != nil { + return 0, nil, true, err + } + for _, row := range rows { + response = wire.AppendBytes(response, 1, row) + } + for _, id := range ids { + response = wire.AppendBytes(response, 2, wire.AppendVarint(nil, 1, uint64(id))) + } + research, e := s.state.ResearchObjects(ctx, packID) + if e != nil { + return 0, nil, true, e + } + for _, id := range research { + response = wire.AppendVarint(response, 3, uint64(id)) + } + return 627, response, true, nil +} diff --git a/go/internal/server/domain/world/pack_info.go b/go/internal/server/domain/world/pack_info.go new file mode 100644 index 0000000..18e85fc --- /dev/null +++ b/go/internal/server/domain/world/pack_info.go @@ -0,0 +1,299 @@ +package world + +import ( + "bd2server/internal/server/design/gamedata" + "bd2server/internal/server/domain/command" + "bd2server/internal/server/protocol/wire" + "encoding/binary" + "fmt" + "log/slog" + "sort" +) + +func (s *Service) packInfoFor(ctx command.Context, packID int) ([]byte, error) { + out, err := s.basePackInfoFor(ctx, packID) + if err != nil { + return out, err + } + rows, err := s.monsterRows(ctx, packID, nil) + if err != nil { + return nil, err + } + for _, row := range rows { + out = wire.AppendBytes(out, 6, row) + } + buffs, err := s.fieldBuffInfo(ctx) + if err != nil { + return nil, err + } + out = append(out, buffs...) + research, err := s.state.ResearchObjects(ctx, packID) + if err != nil { + return nil, err + } + for _, id := range research { + out = wire.AppendVarint(out, 11, uint64(id)) + } + if s.huntingGround == nil { + return out, nil + } + ground, err := s.huntingGround.EnsureForPack(ctx, packID) + if err != nil { + return nil, err + } + if len(ground) == 0 { + return out, nil + } + out, _, err = wire.ReplaceBytes(out, 12, ground) + return out, err +} + +func (s *Service) basePackInfoFor(ctx command.Context, packID int) ([]byte, error) { + out, err := s.mapExplorationWire(ctx, packID) + if err != nil { + return nil, err + } + if active := s.firstUnclearedQuestFor(packID); active != 0 { + quest := s.questInfoWire(packID, active) + chars, _, err := s.resolveActivePartyWires(ctx, packID, active) + if err != nil { + return nil, err + } + for _, char := range chars { + out = wire.AppendBytes(out, 1, char) + } + out = wire.AppendBytes(out, 2, quest) + } + for _, quest := range s.activeSideQuestWires(packID) { + out = wire.AppendBytes(out, 2, quest) + } + cleared := s.completedQuestIDs(packID) + // CommonPacket requests TodayQuestInfo after parsing this response, before + // the waypoint callback calls PackManager.Enter. That separate response owns + // commission restoration; including commissions here lets Enter append them + // a second time when TodayQuestInfo arrives first, crashing the quest HUD. + if len(cleared) != 0 { + var packed []byte + for _, id := range cleared { + packed = binary.AppendUvarint(packed, uint64(id)) + } + out = wire.AppendBytes(out, 3, packed) + } + position := "{}" + mapID := 0 + restored := false + if saved, found := s.state.Position(); found && saved.PackID == packID && saved.Difficulty == s.questDifficulty(packID) && saved.RawJSON != "" { + if pack, arena := s.fieldPacks[packID]; arena && !pack.MapIDs[saved.Position.MapID] { + return nil, fmt.Errorf("world: saved map %d does not belong to arena pack %d", saved.Position.MapID, packID) + } + position = saved.RawJSON + mapID = saved.Position.MapID + restored = true + } + slog.Info("world: deliver field position", "pack", packID, "map", mapID, "restored", restored) + out = wire.AppendString(out, 4, position) + if s.npcReputation != nil { + rows, err := s.npcReputationRows(ctx, packID) + if err != nil { + return nil, err + } + for _, row := range rows { + out = wire.AppendBytes(out, 9, row) + } + } + statues, err := s.statueInfo(ctx, packID) + if err != nil { + return nil, err + } + out = append(out, statues...) + // The remaining starter-only records were observed in the official + // starter-pack response. They represent reputation, hunting-ground, statue, + // and reward state, not generic defaults, so a newly entered later pack must + // not inherit them. + if packID != s.seed.PackID { + visit := wire.AppendVarint(nil, 5, uint64(packID)) + return wire.AppendBytes(out, 12, visit), nil + } + for _, state := range s.seed.InitialReputations { + if s.npcReputation != nil { + break + } + row := wire.AppendVarint(nil, 1, state.GroupID) + row = wire.AppendVarint(row, 2, state.State) + if state.ElapsedSeconds != 0 { + row = wire.AppendVarint(row, 3, state.ElapsedSeconds) + } + out = wire.AppendBytes(out, 9, row) + } + visit := wire.AppendVarint(nil, 5, uint64(packID)) + out = wire.AppendBytes(out, 12, visit) + if s.packJamDesign == nil { + return out, nil + } + if err := s.packJamDesign.ValidateReward(); err != nil { + return nil, err + } + reward := wire.AppendVarint(nil, 3, s.packJamDesign.Reward.Type) + reward = wire.AppendVarint(reward, 4, s.packJamDesign.Reward.Count) + group := wire.AppendBytes(nil, 1, reward) + group = wire.AppendBytes(group, 6, reward) + return wire.AppendBytes(out, 16, group), nil +} + +func (s *Service) packDBInfoRows(ctx command.Context) ([][]byte, error) { + if s.storyCatalog == nil { + return nil, nil + } + return s.storyPackDBInfoRows(ctx) +} + +func (s *Service) accountPackInfo(ctx command.Context) ([]byte, error) { + rows, err := s.packDBInfoRows(ctx) + if err != nil { + return nil, err + } + var out []byte + for _, info := range rows { + out = wire.AppendBytes(out, 1, info) + } + for _, info := range rows { + id, _, _ := wire.Varint(info, 1) + for level := 0; level <= 4; level++ { + if len(s.state.ClearedQuests(int(id), level)) > 0 || s.questDifficulty(int(id)) == level { + out = wire.AppendBytes(out, 2, s.questLevelInfoWire(int(id), level)) + } + } + } + if s.seed.SquareSceneID != 0 { + out = wire.AppendVarint(out, 5, s.seed.SquareSceneID) + } + replays, err := s.state.QuestReplays(ctx) + if err != nil { + return nil, err + } + packs := make([]int, 0, len(replays)) + for pack := range replays { + packs = append(packs, pack) + } + sort.Ints(packs) + for _, pack := range packs { + out = wire.AppendBytes(out, 7, replayWire(pack, replays[pack])) + } + return out, nil +} + +func (s *Service) storyPackDBInfoRows(ctx command.Context) ([][]byte, error) { + replays, err := s.state.QuestReplays(ctx) + if err != nil { + return nil, err + } + played := make(map[int]bool) + for _, quest := range s.state.AllClearedQuests() { + played[quest.PackID] = true + } + ids := make([]int, 0, len(s.storyCatalog.Packs)) + for id := range s.storyCatalog.Packs { + if s.storyCatalog.Packs[id].Type == 5 { + if s.collection == nil { + continue + } + if _, owned := s.collection.Grant(packPurchaseIdentity(id)); !owned { + continue + } + } + if s.storyPackUnlocked(ctx, id) { + ids = append(ids, id) + } + } + sort.Ints(ids) + var rows [][]byte + for _, id := range ids { + row := wire.AppendVarint(nil, 1, uint64(id)) + selection, _ := s.state.Selection(id) + if selection.Difficulty != 0 { + row = wire.AppendVarint(row, 4, uint64(selection.Difficulty)) + } + if selection.Option != 0 { + row = wire.AppendVarint(row, 5, uint64(selection.Option)) + } + mainCleared := 0 + for _, qid := range s.storyCatalog.Packs[id].MainQuestIDs { + if s.state.QuestCleared(qid, id, s.questDifficulty(id)) { + mainCleared++ + } + } + if mainCleared > 0 { + row = wire.AppendVarint(row, 2, uint64(mainCleared)) + } + if s.packCompleteFor(id) { + row = wire.AppendVarint(row, 3, 1) + } + purchased := false + if s.collection != nil { + _, owned := s.collection.Grant(packPurchaseIdentity(id)) + purchased = purchased || owned + if pack := s.storyCatalog.Packs[id]; pack.Type == 0 && pack.BuyPrice == 0 { + _, entered := s.collection.Grant(packEntryIdentity(id)) + purchased = purchased || entered || played[id] + } + } + if purchased { + row = wire.AppendVarint(row, 8, 1) + } + if _, replaying := replays[id]; replaying { + row = wire.AppendVarint(row, 9, 1) + } + rows = append(rows, row) + } + listed := make(map[int]bool, len(ids)) + for _, id := range ids { + listed[id] = true + } + var fieldIDs []int + for id, pack := range s.fieldPacks { + // Skyway ownership rides on its story-catalog row above. + if pack.Type == 5 || s.collection == nil { + continue + } + if _, purchased := s.collection.Grant(packPurchaseIdentity(id)); purchased { + fieldIDs = append(fieldIDs, id) + listed[id] = true + } + } + sort.Ints(fieldIDs) + for _, id := range fieldIDs { + rows = append(rows, s.fieldPackDBInfo(s.fieldPacks[id])) + } + if saved, found := s.state.Position(); found && !listed[saved.PackID] { + if pack, arena := s.fieldPacks[saved.PackID]; arena && pack.Type != 5 && pack.Type != 9 && pack.MapIDs[saved.Position.MapID] { + rows = append(rows, wire.AppendVarint(wire.AppendVarint(nil, 1, uint64(saved.PackID)), 8, 1)) + } + } + return rows, nil +} + +func (s *Service) eventPackDBInfo(pack gamedata.EventFieldPack) []byte { + row := wire.AppendVarint(nil, 1, uint64(pack.ID)) + if s.packPurchased(pack.ID) { + row = wire.AppendVarint(row, 8, 1) + } + return row +} + +func (s *Service) eventPackInfoRows(ctx command.Context) ([][]byte, error) { + if s.eventFieldPacks == nil { + return nil, nil + } + packs, err := s.eventFieldPacks.ListEventFieldPacks(ctx) + if err != nil { + return nil, err + } + var rows [][]byte + for _, pack := range packs { + // PackManager buys a hidden pack only when PackInfo has no row for it. + if s.packPurchased(pack.ID) { + rows = append(rows, s.eventPackDBInfo(pack)) + } + } + return rows, nil +} diff --git a/go/internal/server/domain/world/pack_purchase.go b/go/internal/server/domain/world/pack_purchase.go index 5a94ae5..3cb2da6 100644 --- a/go/internal/server/domain/world/pack_purchase.go +++ b/go/internal/server/domain/world/pack_purchase.go @@ -4,12 +4,110 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" assets "bd2server/internal/server/domain/inventory" + "bd2server/internal/server/domain/roster" + "bd2server/internal/server/protocol/wire" "fmt" ) func packPurchaseIdentity(id int) string { return fmt.Sprintf("pack-purchase:%d", id) } func packEntryIdentity(id int) string { return fmt.Sprintf("pack-entered:%d", id) } +// EnsureInitialPackPurchase awards the configured starting card only during +// account initialization. It does not infer ownership from a saved position. +func (s *Service) EnsureInitialPackPurchase(ctx command.Context) error { + pack, err := s.resolvePack(ctx, s.startingPack()) + if err != nil { + return err + } + _, err = s.purchaseResolvedPack(ctx, pack, true) + return err +} + +func (s *Service) handlePackBuy(ctx command.Context, request []byte) (int, []byte, bool, error) { + id, err := requestPack(request) + if err != nil { + return 6, nil, true, err + } + pack, err := s.resolvePack(ctx, id) + if err != nil { + return 6, nil, true, err + } + if !s.packRequirementsMet(ctx, pack) { + return 6, nil, true, fmt.Errorf("%w: unavailable purchase pack %d", ErrInvalidRequest, id) + } + bundle, err := s.purchaseResolvedPack(ctx, pack, false) + if err != nil { + return 6, nil, true, err + } + var info []byte + switch pack.kind { + case eventCard: + info = s.eventPackDBInfo(pack.event) + case fieldCard: + if pack.field.Type != 5 { + info = s.fieldPackDBInfo(pack.field) + } + } + if info == nil { + rows, err := s.packDBInfoRows(ctx) + if err != nil { + return 6, nil, true, err + } + for _, row := range rows { + value, _, _ := wire.Varint(row, 1) + if value == uint64(id) { + info = row + break + } + } + } + if info == nil { + return 6, nil, true, fmt.Errorf("world: purchased pack %d absent from account", id) + } + return 6, wire.AppendBytes(wire.AppendBytes(nil, 1, info), 2, bundle), true, nil +} + +// All card purchase paths share one receipt. The enclosing account transaction +// commits the price, rewards and ownership together. +func (s *Service) purchaseResolvedPack(ctx command.Context, pack packDefinition, initial bool) ([]byte, error) { + if s.collection == nil { + return nil, fmt.Errorf("world: pack purchase collection unavailable") + } + if s.packPurchased(pack.id) { + return []byte{}, nil + } + buyType, buyPrice, rewards := pack.purchaseTerms() + identity := packPurchaseIdentity(pack.id) + var bundle []byte + var err error + if pack.kind == fieldCard { + economy := s.fieldPackEconomy + if pack.field.Type == 5 { + if s.skyway == nil { + return nil, fmt.Errorf("world: SkyWay purchase runtime unavailable") + } + economy = s.skyway.economy + } + if economy == nil { + return nil, fmt.Errorf("world: field pack purchase economy unavailable") + } + var costs []gamedata.Reward + if !initial && buyPrice != 0 { + costs = []gamedata.Reward{{Type: buyType, Count: buyPrice}} + } + bundle, err = economy.Apply(ctx, identity, costs, rewards) + } else { + bundle, err = s.applyStoryPackPurchase(ctx, pack.id, buyType, buyPrice, rewards, initial) + } + if err != nil { + return nil, err + } + if err := s.collection.RecordGrantMarker(ctx, identity); err != nil { + return nil, err + } + return bundle, nil +} + func (s *Service) grantPurchaseRewards(ctx command.Context, identity string, rewards []gamedata.Reward) ([]assets.Item, error) { var itemRewards []gamedata.BattleReward for _, reward := range rewards { @@ -73,3 +171,51 @@ func purchaseCurrency(typ uint64) bool { } return false } + +func (s *Service) applyStoryPackPurchase(ctx command.Context, id int, buyType, buyPrice uint64, buyRewards []gamedata.Reward, initial bool) ([]byte, error) { + if s.wallet == nil || s.inventory == nil { + return nil, fmt.Errorf("world: purchase services unavailable") + } + identity := packPurchaseIdentity(id) + for _, reward := range buyRewards { + if !purchaseCurrency(reward.Type) && reward.Type != 19 && reward.Type != 11 { + return nil, fmt.Errorf("world: unsupported pack purchase reward type %d", reward.Type) + } + } + if !initial && buyPrice != 0 { + var err error + switch buyType { + case 2: + _, err = s.wallet.SpendJewelryOnce(ctx, identity+":price", buyPrice) + case 3: + _, err = s.wallet.SpendFreeJewelryOnce(ctx, identity+":price", buyPrice) + case 4: + _, err = s.wallet.SpendGoldOnce(ctx, identity+":price", buyPrice) + case 12: + _, err = s.wallet.SpendCatalystOnce(ctx, identity+":price", buyPrice) + default: + return nil, fmt.Errorf("%w: unsupported pack purchase currency%d", ErrInvalidRequest, buyType) + } + if err != nil { + return nil, err + } + } + items, err := s.grantPurchaseRewards(ctx, identity, buyRewards) + if err != nil { + return nil, err + } + var bundle []byte + if grant, found := s.collection.Grant(identity + ":costumes"); found { + bundle = append(bundle, roster.CollectionRewardBundle(s.collection, grant)...) + } + for _, reward := range buyRewards { + if purchaseCurrency(reward.Type) { + currency := wire.AppendVarint(wire.AppendVarint(nil, 3, reward.Type), 4, reward.Count) + bundle = wire.AppendBytes(bundle, 1, currency) + } + } + for _, item := range items { + bundle = wire.AppendBytes(bundle, 1, assets.ItemWire(item)) + } + return bundle, nil +} diff --git a/go/internal/server/domain/world/progress/protocol_adapter.go b/go/internal/server/domain/world/progress/protocol_adapter.go index 2dbe1ed..bcfb8ed 100644 --- a/go/internal/server/domain/world/progress/protocol_adapter.go +++ b/go/internal/server/domain/world/progress/protocol_adapter.go @@ -12,18 +12,8 @@ import ( "strconv" ) -// UpdateQuest consumes QuestUpdateRequest: field 1 seq, field 2 quest_id, -// field 3 pack_id, and repeated packed/unpacked int32 field 4 quest_value. -// It returns the quest id that the response must echo as update_quest_id. -func (s *Store) UpdateQuest(ctx command.Context, request []byte) (int, error) { - questID, found, err := wire.Varint(request, 2) - if err != nil || !found || questID == 0 || questID > uint64(^uint32(0)>>1) { - return 0, fmt.Errorf("%w: quest id", ErrInvalidQuest) - } - packID, found, err := wire.Varint(request, 3) - if err != nil || !found || packID == 0 || packID > uint64(^uint32(0)>>1) { - return 0, fmt.Errorf("%w: pack id", ErrInvalidQuest) - } +// QuestValues reads QuestUpdateRequest.quest_value, packed or unpacked. +func QuestValues(request []byte) ([]int, error) { values := make([]int, 0, 4) if err := wire.Walk(request, func(field wire.Field) error { if field.Number != 4 { @@ -50,7 +40,26 @@ func (s *Store) UpdateQuest(ctx command.Context, request []byte) (int, error) { } return nil }); err != nil { - return 0, fmt.Errorf("%w: quest values", ErrInvalidQuest) + return nil, fmt.Errorf("%w: quest values", ErrInvalidQuest) + } + return values, nil +} + +// UpdateQuest consumes QuestUpdateRequest: field 1 seq, field 2 quest_id, +// field 3 pack_id, and repeated packed/unpacked int32 field 4 quest_value. +// It returns the quest id that the response must echo as update_quest_id. +func (s *Store) UpdateQuest(ctx command.Context, request []byte) (int, error) { + questID, found, err := wire.Varint(request, 2) + if err != nil || !found || questID == 0 || questID > uint64(^uint32(0)>>1) { + return 0, fmt.Errorf("%w: quest id", ErrInvalidQuest) + } + packID, found, err := wire.Varint(request, 3) + if err != nil || !found || packID == 0 || packID > uint64(^uint32(0)>>1) { + return 0, fmt.Errorf("%w: pack id", ErrInvalidQuest) + } + values, err := QuestValues(request) + if err != nil { + return 0, err } progress := QuestProgress{QuestID: int(questID), PackID: int(packID), Values: append([]int(nil), values...)} diff --git a/go/internal/server/domain/world/progress/replay.go b/go/internal/server/domain/world/progress/replay.go new file mode 100644 index 0000000..c93861d --- /dev/null +++ b/go/internal/server/domain/world/progress/replay.go @@ -0,0 +1,83 @@ +package progress + +import ( + "bd2server/internal/server/domain/command" + "encoding/json" + "fmt" + "strconv" +) + +// QuestReplay is a main-story replay of a pack whose hardest difficulty is +// complete. Previous is the selection restored when the replay ends. +type QuestReplay struct { + QuestID int `json:"quest_id"` + Difficulty int `json:"difficulty"` + Values []int `json:"values"` + BattleSkip bool `json:"battle_skip"` + Previous QuestSelection `json:"previous"` +} + +func (r QuestReplay) valid() bool { + return r.QuestID > 0 && r.Difficulty >= 0 && r.Difficulty <= 4 && r.Previous.QuestID >= 0 && r.Previous.Difficulty >= 0 && r.Previous.Difficulty <= 4 && r.Previous.Option >= 0 +} + +func (s *Store) QuestReplay(ctx command.Context, pack int) (QuestReplay, bool, error) { + store, err := s.fieldRewardEntries() + if err != nil { + return QuestReplay{}, false, err + } + raw, found, err := store.LoadEntry(ctx.State, "progress", "quest_replays", strconv.Itoa(pack)) + if err != nil || !found { + return QuestReplay{}, false, err + } + var replay QuestReplay + if err = json.Unmarshal(raw, &replay); err != nil || !replay.valid() { + return QuestReplay{}, false, fmt.Errorf("progress: invalid quest replay for pack %d", pack) + } + return replay, true, nil +} + +func (s *Store) QuestReplays(ctx command.Context) (map[int]QuestReplay, error) { + store, err := s.fieldRewardEntries() + if err != nil { + return nil, err + } + entries, err := store.ListEntries(ctx.State, "progress", "quest_replays") + if err != nil { + return nil, err + } + out := make(map[int]QuestReplay, len(entries)) + for key, raw := range entries { + pack, err := strconv.Atoi(key) + var replay QuestReplay + if err != nil || pack <= 0 || json.Unmarshal(raw, &replay) != nil || !replay.valid() { + return nil, fmt.Errorf("progress: invalid quest replay %q", key) + } + out[pack] = replay + } + return out, nil +} + +func (s *Store) SaveQuestReplay(ctx command.Context, pack int, replay QuestReplay) error { + if pack <= 0 || !replay.valid() { + return fmt.Errorf("progress: invalid quest replay for pack %d", pack) + } + store, err := s.fieldRewardEntries() + if err != nil { + return err + } + raw, err := json.Marshal(replay) + if err != nil { + return err + } + return store.PutEntry(ctx.State, "progress", "quest_replays", strconv.Itoa(pack), raw) +} + +func (s *Store) DeleteQuestReplay(ctx command.Context, pack int) error { + store, err := s.fieldRewardEntries() + if err != nil { + return err + } + _, err = store.DeleteEntry(ctx.State, "progress", "quest_replays", strconv.Itoa(pack)) + return err +} diff --git a/go/internal/server/domain/world/protocol_field_adapter.go b/go/internal/server/domain/world/protocol_field_adapter.go index a651aec..4746783 100644 --- a/go/internal/server/domain/world/protocol_field_adapter.go +++ b/go/internal/server/domain/world/protocol_field_adapter.go @@ -4,6 +4,7 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" assets "bd2server/internal/server/domain/inventory" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/domain/roster" "bd2server/internal/server/domain/world/progress" "bd2server/internal/server/protocol/wire" @@ -677,6 +678,9 @@ func (s *Service) openFieldObjectResponse(ctx command.Context, pack, group, id i if err := s.state.MarkFieldRewardOpened(ctx, pack, id, period); err != nil { return nil, err } + if err := s.recordMission(ctx, conditions.Event{Type: conditions.CollectionGet, Count: 1}); err != nil { + return nil, err + } return append(wire.AppendBytes(nil, 1, nil), effects...), nil } bundle, err := s.openFieldObject(ctx, pack, group, id) @@ -887,7 +891,10 @@ func (s *Service) openFieldObject(ctx command.Context, pack, group, id int) ([]b if obj.BuffID == 0 && obj.MonsterID == 0 && obj.QuestID == 0 && obj.Type != 5 && obj.Type != 6 { return nil, fmt.Errorf("%w: empty field object", ErrInvalidRequest) } - return nil, s.state.MarkFieldRewardOpened(ctx, pack, id, period) + if err = s.state.MarkFieldRewardOpened(ctx, pack, id, period); err != nil { + return nil, err + } + return nil, s.recordMission(ctx, conditions.Event{Type: conditions.CollectionGet, Count: 1}) } if s.wallet == nil || s.inventory == nil { return nil, fmt.Errorf("world: field reward stores unavailable") @@ -980,6 +987,9 @@ func (s *Service) openFieldObject(ctx command.Context, pack, group, id int) ([]b if err = s.state.MarkFieldRewardOpened(ctx, pack, id, period); err != nil { return nil, err } + if err = s.recordMission(ctx, conditions.Event{Type: conditions.CollectionGet, Count: 1}); err != nil { + return nil, err + } var bundle []byte for _, r := range rewards { bundle = wire.AppendBytes(bundle, 1, assets.ItemWire(assets.Item{ID: r.ID, Type: r.Type, Count: r.Count})) diff --git a/go/internal/server/domain/world/protocol_npc_adapter.go b/go/internal/server/domain/world/protocol_npc_adapter.go index bd2041b..2964748 100644 --- a/go/internal/server/domain/world/protocol_npc_adapter.go +++ b/go/internal/server/domain/world/protocol_npc_adapter.go @@ -88,6 +88,16 @@ func (s *Service) handleQuestUpdate(ctx command.Context, request []byte) (int, [ if err != nil || current != pack || !s.canClear(ctx, pack, quest) { return 0, nil, true, ErrInvalidRequest } + replay, replaying, err := s.state.QuestReplay(ctx, pack) + if err != nil { + return 0, nil, true, err + } + if replaying && quest == replay.QuestID { + if err := s.updateQuestReplay(ctx, pack, replay, request); err != nil { + return 0, nil, true, err + } + return 19, wire.AppendBytes(wire.AppendVarint(nil, 1, uint64(quest)), 2, nil), true, nil + } if s.state.QuestCleared(quest, pack, s.questDifficultyFor(pack, quest)) { // A delayed replay must not reinsert a cleared quest into active progress. return 19, wire.AppendBytes(wire.AppendVarint(nil, 1, uint64(quest)), 2, nil), true, nil diff --git a/go/internal/server/domain/world/protocol_pack_adapter.go b/go/internal/server/domain/world/protocol_pack_adapter.go new file mode 100644 index 0000000..981f02b --- /dev/null +++ b/go/internal/server/domain/world/protocol_pack_adapter.go @@ -0,0 +1,56 @@ +package world + +import ( + "fmt" + + "bd2server/internal/server/domain/command" + "bd2server/internal/server/protocol/wire" +) + +func (s *Service) handlePacks(ctx command.Context, path string, request []byte) (int, []byte, bool, error) { + switch path { + case "/PackBuy": + return s.handlePackBuy(ctx, request) + case "/PackDetailInfo": + return s.handlePackDetail(ctx, request) + case "/PackSummaryInfoList": + return s.handlePackSummary(ctx, request) + case "/PackRewardObjectCount": + return s.handlePackRewardCounts(ctx, request) + case "/PackPreviewInfo", "/PackJamEvent": + return s.handlePackDocking(ctx, path, request) + case "/PackInGameInfo": + return s.handlePackEntry(ctx, request) + case "/PackInfo": + seq, found, err := wire.Varint(request, 1) + if err != nil || !found || seq == 0 { + return 4, nil, true, fmt.Errorf("%w: PackInfo missing sequence", ErrInvalidRequest) + } + body, err := s.accountPackInfo(ctx) + if err != nil { + return 4, nil, true, err + } + rows, err := s.eventPackInfoRows(ctx) + if err != nil { + return 4, nil, true, err + } + for _, row := range rows { + body = wire.AppendBytes(body, 1, row) + } + return 4, body, true, nil + default: + return 0, nil, false, nil + } +} + +func requestPack(request []byte) (int, error) { + seq, found, err := wire.Varint(request, 1) + if err != nil || !found || seq == 0 { + return 0, ErrInvalidRequest + } + pack, found, err := wire.Varint(request, 2) + if err != nil || !found || pack == 0 || pack > uint64(^uint32(0)>>1) { + return 0, ErrInvalidRequest + } + return int(pack), nil +} diff --git a/go/internal/server/domain/world/protocol_quest_adapter.go b/go/internal/server/domain/world/protocol_quest_adapter.go index e36ad3f..6560439 100644 --- a/go/internal/server/domain/world/protocol_quest_adapter.go +++ b/go/internal/server/domain/world/protocol_quest_adapter.go @@ -160,6 +160,24 @@ func (s *Service) handleQuestSelection(ctx command.Context, path string, request if !known || !exists { return 0, nil, true, ErrInvalidRequest } + if design.Type == 0 { + replay, replaying, err := s.state.QuestReplay(ctx, pack) + if err != nil { + return 0, nil, true, err + } + if path == "/QuestGiveUp" && replaying { + return s.giveUpQuestReplay(ctx, pack, quest, replay) + } + } + if path == "/QuestAccept" { + retry, _, err := wire.Varint(request, 6) + if err != nil || retry > 1 || retry == 1 && design.Type != 0 { + return 0, nil, true, ErrInvalidRequest + } + if retry == 1 { + return s.acceptQuestReplay(ctx, pack, quest, request) + } + } if path == "/QuestGiveUp" { if design.Type != 0 { if _, ok := s.state.QuestInPack(quest, pack); !ok { diff --git a/go/internal/server/domain/world/protocol_story_adapter.go b/go/internal/server/domain/world/protocol_story_adapter.go index b762570..9e7006f 100644 --- a/go/internal/server/domain/world/protocol_story_adapter.go +++ b/go/internal/server/domain/world/protocol_story_adapter.go @@ -11,22 +11,8 @@ import ( "errors" "fmt" "log/slog" - "slices" - "sort" ) -func requestPack(request []byte) (int, error) { - seq, found, err := wire.Varint(request, 1) - if err != nil || !found || seq == 0 { - return 0, ErrInvalidRequest - } - pack, found, err := wire.Varint(request, 2) - if err != nil || !found || pack == 0 || pack > uint64(^uint32(0)>>1) { - return 0, ErrInvalidRequest - } - return int(pack), nil -} - func requestQuest(request []byte) (int, int, error) { quest, err := requestPack(request) // fields 1 and 2 have the same validation. if err != nil { @@ -39,140 +25,7 @@ func requestQuest(request []byte) (int, int, error) { return quest, int(pack), nil } -// packInfo is the canonical protobuf encoding of the semantic new-account -// starter-pack state. Its response is generated from the authoritative local progress state. - -func (s *Service) packInfoFor(ctx command.Context, packID int) ([]byte, error) { - out, err := s.basePackInfoFor(ctx, packID) - if err != nil { - return out, err - } - rows, err := s.monsterRows(ctx, packID, nil) - if err != nil { - return nil, err - } - for _, row := range rows { - out = wire.AppendBytes(out, 6, row) - } - buffs, err := s.fieldBuffInfo(ctx) - if err != nil { - return nil, err - } - out = append(out, buffs...) - research, err := s.state.ResearchObjects(ctx, packID) - if err != nil { - return nil, err - } - for _, id := range research { - out = wire.AppendVarint(out, 11, uint64(id)) - } - if s.huntingGround == nil { - return out, nil - } - ground, err := s.huntingGround.EnsureForPack(ctx, packID) - if err != nil { - return nil, err - } - if len(ground) == 0 { - return out, nil - } - out, _, err = wire.ReplaceBytes(out, 12, ground) - return out, err -} - -func (s *Service) basePackInfoFor(ctx command.Context, packID int) ([]byte, error) { - out, err := s.mapExplorationWire(ctx, packID) - if err != nil { - return nil, err - } - if active := s.firstUnclearedQuestFor(packID); active != 0 { - quest := s.questInfoWire(packID, active) - chars, _, err := s.resolveActivePartyWires(ctx, packID, active) - if err != nil { - return nil, err - } - for _, char := range chars { - out = wire.AppendBytes(out, 1, char) - } - out = wire.AppendBytes(out, 2, quest) - } - for _, quest := range s.activeSideQuestWires(packID) { - out = wire.AppendBytes(out, 2, quest) - } - cleared := s.completedQuestIDs(packID) - // CommonPacket requests TodayQuestInfo after parsing this response, before - // the waypoint callback calls PackManager.Enter. That separate response owns - // commission restoration; including commissions here lets Enter append them - // a second time when TodayQuestInfo arrives first, crashing the quest HUD. - if len(cleared) != 0 { - var packed []byte - for _, id := range cleared { - packed = binary.AppendUvarint(packed, uint64(id)) - } - out = wire.AppendBytes(out, 3, packed) - } - position := "{}" - mapID := 0 - restored := false - if saved, found := s.state.Position(); found && saved.PackID == packID && saved.Difficulty == s.questDifficulty(packID) && saved.RawJSON != "" { - if pack, arena := s.fieldPacks[packID]; arena && !pack.MapIDs[saved.Position.MapID] { - return nil, fmt.Errorf("world: saved map %d does not belong to arena pack %d", saved.Position.MapID, packID) - } - position = saved.RawJSON - mapID = saved.Position.MapID - restored = true - } - slog.Info("world: deliver field position", "pack", packID, "map", mapID, "restored", restored) - out = wire.AppendString(out, 4, position) - if s.npcReputation != nil { - rows, err := s.npcReputationRows(ctx, packID) - if err != nil { - return nil, err - } - for _, row := range rows { - out = wire.AppendBytes(out, 9, row) - } - } - statues, err := s.statueInfo(ctx, packID) - if err != nil { - return nil, err - } - out = append(out, statues...) - // The remaining starter-only records were observed in the official - // starter-pack response. They represent reputation, hunting-ground, statue, - // and reward state, not generic defaults, so a newly entered later pack must - // not inherit them. - if packID != s.seed.PackID { - visit := wire.AppendVarint(nil, 5, uint64(packID)) - return wire.AppendBytes(out, 12, visit), nil - } - for _, state := range s.seed.InitialReputations { - if s.npcReputation != nil { - break - } - row := wire.AppendVarint(nil, 1, state.GroupID) - row = wire.AppendVarint(row, 2, state.State) - if state.ElapsedSeconds != 0 { - row = wire.AppendVarint(row, 3, state.ElapsedSeconds) - } - out = wire.AppendBytes(out, 9, row) - } - visit := wire.AppendVarint(nil, 5, uint64(packID)) - out = wire.AppendBytes(out, 12, visit) - if s.packJamDesign == nil { - return out, nil - } - if err := s.packJamDesign.ValidateReward(); err != nil { - return nil, err - } - reward := wire.AppendVarint(nil, 3, s.packJamDesign.Reward.Type) - reward = wire.AppendVarint(reward, 4, s.packJamDesign.Reward.Count) - group := wire.AppendBytes(nil, 1, reward) - group = wire.AppendBytes(group, 6, reward) - return wire.AppendBytes(out, 16, group), nil -} - -func (s *Service) clearResponse(ctx command.Context, packID, quest int, designRewards []gamedata.Reward, items []assets.Item, questEquipment *assets.Equipment, nextItems []assets.Item, nextChars [][]byte) []byte { +func (s *Service) questClearRewards(packID, quest int, designRewards []gamedata.Reward, items []assets.Item, questEquipment *assets.Equipment) []byte { var rewards []byte if s.collection != nil { if grant, found := s.collection.Grant(questRewardIdentity(packID, quest, s.questDifficultyFor(packID, quest)) + ":costumes"); found { @@ -223,6 +76,10 @@ func (s *Service) clearResponse(ctx command.Context, packID, quest int, designRe viewCharacter = wire.AppendVarint(viewCharacter, 4, 1) rewards = wire.AppendBytes(rewards, 6, viewCharacter) } + return rewards +} + +func (s *Service) clearResponse(ctx command.Context, packID, quest int, rewards []byte, nextItems []assets.Item, nextChars [][]byte) ([]byte, error) { var out []byte out = wire.AppendBytes(out, 1, rewards) next := s.nextQuestFor(ctx, packID, quest) @@ -247,7 +104,11 @@ func (s *Service) clearResponse(ctx command.Context, packID, quest int, designRe // The final normal quest unlocks PackTable.NextPackId. Without these // PackDBInfo updates the client cannot find the next story pack and // falls back to presenting the hard-difficulty objective. - for _, info := range s.packDBInfoRows(ctx) { + rows, err := s.packDBInfoRows(ctx) + if err != nil { + return nil, err + } + for _, info := range rows { out = wire.AppendBytes(out, 11, info) } } @@ -258,37 +119,9 @@ func (s *Service) clearResponse(ctx command.Context, packID, quest int, designRe } out = wire.AppendBytes(out, 9, s.questLevelInfoWire(packID, s.questDifficultyFor(packID, quest))) out = wire.AppendBytes(out, 12, nil) - return wire.AppendBytes(out, 13, nil) + return wire.AppendBytes(out, 13, nil), nil } -func (s *Service) packDBInfoRows(ctx command.Context) [][]byte { - if s.storyCatalog == nil { - return nil - } - return s.storyPackDBInfoRows(ctx) -} - -func (s *Service) accountPackInfo(ctx command.Context) []byte { - var out []byte - for _, info := range s.packDBInfoRows(ctx) { - out = wire.AppendBytes(out, 1, info) - } - for _, info := range s.packDBInfoRows(ctx) { - id, _, _ := wire.Varint(info, 1) - for level := 0; level <= 4; level++ { - if len(s.state.ClearedQuests(int(id), level)) > 0 || s.questDifficulty(int(id)) == level { - out = wire.AppendBytes(out, 2, s.questLevelInfoWire(int(id), level)) - } - } - } - if s.seed.SquareSceneID != 0 { - out = wire.AppendVarint(out, 5, s.seed.SquareSceneID) - } - return out -} - -// Absorb consumes the exact acquisition objects requested by the client using -// the same period receipts and reward graph as an ordinary field interaction. func (s *Service) ApplyTalentFieldAbsorb(ctx command.Context, _ string, _ roster.Character, rule gamedata.TalentUseRule, ids []uint64) ([]byte, error) { pack, mapID, _, err := s.TalentFieldContext(ctx) if err != nil { @@ -366,110 +199,6 @@ func (s *Service) resolveActivePartyWires(ctx command.Context, packID, questID i return characters, s.currentBattleDeckWires(), nil } -func (s *Service) storyPackDBInfoRows(ctx command.Context) [][]byte { - played := make(map[int]bool) - for _, quest := range s.state.AllClearedQuests() { - played[quest.PackID] = true - } - ids := make([]int, 0, len(s.storyCatalog.Packs)) - for id := range s.storyCatalog.Packs { - if s.storyCatalog.Packs[id].Type == 5 { - if s.collection == nil { - continue - } - if _, owned := s.collection.Grant(packPurchaseIdentity(id)); !owned { - continue - } - } - if s.storyPackUnlocked(ctx, id) { - ids = append(ids, id) - } - } - sort.Ints(ids) - var rows [][]byte - for _, id := range ids { - row := wire.AppendVarint(nil, 1, uint64(id)) - selection, _ := s.state.Selection(id) - if selection.Difficulty != 0 { - row = wire.AppendVarint(row, 4, uint64(selection.Difficulty)) - } - if selection.Option != 0 { - row = wire.AppendVarint(row, 5, uint64(selection.Option)) - } - mainCleared := 0 - for _, qid := range s.storyCatalog.Packs[id].MainQuestIDs { - if s.state.QuestCleared(qid, id, s.questDifficulty(id)) { - mainCleared++ - } - } - if mainCleared > 0 { - row = wire.AppendVarint(row, 2, uint64(mainCleared)) - } - if s.packCompleteFor(id) { - row = wire.AppendVarint(row, 3, 1) - } - purchased := false - if s.collection != nil { - _, owned := s.collection.Grant(packPurchaseIdentity(id)) - purchased = purchased || owned - if pack := s.storyCatalog.Packs[id]; pack.Type == 0 && pack.BuyPrice == 0 { - _, entered := s.collection.Grant(packEntryIdentity(id)) - purchased = purchased || entered || played[id] - } - } - if purchased { - row = wire.AppendVarint(row, 8, 1) - } - rows = append(rows, row) - } - if saved, found := s.state.Position(); found { - if pack, arena := s.fieldPacks[saved.PackID]; arena && pack.Type != 5 && pack.MapIDs[saved.Position.MapID] { - rows = append(rows, wire.AppendVarint(wire.AppendVarint(nil, 1, uint64(saved.PackID)), 8, 1)) - } - } - return rows -} - -func (s *Service) handlePackSummary(ctx command.Context, request []byte) (int, []byte, bool, error) { - seq, found, err := wire.Varint(request, 1) - if err != nil || !found || seq == 0 || seq > 0x7fffffff { - return 0, nil, true, fmt.Errorf("%w: PackSummaryInfoList missing or invalid sequence", ErrInvalidRequest) - } - var response []byte - for _, row := range s.packDBInfoRows(ctx) { - id, found, err := wire.Varint(row, 1) - if err != nil || !found { - return 0, nil, true, fmt.Errorf("world: invalid account pack row") - } - if !s.packSummaryTargets[int(id)] { - continue - } - once, regen, research, err := s.packRewardCounts(ctx, int(id)) - if err != nil { - return 0, nil, true, err - } - row := wire.AppendVarint(nil, 1, id) - if once > 0 { - row = wire.AppendVarint(row, 2, once) - } - if regen > 0 { - row = wire.AppendVarint(row, 3, regen) - } - defeated, err := s.packMonsterDefeatedCount(ctx, int(id)) - if err != nil { - return 0, nil, true, err - } - if defeated > 0 { - row = wire.AppendVarint(row, 4, defeated) - } - if research > 0 { - row = wire.AppendVarint(row, 5, research) - } - response = wire.AppendBytes(response, 1, row) - } - return 625, response, true, nil -} - func intsRequest(raw []byte, number int) ([]uint64, error) { var out []uint64 err := wire.Walk(raw, func(f wire.Field) error { @@ -602,384 +331,10 @@ func (s *Service) handleFieldResearch(ctx command.Context, request []byte) (int, return 59, append(wire.AppendVarint(nil, 1, seq), items...), true, nil } -func (s *Service) handlePackRewardCounts(ctx command.Context, request []byte) (int, []byte, bool, error) { - seq, present, err := wire.Varint(request, 1) - if err != nil || !present || seq == 0 { - return 226, nil, true, ErrInvalidRequest - } - packs, err := intsRequest(request, 2) - if err != nil || len(packs) == 0 { - return 226, nil, true, ErrInvalidRequest - } - types, err := intsRequest(request, 3) - if err != nil { - return 226, nil, true, err - } - if len(types) == 0 { - types = []uint64{1, 2, 3, 4} - } - var out []byte - seen := map[[2]uint64]bool{} - for _, p := range packs { - pack := int(p) - if pack <= 0 || !s.packUnlocked(ctx, pack) { - return 226, nil, true, ErrInvalidRequest - } - for _, t := range types { - if t < 1 || t > 4 { - return 226, nil, true, ErrInvalidRequest - } - key := [2]uint64{p, t} - if seen[key] { - continue - } - seen[key] = true - var count, max uint64 - if t == 1 { - d, e := s.researchDesign(pack) - if e != nil { - return 226, nil, true, e - } - ids, e := s.state.ResearchObjects(ctx, pack) - if e != nil { - return 226, nil, true, e - } - for _, o := range d.Objects { - if o.CollectionID > 0 || o.Reward.Type > 0 { - max++ - } - } - for _, id := range ids { - if o, ok := d.Objects[id]; ok && (o.CollectionID > 0 || o.Reward.Type > 0) { - count++ - } - } - } else { - d, e := s.fieldObjectDesign(ctx, pack) - if e != nil { - return 226, nil, true, e - } - for _, o := range d.Objects { - if !matchesFieldCount(o, t) { - continue - } - period, e := s.fieldObjectPeriodFor(pack, o) - if t != 4 || e == nil { - max++ - } - if e != nil { - continue - } - opened, e := s.state.FieldRewardOpened(ctx, pack, o.ID, period) - if e != nil { - return 226, nil, true, e - } - if opened { - count++ - } - } - } - info := wire.AppendVarint(nil, 1, t) - info = wire.AppendVarint(info, 2, p) - info = wire.AppendVarint(info, 3, count) - info = wire.AppendVarint(info, 4, max) - out = wire.AppendBytes(out, 1, info) - } - } - return 226, out, true, nil -} - -// EnsureInitialPackPurchase is called only by new-account initialization. It -// awards the bootstrap pack's real purchase rewards, not a recovery inference -// from a saved position or from the former seed-only unlock chain. -func (s *Service) EnsureInitialPackPurchase(ctx command.Context) error { - _, err := s.purchaseStoryPack(ctx, s.startingPack(), true) - return err -} - -func (s *Service) handlePackBuy(ctx command.Context, request []byte) (int, []byte, bool, error) { - id, err := requestPack(request) - if err != nil { - return 0, nil, true, err - } - if pack, found, err := s.resolveEventFieldPack(ctx, id); err != nil { - return 0, nil, true, err - } else if found { - bundle, err := s.purchasePack(ctx, id, pack.BuyType, pack.BuyPrice, pack.BuyRewards, false) - if err != nil { - return 0, nil, true, err - } - response := wire.AppendBytes(nil, 1, s.eventPackDBInfo(pack)) - return 6, wire.AppendBytes(response, 2, bundle), true, nil - } - if !s.packUnlocked(ctx, id) { - return 0, nil, true, fmt.Errorf("%w: unavailable purchase pack %d", ErrInvalidRequest, id) - } - bundle, err := s.purchaseStoryPack(ctx, id, false) - if err != nil { - return 0, nil, true, err - } - var info []byte - for _, row := range s.packDBInfoRows(ctx) { - value, _, _ := wire.Varint(row, 1) - if value == uint64(id) { - info = row - break - } - } - if info == nil { - return 0, nil, true, fmt.Errorf("world: purchased pack absent from account") - } - response := wire.AppendBytes(nil, 1, info) - return 6, wire.AppendBytes(response, 2, bundle), true, nil -} - -func (s *Service) purchaseStoryPack(ctx command.Context, id int, initial bool) ([]byte, error) { - if s.storyCatalog == nil { - return nil, fmt.Errorf("world: purchase services unavailable") - } - pack, exists := s.storyCatalog.Packs[id] - if !exists { - return nil, fmt.Errorf("%w: unknown purchase pack %d", ErrInvalidRequest, id) - } - if pack.Type == 5 { - if s.skyway == nil || s.collection == nil { - return nil, fmt.Errorf("world: SkyWay purchase runtime unavailable") - } - identity := packPurchaseIdentity(id) - if _, owned := s.collection.Grant(identity); owned { - return []byte{}, nil - } - var costs []gamedata.Reward - if !initial && pack.BuyPrice > 0 { - costs = []gamedata.Reward{{Type: pack.BuyType, Count: pack.BuyPrice}} - } - bundle, err := s.skyway.economy.Apply(ctx, identity, costs, pack.BuyRewards) - if err != nil { - return nil, err - } - if err = s.collection.RecordGrantMarker(ctx, identity); err != nil { - return nil, err - } - return bundle, nil - } - return s.purchasePack(ctx, id, pack.BuyType, pack.BuyPrice, pack.BuyRewards, initial) -} - -// purchasePack shares the same durable receipt and enclosing account transaction -// across story and calendar-authorized hidden event packs. -func (s *Service) purchasePack(ctx command.Context, id int, buyType, buyPrice uint64, buyRewards []gamedata.Reward, initial bool) ([]byte, error) { - if s.collection == nil || s.wallet == nil || s.inventory == nil { - return nil, fmt.Errorf("world: purchase services unavailable") - } - identity := packPurchaseIdentity(id) - if _, owned := s.collection.Grant(identity); owned { - return []byte{}, nil - } - for _, reward := range buyRewards { - if !purchaseCurrency(reward.Type) && reward.Type != 19 && reward.Type != 11 { - return nil, fmt.Errorf("world: unsupported pack purchase reward type %d", reward.Type) - } - } - if !initial && buyPrice != 0 { - var err error - switch buyType { - case 2: - _, err = s.wallet.SpendJewelryOnce(ctx, identity+":price", buyPrice) - case 3: - _, err = s.wallet.SpendFreeJewelryOnce(ctx, identity+":price", buyPrice) - case 4: - _, err = s.wallet.SpendGoldOnce(ctx, identity+":price", buyPrice) - case 12: - _, err = s.wallet.SpendCatalystOnce(ctx, identity+":price", buyPrice) - default: - return nil, fmt.Errorf("%w: unsupported pack purchase currency%d", ErrInvalidRequest, buyType) - } - if err != nil { - return nil, err - } - } - items, err := s.grantPurchaseRewards(ctx, identity, buyRewards) - if err != nil { - return nil, err - } - if err := s.collection.RecordGrantMarker(ctx, identity); err != nil { - return nil, err - } - var bundle []byte - if grant, found := s.collection.Grant(identity + ":costumes"); found { - bundle = append(bundle, roster.CollectionRewardBundle(s.collection, grant)...) - } - for _, reward := range buyRewards { - if purchaseCurrency(reward.Type) { - currency := wire.AppendVarint(wire.AppendVarint(nil, 3, reward.Type), 4, reward.Count) - bundle = wire.AppendBytes(bundle, 1, currency) - } - } - for _, item := range items { - bundle = wire.AppendBytes(bundle, 1, assets.ItemWire(item)) - } - return bundle, nil -} - -func (s *Service) handlePackDocking(ctx command.Context, path string, request []byte) (int, []byte, bool, error) { - packID, err := requestPack(request) - if err != nil { - return 0, nil, true, err - } - if _, known := s.questsFor(ctx, packID); !known || !s.packUnlocked(ctx, packID) { - return 0, nil, true, fmt.Errorf("%w: unavailable docking pack %d", ErrInvalidRequest, packID) - } - if s.wallet == nil || s.packJamDesign == nil { - return 0, nil, true, fmt.Errorf("world: pack jam design or wallet unavailable") - } - identity := packJamIdentity(packID) - if path == "/PackPreviewInfo" { - var response []byte - titles, err := s.questTitleInfo(packID) - if err != nil { - return 0, nil, true, err - } - for _, title := range titles { - response = wire.AppendBytes(response, 2, title) - } - if active := s.firstUnclearedQuestFor(packID); active != 0 { - quest := wire.AppendVarint(nil, 1, uint64(active)) - quest = wire.AppendVarint(quest, 6, uint64(packID)) - response = wire.AppendBytes(response, 1, quest) - } - if s.wallet.WasGranted(identity) { - response = wire.AppendVarint(response, 3, 1) - } - return 104, response, true, nil - } - // Serialize the claim check and grant so concurrent domain callers cannot - // return the animation reward twice. The wallet commits balance and ledger together. - - if s.wallet.WasGranted(identity) { - return 72, nil, true, nil - } - reward := s.packJamDesign.Reward - if s.packJamDesign.ValidateReward() != nil { - return 0, nil, true, fmt.Errorf("world: unsupported pack jam reward") - } - if _, err := s.wallet.GrantQuestOnce(ctx, identity, []gamedata.Reward{reward}); err != nil { - return 0, nil, true, fmt.Errorf("world: grant pack jam reward: %w", err) - } - item := wire.AppendVarint(nil, 3, reward.Type) - item = wire.AppendVarint(item, 4, reward.Count) - return 72, wire.AppendBytes(nil, 1, item), true, nil -} - -func (s *Service) handlePackDetail(ctx command.Context, request []byte) (int, []byte, bool, error) { - seq, found, err := wire.Varint(request, 1) - if err != nil || !found || seq == 0 || seq > 0x7fffffff { - return 0, nil, true, fmt.Errorf("%w: PackDetailInfo invalid sequence", ErrInvalidRequest) - } - packID, err := requestPack(request) - if err != nil { - return 0, nil, true, err - } - if !s.packUnlocked(ctx, packID) || !s.packSummaryTargets[packID] { - return 0, nil, true, fmt.Errorf("%w: PackDetailInfo unavailable pack %d", ErrInvalidRequest, packID) - } - ids, err := s.openedFieldObjects(ctx, packID) - if err != nil { - return 0, nil, true, err - } - response := []byte{} - rows, err := s.packMonsterRows(ctx, packID) - if err != nil { - return 0, nil, true, err - } - for _, row := range rows { - response = wire.AppendBytes(response, 1, row) - } - for _, id := range ids { - response = wire.AppendBytes(response, 2, wire.AppendVarint(nil, 1, uint64(id))) - } - research, e := s.state.ResearchObjects(ctx, packID) - if e != nil { - return 0, nil, true, e - } - for _, id := range research { - response = wire.AppendVarint(response, 3, uint64(id)) - } - return 627, response, true, nil -} - -func (s *Service) eventPackDBInfo(pack gamedata.EventFieldPack) []byte { - row := wire.AppendVarint(nil, 1, uint64(pack.ID)) - if s.eventPackPurchased(pack.ID) { - row = wire.AppendVarint(row, 8, 1) - } - return row -} - -func (s *Service) eventPackInfoRows(ctx command.Context) ([][]byte, error) { - if s.eventFieldPacks == nil { - return nil, nil - } - packs, err := s.eventFieldPacks.ListEventFieldPacks(ctx) - if err != nil { - return nil, err - } - var rows [][]byte - for _, pack := range packs { - // PackManager buys a hidden pack only when PackInfo has no row for it. - if s.eventPackPurchased(pack.ID) { - rows = append(rows, s.eventPackDBInfo(pack)) - } - } - return rows, nil -} - -func (s *Service) enterEventFieldPack(ctx command.Context, pack gamedata.EventFieldPack) (int, []byte, bool, error) { - if !s.eventPackPurchased(pack.ID) { - return 0, nil, true, fmt.Errorf("%w: event pack %d is not purchased", ErrInvalidRequest, pack.ID) - } - position := pack.InitialPosition - if position == "" { - return 0, nil, true, fmt.Errorf("world: missing event pack initial position") - } - if saved, found := s.state.Position(); found && saved.PackID == pack.ID { - if !slices.Contains(pack.MapIDs, saved.Position.MapID) { - return 0, nil, true, fmt.Errorf("%w: map outside event pack", ErrInvalidRequest) - } - position = saved.RawJSON - } - response := wire.AppendString(nil, 4, position) - exploration, err := s.mapExplorationWire(ctx, pack.ID) - if err != nil { - return 0, nil, true, err - } - response = append(response, exploration...) - buffs, err := s.fieldBuffInfo(ctx) - if err != nil { - return 0, nil, true, err - } - response = append(response, buffs...) - // The common callback dereferences HuntingGroundInfo even in hidden packs. - // Use the domain-generated empty/current snapshot; never borrow the outside - // map's monsters or story progress. - var hunting []byte - if s.huntingGround != nil { - var err error - hunting, err = s.huntingGround.EnsureForPack(ctx, pack.ID) - if err != nil { - return 0, nil, true, err - } - } - response = wire.AppendBytes(response, 12, hunting) - // Hidden-pack entry must retain the outside field position: the client - // intentionally suppresses SaveUserPosition while playing these packs. The - // persistent active pack also stays outside, so relogin cannot be stranded - // in a hidden scene after its calendar closes. - s.setCurrentPack(pack.ID) - return 5, response, true, nil -} - func (s *Service) Handle(ctx command.Context, path string, request []byte) (int, []byte, bool, error) { + if code, body, handled, err := s.handlePacks(ctx, path, request); handled { + return code, body, handled, err + } if code, out, handled, err := s.handleSkyWay(ctx, path, request); handled { return code, out, handled, err } @@ -1037,32 +392,10 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int, return s.handleFieldResearch(ctx, request) case "/TrapDamage", "/FieldTrapInfo", "/InteractionTrigger": return s.handleFieldTraps(ctx, path, request) - case "/PackRewardObjectCount": - return s.handlePackRewardCounts(ctx, request) case "/QuestInfo", "/QuestAccept", "/QuestGiveUp": return s.handleQuestSelection(ctx, path, request) - case "/PackBuy": - return s.handlePackBuy(ctx, request) - case "/PackDetailInfo": - return s.handlePackDetail(ctx, request) - case "/PackSummaryInfoList": - return s.handlePackSummary(ctx, request) - case "/PackPreviewInfo", "/PackJamEvent": - return s.handlePackDocking(ctx, path, request) - case "/PackInfo": - seq, found, err := wire.Varint(request, 1) - if err != nil || !found || seq == 0 { - return 0, nil, true, errors.New("world: PackInfo missing sequence") - } - response := s.accountPackInfo(ctx) - rows, err := s.eventPackInfoRows(ctx) - if err != nil { - return 0, nil, true, err - } - for _, row := range rows { - response = wire.AppendBytes(response, 1, row) - } - return 4, response, true, nil + case "/QuestRetryBattleSkipSave": + return s.saveQuestReplayBattleSkip(ctx, request) case "/CharInfo": seq, found, err := wire.Varint(request, 1) if err != nil || !found || seq == 0 { @@ -1142,87 +475,6 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int, response = wire.AppendBytes(response, 1, encodeCostume(costume)) } return 40, response, true, nil - case "/PackInGameInfo": - if err := s.ResumeFieldTime(ctx); err != nil { - return 0, nil, true, err - } - pack, err := requestPack(request) - if err != nil { - return 0, nil, true, err - } - activeBattle := s.battleActive != nil && s.battleActive(ctx) - if activeBattle { - current, err := s.CurrentPackID(ctx) - if err != nil { - return 0, nil, true, err - } - if pack != current { - return 0, nil, true, fmt.Errorf("%w: cannot change pack during active battle", ErrInvalidRequest) - } - } - if eventPack, found, err := s.resolveEventFieldPack(ctx, pack); err != nil { - return 0, nil, true, err - } else if found { - code, body, handled, e := s.enterEventFieldPack(ctx, eventPack) - if e == nil && s.talentPackInfo != nil { - extra, x := s.talentPackInfo(ctx, pack) - if x != nil { - return 0, nil, true, x - } - body = append(body, extra...) - } - if e == nil && activeBattle { - body = wire.AppendVarint(body, 17, 1) - } - return code, body, handled, e - } - if !s.packUnlocked(ctx, pack) { - return 0, nil, true, fmt.Errorf("%w: unsupported pack %d", ErrInvalidRequest, pack) - } - if s.skyway != nil && pack == s.skyway.design.Pack { - if _, purchased := s.collection.Grant(packPurchaseIdentity(pack)); !purchased { - return 0, nil, true, fmt.Errorf("world: SkyWay pack is not purchased") - } - v, e := s.skyway.load(ctx) - if e != nil { - return 0, nil, true, e - } - if !activeBattle { - v.Run = skyWayRun{Generation: v.Run.Generation} - if e = s.skyway.save(ctx, v); e != nil { - return 0, nil, true, e - } - } - } - if active := s.firstUnclearedQuestFor(pack); active != 0 { - if _, err := s.ensureQuestItems(ctx, pack, active); err != nil { - return 0, nil, true, err - } - } - response, err := s.packInfoFor(ctx, pack) - if err != nil { - return 0, nil, true, err - } - if activeBattle { - response = wire.AppendVarint(response, 17, 1) - } - if s.talentPackInfo != nil { - extra, e := s.talentPackInfo(ctx, pack) - if e != nil { - return 0, nil, true, e - } - response = append(response, extra...) - } - if err := s.state.SetActivePackID(ctx, pack); err != nil { - return 0, nil, true, err - } - if story := s.storyCatalog.Packs[pack]; story.Type == 0 && story.BuyPrice == 0 && s.collection != nil { - if err := s.collection.RecordGrantMarker(ctx, packEntryIdentity(pack)); err != nil { - return 0, nil, true, err - } - } - s.setCurrentPack(pack) - return 5, response, true, nil case "/QuestClear": quest, pack, err := requestQuest(request) if err != nil { @@ -1236,6 +488,42 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int, if !s.canClear(ctx, pack, quest) { return 0, nil, true, fmt.Errorf("%w: quest %d is not active", ErrInvalidRequest, quest) } + quickPlay, _, err := wire.Varint(request, 5) + if err != nil || quickPlay > 1 { + return 0, nil, true, fmt.Errorf("%w: invalid quick-play flag", ErrInvalidRequest) + } + if quickPlay != 0 { + difficulty := s.questDifficultyFor(pack, quest) + if design.Type != 0 || difficulty < 1 || difficulty > 2 || !s.questDifficulties[pack][difficulty] { + return 0, nil, true, fmt.Errorf("%w: quest %d pack %d difficulty %d unavailable for quick play", ErrInvalidRequest, quest, pack, difficulty) + } + for _, id := range s.storyCatalog.Packs[pack].MainQuestIDs { + if !s.state.QuestCleared(id, pack, difficulty-1) { + return 0, nil, true, fmt.Errorf("%w: quick play requires previous difficulty completion", ErrInvalidRequest) + } + } + if design.ConditionType == 1 || design.ConditionType == 3 { + if design.ConditionType != 3 || design.ConditionCount != 1 || s.questBattleWon == nil { + return 0, nil, true, fmt.Errorf("%w: quick battle completion rule unavailable for quest %d", ErrInvalidRequest, quest) + } + won, err := s.questBattleWon(ctx, pack, quest, difficulty) + if err != nil { + return 0, nil, true, err + } + if !won { + return 0, nil, true, fmt.Errorf("%w: quick quest requires committed battle victory pack=%d quest=%d difficulty=%d", ErrInvalidRequest, pack, quest, difficulty) + } + } + } + if design.Type == 0 { + replay, replaying, err := s.state.QuestReplay(ctx, pack) + if err != nil { + return 0, nil, true, err + } + if replaying { + return s.clearQuestReplay(ctx, pack, quest, replay) + } + } wasCleared := s.state.QuestCleared(quest, pack, s.questDifficultyFor(pack, quest)) var previousParty []roster.Character if design.Type == 0 && s.storyRoster != nil { @@ -1251,7 +539,7 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int, if err := s.state.ClearQuest(ctx, quest, pack, s.questDifficultyFor(pack, quest)); err != nil { return 0, nil, true, fmt.Errorf("world: clear quest: %w", err) } - if !wasCleared { + if !wasCleared && quickPlay == 0 { if err := s.beginQuestCompletionPresentation(ctx, pack, quest, s.questDifficultyFor(pack, quest)); err != nil { return 0, nil, true, err } @@ -1292,10 +580,15 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int, saved, positionFound := s.state.Position() slog.Info("quest transition prepared", "account", ctx.AccountID, "pack", pack, "quest", quest, "difficulty", s.questDifficultyFor(pack, quest), "already_cleared", wasCleared, + "quick_play", quickPlay != 0, "next_quest", s.nextQuestFor(ctx, pack, quest), "timeline", design.CompleteCinemaName, "timeline_map", design.TimelineStartMapID, "position_found", positionFound, "saved_position", saved.Position, "party_changes", len(nextChars), "items", len(items)) - return 18, s.clearResponse(ctx, pack, quest, design.Rewards[s.questDifficultyFor(pack, quest)], items, questEquipment, nextItems, nextChars), true, nil + out, err := s.clearResponse(ctx, pack, quest, s.questClearRewards(pack, quest, design.Rewards[s.questDifficultyFor(pack, quest)], items, questEquipment), nextItems, nextChars) + if err != nil { + return 0, nil, true, err + } + return 18, out, true, nil default: return 0, nil, false, nil } diff --git a/go/internal/server/domain/world/quest_battle.go b/go/internal/server/domain/world/quest_battle.go index eb28927..509e24b 100644 --- a/go/internal/server/domain/world/quest_battle.go +++ b/go/internal/server/domain/world/quest_battle.go @@ -5,6 +5,10 @@ import ( "fmt" ) +func (s *Service) AttachQuestVictory(source func(command.Context, int, int, int) (bool, error)) { + s.questBattleWon = source +} + // ValidateQuestBattle checks ownership after GameData resolves the monster's // quest range and battle deck. A side quest remains normal difficulty even // when the player has selected a harder main story. diff --git a/go/internal/server/domain/world/quest_replay.go b/go/internal/server/domain/world/quest_replay.go new file mode 100644 index 0000000..de029e1 --- /dev/null +++ b/go/internal/server/domain/world/quest_replay.go @@ -0,0 +1,205 @@ +package world + +import ( + "bd2server/internal/server/domain/command" + assets "bd2server/internal/server/domain/inventory" + "bd2server/internal/server/domain/roster" + "bd2server/internal/server/domain/world/progress" + "bd2server/internal/server/protocol/wire" + "fmt" +) + +// Main-story replay: once every main quest of a pack is cleared on hard (2), +// QuestReplayPopupUI accepts the first main quest with is_retry, a difficulty +// 0-2 and the battle-skip toggle; QuestPopupUI continues the saved quest. The +// client hides the reward panel while replaying, so replay clears grant nothing. +const replayUnlockDifficulty = 2 + +// replayWire encodes QuestRetryDBInfo; the client converts it into the active +// QuestDBInfo, so quest values travel as object_id like questInfoWire. +func replayWire(pack int, replay progress.QuestReplay) []byte { + out := wire.AppendVarint(nil, 1, uint64(pack)) + if replay.Difficulty != 0 { + out = wire.AppendVarint(out, 2, uint64(replay.Difficulty)) + } + out = wire.AppendVarint(out, 3, uint64(replay.QuestID)) + for _, value := range replay.Values { + out = wire.AppendVarint(out, 5, uint64(value)) + } + if replay.BattleSkip { + out = wire.AppendVarint(out, 6, 1) + } + return out +} + +// endedReplayWire has no quest id; QuestPacket.AddReplayQuest drops the +// client's replay entry for a zero QuestId. +func endedReplayWire(pack int) []byte { return wire.AppendVarint(nil, 1, uint64(pack)) } + +func (s *Service) replayUnlocked(pack int) bool { + ids := s.storyCatalog.Packs[pack].MainQuestIDs + if len(ids) == 0 || !s.questDifficulties[pack][replayUnlockDifficulty] { + return false + } + for _, id := range ids { + if !s.state.QuestCleared(id, pack, replayUnlockDifficulty) { + return false + } + } + return true +} + +func (s *Service) acceptQuestReplay(ctx command.Context, pack, quest int, request []byte) (int, []byte, bool, error) { + level, _, err := wire.Varint(request, 4) + if err != nil || level > replayUnlockDifficulty || level > 0 && !s.questDifficulties[pack][int(level)] { + return 0, nil, true, fmt.Errorf("%w: replay difficulty", ErrInvalidRequest) + } + skip, _, err := wire.Varint(request, 7) + if err != nil || skip > 1 || !s.replayUnlocked(pack) { + return 0, nil, true, fmt.Errorf("%w: replay unavailable for pack %d", ErrInvalidRequest, pack) + } + replay, active, err := s.state.QuestReplay(ctx, pack) + if err != nil { + return 0, nil, true, err + } + switch { + case active && quest == replay.QuestID && int(level) == replay.Difficulty: + case quest == s.storyCatalog.Packs[pack].MainQuestIDs[0]: + previous, _ := s.state.Selection(pack) + if active { + previous = replay.Previous + } + replay = progress.QuestReplay{QuestID: quest, Difficulty: int(level), Previous: previous} + default: + return 0, nil, true, fmt.Errorf("%w: replay quest %d", ErrInvalidRequest, quest) + } + replay.BattleSkip = skip == 1 + if err := s.state.SaveQuestReplay(ctx, pack, replay); err != nil { + return 0, nil, true, err + } + // The selection carries the replay difficulty to battles and story parties. + if err := s.state.SelectQuest(ctx, pack, progress.QuestSelection{QuestID: quest, Difficulty: replay.Difficulty}); err != nil { + return 0, nil, true, err + } + if err := s.state.SetActivePackID(ctx, pack); err != nil { + return 0, nil, true, err + } + s.setCurrentPack(pack) + chars, decks, err := s.resolveActivePartyWires(ctx, pack, quest) + if err != nil { + return 0, nil, true, err + } + var out []byte + for _, char := range chars { + out = wire.AppendBytes(out, 2, char) + } + for _, deck := range decks { + out = wire.AppendBytes(out, 3, deck) + } + items, err := s.ensureQuestItems(ctx, pack, quest) + if err != nil { + return 0, nil, true, err + } + for _, item := range items { + out = wire.AppendBytes(out, 4, assets.ItemWire(item)) + } + return 17, wire.AppendBytes(out, 5, replayWire(pack, replay)), true, nil +} + +func (s *Service) endQuestReplay(ctx command.Context, pack int, replay progress.QuestReplay) error { + if err := s.state.DeleteQuestReplay(ctx, pack); err != nil { + return err + } + return s.state.SelectQuest(ctx, pack, replay.Previous) +} + +func (s *Service) giveUpQuestReplay(ctx command.Context, pack, quest int, replay progress.QuestReplay) (int, []byte, bool, error) { + if quest != replay.QuestID { + return 0, nil, true, fmt.Errorf("%w: replay quest %d is not active", ErrInvalidRequest, quest) + } + if err := s.endQuestReplay(ctx, pack, replay); err != nil { + return 0, nil, true, err + } + out := s.appendCurrentBattleDeck(wire.AppendVarint(nil, 1, uint64(quest)), 2) + return 20, wire.AppendBytes(out, 5, endedReplayWire(pack)), true, nil +} + +func (s *Service) updateQuestReplay(ctx command.Context, pack int, replay progress.QuestReplay, request []byte) error { + values, err := progress.QuestValues(request) + if err != nil { + return err + } + replay.Values = values + return s.state.SaveQuestReplay(ctx, pack, replay) +} + +func (s *Service) clearQuestReplay(ctx command.Context, pack, quest int, replay progress.QuestReplay) (int, []byte, bool, error) { + if quest != replay.QuestID { + return 0, nil, true, fmt.Errorf("%w: replay quest %d is not active", ErrInvalidRequest, quest) + } + var previousParty []roster.Character + var err error + if s.storyRoster != nil { + if previousParty, err = s.resolveStoryCharacters(ctx, pack, quest); err != nil { + return 0, nil, true, err + } + } + var nextItems []assets.Item + var nextChars [][]byte + retry := endedReplayWire(pack) + if next := s.nextQuestFor(ctx, pack, quest); next != 0 { + replay.QuestID, replay.Values = next, nil + if err = s.state.SaveQuestReplay(ctx, pack, replay); err != nil { + return 0, nil, true, err + } + if err = s.state.SelectQuest(ctx, pack, progress.QuestSelection{QuestID: next, Difficulty: replay.Difficulty}); err != nil { + return 0, nil, true, err + } + if nextChars, _, err = s.resolveActivePartyWires(ctx, pack, next); err != nil { + return 0, nil, true, err + } + if nextChars, err = storyPartyChanges(previousParty, nextChars); err != nil { + return 0, nil, true, err + } + if nextItems, err = s.ensureQuestItems(ctx, pack, next); err != nil { + return 0, nil, true, err + } + retry = replayWire(pack, replay) + } else if err = s.endQuestReplay(ctx, pack, replay); err != nil { + return 0, nil, true, err + } + out, err := s.clearResponse(ctx, pack, quest, nil, nextItems, nextChars) + if err != nil { + return 0, nil, true, err + } + return 18, wire.AppendBytes(out, 16, retry), true, nil +} + +// saveQuestReplayBattleSkip consumes QuestRetryBattleSkipSaveRequest: field 1 +// seq, field 2 pack_id, field 3 is_battle_skip. +func (s *Service) saveQuestReplayBattleSkip(ctx command.Context, request []byte) (int, []byte, bool, error) { + pack, err := requestPack(request) + if err != nil { + return 0, nil, true, err + } + skip, _, err := wire.Varint(request, 3) + if err != nil || skip > 1 { + return 0, nil, true, fmt.Errorf("%w: battle skip flag", ErrInvalidRequest) + } + replay, active, err := s.state.QuestReplay(ctx, pack) + if err != nil { + return 0, nil, true, err + } + if !active { + return 0, nil, true, fmt.Errorf("%w: pack %d is not replaying", ErrInvalidRequest, pack) + } + replay.BattleSkip = skip == 1 + if err := s.state.SaveQuestReplay(ctx, pack, replay); err != nil { + return 0, nil, true, err + } + var out []byte + if replay.BattleSkip { + out = wire.AppendVarint(out, 1, 1) + } + return 654, out, true, nil +} diff --git a/go/internal/server/domain/world/side_quest_chain_test.go b/go/internal/server/domain/world/side_quest_chain_test.go index 2950d18..bd301fb 100644 --- a/go/internal/server/domain/world/side_quest_chain_test.go +++ b/go/internal/server/domain/world/side_quest_chain_test.go @@ -18,6 +18,7 @@ import ( "bd2server/internal/server/domain/world/progress" "bd2server/internal/server/protocol/wire" accountstate "bd2server/internal/server/storage/account" + "bd2server/internal/server/storage/instanceid" "bd2server/internal/server/storage/stateio" ) @@ -47,7 +48,8 @@ func TestForestSideQuestCompletionSurvivesPackEntry(t *testing.T) { if err != nil { t.Fatal(err) } - repo, err := accountstate.Open(filepath.Join(t.TempDir(), "state.db")) + statePath := filepath.Join(t.TempDir(), "state.db") + repo, err := accountstate.Open(statePath) if err != nil { t.Fatal(err) } @@ -63,7 +65,7 @@ func TestForestSideQuestCompletionSurvivesPackEntry(t *testing.T) { t.Fatal(err) } defer func() { _ = tx.Rollback() }() - ctx := command.Context{Identity: command.Identity{AccountID: "forest-side-quest", SessionID: "authenticated"}, State: tx} + ctx := command.Context{Identity: command.Identity{AccountID: "forest-side-quest", SessionID: "authenticated"}, State: tx, InstanceIDs: instanceid.New(filepath.Join(filepath.Dir(statePath), "instance-ids.db"))} state, err := progress.OpenStore(ctx, stateio.RootStore{}) if err != nil { t.Fatal(err) diff --git a/go/internal/server/domain/world/start_pack.go b/go/internal/server/domain/world/start_pack.go index fdea19e..ae5ae22 100644 --- a/go/internal/server/domain/world/start_pack.go +++ b/go/internal/server/domain/world/start_pack.go @@ -43,11 +43,14 @@ func (s *Service) ConfigureStartPack(ctx command.Context, packID int, initialize return fmt.Errorf("world: invalid persisted starting chapter %d", entry) } s.startingPackID = entry - active := s.state.ActivePackID() - if active == 0 { - return fmt.Errorf("world: account has no active chapter") + // Configure the in-memory pack from the same source as LoginUser, so an + // arena without its own saved position cannot make the session start in a + // pack the client will not restore. + active, err := s.LastPlayedPackID(ctx) + if err != nil { + return err } - s.setCurrentPack(active) + s.setCurrentPack(int(active)) return nil } diff --git a/go/internal/server/domain/world/story_characters.go b/go/internal/server/domain/world/story_characters.go index 7a26a1e..d7750f6 100644 --- a/go/internal/server/domain/world/story_characters.go +++ b/go/internal/server/domain/world/story_characters.go @@ -31,6 +31,9 @@ func (s *Service) currentBattleParty(ctx command.Context) ([]roster.Character, e // character and talent UI. Availability is independent of battle selection; // StoryCharGroup supplies cosmetic field actors, not inventory identities. func (s *Service) resolveStoryCharacters(ctx command.Context, packID, questID int) ([]roster.Character, error) { + if packID <= 0 { + return nil, fmt.Errorf("world: invalid story pack") + } if s.storyRoster == nil { return nil, nil } @@ -61,10 +64,10 @@ func (s *Service) resolveStoryCharacters(ctx command.Context, packID, questID in authoredOrder = append(authoredOrder, existing.InvenIndex) continue } - if packID <= 0 || packID >= 65536 || d.CharacterID == 0 || d.CharacterID >= 1<<32 || d.Level == 0 || d.Level >= 256 { - return nil, fmt.Errorf("world: story instance namespace overflow") + index, err := s.characters.StoryCharacterIndex(ctx, uint64(packID), d.CharacterID, d.Level) + if err != nil { + return nil, err } - index := roster.StoryCharacterIndexBase | uint64(packID)<<40 | d.CharacterID<<8 | d.Level authoredOrder = append(authoredOrder, index) temporary = append(temporary, roster.Character{InvenIndex: index, ID: d.CharacterID, HP: d.HP, Level: d.Level, CostumeID: d.CostumeID, TalentLevel: d.InitialTalentLevel}) } diff --git a/go/internal/server/domain/world/story_checkpoint.go b/go/internal/server/domain/world/story_checkpoint.go index db6b56d..8a10ca3 100644 --- a/go/internal/server/domain/world/story_checkpoint.go +++ b/go/internal/server/domain/world/story_checkpoint.go @@ -1,6 +1,7 @@ package world import ( + "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" "encoding/json" "errors" @@ -10,6 +11,12 @@ import ( var ErrStoryCheckpointConflict = errors.New("world: story checkpoint conflict") +func storyCheckpointConflict(pending, requested StoryCheckpoint) error { + return fmt.Errorf("%w: pending={pack=%d quest=%d difficulty=%d phase=%s} requested={pack=%d quest=%d difficulty=%d phase=%s}", + ErrStoryCheckpointConflict, pending.PackID, pending.QuestID, pending.Difficulty, pending.Phase, + requested.PackID, requested.QuestID, requested.Difficulty, requested.Phase) +} + type StoryCheckpoint struct { ID string `json:"checkpoint_id"` PackID int `json:"pack_id"` @@ -93,7 +100,7 @@ func (s *Service) StoryCheckpoint(ctx command.Context, request StoryCheckpointRe if candidate == *pending { return reply, nil } - return reply, ErrStoryCheckpointConflict + return reply, storyCheckpointConflict(*pending, request.StoryCheckpoint) } if err = s.validateStoryCheckpoint(ctx, request.StoryCheckpoint); err != nil { return reply, err @@ -108,6 +115,9 @@ func (s *Service) StoryCheckpoint(ctx command.Context, request StoryCheckpointRe } func (s *Service) validateStoryCheckpoint(ctx command.Context, checkpoint StoryCheckpoint) error { + if field, exists := s.fieldPacks[checkpoint.PackID]; exists && field.IntroQuest != nil { + return s.validateFieldIntroCheckpoint(ctx, checkpoint, field) + } pack, exists := s.storyCatalog.Packs[checkpoint.PackID] if !exists || !s.packUnlocked(ctx, checkpoint.PackID) || checkpoint.Difficulty != s.questDifficultyFor(checkpoint.PackID, checkpoint.QuestID) { return fmt.Errorf("%w: checkpoint pack or difficulty unavailable", ErrInvalidRequest) @@ -153,6 +163,20 @@ func (s *Service) validateStoryCheckpoint(ctx command.Context, checkpoint StoryC return nil } +func (s *Service) validateFieldIntroCheckpoint(ctx command.Context, checkpoint StoryCheckpoint, pack gamedata.FieldPack) error { + intro := pack.IntroQuest + current, err := s.CurrentPackID(ctx) + if err != nil { + return err + } + if current != checkpoint.PackID || !s.packUnlocked(ctx, checkpoint.PackID) || intro == nil || + checkpoint.QuestID != intro.ID || checkpoint.Difficulty != 0 || checkpoint.Phase != "accept" || + checkpoint.Timeline != intro.AcceptCinemaName || checkpoint.ObjectID != 0 || checkpoint.SimpleTalkGroupID != 0 || !pack.MapIDs[checkpoint.MapID] { + return fmt.Errorf("%w: field introduction checkpoint unavailable", ErrInvalidRequest) + } + return nil +} + func (s *Service) beginQuestCompletionPresentation(ctx command.Context, pack, quest, difficulty int) error { design := s.storyCatalog.Packs[pack].Quests[quest] if design.CompleteCinemaName == "" { @@ -171,7 +195,7 @@ func (s *Service) beginQuestCompletionPresentation(ctx command.Context, pack, qu return err } if pending != nil && (pending.PackID != pack || pending.QuestID != quest || pending.Difficulty != difficulty || pending.Phase != "interaction" && pending.Phase != "complete") { - return ErrStoryCheckpointConflict + return storyCheckpointConflict(*pending, checkpoint) } return saveStoryCheckpoint(ctx, checkpoint) } diff --git a/go/internal/server/domain/world/world.go b/go/internal/server/domain/world/world.go index ff63a8b..e69e983 100644 --- a/go/internal/server/domain/world/world.go +++ b/go/internal/server/domain/world/world.go @@ -8,6 +8,7 @@ import ( "bd2server/internal/server/design/gamedata" "bd2server/internal/server/domain/command" assets "bd2server/internal/server/domain/inventory" + "bd2server/internal/server/domain/progression/conditions" "bd2server/internal/server/domain/roster" "bd2server/internal/server/domain/roster/deck" "bd2server/internal/server/domain/world/progress" @@ -155,6 +156,7 @@ type Service struct { packJamDesign *gamedata.PackJamDesign fieldPacks map[int]gamedata.FieldPack + fieldPackEconomy FieldPackEconomy eventFieldPacks EventFieldPackSource fieldObjects map[int]gamedata.FieldObjectDesign fieldObjectLoader func(int) (gamedata.FieldObjectDesign, error) @@ -183,20 +185,22 @@ type Service struct { researchEconomy interface { Apply(ctx command.Context, _ string, _ []gamedata.Reward, _ []gamedata.Reward) ([]byte, error) } - squadLevel func() (uint64, error) - seed Seed - state *progress.Store - starter *roster.Starter - equipment *assets.EquipmentInventory - inventory *assets.Inventory - wallet *assets.Wallet - characters *roster.CharacterStore - collection *roster.CollectionStore - decks *deck.Store - quests map[int]gamedata.QuestDesign - transition gamedata.PackTransition - packs map[int]map[int]gamedata.QuestDesign - transitions map[int]gamedata.PackTransition + squadLevel func() (uint64, error) + missionProgress func(command.Context, conditions.Event) error + seed Seed + state *progress.Store + questBattleWon func(command.Context, int, int, int) (bool, error) + starter *roster.Starter + equipment *assets.EquipmentInventory + inventory *assets.Inventory + wallet *assets.Wallet + characters *roster.CharacterStore + collection *roster.CollectionStore + decks *deck.Store + quests map[int]gamedata.QuestDesign + transition gamedata.PackTransition + packs map[int]map[int]gamedata.QuestDesign + transitions map[int]gamedata.PackTransition activePack int transientVersion uint64 @@ -231,32 +235,25 @@ func (s *Service) AttachDecks(ctx command.Context, decks *deck.Store) error { } func (s *Service) questsFor(ctx command.Context, packID int) (map[int]gamedata.QuestDesign, bool) { - if _, found, err := s.resolveEventFieldPack(ctx, packID); err == nil && found { - return map[int]gamedata.QuestDesign{}, true + pack, err := s.resolvePack(ctx, packID) + if err != nil { + return nil, false + } + if pack.kind == eventCard { + return nil, true } if s.storyCatalog != nil { - pack, found := s.storyCatalog.Packs[packID] - if found { - return pack.Quests, true + if story, found := s.storyCatalog.Packs[packID]; found { + return story.Quests, true } } - if _, exists := s.fieldPacks[packID]; exists { - return map[int]gamedata.QuestDesign{}, true - } - return nil, false + return nil, true } // packUnlocked uses installed ContentOpen rules and real account tickets. func (s *Service) packUnlocked(ctx command.Context, packID int) bool { - if pack, found, err := s.resolveEventFieldPack(ctx, packID); err != nil { - return false - } else if found { - return s.eventPackPurchased(pack.ID) - } - if pack, exists := s.fieldPacks[packID]; exists { - return s.fieldPackUnlocked(ctx, pack) - } - return s.storyCatalog != nil && s.storyPackUnlocked(ctx, packID) + pack, err := s.resolvePack(ctx, packID) + return err == nil && s.packAccessible(ctx, pack) } func (s *Service) canClear(ctx command.Context, packID, quest int) bool { diff --git a/go/internal/server/gateway/realtime/server.go b/go/internal/server/gateway/realtime/server.go index 460a963..a0d1584 100644 --- a/go/internal/server/gateway/realtime/server.go +++ b/go/internal/server/gateway/realtime/server.go @@ -283,7 +283,7 @@ func (s *Server) serveConnection(socket net.Conn) { if decoder.Decode(new(any)) != io.EOF { return } - if auth.Channel != string(room.Matching) && auth.Channel != string(room.Action) && auth.Channel != string(room.Defense) && auth.Channel != string(room.Fishing) { + if auth.Channel != string(room.Matching) && auth.Channel != string(room.Action) && auth.Channel != string(room.Defense) && auth.Channel != string(room.Fishing) && auth.Channel != string(room.Square) { return } principal, release, e := s.tickets.Consume(handshake, auth.Ticket, auth.Channel, auth.InstanceID) @@ -382,6 +382,12 @@ func (s *Server) serveConnection(socket net.Conn) { return } first = false + if s.tickets.Validate(c.ctx, c.native.Principal) != nil { + return + } + if activity, ok := s.tickets.(interface{ RecordActivity(room.Principal) }); ok { + activity.RecordActivity(c.native.Principal) + } d, e := s.rooms.Handle(c.ctx, c.native, f) if e != nil { slog.Warn("native realtime packet rejected", "channel", c.native.Channel, "account_id", c.native.Principal.AccountID, "frame_type", f.Type, "reason", e.Error()) diff --git a/go/internal/server/gateway/realtime/server_test.go b/go/internal/server/gateway/realtime/server_test.go index 413791e..745c0a6 100644 --- a/go/internal/server/gateway/realtime/server_test.go +++ b/go/internal/server/gateway/realtime/server_test.go @@ -29,7 +29,7 @@ import ( type integrationRules struct{} func (integrationRules) Profile(_ context.Context, p room.Principal) (room.Profile, error) { - return room.Profile{UserInfo: wire.AppendVarint(nil, 1, uint64(p.OwnerIndex))}, nil + return room.Profile{UserInfo: wire.AppendVarint(nil, 1, uint64(p.OwnerIndex)), SquareUnlocked: true}, nil } func (integrationRules) ValidateSelection(_ room.Profile, s room.Selection) (room.Selection, error) { s.Capacity = 1 @@ -42,9 +42,17 @@ type integrationTickets struct { used map[string]bool p room.Principal instance string + revoked bool } -func (t *integrationTickets) Validate(context.Context, room.Principal) error { return nil } +func (t *integrationTickets) Validate(context.Context, room.Principal) error { + t.mu.Lock() + defer t.mu.Unlock() + if t.revoked { + return room.ErrUnauthorized + } + return nil +} func (t *integrationTickets) Consume(_ context.Context, token, channel, instance string) (room.Principal, func(), error) { t.mu.Lock() defer t.mu.Unlock() @@ -60,7 +68,7 @@ func TestNativeTCPHandshakeMatchingAndEntry(t *testing.T) { defer cancel() results := make(chan room.FinalResult, 1) var s *Server - m, err := room.New(room.Config{AdvertisedHost: "127.0.0.1", TCPPort: 9000, + m, err := room.New(room.Config{AdvertisedHost: "127.0.0.1", TCPPort: 9000, SquareChannels: 35, SquareChannelCapacity: 100, PublishResult: func(result room.FinalResult) bool { results <- result; return true }, Publish: func(d []room.Delivery) { s.Deliver(d) }, }, integrationRules{}) @@ -153,6 +161,48 @@ func TestNativeTCPHandshakeMatchingAndEntry(t *testing.T) { return socket } matching := connect("matching", "boot") + // 2.37.13 NetworkContext first queries channels on Chat, then opens Field. + for _, typ := range []int32{142, 205} { + if e := writeAll(matching, EncodeFrame(room.Frame{Type: typ, Sequence: 17, OwnerIndex: 91})); e != nil { + t.Fatal(e) + } + reply, e := ReadFrame(matching, 4096) + if e != nil || reply.Type != typ+1 || reply.Sequence != 17 { + t.Fatalf("square matching reply %+v %v", reply, e) + } + if typ == 142 { + count, _, _ := wire.Varint(reply.Payload, 3) + if count != 35 { + t.Fatal("native channel directory omitted configured maximum") + } + continue + } + code, _, _ := wire.Bytes(reply.Payload, 2) + guid, _, _ := wire.Bytes(reply.Payload, 6) + view, e := m.View(ctx, tickets.p, room.Square) + if e != nil || len(code) == 0 || len(guid) == 0 { + t.Fatalf("square assignment lacks membership: %v", e) + } + field := connect("square", view.InstanceID) + for _, req := range []room.Frame{ + {Type: 23, Sequence: 18, OwnerIndex: 91, Payload: wire.AppendBytes(nil, 2, code)}, + {Type: 126, Sequence: 19, OwnerIndex: 91, Payload: wire.AppendBytes(wire.AppendBytes(wire.AppendBytes(nil, 2, guid), 3, code), 4, wire.AppendVarint(nil, 1, 91))}, + } { + if e := writeAll(field, EncodeFrame(req)); e != nil { + t.Fatal(e) + } + reply, e := ReadFrame(field, 4096) + if e != nil || reply.Type != req.Type+1 || reply.Sequence != req.Sequence { + t.Fatalf("square relay entry reply %+v %v", reply, e) + } + } + if e := writeAll(matching, EncodeFrame(room.Frame{Type: 1, Sequence: 20, OwnerIndex: 91})); e != nil { + t.Fatal(e) + } + if reply, e := ReadFrame(matching, 4096); e != nil || reply.Type != 2 { + t.Fatalf("channel query/entry broke the shared matching connection: %+v %v", reply, e) + } + } request := wire.AppendVarint(wire.AppendVarint(nil, 4, 4), 5, 1) if err = writeAll(matching, EncodeFrame(room.Frame{Type: 82, Sequence: 2, OwnerIndex: 91, Payload: request})); err != nil { t.Fatal(err) @@ -243,6 +293,16 @@ func TestNativeTCPHandshakeMatchingAndEntry(t *testing.T) { if !errors.Is(err, io.EOF) && !errors.Is(err, syscall.ECONNRESET) { t.Fatalf("forged owner header did not close the authenticated connection: %v", err) } + tickets.mu.Lock() + tickets.revoked = true + tickets.mu.Unlock() + if err = writeAll(matching, EncodeFrame(room.Frame{Type: 1, Sequence: 21, OwnerIndex: 91})); err != nil { + t.Fatal(err) + } + _, err = ReadFrame(matching, 4096) + if !errors.Is(err, io.EOF) && !errors.Is(err, syscall.ECONNRESET) { + t.Fatalf("revoked login could still issue realtime commands before the validation timer: %v", err) + } } type blockedUDPRooms struct { diff --git a/go/internal/server/gateway/session/presence_test.go b/go/internal/server/gateway/session/presence_test.go new file mode 100644 index 0000000..651ab76 --- /dev/null +++ b/go/internal/server/gateway/session/presence_test.go @@ -0,0 +1,86 @@ +package session + +import ( + "context" + "errors" + "testing" + "time" + + "bd2server/internal/server/gateway/transport" + "bd2server/internal/server/runtime/player" +) + +type presenceExecutor struct{} + +func (presenceExecutor) Execute(context.Context, player.Command) (player.Reply, error) { + return player.Reply{}, nil +} +func (presenceExecutor) Recover(context.Context) error { return nil } +func (presenceExecutor) Close() error { return nil } + +type presenceRouter struct{ runtime *player.Runtime } + +func (r presenceRouter) Acquire(context.Context, string) (*player.Runtime, func(), error) { + return r.runtime, func() {}, nil +} + +func TestPresenceExpiresWithoutActivityAndOnlyValidSessionsRenewIt(t *testing.T) { + ctx := context.Background() + runtime, err := player.New("present-player", presenceExecutor{}, player.Limits{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = runtime.Close(ctx) }) + server, err := NewServer(presenceRouter{runtime}, nil) + if err != nil { + t.Fatal(err) + } + now := time.Date(2026, 10, 23, 12, 0, 0, 0, time.UTC) + server.now = func() time.Time { return now } + game, token, err := newGameSession("present-player", now, 24*time.Hour) + if err != nil { + t.Fatal(err) + } + game.generation = runtime.Generation() + server.sessions[sessionTokenKey(token)] = game + if !server.AccountOnline("present-player") || server.AccountOnline("another-player") { + t.Fatal("presence leaked across accounts or missed authenticated activity") + } + now = now.Add(91 * time.Second) + if server.AccountOnline("present-player") { + t.Fatal("unexpired login cookie incorrectly kept disconnected player online") + } + invalid := Principal{AccountID: game.accountID, SessionID: game.id, Generation: game.generation + 1} + if err := server.ValidatePrincipal(ctx, invalid); !errors.Is(err, transport.ErrGameSessionExpired) { + t.Fatalf("stale principal accepted: %v", err) + } + if server.AccountOnline("present-player") { + t.Fatal("invalid relay principal renewed presence") + } + valid := Principal{AccountID: game.accountID, SessionID: game.id, Generation: game.generation} + if err := server.ValidatePrincipal(ctx, valid); err != nil { + t.Fatal(err) + } + if server.AccountOnline("present-player") { + t.Fatal("server-side periodic credential checks incorrectly renewed presence") + } + server.RecordActivity(invalid) + if server.AccountOnline("present-player") { + t.Fatal("stale relay principal recorded activity") + } + server.RecordActivity(valid) + if !server.AccountOnline("present-player") { + t.Fatal("valid native heartbeat did not renew online presence") + } + now = now.Add(91 * time.Second) + if _, err := server.Principal(ctx, "s="+token); err != nil { + t.Fatal(err) + } + if !server.AccountOnline("present-player") { + t.Fatal("authenticated HTTP activity did not renew presence") + } + now = game.expiresAt + if server.AccountOnline("present-player") { + t.Fatal("expired game session retained presence") + } +} diff --git a/go/internal/server/gateway/session/principal.go b/go/internal/server/gateway/session/principal.go index cbdfb79..cf5e665 100644 --- a/go/internal/server/gateway/session/principal.go +++ b/go/internal/server/gateway/session/principal.go @@ -3,6 +3,7 @@ package session import ( "context" "errors" + "time" "bd2server/internal/server/gateway/transport" ) @@ -47,6 +48,34 @@ func (s *Server) ValidatePrincipal(ctx context.Context, p Principal) error { return nil } +func (s *Server) RecordActivity(p Principal) { + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + for _, game := range s.sessions { + if game.accountID == p.AccountID && game.id == p.SessionID && game.generation == p.Generation && now.Before(game.expiresAt) { + game.lastUsed = now + return + } + } +} + +const presenceActivityWindow = 90 * time.Second + +// AccountOnline uses authenticated HTTP activity and native relay heartbeats; +// an idle session cookie alone does not keep a disconnected player online. +func (s *Server) AccountOnline(account string) bool { + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + for _, game := range s.sessions { + if game.accountID == account && now.Before(game.expiresAt) && now.Sub(game.lastUsed) < presenceActivityWindow { + return true + } + } + return false +} + func (s *Server) containsPrincipal(p Principal) bool { s.mu.Lock() defer s.mu.Unlock() diff --git a/go/internal/server/gateway/session/server.go b/go/internal/server/gateway/session/server.go index c5039ea..06734cf 100644 --- a/go/internal/server/gateway/session/server.go +++ b/go/internal/server/gateway/session/server.go @@ -16,6 +16,7 @@ import ( "encoding/json" "errors" "fmt" + "log/slog" "strings" "sync" "time" @@ -119,6 +120,8 @@ func (s *Server) dispatchRaw(ctx context.Context, path string, body []byte, cook if err != nil { if path != "/BatchRequest" { if rejection, handled, encodeErr := s.gameErrorReply(game, err); handled { + timing.rejected = true + slog.WarnContext(ctx, "session game request rejected", "path", path, "error", rejectedRequestError(game.accountID, requests, err)) return rejection, encodeErr } } diff --git a/go/internal/server/gateway/session/timing.go b/go/internal/server/gateway/session/timing.go index 9276411..7f76dff 100644 --- a/go/internal/server/gateway/session/timing.go +++ b/go/internal/server/gateway/session/timing.go @@ -9,6 +9,7 @@ type requestTiming struct { queue, decode, auth, execute, observer time.Duration begin, commit, rollback, encode time.Duration items int + rejected bool } func (t *requestTiming) log(path string, total time.Duration, responseBytes int, err error, completed bool) { @@ -17,6 +18,8 @@ func (t *requestTiming) log(path string, total time.Duration, responseBytes int, status = "panic" } else if err != nil { status = "error" + } else if t.rejected { + status = "rejected" } other := total - t.queue - t.decode - t.auth - t.execute - t.observer - t.begin - t.commit - t.rollback - t.encode slog.Info("session request phases", "path", path, "status", status, diff --git a/go/internal/server/runtime/room/gameplay.go b/go/internal/server/runtime/room/gameplay.go index 34ba0af..d74478f 100644 --- a/go/internal/server/runtime/room/gameplay.go +++ b/go/internal/server/runtime/room/gameplay.go @@ -584,6 +584,12 @@ func (s *state) relay(c Connection, f Frame, u *member) ([]Delivery, error) { } else { return nil, ErrUnauthorized } + case Square: + if innerType < 9002 || innerType > 9007 || number(payload, 1) != u.principal.OwnerIndex || len(payload) > 2048 { + return nil, ErrUnauthorized + } + default: + return nil, ErrUnauthorized } b := integer(nil, 2, u.principal.OwnerIndex) b = blob(b, 3, data) diff --git a/go/internal/server/runtime/room/manager.go b/go/internal/server/runtime/room/manager.go index c4f00a2..a68f684 100644 --- a/go/internal/server/runtime/room/manager.go +++ b/go/internal/server/runtime/room/manager.go @@ -16,6 +16,7 @@ type Manager struct { config Config rules Rules mu sync.Mutex + squareJoinMu sync.Mutex rooms map[string]*owner instances map[string]*owner memberships map[string]string @@ -65,6 +66,7 @@ type member struct { playerSnapshot []byte fishingState []byte fishingMotion []byte + squareMotion []byte runGUID string acceptedRun bool projectionEvents []string @@ -101,6 +103,9 @@ func New(config Config, rules Rules) (*Manager, error) { if config.MaxRooms <= 0 { config.MaxRooms = 1024 } + if config.SquareChannels < 0 || config.SquareChannels > 10000 || config.SquareChannelCapacity < 0 || config.SquareChannelCapacity > 1000 || (config.SquareChannels == 0) != (config.SquareChannelCapacity == 0) { + return nil, errors.New("room: invalid square channel design") + } if config.QueueCommands <= 0 { config.QueueCommands = 256 } @@ -297,6 +302,7 @@ func cloneView(v View) View { for i := range v.Members { v.Members[i].Profile.UserInfo = append([]byte(nil), v.Members[i].Profile.UserInfo...) v.Members[i].Profile.AvatarUseInfo = append([]byte(nil), v.Members[i].Profile.AvatarUseInfo...) + v.Members[i].Profile.AvatarMotions = append([]uint64(nil), v.Members[i].Profile.AvatarMotions...) v.Members[i].Profile.FishingMaps = append([]uint64(nil), v.Members[i].Profile.FishingMaps...) } return v @@ -464,7 +470,7 @@ func (m *Manager) UpdateFishingProjection(ctx context.Context, p Principal, prof } func (m *Manager) Disconnect(ctx context.Context, c Connection) ([]Delivery, error) { var all []Delivery - for _, k := range []Kind{Action, Defense, Fishing} { + for _, k := range []Kind{Action, Defense, Fishing, Square} { o := m.lookup(c.Principal, k) if o == nil { continue @@ -484,6 +490,9 @@ func (m *Manager) Disconnect(ctx context.Context, c Connection) ([]Delivery, err u.gameConnection = "" u.disconnected = m.config.Now() u.networkState = 0 + if k == Square { + return nil, s.broadcast(131, integer(nil, 2, u.principal.OwnerIndex), false, u.principal.OwnerIndex), nil + } return nil, s.chooseHost(), nil } return nil, nil, nil @@ -518,6 +527,7 @@ func (s *state) view() View { p := u.profile p.UserInfo = append([]byte(nil), p.UserInfo...) p.AvatarUseInfo = append([]byte(nil), p.AvatarUseInfo...) + p.AvatarMotions = append([]uint64(nil), p.AvatarMotions...) p.FishingMaps = append([]uint64(nil), p.FishingMaps...) v.Members = append(v.Members, MemberView{Principal: u.principal, Profile: p, CharacterID: u.character, Ready: u.ready, ClientState: u.clientState, Connected: u.gameConnection != "", RunGUID: u.runGUID, AcceptedRun: u.acceptedRun, NativeGUID: u.guid, Wave: u.wave, Kills: u.kills}) } @@ -544,6 +554,14 @@ func (s *state) chooseHost() []Delivery { return nil } func (s *state) expire(now time.Time) []Delivery { + if s.selection.Kind == Square { + for _, u := range append([]*member(nil), s.members...) { + if !u.disconnected.IsZero() && now.Sub(u.disconnected) > s.reconnectWindow() { + s.leaveSquare(u) + } + } + return nil + } var d []Delivery if s.roomState == 0 && now.Sub(s.created) >= s.owner.manager.config.MatchingLimit { s.closed = true @@ -605,7 +623,7 @@ func (m *Manager) checkConnection(c Connection) error { if !validPrincipal(c.Principal) || c.ID == "" { return ErrUnauthorized } - if c.Channel != Matching && c.Channel != Action && c.Channel != Defense && c.Channel != Fishing { + if c.Channel != Matching && c.Channel != Action && c.Channel != Defense && c.Channel != Fishing && c.Channel != Square { return ErrUnauthorized } m.mu.Lock() diff --git a/go/internal/server/runtime/room/protocol.go b/go/internal/server/runtime/room/protocol.go index 6240f39..78f8167 100644 --- a/go/internal/server/runtime/room/protocol.go +++ b/go/internal/server/runtime/room/protocol.go @@ -164,6 +164,9 @@ func (m *Manager) Handle(ctx context.Context, c Connection, f Frame) (deliveries code = 3 case errors.Is(err, ErrNotReady): code = 6 + if f.Type == 185 { + code = 10 + } case errors.Is(err, ErrMailboxFull): code = 8 } @@ -196,7 +199,7 @@ func (m *Manager) Handle(ctx context.Context, c Connection, f Frame) (deliveries return []Delivery{{c.ID, Frame{Type: 173, Sequence: f.Sequence, OwnerIndex: c.Principal.OwnerIndex, Payload: message(m.config.Now(), 2, nil)}}}, nil } } - if c.Channel == Fishing && (f.Type == 70 || f.Type == 72) { + if (c.Channel == Fishing || c.Channel == Square) && (f.Type == 70 || f.Type == 72) { field := 3 if f.Type == 72 { field = 4 @@ -212,6 +215,12 @@ func (m *Manager) Handle(ctx context.Context, c Connection, f Frame) (deliveries body := message(m.config.Now(), 0, nil) return []Delivery{{c.ID, Frame{Type: f.Type + 1, Sequence: f.Sequence, OwnerIndex: c.Principal.OwnerIndex, Payload: body}}}, nil } + if c.Channel == Matching && (f.Type == 142 || f.Type == 124 || f.Type == 205) { + return m.handleSquareChannel(ctx, c, f) + } + if c.Channel == Square { + return m.handleSquare(ctx, c, f) + } if c.Channel == Matching { if f.UDP { return nil, ErrUnauthorized @@ -259,6 +268,8 @@ func responseType(typ int32) int32 { switch typ { case 23, 25, 32, 34, 37, 43, 52, 55, 64, 66, 68, 74, 76, 78, 80, 82, 84, 87, 90, 93, 95, 97, 102, 104, 109, 114, 117, 120, 149, 151, 153, 155, 157, 169, 172, 192, 195, 198, 201, 212, 215, 217, 219: return typ + 1 + case 124, 126, 129, 137, 140, 142, 144, 147, 182, 185, 205: + return typ + 1 } return 0 } diff --git a/go/internal/server/runtime/room/square.go b/go/internal/server/runtime/room/square.go new file mode 100644 index 0000000..fc61bf9 --- /dev/null +++ b/go/internal/server/runtime/room/square.go @@ -0,0 +1,335 @@ +package room + +import ( + "context" + "fmt" + "slices" + "time" + + "bd2server/internal/server/protocol/wire" +) + +func (m *Manager) handleSquareChannel(ctx context.Context, c Connection, f Frame) ([]Delivery, error) { + if f.UDP || len(f.Payload) > 4096 { + return nil, ErrUnauthorized + } + reply := func(body []byte, code int64) []Delivery { + return []Delivery{{c.ID, Frame{Type: f.Type + 1, Sequence: f.Sequence, OwnerIndex: c.Principal.OwnerIndex, Payload: message(m.config.Now(), code, body)}}} + } + if m.config.SquareChannels == 0 { + return reply(nil, 13), nil + } + if f.Type == 142 { + body := integer(nil, 3, int64(m.config.SquareChannels)) + m.mu.Lock() + for channel := 1; channel <= m.config.SquareChannels; channel++ { + if o := m.rooms[squareCode(channel)]; o != nil { + v := o.projection.Load() + if v != nil && len(v.Members) > 0 { + body = blob(body, 2, integer(integer(nil, 1, int64(channel)), 2, int64(len(v.Members)))) + } + } + } + m.mu.Unlock() + return reply(body, 0), nil + } + profile, err := m.rules.Profile(ctx, c.Principal) + if err != nil { + return nil, err + } + if number(profile.UserInfo, 1) != c.Principal.OwnerIndex || !profile.SquareUnlocked { + return nil, ErrUnauthorized + } + m.squareJoinMu.Lock() + defer m.squareJoinMu.Unlock() + channel := int(number(f.Payload, 2)) + previous := m.lookup(c.Principal, Square) + if f.Type == 205 { + if previous != nil { + channel = int(previous.projection.Load().Selection.SquareChannel) + } else { + m.mu.Lock() + for id := 1; id <= m.config.SquareChannels; id++ { + o := m.rooms[squareCode(id)] + if o == nil || len(o.projection.Load().Members) < m.config.SquareChannelCapacity { + channel = id + break + } + } + m.mu.Unlock() + } + } + if f.Type == 205 && channel == 0 { + return reply(nil, 11), nil + } + if channel < 1 || channel > m.config.SquareChannels { + return reply(nil, 2), nil + } + m.mu.Lock() + o := m.rooms[squareCode(channel)] + if o == nil && !m.closed && len(m.rooms) < m.config.MaxRooms { + o = &owner{manager: m, code: squareCode(channel), queue: make(chan operation, m.config.QueueCommands), done: make(chan struct{}), stop: make(chan struct{})} + o.state = &state{owner: o, selection: Selection{Kind: Square, SquareChannel: int64(channel), Capacity: m.config.SquareChannelCapacity}, instance: randomID(), roomState: 2, sequences: map[string]int64{}, created: m.config.Now()} + o.publishView() + m.rooms[o.code] = o + m.instances[o.state.instance] = o + m.wg.Add(1) + go o.run() + } + m.mu.Unlock() + if o == nil { + return reply(nil, 8), nil + } + if previous != o && len(o.projection.Load().Members) >= m.config.SquareChannelCapacity { + return reply(nil, 11), nil + } + var deliveries []Delivery + if previous != nil { + _, d, err := previous.submit(ctx, 0, func(s *state) (any, []Delivery, error) { + u := s.find(c.Principal) + if u == nil { + u = s.byOwner(c.Principal.OwnerIndex) + if u == nil || u.principal.AccountID != c.Principal.AccountID || u.principal.Generation > c.Principal.Generation { + return nil, nil, ErrUnauthorized + } + return nil, s.leaveSquare(u), nil + } + if previous == o { + return nil, nil, nil + } + return nil, s.leaveSquare(u), nil + }) + if err != nil { + return nil, err + } + deliveries = append(deliveries, d...) + } + _, d, err := o.submit(ctx, 0, func(s *state) (any, []Delivery, error) { + u := s.find(c.Principal) + if u == nil { + if s.byOwner(c.Principal.OwnerIndex) != nil { + return nil, nil, ErrUnauthorized + } + if len(s.members) >= s.selection.Capacity { + return nil, reply(nil, 11), nil + } + u = &member{principal: c.Principal, profile: profile, guid: randomID(), entered: m.config.Now(), disconnected: m.config.Now()} + s.members = append(s.members, u) + } + u.matchingConnection = c.ID + u.profile = profile + m.mu.Lock() + m.memberships[memberKey(c.Principal, Square)] = o.code + m.mu.Unlock() + body := s.endpoint(text(nil, 2, o.code), 3, 4, 5) + body = text(body, 6, u.guid) + body = integer(body, 7, s.selection.SquareChannel) + return nil, reply(body, 0), nil + }) + return append(deliveries, d...), err +} + +func squareCode(channel int) string { return fmt.Sprintf("square:%d", channel) } + +func (s *state) leaveSquare(u *member) []Delivery { + d := s.broadcast(131, integer(nil, 2, u.principal.OwnerIndex), false, u.principal.OwnerIndex) + for i, candidate := range s.members { + if candidate == u { + s.members = append(s.members[:i], s.members[i+1:]...) + break + } + } + s.owner.manager.mu.Lock() + delete(s.owner.manager.memberships, memberKey(u.principal, Square)) + s.owner.manager.mu.Unlock() + return d +} + +func squareAvatarUse(u *member) []byte { + return integer(removeField(u.profile.AvatarUseInfo, 1), 1, u.principal.OwnerIndex) +} + +func squareEnterUser(u *member) []byte { + body := blob(nil, 1, u.playerSnapshot) + if len(u.squareMotion) > 0 { + body = blob(body, 2, u.squareMotion) + } + body = blob(body, 3, u.profile.UserInfo) + return blob(body, 4, squareAvatarUse(u)) +} + +func (s *state) squareSnapshot(reconnect bool) []byte { + stateField, enterField := 2, 3 + var body []byte + if reconnect { + body = integer(integer(nil, 2, 2), 3, 2) + stateField, enterField = 4, 5 + } + for _, u := range s.members { + if u.gameConnection == "" || !u.ready { + continue + } + body = blob(body, stateField, u.playerSnapshot) + body = blob(body, enterField, squareEnterUser(u)) + } + return body +} + +func squareState(raw []byte, owner int64) ([]byte, error) { + if len(raw) == 0 || len(raw) > 4096 { + return nil, ErrUnauthorized + } + if err := wire.Walk(raw, func(wire.Field) error { return nil }); err != nil { + return nil, err + } + if id := number(raw, 1); id != 0 && id != owner { + return nil, ErrUnauthorized + } + return integer(removeField(raw, 1), 1, owner), nil +} + +func (m *Manager) handleSquare(ctx context.Context, c Connection, f Frame) ([]Delivery, error) { + if f.UDP || len(f.Payload) > 65536 { + return nil, ErrUnauthorized + } + o := m.lookup(c.Principal, Square) + if o == nil { + return nil, ErrNotFound + } + var profile Profile + if f.Type == 140 || f.Type == 147 || f.Type == 182 { + var err error + profile, err = m.rules.Profile(ctx, c.Principal) + if err != nil { + return nil, err + } + if number(profile.UserInfo, 1) != c.Principal.OwnerIndex { + return nil, ErrUnauthorized + } + } + _, deliveries, err := o.submit(ctx, int64(len(f.Payload)), func(s *state) (any, []Delivery, error) { + u := s.find(c.Principal) + if u == nil { + return nil, nil, ErrUnauthorized + } + if f.Type == 23 || f.Type == 185 { + if f.Type == 23 && stringField(f.Payload, 2) != o.code || f.Type == 185 && stringField(f.Payload, 2) != u.guid { + return nil, nil, ErrUnauthorized + } + if !u.disconnected.IsZero() && m.config.Now().Sub(u.disconnected) > s.reconnectWindow() { + return nil, nil, ErrNotReady + } + if f.Type == 185 && !u.ready { + return nil, nil, ErrNotReady + } + u.gameConnection = c.ID + u.disconnected = time.Time{} + if f.Type == 23 { + return nil, []Delivery{s.reply(c, f, 24, text(s.endpoint(nil, 2, 3, 0), 4, u.guid), 0)}, nil + } + d := []Delivery{s.reply(c, f, 186, s.squareSnapshot(true), 0)} + return nil, append(d, s.broadcast(128, blob(nil, 2, squareEnterUser(u)), false, u.principal.OwnerIndex)...), nil + } + if u.gameConnection != c.ID { + return nil, nil, ErrUnauthorized + } + if f.Type == 126 { + if stringField(f.Payload, 2) != u.guid || stringField(f.Payload, 3) != o.code { + return nil, nil, ErrUnauthorized + } + state, err := squareState(bytesField(f.Payload, 4), u.principal.OwnerIndex) + if err != nil { + return nil, nil, err + } + wasReady := u.ready + u.playerSnapshot, u.ready, u.clientState = state, true, 2 + d := []Delivery{s.reply(c, f, 127, s.squareSnapshot(false), 0)} + if !wasReady { + d = append(d, s.broadcast(128, blob(nil, 2, squareEnterUser(u)), false, u.principal.OwnerIndex)...) + } + return nil, d, nil + } + if !u.ready { + return nil, nil, ErrNotReady + } + switch f.Type { + case 122, 175: + if stringField(f.Payload, 2) != u.guid { + return nil, nil, ErrUnauthorized + } + state, err := squareState(bytesField(f.Payload, 3), u.principal.OwnerIndex) + if err != nil { + return nil, nil, err + } + u.playerSnapshot = state + typ := int32(123) + if f.Type == 175 { + typ = 176 + if number(f.Payload, 4) == 0 { + return nil, nil, nil + } + } + return nil, s.broadcast(typ, blob(nil, 2, state), false, u.principal.OwnerIndex), nil + case 129: + if stringField(f.Payload, 2) != u.guid { + return nil, nil, ErrUnauthorized + } + return nil, append([]Delivery{s.reply(c, f, 130, nil, 0)}, s.leaveSquare(u)...), nil + case 137: + if stringField(f.Payload, 2) != o.code { + return nil, nil, ErrUnauthorized + } + var body []byte + for _, member := range s.members { + if member.ready && member.gameConnection != "" { + body = blob(body, 2, squareAvatarUse(member)) + } + } + return nil, []Delivery{s.reply(c, f, 138, body, 0)}, nil + case 140: + u.profile = profile + d := []Delivery{s.reply(c, f, 141, nil, 0)} + return nil, append(d, s.broadcast(139, blob(nil, 2, squareAvatarUse(u)), false, 0)...), nil + case 144: + motion := bytesField(f.Payload, 2) + id := number(motion, 1) + if len(motion) > 256 || id < 0 || id != 0 && !slices.Contains(u.profile.AvatarMotions, uint64(id)) { + return nil, nil, ErrUnauthorized + } + if err := wire.Walk(motion, func(wire.Field) error { return nil }); err != nil { + return nil, nil, err + } + motion = integer(integer(nil, 1, id), 2, ticks(m.config.Now())) + u.squareMotion = append([]byte(nil), motion...) + d := []Delivery{s.reply(c, f, 145, nil, 0)} + body := blob(integer(nil, 2, u.principal.OwnerIndex), 3, motion) + return nil, append(d, s.broadcast(146, body, false, u.principal.OwnerIndex)...), nil + case 147: + u.profile = profile + return nil, []Delivery{s.reply(c, f, 148, nil, 0)}, nil + case 182: + u.profile = profile + d := []Delivery{s.reply(c, f, 183, nil, 0)} + header := blob(integer(nil, 1, m.config.Now().Unix()), 3, profile.UserInfo) + for _, member := range s.members { + if member.gameConnection != "" && member != u { + d = append(d, Delivery{member.gameConnection, Frame{Type: 184, OwnerIndex: member.principal.OwnerIndex, Payload: blob(nil, 1, header)}}) + } + } + return nil, d, nil + case 66, 68: + if stringField(f.Payload, 2) != u.guid { + return nil, nil, ErrUnauthorized + } + return nil, []Delivery{s.reply(c, f, f.Type+1, integer(nil, 2, number(f.Payload, 3)), 0)}, nil + case 70, 72: + if stringField(f.Payload, 2) != u.guid { + return nil, nil, ErrUnauthorized + } + d, err := s.relay(c, f, u) + return nil, d, err + } + return nil, nil, ErrUnauthorized + }) + return deliveries, err +} diff --git a/go/internal/server/runtime/room/square_test.go b/go/internal/server/runtime/room/square_test.go new file mode 100644 index 0000000..afb3f45 --- /dev/null +++ b/go/internal/server/runtime/room/square_test.go @@ -0,0 +1,243 @@ +package room + +import ( + "context" + "encoding/binary" + "errors" + "sync/atomic" + "testing" + "time" +) + +type squareRules struct{ testRules } + +func (squareRules) Profile(_ context.Context, p Principal) (Profile, error) { + return Profile{UserInfo: text(integer(nil, 1, p.OwnerIndex), 4, p.AccountID), AvatarUseInfo: integer(integer(nil, 1, p.OwnerIndex), 2, 3), AvatarMotions: []uint64{7}, SquareUnlocked: p.AccountID != "locked"}, nil +} + +func squareManager(t *testing.T, capacity int) (*Manager, *atomic.Int64) { + t.Helper() + clock := new(atomic.Int64) + clock.Store(time.Now().UnixNano()) + m, err := New(Config{AdvertisedHost: "127.0.0.1", TCPPort: 9000, SquareChannels: 2, SquareChannelCapacity: capacity, + Now: func() time.Time { return time.Unix(0, clock.Load()) }}, squareRules{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = m.Close(context.Background()) }) + return m, clock +} + +// 2.37.13 NetworkContext requests 142, then 205, then relay 23 and 126. +// ENetMsg and CSSquare* generated fields define these independent wire expectations. +func squareRequest(t *testing.T, m *Manager, c Connection, typ int32, payload []byte) []Delivery { + t.Helper() + d, err := m.Handle(context.Background(), c, Frame{Type: typ, Sequence: 19, OwnerIndex: c.Principal.OwnerIndex, Payload: payload}) + if err != nil { + t.Fatalf("native square packet %d: %v", typ, err) + } + return d +} + +func squareJoin(t *testing.T, m *Manager, account string, owner int64) (Connection, string, string) { + t.Helper() + c := Connection{ID: "matching-" + account, Channel: Matching, Principal: Principal{AccountID: account, OwnerIndex: owner, SessionID: "session-" + account, Generation: 1}} + d := squareRequest(t, m, c, 205, nil) + if len(d) != 1 || d[0].Frame.Type != 206 || number(bytesField(d[0].Frame.Payload, 1), 2) != 0 { + t.Fatalf("automatic channel assignment: %+v", d) + } + room, guid := stringField(d[0].Frame.Payload, 2), stringField(d[0].Frame.Payload, 6) + if room == "" || guid == "" || stringField(d[0].Frame.Payload, 3) != "127.0.0.1" || stringField(d[0].Frame.Payload, 4) != "9000" { + t.Fatal("channel assignment omitted the usable relay endpoint or membership GUID") + } + c.ID, c.Channel = "relay-"+account, Square + squareRequest(t, m, c, 23, text(nil, 2, room)) + return c, room, guid +} + +func squareEnter(t *testing.T, m *Manager, c Connection, room, guid string) []Delivery { + t.Helper() + state := blob(integer(nil, 1, c.Principal.OwnerIndex), 2, integer(nil, 1, 4)) + return squareRequest(t, m, c, 126, blob(text(text(nil, 2, guid), 3, room), 4, state)) +} + +func TestSquareNativeEntryPresenceAndStateAuthority(t *testing.T) { + m, _ := squareManager(t, 2) + a, code, ga := squareJoin(t, m, "alice", 11) + initial := squareEnter(t, m, a, code, ga) + if len(initial) != 1 || initial[0].Frame.Type != 127 || len(repeated(initial[0].Frame.Payload, 3)) != 1 { + t.Fatalf("first entrant snapshot: %+v", initial) + } + b, otherCode, gb := squareJoin(t, m, "bob", 22) + if otherCode != code || ga == gb { + t.Fatal("available channel was not shared with independent membership GUIDs") + } + joined := squareEnter(t, m, b, code, gb) + if len(joined) != 2 || joined[0].Frame.Type != 127 || len(repeated(joined[0].Frame.Payload, 3)) != 2 || joined[1].ConnectionID != a.ID || joined[1].Frame.Type != 128 { + t.Fatalf("second entrant should see both players and announce arrival: %+v", joined) + } + for _, user := range repeated(joined[0].Frame.Payload, 3) { + owner := number(bytesField(user, 1), 1) + if number(bytesField(user, 3), 1) != owner || number(bytesField(user, 4), 1) != owner || number(bytesField(user, 4), 2) != 3 { + t.Fatal("entry user/avatar identity did not come from committed profile") + } + } + for _, payload := range [][]byte{ + blob(text(nil, 2, gb), 3, integer(nil, 1, 11)), + blob(text(nil, 2, ga), 3, integer(nil, 1, 22)), + } { + if _, err := m.Handle(context.Background(), a, Frame{Type: 175, Payload: integer(payload, 4, 1)}); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("foreign membership/state owner accepted: %v", err) + } + } + state := blob(integer(nil, 1, 11), 2, integer(nil, 1, 9)) + payload := integer(blob(text(nil, 2, ga), 3, state), 4, 1) + d := squareRequest(t, m, a, 175, payload) + if len(d) != 1 || d[0].ConnectionID != b.ID || d[0].Frame.Type != 176 || number(bytesField(bytesField(d[0].Frame.Payload, 2), 2), 1) != 9 { + t.Fatalf("authorized movement was not relayed to the other player: %+v", d) + } + quiet := squareRequest(t, m, a, 175, blob(text(nil, 2, ga), 3, state)) + if len(quiet) != 0 { + t.Fatal("IsBroadCast=false movement was broadcast") + } + matching := a + matching.Channel, matching.ID = Matching, "matching-alice" + info := squareRequest(t, m, matching, 142, nil) + if len(info) != 1 || info[0].Frame.Type != 143 || number(info[0].Frame.Payload, 3) != 2 || number(bytesField(info[0].Frame.Payload, 2), 2) != 2 { + t.Fatalf("directory did not report live channel occupancy: %+v", info) + } +} + +func TestSquareCapacityChannelTransferAndReconnectFencing(t *testing.T) { + m, clock := squareManager(t, 1) + a, roomA, ga := squareJoin(t, m, "alice", 11) + squareEnter(t, m, a, roomA, ga) + b, roomB, gb := squareJoin(t, m, "bob", 22) + if roomA == roomB { + t.Fatal("automatic entry overbooked a full channel") + } + squareEnter(t, m, b, roomB, gb) + matching := a + matching.ID, matching.Channel = "matching-alice", Matching + full := squareRequest(t, m, matching, 124, integer(nil, 2, 2)) + if number(bytesField(full[0].Frame.Payload, 1), 2) != 11 { + t.Fatal("full channel did not return E_Matching_Room_Over_User_Count") + } + if view, err := m.View(context.Background(), a.Principal, Square); err != nil || view.RoomCode != roomA { + t.Fatal("failed channel transfer discarded the existing membership") + } + exit := squareRequest(t, m, b, 129, text(nil, 2, gb)) + if len(exit) != 1 || exit[0].Frame.Type != 130 { + t.Fatal("explicit square exit did not acknowledge") + } + transfer := squareRequest(t, m, matching, 124, integer(nil, 2, 2)) + newCode, newGUID := stringField(transfer[0].Frame.Payload, 2), stringField(transfer[0].Frame.Payload, 6) + if newCode != roomB || newGUID == ga { + t.Fatal("channel transfer did not issue new room membership") + } + if _, err := m.Handle(context.Background(), a, Frame{Type: 175, Payload: text(nil, 2, ga)}); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("old room socket retained authority after channel transfer: %v", err) + } + a.ID = "relay-alice-channel2" + squareRequest(t, m, a, 23, text(nil, 2, newCode)) + squareEnter(t, m, a, newCode, newGUID) + if _, err := m.Disconnect(context.Background(), a); err != nil { + t.Fatal(err) + } + replacement := a + replacement.ID = "relay-alice-reconnected" + d := squareRequest(t, m, replacement, 185, text(nil, 2, newGUID)) + if len(d) != 1 || d[0].Frame.Type != 186 || len(repeated(d[0].Frame.Payload, 5)) != 1 { + t.Fatal("reconnect did not restore the player's committed room snapshot") + } + if _, err := m.Handle(context.Background(), a, Frame{Type: 129, Payload: text(nil, 2, newGUID)}); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("replaced relay socket retained authority: %v", err) + } + if _, err := m.Disconnect(context.Background(), replacement); err != nil { + t.Fatal(err) + } + clock.Add(int64(16 * time.Second)) + if reply, err := m.Handle(context.Background(), replacement, Frame{Type: 185, Payload: text(nil, 2, newGUID)}); err != nil || len(reply) != 1 || (number(bytesField(reply[0].Frame.Payload, 1), 2) != 10 && number(bytesField(reply[0].Frame.Payload, 1), 2) != 3) { + t.Fatalf("expired reconnect did not return native failure: %+v %v", reply, err) + } +} + +func TestSquareRelayRejectsSpoofedIdentityAndForeignGameTraffic(t *testing.T) { + m, _ := squareManager(t, 2) + a, code, ga := squareJoin(t, m, "alice", 11) + squareEnter(t, m, a, code, ga) + b, _, gb := squareJoin(t, m, "bob", 22) + squareEnter(t, m, b, code, gb) + relay := func(owner int64, typ uint32) []byte { + inner := make([]byte, 4) + binary.LittleEndian.PutUint32(inner, typ) + return blob(text(nil, 2, ga), 3, append(inner, integer(nil, 1, owner)...)) + } + for _, payload := range [][]byte{relay(22, 9005), relay(11, 1011)} { + if _, err := m.Handle(context.Background(), a, Frame{Type: 70, Payload: payload}); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("spoofed user/foreign gameplay relay accepted: %v", err) + } + } + d := squareRequest(t, m, a, 70, relay(11, 9005)) + if len(d) != 1 || d[0].Frame.Type != 71 || d[0].ConnectionID != b.ID || number(d[0].Frame.Payload, 2) != 11 { + t.Fatalf("native UserStateRelayData not delivered: %+v", d) + } + outsider := a + outsider.Principal.AccountID = "outsider" + if reply, err := m.Handle(context.Background(), outsider, Frame{Type: 126, Payload: text(text(nil, 2, ga), 3, code)}); err != nil || len(reply) != 1 || number(bytesField(reply[0].Frame.Payload, 1), 2) != 3 { + t.Fatalf("nonmember did not receive E_Not_Found_Room: %+v %v", reply, err) + } +} + +func TestSquareNewPlayerGenerationReplacesExpiredLoginMembership(t *testing.T) { + m, _ := squareManager(t, 1) + old, code, guid := squareJoin(t, m, "alice", 11) + squareEnter(t, m, old, code, guid) + current := old + current.ID, current.Channel = "new-login-matching", Matching + current.Principal.Generation++ + current.Principal.SessionID = "new-login-session" + d := squareRequest(t, m, current, 205, nil) + if len(d) != 1 || stringField(d[0].Frame.Payload, 6) == guid || stringField(d[0].Frame.Payload, 2) != code { + t.Fatal("new login did not replace its previous square membership") + } + if _, err := m.View(context.Background(), old.Principal, Square); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("old player generation retained membership: %v", err) + } + old.Channel, old.ID = Matching, "old-login-matching" + if _, err := m.Handle(context.Background(), old, Frame{Type: 205}); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("retired generation reclaimed membership: %v", err) + } +} + +func TestSquareAvatarMotionUsesOwnedProfile(t *testing.T) { + m, _ := squareManager(t, 2) + a, code, ga := squareJoin(t, m, "alice", 11) + squareEnter(t, m, a, code, ga) + b, _, gb := squareJoin(t, m, "bob", 22) + squareEnter(t, m, b, code, gb) + if _, err := m.Handle(context.Background(), a, Frame{Type: 144, Payload: blob(nil, 2, integer(nil, 1, 99))}); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("unowned avatar motion accepted: %v", err) + } + d := squareRequest(t, m, a, 144, blob(nil, 2, integer(nil, 1, 7))) + if len(d) != 2 || d[0].Frame.Type != 145 || d[1].Frame.Type != 146 || d[1].ConnectionID != b.ID || number(bytesField(d[1].Frame.Payload, 3), 1) != 7 { + t.Fatalf("owned avatar motion not acknowledged/broadcast: %+v", d) + } +} + +func TestSquareLockedPlayerCanReadDirectoryButCannotReserveChannel(t *testing.T) { + m, _ := squareManager(t, 2) + c := Connection{ID: "locked-matching", Channel: Matching, Principal: Principal{AccountID: "locked", OwnerIndex: 33, SessionID: "session-locked", Generation: 1}} + d := squareRequest(t, m, c, 142, nil) + if len(d) != 1 || d[0].Frame.Type != 143 || number(d[0].Frame.Payload, 3) != 2 { + t.Fatal("public channel discovery incorrectly requires card ownership") + } + for _, req := range []Frame{{Type: 205}, {Type: 124, Payload: integer(nil, 2, 1)}} { + if _, err := m.Handle(context.Background(), c, req); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("locked player acquired square channel via %d: %v", req.Type, err) + } + } + if _, err := m.View(context.Background(), c.Principal, Square); !errors.Is(err, ErrNotFound) { + t.Fatalf("rejected reservation left membership: %v", err) + } +} diff --git a/go/internal/server/runtime/room/types.go b/go/internal/server/runtime/room/types.go index 89ab2c9..3a9538d 100644 --- a/go/internal/server/runtime/room/types.go +++ b/go/internal/server/runtime/room/types.go @@ -13,6 +13,7 @@ const ( Action Kind = "action" Defense Kind = "defense" Fishing Kind = "fishing" + Square Kind = "square" Matching Kind = "matching" ) @@ -55,6 +56,8 @@ type Delivery struct { type Profile struct { UserInfo []byte AvatarUseInfo []byte + AvatarMotions []uint64 + SquareUnlocked bool RodID int64 BoatLevel int64 BoatSkinID int64 @@ -71,6 +74,7 @@ type Selection struct { MapID int64 BoatLevel int64 BoatSkinID int64 + SquareChannel int64 Capacity int DefenseLastWave int64 Solo bool @@ -93,19 +97,21 @@ type ParticipantRules interface { } type Config struct { - AdvertisedHost string - TCPPort int - UDPPort int - Region int - MaxRooms int - QueueCommands int - QueueBytes int64 - ReconnectWindow time.Duration - LoadingLimit time.Duration - MatchingLimit time.Duration - RoomDuration time.Duration - ResultRetention time.Duration - Now func() time.Time + AdvertisedHost string + TCPPort int + UDPPort int + Region int + SquareChannels int + SquareChannelCapacity int + MaxRooms int + QueueCommands int + QueueBytes int64 + ReconnectWindow time.Duration + LoadingLimit time.Duration + MatchingLimit time.Duration + RoomDuration time.Duration + ResultRetention time.Duration + Now func() time.Time // Publish must enqueue without blocking; false drops a slow connection. Publish func([]Delivery) // PublishResult queues a terminal projection. Acknowledgment follows durable commit. diff --git a/go/internal/server/storage/account/bootstrap.go b/go/internal/server/storage/account/bootstrap.go index b0b2a58..106c738 100644 --- a/go/internal/server/storage/account/bootstrap.go +++ b/go/internal/server/storage/account/bootstrap.go @@ -85,7 +85,7 @@ func (r *Repository) InitializationState(accountDomains ...string) (Initializati // written only after every account domain and first-login entitlement exists; // a rollback therefore leaves a schema-only database that can be retried. func (t *CommandStore) MarkInitializationComplete() error { - payload, err := json.Marshal(bootstrapSnapshot{Version: 1}) + payload, err := json.Marshal(bootstrapSnapshot{Version: 2}) if err != nil { return err } @@ -100,7 +100,7 @@ func validateBootstrap(payload []byte) error { return fmt.Errorf("accountstate: invalid bootstrap marker: %w", err) } var snapshot bootstrapSnapshot - if err := json.Unmarshal(payload, &snapshot); err != nil || snapshot.Version != 1 { + if err := json.Unmarshal(payload, &snapshot); err != nil || snapshot.Version != 2 { return errors.New("accountstate: malformed bootstrap completion marker") } canonical, _ := json.Marshal(snapshot) diff --git a/go/internal/server/storage/account/validate.go b/go/internal/server/storage/account/validate.go index fc827ed..266ecdb 100644 --- a/go/internal/server/storage/account/validate.go +++ b/go/internal/server/storage/account/validate.go @@ -31,10 +31,6 @@ type validationSnapshot struct { characterIndices []uint64 collectionCharacterIndices []uint64 costumeIndices []uint64 - itemNextIndex uint64 - equipmentNextIndex uint64 - characterNextIndex uint64 - costumeNextIndex uint64 equipmentGrants []namedIndex equipmentUsers []namedIndex quests []questKey @@ -73,20 +69,12 @@ func validateSnapshot(snapshot validationSnapshot) []Problem { problems = append(problems, duplicateIndexProblems("equipment.duplicate_index", []string{"equipment", "equipment"}, snapshot.equipmentIndices)...) problems = append(problems, duplicateIndexProblems("characters.duplicate_index", []string{"characters"}, snapshot.characterIndices)...) problems = append(problems, duplicateIndexProblems("costumes.duplicate_index", []string{"collection", "costumes"}, snapshot.costumeIndices)...) - problems = append(problems, nextIndexProblems("inventory.next_index", []string{"inventory", "next_index"}, snapshot.itemNextIndex, snapshot.itemIndices)...) - problems = append(problems, nextIndexProblems("equipment.next_index", []string{"equipment", "next_index"}, snapshot.equipmentNextIndex, snapshot.equipmentIndices)...) - problems = append(problems, nextIndexProblems("collection.next_character_index", []string{"collection", "next_character_index"}, snapshot.characterNextIndex, snapshot.collectionCharacterIndices)...) - problems = append(problems, nextIndexProblems("collection.next_costume_index", []string{"collection", "next_costume_index"}, snapshot.costumeNextIndex, snapshot.costumeIndices)...) for _, grant := range snapshot.equipmentGrants { - // Equipment can be dismantled after it was granted. The grant entry is - // an issuance/idempotency ledger, just like items.grant_items, so the - // historical index need only be nonzero and below the monotonic next - // index; it does not have to remain in the current ownership set. - if grant.index == 0 || grant.index >= snapshot.equipmentNextIndex { + if grant.index == 0 || grant.index >= 1<<59 { problems = append(problems, Problem{ Code: "equipment.grant_missing_equipment", Path: []string{"equipment", "grants", grant.identity}, - Message: "equipment grant index must be nonzero and below next_index", RelatedIDs: []uint64{grant.index}, + Message: "equipment grant must reference a valid permanent instance", RelatedIDs: []uint64{grant.index}, }) } } @@ -112,8 +100,8 @@ func validateSnapshot(snapshot validationSnapshot) []Problem { problems = append(problems, Problem{Code: "inventory.grant_without_marker", Path: path, Message: "historical grant must have an idempotency marker"}) } for _, index := range grant.indices { - if index == 0 || index >= snapshot.itemNextIndex { - problems = append(problems, Problem{Code: "inventory.grant_invalid_index", Path: path, Message: "issued index must be nonzero and below next_index", RelatedIDs: []uint64{index}}) + if index == 0 || index >= 1<<59 { + problems = append(problems, Problem{Code: "inventory.grant_invalid_index", Path: path, Message: "issued index must be a valid permanent instance", RelatedIDs: []uint64{index}}) } } problems = append(problems, duplicateIndexProblems("inventory.grant_duplicate_index", path, grant.indices)...) @@ -140,20 +128,6 @@ func duplicateIndexProblems(code string, path []string, values []uint64) []Probl return problems } -func nextIndexProblems(code string, path []string, next uint64, values []uint64) []Problem { - if len(values) == 0 { - return nil - } - maximum := values[0] - for _, value := range values[1:] { - maximum = max(maximum, value) - } - if next > maximum { - return nil - } - return []Problem{{Code: code, Path: path, Message: "next index must be greater than every existing index", RelatedIDs: []uint64{next}}} -} - func keyProblems(code string, path []string, values []questKey) []Problem { var problems []Problem for _, value := range values { @@ -217,15 +191,6 @@ func (t *CommandStore) Validate() ([]Problem, error) { func validateState(tx *sql.Tx) ([]Problem, error) { snapshot := validationSnapshot{formatVersion: 1, clientVersion: "sqlite", gameDataVersion: "sqlite", granted: make(map[string]bool)} var err error - if snapshot.itemNextIndex, err = coreUint(tx, "items", "next_index"); err != nil { - return nil, err - } - if snapshot.equipmentNextIndex, err = coreUint(tx, "equipment", "next_index"); err != nil { - return nil, err - } - if snapshot.characterNextIndex, snapshot.costumeNextIndex, err = collectionNextIndices(tx); err != nil { - return nil, err - } if snapshot.itemIndices, _, err = indexedEntries(tx, "items", "items", false); err != nil { return nil, err } @@ -241,9 +206,7 @@ func validateState(tx *sql.Tx) ([]Problem, error) { return nil, err } snapshot.characterIndices = append(baseCharacters, acquiredCharacters...) - // Collection allocation owns acquired characters. Base, story and timed - // companions have separate instance namespaces; they still participate in - // duplicate identity and equipment owner validation above. + // Both starter and acquired characters participate in ownership validation. snapshot.collectionCharacterIndices = acquiredCharacters if snapshot.costumeIndices, _, err = indexedEntries(tx, "collection", "costumes", false); err != nil { return nil, err @@ -279,30 +242,6 @@ func loadCore(tx *sql.Tx, domain string) (map[string]json.RawMessage, bool, erro return fields, true, nil } -func coreUint(tx *sql.Tx, domain, field string) (uint64, error) { - fields, found, err := loadCore(tx, domain) - if err != nil || !found { - return 0, err - } - var value uint64 - if raw, ok := fields[field]; !ok || json.Unmarshal(raw, &value) != nil { - return 0, fmt.Errorf("accountstate: invalid %s.%s", domain, field) - } - return value, nil -} - -func collectionNextIndices(tx *sql.Tx) (uint64, uint64, error) { - fields, found, err := loadCore(tx, "collection") - if err != nil || !found { - return 0, 0, err - } - var characters, costumes uint64 - if json.Unmarshal(fields["next_character_index"], &characters) != nil || json.Unmarshal(fields["next_costume_index"], &costumes) != nil { - return 0, 0, errors.New("accountstate: invalid collection next indices") - } - return characters, costumes, nil -} - func indexedEntries(tx *sql.Tx, domain, bucket string, readUseChar bool) ([]uint64, []namedIndex, error) { rows, err := tx.Query(`SELECT entry_key, payload FROM domain_entry WHERE domain_name = ? AND bucket = ? ORDER BY entry_key`, domain, bucket) if err != nil { diff --git a/go/seed/v2_37_13/cash_package_layouts.json b/go/seed/v2_37_13/cash_package_layouts.json new file mode 100644 index 0000000..1d12c4d --- /dev/null +++ b/go/seed/v2_37_13/cash_package_layouts.json @@ -0,0 +1,63 @@ +{ + "version": "2.37.13", + "bundle_version": "20261022174708", + "layouts": { + "PackageUI119": "relay", + "PackageUI127": "relay", + "PackageUI132": "relay", + "PackageUI139": "relay", + "PackageUI144": "relay", + "PackageUI148": "independent", + "PackageUI159": "relay", + "PackageUI160": "relay", + "PackageUI164": "relay", + "PackageUI174": "relay", + "PackageUI175": "relay", + "PackageUI183": "relay", + "PackageUI184": "relay", + "PackageUI193": "relay", + "PackageUI194": "relay", + "PackageUI197": "relay", + "PackageUI199": "independent", + "PackageUI205": "independent", + "PackageUI210": "independent", + "PackageUI211": "independent", + "PackageUI212": "independent", + "PackageUI213": "independent", + "PackageUI214": "independent", + "PackageUI216": "independent", + "PackageUI217": "independent", + "PackageUI219": "relay", + "PackageUI220": "relay", + "PackageUI224": "independent", + "PackageUI227": "relay", + "PackageUI228": "relay", + "PackageUI229": "independent", + "PackageUI232": "relay", + "PackageUI233": "relay", + "PackageUI238": "independent", + "PackageUI240": "independent", + "PackageUI243": "relay", + "PackageUI244": "relay", + "PackageUI251": "independent", + "PackageUI253": "independent", + "PackageUI256": "relay", + "PackageUI257": "relay", + "PackageUI265": "relay", + "PackageUI266": "relay", + "PackageUI273": "independent", + "PackageUI282": "independent", + "PackageUI284": "relay", + "PackageUI285": "relay", + "PackageUI296": "relay", + "PackageUI297": "relay", + "PackageUI303": "independent", + "PackageUI308": "relay", + "PackageUI309": "relay", + "PackageUI311": "independent", + "PackageUI316": "independent", + "PackageUI54": "independent", + "PackageUI80": "relay", + "PackageUI95": "relay" + } +} diff --git a/go/seed/v2_36_7/decks.json b/go/seed/v2_37_13/decks.json similarity index 95% rename from go/seed/v2_36_7/decks.json rename to go/seed/v2_37_13/decks.json index f6f5cf5..e19c908 100644 --- a/go/seed/v2_36_7/decks.json +++ b/go/seed/v2_37_13/decks.json @@ -1,5 +1,5 @@ { - "version": "2.36.7", + "version": "2.37.13", "field_deck": [ {"slot": 1, "character_inven_index": 535604120, "costume_inven_index": 609336981}, {"slot": 2, "character_inven_index": 535604119, "costume_inven_index": 609336980}, diff --git a/go/seed/v2_36_7/event_field_bindings.json b/go/seed/v2_37_13/event_field_bindings.json similarity index 93% rename from go/seed/v2_36_7/event_field_bindings.json rename to go/seed/v2_37_13/event_field_bindings.json index 050cb6e..ed3ced7 100644 --- a/go/seed/v2_36_7/event_field_bindings.json +++ b/go/seed/v2_37_13/event_field_bindings.json @@ -1,5 +1,5 @@ { - "version": "2.36.7", + "version": "2.37.13", "bindings": [ { "pack_id": 20000, diff --git a/go/seed/v2_36_7/login_user.json b/go/seed/v2_37_13/login_user.json similarity index 93% rename from go/seed/v2_36_7/login_user.json rename to go/seed/v2_37_13/login_user.json index 77f5600..e9f77e7 100644 --- a/go/seed/v2_36_7/login_user.json +++ b/go/seed/v2_37_13/login_user.json @@ -1,5 +1,5 @@ { - "version": "2.36.7", + "version": "2.37.13", "packet_code": 3, "user_info_base64": "CJqO1A4SDkd1ZXN0XzMwNzM4MjAyKGQwZDiQTlD0A2gBeGTgAQXqAQIQAeoBDAgCEAEaBjEwLDEuNeoBBAgDEAHqAQQIBBAB6gEKCAUQARoEMzAsM+oBBwgGEAEaATXqAQcICBABGgEw6gEECAkQAeoBBAgKEAH4AYDLqrEEgAIDiAIFsAKQ5vPTizS4AgHYAtKFj9SLNKADBagDBcgDBfADCvgDHoAEHogEyAE=", "response_fields_base64": "IgBQAVgBYAFoAQ==" diff --git a/go/seed/v2_36_7/mail.json b/go/seed/v2_37_13/mail.json similarity index 98% rename from go/seed/v2_36_7/mail.json rename to go/seed/v2_37_13/mail.json index b3343d8..e89a70a 100644 --- a/go/seed/v2_36_7/mail.json +++ b/go/seed/v2_37_13/mail.json @@ -1,5 +1,5 @@ { - "version": "2.36.7", + "version": "2.37.13", "mails": [ { "mail_id": 13042978139, diff --git a/go/seed/v2_36_7/readonly.json b/go/seed/v2_37_13/readonly.json similarity index 99% rename from go/seed/v2_36_7/readonly.json rename to go/seed/v2_37_13/readonly.json index 337f3d6..88beb92 100644 --- a/go/seed/v2_36_7/readonly.json +++ b/go/seed/v2_37_13/readonly.json @@ -1,5 +1,5 @@ { - "version": "2.36.7", + "version": "2.37.13", "responses": { "/ColosseumUserInfo": { "packet_code": 473, diff --git a/go/seed/v2_37_13/starter_gifts.json b/go/seed/v2_37_13/starter_gifts.json new file mode 100644 index 0000000..b4b0a7e --- /dev/null +++ b/go/seed/v2_37_13/starter_gifts.json @@ -0,0 +1,32 @@ +{ + "version": "2.37.13", + "gamedata_version": "20261021182514", + "gifts": [ + { + "identity": "starter:limited-costumes:not-current-pickup:v1", + "title": "New Player Limited Costumes", + "body": "Limited costumes not featured in the current pickup banners. Each costume is enhanced to +5 when claimed." + }, + { + "identity": "starter:prestige-skins:not-current-purchase:v1", + "title": "Prestige Skin Gift", + "body": "Prestige skins not currently available on the cash purchase page." + }, + { + "identity": "starter:limited-avatars:external-sources:v1", + "title": "Limited Avatar Accessories Gift", + "body": "Avatar accessories originally obtained from seasonal events or external promotions. Default outfits and achievement rewards are excluded.", + "external_avatar_parts": [ + {"id": 20018, "unlock_text_id": 1500239, "source": "April Fools commemorative dice event"}, + {"id": 50007, "unlock_text_id": 1500232, "source": "Valentine commemorative roulette event"}, + {"id": 60015, "unlock_text_id": 1500248, "source": "Artbook bonus redemption code"}, + {"id": 60018, "unlock_text_id": 1500268, "source": "Coffee truck thank-you voucher"} + ] + }, + { + "identity": "starter:prestige-avatar:", + "title": "Prestige Avatar Outfit Gift", + "body": "The avatar outfit linked to a prestige skin you own. Only outfit pieces you do not already own are granted when claimed." + } + ] +} diff --git a/go/seed/v2_36_7/starter_player.json b/go/seed/v2_37_13/starter_player.json similarity index 99% rename from go/seed/v2_36_7/starter_player.json rename to go/seed/v2_37_13/starter_player.json index aa5e5f2..25211be 100644 --- a/go/seed/v2_36_7/starter_player.json +++ b/go/seed/v2_37_13/starter_player.json @@ -1,5 +1,5 @@ { - "version": "2.36.7", + "version": "2.37.13", "cooking_recipes": [101], "owned_items": [ { diff --git a/go/seed/v2_36_7/world.json b/go/seed/v2_37_13/world.json similarity index 97% rename from go/seed/v2_36_7/world.json rename to go/seed/v2_37_13/world.json index ed08149..6c37da8 100644 --- a/go/seed/v2_36_7/world.json +++ b/go/seed/v2_37_13/world.json @@ -1,5 +1,5 @@ { - "version": "2.36.7", + "version": "2.37.13", "pack_id": 21, "placeholder_costume_id": 996000, "square_scene_id": 3, diff --git a/plugins/CaptureEnvironment/CaptureEnvironment.csproj b/plugins/CaptureEnvironment/CaptureEnvironment.csproj index a172abe..fc8d129 100644 --- a/plugins/CaptureEnvironment/CaptureEnvironment.csproj +++ b/plugins/CaptureEnvironment/CaptureEnvironment.csproj @@ -7,7 +7,7 @@ Bd2CaptureEnvironment true capture_environment - 2.36.7 + 2.37.13 diff --git a/plugins/CashShop/CashShop.csproj b/plugins/CashShop/CashShop.csproj index b64f97e..8182fc3 100644 --- a/plugins/CashShop/CashShop.csproj +++ b/plugins/CashShop/CashShop.csproj @@ -7,7 +7,7 @@ Bd2CashShop true cash_shop - 2.36.7 + 2.37.13 diff --git a/plugins/FChat/FChat.csproj b/plugins/FChat/FChat.csproj index 316e61a..f898e22 100644 --- a/plugins/FChat/FChat.csproj +++ b/plugins/FChat/FChat.csproj @@ -7,7 +7,7 @@ Bd2FChat true fchat - 2.36.7 + 2.37.13 diff --git a/plugins/GameNames/Mappings/names.json.gz b/plugins/GameNames/Mappings/names.json.gz index 107a306..29fcc26 100644 Binary files a/plugins/GameNames/Mappings/names.json.gz and b/plugins/GameNames/Mappings/names.json.gz differ diff --git a/plugins/GameSdk/samples/ExamplePlugin/ExamplePlugin.csproj b/plugins/GameSdk/samples/ExamplePlugin/ExamplePlugin.csproj index 3dd2170..33a58e5 100644 --- a/plugins/GameSdk/samples/ExamplePlugin/ExamplePlugin.csproj +++ b/plugins/GameSdk/samples/ExamplePlugin/ExamplePlugin.csproj @@ -6,7 +6,7 @@ false false ExamplePlugin - 2.36.7 + 2.37.13 $(GameDir)/BrownDust II_Data/Managed diff --git a/plugins/LocalIdentity/LocalIdentity.csproj b/plugins/LocalIdentity/LocalIdentity.csproj index 0a2dc9d..07da9c5 100644 --- a/plugins/LocalIdentity/LocalIdentity.csproj +++ b/plugins/LocalIdentity/LocalIdentity.csproj @@ -7,7 +7,7 @@ Bd2LocalIdentity true local_identity - 2.36.7 + 2.37.13 diff --git a/plugins/LoginUI/LoginUI.csproj b/plugins/LoginUI/LoginUI.csproj index eb1a972..e58fe3d 100644 --- a/plugins/LoginUI/LoginUI.csproj +++ b/plugins/LoginUI/LoginUI.csproj @@ -7,7 +7,7 @@ Bd2LoginUI true login_ui - 2.36.7 + 2.37.13 diff --git a/schedules/cash_shop.bd2schedule b/schedules/cash_shop.bd2schedule index 1969a8c..cbfffa8 100644 Binary files a/schedules/cash_shop.bd2schedule and b/schedules/cash_shop.bd2schedule differ diff --git a/schedules/event_hubs.bd2schedule b/schedules/event_hubs.bd2schedule index f0d8a2d..650141e 100644 Binary files a/schedules/event_hubs.bd2schedule and b/schedules/event_hubs.bd2schedule differ diff --git a/schedules/events.bd2schedule b/schedules/events.bd2schedule index 6e9dcec..1aff912 100644 Binary files a/schedules/events.bd2schedule and b/schedules/events.bd2schedule differ diff --git a/schedules/gacha.bd2schedule b/schedules/gacha.bd2schedule index ea1a065..2ee977b 100644 Binary files a/schedules/gacha.bd2schedule and b/schedules/gacha.bd2schedule differ diff --git a/schedules/monster_hunt.bd2schedule b/schedules/monster_hunt.bd2schedule index 424930f..2bed8f6 100644 Binary files a/schedules/monster_hunt.bd2schedule and b/schedules/monster_hunt.bd2schedule differ diff --git a/schedules/regular.bd2schedule b/schedules/regular.bd2schedule index 7290905..74dec3c 100644 Binary files a/schedules/regular.bd2schedule and b/schedules/regular.bd2schedule differ diff --git a/tools/client/client-download.json b/tools/client/client-download.json index d2a0c3d..089956a 100644 --- a/tools/client/client-download.json +++ b/tools/client/client-download.json @@ -1,7 +1,7 @@ { - "game_version": "2.36.7", - "game_data_version": "20261012190548", - "bundle_version": "20261007175947", + "game_version": "2.37.13", + "game_data_version": "20261021182514", + "bundle_version": "20261022174708", "platform": "StandaloneWindows64", "server_origin": "https://bd2-test.45.76.195.129.sslip.io", "build_origins": [ @@ -13,12 +13,12 @@ "https://cdn.bd2.pmang.cloud", "https://bd2-cdn.akamaized.net" ], - "game_path": "/Build/Windows/20261002/StandaloneWindows64.2.36.7.zip", - "game_sha256": "3ca28b7c94d65b2cb4e33784d843902758415a3a83870c5f6198f5cd90e3bff3", - "game_bytes": 413552979, - "data_sha256": "0f28881e08029a1a53f86d5b113ba80b70b6d904bec35175b54ecfe90c2b6715", - "data_bytes": 191790996, - "catalog_sha256": "c9ed216c66903bfa1e556f38cc02e2923a48164e8469767d7987f7989d86d385", - "catalog_bytes": 67338179, - "catalog_hash": "0f90a94601be05737f86a4ec7a1c889f" + "game_path": "/Build/Windows/20261023/StandaloneWindows64.2.37.13.zip", + "game_sha256": "8f65954eb323fcffb1c29be13205d373d4f8fba3354e2e8d431d263bb2a6ca56", + "game_bytes": 413694732, + "data_sha256": "f3313a066dd2637678f728136d448adfd413259ae7129a79e109e7332b61a57d", + "data_bytes": 194804246, + "catalog_sha256": "3e19c645e28b90d3601cd0ed7413dc516399ba2b658e0fa509686527048407b8", + "catalog_bytes": 67513445, + "catalog_hash": "ae57bde3e9e5cf6ac57f9b0c0ea39b2f" } diff --git a/versions.json b/versions.json index e11f7fc..26625c4 100644 --- a/versions.json +++ b/versions.json @@ -1,19 +1,19 @@ { - "game_version": "2.36.7", - "client_version": "2.36.7+client.0.2.4", - "server_version": "2.36.7+server.0.2.0", - "game_data_version": "20261012190548", - "bundle_version": "20261007175947", - "seed_directory": "go/seed/v2_36_7", + "game_version": "2.37.13", + "client_version": "2.37.13+client.0.2.10", + "server_version": "2.37.13+server.0.2.0", + "game_data_version": "20261021182514", + "bundle_version": "20261022174708", + "seed_directory": "go/seed/v2_37_13", "plugins": { - "local_identity": "0.7.1", + "local_identity": "0.7.5", "capture_environment": "0.2.0", - "login_ui": "0.3.2", + "login_ui": "0.3.5", "cash_shop": "0.1.2", - "fchat": "0.1.0" + "fchat": "0.1.2" }, "minimum_plugins": { - "local_identity": "0.7.1", + "local_identity": "0.7.3", "capture_environment": "0.2.0", "login_ui": "0.3.2", "cash_shop": "0.1.2",