Files
2026-10-28 18:54:43 +07:00

571 lines
17 KiB
Go

package common
import (
"encoding/json"
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"gac-hkrpg-go"
)
// LogInfo prints a timestamped info line (kept dependency-free).
func LogInfo(format string, args ...any) {
fmt.Printf("%s %s\n", time.Now().Format("2006-01-02 15:04:05"), fmt.Sprintf(format, args...))
}
// ---------------------------------------------------------------------------
// res.json (camelCase, produced by the AstralOS dump pipeline)
// ---------------------------------------------------------------------------
type Vector struct {
X int32 `json:"x"`
Y int32 `json:"y"`
Z int32 `json:"z"`
}
type SceneMonsterInfo struct {
Pos Vector `json:"pos"`
Rot Vector `json:"rot"`
GroupID uint32 `json:"groupId"`
InstID uint32 `json:"instId"`
MonsterID uint32 `json:"monsterId"`
EventID uint32 `json:"eventId"`
}
type SceneNpcInfo struct {
Pos Vector `json:"pos"`
Rot Vector `json:"rot"`
GroupID uint32 `json:"groupId"`
InstID uint32 `json:"instId"`
NpcID uint32 `json:"npcId"`
}
type ScenePropInfo struct {
Pos Vector `json:"pos"`
Rot Vector `json:"rot"`
GroupID uint32 `json:"groupId"`
InstID uint32 `json:"instId"`
PropState uint32 `json:"propState"`
PropID uint32 `json:"propId"`
}
type TeleportInfo struct {
Pos Vector `json:"pos"`
Rot Vector `json:"rot"`
}
type SceneData struct {
Npcs []SceneNpcInfo `json:"npcs"`
Props []ScenePropInfo `json:"props"`
Monsters []SceneMonsterInfo `json:"monsters"`
Teleports map[uint32]TeleportInfo `json:"teleports"`
FinishedSubMissions []uint32 `json:"finishedSubMissions"`
FinishedMainMissions []uint32 `json:"finishedMainMissions"`
Chests []uint32 `json:"chests"`
}
type LevelOutputConfig struct {
DimensionID uint32 `json:"dimensionId"`
GroupProperties map[uint32]map[string]GroupPropertyRule `json:"groupProperties"`
IsEnteredSceneInfo bool `json:"isEnteredSceneInfo"`
Scenes map[uint32]SceneData `json:"scenes"`
PlaneType uint32 `json:"planeType"`
WorldID uint32 `json:"worldId"`
Sections []uint32 `json:"sections"`
SavedValues map[string]int32 `json:"savedValues"`
}
type AvatarConfig struct {
WeaknessBuffID uint32 `json:"weaknessBuffId"`
DamageType string `json:"damageType"`
MaxRank uint32 `json:"maxRank"`
}
type GroupPropertyRule struct {
DefaultValue int32 `json:"DefaultValue"`
MinValue int32 `json:"MinValue"`
MaxValue int32 `json:"MaxValue"`
}
type JsonConfig struct {
MapEntrances map[uint32]MapEntranceEntry `json:"-"`
SceneAnchors map[uint32][]AnchorItem `json:"-"`
SceneDefaultAnchors map[uint32]AnchorItem `json:"-"`
MapTeleportEntrances map[uint32]uint32 `json:"-"`
// entryId -> "P<plane>_F<floor>" -> config
LevelOutputConfigs map[uint32]map[string]*LevelOutputConfig `json:"levelOutputConfigs"`
AvatarConfigs map[uint32]AvatarConfig `json:"avatarConfigs"`
MapDefaultEntranceMap map[uint32]uint32 `json:"mapDefaultEntranceMap"`
RelicAvatarRecommend map[uint32][]uint32 `json:"relicAvatarRecommend"`
SkinIDs []uint32 `json:"skinIds"`
AvatarSkillTreePoints map[uint32]map[uint32]uint32 `json:"-"`
}
var (
gameResOnce sync.Once
gameRes *JsonConfig
gameResErr error
teleportOnce sync.Once
teleportDB map[uint32]map[uint32]TeleportInfo
)
type MapEntranceEntry struct {
ID uint32 `json:"ID"`
EntranceType string `json:"EntranceType"`
PlaneID uint32 `json:"PlaneID"`
FloorID uint32 `json:"FloorID"`
StartGroupID uint32 `json:"StartGroupID"`
StartAnchorID uint32 `json:"StartAnchorID"`
}
type MazePlaneEntry struct {
PlaneID uint32 `json:"PlaneID"`
WorldID uint32 `json:"WorldID"`
StartFloorID uint32 `json:"StartFloorID"`
FloorIDList []uint32 `json:"FloorIDList"`
}
type ResourceTeleport struct {
TeleportID uint32 `json:"teleportId"`
AnchorID uint32 `json:"anchorId"`
GroupID uint32 `json:"groupId"`
InstID uint32 `json:"instId"`
Pos Vector `json:"pos"`
Rot Vector `json:"rot"`
}
type ResourceSceneEntry struct {
PlaneID uint32 `json:"planeID"`
EntryID uint32 `json:"entryID"`
Props []ScenePropInfo `json:"props"`
Monsters []SceneMonsterInfo `json:"monsters"`
Teleports []ResourceTeleport `json:"teleports"`
}
type ResourceResConfig struct {
SceneConfig []ResourceSceneEntry `json:"scene_config"`
}
type AnchorItem struct {
ID uint32 `json:"ID"`
Pos Vector `json:"pos"`
Rot Vector `json:"rot"`
}
type AnchorConfigEntry struct {
EntryID uint32 `json:"entryID"`
Anchor []AnchorItem `json:"anchor"`
}
type AnchorConfigFile struct {
AnchorConfig []AnchorConfigEntry `json:"anchor_config"`
}
// ReadResourceFile reads editable files from the current directory and its
// parents, then falls back to bundled data in ship builds.
func ReadResourceFile(paths ...string) ([]byte, error) {
for _, p := range paths {
for _, prefix := range []string{"", "..", "../..", "../../.."} {
target := filepath.Join(prefix, p)
if raw, err := os.ReadFile(target); err == nil {
return raw, nil
}
}
}
for _, p := range paths {
name := path.Clean(strings.ReplaceAll(filepath.ToSlash(p), "\\", "/"))
if name == "." || name == ".." || strings.HasPrefix(name, "../") || strings.HasPrefix(name, "/") {
continue
}
if raw, err := runtimeassets.ReadFile(name); err == nil {
return raw, nil
}
}
return nil, os.ErrNotExist
}
type ClientLuaScript struct {
Name string
Data []byte
}
// ClientLuaScripts combines maintained embedded scripts with operator-provided
// scripts. Files on disk override embedded files by name.
func ClientLuaScripts() []ClientLuaScript {
files := make(map[string][]byte)
if entries, err := runtimeassets.ReadDir("scripts"); err == nil {
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".lua") {
continue
}
if data, err := runtimeassets.ReadFile(path.Join("scripts", entry.Name())); err == nil {
files[entry.Name()] = data
}
}
}
if entries, err := os.ReadDir("scripts"); err == nil {
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".lua") {
continue
}
if data, err := os.ReadFile(filepath.Join("scripts", entry.Name())); err == nil {
files[entry.Name()] = data
}
}
}
names := make([]string, 0, len(files))
for name := range files {
names = append(names, name)
}
sort.Strings(names)
result := make([]ClientLuaScript, 0, len(names))
for _, name := range names {
result = append(result, ClientLuaScript{Name: name, Data: files[name]})
}
return result
}
func readResourceFile(paths ...string) ([]byte, error) {
return ReadResourceFile(paths...)
}
// GameRes lazily parses res.json and merges supplementary configs from resources/
func GameRes() (*JsonConfig, error) {
gameResOnce.Do(func() {
gameRes = &JsonConfig{}
raw, err := readResourceFile("res.json", "resources/res.json")
if err != nil {
gameResErr = err
return
}
if err := json.Unmarshal(raw, gameRes); err != nil {
gameResErr = fmt.Errorf("res.json is malformed: %w", err)
return
}
if gameRes.LevelOutputConfigs == nil {
gameRes.LevelOutputConfigs = map[uint32]map[string]*LevelOutputConfig{}
}
if gameRes.AvatarConfigs == nil {
gameRes.AvatarConfigs = map[uint32]AvatarConfig{}
}
if gameRes.MapDefaultEntranceMap == nil {
gameRes.MapDefaultEntranceMap = map[uint32]uint32{}
}
_ = Teleports() // ensure teleportDB is initialized
loadSupplementaryResources(gameRes)
applySceneMetadata(gameRes)
})
return gameRes, gameResErr
}
func loadSupplementaryResources(res *JsonConfig) {
// AvatarSkillTreeConfig: maps AvatarID and AnchorType (e.g. Point01 -> 1) to real PointID
if raw, err := readResourceFile("resources/AvatarSkillTreeConfig.json", "AvatarSkillTreeConfig.json"); err == nil {
var tree struct {
Entries []struct {
AvatarID uint32 `json:"AvatarID"`
PointID uint32 `json:"PointID"`
AnchorType string `json:"AnchorType"`
} `json:"avatar_skill_tree"`
}
if err := json.Unmarshal(raw, &tree); err == nil {
if res.AvatarSkillTreePoints == nil {
res.AvatarSkillTreePoints = make(map[uint32]map[uint32]uint32)
}
for _, entry := range tree.Entries {
if entry.AvatarID == 0 || entry.PointID == 0 {
continue
}
var anchorNum uint32
if n, _ := fmt.Sscanf(entry.AnchorType, "Point%d", &anchorNum); n == 1 {
if res.AvatarSkillTreePoints[entry.AvatarID] == nil {
res.AvatarSkillTreePoints[entry.AvatarID] = make(map[uint32]uint32)
}
res.AvatarSkillTreePoints[entry.AvatarID][anchorNum] = entry.PointID
}
}
}
}
// PearlSR's resource export keeps avatar data in AvatarConfig.json;
// res.json may legitimately contain an empty avatarConfigs object.
if raw, err := readResourceFile("resources/AvatarConfig.json"); err == nil {
var avatars struct {
Entries []struct {
ID uint32 `json:"AvatarID"`
DamageType string `json:"DamageType"`
MaxRank uint32 `json:"MaxRank"`
} `json:"avatar_config"`
}
if err := json.Unmarshal(raw, &avatars); err == nil {
for _, avatar := range avatars.Entries {
cfg := res.AvatarConfigs[avatar.ID]
cfg.DamageType = avatar.DamageType
cfg.MaxRank = avatar.MaxRank
res.AvatarConfigs[avatar.ID] = cfg
}
}
}
entrancesByEntry := map[uint32]MapEntranceEntry{}
if raw, err := readResourceFile("resources/MapEntrance.json", "MapEntrance.json"); err == nil {
var list []MapEntranceEntry
if json.Unmarshal(raw, &list) != nil {
var m map[string][]MapEntranceEntry
if json.Unmarshal(raw, &m) == nil {
for _, entries := range m {
list = append(list, entries...)
}
}
}
for _, e := range list {
if e.FloorID != 0 && e.ID != 0 {
if _, ok := res.MapDefaultEntranceMap[e.FloorID]; !ok {
res.MapDefaultEntranceMap[e.FloorID] = e.ID
}
entrancesByEntry[e.ID] = e
}
}
}
planesByID := map[uint32]MazePlaneEntry{}
res.MapEntrances = entrancesByEntry
res.SceneAnchors = map[uint32][]AnchorItem{}
if raw, err := readResourceFile("resources/MazePlane.json", "MazePlane.json"); err == nil {
var list []MazePlaneEntry
if json.Unmarshal(raw, &list) != nil {
var m map[string][]MazePlaneEntry
if json.Unmarshal(raw, &m) == nil {
for _, entries := range m {
list = append(list, entries...)
}
}
}
for _, p := range list {
planesByID[p.PlaneID] = p
if p.StartFloorID != 0 {
if _, ok := res.MapDefaultEntranceMap[p.StartFloorID]; !ok {
res.MapDefaultEntranceMap[p.StartFloorID] = p.PlaneID*100 + 1
}
}
}
}
if raw, err := readResourceFile("resources/res.json"); err == nil {
var res2 ResourceResConfig
if json.Unmarshal(raw, &res2) == nil && len(res2.SceneConfig) > 0 {
for _, sc := range res2.SceneConfig {
floorID := uint32(0)
if ent, ok := entrancesByEntry[sc.EntryID]; ok && ent.FloorID != 0 {
floorID = ent.FloorID
} else if p, ok := planesByID[sc.PlaneID]; ok && p.StartFloorID != 0 {
floorID = p.StartFloorID
} else {
floorID = sc.PlaneID*1000 + 1
}
if _, ok := res.MapDefaultEntranceMap[floorID]; !ok {
res.MapDefaultEntranceMap[floorID] = sc.EntryID
}
if teleportDB[floorID] == nil {
teleportDB[floorID] = map[uint32]TeleportInfo{}
}
for _, t := range sc.Teleports {
tid := t.TeleportID
if tid == 0 {
tid = t.AnchorID
}
if tid != 0 {
teleportDB[floorID][tid] = TeleportInfo{Pos: t.Pos, Rot: t.Rot}
}
}
if _, exists := res.LevelOutputConfigs[sc.EntryID]; !exists {
groups := map[uint32]SceneData{}
for _, p := range sc.Props {
gid := p.GroupID
if gid == 0 {
gid = 1
}
sd := groups[gid]
if sd.Teleports == nil {
sd.Teleports = map[uint32]TeleportInfo{}
}
sd.Props = append(sd.Props, p)
groups[gid] = sd
}
for _, m := range sc.Monsters {
gid := m.GroupID
if gid == 0 {
gid = 1
}
sd := groups[gid]
if sd.Teleports == nil {
sd.Teleports = map[uint32]TeleportInfo{}
}
sd.Monsters = append(sd.Monsters, m)
groups[gid] = sd
}
for _, t := range sc.Teleports {
gid := t.GroupID
if gid == 0 {
gid = 1
}
sd := groups[gid]
if sd.Teleports == nil {
sd.Teleports = map[uint32]TeleportInfo{}
}
tid := t.TeleportID
if tid == 0 {
tid = t.AnchorID
}
if tid != 0 {
sd.Teleports[tid] = TeleportInfo{Pos: t.Pos, Rot: t.Rot}
}
groups[gid] = sd
}
name := fmt.Sprintf("P%d_F%d", sc.PlaneID, floorID)
res.LevelOutputConfigs[sc.EntryID] = map[string]*LevelOutputConfig{
name: {
IsEnteredSceneInfo: true,
Scenes: groups,
WorldID: planesByID[sc.PlaneID].WorldID,
},
}
}
}
}
}
if raw, err := readResourceFile("resources/Anchor.json", "Anchor.json"); err == nil {
var aFile AnchorConfigFile
if json.Unmarshal(raw, &aFile) == nil && len(aFile.AnchorConfig) > 0 {
for _, item := range aFile.AnchorConfig {
res.SceneAnchors[item.EntryID] = item.Anchor
floorID := uint32(0)
if ent, ok := entrancesByEntry[item.EntryID]; ok && ent.FloorID != 0 {
floorID = ent.FloorID
} else {
floorID = item.EntryID*10 + 1
}
if teleportDB[floorID] == nil {
teleportDB[floorID] = map[uint32]TeleportInfo{}
}
for _, a := range item.Anchor {
if a.ID != 0 {
teleportDB[floorID][a.ID] = TeleportInfo{Pos: a.Pos, Rot: a.Rot}
teleportDB[floorID][item.EntryID*100+a.ID] = TeleportInfo{Pos: a.Pos, Rot: a.Rot}
}
}
if _, exists := res.LevelOutputConfigs[item.EntryID]; !exists {
tps := map[uint32]TeleportInfo{}
for _, a := range item.Anchor {
if a.ID != 0 {
tps[a.ID] = TeleportInfo{Pos: a.Pos, Rot: a.Rot}
tps[item.EntryID*100+a.ID] = TeleportInfo{Pos: a.Pos, Rot: a.Rot}
}
}
name := fmt.Sprintf("P%d_F%d", item.EntryID/100, floorID)
res.LevelOutputConfigs[item.EntryID] = map[string]*LevelOutputConfig{
name: {
IsEnteredSceneInfo: true,
Scenes: map[uint32]SceneData{
1: {Teleports: tps},
},
},
}
}
}
}
}
// Supplementary scenes do not carry world metadata. Resolve it from the
// installed entrance/plane tables, including entries supplied by Anchor.json.
floorSavedValues := map[uint32]map[string]int32{}
if raw, err := readResourceFile("resources/FloorSavedValuesConfig.json"); err == nil {
var table struct {
Floors []struct {
FloorID uint32 `json:"FloorID"`
Values []struct {
Name string `json:"Name"`
MaxValue int32 `json:"MaxValue"`
} `json:"SavedValues"`
} `json:"saved_values"`
}
if err := json.Unmarshal(raw, &table); err == nil {
// Same unlocked scene defaults as PearlSR 005d2c12 scene_mgr.zig.
for _, floor := range table.Floors {
values := map[string]int32{}
for _, value := range floor.Values {
if value.Name != "" {
values[value.Name] = value.MaxValue
}
}
floorSavedValues[floor.FloorID] = values
}
} else {
LogInfo("[SCENE] Invalid FloorSavedValuesConfig: %v", err)
}
}
for entryID, configs := range res.LevelOutputConfigs {
entrance, ok := entrancesByEntry[entryID]
if !ok {
continue
}
// Legacy dumps label every entrance in a plane with its first floor.
// An entrance has an explicit floor in MapEntrance; do not derive it.
if len(configs) == 1 {
canonical := fmt.Sprintf("P%d_F%d", entrance.PlaneID, entrance.FloorID)
for name, config := range configs {
if name != canonical {
delete(configs, name)
configs[canonical] = config
}
break
}
}
plane, ok := planesByID[entrance.PlaneID]
if !ok {
continue
}
for name, config := range configs {
config.WorldID = plane.WorldID
var configPlane, configFloor uint32
if n, _ := fmt.Sscanf(name, "P%d_F%d", &configPlane, &configFloor); n != 2 {
continue
}
if config.SavedValues == nil {
config.SavedValues = map[string]int32{}
}
for name, value := range floorSavedValues[configFloor] {
if _, exists := config.SavedValues[name]; !exists {
config.SavedValues[name] = value
}
}
}
}
}
// Teleports lazily parses teleports.json ({floor_id: {teleport_id: info}}).
func Teleports() map[uint32]map[uint32]TeleportInfo {
teleportOnce.Do(func() {
teleportDB = map[uint32]map[uint32]TeleportInfo{}
raw, err := readResourceFile("teleports.json", "resources/teleports.json")
if err == nil {
_ = json.Unmarshal(raw, &teleportDB)
}
})
return teleportDB
}