{"TotalCount":74,"Files":[{"Ident":"roleplaydev.roleplay","Path":"Framework/Lua/Diagnostics/LuaSelfTest.cs","FileName":"LuaSelfTest.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace RoleplayFramework.Lua.Diagnostics;\r\n\r\n/// \u003Csummary\u003E\r\n/// Conformance and sandbox checks for the Lua runtime. Each case runs in a fresh state and\r\n/// must return a string equal to the expected value. Run from the editor with run_csharp:\r\n/// \u003Cc\u003Ereturn RoleplayFramework.Lua.Diagnostics.LuaSelfTest.RunAll();\u003C/c\u003E\r\n/// \u003C/summary\u003E\r\npublic static class LuaSelfTest\r\n{\r\n\tpublic sealed record Result( string Name, bool Passed, string Detail );\r\n\r\n\tpublic sealed record Summary( int Passed, int Failed, string Runtime, double Milliseconds, List\u003CResult\u003E Failures, string Report );\r\n\r\n\tstatic readonly (string name, string code, string expected)[] Cases =\r\n\t{\r\n\t\t// --- core semantics\r\n\t\t(\u0022arith\u0022, \u0022return tostring(1\u002B2*3-4/2) .. \u0027 \u0027 .. tostring(2^10) .. \u0027 \u0027 .. tostring(7 % 3) .. \u0027 \u0027 .. tostring(-7 % 3)\u0022, \u00225 1024 1 2\u0022),\r\n\t\t(\u0022number format\u0022, \u0022return tostring(10/4) .. \u0027 \u0027 .. tostring(1e20) .. \u0027 \u0027 .. tostring(100) .. \u0027 \u0027 .. tostring(0.1)\u0022, \u00222.5 1e\u002B20 100 0.1\u0022),\r\n\t\t(\u0022string coercion\u0022, \u0022return tostring(\u002710\u0027 \u002B 5) .. \u0027 \u0027 .. (1 .. 2)\u0022, \u002215 12\u0022),\r\n\t\t(\u0022precedence\u0022, \u0022return tostring(2^3^2) .. \u0027 \u0027 .. tostring(-2^2) .. \u0027 \u0027 .. tostring(not nil == true)\u0022, \u0022512 -4 true\u0022),\r\n\t\t(\u0022concat right assoc\u0022, \u0022return \u0027a\u0027 .. \u0027b\u0027 .. \u0027c\u0027 .. 1 .. 2\u0022, \u0022abc12\u0022),\r\n\t\t(\u0022and/or\u0022, \u0022return tostring(nil or \u0027x\u0027) .. tostring(false and 1) .. tostring(1 and 2)\u0022, \u0022xfalse2\u0022),\r\n\t\t(\u0022comparison\u0022, \u0022return tostring(1 \u003C 2) .. tostring(\u0027a\u0027 \u003C \u0027b\u0027) .. tostring(2 \u003C= 2) .. tostring(3 ~= 3)\u0022, \u0022truetruetruefalse\u0022),\r\n\t\t(\u0022multiple assign\u0022, \u0022local a, b, c = 1, 2; a, b = b, a; return a .. b .. tostring(c)\u0022, \u002221nil\u0022),\r\n\t\t(\u0022varargs\u0022, \u0022local function f(...) local a, b = ...; return select(\u0027#\u0027, ...), a, b end; local n, a, b = f(1, nil, 3); return n .. tostring(a) .. tostring(b)\u0022, \u002231nil\u0022),\r\n\t\t(\u0022vararg table\u0022, \u0022local function f(...) return {...} end; return #f(1,2,3,4)\u0022, \u00224\u0022),\r\n\t\t(\u0022multret in middle\u0022, \u0022local function f() return 1, 2 end; local t = {f(), f()}; return #t\u0022, \u00223\u0022),\r\n\t\t(\u0022paren truncates\u0022, \u0022local function f() return 1, 2 end; local t = {(f())}; return #t\u0022, \u00221\u0022),\r\n\t\t(\u0022closures per iteration\u0022, \u0022local fs = {}; for i = 1, 3 do fs[i] = function() return i end end; return fs[1]() .. fs[2]() .. fs[3]()\u0022, \u0022123\u0022),\r\n\t\t(\u0022upvalue sharing\u0022, \u0022local function counter() local n = 0; return function() n = n \u002B 1; return n end end; local c = counter(); c(); c(); return c()\u0022, \u00223\u0022),\r\n\t\t(\u0022nested upvalues\u0022, \u0022local x = 1; local function a() return function() return function() x = x \u002B 1; return x end end end; a()()(); return a()()()\u0022, \u00223\u0022),\r\n\t\t(\u0022recursion\u0022, \u0022local function fib(n) if n \u003C 2 then return n end return fib(n-1) \u002B fib(n-2) end; return fib(20)\u0022, \u00226765\u0022),\r\n\t\t(\u0022while/repeat\u0022, \u0022local i, s = 0, 0; while i \u003C 10 do i = i \u002B 1; s = s \u002B i end; repeat s = s - 1 local stop = s \u003C 50 until stop; return s\u0022, \u002249\u0022),\r\n\t\t(\u0022numeric for step\u0022, \u0022local s = \u0027\u0027; for i = 10, 1, -3 do s = s .. i .. \u0027,\u0027 end; return s\u0022, \u002210,7,4,1,\u0022),\r\n\t\t(\u0022generic for pairs\u0022, \u0022local t = {a=1, b=2, c=3}; local s = 0; for k, v in pairs(t) do s = s \u002B v end; return s\u0022, \u00226\u0022),\r\n\t\t(\u0022ipairs stops at nil\u0022, \u0022local t = {1, 2, nil, 4}; local n = 0; for _, v in ipairs(t) do n = n \u002B 1 end; return n\u0022, \u00222\u0022),\r\n\t\t(\u0022pairs order array first\u0022, \u0022local t = {10, 20, 30, x = 1}; local s = \u0027\u0027; for k in pairs(t) do s = s .. tostring(k) end; return s\u0022, \u0022123x\u0022),\r\n\t\t(\u0022clear during traversal\u0022, \u0022local t = {}; for i = 1, 20 do t[\u0027k\u0027..i] = i end; for k in pairs(t) do t[k] = nil end; return tostring(next(t))\u0022, \u0022nil\u0022),\r\n\t\t(\u0022length border\u0022, \u0022local t = {}; t[1] = 1; t[2] = 2; t[3] = 3; t[3] = nil; return #t\u0022, \u00222\u0022),\r\n\t\t(\u0022hash to array migration\u0022, \u0022local t = {}; t[3] = \u0027c\u0027; t[2] = \u0027b\u0027; t[1] = \u0027a\u0027; return #t .. table.concat(t)\u0022, \u00223abc\u0022),\r\n\t\t(\u0022break\u0022, \u0022local n = 0; for i = 1, 100 do if i \u003E 5 then break end; n = i end; return n\u0022, \u00225\u0022),\r\n\t\t(\u0022method call\u0022, \u0022local obj = {v = 41}; function obj:inc() self.v = self.v \u002B 1; return self.v end; return obj:inc()\u0022, \u002242\u0022),\r\n\t\t(\u0022string methods\u0022, \u0022local s = \u0027Hello\u0027; return s:upper() .. s:len() .. (\u0027x\u0027):rep(3)\u0022, \u0022HELLO5xxx\u0022),\r\n\t\t(\u0022long strings\u0022, \u0022local s = [[\\nline1\\nline2]]; local t = [==[a]]b]==]; return #s .. t\u0022, \u002211a]]b\u0022),\r\n\t\t(\u0022escapes\u0022, \u0022return \u0027\\\\65\\\\066\\\\x43\\\\t|\u0027 .. #\u0027\\\\n\u0027\u0022, \u0022ABC\\t|1\u0022),\r\n\r\n\t\t// --- GLua extensions\r\n\t\t(\u0022glua operators\u0022, \u0022local a = 1; if a != 2 \u0026\u0026 !(a == 3) || false then return \u0027ok\u0027 end return \u0027bad\u0027\u0022, \u0022ok\u0022),\r\n\t\t(\u0022glua comments\u0022, \u0022local a = 1 // comment\\n/* block\\ncomment */ return a \u002B 1\u0022, \u00222\u0022),\r\n\t\t(\u0022continue\u0022, \u0022local s = 0; for i = 1, 10 do if i % 2 == 0 then continue end; s = s \u002B i end; return s\u0022, \u002225\u0022),\r\n\r\n\t\t// --- metatables\r\n\t\t(\u0022__index table\u0022, \u0022local base = {greet = function() return \u0027hi\u0027 end}; local o = setmetatable({}, {__index = base}); return o.greet()\u0022, \u0022hi\u0022),\r\n\t\t(\u0022__index function\u0022, \u0022local o = setmetatable({}, {__index = function(t, k) return k .. \u0027!\u0027 end}); return o.foo\u0022, \u0022foo!\u0022),\r\n\t\t(\u0022__newindex\u0022, \u0022local log = {}; local o = setmetatable({}, {__newindex = function(t, k, v) rawset(t, k, v * 2) end}); o.x = 5; return o.x\u0022, \u002210\u0022),\r\n\t\t(\u0022__call\u0022, \u0022local o = setmetatable({}, {__call = function(self, a, b) return a \u002B b end}); return o(2, 3)\u0022, \u00225\u0022),\r\n\t\t(\u0022__add/__eq/__lt\u0022, \u0022local mt = {}; mt.__add = function(a, b) return setmetatable({v = a.v \u002B b.v}, mt) end; mt.__eq = function(a, b) return a.v == b.v end; mt.__lt = function(a, b) return a.v \u003C b.v end; local function V(v) return setmetatable({v = v}, mt) end; return tostring((V(1) \u002B V(2)) == V(3)) .. tostring(V(1) \u003C V(2)) .. tostring(V(2) \u003C= V(1))\u0022, \u0022truetruefalse\u0022),\r\n\t\t(\u0022__tostring\u0022, \u0022return tostring(setmetatable({}, {__tostring = function() return \u0027OBJ\u0027 end}))\u0022, \u0022OBJ\u0022),\r\n\t\t(\u0022__concat/__len/__unm\u0022, \u0022local mt = {__concat = function(a, b) return \u0027cat\u0027 end, __len = function() return 99 end, __unm = function() return \u0027neg\u0027 end}; local o = setmetatable({}, mt); return (o .. \u0027x\u0027) .. #o .. (-o)\u0022, \u0022cat99neg\u0022),\r\n\t\t(\u0022protected metatable\u0022, \u0022local o = setmetatable({}, {__metatable = \u0027locked\u0027}); local ok = pcall(setmetatable, o, {}); return tostring(getmetatable(o)) .. tostring(ok)\u0022, \u0022lockedfalse\u0022),\r\n\r\n\t\t// --- errors\r\n\t\t(\u0022pcall error string\u0022, \u0022local ok, e = pcall(function() error(\u0027boom\u0027) end); return tostring(ok) .. \u0027 \u0027 .. e\u0022, \u0022false test:1: boom\u0022),\r\n\t\t(\u0022pcall error level 0\u0022, \u0022local ok, e = pcall(error, \u0027raw\u0027, 0); return e\u0022, \u0022raw\u0022),\r\n\t\t(\u0022pcall error table\u0022, \u0022local ok, e = pcall(error, {code = 7}); return e.code\u0022, \u00227\u0022),\r\n\t\t(\u0022runtime error position\u0022, \u0022local ok, e = pcall(function()\\nlocal t = nil\\nreturn t.x\\nend); return e\u0022, \u0022test:3: attempt to index local \u0027t\u0027 (a nil value)\u0022),\r\n\t\t(\u0022call nil global\u0022, \u0022local ok, e = pcall(function() undefined_fn() end); return e\u0022, \u0022test:1: attempt to call global \u0027undefined_fn\u0027 (a nil value)\u0022),\r\n\t\t(\u0022arith error\u0022, \u0022local ok, e = pcall(function() return {} \u002B 1 end); return e\u0022, \u0022test:1: attempt to perform arithmetic on a table value\u0022),\r\n\t\t(\u0022compare error\u0022, \u0022local ok, e = pcall(function() return {} \u003C 1 end); return e\u0022, \u0022test:1: attempt to compare table with number\u0022),\r\n\t\t(\u0022xpcall handler\u0022, \u0022local ok, e = xpcall(function() error(\u0027x\u0027, 0) end, function(m) return \u0027handled:\u0027 .. m end); return e\u0022, \u0022handled:x\u0022),\r\n\t\t(\u0022assert\u0022, \u0022local ok, e = pcall(assert, false, \u0027nope\u0027); return e .. tostring(select(2, pcall(assert, 1, 2)))\u0022, \u0022nope1\u0022),\r\n\t\t(\u0022bad argument\u0022, \u0022local ok, e = pcall(string.rep); return e\u0022, \u0022bad argument #1 to \u0027rep\u0027 (string expected, got no value)\u0022),\r\n\t\t(\u0022error rethrow keeps value\u0022, \u0022local ok, e = pcall(function() local ok2, e2 = pcall(error, \u0027inner\u0027, 0); error(e2, 0) end); return e\u0022, \u0022inner\u0022),\r\n\r\n\t\t// --- string library\r\n\t\t(\u0022string.sub\u0022, \u0022local s = \u0027abcdef\u0027; return s:sub(2, 4) .. s:sub(-2) .. s:sub(5, 100) .. s:sub(0)\u0022, \u0022bcdefefabcdef\u0022),\r\n\t\t(\u0022string.byte/char\u0022, \u0022return string.char(string.byte(\u0027ABC\u0027, 1, 3)) .. string.byte(\u0027a\u0027)\u0022, \u0022ABC97\u0022),\r\n\t\t(\u0022string.find plain\u0022, \u0022return table.concat({string.find(\u0027a.b.c\u0027, \u0027.\u0027, 1, true)}, \u0027,\u0027)\u0022, \u00222,2\u0022),\r\n\t\t(\u0022string.find pattern\u0022, \u0022return table.concat({string.find(\u0027hello world\u0027, \u0027o w\u0027)}, \u0027,\u0027) .. \u0027|\u0027 .. table.concat({(\u0027key=value\u0027):find(\u0027(%w\u002B)=(%w\u002B)\u0027)}, \u0027,\u0027)\u0022, \u00225,7|1,9,key,value\u0022),\r\n\t\t(\u0022string.match\u0022, \u0022return string.match(\u0027  trim me  \u0027, \u0027^%s*(.-)%s*$\u0027) .. \u0027|\u0027 .. string.match(\u00272024-11-18\u0027, \u0027(%d\u002B)-(%d\u002B)\u0027)\u0022, \u0022trim me|2024\u0022),\r\n\t\t(\u0022string.match anchors/classes\u0022, \u0022return tostring((\u0027abc\u0027):match(\u0027^b\u0027)) .. (\u0027x=1, y=22\u0027):match(\u0027y=(%d\u002B)\u0027) .. (\u0027[tag]\u0027):match(\u0027%[(%a\u002B)%]\u0027)\u0022, \u0022nil22tag\u0022),\r\n\t\t(\u0022string.gmatch\u0022, \u0022local t = {}; for k, v in string.gmatch(\u0027a=1, b=2, c=3\u0027, \u0027(%w\u002B)=(%w\u002B)\u0027) do t[#t\u002B1] = k .. v end; return table.concat(t, \u0027 \u0027)\u0022, \u0022a1 b2 c3\u0022),\r\n\t\t(\u0022string.gsub string\u0022, \u0022return (string.gsub(\u0027hello world\u0027, \u0027o\u0027, \u00270\u0027)) .. select(2, string.gsub(\u0027aaa\u0027, \u0027a\u0027, \u0027b\u0027))\u0022, \u0022hell0 w0rld3\u0022),\r\n\t\t(\u0022string.gsub captures\u0022, \u0022return (string.gsub(\u0027John Smith\u0027, \u0027(%w\u002B) (%w\u002B)\u0027, \u0027%2, %1\u0027))\u0022, \u0022Smith, John\u0022),\r\n\t\t(\u0022string.gsub function/table\u0022, \u0022local r = string.gsub(\u0027$name is $age\u0027, \u0027%$(%w\u002B)\u0027, {name = \u0027Bob\u0027, age = 30}); local r2 = string.gsub(\u0027abc\u0027, \u0027%w\u0027, function(c) return c:upper() .. \u0027.\u0027 end); return r .. \u0027|\u0027 .. r2\u0022, \u0022Bob is 30|A.B.C.\u0022),\r\n\t\t(\u0022string.gsub limit/anchor\u0022, \u0022return (string.gsub(\u0027aaaa\u0027, \u0027a\u0027, \u0027b\u0027, 2)) .. (string.gsub(\u0027aaaa\u0027, \u0027^a\u0027, \u0027b\u0027))\u0022, \u0022bbaabaaa\u0022),\r\n\t\t(\u0022pattern %b and %f\u0022, \u0022return (\u0027f(a(b)c)d\u0027):match(\u0027%b()\u0027) .. \u0027|\u0027 .. (string.gsub(\u0027THE (quick) fox\u0027, \u0027%f[%a]%a\u002B\u0027, \u0027W\u0027))\u0022, \u0022(a(b)c)|W (W) W\u0022),\r\n\t\t(\u0022pattern back reference\u0022, \u0022return (\u0027say \\\u0022hi\\\u0022 now\u0027):match(\u0027([\\\u0022\\\\\u0027])(.-)%1\u0027)\u0022, \u0022\\\u0022\u0022),\r\n\t\t(\u0022pattern position capture\u0022, \u0022return table.concat({(\u0027hello\u0027):match(\u0027()ll()\u0027)}, \u0027,\u0027)\u0022, \u00223,5\u0022),\r\n\t\t(\u0022pattern sets\u0022, \u0022return (string.gsub(\u0027a1-b2_c3\u0027, \u0027[^%a]\u0027, \u0027\u0027)) .. (string.gsub(\u0027abcxyz\u0027, \u0027[a-c]\u0027, \u0027*\u0027))\u0022, \u0022abc***xyz\u0022),\r\n\t\t(\u0022string.format ints\u0022, \u0022return string.format(\u0027%d|%5d|%-5d|%05d|%\u002Bd|%x|%X|%o\u0027, 42, 42, 42, 42, 42, 255, 255, 8)\u0022, \u002242|   42|42   |00042|\u002B42|ff|FF|10\u0022),\r\n\t\t(\u0022string.format floats\u0022, \u0022return string.format(\u0027%.2f|%10.3f|%e|%g|%g|%g\u0027, 3.14159, 2.5, 12345.678, 0.0001, 1e20, 100)\u0022, \u00223.14|     2.500|1.234568e\u002B04|0.0001|1e\u002B20|100\u0022),\r\n\t\t(\u0022string.format strings\u0022, \u0022return string.format(\u0027%s|%10s|%-4s|%.2s|%q|%%|%c\u0027, \u0027x\u0027, \u0027right\u0027, \u0027l\u0027, \u0027abc\u0027, \u0027a\\\u0022b\u0027, 65)\u0022, \u0022x|     right|l   |ab|\\\u0022a\\\\\\\u0022b\\\u0022|%|A\u0022),\r\n\t\t(\u0022string.format tostring\u0022, \u0022return string.format(\u0027%s %s %s\u0027, nil, true, setmetatable({}, {__tostring = function() return \u0027T\u0027 end}))\u0022, \u0022nil true T\u0022),\r\n\r\n\t\t// --- table / math / misc\r\n\t\t(\u0022table.insert/remove\u0022, \u0022local t = {1, 2, 3}; table.insert(t, 4); table.insert(t, 1, 0); local r = table.remove(t, 2); local last = table.remove(t); return table.concat(t, \u0027,\u0027) .. \u0027|\u0027 .. r .. last\u0022, \u00220,2,3|14\u0022),\r\n\t\t(\u0022table.sort\u0022, \u0022local t = {5, 2, 8, 1, 9}; table.sort(t); local u = {\u0027b\u0027, \u0027c\u0027, \u0027a\u0027}; table.sort(u, function(a, b) return a \u003E b end); return table.concat(t, \u0027,\u0027) .. \u0027|\u0027 .. table.concat(u)\u0022, \u00221,2,5,8,9|cba\u0022),\r\n\t\t(\u0022table.sort stable records\u0022, \u0022local t = {{n=\u0027a\u0027, v=2}, {n=\u0027b\u0027, v=1}, {n=\u0027c\u0027, v=2}}; table.sort(t, function(x, y) return x.v \u003C y.v end); return t[1].n .. t[2].n .. t[3].n\u0022, \u0022bac\u0022),\r\n\t\t(\u0022unpack\u0022, \u0022return select(\u0027#\u0027, unpack({1, 2, 3})) .. table.concat({unpack({1, 2, 3}, 2)})\u0022, \u0022323\u0022),\r\n\t\t(\u0022tonumber\u0022, \u0022return tostring(tonumber(\u00270x1F\u0027)) .. tostring(tonumber(\u0027 12 \u0027)) .. tostring(tonumber(\u0027ff\u0027, 16)) .. tostring(tonumber(\u0027z\u0027))\u0022, \u00223112255nil\u0022),\r\n\t\t(\u0022math\u0022, \u0022return math.floor(3.7) .. math.ceil(3.2) .. math.max(1, 5, 3) .. math.min(4, 2) .. math.abs(-3) .. math.fmod(7, 3)\u0022, \u0022345231\u0022),\r\n\t\t(\u0022math.random range\u0022, \u0022math.randomseed(1); for i = 1, 200 do local r = math.random(1, 6); if r \u003C 1 or r \u003E 6 or r % 1 ~= 0 then return \u0027bad\u0027 end end; return \u0027ok\u0027\u0022, \u0022ok\u0022),\r\n\t\t(\u0022type\u0022, \u0022return type(nil) .. type(1) .. type(\u0027\u0027) .. type({}) .. type(print) .. type(true)\u0022, \u0022nilnumberstringtablefunctionboolean\u0022),\r\n\t\t(\u0022_G\u0022, \u0022x_global = 5; return _G.x_global \u002B _G[\u0027x_global\u0027]\u0022, \u002210\u0022),\r\n\t\t(\u0022os.time\u0022, \u0022return type(os.time()) .. type(os.clock()) .. type(os.date(\u0027%Y\u0027))\u0022, \u0022numbernumberstring\u0022),\r\n\r\n\t\t// --- clearing fields during traversal is allowed in Lua (GMod\u0027s table.Empty does it)\r\n\t\t(\u0022clear array during pairs\u0022, \u0022local t = { 1, 2, 3 } for k in pairs(t) do t[k] = nil end return tostring(next(t))\u0022, \u0022nil\u0022),\r\n\t\t(\u0022clear mixed table during pairs\u0022, \u0022local t = { 1, 2, a = 1, b = 2 } local n = 0 for k in pairs(t) do t[k] = nil n = n \u002B 1 end return n .. tostring(next(t))\u0022, \u00224nil\u0022),\r\n\r\n\t\t// --- sandbox: none of these may exist\r\n\t\t(\u0022sandbox: no io/debug/package\u0022, \u0022return tostring(io) .. tostring(debug) .. tostring(package) .. tostring(require)\u0022, \u0022nilnilnilnil\u0022),\r\n\t\t(\u0022sandbox: no dynamic code loading\u0022, \u0022return tostring(load) .. tostring(loadstring) .. tostring(dofile) .. tostring(loadfile)\u0022, \u0022nilnilnilnil\u0022),\r\n\t\t(\u0022sandbox: no os escape hatches\u0022, \u0022return tostring(os.execute) .. tostring(os.remove) .. tostring(os.rename) .. tostring(os.getenv) .. tostring(os.exit)\u0022, \u0022nilnilnilnilnil\u0022),\r\n\t\t(\u0022sandbox: no env manipulation\u0022, \u0022return tostring(setfenv) .. tostring(getfenv) .. tostring(collectgarbage) .. tostring(newproxy)\u0022, \u0022nilnilnilnil\u0022),\r\n\t\t(\u0022stack overflow is catchable\u0022, \u0022local function f() return f() \u002B 1 end; local ok, e = pcall(f); return tostring(ok) .. tostring(e:find(\u0027stack overflow\u0027) ~= nil)\u0022, \u0022falsetrue\u0022),\r\n\t};\r\n\r\n\tpublic static Summary RunAll()\r\n\t{\r\n\t\tvar start = DateTime.UtcNow;\r\n\t\tvar results = new List\u003CResult\u003E();\r\n\r\n\t\tforeach ( var (name, code, expected) in Cases )\r\n\t\t\tresults.Add( RunCase( name, code, expected ) );\r\n\r\n\t\tresults.Add( CheckSyntaxError() );\r\n\t\tresults.Add( CheckBudget() );\r\n\t\tresults.Add( CheckBudgetNotCatchable() );\r\n\t\tresults.Add( CheckHostBinding() );\r\n\t\tresults.Add( CheckRealmIsolation() );\r\n\t\tresults.Add( CheckHostExceptionContained() );\r\n\t\tresults.Add( CheckExpressionDepthLimit() );\r\n\t\tresults.Add( CheckNestingLimit() );\r\n\r\n\t\tvar ms = (DateTime.UtcNow - start).TotalMilliseconds;\r\n\t\tvar failures = results.FindAll( r =\u003E !r.Passed );\r\n\t\tint passed = results.Count - failures.Count;\r\n\r\n\t\tvar sb = new StringBuilder();\r\n\t\tsb.Append( $\u0022{LuaState.RuntimeName} {LuaState.RuntimeVersion} ({LuaState.LanguageVersion}): {passed}/{results.Count} passed in {ms:F1} ms\u0022 );\r\n\t\tforeach ( var f in failures ) sb.Append( $\u0022\\n  FAIL {f.Name}: {f.Detail}\u0022 );\r\n\r\n\t\treturn new Summary( passed, failures.Count, $\u0022{LuaState.RuntimeName} {LuaState.RuntimeVersion}\u0022, ms, failures, sb.ToString() );\r\n\t}\r\n\r\n\tstatic Result RunCase( string name, string code, string expected )\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tvar L = new LuaState( \u0022selftest\u0022 );\r\n\t\t\tvar r = L.DoString( code, \u0022test\u0022 );\r\n\t\t\tvar got = r.Length \u003E 0 ? r[0].ToString() : \u0022\u003Cno value\u003E\u0022;\r\n\t\t\treturn got == expected\r\n\t\t\t\t? new Result( name, true, null )\r\n\t\t\t\t: new Result( name, false, $\u0022expected [{expected}] got [{got}]\u0022 );\r\n\t\t}\r\n\t\tcatch ( LuaRuntimeException e )\r\n\t\t{\r\n\t\t\treturn new Result( name, false, $\u0022runtime error: {e.Message}\\n{e.LuaTraceback}\u0022 );\r\n\t\t}\r\n\t\tcatch ( Exception e )\r\n\t\t{\r\n\t\t\treturn new Result( name, false, $\u0022{e.GetType().Name}: {e.Message}\u0022 );\r\n\t\t}\r\n\t}\r\n\r\n\tstatic Result CheckSyntaxError()\r\n\t{\r\n\t\tconst string name = \u0022syntax error reports chunk and line\u0022;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tnew LuaState().Load( \u0022local a = 1\\nlocal b = = 2\u0022, \u0022gamemodes/darkrp/sv_init.lua\u0022 );\r\n\t\t\treturn new Result( name, false, \u0022no error raised\u0022 );\r\n\t\t}\r\n\t\tcatch ( LuaSyntaxException e )\r\n\t\t{\r\n\t\t\tbool ok = e.ChunkName == \u0022gamemodes/darkrp/sv_init.lua\u0022 \u0026\u0026 e.Line == 2 \u0026\u0026 e.Message.StartsWith( \u0022gamemodes/darkrp/sv_init.lua:2:\u0022 );\r\n\t\t\treturn new Result( name, ok, e.Message );\r\n\t\t}\r\n\t}\r\n\r\n\tstatic Result CheckBudget()\r\n\t{\r\n\t\tconst string name = \u0022instruction budget stops infinite loop\u0022;\r\n\t\tvar L = new LuaState { InstructionBudget = 100_000 };\r\n\t\ttry\r\n\t\t{\r\n\t\t\tL.DoString( \u0022while true do end\u0022, \u0022loop\u0022 );\r\n\t\t\treturn new Result( name, false, \u0022loop was not stopped\u0022 );\r\n\t\t}\r\n\t\tcatch ( LuaBudgetExceededException e )\r\n\t\t{\r\n\t\t\t// The state must be reusable after the watchdog fires.\r\n\t\t\tvar r = L.DoString( \u0022return 1 \u002B 1\u0022, \u0022after\u0022 );\r\n\t\t\treturn new Result( name, r[0].Number == 2, e.Message );\r\n\t\t}\r\n\t}\r\n\r\n\tstatic Result CheckBudgetNotCatchable()\r\n\t{\r\n\t\tconst string name = \u0022pcall cannot swallow the budget watchdog\u0022;\r\n\t\tvar L = new LuaState { InstructionBudget = 100_000 };\r\n\t\ttry\r\n\t\t{\r\n\t\t\tL.DoString( \u0022while true do pcall(function() while true do end end) end\u0022, \u0022trap\u0022 );\r\n\t\t\treturn new Result( name, false, \u0022loop was not stopped\u0022 );\r\n\t\t}\r\n\t\tcatch ( LuaBudgetExceededException )\r\n\t\t{\r\n\t\t\treturn new Result( name, true, null );\r\n\t\t}\r\n\t}\r\n\r\n\tstatic Result CheckHostBinding()\r\n\t{\r\n\t\tconst string name = \u0022host functions and callbacks\u0022;\r\n\t\tvar L = new LuaState();\r\n\t\tvar hooks = new Dictionary\u003Cstring, LuaValue\u003E();\r\n\t\tvar hook = L.GetOrCreateLibrary( \u0022hook\u0022 );\r\n\t\tLuaState.Register( hook, \u0022Add\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\thooks[LuaState.CheckString( a, 0, \u0022hook.Add\u0022 )] = a[1];\r\n\t\t\treturn null;\r\n\t\t} );\r\n\r\n\t\tL.DoString( \u0022hook.Add(\u0027PlayerSpawn\u0027, function(name, money) return name .. \u0027 spawned with $\u0027 .. money end)\u0022, \u0022sh_init.lua\u0022 );\r\n\t\tvar r = L.PCall( hooks[\u0022PlayerSpawn\u0022], \u0022Alice\u0022, 500 );\r\n\t\treturn new Result( name, r.Success \u0026\u0026 r.Results[0].AsString == \u0022Alice spawned with $500\u0022, r.Error ?? r.Results[0].AsString );\r\n\t}\r\n\r\n\tstatic Result CheckRealmIsolation()\r\n\t{\r\n\t\tconst string name = \u0022realms are isolated\u0022;\r\n\t\tvar server = new LuaState( \u0022server\u0022 );\r\n\t\tvar client = new LuaState( \u0022client\u0022 );\r\n\t\tserver.DoString( \u0022SECRET = \u0027server only\u0027\u0022, \u0022sv_secret.lua\u0022 );\r\n\t\tvar r = client.DoString( \u0022return tostring(SECRET)\u0022, \u0022cl_probe.lua\u0022 );\r\n\t\treturn new Result( name, r[0].AsString == \u0022nil\u0022, r[0].AsString );\r\n\t}\r\n\r\n\tstatic Result CheckExpressionDepthLimit()\r\n\t{\r\n\t\tconst string name = \u0022huge expression chain is rejected, not a crash\u0022;\r\n\t\tvar sb = new StringBuilder( \u0022return 1\u0022 );\r\n\t\tfor ( int i = 0; i \u003C 5000; i\u002B\u002B ) sb.Append( \u0022 \u002B 1\u0022 );\r\n\t\ttry\r\n\t\t{\r\n\t\t\tnew LuaState().Load( sb.ToString(), \u0022chain\u0022 );\r\n\t\t\treturn new Result( name, false, \u0022no error raised\u0022 );\r\n\t\t}\r\n\t\tcatch ( LuaSyntaxException e )\r\n\t\t{\r\n\t\t\treturn new Result( name, e.Message.Contains( \u0022expression too complex\u0022 ), e.Message );\r\n\t\t}\r\n\t}\r\n\r\n\tstatic Result CheckNestingLimit()\r\n\t{\r\n\t\tconst string name = \u0022deep nesting is rejected, not a crash\u0022;\r\n\t\tvar src = new string( \u0027(\u0027, 5000 ) \u002B \u00221\u0022 \u002B new string( \u0027)\u0027, 5000 );\r\n\t\ttry\r\n\t\t{\r\n\t\t\tnew LuaState().Load( \u0022return \u0022 \u002B src, \u0022nest\u0022 );\r\n\t\t\treturn new Result( name, false, \u0022no error raised\u0022 );\r\n\t\t}\r\n\t\tcatch ( LuaSyntaxException e )\r\n\t\t{\r\n\t\t\treturn new Result( name, e.Message.Contains( \u0022too many syntax levels\u0022 ), e.Message );\r\n\t\t}\r\n\t}\r\n\r\n\tstatic Result CheckHostExceptionContained()\r\n\t{\r\n\t\tconst string name = \u0022host exceptions become Lua errors\u0022;\r\n\t\tvar L = new LuaState();\r\n\t\tL.Register( \u0022explode\u0022, ( s, a ) =\u003E throw new InvalidOperationException( \u0022host bug\u0022 ) );\r\n\t\tvar r = L.DoString( \u0022local ok, e = pcall(explode); return e\u0022, \u0022probe\u0022 );\r\n\t\tvar got = r[0].AsString ?? \u0022\u0022;\r\n\t\treturn new Result( name, got.Contains( \u0022internal error in \u0027explode\u0027\u0022 ), got );\r\n\t}\r\n}\r\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Lua/Runtime/Compiler/Ast.cs","FileName":"Ast.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\n\nnamespace RoleplayFramework.Lua.Compiler;\n\n// Tree-walking interpreter. The parser resolves every name to a local slot, an upvalue index\n// or a global at compile time, so execution never does name lookups for locals.\n\ninternal enum ExecResult : byte { Normal, Break, Continue, Return }\n\ninternal sealed class Frame\n{\n\tpublic Cell[] Slots;\n\tpublic LuaValue[] Varargs;\n\tpublic LuaClosure Closure;\n\tpublic LuaState State;\n\tpublic LuaValue[] Returns;\n\tpublic int Line;\n}\n\ninternal struct UpvalDesc\n{\n\tpublic bool FromParentLocal;\n\tpublic int Index;\n\tpublic string Name;\n}\n\ninternal sealed class FunctionProto\n{\n\tpublic string Name;\n\tpublic string ChunkName;\n\tpublic int Line;\n\tpublic int ParamCount;\n\tpublic bool IsVararg;\n\tpublic int SlotCount;\n\tpublic UpvalDesc[] Upvalues;\n\tpublic Block Body;\n}\n\n// ---------------------------------------------------------------- expressions\n\ninternal abstract class Expr\n{\n\tpublic int Line;\n\t/// \u003Csummary\u003ENesting depth of this expression tree (set by the parser).\u003C/summary\u003E\n\tpublic int Depth;\n\tpublic abstract LuaValue Eval( Frame f );\n\tpublic virtual bool IsMulti =\u003E false;\n\tpublic virtual LuaValue[] EvalMulti( Frame f ) =\u003E new[] { Eval( f ) };\n\t/// \u003Csummary\u003EDescribes the variable for error messages, e.g. \u0022global \u0027foo\u0027\u0022.\u003C/summary\u003E\n\tpublic virtual string Describe() =\u003E null;\n\n\tpublic static LuaValue[] EvalList( Frame f, Expr[] exprs )\n\t{\n\t\tint n = exprs.Length;\n\t\tif ( n == 0 ) return LuaValue.EmptyArray;\n\n\t\tvar last = exprs[n - 1];\n\t\tif ( !last.IsMulti )\n\t\t{\n\t\t\tvar r = new LuaValue[n];\n\t\t\tfor ( int i = 0; i \u003C n; i\u002B\u002B ) r[i] = exprs[i].Eval( f );\n\t\t\treturn r;\n\t\t}\n\n\t\tif ( n == 1 ) return last.EvalMulti( f );\n\n\t\tvar firsts = new LuaValue[n - 1];\n\t\tfor ( int i = 0; i \u003C n - 1; i\u002B\u002B ) firsts[i] = exprs[i].Eval( f );\n\t\tvar tail = last.EvalMulti( f );\n\t\tvar all = new LuaValue[firsts.Length \u002B tail.Length];\n\t\tfirsts.CopyTo( all, 0 );\n\t\ttail.CopyTo( all, firsts.Length );\n\t\treturn all;\n\t}\n}\n\ninternal interface IAssignable\n{\n\t/// \u003Csummary\u003EEvaluates the target\u0027s object/key ahead of the right-hand side.\u003C/summary\u003E\n\tobject Prepare( Frame f );\n\tvoid Assign( Frame f, object prepared, LuaValue value );\n}\n\ninternal sealed class ConstExpr : Expr\n{\n\tpublic LuaValue Value;\n\tpublic override LuaValue Eval( Frame f ) =\u003E Value;\n}\n\ninternal sealed class VarargExpr : Expr\n{\n\tpublic override bool IsMulti =\u003E true;\n\tpublic override LuaValue Eval( Frame f ) =\u003E f.Varargs.Length \u003E 0 ? f.Varargs[0] : LuaValue.Nil;\n\tpublic override LuaValue[] EvalMulti( Frame f ) =\u003E f.Varargs;\n}\n\ninternal sealed class ParenExpr : Expr\n{\n\tpublic Expr Inner;\n\tpublic override LuaValue Eval( Frame f ) =\u003E Inner.Eval( f );\n}\n\ninternal sealed class LocalExpr : Expr, IAssignable\n{\n\tpublic int Slot;\n\tpublic string Name;\n\tpublic override LuaValue Eval( Frame f ) =\u003E f.Slots[Slot].Value;\n\tpublic override string Describe() =\u003E $\u0022local \u0027{Name}\u0027\u0022;\n\tpublic object Prepare( Frame f ) =\u003E null;\n\tpublic void Assign( Frame f, object prepared, LuaValue value ) =\u003E f.Slots[Slot].Value = value;\n}\n\ninternal sealed class UpvalExpr : Expr, IAssignable\n{\n\tpublic int Index;\n\tpublic string Name;\n\tpublic override LuaValue Eval( Frame f ) =\u003E f.Closure.Upvalues[Index].Value;\n\tpublic override string Describe() =\u003E $\u0022upvalue \u0027{Name}\u0027\u0022;\n\tpublic object Prepare( Frame f ) =\u003E null;\n\tpublic void Assign( Frame f, object prepared, LuaValue value ) =\u003E f.Closure.Upvalues[Index].Value = value;\n}\n\ninternal sealed class GlobalExpr : Expr, IAssignable\n{\n\tpublic LuaValue Key;\n\tpublic override LuaValue Eval( Frame f )\n\t{\n\t\tvar env = f.Closure.Env;\n\t\tvar v = env.Get( Key );\n\t\tif ( v.IsNil \u0026\u0026 env.Metatable is not null ) return f.State.Index( LuaValue.FromTable( env ), Key );\n\t\treturn v;\n\t}\n\tpublic override string Describe() =\u003E $\u0022global \u0027{Key.AsString}\u0027\u0022;\n\tpublic object Prepare( Frame f ) =\u003E null;\n\tpublic void Assign( Frame f, object prepared, LuaValue value )\n\t{\n\t\tvar env = f.Closure.Env;\n\t\tif ( env.Metatable is null ) env.Set( Key, value );\n\t\telse f.State.SetIndex( LuaValue.FromTable( env ), Key, value );\n\t}\n}\n\ninternal sealed class IndexExpr : Expr, IAssignable\n{\n\tpublic Expr Obj;\n\tpublic Expr Key;\n\n\tsealed class Prepared { public LuaValue Obj; public LuaValue Key; }\n\n\tpublic override LuaValue Eval( Frame f )\n\t{\n\t\tvar o = Obj.Eval( f );\n\t\tvar k = Key.Eval( f );\n\t\tif ( o.Type == LuaType.Table )\n\t\t{\n\t\t\tvar t = (LuaTable)o.Obj;\n\t\t\tvar v = t.Get( k );\n\t\t\tif ( !v.IsNil || t.Metatable is null ) return v;\n\t\t}\n\t\telse if ( o.Type == LuaType.Nil )\n\t\t{\n\t\t\tf.Line = Line;\n\t\t\tthrow new LuaRuntimeException( IndexError( o ) );\n\t\t}\n\t\tf.Line = Line;\n\t\treturn f.State.Index( o, k );\n\t}\n\n\tstring IndexError( LuaValue o )\n\t{\n\t\tvar d = Obj.Describe();\n\t\treturn d is null ? $\u0022attempt to index a {o.TypeName} value\u0022 : $\u0022attempt to index {d} (a {o.TypeName} value)\u0022;\n\t}\n\n\tpublic override string Describe() =\u003E Key is ConstExpr c \u0026\u0026 c.Value.IsString ? $\u0022field \u0027{c.Value.AsString}\u0027\u0022 : null;\n\n\tpublic object Prepare( Frame f ) =\u003E new Prepared { Obj = Obj.Eval( f ), Key = Key.Eval( f ) };\n\n\tpublic void Assign( Frame f, object prepared, LuaValue value )\n\t{\n\t\tvar p = (Prepared)prepared;\n\t\tAssignTo( f, p.Obj, p.Key, value );\n\t}\n\n\tpublic void AssignTo( Frame f, LuaValue o, LuaValue k, LuaValue value )\n\t{\n\t\tf.Line = Line;\n\t\tif ( o.Type == LuaType.Table )\n\t\t{\n\t\t\tvar t = (LuaTable)o.Obj;\n\t\t\tif ( t.Metatable is null ) { t.Set( k, value ); return; }\n\t\t}\n\t\telse if ( o.Type == LuaType.Nil )\n\t\t{\n\t\t\tthrow new LuaRuntimeException( IndexError( o ) );\n\t\t}\n\t\tf.State.SetIndex( o, k, value );\n\t}\n}\n\ninternal sealed class CallExpr : Expr\n{\n\tpublic Expr Fn;\n\tpublic Expr[] Args;\n\n\tpublic override bool IsMulti =\u003E true;\n\n\tpublic override LuaValue Eval( Frame f )\n\t{\n\t\tvar r = EvalMulti( f );\n\t\treturn r.Length \u003E 0 ? r[0] : LuaValue.Nil;\n\t}\n\n\tpublic override LuaValue[] EvalMulti( Frame f )\n\t{\n\t\tvar fn = Fn.Eval( f );\n\t\tvar args = EvalList( f, Args );\n\t\tf.Line = Line;\n\t\tif ( fn.Type != LuaType.Function \u0026\u0026 f.State.GetMetamethod( fn, \u0022__call\u0022 ).IsNil )\n\t\t{\n\t\t\tvar d = Fn.Describe();\n\t\t\tthrow new LuaRuntimeException( d is null ? $\u0022attempt to call a {fn.TypeName} value\u0022 : $\u0022attempt to call {d} (a {fn.TypeName} value)\u0022 );\n\t\t}\n\t\treturn f.State.Call( fn, args );\n\t}\n}\n\ninternal sealed class MethodCallExpr : Expr\n{\n\tpublic Expr Obj;\n\tpublic string Method;\n\tpublic Expr[] Args;\n\n\tpublic override bool IsMulti =\u003E true;\n\n\tpublic override LuaValue Eval( Frame f )\n\t{\n\t\tvar r = EvalMulti( f );\n\t\treturn r.Length \u003E 0 ? r[0] : LuaValue.Nil;\n\t}\n\n\tpublic override LuaValue[] EvalMulti( Frame f )\n\t{\n\t\tvar o = Obj.Eval( f );\n\t\tf.Line = Line;\n\t\tif ( o.IsNil )\n\t\t{\n\t\t\tvar d = Obj.Describe();\n\t\t\tthrow new LuaRuntimeException( d is null ? \u0022attempt to index a nil value\u0022 : $\u0022attempt to index {d} (a nil value)\u0022 );\n\t\t}\n\n\t\tvar fn = f.State.Index( o, LuaValue.FromString( Method ) );\n\n\t\tLuaValue[] args;\n\t\tif ( Args.Length == 0 )\n\t\t{\n\t\t\targs = new[] { o };\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvar rest = EvalList( f, Args );\n\t\t\targs = new LuaValue[rest.Length \u002B 1];\n\t\t\targs[0] = o;\n\t\t\trest.CopyTo( args, 1 );\n\t\t}\n\n\t\tf.Line = Line;\n\t\tif ( fn.Type != LuaType.Function \u0026\u0026 f.State.GetMetamethod( fn, \u0022__call\u0022 ).IsNil )\n\t\t\tthrow new LuaRuntimeException( $\u0022attempt to call method \u0027{Method}\u0027 (a {fn.TypeName} value)\u0022 );\n\n\t\treturn f.State.Call( fn, args );\n\t}\n}\n\ninternal sealed class FunctionExpr : Expr\n{\n\tpublic FunctionProto Proto;\n\n\tpublic override LuaValue Eval( Frame f )\n\t{\n\t\tvar descs = Proto.Upvalues;\n\t\tvar ups = descs.Length == 0 ? Array.Empty\u003CCell\u003E() : new Cell[descs.Length];\n\t\tfor ( int i = 0; i \u003C descs.Length; i\u002B\u002B )\n\t\t{\n\t\t\tups[i] = descs[i].FromParentLocal ? f.Slots[descs[i].Index] : f.Closure.Upvalues[descs[i].Index];\n\t\t}\n\t\treturn LuaValue.FromFunction( new LuaClosure( Proto, ups, f.Closure.Env ) );\n\t}\n}\n\ninternal enum BinOp : byte { Add, Sub, Mul, Div, Mod, Pow, Concat, Eq, Ne, Lt, Le, Gt, Ge }\n\ninternal sealed class BinaryExpr : Expr\n{\n\tpublic BinOp Op;\n\tpublic Expr A;\n\tpublic Expr B;\n\n\tpublic override LuaValue Eval( Frame f )\n\t{\n\t\tvar a = A.Eval( f );\n\t\tvar b = B.Eval( f );\n\n\t\tif ( a.Type == LuaType.Number \u0026\u0026 b.Type == LuaType.Number )\n\t\t{\n\t\t\tdouble x = a.Number, y = b.Number;\n\t\t\tswitch ( Op )\n\t\t\t{\n\t\t\t\tcase BinOp.Add: return LuaValue.FromNumber( x \u002B y );\n\t\t\t\tcase BinOp.Sub: return LuaValue.FromNumber( x - y );\n\t\t\t\tcase BinOp.Mul: return LuaValue.FromNumber( x * y );\n\t\t\t\tcase BinOp.Div: return LuaValue.FromNumber( x / y );\n\t\t\t\tcase BinOp.Mod: return LuaValue.FromNumber( LuaState.Mod( x, y ) );\n\t\t\t\tcase BinOp.Pow: return LuaValue.FromNumber( Math.Pow( x, y ) );\n\t\t\t\tcase BinOp.Eq: return LuaValue.FromBool( x == y );\n\t\t\t\tcase BinOp.Ne: return LuaValue.FromBool( x != y );\n\t\t\t\tcase BinOp.Lt: return LuaValue.FromBool( x \u003C y );\n\t\t\t\tcase BinOp.Le: return LuaValue.FromBool( x \u003C= y );\n\t\t\t\tcase BinOp.Gt: return LuaValue.FromBool( x \u003E y );\n\t\t\t\tcase BinOp.Ge: return LuaValue.FromBool( x \u003E= y );\n\t\t\t}\n\t\t}\n\n\t\tf.Line = Line;\n\t\tvar s = f.State;\n\t\tswitch ( Op )\n\t\t{\n\t\t\tcase BinOp.Eq: return LuaValue.FromBool( s.ValuesEqual( a, b ) );\n\t\t\tcase BinOp.Ne: return LuaValue.FromBool( !s.ValuesEqual( a, b ) );\n\t\t\tcase BinOp.Lt: return LuaValue.FromBool( s.LessThan( a, b ) );\n\t\t\tcase BinOp.Le: return LuaValue.FromBool( s.LessEqual( a, b ) );\n\t\t\tcase BinOp.Gt: return LuaValue.FromBool( s.LessThan( b, a ) );\n\t\t\tcase BinOp.Ge: return LuaValue.FromBool( s.LessEqual( b, a ) );\n\t\t\tcase BinOp.Concat: return s.Concat( a, b );\n\t\t\tdefault: return s.Arith( Op, a, b );\n\t\t}\n\t}\n}\n\ninternal sealed class AndExpr : Expr\n{\n\tpublic Expr A, B;\n\tpublic override LuaValue Eval( Frame f )\n\t{\n\t\tvar a = A.Eval( f );\n\t\treturn a.IsTruthy ? B.Eval( f ) : a;\n\t}\n}\n\ninternal sealed class OrExpr : Expr\n{\n\tpublic Expr A, B;\n\tpublic override LuaValue Eval( Frame f )\n\t{\n\t\tvar a = A.Eval( f );\n\t\treturn a.IsTruthy ? a : B.Eval( f );\n\t}\n}\n\ninternal enum UnOp : byte { Neg, Not, Len }\n\ninternal sealed class UnaryExpr : Expr\n{\n\tpublic UnOp Op;\n\tpublic Expr A;\n\n\tpublic override LuaValue Eval( Frame f )\n\t{\n\t\tvar a = A.Eval( f );\n\t\tswitch ( Op )\n\t\t{\n\t\t\tcase UnOp.Not: return LuaValue.FromBool( !a.IsTruthy );\n\t\t\tcase UnOp.Neg:\n\t\t\t\tif ( a.Type == LuaType.Number ) return LuaValue.FromNumber( -a.Number );\n\t\t\t\tf.Line = Line;\n\t\t\t\treturn f.State.Unm( a );\n\t\t\tdefault:\n\t\t\t\tf.Line = Line;\n\t\t\t\tif ( a.Type == LuaType.String ) return LuaValue.FromNumber( a.AsString.Length );\n\t\t\t\treturn f.State.Len( a, A.Describe() );\n\t\t}\n\t}\n}\n\ninternal sealed class TableExpr : Expr\n{\n\tpublic Expr[] Positional = Array.Empty\u003CExpr\u003E();\n\tpublic Expr[] Keys = Array.Empty\u003CExpr\u003E();\n\tpublic Expr[] Values = Array.Empty\u003CExpr\u003E();\n\t// Order of evaluation: entries are evaluated in source order.\n\tpublic (bool positional, int index)[] Order = Array.Empty\u003C(bool, int)\u003E();\n\n\tpublic override LuaValue Eval( Frame f )\n\t{\n\t\tvar t = new LuaTable( Positional.Length, Keys.Length );\n\t\tint n = 1;\n\t\tfor ( int o = 0; o \u003C Order.Length; o\u002B\u002B )\n\t\t{\n\t\t\tvar (positional, index) = Order[o];\n\t\t\tif ( positional )\n\t\t\t{\n\t\t\t\tvar e = Positional[index];\n\t\t\t\t// Only the very last field of the constructor expands multiple results.\n\t\t\t\tif ( o == Order.Length - 1 \u0026\u0026 e.IsMulti )\n\t\t\t\t{\n\t\t\t\t\tforeach ( var v in e.EvalMulti( f ) ) t.Set( LuaValue.FromNumber( n\u002B\u002B ), v );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tt.Set( LuaValue.FromNumber( n\u002B\u002B ), e.Eval( f ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tvar k = Keys[index].Eval( f );\n\t\t\t\tvar v = Values[index].Eval( f );\n\t\t\t\tf.Line = Keys[index].Line;\n\t\t\t\tif ( k.IsNil ) throw new LuaRuntimeException( \u0022table index is nil\u0022 );\n\t\t\t\tt.Set( k, v );\n\t\t\t}\n\t\t}\n\t\treturn LuaValue.FromTable( t );\n\t}\n}\n\n// ---------------------------------------------------------------- statements\n\ninternal abstract class Stmt\n{\n\tpublic int Line;\n\tpublic abstract ExecResult Exec( Frame f );\n}\n\ninternal sealed class Block\n{\n\tpublic Stmt[] Statements;\n\n\tpublic ExecResult Exec( Frame f )\n\t{\n\t\tvar stmts = Statements;\n\t\tvar state = f.State;\n\t\tfor ( int i = 0; i \u003C stmts.Length; i\u002B\u002B )\n\t\t{\n\t\t\tvar s = stmts[i];\n\t\t\tf.Line = s.Line;\n\t\t\tstate.Step();\n\t\t\tvar r = s.Exec( f );\n\t\t\tif ( r != ExecResult.Normal ) return r;\n\t\t}\n\t\treturn ExecResult.Normal;\n\t}\n}\n\ninternal sealed class LocalStmt : Stmt\n{\n\tpublic int[] Slots;\n\tpublic Expr[] Exprs;\n\n\tpublic override ExecResult Exec( Frame f )\n\t{\n\t\tif ( Slots.Length == 1 \u0026\u0026 Exprs.Length == 1 )\n\t\t{\n\t\t\tf.Slots[Slots[0]] = new Cell( Exprs[0].Eval( f ) );\n\t\t\treturn ExecResult.Normal;\n\t\t}\n\n\t\tvar values = Expr.EvalList( f, Exprs );\n\t\tfor ( int i = 0; i \u003C Slots.Length; i\u002B\u002B )\n\t\t\tf.Slots[Slots[i]] = new Cell( i \u003C values.Length ? values[i] : LuaValue.Nil );\n\t\treturn ExecResult.Normal;\n\t}\n}\n\ninternal sealed class AssignStmt : Stmt\n{\n\tpublic Expr[] Targets;\n\tpublic Expr[] Exprs;\n\n\tpublic override ExecResult Exec( Frame f )\n\t{\n\t\tif ( Targets.Length == 1 \u0026\u0026 Exprs.Length == 1 )\n\t\t{\n\t\t\tvar target = (IAssignable)Targets[0];\n\t\t\tif ( target is IndexExpr ie )\n\t\t\t{\n\t\t\t\tvar o = ie.Obj.Eval( f );\n\t\t\t\tvar k = ie.Key.Eval( f );\n\t\t\t\tvar v = Exprs[0].Eval( f );\n\t\t\t\tie.AssignTo( f, o, k, v );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttarget.Assign( f, null, Exprs[0].Eval( f ) );\n\t\t\t}\n\t\t\treturn ExecResult.Normal;\n\t\t}\n\n\t\tvar prepared = new object[Targets.Length];\n\t\tfor ( int i = 0; i \u003C Targets.Length; i\u002B\u002B ) prepared[i] = ((IAssignable)Targets[i]).Prepare( f );\n\t\tvar values = Expr.EvalList( f, Exprs );\n\t\tfor ( int i = 0; i \u003C Targets.Length; i\u002B\u002B )\n\t\t\t((IAssignable)Targets[i]).Assign( f, prepared[i], i \u003C values.Length ? values[i] : LuaValue.Nil );\n\t\treturn ExecResult.Normal;\n\t}\n}\n\ninternal sealed class CallStmt : Stmt\n{\n\tpublic Expr Call;\n\tpublic override ExecResult Exec( Frame f )\n\t{\n\t\tCall.EvalMulti( f );\n\t\treturn ExecResult.Normal;\n\t}\n}\n\ninternal sealed class DoStmt : Stmt\n{\n\tpublic Block Body;\n\tpublic override ExecResult Exec( Frame f ) =\u003E Body.Exec( f );\n}\n\ninternal sealed class WhileStmt : Stmt\n{\n\tpublic Expr Cond;\n\tpublic Block Body;\n\n\tpublic override ExecResult Exec( Frame f )\n\t{\n\t\tvar state = f.State;\n\t\twhile ( Cond.Eval( f ).IsTruthy )\n\t\t{\n\t\t\tstate.Step();\n\t\t\tvar r = Body.Exec( f );\n\t\t\tif ( r == ExecResult.Break ) break;\n\t\t\tif ( r == ExecResult.Return ) return r;\n\t\t}\n\t\treturn ExecResult.Normal;\n\t}\n}\n\ninternal sealed class RepeatStmt : Stmt\n{\n\tpublic Block Body;\n\tpublic Expr Cond;\n\n\tpublic override ExecResult Exec( Frame f )\n\t{\n\t\tvar state = f.State;\n\t\twhile ( true )\n\t\t{\n\t\t\tstate.Step();\n\t\t\tvar r = Body.Exec( f );\n\t\t\tif ( r == ExecResult.Break ) break;\n\t\t\tif ( r == ExecResult.Return ) return r;\n\t\t\tif ( Cond.Eval( f ).IsTruthy ) break;\n\t\t}\n\t\treturn ExecResult.Normal;\n\t}\n}\n\ninternal sealed class IfStmt : Stmt\n{\n\tpublic Expr[] Conds;\n\tpublic Block[] Blocks;\n\tpublic Block Else;\n\n\tpublic override ExecResult Exec( Frame f )\n\t{\n\t\tfor ( int i = 0; i \u003C Conds.Length; i\u002B\u002B )\n\t\t{\n\t\t\tif ( Conds[i].Eval( f ).IsTruthy ) return Blocks[i].Exec( f );\n\t\t}\n\t\treturn Else is null ? ExecResult.Normal : Else.Exec( f );\n\t}\n}\n\ninternal sealed class NumericForStmt : Stmt\n{\n\tpublic int Slot;\n\tpublic Expr Start, Limit, Step;\n\tpublic Block Body;\n\n\tpublic override ExecResult Exec( Frame f )\n\t{\n\t\tvar state = f.State;\n\t\tdouble start = ForNumber( f, Start.Eval( f ), \u0022initial\u0022 );\n\t\tdouble limit = ForNumber( f, Limit.Eval( f ), \u0022limit\u0022 );\n\t\tdouble step = Step is null ? 1 : ForNumber( f, Step.Eval( f ), \u0022step\u0022 );\n\n\t\tfor ( double i = start; step \u003E 0 ? i \u003C= limit : i \u003E= limit; i \u002B= step )\n\t\t{\n\t\t\tstate.Step();\n\t\t\tf.Slots[Slot] = new Cell( LuaValue.FromNumber( i ) );\n\t\t\tvar r = Body.Exec( f );\n\t\t\tif ( r == ExecResult.Break ) break;\n\t\t\tif ( r == ExecResult.Return ) return r;\n\t\t}\n\t\treturn ExecResult.Normal;\n\t}\n\n\tdouble ForNumber( Frame f, LuaValue v, string what )\n\t{\n\t\tif ( v.Type == LuaType.Number ) return v.Number;\n\t\tif ( v.Type == LuaType.String \u0026\u0026 LuaValue.TryParseNumber( v.AsString, out var d ) ) return d;\n\t\tf.Line = Line;\n\t\tthrow new LuaRuntimeException( $\u0022\u0027for\u0027 {what} value must be a number\u0022 );\n\t}\n}\n\ninternal sealed class GenericForStmt : Stmt\n{\n\tpublic int[] Slots;\n\tpublic Expr[] Exprs;\n\tpublic Block Body;\n\n\tpublic override ExecResult Exec( Frame f )\n\t{\n\t\tvar state = f.State;\n\t\tvar init = Expr.EvalList( f, Exprs );\n\t\tvar fn = init.Length \u003E 0 ? init[0] : LuaValue.Nil;\n\t\tvar s = init.Length \u003E 1 ? init[1] : LuaValue.Nil;\n\t\tvar control = init.Length \u003E 2 ? init[2] : LuaValue.Nil;\n\n\t\t// Fast path for pairs()/next over a plain table.\n\t\tbool isNext = fn.Obj is LuaFunction lf \u0026\u0026 ReferenceEquals( lf, state.NextFunction ) \u0026\u0026 s.Type == LuaType.Table;\n\t\tvar callArgs = new LuaValue[2];\n\n\t\twhile ( true )\n\t\t{\n\t\t\tstate.Step();\n\t\t\tLuaValue k, v = LuaValue.Nil;\n\t\t\tLuaValue[] results = null;\n\n\t\t\tif ( isNext )\n\t\t\t{\n\t\t\t\tf.Line = Line;\n\t\t\t\tif ( !((LuaTable)s.Obj).Next( control, out k, out v ) ) break;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcallArgs = new[] { s, control };\n\t\t\t\tf.Line = Line;\n\t\t\t\tif ( fn.Type != LuaType.Function \u0026\u0026 state.GetMetamethod( fn, \u0022__call\u0022 ).IsNil )\n\t\t\t\t\tthrow new LuaRuntimeException( $\u0022attempt to call a {fn.TypeName} value\u0022 );\n\t\t\t\tresults = state.Call( fn, callArgs );\n\t\t\t\tk = results.Length \u003E 0 ? results[0] : LuaValue.Nil;\n\t\t\t\tif ( k.IsNil ) break;\n\t\t\t}\n\n\t\t\tcontrol = k;\n\t\t\tfor ( int i = 0; i \u003C Slots.Length; i\u002B\u002B )\n\t\t\t{\n\t\t\t\tLuaValue val;\n\t\t\t\tif ( results is null ) val = i == 0 ? k : i == 1 ? v : LuaValue.Nil;\n\t\t\t\telse val = i \u003C results.Length ? results[i] : LuaValue.Nil;\n\t\t\t\tf.Slots[Slots[i]] = new Cell( val );\n\t\t\t}\n\n\t\t\tvar r = Body.Exec( f );\n\t\t\tif ( r == ExecResult.Break ) break;\n\t\t\tif ( r == ExecResult.Return ) return r;\n\t\t}\n\t\treturn ExecResult.Normal;\n\t}\n}\n\ninternal sealed class LocalFunctionStmt : Stmt\n{\n\tpublic int Slot;\n\tpublic FunctionExpr Func;\n\n\tpublic override ExecResult Exec( Frame f )\n\t{\n\t\tvar cell = new Cell();\n\t\tf.Slots[Slot] = cell;\n\t\tcell.Value = Func.Eval( f );\n\t\treturn ExecResult.Normal;\n\t}\n}\n\ninternal sealed class ReturnStmt : Stmt\n{\n\tpublic Expr[] Exprs;\n\tpublic override ExecResult Exec( Frame f )\n\t{\n\t\tf.Returns = Expr.EvalList( f, Exprs );\n\t\treturn ExecResult.Return;\n\t}\n}\n\ninternal sealed class BreakStmt : Stmt\n{\n\tpublic override ExecResult Exec( Frame f ) =\u003E ExecResult.Break;\n}\n\ninternal sealed class ContinueStmt : Stmt\n{\n\tpublic override ExecResult Exec( Frame f ) =\u003E ExecResult.Continue;\n}\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Lua/Runtime/LuaState.cs","FileName":"LuaState.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing RoleplayFramework.Lua.Compiler;\n\nnamespace RoleplayFramework.Lua;\n\n/// \u003Csummary\u003E\n/// One isolated Lua environment (one per realm). Not thread-safe; use from the main thread.\n/// Scripts can only reach what is placed in \u003Csee cref=\u0022Globals\u0022/\u003E: there is no io, os.execute,\n/// debug, package, load/loadstring/dofile or reflection unless the host registers it.\n/// \u003C/summary\u003E\npublic sealed partial class LuaState\n{\n\tpublic const string RuntimeName = \u0022RpLua\u0022;\n\tpublic const string RuntimeVersion = \u00220.1.0\u0022;\n\tpublic const string LanguageVersion = \u0022Lua 5.1\u0022;\n\n\t/// \u003Csummary\u003EMaximum nested Lua/host calls before \u0022stack overflow\u0022.\u003C/summary\u003E\n\t/// \u003Cremarks\u003E\n\t/// The interpreter recurses on the host (.NET) stack and s\u0026amp;box does not whitelist any stack-headroom\n\t/// check, so this limit is what keeps a runaway recursion from killing the process. Measured cost is\n\t/// ~1.7 KB (Release) to ~3 KB (Debug) of native stack per Lua call level; 100 levels stays well under 1 MB.\n\t/// \u003C/remarks\u003E\n\tpublic int MaxCallDepth { get; set; } = 100;\n\n\t/// \u003Csummary\u003E\n\t/// Max statements/loop iterations per top-level host call (0 = unlimited).\n\t/// Exceeding it throws \u003Csee cref=\u0022LuaBudgetExceededException\u0022/\u003E, which pcall cannot catch.\n\t/// \u003C/summary\u003E\n\tpublic long InstructionBudget { get; set; } = 5_000_000;\n\n\tpublic LuaTable Globals { get; }\n\tpublic LuaTable StringMetatable { get; }\n\n\t/// \u003Csummary\u003ELabel used in diagnostics, e.g. \u0022server\u0022, \u0022client\u0022, \u0022shared\u0022.\u003C/summary\u003E\n\tpublic string Name { get; }\n\n\t/// \u003Csummary\u003EReceives output of Lua\u0027s print().\u003C/summary\u003E\n\tpublic Action\u003Cstring\u003E PrintHandler { get; set; }\n\n\tinternal LuaFunction NextFunction { get; private set; }\n\n\treadonly List\u003CFrame\u003E _frames = new();\n\tint _callDepth;\n\tlong _steps;\n\n\tpublic LuaState( string name = \u0022lua\u0022 )\n\t{\n\t\tName = name;\n\t\tGlobals = new LuaTable();\n\t\tStringMetatable = new LuaTable();\n\t\tOpenStandardLibraries();\n\t}\n\n\t// ------------------------------------------------------------ loading / running\n\n\t/// \u003Csummary\u003ECompiles source into a function. Throws \u003Csee cref=\u0022LuaSyntaxException\u0022/\u003E.\u003C/summary\u003E\n\tpublic LuaClosure Load( string source, string chunkName, LuaTable env = null )\n\t{\n\t\tvar proto = Parser.ParseChunk( source, chunkName );\n\t\treturn new LuaClosure( proto, Array.Empty\u003CCell\u003E(), env ?? Globals );\n\t}\n\n\t/// \u003Csummary\u003ECompiles and runs source, returning its results.\u003C/summary\u003E\n\tpublic LuaValue[] DoString( string source, string chunkName, LuaTable env = null )\n\t{\n\t\tvar fn = Load( source, chunkName, env );\n\t\treturn Call( LuaValue.FromFunction( fn ) );\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Calls a Lua value. When called from the host (not from inside Lua), the instruction\n\t/// budget is reset for this call.\n\t/// \u003C/summary\u003E\n\tpublic LuaValue[] Call( LuaValue fn, params LuaValue[] args )\n\t{\n\t\targs ??= LuaValue.EmptyArray;\n\n\t\tif ( _frames.Count == 0 ) _steps = 0;\n\n\t\tif ( fn.Type == LuaType.Function )\n\t\t{\n\t\t\tif ( fn.Obj is LuaClosure lc ) return CallClosure( lc, args );\n\t\t\treturn CallNative( (LuaNativeClosure)fn.Obj, args );\n\t\t}\n\n\t\tvar mm = GetMetamethod( fn, \u0022__call\u0022 );\n\t\tif ( mm.IsNil ) throw new LuaRuntimeException( $\u0022attempt to call a {fn.TypeName} value\u0022 );\n\n\t\tvar full = new LuaValue[args.Length \u002B 1];\n\t\tfull[0] = fn;\n\t\targs.CopyTo( full, 1 );\n\t\treturn Call( mm, full );\n\t}\n\n\tLuaValue[] CallClosure( LuaClosure c, LuaValue[] args )\n\t{\n\t\tvar p = c.Proto;\n\t\tif ( _callDepth \u003E= MaxCallDepth ) throw new LuaRuntimeException( \u0022stack overflow\u0022 );\n\n\t\tvar f = new Frame { Slots = new Cell[p.SlotCount], Closure = c, State = this, Line = p.Line };\n\t\tfor ( int i = 0; i \u003C p.ParamCount; i\u002B\u002B )\n\t\t\tf.Slots[i] = new Cell( i \u003C args.Length ? args[i] : LuaValue.Nil );\n\n\t\tif ( p.IsVararg )\n\t\t{\n\t\t\tif ( args.Length \u003E p.ParamCount )\n\t\t\t{\n\t\t\t\tvar va = new LuaValue[args.Length - p.ParamCount];\n\t\t\t\tArray.Copy( args, p.ParamCount, va, 0, va.Length );\n\t\t\t\tf.Varargs = va;\n\t\t\t}\n\t\t\telse f.Varargs = LuaValue.EmptyArray;\n\t\t}\n\n\t\t_callDepth\u002B\u002B;\n\t\t_frames.Add( f );\n\t\ttry\n\t\t{\n\t\t\tvar r = p.Body.Exec( f );\n\t\t\treturn r == ExecResult.Return ? f.Returns : LuaValue.EmptyArray;\n\t\t}\n\t\t// An exception filter runs during the first (search) pass while this frame is still live,\n\t\t// so the innermost Lua frame can stamp position \u002B traceback without catching. Catching and\n\t\t// rethrowing at every level would grow the native stack quadratically during unwinding.\n\t\tcatch ( LuaRuntimeException ex ) when ( AnnotateError( ex, f ) )\n\t\t{\n\t\t\tthrow;\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\t_frames.RemoveAt( _frames.Count - 1 );\n\t\t\t_callDepth--;\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003EAlways returns false (never catches); only decorates the error on its first sighting.\u003C/summary\u003E\n\tbool AnnotateError( LuaRuntimeException ex, Frame f )\n\t{\n\t\tif ( !ex.PositionApplied )\n\t\t{\n\t\t\tex.PositionApplied = true;\n\t\t\tif ( ex.Value.IsString ) ex.Value = LuaValue.FromString( $\u0022{f.Closure.ChunkName}:{f.Line}: {ex.Value.AsString}\u0022 );\n\t\t}\n\t\tex.LuaTraceback ??= BuildTraceback();\n\t\treturn false;\n\t}\n\n\tLuaValue[] CallNative( LuaNativeClosure fn, LuaValue[] args )\n\t{\n\t\tif ( _callDepth \u003E= MaxCallDepth ) throw new LuaRuntimeException( \u0022stack overflow\u0022 );\n\t\t_callDepth\u002B\u002B;\n\t\ttry\n\t\t{\n\t\t\treturn fn.Body( this, args ) ?? LuaValue.EmptyArray;\n\t\t}\n\t\tcatch ( Exception e ) when ( e is not LuaException )\n\t\t{\n\t\t\t// A host bug must not take down the realm; surface it as a Lua error instead.\n\t\t\tthrow new LuaRuntimeException( $\u0022internal error in \u0027{fn.Name}\u0027: {e.Message}\u0022 );\n\t\t}\n\t\tfinally { _callDepth--; }\n\t}\n\n\t/// \u003Csummary\u003EInstruction budget tick. Called per statement and per loop iteration.\u003C/summary\u003E\n\tinternal void Step()\n\t{\n\t\tif ( \u002B\u002B_steps \u003E InstructionBudget \u0026\u0026 InstructionBudget \u003E 0 )\n\t\t{\n\t\t\tvar where = _frames.Count \u003E 0 ? $\u0022{_frames[^1].Closure.ChunkName}:{_frames[^1].Line}: \u0022 : \u0022\u0022;\n\t\t\tthrow new LuaBudgetExceededException( $\u0022{where}script exceeded its instruction budget ({InstructionBudget:N0}); possible infinite loop\u0022 );\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003EAdds host-side step cost (e.g. for pattern matching work).\u003C/summary\u003E\n\tinternal void AddSteps( long n )\n\t{\n\t\t_steps \u002B= n - 1;\n\t\tStep();\n\t}\n\n\t// ------------------------------------------------------------ error helpers\n\n\t/// \u003Csummary\u003E\u0022chunk:line:\u0022 of the Lua function at \u003Cparamref name=\u0022level\u0022/\u003E (1 = innermost Lua function).\u003C/summary\u003E\n\tpublic string Where( int level )\n\t{\n\t\tint idx = _frames.Count - level;\n\t\tif ( level \u003C 1 || idx \u003C 0 ) return \u0022\u0022;\n\t\tvar f = _frames[idx];\n\t\treturn $\u0022{f.Closure.ChunkName}:{f.Line}: \u0022;\n\t}\n\n\tpublic string BuildTraceback()\n\t{\n\t\tvar sb = new StringBuilder( \u0022stack traceback:\u0022 );\n\t\tint shown = 0;\n\t\tfor ( int i = _frames.Count - 1; i \u003E= 0; i-- )\n\t\t{\n\t\t\tif ( shown\u002B\u002B \u003E= 20 ) { sb.Append( \u0022\\n\\t...\u0022 ); break; }\n\t\t\tvar f = _frames[i];\n\t\t\tvar p = f.Closure.Proto;\n\t\t\tvar what = p.Name == \u0022main chunk\u0022 ? \u0022main chunk\u0022 : $\u0022function \u0027{p.Name}\u0027\u0022;\n\t\t\tsb.Append( $\u0022\\n\\t{p.ChunkName}:{f.Line}: in {what}\u0022 );\n\t\t}\n\t\treturn sb.ToString();\n\t}\n\n\t// ------------------------------------------------------------ metatables\n\n\tpublic LuaTable GetMetatable( LuaValue v ) =\u003E v.Type switch\n\t{\n\t\tLuaType.Table =\u003E ((LuaTable)v.Obj).Metatable,\n\t\tLuaType.String =\u003E StringMetatable,\n\t\tLuaType.UserData =\u003E ((LuaUserData)v.Obj).Metatable,\n\t\t_ =\u003E null,\n\t};\n\n\tpublic LuaValue GetMetamethod( LuaValue v, string name )\n\t{\n\t\tvar mt = GetMetatable( v );\n\t\treturn mt is null ? LuaValue.Nil : mt.Get( name );\n\t}\n\n\t// ------------------------------------------------------------ indexing\n\n\tpublic LuaValue Index( LuaValue obj, LuaValue key )\n\t{\n\t\tfor ( int loop = 0; loop \u003C 100; loop\u002B\u002B )\n\t\t{\n\t\t\tLuaValue handler;\n\t\t\tif ( obj.Type == LuaType.Table )\n\t\t\t{\n\t\t\t\tvar t = (LuaTable)obj.Obj;\n\t\t\t\tvar v = t.Get( key );\n\t\t\t\tif ( !v.IsNil ) return v;\n\t\t\t\tif ( t.Metatable is null ) return LuaValue.Nil;\n\t\t\t\thandler = t.Metatable.Get( \u0022__index\u0022 );\n\t\t\t\tif ( handler.IsNil ) return LuaValue.Nil;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\thandler = GetMetamethod( obj, \u0022__index\u0022 );\n\t\t\t\tif ( handler.IsNil ) throw new LuaRuntimeException( $\u0022attempt to index a {obj.TypeName} value\u0022 );\n\t\t\t}\n\n\t\t\tif ( handler.Type == LuaType.Function )\n\t\t\t{\n\t\t\t\tvar r = Call( handler, obj, key );\n\t\t\t\treturn r.Length \u003E 0 ? r[0] : LuaValue.Nil;\n\t\t\t}\n\t\t\tobj = handler;\n\t\t}\n\t\tthrow new LuaRuntimeException( \u0022loop in gettable\u0022 );\n\t}\n\n\tpublic void SetIndex( LuaValue obj, LuaValue key, LuaValue value )\n\t{\n\t\tfor ( int loop = 0; loop \u003C 100; loop\u002B\u002B )\n\t\t{\n\t\t\tLuaValue handler;\n\t\t\tif ( obj.Type == LuaType.Table )\n\t\t\t{\n\t\t\t\tvar t = (LuaTable)obj.Obj;\n\t\t\t\tif ( t.Metatable is null || !t.Get( key ).IsNil ) { t.Set( key, value ); return; }\n\t\t\t\thandler = t.Metatable.Get( \u0022__newindex\u0022 );\n\t\t\t\tif ( handler.IsNil ) { t.Set( key, value ); return; }\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\thandler = GetMetamethod( obj, \u0022__newindex\u0022 );\n\t\t\t\tif ( handler.IsNil ) throw new LuaRuntimeException( $\u0022attempt to index a {obj.TypeName} value\u0022 );\n\t\t\t}\n\n\t\t\tif ( handler.Type == LuaType.Function )\n\t\t\t{\n\t\t\t\tCall( handler, obj, key, value );\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tobj = handler;\n\t\t}\n\t\tthrow new LuaRuntimeException( \u0022loop in settable\u0022 );\n\t}\n\n\t// ------------------------------------------------------------ arithmetic \u0026 comparison\n\n\tinternal static double Mod( double a, double b ) =\u003E a - Math.Floor( a / b ) * b;\n\n\tpublic static bool ToNumber( LuaValue v, out double d )\n\t{\n\t\tif ( v.Type == LuaType.Number ) { d = v.Number; return true; }\n\t\tif ( v.Type == LuaType.String ) return LuaValue.TryParseNumber( v.AsString, out d );\n\t\td = 0;\n\t\treturn false;\n\t}\n\n\tstatic string EventName( BinOp op ) =\u003E op switch\n\t{\n\t\tBinOp.Add =\u003E \u0022__add\u0022, BinOp.Sub =\u003E \u0022__sub\u0022, BinOp.Mul =\u003E \u0022__mul\u0022, BinOp.Div =\u003E \u0022__div\u0022,\n\t\tBinOp.Mod =\u003E \u0022__mod\u0022, BinOp.Pow =\u003E \u0022__pow\u0022, _ =\u003E \u0022__concat\u0022,\n\t};\n\n\tinternal LuaValue Arith( BinOp op, LuaValue a, LuaValue b )\n\t{\n\t\tif ( ToNumber( a, out var x ) \u0026\u0026 ToNumber( b, out var y ) )\n\t\t{\n\t\t\treturn LuaValue.FromNumber( op switch\n\t\t\t{\n\t\t\t\tBinOp.Add =\u003E x \u002B y,\n\t\t\t\tBinOp.Sub =\u003E x - y,\n\t\t\t\tBinOp.Mul =\u003E x * y,\n\t\t\t\tBinOp.Div =\u003E x / y,\n\t\t\t\tBinOp.Mod =\u003E Mod( x, y ),\n\t\t\t\t_ =\u003E Math.Pow( x, y ),\n\t\t\t} );\n\t\t}\n\n\t\tvar ev = EventName( op );\n\t\tvar mm = GetMetamethod( a, ev );\n\t\tif ( mm.IsNil ) mm = GetMetamethod( b, ev );\n\t\tif ( mm.IsNil )\n\t\t{\n\t\t\tvar bad = ToNumber( a, out _ ) ? b : a;\n\t\t\tthrow new LuaRuntimeException( $\u0022attempt to perform arithmetic on a {bad.TypeName} value\u0022 );\n\t\t}\n\t\tvar r = Call( mm, a, b );\n\t\treturn r.Length \u003E 0 ? r[0] : LuaValue.Nil;\n\t}\n\n\tinternal LuaValue Unm( LuaValue a )\n\t{\n\t\tif ( ToNumber( a, out var x ) ) return LuaValue.FromNumber( -x );\n\t\tvar mm = GetMetamethod( a, \u0022__unm\u0022 );\n\t\tif ( mm.IsNil ) throw new LuaRuntimeException( $\u0022attempt to perform arithmetic on a {a.TypeName} value\u0022 );\n\t\tvar r = Call( mm, a, a );\n\t\treturn r.Length \u003E 0 ? r[0] : LuaValue.Nil;\n\t}\n\n\tinternal LuaValue Len( LuaValue a, string describe = null )\n\t{\n\t\tif ( a.Type == LuaType.String ) return LuaValue.FromNumber( a.AsString.Length );\n\t\tvar mm = GetMetamethod( a, \u0022__len\u0022 );\n\t\tif ( !mm.IsNil )\n\t\t{\n\t\t\tvar r = Call( mm, a );\n\t\t\treturn r.Length \u003E 0 ? r[0] : LuaValue.Nil;\n\t\t}\n\t\tif ( a.Type == LuaType.Table ) return LuaValue.FromNumber( ((LuaTable)a.Obj).Length );\n\t\tthrow new LuaRuntimeException( describe is null ? $\u0022attempt to get length of a {a.TypeName} value\u0022 : $\u0022attempt to get length of {describe} (a {a.TypeName} value)\u0022 );\n\t}\n\n\tinternal LuaValue Concat( LuaValue a, LuaValue b )\n\t{\n\t\tif ( (a.Type == LuaType.String || a.Type == LuaType.Number) \u0026\u0026 (b.Type == LuaType.String || b.Type == LuaType.Number) )\n\t\t\treturn LuaValue.FromString( string.Concat( a.ToString(), b.ToString() ) );\n\n\t\tvar mm = GetMetamethod( a, \u0022__concat\u0022 );\n\t\tif ( mm.IsNil ) mm = GetMetamethod( b, \u0022__concat\u0022 );\n\t\tif ( mm.IsNil )\n\t\t{\n\t\t\tvar bad = a.Type == LuaType.String || a.Type == LuaType.Number ? b : a;\n\t\t\tthrow new LuaRuntimeException( $\u0022attempt to concatenate a {bad.TypeName} value\u0022 );\n\t\t}\n\t\tvar r = Call( mm, a, b );\n\t\treturn r.Length \u003E 0 ? r[0] : LuaValue.Nil;\n\t}\n\n\tpublic bool ValuesEqual( LuaValue a, LuaValue b )\n\t{\n\t\tif ( a.Type != b.Type ) return false;\n\t\tif ( a.Equals( b ) ) return true;\n\t\tif ( a.Type != LuaType.Table \u0026\u0026 a.Type != LuaType.UserData ) return false;\n\n\t\tvar mm1 = GetMetamethod( a, \u0022__eq\u0022 );\n\t\tvar mm2 = GetMetamethod( b, \u0022__eq\u0022 );\n\t\tif ( mm1.IsNil || !mm1.Equals( mm2 ) ) return false;\n\t\tvar r = Call( mm1, a, b );\n\t\treturn r.Length \u003E 0 \u0026\u0026 r[0].IsTruthy;\n\t}\n\n\tpublic bool LessThan( LuaValue a, LuaValue b )\n\t{\n\t\tif ( a.Type == LuaType.Number \u0026\u0026 b.Type == LuaType.Number ) return a.Number \u003C b.Number;\n\t\tif ( a.Type == LuaType.String \u0026\u0026 b.Type == LuaType.String ) return string.CompareOrdinal( a.AsString, b.AsString ) \u003C 0;\n\t\treturn CompareMeta( a, b, \u0022__lt\u0022 );\n\t}\n\n\tpublic bool LessEqual( LuaValue a, LuaValue b )\n\t{\n\t\tif ( a.Type == LuaType.Number \u0026\u0026 b.Type == LuaType.Number ) return a.Number \u003C= b.Number;\n\t\tif ( a.Type == LuaType.String \u0026\u0026 b.Type == LuaType.String ) return string.CompareOrdinal( a.AsString, b.AsString ) \u003C= 0;\n\n\t\tif ( a.Type == b.Type \u0026\u0026 !GetMetamethod( a, \u0022__le\u0022 ).IsNil ) return CompareMeta( a, b, \u0022__le\u0022 );\n\t\t// Lua 5.1 fallback: a \u003C= b  ==  not (b \u003C a)\n\t\treturn !CompareMeta( b, a, \u0022__lt\u0022 );\n\t}\n\n\tbool CompareMeta( LuaValue a, LuaValue b, string ev )\n\t{\n\t\tif ( a.Type == b.Type )\n\t\t{\n\t\t\tvar mm1 = GetMetamethod( a, ev );\n\t\t\tvar mm2 = GetMetamethod( b, ev );\n\t\t\tif ( !mm1.IsNil \u0026\u0026 mm1.Equals( mm2 ) )\n\t\t\t{\n\t\t\t\tvar r = Call( mm1, a, b );\n\t\t\t\treturn r.Length \u003E 0 \u0026\u0026 r[0].IsTruthy;\n\t\t\t}\n\t\t}\n\n\t\tif ( a.Type == b.Type )\n\t\t\tthrow new LuaRuntimeException( $\u0022attempt to compare two {a.TypeName} values\u0022 );\n\t\tthrow new LuaRuntimeException( $\u0022attempt to compare {a.TypeName} with {b.TypeName}\u0022 );\n\t}\n\n\t/// \u003Csummary\u003Etostring() semantics including __tostring.\u003C/summary\u003E\n\tpublic string ToStringMeta( LuaValue v )\n\t{\n\t\tvar mm = GetMetamethod( v, \u0022__tostring\u0022 );\n\t\tif ( !mm.IsNil )\n\t\t{\n\t\t\tvar r = Call( mm, v );\n\t\t\tvar s = r.Length \u003E 0 ? r[0] : LuaValue.Nil;\n\t\t\tif ( s.Type != LuaType.String \u0026\u0026 s.Type != LuaType.Number )\n\t\t\t\tthrow new LuaRuntimeException( \u0022\u0027__tostring\u0027 must return a string\u0022 );\n\t\t\treturn s.ToString();\n\t\t}\n\t\treturn v.ToString();\n\t}\n\n\t// ------------------------------------------------------------ host registration helpers\n\n\tpublic LuaNativeClosure Register( string name, LuaNativeFunction fn ) =\u003E Register( Globals, name, fn );\n\n\tpublic static LuaNativeClosure Register( LuaTable table, string name, LuaNativeFunction fn )\n\t{\n\t\tvar c = new LuaNativeClosure( name, fn );\n\t\ttable.Set( name, LuaValue.FromFunction( c ) );\n\t\treturn c;\n\t}\n\n\t/// \u003Csummary\u003EGets or creates a library table in globals, e.g. \u0022hook\u0022.\u003C/summary\u003E\n\tpublic LuaTable GetOrCreateLibrary( string name )\n\t{\n\t\tvar v = Globals.Get( name );\n\t\tif ( v.IsTable ) return v.AsTable;\n\t\tvar t = new LuaTable();\n\t\tGlobals.Set( name, t );\n\t\treturn t;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Protected host call: runs \u003Cparamref name=\u0022fn\u0022/\u003E and converts script failures into a result\n\t/// instead of an exception. Use this at every engine\u2192Lua boundary so one bad script can\u0027t crash the host.\n\t/// \u003C/summary\u003E\n\tpublic LuaCallResult PCall( LuaValue fn, params LuaValue[] args )\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn new LuaCallResult( true, Call( fn, args ), null, null );\n\t\t}\n\t\tcatch ( LuaRuntimeException e )\n\t\t{\n\t\t\treturn new LuaCallResult( false, LuaValue.EmptyArray, e.Message, e.LuaTraceback );\n\t\t}\n\t\tcatch ( LuaException e )\n\t\t{\n\t\t\treturn new LuaCallResult( false, LuaValue.EmptyArray, e.Message, BuildTraceback() );\n\t\t}\n\t}\n\n\tinternal static LuaValue[] One( LuaValue v ) =\u003E new[] { v };\n}\n\npublic readonly record struct LuaCallResult( bool Success, LuaValue[] Results, string Error, string Traceback );\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Lua/Runtime/LuaStdLib.cs","FileName":"LuaStdLib.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace RoleplayFramework.Lua;\n\n/// \u003Csummary\u003E\n/// Sandboxed subset of the Lua 5.1 standard library.\n/// Deliberately absent: io, os.execute/remove/rename/getenv/exit, debug, package, require,\n/// load, loadstring, loadfile, dofile, setfenv/getfenv, collectgarbage, newproxy, coroutine (not yet implemented).\n/// \u003C/summary\u003E\npublic sealed partial class LuaState\n{\n\tstatic readonly DateTime ClockStart = DateTime.UtcNow;\n\tRandom _random = new();\n\n\t// ------------------------------------------------------------ argument helpers\n\n\tpublic static LuaValue Arg( LuaValue[] args, int i ) =\u003E i \u003C args.Length ? args[i] : LuaValue.Nil;\n\n\tpublic static LuaRuntimeException ArgError( int argIndex, string fname, string msg ) =\u003E\n\t\tnew( $\u0022bad argument #{argIndex \u002B 1} to \u0027{fname}\u0027 ({msg})\u0022 );\n\n\tstatic string Expected( string type, LuaValue got ) =\u003E $\u0022{type} expected, got {(got.IsNil ? \u0022no value\u0022 : got.TypeName)}\u0022;\n\n\tpublic static double CheckNumber( LuaValue[] args, int i, string fname )\n\t{\n\t\tvar v = Arg( args, i );\n\t\tif ( ToNumber( v, out var d ) ) return d;\n\t\tthrow ArgError( i, fname, Expected( \u0022number\u0022, v ) );\n\t}\n\n\tpublic static int CheckInt( LuaValue[] args, int i, string fname )\n\t{\n\t\tvar d = CheckNumber( args, i, fname );\n\t\tif ( double.IsNaN( d ) ) throw ArgError( i, fname, \u0022number has no integer representation\u0022 );\n\t\treturn (int)Math.Clamp( Math.Floor( d ), int.MinValue, int.MaxValue );\n\t}\n\n\tpublic static double OptNumber( LuaValue[] args, int i, string fname, double def ) =\u003E\n\t\tArg( args, i ).IsNil ? def : CheckNumber( args, i, fname );\n\n\tpublic static int OptInt( LuaValue[] args, int i, string fname, int def ) =\u003E\n\t\tArg( args, i ).IsNil ? def : CheckInt( args, i, fname );\n\n\tpublic static string CheckString( LuaValue[] args, int i, string fname )\n\t{\n\t\tvar v = Arg( args, i );\n\t\tif ( v.Type == LuaType.String ) return v.AsString;\n\t\tif ( v.Type == LuaType.Number ) return v.ToString();\n\t\tthrow ArgError( i, fname, Expected( \u0022string\u0022, v ) );\n\t}\n\n\tpublic static string OptString( LuaValue[] args, int i, string fname, string def ) =\u003E\n\t\tArg( args, i ).IsNil ? def : CheckString( args, i, fname );\n\n\tpublic static LuaTable CheckTable( LuaValue[] args, int i, string fname )\n\t{\n\t\tvar v = Arg( args, i );\n\t\tif ( v.Type == LuaType.Table ) return v.AsTable;\n\t\tthrow ArgError( i, fname, Expected( \u0022table\u0022, v ) );\n\t}\n\n\tpublic static LuaValue CheckAny( LuaValue[] args, int i, string fname )\n\t{\n\t\tif ( i \u003C args.Length ) return args[i];\n\t\tthrow ArgError( i, fname, \u0022value expected\u0022 );\n\t}\n\n\tpublic static LuaFunction CheckFunction( LuaValue[] args, int i, string fname )\n\t{\n\t\tvar v = Arg( args, i );\n\t\tif ( v.Type == LuaType.Function ) return v.AsFunction;\n\t\tthrow ArgError( i, fname, Expected( \u0022function\u0022, v ) );\n\t}\n\n\tstatic LuaValue[] Ret( LuaValue v ) =\u003E new[] { v };\n\tstatic LuaValue[] Ret( LuaValue a, LuaValue b ) =\u003E new[] { a, b };\n\n\t// ------------------------------------------------------------ open\n\n\tvoid OpenStandardLibraries()\n\t{\n\t\tOpenBase();\n\t\tOpenString();\n\t\tOpenMath();\n\t\tOpenTable();\n\t\tOpenOs();\n\t}\n\n\tvoid OpenBase()\n\t{\n\t\tvar G = Globals;\n\t\tG.Set( \u0022_G\u0022, G );\n\t\tG.Set( \u0022_VERSION\u0022, LanguageVersion );\n\n\t\tRegister( G, \u0022print\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar sb = new StringBuilder();\n\t\t\tfor ( int i = 0; i \u003C a.Length; i\u002B\u002B )\n\t\t\t{\n\t\t\t\tif ( i \u003E 0 ) sb.Append( \u0027\\t\u0027 );\n\t\t\t\tsb.Append( L.ToStringMeta( a[i] ) );\n\t\t\t}\n\t\t\tL.PrintHandler?.Invoke( sb.ToString() );\n\t\t\treturn null;\n\t\t} );\n\n\t\tRegister( G, \u0022type\u0022, ( L, a ) =\u003E Ret( CheckAny( a, 0, \u0022type\u0022 ).TypeName ) );\n\n\t\tRegister( G, \u0022tostring\u0022, ( L, a ) =\u003E Ret( L.ToStringMeta( CheckAny( a, 0, \u0022tostring\u0022 ) ) ) );\n\n\t\tRegister( G, \u0022tonumber\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar v = CheckAny( a, 0, \u0022tonumber\u0022 );\n\t\t\tint b = OptInt( a, 1, \u0022tonumber\u0022, 10 );\n\t\t\tif ( b == 10 ) return Ret( ToNumber( v, out var d ) ? LuaValue.FromNumber( d ) : LuaValue.Nil );\n\t\t\tif ( b \u003C 2 || b \u003E 36 ) throw ArgError( 1, \u0022tonumber\u0022, \u0022base out of range\u0022 );\n\t\t\tvar s = CheckString( a, 0, \u0022tonumber\u0022 ).Trim().ToLowerInvariant();\n\t\t\tbool neg = s.StartsWith( \u0022-\u0022 );\n\t\t\tif ( neg ) s = s.Substring( 1 );\n\t\t\tif ( s.Length == 0 ) return Ret( LuaValue.Nil );\n\t\t\tdouble n = 0;\n\t\t\tforeach ( var c in s )\n\t\t\t{\n\t\t\t\tint digit = char.IsAsciiDigit( c ) ? c - \u00270\u0027 : char.IsAsciiLetter( c ) ? c - \u0027a\u0027 \u002B 10 : 99;\n\t\t\t\tif ( digit \u003E= b ) return Ret( LuaValue.Nil );\n\t\t\t\tn = n * b \u002B digit;\n\t\t\t}\n\t\t\treturn Ret( neg ? -n : n );\n\t\t} );\n\n\t\tNextFunction = Register( G, \u0022next\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar t = CheckTable( a, 0, \u0022next\u0022 );\n\t\t\treturn t.Next( Arg( a, 1 ), out var k, out var v ) ? Ret( k, v ) : Ret( LuaValue.Nil );\n\t\t} );\n\n\t\tvar nextValue = LuaValue.FromFunction( NextFunction );\n\t\tRegister( G, \u0022pairs\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar t = CheckTable( a, 0, \u0022pairs\u0022 );\n\t\t\treturn new[] { nextValue, LuaValue.FromTable( t ), LuaValue.Nil };\n\t\t} );\n\n\t\tvar ipairsIter = new LuaNativeClosure( \u0022ipairs_iter\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tdouble i = Arg( a, 1 ).Number \u002B 1;\n\t\t\tvar v = L.Index( a[0], LuaValue.FromNumber( i ) );\n\t\t\treturn v.IsNil ? Ret( LuaValue.Nil ) : Ret( i, v );\n\t\t} );\n\t\tRegister( G, \u0022ipairs\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar t = CheckAny( a, 0, \u0022ipairs\u0022 );\n\t\t\tif ( t.Type != LuaType.Table \u0026\u0026 L.GetMetamethod( t, \u0022__index\u0022 ).IsNil ) throw ArgError( 0, \u0022ipairs\u0022, Expected( \u0022table\u0022, t ) );\n\t\t\treturn new[] { LuaValue.FromFunction( ipairsIter ), t, LuaValue.FromNumber( 0 ) };\n\t\t} );\n\n\t\tRegister( G, \u0022select\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar n = Arg( a, 0 );\n\t\t\tif ( n.IsString \u0026\u0026 n.AsString == \u0022#\u0022 ) return Ret( a.Length - 1 );\n\t\t\tint i = CheckInt( a, 0, \u0022select\u0022 );\n\t\t\tif ( i \u003C 0 ) i = a.Length \u002B i;\n\t\t\telse if ( i == 0 ) throw ArgError( 0, \u0022select\u0022, \u0022index out of range\u0022 );\n\t\t\tif ( i \u003C 1 ) throw ArgError( 0, \u0022select\u0022, \u0022index out of range\u0022 );\n\t\t\tif ( i \u003E= a.Length ) return LuaValue.EmptyArray;\n\t\t\tvar r = new LuaValue[a.Length - i];\n\t\t\tArray.Copy( a, i, r, 0, r.Length );\n\t\t\treturn r;\n\t\t} );\n\n\t\tRegister( G, \u0022rawget\u0022, ( L, a ) =\u003E Ret( CheckTable( a, 0, \u0022rawget\u0022 ).Get( CheckAny( a, 1, \u0022rawget\u0022 ) ) ) );\n\t\tRegister( G, \u0022rawset\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar t = CheckTable( a, 0, \u0022rawset\u0022 );\n\t\t\tt.Set( CheckAny( a, 1, \u0022rawset\u0022 ), CheckAny( a, 2, \u0022rawset\u0022 ) );\n\t\t\treturn Ret( t );\n\t\t} );\n\t\tRegister( G, \u0022rawequal\u0022, ( L, a ) =\u003E Ret( CheckAny( a, 0, \u0022rawequal\u0022 ).Equals( CheckAny( a, 1, \u0022rawequal\u0022 ) ) ) );\n\t\tRegister( G, \u0022rawlen\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar v = Arg( a, 0 );\n\t\t\tif ( v.IsTable ) return Ret( v.AsTable.Length );\n\t\t\tif ( v.IsString ) return Ret( v.AsString.Length );\n\t\t\tthrow ArgError( 0, \u0022rawlen\u0022, \u0022table or string expected\u0022 );\n\t\t} );\n\n\t\tRegister( G, \u0022setmetatable\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar t = CheckTable( a, 0, \u0022setmetatable\u0022 );\n\t\t\tvar mt = Arg( a, 1 );\n\t\t\tif ( !mt.IsNil \u0026\u0026 !mt.IsTable ) throw ArgError( 1, \u0022setmetatable\u0022, \u0022nil or table expected\u0022 );\n\t\t\tif ( t.Metatable is not null \u0026\u0026 !t.Metatable.Get( \u0022__metatable\u0022 ).IsNil )\n\t\t\t\tthrow new LuaRuntimeException( \u0022cannot change a protected metatable\u0022 );\n\t\t\tt.Metatable = mt.AsTable;\n\t\t\treturn Ret( t );\n\t\t} );\n\n\t\tRegister( G, \u0022getmetatable\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar mt = L.GetMetatable( CheckAny( a, 0, \u0022getmetatable\u0022 ) );\n\t\t\tif ( mt is null ) return Ret( LuaValue.Nil );\n\t\t\tvar protectedField = mt.Get( \u0022__metatable\u0022 );\n\t\t\treturn Ret( protectedField.IsNil ? LuaValue.FromTable( mt ) : protectedField );\n\t\t} );\n\n\t\tRegister( G, \u0022assert\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tif ( a.Length \u003E 0 \u0026\u0026 a[0].IsTruthy ) return a;\n\t\t\tif ( a.Length \u003C 2 ) throw new LuaRuntimeException( a.Length == 0 ? \u0022bad argument #1 to \u0027assert\u0027 (value expected)\u0022 : \u0022assertion failed!\u0022 );\n\t\t\tthrow new LuaRuntimeException( a[1], true );\n\t\t} );\n\n\t\tRegister( G, \u0022error\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar v = Arg( a, 0 );\n\t\t\tint level = OptInt( a, 1, \u0022error\u0022, 1 );\n\t\t\tif ( v.IsString \u0026\u0026 level \u003E 0 )\n\t\t\t\tv = LuaValue.FromString( L.Where( level ) \u002B v.AsString );\n\t\t\tthrow new LuaRuntimeException( v, true );\n\t\t} );\n\n\t\tRegister( G, \u0022pcall\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar fn = CheckAny( a, 0, \u0022pcall\u0022 );\n\t\t\tvar rest = new LuaValue[Math.Max( 0, a.Length - 1 )];\n\t\t\tif ( rest.Length \u003E 0 ) Array.Copy( a, 1, rest, 0, rest.Length );\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar r = L.Call( fn, rest );\n\t\t\t\tvar full = new LuaValue[r.Length \u002B 1];\n\t\t\t\tfull[0] = LuaValue.True;\n\t\t\t\tr.CopyTo( full, 1 );\n\t\t\t\treturn full;\n\t\t\t}\n\t\t\tcatch ( LuaRuntimeException e )\n\t\t\t{\n\t\t\t\treturn Ret( LuaValue.False, e.Value );\n\t\t\t}\n\t\t} );\n\n\t\tRegister( G, \u0022xpcall\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar fn = CheckAny( a, 0, \u0022xpcall\u0022 );\n\t\t\tvar handler = CheckAny( a, 1, \u0022xpcall\u0022 );\n\t\t\tvar rest = new LuaValue[Math.Max( 0, a.Length - 2 )];\n\t\t\tif ( rest.Length \u003E 0 ) Array.Copy( a, 2, rest, 0, rest.Length );\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar r = L.Call( fn, rest );\n\t\t\t\tvar full = new LuaValue[r.Length \u002B 1];\n\t\t\t\tfull[0] = LuaValue.True;\n\t\t\t\tr.CopyTo( full, 1 );\n\t\t\t\treturn full;\n\t\t\t}\n\t\t\tcatch ( LuaRuntimeException e )\n\t\t\t{\n\t\t\t\tvar hr = L.Call( handler, e.Value );\n\t\t\t\treturn Ret( LuaValue.False, hr.Length \u003E 0 ? hr[0] : LuaValue.Nil );\n\t\t\t}\n\t\t} );\n\n\t\tLuaNativeFunction unpack = ( L, a ) =\u003E\n\t\t{\n\t\t\tvar t = CheckTable( a, 0, \u0022unpack\u0022 );\n\t\t\tint i = OptInt( a, 1, \u0022unpack\u0022, 1 );\n\t\t\tint j = Arg( a, 2 ).IsNil ? t.Length : CheckInt( a, 2, \u0022unpack\u0022 );\n\t\t\tif ( i \u003E j ) return LuaValue.EmptyArray;\n\t\t\tlong n = (long)j - i \u002B 1;\n\t\t\tif ( n \u003E 8000 ) throw new LuaRuntimeException( \u0022too many results to unpack\u0022 );\n\t\t\tvar r = new LuaValue[n];\n\t\t\tfor ( int k = 0; k \u003C n; k\u002B\u002B ) r[k] = t.Get( LuaValue.FromNumber( i \u002B k ) );\n\t\t\treturn r;\n\t\t};\n\t\tRegister( G, \u0022unpack\u0022, unpack );\n\t}\n\n\t// ------------------------------------------------------------ math\n\n\tvoid OpenMath()\n\t{\n\t\tvar M = GetOrCreateLibrary( \u0022math\u0022 );\n\t\tM.Set( \u0022pi\u0022, Math.PI );\n\t\tM.Set( \u0022huge\u0022, double.PositiveInfinity );\n\n\t\tvoid F1( string name, Func\u003Cdouble, double\u003E fn ) =\u003E\n\t\t\tRegister( M, name, ( L, a ) =\u003E Ret( fn( CheckNumber( a, 0, name ) ) ) );\n\n\t\tF1( \u0022abs\u0022, Math.Abs );\n\t\tF1( \u0022ceil\u0022, Math.Ceiling );\n\t\tF1( \u0022floor\u0022, Math.Floor );\n\t\tF1( \u0022sqrt\u0022, Math.Sqrt );\n\t\tF1( \u0022sin\u0022, Math.Sin );\n\t\tF1( \u0022cos\u0022, Math.Cos );\n\t\tF1( \u0022tan\u0022, Math.Tan );\n\t\tF1( \u0022asin\u0022, Math.Asin );\n\t\tF1( \u0022acos\u0022, Math.Acos );\n\t\tF1( \u0022exp\u0022, Math.Exp );\n\t\tF1( \u0022log10\u0022, Math.Log10 );\n\t\tF1( \u0022deg\u0022, x =\u003E x * (180.0 / Math.PI) );\n\t\tF1( \u0022rad\u0022, x =\u003E x * (Math.PI / 180.0) );\n\n\t\tRegister( M, \u0022atan\u0022, ( L, a ) =\u003E Ret( Arg( a, 1 ).IsNil ? Math.Atan( CheckNumber( a, 0, \u0022atan\u0022 ) ) : Math.Atan2( CheckNumber( a, 0, \u0022atan\u0022 ), CheckNumber( a, 1, \u0022atan\u0022 ) ) ) );\n\t\tRegister( M, \u0022atan2\u0022, ( L, a ) =\u003E Ret( Math.Atan2( CheckNumber( a, 0, \u0022atan2\u0022 ), CheckNumber( a, 1, \u0022atan2\u0022 ) ) ) );\n\t\tRegister( M, \u0022pow\u0022, ( L, a ) =\u003E Ret( Math.Pow( CheckNumber( a, 0, \u0022pow\u0022 ), CheckNumber( a, 1, \u0022pow\u0022 ) ) ) );\n\t\tRegister( M, \u0022fmod\u0022, ( L, a ) =\u003E Ret( CheckNumber( a, 0, \u0022fmod\u0022 ) % CheckNumber( a, 1, \u0022fmod\u0022 ) ) );\n\t\tRegister( M, \u0022log\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar x = CheckNumber( a, 0, \u0022log\u0022 );\n\t\t\treturn Ret( Arg( a, 1 ).IsNil ? Math.Log( x ) : Math.Log( x ) / Math.Log( CheckNumber( a, 1, \u0022log\u0022 ) ) );\n\t\t} );\n\t\tRegister( M, \u0022modf\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar x = CheckNumber( a, 0, \u0022modf\u0022 );\n\t\t\tvar ip = x \u003E= 0 ? Math.Floor( x ) : Math.Ceiling( x );\n\t\t\treturn Ret( ip, double.IsInfinity( x ) ? 0 : x - ip );\n\t\t} );\n\t\tRegister( M, \u0022max\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar m = CheckNumber( a, 0, \u0022max\u0022 );\n\t\t\tfor ( int i = 1; i \u003C a.Length; i\u002B\u002B ) m = Math.Max( m, CheckNumber( a, i, \u0022max\u0022 ) );\n\t\t\treturn Ret( m );\n\t\t} );\n\t\tRegister( M, \u0022min\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar m = CheckNumber( a, 0, \u0022min\u0022 );\n\t\t\tfor ( int i = 1; i \u003C a.Length; i\u002B\u002B ) m = Math.Min( m, CheckNumber( a, i, \u0022min\u0022 ) );\n\t\t\treturn Ret( m );\n\t\t} );\n\t\tRegister( M, \u0022random\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tif ( a.Length == 0 ) return Ret( L._random.NextDouble() );\n\t\t\tint lo = 1, hi;\n\t\t\tif ( a.Length == 1 ) hi = CheckInt( a, 0, \u0022random\u0022 );\n\t\t\telse { lo = CheckInt( a, 0, \u0022random\u0022 ); hi = CheckInt( a, 1, \u0022random\u0022 ); }\n\t\t\tif ( lo \u003E hi ) throw ArgError( a.Length == 1 ? 0 : 1, \u0022random\u0022, \u0022interval is empty\u0022 );\n\t\t\treturn Ret( (double)L._random.NextInt64( lo, (long)hi \u002B 1 ) );\n\t\t} );\n\t\tRegister( M, \u0022randomseed\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tL._random = new Random( CheckInt( a, 0, \u0022randomseed\u0022 ) );\n\t\t\treturn null;\n\t\t} );\n\t}\n\n\t// ------------------------------------------------------------ table\n\n\tvoid OpenTable()\n\t{\n\t\tvar T = GetOrCreateLibrary( \u0022table\u0022 );\n\n\t\tRegister( T, \u0022insert\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar t = CheckTable( a, 0, \u0022insert\u0022 );\n\t\t\tif ( a.Length == 2 ) { t.Append( a[1] ); return null; }\n\t\t\tif ( a.Length != 3 ) throw new LuaRuntimeException( \u0022wrong number of arguments to \u0027insert\u0027\u0022 );\n\t\t\tt.Insert( CheckInt( a, 1, \u0022insert\u0022 ), a[2] );\n\t\t\treturn null;\n\t\t} );\n\n\t\tRegister( T, \u0022remove\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar t = CheckTable( a, 0, \u0022remove\u0022 );\n\t\t\tint n = t.Length;\n\t\t\tif ( n == 0 \u0026\u0026 Arg( a, 1 ).IsNil ) return Ret( LuaValue.Nil );\n\t\t\tint pos = OptInt( a, 1, \u0022remove\u0022, n );\n\t\t\treturn Ret( t.RemoveAt( pos ) );\n\t\t} );\n\n\t\tRegister( T, \u0022concat\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar t = CheckTable( a, 0, \u0022concat\u0022 );\n\t\t\tvar sep = OptString( a, 1, \u0022concat\u0022, \u0022\u0022 );\n\t\t\tint i = OptInt( a, 2, \u0022concat\u0022, 1 );\n\t\t\tint j = Arg( a, 3 ).IsNil ? t.Length : CheckInt( a, 3, \u0022concat\u0022 );\n\t\t\tvar sb = new StringBuilder();\n\t\t\tfor ( int k = i; k \u003C= j; k\u002B\u002B )\n\t\t\t{\n\t\t\t\tvar v = t.Get( LuaValue.FromNumber( k ) );\n\t\t\t\tif ( v.Type != LuaType.String \u0026\u0026 v.Type != LuaType.Number )\n\t\t\t\t\tthrow new LuaRuntimeException( $\u0022invalid value (at index {k}) in table for \u0027concat\u0027\u0022 );\n\t\t\t\tif ( k \u003E i ) sb.Append( sep );\n\t\t\t\tsb.Append( v.ToString() );\n\t\t\t\tL.Step();\n\t\t\t}\n\t\t\treturn Ret( sb.ToString() );\n\t\t} );\n\n\t\tRegister( T, \u0022sort\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar t = CheckTable( a, 0, \u0022sort\u0022 );\n\t\t\tvar cmp = Arg( a, 1 );\n\t\t\tif ( !cmp.IsNil \u0026\u0026 !cmp.IsFunction ) throw ArgError( 1, \u0022sort\u0022, Expected( \u0022function\u0022, cmp ) );\n\n\t\t\tint n = t.Length;\n\t\t\tvar items = new LuaValue[n];\n\t\t\tfor ( int i = 0; i \u003C n; i\u002B\u002B ) items[i] = t.Get( LuaValue.FromNumber( i \u002B 1 ) );\n\n\t\t\tFunc\u003CLuaValue, LuaValue, bool\u003E less = cmp.IsNil\n\t\t\t\t? ( x, y ) =\u003E L.LessThan( x, y )\n\t\t\t\t: ( x, y ) =\u003E { var r = L.Call( cmp, x, y ); return r.Length \u003E 0 \u0026\u0026 r[0].IsTruthy; };\n\n\t\t\tMergeSort( L, items, new LuaValue[n], 0, n, less );\n\t\t\tfor ( int i = 0; i \u003C n; i\u002B\u002B ) t.Set( LuaValue.FromNumber( i \u002B 1 ), items[i] );\n\t\t\treturn null;\n\t\t} );\n\n\t\tT.Set( \u0022unpack\u0022, Globals.Get( \u0022unpack\u0022 ) );\n\n\t\tRegister( T, \u0022maxn\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar t = CheckTable( a, 0, \u0022maxn\u0022 );\n\t\t\tdouble max = 0;\n\t\t\tforeach ( var kv in t.Pairs() )\n\t\t\t\tif ( kv.Key.IsNumber \u0026\u0026 kv.Key.Number \u003E max ) max = kv.Key.Number;\n\t\t\treturn Ret( max );\n\t\t} );\n\t}\n\n\tstatic void MergeSort( LuaState L, LuaValue[] a, LuaValue[] tmp, int lo, int hi, Func\u003CLuaValue, LuaValue, bool\u003E less )\n\t{\n\t\tif ( hi - lo \u003C 2 ) return;\n\t\tint mid = (lo \u002B hi) / 2;\n\t\tMergeSort( L, a, tmp, lo, mid, less );\n\t\tMergeSort( L, a, tmp, mid, hi, less );\n\t\tint i = lo, j = mid, k = lo;\n\t\twhile ( i \u003C mid \u0026\u0026 j \u003C hi )\n\t\t{\n\t\t\tL.Step();\n\t\t\ttmp[k\u002B\u002B] = less( a[j], a[i] ) ? a[j\u002B\u002B] : a[i\u002B\u002B];\n\t\t}\n\t\twhile ( i \u003C mid ) tmp[k\u002B\u002B] = a[i\u002B\u002B];\n\t\twhile ( j \u003C hi ) tmp[k\u002B\u002B] = a[j\u002B\u002B];\n\t\tArray.Copy( tmp, lo, a, lo, hi - lo );\n\t}\n\n\t// ------------------------------------------------------------ os (time only)\n\n\tvoid OpenOs()\n\t{\n\t\tvar O = GetOrCreateLibrary( \u0022os\u0022 );\n\t\tRegister( O, \u0022time\u0022, ( L, a ) =\u003E Ret( (double)DateTimeOffset.UtcNow.ToUnixTimeSeconds() ) );\n\t\tRegister( O, \u0022clock\u0022, ( L, a ) =\u003E Ret( (DateTime.UtcNow - ClockStart).TotalSeconds ) );\n\t\tRegister( O, \u0022date\u0022, ( L, a ) =\u003E\n\t\t{\n\t\t\tvar fmt = OptString( a, 0, \u0022date\u0022, \u0022%c\u0022 );\n\t\t\tvar t = Arg( a, 1 ).IsNil ? DateTimeOffset.UtcNow : DateTimeOffset.FromUnixTimeSeconds( (long)CheckNumber( a, 1, \u0022date\u0022 ) );\n\t\t\tif ( fmt.StartsWith( \u0022!\u0022 ) ) fmt = fmt.Substring( 1 );\n\t\t\tif ( fmt.StartsWith( \u0022*t\u0022 ) )\n\t\t\t{\n\t\t\t\tvar r = new LuaTable();\n\t\t\t\tr.Set( \u0022year\u0022, t.Year ); r.Set( \u0022month\u0022, t.Month ); r.Set( \u0022day\u0022, t.Day );\n\t\t\t\tr.Set( \u0022hour\u0022, t.Hour ); r.Set( \u0022min\u0022, t.Minute ); r.Set( \u0022sec\u0022, t.Second );\n\t\t\t\tr.Set( \u0022wday\u0022, (int)t.DayOfWeek \u002B 1 ); r.Set( \u0022yday\u0022, t.DayOfYear ); r.Set( \u0022isdst\u0022, false );\n\t\t\t\treturn Ret( r );\n\t\t\t}\n\t\t\tvar sb = new StringBuilder();\n\t\t\tfor ( int i = 0; i \u003C fmt.Length; i\u002B\u002B )\n\t\t\t{\n\t\t\t\tif ( fmt[i] != \u0027%\u0027 || i \u002B 1 \u003E= fmt.Length ) { sb.Append( fmt[i] ); continue; }\n\t\t\t\tchar c = fmt[\u002B\u002Bi];\n\t\t\t\tsb.Append( c switch\n\t\t\t\t{\n\t\t\t\t\t\u0027Y\u0027 =\u003E t.Year.ToString( \u00220000\u0022 ),\n\t\t\t\t\t\u0027y\u0027 =\u003E (t.Year % 100).ToString( \u002200\u0022 ),\n\t\t\t\t\t\u0027m\u0027 =\u003E t.Month.ToString( \u002200\u0022 ),\n\t\t\t\t\t\u0027d\u0027 =\u003E t.Day.ToString( \u002200\u0022 ),\n\t\t\t\t\t\u0027H\u0027 =\u003E t.Hour.ToString( \u002200\u0022 ),\n\t\t\t\t\t\u0027M\u0027 =\u003E t.Minute.ToString( \u002200\u0022 ),\n\t\t\t\t\t\u0027S\u0027 =\u003E t.Second.ToString( \u002200\u0022 ),\n\t\t\t\t\t\u0027p\u0027 =\u003E t.Hour \u003C 12 ? \u0022AM\u0022 : \u0022PM\u0022,\n\t\t\t\t\t\u0027c\u0027 =\u003E t.ToString( \u0022ddd MMM dd HH:mm:ss yyyy\u0022, System.Globalization.CultureInfo.InvariantCulture ),\n\t\t\t\t\t\u0027x\u0027 =\u003E t.ToString( \u0022MM/dd/yy\u0022, System.Globalization.CultureInfo.InvariantCulture ),\n\t\t\t\t\t\u0027X\u0027 =\u003E t.ToString( \u0022HH:mm:ss\u0022, System.Globalization.CultureInfo.InvariantCulture ),\n\t\t\t\t\t\u0027%\u0027 =\u003E \u0022%\u0022,\n\t\t\t\t\t_ =\u003E \u0022%\u0022 \u002B c,\n\t\t\t\t} );\n\t\t\t}\n\t\t\treturn Ret( sb.ToString() );\n\t\t} );\n\t\tRegister( O, \u0022difftime\u0022, ( L, a ) =\u003E Ret( CheckNumber( a, 0, \u0022difftime\u0022 ) - OptNumber( a, 1, \u0022difftime\u0022, 0 ) ) );\n\t}\n}\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Scripting/Addons/AddonRegistry.cs","FileName":"AddonRegistry.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System.Collections.Generic;\nusing System.Linq;\nusing RoleplayFramework.Diagnostics;\n\nnamespace RoleplayFramework.Scripting;\n\npublic enum AddonStatus\n{\n\t/// \u003Csummary\u003EWill be loaded (or was loaded) for this world.\u003C/summary\u003E\n\tActive,\n\t/// \u003Csummary\u003ESwitched off in framework.json (\u0022DisabledAddons\u0022).\u003C/summary\u003E\n\tDisabled,\n\t/// \u003Csummary\u003ENot made for the running gamemode (\u0022gamemodes\u0022 in addon.json).\u003C/summary\u003E\n\tIncompatible,\n\t/// \u003Csummary\u003EA dependency is missing, switched off, incompatible or the wrong version.\u003C/summary\u003E\n\tBlocked,\n\t/// \u003Csummary\u003Eaddon.json is broken, or the addon is part of a dependency cycle.\u003C/summary\u003E\n\tInvalid,\n}\n\npublic sealed class AddonEntry\n{\n\tpublic string Id { get; init; }\n\tpublic AddonManifest Manifest { get; init; }\n\tpublic AddonStatus Status { get; set; }\n\tpublic string Reason { get; set; }\n}\n\n/// \u003Csummary\u003E\n/// Finds the addons under \u003Cc\u003Elua/addons/*/addon.json\u003C/c\u003E and decides which run with a given gamemode chain:\n/// valid, not switched off, made for the gamemode, and every dependency active in a matching version.\n/// \u003Csee cref=\u0022LoadOrder\u0022/\u003E lists the active ones with dependencies first, otherwise alphabetical, so the server and\n/// every client load them in the same order. Folders starting with \u0022_\u0022 (templates) are ignored.\n/// \u003C/summary\u003E\npublic sealed class AddonRegistry\n{\n\tpublic const string AddonsRoot = \u0022lua/addons\u0022;\n\tpublic const int MaxAddons = 256;\n\n\treadonly Dictionary\u003Cstring, AddonEntry\u003E _all = new();\n\tpublic IReadOnlyDictionary\u003Cstring, AddonEntry\u003E All =\u003E _all;\n\tpublic List\u003CAddonManifest\u003E LoadOrder { get; } = new();\n\n\t/// \u003Csummary\u003EThe resolution used by the running server (for diagnostics and rp_addons).\u003C/summary\u003E\n\tpublic static AddonRegistry Current { get; set; } = new();\n\n\tpublic static AddonRegistry Resolve( BaseFileSystem fs, IReadOnlyCollection\u003Cstring\u003E gamemodeChain, IEnumerable\u003Cstring\u003E disabled )\n\t{\n\t\tvar reg = new AddonRegistry();\n\t\tvar off = new HashSet\u003Cstring\u003E( disabled ?? Enumerable.Empty\u003Cstring\u003E() );\n\t\tvar chain = new HashSet\u003Cstring\u003E( gamemodeChain ?? new List\u003Cstring\u003E() );\n\n\t\tif ( fs.DirectoryExists( AddonsRoot ) )\n\t\t{\n\t\t\tforeach ( var folder in fs.FindDirectory( AddonsRoot, \u0022*\u0022, false ).OrderBy( x =\u003E x, System.StringComparer.Ordinal ) )\n\t\t\t{\n\t\t\t\tif ( folder.StartsWith( \u0022_\u0022 ) ) continue;\n\t\t\t\tvar root = $\u0022{AddonsRoot}/{folder}\u0022;\n\t\t\t\tif ( !fs.FileExists( $\u0022{root}/addon.json\u0022 ) ) continue;\n\t\t\t\tif ( reg._all.Count \u003E= MaxAddons ) { RpLog.Warn( \u0022addons\u0022, $\u0022More than {MaxAddons} addons; \u0027{folder}\u0027 and later ones are ignored\u0022 ); break; }\n\n\t\t\t\tAddonManifest m = null;\n\t\t\t\tstring problem = null;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tif ( !Json.TryDeserialize( fs.ReadAllText( $\u0022{root}/addon.json\u0022 ), out m ) || m is null ) problem = \u0022addon.json is not valid JSON\u0022;\n\t\t\t\t}\n\t\t\t\tcatch ( System.Exception e ) { problem = $\u0022addon.json could not be read: {e.Message}\u0022; }\n\n\t\t\t\tif ( problem is null )\n\t\t\t\t{\n\t\t\t\t\tm.Root = root;\n\t\t\t\t\tvar problems = m.Validate( folder );\n\t\t\t\t\tif ( problems.Count \u003E 0 ) problem = string.Join( \u0022; \u0022, problems );\n\t\t\t\t}\n\n\t\t\t\tvar entry = new AddonEntry { Id = folder, Manifest = problem is null ? m : null };\n\t\t\t\tif ( problem is not null ) { entry.Status = AddonStatus.Invalid; entry.Reason = problem; }\n\t\t\t\telse if ( off.Contains( folder ) ) { entry.Status = AddonStatus.Disabled; entry.Reason = \u0022switched off in framework.json (DisabledAddons)\u0022; }\n\t\t\t\telse if ( m.Gamemodes.Count \u003E 0 \u0026\u0026 !m.Gamemodes.Any( chain.Contains ) )\n\t\t\t\t{\n\t\t\t\t\tentry.Status = AddonStatus.Incompatible;\n\t\t\t\t\tentry.Reason = $\u0022made for {string.Join( \u0022, \u0022, m.Gamemodes )}, not this gamemode\u0022;\n\t\t\t\t}\n\t\t\t\telse entry.Status = AddonStatus.Active;\n\t\t\t\treg._all[folder] = entry;\n\t\t\t}\n\t\t}\n\n\t\t// Cycles among the remaining addons: report every member.\n\t\t// Find every cycle before marking any, so all members are reported.\n\t\tvar cycles = reg._all.Values.Where( e =\u003E e.Status == AddonStatus.Active )\n\t\t\t.Select( e =\u003E (Entry: e, Cycle: reg.FindCycle( e.Id )) ).Where( x =\u003E x.Cycle is not null \u0026\u0026 x.Cycle.Contains( x.Entry.Id ) ).ToList(); // depending on a cycle = blocked below\n\t\tforeach ( var (e, cycle) in cycles )\n\t\t{\n\t\t\te.Status = AddonStatus.Invalid;\n\t\t\te.Reason = $\u0022dependency cycle: {string.Join( \u0022 -\u003E \u0022, cycle )}\u0022;\n\t\t}\n\n\t\t// Dependencies must be active in a matching version; repeat until nothing changes (blocking cascades).\n\t\tbool changed = true;\n\t\twhile ( changed )\n\t\t{\n\t\t\tchanged = false;\n\t\t\tforeach ( var e in reg._all.Values.Where( e =\u003E e.Status == AddonStatus.Active ) )\n\t\t\t{\n\t\t\t\tforeach ( var (dep, constraint) in e.Manifest.Dependencies )\n\t\t\t\t{\n\t\t\t\t\tstring why = null;\n\t\t\t\t\tif ( !reg._all.TryGetValue( dep, out var d ) ) why = $\u0022needs addon \u0027{dep}\u0027, which is not installed\u0022;\n\t\t\t\t\telse if ( d.Status != AddonStatus.Active ) why = $\u0022needs addon \u0027{dep}\u0027, which is {d.Status.ToString().ToLowerInvariant()}\u0022;\n\t\t\t\t\telse if ( !VersionConstraint.Satisfies( d.Manifest.Version, constraint ) ) why = $\u0022needs \u0027{dep}\u0027 {constraint}, but {d.Manifest.Version} is installed\u0022;\n\t\t\t\t\tif ( why is null ) continue;\n\t\t\t\t\te.Status = AddonStatus.Blocked;\n\t\t\t\t\te.Reason = why;\n\t\t\t\t\tchanged = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( changed ) break;\n\t\t\t}\n\t\t}\n\n\t\t// Load order: dependencies first, ties alphabetical.\n\t\tvar seen = new HashSet\u003Cstring\u003E();\n\t\tvoid Add( string id )\n\t\t{\n\t\t\tif ( !seen.Add( id ) ) return;\n\t\t\tvar m = reg._all[id].Manifest;\n\t\t\tforeach ( var d in m.Dependencies.Keys.OrderBy( x =\u003E x, System.StringComparer.Ordinal ) ) Add( d );\n\t\t\treg.LoadOrder.Add( m );\n\t\t}\n\t\tforeach ( var e in reg._all.Values.Where( e =\u003E e.Status == AddonStatus.Active ).OrderBy( e =\u003E e.Id, System.StringComparer.Ordinal ).ToList() )\n\t\t\tAdd( e.Id );\n\n\t\treturn reg;\n\t}\n\n\tList\u003Cstring\u003E FindCycle( string start )\n\t{\n\t\tvar path = new List\u003Cstring\u003E();\n\t\tvar onPath = new HashSet\u003Cstring\u003E();\n\t\tList\u003Cstring\u003E Visit( string id )\n\t\t{\n\t\t\tif ( onPath.Contains( id ) )\n\t\t\t{\n\t\t\t\tvar cyc = path.Skip( path.IndexOf( id ) ).ToList();\n\t\t\t\tcyc.Add( id );\n\t\t\t\treturn cyc;\n\t\t\t}\n\t\t\tif ( !_all.TryGetValue( id, out var e ) || e.Manifest is null || e.Status != AddonStatus.Active ) return null;\n\t\t\tonPath.Add( id );\n\t\t\tpath.Add( id );\n\t\t\tforeach ( var d in e.Manifest.Dependencies.Keys )\n\t\t\t\tif ( Visit( d ) is { } c ) return c;\n\t\t\tpath.RemoveAt( path.Count - 1 );\n\t\t\tonPath.Remove( id );\n\t\t\treturn null;\n\t\t}\n\t\treturn Visit( start );\n\t}\n\n\tpublic void LogSummary()\n\t{\n\t\tif ( _all.Count == 0 ) return;\n\t\tforeach ( var e in _all.Values )\n\t\t{\n\t\t\tif ( e.Status == AddonStatus.Active ) RpLog.Info( \u0022addons\u0022, $\u0022Addon {e.Id} {e.Manifest.Version} \\\u0022{e.Manifest.Title}\\\u0022 active\u0022 );\n\t\t\telse if ( e.Status is AddonStatus.Invalid or AddonStatus.Blocked ) RpLog.Warn( \u0022addons\u0022, $\u0022Addon \u0027{e.Id}\u0027 not loaded ({e.Status.ToString().ToLowerInvariant()}): {e.Reason}\u0022 );\n\t\t\telse RpLog.Info( \u0022addons\u0022, $\u0022Addon \u0027{e.Id}\u0027 not loaded ({e.Status.ToString().ToLowerInvariant()}): {e.Reason}\u0022 );\n\t\t}\n\t}\n}\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Scripting/Api/LuaEntities.cs","FileName":"LuaEntities.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing RoleplayFramework.Lua;\r\nusing RoleplayFramework.Players;\r\n\r\nnamespace RoleplayFramework.Scripting;\r\n\r\n/// \u003Csummary\u003EConversions between Lua Vector/Angle tables and engine types.\u003C/summary\u003E\r\npublic static class LuaConvert\r\n{\r\n\tstatic double Field( LuaTable t, string k, string what )\r\n\t{\r\n\t\tvar v = t.Get( k );\r\n\t\tif ( !v.IsNumber || double.IsNaN( v.Number ) || double.IsInfinity( v.Number ) ) throw new LuaRuntimeException( $\u0022{what}.{k} must be a finite number\u0022 );\r\n\t\treturn v.Number;\r\n\t}\r\n\r\n\tpublic static Vector3 ToVector( LuaValue v, string what = \u0022Vector\u0022 )\r\n\t{\r\n\t\tif ( !v.IsTable ) throw new LuaRuntimeException( $\u0022{what} expected (use Vector(x, y, z))\u0022 );\r\n\t\tvar t = v.AsTable;\r\n\t\treturn new Vector3( (float)Field( t, \u0022x\u0022, what ), (float)Field( t, \u0022y\u0022, what ), (float)Field( t, \u0022z\u0022, what ) );\r\n\t}\r\n\r\n\tpublic static Angles ToAngles( LuaValue v, string what = \u0022Angle\u0022 )\r\n\t{\r\n\t\tif ( !v.IsTable ) throw new LuaRuntimeException( $\u0022{what} expected (use Angle(pitch, yaw, roll))\u0022 );\r\n\t\tvar t = v.AsTable;\r\n\t\treturn new Angles( (float)Field( t, \u0022p\u0022, what ), (float)Field( t, \u0022y\u0022, what ), (float)Field( t, \u0022r\u0022, what ) );\r\n\t}\r\n\r\n\tpublic static LuaValue FromVector( LuaState L, Vector3 v )\r\n\t{\r\n\t\tvar ctor = L.Globals.Get( \u0022Vector\u0022 );\r\n\t\tif ( ctor.IsFunction ) return L.Call( ctor, v.x, v.y, v.z )[0];\r\n\t\tvar t = new LuaTable();\r\n\t\tt.Set( \u0022x\u0022, v.x ); t.Set( \u0022y\u0022, v.y ); t.Set( \u0022z\u0022, v.z );\r\n\t\treturn t;\r\n\t}\r\n\r\n\tpublic static LuaValue FromAngles( LuaState L, Angles a )\r\n\t{\r\n\t\tvar ctor = L.Globals.Get( \u0022Angle\u0022 );\r\n\t\tif ( ctor.IsFunction ) return L.Call( ctor, a.pitch, a.yaw, a.roll )[0];\r\n\t\tvar t = new LuaTable();\r\n\t\tt.Set( \u0022p\u0022, a.pitch ); t.Set( \u0022y\u0022, a.yaw ); t.Set( \u0022r\u0022, a.roll );\r\n\t\treturn t;\r\n\t}\r\n}\r\n\r\ninternal sealed class EntityHandle\r\n{\r\n\tpublic Guid Id;\r\n}\r\n\r\n/// \u003Csummary\u003E\r\n/// The \u003Cc\u003EEntity\u003C/c\u003E type and \u003Cc\u003Eents\u003C/c\u003E/\u003Cc\u003Eutil\u003C/c\u003E libraries.\r\n///\r\n/// Server: ents.Create(class, { model, pos, ang, scale, physics, tint }), ent:SetPos/SetAngles/SetColor/Remove, NW setters.\r\n/// Both:   ents.GetAll(), ents.FindByClass(class), ents.FindInSphere(pos, radius), ent:IsValid/GetClass/GetPos/GetAngles/\r\n///         GetModel/GetKeyValue/GetId, NW getters, util.TraceLine({ start, endpos, filter }).\r\n/// \u003C/summary\u003E\r\npublic static class LuaEntities\r\n{\r\n\tpublic const int MaxCreatedPerRealm = 2000;\r\n\r\n\tpublic static void Register( LuaRealm realm )\r\n\t{\r\n\t\tvar L = realm.State;\r\n\t\tvar methods = new LuaTable();\r\n\t\tvar meta = new LuaTable();\r\n\t\tmeta.Set( \u0022__index\u0022, methods );\r\n\t\tmeta.Set( \u0022__metatable\u0022, \u0022Entity\u0022 );\r\n\t\tLuaState.Register( meta, \u0022__tostring\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar e = Resolve( a, 0 );\r\n\t\t\treturn new LuaValue[] { e is null ? \u0022Entity [NULL]\u0022 : $\u0022Entity [{e.Class}]\u0022 };\r\n\t\t} );\r\n\t\trealm.EntityMeta = meta;\r\n\t\trealm.MethodTables[\u0022Entity\u0022] = methods;\r\n\r\n\t\tbool server = realm.Kind == LuaRealmKind.Server;\r\n\t\tLuaNativeFunction ServerOnly( string name, LuaNativeFunction f ) =\u003E server ? f : ( s, a ) =\u003E throw new LuaRuntimeException( $\u0022{name} can only be called on the server\u0022 );\r\n\t\t// Entity setters: the server, or a client on its own ClientsideModel.\r\n\t\tLuaNativeFunction Owned( string name, LuaNativeFunction f ) =\u003E server ? f : ( s, a ) =\u003E\r\n\t\t\tResolve( a, 0 ) is { IsClientside: true } ? f( s, a ) : throw new LuaRuntimeException( $\u0022{name} can only be called on the server (or on your own ClientsideModel)\u0022 );\r\n\r\n\t\tLuaState.Register( methods, \u0022IsValid\u0022, ( s, a ) =\u003E new LuaValue[] { Resolve( a, 0 ) is not null } );\r\n\t\tLuaState.Register( methods, \u0022GetClass\u0022, ( s, a ) =\u003E new LuaValue[] { Check( a, \u0022GetClass\u0022 ).Class } );\r\n\t\tLuaState.Register( methods, \u0022GetId\u0022, ( s, a ) =\u003E new LuaValue[] { Check( a, \u0022GetId\u0022 ).GameObject.Id.ToString() } );\r\n\t\tLuaState.Register( methods, \u0022GetPos\u0022, ( s, a ) =\u003E new[] { LuaConvert.FromVector( s, Check( a, \u0022GetPos\u0022 ).WorldPosition ) } );\r\n\t\tLuaState.Register( methods, \u0022GetAngles\u0022, ( s, a ) =\u003E new[] { LuaConvert.FromAngles( s, Check( a, \u0022GetAngles\u0022 ).WorldRotation.Angles() ) } );\r\n\t\tLuaState.Register( methods, \u0022GetKeyValue\u0022, ( s, a ) =\u003E\r\n\t\t\tnew LuaValue[] { Check( a, \u0022GetKeyValue\u0022 ).GetKeyValue( LuaState.CheckString( a, 1, \u0022GetKeyValue\u0022 ) ) } );\r\n\r\n\t\tLuaState.Register( methods, \u0022SetPos\u0022, Owned( \u0022SetPos\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar e = Check( a, \u0022SetPos\u0022 );\r\n\t\t\te.WorldPosition = LuaConvert.ToVector( LuaState.Arg( a, 1 ) );\r\n\t\t\treturn null;\r\n\t\t} ) );\r\n\t\tLuaState.Register( methods, \u0022SetAngles\u0022, Owned( \u0022SetAngles\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar e = Check( a, \u0022SetAngles\u0022 );\r\n\t\t\te.WorldRotation = LuaConvert.ToAngles( LuaState.Arg( a, 1 ) ).ToRotation();\r\n\t\t\treturn null;\r\n\t\t} ) );\r\n\t\tLuaState.Register( methods, \u0022SetColor\u0022, Owned( \u0022SetColor\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar e = Check( a, \u0022SetColor\u0022 );\r\n\t\t\tvar c = LuaState.Arg( a, 1 );\r\n\t\t\tif ( !c.IsTable ) throw new LuaRuntimeException( \u0022SetColor expects a Color\u0022 );\r\n\t\t\tvar t = c.AsTable;\r\n\t\t\tfloat Ch( string k ) =\u003E LuaState.ToNumber( t.Get( k ), out var d ) ? (float)Math.Clamp( d / 255.0, 0, 1 ) : 1f;\r\n\t\t\te.Tint = new Color( Ch( \u0022r\u0022 ), Ch( \u0022g\u0022 ), Ch( \u0022b\u0022 ), Ch( \u0022a\u0022 ) );\r\n\t\t\treturn null;\r\n\t\t} ) );\r\n\t\tLuaState.Register( methods, \u0022Remove\u0022, Owned( \u0022Remove\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar e = Resolve( a, 0 );\r\n\t\t\te?.GameObject.Destroy();\r\n\t\t\treturn null;\r\n\t\t} ) );\r\n\r\n\t\tLuaNetVars.AddMethods( realm, methods, ( a, name ) =\u003E Check( a, name ) );\r\n\t\tLuaAppearance.AddMethods( methods, ( a, name ) =\u003E Check( a, name ).GameObject,\r\n\t\t\tgo =\u003E server || go.Components.Get\u003CLuaEntity\u003E() is { IsClientside: true }, isPlayer: false );\r\n\t\tLuaAppearance.RegisterGlobals( realm );\r\n\r\n\t\tvar ents = L.GetOrCreateLibrary( \u0022ents\u0022 );\r\n\t\tLuaState.Register( ents, \u0022GetAll\u0022, ( s, a ) =\u003E ToList( realm, LuaEntity.All( Game.ActiveScene ) ) );\r\n\t\tLuaState.Register( ents, \u0022FindByClass\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar cls = LuaState.CheckString( a, 0, \u0022ents.FindByClass\u0022 );\r\n\t\t\treturn ToList( realm, LuaEntity.All( Game.ActiveScene ).Where( e =\u003E e.Class == cls ) );\r\n\t\t} );\r\n\t\tLuaState.Register( ents, \u0022FindInSphere\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar pos = LuaConvert.ToVector( LuaState.Arg( a, 0 ) );\r\n\t\t\tvar r = (float)LuaState.CheckNumber( a, 1, \u0022ents.FindInSphere\u0022 );\r\n\t\t\treturn ToList( realm, LuaEntity.All( Game.ActiveScene ).Where( e =\u003E e.WorldPosition.Distance( pos ) \u003C= r ) );\r\n\t\t} );\r\n\t\tLuaState.Register( ents, \u0022Create\u0022, ServerOnly( \u0022ents.Create\u0022, ( s, a ) =\u003E new[] { Create( realm, a ) } ) );\r\n\t\tif ( !server )\r\n\t\t{\r\n\t\t\t// Client-only decoration (GMod: ClientsideModel). Not networked; removed when the client realm stops.\r\n\t\t\tLuaNativeFunction csm = ( s, a ) =\u003E new[] { CreateClientside( realm, a ) };\r\n\t\t\tL.Register( \u0022ClientsideModel\u0022, csm );\r\n\t\t\tLuaState.Register( ents, \u0022CreateClientProp\u0022, csm );\r\n\t\t}\r\n\r\n\t\tvar util = L.GetOrCreateLibrary( \u0022util\u0022 );\r\n\t\tLuaState.Register( util, \u0022TraceLine\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar opts = LuaState.CheckTable( a, 0, \u0022util.TraceLine\u0022 );\r\n\t\t\tvar start = LuaConvert.ToVector( opts.Get( \u0022start\u0022 ), \u0022start\u0022 );\r\n\t\t\tvar end = LuaConvert.ToVector( opts.Get( \u0022endpos\u0022 ), \u0022endpos\u0022 );\r\n\t\t\tGameObject ignore = null;\r\n\t\t\tvar filter = opts.Get( \u0022filter\u0022 );\r\n\t\t\tif ( LuaPlayers.HandleOf( filter ) is { } pid ) ignore = LuaPlayers.Find( pid )?.GameObject;\r\n\t\t\telse if ( HandleOf( filter ) is { } eid ) ignore = Game.ActiveScene.Directory.FindByGuid( eid );\r\n\t\t\treturn new[] { Trace( realm, start, end, ignore ) };\r\n\t\t} );\r\n\t}\r\n\r\n\tstatic LuaValue[] ToList( LuaRealm realm, IEnumerable\u003CLuaEntity\u003E list )\r\n\t{\r\n\t\tvar t = new LuaTable();\r\n\t\tforeach ( var e in list ) t.Append( Wrap( realm, e ) );\r\n\t\treturn new LuaValue[] { t };\r\n\t}\r\n\r\n\tstatic LuaValue Create( LuaRealm realm, LuaValue[] a )\r\n\t{\r\n\t\tvar cls = LuaState.CheckString( a, 0, \u0022ents.Create\u0022 );\r\n\t\tif ( cls.Length is 0 or \u003E 64 ) throw LuaState.ArgError( 0, \u0022ents.Create\u0022, \u0022class must be 1-64 characters\u0022 );\r\n\t\tvar opts = LuaState.Arg( a, 1 ).IsTable ? LuaState.Arg( a, 1 ).AsTable : new LuaTable();\r\n\r\n\t\tif ( realm.EntitiesCreated \u003E= MaxCreatedPerRealm \u0026\u0026 LuaEntity.All( Game.ActiveScene ).Count() \u003E= MaxCreatedPerRealm )\r\n\t\t\tthrow new LuaRuntimeException( $\u0022too many entities (limit {MaxCreatedPerRealm})\u0022 );\r\n\r\n\t\t// A path or a package ident (\u0022fish.barrel\u0022 = that mounted package\u0027s main model).\r\n\t\tvar (modelPath, model) = LuaAppearance.LoadModel( opts.Get( \u0022model\u0022 ).IsString ? opts.Get( \u0022model\u0022 ).AsString : \u0022models/dev/box.vmdl\u0022, \u0022ents.Create\u0022 );\r\n\r\n\t\tvar go = new GameObject( true, cls );\r\n\t\tgo.WorldPosition = opts.Get( \u0022pos\u0022 ).IsNil ? Vector3.Zero : LuaConvert.ToVector( opts.Get( \u0022pos\u0022 ), \u0022pos\u0022 );\r\n\t\tgo.WorldRotation = opts.Get( \u0022ang\u0022 ).IsNil ? Rotation.Identity : LuaConvert.ToAngles( opts.Get( \u0022ang\u0022 ), \u0022ang\u0022 ).ToRotation();\r\n\t\tif ( LuaState.ToNumber( opts.Get( \u0022scale\u0022 ), out var sc ) ) go.WorldScale = (float)Math.Clamp( sc, 0.05, 20 );\r\n\r\n\t\t// Optional: \u0022size\u0022 stretches the model to exact dimensions, \u0022offset\u0022 moves the visible/solid part\r\n\t\t// relative to the entity origin (e.g. a door whose origin is its hinge).\r\n\t\tvar modelHolder = go;\r\n\t\tbool hasSize = opts.Get( \u0022size\u0022 ).IsTable, hasOffset = opts.Get( \u0022offset\u0022 ).IsTable;\r\n\t\tif ( hasSize || hasOffset )\r\n\t\t{\r\n\t\t\tmodelHolder = new GameObject( go, true, \u0022Model\u0022 );\r\n\t\t\tif ( hasOffset ) modelHolder.LocalPosition = LuaConvert.ToVector( opts.Get( \u0022offset\u0022 ), \u0022offset\u0022 );\r\n\t\t\tif ( hasSize )\r\n\t\t\t{\r\n\t\t\t\tvar size = LuaConvert.ToVector( opts.Get( \u0022size\u0022 ), \u0022size\u0022 );\r\n\t\t\t\tvar b = model.Bounds.Size;\r\n\t\t\t\tif ( size.x \u003C= 0 || size.y \u003C= 0 || size.z \u003C= 0 || size.Length \u003E 100000 ) throw new LuaRuntimeException( \u0022size must be positive and reasonable\u0022 );\r\n\t\t\t\tmodelHolder.LocalScale = new Vector3( size.x / Math.Max( b.x, 0.001f ), size.y / Math.Max( b.y, 0.001f ), size.z / Math.Max( b.z, 0.001f ) );\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvar renderer = modelHolder.Components.Create\u003CModelRenderer\u003E();\r\n\t\trenderer.Model = model;\r\n\r\n\t\t// collider = \u0022model\u0022: the model\u0027s own physics shape (props); otherwise a box around the model.\r\n\t\tvar wantModel = opts.Get( \u0022collider\u0022 ).IsString \u0026\u0026 opts.Get( \u0022collider\u0022 ).AsString == \u0022model\u0022;\r\n\t\tif ( wantModel \u0026\u0026 model.Physics is { } phys \u0026\u0026 phys.Parts.Count \u003E 0 )\r\n\t\t{\r\n\t\t\tmodelHolder.Components.Create\u003CModelCollider\u003E().Model = model;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvar collider = modelHolder.Components.Create\u003CBoxCollider\u003E();\r\n\t\t\tcollider.Center = model.Bounds.Center;\r\n\t\t\tcollider.Scale = model.Bounds.Size;\r\n\t\t}\r\n\r\n\t\tif ( opts.Get( \u0022physics\u0022 ).IsTruthy ) go.Components.Create\u003CRigidbody\u003E();\r\n\r\n\t\tvar ent = go.Components.Create\u003CLuaEntity\u003E();\r\n\t\tent.Class = cls;\r\n\t\tgo.Components.Create\u003CRpAppearance\u003E().ModelPath = modelPath;\r\n\t\tif ( opts.Get( \u0022material\u0022 ).IsString ) go.Components.Get\u003CRpAppearance\u003E().MaterialPath = LuaAppearance.LoadMaterialPath( opts.Get( \u0022material\u0022 ).AsString, \u0022ents.Create\u0022 );\r\n\r\n\t\tif ( opts.Get( \u0022tint\u0022 ).IsTable )\r\n\t\t{\r\n\t\t\tvar t = opts.Get( \u0022tint\u0022 ).AsTable;\r\n\t\t\tfloat Ch( string k ) =\u003E LuaState.ToNumber( t.Get( k ), out var d ) ? (float)Math.Clamp( d / 255.0, 0, 1 ) : 1f;\r\n\t\t\tent.Tint = new Color( Ch( \u0022r\u0022 ), Ch( \u0022g\u0022 ), Ch( \u0022b\u0022 ), Ch( \u0022a\u0022 ) );\r\n\t\t}\r\n\r\n\t\tif ( Networking.IsActive ) go.NetworkSpawn();\r\n\t\trealm.EntitiesCreated\u002B\u002B;\r\n\t\trealm.CreatedObjects.RemoveAll( o =\u003E !o.IsValid() );\r\n\t\trealm.CreatedObjects.Add( go );\r\n\t\treturn Wrap( realm, ent );\r\n\t}\r\n\r\n\tstatic LuaValue CreateClientside( LuaRealm realm, LuaValue[] a )\r\n\t{\r\n\t\tvar (modelPath, model) = LuaAppearance.LoadModel( LuaState.CheckString( a, 0, \u0022ClientsideModel\u0022 ), \u0022ClientsideModel\u0022 );\r\n\t\trealm.CreatedObjects.RemoveAll( o =\u003E !o.IsValid() );\r\n\t\tif ( realm.CreatedObjects.Count \u003E= MaxCreatedPerRealm ) throw new LuaRuntimeException( $\u0022too many entities (limit {MaxCreatedPerRealm})\u0022 );\r\n\r\n\t\tvar go = new GameObject( true, \u0022clientside\u0022 );\r\n\t\tgo.NetworkMode = NetworkMode.Never;\r\n\t\tgo.Components.Create\u003CModelRenderer\u003E().Model = model;\r\n\t\tvar ent = go.Components.Create\u003CLuaEntity\u003E();\r\n\t\tent.Class = \u0022class C_BaseFlex\u0022;\r\n\t\tent.IsClientside = true;\r\n\t\tgo.Components.Create\u003CRpAppearance\u003E().ModelPath = modelPath;\r\n\t\trealm.CreatedObjects.Add( go );\r\n\t\treturn Wrap( realm, ent );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ETrace result table: { Hit, HitPos, HitNormal, Normal, StartPos, Fraction, Distance, Entity (Entity|Player|nil), HitWorld }.\u003C/summary\u003E\r\n\tpublic static LuaValue Trace( LuaRealm realm, Vector3 start, Vector3 end, GameObject ignore )\r\n\t{\r\n\t\tvar trace = Game.ActiveScene.Trace.Ray( start, end );\r\n\t\tif ( ignore is not null ) trace = trace.IgnoreGameObjectHierarchy( ignore );\r\n\t\tvar tr = trace.Run();\r\n\r\n\t\tvar t = new LuaTable();\r\n\t\tt.Set( \u0022Hit\u0022, tr.Hit );\r\n\t\tt.Set( \u0022HitPos\u0022, LuaConvert.FromVector( realm.State, tr.Hit ? tr.HitPosition : tr.EndPosition ) );\r\n\t\tt.Set( \u0022Distance\u0022, tr.Distance );\r\n\t\tt.Set( \u0022HitNormal\u0022, LuaConvert.FromVector( realm.State, tr.Hit ? tr.Normal : Vector3.Zero ) );\r\n\t\tt.Set( \u0022Normal\u0022, LuaConvert.FromVector( realm.State, (end - start).Normal ) );\r\n\t\tt.Set( \u0022StartPos\u0022, LuaConvert.FromVector( realm.State, start ) );\r\n\t\tt.Set( \u0022Fraction\u0022, tr.Fraction );\r\n\r\n\t\tLuaValue hitEnt = LuaValue.Nil;\r\n\t\tif ( tr.Hit \u0026\u0026 tr.GameObject is not null )\r\n\t\t{\r\n\t\t\tvar player = tr.GameObject.Components.GetInAncestorsOrSelf\u003CRpPlayer\u003E();\r\n\t\t\tvar ent = tr.GameObject.Components.GetInAncestorsOrSelf\u003CLuaEntity\u003E();\r\n\t\t\tif ( player is not null ) hitEnt = LuaPlayers.Wrap( realm, player.ConnectionId );\r\n\t\t\telse if ( ent is not null ) hitEnt = Wrap( realm, ent );\r\n\t\t}\r\n\t\tt.Set( \u0022Entity\u0022, hitEnt );\r\n\t\tt.Set( \u0022HitWorld\u0022, tr.Hit \u0026\u0026 hitEnt.IsNil );\r\n\t\treturn t;\r\n\t}\r\n\r\n\tpublic static LuaValue Wrap( LuaRealm realm, LuaEntity e )\r\n\t{\r\n\t\tvar id = e.GameObject.Id;\r\n\t\tif ( !realm.EntityCache.TryGetValue( id, out var ud ) )\r\n\t\t{\r\n\t\t\tud = new LuaUserData( new EntityHandle { Id = id }, realm.EntityMeta );\r\n\t\t\trealm.EntityCache[id] = ud;\r\n\t\t}\r\n\t\treturn LuaValue.FromUserData( ud );\r\n\t}\r\n\r\n\tinternal static Guid? HandleOf( LuaValue v ) =\u003E\r\n\t\tv.Type == LuaType.UserData \u0026\u0026 v.AsUserData.Value is EntityHandle h ? h.Id : null;\r\n\r\n\tinternal static LuaEntity Resolve( LuaValue[] a, int i )\r\n\t{\r\n\t\tif ( HandleOf( LuaState.Arg( a, i ) ) is not { } id ) return null;\r\n\t\tvar go = Game.ActiveScene?.Directory.FindByGuid( id );\r\n\t\treturn go.IsValid() ? go.Components.Get\u003CLuaEntity\u003E() : null;\r\n\t}\r\n\r\n\tstatic LuaEntity Check( LuaValue[] a, string method )\r\n\t{\r\n\t\tif ( HandleOf( LuaState.Arg( a, 0 ) ) is null ) throw new LuaRuntimeException( $\u0022calling \u0027{method}\u0027 on a non-entity value (use ent:{method}())\u0022 );\r\n\t\treturn Resolve( a, 0 ) ?? throw new LuaRuntimeException( $\u0022calling \u0027{method}\u0027 on a removed entity (check IsValid first)\u0022 );\r\n\t}\r\n}\r\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Scripting/Api/LuaInput.cs","FileName":"LuaInput.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing RoleplayFramework.Lua;\r\nusing RoleplayFramework.Players;\r\n\r\nnamespace RoleplayFramework.Scripting;\r\n\r\n/// \u003Csummary\u003E\r\n/// Client input \u2192 Lua. Each frame the client realm receives \u003Cc\u003EPlayerButtonDown(action)\u003C/c\u003E / \u003Cc\u003EPlayerButtonUp(action)\u003C/c\u003E\r\n/// for the project\u0027s input actions (not while a Lua text box has focus). Escape is reported as \u0022Escape\u0022; if a hook\r\n/// returns true for it, the engine\u0027s own escape handling is suppressed.\r\n///\r\n/// Pressing Use also asks the server to run \u003Cc\u003EPlayerUse(ply, ent)\u003C/c\u003E for whatever the player is looking at (within\r\n/// \u003Csee cref=\u0022UseRange\u0022/\u003E units); the server does the trace itself, so the client can\u0027t choose the target.\r\n/// \u003C/summary\u003E\r\npublic static class LuaInput\r\n{\r\n\tpublic const float UseRange = 120f;\r\n\r\n\tpublic static readonly string[] Actions =\r\n\t{\r\n\t\t\u0022Use\u0022, \u0022Reload\u0022, \u0022Attack1\u0022, \u0022Attack2\u0022, \u0022Jump\u0022, \u0022Duck\u0022, \u0022Drop\u0022, \u0022Flashlight\u0022, \u0022Score\u0022, \u0022Menu\u0022, \u0022Chat\u0022, \u0022View\u0022, \u0022Voice\u0022,\r\n\t\t\u0022Slot1\u0022, \u0022Slot2\u0022, \u0022Slot3\u0022, \u0022Slot4\u0022, \u0022Slot5\u0022, \u0022Slot6\u0022, \u0022Slot7\u0022, \u0022Slot8\u0022, \u0022Slot9\u0022, \u0022Slot0\u0022, \u0022SlotPrev\u0022, \u0022SlotNext\u0022,\r\n\t\t\u0022ShowHelp\u0022, \u0022ShowTeam\u0022, \u0022ShowSpare1\u0022, \u0022ShowSpare2\u0022,\r\n\t};\r\n\r\n\t/// \u003Csummary\u003ECalled every frame on machines with a client realm.\u003C/summary\u003E\r\n\tpublic static void Tick()\r\n\t{\r\n\t\tvar realm = LuaRuntime.Client;\r\n\t\tif ( realm is null ) return;\r\n\r\n\t\tif ( Input.EscapePressed )\r\n\t\t{\r\n\t\t\tvar r = realm.RunHook( \u0022PlayerButtonDown\u0022, \u0022Escape\u0022 );\r\n\t\t\tif ( r is { Length: \u003E 0 } \u0026\u0026 r[0].IsTruthy ) Input.EscapePressed = false;\r\n\t\t}\r\n\r\n\t\tif ( LuaUi.IsTyping ) return;\r\n\r\n\t\tforeach ( var action in Actions )\r\n\t\t{\r\n\t\t\tif ( Input.Pressed( action ) )\r\n\t\t\t{\r\n\t\t\t\t// Gamemode menu keys are easy to misconfigure: log them so \u0022the menu key does nothing\u0022 is diagnosable.\r\n\t\t\t\tif ( action.StartsWith( \u0022Show\u0022 ) ) Diagnostics.RpLog.Info( \u0022input\u0022, $\u0022{action} pressed ({Input.GetButtonOrigin( action )})\u0022 );\r\n\t\t\t\trealm.RunHook( \u0022PlayerButtonDown\u0022, action );\r\n\t\t\t\tif ( action == \u0022Use\u0022 ) RequestUse();\r\n\t\t\t}\r\n\t\t\telse if ( Input.Released( action ) )\r\n\t\t\t{\r\n\t\t\t\trealm.RunHook( \u0022PlayerButtonUp\u0022, action );\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tstatic readonly System.Text.RegularExpressions.Regex KeyPattern = new( \u0022^[a-z0-9_]{1,16}$\u0022 );\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Note: s\u0026amp;box reserves F1-F12 and Escape for the engine (\u003Cc\u003EInputContext.IsReservedButton\u003C/c\u003E); games can never\r\n\t/// see them, as actions or as raw keys. Bind gamemode keys to other keys.\r\n\t///\r\n\t/// Client library \u003Cc\u003Einput\u003C/c\u003E (GMod-style): \u003Cc\u003Einput.IsKeyDown(key)\u003C/c\u003E, \u003Cc\u003Einput.WasKeyPressed(key)\u003C/c\u003E,\r\n\t/// \u003Cc\u003Einput.WasKeyReleased(key)\u003C/c\u003E, \u003Cc\u003Einput.LookupBinding(action)\u003C/c\u003E. Keys are s\u0026amp;box key names: \u0022m\u0022, \u0022f4\u0022,\r\n\t/// \u0022tab\u0022, \u0022enter\u0022, \u0022space\u0022, \u0022mouse1\u0022, ... Both return false while a Lua text box has focus.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void Register( LuaRealm realm )\r\n\t{\r\n\t\tvar t = realm.State.GetOrCreateLibrary( \u0022input\u0022 );\r\n\t\tstring Key( LuaValue[] a, string fname )\r\n\t\t{\r\n\t\t\tvar k = LuaState.CheckString( a, 0, fname ).Trim().ToLowerInvariant();\r\n\t\t\tif ( !KeyPattern.IsMatch( k ) ) throw LuaState.ArgError( 0, fname, $\u0022\u0027{k}\u0027 is not a key name (e.g. \\\u0022m\\\u0022, \\\u0022f4\\\u0022)\u0022 );\r\n\t\t\treturn k;\r\n\t\t}\r\n\t\tbool Safe( Func\u003Cbool\u003E f ) { try { return f(); } catch ( Exception ) { return false; } }\r\n\r\n\t\tLuaState.Register( t, \u0022IsKeyDown\u0022, ( s, a ) =\u003E { var k = Key( a, \u0022input.IsKeyDown\u0022 ); return new LuaValue[] { !LuaUi.IsTyping \u0026\u0026 Safe( () =\u003E Input.Keyboard.Down( k ) ) }; } );\r\n\t\tLuaState.Register( t, \u0022WasKeyPressed\u0022, ( s, a ) =\u003E { var k = Key( a, \u0022input.WasKeyPressed\u0022 ); return new LuaValue[] { !LuaUi.IsTyping \u0026\u0026 Safe( () =\u003E Input.Keyboard.Pressed( k ) ) }; } );\r\n\t\tLuaState.Register( t, \u0022WasKeyReleased\u0022, ( s, a ) =\u003E { var k = Key( a, \u0022input.WasKeyReleased\u0022 ); return new LuaValue[] { Safe( () =\u003E Input.Keyboard.Released( k ) ) }; } );\r\n\t\tLuaState.Register( t, \u0022LookupBinding\u0022, ( s, a ) =\u003E\r\n\t\t\tnew[] { RawKey( LuaState.CheckString( a, 0, \u0022input.LookupBinding\u0022 ) ) is { } k ? LuaValue.FromString( k ) : LuaValue.Nil } );\r\n\t}\r\n\r\n\tstatic Dictionary\u003Cstring, string\u003E _keys;\r\n\r\n\t/// \u003Csummary\u003EThe keyboard key bound to an action in the project\u0027s input settings (e.g. \u0022f4\u0022), or null.\u003C/summary\u003E\r\n\tstatic string RawKey( string action )\r\n\t{\r\n\t\tif ( _keys is null )\r\n\t\t{\r\n\t\t\t_keys = new();\r\n\t\t\tforeach ( var a in Input.GetActions() )\r\n\t\t\t\tif ( !string.IsNullOrEmpty( a.KeyboardCode ) \u0026\u0026 a.KeyboardCode != \u0022None\u0022 ) _keys[a.Name] = a.KeyboardCode.ToLowerInvariant();\r\n\t\t}\r\n\t\treturn _keys.TryGetValue( action, out var k ) ? k : null;\r\n\t}\r\n\r\n\tstatic void RequestUse()\r\n\t{\r\n\t\tif ( !Networking.IsActive ) HandleUse( Guid.Empty );\r\n\t\telse UseRpc();\r\n\t}\r\n\r\n\t[Rpc.Host]\r\n\tpublic static void UseRpc()\r\n\t{\r\n\t\tvar caller = Rpc.Caller;\r\n\t\tif ( !PlayerSessions.Guard( caller, \u0022Player.Use\u0022, 5, 4, out _ ) ) return;\r\n\t\tHandleUse( caller.Id );\r\n\t}\r\n\r\n\tstatic void HandleUse( Guid id )\r\n\t{\r\n\t\tvar realm = LuaRuntime.Server;\r\n\t\tvar body = LuaPlayers.Find( id );\r\n\t\tif ( realm is null || body is null ) return;\r\n\r\n\t\tvar pc = body.Controller;\r\n\t\tvar start = pc?.EyePosition ?? body.WorldPosition;\r\n\t\tvar dir = (pc?.EyeAngles ?? default).Forward;\r\n\t\tvar tr = LuaEntities.Trace( realm, start, start \u002B dir * UseRange, body.GameObject ).AsTable;\r\n\t\tvar target = tr.Get( \u0022Entity\u0022 );\r\n\t\tif ( target.IsNil ) return;\r\n\r\n\t\trealm.RunHook( \u0022PlayerUse\u0022, LuaPlayers.Wrap( realm, id ), target );\r\n\t}\r\n}\r\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Scripting/Api/LuaPlayers.cs","FileName":"LuaPlayers.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing RoleplayFramework.Lua;\r\nusing RoleplayFramework.Net;\r\nusing RoleplayFramework.Players;\r\n\r\nnamespace RoleplayFramework.Scripting;\r\n\r\n/// \u003Csummary\u003EOpaque handle Lua holds for a player. Everything is looked up live, so a stale handle is simply invalid.\u003C/summary\u003E\r\ninternal sealed class PlayerHandle\r\n{\r\n\tpublic Guid ConnectionId;\r\n}\r\n\r\n/// \u003Csummary\u003E\r\n/// The \u003Cc\u003EPlayer\u003C/c\u003E type and \u003Cc\u003Eplayer\u003C/c\u003E library. Lua never gets the engine objects, only a handle with\r\n/// read-only methods; anything that changes state goes through validated framework functions.\r\n/// \u003C/summary\u003E\r\npublic static class LuaPlayers\r\n{\r\n\tpublic static void Register( LuaRealm realm )\r\n\t{\r\n\t\tvar L = realm.State;\r\n\t\tvar methods = new LuaTable();\r\n\t\tvar meta = new LuaTable();\r\n\t\tmeta.Set( \u0022__index\u0022, methods );\r\n\t\tmeta.Set( \u0022__metatable\u0022, \u0022Player\u0022 );\r\n\t\tLuaState.Register( meta, \u0022__tostring\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar p = Body( a, 0 );\r\n\t\t\treturn new LuaValue[] { p is null ? \u0022Player [NULL]\u0022 : $\u0022Player [{p.DisplayName}]\u0022 };\r\n\t\t} );\r\n\t\trealm.PlayerMeta = meta;\r\n\t\trealm.MethodTables[\u0022Player\u0022] = methods;\r\n\r\n\t\tLuaState.Register( methods, \u0022IsValid\u0022, ( s, a ) =\u003E new LuaValue[] { Body( a, 0 ) is not null } );\r\n\r\n\t\tLuaNativeFunction nick = ( s, a ) =\u003E new LuaValue[] { Check( a, \u0022Nick\u0022 ).DisplayName ?? \u0022\u0022 };\r\n\t\tLuaState.Register( methods, \u0022Nick\u0022, nick );\r\n\t\tLuaState.Register( methods, \u0022Name\u0022, nick );\r\n\t\tLuaState.Register( methods, \u0022GetName\u0022, nick );\r\n\r\n\t\tLuaState.Register( methods, \u0022SteamID\u0022, ( s, a ) =\u003E new LuaValue[] { Check( a, \u0022SteamID\u0022 ).SteamId ?? \u0022\u0022 } );\r\n\t\tLuaState.Register( methods, \u0022SteamID64\u0022, ( s, a ) =\u003E new LuaValue[] { Check( a, \u0022SteamID64\u0022 ).SteamId ?? \u0022\u0022 } );\r\n\r\n\t\tLuaState.Register( methods, \u0022Ping\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar c = Check( a, \u0022Ping\u0022 ).Connection;\r\n\t\t\treturn new LuaValue[] { c is null || c.IsHost ? 0 : Math.Round( c.Ping ) };\r\n\t\t} );\r\n\r\n\t\tLuaState.Register( methods, \u0022GetEyeAngles\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar pc = Check( a, \u0022GetEyeAngles\u0022 ).Controller;\r\n\t\t\treturn new[] { LuaConvert.FromAngles( s, pc?.EyeAngles ?? default ) };\r\n\t\t} );\r\n\r\n\t\tLuaState.Register( methods, \u0022GetShootPos\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar p = Check( a, \u0022GetShootPos\u0022 );\r\n\t\t\treturn new[] { LuaConvert.FromVector( s, p.Controller?.EyePosition ?? p.WorldPosition ) };\r\n\t\t} );\r\n\r\n\t\t// ply:GetEyeTrace([maxDistance]) -\u003E { Hit, HitPos, Distance, Entity, HitWorld }\r\n\t\tLuaState.Register( methods, \u0022GetEyeTrace\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar p = Check( a, \u0022GetEyeTrace\u0022 );\r\n\t\t\tvar dist = (float)Math.Clamp( LuaState.OptNumber( a, 1, \u0022GetEyeTrace\u0022, 4096 ), 1, 32768 );\r\n\t\t\tvar pc = p.Controller;\r\n\t\t\tvar start = pc?.EyePosition ?? p.WorldPosition;\r\n\t\t\tvar dir = (pc?.EyeAngles ?? default).Forward;\r\n\t\t\treturn new[] { LuaEntities.Trace( realm, start, start \u002B dir * dist, p.GameObject ) };\r\n\t\t} );\r\n\r\n\t\tLuaNetVars.AddMethods( realm, methods, ( a, name ) =\u003E Check( a, name ) );\r\n\t\tLuaAppearance.AddMethods( methods, ( a, name ) =\u003E Check( a, name ).GameObject, _ =\u003E realm.Kind == LuaRealmKind.Server, isPlayer: true );\r\n\t\tLuaClothing.AddPlayerMethods( methods, ( a, name ) =\u003E Check( a, name ).GameObject, realm.Kind == LuaRealmKind.Server );\r\n\r\n\t\tif ( realm.Kind == LuaRealmKind.Server )\r\n\t\t{\r\n\t\t\tLuaState.Register( methods, \u0022Kick\u0022, ( s, a ) =\u003E\r\n\t\t\t{\r\n\t\t\t\tvar p = Check( a, \u0022Kick\u0022 );\r\n\t\t\t\tvar reason = Net.FrameworkRpc.Bound( LuaState.OptString( a, 1, \u0022Kick\u0022, \u0022Kicked\u0022 ), 200 );\r\n\t\t\t\tvar c = p.Connection;\r\n\t\t\t\tif ( c is null || c == Connection.Local ) throw new LuaRuntimeException( \u0022cannot kick the host or an offline player\u0022 );\r\n\t\t\t\tvar session = PlayerSessions.Get( c.Id );\r\n\t\t\t\tif ( session is not null ) PlayerSessions.Reject( c, session, reason );\r\n\t\t\t\telse c.Kick( reason );\r\n\t\t\t\treturn null;\r\n\t\t\t} );\r\n\r\n\t\t\tLuaState.Register( methods, \u0022Spawn\u0022, ( s, a ) =\u003E\r\n\t\t\t{\r\n\t\t\t\tvar p = Check( a, \u0022Spawn\u0022 );\r\n\t\t\t\tPlayerManager.Current?.Respawn( p.ConnectionId );\r\n\t\t\t\treturn null;\r\n\t\t\t} );\r\n\r\n\t\t\tLuaState.Register( methods, \u0022SetPos\u0022, ( s, a ) =\u003E\r\n\t\t\t{\r\n\t\t\t\tvar p = Check( a, \u0022SetPos\u0022 );\r\n\t\t\t\tvar pos = LuaConvert.ToVector( LuaState.Arg( a, 1 ) );\r\n\t\t\t\tp.Teleport( pos, p.Controller?.EyeAngles ?? default );\r\n\t\t\t\treturn null;\r\n\t\t\t} );\r\n\t\t}\r\n\r\n\t\tLuaState.Register( methods, \u0022GetPos\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar pos = Check( a, \u0022GetPos\u0022 ).WorldPosition;\r\n\t\t\tvar ctor = s.Globals.Get( \u0022Vector\u0022 );\r\n\t\t\tif ( ctor.IsFunction ) return s.Call( ctor, pos.x, pos.y, pos.z );\r\n\t\t\tvar t = new LuaTable();\r\n\t\t\tt.Set( \u0022x\u0022, pos.x ); t.Set( \u0022y\u0022, pos.y ); t.Set( \u0022z\u0022, pos.z );\r\n\t\t\treturn new LuaValue[] { t };\r\n\t\t} );\r\n\r\n\t\tLuaState.Register( methods, \u0022IsLocalPlayer\u0022, ( s, a ) =\u003E new LuaValue[] { Check( a, \u0022IsLocalPlayer\u0022 ).IsLocalPlayer } );\r\n\r\n\t\tLuaState.Register( methods, \u0022IsListenServerHost\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar c = Check( a, \u0022IsListenServerHost\u0022 ).Connection;\r\n\t\t\treturn new LuaValue[] { c is not null \u0026\u0026 c.IsHost };\r\n\t\t} );\r\n\r\n\t\tLuaState.Register( methods, \u0022ChatPrint\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar p = Check( a, \u0022ChatPrint\u0022 );\r\n\t\t\tvar text = FrameworkText( LuaState.CheckString( a, 1, \u0022ChatPrint\u0022 ), 240 );\r\n\t\t\tif ( realm.Kind == LuaRealmKind.Server ) LuaNet.SendFramework( p.ConnectionId, \u0022rp.chatprint\u0022, text );\r\n\t\t\telse if ( p.IsLocalPlayer ) LuaNet.ShowChatPrint( realm, text );\r\n\t\t\treturn null;\r\n\t\t} );\r\n\r\n\t\tvar lib = L.GetOrCreateLibrary( \u0022player\u0022 );\r\n\t\tLuaState.Register( lib, \u0022GetAll\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar t = new LuaTable();\r\n\t\t\tforeach ( var p in Bodies() ) t.Append( Wrap( realm, p.ConnectionId ) );\r\n\t\t\treturn new LuaValue[] { t };\r\n\t\t} );\r\n\t\tLuaState.Register( lib, \u0022GetCount\u0022, ( s, a ) =\u003E new LuaValue[] { Bodies().Count() } );\r\n\r\n\t\tif ( realm.Kind == LuaRealmKind.Client )\r\n\t\t{\r\n\t\t\tL.Register( \u0022LocalPlayer\u0022, ( s, a ) =\u003E\r\n\t\t\t{\r\n\t\t\t\tvar me = RpPlayer.Local( Game.ActiveScene ) ?? Bodies().FirstOrDefault( b =\u003E b.ConnectionId == Guid.Empty );\r\n\t\t\t\treturn new LuaValue[] { me is null ? LuaValue.Nil : Wrap( realm, me.ConnectionId ) };\r\n\t\t\t} );\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EThis machine\u0027s own player as a Lua value in \u003Cparamref name=\u0022realm\u0022/\u003E, or nil (dedicated server, no body yet).\u003C/summary\u003E\r\n\tinternal static LuaValue LocalPlayerValue( LuaRealm realm )\r\n\t{\r\n\t\tif ( Application.IsDedicatedServer ) return LuaValue.Nil;\r\n\t\tvar me = RpPlayer.Local( Game.ActiveScene ) ?? Bodies().FirstOrDefault( b =\u003E b.ConnectionId == Guid.Empty );\r\n\t\treturn me is null ? LuaValue.Nil : Wrap( realm, me.ConnectionId );\r\n\t}\r\n\r\n\tstatic string FrameworkText( string s, int max ) =\u003E Net.FrameworkRpc.Bound( s, max );\r\n\r\n\tstatic IEnumerable\u003CRpPlayer\u003E Bodies() =\u003E RpPlayer.All( Game.ActiveScene ).Where( p =\u003E p.IsValid() );\r\n\r\n\tinternal static RpPlayer Find( Guid id ) =\u003E Bodies().FirstOrDefault( p =\u003E p.ConnectionId == id );\r\n\r\n\t/// \u003Csummary\u003EReturns the (cached) Lua handle for a connection, so the same player is always the same value (== works).\u003C/summary\u003E\r\n\tpublic static LuaValue Wrap( LuaRealm realm, Guid connectionId )\r\n\t{\r\n\t\tif ( !realm.PlayerCache.TryGetValue( connectionId, out var ud ) )\r\n\t\t{\r\n\t\t\tud = new LuaUserData( new PlayerHandle { ConnectionId = connectionId }, realm.PlayerMeta );\r\n\t\t\trealm.PlayerCache[connectionId] = ud;\r\n\t\t}\r\n\t\treturn LuaValue.FromUserData( ud );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EResolves a Lua argument to a player handle\u0027s connection id, or null.\u003C/summary\u003E\r\n\tinternal static Guid? HandleOf( LuaValue v ) =\u003E\r\n\t\tv.Type == LuaType.UserData \u0026\u0026 v.AsUserData.Value is PlayerHandle h ? h.ConnectionId : null;\r\n\r\n\tstatic RpPlayer Body( LuaValue[] a, int i ) =\u003E\r\n\t\tHandleOf( LuaState.Arg( a, i ) ) is { } id ? Find( id ) : null;\r\n\r\n\tstatic RpPlayer Check( LuaValue[] a, string method )\r\n\t{\r\n\t\tif ( HandleOf( LuaState.Arg( a, 0 ) ) is null ) throw new LuaRuntimeException( $\u0022calling \u0027{method}\u0027 on a non-player value (use ply:{method}())\u0022 );\r\n\t\treturn Body( a, 0 ) ?? throw new LuaRuntimeException( $\u0022calling \u0027{method}\u0027 on a disconnected player (check IsValid first)\u0022 );\r\n\t}\r\n}\r\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Scripting/Api/RpHalo.cs","FileName":"RpHalo.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing Sandbox.Rendering;\r\n\r\nnamespace RoleplayFramework.Scripting;\r\n\r\n/// \u003Csummary\u003E\r\n/// Garry\u0027s Mod style halos (halo.Add), client only, used by \u003Cc\u003Eent:SetHighlight(color, width, throughWalls, true)\u003C/c\u003E.\r\n/// Like GMod it works in screen space, every frame, in one command list on the main camera:\r\n/// \u003Clist type=\u0022number\u0022\u003E\r\n/// \u003Citem\u003Ethe haloed models are drawn as flat colour into a mask target (only where they\u0027re visible, unless ignoreZ),\u003C/item\u003E\r\n/// \u003Citem\u003Ethe mask is box-blurred (GMod\u0027s blurX / blurY),\u003C/item\u003E\r\n/// \u003Citem\u003Ethe blur is added onto the screen, except over the haloed objects themselves.\u003C/item\u003E\r\n/// \u003C/list\u003E\r\n/// Shaders: Assets/shaders/rp_halo_mask / rp_halo_blur / rp_halo_composite.\r\n/// \u003C/summary\u003E\r\npublic static class RpHalo\r\n{\r\n\tsealed class Entry\r\n\t{\r\n\t\tpublic GameObject Go;\r\n\t\tpublic Color Color;\r\n\t\tpublic float Radius;\r\n\t\tpublic bool IgnoreZ;\r\n\t}\r\n\r\n\tstatic readonly Dictionary\u003CGameObject, Entry\u003E _entries = new();\r\n\tstatic CommandList _cl;\r\n\tstatic CameraComponent _camera;\r\n\tstatic Material _mask, _blur, _composite;\r\n\tstatic bool _tried, _available;\r\n\r\n\t/// \u003Csummary\u003EHow opaque the halo is near the object (blurred coverage \u00D7 this, capped at 1).\u003C/summary\u003E\r\n\tpublic static float Intensity = 2.2f;\r\n\r\n\tstatic bool Load()\r\n\t{\r\n\t\tif ( _tried ) return _available;\r\n\t\t_tried = true;\r\n\t\ttry\r\n\t\t{\r\n\t\t\t_mask = Material.FromShader( \u0022shaders/rp_halo_mask.shader\u0022 );\r\n\t\t\t_blur = Material.FromShader( \u0022shaders/rp_halo_blur.shader\u0022 );\r\n\t\t\t_composite = Material.FromShader( \u0022shaders/rp_halo_composite.shader\u0022 );\r\n\t\t\t_available = _mask is not null \u0026\u0026 _blur is not null \u0026\u0026 _composite is not null;\r\n\t\t}\r\n\t\tcatch ( Exception e )\r\n\t\t{\r\n\t\t\tDiagnostics.RpLog.Warn( \u0022render\u0022, $\u0022Halo shaders unavailable ({e.Message})\u0022 );\r\n\t\t\t_available = false;\r\n\t\t}\r\n\t\treturn _available;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EAdds or updates a halo. \u003Cparamref name=\u0022radius\u0022/\u003E in pixels (blur size). False if halos can\u0027t render.\u003C/summary\u003E\r\n\tpublic static bool Set( GameObject go, Color color, float radius, bool ignoreZ )\r\n\t{\r\n\t\tif ( !go.IsValid() || !Load() ) return false;\r\n\t\t_entries[go] = new Entry { Go = go, Color = color, Radius = Math.Clamp( radius, 1f, 8f ), IgnoreZ = ignoreZ };\r\n\t\treturn true;\r\n\t}\r\n\r\n\tpublic static void Remove( GameObject go ) { if ( go is not null ) _entries.Remove( go ); }\r\n\r\n\tpublic static void Clear()\r\n\t{\r\n\t\t_entries.Clear();\r\n\t\tDetach();\r\n\t}\r\n\r\n\tstatic void Detach()\r\n\t{\r\n\t\tif ( _camera.IsValid() \u0026\u0026 _cl is not null ) _camera.RemoveCommandList( _cl );\r\n\t\t_camera = null;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EEvery frame (client): records the halo passes for this frame.\u003C/summary\u003E\r\n\tpublic static void Tick()\r\n\t{\r\n\t\tif ( _entries.Count \u003E 0 )\r\n\t\t\tforeach ( var dead in _entries.Keys.Where( g =\u003E !g.IsValid() ).ToList() ) _entries.Remove( dead );\r\n\r\n\t\tvar cam = Game.ActiveScene?.Camera;\r\n\t\tif ( _entries.Count == 0 || cam is null || !_available )\r\n\t\t{\r\n\t\t\tDetach();\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif ( _camera != cam )\r\n\t\t{\r\n\t\t\tDetach();\r\n\t\t\t_cl ??= new CommandList( \u0022rp halo\u0022 );\r\n\t\t\t_camera = cam;\r\n\t\t\t// After transparent objects, before the view model: the gun in your hands stays in front of the halo.\r\n\t\t\tcam.AddCommandList( _cl, Stage.AfterTransparent, 100 );\r\n\t\t}\r\n\t\tRecord( _cl );\r\n\t}\r\n\r\n\tstatic void Record( CommandList cl )\r\n\t{\r\n\t\tcl.Reset();\r\n\t\tvar transparent = new Color( 0, 0, 0, 0 );\r\n\r\n\t\t// 1. mask\r\n\t\tvar mask = cl.GetRenderTarget( \u0022rp_halo_mask\u0022, ImageFormat.RGBA8888, 1, 1 );\r\n\t\tcl.SetRenderTarget( mask );\r\n\t\tcl.Clear( transparent, true, false, false );\r\n\t\tforeach ( var e in _entries.Values )\r\n\t\t{\r\n\t\t\tcl.Set( \u0022HaloColor\u0022, new Vector4( e.Color.r, e.Color.g, e.Color.b, 1f ) );\r\n\t\t\tcl.Set( \u0022HaloIgnoreZ\u0022, e.IgnoreZ ? 1f : 0f );\r\n\t\t\tforeach ( var r in e.Go.Components.GetAll\u003CModelRenderer\u003E( FindMode.EnabledInSelfAndDescendants ) )\r\n\t\t\t\tcl.DrawRenderer( r, new RendererSetup { Material = _mask } );\r\n\t\t}\r\n\r\n\t\t// 2. blur (a 7 x 7 box blur in the shader)\r\n\t\tvar blur = cl.GetRenderTarget( \u0022rp_halo_blur\u0022, ImageFormat.RGBA8888, 1, 1 );\r\n\t\tcl.SetRenderTarget( blur );\r\n\t\tcl.Clear( transparent, true, false, false );\r\n\t\tcl.Set( \u0022HaloSource\u0022, mask.ColorTexture, 0 );\r\n\t\tcl.Blit( _blur );\r\n\r\n\t\t// 3. add onto the screen\r\n\t\tcl.ClearRenderTarget();\r\n\t\tcl.Set( \u0022HaloBlur\u0022, blur.ColorTexture, 0 );\r\n\t\tcl.Set( \u0022HaloMask\u0022, mask.ColorTexture, 0 );\r\n\t\tcl.Set( \u0022HaloIntensity\u0022, Intensity );\r\n\t\t// One colour per frame (the last added halo\u0027s); GMod\u0027s physgun halos all share the weapon colour too.\r\n\t\tvar tint = _entries.Values.Last().Color;\r\n\t\tcl.Set( \u0022HaloTint\u0022, new Vector4( tint.r, tint.g, tint.b, 1f ) );\r\n\t\tcl.Blit( _composite );\r\n\t}\r\n}\r\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Scripting/LuaRuntime.cs","FileName":"LuaRuntime.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\r\nusing System.Linq;\r\nusing RoleplayFramework.Diagnostics;\r\nusing RoleplayFramework.Lua;\r\n\r\nnamespace RoleplayFramework.Scripting;\r\n\r\n/// \u003Csummary\u003E\r\n/// Owns the session\u0027s Lua realms. The server realm runs on the host (and offline); the client realm runs\r\n/// wherever there is a local player. A listen host runs both. Realms live for one world session.\r\n/// \u003C/summary\u003E\r\npublic static class LuaRuntime\r\n{\r\n\tpublic static LuaRealm Server { get; private set; }\r\n\tpublic static LuaRealm Client { get; private set; }\r\n\r\n\t/// \u003Csummary\u003ESerialized content manifest the server sends to joining clients.\u003C/summary\u003E\r\n\tinternal static string ManifestJson { get; private set; }\r\n\tinternal static System.Collections.Generic.List\u003CContentFile\u003E ManifestFiles { get; private set; }\r\n\tinternal static System.Collections.Generic.Dictionary\u003Cstring, string\u003E ManifestTexts { get; private set; }\r\n\tpublic static int ManifestFileCount =\u003E ManifestFiles?.Count ?? 0;\r\n\r\n\tpublic static string ActiveGamemode =\u003E Server?.Gamemode?.Id ?? Client?.Gamemode?.Id;\r\n\tpublic static string ActiveGamemodeVersion =\u003E Server?.Gamemode?.Version ?? Client?.Gamemode?.Version;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Starts (or replaces) the server realm. The new scripts are loaded \u003Ci\u003Ebefore\u003C/i\u003E the running realm is stopped,\r\n\t/// so a reload with a broken file leaves the previous scripts running.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static bool StartServer( string gamemodeId, out string error )\r\n\t{\r\n\t\t// A fresh snapshot of exactly the files this world runs (data-folder copies override built-in gamemodes).\r\n\t\tvar fs = LuaSource.Snapshot();\r\n\t\tvar registry = GamemodeRegistry.Discover( fs );\r\n\r\n\t\tvar addons = ResolveAddons( fs, registry, gamemodeId, Bootstrap.FrameworkHost.Config.DisabledAddons );\r\n\r\n\t\tif ( Server is null ) LuaStorage.Begin( gamemodeId );\r\n\t\tvar realm = new LuaRealm( LuaRealmKind.Server, fs );\r\n\t\tif ( !Load( realm, registry, gamemodeId, addons, out error ) ) return false;\r\n\r\n\t\tSystem.Collections.Generic.List\u003CContentFile\u003E files;\r\n\t\tvar texts = new System.Collections.Generic.Dictionary\u003Cstring, string\u003E();\r\n\t\ttry\r\n\t\t{\r\n\t\t\t// Snapshot the texts now, so what clients download always matches the hashes even if files change later.\r\n\t\t\tfiles = LuaContent.Build( fs, registry, gamemodeId, texts, addons.LoadOrder );\r\n\t\t}\r\n\t\tcatch ( Exception e )\r\n\t\t{\r\n\t\t\terror = $\u0022could not build the content manifest: {e.Message}\u0022;\r\n\t\t\tRpLog.Error( \u0022lua\u0022, error );\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t// The new scripts loaded: retire the old realm (Shutdown hook, its entities) and switch over.\r\n\t\tStopRealm( LuaRealmKind.Server );\r\n\t\tLuaStorage.Begin( gamemodeId );\r\n\t\tManifestFiles = files;\r\n\t\tManifestTexts = texts;\r\n\t\tManifestJson = Json.Serialize( files );\r\n\t\tServer = realm;\r\n\t\tAddonRegistry.Current = addons;\r\n\t\taddons.LogSummary();\r\n\t\tRpLog.Info( \u0022lua\u0022, $\u0022Server realm ready: {realm.Gamemode.Id} {realm.Gamemode.Version}, {realm.LoadedFiles.Count} files, {realm.Addons.Count( a =\u003E a.Loaded )} addon(s), manifest {ManifestFileCount} files\u0022 );\r\n\t\trealm.RunHook( \u0022AddonsLoaded\u0022 );\r\n\t\trealm.RunHook( \u0022Initialize\u0022 );\r\n\t\treturn true;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EClient realm on the authority itself (offline / listen host): the same snapshot the server runs.\u003C/summary\u003E\r\n\tpublic static bool StartClient( string gamemodeId, out string error ) =\u003E StartClient( gamemodeId, LuaSource.Current ?? LuaSource.Snapshot(), out error );\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Client realm from a specific filesystem. \u003Cparamref name=\u0022fromServer\u0022/\u003E: a remote client\u0027s verified download, which\r\n\t/// holds exactly the server\u0027s active addons, so this machine\u0027s own DisabledAddons don\u0027t apply.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static bool StartClient( string gamemodeId, BaseFileSystem fs, out string error, bool fromServer = false )\r\n\t{\r\n\t\tStopRealm( LuaRealmKind.Client );\r\n\t\tvar registry = GamemodeRegistry.Discover( fs, makeCurrent: false );\r\n\t\tvar addons = ResolveAddons( fs, registry, gamemodeId, fromServer ? null : Bootstrap.FrameworkHost.Config.DisabledAddons );\r\n\r\n\t\tvar realm = new LuaRealm( LuaRealmKind.Client, fs );\r\n\t\tif ( !Load( realm, registry, gamemodeId, addons, out error ) ) return false;\r\n\r\n\t\tClient = realm;\r\n\t\tRpLog.Info( \u0022lua\u0022, $\u0022Client realm ready: {realm.Gamemode.Id} {realm.Gamemode.Version}, {realm.LoadedFiles.Count} files, {realm.Addons.Count( a =\u003E a.Loaded )} addon(s)\u0022 );\r\n\t\trealm.RunHook( \u0022AddonsLoaded\u0022 );\r\n\t\trealm.RunHook( \u0022Initialize\u0022 );\r\n\t\tRunDevAutorun( realm );\r\n\t\treturn true;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003Egame.GetMap() \u2192 current map id (\u0022minimal\u0022, \u0022thieves.rpdowntown3t\u0022, ...).\u003C/summary\u003E\r\n\tstatic void RegisterGameLibrary( LuaRealm realm )\r\n\t{\r\n\t\tvar g = realm.State.GetOrCreateLibrary( \u0022game\u0022 );\r\n\t\tLuaState.Register( g, \u0022GetMap\u0022, ( L, a ) =\u003E new LuaValue[] { CurrentMapId() } );\r\n\t\tLuaState.Register( g, \u0022IsDedicated\u0022, ( L, a ) =\u003E new LuaValue[] { Application.IsDedicatedServer } );\r\n\t\t// True when running inside the s\u0026box editor (play mode), where e.g. F1-F4 never reach the game.\r\n\t\tLuaState.Register( g, \u0022IsEditor\u0022, ( L, a ) =\u003E new LuaValue[] { Game.IsEditor } );\r\n\t\t// Session info for menus: server name (\u0022\u0022 offline), networked at all, and whether this machine is the authority.\r\n\t\tLuaState.Register( g, \u0022GetServerName\u0022, ( L, a ) =\u003E new LuaValue[] { Networking.IsActive ? (Net.SessionService.ActiveHost?.Name ?? Networking.ServerName ?? \u0022\u0022) : \u0022\u0022 } );\r\n\t\tLuaState.Register( g, \u0022IsMultiplayer\u0022, ( L, a ) =\u003E new LuaValue[] { Networking.IsActive } );\r\n\t\tLuaState.Register( g, \u0022IsHost\u0022, ( L, a ) =\u003E new LuaValue[] { !Networking.IsActive || Networking.IsHost } );\r\n\r\n\t\tif ( realm.Kind != LuaRealmKind.Client ) return;\r\n\r\n\t\t// game.LeaveToMenu(): disconnect (a host stops its server) and return to the main menu. Runs at the start of the\r\n\t\t// next frame, so the world isn\u0027t torn down while the calling Lua (e.g. a button handler) is still running.\r\n\t\tLuaState.Register( g, \u0022LeaveToMenu\u0022, ( L, a ) =\u003E { _leaveRequested = true; return null; } );\r\n\r\n\t\t// gui: s\u0026box\u0027s own overlays, under Garry\u0027s Mod names where they exist.\r\n\t\tvar gui = realm.State.GetOrCreateLibrary( \u0022gui\u0022 );\r\n\t\tLuaState.Register( gui, \u0022ActivateGameUI\u0022, ( L, a ) =\u003E { Game.Overlay.ShowPauseMenu(); return null; } );\r\n\t\tLuaState.Register( gui, \u0022HideGameUI\u0022, ( L, a ) =\u003E { Game.Overlay.Close(); return null; } );\r\n\t\tLuaState.Register( gui, \u0022OpenSettings\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar page = LuaState.Arg( a, 0 );\r\n\t\t\tvar name = page.IsString ? page.AsString : null;\r\n\t\t\tif ( name is not null \u0026\u0026 name is not (\u0022display\u0022 or \u0022graphics\u0022 or \u0022audio\u0022 or \u0022controls\u0022 or \u0022keybinds\u0022 or \u0022game\u0022 or \u0022storage\u0022 or \u0022developer\u0022 or \u0022about\u0022 or \u0022video\u0022 or \u0022input\u0022) )\r\n\t\t\t\tthrow LuaState.ArgError( 0, \u0022gui.OpenSettings\u0022, \u0022expected display, graphics, audio, controls, keybinds, game, storage, developer or about\u0022 );\r\n\t\t\tGame.Overlay.ShowSettingsModal( name );\r\n\t\t\treturn null;\r\n\t\t} );\r\n\t\tLuaState.Register( gui, \u0022OpenBinds\u0022, ( L, a ) =\u003E { Game.Overlay.ShowBinds(); return null; } );\r\n\t\tLuaState.Register( gui, \u0022OpenPlayerList\u0022, ( L, a ) =\u003E { Game.Overlay.ShowPlayerList(); return null; } );\r\n\t}\r\n\r\n\tstatic bool _leaveRequested;\r\n\r\n\tpublic static string CurrentMapId()\r\n\t{\r\n\t\tif ( !string.IsNullOrEmpty( Net.SessionService.CurrentMap ) ) return Net.SessionService.CurrentMap;\r\n\t\tvar map = Players.WorldMap.Find( Game.ActiveScene );\r\n\t\tif ( map is not null \u0026\u0026 !string.IsNullOrEmpty( map.MapName ) ) return map.MapName;\r\n\t\treturn Game.ActiveScene?.Name ?? \u0022\u0022;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Reloads the running gamemode from its source (the data folder for server owners). The server realm is\r\n\t/// swapped only if the new scripts load; then players get PlayerInitialSpawn/PlayerSpawn again and remote\r\n\t/// clients re-download and restart their client scripts.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static string Reload()\r\n\t{\r\n\t\tvar old = Server;\r\n\t\tif ( old is null ) return \u0022No gamemode is running. Start or host a world first.\u0022;\r\n\t\tvar gm = old.Gamemode.Id;\r\n\r\n\t\tif ( !StartServer( gm, out var error ) )\r\n\t\t\treturn $\u0022Reload failed - the previous scripts keep running. {error}\u0022;\r\n\r\n\t\t// The host\u0027s own client realm runs the same snapshot.\r\n\t\tif ( !Application.IsDedicatedServer \u0026\u0026 !StartClient( gm, out var cerr ) )\r\n\t\t\tRpLog.Error( \u0022lua\u0022, $\u0022Client scripts failed to reload: {cerr}\u0022 );\r\n\r\n\t\tPlayers.PlayerManager.Current?.OnLuaReloaded();\r\n\r\n\t\tint clients = 0;\r\n\t\tforeach ( var s in Players.PlayerSessions.All )\r\n\t\t{\r\n\t\t\tif ( s.State != Players.SessionState.Ready ) continue;\r\n\t\t\tvar c = Connection.Find( s.ConnectionId );\r\n\t\t\tif ( c is null || c == Connection.Local ) continue;\r\n\t\t\ts.State = Players.SessionState.AwaitingContent;\r\n\t\t\ts.ConnectedAt = RealTime.NowDouble; // restart the content timeout\r\n\t\t\tLuaContent.SendManifestTo( c );\r\n\t\t\tclients\u002B\u002B;\r\n\t\t}\r\n\r\n\t\treturn $\u0022Reloaded \u0027{gm}\u0027 ({Server.LoadedFiles.Count} files, {Server.Addons.Count( a =\u003E a.Loaded )} addon(s) from {(LuaSource.Origins.TryGetValue( gm, out var o ) ? o : \u0022?\u0022)}); {clients} remote client(s) are reloading theirs.\u0022;\r\n\t}\r\n\r\n\t[ConCmd( \u0022rp_lua_reload\u0022, Help = \u0022Reload the running gamemode\u0027s Lua (server/host only). Broken scripts are rejected and the old ones keep running.\u0022 )]\r\n\tpublic static void ReloadCommand()\r\n\t{\r\n\t\tif ( !Core.RealmInfo.IsAuthority ) { RpLog.Warn( \u0022lua\u0022, \u0022Only the server can reload Lua.\u0022 ); return; }\r\n\t\tRpLog.Info( \u0022lua\u0022, Reload() );\r\n\t}\r\n\r\n\t[ConCmd( \u0022rp_lua_restore\u0022, Help = \u0022Replace your data-folder copy of a gamemode with the game\u0027s version (your copy is backed up first): rp_lua_restore \u003Cid\u003E\u0022 )]\r\n\tpublic static void RestoreCommand( string id )\r\n\t{\r\n\t\tif ( !Core.RealmInfo.IsAuthority ) { RpLog.Warn( \u0022lua\u0022, \u0022Only the server can restore gamemodes.\u0022 ); return; }\r\n\t\tRpLog.Info( \u0022lua\u0022, LuaSource.Restore( id ) );\r\n\t}\r\n\r\n\tpublic const string DevAutorunPath = \u0022roleplay/dev/autorun_client.lua\u0022;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Development aid for multiplayer testing: when DevMode is on, a *remote client* runs\r\n\t/// data/roleplay/dev/autorun_client.lua (its own local file) after its scripts load. Off by default; the server\r\n\t/// never sends or trusts this file, and it can only do what any client Lua can do.\r\n\t/// \u003C/summary\u003E\r\n\tstatic void RunDevAutorun( LuaRealm realm )\r\n\t{\r\n\t\tif ( !Bootstrap.FrameworkHost.Config.DevMode || Core.RealmInfo.Role != Core.ProcessRole.Client ) return;\r\n\t\tvar fs = FileSystem.Data;\r\n\t\tif ( !fs.FileExists( DevAutorunPath ) ) return;\r\n\r\n\t\tRpLog.Warn( \u0022lua\u0022, $\u0022DevMode: running data/{DevAutorunPath} in the client realm\u0022 );\r\n\t\ttry\r\n\t\t{\r\n\t\t\tvar fn = realm.State.Load( fs.ReadAllText( DevAutorunPath ), \u0022dev/autorun_client.lua\u0022 );\r\n\t\t\trealm.Call( LuaValue.FromFunction( fn ) );\r\n\t\t}\r\n\t\tcatch ( LuaException e )\r\n\t\t{\r\n\t\t\trealm.Report( $\u0022dev autorun failed: {e.Message}\u0022, null );\r\n\t\t}\r\n\t}\r\n\r\n\tstatic AddonRegistry ResolveAddons( BaseFileSystem fs, GamemodeRegistry registry, string gamemodeId, System.Collections.Generic.IEnumerable\u003Cstring\u003E disabled ) =\u003E\r\n\t\tAddonRegistry.Resolve( fs, registry.LoadOrder( gamemodeId )?.ConvertAll( m =\u003E m.Id ), disabled );\r\n\r\n\tstatic bool Load( LuaRealm realm, GamemodeRegistry registry, string gamemodeId, AddonRegistry addons, out string error )\r\n\t{\r\n\t\terror = null;\r\n\t\tLuaPlayers.Register( realm );\r\n\t\tLuaEntities.Register( realm );\r\n\t\tLuaNet.Register( realm );\r\n\t\tGlobalNetVars.Register( realm );\r\n\t\tLuaStorage.Register( realm );\r\n\t\tLuaLog.Register( realm );\r\n\t\tLuaUi.Register( realm );\r\n\t\tLuaContentLib.Register( realm );\r\n\t\tRegisterGameLibrary( realm );\r\n\t\tif ( realm.Kind == LuaRealmKind.Client ) LuaHudModel.Register( realm );\r\n\t\tif ( realm.Kind == LuaRealmKind.Client ) LuaInput.Register( realm );\r\n\t\tLuaDraw.Register( realm );\r\n\t\tLuaClothing.RegisterLibrary( realm );\r\n\t\tLuaCookie.Register( realm );\r\n\t\tLuaKeybind.Register( realm );\r\n\t\tLuaJson.Register( realm );\r\n\t\tLuaConCommand.Register( realm );\r\n\t\tLuaDataFiles.Register( realm );\r\n\t\tLuaAddons.Register( realm );\r\n\t\tLuaPhysics.Register( realm );\r\n\t\tLuaRender.Register( realm );\r\n\t\tLuaView.Register( realm );\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\trealm.LoadFrameworkFiles();\r\n\t\t\trealm.LoadGamemode( registry, gamemodeId );\r\n\t\t\t// Addons after the gamemode: they can override GM functions and add hooks. A broken addon isn\u0027t fatal.\r\n\t\t\trealm.LoadAddons( addons?.LoadOrder ?? new System.Collections.Generic.List\u003CAddonManifest\u003E() );\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tcatch ( LuaRuntimeException e )\r\n\t\t{\r\n\t\t\terror = e.Message;\r\n\t\t\trealm.Report( $\u0022Gamemode \u0027{gamemodeId}\u0027 failed to load: {e.Message}\u0022, e.LuaTraceback );\r\n\t\t}\r\n\t\tcatch ( LuaException e )\r\n\t\t{\r\n\t\t\terror = e.Message;\r\n\t\t\trealm.Report( $\u0022Gamemode \u0027{gamemodeId}\u0027 failed to load: {e.Message}\u0022, null );\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\tpublic static void Tick()\r\n\t{\r\n\t\tif ( _leaveRequested )\r\n\t\t{\r\n\t\t\t_leaveRequested = false;\r\n\t\t\tNet.SessionService.LeaveToMenu();\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar now = Time.Now;\r\n\t\tServer?.Tick( now );\r\n\t\tClient?.Tick( now );\r\n\t\tServer?.RunHook( \u0022Think\u0022 );\r\n\t\tClient?.RunHook( \u0022Think\u0022 );\r\n\t\tif ( Client is not null )\r\n\t\t{\r\n\t\t\tLuaKeybind.Tick( Client );\r\n\t\t}\r\n\t\tLuaCookie.Tick();\r\n\t\tLuaDevReload.Tick();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Client: the Lua drawing hooks (PostDraw...Renderables, HUDPaint). Runs late in the frame (pre-render), after\r\n\t/// every update: beams and 3D2D use this frame\u0027s view, not the last one\u0027s.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void DrawFrame()\r\n\t{\r\n\t\tif ( Client is not null ) LuaDraw.Frame( Client );\r\n\t}\r\n\r\n\tstatic void StopRealm( LuaRealmKind kind )\r\n\t{\r\n\t\tvar realm = kind == LuaRealmKind.Server ? Server : Client;\r\n\t\tif ( realm is null ) return;\r\n\t\trealm.RunHook( \u0022Shutdown\u0022 );\r\n\r\n\t\t// Entities the realm created belong to it: remove them, so a reload doesn\u0027t duplicate doors, props, ...\r\n\t\tint removed = 0;\r\n\t\tforeach ( var go in realm.CreatedObjects )\r\n\t\t\tif ( go.IsValid() ) { go.Destroy(); removed\u002B\u002B; }\r\n\t\tif ( removed \u003E 0 ) RpLog.Info( \u0022lua\u0022, $\u0022{realm.Name} realm removed {removed} entities it had created\u0022 );\r\n\t\tif ( kind == LuaRealmKind.Server ) { LuaPhysics.Clear(); Server = null; ManifestJson = null; ManifestFiles = null; ManifestTexts = null; }\r\n\t\telse { Client = null; LuaRender.Reset(); LuaView.Reset(); LuaHudModel.Clear(); LuaUi.Reset(); LuaKeybind.Reset(); LuaCookie.Flush(); }\r\n\t\tRpLog.Info( \u0022lua\u0022, $\u0022{realm.Name} realm stopped\u0022 );\r\n\t}\r\n\r\n\tpublic static void Shutdown()\r\n\t{\r\n\t\tStopRealm( LuaRealmKind.Client );\r\n\t\tStopRealm( LuaRealmKind.Server );\r\n\t}\r\n}\r\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Core/MapCatalog.cs","FileName":"MapCatalog.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System.Collections.Generic;\nusing System.Text.RegularExpressions;\n\nnamespace RoleplayFramework.Core;\n\n/// \u003Csummary\u003E\n/// Map ids. A map is either\n/// \u003Clist type=\u0022bullet\u0022\u003E\n/// \u003Citem\u003Ea built-in scene of this project (e.g. \u0022minimal\u0022 \u2192 scenes/minimal.scene), or\u003C/item\u003E\n/// \u003Citem\u003Ea cloud map package ident from sbox.game (e.g. \u0022thieves.rpdowntown3t\u0022), loaded at runtime into\n/// \u003Csee cref=\u0022CloudWorldScene\u0022/\u003E through its networked MapInstance.\u003C/item\u003E\n/// \u003C/list\u003E\n/// \u003C/summary\u003E\npublic static class MapCatalog\n{\n\tpublic const string CloudWorldScene = \u0022scenes/world.scene\u0022;\n\n\tpublic static readonly IReadOnlyDictionary\u003Cstring, string\u003E BuiltInScenes = new Dictionary\u003Cstring, string\u003E\n\t{\n\t\t[\u0022minimal\u0022] = \u0022scenes/minimal.scene\u0022,\n\t};\n\n\tstatic readonly Regex PackageIdent = new( @\u0022^[a-z0-9_\\-]{1,64}\\.[a-z0-9_\\-]{1,64}$\u0022 );\n\n\tpublic static bool IsBuiltIn( string map ) =\u003E map is not null \u0026\u0026 BuiltInScenes.ContainsKey( map );\n\n\tpublic static bool IsCloud( string map ) =\u003E map is not null \u0026\u0026 !IsBuiltIn( map ) \u0026\u0026 PackageIdent.IsMatch( map );\n\n\t/// \u003Csummary\u003ENull if valid, else a user-facing reason.\u003C/summary\u003E\n\tpublic static string Validate( string map )\n\t{\n\t\tif ( string.IsNullOrWhiteSpace( map ) ) return \u0022No map selected.\u0022;\n\t\tif ( IsBuiltIn( map ) || IsCloud( map ) ) return null;\n\t\treturn $\u0022\u0027{map}\u0027 is not a built-in map ({string.Join( \u0022, \u0022, BuiltInScenes.Keys )}) or a package ident like org.mapname.\u0022;\n\t}\n\n\t/// \u003Csummary\u003EThe scene that hosts this map.\u003C/summary\u003E\n\tpublic static string SceneFor( string map ) =\u003E IsBuiltIn( map ) ? BuiltInScenes[map] : CloudWorldScene;\n}\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Core/RealmInfo.cs","FileName":"RealmInfo.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"namespace RoleplayFramework.Core;\n\n/// \u003Csummary\u003EWhat this process is right now. Changes over a session (menu \u2192 hosting \u2192 disconnected), so always read it live.\u003C/summary\u003E\npublic enum ProcessRole\n{\n\t/// \u003Csummary\u003ENot in a networked session (main menu, or offline in the editor).\u003C/summary\u003E\n\tOffline,\n\n\t/// \u003Csummary\u003EHeadless dedicated server: server realm only, no local player.\u003C/summary\u003E\n\tDedicatedServer,\n\n\t/// \u003Csummary\u003EListen/local server: this process is the server and also has a local player (server \u002B client realms).\u003C/summary\u003E\n\tListenHost,\n\n\t/// \u003Csummary\u003EConnected to someone else\u0027s server: client realm only.\u003C/summary\u003E\n\tClient,\n}\n\npublic static class RealmInfo\n{\n\tpublic static ProcessRole Role\n\t{\n\t\tget\n\t\t{\n\t\t\tif ( Application.IsDedicatedServer ) return ProcessRole.DedicatedServer;\n\t\t\tif ( !Networking.IsActive ) return ProcessRole.Offline;\n\t\t\treturn Networking.IsHost ? ProcessRole.ListenHost : ProcessRole.Client;\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003ETrue when this process owns authoritative gameplay state (dedicated server, listen host, or offline).\u003C/summary\u003E\n\tpublic static bool IsAuthority =\u003E Role != ProcessRole.Client;\n\n\t/// \u003Csummary\u003ETrue when this process renders UI for a local player.\u003C/summary\u003E\n\tpublic static bool HasLocalPlayer =\u003E Role != ProcessRole.DedicatedServer;\n\n\tpublic static string Describe() =\u003E Role switch\n\t{\n\t\tProcessRole.Offline =\u003E \u0022offline\u0022,\n\t\tProcessRole.DedicatedServer =\u003E \u0022dedicated server\u0022,\n\t\tProcessRole.ListenHost =\u003E \u0022listen host\u0022,\n\t\t_ =\u003E \u0022client\u0022,\n\t};\n}\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Scripting/Api/LuaKeybind.cs","FileName":"LuaKeybind.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing RoleplayFramework.Diagnostics;\nusing RoleplayFramework.Lua;\n\nnamespace RoleplayFramework.Scripting;\n\n/// \u003Csummary\u003E\n/// Client library \u003Cc\u003Ecookie\u003C/c\u003E (GMod-style): small values that persist on the player\u0027s machine, per gamemode.\n///   cookie.GetString(name [, default])  cookie.GetNumber(name [, default])  cookie.Set(name, value)  cookie.Delete(name)\n/// Stored in data/roleplay/cookies.json. Limits: 256 keys per gamemode, 1024 characters per value.\n/// \u003C/summary\u003E\npublic static class LuaCookie\n{\n\tpublic const string Path = \u0022roleplay/cookies.json\u0022;\n\tpublic const int MaxKeys = 256, MaxValueChars = 1024;\n\n\tstatic Dictionary\u003Cstring, Dictionary\u003Cstring, string\u003E\u003E _all;\n\tstatic bool _dirty;\n\tstatic RealTimeSince _sinceFlush;\n\tstatic readonly Regex NamePattern = new( @\u0022^[A-Za-z0-9_.\\-]{1,64}$\u0022 );\n\n\tstatic Dictionary\u003Cstring, Dictionary\u003Cstring, string\u003E\u003E All\n\t{\n\t\tget\n\t\t{\n\t\t\tif ( _all is not null ) return _all;\n\t\t\t_all = new();\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif ( FileSystem.Data.FileExists( Path ) \u0026\u0026 Json.TryDeserialize( FileSystem.Data.ReadAllText( Path ), out Dictionary\u003Cstring, Dictionary\u003Cstring, string\u003E\u003E d ) \u0026\u0026 d is not null )\n\t\t\t\t\t_all = d;\n\t\t\t}\n\t\t\tcatch ( Exception e ) { RpLog.Warn( \u0022cookie\u0022, $\u0022data/{Path} unreadable ({e.Message}); starting empty\u0022 ); }\n\t\t\treturn _all;\n\t\t}\n\t}\n\n\tstatic Dictionary\u003Cstring, string\u003E For( LuaRealm realm )\n\t{\n\t\tvar gm = realm.Gamemode?.Id ?? \u0022_\u0022;\n\t\tif ( !All.TryGetValue( gm, out var d ) ) All[gm] = d = new();\n\t\treturn d;\n\t}\n\n\tpublic static string Get( LuaRealm realm, string name ) =\u003E For( realm ).TryGetValue( name, out var v ) ? v : null;\n\n\tpublic static void Set( LuaRealm realm, string name, string value )\n\t{\n\t\tvar d = For( realm );\n\t\tif ( value is null ) { if ( d.Remove( name ) ) _dirty = true; return; }\n\t\tif ( !d.ContainsKey( name ) \u0026\u0026 d.Count \u003E= MaxKeys ) throw new LuaRuntimeException( $\u0022too many cookies (limit {MaxKeys})\u0022 );\n\t\tif ( value.Length \u003E MaxValueChars ) throw new LuaRuntimeException( $\u0022cookie value longer than {MaxValueChars} characters\u0022 );\n\t\tif ( d.TryGetValue( name, out var old ) \u0026\u0026 old == value ) return;\n\t\td[name] = value;\n\t\t_dirty = true;\n\t}\n\n\t/// \u003Csummary\u003EWrites pending changes at most every 2 seconds (and on \u003Csee cref=\u0022Flush\u0022/\u003E).\u003C/summary\u003E\n\tpublic static void Tick()\n\t{\n\t\tif ( _dirty \u0026\u0026 _sinceFlush \u003E 2 ) Flush();\n\t}\n\n\tpublic static void Flush()\n\t{\n\t\t_sinceFlush = 0;\n\t\tif ( !_dirty ) return;\n\t\t_dirty = false;\n\t\ttry\n\t\t{\n\t\t\tif ( !FileSystem.Data.DirectoryExists( \u0022roleplay\u0022 ) ) FileSystem.Data.CreateDirectory( \u0022roleplay\u0022 );\n\t\t\tCore.SafeDataFile.Write( Path, Json.Serialize( _all ) );\n\t\t}\n\t\tcatch ( Exception e ) { RpLog.Warn( \u0022cookie\u0022, $\u0022could not save cookies: {e.Message}\u0022 ); }\n\t}\n\n\tstatic string Name( LuaValue[] a, string fname )\n\t{\n\t\tvar n = LuaState.CheckString( a, 0, fname );\n\t\tif ( !NamePattern.IsMatch( n ) ) throw LuaState.ArgError( 0, fname, \u0022name: 1-64 characters of A-Z, a-z, 0-9, _ . -\u0022 );\n\t\treturn n;\n\t}\n\n\tpublic static void Register( LuaRealm realm )\n\t{\n\t\tif ( realm.Kind != LuaRealmKind.Client ) return;\n\t\tvar t = realm.State.GetOrCreateLibrary( \u0022cookie\u0022 );\n\t\tLuaState.Register( t, \u0022GetString\u0022, ( s, a ) =\u003E\n\t\t{\n\t\t\tvar v = Get( realm, Name( a, \u0022cookie.GetString\u0022 ) );\n\t\t\treturn new[] { v is not null ? LuaValue.FromString( v ) : LuaState.Arg( a, 1 ) };\n\t\t} );\n\t\tLuaState.Register( t, \u0022GetNumber\u0022, ( s, a ) =\u003E\n\t\t{\n\t\t\tvar v = Get( realm, Name( a, \u0022cookie.GetNumber\u0022 ) );\n\t\t\treturn new[] { v is not null \u0026\u0026 double.TryParse( v, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var d ) ? LuaValue.FromNumber( d ) : LuaState.Arg( a, 1 ) };\n\t\t} );\n\t\tLuaState.Register( t, \u0022Set\u0022, ( s, a ) =\u003E\n\t\t{\n\t\t\tvar v = LuaState.Arg( a, 1 );\n\t\t\tstring text = v.IsNil ? null : v.IsNumber ? v.Number.ToString( \u0022R\u0022, System.Globalization.CultureInfo.InvariantCulture ) : s.ToStringMeta( v );\n\t\t\tSet( realm, Name( a, \u0022cookie.Set\u0022 ), text );\n\t\t\treturn null;\n\t\t} );\n\t\tLuaState.Register( t, \u0022Delete\u0022, ( s, a ) =\u003E { Set( realm, Name( a, \u0022cookie.Delete\u0022 ), null ); return null; } );\n\t}\n}\n\n/// \u003Csummary\u003E\n/// Client library \u003Cc\u003Ekeybind\u003C/c\u003E: gamemode key bindings with labels that players can rebind, and that a HUD can show.\n///\n///   keybind.Register(id, { key = \u0022g\u0022 | action = \u0022Use\u0022, label = \u0022Drop item\u0022, category = \u0022Items\u0022, hint = true,\n///                          pressed = function() end, released = function() end, order = 10 })\n///   keybind.Remove(id)  keybind.GetAll() \u2192 { { id, label, category, key, keyname, action, hint, rebindable }, ... }\n///   keybind.GetKey(id)  keybind.GetKeyName(id)  keybind.IsDown(id)\n///   keybind.SetKey(id, key | nil)    (key binds only; saved in the player\u0027s cookies; nil = default)\n///   keybind.Capture(function(key) end)   (next key the player presses, for \u0022press a key\u0022 rebinding; nil if cancelled)\n///   keybind.KeyName(keyOrAction)  hook \u0022KeybindPressed\u0022(id) / \u0022KeybindReleased\u0022(id)\n/// Panels: p:SetKeyGlyph(keyOrAction) shows the engine\u0027s key/button glyph.\n///\n/// \u003Cc\u003Ekey\u003C/c\u003E is a raw keyboard/mouse key (rebindable by players here); \u003Cc\u003Eaction\u003C/c\u003E follows the game\u0027s input settings.\n/// F1-F12 and Escape are reserved by s\u0026amp;box and can\u0027t be used.\n/// \u003C/summary\u003E\npublic static class LuaKeybind\n{\n\tpublic const int MaxBinds = 128;\n\tstatic readonly Regex IdPattern = new( @\u0022^[a-z0-9_.]{1,48}$\u0022 );\n\tstatic readonly Regex KeyPattern = new( @\u0022^[a-z0-9_]{1,16}$\u0022 );\n\n\tsealed class Bind\n\t{\n\t\tpublic string Id, Label, Category, DefaultKey, Action;\n\t\tpublic bool Hint;\n\t\tpublic int Order, Seq;\n\t\tpublic LuaValue Pressed, Released;\n\t}\n\n\tstatic readonly Dictionary\u003Cstring, Bind\u003E _binds = new();\n\tstatic int _seq;\n\tstatic bool _capturing;\n\n\tpublic static void Reset()\n\t{\n\t\t_binds.Clear();\n\t\tif ( _capturing ) { try { Input.Keyboard.CancelCapture(); } catch ( Exception ) { } }\n\t\t_capturing = false;\n\t}\n\n\tstatic readonly Dictionary\u003Cstring, string\u003E Pretty = new()\n\t{\n\t\t[\u0022space\u0022] = \u0022Space\u0022, [\u0022enter\u0022] = \u0022Enter\u0022, [\u0022return\u0022] = \u0022Enter\u0022, [\u0022tab\u0022] = \u0022Tab\u0022, [\u0022shift\u0022] = \u0022Shift\u0022, [\u0022ctrl\u0022] = \u0022Ctrl\u0022, [\u0022alt\u0022] = \u0022Alt\u0022,\n\t\t[\u0022mouse1\u0022] = \u0022Mouse 1\u0022, [\u0022mouse2\u0022] = \u0022Mouse 2\u0022, [\u0022mouse3\u0022] = \u0022Mouse 3\u0022, [\u0022mouse4\u0022] = \u0022Mouse 4\u0022, [\u0022mouse5\u0022] = \u0022Mouse 5\u0022,\n\t\t[\u0022backspace\u0022] = \u0022Backspace\u0022, [\u0022capslock\u0022] = \u0022Caps Lock\u0022, [\u0022insert\u0022] = \u0022Insert\u0022, [\u0022delete\u0022] = \u0022Delete\u0022, [\u0022home\u0022] = \u0022Home\u0022,\n\t\t[\u0022end\u0022] = \u0022End\u0022, [\u0022pgup\u0022] = \u0022Page Up\u0022, [\u0022pgdn\u0022] = \u0022Page Down\u0022, [\u0022uparrow\u0022] = \u0022\u2191\u0022, [\u0022downarrow\u0022] = \u0022\u2193\u0022,\n\t\t[\u0022leftarrow\u0022] = \u0022\u2190\u0022, [\u0022rightarrow\u0022] = \u0022\u2192\u0022, [\u0022mwheelup\u0022] = \u0022Wheel Up\u0022, [\u0022mwheeldown\u0022] = \u0022Wheel Down\u0022,\n\t};\n\n\t/// \u003Csummary\u003EDisplay text for a raw key (\u0022m\u0022 \u2192 \u0022M\u0022) or an input action (\u0022Use\u0022 \u2192 its bound key).\u003C/summary\u003E\n\tpublic static string KeyName( string keyOrAction )\n\t{\n\t\tif ( string.IsNullOrEmpty( keyOrAction ) ) return \u0022?\u0022;\n\t\tif ( Input.GetActions().Any( a =\u003E a.Name == keyOrAction ) )\n\t\t{\n\t\t\tvar origin = Input.GetButtonOrigin( keyOrAction );\n\t\t\treturn string.IsNullOrEmpty( origin ) ? keyOrAction : KeyName( origin.ToLowerInvariant() );\n\t\t}\n\t\tvar k = keyOrAction.ToLowerInvariant();\n\t\tif ( Pretty.TryGetValue( k, out var p ) ) return p;\n\t\treturn k.Length \u003C= 2 ? k.ToUpperInvariant() : char.ToUpperInvariant( k[0] ) \u002B k.Substring( 1 );\n\t}\n\n\tstatic string EffectiveKey( LuaRealm realm, Bind b ) =\u003E\n\t\tb.Action is not null ? null : LuaCookie.Get( realm, \u0022keybind.\u0022 \u002B b.Id ) is { } custom \u0026\u0026 KeyPattern.IsMatch( custom ) ? custom : b.DefaultKey;\n\n\tstatic bool Safe( Func\u003Cbool\u003E f ) { try { return f(); } catch ( Exception ) { return false; } }\n\n\t/// \u003Csummary\u003EEvery frame on the client: fires pressed/released callbacks and hooks.\u003C/summary\u003E\n\tpublic static void Tick( LuaRealm realm )\n\t{\n\t\tif ( _binds.Count == 0 || _capturing ) return;\n\t\tbool typing = LuaUi.IsTyping;\n\t\tforeach ( var b in _binds.Values.ToList() )\n\t\t{\n\t\t\tvar key = EffectiveKey( realm, b );\n\t\t\tbool pressed = !typing \u0026\u0026 (b.Action is not null ? Input.Pressed( b.Action ) : Safe( () =\u003E Input.Keyboard.Pressed( key ) ));\n\t\t\tbool released = b.Action is not null ? Input.Released( b.Action ) : Safe( () =\u003E Input.Keyboard.Released( key ) );\n\t\t\tif ( pressed ) Fire( realm, b, b.Pressed, \u0022KeybindPressed\u0022 );\n\t\t\tif ( released ) Fire( realm, b, b.Released, \u0022KeybindReleased\u0022 );\n\t\t}\n\t}\n\n\tstatic void Fire( LuaRealm realm, Bind b, LuaValue fn, string hook )\n\t{\n\t\tif ( fn.IsFunction )\n\t\t{\n\t\t\ttry { realm.Call( fn ); }\n\t\t\tcatch ( LuaException e ) { realm.Report( $\u0022keybind \u0027{b.Id}\u0027: {e.Message}\u0022, (e as LuaRuntimeException)?.LuaTraceback ); }\n\t\t}\n\t\trealm.RunHook( hook, b.Id );\n\t}\n\n\tstatic Bind Get( LuaValue[] a, string fname )\n\t{\n\t\tvar id = LuaState.CheckString( a, 0, fname );\n\t\treturn _binds.TryGetValue( id, out var b ) ? b : throw LuaState.ArgError( 0, fname, $\u0022no keybind \u0027{id}\u0027\u0022 );\n\t}\n\n\tpublic static void Register( LuaRealm realm )\n\t{\n\t\tif ( realm.Kind != LuaRealmKind.Client ) return;\n\t\tvar t = realm.State.GetOrCreateLibrary( \u0022keybind\u0022 );\n\n\t\tLuaState.Register( t, \u0022Register\u0022, ( s, a ) =\u003E\n\t\t{\n\t\t\tvar id = LuaState.CheckString( a, 0, \u0022keybind.Register\u0022 );\n\t\t\tif ( !IdPattern.IsMatch( id ) ) throw LuaState.ArgError( 0, \u0022keybind.Register\u0022, \u0022id: 1-48 characters of a-z, 0-9, _ and .\u0022 );\n\t\t\tvar o = LuaState.CheckTable( a, 1, \u0022keybind.Register\u0022 );\n\t\t\tif ( !_binds.ContainsKey( id ) \u0026\u0026 _binds.Count \u003E= MaxBinds ) throw new LuaRuntimeException( $\u0022too many keybinds (limit {MaxBinds})\u0022 );\n\n\t\t\tstring Str( string k, int max ) { var v = o.Get( k ); return v.IsString ? (v.AsString.Length \u003E max ? v.AsString.Substring( 0, max ) : v.AsString) : null; }\n\t\t\tvar b = new Bind\n\t\t\t{\n\t\t\t\tId = id,\n\t\t\t\tLabel = Str( \u0022label\u0022, 64 ) ?? id,\n\t\t\t\tCategory = Str( \u0022category\u0022, 32 ) ?? \u0022General\u0022,\n\t\t\t\tHint = o.Get( \u0022hint\u0022 ).IsTruthy,\n\t\t\t\tOrder = LuaState.ToNumber( o.Get( \u0022order\u0022 ), out var ord ) ? (int)ord : 0,\n\t\t\t\tSeq = _binds.TryGetValue( id, out var old ) ? old.Seq : \u002B\u002B_seq,\n\t\t\t\tPressed = o.Get( \u0022pressed\u0022 ),\n\t\t\t\tReleased = o.Get( \u0022released\u0022 ),\n\t\t\t};\n\t\t\tvar action = Str( \u0022action\u0022, 32 );\n\t\t\tvar key = Str( \u0022key\u0022, 16 )?.Trim().ToLowerInvariant();\n\t\t\tif ( action is not null )\n\t\t\t{\n\t\t\t\tif ( !Input.GetActions().Any( x =\u003E x.Name == action ) ) throw LuaState.ArgError( 1, \u0022keybind.Register\u0022, $\u0022unknown input action \u0027{action}\u0027\u0022 );\n\t\t\t\tb.Action = action;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif ( key is null || !KeyPattern.IsMatch( key ) ) throw LuaState.ArgError( 1, \u0022keybind.Register\u0022, \u0022needs key = \\\u0022g\\\u0022 (a key name) or action = \\\u0022Use\\\u0022\u0022 );\n\t\t\t\tif ( Regex.IsMatch( key, @\u0022^f([1-9]|1[0-2])$\u0022 ) || key == \u0022escape\u0022 )\n\t\t\t\t\tthrow LuaState.ArgError( 1, \u0022keybind.Register\u0022, $\u0022\u0027{key}\u0027 is reserved by s\u0026box (F1-F12 and Escape can\u0027t be used by games)\u0022 );\n\t\t\t\tb.DefaultKey = key;\n\t\t\t}\n\t\t\t_binds[id] = b;\n\t\t\treturn null;\n\t\t} );\n\n\t\tLuaState.Register( t, \u0022Remove\u0022, ( s, a ) =\u003E { _binds.Remove( LuaState.CheckString( a, 0, \u0022keybind.Remove\u0022 ) ); return null; } );\n\n\t\tLuaState.Register( t, \u0022GetAll\u0022, ( s, a ) =\u003E\n\t\t{\n\t\t\tvar list = new LuaTable();\n\t\t\tforeach ( var b in _binds.Values.OrderBy( b =\u003E b.Category ).ThenBy( b =\u003E b.Order ).ThenBy( b =\u003E b.Seq ) )\n\t\t\t{\n\t\t\t\tvar e = new LuaTable();\n\t\t\t\te.Set( \u0022id\u0022, b.Id ); e.Set( \u0022label\u0022, b.Label ); e.Set( \u0022category\u0022, b.Category );\n\t\t\t\tvar key = EffectiveKey( realm, b );\n\t\t\t\te.Set( \u0022key\u0022, key is null ? LuaValue.Nil : LuaValue.FromString( key ) );\n\t\t\t\te.Set( \u0022action\u0022, b.Action is null ? LuaValue.Nil : LuaValue.FromString( b.Action ) );\n\t\t\t\te.Set( \u0022keyname\u0022, KeyName( b.Action ?? key ) );\n\t\t\t\te.Set( \u0022hint\u0022, b.Hint );\n\t\t\t\te.Set( \u0022rebindable\u0022, b.Action is null );\n\t\t\t\tlist.Append( e );\n\t\t\t}\n\t\t\treturn new LuaValue[] { list };\n\t\t} );\n\n\t\tLuaState.Register( t, \u0022GetKey\u0022, ( s, a ) =\u003E\n\t\t{\n\t\t\tvar b = Get( a, \u0022keybind.GetKey\u0022 );\n\t\t\treturn new[] { LuaValue.FromString( b.Action is not null ? (Input.GetButtonOrigin( b.Action ) ?? \u0022\u0022).ToLowerInvariant() : EffectiveKey( realm, b ) ) };\n\t\t} );\n\t\tLuaState.Register( t, \u0022GetKeyName\u0022, ( s, a ) =\u003E { var b = Get( a, \u0022keybind.GetKeyName\u0022 ); return new LuaValue[] { KeyName( b.Action ?? EffectiveKey( realm, b ) ) }; } );\n\t\tLuaState.Register( t, \u0022IsDown\u0022, ( s, a ) =\u003E\n\t\t{\n\t\t\tvar b = Get( a, \u0022keybind.IsDown\u0022 );\n\t\t\tvar key = EffectiveKey( realm, b );\n\t\t\treturn new LuaValue[] { !LuaUi.IsTyping \u0026\u0026 (b.Action is not null ? Input.Down( b.Action ) : Safe( () =\u003E Input.Keyboard.Down( key ) )) };\n\t\t} );\n\t\tLuaState.Register( t, \u0022SetKey\u0022, ( s, a ) =\u003E\n\t\t{\n\t\t\tvar b = Get( a, \u0022keybind.SetKey\u0022 );\n\t\t\tif ( b.Action is not null ) throw new LuaRuntimeException( $\u0022keybind \u0027{b.Id}\u0027 follows the input action \u0027{b.Action}\u0027; players change it in the game\u0027s settings\u0022 );\n\t\t\tvar arg = LuaState.Arg( a, 1 );\n\t\t\tif ( arg.IsNil ) { LuaCookie.Set( realm, \u0022keybind.\u0022 \u002B b.Id, null ); return null; }\n\t\t\tvar key = LuaState.CheckString( a, 1, \u0022keybind.SetKey\u0022 ).Trim().ToLowerInvariant();\n\t\t\tif ( !KeyPattern.IsMatch( key ) || Regex.IsMatch( key, @\u0022^f([1-9]|1[0-2])$\u0022 ) || key == \u0022escape\u0022 )\n\t\t\t\tthrow LuaState.ArgError( 1, \u0022keybind.SetKey\u0022, $\u0022\u0027{key}\u0027 can\u0027t be bound\u0022 );\n\t\t\tLuaCookie.Set( realm, \u0022keybind.\u0022 \u002B b.Id, key == b.DefaultKey ? null : key );\n\t\t\treturn null;\n\t\t} );\n\t\tLuaState.Register( t, \u0022KeyName\u0022, ( s, a ) =\u003E new LuaValue[] { KeyName( LuaState.CheckString( a, 0, \u0022keybind.KeyName\u0022 ) ) } );\n\n\t\tLuaState.Register( t, \u0022Capture\u0022, ( s, a ) =\u003E\n\t\t{\n\t\t\tvar fn = LuaState.Arg( a, 0 );\n\t\t\tif ( !fn.IsFunction ) throw LuaState.ArgError( 0, \u0022keybind.Capture\u0022, \u0022function expected\u0022 );\n\t\t\t_capturing = true;\n\t\t\tInput.Keyboard.Capture( buttons =\u003E\n\t\t\t{\n\t\t\t\t_capturing = false;\n\t\t\t\tif ( LuaRuntime.Client != realm ) return; // realm reloaded meanwhile\n\t\t\t\tvar key = buttons is { Count: \u003E 0 } ? buttons[buttons.Count - 1].ToLowerInvariant() : null;\n\t\t\t\ttry { realm.Call( fn, key is null ? LuaValue.Nil : LuaValue.FromString( key ) ); }\n\t\t\t\tcatch ( LuaException e ) { realm.Report( $\u0022keybind.Capture callback: {e.Message}\u0022, null ); }\n\t\t\t} );\n\t\t\treturn null;\n\t\t} );\n\t}\n}\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Scripting/Api/LuaUi.World.cs","FileName":"LuaUi.World.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing RoleplayFramework.Lua;\r\nusing Sandbox.UI;\r\n\r\nnamespace RoleplayFramework.Scripting;\r\n\r\n/// \u003Csummary\u003E\r\n/// Retained 3D UI: panels placed in the world (client only).\r\n///\r\n///   local p = ui.CreateWorld({ pos = Vector, ang = Angle, scale = 0.1, width = 512, height = 256,\r\n///                              parent = ent|ply, facecamera = false, anchor = \u0022center\u0022|\u0022topleft\u0022, classes = \u0022\u0022 })\r\n///   p:SetWorldPos(v)  p:SetWorldAngles(a)  p:SetWorldScale(s)  p:AttachTo(ent|ply|nil [, offset [, ang]])  p:SetFaceCamera(b)\r\n///\r\n/// The returned panel is a normal Lua panel: add children with ui.Create(kind, p), style them with ui.AddStyle/SetStyle.\r\n/// Orientation follows GMod\u0027s cam.Start3D2D: x runs along ang:Forward(), y along ang:Right(), and the readable side\r\n/// faces ang:Up(). scale = world units per pixel (GMod\u0027s 0.1 means 10 pixels per unit).\r\n/// \u003C/summary\u003E\r\npublic static partial class LuaUi\r\n{\r\n\tpublic const int MaxWorldPanels = 512;\r\n\r\n\t/// \u003Csummary\u003EEngine world panels: 1 pixel = this many units at GameObject scale 1.\u003C/summary\u003E\r\n\tpublic const float EnginePixelSize = 0.05f;\r\n\r\n\tstatic readonly Dictionary\u003CPanel, GameObject\u003E _worldRoots = new();\r\n\tstatic readonly Dictionary\u003CPanel, Vector2\u003E _worldCssSize = new();\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The object scale also scales the CSS pixels inside an engine world panel, but not its PanelSize, so the panel\r\n\t/// area has to grow with it for the CSS size to stay what Lua asked for.\r\n\t/// \u003C/summary\u003E\r\n\tinternal static void ApplyScale( GameObject go, Vector2 cssSize, double unitsPerPixel )\r\n\t{\r\n\t\tvar s = ObjectScaleFor( unitsPerPixel );\r\n\t\tgo.WorldScale = s;\r\n\t\tgo.Components.Get\u003CSandbox.WorldPanel\u003E().PanelSize = cssSize * s;\r\n\t}\r\n\r\n\tstatic void ResetWorld()\r\n\t{\r\n\t\tforeach ( var go in _worldRoots.Values ) if ( go.IsValid() ) go.Destroy();\r\n\t\t_worldRoots.Clear();\r\n\t\t_worldCssSize.Clear();\r\n\t\tLuaDraw.Reset();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EGMod 3D2D angles \u2192 the rotation of an engine world panel (which faces its Forward, x along Left).\u003C/summary\u003E\r\n\tpublic static Rotation From3D2D( Angles a )\r\n\t{\r\n\t\tvar r = a.ToRotation();\r\n\t\treturn Rotation.LookAt( r.Up, -r.Right );\r\n\t}\r\n\r\n\tpublic static float ObjectScaleFor( double unitsPerPixel ) =\u003E (float)Math.Clamp( unitsPerPixel, 0.001, 10 ) / EnginePixelSize;\r\n\r\n\tinternal static GameObject CreateWorldObject( string name, Vector2 size, bool centered )\r\n\t{\r\n\t\tvar go = new GameObject( true, name );\r\n\t\tgo.NetworkMode = NetworkMode.Never;\r\n\t\tvar wp = go.Components.Create\u003CSandbox.WorldPanel\u003E();\r\n\t\twp.PanelSize = size;\r\n\t\twp.HorizontalAlign = centered ? Sandbox.WorldPanel.HAlignment.Center : Sandbox.WorldPanel.HAlignment.Left;\r\n\t\twp.VerticalAlign = centered ? Sandbox.WorldPanel.VAlignment.Center : Sandbox.WorldPanel.VAlignment.Top;\r\n\t\twp.InteractionRange = 0;\r\n\t\treturn go;\r\n\t}\r\n\r\n\tstatic GameObject ObjectOf( LuaValue v )\r\n\t{\r\n\t\tif ( LuaEntities.HandleOf( v ) is { } eid ) return Game.ActiveScene?.Directory.FindByGuid( eid );\r\n\t\tif ( LuaPlayers.HandleOf( v ) is { } pid ) return LuaPlayers.Find( pid )?.GameObject;\r\n\t\treturn null;\r\n\t}\r\n\r\n\tstatic void RegisterWorld( LuaRealm realm, LuaTable ui, Action\u003Cstring, LuaNativeFunction\u003E M )\r\n\t{\r\n\t\tLuaState.Register( ui, \u0022CreateWorld\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar o = LuaState.Arg( a, 0 ).IsTable ? LuaState.Arg( a, 0 ).AsTable : new LuaTable();\r\n\t\t\t_worldRoots.Keys.Where( p =\u003E !p.IsValid() ).ToList().ForEach( p =\u003E _worldRoots.Remove( p ) );\r\n\t\t\tif ( _worldRoots.Count \u003E= MaxWorldPanels ) throw new LuaRuntimeException( $\u0022too many world panels (limit {MaxWorldPanels})\u0022 );\r\n\r\n\t\t\tdouble Num( string k, double def ) =\u003E LuaState.ToNumber( o.Get( k ), out var d ) ? d : def;\r\n\t\t\tvar w = (float)Math.Clamp( Num( \u0022width\u0022, 512 ), 1, 4096 );\r\n\t\t\tvar h = (float)Math.Clamp( Num( \u0022height\u0022, 256 ), 1, 4096 );\r\n\t\t\tvar centered = !(o.Get( \u0022anchor\u0022 ).IsString \u0026\u0026 o.Get( \u0022anchor\u0022 ).AsString == \u0022topleft\u0022);\r\n\r\n\t\t\tvar go = CreateWorldObject( \u0022lua world panel\u0022, new Vector2( w, h ), centered );\r\n\t\t\tvar wp = go.Components.Get\u003CSandbox.WorldPanel\u003E();\r\n\t\t\twp.LookAtCamera = o.Get( \u0022facecamera\u0022 ).IsTruthy;\r\n\r\n\t\t\tvar parentObj = ObjectOf( o.Get( \u0022parent\u0022 ) );\r\n\t\t\tvar pos = o.Get( \u0022pos\u0022 ).IsNil ? Vector3.Zero : LuaConvert.ToVector( o.Get( \u0022pos\u0022 ), \u0022pos\u0022 );\r\n\t\t\tvar ang = o.Get( \u0022ang\u0022 ).IsNil ? new Angles( 0, 0, 0 ) : LuaConvert.ToAngles( o.Get( \u0022ang\u0022 ), \u0022ang\u0022 );\r\n\t\t\tif ( parentObj is not null )\r\n\t\t\t{\r\n\t\t\t\tgo.SetParent( parentObj, false );\r\n\t\t\t\tgo.LocalPosition = pos;\r\n\t\t\t\tgo.LocalRotation = From3D2D( ang );\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tgo.WorldPosition = pos;\r\n\t\t\t\tgo.WorldRotation = From3D2D( ang );\r\n\t\t\t}\r\n\r\n\t\t\tApplyScale( go, new Vector2( w, h ), Num( \u0022scale\u0022, 0.1 ) ); // after parenting: world scale, not relative to the entity\r\n\r\n\t\t\tvar root = wp.GetPanel();\r\n\t\t\troot.StyleSheet.Parse( BaseCss, false );\r\n\t\t\tforeach ( var css in _css ) root.StyleSheet.Parse( css, false );\r\n\t\t\troot.AddClass( \u0022lua-world\u0022 );\r\n\t\t\tvar classes = o.Get( \u0022classes\u0022 ).IsString ? o.Get( \u0022classes\u0022 ).AsString : \u0022\u0022;\r\n\t\t\tif ( !string.IsNullOrWhiteSpace( classes ) ) root.AddClass( classes );\r\n\r\n\t\t\t_worldRoots[root] = go;\r\n\t\t\t_worldCssSize[root] = new Vector2( w, h );\r\n\t\t\treturn new[] { Wrap( root ) };\r\n\t\t} );\r\n\r\n\t\tGameObject WorldGo( LuaValue[] a, string name )\r\n\t\t{\r\n\t\t\tvar p = Check( a, name );\r\n\t\t\treturn _worldRoots.TryGetValue( p, out var go ) \u0026\u0026 go.IsValid() ? go\r\n\t\t\t\t: throw new LuaRuntimeException( $\u0022{name} needs a panel made with ui.CreateWorld\u0022 );\r\n\t\t}\r\n\r\n\t\tM( \u0022SetWorldPos\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar go = WorldGo( a, \u0022SetWorldPos\u0022 );\r\n\t\t\tvar v = LuaConvert.ToVector( LuaState.Arg( a, 1 ) );\r\n\t\t\tif ( go.Parent is not null \u0026\u0026 go.Parent != Game.ActiveScene ) go.LocalPosition = v; else go.WorldPosition = v;\r\n\t\t\treturn null;\r\n\t\t} );\r\n\t\tM( \u0022SetWorldAngles\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar go = WorldGo( a, \u0022SetWorldAngles\u0022 );\r\n\t\t\tvar r = From3D2D( LuaConvert.ToAngles( LuaState.Arg( a, 1 ) ) );\r\n\t\t\tif ( go.Parent is not null \u0026\u0026 go.Parent != Game.ActiveScene ) go.LocalRotation = r; else go.WorldRotation = r;\r\n\t\t\treturn null;\r\n\t\t} );\r\n\t\tM( \u0022SetWorldScale\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar go = WorldGo( a, \u0022SetWorldScale\u0022 );\r\n\t\t\tApplyScale( go, _worldCssSize.TryGetValue( Check( a, \u0022SetWorldScale\u0022 ), out var css ) ? css : new Vector2( 512, 256 ), LuaState.CheckNumber( a, 1, \u0022SetWorldScale\u0022 ) );\r\n\t\t\treturn null;\r\n\t\t} );\r\n\t\tM( \u0022SetFaceCamera\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tWorldGo( a, \u0022SetFaceCamera\u0022 ).Components.Get\u003CSandbox.WorldPanel\u003E().LookAtCamera = LuaState.Arg( a, 1 ).IsTruthy;\r\n\t\t\treturn null;\r\n\t\t} );\r\n\t\tM( \u0022AttachTo\u0022, ( s, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar go = WorldGo( a, \u0022AttachTo\u0022 );\r\n\t\t\tvar scale = go.WorldScale;\r\n\t\t\tvar target = ObjectOf( LuaState.Arg( a, 1 ) );\r\n\t\t\tif ( target is null )\r\n\t\t\t{\r\n\t\t\t\tvar wpos = go.WorldPosition; var wrot = go.WorldRotation;\r\n\t\t\t\tgo.SetParent( null, false );\r\n\t\t\t\tgo.WorldPosition = wpos; go.WorldRotation = wrot;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tgo.SetParent( target, false );\r\n\t\t\t\tgo.LocalPosition = LuaState.Arg( a, 2 ).IsNil ? Vector3.Zero : LuaConvert.ToVector( LuaState.Arg( a, 2 ), \u0022offset\u0022 );\r\n\t\t\t\tgo.LocalRotation = From3D2D( LuaState.Arg( a, 3 ).IsNil ? new Angles( 0, 0, 0 ) : LuaConvert.ToAngles( LuaState.Arg( a, 3 ), \u0022ang\u0022 ) );\r\n\t\t\t}\r\n\t\t\tgo.WorldScale = scale;\r\n\t\t\treturn null;\r\n\t\t} );\r\n\t}\r\n}\r\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Scripting/LuaRealm.cs","FileName":"LuaRealm.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing RoleplayFramework.Diagnostics;\r\nusing RoleplayFramework.Lua;\r\n\r\nnamespace RoleplayFramework.Scripting;\r\n\r\npublic enum LuaRealmKind\r\n{\r\n\t/// \u003Csummary\u003EOnly used to classify files (sh_). Shared files run inside both the server and the client state.\u003C/summary\u003E\r\n\tShared,\r\n\tServer,\r\n\tClient,\r\n}\r\n\r\npublic readonly record struct ScriptError( DateTime TimeUtc, string Realm, string Gamemode, string Message, string Traceback );\r\n\r\n/// \u003Csummary\u003E\r\n/// One Lua environment: the server state or the client state. Shared (sh_) files run in both, like Garry\u0027s Mod.\r\n/// Owns file loading (\u003Cc\u003Einclude\u003C/c\u003E), timers and error reporting. Every engine\u2192Lua call goes through\r\n/// \u003Csee cref=\u0022Call\u0022/\u003E, which never throws: script failures are reported and the host keeps running.\r\n/// \u003C/summary\u003E\r\npublic sealed class LuaRealm\r\n{\r\n\tpublic const string FrameworkRoot = \u0022lua/framework\u0022;\r\n\tconst int MaxIncludeDepth = 16;\r\n\tconst int MaxTimers = 512;\r\n\r\n\tpublic LuaRealmKind Kind { get; }\r\n\tpublic LuaState State { get; }\r\n\tpublic string Name =\u003E Kind == LuaRealmKind.Server ? \u0022server\u0022 : \u0022client\u0022;\r\n\tpublic GamemodeManifest Gamemode { get; private set; }\r\n\tpublic LuaTable GM { get; private set; }\r\n\tpublic IReadOnlyList\u003Cstring\u003E LoadedFiles =\u003E _loaded;\r\n\r\n\t// Per-realm state for the API libraries.\r\n\tinternal LuaTable PlayerMeta;\r\n\tinternal readonly Dictionary\u003CGuid, LuaUserData\u003E PlayerCache = new();\r\n\tinternal readonly Dictionary\u003Cstring, LuaNet.Receiver\u003E NetReceivers = new();\r\n\tinternal LuaTable EntityMeta;\r\n\r\n\t/// \u003Csummary\u003EMethod tables Lua may extend via FindMetaTable(name): \u0022Player\u0022, \u0022Entity\u0022, \u0022Panel\u0022.\u003C/summary\u003E\r\n\tinternal readonly Dictionary\u003Cstring, LuaTable\u003E MethodTables = new();\r\n\tinternal readonly Dictionary\u003CGuid, LuaUserData\u003E EntityCache = new();\r\n\tinternal int EntitiesCreated;\r\n\r\n\t/// \u003Csummary\u003EObjects created through ents.Create; removed when the realm stops (reload, world end).\u003C/summary\u003E\r\n\tinternal readonly List\u003CGameObject\u003E CreatedObjects = new();\r\n\r\n\treadonly BaseFileSystem _fs;\r\n\r\n\t/// \u003Csummary\u003EThe file system this realm loads scripts from (snapshot or downloaded server copy).\u003C/summary\u003E\r\n\tpublic BaseFileSystem Files =\u003E _fs;\r\n\treadonly List\u003Cstring\u003E _loaded = new();\r\n\treadonly Stack\u003Cstring\u003E _roots = new();\r\n\r\n\tstatic readonly List\u003CScriptError\u003E _errors = new();\r\n\tpublic static IReadOnlyList\u003CScriptError\u003E RecentErrors =\u003E _errors;\r\n\r\n\t/// \u003Csummary\u003ERaised for each script error (used by tests and diagnostics).\u003C/summary\u003E\r\n\tpublic static event Action\u003CScriptError\u003E OnScriptError;\r\n\r\n\tpublic LuaRealm( LuaRealmKind kind, BaseFileSystem fs )\r\n\t{\r\n\t\tif ( kind == LuaRealmKind.Shared ) throw new ArgumentException( \u0022A realm is Server or Client; shared files run in both\u0022 );\r\n\r\n\t\tKind = kind;\r\n\t\t_fs = fs;\r\n\t\tState = new LuaState( Name );\r\n\t\tState.PrintHandler = line =\u003E RpLog.Info( \u0022lua\u0022, $\u0022[{Name}] {line}\u0022 );\r\n\r\n\t\tvar G = State.Globals;\r\n\t\tG.Set( \u0022SERVER\u0022, kind == LuaRealmKind.Server );\r\n\t\tG.Set( \u0022CLIENT\u0022, kind == LuaRealmKind.Client );\r\n\t\tG.Set( \u0022REALM\u0022, Name );\r\n\t\tG.Set( \u0022FRAMEWORK_VERSION\u0022, Core.FrameworkInfo.Version );\r\n\t\tG.Set( \u0022LUA_API_VERSION\u0022, Core.FrameworkInfo.LuaApiVersion );\r\n\r\n\t\tState.Register( \u0022include\u0022, ( L, a ) =\u003E Include( LuaState.CheckString( a, 0, \u0022include\u0022 ) ) );\r\n\t\tState.Register( \u0022ErrorNoHalt\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar msg = string.Join( \u0022 \u0022, a.Select( v =\u003E L.ToStringMeta( v ) ) );\r\n\t\t\tReport( msg, null );\r\n\t\t\treturn null;\r\n\t\t} );\r\n\t\tState.Register( \u0022FindMetaTable\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar name = LuaState.CheckString( a, 0, \u0022FindMetaTable\u0022 );\r\n\t\t\treturn new[] { MethodTables.TryGetValue( name, out var t ) ? LuaValue.FromTable( t ) : LuaValue.Nil };\r\n\t\t} );\r\n\t\tState.Register( \u0022CurTime\u0022, ( L, a ) =\u003E new LuaValue[] { Time.Now } );\r\n\t\tState.Register( \u0022RealTime\u0022, ( L, a ) =\u003E new LuaValue[] { RealTime.Now } );\r\n\t\tState.Register( \u0022SysTime\u0022, ( L, a ) =\u003E new LuaValue[] { RealTime.NowDouble } );\r\n\r\n\t\tRegisterTimers();\r\n\t\tRegisterFileLibrary();\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ errors\r\n\r\n\tpublic void Report( string message, string traceback )\r\n\t{\r\n\t\tvar e = new ScriptError( DateTime.UtcNow, Name, (Gamemode?.Id ?? \u0022-\u0022) \u002B (_loadingAddon is null ? \u0022\u0022 : $\u0022\u002B{_loadingAddon}\u0022), message, traceback );\r\n\t\tlock ( _errors )\r\n\t\t{\r\n\t\t\t_errors.Add( e );\r\n\t\t\tif ( _errors.Count \u003E 50 ) _errors.RemoveAt( 0 );\r\n\t\t}\r\n\t\tRpLog.Error( \u0022lua\u0022, $\u0022[{Name}|{e.Gamemode}] {message}{(string.IsNullOrEmpty( traceback ) ? \u0022\u0022 : \u0022\\n\u0022 \u002B traceback)}\u0022 );\r\n\t\ttry { OnScriptError?.Invoke( e ); } catch { }\r\n\t}\r\n\r\n\tpublic static void ClearErrors()\r\n\t{\r\n\t\tlock ( _errors ) _errors.Clear();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EProtected call from the host. Returns the results, or null if the script failed (already reported).\u003C/summary\u003E\r\n\tpublic LuaValue[] Call( LuaValue fn, params LuaValue[] args )\r\n\t{\r\n\t\tvar r = State.PCall( fn, args );\r\n\t\tif ( r.Success ) return r.Results;\r\n\t\tReport( r.Error, r.Traceback );\r\n\t\treturn null;\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ file loading\r\n\r\n\t/// \u003Csummary\u003EWhether a file of \u003Cparamref name=\u0022fileRealm\u0022/\u003E may run in this realm.\u003C/summary\u003E\r\n\tpublic bool Accepts( LuaRealmKind fileRealm ) =\u003E fileRealm == LuaRealmKind.Shared || fileRealm == Kind;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Runs one file by full path (e.g. \u0022lua/gamemodes/darkrp/gamemode/sh_init.lua\u0022). Throws \u003Csee cref=\u0022LuaException\u0022/\u003E\r\n\t/// on failure so callers decide whether it is fatal.\r\n\t/// \u003C/summary\u003E\r\n\tpublic LuaValue[] RunFile( string fullPath )\r\n\t{\r\n\t\tvar rel = fullPath.StartsWith( \u0022lua/\u0022 ) ? fullPath.Substring( 4 ) : fullPath;\r\n\t\tvar realm = LuaPaths.RealmOf( fullPath );\r\n\r\n\t\tif ( realm is null )\r\n\t\t\tthrow new LuaRuntimeException( $\u0022cannot run \u0027{rel}\u0027: Lua file names must start with sh_, sv_ or cl_\u0022 );\r\n\t\tif ( !Accepts( realm.Value ) )\r\n\t\t\tthrow new LuaRuntimeException( $\u0022cannot run \u0027{rel}\u0027 in the {Name} realm (it is a {realm.Value.ToString().ToLowerInvariant()} file)\u0022 );\r\n\t\tif ( !_fs.FileExists( fullPath ) )\r\n\t\t\tthrow new LuaRuntimeException( $\u0022file not found: \u0027{rel}\u0027\u0022 );\r\n\r\n\t\tvar source = _fs.ReadAllText( fullPath );\r\n\t\tvar fn = State.Load( source, rel );\r\n\t\t_loaded.Add( rel );\r\n\t\tCore.LoadingProgress.File( $\u0022{Name}: lua/{rel}\u0022 );\r\n\t\treturn State.Call( LuaValue.FromFunction( fn ) );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ELua include(path): relative to the gamemode (or framework) folder currently loading.\u003C/summary\u003E\r\n\tstatic readonly System.Text.RegularExpressions.Regex DirPattern = new( @\u0022^[a-z0-9_]\u002B(/[a-z0-9_]\u002B)*$\u0022 );\r\n\tstatic readonly System.Text.RegularExpressions.Regex MaskPattern = new( @\u0022^[a-z0-9_*.]{1,64}$\u0022 );\r\n\r\n\t/// \u003Csummary\u003EFolder that gamemode-relative paths resolve against: the file being included, else the running gamemode.\u003C/summary\u003E\r\n\tstring CurrentRoot =\u003E _roots.Count \u003E 0 ? _roots.Peek()\r\n\t\t: Gamemode?.Root ?? throw new LuaRuntimeException( \u0022no gamemode is loaded\u0022 );\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// \u003Cc\u003Efile.Find(\u0022gamemode/modules/*\u0022)\u003C/c\u003E \u2192 files, folders (sorted) inside the gamemode\u0027s own Lua folder;\r\n\t/// \u003Cc\u003Efile.Exists(\u0022gamemode/x.lua\u0022)\u003C/c\u003E. Read-only and limited to the gamemode\u0027s scripts, so on a client it only sees\r\n\t/// the shared and client files the server sent. \u003Cc\u003EAddCSLuaFile\u003C/c\u003E exists for GMod compatibility and does nothing\r\n\t/// (sh_ and cl_ files are always sent).\r\n\t/// \u003C/summary\u003E\r\n\tvoid RegisterFileLibrary()\r\n\t{\r\n\t\tvar t = State.GetOrCreateLibrary( \u0022file\u0022 );\r\n\t\t(string Dir, string Mask) Split( string pattern, string fname )\r\n\t\t{\r\n\t\t\tif ( pattern.Length \u003E 128 || pattern.Contains( \u0022..\u0022 ) || pattern.StartsWith( \u0022/\u0022 ) || pattern.Contains( \u0027:\u0027 ) || pattern.Contains( \u0022\\\\\u0022 ) )\r\n\t\t\t\tthrow LuaState.ArgError( 0, fname, \u0022relative path inside the gamemode folder expected\u0022 );\r\n\t\t\tint slash = pattern.LastIndexOf( \u0027/\u0027 );\r\n\t\t\tvar dir = slash \u003E 0 ? pattern.Substring( 0, slash ) : \u0022\u0022;\r\n\t\t\tvar mask = slash \u003E= 0 ? pattern.Substring( slash \u002B 1 ) : pattern;\r\n\t\t\tif ( (dir != \u0022\u0022 \u0026\u0026 !DirPattern.IsMatch( dir )) || !MaskPattern.IsMatch( mask ) )\r\n\t\t\t\tthrow LuaState.ArgError( 0, fname, \u0022only lowercase a-z, 0-9, _, \u0027/\u0027 and \u0027*\u0027 are allowed\u0022 );\r\n\t\t\treturn (dir == \u0022\u0022 ? CurrentRoot : $\u0022{CurrentRoot}/{dir}\u0022, mask);\r\n\t\t}\r\n\r\n\t\tLuaState.Register( t, \u0022Find\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar (full, mask) = Split( LuaState.CheckString( a, 0, \u0022file.Find\u0022 ), \u0022file.Find\u0022 );\r\n\t\t\tvar files = new LuaTable();\r\n\t\t\tvar dirs = new LuaTable();\r\n\t\t\tif ( _fs.DirectoryExists( full ) )\r\n\t\t\t{\r\n\t\t\t\tforeach ( var f in _fs.FindFile( full, mask, false ).OrderBy( x =\u003E x, StringComparer.Ordinal ) ) files.Append( f );\r\n\t\t\t\tforeach ( var d in _fs.FindDirectory( full, mask, false ).OrderBy( x =\u003E x, StringComparer.Ordinal ) ) dirs.Append( d );\r\n\t\t\t}\r\n\t\t\treturn new LuaValue[] { files, dirs };\r\n\t\t} );\r\n\t\tLuaState.Register( t, \u0022Exists\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar path = LuaState.CheckString( a, 0, \u0022file.Exists\u0022 );\r\n\t\t\tvar (full, mask) = Split( path, \u0022file.Exists\u0022 );\r\n\t\t\treturn new LuaValue[] { !mask.Contains( \u0027*\u0027 ) \u0026\u0026 (_fs.FileExists( $\u0022{full}/{mask}\u0022 ) || _fs.DirectoryExists( $\u0022{full}/{mask}\u0022 )) };\r\n\t\t} );\r\n\t\tState.Register( \u0022AddCSLuaFile\u0022, ( L, a ) =\u003E null );\r\n\t}\r\n\r\n\tLuaValue[] Include( string path )\r\n\t{\r\n\t\tif ( _roots.Count == 0 )\r\n\t\t\tthrow new LuaRuntimeException( \u0022include() can only be used while a gamemode is loading\u0022 );\r\n\t\tif ( _roots.Count \u003E MaxIncludeDepth )\r\n\t\t\tthrow new LuaRuntimeException( \u0022include() nested too deeply (possible include loop)\u0022 );\r\n\r\n\t\tvar problem = LuaPaths.CheckRelative( path );\r\n\t\tif ( problem is not null )\r\n\t\t\tthrow new LuaRuntimeException( $\u0022include(\u0027{path}\u0027): {problem}\u0022 );\r\n\r\n\t\tvar root = _roots.Peek();\r\n\t\tvar full = $\u0022{root}/{path}\u0022;\r\n\t\t_roots.Push( root );\r\n\t\ttry\r\n\t\t{\r\n\t\t\treturn RunFile( full );\r\n\t\t}\r\n\t\tcatch ( LuaSyntaxException e )\r\n\t\t{\r\n\t\t\t// Make syntax errors in included files catchable like any other Lua error.\r\n\t\t\tthrow new LuaRuntimeException( LuaValue.FromString( e.Message ), true );\r\n\t\t}\r\n\t\tfinally\r\n\t\t{\r\n\t\t\t_roots.Pop();\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ERuns every framework file for this realm (lua/framework/sh_*, then sv_* or cl_*), in name order.\u003C/summary\u003E\r\n\tpublic void LoadFrameworkFiles()\r\n\t{\r\n\t\tif ( !_fs.DirectoryExists( FrameworkRoot ) ) return;\r\n\r\n\t\tvar files = _fs.FindFile( FrameworkRoot, \u0022*.lua\u0022, false )\r\n\t\t\t.Where( f =\u003E LuaPaths.RealmOf( f ) is { } r \u0026\u0026 Accepts( r ) )\r\n\t\t\t.OrderBy( f =\u003E LuaPaths.RealmOf( f ) == LuaRealmKind.Shared ? 0 : 1 )\r\n\t\t\t.ThenBy( f =\u003E f, StringComparer.Ordinal )\r\n\t\t\t.ToList();\r\n\r\n\t\t_roots.Push( FrameworkRoot );\r\n\t\ttry\r\n\t\t{\r\n\t\t\tforeach ( var f in files ) RunFile( $\u0022{FrameworkRoot}/{f}\u0022 );\r\n\t\t}\r\n\t\tfinally { _roots.Pop(); }\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Loads a gamemode and its dependencies (dependencies first). For each: the shared entry, then this realm\u0027s entry.\r\n\t/// Throws on any failure; the caller treats that as \u0022gamemode failed to load\u0022.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void LoadGamemode( GamemodeRegistry registry, string id )\r\n\t{\r\n\t\tvar order = registry.LoadOrder( id ) ?? throw new LuaRuntimeException( registry.Invalid.TryGetValue( id, out var p )\r\n\t\t\t? $\u0022gamemode \u0027{id}\u0027 is invalid: {string.Join( \u0022; \u0022, p )}\u0022\r\n\t\t\t: $\u0022gamemode \u0027{id}\u0027 was not found in {GamemodeRegistry.GamemodesRoot}\u0022 );\r\n\r\n\t\tvar main = order[^1];\r\n\t\tGamemode = main;\r\n\r\n\t\tGM = new LuaTable();\r\n\t\tGM.Set( \u0022Name\u0022, main.Title );\r\n\t\tGM.Set( \u0022FolderName\u0022, main.Id );\r\n\t\tGM.Set( \u0022Version\u0022, main.Version );\r\n\t\tGM.Set( \u0022Author\u0022, main.Author ?? \u0022\u0022 );\r\n\t\tState.Globals.Set( \u0022GM\u0022, GM );\r\n\t\tState.Globals.Set( \u0022GAMEMODE\u0022, GM );\r\n\r\n\t\tforeach ( var m in order )\r\n\t\t{\r\n\t\t\t_roots.Push( m.Root );\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tif ( m.Entry.Shared is not null ) RunFile( $\u0022{m.Root}/{m.Entry.Shared}\u0022 );\r\n\t\t\t\tvar own = Kind == LuaRealmKind.Server ? m.Entry.Server : m.Entry.Client;\r\n\t\t\t\tif ( own is not null ) RunFile( $\u0022{m.Root}/{own}\u0022 );\r\n\t\t\t}\r\n\t\t\tfinally { _roots.Pop(); }\r\n\r\n\t\t\t// Derivation: the next gamemode sees what this one defined as GM.BaseClass, so overrides can call\r\n\t\t\t// self.BaseClass.Method(self, ...) like Garry\u0027s Mod.\r\n\t\t\tif ( m != main )\r\n\t\t\t{\r\n\t\t\t\tvar baseClass = new LuaTable();\r\n\t\t\t\tforeach ( var kv in GM.Pairs() ) baseClass.Set( kv.Key, kv.Value );\r\n\t\t\t\tGM.Set( \u0022BaseClass\u0022, baseClass );\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ addons\r\n\r\n\tpublic sealed class AddonLoad\r\n\t{\r\n\t\tpublic AddonManifest Manifest;\r\n\t\tpublic bool Loaded;\r\n\t\tpublic string Error;\r\n\t}\r\n\r\n\treadonly List\u003CAddonLoad\u003E _addons = new();\r\n\t/// \u003Csummary\u003EAddons this realm tried to load, in load order, with the outcome.\u003C/summary\u003E\r\n\tpublic IReadOnlyList\u003CAddonLoad\u003E Addons =\u003E _addons;\r\n\r\n\t/// \u003Csummary\u003EAddon whose files are running right now (for error messages), else null.\u003C/summary\u003E\r\n\tstring _loadingAddon;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Loads addons after the gamemode, in the given order. Unlike the gamemode, a broken addon is not fatal: it is\r\n\t/// reported and skipped, and the others still load. (Hooks it registered before failing stay registered.)\r\n\t/// \u003C/summary\u003E\r\n\tpublic void LoadAddons( IEnumerable\u003CAddonManifest\u003E order )\r\n\t{\r\n\t\tforeach ( var m in order )\r\n\t\t{\r\n\t\t\tvar rec = new AddonLoad { Manifest = m };\r\n\t\t\t_addons.Add( rec );\r\n\r\n\t\t\tvar missing = m.Dependencies.Keys.FirstOrDefault( d =\u003E !_addons.Any( a =\u003E a.Loaded \u0026\u0026 a.Manifest.Id == d ) );\r\n\t\t\tif ( missing is not null )\r\n\t\t\t{\r\n\t\t\t\trec.Error = $\u0022skipped: dependency \u0027{missing}\u0027 failed to load\u0022;\r\n\t\t\t\tReport( $\u0022Addon \u0027{m.Id}\u0027 {rec.Error}\u0022, null );\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\t_roots.Push( m.Root );\r\n\t\t\t_loadingAddon = m.Id;\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tif ( m.Entry is not null )\r\n\t\t\t\t{\r\n\t\t\t\t\tif ( m.Entry.Shared is not null ) RunFile( $\u0022{m.Root}/{m.Entry.Shared}\u0022 );\r\n\t\t\t\t\tvar own = Kind == LuaRealmKind.Server ? m.Entry.Server : m.Entry.Client;\r\n\t\t\t\t\tif ( own is not null ) RunFile( $\u0022{m.Root}/{own}\u0022 );\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvar files = _fs.FindFile( m.Root, \u0022*.lua\u0022, false ).ToList();\r\n\t\t\t\t\tforeach ( var f in files.Where( f =\u003E f.StartsWith( \u0022sh_\u0022 ) ).OrderBy( f =\u003E f, StringComparer.Ordinal ) ) RunFile( $\u0022{m.Root}/{f}\u0022 );\r\n\t\t\t\t\tvar prefix = Kind == LuaRealmKind.Server ? \u0022sv_\u0022 : \u0022cl_\u0022;\r\n\t\t\t\t\tforeach ( var f in files.Where( f =\u003E f.StartsWith( prefix ) ).OrderBy( f =\u003E f, StringComparer.Ordinal ) ) RunFile( $\u0022{m.Root}/{f}\u0022 );\r\n\t\t\t\t}\r\n\t\t\t\trec.Loaded = true;\r\n\t\t\t}\r\n\t\t\tcatch ( LuaException e )\r\n\t\t\t{\r\n\t\t\t\trec.Error = e.Message;\r\n\t\t\t\tReport( $\u0022Addon \u0027{m.Id}\u0027 failed to load and was skipped: {e.Message}\u0022, (e as LuaRuntimeException)?.LuaTraceback );\r\n\t\t\t}\r\n\t\t\tfinally\r\n\t\t\t{\r\n\t\t\t\t_loadingAddon = null;\r\n\t\t\t\t_roots.Pop();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tint ok = _addons.Count( a =\u003E a.Loaded );\r\n\t\tif ( _addons.Count \u003E 0 )\r\n\t\t\tRpLog.Info( \u0022addons\u0022, $\u0022[{Name}] {ok}/{_addons.Count} addon(s) loaded: {string.Join( \u0022, \u0022, _addons.Select( a =\u003E $\u0022{a.Manifest.Id} {a.Manifest.Version}{(a.Loaded ? \u0022\u0022 : \u0022 (failed)\u0022)}\u0022 ) )}\u0022 );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003Ehook.Run(name, ...) from C#: hooks first, then GM:name. Errors are reported, never thrown.\u003C/summary\u003E\r\n\tpublic LuaValue[] RunHook( string name, params LuaValue[] args )\r\n\t{\r\n\t\tvar hook = State.Globals.Get( \u0022hook\u0022 );\r\n\t\tif ( !hook.IsTable ) return null;\r\n\t\tvar run = hook.AsTable.Get( \u0022Run\u0022 );\r\n\t\tif ( !run.IsFunction ) return null;\r\n\r\n\t\tvar full = new LuaValue[args.Length \u002B 1];\r\n\t\tfull[0] = name;\r\n\t\targs.CopyTo( full, 1 );\r\n\t\treturn Call( run, full );\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ timers\r\n\r\n\tsealed class LuaTimer\r\n\t{\r\n\t\tpublic string Id;\r\n\t\tpublic double Interval;\r\n\t\tpublic double Next;\r\n\t\tpublic int RepsLeft; // 0 = forever\r\n\t\tpublic LuaValue Fn;\r\n\t\tpublic bool Paused;\r\n\t\tpublic double Remaining; // while paused: seconds left\r\n\t}\r\n\r\n\treadonly Dictionary\u003Cstring, LuaTimer\u003E _timers = new();\r\n\tint _anon;\r\n\r\n\tpublic int TimerCount =\u003E _timers.Count;\r\n\r\n\tvoid RegisterTimers()\r\n\t{\r\n\t\tvar T = State.GetOrCreateLibrary( \u0022timer\u0022 );\r\n\r\n\t\tLuaState.Register( T, \u0022Simple\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar delay = Math.Max( 0, LuaState.CheckNumber( a, 0, \u0022timer.Simple\u0022 ) );\r\n\t\t\tvar fn = LuaState.CheckFunction( a, 1, \u0022timer.Simple\u0022 );\r\n\t\t\tAddTimer( $\u0022__simple{\u002B\u002B_anon}\u0022, delay, 1, LuaValue.FromFunction( fn ) );\r\n\t\t\treturn null;\r\n\t\t} );\r\n\r\n\t\tLuaState.Register( T, \u0022Create\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar id = LuaState.CheckString( a, 0, \u0022timer.Create\u0022 );\r\n\t\t\tvar delay = LuaState.CheckNumber( a, 1, \u0022timer.Create\u0022 );\r\n\t\t\tvar reps = LuaState.CheckInt( a, 2, \u0022timer.Create\u0022 );\r\n\t\t\tvar fn = LuaState.CheckFunction( a, 3, \u0022timer.Create\u0022 );\r\n\t\t\tif ( delay \u003C 0.01 ) throw LuaState.ArgError( 1, \u0022timer.Create\u0022, \u0022delay must be at least 0.01 seconds\u0022 );\r\n\t\t\tif ( reps \u003C 0 ) throw LuaState.ArgError( 2, \u0022timer.Create\u0022, \u0022repetitions must be 0 (forever) or more\u0022 );\r\n\t\t\tAddTimer( \u0022u:\u0022 \u002B id, delay, reps, LuaValue.FromFunction( fn ) );\r\n\t\t\treturn null;\r\n\t\t} );\r\n\r\n\t\tLuaState.Register( T, \u0022Remove\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\t_timers.Remove( \u0022u:\u0022 \u002B LuaState.CheckString( a, 0, \u0022timer.Remove\u0022 ) );\r\n\t\t\treturn null;\r\n\t\t} );\r\n\r\n\t\tLuaState.Register( T, \u0022Exists\u0022, ( L, a ) =\u003E\r\n\t\t\tnew LuaValue[] { _timers.ContainsKey( \u0022u:\u0022 \u002B LuaState.CheckString( a, 0, \u0022timer.Exists\u0022 ) ) } );\r\n\r\n\t\t// GMod extras. Each returns false when the timer doesn\u0027t exist (like GMod).\r\n\t\tLuaTimer Find( LuaValue[] a, string fname ) =\u003E _timers.TryGetValue( \u0022u:\u0022 \u002B LuaState.CheckString( a, 0, fname ), out var t ) ? t : null;\r\n\r\n\t\tT.Set( \u0022Destroy\u0022, T.Get( \u0022Remove\u0022 ) );\r\n\r\n\t\tLuaState.Register( T, \u0022Adjust\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar t = Find( a, \u0022timer.Adjust\u0022 );\r\n\t\t\tif ( t is null ) return new LuaValue[] { false };\r\n\t\t\tvar delay = LuaState.CheckNumber( a, 1, \u0022timer.Adjust\u0022 );\r\n\t\t\tif ( delay \u003C 0.01 ) throw LuaState.ArgError( 1, \u0022timer.Adjust\u0022, \u0022delay must be at least 0.01 seconds\u0022 );\r\n\t\t\tt.Interval = delay;\r\n\t\t\tif ( t.Paused ) t.Remaining = Math.Min( t.Remaining, delay ); else t.Next = Math.Min( t.Next, Time.Now \u002B delay );\r\n\t\t\tif ( LuaState.Arg( a, 2 ).IsNumber ) t.RepsLeft = Math.Max( 0, (int)LuaState.Arg( a, 2 ).Number );\r\n\t\t\tif ( LuaState.Arg( a, 3 ).IsFunction ) t.Fn = LuaState.Arg( a, 3 );\r\n\t\t\treturn new LuaValue[] { true };\r\n\t\t} );\r\n\r\n\t\tLuaState.Register( T, \u0022Pause\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar t = Find( a, \u0022timer.Pause\u0022 );\r\n\t\t\tif ( t is null || t.Paused ) return new LuaValue[] { false };\r\n\t\t\tt.Paused = true;\r\n\t\t\tt.Remaining = Math.Max( 0, t.Next - Time.Now );\r\n\t\t\treturn new LuaValue[] { true };\r\n\t\t} );\r\n\r\n\t\tLuaState.Register( T, \u0022UnPause\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar t = Find( a, \u0022timer.UnPause\u0022 );\r\n\t\t\tif ( t is null || !t.Paused ) return new LuaValue[] { false };\r\n\t\t\tt.Paused = false;\r\n\t\t\tt.Next = Time.Now \u002B t.Remaining;\r\n\t\t\treturn new LuaValue[] { true };\r\n\t\t} );\r\n\r\n\t\tLuaState.Register( T, \u0022Toggle\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar t = Find( a, \u0022timer.Toggle\u0022 );\r\n\t\t\tif ( t is null ) return new LuaValue[] { false };\r\n\t\t\tif ( t.Paused ) { t.Paused = false; t.Next = Time.Now \u002B t.Remaining; }\r\n\t\t\telse { t.Paused = true; t.Remaining = Math.Max( 0, t.Next - Time.Now ); }\r\n\t\t\treturn new LuaValue[] { !t.Paused };\r\n\t\t} );\r\n\r\n\t\t// Stop: paused and reset to a full interval; Start: (re)starts a full interval.\r\n\t\tLuaState.Register( T, \u0022Stop\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar t = Find( a, \u0022timer.Stop\u0022 );\r\n\t\t\tif ( t is null ) return new LuaValue[] { false };\r\n\t\t\tt.Paused = true;\r\n\t\t\tt.Remaining = t.Interval;\r\n\t\t\treturn new LuaValue[] { true };\r\n\t\t} );\r\n\r\n\t\tLuaState.Register( T, \u0022Start\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar t = Find( a, \u0022timer.Start\u0022 );\r\n\t\t\tif ( t is null ) return new LuaValue[] { false };\r\n\t\t\tt.Paused = false;\r\n\t\t\tt.Next = Time.Now \u002B t.Interval;\r\n\t\t\treturn new LuaValue[] { true };\r\n\t\t} );\r\n\r\n\t\tLuaState.Register( T, \u0022TimeLeft\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar t = Find( a, \u0022timer.TimeLeft\u0022 );\r\n\t\t\tif ( t is null ) return new[] { LuaValue.Nil };\r\n\t\t\treturn new LuaValue[] { t.Paused ? -t.Remaining : Math.Max( 0, t.Next - Time.Now ) }; // GMod: negative while paused\r\n\t\t} );\r\n\r\n\t\tLuaState.Register( T, \u0022RepsLeft\u0022, ( L, a ) =\u003E\r\n\t\t{\r\n\t\t\tvar t = Find( a, \u0022timer.RepsLeft\u0022 );\r\n\t\t\treturn new[] { t is null ? LuaValue.Nil : LuaValue.FromNumber( t.RepsLeft ) };\r\n\t\t} );\r\n\t}\r\n\r\n\tvoid AddTimer( string id, double delay, int reps, LuaValue fn )\r\n\t{\r\n\t\tif ( !_timers.ContainsKey( id ) \u0026\u0026 _timers.Count \u003E= MaxTimers )\r\n\t\t\tthrow new LuaRuntimeException( $\u0022too many timers (limit {MaxTimers})\u0022 );\r\n\t\t_timers[id] = new LuaTimer { Id = id, Interval = delay, Next = Time.Now \u002B delay, RepsLeft = reps, Fn = fn };\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ERuns due timers. Called once per frame by the world.\u003C/summary\u003E\r\n\tpublic void Tick( double now )\r\n\t{\r\n\t\tif ( _timers.Count == 0 ) return;\r\n\r\n\t\tforeach ( var t in _timers.Values.Where( t =\u003E !t.Paused \u0026\u0026 now \u003E= t.Next ).ToList() )\r\n\t\t{\r\n\t\t\tif ( !_timers.TryGetValue( t.Id, out var current ) || current != t ) continue; // removed by another timer\r\n\r\n\t\t\tif ( t.RepsLeft == 1 ) _timers.Remove( t.Id );\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif ( t.RepsLeft \u003E 1 ) t.RepsLeft--;\r\n\t\t\t\tt.Next = now \u002B t.Interval;\r\n\t\t\t}\r\n\r\n\t\t\tif ( Call( t.Fn ) is null )\r\n\t\t\t{\r\n\t\t\t\t// A timer that errors is removed so it can\u0027t spam the log every interval.\r\n\t\t\t\t_timers.Remove( t.Id );\r\n\t\t\t\tRpLog.Warn( \u0022lua\u0022, $\u0022[{Name}] removed timer \u0027{(t.Id.StartsWith( \u0022u:\u0022 ) ? t.Id.Substring( 2 ) : \u0022timer.Simple\u0022)}\u0027 after an error\u0022 );\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/UI/Hud/SessionHud.razor","FileName":"SessionHud.razor","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"@using System\r\n@using System.Linq\r\n@using Sandbox\r\n@using Sandbox.UI\r\n@using RoleplayFramework.Core\r\n@using RoleplayFramework.Net\r\n@using RoleplayFramework.Players\r\n@using RoleplayFramework.Scripting\r\n@inherits PanelComponent\r\n@namespace RoleplayFramework.UI\r\n\r\n\u003Croot class=\u0022@(LoadingProgress.Active ? \u0022is-loading\u0022 : \u0022\u0022)\u0022\u003E\r\n\t@* No framework info box or pause menu: the HUD and the Escape menu belong to the gamemode (Lua; base has GM:Pause*). *@\r\n\t@if ( LuaHudModel.Lines.Count \u003E 0 )\r\n\t{\r\n\t\t\u003Cdiv class=\u0022lua-lines\u0022\u003E\r\n\t\t\t@foreach ( var line in LuaHudModel.Lines )\r\n\t\t\t{\r\n\t\t\t\t\u003Clabel class=\u0022lua-line\u0022\u003E@line.Text\u003C/label\u003E\r\n\t\t\t}\r\n\t\t\u003C/div\u003E\r\n\t}\r\n\r\n\t\u003Cdiv class=\u0022notifications\u0022\u003E\r\n\t\t@foreach ( var n in LuaHudModel.ActiveNotifications( RealTime.Now ) )\r\n\t\t{\r\n\t\t\t\u003Clabel class=\u0022notification\u0022\u003E@n.Text\u003C/label\u003E\r\n\t\t}\r\n\t\u003C/div\u003E\r\n\r\n\t@if ( LoadingProgress.Active )\r\n\t{\r\n\t\tvar pct = (int)MathF.Round( LoadingProgress.Fraction * 100 );\r\n\t\t\u003Cdiv class=\u0022loading\u0022\u003E\r\n\t\t\t\u003Cdiv class=\u0022loading-glow\u0022\u003E\u003C/div\u003E\r\n\t\t\t\u003Cdiv class=\u0022loading-info\u0022\u003E\r\n\t\t\t\t\u003Clabel class=\u0022loading-kicker\u0022\u003E@(Networking.IsActive \u0026\u0026 !Networking.IsHost ? \u0022JOINING\u0022 : \u0022STARTING\u0022)\u003C/label\u003E\r\n\t\t\t\t\u003Clabel class=\u0022loading-title\u0022\u003E@LoadingProgress.Title\u003C/label\u003E\r\n\t\t\t\t@if ( !string.IsNullOrEmpty( LoadingProgress.Subtitle ) )\r\n\t\t\t\t{\r\n\t\t\t\t\t\u003Clabel class=\u0022loading-sub\u0022\u003E@LoadingProgress.Subtitle\u003C/label\u003E\r\n\t\t\t\t}\r\n\t\t\t\u003C/div\u003E\r\n\t\t\t\u003Cdiv class=\u0022loading-tip\u0022\u003E\r\n\t\t\t\t\u003Clabel class=\u0022loading-tip-head\u0022\u003ETIP\u003C/label\u003E\r\n\t\t\t\t\u003Clabel class=\u0022loading-tip-text\u0022\u003E@Tip\u003C/label\u003E\r\n\t\t\t\u003C/div\u003E\r\n\t\t\t\u003Cdiv class=\u0022loading-card\u0022\u003E\r\n\t\t\t\t@foreach ( var done in LoadingProgress.Done.Skip( Math.Max( 0, LoadingProgress.Done.Count - 4 ) ) )\r\n\t\t\t\t{\r\n\t\t\t\t\t\u003Cdiv class=\u0022loading-done\u0022\u003E\r\n\t\t\t\t\t\t\u003Clabel class=\u0022loading-check\u0022\u003E\u2713\u003C/label\u003E\r\n\t\t\t\t\t\t\u003Clabel\u003E@done\u003C/label\u003E\r\n\t\t\t\t\t\u003C/div\u003E\r\n\t\t\t\t}\r\n\t\t\t\t@if ( LoadingProgress.Files.Count \u003E 0 )\r\n\t\t\t\t{\r\n\t\t\t\t\t\u003Cdiv class=\u0022loading-files\u0022\u003E\r\n\t\t\t\t\t\t@foreach ( var f in LoadingProgress.Files )\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\u003Clabel class=\u0022loading-file\u0022\u003E@f\u003C/label\u003E\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\u003C/div\u003E\r\n\t\t\t\t}\r\n\t\t\t\t\u003Cdiv class=\u0022loading-stage-row\u0022\u003E\r\n\t\t\t\t\t\u003Clabel class=\u0022loading-stage\u0022\u003E@LoadingProgress.Stage\u003C/label\u003E\r\n\t\t\t\t\t\u003Clabel class=\u0022loading-pct\u0022\u003E@(pct)%\u003C/label\u003E\r\n\t\t\t\t\u003C/div\u003E\r\n\t\t\t\t\u003Clabel class=\u0022loading-detail\u0022\u003E@LoadingProgress.Detail\u003C/label\u003E\r\n\t\t\t\t\u003Cdiv class=\u0022loading-bar\u0022\u003E\r\n\t\t\t\t\t\u003Cdiv class=\u0022loading-fill\u0022 style=\u0022width: @(pct)%\u0022\u003E\u003C/div\u003E\r\n\t\t\t\t\u003C/div\u003E\r\n\t\t\t\t\u003Clabel class=\u0022loading-time\u0022\u003E@($\u0022{LoadingProgress.FileCount} file(s) \u00B7 {(int)LoadingProgress.Since}s\u0022)\u003C/label\u003E\r\n\t\t\t\u003C/div\u003E\r\n\t\t\u003C/div\u003E\r\n\t}\r\n\u003C/root\u003E\r\n\r\n@code\r\n{\r\n\t// Changes when a notification expires, so the HUD rebuilds and drops it.\r\n\tint NotificationCount =\u003E LuaHudModel.ActiveNotifications( RealTime.Now ).Count();\r\n\r\n\r\n\tstatic readonly string[] Tips =\r\n\t{\r\n\t\t\u0022Hold Q for the spawn menu: props, weapons, entities and tools.\u0022,\r\n\t\t\u0022Z undoes the last prop or tool action.\u0022,\r\n\t\t\u0022Physics gun: hold left mouse, the wheel pulls things closer, E \u002B mouse rotates, right click freezes.\u0022,\r\n\t\t\u0022Press H for help and every key you can use.\u0022,\r\n\t\t\u0022Content from sbox.game is downloaded once and then cached.\u0022,\r\n\t\t\u0022Escape opens the pause menu.\u0022,\r\n\t};\r\n\r\n\tstring Tip =\u003E Tips[(int)(RealTime.Now / 6) % Tips.Length];\r\n\r\n\tprotected override void OnUpdate() =\u003E LoadingProgress.Tick();\r\n\r\n\t// Loading: rebuild on every change, plus each second for the timer and tips.\r\n\tprotected override int BuildHash() =\u003E HashCode.Combine( LuaHudModel.Version, NotificationCount, LoadingProgress.Version,\r\n\t\tLoadingProgress.Active ? (int)RealTime.Now : 0 );\r\n}\r\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Core/ContentPackages.cs","FileName":"ContentPackages.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text.RegularExpressions;\r\nusing System.Threading;\r\nusing System.Threading.Tasks;\r\nusing RoleplayFramework.Diagnostics;\r\n\r\nnamespace RoleplayFramework.Core;\r\n\r\n/// \u003Csummary\u003E\r\n/// Cloud content a server requires: sbox.game packages (models, materials, sounds, maps, ...; packages published through\r\n/// the Steam Workshop are packages too). Sources, merged and de-duplicated:\r\n/// \u003Clist type=\u0022bullet\u0022\u003E\r\n/// \u003Citem\u003Eserver config \u003Cc\u003E\u0022Packages\u0022\u003C/c\u003E and \u003Cc\u003E\u0022Collections\u0022\u003C/c\u003E (framework.json)\u003C/item\u003E\r\n/// \u003Citem\u003Ethe gamemode chain\u0027s \u003Cc\u003E\u0022packages\u0022\u003C/c\u003E and \u003Cc\u003E\u0022collections\u0022\u003C/c\u003E (gamemode.json)\u003C/item\u003E\r\n/// \u003Citem\u003ELua: \u003Cc\u003Econtent.AddPackage\u003C/c\u003E / \u003Cc\u003Econtent.AddCollection\u003C/c\u003E, at load time or while the server runs\u003C/item\u003E\r\n/// \u003C/list\u003E\r\n/// A \u003Cb\u003Ecollection\u003C/b\u003E is a JSON file listing package idents, served from any web server (URL) or stored as a file:\r\n/// \u003Cc\u003E[\u0022org.pkg\u0022, ...]\u003C/c\u003E or \u003Cc\u003E{ \u0022packages\u0022: [ ... ] }\u003C/c\u003E. The server mounts everything before players can join;\r\n/// joining clients receive the list with the script manifest and mount the same packages before their scripts start.\r\n/// Packages added while the server runs are mounted on the server and pushed to every connected client.\r\n/// \u003C/summary\u003E\r\npublic static class ContentPackages\r\n{\r\n\tpublic const int MaxPackages = 128;\r\n\tpublic const int MaxCollections = 16;\r\n\tpublic const int MaxCollectionChars = 64 * 1024;\r\n\tpublic const int CollectionTimeoutSeconds = 15;\r\n\r\n\t/// \u003Csummary\u003EData-folder base for config collections given as file paths (\u0022collections/x.json\u0022 \u2192 roleplay/collections/x.json).\u003C/summary\u003E\r\n\tpublic const string DataBase = \u0022roleplay\u0022;\r\n\r\n\tstatic readonly Regex IdentPattern = new( @\u0022^[a-z0-9_\\-]{1,64}\\.[a-z0-9_\\-]{1,64}$\u0022 );\r\n\tstatic readonly Regex PackageUrlPattern = new( @\u0022sbox\\.game/([a-z0-9_\\-]{1,64})/([a-z0-9_\\-]{1,64})\u0022, RegexOptions.IgnoreCase );\r\n\r\n\t/// \u003Csummary\u003EThe current world\u0027s required packages (server side; sent to clients).\u003C/summary\u003E\r\n\tpublic static IReadOnlyList\u003Cstring\u003E Required =\u003E _required;\r\n\tstatic List\u003Cstring\u003E _required = new();\r\n\r\n\t/// \u003Csummary\u003EPackages mounted in this process, with their titles.\u003C/summary\u003E\r\n\tpublic static IReadOnlyDictionary\u003Cstring, string\u003E Mounted =\u003E _mounted;\r\n\tstatic readonly Dictionary\u003Cstring, string\u003E _mounted = new();\r\n\tstatic readonly Dictionary\u003Cstring, string\u003E _primaryAssets = new();\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Raised after each batch queued through \u003Csee cref=\u0022Enqueue\u0022/\u003E was mounted: (mounted, failed, shared).\r\n\t/// \u003Cc\u003Eshared\u003C/c\u003E = the batch came from the server and is pushed to clients.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static event Action\u003CList\u003Cstring\u003E, List\u003Cstring\u003E, bool\u003E BatchMounted;\r\n\r\n\t/// \u003Csummary\u003EThe main asset of a mounted package (e.g. its .vmdl), or null.\u003C/summary\u003E\r\n\t/// \u003Csummary\u003EThe mounted package\u0027s title, else its ident (for progress text).\u003C/summary\u003E\r\n\tpublic static string TitleOrIdent( string ident ) =\u003E ident is not null \u0026\u0026 _mounted.TryGetValue( ident, out var t ) \u0026\u0026 !string.IsNullOrEmpty( t ) ? t : ident;\r\n\r\n\tpublic static string PrimaryAssetOf( string ident ) =\u003E ident is not null \u0026\u0026 _primaryAssets.TryGetValue( ident, out var a ) ? a : null;\r\n\r\n\tpublic static bool IsValidIdent( string ident ) =\u003E ident is not null \u0026\u0026 IdentPattern.IsMatch( ident );\r\n\r\n\t/// \u003Csummary\u003E\u0022Org.Name\u0022, \u0022 org.name \u0022, \u0022https://sbox.game/org/name\u0022 \u2192 \u0022org.name\u0022 (validity is checked separately).\u003C/summary\u003E\r\n\tpublic static string Normalize( string raw )\r\n\t{\r\n\t\tif ( raw is null ) return null;\r\n\t\tvar s = raw.Trim();\r\n\t\tvar m = PackageUrlPattern.Match( s );\r\n\t\tif ( m.Success ) s = $\u0022{m.Groups[1].Value}.{m.Groups[2].Value}\u0022;\r\n\t\treturn s.ToLowerInvariant();\r\n\t}\r\n\r\n\tpublic static bool IsUrl( string source ) =\u003E\r\n\t\tsource is not null \u0026\u0026 (source.StartsWith( \u0022https://\u0022, StringComparison.OrdinalIgnoreCase ) || source.StartsWith( \u0022http://\u0022, StringComparison.OrdinalIgnoreCase ));\r\n\r\n\t/// \u003Csummary\u003ENull if \u003Cparamref name=\u0022source\u0022/\u003E is a usable collection URL or relative .json path, else why not.\u003C/summary\u003E\r\n\tpublic static string CheckCollectionSource( string source )\r\n\t{\r\n\t\tif ( string.IsNullOrWhiteSpace( source ) ) return \u0022empty collection entry\u0022;\r\n\t\tif ( source.Length \u003E 512 ) return \u0022collection entry is longer than 512 characters\u0022;\r\n\t\tif ( IsUrl( source ) )\r\n\t\t\treturn Uri.TryCreate( source, UriKind.Absolute, out _ ) ? null : $\u0022\u0027{source}\u0027 is not a valid URL\u0022;\r\n\t\tif ( source.Contains( \u0022..\u0022 ) || source.Contains( \u0027\\\\\u0027 ) || source.StartsWith( \u0022/\u0022 ) || source.Contains( \u0027:\u0027 ) )\r\n\t\t\treturn $\u0022\u0027{source}\u0027 must be a URL or a relative path without \u0027..\u0027\u0022;\r\n\t\tif ( !source.EndsWith( \u0022.json\u0022, StringComparison.OrdinalIgnoreCase ) ) return $\u0022\u0027{source}\u0027 must be a .json file\u0022;\r\n\t\treturn null;\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ collections\r\n\r\n\tsealed class CollectionFile\r\n\t{\r\n\t\t[System.Text.Json.Serialization.JsonPropertyName( \u0022packages\u0022 )]\r\n\t\tpublic List\u003Cstring\u003E Packages { get; set; }\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EParses a collection: \u003Cc\u003E[\u0022a.b\u0022, ...]\u003C/c\u003E or \u003Cc\u003E{ \u0022packages\u0022: [...] }\u003C/c\u003E. Invalid entries are skipped and counted.\u003C/summary\u003E\r\n\tpublic static List\u003Cstring\u003E ParseCollection( string text, out string error, out int skipped )\r\n\t{\r\n\t\terror = null;\r\n\t\tskipped = 0;\r\n\t\tList\u003Cstring\u003E raw = null;\r\n\t\tvar trimmed = (text ?? \u0022\u0022).TrimStart();\r\n\t\tif ( trimmed.StartsWith( \u0022[\u0022 ) ) Json.TryDeserialize( trimmed, out raw );\r\n\t\telse if ( trimmed.StartsWith( \u0022{\u0022 ) \u0026\u0026 Json.TryDeserialize( trimmed, out CollectionFile file ) ) raw = file?.Packages;\r\n\r\n\t\tif ( raw is null ) { error = \u0022not a JSON array of package idents or an object with \\\u0022packages\\\u0022\u0022; return new(); }\r\n\r\n\t\tvar list = new List\u003Cstring\u003E();\r\n\t\tforeach ( var r in raw )\r\n\t\t{\r\n\t\t\tvar id = Normalize( r );\r\n\t\t\tif ( !IsValidIdent( id ) ) { skipped\u002B\u002B; continue; }\r\n\t\t\tif ( !list.Contains( id ) ) list.Add( id );\r\n\t\t}\r\n\t\treturn list;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Loads one collection. URLs are fetched over HTTP (timeout and size limit); paths are tried against each of\r\n\t/// \u003Cparamref name=\u0022bases\u0022/\u003E (a file system plus folder) in order. Never throws; returns null and an error instead.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static async Task\u003C(List\u003Cstring\u003E Packages, string Error)\u003E LoadCollectionAsync( string source, IEnumerable\u003C(BaseFileSystem Fs, string Dir)\u003E bases )\r\n\t{\r\n\t\tif ( CheckCollectionSource( source ) is { } bad ) return (null, bad);\r\n\r\n\t\tstring text;\r\n\t\tstring where;\r\n\t\tif ( IsUrl( source ) )\r\n\t\t{\r\n\t\t\twhere = source;\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tusing var cts = new CancellationTokenSource( TimeSpan.FromSeconds( CollectionTimeoutSeconds ) );\r\n\t\t\t\ttext = await Http.RequestStringAsync( source, cancellationToken: cts.Token );\r\n\t\t\t}\r\n\t\t\tcatch ( OperationCanceledException ) { return (null, $\u0022{source}: no answer within {CollectionTimeoutSeconds}s\u0022); }\r\n\t\t\tcatch ( Exception e ) { return (null, $\u0022{source}: {e.Message}\u0022); }\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttext = null;\r\n\t\t\twhere = null;\r\n\t\t\tforeach ( var (fs, dir) in bases ?? Enumerable.Empty\u003C(BaseFileSystem, string)\u003E() )\r\n\t\t\t{\r\n\t\t\t\tif ( fs is null ) continue;\r\n\t\t\t\tvar path = string.IsNullOrEmpty( dir ) ? source : $\u0022{dir.TrimEnd( \u0027/\u0027 )}/{source}\u0022;\r\n\t\t\t\tif ( !fs.FileExists( path ) ) continue;\r\n\t\t\t\ttext = fs.ReadAllText( path );\r\n\t\t\t\twhere = path;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif ( text is null ) return (null, $\u0022collection file \u0027{source}\u0027 was not found\u0022);\r\n\t\t}\r\n\r\n\t\tif ( text is null ) return (null, $\u0022{where}: empty answer\u0022);\r\n\t\tif ( text.Length \u003E MaxCollectionChars ) return (null, $\u0022{where}: larger than {MaxCollectionChars / 1024} KB\u0022);\r\n\r\n\t\tvar list = ParseCollection( text, out var error, out var skipped );\r\n\t\tif ( error is not null ) return (null, $\u0022{where}: {error}\u0022);\r\n\t\tif ( skipped \u003E 0 ) RpLog.Warn( \u0022content\u0022, $\u0022{where}: skipped {skipped} invalid entr{(skipped == 1 ? \u0022y\u0022 : \u0022ies\u0022)} (not org.name idents)\u0022 );\r\n\t\tRpLog.Info( \u0022content\u0022, $\u0022Collection {where}: {list.Count} package(s)\u0022 );\r\n\t\treturn (list, null);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Server: every package the world needs before it starts. framework.json packages and collections, then each gamemode\r\n\t/// of the chain (base first) with its packages and collections (files relative to its folder in \u003Cparamref name=\u0022luaFs\u0022/\u003E).\r\n\t/// Invalid entries and unreachable collections are logged and skipped: content is optional, the server still starts.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static async Task\u003CList\u003Cstring\u003E\u003E ResolveAsync( Scripting.GamemodeRegistry registry, string gamemode, BaseFileSystem luaFs, IEnumerable\u003CScripting.AddonManifest\u003E addons = null )\r\n\t{\r\n\t\tvar list = new List\u003Cstring\u003E();\r\n\t\tvoid Add( IEnumerable\u003Cstring\u003E src, string from )\r\n\t\t{\r\n\t\t\tforeach ( var raw in src ?? Enumerable.Empty\u003Cstring\u003E() )\r\n\t\t\t{\r\n\t\t\t\tvar id = Normalize( raw );\r\n\t\t\t\tif ( !IsValidIdent( id ) ) { RpLog.Warn( \u0022content\u0022, $\u0022Ignoring package \u0027{raw}\u0027 from {from}: not an org.name ident\u0022 ); continue; }\r\n\t\t\t\tif ( !list.Contains( id ) ) list.Add( id );\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvar collections = new List\u003C(string Source, string From, (BaseFileSystem, string)[] Bases)\u003E();\r\n\t\tvar config = Bootstrap.FrameworkHost.Config;\r\n\t\tAdd( config.Packages, \u0022framework.json\u0022 );\r\n\t\tforeach ( var c in config.Collections ?? new List\u003Cstring\u003E() )\r\n\t\t\tcollections.Add( (c, \u0022framework.json\u0022, new[] { (FileSystem.Data, DataBase) }) );\r\n\r\n\t\tforeach ( var m in registry?.LoadOrder( gamemode ) ?? new List\u003CScripting.GamemodeManifest\u003E() )\r\n\t\t{\r\n\t\t\tAdd( m.Packages, $\u0022gamemode \u0027{m.Id}\u0027\u0022 );\r\n\t\t\tforeach ( var c in m.Collections ?? new List\u003Cstring\u003E() )\r\n\t\t\t\tcollections.Add( (c, $\u0022gamemode \u0027{m.Id}\u0027\u0022, new[] { (luaFs, m.Root) }) );\r\n\t\t}\r\n\r\n\t\tforeach ( var a in addons ?? Enumerable.Empty\u003CScripting.AddonManifest\u003E() )\r\n\t\t{\r\n\t\t\tAdd( a.Packages, $\u0022addon \u0027{a.Id}\u0027\u0022 );\r\n\t\t\tforeach ( var c in a.Collections ?? new List\u003Cstring\u003E() )\r\n\t\t\t\tcollections.Add( (c, $\u0022addon \u0027{a.Id}\u0027\u0022, new[] { (luaFs, a.Root) }) );\r\n\t\t}\r\n\r\n\t\tif ( collections.Count \u003E MaxCollections )\r\n\t\t{\r\n\t\t\tRpLog.Warn( \u0022content\u0022, $\u0022{collections.Count} collections configured; only the first {MaxCollections} are loaded\u0022 );\r\n\t\t\tcollections = collections.Take( MaxCollections ).ToList();\r\n\t\t}\r\n\r\n\t\tforeach ( var (source, from, bases) in collections )\r\n\t\t{\r\n\t\t\tvar (ids, error) = await LoadCollectionAsync( source, bases );\r\n\t\t\tif ( error is not null ) { RpLog.Warn( \u0022content\u0022, $\u0022Collection from {from} skipped: {error}\u0022 ); continue; }\r\n\t\t\tAdd( ids, $\u0022collection \u0027{source}\u0027\u0022 );\r\n\t\t}\r\n\r\n\t\tif ( list.Count \u003E MaxPackages )\r\n\t\t{\r\n\t\t\tRpLog.Warn( \u0022content\u0022, $\u0022{list.Count} packages requested; only the first {MaxPackages} are used\u0022 );\r\n\t\t\tlist = list.Take( MaxPackages ).ToList();\r\n\t\t}\r\n\t\treturn list;\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ mounting\r\n\r\n\t/// \u003Csummary\u003EServer: sets the world\u0027s package list and mounts it. Failures are logged and skipped (content is optional).\u003C/summary\u003E\r\n\tpublic static async Task MountRequired( List\u003Cstring\u003E idents, Action\u003Cint, int, string\u003E progress = null )\r\n\t{\r\n\t\t_required = new List\u003Cstring\u003E( idents );\r\n\t\t_queue.Clear();\r\n\t\tawait MountAll( idents, progress );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EMounts packages one by one. Returns the idents that could not be mounted.\u003C/summary\u003E\r\n\t/// \u003Cparam name=\u0022progress\u0022\u003ECalled before each package: (index, count, ident) - feeds the loading screen.\u003C/param\u003E\r\n\tpublic static async Task\u003CList\u003Cstring\u003E\u003E MountAll( IEnumerable\u003Cstring\u003E idents, Action\u003Cint, int, string\u003E progress = null )\r\n\t{\r\n\t\tvar failed = new List\u003Cstring\u003E();\r\n\t\tvar list = idents.ToList();\r\n\t\tfor ( int i = 0; i \u003C list.Count; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tvar id = list[i];\r\n\t\t\tprogress?.Invoke( i, list.Count, id );\r\n\t\t\tif ( _mounted.ContainsKey( id ) ) continue;\r\n\t\t\t// Let a frame through between packages, so the game (and the loading screen) keeps drawing.\r\n\t\t\tawait GameTask.Yield();\r\n\t\t\tvar started = RealTime.Now;\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tvar package = await Package.FetchAsync( id, false );\r\n\t\t\t\tif ( package is null ) { failed.Add( id ); RpLog.Warn( \u0022content\u0022, $\u0022Package \u0027{id}\u0027 was not found on sbox.game\u0022 ); continue; }\r\n\t\t\t\tawait package.MountAsync( false );\r\n\t\t\t\t_mounted[id] = package.Title;\r\n\t\t\t\tif ( !string.IsNullOrEmpty( package.PrimaryAsset ) ) _primaryAssets[id] = package.PrimaryAsset;\r\n\t\t\t\tRpLog.Info( \u0022content\u0022, $\u0022Mounted \u0027{package.Title}\u0027 ({id}, {package.TypeName}) in {RealTime.Now - started:F1}s\u0022 );\r\n\t\t\t}\r\n\t\t\tcatch ( Exception e )\r\n\t\t\t{\r\n\t\t\t\tfailed.Add( id );\r\n\t\t\t\tRpLog.Warn( \u0022content\u0022, $\u0022Could not mount \u0027{id}\u0027: {e.Message}\u0022 );\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn failed;\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ runtime additions (Lua content library)\r\n\r\n\tstatic readonly List\u003C(string Id, bool Share)\u003E _queue = new();\r\n\tstatic Task _pump;\r\n\tstatic int _inflight;\r\n\r\n\t/// \u003Csummary\u003ETrue while queued packages or collections are still being fetched or mounted.\u003C/summary\u003E\r\n\tpublic static bool Busy =\u003E _inflight \u003E 0 || _queue.Count \u003E 0 || _pump is { IsCompleted: false };\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Queues packages to mount. \u003Cparamref name=\u0022share\u0022/\u003E (server side) adds them to \u003Csee cref=\u0022Required\u0022/\u003E, so joining\r\n\t/// clients get them, and pushes them to connected clients once mounted. Returns how many were new.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static int Enqueue( IEnumerable\u003Cstring\u003E idents, bool share )\r\n\t{\r\n\t\tint added = 0;\r\n\t\tforeach ( var id in idents )\r\n\t\t{\r\n\t\t\tif ( !IsValidIdent( id ) ) continue;\r\n\t\t\tif ( share \u0026\u0026 _required.Contains( id ) ) continue;\r\n\t\t\tif ( !share \u0026\u0026 _mounted.ContainsKey( id ) ) continue;\r\n\t\t\tif ( _queue.Any( q =\u003E q.Id == id \u0026\u0026 q.Share == share ) ) continue;\r\n\t\t\tif ( share \u0026\u0026 _required.Count \u003E= MaxPackages )\r\n\t\t\t{\r\n\t\t\t\tRpLog.Warn( \u0022content\u0022, $\u0022Package limit ({MaxPackages}) reached; \u0027{id}\u0027 was not added\u0022 );\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif ( share ) _required.Add( id );\r\n\t\t\t_queue.Add( (id, share) );\r\n\t\t\tadded\u002B\u002B;\r\n\t\t}\r\n\t\tif ( added \u003E 0 \u0026\u0026 _pump is not { IsCompleted: false } ) _pump = Pump();\r\n\t\treturn added;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EFetches a collection in the background, then queues its packages (see \u003Csee cref=\u0022Enqueue\u0022/\u003E).\u003C/summary\u003E\r\n\tpublic static async Task EnqueueCollectionAsync( string source, IEnumerable\u003C(BaseFileSystem Fs, string Dir)\u003E bases, bool share, Action\u003Cstring\u003E onError )\r\n\t{\r\n\t\t_inflight\u002B\u002B;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tvar (ids, error) = await LoadCollectionAsync( source, bases );\r\n\t\t\tif ( error is not null ) { RpLog.Warn( \u0022content\u0022, $\u0022Collection skipped: {error}\u0022 ); onError?.Invoke( error ); return; }\r\n\t\t\tEnqueue( ids, share );\r\n\t\t}\r\n\t\tfinally { _inflight--; }\r\n\t}\r\n\r\n\tstatic async Task Pump()\r\n\t{\r\n\t\t// Never run hooks synchronously inside the Lua call that queued the package (the realm may still be loading).\r\n\t\tawait GameTask.DelayRealtimeSeconds( 0.01f );\r\n\t\twhile ( _queue.Count \u003E 0 )\r\n\t\t{\r\n\t\t\tvar batch = _queue.ToList();\r\n\t\t\t_queue.Clear();\r\n\t\t\tforeach ( var share in new[] { true, false } )\r\n\t\t\t{\r\n\t\t\t\tvar ids = batch.Where( q =\u003E q.Share == share ).Select( q =\u003E q.Id ).Distinct().ToList();\r\n\t\t\t\tif ( ids.Count == 0 ) continue;\r\n\t\t\t\tvar failed = await MountAll( ids );\r\n\t\t\t\tif ( share ) _required.RemoveAll( failed.Contains ); // don\u0027t make joining clients retry broken packages\r\n\t\t\t\tvar ok =ids.Where( i =\u003E !failed.Contains( i ) \u0026\u0026 _mounted.ContainsKey( i ) ).ToList();\r\n\t\t\t\ttry { BatchMounted?.Invoke( ok, failed, share ); }\r\n\t\t\t\tcatch ( Exception e ) { RpLog.Error( \u0022content\u0022, $\u0022ContentMounted handler failed: {e.Message}\u0022 ); }\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EWaits until queued content is mounted (or \u003Cparamref name=\u0022timeoutSeconds\u0022/\u003E pass). Used before opening the lobby.\u003C/summary\u003E\r\n\tpublic static async Task WhenIdle( double timeoutSeconds )\r\n\t{\r\n\t\tvar start = RealTime.Now;\r\n\t\twhile ( Busy \u0026\u0026 RealTime.Now - start \u003C timeoutSeconds )\r\n\t\t\tawait GameTask.DelayRealtimeSeconds( 0.05f );\r\n\t\tif ( Busy ) RpLog.Warn( \u0022content\u0022, $\u0022Content still loading after {timeoutSeconds:F0}s; opening the server anyway\u0022 );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EClient: parses the server\u0027s untrusted, comma-separated list.\u003C/summary\u003E\r\n\tpublic static List\u003Cstring\u003E ParseFromServer( string packed )\r\n\t{\r\n\t\treturn (packed ?? \u0022\u0022).Split( \u0027,\u0027, StringSplitOptions.RemoveEmptyEntries )\r\n\t\t\t.Select( s =\u003E s.Trim() )\r\n\t\t\t.Where( IsValidIdent )\r\n\t\t\t.Distinct()\r\n\t\t\t.Take( MaxPackages )\r\n\t\t\t.ToList();\r\n\t}\r\n}\r\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Core/FrameworkConfig.cs","FileName":"FrameworkConfig.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text.RegularExpressions;\r\nusing RoleplayFramework.Diagnostics;\r\n\r\nnamespace RoleplayFramework.Core;\r\n\r\n/// \u003Csummary\u003E\r\n/// Framework-level configuration (not gamemode config). Stored as JSON in the data folder at\r\n/// \u003Csee cref=\u0022FrameworkConfigStore.Path\u0022/\u003E. Values are validated on load; anything invalid falls back to a default.\r\n/// \u003C/summary\u003E\r\npublic sealed class FrameworkConfig\r\n{\r\n\tpublic const int CurrentSchemaVersion = 1;\r\n\r\n\tpublic int SchemaVersion { get; set; } = CurrentSchemaVersion;\r\n\r\n\t/// \u003Csummary\u003EGamemode id the server runs when none is chosen explicitly.\u003C/summary\u003E\r\n\tpublic string DefaultGamemode { get; set; } = \u0022darkrp\u0022;\r\n\r\n\t/// \u003Csummary\u003EDefault name for a locally hosted server.\u003C/summary\u003E\r\n\tpublic string ServerName { get; set; } = \u0022Roleplay Server\u0022;\r\n\r\n\t/// \u003Csummary\u003EDefault max players for a locally hosted server (clamped to the project\u0027s limit).\u003C/summary\u003E\r\n\tpublic int MaxPlayers { get; set; } = 32;\r\n\r\n\t/// \u003Csummary\u003EEnables development features such as Lua hot reload. Never enable on a public server.\u003C/summary\u003E\r\n\tpublic bool DevMode { get; set; }\r\n\r\n\t/// \u003Csummary\u003EPassword for this machine\u0027s dedicated server lobby (empty = none). Server-local; never sent to clients.\u003C/summary\u003E\r\n\tpublic string ServerPassword { get; set; } = \u0022\u0022;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Map for a dedicated server (\u0022\u0022 = the gamemode\u0027s default map). A map given on the command line\r\n\t/// (\u002Bgame \u0026lt;game\u0026gt; \u0026lt;map\u0026gt;) takes precedence.\r\n\t/// \u003C/summary\u003E\r\n\tpublic string Map { get; set; } = \u0022\u0022;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Where gamemode Lua is loaded from: \u0022data\u0022 (default: an editable copy in this machine\u0027s data folder, made on\r\n\t/// first start) or \u0022builtin\u0022 (the game\u0027s own files; for framework developers editing Assets/lua).\r\n\t/// \u0022auto\u0022 is accepted and means \u0022data\u0022.\r\n\t/// \u003C/summary\u003E\r\n\tpublic string LuaSource { get; set; } = \u0022data\u0022;\r\n\r\n\t/// \u003Csummary\u003Esbox.game packages this server requires (models, materials, ...). Players download them when joining.\u003C/summary\u003E\r\n\tpublic List\u003Cstring\u003E Packages { get; set; } = new();\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Package collections: JSON files listing package idents, either a URL (\u0022https://example.com/content.json\u0022) or a\r\n\t/// file in this server\u0027s data folder relative to \u0022roleplay/\u0022 (e.g. \u0022collections/content.json\u0022).\r\n\t/// \u003C/summary\u003E\r\n\tpublic List\u003Cstring\u003E Collections { get; set; } = new();\r\n\r\n\t/// \u003Csummary\u003ELua addons (lua/addons/\u0026lt;id\u0026gt;) this server does NOT run. Every other installed addon is on.\u003C/summary\u003E\r\n\tpublic List\u003Cstring\u003E DisabledAddons { get; set; } = new();\r\n\r\n\tpublic const int ProjectMaxPlayers = 64;\r\n\tstatic readonly Regex IdPattern = new( \u0022^[a-z0-9_]{1,32}$\u0022 );\r\n\r\n\tpublic static bool IsValidId( string id ) =\u003E id is not null \u0026\u0026 IdPattern.IsMatch( id );\r\n\r\n\t/// \u003Csummary\u003EFixes invalid values in place and returns a description of each correction.\u003C/summary\u003E\r\n\tpublic List\u003Cstring\u003E Validate()\r\n\t{\r\n\t\tvar fixes = new List\u003Cstring\u003E();\r\n\t\tvar defaults = new FrameworkConfig();\r\n\r\n\t\tif ( !IsValidId( DefaultGamemode ) )\r\n\t\t{\r\n\t\t\tfixes.Add( $\u0022DefaultGamemode \u0027{DefaultGamemode}\u0027 is not a valid id (a-z, 0-9, _), using \u0027{defaults.DefaultGamemode}\u0027\u0022 );\r\n\t\t\tDefaultGamemode = defaults.DefaultGamemode;\r\n\t\t}\r\n\r\n\t\tvar name = (ServerName ?? \u0022\u0022).Trim();\r\n\t\tif ( name.Length == 0 ) { fixes.Add( \u0022ServerName was empty\u0022 ); name = defaults.ServerName; }\r\n\t\tif ( name.Length \u003E 64 ) { fixes.Add( \u0022ServerName longer than 64 characters was truncated\u0022 ); name = name.Substring( 0, 64 ); }\r\n\t\tServerName = name;\r\n\r\n\t\tif ( MaxPlayers \u003C 1 || MaxPlayers \u003E ProjectMaxPlayers )\r\n\t\t{\r\n\t\t\tfixes.Add( $\u0022MaxPlayers {MaxPlayers} out of range 1-{ProjectMaxPlayers}\u0022 );\r\n\t\t\tMaxPlayers = Math.Clamp( MaxPlayers, 1, ProjectMaxPlayers );\r\n\t\t}\r\n\r\n\t\tif ( LuaSource is not (\u0022auto\u0022 or \u0022data\u0022 or \u0022builtin\u0022) )\r\n\t\t{\r\n\t\t\tfixes.Add( $\u0022LuaSource \u0027{LuaSource}\u0027 must be auto, data or builtin\u0022 );\r\n\t\t\tLuaSource = \u0022auto\u0022;\r\n\t\t}\r\n\r\n\t\tif ( !string.IsNullOrEmpty( Map ) \u0026\u0026 MapCatalog.Validate( Map ) is { } badMap )\r\n\t\t{\r\n\t\t\tfixes.Add( $\u0022Map: {badMap} Using the gamemode\u0027s default map.\u0022 );\r\n\t\t\tMap = \u0022\u0022;\r\n\t\t}\r\n\r\n\t\tPackages ??= new();\r\n\t\tCollections ??= new();\r\n\t\tDisabledAddons ??= new();\r\n\t\tforeach ( var a in DisabledAddons.ToList() )\r\n\t\t{\r\n\t\t\tif ( IsValidId( a ) ) continue;\r\n\t\t\tfixes.Add( $\u0022DisabledAddons: \u0027{a}\u0027 is not a valid addon id\u0022 );\r\n\t\t\tDisabledAddons.Remove( a );\r\n\t\t}\r\n\t\tforeach ( var c in Collections.ToList() )\r\n\t\t{\r\n\t\t\tif ( ContentPackages.CheckCollectionSource( c ) is not { } bad ) continue;\r\n\t\t\tfixes.Add( $\u0022Collections: {bad}\u0022 );\r\n\t\t\tCollections.Remove( c );\r\n\t\t}\r\n\r\n\t\treturn fixes;\r\n\t}\r\n}\r\n\r\npublic static class FrameworkConfigStore\r\n{\r\n\tpublic const string Directory = \u0022roleplay\u0022;\r\n\tpublic const string Path = \u0022roleplay/framework.json\u0022;\r\n\r\n\tpublic static FrameworkConfig Current { get; private set; } = new();\r\n\r\n\t/// \u003Csummary\u003ELoads (or creates) the config. Never throws: missing or corrupt files fall back to defaults.\u003C/summary\u003E\r\n\tpublic static FrameworkConfig Load()\r\n\t{\r\n\t\tvar fs = FileSystem.Data;\r\n\t\tFrameworkConfig config = null;\r\n\r\n\t\tstatic bool Parses( string text ) =\u003E Json.TryDeserialize( text, out FrameworkConfig c ) \u0026\u0026 c is not null;\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif ( !SafeDataFile.Exists( Path ) )\r\n\t\t\t{\r\n\t\t\t\tconfig = new FrameworkConfig();\r\n\t\t\t\tSave( config );\r\n\t\t\t\tRpLog.Info( \u0022config\u0022, $\u0022No config found, wrote defaults to data/{Path}\u0022 );\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tvar text = SafeDataFile.Read( Path, Parses, out bool recovered );\r\n\t\t\t\tif ( text is not null )\r\n\t\t\t\t{\r\n\t\t\t\t\tJson.TryDeserialize( text, out config );\r\n\t\t\t\t\tif ( recovered )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tRpLog.Warn( \u0022config\u0022, $\u0022data/{Path} was damaged by an interrupted write; recovered the last saved copy\u0022 );\r\n\t\t\t\t\t\tSave( config );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvar backup = $\u0022{Path}.corrupt-{DateTime.UtcNow:yyyyMMdd-HHmmss}\u0022;\r\n\t\t\t\t\tif ( fs.FileExists( Path ) ) fs.WriteAllText( backup, fs.ReadAllText( Path ) );\r\n\t\t\t\t\tRpLog.Warn( \u0022config\u0022, $\u0022data/{Path} could not be parsed; kept a copy at data/{backup} and using defaults\u0022 );\r\n\t\t\t\t\tconfig = new FrameworkConfig();\r\n\t\t\t\t\tSave( config );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch ( Exception e )\r\n\t\t{\r\n\t\t\tRpLog.Error( \u0022config\u0022, $\u0022Failed to read data/{Path}: {e.Message}. Using defaults.\u0022 );\r\n\t\t\tconfig = new FrameworkConfig();\r\n\t\t}\r\n\r\n\t\tif ( config.SchemaVersion \u003E FrameworkConfig.CurrentSchemaVersion )\r\n\t\t\tRpLog.Warn( \u0022config\u0022, $\u0022Config schema {config.SchemaVersion} is newer than supported {FrameworkConfig.CurrentSchemaVersion}; unknown fields are ignored\u0022 );\r\n\t\tconfig.SchemaVersion = FrameworkConfig.CurrentSchemaVersion;\r\n\r\n\t\tforeach ( var fix in config.Validate() )\r\n\t\t\tRpLog.Warn( \u0022config\u0022, fix );\r\n\r\n\t\tCurrent = config;\r\n\t\treturn config;\r\n\t}\r\n\r\n\tpublic static void Save( FrameworkConfig config )\r\n\t{\r\n\t\tSafeDataFile.Write( Path, Json.Serialize( config ) );\r\n\t}\r\n}\r\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Diagnostics/RpLog.cs","FileName":"RpLog.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing RoleplayFramework.Core;\n\nnamespace RoleplayFramework.Diagnostics;\n\npublic enum RpLogLevel { Info, Warning, Error }\n\npublic readonly record struct RpLogEntry( DateTime TimeUtc, RpLogLevel Level, string Category, string Realm, string Message );\n\n/// \u003Csummary\u003E\n/// Structured framework logger. Every line carries a category and the current realm, e.g.\n/// \u003Cc\u003E[rp:bootstrap|offline] Config loaded\u003C/c\u003E. Recent entries are kept in memory for the diagnostics panel.\n/// Never pass passwords, tokens or other private data as messages.\n/// \u003C/summary\u003E\npublic static class RpLog\n{\n\tconst int Capacity = 300;\n\tstatic readonly Queue\u003CRpLogEntry\u003E _recent = new();\n\n\t/// \u003Csummary\u003ERaised for every entry (main thread). The UI uses it to refresh.\u003C/summary\u003E\n\tpublic static event Action\u003CRpLogEntry\u003E OnEntry;\n\n\tpublic static void Info( string category, string message ) =\u003E Write( RpLogLevel.Info, category, message );\n\tpublic static void Warn( string category, string message ) =\u003E Write( RpLogLevel.Warning, category, message );\n\tpublic static void Error( string category, string message ) =\u003E Write( RpLogLevel.Error, category, message );\n\n\tpublic static void Write( RpLogLevel level, string category, string message )\n\t{\n\t\tvar entry = new RpLogEntry( DateTime.UtcNow, level, category, RealmInfo.Describe(), message );\n\n\t\tlock ( _recent )\n\t\t{\n\t\t\t_recent.Enqueue( entry );\n\t\t\twhile ( _recent.Count \u003E Capacity ) _recent.Dequeue();\n\t\t}\n\n\t\tvar line = $\u0022[rp:{category}|{entry.Realm}] {message}\u0022;\n\t\tswitch ( level )\n\t\t{\n\t\t\tcase RpLogLevel.Error: Log.Error( line ); break;\n\t\t\tcase RpLogLevel.Warning: Log.Warning( line ); break;\n\t\t\tdefault: Log.Info( line ); break;\n\t\t}\n\n\t\ttry { OnEntry?.Invoke( entry ); }\n\t\tcatch ( Exception e ) { Log.Warning( $\u0022[rp:log] listener failed: {e.Message}\u0022 ); }\n\t}\n\n\t/// \u003Csummary\u003EMost recent entries, oldest first, optionally at or above a level.\u003C/summary\u003E\n\tpublic static List\u003CRpLogEntry\u003E Recent( int max = 50, RpLogLevel minimum = RpLogLevel.Info )\n\t{\n\t\tvar result = new List\u003CRpLogEntry\u003E();\n\t\tlock ( _recent )\n\t\t{\n\t\t\tforeach ( var e in _recent )\n\t\t\t\tif ( e.Level \u003E= minimum ) result.Add( e );\n\t\t}\n\t\tif ( result.Count \u003E max ) result.RemoveRange( 0, result.Count - max );\n\t\treturn result;\n\t}\n}\n"},{"Ident":"roleplaydev.roleplay","Path":"Framework/Lua/Runtime/Compiler/Parser.cs","FileName":"Parser.cs","PackageType":"game","CodeKind":"Game","AssetVersionId":448161,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace RoleplayFramework.Lua.Compiler;\r\n\r\n/// \u003Csummary\u003ERecursive-descent parser producing a resolved AST (Lua 5.1 grammar \u002B GLua extensions).\u003C/summary\u003E\r\ninternal sealed class Parser\r\n{\r\n\t// Both limits protect the host stack: parsing and evaluation recurse on it.\r\n\tconst int MaxDepth = 100;\r\n\tconst int MaxExprDepth = 150;\r\n\r\n\tsealed class FuncState\r\n\t{\r\n\t\tpublic FuncState Parent;\r\n\t\tpublic readonly List\u003CDictionary\u003Cstring, int\u003E\u003E Blocks = new();\r\n\t\tpublic int SlotCount;\r\n\t\tpublic int ParamCount;\r\n\t\tpublic bool IsVararg;\r\n\t\tpublic readonly List\u003CUpvalDesc\u003E Upvals = new();\r\n\t\tpublic readonly Dictionary\u003Cstring, int\u003E UpvalIndex = new();\r\n\t\tpublic int LoopDepth;\r\n\t}\r\n\r\n\treadonly List\u003CToken\u003E _tokens;\r\n\treadonly string _chunk;\r\n\tint _p;\r\n\tint _depth;\r\n\tFuncState _fs;\r\n\r\n\tParser( List\u003CToken\u003E tokens, string chunk )\r\n\t{\r\n\t\t_tokens = tokens;\r\n\t\t_chunk = chunk;\r\n\t}\r\n\r\n\tpublic static FunctionProto ParseChunk( string source, string chunkName )\r\n\t{\r\n\t\tvar tokens = new Lexer( source, chunkName ).Tokenize();\r\n\t\tvar p = new Parser( tokens, chunkName );\r\n\t\treturn p.MainChunk();\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ token helpers\r\n\r\n\tToken Cur =\u003E _tokens[_p];\r\n\tTokenKind Kind =\u003E _tokens[_p].Kind;\r\n\tTokenKind PeekKind( int n = 1 ) =\u003E _tokens[Math.Min( _p \u002B n, _tokens.Count - 1 )].Kind;\r\n\r\n\tToken Advance() =\u003E _tokens[_p \u003C _tokens.Count - 1 ? _p\u002B\u002B : _p];\r\n\r\n\tbool Accept( TokenKind k )\r\n\t{\r\n\t\tif ( Kind != k ) return false;\r\n\t\tAdvance();\r\n\t\treturn true;\r\n\t}\r\n\r\n\tLuaSyntaxException Error( string msg ) =\u003E new( _chunk, Cur.Line, $\u0022{msg} near \u0027{Cur}\u0027\u0022 );\r\n\r\n\tToken Expect( TokenKind k, string what = null )\r\n\t{\r\n\t\tif ( Kind != k ) throw Error( $\u0022\u0027{what ?? Lexer.Describe( k )}\u0027 expected\u0022 );\r\n\t\treturn Advance();\r\n\t}\r\n\r\n\tvoid ExpectMatch( TokenKind close, TokenKind open, int openLine )\r\n\t{\r\n\t\tif ( Kind == close ) { Advance(); return; }\r\n\t\tif ( openLine == Cur.Line ) throw Error( $\u0022\u0027{Lexer.Describe( close )}\u0027 expected\u0022 );\r\n\t\tthrow Error( $\u0022\u0027{Lexer.Describe( close )}\u0027 expected (to close \u0027{Lexer.Describe( open )}\u0027 at line {openLine})\u0022 );\r\n\t}\r\n\r\n\tstring ExpectName() =\u003E Expect( TokenKind.Name, \u0022\u003Cname\u003E\u0022 ).Text;\r\n\r\n\tvoid Enter()\r\n\t{\r\n\t\tif ( \u002B\u002B_depth \u003E MaxDepth ) throw Error( \u0022chunk has too many syntax levels\u0022 );\r\n\t}\r\n\r\n\tvoid Leave() =\u003E _depth--;\r\n\r\n\t/// \u003Csummary\u003ERecords expression-tree depth so evaluation can\u0027t overflow the host stack (e.g. a\u002Bb\u002Bc\u002B... chains).\u003C/summary\u003E\r\n\tT Nest\u003CT\u003E( T e, Expr a, Expr b = null ) where T : Expr\r\n\t{\r\n\t\te.Depth = 1 \u002B Math.Max( a?.Depth ?? 0, b?.Depth ?? 0 );\r\n\t\tif ( e.Depth \u003E MaxExprDepth ) throw new LuaSyntaxException( _chunk, e.Line, \u0022expression too complex\u0022 );\r\n\t\treturn e;\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ scopes\r\n\r\n\tvoid OpenFunction()\r\n\t{\r\n\t\t_fs = new FuncState { Parent = _fs };\r\n\t\t_fs.Blocks.Add( new Dictionary\u003Cstring, int\u003E() );\r\n\t}\r\n\r\n\tFunctionProto CloseFunction( string name, int line, Block body )\r\n\t{\r\n\t\tvar fs = _fs;\r\n\t\t_fs = fs.Parent;\r\n\t\treturn new FunctionProto\r\n\t\t{\r\n\t\t\tName = name,\r\n\t\t\tChunkName = _chunk,\r\n\t\t\tLine = line,\r\n\t\t\tParamCount = fs.ParamCount,\r\n\t\t\tIsVararg = fs.IsVararg,\r\n\t\t\tSlotCount = fs.SlotCount,\r\n\t\t\tUpvalues = fs.Upvals.ToArray(),\r\n\t\t\tBody = body,\r\n\t\t};\r\n\t}\r\n\r\n\tvoid OpenScope() =\u003E _fs.Blocks.Add( new Dictionary\u003Cstring, int\u003E() );\r\n\tvoid CloseScope() =\u003E _fs.Blocks.RemoveAt( _fs.Blocks.Count - 1 );\r\n\r\n\tint DeclareLocal( string name )\r\n\t{\r\n\t\tint slot = _fs.SlotCount\u002B\u002B;\r\n\t\t_fs.Blocks[^1][name] = slot;\r\n\t\treturn slot;\r\n\t}\r\n\r\n\tstatic int FindLocal( FuncState fs, string name )\r\n\t{\r\n\t\tfor ( int i = fs.Blocks.Count - 1; i \u003E= 0; i-- )\r\n\t\t\tif ( fs.Blocks[i].TryGetValue( name, out int slot ) ) return slot;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\tstatic int FindUpval( FuncState fs, string name )\r\n\t{\r\n\t\tif ( fs.UpvalIndex.TryGetValue( name, out int idx ) ) return idx;\r\n\t\tif ( fs.Parent is null ) return -1;\r\n\r\n\t\tint slot = FindLocal( fs.Parent, name );\r\n\t\tif ( slot \u003E= 0 ) return AddUpval( fs, name, true, slot );\r\n\r\n\t\tint up = FindUpval( fs.Parent, name );\r\n\t\tif ( up \u003E= 0 ) return AddUpval( fs, name, false, up );\r\n\r\n\t\treturn -1;\r\n\t}\r\n\r\n\tstatic int AddUpval( FuncState fs, string name, bool fromLocal, int index )\r\n\t{\r\n\t\tint i = fs.Upvals.Count;\r\n\t\tfs.Upvals.Add( new UpvalDesc { FromParentLocal = fromLocal, Index = index, Name = name } );\r\n\t\tfs.UpvalIndex[name] = i;\r\n\t\treturn i;\r\n\t}\r\n\r\n\tExpr ResolveName( string name, int line )\r\n\t{\r\n\t\tint slot = FindLocal( _fs, name );\r\n\t\tif ( slot \u003E= 0 ) return new LocalExpr { Slot = slot, Name = name, Line = line };\r\n\t\tint up = FindUpval( _fs, name );\r\n\t\tif ( up \u003E= 0 ) return new UpvalExpr { Index = up, Name = name, Line = line };\r\n\t\treturn new GlobalExpr { Key = LuaValue.FromString( name ), Line = line };\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ chunk / blocks\r\n\r\n\tFunctionProto MainChunk()\r\n\t{\r\n\t\tOpenFunction();\r\n\t\t_fs.IsVararg = true;\r\n\t\tvar body = ParseBlockStatements();\r\n\t\tif ( Kind != TokenKind.Eof ) throw Error( \u0022\u0027\u003Ceof\u003E\u0027 expected\u0022 );\r\n\t\treturn CloseFunction( \u0022main chunk\u0022, 0, body );\r\n\t}\r\n\r\n\tstatic bool BlockFollows( TokenKind k ) =\u003E k is TokenKind.Eof or TokenKind.End or TokenKind.Else or TokenKind.ElseIf or TokenKind.Until;\r\n\r\n\tBlock ParseBlock()\r\n\t{\r\n\t\tOpenScope();\r\n\t\tvar b = ParseBlockStatements();\r\n\t\tCloseScope();\r\n\t\treturn b;\r\n\t}\r\n\r\n\tBlock ParseBlockStatements()\r\n\t{\r\n\t\tvar list = new List\u003CStmt\u003E();\r\n\t\twhile ( !BlockFollows( Kind ) )\r\n\t\t{\r\n\t\t\tif ( Kind == TokenKind.Return )\r\n\t\t\t{\r\n\t\t\t\tlist.Add( ParseReturn() );\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif ( Kind == TokenKind.Break || Kind == TokenKind.Continue )\r\n\t\t\t{\r\n\t\t\t\tvar t = Advance();\r\n\t\t\t\tif ( _fs.LoopDepth == 0 ) throw new LuaSyntaxException( _chunk, t.Line, $\u0022no loop to {(t.Kind == TokenKind.Break ? \u0022break\u0022 : \u0022continue\u0022)}\u0022 );\r\n\t\t\t\tlist.Add( t.Kind == TokenKind.Break ? new BreakStmt { Line = t.Line } : new ContinueStmt { Line = t.Line } );\r\n\t\t\t\tAccept( TokenKind.Semicolon );\r\n\t\t\t\t// Like Lua 5.1, break/continue must be the last statement of a block.\r\n\t\t\t\tif ( !BlockFollows( Kind ) ) throw Error( \u0022\u0027end\u0027 expected\u0022 );\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tvar s = ParseStatement();\r\n\t\t\tif ( s is not null ) list.Add( s );\r\n\t\t}\r\n\t\treturn new Block { Statements = list.ToArray() };\r\n\t}\r\n\r\n\tStmt ParseReturn()\r\n\t{\r\n\t\tint line = Advance().Line;\r\n\t\tExpr[] exprs = Array.Empty\u003CExpr\u003E();\r\n\t\tif ( !BlockFollows( Kind ) \u0026\u0026 Kind != TokenKind.Semicolon ) exprs = ParseExprList();\r\n\t\tAccept( TokenKind.Semicolon );\r\n\t\tif ( !BlockFollows( Kind ) ) throw Error( \u0022\u0027\u003Ceof\u003E\u0027 expected\u0022 );\r\n\t\treturn new ReturnStmt { Line = line, Exprs = exprs };\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ statements\r\n\r\n\tStmt ParseStatement()\r\n\t{\r\n\t\tEnter();\r\n\t\ttry\r\n\t\t{\r\n\t\t\tint line = Cur.Line;\r\n\t\t\tswitch ( Kind )\r\n\t\t\t{\r\n\t\t\t\tcase TokenKind.Semicolon:\r\n\t\t\t\t\tAdvance();\r\n\t\t\t\t\treturn null;\r\n\r\n\t\t\t\tcase TokenKind.If: return ParseIf();\r\n\r\n\t\t\t\tcase TokenKind.While:\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tAdvance();\r\n\t\t\t\t\t\tvar cond = ParseExpr();\r\n\t\t\t\t\t\tExpect( TokenKind.Do );\r\n\t\t\t\t\t\t_fs.LoopDepth\u002B\u002B;\r\n\t\t\t\t\t\tvar body = ParseBlock();\r\n\t\t\t\t\t\t_fs.LoopDepth--;\r\n\t\t\t\t\t\tExpectMatch( TokenKind.End, TokenKind.While, line );\r\n\t\t\t\t\t\treturn new WhileStmt { Line = line, Cond = cond, Body = body };\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\tcase TokenKind.Do:\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tAdvance();\r\n\t\t\t\t\t\tvar body = ParseBlock();\r\n\t\t\t\t\t\tExpectMatch( TokenKind.End, TokenKind.Do, line );\r\n\t\t\t\t\t\treturn new DoStmt { Line = line, Body = body };\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\tcase TokenKind.For: return ParseFor();\r\n\r\n\t\t\t\tcase TokenKind.Repeat:\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tAdvance();\r\n\t\t\t\t\t\t_fs.LoopDepth\u002B\u002B;\r\n\t\t\t\t\t\tOpenScope();\r\n\t\t\t\t\t\tvar body = ParseBlockStatements();\r\n\t\t\t\t\t\tExpectMatch( TokenKind.Until, TokenKind.Repeat, line );\r\n\t\t\t\t\t\tvar cond = ParseExpr(); // sees the body\u0027s locals\r\n\t\t\t\t\t\tCloseScope();\r\n\t\t\t\t\t\t_fs.LoopDepth--;\r\n\t\t\t\t\t\treturn new RepeatStmt { Line = line, Body = body, Cond = cond };\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\tcase TokenKind.Function: return ParseFunctionStatement();\r\n\r\n\t\t\t\tcase TokenKind.Local:\r\n\t\t\t\t\tAdvance();\r\n\t\t\t\t\tif ( Accept( TokenKind.Function ) )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tvar name = ExpectName();\r\n\t\t\t\t\t\tint slot = DeclareLocal( name );\r\n\t\t\t\t\t\tvar fn = ParseFunctionBody( name, line, false );\r\n\t\t\t\t\t\treturn new LocalFunctionStmt { Line = line, Slot = slot, Func = fn };\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn ParseLocal( line );\r\n\r\n\t\t\t\tdefault:\r\n\t\t\t\t\treturn ParseExprStatement();\r\n\t\t\t}\r\n\t\t}\r\n\t\tfinally { Leave(); }\r\n\t}\r\n\r\n\tStmt ParseIf()\r\n\t{\r\n\t\tint line = Advance().Line;\r\n\t\tvar conds = new List\u003CExpr\u003E();\r\n\t\tvar blocks = new List\u003CBlock\u003E();\r\n\t\tconds.Add( ParseExpr() );\r\n\t\tExpect( TokenKind.Then );\r\n\t\tblocks.Add( ParseBlock() );\r\n\t\tBlock elseBlock = null;\r\n\r\n\t\twhile ( true )\r\n\t\t{\r\n\t\t\tif ( Accept( TokenKind.ElseIf ) )\r\n\t\t\t{\r\n\t\t\t\tconds.Add( ParseExpr() );\r\n\t\t\t\tExpect( TokenKind.Then );\r\n\t\t\t\tblocks.Add( ParseBlock() );\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif ( Accept( TokenKind.Else ) )\r\n\t\t\t{\r\n\t\t\t\telseBlock = ParseBlock();\r\n\t\t\t}\r\n\t\t\tExpectMatch( TokenKind.End, TokenKind.If, line );\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\treturn new IfStmt { Line = line, Conds = conds.ToArray(), Blocks = blocks.ToArray(), Else = elseBlock };\r\n\t}\r\n\r\n\tStmt ParseFor()\r\n\t{\r\n\t\tint line = Advance().Line;\r\n\t\tvar first = ExpectName();\r\n\r\n\t\tif ( Kind == TokenKind.Assign )\r\n\t\t{\r\n\t\t\tAdvance();\r\n\t\t\tvar start = ParseExpr();\r\n\t\t\tExpect( TokenKind.Comma );\r\n\t\t\tvar limit = ParseExpr();\r\n\t\t\tExpr step = null;\r\n\t\t\tif ( Accept( TokenKind.Comma ) ) step = ParseExpr();\r\n\t\t\tExpect( TokenKind.Do );\r\n\r\n\t\t\tOpenScope();\r\n\t\t\tint slot = DeclareLocal( first );\r\n\t\t\t_fs.LoopDepth\u002B\u002B;\r\n\t\t\tvar body = ParseBlock();\r\n\t\t\t_fs.LoopDepth--;\r\n\t\t\tCloseScope();\r\n\t\t\tExpectMatch( TokenKind.End, TokenKind.For, line );\r\n\t\t\treturn new NumericForStmt { Line = line, Slot = slot, Start = start, Limit = limit, Step = step, Body = body };\r\n\t\t}\r\n\r\n\t\tvar names = new List\u003Cstring\u003E { first };\r\n\t\twhile ( Accept( TokenKind.Comma ) ) names.Add( ExpectName() );\r\n\t\tExpect( TokenKind.In );\r\n\t\tvar exprs = ParseExprList();\r\n\t\tExpect( TokenKind.Do );\r\n\r\n\t\tOpenScope();\r\n\t\tvar slots = new int[names.Count];\r\n\t\tfor ( int i = 0; i \u003C names.Count; i\u002B\u002B ) slots[i] = DeclareLocal( names[i] );\r\n\t\t_fs.LoopDepth\u002B\u002B;\r\n\t\tvar gbody = ParseBlock();\r\n\t\t_fs.LoopDepth--;\r\n\t\tCloseScope();\r\n\t\tExpectMatch( TokenKind.End, TokenKind.For, line );\r\n\t\treturn new GenericForStmt { Line = line, Slots = slots, Exprs = exprs, Body = gbody };\r\n\t}\r\n\r\n\tStmt ParseFunctionStatement()\r\n\t{\r\n\t\tint line = Advance().Line;\r\n\t\tvar nameTok = Cur;\r\n\t\tstring fullName = ExpectName();\r\n\t\tExpr target = ResolveName( fullName, nameTok.Line );\r\n\t\tbool isMethod = false;\r\n\r\n\t\twhile ( Kind == TokenKind.Dot || Kind == TokenKind.Colon )\r\n\t\t{\r\n\t\t\tbool colon = Kind == TokenKind.Colon;\r\n\t\t\tAdvance();\r\n\t\t\tvar key = ExpectName();\r\n\t\t\tfullName \u002B= (colon ? \u0022:\u0022 : \u0022.\u0022) \u002B key;\r\n\t\t\ttarget = new IndexExpr { Line = line, Obj = target, Key = new ConstExpr { Value = LuaValue.FromString( key ), Line = line } };\r\n\t\t\tif ( colon ) { isMethod = true; break; }\r\n\t\t}\r\n\r\n\t\tvar fn = ParseFunctionBody( fullName, line, isMethod );\r\n\t\treturn new AssignStmt { Line = line, Targets = new[] { target }, Exprs = new Expr[] { fn } };\r\n\t}\r\n\r\n\tStmt ParseLocal( int line )\r\n\t{\r\n\t\tvar names = new List\u003Cstring\u003E();\r\n\t\tdo { names.Add( ExpectName() ); } while ( Accept( TokenKind.Comma ) );\r\n\r\n\t\tExpr[] exprs = Array.Empty\u003CExpr\u003E();\r\n\t\tif ( Accept( TokenKind.Assign ) ) exprs = ParseExprList();\r\n\r\n\t\t// Declare after parsing the initialisers: \u0060local x = x\u0060 reads the outer x.\r\n\t\tvar slots = new int[names.Count];\r\n\t\tfor ( int i = 0; i \u003C names.Count; i\u002B\u002B ) slots[i] = DeclareLocal( names[i] );\r\n\r\n\t\tif ( exprs.Length == 0 )\r\n\t\t\texprs = new Expr[] { new ConstExpr { Value = LuaValue.Nil, Line = line } };\r\n\r\n\t\treturn new LocalStmt { Line = line, Slots = slots, Exprs = exprs };\r\n\t}\r\n\r\n\tStmt ParseExprStatement()\r\n\t{\r\n\t\tint line = Cur.Line;\r\n\t\tvar e = ParseSuffixedExpr();\r\n\r\n\t\tif ( Kind == TokenKind.Assign || Kind == TokenKind.Comma )\r\n\t\t{\r\n\t\t\tvar targets = new List\u003CExpr\u003E { e };\r\n\t\t\twhile ( Accept( TokenKind.Comma ) ) targets.Add( ParseSuffixedExpr() );\r\n\t\t\tExpect( TokenKind.Assign );\r\n\t\t\tvar exprs = ParseExprList();\r\n\r\n\t\t\tforeach ( var t in targets )\r\n\t\t\t\tif ( t is not IAssignable ) throw new LuaSyntaxException( _chunk, line, \u0022syntax error (cannot assign to this expression)\u0022 );\r\n\r\n\t\t\treturn new AssignStmt { Line = line, Targets = targets.ToArray(), Exprs = exprs };\r\n\t\t}\r\n\r\n\t\tif ( e is not CallExpr \u0026\u0026 e is not MethodCallExpr ) throw Error( \u0022syntax error\u0022 );\r\n\t\treturn new CallStmt { Line = line, Call = e };\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ functions\r\n\r\n\tFunctionExpr ParseFunctionBody( string name, int line, bool isMethod )\r\n\t{\r\n\t\tOpenFunction();\r\n\t\tif ( isMethod ) { DeclareLocal( \u0022self\u0022 ); _fs.ParamCount\u002B\u002B; }\r\n\r\n\t\tExpect( TokenKind.LParen );\r\n\t\tif ( Kind != TokenKind.RParen )\r\n\t\t{\r\n\t\t\tdo\r\n\t\t\t{\r\n\t\t\t\tif ( Accept( TokenKind.Ellipsis ) ) { _fs.IsVararg = true; break; }\r\n\t\t\t\tDeclareLocal( ExpectName() );\r\n\t\t\t\t_fs.ParamCount\u002B\u002B;\r\n\t\t\t} while ( Accept( TokenKind.Comma ) );\r\n\t\t}\r\n\t\tExpect( TokenKind.RParen );\r\n\r\n\t\tvar loopDepth = _fs.LoopDepth;\r\n\t\tvar body = ParseBlockStatements();\r\n\t\tExpectMatch( TokenKind.End, TokenKind.Function, line );\r\n\t\tvar proto = CloseFunction( name, line, body );\r\n\t\treturn new FunctionExpr { Line = line, Proto = proto };\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ expressions\r\n\r\n\tExpr[] ParseExprList()\r\n\t{\r\n\t\tvar list = new List\u003CExpr\u003E { ParseExpr() };\r\n\t\twhile ( Accept( TokenKind.Comma ) ) list.Add( ParseExpr() );\r\n\t\treturn list.ToArray();\r\n\t}\r\n\r\n\tExpr ParseExpr() =\u003E ParseSubExpr( 0 );\r\n\r\n\t// Lua 5.1 priorities: left / right binding power.\r\n\tstatic bool BinaryPriority( TokenKind k, out int left, out int right )\r\n\t{\r\n\t\tswitch ( k )\r\n\t\t{\r\n\t\t\tcase TokenKind.Or: left = 1; right = 1; return true;\r\n\t\t\tcase TokenKind.And: left = 2; right = 2; return true;\r\n\t\t\tcase TokenKind.Less: case TokenKind.Greater: case TokenKind.LessEq: case TokenKind.GreaterEq:\r\n\t\t\tcase TokenKind.Eq: case TokenKind.NotEq:\r\n\t\t\t\tleft = 3; right = 3; return true;\r\n\t\t\tcase TokenKind.Concat: left = 5; right = 4; return true;\r\n\t\t\tcase TokenKind.Plus: case TokenKind.Minus: left = 6; right = 6; return true;\r\n\t\t\tcase TokenKind.Star: case TokenKind.Slash: case TokenKind.Percent: left = 7; right = 7; return true;\r\n\t\t\tcase TokenKind.Caret: left = 10; right = 9; return true;\r\n\t\t}\r\n\t\tleft = right = 0;\r\n\t\treturn false;\r\n\t}\r\n\r\n\tconst int UnaryPriority = 8;\r\n\r\n\tExpr ParseSubExpr( int limit )\r\n\t{\r\n\t\tEnter();\r\n\t\ttry\r\n\t\t{\r\n\t\t\tExpr e;\r\n\t\t\tint line = Cur.Line;\r\n\t\t\tif ( Kind == TokenKind.Not || Kind == TokenKind.Minus || Kind == TokenKind.Hash )\r\n\t\t\t{\r\n\t\t\t\tvar op = Advance().Kind;\r\n\t\t\t\tvar operand = ParseSubExpr( UnaryPriority );\r\n\t\t\t\te = Nest( FoldUnary( op, operand, line ), operand );\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\te = ParseSimpleExpr();\r\n\t\t\t}\r\n\r\n\t\t\twhile ( BinaryPriority( Kind, out int left, out int right ) \u0026\u0026 left \u003E limit )\r\n\t\t\t{\r\n\t\t\t\tvar opTok = Advance();\r\n\t\t\t\tvar rhs = ParseSubExpr( right );\r\n\t\t\t\te = Nest( MakeBinary( opTok.Kind, e, rhs, opTok.Line ), e, rhs );\r\n\t\t\t}\r\n\t\t\treturn e;\r\n\t\t}\r\n\t\tfinally { Leave(); }\r\n\t}\r\n\r\n\tstatic Expr FoldUnary( TokenKind op, Expr operand, int line )\r\n\t{\r\n\t\tif ( op == TokenKind.Minus \u0026\u0026 operand is ConstExpr c \u0026\u0026 c.Value.IsNumber )\r\n\t\t\treturn new ConstExpr { Line = line, Value = LuaValue.FromNumber( -c.Value.Number ) };\r\n\r\n\t\tvar u = op switch { TokenKind.Not =\u003E UnOp.Not, TokenKind.Minus =\u003E UnOp.Neg, _ =\u003E UnOp.Len };\r\n\t\treturn new UnaryExpr { Line = line, Op = u, A = operand };\r\n\t}\r\n\r\n\tstatic Expr MakeBinary( TokenKind k, Expr a, Expr b, int line )\r\n\t{\r\n\t\tswitch ( k )\r\n\t\t{\r\n\t\t\tcase TokenKind.And: return new AndExpr { Line = line, A = a, B = b };\r\n\t\t\tcase TokenKind.Or: return new OrExpr { Line = line, A = a, B = b };\r\n\t\t}\r\n\r\n\t\tvar op = k switch\r\n\t\t{\r\n\t\t\tTokenKind.Plus =\u003E BinOp.Add,\r\n\t\t\tTokenKind.Minus =\u003E BinOp.Sub,\r\n\t\t\tTokenKind.Star =\u003E BinOp.Mul,\r\n\t\t\tTokenKind.Slash =\u003E BinOp.Div,\r\n\t\t\tTokenKind.Percent =\u003E BinOp.Mod,\r\n\t\t\tTokenKind.Caret =\u003E BinOp.Pow,\r\n\t\t\tTokenKind.Concat =\u003E BinOp.Concat,\r\n\t\t\tTokenKind.Eq =\u003E BinOp.Eq,\r\n\t\t\tTokenKind.NotEq =\u003E BinOp.Ne,\r\n\t\t\tTokenKind.Less =\u003E BinOp.Lt,\r\n\t\t\tTokenKind.LessEq =\u003E BinOp.Le,\r\n\t\t\tTokenKind.Greater =\u003E BinOp.Gt,\r\n\t\t\t_ =\u003E BinOp.Ge,\r\n\t\t};\r\n\t\treturn new BinaryExpr { Line = line, Op = op, A = a, B = b };\r\n\t}\r\n\r\n\tExpr ParseSimpleExpr()\r\n\t{\r\n\t\tvar t = Cur;\r\n\t\tswitch ( t.Kind )\r\n\t\t{\r\n\t\t\tcase TokenKind.Number: Advance(); return new ConstExpr { Line = t.Line, Value = LuaValue.FromNumber( t.Number ) };\r\n\t\t\tcase TokenKind.String: Advance(); return new ConstExpr { Line = t.Line, Value = LuaValue.FromString( t.Text ) };\r\n\t\t\tcase TokenKind.Nil: Advance(); return new ConstExpr { Line = t.Line, Value = LuaValue.Nil };\r\n\t\t\tcase TokenKind.True: Advance(); return new ConstExpr { Line = t.Line, Value = LuaValue.True };\r\n\t\t\tcase TokenKind.False: Advance(); return new ConstExpr { Line = t.Line, Value = LuaValue.False };\r\n\t\t\tcase TokenKind.Ellipsis:\r\n\t\t\t\tAdvance();\r\n\t\t\t\tif ( !_fs.IsVararg ) throw new LuaSyntaxException( _chunk, t.Line, \u0022cannot use \u0027...\u0027 outside a vararg function\u0022 );\r\n\t\t\t\treturn new VarargExpr { Line = t.Line };\r\n\t\t\tcase TokenKind.LBrace: return ParseTable();\r\n\t\t\tcase TokenKind.Function:\r\n\t\t\t\tAdvance();\r\n\t\t\t\treturn ParseFunctionBody( \u0022anonymous\u0022, t.Line, false );\r\n\t\t\tdefault:\r\n\t\t\t\treturn ParseSuffixedExpr();\r\n\t\t}\r\n\t}\r\n\r\n\tExpr ParsePrimaryExpr()\r\n\t{\r\n\t\tvar t = Cur;\r\n\t\tif ( t.Kind == TokenKind.Name )\r\n\t\t{\r\n\t\t\tAdvance();\r\n\t\t\treturn ResolveName( t.Text, t.Line );\r\n\t\t}\r\n\t\tif ( t.Kind == TokenKind.LParen )\r\n\t\t{\r\n\t\t\tAdvance();\r\n\t\t\tvar inner = ParseExpr();\r\n\t\t\tExpectMatch( TokenKind.RParen, TokenKind.LParen, t.Line );\r\n\t\t\t// Parentheses truncate multiple results to one.\r\n\t\t\treturn inner.IsMulti ? new ParenExpr { Line = t.Line, Inner = inner } : inner;\r\n\t\t}\r\n\t\tthrow Error( \u0022unexpected symbol\u0022 );\r\n\t}\r\n\r\n\tExpr ParseSuffixedExpr()\r\n\t{\r\n\t\tvar e = ParsePrimaryExpr();\r\n\t\twhile ( true )\r\n\t\t{\r\n\t\t\tvar t = Cur;\r\n\t\t\tswitch ( t.Kind )\r\n\t\t\t{\r\n\t\t\t\tcase TokenKind.Dot:\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tAdvance();\r\n\t\t\t\t\t\tvar name = ExpectName();\r\n\t\t\t\t\t\te = Nest( new IndexExpr { Line = t.Line, Obj = e, Key = new ConstExpr { Line = t.Line, Value = LuaValue.FromString( name ) } }, e );\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\tcase TokenKind.LBracket:\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tAdvance();\r\n\t\t\t\t\t\tvar key = ParseExpr();\r\n\t\t\t\t\t\tExpect( TokenKind.RBracket );\r\n\t\t\t\t\t\te = Nest( new IndexExpr { Line = t.Line, Obj = e, Key = key }, e, key );\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\tcase TokenKind.Colon:\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tAdvance();\r\n\t\t\t\t\t\tvar name = ExpectName();\r\n\t\t\t\t\t\tvar args = ParseCallArgs();\r\n\t\t\t\t\t\te = Nest( new MethodCallExpr { Line = t.Line, Obj = e, Method = name, Args = args }, e, Deepest( args ) );\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\tcase TokenKind.LParen:\r\n\t\t\t\tcase TokenKind.String:\r\n\t\t\t\tcase TokenKind.LBrace:\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tvar args = ParseCallArgs();\r\n\t\t\t\t\t\te = Nest( new CallExpr { Line = t.Line, Fn = e, Args = args }, e, Deepest( args ) );\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\tdefault:\r\n\t\t\t\t\treturn e;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tstatic Expr Deepest( Expr[] list )\r\n\t{\r\n\t\tExpr best = null;\r\n\t\tforeach ( var x in list ) if ( best is null || x.Depth \u003E best.Depth ) best = x;\r\n\t\treturn best;\r\n\t}\r\n\r\n\tExpr[] ParseCallArgs()\r\n\t{\r\n\t\tvar t = Cur;\r\n\t\tif ( t.Kind == TokenKind.String )\r\n\t\t{\r\n\t\t\tAdvance();\r\n\t\t\treturn new Expr[] { new ConstExpr { Line = t.Line, Value = LuaValue.FromString( t.Text ) } };\r\n\t\t}\r\n\t\tif ( t.Kind == TokenKind.LBrace ) return new[] { ParseTable() };\r\n\r\n\t\tExpect( TokenKind.LParen, \u0022function arguments\u0022 );\r\n\t\tif ( Accept( TokenKind.RParen ) ) return Array.Empty\u003CExpr\u003E();\r\n\t\tvar list = ParseExprList();\r\n\t\tExpectMatch( TokenKind.RParen, TokenKind.LParen, t.Line );\r\n\t\treturn list;\r\n\t}\r\n\r\n\tExpr ParseTable()\r\n\t{\r\n\t\tint line = Expect( TokenKind.LBrace ).Line;\r\n\t\tvar positional = new List\u003CExpr\u003E();\r\n\t\tvar keys = new List\u003CExpr\u003E();\r\n\t\tvar values = new List\u003CExpr\u003E();\r\n\t\tvar order = new List\u003C(bool, int)\u003E();\r\n\r\n\t\twhile ( Kind != TokenKind.RBrace )\r\n\t\t{\r\n\t\t\tif ( Kind == TokenKind.LBracket )\r\n\t\t\t{\r\n\t\t\t\tAdvance();\r\n\t\t\t\tvar k = ParseExpr();\r\n\t\t\t\tExpect( TokenKind.RBracket );\r\n\t\t\t\tExpect( TokenKind.Assign );\r\n\t\t\t\torder.Add( (false, keys.Count) );\r\n\t\t\t\tkeys.Add( k );\r\n\t\t\t\tvalues.Add( ParseExpr() );\r\n\t\t\t}\r\n\t\t\telse if ( Kind == TokenKind.Name \u0026\u0026 PeekKind() == TokenKind.Assign )\r\n\t\t\t{\r\n\t\t\t\tvar nt = Advance();\r\n\t\t\t\tAdvance();\r\n\t\t\t\torder.Add( (false, keys.Count) );\r\n\t\t\t\tkeys.Add( new ConstExpr { Line = nt.Line, Value = LuaValue.FromString( nt.Text ) } );\r\n\t\t\t\tvalues.Add( ParseExpr() );\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\torder.Add( (true, positional.Count) );\r\n\t\t\t\tpositional.Add( ParseExpr() );\r\n\t\t\t}\r\n\r\n\t\t\tif ( !Accept( TokenKind.Comma ) \u0026\u0026 !Accept( TokenKind.Semicolon ) ) break;\r\n\t\t}\r\n\t\tExpectMatch( TokenKind.RBrace, TokenKind.LBrace, line );\r\n\r\n\t\treturn new TableExpr\r\n\t\t{\r\n\t\t\tLine = line,\r\n\t\t\tPositional = positional.ToArray(),\r\n\t\t\tKeys = keys.ToArray(),\r\n\t\t\tValues = values.ToArray(),\r\n\t\t\tOrder = order.ToArray(),\r\n\t\t};\r\n\t}\r\n}\r\n"}]}