content
stringlengths
5
1.05M
if os.getenv('LOCAL_LUA_DEBUGGER_VSCODE') == '1' then require('lldebugger').start() end require 'src/global' local backgroundX = 0 function love.load () math.randomseed(os.time()) love.graphics.setDefaultFilter('nearest', 'nearest') Push:setupScreen(VIRTUAL_WIDTH, VIRTUAL_HEIGHT, WINDOW_WIDTH, WINDOW_HEIGHT, { resizable = true }) Gamestate.registerEvents() Gamestate.switch(States.home) Sounds.music:setLooping(true) Sounds.music:play() end function love.resize (w, h) Push:resize(w,h) end function love.update (dt) backgroundX = backgroundX - 40*dt if backgroundX <= -977 + VIRTUAL_WIDTH then backgroundX = 0 end Timer.update(dt) end function love.draw () love.window.setTitle(string.gsub(love.window.getTitle(), ' %- .+', '') .. ' - FPS: ' .. love.timer.getFPS()) Push:start() love.graphics.draw(Graphics.background, backgroundX, 0) Gamestate.current():render() Push:finish() end
return Def.ActorFrame { --OnCommand=cmd(sleep,999); LoadActor(THEME:GetPathG("","_BGMovies/gameover"))..{ InitCommand=cmd(Cover); }; LoadActor(THEME:GetPathS("ScreenGameOver","music"))..{ OnCommand=cmd(play); }; Def.Quad{ InitCommand=cmd(diffuse,Color("White");setsize,SCREEN_WIDTH,SCREEN_HEIGHT;Center;diffusealpha,0); OnCommand=cmd(sleep,4.5;linear,.5;diffusealpha,1;); }; }; --[[return Def.ActorFrame{ InitCommand=function(self) GAMESTATE:ApplyGameCommand("stopmusic"); SOUND:PlayOnce(THEME:GetPathS("ScreenGameOver", "music")); end; Def.Quad{ InitCommand=cmd(setsize,SCREEN_WIDTH,SCREEN_HEIGHT;diffuse,Color("Black");diffusealpha,0;Center); OnCommand=cmd(sleep,3;linear,1;diffusealpha,1); }; LoadFont("common normal")..{ Text="Thank You For Playing"; InitCommand=cmd(Center;zoom,1.5;diffusebottomedge,Color("HoloBlue");); OnCommand=cmd(sleep,3;decelerate,.5;zoomy,0;zoomx,3); }; LoadFont("common normal")..{ Text="SEE YOU NEXT GAME"; InitCommand=cmd(Center;addy,50;diffusebottomedge,Color("HoloBlue")); OnCommand=cmd(sleep,3;decelerate,.5;zoomy,0;zoomx,3); }; };]]
local hdoor_list = { --Number , Description , default image { "cobble" , "Hidden Cobble Door", "default_cobble"}, { "stone" , "Hidden Stone Door", "default_stone"}, { "wood", "Hidden Wood Door", "default_wood"}, { "stone_brick", "Hidden Stone Brick Door", "default_stone_brick"}, { "brick", "Hidden Brick Door", "default_brick"}, { "desert_cobble", "Hidden Desert Cobble Door", "default_desert_cobble"}, { "furnace", "Hidden Furnace Door" , "mydoors_furnace" , "door7"}, { "chest", "Hidden Chest Door" , "mydoors_chest" , "door8"}, { "bookshelf", "Hidden Bookshelf Door" , "mydoors_bookshelf" , "door9"}, } for i in ipairs(hdoor_list) do local img = hdoor_list[i][1] local desc = hdoor_list[i][2] --local dimg = hdoor_list[i][3] doors.register_door("my_hidden_doors:hidden_door"..img, { description = desc.." Locked", inventory_image = "mydoors_"..img.."_inv.png", groups = {choppy=2,cracky=2,door=1}, only_placer_can_open = false, tiles = {{ name = "mydoors_"..img..".png", backface_culling = true }}, protected = false, }) end doors.register_door("my_hidden_doors:hidden_door_grey", { description = "Grey Door Locked", inventory_image = "mydoors_grey_inv.png", groups = {choppy=2,cracky=2,door=1}, tiles = {{ name = "mydoors_grey.png", backface_culling = true }}, protected = false, }) -- Crafts minetest.register_craft({ output = "my_hidden_doors:hidden_doorcobble 1", recipe = { {"my_hidden_doors:hidden_door_grey", "default:cobble", ""}, {"", "", ""}, {"", "", ""} } }) minetest.register_craft({ output = "my_hidden_doors:hidden_doorstone 1", recipe = { {"my_hidden_doors:hidden_door_grey", "default:stone", ""}, {"", "", ""}, {"", "", ""} } }) minetest.register_craft({ output = "my_hidden_doors:hidden_doorwood 1", recipe = { {"my_hidden_doors:hidden_door_grey", "default:wood", ""}, {"", "", ""}, {"", "", ""} } }) minetest.register_craft({ output = "my_hidden_doors:hidden_doorstone_brick 1", recipe = { {"my_hidden_doors:hidden_door_grey", "default:stonebrick", ""}, {"", "", ""}, {"", "", ""} } }) minetest.register_craft({ output = "my_hidden_doors:hidden_doordesert_cobble 1", recipe = { {"my_hidden_doors:hidden_door_grey", "default:desert_cobble", ""}, {"", "", ""}, {"", "", ""} } }) minetest.register_craft({ output = "my_hidden_doors:hidden_doorfurnace 1", recipe = { {"my_hidden_doors:hidden_door_grey", "default:furnace", ""}, {"", "", ""}, {"", "", ""} } }) minetest.register_craft({ output = "my_hidden_doors:hidden_doorchest 1", recipe = { {"my_hidden_doors:hidden_door_grey", "default:chest", ""}, {"", "", ""}, {"", "", ""} } }) minetest.register_craft({ output = "my_hidden_doors:hidden_doorbookshelf 1", recipe = { {"my_hidden_doors:hidden_door_grey", "default:bookshelf", ""}, {"", "", ""}, {"", "", ""} } }) minetest.register_craft({ output = "my_hidden_doors:hidden_doorbrick 1", recipe = { {"my_hidden_doors:hidden_door_grey", "default:brick", ""}, {"", "", ""}, {"", "", ""} } }) minetest.register_craft({ output = "my_hidden_doors:hidden_door_grey 1", recipe = { {"my_door_wood:wood_dark_grey", "my_door_wood:wood_dark_grey", ""}, {"my_door_wood:wood_dark_grey", "my_door_wood:wood_dark_grey", ""}, {"my_door_wood:wood_dark_grey", "my_door_wood:wood_dark_grey", ""} } })
common = dofile("common.lua") assert = common.assert local url = require("url") --local sys = require("sys") -- URLs to parse, and expected data -- { url = parsed } local parseTests = { ["//some_path"] = { href = "//some_path", pathname = "//some_path" }, ["http://www.narwhaljs.org/blog/categories?id=news"] = { href = "http://www.narwhaljs.org/blog/categories?id=news", protocol = "http:", host = "www.narwhaljs.org", hostname = "www.narwhaljs.org", search = "?id=news", query = "id=news", pathname = "/blog/categories" }, ["http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s="] = { href = "http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=", protocol = "http:", host = "mt0.google.com", hostname = "mt0.google.com", pathname = "/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=" }, ["http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s="] = { href = "http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=", protocol = "http:", host = "mt0.google.com", hostname = "mt0.google.com", search = "???&hl=en&src=api&x=2&y=2&z=3&s=", query = "??&hl=en&src=api&x=2&y=2&z=3&s=", pathname = "/vt/lyrs=m@114" }, ["http://user:[email protected]/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s="] = { href = "http://user:[email protected]/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=", protocol = "http:", host = "user:[email protected]", auth = "user:pass", hostname = "mt0.google.com", search = "???&hl=en&src=api&x=2&y=2&z=3&s=", query = "??&hl=en&src=api&x=2&y=2&z=3&s=", pathname = "/vt/lyrs=m@114" }, ["file:///etc/passwd"] = { href = "file:///etc/passwd", protocol = "file:", pathname = "///etc/passwd" }, ["file:///etc/node/"] = { href = "file:///etc/node/", protocol = "file:", pathname = "///etc/node/" }, ["http:/baz/../foo/bar"] = { href = "http:/baz/../foo/bar", protocol = "http:", pathname = "/baz/../foo/bar" }, ["http://user:[email protected]:8000/foo/bar?baz=quux#frag"] = { href = "http://user:[email protected]:8000/foo/bar?baz=quux#frag", protocol = "http:", host = "user:[email protected]:8000", auth = "user:pass", port = "8000", hostname = "example.com", hash = "#frag", search = "?baz=quux", query = "baz=quux", pathname = "/foo/bar" }, ["//user:[email protected]:8000/foo/bar?baz=quux#frag"] = { href = "//user:[email protected]:8000/foo/bar?baz=quux#frag", host = "user:[email protected]:8000", auth = "user:pass", port = "8000", hostname = "example.com", hash = "#frag", search = "?baz=quux", query = "baz=quux", pathname = "/foo/bar" }, ["http://example.com?foo=bar#frag"] = { href = "http://example.com?foo=bar#frag", protocol = "http:", host = "example.com", hostname = "example.com", hash = "#frag", search = "?foo=bar", query = "foo=bar" }, ["http://example.com?foo=@bar#frag"] = { href = "http://example.com?foo=@bar#frag", protocol = "http:", host = "example.com", hostname = "example.com", hash = "#frag", search = "?foo=@bar", query = "foo=@bar" }, ["http://example.com?foo=/bar/#frag"] = { href = "http://example.com?foo=/bar/#frag", protocol = "http:", host = "example.com", hostname = "example.com", hash = "#frag", search = "?foo=/bar/", query = "foo=/bar/" }, ["http://example.com?foo=?bar/#frag"] = { href = "http://example.com?foo=?bar/#frag", protocol = "http:", host = "example.com", hostname = "example.com", hash = "#frag", search = "?foo=?bar/", query = "foo=?bar/" }, ["http://example.com#frag=?bar/#frag"] = { href = "http://example.com#frag=?bar/#frag", protocol = "http:", host = "example.com", hostname = "example.com", hash = "#frag=?bar/#frag" }, ["/foo/bar?baz=quux#frag"] = { href = "/foo/bar?baz=quux#frag", hash = "#frag", search = "?baz=quux", query = "baz=quux", pathname = "/foo/bar" }, ["http:/foo/bar?baz=quux#frag"] = { href = "http:/foo/bar?baz=quux#frag", protocol = "http:", hash = "#frag", search = "?baz=quux", query = "baz=quux", pathname = "/foo/bar" }, ["mailto:[email protected]?subject=hello"] = { href = "mailto:[email protected]?subject=hello", protocol = "mailto:", host = "[email protected]", auth = "foo", hostname = "bar.com", search = "?subject=hello", query = "subject=hello" }, ["javascript:alert('hello');"] = { href = "javascript:alert('hello');", protocol = "javascript:", host = "alert('hello')", hostname = "alert('hello')", pathname = ";" }, ["xmpp:[email protected]"] = { href = "xmpp:[email protected]", protocol = "xmpp:", host = "[email protected]", auth = "isaacschlueter", hostname = "jabber.org" } } for u, expected in pairs(parseTests) do local actual = url.parse(u) for kk, a in pairs(expected) do local e = expected[kk] --local e = JSON.stringify(expected[i]) --local a = JSON.stringify(actual[i]) assert.equal(e, a, "parse(" .. u .. ")." .. kk .. " == " .. e .. "\nactual: " .. a) end local actual = url.format(expected) local expected = u assert.equal(expected, actual, "format(" .. u .. ") == " .. u .. "\nactual:" .. actual) end local parseTestsWithQueryString = { ["/foo/bar?baz=quux#frag"] = { href = "/foo/bar?baz=quux#frag", hash = "#frag", search = "?baz=quux", query = { baz = "quux" }, pathname = "/foo/bar" }, } --[[ for (var u in parseTestsWithQueryString) { var actual = url.parse(u,true); var expected = parseTestsWithQueryString[u]; for (var i in expected) { var e = JSON.stringify(expected[i]), a = JSON.stringify(actual[i]); assert.equal(e, a, "parse(" + u + ")."+i+" == "+e+"\nactual: "+a); } } --]] for u, expected in pairs(parseTestsWithQueryString) do local actual = url.parse(u, true) for kk, vv in pairs(expected) do local e = expected[kk] local a = expected[vv] assert.equal(e, a, "parse(" .. u .. ")." .. i .. " == " .. e .. "\nactual: " .. a) end end --[====[ -- some extra formatting tests, just to verify that it'll format slightly wonky content to a valid url. local formatTests = { ["http://a.com/a/b/c?s#h"] = { protocol = "http", host = "a.com", pathname = "a/b/c", hash = "h", search = "s" }, ["xmpp:[email protected]"] = { href = "xmpp://[email protected]", protocol = "xmpp:", host = "[email protected]", auth = "isaacschlueter", hostname = "jabber.org" } } for (var u in formatTests) { var actual = url.format(formatTests[u]); assert.equal(actual, u, "wonky format("+u+") == "+u+"\nactual:"+actual); } for _, relativeTest in ipairs{ -- {from, path, expected] {"/foo/bar/baz", "quux", "/foo/bar/quux"}, {"/foo/bar/baz", "quux/asdf", "/foo/bar/quux/asdf"}, {"/foo/bar/baz", "quux/baz", "/foo/bar/quux/baz"}, {"/foo/bar/baz", "../quux/baz", "/foo/quux/baz"}, {"/foo/bar/baz", "/bar", "/bar"}, {"/foo/bar/baz/", "quux", "/foo/bar/baz/quux"}, {"/foo/bar/baz/", "quux/baz", "/foo/bar/baz/quux/baz"}, {"/foo/bar/baz", "../../../../../../../../quux/baz", "/quux/baz"}, {"/foo/bar/baz", "../../../../../../../quux/baz", "/quux/baz"}, {"foo/bar", "../../../baz", "../../baz"}, {"foo/bar/", "../../../baz", "../baz"}, {"http://example.com/b//c//d;p?q#blarg","https:#hash2","https:///#hash2" }, {"http://example.com/b//c//d;p?q#blarg","https:/p/a/t/h?s#hash2","https://p/a/t/h?s#hash2" }, {"http://example.com/b//c//d;p?q#blarg","https://u:[email protected]/p/a/t/h?s#hash2","https://u:[email protected]/p/a/t/h?s#hash2"}, {"http://example.com/b//c//d;p?q#blarg","https:/a/b/c/d","https://a/b/c/d"}, {"http://example.com/b//c//d;p?q#blarg","http:#hash2","http://example.com/b//c//d;p?q#hash2" }, {"http://example.com/b//c//d;p?q#blarg","http:/p/a/t/h?s#hash2","http://example.com/p/a/t/h?s#hash2" }, {"http://example.com/b//c//d;p?q#blarg","http://u:[email protected]/p/a/t/h?s#hash2","http://u:[email protected]/p/a/t/h?s#hash2" }, {"http://example.com/b//c//d;p?q#blarg","http:/a/b/c/d","http://example.com/a/b/c/d"}, {"/foo/bar/baz", "/../etc/passwd", "/etc/passwd"} } do local a = url.resolve(relativeTest[1], relativeTest[2]) local e = relativeTest[3] assert.equal(e, a, "resolve(" .. [relativeTest[1], relativeTest[2]]..") == "..e.. "\n actual="..a) end -- -- Tests below taken from Chiron -- http://code.google.com/p/chironjs/source/browse/trunk/src/test/http/url.js -- -- Copyright (c) 2002-2008 Kris Kowal <http://cixar.com/~kris.kowal> -- used with permission under MIT License -- -- Changes marked with @isaacs local bases = { 'http://a/b/c/d;p?q', 'http://a/b/c/d;p?q=1/2', 'http://a/b/c/d;p=1/2?q', 'fred:///s//a/b/c', 'http:///s//a/b/c' } -- {to, from, result} for _, relativeTest in ipairs{ -- http://lists.w3.org/Archives/Public/uri/2004Feb/0114.html {'../c', 'foo:a/b', 'foo:c'}, {'foo:.', 'foo:a', 'foo:'}, {'/foo/../../../bar', 'zz:abc', 'zz:/bar'}, {'/foo/../bar', 'zz:abc', 'zz:/bar'}, {'foo/../../../bar', 'zz:abc', 'zz:bar'}, -- @isaacs Disagree. Not how web browsers resolve this. -- {'foo/../../../bar', 'zz:abc', 'zz:../../bar'}, -- @isaacs Added {'foo/../bar', 'zz:abc', 'zz:bar'}, {'zz:.', 'zz:abc', 'zz:'}, {'/.' , bases[0], 'http://a/'}, {'/.foo' , bases[0], 'http://a/.foo'}, {'.foo' , bases[0], 'http://a/b/c/.foo'}, -- http://gbiv.com/protocols/uri/test/rel_examples1.html -- examples from RFC 2396 {'g:h' , bases[0], 'g:h'}, {'g' , bases[0], 'http://a/b/c/g'}, {'./g' , bases[0], 'http://a/b/c/g'}, {'g/' , bases[0], 'http://a/b/c/g/'}, {'/g' , bases[0], 'http://a/g'}, {'//g' , bases[0], 'http://g'}, -- changed with RFC 2396bis --('?y' , bases[0], 'http://a/b/c/d;p?y'}, {'?y' , bases[0], 'http://a/b/c/d;p?y'}, {'g?y' , bases[0], 'http://a/b/c/g?y'}, -- changed with RFC 2396bis --('#s' , bases[0], CURRENT_DOC_URI + '#s'}, {'#s' , bases[0], 'http://a/b/c/d;p?q#s'}, {'g#s' , bases[0], 'http://a/b/c/g#s'}, {'g?y#s' , bases[0], 'http://a/b/c/g?y#s'}, {';x' , bases[0], 'http://a/b/c/;x'}, {'g;x' , bases[0], 'http://a/b/c/g;x'}, {'g;x?y#s' , bases[0], 'http://a/b/c/g;x?y#s'}, -- changed with RFC 2396bis --('' , bases[0], CURRENT_DOC_URI], {'' , bases[0], 'http://a/b/c/d;p?q'}, {'.' , bases[0], 'http://a/b/c/'}, {'./' , bases[0], 'http://a/b/c/'}, {'..' , bases[0], 'http://a/b/'}, {'../' , bases[0], 'http://a/b/'}, {'../g' , bases[0], 'http://a/b/g'}, {'../..' , bases[0], 'http://a/'}, {'../../' , bases[0], 'http://a/'}, {'../../g' , bases[0], 'http://a/g'}, {'../../../g', bases[0], ('http://a/../g', 'http://a/g')], {'../../../../g', bases[0], ('http://a/../../g', 'http://a/g')], -- changed with RFC 2396bis --('/./g', bases[0], 'http://a/./g'}, {'/./g', bases[0], 'http://a/g'}, -- changed with RFC 2396bis --('/../g', bases[0], 'http://a/../g'}, {'/../g', bases[0], 'http://a/g'}, {'g.', bases[0], 'http://a/b/c/g.'}, {'.g', bases[0], 'http://a/b/c/.g'}, {'g..', bases[0], 'http://a/b/c/g..'}, {'..g', bases[0], 'http://a/b/c/..g'}, {'./../g', bases[0], 'http://a/b/g'}, {'./g/.', bases[0], 'http://a/b/c/g/'}, {'g/./h', bases[0], 'http://a/b/c/g/h'}, {'g/../h', bases[0], 'http://a/b/c/h'}, {'g;x=1/./y', bases[0], 'http://a/b/c/g;x=1/y'}, {'g;x=1/../y', bases[0], 'http://a/b/c/y'}, {'g?y/./x', bases[0], 'http://a/b/c/g?y/./x'}, {'g?y/../x', bases[0], 'http://a/b/c/g?y/../x'}, {'g#s/./x', bases[0], 'http://a/b/c/g#s/./x'}, {'g#s/../x', bases[0], 'http://a/b/c/g#s/../x'}, {'http:g', bases[0], ('http:g', 'http://a/b/c/g')], {'http:', bases[0], ('http:', bases[0])], -- not sure where this one originated {'/a/b/c/./../../g', bases[0], 'http://a/a/g'}, -- http://gbiv.com/protocols/uri/test/rel_examples2.html -- slashes in base URI's query args {'g' , bases[1], 'http://a/b/c/g'}, {'./g' , bases[1], 'http://a/b/c/g'}, {'g/' , bases[1], 'http://a/b/c/g/'}, {'/g' , bases[1], 'http://a/g'}, {'//g' , bases[1], 'http://g'}, -- changed in RFC 2396bis --('?y' , bases[1], 'http://a/b/c/?y'}, {'?y' , bases[1], 'http://a/b/c/d;p?y'}, {'g?y' , bases[1], 'http://a/b/c/g?y'}, {'g?y/./x' , bases[1], 'http://a/b/c/g?y/./x'}, {'g?y/../x', bases[1], 'http://a/b/c/g?y/../x'}, {'g#s' , bases[1], 'http://a/b/c/g#s'}, {'g#s/./x' , bases[1], 'http://a/b/c/g#s/./x'}, {'g#s/../x', bases[1], 'http://a/b/c/g#s/../x'}, {'./' , bases[1], 'http://a/b/c/'}, {'../' , bases[1], 'http://a/b/'}, {'../g' , bases[1], 'http://a/b/g'}, {'../../' , bases[1], 'http://a/'}, {'../../g' , bases[1], 'http://a/g'}, -- http://gbiv.com/protocols/uri/test/rel_examples3.html -- slashes in path params -- all of these changed in RFC 2396bis {'g' , bases[2], 'http://a/b/c/d;p=1/g'}, {'./g' , bases[2], 'http://a/b/c/d;p=1/g'}, {'g/' , bases[2], 'http://a/b/c/d;p=1/g/'}, {'g?y' , bases[2], 'http://a/b/c/d;p=1/g?y'}, {';x' , bases[2], 'http://a/b/c/d;p=1/;x'}, {'g;x' , bases[2], 'http://a/b/c/d;p=1/g;x'}, {'g;x=1/./y', bases[2], 'http://a/b/c/d;p=1/g;x=1/y'}, {'g;x=1/../y', bases[2], 'http://a/b/c/d;p=1/y'}, {'./' , bases[2], 'http://a/b/c/d;p=1/'}, {'../' , bases[2], 'http://a/b/c/'}, {'../g' , bases[2], 'http://a/b/c/g'}, {'../../' , bases[2], 'http://a/b/'}, {'../../g' , bases[2], 'http://a/b/g'}, -- http://gbiv.com/protocols/uri/test/rel_examples4.html -- double and triple slash, unknown scheme {'g:h' , bases[3], 'g:h'}, {'g' , bases[3], 'fred:///s//a/b/g'}, {'./g' , bases[3], 'fred:///s//a/b/g'}, {'g/' , bases[3], 'fred:///s//a/b/g/'}, {'/g' , bases[3], 'fred:///g'}, -- may change to fred:///s//a/g {'//g' , bases[3], 'fred://g'}, -- may change to fred:///s//g {'//g/x' , bases[3], 'fred://g/x'}, -- may change to fred:///s//g/x {'///g' , bases[3], 'fred:///g'}, {'./' , bases[3], 'fred:///s//a/b/'}, {'../' , bases[3], 'fred:///s//a/'}, {'../g' , bases[3], 'fred:///s//a/g'}, {'../../' , bases[3], 'fred:///s//'}, {'../../g' , bases[3], 'fred:///s//g'}, {'../../../g', bases[3], 'fred:///s/g'}, {'../../../../g', bases[3], 'fred:///g'}, -- may change to fred:///s//a/../../../g -- http://gbiv.com/protocols/uri/test/rel_examples5.html -- double and triple slash, well-known scheme {'g:h' , bases[4], 'g:h'}, {'g' , bases[4], 'http:///s//a/b/g'}, {'./g' , bases[4], 'http:///s//a/b/g'}, {'g/' , bases[4], 'http:///s//a/b/g/'}, {'/g' , bases[4], 'http:///g'}, -- may change to http:///s//a/g {'//g' , bases[4], 'http://g'}, -- may change to http:///s//g {'//g/x' , bases[4], 'http://g/x'}, -- may change to http:///s//g/x {'///g' , bases[4], 'http:///g'}, {'./' , bases[4], 'http:///s//a/b/'}, {'../' , bases[4], 'http:///s//a/'}, {'../g' , bases[4], 'http:///s//a/g'}, {'../../' , bases[4], 'http:///s//'}, {'../../g' , bases[4], 'http:///s//g'}, {'../../../g', bases[4], 'http:///s/g'}, -- may change to http:///s//a/../../g {'../../../../g', bases[4], 'http:///g'}, -- may change to http:///s//a/../../../g -- from Dan Connelly's tests in http://www.w3.org/2000/10/swap/uripath.py {"bar:abc", "foo:xyz", "bar:abc"], {'../abc', 'http://example/x/y/z', 'http://example/x/abc'}, {'http://example/x/abc', 'http://example2/x/y/z', 'http://example/x/abc'}, {'../r', 'http://ex/x/y/z', 'http://ex/x/r'}, {'q/r', 'http://ex/x/y', 'http://ex/x/q/r'}, {'q/r#s', 'http://ex/x/y', 'http://ex/x/q/r#s'}, {'q/r#s/t', 'http://ex/x/y', 'http://ex/x/q/r#s/t'}, {'ftp://ex/x/q/r', 'http://ex/x/y', 'ftp://ex/x/q/r'}, {'', 'http://ex/x/y', 'http://ex/x/y'}, {'', 'http://ex/x/y/', 'http://ex/x/y/'}, {'', 'http://ex/x/y/pdq', 'http://ex/x/y/pdq'}, {'z/', 'http://ex/x/y/', 'http://ex/x/y/z/'}, {'#Animal', 'file:/swap/test/animal.rdf', 'file:/swap/test/animal.rdf#Animal'}, {'../abc', 'file:/e/x/y/z', 'file:/e/x/abc'}, {'/example/x/abc', 'file:/example2/x/y/z', 'file:/example/x/abc'}, {'../r', 'file:/ex/x/y/z', 'file:/ex/x/r'}, {'/r', 'file:/ex/x/y/z', 'file:/r'}, {'q/r', 'file:/ex/x/y', 'file:/ex/x/q/r'}, {'q/r#s', 'file:/ex/x/y', 'file:/ex/x/q/r#s'}, {'q/r#', 'file:/ex/x/y', 'file:/ex/x/q/r#'}, {'q/r#s/t', 'file:/ex/x/y', 'file:/ex/x/q/r#s/t'}, {'ftp://ex/x/q/r', 'file:/ex/x/y', 'ftp://ex/x/q/r'}, {'', 'file:/ex/x/y', 'file:/ex/x/y'}, {'', 'file:/ex/x/y/', 'file:/ex/x/y/'}, {'', 'file:/ex/x/y/pdq', 'file:/ex/x/y/pdq'}, {'z/', 'file:/ex/x/y/', 'file:/ex/x/y/z/'}, {'file://meetings.example.com/cal#m1', 'file:/devel/WWW/2000/10/swap/test/reluri-1.n3', 'file://meetings.example.com/cal#m1'}, {'file://meetings.example.com/cal#m1', 'file:/home/connolly/w3ccvs/WWW/2000/10/swap/test/reluri-1.n3', 'file://meetings.example.com/cal#m1'}, {'./#blort', 'file:/some/dir/foo', 'file:/some/dir/#blort'}, {'./#', 'file:/some/dir/foo', 'file:/some/dir/#'}, -- Ryan Lee {"./", "http://example/x/abc.efg", "http://example/x/"], -- Graham Klyne's tests -- http://www.ninebynine.org/Software/HaskellUtils/Network/UriTest.xls -- 01-31 are from Connelly's cases -- 32-49 {'./q:r', 'http://ex/x/y', 'http://ex/x/q:r'}, {'./p=q:r', 'http://ex/x/y', 'http://ex/x/p=q:r'}, {'?pp/rr', 'http://ex/x/y?pp/qq', 'http://ex/x/y?pp/rr'}, {'y/z', 'http://ex/x/y?pp/qq', 'http://ex/x/y/z'}, {'local/[email protected]#frag', 'mailto:local', 'mailto:local/[email protected]#frag'}, {'more/[email protected]#frag', 'mailto:local/[email protected]', 'mailto:local/more/[email protected]#frag'}, {'y?q', 'http://ex/x/y?q', 'http://ex/x/y?q'}, {'/x/y?q', 'http://ex?p', 'http://ex/x/y?q'}, {'c/d', 'foo:a/b', 'foo:a/c/d'}, {'/c/d', 'foo:a/b', 'foo:/c/d'}, {'', 'foo:a/b?c#d', 'foo:a/b?c'}, {'b/c', 'foo:a', 'foo:b/c'}, {'../b/c', 'foo:/a/y/z', 'foo:/a/b/c'}, {'./b/c', 'foo:a', 'foo:b/c'}, {'/./b/c', 'foo:a', 'foo:/b/c'}, {'../../d', 'foo://a//b/c', 'foo://a/d'}, {'.', 'foo:a', 'foo:'}, {'..', 'foo:a', 'foo:'}, -- 50-57[cf. TimBL comments -- -- http://lists.w3.org/Archives/Public/uri/2003Feb/0028.html, -- http://lists.w3.org/Archives/Public/uri/2003Jan/0008.html) {'abc', 'http://example/x/y%2Fz', 'http://example/x/abc'}, {'../../x%2Fabc', 'http://example/a/x/y/z', 'http://example/a/x%2Fabc'}, {'../x%2Fabc', 'http://example/a/x/y%2Fz', 'http://example/a/x%2Fabc'}, {'abc', 'http://example/x%2Fy/z', 'http://example/x%2Fy/abc'}, {'q%3Ar', 'http://ex/x/y', 'http://ex/x/q%3Ar'}, {'/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'}, {'/x%2Fabc', 'http://example/x/y/z', 'http://example/x%2Fabc'}, {'/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'}, -- 70-77 {'local2@domain2', 'mailto:local1@domain1?query1', 'mailto:local2@domain2'}, {'local2@domain2?query2', 'mailto:local1@domain1', 'mailto:local2@domain2?query2'}, {'local2@domain2?query2', 'mailto:local1@domain1?query1', 'mailto:local2@domain2?query2'}, {'?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'}, {'local@domain?query2', 'mailto:?query1', 'mailto:local@domain?query2'}, {'?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'}, {'http://example/a/b?c/../d', 'foo:bar', 'http://example/a/b?c/../d'}, {'http://example/a/b#c/../d', 'foo:bar', 'http://example/a/b#c/../d'}, -- 82-88 -- ['http:this', 'http://example.org/base/uri', 'http:this'}, -- @isaacs Disagree. Not how browsers do it. ['http:this', 'http://example.org/base/uri', "http://example.org/base/this"], -- @isaacs Added ['http:this', 'http:base', 'http:this'}, ['.//g', 'f:/a', 'f://g'}, ['b/c//d/e', 'f://example.org/base/a', 'f://example.org/base/b/c//d/e'}, ['[email protected]/[email protected]', 'mid:[email protected]/[email protected]', 'mid:[email protected]/[email protected]/[email protected]'}, ['mini1.xml', 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/', 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/mini1.xml'}, ['../b/c', 'foo:a/y/z', 'foo:a/b/c'] } do local a = url.resolve(relativeTest[1], relativeTest[2]) local e = relativeTest[3] assert.equal(e, a, "resolve(" .. [relativeTest[1], relativeTest[2]]..") == "..e.. "\n actual="..a) end --]====]
korriban_world = { lairSpawns = { { lairTemplateName = "tatooine_outlaw_camp_neutral_medium_theater", spawnLimit = -1, minDifficulty = 2, maxDifficulty = 11, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_womprat_womprat_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 3, maxDifficulty = 7, numberToSpawn = 0, weighting = 8, size = 20 }, { lairTemplateName = "tatooine_womprat_lair_neutral_small", spawnLimit = -1, minDifficulty = 3, maxDifficulty = 7, numberToSpawn = 0, weighting = 8, size = 20 }, { lairTemplateName = "tatooine_tatooine_mynock_swarm_neutral_none", spawnLimit = -1, minDifficulty = 3, maxDifficulty = 7, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_tatooine_mynock_lair_neutral_small", spawnLimit = -1, minDifficulty = 3, maxDifficulty = 7, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_kreetle_over_death_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 3, maxDifficulty = 7, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_kreetle_lair_neutral_small", spawnLimit = -1, minDifficulty = 3, maxDifficulty = 7, numberToSpawn = 0, weighting = 8, size = 20 }, { lairTemplateName = "tatooine_kreetle_herd_neutral_none", spawnLimit = -1, minDifficulty = 3, maxDifficulty = 7, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_eopie_herd_neutral_none", spawnLimit = -1, minDifficulty = 3, maxDifficulty = 7, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_eopie_eopie_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 3, maxDifficulty = 7, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_outcast_camp_neutral_small_theater", spawnLimit = -1, minDifficulty = 4, maxDifficulty = 8, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_moisture_thief_neutral_medium_theater", spawnLimit = -1, minDifficulty = 4, maxDifficulty = 8, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_moisture_settler_neutral_medium_theater", spawnLimit = -1, minDifficulty = 4, maxDifficulty = 8, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_insane_kitonak_neutral_none", spawnLimit = -1, minDifficulty = 4, maxDifficulty = 8, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_hermit_neutral_small_theater", spawnLimit = -1, minDifficulty = 4, maxDifficulty = 8, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_evil_settlement_neutral_medium_theater", spawnLimit = -1, minDifficulty = 4, maxDifficulty = 8, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_trandosian_slaver_neutral_medium_theater", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 9, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_nomad_neutral_small_theater", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 9, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_worrt_herd_neutral_none", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 9, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_dwarf_nuna_nuna_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 9, numberToSpawn = 0, weighting = 8, size = 20 }, { lairTemplateName = "tatooine_dwarf_nuna_lair_neutral_medium", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 9, numberToSpawn = 0, weighting = 8, size = 20 }, { lairTemplateName = "tatooine_dwarf_nuna_herd_neutral_none", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 9, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_womprat_herd_neutral_none", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 14, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_wandering_kitonak_neutral_none", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 10, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_jawa_troop_neutral_none", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 10, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_evil_hermit_neutral_none", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 10, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_worrt_lair_neutral_small", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 10, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_womprat_slum_rat_neutral_none", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 10, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_rill_rill_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 10, numberToSpawn = 0, weighting = 8, size = 20 }, { lairTemplateName = "tatooine_rill_pack_neutral_none", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 10, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_rill_lair_neutral_small", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 10, numberToSpawn = 0, weighting = 8, size = 20 }, { lairTemplateName = "tatooine_kreetle_over_swarming_neutral_medium_boss_02", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 10, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_gorg_lair_neutral_small", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 10, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_gorg_herd_neutral_none", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 10, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_rodian_clan_outpost_neutral_large_theater", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 15, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_dim_u_church_neutral_large_theater", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 15, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_dim_u_chapel_neutral_small_theater", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 15, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_kreetle_over_neutral_none", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 15, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_jawa_squad_neutral_none", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 20, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_jawa_outpost_neutral_medium_theater", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 20, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_jawa_warband_neutral_none", spawnLimit = -1, minDifficulty = 6, maxDifficulty = 25, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_cannibal_neutral_none", spawnLimit = -1, minDifficulty = 7, maxDifficulty = 11, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_sevorrt_pack_neutral_none", spawnLimit = -1, minDifficulty = 7, maxDifficulty = 11, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_sevorrt_lair_neutral_medium", spawnLimit = -1, minDifficulty = 7, maxDifficulty = 11, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_gorg_glutton_neutral_none", spawnLimit = -1, minDifficulty = 7, maxDifficulty = 11, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_eopie_lair_neutral_small", spawnLimit = -1, minDifficulty = 7, maxDifficulty = 11, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_spice_fiend_neutral_small_theater", spawnLimit = -1, minDifficulty = 8, maxDifficulty = 12, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_jabba_swooper_camp_neutral_medium_theater", spawnLimit = -1, minDifficulty = 8, maxDifficulty = 12, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_rockmite_swarm_neutral_none", spawnLimit = -1, minDifficulty = 8, maxDifficulty = 12, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_rockmite_click_neutral_small", spawnLimit = -1, minDifficulty = 8, maxDifficulty = 12, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_diseased_bocatt_pack_neutral_none", spawnLimit = -1, minDifficulty = 8, maxDifficulty = 12, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_diseased_bocatt_lair_neutral_medium", spawnLimit = -1, minDifficulty = 8, maxDifficulty = 12, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_tusken_raider_village_neutral_large_theater", spawnLimit = -1, minDifficulty = 8, maxDifficulty = 27, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_dune_stalker_camp_neutral_medium_theater", spawnLimit = -1, minDifficulty = 8, maxDifficulty = 27, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_valarian_swooper_neutral_small_theater", spawnLimit = -1, minDifficulty = 9, maxDifficulty = 13, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_valarian_enforcer_neutral_medium_theater", spawnLimit = -1, minDifficulty = 9, maxDifficulty = 13, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_mound_mite_swarm_neutral_none", spawnLimit = -1, minDifficulty = 9, maxDifficulty = 13, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_mound_mite_click_neutral_small", spawnLimit = -1, minDifficulty = 9, maxDifficulty = 13, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_dewback_lesser_neutral_none", spawnLimit = -1, minDifficulty = 9, maxDifficulty = 13, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_dewback_lesser_lair_neutral_small", spawnLimit = -1, minDifficulty = 9, maxDifficulty = 13, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_valarian_assasin_neutral_large_theater", spawnLimit = -1, minDifficulty = 9, maxDifficulty = 18, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_jabba_enforcer_camp_neutral_medium_theater", spawnLimit = -1, minDifficulty = 9, maxDifficulty = 18, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_jabba_assasin_camp_neutral_large_theater", spawnLimit = -1, minDifficulty = 9, maxDifficulty = 18, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_desert_demon_patrol_neutral_none", spawnLimit = -1, minDifficulty = 9, maxDifficulty = 18, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_desert_demon_outpost_neutral_large_theater", spawnLimit = -1, minDifficulty = 9, maxDifficulty = 18, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_weequay_outpost_neutral_large_theater", spawnLimit = -1, minDifficulty = 9, maxDifficulty = 23, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_zucca_boar_zucca_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 10, maxDifficulty = 14, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_zucca_boar_pack_neutral_none", spawnLimit = -1, minDifficulty = 10, maxDifficulty = 14, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_zucca_boar_lair_neutral_medium", spawnLimit = -1, minDifficulty = 10, maxDifficulty = 14, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_jundland_eopie_lair_neutral_medium", spawnLimit = -1, minDifficulty = 10, maxDifficulty = 14, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_jundland_eopie_herd_neutral_none", spawnLimit = -1, minDifficulty = 10, maxDifficulty = 14, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_mountain_squill_lair_neutral_medium", spawnLimit = -1, minDifficulty = 10, maxDifficulty = 34, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_cupa_cupa_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 11, maxDifficulty = 15, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_cu_pa_herd_neutral_none", spawnLimit = -1, minDifficulty = 11, maxDifficulty = 15, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_scyk_scyk_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 12, maxDifficulty = 16, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_scyk_pack_neutral_none", spawnLimit = -1, minDifficulty = 12, maxDifficulty = 16, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_scyk_lair_neutral_medium", spawnLimit = -1, minDifficulty = 12, maxDifficulty = 16, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_alkhara_bandit_patrol_neutral_none", spawnLimit = -1, minDifficulty = 13, maxDifficulty = 17, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_worrt_giant_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 13, maxDifficulty = 17, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_mutant_womprat_lair_neutral_small", spawnLimit = -1, minDifficulty = 13, maxDifficulty = 17, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_mutant_womprat_herd_neutral_none", spawnLimit = -1, minDifficulty = 13, maxDifficulty = 17, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_giant_worrt_lair_neutral_medium", spawnLimit = -1, minDifficulty = 13, maxDifficulty = 17, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_giant_worrt_herd_neutral_none", spawnLimit = -1, minDifficulty = 13, maxDifficulty = 17, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_alkhara_bandit_outpost_neutral_large_theater", spawnLimit = -1, minDifficulty = 13, maxDifficulty = 22, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_rock_beetle_swarm_neutral_none", spawnLimit = -1, minDifficulty = 13, maxDifficulty = 22, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_rock_beetle_click_neutral_medium", spawnLimit = -1, minDifficulty = 13, maxDifficulty = 22, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_swarming_lesser_dewback_lair_neutral_large", spawnLimit = -1, minDifficulty = 15, maxDifficulty = 19, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_swarming_lesser_dewback_herd_neutral_none", spawnLimit = -1, minDifficulty = 15, maxDifficulty = 19, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_rogue_bantha_neutral_none", spawnLimit = -1, minDifficulty = 15, maxDifficulty = 19, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_feral_bantha_lair_neutral_large", spawnLimit = -1, minDifficulty = 15, maxDifficulty = 19, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_feral_bantha_herd_neutral_none", spawnLimit = -1, minDifficulty = 15, maxDifficulty = 19, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_bocatt_lair_neutral_medium", spawnLimit = -1, minDifficulty = 15, maxDifficulty = 19, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_matriarch_bantha_lair_neutral_large", spawnLimit = -1, minDifficulty = 15, maxDifficulty = 29, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_matriarch_bantha_herd_neutral_none", spawnLimit = -1, minDifficulty = 15, maxDifficulty = 29, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_desert_eopie_lair_neutral_small", spawnLimit = -1, minDifficulty = 16, maxDifficulty = 20, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_desert_eopie_herd_neutral_none", spawnLimit = -1, minDifficulty = 16, maxDifficulty = 20, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_dune_bantha_lair_neutral_large", spawnLimit = -1, minDifficulty = 17, maxDifficulty = 21, numberToSpawn = 0, weighting = 8, size = 30 }, { lairTemplateName = "tatooine_dune_bantha_herd_neutral_none", spawnLimit = -1, minDifficulty = 17, maxDifficulty = 21, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_bantha_dune_bantha_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 17, maxDifficulty = 21, numberToSpawn = 0, weighting = 8, size = 30 }, { lairTemplateName = "tatooine_squill_squill_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 18, maxDifficulty = 22, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_squill_pack_neutral_none", spawnLimit = -1, minDifficulty = 18, maxDifficulty = 22, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_squill_lair_neutral_small", spawnLimit = -1, minDifficulty = 18, maxDifficulty = 22, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_ronto_lair_neutral_large", spawnLimit = -1, minDifficulty = 18, maxDifficulty = 22, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_dune_lizard_pack_neutral_none", spawnLimit = -1, minDifficulty = 18, maxDifficulty = 22, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_dune_lizard_lair_neutral_medium", spawnLimit = -1, minDifficulty = 18, maxDifficulty = 22, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_dune_lizard_dune_lizard_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 18, maxDifficulty = 22, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_ronto_herd_neutral_none", spawnLimit = -1, minDifficulty = 18, maxDifficulty = 27, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_dewback_lair_neutral_large", spawnLimit = -1, minDifficulty = 19, maxDifficulty = 23, numberToSpawn = 0, weighting = 8, size = 30 }, { lairTemplateName = "tatooine_dewback_herd_neutral_none", spawnLimit = -1, minDifficulty = 19, maxDifficulty = 23, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_dewback_dewback_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 19, maxDifficulty = 23, numberToSpawn = 0, weighting = 8, size = 30 }, { lairTemplateName = "tatooine_cu_pa_lair_neutral_medium", spawnLimit = -1, minDifficulty = 19, maxDifficulty = 23, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_cu_pa_wasteland_lair_neutral_medium", spawnLimit = -1, minDifficulty = 19, maxDifficulty = 23, numberToSpawn = 0, weighting = 6, size = 25 }, { lairTemplateName = "tatooine_tusken_raider_patrol_neutral_none", spawnLimit = -1, minDifficulty = 19, maxDifficulty = 33, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_mountain_dewback_lair_neutral_large", spawnLimit = -1, minDifficulty = 20, maxDifficulty = 24, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_mountain_dewback_herd_neutral_none", spawnLimit = -1, minDifficulty = 20, maxDifficulty = 24, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_desert_squill_pack_neutral_none", spawnLimit = -1, minDifficulty = 20, maxDifficulty = 24, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_desert_squill_lair_neutral_small", spawnLimit = -1, minDifficulty = 20, maxDifficulty = 24, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_bull_bantha_lair_neutral_large", spawnLimit = -1, minDifficulty = 20, maxDifficulty = 24, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_bull_bantha_herd_neutral_none", spawnLimit = -1, minDifficulty = 20, maxDifficulty = 24, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_cannibal_dewback_lair_neutral_large", spawnLimit = -1, minDifficulty = 21, maxDifficulty = 25, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_cannibal_dewback_herd_neutral_none", spawnLimit = -1, minDifficulty = 21, maxDifficulty = 25, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_mountain_worrt_lair_neutral_large", spawnLimit = -1, minDifficulty = 22, maxDifficulty = 26, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_mountain_worrt_herd_neutral_none", spawnLimit = -1, minDifficulty = 22, maxDifficulty = 26, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_greater_womprat_lair_neutral_medium", spawnLimit = -1, minDifficulty = 22, maxDifficulty = 26, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_greater_womprat_herd_neutral_none", spawnLimit = -1, minDifficulty = 22, maxDifficulty = 26, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_bocatt_pack_neutral_none", spawnLimit = -1, minDifficulty = 22, maxDifficulty = 26, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_bocatt_bocatt_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 22, maxDifficulty = 26, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_ronto_male_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 23, maxDifficulty = 27, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_desert_razorback_razorback_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 24, maxDifficulty = 28, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_imperial_camp", spawnLimit = -1, minDifficulty = 25, maxDifficulty = 29, numberToSpawn = 0, weighting = 15, size = 20 }, { lairTemplateName = "tatooine_mountain_squill_pack_neutral_none", spawnLimit = -1, minDifficulty = 25, maxDifficulty = 34, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_giant_sand_beetle_swarm_neutral_none", spawnLimit = -1, minDifficulty = 25, maxDifficulty = 34, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_giant_sand_beetle_click_neutral_large", spawnLimit = -1, minDifficulty = 25, maxDifficulty = 34, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_grizzled_dewback_lair_neutral_large", spawnLimit = -1, minDifficulty = 27, maxDifficulty = 31, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_grizzled_dewback_herd_neutral_none", spawnLimit = -1, minDifficulty = 27, maxDifficulty = 31, numberToSpawn = 0, weighting = 15, size = 30 }, { lairTemplateName = "tatooine_dragonet_pack_neutral_none", spawnLimit = -1, minDifficulty = 29, maxDifficulty = 33, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_dragonet_lair_neutral_medium", spawnLimit = -1, minDifficulty = 29, maxDifficulty = 33, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_dragonet_dragonet_neutral_medium_boss_01", spawnLimit = -1, minDifficulty = 29, maxDifficulty = 33, numberToSpawn = 0, weighting = 8, size = 25 }, { lairTemplateName = "tatooine_tusken_raider_warband_neutral_none", spawnLimit = -1, minDifficulty = 34, maxDifficulty = 63, numberToSpawn = 0, weighting = 12, size = 25 }, { lairTemplateName = "tatooine_wild_dune_boar_neutral_none", spawnLimit = -1, minDifficulty = 39, maxDifficulty = 53, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_tusken_raider_kingdom_neutral_large_theater", spawnLimit = -1, minDifficulty = 41, maxDifficulty = 100, numberToSpawn = 0, weighting = 10, size = 30 }, { lairTemplateName = "tatooine_squill_malignant_neutral_none", spawnLimit = -1, minDifficulty = 50, maxDifficulty = 54, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_canyon_krayt_dragon_pack_neutral_none", spawnLimit = 10, minDifficulty = 122, maxDifficulty = 276, numberToSpawn = 0, weighting = 4, size = 35 }, { lairTemplateName = "tatooine_canyon_krayt_dragon_lair_neutral_large", spawnLimit = 10, minDifficulty = 122, maxDifficulty = 276, numberToSpawn = 0, weighting = 4, size = 35 }, { lairTemplateName = "tatooine_giant_canyon_krayt_dragon_pack_neutral_none", spawnLimit = 5, minDifficulty = 275, maxDifficulty = 304, numberToSpawn = 0, weighting = 2, size = 35 }, { lairTemplateName = "tatooine_giant_canyon_krayt_dragon_lair_neutral_large", spawnLimit = 5, minDifficulty = 275, maxDifficulty = 304, numberToSpawn = 0, weighting = 2, size = 35 }, } } addSpawnGroup("korriban_world", korriban_world);
//________________________________ // // NS2 CustomEntitesMod // Made by JimWest 2012 // //________________________________ Script.Load("lua/FunctionContracts.lua") Script.Load("lua/PathingUtility.lua") ScaledModelMixin = CreateMixin( ScaledModelMixin ) ScaledModelMixin.type = "ScaledModel" ScaledModelMixin.expectedMixins = { } ScaledModelMixin.expectedCallbacks = { } ScaledModelMixin.optionalCallbacks = { } ScaledModelMixin.networkVars = { } // create a model if theres a model value function ScaledModelMixin:__initmixin() end function ScaledModelMixin:SetScaledModel(model, animationGraph) if model ~= nil then Shared.PrecacheModel(model) //local graphName = string.gsub(model, ".model", ".animation_graph") //if graphName then // Shared.PrecacheAnimationGraph(graphName) //end if animationGraph then self:SetModel(model, animationGraph) else self:SetModel(model) end end end // only way to scale the model function ScaledModelMixin:OnAdjustModelCoords(modelCoords) local coords = modelCoords if self.scale and self.scale:GetLength() ~= 0 then coords.xAxis = coords.xAxis * self.scale.x coords.yAxis = coords.yAxis * self.scale.y coords.zAxis = coords.zAxis * self.scale.z end return coords end
local name, value = ... _G[name] = value
--[[ Author: Noya Used by: Pizzalol Date: 14.03.2015. Levels up the ability_name to the same level of the ability that runs this ]] function LevelUpAbility( event ) local caster = event.caster local this_ability = event.ability local this_abilityName = this_ability:GetAbilityName() local this_abilityLevel = this_ability:GetLevel() -- The ability to level up local ability_name = event.ability_name local ability_handle = caster:FindAbilityByName(ability_name) local ability_level = ability_handle:GetLevel() -- Check to not enter a level up loop if ability_level ~= this_abilityLevel then ability_handle:SetLevel(this_abilityLevel) end end --[[Author: Pizzalol Date: 18.03.2015. Initialize the axes]] function WhirlingAxesMelee( keys ) local caster = keys.caster local caster_location = caster:GetAbsOrigin() local ability = keys.ability local ability_level = ability:GetLevel() - 1 local start_radius = ability:GetLevelSpecialValueFor("start_radius", ability_level) caster.whirling_axes_melee_hit_table = {} -- Visuals local axe_projectile = keys.axe_projectile local axe_modifier = keys.axe_modifier -- Starting position calculation local angle_east = QAngle(0,-90,0) local angle_west = QAngle(0,90,0) local forward_vector = caster:GetForwardVector() local front_position = caster_location + forward_vector * start_radius local position_east = RotatePosition(caster_location, angle_east, front_position) local position_west = RotatePosition(caster_location, angle_west, front_position) -- East axe if caster.whirling_axes_east and IsValidEntity(caster.whirling_axes_east) then caster.whirling_axes_east:RemoveSelf() end -- Create the axe caster.whirling_axes_east = CreateUnitByName("npc_dota_troll_warlord_axe", position_east, false, caster, caster, caster:GetTeam() ) ability:ApplyDataDrivenModifier(caster, caster.whirling_axes_east, axe_modifier, {}) -- Set the particle local particle_east = ParticleManager:CreateParticle(axe_projectile, PATTACH_ABSORIGIN_FOLLOW, caster.whirling_axes_east) ParticleManager:SetParticleControlEnt(particle_east, 1, caster.whirling_axes_east, PATTACH_POINT_FOLLOW, "attach_hitloc", caster.whirling_axes_east:GetAbsOrigin(), true) ParticleManager:SetParticleControl(particle_east, 4, Vector(5,0,0)) -- Save the relevant data for movement calculation caster.whirling_axes_east.axe_radius = start_radius caster.whirling_axes_east.start_time = GameRules:GetGameTime() caster.whirling_axes_east.side = 0 -- West axe if caster.whirling_axes_west and IsValidEntity(caster.whirling_axes_west) then caster.whirling_axes_west:RemoveSelf() end -- Create the axe caster.whirling_axes_west = CreateUnitByName("npc_dota_troll_warlord_axe", position_west, false, caster, caster, caster:GetTeam() ) ability:ApplyDataDrivenModifier(caster, caster.whirling_axes_west, axe_modifier, {}) -- Set the particle local particle_west = ParticleManager:CreateParticle(axe_projectile, PATTACH_ABSORIGIN_FOLLOW, caster.whirling_axes_west) ParticleManager:SetParticleControlEnt(particle_west, 1, caster.whirling_axes_west, PATTACH_POINT_FOLLOW, "attach_hitloc", caster.whirling_axes_west:GetAbsOrigin(), true) ParticleManager:SetParticleControl(particle_west, 4, Vector(5,0,0)) -- Save the relevant data for movement calculation caster.whirling_axes_west.axe_radius = start_radius caster.whirling_axes_west.start_time = GameRules:GetGameTime() caster.whirling_axes_west.side = 1 end --[[Author: Pizzalol, Ractidous Date: 18.03.2015. Moves the axes around the caster]] function WhirlingAxesMeleeThink( keys ) local caster = keys.caster local target = keys.target local caster_location = caster:GetAbsOrigin() local ability = keys.ability local ability_level = ability:GetLevel() - 1 local elapsed_time = GameRules:GetGameTime() - target.start_time -- If the caster is not alive then remove the axes if not caster:IsAlive() then target:RemoveSelf() return end -- Ability variables local axe_movement_speed = ability:GetLevelSpecialValueFor("axe_movement_speed", ability_level) local max_range = ability:GetLevelSpecialValueFor("max_range", ability_level) local whirl_duration = ability:GetLevelSpecialValueFor("whirl_duration", ability_level) local axe_turn_rate = ability:GetLevelSpecialValueFor("axe_turn_rate", ability_level) local hit_radius = ability:GetLevelSpecialValueFor("hit_radius", ability_level) local think_interval = ability:GetLevelSpecialValueFor("think_interval", ability_level) -- Calculate the radius and limit it to the max range local currentRadius = target.axe_radius local deltaRadius = axe_movement_speed / whirl_duration/2 * think_interval -- This is how fast the axe grows outwards currentRadius = currentRadius + deltaRadius currentRadius = math.min( currentRadius, (max_range - hit_radius)) -- Limit it to the max range -- Save the radius for the next think interval target.axe_radius = currentRadius -- Check which axe is it and then rotate it accordingly local rotation_angle if target.side == 1 then rotation_angle = elapsed_time * axe_turn_rate -- 360 is the turnrate else rotation_angle = elapsed_time * axe_turn_rate + 180 -- Add 180 to rotate it 180 degrees so both axes dont appear at 1 point end -- Rotate the current position local relPos = Vector( 0, currentRadius, 0 ) relPos = RotatePosition( Vector(0,0,0), QAngle( 0, -rotation_angle, 0 ), relPos ) -- Set the position around the target it is supposed to spin around local absPos = GetGroundPosition( relPos + caster_location, target ) target:SetAbsOrigin( absPos ) -- Check if its time to kill the axes if elapsed_time >= whirl_duration then target:RemoveSelf() end end --[[Author: Pizzalol Date: 18.03.2015. Checks if the target has been hit before and then does logic according to that]] function WhirlingAxesMeleeHit( keys ) local caster = keys.caster local target = keys.target local ability = keys.ability local ability_level = ability:GetLevel() - 1 local modifier = keys.modifier local sound = keys.sound -- Ability variables local blind_duration = ability:GetLevelSpecialValueFor("blind_duration", ability_level) local damage = ability:GetLevelSpecialValueFor("damage", ability_level) -- Check if the target has been hit before local hit_check = false for _,unit in ipairs(caster.whirling_axes_melee_hit_table) do if unit == target then hit_check = true break end end -- If the target hasnt been hit before then insert it into the hit table to keep track of it if not hit_check then table.insert(caster.whirling_axes_melee_hit_table, target) -- Apply the blind modifier and play the sound ability:ApplyDataDrivenModifier(caster, target, modifier, {Duration = blind_duration}) EmitSoundOn(sound, target) -- Initialize the damage table and deal damage to the target local damage_table = {} damage_table.attacker = caster damage_table.victim = target damage_table.ability = ability damage_table.damage_type = ability:GetAbilityDamageType() damage_table.damage = damage ApplyDamage(damage_table) end end
Config = { offset = 0, original_volume = 100, system_muted = false, code_seek_just_performed = false, checker = {} } return Config
-- 矩形モジュール local Rectangle = {} -- 初期化 function Rectangle:initialize(x, y, w, h) self.x = x or self.x or 0 self.y = y or self.y or 0 self.width = w or self.width or 0 self.height = h or self.height or 0 end -- 矩形の描画 function Rectangle:drawRectangle() love.graphics.rectangle('line', self:left(), self:top(), self:right() - self:left(), self:bottom() - self:top()) end -- 左端の座標 function Rectangle:left() return self.x - self.width / 2 end -- 上端の座標 function Rectangle:top() return self.y - self.height / 2 end -- 右端の座標 function Rectangle:right() return self:left() + self.width end -- 下端の座標 function Rectangle:bottom() return self:top() + self.height end return Rectangle
local PluginRoot = script.Parent.Parent.Parent local Modules = PluginRoot.Core.Modules local Utilities = require(Modules.Utilities) local CameraState = require(Modules.CameraState) local InputState = require(Modules.InputState) local PairSampler = require(Modules.PairSampler) local Constants = require(Modules.Constants) local roundUp = Utilities.roundUp local roundDown = Utilities.roundDown local CAST_DEPTH = Constants.CAST_DEPTH local CAST_DISTANCE = Constants.CAST_DISTANCE local TURBO_SAMPLER_BUDGET = Constants.TURBO_SAMPLER_BUDGET local MOVING_SAMPLER_BUDGET = Constants.MOVING_SAMPLER_BUDGET local FRAMES_TO_SAMPLER_TURBO = Constants.FRAMES_TO_SAMPLER_TURBO local SAMPLE_SPACING = Constants.SAMPLE_SPACING local SAMPLING_GRID_SIZE = Constants.SAMPLING_GRID_SIZE local CircleSelector = {} CircleSelector.__index = CircleSelector local DEBUG_GENERATOR = false local DEBUG_RAYCAST = false local DEBUG_WARN_WHEN_SAMPLER_DONE = false local debugCircle, debugRaycast if DEBUG_RAYCAST or DEBUG_GENERATOR then local CoreGui = game:GetService("CoreGui") local RunService = game:GetService("RunService") local debugCircleGui = Instance.new("ScreenGui") debugCircleGui.Name = "DebugCircle" debugCircleGui.Parent = CoreGui local freePixels = {} local function putPixel(x, y) local pixel = table.remove(freePixels) if not pixel then pixel = Instance.new("Frame") pixel.Size = UDim2.fromOffset(SAMPLE_SPACING, SAMPLE_SPACING) pixel.AnchorPoint = Vector2.new(0.5, 0.5) pixel.BorderSizePixel = 0 end pixel.BackgroundColor3 = Color3.new(1, 0, 0) pixel.Position = UDim2.fromOffset(x, y) pixel.Parent = debugCircleGui coroutine.wrap(function() for i = 0, 10 do local per = i/10 pixel.BackgroundTransparency = per pixel.BackgroundColor3 = Color3.new(1, 0, 0):lerp(Color3.new(0, 0, 0), per) RunService.Heartbeat:Wait() end pixel.Parent = nil table.insert(freePixels, pixel) end)() end function debugCircle(x, y) putPixel(x, y) end function debugRaycast(x, y) putPixel(x, y) end end --[[ A sequence of indices in a SAMPLING_GRID_SIZE x SAMPLING_GRID_SIZE grid (0 to SAMPLING_GRID_SIZE^2-1). Pattern looks like this when you iterate through it (assuming SAMPLING_GRID_SIZE is 8): i = 1 x_______ ________ ________ ________ ________ ________ ________ ________ i = 4 x___x___ ________ ________ ________ x___x___ ________ ________ ________ i = 16 x_x_x_x_ ________ x_x_x_x_ ________ x_x_x_x_ ________ x_x_x_x_ ________ i = 64 xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx As you can see, the indices are ordered such that iterating through them results in a pattern that gets more and more granular. This is also the reason why SAMPLING_GRID_SIZE must be a power of 2. ]] local gridTraversalOrder do gridTraversalOrder = {} local alreadyVisited = {} local fac = SAMPLING_GRID_SIZE while fac >= 1 do for y = 0, SAMPLING_GRID_SIZE-1 do for x = 0, SAMPLING_GRID_SIZE-1 do if x%fac == 0 and y%fac == 0 then local i = x + y*SAMPLING_GRID_SIZE if not alreadyVisited[i] then table.insert(gridTraversalOrder, i) alreadyVisited[i] = true end end end end fac = fac/2 end end local function createCircleGenerator(centerX, centerY, radius) local generator = coroutine.wrap(function() local radiusSquared = radius * radius local minY = roundDown(centerY - radius, SAMPLE_SPACING) local maxY = roundUp(centerY + radius, SAMPLE_SPACING) local minX = roundDown(centerX - radius, SAMPLE_SPACING) local maxX = roundUp(centerX + radius, SAMPLE_SPACING) for _, i in ipairs(gridTraversalOrder) do local xOffset = (i%SAMPLING_GRID_SIZE) * SAMPLE_SPACING local yOffset = math.floor(i/SAMPLING_GRID_SIZE) * SAMPLE_SPACING for y = minY+yOffset, maxY, SAMPLE_SPACING*SAMPLING_GRID_SIZE do for x = minX+xOffset, maxX, SAMPLE_SPACING*SAMPLING_GRID_SIZE do local distSquared = (x - centerX) ^ 2 + (y - centerY) ^ 2 if distSquared < radiusSquared then if DEBUG_GENERATOR then debugCircle(x, y) end coroutine.yield(x, y) end end end end return end) return generator end local function createRaycastCallback(cameraState) local width = cameraState.viewportX local height = cameraState.viewportY local worldHeight = math.tan(math.rad(cameraState.fov / 2)) * CAST_DEPTH * 2 local worldWidth = (width / height) * worldHeight local down = -cameraState.up local right = cameraState.right local look = cameraState.look local position = cameraState.position local topLeft = position + (look * CAST_DEPTH) + right * worldWidth * -0.5 + down * worldHeight * -0.5 local widthVec = right * worldWidth local heightVec = down * worldHeight local raycastParams = RaycastParams.new() local ignoreList = {} raycastParams.FilterDescendantsInstances = ignoreList raycastParams.FilterType = Enum.RaycastFilterType.Blacklist return function(x, y) local origin = topLeft + widthVec * x / width + heightVec * y / height local dir = (origin - position).unit * CAST_DISTANCE local hit while true do local result = workspace:Raycast(origin, dir, raycastParams) if result == nil then break end hit = result.Instance if hit and hit.Transparency == 1 then table.insert(ignoreList, hit) raycastParams.FilterDescendantsInstances = ignoreList else break end end if hit and not hit.Locked then return { hit } else return {} end end end function CircleSelector.new(initialRadius, initialCameraState, initialInputState) local self = {} setmetatable(self, CircleSelector) self.committed = false self.radius = initialRadius self.cameraState = initialCameraState self.inputState = initialInputState self.started = false self:_resetPending() self:_resetHovered() self:_resetSampleCache() self:_resetSampler() self:_updateCursorInfo() if not initialInputState.leftMouseDown then self.started = true end return self end function CircleSelector:_resetSampleCache() self.alreadySampled = {} self.sampleCache = {} end function CircleSelector:_resetSampler() self.raycaster = createRaycastCallback(self.cameraState) self.circleGen = createCircleGenerator(self.inputState.x, self.inputState.y, self.radius) self.sampler = PairSampler.create( self.alreadySampled, self.sampleCache, self.circleGen, function(x, y) if DEBUG_RAYCAST then debugRaycast(x, y) end local hit = self.raycaster(x, y) return hit end ) self.samplerRunningFrames = 0 self.isSamplerDone = false end function CircleSelector:_calculateSamplerBudget() if self.samplerRunningFrames > FRAMES_TO_SAMPLER_TURBO then return TURBO_SAMPLER_BUDGET else return MOVING_SAMPLER_BUDGET end end function CircleSelector:step(cameraState, inputState) if CameraState.isDifferent(self.cameraState, cameraState) then local oldCameraState = self.cameraState self.cameraState = cameraState self:_onCameraStateChanged(cameraState, oldCameraState) end if InputState.isDifferent(self.inputState, inputState) then local oldInputState = self.inputState self.inputState = inputState self:_onInputStateChanged(inputState, oldInputState) end if self.committed or not self.started then return end local timeStartedSampling = tick() local mouseDown = inputState.leftMouseDown local pendingToAdd, hoveredToAdd = {}, {} local samplerBudget = self:_calculateSamplerBudget() debug.profilebegin("CircleSelector, step sample") while not self.isSamplerDone do local cached, hits = self.sampler() if cached == nil then self.isSamplerDone = true if DEBUG_WARN_WHEN_SAMPLER_DONE then warn("Sampler done.") end break end for _, hit in pairs(hits) do if mouseDown then if not self.pendingSet[hit] then self.pendingSet[hit] = true table.insert(pendingToAdd, hit) end end if not self.pendingSet[hit] and not self.hoveredSet[hit] then self.hoveredSet[hit] = true table.insert(hoveredToAdd, hit) end end local timeSpentSampling = tick() - timeStartedSampling if timeSpentSampling > samplerBudget then break end end debug.profileend() debug.profilebegin("CircleSelector, step tables") local updated = false if #pendingToAdd > 0 then table.move(self.pending, 1, #self.pending, #pendingToAdd+1, pendingToAdd) local newPending = pendingToAdd self.pending = newPending updated = true end if #hoveredToAdd > 0 then table.move(self.hovered, 1, #self.hovered, #hoveredToAdd+1, hoveredToAdd) local newHovered = hoveredToAdd self.hovered = newHovered updated = true end debug.profileend() self.samplerRunningFrames = self.samplerRunningFrames+1 return updated end function CircleSelector:_onCameraStateChanged(newCameraState, oldCameraState) if self.committed then return end self:_resetSampleCache() self:_resetSampler() self:_resetHovered() end function CircleSelector:_onInputStateChanged(newInputState, oldInputState) if self.committed then return end local wasMouseDown = oldInputState.leftMouseDown local isMouseDown = newInputState.leftMouseDown if self.started then if not isMouseDown and wasMouseDown then self.committed = true end else if not isMouseDown then self.started = true end end if self.committed then return end self:_resetSampler() self:_resetHovered() self:_updateCursorInfo() end function CircleSelector:_updateCursorInfo() self.cursorInfo = { x = self.inputState.x, y = self.inputState.y, } end function CircleSelector:getCursorInfo() return self.cursorInfo end function CircleSelector:getPending() return self.pending end function CircleSelector:getHovered() return self.hovered end function CircleSelector:_resetPending() if self.pendingSet and next(self.pendingSet) == nil then return end self.pending = {} self.pendingSet = {} end function CircleSelector:_resetHovered() if self.hoveredSet and next(self.hoveredSet) == nil then return end self.hovered = {} self.hoveredSet = {} end function CircleSelector:getRadius() return self.radius end function CircleSelector:setRadius(radius) self.radius = radius self:_resetSampleCache() self:_resetSampler() self:_resetHovered() end function CircleSelector:isCommitted() return self.committed end function CircleSelector:destroy() end return CircleSelector
-- example top level script for web based build -- copyright 2016 Samuel Baird MIT Licence local platform = require('lt.moonshine.platform') local app = require('lt.app') -- preload assets then launch app app.launch( -- preferred logical screen size (will adjust logical size to canvas dimensions) { width = 480, height = 320 }, -- available asset scales and suffixes { -- only using one set of assets in this web build { scale = 2, suffix = '_x2'}, }, -- initial scene to launch 'preload_scene' )
-- -- EXF: Example Framework -- -- This should make examples easier and more enjoyable to use. -- All examples in one application! Yaay! -- -- Updated by Dresenpai -- Updated again by EntranceJew local exf = require 'exf' function love.load() exf:load() end function love.update(dt) end function love.draw() end function love.keypressed(k) end function love.keyreleased(k) end function love.mousepressed(x, y, b) end function love.mousereleased(x, y, b) end
package("gr") set_homepage("https://gr-framework.org/") set_description("GR framework: a graphics library for visualisation applications") set_license("MIT") if is_plat("windows") then if is_arch("x64") then add_urls("https://github.com/sciapp/gr/releases/download/v$(version)/gr-$(version)-Windows-x86_64-msvc.tar.gz") add_versions("0.57.0", "5e62a425e60885835fa8177ab5311c131bab0bb484722866ee931e81b77a6a5a") add_versions("0.58.0", "a8152c15613c8b8e02f57d2b19632576f133e353057d2d824e9b85c203c3aa90") end elseif is_plat("macosx") then if is_arch("arm64") then add_urls("https://github.com/sciapp/gr/releases/download/v$(version)/gr-$(version)-Darwin-aarch64.tar.gz") add_versions("0.57.0", "a867a9233a26f8797f13adf2b7d9324a397a84d256750db0a29f4b5032b9a47f") add_versions("0.58.0", "3c0132bc7c26665ed812381e103091273999352a3cda8d9e664759c143387755") else add_urls("https://github.com/sciapp/gr/releases/download/v$(version)/gr-$(version)-Darwin-x86_64.tar.gz") add_versions("0.57.0", "b6114420b6ffff1cc41c7a325b53fd2af90942c5d7840ff27b1217488b6fb950") add_versions("0.58.0", "1c808852fec10badea7a5282bc867c5bcc86eda89e07bce7b2f0017a889f16cf") end elseif is_plat("linux") then if is_arch("x86_64") then if linuxos.name() == "ubuntu" then add_urls("https://github.com/sciapp/gr/releases/download/v$(version)/gr-$(version)-Ubuntu-x86_64.tar.gz") add_versions("0.57.0", "5f157733b750be6e8e771e008bf2dab1ee786d50efcc16deb02f6cdda9d03a54") add_versions("0.58.0", "c72767b2880fd561508e526286b30c3fc9bfa78f432ac966eb6455d318c1374d") elseif linuxos.name() == "debian" then add_urls("https://github.com/sciapp/gr/releases/download/v$(version)/gr-$(version)-Debian-x86_64.tar.gz") add_versions("0.57.0", "f20e65b4b93df1409377355cefca0fda714f5b4f1bf0c2292c0bad4232ac0a41") add_versions("0.58.0", "5fc6fe7b58193fbfac9fc32538d1078dd9ab5a606d38e3fdb2a1683b37ec2a76") elseif linuxos.name() == "archlinux" then add_urls("https://github.com/sciapp/gr/releases/download/v$(version)/gr-$(version)-ArchLinux-x86_64.tar.gz") add_versions("0.57.0", "3224971f16a8cc223f57ea240dea346747ea18111c91b64b38b5554f93721cf8") add_versions("0.58.0", "f90fb2b15459d0c3075326646c31a041a61c9b84b4d4ebe015b4283a43c2fe6e") elseif linuxos.name() == "centos" then add_urls("https://github.com/sciapp/gr/releases/download/v$(version)/gr-$(version)-CentOS-x86_64.tar.gz") add_versions("0.57.0", "877d6066690c6dc071db1edb64e79d738fdde6d9a7d4562f33bb76d8b9324b1c") add_versions("0.58.0", "3d403550ae440d4aac607bd61a9c4140ee98390c48ed44594eebef55308466ed") else add_urls("https://github.com/sciapp/gr/releases/download/v$(version)/gr-$(version)-Linux-x86_64.tar.gz") add_versions("0.57.0", "793fef6a18f8faa7bc4fbb2067691bc355a9111b5c2ae5ea41f3552d6c7064d5") add_versions("0.58.0", "d7350611e7bd8a3ff1034b2d13fe4c10c65f99c85c994a32e6dd6da59cb7de3c") end elseif is_arch("x86") then add_urls("https://github.com/sciapp/gr/releases/download/v$(version)/gr-$(version)-Linux-i386.tar.gz") add_versions("0.57.0", "f6ec390e1f9b2a0a83d5b7da95ebfe615aedc84075475a28c363b671353c65c5") add_versions("0.58.0", "681dbd0fa7cea25e189d4f58e5a4b7cf002cea2b13a663df67598f95f6a548a6") end end on_load("windows|x64", "macosx", "linux|x86,x86_64", function (package) local libs = {"GR", "GR3", "GRM", "GKS"} local prefix = "" if package:is_plat("windows") then prefix = "lib" else package:add("ldflags", "-Wl,-rpath," .. package:installdir("lib")) end for _, lib in ipairs(libs) do package:add("links", prefix .. lib) end end) on_install("windows|x64", "macosx", "linux|x86,x86_64", function (package) os.cp("*", package:installdir()) package:addenv("PATH", ".") package:addenv("PATH", "bin") package:addenv("GRDIR", package:installdir()) package:addenv("GKS_WSTYPE", package:is_plat("windows") and "41" or "x11") end) on_test(function (package) package:check_csnippets({test = [[ void test() { double x[] = {0, 0.2, 0.4, 0.6, 0.8, 1.0}; double y[] = {0.3, 0.5, 0.4, 0.2, 0.6, 0.7}; gr_beginprint("test.png"); gr_polyline(6, x, y); gr_axes(gr_tick(0, 1), gr_tick(0, 1), 0, 0, 1, 1, -0.01); gr_endprint(); } ]]}, {includes = "gr.h"}) end)
local L = LibStub("AceLocale-3.0"):NewLocale("SimpleChatCleaner", "enUS", true) if not L then return end L["Simple Chat Cleaner"] = true L["Debug"] = true L["enabled"] = true L["Enabled"] = true L["disabled"] = true L["Enables the Chat Cleaner"] = true L["Toggles debug mode"] = true L["Match Whole Words"] = true L["Filter by the full word only instead of partial matches"] = true L["Filter Friendly"] = true L["Filter friends and guild members"] = true L["AddonEnabled"] = function(X,Y, cmd) return 'version ' .. X .. ' by |cFF00FF00' .. Y .. '|r loaded. |cFF00FF00 /' .. cmd .. '|r to configure.' end L["SessionCount"] = function(ct) return ct .. " messages blocked this session" end L["Add Word to Filter One"] = true L["Adds a word to the first Filter Group"] = true L["Add Word to Filter Two"] = true L["Adds a word to the second Filter Group"] = true L["List Filters"] = true L["List all word filters to the chat console"] = true L["Clear All Filters"] = true L["Removes all words from all filters"] = true L["Config Options"] = true L["Filters"] = true L["Filter Yell"] = true L["Filter /yell"] = true L["Filter Say"] = true L["Filter /say"] = true L["All Channels"] = true L["Empty Filter"] = true L["Channels"] = true L["All Channels"] = true L["Add Channel"] = true L["Adds a channel to filter on, an empty list means ALL channels"] = true L["Stats"] = true L["Show basic filtering stats"] = true -- addon command triggers L["scc"] = true L["simplechatcleaner"] = true L["simplechat"] = true
local _M = {} function _M.set_tracer_provider(tp) _M.tracer_provider = tp end function _M.get_tracer_provider() return _M.tracer_provider end function _M.tracer(name, opts) return _M.tracer_provider:tracer(name, opts) end return _M
require 'image' require 'nn' require 'qt' local optnet = require 'optnet' torch.setdefaulttensortype('torch.FloatTensor') torch.manualSeed(1) opt = { batchSize = 64, -- number of samples to produce noisetype = 'normal', -- type of noise distribution (uniform / normal). net = '', -- path to the generator network imsize = 1, -- used to produce larger images. 1 = 64px. 2 = 80px, 3 = 96px, ... noisemode = 'random', -- random / line / linefull1d / linefull name = 'generation1', -- name of the file saved gpu = 1, -- gpu mode. 0 = CPU, 1 = GPU nz = 100, } for k,v in pairs(opt) do opt[k] = tonumber(os.getenv(k)) or os.getenv(k) or opt[k] end print(opt) if opt.display == 0 then opt.display = false end assert(net ~= '', 'provide a generator model') net = torch.load(opt.net) -- for older models, there was nn.View on the top -- which is unnecessary, and hinders convolutional generations. if torch.type(net:get(1)) == 'nn.View' then net:remove(1) end print(net) local sample_input = torch.randn(2,100,1,1) if opt.gpu > 0 then require 'cunn' require 'cudnn' net:cuda() cudnn.convert(net, cudnn) sample_input = sample_input:cuda() else sample_input = sample_input:float() net:float() end net:evaluate() -- a function to setup double-buffering across the network. -- this drastically reduces the memory needed to generate samples optnet.optimizeMemory(net, sample_input) local function regenerate() noise = torch.Tensor(opt.batchSize, opt.nz, opt.imsize, opt.imsize) noise:normal(0, 1) images = net:forward(noise) images:add(1):mul(0.5) for i=1, images:size(1) do images[i] = image.drawText(images[i], tostring(i), 3, 3, {color={255, 0, 0}, size=2}) end end -- A - B + C local A = {} local B = {} local C = {} print("We will be doing vector arithmetic A - B + C") local win local function choose(name, tab) -- choose images print("Choose three images for " .. name) for i = 1, 3 do print('Choose image number. Enter -1 to regenerate new images: ') local choice = -1 while choice == -1 do regenerate() win = image.display(images, nil, nil, nil, nil, win, nil, nil, true) choice=tonumber(io.read()) end print("Chosen image number " .. choice .. " for " .. name) table.insert(tab, noise[choice]:clone()) end print("Images for " .. name .. " have been chosen") end choose("A", A) choose("B", B) choose("C", C) if win then win.window:setHidden(true) end print("Generating A - B + C") local Aavg = (A[1] + A[2] + A[3]) / 3 local Bavg = (B[1] + B[2] + B[3]) / 3 local Cavg = (C[1] + C[2] + C[3]) / 3 local final_noise = Aavg - Bavg + Cavg -- final display -- place noise vectors in mini-batch noise[1]:copy(A[1]) noise[8]:copy(A[2]) noise[15]:copy(A[3]) noise[22]:copy(Aavg) noise[3]:copy(B[1]) noise[10]:copy(B[2]) noise[17]:copy(B[3]) noise[24]:copy(Bavg) noise[5]:copy(C[1]) noise[12]:copy(C[2]) noise[19]:copy(C[3]) noise[26]:copy(Cavg) noise[28]:copy(final_noise) -- generate images images = net:forward(noise) images:add(1):mul(0.5) -- insert + / - / = symbols images[23]:fill(0) images[25]:fill(0) images[27]:fill(0) images[23] = image.drawText(images[23], "-", 3, 3, {size=10, color={255, 0, 0}}) images[25] = image.drawText(images[25], "+", 3, 3, {size=10, color={255, 0, 0}}) images[27] = image.drawText(images[27], "=", 3, 3, {size=10, color={255, 0, 0}}) -- fill black to dummy boxes for i=0,2 do images[2+7*i]:fill(0) images[4+7*i]:fill(0) images[6+7*i]:fill(0) images[7+7*i]:fill(0) end final_image = image.toDisplayTensor({input=images:narrow(1,1,28), nrow = 7, scaleeach=true}) image.save('arithmetic.png', final_image) print("image saved to arithmetic.png") image.display(final_image)
local Spell = { } Spell.LearnTime = 60 Spell.Description = [[ A charm that allowed the caster to send out red sparks from their wand. The sparks were firework-like in appearance, and had a vast range, shooting up to a great height, then hovering in the spot where the caster aimed. ]] Spell.ApplyDelay = 0.4 Spell.FlyEffect = "hpw_periculum_main" Spell.ImpactEffect = "hpw_periculum_impact" Spell.ForceAnim = { ACT_VM_PRIMARYATTACK_5 } Spell.SpriteColor = Color(255, 80, 80) Spell.CanSelfCast = false Spell.NodeOffset = Vector(-846, -1094, 0) Spell.LeaveParticles = true function Spell:Draw(spell) self:DrawGlow(spell, nil, 128) end function Spell:SpellThink(spell) if SERVER then return end local dlight = DynamicLight(spell:EntIndex()) if dlight then dlight.pos = spell:GetPos() dlight.r = 255 dlight.g = 80 dlight.b = 80 dlight.brightness = 3 dlight.Decay = 600 dlight.Size = 1000 dlight.DieTime = CurTime() + 1 end --[[ if not spell.Emitter then spell.Emitter = ParticleEmitter(spell:GetPos()) return end for i = 1, 2 do local die = math.Rand(5, 15) local vel = VectorRand() * 30 + spell:GetFlyDirection() * 20 local res = math.random(15, 40) local size = math.random(16, 32) local p = spell.Emitter:Add("hpwrewrite/sprites/magicsprite", spell:GetPos()) p:SetDieTime(die) p:SetBounce(0.8) p:SetCollide(true) p:SetVelocity(vel) p:SetAirResistance(res) p:SetStartSize(size) p:SetEndSize(0) p:SetStartAlpha(255) p:SetEndAlpha(0) p:SetColor(255, 50, 50) local p = spell.Emitter:Add("hpwrewrite/sprites/magicsprite", spell:GetPos()) p:SetDieTime(die) p:SetBounce(0.8) p:SetCollide(true) p:SetVelocity(vel) p:SetAirResistance(res) p:SetStartSize(size / 3) p:SetEndSize(0) p:SetStartAlpha(255) p:SetEndAlpha(0) p:SetColor(255, 255, 255) end]] end --[[function Spell:OnRemove(spell) if CLIENT and spell.Emitter then spell.Emitter:Finish() end end]] function Spell:OnFire(wand) return true end --[[function Spell:OnSpellSpawned(wand, spell) wand:PlayCastSound() util.SpriteTrail(spell, 0, HpwRewrite.Colors.White, true, 32, 0, 0.6, 0.05, "hpwrewrite/particles/redrope.vmt") spell.Hovering = false spell.EndPos = Vector(0, 0, 0) local tr = util.TraceLine({ start = spell:GetPos(), endpos = spell:GetPos() + Vector(0, 0, 999999), filter = { spell, self.Owner } }) if tr.Hit then local dist = spell:GetPos():Distance(tr.HitPos) timer.Simple(dist / 10000, function() if spell:IsValid() then spell.EndPos = spell:GetPos() spell.Hovering = true SafeRemoveEntityDelayed(spell, 11) local phys = spell:GetPhysicsObject() if phys:IsValid() then phys:SetVelocity(phys:GetVelocity() * 0.1) end end end) end end]] function Spell:OnSpellSpawned(wand, spell) wand:PlayCastSound() timer.Simple(0.8, function() if IsValid(spell) then HpwRewrite.BlastDamage(self.Owner, spell:GetPos(), 200, 30) HpwRewrite.MakeEffect(self.ImpactEffect, spell:GetPos()) sound.Play("hpwrewrite/spells/periculum.wav", spell:GetPos(), 100, 100) SafeRemoveEntity(spell) end end) end function Spell:OnCollide(spell, data) HpwRewrite.BlastDamage(self.Owner, data.HitPos, 200, 30) sound.Play("hpwrewrite/spells/periculum.wav", data.HitPos, 100, 100) end --[[function Spell:PhysicsThink(spell, phys, dt) if spell.Hovering then return nil, ((spell.EndPos - spell:GetPos()):GetNormal() + VectorRand()) * 600000, true end return nil, nil, false end]] --[[function Spell:OnFire(wand) local newAng = self.Owner:EyeAngles() newAng.p = -90 local name = "hpwrewrite_periculum_handler" .. self.Owner:EntIndex() local time = CurTime() + 0.4 hook.Add("Think", name, function() if not IsValid(self.Owner) then hook.Remove("Think", name) return end if CurTime() > time then hook.Remove("Think", name) return end self.Owner:SetEyeAngles(LerpAngle(FrameTime() * 15, self.Owner:EyeAngles(), newAng)) end) return true end]] HpwRewrite:AddSpell("Periculum", Spell)
-- This module contains everything for highlighting Hop. local M = {} -- Insert the highlights that Hop uses. function M.insert_highlights() -- Highlight used for the mono-sequence keys (i.e. sequence of 1). vim.api.nvim_command("highlight default HopNextKey guifg=#ff007c gui=bold ctermfg=198 cterm=bold") -- Highlight used for the first key in a sequence. vim.api.nvim_command("highlight default HopNextKey1 guifg=#00dfff gui=bold ctermfg=45 cterm=bold") -- Highlight used for the second and remaining keys in a sequence. vim.api.nvim_command("highlight default HopNextKey2 guifg=#2b8db3 ctermfg=33") -- Highlight used for the unmatched part of the buffer. vim.api.nvim_command("highlight default HopUnmatched guifg=#666666 ctermfg=242") end function M.create_autocmd() vim.api.nvim_command("augroup HopInitHighlight") vim.api.nvim_command("autocmd!") vim.api.nvim_command("autocmd ColorScheme * lua require'hop.highlight'.insert_highlights()") vim.api.nvim_command("augroup end") end return M
-- Train an auto-encoder using config.json. require('torch') require('nn') require('optim') require('hdf5') require('cunn') require('lfs') --- Append the tensor tensor to the tensor acc which may initially be nil. local function appendTensor(acc, tensor) if acc == nil then acc = tensor:float() else acc = torch.cat(acc, tensor:float(), 1) end return acc end package.path = package.path .. ';../?/th/init.lua' lib = require('lib') cnncomplete = {} include('0_model.lua') -- Load configuration. configFile = 'config.json' if arg[1] and lib.utils.fileExists(arg[1]) then configFile = arg[1] end print('[Training] reading ' .. configFile) config = lib.utils.readJSON(configFile) config['sup_parameters']['model_file'] = config['base_directory'] .. config['sup_parameters']['model_file'] config['base_directory'] = config['base_directory'] .. '/sup/' config['test_directory'] = config['base_directory'] .. config['test_directory'] config['train_protocol_file'] = config['base_directory'] .. config['train_protocol_file'] config['val_protocol_file'] = config['base_directory'] .. config['val_protocol_file'] config['early_stop_file'] = config['base_directory'] .. config['early_stop_file'] keys = { 'inference_training_inputs', 'inference_training_sdf_inputs', 'inference_training_outputs', 'inference_training_sdf_outputs', 'validation_inputs', 'validation_sdf_inputs', 'validation_outputs', 'validation_sdf_outputs', } for i, key in pairs(keys) do config[key] = config['data_directory'] .. '/' .. config[key] if not lib.utils.fileOrDirectoryExists(config[key]) then print('[Error] file or directory ' .. config[key] .. ' does not exist') os.exit() end end -- Load data for training. print('[Training] reading ' .. config['inference_training_inputs']) inputs_1 = lib.utils.readHDF5(config['inference_training_inputs']) print('[Training] reading ' .. config['inference_training_sdf_inputs']) inputs_2 = lib.utils.readHDF5(config['inference_training_sdf_inputs']) nObservations = inputs_1:size(2) inputs_1 = inputs_1:resize(inputs_1:size(1)*inputs_1:size(2), 1, inputs_1:size(3), inputs_1:size(4), inputs_1:size(5)) inputs_2 = inputs_2:resize(inputs_2:size(1)*inputs_2:size(2), 1, inputs_2:size(3), inputs_2:size(4), inputs_2:size(5)) inputs = torch.cat({inputs_1:float(), inputs_2:float()}, 2) print('[Training] reading ' .. config['inference_training_outputs']) outputs_1 = lib.utils.readHDF5(config['inference_training_outputs']) print('[Training] reading ' .. config['inference_training_sdf_outputs']) outputs_2 = lib.utils.readHDF5(config['inference_training_sdf_outputs']) outputs_1 = outputs_1:repeatTensor(1, nObservations, 1, 1, 1):resize(nObservations*outputs_1:size(1), 1, outputs_1:size(3), outputs_1:size(4), outputs_1:size(5)) outputs_2 = outputs_2:repeatTensor(1, nObservations, 1, 1, 1):resize(nObservations*outputs_2:size(1), 1, outputs_2:size(3), outputs_2:size(4), outputs_2:size(5)) outputs = torch.cat({outputs_1:float(), outputs_2:float()}, 2) -- ! maxLTSDF = torch.max(outputs_2) print('[Training] max LTSDF ' .. maxLTSDF) assert(inputs:size(1) == outputs:size(1)) assert(inputs:size(2) == outputs:size(2)) assert(inputs:size(2) == 2) assert(inputs:size(3) == outputs:size(3)) assert(inputs:size(4) == outputs:size(4)) assert(inputs:size(5) == outputs:size(5)) -- Load data for validation. print('[Training] reading ' .. config['validation_inputs']) valInputs_1 = lib.utils.readHDF5(config['validation_inputs']) print('[Training] reading ' .. config['validation_sdf_inputs']) valInputs_2 = lib.utils.readHDF5(config['validation_sdf_inputs']) valInputs_1 = valInputs_1:resize(valInputs_1:size(1)*valInputs_1:size(2), 1, valInputs_1:size(3), valInputs_1:size(4), valInputs_1:size(5)) valInputs_2 = valInputs_2:resize(valInputs_2:size(1)*valInputs_2:size(2), 1, valInputs_2:size(3), valInputs_2:size(4), valInputs_2:size(5)) valInputs = torch.cat({valInputs_1:float(), valInputs_2:float()}, 2) print('[Training] reading ' .. config['validation_outputs']) valOutputs_1 = lib.utils.readHDF5(config['validation_outputs']) print('[Training] reading ' .. config['validation_sdf_outputs']) valOutputs_2 = lib.utils.readHDF5(config['validation_sdf_outputs']) valOutputs_1 = valOutputs_1:repeatTensor(1, nObservations, 1, 1, 1):resize(nObservations*valOutputs_1:size(1), 1, valOutputs_1:size(3), valOutputs_1:size(4), valOutputs_1:size(5)) valOutputs_2 = valOutputs_2:repeatTensor(1, nObservations, 1, 1, 1):resize(nObservations*valOutputs_2:size(1), 1, valOutputs_2:size(3), valOutputs_2:size(4), valOutputs_2:size(5)) valOutputs = torch.cat({valOutputs_1:float(), valOutputs_2:float()}, 2) assert(valInputs:size(1) == valOutputs:size(1)) assert(valInputs:size(2) == valOutputs:size(2)) assert(valInputs:size(2) == 2) assert(valInputs:size(3) == valOutputs:size(3)) assert(valInputs:size(4) == valOutputs:size(4)) assert(valInputs:size(5) == valOutputs:size(5)) -- Create snapshot directory. print('[Training] creating ' .. config['test_directory']) if not lib.utils.directoryExists(config['test_directory']) then lib.utils.makeDirectory(config['test_directory']) end -- Some assertions to check configuration. assert(#config['channels'] == #config['kernel_sizes']) -- For later simplicity. N = outputs:size()[1] height = outputs:size()[3] width = outputs:size()[4] depth = outputs:size()[5] if width == 54 then model = cnncomplete.Models.low54(cnncomplete.opts) elseif width == 72 then model = cnncomplete.Models.med72(cnncomplete.opts) elseif width == 108 then model = cnncomplete.Models.high108(cnncomplete.opts) elseif width == 32 then model = cnncomplete.Models.low32(cnncomplete.opts) elseif width == 48 then model = cnncomplete.Models.med48(cnncomplete.opts) elseif width == 64 then model = cnncomplete.Models.med64(cnncomplete.opts) else print('[Error] invalid resolution or not suitable model in 0_model.lua found') os.exit() end model = model:cuda() print(model) -- Criterion. occCriterion = nn.BCECriterion() occCriterion.sizeAverage = config['sup_parameters']['size_average'] occCriterion = occCriterion:cuda() sdfCriterion = nn.FixedVarianceGaussianNLLCriterion() sdfCriterion.sizeAverage = config['sup_parameters']['size_average'] sdfCriterion.logvar = 0 sdfCriterion = sdfCriterion:cuda() criterion = nn.PerChannelCriterion() criterion.criteria = {occCriterion, sdfCriterion } criterion.weights = {1, 1 } criterion = criterion:cuda() -- Learning hyperparameters. optimizer = optim.adam batchSize = config['sup_parameters']['batch_size'] learningRate = config['sup_parameters']['learning_rate'] momentum = config['sup_parameters']['momentum'] weightDecay = config['sup_parameters']['weight_decay'] epochs = config['sup_parameters']['epochs'] iterations = epochs*math.floor(N/batchSize) minimumLearningRate = config['sup_parameters']['minimum_learning_rate'] learningRateDecay = config['sup_parameters']['decay_learning_rate'] maximumMomentum = config['sup_parameters']['maximum_momentum'] momentumDecay = config['sup_parameters']['decay_momentum'] decayIterations = config['sup_parameters']['decay_iterations'] lossIterations = config['loss_iterations'] snapshotIterations = config['snapshot_iterations'] testIterations = config['test_iterations'] if not snapshotIterations then snapshotIterations = 2*testIterations end earlyStopError = 1e20 dataAugmentation = 0.5 if dataAugmentation > 0 then print('[Training] data augmentation') end parameters, gradParameters = model:getParameters() parameters = parameters:cuda() gradParameters = gradParameters:cuda() -- Saves the loss. protocol = torch.Tensor(iterations, 14):fill(0) -- Will save: iteration, loss, KLD loss, error, thresh error, learning rate, momentum, lambda valProtocol = torch.Tensor(math.floor(iterations/testIterations) + 1, 16):fill(0) -- Wil save: iteration, loss x2, KLD loss x2, error x2, thresh error x2, mean mean, var mean, mean logvar -- Main training loop. for t = 1, iterations do -- Sample a random batch from the dataset. local shuffle = torch.randperm(N) shuffle = shuffle:narrow(1, 1, batchSize) shuffle = shuffle:long() local _output = outputs:index(1, shuffle) local output = torch.Tensor(batchSize, 2, height, width, depth) local _input = inputs:index(1, shuffle) local input = torch.Tensor(batchSize, 2, height, width, depth) protocol[t][14] = 0 if dataAugmentation then for b = 1, batchSize do local r = math.random() if r < dataAugmentation then local translate_h = torch.random(1, 4) - 2 local translate_w = torch.random(1, 6) - 3 local translate_d = torch.random(1, 4) - 2 lib.translate_mirror(_output:narrow(1, b, 1), output:narrow(1, b, 1), translate_h, translate_w, translate_d) lib.translate_mirror(_input:narrow(1, b, 1), input:narrow(1, b, 1), translate_h, translate_w, translate_d) protocol[t][14] = protocol[t][14] + 1 else output:narrow(1, b, 1):copy(_output:narrow(1, b, 1)) input:narrow(1, b, 1):copy(_input:narrow(1, b, 1)) end end else output = _output end input = input:cuda() output = output:cuda() protocol[t][1] = t --- Definition of the objective on the current mini-batch. -- This will be the objective fed to the optimization algorithm. -- @param x input parameters -- @return object value, gradients local feval = function(x) -- Get new parameters. if x ~= parameters then parameters:copy(x) end -- Reset gradients gradParameters:zero() -- Evaluate function on mini-batch. local pred = model:forward(input) local f = criterion:forward(pred, output) protocol[t][2] = f protocol[t][10] = criterion.criteria[1].output protocol[t][11] = criterion.criteria[2].output -- Estimate df/dW. local df_do = criterion:backward(pred, output) model:backward(output, df_do) -- Weight decay: if weightDecay > 0 then weightDecayLoss = weightDecay * torch.norm(parameters,2)^2/2 protocol[t][4] = weightDecayLoss f = f + weightDecayLoss gradParameters:add(parameters:clone():mul(weightDecay)) end protocol[t][5] = torch.mean(torch.abs(pred - output)) protocol[t][12] = torch.mean(torch.abs(pred:narrow(2, 1, 1) - output:narrow(2, 1, 1))) protocol[t][13] = torch.mean(torch.abs(pred:narrow(2, 2, 1) - output:narrow(2, 2, 1))) gradParameters:clamp(-1, 1) -- return f and df/dX return f, gradParameters end -- Save learning rate and momentum in protocol. protocol[t][7] = learningRate protocol[t][8] = momentum -- Update state with learning rate and momentum. adamState = adamState or { learningRate = learningRate, momentum = momentum, learningRateDecay = 0 -- will be done manually below } optimizer(feval, parameters, adamState) local time = os.date("*t") -- Report a smoothed loss instead of batch loss. if t%lossIterations == 0 then -- Compute losses over the alst config['loss_iterations'] iterations. local smoothedLoss = torch.mean(protocol:narrow(1, t - lossIterations + 1, lossIterations):narrow(2, 2, 1)) local smoothedWeightDecay = torch.mean(protocol:narrow(1, t - lossIterations + 1, lossIterations):narrow(2, 4, 1)) local smoothedError = torch.mean(protocol:narrow(1, t - lossIterations + 1, lossIterations):narrow(2, 5, 1)) local smoothedDataAugmentation = torch.mean(protocol:narrow(1, t - lossIterations + 1, lossIterations):narrow(2, 14, 1)) print('[Training] ' .. t .. '|' .. iterations .. '|' .. time.hour .. ':' .. time.min .. ':' .. time.sec .. ':' .. ' (' .. lib.utils.format_num(smoothedDataAugmentation) .. ')' .. ' [' .. lib.utils.format_num(smoothedLoss) .. ']' .. ' [' .. lib.utils.format_num(smoothedError) .. ']') end -- Decay learning rate and KLD weight, do this before resetting all smoothed -- statistics. if t%decayIterations == 0 then learningRate = math.max(minimumLearningRate, learningRate*learningRateDecay) momentum = math.min(maximumMomentum, momentum*momentumDecay) print('[Training] ' .. t .. '|' .. iterations .. '|' .. time.hour .. ':' .. time.min .. ':' .. time.sec .. ': learning rate ' .. learningRate) print('[Training] ' .. t .. '|' .. iterations .. '|' .. time.hour .. ':' .. time.min .. ':' .. time.sec .. ': momentum ' .. momentum) end -- Validate on validation set. if t%testIterations == 0 or t == 1 or t == iterations then -- In case the validation set gets to large. local valN = valOutputs:size(1) local valBatchSize = batchSize local valNumBatches = math.floor(valN/valBatchSize) local valIteration = math.floor(t/testIterations) + 1 local accValPreds = nil -- iteration, loss x2, KLD loss x2, error x2, thresh error x2, mean mean, var mean, mean logvar for b = 0, valNumBatches do local batchStart = b*valBatchSize + 1 local batchLength = math.min((b + 1)*valBatchSize - b*valBatchSize, valN - b*valBatchSize) if batchLength == 0 then break; end local input = valInputs:narrow(1, batchStart, batchLength) local output = valOutputs:narrow(1, batchStart, batchLength) input = input:cuda() output = output:cuda() local valPreds = model:forward(input) local f = criterion:forward(valPreds, output) valProtocol[valIteration][2] = valProtocol[valIteration][2] + f valProtocol[valIteration][15] = valProtocol[valIteration][15] + criterion.criteria[1].output valProtocol[valIteration][16] = valProtocol[valIteration][16] + criterion.criteria[2].output valProtocol[valIteration][6] = valProtocol[valIteration][6] + torch.mean(torch.abs(valPreds - output)) valProtocol[valIteration][13] = valProtocol[valIteration][13] + torch.mean(torch.abs(valPreds:narrow(2, 1, 1) - output:narrow(2, 1, 1))) valProtocol[valIteration][14] = valProtocol[valIteration][14] + torch.mean(torch.abs(valPreds:narrow(2, 2, 1) - output:narrow(2, 2, 1))) accValPreds = appendTensor(accValPreds, valPreds) end accValPreds = accValPreds:narrow(1, 1, valN) valProtocol[valIteration][1] = t for i = 2, valProtocol:size(2) do valProtocol[valIteration][i] = valProtocol[valIteration][i] / valNumBatches end print('[Training] ' .. t .. '|' .. iterations .. '|' .. time.hour .. ':' .. time.min .. ':' .. time.sec .. ': codes (mean) ' .. valProtocol[valIteration][10] .. ' / ' .. valProtocol[valIteration][11]) print('[Training] ' .. t .. '|' .. iterations .. '|' .. time.hour .. ':' .. time.min .. ':' .. time.sec .. ': codes (logvar) ' .. valProtocol[valIteration][12]) print('[Training] ' .. t .. '|' .. iterations .. '|' .. time.hour .. ':' .. time.min .. ':' .. time.sec .. ': KLD loss ' .. valProtocol[valIteration][4]) print('[Training] ' .. t .. '|' .. iterations .. '|' .. time.hour .. ':' .. time.min .. ':' .. time.sec .. ': validation loss ' .. valProtocol[valIteration][2]) print('[Training] ' .. t .. '|' .. iterations .. '|' .. time.hour .. ':' .. time.min .. ':' .. time.sec .. ': validation error (abs) ' .. valProtocol[valIteration][6] .. ' / ' .. valProtocol[valIteration][7]) local predFile = config['test_directory'] .. t .. '_predictions.h5' lib.utils.writeHDF5(predFile, accValPreds) print('[Training] ' .. t .. '|' .. iterations .. '|' .. time.hour .. ':' .. time.min .. ':' .. time.sec .. ': saved ' .. predFile) local nll = valProtocol[valIteration][3] + valProtocol[valIteration][5] if nll < earlyStopError then earlyStopError = nll local earlyStopIteration = torch.Tensor(1) local earlyStopFile = config['early_stop_file'] earlyStopIteration[1] = t lib.utils.writeHDF5(earlyStopFile, earlyStopIteration) print('[Training] ' .. t .. '|' .. iterations .. '|' .. time.hour .. ':' .. time.min .. ':' .. time.sec .. ': saved ' .. earlyStopFile) local modelFile = config['test_directory'] .. 'early_stop.dat' torch.save(modelFile, model) print('[Training] ' .. t .. '|' .. iterations .. '|' .. time.hour .. ':' .. time.min .. ':' .. time.sec .. ': snapshot ' .. modelFile) end end if t%snapshotIterations == 0 and t > 1 then local modelFile = config['test_directory'] .. t .. '.dat' torch.save(modelFile, model) print('[Training] ' .. t .. '|' .. iterations .. '|' .. time.hour .. ':' .. time.min .. ':' .. time.sec .. ': snapshot ' .. modelFile) end end -- Save the accumulated loss. protocolFile = config['train_protocol_file'] lib.utils.writeHDF5(protocolFile, protocol) print('[Training] protocol ' .. protocolFile) protocolFile = config['val_protocol_file'] lib.utils.writeHDF5(protocolFile, valProtocol) print('[Training] protocol ' .. protocolFile) -- Save the model. modelFile = config['sup_parameters']['model_file'] torch.save(modelFile, model) print('[Training] snapshot ' .. modelFile)
local F, C = unpack(select(2, ...)) local UNITFRAME, cfg = F:GetModule('Unitframe'), C.unitframe function UNITFRAME:AddStatusIndicator(self) local statusIndicator = CreateFrame('Frame') local statusText = F.CreateFS(self.Health, 'pixel', '', nil, true) statusText:SetPoint('LEFT', self.HealthValue, 'RIGHT', 10, 0) local function updateStatus() if UnitAffectingCombat('player') then statusText:SetText('!') statusText:SetTextColor(1, 0, 0) elseif IsResting() then statusText:SetText('Zzz') statusText:SetTextColor(44/255, 141/255, 81/255) else statusText:SetText('') end end local function checkEvents() statusText:Show() statusIndicator:RegisterEvent('PLAYER_ENTERING_WORLD', true) statusIndicator:RegisterEvent('PLAYER_UPDATE_RESTING', true) statusIndicator:RegisterEvent('PLAYER_REGEN_ENABLED', true) statusIndicator:RegisterEvent('PLAYER_REGEN_DISABLED', true) updateStatus() end checkEvents() statusIndicator:SetScript('OnEvent', updateStatus) end function UNITFRAME:AddRaidTargetIndicator(self) local raidTargetIndicator = self.Health:CreateTexture(nil, 'OVERLAY') raidTargetIndicator:SetTexture(C.AssetsPath..'UI-RaidTargetingIcons') raidTargetIndicator:SetAlpha(.5) raidTargetIndicator:SetSize(16, 16) raidTargetIndicator:SetPoint('CENTER', self) self.RaidTargetIndicator = raidTargetIndicator end function UNITFRAME:AddResurrectIndicator(self) local resurrectIndicator = self.Health:CreateTexture(nil, 'OVERLAY') resurrectIndicator:SetSize(16, 16) resurrectIndicator:SetPoint('CENTER') self.ResurrectIndicator = resurrectIndicator end function UNITFRAME:AddReadyCheckIndicator(self) local readyCheckIndicator = self.Health:CreateTexture(nil, 'OVERLAY') readyCheckIndicator:SetPoint('CENTER', self.Health) readyCheckIndicator:SetSize(16, 16) self.ReadyCheckIndicator = readyCheckIndicator end function UNITFRAME:AddGroupRoleIndicator(self) local UpdateLFD = function(self, event) local lfdrole = self.GroupRoleIndicator local role = UnitGroupRolesAssigned(self.unit) if role == 'DAMAGER' then lfdrole:SetTextColor(1, .1, .1, 1) lfdrole:SetText('.') elseif role == 'TANK' then lfdrole:SetTextColor(.3, .4, 1, 1) lfdrole:SetText('x') elseif role == 'HEALER' then lfdrole:SetTextColor(0, 1, 0, 1) lfdrole:SetText('+') else lfdrole:SetTextColor(0, 0, 0, 0) end end local groupRoleIndicator = F.CreateFS(self.Health, 'pixel', '', nil, true) groupRoleIndicator:SetPoint('BOTTOM', self.Health, 1, 1) groupRoleIndicator.Override = UpdateLFD self.GroupRoleIndicator = groupRoleIndicator end function UNITFRAME:AddPhaseIndicator(self) local phaseIndicator = F.CreateFS(self.Health, 'pixel', '?', nil, true) phaseIndicator:SetPoint('TOPRIGHT', self.Health, 0, -2) self.PhaseIndicator = phaseIndicator end
--[[ © 2020 TERRANOVA do not share, re-distribute or modify without permission of its author. --]] ITEM.name = "Chocolate Muffin"; ITEM.model = "models/griim/foodpack/muffin.mdl"; ITEM.width = 1; ITEM.height = 1; ITEM.description = "A delicious, still moist muffin in a tin, with chocolate chips throughout it."; ITEM.permit = "consumables"; ITEM.price = 10; ITEM.restoreHealth = 5; ITEM.rarity = "Common" ITEM.flag = "b" ITEM.category = "Bread";
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include('shared.lua') function ENT:Initialize() self.BaseClass.Initialize(self) self.damaged = 0 self.time = 0 self.water = 100 self.Active = 1 self:ShowOutput() end function ENT:Repair() self.BaseClass.Repair(self) self:SetColor(Color(255, 255, 255, 255)) self.damaged = 0 self.time = 0 self.water = 100 self:ShowOutput() end function ENT:SetActive() self:Repair() end function ENT:Destruct() if CAF and CAF.GetAddon("Life Support") then CAF.GetAddon("Life Support").Destruct(self, true) end end function ENT:ShowOutput() if self:GetNetworkedInt(1) ~= self.water then self:SetNetworkedInt(1, self.water) end end function ENT:Damage() if (self.damaged == 0) then self.damaged = 1 end end function ENT:OnRemove() --nothing end function ENT:Think() self.BaseClass.Think(self) local waterlevel = 0 if CAF then waterlevel = self:WaterLevel2() else waterlevel = self:WaterLevel() end local mul = 1 if self.environment and self.environment.GetTemperature then local temperature = self.environment:GetTemperature(self) if temperature < 278 then mul = 0 elseif temperature < 283 then mul = 0.25 elseif temperature < 288 then mul = 0.5 elseif temperature > 303 then mul = 0.5 elseif temperature > 308 then mul = 0.25 elseif temperature > 318 then mul = 0 end end self.resco2 = self:GetResourceAmount("carbon dioxide") self.reswater = self:GetResourceAmount("water") if waterlevel > 0 then if self.water < 100 then if self.Active == 0 then self:SetColor(Color(255, 255, 255, 255)) self.Active = 1 end self.water = self.water + 1 self:ShowOutput() end elseif self.reswater > 0 then if self.Active == 0 then self:SetColor(Color(255, 255, 255, 255)) self.Active = 1 end self:ConsumeResource("water", 1) if self.water < 100 then self.water = self.water + 1 end self:ShowOutput() elseif self.water > 0 then self.water = self.water - 1 self:ShowOutput() else self.Active = 0 self:SetColor(Color(75, 75, 75, 255)) self:ShowOutput() end if self.Active == 1 then local touse = math.Round(3 * mul) if self.environment then local left = self.environment:Convert(1, 0, touse) if left > 0 then local co2left = self:ConsumeResource("carbon dioxide", left) self:SupplyResource("oxygen", left - co2left) end else local co2left = self:ConsumeResource("carbon dioxide", touse) self:SupplyResource("oxygen", touse - co2left) end end if self:GetNetworkedInt("OOO") ~= self.Active then self:SetOOO(self.Active) end self:NextThink(CurTime() + 1) return true end
Tracker:AddItems("items/common.json") Tracker:AddMaps("maps/maps.json") ScriptHost:LoadScript("scripts/logic.lua") Tracker:AddLocations("locations/virtual.json") Tracker:AddLocations("locations/johto.json") Tracker:AddLocations("locations/kanto.json") Tracker:AddLayouts("layouts/items.json") Tracker:AddLayouts("layouts/tracker.json") if Tracker.ActiveVariantUID == "badge" then ScriptHost:LoadScript("scripts/badge_rando.lua") init_badge_rando() end
-- MENU local devmenu = { { "gvim", "gvim" } } local networkmenu = { { "firefox", "firefox" }, { "chromium", "chromium --disk-cache-size=268435456" }, { "thunderbird", "thunderbird" }, { "pidgin", "pidgin" }, { "skype", "skype" }, { "xchat", "xchat" } } local awesomemenu = { { "edit config", editor_cmd .. " " .. awesome.conffile }, { "restart", awesome.restart }, { "lock", "xlock -mode blank" }, { "quit", awesome.quit }, { "poweroff", "system-state poweroff" }, { "reboot", "system-state reboot" }, { "suspend", "xlock -mode blank -startCmd 'system-state suspend'"}, { "hibernate", "xlock -mode blank -startCmd 'system-state hibernate'"} } mainmenu = awful.menu({ items = { { "terminal", terminal }, { "dev", devmenu }, { "network", networkmenu }, { "awesome", awesomemenu } } }) -- Menubar configuration menubar.utils.terminal = terminal -- Set the terminal for applications that require it
-- Behavior for warden (1) in the level gandriamines routine = function(O) O:gotoTile(36, 10.5) O:gotoTile(36, 5.5) end
TUTORIALS['en'][#TUTORIALS['en'] + 1] = { name = "Calling a Pokemon", contents = { {type = CONTENT_TYPES.IMAGE, value = "/images/tutorial/pokemon_released.png"}, {type = CONTENT_TYPES.TEXT, value = "To release a Pokemon in PSoul you can use two ways:\n\nThe first and simplest, is just clicking the image of the desired Pokemon in your Pokemon window. After clicking, the Pokeball will automatically be moved into the space in your inventory and used."}, {type = CONTENT_TYPES.IMAGE, value = "/images/tutorial/release_pokemon.png"}, {type = CONTENT_TYPES.TEXT, value = "The second way requires a little more knowledge about the game interface. The first thing you need to do is locate your Pokemon Pokeball in your inventory, inside your backpack, and move into the Pokeball space in your inventory. After placing the Pokeball, use it."}, {type = CONTENT_TYPES.IMAGE, value = "/images/tutorial/inventory_pokemon_ball.png"}, } }
--.--------------------------------------------- --. Rules_VC_To_MAIN.lua (Version:1.0) -- --. Applies rules from: -- --. all: VC_TEST -> GLB_SYS -- --. table: WORK_DEF_ROLES -> GLB_RUN -- --.--------------------------------------------- --.-------------------- --. Prefix functions -- --.-------------------- module("CoreRules", package.seeall) function InitRules() local currentRules = { default = { insert = { qualifiedName = qualifiedNameFunc } ,update = { qualifiedName = qualifiedNameFunc ,whereProcess = whereProcessFunc } ,delete = { qualifiedName = qualifiedNameFunc ,whereProcess = whereProcessFunc } } ,VC_WORKUNIT = {} ,generic = genericFunc } return currentRules end --.------------------------------- --. Aux functions --.------------------------------- -- Tables that are in GOM_GLB_RUN function isRunTable (TableName) if TableName == "WORK_DEF_ROLES" or TableName == "VC_WORKUNIT" or TableName == "VC_PACKAGE" then return true end return false end -- Should the schema be replaced function shouldReplaceSchema (SchemaName) if SchemaName == nil or SchemaName == "" or SchemaName == "GLB_SYS" or SchemaName == "GLB_RUN" then return false end return SchemaName == "VC_TEST" end --.------------------------------- --. Processing functions --.------------------------------- function qualifiedNameFunc(SchemaName, TableName) if SchemaName == nil or SchemaName == "" then return TableName end if shouldReplaceSchema (SchemaName) then if isRunTable(TableName) then return "GLB_RUN" .. "." .. TableName end return "GLB_SYS" .. "." .. TableName end return SchemaName .. "." .. TableName end function whereProcessFunc (SchemaName, TableName, Fields, Where) if Where == nil or Where == "" then return Where end if not shouldReplaceSchema (SchemaName) then return Where end if isRunTable(TableName) then local whereNew = string.gsub(Where, SchemaName .. "." .. TableName, "GLB_RUN." .. TableName) if TableName == "WORK_DEF_ROLES" then whereNew = string.gsub(whereNew, SchemaName .. ".WORK_DEF", "GLB_SYS.WORK_DEF") end return whereNew end return string.gsub(Where, SchemaName, "GLB_SYS") end function genericFunc (Line) if Line == nil then return Line end return string.gsub(Line, "VC_TEST", "GOM_GLB_SYS") end
-- Event stuff based on the pubsub. --[[ The MIT License (MIT) Copyright (c) 2015 - 2016 Adrian Pistol Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local _M = {} _M.version = "0.0.1" msgpack = require("msgpack") pubsub = require("pubsub") function _M.handle(name, func, bindings, buffer) local binds = { f = string.dump(func), event_name = name } for k, v in pairs(bindings or {}) do binds[k] = v end pubsub.sub("event:"..name, function() msgpack = require("msgpack") logger = require("libs.logger") event = require("libs.event") prettify = require("prettify") function print(...) logger.log(event_name, logger.normal, prettify(...)) end local func = loadstring(f) f = nil while true do local src = com.receive(threadcom) local args if src then args = msgpack.unpack(src) else args = {} end local suc, err = pcall(func, unpack(args)) if not suc then logger.log(event_name, logger.normal, "(╯°□°)╯︵ ┻━┻: "..err) end end end, binds, buffer) end function _M.listen(name) -- ltn12 compatible listener local retcom = com.create() pubsub.sub("event:"..name, retcom) return function() local src = com.receive(retcom) if src then return msgpack.unpack(src) else return nil end end end function _M.netdial(in_name, out_name, proto, addr) local conn, err = net.dial(proto, addr) if err then error(err) end local inp = com.create() local out = com.create() net.pipe_com_background(conn, inp, out) pubsub.sub("netevent:"..in_name, inp) event.handle("event:".. in_name, function(line) local msgpack = require("msgpack") local pubsub = require("libs.pubsub") pubsub.pub(name, line) end, { name = "netevent:"..in_name }) local tmp_pub = thread.spawn(function() local msgpack = require("msgpack") local pubsub = require("libs.pubsub") while true do pubsub.pub(name, msgpack.pack({com.receive(threadcom)})) end end, { name = "event:"..out_name }) com.pipe_background(out, tmp_pub) end function _M.fire(name, ...) if ({...})[1] then pubsub.pub("event:"..name, msgpack.pack({...})) else pubsub.pub("event:"..name) end end function _M.force_fire(name, ...) if ({...})[1] then pubsub.pub("event:"..name, msgpack.pack({...}), true) else pubsub.pub("event:"..name, nil, true) end end return _M
local games = {} --############################################################################################################################################# --# State/Globals # --############################################################################################################################################# -- {Channel : {ID, Name, State}} games.INSTANCES = {} function games.registerGame(channel, name, state, players) --[[Add game to the instances table]] local id = math.random(10000) while idInUse(id) do id = math.random(10000) end games.INSTANCES[channel] = {id, name, state, players} end function games.deregisterGame(channel) --[[Remove game from the instances table]] games.INSTANCES[channel] = nil end function games.playerInGame(person) --[[Check if player exists in any game]] for game, info in pairs(games.INSTANCES) do for idx, player in pairs(info[4]) do if player == person then return true end end end return false end function idInUse(id) --[[Check if the given game ID is in use]] for game, info in pairs(games.INSTANCES) do if info[1] == id then return true end end return false end function games.getState(channel) return games.INSTANCES[channel][2] end return games
--- Component to block input on specify zone by node -- @module Blocker -- @within BaseComponent -- @alias druid.blocker ---Trigger node -- @tfield node node --- local const = require("druid.const") local component = require("druid.component") local Blocker = component.create("blocker", { component.ON_INPUT }) --- Component init function -- @tparam Blocker self -- @tparam node node Gui node function Blocker.init(self, node) self.node = self:get_node(node) end function Blocker.on_input(self, action_id, action) if action_id ~= const.ACTION_TOUCH and action_id ~= const.ACTION_MULTITOUCH and action_id ~= nil then return false end if not self:is_enabled(self.node) then return false end if gui.pick_node(self.node, action.x, action.y) then return true end return false end --- Set enabled blocker component state -- @tparam Blocker self -- @tparam bool state Enabled state function Blocker.set_enabled(self, state) gui.set_enabled(self.node, state) end --- Return blocked enabled state -- @tparam Blocker self -- @treturn bool True, if blocker is enabled function Blocker.is_enabled(self) return gui.is_enabled(self.node) end return Blocker
local snap = require "snap" local fzy = snap.get "consumer.fzy" local fzf = snap.get "consumer.fzf" local limit = snap.get "consumer.limit" local producer_file = snap.get "producer.ripgrep.file" local producer_jumplist = snap.get "producer.vim.jumplist" local producer_git = snap.get "producer.git.file" local producer_luv_file = snap.get "producer.luv.file" local producer_vimgrep = snap.get "producer.ripgrep.vimgrep" local producer_buffer = snap.get "producer.vim.buffer" local producer_currentbuffer = snap.get "producer.vim.currentbuffer" local producer_oldfile = snap.get "producer.vim.oldfile" local select_file = snap.get "select.file" local select_jumplist = snap.get "select.jumplist" local select_vimgrep = snap.get "select.vimgrep" local select_currentbuffer = snap.get "select.currentbuffer" local preview_file = snap.get "preview.file" local preview_vimgrep = snap.get "preview.vimgrep" local preview_jumplist = snap.get "preview.jumplist" local function _1_() return snap.run { initial_filter = vim.fn.input "Grep> ", multiselect = select_vimgrep.multiselect, producer = limit(50000, producer_vimgrep), prompt = "Grep", select = select_vimgrep.select, steps = { { config = { prompt = "FZY> " }, consumer = fzy } }, views = { preview_vimgrep }, } end snap.register.map({ "n" }, { "<Leader>ff" }, _1_)
if onServer() then local entity = Entity() if not entity.aiOwned then if entity.isShip or entity.isStation or entity.isDrone then entity:addScriptOnce("data/scripts/entity/avocontrol-shiptracker.lua") end end end
--[[ General options panel --]] local ADDON, Addon = ... local General = Addon:NewPanel('General') local L = LibStub('AceLocale-3.0'):GetLocale('Combuctor') local frame local Managed = General:NewCheckButton(L.ActPanel, L.ActPanelTip) Managed:SetPoint('TOPLEFT', 15, -120) Managed:SetScript('OnClick', function() if frame.sets.position then frame:SavePosition(nil) else frame:SavePosition(frame:GetPoint()) end end) local Reversed = General:NewCheckButton(L.LeftFilters, L.LeftFiltersTip) Reversed:SetPoint('TOPLEFT', Managed, 'BOTTOMLEFT', 0, -5) Reversed:SetScript('OnClick', function() frame:SetLeftSideFilter(not frame:IsSideFilterOnLeft()) end) local anchor = Reversed for _, name in ipairs {'ItemsByQuality', 'NewItems', 'UnusableItems', 'SetItems', 'QuestItems'} do local button = General:NewCheckButton(L['Highlight' .. name]) button:SetPoint('TOPLEFT', anchor, 'BOTTOMLEFT', 0, -5) button:SetChecked(not Combuctor:GetSetting('disable' .. name)) button:SetScript('OnClick', function() Combuctor:ToggleSetting('disable' .. name) Combuctor:UpdateFrames() end) anchor = button end local TipCounts = General:NewCheckButton(L.TipCounts, L.TipCountsTip) TipCounts:SetPoint('TOPLEFT', anchor, 'BOTTOMLEFT', 0, -5) TipCounts:SetChecked(Combuctor:IsTipCountEnabled()) TipCounts:SetScript('OnClick', function() Combuctor:ToggleTipCounts() end) function General:OnFrameChanged() frame = Combuctor:GetFrame(Addon.frame) Managed:SetChecked(not frame.sets.position) Reversed:SetChecked(frame:IsSideFilterOnLeft()) end
function createIAckMsg() local msgInfos={} msgInfos["1"]="@dst,uint16_t,2,0" msgInfos["2"]="@totalLgth,uint16_t,2,0" flags=0 handleIAck=structmsg2.createMsgFromList(msgInfos,0,flags); print("2") return handleIAck end createIAckMsg() print("done")
--[[ main.lua Starts the guild bank frame on demand --]] local MODULE = ... local ADDON, Addon = MODULE:match('[^_]+'), _G[MODULE:match('[^_]+')] local Guild = Addon:NewModule('Guild') function Guild:OnEnable() self:RegisterMessage('CACHE_GUILD_OPENED', 'OnOpen') self:RegisterMessage('CACHE_GUILD_CLOSED', 'OnClose') end function Guild:OnOpen() QueryGuildBankTab(GetCurrentGuildBankTab()) Addon.Frames:Show('guild') end function Guild:OnClose() Addon.Frames:Hide('guild') end
return { id = "T10201", mode = 2, once = true, scripts = { { actor = -1, side = 0, nameColor = "#a9f548", say = "右舷发现敌方旗舰!判断舰船型号中……未识别国籍型号", shake = { speed = 1, number = 3 }, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 900013, actorShadow = true, nameColor = "#ffffff", side = 1, actorName = "???", say = "……开火", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = -1, side = 0, nameColor = "#a9f548", say = "敌方旗舰开火了,立即迎击!", shake = { speed = 1, number = 3 }, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } } } }
ITEM.name = "Component" ITEM.desc = "A Weapon." ITEM.category = "Components" ITEM.model = "models/weapons/w_pistol.mdl" ITEM.width = 1 ITEM.height = 1 function ITEM:getDesc(partial) local desc = self.desc local customData = self:getData("custom", {}) if(customData.quality) then desc = desc .. "\nQuality: " ..customData.quality end return Format(desc) end
--[[ A top-down action game made with Bitty Engine Copyright (C) 2021 Tony Wang, all rights reserved Engine page: https://paladin-t.github.io/bitty/ Game page: https://paladin-t.github.io/games/hb/ ]] Object = class({ --[[ Variables. ]] maxHp = 0, hp = 0, atk = 0, x = 0, y = 0, xOffset = nil, yOffset = nil, angleOffset = nil, box = nil, _dead = false, _invincible = nil, _invincibleColor = nil, _disappearable = true, _disappearing = nil, _disappearingTicks = 0, _collider = nil, _spriteAsyncPlay = false, _sprite = nil, _spriteWidth = 0, _spriteHeight = 0, _spriteAngle = 0, _spriteUpdater = nil, _shapeSprites = nil, _shapeLine = nil, _shapeLines = nil, _shapeHeadPosition = nil, _color = Color.new(0, 255, 0), _emitters = nil, _tweens = nil, _walker = nil, _raycaster = nil, _pathfinder = nil, _isBlocked = nil, _slidable = 5, --[[ Constructor. ]] ctor = function (self, resource, box, isBlocked) self.box = box if resource ~= nil then if resource.__name == 'Sprite' then self._sprite = resource self._sprite:play('idle', false, true, self._spriteAsyncPlay) self._spriteWidth, self._spriteHeight = self._sprite.width, self._sprite.height elseif resource['type'] == 'sprite' then self._sprite = resource['resource'] self._sprite:play('idle', false, true, self._spriteAsyncPlay) self._spriteWidth, self._spriteHeight = self._sprite.width, self._sprite.height elseif resource['type'] == 'sprites' then self._shapeSprites = resource local sprite = self._shapeSprites['resource'] sprite:play('idle', false, true, self._spriteAsyncPlay) self._spriteWidth, self._spriteHeight = sprite.width, sprite.height elseif resource['type'] == 'line' then self._shapeLine = resource elseif resource['type'] == 'lines' then self._shapeLines = resource end end if isBlocked ~= nil then self._walker = Walker.new() self._walker.objectSize = Vec2.new(self.box:width(), self.box:height()) self._walker.tileSize = Vec2.new(16, 16) self._walker.offset = Vec2.new(self.box:width() * 0.5, self.box:height() * 0.5) self._isBlocked = isBlocked end end, --[[ Meta methods. ]] __tostring = function (self) return 'Object' end, --[[ Methods. ]] hurt = function (self, other) self.hp = math.max(self.hp - other.atk, 0) if self.hp == 0 then self:kill('killed', other) end return true end, dead = function (self) return self._dead end, kill = function (self, reason, byWhom) self._dead = true self:trigger('dead', reason, byWhom) return self end, revive = function (self) self._dead = false self._disappearing, self._disappearingTicks = nil, 0 self._shapeHeadPosition = nil return self end, invincible = function (self) return self._invincible, self._invincibleColor end, setInvincible = function (self, invincible) self._invincible = invincible return self end, disappearable = function (self) return self._disappearable end, setDisappearable = function (self, disappearable) self._disappearable = disappearable return self end, disappear = function (self) if self._disappearable and self._disappearing == nil then self._disappearing, self._disappearingTicks = 5, 0 end return self end, play = function (self, motion, reset, loop, played) if not self._sprite then return false, nil end if reset == nil then reset = true end if loop == nil then loop = true end local success, duration = self._sprite:play(motion, reset, loop, self._spriteAsyncPlay) if success and played then local ticks = 0 self._spriteUpdater = function (delta) ticks = ticks + delta if ticks >= duration then ticks = ticks - duration played() if not loop then self._spriteUpdater = nil end end end end return success, duration end, angle = function (self) return self._spriteAngle end, setAngle = function (self, angle) if angle < 0 then self._spriteAngle = math.pi * 2 - math.fmod(-angle, math.pi * 2) elseif angle >= math.pi * 2 then self._spriteAngle = math.fmod(angle, math.pi * 2) else self._spriteAngle = angle end return self end, tween = function (self, t) if self._tweens == nil then self._tweens = { } end table.insert(self._tweens, t) return self end, float = function (self, interval, val) local up, down = nil, nil up = Tween.new(interval * 0.5, { y = 0 }, { y = val or -4 }, Tween.easing.linear) :on('changed', function (sender, val) self.yOffset = val.y end) :on('completed', function (sender, val) remove(self._tweens, up) down:reset() self:tween(down) end) down = Tween.new(interval * 0.5, { y = val or -4 }, { y = 0 }, Tween.easing.linear) :on('changed', function (sender, val) self.yOffset = val.y end) :on('completed', function (sender, val) remove(self._tweens, down) up:reset() self:tween(up) end) self:tween(up) return self end, slash = function (self, interval, val) local left, right, middle = nil, nil, nil left = Tween.new(interval * 0.2, { angle = 0 }, { angle = -(val or math.pi * 0.25) }, Tween.easing.linear) :on('changed', function (sender, val) self.angleOffset = val.angle end) :on('completed', function (sender, val) remove(self._tweens, left) self:tween(right) end) right = Tween.new(interval * 0.6, { angle = -(val or math.pi * 0.25) }, { angle = val or math.pi * 0.25 }, Tween.easing.linear) :on('changed', function (sender, val) self.angleOffset = val.angle end) :on('completed', function (sender, val) remove(self._tweens, right) self:tween(middle) end) middle = Tween.new(interval * 0.2, { angle = val or math.pi * 0.25 }, { angle = 0 }, Tween.easing.linear) :on('changed', function (sender, val) self.angleOffset = val.angle end) :on('completed', function (sender, val) remove(self._tweens, middle) end) self:tween(left) return self end, bounce = function (self, interval, val) local x, y = self.x + (val or 10) * (math.random() * 2 - 1), self.y + (val or 10) * (math.random() * 0.2 + 1) self:tween( Tween.new(interval, { x = self.x, y = self.y }, { x = x, y = y }, Tween.easing.outBounce) :on('changed', function (sender, val) self.x, self.y = val.x, val.y end) ) return self end, setBlockedHandler = function (self, isBlocked) if isBlocked == nil then self._walker = nil self._isBlocked = nil else if self._walker == nil then self._walker = Walker.new() end self._walker.objectSize = Vec2.new(self.box:width(), self.box:height()) self._walker.tileSize = Vec2.new(16, 16) self._walker.offset = Vec2.new(self.box:width() * 0.5, self.box:height() * 0.5) self._isBlocked = isBlocked end return self end, raycast = function (self, pos, dir, isBlocked) return self._raycaster:solve(pos, dir, isBlocked or self._isBlocked) end, findpath = function (self, pos, dst) return self._pathfinder:solve(pos, dst) end, reset = function (self) self._tweens = nil return self end, intersects = function (self, other) return Math.intersects(self._collider, other._collider) end, intersectsWithShape = function (self, shape) return Math.intersects(self._collider, shape) end, behave = function (self, delta, hero) error('Implement me.') end, update = function (self, delta) -- Update the tweenings. self:_tween(delta) -- Call custom sprite update handler if it's set. if self._spriteUpdater then self._spriteUpdater(delta) end -- Calculate basic information. local sprite, shapeSprites, shapeLine, shapeLines = self._sprite, self._shapeSprites, self._shapeLine, self._shapeLines local emitters = self._emitters local dstX, dstY, dstW, dstH = self:_build() if self.xOffset ~= nil then dstX = dstX + self.xOffset end if self.yOffset ~= nil then dstY = dstY + self.yOffset end -- Calculate visibility. local visible = true if self._disappearing ~= nil then local INTERVAL = 0.3 self._disappearingTicks = self._disappearingTicks + delta if self._disappearingTicks > INTERVAL then self._disappearingTicks = self._disappearingTicks - INTERVAL self._disappearing = self._disappearing - 1 if self._disappearing <= 0 then self:kill('disappeared', nil) self._disappearing, self._disappearingTicks = nil, 0 end end if self._disappearingTicks > INTERVAL * 0.5 then visible = false end end -- Draw if visible. if visible then if sprite ~= nil then if self._invincible ~= nil then if math.floor(self._invincible * 15) % 2 == 1 then self._invincibleColor = Color.new(255, 255, 255, 16) else self._invincibleColor = nil end self._invincible = self._invincible - delta if self._invincible <= 0 then self._invincible, self._invincibleColor = nil, nil end end local angle = self._spriteAngle if self.angleOffset ~= nil then angle = angle + self.angleOffset end if self._invincibleColor == nil then spr( sprite, dstX, dstY, dstW, dstH, angle ) else spr( sprite, dstX, dstY, dstW, dstH, angle, nil, self._invincibleColor ) end elseif shapeSprites ~= nil then if self._shapeHeadPosition == nil then self._shapeHeadPosition = Vec2.new(dstX, dstY) end local pos = Vec2.new(dstX, dstY) local diff = pos - self._shapeHeadPosition local n, angle = shapeSprites['count'], shapeSprites['angle'] for i = 1, n do local p = self._shapeHeadPosition + diff:rotated((i - ((n - 1) * 0.5 + 1)) * angle) spr( shapeSprites['resource'], p.x, p.y, self._spriteWidth, self._spriteHeight, self._spriteAngle ) end elseif shapeLine ~= nil then if self._shapeHeadPosition == nil then self._shapeHeadPosition = Vec2.new(dstX, dstY) end line( self._shapeHeadPosition.x, self._shapeHeadPosition.y, dstX, dstY, shapeLine['color'] ) elseif shapeLines ~= nil then if self._shapeHeadPosition == nil then self._shapeHeadPosition = Vec2.new(dstX, dstY) end local pos = Vec2.new(dstX, dstY) local diff = pos - self._shapeHeadPosition local n, angle = shapeLines['count'], shapeLines['angle'] local c = shapeLines['color'] for i = 1, n do local p = self._shapeHeadPosition + diff:rotated((i - ((n - 1) * 0.5 + 1)) * angle) line( self._shapeHeadPosition.x, self._shapeHeadPosition.y, p.x, p.y, c ) end end end -- Process and draw emitters. if emitters ~= nil then local dead = nil for i, entry in ipairs(emitters) do local emitter = entry.emitter if emitter.refresh ~= nil then emitter:refresh(self, delta) end emitter:update(delta) emitter:draw() entry.interval = entry.interval - delta if entry.interval <= 0 then if dead == nil then dead = { } end table.insert(dead, 1, i) end end if dead ~= nil then for _, idx in ipairs(dead) do table.remove(emitters, idx) end if #emitters == 0 then emitters = nil self._emitters = nil end end end -- Draw debug information. if DEBUG_SHOW_WIREFRAME then if self._collider.__name == 'Recti' then rect( self._collider:xMin(), self._collider:yMin(), self._collider:xMax(), self._collider:yMax(), false, self._color ) elseif self._collider.__name == 'Vec3' then circ( self._collider.x, self._collider.y, self._collider.z, false, self._color ) end end end, shadow = function (self, delta, offsetX, offsetY) local dstX, dstY, dstW, dstH = self:_build() local angle = self._spriteAngle if self.angleOffset ~= nil then angle = angle + self.angleOffset end local sprite = self._sprite spr( sprite, dstX + (offsetX or 2), dstY + (offsetY or 2), dstW, dstH, angle, nil, COLOR_SHADOW ) return self end, _build = function (self) local dstX, dstY, dstW, dstH = self.x - (self.box:xMin() + self.box:width() * 0.5), self.y - (self.box:yMin() + self.box:height() * 0.5), self._spriteWidth, self._spriteHeight self._collider = Recti.new( dstX + self.box:xMin(), dstY + self.box:yMin(), dstX + self.box:xMax(), dstY + self.box:yMax() ) return dstX, dstY, dstW, dstH end, _move = function (self, step) local newDir = Vec2.new(0, 0) local stepLength = step:normalize() if stepLength > 8 then local singleStepLength = 8 local pos = Vec2.new(self.x, self.y) while stepLength > 0 do -- Split into a few steps to avoid penetration. local step_ = step * math.min(stepLength, singleStepLength) local m = self._walker:solve( pos, step_, self._isBlocked, self._slidable ) pos = pos + m newDir = newDir + m stepLength = stepLength - singleStepLength end else newDir = self._walker:solve( Vec2.new(self.x, self.y), step * stepLength, self._isBlocked, self._slidable ) end return newDir end, _repulse = function (self, other) local EPSILON = 16 local diff = Vec2.new(self.x, self.y) - Vec2.new(other.x, other.y) local l = diff:normalize() if l > EPSILON then return Vec2.new(0, 0) end local FORCE = 10 return diff * (1 - l / EPSILON) * FORCE end, _tween = function (self, delta) if self._tweens ~= nil then local dead = nil for _, t in ipairs(self._tweens) do if t:update(delta) then if dead == nil then dead = { } end table.insert(dead, t) end end if dead ~= nil then self._tweens = filter(self._tweens, function (t) return not exists(dead, t) end) if #self._tweens == 0 then self._tweens = nil end end end return self end, _emit = function (self, emitter, interval) if self._emitters == nil then self._emitters = { } end table.insert( self._emitters, { emitter = emitter, interval = interval } ) return self end }, Event)
--region CTesterManager.lua --Author : jefflwq --Date : 2015/2/28 --说明 : CTesterManager类 --endregion using "Joop" using "System.Collections.Generic" namespace "System.Tester" { class "CTesterManager" : CContentManager { StartTest = function(self, ...) return self:ProcessContent(...) end, } }
-- sorted pairs function spairs(t, order) -- collect the keys local keys = {} for k in pairs(t) do keys[#keys+1] = k end -- if order function given, sort by it by passing the table and keys a, b -- otherwise just sort the keys if order then table.sort(keys, function(a, b) return order(t, a, b) end) else table.sort(keys) end -- return the iterator function local i = 0 return function() i = i + 1 if keys[i] then return keys[i], t[keys[i]] end end end function pressAndRelease(bot_context, keys, key) if bot_context.press_and_release == nil then bot_context.press_and_release = {} bot_context.press_and_release.press_frame = emu.framecount() bot_context.press_and_release.release_frame = emu.framecount() + 4 end local framecount = emu.framecount() if framecount < bot_context.press_and_release.release_frame then keys[key] = true else keys[key] = false bot_context.press_and_release = nil end end
local fakeTilesHelper = require("helpers.fake_tiles") local dashBlock = {} dashBlock.name = "dashBlock" dashBlock.depth = 0 dashBlock.placements = { name = "dash_block", data = { tiletype = "3", blendin = true, canDash = true, permanent = true, width = 8, height = 8 } } dashBlock.sprite = fakeTilesHelper.getEntitySpriteFunction("tiletype", "blendin") return dashBlock
local mod = DBM:NewMod(1719, "DBM-Party-Legion", 7, 800) local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 15008 $"):sub(12, -3)) mod:SetCreatureID(104217) mod:SetEncounterID(1869) mod:SetZone() mod.onlyMythic = true mod:RegisterCombat("combat") --Out of combat register, to support the secondary bosses off to sides mod:RegisterEvents( "SPELL_CAST_START 208165 207881 207980 209378" ) --local specWarnWitheringSoul = mod:NewSpecialWarningInterrupt(208165, "HasInterrupt") local specWarnInfernalEruption = mod:NewSpecialWarningDodge(207881, nil, nil, nil, 2, 2) local specWarnDisintegrationBeam = mod:NewSpecialWarningInterrupt(207980, "HasInterrupt", nil, nil, 1, 2) local specWarnWhirlingBlades = mod:NewSpecialWarningRun(209378, "Melee", nil, nil, 4, 2) local timerWitheringSoulCD = mod:NewCDTimer(14.5, 208165, nil, nil, nil, 3) local timerInfernalEruptionCD = mod:NewCDTimer(32, 207881, nil, nil, nil, 2) local voiceInfernalEruption = mod:NewVoice(207881)--watchstep local voiceDisintegrationBeam = mod:NewVoice(207980, "HasInterrupt")--kickcast local voiceWhirlingBlades = mod:NewVoice(209378, "Melee")--runout function mod:OnCombatStart(delay) timerWitheringSoulCD:Start(12-delay) timerInfernalEruptionCD:Start(19.5-delay) end function mod:SPELL_CAST_START(args) local spellId = args.spellId if spellId == 208165 then --if self:CheckInterruptFilter(args.sourceGUID) then --specWarnWitheringSoul:Show(args.sourceName) --end timerWitheringSoulCD:Start() elseif spellId == 207881 then specWarnInfernalEruption:Show() voiceInfernalEruption:Play("watchstep") timerInfernalEruptionCD:Start() elseif spellId == 207980 and self:CheckInterruptFilter(args.sourceGUID) then specWarnDisintegrationBeam:Show(args.sourceName) voiceDisintegrationBeam:Play("kickcast") elseif spellId == 209378 then specWarnWhirlingBlades:Show() voiceWhirlingBlades:Play("runout") end end
--[=[ @class TorsoIKUtils ]=] local require = require(script.Parent.loader).load(script) local IKUtils = require("IKUtils") local OFFSET_Y = 0.5 local TorsoIKUtils = {} local waistYawClamper = IKUtils.getDampenedAngleClamp( math.rad(20), math.rad(10)) local waistPitchClamper = IKUtils.getDampenedAngleClamp( math.rad(20), -- TODO: Allow forward bend by 40 degrees math.rad(10)) local headYawClamper = IKUtils.getDampenedAngleClamp( math.rad(45), math.rad(15)) local headPitchClamper = IKUtils.getDampenedAngleClamp( math.rad(45), math.rad(15)) function TorsoIKUtils.getTargetAngles(rootPart, target) local baseCFrame = rootPart.CFrame * CFrame.new(0, OFFSET_Y, 0) local offsetWaistY = baseCFrame:pointToObjectSpace(target) local waistY = waistYawClamper(math.atan2(-offsetWaistY.X, -offsetWaistY.Z)) local relativeToWaistY = baseCFrame * CFrame.Angles(0, waistY, 0) local headOffsetY = relativeToWaistY:pointToObjectSpace(target) local headY = headYawClamper(math.atan2(-headOffsetY.X, -headOffsetY.Z)) local relativeToHeadY = relativeToWaistY * CFrame.Angles(0, headY, 0) local offsetWaistZ = relativeToHeadY:pointToObjectSpace(target) local waistZ = waistPitchClamper(math.atan2(offsetWaistZ.Y, -offsetWaistZ.Z)) local relativeToEverything = relativeToHeadY * CFrame.Angles(0, 0, waistZ) local headOffsetZ = relativeToEverything:pointToObjectSpace(target) local headZ = headPitchClamper(math.atan2(headOffsetZ.Y, -headOffsetZ.Z)) return waistY, headY, waistZ, headZ end return TorsoIKUtils
------------------------------------------------------------------------------------------- -- script_time_esp-dsmr-logger.lua door: Michel Groen ------------------------------------------------------------------------------------------- -- Aanpassingen gemaakt door Martijn Hendriks (2020-07-21) ivm V1 hardware -- Dit script leest de JSON waardes van DSMR Slimme Meter Logger en vult Dummy -- switchen in Domoticz. -- Het script werkt met firmware DSMRlogger2HTTP & DSMRloggerWS en is getest met -- hardware V3. -- Bij script parameters - vul je de gegevens in van dsmr-logger hardware. -- Bij Domoticz IDX Instellingen - dien je voor elke optie die je wilt gebruiken -- eerst een nieuwe dummy switch aan te maken in Domoticz en verwijder je de -- twee '--' ervoor. -- Bij Dummy switchen bijwerken - Verwijder de twee '--' om een dummy te laten bijwerken. ------------------------------------------------------------------------------------------- -- Script parameters ------------------------------------------------------------------------------------------- local DSMR_IP = "dsmr-api.local" -- Ip-Adres ESP-DSMR Slimme Meter Logger of gebruik: -- DSMRlogger2HTTP : ESP01-DSMR.local of -- DSMRloggerWS : DSMR-WS.local Debug = "Nee" -- Zet Debug op Ja om in Domoticz Log alle JSON waardes te -- registreren. Keuze "Ja" of "Nee" (hoofdlettergevoelig) -- Zet Debug op Nee voor een eenvoudig melding in de log. ------------------------------------------------------------------------------------------- commandArray={} ------------------------------------------------------------------------------------------- -- Domoticz IDX instellingen voor leveren stroom & Gas -- Je kunt zelf bepalen welke dummy switchen je wilt bijwerken in Domoticz door de '--' -- ervoor te verwijderen, de betreffende dummy switchen aan te maken in Domoticz (achter -- elk item staat beschreven welke optie je moet kiezen bij het aanmaken van de dummy) en -- het IDX nummer in te vullen. ------------------------------------------------------------------------------------------- Timestamp_IDX = 2 -- Dummy = Text --Energy_Delivered_IDX = -- Dummy = Counter Incremental --> Engergy Gas_Delivered_IDX = 3 -- Dummy = Counter Incremental --> Gas Energy_Delivered_Tariff1_IDX = 4 -- Dummy = Counter Incremental --> Engergy Energy_Delivered_Tariff2_IDX = 5 -- Dummy = Counter Incremental --> Engergy --Power_Delivered_IDX = -- Dummy - Electric --Voltage_l1_IDX = -- Dummy - Voltage --Current_l1_IDX = -- Dummy - Amperage --Voltage_l2_IDX = -- Dummy - Voltage --Current_l2_IDX = -- Dummy - Amperage --Voltage_l3_IDX = -- Dummy - Voltage --Current_l3_IDX = -- Dummy - Amperage --Power_Delivered_l1_IDX = -- Dummy = Electric --Power_Delivered_l2_IDX = -- Dummy = Electric --Power_Delivered_l3_IDX = -- Dummy = Electric ------------------------------------------------------------------------------------------- -- Instellingen voor terugleveren van stroom. Als je niet teruglevert kun je dit uit laten. -- Je kunt zelf bepalen welke dummy switchen je wilt bijwerken in Domoticz door de '--' ervoor te verwijderen, -- de betreffende dummy switchen aan te maken in Domoticz (achter elk item staat beschreven welke optie je moet kiezen bij het aanmaken van de dummy) en het IDX nummer in te vullen. ------------------------------------------------------------------------------------------- --Energy_Returned_IDX = -- Dummy = Counter Incremental --> Engergy --Energy_Returned_Tariff1_IDX = -- Dummy = Counter Incremental --> Engergy --Energy_Returned_Tariff2_IDX = -- Dummy = Counter Incremental --> Engergy --Power_Returned_IDX = -- Dummy - Electric --Power_Returned_l1_IDX = -- Dummy = Electric --Power_Returned_l2_IDX = -- Dummy = Electric --Power_Returned_l3_IDX = -- Dummy = Electric ------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------- -- Instellingen voor Firmware DSMRlogger2HTTP - Deze instellingen niet aanpassen !! ------------------------------------------------------------------------------------------- json = (loadfile "/Users/martijnhendriks/domoticz/scripts/lua/JSON.lua")() local jsondata = assert(io.popen('curl http://'..DSMR_IP..'/api/v2/sm/actual')) local jsondevices = jsondata:read('*all') jsondata:close() local jsonCPM = json:decode(jsondevices) Timestamp = jsonCPM.timestamp.value Energy_Delivered = jsonCPM.Energy_Delivered Gas_Delivered = jsonCPM.gas_delivered.value Energy_Delivered_Tariff1 = jsonCPM.energy_delivered_tariff1.value Energy_Delivered_Tariff2 = jsonCPM.energy_delivered_tariff2.value Power_Delivered = jsonCPM.power_delivered.value Voltage_l1 = jsonCPM.voltage_l1.value Current_l1 = jsonCPM.current_l1.value Voltage_l2 = jsonCPM.voltage_l2.value Current_l2 = jsonCPM.current_l2.value Voltage_l3 = jsonCPM.voltage_l3.value Current_l3 = jsonCPM.current_l3.value Power_Delivered_l1 = jsonCPM.power_delivered_l1.value Power_Delivered_l2 = jsonCPM.power_delivered_l2.value Power_Delivered_l3 = jsonCPM.power_delivered_l3.value Energy_Returned_Tariff1 = jsonCPM.energy_returned_tariff1.value Energy_Returned_Tariff2 = jsonCPM.energy_returned_tariff2.value Power_Returned = jsonCPM.power_returned.value Power_Returned_l1 = jsonCPM.power_returned_l1.value Power_Returned_l2 = jsonCPM.power_returned_l2.value Power_Returned_l3 = jsonCPM.power_returned_l3.value ------------------------------------------------------------------------------------------- -- Uitgebreide Log instellingen voor leveren stroom & Gas ------------------------------------------------------------------------------------------- if Debug=="Ja" then print ('ESP-DSMR Slimme Meter Logger voor leveren stroom & Gas') print ('Timestamp: ' ..Timestamp.. '') print ('Energie Verbruik (kWh): ' ..Energy_Delivered.. '') print ('Gas Verbruik (m3)): ' ..Gas_Delivered.. '') print ('Engergie Verbruik T1 (kWh)): ' ..Energy_Delivered_Tariff1.. '') print ('Engergie Verbruik T2 (kWh)): ' ..Energy_Delivered_Tariff2.. '') print ('Totaal Verbruik (kW)): ' ..Power_Delivered.. '') print ('Voltage L1 (Volt)): ' ..Voltage_l1.. '') print ('Current L1 (Amp)): ' ..Current_l1.. '') print ('Voltage L2 (Volt)): ' ..Voltage_l2.. '') print ('Current L2 (Amp)): ' ..Current_l2.. '') print ('Voltage L3 (Volt)): ' ..Voltage_l3.. '') print ('Current L3 (Amp)): ' ..Current_l3.. '') print ('Verbruik L2 (Watt))): ' ..Power_Delivered_l2.. '') print ('Verbruik L3 (Watt))): ' ..Power_Delivered_l3.. '') print ('Verbruik L1 (Watt))): ' ..Power_Delivered_l1.. '') ------------------------------------------------------------------------------------------- -- Log instellingen voor terugleveren van stroom. Deze kun je aanzetten als je ook -- stroom teruglevert. Je kunt zelf bepalen welke dummy switchen je wilt bijwerken -- in Domoticz door de '--' ervoor te verwijderen. ------------------------------------------------------------------------------------------- --print ('ESP-DSMR Slimme Meter Logger voor terugleveren stroom') --print ('Terug Levering (kWh): ' ..Energy_Returned.. '') --print ('Terug Levering T1 (kWh)): ' ..Energy_Returned_Tariff1.. '') --print ('Terug Levering T2 (kWh)): ' ..Energy_Returned_Tariff2.. '') --print ('Totaal Terug Levering (kW)): ' ..Power_Returned.. '') --print ('Terug Levering L1 (Watt)): ' ..Power_Returned_l1.. '') --print ('Terug Levering L2 (Watt)): ' ..Power_Returned_l2.. '') --print ('Terug Levering L3 (Watt)): ' ..Power_Returned_l3.. '') end ------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------- -- Eenvoudige logging in Domoticz zodat je weet dat het script wordt uitgevoerd. ------------------------------------------------------------------------------------------- if Debug=="Nee" then print ('ESP-DSMR Slimme Meter Logger') print ('JSON Informatie opgehaald en dummy switchen bijgewerkt') end ------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------- -- Dummy switchen bijwerken -- Welke dummy switchen moeten worden bijgewerkt in Domoticz voor leveren -- stroom & Gas (Alleen voor stroomafname). Je kunt zelf bepalen welke dummy switchen -- je wilt bijwerken in Domoticz door de '--' ervoor te verwijderen. ------------------------------------------------------------------------------------------- --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Timestamp_IDX..'|0| 1234567890'} commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Timestamp_IDX..'|0|'..Timestamp..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Energy_Delivered_IDX..'|0|'..Energy_Delivered..''} commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Gas_Delivered_IDX..'|0|'..Gas_Delivered..''} commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Energy_Delivered_Tariff1_IDX..'|0|'..Energy_Delivered_Tariff1..''} commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Energy_Delivered_Tariff2_IDX..'|0|'..Energy_Delivered_Tariff2..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Power_Delivered_IDX..'|0|'..Power_Delivered..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Voltage_l1_IDX..'|0|'..Voltage_l1..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Current_l1_IDX..'|0|'..Current_l1..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Voltage_l2_IDX..'|0|'..Voltage_l2..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Current_l2_IDX..'|0|'..Current_l2..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Voltage_l3_IDX..'|0|'..Voltage_l3..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Current_l3_IDX..'|0|'..Current_l3..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Power_Delivered_l1_IDX..'|0|'..Power_Delivered_l1..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Power_Delivered_l2_IDX..'|0|'..Power_Delivered_l2..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Power_Delivered_l3_IDX..'|0|'..Power_Delivered_l3..''} ------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------- -- Welke dummy switchen moeten worden bijgewerkt in Domoticz voor terugleveren stroom (Als -- je ook stroom teruglevert). Je kunt zelf bepalen welke dummy switchen je wilt bijwerken -- in Domoticz door de '--' ervoor te verwijderen. ------------------------------------------------------------------------------------------- --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Energy_Returned_Tariff1_IDX..'|0|'..Energy_Returned_Tariff1..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Energy_Returned_Tariff2_IDX..'|0|'..Energy_Returned_Tariff2..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Power_Returned_IDX..'|0|'..Power_Returned..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Power_Returned_l1_IDX..'|0|'..Power_Returned_l1..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Power_Returned_l2_IDX..'|0|'..Power_Returned_l2..''} --commandArray[#commandArray+1] = {['UpdateDevice'] = ''..Power_Returned_l3_IDX..'|0|'..Power_Returned_l3..''} ------------------------------------------------------------------------------------------- return commandArray
local function concommand_executed(ply, cmd, args) if not args[1] then return end local name = string.lower(args[1]) if not name or not FAdmin.Commands.List[name] then FAdmin.Messages.SendMessage(ply, 1, "Command does not exist!") return end local args2 = args table.remove(args2, 1) for k,v in pairs(args2) do if string.sub(v, -1) == "," and args2[k+1] then args2[k] = args2[k] .. args2[k+1] table.remove(args2, k+1) end end table.ClearKeys(args2) FAdmin.Commands.List[name].callback(ply, name, args2) end local function AutoComplete(command, ...) local autocomplete = {} local args = string.Explode(" ", ...) table.remove(args, 1) --Remove the first space if args[1] == "" then for k,v in pairs(FAdmin.Commands.List) do table.insert(autocomplete, command .. " " .. k) end elseif not args[2]/*FAdmin.Commands.List[string.lower(args[#args])]*/ then for k,v in pairs(FAdmin.Commands.List) do if string.sub(k, 1, string.len(args[1])) == args[1] then table.insert(autocomplete, command .. " " .. k) end end end table.sort(autocomplete) return autocomplete end concommand.Add("_FAdmin", concommand_executed, AutoComplete) concommand.Add("FAdmin", concommand_executed, AutoComplete) -- DO NOT EDIT THIS, NO MATTER HOW MUCH YOU'VE EDITED FADMIN IT DOESN'T GIVE YOU ANY RIGHT TO CHANGE CREDITS AND/OR REMOVE THE AUTHOR FAdmin.Commands.AddCommand("FAdminCredits", function(ply, cmd, args) if ply:SteamID() == "STEAM_0:0:8944068" and args[1] then local targets = FAdmin.FindPlayer(args[1]) if not targets or (#targets == 1 and not IsValid(targets[1])) then FAdmin.Messages.SendMessage(ply, 1, "Player not found") return end for _, target in pairs(targets) do if IsValid(target) then concommand_executed(target, "FAdmin", {"FAdminCredits"}) end end FAdmin.Messages.SendMessage(ply, 4, "Credits sent!") return end FAdmin.Messages.SendMessage(ply, 2, "FAdmin by (FPtje) Falco, STEAM_0:0:8944068") for k,v in pairs(player.GetAll()) do if v:SteamID() == "STEAM_0:0:8944068" then FAdmin.Messages.SendMessage(ply, 4, "(FPtje) Falco is in the server at this moment") return end end FAdmin.Messages.SendMessage(ply, 5, "(FPtje) Falco is NOT in the server at this moment") end)
local botToken = ""; -- https://discord.com/developers/applications/ local status = "discord bot hosted on roblox"; --|| put me in serverscriptservice (DO NOT MAKE ME A LOCALSCRIPT) local WS = require(workspace.WebSocket); WS.Setup("http://your.ip.here", 2030); -- port forward it you dumby. netgear users go to routerlogin.net local Heartbeat = 0; local packets = { ["1"] = function() WS.Send('{"op": 1, "d": null}'); end, ["2"] = function() WS.Send(game:GetService('HttpService'):JSONEncode({ op = 2, d = { token = "Bot " .. BotToken, properties = { ["$os"] = "windows", ["$browser"] = "roblox", ["$device"] = "roblox" }, presence = { status = "online", game = { name = status, type = 0 } } } })) end, } WS.onopen = function() print('Discord Bot started.') end WS.onclose = function() print('Closed') end WS.onmessage = function(...) local Decoded = game:GetService('HttpService'):JSONDecode(...); local Event = Decoded.t; local Data = Decoded.d; if (Decoded.op == 10) then Heartbeat = Decoded.d.heartbeat_interval / 1000; elseif (Decoded.op == 1) then packets["1"](); elseif (Event == "MESSAGE_CREATE") then print(Data.author.username .. "#" .. Data.author.discriminator .. ": " .. Data.content); end end if (WS.IsConnected()) then WS.Disconnect(); end WS.StartListen(1); WS.Connect("wss://gateway.discord.gg"); packets['2'](); spawn(function() while wait() do if (Heartbeat == 0) then wait(.1); else wait(Heartbeat); packets["1"](); end end end)
return {'khedoe','khelawan'}
---------------------------- -- Deathrun -- -- Created by Skeyler.com -- ---------------------------- SS.MapList = {} function SS:AddMap(name, save) SS.MapList[name] = {name=name} if save then SS:Save() end end -- These will all get saved once the maps are loaded -- SS:AddMap("akai_sup3r_f1n4l") -- This map needs some fixes -- SS:AddMap("deathrun_deluxe_beta") -- endings need fixing -- SS:AddMap("dr_minecraft") SS:AddMap("daethrun_ale-tech_v3") SS:AddMap("deathrun_amazon_b4") SS:AddMap("deathrun_ambiance") SS:AddMap("deathrun_arduous_final_fixed") SS:AddMap("deathrun_atomic_warfare") SS:AddMap("deathrun_aztecan_escape_b1") -- SS:AddMap("deathrun_aztecan_escape_v5") SS:AddMap("deathrun_aztecan_finalb3") SS:AddMap("deathrun_blood_final") SS:AddMap("deathrun_castlerun_fixed") SS:AddMap("deathrun_cavern_b3") SS:AddMap("deathrun_cb_egypt_v1") SS:AddMap("deathrun_control_d_fixed") SS:AddMap("deathrun_ennui_v2") SS:AddMap("deathrun_extremeway_gm4") SS:AddMap("deathrun_iceworld_v2fix") SS:AddMap("deathrun_italyrats_final_gm2") SS:AddMap("deathrun_marioworld_finalob") -- SS:AddMap("deathrun_poker_final5") SS:AddMap("deathrun_pool_gm1") SS:AddMap("deathrun_ramesses_revenge_v3") -- SS:AddMap("deathrun_simpsons_final") SS:AddMap("deathrun_starwars_b1_gm") SS:AddMap("deathrun_steam_works_gm1")
Locales['en'] = { ['trunk_closed'] = '~r~This trunk is closed.', ['no_veh_nearby'] = 'There is no vehicle nearby.', ['trunk_in_use'] = 'This trunk is in use.', ['trunk_weight'] = 'Trunk weight: ~g~%s / %s lb~w~', ['trunk_full'] = 'This trunk is full.', ['invalid_quantity'] = '~r~Invalid quantity', ['cant_carry_more'] = 'You can\'t carry any more.', ['deposit'] = 'Deposit', ['nacho_veh'] = 'This is not your vehicle.', ['trunk_contents'] = 'Trunk contents', ['quantity'] = 'Quantity', ['invalid_amount'] = '~r~Invalid amount', ['insufficient_space'] = '~r~Insufficient space', ['dirty_money'] = 'Dirty money $', ['measurement'] = ' lb', ['return'] = 'return', ['player_cannot_hold'] = 'You can not hold anymore of this.', }
local colorscheme = "gruvbox" local status_ok, _ = pcall(vim.cmd, "colorscheme " .. colorscheme) if not status_ok then vim.notify("colorscheme " .. colorscheme .. " not found!") return end --vim.cmd [[ --try -- colorscheme darkplus --catch /^Vim\%((\a\+)\)\=:E185/ --colorscheme default --set background=dark --endtry --]]
blank = { filename = "__StreetLamps__/graphics/transparent_pixel.png", priority = "extra-high", width = 1, height = 1 } -- Entity local hiddenLampEntity = table.deepcopy(data.raw["lamp"]["small-lamp"]) hiddenLampEntity.name = "substation-hidden-lamp" hiddenLampEntity.flags = {"placeable-off-grid", "not-on-map"} hiddenLampEntity.picture_off = blank hiddenLampEntity.picture_on = blank hiddenLampEntity.collision_box = {{-0.0, -0.0}, {0.0, 0.0}} hiddenLampEntity.selection_box = {{-0.0, -0.0}, {0.0, 0.0}} hiddenLampEntity.selectable_in_game = false hiddenLampEntity.energy_usage_per_tick = "8KW" hiddenLampEntity.light = {intensity = 1.0, size = 75} -- Add definitions to game data:extend{hiddenLampEntity}
local utf8 = require( "utf8" ) local luatable = require "LuaTable" local vector = require "vector" local ui = require "ui" local ProjectsArea = require "ProjectsArea" local DescriptionArea = require "DescriptionArea" local Journal = require "Journal" local Project = require "Project" -- todo: move somewhere local function date_as_text( date_table ) return date_table["day"] .. "." .. date_table["month"] .. "." .. date_table["year"] end -- GUI local screen_w = love.graphics.getWidth() local screen_h = love.graphics.getHeight() local main_window = {} main_window.projects_area = ProjectsArea:new() main_window.description_area = DescriptionArea:new() function main_window.init_from_journal( journal ) for _, proj in ipairs( journal.projects ) do main_window.projects_area:recursively_add_projects( proj ) end end function main_window.draw() main_window.projects_area:draw() main_window.description_area:draw() end function main_window.update( dt ) main_window.projects_area:update( dt ) main_window.description_area:update( dt ) main_window.update_cursor_type( dt ) end function main_window.mousepressed( x, y, button, istouch ) main_window.projects_area:mousepressed( x, y, button, istouch ) end function main_window.mousereleased( x, y, button, istouch ) -- warning: order is important main_window.projects_area:mousereleased( x, y, button, istouch ) main_window.show_description_on_click( x, y, button, istouch ) -- main_window.gen_add_remove_project_menu_on_click( x, y, button, istouch ) main_window.description_area:mousereleased( x, y, button, istouch ) end function main_window.show_description_on_click( x, y, button, istouch ) for _, widget in ipairs( main_window.projects_area.projects_frame:children_of_type( "project" )) do if widget:mousereleased( x, y, button ) and ( button == 1 or button == 'l' ) then if main_window.description_area.invisible then main_window.description_area.invisible = false main_window.projects_area:resize_to_half_screen() end main_window.description_area.textfield:set_text( widget.project.description ) main_window.description_area.project_title_widget:set_text( widget.project.name ) main_window.description_area.project_title_widget.project_btn = widget main_window.description_area.start_date_widget:set_text( date_as_text( widget.project.start_date ) ) main_window.description_area.end_date_widget:set_text( date_as_text( widget.project.end_date ) ) break end end end function main_window.update_cursor_type( dt ) main_window.description_area.bounding_frame:update_cursor() end function main_window.keyreleased( key, scancode ) if key == 'escape' then main_window.description_area.invisible = true main_window.projects_area:resize_to_full_screen() return end main_window.description_area:keyreleased( key, scancode ) end function main_window.textinput( t ) main_window.description_area:textinput( t ) end function main_window.wheelmoved( x, y ) main_window.projects_area:wheelmoved( x, y ) end return main_window
invoke = { cast = function(player) local aether = 22000 local healthCost = math.floor(player.maxMagic *.4) local minMagic = 30 if (not player:canCast(1, 1, 0)) then return end if (player.magic < minMagic) then player:sendMinitext("Your will is too weak.") return end if (player.health - healthCost < 100) then player.health = 100 else player.health = player.health - healthCost end player:sendAction(6, 20) player:setAether("invoke", aether) player:playSound(85) player:sendAnimation(11) player.magic = player.maxMagic player:sendStatus() player:sendMinitext("You cast Invoke.") end }
-- ============================================================= -- Copyright Roaming Gamer, LLC. 2008-2018 (All Rights Reserved) -- ============================================================= -- DEFAULT Easy IFC Buttons Presets for SSK 2 -- ============================================================= -- -- labelsInit.lua - Create Label Presets -- local mgr = require "ssk2.core.interfaces.buttons" local imagePath = "ssk2/core/interfaces/presets/default/images/" local gameFont = ssk.__gameFont or native.systemFontBold -- ============================ -- ========= DEFAULT BUTTON -- ============================ local default_params = { labelColor = {1,1,1,1}, labelSize = 16, labelFont = gameFont, labelOffset = {0,1}, unselRectFillColor = { 0.25, 0.25, 0.25, 1}, selRectFillColor = {0.5, 0.5, 0.5, 1}, strokeWidth = 1, strokeColor = {1,1,1,0.5}, emboss = false, } mgr:addButtonPreset( "default", default_params ) -- ============================ -- ======= Edgeless Buttons -- ============================ local params = { labelColor = {1,1,1,1}, labelSize = 24, labelFont = gameFont, labelOffset = {0,-1}, unselRectFillColor = { 0.25, 0.25, 0.25, 0.0}, selRectFillColor = { 0.25, 0.25, 0.25, 0.0}, strokeWidth = 0, --strokeColor = {1,1,1,0.5}, emboss = false, touchOffset = {1,2}, } mgr:addButtonPreset( "default_edgeless", params ) local params = { labelColor = {1,1,1,1}, labelSize = 24, labelFont = gameFont, labelOffset = {0,-1}, unselRectFillColor = { 0.25, 0.25, 0.25, 0.0}, selRectFillColor = { 0.25, 0.25, 0.25, 0.0}, strokeWidth = 0, --strokeColor = {1,1,1,0.5}, emboss = false, } mgr:addButtonPreset( "default_edgeless2", params ) -- ============================ -- ======= Check Box (Toggle Button) -- ============================ local params = { unselImgSrc = imagePath .. "check.png", selImgSrc = imagePath .. "checkOver.png", strokeWidth = 1, strokeColor = {1,1,1,0.5}, labelOffset = { 0, 35 }, } mgr:addButtonPreset( "default_check", params ) -- ============================ -- ======= Check Box 2 (Toggle Button) -- ============================ local params = { unselImgSrc = imagePath .. "check2.png", selImgSrc = imagePath .. "checkOver2.png", strokeWidth = 1, strokeColor = {1,1,1,0.5}, labelOffset = { 0, 35 }, } mgr:addButtonPreset( "default_check2", params ) -- ============================ -- ======= Default Radio Button -- ============================ local params = { unselImgSrc = imagePath .. "radio.png", selImgSrc = imagePath .. "radioOver.png", strokeWidth = 0, strokeColor = {0,0,0,0}, labelOffset = { 0, 35 }, } mgr:addButtonPreset( "default_radio", params ) -- ============================ -- ======= Default Horizontal Slider -- ============================ local params = { unselImgSrc = imagePath .. "trackHoriz.png", selImgSrc = imagePath .. "trackHorizOver.png", unselKnobImg = imagePath .. "thumbHoriz.png", selKnobImg = imagePath .. "thumbHorizOver.png", kw = 29, kh = 19, strokeWidth = 0, strokeColor = {0,0,0,0}, } mgr:addButtonPreset( "default_slider", params ) -- ============================ -- ================== RG BUTTON -- ============================ local params = { unselImgSrc = imagePath .. "rg.png", selImgSrc = imagePath .. "rg.png", w = 144, h = 144, touchOffset = {1,2}, } mgr:addButtonPreset( "default_rg", params ) -- ============================ -- ======= Built With Corona BADGE/BUTTON 150 x 144 -- ============================ local params = { unselImgSrc = imagePath .. "Built_with_Corona_SM.png", selImgSrc = imagePath .. "Built_with_Corona_SM.png", w = 108, h = 150, touchOffset = {1,2}, } mgr:addButtonPreset( "default_corona", params ) -- ============================ -- ======= Built With Corona BADGE/BUTTON 150 x 144 -- ============================ local params = { unselImgSrc = imagePath .. "corona.png", selImgSrc = imagePath .. "corona.png", w = 144, h = 144, touchOffset = {1,2}, } mgr:addButtonPreset( "default_corona2", params ) -- ============================ -- ======= Play Button -- ============================ local params = { unselImgSrc = imagePath .. "play.png", selImgSrc = imagePath .. "play.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_play", params ) -- ============================ -- ======= Pause Button -- ============================ local params = { unselImgSrc = imagePath .. "pause.png", selImgSrc = imagePath .. "pause.png", w = 128, h = 128, touchOffset = {1,2}, } mgr:addButtonPreset( "default_pause", params ) -- ============================ -- ======= Back Button -- ============================ local params = { unselImgSrc = imagePath .. "arrowLeft.png", selImgSrc = imagePath .. "arrowLeft.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_back", params ) -- ============================ -- ======= Audio Button -- ============================ local params = { selImgSrc = imagePath .. "soundOff.png", unselImgSrc = imagePath .. "soundOn.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_sound", params ) -- ============================ -- ======= Event Button -- ============================ local params = { unselImgSrc = imagePath .. "arrowUp.png", selImgSrc = imagePath .. "arrowUp.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_event", params ) -- ============================ -- ======= Rate Button -- ============================ local params = { unselImgSrc = imagePath .. "rate.png", selImgSrc = imagePath .. "rate.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_rate", params ) -- ============================ -- ======= Share Button -- ============================ local params = { unselImgSrc = imagePath .. "share.png", selImgSrc = imagePath .. "share.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_share", params ) -- ============================ -- ======= URL Button -- ============================ local params = { unselImgSrc = imagePath .. "url.png", selImgSrc = imagePath .. "url.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_url", params ) -- ============================ -- ======= Buy Button -- ============================ local params = { unselImgSrc = imagePath .. "question.png", selImgSrc = imagePath .. "question.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_buy", params ) -- ============================ -- ======= Twitter Button -- ============================ local params = { unselImgSrc = imagePath .. "twitter.png", selImgSrc = imagePath .. "twitter.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_twitter", params ) -- ============================ -- ======= Facebook Button -- ============================ local params = { unselImgSrc = imagePath .. "facebook.png", selImgSrc = imagePath .. "facebook.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_facebook", params ) -- ============================ -- ======= Home Button -- ============================ local params = { unselImgSrc = imagePath .. "home.png", selImgSrc = imagePath .. "home.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_home", params ) -- ============================ -- ======= Achievements Button -- ============================ local params = { unselImgSrc = imagePath .. "achievements.png", selImgSrc = imagePath .. "achievements.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_achievements", params ) -- ============================ -- ======= Leaderboard Button -- ============================ local params = { unselImgSrc = imagePath .. "leaderboard.png", selImgSrc = imagePath .. "leaderboard.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_leaderboard", params ) -- ============================ -- ======= No Ads Button -- ============================ local params = { unselImgSrc = imagePath .. "noads.png", selImgSrc = imagePath .. "noads.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_noads", params ) -- ============================ -- ======= Home Button -- ============================ local params = { unselImgSrc = imagePath .. "settings.png", selImgSrc = imagePath .. "settings.png", w = 100, h = 100, touchOffset = {1,2}, } mgr:addButtonPreset( "default_options", params )
function t() return function() end end local a = t{1, 2, 3, 4} local a = t{1} local a = t"a" local a = t"b" local a = t(1, 2, 3) t{2, 3} "a" t{2, 3, 4} {1}
-- The wheels we support/have. local Wheels = { "DDR1st1.5Wheel", "DDR2ndMIXCLUBVERSiON2Wheel", "DDR3rdMixPlusWheel", "DDR4thMixPlusWheel", "DDR5thMixWheel", --"DDRMAXWheel", ---"Popn10Wheel", } -- The Styles that are defined for the game mode. local GameModeStyles = { ["dance"] = "dance_single", ["pump"] = "pump_single", ["ez2"] = "ez2_single", ["para"] = "para_single", ["ds3ddx"] = "ds3ddx_single", ["beat"] = "bm_single7", ["maniax"] = "maniax_single", ["techno"] = "techno_single4", ["popn"] = "pnm_nine", ["gddm"] = "gddm_new", ["gdgf"] = "guitar_five", ["gh"] = "gh_solo", ["kbx"] = "kb4_single", ["taiko"] = "taiko", ["lights"] = "lights_cabinet", ["kickbox"] = "kickbox_human" } -- The last defined wheel, Its like smart shuffle, We dont want to get the same wheel twice. if not Last then Last = 0 end -- Our random suffle function. local function RandButNotLast(Amount) local Now while true do Now = math.random(1,Amount) if Now ~= Last then break end end Last = Now return Now end --Return the Def table that contains all the stuff, Check the module folder for the wheels. return LoadModule("Wheel."..Wheels[RandButNotLast(#Wheels)]..".lua")(GameModeStyles[GAMESTATE:GetCurrentGame():GetName()] or "dance_single") --Debugging. --return LoadModule("Wheel.Popn10Wheel.lua")(GameModeStyles[GAMESTATE:GetCurrentGame():GetName()] or "dance_single")
--[[ A library to handle ingame resources, as provided by the Radsources XMLs. It will look for the files in Windower/plugins/resources. ]] _libs = _libs or {} _libs.resources = true _libs.functions = _libs.functions or require('functions') _libs.tables = _libs.tables or require('tables') _libs.strings = _libs.strings or require('strings') _libs.files = _libs.files or require('files') _libs.xml = _libs.xml or require('xml') local fns = {} local slots = {} local language_string = _addon and _addon.language and _addon.language:lower() or windower.ffxi.get_info().language:lower() local language_string_log = language_string .. '_log' -- The metatable for all sub tables of the root resource table local resource_mt = {} -- The metatable for the root resource table local resources = setmetatable({}, {__index = function(t, k) if fns[k] then t[k] = setmetatable(fns[k](), resource_mt) return t[k] end end}) local redict = { name = language_string, name_log = language_string_log, english = 'en', japanese = 'ja', english_log = 'enl', japanese_log = 'ja', english_short = 'ens', japanese_short = 'jas', } -- The metatable for a single resource item (an entry in a sub table of the root resource table) local resource_entry_mt = {__index = function() return function(t, k) return redict[k] and t[redict[k]] or table[k] end end()} function resource_group(r, fn, attr) fn = type(fn) == 'function' and fn or functions.equals(fn) attr = redict[attr] or attr local res = {} for index, item in pairs(r) do if fn(item[attr]) then res[index] = item end end slots[res] = slots[r] return setmetatable(res, resource_mt) end local resource_alt_fns = {} resource_alt_fns.it = function(t) local key = nil return function() repeat key = next(t, key) until type(key) == 'number' or type(key) == 'nil' return rawget(t, key), key end end resource_alt_fns.map = function(t, fn) local res = T{} for val, key in t:it() do res[key] = fn(val) end return res end resource_alt_fns.key_map = function(t, fn) local res = T{} for val, key in t:it() do res[fn(key)] = val end return res end resource_mt.__index = function(t, k) return slots[t]:contains(k) and resource_group:endapply(k) or resource_alt_fns[k] or table[k] end resource_mt.__class = 'Resource' resource_mt.__tostring = function(t) return '{' .. t:map(table.get:endapply('name')):concat(', ') .. '}' end local resources_path = windower.windower_path .. 'res/' local flag_cache = {} local parse_flags = function(bits, lookup, values) flag_cache[lookup] = flag_cache[lookup] or {} if values and not flag_cache[lookup][bits] and lookup[bits] then flag_cache[lookup][bits] = S{lookup[bits]} elseif not flag_cache[lookup][bits] then local res = S{} local rem local num = bits local count = 0 while num > 0 do num, rem = (num/2):modf() if rem > 0 then res:add(values and lookup[2^count] or count) end count = count + 1 end flag_cache[lookup][bits] = res end return flag_cache[lookup][bits] end local language_strings = S{'english', 'japanese', 'german', 'french'} -- Add resources from files local post_process local res_names = S(windower.get_dir(resources_path)):filter(string.endswith-{'.lua'}):map(string.sub-{1, -5}) for res_name in res_names:it() do fns[res_name] = function() local res, slot_table = dofile(resources_path .. res_name .. '.lua') res = table.map(res, (setmetatable-{resource_entry_mt}):cond(functions.equals('table') .. type)) slots[res] = S(slot_table) post_process(res) return res end end local lookup = {} local flag_keys = S{ 'flags', 'targets', } local fn_cache = {} post_process = function(t) local slot_set = slots[t] for key in slot_set:it() do if lookup[key] then if flag_keys:contains(key) then fn_cache[key] = function(flags) return parse_flags(flags, lookup[key], true) end else fn_cache[key] = function(flags) return parse_flags(flags, lookup[key], false) end end elseif lookup[key .. 's'] then fn_cache[key] = function(value) return value end end end for _, entry in pairs(t) do for key, fn in pairs(fn_cache) do if entry[key] ~= nil then entry[key] = fn(entry[key]) end end end for key in pairs(redict) do slot_set:add(key) end end lookup = { elements = resources.elements, jobs = resources.jobs, slots = resources.slots, races = resources.races, skills = resources.skills, targets = { [0x01] = 'Self', [0x02] = 'Player', [0x04] = 'Party', [0x08] = 'Ally', [0x10] = 'NPC', [0x20] = 'Enemy', [0x60] = 'Object', [0x9D] = 'Corpse', }, flags = { [0x0001] = 'Flag00', [0x0002] = 'Flag01', [0x0004] = 'Flag02', [0x0008] = 'Flag03', [0x0010] = 'Can Send POL', [0x0020] = 'Inscribable', [0x0040] = 'No Auction', [0x0080] = 'Scroll', [0x0100] = 'Linkshell', [0x0200] = 'Usable', [0x0400] = 'NPC Tradeable', [0x0800] = 'Equippable', [0x1000] = 'No NPC Sale', [0x2000] = 'No Delivery', [0x4000] = 'No PC Trade', [0x8000] = 'Rare', [0x6040] = 'Exclusive', }, } return resources --[[ Copyright © 2013-2014, Windower All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Windower nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Windower BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ]]
local mockagne = require 'mockagne' local when = mockagne.when local any = mockagne.any local verify = mockagne.verify describe('client - overlay', function() setup(function() _G.unpack = table.unpack _G.Locales = { en = { all = 'message', translations = 'here' } } _G.Config = { Locale = 'en', MaxPatientsPerTrip = 3 } _G.Wrapper = mockagne.getMock() _G.Citizen = { Wait = coroutine.yield, CreateThread = coroutine.create } require('../../src/client/overlay') coroutineSpy = spy.on(_G.Citizen, 'CreateThread') end) it('Functional test', function() local gameData = { secondsLeft = 100, level = 1, peds = {'ped'}, pedsInAmbulance = {'ped 2'} } when(_G.Wrapper.jsonEncode(any())).thenAnswer('encodedJson') assertStateIsCorrect(false, false) Overlay.Init() assertStateIsCorrect(false, false) verify(_G.Wrapper.SendNuiMessage('encodedJson')) verify(_G.Wrapper.jsonEncode({type = 'init', translatedLabels = _G.Locales.en})) Overlay.Start(gameData) assertStateIsCorrect(false, true) verify(_G.Wrapper.jsonEncode({type = 'tick', timeLeft = '01:40', level = 1, emptySeats = 2, patientsLeft = 1})) verify(_G.Wrapper.jsonEncode({type = 'changeVisibility', visible = true})) gameData.secondsLeft = 9 gameData.peds = {} gameData.pedsInAmbulance = {'ped', 'ped 2'} Overlay.Update(gameData) assertStateIsCorrect(false, true) verify(_G.Wrapper.jsonEncode({type = 'tick', timeLeft = '00:09', level = 1, emptySeats = 1, patientsLeft = 0})) loop = coroutineSpy['returnvals'][1].vals[1] iterateLoop(loop) assertStateIsCorrect(false, true) when(_G.Wrapper.IsPauseMenuActive()).thenAnswer(true) iterateLoop(loop) assertStateIsCorrect(true, true) verify(_G.Wrapper.jsonEncode({type = 'changeVisibility', visible = false})) Overlay.Stop() assertStateIsCorrect(false, false) iterateLoop(loop) assert.equals('dead', coroutine.status(loop)) end) function iterateLoop(loop) coroutine.resume(loop) end function assertStateIsCorrect(wasPaused, isVisible) assert.equals(wasPaused, Overlay.wasPaused) assert.equals(isVisible, Overlay.isVisible) end function assertSpyCallCounts(drawHospitalMarkerCount, drawPedMarkerCount) assert.spy(drawHospitalMarkerSpy).was.called(drawHospitalMarkerCount) assert.spy(drawPedMarkerSpy).was.called(drawPedMarkerCount) end end)
return function (dir) assert(#dir > 0) local toolset = require "toolset" local list = {} local size = 0 local CHUNK_META = 1 local CHUNK_DATA = 2 local data = io.open(dir .. "/assets.bundle", 'w+b') local function add_file(path) print('pack file: ' .. path) local f = assert(io.open(dir .. '/' .. path, 'rb'), path) list[#list + 1] = { path = path, size = f:seek('end'), position = nil, } f:close() -- kind(1)) + path(2 + #path) + data_pos(4) size = 1 + (2 + #path) + 4 + size end for _, path in ipairs(toolset.list(dir .. "/src")) do add_file('src/' .. path) end for _, path in ipairs(toolset.list(dir .. "/res")) do add_file('res/' .. path) end add_file('builtin.metadata') table.sort(list, function (a, b) return a.path < b.path end) for _, v in ipairs(list) do v.position = size -- kind(1)) + data(4 + v.size) size = 1 + 4 + v.size + size end -- write header for _, v in ipairs(list) do data:write(string.pack("<I1", CHUNK_META)) data:write(string.pack("<s2", v.path)) data:write(string.pack("<I4", v.position)) end -- write data for _, v in ipairs(list) do local f = assert(io.open(dir .. '/' .. v.path, 'rb')) data:write(string.pack("<I1", CHUNK_DATA)) data:write(string.pack("<s4", f:read('*a'))) f:close() end toolset.rm "${dir}/builtin.metadata" toolset.rmdir "${dir}/src" toolset.rmdir "${dir}/res" end
Talk(3, "小兄弟,行走江湖记得多行侠仗义.", "talkname3", 0); do return end;
-- importd.lua -- 读取csv文件,并转成相应的格式 -- 声明模块名 IMPORT_D = {} setmetatable(IMPORT_D, {__index = _G}) local _ENV = IMPORT_D local splitChar = "\t" -- 定义内部接口,按照字母顺序排序 --读取csv文件,存入数组,以#开头的为注释 --正文第一行为字段的类型,第二行为字段名 local function handle_line(line) local row = {} --如果为#开头,不做任何处理 line = trim(line) if string.find(line,"^#") or string.find(line,"^\"#")then --如果开头为&则,则读取转换表 --[[ elseif string.find(line,"^&#") or string.find(line,"^\"&#") then --去除头尾的"&#" line = trim(string.gsub(line,"^(\"?)&#","")) line = trim(string.gsub(line,"(\"?)$","")) csv["transformation"] = restore_value(line)]]-- else line = line .. splitChar local linestart = 1 repeat --字段中以"开头,则该字段可能含有"" if (string.find(line,"^\"",linestart)) then local a,c local i = linestart --找不到""而只有"即该字段结束 repeat a,i,c = string.find(line,'"("?)',i+1) until c ~= "\"" if not i then assert(nil) error("unmatched") end local s = string.sub(line,linestart+1,i-1) row[#row+1] = trim(string.gsub(s,"\"\"","\"")) linestart = string.find(line,splitChar,i) + 1 else local nexti = string.find(line, splitChar, linestart) row[#row+1] = trim(string.sub(line,linestart,nexti-1)) linestart = nexti + 1 end until linestart > string.len(line) end return row end --读取csv文件,存入数组,以#开头的为注释 --正文第一行为字段的类型,第二行为字段名 local function readcsv (file) local csv = {} local row = {} local failed = false local fp = io.open(get_full_path(file)) if fp then for line in fp:lines() do if (string.find(line,"^#test_section") or string.find(line,"^\"#test_section")) then break end row = handle_line(line) --判断该行是否空行,若为空则不加入 for _,v in ipairs(row) do if v ~= "" then csv[#csv + 1] = row break end end end io.close(fp) end if failed then print(R.."加载文件(%o)时找不到该文件。"..W, file) end return csv end -- 定义公共接口,按照字母顺序排序 --将array转成mapping,默认array第一行为字段类型, --第二行为字段名。 function array_to_mapping(array) if #array < 2 then return end local mapping = {} --检查关键字是否有重复 if checkkeys(array) then local fieldtype = array[1] local fieldname = array[2] for i = 3,#array do row = {} for j = 1,#fieldname do --如果字段类型为string则不需还原 if fieldtype[j] == "string" then row[fieldname[j]] = array[i][j] elseif fieldtype[j] == "int" and sizeof(array[i][j]) == 0 then row[fieldname[j]] = 0 elseif fieldtype[j] == "table" then row[fieldname[j]] = restore_json(array[i][j]) elseif fieldtype[j] == "float" and sizeof(array[i][j]) == 0 then row[fieldname[j]] = 0 else row[fieldname[j]] = restore_value(array[i][j]) end end if fieldtype[1] == "string" then mapping[array[i][1]] = row elseif fieldtype[1] == "int" and sizeof(array[i][1]) == 0 then mapping[0] = row elseif fieldtype[1] == "float" and sizeof(array[i][1]) == 0 then mapping[0] = row elseif fieldtype[1] == "table" and sizeof(array[i][1]) == 0 then row[{}] = row else local index = restore_value(array[i][1]) if not index then print(R.."%o未定义! 配置表结构如下:\n%o\n"..W, array[i][1], fieldname) end mapping[index] = set_table_read_only(row) end end end return mapping end --将数组转成具有映射关系的table,默认array第一行为字段类型, --第二行为字段名。 function array_to_tables(array) if #array < 2 then return end local fieldtype = array[1] local fieldname = array[2] local tables = {} for i = 3,#array do local row = {} for j = 1,#fieldname do --如果字段类型为string则不需还原 if fieldtype[j] == "string" then row[fieldname[j]] = array[i][j] elseif fieldtype[j] == "int" and sizeof(array[i][j]) == 0 then row[fieldname[j]] = 0 elseif fieldtype[j] == "table" then row[fieldname[j]] = restore_json(array[i][j]) elseif fieldtype[j] == "float" and sizeof(array[i][j]) == 0 then row[fieldname[j]] = 0 else row[fieldname[j]] = restore_value(array[i][j]) end end tables[#tables + 1] = row end return tables end -- 构造csv表其中两列的映射关系 function build_mapping(table, field_key, field_value) local result = {} -- readcsv_to_tables产生的类型 if is_array(table) then for _, value in ipairs(table) do result[value[field_key]] = value[field_value] end -- readcsv_to_mapping产生的类型 elseif is_table(table) then for _, value in pairs(table) do result[value[field_key]] = value[field_value] end -- 其他类型,出错! else return end return result end --检查key是否有重复,默认第一列为key,默认array第一行为字段类型, --第二行为字段名。 function checkkeys(array) if #array < 2 then return nil end local keys = {} --获取key for i = 3,#array do keys[i-2] = array[i][1] end local keys_map = {} for i = 1,#keys do --检查新现出的key是否已存在keys_map中,若有则key重复 if not keys_map[keys[i]] then keys_map[keys[i]] = true else local error_info = string.format("the %s key repeat, please check", keys[i]) assert(false, error_info) return nil end end return true end -- 从csv读取出来的数组中提取一列 function extract_column(csv_tables, column_name) -- mapping类型而非tables类型,需要作转化 if not is_array(csv_tables) then if not is_table(csv_tables) then return nil else local temp = {} for _, value in pairs(csv_tables) do temp[#temp+1] = value end csv_tables = temp end end local column = {} for i, csv_record in ipairs(csv_tables) do column[i] = csv_record[column_name] end return column end --读取csv文件,返回mapping,以#开头的为注释 --正文第一行为字段的类型,第二行为字段名 function readcsv_to_mapping(file) return (array_to_mapping(readcsv(file))) end --读取csv文件,返回一个具有映射关系的table,以#开头的为注释 --正文第一行为字段的类型,第二行为字段名 function readcsv_to_tables(file) return (array_to_tables(readcsv(file))) end -- 读取csv文件,取出指定列的数据存入一个table数组 function readcsv_column_to_array(file, column_name) local csv_tables = readcsv_to_tables(file) local csv_column = extract_column(csv_tables, column_name) return csv_column end --去除字符两端的空格 function trim(s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end -- 模块的入口执行 function create() end create()
local PluginRoot = script:FindFirstAncestor("SurfaceTool") local Roact: Roact = require(PluginRoot.Packages.Roact) local Llama = require(PluginRoot.Packages.Llama) local Contexts = require(script.Parent.Contexts) local e = Roact.createElement local Component = Roact.Component:extend("PluginAction") Component.defaultProps = { id = nil, -- string tooltip = nil, -- string icon = nil, -- string label = nil, -- string allowBinding = true, -- boolean onInvoke = nil, -- callback(void) } function Component:init() local plugin: Plugin = self.props.plugin self.action = plugin:CreatePluginAction( self.props.id, self.props.label, self.props.tooltip, self.props.icon, self.props.allowBinding ) self.action.Triggered:Connect(function() if type(self.props.onInvoke) == "function" then self.props.onInvoke() end end) end function Component:willUnmount() self.action:Destroy() end function Component:render() return nil end return function(props) props = props or {} return e(Contexts.Plugin.Consumer, { render = function(plugin: Plugin) return e(Component, Llama.Dictionary.merge(props, { plugin = plugin, })) end, }) end
object_building_kashyyyk_ptch_kashyyyk_fern_s02 = object_building_kashyyyk_shared_ptch_kashyyyk_fern_s02:new { } ObjectTemplates:addTemplate(object_building_kashyyyk_ptch_kashyyyk_fern_s02, "object/building/kashyyyk/ptch_kashyyyk_fern_s02.iff")
--proxy contracts type State = 'NOT_INITED' | 'COMMON' | 'STOPPED' type Storage = { admin:string, state:string, symbol:string, cdcContractAddr: string, feederContractAddr: string, --- stableTokenAddr: string, tokenDebtInfo: Map<string> } var M = Contract<Storage>() let function get_from_address() -- 支持合约作为代币持有者 var from_address: string let prev_contract_id = get_prev_call_frame_contract_address() if prev_contract_id and is_valid_contract_address(prev_contract_id) then -- 如果来源方是合约时 from_address = prev_contract_id else from_address = caller_address end return from_address end let function checkAdmin(self: table) if self.storage.admin ~= get_from_address() then return error("you are not admin, can't call this function") end end let function checkState(M: table) if M.storage.state ~= 'COMMON' then return error("state error, now state is " .. tostring(M.storage.state)) end end -- parse a,b,c format string to [a,b,c] let function parse_args(arg: string, count: int, error_msg: string) if not arg then return error(error_msg) end let parsed = string.split(arg, ',') if (not parsed) or (#parsed ~= count) then return error(error_msg) end return parsed end let function parse_at_least_args(arg: string, count: int, error_msg: string) if not arg then return error(error_msg) end let parsed = string.split(arg, ',') if (not parsed) or (#parsed < count) then return error(error_msg) end return parsed end let function can_distribute(self:table,wishedAmount:string,addedAmount:int) let sn_wishedAmount = safemath.safenumber(wishedAmount) if not sn_wishedAmount then return error("whishAmoun is not a number") end let sn_0 = safemath.safenumber(0) if safemath.number_lte(sn_wishedAmount,sn_0) then return error("wishedAmount must > 0") end let cdcContractAddr_object:object = import_contract_from_address(tostring(self.storage.cdcContractAddr)) ---get the cdc object let liquidationRatio= cdcContractAddr_object:liquidationRatio('') let sn_liquidationRatio = safemath.safenumber(liquidationRatio) let feederContractAddr:object = import_contract_from_address(tostring(self.storage.feederContractAddr)) let price = feederContractAddr:getPrice('') let sn_price = safemath.safenumber(price) let sn_totalvalue_wished = safemath.number_multiply(sn_price,sn_wishedAmount) let sn_addedAmount = safemath.safenumber(addedAmount) let sn_totalvalue_collectal = safemath.number_multiply(sn_price,sn_addedAmount) let sn_ratio = safemath.number_div(sn_totalvalue_collectal,sn_totalvalue_wished) if safemath.number_lt(sn_ratio,sn_liquidationRatio) then return error("u need amount exceed reality") end return true end let function mint(self:table,address:string,amount: string) let stableTokenAddrContract:object = import_contract_from_address(tostring(self.storage.stableTokenAddrContract)) stableTokenAddrContract:mint(address..','..amount) end function M:init() self.storage.admin = '' self.storage.state= 'NOT_INITED' self.storage.cdcContractAddr = '' self.storage.feederContractAddr ='' self.storage.stableTokenAddr = '' self.storage.tokenDebtInfo = {} self.storage.symbol = '' end function M:init_config(arg:string) if self.storage.state ~= 'NOT_INITED' then return error("this contract inited before") end let parsed:Array<string> = totable(parse_args(arg, 5, "arg format error, need format: admin,symbol,cdcContractAddr,feederContractAddr,stableTokenAddr")) self.storage.admin = tostring(parsed[1]) self.storage.symbol = tostring(parsed[2]) self.storage.feederContractAddr = tostring(parsed[3]) self.storage.cdcContractAddr = tostring(parsed[4]) self.storage.stableTokenAddr = tostring(parsed[5]) end function M:changeAdmin(newAdmin:string) checkAdmin(self) if not is_valid_address(newAdmin) then return error("newAdmin is not valid address") end if newAdmin == self.storage.admin then return error("new admin is same as old") end self.storage.admin = newAdmin emit ChangeAdmin(newAdmin) return "OK" end function M:on_deposit_asset(jsonArgs: string) return error("not supported deposit to proxy contract") end function M:on_deposit_asset_imp(jsonstrArgs:string) if self.storage.state ~= 'NOT_INITED' then return error("this contract inited before") end let arg = json.loads(jsonstrArgs) let addedAmount = tointeger(arg.num) let symbol = tostring(arg.symbol) if symbol ~= self.storage.symbol then return error("deposit error tokens into this contract.") end let from_address = tostring(arg.from_address) let param = tostring(arg.param) let parsed:Array<string> = totable(parse_args(param,2,"arg format error, need format:openCdc,amount or addCollateral,cdc_id")) if parsed[1] == 'openCdc' then ---warning to implement let wishedAmount = parsed[2] can_distribute(self,wishedAmount,addedAmount) let cdc_info = {} cdc_info['owner'] = from_address cdc_info['collateralAmount'] = addedAmount cdc_info['stableTokenAmount'] = tointeger(wishedAmount) cdc_info['secSinceEpoch'] = tointeger(get_chain_now() or 0) let cdc_id = tostring('12213434') fast_map_set("cdc",cdc_id,json.dumps(cdc_info)) cdc_info['cdcId'] = cdc_id mint(self,from_address,wishedAmount) emit OpenCdc(json.dumps(cdc_info)) return cdc_id end if parsed[1] == 'addCollateral' then let cdc_id = tostring(parsed[2]) let cdc_info_obj = fast_map_get("cdc",cdc_id) if cdc_info_obj == nil then return error("cdc not exist , cdc_id:"..cdc_id) end let cdc_info = totable(json.loads(tostring(cdc_info_obj))) if from_address ~= cdc_info['owner'] then return error("only owner can do this operition") end cdc_info['collateralAmount'] = tointeger(cdc_info['collateralAmount']) + addedAmount fast_map_set("cdc",cdc_id,json.dumps(cdc_info)) emit AddCollateral(json.dumps({cdc_id:cdc_id,addAmount:addedAmount})) return "OK"---need emit end end function M:expandLoan(args:string) end return M
-- Copyright 2022 philh30 -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local log = require('log') local utilities = {} --------------------------------------- -- Parses string inputstr using sep as delimeter, returns a table of results function utilities.splitString(inputstr, sep) if sep == nil then sep = "%s" end local t={} for str in string.gmatch(inputstr, "([^"..sep.."]+)") do table.insert(t, str) end return t end --------------------------------------- -- Iterate through and log.debug all levels of a table. Pass ' ' to function as tab function utilities.disptable(table, tab) for key, value in pairs(table) do log.debug (tab .. key, value) if type(value) == 'table' then utilities.disptable(value, ' ' .. tab) end end end --------------------------------------- -- Pad a string with blank space to n characters function utilities.pad(str, n) if #str < n then for x=#str,n,1 do str = str .. ' ' end end return str end --------------------------------------- -- Returns x if it is between min and max, otherwise returns nil function utilities.isBetween(x,min,max) x = tonumber(x) if x and (x >= min) and (x <= max) then return x else return nil end end --------------------------------------- -- Validates a passed time is not nil and in the range of 00:00-23:59 function utilities.validateTime(hour,minute) hour = utilities.isBetween(hour,0,23) minute = utilities.isBetween(minute,0,59) if hour and minute then return hour,minute else return nil end end --------------------------------------- -- Parses string in format of '00:00-00:00' function utilities.splitTime(inputstr) local times = { inputstr:match('(%d+):(%d+)-(%d+):(%d+)') } local start = {utilities.validateTime(times[1],times[2])} local stop = {utilities.validateTime(times[3],times[4])} if start[1] and start[2] and stop[1] and stop[2] then return start[1],start[2],stop[1],stop[2] end return nil end return utilities
-- -- C'Thun Key Bind - World of Warcraft Add'On for key binding. -- Author: Alexander Iglin ([email protected]) -- SlashCmdList["CTHUN"] = function(msg) ProcessInput(msg) end SLASH_CTHUN1 = "/cthun" local EventFrame = CreateFrame("Frame") EventFrame:RegisterEvent("PLAYER_LOGIN") EventFrame:SetScript("OnEvent", function(_, _, _) PrintChatMessage("Hi, ".. UnitName("Player").. "! You can type \"/cthun\" to start binding abilities and items on keys.") end) function ProcessInput(msg) --DEFAULT_CHAT_FRAME:AddMessage("You've entered: ".. msg) if msg then msg = trim(msg) if msg == "" or string.upper(msg) == "HELP" or string.upper(msg) == "USAGE" or string.upper(msg) == "H" then PrintHelp() return 0 end local words = {} for word in msg:gmatch("%w+") do -- for word in msg:gmatch("%S+") do --PrintChatMessage("Word: ".. word) table.insert(words, word) end local action_type if (words[2] == "Hspell") then action_type = "SPELL" elseif (words[2] == "Hitem") then action_type = "ITEM" else PrintChatMessage("Incorrect command: you can only bind key to a spell or item!") return 1 end local key = strupper(words[table.getn(words)]) local spell_or_item_id = tonumber(words[3]) SaveKeyBinding(action_type, spell_or_item_id, key) return 0 else PrintHelp() end end function PrintHelp() PrintChatMessage("To bind spell or item on a specific key, print in chat: ") PrintChatMessage("/cthun [spell or item linked via Shift key] KEY") PrintChatMessage("Example (binding 'Solar Wrath' spell to the key 'E'):") local link = GetSpellLink(190984) PrintChatMessage("/cthun ".. link.. " E") end function SaveKeyBinding(action_type, spell_or_item_id, key) --PrintChatMessage("action_type=".. action_type) --PrintChatMessage("spell or item id=".. spell_or_item_id) --PrintChatMessage("key=".. key) local ok if (action_type == "SPELL") then -- local spellName, spellSubName = GetSpellBookItemName(spell_or_item_id, BOOKTYPE_SPELL) local spellName, rank, icon, castTime, minRange, maxRange, spellId = GetSpellInfo(spell_or_item_id) --DEFAULT_CHAT_FRAME:AddMessage("spellName=".. spellName) -- ok = SetBinding(key, action_type + " " + spellName); ok = SetBindingSpell(key, spellName); else local itemName, itemLink, itemRarity, itemLevel, itemMinLevel, itemType, itemSubType, itemStackCount, itemEquipLoc, itemIcon, itemSellPrice, itemClassID, itemSubClassID, bindType, expacID, itemSetID, isCraftingReagent = GetItemInfo(spell_or_item_id) --DEFAULT_CHAT_FRAME:AddMessage("itemName=".. itemName) -- ok = SetBinding(key, action_type + " " + itemName); ok = SetBindingItem(key, itemName); end if (ok == 1) then PrintChatMessage("Binding failed, please, check your command!") else UpdateActionBars(spell_or_item_id, key) SaveBindings(2) -- 2 for CHARACTER_BINDINGS, 1 for ACCOUNT_BINDINGS PrintChatMessage("Binded successfully!") end end function UpdateActionBars(spell_or_item_id, key) --local bars={"Action","MultiBarBottomLeft","MultiBarBottomRight","MultiBarLeft","MultiBarRight"} local bars={"MultiBarBottomLeft","MultiBarBottomRight","MultiBarLeft","MultiBarRight"} for bar=1,#bars do for button=1,12 do local buttonName = bars[bar].."Button"..button if (GetActionInfo(_G[buttonName].action)) then local _, id, _ = GetActionInfo(_G[buttonName].action) if id == spell_or_item_id then --PrintChatMessage("Found item with id ".. id.. " in button ".. buttonName) local ok = SetBindingClick(key, buttonName); end end end end end function PrintChatMessage(msg) DEFAULT_CHAT_FRAME:AddMessage("[C'Thun]: ".. msg, 255/255, 0/255, 255/255) end --function ListBars() -- local bars={"Action","MultiBarBottomLeft","MultiBarBottomRight","MultiBarLeft","MultiBarRight"} -- for bar=1,#bars do -- for button=1,12 do -- local buttonName = bars[bar].."Button"..button -- print(buttonName,"contains",GetActionInfo(_G[buttonName].action)) -- end -- end --end -- --function ReportActionButtons() -- local lActionSlot = 0; -- for lActionSlot = 1, 120 do -- local lActionText = GetActionText(lActionSlot); -- local lActionTexture = GetActionTexture(lActionSlot); -- if lActionTexture then -- local lMessage = "Slot " .. lActionSlot .. ": [" .. lActionTexture .. "]"; -- if lActionText then -- lMessage = lMessage .. " \"" .. lActionText .. "\""; -- end -- DEFAULT_CHAT_FRAME:AddMessage(lMessage); -- end -- end --end function trim(s) return string.gsub(s, "^%s*(.-)%s*$", "%1") end --local EventFrame = CreateFrame("Frame") --EventFrame:RegisterEvent("PLAYER_LOGIN") --EventFrame:SetScript("OnEvent", function(self,event,...) -- if type(CharacterVar) ~= "number" then -- CharacterVar = 1 -- ChatFrame1:AddMessage('WhyHelloThar '.. UnitName("Player")..". I do believe this is the first time we've met. Nice to meet you!") -- else -- if CharacterVar == 1 then -- ChatFrame1:AddMessage('WhyHelloThar '.. UnitName("Player")..". How nice to see you again. I do believe I've seen you " .. CharacterVar .. " time before.") -- else -- ChatFrame1:AddMessage('WhyHelloThar '.. UnitName("Player")..". How nice to see you again. I do believe I've seen you " .. CharacterVar .. " times before.") -- end -- CharacterVar = CharacterVar + 1 -- end --end)
WEPS = {} function WEPS.TypeForWeapon(class) local tbl = util.WeaponForClass(class) return tbl and tbl.Kind or WEAPON_NONE end -- You'd expect this to go on the weapon entity, but we need to be able to call -- it on a swep table as well. function WEPS.IsEquipment(wep) return wep.Kind and wep.Kind >= WEAPON_EQUIP end function WEPS.GetClass(wep) if istable(wep) then return wep.ClassName or wep.Classname elseif IsValid(wep) then return wep:GetClass() end end function WEPS.DisguiseToggle(ply) if IsValid(ply) and ply:HasEquipmentItem(EQUIP_DISGUISE) then if not ply:GetNWBool("disguised", false) then RunConsoleCommand("ttt_set_disguise", "1") else RunConsoleCommand("ttt_set_disguise", "0") end end end WEPS.BuyableWeapons = { } WEPS.ExcludeWeapons = { } WEPS.BypassRandomWeapons = { } function WEPS.PrepWeaponsLists(role) -- Initialize the lists for this role if not WEPS.BuyableWeapons[role] then WEPS.BuyableWeapons[role] = {} end if not WEPS.ExcludeWeapons[role] then WEPS.ExcludeWeapons[role] = {} end if not WEPS.BypassRandomWeapons[role] then WEPS.BypassRandomWeapons[role] = {} end end local DoesRoleHaveWeaponCache = { } function WEPS.ResetRoleWeaponCache() for id, _ in pairs(ROLE_STRINGS) do DoesRoleHaveWeaponCache[id] = nil end end function WEPS.DoesRoleHaveWeapon(role) if type(DoesRoleHaveWeaponCache[role]) ~= "boolean" then DoesRoleHaveWeaponCache[role] = nil end if DoesRoleHaveWeaponCache[role] ~= nil then return DoesRoleHaveWeaponCache[role] end if WEPS.BuyableWeapons[role] ~= nil and table.Count(WEPS.BuyableWeapons[role]) > 0 then DoesRoleHaveWeaponCache[role] = true return true end for _, w in ipairs(weapons.GetList()) do if w and w.CanBuy and table.HasValue(w.CanBuy, role) then DoesRoleHaveWeaponCache[role] = true return true end end DoesRoleHaveWeaponCache[role] = false return false end
local IO = require "kong.tools.io" local TEST_FILE = "/tmp/test_file" describe("IO", function() before_each(function() os.remove(TEST_FILE) end) it("should detect existing commands", function() assert.truthy(IO.cmd_exists("hash")) assert.falsy(IO.cmd_exists("hashasdasd")) end) it("should write and read from files", function() assert.truthy(IO.write_to_file(TEST_FILE, "this is a test")) assert.are.same("this is a test", IO.read_file(TEST_FILE)) end) it("should detect existing files", function() assert.falsy(IO.file_exists(TEST_FILE)) IO.write_to_file(TEST_FILE, "Test") assert.truthy(IO.cmd_exists(TEST_FILE)) end) it("should execute an OS command", function() local res, code = IO.os_execute("echo \"Hello\"") assert.are.same(0, code) assert.truthy("Hello", res) local res, code = IO.os_execute("LC_ALL=\"C\";asdasda \"Hello\"") assert.are.same(127, code) assert.are.same("asdasda: command not found", res) end) end)
-- Invector, License MIT, Author Jordach -- Fake third person but works like third person local default_eye_offset = vector.new(0,0,0) local ground_eye_offset = vector.new(0,1.7,-30) local ground_eye_offset_3r = vector.new(0,-10,0) local player_relative = vector.new(0,0,0) local player_rot = vector.new(0,0,0) -- Update rate, don't touch me local tick_speed = 0.03 -- Bone rotation things; local kart_root_pos = vector.new(0,0,0) local kart_root_rot = vector.new(0,0,0) -- Particle effect things local rear_left_tyre_pos_min = vector.new(-0.55,0.1,-0.7) local rear_left_tyre_pos_max = vector.new(-0.4,0.2,-0.7) local rear_right_tyre_pos_min = vector.new(0.4,0.1,-0.7) local rear_right_tyre_pos_max = vector.new(0.55,0.2,-0.7) local rear_left_exhaust_pos_min = vector.new(-0.35,0.65,-1.05) local rear_left_exhaust_pos_max = vector.new(-0.4, 0.65,-1.05) local rear_right_exhaust_pos_min = vector.new(0.35, 0.65,-1.05) local rear_right_exhaust_pos_max = vector.new(0.4, 0.65,-1.05) -- Handling specs local turning_radius = 0.0472665 local drifting_radius = turning_radius * 1.75 local drifting_radius_lesser = drifting_radius * 0.5 local drifting_radius_greater = drifting_radius * 1.5 local reverse_radius = 0.0204533 -- Speed specs local max_speed_boost = 13 local max_speed_norm = 7 local forwards_accel = 3 local reverse_accel = -0.55 local braking_factor = 0.75 -- Friction settings local friction_track = 0.92 local friction_off_track = 0.50 local friction_air = 0 -- Drift time needed to boost local small_drift_time = 1 local med_drift_time = 2 local big_drift_time = 3 -- Boost specs local small_boost_time = 0.25 local med_boost_time = 0.5 local big_boost_time = 1.25 -- Empty controls local controls = { up = false, down = false, left = false, right = false, jump = false, aux1 = false, sneak = false, LMB = false, RMB = false, } local drift_particle_def = { amount = 50, vertical = false, collisiondetection = false, minexptime = 0.25, maxexptime = 0.5, glow = 14 } local exhaust_particle_def = { amount = 50, vertical = false, collisiondetection = false, minexptime = 0.15, maxexptime = 0.35 } local nanite_particle_def = { amount = 1000, time = 10, vertical = false, collisiondetection = false, glow = 14, minexptime = 0.5, maxexptime = 0.9, minvel = vector.new(0,1,0), maxvel = vector.new(0,1.5,0), minpos = vector.new(-0.5, 0, -0.5), maxpos = vector.new(0.5, 0.8, 0.5), minsize = 3, maxsize = 6, texture = "invector_ui_nanite_boosters.png" } local kart = { visual = "mesh", mesh = "default_kart.b3d", use_texture_alpha = true, backface_culling = false, makes_footstep_sound = false, textures = { "blue_kart_neo.png", "blue_skin.png", "transparent.png", "transparent.png" }, visual_size = {x=1, y=1}, collisionbox = {-0.61, 0.0, -0.61, 0.61, 1.4, 0.61}, physical = true, collide_with_objects = true, pointable = false, stepheight = 0.5/16, -- Custom fields: _attached_player = nil, _timer = 0, _boost_timer = 0, _ai_timer = 0, _drift_timer = 0, _stun_timer = 0, _immune_timer = 0, _collision_timer = 0, _collision_mod = vector.new(0,0,0), _dvel = 0, _is_drifting = 0, -- 1 = left, -1 = right _drift_level = 0, -- 0 = not drifting, 1 = small, 2 = medium, 3 = big / infinite _boost_type = 0, -- 0 = regular smoke, 1 = small boost, 2 = medium boost, 3 = big boost/boost pad _is_kart = true, -- Useful for homing weapons or AOE weapons _is_creative = minetest.settings:get_bool("creative_mode"), -- Set DURING INIT _is_ai = false, _position = -1, -- Set at race start and during a race _racer_id = -1, -- Set on race start since it's likely singleplayer. _ai_reaction_timing = {min = 2, max = 25}, -- divided by 10 due to math.random() shenanigans _ai_reaction_time = 0, _ai_button_press_success = 35, -- Any number rolled lower than X is considered a failure _ai_last_waypoint = -1, _ai_dist_rand = math.random(1, 250) / 100, _track_sector = 1, -- Lap / track sector for non circuits _waypoint = 0, -- Similar purpose to _position _held_item = 0, _shields = false, -- Can take an extra hit without being stunned, can be bypassed by certain weapons _last_control = table.copy(controls), -- Memorises the last held button for AI to not make things go wrong -- Particle ID holders _rear_left_tyre_spawner = nil, _rear_right_tyre_spawner = nil, _exhaust_left_spawner = nil, _exhaust_right_spawner = nil, _deo = default_eye_offset, _geo = ground_eye_offset, _geo3r = ground_eye_offset_3r, _prel = player_relative, _prot = player_rot } -- Things like rockets, missiles, ION Cannon function kart:spawn_item_forwards() local ent local pos = self.object:get_pos() local yaw = self.object:get_yaw() local vel = self.object:get_velocity() local xm, zm = solarsail.util.functions.yaw_to_vec(yaw, 1) local spawn_pos = vector.add(pos, {x=xm*2, y=1.25, z=zm*2}) local spawn_vel = vector.add(vel, vector.new(xm*15, 0, zm*15)) if self._held_item == 3 then ent = minetest.add_entity(spawn_pos, "invector:item_rocket") local particle = table.copy(invector.items.rocket_particle_trail) particle.attached = ent minetest.add_particlespawner(particle) ent:set_velocity(spawn_vel) elseif self._held_item == 4 then --ent = minetest.add_entity(spawn_pos, "invector:item_missile") --local particle = table.copy(invector.items.rocket_particle_trail) --particle.attached = ent --minetest.add_particlespawner(particle) --ent:set_velocity(spawn_vel) elseif self._held_item == 6 then --ent = minetest.add_entity(spawn_pos, "invector:item_ion_cannon") --ent:set_velocity(spawn_vel) end ent:set_yaw(yaw) end function kart:spawn_item_backwards() local ent local pos = self.object:get_pos() local yaw = self.object:get_yaw() local vel = self.object:get_velocity() local xm, zm = solarsail.util.functions.yaw_to_vec(yaw, 1) local spawn_pos = vector.add(pos, {x=-xm*2, y=1.25, z=-zm*2}) local spawn_vel = vector.add(vel, vector.new(xm*-15, 0, zm*-15)) if self._held_item == 3 then ent = minetest.add_entity(spawn_pos, "invector:item_rocket") local particle = table.copy(invector.items.rocket_particle_trail) particle.attached = ent minetest.add_particlespawner(particle) ent:set_velocity(spawn_vel) elseif self._held_item == 4 then --ent = minetest.add_entity(spawn_pos, "invector:item_missile") --local particle = table.copy(invector.items.rocket_particle_trail) --particle.attached = ent --minetest.add_particlespawner(particle) --ent:set_velocity(spawn_vel) elseif self._held_item == 6 then --ent = minetest.add_entity(spawn_pos, "invector:item_ion_cannon") --ent:set_velocity(spawn_vel) end ent:set_yaw(yaw + 3.142) end -- Things like sand, TNT, PTNT, mese shards etc function kart:throw_item_forwards() local ent local pos = self.object:get_pos() local yaw = self.object:get_yaw() local vel = self.object:get_velocity() local xm, zm = solarsail.util.functions.yaw_to_vec(yaw, 1) local spawn_pos = vector.add(pos, {x=xm*2, y=0.35, z=zm*2}) local throw_vel = vector.add(vel, {x=xm*7.2, y=8, z=zm*7.2}) if self._held_item == 1 then ent = minetest.add_entity(spawn_pos, "invector:item_tnt") elseif self._held_item == 2 then ent = minetest.add_entity(spawn_pos, "invector:item_ptnt") elseif self._held_item == 7 then ent = minetest.add_entity(spawn_pos, "invector:item_sand") elseif self._held_item == 9 then --ent = minetest.add_entity(spawn_pos, "invector:item_mese_shards") end ent:set_acceleration(vector.new(0, -9.71, 0)) ent:set_velocity(throw_vel) end function kart:drop_item_backwards() local ent local pos = self.object:get_pos() local yaw = self.object:get_yaw() local vel = self.object:get_velocity() local xm, zm = solarsail.util.functions.yaw_to_vec(yaw, 1) local spawn_pos = vector.add(pos, {x=-xm*2, y=0.35, z=-zm*2}) local throw_vel = vector.add(vel, {x=0, y=1, z=0}) if self._held_item == 1 then ent = minetest.add_entity(spawn_pos, "invector:item_tnt") elseif self._held_item == 2 then ent = minetest.add_entity(spawn_pos, "invector:item_ptnt") elseif self._held_item == 7 then ent = minetest.add_entity(spawn_pos, "invector:item_sand") elseif self._held_item == 9 then --ent = minetest.add_entity(spawn_pos, "invector:item_mese_shards") end ent:set_velocity(throw_vel) ent:set_acceleration(vector.new(0, -9.71, 0)) end function kart:clear_boost() self._is_drifting = 0 self._drift_timer = 0 self._boost_type = 0 self._boost_timer = 0 end function kart:on_step(dtime, moveresult) if not invector.game_started and not self._is_creative then return end -- Avoid the kart logic over or underscaling things due to framerate variability. local tick_scaling = solarsail.util.functions.remap(dtime, tick_speed/4, tick_speed*4, 0.25, 4) local ratio_tick = solarsail.util.functions.remap(tick_scaling, 0.25, 4, 0, 1) -- Add kart stun if self._stun_timer > 0 then self._stun_timer = self._stun_timer - dtime end -- Nanite Regeneration if self._immune_timer > 0 then self._immune_timer = self._immune_timer - dtime end -- Impulse from other karts if self._collision_timer > 0 then self._collision_timer = self._collision_timer - dtime else -- Clear the vector self._collision_timer = 0 self._collision_mod = vector.new(0,0,0) end -- Tick down the level of boost until it completes if self._boost_timer > 0 then self._boost_timer = self._boost_timer - dtime elseif self._boost_type > 0 then self._boost_type = 0 end local velocity = self.object:get_velocity() local rotation = self.object:get_yaw() local cam_rot_offset = 0 local yaw_offset = 0 local kart_rot_offsets = vector.new(0,0,0) local xv, zv -- Animation and camera handler: local frange, fspeed, fblend, floop = self.object:get_animation() local new_frames = {x=0, y=0} -- Identify the node under the kart for physics and boost/item detection local kart_phys_pos = self.object:get_pos() local kart_node_pos = table.copy(kart_phys_pos) kart_node_pos.y = kart_node_pos.y - 0.5 local node_detector = Raycast(kart_phys_pos, kart_node_pos, false, false) local node_pos if node_detector == nil then else for pointed in node_detector do if pointed.type == "node" then node_pos = table.copy(pointed.under) break end end end local node_data, node if node_pos ~= nil then node_data = minetest.get_node_or_nil(node_pos) node = minetest.registered_nodes[node_data.name] end for k, coll in pairs(moveresult.collisions) do if coll.type == "object" then local ent_lua = coll.object:get_luaentity() if ent_lua._is_kart ~= nil then if ent_lua._raceri_id ~= self._racer_id then local nx, nz = solarsail.util.functions.yaw_to_vec(rotation, self._dvel*0.75) local kart_forwards = vector.new(nx, 0, nz) ent_lua._collision_timer = 1 ent_lua._collision_mod = vector.add( kart_forwards, vector.subtract( vector.multiply(coll.old_velocity, 0.5), vector.multiply(coll.new_velocity, 0.5) ) ) self._dvel = 0 --break end end end end -- Handle boost, item, jump, and waypoints if node_data ~= nil then -- Handle the start/finish line first, then handle waypoints if node.groups.sector ~= nil then if invector.tracks[invector.current_track] == nil then elseif invector.tracks[invector.current_track].track_num_waypoints == self._waypoint then self._waypoint = 0 self._track_sector = self._track_sector + 1 invector.racers[self._racer_id].sector = self._track_sector invector.racers[self._racer_id].waypoint = self._waypoint print("lap: " .. self._track_sector) print("waypoint: " .. 0) self._ai_dist_rand = math.random(1, 250) / 100 end elseif node.groups.waypoint ~= nil then if node.groups.waypoint == self._waypoint + 1 then self._waypoint = 0 + node.groups.waypoint invector.racers[self._racer_id].waypoint = self._waypoint print("waypoint: " .. node.groups.waypoint) self._ai_dist_rand = math.random(1, 250) / 100 end end if node.groups.booster ~= nil then if self._boost_timer <= 0 then if node.groups.booster == 1 then minetest.sound_play("boost_pad_small", {object=self.object, max_hear_distance=8}, true) elseif node.groups.booster == 2 then minetest.sound_play("boost_pad_big", {object=self.object, max_hear_distance=8}, true) end end self._boost_timer = node.groups.booster self._boost_type = 3 end if node.groups.jump ~= nil then if moveresult.touching_ground then velocity.y = node.groups.jump end end if node.groups.item ~= nil then if self._held_item == 0 then self._held_item = invector.items.give_item(self.object) local textures = self.object:get_properties().textures textures[4] = invector.items.id_to_textures[self._held_item] self.object:set_properties({textures = textures}) if self._attached_player ~= nil then minetest.sound_play("item_voice_"..self._held_item, {to_player=self._attached_player:get_player_name(), gain=0.8}) end minetest.swap_node(node_pos, {name=node._swap_to}) minetest.sound_play("item_pickup", {object=self.object, max_hear_distance=8}, true) local timer = minetest.get_node_timer(node_pos) timer:start(invector.items.pad_timer) end end end -- Handle node frictive types here; -- Handle friction on ground if moveresult.touching_ground then local frictive = 0 if node == nil then frictive = friction_off_track elseif node.groups == nil then frictive = friction_off_track elseif node.groups.track == nil then frictive = friction_off_track else frictive = friction_track end self._dvel = solarsail.util.functions.lerp(self._dvel, self._dvel * (frictive * tick_speed), ratio_tick) else -- In air end -- Round down numbers when percentages exponentialise movement: if self._dvel > 0 and self._dvel < 0.05 then self._dvel = 0 elseif self._dvel < 0 and self._dvel > -0.05 then self._dvel = 0 end -- Handle controls for players and AI local control = controls if self._attached_player ~= nil then control = solarsail.controls.player[self._attached_player:get_player_name()] self._last_control = control elseif self._is_ai and self._ai_timer >= self._ai_reaction_time then local new_control, new_reaction_time = invector.ai.think(self) control = new_control self._last_control = new_control self._ai_timer = 0 self._ai_reaction_time = new_reaction_time elseif self._is_ai then control = self._last_control self._ai_timer = self._ai_timer + dtime end if self._stun_timer <= 0 then -- Handle controls; -- Accel braking; if control.up or self._forced_boost then local boost_multi = 1 if self._boost_timer > 0 then boost_multi = 3 elseif node == nil then boost_multi = 0.15 elseif node.groups == nil then boost_multi = 0.15 elseif node.groups.track == nil then boost_multi = 0.15 end self._dvel = self._dvel + ((forwards_accel * boost_multi) * tick_scaling) elseif control.down then -- Reversing local racc_div = 1 -- Make braking half as effective compared to reversing if self._dvel > 0 then racc_div = 2 end self._dvel = self._dvel + ((reverse_accel/racc_div) * tick_scaling) end -- Drifting, turning, do not turn when airborne; if velocity.y ~= 0 then elseif control.jump and self._dvel > 5.5 then -- Direction of drifting if self._is_drifting == 0 then if control.left then self._is_drifting = 1 elseif control.right then self._is_drifting = -1 end else -- Increment timer for boost self._drift_timer = self._drift_timer + dtime -- Drift steering if control.left then if self._is_drifting == 1 then --Left yaw_offset = drifting_radius_greater * tick_scaling elseif self._is_drifting == -1 then yaw_offset = -drifting_radius_lesser * tick_scaling end elseif control.right then if self._is_drifting == 1 then --Left adds, right removes yaw_offset = drifting_radius_lesser * tick_scaling elseif self._is_drifting == -1 then yaw_offset = -drifting_radius_greater * tick_scaling end else if self._is_drifting == 1 then --Left yaw_offset = drifting_radius * tick_scaling elseif self._is_drifting == -1 then yaw_offset = -drifting_radius * tick_scaling end end end elseif control.left then -- Fowards if self._dvel > 0.25 then yaw_offset = turning_radius * tick_scaling -- Reversing elseif self._dvel < -0.1 then yaw_offset = -reverse_radius * tick_scaling end elseif control.right then -- Fowards if self._dvel > 0.5 then yaw_offset = -turning_radius * tick_scaling -- Reversing elseif self._dvel < -0.1 then yaw_offset = reverse_radius * tick_scaling end end -- Give the boost if not control.jump and self._boost_timer <= 0 then self._is_drifting = 0 -- Maximum boost if self._drift_timer >= big_drift_time then self._boost_timer = big_boost_time self._boost_type = 3 self._drift_timer = 0 minetest.sound_play("drift_boost_big", {object=self.object, max_hear_distance=8}, true) -- Medium boost elseif self._drift_timer >= med_drift_time then self._boost_timer = med_boost_time self._boost_type = 2 self._drift_timer = 0 minetest.sound_play("drift_boost_med", {object=self.object, max_hear_distance=8}, true) -- Small boost elseif self._drift_timer >= small_drift_time then self._boost_timer = small_boost_time self._boost_type = 1 self._drift_timer = 0 minetest.sound_play("drift_boost_small", {object=self.object, max_hear_distance=8}, true) end end -- Do not give a boost if falling under the drifting speed or while in air if self._dvel <= 5 or velocity.y ~= 0 then if self._is_drifting ~= 0 then self:clear_boost() end end -- Use Item/Item Alt mode; usually in the form of throw forwards or backwards if control.LMB and self._held_item > 0 then if self._held_item == 1 or self._held_item == 2 then -- TNT family self:drop_item_backwards() elseif self._held_item == 3 or self._held_item == 4 then -- Rocket Family self:spawn_item_forwards() elseif self._held_item == 5 then -- Shield if not self._shields then self._shields = true local textures = self.object:get_properties().textures textures[3] = "invector_kart_shield.png" self.object:set_properties({textures=textures}) end elseif self._held_item == 6 then -- Ion Cannon self:spawn_item_forwards() elseif self._held_item == 7 then -- Sand self:drop_item_backwards() elseif self._held_item == 8 then -- Mese Crystal self._boost_timer = 2 self._boost_type = 3 minetest.sound_play("boost_pad_big", {object=self.object, max_hear_distance=8}, true) elseif self._held_item == 9 then -- Mese Shards elseif self._held_item == 10 then -- Nanites local particles = table.copy(nanite_particle_def) particles.attached = self.object minetest.add_particlespawner(particles) self._boost_timer = 10 self._boost_type = 3 self._immune_timer = 10 end self._held_item = 0 local textures = self.object:get_properties().textures textures[4] = "transparent.png" self.object:set_properties({textures = textures}) elseif control.RMB and self._held_item > 0 then if self._held_item == 1 or self._held_item == 2 then self:throw_item_forwards() elseif self._held_item == 3 or self._held_item == 4 then -- Rocket Family self:spawn_item_backwards() elseif self._held_item == 5 then -- Shield if not self._shields then self._shields = true local textures = self.object:get_properties().textures textures[3] = "invector_kart_shield.png" self.object:set_properties({textures=textures}) end elseif self._held_item == 6 then -- Ion Cannon self:spawn_item_backwards() elseif self._held_item == 7 then -- Sand self:throw_item_forwards() elseif self._held_item == 8 then -- Mese Crystal self._boost_timer = 2 self._boost_type = 3 minetest.sound_play("boost_pad_big", {object=self.object, max_hear_distance=8}, true) elseif self._held_item == 9 then -- Mese Shards elseif self._held_item == 10 then -- Nanites local particles = table.copy(nanite_particle_def) particles.attached = self.object minetest.add_particlespawner(particles) self._boost_timer = 10 self._boost_type = 3 self._immune_timer = 10 end self._held_item = 0 local textures = self.object:get_properties().textures textures[4] = "transparent.png" self.object:set_properties({textures = textures}) end -- Animation frames while driving. if control.up then if control.left then new_frames.x = 60 new_frames.y = 79 elseif control.right then new_frames.x = 120 new_frames.y = 139 else new_frames.x = 0 new_frames.y = 19 end elseif control.down then -- Reversing if self._dvel > 0.5 then if control.left then new_frames.x = 60 new_frames.y = 79 elseif control.right then new_frames.x = 120 new_frames.y = 139 else new_frames.x = 0 new_frames.y = 19 end elseif self._dvel < -0.5 then if control.left then new_frames.x = 90 new_frames.y = 109 elseif control.right then new_frames.x = 150 new_frames.y = 169 else new_frames.x = 30 new_frames.y = 49 end end else -- Coming to a stop or idle if self._dvel > 0.5 then if control.left then new_frames.x = 60 new_frames.y = 79 elseif control.right then new_frames.x = 120 new_frames.y = 139 else new_frames.x = 0 new_frames.y = 19 end elseif self._dvel < -0.5 then if control.left then new_frames.x = 90 new_frames.y = 109 elseif control.right then new_frames.x = 150 new_frames.y = 169 else new_frames.x = 30 new_frames.y = 49 end else -- Idle if control.left then new_frames.x = 79 new_frames.y = 79 elseif control.right then new_frames.x = 139 new_frames.y = 139 else new_frames.x = 19 new_frames.y = 19 end end end xv, zv = solarsail.util.functions.yaw_to_vec(rotation+yaw_offset, self._dvel) local new_vel = vector.new(xv, 0, zv) new_vel = vector.normalize(new_vel) new_vel.y = velocity.y -- Particlespawner handler -- Exhausts; local exhaust_particle = table.copy(exhaust_particle_def) exhaust_particle.attached = self.object exhaust_particle.minvel = vector.new(-0.05, 0.5, -0.25) exhaust_particle.maxvel = vector.new(-0.15, 1.2, -0.5) exhaust_particle.minpos = rear_left_exhaust_pos_min exhaust_particle.maxpos = rear_left_exhaust_pos_max if self._boost_type == 0 and self._exhaust_left_spawner == nil then exhaust_particle.time = 0 exhaust_particle.glow = 0 exhaust_particle.node = {name = "invector:smoke_node"} exhaust_particle.minsize = 1 exhaust_particle.maxsize = 1.15 self._exhaust_left_spawner = minetest.add_particlespawner(exhaust_particle) exhaust_particle.minpos = rear_right_exhaust_pos_min exhaust_particle.maxpos = rear_right_exhaust_pos_max exhaust_particle.minvel.x = 0.05 exhaust_particle.maxvel.x = 0.15 self._exhaust_right_spawner = minetest.add_particlespawner(exhaust_particle) elseif self._boost_type == 1 then exhaust_particle.time = self._boost_timer exhaust_particle.glow = 14 exhaust_particle.node = {name = "invector:boost_1_node"} exhaust_particle.minsize = 1.15 exhaust_particle.maxsize = 1.4 minetest.add_particlespawner(exhaust_particle) exhaust_particle.minpos = rear_right_exhaust_pos_min exhaust_particle.maxpos = rear_right_exhaust_pos_max exhaust_particle.minvel.x = 0.05 exhaust_particle.maxvel.x = 0.15 minetest.add_particlespawner(exhaust_particle) elseif self._boost_type == 2 then exhaust_particle.time = self._boost_timer exhaust_particle.glow = 14 exhaust_particle.node = {name = "invector:boost_2_node"} exhaust_particle.minsize = 1.4 exhaust_particle.maxsize = 1.65 minetest.add_particlespawner(exhaust_particle) exhaust_particle.minpos = rear_right_exhaust_pos_min exhaust_particle.maxpos = rear_right_exhaust_pos_max exhaust_particle.minvel.x = 0.05 exhaust_particle.maxvel.x = 0.15 minetest.add_particlespawner(exhaust_particle) elseif self._boost_type == 3 then exhaust_particle.time = self._boost_timer exhaust_particle.glow = 14 exhaust_particle.node = {name = "invector:boost_3_node"} exhaust_particle.minsize = 1.65 exhaust_particle.maxsize = 1.95 minetest.add_particlespawner(exhaust_particle) exhaust_particle.minpos = rear_right_exhaust_pos_min exhaust_particle.maxpos = rear_right_exhaust_pos_max exhaust_particle.minvel.x = 0.05 exhaust_particle.maxvel.x = 0.15 minetest.add_particlespawner(exhaust_particle) end -- Rear Tyres; local drift_particle = table.copy(drift_particle_def) drift_particle.attached = self.object drift_particle.minvel = vector.new(-new_vel.x/2, (-new_vel.y/2)+0.5, -new_vel.z/2) drift_particle.maxvel = vector.new(-new_vel.x, (-new_vel.y)+0.75, -new_vel.z) if self._drift_timer >= big_drift_time then if self._drift_level == 2 then minetest.sound_play("drift_spark_big", {object=self.object, max_hear_distance=8}, true) self._drift_level = 3 drift_particle.time = 0 drift_particle.texture = "invector_drift_big.png" drift_particle.minsize = 3 drift_particle.maxsize = 4 drift_particle.minpos = rear_left_tyre_pos_min drift_particle.maxpos = rear_left_tyre_pos_max self._rear_left_tyre_spawner = minetest.add_particlespawner(drift_particle) drift_particle.minpos = rear_right_tyre_pos_min drift_particle.maxpos = rear_right_tyre_pos_max self._rear_right_tyre_spawner = minetest.add_particlespawner(drift_particle) end elseif self._drift_timer >= med_drift_time and self._drift_level == 1 then minetest.sound_play("drift_spark_med", {object=self.object, max_hear_distance=8}, true) self._drift_level = 2 drift_particle.time = 1.35 drift_particle.texture = "invector_drift_medium.png" drift_particle.minsize = 2 drift_particle.maxsize = 3 drift_particle.minpos = rear_left_tyre_pos_min drift_particle.maxpos = rear_left_tyre_pos_max minetest.add_particlespawner(drift_particle) drift_particle.minpos = rear_right_tyre_pos_min drift_particle.maxpos = rear_right_tyre_pos_max minetest.add_particlespawner(drift_particle) elseif self._drift_timer >= small_drift_time and self._drift_level == 0 then minetest.sound_play("drift_spark_small", {object=self.object, max_hear_distance=8}, true) self._drift_level = 1 drift_particle.time = 1.35 drift_particle.texture = "invector_drift_small.png" drift_particle.minsize = 1 drift_particle.maxsize = 2 drift_particle.minpos = rear_left_tyre_pos_min drift_particle.maxpos = rear_left_tyre_pos_max minetest.add_particlespawner(drift_particle) drift_particle.minpos = rear_right_tyre_pos_min drift_particle.maxpos = rear_right_tyre_pos_max minetest.add_particlespawner(drift_particle) elseif self._rear_left_tyre_spawner ~= nil then -- Clear max boost particles minetest.delete_particlespawner(self._rear_left_tyre_spawner) minetest.delete_particlespawner(self._rear_right_tyre_spawner) self._rear_left_tyre_spawner = nil self._rear_right_tyre_spawner = nil self._drift_level = 0 end -- Limit velocity based on boost status if self._boost_timer > 0 then if self._dvel > max_speed_boost then self._dvel = max_speed_boost elseif self._dvel < -max_speed_boost then self._dvel = -max_speed_boost end else if self._dvel > max_speed_norm then self._dvel = max_speed_norm elseif self._dvel < -max_speed_norm then self._dvel = -max_speed_norm end end else -- Stunned animation. new_frames.x = 180 new_frames.y = 209 end -- Set camera rotation for players only if not self._last_control.sneak and self._attached_player ~= nil then if self._attached_player:get_look_vertical() ~= 0 then self._attached_player:set_look_vertical(0) end if self._attached_player:get_look_horizontal() ~= rotation+cam_rot_offset then -- Reversing camera mode if required if self._dvel < -0.5 and control.down then cam_rot_offset = 3.142 end self._attached_player:set_look_horizontal(rotation+cam_rot_offset) end end -- Set object rotation and speed, if the kart enters a stunned state; it'll slide in place if not moveresult.touching_ground then xv = nil zv = nil end if xv == nil or zv == nil then self.object:set_velocity( vector.add( velocity, vector.new( self._collision_mod.x*self._collision_timer, self._collision_mod.y*self._collision_timer, self._collision_mod.z*self._collision_timer ) ) ) else self.object:set_velocity( vector.add( {x=xv, y=velocity.y, z=zv}, vector.new( self._collision_mod.x*self._collision_timer, self._collision_mod.y*self._collision_timer, self._collision_mod.z*self._collision_timer ) ) ) end self.object:set_rotation(vector.new(kart_rot_offsets.x, rotation+yaw_offset, 0)) -- Compare against frame table to avoid re-applying the animation if frange.x ~= new_frames.x then self.object:set_animation(new_frames, 60, 0.1, true) end -- Disable regular smoke when boosting or stunned if self._boost_type > 0 and self._exhaust_left_spawner ~= nil then minetest.delete_particlespawner(self._exhaust_left_spawner) minetest.delete_particlespawner(self._exhaust_right_spawner) self._exhaust_left_spawner = nil self._exhaust_right_spawner = nil elseif self._stun_timer > 0 and self._exhaust_left_spawner ~= nil then minetest.delete_particlespawner(self._exhaust_left_spawner) minetest.delete_particlespawner(self._exhaust_right_spawner) self._exhaust_left_spawner = nil self._exhaust_right_spawner = nil end -- Allow exiting the kart while in creative mode to test changes even when stunned; if control.aux1 and self._is_creative then if self._attached_player ~= nil then self._attached_player:set_detach() self._attached_player:hud_set_flags({ crosshair = true, hotbar = true, healthbar = true, wielditem = true, breathbar = true }) self._attached_player:set_eye_offset() self._attached_player = nil self.object:remove() return end end end invector.functions.register_kart("kart", kart)
-- Copyright 2017-2018, Firaxis Games -- This file is being included into the base NotificationPanel file using the wildcard include setup in NotificationPanel.lua -- Refer to the bottom of NotificationPanel.lua to see how that's happening -- DO NOT include any NotificationPanel files here or it will cause problems --include("NotificationPanel"); -- =========================================================================== -- CACHE BASE FUNCTIONS -- =========================================================================== local BASE_RegisterHandlers = RegisterHandlers; local BASE_LateInitialize = LateInitialize; local BASE_OnDefaultAddNotification = OnDefaultAddNotification; -- =========================================================================== -- VARIABLES -- =========================================================================== -- Additional notification handlers for events not defined as part of the g_notificationHandlers object. -- Has to be an additional table due to g_notificationHandlers being an already defined havok structure. -- Indexed by notification type hash. local m_customNotifyHandlers :table = {}; -- =========================================================================== function OnDefaultAddNotification(pNotification:table) BASE_OnDefaultAddNotification(pNotification); local notificationID :number = pNotification:GetID(); local playerID :number = Game.GetLocalPlayer(); local notificationEntry :NotificationType = GetNotificationEntry( playerID, notificationID ); local turnNumber :number = Game.GetCurrentGameTurn() --Skip the war declaration notification spam at start of game if(notificationEntry.m_Instance ~= nil)then if(notificationEntry.m_TypeName == 'NotificationTypes.USER_DEFINED_9')then notificationEntry.m_Instance.Icon:SetIcon("NOTIFICATION_SPY_CHOOSE_ESCAPE_ROUTE"); end end end -- =========================================================================== -- HELPER FUNCTIONS -- =========================================================================== function DismissAll(playerID :number, notificationType :number) local notifyIDList :table = NotificationManager.GetList(playerID); if(notifyIDList ~= nil) then for _, loopNotifyID in pairs(notifyIDList) do local pNotification = NotificationManager.Find(playerID, loopNotifyID); if(pNotification ~= nil and pNotification:GetType() == notificationType) then NotificationManager.Dismiss( playerID, loopNotifyID ); end end end end function DismissByProperty(playerID :number, notificationType :number, propertyName :string, propertyValue) local notifyIDList :table = NotificationManager.GetList(playerID); if(notifyIDList ~= nil) then for _, loopNotifyID in pairs(notifyIDList) do local pNotification = NotificationManager.Find(playerID, loopNotifyID); if(pNotification ~= nil and pNotification:GetType() == notificationType) then local notifyPropValue = pNotification:GetValue(propertyName); if(notifyPropValue ~= nil and notifyPropValue == propertyValue) then NotificationManager.Dismiss( playerID, loopNotifyID ); end end end end end -- =========================================================================== -- NEW NOTIFICATION HANDLERS -- =========================================================================== function OnNewInfamousPirateActivate( notificationEntry : NotificationType ) if (notificationEntry ~= nil and notificationEntry.m_PlayerID == Game.GetLocalPlayer()) then local pNotification :table = GetActiveNotificationFromEntry(notificationEntry, notificationID); if pNotification ~= nil then local searchZoneID :number = pNotification:GetValue(g_notificationKeys.InfamousSearchZoneID); if(searchZoneID ~= nil) then local searchZones :table = Game:GetProperty(g_gamePropertyKeys.InfamousPirateSearchZones); if(searchZones ~= nil) then for loop, curZone in ipairs(searchZones) do if(curZone.ZoneID == searchZoneID and curZone.CenterPlotIndex ~= nil) then local zoneCenterPlot :object = Map.GetPlotByIndex(curZone.CenterPlotIndex); if(zoneCenterPlot ~= nil) then UI.LookAtPlot(zoneCenterPlot:GetX(), zoneCenterPlot:GetY()); end end end end end end end end -- =========================================================================== -- NEW EVENT HANDLERS -- =========================================================================== function OnNotificationAdded_Spy( playerID:number, notificationID:number ) local pAddNotification = NotificationManager.Find(playerID, notificationID); if(pAddNotification == nil) then print("Added notification missing."); return; end end -- ======================================================================================= -- Custom Espionage Handlers -- ======================================================================================= function OnCustomChooseEscapeRouteActivate( notificationEntry : NotificationType ) if (notificationEntry ~= nil and notificationEntry.m_PlayerID == Game.GetLocalPlayer()) then local pNotification :table = GetActiveNotificationFromEntry(notificationEntry, notificationID); if pNotification ~= nil then if pNotification:IsLocationValid() then local x, y = pNotification:GetLocation(); print(" OnCustomChooseEscapeRouteActivate",x,y) LuaEvents.NotificationPanel_OpenCustomEspionageEscape( x, y ); end end end end -- =========================================================================== -- BASE FUNCTION REPLACEMENTS -- =========================================================================== function RegisterHandlers() BASE_RegisterHandlers(); print("RegisterHandlers()",g_notificationHandlers) g_notificationHandlers[NotificationTypes.USER_DEFINED_9].Activate = OnCustomChooseEscapeRouteActivate; end function LateInitialize() BASE_LateInitialize(); Events.NotificationAdded.Add( OnNotificationAdded_Spy ); -- Additional and separate from the base NotificationPanel implementation. end
-- For websocket support local guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" local mime = require("mime") local sha1 = dofile(path.."sha1.lua") local clientList = {} function buffersend(client,msg) if client and clientList[client] then clientList[client].send = (clientList[client].send or "") .. msg end end function loop() repeat local client = server:accept() if client then client:settimeout(0) clientList[client] = ({ socket=client, send="", received="", open=false, }) end until not client for i,v in pairs(clientList) do local client = v if client and client.socket then --RECEIVE local data = "" repeat local c,err = client.socket:receive(1) if c then data=data .. c end if err == "closed" or #data > 4000 then --Way too massive for anyone to expect from a client! doclosed(client.socket) clientList[i] = nil break end until not c --Always check if your loops are correct. I thought "client:receive(1)" was blocking like mad! --Hacky WebSockets Support if data:sub(1,3) == "GET" and data:find("websocket") then --Client is using websocket, we need to send a handshake back! local key = data:match("Sec%-WebSocket%-Key: (%S+)") if key then local accept = mime.b64(sha1.binary(key..guid)):sub(1,-2).."=" local handshake = "HTTP/1.1 101 Switching Protocols\r\n" handshake = handshake.."Upgrade: websocket\r\n" handshake = handshake.."Connection: Upgrade\r\n" handshake = handshake.."Sec-WebSocket-Accept: "..accept.."\r\n\r\n" customsend(client.socket,handshake) client.websocket = true data = "" end end if client.websocket then local dat,opcode,masked,fin = wspayloaddecode(data) if dat then if opcode < 3 then data = dat elseif opcode == 8 then --Client wants to close doclosed(client.socket) clientList[i] = nil elseif opcode == 9 then --PING customsend(client.socket,wspayloadencode(dat,10,false,true)) --Send PONG end --print("GOT","'"..dat.."'","OPCODE: "..tostring(opcode),"Masked: "..tostring(masked),"FIN: "..tostring(fin)) end end client.received=client.received .. data --Open clients here, because we want to keep it clean for websocket handshake. if not client.open then doaccept(client.socket) client.open = true end --UPDATE repeat local st,en = client.received:find("%%") if st then local subcommand = client.received:sub(1,st-1) local suc,err = pcall(dosubcommand, client.socket,subcommand) if not suc then print("Client["..tostring(client).."] Error with: "..subcommand) print(err) end client.received = client.received:sub(en+1,-1) end until not st --SEND if client.websocket then repeat --Send by subcommands, webAO doesn't recognize multiple in one message. local st,en = client.send:find("%%") if st then local subcommand = client.send:sub(1,st) local message = wspayloadencode(subcommand,1,false,true) customsend(client.socket,message) local dat,opcode,masked,fin = wspayloaddecode(message) --print("SENT","'"..tostring(dat).."'","LENGTH: "..tostring(#dat),"OPCODE: "..tostring(opcode),"Masked: "..tostring(masked),"FIN: "..tostring(fin)) client.send = client.send:sub(en+1,-1) end until not st else local data = client.send:sub(1,2048) if #data > 0 then customsend(client.socket,data) end client.send = client.send:sub(2048,-1) end end end doupdate(rate) end
--[[ Generated with https://github.com/TypeScriptToLua/TypeScriptToLua ]] require("lualib_bundle"); local ____exports = {} local ____general = require("constants.general") local General = ____general.default ____exports.default = __TS__Class() local Styles = ____exports.default Styles.name = "Styles" function Styles.prototype.____constructor(self) end Styles.RowsPaneStyle = General.Prefix .. "_rows_pane" Styles.RowButtonStyle = General.Prefix .. "_row_button" Styles.RowButtonSelectedStyle = General.Prefix .. "_row_button_selected" Styles.CellBaseStyle = General.Prefix .. "_cell_base" Styles.CellNameStyle = General.Prefix .. "_cell_name" Styles.CellNumericValueStyle = General.Prefix .. "_cell_numeric_value" Styles.CellResourceStyle = General.Prefix .. "_cell_resource" ____exports.default = Styles return ____exports
object_intangible_beast_bm_snorbal = object_intangible_beast_shared_bm_snorbal:new { } ObjectTemplates:addTemplate(object_intangible_beast_bm_snorbal, "object/intangible/beast/bm_snorbal.iff")
style = {["off_color"] = "fff", ["on_color"] = "fff", ["line_color"] = "000", ["line_width"] = "2"}; line_style = {["line_color"] = "f30", ["line_width"] = "2"}; grid_style = {["off_color"] = "none", ["on_color"] = "none", ["line_color"] = "000", ["line_width"] = "0.1"}; colour_style = {["off_color"] = "fff", ["on_color"] = "f90", ["line_color"] = "000", ["line_width"] = "2"}; text_style = {["font_size"] = "16"} trian = "\(\small\triangle\)" eq = "\(\small\cong\)" name_1 = {"AOB", "AOC", "AOD", "AOE", "BOC", "BOD", "BOE", "COD", "COE", "DOE"} name_2 = {"POQ", "POR", "POS", "POT", "QOR", "QOS", "QOT", "ROS", "ROT", "SOT"} ind = math.random(10) if (ind == 6) then ind = ind - math.random(4) end value = name_1[ind] mycanvas = function() if (ind == 1) then results = "result[0] == 0 && result[1] == 1 && result[2] == 0 && result[3] == 0 && result[4] == 0 && result[5] == 0 && result[6] == 0 && result[7] == 0 && result[8] == 0 && result[9] == 0" end if (ind == 2) then results = "result[0] == 0 && result[1] == 0 && result[2] == 1 && result[3] == 0 && result[4] == 0 && result[5] == 0 && result[6] == 0 && result[7] == 0 && result[8] == 0 && result[9] == 1" end if (ind == 3) then results = "result[0] == 0 && result[1] == 0 && result[2] == 0 && result[3] == 0 && result[4] == 0 && result[5] == 0 && result[6] == 1 && result[7] == 0 && result[8] == 0 && result[9] == 0" end if (ind == 4) then results = "result[0] == 0 && result[1] == 0 && result[2] == 0 && result[3] == 1 && result[4] == 0 && result[5] == 0 && result[6] == 0 && result[7] == 0 && result[8] == 0 && result[9] == 0" end if (ind == 5) then results = "result[0] == 0 && result[1] == 0 && result[2] == 0 && result[3] == 0 && result[4] == 0 && result[5] == 0 && result[6] == 0 && result[7] == 1 && result[8] == 0 && result[9] == 0" end if (ind == 6) then results = "result[0] == 0 && result[1] == 0 && result[2] == 0 && result[3] == 0 && result[4] == 0 && result[5] == 0 && result[6] == 0 && result[7] == 0 && result[8] == 0 && result[9] == 0" end if (ind == 7) then results = "result[0] == 0 && result[1] == 0 && result[2] == 0 && result[3] == 0 && result[4] == 0 && result[5] == 0 && result[6] == 0 && result[7] == 0 && result[8] == 1 && result[9] == 0" end if (ind == 8) then results = "result[0] == 0 && result[1] == 0 && result[2] == 0 && result[3] == 0 && result[4] == 0 && result[5] == 1 && result[6] == 0 && result[7] == 0 && result[8] == 0 && result[9] == 0" end if (ind == 9) then results = "result[0] == 0 && result[1] == 0 && result[2] == 1 && result[3] == 0 && result[4] == 0 && result[5] == 0 && result[6] == 0 && result[7] == 0 && result[8] == 0 && result[9] == 1" end if (ind == 10) then results = "result[0] == 1 && result[1] == 0 && result[2] == 0 && result[3] == 0 && result[4] == 0 && result[5] == 0 && result[6] == 0 && result[7] == 0 && result[8] == 0 && result[9] == 0" end lib.start_canvas(350, 350, "center", results) w = 20 ow = 10 v = 5 if (ind < 5) then lib.add_line(ow+2*w, ow+w, 6*w, 4*w, line_style, true, false) else lib.add_line(ow+2*w, ow+w, 6*w, 4*w, style, true, false) end if (ind == 1 or ind == 5 or ind == 6 or ind == 7) then lib.add_line(ow+2*w, ow+4*w, 6*w, w, line_style, true, false) else lib.add_line(ow+2*w, ow+4*w, 6*w, w, style, true, false) end if (ind == 2 or ind == 5 or ind == 8 or ind == 9) then lib.add_line(ow+2*w, ow+5*w, 6*w, 0, line_style, true, false) else lib.add_line(ow+2*w, ow+5*w, 6*w, 0, style, true, false) end if (ind == 3 or ind == 6 or ind == 8 or ind == 10) then lib.add_line(ow+2*w, ow+7*w, 6*w, -2*w, line_style, true, false) else lib.add_line(ow+2*w, ow+7*w, 6*w, -2*w, style, true, false) end if (ind == 4 or ind == 7 or ind == 9 or ind == 10) then lib.add_line(ow+2*w, ow+9*w, 6*w, -4*w, line_style, true, false) else lib.add_line(ow+2*w, ow+9*w, 6*w, -4*w, style, true, false) end if (ind < 5) then lib.add_line(ow+2*w, ow+w, 0, 3*w, line_style, true, false) else lib.add_line(ow+2*w, ow+w, 0, 3*w, style, true, false) end if (ind > 1 and ind < 8) then lib.add_line(ow+2*w, ow+4*w, 0, w, line_style, true, false) else lib.add_line(ow+2*w, ow+4*w, 0, w, style, true, false) end if (ind == 3 or ind == 4 or ind > 5 and ind < 10) then lib.add_line(ow+2*w, ow+5*w, 0, 2*w, line_style, true, false) else lib.add_line(ow+2*w, ow+5*w, 0, 2*w, style, true, false) end if (ind == 4 or ind == 7 or ind > 8) then lib.add_line(ow+2*w, ow+7*w, 0, 2*w, line_style, true, false) else lib.add_line(ow+2*w, ow+7*w, 0, 2*w, style, true, false) end lib.add_line(ow+8*w, ow+5*w, 6*w, -4*w, style, false, false) lib.add_line(ow+8*w, ow+5*w, 6*w, -2*w, style, false, false) lib.add_line(ow+8*w, ow+5*w, 6*w, -w, style, false, false) lib.add_line(ow+8*w, ow+5*w, 6*w, 0, style, false, false) lib.add_line(ow+8*w, ow+5*w, 6*w, 4*w, style, false, false) lib.add_line(ow+14*w, ow+w, 0, 8*w, style, false, false) reply = trian .. value .. " " .. eq .. " " .. trian lib.add_input(ow+4*w, ow+11*w, 150, 40, reply) st_i = 4 * w st_j = w + ow nr = 0 for j = 1,3 do y = 12*w+ow+j*st_j if (j < 3) then min = 1 max = 4 else min = 2 max = 3 end for i = min,max do nr = nr + 1 x = w+ow+(i-1)*st_i lib.add_circle (x, y, v, colour_style, false, true) lib.add_input(x+v, y-ow, 50, 30, name_2[nr]) end end for i = 1,11 do lib.add_line(w+ow, ow+(i-1)*w, 14*w, 0, grid_style, false, false) end for i = 1,15 do lib.add_line(ow+i*w, ow, 0, 10*w, grid_style, false, false) end lib.add_text(2*w, w+ow, "A", text_style) lib.add_text(2*w, 4*w+ow, "B", text_style) lib.add_text(2*w, 5*w+ow, "C", text_style) lib.add_text(2*w, 7*w+ow, "D", text_style) lib.add_text(2*w, 9*w+ow, "E", text_style) lib.add_text(8*w+ow, 4*w+ow, "O", text_style) lib.add_text(15*w, w+ow, "P", text_style) lib.add_text(15*w, 3*w+ow, "Q", text_style) lib.add_text(15*w, 4*w+ow, "R", text_style) lib.add_text(15*w, 5*w+ow, "S", text_style) lib.add_text(15*w, 9*w+ow, "T", text_style) lib.end_canvas() end
Stage = Object:extend() function Stage:new() self.area = Area(self) self.area:addPhysicsWorld() self.area.world:addCollisionClass('Enemy') self.area.world:addCollisionClass('Player') self.area.world:addCollisionClass('Projectile', {ignores = {'Projectile', 'Player'}}) self.area.world:addCollisionClass('Collectable', {ignores = {'Collectable', 'Projectile'}}) self.area.world:addCollisionClass('EnemyProjectile', {ignores = {'EnemyProjectile', 'Projectile', 'Enemy'}}) self.font = fonts.m5x7_16 self.director = Director(self) self.main_canvas = love.graphics.newCanvas(gw, gh) self.player = self.area:addGameObject('Player', gw/2, gh/2) self.score = 0 end function Stage:update(dt) self.director:update(dt) camera.smoother = Camera.smooth.damped(5) camera:lockPosition(dt, gw/2, gh/2) self.area:update(dt) end function Stage:draw() love.graphics.setCanvas(self.main_canvas) love.graphics.clear() camera:attach(0, 0, gw, gh) self.area:draw() camera:detach() love.graphics.setFont(self.font) -- Score love.graphics.setColor(default_color) love.graphics.print(self.score, gw - 20, 10, 0, 1, 1, math.floor(self.font:getWidth(self.score)/2), math.floor(self.font:getHeight()/2)) love.graphics.setColor(255, 255, 255) -- HP local r, g, b = unpack(hp_color) local hp, max_hp = self.player.hp, self.player.max_hp love.graphics.setColor(r, g, b) love.graphics.rectangle('fill', gw/2 - 52, gh - 16, 48*(hp/max_hp), 4) love.graphics.setColor(r - 32, g - 32, b - 32) love.graphics.rectangle('line', gw/2 - 52, gh - 16, 48, 4) love.graphics.print('HP', gw/2 - 52 + 24, gh - 24, 0, 1, 1, math.floor(self.font:getWidth('HP')/2), math.floor(self.font:getHeight()/2)) love.graphics.print(hp .. '/' .. max_hp, gw/2 - 52 + 24, gh - 6, 0, 1, 1, math.floor(self.font:getWidth(hp .. '/' .. max_hp)/2), math.floor(self.font:getHeight()/2)) love.graphics.setColor(255, 255, 255) love.graphics.setCanvas() love.graphics.setColor(255, 255, 255, 255) love.graphics.setBlendMode('alpha', 'premultiplied') love.graphics.draw(self.main_canvas, 0, 0, 0, sx, sy) love.graphics.setBlendMode('alpha') end function Stage:destroy() self.area:destroy() self.area = nil self.player = nil end function Stage:finish() timer:after(1, function() gotoRoom('Stage') end) end
local fs = require("fs") local utils = require("./miscUtils") local json = require("json") local discordia = require("discordia") local commandHandler = {} commandHandler.commands = {} commandHandler.sortedCommandNames = {} commandHandler.sortedPermissionNames = {} commandHandler.customPermissions = { botOwner = function(member) return member.user==member.client.owner end } commandHandler.strings = { -- bits of text used in multiple places that should be consistent usageFooter = "Angled brackets represent required arguments. Square brackets represent optional arguments. Do not include the brackets in the command. All values are case sensitive.", warnFooter = function(guildSettings, entry) return "Time until a warning is removed: "..(entry.is_active and utils.secondsToTime(entry.end_timestamp-os.time()) or "N/A").."\n" .."Warnings until kick: "..(entry.level<guildSettings.warning_kick_level and guildSettings.warning_kick_level-entry.level or "N/A").."\n" .."Warnings until ban: "..(entry.level<guildSettings.warning_ban_level and guildSettings.warning_ban_level-entry.level or "N/A").."\n" .."Active: "..(entry.is_active and "yes" or "no") end, muteFooter = function(guildSettings, length, end_timestamp, is_active) return "Time until unmute: "..(is_active and utils.secondsToTime(end_timestamp-os.time()) or "N/A").."\n" .."Duration: "..utils.secondsToTime(length).."\n" .."Active: "..(is_active and "yes" or "no") end } commandHandler.load = function() for _,filename in ipairs(fs.readdirSync("commands")) do if filename:match("%.lua$") then local command = require("./commands/"..filename) commandHandler.commands[command.name] = command table.insert(commandHandler.sortedCommandNames, command.name) end end table.sort(commandHandler.sortedCommandNames) commandHandler.sortedPermissionNames = table.keys(discordia.enums.permission) table.sort(commandHandler.sortedPermissionNames) end commandHandler.stripPrefix = function(str, guildSettings, client) return str:gsub("^"..utils.escapePatterns(guildSettings.prefix),""):gsub("^%<%@%!?"..client.user.id.."%>%s+","") end commandHandler.sendUsage = function(channel, prefix, commandString) local splitCommandString = string.split(commandString, " ") local command = commandHandler.commands[splitCommandString[1]] for i=2, #splitCommandString do -- go through commandString to get the command object of the deepest subcommand command = command.subcommands[splitCommandString[i]] end return utils.sendEmbed(channel, "Usage: `"..prefix..command.usage.."`", "ff0000", commandHandler.strings.usageFooter) end commandHandler.sendCommandHelp = function(channel, guildSettings, baseCommandString, command, permissions) if guildSettings.disabled_commands[baseCommandString] then channel:send{ embed = { title = guildSettings.prefix..command.name, description = "`"..guildSettings.prefix..baseCommandString.."` is disabled in this server.", color = discordia.Color.fromHex("ff0000").value } } else local subcommandsKeys = table.keys(command.subcommands) local permissionsString = #permissions>0 and "`"..table.concat(permissions, ", ").."`" or "None" local subcommandsString = #subcommandsKeys>0 and "`"..table.concat(subcommandsKeys, "`, `").."`" or "None" channel:send{ embed = { title = guildSettings.prefix..command.name, description = command.description:gsub("%&prefix%;", guildSettings.prefix), fields = { {name = "Required permissions", value = permissionsString}, {name = "Subcommands", value = subcommandsString}, {name = "Usage", value = "`"..guildSettings.prefix..command.usage.."`"} }, color = discordia.Color.fromHex("00ff00").value, footer = { text = commandHandler.strings.usageFooter } } } end end commandHandler.sendPermissionError = function(channel, commandString, missingPermissions) return utils.sendEmbed(channel, "You need the following permission"..utils.s(#missingPermissions).." to use this command: `" ..table.concat(missingPermissions,", ").."`", "ff0000") end commandHandler.enable = function(commandString, message, guildSettings, conn) if not commandHandler.commands[commandString]:onEnable(message, guildSettings, conn) then return false end guildSettings.disabled_commands[commandString] = nil local encodedSetting = json.encode(guildSettings.disabled_commands) local stmt = conn:prepare("UPDATE guild_settings SET disabled_commands = ? WHERE guild_id = ?;") stmt:reset():bind(encodedSetting, message.guild.id):step() stmt:close() return true end commandHandler.disable = function(commandString, message, guildSettings, conn) if not commandHandler.commands[commandString]:onDisable(message, guildSettings, conn) then return false end guildSettings.disabled_commands[commandString] = true local encodedSetting = json.encode(guildSettings.disabled_commands) local stmt = conn:prepare("UPDATE guild_settings SET disabled_commands = ? WHERE guild_id = ?;") stmt:reset():bind(encodedSetting, message.guild.id):step() stmt:close() return true end commandHandler.doCommands = function(message, guildSettings, conn) local content = commandHandler.stripPrefix(message.content, guildSettings, message.client) local commandString = content:match("^(%S+)") local command = commandHandler.commands[commandString] if message.content~=content and command and not guildSettings.disabled_commands[commandString] then local permissions = guildSettings.command_permissions[commandString] or command.permissions local missingPermissions = {} for _,permission in pairs(permissions) do if permission:match("^yot%.") then if not commandHandler.customPermissions[permission:match("^yot%.(.+)")](message.member) then table.insert(missingPermissions, permission) end else if not message.member:hasPermission(permission) then table.insert(missingPermissions, permission) end end end if #missingPermissions==0 then local argString = content:gsub("^"..commandString.."%s*","") local args = argString:split("%s") command:run(message, argString, args, guildSettings, conn) else commandHandler.sendPermissionError(message.channel, commandString, missingPermissions) end if guildSettings.delete_command_messages then message:delete() end end end commandHandler.doSubcommands = function(message, argString, args, guildSettings, conn, commandString) local splitCommandString = string.split(commandString, " ") local command = commandHandler.commands[splitCommandString[1]] for i=2, #splitCommandString do -- go through commandString to get the command object of the deepest subcommand command = command.subcommands[splitCommandString[i]] end local subcommand = command.subcommands[args[1]] if subcommand then argString=argString:gsub("^%S+%s*","") table.remove(args,1) subcommand:run(message, argString, args, guildSettings, conn) return true end return false end return commandHandler
if not Server then return end local mod = %__MODNAME__% mod:LoadAllModuleFiles("Server") local moduleManager = mod:GetModule('modulemanager') local modules = moduleManager:GetModules() fw_print_debug(moduleManager, "Loading all server files") for _,module in ipairs(modules) do fw_print_debug(moduleManager, "Loading server files for module: %s", module) local path = moduleManager:FormatPath(module, "Server") local ServerFiles = {} Shared.GetMatchingFileNames(path, true, ServerFiles) for _,serverFile in ipairs(ServerFiles) do fw_print_debug(moduleManager, "Loading server file: %s", serverFile) Script.Load(serverFile) end end
--[[ MIT License Copyright (c) 2020 Shoelee Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local t_remove = table.remove local t_clear = table.clear --LuaJIT 2.0.5 local c_create = coroutine.create local c_wrap = coroutine.wrap local c_close = coroutine.close --Lua 5.4 local c_resume = coroutine.resume local c_yield = coroutine.yield local c_status = coroutine.status local c_running = coroutine.running local d_traceback = debug.traceback ------------------------------------------------------------------------------- local eztask={ version = {2,5,5}, tick = os.clock, threads = {}, tasks = {} } local callback = {} local signal = {} local property = {} local thread = {} ------------------------------------------------------------------------------- function eztask.step() for _,thread_ in pairs(eztask.threads) do eztask.resume(thread_) end for task_,t in pairs(eztask.tasks) do if eztask:tick()>=t then eztask.tasks[task_]=nil eztask.resume(task_) end end end function eztask.sleep(t) local thread_=eztask.running or eztask local coroutine_=c_running() if t==nil or type(t)=="number" then if thread_.coroutine==coroutine_ then thread_.resume_tick=thread_:tick()+(t or 0) else thread_.tasks[coroutine_]=thread_:tick()+(t or 0) end else local callback_ if thread_.coroutine==coroutine_ then callback_=t:attach(function(...) callback_:detach() thread_.resume_tick=thread_:tick() eztask.resume(thread_,...) end) else callback_=t:attach(function(...) callback_:detach() eztask.resume(coroutine_,...) end) end end return c_yield() end function eztask.resume(thread_,...) if type(thread_)=="thread" then local success,return_=c_resume(thread_,...) if not success then print(d_traceback(thread_,return_)) end return success,return_ end local top_thread=eztask.running resume_tick=eztask.tick() eztask.running=thread_ if c_status(thread_.coroutine)=="suspended" and thread_.resume_tick and thread_.resume_tick<=thread_:tick() then thread_.resume_tick=nil local _,return_=eztask.resume(thread_.coroutine,...) if return_=="kill" then eztask.running=top_thread return thread_:kill() end end for task_,t in pairs(thread_.tasks) do if thread_:tick()>=t then thread_.tasks[task_]=nil local _,return_=eztask.resume(task_) if return_=="kill" then eztask.running=top_thread return thread_:kill() end elseif c_status(task_)=="dead" then thread_.tasks[task_]=nil end end eztask.running=top_thread end ------------------------------------------------------------------------------- function callback.new(event,call,instance) local callback_={ event = event, call = call, instance = instance, thread = eztask.running } event.callbacks[#event.callbacks+1]=callback_ if callback_.thread then callback_.thread.callbacks[callback_]=callback_ end return setmetatable(callback_,callback) end function callback.detach(callback_) for i,callback__ in ipairs(callback_.event.callbacks) do if callback__==callback_ then callback__.event.callbacks[i]=false end end if callback_.thread then callback_.thread.callbacks[callback_]=nil end end function callback.__call(callback_,...) if not callback_.thread or callback_.thread.running.value then if callback_.instance then eztask.resume( c_create(callback_.call), callback_.instance,... ) else if type(callback_.call)=="function" then eztask.resume(c_create(callback_.call),...) else callback_.call(...) end end end end callback.__index=callback ------------------------------------------------------------------------------- function signal.new() return setmetatable({callbacks={}},signal) end function signal.attach(signal_,call,instance) return callback.new(signal_,call,instance) end function signal.detach(signal_) for i=#signal_.callbacks,1,-1 do local callback_=signal_.callbacks[i] if callback_ and callback_.thread then callback_.thread.callbacks[callback_]=nil end signal_.callbacks[i]=nil end end function signal.__call(signal_,...) for i=1,#signal_.callbacks do local callback_=signal_.callbacks[i] if callback_ then callback_(...) end end for i=#signal_.callbacks,1,-1 do if not signal_.callbacks[i] then t_remove(signal_.callbacks,i) end end end signal.__index=signal ------------------------------------------------------------------------------- function property.new(value) return setmetatable({callbacks={},_value=value},property) end function property.attach(property_,call,instance) return callback.new(property_,call,instance) end function property.detach(property_) for i=#property_.callbacks,1,-1 do local callback_=property_.callbacks[i] if callback_ and callback_.thread then callback_.thread.callbacks[callback_]=nil end property_.callbacks[i]=nil end end function property.__index(property_,k) if k=="value" then return rawget(property_,"_value") else return property[k] end end function property.__newindex(property_,k,v) if k=="value" then local old=rawget(property_,"_value") if v~=old then rawset(property_,"_value",v) for i=1,#property_.callbacks do local callback_=property_.callbacks[i] if callback_ then callback_(property_._value,old) end end for i=#property_.callbacks,1,-1 do if not property_.callbacks[i] then t_remove(property_.callbacks,i) end end end else rawset(property_,k,v) end end ------------------------------------------------------------------------------- function thread.new(env) return setmetatable({ env = env, running = property.new(false), active = property.new(false), resume_state = false, start_tick = 0, stop_tick = 0, resume_tick = 0, usage = 0, tasks = {}, callbacks = {} },thread) end function thread.__call(thread_,...) if thread_.active.value then thread_:kill() end local call_running,call_active thread_.coroutine = c_create(thread_.env) thread_.start_tick = eztask.tick() thread_.stop_tick = thread_.start_tick thread_.resume_tick = 0 thread_.active.value = true thread_.running.value = true eztask.threads[thread_.coroutine]=thread_ call_running=thread_.running:attach(function(state) if state then thread_.start_tick=( thread_.start_tick+( eztask.tick()-thread_.stop_tick ) ) else thread_.stop_tick=eztask.tick() if thread_.coroutine==c_running() then c_yield() end end end) call_active=thread_.active:attach(function(active) if not active then call_running:detach() call_active:detach() end end) eztask.resume(thread_,...) return thread_ end function thread.kill(thread_) if not thread_.coroutine then return end if thread_==eztask.running then return c_yield("kill") end thread_.running.value = false thread_.active.value = false for _,callback_ in pairs(thread_.callbacks) do callback_:detach() end if c_close then c_close(thread_.coroutine) end for task_,t in pairs(thread_.tasks) do thread_.tasks[task_]=nil if c_close then c_close(task_) end end eztask.threads[thread_.coroutine]=nil return thread_ end function thread.tick(thread_) if thread_.running.value then return eztask.tick()-thread_.start_tick else return thread_.stop_tick-thread_.start_tick end end thread.__index=thread ------------------------------------------------------------------------------- eztask.callback = callback eztask.signal = signal eztask.property = property eztask.thread = thread return eztask
local docroc = require 'tools/docroc' io.output('doc/README.md') io.write('RxLua\n===\n\n') local comments = docroc.process('rx.lua') -- Generate table of contents for _, comment in ipairs(comments) do local tags = comment.tags if tags.class then local class = tags.class[1].text io.write('- [' .. class .. '](#' .. class:lower() .. ')\n') else local context = comment.context:match('function.-([:%.].+)') if tags.arg then context = context:gsub('%b()', function(signature) local args = {} for _, arg in ipairs(tags.arg) do table.insert(args, arg.name) end return '(' .. table.concat(args, ', ') .. ')' end) end local name = comment.context:match('function.-[:%.]([^%(]+)') io.write(' - [' .. name .. '](#' .. context:gsub('[^%w%s]+', ''):gsub(' ', '-'):lower() .. ')\n') end end io.write('\n') -- Generate content for _, comment in ipairs(comments) do local tags = comment.tags if tags.class then io.write('# ' .. tags.class[1].text .. '\n\n') if tags.description then io.write(tags.description[1].text .. '\n\n') end else local context = comment.context:match('function.-([:%.].+)') if tags.arg then context = context:gsub('%b()', function(signature) local args = {} for _, arg in ipairs(tags.arg) do table.insert(args, arg.name) end return '(' .. table.concat(args, ', ') .. ')' end) end io.write(('---\n\n#### `%s`\n\n'):format(context)) if tags.description then io.write(('%s\n\n'):format(tags.description[1].text)) end if tags.arg then io.write('| Name | Type | Default | Description |\n') io.write('|------|------|---------|-------------|\n') for _, arg in ipairs(tags.arg) do local name = arg.name name = '`' .. name .. '`' local description = arg.description or '' local type = arg.type:gsub('|', ' or ') local default = '' if arg.optional then type = type .. ' (optional)' default = arg.default or default end local line = '| ' .. name .. ' | ' .. type .. ' | ' .. default .. ' | ' .. description .. ' |' io.write(line .. '\n') end io.write('\n') end end end
--[[ Dummy module Config: none ]] local device, config local status = false local function init(dev) device = dev config = device.config return { setter = "boolean", -- type of value for setting values remotely, nil otherwise getter = "boolean", -- type of value for getting values remotely, nil otherwise } end local function get() -- optional get request return status end local function set(v) -- optional set request status = v end local function run() -- optional parallel function for arbitrary code end return { init = init, get = get, set = set, run = run, }
slot0 = class("GuildBasePage", import("...base.BaseSubView")) slot0.getUIName = function (slot0) slot1, slot2 = slot0:getTargetUI() if not getProxy(GuildProxy):getRawData() then return slot0.uiname end if slot3:getFaction() == GuildConst.FACTION_TYPE_BLHX then slot0.uiname = slot1 elseif slot4 == GuildConst.FACTION_TYPE_CSZZ then slot0.uiname = slot2 end return slot0.uiname end slot0.getTargetUI = function (slot0) return end slot0.Destroy = function (slot0) if slot0._state == slot0.STATES.DESTROY then return end if not slot0:GetLoaded() then slot0._state = slot0.STATES.DESTROY return end slot0._state = slot0.STATES.DESTROY pg.DelegateInfo.Dispose(slot0) slot0:OnDestroy() slot0:disposeEvent() slot0:cleanManagedTween() slot0._tf = nil PoolMgr.GetInstance():DelTempCache(slot0.uiname) if slot0._go ~= nil and slot2 then slot1:ReturnUI(slot2, slot0._go) slot0._go = nil end end return slot0
-- Example of a custom level.lua script which can override game -- lua script. All this level script does it peform drawing offset -- from the touch location. local drawing = require 'drawing' local handlers = {} local drawing_offset = 30 function handlers.OnTouchBegan(x, y) return drawing.OnTouchBegan(x + drawing_offset, y + drawing_offset) end function handlers.OnTouchMoved(x, y) drawing.OnTouchMoved(x + drawing_offset, y + drawing_offset) end function handlers.OnTouchEnded(x, y) drawing.OnTouchEnded(x + drawing_offset, y + drawing_offset) end return handlers
local Broadcast = require("core.Broadcast") local Damage = require("core.Damage") local sfmt = string.format local wrapper = require("core.lib.wrapper") local Combat = wrapper.loadBundleScript("lib/Combat", "bundle-example-combat"); local cooldown = 10; local damagePercent = 350; local favorAmount = 5; return { name = "Smite", requiresTarget = true, initiatesCombat = true, resource = { attribute = "favor", cost = favorAmount }, cooldown = cooldown, run = function(state) return function(self, args, player, target) if not player.equipment["weild"] then return Broadcast.sayAt(player, "You don't have a weapon equipped."); end local amount = Combat.calculateWeaponDamage(player) * (damagePercent / 100); local damage = Damage("health", amount, player, self, { type = "holy" }); Broadcast.sayAt(player, sfmt( "<bold><yellow>Your weapon radiates holy energy and you strike %q!", target.name)); Broadcast.sayAtExcept(player.room, sfmt( "<bold><yellow>%q's weapon radiates holy energy and they strike %q!", player.name, target.name), { target, player }); Broadcast.sayAt(target, sfmt( "<bold><yellow>%q's weapon radiates holy energy and they strike you!", player.name)); damage:commit(target); end end, info = function(self, player) return sfmt( "Empower your weapon with holy energy and strike, dealing <bold>%q% weapon damage. Requires a weapon.", damagePercent); end, };
return { name = "james2doyle/merge", version = "0.0.2", description = "Merge table 1 with table 2, handles nested tables", tags = { "table", "merge", "combine", "nested", "array", "object" }, license = "MIT", author = { name = "James Doyle", email = "[email protected]" }, homepage = "https://github.com/james2doyle/lit-merge", dependencies = {}, files = { "**.lua", "!test*" } }
local colorscheme = 'nightfox' local ok = prequire(colorscheme) if not ok then return end if colorscheme == 'nightfox' then require('nightfox').setup { options = { dim_inactive = false, }, groups = { all = { NormalFloat = { link = 'Normal' }, FloatBorder = { fg = 'bg4' }, BqfPreviewBorder = { link = 'FloatBorder' }, IndentBlanklineContextChar = { link = 'FloatBorder' }, -- fg3 CmpDocumentationBorder = { link = 'FloatBorder' }, CmpItemAbbrMatch = { style = 'bold' }, CmpItemAbbrMatchFuzzy = { style = 'bold' }, TelescopeMatching = { link = 'CmpItemAbbrMatch' }, DiffText = { style = 'bold' }, DiffDelete = { fg = 'syntax.comment' }, }, }, } colorscheme = 'terafox' elseif colorscheme == 'kanagawa' then require('kanagawa').setup { commentStyle = 'NONE', keywordStyle = 'NONE', variablebuiltinStyle = 'NONE', } elseif colorscheme == 'vscode' then vim.g.vscode_style = 'dark' vim.g.vscode_italic_comment = 0 end vim.api.nvim_cmd({ cmd = 'colorscheme', args = { colorscheme } }, {})
include('organizer-lib') function get_sets() sets.TH = { hands={ name="Merlinic Dastanas", augments={'"Treasure Hunter"+2',},hp=9,mp=20}, legs={ name="Merlinic Shalwar", augments={'Pet: Accuracy+16 Pet: Rng. Acc.+16','Pet: Haste+1','"Treasure Hunter"+1','Mag. Acc.+9 "Mag.Atk.Bns."+9',},hp=29,mp=44}, waist="Chaac Belt", } -- Precast Sets sets.precast = {} sets.precast.FC = { ammo="Impatiens", head={ name="Merlinic Hood", augments={'"Fast Cast"+7','MND+10','Mag. Acc.+10','"Mag.Atk.Bns."+10',},mp=56,hp=22}, body={name="Zendik Robe",hp=57,mp=61}, hands={ name="Merlinic Dastanas", augments={'Mag. Acc.+29','"Fast Cast"+7','INT+1',},mp=20,hp=9}, legs={ name="Psycloth Lappas", augments={'MP+80','Mag. Acc.+15','"Fast Cast"+7',},mp=109,hp=43}, feet={ name="Merlinic Crackows", augments={'"Mag.Atk.Bns."+11','"Fast Cast"+7',},hp=4,mp=20}, neck={ name="Orunmila's Torque",mp=30}, waist="Witful Belt", left_ear={ name="Loquac. Earring",mp=30}, left_ring="Weather. Ring +1", right_ear={name="Etiolation Earring",hp=50,mp=50}, right_ring={name="Lebeche Ring",mp=40}, back={ name="Campestres's Cape", augments={'Pet: M.Acc.+20 Pet: M.Dmg.+20','Pet: Mag. Acc.+10','"Fast Cast"+10',}}, } -- 15+13+7+7+12+5+3+2+6+1+10 = 81% FC -- 2+3+4+2 = 11% Quickens sets.precast['Astral Flow'] = { head={ name="Glyphic Horn +1",hp=31,mp=95}, } -- Midcast sets sets.midcast = {} sets.midcast.BP = { -- -10 from Gifts main={ name="Espiritus", augments={'Enmity-6','Pet: "Mag.Atk.Bns."+30','Pet: Damage taken -4%',}, mp=88}, ammo="Sancus Sachet +1", head={name= "Beckoner's Horn +1",hp=31,mp=134}, right_ear={name="Evans Earring",mp=50}, hands={ name="Glyphic Bracers +1", augments={'Inc. Sp. "Blood Pact" magic burst dmg.',},hp=18,mp=41}, legs={ name="Glyphic Spats +1", augments={'Increases Sp. "Blood Pact" accuracy',},hp=38,mp=85}, } -- This set technically has too much BP Recast-, but it compensates for times when I lock gear. sets.midcast['Mana Cede'] = {hands="Beckoner's Bracers +1"} sets.midcast['Elemental Siphon'] = { main="Nirvana", sub="Vox Grip", ammo="Esper Stone +1", neck="Caller's Pendant", rear="Smn. Earring", lear={ name="Andoaa Earring", mp=30}, hands={ name="Telchine Gloves", augments={'"Elemental Siphon"+35','Enh. Mag. eff. dur. +10',},hp=52,mp=44}, head={ name="Telchine Cap", augments={'"Elemental Siphon"+35','Enh. Mag. eff. dur. +10',},hp=36,mp=32}, body={ name="Telchine Chas.", augments={'"Elemental Siphon"+35','Enh. Mag. eff. dur. +10',},hp=54,mp=59}, legs={ name="Telchine Braconi", augments={'"Elemental Siphon"+35','Enh. Mag. eff. dur. +10',},hp=43,mp=29}, waist={name="Kobo Obi",mp=20}, lring={name="Evoker's Ring",mp=25}, rring="Globidonta Ring", back={ name="Conveyance Cape", augments={'Summoning magic skill +5','Pet: Enmity+15','Blood Pact Dmg.+4',},mp=100}, feet={ name="Beckoner's Pigaches +1",hp=9,mp=97}, day = { rring = "Zodiac Ring", } } sets.midcast.Cur = { main="Vadose Rod", sub="Genbu's Shield", head="Marduk's Tiara +1", neck={name="Nodens Gorget",hp=25,mp=25}, ear2="Novia earring", hands={name="Revealer's Mitts +1",hp=22,mp=44}, } sets.midcast.Stoneskin = { neck={name="Nodens Gorget",hp=25,mp=25}, waist="Siegel Sash", legs="Shedir Seraweels" } sets.midcast.Cursna = { head={ name="Vanya Hood", augments={'Healing magic skill +20','"Cure" spellcasting time -7%','Magic dmg. taken -3',},hp=36,mp=32}, body={name="Vanya Robe",hp=54,mp=59}, hands={name="Hieros Mittens",mp=30}, legs={ name="Vanya Slops", augments={'Healing magic skill +20','"Cure" spellcasting time -7%','Magic dmg. taken -3',},hp=43,mp=29}, left_ring="Haoma's Ring", right_ring="Haoma's Ring", back={name="Oretan. Cape +1",hp=30}, feet={name="Vanya Clogs",hp=13,mp=14}, neck="Debilis Medallion", } sets.midcast.EnhancingDuration = { main={ name="Gada", augments={'Enh. Mag. eff. dur. +6','"Mag.Atk.Bns."+9',}}, sub={name="Ammurapi Shield",hp=22,mp=58}, hands={ name="Telchine Gloves", augments={'"Elemental Siphon"+35','Enh. Mag. eff. dur. +10',},hp=52,mp=44}, head={ name="Telchine Cap", augments={'"Elemental Siphon"+35','Enh. Mag. eff. dur. +10',},hp=36,mp=32}, body={ name="Telchine Chas.", augments={'"Elemental Siphon"+35','Enh. Mag. eff. dur. +10',},hp=54,mp=59}, legs={ name="Telchine Braconi", augments={'"Elemental Siphon"+35','Enh. Mag. eff. dur. +10',},hp=43,mp=29}, feet={ name="Telchine Pigaches", augments={'Song spellcasting time -7%','Enh. Mag. eff. dur. +10',}}, } sets.midcast.Refresh = set_combine(sets.midcast.EnhancingDuration,{ head={name="Amalric Coif +1",hp=27,mp=61}, feet={name="Inspirited Boots",hp=9,mp=20}, waist="Gishdubar Sash", back="Grapevine Cape", }) sets.midcast['Diaga'] = sets.TH sets.midcast['Dia'] = sets.TH sets.midcast['Dia II'] = sets.TH sets.midcast['Swipe'] = sets.TH sets.midcast['Lunge'] = sets.TH -- Pet Midcast Sets sets.pet_midcast = {} sets.BP_Base = { main={ name="Espiritus", augments={'Enmity-6','Pet: "Mag.Atk.Bns."+30','Pet: Damage taken -4%',}, mp=88}, sub="Elan Strap +1", ammo="Sancus Sachet +1", head={name="Apogee Crown +1",hp=-110,mp=139}, body={name="Convoker's Doublet +1",hp=50,mp=134}, hands={ name="Merlinic Dastanas", augments={'Pet: Accuracy+30 Pet: Rng. Acc.+30','Blood Pact Dmg.+9','Pet: INT+9','Pet: "Mag.Atk.Bns."+14',},mp=20,hp=9}, legs={ name="Enticer's Pants", augments={'MP+50','Pet: Accuracy+15 Pet: Rng. Acc.+15','Pet: Mag. Acc.+15','Pet: Damage taken -5%',},hp=38,mp=106}, feet={name="Apogee Pumps +1",hp=-90,mp=121}, left_ear="Lugalbanda Earring", right_ear={name="Gelos Earring",mp=35}, left_ring="Varar Ring +1", right_ring="Varar Ring +1", } sets.pet_midcast.Phys_BP = set_combine(sets.BP_Base,{ main="Nirvana", neck="Shulmanu Collar", waist="Klouskap Sash", legs={name="Apogee Slacks +1",hp=-110,mp=56}, back={ name="Campestres's Cape", augments={'Pet: Acc.+20 Pet: R.Acc.+20 Pet: Atk.+20 Pet: R.Atk.+20','Eva.+20 /Mag. Eva.+20','Pet: Haste+10',}}, }) sets.pet_midcast.MAB_BP = set_combine(sets.BP_Base,{ neck={name="Adad amulet",hp=25}, --body={name="Apogee Dalmatica +1",hp=-160,mp=85}, waist={name="Caller's sash",mp=20}, ring2={name="Speaker's Ring",mp=40}, back={ name="Campestres's Cape", augments={'Pet: M.Acc.+20 Pet: M.Dmg.+20','"Fast Cast"+10',}}, }) sets.pet_midcast.MAB_Spell = set_combine(sets.BP_Base,{ neck={name="Adad amulet",hp=25}, --body={name="Apogee Dalmatica +1",hp=-160,mp=85}, waist={name="Caller's sash",mp=20}, ring2={name="Speaker's Ring",mp=40}, right_ring="Globidonta Ring", back={ name="Campestres's Cape", augments={'Pet: M.Acc.+20 Pet: M.Dmg.+20','"Fast Cast"+10',}}, }) sets.pet_midcast.MAcc_BP = set_combine(sets.BP_Base,{ main="Nirvana", sub="Vox Grip", neck={name="Adad amulet",hp=25}, right_ear="Smn. Earring", body={name="Beckoner's Doublet +1",hp=54,mp=151}, hands={name="Lamassu mitts +1",hp=18,mp=44}, feet={ name="Beckoner's Pigaches +1",hp=9,mp=97}, lring={name="Evoker's Ring",mp=25}, right_ring="Globidonta Ring", back={ name="Campestres's Cape", augments={'Pet: M.Acc.+20 Pet: M.Dmg.+20','"Fast Cast"+10',}}, }) sets.pet_midcast.Buff_BP = set_combine(sets.BP_Base,{ -- Did not check main="Nirvana", sub="Vox Grip", head={name= "Beckoner's Horn +1",hp=31,mp=134}, neck="Caller's Pendant", lear={ name="Andoaa Earring", mp=30}, right_ear="Smn. Earring", --body={name="Apogee Dalmatica +1",hp=-160,mp=85}, hands={ name="Glyphic Bracers +1", augments={'Inc. Sp. "Blood Pact" magic burst dmg.',},hp=18,mp=41}, legs={name="Assid. Pants +1",hp=43,mp=29}, lring={name="Evoker's Ring",mp=25}, right_ring="Globidonta Ring", back={ name="Campestres's Cape", augments={'Pet: Acc.+20 Pet: R.Acc.+20 Pet: Atk.+20 Pet: R.Atk.+20','Eva.+20 /Mag. Eva.+20','Pet: Haste+10',}}, }) sets.pet_midcast['Shock Squall'] = { main="Nirvana", sub="Vox Grip", head={name= "Beckoner's Horn +1",hp=31,mp=134}, neck={name="Adad amulet",hp=25}, right_ear="Smn. Earring", body={name="Beckoner's Doublet +1",hp=54,mp=151}, hands={ name="Glyphic Bracers +1", augments={'Inc. Sp. "Blood Pact" magic burst dmg.',},hp=18,mp=41}, lring={name="Evoker's Ring",mp=25}, rring="Globidonta Ring", back={ name="Campestres's Cape", augments={'Pet: M.Acc.+20 Pet: M.Dmg.+20','"Fast Cast"+10',}}, legs={ name="Enticer's Pants", augments={'MP+50','Pet: Accuracy+15 Pet: Rng. Acc.+15','Pet: Mag. Acc.+15','Pet: Damage taken -5%',},hp=38,mp=106}, } --Aftercast Sets sets.aftercast = {} sets.aftercast.None = { main="Mafic Cudgel", sub="Genmei Shield", head={name= "Beckoner's Horn +1",hp=31,mp=134}, neck="Loricate Torque +1", left_ear={ name="Loquac. Earring",mp=30}, right_ear={name="Evans Earring",mp=50}, body={ name="Witching Robe", augments={'MP+50','Mag. Acc.+15','"Mag.Atk.Bns."+15','"Refresh"+1',},hp=50,mp=117}, hands={ name="Hagondes Cuffs +1", augments={'Phys. dmg. taken -3%','Mag. Acc.+23',},hp=30,mp=22}, ring1={name="Dark Ring",hp=-20,mp=20}, ring2="Defending Ring", back="Umbra Cape", waist="Klouskap Sash", legs={name="Assid. Pants +1",hp=43,mp=29}, feet={name="Herald's Gaiters",mp=12}, } -- Including Auto-Refresh II, unaffected by Avatar's Favor: -- Carbuncle: 11MP/tick : 10 Perp- + Refresh ideal (4 + Mitts + Refresh) -- Diabolos/Celestials: 15MP/tick : 14 Perp- + Refresh ideal -- Fenrir: 13MP/tick : 12 Perp- + Refresh ideal -- Spirit: 7MP/tick : 6 Perp- + Refresh ideal (Beckoner's Doublet +1) sets.aftercast.Avatar = {} sets.aftercast.Avatar.Carbuncle = { main="Nirvana", sub="Vox Grip", ammo="Sancus Sachet +1", head={name= "Beckoner's Horn +1",hp=31,mp=134}, body={ name="Witching Robe", augments={'MP+50','Mag. Acc.+15','"Mag.Atk.Bns."+15','"Refresh"+1',},hp=50,mp=117}, hands={name="Asteria Mitts +1",hp=18,mp=44}, legs={name="Assid. Pants +1",hp=43,mp=29}, feet={name="Herald's Gaiters",mp=12}, neck="Shulmanu Collar", waist="Lucidity Sash", lear={ name="Andoaa Earring", mp=30}, right_ear={name="Evans Earring",mp=50}, left_ring="Varar Ring +1", right_ring="Defending Ring", back={ name="Campestres's Cape", augments={'Pet: Acc.+20 Pet: R.Acc.+20 Pet: Atk.+20 Pet: R.Atk.+20','Eva.+20 /Mag. Eva.+20','Pet: Haste+10',}}, } sets.aftercast.Avatar.Garuda = { -- 16 MP/tick, currently negated at -15 Perp with 512 skill main="Nirvana", sub="Vox Grip", ammo="Sancus Sachet +1", head={name= "Beckoner's Horn +1",hp=31,mp=134}, body={ name="Witching Robe", augments={'MP+50','Mag. Acc.+15','"Mag.Atk.Bns."+15','"Refresh"+1',},hp=50,mp=117}, hands={ name="Glyphic Bracers +1", augments={'Inc. Sp. "Blood Pact" magic burst dmg.',},hp=18,mp=41}, legs={name="Assid. Pants +1",hp=43,mp=29}, feet={name="Apogee Pumps +1",hp=-90,mp=121}, neck="Shulmanu Collar", waist="Klouskap Sash", lear={ name="Andoaa Earring", mp=30}, right_ear={name="Evans Earring",mp=50}, left_ring="Varar Ring +1", right_ring="Defending Ring", back={ name="Campestres's Cape", augments={'Pet: Acc.+20 Pet: R.Acc.+20 Pet: Atk.+20 Pet: R.Atk.+20','Eva.+20 /Mag. Eva.+20','Pet: Haste+10',}}, } -- Celestials sets.aftercast.Avatar.Ifrit = sets.aftercast.Avatar.Garuda sets.aftercast.Avatar.Shiva = sets.aftercast.Avatar.Garuda sets.aftercast.Avatar.Ramuh = sets.aftercast.Avatar.Garuda sets.aftercast.Avatar.Leviathan = sets.aftercast.Avatar.Garuda sets.aftercast.Avatar.Titan = sets.aftercast.Avatar.Garuda sets.aftercast.Avatar.Diabolos = sets.aftercast.Avatar.Garuda sets.aftercast.Avatar.Fenrir = { -- ? MP/tick, currently negated at -15 Perp with 512 skill main="Nirvana", sub="Vox Grip", ammo="Sancus Sachet +1", head={name= "Beckoner's Horn +1",hp=31,mp=134}, body={ name="Witching Robe", augments={'MP+50','Mag. Acc.+15','"Mag.Atk.Bns."+15','"Refresh"+1',},hp=50,mp=117}, hands={ name="Glyphic Bracers +1", augments={'Inc. Sp. "Blood Pact" magic burst dmg.',},hp=18,mp=41}, legs={name="Assid. Pants +1",hp=43,mp=29}, feet={name="Apogee Pumps +1",hp=-90,mp=121}, neck="Shulmanu Collar", waist="Klouskap Sash", lear={ name="Andoaa Earring", mp=30}, right_ear={name="Evans Earring",mp=50}, left_ring="Varar Ring +1", right_ring="Defending Ring", back={ name="Campestres's Cape", augments={'Pet: Acc.+20 Pet: R.Acc.+20 Pet: Atk.+20 Pet: R.Atk.+20','Eva.+20 /Mag. Eva.+20','Pet: Haste+10',}}, } -- Fenrir sets.aftercast.Avatar['Cait Sith'] = set_combine(sets.aftercast.Avatar.Fenrir,{ hands={name="Lamassu mitts +1",hp=18,mp=44}, }) sets.aftercast.Avatar.Spirit = { main={ name="Espiritus", augments={'Enmity-6','Pet: "Mag.Atk.Bns."+30','Pet: Damage taken -4%',}, mp=88}, sub="Vox Grip", ammo="Sancus Sachet +1", head={name= "Beckoner's Horn +1",hp=31,mp=134}, body={name="Beckoner's Doublet +1",hp=54,mp=151}, hands={ name="Glyphic Bracers +1", augments={'Inc. Sp. "Blood Pact" magic burst dmg.',},hp=18,mp=41}, legs={ name="Glyphic Spats +1", augments={'Increases Sp. "Blood Pact" accuracy',}}, feet="Marduk's Crackows +1", neck="Caller's Pendant", waist={name="Caller's sash",mp=20}, lear={ name="Andoaa Earring", mp=30}, right_ear="Smn. Earring", lring={name="Evoker's Ring",mp=25}, left_ring="Globidonta Ring", back={ name="Conveyance Cape", augments={'Summoning magic skill +5','Pet: Enmity+15','Blood Pact Dmg.+4',},mp=100}, } -- Spirits sets.aftercast.Resting = { main={name="Numen Staff",mp=45}, sub="Ariesian Grip", ammo={name="Mana Ampulla",mp=20}, head={name= "Beckoner's Horn +1",hp=31,mp=134}, neck={name="Eidolon Pendant +1",mp=15}, ear1="Relaxing Earring", ear2={name="Antivenom Earring",mp=15}, body={ name="Witching Robe", augments={'MP+50','Mag. Acc.+15','"Mag.Atk.Bns."+15','"Refresh"+1',},hp=50,mp=117}, hands={name="Nares Cuffs",mp=50},-- Not technically accurate ring1={name="Celestial Ring",mp=20}, ring2="Angha Ring", back={name="Felicitas Cape +1",mp=15}, waist="Austerity Belt +1", legs={name="Assid. Pants +1",hp=43,mp=29}, feet={name="Chelona Boots +1",mp=40}, } sets.aftercast.Idle = sets.aftercast.None sets.aftercast.Engaged = { body={ name="Hagondes Coat +1", hp=54,mp=59}, neck="Loricate Torque +1", ring1={name="Dark Ring",hp=-20,mp=20}, hands={ name="Hagondes Cuffs +1", augments={'Phys. dmg. taken -3%','Mag. Acc.+23',},hp=30,mp=22}, lear="Genmei Earring", } --[[{ main="Nirvana", sub="Bloodrain Strap", head={name= "Beckoner's Horn +1",hp=31,mp=134}, body="Onca Suit", hands=empty, legs=empty, feet=empty, neck="Lissome Necklace", waist="Klouskap Sash", left_ear="Cessance Earring", right_ear="Telos Earring", left_ring="Rajas Ring", right_ring="Petrov Ring", back="Umbra Cape", }]] sets.midcast['Garland of Bliss'] = { ammo="Pemphredo Tathlum", head={ name="Merlinic Hood", augments={'VIT+8','"Mag.Atk.Bns."+27','Accuracy+5 Attack+5','Mag. Acc.+18 "Mag.Atk.Bns."+18',},mp=56,hp=22}, body={ name="Merlinic Jubbah", augments={'"Mag.Atk.Bns."+29','Magic burst dmg.+11%','INT+10',},hp=49,mp=67}, hands={ name="Amalric Gages +1", augments={'MP+80','Mag. Acc.+20','"Mag.Atk.Bns."+20',},hp=13,mp=106}, legs={ name="Merlinic Shalwar", augments={'Mag. Acc.+25 "Mag.Atk.Bns."+25','MND+4','Mag. Acc.+15','"Mag.Atk.Bns."+12',},hp=29,mp=44}, feet={ name="Amalric Nails +1", augments={'MP+80','Mag. Acc.+20','"Mag.Atk.Bns."+20',},hp=4,mp=106}, neck="Fotia Gorget", waist="Fotia Belt", left_ear="Friomisi Earring", right_ear="Ishvara Earring", left_ring="Weather. Ring +1", right_ring="Shiva Ring +1", back={name="Pahtli Cape",mp=50}, } sets.midcast['Elemental Magic'] ={ main="Marin Staff +1", sub="Enki Strap", ammo="Pemphredo Tathlum", head={ name="Merlinic Hood", augments={'VIT+8','"Mag.Atk.Bns."+27','Accuracy+5 Attack+5','Mag. Acc.+18 "Mag.Atk.Bns."+18',},mp=56,hp=22}, body="Seidr Cotehardie", hands={ name="Amalric Gages +1", augments={'MP+80','Mag. Acc.+20','"Mag.Atk.Bns."+20',},hp=13,mp=106}, legs={ name="Merlinic Shalwar", augments={'Mag. Acc.+25 "Mag.Atk.Bns."+25','MND+4','Mag. Acc.+15','"Mag.Atk.Bns."+12',},hp=29,mp=44}, feet={ name="Amalric Nails +1", augments={'MP+80','Mag. Acc.+20','"Mag.Atk.Bns."+20',},hp=4,mp=106}, neck={name="Saevus Pendant +1",mp=20}, waist={name="Yamabuki-no-Obi",mp=35}, left_ear="Friomisi Earring", right_ear="Crematio Earring", left_ring="Shiva Ring +1", right_ring="Shiva Ring +1", back="Toro Cape", Ice={main="Ngqoqwanb"}, Earth={neck={name="Quanpur Necklace",mp=10}} } sets.midcast.Myrkr={ ammo={name="Ghastly Tathlum +1",mp=35}, head={name= "Beckoner's Horn +1",hp=31,mp=134}, body={name="Beckoner's Doublet +1",hp=54,mp=151}, hands={ name="Amalric Gages +1", augments={'MP+80','Mag. Acc.+20','"Mag.Atk.Bns."+20',},hp=13,mp=106}, legs={ name="Psycloth Lappas", augments={'MP+80','Mag. Acc.+15','"Fast Cast"+7',},mp=109,hp=43}, feet={name="Apogee Pumps +1",hp=-90,mp=121}, neck={name="Sanctity Necklace",hp=35,mp=35}, waist={name="Mujin Obi",mp=60}, left_ear={name="Etiolation Earring",hp=50,mp=50}, right_ear={ name="Moonshade Earring", augments={'Attack+4','TP Bonus +25',}}, left_ring={name="Lebeche Ring",mp=40}, right_ring={name="Sangoma Ring",mp=70}, back={ name="Conveyance Cape", augments={'Summoning magic skill +5','Pet: Enmity+15','Blood Pact Dmg.+4',},mp=100}, } -- Variables and notes to myself Debuff_BPs = T{'Diamond Storm','Sleepga','Slowga','Tidal Roar','Shock Squall','Nightmare','Pavor Nocturnus','Ultimate Terror','Somnolence','Lunar Cry','Lunar Roar'} Magical_BPs = T{'Heavenly Strike','Wind Blade','Holy Mist','Night Terror','Thunderstorm','Geocrush','Meteor Strike','Grand Fall','Lunar Bay','Thunderspark','Nether Blast', 'Aerial Blast','Searing Light','Diamond Dust','Earthen Fury','Zantetsuken','Tidal Wave','Judgment Bolt','Inferno','Howling Moon','Ruinous Omen'} Additional_effect_BPs = T{'Rock Throw'} AvatarList = S{'Shiva','Ramuh','Garuda','Leviathan','Diabolos','Titan','Fenrir','Ifrit','Carbuncle', 'Fire Spirit','Air Spirit','Ice Spirit','Thunder Spirit','Light Spirit','Dark Spirit','Earth Spirit','Water Spirit', 'Cait Sith','Alexander','Odin','Atomos'} send_command('input /macro book 8;wait .1;input /macro set 1') end function pet_change(pet,gain) equip_aftercast(player.status,pet) if player.mpp > 80 then set_priorities('mp','hp') else set_priorities('hp','mp') end end function pet_status_change(a,b) windower.add_to_chat(8,'Pet status change: '..tostring(a)..' '..tostring(b)) -- Useful for knowing when you got aggroed end function precast(spell) if spell.action_type == 'Magic' then equip(sets.precast.FC) end if sets.precast.FC[spell.element] then equip(sets.precast.FC[spell.element]) end if player.mpp > 80 then set_priorities('mp','hp') else set_priorities('hp','mp') end end function midcast(spell) if pet_midaction() then return end equip_aftercast(player.status,pet) -- Put DT gear on if string.find(spell.type,'BloodPact') then if buffactive['Astral Conduit'] then pet_midcast(spell) else equip(sets.midcast.BP) end elseif string.find(spell.english,'Cur') then equip(sets.midcast.Cur) elseif sets.midcast[spell.english] then equip(sets.midcast[spell.english]) if spell.english == 'Elemental Siphon' then if pet.element and pet.element == world.day_element and world.day_element ~= "Light" and world.day_element ~= 'Dark' then equip(sets.midcast['Elemental Siphon'].day) -- Zodiac Ring affects Siphon, but only on Fires-Lightningsday end end elseif spell.skill == 'Elemental Magic' then equip(sets.midcast['Elemental Magic']) if sets.midcast['Elemental Magic'][spell.element] then equip(sets.midcast['Elemental Magic'][spell.element]) end if world.day_element == spell.element or world.weather_element == spell.element then equip({waist="Hachirin-no-Obi"}) end elseif spell.skill == 'Enhancing Magic' then equip(sets.midcast.EnhancingDuration) end if player.mpp > 80 then set_priorities('mp','hp') else set_priorities('hp','mp') end end function aftercast(spell) if pet_midaction() then return elseif spell and string.find(spell.type,'BloodPact') and not spell.interrupted then pet_midcast(spell) else -- Don't want to swap away too quickly if I'm about to put BP damage gear on -- Need to wait 1 in order to allow pet information to update on Release. equip_aftercast(player.status,pet) end if player.mpp > 80 then set_priorities('mp','hp') else set_priorities('hp','mp') end end function status_change(new,old) equip_aftercast(new,pet) if player.mpp > 80 then set_priorities('mp','hp') else set_priorities('hp','mp') end end function pet_midcast(spell) if spell.name == 'Perfect Defense' then equip(sets.midcast['Elemental Siphon'],{feet="Marduk's Crackows +1"}) elseif spell.type=='BloodPactWard' then if Debuff_BPs:contains(spell.name) then equip(sets.pet_midcast.MAcc_BP) else equip(sets.pet_midcast.Buff_BP) end elseif spell.type=='BloodPactRage' then if Magical_BPs:contains(spell.name) or string.find(spell.name,' II') or string.find(spell.name,' IV') then equip(sets.pet_midcast.MAB_BP) elseif Additional_effect_BPs:contains(spell.name) then -- for BPs where the additional effect matters more than the damage equip(sets.pet_midcast.MAcc_BP) else equip(sets.pet_midcast.Phys_BP) end elseif spell.type=='BlackMagic' then equip(sets.pet_midcast.MAB_Spell) end if player.mpp > 80 then set_priorities('mp','hp') else set_priorities('hp','mp') end end function pet_aftercast(spell) windower.add_to_chat(8,'pet_aftercast: '..tostring(spell.name)) equip_aftercast(player.status,pet) if player.mpp > 80 then set_priorities('mp','hp') else set_priorities('hp','mp') end end function self_command(command) if command == 'Idle' then equip_aftercast('Idle',pet) end if player.mpp > 80 then set_priorities('mp','hp') else set_priorities('hp','mp') end end function equip_aftercast(status,pet) if sets.aftercast[status] then equip(sets.aftercast[status]) end if pet.isvalid then if string.find(pet.name,'Spirit') then equip(sets.aftercast.Avatar.Spirit) elseif sets.aftercast.Avatar[pet.name] then equip(sets.aftercast.Avatar[pet.name]) end end if status == "Engaged" then equip(sets.aftercast[status]) end end function set_priorities(key1,key2) local future,current = gearswap.equip_list,gearswap.equip_list_history function get_val(piece,key) if piece and type(piece)=='table' and piece[key] and type(piece[key])=='number' then return piece[key] end return 0 end local diff = {} for i,v in pairs(future) do local priority = get_val(future[i],key1) - get_val(current[i],key1) + (get_val(future[i],key2) - get_val(current[i],key2)) if type(v) == 'table' then future[i].priority = priority else future[i] = {name=v,priority=priority} end end end
-- Workspace: SilverEngine -- ------------------- workspace "SilverEngine" architecture "x86_64" configurations { "Debug", "Release" } startproject "Galena" -- Project: SilverEngine -- ----------------- project "SilverEngine" location "SilverEngine" kind "SharedLib" language "C++" cppdialect "c++17" staticruntime "Off" targetdir "Bin/%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}/%{prj.name}" objdir "Bin-Int/%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}/%{prj.name}" pchheader "AgPch.h" pchsource "%{prj.name}/Src/AgPch.cpp" files { "%{prj.name}/Src/**.cpp", "%{prj.name}/Src/**.h", "%{prj.name}/Vendor/**.h" } includedirs { "%{prj.name}/Src", "%{prj.name}/Vendor" } libdirs { "%{prj.name}/Vendor/Glfw/lib-vc2019", "%{prj.name}/Vendor/Glad" } links { "glfw3.lib", "glad.lib", "opengl32.lib" } filter "system:windows" defines { "AG_PLAT_WINDOWS", "AG_BUILD_DLL" } systemversion "latest" filter "configurations:Debug" defines "AG_BUILD_DEBUG" symbols "Full" optimize "Off" filter "configurations:Release" defines "AG_BUILD_RELEASE" symbols "Off" optimize "Full" -- Project: Galena -- ----------------- project "Galena" location "Galena" kind "ConsoleApp" language "C++" cppdialect "c++17" staticruntime "Off" targetdir "Bin/%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}/%{prj.name}" objdir "Bin-Int/%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}/%{prj.name}" files { "%{prj.name}/Src/**.cpp", "%{prj.name}/Src/**.h" } includedirs { "%{prj.name}/Src", "SilverEngine/Src", "SilverEngine/Vendor" } links { "SilverEngine" } filter "system:windows" defines "AG_PLAT_WINDOWS" systemversion "latest" filter "configurations:Debug" defines "AG_BUILD_DEBUG" symbols "Full" optimize "Off" filter "configurations:Release" defines "AG_BUILD_RELEASE" symbols "Off" optimize "Full"
----------------------------------------- -- ID: 18427 -- Item: Hanafubuki -- Item Effect: TP +10 -- Durration: Instant ----------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") ----------------------------------------- function onItemCheck(target) local result = 0 return result end function onItemUse(target) target:addTP(100) end
isDbg = false function Initialize() hexChars = { [0]='0', [1]='1', [2]='2', [3]='3', [4]='4', [5]='5', [6]='6', [7]='7', [8]='8', [9]='9', [10]='a', [11]='b', [12]='c', [13]='d', [14]='e', [15]='f' } page = tonumber(SKIN:GetVariable('page',1)) ulBytes = SKIN:GetVariable('uploadMax') dlBytes = SKIN:GetVariable('downloadMax') SKIN:Bang('!SetOptionGroup','pButtons','FontColor','#*textMainColor*#') if (page == 1) then SKIN:Bang('!SetOption','page1','FontColor','#*highlightColor*#') elseif page == 2 then SKIN:Bang('!SetOption','page2','FontColor','#*highlightColor*#') colors = { SKIN:GetVariable('textColor'), SKIN:GetVariable('numColor'), SKIN:GetVariable('barColor') } bars = { SKIN:GetMeter('1ColorAlpha'), SKIN:GetMeter('2ColorAlpha'), SKIN:GetMeter('3ColorAlpha') } maxBarW = SKIN:GetMeter('1ColorAlphaBg'):GetW() -- set the width of the bars that show the alpha of the three colors for i=1,#colors do tempW = math.floor(getStringAlphaPercent(colors[i]) * maxBarW) SKIN:Bang('!SetOption', bars[i]:GetName(), 'W', tempW) end elseif page == 3 then SKIN:Bang('!SetOption','page3','FontColor','#*highlightColor*#') elseif page == 4 then SKIN:Bang('!SetOption','page4','FontColor','#*highlightColor*#') elseif page == 5 then SKIN:Bang('!SetOption','page5','FontColor','#*highlightColor*#') else print('C2: wtf? invalid page number in settings skin') end SKIN:Bang('!Redraw') end function Update() end -- ========================================================================================== -- Functions used for displaying and changing the transparency of the colors on page 2 -- called from skin - changes alpha value on a color in Appearance.txt function changeAlpha(color, percent) baseColor = SKIN:GetVariable(color) alpha = math.floor(percent*0.01*255) if (string.find(baseColor, ",") ~= nil) then rgb = string.match(baseColor, "%d+,%d+,%d+") newColor = rgb .. ',' .. alpha else rgb = string.sub(baseColor,1,6) alpha = decToHex(alpha) newColor = rgb .. alpha end SKIN:Bang('!WriteKeyValue','Variables',color,newColor,'#@#Appearance.txt') end -- intended to retreive the alpha component of an RGBA or hex color and return as a percent 0.0 to 1.0 function getStringAlphaPercent(color) local alpha if (string.find(color, ",") ~= nil) then rgbIt = string.gmatch(color,"%d+") rgbTable = {} for match in rgbIt do table.insert(rgbTable, match) end if (#rgbTable < 4) then alpha = 1 else alpha = (rgbTable[4] / 255) alpha = string.format("%.2f",alpha) end else if (string.len(color)) > 6 then alpha = hexToDec(string.sub(color,7,8)) alpha = (alpha / 255) alpha = string.format("%.2f",alpha) else alpha = 1 end end return tonumber(alpha) end -- converts a hexadecimal string to a decimal number function hexToDec(hexNum) hexNum = string.lower(hexNum) sum = 0 for i=1,#hexNum,1 do sum = sum + (findHexChar(string.sub(hexNum,i,i)) * 16^(#hexNum-i)) end return sum end -- converts decimal number to hexadecimal string function decToHex(decNum) local result = {} while (decNum > 0) do table.insert(result, 1, hexChars[math.fmod(decNum, 16)]) decNum = math.floor(decNum / 16) end return table.concat(result,'',1,#result) end -- linearly searches hexChar array for a given character and returns its index function findHexChar(char) for i=0,#hexChars do if hexChars[i] == char then return i end end return -1 end -- ========================================================================================== -- function rewrites appearance.txt and settings.txt with default values function resetAllVariables() settingsDefaults = { { 'Addr', 'Input Address' }, { 'Payment', 'Input Payment Amount' }, } appearanceDefaults = { { 'numColor', '250,250,250,155' }, { 'barColor', '100,100,100,51' }, { 'textColor', '250,250,250,230' }, { 'TextMainColor', '#*textMainColor*#' }, { 'radius', '36' }, { 'orient', 'left' } } for _,t in pairs(settingsDefaults) do SKIN:Bang('!WriteKeyValue', 'Variables', t[1], t[2], '#@#Settings.txt') end for _,t in pairs(appearanceDefaults) do SKIN:Bang('!WriteKeyValue', 'Variables', t[1], t[2], '#@#Appearance.txt') end SKIN:Bang('!RefreshGroup', 'UBQ') print('C2: all user settings reset to default') end
local THNN = require 'nn.THNN' local BCECriterion, parent = torch.class('nn.BCECriterion', 'nn.Criterion') function BCECriterion:__init(weights, sizeAverage) parent.__init(self) if sizeAverage ~= nil then self.sizeAverage = sizeAverage else self.sizeAverage = true end if weights ~= nil then assert(weights:dim() == 1, "weights input should be 1-D Tensor") self.weights = weights end end function BCECriterion:__len() return self.weights and #self.weights or 0 end function BCECriterion:updateOutput(input, target) -- - log(input) * target - log(1 - input) * (1 - target) assert( input:nElement() == target:nElement(), "input and target size mismatch") self.output_tensor = self.output_tensor or input.new(1) local weights = self.weights if weights ~= nil and target:dim() ~= 1 then weights = self.weights:view(1, target:size(2)):expandAs(target) end input.THNN.BCECriterion_updateOutput( input:cdata(), target:cdata(), self.output_tensor:cdata(), self.sizeAverage, THNN.optionalTensor(weights) ) self.output = self.output_tensor[1] return self.output end function BCECriterion:updateGradInput(input, target) -- - (target - input) / ( input (1 - input) ) assert( input:nElement() == target:nElement(), "input and target size mismatch") local weights = self.weights if weights ~= nil and target:dim() ~= 1 then weights = self.weights:view(1, target:size(2)):expandAs(target) end input.THNN.BCECriterion_updateGradInput( input:cdata(), target:cdata(), self.gradInput:cdata(), self.sizeAverage, THNN.optionalTensor(weights) ) return self.gradInput end
--[[ desc: Battle, a component for battle business. author: Musoucrow since: 2018-3-29 alter: 2019-4-10 ]]-- local _TABLE = require("lib.table") local _RESOURCE = require("lib.resource") local _RESMGR = require("actor.resmgr") local _Point3 = require("graphics.drawunit.point3") local _Caller = require("core.caller") ---@class Actor.Component.Battle ---@field public camp int @1=we, 2=enemy ---@field public shaker Util.Gear.Shaker ---@field public pureColorTweener Util.Gear.Tweener ---@field public dmgSoundDatas table<number, SoundData> ---@field public dieSoundDatas table<number, SoundData> ---@field public beatenCaller Core.Caller ---@field public deadCaller Core.Caller ---@field public deadProcess int ---@field public overKill boolean ---@field public banCountMap table<string, int> ---@field public hasEffect boolean ---@field public hasDestroy boolean local _Battle = require("core.class")() local _emptyTab = {} function _Battle.HandleData(data) if (data.dmgSound) then data.dmgSound = _RESOURCE.Recur(_RESMGR.GetSoundData, data.dmgSound) end if (data.dieSound) then data.dieSound = _RESOURCE.Recur(_RESMGR.GetSoundData, data.dieSound) end end function _Battle:Ctor(data, param) self.camp = param.camp or data.camp or 0 self.deadProcess = 0 self.overKill = false self.dmgSoundDatas = data.dmgSound self.dieSoundDatas = data.dieSound self.beatenCaller = _Caller.New() self.deadCaller = _Caller.New() self.hasEffect = data.hasEffect self.hasDestroy = data.hasDestroy if (self.hasEffect == nil) then self.hasEffect = true end if (self.hasDestroy == nil) then self.hasDestroy = true end local banCountMap = data.banCountMap or _emptyTab self.banCountMap = { stun = banCountMap.stun or 0, flight = banCountMap.flight or 0, overturn = banCountMap.overturn or 0, dmgSound = banCountMap.dmgSound or 0, attack = banCountMap.attack or 0, turn = banCountMap.turn or 0, die = banCountMap.die or 0, hide = banCountMap.hide or 0, pure = banCountMap.pure or 0, } self.beatenConfig = { position = _Point3.New(true), damage = 0, direction = 0, isPhysical = false, isCritical = false, isTurn = false, element = "", entity = nil, ---@type Actor.Entity attack = nil, ---@type Actor.Gear.Attack } end return _Battle
return {'udding'}
local Help = {} local function is_heading(line, char) if #line == 0 then return false end for i = 1, #line do local c = line:sub(i, i) if c ~= char then return false end end return true end function Help.get_headings(filepath, start, total) local headings = {} local index = start local last_line = '' while index <= total do local line = vim.fn.getline(index) if is_heading(last_line, '=') then local matches = vim.regex('\\*\\S\\+\\*$'):match_str(line) if matches ~= nil then local heading = '' local i = 1 while i < matches do heading = heading .. line:sub(i, i) i = i + 1 end table.insert(headings, { heading = vim.trim(heading), line = index, path = filepath, }) end end last_line = line index = index + 1 end return headings end function Help.ts_get_headings(filepath, bufnr) local ts = vim.treesitter local query = [[ (headline (word)) @headline_title ]] local parsed_query = ts.parse_query('help', query) local parser = ts.get_parser(bufnr, 'help') local root = parser:parse()[1]:root() local start_row, _, end_row, _ = root:range() local headings = {} for _, node in parsed_query:iter_captures(root, bufnr, start_row, end_row) do local row, _ = node:range() local line = vim.fn.getline(row + 2) table.insert(headings, { heading = vim.trim(line), line = row + 2, path = filepath, }) end return headings end return Help
local vim = vim local api = vim.api local globals = require 'vimwiki_server/globals' local g = require 'vimwiki_server/lib/graphql' local u = require 'vimwiki_server/lib/utils' local v = require 'vimwiki_server/lib/vars' local M = {} -- Synchronous function to execute code under cursor function M.execute_under_cursor() local bridge = globals.bridge local tmp = globals.tmp local path = tmp:get_current_buffer_tmp_path() local reload = true local offset = u.cursor_offset() local query = g.query([[ { page(path: "$path", reload: $reload) { nodeAtOffset(offset: $offset) { element { ... on PreformattedText { language lines input: metadataForKey(key: ":input") output: metadataForKey(key: ":output") } } region { offset len } nextSibling { element { ... on Paragraph { elements { ... on MultiLineComment { lines region { offset len } } } } } } } } } ]], {path=path, reload=reload, offset=offset}) local res = bridge:send_wait_ok(query) if res then local language = u.get(res, 'data.page.nodeAtOffset.element.language') local lines = u.get(res, 'data.page.nodeAtOffset.element.lines') local input = u.get(res, 'data.page.nodeAtOffset.element.input') local output = u.get(res, 'data.page.nodeAtOffset.element.output') local region = u.get(res, 'data.page.nodeAtOffset.region') local comment = find_first_comment( u.get(res, 'data.page.nodeAtOffset.nextSibling.element.elements') ) local result = nil -- If we are given input, interpolate within the code to execute if lines and input then lines = interpolate_lines(lines, input) end -- Evaluate our result based on the language local result = do_eval(language, lines) -- Display our result somewhere return output_result(result, output, region, comment) end end function find_first_comment(elements) if elements then for _, element in ipairs(elements) do if element.lines and element.region then return element end end end return nil end function interpolate_lines(lines, input) local lines_str = table.concat(lines, '\n') local input_val = api.nvim_buf_get_var(0, 'vimwiki_server#internal#result#'..input) for i, line in ipairs(lines) do lines[i] = u.interpolate_vars(line, {input = input_val}) end return lines end function do_eval(language, lines) local result = nil -- Special case for vim since we want to evalute it within our active -- neovim session if language == 'vim' and lines then local code = table.concat(lines or {}, '\n') result = u.nvim_exec(code, true) -- Otherwise, if we know the language, try to evaluate it elseif language ~= nil and lines then local cmd = v.vimwiki_server_code(language) if cmd then result = api.nvim_call_function('system', {cmd, lines}) end -- Finally, if we don't know, we can default to a language if specified elseif lines then local cmd = v.vimwiki_server_code_default() if cmd then result = api.nvim_call_function('system', {cmd, lines}) end end return result end function inject_result_into_buffer(result, code_region, comment) -- If our result is made up of more than one line post-trim, we want to -- show it on its own lines between the comment syntax, otherwise we want -- to show it inline with a single space delimiter local result_str = vim.trim(tostring(result)) local sep = (string.find(result_str, '\n', 1, true) ~= nil) and '\n' or ' ' local text = '%%+RESULT+'..sep..result_str..sep..'+%%' -- Check if we have an element below our code that starts with a comment -- containing our result. If we do, then we want to replace that comment with -- a new version containing our result. If we do not, we want to append a -- blank line after our code followed by a line containing the comment with -- our result. if comment and u.starts_with(comment.lines[1], 'RESULT+') then u.change_in_buffer(comment.region.offset, comment.region.len, text) elseif code_region.offset and code_region.len then local line_nums = u.get_line_numbers(code_region.offset, code_region.len) local last_line_num = line_nums[#line_nums] if last_line_num then -- Jump to the last line of our code block api.nvim_command(tostring(last_line_num)) -- Insert two blank lines api.nvim_command('normal! o') api.nvim_command('normal! o') -- Replace second blank line with our text u.change_in_buffer(code_region.offset + code_region.len + 1, 1, text) end end end function output_result(result, output, code_region, comment) if result and api.nvim_get_vvar('shell_error') == 0 then -- If given a specific location for output, store it if output then local result = vim.trim(u.escape_newline(result)) api.nvim_buf_set_var(0, 'vimwiki_server#internal#result#'..output, result) -- Otherwise, output it into our buffer else return inject_result_into_buffer(result, code_region, comment) end else api.nvim_err_writeln(tostring(result)) end end return M
slot2 = "BaseOnlinePlayerCcsGrid" BaseOnlinePlayerCcsGrid = class(slot1) BaseOnlinePlayerCcsGrid.onCreationComplete = function (slot0) slot13 = slot0.onUserData createSetterGetter(slot2, slot0, "userData", nil, nil, nil, nil, handler(slot11, slot0)) slot3 = slot0 slot0.onUserData(slot2) end BaseOnlinePlayerCcsGrid.onUserData = function (slot0) slot4 = slot0._userData ~= nil slot0.setVisible(slot2, slot0) if slot0._userData then slot6 = slot0._userData.wGender slot0.controller.setHeadBg(slot2, slot0.controller, slot0.head, GAME_STATE.BATTLE) slot4 = slot0._userData slot0.head.setUserData(slot2, slot0.head) slot3 = slot0.txtName_tf slot9 = 2 slot0.txtName_tf.setHtmlText(slot2, StringUtil.truncate(GAME_STATE.BATTLE, slot0._userData.szNickName, 8, nil)) if slot0.head.mask.mask then if not B_HEADCLIPPING then slot4 = slot0.head.mask slot0.head.checkMask2(slot2, slot0.head) else slot4 = false slot0.head.mask.mask.setVisible(slot2, slot0.head.mask.mask) end end slot1 = "" if slot0.model.onlineItemScoreNumRes then slot6 = 1 slot1 = HtmlUtil.createArtNumWithHansUnits(slot3, slot0._userData.lScore, slot0.model.onlineItemScoreNumRes) else slot5 = 1 slot1 = MathUtil.cookNumWithHansUnits(slot3, slot0._userData.lScore) end slot5 = slot1 slot0.txtScore_tf.setHtmlText(slot3, slot0.txtScore_tf) end end BaseOnlinePlayerCcsGrid.destroy = function (slot0) slot3 = slot0.head slot0.head.destroy(slot2) slot3 = slot0.txtName_tf slot0.txtName_tf.destroy(slot2) slot3 = slot0.txtScore_tf slot0.txtScore_tf.destroy(slot2) end return
quest DEscape_hourseeffect begin state start begin ----- Asker At ----- when 50052.use begin if get_time()<=pc.getqf("15saniye") then syschat("<System> 15 saniye gecmeden atini Cagiramassin!") else pc.setqf("15saniye", get_time()+15) cmdchat("DEscapeZirhliAt") end end ----- Asker At ----- when 50053.use begin if get_time()<=pc.getqf("15saniye") then syschat("<System> 15 saniye gecmeden atini Cagiramassin!") else pc.setqf("15saniye", get_time()+15) cmdchat("DEscapeAskerAt") end end end end
function Ichoron_OnCombat(Unit, Event) Unit:SendChatMessage(12, 0, "Water Gun, Water Blast, Ha Ha Ha. Pokemon have nothing on me.") Unit:RegisterEvent("Ichoron_Drained", 5000, 20) Unit:RegisterEvent("Ichoron_Frenzy1", 10000, 20) Unit:RegisterEvent("Ichoron_ProtectiveBubble", 15000, 20) Unit:RegisterEvent("Ichoron_Frenzy2", 20000, 20) Unit:RegisterEvent("Ichoron_WaterBlast1", 25000, 20) Unit:RegisterEvent("Ichoron_WaterBoltVolley1", 30000, 20) Unit:RegisterEvent("Ichoron_WaterBlast2", 35000, 20) Unit:RegisterEvent("Ichoron_WaterBoltVolley2", 40000, 20) end function Ichoron_Drained(Unit, Event) Unit:CastSpell(59820, Unit:GetRandomPlayer(4)) end function Ichoron_Frenzy1(Unit, Event) Unit:CastSpell(27897, Unit:GetMainTank()) end function Ichoron_ProtectiveBubble(Unit, Event) Unit:CastSpell(54306, Unit:GetRandomPlayer(4)) end function Ichoron_Frenzy2(Unit, Event) Unit:CastSpell(27897, Unit:GetRandomPlayer(6)) end function Ichoron_WaterBlast1(Unit, Event) Unit:CastSpell(54237, Unit:GetRandomPlayer(7)) end function Ichoron_WaterBoltVolley1(Unit, Event) Unit:CastSpell(59266, Unit:GetRandomPlayer(4)) end function Ichoron_WaterBlast2(Unit, Event) Unit:CastSpell(59520, Unit:GetMainTank()) end function Ichoron_WaterBoltVolley2(Unit, Event) Unit:CastSpell(59521, Unit:GetRandomPlayer(7)) end function Ichoron_OnLeaveCombat(Unit, Event) Unit:RemoveEvents() Unit:SendChatMessage(12, 0, "Yeah it's better that you go back to playing pokemon!!!") end function Ichoron_OnDied(Unit, Event) Unit:RemoveEvents() Unit:SendChatMessage(12, 0, "Pokemon Suck!!!!!") end function Ichoron_OnKilledTarget(Unit, Event) Unit:SendChatMessage(12, 0, "Take that you Pokemon Lover!!!!") end RegisterUnitEvent(29313, 1, "Ichoron_OnCombat") RegisterUnitEvent(29313, 2, "Ichoron_OnLeaveCombat") RegisterUnitEvent(29313, 3, "Ichoron_OnKilledTarget") RegisterUnitEvent(29313, 4, "Ichoron_OnDied")
-- list.lua list_remove_first_of = function(cur, val) if cur == nil then return nil end if cur.car == val then return cur.cdr else cur.cdr = list_remove_first_of(cur.cdr, val) end return cur end list = function() return { head = nil ,prepend = function(ls, val) ls.head = {car = val, cdr = ls.head} end ,rm = function(ls, val) ls.head = list_remove_first_of(ls.head, val) end ,for_each = function(ls, p) local cur = ls.head while cur do p(cur.car) cur = cur.cdr end end ,handshake = function(ls, p) local cur1 = ls.head local cur2 while cur1 do cur2 = cur1.cdr while cur2 do p(cur1.car, cur2.car) cur2 = cur2.cdr end cur1 = cur1.cdr end end } end elems = function(ls) local cur = ls.head return function() if cur then elem = cur.car cur = cur.cdr return elem else return nil end end end
require ("state_handler") -- Include Simple Tiled Implementation library local sti = require "sti" local tx, ty, sx, sy, map function love.load() map = sti("assets/maps/map_test.lua") tx, ty = 0, 0 sx, sy = 1.5, 1.5 -- Calque des objets dynamiques (au-dessus du dernier ajouté) local layer = map:addCustomLayer("Sprites", #map.layers + 1) -- Get Player spawn point local player for i, object in pairs(map.objects) do if object.name == "Player" then player = object break end end -- player object local sprite = love.graphics.newImage("assets/images/sprites/player/joueurl10c0.png") layer.player = { sprite = sprite, x = player.x, y = player.y, ox = sprite:getWidth() / 2, oy = sprite:getHeight() / 1.05, } -- Draw player layer.draw = function(self) love.graphics.draw( self.player.sprite, math.floor(self.player.x), math.floor(self.player.y), 0, 1, 1, self.player.ox, self.player.oy ) -- Point the position love.graphics.setPointSize(5) love.graphics.points(math.floor(self.player.x), math.floor(self.player.y)) end map:removeLayer("spawnpoints") end function love.update(dt) map:update(dt) end function love.draw() w = love.graphics.getWidth() h = love.graphics.getHeight() map:resize(w, h) map:draw(tx, ty) end