content
stringlengths
5
1.05M
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG Bugtracker: https://forum.404rq.com/bug-reports Suggestions: https://forum.404rq.com/mta-servers-development Donations: https://www.404rq.com/donations Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- Global client properites p_account = nil p_loggedIn = false sec_login_attempts = 0 login_cooldown = nil -- Display status messages from the server addEvent("GTWaccounts:onStatusReceive", true) addEventHandler("GTWaccounts:onStatusReceive", root, function(msg, statusCode) if statusCode == -1 then guiLabelSetColor(labelInfo, 255, 0, 0) elseif statusCode == 0 then guiLabelSetColor(labelInfo, 255, 255, 0) elseif statusCode == 1 then guiLabelSetColor(labelInfo, 0, 255, 0) end guiSetText(labelInfo, msg) end) -- Setup the login GUI (GTWgui must be running) function make_login() x,y = guiGetScreenSize() window = exports.GTWgui:createWindow((x-600)/2, (y-450)/2, 600, 450, "GTW-RPG v4.0 - beta", false ) loginButton = guiCreateButton(480,400,110,40,"Login",false,window) registerButton = guiCreateButton(368,400,110,40,"Register",false,window) introButton = guiCreateButton(256,400,110,40,"View intro",false,window) updatesButton = guiCreateButton(10,400,116,40,"What's new",false,window) labelUser = guiCreateLabel(30, 40, 290, 25, "Username:", false, window) labelPwrd = guiCreateLabel(30, 100, 290, 25, "Password:", false, window) textUser = guiCreateEdit(30,65,290,25,"",false,window) textPwrd = guiCreateEdit(30,125,290,25,"",false,window) labelInfo = guiCreateLabel(30, 210, 290, 80, "", false, window) checkBoxUser = guiCreateCheckBox(30, 160, 290, 20, "Remember Username", false, false, window) checkBoxPwrd = guiCreateCheckBox(30, 180, 290, 20, "Remember Password", false, false, window) -- Shaders control panel labelShaders = guiCreateLabel(360, 40, 230, 25, "Select shaders:", false, window) checkBoxDetail = guiCreateCheckBox(360, 80, 290, 20, "Enable detail shader", false, false, window) checkBoxContrast = guiCreateCheckBox(360, 100, 290, 20, "Enable contrast shader", false, false, window) checkBoxWater = guiCreateCheckBox(360, 120, 290, 20, "Enable water shader", false, false, window) checkBoxCarPaint = guiCreateCheckBox(360, 140, 290, 20, "Enable car reflection shader", false, false, window) labelInfoRight = guiCreateLabel(360, 180, 290, 170, [[Welcome! to sign up, choose account name and password then click register. To login, enter credentials then click login. You may also select shaders to make the game look more realistic or disable shaders for better FPS. Regards: RageQuit 404 community Website: https://404rq.com]], false, window) guiEditSetMasked(textPwrd, true) guiSetInputEnabled(true) -- Friends invite bonus labelFacc = guiCreateLabel(30, 300, 190, 25, "Send your friend a gift", false, window) textFacc = guiCreateEdit(30,325,260,25,"",false,window) faccButtonHelp = guiCreateButton(290,325,30,25,"?",false,window) -- Set GUI font exports.GTWgui:setDefaultFont(loginButton, 10) exports.GTWgui:setDefaultFont(registerButton, 10) exports.GTWgui:setDefaultFont(introButton, 10) exports.GTWgui:setDefaultFont(updatesButton, 10) exports.GTWgui:setDefaultFont(labelUser, 10) exports.GTWgui:setDefaultFont(labelPwrd, 10) exports.GTWgui:setDefaultFont(labelInfo, 10) exports.GTWgui:setDefaultFont(textUser, 9) exports.GTWgui:setDefaultFont(textPwrd, 9) exports.GTWgui:setDefaultFont(checkBoxUser,10) exports.GTWgui:setDefaultFont(checkBoxPwrd, 10) exports.GTWgui:setDefaultFont(labelFacc, 10) exports.GTWgui:setDefaultFont(textFacc, 10) exports.GTWgui:setDefaultFont(faccButtonHelp, 10) exports.GTWgui:setDefaultFont(checkBoxDetail, 10) exports.GTWgui:setDefaultFont(checkBoxContrast, 10) exports.GTWgui:setDefaultFont(checkBoxCarPaint, 10) exports.GTWgui:setDefaultFont(checkBoxWater, 10) exports.GTWgui:setDefaultFont(labelInfoRight, 10) exports.GTWgui:showGUICursor(true) -- Load login details from xml local f = xmlLoadFile('@data.xml', 'account') if f then local user = xmlNodeGetAttribute(xmlFindChild(f, 'user', 0), 'value') or "" local pass = xmlNodeGetAttribute(xmlFindChild(f, 'pass', 0), 'value') or "" local sh_detail = xmlNodeGetAttribute(xmlFindChild(f, 'detail', 0), 'value') or "" local sh_contrast = xmlNodeGetAttribute(xmlFindChild(f, 'contrast', 0), 'value') or "" local sh_water = xmlNodeGetAttribute(xmlFindChild(f, 'water', 0), 'value') or "" local sh_carpaint = xmlNodeGetAttribute(xmlFindChild(f, 'carpaint', 0), 'value') or "" guiSetText(textUser, tostring(user)) guiSetText(textPwrd, tostring(pass)) if user ~= "" then guiCheckBoxSetSelected(checkBoxUser, true) end if pass ~= "" then guiCheckBoxSetSelected(checkBoxPwrd, true) end if sh_detail == "enabled" then guiCheckBoxSetSelected(checkBoxDetail, true) exports.shader_detail:toggleShaderDetail(true) else exports.shader_detail:toggleShaderDetail(false) end if sh_contrast == "enabled" then guiCheckBoxSetSelected(checkBoxContrast, true) exports.shader_contrast:toggleShaderContrast(true) else exports.shader_contrast:toggleShaderContrast(false) end if sh_water == "enabled" then guiCheckBoxSetSelected(checkBoxWater, true) exports.shader_water:toggleShaderWater(true) else exports.shader_water:toggleShaderWater(false) end if sh_carpaint == "enabled" then guiCheckBoxSetSelected(checkBoxCarPaint, true) exports.shader_car_paint_reflect:toggleShaderCarPaint(true) else exports.shader_car_paint_reflect:toggleShaderCarPaint(false) end end end -- Login GUI click events addEventHandler("onClientGUIClick",root,function() -- On login (asyncron function) if source == loginButton then if isTimer(login_cooldown) then return end guiLabelSetColor(labelInfo, 255, 255, 255) guiSetText(labelInfo, "Attempting to login... please wait") fadeCamera(false, 1) setTimer(triggerServerEvent, 1100, 1, "GTWaccounts:attemptClientLogin", localPlayer, guiGetText(textUser), guiGetText(textPwrd)) if sec_login_attempts > 2 then -- Kick after 3 failed login attempts triggerServerEvent("GTWaccounts:kickClientSpammer", localPlayer) end sec_login_attempts = sec_login_attempts + 1 login_cooldown = setTimer(function() toggle_gui_enable(true) end, 3000, 1) toggle_gui_enable(false) -- On registration elseif source == registerButton then triggerServerEvent("GTWaccounts:onClientAttemptRegistration", localPlayer, guiGetText(textUser), guiGetText(textPwrd), guiGetText(textFacc)) -- On view intro start elseif source == introButton then addEventHandler("onClientRender", root, view_gtw_intro) guiSetVisible(window, false) -- On view updates button click (requires GTWupdates) elseif source == updatesButton then exports.GTWupdates:viewUpdateListGUI() -- On help request click elseif source == faccButtonHelp then guiSetText(labelInfo, "Enter your friends account name \nto send him/her an invite bonus\nof $4'000 as a reward.") guiLabelSetColor(labelInfo, 255, 255, 255) -- Toggle shaders elseif source == checkBoxDetail then exports.shader_detail:toggleShaderDetailCMD() elseif source == checkBoxContrast then exports.shader_contrast:toggleShaderContrastCMD() elseif source == checkBoxWater then exports.shader_water:toggleShaderWaterCMD() elseif source == checkBoxCarPaint then exports.shader_car_paint_reflect:toggleShaderCarPaintCMD() end end) -- Enable/disable buttons function toggle_gui_enable(state) guiSetEnabled(loginButton, state) guiSetEnabled(registerButton, state) guiSetEnabled(updatesButton, state) guiSetEnabled(faccButtonHelp, state) guiSetEnabled(textUser, state) guiSetEnabled(textPwrd, state) guiSetEnabled(textFacc, state) end -- On client attempt login addEvent("GTWaccounts:onClientPlayerLogin", true) addEventHandler("GTWaccounts:onClientPlayerLogin", root, function(acnt) local f = xmlCreateFile("@data.xml", "account") local user, pass = "", "" if guiCheckBoxGetSelected(checkBoxUser) then user = guiGetText(textUser) end if guiCheckBoxGetSelected(checkBoxPwrd) then pass = guiGetText(textPwrd) end xmlNodeSetAttribute(xmlCreateChild(f, "user"), "value", user) xmlNodeSetAttribute(xmlCreateChild(f, "pass"), "value", pass) -- Save shaders if guiCheckBoxGetSelected(checkBoxDetail) then xmlNodeSetAttribute(xmlCreateChild(f, "detail"), "value", "enabled") else xmlNodeSetAttribute(xmlCreateChild(f, "detail"), "value", "disabled") end if guiCheckBoxGetSelected(checkBoxContrast) then xmlNodeSetAttribute(xmlCreateChild(f, "contrast"), "value", "enabled") else xmlNodeSetAttribute(xmlCreateChild(f, "contrast"), "value", "disabled") end if guiCheckBoxGetSelected(checkBoxWater) then xmlNodeSetAttribute(xmlCreateChild(f, "water"), "value", "enabled") else xmlNodeSetAttribute(xmlCreateChild(f, "water"), "value", "disabled") end if guiCheckBoxGetSelected(checkBoxCarPaint) then xmlNodeSetAttribute(xmlCreateChild(f, "carpaint"), "value", "enabled") else xmlNodeSetAttribute(xmlCreateChild(f, "carpaint"), "value", "disabled") end xmlSaveFile(f) xmlUnloadFile(f) guiSetVisible(window, false) exports.GTWgui:showGUICursor(false) guiSetInputEnabled(false) showChat(true) -- Set account obtained from the server and login status p_loggedIn = true p_account = acnt end) -- Exported functions to check if logged in or to obtain account name function getPlayerAccount() return p_account or "Guest" end function isClientLoggedIn() return p_loggedIn end -- Get a players ID function getPlayerId(p) local id = nil for i, v in pairs(getElementsByType('player')) do if v == p then id = i break end end return id end -- Display login screen to players who isn't currently logged in addEventHandler("onClientResourceStart", resourceRoot, function() if not getElementData(localPlayer, "isLoggedIn") then exports.GTWtopbar:dm("Welcome! please read the instructions before trying to register", 0,200,0) setTimer(make_login, 500, 1) setBlurLevel(0) showChat(false) triggerServerEvent("GTWaccounts.onClientSend",localPlayer) else p_loggedIn = true end end)
print("Cubic Pixel Works")
local combat = Combat() combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE) combat:setParameter(COMBAT_PARAM_AGGRESSIVE, 0) local condition = Condition(CONDITION_LIGHT) condition:setParameter(CONDITION_PARAM_LIGHT_LEVEL, 8) condition:setParameter(CONDITION_PARAM_LIGHT_COLOR, 215) condition:setParameter(CONDITION_PARAM_TICKS, (60 * 33 + 10) * 1000) combat:setCondition(condition) function onCastSpell(creature, var) return combat:execute(creature, var) end
-- Spectate local spectating = nil local sx, sy = guiGetScreenSize () local randomButton = guiCreateButton ( sx / 2 - 100, sy - 50, 110, 30, "Random Player", false ) local backButton = guiCreateButton ( sx / 2 + 15, sy - 50, 110, 30, "Back", false ) guiSetVisible( backButton, false ) guiSetVisible( randomButton, false ) local oldDim = 0 local oldInt = 0 local timerChecker function onStopSpectating () removeEventHandler( "onClientPreRender", root, spectateRender ) local x, y, z = getElementPosition( localPlayer ) setElementPosition( localPlayer, x, y, z +1 ) guiSetVisible( backButton, false ) guiSetVisible( randomButton, false ) setElementFrozen ( localPlayer, false ) setElementInterior(localPlayer, oldInt) setElementDimension(localPlayer, oldDim) setCameraTarget ( localPlayer ) spectating = nil showCursor( true ) if (isTimer(timerChecker)) then killTimer(timerChecker) timerChecker = nil end end addEventHandler ( "onClientGUIClick", backButton, onStopSpectating ) function randomSpectatePlayer () local allPlayers = getElementsByType ( "player" ) thePlayer = allPlayers[math.random(1,#allPlayers)] if not ( thePlayer == localPlayer ) then setElementFrozen ( localPlayer, true ) oldDim = getElementInterior(localPlayer) oldInt = getElementDimension(localPlayer) spectating = thePlayer setCameraTarget ( thePlayer ) setElementInterior(localPlayer, getElementInterior(thePlayer)) setElementDimension(localPlayer, getElementDimension(thePlayer)) showCursor( false ) if (isTimer(timerChecker)) then killTimer(timerChecker) timerChecker = nil end timerChecker = setTimer(function() setElementInterior(localPlayer, getElementInterior(spectating)) setElementDimension(localPlayer, getElementDimension(spectating)) end, 1000, 0) else randomSpectatePlayer () end end addEventHandler ( "onClientGUIClick", randomButton, randomSpectatePlayer ) function onPlayerSpecate ( thePlayer ) if ( thePlayer ) and not ( spectating ) then if ( isElement( thePlayer ) ) then if not ( thePlayer == localPlayer ) then setElementFrozen ( localPlayer, true ) oldDim = getElementInterior(localPlayer) oldInt = getElementDimension(localPlayer) setCameraTarget ( thePlayer ) guiSetVisible( backButton, true ) guiSetVisible( randomButton, true ) setElementInterior(localPlayer, getElementInterior(thePlayer)) setElementDimension(localPlayer, getElementDimension(thePlayer)) showCursor( false ) spectating = thePlayer addEventHandler( "onClientPreRender", root, spectateRender ) if (isTimer(timerChecker)) then killTimer(timerChecker) timerChecker = nil end timerChecker = setTimer(function() setElementInterior(localPlayer, getElementInterior(spectating)) setElementDimension(localPlayer, getElementDimension(spectating)) end, 1000, 0) else exports.NGCdxmsg:createNewDxMessage("You can't spectate yourself!", 225, 0, 0) end end end end addEventHandler( "onClientPlayerQuit", root, function () if ( spectating ) then if ( spectating == source ) then guiSetVisible( backButton, false ) guiSetVisible( randomButton, false ) local x, y, z = getElementPosition( localPlayer ) setElementPosition( localPlayer, x, y, z +1 ) setElementInterior(localPlayer, oldInt) setElementDimension(localPlayer, oldDim) setCameraTarget ( localPlayer ) setElementFrozen ( localPlayer, false ) spectating = nil showCursor( true ) removeEventHandler( "onClientPreRender", root, spectateRender ) if (isTimer(timerChecker)) then killTimer(timerChecker) timerChecker = nil end end end end ) function spectateRender () if ( spectating ) then dxDrawText ( "Spectating: "..getPlayerName ( spectating ), sx - 170, 200, sx - 170, 200, tocolor ( 255, 255, 255, 255 ), 1 ) end end
import "UnityEngine" import "UnityEngine.UI" import "UnityEngine.EventSystems" local scriptInclude = { } function include(name) table.insert(scriptInclude, name) end function progress(value, text) XBootstrap.GetSingleton():SetProgress(value, text) if value >= 1.0 then XBootstrap.GetSingleton():Clearup() end end function DoRequire(done) for name, v in pairs(package.loaded) do package.loaded[name] = nil end local ret, msg = pcall(require, "requires") if not ret then Debug.LogError( string.format("critial error! requires failed: %s", msg) ) end local totalInclude = #scriptInclude for idx, mod in ipairs(scriptInclude) do local ret, msg = pcall(require, mod) if not ret then error(string.format("critial error! %s requires failed: %s", mod, msg)) end progress(0.1 + idx / totalInclude * 0.7, mod) Yield() end Yield() progress(0.8, tostring(totalInclude)) if done then done() end return ret end function main() math.randomseed(os.time()) local co = coroutine.create(DoRequire) coroutine.resume(co, function() OneTimeInitScene() end) return true end function OneTimeInitScene() XRootContext.GetSingleton():Startup() -- load finished progress(1.0, resmng.LangText(resmng.LG_VERSION_DOWNLOAD)) end function exit() XRootContext.GetSingleton():Shutdown() end
local tilemap = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 0, 0, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 0, 0, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, } local tile_w, tile_h = 16, 16 local tilemap_w, tilemap_h = 20, 15 local tileset_w = 4 local tileset_x, tileset_y = 6, 0 local player_x, player_y = tilemap_w/2*tile_w, tilemap_h/2*tile_h local player_speed = 30 local check_x1, check_y1 = 0, 0 local check_x2, check_y2 = 0, 0 local check_x3, check_y3 = 0, 0 local check_x4, check_y4 = 0, 0 function tile_at(x, y) local position = y*tilemap_w+x+1 if position > 0 and position <= tilemap_w*tilemap_h then return tilemap[position] end return 0 end -- Check each corner of a tile_wxtile_h rectangle -- at to_x, to_y against the tilemap function can_move(to_x, to_y) local x1, y1 = math.floor(to_x/tile_w), math.floor(to_y/tile_h) local x2, y2 = x1+1, y1 local x3, y3 = x1+1, y1+1 local x4, y4 = x1, y1+1 check_x1, check_y1 = x1, y1 check_x2, check_y2 = x2, y2 check_x3, check_y3 = x3, y3 check_x4, check_y4 = x4, y4 return tile_at(x1, y1) == 1 and tile_at(x2, y2) == 1 and tile_at(x3, y3) == 1 and tile_at(x4, y4) == 1 end function init() -- Color 0 is transparent mask(0) end function draw() local x, y = 0, 0 -- Draws tilemap for _, tile in ipairs(tilemap) do local tile_x = tile%tileset_w+tileset_x local tile_y = tile/tileset_w+tileset_y spr(x, y, tile_x, tile_y) x += tile_w if x >= tilemap_w*tile_w then x = 0 y += tile_h end end -- Draws player spr(player_x, player_y, 6, 1) -- Draws collision check rect(check_x1*tile_w, check_y1*tile_h, tile_w, tile_h, 15) rect(check_x2*tile_w, check_y2*tile_h, tile_w, tile_h, 15) rect(check_x3*tile_w, check_y3*tile_h, tile_w, tile_h, 15) rect(check_x4*tile_w, check_y4*tile_h, tile_w, tile_h, 15) -- Debug info print(tostring(math.floor(player_x)) .. ', ' .. tostring(math.floor(player_y)), 0, 0) end function update(dt) local movement = dt*player_speed if btd(UP) then if can_move(player_x, player_y-movement) then player_y -= movement end end if btd(DOWN) then if can_move(player_x, player_y+movement) then player_y += movement end end if btd(LEFT) then if can_move(player_x-movement, player_y) then player_x -= movement end end if btd(RIGHT) then if can_move(player_x+movement, player_y) then player_x += movement end end end
function love.conf(t) t.console = true t.window.width = 1440 t.window.height = 720 end
PAM_EXTENSION.name = "terrortown_support" PAM_EXTENSION.enabled = true function PAM_EXTENSION:OnInitialize() -- terrortown support if GAMEMODE_NAME ~= "terrortown" then return end -- Notify PAM that the round has ended hook.Add("TTTEndRound", "PAM_RoundEnded", function() PAM.EndRound() end) -- ttt2/ttt2 if TTT2 then hook.Add("TTT2LoadNextMap", "PAM_Autostart_TTT2", function(nextmap, rounds_left, time_left) PAM.Start() return true end) return end -- terrortown function CheckForMapSwitch() local rounds_left = math.max(0, GetGlobalInt("ttt_rounds_left", 6) - 1) SetGlobalInt("ttt_rounds_left", rounds_left) local time_left = math.max(0, (GetConVar("ttt_time_limit_minutes"):GetInt() * 60) - CurTime()) if rounds_left <= 0 or time_left <= 0 then timer.Stop("end2prep") if PAM.state == PAM.STATE_DISABLED then PAM.Start() end end end end
---@type Plugin local plugin = ... local function moveItem(item, difference) item.pos:add(difference) item.rigidBody.pos:add(difference) end local function teleportHumanWithItems(man, pos) local oldPos = man.pos:clone() oldPos:mult(-1.0) local difference = pos:clone() difference:add(oldPos) man:teleport(pos) for _, item in pairs({ man.leftHandItem, man.rightHandItem }) do moveItem(item, difference) end end plugin.commands['/find'] = { info = 'Teleport to a player.', usage = '/find <phoneNumber/name>', canCall = function (ply) return ply.isAdmin end, ---@param ply Player ---@param man Human? ---@param args string[] call = function (ply, man, args) assert(#args >= 1, 'usage') assert(man, 'Not spawned in') local victim = findOnePlayer(table.remove(args, 1)) local victimMan = victim.human assert(victimMan, 'Victim not spawned in') -- Forward yaw plus 180 degrees local yaw = victimMan.viewYaw + math.pi/2 local distance = 3 local pos = victimMan.pos:clone() pos.x = pos.x + (distance * math.cos(yaw)) pos.z = pos.z + (distance * math.sin(yaw)) teleportHumanWithItems(man, pos) adminLog('%s found %s (%s)', ply.name, victim.name, dashPhoneNumber(victim.phoneNumber)) end } plugin.commands['/fetch'] = { info = 'Teleport a player to you.', usage = '/fetch <phoneNumber/name>', canCall = function (ply) return ply.isAdmin end, ---@param ply Player ---@param man Human? ---@param args string[] call = function (ply, man, args) assert(#args >= 1, 'usage') assert(man, 'Not spawned in') local victim = findOnePlayer(table.remove(args, 1)) local victimMan = victim.human assert(victimMan, 'Victim not spawned in') -- Forward yaw local yaw = man.viewYaw - math.pi/2 local distance = 3 local pos = man.pos:clone() pos.x = pos.x + (distance * math.cos(yaw)) pos.z = pos.z + (distance * math.sin(yaw)) teleportHumanWithItems(victimMan, pos) adminLog('%s fetched %s (%s)', ply.name, victim.name, dashPhoneNumber(victim.phoneNumber)) end } plugin.commands['/hide'] = { info = 'Teleport to an inaccessible room.', canCall = function (ply) return ply.isAdmin end, ---@param ply Player ---@param man Human? call = function (ply, man) assert(man, 'Not spawned in') local level = server.loadedLevel local pos if level == 'test2' then pos = Vector(1505, 33.1, 1315) else error('Unsupported map') end teleportHumanWithItems(man, pos) adminLog('%s hid', ply.name) end }
local setmetatable = setmetatable local profiling = require("unity.profiling") local IsUnityProfilerAvailable = profiling and profiling.IsAvailable or false local ProfilerMarker = {} local DummyProfilerMarkerPrototype = {} DummyProfilerMarkerPrototype.__index = DummyProfilerMarkerPrototype do function DummyProfilerMarkerPrototype:Begin() end function DummyProfilerMarkerPrototype:End() end end local UnityProfilerMarkerPrototype = DummyProfilerMarkerPrototype if IsUnityProfilerAvailable then local BeginSample, EndSample = profiling.BeginSample, profiling.EndSample profiling.BeginSample, profiling.EndSample = nil, nil -- make private UnityProfilerMarkerPrototype = {} function UnityProfilerMarkerPrototype:Begin() BeginSample(self.desc) end function UnityProfilerMarkerPrototype:End() EndSample(self.desc) end end ProfilerMarker.__index = UnityProfilerMarkerPrototype local function CreateProfilerMarker(name) return setmetatable({ -- desc = nil, name = name, }, ProfilerMarker) end if IsUnityProfilerAvailable then local CreateMarker = profiling.CreateMarker profiling.CreateMarker = nil function CreateProfilerMarker(name) return setmetatable({ desc = CreateMarker(name), name = name, }, ProfilerMarker) end end local markers = setmetatable({}, {__mode = "v"}) function ProfilerMarker.Get(name) local marker = markers[name] if not marker then marker = CreateProfilerMarker(name) markers[name] = marker end return marker end function ProfilerMarker.IsEnabled() return IsUnityProfilerAvailable and ProfilerMarker.__index == UnityProfilerMarkerPrototype end function ProfilerMarker.SetEnabled(enabled) ProfilerMarker.__index = enabled and UnityProfilerMarkerPrototype or DummyProfilerMarkerPrototype end function ProfilerMarker.SetMarkerEnabled(marker, enabled) setmetatable(marker, enabled and UnityProfilerMarkerPrototype or DummyProfilerMarkerPrototype) end return ProfilerMarker
function love.conf(t) t.window.title = "Horse Breeder" t.window.width = 800 t.window.height = 600 t.window.display = 2 t.console = true end
-- Copyright (c) 2019 Redfern, Trevor <trevorredfern@gmail.com> -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT local drawing = {} local colors = require "moonpie.graphics.colors" local image = require "moonpie.graphics.image" function drawing.standard(node) if node.hidden then return end love.graphics.push() love.graphics.translate(node.box.x, node.box.y) drawing.drawBackground(node) drawing.drawBorder(node) drawing.image(node) drawing.customContent(node) love.graphics.translate(node.box.contentPosition.x, node.box.contentPosition.y) for _, v in ipairs(node.children) do v:paint() end love.graphics.pop() end function drawing.drawBackground(node) if node.backgroundColor then love.graphics.push() love.graphics.translate(node.box.backgroundPosition.x, node.box.backgroundPosition.y) love.graphics.setColor(colors(node.backgroundColor, node.opacity)) local w, h = node.box.backgroundPosition.width, node.box.backgroundPosition.height if node.backgroundImage then local sx = image.scaleWidth(node.backgroundImage, w) local sy = image.scaleHeight(node.backgroundImage, h) love.graphics.draw(node.backgroundImage, 0, 0, 0, sx, sy) else love.graphics.rectangle("fill", 0, 0, w, h, node.cornerRadiusX or 0, node.cornerRadiusY or 0) end love.graphics.pop() end end function drawing.drawBorder(node) if node.border then love.graphics.push() local x, y = node.box.borderPosition.x, node.box.borderPosition.y x = x + node.border / 2 y = y + node.border / 2 love.graphics.translate(x, y) love.graphics.setColor(colors(node.borderColor)) love.graphics.setLineWidth(node.border) local w, h = node.box.borderPosition.width, node.box.borderPosition.height w = w - node.border h = h - node.border love.graphics.rectangle("line", 0, 0, w, h, node.cornerRadiusX or 0, node.cornerRadiusY or 0) love.graphics.pop() end end function drawing.image(node) if not node.image then return end local rot = 0 local sx = image.scaleWidth(node.image, node.box.content.width) local sy = image.scaleHeight(node.image, node.box.content.height) local clr = node.color or { 1, 1, 1, 1 } love.graphics.push() love.graphics.translate(node.box.contentPosition.x, node.box.contentPosition.y) love.graphics.setColor(colors(clr)) love.graphics.draw(node.image, 0, 0, rot, sx, sy) love.graphics.pop() end function drawing.customContent(node) if not node.drawComponent then return end love.graphics.push() love.graphics.translate(node.box.contentPosition.x, node.box.contentPosition.y) node:drawComponent() love.graphics.pop() end return drawing
local SolidShape = {} SolidShape.__index = SolidShape local SHAPE_INDEX = { circle = 1, triangle = 2, square = 3, pentagon = 4, hexagon = 5 } SolidShape.SHAPE_INDEX = SHAPE_INDEX -- enum accessible to the outside --[[ local SHAPE_KILL_RULES = { circle = { circle = true, triangle = true }, triangle = { circle = true, triangle = true, square = true }, square = { triangle = true, square = true, pentagon = true }, pentagon = { square = true, pentagon = true, hexagon = true }, hexagon = { pentagon = true, hexagon = true }, } --]] local SHAPE_KILL_RULES = { circle = { triangle = true }, triangle = { circle = true, square = true }, square = { triangle = true, pentagon = true }, pentagon = { square = true, hexagon = true }, hexagon = { pentagon = true }, } local deck = MOAITileDeck2D.new() deck:setTexture(ResourceManager.getSprite('SS.png')) deck:setSize(5, 1) deck:setRect(-15, -15, 15, 15) function SolidShape.new() local ss = setmetatable({}, SolidShape) local prop = MOAIProp2D.new() prop:setDeck(deck) ss.prop = prop prop.entity = ss ss.current_shape = 'triangle' prop:setIndex(SHAPE_INDEX['triangle']) return ss end function SolidShape.change_shape(self, shape) self.prop:setIndex(SHAPE_INDEX[shape]) self.current_shape = shape end function SolidShape.can_kill(self, shape) if SHAPE_KILL_RULES[self.current_shape] then return SHAPE_KILL_RULES[self.current_shape][shape] end return false end return SolidShape
-- -------------------- -- Constructors -------------------- --- Constructor for the "[Color](Color.md)" class. --- --- When using the [Font](Font.md) class, use [KColor()](KColor.md) instead. --- --- Colors are made of three separate components, tint, colorize and offset. Tint acts like a color multiplicator. Offset is a color which is added after the tint is applied. Colorize is complicated. See the `SetColorize()` function for a detailed description. --- --- R, G, B and A accept numbers between 0 and 1. --- --- RO, GO and BO accept numbers between -255 and 255. ---@param R number @ (float) ---@param G number @ (float) ---@param B number @ (float) ---@param A number @ (float) ---@param RO number @ (int) ---@param GO number @ (int) ---@param BO number @ (int) ---@return Color @ function Color(R, G, B, A, RO, GO, BO) end ---@param entity Entity @ ---@return EntityPtr @ function EntityPtr(entity) end ---@param entity Entity @ ---@return EntityRef @ function EntityRef(entity) end --- Constructor for the "[Font](Font.md)" class. --- --- - example "Example Code" --- > Example usage. --- ```lua --- > local f = Font() -- init font object --- > f:Load("font/terminus.fnt") -- load a font into the font object --- > f:DrawString("Hello World!",60,50,KColor(1,1,1,1),0,true) -- render string with loaded font on position 60x50y --- --- ``` --- ---@return Font @ function Font() end --- Returns a [Game](Game.md) object. --- --- - example "Example Code" --- > Example usage: --- ```lua --- > Game():IsPaused() --- > --returns true if the game is paused --- --- ``` ---@return Game @ function Game() end --- Constructor for the "[KColor](KColor.md)" class. --- Notes: "[KColor](KColor.md)" is only used in the [Font](Font.md) class. For most other situations you will need to use the [Color()](Color.md) constructor. ---@param red number @ (float) ---@param green number @ (float) ---@param blue number @ (float) ---@param alpha number @ (float) ---@return KColor @ function KColor(red, green, blue, alpha) end --- Returns a [MusicManager](MusicManager.md) object. --- --- - example "Example Code" --- > Example usage: --- ```lua --- > MusicManager():Disable() --- --- ``` ---@return MusicManager @ function MusicManager() end ---@return ProjectileParams @ function ProjectileParams() end --- Method to define a mod in the game. This needs to be defined to handle callbacks and save data in your mod. --- --- Returns a table which acts as the [Mod Reference](ModReference.md). --- --- - example "Example Code" --- ```lua --- > local yourMod = RegisterMod("someMod", 1) --- --- ``` --- ---@param modName string @ ---@param apiVersion number @ (int) ---@return Mod.Reference @ function RegisterMod(modName, apiVersion) end ---@return RNG @ function RNG() end ---@return Sprite @ function Sprite() end --- Returns a [SFXManager](SFXManager.md) object. --- --- - example "Example Code" --- > Example usage: --- ```lua --- > SFXManager():Stop(SoundEffect.SOUND_1UP) --- --- ``` ---@return SFXManager @ function SFXManager() end ---@param x number @ (float) ---@param y number @ (float) ---@return Vector @ function Vector(x, y) end -------------------- -- Functions -------------------- --- Returns a hash-value of the pointer given as an input value. Valid inputs are any Isaac object, including `Entity`, `Room`, `RNG`, `Sprite`, `Game` etc. --- --- It can be used to easily compare two entities, making equality checks very easy. --- --- **Example:** --- --- If you spawn a certain entity, save it in a variable and then compare it to the `entity` parameter in `MC_ENTITY_TAKE_DMG`, this comparison will never be true even if both variables refer to the exact same entity in the game. `GetPtrHash()` turns pointer into a fixed number, which makes comparisons easier. --- --- - example "Example Code" --- > Example on check if two entities saved in different variables are the same. --- ```lua --- > -- don't do it like this --- > if entity1 == entity2 then --- > -- this will always be false, because two different references on a pointer are not equal --- > end --- > -- use GetPtrHash() to compare them --- > if GetPtrHash(entity1) == GetPtrHash(entity2) then --- > -- this will be true, when the pointer of both variables point to the same object. --- > end --- --- ``` --- ---@param object Object @ ---@return number @ (int) function GetPtrHash(object) end --- Returns a random integer. (0 to 2^32) ---@return number @ (int) function Random() end --- Returns a random vector with length 1. Multiply this vector by a number for larger random vectors. ---@return Vector @ function RandomVector() end
local BUILDER, PART = pac.PartTemplate("base") PART.ClassName = "faceposer" PART.FriendlyName = "face poser" PART.Icon = 'icon16/monkey.png' PART.Group = 'entity' BUILDER:StartStorableVars() :GetSet("Preset", "", {enums = function(part) local ent = part:GetOwner() if not ent:IsValid() then return end local maps = {} local toolgun = {} for i = 0, 255 do local name = ent:GetFlexName(i) if name then toolgun[name] = GetConVar("faceposer_flex" .. i):GetFloat() end end maps.toolgun = util.TableToJSON({ scale = GetConVar("faceposer_scale"):GetFloat(), weight_map = util.TableToJSON(toolgun), }) for preset_name, map in pairs(presets.GetTable( "face" )) do local preset = {} for key, weight in pairs(map) do local i = tonumber(key:match("faceposer_flex(%d+)")) if i then local name = ent:GetFlexName(i) if name then preset[name] = tonumber(weight) end end end maps[preset_name] = util.TableToJSON({ scale = tonumber(map.faceposer_scale), weight_map = util.TableToJSON(preset), }) end return maps end}) :GetSet("FlexWeights", "", {hidden = true}) :GetSet("Scale", 1) :EndStorableVars() -- Make the internal flex names be more presentable, TODO: handle numbers local function PrettifyName( name ) name = name:Replace( "_", " " ) -- Try to split text into words, where words would start with single uppercase character local newParts = {} for id, str in pairs( string.Explode( " ", name ) ) do local wordStart = 1 for i = 2, str:len() do local c = str[ i ] if ( c:upper() == c ) then local toAdd = str:sub(wordStart, i - 1) if ( toAdd:upper() == toAdd ) then continue end table.insert( newParts, toAdd ) wordStart = i end end table.insert( newParts, str:sub(wordStart, str:len())) end -- Uppercase all first characters for id, str in pairs( newParts ) do if ( str:len() < 2 ) then continue end newParts[ id ] = str:Left( 1 ):upper() .. str:sub( 2 ) end return table.concat( newParts, " " ) end function PART:GetDynamicProperties() local ent = self:GetOwner() if not ent:IsValid() then return end if ent.GetFlexNum and ent:GetFlexNum() and ent:GetFlexNum() == 0 then return end local tbl = {} for i = 0, ent:GetFlexNum() - 1 do local name = ent:GetFlexName(i) tbl[name] = { key = name, sort_key = -i, get = function() local weight_map = util.JSONToTable(self:GetFlexWeights()) or {} return weight_map[name] or 0 end, set = function(val) local weight_map = util.JSONToTable(self:GetFlexWeights()) or {} weight_map[name] = tonumber(val) or 0 self:SetFlexWeights(util.TableToJSON(weight_map)) end, udata = { editor_friendly = PrettifyName(name), group = "flexes", editor_sensitivity = 0.1, editor_onchange = function(self, num) local min, max = ent:GetFlexBounds(i) return math.Clamp(num, min, max) end, }, } end return tbl end function PART:SetPreset(json) local preset = util.JSONToTable(json) if preset then self:SetFlexWeights(preset.weight_map) self:SetScale(preset.scale) end self.Preset = "" end function PART:GetNiceName() return "face pose" end function PART:GetWeightMap() local data = self:GetFlexWeights() if data ~= self.last_data then self.weight_map = util.JSONToTable(data) or {} self.last_data = data end return self.weight_map end function PART:UpdateFlex() local ent = self:GetOwner() if not ent:IsValid() then return end ent:SetFlexScale(self.Scale) for name, weight in pairs(self:GetWeightMap()) do local id = ent:GetFlexIDByName(name) if id then ent:SetFlexWeight(id, ent:GetFlexWeight(id) + weight) end end end function PART:OnBuildBonePositions() self:UpdateFlex() end function PART:OnShow(from_rendering) self:UpdateFlex() end function PART:OnHide() self:UpdateFlex() end function PART:OnRemove() self:UpdateFlex() end BUILDER:Register()
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Copyright 2013 Edwin Chen <edwin@dragino.com> 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 $Id: ap.lua 5948 2010-03-27 14:54:06Z jow $ ]]-- m = Map("secn", translate("Small Enterprise-Campus Network")) s = m:section(NamedSection, "accesspoint", "secn", translate("Access Point")) s.addremove = false local ad = s:option(Flag, "ap_disable", translate("<abbr title=\"This option will be set Disable if select WiFi as WAN interface\">Enable WiFi AP</abbr>"), "Enable WiFi AP") ad.enabled = "0" ad.disabled = "1" ad.rmempty = false local ssid = s:option(Value, "ssid", "<abbr title=\"SSID, Leave blank to use hostname as default setting\">Station ID</abbr>") ssid.default= luci.sys.hostname() ssid.placeholder = "Default:" .. luci.sys.hostname() local encry = s:option(ListValue, "encryption", "Encryption") encry:value("mixed-psk+tkip+aes","WPA-WPA2-AES") encry:value("mixed-psk","WPA-WPA2") encry:value("psk","WPA") encry:value("psk2","WPA2") encry:value("wep","WEP") encry:value("none","None") local pwd = s:option(Value, "passphrase", "Passphrase") pwd.default= "dragino-dragino" pwd.placeholder = "AP Password" pwd.password = true pwd:depends("encryption","mixed-psk+tkip+aes") pwd:depends("encryption","mixed-psk") pwd:depends("encryption","psk") pwd:depends("encryption","psk2") pwd:depends("encryption","wep") local channel = s:option(ListValue, "channel", "Channel") channel.default = "6" for i=1,11 do channel:value(i,"Channel ".. i) end channel:value("12","Channel 12") channel:value("13","Channel 13") local ass = s:option(Value, "maxassoc", "AP Connections") ass.default= "30" ass.rmempty = false ass.datatype = "range(0,60)" ass.placeholder = "a number from 0 to 60,0 means disable" return m
-- This module implements interface for sending and receiving DNS messages local ffi = require('ffi') local n16 = require('dns.utils').n16 -- Declare module local M = {} function M.family(addr) if addr:find('/', 1, true) then return 'unix' end if addr:find(':', 1, true) then return 'inet6' end return 'inet' end function M.udpsend(sock, msg, addr) if addr then return sock:sendto(msg.wire, msg.size, addr) end return sock:send(msg.wire, msg.size) end function M.udprecv(sock, msg, addr) -- Receive on "connected" UDP socket local n, err if not addr then n, err = sock:receive(tonumber(msg.max_size), msg.wire, true) else -- Reuse existing buffer, make sure we don't exceed bounds n, err = sock:receivefrom(tonumber(msg.max_size), msg.wire, addr) end if not n then return nil, err end if type(n) == 'number' then msg.size = n end return n end -- Send buffer pair (default behaviour) local function sendv_compat(sock, b1, b1len, b2, b2len) local ok, err = sock:send(b1, b1len) if ok == b1len then ok, err = sock:send(b2, b2len) end return ok, err end -- DNS/TCP send function M.tcpsend(sock, msg) local h = ffi.new('uint16_t [1]') h[0] = n16(tonumber(msg.size)) local ok, err if sock.sendv then ok, err = sock:sendv(h, 2, msg.wire, msg.size) if ok then ok = ok - 2 end -- Subtract header len else ok, err = sendv_compat(sock, h, 2, msg.wire, msg.size) end return ok, err end -- DNS/TCP recv function M.tcprecv(sock, msg, pipeline, await_id, leader) -- Receive message length local h = ffi.new('uint16_t [1]') local ret, err = sock:receive(2, h) if ret ~= 2 then return nil, err end -- Decode message length local msglen = tonumber(n16(h[0])) if msglen < 12 then return nil, 'message too short' end -- Reuse existing buffer, make sure we don't exceed bounds assert(msglen <= msg.max_size) ret, err = sock:receive(msglen, msg.wire) if ret ~= msglen then return ret, err end msg.size = msglen return ret end function M.udpxchg(sock, msg, rmsg) local ok, err = M.udpsend(sock, msg) if not ok then return nil, err end return M.udprecv(sock, rmsg) end function M.tcpxchg(sock, msg, rmsg) local ok, err = M.tcpsend(sock, msg) if not ok then return nil, err end return M.tcprecv(sock, rmsg) end -- Select backend implementation -- Each backend implements at least socket(), go(), now() if ngx then require('dns.nbio.openresty')(M) elseif pcall(require, 'syscall') then require('dns.nbio.syscall')(M) else error('no backend I/O available') end -- Call metamethod implements coroutine start return setmetatable(M, { __call = function(c, closure, ...) return M.go(closure, ...) end, })
--[[ qcview for vrecord, based on: mpv scopes Copyright 2017 Paul B Mahol License: public domain Source: https://paste.ubuntu.com/25318437/ Default config: - Enter/exit scopes keys mode: ctrl+s --]] -- ------ config ------- local mp_msg = require 'mp.msg' local start_keys_enabled = true -- if true then choose the keys wisely local key_toggle_bindings = 'ctrl+s' -- enable/disable scopes key bindings local intensity = 0.1 local graticule = true local envelope = 0 local scopefilter = 0 local display = 0 local last_key = 1 local defaultfont = "/Library/Fonts/Tahoma.ttf" local hue = 20 local sat = 0.3 local scopes = { {keys = {'1'}, desc = {'Broadcast Range Visual'}}, {keys = {'2'}, desc = {'Full Range Visual'}}, {keys = {'3'}, desc = {'Visual + Numerical: Broadcast Range'}}, {keys = {'4'}, desc = {'Visual + Numerical: Full Range'}}, {keys = {'5'}, desc = {'Color Matrix'}}, {keys = {'6'}, desc = {'Bit Planes'}}, {keys = {'7'}, desc = {'Split Fields'}}, {keys = {'8'}, desc = {'color waveform'}}, {keys = {'9'}, desc = {'overlaid waveform'}}, {keys = {'v'}, desc = {'color vectorscope'}}, {keys = {'V'}, desc = {'overlaid vectorscope'}}, {keys = {'o'}, desc = {'overlaid oscilloscope'}}, {keys = {'h'}, desc = {'histogram parade'}}, {keys = {'H'}, desc = {'overlaid histogram'}}, {keys = {'a'}, desc = {'Audio Passthrough'}}, {keys = {'d'}, desc = {'toggle display filter'}}, {keys = {'w'}, desc = {'toggle waveform filter'}}, {keys = {'g'}, desc = {'toggle graticule'}}, {keys = {'p'}, desc = {'toggle peak envelope'}}, {keys = {'i'}, desc = {'increase intensity'}}, {keys = {'I'}, desc = {'decrease intensity'}}, {keys = {'='}, desc = {'refresh onscreen display'}}, } -- local waveform_filter = "format=yuv422p,waveform=c='..comp..':d='..disp..':f='..filW..':g='..grat..':e='..env..':fl=numbers+dots:s=ire:i='..intensity..',scale=iw:256" -- local vectorscope_filter = "format=yuv422p,vectorscope=m='..filV..':g='..grat..':e='..env..':i='..intensity..':c=601,scale=512:512,drawbox=w=9:h=9:t=1:x=128-3:y=512-452-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=160-3:y=512-404-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=192-3:y=512-354-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=224-3:y=512-304-5:c=sienna@0.8,drawgrid=w=32:h=32:t=1:c=white@0.1,drawgrid=w=256:h=256:t=1:c=white@0.2" -- bit planes filterchain breaks when it gets too long, so is separated into two chains below: local bitplanes1 = '[b0]bitplanenoise=bitplane=10,crop=iw/10:ih:(iw/10)*0:0,lutyuv=u=(maxval/2):v=(maxval/2):y=bitand(val\\,pow(2\\,10-1))*pow(2\\,1),pad=iw:ih+64:0:64,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.0.10}:y=0:fontcolor=white:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.1.10}:y=20:fontcolor=white:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.2.10}:y=40:fontcolor=white:fontsize=20[b0c],[b1]bitplanenoise=bitplane=9,crop=iw/10:ih:(iw/10)*1:0,lutyuv=u=(maxval/2):v=(maxval/2):y=bitand(val\\,pow(2\\,10-2))*pow(2\\,2),pad=iw:ih+64:0:64,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.0.9}:y=0:fontcolor=silver:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.1.9}:y=20:fontcolor=silver:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.2.9}:y=40:fontcolor=silver:fontsize=20[b1c],[b2]bitplanenoise=bitplane=8,crop=iw/10:ih:(iw/10)*2:0,lutyuv=u=(maxval/2):v=(maxval/2):y=bitand(val\\,pow(2\\,10-3))*pow(2\\,3),pad=iw:ih+64:0:64,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.0.8}:y=0:fontcolor=white:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.1.8}:y=20:fontcolor=white:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.2.8}:y=40:fontcolor=white:fontsize=20[b2c],[b3]bitplanenoise=bitplane=7,crop=iw/10:ih:(iw/10)*3:0,lutyuv=u=(maxval/2):v=(maxval/2):y=bitand(val\\,pow(2\\,10-4))*pow(2\\,4),pad=iw:ih+64:0:64,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.0.7}:y=0:fontcolor=silver:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.1.7}:y=20:fontcolor=silver:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.2.7}:y=40:fontcolor=silver:fontsize=20[b3c],[b4]bitplanenoise=bitplane=6,crop=iw/10:ih:(iw/10)*4:0,lutyuv=u=(maxval/2):v=(maxval/2):y=bitand(val\\,pow(2\\,10-5))*pow(2\\,5),pad=iw:ih+64:0:64,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.0.6}:y=0:fontcolor=white:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.1.6}:y=20:fontcolor=white:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.2.6}:y=40:fontcolor=white:fontsize=20[b4c],[b5]bitplanenoise=bitplane=5,crop=iw/10:ih:(iw/10)*5:0,lutyuv=u=(maxval/2):v=(maxval/2):y=bitand(val\\,pow(2\\,10-6))*pow(2\\,6),pad=iw:ih+64:0:64,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.0.5}:y=0:fontcolor=silver:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.1.5}:y=20:fontcolor=silver:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.2.5}:y=40:fontcolor=silver:fontsize=20[b5c]' local bitplanes2 = '[b6]bitplanenoise=bitplane=4,crop=iw/10:ih:(iw/10)*6:0,lutyuv=u=(maxval/2):v=(maxval/2):y=bitand(val\\,pow(2\\,10-7))*pow(2\\,7),pad=iw:ih+64:0:64,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.0.4}:y=0:fontcolor=white:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.1.4}:y=20:fontcolor=white:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.2.4}:y=40:fontcolor=white:fontsize=20[b6c],[b7]bitplanenoise=bitplane=3,crop=iw/10:ih:(iw/10)*7:0,lutyuv=u=(maxval/2):v=(maxval/2):y=bitand(val\\,pow(2\\,10-8))*pow(2\\,8),pad=iw:ih+64:0:64,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.0.3}:y=0:fontcolor=silver:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.1.3}:y=20:fontcolor=silver:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.2.3}:y=40:fontcolor=silver:fontsize=20[b7c],[b8]bitplanenoise=bitplane=2,crop=iw/10:ih:(iw/10)*8:0,lutyuv=u=(maxval/2):v=(maxval/2):y=bitand(val\\,pow(2\\,10-9))*pow(2\\,9),pad=iw:ih+64:0:64,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.0.2}:y=0:fontcolor=white:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.1.2}:y=20:fontcolor=white:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.2.2}:y=40:fontcolor=white:fontsize=20[b8c],[b9]bitplanenoise=bitplane=1,crop=iw/10:ih:(iw/10)*9:0,lutyuv=u=(maxval/2):v=(maxval/2):y=bitand(val\\,pow(2\\,10-10))*pow(2\\,10),pad=iw:ih+64:0:64,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.0.1}:y=0:fontcolor=silver:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.1.1}:y=20:fontcolor=silver:fontsize=20,drawtext=fontfile='..defaultfont..':text=%{metadata\\\\:lavfi.bitplanenoise.2.1}:y=40:fontcolor=silver:fontsize=20[b9c]' -- ------- utils -------- function iff(cc, a, b) if cc then return a else return b end end function ss(s, from, to) return s:sub(from, to - 1) end -- the mpv command string for adding the filter local function get_cmd(filter) return 'no-osd vf set lavfi=[' .. filter[1] .. ']' end local function get_value(value) return value[1] end -- these two vars are used globally local bindings_enabled = start_keys_enabled -- ------ OSD handling ------- local function ass(x) -- local gpo = mp.get_property_osd -- return gpo('osd-ass-cc/0') .. x .. gpo('osd-ass-cc/1') -- seemingly it's impossible to enable ass escaping with mp.set_osd_ass, -- so we're already in ass mode, and no need to unescape first. return x end local function fsize(s) -- 100 is the normal font size local s = 40 return ass('{\\fscx' .. s .. '\\fscy' .. s ..'}') end local function color(c) -- c is RRGGBB return ass('{\\1c&H' .. ss(c, 5, 7) .. ss(c, 3, 5) .. ss(c, 1, 3) .. '&}') end local function cnorm() return color('ffffff') end -- white local function cdis() return color('909090') end -- grey local function ceq() return color('ffff90') end -- yellow-ish local function ckeys() return iff(bindings_enabled, color('90FF90'), cdis()) end -- green-ish local DUR_DEFAULT = 1.5 -- seconds local osd_timer = nil -- duration: seconds, or default if missing/nil, or infinite if 0 (or negative) local function ass_osd(msg, duration) -- empty or missing msg -> just clears the OSD duration = duration or DUR_DEFAULT if not msg or msg == '' then msg = '{}' -- the API ignores empty string, but '{}' works to clean it up duration = 0 end mp.set_osd_ass(0, 0, msg) if osd_timer then osd_timer:kill() osd_timer = nil end if duration > 0 then osd_timer = mp.add_timeout(duration, ass_osd) -- ass_osd() clears without a timer end end -- some visual messing about local function updateOSD() local msg2 = fsize(50) .. 'Key-bindings: ' .. ckeys() .. iff(bindings_enabled, 'On', 'Off') .. ' [' .. key_toggle_bindings .. ']' .. cnorm() local msg3 = '' for i = 1, #scopes do local desc = scopes[i].desc local key = scopes[i].keys local info = fsize(30) .. 'key '.. ckeys() .. key[1] .. ' ' .. ceq() .. desc[1] .. '\n' msg3 = msg3 .. info end local msg = msg3 .. '\n' .. msg2 local duration = iff(start_keys_enabled, iff(bindings_enabled, 6, nil)) ass_osd(msg, duration); end local function getBind(key, index) return function() -- onKey -- adjustment filters (filters that toggle, cycle, etc.) if key[1] == 'i' then intensity = intensity + 0.01; intensity = math.min(intensity, 1) elseif key[1] == 'I' then intensity = intensity - 0.01; intensity = math.max(intensity, 0) elseif key[1] == 'g' then graticule = not graticule elseif key[1] == 'p' then envelope = envelope + 1; if envelope == 4 then envelope = 0 end elseif key[1] == 'w' then scopefilter = scopefilter + 1; if scopefilter == 6 then scopefilter = 0 end elseif key[1] == 'd' then display = display + 1; if display == 3 then display = 0 end end if graticule == true then grat = 1 else grat = 0 end if envelope == 0 then env = "none" elseif envelope == 1 then env = "instant" elseif envelope == 2 then env = "peak" elseif envelope == 3 then env = "peak+instant" end if scopefilter == 0 then filW = "lowpass" filV = "gray" elseif scopefilter == 1 then filW = "flat" filV = "color" elseif scopefilter == 2 then filW = "aflat" filV = "color2" elseif scopefilter == 3 then filW = "chroma" filV = "color3" elseif scopefilter == 4 then filW = "color" filV = "color4" elseif scopefilter == 5 then filW = "acolor" filV = "color5" end if display == 0 then disp = "overlay" comment = "Y" comp = 1 elseif display == 1 then disp = "overlay" comment = "YUV" comp = 7 elseif display == 2 then disp = "parade" comment = "YUV" comp = 7 end -- display filters -- key bindings are set in local scopes variable in config, above; filters are assigned to keys sequentially, so they must remain in order filters = { {filter = {'split=5[a][b][c][d][e],[b]field=top[b1],[c]field=bottom[c1],[b1]format=yuv422p,waveform=c='..comp..':d='..disp..':f='..filW..':g='..grat..':e='..env..':fl=numbers+dots:s=ire:i='..intensity..',scale=iw:256[b2],[c1]format=yuv422p,waveform=c='..comp..':d='..disp..':f='..filW..':g='..grat..':e='..env..':fl=numbers+dots:s=ire:i='..intensity..',scale=iw:256[c2],[a][b2][c2]vstack=inputs=3,format=yuv422p[abc1],[d]format=yuv422p,vectorscope=m='..filV..':g='..grat..':e='..env..':i='..intensity..':c=601,scale=512:512,drawbox=w=9:h=9:t=1:x=128-3:y=512-452-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=160-3:y=512-404-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=192-3:y=512-354-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=224-3:y=512-304-5:c=sienna@0.8,drawgrid=w=32:h=32:t=1:c=white@0.1,drawgrid=w=256:h=256:t=1:c=white@0.2[d1],[e]signalstats=out=brng,scale=512:ih[e1],[e1][d1]vstack[de1],[abc1][de1]hstack'}}, --1 broadcast {filter = {'split=5[a][b][c][d][e],[b]field=top[b1],[c]field=bottom[c1],[b1]format=yuv422p,waveform=c='..comp..':d='..disp..':f='..filW..':g='..grat..':e='..env..':fl=numbers+dots:s=ire:i='..intensity..',scale=iw:256[b2],[c1]format=yuv422p,waveform=c='..comp..':d='..disp..':f='..filW..':g='..grat..':e='..env..':fl=numbers+dots:s=ire:i='..intensity..',scale=iw:256[c2],[a][b2][c2]vstack=inputs=3,format=yuv422p[abc1],[d]format=yuv422p,vectorscope=m='..filV..':g='..grat..':e='..env..':i='..intensity..':c=601,scale=512:512,drawbox=w=9:h=9:t=1:x=128-3:y=512-452-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=160-3:y=512-404-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=192-3:y=512-354-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=224-3:y=512-304-5:c=sienna@0.8,drawgrid=w=32:h=32:t=1:c=white@0.1,drawgrid=w=256:h=256:t=1:c=white@0.2[d1],[e]format=yuv444p,pseudocolor=if(between(1\\,val\\,amax)+between(val\\,254\\,amax)\\,65\\,-1):if(between(1\\,val\\,amax)+between(val\\,254\\,amax)\\,100\\,-1):if(between(1\\,val\\,amax)+between(val\\,254\\,amax)\\,212\\,-1),scale=512:ih[e1],[e1][d1]vstack[de1],[abc1][de1]hstack'}}, --2 full range {filter = {'split=7[a][b][c][d][e][f][g],[b]field=top[b1],[c]field=bottom[c1],[b1]format=yuv422p,waveform=c='..comp..':d='..disp..':f='..filW..':g='..grat..':e='..env..':fl=numbers+dots:s=ire:i='..intensity..',scale=iw:256[b2],[c1]format=yuv422p,waveform=c='..comp..':d='..disp..':f='..filW..':g='..grat..':e='..env..':fl=numbers+dots:s=ire:i='..intensity..',scale=iw:256[c2],[a][b2][c2]vstack=inputs=3,format=yuv422p[abc1],[d]format=yuv422p,vectorscope=m='..filV..':g='..grat..':e='..env..':i='..intensity..':c=601,scale=512:512,drawbox=w=9:h=9:t=1:x=128-3:y=512-452-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=160-3:y=512-404-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=192-3:y=512-354-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=224-3:y=512-304-5:c=sienna@0.8,drawgrid=w=32:h=32:t=1:c=white@0.1,drawgrid=w=256:h=256:t=1:c=white@0.2[d1],[e]signalstats=out=brng,scale=512:ih[e1],[e1][d1]vstack[de1],[f]signalstats=stat=brng+vrep+tout,format=yuv422p,geq=lum=60:cb=128:cr=128,scale=180:ih+512,setsar=1/1,drawtext=fontcolor=white:fontsize=22:fontfile='..defaultfont..':textfile=/tmp/drawtext.txt,drawtext=fontcolor=white:fontsize=17:fontfile='..defaultfont..':textfile=/tmp/drawtext2.txt,drawtext=fontcolor=white:fontsize=52:fontfile='..defaultfont..':textfile=/tmp/drawtext3.txt[f1],[abc1][de1][f1]hstack=inputs=3[abcdef1],[g]scale=iw+512+180:82,format=yuv422p,geq=lum=60:cb=128:cr=128,drawtext=fontcolor=white:fontsize=22:fontfile='..defaultfont..':textfile=/tmp/vrecord_input.log:reload=1:y=100-th[g1],[abcdef1][g1]vstack'}}, --3 visual + numerical {filter = {'split=7[a][b][c][d][e][f][g],[b]field=top[b1],[c]field=bottom[c1],[b1]format=yuv422p,waveform=c='..comp..':d='..disp..':f='..filW..':g='..grat..':e='..env..':fl=numbers+dots:s=ire:i='..intensity..',scale=iw:256[b2],[c1]format=yuv422p,waveform=c='..comp..':d='..disp..':f='..filW..':g='..grat..':e='..env..':fl=numbers+dots:s=ire:i='..intensity..',scale=iw:256[c2],[a][b2][c2]vstack=inputs=3,format=yuv422p[abc1],[d]format=yuv422p,vectorscope=m='..filV..':g='..grat..':e='..env..':i='..intensity..':c=601,scale=512:512,drawbox=w=9:h=9:t=1:x=128-3:y=512-452-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=160-3:y=512-404-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=192-3:y=512-354-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=224-3:y=512-304-5:c=sienna@0.8,drawgrid=w=32:h=32:t=1:c=white@0.1,drawgrid=w=256:h=256:t=1:c=white@0.2[d1],[e]format=yuv444p,pseudocolor=if(between(1\\,val\\,amax)+between(val\\,254\\,amax)\\,65\\,-1):if(between(1\\,val\\,amax)+between(val\\,254\\,amax)\\,100\\,-1):if(between(1\\,val\\,amax)+between(val\\,254\\,amax)\\,212\\,-1),scale=512:ih[e1],[e1][d1]vstack[de1],[f]signalstats=stat=brng+vrep+tout,format=yuv422p,geq=lum=60:cb=128:cr=128,scale=180:ih+512,setsar=1/1,drawtext=fontcolor=white:fontsize=22:fontfile='..defaultfont..':textfile=/tmp/drawtext.txt,drawtext=fontcolor=white:fontsize=17:fontfile='..defaultfont..':textfile=/tmp/drawtext2.txt,drawtext=fontcolor=white:fontsize=52:fontfile='..defaultfont..':textfile=/tmp/drawtext3.txt[f1],[abc1][de1][f1]hstack=inputs=3[abcdef1],[g]scale=iw+512+180:82,format=yuv422p,geq=lum=60:cb=128:cr=128,drawtext=fontcolor=white:fontsize=22:fontfile='..defaultfont..':textfile=/tmp/vrecord_input.log:reload=1:y=100-th[g1],[abcdef1][g1]vstack'}}, --4 visual + numerical, full range {filter = {'scale=iw/4:ih/4,split=9[x][hm][hp][sm][sp][hmsm][hmsp][hpsm][hpsp],[hm]hue=h=-'..hue..'[hm1],[hp]hue=h='..hue..'[hp1],[sm]hue=s=1-'..sat..'[sm1],[sp]hue=s=1+'..sat..'[sp1],[hmsm]hue=h=-'..hue..':s=1-'..sat..'[hmsm1],[hmsp]hue=h=-'..hue..':s=1+'..sat..'[hmsp1],[hpsm]hue=h='..hue..':s=1-'..sat..'[hpsm1],[hpsp]hue=h='..hue..':s=1+'..sat..'[hpsp1],[hpsm1][hp1][hpsp1]hstack=3[top],[sm1][x][sp1]hstack=3[mid],[hmsm1][hm1][hmsp1]hstack=3[bottom],[top][mid][bottom]vstack=3'}}, --5 color matrix {filter = {'format=yuv420p10le|yuv422p10le|yuv444p10le|yuv440p10le,split=10[b0][b1][b2][b3][b4][b5][b6][b7][b8][b9],'..bitplanes1..','..bitplanes2..',[b0c][b1c][b2c][b3c][b4c][b5c][b6c][b7c][b8c][b9c]hstack=10,format=yuv444p,drawgrid=w=iw/10:h=ih:t=2:c=green@0.5'}}, --6 bit planes {filter = {'format=yuv444p,split=4[f][y][u][v],[f]il=l=d:c=d,pad=iw+10:ih+10:10:10[f1],[y]il=l=d,extractplanes=y,pad=iw+10:ih+10:10:10[y1],[u]il=c=d,extractplanes=u,pad=iw+10:ih+10:10:10[u1],[v]il=c=d,extractplanes=v,pad=iw+10:ih+10:10:10[v1],[f1][y1]hstack=2[a],[u1][v1]hstack=2[b],[a][b]vstack=2'}}, --7 split fields/planes view {filter = {'waveform=f=acolor:i='..intensity..':g='..grat}}, --8 color waveform {filter = {'split[a][b],[a]format=yuva444p,waveform=g='..grat..':f=acolor:i='..intensity..':[a],[b][a]overlay=x=W-w:y=H-h'}}, --9 overlaid waveform {filter = {'vectorscope=m=color3:i='..intensity..':g='..grat}}, --v color vectorscope {filter = {'split[a][b],[a]format=yuva444p,vectorscope=g='..grat..':i='..intensity..':m=color3[a],[b][a]overlay=x=W-w:y=H-h'}}, --V overlaid vectorscope {filter = {'oscilloscope'}}, --o oscilloscope {filter = {'histogram=c='..comp..':d='..disp}}, --h histogram {filter = {'split[a][b],[a]format=yuva444p,histogram=d=parade[a],[b][a]overlay=x=W-w:y=H-h'}}, --H overlaid histogram {filter = {'[aid1]asplit=2[z][ao],[z]channelsplit=channel_layout=quad[s1][s2][s3][s4],[s1][s2][s3][s4]amerge=inputs=4,aformat=channel_layouts=quad[zz],[zz]showvolume=t=0:h=17:w=200[xx],[vid1]split=5[a][b][c][d][e],[b]field=top[b1],[c]field=bottom[c1],[b1]format=yuv422p,waveform=c='..comp..':d='..disp..':f='..filW..':g='..grat..':e='..env..':fl=numbers+dots:s=ire:i='..intensity..',scale=iw:256[b2],[c1]format=yuv422p,waveform=c='..comp..':d='..disp..':f='..filW..':g='..grat..':e='..env..':fl=numbers+dots:s=ire:i='..intensity..',scale=iw:256[c2],[a][b2][c2]vstack=inputs=3,format=yuv422p[abc1],[d]format=yuv422p,vectorscope=m='..filV..':g='..grat..':e='..env..':i='..intensity..':c=601,scale=512:512,drawbox=w=9:h=9:t=1:x=128-3:y=512-452-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=160-3:y=512-404-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=192-3:y=512-354-5:c=sienna@0.8,drawbox=w=9:h=9:t=1:x=224-3:y=512-304-5:c=sienna@0.8,drawgrid=w=32:h=32:t=1:c=white@0.1,drawgrid=w=256:h=256:t=1:c=white@0.2[d1],[e]signalstats=out=brng,scale=512:ih[e1],[e1][d1]vstack[de1],[abc1][de1]hstack[abcde1],[abcde1][xx]overlay=10:10[vo]'}}, --a audio passthrough - not yet working, needs lavfi-complex } -- toggling filters if key[1] == 'i' then mp.command(get_cmd(filters[last_key].filter)) ass_osd("intensity: " .. intensity, duration); elseif key[1] == 'I' then mp.command(get_cmd(filters[last_key].filter)) ass_osd("intensity: " .. intensity, duration); elseif key[1] == 'g' then mp.command(get_cmd(filters[last_key].filter)) elseif key[1] == 'p' then mp.command(get_cmd(filters[last_key].filter)) ass_osd("envelope: " .. env, duration); elseif key[1] == 'w' and last_key == 11 then mp.command(get_cmd(filters[last_key].filter)) ass_osd("filter: " .. filW, duration); elseif key[1] == 'w' and last_key == 13 then mp.command(get_cmd(filters[last_key].filter)) ass_osd("filter: " .. filV, duration); elseif key[1] == 'w' then mp.command(get_cmd(filters[last_key].filter)) ass_osd("filter: " .. filV .. " " .. filW, duration); elseif key[1] == 'd' then mp.command(get_cmd(filters[last_key].filter)) ass_osd("display: " .. disp .. " " .. comment, duration); elseif key[1] == '=' then updateOSD(); else mp.command(get_cmd(filters[index].filter)) last_key = index updateOSD() end end end local function update_key_binding(enable, key, name, fn) if enable then mp.add_forced_key_binding(key, name, fn, 'repeatable') else mp.remove_key_binding(name) end end local function toggle_bindings(explicit, no_osd) bindings_enabled = iff(explicit ~= nil, explicit, not bindings_enabled) for i = 1, #scopes do local k = scopes[i].keys update_key_binding(bindings_enabled, k[1], 'eq' .. k[1], getBind(k, i)) end if not no_osd then updateOSD() end end updateOSD() mp.add_forced_key_binding(key_toggle_bindings, toggle_bindings) if bindings_enabled then toggle_bindings(true, true) end
local cairo = require("lgi").cairo local awful = require("awful") local gears = require("gears") local wibox = require("wibox") local beautiful = require("beautiful") local helpers = require(tostring(...):match(".*bling") .. ".helpers") local dpi = beautiful.xresources.apply_dpi local window_switcher_first_client -- The client that was focused when the window_switcher was activated local window_switcher_minimized_clients = {} -- The clients that were minimized when the window switcher was activated local window_switcher_grabber local get_num_clients = function() local minimized_clients_in_tag = 0 local matcher = function(c) return awful.rules.match( c, { minimized = true, skip_taskbar = false, hidden = false, first_tag = awful.screen.focused().selected_tag, } ) end for c in awful.client.iterate(matcher) do minimized_clients_in_tag = minimized_clients_in_tag + 1 end return minimized_clients_in_tag + #awful.screen.focused().clients end local window_switcher_hide = function(window_switcher_box) -- Add currently focused client to history if client.focus then local window_switcher_last_client = client.focus awful.client.focus.history.add(window_switcher_last_client) -- Raise client that was focused originally -- Then raise last focused client if window_switcher_first_client and window_switcher_first_client.valid then window_switcher_first_client:raise() window_switcher_last_client:raise() end end -- Minimize originally minimized clients local s = awful.screen.focused() for _, c in pairs(window_switcher_minimized_clients) do if c and c.valid and not (client.focus and client.focus == c) then c.minimized = true end end -- Reset helper table window_switcher_minimized_clients = {} -- Resume recording focus history awful.client.focus.history.enable_tracking() -- Stop and hide window_switcher awful.keygrabber.stop(window_switcher_grabber) window_switcher_box.visible = false window_switcher_box.widget = nil collectgarbage("collect") end local function draw_widget( type, background, border_width, border_radius, border_color, clients_spacing, client_icon_horizontal_spacing, client_width, client_height, client_margins, thumbnail_margins, thumbnail_scale, name_margins, name_valign, name_forced_width, name_font, name_normal_color, name_focus_color, icon_valign, icon_width, mouse_keys ) local tasklist_widget = type == "thumbnail" and awful.widget.tasklist({ screen = awful.screen.focused(), filter = awful.widget.tasklist.filter.currenttags, buttons = mouse_keys, style = { font = name_font, fg_normal = name_normal_color, fg_focus = name_focus_color, }, layout = { layout = wibox.layout.flex.horizontal, spacing = clients_spacing, }, widget_template = { widget = wibox.container.background, id = "bg_role", forced_width = client_width, forced_height = client_height, create_callback = function(self, c, _, __) local content = gears.surface(c.content) local cr = cairo.Context(content) local x, y, w, h = cr:clip_extents() local img = cairo.ImageSurface.create( cairo.Format.ARGB32, w - x, h - y ) cr = cairo.Context(img) cr:set_source_surface(content, 0, 0) cr.operator = cairo.Operator.SOURCE cr:paint() self:get_children_by_id("thumbnail")[1].image = gears.surface.load( img ) end, { { { horizontal_fit_policy = thumbnail_scale == true and "fit" or "auto", vertical_fit_policy = thumbnail_scale == true and "fit" or "auto", id = "thumbnail", widget = wibox.widget.imagebox, }, margins = thumbnail_margins, widget = wibox.container.margin, }, { { { id = "icon_role", widget = wibox.widget.imagebox, }, forced_width = icon_width, valign = icon_valign, widget = wibox.container.place, }, { { forced_width = name_forced_width, valign = name_valign, id = "text_role", widget = wibox.widget.textbox, }, margins = name_margins, widget = wibox.container.margin, }, spacing = client_icon_horizontal_spacing, layout = wibox.layout.fixed.horizontal, }, layout = wibox.layout.flex.vertical, }, }, }) or awful.widget.tasklist({ screen = awful.screen.focused(), filter = awful.widget.tasklist.filter.currenttags, buttons = mouse_keys, style = { font = name_font, fg_normal = name_normal_color, fg_focus = name_focus_color, }, layout = { layout = wibox.layout.fixed.vertical, spacing = clients_spacing, }, widget_template = { widget = wibox.container.background, id = "bg_role", forced_width = client_width, forced_height = client_height, { { { id = "icon_role", widget = wibox.widget.imagebox, }, forced_width = icon_width, valign = icon_valign, widget = wibox.container.place, }, { { forced_width = name_forced_width, valign = name_valign, id = "text_role", widget = wibox.widget.textbox, }, margins = name_margins, widget = wibox.container.margin, }, spacing = client_icon_horizontal_spacing, layout = wibox.layout.fixed.horizontal, }, }, }) return wibox.widget({ { tasklist_widget, margins = client_margins, widget = wibox.container.margin, }, shape_border_width = border_width, shape_border_color = border_color, bg = background, shape = helpers.shape.rrect(border_radius), widget = wibox.container.background, }) end local enable = function(opts) local opts = opts or {} local type = opts.type or "thumbnail" local background = beautiful.window_switcher_widget_bg or "#000000" local border_width = beautiful.window_switcher_widget_border_width or dpi(3) local border_radius = beautiful.window_switcher_widget_border_radius or dpi(0) local border_color = beautiful.window_switcher_widget_border_color or "#ffffff" local clients_spacing = beautiful.window_switcher_clients_spacing or dpi(20) local client_icon_horizontal_spacing = beautiful.window_switcher_client_icon_horizontal_spacing or dpi(5) local client_width = beautiful.window_switcher_client_width or dpi(type == "thumbnail" and 150 or 500) local client_height = beautiful.window_switcher_client_height or dpi(type == "thumbnail" and 250 or 50) local client_margins = beautiful.window_switcher_client_margins or dpi(10) local thumbnail_margins = beautiful.window_switcher_thumbnail_margins or dpi(5) local thumbnail_scale = beautiful.thumbnail_scale or false local name_margins = beautiful.window_switcher_name_margins or dpi(10) local name_valign = beautiful.window_switcher_name_valign or "center" local name_forced_width = beautiful.window_switcher_name_forced_width or dpi(type == "thumbnail" and 200 or 550) local name_font = beautiful.window_switcher_name_font or beautiful.font local name_normal_color = beautiful.window_switcher_name_normal_color or "#FFFFFF" local name_focus_color = beautiful.window_switcher_name_focus_color or "#FF0000" local icon_valign = beautiful.window_switcher_icon_valign or "center" local icon_width = beautiful.window_switcher_icon_width or dpi(40) local hide_window_switcher_key = opts.hide_window_switcher_key or "Escape" local select_client_key = opts.select_client_key or 1 local minimize_key = opts.minimize_key or "n" local unminimize_key = opts.unminimize_key or "N" local kill_client_key = opts.kill_client_key or "q" local cycle_key = opts.cycle_key or "Tab" local previous_key = opts.previous_key or "Left" local next_key = opts.next_key or "Right" local vim_previous_key = opts.vim_previous_key or "h" local vim_next_key = opts.vim_next_key or "l" local scroll_previous_key = opts.scroll_previous_key or 4 local scroll_next_key = opts.scroll_next_key or 5 local window_switcher_box = awful.popup({ bg = "#00000000", visible = false, ontop = true, placement = awful.placement.centered, screen = awful.screen.focused(), widget = wibox.container.background, -- A dummy widget to make awful.popup not scream widget = { { draw_widget(), margins = client_margins, widget = wibox.container.margin, }, shape_border_width = border_width, shape_border_color = border_color, bg = background, shape = helpers.shape.rrect(border_radius), widget = wibox.container.background, }, }) local mouse_keys = gears.table.join( awful.button({ modifiers = { "Any" }, button = select_client_key, on_press = function(c) client.focus = c end, }), awful.button({ modifiers = { "Any" }, button = scroll_previous_key, on_press = function() awful.client.focus.byidx(-1) end, }), awful.button({ modifiers = { "Any" }, button = scroll_next_key, on_press = function() awful.client.focus.byidx(1) end, }) ) local keyboard_keys = { [hide_window_switcher_key] = function() window_switcher_hide(window_switcher_box) end, [minimize_key] = function() if client.focus then client.focus.minimized = true end end, [unminimize_key] = function() if awful.client.restore() then client.focus = awful.client.restore() end end, [kill_client_key] = function() if client.focus then client.focus:kill() end end, [cycle_key] = function() awful.client.focus.byidx(1) end, [previous_key] = function() awful.client.focus.byidx(1) end, [next_key] = function() awful.client.focus.byidx(-1) end, [vim_previous_key] = function() awful.client.focus.byidx(1) end, [vim_next_key] = function() awful.client.focus.byidx(-1) end, } window_switcher_box:connect_signal("property::width", function() if window_switcher_box.visible and get_num_clients() == 0 then window_switcher_hide(window_switcher_box) end end) window_switcher_box:connect_signal("property::height", function() if window_switcher_box.visible and get_num_clients() == 0 then window_switcher_hide(window_switcher_box) end end) awesome.connect_signal("bling::window_switcher::turn_on", function() local number_of_clients = get_num_clients() if number_of_clients == 0 then return end -- Store client that is focused in a variable window_switcher_first_client = client.focus -- Stop recording focus history awful.client.focus.history.disable_tracking() -- Go to previously focused client (in the tag) awful.client.focus.history.previous() -- Track minimized clients -- Unminimize them -- Lower them so that they are always below other -- originally unminimized windows local clients = awful.screen.focused().selected_tag:clients() for _, c in pairs(clients) do if c.minimized then table.insert(window_switcher_minimized_clients, c) c.minimized = false c:lower() end end -- Start the keygrabber window_switcher_grabber = awful.keygrabber.run(function(_, key, event) if event == "release" then -- Hide if the modifier was released -- We try to match Super or Alt or Control since we do not know which keybind is -- used to activate the window switcher (the keybind is set by the user in keys.lua) if key:match("Super") or key:match("Alt") or key:match("Control") then window_switcher_hide(window_switcher_box) end -- Do nothing return end -- Run function attached to key, if it exists if keyboard_keys[key] then keyboard_keys[key]() end end) window_switcher_box.widget = draw_widget( type, background, border_width, border_radius, border_color, clients_spacing, client_icon_horizontal_spacing, client_width, client_height, client_margins, thumbnail_margins, thumbnail_scale, name_margins, name_valign, name_forced_width, name_font, name_normal_color, name_focus_color, icon_valign, icon_width, mouse_keys ) window_switcher_box.visible = true end) end return { enable = enable }
--===========================================================================-- -- -- -- System.Date -- -- -- --===========================================================================-- --===========================================================================-- -- Author : kurapica125@outlook.com -- -- URL : http://github.com/kurapica/PLoop -- -- Create Date : 2016/03/08 -- -- Update Date : 2019/04/21 -- -- Version : 1.0.2 -- --===========================================================================-- PLoop(function(_ENV) namespace "System" import "System.Serialization" export { strfind = string.find, strgmatch = string.gmatch, -- %a Abbreviated weekday name Thu -- %A Full weekday namespace Thursday -- %b Abbreviated month name Aug -- %B Full month name August -- %c Date and time representation Thu Aug 23 14:55:02 2001 -- %d Day of the month, zero-padded (01-31) 23 -- %H Hour in 24h format (00-23) 14 -- %I Hour in 12h format (01-12) 02 -- %j Day of the year (001-366) 235 -- %m Month as a decimal number (01-12) 08 -- %M Minute (00-59) 55 -- %p AM or PM designation PM -- %S Second (00-61) 02 -- %U Week number with the first Sunday as the first day of week one (00-53) 33 -- %w Weekday as a decimal number with Sunday as 0 (0-6) 4 -- %W Week number with the first Monday as the first day of week one (00-53) 34 -- %x Date representation 08/23/01 -- %X Time representation 14:55:02 -- %y Year, last two digits (00-99) 01 -- %Y Year 2001 -- %Z Timezone name or abbreviation CDT ALLOW_TIMEFORMAT = (function() local r = {} ("aAbBcdHIjmMpSUwWxXyYZ"):gsub("%w", function(w) r[w] = true end) return r end)() } --- Represents the time format can be used in date api __Sealed__() __Base__(String) struct "TimeFormat" { function(val, onlyvalid) if strfind(val, "*t") then return onlyvalid or "the %s can't contains '*t' as time format" else local hasfmt = false for s in strgmatch(val, "%%(.)") do if ALLOW_TIMEFORMAT[s] then hasfmt = true else return onlyvalid or "the '" .. s .. "' can't be used as time format" end end if not hasfmt then return "the %s doesn't contains any time formats" end end end } --- Represents the date object __Final__() __Sealed__() __Serializable__() __NoRawSet__(false) __NoNilValue__(false) class "Date" (function (_ENV) extend "ICloneable" "ISerializable" export { date = _G.os and os.date or _G.date, time = _G.os and os.time or _G.time, diff = _G.os and os.difftime or _G.difftime, pairs = pairs, type = type, getmetatable = getmetatable, strfind = strfind, rawset = rawset, tonumber = tonumber, } local offset = diff(time(date("*t", 10^8)), time(date("!*t", 10^8))) local r2Time = function (self) self.time = time(self) end local r4Time = function (self) for k, v in pairs(date("*t", self.time)) do rawset(self, k, v) end end local getnow = time ----------------------------------------------------------- -- static property -- ----------------------------------------------------------- --- Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time. __Static__() property "Now" { get = function() return Date() end } --- Gets and Sets the function that return the current time value(the total second from 1970/1/1 00:00:00) __Static__() property "GetTimeOfDay" { type = Function, set = function(self, val) getnow = val end, get = function() return getnow end } ----------------------------------------------------------- -- property -- ----------------------------------------------------------- --- The year of the date property "Year" { type = Integer, field = "year", handler = r2Time } --- The month of the year, 1-12 property "Month" { type = Integer, field = "month",handler = function(self, value) r2Time(self) if value < 1 or value > 12 then r4Time(self) end end } --- The day of the month, 1-31 property "Day" { type = Integer, field = "day", handler = function(self, value) r2Time(self) if value < 1 or value > 28 then r4Time(self) end end } --- The hour of the day, 0-23 property "Hour" { type = Integer, field = "hour", handler = function(self, value) r2Time(self) if value < 0 or value > 23 then r4Time(self) end end } --- The minute of the hour, 0-59 property "Minute" { type = Integer, field = "min", handler = function(self, value) r2Time(self) if value < 0 or value > 59 then r4Time(self) end end } --- The Second of the minute, 0-61 property "Second" { type = Integer, field = "sec", handler = function(self, value) r2Time(self) if value < 0 or value > 59 then r4Time(self) end end } --- The weekday, Sunday is 1 property "DayOfWeek" { get = function(self) return date("*t", self.time).wday end } --- The day of the year property "DayOfYear" { get = function(self) return date("*t", self.time).yday end } --- Indicates whether this instance of DateTime is within the daylight saving time range for the current time zone. property "IsDaylightSavingTime" { get = function(self) return date("*t", self.time).isdst end } --- Gets the time that represent the date and time of this instance. property "Time" { type = Integer, field = "time", handler = r4Time } ----------------------------------------------------------- -- static method -- ----------------------------------------------------------- --- Parse a string data to Date object __Static__() __Arguments__{ NEString, TimeFormat, Boolean/false } function Parse(s, format, isutc) local year, month, day, hour, min, sec local index = 1 if format:find("^!") then isutc = true format = format:sub(2) end -- %d Day of the month, zero-padded (01-31) 23 -- %H Hour in 24h format (00-23) 14 -- %m Month as a decimal number (01-12) 08 -- %M Minute (00-59) 55 -- %S Second (00-61) 02 -- %X Time representation 14:55:02 -- %Y Year 2001 local pattern = format:gsub("%%(.)", function(w) if w == "d" then day = index index = index + 1 return "(%d?%d)" elseif w == "H" then hour = index index = index + 1 return "(%d?%d)" elseif w == "m" then month = index index = index + 1 return "(%d?%d)" elseif w == "M" then min = index index = index + 1 return "(%d?%d)" elseif w == "S" then sec = index index = index + 1 return "(%d?%d)" elseif w == "X" then hour = index index = index + 1 min = index index = index + 1 sec = index index = index + 1 return "(%d?%d):(%d?%d):(%d?%d)" elseif w == "Y" then year = index index = index + 1 return "(%d%d%d%d)" end end) if not (year and month and day) or ((hour or min or sec) and not (hour and min and sec)) then error("Usage: Date.Parse(s[, format][,isutc]) - the format isn't valid", 2) end local rs = { s:match(pattern) } year = tonumber(rs[year]) month = tonumber(rs[month]) day = tonumber(rs[day]) if hour then hour = tonumber(rs[hour]) min = tonumber(rs[min]) sec = tonumber(rs[sec]) end if not (year and month and day) or ((hour or min or sec) and not (hour and min and sec)) then return end return Date(year, month, day, hour, min, sec, isutc) end __Static__() __Arguments__{ NEString, Boolean/false, Boolean/false } function Parse(s, isEndOfDay, isutc) local year, month, day, hour, min, sec local index = 0 for n in s:gmatch("%d+") do index = index + 1 if index == 1 then year = tonumber(n) elseif index == 2 then month = tonumber(n) elseif index == 3 then day = tonumber(n) elseif index == 4 then hour = tonumber(n) elseif index == 5 then min = tonumber(n) elseif index == 6 then sec = tonumber(n) break end end if (year and month and day and year >= 1970 and month >= 1 and month <= 12 and day >= 1 and day <= 31) and (not hour or (hour >= 0 and hour < 24)) and (not min or (min >= 0 and min < 60)) and (not sec or (sec >= 0 and sec < 60)) then return Date(year, month, day, hour or isEndOfDay and 23 or 0, min or isEndOfDay and 59 or 0, sec or isEndOfDay and 59 or 0, isutc) end end ----------------------------------------------------------- -- method -- ----------------------------------------------------------- --- Serialize the date function Serialize(self, info) info:SetValue("time", self.Time) end --- Return the diff second for the two Date object __Arguments__{ Date } function Diff(self, obj) return diff(self.time, obj.time) end --- Converts the value of the current DateTime object to its equivalent string representation using the specified format. __Arguments__{ TimeFormat/"%Y-%m-%d %X" } function ToString(self, fmt) return date(fmt, self.time) end --- Converts the value of the current DateTime object to its equivalent UTC string representation using the specified format. __Arguments__{ TimeFormat/"!%Y-%m-%d %X" } function ToUTCString(self, fmt) if not strfind(fmt, "^!") then fmt = "!" .. fmt end return date(fmt, self.time) end --- Adds the specified number of years to the value of this instance, and return a new date object __Arguments__{ Integer } function AddYears(self, years) return Date(self.year + years, self.month, self.day, self.hour, self.min, self.sec) end --- Adds the specified number of months to the value of this instance, and return a new date object __Arguments__{ Integer } function AddMonths(self, months) return Date(self.year, self.month + months, self.day, self.hour, self.min, self.sec) end --- Adds the specified number of months to the value of this instance, and return a new date object __Arguments__{ Integer } function AddDays(self, days) return Date(self.year, self.month, self.day + days, self.hour, self.min, self.sec) end --- Adds the specified number of hours to the value of this instance, and return a new date object __Arguments__{ Integer } function AddHours(self, hours) return Date(self.year, self.month, self.day, self.hour + hours, self.min, self.sec) end --- Adds the specified number of minutes to the value of this instance, and return a new date object __Arguments__{ Integer } function AddMinutes(self, minutes) return Date(self.year, self.month, self.day, self.hour, self.min + minutes, self.sec) end --- Adds the specified number of seconds to the value of this instance, and return a new date object __Arguments__{ Integer } function AddSeconds(self, seconds) return Date(self.year, self.month, self.day, self.hour, self.min, self.sec + seconds) end --- Return a Clone of the date oject function Clone(self) return Date(self.Time) end ----------------------------------------------------------- -- constructor -- ----------------------------------------------------------- __Arguments__{ SerializationInfo } function __new(_, info) local self = { time = info:GetValue("time") or 0 } r4Time(self) return self, true end __Arguments__{ RawTable } function __new(_, time) -- No more check return time, true end __Arguments__{ Variable("time", Integer, true) } function __new(_, tm) local self = { time = tm or getnow() } r4Time(self) return self, true end __Arguments__{ Variable("year", Integer), Variable("month", Integer), Variable("day", Integer), Variable("hour", Integer, true, 12), Variable("min", Integer, true, 0), Variable("sec", Integer, true, 0), Variable("utc", Boolean, true, false) } function __new(_, year, month, day, hour, min, sec, utc) local self = { year = year, month = month, day = day, hour = hour, min = min, sec = utc and (sec + offset) or sec, } r2Time(self) r4Time(self) return self, true end ------------------------------------ -- Meta-method ------------------------------------ __Arguments__{ Date } function __eq(self, obj) return self.time == obj.time end __Arguments__{ Date } function __lt(self, obj) return self.time < obj.time end __Arguments__{ Date } function __le(self, obj) return self.time <= obj.time end __sub = Diff __tostring = ToString export { Date } end) end)
local casino = require("casino") local event = require("event") local shell = require("shell") local unicode = require("unicode") local settings = require("settings") local computer = require('computer') local games local currencies local image local buffer local colorlib REPOSITORY = settings.REPOSITORY CURRENT_APP = nil SHOULD_INTERRUPT = false event.shouldInterrupt = function() if SHOULD_INTERRUPT then SHOULD_INTERRUPT = false if CURRENT_APP then CURRENT_APP = nil return true end end return false end local state = { selection = 1, devMode = false, currencyDropdown = false } local requiredDirectories = { "/lib/FormatModules", "/home/images/", "/home/images/games_logo", "/home/images/currencies", "/home/apps" } local libs = { { url = REPOSITORY .. "/config/settings.lua", path = "/lib/settings.lua" }, { url = REPOSITORY .. "/libs/casino.lua", path = "/lib/casino.lua" }, { url = REPOSITORY .. "/external/IgorTimofeev/AdvancedLua.lua", path = "/lib/advancedLua.lua" }, { url = REPOSITORY .. "/external/IgorTimofeev/Color.lua", path = "/lib/color.lua" }, { url = REPOSITORY .. "/external/IgorTimofeev/OCIF.lua", path = "/lib/FormatModules/OCIF.lua" }, { url = REPOSITORY .. "/external/IgorTimofeev/Image.lua", path = "/lib/image.lua" }, { url = REPOSITORY .. "/external/IgorTimofeev/DoubleBuffering.lua", path = "/lib/doubleBuffering.lua" }, { url = REPOSITORY .. "/config/games.lua", path = "/lib/games.lua" }, { url = REPOSITORY .. "/config/currencies.lua", path = "/lib/currencies.lua" }, { url = REPOSITORY .. "/libs/slot_machine.lua", path = "/lib/slot_machine.lua" } } local function isAdmin(player) for i = 1, #settings.ADMINS do if settings.ADMINS[i] == player then return true end end return false end local function writeCenter(x, y, text, color) buffer.drawText(math.floor(x - unicode.len(text) / 2), math.floor(y), color, text) end local function drawRectangleWithCenterText(x, y, width, height, text, bgColor, fgColor) buffer.drawRectangle(x, y, width, height, bgColor, 0, " ") writeCenter(width / 2 + x, height / 2 + y, text, fgColor) end local function drawBigText(x, y, text) if not text then return end local lines = casino.splitString(text, "\n") for i = 0, #lines - 1 do buffer.drawText(x, y + i, 0x000000, lines[i + 1]) end end local function drawCurrency(x, y, currency, current) buffer.drawRectangle(x, y, 46, 3, --[[current and 0xA890AA or--]] 0xE3E3E3, 0, " ") buffer.drawText(x + 8, y , 0, currency.name) buffer.drawText(x + 8, y + 1, 0, "Максимальная ставка: " .. (currency.max or "-")) buffer.drawText(x + 8, y + 2, 0, "У казино: " .. casino.getCurrencyInStorage(currency) .. " шт.") local color = currency.color or 0xE3E3E3 local darkColor = colorlib.transition(color, 0, 0.1) if currency.model == 'INGOT' then buffer.drawSemiPixelLine(x, y * 2 + 1, x + 2, y * 2 + 1, darkColor) buffer.drawSemiPixelLine(x + 3, y * 2, x + 5, y * 2, darkColor) buffer.drawSemiPixelLine(x, y * 2 + 2, x + 2, y * 2 + 2, color) buffer.drawSemiPixelLine(x + 3, y * 2 + 1, x + 5, y * 2 + 1, color) buffer.drawSemiPixelLine(x, y * 2 + 3, x + 2, y * 2 + 3, darkColor) buffer.drawSemiPixelLine(x + 3, y * 2 + 2, x + 5, y * 2 + 2, darkColor) elseif currency.model == 'DUST' then buffer.drawSemiPixelRectangle(x + 2, y * 2 + 1, 3, 2, color) buffer.drawSemiPixelRectangle(x + 1, y * 2 + 3, 5, 1, color) buffer.drawSemiPixelLine(x, y * 2 + 3, x + 3, y * 2, darkColor) buffer.drawSemiPixelLine(x + 3, y * 2, x + 6, y * 2 + 3, darkColor) buffer.drawSemiPixelLine(x + 1, y * 2 + 4, x + 5, y * 2 + 4, darkColor) elseif currency.model == 'BLOCK' then buffer.drawSemiPixelRectangle(x, y * 2 - 1, 6, 6, darkColor) buffer.drawSemiPixelRectangle(x + 1, y * 2, 4, 4, color) end end local function drawStatic() buffer.setResolution(160, 50) drawRectangleWithCenterText(1, 1, 160, 5, settings.TITLE, 0x431148, 0xFFFFFF) if (state.devMode) then writeCenter(158, 1, "{dev}", 0xE700FF) writeCenter(160, 2, "X", 0xFF0000) writeCenter(157, 3, "[LIBS]", 0xE700FF) else writeCenter(158, 1, "{dev}", 0x78517C) end buffer.drawRectangle(1, 6, 48, 45, 0xF2F2F2, 0, " ") buffer.drawChanges() end local function drawLibSettings() buffer.drawRectangle(49, 6, 112, 45, 0xFFFFFF, 0, " ") for i = 1, #libs do buffer.drawText(51, 5 + i * 2, 0x0000AA, "Скачать Правка"); buffer.drawText(68, 5 + i * 2, 0, libs[i].path); end buffer.drawText(51, 5 + (1 + #libs) * 2, 0xff0000, "При редактировании, компьютер не будет защищен от других игроков!"); buffer.drawText(51, 6 + (1 + #libs) * 2, 0xff0000, "Изменения вступят в силу после перезагрузки!"); buffer.drawChanges() end local function drawDynamic() if state.selection == 0 then drawLibSettings() return end local selection = games[state.selection] local gameImgPath = "/home/images/games_logo/" .. selection.image buffer.drawRectangle(49, 6, 112, 45, 0xFFFFFF, 0, " ") buffer.drawRectangle(1, 6, 48, 45, 0xF2F2F2, 0, " ") casino.downloadFile(REPOSITORY .. "/resources/images/games_logo/" .. selection.image, gameImgPath) buffer.drawImage(51, 7, image.load(gameImgPath)) -- 50х32 writeCenter(133, 7, selection.title, 0x000000) drawBigText(102, 9, (selection.description or " ") .. "\n \n" .. "Разработчик: " .. selection.author) for i = 1, #games do local bgColor = selection == games[i] and 0xA890AA or 0xE3E3E3 drawRectangleWithCenterText(2, 3 + i * 4, 46, 3, games[i].title, bgColor, 0x000000) end local currentCurrency = casino.getCurrency() if state.currencyDropdown then local currencyLen = #currencies for i = 1, currencyLen do drawCurrency(2, 43 - 4 * (currencyLen - i), currencies[i], currencies[i] == currentCurrency) end end drawRectangleWithCenterText(2, 46, 46, 1, "Текущая валюта", 0x431148, 0xFFFFFF) drawCurrency(2, 47, currentCurrency) buffer.drawText(40, 48, 0, "Сменить") if (state.devMode) then drawRectangleWithCenterText(51, 40, 50, 5, "Обновить", 0x431148, 0xffffff) else if selection.available then drawRectangleWithCenterText(51, 40, 50, 5, "Играть", 0x431148, 0xffffff) else drawRectangleWithCenterText(51, 40, 50, 5, "Временно недоступно", 0x433b44, 0xffffff) end end buffer.drawChanges() end local function removeUsers() local users = table.pack(computer.users()) for i = 1, #users do if not isAdmin(users[i]) then computer.removeUser(users[i]) end end end local function onPimPlayerOff(_, name) SHOULD_INTERRUPT = true end local function handlePim() if casino.container.getInventoryName() == 'pim' then removeUsers() casino.setCurrency(currencies[1]) buffer.setResolution(32, 9) buffer.drawRectangle(1, 1, 32, 9, 0xFFFFFF, 0x0, ' ') buffer.drawText(5, 3, 0x000000, 'Наступите, чтобы начать') buffer.drawText(15, 6, 0x000000, ' ||') buffer.drawText(15, 7, 0x000000, ' ||') buffer.drawText(15, 8, 0x000000, '\\ /') buffer.drawText(15, 9, 0x000000, ' \\/') buffer.drawChanges() while casino.container.getInventoryName() == 'pim' do os.sleep(0.5) end computer.addUser(casino.container.getInventoryName()) buffer.drawRectangle(1, 1, 32, 9, 0xFFFFFF, 0x0, ' ') drawRectangleWithCenterText(1, 4, 32, 1, casino.container.getInventoryName(), 0xFFFFFF, 0x0) buffer.drawText(2, 6, 0xFF0000, 'Не покидайте PIM до конца игры') buffer.drawChanges() os.sleep(2) drawStatic() drawDynamic() buffer.drawChanges() end end local function initLauncher() for i = 1, #requiredDirectories do shell.execute("md " .. requiredDirectories[i]) end for i = 1, #libs do casino.downloadFile(libs[i].url, libs[i].path) end games = require("games") currencies = require("currencies") image = require("image") buffer = require("doubleBuffering") colorlib = require("color") casino.setCurrency(currencies[1]) end initLauncher() buffer.flush() drawStatic() drawDynamic() if settings.PAYMENT_METHOD == 'PIM' then event.listen('player_off', onPimPlayerOff) end while true do :: continue :: -- В Lua отсутствует ключевое слово continiue local e, _, x, y, _, p = event.pull(1) if e == "touch" then if state.devMode and not isAdmin(p) then goto continue end -- Currency if state.currencyDropdown and state.selection > 0 then if x >= 2 and x <= 46 and y % 4 ~= 2 then local currencyId = math.floor((y - (47 - 4 * #currencies)) / 4 + 1) if currencyId > 0 and currencyId <= #currencies then casino.setCurrency(currencies[currencyId]) end end state.currencyDropdown = false drawDynamic() goto continue elseif x >= 2 and y >= 46 and x <= 92 and y <= 50 and state.selection > 0 then state.currencyDropdown = true drawDynamic() end -- Left menu buttons if (x >= 2 and x <= 47 and y >= 7 and ((y - 2) % 4)) and state.selection > 0 then local selection = math.floor((y - 3) / 4) if (selection <= #games) then state.selection = selection drawDynamic() end end -- Run/Update button if (x >= 51 and y >= 40 and x <= 100 and y <= 44) and state.selection > 0 then local selection = games[state.selection] if state.devMode then drawRectangleWithCenterText(51, 40, 50, 5, "Обновить", 0x5B5B5B, 0xffffff) buffer.drawChanges() casino.downloadFile(REPOSITORY .. "/resources/images/games_logo/" .. selection.image, "/home/images/games_logo/" .. selection.image, true) casino.downloadFile(REPOSITORY .. "/apps/" .. selection.file, "/home/apps/" .. selection.file, true) drawRectangleWithCenterText(51, 40, 50, 5, "Обновить", 0x431148, 0xffffff) drawDynamic() else if selection.available then casino.downloadFile(REPOSITORY .. "/apps/" .. selection.file, "/home/apps/" .. selection.file) CURRENT_APP = selection.title local result, errorMsg = pcall(loadfile("/home/apps/" .. selection.file)) CURRENT_APP = nil casino.gameIsOver() drawStatic() drawDynamic() end end end -- Lib buttons if state.devMode and state.selection == 0 and y >= 7 and y % 2 == 1 then local lib = libs[math.floor((y - 7) / 2) + 1] -- Download if lib and x >= 51 and x <= 57 then buffer.drawText(51, y, 0xAAAAAA, "Скачать"); buffer.drawChanges() casino.downloadFile(lib.url, lib.path, true) buffer.drawText(51, y, 0x0000AA, "Скачать"); buffer.drawChanges() end -- Edit if lib and x >= 60 and x <= 65 then local component = require("component") component.gpu.setBackground(0); component.gpu.setForeground(0xffffff); shell.execute("edit " .. lib.path) drawStatic() drawDynamic() end end -- Dev mode button if x >= 157 and y == 1 and isAdmin(p) then state.devMode = not state.devMode state.selection = 1 drawStatic() drawDynamic() end -- Reset button if x == 159 and y == 2 and state.devMode then shell.execute("reboot") end -- Libs configuration if x >= 156 and y == 3 and state.devMode then state.selection = 0 drawStatic() drawDynamic() end end if settings.PAYMENT_METHOD == 'PIM' then handlePim() end end
local Cuboid = assert(foundation.com.Cuboid) local ng = Cuboid.new_fast_node_box local function pie_on_rightclick(pos, node, clicker, itemstack, pointed_thing) local nodedef = minetest.registered_nodes[node.name] if nodedef.pie_stage > 1 then -- TODO: add a pie slice to clicker's inventory node.name = "yatm_culinary:pie_" .. (nodedef.pie_stage - 1) minetest.swap_node(pos, node) else minetest.remove_node(pos) end end local pie_node_box = { type = "fixed", fixed = { ng( 2, 0, 2, 12, 5, 12), ng( 1, 3, 1, 14, 1, 14), } } minetest.register_node("yatm_culinary:pie_8", { codex_entry_id = "yatm_culinary:pie", basename = "yatm_culinary:pie", description = "Pie", groups = { cracky = 1, }, tiles = { "yatm_pie_top.png", "yatm_pie_bottom.png", "yatm_pie_side.png", "yatm_pie_side.png", "yatm_pie_side.png", "yatm_pie_side.png" }, paramtype = "light", paramtype2 = "facedir", drawtype = "nodebox", node_box = pie_node_box, pie_stage = 8, on_rightclick = pie_on_rightclick, }) for i = 1,7 do local sliced_pie_node_box = { type = "fixed", fixed = { ng( 2, 0, 2, 12 * i / 8, 5, 12), ng( 1, 3, 1, 13 * i / 8, 1, 14), } } minetest.register_node("yatm_culinary:pie_" .. i, { codex_entry_id = "yatm_culinary:pie", basename = "yatm_culinary:pie", description = "Pie", groups = { cracky = 1, not_in_creative_inventory = 1, }, tiles = { "yatm_pie_top.png", "yatm_pie_bottom.png", "yatm_pie_side.cut.png", "yatm_pie_side.png", "yatm_pie_side.png", "yatm_pie_side.png" }, paramtype = "light", paramtype2 = "facedir", drawtype = "nodebox", node_box = sliced_pie_node_box, pie_stage = i, on_rightclick = pie_on_rightclick, }) end
/* * Torrent - 2013 Illuminati Productions * * This product is 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 panel = {}; function panel:Init() // The current angle of the radial panel self.angle = 0; // The maximum amount the angle can get to self.maxAngle = 0; // The current angular inertia of the radial panel self.inertia = 0; // All of the items that the panel contains self.Items = {}; // All of the catergories self.Catergories = {}; // Currently selected catergory self.CurrentCatergory = nil; // The function called when the panel has stopped moving self.stopFunc = false; // A variable used to tell whether the function called when the panel has stopped moving has been called self.hasStopped = false; // The mode of the panel. -1 for inwards facing panels 1 for outwards facing panels self.mode = true; self.mul = 1; // This is added into the circular calculations to "stretch" the circle on the X axis self.stretch = 0; // The speed that the panel is opened and closed at self.stateSpeed = 20; end function panel:SetMode( mode ) self.mode = mode; self.mul = (mode == 1) and 1 or -1; end // Hides all items in the current catergory function panel:HideCatergoryContents() for name, panel in pairs( self.Items[ self.CurrentCatergory ] or {} ) do panel:SetVisible( false ); end end function panel:ValidateAngles() if ( self.mode ) then if ( self.angle < 0 ) then self.angle = 0; self.inertia = 0; end if ( self.angle > self.maxAngle ) then self.angle = self.maxAngle; self.inertia = 0; end else if ( self.angle > 0 ) then self.angle = 0; self.inertia = 0; end if ( self.angle < -self.maxAngle ) then self.angle = -self.maxAngle; self.inertia = 0; end end end function panel:Think() self:ValidateAngles(); local i = 0; for name, panel in pairs( self.Items[ self.CurrentCatergory ] or {} ) do if ( !ValidPanel( panel ) ) then continue; end if ( ( self.mode && ( ( self.angle + i ) >= 0 && ( self.angle + i ) <= 180 ) || !self.mode && ( ( self.angle + i ) <= 0 && ( self.angle + i ) >= -180 ) ) ) then if ( !panel:IsVisible() ) then panel:SetVisible( true ); end local x = ( math.sin( ( ( (self.angle + i) ) * math.pi ) / 180 ) ) * ( (ScrW() / 6) - 25 - self.stretch ); local y = ( math.cos( ( ( (self.angle + i) ) * math.pi ) / 180 ) ) * ( (ScrH() / 2) - 25 ); panel:SetPos( ( self.x + x ) - 25, (self.y + y) - 25 ); else if ( panel:IsVisible() ) then panel:SetVisible( false ); end end i = i - ( self.mul * ( 25 ) ); end self:CalcRotate(); end function panel:CalcRotate() if ( self.isDepressed ) then if ( self.lastY ) then self.inertia = self.inertia + ( self.lastY - gui.MouseY() ) / 20; end if ( self.lastX ) then self.stretch = self.stretch + ( self.lastX - gui.MouseX() ); end else self.stretch = Lerp( 0.30, self.stretch or 0, 0); end // Apply inertial force self.angle = self.angle + self.mul * (self.inertia or 0); // Decrease inertia self.inertia = Lerp( 0.10, self.inertia or 0, self.shouldClose and -10 or 0 ); if ( self.angle <= 0 ) then if ( self.stopFunc && isfunction( self.stopFunc ) && !self.hasStopped ) then self.stopFunc(); self.hasStopped = true; // In every case the panel should stop it's eternal intertia when the panel has reached it's destination self.shouldClose = false; end else self.hasStopped = false; end // Store last mouse position self.lastY = gui.MouseY(); self.lastX = gui.MouseX(); end function panel:Open() if ( self.stopFunc ) then return; end self.angle = 0; // Kick the panel open self.inertia = self.stateSpeed; end function panel:Close() if ( self.stopFunc ) then return; end // Keep spinning the panel until it closes self.shouldClose = true; end function panel:SetStopFunction( func ) self.stopFunc = func; end function panel:OnMousePressed( panel, func ) panel.isDepressed = true; panel.startClickX, panel.startClickY = gui.MouseX(), gui.MouseY(); panel.pressedAt = CurTime(); end function panel:OnMouseReleased( panel, func ) if ( !panel.pressedAt ) then return; end panel.isDepressed = false; if ( panel.inertia && ( panel.inertia < 1 && panel.inertia > -1 ) && ( CurTime() - panel.pressedAt ) < 0.2 ) then if ( func && isfunction(func) ) then func(); end end end function panel:AddItem( name, model, info, price, func, cat ) if ( !ValidPanel( self:GetParent() ) ) then return; end self.Items[ cat ] = self.Items[ cat ] or {}; self.Items[ cat ][ name ] = vgui.Create( "DPanel", self:GetParent() ); self.Items[ cat ][ name ]:SetSize( 50, 50 ); self.Items[ cat ][ name ].Paint = function( panel ) local w, h = panel:GetSize(); if ( self.Items[ "Favourites" ] && self.Items[ "Favourites" ][ name ] ) then surface.SetDrawColor( Color( 255, 255, 0, 255 ) ); surface.DrawOutlinedRect( 0, 0, w, h ); elseif ( LocalPlayer():GetMoney() < ( price or 0) ) then surface.SetDrawColor( Color( 255, 0, 0, 255 ) ); surface.DrawOutlinedRect( 0, 0, w, h ); else surface.SetDrawColor( Color( 0, 255, 0, 255 ) ); surface.DrawOutlinedRect( 0, 0, w, h ); end end self.Items[ cat ][ name ].Icon = vgui.Create( "SpawnIcon", self.Items[ cat ][name] ); self.Items[ cat ][ name ].Icon:SetModel( model ); self.Items[ cat ][ name ].Icon:SetPos( 1, 1 ); self.Items[ cat ][ name ].Icon:SetSize( 48, 48 ); self.Items[ cat ][ name ].Icon:SetTooltip( info ); local f_oldP = self.Items[ cat ][ name ].Icon.OnMousePressed; local f_oldR = self.Items[ cat ][ name ].Icon.OnMouseReleased; local _self = self; self.Items[ cat ][ name ].Icon.OnMousePressed = function( panel, t ) if ( input.IsMouseDown( MOUSE_LEFT ) ) then _self:OnMousePressed(_self,func); f_oldP( panel, t ); elseif ( input.IsMouseDown( MOUSE_RIGHT ) ) then local tbl = string.Explode( ",", cookie.GetString( "torrent_prop_favourites" ) or "" ) or {}; if ( table.HasValue( tbl, model ) ) then local _cookie = ""; for _, mdl in pairs( tbl ) do if ( mdl == model || mdl == "" ) then continue; end _cookie = _cookie .. mdl .. ","; end if ( self.Items[ "Favourites" ] && self.Items[ "Favourites" ][ name ] ) then self.Items[ "Favourites" ][ name ]:Remove(); self.Items[ "Favourites" ][ name ] = nil; end cookie.Set( "torrent_prop_favourites", _cookie ); else cookie.Set( "torrent_prop_favourites", ( cookie.GetString( "torrent_prop_favourites" ) or "" ) .. model .. "," ); self:AddItem( name, model, info, price, func, "Favourites" ); end self:DoLayout(); end end self.Items[ cat ][ name ].Icon.OnMouseReleased = function( panel, t ) _self:OnMouseReleased(_self,func); f_oldR( panel, t ); end self.Items[ cat ][ name ]:SetVisible( false ); end function panel:DoLayout( switch ) local count = table.Count( self.Catergories ) + 1; local height, width = 25, 150; local i = 0; local amount = 0; for name, panel in pairs( self.Catergories ) do local lAmount = amount; amount = table.Count( self.Items[ name ] or {} ); if ( amount > lAmount && switch ) then self.CurrentCatergory = name; end panel:SetPos( self.mode and 1 or ScrW() - width - 1, ( (ScrH() / 2) - ( count * height ) ) + i ); panel:SetSize( width, height ); panel:SetText( panel:GetName() .. " (".. amount .. ")" ) i = i + height; end local cmax = ( table.Count( self.Items[ self.CurrentCatergory ] or {} )-1 ) * 20; self.maxAngle = ( cmax > 180 ) and cmax or 180; end function panel:AddCat( name ) if ( self.Catergories[ name ] ) then return; end self.Catergories[ name ] = vgui.Create( "DButton", self:GetParent() ); self.Catergories[ name ]:SetName( name ); self.Catergories[ name ].DoClick = function( panel ) self:Close(); self:SetStopFunction( function() // Clean up panels self:HideCatergoryContents(); self.CurrentCatergory = panel:GetName(); self.angle = 0; local cmax = ( ( table.Count( self.Items[ self.CurrentCatergory ] or {} ) ) * 25) + ( self.mul * 1 ); self.maxAngle = ( cmax > 180 ) and cmax or 180 ; self:SetStopFunction( nil ); self:Open(); end); end self.CurrentCatergory = name; end vgui.Register( "sm_radial_itemlist", panel, "Panel" )
-- This file is subject to copyright - contact swampservers@gmail.com for more information. -- INSTALL: CINEMA SWEP.PrintName = "Golf Club" SWEP.ViewModel = "models/pyroteknik/putter.mdl" SWEP.WorldModel = "models/pyroteknik/putter.mdl" SWEP.Slot = 0 SWEP.AutoSwitchTo = false ------------------------------------------------------------------- SWEP.Author = "Swamp & PYROTEKNIK" SWEP.Purpose = "Hit the thing with it" SWEP.Instructions = "Left/right click: place, hit ball\nReload: retry hole" SWEP.Spawnable = true SWEP.AdminSpawnable = true ----------------------------------------------- SWEP.Primary.Delay = 0.3 SWEP.Primary.Recoil = 0 SWEP.Primary.Damage = 0 SWEP.Primary.NumShots = 1 SWEP.Primary.Cone = 0 SWEP.Primary.ClipSize = 1 SWEP.Primary.DefaultClip = 1 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "none" ------------------------------------------------- SWEP.Secondary.Delay = 60.999999999 SWEP.Secondary.Recoil = 0 SWEP.Secondary.Damage = 1 SWEP.Secondary.NumShots = 1 SWEP.Secondary.Cone = 0 SWEP.Secondary.ClipSize = 1 SWEP.Secondary.DefaultClip = 1 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" ------------------------------------------------- function SWEP:SetupDataTables() self:NetworkVar("Int", 0, "Stage") self:NetworkVar("Int", 1, "Stroke") self:NetworkVar("Entity", 0, "Ball") self:NetworkVar("Bool", 1, "Controls") end -- Called every frame function SWEP:Think() -- if SERVER and self:GetOwner()==ME() then print(self:GetStage()) end local ht = (self:GetStage() == 2) and "passive" or "normal" if ht ~= self:GetHoldType() then self:SetHoldType(ht) end if SERVER and self:GetStage() == 2 then -- print(self:GetBall()) if self.Owner:GetPos():Distance(self:GetBall():GetPos()) > self.ShotFinishDist + 300 then self:CancelShot() end end -- if (SERVER) then -- if (self:Clip1() > 0 and stage ~= 0) then -- self:SetStage(0) -- end -- if (stage == 1) then -- local fball = self.ActiveBall -- if (IsValid(fball)) then -- if (not fball:GetPhysicsObject():IsMotionEnabled()) then -- self:SetBallToShoot(fball) -- self:SetStage(2) -- end -- end -- end -- end end function SWEP:WeirdGolf() return self:GetBall():GetControls() end function SWEP:PrimaryAttack() if self:GetStage() == 2 and self:WeirdGolf() then if CLIENT and LocalPlayer() == self.Owner and IsFirstTimePredicted() then if GOLFCAMVECTOR then ENDGOLFSHOT() return end local ball = self:GetBall() local p1 = ball:GetPos() local p2 = util.IntersectRayWithPlane(self:GetOwner():EyePos(), self:GetOwner():EyeAngles():Forward(), p1, Vector(0, 0, 1)) if p1:Distance(self.Owner:GetPos()) < 80 and p2 then local vec = p2 - p1 vec.z = 0 STARTGOLFSHOT(vec:GetNormalized()) end end return end -- if self:GetStage()== 2 then -- self:GetOwner():SetAnimation(PLAYER_ATTACK1) -- end if SERVER then self:SV_PrimaryAttack() end self:SetNextPrimaryFire(CurTime() + 0.2) self:SetNextSecondaryFire(CurTime() + 0.2) return true end function SWEP:SecondaryAttack() if SERVER then self:CancelShot() end end function SWEP:Reload() if SERVER then if CurTime() - (self.ReloadTime or 0) < 0.5 then return end self.ReloadTime = CurTime() self:CancelShot() self:SetControls(not self:GetControls()) self.Owner:SendLua([[surface.PlaySound('weapons/smg1/switch_single.wav')]]) end end function SWEP:Holster() if SERVER then self:CancelShot() end return true end function SWEP:OnRemove() if SERVER then self:CancelShot() end end function HitGolfball(ball, speed) speed.z = 0 if speed:Length() > 500 then speed = speed:GetNormalized() * 500 end ball:GetPhysicsObject():ApplyForceCenter(speed * 40) end
-- This file is licensed under the terms of the BSD 2-clause license. -- See LICENSE.txt for details. irc.msgs = irc.lib.msgs function irc:logChat(message, name) if name then name = " to "..name else name = "" end minetest.log("action", "IRC CHAT"..name..": "..message) end function irc:sendLocal(message) minetest.chat_send_all(message) irc:logChat(message) end function irc:playerMessage(name, message) return ("<%s> %s"):format(name, message) end
function PowerUpVariaSuit.main() end PowerUpVariaSuit.Self = nil function PowerUpVariaSuit.OnPickedUp(_ARG_0_) Game.PlayEntitySoundContinueOnDead("generic/obtencion.wav", _ARG_0_.sName, 1, 500, 4000, 1) local oActor = Game.GetActor("cutsceneplayer_30") if oActor ~= nil then _ARG_0_.MODELUPDATER.bWantsEnabled = false oActor.CUTSCENE:TryLaunchCutscene() end PowerUpVariaSuit.Self = _ARG_0_ end function PowerUpVariaSuit.ShowMessage() if PowerUpVariaSuit.Self ~= nil then PowerUpVariaSuit.Self.PICKABLE:OnItemEnd() Game.SaveGame("checkpoint", "", "SP_CUT_VariaSuit", false) end end function PowerUpVariaSuit.ChangeSuit() Game.GetPlayer().INVENTORY:SetItemAmount("ITEM_VARIA_SUIT", 1, true) Game.GetPlayer().MODELUPDATER.sModelAlias = "Varia" Game.GetPlayer().MODELUPDATER:ForceUpdate() end function PowerUpVariaSuit.OnItemEnd(_ARG_0_) end
return {'efedrine','efemeer','efemeriden','efe','efemere'}
require('utils') local image = require("../image"); local item = require("../item") return { name = "Rummage", amount = 5, condition = function (state) return state.knightInvited and state.coins >= 10 end, description = "You decide to rummage through the knights' storeroom.", heads = { effectDescription = "Obtain ??? (10%)", effect = function (state) if not table.contains(state.items, item.crystalBall) and love.math.random() <= 0.05 then table.insert(state.items, item.crystalBall) return { description = "You find a crystal ball. Who knew you had such an item in the storeroom!", image = image.crystalBall } else return { description = "You find nothing. Alas, c'est la vie.", image = image.shrug } end end }, tails = { effectDescription = "Obtain 3 'Red Apple' (75%)", effect = function (state) if love.math.random() <= 0.75 then table.insert(state.items, item.apple) table.insert(state.items, item.apple) table.insert(state.items, item.apple) return { description = "You find 3 apples. Now you can keep up to 3 doctors away a day!", image = image.apple } else return { description = "You find nothing. Alas, c'est la vie.", image = image.shrug } end end }, beg = { effectDescription = "+2 coins (50%)", effect = function (state) if love.math.random() <= 0.5 then state.coins = state.coins + 2 return { description = "You find 2 coins on the ground. Yeah, you'll take it.", image = image.plus2 } else return { description = "You find nothing. Alas, c'est la vie.", image = image.shrug } end end } }
--[[ Nameplate Filter Add the nameplates name that you do NOT want to see. ]] local E, L, V, P, G = unpack(select(2, ...)) --Engine G.nameplate.filters = { ElvUI_Boss = { triggers = { level = true, curlevel = -1, priority = 2 }, actions = { usePortrait = true, scale = 1.15 } }, ElvUI_Target = { triggers = { isTarget = true }, actions = { scale = 1.2 } }, ElvUI_NonTarget = { triggers = { notTarget = true, requireTarget = true, nameplateType = { enable = true, friendlyPlayer = true, friendlyNPC = true, enemyPlayer = true, enemyNPC = true } }, actions = { alpha = 30 } }, ElvUI_Explosives = { triggers = { priority = 2, nameplateType = { enable = true, enemyNPC = true }, names = { ["120651"] = true } }, actions = { usePortrait = true, scale = 1.15, color = { health = true, healthColor = {r = 0, g = 255, b = 255} } } } } E.StyleFilterDefaults = { triggers = { priority = 1, targetMe = false, isTarget = false, notTarget = false, requireTarget = false, questBoss = false, level = false, casting = { isCasting = false, isChanneling = false, notCasting = false, notChanneling = false, interruptible = false, notSpell = false, spells = {} }, role = { tank = false, healer = false, damager = false }, classification = { worldboss = false, rareelite = false, elite = false, rare = false, normal = false, trivial = false, minus = false }, class = {}, -- this can stay empty we only will accept values that exist raidTarget = { star = false, circle = false, diamond = false, triangle = false, moon = false, square = false, cross = false, skull = false }, talent = { type = "normal", enabled = false, requireAll = false, tier1enabled = false, tier1 = {missing = false, column = 0}, tier2enabled = false, tier2 = {missing = false, column = 0}, tier3enabled = false, tier3 = {missing = false, column = 0}, tier4enabled = false, tier4 = {missing = false, column = 0}, tier5enabled = false, tier5 = {missing = false, column = 0}, tier6enabled = false, tier6 = {missing = false, column = 0}, tier7enabled = false, tier7 = {missing = false, column = 0} }, threat = { enable = false, good = false, goodTransition = false, badTransition = false, bad = false, offTank = false, offTankGoodTransition = false, offTankBadTransition = false }, curlevel = 0, maxlevel = 0, minlevel = 0, healthThreshold = false, healthUsePlayer = false, underHealthThreshold = 0, overHealthThreshold = 0, powerThreshold = false, powerUsePlayer = false, underPowerThreshold = 0, overPowerThreshold = 0, names = {}, creatureType = { enable = false, Aberration = false, Beast = false, Critter = false, Demon = false, Dragonkin = false, Elemental = false, ["Gas Cloud"] = false, Giant = false, Humanoid = false, Mechanical = false, ["Not specified"] = false, Totem = false, Undead = false, ["Wild Pet"] = false, ["Non-combat Pet"] = false }, nameplateType = { enable = false, friendlyPlayer = false, friendlyNPC = false, enemyPlayer = false, enemyNPC = false, player = false }, reactionType = { enabled = false, reputation = false, hated = false, hostile = false, unfriendly = false, neutral = false, friendly = false, honored = false, revered = false, exalted = false }, instanceType = { none = false, scenario = false, party = false, raid = false, arena = false, pvp = false }, keyMod = { enable = false, Modifier = false, Shift = false, Alt = false, Control = false, LeftShift = false, LeftAlt = false, LeftControl = false, RightShift = false, RightAlt = false, RightControl = false }, instanceDifficulty = { dungeon = { normal = false, heroic = false, mythic = false, ["mythic+"] = false, timewalking = false }, raid = { lfr = false, normal = false, heroic = false, mythic = false, timewalking = false, legacy10normal = false, legacy25normal = false, legacy10heroic = false, legacy25heroic = false } }, cooldowns = { names = {}, mustHaveAll = false }, buffs = { mustHaveAll = false, missing = false, names = {}, minTimeLeft = 0, maxTimeLeft = 0 }, debuffs = { mustHaveAll = false, missing = false, names = {}, minTimeLeft = 0, maxTimeLeft = 0 }, isResting = false, isPet = false, isNotPet = false, isPlayerControlled = false, isNotPlayerControlled = false, isOwnedByPlayer = false, isNotOwnedByPlayer = false, isPvP = false, isNotPvP = false, isTapDenied = false, isNotTapDenied = false, playerCanAttack = false, playerCanNotAttack = false, -- combat inCombat = false, outOfCombat = false, inCombatUnit = false, outOfCombatUnit = false, -- vehicle inVehicle = false, outOfVehicle = false, inVehicleUnit = false, outOfVehicleUnit = false }, actions = { color = { health = false, power = false, border = false, name = false, healthColor = {r = 1, g = 1, b = 1, a = 1}, powerColor = {r = 1, g = 1, b = 1, a = 1}, borderColor = {r = 1, g = 1, b = 1, a = 1}, nameColor = {r = 1, g = 1, b = 1, a = 1} }, texture = { enable = false, texture = "ElvUI Norm" }, flash = { enable = false, color = {r = 1, g = 1, b = 1, a = 1}, speed = 4 }, hide = false, usePortrait = false, nameOnly = false, scale = 1, alpha = -1 } }
local name = "nfpm" local version = "2.15.1" food = { name = name, description = "nFPM is a simple, 0-dependencies, deb, rpm and apk packager.", license = "MIT", homepage = "https://nfpm.goreleaser.com", version = version, packages = { { os = "linux", arch = "arm64", url = "https://github.com/goreleaser/nfpm/releases/download/v2.15.1/nfpm_2.15.1_Linux_arm64.tar.gz", sha256 = "4725f8d645472e4c3a4e4ae19a86cb1f373de082b8e107f38dd0a4b5609b808b", resources = { { path = "nfpm", installpath = "bin/nfpm", executable = true }, } }, { os = "darwin", arch = "amd64", url = "https://github.com/goreleaser/nfpm/releases/download/v2.15.1/nfpm_2.15.1_Darwin_x86_64.tar.gz", sha256 = "9512b6b706cc750601b0f42f320ff31fb44cd9ef73ffef408c75431ee008ce77", resources = { { path = "nfpm", installpath = "bin/nfpm", executable = true }, } }, { os = "windows", arch = "amd64", url = "https://github.com/goreleaser/nfpm/releases/download/v2.15.1/nfpm_2.15.1_Windows_x86_64.zip", sha256 = "749c77d62abcfd9632d72883e9fde0c1ef7061e105fe05084cd5a70436d83362", resources = { { path = "nfpm.exe", installpath = "bin\\nfpm.exe", }, } }, { os = "darwin", arch = "arm64", url = "https://github.com/goreleaser/nfpm/releases/download/v2.15.1/nfpm_2.15.1_Darwin_arm64.tar.gz", sha256 = "bc7957f75fd36f55d36118296db017701aa89c038f060269b3bc59b54058488c", resources = { { path = "nfpm", installpath = "bin/nfpm", executable = true }, } }, { os = "windows", arch = "arm64", url = "https://github.com/goreleaser/nfpm/releases/download/v2.15.1/nfpm_2.15.1_Windows_arm64.zip", sha256 = "860dedf5dcb9005a825f35694a062912696dde21209c6ef1a66fb6e924d02647", resources = { { path = "nfpm.exe", installpath = "bin\\nfpm.exe", }, } }, { os = "linux", arch = "amd64", url = "https://github.com/goreleaser/nfpm/releases/download/v2.15.1/nfpm_2.15.1_Linux_x86_64.tar.gz", sha256 = "9096188ef2fae545c1d1467a6802e58a19ddab827cf9acee2ebd68d8e456dfff", resources = { { path = "nfpm", installpath = "bin/nfpm", executable = true }, } }, } }
if not LoadResourceFile(GetCurrentResourceName(), "players.json") then SaveResourceFile(GetCurrentResourceName(), "players.json", "{}", -1) end Citizen.CreateThread(function() while GetConvar('rcon_password', nil) ~= nil do local buffer = GetConsoleBuffer() for i=0, GetNumPlayerIndices() -1 do local player = GetPlayerFromIndex(i) if IsPlayerAuthed(player) then TriggerClientEvent("console:SetAuth", player, true) TriggerClientEvent("console:UpdateConsoleBuffer", player, buffer) else TriggerClientEvent("console:SetAuth", player, false) end end Citizen.Wait(500) end print('^1Fatal Error (ingame console): ^3No rcon password is defined. Make sure to set \'rcon_password\' in your server.cfg^7') end) RegisterServerEvent("console:ExecuteConsoleCommand") AddEventHandler("console:ExecuteConsoleCommand", function(cmd) if IsPlayerAuthed(source) then ExecuteCommand(cmd) if not IsPrincipalAceAllowed('resource.'..GetCurrentResourceName(), 'command') then print('^1Please make sure to add ^3add_ace resource.'..GetCurrentResourceName()..' command allow^1 to your server.cfg^7') end end end) RegisterServerEvent("console:CheckPasssword") AddEventHandler("console:CheckPasssword", function(pwd) if GetConvar('rcon_password', nil) == pwd then local players = json.decode(LoadResourceFile(GetCurrentResourceName(), "players.json")) if players == nil then players = {} end players[GetSteamHex(source)] = pwd SaveResourceFile(GetCurrentResourceName(), "players.json", json.encode(players), -1) --TriggerClientEvent("console:SetAuth", source, true) else TriggerClientEvent("console:ErrorMsg", source, 'Invalid rcon password.') end end) function IsPlayerAuthed(player) local players = json.decode(LoadResourceFile(GetCurrentResourceName(), "players.json")) if players == nil then players = {} end local hex = GetSteamHex(player) if hex ~= nil then if players[hex] == GetConvar('rcon_password', nil) then return true end end return false end function GetSteamHex(player) local hex = nil for i=0, GetNumPlayerIdentifiers(player)-1 do local id = GetPlayerIdentifier(player, i) if string.find(id, "steam:") then hex = id break; end end return hex; end
local AddUiTop = {} local Controller = require('mvc.Controller') local App = require('app.App') local _suitop function AddUiTop.show(type_, callBack_) type_ = type_ or 1 if not _suitop then _suitop = Controller.loadController('UiTopController'); --App.topLayer:addChild(_suitop.view) end _suitop:switch(type_, callBack_) _suitop.view:setVisible(true) _suitop:enabledSetting(true) end function AddUiTop.enableSetting(b) _suitop:enabledSetting(b) end function AddUiTop.hide() if _suitop then _suitop.view:setVisible(false) end end return AddUiTop
--Vayne local pred = module.internal("pred") local ts = module.internal('TS') local orb = module.internal("orb") local EvadeInternal = module.seek("evade") local minionmanager = objManager.minions local delayedActions, delayedActionsExecuter = {}, nil local function DelayAction(func, delay, args) --delay in seconds if not delayedActionsExecuter then function delayedActionsExecuter() for t, funcs in pairs(delayedActions) do if t <= os.clock() then for i = 1, #funcs do local f = funcs[i] if f and f.func then f.func(unpack(f.args or {})) end end delayedActions[t] = nil end end end cb.add(cb.tick, delayedActionsExecuter) end local t = os.clock() + (delay or 0) if delayedActions[t] then delayedActions[t][#delayedActions[t] + 1] = {func = func, args = args} else delayedActions[t] = {{func = func, args = args}} end end local function CheckBuffType(obj, bufftype) if obj then for i = 0, obj.buffManager.count - 1 do local buff = obj.buffManager:get(i) if buff and buff.valid and buff.type == bufftype and (buff.stacks > 0 or buff.stacks2 > 0) then return true end end end end local function CheckBuff(obj, buffname) if obj then for i = 0, obj.buffManager.count - 1 do local buff = obj.buffManager:get(i) if buff and buff.valid and buff.name == buffname and buff.stacks == 1 then return true end end end end local function GetPercentHealth(obj) local obj = obj or player return (obj.health / obj.maxHealth) * 100 end local function GetPercentMana(obj) local obj = obj or player return (obj.mana / obj.maxMana) * 100 end local function GetPercentPar(obj) local obj = obj or player return (obj.par / obj.maxPar) * 100 end local interruptableSpells = { ["anivia"] = { {menuslot = "R", slot = 3, spellname = "glacialstorm", channelduration = 6} }, ["caitlyn"] = { {menuslot = "R", slot = 3, spellname = "caitlynaceinthehole", channelduration = 1} }, ["ezreal"] = { {menuslot = "R", slot = 3, spellname = "ezrealtrueshotbarrage", channelduration = 1} }, ["fiddlesticks"] = { {menuslot = "W", slot = 1, spellname = "drain", channelduration = 5}, {menuslot = "R", slot = 3, spellname = "crowstorm", channelduration = 1.5} }, ["gragas"] = { {menuslot = "W", slot = 1, spellname = "gragasw", channelduration = 0.75} }, ["janna"] = { {menuslot = "R", slot = 3, spellname = "reapthewhirlwind", channelduration = 3} }, ["karthus"] = { {menuslot = "R", slot = 3, spellname = "karthusfallenone", channelduration = 3} }, ["katarina"] = { {menuslot = "R", slot = 3, spellname = "katarinar", channelduration = 2.5} }, ["lucian"] = { {menuslot = "R", slot = 3, spellname = "lucianr", channelduration = 2} }, ["lux"] = { {menuslot = "R", slot = 3, spellname = "luxmalicecannon", channelduration = 0.5} }, ["malzahar"] = { {menuslot = "R", slot = 3, spellname = "malzaharr", channelduration = 2.5} }, ["masteryi"] = { {menuslot = "W", slot = 1, spellname = "meditate", channelduration = 4} }, ["missfortune"] = { {menuslot = "R", slot = 3, spellname = "missfortunebullettime", channelduration = 3} }, ["nunu"] = { {menuslot = "R", slot = 3, spellname = "absolutezero", channelduration = 3} }, ["pantheon"] = { {menuslot = "R", slot = 3, spellname = "pantheonrjump", channelduration = 2} }, ["shen"] = { {menuslot = "R", slot = 3, spellname = "shenr", channelduration = 3} }, ["twistedfate"] = { {menuslot = "R", slot = 3, spellname = "gate", channelduration = 1.5} }, ["varus"] = { {menuslot = "Q", slot = 0, spellname = "varusq", channelduration = 4} }, ["warwick"] = { {menuslot = "R", slot = 3, spellname = "warwickr", channelduration = 1.5} }, ["xerath"] = { {menuslot = "R", slot = 3, spellname = "xerathlocusofpower2", channelduration = 3} } } local function ST(res, obj, Distancia) if Distancia > 1000 then return true end res.obj = obj return true end local function GetTargetSelector() return ts.get_result(ST).obj end local function Floor(number) return math.floor((number) * 100) * 0.01 end local FlashSlot = nil if player:spellSlot(4).name == "SummonerFlash" then FlashSlot = 4 elseif player:spellSlot(5).name == "SummonerFlash" then FlashSlot = 5 end local condemnTable = { } local tumblePositions = { } local castPos = nil local menu = menu("Nicky [Vayne]", "[Nicky]Vayne") menu:menu("MQ", "Setting [Q]") menu.MQ:header("XD", "Setting [Q]") menu.MQ:boolean("QC", "Use Q in Combo", true) menu.MQ:dropdown("AFO", "Use [Q]: ", 2, {"After Attack", "Pos Attack"}) menu.MQ:dropdown("Qmode", "AA Reset Mode: ", 2, {"Heroes Only", "Heroes + Jungle", "Always", "Never"}) menu.MQ:dropdown("Q2mode", "Tumble Logic: ", 1, {"Smart", "Aggressive"}) -- menu:menu("MW", "Setting [W]") menu.MW:header("XD2", "Setting [W]") menu.MW:boolean("FW", "Force Marked Target", true) -- menu:menu("ME", "Setting [E]") menu.ME:boolean("AutoCoondem", "Use Auto Condemn", true) menu.ME:boolean("CF", "Use Auto Flash + Condemn", true) menu.ME:boolean("ATE", "AutoInterrupt", false) menu.ME:slider("CH", "Condemn Hitchance", 50, 0, 100, 1) menu.MW:boolean("try", "Use To Proc Third Mark", false) -- menu:menu("MR", "Setting [R]") menu.MR:boolean("RC", "Use R in Combo", true) menu.MR:slider("Rhitenemy", "Min. Enemies to Use", 3, 1, 5, 1) menu:menu("JC", "Setting [Jungle]") menu.JC:boolean("QJ", "Use Q in Jungle", true) menu.JC:boolean("AAE", "Use [E] Condemn", true) menu.JC:slider("manaj", "Mana [Jungle]", 45, 0, 100, 1) -- menu:menu("Keys", "Setting [Keys]") menu.Keys:keybind("CK", "[Key] Combo", "Space", nil) local function ValidTarget(object) return (object and not object.isDead and object.isVisible and object.isTargetable and not CheckBuffType(object, 17)) end local function GetDistanceSqr(p1, p2) local p2 = p2 or player local dx = p1.x - p2.x local dz = (p1.z or p1.y) - (p2.z or p2.y) return dx * dx + dz * dz end local function GetDistance(p1, p2) local squaredDistance = GetDistanceSqr(p1, p2) return math.sqrt(squaredDistance) end local function IsValidTarget(unit, range) return unit and unit.isVisible and not unit.isDead and (not range or GetDistance(unit) <= range) end local function RotateAroundPoint(v1,v2, angle) cos, sin = math.cos(angle), math.sin(angle) x = ((v1.x - v2.x) * cos) - ((v2.z - v1.z) * sin) + v2.x z = ((v2.z - v1.z) * cos) + ((v1.x - v2.x) * sin) + v2.z return vec3(x, v1.y, z or 0) end local function GetWallPosition(target, range) range = range or 400 for i= 0, 360, 45 do angle = i * math.pi/180 targetPosition = target.pos targetRotated = vec3(targetPosition.x + range, targetPosition.y, targetPosition.z) Wallid = vec3(RotateAroundPoint(targetRotated, targetPosition, angle)) if navmesh.isWall(Wallid) and GetDistance(Wallid) < range then return Wallid end end end local function IsQEvade(t,f,x) return EvadeInternal.core.is_action_safe(t, f, x) end local function FlashE() for i = 0, objManager.enemies_n - 1 do local enemy = objManager.enemies[i] if ValidTarget(enemy) then if IsValidTarget(enemy, 700) and (FlashSlot and player:spellSlot(FlashSlot).state == 0) and player:spellSlot(2).state == 0 then targetPos = enemy.pos playerPos = player.pos wallPos = GetWallPosition(enemy, 435) if (wallPos) then insecPos = targetPos + (targetPos - wallPos):norm() * 200 if insecPos:dist(playerPos) <= 425 then --if then player:castSpell("obj", 2, enemy) DelayAction(function() player:castSpell("pos", FlashSlot, insecPos) end, 0.1) --end end end end end end end local function OnProcessSpell(spell) if menu.ME.ATE:get() then if spell.owner.type == TYPE_HERO and spell.owner.team == TEAM_ENEMY then -- <3 <3 <3 By Kornis <3 <3 <3 local enemyName = string.lower(spell.owner.charName) if interruptableSpells[enemyName] then for i = 1, #interruptableSpells[enemyName] do if player.pos2D:dist(spell.owner.pos2D) < 700 and ValidTarget(spell.owner) and player:spellSlot(2).state == 0 then player:castSpell("obj", 2, spell.owner) end end end end end end local function Condemn(target) local pP = vec3(player.x, player.y, player.z) local eP = vec3(target.x, target.y, target.z) local eP2 = target.pos local pD = Floor(410) if (navmesh.isWall(eP:ext(pP,-pD)) or navmesh.isWall(eP:ext(pP, -pD/2)) or navmesh.isWall(eP:ext(pP, -pD/3))) then local hitchance = 50 / 100 eP2 = eP + (eP2 - eP):norm() * target.moveSpeed * hitchance * 0.5 for i = 15, pD, 75 do local col1 = eP2 + (eP2 - pP):norm() * i local col2 = eP + (eP - pP):norm() * i if navmesh.isWall(col1) and navmesh.isWall(col2) then player:castSpell("obj", 2, target) end end end end local function GetKitePosition(target) tumblePositions = {} for i = 0, 360, 22.5 do angle = i * (math.pi/180) myPos = player.pos tPos = target.pos rot = RotateAroundPoint(tPos, myPos, angle) pos = myPos + (myPos - rot):norm() * 300 table.insert(tumblePositions, pos) if ValidTarget(target) then for i = 0, objManager.enemies_n - 1 do local target = objManager.enemies[i] dist = GetDistance(target, pos) / 2 if (dist < 340 and dist > 200) then return pos end end else dist = GetDistance(vec3(target.x, target.y, target.z), pos) if dist > 250 and dist < 380 then return pos end end end return nil end local function count_enemies_in_range(pos, range) local enemies_in_range = {} for i = 0, objManager.enemies_n - 1 do local enemy = objManager.enemies[i] if pos:dist(enemy.pos) < range and IsValidTarget(enemy) then enemies_in_range[#enemies_in_range + 1] = enemy end end return enemies_in_range end local function count_allyes_in_range(pos, range) local allyes_in_range = {} for i = 0, objManager.allies_n - 1 do local allg = objManager.allies[i] if pos:dist(allg.pos) < range and IsValidTarget(allg) then allyes_in_range[#allyes_in_range + 1] = allg end end return allyes_in_range end local function dasdasdasda(target) local wallPos = GetWallPosition(target, 140) local qToEPos = GetWallPosition(target, 200) local kitePos = GetKitePosition(target) if GetPercentHealth(player) < 50 and GetPercentHealth(target) > 50 then local IspOS = player.pos + (target.pos - player.pos):norm() * -150 player:castSpell("pos", 0, vec3(IspOS)) elseif GetPercentHealth(player) > 50 and GetPercentHealth(target) < 50 then local IspOS2 = player.pos + (target.pos - player.pos):norm() * 150 player:castSpell("pos", 0, vec3(IspOS2)) elseif GetDistance(target) > player.attackRange then local IspOS32 = player.pos + (target.pos - player.pos):norm() * 150 player:castSpell("pos", 0, vec3(IspOS32)) elseif #count_enemies_in_range(player.pos, 1000) >= 2 then local ddddd = player.pos + (target.pos - player.pos):norm() * -150 player:castSpell("pos", 0, vec3(ddddd)) end end local function IsDangerousPosition(unit) for i = 0, objManager.enemies_n - 1 do local target = objManager.enemies[i] if not target.isDead and unit:distSqr(target) < 300 * 300 then return true end end return false end local function GetSmartTumblePos(target) local myHeroPos = player.pos local possiblePos = myHeroPos:ext(mousePos, 300) or vec3(0,0,0) local targetPos = vec3(target.x, target.y, target.z) or vec3(0,0,0) local p0 = myHeroPos local points= { [1] = p0 + vec3(300,0,0), [2] = p0 + vec3(277,0,114), [3] = p0 + vec3(212,0,212), [4] = p0 + vec3(114,0,277), [5] = p0 + vec3(0,0,300), [6] = p0 + vec3(-114,0,277), [7] = p0 + vec3(-212,0,212), [8] = p0 + vec3(-277,0,114), [9] = p0 + vec3(-300,0,0), [10] = p0 + vec3(-277,0,-114), [11] = p0 + vec3(-212,0,-212), [12] = p0 + vec3(-114,0,-277), [13] = p0 + vec3(0,0,-300), [14] = p0 + vec3(114,0,-277), [15] = p0 + vec3(212,0,-212), [16] = p0 + vec3(277,0,-114)} --- for i=1,#points do if IsDangerousPosition(points[i]) == false and GetDistanceSqr(points[i], targetPos) < 500 * 500 then if (navmesh.isWall(targetPos:ext(myHeroPos, -450))) then return points[i] end end end if IsDangerousPosition(possiblePos) == false then return possiblePos end for i=1,#points do if IsDangerousPosition(points[i]) == false and GetDistanceSqr(points[i], targetPos) < 500 * 500 then --and GetDistance(points[i],mousePos) <= GetDistance(bestPos, mousePos) return points[i] end end end local function Clear() local target = { obj = nil, health = 0, mode = "jungleclear" } local aaRange = player.attackRange + player.boundingRadius + 200 for i = 0, minionmanager.size[TEAM_NEUTRAL] - 1 do local obj = minionmanager[TEAM_NEUTRAL][i] if player.pos:dist(obj.pos) <= aaRange and obj.maxHealth > target.health then target.obj = obj target.health = obj.maxHealth end end if target.obj then if target.mode == "jungleclear" and player.par / player.maxPar * 100 >= menu.JC.manaj:get() then if menu.JC.QJ:get() and player:spellSlot(0).state == 0 then local ddddd = player.pos + (target.obj.pos - player.pos):norm() * -150 player:castSpell("pos", 0, vec3(ddddd)) end if menu.JC.AAE:get() and player:spellSlot(2).state == 0 then Condemn(target.obj) end end end end local function CastQ(target) local range = 300 + player.attackRange + (player.boundingRadius + target.boundingRadius) if GetDistance(target) <= range then if IsQEvade(game.mousePos, math.huge, 0.25) then player:castSpell("pos", 0, game.mousePos) end end end local function CastR(target) if GetDistance(target) <= 1000 and #count_enemies_in_range(player.pos, 1000) >= menu.MR.Rhitenemy:get() then player:castSpell("self", 3) end end local function Combo() local target = GetTargetSelector() if ValidTarget(target) then if menu.MQ.AFO:get() == 1 then CastQ(target) end Condemn(target) CastR(target) end end local function ComboIsReday() local target = GetTargetSelector() if ValidTarget(target) then if menu.MQ.AFO:get() == 2 then CastQ(target) end Condemn(target) end end local function OnDraw() local target = GetTargetSelector() if ValidTarget(target) then graphics.draw_circle(target.pos, 70, 2, graphics.argb(255, 255, 255, 255), 100) end end local function OnTick() if menu.ME.CF:get() then FlashE() end if orb.combat.is_active() then ComboIsReday() end end local function On_Load() if orb.menu.lane_clear:get() then Clear() end if orb.combat.is_active() then Combo() end end orb.combat.register_f_pre_tick(OnTick) orb.combat.register_f_after_attack(On_Load) cb.add(cb.draw, OnDraw) cb.add(cb.spell, OnProcessSpell)
-- Main ---------------------------------------------------------- local OneSignal = require("plugin.OneSignal") local composer = require("composer") local json = require("json") local myData = require("mydata") local loadsave = require( "loadsave" ) local lfs = require( "lfs" ) display.setStatusBar( display.HiddenStatusBar ) ----------------TEST PUSH NOTIFICATION WITH OneSignal---------------------------- -- This function gets called when the user opens a notification or one is received when the app is open and active. -- Change the code below to fit your app's needs. function DidReceiveRemoteNotification(message, additionalData, isActive) end -- Memory Check for Memory Leaks -- local function checkMem() -- collectgarbage("collect") -- local memUsage_str = string.format( "MEMORY= %.3f KB", collectgarbage( "count" ) ) -- print( memUsage_str .. " | TEXTURE= "..(system.getInfo("textureMemoryUsed")/1048576) ) -- end -- timer.performWithDelay( 1000, checkMem, 0 ) --GitHub Note: OneSignal is used for Push notifications - https://documentation.onesignal.com/docs/corona-sdk local function onSystemEvent( event ) if event.type == "applicationStart" then --GitHub Note: Here you have to put your OneSignal appId and googleProjectNumber: OneSignal.Init("XXX", "XXX", DidReceiveRemoteNotification) OneSignal.EnableInAppAlertNotification(true) OneSignal.EnableNotificationsWhenActive(true) OneSignal.SendTag("ChatActive", "true") OneSignal.SendTag("version", "v1.1.2") elseif event.type == "applicationExit" then --this block executed just prior to the app quitting --OS closes least recently used app, user explicitly quits, etc. OneSignal.SendTag("ChatActive", "false") elseif event.type == "applicationSuspend" then --this block executed when app goes into “suspend” state --e.g. user receives phone call, presses home button, etc. OneSignal.SendTag("ChatActive", "false") elseif event.type == "applicationResume" then --this block executed when app resumes from “suspend” state --e.g. user goes back into app (while it is still running in bg) OneSignal.SendTag("ChatActive", "true") end end Runtime:addEventListener( "system", onSystemEvent ) local function onAlert( event ) if ( event.action == "clicked" ) then if system.getInfo("platformName")=="Android" then native.requestExit() else os.exit() end end end local function skinNetworkListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occurred...Err: 1", { "Close" }, onAlert ) else print ( "RESPONSE: " .. event.response ) local t = json.decode( base64Decode(event.response) ) if ( t == nil ) then print ("EMPTY T") skinColor="green" else skinColor=t.skin --skinColor="aqua" end applySkin(skinColor) composer.gotoScene("homeScene") end end local function renewSucceeded(token) --local alert = native.showAlert( "EliteHax", "Logged In!!\nID: "..player_id, { "Close" }, onClose ) local loginStatus = { token = token } loadsave.saveTable( loginStatus, "loginStatus.json" ) --GetSkin loginInfo = localToken() local headers = {} local body = "id="..string.urlEncode(loginInfo.token) local params = {} params.headers = headers params.body = body network.request( host().."getSkin.php", "POST", skinNetworkListener, params ) end local function renewListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occurred... Err: 2", { "Close" }, onAlert ) else print ( "RESPONSE TOKEN: " .. event.response ) local t = json.decode( base64Decode(event.response) ) if ( t == nil ) then print ("EMPTY T") composer.gotoScene("loginScene") elseif (t.BAN) then local alert = native.showAlert( "EliteHax", "You have been banned from EliteHax.\nReason: "..t.reason.."\nIf you have any question, please contact support@elitehax.it", { "Close" }, onAlert ) elseif (t.ANON) then local alert = native.showAlert( "EliteHax", "You cannot login to EliteHax with an anonymous connection.\nIf you need to use a proxy please contact support@elitehax.it", { "Close" }, onAlert ) elseif (t.status == "OK") then renewSucceeded(t.token) end end end local function appPackageCheck(event) if system.getInfo("platformName")=="Android" then print("Package: "..system.getInfo("androidAppPackageName")) if (system.getInfo("androidAppPackageName") ~= "it.EliteHax") then native.requestExit() end end end local function checkCertificate(event) if ((cert == nil) and (retries<10)) then retries=retries+1 cert = conn:getpeercertificate() timer.performWithDelay(500,checkCertificate) else local sha512 = cert:digest("sha512") print("SHA: "..sha512) conn:close() checkCert=false for k, v in pairs(cert:issuer()) do for i, j in pairs(v) do print(i, j) if (j=="COMODO ECC Domain Validation Secure Server CA 2") then checkCert=true elseif (j=="Encryption Everywhere DV TLS CA - G1") then checkCert=true end end end if (checkCert==false) then if (system.getInfo("platformName")=="Android") then native.requestExit() else os.exit() end end if ((sha512 ~= "962ab5d31cbc60c3b4420df76eaaae2c5861232bc12831fd1c06e071738e8cdc21f4491baf44e42a9df3fd35b7948f44e434ffb9fbd30b1f71d36ac42f131d47") and (sha512 ~= "11a8dafe019caa5573bc1437cf63901c971d50273c0cda785585cafd2e0d88d51f3c476e9d1b6ca56dcab60226dc39cadcad1dc67dc19a55d3ea67cdcfd2aa3a")) then if (system.getInfo("platformName")=="Android") then native.requestExit() else os.exit() end end end end local function downloadUpdateClose(event) system.openURL( "https://play.google.com/store/apps/details?id=it.EliteHax" ) if system.getInfo("platformName")=="Android" then native.requestExit() else os.exit() end end local function downloadUpdate(event) local i = event.index if ( i == 1 ) then system.openURL( "https://play.google.com/store/apps/details?id=it.EliteHax" ) if system.getInfo("platformName")=="Android" then native.requestExit() else os.exit() end elseif ( i == 2 ) then --Nothing end end local function checkSystemListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occurred... Please retry with a stable internet connection.\nIf the issue persists, please contact support@elitehax.it", { "Close" }, onAlert ) else print ( "RESPONSE TOKEN: " .. event.response ) local t = json.decode( base64Decode(event.response) ) local now = os.time() local diff= os.difftime(now, os.time(os.date("!*t", now)))/3600 local lang = system.getPreference( "ui", "language" ) local country = system.getPreference( "locale", "country" ) local jsonRequest = {["tz"] = diff, ["lang"] = lang, ["country"] = country} jsonRequest = base64Encode(json.encode(jsonRequest)) if ( t == nil ) then print ("EMPTY T") local alert = native.showAlert( "EliteHax", "Oops.. An error occurred...\nPlease contact support@elitehax.it", { "Close" }, onAlert ) elseif (t.status == "OK") then --Retrieve Login Info loginInfo = loadsave.loadTable( "loginStatus.json" ) system.setTapDelay( 1 ) if (loginInfo == nil) then composer.gotoScene("loginScene") else local headers = {} local body = "deviceid="..base64Encode(system.getInfo("deviceID")).."&id="..string.urlEncode(loginInfo.token).."&env="..string.urlEncode(jsonRequest) local params = {} params.headers = headers params.body = body network.request( host().."renewToken.php", "POST", renewListener, params ) end elseif (t.status == "US") then --Retrieve Login Info local alert = native.showAlert( "EliteHax", "A new EliteHax update is available on Google Play Store!", { "Download", "Skip" }, downloadUpdate ) loginInfo = loadsave.loadTable( "loginStatus.json" ) system.setTapDelay( 1 ) if (loginInfo == nil) then composer.gotoScene("loginScene") else local headers = {} local body = "deviceid="..base64Encode(system.getInfo("deviceID")).."&id="..string.urlEncode(loginInfo.token).."&env="..string.urlEncode(jsonRequest) local params = {} params.headers = headers params.body = body network.request( host().."renewToken.php", "POST", renewListener, params ) end elseif (t.status == "UR") then --Retrieve Login Info local alert = native.showAlert( "EliteHax", "A new EliteHax update is required to continue.", { "Download" }, downloadUpdateClose ) elseif (t.status == "CM") then --Retrieve Login Info if (t.login=="Y") then local alert = native.showAlert( "EliteHax", t.message, { "Close" } ) loginInfo = loadsave.loadTable( "loginStatus.json" ) system.setTapDelay( 1 ) if (loginInfo == nil) then composer.gotoScene("loginScene") else local headers = {} local body = "deviceid="..base64Encode(system.getInfo("deviceID")).."&id="..string.urlEncode(loginInfo.token).."&env="..string.urlEncode(jsonRequest) local params = {} params.headers = headers params.body = body network.request( host().."renewToken.php", "POST", renewListener, params ) end else local alert = native.showAlert( "EliteHax", t.message, { "Close" }, onAlert ) end end end end --Certificate Pinning! local socket = require("socket") local ssl = require("plugin.openssl") local plugin_luasec_ssl = require('plugin_luasec_ssl') local params = { mode = "client", protocol = "tlsv1_2", verify = "none", options = "single_ecdh_use", } conn = socket.tcp() conn:settimeout(3000) conn:connect("app.elitehax.it", 443) conn = plugin_luasec_ssl.wrap(conn, params) conn:sni("app.elitehax.it") conn:dohandshake() conn:send("GET / HTTP/1.1\nHost: www.elitehax.it\nUser-Agent: EliteHax 3.0.7\nAccept: */*\n\n") retries=0 cert = conn:getpeercertificate() local line, err = conn:receive() --GitHub Note: here you can enable/disable Certificate Pinning - to mitigate MITM --timer.performWithDelay(200,checkCertificate) --App Package Name Check! appPackageCheck() --Local Notification localNotification = loadsave.loadTable( "localNotification.json" ) if (localNotification == nil) then taskNotificationActive=true researchNotificationActive=true local notificationStatus = { taskActive = true, researchActive = true } loadsave.saveTable( notificationStatus, "localNotification.json" ) else if (localNotification.taskActive==false) then taskNotificationActive = localNotification.taskActive else taskNotificationActive = true end if (localNotification.researchActive==false) then researchNotificationActive = localNotification.researchActive else researchNotificationActive = true end end --Local Music localMusic = loadsave.loadTable( "localMusic.json" ) if (localMusic == nil) then musicActive=true local musicStatus = { active = true } loadsave.saveTable( musicStatus, "localMusic.json" ) else musicActive = localMusic.active end --Local Sound Effects localSfx = loadsave.loadTable( "localSfx.json" ) if (localSfx == nil) then sfxActive=true local sfxStatus = { active = true } loadsave.saveTable( sfxStatus, "localSfx.json" ) else sfxActive = localSfx.active end notificationActive = loadsave.loadTable( "localNotificationStatus.json" ) if (notificationActive == nil) then notificationActive = { task = nil, taskTime = 0, research = nil, researchTime = 0 } end --Random Init math.randomseed(os.time()) math.random() math.random() math.random() mclickSound = audio.loadSound( "audio/UI_Quirky7.mp3" ) mbackSound = audio.loadSound( "audio/UI_Quirky8.mp3" ) mrewardSound = audio.loadSound( "audio/PowerUp17.mp3" ) mwin = audio.loadSound("audio/SynthChime2.mp3") mlose = audio.loadSound("audio/Creepy4.mp3") mtarget = audio.loadSound("audio/Creepy-Roll-Over-1.mp3") function tapSound(event) if (sfxActive==true) then audio.play(mclickSound) end end function backSound(event) if (sfxActive==true) then audio.play(mbackSound) end end function rewardSound(event) if (sfxActive==true) then audio.play(mrewardSound) end end function winSound(event) if (sfxActive==true) then audio.play(mwin) end end function loseSound(event) if (sfxActive==true) then audio.play(mlose) end end function targetSound(event) if (sfxActive==true) then if (targetAudio==true) then audio.play(mtarget) targetAudio=false end end end function backgroundLoginSound(event) if (musicActive==true) then if (backgroundMusicChannel) then audio.stop(backgroundMusicChannel) audio.dispose(backgroundMusicChannel) end backgroundMusic = audio.loadStream( "audio/Dystopic-Technology_Looping.mp3" ) backgroundMusicChannel2 = audio.play( backgroundMusic, { channel=1, loops=-1, fadein=1000 } ) end end function backgroundSound(event) if (musicActive==true) then if (backgroundMusicChannel2) then audio.stop(backgroundMusicChannel2) audio.dispose(backgroundMusicChannel2) end if (backgroundMusicChannel==nil) then backgroundMusic = audio.loadStream( "audio/Cyber-REM_Looping.mp3" ) backgroundMusicChannel = audio.play( backgroundMusic, { loops=-1, fadein=1000 } ) end else if (backgroundMusicChannel) then audio.stop() audio.dispose(backgroundMusicChannel) end end end local headers = {} local body = "" local params = {} params.headers = headers params.body = body network.request( host().."checkSystem.php", "POST", checkSystemListener, params )
local log = require("log") local Api = require("coreApi") local json = require("json") local http = require("http") function ReceiveFriendMsg(CurrentQQ, data) return 1 end function ReceiveGroupMsg(CurrentQQ, data) if data.FromUserId ==2986807981 then--防止自我复读 return 1 end if string.find(data.Content, "#") and string.find(data.Content, ".jpg") then toptext = "" bottomtext = "" toptext = string.sub(data.Content, 1, string.find(data.Content, "#")-1) bottomtext = string.sub(data.Content,string.find(data.Content, "#")+1, -5) --print(toptext.." ") --print(bottomtext) toptext = urlEncode(toptext) bottomtext = urlEncode(bottomtext) if toptext == "" then toptext =" " end if bottomtext == "" then bottomtext =" " end ApiRet = Api.Api_SendMsg( CurrentQQ, { toUser = data.FromGroupId, sendToType = 2, sendMsgType = "PicMsg", content = "本群已内置傻屌图生成器:http://yurafuca.com/5000choyen/index_cn.html", atUser = 0, voiceUrl = "", voiceBase64Buf = "", picUrl = "http://5000choyen.app.cyberrex.ml/image?top="..toptext.."&bottom="..bottomtext, --感谢dalao的API https://github.com/CyberRex0/5000choyen-api picBase64Buf = "", fileMd5 = "" } ) end toptext=nil bottomtext=nil return 1 end function ReceiveEvents(CurrentQQ, data, extData) return 1 end function urlEncode(s) --url编码解码 s = string.gsub(s, "([^%w%.%- ])", function(c) return string.format("%%%02X", string.byte(c)) end) return string.gsub(s, " ", "+") end function urlDecode(s) s = string.gsub(s, '%%(%x%x)', function(h) return string.char(tonumber(h, 16)) end) return s end
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0273-webengine-projection-mode.md -- -- Description: -- Check that SDL doesn't close the connection with WebEngine -- projection app if the app was closed (HMILevel NONE is assigned) -- -- Precondition: -- 1. SDL and HMI are started -- 2. WebEngine projection app is connected to SDL, successfully -- registered and activated (HMI level is FULL) -- -- Sequence: -- 1. Application registers with WEB_VIEW appHMIType -- a. SDL successfully registers application (resultCode SUCCESS, success:"true") -- b. SDL assigns HMILevel (NONE) to the WebEngine projection app and doesn't close the WebSocket connection -- 2. Activate web application -- a. WebEngine projection application successfully activated using remained connection to SDL -- 3. Deactivate web application to NONE and check connection -- a. Exit from application (reason = "USER_EXIT") --------------------------------------------------------------------------------------------------- -- [[ Required Shared Libraries ]] local common = require('test_scripts/WebEngine/commonWebEngine') --[[ Local Variables ]] local appSessionId = 1 local appHMIType = { "WEB_VIEW" } --[[ General configuration parameters ]] config.application1.registerAppInterfaceParams.appHMIType = appHMIType --[[ Local Functions ]] local function deactivateAppToNoneAndCheckConnection() common.getHMIConnection():SendNotification("BasicCommunication.OnExitApplication", { appID = common.getHMIAppId(), reason = "USER_EXIT" }) common.getMobileSession():ExpectNotification("OnHMIStatus", { hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN" }) common.getMobileSession():ExpectEvent(common.disconnectedEvent, "Disconnected") :Times(0) :Timeout(10000) end --[[ Scenario ]] common.Title("Preconditions") common.Step("Clean environment", common.preconditions) common.Step("Update WS Server Certificate parameters in smartDeviceLink.ini file", common.commentAllCertInIniFile) common.Step("Add AppHMIType to preloaded policy table", common.updatePreloadedPT, { appSessionId, appHMIType}) common.Step("Start SDL, HMI", common.startWOdeviceConnect) common.Step("Connect WebEngine device", common.connectWebEngine, { appSessionId, "WS" }) common.Title("Test") common.Step("Register App without PTU", common.registerAppWOPTU, { appSessionId }) common.Step("Activate web app", common.activateApp, { appSessionId }) common.Step("Deactivate web app to NONE and check connection", deactivateAppToNoneAndCheckConnection) common.Step("Check connection via successful activation", common.activateApp, { appSessionId }) common.Title("Postconditions") common.Step("Stop SDL", common.postconditions)
local function invert_map(m) local inv = {} for k, v in pairs(m) do inv[v] = k end return inv end -- x- to x+ local param2_x_mapping = { [1] = 3, [3] = 1, [5] = 7, [9] = 11, [16] = 11, [18] = 14, [23] = 21, [21] = 23 } -- x- to x+ local param2_x_mapping_inv = invert_map(param2_x_mapping) -- y- to y+ local param2_y_mapping = { [20] = 0, [23] = 1, [22] = 2, [21] = 3 } -- y+ to y- local param2_y_mapping_inv = invert_map(param2_y_mapping) -- z- to z+ local param2_z_mapping = { [0] = 2, [2] = 0, [9] = 5, [11] = 14, [12] = 14, [16] = 18, [20] = 22, [22] = 20 } -- z- to z+ local param2_z_mapping_inv = invert_map(param2_z_mapping) function build_mirror.rotate_node(node, axis_direction) local def = minetest.registered_nodes[node.name] if not def then return node end local paramtype2 = def.paramtype2 if paramtype2 ~= "facedir" and paramtype2 ~= "colorfacedir" then -- can't rotate this return node end print("rotate_node param2=" .. node.param2 .. " axis_direction=" .. axis_direction) local param2 if axis_direction == "x+" then param2 = param2_x_mapping[node.param2] elseif axis_direction == "x-" then param2 = param2_x_mapping_inv[node.param2] elseif axis_direction == "y+" then param2 = param2_y_mapping[node.param2] elseif axis_direction == "y-" then param2 = param2_y_mapping_inv[node.param2] elseif axis_direction == "z+" then param2 = param2_z_mapping[node.param2] elseif axis_direction == "z-" then param2 = param2_z_mapping_inv[node.param2] else error("not a valid axis-direction: " .. axis_direction) end print("rotate_node(II) param2=" .. (param2 or "nil")) return { name = node.name, param2 = param2 or node.param2 } end
meta.name = "The Floor is Lava" meta.version = "0.5" meta.description = "All floor tiles become lava shortly after standing on them" meta.author = "garebear" TILES = {} DEFAULT_LAVA_TIMER = 60 * 2 PARTICLE_DELAY = 15 SAFE_FLOOR = nil UNSAFE_FLOORS = { [ENT_TYPE.FLOORSTYLED_MINEWOOD] = true, [ENT_TYPE.FLOOR_GENERIC] = true, [ENT_TYPE.FLOOR_SURFACE] = true, [ENT_TYPE.FLOOR_SURFACE_HIDDEN] = true, [ENT_TYPE.FLOORSTYLED_STONE] = true, [ENT_TYPE.FLOORSTYLED_TEMPLE] = true, [ENT_TYPE.FLOORSTYLED_PAGODA] = true, [ENT_TYPE.FLOORSTYLED_BABYLON] = true, [ENT_TYPE.FLOORSTYLED_SUNKEN] = true, [ENT_TYPE.FLOORSTYLED_BEEHIVE] = true, [ENT_TYPE.FLOORSTYLED_VLAD] = true, [ENT_TYPE.FLOORSTYLED_COG] = true, [ENT_TYPE.FLOORSTYLED_MOTHERSHIP] = true, [ENT_TYPE.FLOORSTYLED_DUAT] = true, [ENT_TYPE.FLOORSTYLED_PALACE] = true, [ENT_TYPE.FLOORSTYLED_GUTS] = true, } register_option_int( "lava_timer", "Frames before floor tile turns to lava.", DEFAULT_LAVA_TIMER, 60 * 1, 60 * 5 ) register_option_bool( "thicc_lava", "Use Thicc Lava", true ) register_option_bool( "bomb_olmec", "Olmec is Bombs", true ) register_option_bool( "bomb_tiamat", "Tiamat is Bombs", true ) register_option_bool( "safe_platform", "Safe Starting Platform", false ) register_option_bool( "safe_minewood", "Minewood is Safe", true ) register_option_bool( "safe_sunken", "Sunken Stone is Safe", true ) register_option_bool( "safe_pagodas", "Pagodas are Safe", true ) register_option_bool( "remove_cobwebs", "Remove Cobwebs", true ) register_option_bool( "remove_quillback_pushblocks", "Remove Quillback Pushblocks", true ) function clamp(n, low, high) return math.min(math.max(n, low), high) end function get_particle_timeout() return clamp(options.lava_timer - PARTICLE_DELAY, 0, options.lava_timer) end function test_and_get_floor_entity(uid) -- Outstanding callback from previous level, just early exit. if TILES[uid] == nil then return end local entity = get_entity(uid) if entity == nil then return end if not is_floor(entity) then return end return entity end function is_level() return state.screen == 12 and state.screen_next == 12 end function emit_particles(uid) if not is_level() then return end local entity = test_and_get_floor_entity(uid) if entity == nil then return end generate_particles(PARTICLEEMITTER.EXPLOSION_SPARKS, uid) end function spawn_lava(x, y) if options.thicc_lava then return spawn_liquid(ENT_TYPE.LIQUID_STAGNANT_LAVA, x, y) end return spawn_liquid(ENT_TYPE.LIQUID_LAVA, x, y) end function bomb_or_break(uid, x, y, layer, should_bomb) if should_bomb then spawn_entity(ENT_TYPE.FX_EXPLOSION, x, y, layer, 0, 0) else kill_entity(uid) end end function make_tile_lava(uid) if not is_level() then return end local entity = test_and_get_floor_entity(uid) if entity == nil then return end local x, y, layer = get_position(uid) if state.theme == THEME.OLMEC then bomb_or_break(uid, x, y, layer, options.bomb_olmec) elseif state.theme == THEME.TIAMAT then bomb_or_break(uid, x, y, layer, options.bomb_tiamat) else kill_entity(uid) if layer == LAYER.BACK then return end spawn_lava(x, y) end end function get_player_or_mount(player) overlay = player.overlay if overlay == nil then return player end if overlay.type.search_flags & MASK.MOUNT == 0 then return player end local mount = overlay:as_mount() return mount end function queue_lava(uid) local callbacks = {} table.insert(callbacks, set_timeout(function() emit_particles(uid) end, get_particle_timeout())) table.insert(callbacks, set_timeout(function() make_tile_lava(uid) end, options.lava_timer)) TILES[uid] = callbacks end function maybe_schedule_lava(player) local player = get_player_or_mount(player) -- Already scheduled lava-ing if TILES[player.standing_on_uid] ~= nil then return end -- Not standing on anything if player.standing_on_uid <= 0 then return end local standing_uid = player.standing_on_uid if options.safe_platform and standing_uid == SAFE_FLOOR then return end local standing_entity = get_entity(standing_uid) -- Didn't get an entity back if standing_entity == nil then return end if not is_floor(standing_entity) then return end if options.safe_minewood and standing_entity.type.id == ENT_TYPE.FLOORSTYLED_MINEWOOD then return end if options.safe_pagodas and standing_entity.type.id == ENT_TYPE.FLOORSTYLED_PAGODA then return end if options.safe_sunken and standing_entity.type.id == ENT_TYPE.FLOORSTYLED_SUNKEN then return end queue_lava(standing_uid) end function is_floor(entity) return UNSAFE_FLOORS[entity.type.id] ~= nil end function remove_all(ent_type) uids = get_entities_by_type(ent_type) for _, uid in ipairs(uids) do kill_entity(uid) end end set_callback(function() -- Clear any outstanding callbacks TILES = {} for _, player in ipairs(players) do if player ~= nil then SAFE_FLOOR = player.standing_on_uid end end if options.remove_quillback_pushblocks and state.world == 1 and state.level == 4 then remove_all(ENT_TYPE.ACTIVEFLOOR_PUSHBLOCK) end if options.remove_cobwebs then remove_all(ENT_TYPE.ITEM_WEB) end end, ON.LEVEL) function clean_up_lava(lava_uid, exit_uids) if state.world == 5 then local x, y, _ = get_position(lava_uid) if y < 5 then kill_entity(lava_uid) end end if exit_uids == nil or #exit_uids <= 0 then return end for _, exit_uid in ipairs(exit_uids) do local exit = get_entity(exit_uid) local lava = get_entity(lava_uid) if exit:overlaps_with(lava) then kill_entity(lava_uid) end end end set_callback(function() for _, player in ipairs(players) do if player ~= nil then maybe_schedule_lava(player) end end lava_uids = get_entities_by_mask(MASK.LAVA) exit_uids = get_entities_by_type(ENT_TYPE.FLOOR_DOOR_EXIT) for _, lava_uid in ipairs(lava_uids) do clean_up_lava(lava_uid, exit_uids) end end, ON.FRAME) -- Boulder doesn't like hitting lava set_pre_entity_spawn(function(ent_type, x, y, l, overlay) return spawn(ENT_TYPE.ITEM_ROCK, x, y, l, 0, 0) end, SPAWN_TYPE.ANY, 0, ENT_TYPE.ACTIVEFLOOR_BOULDER)
return { ['int'] = { _name='NormalClazz',name='int',desc='primity type:int',parents={},methods={},is_abstract=false,fields={},}, }
-- started: 2015-07-16 -------------------------------------------------------------------------------- -- _G [false] = true -- _G [true] = false -- _G [{}] = "aaa" -------------------------------------------------------------------------------- -- luacheck: new_globals Settings far.ReloadDefaultScript = true local F = far.Flags local Title = "Lua Panel" local VK = win.GetVirtualKeys() local band = bit.band local Settings = { LastPanelMode = ("1"):byte(); LastSortMode = F.SM_NAME; LastSortOrder = 0; } function export.GetPluginInfo() return { CommandPrefix = "luapanel", Flags = 0, PluginConfigStrings = { Title }, PluginMenuStrings = { Title }, SysId = far.GetPluginId(), } end function export.OpenPlugin(OpenFrom, Item) local obj = { CurDir="", {table = _G} } if (OpenFrom == F.OPEN_PLUGINSMENU) or (OpenFrom == F.OPEN_SHORTCUT) then return obj elseif OpenFrom == F.OPEN_COMMANDLINE then local str = Item:match("^%s*(.-)%s*$") -- trim whitespace from both sides local v = _G[str] if type(v) == "table" then obj.CurDir = str table.insert(obj, {table = v}) end return obj end end -- -- @param object contains a list (stack) of tables; stack top is of interest now. -- function export.GetFindData (object, handle, OpMode) --if band(OpMode, F.OPM_FIND) ~= 0 then return end local data = {} local curr = object[#object] -- get stack top for k,v in pairs(curr.table) do local str local tp = type(v) if tp == "string" then str = '"'..v..'"' elseif tp == "number" and v == math.floor(v) then str = ("%-11s : 0x%X"):format(tostring(v), v) else str = tostring(v) end table.insert(data, { FileName = tostring(k); FileAttributes = tp=="table" and "d" or ""; CustomColumnData = { str }; UserData = { element=v }; }) end return data end local PanelModes do local m1 = { ColumnTypes = "N,C0", ColumnWidths = "40%,60%", ColumnTitles = { "Key","Value" }, StatusColumnTypes = "N", StatusColumnWidths = "0", FullScreen = false, } local m2 = { ColumnTypes = "N,C0", ColumnWidths = "30%,70%", ColumnTitles = { "Key","Value" }, StatusColumnTypes = "N", StatusColumnWidths = "0", FullScreen = true, } PanelModes = { m2,m1,m2, m1,m2,m1, m2,m1,m2, m1 } end function export.GetOpenPluginInfo (obj, handle) return { Flags = F.OPIF_ADDDOTS, --CurDir = obj.CurDir, PanelTitle = obj.CurDir=="" and Title or Title..": "..obj.CurDir, PanelModesArray = PanelModes, PanelModesNumber = 10, StartPanelMode = Settings.LastPanelMode, StartSortMode = Settings.LastSortMode, StartSortOrder = Settings.LastSortOrder, ShortcutData = nil, } end function export.ProcessEvent (object, handle, Event, Param) if Event == F.FE_IDLE then panel.UpdatePanel(handle,true) panel.RedrawPanel(handle) elseif Event == F.FE_CHANGEVIEWMODE then local info = panel.GetPanelInfo(handle) Settings.LastPanelMode = tostring(info.ViewMode):byte() end end function export.ProcessKey (object, handle, Key, ControlState) if band(Key, F.PKF_PREPROCESS) ~= 0 then return false end local A = (0 ~= band(ControlState, F.PKF_ALT)) local C = (0 ~= band(ControlState, F.PKF_CONTROL)) local S = (0 ~= band(ControlState, F.PKF_SHIFT)) if not (A or C or S) and Key == VK.RETURN then local item = panel.GetCurrentPanelItem(handle) if item.FileName == ".." then -- try to "return" to the parent table if #object > 1 then local info = object[#object].info object[#object] = nil -- pop the element off the stack object.CurDir = object.CurDir:match("(.+)%..+") or "" panel.UpdatePanel(handle) panel.RedrawPanel(handle, info) return true end else -- try to "enter" a table local curr = item.UserData and item.UserData.element if type(curr) == "table" then object[#object+1] = { table=curr, info=panel.GetPanelInfo(handle) } object.CurDir = object.CurDir=="" and item.FileName or object.CurDir.."."..item.FileName panel.UpdatePanel(handle) panel.RedrawPanel(handle, {CurrentItem=1}) return true end end end end
-- 字符串操作 -- 字符串全部转为大写字母。 print(string.upper("argument")) -- 字符串全部转为小写字母。 print(string.lower("Argument")) -- string.gsub(mainString,findString,replaceString,num) -- 在字符串中替换,mainString为要替换的字符串, findString 为被替换的字符,replaceString 要替换的字符,num 替换次数(可以忽略,则全部替换),如: str, len = string.gsub("abc", "a", "b", 1) print(str .. len) -- 在一个指定的目标字符串中搜索指定的内容(第三个参数为索引),返回其具体位置。不存在则返回 nil。 _ost, _end = string.find("你好", "好") if _ost == nil then print("not find") else print(_ost .. _end) end -- print(string.reverse( "hello" )) print(string.format("the value is:%d",4)) -- string.char(arg) 和 string.byte(arg[,int]) -- char 将整型数字转成字符并连接, byte 转换字符为整数值(可以指定某个字符,默认第一个字符)。 print(string.char(97,98,99,100)) print(string.byte("ABCD",4)) -- string.len(arg) -- 计算字符串长度。 print(string.len("abc")) print(#"abc") print(string.rep("a", 10))
local ErrorController = {} function ErrorController:error() local view = self:getView() view:assign(self.err) return view:display() end return ErrorController
local env = vim.env local g = vim.g local fn = vim.fn local api = vim.api local o = vim.o local utils = require("utils") local nmap = utils.nmap local xmap = utils.xmap local omap = utils.omap local imap = utils.imap if (fn.isdirectory(".git")) then nmap("<leader>t", ":GitFiles --cached --others --exclude-standard<cr>") else nmap("<leader>t", ":FZF<cr>") end nmap("<leader>s", ":GFiles?<cr>") nmap("<leader>r", ":Buffers<cr>") nmap("<leader>e", ":FZF<cr>") nmap("<leader><tab>", "<plug>(fzf-maps-n)") xmap("<leader><tab>", "<plug>(fzf-maps-x)") omap("<leader><tab>", "<plug>(fzf-maps-o)") -- Insert mode completion imap("<c-x><c-k>", "<plug>(fzf-complete-word)") imap("<c-x><c-f>", "<plug>(fzf-complete-path)") imap("<c-x><c-j>", "<plug>(fzf-complete-file-ag)") imap("<c-x><c-l>", "<plug>(fzf-complete-line)") api.nvim_exec( [[ command! FZFMru call fzf#run({ 'source': v:oldfiles, 'sink': 'e', 'options': '-m -x +s', 'down': '40%'}) command! -bang -nargs=* Find call fzf#vim#grep('rg --column --line-number --no-heading --follow --color=always '.<q-args>.' || true', 1, <bang>0 ? fzf#vim#with_preview('up:60%') : fzf#vim#with_preview('right:50%:hidden', '?'), <bang>0) command! -bang -nargs=? -complete=dir Files call fzf#vim#files(<q-args>, fzf#vim#with_preview(), <bang>0) command! -bang -nargs=? -complete=dir GitFiles call fzf#vim#gitfiles(<q-args>, fzf#vim#with_preview(), <bang>0) ]], false ) function FloatingFZF() local lines = o.lines local columns = o.columns local buf = api.nvim_create_buf(true, true) local height = fn.float2nr(lines * 0.5) local width = fn.float2nr(columns * 0.7) local horizontal = fn.float2nr((columns - width) / 2) local vertical = 0 local opts = { relative = "editor", row = vertical, col = horizontal, width = width, height = height, style = "minimal" } vim.api.nvim_open_win(buf, true, opts) end local fzf_opts = { env.FZF_DEFAULT_OPTS or "", " --layout=reverse", ' --pointer=" "', " --info=hidden", " --border=rounded", " --bind å:select-all+accept" } env.FZF_DEFAULT_OPTS = table.concat(fzf_opts, "") g.fzf_preview_window = {"right:50%:hidden", "?"} g.fzf_layout = {window = "call v:lua.FloatingFZF()"}
function Client_PresentConfigureUI(rootParent) rootParentobj = rootParent; JustSpectatorinit = Mod.Settings.JustSpectator; if(JustSpectatorinit == nil)then JustSpectatorinit = true; end ShowUI(); end function ShowUI() local horz = UI.CreateHorizontalLayoutGroup(rootParentobj); inputJustSpectator = UI.CreateCheckBox(horz).SetText('Just Spectators can see the data').SetIsChecked(JustSpectatorinit); end
-- note: the garbage collector can be explicitly invoked with collectgarbage function test_gc_does_not_remove_values_from_regular_tables_with_references() local t = {} t.foo = {} collectgarbage() assert_equal(__('table'), type(t.foo)) end function test_gc_removes_values_from_tables_with__mode_set_to_v_if_there_are_no_other_references_to_them() local t = setmetatable({}, { __mode = 'v' }) t.foo = {} collectgarbage() assert_equal(__('nil'), type(t.foo)) end function test_gc_does_not_remove_values_from_tables_with__mode_set_to_v_if_there_are_other_references() local t = setmetatable({}, { __mode = 'v' }) local x = {} t.foo = x collectgarbage() assert_equal(__('table'), type(t.foo)) end function test_gc_does_not_remove_keys_from_regular_tables() local t = {} local x = {} t[x] = true collectgarbage() assert_equal(__(true), t[x]) end -- not a test, a helper local function has_anything(t) for k,v in pairs(t) do return true end return false end function test_gc_does_not_remove_the_key_when__mode_is_k_and_there_are_other_references_to_it() local t = setmetatable({}, { __mode = 'k' }) local x = {} t[x] = true collectgarbage() assert_equal(__(true), has_anything(t)) end function test_gc_removes_the_key_when__mode_is_k_and_no_other_references_remain() local t = setmetatable({}, { __mode = 'k' }) do local x = {} t[x] = true end collectgarbage() assert_equal(__(false), has_anything(t)) end function test_really_weak_tables_have_their_mode_set_to_both_k_and_v() local t = setmetatable({}, { __mode = 'kv' }) do local x = {} t[x] = x end assert_equal(__(true), has_anything(t)) collectgarbage() assert_equal(__(false), has_anything(t)) end
local copas=require'copas' local ws_client local sslparams = { mode = "client", protocol = "tlsv1_2", verify = "none", options = "all", } copas.addthread(function ( ) copas.sleep(0.1) local ws_uri='wss://echo.websocket.org' ws_client = require('websocket.client').copas() local r,msg=ws_client:connect(ws_uri,'wss',sslparams) print('connected',r,msg) if not r then return end connected = true while true do l=ws_client:receive() print('received',l) copas.sleep(0.1) end end) copas.addthread(function ( ) copas.sleep(0.1) cnt = 1 while true do cnt=cnt+1 if cnt>200 then cnt = 0 if connected then print('send') ws_client:send('ping') end end copas.sleep(0.1) end end) copas.loop()
name = "EcoManager" uid = "b2cde810-15d0-4bfa-af66-ec2d6ecd561b" version = 3 copyright = "Crotalus" description = "EcoManager v3, more efficient energy throttling" author = "Crotalus" url = "" icon = "" selectable = true enabled = true exclusive = false ui_only = true requires = {} requiresNames = {} conflicts = { "e6d78791-dac8-4f5a-bf86-87e1f91f6122", "21188cdf-ec69-43bd-b756-6140a84c0197", "5c1ac506-03d3-4734-b6c1-0746592849c3", "5f56b6fd-de36-44f1-ba2b-e7d012025f2a", "ecbf6277-24e3-437a-b968-75e7e7c67db9" } before = {} after = {}
minetest.register_entity("factory:moving_item", { initial_properties = { hp_max = 1, physical = false, collisionbox = {0.125, 0.125, 0.125, 0.125, 0.125, 0.125}, visual = "wielditem", visual_size = {x = 0.2, y = 0.2}, textures = {""}, spritediv = {x = 1, y = 1}, initial_sprite_basepos = {x = 0, y = 0}, is_visible = false, }, physical_state = true, itemstring = '', set_item = function(self, itemstring) self.itemstring = itemstring local stack = ItemStack(itemstring) local count = stack:get_count() local max_count = stack:get_stack_max() if count > max_count then count = max_count self.itemstring = stack:get_name().." "..max_count end local s = 0.15 + 0.15 * (count / max_count) local c = 0.8 * s local itemtable = stack:to_table() local itemname = nil if itemtable then itemname = stack:to_table().name end --[[local item_texture = nil local item_type = "" if minetest.registered_items[itemname] then item_texture = minetest.registered_items[itemname].inventory_image item_type = minetest.registered_items[itemname].type end--]] local prop = { is_visible = true, visual = "wielditem", textures = {itemname}, visual_size = {x = s, y = s}, collisionbox = {-c, -c, -c, c, c, c}, --automatic_rotate = math.pi * 0.2, } self.object:set_properties(prop) end, get_staticdata = function(self) return minetest.serialize({ itemstring = self.itemstring }) end, on_activate = function(self, staticdata) if string.sub(staticdata, 1, string.len("return")) == "return" then local data = minetest.deserialize(staticdata) if data and type(data) == "table" then self.itemstring = data.itemstring end else self.itemstring = staticdata end self.object:set_armor_groups({immortal = 1}) self:set_item(self.itemstring) end, on_step = function(self) local pos = self.object:get_pos() local speed = 0.8 local apos = vector.round(pos) apos.y=apos.y+1 local napos = minetest.get_node(pos) if minetest.get_node(apos).name == "factory:upward_vacuum_on" or napos.name == "factory:upward_vacuum_on" then local vacpos if napos.name == "factory:upward_vacuum_on" then vacpos = vector.round(pos) else vacpos = vector.round(apos) end local inv = minetest.get_meta(vacpos):get_inventory() if ItemStack(self.itemstring):get_name()==inv:get_list("sort")[1]:get_name() then local a = minetest.facedir_to_dir(minetest.get_node(vacpos).param2) vacpos.y = vacpos.y + 0.15 --correct height local targetpos = vector.add(vacpos,a) targetpos.y = targetpos.y local dir = vector.subtract(targetpos,pos) --distance to the target if math.abs(dir.y)>0.1 then dir = vector.subtract(vacpos,pos) --distance to the vacuum if math.abs(dir.x)>0.1 or math.abs(dir.z)>0.1 then dir.y = 0 dir.x = math.sign(dir.x) dir.z = math.sign(dir.z) end else if math.abs(vector.length(dir))<0.001 then local stack = ItemStack(self.itemstring) minetest.add_item(pos, stack) self.object:remove() end end dir=vector.multiply(dir,2) --correct speed self.object:setvelocity(vector.divide(dir,speed)) return end end -- a copy of the facedir so we don't overwrite the facedir table local dir = vector.new(minetest.facedir_to_dir(napos.param2)) if napos.name == "factory:belt" then dir.y = math.floor(pos.y + 0.5) + 0.15 - pos.y --target height self.object:setvelocity(vector.divide(dir,speed)) elseif napos.name == "factory:belt_center" then dir.y = math.floor(pos.y + 0.5) + 0.15 - pos.y --target height if dir.x == 0 then dir.x = (apos.x - pos.x) * 2 elseif dir.z == 0 then dir.z = (apos.z - pos.z) * 2 end self.object:setvelocity(vector.divide(dir,speed)) elseif minetest.get_item_group(napos.name, "factory_mover") > 0 then dir = vector.subtract(vector.round(pos),pos) --distance to the middle if math.abs(dir.x)>0.2 or math.abs(dir.z)>0.2 then if dir.y~=0.29 then self.object:setpos(vector.add(pos,{x=0,y=dir.y+0.19,z=0})) -- correct position end dir.y=0 end if math.abs(vector.length(dir))<0.001 then local stack = ItemStack(self.itemstring) minetest.add_item(pos, stack) self.object:remove() end dir=vector.multiply(dir,2) --correct speed self.object:setvelocity(vector.divide(dir,speed)) elseif napos.name:find("factory:") and napos.name:find("taker") then dir = vector.multiply(dir,-1) --output direction dir.y = (math.floor(pos.y + 0.5) + 0.19 - pos.y) * 8 --target height self.object:setvelocity(vector.divide(dir,speed)) else local stack = ItemStack(self.itemstring) local veldir = self.object:getvelocity(); --perhaps don't drop into nodes minetest.add_item({x = pos.x + veldir.x / 3, y = pos.y, z = pos.z + veldir.z / 3}, stack) self.object:remove() end end }) function factory.do_moving_item(pos, item) if item==":" or item=="" then return end local stack = ItemStack(item) local obj = minetest.add_entity(pos, "factory:moving_item") obj:get_luaentity():set_item(stack:to_string()) return obj end local belts = factory.require "machines/belt" if factory.setting_enabled("stepBeltvelocity") then minetest.register_globalstep(function(dtime) for _,player in pairs(minetest.get_connected_players()) do local bpos = vector.round(player:get_pos()) local napos = minetest.get_node(bpos) if napos.name == "factory:belt" or napos.name == "factory:belt_center" then local speed = math.min(dtime * 30, 3) belts.move_player(player,bpos,speed,napos) end end end) end
------------------------------------------------------------------ -- -- Author: Alexey Melnichuk <alexeymelnichuck@gmail.com> -- -- Copyright (C) 2015 Alexey Melnichuk <alexeymelnichuck@gmail.com> -- -- Licensed according to the included 'LICENSE' document -- -- This file is part of lua-lluv-websocket library. -- ------------------------------------------------------------------ local ut = require "lluv.utils" local validate = require "lluv.websocket.utf8_validator".validate local Utf8Validator = ut.class() do function Utf8Validator:__init() return self:reset() end function Utf8Validator:reset() self._tail = '' return self end function Utf8Validator:next(str, last) str = self._tail .. str local ok, pos = validate(str) if ok then self._tail = '' else self._tail = string.sub(str, pos) end if last then return self._tail == '' end return #self._tail < 4 end function Utf8Validator:validate(str) return validate(str) end end return { validator = Utf8Validator.new }
return { summary = 'Get the type of the Texture.', description = 'Returns the type of the Texture.', arguments = {}, returns = { { name = 'type', type = 'TextureType', description = 'The type of the Texture.' } }, related = { 'TextureType', 'lovr.graphics.newTexture' } }
--This file should contain all commands meant to be used by mappings. local cc = require("neo-tree.sources.common.commands") local fs = require("neo-tree.sources.filesystem") local utils = require("neo-tree.utils") local filter = require("neo-tree.sources.filesystem.lib.filter") local renderer = require("neo-tree.ui.renderer") local log = require("neo-tree.log") local M = {} local refresh = function(state) fs._navigate_internal(state, nil, nil, nil, false) end local redraw = function(state) renderer.redraw(state) end M.add = function(state) cc.add(state, utils.wrap(fs.show_new_children, state)) end M.add_directory = function(state) cc.add_directory(state, utils.wrap(fs.show_new_children, state)) end M.clear_filter = function(state) fs.reset_search(state, true) end M.copy = function(state) cc.copy(state, utils.wrap(refresh, state)) end ---Marks node as copied, so that it can be pasted somewhere else. M.copy_to_clipboard = function(state) cc.copy_to_clipboard(state, utils.wrap(redraw, state)) end M.copy_to_clipboard_visual = function(state, selected_nodes) cc.copy_to_clipboard_visual(state, selected_nodes, utils.wrap(redraw, state)) end ---Marks node as cut, so that it can be pasted (moved) somewhere else. M.cut_to_clipboard = function(state) cc.cut_to_clipboard(state, utils.wrap(redraw, state)) end M.cut_to_clipboard_visual = function(state, selected_nodes) cc.cut_to_clipboard_visual(state, selected_nodes, utils.wrap(redraw, state)) end M.move = function(state) cc.move(state, utils.wrap(refresh, state)) end ---Pastes all items from the clipboard to the current directory. M.paste_from_clipboard = function(state) cc.paste_from_clipboard(state, utils.wrap(fs.show_new_children, state)) end M.delete = function(state) cc.delete(state, utils.wrap(refresh, state)) end M.delete_visual = function(state, selected_nodes) cc.delete_visual(state, selected_nodes, utils.wrap(refresh, state)) end ---Shows the filter input, which will filter the tree. M.filter_as_you_type = function(state) filter.show_filter(state, true) end ---Shows the filter input, which will filter the tree. M.filter_on_submit = function(state) filter.show_filter(state, false) end ---Shows the filter input in fuzzy finder mode. M.fuzzy_finder = function(state) filter.show_filter(state, true, true) end ---Navigate up one level. M.navigate_up = function(state) local parent_path, _ = utils.split_path(state.path) if not utils.truthy(parent_path) then return end local path_to_reveal = nil local node = state.tree:get_node() if node then path_to_reveal = node:get_id() end if state.search_pattern then fs.reset_search(state, false) end log.debug("Changing directory to:", parent_path) fs._navigate_internal(state, parent_path, path_to_reveal, nil, false) end local focus_next_git_modified = function(state, reverse) local node = state.tree:get_node() local current_path = node:get_id() local g = state.git_status_lookup if not utils.truthy(g) then return end local paths = { current_path } for path, status in pairs(g) do if path ~= current_path and status and status ~= "!!" then --don't include files not in the current working directory if utils.is_subpath(state.path, path) then table.insert(paths, path) end end end local sorted_paths = utils.sort_by_tree_display(paths) if reverse then sorted_paths = utils.reverse_list(sorted_paths) end local is_file = function (path) local success, stats = pcall(vim.loop.fs_stat, path) return (success and stats and stats.type ~= "directory") end local passed = false local target = nil for _, path in ipairs(sorted_paths) do if target == nil and is_file(path) then target = path end if passed then if is_file(path) then target = path break end elseif path == current_path then passed = true end end local existing = state.tree:get_node(target) if existing then renderer.focus_node(state, target) else fs.navigate(state, state.path, target, nil, false) end end M.next_git_modified = function(state) focus_next_git_modified(state, false) end M.prev_git_modified = function(state) focus_next_git_modified(state, true) end M.open = function(state) cc.open(state, utils.wrap(fs.toggle_directory, state)) end M.open_split = function(state) cc.open_split(state, utils.wrap(fs.toggle_directory, state)) end M.open_vsplit = function(state) cc.open_vsplit(state, utils.wrap(fs.toggle_directory, state)) end M.open_tabnew = function (state) cc.open_tabnew(state, utils.wrap(fs.toggle_directory, state)) end M.open_with_window_picker = function(state) cc.open_with_window_picker(state, utils.wrap(fs.toggle_directory, state)) end M.split_with_window_picker = function(state) cc.split_with_window_picker(state, utils.wrap(fs.toggle_directory, state)) end M.vsplit_with_window_picker = function(state) cc.vsplit_with_window_picker(state, utils.wrap(fs.toggle_directory, state)) end M.refresh = refresh M.rename = function(state) cc.rename(state, utils.wrap(refresh, state)) end M.set_root = function(state) local tree = state.tree local node = tree:get_node() if node.type == "directory" then if state.search_pattern then fs.reset_search(state, false) end fs._navigate_internal(state, node.id, nil, nil, false) end end ---Toggles whether hidden files are shown or not. M.toggle_hidden = function(state) state.filtered_items.visible = not state.filtered_items.visible log.info("Toggling hidden files: " .. tostring(state.filtered_items.visible)) refresh(state) end ---Toggles whether the tree is filtered by gitignore or not. M.toggle_gitignore = function(state) log.warn("`toggle_gitignore` has been removed, running toggle_hidden instead.") M.toggle_hidden(state) end M.toggle_node = function (state) cc.toggle_node(state, utils.wrap(fs.toggle_directory, state)) end cc._add_common_commands(M) return M
cc = cc or {} ---EventListenerFocus object ---@class EventListenerFocus : EventListener local EventListenerFocus = {} cc.EventListenerFocus = EventListenerFocus -------------------------------- -- ---@return bool function EventListenerFocus:init() end -------------------------------- ---/ Overrides ---@return EventListenerFocus function EventListenerFocus:clone() end -------------------------------- -- ---@return bool function EventListenerFocus:checkAvailable() end -------------------------------- -- ---@return EventListenerFocus function EventListenerFocus:EventListenerFocus() end return EventListenerFocus
-- ffi setup local ffi = require("ffi") local C = ffi.C local Lib = require("extensions.sn_mod_support_apis.lua_library") local menu = {} local dock_menu = {} local sto_menu = {} local config = { modes = { [1] = { id = "travel", name = ReadText(1002, 1158), stoptext = ReadText(1002, 1159), action = 303 }, [2] = { id = "scan", name = ReadText(1002, 1156), stoptext = ReadText(1002, 1157), action = 304 }, [3] = { id = "scan_longrange", name = ReadText(1002, 1155), stoptext = ReadText(1002, 1160), action = 305 }, [4] = { id = "seta", name = ReadText(1001, 1132), stoptext = ReadText(1001, 8606), action = 225 }, }, consumables = { { id = "satellite", type = "civilian", getnum = C.GetNumAllSatellites, getdata = C.GetAllSatellites, callback = C.LaunchSatellite }, { id = "navbeacon", type = "civilian", getnum = C.GetNumAllNavBeacons, getdata = C.GetAllNavBeacons, callback = C.LaunchNavBeacon }, { id = "resourceprobe", type = "civilian", getnum = C.GetNumAllResourceProbes, getdata = C.GetAllResourceProbes, callback = C.LaunchResourceProbe }, { id = "lasertower", type = "military", getnum = C.GetNumAllLaserTowers, getdata = C.GetAllLaserTowers, callback = C.LaunchLaserTower }, { id = "mine", type = "military", getnum = C.GetNumAllMines, getdata = C.GetAllMines, callback = C.LaunchMine }, }, inactiveButtonProperties = { bgColor = Helper.defaultUnselectableButtonBackgroundColor, highlightColor = Helper.defaultUnselectableButtonHighlightColor }, activeButtonTextProperties = { halign = "center" }, inactiveButtonTextProperties = { halign = "center", color = Helper.color.grey }, dronetypes = { { id = "orecollector", name = ReadText(20214, 500) }, { id = "gascollector", name = ReadText(20214, 400) }, { id = "defence", name = ReadText(20214, 300) }, { id = "transport", name = ReadText(20214, 900) }, }, turretmodes = { [1] = { id = "defend", text = ReadText(1001, 8613), icon = "", displayremoveoption = false }, [2] = { id = "attackenemies", text = ReadText(1001, 8614), icon = "", displayremoveoption = false }, [3] = { id = "attackcapital", text = ReadText(1001, 8624), icon = "", displayremoveoption = false }, [4] = { id = "attackfighters", text = ReadText(1001, 8625), icon = "", displayremoveoption = false }, [5] = { id = "mining", text = ReadText(1001, 8616), icon = "", displayremoveoption = false }, [6] = { id = "missiledefence", text = ReadText(1001, 8615), icon = "", displayremoveoption = false }, [7] = { id = "autoassist", text = ReadText(1001, 8617), icon = "", displayremoveoption = false }, }, turretmodesstation = { [1] = { id = "defend", text = ReadText(1001, 8613), icon = "", displayremoveoption = false }, [2] = { id = "attackenemies", text = ReadText(1001, 8614), icon = "", displayremoveoption = false }, [3] = { id = "attackcapital", text = ReadText(1001, 8624), icon = "", displayremoveoption = false }, [4] = { id = "attackfighters", text = ReadText(1001, 8625), icon = "", displayremoveoption = false }, [5] = { id = "missiledefence", text = ReadText(1001, 8615), icon = "", displayremoveoption = false }, }, turretmodesexpanded = { [1] = { id = "defend", text = ReadText(1001, 8613), icon = "", displayremoveoption = false }, [2] = { id = "attackenemies", text = ReadText(1001, 8614), icon = "", displayremoveoption = false }, [3] = { id = "attackcapital", text = ReadText(1001, 8624), icon = "", displayremoveoption = false }, [4] = { id = "attackfighters", text = ReadText(1001, 8625), icon = "", displayremoveoption = false }, [5] = { id = "mining", text = ReadText(1001, 8616), icon = "", displayremoveoption = false }, [6] = { id = "missiledefence", text = ReadText(1001, 8615), icon = "", displayremoveoption = false }, [7] = { id = "autoassist", text = ReadText(1001, 8617), icon = "", displayremoveoption = false }, [8] = { id = "engines", text = ReadText(92015, 5000), icon = "", displayremoveoption = false }, [9] = { id = "shields", text = ReadText(92015, 5001), icon = "", displayremoveoption = false }, [10] = { id = "weps_m", text = ReadText(92015, 5002), icon = "", displayremoveoption = false }, [11] = { id = "weps_l", text = ReadText(92015, 5003), icon = "", displayremoveoption = false }, [12] = { id = "missiles", text = ReadText(92015, 5004), icon = "", displayremoveoption = false }, [13] = { id = "batteries", text = ReadText(92015, 5005), icon = "", displayremoveoption = false }, [14] = { id = "disable", text = ReadText(92015, 5006), icon = "", displayremoveoption = false }, [15] = { id = "targetsubclear", text = ReadText(92015, 5007), icon = "", displayremoveoption = false }, }, turretmode_t = { ["engines"] = "engines", ["shields"] = "shields", ["weps_m"] = "weps_m", ["weps_l"] = "weps_l", ["missiles"] = "missiles", ["batteries"] = "batteries", ["disable"] = "disable" }, mapRowHeight = Helper.standardTextHeight, mapFontSize = Helper.standardFontSize, infoFrameLayer2 = 5, infoFrameLayer = 4 } local function init() DebugError("Subsystem Targeting Orders Init") menu = Lib.Get_Egosoft_Menu("MapMenu") menu.setupLoadoutInfoSubmenuRows = sto_menu.setupLoadoutInfoSubmenuRows dock_menu = Lib.Get_Egosoft_Menu("DockedMenu") dock_menu.display = sto_menu.display end function sto_menu.setupLoadoutInfoSubmenuRows(mode, inputtable, inputobject, instance) local object64 = ConvertStringTo64Bit(tostring(inputobject)) local isplayerowned, isonlineobject, isenemy, ishostile = GetComponentData(object64, "isplayerowned", "isonlineobject", "isenemy", "ishostile") local titlecolor = Helper.color.white if isplayerowned then titlecolor = menu.holomapcolor.playercolor if object64 == C.GetPlayerObjectID() then titlecolor = menu.holomapcolor.currentplayershipcolor end elseif isonlineobject and menu.getFilterOption("layer_think") and menu.getFilterOption("think_diplomacy_highlightvisitor") then titlecolor = menu.holomapcolor.visitorcolor elseif ishostile then titlecolor = menu.holomapcolor.hostilecolor elseif isenemy then titlecolor = menu.holomapcolor.enemycolor end local loadout = {} if mode == "ship" or mode == "station" then loadout = { ["component"] = {}, ["macro"] = {}, ["ware"] = {} } for i, upgradetype in ipairs(Helper.upgradetypes) do if upgradetype.supertype == "macro" then loadout.component[upgradetype.type] = {} local numslots = 0 if C.IsComponentClass(inputobject, "defensible") then numslots = tonumber(C.GetNumUpgradeSlots(inputobject, "", upgradetype.type)) end for j = 1, numslots do local current = C.GetUpgradeSlotCurrentComponent(inputobject, upgradetype.type, j) if current ~= 0 then table.insert(loadout.component[upgradetype.type], current) end end elseif upgradetype.supertype == "virtualmacro" then loadout.macro[upgradetype.type] = {} local numslots = tonumber(C.GetNumVirtualUpgradeSlots(inputobject, "", upgradetype.type)) for j = 1, numslots do local current = ffi.string(C.GetVirtualUpgradeSlotCurrentMacro(inputobject, upgradetype.type, j)) if current ~= "" then table.insert(loadout.macro[upgradetype.type], current) end end elseif upgradetype.supertype == "software" then loadout.ware[upgradetype.type] = {} local numslots = C.GetNumSoftwareSlots(inputobject, "") local buf = ffi.new("SoftwareSlot[?]", numslots) numslots = C.GetSoftwareSlots(buf, numslots, inputobject, "") for j = 0, numslots - 1 do local current = ffi.string(buf[j].current) if current ~= "" then table.insert(loadout.ware[upgradetype.type], current) end end elseif upgradetype.supertype == "ammo" then loadout.macro[upgradetype.type] = {} end end end local cheatsecrecy = false -- secrecy stuff local nameinfo = cheatsecrecy or C.IsInfoUnlockedForPlayer(inputobject, "name") local defenceinfo_low = cheatsecrecy or C.IsInfoUnlockedForPlayer(inputobject, "defence_level") local defenceinfo_high = cheatsecrecy or C.IsInfoUnlockedForPlayer(inputobject, "defence_status") local unitinfo_capacity = cheatsecrecy or C.IsInfoUnlockedForPlayer(inputobject, "units_capacity") local unitinfo_amount = cheatsecrecy or C.IsInfoUnlockedForPlayer(inputobject, "units_amount") local unitinfo_details = cheatsecrecy or C.IsInfoUnlockedForPlayer(inputobject, "units_details") local equipment_mods = cheatsecrecy or C.IsInfoUnlockedForPlayer(inputobject, "equipment_mods") --- title --- local row = inputtable:addRow(false, {fixed = true, bgColor = Helper.defaultTitleBackgroundColor}) row[1]:setColSpan(13):createText(ReadText(1001, 9413), Helper.headerRow1Properties) local objectname = Helper.unlockInfo(nameinfo, ffi.string(C.GetComponentName(inputobject))) -- object name local row = inputtable:addRow("info_focus", { fixed = true, bgColor = Helper.defaultTitleBackgroundColor }) row[13]:createButton({ width = config.mapRowHeight, cellBGColor = Helper.color.transparent }):setIcon("menu_center_selection", { width = config.mapRowHeight, height = config.mapRowHeight, y = (Helper.headerRow1Height - config.mapRowHeight) / 2 }) row[13].handlers.onClick = function () return C.SetFocusMapComponent(menu.holomap, menu.infoSubmenuObject, true) end if (mode == "ship") or (mode == "station") then row[1]:setBackgroundColSpan(12):setColSpan(6):createText(objectname, Helper.headerRow1Properties) row[1].properties.color = titlecolor row[7]:setColSpan(6):createText(Helper.unlockInfo(nameinfo, ffi.string(C.GetObjectIDCode(inputobject))), Helper.headerRow1Properties) row[7].properties.halign = "right" row[7].properties.color = titlecolor else row[1]:setBackgroundColSpan(12):setColSpan(12):createText(objectname, Helper.headerRow1Properties) row[1].properties.color = titlecolor end if mode == "ship" then local pilot = GetComponentData(inputobject, "assignedpilot") pilot = ConvertIDTo64Bit(pilot) local pilotname, skilltable, postname, aicommandstack, aicommand, aicommandparam, aicommandaction, aicommandactionparam = "-", {}, ReadText(1001, 4847), {} if pilot and IsValidComponent(pilot) then pilotname, skilltable, postname, aicommandstack, aicommand, aicommandparam, aicommandaction, aicommandactionparam = GetComponentData(pilot, "name", "skills", "postname", "aicommandstack", "aicommand", "aicommandparam", "aicommandaction", "aicommandactionparam") end local isbigship = C.IsComponentClass(inputobject, "ship_m") or C.IsComponentClass(inputobject, "ship_l") or C.IsComponentClass(inputobject, "ship_xl") -- weapon config if isplayerowned and (#loadout.component.weapon > 0) then local row = inputtable:addRow(false, { bgColor = Helper.defaultTitleBackgroundColor }) row[1]:setColSpan(13):createText(ReadText(1001, 9409), Helper.headerRowCenteredProperties) -- Weapon Configuration -- subheader local row = inputtable:addRow(false, { bgColor = Helper.color.unselectable }) row[3]:setColSpan(5):createText(ReadText(1001, 9410), { font = Helper.standardFontBold }) -- Primary row[8]:setColSpan(6):createText(ReadText(1001, 9411), { font = Helper.standardFontBold }) -- Secondary -- active weapon groups local row = inputtable:addRow("info_weaponconfig_active", { bgColor = Helper.color.transparent }) row[2]:createText(ReadText(1001, 11218)) for j = 1, 4 do row[2 + j]:createCheckBox(function () return C.GetDefensibleActiveWeaponGroup(inputobject, true) == j end, { width = config.mapRowHeight, height = config.mapRowHeight, symbol = "arrow", bgColor = function () return menu.infoWeaponGroupCheckBoxColor(inputobject, j, true) end }) row[2 + j].handlers.onClick = function () C.SetDefensibleActiveWeaponGroup(inputobject, true, j) end end for j = 1, 4 do row[7 + j]:createCheckBox(function () return C.GetDefensibleActiveWeaponGroup(inputobject, false) == j end, { width = config.mapRowHeight, height = config.mapRowHeight, symbol = "arrow", bgColor = function () return menu.infoWeaponGroupCheckBoxColor(inputobject, j, false) end }) row[7 + j].handlers.onClick = function () C.SetDefensibleActiveWeaponGroup(inputobject, false, j) end end inputtable:addEmptyRow(config.mapRowHeight / 2) -- weapons for i, gun in ipairs(loadout.component.weapon) do local gun = ConvertStringTo64Bit(tostring(gun)) local numweapongroups = C.GetNumWeaponGroupsByWeapon(inputobject, gun) local rawweapongroups = ffi.new("UIWeaponGroup[?]", numweapongroups) numweapongroups = C.GetWeaponGroupsByWeapon(rawweapongroups, numweapongroups, inputobject, gun) local uiweapongroups = { primary = {}, secondary = {} } for j = 0, numweapongroups - 1 do -- there are two sets: primary and secondary. -- each set has four groups. -- .primary tells you if this particular weapon is active in a group in the primary or secondary group set. -- .idx tells you which group in that group set it is active in. if rawweapongroups[j].primary then uiweapongroups.primary[rawweapongroups[j].idx] = true else uiweapongroups.secondary[rawweapongroups[j].idx] = true end --print("primary: " .. tostring(rawweapongroups[j].primary) .. ", idx: " .. tostring(rawweapongroups[j].idx)) end local row = inputtable:addRow("info_weaponconfig" .. i, { bgColor = Helper.color.transparent }) row[2]:createText(ffi.string(C.GetComponentName(gun))) -- primary weapon groups for j = 1, 4 do row[2 + j]:createCheckBox(uiweapongroups.primary[j], { width = config.mapRowHeight, height = config.mapRowHeight, bgColor = function () return menu.infoWeaponGroupCheckBoxColor(inputobject, j, true) end }) row[2 + j].handlers.onClick = function() menu.infoSetWeaponGroup(inputobject, gun, true, j, not uiweapongroups.primary[j]) end end -- secondary weapon groups for j = 1, 4 do row[7 + j]:createCheckBox(uiweapongroups.secondary[j], { width = config.mapRowHeight, height = config.mapRowHeight, bgColor = function () return menu.infoWeaponGroupCheckBoxColor(inputobject, j, false) end }) row[7 + j].handlers.onClick = function() menu.infoSetWeaponGroup(inputobject, gun, false, j, not uiweapongroups.secondary[j]) end end if IsComponentClass(gun, "missilelauncher") then local nummissiletypes = C.GetNumAllMissiles(inputobject) local missilestoragetable = ffi.new("AmmoData[?]", nummissiletypes) nummissiletypes = C.GetAllMissiles(missilestoragetable, nummissiletypes, inputobject) local gunmacro = GetComponentData(gun, "macro") local dropdowndata = {} for j = 0, nummissiletypes-1 do local ammomacro = ffi.string(missilestoragetable[j].macro) if C.IsAmmoMacroCompatible(gunmacro, ammomacro) then table.insert(dropdowndata, {id = ammomacro, text = GetMacroData(ammomacro, "name"), icon = "", displayremoveoption = false}) end end -- if the ship has no compatible ammunition in ammo storage, have the dropdown print "Out of ammo" and make it inactive. local currentammomacro = "empty" local dropdownactive = true if #dropdowndata == 0 then dropdownactive = false table.insert(dropdowndata, {id = "empty", text = ReadText(1001, 9412), icon = "", displayremoveoption = false}) -- Out of ammo else -- NB: currentammomacro can be null currentammomacro = ffi.string(C.GetCurrentAmmoOfWeapon(gun)) end row = inputtable:addRow(("info_weaponconfig" .. i .. "_ammo"), { bgColor = Helper.color.transparent }) row[2]:createText((ReadText(1001, 2800) .. ReadText(1001, 120))) -- Ammunition, : row[3]:setColSpan(11):createDropDown(dropdowndata, {startOption = currentammomacro, active = dropdownactive}) row[3].handlers.onDropDownConfirmed = function(_, newammomacro) C.SetAmmoOfWeapon(gun, newammomacro) end elseif pilot and IsValidComponent(pilot) and IsComponentClass(gun, "bomblauncher") then local numbombtypes = C.GetNumAllInventoryBombs(pilot) local bombstoragetable = ffi.new("AmmoData[?]", numbombtypes) numbombtypes = C.GetAllInventoryBombs(bombstoragetable, numbombtypes, pilot) local gunmacro = GetComponentData(gun, "macro") local dropdowndata = {} for j = 0, numbombtypes-1 do local ammomacro = ffi.string(bombstoragetable[j].macro) if C.IsAmmoMacroCompatible(gunmacro, ammomacro) then table.insert(dropdowndata, {id = ammomacro, text = GetMacroData(ammomacro, "name"), icon = "", displayremoveoption = false}) end end -- if the ship has no compatible ammunition in ammo storage, have the dropdown print "Out of ammo" and make it inactive. local currentammomacro = "empty" local dropdownactive = true if #dropdowndata == 0 then dropdownactive = false table.insert(dropdowndata, {id = "empty", text = ReadText(1001, 9412), icon = "", displayremoveoption = false}) -- Out of ammo else -- NB: currentammomacro can be null currentammomacro = ffi.string(C.GetCurrentAmmoOfWeapon(gun)) end row = inputtable:addRow(("info_weaponconfig" .. i .. "_ammo"), { bgColor = Helper.color.transparent }) row[2]:createText((ReadText(1001, 2800) .. ReadText(1001, 120))) -- Ammunition, : row[3]:setColSpan(11):createDropDown(dropdowndata, {startOption = currentammomacro, active = dropdownactive}) row[3].handlers.onDropDownConfirmed = function(_, newammomacro) C.SetAmmoOfWeapon(gun, newammomacro) end end end end end if (mode == "ship") or (mode == "station") then -- turret behaviour if isplayerowned and #loadout.component.turret > 0 then local hasnormalturrets = false local hasmissileturrets = false local hasoperationalnormalturrets = false local hasoperationalmissileturrets = false local row = inputtable:addRow(false, { bgColor = Helper.defaultTitleBackgroundColor }) row[1]:setColSpan(13):createText(ReadText(1001, 8612), Helper.headerRowCenteredProperties) -- Turret Behaviour menu.turrets = {} local numslots = tonumber(C.GetNumUpgradeSlots(inputobject, "", "turret")) for j = 1, numslots do local groupinfo = C.GetUpgradeSlotGroup(inputobject, "", "turret", j) if (ffi.string(groupinfo.path) == "..") and (ffi.string(groupinfo.group) == "") then local current = C.GetUpgradeSlotCurrentComponent(inputobject, "turret", j) if current ~= 0 then if (not hasmissileturrets) or (not hasnormalturrets) then local ismissileturret = C.IsComponentClass(current, "missileturret") hasmissileturrets = hasmissileturrets or ismissileturret hasnormalturrets = hasnormalturrets or (not ismissileturret) end table.insert(menu.turrets, current) end end end menu.turretgroups = {} local n = C.GetNumUpgradeGroups(inputobject, "") local buf = ffi.new("UpgradeGroup2[?]", n) n = C.GetUpgradeGroups2(buf, n, inputobject, "") for i = 0, n - 1 do if (ffi.string(buf[i].path) ~= "..") or (ffi.string(buf[i].group) ~= "") then local group = { context = buf[i].contextid, path = ffi.string(buf[i].path), group = ffi.string(buf[i].group) } local groupinfo = C.GetUpgradeGroupInfo2(inputobject, "", group.context, group.path, group.group, "turret") if (groupinfo.count > 0) then group.operational = groupinfo.operational group.currentmacro = ffi.string(groupinfo.currentmacro) group.slotsize = ffi.string(groupinfo.slotsize) if (not hasmissileturrets) or (not hasnormalturrets) then local ismissileturret = IsMacroClass(group.currentmacro, "missileturret") hasmissileturrets = hasmissileturrets or ismissileturret hasnormalturrets = hasnormalturrets or (not ismissileturret) if ismissileturret then if not hasoperationalmissileturrets then hasoperationalmissileturrets = group.operational > 0 end else if not hasoperationalnormalturrets then hasoperationalnormalturrets = group.operational > 0 end end end table.insert(menu.turretgroups, group) end end end if (#menu.turrets > 0) or (#menu.turretgroups > 0) then if mode == "ship" then local pilotentityid = GetControlEntity(inputobject) local row = inputtable:addRow("info_turretconfig", { bgColor = Helper.color.transparent }) row[2]:setColSpan(3):createText(ReadText(1001, 2963)) row[5]:setColSpan(9):createDropDown(config.turretmodesexpanded, { startOption = function () local startoption = menu.getDropDownTurretModeOption(inputobject, "all") if GetNPCBlackboard(pilotentityid, "$SubTargetPref") ~= "" and GetNPCBlackboard(pilotentityid, "$SubTargetPref") then startoption = GetNPCBlackboard(pilotentityid, "$SubTargetPref") end return startoption end }) row[5].handlers.onDropDownConfirmed = function(_, newturretmode) if config.turretmode_t[newturretmode] then AddUITriggeredEvent("WeaponModeChanged", "onWeaponModeSelected", newturretmode) SetNPCBlackboard(pilotentityid, "$SubTargetPref", newturretmode) elseif newturretmode == "targetsubclear" then menu.noupdate = false AddUITriggeredEvent("WeaponModeChanged", "onWeaponModeSelected", newturretmode) SetNPCBlackboard(pilotentityid, "$SubTargetPref", "") else menu.noupdate = false C.SetAllTurretModes(inputobject, newturretmode) end end row[5].handlers.onDropDownActivated = function () menu.noupdate = true end local row = inputtable:addRow("info_turretconfig_2", { bgColor = Helper.color.transparent }) row[5]:setColSpan(9):createButton({ height = config.mapRowHeight }):setText(function () return menu.areTurretsArmed(inputobject) and ReadText(1001, 8631) or ReadText(1001, 8632) end, { halign = "center" }) row[5].handlers.onClick = function () return C.SetAllTurretsArmed(inputobject, not menu.areTurretsArmed(inputobject)) end local dropdownCount = 1 for i, turret in ipairs(menu.turrets) do inputtable:addEmptyRow(config.mapRowHeight / 2) local row = inputtable:addRow("info_turretconfig" .. i, { bgColor = Helper.color.transparent }) row[2]:setColSpan(3):createText(ffi.string(C.GetComponentName(turret))) row[5]:setColSpan(9):createDropDown(config.turretmodes, { startOption = function () return menu.getDropDownTurretModeOption(turret) end }) row[5].handlers.onDropDownConfirmed = function(_, newturretmode) menu.noupdate = false; C.SetWeaponMode(turret, newturretmode) end row[5].handlers.onDropDownActivated = function () menu.noupdate = true end dropdownCount = dropdownCount + 1 if dropdownCount == 14 then inputtable.properties.maxVisibleHeight = inputtable:getFullHeight() end local row = inputtable:addRow("info_turretconfig" .. i .. "_2", { bgColor = Helper.color.transparent }) row[5]:setColSpan(9):createButton({ height = config.mapRowHeight }):setText(function () return C.IsWeaponArmed(turret) and ReadText(1001, 8631) or ReadText(1001, 8632) end, { halign = "center" }) row[5].handlers.onClick = function () return C.SetWeaponArmed(turret, not C.IsWeaponArmed(turret)) end end for i, group in ipairs(menu.turretgroups) do inputtable:addEmptyRow(config.mapRowHeight / 2) local name = ReadText(1001, 8023) .. " " .. i .. ((group.currentmacro ~= "") and (" (" .. menu.getSlotSizeText(group.slotsize) .. " " .. GetMacroData(group.currentmacro, "shortname") .. ")") or "") local row = inputtable:addRow("info_turretgroupconfig" .. i, { bgColor = Helper.color.transparent }) row[2]:setColSpan(3):createText(name, { color = (group.operational > 0) and Helper.color.white or Helper.color.red }) row[5]:setColSpan(9):createDropDown(config.turretmodes, { startOption = function () return menu.getDropDownTurretModeOption(inputobject, group.context, group.path, group.group) end, active = group.operational > 0 }) row[5].handlers.onDropDownConfirmed = function(_, newturretmode) menu.noupdate = false; C.SetTurretGroupMode2(inputobject, group.context, group.path, group.group, newturretmode) end row[5].handlers.onDropDownActivated = function () menu.noupdate = true end dropdownCount = dropdownCount + 1 if dropdownCount == 14 then inputtable.properties.maxVisibleHeight = inputtable:getFullHeight() end local row = inputtable:addRow("info_turretgroupconfig" .. i .. "_2", { bgColor = Helper.color.transparent }) row[5]:setColSpan(9):createButton({ height = config.mapRowHeight }):setText(function () return C.IsTurretGroupArmed(inputobject, group.context, group.path, group.group) and ReadText(1001, 8631) or ReadText(1001, 8632) end, { halign = "center" }) row[5].handlers.onClick = function () return C.SetTurretGroupArmed(inputobject, group.context, group.path, group.group, not C.IsTurretGroupArmed(inputobject, group.context, group.path, group.group)) end end elseif mode == "station" then if hasnormalturrets then -- non-missile local row = inputtable:addRow("info_turretconfig", { bgColor = Helper.color.transparent }) row[2]:setColSpan(3):createText(ReadText(1001, 8397)) row[5]:setColSpan(9):createDropDown(config.turretmodesstation, { startOption = function () return menu.getDropDownTurretModeOption(inputobject, "all", false) end, active = hasoperationalnormalturrets, mouseOverText = (not hasoperationalnormalturrets) and ReadText(1026, 3235) or nil }) row[5].handlers.onDropDownConfirmed = function(_, newturretmode) menu.noupdate = false; C.SetAllNonMissileTurretModes(inputobject, newturretmode) end row[5].handlers.onDropDownActivated = function () menu.noupdate = true end local row = inputtable:addRow("info_turretconfig_2", { bgColor = Helper.color.transparent }) row[5]:setColSpan(9):createButton({ height = config.mapRowHeight }):setText(function () return menu.areTurretsArmed(inputobject, false) and ReadText(1001, 8631) or ReadText(1001, 8632) end, { halign = "center" }) row[5].handlers.onClick = function () return C.SetAllNonMissileTurretsArmed(inputobject, not menu.areTurretsArmed(inputobject, false)) end end if hasmissileturrets then -- missile local row = inputtable:addRow("info_turretconfig_missile", { bgColor = Helper.color.transparent }) row[2]:setColSpan(3):createText(ReadText(1001, 9031)) row[5]:setColSpan(9):createDropDown(config.turretmodesstation, { startOption = function () return menu.getDropDownTurretModeOption(inputobject, "all", true) end, active = hasoperationalmissileturrets, mouseOverText = (not hasoperationalnormalturrets) and ReadText(1026, 3235) or nil }) row[5].handlers.onDropDownConfirmed = function(_, newturretmode) menu.noupdate = false; C.SetAllMissileTurretModes(inputobject, newturretmode) end row[5].handlers.onDropDownActivated = function () menu.noupdate = true end local row = inputtable:addRow("info_turretconfig_missile_2", { bgColor = Helper.color.transparent }) row[5]:setColSpan(9):createButton({ height = config.mapRowHeight }):setText(function () return menu.areTurretsArmed(inputobject, true) and ReadText(1001, 8631) or ReadText(1001, 8632) end, { halign = "center" }) row[5].handlers.onClick = function () return C.SetAllMissileTurretsArmed(inputobject, not menu.areTurretsArmed(inputobject, true)) end end end end end -- drones local isplayeroccupiedship = menu.infoSubmenuObject == ConvertStringTo64Bit(tostring(C.GetPlayerOccupiedShipID())) local unitstoragetable = C.IsComponentClass(object64, "defensible") and GetUnitStorageData(object64) or { stored = 0, capacity = 0 } local locunitcapacity = Helper.unlockInfo(unitinfo_capacity, tostring(unitstoragetable.capacity)) local locunitcount = Helper.unlockInfo(unitinfo_amount, tostring(unitstoragetable.stored)) menu.drones = {} local dronetypes = { { id = "orecollector", name = ReadText(20214, 500), displayonly = true }, { id = "gascollector", name = ReadText(20214, 400), displayonly = true }, { id = "defence", name = ReadText(20214, 300) }, { id = "transport", name = ReadText(20214, 900) }, { id = "build", name = ReadText(20214, 1000), skipmode = true }, { id = "repair", name = ReadText(20214, 1100), skipmode = true }, } for _, dronetype in ipairs(dronetypes) do if C.GetNumStoredUnits(inputobject, dronetype.id, false) > 0 then local entry if not dronetype.skipmode then entry = { type = dronetype.id, name = dronetype.name, current = ffi.string(C.GetCurrentDroneMode(inputobject, dronetype.id)), modes = {}, displayonly = dronetype.displayonly, } local n = C.GetNumDroneModes(inputobject, dronetype.id) local buf = ffi.new("DroneModeInfo[?]", n) n = C.GetDroneModes(buf, n, inputobject, dronetype.id) for i = 0, n - 1 do local id = ffi.string(buf[i].id) if (id ~= "trade") or (id == entry.current) then table.insert(entry.modes, { id = id, text = ffi.string(buf[i].name), icon = "", displayremoveoption = false }) end end else entry = { type = dronetype.id, name = dronetype.name, } end table.insert(menu.drones, entry) end end if unitstoragetable.capacity > 0 then -- title local row = inputtable:addRow(false, { bgColor = Helper.defaultTitleBackgroundColor }) row[1]:setColSpan(13):createText(ReadText(1001, 8619), Helper.headerRowCenteredProperties) -- capcity local row = inputtable:addRow(false, { bgColor = Helper.color.unselectable }) row[2]:createText(ReadText(1001, 8393)) row[8]:setColSpan(6):createText(locunitcount .. " / " .. locunitcapacity, { halign = "right" }) -- drones if unitinfo_details then for i, entry in ipairs(menu.drones) do if i ~= 1 then inputtable:addEmptyRow(config.mapRowHeight / 2) end local hasmodes = (mode == "ship") and entry.current -- drone name, amount and mode local row1 = inputtable:addRow("drone_config", { bgColor = Helper.color.transparent }) row1[2]:createText(entry.name) row1[3]:setColSpan(isplayerowned and 2 or 11):createText(function () return Helper.unlockInfo(unitinfo_amount, C.GetNumStoredUnits(inputobject, entry.type, false)) end, { halign = isplayerowned and "left" or "right" }) -- active and armed status local row2 = inputtable:addRow("drone_config", { bgColor = Helper.color.transparent }) row2[2]:createText(" " .. ReadText(1001, 11229), { color = hasmodes and function () return C.IsDroneTypeArmed(inputobject, entry.type) and Helper.color.white or Helper.color.grey end or nil }) row2[3]:setColSpan(isplayerowned and 2 or 11):createText(function () return Helper.unlockInfo(unitinfo_amount, C.GetNumUnavailableUnits(inputobject, entry.type)) end, { halign = isplayerowned and "left" or "right", color = hasmodes and function () return C.IsDroneTypeBlocked(inputobject, entry.type) and Helper.color.warningorange or (C.IsDroneTypeArmed(inputobject, entry.type) and Helper.color.white or Helper.color.grey) end or nil }) -- drone mode support - disabled for mining drones, to avoid conflicts with order defined drone behaviour if hasmodes then local isblocked = C.IsDroneTypeBlocked(inputobject, entry.type) if isplayerowned then local active = (isplayeroccupiedship or (not entry.displayonly)) and (not isblocked) local mouseovertext = "" if isblocked then mouseovertext = ReadText(1026, 3229) elseif (not isplayeroccupiedship) and entry.displayonly then mouseovertext = ReadText(1026, 3230) end row1[5]:setColSpan(9):createDropDown(entry.modes, { startOption = function () return ffi.string(C.GetCurrentDroneMode(inputobject, entry.type)) end, active = active, mouseOverText = mouseovertext }) row1[5].handlers.onDropDownConfirmed = function (_, newdronemode) C.SetDroneMode(inputobject, entry.type, newdronemode) end row2[5]:setColSpan(9):createButton({ active = active, mouseOverText = mouseovertext, height = config.mapRowHeight }):setText(function () return C.IsDroneTypeArmed(inputobject, entry.type) and ReadText(1001, 8622) or ReadText(1001, 8623) end, { halign = "center" }) row2[5].handlers.onClick = function () return C.SetDroneTypeArmed(inputobject, entry.type, not C.IsDroneTypeArmed(inputobject, entry.type)) end end end end end end -- subordinates if isplayerowned then if C.IsComponentClass(inputobject, "controllable") then local subordinates = GetSubordinates(inputobject) local groups = {} local usedassignments = {} for _, subordinate in ipairs(subordinates) do local purpose, shiptype = GetComponentData(subordinate, "primarypurpose", "shiptype") local group = GetComponentData(subordinate, "subordinategroup") if group and group > 0 then if groups[group] then table.insert(groups[group].subordinates, subordinate) if shiptype == "resupplier" then groups[group].numassignableresupplyships = groups[group].numassignableresupplyships + 1 end if purpose == "mine" then groups[group].numassignableminingships = groups[group].numassignableminingships + 1 end else local assignment = ffi.string(C.GetSubordinateGroupAssignment(inputobject, group)) usedassignments[assignment] = group groups[group] = { assignment = assignment, subordinates = { subordinate }, numassignableresupplyships = (shiptype == "resupplier") and 1 or 0, numassignableminingships = (purpose == "mine") and 1 or 0 } end end end if #subordinates > 0 then -- title local row = inputtable:addRow(false, { bgColor = Helper.defaultTitleBackgroundColor }) row[1]:setColSpan(13):createText(ReadText(1001, 8626), Helper.headerRowCenteredProperties) local isstation = C.IsComponentClass(inputobject, "station") for i = 1, isstation and 4 or 10 do if groups[i] then local supplyactive = (groups[i].numassignableresupplyships == #groups[i].subordinates) and ((not usedassignments["supplyfleet"]) or (usedassignments["supplyfleet"] == i)) local subordinateassignments = { [1] = { id = "defence", text = ReadText(20208, 40301), icon = "", displayremoveoption = false }, [2] = { id = "supplyfleet", text = ReadText(20208, 40701), icon = "", displayremoveoption = false, active = supplyactive, mouseovertext = supplyactive and "" or ReadText(1026, 8601) }, } if GetComponentData(inputobject, "shiptype") == "resupplier" then table.insert(subordinateassignments, { id = "trade", text = ReadText(20208, 40101), icon = "", displayremoveoption = false }) end if isstation then local miningactive = (groups[i].numassignableminingships == #groups[i].subordinates) and ((not usedassignments["mining"]) or (usedassignments["mining"] == i)) table.insert(subordinateassignments, { id = "mining", text = ReadText(20208, 40201), icon = "", displayremoveoption = false, active = miningactive, mouseovertext = miningactive and "" or ReadText(1026, 8602) }) local tradeactive = ((not usedassignments["trade"]) or (usedassignments["trade"] == i)) table.insert(subordinateassignments, { id = "trade", text = ReadText(20208, 40101), icon = "", displayremoveoption = false, active = tradeactive, mouseovertext = tradeactive and ((groups[i].numassignableminingships > 0) and (Helper.convertColorToText(Helper.color.warningorange) .. ReadText(1026, 8607)) or "") or ReadText(1026, 7840) }) local tradeforbuildstorageactive = (groups[i].numassignableminingships == 0) and ((not usedassignments["tradeforbuildstorage"]) or (usedassignments["tradeforbuildstorage"] == i)) table.insert(subordinateassignments, { id = "tradeforbuildstorage", text = ReadText(20208, 40801), icon = "", displayremoveoption = false, active = tradeforbuildstorageactive, mouseovertext = tradeforbuildstorageactive and "" or ReadText(1026, 8603) }) elseif C.IsComponentClass(inputobject, "ship") then table.insert(subordinateassignments, { id = "attack", text = ReadText(20208, 40901), icon = "", displayremoveoption = false }) table.insert(subordinateassignments, { id = "interception", text = ReadText(20208, 41001), icon = "", displayremoveoption = false }) table.insert(subordinateassignments, { id = "follow", text = ReadText(20208, 41301), icon = "", displayremoveoption = false }) local active = true local mouseovertext = "" local buf = ffi.new("Order") if not C.GetDefaultOrder(buf, inputobject) then active = false mouseovertext = ReadText(1026, 8606) end table.insert(subordinateassignments, { id = "assist", text = ReadText(20208, 41201), icon = "", displayremoveoption = false, active = active, mouseovertext = mouseovertext }) end local isdockingpossible = false for _, subordinate in ipairs(groups[i].subordinates) do if IsDockingPossible(subordinate, inputobject) then isdockingpossible = true break end end local active = true local mouseovertext = "" if not GetComponentData(inputobject, "hasshipdockingbays") then active = false mouseovertext = ReadText(1026, 8604) elseif not isdockingpossible then active = false mouseovertext = ReadText(1026, 8605) end local row = inputtable:addRow("subordinate_config", { bgColor = Helper.color.transparent }) row[2]:createText(function () menu.updateSubordinateGroupInfo(inputobject); return ReadText(20401, i) .. (menu.subordinategroups[i] and (" (" .. ((not C.ShouldSubordinateGroupDockAtCommander(inputobject, i)) and ((#menu.subordinategroups[i].subordinates - menu.subordinategroups[i].numdockedatcommander) .. "/") or "") .. #menu.subordinategroups[i].subordinates ..")") or "") end, { color = isblocked and Helper.color.warningorange or nil }) row[3]:setColSpan(11):createDropDown(subordinateassignments, { startOption = function () menu.updateSubordinateGroupInfo(inputobject); return menu.subordinategroups[i] and menu.subordinategroups[i].assignment or "" end }) row[3].handlers.onDropDownActivated = function () menu.noupdate = true end row[3].handlers.onDropDownConfirmed = function (_, newassignment) C.SetSubordinateGroupAssignment(inputobject, i, newassignment); menu.noupdate = false end local row = inputtable:addRow("subordinate_config", { bgColor = Helper.color.transparent }) row[3]:setColSpan(11):createButton({ active = active, mouseOverText = mouseovertext, height = config.mapRowHeight }):setText(function () return C.ShouldSubordinateGroupDockAtCommander(inputobject, i) and ReadText(1001, 8630) or ReadText(1001, 8629) end, { halign = "center" }) row[3].handlers.onClick = function () return C.SetSubordinateGroupDockAtCommander(inputobject, i, not C.ShouldSubordinateGroupDockAtCommander(inputobject, i)) end end end end end end -- ammunition local nummissiletypes = C.GetNumAllMissiles(inputobject) local missilestoragetable = ffi.new("AmmoData[?]", nummissiletypes) nummissiletypes = C.GetAllMissiles(missilestoragetable, nummissiletypes, inputobject) local totalnummissiles = 0 for i = 0, nummissiletypes - 1 do totalnummissiles = totalnummissiles + missilestoragetable[i].amount end local missilecapacity = 0 if C.IsComponentClass(inputobject, "defensible") then missilecapacity = GetComponentData(inputobject, "missilecapacity") end local locmissilecapacity = Helper.unlockInfo(defenceinfo_low, tostring(missilecapacity)) local locnummissiles = Helper.unlockInfo(defenceinfo_high, tostring(totalnummissiles)) if totalnummissiles > 0 then -- title local row = inputtable:addRow(false, { bgColor = Helper.defaultTitleBackgroundColor }) row[1]:setColSpan(12):createText(ReadText(1001, 2800), Helper.headerRowCenteredProperties) -- Ammunition -- capcity local row = inputtable:addRow(false, { bgColor = Helper.color.unselectable }) row[2]:createText(ReadText(1001, 8393)) row[8]:setColSpan(6):createText(locnummissiles .. " / " .. locmissilecapacity, { halign = "right" }) if defenceinfo_high then for i = 0, nummissiletypes - 1 do local macro = ffi.string(missilestoragetable[i].macro) local row = inputtable:addRow({ "info_weapons", macro, inputobject }, { bgColor = Helper.color.transparent }) row[2]:createText(GetMacroData(macro, "name")) row[8]:setColSpan(6):createText(tostring(missilestoragetable[i].amount), { halign = "right" }) end end end end if mode == "ship" then -- countermeasures local numcountermeasuretypes = C.GetNumAllCountermeasures(inputobject) local countermeasurestoragetable = ffi.new("AmmoData[?]", numcountermeasuretypes) numcountermeasuretypes = C.GetAllCountermeasures(countermeasurestoragetable, numcountermeasuretypes, inputobject) local totalnumcountermeasures = 0 for i = 0, numcountermeasuretypes - 1 do totalnumcountermeasures = totalnumcountermeasures + countermeasurestoragetable[i].amount end local countermeasurecapacity = GetComponentData(object64, "countermeasurecapacity") local loccountermeasurecapacity = Helper.unlockInfo(defenceinfo_low, tostring(countermeasurecapacity)) local locnumcountermeasures = Helper.unlockInfo(defenceinfo_high, tostring(totalnumcountermeasures)) if totalnumcountermeasures > 0 then -- title local row = inputtable:addRow(false, { bgColor = Helper.defaultTitleBackgroundColor }) row[1]:setColSpan(13):createText(ReadText(20215, 1701), Helper.headerRowCenteredProperties) -- Countermeasures -- capcity local row = inputtable:addRow(false, { bgColor = Helper.color.unselectable }) row[2]:createText(ReadText(1001, 8393)) row[8]:setColSpan(6):createText(locnumcountermeasures .. " / " .. loccountermeasurecapacity, { halign = "right" }) if defenceinfo_high then for i = 0, numcountermeasuretypes - 1 do local row = inputtable:addRow(true, { bgColor = Helper.color.transparent, interactive = false }) row[2]:createText(GetMacroData(ffi.string(countermeasurestoragetable[i].macro), "name")) row[8]:setColSpan(6):createText(tostring(countermeasurestoragetable[i].amount), { halign = "right" }) end end end -- deployables local consumables = { { id = "satellite", type = "civilian", getnum = C.GetNumAllSatellites, getdata = C.GetAllSatellites, callback = C.LaunchSatellite }, { id = "navbeacon", type = "civilian", getnum = C.GetNumAllNavBeacons, getdata = C.GetAllNavBeacons, callback = C.LaunchNavBeacon }, { id = "resourceprobe", type = "civilian", getnum = C.GetNumAllResourceProbes, getdata = C.GetAllResourceProbes, callback = C.LaunchResourceProbe }, { id = "lasertower", type = "military", getnum = C.GetNumAllLaserTowers, getdata = C.GetAllLaserTowers, callback = C.LaunchLaserTower }, { id = "mine", type = "military", getnum = C.GetNumAllMines, getdata = C.GetAllMines, callback = C.LaunchMine }, } local totalnumdeployables = 0 local consumabledata = {} for _, entry in ipairs(consumables) do local n = entry.getnum(inputobject) local buf = ffi.new("AmmoData[?]", n) n = entry.getdata(buf, n, inputobject) consumabledata[entry.id] = {} for i = 0, n - 1 do table.insert(consumabledata[entry.id], { macro = ffi.string(buf[i].macro), name = GetMacroData(ffi.string(buf[i].macro), "name"), amount = buf[i].amount, capacity = buf[i].capacity }) totalnumdeployables = totalnumdeployables + buf[i].amount end end local deployablecapacity = C.GetDefensibleDeployableCapacity(inputobject) local printednumdeployables = Helper.unlockInfo(defenceinfo_low, tostring(totalnumdeployables)) local printeddeployablecapacity = Helper.unlockInfo(defenceinfo_low, tostring(deployablecapacity)) if totalnumdeployables > 0 then -- title local row = inputtable:addRow(false, { bgColor = Helper.defaultTitleBackgroundColor }) row[1]:setColSpan(13):createText(ReadText(1001, 1332), Helper.headerRowCenteredProperties) -- Deployables -- capcity local row = inputtable:addRow(false, { bgColor = Helper.color.unselectable }) row[2]:createText(ReadText(1001, 8393)) row[8]:setColSpan(6):createText(printednumdeployables .. " / " .. printeddeployablecapacity, { halign = "right" }) if defenceinfo_high then for _, entry in ipairs(consumables) do if #consumabledata[entry.id] > 0 then for _, data in ipairs(consumabledata[entry.id]) do local row = inputtable:addRow({ "info_deploy", data.macro, inputobject }, { bgColor = Helper.color.transparent }) row[2]:createText(data.name) row[8]:setColSpan(6):createText(data.amount, { halign = "right" }) end end end if isplayerowned then -- deploy local row = inputtable:addRow("info_deploy", { bgColor = Helper.color.transparent }) row[3]:setColSpan(11):createButton({ height = config.mapRowHeight, active = function () return next(menu.infoTablePersistentData[instance].macrostolaunch) ~= nil end }):setText(ReadText(1001, 8390), { halign = "center" }) row[3].handlers.onClick = function () return menu.buttonDeploy(instance) end end end end end if (mode == "ship") or (mode == "station") then -- loadout if (#loadout.component.weapon > 0) or (#loadout.component.turret > 0) or (#loadout.component.shield > 0) or (#loadout.component.engine > 0) or (#loadout.macro.thruster > 0) or (#loadout.ware.software > 0) then if defenceinfo_high then local hasshown = false -- title local row = inputtable:addRow(false, { bgColor = Helper.defaultTitleBackgroundColor }) row[1]:setColSpan(13):createText(ReadText(1001, 9413), Helper.headerRowCenteredProperties) -- Loadout local row = inputtable:addRow(false, { bgColor = Helper.color.unselectable }) row[2]:setColSpan(5):createText(ReadText(1001, 7935), { font = Helper.standardFontBold }) row[7]:setColSpan(4):createText(ReadText(1001, 1311), { font = Helper.standardFontBold, halign = "right" }) row[11]:setColSpan(3):createText(ReadText(1001, 12), { font = Helper.standardFontBold, halign = "right" }) inputtable:addEmptyRow(config.mapRowHeight / 2) local macroequipment = { { type = "weapon", encyclopedia = "info_weapon" }, { type = "turret", encyclopedia = "info_weapon" }, { type = "shield", encyclopedia = "info_equipment" }, { type = "engine", encyclopedia = "info_equipment" }, } for _, entry in ipairs(macroequipment) do if #loadout.component[entry.type] > 0 then if hasshown then inputtable:addEmptyRow(config.mapRowHeight / 2) end hasshown = true local locmacros = menu.infoCombineLoadoutComponents(loadout.component[entry.type]) for macro, data in pairs(locmacros) do local row = inputtable:addRow({ entry.encyclopedia, macro, inputobject }, { bgColor = Helper.color.transparent }) row[2]:setColSpan(5):createText(GetMacroData(macro, "name")) row[7]:setColSpan(4):createText(data.count .. " / " .. data.count + data.construction, { halign = "right" }) local shieldpercent = data.shieldpercent local hullpercent = data.hullpercent if data.count > 0 then shieldpercent = shieldpercent / data.count hullpercent = hullpercent / data.count end row[11]:setColSpan(3):createShieldHullBar(shieldpercent, hullpercent, { scaling = false, width = row[11]:getColSpanWidth() / 2, x = row[11]:getColSpanWidth() / 4 }) AddKnownItem(GetMacroData(macro, "infolibrary"), macro) end end end if #loadout.macro.thruster > 0 then if hasshown then inputtable:addEmptyRow(config.mapRowHeight / 2) end hasshown = true -- ships normally only have 1 set of thrusters. in case a ship has more, this will list all of them. for i, val in ipairs(loadout.macro.thruster) do local row = inputtable:addRow({ "info_equipment", macro, inputobject }, { bgColor = Helper.color.transparent }) row[2]:setColSpan(12):createText(GetMacroData(val, "name")) AddKnownItem(GetMacroData(val, "infolibrary"), val) end end if #loadout.ware.software > 0 then if hasshown then inputtable:addEmptyRow(config.mapRowHeight / 2) end hasshown = true for i, val in ipairs(loadout.ware.software) do local row = inputtable:addRow({ "info_software", val, inputobject }, { bgColor = Helper.color.transparent }) row[2]:setColSpan(12):createText(GetWareData(val, "name")) AddKnownItem("software", val) end end else local row = inputtable:addRow(false, { bgColor = Helper.color.unselectable }) row[2]:setColSpan(12):createText(ReadText(1001, 3210)) end end end if mode == "ship" then -- mods -- title local row = inputtable:addRow(false, { bgColor = Helper.defaultTitleBackgroundColor }) row[1]:setColSpan(13):createText(ReadText(1001, 8031), Helper.headerRowCenteredProperties) if equipment_mods and GetComponentData(object64, "hasanymod") then local hasshown = false -- chassis local hasinstalledmod, installedmod = Helper.getInstalledModInfo("ship", inputobject) if hasinstalledmod then if hasshown then inputtable:addEmptyRow(config.mapRowHeight / 2) end hasshown = true row = menu.addEquipmentModInfoRow(inputtable, "ship", installedmod, ReadText(1001, 8008)) end -- weapon for i, weapon in ipairs(loadout.component.weapon) do local hasinstalledmod, installedmod = Helper.getInstalledModInfo("weapon", weapon) if hasinstalledmod then if hasshown then inputtable:addEmptyRow(config.mapRowHeight / 2) end hasshown = true row = menu.addEquipmentModInfoRow(inputtable, "weapon", installedmod, ffi.string(C.GetComponentName(weapon))) end end -- turret for i, turret in ipairs(loadout.component.turret) do local hasinstalledmod, installedmod = Helper.getInstalledModInfo("turret", turret) if hasinstalledmod then if hasshown then inputtable:addEmptyRow(config.mapRowHeight / 2) end hasshown = true row = menu.addEquipmentModInfoRow(inputtable, "weapon", installedmod, ffi.string(C.GetComponentName(turret))) end end -- shield local shieldgroups = {} local n = C.GetNumShieldGroups(inputobject) local buf = ffi.new("ShieldGroup[?]", n) n = C.GetShieldGroups(buf, n, inputobject) for i = 0, n - 1 do local entry = {} entry.context = buf[i].context entry.group = ffi.string(buf[i].group) entry.component = buf[i].component table.insert(shieldgroups, entry) end for i, entry in ipairs(shieldgroups) do if (entry.context == inputobject) and (entry.group == "") then shieldgroups.hasMainGroup = true -- force maingroup to first index table.insert(shieldgroups, 1, entry) table.remove(shieldgroups, i + 1) break end end for i, shieldgroupdata in ipairs(shieldgroups) do local hasinstalledmod, installedmod = Helper.getInstalledModInfo("shield", inputobject, shieldgroupdata.context, shieldgroupdata.group) if hasinstalledmod then local name = GetMacroData(GetComponentData(ConvertStringTo64Bit(tostring(shieldgroupdata.component)), "macro"), "name") if (i == 1) and shieldgroups.hasMainGroup then name = ReadText(1001, 8044) end if hasshown then inputtable:addEmptyRow(config.mapRowHeight / 2) end hasshown = true row = menu.addEquipmentModInfoRow(inputtable, "shield", installedmod, name) end end -- engine local hasinstalledmod, installedmod = Helper.getInstalledModInfo("engine", inputobject) if hasinstalledmod then if hasshown then inputtable:addEmptyRow(config.mapRowHeight / 2) end hasshown = true row = menu.addEquipmentModInfoRow(inputtable, "engine", installedmod, ffi.string(C.GetComponentName(loadout.component.engine[1]))) end else local row = inputtable:addRow(false, { bgColor = Helper.color.unselectable }) row[2]:setColSpan(12):createText(Helper.unlockInfo(equipment_mods, ReadText(1001, 8394))) end end if mode == "none" then local row = inputtable:addRow(false, { bgColor = Helper.color.unselectable }) row[2]:setColSpan(12):createText(ReadText(1001, 6526)) end end function sto_menu.display() Helper.removeAllWidgetScripts(dock_menu) local width = Helper.viewWidth local height = Helper.viewHeight local xoffset = 0 local yoffset = 0 dock_menu.frame = Helper.createFrameHandle(dock_menu, { width = width, x = xoffset, y = yoffset, backgroundID = "solid", backgroundColor = Helper.color.semitransparent, standardButtons = ((dock_menu.mode == "docked") and (dock_menu.currentplayership ~= 0)) and {} or { close = true, back = true } }) dock_menu.createTopLevel(dock_menu.frame) local table_topleft, table_header, table_button, row local isdocked = (dock_menu.currentplayership ~= 0) and GetComponentData(dock_menu.currentplayership, "isdocked") local ownericon, owner, shiptrader, isdock, canbuildships, isplayerowned, issupplyship, canhavetradeoffers = GetComponentData(dock_menu.currentcontainer, "ownericon", "owner", "shiptrader", "isdock", "canbuildships", "isplayerowned", "issupplyship", "canhavetradeoffers") local cantrade = canhavetradeoffers and isdock local canwareexchange = cantrade and isplayerowned --NB: equipment docks currently do not have ship traders local dockedplayerships = {} Helper.ffiVLA(dockedplayerships, "UniverseID", C.GetNumDockedShips, C.GetDockedShips, dock_menu.currentcontainer, "player") local canequip = false local cansupply = false for _, ship in ipairs(dockedplayerships) do if C.CanContainerEquipShip(dock_menu.currentcontainer, ship) then canequip = true end if isplayerowned and C.CanContainerSupplyShip(dock_menu.currentcontainer, ship) then cansupply = true end end local canmodifyship = (shiptrader ~= nil) and (canequip or cansupply) and isdock local canbuyship = (shiptrader ~= nil) and canbuildships and isdock --print("cantrade: " .. tostring(cantrade) .. ", canbuyship: " .. tostring(canbuyship) .. ", canmodifyship: " .. tostring(canmodifyship)) width = (width / 3) - Helper.borderSize -- set up a new table table_topleft = dock_menu.frame:addTable(1, { tabOrder = 0, width = Helper.playerInfoConfig.width, height = Helper.playerInfoConfig.height, x = Helper.playerInfoConfig.offsetX, y = Helper.playerInfoConfig.offsetY, scaling = false }) row = table_topleft:addRow(false, { fixed = true, bgColor = Helper.color.transparent60 }) local icon = row[1]:createIcon(function () local logo = C.GetCurrentPlayerLogo(); return ffi.string(logo.icon) end, { width = Helper.playerInfoConfig.height, height = Helper.playerInfoConfig.height, color = Helper.getPlayerLogoColor }) local fontsize = Helper.scaleFont(Helper.standardFont, Helper.standardFontSize) local textheight = math.ceil(C.GetTextHeight(Helper.playerInfoConfigTextLeft(), Helper.standardFont, Helper.playerInfoConfig.fontsize, Helper.playerInfoConfig.width - Helper.playerInfoConfig.height - Helper.borderSize)) icon:setText(Helper.playerInfoConfigTextLeft, { fontsize = Helper.playerInfoConfig.fontsize, halign = "left", x = Helper.playerInfoConfig.height + Helper.borderSize, y = (Helper.playerInfoConfig.height - textheight) / 2 }) icon:setText2(Helper.playerInfoConfigTextRight, { fontsize = Helper.playerInfoConfig.fontsize, halign = "right", x = Helper.borderSize, y = (Helper.playerInfoConfig.height - textheight) / 2 }) local xoffset = (Helper.viewWidth - width) / 2 local yoffset = 25 table_header = dock_menu.frame:addTable(11, { tabOrder = 1, width = width, x = xoffset, y = dock_menu.topLevelOffsetY + Helper.borderSize + yoffset, highlightMode = "off" }) table_header:setColWidth(1, math.floor((width - 2 * Helper.borderSize) / 3), false) table_header:setColWidth(3, Helper.standardTextHeight) table_header:setColWidth(4, Helper.standardTextHeight) table_header:setColWidth(5, Helper.standardTextHeight) table_header:setColWidth(6, Helper.standardTextHeight) table_header:setColWidth(8, Helper.standardTextHeight) table_header:setColWidth(9, Helper.standardTextHeight) table_header:setColWidth(10, Helper.standardTextHeight) table_header:setColWidth(11, Helper.standardTextHeight) table_header:setDefaultColSpan(1, 1) table_header:setDefaultColSpan(2, 5) table_header:setDefaultColSpan(7, 5) table_header:setDefaultBackgroundColSpan(1, 11) local row = table_header:addRow(false, { fixed = true, bgColor = Helper.color.transparent }) local color = Helper.color.white if isplayerowned then if dock_menu.currentcontainer == C.GetPlayerObjectID() then color = Helper.color.playergreen else color = Helper.color.green end end row[1]:setColSpan(11):createText(dock_menu.currentcontainer and ffi.string(C.GetComponentName(dock_menu.currentcontainer)) or "", Helper.headerRowCenteredProperties) row[1].properties.color = color height = Helper.scaleY(Helper.standardTextHeight) local row = table_header:addRow(false, { fixed = true, bgColor = Helper.color.unselectable }) if dock_menu.mode == "cockpit" then row[2]:createText(ffi.string(C.GetObjectIDCode(dock_menu.currentcontainer)), { halign = "center", color = color }) else row[1]:createIcon(ownericon, { width = height, height = height, x = row[1]:getWidth() - height, scaling = false }) row[2]:createText(function() return GetComponentData(dock_menu.currentcontainer, "ownername") end, { halign = "center" }) row[7]:createText(function() return "[" .. GetUIRelation(GetComponentData(dock_menu.currentcontainer, "owner")) .. "]" end, { halign = "left" }) end table_header:addEmptyRow(yoffset) if dock_menu.mode == "cockpit" then local row = table_header:addRow("buttonRow1", { bgColor = Helper.color.transparent, fixed = true }) row[1]:createButton(config.inactiveButtonProperties):setText("", config.inactiveButtonTextProperties) -- dummy local active = (dock_menu.currentplayership ~= 0) and C.CanPlayerStandUp() row[2]:createButton(active and { mouseOverText = GetLocalizedKeyName("action", 277), helpOverlayID = "docked_getup", helpOverlayText = " ", helpOverlayHighlightOnly = true } or config.inactiveButtonProperties):setText(ReadText(1002, 20014), active and config.activeButtonTextProperties or config.inactiveButtonTextProperties) -- "Get Up" if active then row[2].handlers.onClick = dock_menu.buttonGetUp end row[7]:createButton({ mouseOverText = GetLocalizedKeyName("action", 316), helpOverlayID = "docked_shipinformation", helpOverlayText = " ", helpOverlayHighlightOnly = true }):setText(ReadText(1001, 8602), { halign = "center" }) -- "Ship Information" row[7].handlers.onClick = dock_menu.buttonShipInfo local row = table_header:addRow("buttonRow3", { bgColor = Helper.color.transparent, fixed = true }) local currentactivity = GetPlayerActivity() if currentactivity ~= "none" then local text = "" for _, entry in ipairs(config.modes) do if entry.id == currentactivity then text = entry.stoptext break end end local active = dock_menu.currentplayership ~= 0 row[2]:createButton(active and {helpOverlayID = "docked_stopmode", helpOverlayText = " ", helpOverlayHighlightOnly = true } or config.inactiveButtonProperties):setText(text, active and config.activeButtonTextProperties or config.inactiveButtonTextProperties) -- "Stop Mode" if active then row[2].handlers.onClick = dock_menu.buttonStopMode row[2].properties.uiTriggerID = "stopmode" end else local active = dock_menu.currentplayership ~= 0 local modes = {} if active then for _, entry in ipairs(config.modes) do local active = true local visible = true if entry.id == "travel" then active = (dock_menu.currentplayership ~= 0) and C.CanStartTravelMode(dock_menu.currentplayership) elseif entry.id == "seta" then visible = C.CanActivateSeta(false) end local mouseovertext = GetLocalizedKeyName("action", entry.action) if visible then table.insert(modes, { id = entry.id, text = entry.name, icon = "", displayremoveoption = false, active = active, mouseovertext = mouseovertext }) end end end row[2]:createDropDown(modes, { helpOverlayID = "docked_modes", helpOverlayText = " ", helpOverlayHighlightOnly = true, height = Helper.standardButtonHeight, startOption = "", textOverride = ReadText(1002, 1001), bgColor = active and Helper.defaultButtonBackgroundColor or Helper.defaultUnselectableButtonBackgroundColor, highlightColor = active and Helper.defaultButtonHighlightColor or Helper.defaultUnselectableButtonHighlightColor }):setTextProperties(active and config.activeButtonTextProperties or config.inactiveButtonTextProperties) -- Modes if active then row[2].handlers.onDropDownConfirmed = dock_menu.dropdownMode row[2].properties.uiTriggerID = "startmode" end end local civilian, military, isinhighway = {}, {}, false if dock_menu.currentplayership ~= 0 then for _, consumabledata in ipairs(config.consumables) do local numconsumable = consumabledata.getnum(dock_menu.currentplayership) if numconsumable > 0 then local consumables = ffi.new("AmmoData[?]", numconsumable) numconsumable = consumabledata.getdata(consumables, numconsumable, dock_menu.currentplayership) for j = 0, numconsumable - 1 do if consumables[j].amount > 0 then local macro = ffi.string(consumables[j].macro) if consumabledata.type == "civilian" then table.insert(civilian, { id = consumabledata.id .. ":" .. macro, text = GetMacroData(macro, "name"), text2 = "(" .. consumables[j].amount .. ")", icon = "", displayremoveoption = false }) else table.insert(military, { id = consumabledata.id .. ":" .. macro, text = GetMacroData(macro, "name"), text2 = "(" .. consumables[j].amount .. ")", icon = "", displayremoveoption = false }) end end end end end isinhighway = C.GetContextByClass(dock_menu.currentplayership, "highway", false) ~= 0 end local active = (#civilian > 0) and (not isinhighway) local mouseovertext = "" if #civilian == 0 then mouseovertext = ReadText(1026, 7818) elseif isinhighway then mouseovertext = ReadText(1026, 7845) end row[1]:createDropDown(civilian, { helpOverlayID = "docked_deploy_civ", helpOverlayText = " ", helpOverlayHighlightOnly = true, height = Helper.standardButtonHeight, startOption = "", textOverride = ReadText(1001, 8607), text2Override = " ", bgColor = active and Helper.defaultButtonBackgroundColor or Helper.defaultUnselectableButtonBackgroundColor, highlightColor = active and Helper.defaultButtonHighlightColor or Helper.defaultUnselectableButtonHighlightColor, mouseOverText = mouseovertext, }):setTextProperties(active and config.activeButtonTextProperties or config.inactiveButtonTextProperties):setText2Properties(active and config.activeButtonTextProperties or config.inactiveButtonTextProperties) -- Deploy Civilian row[1].properties.text2.halign = "right" row[1].properties.text2.x = Helper.standardTextOffsetx if active then row[1].handlers.onDropDownConfirmed = dock_menu.dropdownDeploy end local active = (#military > 0) and (not isinhighway) local mouseovertext = "" if #military == 0 then mouseovertext = ReadText(1026, 7819) elseif isinhighway then mouseovertext = ReadText(1026, 7845) end row[7]:createDropDown(military, { helpOverlayID = "docked_deploy_mil", helpOverlayText = " ", helpOverlayHighlightOnly = true, height = Helper.standardButtonHeight, startOption = "", textOverride = ReadText(1001, 8608), text2Override = " ", bgColor = active and Helper.defaultButtonBackgroundColor or Helper.defaultUnselectableButtonBackgroundColor, highlightColor = active and Helper.defaultButtonHighlightColor or Helper.defaultUnselectableButtonHighlightColor, mouseOverText = mouseovertext, }):setTextProperties(active and config.activeButtonTextProperties or config.inactiveButtonTextProperties):setText2Properties(active and config.activeButtonTextProperties or config.inactiveButtonTextProperties) -- Deploy Military row[7].properties.text2.halign = "right" row[7].properties.text2.x = Helper.standardTextOffsetx if active then row[7].handlers.onDropDownConfirmed = dock_menu.dropdownDeploy end local row = table_header:addRow("buttonRow2", { bgColor = Helper.color.transparent, fixed = true }) local active = (dock_menu.currentplayership ~= 0) and C.HasShipFlightAssist(dock_menu.currentplayership) row[1]:createButton(active and { mouseOverText = GetLocalizedKeyName("action", 221), helpOverlayID = "docked_flightassist", helpOverlayText = " ", helpOverlayHighlightOnly = true } or config.inactiveButtonProperties):setText(ReadText(1001, 8604), active and config.activeButtonTextProperties or config.inactiveButtonTextProperties) -- "Flight Assist" if active then row[1].handlers.onClick = dock_menu.buttonFlightAssist end row[2]:createButton({ bgColor = dock_menu.dockButtonBGColor, highlightColor = dock_menu.dockButtonHighlightColor, helpOverlayID = "docked_dock", helpOverlayText = " ", helpOverlayHighlightOnly = true }):setText(ReadText(1001, 8605), { halign = "center", color = dock_menu.dockButtonTextColor }) -- "Dock" row[2].properties.mouseOverText = GetLocalizedKeyName("action", 175) row[2].handlers.onClick = dock_menu.buttonDock local active = (dock_menu.currentplayership ~= 0) and C.ToggleAutoPilot(true) row[7]:createButton(active and { mouseOverText = GetLocalizedKeyName("action", 179), helpOverlayID = "docked_autopilot", helpOverlayText = " ", helpOverlayHighlightOnly = true } or config.inactiveButtonProperties):setText(ReadText(1001, 8603), active and config.activeButtonTextProperties or config.inactiveButtonTextProperties) -- "Autopilot" if active then row[7].handlers.onClick = dock_menu.buttonAutoPilot end if dock_menu.currentplayership ~= 0 then local weapons = {} local numslots = tonumber(C.GetNumUpgradeSlots(dock_menu.currentplayership, "", "weapon")) for j = 1, numslots do local current = C.GetUpgradeSlotCurrentComponent(dock_menu.currentplayership, "weapon", j) if current ~= 0 then table.insert(weapons, current) end end local pilot = GetComponentData(dock_menu.currentplayership, "assignedpilot") dock_menu.currentammo = {} if #weapons > 0 then table_header:addEmptyRow(yoffset) local titlerow = table_header:addRow(false, { bgColor = Helper.color.transparent }) titlerow[1]:setColSpan(11):createText(ReadText(1001, 9409), Helper.headerRowCenteredProperties) titlerow[1].properties.helpOverlayID = "docked_weaponconfig" titlerow[1].properties.helpOverlayText = " " titlerow[1].properties.helpOverlayHeight = titlerow:getHeight() titlerow[1].properties.helpOverlayHighlightOnly = true titlerow[1].properties.helpOverlayScaling = false local row = table_header:addRow(false, { bgColor = Helper.color.unselectable }) row[2]:createText(ReadText(1001, 9410), { font = Helper.standardFontBold, halign = "center" }) row[7]:createText(ReadText(1001, 9411), { font = Helper.standardFontBold, halign = "center" }) titlerow[1].properties.helpOverlayHeight = titlerow[1].properties.helpOverlayHeight + row:getHeight() + Helper.borderSize -- active weapon groups local row = table_header:addRow("weaponconfig_active", { bgColor = Helper.color.transparent }) row[1]:setColSpan(2):createText(ReadText(1001, 11218)) row[7]:setColSpan(1) for j = 1, 4 do row[2 + j]:createCheckBox(function () return C.GetDefensibleActiveWeaponGroup(dock_menu.currentplayership, true) == j end, { width = Helper.standardTextHeight, height = Helper.standardTextHeight, symbol = "arrow", bgColor = function () return dock_menu.checkboxWeaponGroupColor(j, true) end }) row[2 + j].handlers.onClick = function () C.SetDefensibleActiveWeaponGroup(dock_menu.currentplayership, true, j) end end for j = 1, 4 do row[7 + j]:createCheckBox(function () return C.GetDefensibleActiveWeaponGroup(dock_menu.currentplayership, false) == j end, { width = Helper.standardTextHeight, height = Helper.standardTextHeight, symbol = "arrow", bgColor = function () return dock_menu.checkboxWeaponGroupColor(j, false) end }) row[7 + j].handlers.onClick = function () C.SetDefensibleActiveWeaponGroup(dock_menu.currentplayership, false, j) end end table_header:addEmptyRow(Helper.standardTextHeight / 2) for _, weapon in ipairs(weapons) do local numweapongroups = C.GetNumWeaponGroupsByWeapon(dock_menu.currentplayership, weapon) local rawweapongroups = ffi.new("UIWeaponGroup[?]", numweapongroups) numweapongroups = C.GetWeaponGroupsByWeapon(rawweapongroups, numweapongroups, dock_menu.currentplayership, weapon) local uiweapongroups = { primary = {}, secondary = {} } for j = 0, numweapongroups-1 do if rawweapongroups[j].primary then uiweapongroups.primary[rawweapongroups[j].idx] = true else uiweapongroups.secondary[rawweapongroups[j].idx] = true end end local row = table_header:addRow("weaponconfig", { bgColor = Helper.color.transparent }) row[1]:setColSpan(2):createText(ffi.string(C.GetComponentName(weapon))) row[7]:setColSpan(1) for j = 1, 4 do row[2 + j]:createCheckBox(uiweapongroups.primary[j], { width = Helper.standardTextHeight, height = Helper.standardTextHeight, bgColor = function () return dock_menu.checkboxWeaponGroupColor(j, true) end }) row[2 + j].handlers.onClick = function() dock_menu.checkboxWeaponGroup(dock_menu.currentplayership, weapon, true, j, not uiweapongroups.primary[j]) end end for j = 1, 4 do row[7 + j]:createCheckBox(uiweapongroups.secondary[j], { width = Helper.standardTextHeight, height = Helper.standardTextHeight, bgColor = function () return dock_menu.checkboxWeaponGroupColor(j, false) end }) row[7 + j].handlers.onClick = function() dock_menu.checkboxWeaponGroup(dock_menu.currentplayership, weapon, false, j, not uiweapongroups.secondary[j]) end end titlerow[1].properties.helpOverlayHeight = titlerow[1].properties.helpOverlayHeight + row:getHeight() + Helper.borderSize if C.IsComponentClass(weapon, "missilelauncher") then local nummissiletypes = C.GetNumAllMissiles(dock_menu.currentplayership) local missilestoragetable = ffi.new("AmmoData[?]", nummissiletypes) nummissiletypes = C.GetAllMissiles(missilestoragetable, nummissiletypes, dock_menu.currentplayership) local weaponmacro = GetComponentData(ConvertStringTo64Bit(tostring(weapon)), "macro") local dropdowndata = {} for j = 0, nummissiletypes-1 do local ammomacro = ffi.string(missilestoragetable[j].macro) if C.IsAmmoMacroCompatible(weaponmacro, ammomacro) then table.insert(dropdowndata, {id = ammomacro, text = GetMacroData(ammomacro, "name"), icon = "", displayremoveoption = false}) end end -- if the ship has no compatible ammunition in ammo storage, have the dropdown print "Out of ammo" and make it inactive. dock_menu.currentammo[tostring(weapon)] = "empty" local dropdownactive = true if #dropdowndata == 0 then dropdownactive = false table.insert(dropdowndata, {id = "empty", text = ReadText(1001, 9412), icon = "", displayremoveoption = false}) -- Out of ammo else -- NB: currentammomacro can be null dock_menu.currentammo[tostring(weapon)] = ffi.string(C.GetCurrentAmmoOfWeapon(weapon)) end local row = table_header:addRow("ammo_config", { bgColor = Helper.color.transparent }) row[1]:createText(" " .. ReadText(1001, 2800) .. ReadText(1001, 120)) -- Ammunition, : row[2]:setColSpan(10):createDropDown(dropdowndata, { startOption = function () return dock_menu.getDropDownOption(weapon) end, active = dropdownactive }) row[2].handlers.onDropDownConfirmed = function(_, newammomacro) C.SetAmmoOfWeapon(weapon, newammomacro) end titlerow[1].properties.helpOverlayHeight = titlerow[1].properties.helpOverlayHeight + row:getHeight() + Helper.borderSize elseif pilot and C.IsComponentClass(weapon, "bomblauncher") then local pilot64 = ConvertIDTo64Bit(pilot) local numbombtypes = C.GetNumAllInventoryBombs(pilot64) local bombstoragetable = ffi.new("AmmoData[?]", numbombtypes) numbombtypes = C.GetAllInventoryBombs(bombstoragetable, numbombtypes, pilot64) local weaponmacro = GetComponentData(ConvertStringTo64Bit(tostring(weapon)), "macro") local dropdowndata = {} for j = 0, numbombtypes-1 do local ammomacro = ffi.string(bombstoragetable[j].macro) if C.IsAmmoMacroCompatible(weaponmacro, ammomacro) then table.insert(dropdowndata, { id = ammomacro, text = GetMacroData(ammomacro, "name"), icon = "", displayremoveoption = false }) end end -- if the ship has no compatible ammunition in ammo storage, have the dropdown print "Out of ammo" and make it inactive. dock_menu.currentammo[tostring(weapon)] = "empty" local dropdownactive = true if #dropdowndata == 0 then dropdownactive = false table.insert(dropdowndata, { id = "empty", text = ReadText(1001, 9412), icon = "", displayremoveoption = false }) -- Out of ammo else -- NB: currentammomacro can be null dock_menu.currentammo[tostring(weapon)] = ffi.string(C.GetCurrentAmmoOfWeapon(weapon)) end local row = table_header:addRow("ammo_config", { bgColor = Helper.color.transparent }) row[1]:createText(" " .. ReadText(1001, 2800) .. ReadText(1001, 120)) -- Ammunition, : row[2]:setColSpan(10):createDropDown(dropdowndata, { startOption = function () return dock_menu.getDropDownOption(weapon) end, active = dropdownactive }) row[2].handlers.onDropDownConfirmed = function(_, newammomacro) C.SetAmmoOfWeapon(weapon, newammomacro) end titlerow[1].properties.helpOverlayHeight = titlerow[1].properties.helpOverlayHeight + row:getHeight() + Helper.borderSize end end end dock_menu.turrets = {} local numslots = tonumber(C.GetNumUpgradeSlots(dock_menu.currentplayership, "", "turret")) for j = 1, numslots do local groupinfo = C.GetUpgradeSlotGroup(dock_menu.currentplayership, "", "turret", j) if (ffi.string(groupinfo.path) == "..") and (ffi.string(groupinfo.group) == "") then local current = C.GetUpgradeSlotCurrentComponent(dock_menu.currentplayership, "turret", j) if current ~= 0 then table.insert(dock_menu.turrets, current) end end end dock_menu.turretgroups = {} local n = C.GetNumUpgradeGroups(dock_menu.currentplayership, "") local buf = ffi.new("UpgradeGroup2[?]", n) n = C.GetUpgradeGroups2(buf, n, dock_menu.currentplayership, "") for i = 0, n - 1 do if (ffi.string(buf[i].path) ~= "..") or (ffi.string(buf[i].group) ~= "") then local group = { context = buf[i].contextid, path = ffi.string(buf[i].path), group = ffi.string(buf[i].group) } local groupinfo = C.GetUpgradeGroupInfo2(dock_menu.currentplayership, "", group.context, group.path, group.group, "turret") if (groupinfo.count > 0) then group.operational = groupinfo.operational group.currentmacro = ffi.string(groupinfo.currentmacro) group.slotsize = ffi.string(groupinfo.slotsize) table.insert(dock_menu.turretgroups, group) end end end if (#dock_menu.turrets > 0) or (#dock_menu.turretgroups > 0) then table_header:addEmptyRow(yoffset) local row = table_header:addRow(false, { bgColor = Helper.color.transparent }) row[1]:setColSpan(11):createText(ReadText(1001, 8612), Helper.headerRowCenteredProperties) local row = table_header:addRow(false, { bgColor = Helper.color.unselectable }) row[2]:createText(ReadText(1001, 8620), { font = Helper.standardFontBold, halign = "center" }) row[7]:createText(ReadText(1001, 12), { font = Helper.standardFontBold, halign = "center" }) local pilotentityid = GetControlEntity(dock_menu.currentplayership) local row = table_header:addRow("turret_config", { bgColor = Helper.color.transparent }) row[1]:createText(ReadText(1001, 2963)) row[2]:setColSpan(5):createDropDown(config.turretmodesexpanded, { startOption = function () local startoption = dock_menu.getDropDownTurretModeOption(dock_menu.currentplayership, "all") if GetNPCBlackboard(pilotentityid, "$SubTargetPref") ~= "" and GetNPCBlackboard(pilotentityid, "$SubTargetPref") then startoption = GetNPCBlackboard(pilotentityid, "$SubTargetPref") end return startoption end, helpOverlayID = "docked_turretconfig_modes", helpOverlayText = " ", helpOverlayHighlightOnly = true }) row[2].handlers.onDropDownConfirmed = function(_, newturretmode) if config.turretmode_t[newturretmode] then AddUITriggeredEvent("WeaponModeChanged", "onWeaponModeSelected", newturretmode) SetNPCBlackboard(pilotentityid, "$SubTargetPref", newturretmode) elseif newturretmode == "targetsubclear" then dock_menu.noupdate = false AddUITriggeredEvent("WeaponModeChanged", "onWeaponModeSelected", newturretmode) SetNPCBlackboard(pilotentityid, "$SubTargetPref", "") else dock_menu.noupdate = false C.SetAllTurretModes(dock_menu.currentplayership, newturretmode) end end row[7]:setColSpan(5):createButton({ helpOverlayID = "docked_turretconfig_arm", helpOverlayText = " ", helpOverlayHighlightOnly = true }):setText(function () return dock_menu.areTurretsArmed(dock_menu.currentplayership) and ReadText(1001, 8631) or ReadText(1001, 8632) end, { halign = "center" }) row[7].handlers.onClick = function () return C.SetAllTurretsArmed(dock_menu.currentplayership, not dock_menu.areTurretsArmed(dock_menu.currentplayership)) end local turretscounter = 0 for i, turret in ipairs(dock_menu.turrets) do local row = table_header:addRow("turret_config", { bgColor = Helper.color.transparent }) turretscounter = turretscounter + 1 local turretname = ffi.string(C.GetComponentName(turret)) local mouseovertext = "" local textwidth = C.GetTextWidth(turretname, Helper.standardFont, Helper.scaleFont(Helper.standardFont, Helper.standardFontSize)) + Helper.scaleX(Helper.standardTextOffsetx) if (textwidth > row[1]:getWidth()) then mouseovertext = turretname end row[1]:createText(turretname, { mouseOverText = mouseovertext }) row[2]:setColSpan(5):createDropDown(config.turretmodes, { startOption = function () return dock_menu.getDropDownTurretModeOption(turret) end, helpOverlayID = "docked_turrets_modes".. turretscounter, helpOverlayText = " ", helpOverlayHighlightOnly = true }) row[2].handlers.onDropDownConfirmed = function(_, newturretmode) C.SetWeaponMode(turret, newturretmode) end row[7]:setColSpan(5):createButton({helpOverlayID = "docked_turrets_arm" .. turretscounter, helpOverlayText = " ", helpOverlayHighlightOnly = true }):setText(function () return C.IsWeaponArmed(turret) and ReadText(1001, 8631) or ReadText(1001, 8632) end, { halign = "center" }) row[7].handlers.onClick = function () return C.SetWeaponArmed(turret, not C.IsWeaponArmed(turret)) end end local turretgroupscounter = 0 for i, group in ipairs(dock_menu.turretgroups) do local row = table_header:addRow("turret_config", { bgColor = Helper.color.transparent }) turretgroupscounter = turretgroupscounter + 1 local groupname = ReadText(1001, 8023) .. " " .. i .. ((group.currentmacro ~= "") and (" (" .. dock_menu.getSlotSizeText(group.slotsize) .. " " .. GetMacroData(group.currentmacro, "shortname") .. ")") or "") local mouseovertext = "" local textwidth = C.GetTextWidth(groupname, Helper.standardFont, Helper.scaleFont(Helper.standardFont, Helper.standardFontSize)) + Helper.scaleX(Helper.standardTextOffsetx) if (textwidth > row[1]:getWidth()) then mouseovertext = groupname end row[1]:createText(groupname, { color = (group.operational > 0) and Helper.color.white or Helper.color.red, mouseOverText = mouseovertext }) row[2]:setColSpan(5):createDropDown(config.turretmodes, { startOption = function () return dock_menu.getDropDownTurretModeOption(dock_menu.currentplayership, group.context, group.path, group.group) end, active = group.operational > 0, helpOverlayID = "docked_turretgroups_modes".. turretgroupscounter, helpOverlayText = " ", helpOverlayHighlightOnly = true }) row[2].handlers.onDropDownConfirmed = function(_, newturretmode) C.SetTurretGroupMode2(dock_menu.currentplayership, group.context, group.path, group.group, newturretmode) end row[7]:setColSpan(5):createButton({ helpOverlayID = "docked_turretgroups_arm" .. turretgroupscounter, helpOverlayText = " ", helpOverlayHighlightOnly = true }):setText(function () return C.IsTurretGroupArmed(dock_menu.currentplayership, group.context, group.path, group.group) and ReadText(1001, 8631) or ReadText(1001, 8632) end, { halign = "center" }) row[7].handlers.onClick = function () return C.SetTurretGroupArmed(dock_menu.currentplayership, group.context, group.path, group.group, not C.IsTurretGroupArmed(dock_menu.currentplayership, group.context, group.path, group.group)) end end end dock_menu.drones = {} for _, dronetype in ipairs(config.dronetypes) do if C.GetNumStoredUnits(dock_menu.currentplayership, dronetype.id, false) > 0 then local entry = { type = dronetype.id, name = dronetype.name, current = ffi.string(C.GetCurrentDroneMode(dock_menu.currentplayership, dronetype.id)), modes = {}, } local n = C.GetNumDroneModes(dock_menu.currentplayership, dronetype.id) local buf = ffi.new("DroneModeInfo[?]", n) n = C.GetDroneModes(buf, n, dock_menu.currentplayership, dronetype.id) for i = 0, n - 1 do local id = ffi.string(buf[i].id) if (id ~= "trade") or (id == entry.current) then table.insert(entry.modes, { id = id, text = ffi.string(buf[i].name), icon = "", displayremoveoption = false }) end end table.insert(dock_menu.drones, entry) end end if #dock_menu.drones > 0 then table_header:addEmptyRow(yoffset) local row = table_header:addRow(false, { bgColor = Helper.color.transparent }) row[1]:setColSpan(11):createText(ReadText(1001, 8619), Helper.headerRowCenteredProperties) local row = table_header:addRow(false, { bgColor = Helper.color.unselectable }) row[2]:createText(ReadText(1001, 8620), { font = Helper.standardFontBold, halign = "center" }) row[7]:createText(ReadText(1001, 12), { font = Helper.standardFontBold, halign = "center" }) for _, entry in ipairs(dock_menu.drones) do local isblocked = C.IsDroneTypeBlocked(dock_menu.currentplayership, entry.type) local row = table_header:addRow("drone_config", { bgColor = Helper.color.transparent }) row[1]:createText(function () return entry.name .. " (" .. (C.IsDroneTypeArmed(dock_menu.currentplayership, entry.type) and (C.GetNumUnavailableUnits(dock_menu.currentplayership, entry.type) .. "/") or "") .. C.GetNumStoredUnits(dock_menu.currentplayership, entry.type, false) ..")" end, { color = isblocked and Helper.color.warningorange or nil }) row[2]:setColSpan(5):createDropDown(entry.modes, { startOption = function () return ffi.string(C.GetCurrentDroneMode(dock_menu.currentplayership, entry.type)) end, active = not isblocked }) row[2].handlers.onDropDownConfirmed = function (_, newdronemode) C.SetDroneMode(dock_menu.currentplayership, entry.type, newdronemode) end row[7]:setColSpan(5):createButton({ active = not isblocked }):setText(function () return C.IsDroneTypeArmed(dock_menu.currentplayership, entry.type) and ReadText(1001, 8622) or ReadText(1001, 8623) end, { halign = "center" }) row[7].handlers.onClick = function () return C.SetDroneTypeArmed(dock_menu.currentplayership, entry.type, not C.IsDroneTypeArmed(dock_menu.currentplayership, entry.type)) end row[7].properties.helpOverlayID = "docked_drones_" .. entry.type row[7].properties.helpOverlayText = " " row[7].properties.helpOverlayHighlightOnly = true end end -- subordinates local subordinates = GetSubordinates(dock_menu.currentplayership) local groups = {} local usedassignments = {} for _, subordinate in ipairs(subordinates) do local purpose, shiptype = GetComponentData(subordinate, "primarypurpose", "shiptype") local group = GetComponentData(subordinate, "subordinategroup") if group and group > 0 then if groups[group] then table.insert(groups[group].subordinates, subordinate) if shiptype == "resupplier" then groups[group].numassignableresupplyships = groups[group].numassignableresupplyships + 1 end if purpose == "mine" then groups[group].numassignableminingships = groups[group].numassignableminingships + 1 end else local assignment = ffi.string(C.GetSubordinateGroupAssignment(dock_menu.currentplayership, group)) usedassignments[assignment] = i groups[group] = { assignment = assignment, subordinates = { subordinate }, numassignableresupplyships = (shiptype == "resupplier") and 1 or 0, numassignableminingships = (purpose == "mine") and 1 or 0 } end end end if #subordinates > 0 then table_header:addEmptyRow(yoffset) local row = table_header:addRow(false, { bgColor = Helper.color.transparent }) row[1]:setColSpan(11):createText(ReadText(1001, 8626), Helper.headerRowCenteredProperties) local row = table_header:addRow(false, { bgColor = Helper.color.unselectable }) row[1]:createText(ReadText(1001, 8627), { font = Helper.standardFontBold, halign = "center" }) row[2]:createText(ReadText(1001, 8373), { font = Helper.standardFontBold, halign = "center" }) row[7]:createText(ReadText(1001, 8628), { font = Helper.standardFontBold, halign = "center" }) for i = 1, 10 do if groups[i] then local supplyactive = (groups[i].numassignableresupplyships == #groups[i].subordinates) and ((not usedassignments["supplyfleet"]) or (usedassignments["supplyfleet"] == i)) local subordinateassignments = { [1] = { id = "defence", text = ReadText(20208, 40301), icon = "", displayremoveoption = false }, [2] = { id = "supplyfleet", text = ReadText(20208, 40701), icon = "", displayremoveoption = false, active = supplyactive, mouseovertext = supplyactive and "" or ReadText(1026, 8601) }, } if C.IsComponentClass(dock_menu.currentplayership, "station") then local miningactive = (groups[i].numassignableminingships == #groups[i].subordinates) and ((not usedassignments["mining"]) or (usedassignments["mining"] == i)) table.insert(subordinateassignments, { id = "mining", text = ReadText(20208, 40201), icon = "", displayremoveoption = false, active = miningactive, mouseovertext = miningactive and "" or ReadText(1026, 8602) }) local tradeactive = (not usedassignments["trade"]) or (usedassignments["trade"] == i) table.insert(subordinateassignments, { id = "trade", text = ReadText(20208, 40101), icon = "", displayremoveoption = false, active = tradeactive, mouseovertext = tradeactive and ((groups[i].numassignableminingships > 0) and (Helper.convertColorToText(Helper.color.warningorange) .. ReadText(1026, 8607)) or "") or ReadText(1026, 7840) }) local tradeforbuildstorageactive = (groups[i].numassignableminingships == 0) and ((not usedassignments["tradeforbuildstorage"]) or (usedassignments["tradeforbuildstorage"] == i)) table.insert(subordinateassignments, { id = "tradeforbuildstorage", text = ReadText(20208, 40801), icon = "", displayremoveoption = false, active = tradeforbuildstorageactive, mouseovertext = tradeforbuildstorageactive and "" or ReadText(1026, 8603) }) elseif C.IsComponentClass(dock_menu.currentplayership, "ship") then table.insert(subordinateassignments, { id = "attack", text = ReadText(20208, 40901), icon = "", displayremoveoption = false }) table.insert(subordinateassignments, { id = "interception", text = ReadText(20208, 41001), icon = "", displayremoveoption = false }) table.insert(subordinateassignments, { id = "follow", text = ReadText(20208, 41301), icon = "", displayremoveoption = false }) local active = true local mouseovertext = "" local buf = ffi.new("Order") if not C.GetDefaultOrder(buf, dock_menu.currentplayership) then active = false mouseovertext = ReadText(1026, 8606) end table.insert(subordinateassignments, { id = "assist", text = ReadText(20208, 41201), icon = "", displayremoveoption = false, active = active, mouseovertext = mouseovertext }) if GetComponentData(dock_menu.currentplayership, "shiptype") == "resupplier" then table.insert(subordinateassignments, { id = "trade", text = ReadText(20208, 40101), icon = "", displayremoveoption = false }) end end local isdockingpossible = false for _, subordinate in ipairs(groups[i].subordinates) do if IsDockingPossible(subordinate, dock_menu.currentplayership) then isdockingpossible = true break end end local active = true local mouseovertext = "" if not GetComponentData(dock_menu.currentplayership, "hasshipdockingbays") then active = false mouseovertext = ReadText(1026, 8604) elseif not isdockingpossible then active = false mouseovertext = ReadText(1026, 8605) end local row = table_header:addRow("subordinate_config", { bgColor = Helper.color.transparent }) row[1]:createText(function () dock_menu.updateSubordinateGroupInfo(); return ReadText(20401, i) .. (dock_menu.subordinategroups[i] and (" (" .. ((not C.ShouldSubordinateGroupDockAtCommander(dock_menu.currentplayership, i)) and ((#dock_menu.subordinategroups[i].subordinates - dock_menu.subordinategroups[i].numdockedatcommander) .. "/") or "") .. #dock_menu.subordinategroups[i].subordinates ..")") or "") end, { color = isblocked and Helper.color.warningorange or nil }) row[2]:setColSpan(5):createDropDown(subordinateassignments, { startOption = function () dock_menu.updateSubordinateGroupInfo(); return dock_menu.subordinategroups[i] and dock_menu.subordinategroups[i].assignment or "" end }) row[2].handlers.onDropDownConfirmed = function (_, newassignment) C.SetSubordinateGroupAssignment(dock_menu.currentplayership, i, newassignment) end row[7]:setColSpan(5):createButton({ active = active, mouseOverText = mouseovertext }):setText(function () return C.ShouldSubordinateGroupDockAtCommander(dock_menu.currentplayership, i) and ReadText(1001, 8630) or ReadText(1001, 8629) end, { halign = "center" }) row[7].handlers.onClick = function () return C.SetSubordinateGroupDockAtCommander(dock_menu.currentplayership, i, not C.ShouldSubordinateGroupDockAtCommander(dock_menu.currentplayership, i)) end end end end end else local row = table_header:addRow("buttonRow1", { bgColor = Helper.color.transparent, fixed = true }) local active = canwareexchange row[1]:createButton(active and {helpOverlayID = "docked_transferwares", helpOverlayText = " ", helpOverlayHighlightOnly = true } or config.inactiveButtonProperties):setText(ReadText(1001, 8618), active and config.activeButtonTextProperties or config.inactiveButtonTextProperties) -- "Transfer Wares" if active then row[1].handlers.onClick = function() return dock_menu.buttonTrade(true) end end local active = dock_menu.currentplayership ~= 0 row[2]:createButton(active and { mouseOverText = GetLocalizedKeyName("action", 277), helpOverlayID = "docked_getup", helpOverlayText = " ", helpOverlayHighlightOnly = true } or config.inactiveButtonProperties):setText(ReadText(1002, 20014), active and config.activeButtonTextProperties or config.inactiveButtonTextProperties) -- "Get Up" row[2].handlers.onClick = dock_menu.buttonGetUp local active = dock_menu.currentplayership ~= 0 row[7]:createButton(active and { mouseOverText = GetLocalizedKeyName("action", 316), helpOverlayID = "docked_shipinfo", helpOverlayText = " ", helpOverlayHighlightOnly = true } or config.inactiveButtonProperties):setText(ReadText(1001, 8602), active and config.activeButtonTextProperties or config.inactiveButtonTextProperties) -- "Ship Information" if active then row[7].handlers.onClick = dock_menu.buttonDockedShipInfo end local row = table_header:addRow("buttonRow2", { bgColor = Helper.color.transparent, fixed = true }) local active = canbuyship row[1]:createButton(active and {helpOverlayID = "docked_buyships", helpOverlayText = " ", helpOverlayHighlightOnly = true } or config.inactiveButtonProperties):setText(ReadText(1002, 8008), active and config.activeButtonTextProperties or config.inactiveButtonTextProperties) -- "Buy Ships" if active then row[1].handlers.onClick = dock_menu.buttonBuyShip end local active = cantrade row[2]:createButton(active and {helpOverlayID = "docked_trade", helpOverlayText = " ", helpOverlayHighlightOnly = true } or config.inactiveButtonProperties):setText(ReadText(1002, 9005), active and config.activeButtonTextProperties or config.inactiveButtonTextProperties) -- "Trade" if active then row[2].handlers.onClick = function() return dock_menu.buttonTrade(false) end end local active = canmodifyship row[7]:createButton(active and {helpOverlayID = "docked_upgrade_repair", helpOverlayText = " ", helpOverlayHighlightOnly = true } or config.inactiveButtonProperties):setText(issupplyship and ReadText(1001, 7877) or ReadText(1001, 7841), active and config.activeButtonTextProperties or config.inactiveButtonTextProperties) -- Upgrade / Repair Ship if dockedplayerships[1] and (not canequip) then row[7].properties.mouseOverText = (C.IsComponentClass(dockedplayerships[1], "ship_l") or C.IsComponentClass(dockedplayerships[1], "ship_xl")) and ReadText(1026, 7807) or ReadText(1026, 7806) elseif not isdock then row[7].properties.mouseOverText = ReadText(1026, 8014) end if active then row[7].handlers.onClick = dock_menu.buttonModifyShip end local row = table_header:addRow("buttonRow3", { bgColor = Helper.color.transparent, fixed = true }) row[1]:createButton(config.inactiveButtonProperties):setText("", config.inactiveButtonTextProperties) -- dummy if dock_menu.currentplayership ~= 0 then row[2]:createButton({ mouseOverText = GetLocalizedKeyName("action", 175), bgColor = dock_menu.undockButtonBGColor, highlightColor = dock_menu.undockButtonHighlightColor, helpOverlayID = "docked_undock", helpOverlayText = " ", helpOverlayHighlightOnly = true }):setText(ReadText(1002, 20013), { halign = "center", color = dock_menu.undockButtonTextColor }) -- "Undock" row[2].handlers.onClick = dock_menu.buttonUndock else row[2]:createButton({ mouseOverText = GetLocalizedKeyName("action", 175), helpOverlayID = "docked_gotoship", helpOverlayText = " ", helpOverlayHighlightOnly = true }):setText(ReadText(1001, 7305), { halign = "center" }) -- "Go to Ship" row[2].handlers.onClick = dock_menu.buttonGoToShip end row[7]:createButton(config.inactiveButtonProperties):setText("", config.inactiveButtonTextProperties) -- dummy local row = table_header:addRow(false, { bgColor = Helper.color.transparent, fixed = true }) row[1]:setColSpan(11):createBoxText(dock_menu.infoText, { halign = "center", color = Helper.color.warningorange, boxColor = dock_menu.infoBoxColor }) end if dock_menu.table_header then table_header:setTopRow(GetTopRow(dock_menu.table_header)) table_header:setSelectedRow(dock_menu.selectedRows.header or Helper.currentTableRow[dock_menu.table_header]) table_header:setSelectedCol(dock_menu.selectedCols.header or Helper.currentTableCol[dock_menu.table_header] or 0) else table_header:setSelectedRow(dock_menu.selectedRows.header) table_header:setSelectedCol(dock_menu.selectedCols.header or 0) end dock_menu.selectedRows.header = nil dock_menu.selectedCols.header = nil table_header.properties.maxVisibleHeight = Helper.viewHeight - table_header.properties.y - Helper.frameBorder dock_menu.frame.properties.height = math.min(Helper.viewHeight, table_header:getVisibleHeight() + table_header.properties.y + Helper.scaleY(Helper.standardButtonHeight)) -- display view/frame dock_menu.frame:display() end init()
function onCreate() makeAnimatedLuaSprite('Trall_Back', 'Trall_Back', -800, -190); scaleObject('Trall_Back', 5.3, 5.3) addAnimationByPrefix('Trall_Back', 'Trall_Back', 'Trall_Back', 24, true); objectPlayAnimation('Trall_Back', 'Trall_Back', true) addLuaSprite('Trall_Back', false); makeLuaSprite('Trall_girl', 'Trall_girl', -500, -160); addLuaSprite('Trall_girl', false); doTweenAngle('Trall_girl', 'Trall_girl' , 40000 , 222, circInOut); scaleObject('Trall_girl', 1, 1) makeLuaSprite('Trall_girl2', 'Trall_girl2', 1200, -160); addLuaSprite('Trall_girl2', false); doTweenAngle('Trall_girl2', 'Trall_girl2' , 40000 , 222, circInOut); scaleObject('Trall_girl2', 1, 1) makeAnimatedLuaSprite('stupidclown', 'stupidclown', 90, 255); addAnimationByPrefix('stupidclown', 'stupidclown', 'stupidclown', 24, true); objectPlayAnimation('stupidclown', 'stupidclown', true) addLuaSprite('stupidclown', false); makeAnimatedLuaSprite('stupiderp', 'stupiderp', -250, 255); scaleObject('stupiderp', 1, 1) addAnimationByPrefix('stupiderp', 'stupiderp', 'stupiderp', 24, true); objectPlayAnimation('stupiderp', 'stupiderp', true) addLuaSprite('stupiderp', false); makeAnimatedLuaSprite('stupidsmiler', 'stupidsmiler', -90, 255); scaleObject('stupidsmiler', 1, 1) addAnimationByPrefix('stupidsmiler', 'stupidsmiler', 'stupidsmiler', 24, true); objectPlayAnimation('stupidsmiler', 'stupidsmiler', true) addLuaSprite('stupidsmiler', false); makeAnimatedLuaSprite('stupidstair', 'stupidstair', 260, 255); scaleObject('stupidstair', 1, 1) addAnimationByPrefix('stupidstair', 'stupidstair', 'stupidstair', 24, true); objectPlayAnimation('stupidstair', 'stupidstair', true) addLuaSprite('stupidstair', false); end function onEvent(name,value1,value2) if name == 'Play Animation' then if value1 == 'nadie' then setProperty('stupidclown.visible', false); setProperty('stupiderp.visible', false); setProperty('stupidsmiler.visible', false); setProperty('stupidstair.visible', false); end if value1 == 'clown' then setProperty('stupidclown.visible', true); setProperty('stupiderp.visible', false); setProperty('stupidsmiler.visible', false); setProperty('stupidstair.visible', false); end if value1 == 'derp' then setProperty('stupidclown.visible', false); setProperty('stupiderp.visible', true); setProperty('stupidsmiler.visible', false); setProperty('stupidstair.visible', false); end if value1 == 'smiler' then setProperty('stupidclown.visible', false); setProperty('stupiderp.visible', false); setProperty('stupidsmiler.visible', true); setProperty('stupidstair.visible', false); end if value1 == 'stair' then setProperty('stupidclown.visible', false); setProperty('stupiderp.visible', false); setProperty('stupidsmiler.visible', false); setProperty('stupidstair.visible', true); end if value1 == 'todos' then setProperty('stupidclown.visible', true); setProperty('stupiderp.visible', true); setProperty('stupidsmiler.visible', true); setProperty('stupidstair.visible', true); doTweenAngle('stupidstair', 'stupidstair' , 30000 , 222, circInOut); doTweenAngle('stupidsmiler', 'stupidsmiler' , 30000 , 222, circInOut); doTweenAngle('stupiderp', 'stupiderp' , 30000 , 222, circInOut); doTweenAngle('stupidclown', 'stupidclown' , 30000 , 222, circInOut); doTweenAngle('stupidclow', 'dad' , 30000 , 222, circInOut); doTweenAngle('stupidclownc', 'boyfriend' , 30000 , 222, circInOut); end end end
local PANEL = {} PANEL.last_pos = 0 PANEL.margin = 0 function PANEL:Init() self.VBar.Paint = function() return true end self.VBar.btnUp.Paint = function() return true end self.VBar.btnDown.Paint = function() return true end self.VBar.btnGrip.Paint = function() return true end self:PerformLayout() function self:OnScrollbarAppear() return true end end function PANEL:Paint(width, height) Theme.hook('PaintSidebar', self, width, height) end function PANEL:Clear() self.BaseClass.Clear(self) self.last_pos = 0 end -- 'borrowed' from lua/vgui/dscrollpanel.lua function PANEL:PerformLayout() local old_height = self.pnlCanvas:GetTall() local old_width = self:GetWide() local ypos = 0 self:Rebuild() self.VBar:SetUp(self:GetTall(), self.pnlCanvas:GetTall()) ypos = self.VBar:GetOffset() self.pnlCanvas:SetPos(0, ypos) self.pnlCanvas:SetWide(old_width) self:Rebuild() if old_height != self.pnlCanvas:GetTall() then self.VBar:SetScroll(self.VBar:GetScroll()) end end function PANEL:add_panel(panel, center) local x, y = panel:GetPos() if center then x = self:GetWide() * 0.5 - panel:GetWide() * 0.5 end panel:SetPos(x, self.last_pos) self:AddItem(panel) self.last_pos = self.last_pos + self.margin + panel:GetTall() end function PANEL:add_button(text, callback) local button = vgui.Create('fl_button', self) button:SetSize(self:GetWide(), Theme.get_option('menu_sidebar_height')) button:SetDrawBackground(true) button:SetFont(Theme.get_font('text_normal_smaller')) button:set_text(text) button:set_text_autoposition(true) button.DoClick = function(btn) btn:set_active(true) if IsValid(self.prev_button) and self.prev_button != btn then self.prev_button:set_active(false) end self.prev_button = btn if isfunction(callback) then callback(btn) end end self:add_panel(button) return button end function PANEL:add_space(px) self.last_pos = self.last_pos + px end function PANEL:set_margin(margin) self.margin = tonumber(margin) or 0 end function PANEL:center_items() for k, v in ipairs(self:GetCanvas():GetChildren()) do local x, y = v:GetPos() v:SetPos(self:GetWide() / 2 - v:GetWide() / 2, y) end end vgui.Register('fl_sidebar', PANEL, 'DScrollPanel')
---@class CS.FairyEditor.PackageGroupSettings : CS.FairyEditor.SettingsBase ---@field public groups CS.System.Collections.Generic.List_CS.FairyEditor.PackageGroupSettings.PackageGroup ---@type CS.FairyEditor.PackageGroupSettings CS.FairyEditor.PackageGroupSettings = { } ---@return CS.FairyEditor.PackageGroupSettings ---@param project CS.FairyEditor.FProject function CS.FairyEditor.PackageGroupSettings.New(project) end ---@return CS.FairyEditor.PackageGroupSettings.PackageGroup ---@param name string function CS.FairyEditor.PackageGroupSettings:GetGroup(name) end return CS.FairyEditor.PackageGroupSettings
-- Bench transformation matrix computation for a list of entities. package.path = "src/?.lua;../src/?.lua;"..package.path local mgl = require("MGL") local tvec3 = mgl.require_vec(3) local ents, ticks = ... ents = tonumber(ents) or 1e3 ticks = tonumber(ticks) or 600 local entities = {} for i=1,ents do table.insert(entities, { position = mgl.vec3(math.random(), math.random(), math.random()), rotation = mgl.vec3(math.random(), math.random(), math.random()), scale = mgl.vec3(math.random(), math.random(), math.random()) }) end local ax = mgl.vec3(1,0,0) local ay = mgl.vec3(0,1,0) local az = mgl.vec3(0,0,1) local rad = math.rad local translate = mgl.translate:resolve(tvec3) local rotate = mgl.rotate:resolve(tvec3, "number") local scale = mgl.scale:resolve(tvec3) -- Note: the multiplication may also be pre-resolved to slightly increase performances, but is avoided here for readability. for i=1,ticks do for _, ent in ipairs(entities) do ent.transform = translate(ent.position) -- * rotate(ax, rad(ent.rotation.x)) * rotate(ay, rad(ent.rotation.y)) * rotate(az, rad(ent.rotation.z)) * scale(ent.scale) end end
ys = ys or {} slot1 = ys.Battle.BattleUnitEvent ys.Battle.BattleAircraftCharacter = class("BattleAircraftCharacter", ys.Battle.BattleCharacter) ys.Battle.BattleAircraftCharacter.__name = "BattleAircraftCharacter" ys.Battle.BattleAircraftCharacter.Ctor = function (slot0) slot0.super.Ctor(slot0) slot0._hpBarOffset = Vector3(0, 1.6, 0) slot0:SetYShakeMin() slot0:SetYShakeMax() slot0.shadowScale = Vector3.one slot0.shadowPos = Vector3.zero end ys.Battle.BattleAircraftCharacter.SetUnitData = function (slot0, slot1) slot0._unitData = slot1 slot0:AddUnitEvent() end ys.Battle.BattleAircraftCharacter.InitWeapon = function (slot0) slot0._weapon = slot0._unitData:GetWeapon() for slot4, slot5 in ipairs(slot0._weapon) do slot5:RegisterEventListener(slot0, slot0.CREATE_BULLET, slot0.onCreateBullet) end end ys.Battle.BattleAircraftCharacter.GetModleID = function (slot0) return slot0._unitData:GetSkinID() end ys.Battle.BattleAircraftCharacter.GetInitScale = function (slot0) return 1 end ys.Battle.BattleAircraftCharacter.AddUnitEvent = function (slot0) return end ys.Battle.BattleAircraftCharacter.RemoveUnitEvent = function (slot0) for slot4, slot5 in ipairs(slot0._weapon) do slot5:UnregisterEventListener(slot0, slot0.CREATE_BULLET) end if slot0._unitData:GetIFF() == slot1.Battle.BattleConfig.FOE_CODE then slot0._unitData:UnregisterEventListener(slot0, slot0.UPDATE_AIR_CRAFT_HP) end end ys.Battle.BattleAircraftCharacter.PlayAction = function (slot0) return end ys.Battle.BattleAircraftCharacter.Update = function (slot0) slot0:UpdateMatrix() slot0:UpdateDirection() slot0:UpdateUIComponentPosition() slot0:UpdateShadow() slot0:UpdatePosition() if slot0._unitData:GetIFF() == slot0.Battle.BattleConfig.FOE_CODE then slot0:UpdateHPPop() slot0:UpdateHPBarPostition() slot0:UpdateHpBar() end end ys.Battle.BattleAircraftCharacter.UpdatePosition = function (slot0) slot0._tf.localPosition = slot0._unitData:GetPosition() slot0._characterPos = slot0._unitData:GetPosition() end ys.Battle.BattleAircraftCharacter.UpdateDirection = function (slot0) if slot0._unitData:GetCurrentState() ~= slot0._unitData.STATE_CREATE then return end slot1 = slot0._unitData:GetSize() if slot0._unitData:GetDirection() == slot0.Battle.BattleConst.UnitDir.RIGHT then slot0._tf.localScale = Vector3(slot1, slot1, slot1) elseif slot0._unitData:GetDirection() == slot0.Battle.BattleConst.UnitDir.LEFT then slot0._tf.localScale = Vector3(-slot1, slot1, slot1) end end ys.Battle.BattleAircraftCharacter.UpdateHPBarPostition = function (slot0) slot0._hpBarPos:Copy(slot0._referenceVector):Add(slot0._hpBarOffset) slot0._HPBarTf.position = slot0._hpBarPos end ys.Battle.BattleAircraftCharacter.UpdateShadow = function (slot0) if slot0._shadow and slot0._unitData:GetCurrentState() == slot0._unitData.STATE_CREATE then slot1 = slot0._unitData:GetPosition() slot0.shadowScale.z = math.min(4, math.max(2, 4 - (4 * slot1.y) / slot0.Battle.BattleConfig.AircraftHeight)) slot0.shadowScale.x = slot2 slot0._shadowTF.localScale = slot0.shadowScale slot0.shadowPos.z = slot1.z slot0.shadowPos.x = slot1.x slot0._shadowTF.position = slot0.shadowPos end end ys.Battle.BattleAircraftCharacter.GetYShake = function (slot0) slot0._YShakeCurrent = slot0._YShakeCurrent or 0 slot0._YShakeDir = slot0._YShakeDir or 1 slot0._YShakeCurrent = slot0._YShakeCurrent + 0.1 * slot0._YShakeDir if slot0._YShakeMax < slot0._YShakeCurrent and slot0._YShakeDir == 1 then slot0._YShakeDir = -1 slot0:SetYShakeMin() elseif slot0._YShakeCurrent < slot0._YShakeMin and slot0._YShakeDir == -1 then slot0._YShakeDir = 1 slot0:SetYShakeMax() end return slot0._YShakeCurrent end ys.Battle.BattleAircraftCharacter.SetYShakeMin = function (slot0) slot0._YShakeMin = -1 - 2 * math.random() end ys.Battle.BattleAircraftCharacter.SetYShakeMax = function (slot0) slot0._YShakeMax = 1 + 2 * math.random() end ys.Battle.BattleAircraftCharacter.AddModel = function (slot0, slot1) slot0:SetGO(slot1) slot0._hpBarOffset = Vector3(0, slot0._unitData:GetBoxSize().y, 0) slot0:SetBoneList() slot0._tf.position = slot0._unitData:GetPosition() slot0:UpdateMatrix() slot0._unitData:ActiveCldBox() end ys.Battle.BattleAircraftCharacter.AddShadow = function (slot0, slot1) slot0._shadow = slot0:GetTf():Find("model/shadow").gameObject slot0._shadowTF = slot0._shadow.transform end ys.Battle.BattleAircraftCharacter.AddHPBar = function (slot0, slot1) slot0._HPBar = slot1 slot0._HPBarTf = slot1.transform slot0._HPProgress = slot0._HPBarTf:Find("blood"):GetComponent(typeof(Image)) slot1:SetActive(true) slot0._unitData:RegisterEventListener(slot0, slot0.UPDATE_AIR_CRAFT_HP, slot0.OnUpdateHP) slot0:UpdateHpBar() end ys.Battle.BattleAircraftCharacter.updateSomkeFX = function (slot0) return end return
pfDB["zones"]["koKR-tbc"] = { [1] = "던 모로", [3] = "황야의 땅", [4] = "저주받은 땅", [8] = "슬픔의 늪", [10] = "그늘숲", [11] = "저습지", [12] = "엘윈 숲", [14] = "듀로타", [15] = "먼지진흙 습지대", [16] = "아즈샤라", [17] = "불모의 땅", [21] = "쿨 티라스", [22] = "프로그래머의 섬", [25] = "검은바위 산", [28] = "서부 역병지대", [30] = "나인", [33] = "가시덤불 골짜기", [36] = "알터랙 산맥", [38] = "모단 호수", [40] = "서부 몰락지대", [41] = "죽음의 고개", [44] = "붉은마루 산맥", [45] = "아라시 고원", [46] = "불타는 평원", [47] = "동부 내륙지", [51] = "이글거리는 협곡", [55] = "영웅의 계곡 미사용", [65] = "*** 미사용 ***", [66] = "*** 미사용 ***", [67] = "*** 미사용 ***", [85] = "티리스팔 숲", [130] = "은빛소나무 숲", [139] = "동부 역병지대", [141] = "텔드랏실", [148] = "어둠의 해안", [151] = "디자이너의 섬", [170] = "로다미어 호수", [187] = "다르나서스 미사용", [206] = "서부 몰락지대 미사용", [207] = "대해", [208] = "철갑 동굴 미사용", [209] = "그림자송곳니 성채", [210] = "*** 미사용 ***", [214] = "대해", [215] = "멀고어", [267] = "힐스브래드 구릉지", [268] = "아즈샤라 분화구", [269] = "던 알가즈", [276] = "돌다지 고개 미사용", [293] = "소라딘의 성벽", [296] = "남쪽 바다 미사용", [308] = "성난 바다", [330] = "탄돌 교각", [331] = "잿빛 골짜기", [332] = "대해", [357] = "페랄라스", [361] = "악령의 숲", [377] = "분노의 강", [394] = "다로미어 호수 미사용", [395] = "카엘 다로우 미사용", [400] = "버섯구름 봉우리", [405] = "잊혀진 땅", [406] = "돌발톱 산맥", [407] = "오그리마 미사용", [408] = "길리짐의 섬", [409] = "학자 라피디스의 섬", [434] = "악령불 언덕", [440] = "타나리스", [457] = "장막의 바다", [470] = "썬더 블러프 미사용", [474] = "수렵의 봉우리 미사용", [475] = "정기의 봉우리 미사용", [476] = "장로의 봉우리 미사용", [490] = "운고로 분화구", [491] = "가시덩굴 우리", [493] = "달의 숲", [512] = "블랙후프 마을", [616] = "하이잘 산", [618] = "여명의 설원", [676] = "아웃랜드", [696] = "장인의 정원 미사용", [697] = "상인의 정원 미사용", [698] = "신전 정원 미사용", [699] = "엘룬의 신전 미사용", [700] = "세나리온 자치령 미사용", [701] = "전사의 정원 미사용", [717] = "스톰윈드 지하감옥", [718] = "통곡의 동굴", [719] = "검은심연의 나락", [721] = "놈리건", [722] = "가시덩굴 구릉", [796] = "붉은십자군 수도원", [876] = "GM의 안식처", [956] = "신록의 들판", [1118] = "낮은벌 미사용", [1121] = "공포의 섬", [1176] = "줄파락", [1196] = "알카즈 섬 미사용", [1337] = "울다만", [1377] = "실리더스", [1397] = "에메랄드 숲", [1417] = "가라앉은 사원", [1477] = "아탈학카르 신전", [1497] = "언더시티", [1519] = "스톰윈드", [1537] = "아이언포지", [1579] = "죽음의 폐광 002 미사용", [1580] = "철갑 동굴 003 미사용", [1581] = "죽음의 폐광", [1583] = "검은바위 첨탑", [1584] = "검은바위 나락", [1597] = "랩터 서식지 미사용", [1598] = "그롤돔 농장 미사용", [1601] = "검은가시 마루 미사용", [1602] = "가시덩굴 벌판 미사용", [1603] = "아가마고르 미사용", [1637] = "오그리마", [1638] = "썬더 블러프", [1657] = "다르나서스", [1757] = "주홍빛 장막호", [1758] = "격정의 파도호", [1771] = "기만자의 사원", [1817] = "진흙늪 동굴", [1941] = "시간의 동굴", [1977] = "줄구룹", [2017] = "스트라솔름", [2037] = "쿠엘탈라스", [2057] = "스칼로맨스", [2100] = "마라우돈", [2137] = "예언의 웅덩이 미사용", [2159] = "오닉시아의 둥지", [2257] = "깊은굴 지하철", [2259] = "마리스 농장 미사용", [2280] = "스트라솔름 미사용", [2366] = "검은늪", [2367] = "옛 힐스브래드 구릉지", [2437] = "성난불길 협곡", [2557] = "혈투의 전장", [2597] = "알터랙 계곡", [2677] = "검은날개 둥지", [2717] = "화산 심장부", [2777] = "알터랙 계곡 미사용", [2817] = "*** 미사용 ***", [2917] = "전설의 전당", [2918] = "용사의 전당", [3237] = "검투장 미사용", [3277] = "전쟁노래 협곡", [3358] = "아라시 분지", [3428] = "안퀴라즈", [3429] = "안퀴라즈 폐허", [3430] = "영원노래 숲", [3431] = "선스트라이더 섬", [3432] = "다트리마의 제단", [3433] = "유령의 땅", [3434] = "스카라베 정원", [3435] = "장군의 정원", [3436] = "안퀴라즈 저장실", [3437] = "안퀴라즈 부화장", [3438] = "안퀴라즈 둥지", [3439] = "감시자의 정원", [3440] = "스카라베 정원", [3441] = "장군의 정원", [3442] = "안퀴라즈 저장실", [3443] = "안퀴라즈 부화장", [3444] = "안퀴라즈 둥지", [3445] = "감시자의 정원", [3446] = "황혼의 터", [3455] = "북해", [3456] = "낙스라마스", [3457] = "카라잔", [3459] = "도시", [3460] = "황금 해안", [3461] = "해돋이 부두", [3462] = "산들바람 마을", [3463] = "마법학자 관문", [3464] = "원정순찰대 산장", [3465] = "북부 성소", [3466] = "서부 성소", [3467] = "동부 성소", [3468] = "살데릴의 안식처", [3469] = "튜론의 매타조 훈련장", [3470] = "잔잔한 속삭임 연못", [3471] = "생명의 숲", [3472] = "하늘바람 해안", [3473] = "엘렌다르 호수", [3474] = "불타버린 숲", [3475] = "제브와타", [3476] = "토르와타", [3477] = "카라잔 미사용", [3478] = "안퀴라즈 성문", [3479] = "장막의 바다", [3480] = "더스크위더 정원", [3481] = "더스크위더 첨탑", [3482] = "죽음의 흉터", [3483] = "지옥불 반도", [3484] = "태양 첨탑", [3485] = "팔스리엔 마법학회", [3487] = "실버문", [3488] = "트랜퀼리엔", [3489] = "태양왕관 마을", [3490] = "황금안개 마을", [3491] = "윈드러너 마을", [3492] = "윈드러너 첨탑", [3493] = "태양의 성소", [3494] = "달의 성소", [3495] = "돈스타 첨탑", [3496] = "원정순찰대 초소", [3497] = "안다로스", [3498] = "안텔라스", [3499] = "안오윈", [3500] = "데솔름", [3501] = "피투성이 지구라트", [3502] = "울부짖는 지구라트", [3503] = "샬란디스 섬", [3504] = "토릴 영지", [3505] = "미명 광산", [3506] = "안딜리엔 영지", [3507] = "도끼 언덕", [3508] = "아마니 고개", [3509] = "해넘이 봉우리", [3510] = "아마니 지하묘지", [3511] = "저주받은 자의 탑", [3512] = "제브소라", [3513] = "엘렌다르 호수", [3514] = "죽음의 흉터", [3515] = "엘렌다르 강", [3516] = "제브텔라", [3517] = "제브노와", [3518] = "나그란드", [3519] = "테로카르 숲", [3520] = "어둠달 골짜기", [3521] = "장가르 습지대", [3522] = "칼날 산맥", [3523] = "황천의 폭풍", [3524] = "하늘안개 섬", [3525] = "핏빛안개 섬", [3526] = "암멘 골짜기", [3527] = "추락 지점", [3528] = "희망의 호수", [3529] = "다닥나무 숲", [3530] = "어둠 마루", [3531] = "위험한 거리", [3532] = "새벽길", [3533] = "실버문 폐허", [3534] = "페스의 길", [3535] = "지옥불 성채", [3536] = "스랄마", [3537] = "REUSE", [3538] = "명예의 요새", [3539] = "운명의 계단", [3540] = "뒤틀린 황천", [3541] = "멸망의 괴철로 기지", [3542] = "영광의 길", [3543] = "거대한 균열", [3544] = "수정 들판", [3545] = "지옥불 성채", [3546] = "원정대 무기고", [3547] = "킬제덴의 옥좌", [3548] = "분노의 괴철로 기지", [3549] = "파멸자의 침공 거점", [3550] = "보룬 폐허", [3551] = "샤나르 폐허", [3552] = "텔하마트 사원", [3553] = "아고나르의 웅덩이", [3554] = "매의 감시탑", [3555] = "마그하르 거점", [3556] = "하알레쉬 소굴", [3557] = "엑소다르", [3558] = "엘렌다르 폭포", [3559] = "다닥나무 언덕", [3560] = "암멘 들판", [3561] = "신성한 숲", [3562] = "지옥불 성루", [3563] = "지옥불 성채", [3564] = "잿불숲", [3565] = "세나리온 야영지", [3566] = "달날개 소굴", [3567] = "탈출선 착륙지", [3568] = "탈출선 잔해", [3569] = "파도 동굴", [3570] = "성난비늘 거점", [3571] = "뾰족가지 마을", [3572] = "너울소나무 요새", [3573] = "오디시우스의 정박지", [3574] = "발라르의 나루", [3575] = "개펄 해안", [3576] = "하늘 감시초소", [3577] = "기즐의 야영지", [3578] = "화물선 잔해", [3579] = "배신자의 만", [3580] = "갈기바람 봉우리", [3581] = "갈기바람 길", [3582] = "제스고르", [3583] = "녹주석 해안", [3584] = "핏빛 감시초소", [3585] = "칼날숲", [3586] = "벡터 코일", [3587] = "초공간 추진기", [3588] = "극저온 핵", [3589] = "진홍 해안", [3590] = "성난비늘 둥지", [3591] = "로레스아란 폐허", [3592] = "나지비안", [3593] = "악사리엔", [3594] = "검은진흙 해안", [3595] = "타락의 웅덩이", [3596] = "숨은 산호초", [3597] = "호박그물 고개", [3598] = "고룡흉터 섬", [3599] = "갈퀴발톱 언덕", [3600] = "뾰족가지 군락", [3601] = "성난깃털 마루", [3602] = "케셀의 길목", [3603] = "텔아시온의 야영지", [3604] = "핏빛저주의 산호초", [3605] = "과거의 하이잘", [3606] = "하이잘 정상", [3607] = "불뱀 제단", [3608] = "구원자의 안식처", [3609] = "미사용3", [3610] = "불타는 칼날 폐허", [3611] = "부족 초소", [3612] = "핏빛저주의 섬", [3613] = "가라다르", [3614] = "하늘노래 호수", [3615] = "정령의 옥좌", [3616] = "웃는 해골 폐허", [3617] = "전쟁망치 언덕", [3618] = "그룰의 둥지", [3619] = "아우렌 마루", [3620] = "아우렌 폭포", [3621] = "태양여울 호수", [3622] = "태양여울 주둔지", [3623] = "에어리스 착륙지", [3624] = "경악의 괴철로 기지", [3625] = "증오의 괴철로 기지", [3626] = "텔라아르", [3627] = "북새바람 동굴", [3628] = "할라아", [3629] = "마파람 동굴", [3630] = "오슈군", [3631] = "정기의 들판", [3632] = "샤마나르", [3633] = "선조의 터", [3634] = "바람갈대 마을", [3635] = "미사용2", [3636] = "정령의 고원", [3637] = "킬소로우 요새", [3638] = "시험의 투기장", [3639] = "은빛안개 섬", [3640] = "비수늪 마을", [3641] = "그늘늪 마을", [3642] = "야생늪 마을", [3643] = "피비늘 군락", [3644] = "텔레도르", [3645] = "자브라진", [3646] = "쿠아그 마루", [3647] = "부화의 골짜기", [3648] = "죽음의 늪", [3649] = "스포어가르", [3650] = "앙고로쉬 영토", [3651] = "앙고로쉬 소굴", [3652] = "버섯 동굴", [3653] = "물갈퀴 호수", [3654] = "배수로", [3655] = "그늘늪 호수", [3656] = "수렁등불 호수", [3657] = "차원문 폐허", [3658] = "포자바람 호수", [3659] = "바다자리 호수", [3660] = "칼날 고개", [3661] = "칼날이빨 대협곡", [3662] = "대강당", [3663] = "버려진 장원", [3664] = "태양의 여사냥꾼", [3665] = "매날개 광장", [3666] = "할라아니 분지", [3667] = "벌거벗은 수렁", [3668] = "보하무 폐허", [3669] = "경기장", [3670] = "전망대", [3671] = "무너진 언덕", [3672] = "마그하리 행렬", [3673] = "네싱워리 탐험대", [3674] = "세나리온 수풀", [3675] = "투렘", [3676] = "장막의 쉬에노르", [3677] = "장막의 스키스", [3678] = "장막의 샬라스", [3679] = "스케티스", [3680] = "검은바람 계곡", [3681] = "불꽃날개 거점", [3682] = "그란골바르 마을", [3683] = "돌망치 요새", [3684] = "알레리아 성채", [3685] = "해골이빨 폐허", [3686] = "장막의 리디크", [3687] = "올렘바스", [3688] = "아킨둔", [3689] = "장막의 레스크", [3690] = "검은바람 호수", [3691] = "에레노루 호수", [3692] = "조룬 호수", [3693] = "스키실 산맥", [3694] = "안개 마루", [3695] = "뒤틀린 언덕", [3696] = "울타리 언덕", [3697] = "해골 무덤", [3698] = "나그란드 투기장", [3699] = "웃는 해골 광장", [3700] = "피의 투기장", [3701] = "투기장", [3702] = "칼날 투기장", [3703] = "샤트라스", [3704] = "수호자의 관문", [3705] = "텔라아리 분지", [3706] = "어둠의 문", [3707] = "얼라이언스 주둔지", [3708] = "호드 야영지", [3709] = "나이트 엘프 마을", [3710] = "놀드랏실", [3711] = "미사용", [3712] = "52번 구역", [3713] = "피의 용광로", [3714] = "으스러진 손의 전당", [3715] = "증기 저장고", [3716] = "지하수렁", [3717] = "강제 노역소", [3718] = "늪쥐 감시초소", [3719] = "피투성이굴 폐허", [3720] = "쌍둥이 첨탑 폐허", [3721] = "부서진 잔해", [3722] = "아라 마나괴철로", [3723] = "알클론 폐허", [3724] = "코스모렌치", [3725] = "엔카트 폐허", [3726] = "브나르 마나괴철로", [3727] = "고철 지대", [3728] = "소용돌이 지대", [3729] = "고철더미", [3730] = "코루 마나괴철로", [3731] = "폭풍우 균열", [3732] = "키린바르 마을", [3733] = "자줏빛 탑", [3734] = "듀로 마나괴철로", [3735] = "공허의 바람 고원", [3736] = "울트리스 마나괴철로", [3737] = "하늘 마루", [3738] = "폭풍 첨탑", [3739] = "망각의 괴철로 주둔지", [3740] = "지옥의 괴철로 주둔지", [3741] = "파랄론 폐허", [3742] = "소크레타르의 옥좌", [3743] = "불타는 군단 요새", [3744] = "어둠달 마을", [3745] = "와일드해머 성채", [3746] = "굴단의 손아귀", [3747] = "지옥의 구덩이", [3748] = "죽음의 괴철로", [3749] = "갈퀴흉터 저수지", [3750] = "갈퀴흉터 거점", [3751] = "태양불꽃 거점", [3752] = "일리다리 거점", [3753] = "바아리 폐허", [3754] = "샤타르 제단", [3755] = "파멸의 계단", [3756] = "카라보르 폐허", [3757] = "아타말 언덕", [3758] = "황천날개 벌판", [3759] = "황천날개 마루", [3760] = "울타리 언덕", [3761] = "높은길", [3762] = "바람갈대 고개", [3763] = "장가르 마루", [3764] = "황혼의 마루", [3765] = "서슬가시 고개", [3766] = "오레보르 피난처", [3767] = "칼날 고개", [3768] = "뾰족 마루", [3769] = "천둥군주 요새", [3770] = "칼날이빨 대협곡", [3771] = "생명의 숲", [3772] = "실바나르", [3773] = "칼날첨탑 요새", [3774] = "그룰의 둥지", [3775] = "피의 투기장", [3776] = "피망치 전초기지", [3777] = "피망치 야영지", [3778] = "드레니시스트 광산", [3779] = "트로그마의 점령지", [3780] = "검은날개 소굴", [3781] = "그리쉬나스", [3782] = "장막의 래쉬", [3783] = "장막의 베크", [3784] = "공포의 괴철로 기지", [3785] = "격노의 괴철로 기지", [3786] = "오그릴라", [3787] = "고통의 괴철로 기지", [3788] = "낮은길", [3789] = "어둠의 미궁", [3790] = "아키나이 납골당", [3791] = "세데크 전당", [3792] = "마나 무덤", [3793] = "지옥불꽃 협곡", [3794] = "뼈의 골짜기", [3795] = "샤나아리 황무지", [3796] = "일그러진 벌판", [3797] = "무너진 하늘 마루", [3798] = "하알레쉬 협곡", [3799] = "돌담 협곡", [3800] = "가시송곳니 언덕", [3801] = "마그하르 영토", [3802] = "공허의 마루", [3803] = "심연의 절벽", [3804] = "군단 전초지", [3805] = "줄아만", [3806] = "보급 짐마차", [3807] = "지옥절단기 함락지", [3808] = "세나리온 초소", [3809] = "남쪽 성루", [3810] = "북쪽 성루", [3811] = "고르가즈 전초기지", [3812] = "해골망치 초소", [3813] = "고통의 길", [3814] = "동쪽 보급 짐마차", [3815] = "원정대 거점", [3816] = "비행선 추락지", [3817] = "시험 지역", [3818] = "피비늘 영토", [3819] = "암흑갈기 군락", [3820] = "폭풍의 눈", [3821] = "감시자의 수용소", [3822] = "해그늘 주둔지", [3823] = "고행의 섬", [3824] = "피망치 협곡", [3825] = "용의 무덤", [3826] = "비수아귀 협곡", [3827] = "베크하르 고원", [3828] = "루안 숲", [3829] = "장막의 루안", [3830] = "까마귀 숲", [3831] = "죽음의 문", [3832] = "소용돌이 고원", [3833] = "칼날 마루", [3834] = "광기의 마루", [3835] = "먼지깃 협곡", [3836] = "마그테리돈의 둥지", [3837] = "성난태양 주둔지", [3838] = "해골망치 산맥", [3839] = "버려진 무기고", [3840] = "검은 사원", [3841] = "암흑갈기 호숫가", [3842] = "폭풍우 요새", [3844] = "모크나탈 마을", [3845] = "폭풍우 요새", [3846] = "알카트라즈", [3847] = "신록의 정원", [3848] = "알카트라즈", [3849] = "메카나르", [3850] = "황천의 돌무지", [3851] = "중앙 생태지구 주둔지", [3852] = "툴루맨의 정박지", [3854] = "자유연합 경비초소", [3855] = "피의 투기장", [3856] = "엘렌다르 건널목", [3857] = "암멘 여울", [3858] = "서슬가시 벼랑", [3859] = "실미르 호수", [3860] = "라스토크 숲", [3861] = "탈라시안 고개", [3862] = "휘몰이 협곡", [3863] = "파괴된 벌판", [3864] = "바쉬르 영지", [3865] = "수정 돌기", [3866] = "불타버린 언덕", [3867] = "칼날 협곡", [3868] = "자이로 교각", [3869] = "마법사 탑", [3870] = "블러드 엘프 경비탑", [3871] = "드레나이 폐허", [3872] = "지옥절단기 폐허", [3873] = "발명품 실험장", [3874] = "외곽 생태지구", [3875] = "하늘마루 생태지구", [3876] = "수데론 생태지구", [3877] = "중앙 생태지구", [3878] = "에테리움 작전 지역", [3879] = "예배당 지구", [3880] = "지온 작업 갱도", [3881] = "트렐리움 광산", [3882] = "파괴자의 침공 거점", [3883] = "붐의 야영지", [3884] = "해골망치 고개", [3885] = "황천그물 마루", [3886] = "버려진 짐마차", [3887] = "피난민 행렬", [3888] = "어둠의 무덤", [3889] = "장막의 라제", [3890] = "빛의 무덤", [3891] = "부패의 언덕", [3892] = "고뇌의 언덕", [3893] = "규율의 광장", [3894] = "아키나이 영지", [3895] = "세나리온 감시초소", [3896] = "알도르 마루", [3897] = "빛의 정원", [3898] = "점술가 언덕", [3899] = "고난의 거리", [3900] = "대군주의 침공 거점", [3901] = "알레리아 초소", [3902] = "돌망치 야영지", [3903] = "바울더모크", [3904] = "저주받은 골짜기", [3905] = "갈퀴송곳니 저수지", [3906] = "핏빛 여울", [3907] = "청록 해안", [3908] = "무지렁이 골짜기", [3909] = "잃어버린 언덕", [3910] = "안개숲", [3911] = "평온의 해변", [3912] = "황금가지 고개", [3913] = "팔리타스 마법석", [3914] = "샨도르 마법석", [3915] = "구름다리 해변", [3916] = "달새김 숲", [3917] = "아킨둔", [3918] = "토쉴리의 연구기지", [3919] = "노래하는 마루", [3920] = "징검다리 거점", [3921] = "아클로니스 마루", [3922] = "칼날첨탑 전초기지", [3923] = "그룰의 둥지", [3924] = "북녘망치 탑", [3925] = "남녘망치 탑", [3926] = "부서진 평원", [3927] = "오로노크의 농장", [3928] = "저주의 제단", [3929] = "정복의 길", [3930] = "해그늘 벌판", [3931] = "칼날첨탑 영토", [3932] = "스케슬론 주둔지", [3933] = "스케슬론 폐허", [3934] = "마을 광장", [3935] = "마법사 지구", [3936] = "죽음의 괴철로 탑", [3937] = "잿가루 감시초소", [3938] = "별의 성소", [3939] = "용아귀 요새", [3940] = "악취나는 웅덩이", [3941] = "시험용", [3942] = "라잔의 영지", [3943] = "대재앙의 침공 거점", [3944] = "어둠의 제단", [3945] = "황천날개 고개", [3946] = "웨인의 은거처", [3947] = "끓어오르는 웅덩이", [3948] = "Brian and Pat Test", [3949] = "용암 지대", [3950] = "붉은 감시초소", [3951] = "영원의 숲", [3952] = "고룡해골 다리", [3953] = "비늘날개 절벽", [3954] = "고룡해골 굴", [3955] = "지옥불 분지", [3956] = "어둠의 계단", [3957] = "샤타리 전초기지", [3958] = "샤타리 주둔지", [3959] = "검은 사원", [3960] = "영혼분쇄자의 은신처", [3961] = "슬픔의 날개 거점", [3962] = "빔골의 마법진", [3963] = "용돌기 마루", [3964] = "하늘경비대 전초기지", [3965] = "황천날개 광산", [3966] = "용아귀 주둔지", [3967] = "용아귀 하늘길", [3968] = "로데론의 폐허", [3969] = "리븐다크의 둥지", [3970] = "옵시디아의 둥지", [3971] = "인시디온의 둥지", [3972] = "퓨리윙의 둥지", [3973] = "검은바람 비행기지", [3974] = "장막의 하리크", [3975] = "테로크의 안식처", [3976] = "장막의 알라라크", [3977] = "장막의 쉴라크 언덕", [3978] = "장막의 쉴라크", [4008] = "샤툴의 순간이동기", [4009] = "일리다리 훈련장", [4010] = "진흙톱니 거점", [4046] = "공포뿔 거점", [4047] = "내트의 정박지", [4049] = "타베사의 농장", [4067] = "역병의 숲 경비탑", [4075] = "태양샘 고원", [4076] = "미사용", [4078] = "서슬가시 언덕", [4080] = "쿠엘다나스 섬", [4081] = "새벽추적자호", [4082] = "신로렌호", [4083] = "실버문의 긍지호", [4084] = "피의 맹세호", [4085] = "무너진 태양 집결지", [4086] = "태양너울 성소", [4087] = "태양너울 항구", [4088] = "태양너울 무기고", [4089] = "돈스타 마을", [4090] = "새벽 광장", [4091] = "초록아가미 해안", [4092] = "죽음의 흉터", [4093] = "태양 괴철로", [4094] = "태양샘 고원", [4095] = "마법학자의 정원", [4131] = "마법학자의 정원", [4139] = "무리해 광장", [4140] = "죽음의 흉터", }
#!/home/jart/bin/redbean -i assert(unix.sigaction(unix.SIGUSR1, function(sig) gotsigusr1 = true end)) gotsigusr1 = false assert(unix.raise(unix.SIGUSR1)) if gotsigusr1 then print('hooray the signal was delivered') else print('oh no some other signal was handled') end
require"ISUI/ISPanelJoypad" ---@class ISColorPicker : ISPanelJoypad ISColorPicker = ISPanelJoypad:derive("ISColorPicker"); function ISColorPicker:render() ISPanelJoypad.render(self) for i,color in ipairs(self.colors) do local col = (i-1) % self.columns local row = math.floor((i-1) / self.columns) self:drawRect(self.borderSize + col * self.buttonSize, self.borderSize + row * self.buttonSize, self.buttonSize, self.buttonSize, 1.0, color.r, color.g, color.b) end for col=1,self.columns do self:drawRect(self.borderSize + col * self.buttonSize, self.borderSize, 1, self.buttonSize * self.rows, 1.0, 0.0, 0.0, 0.0) end for row=1,self.rows do self:drawRect(self.borderSize, self.borderSize + row * self.buttonSize, self.buttonSize * self.columns, 1, 1.0, 0.0, 0.0, 0.0) end local col = (self.index-1) % self.columns local row = math.floor((self.index-1) / self.columns) self:drawRectBorder(self.borderSize + col * self.buttonSize, self.borderSize + row * self.buttonSize, self.buttonSize + 1, self.buttonSize + 1, 1.0, 1.0, 1.0, 1.0) if self.joyfocus then self:drawRectBorder(0, -self:getYScroll(), self:getWidth(), self:getHeight(), 0.4, 0.2, 1.0, 1.0); self:drawRectBorder(1, 1-self:getYScroll(), self:getWidth()-2, self:getHeight()-2, 0.4, 0.2, 1.0, 1.0); end end function ISColorPicker:onMouseDown(x, y) self.mouseDown = true self:onMouseMove(0, 0) return true end function ISColorPicker:onMouseDownOutside(x, y) self:removeSelf() return true end function ISColorPicker:onMouseMove(dx, dy) if self.otherFct then return true; end if not self.mouseDown then return true end local x = self:getMouseX() local y = self:getMouseY() local col = math.floor((x - self.borderSize) / self.buttonSize) local row = math.floor((y - self.borderSize) / self.buttonSize) if col < 0 then col = 0 end if col >= self.columns then col = self.columns - 1 end if row < 0 then row = 0 end if row >= self.rows then row = self.rows - 1 end local index = col + row * self.columns + 1 if index == self.index then return true end self.index = index if self.pickedFunc then self.pickedFunc(self.pickedTarget, self.colors[self.index], false, self.pickedArgs[1], self.pickedArgs[2], self.pickedArgs[3], self.pickedArgs[4]) end return true end function ISColorPicker:onMouseUp(x, y) if self.mouseDown then self.mouseDown = false if self.otherFct then self:picked2(true) else self:picked(true) end end return true end function ISColorPicker:picked2(hide) if hide then self:removeSelf() end local x = self:getMouseX() local y = self:getMouseY() local col = math.floor((x - self.borderSize) / self.buttonSize) local row = math.floor((y - self.borderSize) / self.buttonSize) if col < 0 then col = 0 end if col >= self.columns then col = self.columns - 1 end if row < 0 then row = 0 end if row >= self.rows then row = self.rows - 1 end self.index = col + row * self.columns + 1 if self.pickedFunc then self.pickedFunc(self.pickedTarget, self.colors[self.index], false, self.pickedArgs[1], self.pickedArgs[2], self.pickedArgs[3], self.pickedArgs[4]) end end function ISColorPicker:onMouseUpOutside(x, y) return self:onMouseUp(x, y) end function ISColorPicker:onJoypadDirLeft(joypadData) local col = (self.index-1) % self.columns if col > 0 then self.index = self.index - 1 else self.index = self.index + self.columns - 1 end self:picked(false) end function ISColorPicker:onJoypadDirRight(joypadData) local col = (self.index-1) % self.columns if col < self.columns-1 then self.index = self.index + 1 else self.index = self.index - self.columns + 1 end self:picked(false) end function ISColorPicker:onJoypadDirUp(joypadData) local row = math.floor((self.index-1) / self.columns) if row > 0 then self.index = self.index - self.columns else self.index = self.index + self.columns * (self.rows - 1) end self:picked(false) end function ISColorPicker:onJoypadDirDown(joypadData) local row = math.floor((self.index-1) / self.columns) if row < self.rows-1 then self.index = self.index + self.columns else self.index = self.index - self.columns * (self.rows - 1) end self:picked(false) end function ISColorPicker:onJoypadDown(button) if button == Joypad.AButton then self:picked(true) end if button == Joypad.BButton then self:removeSelf() end end function ISColorPicker:removeSelf() if self.parent then self.parent:removeChild(self) else self:removeFromUIManager() end if self.joyfocus then self.joyfocus.focus = self.resetFocusTo end end function ISColorPicker:picked(hide) if hide then self:removeSelf() end if self.pickedFunc then self.pickedFunc(self.pickedTarget, self.colors[self.index], mouseUp, self.pickedArgs[1], self.pickedArgs[2], self.pickedArgs[3], self.pickedArgs[4]) end end function ISColorPicker:setInitialColor(initial) local d = 10000000 for index,color in ipairs(self.colors) do local dr = math.abs(initial:getR() - color.r) local dg = math.abs(initial:getG() - color.g) local db = math.abs(initial:getB() - color.b) if dr + dg + db < d then d = dr + dg + db self.index = index end end end function ISColorPicker:setPickedFunc(func, arg1, arg2, arg3, arg4) self.pickedFunc = func self.pickedArgs = { arg1, arg2, arg3, arg3 } end function ISColorPicker:setColors(colors, columns, rows) self.colors = colors self.columns = columns self.rows = rows local width = columns * self.buttonSize + self.borderSize * 2 local height = rows * self.buttonSize + self.borderSize * 2 self:setWidth(width) self:setHeight(height) self.index = math.min(self.index, #colors) end function ISColorPicker:new(x, y, HSBFactor) local buttonSize = 20 local borderSize = 12 local columns = 18 local rows = 12 local width = columns * buttonSize + borderSize * 2 local height = rows * buttonSize + borderSize * 2 local o = ISPanelJoypad.new(self, x, y, width, height) o.backgroundColor.a = 1 o.borderSize = borderSize o.buttonSize = buttonSize o.columns = columns o.rows = rows o.index = 1 o.pickedArgs = {} o.colors = {} local i = 0 local newColor = Color.new(1.0, 1.0, 1.0, 1.0); for red = 0,255,51 do for green = 0,255,51 do for blue = 0,255,51 do local col = i % columns local row = math.floor(i / columns) if row % 2 == 0 then row = row / 2 else row = math.floor(row / 2) + 6 end newColor:set(red / 255, green / 255, blue / 255, 1.0) if col == columns-1 and row == rows-1 then -- Pure white newColor:set(1.0, 1.0, 1.0, 1.0) elseif HSBFactor then newColor:changeHSBValue(HSBFactor.h, HSBFactor.s, HSBFactor.b); end -- o.colors[col + row * columns + 1] = { r = red/255, g = green/255, b = blue/255 } o.colors[col + row * columns + 1] = { r = newColor:getRedFloat(), g = newColor:getGreenFloat(), b = newColor:getBlueFloat() } i = i + 1 end end end return o end
local M = {} M._user_options = {} M.setup = function(opts, _bufnr) local bufnr = _bufnr or 0 function M._user_options.picker(...) local pickers = require('sqls.pickers') return (pickers[opts.picker] or pickers.default)(...) end vim.api.nvim_buf_call(bufnr, function() vim.cmd [[command! -buffer -range SqlsExecuteQuery lua require'sqls.commands'.exec('executeQuery', '<mods>', <range> ~= 0, nil, <line1>, <line2>)]] vim.cmd [[command! -buffer -range SqlsExecuteQueryVertical lua require'sqls.commands'.exec('executeQuery', '<mods>', <range> ~= 0, '-show-vertical', <line1>, <line2>)]] vim.cmd [[command! -buffer SqlsShowDatabases lua require'sqls.commands'.exec('showDatabases', '<mods>')]] vim.cmd [[command! -buffer SqlsShowSchemas lua require'sqls.commands'.exec('showSchemas', '<mods>')]] vim.cmd [[command! -buffer SqlsShowConnections lua require'sqls.commands'.exec('showConnections', '<mods>')]] -- Not yet supported by the language server: -- vim.cmd [[command! -buffer SqlsShowTables lua require'sqls.commands'.exec('showTables', '<mods>')]] -- vim.cmd [[command! -buffer SqlsDescribeTable lua require'sqls.commands'.exec('describeTable', '<mods>')]] vim.cmd [[command! -buffer -nargs=? SqlsSwitchDatabase lua require'sqls.commands'.switch_database(<f-args>)]] vim.cmd [[command! -buffer -nargs=? SqlsSwitchConnection lua require'sqls.commands'.switch_connection(<f-args>)]] end) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<Plug>(sqls-execute-query)', "<Cmd>set opfunc=v:lua.require'sqls.commands'.query<CR>g@", {silent = true}) vim.api.nvim_buf_set_keymap(bufnr, 'x', '<Plug>(sqls-execute-query)', "<Cmd>set opfunc=v:lua.require'sqls.commands'.query<CR>g@", {silent = true}) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<Plug>(sqls-execute-query-vertical)', "<Cmd>set opfunc=v:lua.require'sqls.commands'.query_vertical<CR>g@", {silent = true}) vim.api.nvim_buf_set_keymap(bufnr, 'x', '<Plug>(sqls-execute-query-vertical)', "<Cmd>set opfunc=v:lua.require'sqls.commands'.query_vertical<CR>g@", {silent = true}) end M.on_attach = function(client, bufnr) client.resolved_capabilities.execute_command = true client.commands = M.commands M.setup({}, bufnr) end M.commands = { executeQuery = function(code_action, command) require('sqls.commands').exec('executeQuery') end, showDatabases = function(code_action, command) require('sqls.commands').exec('showDatabases') end, showSchemas = function(code_action, command) require('sqls.commands').exec('showSchemas') end, showConnections = function(code_action, command) require('sqls.commands').exec('showConnections') end, showTables = function(code_action, command) require('sqls.commands').exec('showTables') end, describeTable = function(code_action, command) require('sqls.commands').exec('describeTable') end, switchConnections = function(code_action, command) require('sqls.commands').switch_connection() end, switchDatabase = function(code_action, command) require('sqls.commands').switch_database() end, } return M
local addon, tbl = ...; tbl.Ignore = function(arg) if tonumber(arg) ~= nil then arg = tonumber(arg) tbl.Ignore_ID(arg) else tbl.Ignore_Text(arg) end end tbl.Remove = function(arg) if tonumber(arg) then -- The passed argument is a number or item ID. arg = tonumber(arg); if tbl.Items[arg] then if tbl.Items[arg].itemLink ~= nil then print(tbl.L["ADDON_NAME"] .. tbl.L["REMOVED"] .. " " .. tbl.Items[arg].itemLink .. ".") else print(tbl.L["ADDON_NAME"] .. tbl.L["REMOVED"] .. " " .. arg .. ".") end tbl.Items[arg] = nil end elseif not tonumber(arg) then -- The passed argument isn't a number, and is likely an item's link. arg = (GetItemInfoInstant(arg)); -- Converts the supposed item link into an item ID. if tonumber(arg) then arg = tonumber(arg); if tbl.Items[arg] then if tbl.Items[arg].itemLink ~= nil then print(tbl.L["ADDON_NAME"] .. tbl.L["REMOVED"] .. " " .. tbl.Items[arg].itemLink .. ".") else print(tbl.L["ADDON_NAME"] .. tbl.L["REMOVED"] .. " " .. arg .. ".") end tbl.Items[arg] = nil end end else print(tbl.L["ADDON_NAME"] .. tbl.L["BAD_REQUEST"]); end if (tbl.LootTemplate[arg]) then tbl.LootTemplate[arg] = nil end -- Remove all associated entries that the player looted the item from. end -- Synopsis: Allows the player to remove undesired items from the items table using its ID or link. tbl.Search = function(query) if tonumber(query) ~= nil then query = tonumber(query) tbl.Search_ID(query) else tbl.Search_Text(query) end end --[[ Synopsis: Allows the player to search the items table by an item's ID or its partial/full name, a creature's name, or a zone's name. Use Case(s): - Item: The most common search is by an item's ID or partial/full name to provide another player with proof an item still drops. - Creature: A search to see what items a particular creature has dropped. This is made possible by keeping track of the items a creature has dropped (call a "loot table"). - Zone: An entire zone search, doesn't matter which creature in the zone dropped the item. Provides the player with every item that dropped in the provided zone. Partial/full names supported. ]] tbl.CheckProgress = function() print(tbl.L["ADDON_NAME"] .. tbl.GetCount(tbl.Items) .. " " .. tbl.L["OF"] .. " " .. tbl.L["APPROXIMATELY"] .. " " .. 154000 .. " (" .. tbl.Round(tbl.GetCount(tbl.Items)/154000) .. "%)") end
--[[ The OpenSSL stack library. Note `safestack` is not usable here in ffi because those symbols are eaten after preprocessing. Instead, we should do a Lua land type checking by having a nested field indicating which type of cdata its ctx holds. ]] local ffi = require "ffi" local C = ffi.C require "resty.openssl.include.ossl_typ" local OPENSSL_10 = require("resty.openssl.version").OPENSSL_10 local OPENSSL_11_OR_LATER = require("resty.openssl.version").OPENSSL_11_OR_LATER local BORINGSSL = require("resty.openssl.version").BORINGSSL local _M = {} ffi.cdef [[ typedef char *OPENSSL_STRING; ]] if OPENSSL_11_OR_LATER and not BORINGSSL then ffi.cdef [[ typedef struct stack_st OPENSSL_STACK; OPENSSL_STACK *OPENSSL_sk_new_null(void); int OPENSSL_sk_push(OPENSSL_STACK *st, const void *data); void OPENSSL_sk_pop_free(OPENSSL_STACK *st, void (*func) (void *)); int OPENSSL_sk_num(const OPENSSL_STACK *); void *OPENSSL_sk_value(const OPENSSL_STACK *, int); OPENSSL_STACK *OPENSSL_sk_dup(const OPENSSL_STACK *st); void OPENSSL_sk_free(OPENSSL_STACK *); void *OPENSSL_sk_delete(OPENSSL_STACK *st, int loc); typedef void (*OPENSSL_sk_freefunc)(void *); typedef void *(*OPENSSL_sk_copyfunc)(const void *); OPENSSL_STACK *OPENSSL_sk_deep_copy(const OPENSSL_STACK *, OPENSSL_sk_copyfunc c, OPENSSL_sk_freefunc f); ]] _M.OPENSSL_sk_pop_free = C.OPENSSL_sk_pop_free _M.OPENSSL_sk_new_null = C.OPENSSL_sk_new_null _M.OPENSSL_sk_push = C.OPENSSL_sk_push _M.OPENSSL_sk_pop_free = C.OPENSSL_sk_pop_free _M.OPENSSL_sk_num = C.OPENSSL_sk_num _M.OPENSSL_sk_value = C.OPENSSL_sk_value _M.OPENSSL_sk_dup = C.OPENSSL_sk_dup _M.OPENSSL_sk_delete = C.OPENSSL_sk_delete _M.OPENSSL_sk_free = C.OPENSSL_sk_free _M.OPENSSL_sk_deep_copy = C.OPENSSL_sk_deep_copy elseif OPENSSL_10 or BORINGSSL then ffi.cdef [[ typedef struct stack_st _STACK; // i made this up typedef struct stack_st OPENSSL_STACK; _STACK *sk_new_null(void); void sk_pop_free(_STACK *st, void (*func) (void *)); _STACK *sk_dup(_STACK *st); void sk_free(_STACK *st); _STACK *sk_deep_copy(_STACK *, void *(*)(void *), void (*)(void *)); ]] if BORINGSSL then -- indices are using size_t instead of int ffi.cdef [[ size_t sk_push(_STACK *st, void *data); size_t sk_num(const _STACK *); void *sk_value(const _STACK *, size_t); void *sk_delete(_STACK *st, size_t loc); ]] else -- normal OpenSSL 1.0 ffi.cdef [[ int sk_push(_STACK *st, void *data); int sk_num(const _STACK *); void *sk_value(const _STACK *, int); void *sk_delete(_STACK *st, int loc); ]] end _M.OPENSSL_sk_pop_free = C.sk_pop_free _M.OPENSSL_sk_new_null = C.sk_new_null _M.OPENSSL_sk_push = function(...) return tonumber(C.sk_push(...)) end _M.OPENSSL_sk_pop_free = C.sk_pop_free _M.OPENSSL_sk_num = function(...) return tonumber(C.sk_num(...)) end _M.OPENSSL_sk_value = C.sk_value _M.OPENSSL_sk_delete = C.sk_delete _M.OPENSSL_sk_dup = C.sk_dup _M.OPENSSL_sk_free = C.sk_free _M.OPENSSL_sk_deep_copy = C.sk_deep_copy end return _M
--[[ poo funcional ]]-- local function novo(pixelPorMetro, gx, gy) love.physics.setMeter(pixelPorMetro) local classe = love.physics.newWorld(pixelPorMetro *gx, pixelPorMetro *gy, true) --classe:setCallbacks(inicioContato, fimContato, preContato, posContato) return classe end mundo = { novo = novo } return mundo
local Cuboid = assert(foundation.com.Cuboid) local ng = Cuboid.new_fast_node_box local node_box = { type = "fixed", fixed = { ng( 0, 2, 0, 15, 4, 1), ng( 0, 10, 0, 15, 4, 1), ng(15, 2, 0, 1, 4, 15), ng(15, 10, 0, 1, 4, 15), ng( 1, 2, 15, 15, 4, 1), ng( 1, 10, 15, 15, 4, 1), ng( 0, 2, 1, 1, 4, 15), ng( 0, 10, 1, 1, 4, 15), }, } local single_node_box = { type = "fixed", fixed = { ng( 0, 2, 0, 15, 12, 1), ng(15, 2, 0, 1, 12, 15), ng( 1, 2, 15, 15, 12, 1), ng( 0, 2, 1, 1, 12, 15), }, } minetest.register_node("yatm_armoury_icbm:icbm_guiding_ring", { description = "ICBM Guiding Ring (Double Band)", codex_entry_id = "yatm_armoury_icbm:icbm_guiding_ring", groups = { cracky = 1, icbm_guiding_ring = 1, }, use_texture_alpha = "opaque", tiles = { "yatm_icbm_guiding_ring_top.png", "yatm_icbm_guiding_ring_bottom.png", "yatm_icbm_guiding_ring_side.png", "yatm_icbm_guiding_ring_side.png", "yatm_icbm_guiding_ring_side.png", "yatm_icbm_guiding_ring_side.png", }, paramtype = "light", paramtype2 = "facedir", sounds = yatm.node_sounds:build("metal"), drawtype = "nodebox", node_box = node_box, is_ground_content = false, sunlight_propagates = true, }) minetest.register_node("yatm_armoury_icbm:icbm_guiding_ring_single", { description = "ICBM Guiding Ring (Single Band)", codex_entry_id = "yatm_armoury_icbm:icbm_guiding_ring", groups = { cracky = 1, icbm_guiding_ring = 1, }, use_texture_alpha = "opaque", tiles = { "yatm_icbm_guiding_ring_top.png", "yatm_icbm_guiding_ring_bottom.png", "yatm_icbm_guiding_ring_single_side.png", "yatm_icbm_guiding_ring_single_side.png", "yatm_icbm_guiding_ring_single_side.png", "yatm_icbm_guiding_ring_single_side.png", }, paramtype = "light", paramtype2 = "facedir", sounds = yatm.node_sounds:build("metal"), drawtype = "nodebox", node_box = single_node_box, is_ground_content = false, sunlight_propagates = true, }) minetest.register_node("yatm_armoury_icbm:icbm_guiding_ring_warning_strips", { description = "ICBM Guiding Ring [Warning Strips] (Double Band)", codex_entry_id = "yatm_armoury_icbm:icbm_guiding_ring", groups = { cracky = 1, icbm_guiding_ring = 1, }, use_texture_alpha = "opaque", tiles = { "yatm_icbm_guiding_ring_top.png", "yatm_icbm_guiding_ring_bottom.png", "yatm_icbm_guiding_ring_warning_side.png", "yatm_icbm_guiding_ring_warning_side.png", "yatm_icbm_guiding_ring_warning_side.png", "yatm_icbm_guiding_ring_warning_side.png", }, paramtype = "light", paramtype2 = "facedir", sounds = yatm.node_sounds:build("metal"), drawtype = "nodebox", node_box = node_box, is_ground_content = false, sunlight_propagates = true, }) minetest.register_node("yatm_armoury_icbm:icbm_guiding_ring_single_warning_strips", { description = "ICBM Guiding Ring [Warning Strips] (Single Band)", codex_entry_id = "yatm_armoury_icbm:icbm_guiding_ring", groups = { cracky = 1, icbm_guiding_ring = 1, }, use_texture_alpha = "opaque", tiles = { "yatm_icbm_guiding_ring_top.png", "yatm_icbm_guiding_ring_bottom.png", "yatm_icbm_guiding_ring_warning_single_side.png", "yatm_icbm_guiding_ring_warning_single_side.png", "yatm_icbm_guiding_ring_warning_single_side.png", "yatm_icbm_guiding_ring_warning_single_side.png", }, paramtype = "light", paramtype2 = "facedir", sounds = yatm.node_sounds:build("metal"), drawtype = "nodebox", node_box = single_node_box, is_ground_content = false, sunlight_propagates = true, })
local _, addon = ... local quickgroups = addon.new_module("quickgroups") local colors = addon.get_module("colors") local function add_tooltip_text(tooltip) local name, _ = tooltip:GetItem(); -- Add tooltip text only when hovering over keystone if name == "Mythic Keystone" and not CursorHasItem() then tooltip:AddLine( "\n|cffeda55fAlt-Click|r to list group for this keystone.") end end -- Please don't hate me for this, but no idea how else to do this conversion! local function GetActivityGrpIdFromMapId(map_id) if type(map_id) ~= "number" then map_id = tonumber(map_id) end local map_name = C_ChallengeMode.GetMapUIInfo(map_id) -- Create map of map name -> group id local grp_id_dict = {} for i = 259, 266 do local name = C_LFGList.GetActivityGroupInfo(i) grp_id_dict[name] = i end return grp_id_dict[map_name] end local function CreateListing(item_string) local item_data = {strsplit(":", item_string)} -- If the item is not a keystone, do nothing if item_data[1] ~= "keystone" then return end -- Open up group creation panel if not already open local panel = LFGListFrame.EntryCreation if (not LFGListFrame.EntryCreation:IsVisible()) then PVEFrame_ShowFrame("GroupFinderFrame", "LFGListPVEStub") -- categoryID 2 == Dungeons LFGListEntryCreation_Show(panel, LFGListFrame.baseFilters, 2, panel.selectedFilters) end -- Fill out group info -- Select correct dungeon local group_id = GetActivityGrpIdFromMapId(item_data[3]) LFGListEntryCreation_Select(panel, nil, nil, group_id, nil) -- Fill in required ilvl info if addon.c("autofill_ilvl") then local config = addon.get_module("config") local min_ilvl = 0 if addon.c("autofill_ilvl_mode") == config.AutofillModes.ROUND then -- Get min ilvl by rounding down to next multiple of "autofill_ilvl_nr" local _, avg_ilvl, _ = GetAverageItemLevel() min_ilvl = avg_ilvl - avg_ilvl % addon.c("autofill_ilvl_nr") elseif addon.c("autofill_ilvl_mode") == config.AutofillModes.STATIC then -- Use a static ilvl for autofilling min_ilvl = addon.c("autofill_ilvl_nr") end -- Set min ilvl panel.ItemLevel.EditBox:SetText(min_ilvl) else panel.ItemLevel.EditBox:SetText("") panel.ItemLevel.CheckButton:SetChecked(false) end -- Change title to include name suggestion local level = item_data[4] panel.NameLabel:SetText("Title (suggested: \"" .. colors:colorise_string("+" .. level, "blue") .. "\")") end local function OnModifiedClick(self, button) if IsAltKeyDown() and button == "LeftButton" and not CursorHasItem() then local link = GetContainerItemLink(self:GetParent():GetID(), self:GetID()) -- Retuturn if user clicked on nothing if (not link) then return end local item_string = select(3, strfind(link, "|H(.+)|h")) CreateListing(item_string) end end local function OnHyperlinkClick(chatFrame, link, text, button) if IsAltKeyDown() and button == "LeftButton" then CreateListing(link) end end function quickgroups:init() addon.print("Called quickgroups init!") -- Hook up tooltip addition GameTooltip:HookScript("OnTooltipSetItem", add_tooltip_text) -- Hook up alt clicking keystone hooksecurefunc("ContainerFrameItemButton_OnModifiedClick", OnModifiedClick) hooksecurefunc("ChatFrame_OnHyperlinkShow", OnHyperlinkClick) end
--[[ EVALSHA SHA1(__FILE__) model id > Time complexity: O(1) Delete a hash at "#model:id:#id", and the corresponding id from the indexed attribute id sets. # Return value The number of keys deleted from Redis --]] -- The arguments can be accessed by Lua using the KEYS global variable in the -- form of a one-based array (so KEYS[1], KEYS[2], ...). -- -- KEYS = id, hash_tag -- ARGV = Model.name index_attr_size range_index_attr_size [index_attr_key ...] [range_index_attr_key ...] [custom_index_name ...] <%= include_lua 'shared/index_helper_methods' %> -- Validate input to script before making Redis db calls if #KEYS ~= 2 then error('Expected keys of be of size 2') end local model = ARGV[1] local id, hash_tag = unpack(KEYS) -- key = "#{model}:id:{id}" local key = model .. ':id:' .. id local index_attr_pos = 4 local range_attr_pos = index_attr_pos + ARGV[2] local custom_index_pos = range_attr_pos + ARGV[3] -- Clean up id sets for both index and range index attributes local index_attr_keys = {unpack(ARGV, index_attr_pos, range_attr_pos - 1)} if #index_attr_keys > 0 then -- Retrieve old index attr values so we can delete them in the attribute id sets local attr_vals = redis.call('hmget', key, unpack(index_attr_keys)) for i=1, #index_attr_keys do delete_id_from_index_attr(hash_tag, model, index_attr_keys[i], attr_vals[i], id) end end local range_index_attr_keys = {unpack(ARGV, range_attr_pos, custom_index_pos - 1)} if #range_index_attr_keys > 0 then local attr_vals = redis.call('hmget', key, unpack(range_index_attr_keys)) for i=1, #range_index_attr_keys do delete_id_from_range_index_attr(hash_tag, model, range_index_attr_keys[i], attr_vals[i], id) end end -- Delete record from custom indexes local custom_index_names = {unpack(ARGV, custom_index_pos)} for _, index_name in ipairs(custom_index_names) do delete_record_from_custom_index(hash_tag, model, index_name, id) end -- delete the actual key return redis.call('del', key)
ITEM.name = "Telephone" ITEM.description = "itemTelephoneDesc" ITEM.price = 5 ITEM.model = "models/mosi/fallout4/props/junk/phone.mdl"
-- Natural Selection 2 'Classic Entities Mod' -- Adds some additional entities inspired by Half-Life 1 and the Extra Entities Mod by JimWest - https://github.com/JimWest/ExtraEntitesMod -- Designed to work with maps developed for Extra Entities Mod. -- Source located at - https://github.com/xToken/ClassicEnts -- lua\ClassicEnts\ControlledPusher.lua -- Dragon Script.Load("lua/Mixins/SignalListenerMixin.lua") Script.Load("lua/Trigger.lua") Script.Load("lua/ClassicEnts/EEMMixin.lua") Script.Load("lua/ClassicEnts/ControlledMixin.lua") class 'ControlledPusher' (Trigger) ControlledPusher.kMapName = "controlled_pusher" local kDefaultForce = 50 local kPushPlayerCooldown = 0.3 local kVerticleScalar = 1.2 //EEM used to move player up a bit, use this to account for that. local networkVars = { direction = "vector", force = "float" } -- Maintain Compat with EEM local function AnglesToVector(angles) local direction = Vector(0,0,0) if angles then direction.z = math.cos(angles.pitch) direction.y = -math.sin(angles.pitch) * kVerticleScalar if angles.yaw ~= 0 then direction.x = direction.z * math.sin(angles.yaw) direction.z = direction.z * math.cos(angles.yaw) end end return direction end function ControlledPusher:OnCreate() Trigger.OnCreate(self) InitMixin(self, SignalListenerMixin) -- SignalMixin sets this on init, but I need to confirm its set on ent. self.listenChannel = nil self.direction = Vector(0, 1, 0) -- Straight upppp tooo the mooon. self.force = kDefaultForce self:SetRelevancyDistance(kMaxRelevancyDistance) end function ControlledPusher:OnInitialized() Trigger.OnInitialized(self) InitMixin(self, ControlledMixin) if Server then InitMixin(self, EEMMixin) self.direction = AnglesToVector(self:GetAngles()) -- Editor wont allow redefining a property with the same name without crashing :/ if self.realforce ~= nil then self.force = self.realforce elseif self.realForce ~= nil then -- Incase anyone caught my earlier mistake and fixed it in the map self.force = self.realForce end end self:SetTriggerCollisionEnabled(true) end function ControlledPusher:GetIsMapEntity() return true end function ControlledPusher:CanPushEntity(entity) if self:GetIsEnabled() and entity and entity:isa("Player") and HasMixin(entity, "Moveable") and entity:GetIsAlive() and entity.pushTime + kPushPlayerCooldown < Shared.GetTime() then return true end return false end function ControlledPusher:OnSetEnabled(enabled) if enabled then self:ForEachEntityInTrigger(self.OnTriggerEntered) end end function ControlledPusher:OnTriggerEntered(enterEnt, triggerEnt) if self:CanPushEntity(enterEnt) then if gDebugClassicEnts then Shared.Message(string.format("Pushing entity %s in direction %s with %s force.", enterEnt:GetId(), self.direction, self.force)) end enterEnt:SetBaseVelocity(self.direction * self.force, true) enterEnt.pushTime = Shared.GetTime() end end Shared.LinkClassToMap("ControlledPusher", ControlledPusher.kMapName, networkVars)
package("bgfx") set_homepage("https://bkaradzic.github.io/bgfx/") set_description("Cross-platform, graphics API agnostic, “Bring Your Own Engine/Framework” style rendering library") set_license("BSD-2-Clause") add_urls("https://github.com/bkaradzic/bgfx.git") add_versions("7816", "5ecddbf4d51e2dda2a56ae8cafef4810e3a45d87") add_resources("7816", "bx", "https://github.com/bkaradzic/bx.git", "51f25ba638b9cb35eb2ac078f842a4bed0746d56") add_resources("7816", "bimg", "https://github.com/bkaradzic/bimg.git", "8355d36befc90c1db82fca8e54f38bfb7eeb3530") if is_plat("windows") then add_syslinks("user32", "gdi32", "psapi") elseif is_plat("macosx") then add_frameworks("Metal", "QuartzCore", "Cocoa") elseif is_plat("linux") then add_deps("libx11") add_syslinks("GL", "pthread", "dl") end on_load("windows", "macosx", "linux", function (package) local suffix = package:debug() and "Debug" or "Release" for _, lib in ipairs({"bgfx", "bimg", "bx"}) do package:add("links", lib .. suffix) end end) on_install("windows", "macosx", "linux", function (package) local bxdir = package:resourcefile("bx") local bimgdir = package:resourcefile("bimg") local genie = path.join(bxdir, "tools", "bin") if is_host("windows") then genie = path.join(genie, "windows", "genie.exe") elseif is_host("macosx") then genie = path.join(genie, "darwin", "genie") elseif is_host("linux") then genie = path.join(genie, "linux", "genie") end local args = {"--with-tools"} os.trycp(path.join("include", "bgfx"), package:installdir("include")) os.trycp(path.join(bxdir, "include", "*"), package:installdir("include")) os.trycp(path.join(bimgdir, "include", "*"), package:installdir("include")) local mode = package:debug() and "Debug" or "Release" if package:is_plat("windows") then import("package.tools.msbuild") import("core.tool.toolchain") local msvc = toolchain.load("msvc") table.insert(args, "vs" .. msvc:config("vs")) local envs = msbuild.buildenvs(package) envs.BX_DIR = bxdir envs.BIMG_DIR = bimgdir os.vrunv(genie, args, {envs = envs}) local configs = {} table.insert(configs, "/p:Configuration=" .. mode) table.insert(configs, "/p:Platform=" .. (package:is_arch("x64") and "x64" or "Win32")) table.insert(configs, "bgfx.sln") os.cd(format(".build/projects/vs%s", msvc:config("vs"))) msbuild.build(package, configs) os.trycp("../../win*_vs*/bin/*.lib|*example*", package:installdir("lib")) os.trycp("../../win*_vs*/bin/*.exe", package:installdir("bin")) else import("package.tools.make") local configs local target if package:is_plat("macosx") then target = (package:is_arch("x86_64") and "osx-x64" or "osx-arm64") table.insert(args, "--gcc=" .. target) configs = {"-C", ".build/projects/gmake-" .. target, "config=" .. mode:lower()} elseif package:is_plat("linux") then table.insert(args, "--gcc=linux-gcc") target = "linux" .. (package:is_arch("x86_64") and "64" or "32") .. "_gcc" configs = {"-C", ".build/projects/gmake-linux", "config=" .. mode:lower() .. (package:is_arch("x86_64") and "64" or "32")} end table.insert(args, "gmake") local envs = make.buildenvs(package) envs.BX_DIR = bxdir envs.BIMG_DIR = bimgdir os.vrunv(genie, args, {envs = envs}) make.build(package, configs) if package:is_plat("macosx") then os.trycp(".build/" .. target .. "/bin/*.a|*example*", package:installdir("lib")) os.trycp(".build/" .. target .. "/bin/*|.build/*.*", package:installdir("bin")) elseif package:is_plat("linux") then os.trycp(".build/" .. target .. "/bin/*.a|*example*", package:installdir("lib")) os.trycp(".build/" .. target .. "/bin/*|.build/*.*", package:installdir("bin")) end end package:addenv("PATH", "bin") end) on_test(function (package) assert(package:check_cxxsnippets({test = [[ void test() { bgfx::init(); } ]]}, {configs = {languages = "c++14"}, includes = "bgfx/bgfx.h"})) end)
modifier_chashaobao = class({}) function modifier_chashaobao:IsPurgable() return false end function modifier_chashaobao:RemoveOnDeath() return false end function modifier_chashaobao:GetTexture() return "player/chashaobao" end function modifier_chashaobao:OnCreated() self.iHealthRegen = 1.0 self.iIncomingDamage = -8 self.iStatusResist = 8 end function modifier_chashaobao:DeclareFunctions() return { MODIFIER_PROPERTY_HEALTH_REGEN_PERCENTAGE_UNIQUE, MODIFIER_PROPERTY_INCOMING_DAMAGE_PERCENTAGE, MODIFIER_PROPERTY_STATUS_RESISTANCE_STACKING, } end function modifier_chashaobao:GetModifierHealthRegenPercentageUnique() return self.iHealthRegen end function modifier_chashaobao:GetModifierIncomingDamage_Percentage() return self.iIncomingDamage end function modifier_chashaobao:GetModifierStatusResistanceStacking() return self.iStatusResist end
test_run = require('test_run').new() test_run:cmd('restart server default with cleanup=1') fio = require('fio') test_run:cmd("setopt delimiter ';'") function dump_header(path) local f = io.open(path) local header = {} while true do local line = f:read() if line == "" then break end table.insert(header, line) end f:close() return header end; test_run:cmd("setopt delimiter ''"); test_run:cmd("push filter '"..box.info.uuid.."' to '<instance_uuid>'") test_run:cmd("push filter '".._TARANTOOL.."' to '<version>'") checkpoint_lsn = box.info.lsn -- SNAP files snap_name = string.format("%020d.snap", checkpoint_lsn) dump_header(fio.pathjoin(box.cfg.memtx_dir, snap_name)) -- XLOG files box.space._schema:insert({"layout_test"}) xlog_name = string.format("%020d.xlog", checkpoint_lsn) dump_header(fio.pathjoin(box.cfg.wal_dir, xlog_name)) box.space._schema:delete({"layout_test"}) box.snapshot() checkpoint_lsn = box.info.lsn -- SNAP files snap_name = string.format("%020d.snap", checkpoint_lsn) dump_header(fio.pathjoin(box.cfg.memtx_dir, snap_name)) -- XLOG files box.space._schema:insert({"layout_test"}) xlog_name = string.format("%020d.xlog", checkpoint_lsn) dump_header(fio.pathjoin(box.cfg.wal_dir, xlog_name)) box.space._schema:delete({"layout_test"}) test_run:cmd("clear filter")
-- generated from corecrt_wstdio.h local ffi = require 'ffi' ffi.cdef[[ struct _iobuf{ void* _Placeholder; }; typedef struct _iobuf FILE; ]]
return {'aerobic','aerobics','aeroclub','aerodroom','aerodynamica','aerodynamisch','aeronaut','aeronautiek','aeronautisch','aeroob','aerosol','aerostatica','aerobiccen','aerosolverpakking','aerts','aerdt','aernout','aertssen','aertsen','aerssens','aerobe','aeroclubs','aerodynamische','aerosolen','aerobict','aerobicte','aeronauten','aerosolverpakkingen'}
local _, ns = ... local oUF = ns.oUF or oUF ns.PortraitTimerDB = { -- Immunitys [1022] = true, -- Hand of Protection [104773] = true, -- Unending Resolve [18499] = true, -- Berserker Rage [196555] = true, -- Netherwalk (Talent) [204018] = true, -- Blessing of Spellwarding (Talented verion of Blessing of Protection) [33786] = true, -- Cyclone (PvP Talent) [45438] = true, -- Ice Block [46924] = true, -- Bladestorm [47585] = true, -- Dispersion [642] = true, -- Divine Shield -- Stuns [1776] = true, -- Gouge [179057] = true, -- Chaos Nova [1833] = true, -- Cheap Shot [199804] = true, -- Between the Eyes [207165] = true, -- Abomination's Might [211794] = true, -- Winter is Coming [211881] = true, -- Fel Eruption [221562] = true, -- Asphyxiate [22570] = true, -- Maim [30283] = true, -- Shadowfury [408] = true, -- Kidney Shot [46968] = true, -- Shockwave [47481] = true, -- Gnaw [5211] = true, -- Mighty Bash [6770] = true, -- Sap [853] = true, -- Hammer of Justice [88625] = true, -- Holy Word: Chastise [89766] = true, -- Axe Toss [91797] = true, -- Monstrous Blow (Gnaw with DT) -- CC [115078] = true, -- Paralysis [118] = true, -- Polymorph [187650] = true, -- Freezing Trap [20066] = true, -- Repentance [205364] = true, -- Dominant Mind (Talented verion of Mind Control) [2094] = true, -- Blind [217832] = true, -- Imprison [31661] = true, -- Dragon's Breath [339] = true, -- Entangling Roots [51514] = true, -- Hex [5246] = true, -- Intimidating Shout [5484] = true, -- Howl of Terror [5782] = true, -- Fear [605] = true, -- Mind Control [6358] = true, -- Seduction [6789] = true, -- Death Coil [8122] = true, -- Psychic Scream [9484] = true, -- Shackle Undead -- CC immune [1044] = true, -- Hand of Freedom [31224] = true, -- Cloak of Shadows [51271] = true, -- Pillar of Frost [53271] = true, -- Master's Call -- Dmg reductions [186265] = true, -- Aspect of the Turtle [198589] = true, -- Blur [203720] = true, -- Demon Spikes [218256] = true, -- Empower Wards [22812] = true, -- Barkskin [33206] = true, -- Pain Suppression [48707] = true, -- Anti-Magic Shell [48792] = true, -- Icebound Fortitude [498] = true, -- Divine Protection [5277] = true, -- Evasion [61336] = true, -- Survival Instincts [871] = true, -- Shield Wall -- Silences [1330] = true, -- Garrote - Silence [15487] = true, -- Silence (priest) [183752] = true, -- Consume Magic [19647] = true, -- Spell Lock [202137] = true, -- Sigil of Silence [47476] = true, -- Strangulate -- Dmg buffs [211048] = true, -- Chaos Blades [31884] = true, -- Avenging Wrath -- Helpful buffs [121557] = true, -- Feather [1850] = true, -- Dash [23920] = true, -- Spell Reflection (warrior) [2983] = true, -- Sprint [47788] = true, -- Guardian Spirit [68992] = true, -- Darkflight (Worgen racial) [6940] = true, -- Hand of Sacrifice } local Update = function(self, event, unit) if self.unit ~= unit or self.IsTargetFrame then return end local element = self.PortraitTimer local name, texture, duration, expirationTime, spellId local results for i = 1, 40 do name, texture, _, _, duration, expirationTime, _, _, _, spellId = UnitBuff(unit, i) if name then results = ns.PortraitTimerDB[spellId] if results then element.Icon:SetTexture(texture) CooldownFrame_Set(element.cooldownFrame, expirationTime - duration, duration, duration > 0) element:Show() if self.CombatFeedbackText then self.CombatFeedbackText.maxAlpha = 0 end return end end end for i = 1, 40 do name, texture, _, _, duration, expirationTime, _, _, _, spellId = UnitDebuff(unit, i) if name then results = ns.PortraitTimerDB[spellId] if results then element.Icon:SetTexture(texture) CooldownFrame_Set(element.cooldownFrame, expirationTime - duration, duration, duration > 0) element:Show() if self.CombatFeedbackText then self.CombatFeedbackText.maxAlpha = 0 end return end end end element:Hide() if self.CombatFeedbackText then self.CombatFeedbackText.maxAlpha = 1 end if event == "PLAYER_ENTERING_WORLD" then CooldownFrame_Set(element.cooldownFrame, 1, 1, 1) end end local Enable = function(self) local element = self.PortraitTimer if element then self:RegisterEvent("UNIT_AURA", Update) self:RegisterEvent("PLAYER_ENTERING_WORLD", Update, true) if not element.Icon then local mask = element:CreateMaskTexture() mask:SetTexture("Interface\\CHARACTERFRAME\\TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE") mask:SetAllPoints(element) element.Icon = element:CreateTexture(nil, "ARTWORK") element.Icon:SetAllPoints(element) element.Icon:SetTexCoord(0.07, 0.93, 0.07, 0.93) end if not element.cooldownFrame then element.cooldownFrame = CreateFrame("Cooldown", nil, element, "CooldownFrameTemplate") element.cooldownFrame:SetAllPoints(element) element.cooldownFrame:SetHideCountdownNumbers(false) element.cooldownFrame:SetDrawSwipe(false) end element:Hide() return true end end local Disable = function(self) local element = self.PortraitTimer if element then self:UnregisterEvent("UNIT_AURA", Update) self:UnregisterEvent("PLAYER_ENTERING_WORLD", Update) end end oUF:AddElement("PortraitTimer", Update, Enable, Disable)
LANGUAGE = { optDrawSafezones = "Disable rendering of safezones.", optdDrawSafezones = "Disables the drawing of safe zones, such green circles.", optEntityShadows = "Entity shadow drawing", optdEntityShadows = "Sets whether an entity's shadow should be drawn.", optDrawOutlineSZ = "Disable drawing of players in safe zones.", optColorSafezones = "The color of the safe zone.", optColorSafezonePlayers = "The color of the players in the safe zone.", optColorOutlineItems = "Outline color for items.", optdColorOutlineItems = "When you look at an item.", optSquadTeamColor = "Squad color", optdSquadTeamColor = "On the map, chat, etc.", optToggleEffects = "First Person Effects", colors = "Colors", option_remove = "Remove", option_edit = "Edit", option_done = "Done", option_use = "Использовать", Health = "Health", text_yes = "Yes", text_no = "No", global_ooc_disabled = "Global OOC is disabled on this server.", // primary_needs well_fed = "Well fed", needs_hunger = "Hunger", needs_thirst = "Thirst", // stamina Stamina = "Stamina", // radiation Radiation = "Radiation", // enchanced_damage broken_leg = "BROKEN LEG", bleeding_type_mild = "MILD", bleeding_type_average = "AVERAGE", bleeding_type_serious = "SERIOUS", bleeding_type_heavy = "HEAVY", bleeding_blood_loss = "BLOOD LOSS", // safezone safezone_title = "Safezone", // Reputation reputation = "Reputation", combat_logged = "COMBAT LOGGED", cannot_enter_safezone = "CANNOT ENTER SAFEZONE", // chat_channels tradeChatDelay = "You must wait %s more seconds before using trade again!", tradeChatPrefix = "[Trade] ", globalChatPrefix = "[Global] ", localChatPrefix = "[Local] ", squadChatPrefix = "[Squad] ", onlyEnglishLetters = "Only english is allowed in global chat.", cmdTradeChat = "Sends a message in trade chat.", cmdSquadChat = "Sends a message to the squad.", cmdOOC = "Sends a message in global chat.", // Durability Repair = "Repair", RepairKitWrong = 'You do not have a repair kit!', DurabilityUnusableTip = "This weapon is broken.", conditionDesc = "Durability: %s (%s%%)", txtCond0 = "Factory New", txtCond1 = "Almost New", txtCond2 = "Visibly Wornout", txtCond3 = "Barely Functional", txtCond4 = "Broken", weaponJammed = "Your weapon has jammed! Press the RELOAD key.", raiseDurability = "Durability", // Grave here_lies = "Here lies", to_loot = "to loot", grave = "Grave", // Merchant merchant_title = "Merchant", // Stash stash_title = "Stash", stash_title_count = "Stash %d/%d", stash_desc = "Store your items and money here", stash_far = "It is too far from the stash.", stash_full = "There is no room in the stash for this item!", stash_enter_money = "Enter the amount", derma_request_cancel = "Cancel", deposit = "Deposit", withdraw = "Withdraw", // ArcCW ["Empty clip"] = "Empty clip", arccw_alreadyAttached = "This slot is occupied!", Consume = "Consume", Attach = "Attach", Split = "Split", split_enter_quantity = "Enter the quantity", // squad squad_menu_title = "SQUAD MENU", squad_menu_messageday = "Message of the Day", squad_menu_holdername = "Input squad name", squad_menu_holderdesc = "Enter the message of the day", squad_menu_opt_sendpm = "Send PM", squad_menu_opt_message = "Message", squad_menu_btn_raiseofficer = "Raise to officer", squad_menu_btn_ask_raiseofficer = "Are you sure you want to raise?", squad_menu_btn_raise = "Raise", squad_menu_text_Leader = "Leader", squad_menu_text_Officers = "Officers", squad_menu_text_Members = "Members", squad_menu_text_logo = "Logo", squad_menu_text_logo2 = "Squad Logo", squad_menu_holderlogo = "Link to image (only www.imgur.com)", squad_menu_btn_invite = "Invite member", squad_menu_btn_color = "Change squad color", squad_menu_btn_disband = "Disband squad", squad_menu_btn_ask_disband = "Are you sure you want to disband your squad? This action is permanent!", squad_menu_btn_leave = "Leave squad", squad_menu_btn_editdesc = "Edit (max characters: 2048)", squad_menu_btn_save = "Save", squad_menu_btn_demote = "Demote to member", squad_menu_btn_ask_demote = "Are you sure you want to demote?", squad_menu_text_demote = "Demote", squad_menu_btn_kickmember = "Kick member", squad_menu_text_kickmember = "Are you sure you want to kick %s from %s?", squad_leader_disbanded = "The leader has disbanded the squad!", squad_kicked = "You were kicked out of the squad!", squad_successfully_left = "You have successfully left the squad.", squad_create_wait = "The squad is in the process of being created, wait.", squad_promoted_rank = "You were promoted to rank officer.", squad_promoted_rank2 = "Member %s was promoted to rank officer.", squad_demoted_rank = "You were demoted to rank member.", squad_demoted_rank2 = "Member %s was demoted to rank member.", squad_successfully_created = "Squad %s was successfully created!", squad_invite = "%s invites you to his squad %s. Type in chat /saccept", squad_invite_accepted = "%s accepted your invitation to the squad.", squad_invite_accepted2 = "You have been added to a squad: %s", // Flash window optFlashWindow = "Flash Window", optdFlashWindow = "Whether the window should blink when the game is minimized.", // Inventory text_rmb_takeallmoney = "RMB - take all the money", text_rmb_giveallmoney = "RMB - give all the money", text_rmb_dropallmoney = "RMB - drop all the money", take_all = "Take all", // Player spawn points psp_btn_spawnatsafe = "Spawn at Safe Zone", psp_btn_spawnrandomly = "Spawn randomly", psp_btn_disconnect = "Disconnect", // clothes clothes_text_slot = "Slot: %s", // Scoreboard scoreboard_players = "PLAYERS:", // killfeed ["killfeed.death.bledout"] = "bled out", ["killfeed.death.radiation"] = "radiation sickness", ["killfeed.death.drowned"] = "drowned", ["killfeed.death.overdose"] = "overdose", }
Blips = { entities = {}, } function Blips:Add(netId, coords) -- Check duty and entity. if not exports.jobs:IsOnDuty(Config.Marking.Faction) or self.entities[netId] ~= nil then return end -- Create blip. local blip = AddBlipForCoord(coords.x, coords.y, coords.z) SetBlipSprite(blip, 317) SetBlipColour(blip, 49) SetBlipScale(blip, 1.0) SetBlipAsShortRange(blip, true) -- Set blip label. if not self.label then self.label = "IMPOUND_BLIP" AddTextEntry(self.label, "Impound Request") end BeginTextCommandSetBlipName(self.label) EndTextCommandSetBlipName(blip) -- Cache blip. self.entities[netId] = blip end function Blips:Remove(netId) local blip = self.entities[netId] if blip == nil then return end if DoesBlipExist(blip) then RemoveBlip(blip) end self.entities[netId] = nil end function Blips:Update(netId, coords) local blip = self.entities[netId] if blip == nil then return end if DoesBlipExist(blip) then SetBlipCoords(blip, coords.x, coords.y, coords.z) else self.entities[netId] = nil end end function Blips:Clear() for entity, blip in pairs(self.entities) do if DoesBlipExist(blip) then RemoveBlip(blip) end end self.entities = {} end
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end -- Travel local function addTravelKeyword(keyword, text, cost, destination, condition) local travelKeyword = keywordHandler:addKeyword({keyword}, StdModule.say, {npcHandler = npcHandler, text = text, cost = cost, discount = 'postman'}, condition) travelKeyword:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = true, cost = cost, discount = 'postman', destination = destination}) travelKeyword:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, text = 'We would like to serve you some time.', reset = true}) end addTravelKeyword('peg leg', 'Ohhhh. So... <lowers his voice> \'you know who\' sent you so I sail you to \'you know where\'. <wink> <wink> It will cost |TRAVELCOST| to cover my expenses. Is it that what you wish?', 50, Position(32348, 32625, 7), function(player) return player:getStorageValue(Storage.TheShatteredIsles.AccessToMeriana) == 1 end) addTravelKeyword('treasure island', 'Do you seek a passage to Treasure Island for |TRAVELCOST|?', 150, Position(32132, 32913, 7)) keywordHandler:addKeyword({'passage'}, StdModule.say, {npcHandler = npcHandler, text = 'Where do you want to go? To {Treasure Island}?'}) keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, text = 'I am the captain of this ship.'}) keywordHandler:addKeyword({'captain'}, StdModule.say, {npcHandler = npcHandler, text = 'I am the captain of this ship.'}) npcHandler:setMessage(MESSAGE_GREET, "Greetings, daring adventurer. If you need a {passage}, let me know.") npcHandler:setMessage(MESSAGE_FAREWELL, "Good bye.") npcHandler:setMessage(MESSAGE_WALKAWAY, "Oh well.") npcHandler:addModule(FocusModule:new())
getglobal game getfield -1 Workspace getfield -1 Player1 getfield -1 HumanoidRootPart getglobal game getfield -1 Workspace getfield -1 Player2 getfield -1 Torso getfield -1 CFrame setfield -6 CFrame emptystack
-- This file contains the following functions: -- load_rotated_mnist(file_name, count) -- get_transformed(batch_inputs, opt) -- calculate_error(model, data_to_check, opt) -- Loads the dataset from an .amat file. function load_rotated_mnist(file_name, count) local loaded_data = {} for line in io.lines(file_name) do local chunks = {} for w in line:gmatch("%S+") do chunks[#chunks + 1] = tonumber(w) end loaded_data[#loaded_data + 1] = chunks end local loaded_data = torch.Tensor(loaded_data) local data = {} data.data = loaded_data[{{1, count}, {1, -2}}] data.labels = loaded_data[{{1, count}, {-1, -1}}] local shuffled_indices = torch.randperm(data.data:size(1)):long() data.data = data.data:index(1, shuffled_indices) data.labels = data.labels:index(1, shuffled_indices) data.labels:add(1) local real_size = math.sqrt(data.data:size(2)) data.data = data.data:reshape(data.data:size(1), 1, real_size, real_size) print('--------------------------------') print('inputs', data.data:size()) print('targets', data.labels:size()) print('min target', data.labels:min()) print('max target', data.labels:max()) print('--------------------------------') return data end -- Augments the tensor along the second dimension with transformed instances -- (rotation is used here, but various transformations can be used). function get_transformed(batch_inputs, opt) local st = torch.LongStorage(5) st[1] = batch_inputs:size(1) -- the number of images st[2] = opt.n_transformations st[3] = 1 -- the number of channels is 1 st[4] = opt.input_size st[5] = opt.input_size local result = torch.Tensor(st) for index = 1, batch_inputs:size(1) do local padded_sample = torch.Tensor(opt.input_size, opt.input_size):zero() local offset = (opt.input_size - opt.real_size) / 2 padded_sample[{{1 + offset, opt.input_size - offset}, {1 + offset, opt.input_size - offset}}] = batch_inputs[index]:squeeze() padded_sample = padded_sample:t():contiguous() for angle_index = 1, opt.n_transformations do result[index][angle_index][1] = image.rotate(padded_sample, 2 * math.pi * angle_index / opt.n_transformations, 'bilinear') end end return result end -- Calculates the number of mispredictions of the trained model. function calculate_error(model, data_to_check, opt) model:evaluate() local data_size = data_to_check.data:size(1) local batches_per_dataset = math.ceil(data_size / opt.batch_size) local error = 0 for batch_index = 0, (batches_per_dataset - 1) do local start_index = batch_index * opt.batch_size + 1 local end_index = math.min(data_size, (batch_index + 1) * opt.batch_size) local batch_targets = data_to_check.labels[{{start_index, end_index},1}]:cuda() local transformed_batch = data_to_check.data[{{start_index, end_index}}] local batch_inputs = transformed_batch:cuda() local logProbs = model:forward(batch_inputs) local classProbabilities = torch.exp(logProbs) local _, max_inds = torch.max(classProbabilities, 2) classPredictions = torch.Tensor():resize(max_inds:size(1)) :copy(max_inds[{{1,max_inds:size(1)},1}]):cuda() error = error + classPredictions:ne(batch_targets):sum() end model:training() return error / data_size end
--[[ @author gilaga4815 Last Update : 6 / 8 / 2021 A-Chassis Vehicle Output Interpreter Bootstrapper ]] -- Services local SelectionService = game:GetService("Selection") local StudioService = game:GetService("StudioService") local LogService = game:GetService("LogService") local OutputAnalyzer = require(script.Parent:WaitForChild("OutputAnalyzer")) local UI_Util = require(script.Parent:WaitForChild("UI_Utility")) local UI_Enums = require(script.Parent:WaitForChild("UI_Utility"):WaitForChild("UI_Enums")) local lastLogTime = plugin:GetSetting("LastLogTime") -- Enums for the plugin display here local debugWidgetData = DockWidgetPluginGuiInfo.new(Enum.InitialDockState.Float,false,false,100,200,50, 100) local ancestryConnections = {} -- Plugin Setup local backButton = nil local function searchUntilPlugin(currentAsset) if currentAsset.Parent.Name ~= "Plugins" and currentAsset.Parent ~= game.Workspace then return searchUntilPlugin(currentAsset.Parent) else return currentAsset end end -- GUI Handling local function scriptSelector(parentTo, scriptAsset) -- scriptAsset is the broken script that the plugins is looking for. local scriptButton = UI_Util.CreateClassButton(false, scriptAsset:IsA("LocalScript") and "LocalScript" or "Script") scriptButton.Name = scriptAsset.Name scriptButton.Text = " " .. scriptAsset.Name UI_Util.SetupButton( scriptButton, parentTo, function(returnValue) local selectAsset = searchUntilPlugin(scriptAsset) -- this will get the correct plugin path of the azsset if returnValue then SelectionService:Add({selectAsset}) else SelectionService:Remove({selectAsset}) end end, { MouseEnterLeave = true, Toggleable = true, } ) -- Script Connections ancestryConnections[#ancestryConnections + 1] = scriptAsset.AncestryChanged:Connect(function() if not scriptAsset:IsDescendantOf(game) then scriptButton:Destroy() end end) end local function createCarSelector(parentTo, carModel) local newButton = UI_Util.CreateClassButton(true, "Model") newButton.Name = carModel.Name newButton.Text = " " .. newButton.Name UI_Util.SetupButton( newButton, parentTo, function(returnValue) if not returnValue then return end for i = 1, #ancestryConnections do ancestryConnections[i]:Disconnect() end UI_Util.ClearFrame(parentTo, {backButton}) backButton.Visible = true backButton.Parent = parentTo -- Handle the actual output stuff now local newAnalyses = OutputAnalyzer.New(carModel) local scanResults = newAnalyses:PerformScan(lastLogTime) if scanResults then for i = 1, #scanResults do scriptSelector(parentTo, scanResults[i]) end else local newDisclaimer = Instance.new("TextLabel", parentTo) newDisclaimer.Size = UDim2.new(1, 0, 0, 200) newDisclaimer.BorderSizePixel = 0 newDisclaimer.BackgroundColor3 = UI_Enums.StudioColorValues.Main newDisclaimer.TextColor3 = Color3.fromRGB(255, 255, 0) newDisclaimer.TextXAlignment = Enum.TextXAlignment.Center newDisclaimer.TextScaled = true newDisclaimer.Font = Enum.Font.TitilliumWeb newDisclaimer.Text = "After scanning the vehicle no errors were found. However this may be because you never tested this vehicle.\nIf this is the case please test the vehicle for as long as you would like, in order to gather error data from the vehicle\nin order for this plugin to work. Please hit [BACK]\n or start a new session." end newAnalyses:Destroy() end, { MouseEnterLeave = true, DoubleClick = true, } ) end -- Element Setup -- Plugin Specific Stuff local debugToolbar = plugin:CreateToolbar("Chassis Debug Tool") local showDebugFrame = debugToolbar:CreateButton("Tool Output", "Toggle Tool Output", "rbxassetid://6903761098") local debugWidget = plugin:CreateDockWidgetPluginGui("AC_DebugOutput", debugWidgetData) debugWidget.Title = "AC Broken Plugins" -- Regular UI Stuff local outputFrame = Instance.new("ScrollingFrame", debugWidget) local outputLayout = Instance.new("UIListLayout", outputFrame) outputFrame.Size = UDim2.new(1, 0, 1, 0) outputFrame.BackgroundColor3 = UI_Enums.StudioColorValues.Main outputFrame.BorderSizePixel = 0 outputFrame.ScrollBarThickness = 10 outputFrame.ScrollBarImageColor3 = UI_Enums.StudioColorValues.ScrollBar outputFrame.CanvasSize = UDim2.new(0, 0, 0, outputLayout.AbsoluteContentSize.Y) outputLayout.SortOrder = Enum.SortOrder.LayoutOrder -- Create a single use back button so it doesn't need to be created later backButton = UI_Util.CreateClassButton() backButton.Name = "Back" backButton.Text = "BACK" backButton.Visible = false backButton.LayoutOrder = 2 UI_Util.SetupButton( backButton, outputFrame, function() backButton.Visible = false UI_Util.ClearFrame(outputFrame, {backButton}) for _, v in pairs(game.Workspace:GetDescendants()) do if v:FindFirstChild("DriveSeat") then createCarSelector(outputFrame, v) end end end ) -- Connections and calls here outputLayout:GetPropertyChangedSignal("AbsoluteContentSize"):Connect(function() outputFrame.CanvasSize = UDim2.new(0, 0, 0, outputLayout.AbsoluteContentSize.Y) end) showDebugFrame.Click:Connect(function() debugWidget.Enabled = not debugWidget.Enabled end) plugin.Unloading:Connect(function() local lastLog = (LogService:GetLogHistory() ~= nil) and LogService:GetLogHistory()[#LogService:GetLogHistory()].timestamp print(lastLog) plugin:SetSetting("LastLogTime", lastLog or nil) end) for _, car in pairs(game.Workspace:GetChildren()) do if car:FindFirstChild("DriveSeat") then createCarSelector(outputFrame, car) end end
-- A Redis script is transactional by definition -- http://redis.io/topics/transactions local channel = KEYS[1] -- get oldest message in processing list local messageId = redis.call('RPOP', channel .. ".processing") if not messageId then -- processing list is empty redis.call('set', 'debug', 'return nil') return -1 end if true == redis.call('EXISTS', channel .. ".alive." .. messageId) then -- oldest item in processing list is not timed-out yet return -2 end local rawJson = redis.call('GET', channel .. ".value." .. messageId) local message = cjson.decode(rawJson) -- last processing attempt cost us one counter, decrement message['counter'] = message['counter'] - 1 -- if at least one processing attempt remains, reinsert to queue if message['counter'] >= 1 then -- item has remaining retries, update counter and reinsert to queue redis.call('SET', channel .. ".value." .. messageId, cjson.encode(message)) redis.call('LPUSH', channel .. ".queue", messageId) -- set value used by Message::isFailedPermanently() message['failed'] = false return cjson.encode(message) else message['failed'] = true return cjson.encode(message) end
ESX = nil function defESX() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Wait(0) end end Citizen.CreateThread(function() defESX() end) function Notification(msg) SetNotificationTextEntry('STRING') AddTextComponentSubstringPlayerName(msg) DrawNotification(false, true) end RegisterNetEvent("dReport:Notification") AddEventHandler("dReport:Notification", function(msg) Notification(msg) end) RegisterNetEvent("dReport:Open/CloseReport") AddEventHandler("dReport:Open/CloseReport", function(type, nomdumec, raisondumec) if type == 1 then ESX.TriggerServerCallback('dReport:getUsergroup', function(group) if group == 'superadmin' or group == 'admin' or group == 'mod' then ESX.ShowNotification('Un nouveau report à été effectué !') end end) elseif type == 2 then ESX.TriggerServerCallback('dReport:getUsergroup', function(group) if group == 'superadmin' or group == 'admin' or group == 'mod' then ESX.ShowNotification('Le report de ~b~'..nomdumec..'~s~ à été fermé !') end end) end end) function setpsurlemec(iddumec) if iddumec then local PlayerPos = GetEntityCoords(GetPlayerPed(GetPlayerFromServerId(iddumec))) SetEntityCoords(PlayerPedId(), PlayerPos.x, PlayerPos.y, PlayerPos.z) end end function tplemecsurmoi(iddugars) if iddugars then local plyPedCoords = GetEntityCoords(PlayerPedId()) TriggerServerEvent('dReport:bring', iddugars, plyPedCoords, "bring") end end RegisterNetEvent('dReport:bring') AddEventHandler('dReport:bring', function(plyPedCoords) plyPed = PlayerPedId() SetEntityCoords(plyPed, plyPedCoords) end) function KeyboardInput(TextEntry, ExampleText, MaxStringLenght) AddTextEntry('FMMC_KEY_TIP1', TextEntry) DisplayOnscreenKeyboard(1, "FMMC_KEY_TIP1", "", ExampleText, "", "", "", MaxStringLenght) blockinput = true while UpdateOnscreenKeyboard() ~= 1 and UpdateOnscreenKeyboard() ~= 2 do Wait(0) end if UpdateOnscreenKeyboard() ~= 2 then local result = GetOnscreenKeyboardResult() Wait(500) blockinput = false return result else Wait(500) blockinput = false return nil end end
local skynet = require "skynet" local datacenter = require "skynet.datacenter" local mysocket = require "mysocket" local pm = require "playerctrl" local tm = require "tablectrl" local utils = require "myfunlib.base_tips.utils" local MsgList = require 'MsgList' local comman_msg = MsgList.comman local CMD = {} local db local group_list = {} --创建房间 local ret_create = {mode="hall",cmd = "create",info ={game_id=1}} --加入房间 进入游戏 local ret_join = {mode="hall",cmd = "create",info ={gid = 1,game_id=1}} --退出房间 local ret_exit = {mode="any",cmd = "exit",info ={gid=1}} --提出解散房间 local ret_tidel = {mode="any",cmd = "tidel",info ={text="",user={}}} --是否同意解散房间 local ret_agdel = {mode="any",cmd = "agdel",info ={uid="",name="",agree=false,isover=false}} function echo_user(user,uid) if user[tostring(uid)] then return user[tostring(uid)] end return nil end function get_group(uid) for key, value in pairs(group_list) do if echo_user(value.uids,uid) then return value end end return nil end function get_groupfds(group) local fd_list = {} for k, v in pairs(group.uids) do local user = pm.get(v) if user then table.insert(fd_list,user.fd) end end return fd_list end function get_groupusers(group) local user_list = {} for k, v in pairs(group.uids) do local user = pm.get(v) if user then table.insert(user_list,user) end end return user_list end --更新到共享数据中 function update_group() datacenter.set("group_list",group_list) end --没1分种清理一次pm 当user.fd 为负数时且不在 不在任何group中只就可以把user删了 --随便保存一下数据 function cls_pm() local player_list = pm.getlist() for k, v in pairs(player_list) do if v.fd<0 and get_group(v.uid)==nil then pm.del(v.uid) print("pm clear "..v.uid) end end end function speed_test(uid) --不在任何组中 创建组 pm.add({uid = uid,nick_name = "123",touxian = "123"},-uid) msg = {fd = -uid,rule={wanfa=1,difen=1,jushu=8,fanfei=1,ip=0}} CMD.create_group(msg) end --添加机器人 local g_robid = 100000 function add_robit(group,count) for i=1,count,1 do local rouid = -(g_robid) g_robid = g_robid+1 --添加机器人 pm.add({uid = rouid,nick_name = "rob"..rouid,touxian = "http://thirdwx.qlogo.cn/mmopen/vi_32/3EB7dFdNRKmjHmkRpGvjqZh2ia0Oj69tticicvb3T2lsFDricb4Sc7YPHhPlJvolJ8uv5GaibSk65q1g4IDz5R5hS1w/132"},rouid) --机器人加入 CMD.join_group({fd = rouid,uid = rouid,gid=group.gid}) skynet.send(group.ser, "lua", "ready",{fd = rouid}) end end function CMD.disconnect(fd) --断开只改fd为0(不会影响游戏逻辑中用uid从pm中更新fd_list -- 和用fd_list从pm得到user --对于原路返回的fd不可能为负数所以user在pm得不到 local user = pm.getbyfd(fd) if user then user.fd = -user.uid pm.set(user) print("disconnect uid"..user.uid) end end --解散房间 function CMD.tidel(msg) local user = pm.getbyfd(msg.fd) if user then local group = get_group(user.uid) if group then local uid = user.uid local gid = group.gid local users = get_groupusers(group) group_list[gid].agdel = {} ret_tidel.info.text = user.nick_name print("#users"..#users) ret_tidel.info.user = {} for i=1,#users,1 do ret_tidel.info.user[i] = {state=0,name,uid} ret_tidel.info.user[i].uid = users[i].uid ret_tidel.info.user[i].name = users[i].nick_name ret_tidel.info.user[i].touxian = users[i].touxian ret_tidel.info.user[i].state = 1 group_list[gid].agdel[users[i].uid] = 0--0等待 1同意 2 不同意 if tonumber(users[i].uid) < 0 then group_list[gid].agdel[users[i].uid] = 1 end end local fd_list = get_groupfds(group) mysocket.writebro(fd_list,ret_tidel) --挂起游戏 skynet.call(group.ser, "lua", "game_hang",true) else comman_msg.showbox.info.msg = "已不在房间中" mysocket.write(user.fd, comman_msg.showbox) end end end --是否同意解散房间 function CMD.agdel(msg) local user = pm.getbyfd(msg.fd) if user then local group = get_group(user.uid) if group then local uid = user.uid local gid = group.gid local agree_count = 0 local disagree_count = 0 if msg.info.agree then group_list[gid].agdel[uid] = 1 else group_list[gid].agdel[uid] = 2 end for k, v in pairs(group.uids) do if group_list[gid].agdel[v]==1 then agree_count = agree_count+1 elseif group_list[gid].agdel[v]==2 then disagree_count = disagree_count+1 end end local fd_list = get_groupfds(group) local user_count = (#fd_list) print("user_count"..user_count.."disagree_count"..disagree_count.."agree_count"..agree_count) ret_agdel.info.uid = uid ret_agdel.info.name = user.nick_name ret_agdel.info.agree = msg.info.agree ret_agdel.info.isover = (disagree_count>=user_count*0.5) or (agree_count>=user_count*0.5) mysocket.writebro(fd_list,ret_agdel) --役票结束 不挂起 if ret_agdel.info.isover then skynet.call(group.ser, "lua", "game_hang",false) end if disagree_count>=(#fd_list)*0.5 then --不解散房间 comman_msg.showbox.info.msg = "玩家大多数不同意解散!" mysocket.writebro(fd_list,comman_msg.showbox) elseif agree_count>=(#fd_list)*0.5 then --解散房间 print("remove group and stop ser") mysocket.writebro(fd_list, {mode="hall",cmd="showbox",info={msg = "游戏已解散"}}) mysocket.writebro(fd_list,ret_exit)--退出房间 skynet.send(group.ser, "lua", "disconnect") group_list[group.gid] = nil end end end end -- function CMD.exit_group(msg) local user = pm.getbyfd(msg.fd) if user then local group = get_group(user.uid) if group then --只有一个玩家时才可以退出 local user_count = 0 for k, v in pairs(group.uids) do user_count = user_count+1 end --100 等待准备 --102 游戏结束局数已到 local game_state = skynet.call(group.ser, "lua", "game_state",msg) --当玩家需要退出房间时要从游戏逻辑中判断是否能退出 if game_state == 102 then for k, v in pairs(group.uids) do if v == user.uid then group.uids[k] = nil skynet.call(group.ser, "lua", "exit_group",msg) print(user.uid.." exit_group") end end if skynet.table_size(group.uids)==0 then print("remove group and stop ser") skynet.send(group.ser, "lua", "disconnect") group_list[group.gid] = nil end end end end end -- function CMD.join_group(msg) local user = pm.getbyfd(msg.fd) if user then local group = get_group(user.uid) local ret_msg = {mode="hall",cmd="showbox",info={msg = ""}} if group then ret_join.info.gid = group.gid ret_join.info.game_id = group.game_id mysocket.write(msg.fd, ret_join) --重启游戏 skynet.call(group.ser, "lua", "resgame",msg) comman_msg.showbox.info.msg = "自动跳转到原来房间,要退出请先解散。" mysocket.write(msg.fd, comman_msg.showbox) --print("已在组中") else group =group_list[msg.gid] if group and skynet.table_size(group.uids)< group.maxuser then group.uids[tostring(user.uid)] = user.uid update_group() ret_join.info.gid = group.gid ret_join.info.game_id = group.game_id mysocket.write(msg.fd, ret_join) skynet.call(group.ser, "lua", "join",msg) --print("房间 join ok "..user.uid) elseif group == nil then ret_msg.info.msg = "房间不存在" mysocket.write(msg.fd, ret_msg) --print("房间不存在") else ret_msg.info.msg = "房间已满人" mysocket.write(msg.fd, ret_msg) --print("房间已满人") end end end end -- function CMD.create_group(msg) local fd = msg.fd local ser = nil local index = (#group_list)+1; --查找是否在其中的一个组里 local user = pm.getbyfd(fd) if user then local group = get_group(user.uid) if group then --已在组中 客户要进入游戏中 ret_join.info.gid = group.gid ret_join.info.game_id = group.game_id mysocket.write(msg.fd, ret_join) --重启游戏 skynet.send(group.ser, "lua", "resgame",msg) comman_msg.showbox.info.msg = "自动跳转到原来房间,要退出请先解散。" mysocket.write(msg.fd, comman_msg.showbox) print("已在组中") else --不在任何组中 创建组 --扣房费 local fanfei = {1,2} local needfanfei = fanfei[msg.rule.fanfei] if user.card - needfanfei >=0 then user.card = user.card-needfanfei pm.set(user) local ser = skynet.newservice("kddmj") group = {uids = {},fzuid = 0,agdel={},ser = ser,game_id = 1,maxuser = 4,rule={}} group.fzuid = user.uid group.rule = msg.rule group.gid = math.random(100000,888888)+user.uid group_list[group.gid] = group update_group() skynet.call(ser, "lua", "start",group.gid) add_robit(group,2) --加入到此房间中 CMD.join_group({fd = msg.fd,uid = user.uid,gid=group.gid}) --添加机器人 print("创建房间 "..group.gid) ret_create.info.gid = group.gid ret_create.info.game_id = group.game_id mysocket.write(msg.fd, ret_create) else comman_msg.showbox.info.msg = "房卡不足请充值" mysocket.write(msg.fd,comman_msg.showbox) end end else --no login end end -- function CMD.game_msg(msg) local user = pm.getbyfd(msg.fd) if user then local group = get_group(user.uid) if group then msg.info.fd = msg.fd skynet.call(group.ser, "lua", msg.game_cmd , msg.info) end end end skynet.start(function() db = datacenter.get("db") pm.init(datacenter.get("pm")) tm.init(datacenter.get("tm")) skynet.fork(function() skynet.sleep(200) for i=1,200,1 do --speed_test(os.time()+math.random(5000,8000)) --print("speed_test "..i) end end) skynet.fork(function() while true do update_group() skynet.sleep(1) end end) skynet.fork(function() while true do cls_pm() skynet.sleep(1000*60) end end) skynet.dispatch("lua", function(session, source, cmd, subcmd, ...) local f = CMD[cmd] if f then skynet.ret(skynet.pack(f(subcmd, ...))) end end) end)
local drawableFunction = {} function drawableFunction.fromFunction(func, ...) local drawable = { _type = "drawableFunction" } drawable.func = func drawable.args = {...} drawable.draw = function(self) self.func(unpack(self.args)) end return drawable end return drawableFunction
------------------------------------------------------------------------------- -- Module Declaration -- local mod, CL = BigWigs:NewBoss("High Priest Venoxis", 859, 175) if not mod then return end mod:RegisterEnableMob(52155) mod.engageId = 1178 mod.respawnTime = 30 -------------------------------------------------------------------------------- -- Locals -- local breathsLeft = 2 ------------------------------------------------------------------------------- -- Initialization -- function mod:GetOptions() return { {96477, "ICON", "FLASH"}, -- Toxic Link 96509, -- Breath of Hethiss 96466, -- Whispers of Hethiss 96842, -- Bloodvenom 96653, -- Venom Withdrawal (triggered by 96512) } end function mod:OnBossEnable() self:Log("SPELL_AURA_APPLIED", "ToxicLink", 96477) self:Log("SPELL_AURA_REMOVED", "ToxicLinkRemoved", 96477) self:Log("SPELL_AURA_APPLIED", "BreathOfHethiss", 96509) self:Log("SPELL_AURA_APPLIED", "WhispersOfHethiss", 96466) self:Log("SPELL_AURA_REMOVED", "WhispersOfHethissRemoved", 96466) self:Log("SPELL_CAST_START", "Bloodvenom", 96842) self:Log("SPELL_AURA_APPLIED", "BlessingOfTheSnakeGod", 96512) self:Log("SPELL_AURA_REMOVED", "BlessingOfTheSnakeGodRemoved", 96512) end function mod:OnEngage() breathsLeft = 2 end ------------------------------------------------------------------------------- -- Event Handlers -- do local linkTargets = mod:NewTargetList() function mod:ToxicLink(args) if self:Me(args.destGUID) then self:Flash(args.spellId) end linkTargets[#linkTargets + 1] = args.destName if #linkTargets == 1 then self:ScheduleTimer("TargetMessage", 0.2, args.spellId, linkTargets, "orange", "Alarm") self:PrimaryIcon(args.spellId, args.destName) else self:SecondaryIcon(args.spellId, args.destName) end end function mod:ToxicLinkRemoved(args) self:PrimaryIcon(args.spellId) self:SecondaryIcon(args.spellId) end end function mod:BreathOfHethiss(args) breathsLeft = breathsLeft - 1 self:Message(args.spellId, "red") if (breathsLeft > 0) then self:CDBar(args.spellId, 12) end end function mod:WhispersOfHethiss(args) if self:MobId(args.destGUID) == 52155 then return end -- applies this to himself as well self:Message(args.spellId, "orange", "Alert", CL.casting:format(args.spellName)) self:TargetBar(args.spellId, 8, args.destName) end function mod:WhispersOfHethissRemoved(args) if self:MobId(args.destGUID) == 52155 then return end -- applies this to himself as well self:StopBar(args.spellName, args.destName) end function mod:Bloodvenom(args) self:Message(args.spellId, "red", "Alert", CL.casting:format(args.spellName)) self:ScheduleTimer("Bar", 3, args.spellId, 14) end function mod:BlessingOfTheSnakeGod() breathsLeft = 2 self:CDBar(96842, 38) -- Bloodvenom self:CDBar(96509, 5.5) -- Breath of Hethiss end function mod:BlessingOfTheSnakeGodRemoved() self:Message(96653, "green", "Info") -- Venom Withdrawal self:Bar(96653, 10) end
description = [[ Crawls webservers in search of RFI (remote file inclusion) vulnerabilities. It tests every form field it finds and every parameter of a URL containing a query. ]] --- -- @usage -- nmap --script http-rfi-spider -p80 <host> -- -- -- @output -- PORT STATE SERVICE REASON -- 80/tcp open http syn-ack -- | http-rfi-spider: -- | Possible RFI in form at path: /pio/rfi_test2.php, action: /rfi_test2.php for fields: -- | color -- |_ inc -- -- @args http-rfi-spider.inclusionurl the url we will try to include, defaults -- to <code>http://tools.ietf.org/html/rfc13?</code> -- @args http-rfi-spider.pattern the pattern to search for in <code>response.body</code> -- to determine if the inclusion was successful, defaults to -- <code>'20 August 1969'</code> -- @args http-rfi-spider.maxdepth the maximum amount of directories beneath -- the initial url to spider. A negative value disables the limit. -- (default: 3) -- @args http-rfi-spider.maxpagecount the maximum amount of pages to visit. -- A negative value disables the limit (default: 20) -- @args http-rfi-spider.url the url to start spidering. This is a URL -- relative to the scanned host eg. /default.html (default: /) -- @args http-rfi-spider.withinhost only spider URLs within the same host. -- (default: true) -- @args http-rfi-spider.withindomain only spider URLs within the same -- domain. This widens the scope from <code>withinhost</code> and can -- not be used in combination. (default: false) -- author = "Piotr Olma" license = "Same as Nmap--See http://nmap.org/book/man-legal.html" categories = {"intrusive"} local shortport = require 'shortport' local http = require 'http' local stdnse = require 'stdnse' local url = require 'url' local httpspider = require 'httpspider' local string = require 'string' local table = require 'table' -- this is a variable that will hold the function that checks if a pattern we are searching for is in -- response's body local check_response -- this variable will hold the injection url local inclusion_url -- checks if a field is of type we want to check for rfi local function rfi_field(field_type) return field_type=="text" or field_type=="radio" or field_type=="checkbox" or field_type=="textarea" end -- generates postdata with value of "sampleString" for every field (that satisfies rfi_field()) of a form local function generate_safe_postdata(form) local postdata = {} for _,field in ipairs(form["fields"]) do if rfi_field(field["type"]) then postdata[field["name"]] = "sampleString" end end return postdata end -- checks each field of a form to see if it's vulnerable to rfi local function check_form(form, host, port, path) local vulnerable_fields = {} local postdata = generate_safe_postdata(form) local sending_function, response local form_submission_path = url.absolute(path, form.action) if form["method"]=="post" then sending_function = function(data) return http.post(host, port, form_submission_path, nil, nil, data) end else sending_function = function(data) return http.get(host, port, form_submission_path.."?"..url.build_query(data), nil) end end for _,field in ipairs(form["fields"]) do if rfi_field(field["type"]) then stdnse.debug2("checking field %s", field["name"]) postdata[field["name"]] = inclusion_url response = sending_function(postdata) if response and response.body and response.status==200 then if check_response(response.body) then vulnerable_fields[#vulnerable_fields+1] = field["name"] end end postdata[field["name"]] = "sampleString" end end return vulnerable_fields end -- builds urls with a query that would let us decide if a parameter is rfi vulnerable local function build_urls(injectable) local new_urls = {} for _,u in ipairs(injectable) do if type(u) == "string" then local parsed_url = url.parse(u) local old_query = url.parse_query(parsed_url.query) for f,v in pairs(old_query) do old_query[f] = inclusion_url parsed_url.query = url.build_query(old_query) table.insert(new_urls, url.build(parsed_url)) old_query[f] = v end end end return new_urls end -- as in sql-injection.nse local function inject(host, port, injectable) local all = nil for k, v in pairs(injectable) do all = http.pipeline_add(v, nil, all, 'GET') end return http.pipeline_go(host, port, all) end local function check_responses(urls, responses) if responses == nil or #responses==0 then return {} end local suspects = {} for i,r in ipairs(responses) do if r.body then if check_response(r.body) then local parsed = url.parse(urls[i]) if suspects[parsed.path] then table.insert(suspects[parsed.path], parsed.query) else suspects[parsed.path] = {} table.insert(suspects[parsed.path], parsed.query) end end end end return suspects end portrule = shortport.port_or_service( {80, 443}, {"http", "https"}, "tcp", "open") function action(host, port) inclusion_url = stdnse.get_script_args('http-rfi-spider.inclusionurl') or 'http://tools.ietf.org/html/rfc13?' local pattern_to_search = stdnse.get_script_args('http-rfi-spider.pattern') or '20 August 1969' -- once we know the pattern we'll be searching for, we can set up the function check_response = function(body) return string.find(body, pattern_to_search) end -- create a new crawler instance local crawler = httpspider.Crawler:new( host, port, nil, { scriptname = SCRIPT_NAME} ) if ( not(crawler) ) then return end local return_table = {} while(true) do local status, r = crawler:crawl() if ( not(status) ) then if ( r.err ) then return stdnse.format_output(true, ("ERROR: %s"):format(r.reason)) else break end end -- first we try rfi on forms if r.response and r.response.body and r.response.status==200 then local all_forms = http.grab_forms(r.response.body) for _,form_plain in ipairs(all_forms) do local form = http.parse_form(form_plain) local path = r.url.path if form and form.action then local vulnerable_fields = check_form(form, host, port, path) if #vulnerable_fields > 0 then vulnerable_fields["name"] = "Possible RFI in form at path: "..path..", action: "..form["action"].." for fields:" table.insert(return_table, vulnerable_fields) end end end --for end --if -- now try inclusion by query parameters local injectable = {} -- search for injectable links (as in sql-injection.nse) if r.response.status and r.response.body then local links = httpspider.LinkExtractor:new(r.url, r.response.body, crawler.options):getLinks() for _,u in ipairs(links) do local url_parsed = url.parse(u) if url_parsed.query then table.insert(injectable, u) end end end if #injectable > 0 then local new_urls = build_urls(injectable) local responses = inject(host, port, new_urls) local suspects = check_responses(new_urls, responses) for p,q in pairs(suspects) do local vulnerable_fields = q vulnerable_fields["name"] = "Possible RFI in parameters at path: "..p.." for queries:" table.insert(return_table, vulnerable_fields) end end end return stdnse.format_output(true, return_table) end
application = { content = { width = 600, height = 1024, scale = "Letterbox", fps = 60, antialias = true, imageSuffix = { ["@2x"] = 2, }, }, }
data.raw["utility-constants"].default.ghost_tint = { r = settings.startup['blue-ghosts-r'].value, g = settings.startup['blue-ghosts-g'].value, b = settings.startup['blue-ghosts-b'].value, a = settings.startup['blue-ghosts-alpha'].value } for _, drill in pairs(data.raw["mining-drill"]) do if drill.radius_visualisation_picture ~= nil then drill.radius_visualisation_picture.filename = "__Blue-Ghosts__/graphics/electric-mining-drill-radius-visualization.png" drill.radius_visualisation_picture.tint = { r = settings.startup['blue-ghosts-drill-area-r'].value, g = settings.startup['blue-ghosts-drill-area-g'].value, b = settings.startup['blue-ghosts-drill-area-b'].value, a = settings.startup['blue-ghosts-drill-area-alpha'].value } end end
Class("Slider")( { ["load"] = function(s) table.insert(GUIs, s) end, ["clickedOn"] = false, ["hoverShadingPercent"] = 20, --Better to have a darker shading because it's harder to see on a slider ["mouseDownShadingPercent"] = 30, ["slots"] = 6, --How many slots for the slideRectangle to fit into. ["slotsVisible"] = true, --Do the slots display? ["slotsColor"] = {0.4, 0.5, 0.4, 1}, ["slotsSize"] = {2, 5}, --How big are the slots drawn? ["slotsOnBar"] = true, --If true the slots appear centered on the bar rather than below. ["slideRectangleSize"] = {4, 10}, ["slideRectanglePosition"] = 1, --Measured in slots not pixels. ["slideRectangleBorderColor"] = {0.3, 0.8, 0.9, 1}, ["slideRectangleBackgroundColor"] = {0.4, 0.5, 0.4, 1}, ["slideRectangleBorderWidth"] = 2, ["sliderBarHeight"] = 1, --How tall the bar the slider sits on is. --Overwride gDraw and gUpdate. ["gDraw"] = function(se, Args) love.graphics.setColor(unpack(se.backgroundColor)) love.graphics.draw( GUIGraphics["spotImg"], se.position[1], se.position[2] + se.size[2] / 2 - se.sliderBarHeight / 2, 0, se.size[1], se.sliderBarHeight ) if se.borderVisible then love.graphics.setColor(unpack(se.borderColor)) drawBorder( se.position[1], se.position[2] + se.size[2] / 2 - se.sliderBarHeight / 2, se.size[1], se.sliderBarHeight, se.borderWidth ) end local slotDistance = se.size[1] / se.slots if se.slotsVisible then love.graphics.setColor(unpack(se.slotsColor)) if se.slotsOnBar then for i = 1, se.slots do love.graphics.draw( GUIGraphics["spotImg"], se.position[1] + slotDistance * i - se.slotsSize[1] / 2 - slotDistance / 2, se.position[2] + se.size[2] / 2 - se.slotsSize[2] / 2, 0, se.slotsSize[1], se.slotsSize[2] ) end else for i = 1, se.slots do love.graphics.draw( GUIGraphics["spotImg"], se.position[1] + slotDistance * i - se.slotsSize[1] / 2 - slotDistance / 2, se.position[2] + se.size[2] / 2, 0, se.slotsSize[1], se.slotsSize[2] ) end end end local sliderPosition = { se.position[1] + slotDistance * se.slideRectanglePosition - slotDistance / 2 - se.slideRectangleSize[1] / 2, se.position[2] + se.size[2] / 2 - se.slideRectangleSize[2] / 2 } love.graphics.setColor(unpack(se.slideRectangleBackgroundColor)) love.graphics.draw( GUIGraphics["spotImg"], sliderPosition[1], sliderPosition[2], 0, se.slideRectangleSize[1], se.slideRectangleSize[2] ) love.graphics.setColor(unpack(se.slideRectangleBorderColor)) drawBorder(sliderPosition[1], sliderPosition[2], se.slideRectangleSize[1], se.slideRectangleSize[2], 2) if se.shadingVisible then if se.mouseLDown then drawShading( sliderPosition[1], sliderPosition[2], se.slideRectangleSize[1], se.slideRectangleSize[2], se.mouseDownShadingPercent ) elseif se.mouseHovering then drawShading( sliderPosition[1], sliderPosition[2], se.slideRectangleSize[1], se.slideRectangleSize[2], se.hoverShadingPercent ) end end end, ["update"] = function(se, Time) local slotDistance = se.size[1] / se.slots local sliderPosition = { se.position[1] + slotDistance * se.slideRectanglePosition - slotDistance / 2 - se.slideRectangleSize[1] / 2, se.position[2] + se.size[2] / 2 - se.slideRectangleSize[2] / 2 } if se.mouseLDown then if mousePosition[1] < se.position[1] then se.slideRectanglePosition = 1 elseif mousePosition[1] > se.position[1] + se.size[1] then se.slideRectanglePosition = se.slots else for i = 1, se.slots do --Any more efficient way of finding closest? :L if mousePosition[1] < se.position[1] + i * slotDistance then se.slideRectanglePosition = i break end end end end end, ["gUpdate"] = function(self, dt) --Cache values for events local previously = { ["bld"] = self.mouseLDown, ["brd"] = self.mouseRDown, ["mh"] = self.mouseHovering, ["tts"] = self.toolTipSeconds } local slotDistance = self.size[1] / self.slots local sliderPosition = { self.position[1] + slotDistance * self.slideRectanglePosition - slotDistance / 2 - self.slideRectangleSize[1] / 2, self.position[2] + self.size[2] / 2 - self.slideRectangleSize[2] / 2 } local mouseWithinComponent = love.mouse.getX() > sliderPosition[1] and love.mouse.getY() > sliderPosition[2] and love.mouse.getX() < sliderPosition[1] + self.slideRectangleSize[1] and love.mouse.getY() < sliderPosition[2] + self.slideRectangleSize[2] if mouseWithinComponent then self.mouseHovering = true if self.toolTipSeconds > 0 then self.toolTipSeconds = self.toolTipSeconds - dt end if mouseLeft then self.mouseLDown = true if not mouseLeftCache then self.mouseLDownWithinThisComponent = true end else self.mouseLDown = false end if mouseRight then self.mouseRDown = true if not mouseRightCache then self.mouseRDownWithinThisComponent = true end else self.mouseRDown = false end else self.mouseHovering = false if not mouseLeft then self.mouseLDown = false end self.mouseRDown = false self.toolTipSeconds = self.toolTipSeconds2 end --Fire necessary events. if not previously["bld"] and self.mouseLDown and not mouseLeftCache then self.mouseButtonLDown:run(unpack(mousePosition)) end if not previously["brd"] and self.mouseRDown and not mouseRightCache then self.mouseButtonRDown:run(unpack(mousePosition)) end if previously["bld"] and not self.mouseLDown then self.mouseButtonLUp:run(unpack(mousePosition)) end if previously["brd"] and not self.mouseRDown then self.mouseButtonRUp:run(unpack(mousePosition)) end if previously["bld"] and not self.mouseLDown and self.mouseLDownWithinThisComponent then self.mouseButtonLClick:run(unpack(mousePosition)) end if previously["brd"] and not self.mouseRDown and self.mouseRDownWithinThisComponent then self.mouseButtonRClick:run(unpack(mousePosition)) end if self.mouseHovering and not previously["mh"] then self.mouseEnter:run(unpack(mousePosition)) end if not self.mouseHovering and previously["mh"] then self.mouseExit:run(unpack(mousePosition)) end if self.mouseHovering and previously["mh"] and unpack(mousePosition) ~= unpack(mousePositionCache) then self.mouseMove:run(unpack(mousePosition)) end end, ["sliderMoved"] = newEvent() }, {GUIElement} )
local function Symbol(Name: string) local self = newproxy(true) local Metatable = getmetatable(self) local SymbolName = string.format("Symbol(%s)", Name) function Metatable.__tostring() return SymbolName end return self end return Symbol
local RecruitAFriendShared = { Tables = { { Name = "RafLinkType", Type = "Enumeration", NumValues = 4, MinValue = 0, MaxValue = 3, Fields = { { Name = "None", Type = "RafLinkType", EnumValue = 0 }, { Name = "Recruit", Type = "RafLinkType", EnumValue = 1 }, { Name = "Friend", Type = "RafLinkType", EnumValue = 2 }, { Name = "Both", Type = "RafLinkType", EnumValue = 3 }, }, }, }, }; APIDocumentation:AddDocumentationTable(RecruitAFriendShared);
------------------------------------------------------------------------------- -- Prints logging information to console -- -- @author Thiago Costa Ponte (thiago@ideais.com.br) -- -- @copyright 2004-2021 Kepler Project -- ------------------------------------------------------------------------------- local logging = require"logging" function logging.console(params, ...) params = logging.getDeprecatedParams({ "logPattern" }, params, ...) local logPattern = params.logPattern local timestampPattern = params.timestampPattern return logging.new( function(self, level, message) io.stdout:write(logging.prepareLogMsg(logPattern, os.date(timestampPattern), level, message)) return true end) end return logging.console
require('torch') require('onmt.init') local tokenizer = require('tools.utils.tokenizer') local unicode = require('tools.utils.unicode') local separators = require('tools.utils.separators') local HookManager = require('onmt.utils.HookManager') local tds = require('tds') local cmd = onmt.utils.ExtendedCmdLine.new('learn_bpe.lua') local options = { { '-size', '30000', [[The number of merge operations to learn.]] }, { '-bpe_mode', 'suffix', [[Define the BPE mode. `prefix`: append `<w>` to the begining of each word to learn prefix-oriented pair statistics; `suffix`: append `</w>` to the end of each word to learn suffix-oriented pair statistics, as in the original Python script; `both`: `suffix` and `prefix`; `none`: no `suffix` nor `prefix`.]], { enum = {'suffix', 'prefix', 'both', 'none'} } }, { '-bpe_EOT_marker', separators.EOT, [[Marker used to mark the End of Token while applying BPE in mode 'prefix' or 'both'.]] }, { '-bpe_BOT_marker', separators.BOT, [[Marker used to mark the Beginning of Token while applying BPE in mode 'suffix' or 'both'.]] }, { '-save_bpe', '', [[Path to save the output model.]], { valid = onmt.utils.ExtendedCmdLine.nonEmpty } } } cmd:setCmdLineOptions(options, 'BPE') -- prepare tokenization option options = {} local topts = tokenizer.getOpts() for _, v in ipairs(topts) do if v[1]:sub(1,4) ~= '-bpe' then -- change mode option to include disabling mode (default) if v[1] == '-mode' then v[2] = 'space' end local opttmp = {table.unpack(v)} opttmp[1] = '-tok_' .. v[1]:sub(2) table.insert(options, {table.unpack(opttmp)}) end end cmd:setCmdLineOptions(options, "Tokenizer") -- insert on the fly the option depending if there is a hook selected onmt.utils.HookManager.updateOpt(arg, cmd) onmt.utils.HookManager.declareOpts(cmd) onmt.utils.Logger.declareOpts(cmd) local opt = cmd:parse(arg) local function string2word(s) local t = {} if opt.bpe_mode == 'prefix' or opt.bpe_mode == 'both' then table.insert(t, opt.bpe_BOT_marker) end for _, c in unicode.utf8_iter(s) do table.insert(t, c) end if opt.bpe_mode == 'suffix' or opt.bpe_mode == 'both' then table.insert(t, opt.bpe_EOT_marker) end return table.concat(t, " ") end local function replace(word, bigram) local new_word = {} local merge = false for i = 1, #word do if (merge) then if word[i] == bigram[2] then table.insert(new_word, bigram[1] .. bigram[2]) merge = false elseif word[i] == bigram[1] then table.insert(new_word, bigram[1]) else table.insert(new_word, bigram[1]) table.insert(new_word, word[i]) merge = false end else if bigram[1] == word[i] then merge = true else table.insert(new_word, word[i]) end end end if merge then table.insert(new_word, word[#word]) end return table.concat(new_word, " ") end local function updatedict(d, key1, key2, value) if d[key1] == nil then d[key1] = tds.Hash({ [key2] = value}) else if d[key1][key2] == nil then d[key1][key2] = 1 else d[key1][key2] = d[key1][key2] + value end end end local function get_vocabulary() local vocab = tds.Hash() local l = io.read() -- tokenization options local tokopts = {} for k, v in pairs(opt) do if k:sub(1,4) == 'tok_' then k = k:sub(5) tokopts[k] = v end end _G.logger:info("Using on-the-fly '%s' tokenization for input", tokopts["mode"]) local segmentor = function (line) return tokenizer.tokenize(tokopts, line, nil) end _G.logger:info('Building vocabulary from STDIN') local count = 1 while not(l == nil) do local toks = segmentor(l) local words = onmt.utils.Features.extract(toks) for i = 1, #words do local word = words[i] if not word:find(separators.ph_marker_open) then vocab[word] = (vocab[word] or 0) + 1 end end l = io.read() count = count + 1 if count % 100000 == 0 then _G.logger:info('... ' .. count .. ' sentences processed') end end local vocabreal = tds.Hash() for k, v in pairs(vocab) do vocabreal[string2word(k)] = v end return vocabreal end local function get_pair_statistics(vocab) local stats = tds.Hash() local indices = tds.Hash() for idx, word_freq in ipairs(vocab) do local word = word_freq[1] local freq = word_freq[2] local chars = onmt.utils.String.split(word, " ") local prev_char = chars[1] for i=2, #chars do local bigram = prev_char .. " " .. chars[i] stats[bigram] = ( stats[bigram] or 0 ) + freq updatedict(indices, bigram, idx, 1) prev_char = chars[i] end end return stats, indices end local function replace_pair(pair, vocab, indices) local changed = {} local bigram = onmt.utils.String.split(pair, " ") for idx, ifreq in pairs (indices[pair]) do if not (ifreq < 1) then local word_freq = vocab[idx] local word = word_freq[1] local freq = word_freq[2] local new_word = replace(onmt.utils.String.split(word, ' '), bigram) vocab[idx] = tds.Vec({new_word, freq}) table.insert(changed, {idx, new_word, word, freq}) end end return changed end local function find_index (word, pattern, i) for k,v in pairs(word) do if k >= i and v == pattern then return k end end end local function update_pair_statistics(pair, changed, stats, indices) stats[pair] = 0 indices[pair] = tds.Hash() local bigram = onmt.utils.String.split(pair, " ") local first = bigram[1] local second = bigram[2] local new_pair = first .. second for ii = 1, #changed do local c = changed[ii] local idx = c [1] local new_word = onmt.utils.String.split(c[2], " ") local old_word = onmt.utils.String.split(c[3], " ") local freq = c[4] local i = 1 while true do i = find_index(old_word, first, i) if i == nil then break end if i < #old_word and old_word[i+1] == second then if i > 1 then local prev = old_word[i-1] .. " " .. old_word[i] stats[prev] = ( stats[prev] or 0 ) - freq updatedict(indices, prev, idx, -1) end if i <= #old_word-2 then if old_word[i+2] ~= first or i >= #old_word-3 or old_word[i+3] ~= second then local nex = old_word[i+1] .. " " .. old_word[i+2] stats[nex] = ( stats[nex] or 0 ) - freq updatedict(indices, nex, idx, -1) end end i = i + 2 else i = i + 1 end end i = 0 while true do i = find_index(new_word, new_pair, i) if i == nil then break end if i > 1 then local prev = new_word[i-1] .. " " .. new_word[i] stats[prev] = ( stats[prev] or 0 ) + freq updatedict(indices, prev, idx, 1) end if i <= #new_word-1 and new_word[i+1] ~= new_pair then local nex = new_word[i] .. " " .. new_word[i+1] stats[nex] = ( stats[nex] or 0 ) + freq updatedict(indices, nex, idx, 1) end i = i + 1 end end end local function maxKey(map) local max_value = 0 local max_key = {} for k, v in pairs(map) do if v > max_value then max_value = v max_key = {k} elseif v == max_value then table.insert(max_key, k) end end table.sort(max_key) return max_key[1] end local function prune_stats(stats, big_stats, threshold) for item, freq in pairs(stats) do if freq < threshold then stats[item] = nil if freq < 0 then big_stats[item] = ( big_stats[item] or 0 ) + freq else big_stats[item] = freq end end end end local function clone (t) -- shallow-copy a tds hash local target = tds.Hash() for k, v in pairs(t) do target[k] = v end return target end local function main() _G.logger = onmt.utils.Logger.new(opt.log_file, opt.disable_logs, opt.log_level, opt.log_tag) _G.hookManager = HookManager.new(opt) local vocab = get_vocabulary() local sorted_vocab = tds.Vec() for k, v in pairs(vocab) do sorted_vocab[#sorted_vocab+1] = tds.Vec({k, v}) end sorted_vocab:sort(function(a, b) return a[2] > b[2] end) _G.logger:info('Getting pair statistics from vocabulary') local stats, indices = get_pair_statistics (sorted_vocab) local big_stats = clone(stats) local threshold = stats[maxKey(stats)] / 10 local bpe_options = {'v3'} if opt.bpe_mode == 'prefix' or opt.bpe_mode == 'both' then table.insert(bpe_options, "true") else table.insert(bpe_options, "false") end if opt.bpe_mode == 'suffix' or opt.bpe_mode == 'both' then table.insert(bpe_options, "true") else table.insert(bpe_options, "false") end if opt.tok_case_feature then table.insert(bpe_options, "true") else table.insert(bpe_options, "false") end table.insert(bpe_options, opt.bpe_BOT_marker) table.insert(bpe_options, opt.bpe_EOT_marker) _G.logger:info('Generating merge operations to output') local f = assert(io.open(opt.save_bpe, 'w')) f:write(table.concat(bpe_options, ";") .. "\n") for i = 1, opt.size do local most_frequent if stats ~= nil then most_frequent = maxKey(stats) end -- we probably missed the best pair because of pruning; go back to full statistics if stats == nil or stats[most_frequent] < threshold then prune_stats(stats, big_stats, threshold) stats = clone(big_stats) most_frequent = maxKey(stats) -- threshold is inspired by Zipfian assumption, but should only affect speed threshold = stats[most_frequent] * i/(i+10000.0) prune_stats(stats, big_stats, threshold) end if stats[most_frequent] < 2 then io.stderr:write("No pair has frequency > 1. Stopping\n") break end local changed = replace_pair(most_frequent, sorted_vocab, indices) update_pair_statistics(most_frequent, changed, stats, indices) stats[most_frequent] = 0 f:write(most_frequent .. "\n") if i % 1000 == 0 then _G.logger:info('... ' .. i .. ' merge operations generated') end end f:close() end main()
local wezterm = require 'wezterm'; return { font = wezterm.font("MonoLisa", {weight="Book"}), font_size = 10.0, enable_tab_bar = false, enable_scroll_tab = false, window_padding = { left = 30, right = 30, top = 30, bottom = 30, } }
fx_version "cerulean" games { "gta5" } dependency "connectqueue" dependency "oxmysql" server_scripts { "@oxmysql/lib/MySQL.lua", "@connectqueue/connectqueue.lua", "@caue-lib/shared/sh_ids.lua", "sv_whitelist.lua" }
require("games/common2/module/props/vipKickConfig2"); RoomPropsLogic = class(DataInterfaceBase); --[[ 房间内使用道具 ]] RoomPropsLogic.propCmds = { PROPS_NO_ENOUGH = 0, -- 道具不足 PROPS_VIP = 1, -- VIP道具 PROPS_OUTDATE = 2, -- 道具过时 PROPS_NORMAL = 3, -- 正常使用 } RoomPropsLogic.getInstance = function() if not RoomPropsLogic.s_instance then RoomPropsLogic.s_instance = new(RoomPropsLogic); end return RoomPropsLogic.s_instance; end RoomPropsLogic.releaseInstance = function() delete(RoomPropsLogic.s_instance); RoomPropsLogic.s_instance = nil; end RoomPropsLogic.ctor = function(self) PropIsolater.getInstance():setObserver(self); EventDispatcher.getInstance():register(GameMechineConfig.BROADCAST_ACTION,self,self.monitoringAction); end RoomPropsLogic.dtor = function(self) PropIsolater.getInstance():clearObserver(self); EventDispatcher.getInstance():unregister(GameMechineConfig.BROADCAST_ACTION,self,self.monitoringAction); end RoomPropsLogic.monitoringAction = function(self,action,seat,uid,info,isFast) if self.s_actionFuncMap and type(self.s_actionFuncMap[action])=="function" then self.s_actionFuncMap[action](self,seat,uid,info,isFast); end end ------------------------- 社交道具逻辑开始 -------------------------------------- --[Comment] -- 请求使用道具 -- propInfo:道具信息 -- targets:使用者与被使用者座位,格式:1,2 RoomPropsLogic.onRequestUseProps = function (self, cmd, propInfo, targetMid) if cmd == RoomPropsLogic.propCmds.PROPS_NO_ENOUGH then -- 不足 Toast.getInstance():showText(kTextNoTypeProp,50,30,kAlignLeft,"",26,200,175,110); return; elseif cmd == RoomPropsLogic.propCmds.PROPS_OUTDATE then -- 过期 Toast.getInstance():showText(kTextPropDue,50,30,kAlignLeft,"",26,200,175,110); return; elseif cmd == RoomPropsLogic.propCmds.PROPS_VIP then -- 会员使用 return; elseif cmd == RoomPropsLogic.propCmds.PROPS_NORMAL then local localseat = PlayerSeat.getInstance():getMyLocalSeat(); -- self:notify(RoomPropsLogic.Delegate.onHidPlayerInfo,localseat); MechineManage.getInstance():receiveAction(GameMechineConfig.ACTION_NS_CLOSEPLAYERWND); end local targetInfo = GamePlayerManager2.getInstance():getPlayerByMid(targetMid); if not targetInfo then return ; end if targetMid == UserBaseInfoIsolater.getInstance():getUserId()then self:showToast("社交道具无法对自己使用"); -- 不可对自己使用道具 else local targets = string.format("%d,%d", GamePlayerManager2.getInstance():getPlayerBySeat(GameConstant.SEAT_LOCAL_MINE):getSeatId(), targetInfo:getSeatId()); PropIsolater.getInstance():requestUseProp(propInfo.type, 1,targets); end end -- 使用踢人卡 RoomPropsLogic.onResponseKick = function(self,seat,uid,data,isFast) Log.d("RoomPropsLogic.onResponseKick",data) if type(data) == "table" then if data.errorcode ~= 0 then self:handleKickEvent(data.errorcode); return; end if data.vipuid ~= UserBaseInfoIsolater.getInstance():getUserId() then if data.kickuid == UserBaseInfoIsolater.getInstance():getUserId() then -- 自己被踢出房间,请求退出 local action = GameMechineConfig.ACTION_NS_KICKOUT_SUCCESS; MechineManage.getInstance():receiveAction(action, {}, data.kickuid); end else local action = GameMechineConfig.ACTION_SHOWKICKANIM; MechineManage.getInstance():receiveAction(action, data); end end end RoomPropsLogic.showToast = function(self,msg) if not string.isEmpty(msg) then Toast.getInstance():showText(msg,50,30,kAlignLeft,"",24,200,175,110); end end RoomPropsLogic.handleKickEvent = function ( self, errorCode ) -- body self:showToast(KICK_STR2[errorCode] or "踢人失败"); if errorCode == KICK_CODE2.VIP_OUTTIME or errorCode == KICK_CODE2.NO_KICK_PROP then -- if errorCode == KICK_CODE2.VIP_OUTTIME then -- 刷新VIP状态 UserIdentityIsolater.getInstance():setNormalIdentity(); UserIdentityIsolater.getInstance():refreshUserIdentity(0, UserIdentityIsolater.getInstance():getIdentity()); local action = GameMechineConfig.ACTION_NS_UPDATE_USERINFO; MechineManage.getInstance():receiveAction(action); -- end -- 走vip充值 UBReport.getInstance():report(UBConfig.kHallGetVipKick); PayIsolater.getInstance():setSceneType(UBPaySceneConfig.kRoomUserInfoVipRecharge); local action = GameMechineConfig.ACTION_RECHARGE; local data = {scene=PayIsolater.eGoodsListId.VipCharge}; MechineManage.getInstance():receiveAction(action,data); end end
-- PASTE THIS ALONG WITH THE OTHER 3 SCRIPTS TO "ServerScriptService" or the phone will not work! local ReplicatedStorage = game:GetService("ReplicatedStorage") local PhoneCallEvent = ReplicatedStorage:WaitForChild("PhoneCallEvent") PhoneCallEvent.OnServerEvent:Connect(function(player, receiver) print("Ringing a call to " .. receiver) local success, errormessage = pcall(function() ReceiverPlayer = game.Players:FindFirstChild(receiver) end) if success then PhoneCallEvent:FireClient(ReceiverPlayer, "Receiver", player.Name) --otherName PhoneCallEvent:FireClient(player, "Caller", receiver) print("Phone is ringing ok") else warn(errormessage) end end)
local ItemId = pExodus.ItemId local CostumeId = pExodus.CostumeId pExodus.ItemId.YIN = Isaac.GetItemIdByName("Yin") pExodus.CostumeId.YIN = Isaac.GetCostumeIdByPath("gfx/characters/costume_Yin.anm2") pExodus:AddItemCostume(ItemId.YIN, pExodus.CostumeId.YIN) function pExodus.yinCache(player, flag) local heartmap = player:GetBlackHearts() local blackhearts = 0 while heartmap > 0 do heartmap = heartmap - 2^(math.floor(math.log(heartmap) / math.log(2))) blackhearts = blackhearts + 1 end local soulhearts = player:GetSoulHearts() - (blackhearts * 2) if flag == CacheFlag.CACHE_FIREDELAY and player:HasCollectible(ItemId.YIN) then if player:HasCollectible(ItemId.YANG) then player.MaxFireDelay = player.MaxFireDelay - blackhearts else player.MaxFireDelay = player.MaxFireDelay - blackhearts + math.ceil(soulhearts / 2) end end end pExodus:AddCallback(ModCallbacks.MC_EVALUATE_CACHE, pExodus.yinCache)