This commit is contained in:
Akbar Yahya
2022-11-21 16:30:31 +08:00
commit e0d4d8040c
3326 changed files with 683000 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
----------------------
-- 这是Lua端BenchMark包含了一些profiler和memory的操作
-- @module BenchMark
local BenchMark = {
memory = require('Base/memory'),
profiler = require('Base/profiler')
}
--- Profiler方法
-- @section profiler
function BenchMark:StartProfiler()
self.profiler.start()
end
function BenchMark:StopProfiler()
self.profiler.stop()
end
function BenchMark:Report()
print(self.profiler.report())
end
--- Memory方法
-- @section memory
function BenchMark:PrintTotalMemory()
return self.memory.total()
end
function BenchMark:PrintMemorySnapshot()
print(self.memory.snapshot())
end
return BenchMark

View File

@@ -0,0 +1,45 @@
function clone(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for k, v in pairs(object) do
new_table[_copy(k)] = _copy(v)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end
function class(className, super)
local superType = type(super)
if superType ~= "table" or super.new == nil then
super = nil
end
local cls = {}
if super then
--cls = clone(super)
cls = super:new()
setmetatable(cls, super)
end
cls.__className = className
cls.__super = super
function cls:new(...)
local o = {}
cls.__index = cls
setmetatable(o, cls)
return o
end
return cls
end

View File

@@ -0,0 +1,41 @@
inspect = require('Base/Inspect')
util = require('Base/util')
M = require('Base/uMath')
local common = {}
common.lua_manager = singletonManager:GetSingletonInstance("MoleMole.LuaManager")
local function async_immediate_return(obj, cb)
common.lua_manager:ImmediateCallback(obj, cb)
end
common.do_immediate = util.async_to_sync(async_immediate_return)
local function async_yield_return(to_yield, cb)
common.lua_manager:YieldCallback(to_yield, cb)
end
common.do_yield = util.async_to_sync(async_yield_return)
local function async_call(to_yield, cb)
local co = common.lua_manager:CoroutineCall(to_yield, cb)
return co
end
common.coroutine_call = async_call;
local function async_stop(coroutine)
common.lua_manager:CoroutineStop(coroutine)
end
common.coroutine_stop = async_stop;
local function async_do_ldevent(ldevent, cb)
common.lua_manager:StartLDEvent(ldevent, cb)
end
common.do_ldevent = util.async_to_sync(async_do_ldevent)
common.do_listen_ldEvent = function(ldevent, cb)
common.lua_manager:StartLDEvent(ldevent, util.coroutine_call(cb))
end
--xlua.private_accessible(CS.MoleMole.EntityManager)
--print("common in common2 "..inspect(common).." "..common.entity_manager._entityMap:ToString().." "..tostring(common.entity_manager:GetEntity(0)))
return common

View File

@@ -0,0 +1,23 @@
--reload
dispatch_funcs = {}
function dispatch_funcs.on_level_destroy( ... )
for k,v in ipairs({...}) do
print(k,v)
end
print("on_level_destroy in lua")
level.destroy()
end
dispatch_funcs.dispatch_func = function(function_name, ... )
local fun = dispatch_funcs[function_name]
if fun ~= nil then
return fun(...)
else
print("get func failed "..function_name)
end
return nil
end
return dispatch_funcs

View File

@@ -0,0 +1,347 @@
-- don't use inspect in RELEASE, it's actually pretty costly
if not _G.NG_HSOD_DEBUG then
local noinspect = function(...)
return ''
end
return noinspect
end
-- HACk to always use original pairs
local pairs
if _G._orig_pairs ~= nil then
pairs = _G._orig_pairs
else
pairs = _G.pairs
end
local inspect ={
_VERSION = 'inspect.lua 3.0.0',
_URL = 'http://github.com/kikito/inspect.lua',
_DESCRIPTION = 'human-readable representations of tables',
_LICENSE = [[
MIT LICENSE
Copyright (c) 2013 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
}
inspect.KEY = setmetatable({}, {__tostring = function() return 'inspect.KEY' end})
inspect.METATABLE = setmetatable({}, {__tostring = function() return 'inspect.METATABLE' end})
-- Apostrophizes the string if it has quotes, but not aphostrophes
-- Otherwise, it returns a regular quoted string
local function smartQuote(str)
if str:match('"') and not str:match("'") then
return "'" .. str .. "'"
end
return '"' .. str:gsub('"', '\\"') .. '"'
end
local controlCharsTranslation = {
["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n",
["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v"
}
local function escape(str)
local result = str:gsub("\\", "\\\\"):gsub("(%c)", controlCharsTranslation)
return result
end
local function isIdentifier(str)
return type(str) == 'string' and str:match( "^[_%a][_%a%d]*$" )
end
local function isSequenceKey(k, length)
return type(k) == 'number'
and 1 <= k
and k <= length
and math.floor(k) == k
end
local defaultTypeOrders = {
['number'] = 1, ['boolean'] = 2, ['string'] = 3, ['table'] = 4,
['function'] = 5, ['userdata'] = 6, ['thread'] = 7
}
local function sortKeys(a, b)
local ta, tb = type(a), type(b)
-- strings and numbers are sorted numerically/alphabetically
if ta == tb and (ta == 'string' or ta == 'number') then return a < b end
local dta, dtb = defaultTypeOrders[ta], defaultTypeOrders[tb]
-- Two default types are compared according to the defaultTypeOrders table
if dta and dtb then return defaultTypeOrders[ta] < defaultTypeOrders[tb]
elseif dta then return true -- default types before custom ones
elseif dtb then return false -- custom types after default ones
end
-- custom types are sorted out alphabetically
return ta < tb
end
local function getNonSequentialKeys(t)
local keys, length = {}, #t
for k,_ in pairs(t) do
if not isSequenceKey(k, length) then table.insert(keys, k) end
end
table.sort(keys, sortKeys)
return keys
end
local function getToStringResultSafely(t, mt)
local __tostring = type(mt) == 'table' and rawget(mt, '__tostring')
local str, ok
if type(__tostring) == 'function' then
ok, str = pcall(__tostring, t)
str = ok and str or 'error: ' .. tostring(str)
end
if type(str) == 'string' and #str > 0 then return str end
end
local maxIdsMetaTable = {
__index = function(self, typeName)
rawset(self, typeName, 0)
return 0
end
}
local idsMetaTable = {
__index = function (self, typeName)
local col = setmetatable({}, {__mode = "kv"})
rawset(self, typeName, col)
return col
end
}
local function countTableAppearances(t, tableAppearances)
tableAppearances = tableAppearances or setmetatable({}, {__mode = "k"})
if type(t) == 'table' then
if not tableAppearances[t] then
tableAppearances[t] = 1
for k,v in pairs(t) do
countTableAppearances(k, tableAppearances)
countTableAppearances(v, tableAppearances)
end
countTableAppearances(getmetatable(t), tableAppearances)
else
tableAppearances[t] = tableAppearances[t] + 1
end
end
return tableAppearances
end
local copySequence = function(s)
local copy, len = {}, #s
for i=1, len do copy[i] = s[i] end
return copy, len
end
local function makePath(path, ...)
local keys = {...}
local newPath, len = copySequence(path)
for i=1, #keys do
newPath[len + i] = keys[i]
end
return newPath
end
local function processRecursive(process, item, path)
if item == nil then return nil end
local processed = process(item, path)
if type(processed) == 'table' then
local processedCopy = {}
local processedKey
for k,v in pairs(processed) do
processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY))
if processedKey ~= nil then
processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey))
end
end
local mt = processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE))
setmetatable(processedCopy, mt)
processed = processedCopy
end
return processed
end
-------------------------------------------------------------------
local Inspector = {}
local Inspector_mt = {__index = Inspector}
function Inspector:puts(...)
local args = {...}
local buffer = self.buffer
local len = #buffer
for i=1, #args do
len = len + 1
buffer[len] = tostring(args[i])
end
end
function Inspector:down(f)
self.level = self.level + 1
f()
self.level = self.level - 1
end
function Inspector:tabify()
self:puts(self.newline, string.rep(self.indent, self.level))
end
function Inspector:alreadyVisited(v)
return self.ids[type(v)][v] ~= nil
end
function Inspector:getId(v)
local tv = type(v)
local id = self.ids[tv][v]
if not id then
id = self.maxIds[tv] + 1
self.maxIds[tv] = id
self.ids[tv][v] = id
end
return id
end
function Inspector:putKey(k)
if isIdentifier(k) then return self:puts(k) end
self:puts("[")
self:putValue(k)
self:puts("]")
end
function Inspector:putTable(t)
if t == inspect.KEY or t == inspect.METATABLE then
self:puts(tostring(t))
elseif self:alreadyVisited(t) then
self:puts('<table ', self:getId(t), '>')
elseif self.level >= self.depth then
self:puts('{...}')
else
if self.tableAppearances[t] > 1 then self:puts('<', self:getId(t), '>') end
local nonSequentialKeys = getNonSequentialKeys(t)
local length = #t
local mt = getmetatable(t)
local toStringResult = getToStringResultSafely(t, mt)
--change to tabify by xrq
self:tabify()
self:puts('{')
self:down(function()
if toStringResult then
self:puts(' -- ', escape(toStringResult))
if length >= 1 then self:tabify() end
end
local count = 0
for i=1, length do
if count > 0 then self:puts(',') end
-- self:puts(' ') --remove the space just after '{' by xrq
self:putValue(t[i])
count = count + 1
end
for _,k in ipairs(nonSequentialKeys) do
if count > 0 then self:puts(',') end
self:tabify()
self:putKey(k)
self:puts(' = ')
self:putValue(t[k])
count = count + 1
end
if mt then
if count > 0 then self:puts(',') end
self:tabify()
self:puts('<metatable> = ')
self:putValue(mt)
end
end)
if #nonSequentialKeys > 0 or mt then -- result is multi-lined. Justify closing }
self:tabify()
elseif length > 0 then -- array tables have one extra space before closing }
--self:puts(' ') -- remove the space before '}' by xrq
end
self:puts('}')
end
end
function Inspector:putValue(v)
local tv = type(v)
if tv == 'string' then
self:puts(smartQuote(escape(v)))
elseif tv == 'number' or tv == 'boolean' or tv == 'nil' then
self:puts(tostring(v))
elseif tv == 'table' then
self:putTable(v)
else
self:puts('<',tv,' ',self:getId(v),'>')
end
end
-------------------------------------------------------------------
function inspect.inspect(root, options)
options = options or {}
local depth = options.depth or math.huge
local newline = options.newline or '\n'
local indent = options.indent or ' '
local process = options.process
if process then
root = processRecursive(process, root, {})
end
local inspector = setmetatable({
depth = depth,
buffer = {},
level = 0,
ids = setmetatable({}, idsMetaTable),
maxIds = setmetatable({}, maxIdsMetaTable),
newline = newline,
indent = indent,
tableAppearances = countTableAppearances(root)
}, Inspector_mt)
inspector:putValue(root)
return table.concat(inspector.buffer)
end
setmetatable(inspect, { __call = function(_, ...) return inspect.inspect(...) end })
return inspect

View File

@@ -0,0 +1,272 @@
local SceneData = {}
SceneData.SceneDataDic = {}
SceneData.DefaultSceneID = 3
SceneData.currSceneID = -1
SceneData.ClearScene = function(self)
if SceneData.currSceneID <= 0 then
return
end
SceneData.SceneDataDic[SceneData.currSceneID] = nil
end
local function DoRequire(path)
util.do_require(path)
end
local function GetSceneDataSchemePath(sceneID)
local sceneIDStr = tostring(sceneID)
local path = "Scene/" .. sceneIDStr .. "/scene" .. sceneIDStr
return path
end
local function AddEntityInfoToDic(infos, dic)
if infos == nil then
return
end
for i = 1, #infos do
local info = infos[i]
dic[info.config_id] = info
end
end
local function ClearTempSceneData()
groups = nil
dummy_points = nil
routes_config = nil
routes = nil
monsters = nil
npcs = nil
gadgets = nil
regions = nil
triggers = nil
variables = nil
init_config = nil
end
local function CreateSceneData(schemePath)
DoRequire(schemePath)
local sceneData =
{
scene_config = nil,
blocks = nil,
groups = nil,
dummy_points = nil,
routes = nil,
ConfigType ={
Monster = 0,
Npc = 1,
Gadget = 2,
},
GetConfig = function(self, groupID, configID, type)
local groupInfo = self.groups[groupID]
if groupInfo == nil then
return nil
end
if type == self.ConfigType.Monster then
return groupInfo.monsterDic[configID]
elseif type == self.ConfigType.Npc then
return groupInfo.npcDic[configID]
elseif type == self.ConfigType.Gadget then
return groupInfo.gadgetDic[configID]
else
return nil
end
end,
GetMonsterConfig = function(self, groupID, configID)
return self:GetConfig(groupID, configID, self.ConfigType.Monster)
end,
GetNpcConfig = function(self, groupID, configID)
return self:GetConfig(groupID, configID, self.ConfigType.Npc)
end,
GetGadgetConfig = function(self, groupID, configID)
return self:GetConfig(groupID, configID, self.ConfigType.Gadget)
end,
GetInitGadgets = function(self)
local gadgetList = {}
local cnt = 1
for k, v in pairs(self.groups) do
local groupID = k
if v ~= nil and v.initConfig ~= nil then
for i = 1, #(v.initConfig.gadgets) do
local configID = v.initConfig.gadgets[i]
local config = self:GetGadgetConfig(groupID, configID)
gadgetList[cnt] = config
cnt = cnt + 1
end
end
end
return gadgetList
end,
GetInitNpcs = function(self)
local npcList = {}
local cnt = 1
for k, v in pairs(self.groups) do
local groupID = k
if v ~= nil and v.initConfig ~= nil then
for i = 1, #(v.initConfig.npcs) do
local configID = v.initConfig.npcs[i]
local config = self:GetNpcConfig(groupID, configID)
npcList[cnt] = config
cnt = cnt + 1
end
end
end
return npcList
end,
GetSuiteGadgets = function(self)
local gadgetList = {}
local cnt = 1
--每个group
for k, v in pairs(self.groups) do
local groupID = k
if v ~= nil and v.suites ~= nil then
--每个suite
for i = 1, #(v.suites) do
local suite = v.suites[i]
if(suite.gadgets~=nil) then
for key,value in pairs(suite.gadgets) do
local configID = value
local config = self:GetGadgetConfig(groupID, configID)
gadgetList[cnt] = config
cnt = cnt + 1
end
end
end
end
end
return gadgetList
end,
GetDummyPoint = function(self, dummyName)
if self.dummy_points == nil then
return nil
end
local dummyPoint = nil
if self.dummy_points[dummyName] ~= nil then
dummyPoint = self.dummy_points[dummyName]
end
return dummyPoint
end,
GetRouteConfig = function(self, routeName)
if self.routes == nil then
return nil
end
local routeConfig = nil
if self.routes[routeName] ~= nil then
routeConfig = self.routes[routeName]
end
return routeConfig
end
}
sceneData.scene_config = scene_config
local blocksDic = {}
local groupDic = {}
if blocks == nil then
blocks = {}
end
print(#blocks)
for i=1 , #blocks do
local blockData = { groups = nil }
local blockIndex = blocks[i]
local blockIndexStr = tostring(blockIndex)
local blockPath = schemePath .. "_block" .. blockIndexStr
DoRequire(blockPath)
if groups == nil then
groups = {}
end
blockData.groups = groups
blocksDic[blockIndex] = blockData
for j=1 , #groups do
local group = groups[j]
local groupIndexStr = tostring(group.id)
local groupPath = schemePath .. "_group" .. groupIndexStr
DoRequire(groupPath)
local groupInfo = { monsterDic = {}, npcDic = {}, gadgetDic = {}, regionDic = {}, triggerDic = {}, variables = {}, initConfig = {}, suites = {}}
AddEntityInfoToDic(monsters, groupInfo.monsterDic)
AddEntityInfoToDic(npcs, groupInfo.npcDic)
AddEntityInfoToDic(gadgets, groupInfo.gadgetDic)
AddEntityInfoToDic(regions, groupInfo.regionDic)
groupInfo.suites = suites
groupInfo.initConfig = init_config
groupDic[group.id] = groupInfo
end
end
sceneData.blocks = blocksDic
sceneData.groups = groupDic
if dummy_points ~= nil and #dummy_points > 0 then
local dummy_point_path = schemePath .. "_" .. dummy_points[1]
DoRequire(dummy_point_path)
sceneData.dummy_points = dummy_points
end
if routes_config ~= nil and #routes_config > 0 then
local routes_path = schemePath .. "_" .. routes_config[1]
DoRequire(routes_path)
sceneData.routes = routes
end
--clear temp data
ClearTempSceneData()
return sceneData
end
SceneData.LoadScene = function(self, sceneID, isOnlyLoad)
print("######sceneID")
print(sceneID)
local sceneData = SceneData.SceneDataDic[sceneID]
if sceneData ~= nil then
if not isOnlyLoad then
SceneData.currSceneID = sceneID
end
return sceneData
end
local schemePath = GetSceneDataSchemePath(sceneID)
sceneData = CreateSceneData(schemePath)
SceneData.SceneDataDic[sceneID] = sceneData
if not isOnlyLoad then
SceneData.currSceneID = sceneID
end
return sceneData
end
SceneData.GetSceneData = function(self, sceneID)
local sceneData = SceneData.SceneDataDic[sceneID]
if sceneData == nil then
sceneData = SceneData.LoadScene(self, sceneID, true)
end
return sceneData
end
SceneData.GetDummyPoint = function(self, sceneID, dummyName)
local sceneData = SceneData.GetSceneData(self, sceneID)
return sceneData:GetDummyPoint(dummyName)
end
SceneData.GetRouteConfig = function(self, sceneID, routeName)
local sceneData = SceneData.GetSceneData(self, sceneID)
return sceneData:GetRouteConfig(routeName)
end
return SceneData

View File

@@ -0,0 +1,20 @@
-- Tencent is pleased to support the open source community by making xLua available.
-- Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
-- Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
-- http://opensource.org/licenses/MIT
-- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
local function snapshot()
error('use memory leak checker instead!')
end
--returns the total memory in use by Lua (in Kbytes).
local function total()
error('use memory leak checker instead!')
end
return {
snapshot = snapshot,
total = total
}

View File

@@ -0,0 +1,125 @@
-- Tencent is pleased to support the open source community by making xLua available.
-- Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
-- Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
-- http://opensource.org/licenses/MIT
-- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
local get_time = os.clock
local sethook = xlua.sethook or debug.sethook
local func_info_map = nil
local start_time
local function create_func_info(db_info)
return {
db_info = db_info,
count = 0,
total_time = 0
}
end
local function on_hook(event, func_info_id, source)
local func_info = func_info_map[func_info_id]
if not func_info then
func_info = create_func_info(debug.getinfo( 2, 'nS' ))
func_info_map[func_info_id] = func_info
end
if event == "call" then
func_info.call_time = get_time()
func_info.count = func_info.count + 1
func_info.return_time = nil
elseif event == "return" or event == 'tail return' then
local now = get_time()
if func_info.call_time then
func_info.total_time = func_info.total_time + (now - func_info.call_time)
func_info.call_time = nil
else
func_info.total_time = func_info.total_time + (now - (func_info.return_time or now))
func_info.count = func_info.count + 1
end
func_info.return_time = now
if source and func_info.count == 1 then
func_info.db_info.short_src = source
end
end
end
local function start()
func_info_map = {}
start_time = get_time()
sethook(on_hook, 'cr')
end
local function pause()
sethook()
end
local function resume()
sethook(on_hook, 'cr')
end
local function stop()
sethook()
func_info_map = nil
start_time = nil
end
local function report_output_line(rp, stat_interval)
local source = rp.db_info.short_src or '[NA]'
local linedefined = (rp.db_info.linedefined and rp.db_info.linedefined >= 0) and string.format(":%i", rp.db_info.linedefined) or ''
source = source .. linedefined
local name = rp.db_info.name or '[anonymous]'
local total_time = string.format("%04.3f", rp.total_time * 1000)
local average_time = string.format("%04.3f", rp.total_time / rp.count * 1000)
local relative_time = string.format("%03.2f%%", (rp.total_time / stat_interval) * 100 )
local count = string.format("%7i", rp.count)
return string.format("|%-40.40s: %-50.50s: %-12s: %-12s: %-12s: %-12s|\n", name, source, total_time, average_time, relative_time, count)
end
local sort_funcs = {
TOTAL = function(a, b) return a.total_time > b.total_time end,
AVERAGE = function(a, b) return a.average > b.average end,
CALLED = function(a, b) return a.count > b.count end
}
local function report(sort_by)
sethook()
local sort_func = type(sort_by) == 'function' and sort_by or sort_funcs[sort_by]
local FORMAT_HEADER_LINE = "|%-40s: %-50s: %-12s: %-12s: %-12s: %-12s|\n"
local header = string.format( FORMAT_HEADER_LINE, "FUNCTION", "SOURCE", "TOTAL(MS)", "AVERAGE(MS)", "RELATIVE", "CALLED" )
local stat_interval = get_time() - (start_time or get_time())
local report_list = {}
for _, rp in pairs(func_info_map) do
table.insert(report_list, {
total_time = rp.total_time,
count = rp.count,
average = rp.total_time / rp.count,
output = report_output_line(rp, stat_interval)
})
end
table.sort(report_list, sort_func or sort_funcs.TOTAL)
local output = header
for i, rp in ipairs(report_list) do
output = output .. rp.output
end
sethook(on_hook, 'cr')
return output
end
return {
--开始统计
start = start,
--获取报告start和stop之间可以多次调用参数sort_by类型是string可以是'TOTAL','AVERAGE', 'CALLED'
report = report,
--停止统计
stop = stop
}

View File

@@ -0,0 +1,89 @@
----------------------
-- 这是Lua端数学包装
-- @module M
local M = M or {}
csMath = CS.MoleMole.LuaMath
--- PI
M.PI = 3.14159
--- 角度转弧度
-- @tparam float deg 角度
M.Deg2Rad = function(deg)
return (M.PI / 180) * deg
end
--- 弧度转角度
-- @tparam float rad 弧度
M.Rad2Deg = function(rad)
return (180 / M.PI) * rad
end
--- 生成一个位置
-- @tparam float x x坐标
-- @tparam float y y坐标
-- @tparam float z z坐标
M.Pos = function(x, y, z)
local pos = CS.UnityEngine.Vector3(x, y, z)
return pos
end
--- 生成一个朝向
-- @tparam float x x分量
-- @tparam float y y分量
-- @tparam float z z分量
M.Dir = function(x, y, z)
local dir = CS.UnityEngine.Vector3(x, y, z)
return dir
end
--- 生成一个欧拉转向
-- @tparam float x 绕x轴角度
-- @tparam float y 绕y轴角度
-- @tparam float z 绕z轴角度
M.Euler = function(x, y, z)
local euler = CS.UnityEngine.Vector3(x, y, z)
return euler
end
--- 欧拉转向转成朝向
-- @tparam Vector3 euler 欧拉转向
M.Euler2DirXZ = function(euler)
local heading = M.Deg2Rad(euler.y)
return M.Dir(math.sin(heading), 0, math.cos(heading))
end
--- 朝向转成欧拉转向
-- @tparam Vector3 dir 朝向
M.Dir2Euler = function(dir)
return csMath.Forward2Euler(dir)
end
--- XZ平面几乎一致
-- @tparam Vector3 posA 位置坐标A
-- @tparam Vector3 posB 位置坐标B
-- @tparam float maxDist 容忍距离
M.IsSameXZ = function(posA, posB, maxDist)
if posA.x - posB.x > -maxDist and posA.x - posB.x < maxDist
and posA.z - posB.z > -maxDist and posA.z - posB.z < maxDist then
return true
end
return false
end
--- 两点距离
-- @tparam Vector3 posA 位置坐标A
-- @tparam Vector3 posB 位置坐标B
M.Dist = function(posA, posB)
return CS.UnityEngine.Vector3.Distance(posA, posB)
end
--- 欧式距离几乎一致
M.IsSamePos = function(posA, posB, maxDist)
local dist = M.Dist(posA, posB)
if dist < maxDist then
return true
end
return false
end
--- 返回一个颜色
M.Color = function(r, g, b, a)
local color = CS.UnityEngine.Color(r, g, b, a)
return color
end
return M

View File

@@ -0,0 +1,226 @@
-- Tencent is pleased to support the open source community by making xLua available.
-- Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
-- Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
-- http://opensource.org/licenses/MIT
-- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
local unpack = unpack or table.unpack
local function async_to_sync(async_func, callback_pos)
return function(...)
local _co = coroutine.running() or error ('this function must be run in coroutine')
local rets
local waiting = false
local function cb_func(...)
if waiting then
assert(coroutine.resume(_co, ...))
else
rets = {...}
end
end
local params = {...}
table.insert(params, callback_pos or (#params + 1), cb_func)
async_func(unpack(params))
if rets == nil then
waiting = true
rets = {coroutine.yield()}
end
return unpack(rets)
end
end
local function coroutine_call(func)
return function(...)
local co = coroutine.create(func)
assert(coroutine.resume(co, ...))
end
end
local move_end = {}
local generator_mt = {
__index = {
MoveNext = function(self)
self.Current = self.co()
if self.Current == move_end then
self.Current = nil
return false
else
return true
end
end;
Reset = function(self)
self.co = coroutine.wrap(self.w_func)
end
}
}
local function cs_generator(func, ...)
local params = {...}
local generator = setmetatable({
w_func = function()
func(unpack(params))
return move_end
end
}, generator_mt)
generator:Reset()
return generator
end
local function loadpackage(...)
for _, loader in ipairs(package.searchers) do
local func = loader(...)
if type(func) == 'function' then
return func
end
end
end
local function auto_id_map()
local hotfix_id_map = require 'hotfix_id_map'
local org_hotfix = xlua.hotfix
xlua.hotfix = function(cs, field, func)
local map_info_of_type = hotfix_id_map[typeof(cs):ToString()]
if map_info_of_type then
if func == nil then func = false end
local tbl = (type(field) == 'table') and field or {[field] = func}
for k, v in pairs(tbl) do
local map_info_of_methods = map_info_of_type[k]
local f = type(v) == 'function' and v or nil
for _, id in ipairs(map_info_of_methods or {}) do
CS.XLua.HotfixDelegateBridge.Set(id, f)
end
--CS.XLua.HotfixDelegateBridge.Set(
end
xlua.private_accessible(cs)
else
return org_hotfix(cs, field, func)
end
end
end
--和xlua.hotfix的区别是这个可以调用原来的函数
local function hotfix_ex(cs, field, func)
assert(type(field) == 'string' and type(func) == 'function', 'invalid argument: #2 string needed, #3 function needed!')
local function func_after(...)
xlua.hotfix(cs, field, nil)
local ret = {func(...)}
xlua.hotfix(cs, field, func_after)
return unpack(ret)
end
xlua.hotfix(cs, field, func_after)
end
local function bind(func, obj)
return function(...)
return func(obj, ...)
end
end
--为了兼容luajitlua53版本直接用|操作符即可
local enum_or_op = debug.getmetatable(CS.System.Reflection.BindingFlags.Public).__bor
local enum_or_op_ex = function(first, ...)
for _, e in ipairs({...}) do
first = enum_or_op(first, e)
end
return first
end
-- description: 直接用C#函数创建delegate
local function createdelegate(delegate_cls, obj, impl_cls, method_name, parameter_type_list)
local flag = enum_or_op_ex(CS.System.Reflection.BindingFlags.Public, CS.System.Reflection.BindingFlags.NonPublic,
CS.System.Reflection.BindingFlags.Instance, CS.System.Reflection.BindingFlags.Static)
local m = parameter_type_list and typeof(impl_cls):GetMethod(method_name, flag, nil, parameter_type_list, nil)
or typeof(impl_cls):GetMethod(method_name, flag)
return CS.System.Delegate.CreateDelegate(typeof(delegate_cls), obj, m)
end
local function state(csobj, state)
local csobj_mt = getmetatable(csobj)
for k, v in pairs(csobj_mt) do rawset(state, k, v) end
local csobj_index, csobj_newindex = state.__index, state.__newindex
state.__index = function(obj, k)
return rawget(state, k) or csobj_index(obj, k)
end
state.__newindex = function(obj, k, v)
if rawget(state, k) ~= nil then
rawset(state, k, v)
else
csobj_newindex(obj, k, v)
end
end
debug.setmetatable(csobj, state)
return state
end
local function print_func_ref_by_csharp()
local registry = debug.getregistry()
for k, v in pairs(registry) do
if type(k) == 'number' and type(v) == 'function' and registry[v] == k then
local info = debug.getinfo(v)
print(string.format('%s:%d', info.short_src, info.linedefined))
end
end
end
-- 深拷贝
local function deepcopy(object, origin)
local lookup_table = {}
local ret = nil
if (type(origin) == "table") then
ret = origin
end
local function _copy(object, origin)
if (type(object) ~= "table") then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = nil
if origin ~= nil then
new_table = origin
else
new_table = {}
end
lookup_table[object] = new_table
for index, value in pairs(object) do
new_table[_copy(index)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object, ret)
end
--- 忽略缓存的require
local function do_require(path)
if package.loaded[path] ~= nil then
package.loaded[path] = nil
end
require(path)
end
--- 卸载require的module
local function unrequire(path)
package.loaded[path] = nil
_G[path] = nil
end
return {
async_to_sync = async_to_sync,
coroutine_call = coroutine_call,
cs_generator = cs_generator,
loadpackage = loadpackage,
auto_id_map = auto_id_map,
hotfix_ex = hotfix_ex,
bind = bind,
createdelegate = createdelegate,
deepcopy = deepcopy,
do_require = do_require,
unrequire = unrequire,
state = state,
print_func_ref_by_csharp = print_func_ref_by_csharp,
}