chore: upgrade ts2lua-unreal to v0.3.1 with lowercase lib/module.lua & lib/class.lua and commit framework refactor

This commit is contained in:
szy73711 committed 2026-11-30 03:43:42 +08:00
1 parent 783dccf53d
commit 3572f2da43
206 files changed
+14442 -13186

No files matched your search

@@ -0,0 +1,266 @@
local ____lualib = require("lualib_bundle")
local __TS__ClassExtends = ____lualib.__TS__ClassExtends
local __TS__New = ____lualib.__TS__New
local ____exports = __module.env
local M__share_base_logger = __MODULE__.Import("share.base.logger", __module)
local Logger = M__share_base_logger.Logger
local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module)
local ScopedObject = M__share_base_scoped_object.ScopedObject
local M__share_event_event_hub = __MODULE__.Import("share.event.event_hub", __module)
local EventHub = M__share_event_event_hub.EventHub
local M__framework_core_scheduler = __MODULE__.Import("framework.core.scheduler", __module)
local FrameScheduler = M__framework_core_scheduler.FrameScheduler
local M__framework_module_mgr_registry = __MODULE__.Import("framework.module.mgr_registry", __module)
local MgrRegistry = M__framework_module_mgr_registry.MgrRegistry
local logger = Logger("GameContext")
____exports.WorldContext = __TS__DefineClass("WorldContext", __module)
local WorldContext = ____exports.WorldContext
WorldContext.name = "WorldContext"
__TS__ClassExtends(WorldContext, ScopedObject)
function WorldContext.prototype.____constructor(self, worldGen, world)
ScopedObject.prototype.____constructor(self)
self.worldGen = worldGen
self.world = world
end
____exports.LocalPlayerContext = __TS__DefineClass("LocalPlayerContext", __module)
local LocalPlayerContext = ____exports.LocalPlayerContext
LocalPlayerContext.name = "LocalPlayerContext"
__TS__ClassExtends(LocalPlayerContext, ScopedObject)
function LocalPlayerContext.prototype.____constructor(self, playerIndex, playerController)
ScopedObject.prototype.____constructor(self)
self.services = {}
self.playerIndex = playerIndex
self.playerController = playerController
end
function LocalPlayerContext.prototype.RegisterService(self, key, service)
local old = self.services[key]
if old ~= nil and old ~= service then
old:Dispose()
end
self.services[key] = service
self:AddScopedObject(service)
return service
end
function LocalPlayerContext.prototype.GetService(self, key)
return self.services[key]
end
---
-- @module_data
local nextContextId = 0
____exports.GameInstanceContext = __TS__DefineClass("GameInstanceContext", __module)
local GameInstanceContext = ____exports.GameInstanceContext
GameInstanceContext.name = "GameInstanceContext"
__TS__ClassExtends(GameInstanceContext, ScopedObject)
function GameInstanceContext.prototype.____constructor(self, gameInstance)
ScopedObject.prototype.____constructor(self)
self.shuttingDown = false
self.localPlayers = {}
self.services = {}
self.shutdownHooks = {}
nextContextId = nextContextId + 1
self.contextId = nextContextId
self.gameInstance = gameInstance
self.scheduler = __TS__New(FrameScheduler)
self.mgrRegistry = __TS__New(MgrRegistry)
self.appEvents = __TS__New(
EventHub,
"AppLifecycle#" .. tostring(self.contextId)
)
self.worldContext = __TS__New(
____exports.WorldContext,
self.scheduler:GetCurrentWorldGen()
)
end
function GameInstanceContext.prototype.IsShuttingDown(self)
return self.shuttingDown or self:IsDisposed()
end
function GameInstanceContext.prototype.GetWorldContext(self)
return self.worldContext
end
function GameInstanceContext.prototype.GetWorldGen(self)
return self.worldContext.worldGen
end
function GameInstanceContext.prototype.GetOrCreateLocalPlayer(self, playerIndex, pc)
local lp = self.localPlayers[playerIndex]
if lp == nil or lp:IsDisposed() then
lp = __TS__New(____exports.LocalPlayerContext, playerIndex, pc)
self.localPlayers[playerIndex] = lp
elseif pc ~= nil then
lp.playerController = pc
end
return lp
end
function GameInstanceContext.prototype.RemoveLocalPlayer(self, playerIndex)
local lp = self.localPlayers[playerIndex]
if lp ~= nil then
self.localPlayers[playerIndex] = nil
lp:Dispose()
end
end
function GameInstanceContext.prototype.RegisterService(self, key, service)
local old = self.services[key]
if old ~= nil and old ~= service then
old:Dispose()
end
self.services[key] = service
return service
end
function GameInstanceContext.prototype.GetService(self, key)
return self.services[key]
end
function GameInstanceContext.prototype.AddShutdownHook(self, hook)
if self.shuttingDown then
return
end
self.shutdownHooks[#self.shutdownHooks + 1] = hook
end
function GameInstanceContext.prototype.Tick(self, unscaledDeltaSeconds, worldDeltaSeconds, isWorldPaused)
if isWorldPaused == nil then
isWorldPaused = false
end
if self:IsShuttingDown() then
return
end
self.scheduler:Tick(unscaledDeltaSeconds, worldDeltaSeconds, isWorldPaused)
end
function GameInstanceContext.prototype.OnWorldCleanup(self, nextWorld)
if self:IsShuttingDown() then
return
end
local oldGen = self.worldContext.worldGen
self.appEvents.emit.OnWorldCleanup(oldGen)
self.worldContext:Dispose()
local newGen = self.scheduler:InvalidateWorld()
self.worldContext = __TS__New(____exports.WorldContext, newGen, nextWorld)
end
function GameInstanceContext.prototype.Dispose(self)
if self:IsDisposed() then
return
end
self.shuttingDown = true
self.appEvents.emit.OnBeforeShutdown()
local playerKeys = {}
for idx in pairs(self.localPlayers) do
playerKeys[#playerKeys + 1] = idx
end
do
local i = 0
while i < #playerKeys do
local idx = playerKeys[i + 1]
local lp = self.localPlayers[idx]
self.localPlayers[idx] = nil
if lp ~= nil then
lp:Dispose()
end
i = i + 1
end
end
self.worldContext:Dispose()
self.scheduler:InvalidateWorld()
do
local i = #self.shutdownHooks - 1
while i >= 0 do
self.shutdownHooks[i + 1]()
i = i - 1
end
end
self.shutdownHooks = {}
local serviceList = {}
for k, svc in pairs(self.services) do
if svc ~= nil then
self.services[k] = nil
serviceList[#serviceList + 1] = svc
end
end
do
local i = 0
while i < #serviceList do
serviceList[i + 1]:Dispose()
i = i + 1
end
end
self.mgrRegistry:Dispose()
self.scheduler:Dispose()
self.appEvents:Dispose()
ScopedObject.prototype.Dispose(self)
logger:Info("GameInstanceContext disposed", {contextId = self.contextId})
end
---
-- @module_data
local activeContextsByKey = {}
---
-- @noSelf
function ____exports.GetGameInstanceKey(gameInstance)
if gameInstance.GetName ~= nil then
return gameInstance:GetName()
end
return tostring(gameInstance)
end
---
-- @noSelf
function ____exports.CreateGameInstanceContext(gameInstance)
local key = ____exports.GetGameInstanceKey(gameInstance)
local old = activeContextsByKey[key]
if old ~= nil and not old:IsDisposed() then
old:Dispose()
end
local ctx = __TS__New(____exports.GameInstanceContext, gameInstance)
activeContextsByKey[key] = ctx
return ctx
end
---
-- @noSelf
function ____exports.GetGameInstanceContext(gameInstance)
return activeContextsByKey[____exports.GetGameInstanceKey(gameInstance)]
end
---
-- @noSelf
function ____exports.DestroyGameInstanceContext(gameInstance)
local key = ____exports.GetGameInstanceKey(gameInstance)
local ctx = activeContextsByKey[key]
if ctx ~= nil then
activeContextsByKey[key] = nil
ctx:Dispose()
end
end
---
-- @noSelf
function ____exports.GetActiveGameInstanceContextCount()
local count = 0
for _, ctx in pairs(activeContextsByKey) do
if ctx ~= nil and not ctx:IsDisposed() then
count = count + 1
end
end
return count
end
function __module.StashData(env, to)
local ____has = to.__has__
if not ____has then
____has = {}
to.__has__ = ____has
end
to.nextContextId = nextContextId
____has.nextContextId = true
to.activeContextsByKey = activeContextsByKey
____has.activeContextsByKey = true
end
function __module.RestoreData(env, from)
local ____has = from.__has__
if not ____has then
return
end
if ____has.nextContextId then
nextContextId = from.nextContextId
end
if ____has.activeContextsByKey then
activeContextsByKey = from.activeContextsByKey
end
end
function __module.UpdateImports()
Logger = M__share_base_logger.Logger
ScopedObject = M__share_base_scoped_object.ScopedObject
EventHub = M__share_event_event_hub.EventHub
FrameScheduler = M__framework_core_scheduler.FrameScheduler
MgrRegistry = M__framework_module_mgr_registry.MgrRegistry
end
+365
View File
@@ -0,0 +1,365 @@
local ____exports = __module.env
local FALLBACK_NULL = {__json_null__ = true}
local FALLBACK_EMPTY_ARRAY = {__json_empty_array__ = true}
---
-- @module_data
local cachedNative = nil
local function TryLoadNativeJson()
if cachedNative ~= nil then
local ____temp_0
if cachedNative == false then
____temp_0 = nil
else
____temp_0 = cachedNative
end
return ____temp_0
end
local ok, mod = pcall(require, "ue_json")
if ok and type(mod) == "table" and type(mod.encode) == "function" and type(mod.decode) == "function" then
cachedNative = mod
return cachedNative
end
cachedNative = false
return nil
end
local function EscapeJsonString(str)
local escaped = string.gsub(
str,
"[%z-\\\"]",
function(ch)
if ch == "\"" then
return "\\\""
end
if ch == "\\" then
return "\\\\"
end
if ch == "\b" then
return "\\b"
end
if ch == "\f" then
return "\\f"
end
if ch == "\n" then
return "\\n"
end
if ch == "\r" then
return "\\r"
end
if ch == "\t" then
return "\\t"
end
return string.format(
"\\u%04x",
string.byte(ch)
)
end
)
return ("\"" .. escaped) .. "\""
end
local function IsPureArray(tbl)
local count = 0
local maxKey = 0
for k in pairs(tbl) do
count = count + 1
if type(k) ~= "number" or math.type(k) ~= "integer" or k <= 0 then
return false, 0
end
if k > maxKey then
maxKey = k
end
end
return count > 0 and maxKey == count, maxKey
end
local function FallbackEncodeValue(val, depth)
if depth > 64 then
return nil, "JSON encode exceeded maximum depth (64)"
end
if val == nil or val == FALLBACK_NULL then
return "null", nil
end
if val == FALLBACK_EMPTY_ARRAY then
return "[]", nil
end
local t = type(val)
if t == "boolean" then
return val and "true" or "false", nil
end
if t == "number" then
local num = val
if num ~= num or num == math.huge or num == -math.huge then
return nil, "Cannot encode NaN or Infinity to JSON"
end
if math.type(num) == "integer" then
return string.format("%d", num), nil
end
return string.format("%.17g", num), nil
end
if t == "string" then
return EscapeJsonString(val), nil
end
if t == "table" then
local tbl = val
local isArr, len = IsPureArray(tbl)
if isArr then
local items = {}
do
local i = 1
while i <= len do
local encoded, err = FallbackEncodeValue(tbl[i], depth + 1)
if err ~= nil then
return nil, err
end
items[#items + 1] = encoded
i = i + 1
end
end
return ("[" .. table.concat(items, ",")) .. "]", nil
end
local pairsOut = {}
for k, v in pairs(tbl) do
local kt = type(k)
if kt ~= "string" and kt ~= "number" then
return nil, "Unsupported JSON object key type: " .. kt
end
local encodedVal, err = FallbackEncodeValue(v, depth + 1)
if err ~= nil then
return nil, err
end
pairsOut[#pairsOut + 1] = (EscapeJsonString(tostring(k)) .. ":") .. encodedVal
end
return ("{" .. table.concat(pairsOut, ",")) .. "}", nil
end
return nil, "Unsupported Lua type for JSON encode: " .. t
end
local function SkipWs(st)
while st.pos <= st.len do
local b = string.byte(st.src, st.pos)
if b == 32 or b == 9 or b == 10 or b == 13 then
st.pos = st.pos + 1
else
break
end
end
end
local function ParseString(st)
st.pos = st.pos + 1
local out = {}
while st.pos <= st.len do
local ch = string.sub(st.src, st.pos, st.pos)
if ch == "\"" then
st.pos = st.pos + 1
return table.concat(out), nil
end
if ch == "\\" then
st.pos = st.pos + 1
if st.pos > st.len then
return nil, "Unterminated escape in JSON string"
end
local esc = string.sub(st.src, st.pos, st.pos)
st.pos = st.pos + 1
if esc == "\"" or esc == "\\" or esc == "/" then
out[#out + 1] = esc
elseif esc == "b" then
out[#out + 1] = "\b"
elseif esc == "f" then
out[#out + 1] = "\f"
elseif esc == "n" then
out[#out + 1] = "\n"
elseif esc == "r" then
out[#out + 1] = "\r"
elseif esc == "t" then
out[#out + 1] = "\t"
elseif esc == "u" then
local hex = string.sub(st.src, st.pos, st.pos + 3)
local code = tonumber(hex, 16)
if code == nil or #hex < 4 then
return nil, "Invalid \\u escape"
end
st.pos = st.pos + 4
out[#out + 1] = utf8.char(code)
else
return nil, "Invalid escape char: \\" .. esc
end
else
out[#out + 1] = ch
st.pos = st.pos + 1
end
end
return nil, "Unterminated JSON string"
end
local function ParseValue(st, depth)
if depth > 64 then
return nil, "JSON decode exceeded maximum depth (64)"
end
SkipWs(st)
if st.pos > st.len then
return nil, "Unexpected EOF"
end
local ch = string.sub(st.src, st.pos, st.pos)
if ch == "\"" then
return ParseString(st)
end
if ch == "{" then
st.pos = st.pos + 1
local obj = {}
SkipWs(st)
if string.sub(st.src, st.pos, st.pos) == "}" then
st.pos = st.pos + 1
return obj, nil
end
while true do
SkipWs(st)
if string.sub(st.src, st.pos, st.pos) ~= "\"" then
return nil, "Expected string key in JSON object"
end
local key, keyErr = ParseString(st)
if keyErr ~= nil then
return nil, keyErr
end
SkipWs(st)
if string.sub(st.src, st.pos, st.pos) ~= ":" then
return nil, "Expected ':' in JSON object"
end
st.pos = st.pos + 1
local val, valErr = ParseValue(st, depth + 1)
if valErr ~= nil then
return nil, valErr
end
obj[key] = val
SkipWs(st)
local sep = string.sub(st.src, st.pos, st.pos)
if sep == "}" then
st.pos = st.pos + 1
return obj, nil
end
if sep ~= "," then
return nil, "Expected ',' or '}' in JSON object"
end
st.pos = st.pos + 1
end
end
if ch == "[" then
st.pos = st.pos + 1
local arr = {}
SkipWs(st)
if string.sub(st.src, st.pos, st.pos) == "]" then
st.pos = st.pos + 1
return arr, nil
end
local idx = 1
while true do
local val, valErr = ParseValue(st, depth + 1)
if valErr ~= nil then
return nil, valErr
end
arr[idx] = val
idx = idx + 1
SkipWs(st)
local sep = string.sub(st.src, st.pos, st.pos)
if sep == "]" then
st.pos = st.pos + 1
return arr, nil
end
if sep ~= "," then
return nil, "Expected ',' or ']' in JSON array"
end
st.pos = st.pos + 1
end
end
if string.sub(st.src, st.pos, st.pos + 3) == "true" then
st.pos = st.pos + 4
return true, nil
end
if string.sub(st.src, st.pos, st.pos + 4) == "false" then
st.pos = st.pos + 5
return false, nil
end
if string.sub(st.src, st.pos, st.pos + 3) == "null" then
st.pos = st.pos + 4
return st.keepNull and FALLBACK_NULL or nil, nil
end
local numStr = string.match(st.src, "^%-?%d+%.?%d*[eE]?[%+%-]?%d*", st.pos)
if numStr ~= nil and numStr ~= "" then
local parsed = tonumber(numStr)
if parsed ~= nil then
st.pos = st.pos + #numStr
return parsed, nil
end
end
return nil, "Unexpected token at pos " .. tostring(st.pos)
end
local function FallbackDecode(raw, keepNull)
local st = {src = raw, len = #raw, pos = 1, keepNull = keepNull}
local val, err = ParseValue(st, 0)
if err ~= nil then
return nil, err
end
SkipWs(st)
if st.pos <= st.len then
return nil, "Trailing characters after JSON value"
end
return val, nil
end
function ____exports.IsNativeBackend()
return TryLoadNativeJson() ~= nil
end
function ____exports.GetNull()
local native = TryLoadNativeJson()
local ____temp_1
if native ~= nil then
____temp_1 = native.null
else
____temp_1 = FALLBACK_NULL
end
return ____temp_1
end
function ____exports.GetEmptyArray()
local native = TryLoadNativeJson()
local ____temp_2
if native ~= nil then
____temp_2 = native.empty_array
else
____temp_2 = FALLBACK_EMPTY_ARRAY
end
return ____temp_2
end
function ____exports.Encode(value)
local native = TryLoadNativeJson()
if native ~= nil then
return native.encode(value)
end
return FallbackEncodeValue(value, 0)
end
function ____exports.Decode(raw, keepNull)
if keepNull == nil then
keepNull = false
end
if type(raw) ~= "string" or raw == "" then
return nil, "Empty JSON input"
end
local native = TryLoadNativeJson()
if native ~= nil then
return native.decode(raw, keepNull)
end
return FallbackDecode(raw, keepNull)
end
function __module.StashData(env, to)
local ____has = to.__has__
if not ____has then
____has = {}
to.__has__ = ____has
end
to.cachedNative = cachedNative
____has.cachedNative = true
end
function __module.RestoreData(env, from)
local ____has = from.__has__
if not ____has then
return
end
if ____has.cachedNative then
cachedNative = from.cachedNative
end
end
function __module.UpdateImports()
end
+404
View File
@@ -0,0 +1,404 @@
local ____lualib = require("lualib_bundle")
local __TS__New = ____lualib.__TS__New
local __TS__InstanceOf = ____lualib.__TS__InstanceOf
local __TS__ArraySetLength = ____lualib.__TS__ArraySetLength
local ____exports = __module.env
local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module)
local ScopedObject = M__share_base_scoped_object.ScopedObject
local M__share_base_traceback = __MODULE__.Import("share.base.traceback", __module)
local tbpcall = M__share_base_traceback.tbpcall
____exports.TimerHandle = __TS__DefineClass("TimerHandle", __module)
local TimerHandle = ____exports.TimerHandle
TimerHandle.name = "TimerHandle"
function TimerHandle.prototype.____constructor(self, scheduler, entryId)
self.disposed = false
self.scheduler = scheduler
self.entryId = entryId
end
function TimerHandle.prototype.GetId(self)
return self.entryId
end
function TimerHandle.prototype.IsDisposed(self)
return self.disposed
end
function TimerHandle.prototype.IsActive(self)
return not self.disposed and self.scheduler ~= nil and self.scheduler:IsEntryActive(self.entryId)
end
function TimerHandle.prototype.Cancel(self)
self:Dispose()
end
function TimerHandle.prototype.Dispose(self)
if self.disposed then
return
end
self.disposed = true
if self.scheduler ~= nil then
local s = self.scheduler
self.scheduler = nil
s:CancelById(self.entryId)
end
end
function TimerHandle.prototype.MarkCompletedInternal(self)
self.disposed = true
self.scheduler = nil
end
____exports.FrameScheduler = __TS__DefineClass("FrameScheduler", __module)
local FrameScheduler = ____exports.FrameScheduler
FrameScheduler.name = "FrameScheduler"
function FrameScheduler.prototype.____constructor(self)
self.nextId = 0
self.monotonicTime = 0
self.worldTime = 0
self.currentWorldGen = 1
self.frameCounter = 0
self.disposed = false
self.entriesById = {}
self.frameIds = {}
self.worldIds = {}
self.monotonicIds = {}
end
function FrameScheduler.prototype.IsDisposed(self)
return self.disposed
end
function FrameScheduler.prototype.NowSeconds(self)
return self.monotonicTime
end
function FrameScheduler.prototype.GetWorldTimeSeconds(self)
return self.worldTime
end
function FrameScheduler.prototype.GetFrameCount(self)
return self.frameCounter
end
function FrameScheduler.prototype.GetCurrentWorldGen(self)
return self.currentWorldGen
end
function FrameScheduler.prototype.IsEntryActive(self, id)
local entry = self.entriesById[id]
return entry ~= nil and not entry.cancelled
end
function FrameScheduler.prototype.AddFrameTimer(self, frames, callback, owner)
local count = math.max(
1,
math.floor(frames)
)
return self:CreateEntry(
"frame",
count,
0,
false,
callback,
owner
)
end
function FrameScheduler.prototype.RunNextFrame(self, callback, owner)
return self:AddFrameTimer(1, callback, owner)
end
function FrameScheduler.prototype.AddWorldTimer(self, delaySeconds, callback, owner)
local delay = math.max(0, delaySeconds)
return self:CreateEntry(
"world",
0,
delay,
false,
callback,
owner
)
end
function FrameScheduler.prototype.AddWorldRepeatTimer(self, intervalSeconds, callback, owner)
if intervalSeconds <= 0 then
return self:CreateEntry(
"frame",
1,
0,
true,
callback,
owner
)
end
return self:CreateEntry(
"world",
0,
intervalSeconds,
true,
callback,
owner
)
end
function FrameScheduler.prototype.AddTimer(self, delaySeconds, callback, owner)
return self:AddMonotonicTimer(delaySeconds, callback, owner)
end
function FrameScheduler.prototype.AddRepeatTimer(self, intervalSeconds, callback, owner)
return self:AddMonotonicRepeatTimer(intervalSeconds, callback, owner)
end
function FrameScheduler.prototype.AddMonotonicTimer(self, delaySeconds, callback, owner)
local delay = math.max(0, delaySeconds)
return self:CreateEntry(
"monotonic",
0,
delay,
false,
callback,
owner
)
end
function FrameScheduler.prototype.AddMonotonicRepeatTimer(self, intervalSeconds, callback, owner)
local interval = math.max(0.001, intervalSeconds)
return self:CreateEntry(
"monotonic",
0,
interval,
true,
callback,
owner
)
end
function FrameScheduler.prototype.CreateEntry(self, domain, remainingFrames, intervalSec, ____repeat, callback, owner)
self.nextId = self.nextId + 1
local id = self.nextId
local handle = __TS__New(____exports.TimerHandle, self, id)
if self.disposed or owner ~= nil and owner:IsDisposed() then
handle:MarkCompletedInternal()
return handle
end
local baseTime = domain == "world" and self.worldTime or self.monotonicTime
local entry = {
id = id,
domain = domain,
callback = callback,
owner = owner,
["repeat"] = ____repeat,
cancelled = false,
remainingFrames = remainingFrames,
intervalSec = intervalSec,
nextTriggerTime = baseTime + intervalSec,
worldGen = self.currentWorldGen,
handle = handle
}
self.entriesById[id] = entry
if domain == "frame" then
self.frameIds[#self.frameIds + 1] = id
elseif domain == "world" then
self.worldIds[#self.worldIds + 1] = id
else
self.monotonicIds[#self.monotonicIds + 1] = id
end
if owner ~= nil and __TS__InstanceOf(owner, ScopedObject) then
owner:AddScopedObject(handle)
end
return handle
end
function FrameScheduler.prototype.CancelById(self, id)
local entry = self.entriesById[id]
if entry == nil then
return
end
entry.cancelled = true
self.entriesById[id] = nil
end
function FrameScheduler.prototype.InvalidateWorld(self)
local prevGen = self.currentWorldGen
self.currentWorldGen = self.currentWorldGen + 1
self.worldTime = 0
self:CancelEntriesForWorldGen(self.worldIds, prevGen)
self:CancelEntriesForWorldGen(self.frameIds, prevGen)
return self.currentWorldGen
end
function FrameScheduler.prototype.CancelEntriesForWorldGen(self, idList, worldGen)
local kept = {}
do
local i = 0
while i < #idList do
do
local id = idList[i + 1]
local entry = self.entriesById[id]
if entry == nil or entry.cancelled then
goto __continue38
end
if entry.worldGen == worldGen then
entry.cancelled = true
self.entriesById[id] = nil
entry.handle:MarkCompletedInternal()
else
kept[#kept + 1] = id
end
end
::__continue38::
i = i + 1
end
end
__TS__ArraySetLength(idList, 0)
do
local i = 0
while i < #kept do
idList[i + 1] = kept[i + 1]
i = i + 1
end
end
end
function FrameScheduler.prototype.Tick(self, unscaledDeltaSeconds, worldDeltaSeconds, isWorldPaused)
if isWorldPaused == nil then
isWorldPaused = false
end
if self.disposed then
return
end
local safeUnscaled = math.max(0, unscaledDeltaSeconds)
self.monotonicTime = self.monotonicTime + safeUnscaled
self.frameCounter = self.frameCounter + 1
self:ProcessTimedQueue(self.monotonicIds, self.monotonicTime)
if not isWorldPaused then
local safeWorldDt = math.max(0, worldDeltaSeconds or safeUnscaled)
self.worldTime = self.worldTime + safeWorldDt
self:ProcessTimedQueue(self.worldIds, self.worldTime)
end
self:ProcessFrameQueue()
end
function FrameScheduler.prototype.ProcessFrameQueue(self)
local snapshotLen = #self.frameIds
local nextFrameIds = {}
do
local i = 0
while i < snapshotLen do
do
local id = self.frameIds[i + 1]
local entry = self.entriesById[id]
if entry == nil or entry.cancelled then
goto __continue49
end
if entry.owner ~= nil and entry.owner:IsDisposed() then
entry.cancelled = true
self.entriesById[id] = nil
entry.handle:MarkCompletedInternal()
goto __continue49
end
entry.remainingFrames = entry.remainingFrames - 1
if entry.remainingFrames <= 0 then
if not entry["repeat"] then
entry.cancelled = true
self.entriesById[id] = nil
entry.handle:MarkCompletedInternal()
else
entry.remainingFrames = 1
nextFrameIds[#nextFrameIds + 1] = id
end
tbpcall(entry.callback)
else
nextFrameIds[#nextFrameIds + 1] = id
end
end
::__continue49::
i = i + 1
end
end
do
local i = snapshotLen
while i < #self.frameIds do
local id = self.frameIds[i + 1]
local entry = self.entriesById[id]
if entry ~= nil and not entry.cancelled then
nextFrameIds[#nextFrameIds + 1] = id
end
i = i + 1
end
end
self.frameIds = nextFrameIds
end
function FrameScheduler.prototype.ProcessTimedQueue(self, idList, currentTime)
local snapshotLen = #idList
local kept = {}
do
local i = 0
while i < snapshotLen do
do
local id = idList[i + 1]
local entry = self.entriesById[id]
if entry == nil or entry.cancelled then
goto __continue61
end
if entry.owner ~= nil and entry.owner:IsDisposed() then
entry.cancelled = true
self.entriesById[id] = nil
entry.handle:MarkCompletedInternal()
goto __continue61
end
if currentTime + 1e-9 >= entry.nextTriggerTime then
if not entry["repeat"] then
entry.cancelled = true
self.entriesById[id] = nil
entry.handle:MarkCompletedInternal()
tbpcall(entry.callback)
else
entry.nextTriggerTime = currentTime + entry.intervalSec
tbpcall(entry.callback)
if not entry.cancelled and self.entriesById[id] ~= nil then
kept[#kept + 1] = id
end
end
else
kept[#kept + 1] = id
end
end
::__continue61::
i = i + 1
end
end
do
local i = snapshotLen
while i < #idList do
local id = idList[i + 1]
local entry = self.entriesById[id]
if entry ~= nil and not entry.cancelled then
kept[#kept + 1] = id
end
i = i + 1
end
end
__TS__ArraySetLength(idList, 0)
do
local i = 0
while i < #kept do
idList[i + 1] = kept[i + 1]
i = i + 1
end
end
end
function FrameScheduler.prototype.GetStats(self)
local frameTasks = self:CountActive(self.frameIds)
local worldTasks = self:CountActive(self.worldIds)
local monotonicTasks = self:CountActive(self.monotonicIds)
return {frameTasks = frameTasks, worldTasks = worldTasks, monotonicTasks = monotonicTasks, totalTasks = frameTasks + worldTasks + monotonicTasks}
end
function FrameScheduler.prototype.CountActive(self, idList)
local count = 0
do
local i = 0
while i < #idList do
local entry = self.entriesById[idList[i + 1]]
if entry ~= nil and not entry.cancelled then
count = count + 1
end
i = i + 1
end
end
return count
end
function FrameScheduler.prototype.Dispose(self)
if self.disposed then
return
end
self.disposed = true
for id, entry in pairs(self.entriesById) do
if entry ~= nil then
entry.cancelled = true
entry.handle:MarkCompletedInternal()
self.entriesById[id] = nil
end
end
self.frameIds = {}
self.worldIds = {}
self.monotonicIds = {}
end
function __module.UpdateImports()
ScopedObject = M__share_base_scoped_object.ScopedObject
tbpcall = M__share_base_traceback.tbpcall
end
+130
View File
@@ -0,0 +1,130 @@
local ____lualib = require("lualib_bundle")
local __TS__ClassExtends = ____lualib.__TS__ClassExtends
local __TS__New = ____lualib.__TS__New
local ____exports = __module.env
local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module)
local ScopedObject = M__share_base_scoped_object.ScopedObject
____exports.MgrDataBase = __TS__DefineClass("MgrDataBase", __module)
local MgrDataBase = ____exports.MgrDataBase
MgrDataBase.name = "MgrDataBase"
function MgrDataBase.prototype.____constructor(self)
end
function MgrDataBase.prototype.OnEnterGame(self)
end
function MgrDataBase.prototype.OnExitGame(self)
end
____exports.ControllerBase = __TS__DefineClass("ControllerBase", __module)
local ControllerBase = ____exports.ControllerBase
ControllerBase.name = "ControllerBase"
__TS__ClassExtends(ControllerBase, ScopedObject)
function ControllerBase.prototype.____constructor(self, mgr)
ScopedObject.prototype.____constructor(self)
self.mgr = mgr
end
function ControllerBase.prototype.OnEnter(self)
end
function ControllerBase.prototype.OnBindEvents(self)
end
function ControllerBase.prototype.OnActive(self)
end
function ControllerBase.prototype.OnExit(self)
end
____exports.MgrBase = __TS__DefineClass("MgrBase", __module)
local MgrBase = ____exports.MgrBase
MgrBase.name = "MgrBase"
__TS__ClassExtends(MgrBase, ScopedObject)
function MgrBase.prototype.____constructor(self, ...)
ScopedObject.prototype.____constructor(self, ...)
self.controllers = {}
self.isActive = true
end
function MgrBase.prototype.Initialization(self)
self:OnCreate()
self:OnBindControllers()
self:OnBindEvents()
end
function MgrBase.prototype.OnBindControllers(self)
end
function MgrBase.prototype.OnBindEvents(self)
end
function MgrBase.prototype.OnEnterGame(self)
end
function MgrBase.prototype.OnExitGame(self)
end
function MgrBase.prototype.OnClean(self)
end
function MgrBase.prototype.SetActive(self, active)
self.isActive = active
if active then
self:EnableControllers()
self:EnableAllEventListeners()
else
self:DisableControllers()
self:DisableAllEventListeners()
end
end
function MgrBase.prototype.AddController(self, ctor)
local existing = self.controllers[ctor]
assert(existing == nil, "MgrBase.AddController: controller already added")
local ctrl = __TS__New(ctor, self)
self.controllers[ctor] = ctrl
ctrl:OnEnter()
ctrl:OnBindEvents()
ctrl:OnActive()
return ctrl
end
function MgrBase.prototype.GetController(self, ctor)
return self.controllers[ctor]
end
function MgrBase.prototype.DelController(self, ctor)
local ctrl = self.controllers[ctor]
if ctrl == nil then
return
end
self.controllers[ctor] = nil
ctrl:OnExit()
ctrl:Dispose()
end
function MgrBase.prototype.DelAllControllers(self)
local list = {}
for ctorKey, ctrl in pairs(self.controllers) do
if ctrl ~= nil then
self.controllers[ctorKey] = nil
list[#list + 1] = ctrl
end
end
do
local i = 0
while i < #list do
list[i + 1]:OnExit()
list[i + 1]:Dispose()
i = i + 1
end
end
end
function MgrBase.prototype.EnableControllers(self)
for _, ctrl in pairs(self.controllers) do
if ctrl ~= nil then
ctrl:EnableAllEventListeners()
ctrl:OnActive()
end
end
end
function MgrBase.prototype.DisableControllers(self)
for _, ctrl in pairs(self.controllers) do
if ctrl ~= nil then
ctrl:DisableAllEventListeners()
end
end
end
function MgrBase.prototype.Dispose(self)
if self:IsDisposed() then
return
end
self:DelAllControllers()
self:OnClean()
ScopedObject.prototype.Dispose(self)
end
function __module.UpdateImports()
ScopedObject = M__share_base_scoped_object.ScopedObject
end
@@ -0,0 +1,124 @@
local ____lualib = require("lualib_bundle")
local __TS__New = ____lualib.__TS__New
local ____exports = __module.env
---
-- @noSelf
local function ResolveClassName(ctor, explicitName)
if explicitName ~= nil and explicitName ~= "" then
return explicitName
end
local rawName = ctor.name
if rawName ~= nil and type(rawName) == "string" and rawName ~= "" then
return rawName
end
return tostring(ctor)
end
____exports.MgrRegistry = __TS__DefineClass("MgrRegistry", __module)
local MgrRegistry = ____exports.MgrRegistry
MgrRegistry.name = "MgrRegistry"
function MgrRegistry.prototype.____constructor(self)
self.mgrByCtor = {}
self.mgrNameByCtor = {}
self.mgrByName = {}
self.dataByCtor = {}
self.disposed = false
end
function MgrRegistry.prototype.CreateMgrData(self, ctor)
local existing = self.dataByCtor[ctor]
if existing ~= nil then
return existing
end
local data = __TS__New(ctor)
self.dataByCtor[ctor] = data
return data
end
function MgrRegistry.prototype.GetMgrData(self, ctor)
return self.dataByCtor[ctor]
end
function MgrRegistry.prototype.DelMgrData(self, ctor)
local data = self.dataByCtor[ctor]
if data == nil then
return
end
self.dataByCtor[ctor] = nil
data:Dispose()
end
function MgrRegistry.prototype.CreateMgr(self, ctor, explicitName)
local existing = self.mgrByCtor[ctor]
if existing ~= nil then
return existing
end
local mgr = __TS__New(ctor)
local name = ResolveClassName(ctor, explicitName)
self.mgrByCtor[ctor] = mgr
self.mgrNameByCtor[ctor] = name
self.mgrByName[name] = mgr
mgr:Initialization()
return mgr
end
function MgrRegistry.prototype.GetMgr(self, ctor)
return self.mgrByCtor[ctor]
end
function MgrRegistry.prototype.GetMgrByName(self, name)
return self.mgrByName[name]
end
function MgrRegistry.prototype.DelMgr(self, ctor)
local mgr = self.mgrByCtor[ctor]
if mgr == nil then
return
end
local name = self.mgrNameByCtor[ctor]
self.mgrByCtor[ctor] = nil
self.mgrNameByCtor[ctor] = nil
if name ~= nil and self.mgrByName[name] == mgr then
self.mgrByName[name] = nil
end
mgr:Dispose()
end
function MgrRegistry.prototype.GetMgrCount(self)
local count = 0
for _, mgr in pairs(self.mgrByCtor) do
if mgr ~= nil then
count = count + 1
end
end
return count
end
function MgrRegistry.prototype.Dispose(self)
if self.disposed then
return
end
self.disposed = true
local mgrList = {}
for key, mgr in pairs(self.mgrByCtor) do
if mgr ~= nil then
self.mgrByCtor[key] = nil
mgrList[#mgrList + 1] = mgr
end
end
self.mgrNameByCtor = {}
self.mgrByName = {}
do
local i = 0
while i < #mgrList do
mgrList[i + 1]:Dispose()
i = i + 1
end
end
local dataList = {}
for key, data in pairs(self.dataByCtor) do
if data ~= nil then
self.dataByCtor[key] = nil
dataList[#dataList + 1] = data
end
end
do
local i = 0
while i < #dataList do
dataList[i + 1]:Dispose()
i = i + 1
end
end
end
function __module.UpdateImports()
end
@@ -0,0 +1,12 @@
local ____exports = __module.env
---
-- @noSelfInFile
____exports.ASSET_KEYS = {MINI_SETTINGS_ICON = "tex.mini_settings_icon", MINI_SETTINGS_WIDGET = "ui.mini_settings"}
____exports.BASE_ASSET_PATHS = {[____exports.ASSET_KEYS.MINI_SETTINGS_ICON] = "/Game/UI/Textures/T_MiniSettingsIcon.T_MiniSettingsIcon", [____exports.ASSET_KEYS.MINI_SETTINGS_WIDGET] = "/Game/UI/WBP_MiniSettings.WBP_MiniSettings_C"}
function ____exports.RegisterBaseAssetCatalog(subsystem)
for logicalKey, softPath in pairs(____exports.BASE_ASSET_PATHS) do
subsystem:RegisterBaseAssetKey(logicalKey, softPath)
end
end
function __module.UpdateImports()
end
@@ -0,0 +1,348 @@
local ____lualib = require("lualib_bundle")
local __TS__ClassExtends = ____lualib.__TS__ClassExtends
local __TS__New = ____lualib.__TS__New
local __TS__InstanceOf = ____lualib.__TS__InstanceOf
local ____exports = __module.env
local M__share_base_logger = __MODULE__.Import("share.base.logger", __module)
local Logger = M__share_base_logger.Logger
local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module)
local ScopedObject = M__share_base_scoped_object.ScopedObject
local M__share_base_traceback = __MODULE__.Import("share.base.traceback", __module)
local tbpcall = M__share_base_traceback.tbpcall
local M__framework_context_game_context = __MODULE__.Import("framework.context.game_context", __module)
local GetGameInstanceKey = M__framework_context_game_context.GetGameInstanceKey
local M__framework_resource_asset_catalog = __MODULE__.Import("framework.resource.asset_catalog", __module)
local RegisterBaseAssetCatalog = M__framework_resource_asset_catalog.RegisterBaseAssetCatalog
local logger = Logger("ResourceService")
____exports.UEResourceBackend = __TS__DefineClass("UEResourceBackend", __module)
local UEResourceBackend = ____exports.UEResourceBackend
UEResourceBackend.name = "UEResourceBackend"
function UEResourceBackend.prototype.____constructor(self, subsystem)
self.subsystem = subsystem
end
function UEResourceBackend.prototype.ResolveAssetPath(self, keyOrPath)
return self.subsystem:ResolveAssetPath(keyOrPath)
end
function UEResourceBackend.prototype.DoesAssetExist(self, keyOrPath)
return self.subsystem:DoesAssetExist(keyOrPath)
end
function UEResourceBackend.prototype.IsPackagedMode(self)
return UE.ULuaResourceSubsystem.IsPackagedResourceMode()
end
function UEResourceBackend.prototype.RequestLoadObjectAsync(self, keyOrPath, worldGen)
return self.subsystem:RequestLoadObjectAsync(keyOrPath, worldGen)
end
function UEResourceBackend.prototype.RequestLoadClassAsync(self, keyOrPath, worldGen)
return self.subsystem:RequestLoadClassAsync(keyOrPath, worldGen)
end
function UEResourceBackend.prototype.CancelRequest(self, requestId)
return self.subsystem:CancelRequest(requestId)
end
function UEResourceBackend.prototype.CancelRequestsForWorld(self, worldGen)
return self.subsystem:CancelRequestsForWorld(worldGen)
end
function UEResourceBackend.prototype.ReleaseAsset(self, resolvedSoftPath)
self.subsystem:ReleaseAsset(resolvedSoftPath)
end
function UEResourceBackend.prototype.GetResourceStats(self)
return self.subsystem:GetResourceStats()
end
____exports.ResourceLease = __TS__DefineClass("ResourceLease", __module)
local ResourceLease = ____exports.ResourceLease
ResourceLease.name = "ResourceLease"
function ResourceLease.prototype.____constructor(self, resolvedPath, asset, backend)
self.disposed = false
self.resolvedPath = resolvedPath
self.asset = asset
self.backend = backend
end
function ResourceLease.prototype.GetAsset(self)
if self.disposed then
return nil
end
return self.asset
end
function ResourceLease.prototype.IsDisposed(self)
return self.disposed
end
function ResourceLease.prototype.Dispose(self)
if self.disposed then
return
end
self.disposed = true
self.asset = nil
if self.backend ~= nil then
local b = self.backend
self.backend = nil
b:ReleaseAsset(self.resolvedPath)
end
end
____exports.ResourceLoadHandle = __TS__DefineClass("ResourceLoadHandle", __module)
local ResourceLoadHandle = ____exports.ResourceLoadHandle
ResourceLoadHandle.name = "ResourceLoadHandle"
function ResourceLoadHandle.prototype.____constructor(self, service, requestId)
self.disposed = false
self.service = service
self.requestId = requestId
end
function ResourceLoadHandle.prototype.AttachLeaseInternal(self, lease)
if self.disposed then
lease:Dispose()
return
end
self.lease = lease
self.service = nil
end
function ResourceLoadHandle.prototype.MarkSettledWithoutLeaseInternal(self)
self.service = nil
end
function ResourceLoadHandle.prototype.GetLease(self)
return self.lease
end
function ResourceLoadHandle.prototype.IsDisposed(self)
return self.disposed
end
function ResourceLoadHandle.prototype.Cancel(self)
self:Dispose()
end
function ResourceLoadHandle.prototype.Dispose(self)
if self.disposed then
return
end
self.disposed = true
if self.service ~= nil then
local svc = self.service
self.service = nil
svc:CancelPendingByIdInternal(self.requestId)
end
if self.lease ~= nil then
local l = self.lease
self.lease = nil
l:Dispose()
end
end
---
-- @module_data
local serviceByGameInstanceKey = {}
____exports.ResourceService = __TS__DefineClass("ResourceService", __module)
local ResourceService = ____exports.ResourceService
ResourceService.name = "ResourceService"
__TS__ClassExtends(ResourceService, ScopedObject)
function ResourceService.prototype.____constructor(self, ctx, backend)
ScopedObject.prototype.____constructor(self)
self.pendingById = {}
self.ctx = ctx
self.backend = backend
if ctx.gameInstance ~= nil then
self.giKey = GetGameInstanceKey(ctx.gameInstance)
serviceByGameInstanceKey[self.giKey] = self
end
ctx.appEvents.on.OnWorldCleanup(
function(oldWorldGen)
self:CancelForWorld(oldWorldGen)
end,
self
)
end
function ResourceService.prototype.ResolveAssetPath(self, keyOrPath)
return self.backend:ResolveAssetPath(keyOrPath)
end
function ResourceService.prototype.DoesAssetExist(self, keyOrPath)
return self.backend:DoesAssetExist(keyOrPath)
end
function ResourceService.prototype.IsPackagedMode(self)
return self.backend:IsPackagedMode()
end
function ResourceService.prototype.LoadObjectAsync(self, keyOrPath, owner, callback)
return self:StartAsyncLoad(keyOrPath, owner, callback, false)
end
function ResourceService.prototype.LoadTextureAsync(self, keyOrPath, owner, callback)
return self:LoadObjectAsync(keyOrPath, owner, callback)
end
function ResourceService.prototype.LoadClassAsync(self, keyOrPath, owner, callback)
return self:StartAsyncLoad(keyOrPath, owner, callback, true)
end
function ResourceService.prototype.StartAsyncLoad(self, keyOrPath, owner, callback, isClassLoad)
if self:IsDisposed() or self.ctx:IsShuttingDown() or owner ~= nil and owner:IsDisposed() then
local dead = __TS__New(____exports.ResourceLoadHandle, self, 0)
dead:Dispose()
return dead
end
local worldGen = self.ctx:GetWorldGen()
local requestId = isClassLoad and self.backend:RequestLoadClassAsync(keyOrPath, worldGen) or self.backend:RequestLoadObjectAsync(keyOrPath, worldGen)
local handle = __TS__New(____exports.ResourceLoadHandle, self, requestId)
local record = {
requestId = requestId,
keyOrPath = keyOrPath,
worldGen = worldGen,
owner = owner,
callback = callback,
handle = handle,
cancelled = false
}
self.pendingById[requestId] = record
if owner ~= nil and __TS__InstanceOf(owner, ScopedObject) then
owner:AddScopedObject(handle)
end
return handle
end
function ResourceService.prototype.CancelPendingByIdInternal(self, requestId)
local record = self.pendingById[requestId]
if record == nil then
return
end
record.cancelled = true
self.pendingById[requestId] = nil
self.backend:CancelRequest(requestId)
end
function ResourceService.prototype.CancelForWorld(self, worldGen)
local toCancel = {}
for id, rec in pairs(self.pendingById) do
if rec ~= nil and rec.worldGen == worldGen then
toCancel[#toCancel + 1] = id
end
end
do
local i = 0
while i < #toCancel do
local rec = self.pendingById[toCancel[i + 1]]
if rec ~= nil then
rec.cancelled = true
self.pendingById[toCancel[i + 1]] = nil
rec.handle:MarkSettledWithoutLeaseInternal()
end
i = i + 1
end
end
self.backend:CancelRequestsForWorld(worldGen)
return #toCancel
end
function ResourceService.prototype.HandleNativeLoadComplete(self, requestId, ok, loadedObj, resolvedPath, errorMessage)
local record = self.pendingById[requestId]
if record == nil then
if ok and resolvedPath ~= "" then
self.backend:ReleaseAsset(resolvedPath)
end
return
end
self.pendingById[requestId] = nil
local isStale = record.cancelled or self:IsDisposed() or self.ctx:IsShuttingDown() or record.worldGen ~= self.ctx:GetWorldGen() or record.owner ~= nil and record.owner:IsDisposed() or record.handle:IsDisposed()
if isStale then
record.handle:MarkSettledWithoutLeaseInternal()
if ok and resolvedPath ~= "" then
self.backend:ReleaseAsset(resolvedPath)
end
return
end
if ok and loadedObj ~= nil then
local lease = __TS__New(____exports.ResourceLease, resolvedPath, loadedObj, self.backend)
record.handle:AttachLeaseInternal(lease)
tbpcall(
record.callback,
true,
loadedObj,
lease,
nil
)
else
record.handle:MarkSettledWithoutLeaseInternal()
local err = errorMessage ~= "" and errorMessage or "Failed to load resource: " .. record.keyOrPath
logger:Warn("Resource load failed", {key = record.keyOrPath, path = resolvedPath, err = err})
tbpcall(
record.callback,
false,
nil,
nil,
err
)
end
end
function ResourceService.prototype.GetDiagnostics(self)
local pending = 0
for _, rec in pairs(self.pendingById) do
if rec ~= nil and not rec.cancelled then
pending = pending + 1
end
end
local nativeInFlight, nativeRetained, nativeRefs = self.backend:GetResourceStats()
return {tsPendingRequests = pending, nativeInFlight = nativeInFlight, nativeRetainedAssets = nativeRetained, nativeTotalRefCount = nativeRefs}
end
function ResourceService.prototype.Dispose(self)
if self:IsDisposed() then
return
end
local ids = {}
for id in pairs(self.pendingById) do
ids[#ids + 1] = id
end
do
local i = 0
while i < #ids do
self:CancelPendingByIdInternal(ids[i + 1])
i = i + 1
end
end
if self.giKey ~= nil and serviceByGameInstanceKey[self.giKey] == self then
serviceByGameInstanceKey[self.giKey] = nil
end
ScopedObject.prototype.Dispose(self)
end
--- 供 C++ FLuaCallbackBridge 回调的纯函数入口(路由到对应 GameInstance 的 ResourceService)。
--
-- @noSelf
function ____exports.OnNativeLoadComplete(gameInstance, requestId, ok, loadedObj, resolvedPath, errorMessage)
local svc = serviceByGameInstanceKey[GetGameInstanceKey(gameInstance)]
if svc ~= nil then
svc:HandleNativeLoadComplete(
requestId,
ok,
loadedObj,
resolvedPath,
errorMessage
)
end
end
--- 为指定 GameInstanceContext 装配生产环境 ResourceService。
--
-- @noSelf
function ____exports.CreateUEResourceService(ctx)
if ctx.gameInstance == nil then
return nil
end
local subsystem = UE.ULuaResourceSubsystem.GetFromGameInstance(ctx.gameInstance)
if subsystem == nil then
logger:Error("ULuaResourceSubsystem unavailable on GameInstance")
return nil
end
RegisterBaseAssetCatalog(subsystem)
return __TS__New(
____exports.ResourceService,
ctx,
__TS__New(____exports.UEResourceBackend, subsystem)
)
end
function __module.StashData(env, to)
local ____has = to.__has__
if not ____has then
____has = {}
to.__has__ = ____has
end
to.serviceByGameInstanceKey = serviceByGameInstanceKey
____has.serviceByGameInstanceKey = true
end
function __module.RestoreData(env, from)
local ____has = from.__has__
if not ____has then
return
end
if ____has.serviceByGameInstanceKey then
serviceByGameInstanceKey = from.serviceByGameInstanceKey
end
end
function __module.UpdateImports()
Logger = M__share_base_logger.Logger
ScopedObject = M__share_base_scoped_object.ScopedObject
tbpcall = M__share_base_traceback.tbpcall
GetGameInstanceKey = M__framework_context_game_context.GetGameInstanceKey
RegisterBaseAssetCatalog = M__framework_resource_asset_catalog.RegisterBaseAssetCatalog
end
+222
View File
@@ -0,0 +1,222 @@
local ____lualib = require("lualib_bundle")
local __TS__New = ____lualib.__TS__New
local ____exports = __module.env
local M__share_base_logger = __MODULE__.Import("share.base.logger", __module)
local Logger = M__share_base_logger.Logger
local Json = __MODULE__.Import("framework.core.json", __module)
local logger = Logger("LocalSave")
local SCOPE_PREFIX = {global = "gdata", role = "rdata", chat = "cdata", setting = "sdata"}
local SAVE_DEBOUNCE_SECONDS = 0.1
---
-- @noSelf
function ____exports.BuildSlotName(scope, identity)
local prefix = SCOPE_PREFIX[scope]
if identity == nil or identity == "" then
return prefix
end
return (prefix .. "_") .. identity
end
____exports.LocalSaveStore = __TS__DefineClass("LocalSaveStore", __module)
local LocalSaveStore = ____exports.LocalSaveStore
LocalSaveStore.name = "LocalSaveStore"
function LocalSaveStore.prototype.____constructor(self, slotName, backend, clock, schemaVersion, userIndex)
if schemaVersion == nil then
schemaVersion = 1
end
if userIndex == nil then
userIndex = 0
end
self.data = {}
self.loadedVersion = 0
self.lastLoadStatus = "not_found"
self.lastWriteStatus = "ok"
self.recoveredFromBackup = false
self.dirty = false
self.disposed = false
self.slotName = slotName
self.backend = backend
self.clock = clock
self.schemaVersion = schemaVersion
self.userIndex = userIndex
self:Reload()
end
function LocalSaveStore.prototype.Reload(self)
local readResult = self.backend:LoadSlotUtf8(self.slotName, self.userIndex)
self.lastLoadStatus = readResult.status
self.recoveredFromBackup = readResult.recoveredFromBackup
if readResult.status == "not_found" then
self.data = {}
self.loadedVersion = self.schemaVersion
return "not_found"
end
if readResult.status ~= "ok" then
logger:Warn("Failed to load save slot", {slot = self.slotName, status = readResult.status, err = readResult.errorMessage})
self.data = {}
self.loadedVersion = 0
return readResult.status
end
local decoded, decodeErr = Json.Decode(readResult.payloadUtf8)
if decodeErr ~= nil or type(decoded) ~= "table" then
logger:Error("Corrupted JSON payload in save slot", {slot = self.slotName, err = decodeErr or "non-table root"})
self.lastLoadStatus = "corrupted"
self.data = {}
self.loadedVersion = 0
return "corrupted"
end
local env = decoded
if type(env.version) ~= "number" or type(env.data) ~= "table" then
logger:Error("Invalid LocalSaveEnvelope schema in save slot", {slot = self.slotName})
self.lastLoadStatus = "corrupted"
self.data = {}
self.loadedVersion = 0
return "corrupted"
end
self.loadedVersion = env.version
self.data = env.data
return "ok"
end
function LocalSaveStore.prototype.GetLastLoadStatus(self)
return self.lastLoadStatus
end
function LocalSaveStore.prototype.GetLastWriteStatus(self)
return self.lastWriteStatus
end
function LocalSaveStore.prototype.WasRecoveredFromBackup(self)
return self.recoveredFromBackup
end
function LocalSaveStore.prototype.GetLoadedSchemaVersion(self)
return self.loadedVersion
end
function LocalSaveStore.prototype.IsDirty(self)
return self.dirty
end
function LocalSaveStore.prototype.Has(self, key)
return self.data[key] ~= nil
end
function LocalSaveStore.prototype.Get(self, key)
return self.data[key]
end
function LocalSaveStore.prototype.GetDefault(self, key, defaultValue)
local val = self.data[key]
if val ~= nil then
return val
end
return defaultValue
end
function LocalSaveStore.prototype.Set(self, key, value)
if self.disposed then
return
end
self.data[key] = value
self.dirty = true
self:ScheduleSave()
end
function LocalSaveStore.prototype.DeleteKey(self, key)
if self.disposed then
return
end
self.data[key] = nil
self.dirty = true
self:ScheduleSave()
end
function LocalSaveStore.prototype.DeleteAll(self)
if self.disposed then
return
end
self.data = {}
self.dirty = true
self:ScheduleSave()
end
function LocalSaveStore.prototype.ScheduleSave(self)
if self.delayTimer ~= nil and self.delayTimer:IsActive() then
return
end
self.delayTimer = self.clock:AddTimer(
SAVE_DEBOUNCE_SECONDS,
function()
self.delayTimer = nil
self:Flush()
end
)
end
function LocalSaveStore.prototype.Flush(self)
if self.delayTimer ~= nil then
self.delayTimer:Cancel()
self.delayTimer = nil
end
if not self.dirty then
return "ok"
end
local envelope = {version = self.schemaVersion, data = self.data}
local encoded, encodeErr = Json.Encode(envelope)
if encodeErr ~= nil or encoded == nil then
logger:Error("JSON encode failed for save slot", {slot = self.slotName, err = encodeErr})
self.lastWriteStatus = "write_failed"
return "write_failed"
end
local status = self.backend:SaveSlotUtf8(self.slotName, encoded, self.userIndex)
self.lastWriteStatus = status
if status == "ok" then
self.dirty = false
self.loadedVersion = self.schemaVersion
else
logger:Error("Failed to save slot", {slot = self.slotName, status = status})
end
return status
end
function LocalSaveStore.prototype.Dispose(self)
if self.disposed then
return
end
self:Flush()
self.disposed = true
end
____exports.LocalSaveManager = __TS__DefineClass("LocalSaveManager", __module)
local LocalSaveManager = ____exports.LocalSaveManager
LocalSaveManager.name = "LocalSaveManager"
function LocalSaveManager.prototype.____constructor(self, backend, clock)
self.storesBySlot = {}
self.disposed = false
self.backend = backend
self.clock = clock
end
function LocalSaveManager.prototype.GetOrOpenStore(self, scope, identity, schemaVersion)
if schemaVersion == nil then
schemaVersion = 1
end
local slotName = ____exports.BuildSlotName(scope, identity)
local store = self.storesBySlot[slotName]
if store == nil then
store = __TS__New(
____exports.LocalSaveStore,
slotName,
self.backend,
self.clock,
schemaVersion
)
self.storesBySlot[slotName] = store
end
return store
end
function LocalSaveManager.prototype.FlushAll(self)
for _, store in pairs(self.storesBySlot) do
if store ~= nil then
store:Flush()
end
end
end
function LocalSaveManager.prototype.Dispose(self)
if self.disposed then
return
end
self.disposed = true
for slot, store in pairs(self.storesBySlot) do
if store ~= nil then
self.storesBySlot[slot] = nil
store:Dispose()
end
end
end
function __module.UpdateImports()
Logger = M__share_base_logger.Logger
end
@@ -0,0 +1,152 @@
local ____exports = __module.env
---
-- @noSelf
local function MapNativeStatus(nativeStatus)
if nativeStatus == UE.ELuaStorageStatus.Ok then
return "ok"
end
if nativeStatus == UE.ELuaStorageStatus.NotFound then
return "not_found"
end
if nativeStatus == UE.ELuaStorageStatus.Corrupted then
return "corrupted"
end
if nativeStatus == UE.ELuaStorageStatus.WriteFailed then
return "write_failed"
end
return "invalid_argument"
end
____exports.UEStorageBackend = __TS__DefineClass("UEStorageBackend", __module)
local UEStorageBackend = ____exports.UEStorageBackend
UEStorageBackend.name = "UEStorageBackend"
function UEStorageBackend.prototype.____constructor(self)
end
function UEStorageBackend.prototype.LoadSlotUtf8(self, slotName, userIndex)
if userIndex == nil then
userIndex = 0
end
local res = UE.ULuaStorageLibrary.LoadSlotUtf8(slotName, userIndex)
return {
status = MapNativeStatus(res.Status),
payloadUtf8 = res.PayloadUtf8 or "",
containerVersion = res.ContainerVersion or 0,
recoveredFromBackup = res.bRecoveredFromBackup == true,
errorMessage = res.ErrorMessage or ""
}
end
function UEStorageBackend.prototype.SaveSlotUtf8(self, slotName, payloadUtf8, userIndex)
if userIndex == nil then
userIndex = 0
end
return MapNativeStatus(UE.ULuaStorageLibrary.SaveSlotUtf8(slotName, payloadUtf8, userIndex))
end
function UEStorageBackend.prototype.DeleteSlot(self, slotName, userIndex)
if userIndex == nil then
userIndex = 0
end
return UE.ULuaStorageLibrary.DeleteSlot(slotName, userIndex, true)
end
function UEStorageBackend.prototype.DoesSlotExist(self, slotName, userIndex)
if userIndex == nil then
userIndex = 0
end
return UE.ULuaStorageLibrary.DoesSlotExist(slotName, userIndex)
end
____exports.MemoryStorageBackend = __TS__DefineClass("MemoryStorageBackend", __module)
local MemoryStorageBackend = ____exports.MemoryStorageBackend
MemoryStorageBackend.name = "MemoryStorageBackend"
function MemoryStorageBackend.prototype.____constructor(self)
self.slots = {}
self.backups = {}
self.corruptCopies = {}
self.corruptedPrimaryFlags = {}
self.writeCount = 0
self.failNextWrite = false
end
function MemoryStorageBackend.prototype.InjectCorruptPrimary(self, slotName, rawGarbage)
self.slots[slotName] = rawGarbage
self.corruptedPrimaryFlags[slotName] = true
end
function MemoryStorageBackend.prototype.GetCorruptCopy(self, slotName)
return self.corruptCopies[slotName]
end
function MemoryStorageBackend.prototype.LoadSlotUtf8(self, slotName, _userIndex)
if _userIndex == nil then
_userIndex = 0
end
local primary = self.slots[slotName]
local backup = self.backups[slotName]
if primary == nil and backup == nil then
return {
status = "not_found",
payloadUtf8 = "",
containerVersion = 0,
recoveredFromBackup = false,
errorMessage = ""
}
end
if primary ~= nil and not self.corruptedPrimaryFlags[slotName] then
return {
status = "ok",
payloadUtf8 = primary,
containerVersion = 1,
recoveredFromBackup = false,
errorMessage = ""
}
end
if primary ~= nil and self.corruptedPrimaryFlags[slotName] then
self.corruptCopies[slotName] = primary
end
if backup ~= nil then
return {
status = "ok",
payloadUtf8 = backup,
containerVersion = 1,
recoveredFromBackup = true,
errorMessage = "Primary slot corrupted; recovered from backup"
}
end
return {
status = "corrupted",
payloadUtf8 = "",
containerVersion = 0,
recoveredFromBackup = false,
errorMessage = "Primary slot corrupted and no valid backup exists"
}
end
function MemoryStorageBackend.prototype.SaveSlotUtf8(self, slotName, payloadUtf8, _userIndex)
if _userIndex == nil then
_userIndex = 0
end
self.writeCount = self.writeCount + 1
if self.failNextWrite then
self.failNextWrite = false
return "write_failed"
end
local prev = self.slots[slotName]
if prev ~= nil and not self.corruptedPrimaryFlags[slotName] then
self.backups[slotName] = prev
end
self.slots[slotName] = payloadUtf8
self.corruptedPrimaryFlags[slotName] = nil
return "ok"
end
function MemoryStorageBackend.prototype.DeleteSlot(self, slotName, _userIndex)
if _userIndex == nil then
_userIndex = 0
end
local existed = self.slots[slotName] ~= nil or self.backups[slotName] ~= nil
self.slots[slotName] = nil
self.backups[slotName] = nil
self.corruptCopies[slotName] = nil
self.corruptedPrimaryFlags[slotName] = nil
return existed
end
function MemoryStorageBackend.prototype.DoesSlotExist(self, slotName, _userIndex)
if _userIndex == nil then
_userIndex = 0
end
return self.slots[slotName] ~= nil
end
function __module.UpdateImports()
end
+76
View File
@@ -0,0 +1,76 @@
local ____exports = __module.env
____exports.UI_LAYER_ZORDER = {
background = 0,
normal = 100,
popup = 200,
tips = 300,
system = 400
}
---
-- @module_data
local configByCtor = {}
---
-- @module_data
local configByName = {}
--- 显式 UI 窗口注册表(替代源端
--
-- @UIConfig 装饰器,符合 ts2lua-unreal 编译期白名单规则)。
function ____exports.RegisterUIConfig(ctor, input)
local ____input_name_2 = input.name
local ____input_assetKey_3 = input.assetKey
local ____input_singleton_0 = input.singleton
if ____input_singleton_0 == nil then
____input_singleton_0 = true
end
local ____temp_4 = input.layer or "normal"
local ____temp_5 = input.type or "normal"
local ____temp_6 = input.cacheTag or "no_cache"
local ____input_blockWorldClick_1 = input.blockWorldClick
if ____input_blockWorldClick_1 == nil then
____input_blockWorldClick_1 = true
end
local item = {
name = ____input_name_2,
assetKey = ____input_assetKey_3,
singleton = ____input_singleton_0,
layer = ____temp_4,
type = ____temp_5,
cacheTag = ____temp_6,
blockWorldClick = ____input_blockWorldClick_1,
ctor = ctor
}
configByCtor[ctor] = item
configByName[item.name] = item
return item
end
function ____exports.GetUIConfig(ctor)
return configByCtor[ctor]
end
function ____exports.GetUIConfigByName(name)
return configByName[name]
end
function __module.StashData(env, to)
local ____has = to.__has__
if not ____has then
____has = {}
to.__has__ = ____has
end
to.configByCtor = configByCtor
____has.configByCtor = true
to.configByName = configByName
____has.configByName = true
end
function __module.RestoreData(env, from)
local ____has = from.__has__
if not ____has then
return
end
if ____has.configByCtor then
configByCtor = from.configByCtor
end
if ____has.configByName then
configByName = from.configByName
end
end
function __module.UpdateImports()
end
@@ -0,0 +1,162 @@
local ____lualib = require("lualib_bundle")
local __TS__ClassExtends = ____lualib.__TS__ClassExtends
local __TS__New = ____lualib.__TS__New
local __TS__InstanceOf = ____lualib.__TS__InstanceOf
local ____exports = __module.env
local M__share_base_logger = __MODULE__.Import("share.base.logger", __module)
local Logger = M__share_base_logger.Logger
local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module)
local ScopedObject = M__share_base_scoped_object.ScopedObject
local M__share_base_traceback = __MODULE__.Import("share.base.traceback", __module)
local tbpcall = M__share_base_traceback.tbpcall
local M__framework_context_game_context = __MODULE__.Import("framework.context.game_context", __module)
local GetGameInstanceKey = M__framework_context_game_context.GetGameInstanceKey
local logger = Logger("UIDelegateBridge")
____exports.UEButtonDelegateBackend = __TS__DefineClass("UEButtonDelegateBackend", __module)
local UEButtonDelegateBackend = ____exports.UEButtonDelegateBackend
UEButtonDelegateBackend.name = "UEButtonDelegateBackend"
function UEButtonDelegateBackend.prototype.____constructor(self, subsystem)
self.subsystem = subsystem
end
function UEButtonDelegateBackend.prototype.BindButtonClicked(self, button)
return self.subsystem:BindButtonClicked(button)
end
function UEButtonDelegateBackend.prototype.UnbindButtonClicked(self, bindingId)
return self.subsystem:UnbindButtonClicked(bindingId)
end
function UEButtonDelegateBackend.prototype.GetActiveBindingCount(self)
return self.subsystem:GetActiveBindingCount()
end
local ButtonBindingHandle = __TS__DefineClass("ButtonBindingHandle", __module)
ButtonBindingHandle.name = "ButtonBindingHandle"
function ButtonBindingHandle.prototype.____constructor(self, bridge, bindingId)
self.bridge = bridge
self.bindingId = bindingId
end
function ButtonBindingHandle.prototype.Dispose(self)
if self.bridge ~= nil then
local b = self.bridge
self.bridge = nil
b:UnbindById(self.bindingId)
end
end
---
-- @module_data
local bridgeByGameInstanceKey = {}
____exports.UIDelegateBridge = __TS__DefineClass("UIDelegateBridge", __module)
local UIDelegateBridge = ____exports.UIDelegateBridge
UIDelegateBridge.name = "UIDelegateBridge"
__TS__ClassExtends(UIDelegateBridge, ScopedObject)
function UIDelegateBridge.prototype.____constructor(self, ctx, backend)
ScopedObject.prototype.____constructor(self)
self.bindings = {}
self.backend = backend
if ctx.gameInstance ~= nil then
self.giKey = GetGameInstanceKey(ctx.gameInstance)
bridgeByGameInstanceKey[self.giKey] = self
end
end
function UIDelegateBridge.prototype.BindButtonClick(self, button, callback, owner)
local bindingId = self.backend:BindButtonClicked(button)
assert(bindingId > 0, "UIDelegateBridge.BindButtonClick: failed to bind button")
self.bindings[bindingId] = {bindingId = bindingId, callback = callback, owner = owner}
local handle = __TS__New(ButtonBindingHandle, self, bindingId)
if owner ~= nil and __TS__InstanceOf(owner, ScopedObject) then
owner:AddScopedObject(handle)
end
return handle
end
function UIDelegateBridge.prototype.UnbindById(self, bindingId)
if self.bindings[bindingId] == nil then
return
end
self.bindings[bindingId] = nil
self.backend:UnbindButtonClicked(bindingId)
end
function UIDelegateBridge.prototype.DispatchButtonClicked(self, bindingId)
if self:IsDisposed() then
return
end
local rec = self.bindings[bindingId]
if rec == nil then
return
end
if rec.owner ~= nil and rec.owner:IsDisposed() then
self:UnbindById(bindingId)
return
end
tbpcall(rec.callback)
end
function UIDelegateBridge.prototype.GetActiveBindingCount(self)
return self.backend:GetActiveBindingCount()
end
function UIDelegateBridge.prototype.Dispose(self)
if self:IsDisposed() then
return
end
local ids = {}
for id in pairs(self.bindings) do
ids[#ids + 1] = id
end
do
local i = 0
while i < #ids do
self:UnbindById(ids[i + 1])
i = i + 1
end
end
if self.giKey ~= nil and bridgeByGameInstanceKey[self.giKey] == self then
bridgeByGameInstanceKey[self.giKey] = nil
end
ScopedObject.prototype.Dispose(self)
end
--- 供 C++ FLuaCallbackBridge::CallInt 回调的纯函数入口。
--
-- @noSelf
function ____exports.OnNativeButtonClicked(gameInstance, bindingId)
local bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)]
if bridge ~= nil then
bridge:DispatchButtonClicked(bindingId)
end
end
---
-- @noSelf
function ____exports.CreateUEUIDelegateBridge(ctx)
if ctx.gameInstance == nil then
return nil
end
local subsystem = UE.ULuaUIEventSubsystem.GetFromGameInstance(ctx.gameInstance)
if subsystem == nil then
logger:Error("ULuaUIEventSubsystem unavailable on GameInstance")
return nil
end
return __TS__New(
____exports.UIDelegateBridge,
ctx,
__TS__New(____exports.UEButtonDelegateBackend, subsystem)
)
end
function __module.StashData(env, to)
local ____has = to.__has__
if not ____has then
____has = {}
to.__has__ = ____has
end
to.bridgeByGameInstanceKey = bridgeByGameInstanceKey
____has.bridgeByGameInstanceKey = true
end
function __module.RestoreData(env, from)
local ____has = from.__has__
if not ____has then
return
end
if ____has.bridgeByGameInstanceKey then
bridgeByGameInstanceKey = from.bridgeByGameInstanceKey
end
end
function __module.UpdateImports()
Logger = M__share_base_logger.Logger
ScopedObject = M__share_base_scoped_object.ScopedObject
tbpcall = M__share_base_traceback.tbpcall
GetGameInstanceKey = M__framework_context_game_context.GetGameInstanceKey
end
+357
View File
@@ -0,0 +1,357 @@
local ____lualib = require("lualib_bundle")
local __TS__ClassExtends = ____lualib.__TS__ClassExtends
local __TS__New = ____lualib.__TS__New
local ____exports = __module.env
local M__share_base_logger = __MODULE__.Import("share.base.logger", __module)
local Logger = M__share_base_logger.Logger
local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module)
local ScopedObject = M__share_base_scoped_object.ScopedObject
local M__share_event_event_hub = __MODULE__.Import("share.event.event_hub", __module)
local EventHub = M__share_event_event_hub.EventHub
local M__share_base_traceback = __MODULE__.Import("share.base.traceback", __module)
local tbpcall = M__share_base_traceback.tbpcall
local M__framework_ui_ui_config = __MODULE__.Import("framework.ui.ui_config", __module)
local GetUIConfig = M__framework_ui_ui_config.GetUIConfig
local UI_LAYER_ZORDER = M__framework_ui_ui_config.UI_LAYER_ZORDER
local logger = Logger("UIManager")
____exports.UEWidgetAdapter = __TS__DefineClass("UEWidgetAdapter", __module)
local UEWidgetAdapter = ____exports.UEWidgetAdapter
UEWidgetAdapter.name = "UEWidgetAdapter"
function UEWidgetAdapter.prototype.____constructor(self)
end
function UEWidgetAdapter.prototype.FindChild(self, widget, name)
return UE.ULuaUIEventSubsystem.FindChildWidgetByName(widget, name)
end
function UEWidgetAdapter.prototype.AddToViewport(self, widget, zOrder)
if widget.IsInViewport ~= nil and widget:IsInViewport() then
return
end
local hasPlayer = widget.GetOwningPlayer ~= nil and widget:GetOwningPlayer() ~= nil
if hasPlayer and widget.AddToPlayerScreen ~= nil then
widget:AddToPlayerScreen(zOrder)
elseif widget.AddToViewport ~= nil then
widget:AddToViewport(zOrder)
end
end
function UEWidgetAdapter.prototype.RemoveFromParent(self, widget)
if widget.RemoveFromParent ~= nil then
widget:RemoveFromParent()
end
end
function UEWidgetAdapter.prototype.SetVisible(self, widget, visible)
if widget.SetVisibility ~= nil then
widget:SetVisibility(visible and UE.ESlateVisibility.Visible or UE.ESlateVisibility.Collapsed)
end
end
function UEWidgetAdapter.prototype.IsWidgetValid(self, widget)
return widget ~= nil and UE.UKismetSystemLibrary.IsValid(widget)
end
____exports.UEWidgetFactory = __TS__DefineClass("UEWidgetFactory", __module)
local UEWidgetFactory = ____exports.UEWidgetFactory
UEWidgetFactory.name = "UEWidgetFactory"
function UEWidgetFactory.prototype.____constructor(self)
end
function UEWidgetFactory.prototype.CreateWidget(self, widgetClass, worldContext, owningPlayer)
if worldContext == nil then
return nil
end
return UE.UWidgetBlueprintLibrary.Create(worldContext, widgetClass, owningPlayer)
end
____exports.UIManager = __TS__DefineClass("UIManager", __module)
local UIManager = ____exports.UIManager
UIManager.name = "UIManager"
__TS__ClassExtends(UIManager, ScopedObject)
function UIManager.prototype.____constructor(self, ctx, playerCtx, resourceService, widgetFactory, widgetAdapter)
ScopedObject.prototype.____constructor(self)
self.windowStack = {}
self.singletonByName = {}
self.cachedByName = {}
self.zOrderCounter = 0
self.inputMode = "game"
self.ctx = ctx
self.playerCtx = playerCtx
self.resourceService = resourceService
self.widgetFactory = widgetFactory or __TS__New(____exports.UEWidgetFactory)
self.widgetAdapter = widgetAdapter or __TS__New(____exports.UEWidgetAdapter)
self.events = __TS__New(
EventHub,
string.format("UIManager#%d_P%d", ctx.contextId, playerCtx.playerIndex)
)
ctx.appEvents.on.OnWorldCleanup(
function()
self:CloseAll(true)
end,
self
)
end
function UIManager.prototype.ShowUI(self, ctor, args, onOpened)
if self:IsDisposed() or self.ctx:IsShuttingDown() then
if onOpened ~= nil then
tbpcall(onOpened, false, nil, "UIManager is shutting down")
end
return nil
end
local config = GetUIConfig(ctor)
if config == nil then
error("UIManager.ShowUI: window class is not registered via RegisterUIConfig")
return nil
end
if config.singleton then
local existing = self.singletonByName[config.name]
if existing ~= nil and not existing:IsDisposed() and not existing:IsClosing() then
if existing:IsLoaded() then
local zOrder = self:AllocateZOrder(config)
existing:ShowInternal(zOrder, args)
self:SyncFocusAndInputMode()
if onOpened ~= nil then
tbpcall(onOpened, true, existing, nil)
end
elseif onOpened ~= nil then
self.events.on.OnWindowOpened(
function(openedName, openedWin)
if openedName == config.name and openedWin == existing then
tbpcall(onOpened, true, openedWin, nil)
end
end,
existing
)
end
return existing
end
end
local cached = self.cachedByName[config.name]
if cached ~= nil and not cached:IsDisposed() then
self.cachedByName[config.name] = nil
if config.singleton then
self.singletonByName[config.name] = cached
end
self.windowStack[#self.windowStack + 1] = cached
local zOrder = self:AllocateZOrder(config)
cached:ReuseInternal(zOrder, args)
self:SyncFocusAndInputMode()
self.events.emit.OnWindowOpened(config.name, cached)
if onOpened ~= nil then
tbpcall(onOpened, true, cached, nil)
end
return cached
end
local win = __TS__New(ctor)
win:InitContextInternal(self.ctx, self, config, self.widgetAdapter)
if config.singleton then
self.singletonByName[config.name] = win
end
self.windowStack[#self.windowStack + 1] = win
local loadHandle = self.resourceService:LoadClassAsync(
config.assetKey,
win,
function(ok, widgetClass, _lease, errMsg)
if win:IsDisposed() or win:IsClosing() or self:IsDisposed() then
return
end
if not ok or widgetClass == nil then
logger:Error("Failed to load widget class", {window = config.name, assetKey = config.assetKey, err = errMsg})
self:RemoveFromStackAndSingleton(win)
win:SetLoadingStateInternal(false, nil)
win:Dispose()
if onOpened ~= nil then
tbpcall(onOpened, false, nil, errMsg or "Widget class load failed")
end
return
end
local worldContext = self.ctx:GetWorldContext().world or self.playerCtx.playerController or self.ctx.gameInstance
local widget = self.widgetFactory:CreateWidget(widgetClass, worldContext, self.playerCtx.playerController)
if widget == nil then
local createErr = string.format("[%s] Failed to instantiate UUserWidget", config.name)
logger:Error(createErr)
self:RemoveFromStackAndSingleton(win)
win:SetLoadingStateInternal(false, nil)
win:Dispose()
if onOpened ~= nil then
tbpcall(onOpened, false, nil, createErr)
end
return
end
win:AttachWidgetInternal(widget)
local zOrder = self:AllocateZOrder(config)
win:ShowInternal(zOrder, args)
self:SyncFocusAndInputMode()
self.events.emit.OnWindowOpened(config.name, win)
if onOpened ~= nil then
tbpcall(onOpened, true, win, nil)
end
end
)
win:SetLoadingStateInternal(true, loadHandle)
return win
end
function UIManager.prototype.GetSingletonUI(self, ctor)
local config = GetUIConfig(ctor)
if config == nil then
return nil
end
return self.singletonByName[config.name]
end
function UIManager.prototype.CloseSingletonUI(self, ctor)
local win = self:GetSingletonUI(ctor)
if win ~= nil then
win:Close()
end
end
function UIManager.prototype.GetTopWindow(self)
do
local i = #self.windowStack - 1
while i >= 0 do
local win = self.windowStack[i + 1]
if not win:IsDisposed() and not win:IsClosing() then
return win
end
i = i - 1
end
end
return nil
end
function UIManager.prototype.HandleWindowCachedInternal(self, win)
self:RemoveFromStackAndSingleton(win)
local oldCached = self.cachedByName[win.config.name]
if oldCached ~= nil and oldCached ~= win then
oldCached:ForceDisposeFromCacheInternal()
end
self.cachedByName[win.config.name] = win
self:SyncFocusAndInputMode()
self.events.emit.OnWindowClosed(win.config.name, win)
end
function UIManager.prototype.HandleWindowClosedInternal(self, win)
self:RemoveFromStackAndSingleton(win)
self:SyncFocusAndInputMode()
self.events.emit.OnWindowClosed(win.config.name, win)
end
function UIManager.prototype.EvictCache(self)
local toEvict = {}
for name, win in pairs(self.cachedByName) do
if win ~= nil then
self.cachedByName[name] = nil
toEvict[#toEvict + 1] = win
end
end
do
local i = 0
while i < #toEvict do
toEvict[i + 1]:ForceDisposeFromCacheInternal()
i = i + 1
end
end
end
function UIManager.prototype.CloseAll(self, alsoEvictCache)
if alsoEvictCache == nil then
alsoEvictCache = true
end
local copy = {}
do
local i = #self.windowStack - 1
while i >= 0 do
copy[#copy + 1] = self.windowStack[i + 1]
i = i - 1
end
end
do
local i = 0
while i < #copy do
copy[i + 1]:Close()
i = i + 1
end
end
if alsoEvictCache then
self:EvictCache()
end
self:SyncFocusAndInputMode()
end
function UIManager.prototype.GetDiagnostics(self)
local openWindows = 0
local loadingWindows = 0
do
local i = 0
while i < #self.windowStack do
local w = self.windowStack[i + 1]
if not w:IsDisposed() then
if w:IsLoading() then
loadingWindows = loadingWindows + 1
else
openWindows = openWindows + 1
end
end
i = i + 1
end
end
local cachedWindows = 0
for _, w in pairs(self.cachedByName) do
if w ~= nil and not w:IsDisposed() then
cachedWindows = cachedWindows + 1
end
end
local top = self:GetTopWindow()
return {
openWindows = openWindows,
loadingWindows = loadingWindows,
cachedWindows = cachedWindows,
topWindowName = top ~= nil and top.config.name or nil,
inputMode = self.inputMode
}
end
function UIManager.prototype.AllocateZOrder(self, config)
self.zOrderCounter = self.zOrderCounter + 1
return UI_LAYER_ZORDER[config.layer] + self.zOrderCounter % 90
end
function UIManager.prototype.RemoveFromStackAndSingleton(self, win)
if self.singletonByName[win.config.name] == win then
self.singletonByName[win.config.name] = nil
end
do
local i = #self.windowStack - 1
while i >= 0 do
if self.windowStack[i + 1] == win then
table.remove(self.windowStack, i + 1)
break
end
i = i - 1
end
end
end
function UIManager.prototype.SyncFocusAndInputMode(self)
local top = self:GetTopWindow()
local nextMode = top ~= nil and top.config.blockWorldClick and "ui" or "game"
self.inputMode = nextMode
local pc = self.playerCtx.playerController
if pc ~= nil and UE ~= nil and UE.UKismetSystemLibrary.IsValid(pc) then
if nextMode == "ui" then
pc.bShowMouseCursor = true
local ____UE_UWidgetBlueprintLibrary_SetInputMode_UIOnlyEx_1 = UE.UWidgetBlueprintLibrary.SetInputMode_UIOnlyEx
local ____temp_0
if top ~= nil then
____temp_0 = top:GetWidget()
else
____temp_0 = nil
end
____UE_UWidgetBlueprintLibrary_SetInputMode_UIOnlyEx_1(pc, ____temp_0, UE.EMouseLockMode.DoNotLock, false)
else
pc.bShowMouseCursor = false
UE.UWidgetBlueprintLibrary.SetInputMode_GameOnly(pc, false)
end
end
self.events.emit.OnFocusRestored(top ~= nil and top.config.name or nil)
end
function UIManager.prototype.Dispose(self)
if self:IsDisposed() then
return
end
self:CloseAll(true)
self.events:Dispose()
ScopedObject.prototype.Dispose(self)
end
function __module.UpdateImports()
Logger = M__share_base_logger.Logger
ScopedObject = M__share_base_scoped_object.ScopedObject
EventHub = M__share_event_event_hub.EventHub
tbpcall = M__share_base_traceback.tbpcall
GetUIConfig = M__framework_ui_ui_config.GetUIConfig
UI_LAYER_ZORDER = M__framework_ui_ui_config.UI_LAYER_ZORDER
end
+202
View File
@@ -0,0 +1,202 @@
local ____lualib = require("lualib_bundle")
local __TS__ClassExtends = ____lualib.__TS__ClassExtends
local ____exports = __module.env
local M__share_base_logger = __MODULE__.Import("share.base.logger", __module)
local Logger = M__share_base_logger.Logger
local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module)
local ScopedObject = M__share_base_scoped_object.ScopedObject
local M__share_base_traceback = __MODULE__.Import("share.base.traceback", __module)
local tbpcall = M__share_base_traceback.tbpcall
local logger = Logger("UIWindow")
____exports.UIWindow = __TS__DefineClass("UIWindow", __module)
local UIWindow = ____exports.UIWindow
UIWindow.name = "UIWindow"
__TS__ClassExtends(UIWindow, ScopedObject)
function UIWindow.prototype.____constructor(self, ...)
ScopedObject.prototype.____constructor(self, ...)
self.widget = nil
self.isLoading = false
self.isLoaded = false
self.isVisible = false
self.isClosing = false
self.isCached = false
self.buttonBindings = {}
end
function UIWindow.prototype.InitContextInternal(self, ctx, uiManager, config, widgetAdapter)
self.ctx = ctx
self.uiManager = uiManager
self.config = config
self.widgetAdapter = widgetAdapter
end
function UIWindow.prototype.GetWidget(self)
return self.widget
end
function UIWindow.prototype.IsLoading(self)
return self.isLoading
end
function UIWindow.prototype.IsLoaded(self)
return self.isLoaded
end
function UIWindow.prototype.IsVisible(self)
return self.isVisible
end
function UIWindow.prototype.IsClosing(self)
return self.isClosing
end
function UIWindow.prototype.IsCached(self)
return self.isCached
end
function UIWindow.prototype.SetLoadingStateInternal(self, loading, handle)
self.isLoading = loading
self.classLoadHandle = handle
end
function UIWindow.prototype.AttachWidgetInternal(self, widget)
self.widget = widget
self.isLoading = false
self.isLoaded = true
self.isCached = false
self:OnBindWidgets()
end
function UIWindow.prototype.RequireWidget(self, widgetName)
assert(
self.widget ~= nil,
string.format("[%s] Widget root is not attached", self.config.name)
)
local child = self.widgetAdapter:FindChild(self.widget, widgetName)
assert(
child ~= nil,
string.format("[%s] Required child widget '%s' not found in Widget Blueprint", self.config.name, widgetName)
)
return child
end
function UIWindow.prototype.BindButtonClick(self, button, callback)
local bridge = self.ctx:GetService("uiDelegateBridge")
if bridge == nil then
logger:Warn("UIDelegateBridge not registered on context", {window = self.config.name})
return nil
end
local handle = bridge:BindButtonClick(button, callback, self)
self.buttonBindings[#self.buttonBindings + 1] = handle
return handle
end
function UIWindow.prototype.UnbindAllButtons(self)
do
local i = 0
while i < #self.buttonBindings do
self.buttonBindings[i + 1]:Dispose()
i = i + 1
end
end
self.buttonBindings = {}
end
function UIWindow.prototype.ShowInternal(self, zOrder, args)
if self:IsDisposed() or self.isClosing then
return
end
tbpcall(function()
self:OnPreShow(args)
end)
if self.widget ~= nil then
self.widgetAdapter:AddToViewport(self.widget, zOrder)
self.widgetAdapter:SetVisible(self.widget, true)
end
self.isVisible = true
tbpcall(function()
self:OnShow()
end)
end
function UIWindow.prototype.ReuseInternal(self, zOrder, args)
if self:IsDisposed() then
return
end
self.isCached = false
self.isClosing = false
self:EnableAllEventListeners()
self:OnBindWidgets()
tbpcall(function()
self:OnReuseUI(args)
end)
self:ShowInternal(zOrder, args)
end
function UIWindow.prototype.Hide(self)
if not self.isVisible then
return
end
self.isVisible = false
if self.widget ~= nil and self.widgetAdapter:IsWidgetValid(self.widget) then
self.widgetAdapter:SetVisible(self.widget, false)
end
tbpcall(function()
self:OnHide()
end)
end
function UIWindow.prototype.Close(self, onClosed)
if self:IsDisposed() or self.isCached or self.isClosing then
return
end
self.isClosing = true
if self.isLoading and self.classLoadHandle ~= nil then
self.classLoadHandle:Cancel()
self.classLoadHandle = nil
self.isLoading = false
end
local canCache = self.config.cacheTag == "cache" and self.isLoaded and self.widget ~= nil and self.widgetAdapter:IsWidgetValid(self.widget) and not self.ctx:IsShuttingDown()
if canCache then
self.isVisible = false
self.isCached = true
self.isClosing = false
self:UnbindAllButtons()
self:DisableAllEventListeners()
self.widgetAdapter:RemoveFromParent(self.widget)
tbpcall(function()
self:OnClose()
end)
self.uiManager:HandleWindowCachedInternal(self)
if onClosed ~= nil then
tbpcall(onClosed)
end
return
end
if self.isLoaded then
tbpcall(function()
self:OnClose()
end)
end
self.isVisible = false
self:UnbindAllButtons()
if self.widget ~= nil and self.widgetAdapter:IsWidgetValid(self.widget) then
self.widgetAdapter:RemoveFromParent(self.widget)
end
self.widget = nil
self.uiManager:HandleWindowClosedInternal(self)
self:Dispose()
if onClosed ~= nil then
tbpcall(onClosed)
end
end
function UIWindow.prototype.ForceDisposeFromCacheInternal(self)
self.isCached = false
self:UnbindAllButtons()
if self.widget ~= nil and self.widgetAdapter:IsWidgetValid(self.widget) then
self.widgetAdapter:RemoveFromParent(self.widget)
end
self.widget = nil
self:Dispose()
end
function UIWindow.prototype.OnBindWidgets(self)
end
function UIWindow.prototype.OnPreShow(self, _args)
end
function UIWindow.prototype.OnShow(self)
end
function UIWindow.prototype.OnReuseUI(self, _args)
end
function UIWindow.prototype.OnHide(self)
end
function UIWindow.prototype.OnClose(self)
end
function __module.UpdateImports()
Logger = M__share_base_logger.Logger
ScopedObject = M__share_base_scoped_object.ScopedObject
tbpcall = M__share_base_traceback.tbpcall
end