feat(all): save preset first-turn actions and apply them in battle

This commit is contained in:
Flechazo committed 2026-10-25 17:42:23 +08:00
1 parent e06d68aaaf
commit ed2b24ef2c
25 files changed
+2258 -15

No files matched your search

+6 -2
View File
@@ -29,6 +29,7 @@ type pluginVersions struct {
LoginUI string `json:"login_ui"`
CashShop string `json:"cash_shop"`
FChat string `json:"fchat"`
FBattle string `json:"fbattle,omitempty"`
}
func readConfig(path string, config *Config) error {
@@ -106,6 +107,9 @@ namespace Bd2Build
func (c Config) validate(plugin string) (string, error) {
plugins := map[string]string{"local_identity": c.Plugins.LocalIdentity, "capture_environment": c.Plugins.CaptureEnvironment, "login_ui": c.Plugins.LoginUI, "cash_shop": c.Plugins.CashShop, "fchat": c.Plugins.FChat}
if c.Plugins.FBattle != "" {
plugins["fbattle"] = c.Plugins.FBattle
}
selected, found := plugins[plugin]
if !found {
return "", fmt.Errorf("unsupported plugin %q", plugin)
@@ -115,8 +119,8 @@ func (c Config) validate(plugin string) (string, error) {
if !semver.MatchString(c.GameVersion) {
return "", errors.New("game_version must be a numeric three-part version")
}
for _, key := range []string{"local_identity", "capture_environment", "login_ui", "cash_shop", "fchat"} {
if !semver.MatchString(plugins[key]) {
for key, value := range plugins {
if !semver.MatchString(value) {
return "", fmt.Errorf("plugins.%s must be a numeric three-part version", key)
}
}
+1
View File
@@ -25,6 +25,7 @@ var definitions = []Definition{
{ID: "login_ui", ProjectPath: "LoginUI/LoginUI.csproj", Framework: "netstandard2.1", FileName: "BD2LoginUI.dll", VersionKey: "login_ui", UsesGameSdk: true, Dependencies: []string{"game_names"}},
{ID: "cash_shop", ProjectPath: "CashShop/CashShop.csproj", Framework: "netstandard2.1", FileName: "BD2CashShop.dll", VersionKey: "cash_shop", UsesGameSdk: true, Dependencies: []string{"game_names"}},
{ID: "fchat", ProjectPath: "FChat/FChat.csproj", Framework: "netstandard2.1", FileName: "BD2FChat.dll", VersionKey: "fchat", UsesGameSdk: true, Dependencies: []string{"game_names", "login_ui"}},
{ID: "fbattle", ProjectPath: "FBattle/FBattle.csproj", Framework: "netstandard2.1", FileName: "BD2FBattle.dll", VersionKey: "fbattle", UsesGameSdk: true, Dependencies: []string{"game_names", "local_identity"}},
{ID: "brown_dust_x_accel", ProjectPath: "BrownDustXAccel/BrownDustXAccel.csproj", Framework: "netstandard2.1", FileName: "BD2BrownDustXAccel.dll"},
}
+1 -1
View File
@@ -184,7 +184,7 @@ func (f Fingerprint) Validate() error {
func knownPlayerPlugin(id string) bool {
switch id {
case "local_identity", "login_ui", "cash_shop", "fchat":
case "local_identity", "login_ui", "cash_shop", "fchat", "fbattle":
return true
default:
return false
+9 -1
View File
@@ -46,6 +46,7 @@ type PluginVersions struct {
LoginUI string `json:"login_ui"`
CashShop string `json:"cash_shop"`
FChat string `json:"fchat"`
FBattle string `json:"fbattle,omitempty"`
}
// Load reads one explicit version file. Unknown fields and trailing JSON are
@@ -89,6 +90,9 @@ func (c Config) Validate() error {
return fmt.Errorf("minimum_plugins.%s must be a numeric three-part version no newer than plugins.%s", id, id)
}
}
if c.Plugins.FBattle != "" && !semanticVersion.MatchString(c.Plugins.FBattle) {
return errors.New("plugins.fbattle must be a numeric three-part version")
}
if err := validateReleaseVersion("client_version", c.ClientVersion, c.GameVersion, "client"); err != nil {
return err
}
@@ -114,7 +118,11 @@ func (c Config) Validate() error {
// ByID lists the plugin versions under their versions.json keys.
func (p PluginVersions) ByID() map[string]string {
return map[string]string{"local_identity": p.LocalIdentity, "capture_environment": p.CaptureEnvironment, "login_ui": p.LoginUI, "cash_shop": p.CashShop, "fchat": p.FChat}
versions := map[string]string{"local_identity": p.LocalIdentity, "capture_environment": p.CaptureEnvironment, "login_ui": p.LoginUI, "cash_shop": p.CashShop, "fchat": p.FChat}
if p.FBattle != "" {
versions["fbattle"] = p.FBattle
}
return versions
}
func (p PluginVersions) pairs(minimum PluginVersions) map[string][2]string {
@@ -0,0 +1,162 @@
package deck
import (
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/stateio"
"encoding/json"
"errors"
"fmt"
"strconv"
)
// BattleAction uses the native battle selection sentinels: zero is a normal
// attack, -1 is knock-back, and a positive value is an owned costume instance.
type BattleAction struct {
CharacterIndex uint64 `json:"character_index"`
CostumeIndex int64 `json:"costume_index"`
BurstLevel uint64 `json:"burst_level,omitempty"`
}
func cloneBattlePlan(plan []BattleAction) []BattleAction {
if plan == nil {
return nil
}
if len(plan) == 0 {
return make([]BattleAction, 0)
}
return append([]BattleAction(nil), plan...)
}
func clipBattlePlan(preset Preset, plan []BattleAction) []BattleAction {
owned := make(map[uint64]bool, len(preset.Decks))
for _, deck := range preset.Decks {
owned[deck.Deck.CharacterInvenIndex] = true
}
result := make([]BattleAction, 0, len(plan))
for _, action := range plan {
if owned[action.CharacterIndex] {
result = append(result, action)
}
}
return result
}
func (s *Store) loadBattlePlans(ctx command.Context) error {
raw, err := s.storage.ListEntries(ctx.State, "deck", "battle_plans")
if err != nil {
return err
}
for key, payload := range raw {
slot, err := strconv.ParseUint(key, 10, 64)
if err != nil || key != strconv.FormatUint(slot, 10) || slot >= s.presetSlots {
return fmt.Errorf("deck: invalid battle plan key %q", key)
}
plan := make([]BattleAction, 0)
if err := json.Unmarshal(payload, &plan); err != nil {
return fmt.Errorf("deck: invalid battle plan %q: %w", key, err)
}
if plan == nil {
plan = make([]BattleAction, 0)
}
preset, ok := s.presets[slot]
if !ok {
return fmt.Errorf("deck: battle plan %q has no preset", key)
}
preset.BattlePlan = cloneBattlePlan(plan)
s.presets[slot] = preset
}
return nil
}
func (s *Store) validateBattlePlan(preset Preset, plan []BattleAction) error {
if len(plan) > len(preset.Decks) {
return errors.New("battle plan has too many actions")
}
characters := make(map[uint64]PresetDeck, len(preset.Decks))
for _, deck := range preset.Decks {
characters[deck.Deck.CharacterInvenIndex] = deck
}
seen := make(map[uint64]bool, len(plan))
for _, action := range plan {
if action.CharacterIndex == 0 || seen[action.CharacterIndex] {
return errors.New("battle plan has an invalid or repeated character")
}
if _, ok := characters[action.CharacterIndex]; !ok {
return fmt.Errorf("battle plan character %d is not in preset", action.CharacterIndex)
}
seen[action.CharacterIndex] = true
if action.CostumeIndex < -1 {
return fmt.Errorf("battle plan character %d has invalid action", action.CharacterIndex)
}
if action.CostumeIndex > 0 {
if s.collection == nil {
return errors.New("battle plan collection unavailable")
}
costume, found := s.collection.CostumeByIndex(uint64(action.CostumeIndex))
if !found || costume.UseChar != action.CharacterIndex {
return fmt.Errorf("battle plan costume %d does not belong to character %d", action.CostumeIndex, action.CharacterIndex)
}
if action.BurstLevel > costume.BurstLevel {
return fmt.Errorf("battle plan costume %d burst level exceeds owned level", action.CostumeIndex)
}
} else if action.BurstLevel != 0 {
return fmt.Errorf("battle plan character %d has burst without a costume skill", action.CharacterIndex)
}
}
return nil
}
func battlePlanMutation(p Preset) (stateio.EntryMutation, error) {
payload, err := json.Marshal(p.BattlePlan)
if err != nil {
return stateio.EntryMutation{}, err
}
return stateio.EntryMutation{Bucket: "battle_plans", Key: strconv.FormatUint(p.Slot, 10), Payload: payload}, nil
}
func battlePlanWire(plan []BattleAction) []byte {
var out []byte
for _, action := range plan {
entry := wire.AppendVarint(nil, 1, action.CharacterIndex)
entry = wire.AppendVarint(entry, 2, uint64(action.CostumeIndex))
if action.BurstLevel != 0 {
entry = wire.AppendVarint(entry, 3, action.BurstLevel)
}
out = wire.AppendBytes(out, 2, entry)
}
// Presence of schema=1 distinguishes an explicitly empty plan from a
// missing extension, while preserving the native request's zero defaults.
return wire.AppendVarint(out, 1, 1)
}
func decodeBattlePlan(data []byte) ([]BattleAction, error) {
schema, found, err := wire.Varint(data, 1)
if err != nil || !found || schema != 1 {
return nil, errors.New("deck: unsupported battle plan schema")
}
plan := make([]BattleAction, 0)
err = wire.Walk(data, func(field wire.Field) error {
if field.Number != 2 {
return nil
}
if field.Type != 2 {
return errors.New("deck: invalid battle plan action")
}
character, ok, e := wire.Varint(field.Value, 1)
if e != nil || !ok {
return errors.New("deck: battle action missing character")
}
costume, _, e := wire.Varint(field.Value, 2)
if e != nil {
return e
}
burst, _, e := wire.Varint(field.Value, 3)
if e != nil {
return e
}
plan = append(plan, BattleAction{CharacterIndex: character, CostumeIndex: int64(costume), BurstLevel: burst})
return nil
})
return plan, err
}
@@ -0,0 +1,188 @@
package deck
import (
"bd2server/internal/common/versionconfig"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/stateio"
"bytes"
"encoding/json"
"testing"
)
func TestBattlePlanWireRoundTripPreservesNativeSentinels(t *testing.T) {
want := []BattleAction{
{CharacterIndex: 101, CostumeIndex: 0},
{CharacterIndex: 102, CostumeIndex: -1},
{CharacterIndex: 103, CostumeIndex: 9001, BurstLevel: 2},
}
// schema=1; action fields are character=1, costume=2, burst=3.
// int64 -1 is the native ten-byte varint used for knock-back.
fixture := []byte{0x12, 4, 8, 101, 16, 0, 0x12, 13, 8, 102, 16,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 1,
0x12, 7, 8, 103, 16, 0xa9, 0x46, 24, 2, 8, 1}
if encoded := battlePlanWire(want); !bytes.Equal(encoded, fixture) {
t.Fatalf("encoded native action plan=%x want %x", encoded, fixture)
}
got, err := decodeBattlePlan(fixture)
if err != nil {
t.Fatal(err)
}
if len(got) != len(want) {
t.Fatalf("decoded %d actions, want %d", len(got), len(want))
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("action %d = %#v, want %#v", i, got[i], want[i])
}
}
empty, err := decodeBattlePlan(battlePlanWire([]BattleAction{}))
if err != nil || empty == nil || len(empty) != 0 {
t.Fatalf("explicit empty plan was not preserved: %#v, %v", empty, err)
}
}
func TestValidateBattlePlanRejectsCharactersOutsidePreset(t *testing.T) {
s := &Store{}
preset := Preset{Slot: 1, Decks: []PresetDeck{{Deck: DeckEntry{CharacterInvenIndex: 7}}}}
if err := s.validateBattlePlan(preset, []BattleAction{{CharacterIndex: 8}}); err == nil {
t.Fatal("expected action for a character outside the preset to be rejected")
}
}
func TestValidateBattlePlanRejectsBurstOnDefaultAttack(t *testing.T) {
s := &Store{}
preset := Preset{Slot: 1, Decks: []PresetDeck{{Deck: DeckEntry{CharacterInvenIndex: 7}}}}
if err := s.validateBattlePlan(preset, []BattleAction{{CharacterIndex: 7, BurstLevel: 1}}); err == nil {
t.Fatal("expected burst on normal attack to be rejected")
}
}
func TestBattlePlanPersistsByPresetSlotAndReloadsAfterReopen(t *testing.T) {
mem := stateio.NewMemory()
ctx := command.Context{State: mem}
equipment := make([]PresetEquipmentItem, 5)
for i := range equipment {
equipment[i].Type = uint64(i)
}
preset := Preset{Name: "Plan", Slot: 1, Decks: []PresetDeck{{Deck: DeckEntry{CharacterInvenIndex: 7, CostumeInvenIndex: 1, Slot: 1}, Equipment: equipment}}, BattlePlan: []BattleAction{{CharacterIndex: 7, CostumeIndex: -1}}}
store := &Store{storage: stateio.RootStore{}, state: state{Version: versionconfig.State(), FieldDeck: []FieldEntry{{CharacterInvenIndex: 1, Slot: 1}}, Waypoints: map[uint64][]uint64{}, Costumes: map[uint64]uint64{}, Packs: map[uint64]uint64{}}}
if err := store.persistPresetLocked(ctx, preset); err != nil {
t.Fatal(err)
}
if err := store.persistActivePreset(ctx, store.state, 1); err != nil {
t.Fatal(err)
}
seed := Seed{Version: versionconfig.State(), FieldDeck: []FieldEntry{{CharacterInvenIndex: 1, Slot: 1}}}
reopened, err := OpenStore(ctx, stateio.RootStore{}, seed, gamedata.PresetDesign{BaseCount: 2, Maximum: 2, PriceType: 4, Price: 2000, Icons: map[uint64]bool{}})
if err != nil {
t.Fatal(err)
}
got := reopened.presets[1].BattlePlan
if len(got) != 1 || got[0].CharacterIndex != 7 || got[0].CostumeIndex != -1 {
t.Fatalf("reloaded plan = %#v", got)
}
if reopened.activePreset == nil || *reopened.activePreset != 1 {
t.Fatalf("reloaded active preset = %#v", reopened.activePreset)
}
data, found, err := mem.LoadEntry("deck", "active_preset", "slot")
if err != nil || !found {
t.Fatalf("active preset missing: found=%v err=%v", found, err)
}
var slot uint64
if err := json.Unmarshal(data, &slot); err != nil || slot != 1 {
t.Fatalf("active slot=%d err=%v", slot, err)
}
}
func TestExplicitEmptyBattlePlanIsPersistedAsClear(t *testing.T) {
mem := stateio.NewMemory()
ctx := command.Context{State: mem}
store := &Store{storage: stateio.RootStore{}, state: state{Version: versionconfig.State(), FieldDeck: []FieldEntry{{CharacterInvenIndex: 1, Slot: 1}}, Waypoints: map[uint64][]uint64{}, Costumes: map[uint64]uint64{}, Packs: map[uint64]uint64{}}}
preset := Preset{Name: "Clear", Slot: 0, BattlePlan: []BattleAction{{CharacterIndex: 7, CostumeIndex: -1}}}
if err := store.persistPresetLocked(ctx, preset); err != nil {
t.Fatal(err)
}
// A native client that omits field 100 must leave the existing plan alone.
preset.BattlePlan = nil
if err := store.persistPresetLocked(ctx, preset); err != nil {
t.Fatal(err)
}
unchanged, found, err := mem.LoadEntry("deck", "battle_plans", "0")
if err != nil || !found {
t.Fatalf("omitted plan unexpectedly cleared existing value: found=%v err=%v", found, err)
}
var unchangedPlan []BattleAction
if err := json.Unmarshal(unchanged, &unchangedPlan); err != nil || len(unchangedPlan) != 1 || unchangedPlan[0].CostumeIndex != -1 {
t.Fatalf("omitted plan changed value: %#v err=%v", unchangedPlan, err)
}
preset.BattlePlan = []BattleAction{}
if err := store.persistPresetLocked(ctx, preset); err != nil {
t.Fatal(err)
}
payload, found, err := mem.LoadEntry("deck", "battle_plans", "0")
if err != nil || !found {
t.Fatalf("empty plan was not persisted: found=%v err=%v", found, err)
}
var decoded []BattleAction
if err := json.Unmarshal(payload, &decoded); err != nil || decoded == nil {
t.Fatalf("stored empty plan=%s err=%v", payload, err)
}
seed := Seed{Version: versionconfig.State(), FieldDeck: []FieldEntry{{CharacterInvenIndex: 1, Slot: 1}}}
storeCore, err := store.corePayloadLocked()
if err != nil {
t.Fatal(err)
}
if err := mem.Save("deck", storeCore); err != nil {
t.Fatal(err)
}
reopened, err := OpenStore(ctx, stateio.RootStore{}, seed, gamedata.PresetDesign{BaseCount: 1, Maximum: 1, PriceType: 4, Price: 2000, Icons: map[uint64]bool{}})
if err != nil {
t.Fatal(err)
}
if plan := reopened.presets[0].BattlePlan; plan == nil || len(plan) != 0 {
t.Fatalf("explicit clear did not replace old plan: %#v", plan)
}
}
func TestBattlePlanWireRejectsInvalidSchemasAndShape(t *testing.T) {
if _, err := decodeBattlePlan(nil); err == nil {
t.Fatal("missing schema accepted")
}
if _, err := decodeBattlePlan(wire.AppendVarint(nil, 1, 2)); err == nil {
t.Fatal("unsupported schema accepted")
}
s := &Store{}
preset := Preset{Decks: []PresetDeck{{Deck: DeckEntry{CharacterInvenIndex: 7}}, {Deck: DeckEntry{CharacterInvenIndex: 8}}}}
for _, plan := range [][]BattleAction{{{CharacterIndex: 7}, {CharacterIndex: 7}}, {{CharacterIndex: 7}, {CharacterIndex: 8}, {CharacterIndex: 9}}, {{CharacterIndex: 7, CostumeIndex: -2}}} {
if err := s.validateBattlePlan(preset, plan); err == nil {
t.Fatalf("invalid plan accepted: %#v", plan)
}
}
}
func TestBattlePlanRejectsWrongCostumeAndBurst(t *testing.T) {
mem := stateio.NewMemory()
ctx := command.Context{State: mem}
collection, err := roster.OpenCollectionStore(ctx, stateio.RootStore{}, []roster.Costume{{InvenIndex: 90, ID: 9, UseChar: 8, BurstLevel: 1}, {InvenIndex: 91, ID: 10, UseChar: 7, BurstLevel: 1}})
if err != nil {
t.Fatal(err)
}
s := &Store{collection: collection}
preset := Preset{Decks: []PresetDeck{{Deck: DeckEntry{CharacterInvenIndex: 7}}}}
for _, action := range []BattleAction{{CharacterIndex: 7, CostumeIndex: 90}, {CharacterIndex: 7, CostumeIndex: 91, BurstLevel: 2}} {
if err := s.validateBattlePlan(preset, []BattleAction{action}); err == nil {
t.Fatalf("invalid costume action accepted: %#v", action)
}
}
}
func TestClipBattlePlanDropsMembersRemovedFromPreset(t *testing.T) {
preset := Preset{Decks: []PresetDeck{{Deck: DeckEntry{CharacterInvenIndex: 7}}}}
got := clipBattlePlan(preset, []BattleAction{{CharacterIndex: 7}, {CharacterIndex: 8}})
if len(got) != 1 || got[0].CharacterIndex != 7 {
t.Fatalf("clipped plan = %#v", got)
}
}
+14 -1
View File
@@ -72,6 +72,7 @@ type Store struct {
presetSlots uint64
presetDesign gamedata.PresetDesign
costumeSettings map[uint64]CostumeSetting
activePreset *uint64
wallet *assets.Wallet
characters *roster.CharacterStore
equipment *assets.EquipmentInventory
@@ -193,7 +194,7 @@ func OpenStore(ctx command.Context, storage stateio.Store, seed Seed, designs ..
return nil, fmt.Errorf("deck: load state: %w", e)
}
if b == nil {
if e = stateio.RequireNoEntries(entries, ctx.State, "deck", "presets", "preset_config", "costume_settings", "field_settings"); e != nil {
if e = stateio.RequireNoEntries(entries, ctx.State, "deck", "presets", "preset_config", "battle_plans", "active_preset", "costume_settings", "field_settings"); e != nil {
return nil, fmt.Errorf("deck: invalid entry storage: %w", e)
}
return s, nil
@@ -215,6 +216,18 @@ func OpenStore(ctx command.Context, storage stateio.Store, seed Seed, designs ..
if e = s.loadPresetEntries(ctx); e != nil {
return nil, e
}
if e = s.loadBattlePlans(ctx); e != nil {
return nil, e
}
if raw, found, e := entries.LoadEntry(ctx.State, "deck", "active_preset", "slot"); e != nil {
return nil, e
} else if found {
var slot uint64
if e = json.Unmarshal(raw, &slot); e != nil || slot >= s.presetSlots {
return nil, errors.New("deck: invalid active preset")
}
s.activePreset = &slot
}
return s, nil
}
func (s *Store) EnsurePersisted(ctx command.Context) error {
@@ -15,12 +15,13 @@ import (
)
type Preset struct {
Name string `json:"name"`
ResourceID uint64 `json:"resource_id"`
ResourceColor uint64 `json:"resource_color"`
Slot uint64 `json:"slot"`
Decks []PresetDeck `json:"decks"`
Blesses []PresetBless `json:"blesses"`
Name string `json:"name"`
ResourceID uint64 `json:"resource_id"`
ResourceColor uint64 `json:"resource_color"`
Slot uint64 `json:"slot"`
Decks []PresetDeck `json:"decks"`
Blesses []PresetBless `json:"blesses"`
BattlePlan []BattleAction `json:"-"`
}
type PresetDeck struct {
@@ -58,6 +59,13 @@ func (s *Store) AttachPresetRuntime(ctx command.Context, wallet *assets.Wallet,
}
s.wallet, s.characters, s.equipment, s.collection = wallet, characters, equipment, collection
for _, preset := range s.presets {
if preset.BattlePlan != nil {
if err := s.validateBattlePlan(preset, preset.BattlePlan); err != nil {
return fmt.Errorf("deck: saved battle plan %d: %w", preset.Slot, err)
}
}
}
return s.validatePresetOwnershipLocked(ctx)
}
@@ -236,7 +244,15 @@ func (s *Store) persistPresetLocked(ctx command.Context, p Preset) error {
if err != nil {
return err
}
return s.storage.SaveWithEntries(ctx.State, "deck", core, []stateio.EntryMutation{{Bucket: "presets", Key: strconv.FormatUint(p.Slot, 10), Payload: payload}})
changes := []stateio.EntryMutation{{Bucket: "presets", Key: strconv.FormatUint(p.Slot, 10), Payload: payload}}
if p.BattlePlan != nil {
plan, err := battlePlanMutation(p)
if err != nil {
return err
}
changes = append(changes, plan)
}
return s.storage.SaveWithEntries(ctx.State, "deck", core, changes)
}
func (s *Store) corePayloadLocked() ([]byte, error) {
@@ -277,6 +277,12 @@ func decodePreset(data []byte) (Preset, error) {
return err
}
p.Blesses = append(p.Blesses, bless)
case 100:
plan, err := decodeBattlePlan(field.Value)
if err != nil {
return err
}
p.BattlePlan = plan
}
return nil
})
@@ -399,6 +405,10 @@ func presetWire(p Preset) []byte {
}
out = wire.AppendBytes(out, 6, b)
}
// Every preset advertises the extension. An empty plan means the player has
// explicitly cleared it (or has never configured it), while a missing field
// is reserved for old servers and is never emitted by this implementation.
out = wire.AppendBytes(out, 100, battlePlanWire(p.BattlePlan))
return out
}
@@ -452,6 +462,13 @@ func (s *Store) handlePresetInfo(request []byte) (int, []byte, bool, error) {
for _, slot := range slots {
response = wire.AppendBytes(response, 1, presetWire(s.presets[slot]))
}
// Field 100 is the FBattle capability marker. It is deliberately present
// even for a new account with no ordinary presets, allowing the plugin to
// open the editor and save its first plan without guessing server support.
response = wire.AppendBytes(response, 100, battlePlanWire(nil))
if s.activePreset != nil {
response = wire.AppendVarint(response, 101, *s.activePreset)
}
return 178, response, true, nil
}
@@ -475,6 +492,16 @@ func (s *Store) handlePresetSave(ctx command.Context, request []byte) (int, []by
if s.characters == nil || s.collection == nil || s.equipment == nil {
return 0, nil, true, errors.New("deck: preset runtime unavailable")
}
if p, exists := s.presets[preset.Slot]; exists && preset.BattlePlan == nil {
// Old clients omit the extension. Preserve their saved actions, pruning
// only characters removed from this newly submitted preset.
preset.BattlePlan = clipBattlePlan(preset, p.BattlePlan)
}
if preset.BattlePlan != nil {
if err := s.validateBattlePlan(preset, preset.BattlePlan); err != nil {
return 0, nil, true, fmt.Errorf("deck: invalid battle plan: %w", err)
}
}
if err := s.validatePresetOwnedLocked(ctx, preset); err != nil {
return 0, nil, true, fmt.Errorf("deck: invalid preset: %w", err)
}
@@ -482,8 +509,9 @@ func (s *Store) handlePresetSave(ctx command.Context, request []byte) (int, []by
return 0, nil, true, fmt.Errorf("deck: persist preset: %w", err)
}
s.presets[preset.Slot] = preset
s.rememberReplyLocked(ctx, "save", seq, 179, nil)
return 179, nil, true, nil
body := wire.AppendBytes(nil, 100, battlePlanWire(preset.BattlePlan))
s.rememberReplyLocked(ctx, "save", seq, 179, body)
return 179, body, true, nil
}
func (s *Store) handlePresetAddSlot(ctx command.Context, request []byte) (int, []byte, bool, error) {
@@ -614,6 +642,10 @@ func (s *Store) handlePresetDelete(ctx command.Context, request []byte) (int, []
}
seen[slot] = true
changes = append(changes, stateio.EntryMutation{Bucket: "presets", Key: strconv.FormatUint(slot, 10), Delete: true})
changes = append(changes, stateio.EntryMutation{Bucket: "battle_plans", Key: strconv.FormatUint(slot, 10), Delete: true})
if s.activePreset != nil && *s.activePreset == slot {
changes = append(changes, stateio.EntryMutation{Bucket: "active_preset", Key: "slot", Delete: true})
}
}
core, err := s.corePayloadLocked()
if err != nil {
@@ -624,6 +656,9 @@ func (s *Store) handlePresetDelete(ctx command.Context, request []byte) (int, []
}
for slot := range seen {
delete(s.presets, slot)
if s.activePreset != nil && *s.activePreset == slot {
s.activePreset = nil
}
}
// 2.36.7 contains the request/response classes but no PacketCode enum
// member. Code zero is the same compatibility fallback used for other
@@ -678,7 +713,7 @@ func (s *Store) handlePresetUse(ctx command.Context, request []byte) (int, []byt
next := clone(s.state)
next.Deck = append([]DeckEntry(nil), deckEntries...)
maps.Copy(next.Costumes, assignments)
if err := s.commit(ctx, next); err != nil {
if err := s.persistActivePreset(ctx, next, slot); err != nil {
return 0, nil, true, fmt.Errorf("deck: persist applied preset: %w", err)
}
var response []byte
@@ -714,10 +749,31 @@ func (s *Store) handlePresetUse(ctx command.Context, request []byte) (int, []byt
}
response = wire.AppendBytes(response, 3, info)
}
response = wire.AppendBytes(response, 100, battlePlanWire(preset.BattlePlan))
response = wire.AppendVarint(response, 101, slot)
s.rememberReplyLocked(ctx, "use", seq, 409, response)
return 409, response, true, nil
}
func (s *Store) persistActivePreset(ctx command.Context, next state, slot uint64) error {
activePayload, err := json.Marshal(slot)
if err != nil {
return err
}
if s.storage != nil {
core, err := json.MarshalIndent(next, "", " ")
if err != nil {
return err
}
if err := s.storage.SaveWithEntries(ctx.State, "deck", append(core, '\n'), []stateio.EntryMutation{{Bucket: "active_preset", Key: "slot", Payload: activePayload}}); err != nil {
return err
}
}
s.state = next
s.activePreset = &slot
return nil
}
func costumeSettingWire(setting CostumeSetting) []byte {
out := wire.AppendVarint(nil, 1, setting.CharacterIndex)
for _, item := range setting.Sequence {
+251
View File
@@ -0,0 +1,251 @@
using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace Bd2FBattle;
// One copy of the battle's action card, drawn from preset data instead of a
// live BattleCharData: the same artwork, range grid, SP and burst bubbles,
// burst arrows and element selection effect the player sees in battle.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0031", Justification = "UnityEngine.Object null checks also detect destroyed native objects.")]
internal sealed class ActionCard
{
private static readonly Color32[] DefaultElementColors =
[new(56, 104, 180, 255), new(156, 56, 56, 255), new(45, 96, 57, 255), new(237, 173, 103, 255), new(187, 29, 226, 255), new(191, 191, 191, 255)];
private readonly ActionCatalog catalog;
private readonly Color32[] elementColors;
private readonly GameObject normal, skill, focus, burstArrows;
private readonly GameObject statsObject, bubbleTemplate;
private readonly UISprite stats, attackRange, skillRange, skillIcon, skillLevel;
private readonly GameObject attackArrow, targetParent;
private readonly Transform knockBackIcon, bubbles;
private readonly TMP_Text damage, attackTarget, skillTarget;
private readonly RawImage artwork;
private readonly TextureLease art;
private readonly (GameObject On, GameObject Off) left, right;
private readonly List<GameObject> bubblePool = [];
private bool? skillArt;
internal ActionOption Option { get; }
internal RectTransform Root { get; }
internal Transform SelectEffectParent { get; }
internal Transform BurstEffectParent { get; }
internal Button Choose { get; }
internal Button BurstDown { get; }
internal Button BurstUp { get; }
internal int Burst { get; set; }
internal ActionCard(NativeActionControls native, Transform parent, ActionCatalog owner, ActionOption option)
{
catalog = owner;
Option = option;
GameObject copy = NativeActionControls.Dormant(native.CardTemplate, "Action " + option.Index);
BattleUIComponent_CharActionSelectItem card = copy.GetComponent<BattleUIComponent_CharActionSelectItem>();
elementColors = NativeActionControls.Field<Color32[]>(card, "_targetImgElementColors") is { Length: >= 6 } colors ? colors : DefaultElementColors;
normal = Required<GameObject>(card, "_objDefault");
skill = Required<GameObject>(card, "_objSkill");
targetParent = Required<GameObject>(card, "_objTargetParent");
stats = Required<UISprite>(card, "_imgAttackIcon");
statsObject = stats.gameObject;
damage = Required<TMP_Text>(card, "_textDefaultDamage");
knockBackIcon = Required<Transform>(card, "_transformKnockBackIcon");
object attack = Required<object>(card, "_attackTargetRange");
attackTarget = NativeActionControls.Field<TMP_Text>(attack, "_textTargetType");
attackRange = Required<UISprite>(attack, "_imgTargetRange");
attackArrow = NativeActionControls.Field<GameObject>(attack, "_objKnockBackArrow");
object range = Required<object>(card, "_skillTargetRange");
skillTarget = NativeActionControls.Field<TMP_Text>(range, "_textTargetType");
skillRange = Required<UISprite>(range, "_imgTargetRange");
skillIcon = Required<UISprite>(card, "_imgSkillIcon");
skillLevel = NativeActionControls.Field<UISprite>(card, "_imgSkillLevel");
artwork = Required<RawImage>(card, "_imgChar");
bubbles = Required<GameObject>(card, "_objBubbleLayout").transform;
bubbleTemplate = Required<Component>(card, "_originBubble").gameObject;
SelectEffectParent = NativeActionControls.Field<Transform>(card, "_transformSelectEffect");
BurstEffectParent = NativeActionControls.Field<Transform>(card, "_transformBurstEffect");
focus = NativeActionControls.Field<GameObject>(card, "_objCostumeUseSequenceFocus");
Component burst = NativeActionControls.Field<Component>(card, "_burstUI");
burstArrows = burst?.gameObject;
left = Arrow(NativeActionControls.Field<Component>(burst, "_btnLeft"));
right = Arrow(NativeActionControls.Field<Component>(burst, "_btnRight"));
Hide(card, "_objMonsterCharIcon", "_objDisable", "_objCoolTime", "_objSilence", "_objInterrupt", "_objBan", "_objInfinite");
Hide(card, "_spritePrestigeSkinIcon");
object priority = NativeActionControls.Field<object>(card, "_priorityToggle");
Hide(priority, "_objRoot");
object golem = NativeActionControls.Field<object>(card, "_golemToggle");
Hide(golem, "_objRoot");
NativeActionControls.Strip(copy, script => script is BattleCharSkillItemBubble || script is BattleCharSkillItemBubbleBurst ||
script is ButtonOnOffComponent || script is BattleUIComponent_CharActionSelectItem_BurstUI);
bubbleTemplate.SetActive(false);
Root = NativeActionControls.Place(NativeActionControls.Wake(copy, parent), parent, 0, 0, NativeActionControls.CardSize.x, NativeActionControls.CardSize.y);
Root.anchorMin = Root.anchorMax = Root.pivot = new Vector2(0, 1);
art = artwork.gameObject.AddComponent<TextureLease>();
Choose = Clickable(copy, copy.GetComponentInChildren<Graphic>(true));
BurstDown = left.On == null ? null : Clickable(left.On.transform.parent.gameObject, left.On.GetComponentInChildren<Graphic>(true));
BurstUp = right.On == null ? null : Clickable(right.On.transform.parent.gameObject, right.On.GetComponentInChildren<Graphic>(true));
if (SelectEffectParent != null) SelectEffectParent.gameObject.SetActive(false);
if (BurstEffectParent != null) BurstEffectParent.gameObject.SetActive(false);
Draw();
}
private static T Required<T>(object owner, string name) where T : class =>
NativeActionControls.Field<T>(owner, name) ?? throw new MissingMemberException("Native action card " + name + " unavailable.");
private static void Hide(object owner, params string[] names)
{
foreach (string name in names)
{
object value = NativeActionControls.Field<object>(owner, name);
GameObject target = value as GameObject ?? (value as Component)?.gameObject;
if (target != null) target.SetActive(false);
}
}
private static (GameObject, GameObject) Arrow(Component button) =>
(NativeActionControls.Field<GameObject>(button, "_objOn"), NativeActionControls.Field<GameObject>(button, "_objOff"));
private static Button Clickable(GameObject target, Graphic surface)
{
if (surface != null) surface.raycastTarget = true;
Button button = target.AddComponent<Button>();
button.transition = Selectable.Transition.None;
button.targetGraphic = surface;
return button;
}
// Draws the parts that never change: what the action is and how it hits.
private void Draw()
{
Color color = elementColors[Math.Max(0, Math.Min(elementColors.Length - 1, catalog.Element))];
bool isSkill = Option.IsSkill;
normal.SetActive(!isSkill);
skill.SetActive(isSkill);
if (burstArrows != null) burstArrows.SetActive(false);
if (focus != null) focus.SetActive(false);
if (isSkill)
{
skillIcon.SetSprite(Option.SkillIcon);
if (skillLevel != null)
{
skillLevel.gameObject.SetActive(Option.Costume.Level > 0);
if (Option.Costume.Level > 0) skillLevel.SetSprite($"upgrade_{Option.Costume.Level}");
}
if (skillTarget != null)
skillTarget.text = LocalTextInfo.GetText(CostumeInfo.GetTargetTypeTextId(Option.Skill, Option.Skill.BuffId.Count > 0 ? Option.Skill.BuffId[0] : 0));
skillRange.color = color;
return;
}
knockBackIcon.gameObject.SetActive(false);
if (attackArrow != null) attackArrow.SetActive(false);
damage.text = Option.Name;
if (Option.IsDefault)
{
statsObject.SetActive(false);
targetParent.SetActive(false);
return;
}
CostumeInfoDTO costume = catalog.AppearanceInfo;
targetParent.SetActive(true);
attackRange.color = color;
attackRange.gameObject.SetActive(true);
if (Option.Index == 0)
{
statsObject.SetActive(true);
stats.SetSprite(costume.AttackType == (int)ECostumeAttackType.PHYSICAL ? "icon_stats_physical" : "icon_stats_magical");
attackRange.SetSprite($"range{costume.AttackRangeCount}_{costume.AttackRange}");
if (attackTarget != null) attackTarget.text = LocalTextInfo.GetText(CostumeInfo.GetTargetTypeTextId(catalog.AppearanceSkill, 0));
return;
}
statsObject.SetActive(false);
attackRange.SetSprite(SkillInfo.GetKnockBackType(costume.NorSubAttackBuffId).GetKnockBackImageName());
if (attackArrow != null) attackArrow.SetActive(true);
if (attackTarget != null) attackTarget.text = LocalTextInfo.GetText(2052);
knockBackIcon.rotation = Quaternion.Euler(0, 0, KnockBackRotation(SkillInfo.GetBuffTable(costume.NorSubAttackBuffId)?.SubType ?? 0));
knockBackIcon.gameObject.SetActive(true);
}
private static float KnockBackRotation(int subType) => subType switch
{
2 => 180,
3 => 270,
4 => 90,
5 => 135,
6 => 45,
7 => 225,
8 => 315,
_ => 0,
};
// Draws what depends on the player's choice, as the battle card does for
// its reserved action: skill artwork, filled burst bubbles and arrows.
internal void Refresh(bool selected, bool busy, bool effectShown, int available)
{
Choose.interactable = !busy;
if (focus != null) focus.SetActive(selected && !effectShown);
if (!Option.IsSkill) return;
bool useSkillArt = selected;
if (skillArt != useSkillArt)
{
skillArt = useSkillArt;
art.Load(artwork, Option.Costume.CostumeDesignId, useSkillArt);
}
skillRange.SetSprite(Option.Range(Burst));
int burstSp = Option.BurstSp(Burst);
int baseSp = Math.Max(0, Option.Sp(Burst) - burstSp);
int slots = Option.BurstSp(Option.MaxBurst);
int index = 0;
// Dimmed bubbles mark a skill the first turn's SP cannot pay for.
BattleCharSkillItemBubble.States baseState = selected ? BattleCharSkillItemBubble.States.SELECT :
Option.Sp(0) > available ? BattleCharSkillItemBubble.States.NOT_ENOUGHT : BattleCharSkillItemBubble.States.NORMAL;
for (int i = 0; i < baseSp; i++) Bubble(index++, baseState);
for (int i = 0; i < slots; i++)
Bubble(index++, selected && i < burstSp ? BattleCharSkillItemBubble.States.BURST : BattleCharSkillItemBubble.States.BURST_EMPTY);
for (; index < bubblePool.Count; index++) bubblePool[index].SetActive(false);
bool arrows = selected && Option.MaxBurst > 0 && burstArrows != null;
if (burstArrows != null) burstArrows.SetActive(arrows);
SetArrow(left, BurstDown, arrows && Burst > 0, busy);
SetArrow(right, BurstUp, arrows && Burst < Option.MaxBurst, busy);
}
private static void SetArrow((GameObject On, GameObject Off) arrow, Button button, bool enabled, bool busy)
{
if (arrow.On != null) arrow.On.SetActive(enabled);
if (arrow.Off != null) arrow.Off.SetActive(!enabled);
if (button != null) button.interactable = enabled && !busy;
}
// Mirrors BattleCharSkillItemBubble.Set on a copy of the card's bubble.
private void Bubble(int index, BattleCharSkillItemBubble.States state)
{
while (bubblePool.Count <= index)
{
GameObject copy = UnityEngine.Object.Instantiate(bubbleTemplate, bubbles, false);
copy.name = "Image - Bubble " + bubblePool.Count;
bubblePool.Add(copy);
}
Transform bubble = bubblePool[index].transform;
bool burst = state is BattleCharSkillItemBubble.States.BURST or BattleCharSkillItemBubble.States.BURST_EMPTY;
Show(bubble, "Image - BubbleNormal", state == BattleCharSkillItemBubble.States.NORMAL);
Show(bubble, "Image - BubbleSelect", state == BattleCharSkillItemBubble.States.SELECT);
Show(bubble, "Image - BubbleDimd", state == BattleCharSkillItemBubble.States.NOT_ENOUGHT);
Show(bubble, "Image - BubbleNormal - Plus", false);
Show(bubble, "Image - BubbleNormal - Minus", false);
Transform slot = bubble.Find("BurstSlot");
if (slot != null)
{
slot.gameObject.SetActive(burst);
Show(slot, "Image - BubbleBurstBg", state == BattleCharSkillItemBubble.States.BURST_EMPTY);
Show(slot, "Image - BubbleBurst", state == BattleCharSkillItemBubble.States.BURST);
}
bubble.gameObject.SetActive(true);
}
private static void Show(Transform parent, string name, bool active)
{
Transform child = parent.Find(name);
if (child != null) child.gameObject.SetActive(active);
}
}
+77
View File
@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BDNetwork;
using Proto.Design.common;
using Proto.Net;
using TextComponent = BD2.GameSdk.Component;
namespace Bd2FBattle;
internal sealed class ActionCatalog
{
internal CharDBInfo Character { get; }
internal CharTable Definition { get; }
internal CostumeDBInfo Appearance { get; }
internal CostumeInfoDTO AppearanceInfo { get; }
internal SkillTable AppearanceSkill { get; }
internal int Element => Definition.Element;
internal string Name => LocalTextInfo.GetNameText(Definition.CharNameTextId);
internal List<ActionOption> Options { get; } = [];
internal ActionCatalog(DeckDBInfo deck, PresetDBInfo preset)
{
Character = CommonPacket.GetCharInfo(deck.CharInvenIndex) ?? throw new InvalidOperationException("Preset character is unavailable.");
Definition = CharInfo.GetCharInfo(Character.Id);
long costumeIndex = preset.DeckInfo.FirstOrDefault(item => item.DeckBaseInfo?.CharInvenIndex == Character.InvenIndex)?.CostumeInvenIndex ?? Character.UseCostume;
Appearance = CostumePacket.GetCostumeDBInfo(costumeIndex) ?? CostumePacket.GetCostumeDBInfo(Character.UseCostume) ??
throw new InvalidOperationException("Preset costume is unavailable.");
AppearanceInfo = CostumeInfo.GetCostumeInfo(Appearance.Id);
AppearanceSkill = SkillInfo.GetSkillInfo(AppearanceInfo.SkillGroupId, Appearance.Level);
Options.Add(new ActionOption(long.MinValue, Text("fbattle.action.default")));
Options.Add(new ActionOption(0, Text("fbattle.action.attack")));
Options.Add(new ActionOption(-1, Text("fbattle.action.knockback")));
CostumePacket.GetCostumeDBInfoList(Character, out List<CostumeDBInfo> costumes);
foreach (CostumeDBInfo costume in costumes.OrderBy(item => item.InvenIndex == costumeIndex ? 0 : 1).ThenBy(item => item.Id))
Options.Add(new ActionOption(costume));
}
internal static string Text(string key) => TextComponent.Translatable(key).GetString();
}
internal sealed class ActionOption
{
internal long Index { get; }
internal string Name { get; }
internal CostumeDBInfo Costume { get; }
internal CostumeInfoDTO Definition { get; }
internal SkillTable Skill { get; }
internal string SkillIcon { get; }
internal bool IsSkill => Costume != null;
internal bool IsDefault => Index == long.MinValue;
internal int MaxBurst => Math.Max(0, Costume?.BurstLevel ?? 0);
internal ActionOption(long index, string name) { Index = index; Name = name; }
internal ActionOption(CostumeDBInfo costume)
{
Costume = costume;
Index = costume.InvenIndex;
Definition = CostumeInfo.GetCostumeInfo(costume.Id);
Name = LocalTextInfo.GetNameText(Definition.CostumeNameTextId);
Skill = SkillInfo.GetSkillInfo(Definition.SkillGroupId, costume.Level);
SkillIcon = SkillInfo.GetSkillDesignTable(Skill.SkillDesignId).SkillIconSpriteName;
}
internal int Sp(int burst) => IsSkill ? SkillInfo.GetSpReqCount(Skill, Costume.Id, [.. Costume.PotentialId], burst, null) : 0;
// SP the burst levels add on top of the skill, as the battle card counts its burst bubbles.
internal int BurstSp(int burst) => IsSkill ? CostumeInfo.GetCostumeBurstTableNeedSp(Skill.GroupId, burst) : 0;
internal string Range(int burst)
{
if (!IsSkill) return null;
(int range, int count) = SkillInfo.GetAttackRangeOption(Skill, Costume.Id, [.. Costume.PotentialId], null, burst);
return $"range{count}_{range}";
}
}
+18
View File
@@ -0,0 +1,18 @@
using System;
namespace Bd2FBattle;
internal sealed class ActionChoice(long characterIndex, long costumeIndex, int burstLevel) : IEquatable<ActionChoice>
{
internal long CharacterIndex { get; } = characterIndex;
internal long CostumeIndex { get; } = costumeIndex;
internal int BurstLevel { get; } = burstLevel;
internal ActionChoice Clone() => new(CharacterIndex, CostumeIndex, BurstLevel);
public bool Equals(ActionChoice other) => other != null && CharacterIndex == other.CharacterIndex &&
CostumeIndex == other.CostumeIndex && BurstLevel == other.BurstLevel;
public override bool Equals(object obj) => obj is ActionChoice other && Equals(other);
public override int GetHashCode() => HashCode.Combine(CharacterIndex, CostumeIndex, BurstLevel);
}
+131
View File
@@ -0,0 +1,131 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Google.Protobuf;
namespace Bd2FBattle;
internal static class ActionPlanWire
{
internal const int PlanField = 100;
internal const int ActiveSlotField = 101;
internal static byte[] ReplacePlan(byte[] preset, IEnumerable<ActionChoice> choices)
{
using var stream = new MemoryStream();
using (var input = new CodedInputStream(preset))
{
while (!input.IsAtEnd)
{
int start = checked((int)input.Position);
uint tag = input.ReadTag();
if (tag == 0) break;
input.SkipLastField();
if (WireFormat.GetTagFieldNumber(tag) != PlanField)
stream.Write(preset, start, checked((int)input.Position) - start);
}
}
byte[] extension = Extension(choices);
stream.Write(extension, 0, extension.Length);
return stream.ToArray();
}
internal static byte[] Extension(IEnumerable<ActionChoice> choices)
{
using var planStream = new MemoryStream();
using (var writer = new CodedOutputStream(planStream, true))
{
writer.WriteTag(1, WireFormat.WireType.Varint);
writer.WriteUInt32(1);
foreach (ActionChoice choice in choices.OrderBy(c => c.CharacterIndex))
{
using var entryStream = new MemoryStream();
using (var entry = new CodedOutputStream(entryStream, true))
{
entry.WriteTag(1, WireFormat.WireType.Varint);
entry.WriteInt64(choice.CharacterIndex);
entry.WriteTag(2, WireFormat.WireType.Varint);
entry.WriteInt64(choice.CostumeIndex);
entry.WriteTag(3, WireFormat.WireType.Varint);
entry.WriteInt32(choice.BurstLevel);
}
writer.WriteTag(2, WireFormat.WireType.LengthDelimited);
writer.WriteBytes(ByteString.CopyFrom(entryStream.ToArray()));
}
}
using var stream = new MemoryStream();
using (var output = new CodedOutputStream(stream, true))
{
output.WriteTag(PlanField, WireFormat.WireType.LengthDelimited);
output.WriteBytes(ByteString.CopyFrom(planStream.ToArray()));
}
return stream.ToArray();
}
internal static bool TryRead(byte[] raw, out Dictionary<long, ActionChoice> choices, out int? activeSlot)
{
choices = null;
activeSlot = null;
using var input = new CodedInputStream(raw);
uint tag;
while ((tag = input.ReadTag()) != 0)
{
if (tag == WireFormat.MakeTag(PlanField, WireFormat.WireType.LengthDelimited))
{
if (choices != null) throw new InvalidDataException("Duplicate FBattle action plan");
choices = DecodePlan(input.ReadBytes().ToByteArray());
}
else if (tag == WireFormat.MakeTag(ActiveSlotField, WireFormat.WireType.Varint))
{
activeSlot = checked((int)input.ReadUInt64());
}
else input.SkipLastField();
}
return choices != null;
}
private static Dictionary<long, ActionChoice> DecodePlan(byte[] raw)
{
var choices = new Dictionary<long, ActionChoice>();
int schema = 0;
using var input = new CodedInputStream(raw);
uint tag;
while ((tag = input.ReadTag()) != 0)
{
switch (tag)
{
case 8: schema = input.ReadInt32(); break;
case 18:
ActionChoice choice = DecodeChoice(input.ReadBytes().ToByteArray());
if (choices.Count >= 12 || choices.ContainsKey(choice.CharacterIndex))
throw new InvalidDataException("Invalid FBattle action plan members");
choices.Add(choice.CharacterIndex, choice);
break;
default: input.SkipLastField(); break;
}
}
if (schema != 1) throw new InvalidDataException("Unsupported FBattle action plan format");
return choices;
}
private static ActionChoice DecodeChoice(byte[] raw)
{
long character = 0, costume = 0;
int burst = 0;
using var input = new CodedInputStream(raw);
uint tag;
while ((tag = input.ReadTag()) != 0)
{
switch (tag)
{
case 8: character = input.ReadInt64(); break;
case 16: costume = input.ReadInt64(); break;
case 24: burst = input.ReadInt32(); break;
default: input.SkipLastField(); break;
}
}
if (character <= 0 || costume < -1 || burst < 0 || (costume <= 0 && burst != 0))
throw new InvalidDataException("Invalid FBattle action choice");
return new ActionChoice(character, costume, burst);
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"fbattle.entry": "Actions",
"fbattle.title": "Preset Actions",
"fbattle.info": "Choose each character's first-turn action; on a selected skill, the arrows set its burst. Burst 0 still casts the skill, and later turns follow the game. Drag sideways for more actions.",
"fbattle.action.default": "Follow game",
"fbattle.action.attack": "Normal attack",
"fbattle.action.knockback": "Knockback",
"fbattle.sp_total": "First-turn skills: {0} / {1} SP",
"fbattle.sp_partial": "Chosen actions: {0} / {1} SP (excludes characters following the game)",
"fbattle.unsaved": "Unsaved changes",
"fbattle.saved": "Saved",
"fbattle.saving": "Saving preset and actions…",
"fbattle.save_failed": "Save failed. Your changes remain open; please try again.",
"fbattle.open_failed": "Unable to open the action editor. Please check the plugin log.",
"fbattle.empty": "Add characters to the preset first.",
"fbattle.save": "Save",
"fbattle.cancel": "Cancel",
"fbattle.discard": "Discard changes",
"fbattle.confirm.title": "Save preset actions?",
"fbattle.confirm.message": "Your action changes have not been saved. Save also saves this preset's characters, positions and equipment. Discard leaves the actions unchanged. Cancel returns to editing.",
"fbattle.server_required": "This server does not support preset actions. Please update the server.",
"fbattle.request_failed": "Unable to load or save preset actions. Please try again later."
}
+23
View File
@@ -0,0 +1,23 @@
{
"fbattle.entry": "行動設定",
"fbattle.title": "プリセットの行動設定",
"fbattle.info": "各キャラクターの初回行動を選びます。選択中のスキルは左右の矢印でバーストを調整できます。バースト 0 でもスキルを使用し、以降のターンはゲームに従います。横にドラッグすると他の行動を表示します。",
"fbattle.action.default": "ゲームに従う",
"fbattle.action.attack": "通常攻撃",
"fbattle.action.knockback": "ノックバック",
"fbattle.sp_total": "初回スキル合計:{0} / {1} SP",
"fbattle.sp_partial": "指定済みの行動:{0} / {1} SP(ゲームに従うキャラを除く)",
"fbattle.unsaved": "未保存の変更あり",
"fbattle.saved": "保存済み",
"fbattle.saving": "プリセットと行動を保存中…",
"fbattle.save_failed": "保存に失敗しました。変更内容は保持されています。再度お試しください。",
"fbattle.open_failed": "行動設定を開けません。プラグインログを確認してください。",
"fbattle.empty": "先にプリセットにキャラクターを追加してください。",
"fbattle.save": "保存",
"fbattle.cancel": "キャンセル",
"fbattle.discard": "変更を破棄",
"fbattle.confirm.title": "行動設定を保存しますか?",
"fbattle.confirm.message": "行動設定に未保存の変更があります。保存すると現在のキャラ・配置・装備も保存します。破棄すると行動設定を変更せずに閉じます。キャンセルで編集を続けます。",
"fbattle.server_required": "このサーバーはプリセットの行動設定に対応していません。サーバーを更新してください。",
"fbattle.request_failed": "プリセットの行動設定を読み込み、または保存できません。後でもう一度お試しください。"
}
+23
View File
@@ -0,0 +1,23 @@
{
"fbattle.entry": "행동 설정",
"fbattle.title": "프리셋 행동 설정",
"fbattle.info": "캐릭터별 첫 턴 행동을 선택합니다. 선택한 스킬은 좌우 화살표로 버스트를 조절합니다. 버스트 0도 스킬을 사용하며 이후 턴은 게임을 따릅니다. 가로로 드래그하면 다른 행동을 볼 수 있습니다.",
"fbattle.action.default": "게임 설정 따르기",
"fbattle.action.attack": "일반 공격",
"fbattle.action.knockback": "넉백",
"fbattle.sp_total": "첫 턴 스킬 합계: {0} / {1} SP",
"fbattle.sp_partial": "지정한 행동: {0} / {1} SP (게임 설정을 따르는 캐릭터 제외)",
"fbattle.unsaved": "저장하지 않은 변경 사항",
"fbattle.saved": "저장됨",
"fbattle.saving": "프리셋과 행동을 저장하는 중…",
"fbattle.save_failed": "저장하지 못했습니다. 변경 사항은 유지됩니다. 다시 시도해 주세요.",
"fbattle.open_failed": "행동 편집기를 열 수 없습니다. 플러그인 로그를 확인해 주세요.",
"fbattle.empty": "먼저 프리셋에 캐릭터를 추가해 주세요.",
"fbattle.save": "저장",
"fbattle.cancel": "취소",
"fbattle.discard": "변경 버리기",
"fbattle.confirm.title": "행동 설정을 저장할까요?",
"fbattle.confirm.message": "저장하지 않은 행동 변경 사항이 있습니다. 저장하면 현재 캐릭터, 위치, 장비도 함께 저장합니다. 버리면 행동 설정을 변경하지 않고 닫습니다. 취소하면 편집을 계속합니다.",
"fbattle.server_required": "현재 서버는 프리셋 행동 설정을 지원하지 않습니다. 서버를 업데이트해 주세요.",
"fbattle.request_failed": "프리셋 행동 설정을 불러오거나 저장할 수 없습니다. 나중에 다시 시도해 주세요."
}
+23
View File
@@ -0,0 +1,23 @@
{
"fbattle.entry": "出手方式",
"fbattle.title": "编辑出手方式",
"fbattle.info": "选择每位角色首轮的招式;选中技能后可用左右箭头调整爆发。爆发 0 仍会施放技能,后续回合交给游戏。横向拖动查看更多招式。",
"fbattle.action.default": "跟随游戏",
"fbattle.action.attack": "普通攻击",
"fbattle.action.knockback": "击退",
"fbattle.sp_total": "首轮技能合计:{0} / {1} SP",
"fbattle.sp_partial": "已指定招式:{0} / {1} SP(不含跟随游戏的角色)",
"fbattle.unsaved": "尚未保存",
"fbattle.saved": "已保存",
"fbattle.saving": "正在保存预设和出手方式…",
"fbattle.save_failed": "保存失败,修改仍保留在此界面,请重试。",
"fbattle.open_failed": "无法打开出手方式编辑器,请检查插件日志。",
"fbattle.empty": "请先在预设中添加角色。",
"fbattle.save": "保存",
"fbattle.cancel": "取消",
"fbattle.discard": "丢弃修改",
"fbattle.confirm.title": "保存出手方式?",
"fbattle.confirm.message": "出手方式有未保存的修改。保存将同时保存当前预设的角色、站位和装备;丢弃则不保存出手方式。取消可继续编辑。",
"fbattle.server_required": "当前服务器不支持预设出手方式,请更新服务端。",
"fbattle.request_failed": "无法读取或保存预设出手方式,请稍后重试。"
}
+23
View File
@@ -0,0 +1,23 @@
{
"fbattle.entry": "出手方式",
"fbattle.title": "編輯出手方式",
"fbattle.info": "選擇每位角色首輪的招式;選中技能後可用左右箭頭調整爆發。爆發 0 仍會施放技能,後續回合交給遊戲。橫向拖曳查看更多招式。",
"fbattle.action.default": "跟隨遊戲",
"fbattle.action.attack": "普通攻擊",
"fbattle.action.knockback": "擊退",
"fbattle.sp_total": "首輪技能合計:{0} / {1} SP",
"fbattle.sp_partial": "已指定招式:{0} / {1} SP(不含跟隨遊戲的角色)",
"fbattle.unsaved": "尚未儲存",
"fbattle.saved": "已儲存",
"fbattle.saving": "正在儲存預設與出手方式…",
"fbattle.save_failed": "儲存失敗,修改仍保留於此畫面,請重試。",
"fbattle.open_failed": "無法開啟出手方式編輯器,請檢查外掛日誌。",
"fbattle.empty": "請先在預設中加入角色。",
"fbattle.save": "儲存",
"fbattle.cancel": "取消",
"fbattle.discard": "捨棄修改",
"fbattle.confirm.title": "儲存出手方式?",
"fbattle.confirm.message": "出手方式有尚未儲存的修改。儲存會同時儲存目前預設的角色、站位與裝備;捨棄則不儲存出手方式。取消可繼續編輯。",
"fbattle.server_required": "目前伺服器不支援預設出手方式,請更新伺服器。",
"fbattle.request_failed": "無法讀取或儲存預設出手方式,請稍後重試。"
}
+133
View File
@@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Battle.BattleRecord;
using BD2.GameNames;
using HarmonyLib;
using Proto.Net;
namespace Bd2FBattle;
internal static class BattleExecution
{
private static object preparedProcessor;
private static bool forceBurst;
internal static void Install(Harmony harmony)
{
harmony.Patch(Game.Method(() => BattlePlayLibrary.AutoSkillReserve(default, null)),
prefix: new HarmonyMethod(typeof(BattleExecution), nameof(BeforeSkills)),
finalizer: new HarmonyMethod(typeof(BattleExecution), nameof(AfterAutomatic)));
harmony.Patch(Game.Method(() => BattlePlayLibrary.AutoBurstReserve(default, null)),
prefix: new HarmonyMethod(typeof(BattleExecution), nameof(BeforeBursts)),
finalizer: new HarmonyMethod(typeof(BattleExecution), nameof(AfterAutomatic)));
harmony.Patch(Game.Method(() => BattlePlayLibrary.AutoBurstReserveForChar(null, null)),
prefix: new HarmonyMethod(typeof(BattleExecution), nameof(BeforeCharacterBurst)),
finalizer: new HarmonyMethod(typeof(BattleExecution), nameof(AfterAutomatic)));
harmony.Patch(Game.Method<BattlePlayManager>(battle => battle.ProcessAutoBattleWhenEnterBattle(null)),
postfix: new HarmonyMethod(typeof(BattleExecution), nameof(AfterReady)));
harmony.Patch(Game.Getter(() => UserSettingInfo.IsAutoBattleBurst),
prefix: new HarmonyMethod(typeof(BattleExecution), nameof(AutoBurstEnabled)));
harmony.Patch(Game.Method<BattlePlayManager>(battle => battle.Retry()),
prefix: new HarmonyMethod(typeof(BattleExecution), nameof(Reset)));
}
internal static void Reset() => preparedProcessor = null;
private static bool AutoBurstEnabled(ref bool __result)
{
if (!forceBurst) return true;
__result = true;
return false;
}
private static void BeforeSkills(ETeamType __0, out PlanScope __state) => __state = CreateScope(__0, false);
private static void BeforeBursts(ETeamType __0, out PlanScope __state) => __state = CreateScope(__0, true);
private static void BeforeCharacterBurst(BattleCharData __0, out PlanScope __state) =>
__state = __0 == null ? null : CreateScope(__0.TeamType, true);
private static Exception AfterAutomatic(Exception __exception, PlanScope __state)
{
__state?.Dispose();
return __exception;
}
private static bool TryPlan(out BattlePlayManager battle, out IList<BattleCharData> team, out Dictionary<long, ActionChoice> choices)
{
battle = BattlePlayManager.Instance;
team = null;
choices = null;
if (battle == null || battle.BattleProcessor == null || battle.GetBattleTurn() > 1 || battle.IsRetryCharActionSetting ||
battle.IsPVPMode() || battle.IsTotalWar() || battle.IsRoguelike || battle.IsMonsterHunt || battle.IsGuildRaidBoss() ||
BattleRecordManager.IsReadyBattleRecord || !battle.IsBlueTurn()) return false;
team = battle.GetTeamBattleCharSequenceList(ETeamType.TT_BLUE);
return team != null && PresetPlans.TryActive(team.Select(character => character.CharInvenIndex), out choices);
}
private static PlanScope CreateScope(ETeamType teamType, bool burst)
{
if (teamType != ETeamType.TT_BLUE || !TryPlan(out _, out IList<BattleCharData> team, out Dictionary<long, ActionChoice> choices))
return null;
var scope = new PlanScope();
try
{
foreach (BattleCharData character in team)
{
if (!choices.TryGetValue(character.CharInvenIndex, out ActionChoice choice) || character.IsBorrowedSupporter) continue;
if (choice.CostumeIndex > 0)
{
CostumeDBInfo costume = CostumePacket.GetCostumeDBInfo(choice.CostumeIndex);
if (costume == null) continue;
int allowed = Math.Min(choice.BurstLevel, costume.BurstLevel);
scope.Add(character, choice.CostumeIndex, burst ? allowed : 0);
}
else scope.Add(character, choice.CostumeIndex, 0);
}
return scope;
}
catch
{
scope.Dispose();
throw;
}
}
private static void AfterReady(BattlePlayManager __instance, BattleUIBase __0)
{
if (__0 == null || !TryPlan(out _, out _, out _) || ReferenceEquals(preparedProcessor, __instance.BattleProcessor)) return;
preparedProcessor = __instance.BattleProcessor;
try
{
BattlePlayLibrary.CancelSkillReserve(ETeamType.TT_BLUE, __0, false);
BattlePlayLibrary.AutoSkillReserve(ETeamType.TT_BLUE, __0);
forceBurst = true;
BattlePlayLibrary.AutoBurstReserve(ETeamType.TT_BLUE, __0);
}
finally { forceBurst = false; }
}
private sealed class PlanScope : IDisposable
{
private readonly List<(BattleCharData Character, DeckCostumeSettingSeqInfo[] Sequence, int Slot)> previous = [];
internal void Add(BattleCharData character, long costume, int burst)
{
previous.Add((character, character.DeckCostumeSettingSeqInfoList.ToArray(), character.UseSequenceSlotIndex));
character.DeckCostumeSettingSeqInfoList.Clear();
character.DeckCostumeSettingSeqInfoList.Add(new DeckCostumeSettingSeqInfo(costume, burst));
character.UseSequenceSlotIndex = 0;
}
public void Dispose()
{
foreach ((BattleCharData character, DeckCostumeSettingSeqInfo[] sequence, int slot) in previous)
{
character.DeckCostumeSettingSeqInfoList.Clear();
character.DeckCostumeSettingSeqInfoList.AddRange(sequence);
character.UseSequenceSlotIndex = slot;
}
previous.Clear();
}
}
}
+26
View File
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>disable</Nullable>
<AssemblyName>BD2FBattle</AssemblyName>
<RootNamespace>Bd2FBattle</RootNamespace>
<BD2UsesGameSdk>true</BD2UsesGameSdk>
<BD2PluginVersionKey>fbattle</BD2PluginVersionKey>
<BD2GameVersion>2.37.13</BD2GameVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="BepInEx"><HintPath>$(BD2BepInExDir)/core/BepInEx.dll</HintPath><Private>false</Private></Reference>
<Reference Include="0Harmony"><HintPath>$(BD2BepInExDir)/core/0Harmony.dll</HintPath><Private>false</Private></Reference>
<Reference Include="Google.Protobuf"><HintPath>$(BD2ManagedDir)/Google.Protobuf.dll</HintPath><Private>false</Private></Reference>
<Reference Include="Unity.TextMeshPro"><HintPath>$(BD2ManagedDir)/Unity.TextMeshPro.dll</HintPath><Private>false</Private></Reference>
<Reference Include="Unity.ResourceManager"><HintPath>$(BD2ManagedDir)/Unity.ResourceManager.dll</HintPath><Private>false</Private></Reference>
<Reference Include="UniTask"><HintPath>$(BD2ManagedDir)/UniTask.dll</HintPath><Private>false</Private></Reference>
<Reference Include="UnityEngine"><HintPath>$(BD2ManagedDir)/UnityEngine.dll</HintPath><Private>false</Private></Reference>
<Reference Include="UnityEngine.CoreModule"><HintPath>$(BD2ManagedDir)/UnityEngine.CoreModule.dll</HintPath><Private>false</Private></Reference>
<Reference Include="UnityEngine.UI"><HintPath>$(BD2ManagedDir)/UnityEngine.UI.dll</HintPath><Private>false</Private></Reference>
<Reference Include="UnityEngine.UIModule"><HintPath>$(BD2ManagedDir)/UnityEngine.UIModule.dll</HintPath><Private>false</Private></Reference>
<Reference Include="UnityEngine.InputLegacyModule"><HintPath>$(BD2ManagedDir)/UnityEngine.InputLegacyModule.dll</HintPath><Private>false</Private></Reference>
<Reference Include="UnityEngine.TextRenderingModule"><HintPath>$(BD2ManagedDir)/UnityEngine.TextRenderingModule.dll</HintPath><Private>false</Private></Reference>
</ItemGroup>
</Project>
+267
View File
@@ -0,0 +1,267 @@
using System;
using System.Linq;
using System.Reflection;
using BD2.GameNames;
using Cysharp.Threading.Tasks;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Bd2FBattle;
// Templates and clone helpers for the game's own widgets. Every clone is made
// under an inactive holder so game scripts can be removed before they wake up.
internal sealed class NativeActionControls
{
// The battle list lays its cards out at this size in landscape.
internal static readonly Vector2 CardSize = new(280, 90);
internal GameObject CardTemplate { get; }
internal GameObject SlotTemplate { get; }
internal Vector2 SlotSize { get; }
internal NativeActionControls(GameObject battlePrefab, CharManageUI editor)
{
CardTemplate = (battlePrefab.GetComponentInChildren<BattleUIComponent_CharActionSelectItem>(true) ??
throw new MissingMemberException("Native battle action card template unavailable.")).gameObject;
CharManageLoopScrollItem[] items = editor.GetComponentsInChildren<CharManageLoopScrollItem>(true);
CharManageLoopScrollItem item = items.FirstOrDefault(entry => entry.gameObject.activeInHierarchy) ?? items.FirstOrDefault() ??
throw new MissingMemberException("Native character list card unavailable.");
SlotTemplate = item.gameObject;
Vector2 size = ((RectTransform)item.transform).rect.size;
SlotSize = size.x > 10 && size.y > 10 ? size : new Vector2(120, 224);
}
internal static T Field<T>(object target, string name) where T : class => target == null ? null :
target.GetType().GetGameField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(target) as T;
internal static int Integer(object target, string name) => (int)(target.GetType().GetGameField(name,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(target) ?? throw new MissingFieldException(target.GetType().Name, name));
internal static void LoadBattlePrefab(Action<AddressableAsset<GameObject>> ready, Action<Exception> failed)
{
MethodInfo method = typeof(AssetManager).GetGameMethod("GetAssetWithFailure", BindingFlags.Public | BindingFlags.Static) ??
throw new MissingMethodException(nameof(AssetManager), "GetAssetWithFailure");
Action<AddressableAsset<GameObject>> complete = async asset => { await UniTask.SwitchToMainThread(); ready(asset); };
Action<Exception> failure = async error => { await UniTask.SwitchToMainThread(); failed(error); };
method.MakeGenericMethod(typeof(GameObject)).Invoke(null, ["UIPrefabs/BattleUI_FieldBattle.prefab", complete, failure]);
}
// Copies source without running any of its scripts. Call Wake once the
// caller has read what it needs from the copy and removed the rest.
internal static GameObject Dormant(GameObject source, string name)
{
var holder = new GameObject("FBattle Dormant");
holder.SetActive(false);
GameObject copy = UnityEngine.Object.Instantiate(source, holder.transform, false);
copy.name = name;
copy.SetActive(true);
return copy;
}
internal static RectTransform Wake(GameObject copy, Transform parent)
{
Transform holder = copy.transform.parent;
copy.transform.SetParent(parent, false);
if (holder != null && holder.childCount == 0) UnityEngine.Object.Destroy(holder.gameObject);
foreach (CanvasGroup group in copy.GetComponents<CanvasGroup>()) { group.alpha = 1; group.interactable = true; group.blocksRaycasts = true; }
return (RectTransform)copy.transform;
}
// Input, localisation and list scripts would fight the editor; graphics,
// layout and effect scripts stay so the copy keeps the game's look.
internal static void Strip(GameObject copy, Func<MonoBehaviour, bool> alsoRemove = null)
{
foreach (MonoBehaviour script in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (script == null) continue;
if (script is LocalTextConverter || script is MultiPlatformInputBinder || script is LoopScrollItemBase ||
script is IEventSystemHandler || alsoRemove?.Invoke(script) == true)
UnityEngine.Object.DestroyImmediate(script);
}
}
internal static RectTransform Rect(string name, Transform parent, float x, float y, float width, float height)
{
var child = new GameObject(name, typeof(RectTransform));
return Place(child.transform, parent, x, y, width, height);
}
internal static RectTransform Place(Transform child, Transform parent, float x, float y, float width, float height)
{
child.SetParent(parent, false);
foreach (Behaviour component in child.GetComponents<Behaviour>()) if (IsLayout(component)) component.enabled = false;
var rect = (RectTransform)child;
rect.localScale = Vector3.one;
rect.localRotation = Quaternion.identity;
rect.anchorMin = rect.anchorMax = rect.pivot = new Vector2(.5f, .5f);
rect.anchoredPosition = new Vector2(x, y);
rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, width);
rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height);
IgnoreLayout(rect);
return rect;
}
internal static void IgnoreLayout(Component target)
{
LayoutElement layout = target.GetComponent<LayoutElement>() ?? target.gameObject.AddComponent<LayoutElement>();
layout.ignoreLayout = true;
}
internal static bool IsLayout(Behaviour component) => component is LayoutGroup || component is ContentSizeFitter ||
component.GetType().Namespace == "TheraBytes.BetterUi" && component is not Graphic && component is not Selectable;
internal static TMP_Text Label(TMP_Text template, Transform parent, string name, string value, float x, float y,
float width, float height = 30, float size = 22, TextAlignmentOptions alignment = TextAlignmentOptions.MidlineLeft)
{
GameObject copy = Dormant(template.gameObject, name);
Strip(copy);
TMP_Text label = copy.GetComponent<TMP_Text>();
Place(Wake(copy, parent), parent, x, y, width, height);
label.text = value;
// The popup fades its own title in; a copy taken mid-fade would stay invisible.
label.alpha = 1;
label.canvasRenderer.SetAlpha(1);
label.enableAutoSizing = true;
label.fontSizeMax = size;
label.fontSizeMin = Math.Min(14, size);
label.alignment = alignment;
label.enableWordWrapping = true;
label.overflowMode = TextOverflowModes.Ellipsis;
label.margin = Vector4.zero;
label.richText = false;
label.raycastTarget = false;
return label;
}
// A game button with its own title, its click rerouted to the editor.
internal static Button Button(GameObject template, Transform parent, string name, string title, Vector2 size, Action click)
{
GameObject copy = Dormant(template, name);
Selectable look = copy.GetComponent<Selectable>();
Selectable.Transition transition = look == null ? Selectable.Transition.None : look.transition;
AnimationTriggers triggers = look?.animationTriggers;
ColorBlock colors = look == null ? ColorBlock.defaultColorBlock : look.colors;
SpriteState sprites = look == null ? default : look.spriteState;
Graphic surface = look?.targetGraphic;
Strip(copy, script => script is Selectable);
foreach (Behaviour component in copy.GetComponentsInChildren<Behaviour>(true)) if (IsLayout(component)) component.enabled = false;
foreach (TMP_Text label in copy.GetComponentsInChildren<TMP_Text>(true))
{
// Shrink long titles but never grow past the button's own size.
float native = label.enableAutoSizing ? label.fontSizeMax : label.fontSize;
label.text = title;
label.enableAutoSizing = true;
label.fontSizeMax = native;
label.fontSizeMin = Math.Min(14, native);
}
RectTransform rect = Place(Wake(copy, parent), parent, 0, 0, size.x, size.y);
if (surface == null) surface = copy.GetComponent<Graphic>() ?? copy.GetComponentsInChildren<Graphic>(true).FirstOrDefault(graphic => graphic is not TMP_Text);
if (surface != null) surface.raycastTarget = true;
Button button = copy.AddComponent<Button>();
// Keep the game's press feedback (its animator triggers or tints).
button.transition = transition;
if (triggers != null) button.animationTriggers = triggers;
button.colors = colors;
button.spriteState = sprites;
button.targetGraphic = surface;
button.onClick.AddListener(() => click());
rect.gameObject.SetActive(true);
return button;
}
internal static Image Fill(Transform parent, string name, Color color, float x, float y, float width, float height)
{
Image image = Rect(name, parent, x, y, width, height).gameObject.AddComponent<Image>();
image.color = color;
image.raycastTarget = false;
return image;
}
internal static T Scroll<T>(Transform parent, string name, float x, float y, float width, float height, bool horizontal) where T : ScrollRect
{
RectTransform root = Rect(name, parent, x, y, width, height);
Image surface = root.gameObject.AddComponent<Image>();
surface.color = Color.clear;
root.gameObject.AddComponent<RectMask2D>();
T scroll = root.gameObject.AddComponent<T>();
scroll.viewport = root;
scroll.horizontal = horizontal;
scroll.vertical = !horizontal;
scroll.movementType = ScrollRect.MovementType.Clamped;
scroll.scrollSensitivity = 40;
RectTransform content = Rect(name + " Content", root, 0, 0, width, height);
content.anchorMin = content.anchorMax = content.pivot = new Vector2(0, 1);
content.anchoredPosition = Vector2.zero;
scroll.content = content;
return scroll;
}
}
// A row of cards inside the character list: the wheel and vertical drags go
// to the list, horizontal drags page through the cards.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0031", Justification = "UnityEngine.Object null checks also detect destroyed native objects.")]
internal sealed class RowScroll : ScrollRect
{
internal ScrollRect Outer;
private bool outerDrag;
private bool Overflows => content != null && viewport != null && content.rect.width > viewport.rect.width + 1;
public override void OnScroll(PointerEventData data)
{
if (Outer != null) Outer.OnScroll(data);
}
public override void OnInitializePotentialDrag(PointerEventData data)
{
Outer?.OnInitializePotentialDrag(data);
base.OnInitializePotentialDrag(data);
}
public override void OnBeginDrag(PointerEventData data)
{
outerDrag = !Overflows || Mathf.Abs(data.delta.y) > Mathf.Abs(data.delta.x);
if (outerDrag) Outer?.OnBeginDrag(data);
else base.OnBeginDrag(data);
}
public override void OnDrag(PointerEventData data)
{
if (outerDrag) Outer?.OnDrag(data);
else base.OnDrag(data);
}
public override void OnEndDrag(PointerEventData data)
{
if (outerDrag) Outer?.OnEndDrag(data);
else base.OnEndDrag(data);
outerDrag = false;
}
}
// Releases a texture the game loaded for one of the editor's images.
internal sealed class TextureLease : MonoBehaviour
{
private AddressableAsset<Texture> asset;
private int generation;
internal void Load(RawImage image, int costumeDesignId, bool skillArt)
{
int current = ++generation;
void loaded(AddressableAsset<Texture> texture)
{
if (this == null || image == null || current != generation) { texture.Release(); return; }
asset?.Release();
asset = texture;
image.texture = texture.Asset;
image.gameObject.SetActive(true);
}
if (skillArt) AssetManager.GetCharSkillIllustTexture(costumeDesignId, loaded);
else AssetManager.GetCharInvenIllustTexture(costumeDesignId, loaded);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0051", Justification = "Unity invokes this lifecycle callback.")]
private void OnDestroy() { generation++; asset?.Release(); asset = null; }
}
+37
View File
@@ -0,0 +1,37 @@
using System;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
namespace Bd2FBattle;
[BepInPlugin(PluginId, Name, Version)]
[BepInDependency("bd2.localidentity", BepInDependency.DependencyFlags.HardDependency)]
public sealed class Plugin : BaseUnityPlugin
{
public const string PluginId = "bd2.fbattle";
public const string Name = "BD2 FBattle";
public const string Version = Bd2Build.Versions.Plugin;
internal static ManualLogSource Log;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0051", Justification = "Unity invokes this lifecycle callback.")]
private void Awake()
{
Log = Logger;
#pragma warning disable CA2000
var harmony = new Harmony(PluginId);
#pragma warning restore CA2000
try
{
PresetPlans.Install(harmony);
BattleExecution.Install(harmony);
PresetEditorEntry.Install(harmony);
Logger.LogInfo("Preset action editor and first-turn battle plans installed");
}
catch (Exception error)
{
harmony.UnpatchSelf();
Logger.LogError("FBattle initialization failed: " + error);
}
}
}
+364
View File
@@ -0,0 +1,364 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Helper;
using Proto.Net;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace Bd2FBattle;
// The action editor, hosted in the game's greeting popup. Each preset member
// gets a row: the character list card (portrait, name, element), then the
// battle action cards it can pick from, laid out in up to two lines.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0031", Justification = "UnityEngine.Object null checks also detect destroyed native objects.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0051", Justification = "Unity invokes these lifecycle callbacks.")]
internal sealed class PresetActionEditor : MonoBehaviour, IDisposable
{
private const float PanelWidth = 1560, PanelHeight = 1000, ListWidth = 1500, ListHeight = 740, ListY = -4;
private const float Gap = 10, RowPadding = 12;
private GreetingPopupUI popup;
private CharManageUI owner;
private NativeActionControls native;
private PresetDBInfo preset;
private int slot;
private Dictionary<long, ActionChoice> original, draft;
private Transform frame;
private RectTransform root;
private TMP_Text textTemplate, status;
private GameObject originalSave, originalCancel;
private Vector2 frameSize;
private Vector3 frameScale;
private readonly List<(GameObject Object, bool Active)> hidden = [];
private readonly List<Behaviour> layouts = [];
private readonly List<Button> buttons = [];
private readonly List<Row> rows = [];
private bool busy, disposed, confirming;
internal bool AllowClose { get; private set; }
internal void Initialize(GreetingPopupUI host, CharManageUI editor, NativeActionControls controls)
{
popup = host; owner = editor; native = controls;
preset = NativeActionControls.Field<PresetDBInfo>(editor, "_presetInfo")?.Clone() ?? throw new MissingMemberException("Preset draft unavailable.");
slot = NativeActionControls.Integer(editor, "_presetIndex");
var members = new HashSet<long>(editor.DeckList.Select(item => item.CharInvenIndex));
draft = PresetPlans.Get(slot).Where(item => members.Contains(item.Key)).ToDictionary(item => item.Key, item => item.Value.Clone());
original = draft.ToDictionary(item => item.Key, item => item.Value.Clone());
TMP_InputField input = NativeActionControls.Field<TMP_InputField>(host, "_inputField");
originalSave = NativeActionControls.Field<GameObject>(host, "_objChangeButton");
originalCancel = NativeActionControls.Field<GameObject>(host, "_objCancelButton");
if (input == null || originalSave == null || originalCancel == null) throw new MissingMemberException("Native popup controls unavailable.");
Transform nameBox = input.transform.parent;
frame = nameBox.parent.parent;
textTemplate = frame.GetComponentsInChildren<TMP_Text>(true).FirstOrDefault(text => text.gameObject.name == "Text - Title") ??
throw new MissingMemberException("Native popup title unavailable.");
BuildFrame(nameBox.parent.gameObject);
Label(root, "Title", ActionCatalog.Text("fbattle.title") + " · " + preset.PresetName, 0, 440, 1300, 50, 34, TextAlignmentOptions.Midline);
Label(root, "Explanation", ActionCatalog.Text("fbattle.info"), 0, 398, 1420, 36, 20, TextAlignmentOptions.Midline);
ScrollRect list = NativeActionControls.Scroll<ScrollRect>(root, "Characters", 0, ListY, ListWidth, ListHeight, false);
List<DeckDBInfo> ordered = [.. editor.DeckList.Where(item => item.CharInvenIndex > 0).OrderBy(item => item.Sequence)];
float y = 0;
for (int index = 0; index < ordered.Count; index++) y += BuildRow(list, ordered[index], index, y) + Gap;
list.content.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Math.Max(ListHeight, y - Gap));
list.verticalNormalizedPosition = 1;
status = Label(root, "Status", string.Empty, 0, -410, 1400, 34, 22, TextAlignmentOptions.Midline);
var size = new Vector2(220, 64);
Button cancel = NativeActionControls.Button(originalCancel, root, "Cancel", ActionCatalog.Text("fbattle.cancel"), size, RequestClose);
Button save = NativeActionControls.Button(originalSave, root, "Save", ActionCatalog.Text("fbattle.save"), size, Save);
((RectTransform)cancel.transform).anchoredPosition = new Vector2(-150, -460);
((RectTransform)save.transform).anchoredPosition = new Vector2(150, -460);
buttons.Add(cancel); buttons.Add(save);
foreach (Row row in rows) RefreshRow(row);
UpdateStatus();
}
// Turns the popup's frame into the editor's panel; Dispose puts it back.
private void BuildFrame(GameObject renameBox)
{
var frameRect = (RectTransform)frame;
frameSize = frameRect.sizeDelta; frameScale = frameRect.localScale;
foreach (Behaviour layout in frame.GetComponentsInChildren<Behaviour>(true))
if (layout.enabled && NativeActionControls.IsLayout(layout)) { layouts.Add(layout); layout.enabled = false; }
Hide(renameBox); Hide(originalSave.transform.parent.gameObject);
foreach (TMP_Text text in frame.GetComponentsInChildren<TMP_Text>(true))
if (text.gameObject.name is "Text - Title" or "Text - Info") Hide(text.gameObject);
frameRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, PanelWidth);
frameRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, PanelHeight);
root = NativeActionControls.Rect("FBattle Action Editor", frame, 0, 0, PanelWidth, PanelHeight);
Rescale();
}
private void Hide(GameObject child) { if (child == null) return; hidden.Add((child, child.activeSelf)); child.SetActive(false); }
private void Rescale()
{
if (frame == null || popup == null) return;
Canvas canvas = popup.GetComponentInParent<Canvas>();
if (canvas == null || canvas.rootCanvas.transform is not RectTransform canvasRect) return;
float scale = Mathf.Min(1, (canvasRect.rect.width - 40) / PanelWidth, (canvasRect.rect.height - 40) / PanelHeight);
frame.localScale = frameScale * Mathf.Max(.1f, scale);
}
private float BuildRow(ScrollRect list, DeckDBInfo deck, int order, float top)
{
var catalog = new ActionCatalog(deck, preset);
Vector2 card = NativeActionControls.CardSize;
Vector2 slotSize = native.SlotSize;
int lines = 2 * card.y + Gap <= slotSize.y + 1 ? 2 : 1;
float height = Math.Max(slotSize.y, lines * card.y + (lines - 1) * Gap) + RowPadding * 2;
RectTransform rowRoot = NativeActionControls.Rect("Character " + deck.CharInvenIndex, list.content, 0, 0, ListWidth, height);
rowRoot.anchorMin = rowRoot.anchorMax = rowRoot.pivot = new Vector2(0, 1);
rowRoot.anchoredPosition = new Vector2(0, -top);
NativeActionControls.Fill(rowRoot, "Row Background", new Color(0, 0, 0, .28f), 0, 0, ListWidth, height);
var row = new Row(catalog);
rows.Add(row);
BuildIdentity(rowRoot, catalog, order, -ListWidth / 2 + RowPadding + slotSize.x / 2);
float cardsLeft = RowPadding * 2 + slotSize.x;
float cardsWidth = ListWidth - cardsLeft - RowPadding;
float cardsHeight = lines * card.y + (lines - 1) * Gap;
RowScroll actions = NativeActionControls.Scroll<RowScroll>(rowRoot, "Action Cards", -ListWidth / 2 + cardsLeft + cardsWidth / 2, 0, cardsWidth, cardsHeight, true);
actions.Outer = list;
int columns = (catalog.Options.Count + lines - 1) / lines;
actions.content.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, Math.Max(cardsWidth, columns * (card.x + Gap) - Gap));
draft.TryGetValue(catalog.Character.InvenIndex, out ActionChoice chosen);
for (int index = 0; index < catalog.Options.Count; index++)
{
ActionOption option = catalog.Options[index];
var view = new ActionCard(native, actions.content, catalog, option);
view.Root.anchoredPosition = new Vector2(index % columns * (card.x + Gap), -(index / columns) * (card.y + Gap));
if (option.IsSkill && chosen != null && chosen.CostumeIndex == option.Index) view.Burst = Math.Min(option.MaxBurst, Math.Max(0, chosen.BurstLevel));
view.Choose.onClick.AddListener(() => Select(row, view));
view.BurstDown?.onClick.AddListener(() => ChangeBurst(row, view, -1));
view.BurstUp?.onClick.AddListener(() => ChangeBurst(row, view, 1));
row.Cards.Add(view);
}
actions.horizontalNormalizedPosition = 0;
LoadEffect(row, $"UIPrefabsParts/Eff_SkillCard_{catalog.Element}_NEW.prefab", effect => row.SelectEffect = effect);
LoadEffect(row, "UIPrefabsParts/Eff_SkillCard_Burst.prefab", effect => row.BurstEffect = effect);
return height;
}
// The character list card, so the row reads like the preset screen itself.
private void BuildIdentity(RectTransform rowRoot, ActionCatalog catalog, int order, float x)
{
GameObject copy = NativeActionControls.Dormant(native.SlotTemplate, "Character Card");
NativeActionControls.Strip(copy, script => script is Selectable);
CanvasGroup group = copy.GetComponent<CanvasGroup>() ?? copy.AddComponent<CanvasGroup>();
RectTransform rect = NativeActionControls.Place(NativeActionControls.Wake(copy, rowRoot), rowRoot, x, 0, native.SlotSize.x, native.SlotSize.y);
group.interactable = false;
group.blocksRaycasts = false;
CharacterSlotSetting card = copy.GetComponentInChildren<CharacterSlotSetting>(true) ?? throw new MissingMemberException("Native character card unavailable.");
CharDBInfo character = catalog.Character;
card.SetCharDbInfo(character);
card.SetCharacter(catalog.Appearance.Id, catalog.Appearance.CostumeDesignId, character.Level, catalog.Appearance.Level, catalog.Name,
character.Hp, catalog.Definition.Type, ECharacterSlotMotionType.Idle, null);
card.SetBlockState(true);
card.SetSwap(false);
card.SetSwap2(false);
card.SetIncludeBattleDeckMark(false);
card.SetActiveExhaustion(character.Hp <= 0);
card.SetSequence(order);
card.SetSequenceChange(false);
rect.gameObject.SetActive(true);
}
private void LoadEffect(Row row, string address, Action<GameObject> loaded)
{
AssetManager.GetPrefabAsset(address, effect =>
{
if (effect == null) return;
if (disposed || this == null) { Destroy(effect); return; }
effect.SetActive(false);
effect.transform.SetParent(root, false);
loaded(effect);
RefreshRow(row);
});
}
// First-turn SP: the battle starts the player's team with this many
// bubbles and adds the per-turn SP only after the first turn.
private static int Budget => Math.Min(BattleDefaultInfo.SpStartPvECount, BattleDefaultInfo.SkillBubbleMaxPoint);
private int Cost(Row row) => draft.TryGetValue(row.Catalog.Character.InvenIndex, out ActionChoice choice) ?
row.Catalog.Options.FirstOrDefault(item => item.Index == choice.CostumeIndex)?.Sp(choice.BurstLevel) ?? 0 : 0;
// SP left for this row once every other chosen action is paid for.
private int Available(Row row) => Budget - rows.Where(other => other != row).Sum(Cost);
private void Select(Row row, ActionCard card)
{
if (busy) return;
if (card.Option.IsSkill && card.Option.Sp(card.Burst) > Available(row))
{
// As in battle: drop the burst until the skill fits, else refuse.
int burst = card.Burst;
while (burst > 0 && card.Option.Sp(burst) > Available(row)) burst--;
if (card.Option.Sp(burst) > Available(row)) { UIManager.OpenBarNotice(LocalTextInfo.GetText(684), false, null); return; }
card.Burst = burst;
}
long character = row.Catalog.Character.InvenIndex;
if (card.Option.IsDefault) draft.Remove(character);
else draft[character] = new ActionChoice(character, card.Option.Index, card.Option.IsSkill ? card.Burst : 0);
RefreshRow(row);
foreach (Row other in rows) if (other != row) RefreshRow(other);
UpdateStatus();
}
private void ChangeBurst(Row row, ActionCard card, int delta)
{
if (busy) return;
int burst = Math.Max(0, Math.Min(card.Option.MaxBurst, card.Burst + delta));
if (burst == card.Burst) return;
if (delta > 0 && card.Option.Sp(burst) > Available(row)) { UIManager.OpenBarNotice(LocalTextInfo.GetText(3100004), false, null); return; }
card.Burst = burst;
Select(row, card);
}
private void RefreshRow(Row row)
{
if (disposed) return;
draft.TryGetValue(row.Catalog.Character.InvenIndex, out ActionChoice selected);
int available = Available(row);
ActionCard chosen = null;
foreach (ActionCard card in row.Cards)
{
bool active = selected == null ? card.Option.IsDefault : selected.CostumeIndex == card.Option.Index;
if (active) chosen = card;
card.Refresh(active, busy, row.SelectEffect != null && card.SelectEffectParent != null, available);
}
Attach(row.SelectEffect, chosen?.SelectEffectParent, ref row.SelectHost, true);
bool bursting = chosen != null && chosen.Option.IsSkill && chosen.Burst > 0;
Attach(row.BurstEffect, bursting ? chosen.BurstEffectParent : null, ref row.BurstHost, false);
}
// Moves an effect onto the selected card the way the battle list does,
// replaying it only when the selection actually moves.
private static void Attach(GameObject effect, Transform host, ref Transform current, bool replay)
{
if (effect == null) return;
if (current == host && effect.activeSelf == (host != null)) return;
if (current != null && current != host) current.gameObject.SetActive(false);
current = host;
if (host == null) { effect.SetActive(false); return; }
host.gameObject.SetActive(true);
var rect = (RectTransform)effect.transform;
rect.SetParent(host, false);
rect.localScale = Vector3.one;
rect.anchoredPosition = Vector2.zero;
if (rect.anchorMin != rect.anchorMax) rect.offsetMin = rect.offsetMax = Vector2.zero;
if (replay || !effect.activeSelf) { effect.SetActive(false); effect.SetActive(true); }
}
private bool Dirty => original.Count != draft.Count || draft.Any(pair => !original.TryGetValue(pair.Key, out ActionChoice before) ||
before.CostumeIndex != pair.Value.CostumeIndex || before.BurstLevel != pair.Value.BurstLevel);
private void UpdateStatus()
{
bool automatic = rows.Any(row => !draft.ContainsKey(row.Catalog.Character.InvenIndex));
status.text = string.Format(CultureInfo.CurrentCulture, ActionCatalog.Text(automatic ? "fbattle.sp_partial" : "fbattle.sp_total"),
rows.Sum(Cost), Budget) + " · " + ActionCatalog.Text(Dirty ? "fbattle.unsaved" : "fbattle.saved");
}
private void SetBusy(bool value)
{
busy = value;
foreach (Button button in buttons) if (button != null) button.interactable = !value;
foreach (Row row in rows) RefreshRow(row);
}
private void Save()
{
if (busy || owner == null) return;
SetBusy(true);
status.text = ActionCatalog.Text("fbattle.saving");
try
{
Dictionary<long, List<EquipDBInfo>> equipment = NativeActionControls.Field<Dictionary<long, List<EquipDBInfo>>>(owner, "_presetManagedEquipDataByChar") ??
throw new MissingMemberException("Preset equipment draft unavailable.");
PresetDBInfo saved = preset.Clone();
Prset.RefreshPresetDBInfo(ref saved, owner.DeckList, equipment);
PresetDBInfo complete = saved;
PresetPlans.Save(saved, slot, draft.Values, () =>
{
if (disposed) return;
draft = PresetPlans.Get(slot);
original = draft.ToDictionary(item => item.Key, item => item.Value.Clone());
preset = complete.Clone();
if (owner != null)
{
owner.SetConfigPresetData(complete.Clone(), slot);
owner.SetTabCharManageUI(owner.CurrentTab, true);
}
busy = false;
Close();
UIManager.OpenBarNotice(ActionCatalog.Text("fbattle.saved"), false, null);
}, SaveFailed);
}
catch (Exception error) { Plugin.Log?.LogWarning("FBattle save: " + error); SaveFailed(error.Message); }
}
private void SaveFailed(string error)
{
if (disposed) return;
SetBusy(false);
status.text = ActionCatalog.Text("fbattle.save_failed");
Plugin.Log?.LogWarning("FBattle preset save failed: " + error);
}
internal void Click(GameObject clicked)
{
if (clicked == null) return;
if (clicked == originalCancel || clicked.name == "Button - Back" || clicked.name == "Button - background" || popup.IsClickedBackButton(clicked)) RequestClose();
}
// Esc, the back button and Cancel all land here. Unsaved changes get the
// deck editor's own save / discard prompt.
internal void RequestClose()
{
if (busy || confirming || disposed) return;
if (!Dirty) { Close(); return; }
confirming = true;
UIManager.AddUI<DeckSavePopupUI>(confirm =>
{
if (disposed) { confirm.CloseForceUI(true); return; }
confirm.SetSortingOrder(Math.Max(confirm.SortingOrder, popup.SortingOrder + 1));
confirm.AddCloseCallback(() => { confirming = false; });
confirm.OpenPopup(ActionCatalog.Text("fbattle.confirm.message"), ActionCatalog.Text("fbattle.confirm.title"),
ActionCatalog.Text("fbattle.save"), ActionCatalog.Text("fbattle.discard"), MessagePopupUI.EMessagePopupButtonStyle.OK_CANCEL,
(ok, dialog) => { if (ok) { confirming = false; Save(); } }, true,
() => { confirm.CloseUI(); confirming = false; Close(); });
}, "", false, "");
}
private void Close() { AllowClose = true; if (popup != null) popup.CloseUI(); }
private TMP_Text Label(Transform parent, string name, string value, float x, float y, float width, float height, float size, TextAlignmentOptions alignment) =>
NativeActionControls.Label(textTemplate, parent, name, value, x, y, width, height, size, alignment);
private void LateUpdate() => Rescale();
private void OnDisable() => Dispose();
public void Dispose()
{
if (disposed) return;
disposed = true;
foreach (Row row in rows) { if (row.SelectEffect != null) Destroy(row.SelectEffect); if (row.BurstEffect != null) Destroy(row.BurstEffect); }
if (root != null) Destroy(root.gameObject);
if (frame != null) { ((RectTransform)frame).sizeDelta = frameSize; frame.localScale = frameScale; }
foreach ((GameObject child, bool active) in hidden) if (child != null) child.SetActive(active);
foreach (Behaviour layout in layouts) if (layout != null) layout.enabled = true;
rows.Clear(); buttons.Clear(); hidden.Clear(); layouts.Clear();
Destroy(this);
}
private sealed class Row(ActionCatalog catalog)
{
internal ActionCatalog Catalog { get; } = catalog;
internal List<ActionCard> Cards { get; } = [];
internal GameObject SelectEffect, BurstEffect;
internal Transform SelectHost, BurstHost;
}
}
+176
View File
@@ -0,0 +1,176 @@
using System;
using System.Linq;
using System.Reflection;
using BD2.GameNames;
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
namespace Bd2FBattle;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0031", Justification = "UnityEngine.Object null checks also detect destroyed native objects.")]
internal static class PresetEditorEntry
{
private static AddressableAsset<GameObject> battleAsset;
private static bool loading, quitting;
private static readonly string[] BottomButtons = ["_buttonReset", "_buttonCancel", "_buttonOk"];
internal static void Install(Harmony harmony)
{
Application.quitting += Release;
harmony.Patch(Method(typeof(CharManageUI), "OpenCharManageUI"), postfix: new HarmonyMethod(typeof(PresetEditorEntry), nameof(Ready)));
harmony.Patch(Method(typeof(CharManageUI), "SetTabCharManageUI"), postfix: new HarmonyMethod(typeof(PresetEditorEntry), nameof(Ready)));
harmony.Patch(Method(typeof(GreetingPopupUI), "OnClickUI", typeof(GameObject)), prefix: new HarmonyMethod(typeof(PresetEditorEntry), nameof(PopupClick)));
harmony.Patch(Method(typeof(UIBase), "CloseUI"), prefix: new HarmonyMethod(typeof(PresetEditorEntry), nameof(PopupClose)));
}
private static MethodInfo Method(Type owner, string name, params Type[] parameters)
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
return (parameters.Length == 0 ? owner.GetGameMethod(name, flags) : owner.GetGameMethod(name, flags, null, parameters, null)) ??
throw new MissingMethodException(owner.Name, name);
}
private static void Ready(CharManageUI __instance)
{
if (__instance.OpenFromType != CharManageUI.ECharManageUIOpenFrom.FromPresetSetting) return;
try
{
PresetEditorButton current = __instance.GetComponent<PresetEditorButton>();
if (current != null) { current.Refresh(); return; }
Button[] row = BottomButtons.Select(name => NativeActionControls.Field<Button>(NativeActionControls.Field<object>(__instance, name), "_button")).ToArray();
Button template = row[2] ?? row[0];
if (template == null || row[0] == null) throw new MissingMemberException("Preset bottom buttons unavailable.");
Vector2 size = ((RectTransform)template.transform).rect.size;
Button entry = NativeActionControls.Button(template.gameObject, template.transform.parent, "FBattle Edit Actions",
ActionCatalog.Text("fbattle.entry"), size, () => Open(__instance));
IconFree(entry.transform);
__instance.gameObject.AddComponent<PresetEditorButton>().Initialize(__instance, entry, row);
}
catch (Exception error) { Plugin.Log?.LogWarning("FBattle preset entry: " + error); }
}
// The bottom buttons carry an icon (reset arrow, check mark) that would
// mislabel the entry, so drop it and centre the title in its place.
private static void IconFree(Transform button)
{
foreach (Transform state in button)
{
if (state.name == "Image - Disable") { state.gameObject.SetActive(false); continue; }
if (state.name != "Image - Enable") continue;
Transform icon = state.Find("Image - Bg");
if (icon != null) icon.gameObject.SetActive(false);
}
foreach (Transform child in button)
{
if (child.name == "Image - Bg") child.gameObject.SetActive(false);
if (child.name != "Text - Title" || child is not RectTransform title) continue;
title.offsetMin = new Vector2(12, title.offsetMin.y);
title.offsetMax = new Vector2(-12, title.offsetMax.y);
}
}
private static void Open(CharManageUI owner)
{
if (quitting || loading || UIManager.IsShowingNetworkErrorPopup) return;
if (owner.DeckList.Count == 0) { UIManager.OpenBarNotice(ActionCatalog.Text("fbattle.empty"), false, null); return; }
loading = true;
PresetPlans.Load(() =>
{
if (quitting || owner == null || !owner.isActiveAndEnabled) { loading = false; return; }
if (battleAsset != null) { loading = false; Show(owner); return; }
try
{
NativeActionControls.LoadBattlePrefab(asset =>
{
loading = false;
if (quitting) { asset.Release(); return; }
battleAsset = asset;
if (owner != null && owner.isActiveAndEnabled) Show(owner);
}, Failed);
}
catch (Exception error) { Failed(error); }
}, error => Failed(new InvalidOperationException(error)));
}
private static void Show(CharManageUI owner)
{
try
{
var controls = new NativeActionControls(battleAsset.Asset, owner);
UIManager.AddUI<GreetingPopupUI>(popup =>
{
if (quitting || owner == null || !owner.isActiveAndEnabled) { popup.CloseForceUI(true); return; }
try { popup.gameObject.AddComponent<PresetActionEditor>().Initialize(popup, owner, controls); }
catch (Exception error) { popup.CloseForceUI(true); Failed(error); }
}, "GreetingPopupUI", true, "");
}
catch (Exception error) { Failed(error); }
}
private static void Failed(Exception error)
{
loading = false;
if (quitting) return;
UIManager.OpenBarNotice(ActionCatalog.Text("fbattle.open_failed"), false, null);
Plugin.Log?.LogWarning("FBattle preset editor: " + error);
}
private static bool PopupClick(GreetingPopupUI __instance, GameObject __0)
{
PresetActionEditor panel = __instance.GetComponent<PresetActionEditor>();
if (panel == null) return true;
panel.Click(__0);
return false;
}
private static bool PopupClose(UIBase __instance)
{
if (__instance is not GreetingPopupUI) return true;
PresetActionEditor panel = __instance.GetComponent<PresetActionEditor>();
if (panel == null || panel.AllowClose) return true;
panel.RequestClose();
return false;
}
private static void Release() { quitting = true; battleAsset?.Release(); battleAsset = null; }
}
// Keeps the entry just left of the leftmost visible bottom button; which of
// them shows depends on the editor's state and layout.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0031", Justification = "UnityEngine.Object null checks also detect destroyed native objects.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0051", Justification = "Unity invokes these lifecycle callbacks.")]
internal sealed class PresetEditorButton : MonoBehaviour
{
private const float Spacing = 20;
private CharManageUI owner;
private Button entry;
private Button[] row;
internal void Initialize(CharManageUI editor, Button button, Button[] bottom)
{ owner = editor; entry = button; row = bottom; Refresh(); }
internal void Refresh()
{
if (entry == null || owner == null) return;
RectTransform anchor = null;
foreach (Button button in row)
{
if (button == null || !button.gameObject.activeInHierarchy) continue;
var rect = (RectTransform)button.transform;
if (anchor == null || rect.position.x < anchor.position.x) anchor = rect;
}
bool show = owner.OpenFromType == CharManageUI.ECharManageUIOpenFrom.FromPresetSetting && anchor != null;
if (entry.gameObject.activeSelf != show) entry.gameObject.SetActive(show);
if (!show) return;
var own = (RectTransform)entry.transform;
if (own.parent != anchor.parent) own.SetParent(anchor.parent, false);
own.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, anchor.rect.width);
own.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, anchor.rect.height);
own.position = anchor.position - anchor.right * (anchor.rect.width + Spacing) * anchor.lossyScale.x;
entry.interactable = true;
}
private void LateUpdate() => Refresh();
private void OnDestroy() { if (entry != null) Destroy(entry.gameObject); }
}
+200
View File
@@ -0,0 +1,200 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BD2.GameNames;
using BDNetwork;
using gamfs;
using Google.Protobuf;
using Helper;
using HarmonyLib;
using Proto.Net;
using TextComponent = BD2.GameSdk.Component;
namespace Bd2FBattle;
internal static class PresetPlans
{
private static readonly Dictionary<int, Dictionary<long, ActionChoice>> Plans = [];
private static readonly Dictionary<int, HashSet<long>> Members = [];
private static bool loaded;
private static bool supported;
private static int epoch;
private static int? activeSlot;
internal static void Install(Harmony harmony)
{
harmony.Patch(Game.Method<NetworkManager>(network => network.Send(null, null, true, null, false, null)),
prefix: new HarmonyMethod(typeof(PresetPlans), nameof(BeforeSend)));
harmony.Patch(Game.Method(() => CommonPacket.Reset()),
prefix: new HarmonyMethod(typeof(PresetPlans), nameof(Reset)));
}
internal static Dictionary<long, ActionChoice> Get(int slot) => Plans.TryGetValue(slot, out Dictionary<long, ActionChoice> plan)
? plan.ToDictionary(pair => pair.Key, pair => pair.Value.Clone()) : [];
internal static bool TryActive(IEnumerable<long> team, out Dictionary<long, ActionChoice> choices)
{
choices = null;
if (!loaded || !supported || activeSlot == null || !Members.TryGetValue(activeSlot.Value, out HashSet<long> members) ||
!members.SetEquals(team) || !Plans.TryGetValue(activeSlot.Value, out choices) || choices.Count == 0)
return false;
return true;
}
internal static void Load(Action success, Action<string> failure)
{
if (loaded)
{
if (supported) success?.Invoke();
else failure?.Invoke(ServerRequired());
return;
}
int account = epoch;
SG.Net.Send(new PresetInfoRequest { Seq = Sequence.ReqSeq }, (data, _, error) =>
{
if (account != epoch) { failure?.Invoke(Failed()); return false; }
if (error != 0 || !supported) { failure?.Invoke(error != 0 ? Failed() : ServerRequired()); return false; }
success?.Invoke();
return true;
}, true, null, false, () => failure?.Invoke(Failed()));
}
internal static void Save(PresetDBInfo preset, int slot, IEnumerable<ActionChoice> choices, Action success, Action<string> failure)
{
if (!supported) { failure?.Invoke(ServerRequired()); return; }
PresetDBInfo snapshot = PresetDBInfo.Parser.ParseFrom(ActionPlanWire.ReplacePlan(preset.ToByteArray(), choices));
snapshot.Slot = slot;
var request = new PresetSaveRequest { Seq = Sequence.ReqSeq, PresetInfo = snapshot };
int account = epoch;
SG.Net.Send(request, (data, packetCode, error) =>
{
if (account != epoch || error != 0) { failure?.Invoke(Failed()); return false; }
if (!ActionPlanWire.TryRead(data, out Dictionary<long, ActionChoice> saved, out _)) { failure?.Invoke(ServerRequired()); return false; }
Plans[slot] = saved;
RememberMembers(snapshot);
loaded = supported = true;
BattleExecution.Reset();
if (slot < CommonPacket.PresetInfoList.Count)
{
CommonPacket.PresetInfoList[slot] = snapshot;
Prset.SyncCachedIntegratedPreset(EPresetMode.Normal, slot);
}
success?.Invoke();
return true;
}, true, null, false, () => failure?.Invoke(Failed()));
}
private static string ServerRequired() => TextComponent.Translatable("fbattle.server_required").GetString();
private static string Failed() => TextComponent.Translatable("fbattle.request_failed").GetString();
private static void Reset()
{
epoch++;
loaded = supported = false;
activeSlot = null;
Plans.Clear();
Members.Clear();
BattleExecution.Reset();
}
private static void BeforeSend(IMessage __0, ref PacketRecvCallback __1, ref BatchPacketRecvCallback __3)
{
if (__0 is not (PresetInfoRequest or PresetSaveRequest or PresetUseRequest or PresetDeleteRequest)) return;
IMessage request = __0;
int account = epoch;
if (__1 != null)
{
PacketRecvCallback original = __1;
__1 = (data, code, error) =>
{
if (account == epoch && error == 0) ReceiveSafely(request, data);
return original(data, code, error);
};
}
if (__3 != null)
{
BatchPacketRecvCallback original = __3;
__3 = (data, code, error) =>
{
if (account == epoch && error == 0) ReceiveSafely(request, data.ToByteArray());
return original(data, code, error);
};
}
}
private static void ReceiveSafely(IMessage request, byte[] data)
{
try
{
switch (request)
{
case PresetInfoRequest:
ReceiveInfo(data);
break;
case PresetSaveRequest save:
if (ActionPlanWire.TryRead(data, out Dictionary<long, ActionChoice> saved, out _))
{
Plans[save.PresetInfo.Slot] = saved;
RememberMembers(save.PresetInfo);
supported = true;
BattleExecution.Reset();
}
break;
case PresetUseRequest use:
activeSlot = null;
if (ActionPlanWire.TryRead(data, out Dictionary<long, ActionChoice> applied, out int? slot))
{
if (slot != use.Slot) throw new InvalidOperationException("Preset action response slot mismatch");
activeSlot = slot;
Plans[use.Slot] = applied;
PresetDBInfo preset = CommonPacket.PresetInfoList.FirstOrDefault(p => p.Slot == use.Slot);
if (preset != null) RememberMembers(preset);
supported = true;
loaded = true;
}
BattleExecution.Reset();
break;
case PresetDeleteRequest delete:
foreach (int deletedSlot in delete.Slot)
{
Plans.Remove(deletedSlot);
Members.Remove(deletedSlot);
if (activeSlot == deletedSlot) activeSlot = null;
}
BattleExecution.Reset();
break;
}
}
catch (Exception error)
{
Reset();
Plugin.Log?.LogWarning("Preset action configuration rejected: " + error.Message);
}
}
private static void ReceiveInfo(byte[] data)
{
PresetInfoResponse response = PresetInfoResponse.Parser.ParseFrom(data);
var next = new Dictionary<int, Dictionary<long, ActionChoice>>();
bool available = false;
foreach (PresetDBInfo preset in response.PresetInfo)
{
if (ActionPlanWire.TryRead(preset.ToByteArray(), out Dictionary<long, ActionChoice> plan, out _))
{
next.Add(preset.Slot, plan);
available = true;
}
}
ActionPlanWire.TryRead(data, out Dictionary<long, ActionChoice> capability, out int? selected);
Plans.Clear();
Members.Clear();
foreach (KeyValuePair<int, Dictionary<long, ActionChoice>> pair in next) Plans.Add(pair.Key, pair.Value);
foreach (PresetDBInfo preset in response.PresetInfo) RememberMembers(preset);
activeSlot = selected;
supported = available || capability != null;
loaded = true;
}
private static void RememberMembers(PresetDBInfo preset) => Members[preset.Slot] = new HashSet<long>(
preset.DeckInfo.Select(entry => entry.DeckBaseInfo.CharInvenIndex).Where(index => index > 0));
}