repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
rlcevg/Zero-K
LuaUI/Widgets/dbg_stuckkeys.lua
18
1634
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Stuck Keys", desc = "v0.01 Alerts user when a key is stuck.", author = "CarRepairer", date = "2011-03-01", license = "GNU GPL, v2 or later", layer = 1, enabled = false, } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local echo = Spring.Echo -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- include("keysym.h.lua") local keysyms = {} for k,v in pairs(KEYSYMS) do keysyms[v] = k end local keys = {} local cycle = 1 -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:KeyPress(key, modifier, isRepeat) if not keys[key] then keys[key] = 30 end end function widget:KeyRelease(key) keys[key] = nil end function widget:Update() cycle = (cycle + 1) % 32 if cycle == 1 then for key, time in pairs(keys) do keys[key] = time - 1 if keys[key] < 0 then echo( 'The key "' .. keysyms[key] .. '" has been pressed for over 30 seconds. It might be stuck, try tapping it.' ) keys[key] = 30 end end end end --------------------------------------------------------------------------------
gpl-2.0
VladimirTyrin/wireshark
test/lua/dir.lua
31
6467
-- test script for wslua Dir functions ------------- helper funcs ------------ local total_tests = 0 local function testing(name) print("---- Testing "..name.." ---- ") end local function test(name, ...) total_tests = total_tests + 1 io.stdout:write("test "..name.."-"..total_tests.."...") if (...) == true then io.stdout:write("passed\n") return true else io.stdout:write("failed!\n") error(name.." test failed!") end end -- the following are so we can use pcall (which needs a function to call) local function callDirFuncBase(name, t) t.result = Dir[name]() return true end local function callDirFunc(name, val, t) t.result = Dir[name](val) return true end local function makeFile(filename) local f = io.open(filename, "w") if not f then error ("failed to make file"..filename.." in directory\n".. "make sure to delete 'temp' directory before running again") end f:write("fooobarrloo") f:close() return true end -------------------------- -- for our called function results local t = {} testing("Dir basics") test("global", _G.Dir ~= nil) test("global", type(Dir.make) == 'function') test("global", type(Dir.remove) == 'function') test("global", type(Dir.remove_all) == 'function') test("global", type(Dir.open) == 'function') test("global", type(Dir.close) == 'function') test("global", type(Dir.exists) == 'function') test("global", type(Dir.personal_config_path) == 'function') test("global", type(Dir.global_config_path) == 'function') test("global", type(Dir.personal_plugins_path) == 'function') test("global", type(Dir.global_plugins_path) == 'function') testing("Dir paths/filenames") test("Dir.__FILE__", __FILE__ ~= nil) test("Dir.__DIR__", __DIR__ ~= nil) test("Dir.exists", pcall(callDirFunc, "exists", "temp", t)) test("Dir.personal_config_path", pcall(callDirFuncBase, "personal_config_path", t)) test("Dir.global_config_path", pcall(callDirFuncBase, "global_config_path", t)) test("Dir.personal_plugins_path", pcall(callDirFuncBase, "personal_plugins_path", t)) test("Dir.global_plugins_path", pcall(callDirFuncBase, "global_plugins_path", t)) print("\nFor your information, I got the following info:\n") print("__FILE__ = '" .. __FILE__ .. "'") print("__DIR__ = '" .. __DIR__ .. "'") print("personal_config_path = '" .. Dir.personal_config_path() .. "'") print("global_config_path = '" .. Dir.global_config_path() .. "'") print("personal_plugins_path = '" .. Dir.personal_plugins_path() .. "'") print("global_plugins_path = '" .. Dir.global_plugins_path() .. "'") print("\n") testing("Directory manipulation") test("Dir.exists", pcall(callDirFunc, "exists", "temp", t)) if t.result == true or t.result == false then error("this testsuite requires there be no 'temp' directory or file; please remove it") end testing("Dir.make") test("Dir.make", pcall(callDirFunc, "make", "temp", t) and t.result == true) test("Dir.exists", pcall(callDirFunc, "exists", "temp", t) and t.result == true) -- make the same dir, should give false test("Dir.make", pcall(callDirFunc, "make", "temp", t) and t.result == false) testing("Dir.remove") test("Dir.remove", pcall(callDirFunc, "remove", "temp", t) and t.result == true) test("Dir.exists", pcall(callDirFunc, "exists", "temp", t) and t.result == nil) test("Dir.remove", pcall(callDirFunc, "remove", "temp", t) and t.result == false) Dir.make("temp") makeFile("temp/file.txt") -- will return nil because temp has a file test("Dir.remove", pcall(callDirFunc, "remove", "temp", t) and t.result == nil) testing("Dir.remove_all") test("Dir.remove_all", pcall(callDirFunc, "remove_all", "temp", t) and t.result == true) test("Dir.remove_all", pcall(callDirFunc, "remove_all", "temp", t) and t.result == false) Dir.make("temp") makeFile("temp/file1.txt") makeFile("temp/file2.txt") makeFile("temp/file3.txt") test("Dir.remove_all", pcall(callDirFunc, "remove_all", "temp", t) and t.result == true) test("Dir.remove_all", pcall(callDirFunc, "remove_all", "temp", t) and t.result == false) testing("Dir.open") Dir.make("temp") makeFile("temp/file1.txt") makeFile("temp/file2.txt") makeFile("temp/file3.txt") test("Dir.open", pcall(callDirFunc, "open", "temp", t)) test("Dir.open", type(t.result) == 'userdata') test("Dir.open", typeof(t.result) == 'Dir') io.stdout:write("calling Dir object...") local dir = t.result local files = {} files[dir()] = true io.stdout:write("passed\n") files[dir()] = true files[dir()] = true test("Dir.call", files["file1.txt"]) test("Dir.call", files["file2.txt"]) test("Dir.call", files["file3.txt"]) test("Dir.call", dir() == nil) test("Dir.call", dir() == nil) testing("Dir.close") test("Dir.close", pcall(callDirFunc, "close", dir, t)) test("Dir.close", pcall(callDirFunc, "close", dir, t)) testing("Negative testing 1") -- now try breaking it test("Dir.open", pcall(callDirFunc, "open", "temp", t)) dir = t.result -- call dir() now files = {} files[dir()] = true Dir.remove_all("temp") -- call it again files[dir()] = true files[dir()] = true test("Dir.call", files["file1.txt"]) test("Dir.call", files["file2.txt"]) test("Dir.call", files["file3.txt"]) test("Dir.close", pcall(callDirFunc, "close", dir, t)) testing("Negative testing 2") -- do it again, but this time don't do dir() until after removing the files Dir.make("temp") makeFile("temp/file1.txt") makeFile("temp/file2.txt") makeFile("temp/file3.txt") test("Dir.open", pcall(callDirFunc, "open", "temp", t)) dir = t.result Dir.remove_all("temp") -- now do it file = dir() test("Dir.call", file == nil) test("Dir.close", pcall(callDirFunc, "close", dir, t)) -- negative tests testing("Negative testing 3") -- invalid args test("Dir.make", not pcall(callDirFunc, "make", {}, t)) test("Dir.make", not pcall(callDirFunc, "make", nil, t)) test("Dir.remove", not pcall(callDirFunc, "remove", {}, t)) test("Dir.remove", not pcall(callDirFunc, "remove", nil, t)) test("Dir.remove_all", not pcall(callDirFunc, "remove_all", {}, t)) test("Dir.remove_all", not pcall(callDirFunc, "remove_all", nil, t)) test("Dir.open", not pcall(callDirFunc, "open", {}, t)) test("Dir.open", not pcall(callDirFunc, "open", nil, t)) test("Dir.close", not pcall(callDirFunc, "close", "dir", t)) test("Dir.close", not pcall(callDirFunc, "close", nil, t)) print("\n-----------------------------\n") print("All tests passed!\n\n")
gpl-2.0
rlcevg/Zero-K
effects/corpun.lua
25
1956
-- corpun_shockwave return { ["corpun_shockwave"] = { clouds0 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, underwater = 0, water = false, properties = { airdrag = 0.95, colormap = [[0 0 0 0.001 0.2 0.15 0 0.08 0 0 0 0.001]], directional = true, emitrot = 90, emitrotspread = 0, emitvector = [[0, 1, 0]], gravity = [[0, -0.1, 0]], numparticles = 3, particlelife = 140, particlelifespread = 0, particlesize = 2, particlesizespread = 1, particlespeed = 5, particlespeedspread = 0, pos = [[15, 1, 0]], sizegrowth = 0.3, sizemod = 1.0, texture = [[kfoom]], }, }, clouds1 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, underwater = 0, water = false, properties = { airdrag = 0.95, colormap = [[0 0 0 0.001 0.04 0.04 0.04 0.2 0 0 0 0.001]], directional = true, emitrot = 90, emitrotspread = 0, emitvector = [[0, 1, 0]], gravity = [[0, -0.1, 0]], numparticles = 20, particlelife = 140, particlelifespread = 0, particlesize = 4, particlesizespread = 1, particlespeed = 5, particlespeedspread = 0, pos = [[15, 1, 0]], sizegrowth = 0.3, sizemod = 1.0, texture = [[kfoam]], }, }, }, }
gpl-2.0
cailyoung/CommandPost
src/extensions/cp/apple/finalcutpro/plugins/guiscan.lua
1
20650
local log = require("hs.logger").new("guiscan") local dialog = require("cp.dialog") local fcp = require("cp.apple.finalcutpro") local plugins = require("cp.apple.finalcutpro.plugins") local just = require("cp.just") local insert, remove = table.insert, table.remove local format = string.format local mod = {} -- scanVideoEffects() -> table -- Function -- Scans the list of video effects in the FCPX GUI and returns it as a list. -- -- Parameters: -- * None -- -- Returns: -- * The table of video effect names, or `nil` if there was a problem. local function scanVideoEffects() -------------------------------------------------------------------------------- -- Make sure Final Cut Pro is active: -------------------------------------------------------------------------------- fcp:launch() -------------------------------------------------------------------------------- -- Make sure Effects panel is open: -------------------------------------------------------------------------------- local effects = fcp:effects() local effectsShowing = effects:isShowing() if not effects:show():isShowing() then dialog.displayErrorMessage("Unable to activate the Effects panel.") return nil end local effectsLayout = effects:saveLayout() -------------------------------------------------------------------------------- -- Make sure "Installed Effects" is selected: -------------------------------------------------------------------------------- effects:showInstalledEffects() -------------------------------------------------------------------------------- -- Make sure there's nothing in the search box: -------------------------------------------------------------------------------- effects:search():clear() local sidebar = effects:sidebar() -------------------------------------------------------------------------------- -- Ensure the sidebar is visible -------------------------------------------------------------------------------- effects:showSidebar() -------------------------------------------------------------------------------- -- If it's still invisible, we have a problem. -------------------------------------------------------------------------------- if not sidebar:isShowing() then dialog.displayErrorMessage("Unable to activate the Effects sidebar.") return nil end -------------------------------------------------------------------------------- -- Click 'All Video': -------------------------------------------------------------------------------- if not effects:showAllVideoEffects() then dialog.displayErrorMessage("Unable to select all video effects.") return nil end -------------------------------------------------------------------------------- -- Get list of All Video Effects: -------------------------------------------------------------------------------- local effectsList = effects:getCurrentTitles() if not effectsList then dialog.displayErrorMessage("Unable to get list of all effects.") return nil end -------------------------------------------------------------------------------- -- Restore Effects: -------------------------------------------------------------------------------- effects:loadLayout(effectsLayout) if not effectsShowing then effects:hide() end -------------------------------------------------------------------------------- -- All done! -------------------------------------------------------------------------------- if #effectsList == 0 then dialog.displayMessage(i18n("updateEffectsListFailed") .. "\n\n" .. i18n("pleaseTryAgain")) return nil else return effectsList end end -- scanAudioEffects() -> table -- Function -- Scans the list of audio effects in the FCPX GUI and returns it as a list. -- -- Parameters: -- * None -- -- Returns: -- * The table of audio effect names, or `nil` if there was a problem. local function scanAudioEffects() -------------------------------------------------------------------------------- -- Make sure Final Cut Pro is active: -------------------------------------------------------------------------------- fcp:launch() -------------------------------------------------------------------------------- -- Make sure Effects panel is open: -------------------------------------------------------------------------------- local effects = fcp:effects() local effectsShowing = effects:isShowing() if not effects:show():isShowing() then dialog.displayErrorMessage("Unable to activate the Effects panel.") return nil end local effectsLayout = effects:saveLayout() -------------------------------------------------------------------------------- -- Make sure "Installed Effects" is selected: -------------------------------------------------------------------------------- effects:showInstalledEffects() -------------------------------------------------------------------------------- -- Make sure there's nothing in the search box: -------------------------------------------------------------------------------- effects:search():clear() local sidebar = effects:sidebar() -------------------------------------------------------------------------------- -- Ensure the sidebar is visible -------------------------------------------------------------------------------- effects:showSidebar() -------------------------------------------------------------------------------- -- If it's still invisible, we have a problem. -------------------------------------------------------------------------------- if not sidebar:isShowing() then dialog.displayErrorMessage("Unable to activate the Effects sidebar.") return nil end -------------------------------------------------------------------------------- -- Click 'All Audio': -------------------------------------------------------------------------------- if not effects:showAllAudioEffects() then dialog.displayErrorMessage("Unable to select all audio effects.") return nil end -------------------------------------------------------------------------------- -- Get list of All Video Effects: -------------------------------------------------------------------------------- local effectsList = effects:getCurrentTitles() if not effectsList then dialog.displayErrorMessage("Unable to get list of all effects.") return nil end -------------------------------------------------------------------------------- -- Restore Effects: -------------------------------------------------------------------------------- effects:loadLayout(effectsLayout) if not effectsShowing then effects:hide() end -------------------------------------------------------------------------------- -- All done! -------------------------------------------------------------------------------- if #effectsList == 0 then dialog.displayMessage(i18n("updateEffectsListFailed") .. "\n\n" .. i18n("pleaseTryAgain")) return nil else return effectsList end end -- scanTransitions() -> table -- Function -- Scans the list of transitions in the FCPX GUI and returns it as a list. -- -- Parameters: -- * None -- -- Returns: -- * The table of transition names, or `nil` if there was a problem. local function scanTransitions() -------------------------------------------------------------------------------- -- Make sure Final Cut Pro is active: -------------------------------------------------------------------------------- fcp:launch() -------------------------------------------------------------------------------- -- Save the layout of the Effects panel, in case we switch away... -------------------------------------------------------------------------------- local effects = fcp:effects() local effectsLayout = nil if effects:isShowing() then effectsLayout = effects:saveLayout() end -------------------------------------------------------------------------------- -- Make sure Transitions panel is open: -------------------------------------------------------------------------------- local transitions = fcp:transitions() local transitionsShowing = transitions:isShowing() if not transitions:show():isShowing() then dialog.displayErrorMessage("Unable to activate the Transitions panel.") return nil end local transitionsLayout = transitions:saveLayout() -------------------------------------------------------------------------------- -- Make sure "Installed Transitions" is selected: -------------------------------------------------------------------------------- transitions:showInstalledTransitions() -------------------------------------------------------------------------------- -- Make sure there's nothing in the search box: -------------------------------------------------------------------------------- transitions:search():clear() -------------------------------------------------------------------------------- -- Make sure the sidebar is visible: -------------------------------------------------------------------------------- local sidebar = transitions:sidebar() transitions:showSidebar() if not sidebar:isShowing() then dialog.displayErrorMessage("Unable to activate the Transitions sidebar.") return nil end -------------------------------------------------------------------------------- -- Click 'All' in the sidebar: -------------------------------------------------------------------------------- transitions:showAllTransitions() -------------------------------------------------------------------------------- -- Get list of All Transitions: -------------------------------------------------------------------------------- local allTransitions = transitions:getCurrentTitles() -------------------------------------------------------------------------------- -- Restore Effects and Transitions Panels: -------------------------------------------------------------------------------- transitions:loadLayout(transitionsLayout) if effectsLayout then effects:loadLayout(effectsLayout) end if not transitionsShowing then transitions:hide() end -------------------------------------------------------------------------------- -- Return results: -------------------------------------------------------------------------------- return allTransitions end -------------------------------------------------------------------------------- -- GET LIST OF GENERATORS: -------------------------------------------------------------------------------- local function scanGenerators() -------------------------------------------------------------------------------- -- Make sure Final Cut Pro is active: -------------------------------------------------------------------------------- fcp:launch() local generators = fcp:generators() local browserLayout = fcp:browser():saveLayout() -------------------------------------------------------------------------------- -- Make sure Generators and Generators panel is open: -------------------------------------------------------------------------------- if not generators:show():isShowing() then dialog.displayErrorMessage("Unable to activate the Generators and Generators panel.") return nil end -------------------------------------------------------------------------------- -- Make sure there's nothing in the search box: -------------------------------------------------------------------------------- generators:search():clear() -------------------------------------------------------------------------------- -- Click 'Generators': -------------------------------------------------------------------------------- generators:showAllGenerators() -------------------------------------------------------------------------------- -- Make sure "Installed Generators" is selected: -------------------------------------------------------------------------------- generators:group():selectItem(1) -------------------------------------------------------------------------------- -- Get list of All Transitions: -------------------------------------------------------------------------------- local effectsList = generators:contents():childrenUI() local allGenerators = {} if effectsList ~= nil then for i=1, #effectsList do allGenerators[i] = effectsList[i]:attributeValue("AXTitle") end else dialog.displayErrorMessage("Unable to get list of all generators.") return nil end -------------------------------------------------------------------------------- -- Restore Effects or Transitions Panel: -------------------------------------------------------------------------------- fcp:browser():loadLayout(browserLayout) -------------------------------------------------------------------------------- -- Return the results: -------------------------------------------------------------------------------- return allGenerators end local function scanTitles() -------------------------------------------------------------------------------- -- Make sure Final Cut Pro is active: -------------------------------------------------------------------------------- fcp:launch() local generators = fcp:generators() local browserLayout = fcp:browser():saveLayout() -------------------------------------------------------------------------------- -- Make sure Titles and Generators panel is open: -------------------------------------------------------------------------------- if not generators:show():isShowing() then dialog.displayErrorMessage("Unable to activate the Titles and Generators panel.") return nil end -------------------------------------------------------------------------------- -- Make sure there's nothing in the search box: -------------------------------------------------------------------------------- generators:search():clear() -------------------------------------------------------------------------------- -- Click 'Titles': -------------------------------------------------------------------------------- generators:showAllTitles() -------------------------------------------------------------------------------- -- Make sure "Installed Titles" is selected: -------------------------------------------------------------------------------- generators:group():selectItem(1) -------------------------------------------------------------------------------- -- Get list of All Transitions: -------------------------------------------------------------------------------- local effectsList = generators:contents():childrenUI() local allTitles = {} if effectsList ~= nil then for i=1, #effectsList do allTitles[i] = effectsList[i]:attributeValue("AXTitle") end else dialog.displayErrorMessage("Unable to get list of all titles.") return nil end -------------------------------------------------------------------------------- -- Restore Effects or Transitions Panel: -------------------------------------------------------------------------------- fcp:browser():loadLayout(browserLayout) return allTitles end -- cp.apple.finalcutpro.plugins.guiscan.check([language]) -> boolean, string -- Function -- Compares the list of plugins created via file scanning to that produced by GUI scanning. -- A detailed report is output in the Error Log. -- -- Parameters: -- * `language` - The language to scan in. Defaults the the current FCPX language. -- -- Returns: -- * `true` if all plugins match. -- * The text value of the report. function mod.check(language) language = language or fcp:currentLanguage() local value = "" function ln(str, ...) value = value .. format(str, ...) .. "\n" end fcp.currentLanguage:set(language) fcp:launch() just.doUntil(function() return fcp:isFrontmost() end, 20, 0.1) -------------------------------------------------------------------------------- -- Debug Message: -------------------------------------------------------------------------------- ln("\n---------------------------------------------------------") ln(" COMPARING PLUGIN FILE SCAN RESULTS TO GUI SCAN RESULTS:") ln("---------------------------------------------------------\n") -------------------------------------------------------------------------------- -- Plugin Types: -------------------------------------------------------------------------------- local pluginScanners = { [plugins.types.audioEffect] = scanAudioEffects, [plugins.types.videoEffect] = scanVideoEffects, [plugins.types.transition] = scanTransitions, [plugins.types.generator] = scanGenerators, [plugins.types.title] = scanTitles, } -------------------------------------------------------------------------------- -- Begin Scan: -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Debug Message: -------------------------------------------------------------------------------- ln("---------------------------------------------------------") ln(" CHECKING LANGUAGE: %s", language) ln("---------------------------------------------------------") local failed = false for newType,scanner in pairs(pluginScanners) do -------------------------------------------------------------------------------- -- Get settings from GUI Scripting Results: -------------------------------------------------------------------------------- local oldPlugins = scanner(language) if oldPlugins then -------------------------------------------------------------------------------- -- Debug Message: -------------------------------------------------------------------------------- ln(" - Checking Plugin Type: %s", newType) local newPlugins = fcp:plugins():ofType(newType, language) local newPluginNames = {} if newPlugins then for _,plugin in ipairs(newPlugins) do local name = plugin.name local plugins = newPluginNames[name] local unmatched = nil if not plugins then plugins = { matched = {}, unmatched = {}, partials = {}, } newPluginNames[name] = plugins end insert(plugins.unmatched, plugin) end end -------------------------------------------------------------------------------- -- Compare Results: -------------------------------------------------------------------------------- local errorCount = 0 for _, oldFullName in pairs(oldPlugins) do local oldTheme, oldName = string.match(oldFullName, "^(.-) %- (.+)$") oldName = oldName or oldFullName local newPlugins = newPluginNames[oldFullName] or newPluginNames[oldName] if not newPlugins then ln(" - ERROR: Missing %s: %s", oldType, oldFullName) errorCount = errorCount + 1 else local unmatched = newPlugins.unmatched local found = false for i,plugin in ipairs(unmatched) do -- ln(" - INFO: Checking plugin: %s (%s)", plugin.name, plugin.theme) if plugin.theme == oldTheme then -- ln(" - INFO: Exact match for plugin: %s (%s)", oldName, oldTheme) insert(newPlugins.matched, plugin) remove(unmatched, i) found = true break end end if not found then -- ln(" - INFO: Partial for '%s' plugin.", oldFullName) insert(newPlugins.partials, oldFullName) end end end for newName, plugins in pairs(newPluginNames) do if #plugins.partials ~= #plugins.unmatched then for _,oldFullName in ipairs(plugins.partials) do ln(" - ERROR: GUI Scan %s plugin unmatched: %s", newType, oldFullName) errorCount = errorCount + 1 end for _,plugin in ipairs(plugins.unmatched) do local newFullName = plugin.name if plugin.theme then newFullName = plugin.theme .." - "..newFullName end ln(" - ERROR: File Scan %s plugin unmatched: %s\n\t\t%s", newType, newFullName, plugin.path) errorCount = errorCount + 1 end end end -------------------------------------------------------------------------------- -- If all results matched: -------------------------------------------------------------------------------- if errorCount == 0 then ln(" - SUCCESS: %s all matched!\n", newType) else ln(" - ERROR: %s had %d errors!\n", newType, errorCount) end failed = failed or (errorCount ~= 0) else ln(" - SKIPPING: Could not find settings for: %s (%s)", newType, language) end end return not failed, value end function mod.checkAll() local failed, value = false, "" for _,language in ipairs(fcp:getSupportedLanguages()) do local ok, result = mod.check(langauge) failed = failed or not ok value = value .. result .. "\n" end return not failed, value end return mod
mit
AOKP/external_skia
tools/lua/skia.lua
207
1863
-- Experimental helpers for skia -- function string.startsWith(String,Start) return string.sub(String,1,string.len(Start))==Start end function string.endsWith(String,End) return End=='' or string.sub(String,-string.len(End))==End end Sk = {} function Sk.isFinite(x) return x * 0 == 0 end ------------------------------------------------------------------------------- Sk.Rect = { left = 0, top = 0, right = 0, bottom = 0 } Sk.Rect.__index = Sk.Rect function Sk.Rect.new(l, t, r, b) local rect if r then -- 4 arguments rect = { left = l, top = t, right = r, bottom = b } elseif l then -- 2 arguments rect = { right = l, bottom = t } else -- 0 arguments rect = {} end setmetatable(rect, Sk.Rect) return rect; end function Sk.Rect:width() return self.right - self.left end function Sk.Rect:height() return self.bottom - self.top end function Sk.Rect:isEmpty() return self:width() <= 0 or self:height() <= 0 end function Sk.Rect:isFinite() local value = self.left * 0 value = value * self.top value = value * self.right value = value * self.bottom return 0 == value end function Sk.Rect:setEmpty() self.left = 0 self.top = 0 self.right = 0 self.bottom = 0 end function Sk.Rect:set(l, t, r, b) self.left = l self.top = t self.right = r self.bottom = b end function Sk.Rect:offset(dx, dy) dy = dy or dx self.left = self.left + dx self.top = self.top + dy self.right = self.right + dx self.bottom = self.bottom + dy end function Sk.Rect:inset(dx, dy) dy = dy or dx self.left = self.left + dx self.top = self.top + dy self.right = self.right - dx self.bottom = self.bottom - dy end -------------------------------------------------------------------------------
bsd-3-clause
rlcevg/Zero-K
LuaUI/Widgets/gui_chili_rejoin_progress.lua
9
16494
function widget:GetInfo() return { name = "Chili Rejoining Progress Bar", desc = "v1.132 Show the progress of rejoining and temporarily turn-off Text-To-Speech while rejoining", author = "msafwan (use UI from KingRaptor's Chili-Vote) ", date = "Oct 10, 2012", license = "GNU GPL, v2 or later", layer = 0, experimental = false, enabled = true, -- loaded by default? --handler = true, -- allow this widget to use 'widgetHandler:FindWidget()' } end -------------------------------------------------------------------------------- --Crude Documentation----------------------------------------------------------- --How it meant to work: --1) GameProgress return serverFrame --> IF I-am-behind THEN activate chili UI ELSE de-activate chili UI --> Update the estimated-time-of-completion every second. --2) LuaRecvMsg return timeDifference --> IF I-am-behind THEN activate chili UI ELSE nothing ---> Update the estimated-time-of-completion every second. --3) at GameStart send LuaMsg containing GameStart's UTC. --Others: some tricks to increase efficiency, bug fix, ect -------------------------------------------------------------------------------- --Localize Spring function------------------------------------------------------ local spGetSpectatingState = Spring.GetSpectatingState -------------------------------------------------------------------------------- --Chili Variable----------------------------------------------------------------- ref: gui_chili_vote.lua by KingRaptor local Chili local Button local Label local Window local Panel local TextBox local Image local Progressbar local Control local Font -- elements local window, stack_main, label_title local stack_vote, label_vote, button_vote, progress_vote local voteCount, voteMax -------------------------------------------------------------------------------- --Calculator Variable------------------------------------------------------------ local serverFrameRate_G = 30 --//constant: assume server run at x1.0 gamespeed. local serverFrameNum1_G = nil --//variable: get the latest server's gameFrame from GameProgress() and do work with it. local oneSecondElapsed_G = 0 --//variable: a timer for 1 second, used in Update(). Update UI every 1 second. local myGameFrame_G = 0 --//variable: get latest my gameFrame from GameFrame() and do work with it. local myLastFrameNum_G = 0 --//variable: used to calculate local game-frame rate. local ui_active_G = false --//variable:indicate whether UI is shown or hidden. local averageLocalSpeed_G = {sumOfSpeed= 0, sumCounter= 0} --//variable: store the local-gameFrame speeds so that an average can be calculated. local defaultAverage_G = 30 --//constant: Initial/Default average is set at 30gfps (x1.0 gameSpeed) local simpleMovingAverageLocalSpeed_G = {storage={},index = 1, runningAverage=defaultAverage_G} --//variable: for calculating rolling average. Initial/Default average is set at 30gfps (x1.0 gameSpeed) -------------------------------------------------------------------------------- --Variable for fixing GameProgress delay at rejoin------------------------------ local myTimestamp_G = 0 --//variable: store my own timestamp at GameStart local serverFrameNum2_G = nil --//variable: the expected server-frame of current running game local submittedTimestamp_G = {} --//variable: store all timestamp at GameStart submitted by original players (assuming we are rejoining) local functionContainer_G = function(x) end --//variable object: store a function local myPlayerID_G = 0 local gameProgressActive_G = false --//variable: signal whether GameProgress has been updated. local iAmReplay_G = false -------------------------------------------------------------------------------- --For testing GUI--------------------------------------------------------------- local forceDisplay = nil -------------------------------------------------------------------------------- --[[ if VFS.FileExists("Luaui/Config/ZK_data.lua") then local configFile = VFS.Include("Luaui/Config/ZK_data.lua") ttsControlEnabled_G = configFile["EPIC Menu"].config.epic_Text_To_Speech_Control_enable if ttsControlEnabled_G == nil then ttsControlEnabled_G = true end end --]] local function ActivateGUI_n_TTS (frameDistanceToFinish, ui_active, ttsControlEnabled, altThreshold) if frameDistanceToFinish >= (altThreshold or 120) then if not ui_active then screen0:AddChild(window) ui_active = true if ttsControlEnabled then Spring.Echo(Spring.GetPlayerInfo(myPlayerID_G) .. " DISABLE TTS") --eg: output "<playerName> DISABLE TTS" end end elseif frameDistanceToFinish < (altThreshold or 120) then if ui_active then screen0:RemoveChild(window) ui_active = false if ttsControlEnabled then Spring.Echo(Spring.GetPlayerInfo(myPlayerID_G) .. " ENABLE TTS") end end end return ui_active end function widget:GameProgress(serverFrameNum) --this function run 3rd. It read the official serverFrameNumber local myGameFrame = myGameFrame_G local ui_active = ui_active_G -----localize-- local ttsControlEnabled = CheckTTSwidget() local serverFrameNum1 = serverFrameNum local frameDistanceToFinish = serverFrameNum1-myGameFrame ui_active = ActivateGUI_n_TTS (frameDistanceToFinish, ui_active, ttsControlEnabled) -----return-- serverFrameNum1_G = serverFrameNum1 ui_active_G = ui_active gameProgressActive_G = true end function widget:Update(dt) --this function run 4th. It update the progressBar if ui_active_G then oneSecondElapsed_G = oneSecondElapsed_G + dt if oneSecondElapsed_G >= 1 then --wait for 1 second period -----var localize----- local serverFrameNum1 = serverFrameNum1_G local serverFrameNum2 = serverFrameNum2_G local oneSecondElapsed = oneSecondElapsed_G local myLastFrameNum = myLastFrameNum_G local serverFrameRate = serverFrameRate_G local myGameFrame = myGameFrame_G local simpleMovingAverageLocalSpeed = simpleMovingAverageLocalSpeed_G -----localize local serverFrameNum = serverFrameNum1 or serverFrameNum2 --use FrameNum from GameProgress if available, else use FrameNum derived from LUA_msg. serverFrameNum = serverFrameNum + serverFrameRate*oneSecondElapsed -- estimate Server's frame number after each widget:Update() while waiting for GameProgress() to refresh with actual value. local frameDistanceToFinish = serverFrameNum-myGameFrame local myGameFrameRate = (myGameFrame - myLastFrameNum) / oneSecondElapsed --Method1: simple average --[[ averageLocalSpeed_G.sumOfSpeed = averageLocalSpeed_G.sumOfSpeed + myGameFrameRate -- try to calculate the average of local gameFrame speed. averageLocalSpeed_G.sumCounter = averageLocalSpeed_G.sumCounter + 1 myGameFrameRate = averageLocalSpeed_G.sumOfSpeed/averageLocalSpeed_G.sumCounter -- using the average to calculate the estimate for time of completion. --]] --Method2: simple moving average myGameFrameRate = SimpleMovingAverage(myGameFrameRate, simpleMovingAverageLocalSpeed) -- get our average frameRate local timeToComplete = frameDistanceToFinish/myGameFrameRate -- estimate the time to completion. local timeToComplete_string = "?/?" local minute, second = math.modf(timeToComplete/60) --second divide by 60sec-per-minute, then saperate result from its remainder second = 60*second --multiply remainder with 60sec-per-minute to get second back. timeToComplete_string = string.format ("Time Remaining: %d:%02d" , minute, second) progress_vote:SetCaption(timeToComplete_string) progress_vote:SetValue(myGameFrame/serverFrameNum) oneSecondElapsed = 0 myLastFrameNum = myGameFrame if serverFrameNum1 then serverFrameNum1 = serverFrameNum --update serverFrameNum1 if value from GameProgress() is used, else serverFrameNum2 = serverFrameNum end --update serverFrameNum2 if value from LuaRecvMsg() is used. -----return serverFrameNum1_G = serverFrameNum1 serverFrameNum2_G = serverFrameNum2 oneSecondElapsed_G = oneSecondElapsed myLastFrameNum_G = myLastFrameNum simpleMovingAverageLocalSpeed_G = simpleMovingAverageLocalSpeed end end end local function RemoveLUARecvMsg(n) if n > 150 then iAmReplay_G = nil spGetSpectatingState = nil --de-reference the function so that garbage collector can clean it up. widgetHandler:RemoveCallIn("RecvLuaMsg") --remove unused method for increase efficiency after frame> timestampLimit (150frame or 5 second). functionContainer_G = function(x) end --replace this function with an empty function/method end end function widget:GameFrame(n) --this function run at all time. It update current gameFrame myGameFrame_G = n functionContainer_G(n) --function that are able to remove itself. Reference: gui_take_reminder.lua (widget by EvilZerggin, modified by jK) end --//thanks to Rafal[0K] for pointing to the rolling average idea. function SimpleMovingAverage(myGameFrameRate, simpleMovingAverageLocalSpeed) --//remember current frameRate, and advance table index by 1 local index = (simpleMovingAverageLocalSpeed.index) --retrieve current index. simpleMovingAverageLocalSpeed.storage[index] = myGameFrameRate --remember current frameRate at current index. simpleMovingAverageLocalSpeed.index = simpleMovingAverageLocalSpeed.index +1 --advance index by 1. --//wrap table index around. Create a circle local poolingSize = 10 --//number of sample. note: simpleMovingAverage() is executed every second, so the value represent an average spanning 10 second. if (simpleMovingAverageLocalSpeed.index == (poolingSize + 2)) then --when table out-of-bound: simpleMovingAverageLocalSpeed.index = 1 --wrap the table index around (create a circle of 150 + 1 (ie: poolingSize plus 1 space) entry). end --//update averages index = (simpleMovingAverageLocalSpeed.index) --retrieve an index advanced by 1. local oldAverage = (simpleMovingAverageLocalSpeed.storage[index] or defaultAverage_G) --retrieve old average or use initial/default average as old average. simpleMovingAverageLocalSpeed.runningAverage = simpleMovingAverageLocalSpeed.runningAverage + myGameFrameRate/poolingSize - oldAverage/poolingSize --calculate average: add new value, remove old value. Ref: http://en.wikipedia.org/wiki/Moving_average#Simple_moving_average local avgGameFrameRate = simpleMovingAverageLocalSpeed.runningAverage -- replace myGameFrameRate with its average value. return avgGameFrameRate, simpleMovingAverageLocalSpeed end function CheckTTSwidget() local ttsValue --[[ local widget = widgetHandler:FindWidget("Text To Speech Control") --find widget. Reference: gui_epicmenu.lua by Carrepairer/Wagonrepairer if widget then --get all variable from TTS control widget. ttsValue = widget.options.enable.value --get the value else --If widget is not found, then 'Rejoin Progress widget' will not try to disable/enable TTS. It became neutral. ttsValue = false --disable TTS control end --]] if WG.textToSpeechCtrl then ttsValue = WG.textToSpeechCtrl.ttsEnable --retrieve Text-To-Speech widget settings from global table. else ttsValue = false end return ttsValue end ---------------------------------------------------------- --Chili-------------------------------------------------- function widget:Initialize() functionContainer_G = RemoveLUARecvMsg myPlayerID_G = Spring.GetMyPlayerID() iAmReplay_G = Spring.IsReplay() -- setup Chili Chili = WG.Chili Button = Chili.Button Label = Chili.Label Colorbars = Chili.Colorbars Window = Chili.Window StackPanel = Chili.StackPanel Image = Chili.Image Progressbar = Chili.Progressbar Control = Chili.Control screen0 = Chili.Screen0 --create main Chili elements -- local height = tostring(math.floor(screenWidth/screenHeight*0.35*0.35*100)) .. "%" -- local y = tostring(math.floor((1-screenWidth/screenHeight*0.35*0.35)*100)) .. "%" local screenWidth, screenHeight = Spring.GetWindowGeometry() local y = screenWidth*2/11 + 32 -- local labelHeight = 24 -- local fontSize = 16 window = Window:New{ --parent = screen0, name = 'rejoinProgress'; color = {0, 0, 0, 0}, width = 260, height = 60, left = 2, --dock left? y = y, --halfway on screen? dockable = true, draggable = false, --disallow drag to avoid capturing mouse click resizable = false, tweakDraggable = true, tweakResizable = true, minWidth = MIN_WIDTH, minHeight = MIN_HEIGHT, padding = {0, 0, 0, 0}, savespace = true, --probably could save space? --itemMargin = {0, 0, 0, 0}, } stack_main = StackPanel:New{ parent = window, resizeItems = true; orientation = "vertical"; height = "100%"; width = "100%"; padding = {0, 0, 0, 0}, itemMargin = {0, 0, 0, 0}, } label_title = Label:New{ parent = stack_main, autosize=false; align="center"; valign="top"; caption = ''; height = 16, width = "100%"; } --[[ stack_vote = StackPanel:New{ parent = stack_main, resizeItems = true; orientation = "horizontal"; y = (40*(1-1))+15 ..'%', height = "40%"; width = "100%"; padding = {0, 0, 0, 0}, itemMargin = {0, 0, 0, 0}, } --]] progress_vote = Progressbar:New{ parent = stack_main, x = "0%", y = '40%', --position at 40% of the window's height width = "100%"; --maximum width height = "100%", max = 1; caption = "?/?"; color = {0.9,0.15,0.2,1}; --Red, {0.2,0.9,0.3,1} --Green } progress_vote:SetValue(0) voteCount = 0 voteMax = 1 -- protection against div0 label_title:SetCaption("Catching up.. Please Wait") if forceDisplay then ActivateGUI_n_TTS (1, false, false, 0) --force GUI to display for testing return end end ---------------------------------------------------------- --fix for Game Progress delay----------------------------- function widget:RecvLuaMsg(bigMsg, playerID) --this function run 2nd. It read the LUA timestamp if forceDisplay then ActivateGUI_n_TTS (1, false, false, 0) --force GUI to display for testing return end if gameProgressActive_G or iAmReplay_G then --skip LUA message if gameProgress is already active OR game is a replay return false end local iAmSpec = spGetSpectatingState() local myMsg = (playerID == myPlayerID_G) if (myMsg or iAmSpec) then if bigMsg:sub(1,9) == "rejnProg " then --check for identifier -----var localize----- local ui_active = ui_active_G local submittedTimestamp = submittedTimestamp_G local myTimestamp = myTimestamp_G -----localize local timeMsg = bigMsg:sub(10) --saperate time-message from the identifier local systemSecond = tonumber(timeMsg) --Spring.Echo(systemSecond .. " B") submittedTimestamp[#submittedTimestamp +1] = systemSecond --store all submitted timestamp from each players local sumSecond= 0 for i=1, #submittedTimestamp,1 do sumSecond = sumSecond + submittedTimestamp[i] end --Spring.Echo(sumSecond .. " C") local avgSecond = sumSecond/#submittedTimestamp --Spring.Echo(avgSecond .. " D") local secondDiff = myTimestamp - avgSecond --Spring.Echo(secondDiff .. " E") local frameDiff = secondDiff*30 local serverFrameNum2 = frameDiff --this value represent the estimate difference in frame when everyone was submitting their timestamp at game start. Therefore the difference in frame will represent how much frame current player are ahead of us. local ttsControlEnabled = CheckTTSwidget() ui_active = ActivateGUI_n_TTS (frameDiff, ui_active, ttsControlEnabled, 1800) -----return ui_active_G = ui_active serverFrameNum2_G = serverFrameNum2 submittedTimestamp_G = submittedTimestamp end end end function widget:GameStart() --this function run 1st, before any other function. It send LUA timestamp --local format = "%H:%M" local currentTime = os.date("!*t") --ie: clock on "gui_epicmenu.lua" (widget by CarRepairer), UTC & format: http://lua-users.org/wiki/OsLibraryTutorial local systemSecond = currentTime.hour*3600 + currentTime.min*60 + currentTime.sec local myTimestamp = systemSecond --Spring.Echo(systemSecond .. " A") local timestampMsg = "rejnProg " .. systemSecond --currentTime --create a timestamp message Spring.SendLuaUIMsg(timestampMsg) --this message will remain in server's cache as a LUA message which rejoiner can intercept. Thus allowing the game to leave a clue at game start for latecomer. The latecomer will compare the previous timestamp with present and deduce the catch-up time. ------return myTimestamp_G = myTimestamp end
gpl-2.0
Unrepentant-Atheist/mame
3rdparty/genie/src/_premake_main.lua
6
4416
-- -- _premake_main.lua -- Script-side entry point for the main program logic. -- Copyright (c) 2002-2011 Jason Perkins and the Premake project -- _WORKING_DIR = os.getcwd() -- -- Inject a new target platform into each solution; called if the --platform -- argument was specified on the command line. -- local function injectplatform(platform) if not platform then return true end platform = premake.checkvalue(platform, premake.fields.platforms.allowed) for sln in premake.solution.each() do local platforms = sln.platforms or { } -- an empty table is equivalent to a native build if #platforms == 0 then table.insert(platforms, "Native") end -- the solution must provide a native build in order to support this feature if not table.contains(platforms, "Native") then return false, sln.name .. " does not target native platform\nNative platform settings are required for the --platform feature." end -- add it to the end of the list, if it isn't in there already if not table.contains(platforms, platform) then table.insert(platforms, platform) end sln.platforms = platforms end return true end -- -- Script-side program entry point. -- function _premake_main(scriptpath) -- if running off the disk (in debug mode), load everything -- listed in _manifest.lua; the list divisions make sure -- everything gets initialized in the proper order. if (scriptpath) then local scripts = dofile(scriptpath .. "/_manifest.lua") for _,v in ipairs(scripts) do dofile(scriptpath .. "/" .. v) end end -- Now that the scripts are loaded, I can use path.getabsolute() to properly -- canonicalize the executable path. _PREMAKE_COMMAND = path.getabsolute(_PREMAKE_COMMAND) -- Set up the environment for the chosen action early, so side-effects -- can be picked up by the scripts. premake.action.set(_ACTION) -- Seed the random number generator so actions don't have to do it themselves math.randomseed(os.time()) -- If there is a project script available, run it to get the -- project information, available options and actions, etc. if (nil ~= _OPTIONS["file"]) then local fname = _OPTIONS["file"] if (os.isfile(fname)) then dofile(fname) else error("No genie script '" .. fname .. "' found!", 2) end else local dir, name = premake.findDefaultScript(path.getabsolute("./")) if dir ~= nil then os.chdir(dir) dofile(name) end end -- Process special options if (_OPTIONS["version"] or _OPTIONS["help"] or not _ACTION) then printf("GENie - Project generator tool %s", _GENIE_VERSION_STR) printf("https://github.com/bkaradzic/GENie") if (not _OPTIONS["version"]) then premake.showhelp() end return 1 end -- Validate the command-line arguments. This has to happen after the -- script has run to allow for project-specific options action = premake.action.current() if (not action) then error("Error: no such action '" .. _ACTION .. "'", 0) end ok, err = premake.option.validate(_OPTIONS) if (not ok) then error("Error: " .. err, 0) end -- Sanity check the current project setup ok, err = premake.checktools() if (not ok) then error("Error: " .. err, 0) end -- If a platform was specified on the command line, inject it now ok, err = injectplatform(_OPTIONS["platform"]) if (not ok) then error("Error: " .. err, 0) end local profiler = newProfiler() if (nil ~= _OPTIONS["debug-profiler"]) then profiler:start() end -- work-in-progress: build the configurations print("Building configurations...") premake.bake.buildconfigs() if (nil ~= _OPTIONS["debug-profiler"]) then profiler:stop() local filePath = path.getabsolute("GENie-profiler-bake.txt") print("Writing debug-profiler report " .. filePath .. ".") local outfile = io.open(filePath, "w+") profiler:report(outfile) outfile:close() end ok, err = premake.checkprojects() if (not ok) then error("Error: " .. err, 0) end premake.stats = { } premake.stats.num_generated = 0 premake.stats.num_skipped = 0 -- Hand over control to the action printf("Running action '%s'...", action.trigger) premake.action.call(action.trigger) printf("Done. Generated %d/%d projects." , premake.stats.num_generated , premake.stats.num_generated+premake.stats.num_skipped ) return 0 end
gpl-2.0
Satoshi-t/Re-SBS
lang/zh_CN/Package/SPPackage.lua
1
39476
-- translation for SP Package return { ["sp"] = "SP", ["#yangxiu"] = "恃才放旷", ["yangxiu"] = "杨修", ["illustrator:yangxiu"] = "张可", ["jilei"] = "鸡肋", [":jilei"] = "每当你受到伤害后,你可以选择一种牌的类别,伤害来源不能使用、打出或弃置其该类别的手牌,直到回合结束。", ["@jilei_basic"] = "鸡肋(基本牌)", ["@jilei_equip"] = "鸡肋(装备牌)", ["@jilei_trick"] = "鸡肋(锦囊牌)", ["danlao"] = "啖酪", [":danlao"] = "每当至少两名角色成为锦囊牌的目标后,若你为目标角色,你可以摸一张牌,然后该锦囊牌对你无效。", ["#Jilei"] = "由于“<font color=\"yellow\"><b>鸡肋</b></font>”效果,%from 本回合不能使用、打出或弃置 %arg", ["#JileiClear"] = "%from 的“<font color=\"yellow\"><b>鸡肋</b></font>”效果消失", ["#gongsunzan"] = "白马将军", ["gongsunzan"] = "SP公孙瓒", ["&gongsunzan"] = "公孙瓒", ["illustrator:gongsunzan"] = "Vincent", ["yicong"] = "义从", [":yicong"] = "锁定技。若你的体力值大于2,你与其他角色的距离-1;若你的体力值小于或等于2,其他角色与你的距离+1。", ["#yuanshu"] = "仲家帝", ["yuanshu"] = "SP袁术", ["&yuanshu"] = "袁术", ["illustrator:yuanshu"] = "吴昊", ["yongsi"] = "庸肆", [":yongsi"] = "锁定技。摸牌阶段,你额外摸X张牌。弃牌阶段开始时,你须弃置X张牌。(X为现存势力数)", ["weidi"] = "伪帝", [":weidi"] = "[NoAutoRep]<font color=#0000FF><b>锁定技。</b></font>你拥有且可以发动主公的主公技。", ["@weidi-jijiang"] = "请发动“激将”", ["#YongsiGood"] = "%from 的“%arg2”被触发,额外摸了 %arg 张牌", ["#YongsiBad"] = "%from 的“%arg2”被触发,须弃置 %arg 张牌", ["#YongsiJilei"] = "%from 的“%arg2”被触发,由于“<font color=\"yellow\"><b>鸡肋</b></font>”的效果,仅弃置了 %arg 张牌", ["#YongsiWorst"] = "%from 的“%arg2”被触发,弃置了所有牌(共 %arg 张)", ["#sp_guanyu"] = "汉寿亭侯", ["sp_guanyu"] = "SP关羽", ["&sp_guanyu"] = "关羽", ["illustrator:sp_guanyu"] = "LiuHeng", ["danji"] = "单骑", [":danji"] = "觉醒技。准备阶段开始时,若你的手牌数大于体力值,且本局游戏主公为曹操,你失去1点体力上限,然后获得“马术”。", ["$DanjiAnimate"] = "image=image/animate/danji.png", ["#DanjiWake"] = "%from 的手牌数 %arg 大于体力值 %arg2 ,且本局游戏主公为曹操,触发“<font color=\"yellow\"><b>单骑</b></font>”觉醒", ["#caohong"] = "福将", ["caohong"] = "曹洪", ["illustrator:caohong"] = "LiuHeng", ["yuanhu"] = "援护", [":yuanhu"] = "结束阶段开始时,你可以将一张装备牌置于一名角色装备区内:若此牌为武器牌,你弃置该角色距离1的一名角色区域内的一张牌;若此牌为防具牌,该角色摸一张牌;若此牌为坐骑牌,该角色回复1点体力。", ["@yuanhu-equip"] = "你可以发动“援护”", ["@yuanhu-discard"] = "请选择 %src 距离1的一名角色", ["~yuanhu"] = "选择一张装备牌→选择一名角色→点击确定", ["#guanyinping"] = "武姬", ["guanyinping"] = "关银屏", ["illustrator:guanyinping"] = "木美人", ["xueji"] = "血祭", [":xueji"] = "阶段技。你可以弃置一张红色牌并选择你攻击范围内的至多X名角色:若如此做,你对这些角色各造成1点伤害,然后这些角色各摸一张牌。(X为你已损失的体力值)", ["huxiao"] = "虎啸", [":huxiao"] = "锁定技。每当你于出牌阶段使用【杀】被【闪】抵消后,本阶段你可以额外使用一张【杀】。", ["wuji"] = "武继", [":wuji"] = "觉醒技。结束阶段开始时,若你于本回合造成了至少3点伤害,你增加1点体力上限,回复1点体力,然后失去“虎啸”。", ["$WujiAnimate"] = "image=image/animate/wuji.png", ["#WujiWake"] = "%from 本回合已造成 %arg 点伤害,触发“%arg2”觉醒", ["#xiahouba"] = "棘途壮志", ["xiahouba"] = "夏侯霸", ["illustrator:xiahouba"] = "熊猫探员", ["baobian"] = "豹变", [":baobian"] = "锁定技。若你的体力值为:3或更低,你拥有“挑衅”;2或更低,你拥有“咆哮”;1或更低,你拥有“神速”。", ["#chenlin"] = "破竹之咒", ["chenlin"] = "陈琳", ["illustrator:chenlin"] = "木美人", ["bifa"] = "笔伐", [":bifa"] = "结束阶段开始时,你可以将一张手牌扣置于一名无“笔伐牌”的其他角色旁:若如此做,该角色的回合开始时,其观看此牌,然后选择一项:1.交给你一张与此牌类型相同的牌并获得此牌;2.将此牌置入弃牌堆,然后失去1点体力。", ["@bifa-remove"] = "你可以发动“笔伐”", ["~bifa"] = "选择一张手牌→选择一名其他角色→点击确定", ["@bifa-give"] = "请交给目标角色一张类型相同的手牌", ["songci"] = "颂词", [":songci"] = "出牌阶段,你可以令一名手牌数大于体力值的角色弃置两张牌,或令一名手牌数小于体力值的角色摸两张牌。对每名角色限一次。", ["$BifaView"] = "%from 观看了 %arg 牌 %card", ["@songci"] = "颂词", ["#erqiao"] = "江东之花", ["erqiao"] = "大乔&小乔", ["&erqiao"] = "大乔小乔", ["illustrator:erqiao"] = "木美人", ["xingwu"] = "星舞", [":xingwu"] = "弃牌阶段开始时,你可以将一张与你本回合使用的牌颜色均不同的手牌置于武将牌上:若你有至少三张“星舞牌”,你将之置入弃牌堆并选择一名男性角色,该角色受到2点伤害并弃置其装备区的所有牌。", ["@xingwu"] = "你可以发动“星舞”将一张手牌置于武将牌上", ["@xingwu-choose"] = "请选择一名男性角色", ["luoyan"] = "落雁", [":luoyan"] = "锁定技。若你的武将牌上有“星舞牌”,你拥有“天香”和“流离”。", ["#xiahoushi"] = "疾冲之恋", ["xiahoushi"] = "夏侯氏", ["illustrator:xiahoushi"] = "牧童的短笛", ["yanyu"] = "燕语", [":yanyu"] = "一名角色的出牌阶段开始时,你可以弃置一张牌:若如此做,本回合的出牌阶段内限三次,一张与此牌类型相同的牌置入弃牌堆时,你可以令一名角色获得之。", ["@yanyu-discard"] = "你可以弃置一张牌发动“燕语”", ["@yanyu-give"] = "你可以令一名角色获得 %arg[%arg2]", ["xiaode"] = "孝德", [":xiaode"] = "每当一名其他角色死亡结算后,你可以拥有该角色武将牌上的一项技能(除主公技与觉醒技),且“孝德”无效,直到你的回合结束时。每当你失去“孝德”后,你失去以此法获得的技能。", ["#zhangbao"] = "地公将军", ["zhangbao"] = "张宝", ["illustrator:zhangbao"] = "大佬荣", ["zhoufu"] = "咒缚", [":zhoufu"] = "阶段技。你可以将一张手牌置于一名无“咒缚牌”的其他角色旁:若如此做,该角色进行判定时,以“咒缚牌”作为判定牌。一名角色的回合结束后,若该角色有“咒缚牌”,你获得此牌。", ["incantation"] = "咒缚", ["yingbing"] = "影兵", [":yingbing"] = "每当一张“咒缚牌”成为判定牌后,你可以摸两张牌。", ["$ZhoufuJudge"] = "%from 的判定牌为 %arg 牌 %card", ["#caoang"] = "取义成仁", ["caoang"] = "曹昂", ["illustrator:caoang"] = "MSNZero", ["kangkai"] = "慷忾", [":kangkai"] = "每当一名距离1以内的角色成为【杀】的目标后,你可以摸一张牌,然后正面朝上交给该角色一张牌:若此牌为装备牌,该角色可以使用之。", ["@kangkai-give"] = "请交给 %src 一张牌", ["kangkai_use:use"] = "你可以使用该装备牌", ["#xingcai"] = "敬哀皇后", ["xingcai"] = "星彩", ["illustrator:xingcai"] = "depp", ["shenxian"] = "甚贤", [":shenxian"] = "你的回合外,每当一名其他角色因弃置而失去牌后,若其中有基本牌,你可以摸一张牌。", ["qiangwu"] = "枪舞", [":qiangwu"] = "阶段技。你可以进行判定:若如此做,本回合,你使用点数小于判定牌点数的【杀】无距离限制,你使用点数大于判定牌点数的【杀】无次数限制且不计入次数限制。", ["#zumao"] = "碧血染赤帻", ["zumao"] = "祖茂", ["illustrator:zumao"] = "DH", ["yinbing"] = "引兵", [":yinbing"] = "结束阶段开始时,你可以将至少一张非基本牌置于武将牌上。每当你受到【杀】或【决斗】的伤害后,你将一张“引兵牌”置入弃牌堆。", ["@yinbing"] = "你可以发动“引兵”", ["~yinbing"] = "选择至少一张非基本牌→点击确定", ["juedi"] = "绝地", [":juedi"] = "准备阶段开始时,若你有“引兵牌”,你可以选择一项:1.将这些牌置入弃牌堆并摸等量的牌;2.令一名体力值不大于你的其他角色回复1点体力并获得这些牌。", ["@juedi"] = "你可以选择一名体力值不大于你的其他角色,否则你将“引兵牌”置入弃牌堆并摸等量的牌", ["#zhugedan"] = "薤露蒿里", ["zhugedan"] = "诸葛诞", ["illustrator:zhugedan"] = "雪君S", ["gongao"] = "功獒", [":gongao"] = "锁定技。每当一名其他角色死亡时,你增加1点体力上限,回复1点体力。", ["juyi"] = "举义", [":juyi"] = "觉醒技。准备阶段开始时,若你已受伤且体力上限大于角色数,你将手牌补至体力上限,然后获得“崩坏”和“威重”(锁定技。每当你的体力上限改变后,你摸一张牌)。", ["weizhong"] = "威重", [":weizhong"] = "锁定技。每当你的体力上限改变后,你摸一张牌。", ["$JuyiAnimate"] = "image=image/animate/juyi.png", ["#JuyiWake"] = "%from 的体力上限(%arg)大于角色数(%arg2),触发“<font color=\"yellow\"><b>举义</b></font>”觉醒", ["#sunluyu"] = "舍身饲虎", ["sunluyu"] = "孙鲁育", ["illustrator:sunluyu"] = "depp", ["meibu"] = "魅步", [":meibu"] = "一名其他角色的出牌阶段开始时,若你不在其攻击范围内,你可以令该角色的锦囊牌均视为【杀】,直到回合结束:若如此做,本回合你在其攻击范围内。", ["mumu"] = "穆穆", [":mumu"] = "结束阶段开始时,若你未于本回合出牌阶段内造成伤害,你可以选择一项:弃置一名角色装备区的武器牌,然后摸一张牌;或将一名其他角色装备区的防具牌移动至你的装备区(替换原装备)。", ["@mumu-weapon"] = "你可以弃置一名角色装备区的武器牌", ["@mumu-armor"] = "你可以将一名其他角色装备区的防具牌移动至你的装备区", ["#maliang"] = "白眉智士", ["maliang"] = "马良", ["illustrator:maliang"] = "LiuHeng", ["xiemu"] = "协穆", [":xiemu"] = "阶段技。你可以弃置一张【杀】并选择一个势力:若如此做,直到你的回合开始时,每当你成为该势力的角色的黑色牌的目标后,你摸两张牌。", ["naman"] = "纳蛮", [":naman"] = "每当其他角色打出的【杀】因打出而置入弃牌堆时,你可以获得之。", ["#chengyu"] = "泰山捧日", ["chengyu"] = "程昱", ["illustrator:chengyu"] = "GH", ["shefu"] = "设伏", [":shefu"] = "结束阶段开始时,你可以将一张手牌扣置于武将牌旁,称为“伏兵”,并为该牌记录一种基本牌或锦囊牌的牌名(与其他“伏兵”均不相同)。你的回合外,每当一名角色使用基本牌或锦囊牌时,若此牌的牌名与一张“伏兵”的记录相同,你可以将此“伏兵”置入弃牌堆:若如此做,此牌无效。", ["ambush"] = "伏兵", ["@shefu-prompt"] = "你可以发动“设伏”", ["~shefu"] = "在对话框中选择牌名→选择一张手牌→点击确定", ["shefu_cancel:data"] = "你可以发动“设伏”令【%arg】无效<br/> <b>注</b>: 若你无对应牌名的“伏兵”则没有任何效果", ["benyu"] = "贲育", [":benyu"] = "每当你受到有来源的伤害后,若伤害来源存活,若你的手牌数:小于X,你可以将手牌补至X(至多为5)张;大于X,你可以弃置至少X+1张手牌,然后对伤害来源造成1点伤害。(X为伤害来源的手牌数)", ["@benyu-discard"] = "你可以发动“贲育”弃置至少 %arg 张手牌对 %dest 造成1点伤害", ["~benyu"] = "选择足量的手牌→点击确定", ["$ShefuRecord"] = "%from 为 %card 记录牌名【%arg】", ["#ShefuEffect"] = "%from 发动了“%arg2”,%to 使用的【%arg】无效", ["#huangjinleishi"] = "雷祭之姝", ["huangjinleishi"] = "黄巾雷使", ["illustrator:huangjinleishi"] = "depp", ["fulu"] = "符箓", [":fulu"] = "你可以将一张普通【杀】当雷【杀】使用。", ["zhuji"] = "助祭", [":zhuji"] = "每当一名角色造成雷电伤害时,你可以令其进行判定:若结果为黑色,此伤害+1;红色,其获得判定牌。", ["#ZhujiBuff"] = "%from 的“<font color=\"yellow\"><b>助祭</b></font>”效果被触发,伤害从 %arg 点增加至 %arg2 点", ["#sp_wenpin"] = "坚城宿将", ["sp_wenpin"] = "文聘", ["illustrator:sp_wenpin"] = "G.G.G." , ["spzhenwei"] = "镇卫", [":spzhenwei"] = "每当一名体力值小于你的角色成为【杀】或黑色锦囊牌的目标时,若目标数为1,你可以弃置一张牌,选择一项:1.你摸一张牌,若如此做,将此牌转移给你;2.此牌无效,然后将此牌置于使用者的武将牌旁,称为“兵”,一名角色的回合结束时,一名角色获得其所有的“兵”。", ["zhenweipile"] = "兵", ["@sp_zhenwei"] = "你可以对 %src 发动“<font color=\"yellow\"><b>镇卫</b></font>”", ["@qiaoshui-add:::collateral"] = "你可以对 %src 发动“<font color=\"yellow\"><b>镇卫</b></font>”", ["spzhenwei:draw"] = "摸一张牌,然后成为此牌的目标", ["spzhenwei:null"] = "令此牌失效并将之移出游戏", ["simalang"] = "司马朗", ["#simalang"] = "再世神农" , ["illustrator:spsimalang"] = "Sky", ["cv:simalang"] = "", ["junbing"] = "郡兵", [":junbing"] = "一名角色的结束阶段开始时,若其手牌数小于等于1,其可以摸一张牌。若如此做,该角色须将所有手牌交给你,然后你交给其等量的牌。", ["junbing:junbing_invoke"] = "你要发动 %src 的技能“<font color=\"yellow\"><b>郡兵</b></font>”吗?", ["@junbing-return"] = "%src 发动“<font color=\"yellow\"><b>郡兵</b></font>”将所有手牌(%arg 张)交给你,请选择要交给 %src 的手牌。", ["quji"] = "去疾", [":quji"] = "出牌阶段限一次,你可以弃置X张牌(X为你已损失的体力值)。然后令至多X名已受伤的角色各回复1点体力。若你以此法弃置的牌中有黑色牌,你失去1点体力。", ["#sunhao"] = "时日曷丧", ["sunhao"] = "孙皓", --SE神受我一拜,不过这吸毒一样的人一看就不是萌萌哒的SE! ["illustrator:sunhao"] = "Liuheng", ["canshi"] = "残蚀", [":canshi"] = "摸牌阶段开始时,你可以放弃摸牌,摸X张牌(X 为已受伤的角色数),若如此做,当你于此回合内使用基本牌或锦囊牌时,你弃置一张牌。", ["@canshi-discard"] = "请弃置一张牌", ["chouhai"] = "仇海", [":chouhai"] = "锁定技。当你受到伤害时,若你没有手牌,你令此伤害+1。", ["guiming"] = "归命", [":guiming"] = "主公技。锁定技。其他吴势力角色于你的回合内视为已受伤的角色。", ["OL"] = "OL专属", ["#zhugeke"] = "兴家赤族", ["zhugeke"] = "诸葛恪", ["illustrator:zhugeke"] = "LiuHeng", ["aocai"] = "傲才", [":aocai"] = "你的回合外,每当你需要使用或打出一张基本牌时,你可以观看牌堆顶的两张牌,然后使用或打出其中一张该类别的基本牌。", ["duwu"] = "黩武", [":duwu"] = "出牌阶段,你可以弃置任意数量的牌并选择攻击范围内的一名体力值等于该数量的角色:若如此做,你对该角色造成1点伤害。若此伤害令该角色进入濒死状态,濒死结算后你失去1点体力,且本阶段“黩武”无效。", ["#AocaiUse"] = "%from 发动 %arg 使用/打出了牌堆顶的第 %arg2 张牌", ["#lingcao"] = "侠义先锋", -- unofficial ["lingcao"] = "凌操", ["illustrator:lingcao"] = "樱花闪乱", -- unofficial, origin: 凌统 (一将成名2011参赛稿) ["dujin"] = "独进", [":dujin"] = "摸牌阶段,你可以额外摸X+1张牌。(X为你装备区的牌数的一半,向下取整)", ["#sunru"] = "温善贤惠", -- unofficial ["sunru"] = "孙茹", ["illustrator:sunru"] = "Yi章", -- unofficial, origin: 步练师 (一将成名2012参赛稿) ["qingyi"] = "轻逸", [":qingyi"] = "你可以跳过判定阶段和摸牌阶段:若如此做,视为你使用一张无距离限制的【杀】。", ["@qingyi-slash"] = "你可以跳过判定阶段和摸牌阶段发动“轻逸”", ["~qingyi"] = "选择【杀】的目标角色→点击确定", ["shixin"] = "释衅", [":shixin"] = "锁定技。每当你受到火焰伤害时,防止此伤害。", ["#ShixinProtect"] = "%from 的“<font color=\"yellow\"><b>释衅</b></font>”被触发,防止了 %arg 点伤害[%arg2]", ["#ol_masu"] = "恃才傲物", ["ol_masu"] = "OL马谡", ["&ol_masu"] = "马谡", ["illustrator:ol_masu"] = "张帅", ["sanyao"] = "散谣", [":sanyao"] = "阶段技。你可以弃置一张牌并选择一名体力值为场上最多(或之一)的角色:若如此做,该角色受到1点伤害。", ["zhiman"] = "制蛮", [":zhiman"] = "每当你对一名角色造成伤害时,你可以防止此伤害,然后获得其装备区或判定区的一张牌。", ["#ol_yujin"] = "魏武之刚", ["ol_yujin"] = "OL于禁", ["&ol_yujin"] = "于禁", ["illustrator:ol_yujin"] = "Yi章", ["jieyue"] = "节钺", [":jieyue"] = "结束阶段开始时,你可以弃置一张手牌,然后令一名其他角色选择一项:将一张牌置于你的武将牌上;或令你弃置其一张牌。你武将牌上有牌时,你可以将红色手牌当【闪】、黑色的手牌当【无懈可击】使用或打出。准备阶段开始时,你获得你武将牌上的牌。", ["@jieyue"] = "你可以发动“<font color=\"yellow\"><b>节钺</b></font>”", ["~jieyue"] = "选择一张手牌并选择一名目标角色→点击确定", ["@jieyue_put"] = "%src 对你发动了“<font color=\"yellow\"><b>节钺</b></font>”,请将一张牌置于其武将牌上,或点“取消”令其弃置你的一张牌", ["jieyue_pile"] = "节钺", ["hanba"] = "旱魃", ["#hanba"] = "如惔如焚", ["illustrator:hanba"] = "雪君s", ["fentian"] = "焚天", [":fentian"] = "锁定技,结束阶段开始时,若你的手牌数小于你的体力值,你选择一名你攻击范围内的角色,将其一张牌置于你的武将牌上,称为“焚”。锁定技,你的攻击范围+X(X为“焚”的数量)。", ["@fentian-choose"] = "请选择一名攻击范围内的角色", ["burn"] = "焚", ["zhiri"] = "炙日", [":zhiri"] = "觉醒技,准备阶段开始时,若“焚”数不小于3,你减1点体力上限,然后获得技能“心惔”(出牌阶段限一次,你可以将两张“焚”置入弃牌堆并选择一名角色,该角色失去一点体力)。", ["xintan"] = "心惔", [":xintan"] = "出牌阶段限一次,你可以将两张“焚”置入弃牌堆并选择一名角色,该角色失去一点体力。", ["#ol_liubiao"] = "跨蹈汉南", ["ol_liubiao"] = "OL刘表", ["&ol_liubiao"] = "刘表" , ["designer:liubiao"] = "管乐", ["illustrator:liubiao"] = "关东煮", ["olzishou"] = "自守", [":olzishou"] = "摸牌阶段摸牌时,你可以额外摸X张牌(X为现存势力数)。若如此做,你于本回合出牌阶段内使用的牌不能指定其他角色为目标。", ["ol_xingcai"] = "OL星彩" , ["&ol_xingcai"] = "星彩" , ["olshenxian"] = "甚贤" , [":olshenxian"] = "每名其他角色的回合限一次,你的回合外,每当有其他角色因弃置而失去牌时,若其中有基本牌,你可以摸一张牌。", ["ol_sunluyu"] = "OL孙鲁育" , ["&ol_sunluyu"] = "孙鲁育" , ["olmeibu"] = "魅步" , [":olmeibu"] = "一名其他角色的出牌阶段开始时,若你不在其攻击范围内,你可以令该角色的锦囊牌均视为【杀】,直到该角色以此法使用了一张【杀】或回合结束。若如此做,则直到回合结束,视为你在其攻击范围内。" , ["olmumu"] = "穆穆" , [":olmumu"] = "出牌阶段限一次,你可以弃置一张【杀】或黑色锦囊牌,然后选择一项:弃置场上一张武器牌,然后摸一张牌;或将场上的一张防具牌移动到你的装备区里(可替换原防具)。" , ["ol_xusheng"] = "OL徐盛" , ["&ol_xusheng"] = "徐盛" , ["olpojun"] = "破军" , [":olpojun"] = "出牌阶段,你的【杀】指定目标后,你可以将目标至多X张牌移出游戏外,若如此做,结束阶段开始时,其获得以此法移出游戏的牌(X为目标角色的体力值)。" , ["ol_sun1uyu"] = "OL孙鲁育-第二版" , ["&ol_sun1uyu"] = "孙鲁育" , ["#ol_sun1uyu"] = "舍身饲虎", ["olmeibu2"] = "魅步" , [":olmeibu2"] = "一名其他角色的出牌阶段开始时,若你不在其攻击范围内,你可以令该角色获得技能“止息”直到回合结束(锁定技,你使用了一张锦囊牌后,你的锦囊牌均视为【杀】)。若如此做,则直到回合结束,视为你在其攻击范围内。" , ["olmumu2"] = "穆穆" , [":olmumu2"] = "出牌阶段限一次,你可以弃置一张牌,然后选择一项:弃置场上的一张装备牌,然后摸一张牌;或获得场上的一张防具牌。若你以此法弃置的牌是【杀】或黑色锦囊牌,则直到你的下个回合开始,去掉技能“魅步”中的最后一句描述。" , ["shixie"] = "士燮" , ["#shixie"] = "南交学祖" , ["biluan"] = "避乱" , [":biluan"] = "摸牌阶段,你可以放弃摸牌,然后直到你的下回合开始,全场每有一个势力存活,其他角色计算与你的距离便+1。" , ["lixia"] = "礼下" , [":lixia"] = " 其他角色的结束阶段开始时,若你不在其攻击范围内,你可以摸一张牌,然后直到你的下回合开始,其他角色计算与你的距离-1。" , ["zhanglu"] = "张鲁" , ["#zhanglu"] = "五斗米道" , ["yishe"] = "义舍" , [":yishe"] = "结束阶段开始时,若你的武将牌上没有牌,你可以摸两张牌,然后将两张牌置于你的武将牌上,称为“米”;当你武将牌上最后的“米”移动到其他区域后,你回复1点体力。" , ["@yishe"] = "请选两张牌作为“米”", ["rice"] = "米", ["bushi"] = "布施" , ["@bushi"] = "请选一张“米”获得" , ["~bushi"] = "选择一张“米”→点击确定", [":bushi"] = "当你对其他角色造成1点伤害,或受到1点伤害后,该角色可以获得你武将牌上的一张“米”。" , ["midao"] = "米道" , [":midao"] = " 在一名角色的判定牌生效前,你可以打出一张“米”代替之。" , ["@midao-card"] = CommonTranslationTable["@askforretrial"], ["~midao"] = "选择一张牌→点击确定", ["mayunlu"] = "马云騄" , ["#mayunlu"] = "虎威夫人" , ["fengpo"] = "凤魄" , [":fengpo"] = " 当你于出牌阶段内使用【杀】或【决斗】仅指定一名角色为目标后,若此牌是你此阶段使用的第一张牌,则你可以选择一项:摸X张牌;此【杀】或【决斗】伤害+X(X为其手牌中方块牌的数量)。" , ["ol_caiwenji"] = "OL蔡文姬" , ["&ol_caiwenji"] = "蔡文姬" , ["#ol_caiwenji"] = "金壁之才", ["chenqing"] = "陈情" , [":chenqing"] = "每名角色的回合限一次,当一名角色处于濒死状态时,你可以令另一名其他角色摸四张牌,然后弃置四张牌。若其以此法弃置的牌花色各不相同,则视为该角色对濒死的角色使用一张【桃】。" , ["moshi"] = "默识" , [":moshi"] = "结束阶段开始时,你可以将一张手牌当你本回合出牌阶段使用的第一张基本或非延时类锦囊牌使用。然后,你可以将一张手牌当你本回合出牌阶段使用的第二张基本或非延时类锦囊牌使用。" , ["ol_madai"] = "OL马岱", ["&ol_madai"] = "马岱", ["illustrator:ol_madai"] = "琛·美弟奇", ["olqianxi"] = "潜袭" , [":olqianxi"] = "准备阶段开始时,你可以摸一张牌然后弃置一张牌。若如此做,你选择距离为1的一名其他角色,然后直到回合结束,该角色不能使用或打出与你以此法弃置的牌颜色相同的手牌。" , ["ol_wangyi"] = "OL王异", ["&ol_wangyi"] = "王异", ["illustrator:ol_wangyi"] = "团扇子大人", ["olmiji"] = "秘计" , [":olmiji"] = "结束阶段开始时,若你已受伤,你可以摸至多X张牌(X为你已损失的体力值)。若如此做,你可以将等量的手牌交给其他角色。" , -- E.SP 001 とある奇葩の凯撒 ["caesar"] = "凯撒", ["illustrator:caesar"] = "青骑士", ["conqueror"] = "征服", [":conqueror"] = "当你使用【杀】指定一个目标后,你可以选择一种牌的类别,令其选择一项:\n1.将一张此类别的牌交给你,若如此做,此次对其结算的此【杀】对其无效;\n2.不能使用【闪】响应此【杀】。 ", ["@conqueror-exchange"] = "%src 对你发动了“<font color=\"yellow\"><b>征服</b></font>”,请将一张 %arg 交给 %src", -- J.SP ["jiexian_sp"] = "界限突破-SP", ["JSP"] = "界限突破-SP", ["jsp_sunshangxiang"] = "J.SP孙尚香", ["&jsp_sunshangxiang"] = "孙尚香", ["#jsp_sunshangxiang"] = "梦醉良缘", ["liangzhu"] = "良助", [":liangzhu"] = "当一名角色于其出牌阶段内回复体力时,你可以选择一项:摸一张牌,或令该角色摸两张牌。", ["liangzhu:draw"] = "摸一张牌", ["liangzhu:letdraw"] = "让其摸两张牌", ["liangzhu:dismiss"] = "取消", ["fanxiang"] = "返乡", [":fanxiang"] = "觉醒技。准备阶段开始时,若全场有至少一名已受伤角色,且你曾发动过“良助”令其摸牌," .. "则你回复1点体力和体力上限,失去技能“良助”并获得技能“枭姬”。", ["jsp_machao"] = "J.SP马超", ["&jsp_machao"] = "马超", ["designer:jsp_machao"] = "伴剑一生", ["#jsp_machao"] = "西凉的猛狮", ["illustrator:jsp_machao"] = "depp", ["zhuiji"] = "追击", [":zhuiji"] = "<font color=\"blue\"><b>锁定技,</b></font>你计算体力值比你少的角色的距离始终为1。", ["cihuai"] = "刺槐", ["@cihuai"] = "刺槐", [":cihuai"] = "出牌阶段开始时,你可以展示你的手牌,若其中没有【杀】,则你使用或打出【杀】时不需要手牌,直到你的手牌数变化或有角色死亡。", ["jsp_guanyu"] = "J.SP关羽", ["&jsp_guanyu"] = "关羽", ["#jsp_guanyu"] = "汉寿亭侯", ["illustrator:jsp_guanyu"] = "Zero", ["jspdanqi"] = "单骑", [":jspdanqi"] = "觉醒技。准备阶段开始时,若你的手牌数大于你的体力值且主公不为刘备,你减1点体力上限,然后获得“马术”和“怒斩”。", ["nuzhan"] = "怒斩", [":nuzhan"] = "锁定技。你使用的由一张锦囊牌转化而来的【杀】不计入限制的使用次数;锁定技。你使用的由一张装备牌转化而来的【杀】的伤害值基数+1。", ["jsp_jiangwei"] = "J.SP姜维", ["&jsp_jiangwei"] = "姜维", ["#jsp_jiangwei"] = "幼麒", ["kunfen"] = "困奋", [":kunfen"] = "锁定技。结束阶段开始时你失去一点体力,然后摸两张牌。", ["fengliang"] = "逢亮", [":fengliang"] = "觉醒技。当你进入濒死状态时,你减1点体力上限并将体力值恢复至2点,然后获得技能“挑衅”,将技能“困奋”改为非锁定技。”", ["jsp_zhaoyun"] = "J.SP赵云" , ["&jsp_zhaoyun"] = "赵云" , ["#jsp_zhaoyun"] = "常山的游龙" , ["chixin"] = "赤心", [":chixin"] = "你可以将一张♦牌当【杀】或【闪】使用或打出。出牌阶段,你对此阶段内你没有对其使用过【杀】,且在你攻击范围内的角色使用【杀】无次数限制。" , ["suiren"] = "随仁", [":suiren"] = "限定技。准备阶段开始时,你可以失去技能“义从”,然后加1点体力上限并回复1点体力,再令一名角色摸三张牌。", ["@suiren-draw"] = "请选择“随仁”摸牌的角色", ["jsp_huangyueying"] = "J.SP黄月英" , ["&jsp_huangyueying"] = "黄月英" , ["#jsp_huangyueying"] = "闺中璞玉" , ["jiqiao"] = "机巧", [":jiqiao"] = "出牌阶段开始时,你可以弃置X张装备牌(X不小于1),然后亮出牌堆顶2X张牌,你获得其中的锦囊牌,将其余的牌置入弃牌堆。" , ["@jiqiao"] = "你可以发动“<font color=\"yellow\"><b>机巧</b></font>”", ["~jiqiao"] = "选择任意张装备牌→点击确定", ["linglong"] = "玲珑", [":linglong"] = "锁定技。若你的装备区没有防具牌,视为你装备【八卦阵】;若你的装备区没有坐骑牌,你的手牌上限+1;你的装备区没有宝物牌,视为你拥有技能“奇才”。", ["#linglong-treasure"] = "玲珑", --TWSP ["TaiwanYJCM"] = "台湾一将成名", ["Taiwan_yjcm"] = "台湾一将成名", ["twyj_xiahouba"] = "TW夏侯霸", ["&twyj_xiahouba"] = "夏侯霸", ["#twyj_xiahouba"] = "弃魏投蜀", ["illustrator:twyj_xiahouba"] = "王翎", ["designer:twyj_xiahouba"] = "阿呆", ["yinqin"] = "姻亲", [":yinqin"] = "准备阶段开始时,你可以将你的势力改为魏或蜀。 ", ["twbaobian"] = "豹变", [":twbaobian"] = "当你使用【杀】或【决斗】对目标角色造成伤害时,若其势力与你:相同,你可以防止此伤害,令其将手牌补至X张(X为其体力上限);\n不同且其手牌数大于其体力值,你可以弃置其Y张手牌(Y为其手牌数与体力值的差)。", ["twyj_zumao"] = "TW祖茂", ["&twyj_zumao"] = "祖茂", ["#twyj_zumao"] = "赤帻映苍天", ["illustrator:twyj_zumao"] = "黄智隆", ["designer:twyj_zumao"] = "ㄎㄎ", ["tijin"] = "替巾", [":tijin"] = "当其他角色使用【杀】指定目标时,若你在其攻击范围内且目标数为1,你可以将之转移给自己,若如此做,当此【杀】结算结束后,你弃置其一张牌。", ["twyj_caoang"] = "TW曹昂", ["&twyj_caoang"] = "曹昂", ["#twyj_caoang"] = "舍身救父", ["illustrator:twyj_caoang"] = "陈俊佐", ["designer:twyj_caoang"] = "Aaron", ["xiaolian"] = "孝廉", [":xiaolian"] = "当其他角色成为【杀】的目标时,若目标数为1,你可以将之转移给自己,若如此做,当你受到此【杀】造成的伤害后,你可以将一张牌置于其武将牌旁,称为“马”;\n锁定技,所有角色与武将牌旁有“马”的角色的距离+X(X为这些“马”数)", ["@xiaolian-put"] = "你可以发动“孝廉”将一张牌(包括装备牌)置于其武将牌上", ["xlhorse"] = "马", -- HuLao Pass ["Hulaopass"] = "虎牢关模式", ["HulaoPass"] = "虎牢关", ["#shenlvbu1"] = "最强神话", ["shenlvbu1"] = "吕布-虎牢关", ["&shenlvbu1"] = "最强神话", ["illustrator:shenlvbu1"] = "LiuHeng", ["#shenlvbu2"] = "暴怒的战神", ["shenlvbu2"] = "吕布-虎牢关", ["&shenlvbu2"] = "暴怒战神", ["illustrator:shenlvbu2"] = "LiuHeng", ["xiuluo"] = "修罗", [":xiuluo"] = "准备阶段开始时,你可以弃置一张与判定区内延时锦囊牌花色相同的手牌:若如此做,你弃置该延时锦囊牌。", ["@xiuluo"] = "请弃置一张与判定区某一张牌花色相同的手牌", ["shenwei"] = "神威", [":shenwei"] = "锁定技。摸牌阶段,你额外摸两张牌。你的手牌上限+2。", ["shenji"] = "神戟", [":shenji"] = "锁定技。若你的装备区没有武器牌,你使用【杀】可以额外选择至多两名目标。", ["#HulaoTransfigure"] = "%arg 变身为 %arg2, 第二阶段开始!", ["#Reforming"] = "%from 进入重整状态", ["#ReformingRecover"] = "%from 在重整状态中回复了 %arg 点体力", ["#ReformingDraw"] = "%from 在重整状态中摸了 %arg 张牌", ["#ReformingRevive"] = "%from 从重整状态中复活!", ["draw_1v3"] = "重整摸牌", ["weapon_recast"] = "武器重铸", ["Hulaopass:recover"] = "回复1点体力", ["Hulaopass:draw"] = "摸一张牌", ["StageChange"] = "第二阶段", ["sp_cards"] = "SP卡牌包", ["sp_moonspear"] = "银月枪", [":sp_moonspear"] = "装备牌·武器<br /><b>攻击范围</b>:3<br /><b>武器技能</b>:你的回合外,每当你使用或打出一张黑色牌时,你可以令你攻击范围内的一名角色打出一张【闪】,否则该角色受到1点伤害。", ["@sp_moonspear"] = "请选择攻击范围内的一名角色令其打出一张【闪】", ["@moon-spear-jink"] = "【银月枪】效果被触发,请打出一张【闪】", ["#zhuling"] = "良将之亚", ["zhuling"] = "朱灵", ["zhanyi"] = "战意", [":zhanyi"] = "<font color = 'green'><b>出牌阶段限一次</b></font>,你可以弃置一张牌并失去1点体力,然后根据你弃置的牌获得以下效果直到回合结束:\ ●基本牌,你可以将一张基本牌当任意一张基本牌使用或打出;\ ●锦囊牌,摸两张牌且你使用的牌无距离限制;\ ●装备牌,你使用【杀】指定目标角色后,其弃置两张牌。", ["@zhanyiequip_discard"] = "<font color=\"yellow\">战意</font> 请弃置两张牌。" , ["zhanyi_equip"] = "战意", ["#lifeng"] = "继父尽事", ["lifeng"] = "李丰", ["tunchu"] = "屯储", [":tunchu"] = "摸牌阶段摸牌时,你可以额外摸两张牌,然后将一张手牌置于你的武将牌上,称为“粮”。锁定技,若你的武将牌上有“粮”,你不能使用【杀】和决斗。", ["@tunchu-put"] = "请将一张手牌置于武将牌上", ["food"] = "粮", ["shuliang"] = "输粮", [":shuliang"] = "当一名角色的结束阶段开始时,若其没有手牌,你可以将一张“粮”置入弃牌堆,其摸两张牌。", ["@shuliang"] = "你可以发送“输粮”。" , ["~shuliang"] = "选择一张“粮”→点击“确定”", ["#liuzan"] = "啸天亢音", ["liuzan"] = "留赞", ["fenyin"] = "奋音", [":fenyin"] = "当你使用牌时,若此牌与你于本回合内使用的上一张牌的颜色不同,你可以摸一张牌。", ["ol_liubei"] = "OL刘备", ["&ol_liubei"] = "刘备" , ["olrende"] = "仁德" , [":olrende"] = "出牌阶段,你可以将任意张手牌交给一名其他角色,然后你于此阶段内不能再次以此法交给该角色牌。当你以此法交给其他角色的牌数在同一阶段内首次达到两张或更多时,你回复1点体力", ["ol_xiahoudun"] = "OL夏侯惇" , ["&ol_xiahoudun"] = "夏侯惇" , ["olqingjian"] = "清俭" , [":olqingjian"] = "当你于摸牌阶段外获得牌后,你可将其中任意张牌置于武将牌上,若如此做,此回合结束后,你将武将牌上的所有牌交给其他角色", ["@olqingjian"] = "你可以将至多 %arg 张手牌置于武将牌上" , ["@olqingjian-distribute"] = "请将清俭置于武将牌上的牌任意分配" , ["~olqingjian"] = "选择任意张置于武将牌上的牌-选择一名角色-点击“确定”" , ["ol_bulianshi"] = "OL步练师", ["&ol_bulianshi"] = "步练师", ["illustrator:ol_bulianshi"] = "勺子妞", ["olanxu"] = "安恤", [":olanxu"] = "出牌阶段限一次,你可以选择两名手牌数不同的其他角色,令其中手牌多的角色将一张手牌交给手牌少的角色,然后若这两名角色手牌数相等,你选择一项:1.摸一张牌;2.回复1点体力。", ["@olanxu"] = "%src 发动对您发动了“安恤”,请将一张手牌交给 %dest", ["olanxu:draw"] = "摸一张牌", ["olanxu:recover"] = "回复1点体力", ["ol_ii_caiwenji"] = "OL蔡文姬-第二版", ["&ol_ii_caiwenji"] = "蔡文姬", ["#ol_ii_caiwenji"] = "金壁之才", ["illustrator:ol_ii_caiwenji"] = "木美人", ["olchenqing"] = "陈情", [":olchenqing"] = "每轮限一次,当一名角色处于濒死状态时,你可以令另一名其他角色摸四张牌,然后弃置四张牌。若其以此法弃置的四张牌花色各不相同,则视为该角色对濒死的角色使用一张【桃】", ["@advise"] = "谏", ["@olchenqing"] = "%src 要挂了,您可以选择一名其他角色,对其发动“陈情”", ["@olchenqing-exchange"] = "%src 对您发动了“陈情”,请您弃置四张牌。若您弃置的牌花色各不相同,视为您对濒死角色 %dest 使用一张【桃】", ["ol_yuanshu"] = "OL袁术", ["&ol_yuanshu"] = "袁术", ["illustrator:ol_yuanshu"] = "吴昊", ["olyongsi"] = "庸肆", [":olyongsi"] = "锁定技,摸牌阶段开始时,你改为摸X张牌。锁定技,弃牌阶段开始时,你选择一项:1.弃置一张牌;2.失去1点体力。(X为场上势力数)", ["@olyongsi"] = "庸肆:请弃置1张牌(包括装备),否则你将失去1点体力", ["oljixi"] = "觊玺", [":oljixi"] = "觉醒技,你的回合结束时,若你连续三回合没有失去过体力,则你加1点体力上限并回复1点体力,然后选择一项:1.获得技能“妄尊”;2.摸两张牌并获得当前主公的主公技。", ["#oljixi-wake"] = "%from 连续三个回合没有失去过体力,触发“<font color=\"yellow\"><b>觊玺</b></font>”觉醒", ["oljixi:wangzun"] = "获得技能“妄尊”", ["oljixi:lordskill"] = "摸两张牌并获得主公技", ["oljixi_lordskill"] = "觊玺", ["ol_zhangjiao"] = "OL张角", ["&ol_zhangjiao"] = "张角", ["illustrator:ol_zhangjiao"] = "LiuHeng", ["olleiji"] = "雷击", [":olleiji"] = "当你使用或打出【闪】时,你可以令一名其他角色进行判定,若结果为:黑桃,你对该角色造成2点雷电伤害;梅花,你回复1点体力,然后对该角色造成1点雷电伤害。", ["@olleiji"] = "您可以发动“雷击”选择一名其他角色,令其进行判定", ["ol_caozhi"] = "OL曹植", ["&ol_caozhi"] = "曹植", ["designer:caozhi"] = "Foxear", ["illustrator:caozhi"] = "木美人", ["olluoying"] = "落英", [":olluoying"] = "其他角色的梅花牌因弃置或判定而置入弃牌堆后,你可以获得其中的任意张。", ["zhugeguo"] = "诸葛果", ["&zhugeguo"] = "诸葛果", ["#zhugeguo"] = "凤阁乘烟", ["illustrator:zhugeguo"] = "手机三国杀", ["olyuhua"] = "羽化", [":olyuhua"] = "锁定技。弃牌阶段内,你的非基本牌不计入手牌数,且你不能弃置你的非基本牌。", ["#olyuhua-effect"] = "受技能“<font color=\"yellow\"><b>羽化</b></font>”的影响,%from 的手牌数视为 %arg", ["olqirang"] = "祈禳", [":olqirang"] = "当有装备牌进入你的装备区时,你可以获得牌堆中的一张锦囊牌。", ["#olqirang-failed"] = "牌堆中没有锦囊牌,取消“<font color=\"yellow\"><b>祈禳</b></font>”的后续效果", }
gpl-3.0
notcake/glib
lua/glib/databases/mysqldatabase.lua
1
1820
-- MySQL1.8 local self = {} GLib.Databases.MySqlDatabase = GLib.MakeConstructor (self, GLib.Databases.IDatabase) local loaded = false function self:ctor () self.Database = nil if not loaded then require ("mysql") loaded = true end end function self:Connect (server, port, username, password, databaseName, callback) if callback then GLib.CallSelfAsSync () return end if self:IsConnected () then self:Disconnect () return self:Connect (server, port, username, password, databaseName) end local database, error = mysql.connect (server, username, password, databaseName, port) if database == 0 then return false, error end self.Database = database return true end function self:Disconnect (callback) if callback then GLib.CallSelfAsSync () return end if not self:IsConnected () then return true end local success, error = mysql.disconnect (self.Database) if not success then return false, error end self.Database = nil return true end function self:EscapeString (string) if not self:IsConnected () then return "" end local string, error = mysql.escape (self.Database, string) return string or "" end function self:GetDatabaseListQuery () return "SHOW DATABASES" end function self:GetTableListQuery (database) if database then return "SHOW TABLES IN " .. database else return "SHOW TABLES" end end function self:IsConnected () return self.Database ~= nil end function self:Query (query, callback) if callback then GLib.CallSelfAsSync () return end if not self:IsConnected () then return false, "Not connected to the database." end local result, success, error = mysql.query (self.Database, query) if not success then return false, error end return true, result end
gpl-3.0
AliKhodadad/Telebot
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
aqasaeed/fix
plugins/inrealm.lua
1
18414
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realmM(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Il gruppo '..string.gsub(group_name, '_', ' ')..' è stato creato.' end end local function set_description(msg, data, target, about) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Descrizione impostata:\n'..about end local function set_rules(msg, data, target) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Regole impostate:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Nome già bloccato' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Nome bloccato' end end local function unlock_group_name(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Nome già sbloccato' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Nome sbloccato' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Membri già bloccati' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Membri bloccati' end local function unlock_group_member(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Membri già sbloccati' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Membri sbloccati' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Foto già bloccata' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Inviami la nuova foto ora' end local function unlock_group_photo(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Foto già sbloccata' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Foto sbloccata' end end local function lock_group_flood(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Flood già bloccato' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Flood bloccato' end end local function unlock_group_flood(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Flood già sbloccato' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Flood sbloccato' end end local function lock_group_bots(msg, data, target) local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Protezione dai bot (API) già abilitata' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Protezione dai bot (API) abilitata' end end local function unlock_group_bots(msg, data, target) local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Protezione dai bot (API) già disabilitata' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Protezione dai bot (API) disabilitata' end end local function lock_group_arabic(msg, data, target) local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Caratteri arabi già bloccati' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Caratteri arabi bloccati' end end local function unlock_group_arabic(msg, data, target) local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Caratteri arabi già sbloccati' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Caratteri arabi sbloccati' end end -- show group settings local function show_group_settings(msg, data, target) local settings = data[tostring(target)]['settings'] local text = "Impostazioni gruppo:\n\nBlocco nome: "..settings.lock_name.."\nBlocco foto: "..settings.lock_photo.."\nBlocco membri: "..settings.lock_member.."\nBlocco flood: "..settings.flood.."\nBlocco bot: "..settings.lock_bots.."\nBlocco arabo: "..settings.lock_arabic return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end send_large_msg(receiver, text) local file = io.open("./groups/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Utenti in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end local file = io.open("./groups/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Accesso negato!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' è già un amministratore.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' è stato promosso ad amministratore.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Accesso negato!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' non è un amministratore.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' ora non è più amministratore.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'Lista degli amministratori nel Realm:\n\n-sudo user-' for k,v in pairs(data[tostring(admins)]) do message = message .. '- @' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function group_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'Nessun gruppo al momento' end local message = 'Lista dei gruppi:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("groups.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' è già amministratore.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' è stato promosso ad amministratore.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' non è amministratore.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' da ora non è più amministratore.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'Nessun @'..member..' in questo gruppo.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'aggadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'rimadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end function run(msg, matches) --vardump(msg) if matches[1] == 'creagruppo' and matches[2] then group_name = matches[2] return create_group(msg) end if matches[1] == 'log' then savelog(msg.to.id, "log creato") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'membrifile' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] ha richiesto la lista dei membri ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'membri' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] ha richiesto la lista dei membri come file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if not is_realmM(msg) then return end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'impostabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'impostaregole' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'blocca' then --group lock * local target = matches[2] if matches[3] == 'nome' then return lock_group_name(msg, data, target) end if matches[3] == 'membri' then return lock_group_member(msg, data, target) end if matches[3] == 'foto' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end if matches[3] == 'bot' then return lock_group_bots(msg, data, target) end if matches[3] == 'arabo' then return lock_group_arabic(msg, data, target) end end if matches[1] == 'sblocca' then --group unlock * local target = matches[2] if matches[3] == 'nome' then return unlock_group_name(msg, data, target) end if matches[3] == 'membri' then return unlock_group_member(msg, data, target) end if matches[3] == 'foto' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end if matches[3] == 'bot' then return unlock_group_bots(msg, data, target) end if matches[3] == 'arabo' then return unlock_group_arabic(msg, data, target) end end if matches[1] == 'info' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'nome' then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) end end end if matches[1] == 'chat_add_user' and not is_admin(msg) then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id chat_del_user(chat, user, ok_cb, true) end if matches[1] == 'aggadmin' and is_sudo(msg) then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("L'utente "..admin_id.." è stato promosso ad amministratore") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "aggadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'rimadmin' and is_sudo(msg) then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("L'utente "..admin_id.." ora non è più amministratore") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "rimadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'lista' and matches[2] == 'admin' then return admin_list(msg) end if matches[1] == 'lista' and matches[2] == 'gruppi' then group_list(msg) send_document("chat#id"..msg.to.id, "groups.txt", ok_cb, false) return "Lista dei gruppi creata" --group_list(msg) end end return { patterns = { "^/(creagruppo) (.*)$", "^/(impostabout) (%d+) (.*)$", "^/(impostaregole) (%d+) (.*)$", "^/(nome) (%d+) (.*)$", "^/(blocca) (%d+) (.*)$", "^/(sblocca) (%d+) (.*)$", "^/(info) (%d+)$", "^/(membri)$", "^/(membrifile)$", "^/(aggadmin) (.*)$", -- sudoers only "^/(rimadmin) (.*)$", -- sudoers only "^/(lista) (.*)$", "^/(log)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
anholt/ValyriaTear
dat/battles/characters_animations/kalya_throw_stone.lua
4
5809
-- Filename: thanis_attack.lua -- This file is scripting Bronann's attack animation, called by attack skills. -- The initialize() function is called once, followed by calls to the update function. -- When the update function returns true, the attack is finished. -- Set the namespace local ns = {}; setmetatable(ns, {__index = _G}); kalya_throw_stone = ns; setfenv(1, ns); -- local references local character = {}; local target = {}; local target_actor = {}; local skill = {}; local stone_pos_x = 0.0; local stone_pos_y = 0.0; local stone_height = 0.0; local total_distance = 0.0; local height_diff = 0.0; local height_min = 0.0; local a_coeff = 0.0; local distance_moved_x = 0.0; local distance_moved_y = 0.0; local enemy_pos_x = 0.0; local enemy_pos_y = 0.0; local attack_step = 0; local attack_time = 0.0; local damage_triggered = false; -- character, the BattleActor attacking (here Kalya) -- target, the BattleEnemy target -- The skill id used on target function Initialize(_character, _target, _skill) -- Keep the reference in memory character = _character; target = _target; target_actor = _target:GetActor(); skill = _skill; -- Don't attack if the character isn't alive if (character:IsAlive() == false) then return; end -- Set the arrow flying height members stone_height = (character:GetSpriteHeight() / 2.0) + 5.0; total_distance = math.abs(target_actor:GetXLocation() - character:GetXLocation()); height_diff = stone_height - (target_actor:GetSpriteHeight() / 2.0); height_min = math.min(stone_height, (target_actor:GetSpriteHeight() / 2.0)); -- Set the arrow starting position stone_pos_x = character:GetXLocation() + character:GetSpriteWidth() / 2.0; stone_pos_y = character:GetYLocation() - stone_height; character:SetAmmoPosition(stone_pos_x, stone_pos_y); -- Make the arrow reach the enemy center enemy_pos_x = target_actor:GetXLocation(); enemy_pos_y = target_actor:GetYLocation() - target_actor:GetSpriteHeight() / 2.0; attack_step = 0; attack_time = 0; damage_triggered = false; distance_moved_x = SystemManager:GetUpdateTime() / vt_map.MapMode.NORMAL_SPEED * 210.0; local y_diff = stone_pos_y - enemy_pos_y; if (y_diff == 0.0) then a_coeff = 0.0; distance_moved_y = 0.0; else a_coeff = (enemy_pos_x - stone_pos_x) / (stone_pos_y - enemy_pos_y); if (a_coeff < 0) then a_coeff = -a_coeff; end distance_moved_y = (1/a_coeff) * distance_moved_x; end --print("distance x: ", enemy_pos_x - character_pos_x - 64.0) --print("distance y: ", character_pos_y - enemy_pos_y) --print (distance_moved_x, 1/a_coeff, distance_moved_y); -- Override the ammo as a stone. character:GetAmmo():LoadAmmoAnimatedImage("img/sprites/battle/ammo/rock_ammo.lua"); end function Update() -- The update time can vary, so update the distance on each update as well. distance_moved_x = SystemManager:GetUpdateTime() / vt_map.MapMode.NORMAL_SPEED * 210.0; if (a_coeff ~= 0.0) then distance_moved_y = (1/a_coeff) * distance_moved_x; end -- Update the stone flying height according to the distance -- Get the % of of x distance left local distance_left = math.abs((stone_pos_x + distance_moved_x) - enemy_pos_x); if (total_distance > 0.0) then if (height_diff > 0.0) then stone_height = height_min + ((distance_left / total_distance) * height_diff); else stone_height = height_min + (((total_distance - distance_left) / total_distance) * -height_diff); end end -- Attack the enemy if (attack_step == 0) then character:ChangeSpriteAnimation("throw_stone") attack_step = 1 end -- Make the character go back to idle once attacked if (attack_step == 1) then attack_time = attack_time + SystemManager:GetUpdateTime(); if (attack_time > 700.0) then attack_step = 2; AudioManager:PlaySound("snd/throw.wav"); character:SetShowAmmo(true); end end -- Triggers the arrow animation if (attack_step == 2) then if (stone_pos_x > enemy_pos_x) then stone_pos_x = stone_pos_x - distance_moved_x; if stone_pos_x < enemy_pos_x then stone_pos_x = enemy_pos_x end end if (stone_pos_x < enemy_pos_x) then stone_pos_x = stone_pos_x + distance_moved_x; if stone_pos_x > enemy_pos_x then stone_pos_x = enemy_pos_x end end if (stone_pos_y > enemy_pos_y) then stone_pos_y = stone_pos_y - distance_moved_y; if stone_pos_y < enemy_pos_y then stone_pos_y = enemy_pos_y end end if (stone_pos_y < enemy_pos_y) then stone_pos_y = stone_pos_y + distance_moved_y; if stone_pos_y > enemy_pos_y then stone_pos_y = enemy_pos_y end end character:SetAmmoPosition(stone_pos_x, stone_pos_y + stone_height); character:GetAmmo():SetFlyingHeight(stone_height); if (stone_pos_x >= enemy_pos_x and stone_pos_y == enemy_pos_y) then character:ChangeSpriteAnimation("idle"); attack_step = 3; end end if (attack_step == 3) then -- Triggers the damage once the arrow has reached the enemy if (damage_triggered == false) then skill:ExecuteBattleFunction(character, target); -- Remove the skill points at the end of the third attack character:SubtractSkillPoints(skill:GetSPRequired()); damage_triggered = true; character:SetShowAmmo(false); end attack_step = 4 end if (attack_step == 4) then return true; end return false; end
gpl-2.0
anholt/ValyriaTear
dat/actors/map_objects.lua
1
15305
objects = {} objects["Barrel1"] = { animation_filename = "img/sprites/map/objects/barrel1.lua", coll_half_width = 0.78, coll_height = 1.6, img_half_width = 0.78, img_height = 2.125 } objects["Bed1"] = { animation_filename = "img/sprites/map/objects/bed1.lua", coll_half_width = 1.75, coll_height = 5.50, img_half_width = 1.75, img_height = 5.68 } objects["Bed2"] = { animation_filename = "img/sprites/map/objects/bed2.lua", coll_half_width = 3.31, coll_height = 5.50, img_half_width = 3.31, img_height = 5.68 } objects["Bench1"] = { animation_filename = "img/sprites/map/objects/bench1.lua", coll_half_width = 3.0, coll_height = 1.6, img_half_width = 3.0, img_height = 2.0 } objects["Bench2"] = { animation_filename = "img/sprites/map/objects/bench2.lua", coll_half_width = 1.0, coll_height = 1.6, img_half_width = 1.0, img_height = 2.0 } objects["Box1"] = { animation_filename = "img/sprites/map/objects/box1.lua", coll_half_width = 1.0, coll_height = 2.27, img_half_width = 1.0, img_height = 2.37 } objects["Book1"] = { animation_filename = "img/sprites/map/objects/book1.lua", coll_half_width = 1.0, coll_height = 1.8, img_half_width = 1.0, img_height = 2.0 } objects["Bread1"] = { animation_filename = "img/sprites/map/objects/bread1.lua", coll_half_width = 1.0, coll_height = 1.8, img_half_width = 1.0, img_height = 2.0 } objects["Bush1"] = { animation_filename = "img/sprites/map/objects/bush1.lua", coll_half_width = 1.9, coll_height = 3.8, img_half_width = 2.0, img_height = 4.0 } objects["Bush2"] = { animation_filename = "img/sprites/map/objects/bush2.lua", coll_half_width = 1.9, coll_height = 3.8, img_half_width = 2.0, img_height = 4.0 } objects["Bush3"] = { animation_filename = "img/sprites/map/objects/bush3.lua", coll_half_width = 1.9, coll_height = 3.8, img_half_width = 2.0, img_height = 4.0 } objects["Bush4"] = { animation_filename = "img/sprites/map/objects/bush4.lua", coll_half_width = 1.9, coll_height = 3.8, img_half_width = 2.0, img_height = 4.0 } objects["Campfire1"] = { animation_filename = "img/sprites/map/objects/campfire.lua", coll_half_width = 1.0, coll_height = 1.6, img_half_width = 2.0, img_height = 4.0 } objects["Candle1"] = { animation_filename = "img/sprites/map/objects/candle1.lua", coll_half_width = 1.0, coll_height = 1.8, img_half_width = 1.0, img_height = 2.0 } objects["Cat1"] = { animation_filename = "img/sprites/map/objects/cat1.lua", coll_half_width = 0.95, coll_height = 0.9, img_half_width = 0.68, img_height = 1.56 } objects["Chair1"] = { animation_filename = "img/sprites/map/objects/chair1.lua", coll_half_width = 0.95, coll_height = 0.9, img_half_width = 0.95, img_height = 2.9 } objects["Chair1_inverted"] = { animation_filename = "img/sprites/map/objects/chair1_inverted.lua", coll_half_width = 0.95, coll_height = 0.9, img_half_width = 0.95, img_height = 2.9 } objects["Chair1_north"] = { animation_filename = "img/sprites/map/objects/chair1_north.lua", coll_half_width = 0.75, coll_height = 0.9, img_half_width = 0.75, img_height = 2.81 } objects["Chair2"] = { animation_filename = "img/sprites/map/objects/chair2.lua", coll_half_width = 0.95, coll_height = 0.9, img_half_width = 0.95, img_height = 2.9 } objects["Clock1"] = { animation_filename = "img/sprites/map/objects/clock1.lua", coll_half_width = 1.0, coll_height = 1.9, img_half_width = 1.0, img_height = 2.0 } objects["Dog1"] = { animation_filename = "img/sprites/map/objects/dog1.lua", coll_half_width = 1.18, coll_height = 1.6, img_half_width = 1.18, img_height = 2.6 } objects["Fence1 horizontal"] = { animation_filename = "img/sprites/map/objects/fence1-horizontal.lua", coll_half_width = 1.0, coll_height = 1.2, img_half_width = 1.0, img_height = 2.0 } objects["Fence1 vertical"] = { animation_filename = "img/sprites/map/objects/fence1-vertical.lua", coll_half_width = 0.6, coll_height = 2.0, img_half_width = 1.0, img_height = 2.0 } objects["Fence1 l top left"] = { animation_filename = "img/sprites/map/objects/fence1-l-top-left.lua", coll_half_width = 0.6, coll_height = 1.2, img_half_width = 1.0, img_height = 2.0 } objects["Fence1 l top right"] = { animation_filename = "img/sprites/map/objects/fence1-l-top-right.lua", coll_half_width = 0.6, coll_height = 1.2, img_half_width = 1.0, img_height = 2.0 } objects["Fence1 l bottom left"] = { animation_filename = "img/sprites/map/objects/fence1-l-bottom-left.lua", coll_half_width = 0.6, coll_height = 1.2, img_half_width = 1.0, img_height = 2.0 } objects["Fence1 l bottom right"] = { animation_filename = "img/sprites/map/objects/fence1-l-bottom-right.lua", coll_half_width = 0.6, coll_height = 1.2, img_half_width = 1.0, img_height = 2.0 } objects["Flower Pot1"] = { animation_filename = "img/sprites/map/objects/flower_pot1.lua", coll_half_width = 0.59, coll_height = 1.2, img_half_width = 0.59, img_height = 1.68 } objects["Flower Pot2"] = { animation_filename = "img/sprites/map/objects/flower_pot2.lua", coll_half_width = 0.53, coll_height = 1.2, img_half_width = 0.53, img_height = 1.75 } objects["Grass Clump1"] = { animation_filename = "img/sprites/map/objects/grass_clump1.lua", coll_half_width = 2.2, coll_height = 1.2, img_half_width = 2.5, img_height = 3.5 } objects["Green Pepper1"] = { animation_filename = "img/sprites/map/objects/green_pepper1.lua", coll_half_width = 1.0, coll_height = 1.8, img_half_width = 1.0, img_height = 2.0 } objects["Knife1"] = { animation_filename = "img/sprites/map/objects/knife1.lua", coll_half_width = 1.0, coll_height = 1.8, img_half_width = 1.0, img_height = 2.0 } objects["Layna Statue"] = { animation_filename = "img/sprites/map/objects/layna_statue.lua", coll_half_width = 0.93, coll_height = 2.0, img_half_width = 0.93, img_height = 5.31 } objects["Locker"] = { animation_filename = "img/sprites/map/objects/locker.lua", coll_half_width = 0.75, coll_height = 1.1, img_half_width = 0.75, img_height = 1.43 } objects["Paper and Feather"] = { animation_filename = "img/sprites/map/objects/paper_feather.lua", coll_half_width = 0.93, coll_height = 1.75, img_half_width = 0.93, img_height = 1.75 } objects["Parchment"] = { animation_filename = "img/sprites/map/objects/parchment.lua", coll_half_width = 0.59, coll_height = 1.31, img_half_width = 0.59, img_height = 1.31 } objects["Plate Pile1"] = { animation_filename = "img/sprites/map/objects/plate_pile1.lua", coll_half_width = 1.0, coll_height = 1.8, img_half_width = 1.0, img_height = 2.0 } objects["Rock1"] = { animation_filename = "img/sprites/map/objects/rock1.lua", coll_half_width = 1.0, coll_height = 1.63, img_half_width = 1.0, img_height = 1.93 } objects["Rock2"] = { animation_filename = "img/sprites/map/objects/rock2.lua", coll_half_width = 0.9, coll_height = 1.78, img_half_width = 0.9, img_height = 3.56 } objects["Rock3"] = { animation_filename = "img/sprites/map/objects/rock3.lua", coll_half_width = 4.0, coll_height = 6.0, img_half_width = 4.0, img_height = 6.0 } objects["Rolling Stone"] = { animation_filename = "img/sprites/map/objects/rolling_stone.lua", coll_half_width = 0.9, coll_height = 1.8, img_half_width = 1.0, img_height = 2.0 } objects["Sauce Pot1"] = { animation_filename = "img/sprites/map/objects/sauce_pot1.lua", coll_half_width = 1.0, coll_height = 1.8, img_half_width = 1.0, img_height = 2.0 } objects["Shroom"] = { animation_filename = "img/sprites/map/enemies/spiky_mushroom_idle_object.lua", coll_half_width = 0.9, coll_height = 1.9, img_half_width = 1.25, img_height = 2.6 } objects["Stone Sign1"] = { animation_filename = "img/sprites/map/objects/stone_sign1.lua", coll_half_width = 1.03, coll_height = 2.18, img_half_width = 1.03, img_height = 2.18 } objects["Table1"] = { animation_filename = "img/sprites/map/objects/table1.lua", coll_half_width = 2.95, coll_height = 3.9, img_half_width = 2.95, img_height = 5.0 } objects["Table2"] = { animation_filename = "img/sprites/map/objects/table2.lua", coll_half_width = 2.95, coll_height = 3.9, img_half_width = 2.95, img_height = 5.0 } objects["Big Wooden Table"] = { animation_filename = "img/sprites/map/objects/wooden_table_big.lua", coll_half_width = 3.0, coll_height = 4.77, img_half_width = 3.0, img_height = 4.87 } objects["Small Wooden Table"] = { animation_filename = "img/sprites/map/objects/wooden_table_small.lua", coll_half_width = 2.0, coll_height = 2.7, img_half_width = 2.0, img_height = 4.0 } objects["Salad1"] = { animation_filename = "img/sprites/map/objects/salad1.lua", coll_half_width = 1.0, coll_height = 1.8, img_half_width = 1.0, img_height = 2.0 } objects["Tree Big1"] = { animation_filename = "img/sprites/map/objects/tree_big1.lua", coll_half_width = 3.0, coll_height = 4.0, img_half_width = 3.0, img_height = 8.0 } objects["Tree Big2"] = { animation_filename = "img/sprites/map/objects/tree_big2.lua", coll_half_width = 2.0, coll_height = 3.4, img_half_width = 2.0, img_height = 6.8 } objects["Tree Little1"] = { animation_filename = "img/sprites/map/objects/tree_little1.lua", coll_half_width = 1.5, coll_height = 2.8, img_half_width = 2.0, img_height = 6.0 } objects["Tree Little2"] = { animation_filename = "img/sprites/map/objects/tree_little2.lua", coll_half_width = 1.5, coll_height = 2.8, img_half_width = 2.0, img_height = 6.0 } objects["Tree Little3"] = { animation_filename = "img/sprites/map/objects/tree_little3.lua", coll_half_width = 1.5, coll_height = 2.8, img_half_width = 2.0, img_height = 6.0 } objects["Tree Little4"] = { animation_filename = "img/sprites/map/objects/tree_little4.lua", coll_half_width = 1.5, coll_height = 2.8, img_half_width = 2.0, img_height = 6.0 } objects["Tree Small1"] = { animation_filename = "img/sprites/map/objects/tree_small1.lua", coll_half_width = 1.75, coll_height = 2.43, img_half_width = 1.75, img_height = 4.87 } objects["Tree Small2"] = { animation_filename = "img/sprites/map/objects/tree_small2.lua", coll_half_width = 3.0, coll_height = 3.0, img_half_width = 3.0, img_height = 6.0 } objects["Tree Small3"] = { animation_filename = "img/sprites/map/objects/tree_small3.lua", coll_half_width = 2.0, coll_height = 2.5, img_half_width = 3.5, img_height = 8.0 } objects["Tree Small3 Tilting"] = { animation_filename = "img/sprites/map/objects/tree_small3_tilting.lua", coll_half_width = 2.0, coll_height = 2.5, img_half_width = 3.46, img_height = 8.25 } objects["Tree Small4"] = { animation_filename = "img/sprites/map/objects/tree_small4.lua", coll_half_width = 2.0, coll_height = 2.5, img_half_width = 3.5, img_height = 8.0 } objects["Tree Small5"] = { animation_filename = "img/sprites/map/objects/tree_small5.lua", coll_half_width = 2.0, coll_height = 2.5, img_half_width = 3.5, img_height = 8.0 } objects["Tree Small5 Fallen"] = { animation_filename = "img/sprites/map/objects/tree_small5_fallen.lua", coll_half_width = 4.0, coll_height = 3.5, img_half_width = 4.03, img_height = 7.0 } objects["Tree Small6"] = { animation_filename = "img/sprites/map/objects/tree_small6.lua", coll_half_width = 2.0, coll_height = 2.5, img_half_width = 3.5, img_height = 8.0 } objects["Tree Tiny1"] = { animation_filename = "img/sprites/map/objects/tree_tiny1.lua", coll_half_width = 1.6, coll_height = 1.7, img_half_width = 2.0, img_height = 4.0 } objects["Tree Tiny2"] = { animation_filename = "img/sprites/map/objects/tree_tiny2.lua", coll_half_width = 1.6, coll_height = 1.7, img_half_width = 2.0, img_height = 4.0 } objects["Tree Tiny3"] = { animation_filename = "img/sprites/map/objects/tree_tiny3.lua", coll_half_width = 1.6, coll_height = 1.7, img_half_width = 2.0, img_height = 4.0 } objects["Tree Tiny4"] = { animation_filename = "img/sprites/map/objects/tree_tiny4.lua", coll_half_width = 1.6, coll_height = 1.7, img_half_width = 2.0, img_height = 4.0 } objects["Vase1"] = { animation_filename = "img/sprites/map/objects/vase1.lua", coll_half_width = 0.75, coll_height = 1.2, img_half_width = 0.75, img_height = 1.5 } objects["Well"] = { animation_filename = "img/sprites/map/objects/well.lua", coll_half_width = 2.10, coll_height = 3.20, img_half_width = 2.43, img_height = 4.56 } objects["Wooden Sword1"] = { animation_filename = "img/sprites/map/objects/wooden_sword1.lua", coll_half_width = 0.65, coll_height = 2.5, img_half_width = 0.65, img_height = 2.5 } -- "Ground" lights -- Those are special light effect that have to be applied before the sky layer objects["Left Window Light"] = { animation_filename = "img/misc/lights/left_window_light.lua", coll_half_width = 0.0, coll_height = 0.0, img_half_width = 1.56, img_height = 4.5 } objects["Right Window Light"] = { animation_filename = "img/misc/lights/right_window_light.lua", coll_half_width = 0.0, coll_height = 0.0, img_half_width = 1.56, img_height = 4.5 } objects["Left Window Light 2"] = { animation_filename = "img/misc/lights/left_window_light.lua", coll_half_width = 0.0, coll_height = 0.0, img_half_width = 2.56, img_height = 6.5 } objects["Right Window Light 2"] = { animation_filename = "img/misc/lights/right_window_light.lua", coll_half_width = 0.0, coll_height = 0.0, img_half_width = 2.56, img_height = 6.5 } -- The helper function permitting to easily create a prepared map object function CreateObject(Map, name, x, y) if (objects[name] == nil) then print("Error: No object named: "..name.." found!!"); return nil; end if (Map == nil) then print("Error: Function called with invalid Map object"); return nil; end local object = {} object = vt_map.PhysicalObject(); object:SetObjectID(Map.object_supervisor:GenerateObjectID()); object:SetPosition(x, y); object:SetCollHalfWidth(objects[name].coll_half_width); object:SetCollHeight(objects[name].coll_height); object:SetImgHalfWidth(objects[name].img_half_width); object:SetImgHeight(objects[name].img_height); object:AddAnimation(objects[name].animation_filename); return object; end
gpl-2.0
notcake/glib
lua/glib/lua/decompiler/tableconstant.lua
1
2973
local self = {} GLib.Lua.TableConstant = GLib.MakeConstructor (self, GLib.Lua.GarbageCollectedConstant) function self:ctor (str) self.Type = GLib.Lua.GarbageCollectedConstantType.Table self.ArrayCount = 0 self.HashCount = 0 self.ArrayElements = {} self.HashKeys = {} self.HashValues = {} self.Value = {} end function self:Deserialize (type, inBuffer) self.ArrayCount = inBuffer:ULEB128 () self.HashCount = inBuffer:ULEB128 () self.Value = {} for i = 0, self.ArrayCount - 1 do self.ArrayElements [i] = self:DeserializeElement (inBuffer) self.Value [i] = self.ArrayElements [i] end for i = 1, self.HashCount do self.HashKeys [i] = self:DeserializeElement (inBuffer) self.HashValues [i] = self:DeserializeElement (inBuffer) self.Value [self.HashKeys [i]] = self.HashValues [i] end end function self:DeserializeElement (inBuffer) local elementType = inBuffer:ULEB128 () if elementType == GLib.Lua.TableKeyValueType.Nil then return nil elseif elementType == GLib.Lua.TableKeyValueType.False then return false elseif elementType == GLib.Lua.TableKeyValueType.True then return true elseif elementType == GLib.Lua.TableKeyValueType.Integer then return inBuffer:ULEB128 () elseif elementType == GLib.Lua.TableKeyValueType.Double then local low32 = inBuffer:ULEB128 () local high32 = inBuffer:ULEB128 () return GLib.BitConverter.UInt32sToDouble (low32, high32) elseif elementType >= GLib.Lua.TableKeyValueType.String then local length = elementType - GLib.Lua.TableKeyValueType.String return inBuffer:Bytes (length) end return nil end function self:GetLuaString () if self.ArrayCount == 0 and self.HashCount == 0 then return "{}" end local luaString = GLib.StringBuilder () luaString:Append ("{") local first = true for i = 0, self.ArrayCount - 1 do if not first then luaString:Append (",") end local element = self.ArrayElements [i] if i == 0 then if element ~= nil then first = false luaString:Append ("\n\t") element = GLib.Lua.ToLuaString (element) luaString:Append ("[0] = ") luaString:Append (element) end else first = false luaString:Append ("\n\t") element = GLib.Lua.ToLuaString (element) luaString:Append (element) end end for i = 1, self.HashCount do if not first then luaString:Append (",") end first = false luaString:Append ("\n\t") local key = self.HashKeys [i] if type (key) ~= "string" or not GLib.Lua.IsValidVariableName (key) then key = GLib.Lua.ToLuaString (key) end luaString:Append (key) luaString:Append (" = ") local value = self.HashValues [i] value = GLib.Lua.ToLuaString (value) luaString:Append (value) end luaString:Append ("\n}") return luaString:ToString () end function self:ToString () return "{ Table: " .. self:GetLuaString () .. " }" end
gpl-3.0
stas2z/openwrt-witi
package/luci/modules/luci-mod-admin-mini/luasrc/model/cbi/mini/wifi.lua
48
11450
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. -- Data init -- local fs = require "nixio.fs" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() if not uci:get("network", "wan") then uci:section("network", "interface", "wan", {proto="none", ifname=" "}) uci:save("network") uci:commit("network") end local wlcursor = luci.model.uci.cursor_state() local wireless = wlcursor:get_all("wireless") local wifidevs = {} local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" then table.insert(ifaces, v) end end wlcursor:foreach("wireless", "wifi-device", function(section) table.insert(wifidevs, section[".name"]) end) -- Main Map -- m = Map("wireless", translate("Wifi"), translate("Here you can configure installed wifi devices.")) m:chain("network") -- Status Table -- s = m:section(Table, ifaces, translate("Networks")) link = s:option(DummyValue, "_link", translate("Link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d/%d" %{ iwinfo.quality, iwinfo.quality_max } or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and iwinfo.bssid or "-" end channel = s:option(DummyValue, "channel", translate("Channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("Protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("Mode")) encryption = s:option(DummyValue, "encryption", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) power = s:option(DummyValue, "_power", translate("Power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d dBm" % iwinfo.txpower or "-" end scan = s:option(Button, "_scan", translate("Scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end -- WLAN-Scan-Table -- t2 = m:section(Table, {}, translate("<abbr title=\"Wireless Local Area Network\">WLAN</abbr>-Scan"), translate("Wifi networks in your local environment")) function scan.write(self, section) m.autoapply = false t2.render = t2._render local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) if iwinfo then local _, cell for _, cell in ipairs(iwinfo.scanlist) do t2.data[#t2.data+1] = { Quality = "%d/%d" %{ cell.quality, cell.quality_max }, ESSID = cell.ssid, Address = cell.bssid, Mode = cell.mode, ["Encryption key"] = cell.encryption.enabled and "On" or "Off", ["Signal level"] = "%d dBm" % cell.signal, ["Noise level"] = "%d dBm" % iwinfo.noise } end end end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("Link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return self.map:get(section, "ESSID") end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("Mode")) chan = t2:option(DummyValue, "channel", translate("Channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) t2:option(DummyValue, "Signal level", translate("Signal")) t2:option(DummyValue, "Noise level", translate("Noise")) if #wifidevs < 1 then return m end -- Config Section -- s = m:section(NamedSection, wifidevs[1], "wifi-device", translate("Devices")) s.addremove = false en = s:option(Flag, "disabled", translate("enable")) en.rmempty = false en.enabled = "0" en.disabled = "1" function en.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end local hwtype = m:get(wifidevs[1], "type") if hwtype == "atheros" then mode = s:option(ListValue, "hwmode", translate("Mode")) mode.override_values = true mode:value("", "auto") mode:value("11b", "802.11b") mode:value("11g", "802.11g") mode:value("11a", "802.11a") mode:value("11bg", "802.11b+g") mode.rmempty = true end ch = s:option(Value, "channel", translate("Channel")) for i=1, 14 do ch:value(i, i .. " (2.4 GHz)") end s = m:section(TypedSection, "wifi-iface", translate("Local Network")) s.anonymous = true s.addremove = false s:option(Value, "ssid", translate("Network Name (<abbr title=\"Extended Service Set Identifier\">ESSID</abbr>)")) bssid = s:option(Value, "bssid", translate("<abbr title=\"Basic Service Set Identifier\">BSSID</abbr>")) local devs = {} luci.model.uci.cursor():foreach("wireless", "wifi-device", function (section) table.insert(devs, section[".name"]) end) if #devs > 1 then device = s:option(DummyValue, "device", translate("Device")) else s.defaults.device = devs[1] end mode = s:option(ListValue, "mode", translate("Mode")) mode.override_values = true mode:value("ap", translate("Provide (Access Point)")) mode:value("adhoc", translate("Independent (Ad-Hoc)")) mode:value("sta", translate("Join (Client)")) function mode.write(self, section, value) if value == "sta" then local oldif = m.uci:get("network", "wan", "ifname") if oldif and oldif ~= " " then m.uci:set("network", "wan", "_ifname", oldif) end m.uci:set("network", "wan", "ifname", " ") self.map:set(section, "network", "wan") else if m.uci:get("network", "wan", "_ifname") then m.uci:set("network", "wan", "ifname", m.uci:get("network", "wan", "_ifname")) end self.map:set(section, "network", "lan") end return ListValue.write(self, section, value) end encr = s:option(ListValue, "encryption", translate("Encryption")) encr.override_values = true encr:value("none", "No Encryption") encr:value("wep", "WEP") if hwtype == "atheros" or hwtype == "mac80211" then local supplicant = fs.access("/usr/sbin/wpa_supplicant") local hostapd = fs.access("/usr/sbin/hostapd") if hostapd and supplicant then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode") encr:value("wpa", "WPA-Radius", {mode="ap"}, {mode="sta"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}, {mode="sta"}) elseif hostapd and not supplicant then encr:value("psk", "WPA-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk2", "WPA2-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="ap"}, {mode="adhoc"}) encr:value("wpa", "WPA-Radius", {mode="ap"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) elseif not hostapd and supplicant then encr:value("psk", "WPA-PSK", {mode="sta"}) encr:value("psk2", "WPA2-PSK", {mode="sta"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="sta"}) encr:value("wpa", "WPA-EAP", {mode="sta"}) encr:value("wpa2", "WPA2-EAP", {mode="sta"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) else encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) end elseif hwtype == "broadcom" then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk+psk2", "WPA-PSK/WPA2-PSK Mixed Mode") end key = s:option(Value, "key", translate("Key")) key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "psk2") key:depends("encryption", "psk+psk2") key:depends("encryption", "psk-mixed") key:depends({mode="ap", encryption="wpa"}) key:depends({mode="ap", encryption="wpa2"}) key.rmempty = true key.password = true server = s:option(Value, "server", translate("Radius-Server")) server:depends({mode="ap", encryption="wpa"}) server:depends({mode="ap", encryption="wpa2"}) server.rmempty = true port = s:option(Value, "port", translate("Radius-Port")) port:depends({mode="ap", encryption="wpa"}) port:depends({mode="ap", encryption="wpa2"}) port.rmempty = true if hwtype == "atheros" or hwtype == "mac80211" then nasid = s:option(Value, "nasid", translate("NAS ID")) nasid:depends({mode="ap", encryption="wpa"}) nasid:depends({mode="ap", encryption="wpa2"}) nasid.rmempty = true eaptype = s:option(ListValue, "eap_type", translate("EAP-Method")) eaptype:value("TLS") eaptype:value("TTLS") eaptype:value("PEAP") eaptype:depends({mode="sta", encryption="wpa"}) eaptype:depends({mode="sta", encryption="wpa2"}) cacert = s:option(FileUpload, "ca_cert", translate("Path to CA-Certificate")) cacert:depends({mode="sta", encryption="wpa"}) cacert:depends({mode="sta", encryption="wpa2"}) privkey = s:option(FileUpload, "priv_key", translate("Path to Private Key")) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa"}) privkeypwd = s:option(Value, "priv_key_pwd", translate("Password of Private Key")) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa"}) auth = s:option(Value, "auth", translate("Authentication")) auth:value("PAP") auth:value("CHAP") auth:value("MSCHAP") auth:value("MSCHAPV2") auth:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) auth:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) identity = s:option(Value, "identity", translate("Identity")) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) password = s:option(Value, "password", translate("Password")) password:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) password:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) end if hwtype == "atheros" or hwtype == "broadcom" then iso = s:option(Flag, "isolate", translate("AP-Isolation"), translate("Prevents Client to Client communication")) iso.rmempty = true iso:depends("mode", "ap") hide = s:option(Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>")) hide.rmempty = true hide:depends("mode", "ap") end if hwtype == "mac80211" or hwtype == "atheros" then bssid:depends({mode="adhoc"}) end if hwtype == "broadcom" then bssid:depends({mode="wds"}) bssid:depends({mode="adhoc"}) end return m
gpl-2.0
rlcevg/Zero-K
LuaUI/Configs/nubtron_config.lua
12
8942
--[[ INSTRUCTIONS Choose names for the unitClass table and use those names in conditions. For example if you use "Con" then you must use "ConSelected" not "conSelected": local unitClasses = { Con = { 'armrectr' }, } local steps = { selectCon = { image = unitClasses.Con[1] ..'.png', passIfAny = { 'ConSelected' }, }, } Use the mClasses table to indicate mobile units, as opposed to structures. local mClasses = { Con=1, } ** Tasks and Steps ** Tasks and steps can either pass (move to next task/step) or fail (go to previous task/step). A task contains a set of steps. Define the steps in a task using the "states" table (sorry, steps = states). A task will pass when its own conditions pass and it's on its final step (state). You can set conditions for a tasks/steps using the following tables. ** Condition tables ** errIfAny - task/step fails if any conditions are true errIfAnyNot - task/step fails if any conditions are false passIfAny - task/step completes if any conditions are true passIfAnyNot - task/step completes if any conditions are false ** Generic conditions ** have<unitClass> - unit exists and is completed <unitClass>Selected - unit is selected ** Special Built-in conditions ** clickedNubtron - user clicks Next button commSelected - user selects commander (based on customparam in ZK) gameStarted guardFac - constructor (Con) guards factory (BotLab) lowMetalIncome lowEnergryIncome metalMapView ** Generic Steps (autogenerated for you) ** selectBuild<unitClass> - Tells user to select a structure from the build menu start<unitClass> - Triggers if user selected the structure to be built. Tells user to place the structure build<unitClass> - Unit (mobile or structure) is being built finish<unitClass> - Triggers if structure partly completed structure is no longer being built, tells user that structure needs finishing ]] --- unit classes --- local unitClasses = { Mex = { 'cormex' }, Solar = { 'armsolar' }, LLT = { 'corllt' }, BotLab = { 'factorycloak' }, Radar = { 'corrad' }, Con = { 'armrectr' }, Raider = { 'armpw' }, } local unitClassNames = { Mex = 'Mex', Solar = 'Solar Collector', LLT = 'LLT', BotLab = 'Bot Lab', Radar = 'Radar', Con = 'Constructor', Raider = 'Raider', } --mobile units local mClasses = { Con=1, Raider=1, } -- generic sub states local steps = { intro = { --message = 'Hello! I am Nubtron, the friendly robot. I will teach you how to play Complete Annihilation. <(Click here to continue)>', passIfAny = { 'clickedNubtron', }, }, intro2 = { --message = 'Just follow my instructions. You can drag this window around by my face. <(Click here to continue)>', passIfAny = { 'clickedNubtron'}, }, intro3 = { --message = 'Practice zooming the camera in and out with your mouse\'s scroll wheel <(Click here to continue)>', passIfAny = { 'clickedNubtron' }, }, intro4 = { --message = 'Practice panning the camera up, down, left and right with your arrow keys. <(Click here to continue)>', passIfAny = { 'clickedNubtron' }, }, intro5 = { --message = 'Place your starting position by clicking on a nice flat spot on the map, then click on the <Ready> button', passIfAny = { 'gameStarted' }, }, selectComm = { --message = 'Select only your commander by clicking on it or pressing <ctrl+c>.', passIfAny = {'commSelected'} }, showMetalMap = { --message = 'View the metal map by pressing <F4>.', passIfAny = { 'metalMapView' } }, hideMetalMap = { --message = 'Hide the metal map by pressing <F4>.', passIfAnyNot = { 'metalMapView' } }, selectBotLab = { --message = 'Select only your Bot Lab by clicking on it (the blue circles will help you find it).', passIfAny = { 'BotLabSelected' } }, selectCon = { --message = 'Select one constructor by clicking on it (the blue circles will help you find it).', --image = { arm='unitpics/'.. unitClasses.Con[1] ..'.png', core='unitpics/'.. unitClasses.Con[2] ..'.png' }, image = unitClasses.Con[1] ..'.png', passIfAny = { 'ConSelected' }, }, guardFac = { --message = 'Have the constructor guard your Bot Lab by right clicking on the Lab. The constructor will assist it until you give it a different order.', errIfAnyNot = { 'ConSelected' }, }, --[[ rotate = { --message = 'Try rotating.', errIfAnyNot = { 'commSelected', 'BotLabBuildSelected' }, passIfAny = { 'clickedNubtron' } }, --]] tutorialEnd = { --message = 'This is the end of the tutorial. It is now safe to shut off Nubtron. Goodbye! (Click here to restart tutorial)', passIfAny = {'clickedNubtron'} }, } -- main states -- use any names you wish here, so long as they match up to the tasks table local taskOrder = { 'intro', 'restoreInterface', 'buildMex', 'buildSolar', 'buildLLT', 'buildMex2', 'buildSolar2', 'buildFac', 'buildRadar', 'buildCon', 'conAssist', 'buildRaider', 'congrats', } --use "states" from the steps table above. local tasks = { intro = { --desc = 'Introduction', states = {'intro', 'intro2', 'intro3', 'intro4', 'intro5', }, }, restoreInterface = { --desc = 'Restore your interface', states = { 'hideMetalMap', }, }, buildMex = { --desc = 'Building a Metal Extractor (mex)', --tip = 'Metal extractors output metal which is the heart of your economy.', states = { 'selectComm', 'showMetalMap', 'finishMex', 'selectBuildMex', 'startMex', 'buildMex', 'hideMetalMap' }, passIfAll = { 'haveMex',}, }, buildSolar = { --desc = 'Building a Solar Collector', --tip = 'Energy generating structures power your mexes and factories.', states = { 'selectComm', 'finishSolar', 'selectBuildSolar', 'startSolar', 'buildSolar'}, errIfAny = { 'metalMapView' }, errIfAnyNot = { 'haveMex' }, passIfAll = { 'haveSolar',}, }, buildLLT = { --desc = 'Building a Light Laser Tower (LLT)', states = { 'selectComm', 'finishLLT', 'selectBuildLLT', 'startLLT', 'buildLLT' }, errIfAny = { 'metalMapView' }, errIfAnyNot = { 'haveMex', 'haveSolar' }, passIfAll = { 'haveLLT',}, }, buildMex2 = { --desc = 'Building another mex on a different metal spot.', ---tip = 'Always try to acquire more metal spots to build more mexes.', states = { 'selectComm', 'showMetalMap', 'finishMex', 'selectBuildMex', 'startMex', 'buildMex', 'hideMetalMap'}, errIfAnyNot = { 'haveMex', 'haveSolar' }, passIfAnyNot = { 'lowMetalIncome', }, }, buildSolar2 = { --desc = 'Building another Solar Collector', --tip = 'Always try and build more energy structures to keep your economy growing.', states = { 'selectComm', 'finishSolar', 'selectBuildSolar', 'startSolar', 'buildSolar', }, errIfAny = { 'metalMapView', }, errIfAnyNot = { 'haveMex', 'haveSolar' }, passIfAnyNot = { 'lowEnergyIncome', } }, buildFac = { --desc = 'Building a Factory', states = { 'selectComm', 'finishBotLab', 'selectBuildBotLab', 'startBotLab', 'buildBotLab' }, errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', }, errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT' }, passIfAll = { 'haveBotLab',}, }, buildRadar = { --desc = 'Building a Radar', --tip = 'Radar coverage shows you distant enemy units as blips.', states = { 'selectComm', 'finishRadar', 'selectBuildRadar', 'startRadar', 'buildRadar' }, errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', }, errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT', 'haveBotLab' }, passIfAll = { 'haveRadar',}, }, buildCon = { --desc = 'Building a Constructor', --tip = 'Just like your Commander, Constructors build (and assist building of) structures.', states = { 'selectBotLab', 'selectBuildCon', 'buildCon' }, errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', }, errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT', 'haveBotLab', 'haveRadar' }, passIfAll = { 'haveCon',}, }, conAssist = { --desc = 'Using a constructor to assist your factory', --tip = 'Factories that are assisted by constructors build faster.', states = { 'selectCon', 'guardFac', }, errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', }, errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT', 'haveBotLab', 'haveRadar', 'haveCon' }, passIfAll = { 'guardFac',}, }, buildRaider = { --desc = 'Building Raider Bots in your factory.', --tip = 'Combat units are used to attack your enemies and make them suffer.', states = { 'selectBotLab', 'selectBuildRaider', 'buildRaider', }, errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', }, errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT', 'haveBotLab', 'haveRadar', 'haveCon', 'guardFac' }, passIfAll = { 'haveRaider',}, }, congrats = { --desc = 'Congratulations!', errIfAny = { 'metalMapView' }, states = { 'tutorialEnd'}, }, } return {unitClasses=unitClasses, unitClassNames=unitClassNames, mClasses=mClasses, steps=steps, tasks=tasks, taskOrder=taskOrder,}
gpl-2.0
nbkmmw/-m1_l1
plugins/ar-supergroup.lua
1
80814
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY SAJJAD NOORI ▀▄ ▄▀ ▀▄ ▄▀ BY SAJAD NOORI (@SAJJADNOORI) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY SAJJAD NOORI ▀▄ ▄▀ ▀▄ ▄▀ Orders : الاوامر ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] local function check_member_super(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg if success == 0 then send_large_msg(receiver, "👌🏻لتلعَب بكَيفك فقَطَ أَلمطور يحَق لهَ✔️") end for k,v in pairs(result) do local member_id = v.peer_id if member_id ~= our_id then -- SuperGroup configuration data[tostring(msg.to.id)] = { group_type = 'SuperGroup', long_id = msg.to.peer_id, moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.title, '_', ' '), lock_arabic = 'no', lock_link = "no", flood = 'yes', lock_spam = 'yes', lock_sticker = 'no', member = 'no', public = 'no', lock_rtl = 'no', lock_contacts = 'no', strict = 'no' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) local text = ' تم اتفعيل كبد حياتي تريد اتراسل صانع اسورس اضغط هنا: @m1_l1✔️.' return reply_msg(msg.id, text, ok_cb, false) end end end --Check Members #rem supergroup local function check_member_superrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local text = '✔️ تمً تَعطَيلَ ألمَجمَوَعـه ✔️.' return reply_msg(msg.id, text, ok_cb, false) end end end --Function to Add supergroup local function superadd(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg}) end --Function to remove supergroup local function superrem(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg}) end --Get and output admins and bots in supergroup local function callback(cb_extra, success, result) local i = 1 local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ") local member_type = cb_extra.member_type local text = member_type.." for "..chat_name..":\n" for k,v in pairsByKeys(result) do if not v.first_name then name = " " else vname = v.first_name:gsub("‮", "") name = vname:gsub("_", " ") end text = text.."\n"..i.." - "..name.."["..v.peer_id.."]" i = i + 1 end send_large_msg(cb_extra.receiver, text) end --Get and output info about supergroup local function callback_info(cb_extra, success, result) local title ="♨️ معلومات عن مجموعة⁉️: ["..result.title.."]\n\n" local admin_num = "❣ عدد الادمنيه: "..result.admins_count.."\n" local user_num = "❣ عدد الاعضاء: "..result.participants_count.."\n" local kicked_num = "❣ الاعضاء الاكثر تفاعل: "..result.kicked_count.."\n" local channel_id = "❣ ايدي المجموعه: "..result.peer_id.."\n" if result.username then channel_username = "❣ معرف المجموعه : @"..result.username else channel_username = "" end local text = title..admin_num..user_num..kicked_num..channel_id..channel_username send_large_msg(cb_extra.receiver, text) end --Get and output members of supergroup local function callback_who(cb_extra, success, result) local text = "❗️ اعضاء المجموعه ♨️ "..cb_extra.receiver local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then username = " @"..v.username else username = "" end text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n" --text = text.."\n"..username i = i + 1 end local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false) post_msg(cb_extra.receiver, text, ok_cb, false) end --Get and output list of kicked users for supergroup local function callback_kicked(cb_extra, success, result) --vardump(result) local text = "❗️ قائمه ايديات الاعضاء ♨️ "..cb_extra.receiver.."\n\n" local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then name = name.." @"..v.username end text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n" i = i + 1 end local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false) --send_large_msg(cb_extra.receiver, text) end --Begin supergroup locks local function lock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return '😠 الروابط بالفعل مقفوله في المجموعه 🔐' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return ' تم ✔️ قفل الروابط في المجموعه 🔐' end end local function unlock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return '😠 الروابط بالفعل مفتوحه في المجموعه 🔓✔️' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return ' تم ✔️ فتح الروابط في المجموعه يمكنك الارسال الان 🔓' end end local function lock_group_spam(msg, data, target) if not is_momod(msg) then return end if not is_owner(msg) then return "✋🏻 لا تلعب بكيفك فقط المدير والادمن يفعل ذالك😠" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return '😠 مضاد السبام بالفعل مفتوح 💊🔓' else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return 'تم ✔️ فتح مضاد السبام 💊 🔓' end end local function unlock_group_spam(msg, data, target) if not is_momod(msg) then return end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return '😠 مضاد السبام بالفعيل مقفول 💊 ✔️' else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return 'تم ✔️ قفل مضاد السبام 💊 🔐' end end local function lock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return '😠 التكرار بالفعل مقفل 🔐✔️' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'تم ✔️ قفل التكرار 🔐' end end local function unlock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return '😠 التكرار بالفعل مفتوح 🔓✔️' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'تم ✔️ فتح التكرار 🔓' end end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return '😠 الغه العربيه بالفعل مقفوله 🔐✔️' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'تم ✔️ قفل اللغه العربيه 🔐' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return '😠 اللغه العربيه بالفعل مفتوحه 🔓✔️' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'تم ✔️ فتح اللغه العربيه 🔓' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return '😠 الاضافه بالفعل مقفوله 🔐✋🏻' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'تم ✔️ قفل الاضافه 🔐✋🏻' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return '😠 الاضافه بالفعل مفتوحه 🔓✔️' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'تم ✔️ فتح الاضافه 🔓🌹' end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return '😠 الاضافه الجماعيه بالفعل مقفوله 🔐 ✋🏻' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'تم ✔️ قفل الاضافه الجماعيه 🔐 ✋🏻' end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return '😠 الاضافه الجماعيه بالفعل مفتوحه 🔓✔️' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'تم ✔️ فتح الاضافه الجماعيه 🔓🌹' end end local function lock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return '😠 الملصقات بالفعل مقفوله 🔐✋🏻' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'تم ✔️ قفل الملصقات 🔐✋🏻' end end local function unlock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return '😠 الملصقات بالفعل مفتوحه 🔓✔️' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'تم ✔️ فتح الملصقات 🔐✔️' end end local function lock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'yes' then return '😠 جهات الاتصال بالفعل مقفوله 🔐✋🏻' else data[tostring(target)]['settings']['lock_contacts'] = 'yes' save_data(_config.moderation.data, data) return 'تم ✔️ قفل جهات الاتصال 🔐✋🏻' end end local function unlock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'no' then return '😠 جهات الاتصال بالفعل مفتوحه 🔓✔️' else data[tostring(target)]['settings']['lock_contacts'] = 'no' save_data(_config.moderation.data, data) return 'تم ✔️ فتح جهات الاتصال 🔓⭕️' end end local function enable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'yes' then return '😠 التحذير بالفعل مقفول 🔐✋🏻' else data[tostring(target)]['settings']['strict'] = 'yes' save_data(_config.moderation.data, data) return 'تم ✔️ قفل التحذير 🔐✋🏻' end end local function disable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'no' then return '😠 التحذير بالفعل مفتوح 🔓✔️' else data[tostring(target)]['settings']['strict'] = 'no' save_data(_config.moderation.data, data) return '✔️ تم فتح التحذير 🔓⭕️' end end --End supergroup locks --'Set supergroup rules' function local function set_rulesmod(msg, data, target) if not is_momod(msg) then return end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'تم ✔️ وضع القوانين 📋 في المجموعة 👥' end --'Get supergroup rules' function local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'ليس ❌ هناك قوانين 📋 في المجموعة 👥' end local rules = data[tostring(msg.to.id)][data_cat] local group_name = data[tostring(msg.to.id)]['settings']['set_name'] local rules = group_name..' 📋 قوانين مجموعة ♨️\n\n'..rules:gsub("/n", " ") return rules end --Set supergroup to public or not public function local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "❌ 😠 لا تلعب بكيفك فقط المدير والادمن يفعل ذالك❗️✋🏻" end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'yes' then return '😠 المجموعه عامه بالفعل ✔️' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return '👥 المجموعه الان اصبحت عامه ♨️✔️' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'no' then return '👥المجموعه ❌ ليست عامه ❗️' else data[tostring(target)]['settings']['public'] = 'no' data[tostring(target)]['long_id'] = msg.to.long_id save_data(_config.moderation.data, data) return '👥 المجموعه الان ليست عامه ❗️' end end --Show supergroup settings; function function show_supergroup_settingsmod(msg, target) if not is_momod(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "⚙ اعدادات المجموعه 👥\n❣ قفل الروابط : "..settings.lock_link.."\n❣ قفل التكرار: "..settings.flood.."\n❣ عدد التكرار : "..NUM_MSG_MAX.."\n❣ قفل الكلايش الطويله: "..settings.lock_spam.."\n❣ قفل اللغه العربيه: "..settings.lock_arabic.."\n❣ قفل الاضافه: "..settings.lock_member.."\n❣ قفل المغادره: "..settings.lock_rtl.."\n❣ قفل الملصقات: "..settings.lock_sticker.."\n❣ المراقبه: "..settings.public.."\n❣ قفل جميع الاعدادات: "..settings.strict return text end local function promote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' 😠 لتلح هوه بالفعل ضمن الاداره 😈.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) end local function demote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' 😠✋🏻 لـتَلحَ هَوَهَ بأَلفعَل ضمَنْ ألآَعضأء 👿.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) end local function promote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return send_large_msg(receiver, '✋🏻❌ الَمَجموَعهْ ليستَ فعأَلهَ ❗️.') end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' 😠 لتلَحَ هَوْهَ بألفعلَ ضمََنَ أَلآَدمَنِيـَهْ 😈.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' رفَعـوَكَ أدمـن 😉🎓 شدَ حيـلكَ 💪🔅.') end local function demote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return send_large_msg(receiver, '✋🏻❌ الَمَجموَعهْ ليستَ فعأَلهَ ❗️.') end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' 😠✋🏻 لـتَلحَ هَوَهَ بأَلفعَل ضمَنْ ألآَعضأء 👿.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' خِطيَهْ نَزلَوَ منَ ألآَدمنَيِهَ 💔 لتَبجي يَـَأ لمَعهَ عينَي😢.') end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return '✋🏻❌ الَمَجموَعهْ ليستَ فعأَلهَ ❗️.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then return '❌ لآَ يِـوَجـدَ أَدمنـيِهَ حـأليـأَ ❗️.' end local i = 1 local message = '\n💢 قأئمَهَ ألآَدمــنيِهَ ⁉️ ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end -- Start by reply actions function get_message_callback(extra, success, result) local get_cmd = extra.get_cmd local msg = extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") if get_cmd == "ايدي" and not result.action then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]") id1 = send_large_msg(channel, result.from.peer_id) elseif get_cmd == 'ايدي' and result.action then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id else user_id = result.peer_id end local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]") id1 = send_large_msg(channel, user_id) end elseif get_cmd == "idfrom" then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]") id2 = send_large_msg(channel, result.fwd_from.peer_id) elseif get_cmd == 'channel_block' and not result.action then local member_id = result.from.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "❌ لاتمسلت بكيفك لايمكنك طرد الادمن أو المديرَ❗️") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "❌ لا تمسلت بكيفك لايمكنك طرد الاداري❗️") end --savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply") kick_user(member_id, channel_id) elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then local user_id = result.action.user.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "❌ لاتمسلت بكيفك لايمكنك طرد الادمن أو المديرَ❗️") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "❌ لا تمسلت بكيفك لايمكنك طرد الاداري❗️") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.") kick_user(user_id, channel_id) elseif get_cmd == "مسح" then delete_msg(result.id, ok_cb, false) savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply") elseif get_cmd == "رفع اداري" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." بَعـدَ شـتريَدْ 😍 مَنَ ربـَكَ تَمَ رفعَكَ فَي ألآَدرهَ 💪" else text = "[ "..user_id.." ]بَعـدَ شـتريَدْ 😍 مَنَ ربـَكَ تَمَ رفعَكَ فَي ألآَدرهَ 💪" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "تنزيل اداري" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id if is_admin2(result.from.peer_id) then return send_large_msg(channel_id, "✋🏻❌ لآ تمسَلت بكَيفكَ لآَ يمكَنَكَ تنزَيل أدأريَ 😂") end channel_demote(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." خطـيهَ تمَ تنزيله 😢 مَنْ ألآَدأرهَ لتبجي جرَأَرهَ كلـبيَ 💔" else text = "[ "..user_id.." ] خطـيهَ تمَ تنزيله 😢 مَنْ ألآَدأرهَ لتبجي جرَأَرهَ كلـبيَ 💔" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "رفع المدير" then local group_owner = data[tostring(result.to.peer_id)]['set_owner'] if group_owner then local channel_id = 'channel#id'..result.to.peer_id if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(channel_id, user, ok_cb, false) end local user_id = "user#id"..result.from.peer_id channel_set_admin(channel_id, user_id, ok_cb, false) data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply") if result.from.username then text = "@"..result.from.username.." [ "..result.from.peer_id.." ] ولآَ يـهمَكَ تمَ ✔️ رفعـكَ مـديـر 👍 سفنجهَ كلـبيَ 💔" else text = "[ "..result.from.peer_id.." ] ولآَ يـهمَكَ تمَ ✔️ رفعـكَ مـديـر 👍 سفنجهَ كلـبيَ 💔" end send_large_msg(channel_id, text) end elseif get_cmd == "رفع ادمن" then local receiver = result.to.peer_id local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id if result.to.peer_type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply") promote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_set_mod(channel_id, user, ok_cb, false) end elseif get_cmd == "تنزيل ادمن" then local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id --local user = "user#id"..result.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] تنزيل ادمن: @"..member_username.."["..user_id.."] by reply") demote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_demote(channel_id, user, ok_cb, false) elseif get_cmd == 'mute_user' then if result.service then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id end end if action == 'chat_add_user_link' then if result.from then user_id = result.from.peer_id end end else user_id = result.from.peer_id end local receiver = extra.receiver local chat_id = msg.to.id print(user_id) print(chat_id) if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, "["..user_id.."] 😉 جراره ❤️ راح الكتم منك يلا دردش 💔") elseif is_admin1(msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] ✋🏻عميت على نفسك تم كتمك 🤐") end end end -- End by reply actions --By ID actions local function cb_user_info(extra, success, result) local receiver = extra.receiver local user_id = result.peer_id local get_cmd = extra.get_cmd local data = load_data(_config.moderation.data) --[[if get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" else text = "[ "..result.peer_id.." ] has been set as an admin" end send_large_msg(receiver, text)]] if get_cmd == "تنزيل اداري" then if is_admin2(result.peer_id) then return send_large_msg(receiver, "لآ تمسَلت بكَيفكَ لآَ يمكَنَكَ تنزَيل أدأريَ 😂") end local user_id = "user#id"..result.peer_id channel_demote(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." خطـيهَ تمَ تنزيله 😢 منْ ألآَدأرهَ لتبجي جرَأَرهَ كلـبيَ 💔" send_large_msg(receiver, text) else text = "[ "..result.peer_id.." ] خطـيهَ تمَ تنزيله 😢 منْ ألآَدأرهَ لتبجي جرَأَرهَ كلـبيَ 💔" send_large_msg(receiver, text) end elseif get_cmd == "رفع ادمن" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end promote2(receiver, member_username, user_id) elseif get_cmd == "تنزيل ادمن" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end demote2(receiver, member_username, user_id) end end -- Begin resolve username actions local function callbackres(extra, success, result) local member_id = result.peer_id local member_username = "@"..result.username local get_cmd = extra.get_cmd if get_cmd == "الايدي" then local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local channel = 'channel#id'..extra.channelid send_large_msg(channel, user..'\n'..name) return user elseif get_cmd == "ايدي" then local user = result.peer_id local channel = 'channel#id'..extra.channelid send_large_msg(channel, user) return user elseif get_cmd == "invite" then local receiver = extra.channel local user_id = "user#id"..result.peer_id channel_invite(receiver, user_id, ok_cb, false) --[[elseif get_cmd == "channel_block" then local user_id = result.peer_id local channel_id = extra.channelid local sender = extra.sender if member_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end kick_user(user_id, channel_id) elseif get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel channel_set_admin(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been set as an admin" send_large_msg(channel_id, text) end elseif get_cmd == "setowner" then local receiver = extra.channel local channel = string.gsub(receiver, 'channel#id', '') local from_id = extra.from_id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then local user = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(result.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username") if result.username then text = member_username.." [ "..result.peer_id.." ] added as owner" else text = "[ "..result.peer_id.." ] added as owner" end send_large_msg(receiver, text) end]] elseif get_cmd == "رفع ادمن" then local receiver = extra.channel local user_id = result.peer_id --local user = "user#id"..result.peer_id promote2(receiver, member_username, user_id) --channel_set_mod(receiver, user, ok_cb, false) elseif get_cmd == "تنزيل ادمن" then local receiver = extra.channel local user_id = result.peer_id local user = "user#id"..result.peer_id demote2(receiver, member_username, user_id) elseif get_cmd == "تنزيل اداري" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel if is_admin2(result.peer_id) then return send_large_msg(channel_id, "لآ تمسَلت بكَيفكَ لآَ يمكَنَكَ تنزَيل أدأريَ 😂") end channel_demote(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." خطـيهَ تمَ تنزيله 😢 منْ ألآَدأرهَ لتبجي جرَأَرهَ كلـبيَ 💔" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." خطـيهَ تمَ تنزيله 😢 منْ ألآَدأرهَ لتبجي جرَأَرهَ كلـبيَ 💔" send_large_msg(channel_id, text) end local receiver = extra.channel local user_id = result.peer_id demote_admin(receiver, member_username, user_id) elseif get_cmd == 'mute_user' then local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] removed from muted user list") elseif is_owner(extra.msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to muted user list") end end end --End resolve username actions --Begin non-channel_invite username actions local function in_channel_cb(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local msg = cb_extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(cb_extra.msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local member = cb_extra.username local memberid = cb_extra.user_id if member then text = 'لايوجد عضو @'..member..' في هاذه المجموعه.' else text = 'لايوجد عضو ['..memberid..'] في هاذه المجموعه.' end if get_cmd == "channel_block" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = v.peer_id local channel_id = cb_extra.msg.to.id local sender = cb_extra.msg.from.id if user_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(user_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "❌ لاتمسلت بكيفك لايمكنك طرد الادمن أو المديرَ❗️") end if is_admin2(user_id) then return send_large_msg("channel#id"..channel_id, "❌ لا تمسلت بكيفك لايمكنك طرد الاداري❗️") end if v.username then text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]") else text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]") end kick_user(user_id, channel_id) return end end elseif get_cmd == "رفع اداري" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = "user#id"..v.peer_id local channel_id = "channel#id"..cb_extra.msg.to.id channel_set_admin(channel_id, user_id, ok_cb, false) if v.username then text = "@"..v.username.." ["..v.peer_id.."] بَعـدَ شـتريَدْ 😍 منَ ربـَكَ تَمَ رفعَكَ فَي ألآَدرهَ 💪" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]") else text = "["..v.peer_id.."] بَعـدَ شـتريَدْ 😍 منَ ربـَكَ تَمَ رفعَكَ فَي ألآَدرهَ 💪" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id) end if v.username then member_username = "@"..v.username else member_username = string.gsub(v.print_name, '_', ' ') end local receiver = channel_id local user_id = v.peer_id promote_admin(receiver, member_username, user_id) end send_large_msg(channel_id, text) return end elseif get_cmd == 'رفع المدير' then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..v.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(v.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username") if result.username then text = member_username.." ["..v.peer_id.."] ولآَ يـهمَكَ تمَ ✔️ رفعـكَ مـديـر 👍 سفنجهَ كلـبيَ 💔" else text = "["..v.peer_id.."] ولآَ يـهمَكَ تمَ ✔️ رفعـكَ مـديـر 👍 سفنجهَ كلـبيَ 💔" end end elseif memberid and vusername ~= member and vpeer_id ~= memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end data[tostring(channel)]['set_owner'] = tostring(memberid) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username") text = "["..memberid.."] ولآَ يـهمَكَ تمَ ✔️ رفعـكَ مـديـر 👍 سفنجهَ كلـبيَ 💔" end end end end send_large_msg(receiver, text) end --End non-channel_invite username actions --'Set supergroup photo' function local function set_supergroup_photo(msg, success, result) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return end local receiver = get_receiver(msg) if success then local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) channel_set_photo(receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end --Run function local function run(msg, matches) if msg.to.type == 'chat' then if matches[1] == 'ترقيه سوبر' then if not is_admin1(msg) then return end local receiver = get_receiver(msg) chat_upgrade(receiver, ok_cb, false) end elseif msg.to.type == 'channel'then if matches[1] == 'ترقيه سوبر' then if not is_admin1(msg) then return end return "المجموعة 👥 خارقة ♻️ بالفعل ⁉️" end end if msg.to.type == 'channel' then local support_id = msg.from.id local receiver = get_receiver(msg) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local data = load_data(_config.moderation.data) if matches[1] == 'تفعيل المجموعه' and not matches[2] then if not is_admin1(msg) and not is_support(support_id) then return end if is_super_group(msg) then return reply_msg(msg.id, '👈 ألمَجمَوَعــهَ بألــتأكيَدَ مفعَلهَ ✔️..', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup") superadd(msg) set_mutes(msg.to.id) channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false) end if matches[1] == 'تعطيل المجموعه' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then return reply_msg(msg.id, '👈 ألمَجمَوَعــهَ بألــتأكيَدَ تَمَ تَعَطيَلهَأَ ✔️..', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed") superrem(msg) rem_mutes(msg.to.id) end if not data[tostring(msg.to.id)] then return end if matches[1] == "معلومات المجموعه" then if not is_owner(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info") channel_info(receiver, callback_info, {receiver = receiver, msg = msg}) end if matches[1] == "الاداريين" then if not is_owner(msg) and not is_support(msg.from.id) then return end member_type = '❤️ قَأئـمَهَ أَلأدرييــنَ ❤️' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list") admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1] == "مدير المجموعه" then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "✋🏻❌ لا يوجد مدير في المجموعه ننتظر انتخاباتكم لتعين المدير 😂😚" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "❤️ مدير المجموعة المحترم ❤️ ["..group_owner..']' end if matches[1] == "الادمنيه" then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) -- channel_get_admins(receiver,callback, {receiver = receiver}) end if matches[1] == "كشف بوت" and is_momod(msg) then member_type = 'كشف البوتات ب المجموعه' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list") channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1] == "ايدي الاعضاء" and not matches[2] and is_momod(msg) then local user_id = msg.from.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list") channel_get_users(receiver, callback_who, {receiver = receiver}) end if matches[1] == "kicked" and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list") channel_get_kicked(receiver, callback_kicked, {receiver = receiver}) end if matches[1] == 'مسح' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'مسح', msg = msg } delete_msg(msg.id, ok_cb, false) get_message(msg.reply_id, get_message_callback, cbreply_extra) end end if matches[1] == 'بلوك' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'channel_block', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'بلوك' and string.match(matches[2], '^%d+$') then --[[local user_id = matches[2] local channel_id = msg.to.id if is_momod2(user_id, channel_id) and not is_admin2(user_id) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]") kick_user(user_id, channel_id)]] local get_cmd = 'channel_block' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif msg.text:match("@[%a%d]") then --[[local cbres_extra = { channelid = msg.to.id, get_cmd = 'channel_block', sender = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'channel_block' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'ايدي' then if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then local cbreply_extra = { get_cmd = 'ايدي', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then local cbreply_extra = { get_cmd = 'idfrom', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif msg.text:match("@[%a%d]") then local cbres_extra = { channelid = msg.to.id, get_cmd = 'ايدي' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username) resolve_username(username, callbackres, cbres_extra) else savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID") return "❣ ايدي مجموعة "..string.gsub(msg.to.print_name, "_", " ")..": "..msg.to.id end end if matches[1] == 'مغادره' then if msg.to.type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] left via kickme") channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if matches[1] == 'تغير الرابط' and is_momod(msg)then local function callback_link (extra , success, result) local receiver = get_receiver(msg) if success == 0 then send_large_msg(receiver, '*✋🏻❌ عذرا لا يمكن تغير رابط هاذه المجموعه 👍* \nالمجموعه ليست من صنع البوت.\n\nيرجئ استخدام الرابط الخاص بها في اعدادات المجموعه') data[tostring(msg.to.id)]['settings']['set_link'] = nil save_data(_config.moderation.data, data) else send_large_msg(receiver, "تم✔️ تغير الرابط 👥 ") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link") export_channel_link(receiver, callback_link, false) end if matches[1] == 'ضع رابط' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting' save_data(_config.moderation.data, data) return '✋🏻 يرجئ ارسال رابط المجموعه خاص بك 👥' end if msg.text then if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = msg.text save_data(_config.moderation.data, data) return "تم ✔️ حفظ الرابط 👍" end end if matches[1] == 'الرابط' then if not is_momod(msg) then return end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "❓يرجئ ارسال [/تغير الرابط] لانشاء رابط المجموعه👍🏻✔️" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "⁉️ رابط المجموعه 👥:\n"..group_link end if matches[1] == "invite" and is_sudo(msg) then local cbres_extra = { channel = get_receiver(msg), get_cmd = "invite" } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username) resolve_username(username, callbackres, cbres_extra) end if matches[1] == 'الايدي' and is_owner(msg) then local cbres_extra = { channelid = msg.to.id, get_cmd = 'الايدي' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username) resolve_username(username, callbackres, cbres_extra) end --[[if matches[1] == 'kick' and is_momod(msg) then local receiver = channel..matches[3] local user = "user#id"..matches[2] chaannel_kick(receiver, user, ok_cb, false) end]] if matches[1] == 'رفع اداري' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'رفع اداري', msg = msg } setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'رفع اداري' and string.match(matches[2], '^%d+$') then --[[] local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'setadmin' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]] local get_cmd = 'رفع اداري' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'رفع اداري' and not string.match(matches[2], '^%d+$') then --[[local cbres_extra = { channel = get_receiver(msg), get_cmd = 'setadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'رفع اداري' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'تنزيل اداري' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'تنزيل اداري', msg = msg } demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'تنزيل اداري' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'تنزيل اداري' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'تنزيل اداري' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'تنزيل اداري' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username) resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'رفع المدير' and is_owner(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'رفع المدير', msg = msg } setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'رفع المدير' and string.match(matches[2], '^%d+$') then --[[ local group_owner = data[tostring(msg.to.id)]['set_owner'] if group_owner then local receiver = get_receiver(msg) local user_id = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user_id, ok_cb, false) end local user = "user#id"..matches[2] channel_set_admin(receiver, user, ok_cb, false) data[tostring(msg.to.id)]['set_owner'] = tostring(matches[2]) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = "[ "..matches[2].." ] added as owner" return text end]] local get_cmd = 'رفع المدير' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'رفع المدير' and not string.match(matches[2], '^%d+$') then local get_cmd = 'رفع المدير' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'رفع ادمن' then if not is_momod(msg) then return end if not is_owner(msg) then return "👌🏻لتلعَب بكَيفك فقَطَ المدير او الاداري يحَق لهَ✔️" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'رفع ادمن', msg = msg } promote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'رفع ادمن' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'رفع ادمن' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'رفع ادمن' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'رفع ادمن', } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'mp' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_set_mod(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'md' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_demote(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'تنزيل ادمن' then if not is_momod(msg) then return end if not is_owner(msg) then return "👌🏻لتلعَب بكَيفك فقَطَ المدير او الاداري يحَق لهَ✔️" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'تنزيل ادمن', msg = msg } demote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'تنزيل ادمن' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'تنزيل ادمن' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'تنزيل ادمن' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == "ضع اسم" and is_momod(msg) then local receiver = get_receiver(msg) local set_name = string.gsub(matches[2], '_', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2]) rename_channel(receiver, set_name, ok_cb, false) end if msg.service and msg.action.type == 'chat_rename' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title) data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title save_data(_config.moderation.data, data) end if matches[1] == "ضع وصف" and is_momod(msg) then local receiver = get_receiver(msg) local about_text = matches[2] local data_cat = 'description' local target = msg.to.id data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text) channel_set_about(receiver, about_text, ok_cb, false) return "تم ✔️ وضع وصف المجموعه 👥\n\n✋🏻 انضر الئ الحول لتشاهد الوصف الجديد 👥" end if matches[1] == "ضع معرف" and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "تم ✔️ وضع معرف للمجموعه 👥⁉️\n\n✋🏻 انضر الئ الحول لتشاهد تغيرات المجموعه 👥") elseif success == 0 then send_large_msg(receiver, "💢 فشل تعيين معرف المجموعه 👥⁉️\nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.") end end local username = string.gsub(matches[2], '@', '') channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end if matches[1] == 'ضع قوانين' and is_momod(msg) then rules = matches[2] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]") return set_rulesmod(msg, data, target) end if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo") load_photo(msg.id, set_supergroup_photo, msg) return end end if matches[1] == 'ضع صوره' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo") return '✋🏻ارسل لي صوره الان ✔️👍' end if matches[1] == 'مسح' then if not is_momod(msg) then return end if not is_momod(msg) then return "👌🏻لتلعَب بكَيفك فقَطَ المدير يحَق لهَ✔️" end if matches[2] == 'الادمنيه' then if next(data[tostring(msg.to.id)]['moderators']) == nil then return '❗️ عذرا لا يوجد ادمنيه في المجموعه ليتم مسحهم ❌' end for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") return '❌ تم مسح قائمه الادمنيه ✔️' end if matches[2] == 'القوانين' then local data_cat = 'rules' if data[tostring(msg.to.id)][data_cat] == nil then return "❗️عذرا لا يوجد قوانين في المجموعه ليتم مسحها ❌" end data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") return '❌ تم مسح قوانين المجموعه ✔️' end if matches[2] == 'الوصف' then local receiver = get_receiver(msg) local about_text = ' ' local data_cat = 'description' if data[tostring(msg.to.id)][data_cat] == nil then return '❗️عذرا لا يوجد وصف في المجموعه ليتم مسحه ❌' end data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") channel_set_about(receiver, about_text, ok_cb, false) return "❌ تم مسح وصف المجموعه ✔️" end if matches[2] == 'المكتومين' then chat_id = msg.to.id local hash = 'mute_user:'..chat_id redis:del(hash) return "❌ تم مسح قائمه المكتومين ✔️" end if matches[2] == 'المعرف' and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "❌ تم مسح معرف المجموعه ✔️") elseif success == 0 then send_large_msg(receiver, "❗️غذرا فشل مسح معرف المجموعه ❌") end end local username = "" channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end end if matches[1] == 'قفل' and is_momod(msg) then local target = msg.to.id if matches[2] == 'الروابط' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ") return lock_group_links(msg, data, target) end if matches[2] == 'الكلايش' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ") return lock_group_spam(msg, data, target) end if matches[2] == 'التكرار' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_flood(msg, data, target) end if matches[2] == 'العربيه' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'الاضافه' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2]:lower() == 'الاضافه الجماعيه' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names") return lock_group_rtl(msg, data, target) end if matches[2] == 'الملصقات' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting") return lock_group_sticker(msg, data, target) end if matches[2] == 'جهات الاتصال' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting") return lock_group_contacts(msg, data, target) end if matches[2] == 'الكل' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings") return enable_strict_rules(msg, data, target) end end if matches[1] == 'فتح' and is_momod(msg) then local target = msg.to.id if matches[2] == 'الروابط' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting") return unlock_group_links(msg, data, target) end if matches[2] == 'الكلايش' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam") return unlock_group_spam(msg, data, target) end if matches[2] == 'التكرار' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood") return unlock_group_flood(msg, data, target) end if matches[2] == 'العربيه' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked Arabic") return unlock_group_arabic(msg, data, target) end if matches[2] == 'الاضافه' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2]:lower() == 'الاضافه الجماعيه' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names") return unlock_group_rtl(msg, data, target) end if matches[2] == 'الملصقات' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting") return unlock_group_sticker(msg, data, target) end if matches[2] == 'جهات الاتصال' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting") return unlock_group_contacts(msg, data, target) end if matches[2] == 'التحذير' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings") return disable_strict_rules(msg, data, target) end end if matches[1] == 'ضع تكرار' then if not is_momod(msg) then return end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "😈 ضع تكرار من 5 الئ 20 ✔️" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'تم ☑️ تعيين التكرار ‼️⚙ للعدد 👈🏿: '..matches[2] end if matches[1] == 'المراقبه' and is_momod(msg) then local target = msg.to.id if matches[2] == 'نعم' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'لا' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: not public") return unset_public_membermod(msg, data, target) end end if matches[1] == 'قفل' and is_momod(msg) then local chat_id = msg.to.id if matches[2] == 'الصوت' then local msg_type = 'Audio' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'الصور' then local msg_type = 'Photo' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'الفيديو' then local msg_type = 'Video' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'الصور المتحركه' then local msg_type = 'Gifs' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." have been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'الفايلات' then local msg_type = 'Documents' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." have been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'الدردشه' then local msg_type = 'Text' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "Mute "..msg_type.." is already on" end end if matches[2] == 'المجموعه' then local msg_type = 'All' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return "Mute "..msg_type.." has been enabled" else return "Mute "..msg_type.." is already on" end end end if matches[1] == 'فتح' and is_momod(msg) then local chat_id = msg.to.id if matches[2] == 'الصوت' then local msg_type = 'Audio' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'الصور' then local msg_type = 'Photo' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'الفيديو' then local msg_type = 'Video' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'الصور المتحركه' then local msg_type = 'Gifs' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'الفايلات' then local msg_type = 'Documents' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'الدردشه' then local msg_type = 'Text' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute message") unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute text is already off" end end if matches[2] == 'المجموعه' then local msg_type = 'All' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return "Mute "..msg_type.." has been disabled" else return "Mute "..msg_type.." is already disabled" end end end if matches[1] == "كتم" and is_momod(msg) then local chat_id = msg.to.id local hash = "mute_user"..chat_id local user_id = "" if type(msg.reply_id) ~= "nil" then local receiver = get_receiver(msg) local get_cmd = "mute_user" muteuser = get_message(msg.reply_id, get_message_callback, {receiver = receiver, get_cmd = get_cmd, msg = msg}) elseif matches[1] == "كتم" and string.match(matches[2], '^%d+$') then local user_id = matches[2] if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list") return "["..user_id.."] removed from the muted users list" elseif is_momod(msg) then mute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list") return "["..user_id.."] added to the muted user list" end elseif matches[1] == "كتم" and not string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local get_cmd = "mute_user" local username = matches[2] local username = string.gsub(matches[2], '@', '') resolve_username(username, callbackres, {receiver = receiver, get_cmd = get_cmd, msg=msg}) end end if matches[1] == "اعدادات الوسائط" and is_momod(msg) then local chat_id = msg.to.id if not has_mutes(chat_id) then set_mutes(chat_id) return mutes_list(chat_id) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist") return mutes_list(chat_id) end if matches[1] == "المكتومين" and is_momod(msg) then local chat_id = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist") return muted_user_list(chat_id) end if matches[1] == 'الاعدادات' and is_momod(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ") return show_supergroup_settingsmod(msg, target) end if matches[1] == 'القوانين' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'help' and not is_owner(msg) then text = "Message /superhelp to @Teleseed in private for SuperGroup help" reply_msg(msg.id, text, ok_cb, false) elseif matches[1] == 'help' and is_owner(msg) then local name_log = user_print_name(msg.from) savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp") return super_help() end if matches[1] == 'peer_id' and is_admin1(msg)then text = msg.to.peer_id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end if matches[1] == 'msg.to.id' and is_admin1(msg) then text = msg.to.id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end --Admin Join Service Message if msg.service then local action = msg.action.type if action == 'chat_add_user_link' then if is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.from.id) and not is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup") channel_set_mod(receiver, user, ok_cb, false) end end if action == 'chat_add_user' then if is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_mod(receiver, user, ok_cb, false) end end end if matches[1] == 'msg.to.peer_id' then post_large_msg(receiver, msg.to.peer_id) end end end local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end return { patterns = { "^(تفعيل المجموعه)$", "^(تعطيل المجموعه)$", "^([Mm]ove) (.*)$", "^(معلومات المجموعه)$", "^(الاداريين)$", "^(مدير المجموعه)$", "^(الادمنيه)$", "^(كشف بوت)$", "^(ايدي الاعضاء)$", "^([Kk]icked)$", "^(بلوك) (.*)", "^(بلوك)", "^(ترقيه سوبر)$", "^(ايدي)$", "^(ايدي) (.*)$", "^(مغادره)$", "^[#!/]([Kk]ick) (.*)$", "^(تغير الرابط)$", "^(ضع رابط)$", "^(الرابط)$", "^(الايدي) (.*)$", "^(رفع اداري) (.*)$", "^(رفع اداري)", "^(تنزيل اداري) (.*)$", "^(تنزيل اداري)", "^(رفع المدير) (.*)$", "^(رفع المدير)$", "^(رفع ادمن) (.*)$", "^(رفع ادمن)", "^(تنزيل ادمن) (.*)$", "^(تنزيل ادمن)", "^(ضع اسم) (.*)$", "^(ضع وصف) (.*)$", "^(ضع قوانين) (.*)$", "^(ضع صوره)$", "^(ضع معرف) (.*)$", "^(مسح)$", "^(قفل) (.*)$", "^(فتح) (.*)$", "^(قفل) ([^%s]+)$", "^(فتح) ([^%s]+)$", "^(كتم)$", "^(كتم) (.*)$", "^(المراقبه) (.*)$", "^(الاعدادات)$", "^(القوانين)$", "^(ضع تكرار) (%d+)$", "^(مسح) (.*)$", "^[#!/]([Hh]elpp)$", "^(اعدادات الوسائط)$", "^(المكتومين)$", "[#!/](mp) (.*)", "[#!/](md) (.*)", "^(https://telegram.me/joinchat/%S+)$", "msg.to.peer_id", "%[(document)%]", "%[(photo)%]", "%[(video)%]", "%[(audio)%]", "%[(contact)%]", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process } --End supergrpup.lua --By @SAJJADNOORI
gpl-2.0
rlcevg/Zero-K
LuaUI/Widgets/unit_jumper_jumpOverObstacle.lua
5
20448
local version = "v0.507" function widget:GetInfo() return { name = "Auto Jump Over Terrain", desc = version .. " Jumper automatically jump over terrain or buildings if it shorten walk time.", author = "Msafwan", date = "4 February 2014", license = "GNU GPL, v2 or later", layer = 21, enabled = false } end VFS.Include("LuaRules/Configs/customcmds.h.lua") VFS.Include("LuaRules/Utilities/isTargetReachable.lua") local spGetUnitPosition = Spring.GetUnitPosition local spGetUnitRulesParam = Spring.GetUnitRulesParam local spValidUnitID = Spring.ValidUnitID local spValidFeatureID = Spring.ValidFeatureID local spGetCommandQueue = Spring.GetCommandQueue local spGiveOrderArrayToUnitArray = Spring.GiveOrderArrayToUnitArray local spGetFeaturePosition = Spring.GetFeaturePosition local spGetUnitIsStunned = Spring.GetUnitIsStunned local spGetGameSeconds = Spring.GetGameSeconds ------------------------------------------------------------ ------------------------------------------------------------ local gaussUnitDefID = UnitDefNames["armpb"].id local myTeamID local jumperAddInfo={} --Spread job stuff: (spread looping across 1 second) local spreadJobs=nil; local effectedUnit={}; local spreadPreviousIndex = nil; --end spread job stuff --Network lag hax stuff: (wait until unit receive command before processing 2nd time) local waitForNetworkDelay = nil; local issuedOrderTo = {} --end network lag stuff local jumpersToJump = {} local jumpersToWatch = {} local jumpersToJump_Count = 0 local jumpersUnitID = {} local jumperDefs = VFS.Include("LuaRules/Configs/jump_defs.lua") local exclusions = { UnitDefNames["corsumo"].id, -- has AoE damage on jump, could harm allies --UnitDefNames["corsktl"].id -- jump is precious } for i = 1, #exclusions do jumperDefs[exclusions[i]] = nil end function widget:Initialize() local _, _, spec, teamID = Spring.GetPlayerInfo(Spring.GetMyPlayerID()) if spec then widgetHandler:RemoveWidget() return false end myTeamID = teamID end function widget:GameFrame(n) if n%30==14 then --every 30 frame period (1 second) at the 14th frame: --check if we were waiting for lag for too long local currentSecond = spGetGameSeconds() if waitForNetworkDelay then if currentSecond - waitForNetworkDelay[1] > 4 then waitForNetworkDelay = nil end end end if ( n%15==0 and not waitForNetworkDelay) or spreadJobs then local numberOfUnitToProcess = 29 --NUMBER OF UNIT PER SECOND. minimum: 29 unit per second local numberOfUnitToProcessPerFrame = math.ceil(numberOfUnitToProcess/29) --spread looping to entire 1 second spreadJobs = false local numberOfLoopToProcessPerFrame = math.ceil(jumpersToJump_Count/29) local currentLoopIndex = spreadPreviousIndex or 1 local currentLoopCount = 0 local currentUnitProcessed = 0 local finishLoop = false if currentLoopIndex >= jumpersToJump_Count then finishLoop =true end local k = currentLoopIndex while (k<=jumpersToJump_Count) do local unitID = jumpersToJump[k][2] local validUnitID = spValidUnitID(unitID) if not validUnitID then DeleteEntryThenReIndex(k,unitID) k = k -1 end if validUnitID then local unitDefID = jumpersToJump[k][1] if not jumperAddInfo[unitDefID] then local moveID = UnitDefs[unitDefID].moveDef.id local ud = UnitDefs[unitDefID] local halfJumprangeSq = (jumperDefs[unitDefID].range/2)^2 local heightSq = jumperDefs[unitDefID].height^2 local totalFlightDist = math.sqrt(halfJumprangeSq+heightSq)*2 local jumpTime = (totalFlightDist/jumperDefs[unitDefID].speed + jumperDefs[unitDefID].delay)/30 -- is in second local unitSpeed = ud.speed --speed is in elmo-per-second local weaponRange = GetUnitFastestWeaponRange(ud) local unitSize = math.max(ud.xsize*4, ud.zsize*4) jumperAddInfo[unitDefID] = {moveID,jumpTime,unitSpeed,weaponRange, unitSize} end repeat --note: not looping, only for using "break" as method of escaping code local _,_,inBuild = spGetUnitIsStunned(unitID) if inBuild then break; --a.k.a: Continue end --IS NEW UNIT? initialize them-- effectedUnit[unitID] = effectedUnit[unitID] or {cmdCount=0,cmdOne={id=nil,x=nil,y=nil,z=nil},cmdTwo={id=nil,x=nil,y=nil,z=nil}} --IS UNIT IDLE? skip-- local cmd_queue = spGetCommandQueue(unitID, -1); if not (cmd_queue and cmd_queue[1]) then DeleteEntryThenReIndex(k,unitID) k = k -1 break; --a.k.a: Continue end -- IS UNIT WAITING? skip-- if (cmd_queue[1].id== CMD.WAIT) then break; end --IS UNIT CHARGING JUMP? skip-- local jumpReload = spGetUnitRulesParam(unitID,"jumpReload") if jumpReload then if jumpReload < 0.95 then break; --a.k.a: Continue end end --EXTRACT RELEVANT FIRST COMMAND -- local cmd_queue2 local unitIsAttacking for i=1, #cmd_queue do local cmd = cmd_queue[i] local equivalentMoveCMD = ConvertCMDToMOVE({cmd}) if equivalentMoveCMD then unitIsAttacking = (cmd.id == CMD.ATTACK) cmd_queue2 = equivalentMoveCMD break end end if not cmd_queue2 then break end currentUnitProcessed = currentUnitProcessed + 1 --CHECK POSITION OF PREVIOUS JUMP-- local extraCmd1 = nil local extraCmd2 = nil local jumpCmdPos = 0 if effectedUnit[unitID].cmdCount >0 then for i=1, #cmd_queue do local cmd = cmd_queue[i] if cmd.id == effectedUnit[unitID].cmdOne.id and cmd.params[1] == effectedUnit[unitID].cmdOne.x and cmd.params[2] == effectedUnit[unitID].cmdOne.y and cmd.params[3] == effectedUnit[unitID].cmdOne.z then extraCmd1 = {CMD.REMOVE, {cmd.tag},{"shift"}} jumpCmdPos = i end if cmd.id == effectedUnit[unitID].cmdTwo.id and cmd.params[1] == effectedUnit[unitID].cmdTwo.x and cmd.params[2] == effectedUnit[unitID].cmdTwo.y and cmd.params[3] == effectedUnit[unitID].cmdTwo.z then extraCmd2 = {CMD.REMOVE, {cmd.tag},{"shift"}} jumpCmdPos = jumpCmdPos or i break end end end --CHECK FOR OBSTACLE IN LINE-- local tx,ty,tz = cmd_queue2.params[1],cmd_queue2.params[2],cmd_queue2.params[3] local px,py,pz = spGetUnitPosition(unitID) local enterPoint_X,enterPoint_Y,enterPoint_Z,exitPoint_X,exitPoint_Y,exitPoint_Z = GetNearestObstacleEnterAndExitPoint(px,py,pz, tx,tz, unitDefID) if exitPoint_X and exitPoint_Z then local unitSpeed = jumperAddInfo[unitDefID][3] local moveID = jumperAddInfo[unitDefID][1] local weaponRange = jumperAddInfo[unitDefID][4] --MEASURE REGULAR DISTANCE-- local distance = GetWaypointDistance(unitID,moveID,cmd_queue2,px,py,pz,unitIsAttacking,weaponRange) local normalTimeToDest = (distance/unitSpeed) --is in second --MEASURE DISTANCE WITH JUMP-- cmd_queue2.params[1]=enterPoint_X cmd_queue2.params[2]=enterPoint_Y cmd_queue2.params[3]=enterPoint_Z distance = GetWaypointDistance(unitID,moveID,cmd_queue2,px,py,pz,false,0) --distance to jump-start point local timeToJump = (distance/unitSpeed) --is in second cmd_queue2.params[1]=tx --target coordinate cmd_queue2.params[2]=ty cmd_queue2.params[3]=tz local jumpTime = jumperAddInfo[unitDefID][2] distance = GetWaypointDistance(unitID,moveID,cmd_queue2,exitPoint_X,exitPoint_Y,exitPoint_Z,unitIsAttacking,weaponRange) --dist out of jump-landing point local timeFromExitToDestination = (distance/unitSpeed) --in second local totalTimeWithJump = timeToJump + timeFromExitToDestination + jumpTime --NOTE: time to destination is in second. local normalPathTime = normalTimeToDest - 2 --add 2 second benefit to regular walking (make walking more attractive choice unless jump can save more than 1 second travel time) if totalTimeWithJump < normalPathTime then local commandArray = {[1]=nil,[2]=nil,[3]=nil,[4]=nil} if (math.abs(enterPoint_X-px)>50 or math.abs(enterPoint_Z-pz)>50) then commandArray[1]= {CMD.INSERT, {0, CMD.MOVE, CMD.OPT_INTERNAL, enterPoint_X,enterPoint_Y,enterPoint_Z}, {"alt"}} commandArray[2]= {CMD.INSERT, {0, CMD_JUMP, CMD.OPT_INTERNAL, exitPoint_X,exitPoint_Y,exitPoint_Z}, {"alt"}} commandArray[3]= extraCmd2 commandArray[4]= extraCmd1 effectedUnit[unitID].cmdCount = 2 effectedUnit[unitID].cmdOne.id = CMD.MOVE effectedUnit[unitID].cmdOne.x = enterPoint_X effectedUnit[unitID].cmdOne.y = enterPoint_Y effectedUnit[unitID].cmdOne.z = enterPoint_Z effectedUnit[unitID].cmdTwo.id = CMD_JUMP effectedUnit[unitID].cmdTwo.x = exitPoint_X effectedUnit[unitID].cmdTwo.y = exitPoint_Y effectedUnit[unitID].cmdTwo.z = exitPoint_Z issuedOrderTo[unitID] = {CMD.MOVE,enterPoint_X,enterPoint_Y,enterPoint_Z} else commandArray[1]= {CMD.INSERT, {0, CMD_JUMP, CMD.OPT_INTERNAL, exitPoint_X,exitPoint_Y,exitPoint_Z}, {"alt"}} commandArray[2]= extraCmd2 commandArray[3]= extraCmd1 effectedUnit[unitID].cmdCount = 1 effectedUnit[unitID].cmdTwo.id = CMD_JUMP effectedUnit[unitID].cmdTwo.x = exitPoint_X effectedUnit[unitID].cmdTwo.y = exitPoint_Y effectedUnit[unitID].cmdTwo.z = exitPoint_Z issuedOrderTo[unitID] = {CMD_JUMP,exitPoint_X,exitPoint_Y,exitPoint_Z} end spGiveOrderArrayToUnitArray({unitID},commandArray) waitForNetworkDelay = waitForNetworkDelay or {spGetGameSeconds(),0} waitForNetworkDelay[2] = waitForNetworkDelay[2] + 1 end elseif jumpCmdPos >= 2 then spGiveOrderArrayToUnitArray({unitID},{extraCmd2,extraCmd1}) --another command was sandwiched before the Jump command, making Jump possibly outdated/no-longer-optimal. Remove Jump effectedUnit[unitID].cmdCount = 0 end until true currentLoopCount = currentLoopCount + 1 end if k >= jumpersToJump_Count then finishLoop =true break elseif currentUnitProcessed >= numberOfUnitToProcessPerFrame or currentLoopCount>= numberOfLoopToProcessPerFrame then spreadJobs = true spreadPreviousIndex = k+1 --continue at next frame break end k = k + 1 end if finishLoop then spreadPreviousIndex = nil end end end function DeleteEntryThenReIndex(k,unitID) --last position to current position if k ~= jumpersToJump_Count then local lastUnitID = jumpersToJump[jumpersToJump_Count][2] jumpersToJump[k] = jumpersToJump[jumpersToJump_Count] jumpersUnitID[lastUnitID] = k end effectedUnit[unitID] = nil jumpersUnitID[unitID] = nil jumpersToJump[jumpersToJump_Count] = nil jumpersToJump_Count = jumpersToJump_Count - 1 end function GetNearestObstacleEnterAndExitPoint(currPosX,currPosY, currPosZ, targetPosX,targetPosZ, unitDefID) local nearestEnterPoint_X,original_X = currPosX,currPosX local nearestEnterPoint_Z,original_Z = currPosZ,currPosZ local nearestEnterPoint_Y,original_Y = currPosY,currPosY local exitPoint_X, exitPoint_Z,exitPoint_Y local overobstacle = false local distFromObstacle = 0 local distToTarget= 0 local unitBoxDist local defaultJumprange = jumperDefs[unitDefID].range -20 local addingFunction = function() end local check_n_SavePosition = function(x,z,gradient,addValue) local endOfLine = (math.abs(x-targetPosX) < 20) and (math.abs(z-targetPosZ) < 20) if endOfLine then return x,z,true end local y = Spring.GetGroundHeight(x, z) local clear,_ = Spring.TestBuildOrder(gaussUnitDefID or unitDefID, x,y ,z, 1) -- Spring.MarkerAddPoint(x,y ,z, clear) if clear == 0 then overobstacle = true if distToTarget==0 then distToTarget = math.sqrt((targetPosX-x)^2 + (targetPosZ-z)^2) local backX,backZ = addingFunction(x,z,addValue*-5,gradient) local backY = Spring.GetGroundHeight(backX, backZ) distFromObstacle = math.sqrt((x-backX)^2 + (z-backZ)^2) local backDistToTarget = math.sqrt((targetPosX-backX)^2 + (targetPosZ-backZ)^2) local unitDistToTarget = math.sqrt((targetPosX-original_X)^2 + (targetPosZ-original_Z)^2) if unitDistToTarget > backDistToTarget then nearestEnterPoint_X = backX --always used 1 step behind current box, avoid too close to terrain nearestEnterPoint_Z = backZ nearestEnterPoint_Y = backY else nearestEnterPoint_X = original_X --always used 1 step behind current box, avoid too close to terrain nearestEnterPoint_Z = original_Z nearestEnterPoint_Y = original_Y end -- Spring.MarkerAddPoint(backX,backY,backZ, "enter") else distFromObstacle = distFromObstacle + unitBoxDist distToTarget = distToTarget - unitBoxDist end elseif overobstacle then distFromObstacle = distFromObstacle + unitBoxDist distToTarget = distToTarget - unitBoxDist if distFromObstacle < defaultJumprange and distToTarget>0 then exitPoint_X = x exitPoint_Z = z exitPoint_Y = y -- Spring.MarkerAddPoint(x,y,z, "exit") else return x,z,true end end x,z = addingFunction(x,z,addValue,gradient) return x,z,false end local x, z = currPosX,currPosZ local xDiff = targetPosX -currPosX local zDiff = targetPosZ -currPosZ local unitBoxSize = jumperAddInfo[unitDefID][5] local finish=false if math.abs(xDiff) > math.abs(zDiff) then local xSgn = xDiff/math.abs(xDiff) local gradient = zDiff/xDiff unitBoxDist = math.sqrt(unitBoxSize*unitBoxSize + unitBoxSize*gradient*unitBoxSize*gradient) local xadd = unitBoxSize*xSgn addingFunction = function(x,z,addValue,gradient) return x+addValue, z+addValue*gradient end for i=1, 9999 do x,z,finish = check_n_SavePosition(x,z,gradient,xadd) if finish then break end end else local zSgn = zDiff/math.abs(zDiff) local gradient = xDiff/zDiff unitBoxDist = math.sqrt(unitBoxSize*unitBoxSize + unitBoxSize*gradient*unitBoxSize*gradient) local zadd = unitBoxSize*zSgn addingFunction = function(x,z,addValue,gradient) return x+addValue*gradient, z + addValue end for i=1, 9999 do x,z,finish = check_n_SavePosition(x,z,gradient,zadd) if finish then break end end end return nearestEnterPoint_X,nearestEnterPoint_Y,nearestEnterPoint_Z,exitPoint_X,exitPoint_Y,exitPoint_Z end function GetUnitFastestWeaponRange(unitDef) local fastestReloadTime, fastReloadRange = 999,-1 for _, weapons in ipairs(unitDef.weapons) do --reference: gui_contextmenu.lua by CarRepairer local weaponsID = weapons.weaponDef local weaponsDef = WeaponDefs[weaponsID] if weaponsDef.name and not (weaponsDef.name:find('fake') or weaponsDef.name:find('noweapon')) then --reference: gui_contextmenu.lua by CarRepairer if not weaponsDef.isShield then --if not shield then this is conventional weapon local reloadTime = weaponsDef.reload if reloadTime < fastestReloadTime then --find the weapon with the smallest reload time fastestReloadTime = reloadTime fastReloadRange = weaponsDef.range end end end end return fastReloadRange end function ConvertCMDToMOVE(command) if (command == nil) then return nil end command = command[1] if (command == nil) then return nil end if command.id == CMD.MOVE or command.id == CMD.PATROL or command.id == CMD.FIGHT or command.id == CMD.JUMP or command.id == CMD.ATTACK then if not command.params[2] then local x,y,z = spGetUnitPosition(command.params[1]) if not x then --outside LOS and radar return nil end command.id = CMD.MOVE command.params[1] = x command.params[2] = y command.params[3] = z return command else command.id = CMD.MOVE return command end end if command.id == CMD.RECLAIM or command.id == CMD.REPAIR or command.id == CMD.GUARD or command.id == CMD.RESSURECT then local isPossible2PartAreaCmd = command.params[5] if not command.params[4] or isPossible2PartAreaCmd then --if not area-command or the is the 2nd part of area-command (1st part have radius at 4th-param, 2nd part have unitID/featureID at 1st-param and radius at 5th-param) if not command.params[2] or isPossible2PartAreaCmd then local x,y,z if command.id == CMD.REPAIR or command.id == CMD.GUARD then x,y,z = GetUnitOrFeaturePosition(command.params[1]) elseif command.id == CMD.RECLAIM or command.id == CMD.RESSURECT then x,y,z = GetUnitOrFeaturePosition(command.params[1]) end if not x then return nil end command.id = CMD.MOVE command.params[1] = x command.params[2] = y command.params[3] = z return command else command.id = CMD.MOVE return command end else return nil --no area command allowed end end if command.id < 0 then if command.params[3]==nil then --is building unit in factory return nil end command.id = CMD.MOVE return command end if command.id == CMD_WAIT_AT_BEACON then return command end return nil end function GetWaypointDistance(unitID,moveID,queue,px,py,pz,isAttackCmd,weaponRange) --Note: source is from unit_transport_ai.lua (by Licho) local d = 0 if (queue == nil) then return 99999 end local v = queue if (v.id == CMD.MOVE) then local reachable = true --always assume target reachable local waypoints if moveID then --unit has compatible moveID? local minimumGoalDist = (isAttackCmd and weaponRange-20) or 128 local result, lastwaypoint result, lastwaypoint, waypoints = Spring.Utilities.IsTargetReachable(moveID,px,py,pz,v.params[1],v.params[2],v.params[3],minimumGoalDist) if result == "outofreach" then --abit out of reach? reachable=false --target is unreachable! end end if reachable then local distOffset = (isAttackCmd and weaponRange-20) or 0 if waypoints then --we have waypoint to destination? local way1,way2,way3 = px,py,pz for i=1, #waypoints do --sum all distance in waypoints d = d + Dist(way1,way2,way3, waypoints[i][1],waypoints[i][2],waypoints[i][3]) way1,way2,way3 = waypoints[i][1],waypoints[i][2],waypoints[i][3] end d = d + math.max(0,Dist(way1,way2,way3, v.params[1], v.params[2], v.params[3])-distOffset) --connect endpoint of waypoint to destination else --so we don't have waypoint? d = d + math.max(0,Dist(px,py, pz, v.params[1], v.params[2], v.params[3])-distOffset) --we don't have waypoint then measure straight line end else --pathing says target unreachable?! d = d + Dist(px,py, pz, v.params[1], v.params[2], v.params[3])*10 +9999 --target unreachable! end end return d end function Dist(x,y,z, x2, y2, z2) local xd = x2-x local yd = y2-y local zd = z2-z return math.sqrt(xd*xd + yd*yd + zd*zd) end function GetUnitOrFeaturePosition(id) --copied from cmd_commandinsert.lua widget (by dizekat) if id<=Game.maxUnits and spValidUnitID(id) then return spGetUnitPosition(id) elseif spValidFeatureID(id-Game.maxUnits) then return spGetFeaturePosition(id-Game.maxUnits) --featureID is always offset by maxunit count end return nil end ------------------------------------------------------------ ------------------------------------------------------------ function widget:UnitFinished(unitID,unitDefID,unitTeam) if myTeamID==unitTeam and jumperDefs[unitDefID] and not jumpersUnitID[unitID] then jumpersToJump_Count = jumpersToJump_Count + 1 jumpersToJump[jumpersToJump_Count] = {unitDefID,unitID} jumpersUnitID[unitID] = jumpersToJump_Count end end function widget:UnitCommand(unitID, unitDefID, unitTeam, cmdID, cmdOpts, cmdParams) if myTeamID==unitTeam and jumperDefs[unitDefID] then if (cmdID ~= CMD.INSERT) then if not jumpersUnitID[unitID] then jumpersToJump_Count = jumpersToJump_Count + 1 jumpersToJump[jumpersToJump_Count] = {unitDefID,unitID} jumpersUnitID[unitID] = jumpersToJump_Count end end if (cmdID == CMD.INSERT) then --detected our own command (indicate network delay have passed) local issuedOrderContent = issuedOrderTo[unitID] if issuedOrderContent and (cmdParams[4] == issuedOrderContent[2] and cmdParams[5] == issuedOrderContent[3] and cmdParams[6] == issuedOrderContent[4]) then issuedOrderTo[unitID] = nil if waitForNetworkDelay then waitForNetworkDelay[2] = waitForNetworkDelay[2] - 1 if waitForNetworkDelay[2]==0 then waitForNetworkDelay = nil end end end end end end
gpl-2.0
Satoshi-t/Re-SBS
lua/ai/sp-ai.lua
1
95602
sgs.weapon_range.SPMoonSpear = 3 sgs.ai_skill_playerchosen.sp_moonspear = function(self, targets) targets = sgs.QList2Table(targets) self:sort(targets, "defense") for _, target in ipairs(targets) do if self:isEnemy(target) and self:damageIsEffective(target) and sgs.isGoodTarget(target, targets, self) then return target end end return nil end sgs.ai_playerchosen_intention.sp_moonspear = 80 function sgs.ai_slash_prohibit.weidi(self, from, to, card) local lord = self.room:getLord() if not lord then return false end if to:isLord() then return false end for _, askill in sgs.qlist(lord:getVisibleSkillList(true)) do if askill:objectName() ~= "weidi" and askill:isLordSkill() then local filter = sgs.ai_slash_prohibit[askill:objectName()] if type(filter) == "function" and filter(self, from, to, card) then return true end end end end sgs.ai_skill_use["@jijiang"] = function(self, prompt) if self.player:hasFlag("Global_JijiangFailed") then return "." end local card = sgs.Card_Parse("@JijiangCard=.") local dummy_use = { isDummy = true } self:useSkillCard(card, dummy_use) if dummy_use.card then local jijiang = {} if sgs.jijiangtarget then for _, p in ipairs(sgs.jijiangtarget) do table.insert(jijiang, p:objectName()) end return "@JijiangCard=.->" .. table.concat(jijiang, "+") end end return "." end --[[ 技能:庸肆(弃牌部分) 备注:为了解决场上有古锭刀时弃白银狮子的问题而重写此弃牌方案。 ]]-- sgs.ai_skill_discard.yongsi = function(self, discard_num, min_num, optional, include_equip) if optional then return {} end local flag = "h" local equips = self.player:getEquips() if include_equip and not (equips:isEmpty() or self.player:isJilei(equips:first())) then flag = flag .. "e" end local cards = self.player:getCards(flag) local to_discard = {} cards = sgs.QList2Table(cards) local aux_func = function(card) local place = self.room:getCardPlace(card:getEffectiveId()) if place == sgs.Player_PlaceEquip then if card:isKindOf("SilverLion") then local players = self.room:getOtherPlayers(self.player) for _,p in sgs.qlist(players) do local blade = p:getWeapon() if blade and blade:isKindOf("GudingBlade") then if p:inMyAttackRange(self.player) then if self:isEnemy(p, self.player) then return 6 end else break --因为只有一把古锭刀,检测到有人装备了,其他人就不会再装备了,此时可跳出检测。 end end end if self.player:isWounded() then return -2 end elseif card:isKindOf("Weapon") and self.player:getHandcardNum() < discard_num + 2 and not self:needKongcheng() then return 0 elseif card:isKindOf("OffensiveHorse") and self.player:getHandcardNum() < discard_num + 2 and not self:needKongcheng() then return 0 elseif card:isKindOf("OffensiveHorse") then return 1 elseif card:isKindOf("Weapon") then return 2 elseif card:isKindOf("DefensiveHorse") then return 3 elseif self:hasSkills("bazhen|yizhong") and card:isKindOf("Armor") then return 0 elseif card:isKindOf("Armor") then return 4 end elseif self:hasSkills(sgs.lose_equip_skill) then return 5 else return 0 end return 0 end local compare_func = function(a, b) if aux_func(a) ~= aux_func(b) then return aux_func(a) < aux_func(b) end return self:getKeepValue(a) < self:getKeepValue(b) end table.sort(cards, compare_func) local least = min_num if discard_num - min_num > 1 then least = discard_num -1 end for _, card in ipairs(cards) do if not self.player:isJilei(card) then table.insert(to_discard, card:getId()) end if (self.player:hasSkill("qinyin") and #to_discard >= least) or #to_discard >= discard_num then break end end return to_discard end sgs.ai_skill_invoke.danlao = function(self, data) local effect = data:toCardUse() local current = self.room:getCurrent() if effect.card:isKindOf("GodSalvation") and self.player:isWounded() or effect.card:isKindOf("ExNihilo") then return false elseif effect.card:isKindOf("AmazingGrace") and (self.player:getSeat() - current:getSeat()) % (global_room:alivePlayerCount()) < global_room:alivePlayerCount()/2 then return false else return true end end sgs.ai_skill_invoke.jilei = function(self, data) local damage = data:toDamage() if not damage then return false end self.jilei_source = damage.from return self:isEnemy(damage.from) end sgs.ai_skill_choice.jilei = function(self, choices) local tmptrick = sgs.Sanguosha:cloneCard("ex_nihilo") if (self:hasCrossbowEffect(self.jilei_source) and self.jilei_source:inMyAttackRange(self.player)) or self.jilei_source:isCardLimited(tmptrick, sgs.Card_MethodUse, true) then return "BasicCard" else return "TrickCard" end end local function yuanhu_validate(self, equip_type, is_handcard) local is_SilverLion = false if equip_type == "SilverLion" then equip_type = "Armor" is_SilverLion = true end local targets if is_handcard then targets = self.friends else targets = self.friends_noself end if equip_type ~= "Weapon" then if equip_type == "DefensiveHorse" or equip_type == "OffensiveHorse" then self:sort(targets, "hp") end if equip_type == "Armor" then self:sort(targets, "handcard") end if is_SilverLion then for _, enemy in ipairs(self.enemies) do if enemy:hasSkill("kongcheng") and enemy:isKongcheng() then local seat_diff = enemy:getSeat() - self.player:getSeat() local alive_count = self.room:alivePlayerCount() if seat_diff < 0 then seat_diff = seat_diff + alive_count end if seat_diff > alive_count / 2.5 + 1 then return enemy end end end for _, enemy in ipairs(self.enemies) do if self:hasSkills("bazhen|yizhong", enemy) then return enemy end end end for _, friend in ipairs(targets) do local has_equip = false for _, equip in sgs.qlist(friend:getEquips()) do if equip:isKindOf(equip_type) then has_equip = true break end end if not has_equip then if equip_type == "Armor" then if not self:needKongcheng(friend, true) and not self:hasSkills("bazhen|yizhong", friend) then return friend end else if friend:isWounded() and not (friend:hasSkill("longhun") and friend:getCardCount(true) >= 3) then return friend end end end end else for _, friend in ipairs(targets) do local has_equip = false for _, equip in sgs.qlist(friend:getEquips()) do if equip:isKindOf(equip_type) then has_equip = true break end end if not has_equip then for _, aplayer in sgs.qlist(self.room:getAllPlayers()) do if friend:distanceTo(aplayer) == 1 then if self:isFriend(aplayer) and not aplayer:containsTrick("YanxiaoCard") and (aplayer:containsTrick("indulgence") or aplayer:containsTrick("supply_shortage") or (aplayer:containsTrick("lightning") and self:hasWizard(self.enemies))) then aplayer:setFlags("AI_YuanhuToChoose") return friend end end end self:sort(self.enemies, "defense") for _, enemy in ipairs(self.enemies) do if friend:distanceTo(enemy) == 1 and self.player:canDiscard(enemy, "he") then enemy:setFlags("AI_YuanhuToChoose") return friend end end end end end return nil end sgs.ai_skill_use["@@yuanhu"] = function(self, prompt) local cards = self.player:getHandcards() cards = sgs.QList2Table(cards) self:sortByKeepValue(cards) if self.player:hasArmorEffect("silver_lion") then local player = yuanhu_validate(self, "SilverLion", false) if player then return "@YuanhuCard=" .. self.player:getArmor():getEffectiveId() .. "->" .. player:objectName() end end if self.player:getOffensiveHorse() then local player = yuanhu_validate(self, "OffensiveHorse", false) if player then return "@YuanhuCard=" .. self.player:getOffensiveHorse():getEffectiveId() .. "->" .. player:objectName() end end if self.player:getWeapon() then local player = yuanhu_validate(self, "Weapon", false) if player then return "@YuanhuCard=" .. self.player:getWeapon():getEffectiveId() .. "->" .. player:objectName() end end if self.player:getArmor() and self.player:getLostHp() <= 1 and self.player:getHandcardNum() >= 3 then local player = yuanhu_validate(self, "Armor", false) if player then return "@YuanhuCard=" .. self.player:getArmor():getEffectiveId() .. "->" .. player:objectName() end end for _, card in ipairs(cards) do if card:isKindOf("DefensiveHorse") then local player = yuanhu_validate(self, "DefensiveHorse", true) if player then return "@YuanhuCard=" .. card:getEffectiveId() .. "->" .. player:objectName() end end end for _, card in ipairs(cards) do if card:isKindOf("OffensiveHorse") then local player = yuanhu_validate(self, "OffensiveHorse", true) if player then return "@YuanhuCard=" .. card:getEffectiveId() .. "->" .. player:objectName() end end end for _, card in ipairs(cards) do if card:isKindOf("Weapon") then local player = yuanhu_validate(self, "Weapon", true) if player then return "@YuanhuCard=" .. card:getEffectiveId() .. "->" .. player:objectName() end end end for _, card in ipairs(cards) do if card:isKindOf("SilverLion") then local player = yuanhu_validate(self, "SilverLion", true) if player then return "@YuanhuCard=" .. card:getEffectiveId() .. "->" .. player:objectName() end end if card:isKindOf("Armor") and yuanhu_validate(self, "Armor", true) then local player = yuanhu_validate(self, "Armor", true) if player then return "@YuanhuCard=" .. card:getEffectiveId() .. "->" .. player:objectName() end end end end sgs.ai_skill_playerchosen.yuanhu = function(self, targets) targets = sgs.QList2Table(targets) for _, p in ipairs(targets) do if p:hasFlag("AI_YuanhuToChoose") then p:setFlags("-AI_YuanhuToChoose") return p end end return targets[1] end sgs.ai_card_intention.YuanhuCard = function(self, card, from, to) if to[1]:hasSkill("bazhen") or to[1]:hasSkill("yizhong") or (to[1]:hasSkill("kongcheng") and to[1]:isKongcheng()) then if sgs.Sanguosha:getCard(card:getEffectiveId()):isKindOf("SilverLion") then sgs.updateIntention(from, to[1], 10) return end end sgs.updateIntention(from, to[1], -50) end sgs.ai_cardneed.yuanhu = sgs.ai_cardneed.equip sgs.yuanhu_keep_value = { Peach = 6, Jink = 5.1, Weapon = 4.7, Armor = 4.8, Horse = 4.9 } sgs.ai_cardneed.xueji = function(to, card) return to:getHandcardNum() < 3 and card:isRed() end local xueji_skill = {} xueji_skill.name = "xueji" table.insert(sgs.ai_skills, xueji_skill) xueji_skill.getTurnUseCard = function(self) if self.player:hasUsed("XuejiCard") then return end if not self.player:isWounded() then return end local card local cards = self.player:getCards("he") cards = sgs.QList2Table(cards) self:sortByUseValue(cards, true) for _, acard in ipairs(cards) do if acard:isRed() then card = acard break end end if card then card = sgs.Card_Parse("@XuejiCard=" .. card:getEffectiveId()) return card end return nil end local function can_be_selected_as_target_xueji(self, card, who) -- validation of rule if self.player:getWeapon() and self.player:getWeapon():getEffectiveId() == card:getEffectiveId() then if self.player:distanceTo(who, sgs.weapon_range[self.player:getWeapon():getClassName()] - self.player:getAttackRange(false)) > self.player:getAttackRange() then return false end elseif self.player:getOffensiveHorse() and self.player:getOffensiveHorse():getEffectiveId() == card:getEffectiveId() then if self.player:distanceTo(who, 1) > self.player:getAttackRange() then return false end elseif self.player:distanceTo(who) > self.player:getAttackRange() then return false end -- validation of strategy if self:isEnemy(who) and self:damageIsEffective(who) and not self:cantbeHurt(who) and not self:getDamagedEffects(who) and not self:needToLoseHp(who) then if not self.player:hasSkill("jueqing") then if who:hasSkill("guixin") and (self.room:getAliveCount() >= 4 or not who:faceUp()) and not who:hasSkill("manjuan") then return false end if (who:hasSkill("ganglie") or who:hasSkill("neoganglie")) and (self.player:getHp() == 1 and self.player:getHandcardNum() <= 2) then return false end if who:hasSkill("jieming") then for _, enemy in ipairs(self.enemies) do if enemy:getHandcardNum() <= enemy:getMaxHp() - 2 and not enemy:hasSkill("manjuan") then return false end end end if who:hasSkill("fangzhu") then for _, enemy in ipairs(self.enemies) do if not enemy:faceUp() then return false end end end if who:hasSkill("yiji") then local huatuo = self.room:findPlayerBySkillName("jijiu") if huatuo and self:isEnemy(huatuo) and huatuo:getHandcardNum() >= 3 then return false end end end return true elseif self:isFriend(who) then if who:hasSkill("yiji") and not self.player:hasSkill("jueqing") then local huatuo = self.room:findPlayerBySkillName("jijiu") if (huatuo and self:isFriend(huatuo) and huatuo:getHandcardNum() >= 3 and huatuo ~= self.player) or (who:getLostHp() == 0 and who:getMaxHp() >= 3) then return true end end if who:hasSkill("hunzi") and who:getMark("hunzi") == 0 and who:objectName() == self.player:getNextAlive():objectName() and who:getHp() == 2 then return true end if self:cantbeHurt(who) and not self:damageIsEffective(who) and not (who:hasSkill("manjuan") and who:getPhase() == sgs.Player_NotActive) and not (who:hasSkill("kongcheng") and who:isKongcheng()) then return true end return false end return false end sgs.ai_skill_use_func.XuejiCard = function(card, use, self) if self.player:getLostHp() == 0 or self.player:hasUsed("XuejiCard") then return end self:sort(self.enemies) local to_use = false for _, enemy in ipairs(self.enemies) do if can_be_selected_as_target_xueji(self, card, enemy) then to_use = true break end end if not to_use then for _, friend in ipairs(self.friends_noself) do if can_be_selected_as_target_xueji(self, card, friend) then to_use = true break end end end if to_use then use.card = card if use.to then for _, enemy in ipairs(self.enemies) do if can_be_selected_as_target_xueji(self, card, enemy) then use.to:append(enemy) if use.to:length() == self.player:getLostHp() then return end end end for _, friend in ipairs(self.friends_noself) do if can_be_selected_as_target_xueji(self, card, friend) then use.to:append(friend) if use.to:length() == self.player:getLostHp() then return end end end assert(use.to:length() > 0) end end end sgs.ai_card_intention.XuejiCard = function(self, card, from, tos) local room = from:getRoom() local huatuo = room:findPlayerBySkillName("jijiu") for _,to in ipairs(tos) do local intention = 60 if to:hasSkill("yiji") and not from:hasSkill("jueqing") then if (huatuo and self:isFriend(huatuo) and huatuo:getHandcardNum() >= 3 and huatuo:objectName() ~= from:objectName()) then intention = -30 end if to:getLostHp() == 0 and to:getMaxHp() >= 3 then intention = -10 end end if to:hasSkill("hunzi") and to:getMark("hunzi") == 0 then if to:objectName() == from:getNextAlive():objectName() and to:getHp() == 2 then intention = -20 end end if self:cantbeHurt(to) and not self:damageIsEffective(to) then intention = -20 end sgs.updateIntention(from, to, intention) end end sgs.ai_use_value.XuejiCard = 3 sgs.ai_use_priority.XuejiCard = 2.35 sgs.ai_skill_use["@@bifa"] = function(self, prompt) local cards = self.player:getHandcards() cards = sgs.QList2Table(cards) self:sortByKeepValue(cards) self:sort(self.enemies, "hp") if #self.enemies < 0 then return "." end for _, enemy in ipairs(self.enemies) do if enemy:getPile("bifa"):length() > 0 then continue end if not (self:needToLoseHp(enemy) and not self:hasSkills(sgs.masochism_skill, enemy)) then for _, c in ipairs(cards) do if c:isKindOf("EquipCard") then return "@BifaCard=" .. c:getEffectiveId() .. "->" .. enemy:objectName() end end for _, c in ipairs(cards) do if c:isKindOf("TrickCard") and not (c:isKindOf("Nullification") and self:getCardsNum("Nullification") == 1) then return "@BifaCard=" .. c:getEffectiveId() .. "->" .. enemy:objectName() end end for _, c in ipairs(cards) do if c:isKindOf("Slash") then return "@BifaCard=" .. c:getEffectiveId() .. "->" .. enemy:objectName() end end end end end sgs.ai_skill_cardask["@bifa-give"] = function(self, data) local card_type = data:toString() local cards = self.player:getHandcards() cards = sgs.QList2Table(cards) if self:needToLoseHp() and not self:hasSkills(sgs.masochism_skill) then return "." end self:sortByUseValue(cards) for _, c in ipairs(cards) do if c:isKindOf(card_type) and not isCard("Peach", c, self.player) and not isCard("ExNihilo", c, self.player) then return "$" .. c:getEffectiveId() end end return "." end sgs.ai_card_intention.BifaCard = 30 sgs.bifa_keep_value = { Peach = 6, Jink = 5.1, Nullification = 5, EquipCard = 4.9, TrickCard = 4.8 } local songci_skill = {} songci_skill.name = "songci" table.insert(sgs.ai_skills, songci_skill) songci_skill.getTurnUseCard = function(self) return sgs.Card_Parse("@SongciCard=.") end sgs.ai_skill_use_func.SongciCard = function(card,use,self) self:sort(self.friends, "handcard") for _, friend in ipairs(self.friends) do if friend:getMark("songci" .. self.player:objectName()) == 0 and friend:getHandcardNum() < friend:getHp() and not (friend:hasSkill("manjuan") and self.room:getCurrent() ~= friend) then if not (friend:hasSkill("kongcheng") and friend:isKongcheng()) then use.card = sgs.Card_Parse("@SongciCard=.") if use.to then use.to:append(friend) end return end end end self:sort(self.enemies, "handcard") self.enemies = sgs.reverse(self.enemies) for _, enemy in ipairs(self.enemies) do if enemy:getMark("songci" .. self.player:objectName()) == 0 and enemy:getHandcardNum() > enemy:getHp() and not enemy:isNude() and not self:doNotDiscard(enemy, "nil", false, 2) then use.card = sgs.Card_Parse("@SongciCard=.") if use.to then use.to:append(enemy) end return end end end sgs.ai_use_value.SongciCard = 3 sgs.ai_use_priority.SongciCard = 3 sgs.ai_card_intention.SongciCard = function(self, card, from, to) sgs.updateIntention(from, to[1], to[1]:getHandcardNum() > to[1]:getHp() and 80 or -80) end sgs.ai_skill_cardask["@xingwu"] = function(self, data) local cards = sgs.QList2Table(self.player:getHandcards()) if #cards <= 1 and self.player:getPile("xingwu"):length() == 1 then return "." end local good_enemies = {} for _, enemy in ipairs(self.enemies) do if enemy:isMale() and ((self:damageIsEffective(enemy) and not self:cantbeHurt(enemy, self.player, 2)) or (not self:damageIsEffective(enemy) and not enemy:getEquips():isEmpty() and not (enemy:getEquips():length() == 1 and enemy:getArmor() and self:needToThrowArmor(enemy)))) then table.insert(good_enemies, enemy) end end if #good_enemies == 0 and (not self.player:getPile("xingwu"):isEmpty() or not self.player:hasSkill("luoyan")) then return "." end local red_avail, black_avail local n = self.player:getMark("xingwu") if bit32.band(n, 2) == 0 then red_avail = true end if bit32.band(n, 1) == 0 then black_avail = true end self:sortByKeepValue(cards) local xwcard = nil local heart = 0 local to_save = 0 for _, card in ipairs(cards) do if self.player:hasSkill("tianxiang") and card:getSuit() == sgs.Card_Heart and heart < math.min(self.player:getHp(), 2) then heart = heart + 1 elseif isCard("Jink", card, self.player) then if self.player:hasSkill("liuli") and self.room:alivePlayerCount() > 2 then for _, p in sgs.qlist(self.room:getOtherPlayers(self.player)) do if self:canLiuli(self.player, p) then xwcard = card break end end end if not xwcard and self:getCardsNum("Jink") >= 2 then xwcard = card end elseif to_save > self.player:getMaxCards() or (not isCard("Peach", card, self.player) and not (self:isWeak() and isCard("Analeptic", card, self.player))) then xwcard = card else to_save = to_save + 1 end if xwcard then if (red_avail and xwcard:isRed()) or (black_avail and xwcard:isBlack()) then break else xwcard = nil to_save = to_save + 1 end end end if xwcard then return "$" .. xwcard:getEffectiveId() else return "." end end sgs.ai_skill_playerchosen.xingwu = function(self, targets) local good_enemies = {} for _, enemy in ipairs(self.enemies) do if enemy:isMale() then table.insert(good_enemies, enemy) end end if #good_enemies == 0 then return targets:first() end local getCmpValue = function(enemy) local value = 0 if self:damageIsEffective(enemy) then local dmg = enemy:hasArmorEffect("silver_lion") and 1 or 2 if enemy:getHp() <= dmg then value = 5 else value = value + enemy:getHp() / (enemy:getHp() - dmg) end if not sgs.isGoodTarget(enemy, self.enemies, self) then value = value - 2 end if self:cantbeHurt(enemy, self.player, dmg) then value = value - 5 end if enemy:isLord() then value = value + 2 end if enemy:hasArmorEffect("silver_lion") then value = value - 1.5 end if self:hasSkills(sgs.exclusive_skill, enemy) then value = value - 1 end if self:hasSkills(sgs.masochism_skill, enemy) then value = value - 0.5 end end if not enemy:getEquips():isEmpty() then local len = enemy:getEquips():length() if enemy:hasSkills(sgs.lose_equip_skill) then value = value - 0.6 * len end if enemy:getArmor() and self:needToThrowArmor() then value = value - 1.5 end if enemy:hasArmorEffect("silver_lion") then value = value - 0.5 end if enemy:getWeapon() then value = value + 0.8 end if enemy:getArmor() then value = value + 1 end if enemy:getDefensiveHorse() then value = value + 0.9 end if enemy:getOffensiveHorse() then value = value + 0.7 end if self:getDangerousCard(enemy) then value = value + 0.3 end if self:getValuableCard(enemy) then value = value + 0.15 end end return value end local cmp = function(a, b) return getCmpValue(a) > getCmpValue(b) end table.sort(good_enemies, cmp) return good_enemies[1] end sgs.ai_playerchosen_intention.xingwu = 80 sgs.ai_skill_cardask["@yanyu-discard"] = function(self, data) if self.player:getHandcardNum() < 3 and self.player:getPhase() ~= sgs.Player_Play then if self:needToThrowArmor() then return "$" .. self.player:getArmor():getEffectiveId() elseif self:needKongcheng(self.player, true) and self.player:getHandcardNum() == 1 then return "$" .. self.player:handCards():first() else return "." end end local current = self.room:getCurrent() local cards = sgs.QList2Table(self.player:getHandcards()) self:sortByKeepValue(cards) if current:objectName() == self.player:objectName() then local ex_nihilo, savage_assault, archery_attack for _, card in ipairs(cards) do if card:isKindOf("ExNihilo") then ex_nihilo = card elseif card:isKindOf("SavageAssault") and not current:hasSkills("noswuyan|wuyan") then savage_assault = card elseif card:isKindOf("ArcheryAttack") and not current:hasSkills("noswuyan|wuyan") then archery_attack = card end end if savage_assault and self:getAoeValue(savage_assault) <= 0 then savage_assault = nil end if archery_attack and self:getAoeValue(archery_attack) <= 0 then archery_attack = nil end local aoe = archery_attack or savage_assault if ex_nihilo then for _, card in ipairs(cards) do if card:getTypeId() == sgs.Card_TypeTrick and not card:isKindOf("ExNihilo") and card:getEffectiveId() ~= ex_nihilo:getEffectiveId() then return "$" .. card:getEffectiveId() end end end if self.player:isWounded() then local peach for _, card in ipairs(cards) do if card:isKindOf("Peach") then peach = card break end end local dummy_use = { isDummy = true } self:useCardPeach(peach, dummy_use) if dummy_use.card and dummy_use.card:isKindOf("Peach") then for _, card in ipairs(cards) do if card:getTypeId() == sgs.Card_TypeBasic and card:getEffectiveId() ~= peach:getEffectiveId() then return "$" .. card:getEffectiveId() end end end end if aoe then for _, card in ipairs(cards) do if card:getTypeId() == sgs.Card_TypeTrick and card:getEffectiveId() ~= aoe:getEffectiveId() then return "$" .. card:getEffectiveId() end end end if self:getCardsNum("Slash") > 1 then for _, card in ipairs(cards) do if card:objectName() == "slash" then return "$" .. card:getEffectiveId() end end end else local throw_trick local aoe_type if getCardsNum("ArcheryAttack", current, self.player) >= 1 and not current:hasSkills("noswuyan|wuyan") then aoe_type = "archery_attack" end if getCardsNum("SavageAssault", current, self.player) >= 1 and not current:hasSkills("noswuyan|wuyan") then aoe_type = "savage_assault" end if aoe_type then local aoe = sgs.Sanguosha:cloneCard(aoe_type) if self:getAoeValue(aoe, current) > 0 then throw_trick = true end end if getCardsNum("ExNihilo", current, self.player) > 0 then throw_trick = true end if throw_trick then for _, card in ipairs(cards) do if card:getTypeId() == sgs.Card_TypeTrick and not isCard("ExNihilo", card, self.player) then return "$" .. card:getEffectiveId() end end end if self:getCardsNum("Slash") > 1 then for _, card in ipairs(cards) do if card:objectName() == "slash" then return "$" .. card:getEffectiveId() end end end if self:getCardsNum("Jink") > 1 then for _, card in ipairs(cards) do if card:isKindOf("Jink") then return "$" .. card:getEffectiveId() end end end if self.player:getHp() >= 3 and (self.player:getHandcardNum() > 3 or self:getCardsNum("Peach") > 0) then for _, card in ipairs(cards) do if card:isKindOf("Slash") then return "$" .. card:getEffectiveId() end end end if getCardsNum("TrickCard", current, self.player) - getCardsNum("Nullification", current, self.player) > 0 then for _, card in ipairs(cards) do if card:getTypeId() == sgs.Card_TypeTrick and not isCard("ExNihilo", card, self.player) then return "$" .. card:getEffectiveId() end end end end if self:needToThrowArmor() then return "$" .. self.player:getArmor():getEffectiveId() else return "." end end sgs.ai_skill_askforag.yanyu = function(self, card_ids) local cards = {} for _, id in ipairs(card_ids) do table.insert(cards, sgs.Sanguosha:getEngineCard(id)) end self.yanyu_need_player = nil local card, player = self:getCardNeedPlayer(cards, true) if card and player then self.yanyu_need_player = player return card:getEffectiveId() end return -1 end sgs.ai_skill_playerchosen.yanyu = function(self, targets) local only_id = self.player:getMark("YanyuOnlyId") - 1 if only_id < 0 then assert(self.yanyu_need_player ~= nil) return self.yanyu_need_player else local card = sgs.Sanguosha:getEngineCard(only_id) if card:getTypeId() == sgs.Card_TypeTrick and not card:isKindOf("Nullification") then return self.player end local cards = { card } local c, player = self:getCardNeedPlayer(cards, true) return player end end sgs.ai_playerchosen_intention.yanyu = function(self, from, to) if hasManjuanEffect(to) then return end local intention = -60 if self:needKongcheng(to, true) then intention = 10 end sgs.updateIntention(from, to, intention) end sgs.ai_skill_invoke.xiaode = function(self, data) local round = self:playerGetRound(self.player) local xiaode_skill = sgs.ai_skill_choice.huashen(self, table.concat(data:toStringList(), "+"), nil, math.random(1 - round, 7 - round)) if xiaode_skill then sgs.xiaode_choice = xiaode_skill return true else sgs.xiaode_choice = nil return false end end sgs.ai_skill_choice.xiaode = function(self, choices) return sgs.xiaode_choice end function sgs.ai_cardsview_valuable.aocai(self, class_name, player) if player:hasFlag("Global_AocaiFailed") or player:getPhase() ~= sgs.Player_NotActive then return end if class_name == "Slash" and sgs.Sanguosha:getCurrentCardUseReason() == sgs.CardUseStruct_CARD_USE_REASON_RESPONSE_USE then return "@AocaiCard=.:slash" elseif (class_name == "Peach" and player:getMark("Global_PreventPeach") == 0) or class_name == "Analeptic" then local dying = self.room:getCurrentDyingPlayer() if dying and dying:objectName() == player:objectName() then local user_string = "peach+analeptic" if player:getMark("Global_PreventPeach") > 0 then user_string = "analeptic" end return "@AocaiCard=.:" .. user_string else local user_string if class_name == "Analeptic" then user_string = "analeptic" else user_string = "peach" end return "@AocaiCard=.:" .. user_string end end end sgs.ai_skill_invoke.aocai = function(self, data) local asked = data:toStringList() local pattern = asked[1] local prompt = asked[2] return self:askForCard(pattern, prompt, 1) ~= "." end sgs.ai_skill_askforag.aocai = function(self, card_ids) local card = sgs.Sanguosha:getCard(card_ids[1]) if card:isKindOf("Jink") and self.player:hasFlag("dahe") then for _, id in ipairs(card_ids) do if sgs.Sanguosha:getCard(id):getSuit() == sgs.Card_Heart then return id end end return -1 end return card_ids[1] end function SmartAI:getSaveNum(isFriend) local num = 0 for _, player in sgs.qlist(self.room:getAllPlayers()) do if (isFriend and self:isFriend(player)) or (not isFriend and self:isEnemy(player)) then if not self.player:hasSkill("wansha") or player:objectName() == self.player:objectName() then if player:hasSkill("jijiu") then num = num + self:getSuitNum("heart", true, player) num = num + self:getSuitNum("diamond", true, player) num = num + player:getHandcardNum() * 0.4 end if player:hasSkill("nosjiefan") and getCardsNum("Slash", player, self.player) > 0 then if self:isFriend(player) or self:getCardsNum("Jink") == 0 then num = num + getCardsNum("Slash", player, self.player) end end num = num + getCardsNum("Peach", player, self.player) end if player:hasSkill("buyi") and not player:isKongcheng() then num = num + 0.3 end if player:hasSkill("chunlao") and not player:getPile("wine"):isEmpty() then num = num + player:getPile("wine"):length() end if player:hasSkill("jiuzhu") and player:getHp() > 1 and not player:isNude() then num = num + 0.9 * math.max(0, math.min(player:getHp() - 1, player:getCardCount(true))) end if player:hasSkill("renxin") and player:objectName() ~= self.player:objectName() and not player:isKongcheng() then num = num + 1 end end end return num end local duwu_skill = {} duwu_skill.name = "duwu" table.insert(sgs.ai_skills, duwu_skill) duwu_skill.getTurnUseCard = function(self, inclusive) if self.player:hasFlag("DuwuEnterDying") or #self.enemies == 0 then return end return sgs.Card_Parse("@DuwuCard=.") end sgs.ai_skill_use_func.DuwuCard = function(card, use, self) local cmp = function(a, b) if a:getHp() < b:getHp() then if a:getHp() == 1 and b:getHp() == 2 then return false else return true end end return false end local enemies = {} for _, enemy in ipairs(self.enemies) do if self:canAttack(enemy, self.player) and self.player:inMyAttackRange(enemy) then table.insert(enemies, enemy) end end if #enemies == 0 then return end table.sort(enemies, cmp) if enemies[1]:getHp() <= 0 then use.card = sgs.Card_Parse("@DuwuCard=.") if use.to then use.to:append(enemies[1]) end return end -- find cards local card_ids = {} if self:needToThrowArmor() then table.insert(card_ids, self.player:getArmor():getEffectiveId()) end local zcards = self.player:getHandcards() local use_slash, keep_jink, keep_analeptic = false, false, false for _, zcard in sgs.qlist(zcards) do if not isCard("Peach", zcard, self.player) and not isCard("ExNihilo", zcard, self.player) then local shouldUse = true if zcard:getTypeId() == sgs.Card_TypeTrick then local dummy_use = { isDummy = true } self:useTrickCard(zcard, dummy_use) if dummy_use.card then shouldUse = false end end if zcard:getTypeId() == sgs.Card_TypeEquip and not self.player:hasEquip(zcard) then local dummy_use = { isDummy = true } self:useEquipCard(zcard, dummy_use) if dummy_use.card then shouldUse = false end end if isCard("Jink", zcard, self.player) and not keep_jink then keep_jink = true shouldUse = false end if self.player:getHp() == 1 and isCard("Analeptic", zcard, self.player) and not keep_analeptic then keep_analeptic = true shouldUse = false end if shouldUse then table.insert(card_ids, zcard:getId()) end end end local hc_num = #card_ids local eq_num = 0 if self.player:getOffensiveHorse() then table.insert(card_ids, self.player:getOffensiveHorse():getEffectiveId()) eq_num = eq_num + 1 end if self.player:getWeapon() and self:evaluateWeapon(self.player:getWeapon()) < 5 then table.insert(card_ids, self.player:getWeapon():getEffectiveId()) eq_num = eq_num + 2 end local function getRangefix(index) if index <= hc_num then return 0 elseif index == hc_num + 1 then if eq_num == 2 then return sgs.weapon_range[self.player:getWeapon():getClassName()] - self.player:getAttackRange(false) else return 1 end elseif index == hc_num + 2 then return sgs.weapon_range[self.player:getWeapon():getClassName()] end end for _, enemy in ipairs(enemies) do if enemy:getHp() > #card_ids then continue end if enemy:getHp() <= 0 then use.card = sgs.Card_Parse("@DuwuCard=.") if use.to then use.to:append(enemy) end return elseif enemy:getHp() > 1 then local hp_ids = {} if self.player:distanceTo(enemy, getRangefix(enemy:getHp())) <= self.player:getAttackRange() then for _, id in ipairs(card_ids) do table.insert(hp_ids, id) if #hp_ids == enemy:getHp() then break end end use.card = sgs.Card_Parse("@DuwuCard=" .. table.concat(hp_ids, "+")) if use.to then use.to:append(enemy) end return end else if not self:isWeak() or self:getSaveNum(true) >= 1 then if self.player:distanceTo(enemy, getRangefix(1)) <= self.player:getAttackRange() then use.card = sgs.Card_Parse("@DuwuCard=" .. card_ids[1]) if use.to then use.to:append(enemy) end return end end end end end sgs.ai_use_priority.DuwuCard = 0.6 sgs.ai_use_value.DuwuCard = 2.45 sgs.dynamic_value.damage_card.DuwuCard = true sgs.ai_card_intention.DuwuCard = 80 function getNextJudgeReason(self, player) if self:playerGetRound(player) > 2 then if player:hasSkills("ganglie|vsganglie") then return end local caiwenji = self.room:findPlayerBySkillName("beige") if caiwenji and caiwenji:canDiscard(caiwenji, "he") and self:isFriend(caiwenji, player) then return end if player:hasArmorEffect("eight_diagram") or player:hasSkill("bazhen") then if self:playerGetRound(player) > 3 and self:isEnemy(player) then return "EightDiagram" else return end end end if self:isFriend(player) and player:hasSkill("luoshen") then return "luoshen" end if not player:getJudgingArea():isEmpty() and not player:containsTrick("YanxiaoCard") then return player:getJudgingArea():last():objectName() end if player:hasSkill("qianxi") then return "qianxi" end if player:hasSkill("nosmiji") and player:getLostHp() > 0 then return "nosmiji" end if player:hasSkill("tuntian") then return "tuntian" end if player:hasSkill("tieji") then return "tieji" end if player:hasSkill("nosqianxi") then return "nosqianxi" end if player:hasSkill("caizhaoji_hujia") then return "caizhaoji_hujia" end end local zhoufu_skill = {} zhoufu_skill.name = "zhoufu" table.insert(sgs.ai_skills, zhoufu_skill) zhoufu_skill.getTurnUseCard = function(self) if self.player:hasUsed("ZhoufuCard") or self.player:isKongcheng() then return end return sgs.Card_Parse("@ZhoufuCard=.") end sgs.ai_skill_use_func.ZhoufuCard = function(card, use, self) local cards = {} for _, card in sgs.qlist(self.player:getHandcards()) do table.insert(cards, sgs.Sanguosha:getEngineCard(card:getEffectiveId())) end self:sortByKeepValue(cards) self:sort(self.friends_noself) local zhenji for _, friend in ipairs(self.friends_noself) do if friend:getPile("incantation"):length() > 0 then continue end local reason = getNextJudgeReason(self, friend) if reason then if reason == "luoshen" then zhenji = friend elseif reason == "indulgence" then for _, card in ipairs(cards) do if card:getSuit() == sgs.Card_Heart or (friend:hasSkill("hongyan") and card:getSuit() == sgs.Card_Spade) and (friend:hasSkill("tiandu") or not self:isValuableCard(card)) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(friend) end return end end elseif reason == "supply_shortage" then for _, card in ipairs(cards) do if card:getSuit() == sgs.Card_Club and (friend:hasSkill("tiandu") or not self:isValuableCard(card)) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(friend) end return end end elseif reason == "lightning" and not friend:hasSkills("hongyan|wuyan") then for _, card in ipairs(cards) do if (card:getSuit() ~= sgs.Card_Spade or card:getNumber() == 1 or card:getNumber() > 9) and (friend:hasSkill("tiandu") or not self:isValuableCard(card)) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(friend) end return end end elseif reason == "nosmiji" then for _, card in ipairs(cards) do if card:getSuit() == sgs.Card_Club or (card:getSuit() == sgs.Card_Spade and not friend:hasSkill("hongyan")) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(friend) end return end end elseif reason == "nosqianxi" or reason == "tuntian" then for _, card in ipairs(cards) do if (card:getSuit() ~= sgs.Card_Heart and not (card:getSuit() == sgs.Card_Spade and friend:hasSkill("hongyan"))) and (friend:hasSkill("tiandu") or not self:isValuableCard(card)) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(friend) end return end end elseif reason == "tieji" or reason == "caizhaoji_hujia" then for _, card in ipairs(cards) do if (card:isRed() or card:getSuit() == sgs.Card_Spade and friend:hasSkill("hongyan")) and (friend:hasSkill("tiandu") or not self:isValuableCard(card)) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(friend) end return end end end end end if zhenji then for _, card in ipairs(cards) do if card:isBlack() and not (zhenji:hasSkill("hongyan") and card:getSuit() == sgs.Card_Spade) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(zhenji) end return end end end self:sort(self.enemies) for _, enemy in ipairs(self.enemies) do if enemy:getPile("incantation"):length() > 0 then continue end local reason = getNextJudgeReason(self, enemy) if not enemy:hasSkill("tiandu") and reason then if reason == "indulgence" then for _, card in ipairs(cards) do if not (card:getSuit() == sgs.Card_Heart or (enemy:hasSkill("hongyan") and card:getSuit() == sgs.Card_Spade)) and not self:isValuableCard(card) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(enemy) end return end end elseif reason == "supply_shortage" then for _, card in ipairs(cards) do if card:getSuit() ~= sgs.Card_Club and not self:isValuableCard(card) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(enemy) end return end end elseif reason == "lightning" and not enemy:hasSkills("hongyan|wuyan") then for _, card in ipairs(cards) do if card:getSuit() == sgs.Card_Spade and card:getNumber() >= 2 and card:getNumber() <= 9 then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(enemy) end return end end elseif reason == "nosmiji" then for _, card in ipairs(cards) do if card:isRed() or card:getSuit() == sgs.Card_Spade and enemy:hasSkill("hongyan") then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(enemy) end return end end elseif reason == "nosqianxi" or reason == "tuntian" then for _, card in ipairs(cards) do if (card:getSuit() == sgs.Card_Heart or card:getSuit() == sgs.Card_Spade and enemy:hasSkill("hongyan")) and not self:isValuableCard(card) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(enemy) end return end end elseif reason == "tieji" or reason == "caizhaoji_hujia" then for _, card in ipairs(cards) do if (card:getSuit() == sgs.Card_Club or (card:getSuit() == sgs.Card_Spade and not enemy:hasSkill("hongyan"))) and not self:isValuableCard(card) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(enemy) end return end end end end end local has_indulgence, has_supplyshortage local friend for _, p in ipairs(self.friends) do if getKnownCard(p, self.player, "Indulgence", true, "he") > 0 then has_indulgence = true friend = p break end if getKnownCard(p, self.player, "SupplySortage", true, "he") > 0 then has_supplyshortage = true friend = p break end end if has_indulgence then local indulgence = sgs.Sanguosha:cloneCard("indulgence") for _, enemy in ipairs(self.enemies) do if enemy:getPile("incantation"):length() > 0 then continue end if self:hasTrickEffective(indulgence, enemy, friend) and self:playerGetRound(friend) < self:playerGetRound(enemy) and not self:willSkipPlayPhase(enemy) then for _, card in ipairs(cards) do if not (card:getSuit() == sgs.Card_Heart or (enemy:hasSkill("hongyan") and card:getSuit() == sgs.Card_Spade)) and not self:isValuableCard(card) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(enemy) end return end end end end elseif has_supplyshortage then local supplyshortage = sgs.Sanguosha:cloneCard("supply_shortage") local distance = self:getDistanceLimit(supplyshortage, friend) for _, enemy in ipairs(self.enemies) do if enemy:getPile("incantation"):length() > 0 then continue end if self:hasTrickEffective(supplyshortage, enemy, friend) and self:playerGetRound(friend) < self:playerGetRound(enemy) and not self:willSkipDrawPhase(enemy) and friend:distanceTo(enemy) <= distance then for _, card in ipairs(cards) do if card:getSuit() ~= sgs.Card_Club and not self:isValuableCard(card) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(enemy) end return end end end end end for _, target in sgs.qlist(self.room:getOtherPlayers(self.player)) do if target:getPile("incantation"):length() > 0 then continue end if self:hasEightDiagramEffect(target) then for _, card in ipairs(cards) do if (card:isRed() and self:isFriend(target)) or (card:isBlack() and self:isEnemy(target)) and not self:isValuableCard(card) then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(target) end return end end end end if self:getOverflow() > 0 then for _, target in sgs.qlist(self.room:getOtherPlayers(self.player)) do if target:getPile("incantation"):length() > 0 then continue end for _, card in ipairs(cards) do if not self:isValuableCard(card) and math.random() > 0.5 then use.card = sgs.Card_Parse("@ZhoufuCard=" .. card:getEffectiveId()) if use.to then use.to:append(target) end return end end end end end sgs.ai_card_intention.ZhoufuCard = 0 sgs.ai_use_value.ZhoufuCard = 2 sgs.ai_use_priority.ZhoufuCard = sgs.ai_use_priority.Indulgence - 0.1 local function getKangkaiCard(self, target, data) local use = data:toCardUse() local weapon, armor, def_horse, off_horse = {}, {}, {}, {} for _, card in sgs.qlist(self.player:getHandcards()) do if card:isKindOf("Weapon") then table.insert(weapon, card) elseif card:isKindOf("Armor") then table.insert(armor, card) elseif card:isKindOf("DefensiveHorse") then table.insert(def_horse, card) elseif card:isKindOf("OffensiveHorse") then table.insert(off_horse, card) end end if #armor > 0 then for _, card in ipairs(armor) do if ((not target:getArmor() and not target:hasSkills("bazhen|yizhong")) or (target:getArmor() and self:evaluateArmor(card, target) >= self:evaluateArmor(target:getArmor(), target))) and not (card:isKindOf("Vine") and use.card:isKindOf("FireSlash") and self:slashIsEffective(use.card, target, use.from)) then return card:getEffectiveId() end end end if self:needToThrowArmor() and ((not target:getArmor() and not target:hasSkills("bazhen|yizhong")) or (target:getArmor() and self:evaluateArmor(self.player:getArmor(), target) >= self:evaluateArmor(target:getArmor(), target))) and not (self.player:getArmor():isKindOf("Vine") and use.card:isKindOf("FireSlash") and self:slashIsEffective(use.card, target, use.from)) then return self.player:getArmor():getEffectiveId() end if #def_horse > 0 then return def_horse[1]:getEffectiveId() end if #weapon > 0 then for _, card in ipairs(weapon) do if not target:getWeapon() or (self:evaluateArmor(card, target) >= self:evaluateArmor(target:getWeapon(), target)) then return card:getEffectiveId() end end end if self.player:getWeapon() and self:evaluateWeapon(self.player:getWeapon()) < 5 and (not target:getArmor() or (self:evaluateArmor(self.player:getWeapon(), target) >= self:evaluateArmor(target:getWeapon(), target))) then return self.player:getWeapon():getEffectiveId() end if #off_horse > 0 then return off_horse[1]:getEffectiveId() end if self.player:getOffensiveHorse() and ((self.player:getWeapon() and not self.player:getWeapon():isKindOf("Crossbow")) or self.player:hasSkills("mashu|tuntian")) then return self.player:getOffensiveHorse():getEffectiveId() end end sgs.ai_skill_invoke.kangkai = function(self, data) self.kangkai_give_id = nil if hasManjuanEffect(self.player) then return false end local target = data:toPlayer() if not target then return false end if target:objectName() == self.player:objectName() then return true elseif not self:isFriend(target) then return hasManjuanEffect(target) else local id = getKangkaiCard(self, target, self.player:getTag("KangkaiSlash")) if id then return true else return not self:needKongcheng(target, true) end end end sgs.ai_skill_cardask["@kangkai_give"] = function(self, data, pattern, target) if self:isFriend(target) then local id = getKangkaiCard(self, target, data) if id then return "$" .. id end if self:getCardsNum("Jink") > 1 then for _, card in sgs.qlist(self.player:getHandcards()) do if isCard("Jink", card, target) then return "$" .. card:getEffectiveId() end end end for _, card in sgs.qlist(self.player:getHandcards()) do if not self:isValuableCard(card) then return "$" .. card:getEffectiveId() end end else local to_discard = self:askForDiscard("dummyreason", 1, 1, false, true) if #to_discard > 0 then return "$" .. to_discard[1] end end end sgs.ai_skill_invoke.kangkai_use = function(self, data) local use = self.player:getTag("KangkaiSlash"):toCardUse() local card = self.player:getTag("KangkaiCard"):toCard() if not use.card or not card then return false end if card:isKindOf("Vine") and use.card:isKindOf("FireSlash") and self:slashIsEffective(use.card, self.player, use.from) then return false end if ((card:isKindOf("DefensiveHorse") and self.player:getDefensiveHorse()) or (card:isKindOf("OffensiveHorse") and (self.player:getOffensiveHorse() or (self.player:hasSkill("drmashu") and self.player:getDefensiveHorse())))) and not self.player:hasSkills(sgs.lose_equip_skill) then return false end if card:isKindOf("Armor") and ((self.player:hasSkills("bazhen|yizhong") and not self.player:getArmor()) or (self.player:getArmor() and self:evaluateArmor(card) < self:evaluateArmor(self.player:getArmor()))) then return false end if card:isKindOf("Weanpon") and (self.player:getWeapon() and self:evaluateArmor(card) < self:evaluateArmor(self.player:getWeapon())) then return false end return true end sgs.ai_skill_use["@@qingyi"] = function(self, prompt) local card_str = sgs.ai_skill_use["@@shensu1"](self, "@shensu1") return string.gsub(card_str, "ShensuCard", "QingyiCard") end --星彩 sgs.ai_skill_invoke.shenxian = sgs.ai_skill_invoke.luoying local qiangwu_skill = {} qiangwu_skill.name = "qiangwu" table.insert(sgs.ai_skills, qiangwu_skill) qiangwu_skill.getTurnUseCard = function(self) if self.player:hasUsed("QiangwuCard") then return end return sgs.Card_Parse("@QiangwuCard=.") end sgs.ai_skill_use_func.QiangwuCard = function(card, use, self) if self.player:hasUsed("QiangwuCard") then return end use.card = card end sgs.ai_use_value.QiangwuCard = 3 sgs.ai_use_priority.QiangwuCard = 11 --祖茂 sgs.ai_skill_use["@@yinbing"] = function(self, prompt) --手牌 local otherNum = self.player:getHandcardNum() - self:getCardsNum("BasicCard") if otherNum == 0 then return "." end local slashNum = self:getCardsNum("Slash") local jinkNum = self:getCardsNum("Jink") local enemyNum = #self.enemies local friendNum = #self.friends local value = 0 if otherNum > 1 then value = value + 0.3 end for _,card in sgs.qlist(self.player:getHandcards()) do if card:isKindOf("EquipCard") then value = value + 1 end end if otherNum == 1 and self:getCardsNum("Nullification") == 1 then value = value - 0.2 end --已有引兵 if self.player:getPile("yinbing"):length() > 0 then value = value + 0.2 end --双将【空城】 if self:needKongcheng() and self.player:getHandcardNum() == 1 then value = value + 3 end if enemyNum == 1 then value = value + 0.7 end if friendNum - enemyNum > 0 then value = value + 0.2 else value = value - 0.3 end local slash = sgs.Sanguosha:cloneCard("slash") --关于 【杀】和【决斗】 if slashNum == 0 then value = value - 0.1 end if jinkNum == 0 then value = value - 0.5 end if jinkNum == 1 then value = value + 0.2 end if jinkNum > 1 then value = value + 0.5 end if self.player:getArmor() and self.player:getArmor():isKindOf("EightDiagram") then value = value + 0.4 end for _,enemy in ipairs(self.enemies) do if enemy:canSlash(self.player, slash) and self:slashIsEffective(slash, self.player, enemy) and (enemy:inMyAttackRange(self.player) or enemy:hasSkills("zhuhai|shensu")) then if ((enemy:getWeapon() and enemy:getWeapon():isKindOf("Crossbow")) or enemy:hasSkills("paoxiao|tianyi|xianzhen|jiangchi|fuhun|gongqi|longyin|qiangwu")) and enemy:getHandcardNum() > 1 then value = value - 0.2 end if enemy:hasSkills("tieqi|wushuang|yijue|liegong|mengjin|qianxi") then value = value - 0.2 end value = value - 0.2 end if enemy:hasSkills("lijian|shuangxiong|mingce|mizhao") then value = value - 0.2 end end --肉盾 local yuanshu = self.room:findPlayerBySkillName("tongji") if yuanshu and yuanshu:getHandcardNum() > yuanshu:getHp() then value = value + 0.4 end for _,friend in ipairs(self.friends) do if friend:hasSkills("fangquan|zhenwei|kangkai") then value = value + 0.4 end end if value < 0 then return "." end local card_ids = {} local nulId for _,card in sgs.qlist(self.player:getHandcards()) do if not card:isKindOf("BasicCard") then if card:isKindOf("Nullification") then nulId = card:getEffectiveId() else table.insert(card_ids, card:getEffectiveId()) end end end if nulId and #card_ids == 0 then table.insert(card_ids, nulId) end return "@YinbingCard=" .. table.concat(card_ids, "+") .. "->." end sgs.yinbing_keep_value = { EquipCard = 5, TrickCard = 4 } sgs.ai_skill_invoke.juedi = function(self, data) for _, friend in ipairs(self.friends_noself) do if friend:getLostHp() > 0 then return true end end if self:isWeak() then return true end return false end sgs.ai_skill_playerchosen.juedi = function(self, targets) targets = sgs.QList2Table(targets) self:sort(targets, "defense") for _,p in ipairs(targets) do if self:isFriend(p) then return p end end return end sgs.ai_skill_invoke.meibu = function (self, data) local target = self.room:getCurrent() if self:isFriend(target) then --锦囊不如杀重要的情况 local trick = sgs.Sanguosha:cloneCard("nullification") if target:hasSkill("wumou") or target:isJilei(trick) then return true end local slash = sgs.Sanguosha:cloneCard("Slash") dummy_use = {isDummy = true, from = target, to = sgs.SPlayerList()} self:useBasicCard(slash, dummy_use) if target:getWeapon() and target:getWeapon():isKindOf("Crossbow") and not dummy_use.to:isEmpty() then return true end if target:hasSkills("paoxiao|tianyi|xianzhen|jiangchi|fuhun|qiangwu") and not self:isWeak(target) and not dummy_use.to:isEmpty() then return true end else local slash2 = sgs.Sanguosha:cloneCard("Slash") if target:isJilei(slash2) then return true end if target:getWeapon() and target:getWeapon():isKindOf("blade") then return false end if target:hasSkills("paoxiao|tianyi|xianzhen|jiangchi|fuhun|qiangwu") or (target:getWeapon() and target:getWeapon():isKindOf("Crossbow")) then return false end if target:hasSkills("wumou|gongqi") then return false end if target:hasSkills("guose|qixi|duanliang|luanji") and target:getHandcardNum() > 1 then return true end if target:hasSkills("shuangxiong") and not self:isWeak(target) then return true end if not self:slashIsEffective(slash2, self.player, target) and not self:isWeak() then return true end if self.player:getArmor() and self.player:getArmor():isKindOf("Vine") and not self:isWeak() then return true end if self.player:getArmor() and not self:isWeak() and self:getCardsNum("Jink") > 0 then return true end end return false end sgs.ai_skill_choice.mumu = function(self, choices) local armorPlayersF = {} local weaponPlayersE = {} local armorPlayersE = {} for _,p in ipairs(self.friends_noself) do if p:getArmor() and p:objectName() ~= self.player:objectName() then table.insert(armorPlayersF, p) end end for _,p in ipairs(self.enemies) do if p:getWeapon() and self.player:canDiscard(p, p:getWeapon():getEffectiveId()) then table.insert(weaponPlayersE, p) end if p:getArmor() and p:objectName() ~= self.player:objectName() then table.insert(armorPlayersE, p) end end self.player:setFlags("mumu_armor") if #armorPlayersF > 0 then for _,friend in ipairs(armorPlayersF) do if (friend:getArmor():isKindOf("Vine") and not self.player:getArmor() and not friend:hasSkills("kongcheng|zhiji")) or (friend:getArmor():isKindOf("SilverLion") and friend:getLostHp() > 0) then return "armor" end end end if #armorPlayersE > 0 then if not self.player:getArmor() then return "armor" end if self.player:getArmor() and self.player:getArmor():isKindOf("SilverLion") and self.player:getLostHp() > 0 then return "armor" end for _,enemy in ipairs(armorPlayersE) do if enemy:getArmor():isKindOf("Vine") or self:isWeak(enemy) then return "armor" end end end self.player:setFlags("-mumu_armor") if #weaponPlayersE > 0 then return "weapon" end self.player:setFlags("mumu_armor") if #armorPlayersE > 0 then for _,enemy in ipairs(armorPlayersE) do if not enemy:getArmor():isKindOf("SilverLion") and enemy:getLostHp() > 0 then return "armor" end end end self.player:setFlags("-mumu_armor") return "cancel" end sgs.ai_skill_playerchosen.mumu = function(self, targets) if self.player:hasFlag("mumu_armor") then for _,target in sgs.qlist(targets) do if self:isFriend(target) and target:getArmor():isKindOf("SilverLion") and target:getLostHp() > 0 then return target end if self:isEnemy(target) and target:getArmor():isKindOf("SilverLion") and target:getLostHp() == 0 then return target end end for _,target in sgs.qlist(targets) do if self:isEnemy(target) and (self:isWeak(target) or target:getArmor():isKindOf("Vine")) then return target end end for _,target in sgs.qlist(targets) do if self:isEnemy(target) then return target end end else for _,target in sgs.qlist(targets) do if self:isEnemy(target) and target:hasSkills("liegong|qiangxi|jijiu|guidao|anjian") then return target end end for _,target in sgs.qlist(targets) do if self:isEnemy(target) then return target end end end return targets:at(0) end --马良 local xiemu_skill = {} xiemu_skill.name = "xiemu" table.insert(sgs.ai_skills, xiemu_skill) xiemu_skill.getTurnUseCard = function(self) if self.player:hasUsed("XiemuCard") then return end if self:getCardsNum("Slash") == 0 then return end local kingdomDistribute = {} kingdomDistribute["wei"] = 0; kingdomDistribute["shu"] = 0; kingdomDistribute["wu"] = 0; kingdomDistribute["qun"] = 0; for _,p in sgs.qlist(self.room:getAlivePlayers()) do if kingdomDistribute[p:getKingdom()] and self:isEnemy(p) and p:inMyAttackRange(self.player) then kingdomDistribute[p:getKingdom()] = kingdomDistribute[p:getKingdom()] + 1 else kingdomDistribute[p:getKingdom()] = kingdomDistribute[p:getKingdom()] + 0.2 end if p:hasSkill("luanji") and p:getHandcardNum() > 2 then kingdomDistribute["qun"] = kingdomDistribute["qun"] + 3 end if p:hasSkill("qixi") and self:isEnemy(p) and p:getHandcardNum() > 2 then kingdomDistribute["wu"] = kingdomDistribute["wu"] + 2 end if p:hasSkill("zaoxian") and self:isEnemy(p) and p:getPile("field"):length() > 1 then kingdomDistribute["wei"] = kingdomDistribute["wei"] + 2 end end maxK = "wei" if kingdomDistribute["shu"] > kingdomDistribute[maxK] then maxK = "shu" end if kingdomDistribute["wu"] > kingdomDistribute[maxK] then maxK = "wu" end if kingdomDistribute["qun"] > kingdomDistribute[maxK] then maxK = "qun" end if kingdomDistribute[maxK] + self:getCardsNum("Slash") < 4 then return end local newData = sgs.QVariant(maxK) self.room:setTag("xiemu_choice", newData) local subcard for _,c in sgs.qlist(self.player:getHandcards()) do if c:isKindOf("Slash") then subcard = c end end if not subcard then return end return sgs.Card_Parse("@XiemuCard=" .. subcard:getEffectiveId()) end sgs.ai_skill_use_func.XiemuCard = function(card, use, self) if self.player:hasUsed("XiemuCard") then return end use.card = card end sgs.ai_skill_choice.xiemu = function(self, choices) local choice = self.room:getTag("xiemu_choice"):toString() self.room:setTag("xiemu_choice", sgs.QVariant()) return choice end sgs.ai_use_value.XiemuCard = 5 sgs.ai_use_priority.XiemuCard = 10 sgs.ai_skill_invoke.naman = function(self, data) if self:needKongcheng(self.player, true) and self.player:getHandcardNum() == 0 then return false end return true end --chengyi --黄巾雷使 sgs.ai_view_as.fulu = function(card, player, card_place) local suit = card:getSuitString() local number = card:getNumberString() local card_id = card:getEffectiveId() if card_place ~= sgs.Player_PlaceSpecial and card:getClassName() == "Slash" and not card:hasFlag("using") then return ("thunder_slash:fulu[%s:%s]=%d"):format(suit, number, card_id) end end sgs.ai_skill_invoke.fulu = function(self, data) local use = data:toCardUse() for _, player in sgs.qlist(use.to) do if self:isEnemy(player) and self:damageIsEffective(player, sgs.DamageStruct_Thunder) and sgs.isGoodTarget(player, self.enemies, self) then return true end end return false end local fulu_skill = {} fulu_skill.name = "fulu" table.insert(sgs.ai_skills, fulu_skill) fulu_skill.getTurnUseCard = function(self, inclusive) local cards = self.player:getCards("h") cards = sgs.QList2Table(cards) local slash self:sortByUseValue(cards, true) for _, card in ipairs(cards) do if card:getClassName() == "Slash" then slash = card break end end if not slash then return nil end local dummy_use = { to = sgs.SPlayerList(), isDummy = true } self:useCardThunderSlash(slash, dummy_use) if dummy_use.card and dummy_use.to:length() > 0 then local use = sgs.CardUseStruct() use.from = self.player use.to = dummy_use.to use.card = slash local data = sgs.QVariant() data:setValue(use) if not sgs.ai_skill_invoke.fulu(self, data) then return nil end else return nil end if slash then local suit = slash:getSuitString() local number = slash:getNumberString() local card_id = slash:getEffectiveId() local card_str = ("thunder_slash:fulu[%s:%s]=%d"):format(suit, number, card_id) local mySlash = sgs.Card_Parse(card_str) assert(mySlash) return mySlash end end sgs.ai_skill_invoke.zhuji = function(self, data) local damage = data:toDamage() if self:isFriend(damage.from) and not self:isFriend(damage.to) then return true end return false end --文聘 sgs.ai_skill_cardask["@sp_zhenwei"] = function(self, data) local use = data:toCardUse() if use.to:length() ~= 1 or not use.from or not use.card then return "." end if not self:isFriend(use.to:at(0)) or self:isFriend(use.from) then return "." end if use.to:at(0):hasSkills("liuli|tianxiang") and use.card:isKindOf("Slash") and use.to:at(0):getHandcardNum() > 1 then return "." end if use.card:isKindOf("Slash") and not self:slashIsEffective(use.card, use.to:at(0), use.from) then return "." end if use.to:at(0):hasSkills(sgs.masochism_skill) and not self:isWeak(use.to:at(0)) then return "." end if self.player:getHandcardNum() + self.player:getEquips():length() < 2 and not self:isWeak(use.to:at(0)) then return "." end local to_discard = self:askForDiscard("sp_zhenwei", 1, 1, false, true) if #to_discard > 0 then if not (use.card:isKindOf("Slash") and self:isWeak(use.to:at(0))) and sgs.Sanguosha:getCard(to_discard[1]):isKindOf("Peach") then return "." end return "$" .. to_discard[1] else return "." end end sgs.ai_skill_choice.spzhenwei = function(self, choices, data) local use = data:toCardUse() if self:isWeak() or self.player:getHandcardNum() < 2 then return "null" end if use.card:isKindOf("TrickCard") and use.from:hasSkill("jizhi") then return "draw" end if use.card:isKindOf("Slash") and (use.from:hasSkills("paoxiao|tianyi|xianzhen|jiangchi|fuhun|qiangwu") or (use.from:getWeapon() and use.from:getWeapon():isKindOf("Crossbow"))) and self:getCardsNum("Jink") == 0 then return "null" end if use.card:isKindOf("SupplyShortage") then return "null" end if use.card:isKindOf("Slash") and self:getCardsNum("Jink") == 0 and self.player:getLostHp() > 0 then return "null" end if use.card:isKindOf("Indulgence") and self.player:getHandcardNum() + 1 > self.player:getHp() then return "null" end if use.card:isKindOf("Slash") and use.from:hasSkills("tieqi|wushuang|yijue|liegong|mengjin|qianxi") and not (use.from:getWeapon() and use.from:getWeapon():isKindOf("Crossbow")) then return "null" end return "draw" end --司马朗 local quji_skill = {} quji_skill.name = "quji" table.insert(sgs.ai_skills, quji_skill) quji_skill.getTurnUseCard = function(self) if self.player:getHandcardNum() < self.player:getLostHp() then return nil end if self.player:usedTimes("QujiCard") > 0 then return nil end if self.player:getLostHp() == 0 then return end local cards = self.player:getHandcards() cards = sgs.QList2Table(cards) local arr1, arr2 = self:getWoundedFriend(false, true) if #arr1 + #arr2 < self.player:getLostHp() then return end local compare_func = function(a, b) local v1 = self:getKeepValue(a) + ( a:isBlack() and 50 or 0 ) + ( a:isKindOf("Peach") and 50 or 0 ) local v2 = self:getKeepValue(b) + ( b:isBlack() and 50 or 0 ) + ( b:isKindOf("Peach") and 50 or 0 ) return v1 < v2 end table.sort(cards, compare_func) if cards[1]:isBlack() and self.player:getLostHp() > 0 then return end if self.player:getLostHp() == 2 and (cards[1]:isBlack() or cards[2]:isBlack()) then return end local card_str = "@QujiCard="..cards[1]:getId() local left = self.player:getLostHp() - 1 while left > 0 do card_str = card_str.."+"..cards[self.player:getLostHp() + 1 - left]:getId() left = left - 1 end return sgs.Card_Parse(card_str) end sgs.ai_skill_use_func.QujiCard = function(card, use, self) local arr1, arr2 = self:getWoundedFriend(false, true) local target = nil local num = self.player:getLostHp() for num = 1, self.player:getLostHp() do if #arr1 > num - 1 and (self:isWeak(arr1[num]) or self:getOverflow() >= 1) and arr1[num]:getHp() < getBestHp(arr1[num]) then target = arr1[num] end if target then if use.to then use.to:append(target) end else break end end if num < self.player:getLostHp() then if #arr2 > 0 then for _, friend in ipairs(arr2) do if not friend:hasSkills("hunzi|longhun") then if use.to then use.to:append(friend) num = num + 1 if num == self.player:getLostHp() then break end end end end end end use.card = card return end sgs.ai_use_priority.QujiCard = 4.2 sgs.ai_card_intention.QujiCard = -100 sgs.dynamic_value.benefit.QujiCard = true sgs.quji_suit_value = { heart = 6, diamond = 6 } sgs.ai_cardneed.quji = function(to, card) return card:isRed() end sgs.ai_skill_invoke.junbing = function(self, data) local simalang = self.room:findPlayerBySkillName("junbing") if self:isFriend(simalang) then return true end return false end --孙皓 sgs.ai_skill_invoke.canshi = function(self, data) local n = 0 for _, p in sgs.qlist(self.room:getAlivePlayers()) do if p:isWounded() or (self.player:hasSkill("guiming") and self.player:isLord() and p:getKingdom() == "wu" and self.player:objectName() ~= p:objectName()) then n = n + 1 end end if n <= 2 then return false end if n == 3 and (not self:isWeak() or self:willSkipPlayPhase()) then return true end if n > 3 then return true end return false end sgs.ai_card_intention.QingyiCard = sgs.ai_card_intention.Slash --OL专属-- --李丰 --屯储 --player->askForSkillInvoke("tunchu") sgs.ai_skill_invoke["tunchu"] = function(self, data) if #self.enemies == 0 then return true end local callback = sgs.ai_skill_choice.jiangchi local choice = callback(self, "jiang+chi+cancel") if choice == "jiang" then return true end for _, friend in ipairs(self.friends_noself) do if (friend:getHandcardNum() < 2 or (friend:hasSkill("rende") and friend:getHandcardNum() < 3)) and choice == "cancel" then return true end end return false end --room->askForExchange(player, "tunchu", 1, 1, false, "@tunchu-put") --输粮 --room->askForUseCard(p, "@@shuliang", "@shuliang", -1, Card::MethodNone) sgs.ai_skill_use["@@shuliang"] = function(self, prompt, method) local target = self.room:getCurrent() if target and self:isFriend(target) then return "@ShuliangCard=" .. self.player:getPile("food"):first() end return "." end --朱灵 --战意 --ZhanyiCard:Play --ZhanyiViewAsBasicCard:Response --ZhanyiViewAsBasicCard:Play --room->askForDiscard(p, "zhanyi_equip", 2, 2, false, true, "@zhanyiequip_discard") --room->askForChoice(zhuling, "zhanyi_slash", guhuo_list.join("+")) --room->askForChoice(zhuling, "zhanyi_saveself", guhuo_list.join("+")) local zhanyi_skill = {} zhanyi_skill.name = "zhanyi" table.insert(sgs.ai_skills, zhanyi_skill) zhanyi_skill.getTurnUseCard = function(self) if not self.player:hasUsed("ZhanyiCard") then return sgs.Card_Parse("@ZhanyiCard=.") end if self.player:getMark("ViewAsSkill_zhanyiEffect") > 0 then local use_basic = self:ZhanyiUseBasic() local cards = self.player:getCards("h") cards=sgs.QList2Table(cards) self:sortByUseValue(cards, true) local BasicCards = {} for _, card in ipairs(cards) do if card:isKindOf("BasicCard") then table.insert(BasicCards, card) end end if use_basic and #BasicCards > 0 then return sgs.Card_Parse("@ZhanyiViewAsBasicCard=" .. BasicCards[1]:getId() .. ":"..use_basic) end end end sgs.ai_skill_use_func.ZhanyiCard = function(card, use, self) local to_discard local cards = self.player:getCards("h") cards=sgs.QList2Table(cards) self:sortByUseValue(cards, true) local TrickCards = {} for _, card in ipairs(cards) do if card:isKindOf("Disaster") or card:isKindOf("GodSalvation") or card:isKindOf("AmazingGrace") or self:getCardsNum("TrickCard") > 1 then table.insert(TrickCards, card) end end if #TrickCards > 0 and (self.player:getHp() > 2 or self:getCardsNum("Peach") > 0 ) and self.player:getHp() > 1 then to_discard = TrickCards[1] end local EquipCards = {} if self:needToThrowArmor() and self.player:getArmor() then table.insert(EquipCards,self.player:getArmor()) end for _, card in ipairs(cards) do if card:isKindOf("EquipCard") then table.insert(EquipCards, card) end end if not self:isWeak() and self.player:getDefensiveHorse() then table.insert(EquipCards,self.player:getDefensiveHorse()) end if self.player:hasTreasure("wooden_ox") and self.player:getPile("wooden_ox"):length() == 0 then table.insert(EquipCards,self.player:getTreasure()) end self:sort(self.enemies, "defense") if self:getCardsNum("Slash") > 0 and ((self.player:getHp() > 2 or self:getCardsNum("Peach") > 0 ) and self.player:getHp() > 1) then for _, enemy in ipairs(self.enemies) do if (self:isWeak(enemy)) or (enemy:getCardCount(true) <= 4 and enemy:getCardCount(true) >=1) and self.player:canSlash(enemy) and self:slashIsEffective(sgs.Sanguosha:cloneCard("slash"), enemy, self.player) and self.player:inMyAttackRange(enemy) and not self:needToThrowArmor(enemy) then to_discard = EquipCards[1] break end end end local BasicCards = {} for _, card in ipairs(cards) do if card:isKindOf("BasicCard") then table.insert(BasicCards, card) end end local use_basic = self:ZhanyiUseBasic() if (use_basic == "peach" and self.player:getHp() > 1 and #BasicCards > 3) --or (use_basic == "analeptic" and self.player:getHp() > 1 and #BasicCards > 2) or (use_basic == "slash" and self.player:getHp() > 1 and #BasicCards > 1) then to_discard = BasicCards[1] end if to_discard then use.card = sgs.Card_Parse("@ZhanyiCard=" .. to_discard:getEffectiveId()) return end end sgs.ai_use_priority.ZhanyiCard = 10 sgs.ai_skill_use_func.ZhanyiViewAsBasicCard=function(card,use,self) local userstring=card:toString() userstring=(userstring:split(":"))[3] local zhanyicard=sgs.Sanguosha:cloneCard(userstring, card:getSuit(), card:getNumber()) zhanyicard:setSkillName("zhanyi") if zhanyicard:getTypeId() == sgs.Card_TypeBasic then if not use.isDummy and use.card and zhanyicard:isKindOf("Slash") and (not use.to or use.to:isEmpty()) then return end self:useBasicCard(zhanyicard, use) end if not use.card then return end use.card=card end sgs.ai_use_priority.ZhanyiViewAsBasicCard = 8 function SmartAI:ZhanyiUseBasic() local has_slash = false local has_peach = false --local has_analeptic = false local cards = self.player:getCards("h") cards=sgs.QList2Table(cards) self:sortByUseValue(cards, true) local BasicCards = {} for _, card in ipairs(cards) do if card:isKindOf("BasicCard") then table.insert(BasicCards, card) if card:isKindOf("Slash") then has_slash = true end if card:isKindOf("Peach") then has_peach = true end --if card:isKindOf("Analeptic") then has_analeptic = true end end end if #BasicCards <= 1 then return nil end local ban = table.concat(sgs.Sanguosha:getBanPackages(), "|") self:sort(self.enemies, "defense") for _, enemy in ipairs(self.enemies) do if (self:isWeak(enemy)) and self.player:canSlash(enemy) and self:slashIsEffective(sgs.Sanguosha:cloneCard("slash"), enemy, self.player) and self.player:inMyAttackRange(enemy) then --if not has_analeptic and not ban:match("maneuvering") and self.player:getMark("drank") == 0 --and getKnownCard(enemy, self.player, "Jink") == 0 and #BasicCards > 2 then return "analeptic" end if not has_slash then return "slash" end end end if self:isWeak() and not has_peach then return "peach" end return nil end sgs.ai_skill_choice.zhanyi_saveself = function(self, choices) if self:getCard("Peach") or not self:getCard("Analeptic") then return "peach" else return "analeptic" end end sgs.ai_skill_choice.zhanyi_slash = function(self, choices) return "slash" end --马谡 --散谣 --SanyaoCard:Play local sanyao_skill = { name = "sanyao", getTurnUseCard = function(self, inclusive) if self.player:hasUsed("SanyaoCard") then return nil elseif self.player:canDiscard(self.player, "he") then return sgs.Card_Parse("@SanyaoCard=.") end end, } table.insert(sgs.ai_skills, sanyao_skill) sgs.ai_skill_use_func["SanyaoCard"] = function(card, use, self) local alives = self.room:getAlivePlayers() local max_hp = -1000 for _,p in sgs.qlist(alives) do local hp = p:getHp() if hp > max_hp then max_hp = hp end end local friends, enemies = {}, {} for _,p in sgs.qlist(alives) do if p:getHp() == max_hp then if self:isFriend(p) then table.insert(friends, p) elseif self:isEnemy(p) then table.insert(enemies, p) end end end local target = nil if #enemies > 0 then self:sort(enemies, "hp") for _,enemy in ipairs(enemies) do if self:damageIsEffective(enemy, sgs.DamageStruct_Normal, self.player) then if self:cantbeHurt(enemy, self.player) then elseif self:needToLoseHp(enemy, self.player, false) then elseif self:getDamagedEffects(enemy, self.player, false) then else target = enemy break end end end end if #friends > 0 and not target then self:sort(friends, "hp") friends = sgs.reverse(friends) for _,friend in ipairs(friends) do if self:damageIsEffective(friend, sgs.DamageStruct_Normal, self.player) then if self:needToLoseHp(friend, self.player, false) then elseif friend:getCards("j"):length() > 0 and self.player:hasSkill("zhiman") then elseif self:needToThrowArmor(friend) and self.player:hasSkill("zhiman") then target = friend break end end end end if target then local cost = self:askForDiscard("dummy", 1, 1, false, true) if #cost == 1 then local card_str = "@SanyaoCard="..cost[1] local acard = sgs.Card_Parse(card_str) use.card = acard if use.to then use.to:append(target) end end end end sgs.ai_use_value["SanyaoCard"] = 1.75 sgs.ai_card_intention["SanyaoCard"] = function(self, card, from, tos) local target = tos[1] if getBestHp(target) > target:getHp() then return elseif self:needToLoseHp(target, from, false) then return elseif self:getDamagedEffects(target, from, false) then return end sgs.updateIntention(from, target, 30) end --制蛮 --player->askForSkillInvoke(this, data) sgs.ai_skill_invoke["zhiman"] = sgs.ai_skill_invoke["yishi"] --room->askForCardChosen(player, damage.to, "ej", objectName()) --于禁 --节钺 --room->askForExchange(effect.to, "jieyue", 1, 1, true, QString("@jieyue_put:%1").arg(effect.from->objectName()), true) sgs.ai_skill_discard["jieyue"] = function(self, discard_num, min_num, optional, include_equip) local source = self.room:getCurrent() if source and self:isEnemy(source) then return {} end return self:askForDiscard("dummy", discard_num, min_num, false, include_equip) end --room->askForCardChosen(effect.from, effect.to, "he", objectName(), false, Card::MethodDiscard) --room->askForUseCard(player, "@@jieyue", "@jieyue", -1, Card::MethodDiscard, false) sgs.ai_skill_use["@@jieyue"] = function(self, prompt, method) if self.player:isKongcheng() then return "." elseif #self.enemies == 0 then return "." end local handcards = self.player:getHandcards() handcards = sgs.QList2Table(handcards) self:sortByKeepValue(handcards) local to_use = nil local isWeak = self:isWeak() local isDanger = isWeak and ( self.player:getHp() + self:getAllPeachNum() <= 1 ) for _,card in ipairs(handcards) do if self.player:isJilei(card) then elseif card:isKindOf("Peach") or card:isKindOf("ExNihilo") then elseif isDanger and card:isKindOf("Analeptic") then elseif isWeak and card:isKindOf("Jink") then else to_use = card break end end if not to_use then return "." end if #self.friends_noself > 0 then local has_black, has_red = false, false local need_null, need_jink = false, false for _,card in ipairs(handcards) do if card:getEffectiveId() ~= to_use:getEffectiveId() then if card:isRed() then has_red = true break end end end for _,card in ipairs(handcards) do if card:getEffectiveId() ~= to_use:getEffectiveId() then if card:isBlack() then has_black = true break end end end if has_black then local f_num = self:getCardsNum("Nullification", "he", true) local e_num = 0 for _,friend in ipairs(self.friends_noself) do f_num = f_num + getCardsNum("Nullification", friend, self.player) end for _,enemy in ipairs(self.enemies) do e_num = e_num + getCardsNum("Nullification", enemy, self.player) end if f_num < e_num then need_null = true end end if has_red and not need_null then if self:getCardsNum("Jink", "he", false) == 0 then need_jink = true else for _,friend in ipairs(self.friends_noself) do if getCardsNum("Jink", friend, self.player) == 0 then if friend:hasLordSkill("hujia") and self.player:getKingdom() == "wei" then need_jink = true break elseif friend:hasSkill("lianli") and self.player:isMale() then need_jink = true break end end end end end if need_jink or need_null then self:sort(self.friends_noself, "defense") self.friends_noself = sgs.reverse(self.friends_noself) for _,friend in ipairs(self.friends_noself) do if not friend:isNude() then local card_str = "@JieyueCard="..to_use:getEffectiveId().."->"..friend:objectName() return card_str end end end end local target = self:findPlayerToDiscard("he", false, true) if target then local card_str = "@JieyueCard="..to_use:getEffectiveId().."->"..target:objectName() return card_str end local targets = self:findPlayerToDiscard("he", false, false, nil, true) for _,friend in ipairs(targets) do if not self:isEnemy(friend) then local card_str = "@JieyueCard="..to_use:getEffectiveId().."->"..friend:objectName() return card_str end end return "." end --jieyue:Response sgs.ai_view_as["jieyue"] = function(card, player, card_place, class_name) if not player:getPile("jieyue_pile"):isEmpty() then if card_place == sgs.Player_PlaceHand then local suit = card:getSuitString() local point = card:getNumber() local id = card:getEffectiveId() if class_name == "Jink" and card:isRed() then return string.format("jink:jieyue[%s:%d]=%d", suit, point, id) elseif class_name == "Nullification" and card:isBlack() then return string.format("nullification:jieyue[%s:%d]=%d", suit, point, id) end end end end --刘表 --自守 --player->askForSkillInvoke(this) sgs.ai_skill_invoke["olzishou"] = sgs.ai_skill_invoke["zishou"] sgs.ai_skill_invoke.cv_sunshangxiang = function(self, data) local lord = self.room:getLord() if lord and lord:hasLordSkill("shichou") then return self:isFriend(lord) end return lord:getKingdom() == "shu" end sgs.ai_skill_invoke.cv_caiwenji = function(self, data) local lord = self.room:getLord() if lord and lord:hasLordSkill("xueyi") then return not self:isFriend(lord) end return lord:getKingdom() == "wei" end sgs.ai_skill_invoke.cv_machao = function(self, data) local lord = self.room:getLord() if lord and lord:hasLordSkill("xueyi") and self:isFriend(lord) then sgs.ai_skill_choice.cv_machao = "sp_machao" return true end if lord and lord:hasLordSkill("shichou") and not self:isFriend(lord) then sgs.ai_skill_choice.cv_machao = "sp_machao" return true end if lord and lord:getKingdom() == "qun" and not lord:hasLordSkill("xueyi") then sgs.ai_skill_choice.cv_machao = "sp_machao" return true end if math.random(0, 2) == 0 then sgs.ai_skill_choice.cv_machao = "tw_machao" return true end end sgs.ai_skill_invoke.cv_diaochan = function(self, data) if math.random(0, 2) == 0 then return false elseif math.random(0, 3) == 0 then sgs.ai_skill_choice.cv_diaochan = "tw_diaochan" return true elseif math.random(0, 3) == 0 then sgs.ai_skill_choice.cv_diaochan = "heg_diaochan" return true else sgs.ai_skill_choice.cv_diaochan = "sp_diaochan" return true end end sgs.ai_skill_invoke.cv_pangde = sgs.ai_skill_invoke.cv_caiwenji sgs.ai_skill_invoke.cv_jiaxu = sgs.ai_skill_invoke.cv_caiwenji sgs.ai_skill_invoke.cv_yuanshu = function(self, data) return math.random(0, 2) == 0 end sgs.ai_skill_invoke.cv_zhaoyun = sgs.ai_skill_invoke.cv_yuanshu sgs.ai_skill_invoke.cv_ganning = sgs.ai_skill_invoke.cv_yuanshu sgs.ai_skill_invoke.cv_shenlvbu = sgs.ai_skill_invoke.cv_yuanshu sgs.ai_skill_invoke.cv_daqiao = function(self, data) if math.random(0, 3) >= 1 then return false elseif math.random(0, 4) == 0 then sgs.ai_skill_choice.cv_daqiao = "tw_daqiao" return true else sgs.ai_skill_choice.cv_daqiao = "wz_daqiao" return true end end sgs.ai_skill_invoke.cv_xiaoqiao = function(self, data) if math.random(0, 3) >= 1 then return false elseif math.random(0, 4) == 0 then sgs.ai_skill_choice.cv_xiaoqiao = "wz_xiaoqiao" return true else sgs.ai_skill_choice.cv_xiaoqiao = "heg_xiaoqiao" return true end end sgs.ai_skill_invoke.cv_zhouyu = function(self, data) if math.random(0, 3) >= 1 then return false elseif math.random(0, 4) == 0 then sgs.ai_skill_choice.cv_zhouyu = "heg_zhouyu" return true else sgs.ai_skill_choice.cv_zhouyu = "sp_heg_zhouyu" return true end end sgs.ai_skill_invoke.cv_zhenji = function(self, data) if math.random(0, 3) >= 2 then return false elseif math.random(0, 4) == 0 then sgs.ai_skill_choice.cv_zhenji = "sp_zhenji" return true elseif math.random(0, 4) == 0 then sgs.ai_skill_choice.cv_zhenji = "tw_zhenji" return true else sgs.ai_skill_choice.cv_zhenji = "heg_zhenji" return true end end sgs.ai_skill_invoke.cv_lvbu = function(self, data) if math.random(0, 3) >= 1 then return false elseif math.random(0, 4) == 0 then sgs.ai_skill_choice.cv_lvbu = "tw_lvbu" return true else sgs.ai_skill_choice.cv_lvbu = "heg_lvbu" return true end end sgs.ai_skill_invoke.cv_zhangliao = sgs.ai_skill_invoke.cv_yuanshu sgs.ai_skill_invoke.cv_luxun = sgs.ai_skill_invoke.cv_yuanshu sgs.ai_skill_invoke.cv_huanggai = function(self, data) return math.random(0, 4) == 0 end sgs.ai_skill_invoke.cv_guojia = sgs.ai_skill_invoke.cv_huanggai sgs.ai_skill_invoke.cv_zhugeke = sgs.ai_skill_invoke.cv_huanggai sgs.ai_skill_invoke.cv_yuejin = sgs.ai_skill_invoke.cv_huanggai sgs.ai_skill_invoke.cv_madai = false --@todo: update after adding the avatars sgs.ai_skill_invoke.cv_zhugejin = function(self, data) return math.random(0, 4) > 1 end sgs.ai_skill_invoke.conqueror= function(self, data) local target = data:toPlayer() if self:isFriend(target) and not self:needToThrowArmor(target) then return false end return true end sgs.ai_skill_choice.conqueror = function(self, choices, data) local target = data:toPlayer() if (self:isFriend(target) and not self:needToThrowArmor(target)) or (self:isEnemy(target) and target:getEquips():length() == 0) then return "EquipCard" end local choice = {} table.insert(choice, "EquipCard") table.insert(choice, "TrickCard") table.insert(choice, "BasicCard") if (self:isEnemy(target) and not self:needToThrowArmor(target)) or (self:isFriend(target) and target:getEquips():length() == 0) then table.removeOne(choice, "EquipCard") if #choice == 1 then return choice[1] end end if (self:isEnemy(target) and target:getHandcardNum() < 2) then table.removeOne(choice, "BasicCard") if #choice == 1 then return choice[1] end end if (self:isEnemy(target) and target:getHandcardNum() > 3) then table.removeOne(choice, "TrickCard") if #choice == 1 then return choice[1] end end return choice[math.random(1, #choice)] end sgs.ai_skill_cardask["@conqueror"] = function(self, data) local has_card local cards = sgs.QList2Table(self.player:getCards("he")) self:sortByUseValue(cards, true) for _,cd in ipairs(cards) do if self:getArmor("SilverLion") and card:isKindOf("SilverLion") then has_card = cd break end if not cd:isKindOf("Peach") and not card:isKindOf("Analeptic") and not (self:getArmor() and cd:objectName() == self.player:getArmor():objectName()) then has_card = cd break end end if has_card then return "$" .. has_card:getEffectiveId() else return ".." end end sgs.ai_skill_playerchosen.fentian = function(self, targets) self:sort(self.enemies,"defense") for _, enemy in ipairs(self.enemies) do if (not self:doNotDiscard(enemy) or self:getDangerousCard(enemy) or self:getValuableCard(enemy)) and not enemy:isNude() and self.player:inMyAttackRange(enemy) then return enemy end end for _, friend in ipairs(self.friends) do if(self:hasSkills(sgs.lose_equip_skill, friend) and not friend:getEquips():isEmpty()) or (self:needToThrowArmor(friend) and friend:getArmor()) or self:doNotDiscard(friend) and self.player:inMyAttackRange(friend) then return friend end end for _, enemy in ipairs(self.enemies) do if not enemy:isNude() and self.player:inMyAttackRange(enemy) then return enemy end end for _, friend in ipairs(self.friends) do if not friend:isNude() and self.player:inMyAttackRange(friend) then return friend end end end sgs.ai_playerchosen_intention.fentian = 20 local getXintanCard = function(pile) if #pile > 1 then return pile[1], pile[2] end return nil end local xintan_skill = {} xintan_skill.name = "xintan" table.insert(sgs.ai_skills, xintan_skill) xintan_skill.getTurnUseCard=function(self) if self.player:hasUsed("XintanCard") then return end if self.player:getPile("burn"):length() <= 1 then return end local ints = sgs.QList2Table(self.player:getPile("burn")) local a, b = getXintanCard(ints) if a and b then return sgs.Card_Parse("@XintanCard=" .. tostring(a) .. "+" .. tostring(b)) end end sgs.ai_skill_use_func.XintanCard = function(card, use, self) local target self:sort(self.enemies, "hp") for _, enemy in ipairs(self.enemies) do if not self:needToLoseHp(enemy, self.player) and ((self:isWeak(enemy) or enemy:getHp() == 1) or self.player:getPile("burn"):length() > 3) then target = enemy end end if not target then for _, friend in ipairs(self.friends) do if not self:needToLoseHp(friend, self.player) then target = friend end end end if target then use.card = card if use.to then use.to:append(target) end return end end sgs.ai_use_priority.XintanCard = 7 sgs.ai_use_value.XintanCard = 3 sgs.ai_card_intention.XintanCard = 80 sgs.ai_skill_use["@@shefu"] = function(self, data) local record for _, friend in ipairs(self.friends) do if self:isWeak(friend) then for _, enemy in ipairs(self.enemies) do if enemy:inMyAttackRange(friend) then if self.player:getMark("Shefu_slash") == 0 then record = "slash" end end end end end if not record then for _, enemy in ipairs(self.enemies) do if self:isWeak(enemy) then for _, friend in ipairs(self.friends) do if friend:inMyAttackRange(enemy) then if self.player:getMark("Shefu_peach") == 0 then record = "peach" elseif self.player:getMark("Shefu_jink") == 0 then record = "jink" end end end end end end if not record then for _, enemy in ipairs(self.enemies) do if enemy:getHp() == 1 then if self.player:getMark("Shefu_peach") == 0 then record = "peach" end end end end if not record then for _, enemy in ipairs(self.enemies) do if getKnownCard(enemy, self.player, "ArcheryAttack", false) > 0 or (enemy:hasSkill("luanji") and enemy:getHandcardNum() > 3) and self.player:getMark("Shefu_archery_attack") == 0 then record = "archery_attack" elseif getKnownCard(enemy, self.player, "SavageAssault", false) > 0 and self.player:getMark("Shefu_savage_assault") == 0 then record = "savage_assault" elseif getKnownCard(enemy, self.player, "Indulgence", false) > 0 or (enemy:hasSkills("guose|nosguose") and enemy:getHandcardNum() > 2) and self.player:getMark("Shefu_indulgence") == 0 then record = "indulgence" end end end for _, player in sgs.qlist(self.room:getAlivePlayers()) do if player:containsTrick("lightning") and self:hasWizard(self.enemies) then if self.player:getMark("Shefu_lightning") == 0 then record = "lightning" end end end if not record then if self.player:getMark("Shefu_slash") == 0 then record = "slash" elseif self.player:getMark("Shefu_peach") == 0 then record = "peach" end end local cards = sgs.QList2Table(self.player:getHandcards()) local use_card self:sortByKeepValue(cards) for _,card in ipairs(cards) do if not card:isKindOf("Peach") and not (self:isWeak() and card:isKindOf("Jink"))then use_card = card end end if record and use_card then return "@ShefuCard="..use_card:getEffectiveId()..":"..record end end sgs.ai_skill_invoke.shefu_cancel = function(self) local data = self.room:getTag("ShefuData") local use = data:toCardUse() local from = use.from local to = use.to:first() if from and self:isEnemy(from) then if (use.card:isKindOf("Jink") and self:isWeak(from)) or (use.card:isKindOf("Peach") and self:isWeak(from)) or use.card:isKindOf("Indulgence") or use.card:isKindOf("ArcheryAttack") or use.card:isKindOf("SavageAssault") then return true end end if to and self:isFriend(to) then if (use.card:isKindOf("Slash") and self:isWeak(to)) or use.card:isKindOf("Lightning") then return true end end return false end sgs.ai_skill_invoke.benyu = function(self, data) return true end sgs.ai_skill_cardask["@@benyu"] = function(self, data) local damage = self.room:getTag("CurrentDamageStruct"):toDamage() if not damage.from or self.player:isKongcheng() or not self:isEnemy(damage.from) then return "." end local needcard_num = damage.from:getHandcardNum() + 1 local cards = self.player:getCards("he") local to_discard = {} cards = sgs.QList2Table(cards) self:sortByKeepValue(cards) for _, card in ipairs(cards) do if not card:isKindOf("Peach") or damage.from:getHp() == 1 then table.insert(to_discard, card:getEffectiveId()) if #to_discard == needcard_num then break end end end if #to_discard == needcard_num then return "$" .. table.concat(to_discard, "+") end return "." end sgs.ai_skill_choice.liangzhu = function(self, choices, data) local current = self.room:getCurrent() if self:isFriend(current) and (self:isWeak(current) or current:hasSkills(sgs.cardneed_skill))then return "letdraw" end return "draw" end sgs.ai_skill_invoke.cihuai = function(self, data) local has_slash = false local cards = self.player:getCards("h") cards=sgs.QList2Table(cards) for _, card in ipairs(cards) do if card:isKindOf("Slash") then has_slash = true end end if has_slash then return false end self:sort(self.enemies, "defenseSlash") for _, enemy in ipairs(self.enemies) do local slash = sgs.Sanguosha:cloneCard("slash", sgs.Card_NoSuit, 0) local eff = self:slashIsEffective(slash, enemy) and sgs.isGoodTarget(enemy, self.enemies, self) if eff and self.player:canSlash(enemy) and not self:slashProhibit(nil, enemy) then return true end end return false end local cihuai_skill = {} cihuai_skill.name = "cihuai" table.insert(sgs.ai_skills, cihuai_skill) cihuai_skill.getTurnUseCard = function(self) if self.player:getMark("@cihuai") > 0 then local card_str = ("slash:_cihuai[no_suit:0]=.") local slash = sgs.Card_Parse(card_str) assert(slash) return slash end end sgs.ai_skill_invoke.kunfen = function(self, data) if not self:isWeak() and (self.player:getHp() > 2 or (self:getCardsNum("Peach") > 0 and self.player:getHp() > 1)) then return true end return false end local chixin_skill={} chixin_skill.name="chixin" table.insert(sgs.ai_skills,chixin_skill) chixin_skill.getTurnUseCard = function(self, inclusive) local cards = self.player:getCards("he") cards=sgs.QList2Table(cards) local diamond_card self:sortByUseValue(cards,true) local useAll = false self:sort(self.enemies, "defense") for _, enemy in ipairs(self.enemies) do if enemy:getHp() == 1 and not enemy:hasArmorEffect("EightDiagram") and self.player:distanceTo(enemy) <= self.player:getAttackRange() and self:isWeak(enemy) and getCardsNum("Jink", enemy, self.player) + getCardsNum("Peach", enemy, self.player) + getCardsNum("Analeptic", enemy, self.player) == 0 then useAll = true break end end local disCrossbow = false if self:getCardsNum("Slash") < 2 or self.player:hasSkill("paoxiao") then disCrossbow = true end for _,card in ipairs(cards) do if card:getSuit() == sgs.Card_Diamond and (not isCard("Peach", card, self.player) and not isCard("ExNihilo", card, self.player) and not useAll) and (not isCard("Crossbow", card, self.player) and not disCrossbow) and (self:getUseValue(card) < sgs.ai_use_value.Slash or inclusive or sgs.Sanguosha:correctCardTarget(sgs.TargetModSkill_Residue, self.player, sgs.Sanguosha:cloneCard("slash")) > 0) then diamond_card = card break end end if not diamond_card then return nil end local suit = diamond_card:getSuitString() local number = diamond_card:getNumberString() local card_id = diamond_card:getEffectiveId() local card_str = ("slash:chixin[%s:%s]=%d"):format(suit, number, card_id) local slash = sgs.Card_Parse(card_str) assert(slash) return slash end sgs.ai_view_as.chixin = function(card, player, card_place, class_name) local suit = card:getSuitString() local number = card:getNumberString() local card_id = card:getEffectiveId() if card_place ~= sgs.Player_PlaceSpecial and card:getSuit() == sgs.Card_Diamond and not card:isKindOf("Peach") and not card:hasFlag("using") then if class_name == "Slash" then return ("slash:chixin[%s:%s]=%d"):format(suit, number, card_id) elseif class_name == "Jink" then return ("jink:chixin[%s:%s]=%d"):format(suit, number, card_id) end end end sgs.ai_cardneed.chixin = function(to, card) return card:getSuit() == sgs.Card_Diamond end sgs.ai_skill_playerchosen.suiren = function(self, targets) if self.player:getMark("@suiren") == 0 then return "." end if self:isWeak() and (self:getOverflow() < -2 or not self:willSkipPlayPhase()) then return self.player end self:sort(self.friends_noself, "defense") for _, friend in ipairs(self.friends) do if self:isWeak(friend) and not self:needKongcheng(friend) then return friend end end self:sort(self.enemies, "defense") for _, enemy in ipairs(self.enemies) do if (self:isWeak(enemy) and enemy:getHp() == 1) and self.player:getHandcardNum() < 2 and not self:willSkipPlayPhase() and self.player:inMyAttackRange(enemy) then return self.player end end end sgs.ai_playerchosen_intention.suiren = -60
gpl-3.0
rlcevg/Zero-K
LuaUI/Widgets/init_startup_info_selector.lua
1
9334
local versionNumber = "1.22" -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Startup Info and Selector", desc = "[v" .. string.format("%s", versionNumber ) .. "] Shows important information and options on startup.", author = "SirMaverick", date = "2009,2010", license = "GNU GPL, v2 or later", layer = 0, enabled = true } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --[[ -- Features: _ Show a windows at game start with pictures to choose commander type. ]]-- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local spGetGameRulesParam = Spring.GetGameRulesParam -- FIXME use tobool instead of this string comparison silliness local coop = (Spring.GetModOptions().coop == "1") or false local forcejunior = (Spring.GetModOptions().forcejunior == "1") or false local Chili local Window local ScrollPanel local Grid local Label local screen0 local Image local Button local vsx, vsy = widgetHandler:GetViewSizes() local modoptions = Spring.GetModOptions() --used in LuaUI\Configs\startup_info_selector.lua for planetwars local selectorShown = false local mainWindow local scroll local grid local trainerCheckbox local buttons = {} local buttonLabels = {} local trainerLabels = {} local actionShow = "showstartupinfoselector" local optionData local noComm = false local gameframe = Spring.GetGameFrame() local WINDOW_WIDTH = 720 local WINDOW_HEIGHT = 480 local BUTTON_WIDTH = 128 local BUTTON_HEIGHT = 128 if (vsx < 1024 or vsy < 768) then --shrinker WINDOW_WIDTH = vsx* (WINDOW_WIDTH/1024) WINDOW_HEIGHT = vsy* (WINDOW_HEIGHT/768) BUTTON_WIDTH = vsx* (BUTTON_WIDTH/1024) BUTTON_HEIGHT = vsy* (BUTTON_HEIGHT/768) end --local wantLabelUpdate = false -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- wait for next screenframe so Grid can resize its elements first -- doesn't actually work local function ToggleTrainerButtons(bool) for i=1,#buttons do if buttons[i].trainer then if bool then grid:AddChild(buttons[i]) else grid:RemoveChild(buttons[i]) end end end end options_path = 'Settings/HUD Panels/Commander Selector' options = { hideTrainers = { name = 'Hide Trainer Commanders', --desc = '', type = 'bool', value = false, OnChange = function(self) --if trainerCheckbox then -- trainerCheckbox:Toggle() --end ToggleTrainerButtons(not self.value) end }, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function PlaySound(filename, ...) local path = filename..".WAV" if (VFS.FileExists(path)) then Spring.PlaySoundFile(path, ...) else --Spring.Echo(filename) Spring.Echo("<Startup Info Selector>: Error - file "..path.." doesn't exist.") end end function widget:ViewResize(viewSizeX, viewSizeY) vsx = viewSizeX vsy = viewSizeY end function Close(commPicked) if not commPicked then --Spring.Echo("Requesting baseline comm") --Spring.SendLuaRulesMsg("faction:comm_trainer_strike") end --Spring_SendCommands("say: a:I chose " .. option.button}) if mainWindow then mainWindow:Dispose() end end local function CreateWindow() if mainWindow then mainWindow:Dispose() end local numColumns = math.floor(WINDOW_WIDTH/BUTTON_WIDTH) local numRows = math.ceil(#optionData/numColumns) mainWindow = Window:New{ resizable = false, draggable = false, clientWidth = WINDOW_WIDTH, clientHeight = WINDOW_HEIGHT, x = (vsx - WINDOW_WIDTH)/2, y = ((vsy - WINDOW_HEIGHT)/2), parent = screen0, caption = "COMMANDER SELECTOR", } --scroll = ScrollPanel:New{ -- parent = mainWindow, -- horizontalScrollbar = false, -- bottom = 36, -- x = 2, -- y = 12, -- right = 2, --} grid = Grid:New{ parent = mainWindow, autosize = false, resizeItems = true, x=0, right=0, y=0, bottom=36, centerItems = false, } -- add posters local i = 0 for index,option in ipairs(optionData) do i = i + 1 local hideButton = options.hideTrainers.value and option.trainer local button = Button:New { parent = (not hideButton) and grid or nil, caption = "", --option.name, --option.trainer and "TRAINER" or "", valign = "bottom", tooltip = option.tooltip, --added comm name under cursor on tooltip too, like for posters width = BUTTON_WIDTH, height = BUTTON_HEIGHT, padding = {5,5,5,5}, OnClick = {function() Spring.SendLuaRulesMsg("customcomm:"..option.commProfile) Spring.SendCommands({'say a:I choose: '..option.name..'!'}) Close(true) end}, trainer = option.trainer, } buttons[i] = button local image = Image:New{ parent = button, file = option.image,--lookup Configs/startup_info_selector.lua to get optiondata tooltip = option.tooltip, x = 2, y = 2, right = 2, bottom = 12, } local label = Label:New{ parent = button, x = "15%", bottom = 4, caption = option.name, align = "center", font = {size = 14}, } buttonLabels[i] = label if option.trainer then local trainerLabel = Label:New{ parent = image, x = "25%", y = "50%", caption = "TRAINER", align = "center", font = {color = {1,0.2,0.2,1}, size=16, outline=true, outlineColor={1,1,1,0.8}}, } trainerLabels[i] = trainerLabel end end local cbWidth = WINDOW_WIDTH*0.75 local closeButton = Button:New{ parent = mainWindow, caption = "CLOSE", width = cbWidth, x = (WINDOW_WIDTH - cbWidth)/2, height = 30, bottom = 2, OnClick = {function() Close(false) end} } --[[ -- FIXME: EPIC doesn't remember the setting if you change it with this checkbox trainerCheckbox = Chili.Checkbox:New{ parent = mainWindow, x = 4, bottom = 2, width = 160, caption = "Hide Trainer Comms", checked = options.hideTrainers.value, OnChange = { function(self) options.hideTrainers.value = self.checked ToggleTrainerButtons(self.checked) end }, } ]] grid:Invalidate() end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:Initialize() optionData = include("Configs/startup_info_selector.lua") if not (WG.Chili) then widgetHandler:RemoveWidget() end if (Spring.GetSpectatingState() or Spring.IsReplay() or forcejunior) and (not Spring.IsCheatingEnabled()) then Spring.Echo("<Startup Info and Selector> Spectator mode, Junior forced, or replay. Widget removed.") widgetHandler:RemoveWidget() return end -- chili setup Chili = WG.Chili Window = Chili.Window ScrollPanel = Chili.ScrollPanel Grid = Chili.Grid Label = Chili.Label screen0 = Chili.Screen0 Image = Chili.Image Button = Chili.Button -- FIXME: because this code runs before gadget:GameLoad(), the selector window pops up -- even if comm is already selected -- nothing serious, just annoying local playerID = Spring.GetMyPlayerID() local teamID = Spring.GetMyTeamID() if (coop and playerID and Spring.GetGameRulesParam("commSpawnedPlayer"..playerID) == 1) or (not coop and Spring.GetTeamRulesParam(teamID, "commSpawned") == 1) then noComm = true -- will prevent window from auto-appearing; can still be brought up from the button end PlaySound("LuaUI/Sounds/Voices/initialized_core_1", 1, 'ui') vsx, vsy = widgetHandler:GetViewSizes() widgetHandler:AddAction(actionShow, CreateWindow, nil, "t") if (not noComm) then buttonWindow = Window:New{ resizable = false, draggable = false, width = 64, height = 64, right = 0, y = 160, tweakDraggable = true, color = {0, 0, 0, 0}, padding = {0, 0, 0, 0}, itemMargin = {0, 0, 0, 0} } if Spring.GetGameSeconds() <= 0 then screen0:AddChild(buttonWindow) end button = Button:New{ parent = buttonWindow, caption = '', tooltip = "Open comm selection screen", width = "100%", height = "100%", x = 0, y = 0, OnClick = {function() Spring.SendCommands({"luaui "..actionShow}) end} } buttonImage = Image:New{ parent = button, width="100%"; height="100%"; x=0; y=0; file = "LuaUI/Images/startup_info_selector/selecticon.png", keepAspect = false, } CreateWindow() end end -- hide window if game was loaded local timer = 0 function widget:Update(dt) if gameframe < 1 then timer = timer + dt if timer >= 0.1 then if (spGetGameRulesParam("loadedGame") == 1) and mainWindow then mainWindow:Dispose() end end end end function widget:Shutdown() --if mainWindow then --mainWindow:Dispose() --end widgetHandler:RemoveAction(actionShow) end function widget:Gameframe(n) gameframe = n end function widget:GameStart() screen0:RemoveChild(buttonWindow) end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
rlcevg/Zero-K
scripts/nanoaim.h.lua
15
2783
------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- -- -- Author: jK @ 2010 -- -- How to use: -- -- 1. Add to the start of your script: include "nanoaim.h.lua" -- 2. After you define your pieces tell which you want to smoke e.g.: local nanoPieces = { piece "nano_aim" } -- 3. In your 'function script:Create()' add: StartThread(UpdateNanoDirectionThread, nanoPieces [, updateInterval = 1000 [, turnSpeed = 0.75*math.pi [, turnSpeedVert = turnSpeed ]]]) -- 4. In your 'function script.StartBuilding()' add: UpdateNanoDirection(nanoPieces [, turnSpeed = 0.75*math.pi [, turnSpeedVert = turnSpeed ]]) -- 5. Don't forget to set COB.INBUILDSTANCE:=1 & COB.INBUILDSTANCE:=0 in StartBuilding/StopBuilding -- ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local Utils_GetUnitNanoTarget = Spring.Utilities.GetUnitNanoTarget function UpdateNanoDirection(nanopieces,turnSpeed,turnSpeedVert) local type, target, isFeature = Utils_GetUnitNanoTarget(unitID) if (target) then local x,y,z if (type == "restore") then x,y,z = target[1],target[2],target[3] elseif (not isFeature) then x,y,z = Spring.GetUnitPosition(target) else x,y,z = Spring.GetFeaturePosition(target) end local ux,uy,uz = Spring.GetUnitPosition(unitID) local dx,dy,dz = x-ux,y-uy,z-uz local th = Spring.GetHeadingFromVector(dx,dz) local h = Spring.GetUnitHeading(unitID) local heading = (th - h) * math.pi / 32768 local length = math.sqrt(dx*dx + dy*dy + dz*dz) local norm_dy = (length > 0 and dy / length) or 0 local tp = math.asin(norm_dy) local p = math.asin(select(2,Spring.GetUnitDirection(unitID))) local pitch = p - tp turnSpeed = turnSpeed or (0.75*math.pi) turnSpeedVert = turnSpeedVert or turnSpeed local turned = false for i=1,#nanopieces do local nano = nanopieces[i] local cur_head,cur_pitch = Spring.UnitScript.GetPieceRotation(nano) if (cur_head ~= heading)or(cur_pitch ~= pitch) then Turn(nano, y_axis, heading, turnSpeed) Turn(nano, x_axis, pitch, turnSpeedVert) turned = true end end if (turned) then WaitForTurn(nanopieces[1], y_axis) end end end function UpdateNanoDirectionThread(nanopieces, updateInterval, turnSpeed,turnSpeedVert) updateInterval = updateInterval or 1000 while true do UpdateNanoDirection(nanopieces,turnSpeed,turnSpeedVert) Sleep(updateInterval) end end ------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------
gpl-2.0
stas2z/openwrt-witi
package/luci/modules/luci-base/luasrc/sys.lua
40
15171
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local io = require "io" local os = require "os" local table = require "table" local nixio = require "nixio" local fs = require "nixio.fs" local uci = require "luci.model.uci" local luci = {} luci.util = require "luci.util" luci.ip = require "luci.ip" local tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select = tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select module "luci.sys" function call(...) return os.execute(...) / 256 end exec = luci.util.exec function mounts() local data = {} local k = {"fs", "blocks", "used", "available", "percent", "mountpoint"} local ps = luci.util.execi("df") if not ps then return else ps() end for line in ps do local row = {} local j = 1 for value in line:gmatch("[^%s]+") do row[k[j]] = value j = j + 1 end if row[k[1]] then -- this is a rather ugly workaround to cope with wrapped lines in -- the df output: -- -- /dev/scsi/host0/bus0/target0/lun0/part3 -- 114382024 93566472 15005244 86% /mnt/usb -- if not row[k[2]] then j = 2 line = ps() for value in line:gmatch("[^%s]+") do row[k[j]] = value j = j + 1 end end table.insert(data, row) end end return data end -- containing the whole environment is returned otherwise this function returns -- the corresponding string value for the given name or nil if no such variable -- exists. getenv = nixio.getenv function hostname(newname) if type(newname) == "string" and #newname > 0 then fs.writefile( "/proc/sys/kernel/hostname", newname ) return newname else return nixio.uname().nodename end end function httpget(url, stream, target) if not target then local source = stream and io.popen or luci.util.exec return source("wget -qO- '"..url:gsub("'", "").."'") else return os.execute("wget -qO '%s' '%s'" % {target:gsub("'", ""), url:gsub("'", "")}) end end function reboot() return os.execute("reboot >/dev/null 2>&1") end function syslog() return luci.util.exec("logread") end function dmesg() return luci.util.exec("dmesg") end function uniqueid(bytes) local rand = fs.readfile("/dev/urandom", bytes) return rand and nixio.bin.hexlify(rand) end function uptime() return nixio.sysinfo().uptime end net = {} -- The following fields are defined for arp entry objects: -- { "IP address", "HW address", "HW type", "Flags", "Mask", "Device" } function net.arptable(callback) local arp = (not callback) and {} or nil local e, r, v if fs.access("/proc/net/arp") then for e in io.lines("/proc/net/arp") do local r = { }, v for v in e:gmatch("%S+") do r[#r+1] = v end if r[1] ~= "IP" then local x = { ["IP address"] = r[1], ["HW type"] = r[2], ["Flags"] = r[3], ["HW address"] = r[4], ["Mask"] = r[5], ["Device"] = r[6] } if callback then callback(x) else arp = arp or { } arp[#arp+1] = x end end end end return arp end local function _nethints(what, callback) local _, k, e, mac, ip, name local cur = uci.cursor() local ifn = { } local hosts = { } local function _add(i, ...) local k = select(i, ...) if k then if not hosts[k] then hosts[k] = { } end hosts[k][1] = select(1, ...) or hosts[k][1] hosts[k][2] = select(2, ...) or hosts[k][2] hosts[k][3] = select(3, ...) or hosts[k][3] hosts[k][4] = select(4, ...) or hosts[k][4] end end if fs.access("/proc/net/arp") then for e in io.lines("/proc/net/arp") do ip, mac = e:match("^([%d%.]+)%s+%S+%s+%S+%s+([a-fA-F0-9:]+)%s+") if ip and mac then _add(what, mac:upper(), ip, nil, nil) end end end if fs.access("/etc/ethers") then for e in io.lines("/etc/ethers") do mac, ip = e:match("^([a-f0-9]%S+) (%S+)") if mac and ip then _add(what, mac:upper(), ip, nil, nil) end end end if fs.access("/var/dhcp.leases") then for e in io.lines("/var/dhcp.leases") do mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)") if mac and ip then _add(what, mac:upper(), ip, nil, name ~= "*" and name) end end end cur:foreach("dhcp", "host", function(s) for mac in luci.util.imatch(s.mac) do _add(what, mac:upper(), s.ip, nil, s.name) end end) for _, e in ipairs(nixio.getifaddrs()) do if e.name ~= "lo" then ifn[e.name] = ifn[e.name] or { } if e.family == "packet" and e.addr and #e.addr == 17 then ifn[e.name][1] = e.addr:upper() elseif e.family == "inet" then ifn[e.name][2] = e.addr elseif e.family == "inet6" then ifn[e.name][3] = e.addr end end end for _, e in pairs(ifn) do if e[what] and (e[2] or e[3]) then _add(what, e[1], e[2], e[3], e[4]) end end for _, e in luci.util.kspairs(hosts) do callback(e[1], e[2], e[3], e[4]) end end -- Each entry contains the values in the following order: -- [ "mac", "name" ] function net.mac_hints(callback) if callback then _nethints(1, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 if name and name ~= mac then callback(mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4) end end) else local rv = { } _nethints(1, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 if name and name ~= mac then rv[#rv+1] = { mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 } end end) return rv end end -- Each entry contains the values in the following order: -- [ "ip", "name" ] function net.ipv4_hints(callback) if callback then _nethints(2, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4, nil, 100) or mac if name and name ~= v4 then callback(v4, name) end end) else local rv = { } _nethints(2, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4, nil, 100) or mac if name and name ~= v4 then rv[#rv+1] = { v4, name } end end) return rv end end -- Each entry contains the values in the following order: -- [ "ip", "name" ] function net.ipv6_hints(callback) if callback then _nethints(3, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v6, nil, 100) or mac if name and name ~= v6 then callback(v6, name) end end) else local rv = { } _nethints(3, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v6, nil, 100) or mac if name and name ~= v6 then rv[#rv+1] = { v6, name } end end) return rv end end function net.conntrack(callback) local connt = {} if fs.access("/proc/net/nf_conntrack", "r") then for line in io.lines("/proc/net/nf_conntrack") do line = line:match "^(.-( [^ =]+=).-)%2" local entry, flags = _parse_mixed_record(line, " +") if flags[6] ~= "TIME_WAIT" then entry.layer3 = flags[1] entry.layer4 = flags[3] for i=1, #entry do entry[i] = nil end if callback then callback(entry) else connt[#connt+1] = entry end end end elseif fs.access("/proc/net/ip_conntrack", "r") then for line in io.lines("/proc/net/ip_conntrack") do line = line:match "^(.-( [^ =]+=).-)%2" local entry, flags = _parse_mixed_record(line, " +") if flags[4] ~= "TIME_WAIT" then entry.layer3 = "ipv4" entry.layer4 = flags[1] for i=1, #entry do entry[i] = nil end if callback then callback(entry) else connt[#connt+1] = entry end end end else return nil end return connt end function net.devices() local devs = {} for k, v in ipairs(nixio.getifaddrs()) do if v.family == "packet" then devs[#devs+1] = v.name end end return devs end function net.deviceinfo() local devs = {} for k, v in ipairs(nixio.getifaddrs()) do if v.family == "packet" then local d = v.data d[1] = d.rx_bytes d[2] = d.rx_packets d[3] = d.rx_errors d[4] = d.rx_dropped d[5] = 0 d[6] = 0 d[7] = 0 d[8] = d.multicast d[9] = d.tx_bytes d[10] = d.tx_packets d[11] = d.tx_errors d[12] = d.tx_dropped d[13] = 0 d[14] = d.collisions d[15] = 0 d[16] = 0 devs[v.name] = d end end return devs end -- The following fields are defined for route entry tables: -- { "dest", "gateway", "metric", "refcount", "usecount", "irtt", -- "flags", "device" } function net.routes(callback) local routes = { } for line in io.lines("/proc/net/route") do local dev, dst_ip, gateway, flags, refcnt, usecnt, metric, dst_mask, mtu, win, irtt = line:match( "([^%s]+)\t([A-F0-9]+)\t([A-F0-9]+)\t([A-F0-9]+)\t" .. "(%d+)\t(%d+)\t(%d+)\t([A-F0-9]+)\t(%d+)\t(%d+)\t(%d+)" ) if dev then gateway = luci.ip.Hex( gateway, 32, luci.ip.FAMILY_INET4 ) dst_mask = luci.ip.Hex( dst_mask, 32, luci.ip.FAMILY_INET4 ) dst_ip = luci.ip.Hex( dst_ip, dst_mask:prefix(dst_mask), luci.ip.FAMILY_INET4 ) local rt = { dest = dst_ip, gateway = gateway, metric = tonumber(metric), refcount = tonumber(refcnt), usecount = tonumber(usecnt), mtu = tonumber(mtu), window = tonumber(window), irtt = tonumber(irtt), flags = tonumber(flags, 16), device = dev } if callback then callback(rt) else routes[#routes+1] = rt end end end return routes end -- The following fields are defined for route entry tables: -- { "source", "dest", "nexthop", "metric", "refcount", "usecount", -- "flags", "device" } function net.routes6(callback) if fs.access("/proc/net/ipv6_route", "r") then local routes = { } for line in io.lines("/proc/net/ipv6_route") do local dst_ip, dst_prefix, src_ip, src_prefix, nexthop, metric, refcnt, usecnt, flags, dev = line:match( "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) +([^%s]+)" ) if dst_ip and dst_prefix and src_ip and src_prefix and nexthop and metric and refcnt and usecnt and flags and dev then src_ip = luci.ip.Hex( src_ip, tonumber(src_prefix, 16), luci.ip.FAMILY_INET6, false ) dst_ip = luci.ip.Hex( dst_ip, tonumber(dst_prefix, 16), luci.ip.FAMILY_INET6, false ) nexthop = luci.ip.Hex( nexthop, 128, luci.ip.FAMILY_INET6, false ) local rt = { source = src_ip, dest = dst_ip, nexthop = nexthop, metric = tonumber(metric, 16), refcount = tonumber(refcnt, 16), usecount = tonumber(usecnt, 16), flags = tonumber(flags, 16), device = dev, -- lua number is too small for storing the metric -- add a metric_raw field with the original content metric_raw = metric } if callback then callback(rt) else routes[#routes+1] = rt end end end return routes end end function net.pingtest(host) return os.execute("ping -c1 '"..host:gsub("'", '').."' >/dev/null 2>&1") end process = {} function process.info(key) local s = {uid = nixio.getuid(), gid = nixio.getgid()} return not key and s or s[key] end function process.list() local data = {} local k local ps = luci.util.execi("/bin/busybox top -bn1") if not ps then return end for line in ps do local pid, ppid, user, stat, vsz, mem, cpu, cmd = line:match( "^ *(%d+) +(%d+) +(%S.-%S) +([RSDZTW][W ][<N ]) +(%d+) +(%d+%%) +(%d+%%) +(.+)" ) local idx = tonumber(pid) if idx then data[idx] = { ['PID'] = pid, ['PPID'] = ppid, ['USER'] = user, ['STAT'] = stat, ['VSZ'] = vsz, ['%MEM'] = mem, ['%CPU'] = cpu, ['COMMAND'] = cmd } end end return data end function process.setgroup(gid) return nixio.setgid(gid) end function process.setuser(uid) return nixio.setuid(uid) end process.signal = nixio.kill user = {} -- { "uid", "gid", "name", "passwd", "dir", "shell", "gecos" } user.getuser = nixio.getpw function user.getpasswd(username) local pwe = nixio.getsp and nixio.getsp(username) or nixio.getpw(username) local pwh = pwe and (pwe.pwdp or pwe.passwd) if not pwh or #pwh < 1 or pwh == "!" or pwh == "x" then return nil, pwe else return pwh, pwe end end function user.checkpasswd(username, pass) local pwh, pwe = user.getpasswd(username) if pwe then return (pwh == nil or nixio.crypt(pass, pwh) == pwh) end return false end function user.setpasswd(username, password) if password then password = password:gsub("'", [['"'"']]) end if username then username = username:gsub("'", [['"'"']]) end return os.execute( "(echo '" .. password .. "'; sleep 1; echo '" .. password .. "') | " .. "passwd '" .. username .. "' >/dev/null 2>&1" ) end wifi = {} function wifi.getiwinfo(ifname) local stat, iwinfo = pcall(require, "iwinfo") if ifname then local c = 0 local u = uci.cursor_state() local d, n = ifname:match("^(%w+)%.network(%d+)") if d and n then ifname = d n = tonumber(n) u:foreach("wireless", "wifi-iface", function(s) if s.device == d then c = c + 1 if c == n then ifname = s.ifname or s.device return false end end end) elseif u:get("wireless", ifname) == "wifi-device" then u:foreach("wireless", "wifi-iface", function(s) if s.device == ifname and s.ifname then ifname = s.ifname return false end end) end local t = stat and iwinfo.type(ifname) local x = t and iwinfo[t] or { } return setmetatable({}, { __index = function(t, k) if k == "ifname" then return ifname elseif x[k] then return x[k](ifname) end end }) end end init = {} init.dir = "/etc/init.d/" function init.names() local names = { } for name in fs.glob(init.dir.."*") do names[#names+1] = fs.basename(name) end return names end function init.index(name) if fs.access(init.dir..name) then return call("env -i sh -c 'source %s%s enabled; exit ${START:-255}' >/dev/null" %{ init.dir, name }) end end local function init_action(action, name) if fs.access(init.dir..name) then return call("env -i %s%s %s >/dev/null" %{ init.dir, name, action }) end end function init.enabled(name) return (init_action("enabled", name) == 0) end function init.enable(name) return (init_action("enable", name) == 1) end function init.disable(name) return (init_action("disable", name) == 0) end function init.start(name) return (init_action("start", name) == 0) end function init.stop(name) return (init_action("stop", name) == 0) end -- Internal functions function _parse_mixed_record(cnt, delimiter) delimiter = delimiter or " " local data = {} local flags = {} for i, l in pairs(luci.util.split(luci.util.trim(cnt), "\n")) do for j, f in pairs(luci.util.split(luci.util.trim(l), delimiter, nil, true)) do local k, x, v = f:match('([^%s][^:=]*) *([:=]*) *"*([^\n"]*)"*') if k then if x == "" then table.insert(flags, k) else data[k] = v end end end end return data, flags end
gpl-2.0
Unrepentant-Atheist/mame
3rdparty/genie/src/actions/fastbuild/fastbuild_solution.lua
41
5961
-- Generates a FASTBuild config file for a solution. -- Note that table order iteration should be deterministic, so the .bff file content is not -- arbitrarily changed each time it's generated. There are several places in this file -- where sorts are done for that reason. function premake.fastbuild.solution(sln) -- Presuppose we are building a fastbuild config for vs2015 only. io.indent = ' ' _p('// FastBuild solution configuration file. Generated by GENie.') _p('//------------------------------------------------------------------------------------') _p('// %s', sln.name) _p('//------------------------------------------------------------------------------------') _p('#import VS140COMNTOOLS') -- Create a batch file to run vcvarsall, and capture the variables it sets: local is64bit = os.is64bit() local target64 = (is64bit and ' amd64') or ' x86_amd64' local target32 = (is64bit and ' amd64_x86') or '' local getvcvarscontent = [[ @set INCLUDE= @set LIB= @set CommandPromptType= @set PreferredToolArchitecture= @set Platform= @set Path=%SystemRoot%\System32;%SystemRoot%;%SystemRoot%\System32\wbem @call "%VS140COMNTOOLS%..\..\VC\vcvarsall.bat" %1 @echo %INCLUDE% @echo %LIB% @echo %CommandPromptType% @echo %PreferredToolArchitecture% @echo %Platform% @echo %Path% ]] -- Save the temp file. local getvcvarsfilepath = os.getenv('TEMP')..'\\getvcvars.bat' local getvcvarsfile = assert(io.open(getvcvarsfilepath, 'w')) getvcvarsfile:write(getvcvarscontent) getvcvarsfile:close() local vcvarsrawx86 = os.outputof(string.format('call "%s"%s', getvcvarsfilepath, target32)) local vcvarsrawx64 = os.outputof(string.format('call "%s"%s', getvcvarsfilepath, target64)) os.remove(getvcvarsfilepath) local msvcvars = {} msvcvars.x32 = {} msvcvars.x64 = {} local includeslibssplitter = string.gmatch(vcvarsrawx64, "[^\n]+") msvcvars.x64.includesraw = includeslibssplitter() msvcvars.x64.libpathsraw = includeslibssplitter() msvcvars.x64.commandprompttype = includeslibssplitter() msvcvars.x64.preferredtoolarchitecture = includeslibssplitter() msvcvars.x64.platform = includeslibssplitter() msvcvars.x64.pathraw = includeslibssplitter() includeslibssplitter = string.gmatch(vcvarsrawx86, "[^\n]+") msvcvars.x32.includesraw = includeslibssplitter() msvcvars.x32.libpathsraw = includeslibssplitter() msvcvars.x32.commandprompttype = includeslibssplitter() msvcvars.x32.preferredtoolarchitecture = includeslibssplitter() msvcvars.x32.platform = includeslibssplitter() msvcvars.x32.pathraw = includeslibssplitter() local function printincludes(includesraw) _p(1, ".MSVCIncludes = ''") for i in string.gmatch(includesraw, "[^;]+") do _p(2, "+ ' /I\"%s\"'", i) end end local function printlibpaths(libpathsraw) _p(1, ".MSVCLibPaths = ''") for i in string.gmatch(libpathsraw, "[^;]+") do _p(2, "+ ' /LIBPATH:\"%s\"'", i) end end if is64bit then _p('.MSVCx64Config =') _p('[') _p(1, ".Compiler = '$VS140COMNTOOLS$..\\..\\VC\\bin\\amd64\\cl.exe'") _p(1, ".Librarian = '$VS140COMNTOOLS$..\\..\\VC\\bin\\amd64\\lib.exe'") _p(1, ".Linker = '$VS140COMNTOOLS$..\\..\\VC\\bin\\amd64\\link.exe'") printincludes(msvcvars.x64.includesraw) printlibpaths(msvcvars.x64.libpathsraw) _p(']') _p('') _p('.MSVCx86Config =') _p('[') _p(1, ".Compiler = '$VS140COMNTOOLS$..\\..\\VC\\bin\\amd64_x86\\cl.exe'") _p(1, ".Librarian = '$VS140COMNTOOLS$..\\..\\VC\\bin\\amd64_x86\\lib.exe'") _p(1, ".Linker = '$VS140COMNTOOLS$..\\..\\VC\\bin\\amd64_x86\\link.exe'") printincludes(msvcvars.x32.includesraw) printlibpaths(msvcvars.x32.libpathsraw) _p(']') _p('') else _p('.MSVCx64Config =') _p('[') _p(1, ".Compiler = '$VS140COMNTOOLS$..\\..\\VC\\bin\\x86_amd64\\cl.exe'") _p(1, ".Librarian = '$VS140COMNTOOLS$..\\..\\VC\\bin\\x86_amd64\\lib.exe'") _p(1, ".Linker = '$VS140COMNTOOLS$..\\..\\VC\\bin\\x86_amd64\\link.exe'") printincludes(msvcvars.x64.includesraw) printlibpaths(msvcvars.x64.libpathsraw) _p(']') _p('') _p('.MSVCx86Config =') _p('[') _p(1, ".Compiler = '$VS140COMNTOOLS$..\\..\\VC\\bin\\cl.exe'") _p(1, ".Librarian = '$VS140COMNTOOLS$..\\..\\VC\\bin\\lib.exe'") _p(1, ".Linker = '$VS140COMNTOOLS$..\\..\\VC\\bin\\link.exe'") printincludes(msvcvars.x32.includesraw) printlibpaths(msvcvars.x32.libpathsraw) _p(']') _p('') end local msvcbin = '$VS140COMNTOOLS$..\\..\\VC\\bin' .. ((is64bit and '\\amd64') or '') _p('#import Path') _p('#import TMP') _p('#import SystemRoot') _p('') _p('Settings') _p('{') _p(1, '.Environment = {') _p(2, "'Path=%s;$Path$',", msvcbin) _p(2, "'TMP=$TMP$',") _p(2, "'SystemRoot=$SystemRoot$',") _p(2, '}') _p('}') _p('') local function projkindsort(a, b) local projvaluemap = { ConsoleApp = 3, WindowedApp = 3, SharedLib = 2, StaticLib = 1, } if projvaluemap[a.kind] == projvaluemap[b.kind] then return a.name < b.name else return projvaluemap[a.kind] < projvaluemap[b.kind] end end local sortedprojs = {} for prj in premake.solution.eachproject(sln) do table.insert(sortedprojs, prj) end table.sort(sortedprojs, projkindsort) for _, prj in ipairs(sortedprojs) do local fname = premake.project.getbasename(prj.name, '%%.bff') fname = path.join(prj.location, fname) fname = path.getrelative(sln.location, fname) _p('#include "%s"', fname) end _p('') _p('.ProjectVariants = {') for _, plat in ipairs(sln.platforms) do for _, cfg in ipairs(sln.configurations) do _p(1, "'%s-%s',", cfg, plat) end end _p('}') _p('') _p('ForEach(.Variant in .ProjectVariants)') _p('{') _p(1, "Alias('all-$Variant$')") _p(1, '{') _p(2, '.Targets = {') for _, prj in ipairs(sortedprojs) do _p(3, "'%s-$Variant$',", prj.name) end _p(2, '}') _p(1, '}') _p('}') end
gpl-2.0
Jeffyrao/nn
NarrowTable.lua
38
1151
local NarrowTable, parent = torch.class('nn.NarrowTable', 'nn.Module') function NarrowTable:__init(offset, length) parent.__init(self) self.offset = offset self.length = length or 1 if not offset then error('nn.NarrowTable(offset, length)') end self.output = {} self.gradInput = {} end function NarrowTable:updateOutput(input) for k,v in ipairs(self.output) do self.output[k] = nil end for i=1,self.length do self.output[i] = input[self.offset+i-1] end return self.output end function NarrowTable:updateGradInput(input, gradOutput) for i=1,#gradOutput do self.gradInput[self.offset+i-1] = gradOutput[i] end for i=1,#input do if (i < self.offset) or (i >= self.offset + self.length) then self.gradInput[i] = nn.utils.recursiveResizeAs(self.gradInput[i], input[i]) nn.utils.recursiveFill(self.gradInput[i], 0) end end for i=#input+1,#self.gradInput do self.gradInput[i] = nil end return self.gradInput end function NarrowTable:type(type, tensorCache) self.output = {} self.gradInput = {} return parent.type(self, type, tensorCache) end
bsd-3-clause
EliHar/Pattern_recognition
torch1/install/share/lua/5.1/luarocks/fetch/svn.lua
14
2187
--- Fetch back-end for retrieving sources from Subversion. --module("luarocks.fetch.svn", package.seeall) local svn = {} local unpack = unpack or table.unpack local fs = require("luarocks.fs") local dir = require("luarocks.dir") local util = require("luarocks.util") --- Download sources for building a rock, using Subversion. -- @param rockspec table: The rockspec table -- @param extract boolean: Unused in this module (required for API purposes.) -- @param dest_dir string or nil: If set, will extract to the given directory. -- @return (string, string) or (nil, string): The absolute pathname of -- the fetched source tarball and the temporary directory created to -- store it; or nil and an error message. function svn.get_sources(rockspec, extract, dest_dir) assert(type(rockspec) == "table") assert(type(dest_dir) == "string" or not dest_dir) local svn_cmd = rockspec.variables.SVN local ok, err_msg = fs.is_tool_available(svn_cmd, "--version", "Subversion") if not ok then return nil, err_msg end local name_version = rockspec.name .. "-" .. rockspec.version local module = rockspec.source.module or dir.base_name(rockspec.source.url) local url = rockspec.source.url:gsub("^svn://", "") local command = {svn_cmd, "checkout", url, module} if rockspec.source.tag then table.insert(command, 5, "-r") table.insert(command, 6, rockspec.source.tag) end local store_dir if not dest_dir then store_dir = fs.make_temp_dir(name_version) if not store_dir then return nil, "Failed creating temporary directory." end util.schedule_function(fs.delete, store_dir) else store_dir = dest_dir end local ok, err = fs.change_dir(store_dir) if not ok then return nil, err end if not fs.execute(unpack(command)) then return nil, "Failed fetching files from Subversion." end ok, err = fs.change_dir(module) if not ok then return nil, err end for _, d in ipairs(fs.find(".")) do if dir.base_name(d) == ".svn" then fs.delete(dir.path(store_dir, module, d)) end end fs.pop_dir() fs.pop_dir() return module, store_dir end return svn
mit
ikstream/Minstrel-Blues
measurement/minstrel-measurement/bin/fetch_file.lua
1
1382
misc = require ('misc') local argparse = require "argparse" local parser = argparse("fetch_file", "dump file continuously to stdout") parser:argument("filename", "Filename to fetch.") parser:flag ("-l --line", "Read line by line", false ) parser:flag ("-b --binary", "Read binary file", false ) parser:option ("-i --interval", "Number of nanoseconds between reads", "500000000" ) local args = parser:parse() -- fixme: -l or -b, exclude -lb local nanoseconds = 1/1e9 local interval_num = tonumber ( args.interval ) local mode = "r" if (args.binary) then mode = mode .. "b" end local fname = args.filename or "" --fname = string.gsub ( fname, ":", "\\:" ) -- note: line reads can result in broken lines while ( true ) do if ( isFile ( fname ) == false ) then io.stderr:write ( "Error: Not a File: " .. fname .. "\n") os.exit ( 1 ) end local file = io.open ( fname, mode ) if ( file == nil ) then io.stderr:write ( "Error: Open file failed: " .. fname .. ", mode: " .. mode .. "\n" ) os.exit ( 1 ) end if ( args.line ) then local line = file:read ("*l") if (line ~= nil) then print ( line ) end else local content = file:read ("*a") if (content ~= nil) then print ( content ) end end file:close() misc.nanosleep(interval_num * nanoseconds) -- sleep for 500000 µs end
gpl-2.0
simpla-fusion/SimPla
scripts/configure/cold_plasma.lua
1
3329
Description="For Cold Plasma Dispersion" -- description or other text things. -- SI Unit System c = 299792458 -- m/s e=1.60217656e-19 -- C me=9.10938291e-31 --kg mp=1.672621777e-27 --kg mp_me=1836.15267245 -- KeV = 1.1604e7 -- K Tesla = 1.0 -- Tesla PI=3.141592653589793 TWOPI=PI*2 k_B=1.3806488e-23 --Boltzmann_constant epsilon0=8.8542e-12 -- k_parallel=6.5 Btor= 1.0 * Tesla Ti = 0.0003 * KeV Te = 0.05 * KeV N0 = 1.0e19-- m^-3 omega_ci = e * Btor/mp -- e/m_p B0 rad/s vTi= math.sqrt(k_B*Ti*2/mp) rhoi = vTi/omega_ci -- m omega_ce = e * Btor/me -- e/m_p B0 rad/s vTe= math.sqrt(k_B*Te*2/me) rhoe = vTe/omega_ce -- m omeaga_pe=math.sqrt(N0*e*e/(me*epsilon0)) NX = 128 NY = 1 NZ = 1 LX = 0.05 --m --100000*rhoi --0.6 LY = 0 --2.0*math.pi/k0 LZ = 0 -- 2.0*math.pi/18 GW = 5 omega_ext=omega_ci*1.2 -- From Gan InitN0=function(x,y,z) -- local X0 = 12*LX/NX; -- local DEN_JUMP = 0.4*LX; -- local DEN_GRAD = 0.2*LX; -- local AtX0 = 2./math.pi*math.atan((-DEN_JUMP)/DEN_GRAD); -- local AtLX = 2./math.pi*math.atan((LX-DEN_JUMP-X0)/DEN_GRAD); -- local DenCof = 1./(AtLX-AtX0); -- local dens1 = DenCof*(2./math.pi*math.atan((x-DEN_JUMP)/DEN_GRAD)-AtX0); return N0 --*dens1 end InitB0=function(x,y,z) return {0,0,Btor} end InitValue={ E=function(x,y,z) ---[[ local res = 0.0; for i=1,20 do res=res+math.sin(x/LX*TWOPI* i); end; return {res,res,res} end --[[ --]] -- E = 0.0 , J = 0.0 , B = InitB0 , ne = InitN0 } Grid= { Type="RectMesh", UnitSystem={Type="SI"}, Topology= { Type="RectMesh", Dimensions={NX,NY,NZ}, -- number of grid, now only first dimension is valid }, Geometry= { Type="Origin_DxDyDz", Min={0.0,0.0,0.0}, Max={LX,LY,LZ}, --dt= 2.0*math.pi/omega_ci/100.0 }, -- dt= TWOPI/omeaga_pe dt= 0.5*LX/NX/c -- time step } --[[ Model= { {Type="Vacuum",Region={{0.2*LX,0,0},{0.8*LX,0,0}},Op="Push"}, {Type="Plasma", Select=function(x,y,z) return x>1.0 and x<2.0 end ,Op="Register"}, } --]] ---[[ Particles={ -- H ={Type="Full",Mass=mp,Charge=e,Temperature=Ti,Density=InitN0,PIC=100 }, -- H ={Type="DeltaF",Mass=mp,Charge=e,Temperature=Ti,Density=InitN0,PIC=100 } ele ={Type="DeltaF",Mass=me,Charge=-e,Temperature=Te,Density=InitN0,PIC=100 } } --]] FieldSolver= { ColdFluid= { Species= { -- H={Name="H",Mass =mp,Charge=e, Density=InitN0 }, -- ele={Name="ele",Mass =me,Charge=-e, Density=InitN0 } , } }, --[[ PML= {Min={0.1*LX,0.1*LY,0.1*LZ},Max={0.9*LX,0.9*LY,0.9*LZ}} --]] } Constraints= { --[[ { DOF="E",IsHard=true, Select={Type="Boundary", Material="Vacuum" }, Value= 0 }, { DOF="J", Range={ {0.5*LX,0,0}}, IsHard=true, Value=function(t,x,y,z) local tau = t*omega_ext return { 0,math.sin(tau),0} end } --]] -- *(1-math.exp(-tau*tau) -- { -- DOF="J", -- Select={Type="Media", Tag="Vacuum"}, -- Value= 0 -- }, -- { -- DOF="Particles", -- Select={Type="Media", Tag="Vacuum"}, -- Value= "Absorb" -- }, } -- The End ---------------------------------------
bsd-3-clause
medialab-prado/Interactivos-15-Ego
minetest-ego/games/adventuretest/mods/physics/init.lua
1
1742
-- a Mod for keeping track of a player's current -- physics properties and allows building layers of -- physics across multiple mods -- physics persist across sessions and server shutdowns physics = {} function physics.adjust_physics(player,_physics) local name = player:get_player_name() for p,v in pairs(_physics) do pd.increment(name,p,v) end physics.apply(player,name) end function physics.apply(player,name,dtime) if player ~= nil then if pd.get(name,"frozen") ~= true then local o = physics.get_player_physics(name) player:set_physics_override(o) end end end function physics.freeze_player(name) local player = minetest.get_player_by_name(name) pd.set(name,"frozen",true) player:set_physics_override({speed=0,jump=0}) end function physics.unfreeze_player(name) local player = minetest.get_player_by_name(name) pd.set(name,"frozen",false) physics.apply(player,name) end function physics.remove_item_physics(player,item) if minetest.registered_items[item] ~= nil then if minetest.registered_items[item].physics ~= nil then local physics_adj = {} for k,v in pairs(minetest.registered_items[item].physics) do physics_adj[k] = v * -1 end physics.adjust_physics(player,physics_adj) end end end function physics.get_player_physics(name) local o = {} o["speed"] = pd.get_number(name,"speed") o["jump"] = pd.get_number(name,"jump") o["gravity"] = pd.get_number(name,"gravity") return o end function physics.apply_item_physics(player,item) if minetest.registered_items[item] ~= nil then if minetest.registered_items[item].physics ~= nil then physics.adjust_physics(player,minetest.registered_items[item].physics) end end end adventuretest.register_pl_hook(physics.apply,30)
mit
medialab-prado/Interactivos-15-Ego
minetest-ego/games/adventuretest/mods/mg_villages/spawn_player.lua
1
1525
function mg_villages.spawnplayer(player) if( minetest.setting_get("static_spawnpoint")) then return; end -- make sure the village types are initialized if( not( mg_villages.village_types )) then mg_villages.init_weights(); end local noise1 = minetest.get_perlin(12345, 6, 0.5, 256) local min_dist = math.huge local min_pos = game_origin for bx = -20, 20 do for bz = -20, 20 do local minp = {x = min_pos.x + bx, y = -32, z = min_pos.z + bz} for _, village in ipairs(mg_villages.villages_at_point(minp, noise1)) do if math.abs(village.vx) + math.abs(village.vz) < min_dist then min_pos = {x = village.vx, y = village.vh + 2, z = village.vz} -- some villages are later adjusted in height; adapt these changes local village_id = tostring( village.vx )..':'..tostring( village.vz ); if( mg_villages.all_villages[ village_id ] and mg_villages.all_villages[ village_id ].optimal_height ) then min_pos.y = mg_villages.all_villages[ village_id ].vh + 2; -- the first villages will have a height of 1 in order to make sure that the player does not end up embedded in stone else min_pos.y = 1+2; end min_dist = math.abs(village.vx) + math.abs(village.vz) end end end end player:setpos(min_pos) local name = player:get_player_name() pd.set(name,"homepos",min_pos) end mg_villages.on_newplayer = function(player) mg_villages.spawnplayer(player) end --minetest.register_on_respawnplayer(function(player) --spawnplayer(player) --return true --end)
mit
Jennal/cocos2dx-3.2-qt
cocos/scripting/lua-bindings/auto/api/CCBReader.lua
6
3794
-------------------------------- -- @module CCBReader -- @extend Ref -- @parent_module cc -------------------------------- -- @function [parent=#CCBReader] addOwnerOutletName -- @param self -- @param #string str -------------------------------- -- @function [parent=#CCBReader] getOwnerCallbackNames -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBReader] addDocumentCallbackControlEvents -- @param self -- @param #int eventtype -------------------------------- -- @function [parent=#CCBReader] setCCBRootPath -- @param self -- @param #char char -------------------------------- -- @function [parent=#CCBReader] addOwnerOutletNode -- @param self -- @param #cc.Node node -------------------------------- -- @function [parent=#CCBReader] getOwnerCallbackNodes -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBReader] readSoundKeyframesForSeq -- @param self -- @param #cc.CCBSequence ccbsequence -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#CCBReader] getCCBRootPath -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#CCBReader] getOwnerCallbackControlEvents -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBReader] getOwnerOutletNodes -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBReader] readUTF8 -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#CCBReader] addOwnerCallbackControlEvents -- @param self -- @param #int eventtype -------------------------------- -- @function [parent=#CCBReader] getOwnerOutletNames -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBReader] setAnimationManager -- @param self -- @param #cc.CCBAnimationManager ccbanimationmanager -------------------------------- -- @function [parent=#CCBReader] readCallbackKeyframesForSeq -- @param self -- @param #cc.CCBSequence ccbsequence -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#CCBReader] getAnimationManagersForNodes -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBReader] getNodesWithAnimationManagers -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBReader] getAnimationManager -- @param self -- @return CCBAnimationManager#CCBAnimationManager ret (return value: cc.CCBAnimationManager) -------------------------------- -- @function [parent=#CCBReader] setResolutionScale -- @param self -- @param #float float -------------------------------- -- @overload self, cc.CCBReader -- @overload self, cc.NodeLoaderLibrary, cc.CCBMemberVariableAssigner, cc.CCBSelectorResolver, cc.NodeLoaderListener -- @overload self -- @function [parent=#CCBReader] CCBReader -- @param self -- @param #cc.NodeLoaderLibrary nodeloaderlibrary -- @param #cc.CCBMemberVariableAssigner ccbmembervariableassigner -- @param #cc.CCBSelectorResolver ccbselectorresolver -- @param #cc.NodeLoaderListener nodeloaderlistener return nil
mit
rlcevg/Zero-K
units/corthud.lua
6
5705
unitDef = { unitname = [[corthud]], name = [[Thug]], description = [[Shielded Assault Bot]], acceleration = 0.25, activateWhenBuilt = true, brakeRate = 0.22, buildCostEnergy = 180, buildCostMetal = 180, buildPic = [[CORTHUD.png]], buildTime = 180, canAttack = true, canGuard = true, canMove = true, canPatrol = true, category = [[LAND]], corpse = [[DEAD]], customParams = { description_bp = [[Robô assaltante]], description_fr = [[Robot d'Assaut]], description_de = [[Sturmroboter mit Schild]], description_pl = [[Bot szturmowy z tarcza]], helptext = [[Weak on its own, the Thug makes an excellent screen for Outlaws and Rogues. The linking shield gives Thugs strength in numbers, but can be defeated by AoE weapons or focus fire.]], helptext_bp = [[Thug é um robô assaultante. Pode resistir muito dano, e é útil como um escudo para os mais fracos porém mais potentes Rogues.]], helptext_fr = [[Le Thug est extraordinairement r?sistant pour sa taille. Si ses canons ? plasma n'ont pas la pr?cision requise pour abattre les cibles rapides, il reste n?anmoins un bouclier parfait pour des unit?s moins solides telles que les Rogues.]], helptext_de = [[Der Thug ist zwar für sich alleine ziemlich schwach, doch bietet er für Rogues und Outlaws eine gute Abschirmung. Der sich verbindende Schild erzeugt mehr Stärke, sobald sich mehrere Thugs zusammenschließen, kann aber durch AoE Waffen oder fokusiertes Feuer geschlagen werden.]], helptext_pl = [[Chociaz pojedynczo jest slaby, Thug moze dzielic tarcze z innymi jednostkami w nia wyposazona (w tym z innymi Thugami), co znacznie zwieksza jego potencjal w duzych ilosciach. Tarcza swietnie nadaje sie tez do chronienia delikatniejszych jednostek, ktore same nie maja tarczy, jak na przyklad Rogue lub Outlaw.]], }, explodeAs = [[BIG_UNITEX]], footprintX = 2, footprintZ = 2, iconType = [[walkerassault]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, maxDamage = 960, maxSlope = 36, maxVelocity = 1.925, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[KBOT2]], noChaseCategory = [[TERRAFORM FIXEDWING SUB]], objectName = [[thud.s3o]], onoffable = false, script = [[corthud.lua]], seismicSignature = 4, selfDestructAs = [[BIG_UNITEX]], sfxtypes = { explosiongenerators = { [[custom:THUDMUZZLE]], [[custom:THUDSHELLS]], [[custom:THUDDUST]], }, }, sightDistance = 420, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ComTrack]], trackWidth = 22, turnRate = 2000, upright = true, weapons = { { def = [[THUD_WEAPON]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, { def = [[SHIELD]], }, }, weaponDefs = { SHIELD = { name = [[Energy Shield]], damage = { default = 10, }, exteriorShield = true, shieldAlpha = 0.2, shieldBadColor = [[1 0.1 0.1]], shieldGoodColor = [[0.1 0.1 1]], shieldInterceptType = 3, shieldPower = 1250, shieldPowerRegen = 16, shieldPowerRegenEnergy = 0, shieldRadius = 80, shieldRepulser = false, shieldStartingPower = 850, smartShield = true, texture1 = [[shield3mist]], visibleShield = true, visibleShieldHitFrames = 4, visibleShieldRepulse = true, weaponType = [[Shield]], }, THUD_WEAPON = { name = [[Light Plasma Cannon]], areaOfEffect = 36, craterBoost = 0, craterMult = 0, damage = { default = 170, planes = 170, subs = 8, }, explosionGenerator = [[custom:MARY_SUE]], impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, range = 280, reloadtime = 4, soundHit = [[explosion/ex_med5]], soundStart = [[weapon/cannon/cannon_fire5]], turret = true, weaponType = [[Cannon]], weaponVelocity = 200, }, }, featureDefs = { DEAD = { description = [[Wreckage - Thug]], blocking = true, damage = 960, energy = 0, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, metal = 72, object = [[thug_d.s3o]], reclaimable = true, reclaimTime = 72, }, HEAP = { description = [[Debris - Thug]], blocking = false, damage = 960, energy = 0, footprintX = 2, footprintZ = 2, metal = 36, object = [[debris2x2c.s3o]], reclaimable = true, reclaimTime = 36, }, }, } return lowerkeys({ corthud = unitDef })
gpl-2.0
EliHar/Pattern_recognition
openface1/training/torch-TripletEmbedding/test.lua
3
1950
-------------------------------------------------------------------------------- -- Test function for TripletEmbeddingCriterion -------------------------------------------------------------------------------- -- Alfredo Canziani, Apr/May 15 -------------------------------------------------------------------------------- cuda = false require 'nn' require 'TripletEmbedding' if cuda then require 'cutorch' torch.setdefaulttensortype('torch.CudaTensor') cutorch.manualSeedAll(0) end colour = require 'trepl.colorize' local b = colour.blue torch.manualSeed(0) batch = 3 embeddingSize = 5 -- Ancore embedding batch a = torch.rand(batch, embeddingSize) print(b('ancore embedding batch:')); print(a) -- Positive embedding batch p = torch.rand(batch, embeddingSize) print(b('positive embedding batch:')); print(p) -- Negativep embedding batch n = torch.rand(batch, embeddingSize) print(b('negative embedding batch:')); print(n) -- Testing the loss function forward and backward loss = nn.TripletEmbeddingCriterion(.2) if cuda then loss = loss:cuda() end print(colour.red('loss: '), loss:forward({a, p, n}), '\n') gradInput = loss:backward({a, p, n}) print(b('gradInput[1]:')); print(gradInput[1]) print(b('gradInput[2]:')); print(gradInput[2]) print(b('gradInput[3]:')); print(gradInput[3]) -- Jacobian test d = 1e-6 jacobian = {} zz = torch.Tensor{ {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, } for k = 1, 3 do jacobian[k] = torch.zeros(a:size()) z = zz[k] for i = 1, a:size(1) do for j = 1, a:size(2) do pert = torch.zeros(a:size()) pert[i][j] = d outA = loss:forward({a - pert*z[1], p - pert*z[2], n - pert*z[3]}) outB = loss:forward({a + pert*z[1], p + pert*z[2], n + pert*z[3]}) jacobian[k][i][j] = (outB - outA)/(2*d) end end end print(b('jacobian[1]:')); print(jacobian[1]) print(b('jacobian[2]:')); print(jacobian[2]) print(b('jacobian[3]:')); print(jacobian[3])
mit
ViolyS/RayUI_VS
Interface/AddOns/RayUI/modules/nameplates/elements/NPCTitle.lua
2
1646
---------------------------------------------------------- -- Load RayUI Environment ---------------------------------------------------------- RayUI:LoadEnv("NamePlates") local mod = _NamePlates local LSM = LibStub("LibSharedMedia-3.0") local tooltip = CreateFrame("GameTooltip", "RayUI_NPCTitle", UIParent, "GameTooltipTemplate") tooltip:SetPoint("CENTER") tooltip:SetSize(200, 200) GameTooltip_SetDefaultAnchor(tooltip, UIParent) function mod:UpdateElement_NPCTitle(frame) frame.NPCTitle:SetText("") if not UnitIsPlayer(frame.unit) and not UnitPlayerControlled(frame.unit) and not UnitIsUnit("target", frame.unit) and not self.db.units[frame.UnitType].healthbar then tooltip:SetOwner(UIParent, "ANCHOR_NONE") tooltip:SetUnit(frame.unit) tooltip:Show() local title = RayUI_NPCTitleTextLeft2:GetText(); tooltip:Hide() if not title or title:find('^Level ') or title:find('^'..LEVEL) then return end frame.NPCTitle:SetText(title) local reactionType = UnitReaction(frame.unit, "player") local r, g, b if(reactionType == 4) then r, g, b = unpack(RayUF.colors.reaction[4]) elseif(reactionType > 4) then r, g, b = unpack(RayUF.colors.reaction[5]) else r, g, b = unpack(RayUF.colors.reaction[1]) end frame.NPCTitle:SetTextColor(r - 0.1, g - 0.1, b - 0.1) end end function mod:ConfigureElement_NPCTitle(frame) local title = frame.NPCTitle title:SetJustifyH("CENTER") title:SetPoint("TOP", frame.Name, "BOTTOM", 0, -2) title:SetFont(LSM:Fetch("font", R["media"].font), self.db.fontsize, "OUTLINE") end function mod:ConstructElement_NPCTitle(frame) return frame:CreateFontString(nil, "OVERLAY") end
mit
EliHar/Pattern_recognition
torch1/install/share/lua/5.1/nn/DepthConcat.lua
9
4601
------------------------------------------------------------------------ --[[ DepthConcat ]]-- -- Concatenates the output of Convolutions along the depth dimension -- (nOutputFrame). This is used to implement the DepthConcat layer -- of the Going deeper with convolutions paper : -- http://arxiv.org/pdf/1409.4842v1.pdf -- The normal Concat Module can't be used since the spatial dimensions -- of tensors to be concatenated may have different values. To deal with -- this, we select the largest spatial dimensions and add zero-padding -- around the smaller dimensions. ------------------------------------------------------------------------ local DepthConcat, _ = torch.class('nn.DepthConcat', 'nn.Concat') function DepthConcat:windowNarrow(output, currentOutput, offset) local outputWindow = output:narrow(self.dimension, offset, currentOutput:size(self.dimension)) for dim=1,self.size:size(1) do local currentSize = currentOutput:size(dim) if dim ~= self.dimension and self.size[dim] ~= currentSize then -- 5x5 vs 3x3 -> start = [(5-3)/2] + 1 = 2 (1 pad each side) -- 9x9 vs 5x5 -> start = [(9-5)/2] + 1 = 3 (2 pad each side) -- 9x9 vs 4x4 -> start = [(9-4)/2] + 1 = 3.5 (2 pad, 3 pad) local start = math.floor(((self.size[dim] - currentSize) / 2) + 1) outputWindow = outputWindow:narrow(dim, start, currentSize) end end return outputWindow end function DepthConcat:updateOutput(input) local outs = {} for i=1,#self.modules do local currentOutput = self:rethrowErrors(self.modules[i], i, 'updateOutput', input) outs[i] = currentOutput if i == 1 then self.size:resize(currentOutput:dim()):copy(currentOutput:size()) else self.size[self.dimension] = self.size[self.dimension] + currentOutput:size(self.dimension) for dim=1,self.size:size(1) do if dim ~= self.dimension then -- take the maximum size (shouldn't change anything for batch dim) self.size[dim] = math.max(self.size[dim], currentOutput:size(dim)) end end end end self.output:resize(self.size):zero() --zero for padding local offset = 1 for i,module in ipairs(self.modules) do local currentOutput = outs[i] local outputWindow = self:windowNarrow(self.output, currentOutput, offset) outputWindow:copy(currentOutput) offset = offset + currentOutput:size(self.dimension) end return self.output end function DepthConcat:updateGradInput(input, gradOutput) self.gradInput:resizeAs(input) local offset = 1 for i,module in ipairs(self.modules) do local currentOutput = module.output local gradOutputWindow = self:windowNarrow(gradOutput, currentOutput, offset) local currentGradInput = self:rethrowErrors(module, i, 'updateGradInput', input, gradOutputWindow) if i==1 then self.gradInput:copy(currentGradInput) else self.gradInput:add(currentGradInput) end offset = offset + currentOutput:size(self.dimension) end return self.gradInput end function DepthConcat:accGradParameters(input, gradOutput, scale) scale = scale or 1 local offset = 1 for i,module in ipairs(self.modules) do local currentOutput = module.output local gradOutputWindow = self:windowNarrow(gradOutput, currentOutput, offset) self:rethrowErrors(module, i, 'accGradParameters', input, gradOutputWindow, scale) offset = offset + currentOutput:size(self.dimension) end end function DepthConcat:backward(input, gradOutput, scale) self.gradInput:resizeAs(input) scale = scale or 1 local offset = 1 for i,module in ipairs(self.modules) do local currentOutput = module.output local gradOutputWindow = self:windowNarrow(gradOutput, currentOutput, offset) local currentGradInput = self:rethrowErrors(module, i, 'backward', input, gradOutputWindow) if i==1 then self.gradInput:copy(currentGradInput) else self.gradInput:add(currentGradInput) end offset = offset + currentOutput:size(self.dimension) end return self.gradInput end function DepthConcat:accUpdateGradParameters(input, gradOutput, lr) local offset = 1 for i,module in ipairs(self.modules) do local currentOutput = module.output local gradOutputWindow = self:windowNarrow(gradOutput, currentOutput, offset) self:rethrowErrors(module, i, 'accUpdateGradParameters', input, gradOutputWindow, lr) offset = offset + currentOutput:size(self.dimension) end end
mit
joaocc/ta3d-git
src/netserver/netserver.lua
2
35514
#!/usr/bin/lua if log_file == nil then log_file = io.open("netserver.log","w") end function log_debug(...) local msg = os.date() .. " [debug] " .. table.concat({...}," ") print(msg) log_file:write(msg) log_file:write("\n") log_file:flush() end function log_error(...) local msg = os.date() .. " [error] " .. table.concat({...}," ") print(msg) log_file:write(msg) log_file:write("\n") log_file:flush() end function copyFile(src, dst) local file_src = io.open(src,"r") if file_src == nil then log_error("copyFile failed: could not open ", src) return end local file_dst = io.open(dst,"w") if file_dst == nil then file_src:close() log_error("copyFile failed: could not open ", dst) return end local data = file_src:read("*a") file_dst:write(data) file_dst:flush() data = nil file_src:close() file_dst:close() end -- parse a command sent by a client (command arg0 "arg \" 1" ==> {"command","arg0","arg \" 1"} function parseCommand(msg) local args = {} local inString = false local current = "" local discard = false for i = 1, string.len(msg) do if not inString then if msg:sub(i, i) == "\"" or msg:sub(i, i) == " " then if current ~= "" then table.insert(args, current) current = "" end inString = (msg:sub(i, i) == "\"") else current = current .. msg:sub(i, i) end discard = false else if not discard then if msg:sub(i, i) == "\"" then table.insert(args, current) current = "" inString = false elseif msg:sub(i, i) == "\\" and i + 1 < string.len(msg) then i = i + 1 current = current .. msg:sub(i, i) discard = true else current = current .. msg:sub(i, i) end else discard = false end end end if current ~= "" then table.insert(args, current) end return args end SERVER_VERSION = "TA3D netserver 0.1.0" STATE_CONNECTING = 0 STATE_CONNECTED = 1 STATE_DISCONNECTED = 2 -- initialize Mysql stuffs require("luasql.mysql") if luasql == nil or luasql.mysql == nil then log_error("luasql not found") os.exit() end mysql = luasql.mysql() if mysql == nil then log_error("could not initialize luasql.mysql") os.exit() end cfg_file = io.open("db.cfg") if cfg_file ~= nil then db_host = cfg_file:read() db_user = cfg_file:read() db_pass = cfg_file:read() cfg_file:close() else db_host = "localhost" db_user = "user" db_pass = "password" end netserver_db = mysql:connect("netserver", db_user, db_pass, db_host) if netserver_db == nil then log_error("could not connect to database") os.exit() end function mysql_reconnect() -- when connection to MySQL database is closed, let's reopen it :D log_debug("reconnecting to MySQL server") netserver_db:close() log_debug("connection to MySQL server closed") netserver_db = mysql:connect("netserver", db_user, db_pass, db_host) if netserver_db then log_debug("connected to MySQL server") else log_error("impossible to connect to MySQL server!") end end function mysql_safe_request(req) local cur, err = netserver_db:execute(req) if err ~= nil then log_error( err ) log_debug( "I am going to reconnect to MySQL server and retry request : '" .. req .. "'") mysql_reconnect() cur, err = netserver_db:execute(req) end return cur, err end -- do not erase clients data if set (to allow live reloading of server code) -- the login table (since it's a hash table it's much faster than going through the whole clients table) if clients_login == nil then clients_login = {} end -- the socket table ==> this will prevent going trough all sockets if they are not being used if socket_table == nil then socket_table = {} end if socket_list == nil then socket_list = {} end -- the chan table if chans == nil then chans = {} end if chans_len == nil then chans_len = {} end -- the game server table if game_server_table == nil then game_server_table = {} end function fixSQL(str) local safe_str, n = string.gsub(str, "['\"\\]", "\\%1") return safe_str end function escape(str) local escaped_str, n = string.gsub(str, "[\"\\]", "\\%1") escaped_str, n = string.gsub(escaped_str, "\n", "\\n") return escaped_str end function removeSocket(sock) socket_table[sock] = nil for i, s in ipairs(socket_list) do if s == sock then table.remove(socket_list, i) break end end end -- Tell a client (or all clients if nill) everything he needs about a server function sendServerInfo(client, server) local msg = "SERVER NAME \"" .. escape(server.name) .. "\" MOD \"" .. escape(server.mod) .. "\" HOST \"" .. escape(server.host) .. "\" MAP \"" .. escape(server.map) .. "\" VERSION \"" .. escape(server.version) .. "\" SLOTS \"" .. escape(server.slots) .. "\" OWNER \"" .. escape(server.owner) .. "\"" if client == nil then sendAll(msg) else client:send(msg) end end -- Close the given server function closeServer(server) sendAll("UNSERVER \"" .. escape(server.name) .. "\"") if server.players ~= nil then for k, v in pairs(server.players) do if clients_login[v] ~= nil then clients_login[v]:send("UNJOIN \"" .. escape(server.host) .. "\"") clients_login[v].server = nil joinChan(clients_login[v]) end end end game_server_table[server.name] = nil clients_login[server.owner].server = nil end -- Join a server function joinServer(server, client) if server == nil then return end if tonumber(server.slots) > 0 then server.slots = tostring(tonumber(server.slots) - 1) table.insert(server.players, client.login) client:send("JOIN \"" .. escape(server.host) .. "\"") leaveChan(client) else client:send("ERROR Server is full") end end -- Leave a server function unjoinServer(server, client) if server == nil then return elseif server.owner == client.login then return closeServer(server) end local found = false for k, v in ipairs(server.players) do if v == client.login then found = k end end if found ~= false then if found < #(server.players) then server.players[found] = server.players[#(server.players)] else server.players[found] = nil end server.slots = tostring(tonumber(server.slots) + 1) client:send("UNJOIN \"" .. escape(server.host) .. "\"") joinChan(client) end end -- Tell everyone on client's chan that client is there function joinChan(client) if client.state ~= STATE_CONNECTED then return end -- identify * to nil if client.chan == nil then client.chan = "*" end if chans[client.chan] == nil then chans[client.chan] = {} chans_len[client.chan] = 0 sendAll("CHAN \"" .. escape(client.chan) .. "\"") end chans_len[client.chan] = chans_len[client.chan] + 1 chans[client.chan][client.login] = true for c, v in pairs(chans[client.chan]) do if c ~= client.login then -- I guess the client knows he's joining the chan ... (also would crash at login time) clients_login[c]:send("USER \"" .. escape(client.login) .. "\"") end end end -- Tell everyone on client's chan that client is leaving chan function leaveChan(client) if client.state ~= STATE_CONNECTED then return end if client.chan == nil then client.chan = "*" end if chans[client.chan] ~= nil and chans_len[client.chan] == 1 then chans[client.chan] = nil chans_len[client.chan] = nil sendAll("DECHAN \"" .. escape(client.chan) .. "\"") else chans_len[client.chan] = chans_len[client.chan] - 1 chans[client.chan][client.login] = nil for c, v in pairs(chans[client.chan]) do if c ~= client.login then -- I guess the client knows he's leaving the chan ... clients_login[c]:send("LEAVE \"" .. escape(client.login) .. "\"") end end end end -- Returns a table containing all the results returned by MySQL function getFromDB(req) local cur, err = mysql_safe_request(req) if cur == nil or cur == 0 or cur:numrows() == 0 then log_error( err ) return {} end local table = {} local nbResults = cur:numrows() for i = 1, nbResults do table[i] = cur:fetch({}, "a") end return table end -- Identify a client, connect it if password and login match function identifyClient(client, password) local cur, err = mysql_safe_request("SELECT * FROM `clients` WHERE `login`='" .. fixSQL(client.login) .. "' AND `password`=PASSWORD('" .. fixSQL(password) .. "') AND `banned`=0") if cur == nil or cur == 0 or cur:numrows() ~= 1 then log_error( err ) return false end local row = cur:fetch({}, "a") client.ID = tonumber( row.ID ) client.admin = tonumber( row.admin ) return true end -- Register a new client if there is no account with the same name function registerClient(client, password) local cur, err = mysql_safe_request("SELECT * FROM `clients` WHERE `login`='" .. fixSQL(client.login) .. "'") if cur == nil or cur == 0 or cur:numrows() ~= 0 then log_error( err ) return false end cur, err = mysql_safe_request("INSERT INTO clients(`login`, `password`,`ID`,`admin`,`banned`) VALUES('" .. fixSQL(client.login) .. "', PASSWORD('" .. fixSQL(password) .. "'),NULL,'0','0')") if cur == nil or cur == 0 then log_error( err ) return false end return identifyClient(client, password) end -- Ban a client function banClient(login) mysql_safe_request("UPDATE `clients` SET `banned` = '1' WHERE `login`='" .. fixSQL(login) .. "'") if clients_login[login] then clients_login[login]:send("MESSAGE you have been banned") clients_login[login]:disconnect() end end -- Unban a client function unbanClient(login) mysql_safe_request("UPDATE `clients` SET `banned` = '0' WHERE `login`='" .. fixSQL(login) .. "'") end -- Kill a client function killClient(login) mysql_safe_request("DELETE FROM `clients` WHERE `login`='" .. fixSQL(login) .. "'") if clients_login[login] then clients_login[login]:send("MESSAGE you have been killed") clients_login[login]:disconnect() end end -- Get a value from the mysql database (info table) function getValue(name) local cur, err = mysql_safe_request("SELECT value FROM `info` WHERE name='" .. fixSQL(name) .. "'") if cur == nil or cur == 0 or cur:numrows() ~= 1 then log_error( err ) return "" end local row = cur:fetch({}, "a") return row.value end -- Broadcast a message to all admins function sendAdmins(msg) for id, s in ipairs(socket_list) do local c = socket_table[s] if c ~= nil and c.state == STATE_CONNECTED and c.admin == 1 then c:send(msg) end end end -- Send all function sendAll(msg) for id, s in ipairs(socket_list) do local c = socket_table[s] if c ~= nil and c.state == STATE_CONNECTED then c:send(msg) end end end -- this is where the magic takes place function processClient(client) while true do local msg, err = client:receive() -- if an error is detected, close the connection if err ~= nil and err ~= "timeout" then log_debug("socket error:", err) client:disconnect() return end -- what is client telling us ? if msg ~= nil then if client.login == nil then log_debug(client.sock:getpeername() .. " (nil) sent: ", msg) else log_debug(client.sock:getpeername() .. " (" .. client.login .. ") sent: ", msg) end if msg == "DISCONNECT" then client:disconnect() return end -- parse words args = parseCommand(msg) -- parsing error: let the main loop restart this function for us if #args == 0 then return end if client.state == STATE_CONNECTING then -- Client is not connected -- login command: CLIENT VERSION if args[1] == "CLIENT" then client.version = table.concat(args, " ", 2) log_debug("client version ", client.version, " registered") if client.version ~= getValue("LAST_VERSION") then log_debug("new version available, sending update notification") client:send("MESSAGE " .. getValue("UPDATE_NOTIFICATION")) end -- login command: LOGIN USER PASSWORD elseif args[1] == "LOGIN" and #args == 3 then if client.version == nil then client:send("ERROR client version unknown, send version first") else client.login = args[2] if clients_login[client.login] ~= nil then client.login = nil client:send("ERROR session already opened") else local password = args[3] local success = identifyClient(client, password) if success then client:connect() else client.login = nil client:send("ERROR login or password incorrect") end end end -- login command: REGISTER USER PASSWORD elseif args[1] == "REGISTER" and #args == 3 then if client.version == nil then client:send("ERROR client version unknown, send version first") else client.login = args[2] local password = args[3] local success = registerClient(client, password) if success then client:connect() else client.login = nil client:send("ERROR login already used") end end -- GET MOD LIST : client is asking for the mod list elseif args[1] == "GET" and #args >= 3 and args[2] == "MOD" and args[3] == "LIST" then local mod_list = getFromDB("SELECT * FROM mods") client:send("CLEAR MOD LIST") -- this is used to force refresh of mod list for i, mod in ipairs(mod_list) do client:send("MOD \"" .. escape(mod.ID) .. "\" \"" .. escape(mod.version) .. "\" \"" .. escape(mod.name) .. "\" \"" .. escape(mod.file) .. "\" \"" .. escape(mod.author) .. "\" \"" .. escape(mod.comment) .. "\"") end else client:send("ERROR could not parse request") end elseif client.state == STATE_CONNECTED then -- Client is connected -- GET USER LIST : client is asking for the client list (clients on the same chan) if args[1] == "GET" and #args >= 3 and args[2] == "USER" and args[3] == "LIST" then if client.chan == nil then client.chan = "*" end for c, v in pairs(chans[client.chan]) do client:send("USER \"" .. escape(c) .. "\"") end -- GET MOD LIST : client is asking for the mod list elseif args[1] == "GET" and #args >= 3 and args[2] == "MOD" and args[3] == "LIST" then local mod_list = getFromDB("SELECT * FROM mods") client:send("CLEAR MOD LIST") -- this is used to force refresh of mod list for i, mod in ipairs(mod_list) do client:send("MOD \"" .. escape(mod.ID) .. "\" \"" .. escape(mod.version) .. "\" \"" .. escape(mod.name) .. "\" \"" .. escape(mod.file) .. "\" \"" .. escape(mod.author) .. "\" \"" .. escape(mod.comment) .. "\"") end -- GET CHAN LIST : client is asking for the chan list elseif args[1] == "GET" and #args >= 3 and args[2] == "CHAN" and args[3] == "LIST" then for c, v in pairs(chans) do client:send("CHAN \"" .. escape(c) .. "\"") end -- GET CLIENT LIST : list ALL clients elseif args[1] == "GET" and #args >= 3 and args[2] == "CLIENT" and args[3] == "LIST" then for id, s in ipairs(socket_list) do local c = socket_table[s] if c ~= nil and c.state == STATE_CONNECTED then client:send("CLIENT \"" .. escape(c.login) .. "\"") end end -- GET SERVER LIST : client is asking for the server list elseif args[1] == "GET" and #args >= 3 and args[2] == "SERVER" and args[3] == "LIST" then client:send("CLEAR SERVER LIST") -- this is used to force refresh of server list for i, server in pairs(game_server_table) do sendServerInfo(client, server) end -- UNSERVER : client is closing its server elseif args[1] == "UNSERVER" then if client.server ~= nil and client.server.owner == client.login then closeServer(client.server) end -- SERVER : client is creating/updating a server elseif args[1] == "SERVER" then -- get the basic info about the server local new_server = {name="", mod="", host=string.match(client.sock:getpeername(),"%d+%.%d+%.%d+%.%d+"), slots=0, map="", owner=client.login, version=client.version, players={client.login}} local discard = false for i, v in ipairs(args) do if not discard and i < #args then if v == "NAME" then new_server.name = args[i+1] discard = true elseif v == "MOD" then new_server.mod = args[i+1] discard = true elseif v == "SLOTS" then new_server.slots = args[i+1] discard = true elseif v == "MAP" then new_server.map = args[i+1] discard = true end else discard = false end end if new_server.name == "" then if client.server ~= nil then new_server.name = client.server.name else client:send("ERROR No server name specified when creating a server!") return end end if new_server.mod == "" and client.server ~= nil then new_server.mod = client.server.mod end if game_server_table[new_server.name] ~= nil and game_server_table[new_server.name].owner ~= client.login then client:send("ERROR Can't create server : there is already a server with this name!") client.server = nil else if client.server ~= nil and client.server.name ~= new_server.name then -- this is important since it prevents a client from flooding the game server list closeServer(client.server) end if game_server_table[new_server.name] == nil then -- send back this information to all clients in order to update their data sendServerInfo(nil, new_server) game_server_table[new_server.name] = new_server client:send("HOST"); else -- send back this updated information to all clients in order to update their data if game_server_table[new_server.name].mod ~= new_server.mod or game_server_table[new_server.name].slots ~= new_server.slots or game_server_table[new_server.name].map ~= new_server.map then sendServerInfo(nil, new_server) end game_server_table[new_server.name].mod = new_server.mod game_server_table[new_server.name].slots = new_server.slots game_server_table[new_server.name].map = new_server.map end client.server = game_server_table[new_server.name] end -- JOIN server : client is joining a server elseif args[1] == "JOIN" and #args == 2 then if client.server ~= nil then client:send("ERROR You have already joined a server") elseif game_server_table[args[2]] == nil then client:send("ERROR Could not join server : server doesn't exist") else joinServer(game_server_table[args[2]], client) end -- UNJOIN server : client is leaving a server elseif args[1] == "UNJOIN" then if client.server == nil then client:send("ERROR No server to leave") else unjoinServer(client.server, client) end -- SEND to msg : client is sending a message to another client elseif args[1] == "SEND" and #args >= 3 then if args[2] ~= nil and args[2] ~= client.login and clients_login[args[2]] ~= nil and clients_login[args[2]].state == STATE_CONNECTED then clients_login[args[2]]:send("MSG \"" .. escape(client.login) .. "\" \"" .. escape(table.concat(args, " ", 3)) .. "\"") end -- SENDALL msg : client is sending a message to other clients in the same chan elseif args[1] == "SENDALL" and #args >= 2 then if client.chan == nil then client.chan = "*" end if chans[client.chan] ~= nil then for c, v in pairs(chans[client.chan]) do if c ~= client.login then clients_login[c]:send("MSG \"" .. escape(client.login) .. "\" \"" .. escape(table.concat(args, " ", 2)) .. "\"") end end end -- CLOSE server : admin privilege, close a server elseif args[1] == "CLOSE" and #args == 2 then if client.admin == 1 then if game_server_table[args[2]] ~= nil then closeServer(game_server_table[args[2]]) else client:send("ERROR Server not found!") end else client:send("ERROR you don't have the right to do that") end -- KICK user : admin privilege, disconnect someone (self kick works) elseif args[1] == "KICK" and #args == 2 then if client.admin == 1 then if clients_login[args[2]] ~= nil then clients_login[args[2]]:send("MESSAGE You have been kicked") clients_login[args[2]]:disconnect() end else client:send("ERROR you don't have the right to do that") end -- BAN user : admin privilege, disconnect someone and prevent him from reconnecting (self ban works) elseif args[1] == "BAN" and #args == 2 then if client.admin == 1 then banClient(args[2]) else client:send("ERROR you don't have the right to do that") end -- UNBAN user : admin privilege, remove ban flag on a user (self unban works ... but you've been banned you don't get here) elseif args[1] == "UNBAN" and #args == 2 then if client.admin == 1 then unbanClient(args[2]) else client:send("ERROR you don't have the right to do that") end -- KILL user : admin privilege, remove a user account (self kill doesn't work) elseif args[1] == "KILL" and #args == 2 then if client.admin == 1 and client.login ~= args[2] then killClient(args[2]) else client:send("ERROR you don't have the right to do that") end -- RELOAD SERVER : admin privilege, live reload of server code (update server without closing any connection) elseif args[1] == "RELOAD" and args[2] == "SERVER" then if client.admin == 1 then _G.reload = true else client:send("ERROR you don't have the right to do that") end -- SHUTDOWN SERVER : admin privilege, stop server (closes all connections) elseif args[1] == "SHUTDOWN" and args[2] == "SERVER" then if client.admin == 1 then for id = #socket_list, 1, -1 do local s = socket_list[id] if s ~= nil then local c = socket_table[s] if c ~= nil then c:send("MESSAGE Server is being shut down for maintenance, sorry for the inconvenience") c:disconnect() end end end log_debug("Server is being shut down") os.exit() else client:send("ERROR you don't have the right to do that") end -- CRASH SERVER: admin privilege, crash the server (thus resuming previous server version ... be careful with that) elseif args[1] == "CRASH" and args[2] == "SERVER" then if client.admin == 1 then error(table.concat(args," ",3)) else client:send("ERROR you don't have the right to do that") end -- CHAN chan_name: change chan for client elseif args[1] == "CHAN" then leaveChan(client) client.chan = args[2] joinChan(client) else client:send("ERROR could not parse request") end else -- Duhh oO, what are we doing here ? client:disconnect() end end -- let the others access the server too coroutine.yield() end end -- create a new client structure linked to the incoming socket function newClient(incoming) local client = {sock = incoming, state = STATE_CONNECTING, send = function(this,msg) this.sock:send(msg .. "\n") end, receive = function(this) return this.sock:receive() end, ID = nil, login = nil, version = nil, serve = coroutine.wrap(processClient), connect = function(this) clients_login[this.login] = this -- we need this to do fast look ups this.state = STATE_CONNECTED this:send("CONNECTED") joinChan(this) end, disconnect = function(this) if this.server ~= nil then -- leave this server unjoinServer(this.server, this) end if this.login ~= nil then -- allow garbage collection clients_login[this.login] = nil end removeSocket(this.sock) leaveChan(this) -- don't forget to leave the chan! this:send("CLOSE") this.sock:close() this.state = STATE_DISCONNECTED end} client.sock:settimeout(0) client:send("SERVER \"" .. escape(SERVER_VERSION) .. "\"") socket_table[client.sock] = client table.insert(socket_list, client.sock) end --************************************************************************-- -- -- -- TA3D Netserver -- -- -- --************************************************************************-- -- This is the server monitor, it is responsible for warm restart and crash management if _G.reload == nil then log_debug("Server monitor started") local chunks = {} while true do local reloadFile = _G.reload or #chunks == 0 if reloadFile then if _G.reload then log_debug() log_debug("--- Warm restart ---") log_debug() end local chunk = loadfile("netserver.lua") if chunk ~= nil then if _G.reload then sendAdmins("MESSAGE Warm restart in progress") end table.insert(chunks, chunk) else if _G.reload then sendAdmins("MESSAGE Warm restart failed, resuming current version") log_error("could not load netserver.lua! Warm restart failed") log_debug("resuming current server version") else log_error("could not load netserver.lua! Server start failed") end end end -- run the last available chunk (in case it crashes, it'll remove the last one and try with the previous one :) ) if #chunks > 0 then local chunk = chunks[ #chunks ] _G.reload = true local success, msg = pcall(chunk) -- on crash if not success then log_error(msg) log_error("server crashed, resuming previous working version") table.remove(chunks) _G.crashRecovery = true -- on exit (on reload request we just loop and load the new version) elseif _G.reload == nil then break end end end -- we're in monitor mode so don't run the server on exit :p os.exit() end -- Normal server code log_debug("Starting " .. SERVER_VERSION) local socket = require("socket") if socket == nil then log_debug("error: luasocket not found") os.exit() end -- loads the luasocket library if server == nil then server = socket.bind("*", 4240) if server == nil then log_debug("error: could not create a TCP server socket :(") os.exit() end end server:settimeout(0.001) -- If server has been restarted, then update coroutines if _G.reload and #socket_list > 0 then log_debug("warm restart detected, updating clients coroutines and socket_table") for s, c in pairs(socket_table) do c.serve = coroutine.wrap(processClient) end sendAdmins("MESSAGE Warm restart successful") end socket_list[1] = server -- Wow, we've just recovered from a crash :s if _G.crashRecovery then _G.crashRecovery = nil sendAdmins("MESSAGE Server just recovered from a crash") end -- prevent it from restarting in an infinite loop _G.reload = nil while true do local read, write, err = socket.select( socket_list, nil, 10 ) local incoming = server:accept() if incoming ~= nil then log_debug("incoming connection from ", incoming:getpeername() ) -- ok, we have a new client, we add it to the client list newClient(incoming) end for i, s in ipairs(read) do if s ~= server then local c = socket_table[s] if c == nil then if socket_list[s] ~= nil then table.remove(socket_list, socket_list[s]) end socket_list[s] = nil else if c.state == STATE_DISCONNECTED then -- If the client has disconnected, remove it from the clients table removeSocket(c.sock) else -- Serve all clients c:serve() end end end end -- in case we want to reload the server, just return and let the monitor do the job if _G.reload == true then return end end
gpl-2.0
anholt/ValyriaTear
dat/tilesets/mountain_house_exterior.lua
4
11981
tileset = {} tileset.image = "img/tilesets/mountain_house_exterior.png" tileset.num_tile_cols = 16 tileset.num_tile_rows = 16 -- The general walkability of the tiles in the tileset. Zero indicates walkable. One tile has four walkable quadrants listed as: NW corner, NE corner, SW corner, SE corner. tileset.walkability = {} tileset.walkability[0] = {} tileset.walkability[0][0] = { 0, 0, 0, 0 } tileset.walkability[0][1] = { 0, 0, 0, 0 } tileset.walkability[0][2] = { 0, 0, 0, 0 } tileset.walkability[0][3] = { 0, 0, 0, 0 } tileset.walkability[0][4] = { 0, 0, 0, 0 } tileset.walkability[0][5] = { 0, 0, 0, 0 } tileset.walkability[0][6] = { 0, 0, 0, 0 } tileset.walkability[0][7] = { 0, 0, 0, 0 } tileset.walkability[0][8] = { 0, 0, 0, 0 } tileset.walkability[0][9] = { 0, 0, 0, 0 } tileset.walkability[0][10] = { 1, 1, 1, 1 } tileset.walkability[0][11] = { 1, 1, 1, 1 } tileset.walkability[0][12] = { 1, 1, 1, 1 } tileset.walkability[0][13] = { 1, 1, 1, 1 } tileset.walkability[0][14] = { 1, 1, 1, 1 } tileset.walkability[0][15] = { 1, 1, 1, 1 } tileset.walkability[1] = {} tileset.walkability[1][0] = { 0, 0, 0, 0 } tileset.walkability[1][1] = { 0, 0, 0, 0 } tileset.walkability[1][2] = { 0, 0, 0, 0 } tileset.walkability[1][3] = { 0, 0, 0, 0 } tileset.walkability[1][4] = { 0, 0, 0, 0 } tileset.walkability[1][5] = { 0, 0, 0, 0 } tileset.walkability[1][6] = { 0, 0, 0, 0 } tileset.walkability[1][7] = { 0, 0, 0, 0 } tileset.walkability[1][8] = { 0, 0, 0, 0 } tileset.walkability[1][9] = { 0, 0, 0, 0 } tileset.walkability[1][10] = { 1, 1, 1, 1 } tileset.walkability[1][11] = { 1, 1, 1, 1 } tileset.walkability[1][12] = { 1, 1, 1, 1 } tileset.walkability[1][13] = { 1, 1, 1, 1 } tileset.walkability[1][14] = { 1, 1, 1, 1 } tileset.walkability[1][15] = { 1, 1, 1, 1 } tileset.walkability[2] = {} tileset.walkability[2][0] = { 0, 0, 0, 0 } tileset.walkability[2][1] = { 1, 1, 1, 1 } tileset.walkability[2][2] = { 1, 1, 1, 1 } tileset.walkability[2][3] = { 1, 1, 1, 1 } tileset.walkability[2][4] = { 1, 1, 1, 1 } tileset.walkability[2][5] = { 1, 1, 1, 1 } tileset.walkability[2][6] = { 1, 1, 1, 1 } tileset.walkability[2][7] = { 1, 1, 1, 1 } tileset.walkability[2][8] = { 1, 1, 1, 1 } tileset.walkability[2][9] = { 0, 0, 0, 0 } tileset.walkability[2][10] = { 1, 1, 1, 1 } tileset.walkability[2][11] = { 1, 1, 1, 1 } tileset.walkability[2][12] = { 1, 1, 1, 1 } tileset.walkability[2][13] = { 1, 1, 1, 1 } tileset.walkability[2][14] = { 1, 1, 1, 1 } tileset.walkability[2][15] = { 1, 1, 1, 1 } tileset.walkability[3] = {} tileset.walkability[3][0] = { 0, 0, 0, 0 } tileset.walkability[3][1] = { 1, 1, 1, 1 } tileset.walkability[3][2] = { 1, 1, 1, 1 } tileset.walkability[3][3] = { 1, 1, 1, 1 } tileset.walkability[3][4] = { 1, 1, 1, 1 } tileset.walkability[3][5] = { 1, 1, 1, 1 } tileset.walkability[3][6] = { 1, 1, 1, 1 } tileset.walkability[3][7] = { 1, 1, 1, 1 } tileset.walkability[3][8] = { 1, 1, 1, 1 } tileset.walkability[3][9] = { 0, 0, 0, 0 } tileset.walkability[3][10] = { 1, 1, 1, 1 } tileset.walkability[3][11] = { 1, 1, 1, 1 } tileset.walkability[3][12] = { 1, 1, 1, 1 } tileset.walkability[3][13] = { 1, 1, 1, 1 } tileset.walkability[3][14] = { 0, 0, 0, 0 } tileset.walkability[3][15] = { 0, 0, 0, 0 } tileset.walkability[4] = {} tileset.walkability[4][0] = { 0, 0, 0, 0 } tileset.walkability[4][1] = { 1, 1, 1, 1 } tileset.walkability[4][2] = { 1, 1, 1, 1 } tileset.walkability[4][3] = { 1, 1, 1, 1 } tileset.walkability[4][4] = { 1, 1, 1, 1 } tileset.walkability[4][5] = { 1, 1, 1, 1 } tileset.walkability[4][6] = { 1, 1, 1, 1 } tileset.walkability[4][7] = { 1, 1, 1, 1 } tileset.walkability[4][8] = { 1, 1, 1, 1 } tileset.walkability[4][9] = { 0, 0, 0, 0 } tileset.walkability[4][10] = { 1, 1, 1, 1 } tileset.walkability[4][11] = { 1, 1, 1, 1 } tileset.walkability[4][12] = { 1, 1, 1, 1 } tileset.walkability[4][13] = { 1, 1, 1, 1 } tileset.walkability[4][14] = { 0, 0, 0, 0 } tileset.walkability[4][15] = { 0, 0, 0, 0 } tileset.walkability[5] = {} tileset.walkability[5][0] = { 0, 0, 0, 0 } tileset.walkability[5][1] = { 1, 1, 1, 1 } tileset.walkability[5][2] = { 1, 1, 1, 1 } tileset.walkability[5][3] = { 1, 1, 1, 1 } tileset.walkability[5][4] = { 1, 1, 1, 1 } tileset.walkability[5][5] = { 1, 1, 1, 1 } tileset.walkability[5][6] = { 1, 1, 1, 1 } tileset.walkability[5][7] = { 1, 1, 1, 1 } tileset.walkability[5][8] = { 1, 1, 1, 1 } tileset.walkability[5][9] = { 0, 0, 0, 0 } tileset.walkability[5][10] = { 0, 0, 0, 0 } tileset.walkability[5][11] = { 0, 0, 0, 0 } tileset.walkability[5][12] = { 1, 1, 1, 1 } tileset.walkability[5][13] = { 1, 1, 1, 1 } tileset.walkability[5][14] = { 0, 0, 0, 0 } tileset.walkability[5][15] = { 0, 0, 0, 0 } tileset.walkability[6] = {} tileset.walkability[6][0] = { 0, 0, 0, 0 } tileset.walkability[6][1] = { 1, 1, 1, 1 } tileset.walkability[6][2] = { 1, 1, 1, 1 } tileset.walkability[6][3] = { 1, 1, 1, 1 } tileset.walkability[6][4] = { 1, 1, 1, 1 } tileset.walkability[6][5] = { 1, 1, 1, 1 } tileset.walkability[6][6] = { 1, 1, 1, 1 } tileset.walkability[6][7] = { 1, 1, 1, 1 } tileset.walkability[6][8] = { 1, 1, 1, 1 } tileset.walkability[6][9] = { 0, 0, 0, 0 } tileset.walkability[6][10] = { 1, 1, 1, 1 } tileset.walkability[6][11] = { 1, 1, 1, 1 } tileset.walkability[6][12] = { 0, 0, 0, 0 } tileset.walkability[6][13] = { 0, 0, 0, 0 } tileset.walkability[6][14] = { 1, 1, 1, 1 } tileset.walkability[6][15] = { 1, 1, 1, 1 } tileset.walkability[7] = {} tileset.walkability[7][0] = { 0, 0, 0, 1 } tileset.walkability[7][1] = { 1, 1, 1, 1 } tileset.walkability[7][2] = { 1, 1, 1, 1 } tileset.walkability[7][3] = { 1, 1, 1, 1 } tileset.walkability[7][4] = { 1, 1, 1, 1 } tileset.walkability[7][5] = { 1, 1, 1, 1 } tileset.walkability[7][6] = { 1, 1, 1, 1 } tileset.walkability[7][7] = { 1, 1, 1, 1 } tileset.walkability[7][8] = { 1, 1, 1, 1 } tileset.walkability[7][9] = { 0, 0, 1, 0 } tileset.walkability[7][10] = { 1, 1, 1, 1 } tileset.walkability[7][11] = { 1, 1, 1, 1 } tileset.walkability[7][12] = { 0, 0, 0, 0 } tileset.walkability[7][13] = { 0, 0, 0, 0 } tileset.walkability[7][14] = { 1, 1, 1, 1 } tileset.walkability[7][15] = { 1, 1, 1, 1 } tileset.walkability[8] = {} tileset.walkability[8][0] = { 0, 1, 0, 0 } tileset.walkability[8][1] = { 1, 1, 1, 1 } tileset.walkability[8][2] = { 1, 1, 1, 1 } tileset.walkability[8][3] = { 1, 1, 1, 1 } tileset.walkability[8][4] = { 1, 1, 1, 1 } tileset.walkability[8][5] = { 1, 1, 1, 1 } tileset.walkability[8][6] = { 1, 1, 1, 1 } tileset.walkability[8][7] = { 1, 1, 1, 1 } tileset.walkability[8][8] = { 1, 1, 1, 1 } tileset.walkability[8][9] = { 1, 0, 0, 0 } tileset.walkability[8][10] = { 1, 1, 1, 1 } tileset.walkability[8][11] = { 1, 1, 1, 1 } tileset.walkability[8][12] = { 0, 0, 0, 0 } tileset.walkability[8][13] = { 0, 0, 0, 0 } tileset.walkability[8][14] = { 0, 0, 0, 0 } tileset.walkability[8][15] = { 0, 0, 0, 0 } tileset.walkability[9] = {} tileset.walkability[9][0] = { 0, 0, 0, 0 } tileset.walkability[9][1] = { 0, 0, 0, 0 } tileset.walkability[9][2] = { 0, 0, 0, 0 } tileset.walkability[9][3] = { 0, 0, 0, 0 } tileset.walkability[9][4] = { 0, 0, 0, 0 } tileset.walkability[9][5] = { 0, 0, 0, 0 } tileset.walkability[9][6] = { 0, 0, 0, 0 } tileset.walkability[9][7] = { 0, 0, 0, 0 } tileset.walkability[9][8] = { 0, 0, 0, 0 } tileset.walkability[9][9] = { 0, 0, 0, 0 } tileset.walkability[9][10] = { 0, 0, 0, 0 } tileset.walkability[9][11] = { 0, 0, 0, 0 } tileset.walkability[9][12] = { 0, 0, 0, 0 } tileset.walkability[9][13] = { 0, 0, 0, 0 } tileset.walkability[9][14] = { 0, 0, 0, 0 } tileset.walkability[9][15] = { 0, 0, 0, 0 } tileset.walkability[10] = {} tileset.walkability[10][0] = { 0, 0, 0, 0 } tileset.walkability[10][1] = { 1, 1, 1, 1 } tileset.walkability[10][2] = { 1, 1, 1, 1 } tileset.walkability[10][3] = { 1, 1, 1, 1 } tileset.walkability[10][4] = { 1, 1, 1, 1 } tileset.walkability[10][5] = { 1, 1, 1, 1 } tileset.walkability[10][6] = { 1, 1, 1, 1 } tileset.walkability[10][7] = { 1, 1, 1, 1 } tileset.walkability[10][8] = { 1, 1, 1, 1 } tileset.walkability[10][9] = { 0, 0, 0, 0 } tileset.walkability[10][10] = { 0, 0, 0, 0 } tileset.walkability[10][11] = { 0, 0, 0, 0 } tileset.walkability[10][12] = { 0, 0, 0, 0 } tileset.walkability[10][13] = { 0, 0, 0, 0 } tileset.walkability[10][14] = { 0, 0, 0, 0 } tileset.walkability[10][15] = { 0, 0, 0, 0 } tileset.walkability[11] = {} tileset.walkability[11][0] = { 0, 0, 0, 0 } tileset.walkability[11][1] = { 1, 1, 1, 1 } tileset.walkability[11][2] = { 1, 1, 1, 1 } tileset.walkability[11][3] = { 1, 1, 1, 1 } tileset.walkability[11][4] = { 1, 1, 1, 1 } tileset.walkability[11][5] = { 1, 1, 1, 1 } tileset.walkability[11][6] = { 1, 1, 1, 1 } tileset.walkability[11][7] = { 1, 1, 1, 1 } tileset.walkability[11][8] = { 1, 1, 1, 1 } tileset.walkability[11][9] = { 0, 0, 0, 0 } tileset.walkability[11][10] = { 0, 0, 0, 0 } tileset.walkability[11][11] = { 0, 0, 0, 0 } tileset.walkability[11][12] = { 0, 0, 0, 0 } tileset.walkability[11][13] = { 0, 0, 0, 0 } tileset.walkability[11][14] = { 0, 0, 0, 0 } tileset.walkability[11][15] = { 0, 0, 0, 0 } tileset.walkability[12] = {} tileset.walkability[12][0] = { 0, 0, 0, 0 } tileset.walkability[12][1] = { 1, 1, 1, 1 } tileset.walkability[12][2] = { 1, 1, 1, 1 } tileset.walkability[12][3] = { 1, 1, 1, 1 } tileset.walkability[12][4] = { 1, 1, 1, 1 } tileset.walkability[12][5] = { 1, 1, 1, 1 } tileset.walkability[12][6] = { 1, 1, 1, 1 } tileset.walkability[12][7] = { 1, 1, 1, 1 } tileset.walkability[12][8] = { 1, 1, 1, 1 } tileset.walkability[12][9] = { 0, 0, 0, 0 } tileset.walkability[12][10] = { 0, 0, 0, 0 } tileset.walkability[12][11] = { 0, 0, 0, 0 } tileset.walkability[12][12] = { 0, 0, 0, 0 } tileset.walkability[12][13] = { 0, 0, 0, 0 } tileset.walkability[12][14] = { 0, 0, 0, 0 } tileset.walkability[12][15] = { 0, 0, 0, 0 } tileset.walkability[13] = {} tileset.walkability[13][0] = { 0, 0, 0, 0 } tileset.walkability[13][1] = { 1, 1, 1, 1 } tileset.walkability[13][2] = { 1, 1, 1, 1 } tileset.walkability[13][3] = { 1, 1, 1, 1 } tileset.walkability[13][4] = { 1, 1, 1, 1 } tileset.walkability[13][5] = { 1, 1, 1, 1 } tileset.walkability[13][6] = { 1, 1, 1, 1 } tileset.walkability[13][7] = { 1, 1, 1, 1 } tileset.walkability[13][8] = { 1, 1, 1, 1 } tileset.walkability[13][9] = { 0, 0, 0, 0 } tileset.walkability[13][10] = { 0, 0, 0, 0 } tileset.walkability[13][11] = { 0, 0, 0, 0 } tileset.walkability[13][12] = { 0, 0, 0, 0 } tileset.walkability[13][13] = { 0, 0, 0, 0 } tileset.walkability[13][14] = { 0, 0, 0, 0 } tileset.walkability[13][15] = { 0, 0, 0, 0 } tileset.walkability[14] = {} tileset.walkability[14][0] = { 0, 0, 0, 0 } tileset.walkability[14][1] = { 1, 1, 1, 1 } tileset.walkability[14][2] = { 1, 1, 1, 1 } tileset.walkability[14][3] = { 1, 1, 1, 1 } tileset.walkability[14][4] = { 1, 1, 1, 1 } tileset.walkability[14][5] = { 1, 1, 1, 1 } tileset.walkability[14][6] = { 1, 1, 1, 1 } tileset.walkability[14][7] = { 1, 1, 1, 1 } tileset.walkability[14][8] = { 1, 1, 1, 1 } tileset.walkability[14][9] = { 0, 0, 0, 0 } tileset.walkability[14][10] = { 0, 0, 0, 0 } tileset.walkability[14][11] = { 0, 0, 0, 0 } tileset.walkability[14][12] = { 0, 0, 0, 0 } tileset.walkability[14][13] = { 0, 0, 0, 0 } tileset.walkability[14][14] = { 0, 0, 0, 0 } tileset.walkability[14][15] = { 0, 0, 0, 0 } tileset.walkability[15] = {} tileset.walkability[15][0] = { 0, 0, 0, 0 } tileset.walkability[15][1] = { 1, 1, 0, 0 } tileset.walkability[15][2] = { 1, 0, 0, 0 } tileset.walkability[15][3] = { 0, 0, 0, 0 } tileset.walkability[15][4] = { 0, 0, 0, 0 } tileset.walkability[15][5] = { 0, 0, 0, 0 } tileset.walkability[15][6] = { 0, 0, 0, 0 } tileset.walkability[15][7] = { 0, 1, 0, 0 } tileset.walkability[15][8] = { 1, 1, 0, 0 } tileset.walkability[15][9] = { 0, 0, 0, 0 } tileset.walkability[15][10] = { 0, 0, 0, 0 } tileset.walkability[15][11] = { 0, 0, 0, 0 } tileset.walkability[15][12] = { 0, 0, 0, 0 } tileset.walkability[15][13] = { 0, 0, 0, 0 } tileset.walkability[15][14] = { 0, 0, 0, 0 } tileset.walkability[15][15] = { 0, 0, 0, 0 }
gpl-2.0
rlcevg/Zero-K
units/roost.lua
2
3459
unitDef = { unitname = [[roost]], name = [[Roost]], description = [[Spawns Chicken]], acceleration = 0, activateWhenBuilt = true, brakeRate = 0, buildAngle = 4096, buildCostEnergy = 340, buildCostMetal = 340, builder = false, buildPic = [[roost.png]], buildTime = 340, category = [[SINK]], customParams = { description_de = [[Erzeugt Chicken]], description_pl = [[Rozmnaza kurczaki]], helptext = [[Roosts such as this one are the hatching grounds of the Thunderbirds.]], helptext_de = [[In den Nestern der Chicken wird die Brut herangezogen und nach einer gewissen Zeit auf die restliche Welt losgelassen.]], helptext_pl = [[W tym gniezdzie rodza sie kurczaki.]], }, energyMake = 0, explodeAs = [[NOWEAPON]], footprintX = 3, footprintZ = 3, iconType = [[special]], idleAutoHeal = 0, idleTime = 1800, levelGround = false, mass = 226, maxDamage = 1800, maxSlope = 36, maxVelocity = 0, metalMake = 2.5, minCloakDistance = 150, noAutoFire = false, objectName = [[roost]], seismicSignature = 4, selfDestructAs = [[NOWEAPON]], sfxtypes = { explosiongenerators = { [[custom:dirt2]], [[custom:dirt3]], }, }, side = [[THUNDERBIRDS]], sightDistance = 273, smoothAnim = true, turnRate = 0, upright = false, waterline = 0, workerTime = 0, yardMap = [[ooooooooo]], weapons = { { def = [[AEROSPORES]], onlyTargetCategory = [[FIXEDWING GUNSHIP]], }, }, weaponDefs = { AEROSPORES = { name = [[Anti-Air Spores]], areaOfEffect = 24, avoidFriendly = false, burst = 4, burstrate = 0.2, canAttackGround = false, collideFriendly = false, craterBoost = 0, craterMult = 0, damage = { default = 80, planes = 80, subs = 8, }, dance = 60, explosionGenerator = [[custom:NONE]], fireStarter = 0, fixedlauncher = 1, flightTime = 5, groundbounce = 1, heightmod = 0.5, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 2, model = [[chickeneggblue.s3o]], range = 600, reloadtime = 3, smokeTrail = true, startVelocity = 100, texture1 = [[]], texture2 = [[sporetrailblue]], tolerance = 10000, tracks = true, turnRate = 24000, turret = true, waterweapon = true, weaponAcceleration = 100, weaponType = [[MissileLauncher]], weaponVelocity = 500, wobble = 32000, }, }, featureDefs = { }, } return lowerkeys({ roost = unitDef })
gpl-2.0
pielover88888/denice
lua/functions.lua
2
2062
-- global variable for xml lib xml = require('LuaXml') -- select words above threshold size and add to a table function big_words(str, thresh) local r = {} for i,word in pairs(str_split(str, " ")) do if word:len() >= thresh then r[#r+1] = word end end return r end -- split string by separator function str_split(str, sep) if str == nil then return {} else local sep, fields = sep or " ", {} local str = str.." " local index = 1 while index <= str:len() do local piece_end = str:find(sep, index) if piece_end == nil then piece_end = str:len() end fields[#fields+1] = str:sub(index, piece_end - 1) index = piece_end + 1 end return fields end end -- merge all but first (max-1) entries in table returned by str_split function str_split_max(str, sep, max) local t1 = {} for i,v in pairs(str_split(str, sep)) do if #t1 < max then t1[i] = v else t1[#t1] = t1[#t1]..sep..v end end return t1 end -- helper function for xml parsing function getNodes(t,nodeName,first) local returnNodes = {} for i,v in pairs(t) do if type(v) == "table" and v[0] == nodeName then if first then if type(v) == "table" then v.getNodes = getNodes end return v end table.insert(returnNodes,v) end end return returnNodes end -- trim leading or trailing spaces function cleanSpace(s) return s:gsub("^ +",""):gsub(" +$","") end -- url encode a string function url_encode(str) if (str) then str = string.gsub (str, "\n", "\r\n") str = string.gsub (str, "([^%w %-%_%.%~])", function (c) return string.format ("%%%02X", string.byte(c)) end) str = string.gsub (str, " ", "+") end return str end
mit
upsoft/Atlas
lib/proxy/tokenizer.lua
41
6215
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] require("mysql.tokenizer") module("proxy.tokenizer", package.seeall) --- -- normalize a query -- -- * remove comments -- * quote literals -- * turn constants into ? -- * turn tokens into uppercase -- -- @param tokens a array of tokens -- @return normalized SQL query -- -- @see tokenize function normalize(tokens) -- we use a string-stack here and join them at the end -- see http://www.lua.org/pil/11.6.html for more -- local stack = {} -- literals that are SQL commands if they appear at the start -- (all uppercase) local literal_keywords = { ["COMMIT"] = { }, ["ROLLBACK"] = { }, ["BEGIN"] = { }, ["START"] = { "TRANSACTION" }, } for i = 1, #tokens do local token = tokens[i] -- normalize the query if token["token_name"] == "TK_COMMENT" then elseif token["token_name"] == "TK_COMMENT_MYSQL" then -- a /*!... */ comment -- -- we can't look into the comment as we don't know which server-version -- we will talk to, pass it on verbatimly table.insert(stack, "/*!" ..token.text .. "*/ ") elseif token["token_name"] == "TK_LITERAL" then if token.text:sub(1, 1) == "@" then -- append session variables as is table.insert(stack, token.text .. " ") elseif #stack == 0 then -- nothing is on the stack yet local u_text = token.text:upper() if literal_keywords[u_text] then table.insert(stack, u_text .. " ") else table.insert(stack, "`" .. token.text .. "` ") end elseif #stack == 1 then local u_text = token.text:upper() local starting_keyword = stack[1]:sub(1, -2) if literal_keywords[starting_keyword] and literal_keywords[starting_keyword][1] == u_text then table.insert(stack, u_text .. " ") else table.insert(stack, "`" .. token.text .. "` ") end else table.insert(stack, "`" .. token.text .. "` ") end elseif token["token_name"] == "TK_STRING" or token["token_name"] == "TK_INTEGER" or token["token_name"] == "TK_FLOAT" then table.insert(stack, "? ") elseif token["token_name"] == "TK_FUNCTION" then table.insert(stack, token.text:upper()) else table.insert(stack, token.text:upper() .. " ") end end return table.concat(stack) end --- -- call the included tokenizer -- -- this function is only a wrapper and exists mostly -- for constancy and documentation reasons function tokenize(packet) local tokens = tokenizer.tokenize(packet) local attr = 0 if tokens[1].token_name == "TK_COMMENT" or tokens[1].token_name == "TK_COMMENT_MYSQL" then if string.match(tokens[1].text:upper(), "^%s*MASTER%s*$") then attr = 1 --1´ú±íÇ¿ÖÆ¶Ámaster end end return tokens, attr end --- -- return the first command token -- -- * strips the leading comments function first_stmt_token(tokens) for i = 1, #tokens do local token = tokens[i] -- normalize the query if token["token_name"] == "TK_COMMENT" then elseif token["token_name"] == "TK_LITERAL" then -- commit and rollback at LITERALS return token else -- TK_SQL_* are normal tokens return token end end return nil end --- --[[ returns an array of simple token values without id and name, and stripping all comments @param tokens an array of tokens, as produced by the tokenize() function @param quote_strings : if set, the string tokens will be quoted @see tokenize --]] function bare_tokens (tokens, quote_strings) local simple_tokens = {} for i = 1, #tokens do local token = tokens[i] if (token['token_name'] == 'TK_STRING') and quote_strings then table.insert(simple_tokens, string.format('%q', token['text'] )) elseif (token['token_name'] ~= 'TK_COMMENT') then table.insert(simple_tokens, token['text']) end end return simple_tokens end --- --[[ Returns a text query from an array of tokens, stripping off comments @param tokens an array of tokens, as produced by the tokenize() function @param start_item ignores tokens before this one @param end_item ignores token after this one @see tokenize --]] function tokens_to_query ( tokens , start_item, end_item ) if not start_item then start_item = 1 end if not end_item then end_item = #tokens end local counter = 0 local new_query = '' for i = 1, #tokens do local token = tokens[i] counter = counter + 1 if (counter >= start_item and counter <= end_item ) then if (token['token_name'] == 'TK_STRING') then new_query = new_query .. string.format('%q', token['text'] ) elseif token['token_name'] ~= 'TK_COMMENT' then new_query = new_query .. token['text'] end if (token['token_name'] ~= 'TK_FUNCTION') and (token['token_name'] ~= 'TK_COMMENT') then new_query = new_query .. ' ' end end end return new_query end --- --[[ returns an array of tokens, stripping off all comments @param tokens an array of tokens, as produced by the tokenize() function @see tokenize, simple_tokens --]] function tokens_without_comments (tokens) local new_tokens = {} for i = 1, #tokens do local token = tokens[i] if (token['token_name'] ~= 'TK_COMMENT' and token['token_name'] ~= 'TK_COMMENT_MYSQL') then table.insert(new_tokens, token) end end return new_tokens end
gpl-2.0
rlcevg/Zero-K
LuaRules/Configs/lups_projectile_fxs.lua
12
3125
local MergeTable = Spring.Utilities.MergeTable local fx = { flame_heat = { class = 'JitterParticles2', colormap = { {1,1,1,1},{1,1,1,1} }, count = 6, life = 24, delaySpread = 25, force = {-10,0,0}, --forceExp = 0.2, emitRotSpread= 10, speed = 10, speedSpread = 0, speedExp = 1.5, size = 15, sizeGrowth = 5.0, scale = 1.5, strength = 1.0, heat = 2, }, sonic_distort = { class = 'SphereDistortion', colormap = { {1,1,1,1},{1,1,1,1} }, count = 1, life = 24, delaySpread = 0, force = {0,0,0}, --forceExp = 0.2, emitRotSpread= 180, speed = 0, speedSpread = 0, speedExp = 0, size = 50, sizeGrowth = 0, scale = 5, strength = 10, growth = 0, heat = 20, }, flame1 = { class = 'SimpleParticles2', colormap = { {1, 1, 1, 0.01}, {1, 1, 1, 0.01}, {0.75, 0.5, 0.5, 0.01}, {0.35, 0.15, 0.15, 0.25}, {0.1, 0.035, 0.01, 0.2}, {0, 0, 0, 0.01} }, count = 4, life = 24, delaySpread = 25, force = {0,1,0}, --forceExp = 0.2, emitRotSpread= 8, rotSpeed = 1, rotSpread = 360, rotExp = 9, --speed = 10, --speedSpread = 0, --speedExp = 1.5, size = 2, sizeGrowth = 4.0, sizeExp = 0.7, --texture = "bitmaps/smoke/smoke06.tga", texture = altFlameTexture and "bitmaps/GPL/flame_alt.png" or "bitmaps/GPL/flame.png", }, flame2 = { class = 'SimpleParticles2', colormap = { {1, 1, 1, 0.01}, {0, 0, 0, 0.01} }, count = 20, --delay = 20, life = 10, lifeSpread = 20, delaySpread = 15, force = {0,1,0}, --forceExp = 0.2, emitRotSpread= 3, rotSpeed = 1, rotSpread = 360, rotExp = 9, --speed = 10, --speedSpread = 0, size = 2, sizeGrowth = 4.0, sizeExp = 0.65, --texture = "bitmaps/smoke/smoke06.tga", texture = altFlameTexture and "bitmaps/GPL/flame_alt.png" or "bitmaps/GPL/flame.png", }, } local tbl = { --[[ corpyro_flamethrower = { {class = "JitterParticles2", options = fx.flame_heat}, {class = "SimpleParticles2", options = fx.flame1}, {class = "SimpleParticles2", options = fx.flame2}, }, ]]-- hoverscout_sonicgun = { {class = "JitterParticles2", options = fx.sonic_distort}, }, } local tbl2 = {} for weaponName, data in pairs(tbl) do local weaponDef = WeaponDefNames[weaponName] or {} local weaponID = weaponDef.id if weaponID then tbl2[weaponID] = data end end return tbl2
gpl-2.0
avataronline/avatarclient
data/locales/Nova pasta/sv.lua
7
17580
-- thanks cometangel, who made these translations locale = { name = "sv", charset = "cp1252", languageName = "Svenska", formatNumbers = true, decimalSeperator = ',', thousandsSeperator = ' ', translation = { ["1a) Offensive Name"] = "1a) Offensivt Namn", ["1b) Invalid Name Format"] = "1b) Ogiltigt Namnformat", ["1c) Unsuitable Name"] = "1c) Opassande Namn", ["1d) Name Inciting Rule Violation"] = "1d) Namn anstiftar regelbrott.", ["2a) Offensive Statement"] = "2a) Offensivt Uttryck", ["2b) Spamming"] = "2b) Spammning", ["2c) Illegal Advertising"] = "2c) Olaglig Reklamföring", ["2d) Off-Topic Public Statement"] = "2d) Icke-Ämneförhållande publiskt uttryck", ["2e) Non-English Public Statement"] = "2e) Icke-Engelskt publiskt uttryck", ["2f) Inciting Rule Violation"] = "2f) Antyder regelbrytande", ["3a) Bug Abuse"] = "3a) Missbrukande av bugg", ["3b) Game Weakness Abuse"] = "3b) Spelsvaghetsmissbruk", ["3c) Using Unofficial Software to Play"] = "3c) Använder Icke-officiel mjukvara för att spela", ["3d) Hacking"] = "3d) Hackar", ["3e) Multi-Clienting"] = "3e) Multi-klient", ["3f) Account Trading or Sharing"] = "3f) Kontohandel", ["4a) Threatening Gamemaster"] = "4a) Hotar gamemaster", ["4b) Pretending to Have Influence on Rule Enforcement"] = "4b) Låtsas ha inflytande på Regelsystem", ["4c) False Report to Gamemaster"] = "4c) Falsk rapport till gamemaster", ["Accept"] = "Acceptera", ["Account name"] = "Konto namn", ["Account Status:"] = false, ["Action:"] = "Handling:", ["Add"] = "Lägg till", ["Add new VIP"] = "Ny VIP", ["Addon 1"] = "Tillägg 1", ["Addon 2"] = "Tillägg 2", ["Addon 3"] = "Tillägg 3", ["Add to VIP list"] = "Lägg till på VIP Listan", ["Adjust volume"] = "Justera Volym", ["Alas! Brave adventurer, you have met a sad fate.\nBut do not despair, for the gods will bring you back\ninto this world in exchange for a small sacrifice\n\nSimply click on Ok to resume your journeys!"] = false, ["All"] = false, ["All modules and scripts were reloaded."] = "Alla moduler och skript laddades om", ["Allow auto chase override"] = "Tillåt Jaktstyrning", ["Also known as dash in tibia community, recommended\nfor playing characters with high speed"] = false, ["Ambient light: %s%%"] = false, ["Amount:"] = "Antal:", ["Amount"] = "Antal", ["Anonymous"] = "Anonym", ["Are you sure you want to logout?"] = "Är du säker att du vill logga ut?", ["Attack"] = "Attackera", ["Author"] = "Översättare", ["Autoload"] = "Automatisk Laddning", ["Autoload priority"] = "Laddningsprioritet", ["Auto login"] = "Autoinloggning", ["Auto login selected character on next charlist load"] = "Logga in Näst laddad karaktär automatisk nästa gång karaktärlistan laddar", ["Axe Fighting"] = "Yx Stridande", ["Balance:"] = "Balans:", ["Banishment"] = "Bannlysning", ["Banishment + Final Warning"] = "Bannlysning + Sista varning", ["Battle"] = "Strid", ["Browse"] = "Bläddra", ["Bug report sent."] = "Buggrapport Skickad.", ["Button Assign"] = "Assignera Knapp", ["Buy"] = "Köp", ["Buy Now"] = "Köp Nu", ["Buy Offers"] = "Köp Offerter", ["Buy with backpack"] = "Köp med ryggsäck", ["Cancel"] = "Avbryt", ["Cannot login while already in game."] = "Kan ej logga in medan du redan är i spelet.", ["Cap"] = "Kap", ["Capacity"] = "Kapacitet", ["Center"] = "Centrera", ["Channels"] = "Kanaler", ["Character List"] = "Karaktär lista", ["Classic control"] = "Klassisk kontroll", ["Clear current message window"] = "Rensa nuvarande meddelanderuta", ["Clear Messages"] = false, ["Clear object"] = "Rensa objekt", ["Client needs update."] = "Klienten behöver uppdateras.", ["Close"] = "Stäng", ["Close this channel"] = "Stäng Denna Kanal", ["Club Fighting"] = "Klubb Stridande", ["Combat Controls"] = "Krigs Kontroller", ["Comment:"] = "Kommentar:", ["Connecting to game server..."] = "Kopplar upp till spelserver...", ["Connecting to login server..."] = "Kopplar upp till autentiseringserver...", ["Console"] = false, ["Cooldowns"] = false, ["Copy message"] = "Kopiera meddelande", ["Copy name"] = "Kopiera namn", ["Copy Name"] = "Kopiera Namn", ["Create Map Mark"] = false, ["Create mark"] = false, ["Create New Offer"] = "Skapa ny offert.", ["Create Offer"] = "Skapa Offert", ["Current hotkeys:"] = "Aktuella snabbtangenter", ["Current hotkey to add: %s"] = "Ny Snabbtangent: %s", ["Current Offers"] = "Nuvarande Offerter", ["Default"] = "Standard", ["Delete mark"] = false, ["Description:"] = false, ["Description"] = "Beskrivning", ["Destructive Behaviour"] = "Destruktivt beteende", ["Detail"] = "Detalj", ["Details"] = "Detaljer", ["Disable Shared Experience"] = "Avaktivera delad erfarenhet", ["Dismount"] = false, ["Display connection speed to the server (milliseconds)"] = false, ["Distance Fighting"] = "Distans Stridande", ["Don't stretch/shrink Game Window"] = false, ["Edit hotkey text:"] = "Ändra Snabbtangent:", ["Edit List"] = "Ändra Lista", ["Edit Text"] = "Ändra text", ["Enable music"] = "Aktivera musik", ["Enable Shared Experience"] = "Aktivera delad erfarenhet", ["Enable smart walking"] = false, ["Enable vertical synchronization"] = "Aktivera vertikal synkronisering", ["Enable walk booster"] = false, ["Enter Game"] = "Gå in i Spelet", ["Enter one name per line."] = "Skriv ett namn per linje.", ["Enter with your account again to update your client."] = false, ["Error"] = "Fel", ["Error"] = "Fel", ["Excessive Unjustified Player Killing"] = "Överdrivet oberättigat dödande av spelare", ["Exclude from private chat"] = "Exkludera från privat chat", ["Exit"] = "Avsluta", ["Experience"] = "Erfarenhet", ["Filter list to match your level"] = "Filtrera efter nivå", ["Filter list to match your vocation"] = "Filtrera efter kallelse", ["Find:"] = false, ["Fishing"] = "Fiske", ["Fist Fighting"] = "Hand Stridande", ["Follow"] = "Följ", ["Force Exit"] = false, ["For Your Information"] = false, ["Free Account"] = false, ["Fullscreen"] = "Helskärm", ["Game"] = false, ["Game framerate limit: %s"] = "Spelets FPS gräns: %s", ["Graphics"] = "Grafik", ["Graphics card driver not detected"] = false, ["Graphics Engine:"] = "Grafikmotor:", ["Head"] = "Huvud", ["Healing"] = false, ["Health Info"] = "Livsinfo", ["Health Information"] = "Livsinformation", ["Hide monsters"] = "Göm Monster", ["Hide non-skull players"] = "Göm icke-skullad spelare", ["Hide Npcs"] = "Göm NPCs", ["Hide Offline"] = false, ["Hide party members"] = "Göm gruppmedlemmar", ["Hide players"] = "Göm spelare", ["Hide spells for higher exp. levels"] = false, ["Hide spells for other vocations"] = false, ["Hit Points"] = "Livspoäng", ["Hold left mouse button to navigate\nScroll mouse middle button to zoom\nRight mouse button to create map marks"] = false, ["Hotkeys"] = "Snabbtangenter", ["If you shut down the program, your character might stay in the game.\nClick on 'Logout' to ensure that you character leaves the game properly.\nClick on 'Exit' if you want to exit the program without logging out your character."] = "Om du stänger av programmet kan din karaktär stanna i spelet.\nKlicka på 'Logga ut' för att säkerställa att din karaktär lämnar spelet korrekt.\nKlicka på 'Avsluta' om du vill avsluta programmet utan att logga ut din karaktär.", ["Ignore"] = false, ["Ignore capacity"] = "Ignorera kapacitet", ["Ignored players:"] = false, ["Ignore equipped"] = "Ignorera utrustning", ["Ignore List"] = false, ["Ignore players"] = false, ["Ignore Private Messages"] = false, ["Ignore Yelling"] = false, ["Interface framerate limit: %s"] = "Gränssnitt FPS gräns: %s", ["Inventory"] = "Utrustning", ["Invite to Party"] = "Bjud till grupp", ["Invite to private chat"] = "Bjud in i privat chat", ["IP Address Banishment"] = "Bannlysning av IP", ["Item Offers"] = "Objekt offert", ["It is empty."] = false, ["Join %s's Party"] = "Gå med i %s's Grupp", ["Leave Party"] = "Lämna Grupp", ["Level"] = "Nivå", ["Lifetime Premium Account"] = false, ["Limits FPS to 60"] = "Stoppa FPS vid 60", ["List of items that you're able to buy"] = "Lista av saker du kan köpa", ["List of items that you're able to sell"] = "Lista av saker du kan sälja", ["Load"] = "Ladda", ["Logging out..."] = "Loggar ut...", ["Login"] = "Logga in", ["Login Error"] = "Autentifikations fel", ["Login Error"] = "Autentifikations fel", ["Logout"] = "Logga ut", ["Look"] = "Kolla", ["Magic Level"] = "Magisk Nivå", ["Make sure that your client uses\nthe correct game protocol version"] = "Var säker på att din client\n andvänder rätt protokol version", ["Mana"] = "Mana", ["Manage hotkeys:"] = "Ändra snabbtangenten:", ["Market"] = "Marknad", ["Market Offers"] = "Marknadsofferter", ["Message of the day"] = "Dagens meddelande", ["Message to "] = "Meddelande till ", ["Message to %s"] = "Meddelande till %s", ["Minimap"] = "Minikarta", ["Module Manager"] = "Modul Manager", ["Module name"] = "Modul namn", ["Mount"] = false, ["Move Stackable Item"] = "Flytta stapelbart föremål", ["Move up"] = "Flytta upp", ["My Offers"] = "Mina offerter", ["Name:"] = "Namn:", ["Name Report"] = "Namn Rapport", ["Name Report + Banishment"] = "Namn rapport + Bannlysning", ["Name Report + Banishment + Final Warning"] = "Namn rapport + Bannlysning + Sista varning", ["No"] = "Nej", ["No graphics card detected, everything will be drawn using the CPU,\nthus the performance will be really bad.\nPlease update your graphics driver to have a better performance."] = false, ["No item selected."] = "Ingen sak vald.", ["No Mount"] = "Ingen Mount", ["No Outfit"] = "Ingen Utstyrsel", ["No statement has been selected."] = "Inget påstående är valt.", ["Notation"] = "Notering", ["NPC Trade"] = "Handel NPC", ["Offer History"] = "Offert Historia", ["Offers"] = "Offerter", ["Offer Type:"] = "Offert typ:", ["Offline Training"] = false, ["Ok"] = "Ok", ["on %s.\n"] = "på %s.\n", ["Open"] = "Öppna", ["Open a private message channel:"] = "Öppna en privat meddelandekanal:", ["Open charlist automatically when starting client"] = false, ["Open in new window"] = "Öppna i nytt fönster", ["Open new channel"] = "Öppna ny kanal", ["Options"] = "Inställningar", ["Overview"] = false, ["Pass Leadership to %s"] = "Ge ledarskap till %s", ["Password"] = "Lösenord", ["Piece Price:"] = "Per Styck:", ["Please enter a character name:"] = "Skriv in ett karaktärsnamn:", ["Please, press the key you wish to add onto your hotkeys manager"] = "Tryck på knappen som du\nvill lägga till som snabbtangent", ["Please Select"] = "Välj", ["Please use this dialog to only report bugs. Do not report rule violations here!"] = "Använd den här dialogrutan endast för att rapportera buggar. Rapportera inte regelbrott här!", ["Please wait"] = "Var God Vänta", ["Port"] = "Port", ["Position:"] = false, ["Position: %i %i %i"] = false, ["Premium Account (%s) days left"] = false, ["Price:"] = "Pris", ["Primary"] = "Primär", ["Protocol"] = "Protokoll", ["Quest Log"] = "Uppdragslog", ["Randomize"] = "Slumpa", ["Randomize characters outfit"] = "Slumpa karaktärs utstyrsel", ["Reason:"] = "Anledning:", ["Refresh"] = "Uppdatera", ["Refresh Offers"] = false, ["Regeneration Time"] = false, ["Reject"] = "Avvisa", ["Reload All"] = "Ladda om allt", ["Remember account and password when starts client"] = false, ["Remember password"] = "Kom ihåg lösenord", ["Remove"] = "Ta bort", ["Remove %s"] = "Ta bort %s", ["Report Bug"] = "Rapportera Bugg", ["Reserved for more functionality later."] = false, ["Reset Market"] = false, ["Revoke %s's Invitation"] = "Annulera %s's Inbjudan", ["Rotate"] = "Rotera", ["Rule Violation"] = "Regel Brott", ["Save"] = false, ["Save Messages"] = false, ["Search:"] = "Sök:", ["Search all items"] = false, ["Secondary"] = "Sekundär", ["Select object"] = "Välj Objekt", ["Select Outfit"] = "Välj Utstyrsel", ["Select your language"] = false, ["Sell"] = "Sälj", ["Sell Now"] = "Sälj Nu", ["Sell Offers"] = "Sälj Offerter", ["Send"] = "Skicka", ["Send automatically"] = "Skicka automatiskt", ["Send Message"] = false, ["Server"] = "Server", ["Server Log"] = "Server Log", ["Set Outfit"] = "Bestäm Utstyrsel", ["Shielding"] = "Sköld", ["Show all items"] = "Visa alla saker", ["Show connection ping"] = false, ["Show Depot Only"] = "Visa bara förråd", ["Show event messages in console"] = "Visa event meddelanden i konsol", ["Show frame rate"] = "Visa FPS", ["Show info messages in console"] = "Visa info meddelanden i konsol", ["Show left panel"] = "Visa vänster panel", ["Show levels in console"] = "Visa nivåer i konsol", ["Show Offline"] = false, ["Show private messages in console"] = "Visa privata meddelanden i konsol", ["Show private messages on screen"] = "Visa privata meddelanden på skärmen", ["Show Server Messages"] = false, ["Show status messages in console"] = "Visa statusmeddelanden i konsol", ["Show Text"] = "Visa Text", ["Show timestamps in console"] = "Visa tidstämpel i konsol", ["Show your depot items only"] = "Visa mitt förråd endast", ["Skills"] = "Förmågor", ["Soul"] = "Själ", ["Soul Points"] = "Själpoäng", ["Special"] = false, ["Speed"] = false, ["Spell Cooldowns"] = false, ["Spell List"] = false, ["Stamina"] = "Uthållighet", ["Statement:"] = "Påstående:", ["Statement Report"] = "Påståenderapport", ["Statistics"] = "Statistik", ["Stop Attack"] = "Sluta Attackera", ["Stop Follow"] = "Sluta Följa", ["Support"] = false, ["%s: (use object)"] = "%s: (Använd objekt)", ["%s: (use object on target)"] = "%s: (Använd objekt på mål)", ["%s: (use object on yourself)"] = "%s: (Använd objekt på mig)", ["%s: (use object with crosshair)"] = "%s: (Använd objekt med sikte)", ["Sword Fighting"] = "Svärd Stridning", ["Terminal"] = "Terminal", ["There is no way."] = "Det finns ingen väg.", ["Title"] = false, ["Total Price:"] = "Totalt Pris:", ["Trade"] = "Handel", ["Trade with ..."] = "Handla med ...", ["Trying to reconnect in %s seconds."] = "Försöker koppla upp igen om %s sekunder.", ["Unable to load dat file, please place a valid dat in '%s'"] = "kan ej ladda dat filen, lägg en giltig dat fil i '%s'", ["Unable to load spr file, please place a valid spr in '%s'"] = "kan ej ladda spr filen, lägg en giltig spr fil i '%s'", ["Unable to logout."] = "Kan ej logga ut.", ["Unignore"] = false, ["Unload"] = "Avladda", ["Update needed"] = false, ["Use"] = "Använd", ["Use on target"] = "Använd på mål", ["Use on yourself"] = "Använd på mig", ["Use with ..."] = "Använd med ...", ["Version"] = "Version", ["VIP List"] = "VIP Lista", ["Voc."] = "Kallelse", ["Vocation"] = false, ["Waiting List"] = "Kölista", ["Website"] = "Websida", ["Weight:"] = "Vikt:", ["Will detect when to use diagonal step based on the\nkeys you are pressing"] = false, ["With crosshair"] = "Med sikte", ["Yes"] = "Ja", ["You are bleeding"] = "Du Blöder", ["You are burning"] = "Du brinner", ["You are cursed"] = "Du är fördömd", ["You are dazzled"] = "Du är chockad", ["You are dead."] = "Du är död.", ["You are dead"] = "Du är död", ["You are drowning"] = "Du drunknar", ["You are drunk"] = "Du är full.", ["You are electrified"] = "Du är elektrifierad", ["You are freezing"] = "Du Fryser", ["You are hasted"] = "Du är i hast", ["You are hungry"] = "Du är hungrig", ["You are paralysed"] = "Du är paralyserad", ["You are poisoned"] = "Du är förgiftad", ["You are protected by a magic shield"] = "Du är skyddad av en magisk sköld", ["You are strengthened"] = "Du är förstärkt", ["You are within a protection zone"] = "Du är inom en skyddszon", ["You can enter new text."] = "Du kan skriva i ny text.", ["You have %s percent"] = "Du har %s procent", ["You have %s percent to go"] = "Du har %s procent kvar", ["You may not logout during a fight"] = "Du kan ej logga ut i strid", ["You may not logout or enter a protection zone"] = "Du kan ej logga ut eller gå in i en skyddszon", ["You must enter a comment."] = "Du måste skriva en kommentar", ["You must enter a valid server address and port."] = "Du måste fylla i en giltig server adress och port", ["You must select a character to login!"] = "Du måste välja en karaktär för att logga in!", ["Your Capacity:"] = "Din Kapacitet:", ["You read the following, written by \n%s\n"] = "Du läser följande, Skrivet av \n%s\n", ["You read the following, written on \n%s.\n"] = false, ["Your Money:"] = "Dina Pengar:", } } modules.client_locales.installLocale(locale)
mit
stanfordnlp/treelstm
relatedness/main.lua
10
5522
--[[ Training script for semantic relatedness prediction on the SICK dataset. --]] require('..') -- Pearson correlation function pearson(x, y) x = x - x:mean() y = y - y:mean() return x:dot(y) / (x:norm() * y:norm()) end -- read command line arguments local args = lapp [[ Training script for semantic relatedness prediction on the SICK dataset. -m,--model (default dependency) Model architecture: [dependency, constituency, lstm, bilstm] -l,--layers (default 1) Number of layers (ignored for Tree-LSTM) -d,--dim (default 150) LSTM memory dimension -e,--epochs (default 10) Number of training epochs ]] local model_name, model_class if args.model == 'dependency' then model_name = 'Dependency Tree LSTM' model_class = treelstm.TreeLSTMSim elseif args.model == 'constituency' then model_name = 'Constituency Tree LSTM' model_class = treelstm.TreeLSTMSim elseif args.model == 'lstm' then model_name = 'LSTM' model_class = treelstm.LSTMSim elseif args.model == 'bilstm' then model_name = 'Bidirectional LSTM' model_class = treelstm.LSTMSim end local model_structure = args.model header(model_name .. ' for Semantic Relatedness') -- directory containing dataset files local data_dir = 'data/sick/' -- load vocab local vocab = treelstm.Vocab(data_dir .. 'vocab-cased.txt') -- load embeddings print('loading word embeddings') local emb_dir = 'data/glove/' local emb_prefix = emb_dir .. 'glove.840B' local emb_vocab, emb_vecs = treelstm.read_embedding(emb_prefix .. '.vocab', emb_prefix .. '.300d.th') local emb_dim = emb_vecs:size(2) -- use only vectors in vocabulary (not necessary, but gives faster training) local num_unk = 0 local vecs = torch.Tensor(vocab.size, emb_dim) for i = 1, vocab.size do local w = vocab:token(i) if emb_vocab:contains(w) then vecs[i] = emb_vecs[emb_vocab:index(w)] else num_unk = num_unk + 1 vecs[i]:uniform(-0.05, 0.05) end end print('unk count = ' .. num_unk) emb_vocab = nil emb_vecs = nil collectgarbage() -- load datasets print('loading datasets') local train_dir = data_dir .. 'train/' local dev_dir = data_dir .. 'dev/' local test_dir = data_dir .. 'test/' local constituency = (args.model == 'constituency') local train_dataset = treelstm.read_relatedness_dataset(train_dir, vocab, constituency) local dev_dataset = treelstm.read_relatedness_dataset(dev_dir, vocab, constituency) local test_dataset = treelstm.read_relatedness_dataset(test_dir, vocab, constituency) printf('num train = %d\n', train_dataset.size) printf('num dev = %d\n', dev_dataset.size) printf('num test = %d\n', test_dataset.size) -- initialize model local model = model_class{ emb_vecs = vecs, structure = model_structure, num_layers = args.layers, mem_dim = args.dim, } -- number of epochs to train local num_epochs = args.epochs -- print information header('model configuration') printf('max epochs = %d\n', num_epochs) model:print_config() -- train local train_start = sys.clock() local best_dev_score = -1.0 local best_dev_model = model header('Training model') for i = 1, num_epochs do local start = sys.clock() printf('-- epoch %d\n', i) model:train(train_dataset) printf('-- finished epoch in %.2fs\n', sys.clock() - start) -- uncomment to compute train scores --[[ local train_predictions = model:predict_dataset(train_dataset) local train_score = pearson(train_predictions, train_dataset.labels) printf('-- train score: %.4f\n', train_score) --]] local dev_predictions = model:predict_dataset(dev_dataset) local dev_score = pearson(dev_predictions, dev_dataset.labels) printf('-- dev score: %.4f\n', dev_score) if dev_score > best_dev_score then best_dev_score = dev_score best_dev_model = model_class{ emb_vecs = vecs, structure = model_structure, num_layers = args.layers, mem_dim = args.dim, } best_dev_model.params:copy(model.params) end end printf('finished training in %.2fs\n', sys.clock() - train_start) -- evaluate header('Evaluating on test set') printf('-- using model with dev score = %.4f\n', best_dev_score) local test_predictions = best_dev_model:predict_dataset(test_dataset) local test_score = pearson(test_predictions, test_dataset.labels) printf('-- test score: %.4f\n', test_score) -- create predictions and model directories if necessary if lfs.attributes(treelstm.predictions_dir) == nil then lfs.mkdir(treelstm.predictions_dir) end if lfs.attributes(treelstm.models_dir) == nil then lfs.mkdir(treelstm.models_dir) end -- get paths local file_idx = 1 local predictions_save_path, model_save_path while true do predictions_save_path = string.format( treelstm.predictions_dir .. '/rel-%s.%dl.%dd.%d.pred', args.model, args.layers, args.dim, file_idx) model_save_path = string.format( treelstm.models_dir .. '/rel-%s.%dl.%dd.%d.th', args.model, args.layers, args.dim, file_idx) if lfs.attributes(predictions_save_path) == nil and lfs.attributes(model_save_path) == nil then break end file_idx = file_idx + 1 end -- write predictions to disk local predictions_file = torch.DiskFile(predictions_save_path, 'w') print('writing predictions to ' .. predictions_save_path) for i = 1, test_predictions:size(1) do predictions_file:writeFloat(test_predictions[i]) end predictions_file:close() -- write models to disk print('writing model to ' .. model_save_path) best_dev_model:save(model_save_path) -- to load a saved model -- local loaded = model_class.load(model_save_path)
gpl-2.0
rlcevg/Zero-K
effects/ataalaser.lua
8
4970
return { ["ataalaser"] = { groundsmoke = { class = [[CSimpleParticleSystem]], count = 1, ground = 0, unit = 1, properties = { airdrag = 0.8, colormap = [[0.2 0 0.25 1 0.4 0 0.7 1 0 0 0 0]], directional = true, emitrot = 0, emitrotspread = 20, emitvector = [[0, 1, 0]], gravity = [[0, 2, 0]], numparticles = 1, particlelife = 4, particlelifespread = 10, particlesize = 4, particlesizespread = 20, particlespeed = 1, particlespeedspread = 7, pos = [[0 r-10 r10, 0 r-10 r10, 0 r-10 r10]], sizegrowth = 1.7, sizemod = 1, texture = [[smokesmall]], }, }, flash = { class = [[CSimpleParticleSystem]], count = 1, ground = 1, air = 1, properties = { airdrag = 0.8, colormap = [[0.25 0.35 1 0.01 0 0 0 0]], directional = true, emitrot = 0, emitrotspread = 20, emitvector = [[0, 1, 0]], gravity = [[0, 2, 0]], numparticles = 1, particlelife = 8, particlelifespread = 8, particlesize = 4, particlesizespread = 18, particlespeed = 1, particlespeedspread = 7, pos = [[0 r-10 r10, 0 r-10 r10, 0 r-10 r10]], sizegrowth = 1.5, sizemod = 1, texture = [[flare]], }, }, flash2 = { class = [[CSimpleParticleSystem]], count = 1, ground = 1, air = 1, properties = { airdrag = 0.8, colormap = [[0.3 0.15 0.9 0.01 0 0 0 0]], directional = 0, emitrot = 0, emitrotspread = 0, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 15, particlelifespread = 4, particlesize = 8, particlesizespread = 4, particlespeed = 1, particlespeedspread = 7, pos = [[0,15,0]], sizegrowth = 1, sizemod = 1.1, texture = [[flare]], }, }, stacheln1 = { air = true, class = [[explspike]], count = 2, ground = true, water = true, properties = { alpha = 2, alphadecay = 0.25, color = [[0.15, 0.25, 1]], dir = [[r20 r-15, r-15 r20, r20 r-15]], length = 10, lengthgrowth = -3, pos = [[0, 1, 0]], width = 20, }, }, funken = { class = [[CSimpleParticleSystem]], count = 1, ground = true, unit = 1, properties = { airdrag = 1, colormap = [[0.15 0.25 1 0.01 0.3 0.15 0.75 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 90, emitvector = [[0,1,0]], gravity = [[0,0, 0]], numparticles = 5, particlelife = 12, particlelifespread = 15, particlesize = 6, particlesizespread = 0, particlespeed = 4, particlespeedspread = 5, pos = [[0, 1, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[gunshot]], }, }, yudell = { air = false, class = [[CSimpleGroundFlash]], count = 1, ground = true, water = false, properties = { colormap = [[0.6 0.25 1 0.2 0.4 0.2 1 0.2 0 0 0 0]], size = 80, sizegrowth = [[-1.25]], texture = [[groundflash]], ttl = 60, }, }, yudell3 = { air = false, class = [[CSimpleGroundFlash]], count = 1, ground = true, water = false, properties = { colormap = [[1 1 0 0.2 1 .45 0 0.2 0 0 0 0]], size = 20, sizegrowth = [[-1.25]], texture = [[groundflash]], ttl = 60, }, }, }, }
gpl-2.0
EliHar/Pattern_recognition
openface1/training/attic/test-hardNeg.lua
8
6898
-- Copyright 2015-2016 Carnegie Mellon University -- -- 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. testLogger = optim.Logger(paths.concat(opt.save, 'test.log')) local batchNumber local triplet_loss local timer = torch.Timer() function test() print('==> doing epoch on validation data:') print("==> online epoch # " .. epoch) batchNumber = 0 cutorch.synchronize() timer:reset() model:evaluate() model:cuda() triplet_loss = 0 local i = 1 while batchNumber < opt.epochSize do donkeys:addjob( function() local inputs, numPerClass = trainLoader:samplePeople(opt.peoplePerBatch, opt.imagesPerPerson) inputs = inputs:float() numPerClass = numPerClass:float() return sendTensor(inputs), sendTensor(numPerClass) end, testBatch ) if i % 5 == 0 then donkeys:synchronize() collectgarbage() end i = i + 1 end donkeys:synchronize() cutorch.synchronize() triplet_loss = triplet_loss / opt.testEpochSize testLogger:add{ ['avg triplet loss (test set)'] = triplet_loss } print(string.format('Epoch: [%d][TESTING SUMMARY] Total Time(s): %.2f \t' .. 'average triplet loss (per batch): %.2f', epoch, timer:time().real, triplet_loss)) print('\n') end local inputsCPU = torch.FloatTensor() local numPerClass = torch.FloatTensor() function testBatch(inputsThread, numPerClassThread) if batchNumber >= opt.epochSize then return end cutorch.synchronize() timer:reset() receiveTensor(inputsThread, inputsCPU) receiveTensor(numPerClassThread, numPerClass) -- inputs:resize(inputsCPU:size()):copy(inputsCPU) local numImages = inputsCPU:size(1) local embeddings = torch.Tensor(numImages, 128) local singleNet = model.modules[1] local beginIdx = 1 local inputs = torch.CudaTensor() while beginIdx <= numImages do local endIdx = math.min(beginIdx+opt.testBatchSize-1, numImages) local range = {{beginIdx,endIdx}} local sz = inputsCPU[range]:size() inputs:resize(sz):copy(inputsCPU[range]) local reps = singleNet:forward(inputs):float() embeddings[range] = reps beginIdx = endIdx + 1 end assert(beginIdx - 1 == numImages) local numTrips = numImages - opt.peoplePerBatch local as = torch.Tensor(numTrips, inputs:size(2), inputs:size(3), inputs:size(4)) local ps = torch.Tensor(numTrips, inputs:size(2), inputs:size(3), inputs:size(4)) local ns = torch.Tensor(numTrips, inputs:size(2), inputs:size(3), inputs:size(4)) function dist(emb1, emb2) local d = emb1 - emb2 return d:cmul(d):sum() end local tripIdx = 1 local shuffle = torch.randperm(numTrips) local embStartIdx = 1 local nRandomNegs = 0 for i = 1,opt.peoplePerBatch do local n = numPerClass[i] for j = 1,n-1 do local aIdx = embStartIdx local pIdx = embStartIdx+j as[shuffle[tripIdx]] = inputsCPU[aIdx] ps[shuffle[tripIdx]] = inputsCPU[pIdx] -- Select a semi-hard negative that has a distance -- further away from the positive exemplar. local posDist = dist(embeddings[aIdx], embeddings[pIdx]) local selNegIdx = embStartIdx while selNegIdx >= embStartIdx and selNegIdx <= embStartIdx+n-1 do selNegIdx = (torch.random() % numImages) + 1 end local selNegDist = dist(embeddings[aIdx], embeddings[selNegIdx]) local randomNeg = true for k = 1,numImages do if k < embStartIdx or k > embStartIdx+n-1 then local negDist = dist(embeddings[aIdx], embeddings[k]) if posDist < negDist and negDist < selNegDist and math.abs(posDist-negDist) < alpha then randomNeg = false selNegDist = negDist selNegIdx = k end end end if randomNeg then nRandomNegs = nRandomNegs + 1 end ns[shuffle[tripIdx]] = inputsCPU[selNegIdx] tripIdx = tripIdx + 1 end embStartIdx = embStartIdx + n end assert(embStartIdx - 1 == numImages) assert(tripIdx - 1 == numTrips) print((' + (nRandomNegs, nTrips) = (%d, %d)'):format(nRandomNegs, numTrips)) beginIdx = 1 local asCuda = torch.CudaTensor() local psCuda = torch.CudaTensor() local nsCuda = torch.CudaTensor() -- Return early if the loss is 0 for `numZeros` iterations. local numZeros = 4 local zeroCounts = torch.IntTensor(numZeros):zero() local zeroIdx = 1 -- Return early if the loss shrinks too much. -- local firstLoss = nil -- TODO: Should be <=, but batches with just one image cause errors. while beginIdx < numTrips do local endIdx = math.min(beginIdx+opt.testBatchSize, numTrips) local range = {{beginIdx,endIdx}} local sz = as[range]:size() asCuda:resize(sz):copy(as[range]) psCuda:resize(sz):copy(ps[range]) nsCuda:resize(sz):copy(ns[range]) local output = model:forward({asCuda, psCuda, nsCuda}) local err = criterion:forward(output) cutorch.synchronize() batchNumber = batchNumber + 1 print(string.format('Epoch: [%d][%d/%d] Triplet Loss: %.2f', epoch, batchNumber, opt.testEpochSize, err)) timer:reset() triplet_loss = triplet_loss + err -- Return early if the epoch is over. if batchNumber >= opt.epochSize then return end -- Return early if the loss is 0 for `numZeros` iterations. zeroCounts[zeroIdx] = (err == 0.0) and 1 or 0 -- Boolean to int. zeroIdx = (zeroIdx % numZeros) + 1 if zeroCounts:sum() == numZeros then return end -- Return early if the loss shrinks too much. -- if firstLoss == nil then -- firstLoss = err -- else -- -- Triplets trivially satisfied if err=0 -- if err ~= 0 and firstLoss/err > 4 then -- return -- end -- end beginIdx = endIdx + 1 end assert(beginIdx - 1 == numTrips or beginIdx == numTrips) end
mit
TeleBang/bangtg
plugins/funhelp.lua
2
2826
do function run(msg, matches) if msg.to.type == 'channel' and is_momod(msg) then return ''..[[ ➖➖➖➖➖➖➖ ✔️لیست دستورات فان: ➖➖➖➖➖➖➖ 💢》#فعالان گروه ❔لیست سه فعال گروه 💢》#درباره من ❔اطلاعاتی درباره شما 💢》#استیکر نوشته (کلمه) ❔نوشتن متن بر روی استیکر 💢》#استیکر ❔تبدیل عکس به استیکر با ریپلی بر روی عکس 💢》#عکس ❔تبدیل استیکر به عکس با ریپلی برروی استیکر 💢》#گیف ❔تبدیل ویدیو به گیف با ریپلی بر روی ویدیو 💢》#آهنگ ❔تبدیل وویس به اهنگ با ریپلی بر روی وویس 💢》#فیلم ❔تبدیل گیف به ویدیو با ریپلی بر روی گیف 💢》#وویس (متن) ❔تبدیل متن به وویس 💢》#جستجوی (متن) ❔جستجو در اپارات 💢》#نوشتن (کلمه) ❔نوشتن اسم یا کلمه با 100 فونت زیبا 💢》#هواشناسی (شهر) ❔هواشناسی(بجای شهر نام شهر مورد نظر را به انگلیسی بنویسید) 💢》#زمان ❔زمان بصورت استیکر 💢》زمان (مکان) نمایش زمان مکان مورد نظر شما(مثلا:مادرید) 💢》#اذان (شهر) ❔زمان تمامی اذان های یک شهر(جای شهر نام شهر مورد نظر رابه انگلیسی بنویسید) 💢》#ترجمه انگلیسی (متن) ❔ترجمه فارسی به انگلیسی 💢》#ترجمه فارسی (متن) ❔ترجمه انگلیسی به فارسی 💢》#معنی (کلمه) ❔معنی کلمات فارسی ومعنی اسامی فارسی 💢》#گیف (کلمه) ❔کلمه یا اسم شما بصورت گیف 💢》#ماشین حساب عدد(-+×÷)عدد ❔حساب چهار عمل اصلی ریاضی 💢》#کوتاه کردن (لینک) کوتاه کردن لینک شما(بجای (لینک) لینک خود را قرار دهید) 💢》#لینک اصلی (لینک کوتاه شده) ❔تبدیل لینک کوتاه شده به لینک اصلی 💢》#اخبار ❔جدیدترین اخبار 💢》#معادل (مقدارپول) ❔مقدار ارز در بازار 💢》#عکس نوشته (متن) ❔کلمه یا اسم شما بصورت عکس ➰بجای کلمه یا متن موارد دلخواه خود را بنویسید. ➖➖➖➖➖➖➖ ➰ ʝօìղ մʂ ìժ çհ : ➰ @antispamandhack ➖➖➖➖➖➖➖ ]] end end return { description = "Robot and Creator About", usage = "/ver : robot info", patterns = { "^[!#/]راهنمای فان$", }, run = run } end
agpl-3.0
DrFR0ST/Human-Apocalypse
lib/shine/init.lua
7
3313
--[[ The MIT License (MIT) Copyright (c) 2015 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local BASE = ... local shine = {} shine.__index = shine -- commonly used utility function function shine._render_to_canvas(_, canvas, func, ...) local old_canvas = love.graphics.getCanvas() love.graphics.setCanvas(canvas) love.graphics.clear() func(...) love.graphics.setCanvas(old_canvas) end function shine._apply_shader_to_scene(_, shader, canvas, func, ...) local s = love.graphics.getShader() local co = {love.graphics.getColor()} -- draw scene to canvas shine._render_to_canvas(_, canvas, func, ...) -- apply shader to canvas love.graphics.setColor(co) love.graphics.setShader(shader) local b = love.graphics.getBlendMode() love.graphics.setBlendMode('alpha', 'premultiplied') love.graphics.draw(canvas, 0,0) love.graphics.setBlendMode(b) -- reset shader and canvas love.graphics.setShader(s) end -- effect chaining function shine.chain(first, second) local effect = {} function effect:set(k, v) local ok = pcall(first.set, first, k, v) ok = pcall(second.set, second, k, v) or ok if not ok then error("Unknown property: " .. tostring(k)) end end function effect:draw(func, ...) local args = {n = select('#',...), ...} second(function() first(func, unpack(args, 1, args.n)) end) end return setmetatable(effect, {__newindex = shine.__newindex, __index = shine, __call = effect.draw}) end -- guards function shine.draw() error("Incomplete effect: draw(func) not implemented", 2) end function shine.set() error("Incomplete effect: set(key, value) not implemented", 2) end function shine.__newindex(self, k, v) if k == "parameters" then assert(type(v) == "table") for k,v in pairs(v) do self:set(k,v) end else self:set(k, v) end end return setmetatable({}, {__index = function(self, key) local ok, effect = pcall(require, BASE .. "." .. key) if not ok then error("No such effect: "..key, 2) end setmetatable(effect, shine) local constructor = function(t) local instance = {} effect.new(instance) setmetatable(instance, {__newindex = shine.__newindex, __index = effect, __call = effect.draw}) if t and type(t) == "table" then instance.parameters = t end return instance end self[key] = constructor return constructor end})
mit
cailyoung/CommandPost
src/extensions/cp/apple/finalcutpro/main/KeywordEditor.lua
1
17340
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- F I N A L C U T P R O A P I -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === cp.apple.finalcutpro.main.KeywordEditor === --- --- Keyword Editor Module. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Logger: -------------------------------------------------------------------------------- local log = require("hs.logger").new("keywordEditor") -------------------------------------------------------------------------------- -- CommandPost Extensions: -------------------------------------------------------------------------------- local axutils = require("cp.ui.axutils") local prop = require("cp.prop") -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local KeywordEditor = {} --- cp.apple.finalcutpro.main.KeywordEditor:new(parent) -> KeywordEditor object --- Method --- Creates a new KeywordEditor object --- --- Parameters: --- * `parent` - The parent --- --- Returns: --- * A KeywordEditor object function KeywordEditor:new(parent) local o = { _parent = parent, _child = {} } return prop.extend(o, KeywordEditor) end --- cp.apple.finalcutpro.main.KeywordEditor:parent() -> table --- Method --- Returns the KeywordEditor's parent table --- --- Parameters: --- * None --- --- Returns: --- * The parent object as a table function KeywordEditor:parent() return self._parent end --- cp.apple.finalcutpro.main.KeywordEditor:app() -> table --- Method --- Returns the `cp.apple.finalcutpro` app table --- --- Parameters: --- * None --- --- Returns: --- * The application object as a table function KeywordEditor:app() return self:parent():app() end --- cp.apple.finalcutpro.main.KeywordEditor:toolbarCheckBoxUI() -> hs._asm.axuielement object --- Method --- Returns the `hs._asm.axuielement` object for the Keyword Editor button in the toolbar --- --- Parameters: --- * None --- --- Returns: --- * A `hs._asm.axuielement` object function KeywordEditor:toolbarCheckBoxUI() return axutils.cache(self, "_toolbarCheckBoxUI", function() local primaryWindowUI = self:parent():primaryWindow():UI() if not primaryWindowUI then return nil end local toolbar = axutils.childWithRole(primaryWindowUI, "AXToolbar") if not toolbar then return nil end local group = axutils.childWithRole(toolbar, "AXGroup") if not group then return nil end local checkBox = axutils.childWithRole(group, "AXCheckBox") return checkBox end) end --- cp.apple.finalcutpro.main.KeywordEditor.matches(element) -> boolean --- Function --- Checks to see if an `hs._asm.axuielement` object matches a Keyword Editor window --- --- Parameters: --- * element - the `hs._asm.axuielement` object you want to check --- --- Returns: --- * `true` if a match otherwise `false` function KeywordEditor.matches(element) if element then return element:attributeValue("AXSubrole") == "AXDialog" and element:attributeValueCount("AXChildren") == 6 or element:attributeValueCount("AXChildren") == 26 end return false end --- cp.apple.finalcutpro.main.KeywordEditor:UI() -> hs._asm.axuielement object --- Method --- Returns the `hs._asm.axuielement` object for the Keyword Editor window --- --- Parameters: --- * None --- --- Returns: --- * A `hs._asm.axuielement` object function KeywordEditor:UI() return axutils.cache(self, "_ui", function() local windowsUI = self:parent():windowsUI() return windowsUI and self:_findWindowUI(windowsUI) end, KeywordEditor.matches) end -- cp.apple.finalcutpro.main.KeywordEditor_findWindowUI(windows) -> hs._asm.axuielement object | nil -- Method -- Finds the Keyword Editor window. -- -- Parameters: -- * windows - a table of `hs._asm.axuielement` object to search -- -- Returns: -- * A `hs._asm.axuielement` object if succesful otherwise `nil` function KeywordEditor:_findWindowUI(windows) for _,window in ipairs(windows) do if KeywordEditor.matches(window) then return window end end return nil end --- cp.apple.finalcutpro.main.KeywordEditor:isShowing() -> boolean --- Method --- Gets whether or not the Keyword Editor is currently showing. --- --- Parameters: --- * None --- --- Returns: --- * `true` if showing otherwise `false` function KeywordEditor:isShowing() local checkBox = self:toolbarCheckBoxUI() return checkBox and checkBox:attributeValue("AXValue") == 1 end --- cp.apple.finalcutpro.main.KeywordEditor:show() -> boolean --- Method --- Shows the Keyword Editor. --- --- Parameters: --- * None --- --- Returns: --- * KeywordEditor object --- * `true` if successful otherwise `false` function KeywordEditor:show() local checkBox = self:toolbarCheckBoxUI() if checkBox and checkBox:attributeValue("AXValue") == 0 then local result = checkBox:performAction("AXPress") if result then return self, true end end return self, false end --- cp.apple.finalcutpro.main.KeywordEditor:hide() -> boolean --- Method --- Hides the Keyword Editor. --- --- Parameters: --- * None --- --- Returns: --- * KeywordEditor object --- * `true` if successful otherwise `false` function KeywordEditor:hide() local checkBox = self:toolbarCheckBoxUI() if checkBox and checkBox:attributeValue("AXValue") == 1 then if checkBox:performAction("AXPress") then return self, true end end return self, false end --- cp.apple.finalcutpro.main.KeywordEditor:keyword(value) -> string | table | nil --- Method --- Sets or gets the main Keyword Textbox value. --- --- Parameters: --- * value - The value you want to set the keyword textbox to. This can either be a string, with the tags separated by a comma, or a table of tags. --- --- Returns: --- * `value` if successful otherwise `false` function KeywordEditor:keyword(value) local ui = self:UI() if type(value) == "nil" then -------------------------------------------------------------------------------- -- Getter: -------------------------------------------------------------------------------- local result = {} if ui then local textbox = axutils.childWithRole(ui, "AXTextField") if textbox then local children = textbox:attributeValue("AXChildren") for _, child in ipairs(children) do table.insert(result, child:attributeValue("AXValue")) end return result end end log.ef("Could not get Keyword.") return false else -------------------------------------------------------------------------------- -- Setter: -------------------------------------------------------------------------------- if ui then local textbox = axutils.childWithRole(ui, "AXTextField") if textbox then if type(value) == "string" then if textbox:setAttributeValue("AXValue", value) then if textbox:performAction("AXConfirm") then return value end end elseif type(value) == "table" and #value >= 1 then local result = table.concat(value, ", ") if result and textbox:setAttributeValue("AXValue", result) then if textbox:performAction("AXConfirm") then return value end end end end end log.ef("Could not set Keyword.") return false end end --- cp.apple.finalcutpro.main.KeywordEditor:removeKeyword(keyword) -> boolean --- Method --- Removes a keyword from the main Keyword Textbox. --- --- Parameters: --- * keyword - The keyword you want to remove as a string. --- --- Returns: --- * `true` if successful otherwise `false` function KeywordEditor:removeKeyword(keyword) if type(keyword) ~= "string" then log.ef("Keyword is invalid.") return false end local ui = self:UI() local result = {} if ui then local textbox = axutils.childWithRole(ui, "AXTextField") if textbox then local children = textbox:attributeValue("AXChildren") local found = false for _, child in ipairs(children) do local value = child:attributeValue("AXValue") if keyword ~= value then table.insert(result, value) else found = true end end if not found then log.ef("Could not find keyword to remove: %s", keyword) return false end local resultString = table.concat(result, ", ") log.df("resultString: %s", resultString) if resultString and textbox:setAttributeValue("AXValue", resultString) then if textbox:performAction("AXConfirm") then return true end end end end log.ef("Could not find UI.") return false end -------------------------------------------------------------------------------- -- -- KEYBOARD SHORTCUTS: -- -------------------------------------------------------------------------------- --- === cp.apple.finalcutpro.main.KeywordEditor.KeyboardShortcuts === --- --- Keyboard Shortcuts local KeyboardShortcuts = {} function KeywordEditor:keyboardShortcuts() return KeyboardShortcuts:new(self) end --- cp.apple.finalcutpro.main.KeywordEditor.KeyboardShortcuts:new(parent) -> KeyboardShortcuts object --- Method --- Creates a new KeyboardShortcuts object --- --- Parameters: --- * `parent` - The parent --- --- Returns: --- * A KeyboardShortcuts object function KeyboardShortcuts:new(parent) local o = { _parent = parent, _child = {} } return prop.extend(o, KeyboardShortcuts) end --- cp.apple.finalcutpro.main.KeywordEditor.KeyboardShortcuts:parent() -> table --- Method --- Returns the KeywordShortcuts's parent table --- --- Parameters: --- * None --- --- Returns: --- * The parent object as a table function KeyboardShortcuts:parent() return self._parent end --- cp.apple.finalcutpro.main.KeywordEditor.KeyboardShortcuts:isShowing() -> boolean --- Method --- Gets whether or not the Keyword Editor's Keyboard Shortcuts section is currently showing. --- --- Parameters: --- * None --- --- Returns: --- * `true` if showing otherwise `false` function KeyboardShortcuts:isShowing() local ui = self:parent():UI() local disclosureTriangle = axutils.childWithRole(ui, "AXDisclosureTriangle") return disclosureTriangle and disclosureTriangle:attributeValue("AXValue") == 1 end --- cp.apple.finalcutpro.main.KeywordEditor.KeyboardShortcuts:show() -> boolean --- Method --- Shows the Keyword Editor's Keyboard Shortcuts section. --- --- Parameters: --- * None --- --- Returns: --- * `true` if successful otherwise `false` function KeyboardShortcuts:show() local ui = self:parent():UI() local disclosureTriangle = axutils.childWithRole(ui, "AXDisclosureTriangle") if disclosureTriangle:attributeValue("AXValue") == 0 then if disclosureTriangle:performAction("AXPress") then return true end end return false end --- cp.apple.finalcutpro.main.KeywordEditor.KeyboardShortcuts:hide() -> boolean --- Method --- Hides the Keyword Editor's Keyboard Shortcuts section. --- --- Parameters: --- * None --- --- Returns: --- * `true` if successful otherwise `false` function KeyboardShortcuts:hide() local ui = self:parent():UI() local disclosureTriangle = axutils.childWithRole(ui, "AXDisclosureTriangle") if disclosureTriangle:attributeValue("AXValue") == 1 then if disclosureTriangle:performAction("AXPress") then return true end end return false end --- cp.apple.finalcutpro.main.KeywordEditor.KeyboardShortcuts:keyword(item, value) -> string | table | nil --- Method --- Sets or gets a specific Keyboard Shortcut Keyword Textbox value. --- --- Parameters: --- * item - The textbox you want to update. This can be a number between 1 and 9. --- * value - The value you want to set the keyword textbox to. This can either be a string, with the tags separated by a comma, or a table of tags. --- --- Returns: --- * `value` if successful otherwise `false` function KeyboardShortcuts:keyword(item, value) if not item or type(item) ~= "number" or item < 1 or item > 9 then log.ef("The keyboard shortcuts item must be between 1 and 9.") return nil end item = item + 1 if not self:isShowing() then self:show() end local ui = self:parent():UI() if ui then local textfields = axutils.childrenWith(ui, "AXRole", "AXTextField") if textfields and #textfields == 10 then if type(value) == "nil" then -------------------------------------------------------------------------------- -- Getter: -------------------------------------------------------------------------------- local result = {} if #textfields[item]:attributeValue("AXChildren") > 0 then local children = textfields[item]:attributeValue("AXChildren") for _, child in ipairs(children) do table.insert(result, child:attributeValue("AXValue")) end return result end return {} elseif type(value) == "string" then -------------------------------------------------------------------------------- -- String Setter: -------------------------------------------------------------------------------- if textfields[item]:setAttributeValue("AXValue", value) then if textfields[item]:performAction("AXConfirm") then return value end end elseif type(value) == "table" then -------------------------------------------------------------------------------- -- String Setter: -------------------------------------------------------------------------------- local result = "" for _, v in pairs(value) do result = result .. v .. ", " end if textfields[item]:setAttributeValue("AXValue", result) then if textfields[item]:performAction("AXConfirm") then return value end end end log.ef("Failed to set Keyword.") return false end end return false end --- cp.apple.finalcutpro.main.KeywordEditor.KeyboardShortcuts:apply(item) -> boolean --- Method --- Applies a Keyword Shortcut. --- --- Parameters: --- * item - The textbox you want to update. This can be a number between 1 and 9. --- --- Returns: --- * `true` if successful otherwise `false` function KeyboardShortcuts:apply(item) if not item or type(item) ~= "number" or item < 1 or item > 9 then log.ef("The keyboard shortcuts item must be between 1 and 9.") return false end if not self:isShowing() then self:show() end local ui = self:parent():UI() if ui then local buttons = axutils.childrenWith(ui, "AXRole", "AXButton") if buttons and #buttons == 11 then if buttons[item]:performAction("AXPress") then return true end end end log.ef("Failed to Apply Keyword.") return false end --- cp.apple.finalcutpro.main.KeywordEditor.KeyboardShortcuts:removeAllKeywords() -> boolean --- Method --- Triggers the "Remove all Keywords" button. --- --- Parameters: --- * None --- --- Returns: --- * `true` if successful otherwise `false` function KeyboardShortcuts:removeAllKeywords() if not self:isShowing() then self:show() end local ui = self:parent():UI() if ui then local buttons = axutils.childrenWith(ui, "AXRole", "AXButton") if buttons and #buttons == 11 then if buttons[10]:performAction("AXPress") then return true end end end log.ef("Could not remove all keywords.") return false end return KeywordEditor
mit
mrjon1/kpbot
plugins/get.lua
613
1067
local function get_variables_hash(msg) if msg.to.type == 'chat' then return 'chat:'..msg.to.id..':variables' end if msg.to.type == 'user' then return 'user:'..msg.from.id..':variables' end end local function list_variables(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do text = text..names[i]..'\n' end return text end end local function get_value(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return'Not found, use "!get" to list variables' else return var_name..' => '..value end end end local function run(msg, matches) if matches[2] then return get_value(msg, matches[2]) else return list_variables(msg) end end return { description = "Retrieves variables saved with !set", usage = "!get (value_name): Returns the value_name value.", patterns = { "^(!get) (.+)$", "^!get$" }, run = run }
gpl-2.0
avataronline/avatarclient
modules/game_shadermanager/shadermanager.lua
1
1859
local MapShaders = { ["default"] = { path = "/data/shaders/default.frag" }; ["temple_effect"] = { path = "/data/shaders/temple_effect.frag" }; ["red_alert"] = {path = "/data/shaders/red_alert.frag"}; ["challenge_effect"] = {path = "/data/shaders/challenge_effect.frag"}; ["test1"] = {path = "/data/shaders/test1.frag"}; ["test2"] = {path = "/data/shaders/test2.frag"}; ["test3"] = {path = "/data/shaders/test3.frag"}; ["test4"] = {path = "/data/shaders/test4.frag"}; ["test5"] = {path = "/data/shaders/test5.frag"}; ["test6"] = {path = "/data/shaders/test6.frag"}; ["test7"] = {path = "/data/shaders/test7.frag"}; ["test8"] = {path = "/data/shaders/test8.frag"}; ["test9"] = {path = "/data/shaders/test9.frag"}; ["test10"] = {path = "/data/shaders/test10.frag"}; ["test11"] = {path = "/data/shaders/test11.frag"}; } local function parseShader(protocol, opcode, buffer) local msg = InputMessage.create() msg:setBuffer(buffer) local packet = msg:getStrTable() if not g_graphics.canUseShaders() then return end local map = modules.game_interface.getMapPanel() if packet.action == "active" then local shader = g_shaders.getShader(packet.name) if shader then map:setMapShader(shader) end return end map:setMapShader(g_shaders.getDefaultMapShader()) modules.game_healthinfo.checkHealthAlert() end function init() ProtocolGame.registerExtendedOpcode(ExtendedIds.MapShader, parseShader) for name, opts in pairs(MapShaders) do local shader = g_shaders.createFragmentShader(name, opts.path) if opts.tex1 then shader:addMultiTexture(opts.tex1) end if opts.tex2 then shader:addMultiTexture(opts.tex2) end if opts.tex3 then shader:addMultiTexture(opts.tex3) end end end function terminate() ProtocolGame.unregisterExtendedOpcode(ExtendedIds.MapShader, parseShader) end
mit
botme2018/sky202020
tg/tdcli.lua
102
88571
--[[ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ]]-- -- Vector example form is like this: {[0] = v} or {v1, v2, v3, [0] = v} -- If false or true crashed your telegram-cli, try to change true to 1 and false to 0 -- Main Bot Framework local M = {} -- @chat_id = user, group, channel, and broadcast -- @group_id = normal group -- @channel_id = channel and broadcast local function getChatId(chat_id) local chat = {} local chat_id = tostring(chat_id) if chat_id:match('^-100') then local channel_id = chat_id:gsub('-100', '') chat = {ID = channel_id, type = 'channel'} else local group_id = chat_id:gsub('-', '') chat = {ID = group_id, type = 'group'} end return chat end local function getInputFile(file) if file:match('/') then infile = {ID = "InputFileLocal", path_ = file} elseif file:match('^%d+$') then infile = {ID = "InputFileId", id_ = file} else infile = {ID = "InputFilePersistentId", persistent_id_ = file} end return infile end -- User can send bold, italic, and monospace text uses HTML or Markdown format. local function getParseMode(parse_mode) if parse_mode then local mode = parse_mode:lower() if mode == 'markdown' or mode == 'md' then P = {ID = "TextParseModeMarkdown"} elseif mode == 'html' then P = {ID = "TextParseModeHTML"} end end return P end -- Returns current authorization state, offline request local function getAuthState(dl_cb, cmd) tdcli_function ({ ID = "GetAuthState", }, dl_cb, cmd) end M.getAuthState = getAuthState -- Sets user's phone number and sends authentication code to the user. -- Works only when authGetState returns authStateWaitPhoneNumber. -- If phone number is not recognized or another error has happened, returns an error. Otherwise returns authStateWaitCode -- @phone_number User's phone number in any reasonable format -- @allow_flash_call Pass True, if code can be sent via flash call to the specified phone number -- @is_current_phone_number Pass true, if the phone number is used on the current device. Ignored if allow_flash_call is False local function setAuthPhoneNumber(phone_number, allow_flash_call, is_current_phone_number, dl_cb, cmd) tdcli_function ({ ID = "SetAuthPhoneNumber", phone_number_ = phone_number, allow_flash_call_ = allow_flash_call, is_current_phone_number_ = is_current_phone_number }, dl_cb, cmd) end M.setAuthPhoneNumber = setAuthPhoneNumber -- Resends authentication code to the user. -- Works only when authGetState returns authStateWaitCode and next_code_type of result is not null. -- Returns authStateWaitCode on success local function resendAuthCode(dl_cb, cmd) tdcli_function ({ ID = "ResendAuthCode", }, dl_cb, cmd) end M.resendAuthCode = resendAuthCode -- Checks authentication code. -- Works only when authGetState returns authStateWaitCode. -- Returns authStateWaitPassword or authStateOk on success -- @code Verification code from SMS, Telegram message, voice call or flash call -- @first_name User first name, if user is yet not registered, 1-255 characters -- @last_name Optional user last name, if user is yet not registered, 0-255 characters local function checkAuthCode(code, first_name, last_name, dl_cb, cmd) tdcli_function ({ ID = "CheckAuthCode", code_ = code, first_name_ = first_name, last_name_ = last_name }, dl_cb, cmd) end M.checkAuthCode = checkAuthCode -- Checks password for correctness. -- Works only when authGetState returns authStateWaitPassword. -- Returns authStateOk on success -- @password Password to check local function checkAuthPassword(password, dl_cb, cmd) tdcli_function ({ ID = "CheckAuthPassword", password_ = password }, dl_cb, cmd) end M.checkAuthPassword = checkAuthPassword -- Requests to send password recovery code to email. -- Works only when authGetState returns authStateWaitPassword. -- Returns authStateWaitPassword on success local function requestAuthPasswordRecovery(dl_cb, cmd) tdcli_function ({ ID = "RequestAuthPasswordRecovery", }, dl_cb, cmd) end M.requestAuthPasswordRecovery = requestAuthPasswordRecovery -- Recovers password with recovery code sent to email. -- Works only when authGetState returns authStateWaitPassword. -- Returns authStateOk on success -- @recovery_code Recovery code to check local function recoverAuthPassword(recovery_code, dl_cb, cmd) tdcli_function ({ ID = "RecoverAuthPassword", recovery_code_ = recovery_code }, dl_cb, cmd) end M.recoverAuthPassword = recoverAuthPassword -- Logs out user. -- If force == false, begins to perform soft log out, returns authStateLoggingOut after completion. -- If force == true then succeeds almost immediately without cleaning anything at the server, but returns error with code 401 and description "Unauthorized" -- @force If true, just delete all local data. Session will remain in list of active sessions local function resetAuth(force, dl_cb, cmd) tdcli_function ({ ID = "ResetAuth", force_ = force or nil }, dl_cb, cmd) end M.resetAuth = resetAuth -- Check bot's authentication token to log in as a bot. -- Works only when authGetState returns authStateWaitPhoneNumber. -- Can be used instead of setAuthPhoneNumber and checkAuthCode to log in. -- Returns authStateOk on success -- @token Bot token local function checkAuthBotToken(token, dl_cb, cmd) tdcli_function ({ ID = "CheckAuthBotToken", token_ = token }, dl_cb, cmd) end M.checkAuthBotToken = checkAuthBotToken -- Returns current state of two-step verification local function getPasswordState(dl_cb, cmd) tdcli_function ({ ID = "GetPasswordState", }, dl_cb, cmd) end M.getPasswordState = getPasswordState -- Changes user password. -- If new recovery email is specified, then error EMAIL_UNCONFIRMED is returned and password change will not be applied until email confirmation. -- Application should call getPasswordState from time to time to check if email is already confirmed -- @old_password Old user password -- @new_password New user password, may be empty to remove the password -- @new_hint New password hint, can be empty -- @set_recovery_email Pass True, if recovery email should be changed -- @new_recovery_email New recovery email, may be empty local function setPassword(old_password, new_password, new_hint, set_recovery_email, new_recovery_email, dl_cb, cmd) tdcli_function ({ ID = "SetPassword", old_password_ = old_password, new_password_ = new_password, new_hint_ = new_hint, set_recovery_email_ = set_recovery_email, new_recovery_email_ = new_recovery_email }, dl_cb, cmd) end M.setPassword = setPassword -- Returns set up recovery email. -- This method can be used to verify a password provided by the user -- @password Current user password local function getRecoveryEmail(password, dl_cb, cmd) tdcli_function ({ ID = "GetRecoveryEmail", password_ = password }, dl_cb, cmd) end M.getRecoveryEmail = getRecoveryEmail -- Changes user recovery email. -- If new recovery email is specified, then error EMAIL_UNCONFIRMED is returned and email will not be changed until email confirmation. -- Application should call getPasswordState from time to time to check if email is already confirmed. -- If new_recovery_email coincides with the current set up email succeeds immediately and aborts all other requests waiting for email confirmation -- @password Current user password -- @new_recovery_email New recovery email local function setRecoveryEmail(password, new_recovery_email, dl_cb, cmd) tdcli_function ({ ID = "SetRecoveryEmail", password_ = password, new_recovery_email_ = new_recovery_email }, dl_cb, cmd) end M.setRecoveryEmail = setRecoveryEmail -- Requests to send password recovery code to email local function requestPasswordRecovery(dl_cb, cmd) tdcli_function ({ ID = "RequestPasswordRecovery", }, dl_cb, cmd) end M.requestPasswordRecovery = requestPasswordRecovery -- Recovers password with recovery code sent to email -- @recovery_code Recovery code to check local function recoverPassword(recovery_code, dl_cb, cmd) tdcli_function ({ ID = "RecoverPassword", recovery_code_ = tostring(recovery_code) }, dl_cb, cmd) end M.recoverPassword = recoverPassword -- Returns current logged in user local function getMe(dl_cb, cmd) tdcli_function ({ ID = "GetMe", }, dl_cb, cmd) end M.getMe = getMe -- Returns information about a user by its identifier, offline request if current user is not a bot -- @user_id User identifier local function getUser(user_id, dl_cb, cmd) tdcli_function ({ ID = "GetUser", user_id_ = user_id }, dl_cb, cmd) end M.getUser = getUser -- Returns full information about a user by its identifier -- @user_id User identifier local function getUserFull(user_id, dl_cb, cmd) tdcli_function ({ ID = "GetUserFull", user_id_ = user_id }, dl_cb, cmd) end M.getUserFull = getUserFull -- Returns information about a group by its identifier, offline request if current user is not a bot -- @group_id Group identifier local function getGroup(group_id, dl_cb, cmd) tdcli_function ({ ID = "GetGroup", group_id_ = getChatId(group_id).ID }, dl_cb, cmd) end M.getGroup = getGroup -- Returns full information about a group by its identifier -- @group_id Group identifier local function getGroupFull(group_id, dl_cb, cmd) tdcli_function ({ ID = "GetGroupFull", group_id_ = getChatId(group_id).ID }, dl_cb, cmd) end M.getGroupFull = getGroupFull -- Returns information about a channel by its identifier, offline request if current user is not a bot -- @channel_id Channel identifier local function getChannel(channel_id, dl_cb, cmd) tdcli_function ({ ID = "GetChannel", channel_id_ = getChatId(channel_id).ID }, dl_cb, cmd) end M.getChannel = getChannel -- Returns full information about a channel by its identifier, cached for at most 1 minute -- @channel_id Channel identifier local function getChannelFull(channel_id, dl_cb, cmd) tdcli_function ({ ID = "GetChannelFull", channel_id_ = getChatId(channel_id).ID }, dl_cb, cmd) end M.getChannelFull = getChannelFull -- Returns information about a secret chat by its identifier, offline request -- @secret_chat_id Secret chat identifier local function getSecretChat(secret_chat_id, dl_cb, cmd) tdcli_function ({ ID = "GetSecretChat", secret_chat_id_ = secret_chat_id }, dl_cb, cmd) end M.getSecretChat = getSecretChat -- Returns information about a chat by its identifier, offline request if current user is not a bot -- @chat_id Chat identifier local function getChat(chat_id, dl_cb, cmd) tdcli_function ({ ID = "GetChat", chat_id_ = chat_id }, dl_cb, cmd) end M.getChat = getChat -- Returns information about a message -- @chat_id Identifier of the chat, message belongs to -- @message_id Identifier of the message to get local function getMessage(chat_id, message_id, dl_cb, cmd) tdcli_function ({ ID = "GetMessage", chat_id_ = chat_id, message_id_ = message_id }, dl_cb, cmd) end M.getMessage = getMessage -- Returns information about messages. -- If message is not found, returns null on the corresponding position of the result -- @chat_id Identifier of the chat, messages belongs to -- @message_ids Identifiers of the messages to get local function getMessages(chat_id, message_ids, dl_cb, cmd) tdcli_function ({ ID = "GetMessages", chat_id_ = chat_id, message_ids_ = message_ids -- vector }, dl_cb, cmd) end M.getMessages = getMessages -- Returns information about a file, offline request -- @file_id Identifier of the file to get local function getFile(file_id, dl_cb, cmd) tdcli_function ({ ID = "GetFile", file_id_ = file_id }, dl_cb, cmd) end M.getFile = getFile -- Returns information about a file by its persistent id, offline request -- @persistent_file_id Persistent identifier of the file to get local function getFilePersistent(persistent_file_id, dl_cb, cmd) tdcli_function ({ ID = "GetFilePersistent", persistent_file_id_ = persistent_file_id }, dl_cb, cmd) end M.getFilePersistent = getFilePersistent -- Returns list of chats in the right order, chats are sorted by (order, chat_id) in decreasing order. -- For example, to get list of chats from the beginning, the offset_order should be equal 2^63 - 1 -- @offset_order Chat order to return chats from -- @offset_chat_id Chat identifier to return chats from -- @limit Maximum number of chats to be returned local function getChats(offset_order, offset_chat_id, limit, dl_cb, cmd) if not limit or limit > 20 then limit = 20 end tdcli_function ({ ID = "GetChats", offset_order_ = offset_order or 9223372036854775807, offset_chat_id_ = offset_chat_id or 0, limit_ = limit }, dl_cb, cmd) end M.getChats = getChats -- Searches public chat by its username. -- Currently only private and channel chats can be public. -- Returns chat if found, otherwise some error is returned -- @username Username to be resolved local function searchPublicChat(username, dl_cb, cmd) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, dl_cb, cmd) end M.searchPublicChat = searchPublicChat -- Searches public chats by prefix of their username. -- Currently only private and channel (including supergroup) chats can be public. -- Returns meaningful number of results. -- Returns nothing if length of the searched username prefix is less than 5. -- Excludes private chats with contacts from the results -- @username_prefix Prefix of the username to search local function searchPublicChats(username_prefix, dl_cb, cmd) tdcli_function ({ ID = "SearchPublicChats", username_prefix_ = username_prefix }, dl_cb, cmd) end M.searchPublicChats = searchPublicChats -- Searches for specified query in the title and username of known chats, offline request. -- Returns chats in the order of them in the chat list -- @query Query to search for, if query is empty, returns up to 20 recently found chats -- @limit Maximum number of chats to be returned local function searchChats(query, limit, dl_cb, cmd) if not limit or limit > 20 then limit = 20 end tdcli_function ({ ID = "SearchChats", query_ = query, limit_ = limit }, dl_cb, cmd) end M.searchChats = searchChats -- Adds chat to the list of recently found chats. -- The chat is added to the beginning of the list. -- If the chat is already in the list, at first it is removed from the list -- @chat_id Identifier of the chat to add local function addRecentlyFoundChat(chat_id, dl_cb, cmd) tdcli_function ({ ID = "AddRecentlyFoundChat", chat_id_ = chat_id }, dl_cb, cmd) end M.addRecentlyFoundChat = addRecentlyFoundChat -- Deletes chat from the list of recently found chats -- @chat_id Identifier of the chat to delete local function deleteRecentlyFoundChat(chat_id, dl_cb, cmd) tdcli_function ({ ID = "DeleteRecentlyFoundChat", chat_id_ = chat_id }, dl_cb, cmd) end M.deleteRecentlyFoundChat = deleteRecentlyFoundChat -- Clears list of recently found chats local function deleteRecentlyFoundChats(dl_cb, cmd) tdcli_function ({ ID = "DeleteRecentlyFoundChats", }, dl_cb, cmd) end M.deleteRecentlyFoundChats = deleteRecentlyFoundChats -- Returns list of common chats with an other given user. -- Chats are sorted by their type and creation date -- @user_id User identifier -- @offset_chat_id Chat identifier to return chats from, use 0 for the first request -- @limit Maximum number of chats to be returned, up to 100 local function getCommonChats(user_id, offset_chat_id, limit, dl_cb, cmd) if not limit or limit > 100 then limit = 100 end tdcli_function ({ ID = "GetCommonChats", user_id_ = user_id, offset_chat_id_ = offset_chat_id, limit_ = limit }, dl_cb, cmd) end M.getCommonChats = getCommonChats -- Returns messages in a chat. -- Automatically calls openChat. -- Returns result in reverse chronological order, i.e. in order of decreasing message.message_id -- @chat_id Chat identifier -- @from_message_id Identifier of the message near which we need a history, you can use 0 to get results from the beginning, i.e. from oldest to newest -- @offset Specify 0 to get results exactly from from_message_id or negative offset to get specified message and some newer messages -- @limit Maximum number of messages to be returned, should be positive and can't be greater than 100. -- If offset is negative, limit must be greater than -offset. -- There may be less than limit messages returned even the end of the history is not reached local function getChatHistory(chat_id, from_message_id, offset, limit, dl_cb, cmd) if not limit or limit > 100 then limit = 100 end tdcli_function ({ ID = "GetChatHistory", chat_id_ = chat_id, from_message_id_ = from_message_id, offset_ = offset or 0, limit_ = limit }, dl_cb, cmd) end M.getChatHistory = getChatHistory -- Deletes all messages in the chat. -- Can't be used for channel chats -- @chat_id Chat identifier -- @remove_from_chat_list Pass true, if chat should be removed from the chat list local function deleteChatHistory(chat_id, remove_from_chat_list, dl_cb, cmd) tdcli_function ({ ID = "DeleteChatHistory", chat_id_ = chat_id, remove_from_chat_list_ = remove_from_chat_list }, dl_cb, cmd) end M.deleteChatHistory = deleteChatHistory -- Searches for messages with given words in the chat. -- Returns result in reverse chronological order, i. e. in order of decreasimg message_id. -- Doesn't work in secret chats -- @chat_id Chat identifier to search in -- @query Query to search for -- @from_message_id Identifier of the message from which we need a history, you can use 0 to get results from beginning -- @limit Maximum number of messages to be returned, can't be greater than 100 -- @filter Filter for content of searched messages -- filter = Empty|Animation|Audio|Document|Photo|Video|Voice|PhotoAndVideo|Url|ChatPhoto local function searchChatMessages(chat_id, query, from_message_id, limit, filter, dl_cb, cmd) if not limit or limit > 100 then limit = 100 end tdcli_function ({ ID = "SearchChatMessages", chat_id_ = chat_id, query_ = query, from_message_id_ = from_message_id, limit_ = limit, filter_ = { ID = 'SearchMessagesFilter' .. filter }, }, dl_cb, cmd) end M.searchChatMessages = searchChatMessages -- Searches for messages in all chats except secret chats. Returns result in reverse chronological order, i. e. in order of decreasing (date, chat_id, message_id) -- @query Query to search for -- @offset_date Date of the message to search from, you can use 0 or any date in the future to get results from the beginning -- @offset_chat_id Chat identifier of the last found message or 0 for the first request -- @offset_message_id Message identifier of the last found message or 0 for the first request -- @limit Maximum number of messages to be returned, can't be greater than 100 local function searchMessages(query, offset_date, offset_chat_id, offset_message_id, limit, dl_cb, cmd) if not limit or limit > 100 then limit = 100 end tdcli_function ({ ID = "SearchMessages", query_ = query, offset_date_ = offset_date, offset_chat_id_ = offset_chat_id, offset_message_id_ = offset_message_id, limit_ = limit }, dl_cb, cmd) end M.searchMessages = searchMessages -- Invites bot to a chat (if it is not in the chat) and send /start to it. -- Bot can't be invited to a private chat other than chat with the bot. -- Bots can't be invited to broadcast channel chats and secret chats. -- Returns sent message. -- UpdateChatTopMessage will not be sent, so returned message should be used to update chat top message -- @bot_user_id Identifier of the bot -- @chat_id Identifier of the chat -- @parameter Hidden parameter sent to bot for deep linking (https://api.telegram.org/bots#deep-linking) -- parameter=start|startgroup or custom as defined by bot creator local function sendBotStartMessage(bot_user_id, chat_id, parameter, dl_cb, cmd) tdcli_function ({ ID = "SendBotStartMessage", bot_user_id_ = bot_user_id, chat_id_ = chat_id, parameter_ = parameter }, dl_cb, cmd) end M.sendBotStartMessage = sendBotStartMessage -- Sends result of the inline query as a message. -- Returns sent message. -- UpdateChatTopMessage will not be sent, so returned message should be used to update chat top message. -- Always clears chat draft message -- @chat_id Chat to send message -- @reply_to_message_id Identifier of a message to reply to or 0 -- @disable_notification Pass true, to disable notification about the message, doesn't works in secret chats -- @from_background Pass true, if the message is sent from background -- @query_id Identifier of the inline query -- @result_id Identifier of the inline result local function sendInlineQueryResultMessage(chat_id, reply_to_message_id, disable_notification, from_background, query_id, result_id, dl_cb, cmd) tdcli_function ({ ID = "SendInlineQueryResultMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, query_id_ = query_id, result_id_ = result_id }, dl_cb, cmd) end M.sendInlineQueryResultMessage = sendInlineQueryResultMessage -- Forwards previously sent messages. -- Returns forwarded messages in the same order as message identifiers passed in message_ids. -- If message can't be forwarded, null will be returned instead of the message. -- UpdateChatTopMessage will not be sent, so returned messages should be used to update chat top message -- @chat_id Identifier of a chat to forward messages -- @from_chat_id Identifier of a chat to forward from -- @message_ids Identifiers of messages to forward -- @disable_notification Pass true, to disable notification about the message, doesn't works if messages are forwarded to secret chat -- @from_background Pass true, if the message is sent from background local function forwardMessages(chat_id, from_chat_id, message_ids, disable_notification, dl_cb, cmd) tdcli_function ({ ID = "ForwardMessages", chat_id_ = chat_id, from_chat_id_ = from_chat_id, message_ids_ = message_ids, -- vector disable_notification_ = disable_notification, from_background_ = 1 }, dl_cb, cmd) end M.forwardMessages = forwardMessages -- Changes current ttl setting in a secret chat and sends corresponding message -- @chat_id Chat identifier -- @ttl New value of ttl in seconds local function sendChatSetTtlMessage(chat_id, ttl, dl_cb, cmd) tdcli_function ({ ID = "SendChatSetTtlMessage", chat_id_ = chat_id, ttl_ = ttl }, dl_cb, cmd) end M.sendChatSetTtlMessage = sendChatSetTtlMessage -- Deletes messages. -- UpdateDeleteMessages will not be sent for messages deleted through that function -- @chat_id Chat identifier -- @message_ids Identifiers of messages to delete local function deleteMessages(chat_id, message_ids, dl_cb, cmd) tdcli_function ({ ID = "DeleteMessages", chat_id_ = chat_id, message_ids_ = message_ids -- vector }, dl_cb, cmd) end M.deleteMessages = deleteMessages -- Deletes all messages in the chat sent by the specified user. -- Works only in supergroup channel chats, needs appropriate privileges -- @chat_id Chat identifier -- @user_id User identifier local function deleteMessagesFromUser(chat_id, user_id, dl_cb, cmd) tdcli_function ({ ID = "DeleteMessagesFromUser", chat_id_ = chat_id, user_id_ = user_id }, dl_cb, cmd) end M.deleteMessagesFromUser = deleteMessagesFromUser -- Edits text of text or game message. -- Non-bots can edit message in a limited period of time. -- Returns edited message after edit is complete server side -- @chat_id Chat the message belongs to -- @message_id Identifier of the message -- @reply_markup Bots only. New message reply markup -- @input_message_content New text content of the message. Should be of type InputMessageText local function editMessageText(chat_id, message_id, reply_markup, text, disable_web_page_preview, parse_mode, dl_cb, cmd) local TextParseMode = getParseMode(parse_mode) tdcli_function ({ ID = "EditMessageText", chat_id_ = chat_id, message_id_ = message_id, reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup input_message_content_ = { ID = "InputMessageText", text_ = text, disable_web_page_preview_ = disable_web_page_preview, clear_draft_ = 0, entities_ = {}, parse_mode_ = TextParseMode, }, }, dl_cb, cmd) end M.editMessageText = editMessageText -- Edits message content caption. -- Non-bots can edit message in a limited period of time. -- Returns edited message after edit is complete server side -- @chat_id Chat the message belongs to -- @message_id Identifier of the message -- @reply_markup Bots only. New message reply markup -- @caption New message content caption, 0-200 characters local function editMessageCaption(chat_id, message_id, reply_markup, caption, dl_cb, cmd) tdcli_function ({ ID = "EditMessageCaption", chat_id_ = chat_id, message_id_ = message_id, reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup caption_ = caption }, dl_cb, cmd) end M.editMessageCaption = editMessageCaption -- Bots only. -- Edits message reply markup. -- Returns edited message after edit is complete server side -- @chat_id Chat the message belongs to -- @message_id Identifier of the message -- @reply_markup New message reply markup local function editMessageReplyMarkup(inline_message_id, reply_markup, caption, dl_cb, cmd) tdcli_function ({ ID = "EditInlineMessageCaption", inline_message_id_ = inline_message_id, reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup caption_ = caption }, dl_cb, cmd) end M.editMessageReplyMarkup = editMessageReplyMarkup -- Bots only. -- Edits text of an inline text or game message sent via bot -- @inline_message_id Inline message identifier -- @reply_markup New message reply markup -- @input_message_content New text content of the message. Should be of type InputMessageText local function editInlineMessageText(inline_message_id, reply_markup, text, disable_web_page_preview, dl_cb, cmd) tdcli_function ({ ID = "EditInlineMessageText", inline_message_id_ = inline_message_id, reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup input_message_content_ = { ID = "InputMessageText", text_ = text, disable_web_page_preview_ = disable_web_page_preview, clear_draft_ = 0, entities_ = {} }, }, dl_cb, cmd) end M.editInlineMessageText = editInlineMessageText -- Bots only. -- Edits caption of an inline message content sent via bot -- @inline_message_id Inline message identifier -- @reply_markup New message reply markup -- @caption New message content caption, 0-200 characters local function editInlineMessageCaption(inline_message_id, reply_markup, caption, dl_cb, cmd) tdcli_function ({ ID = "EditInlineMessageCaption", inline_message_id_ = inline_message_id, reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup caption_ = caption }, dl_cb, cmd) end M.editInlineMessageCaption = editInlineMessageCaption -- Bots only. -- Edits reply markup of an inline message sent via bot -- @inline_message_id Inline message identifier -- @reply_markup New message reply markup local function editInlineMessageReplyMarkup(inline_message_id, reply_markup, dl_cb, cmd) tdcli_function ({ ID = "EditInlineMessageReplyMarkup", inline_message_id_ = inline_message_id, reply_markup_ = reply_markup -- reply_markup:ReplyMarkup }, dl_cb, cmd) end M.editInlineMessageReplyMarkup = editInlineMessageReplyMarkup -- Sends inline query to a bot and returns its results. -- Unavailable for bots -- @bot_user_id Identifier of the bot send query to -- @chat_id Identifier of the chat, where the query is sent -- @user_location User location, only if needed -- @query Text of the query -- @offset Offset of the first entry to return local function getInlineQueryResults(bot_user_id, chat_id, latitude, longitude, query, offset, dl_cb, cmd) tdcli_function ({ ID = "GetInlineQueryResults", bot_user_id_ = bot_user_id, chat_id_ = chat_id, user_location_ = { ID = "Location", latitude_ = latitude, longitude_ = longitude }, query_ = query, offset_ = offset }, dl_cb, cmd) end M.getInlineQueryResults = getInlineQueryResults -- Bots only. -- Sets result of the inline query -- @inline_query_id Identifier of the inline query -- @is_personal Does result of the query can be cached only for specified user -- @results Results of the query -- @cache_time Allowed time to cache results of the query in seconds -- @next_offset Offset for the next inline query, pass empty string if there is no more results -- @switch_pm_text If non-empty, this text should be shown on the button, which opens private chat with the bot and sends bot start message with parameter switch_pm_parameter -- @switch_pm_parameter Parameter for the bot start message local function answerInlineQuery(inline_query_id, is_personal, cache_time, next_offset, switch_pm_text, switch_pm_parameter, dl_cb, cmd) tdcli_function ({ ID = "AnswerInlineQuery", inline_query_id_ = inline_query_id, is_personal_ = is_personal, results_ = results, --vector<InputInlineQueryResult>, cache_time_ = cache_time, next_offset_ = next_offset, switch_pm_text_ = switch_pm_text, switch_pm_parameter_ = switch_pm_parameter }, dl_cb, cmd) end M.answerInlineQuery = answerInlineQuery -- Sends callback query to a bot and returns answer to it. -- Unavailable for bots -- @chat_id Identifier of the chat with a message -- @message_id Identifier of the message, from which the query is originated -- @payload Query payload -- @text Text of the answer -- @show_alert If true, an alert should be shown to the user instead of a toast -- @url URL to be open local function getCallbackQueryAnswer(chat_id, message_id, text, show_alert, url, dl_cb, cmd) tdcli_function ({ ID = "GetCallbackQueryAnswer", chat_id_ = chat_id, message_id_ = message_id, payload_ = { ID = "CallbackQueryAnswer", text_ = text, show_alert_ = show_alert, url_ = url }, }, dl_cb, cmd) end M.getCallbackQueryAnswer = getCallbackQueryAnswer -- Bots only. -- Sets result of the callback query -- @callback_query_id Identifier of the callback query -- @text Text of the answer -- @show_alert If true, an alert should be shown to the user instead of a toast -- @url Url to be opened -- @cache_time Allowed time to cache result of the query in seconds local function answerCallbackQuery(callback_query_id, text, show_alert, url, cache_time, dl_cb, cmd) tdcli_function ({ ID = "AnswerCallbackQuery", callback_query_id_ = callback_query_id, text_ = text, show_alert_ = show_alert, url_ = url, cache_time_ = cache_time }, dl_cb, cmd) end M.answerCallbackQuery = answerCallbackQuery -- Bots only. -- Updates game score of the specified user in the game -- @chat_id Chat a message with the game belongs to -- @message_id Identifier of the message -- @edit_message True, if message should be edited -- @user_id User identifier -- @score New score -- @force Pass True to update the score even if it decreases. If score is 0, user will be deleted from the high scores table local function setGameScore(chat_id, message_id, edit_message, user_id, score, force, dl_cb, cmd) tdcli_function ({ ID = "SetGameScore", chat_id_ = chat_id, message_id_ = message_id, edit_message_ = edit_message, user_id_ = user_id, score_ = score, force_ = force }, dl_cb, cmd) end M.setGameScore = setGameScore -- Bots only. -- Updates game score of the specified user in the game -- @inline_message_id Inline message identifier -- @edit_message True, if message should be edited -- @user_id User identifier -- @score New score -- @force Pass True to update the score even if it decreases. If score is 0, user will be deleted from the high scores table local function setInlineGameScore(inline_message_id, edit_message, user_id, score, force, dl_cb, cmd) tdcli_function ({ ID = "SetInlineGameScore", inline_message_id_ = inline_message_id, edit_message_ = edit_message, user_id_ = user_id, score_ = score, force_ = force }, dl_cb, cmd) end M.setInlineGameScore = setInlineGameScore -- Bots only. -- Returns game high scores and some part of the score table around of the specified user in the game -- @chat_id Chat a message with the game belongs to -- @message_id Identifier of the message -- @user_id User identifie local function getGameHighScores(chat_id, message_id, user_id, dl_cb, cmd) tdcli_function ({ ID = "GetGameHighScores", chat_id_ = chat_id, message_id_ = message_id, user_id_ = user_id }, dl_cb, cmd) end M.getGameHighScores = getGameHighScores -- Bots only. -- Returns game high scores and some part of the score table around of the specified user in the game -- @inline_message_id Inline message identifier -- @user_id User identifier local function getInlineGameHighScores(inline_message_id, user_id, dl_cb, cmd) tdcli_function ({ ID = "GetInlineGameHighScores", inline_message_id_ = inline_message_id, user_id_ = user_id }, dl_cb, cmd) end M.getInlineGameHighScores = getInlineGameHighScores -- Deletes default reply markup from chat. -- This method needs to be called after one-time keyboard or ForceReply reply markup has been used. -- UpdateChatReplyMarkup will be send if reply markup will be changed -- @chat_id Chat identifier -- @message_id Message identifier of used keyboard local function deleteChatReplyMarkup(chat_id, message_id, dl_cb, cmd) tdcli_function ({ ID = "DeleteChatReplyMarkup", chat_id_ = chat_id, message_id_ = message_id }, dl_cb, cmd) end M.deleteChatReplyMarkup = deleteChatReplyMarkup -- Sends notification about user activity in a chat -- @chat_id Chat identifier -- @action Action description -- action = Typing|Cancel|RecordVideo|UploadVideo|RecordVoice|UploadVoice|UploadPhoto|UploadDocument|GeoLocation|ChooseContact|StartPlayGame local function sendChatAction(chat_id, action, progress, dl_cb, cmd) tdcli_function ({ ID = "SendChatAction", chat_id_ = chat_id, action_ = { ID = "SendMessage" .. action .. "Action", progress_ = progress or 100 } }, dl_cb, cmd) end M.sendChatAction = sendChatAction -- Sends notification about screenshot taken in a chat. -- Works only in secret chats -- @chat_id Chat identifier local function sendChatScreenshotTakenNotification(chat_id, dl_cb, cmd) tdcli_function ({ ID = "SendChatScreenshotTakenNotification", chat_id_ = chat_id }, dl_cb, cmd) end M.sendChatScreenshotTakenNotification = sendChatScreenshotTakenNotification -- Chat is opened by the user. -- Many useful activities depends on chat being opened or closed. For example, in channels all updates are received only for opened chats -- @chat_id Chat identifier local function openChat(chat_id, dl_cb, cmd) tdcli_function ({ ID = "OpenChat", chat_id_ = chat_id }, dl_cb, cmd) end M.openChat = openChat -- Chat is closed by the user. -- Many useful activities depends on chat being opened or closed. -- @chat_id Chat identifier local function closeChat(chat_id, dl_cb, cmd) tdcli_function ({ ID = "CloseChat", chat_id_ = chat_id }, dl_cb, cmd) end M.closeChat = closeChat -- Messages are viewed by the user. -- Many useful activities depends on message being viewed. For example, marking messages as read, incrementing of view counter, updating of view counter, removing of deleted messages in channels -- @chat_id Chat identifier -- @message_ids Identifiers of viewed messages local function viewMessages(chat_id, message_ids, dl_cb, cmd) tdcli_function ({ ID = "ViewMessages", chat_id_ = chat_id, message_ids_ = message_ids -- vector }, dl_cb, cmd) end M.viewMessages = viewMessages -- Message content is opened, for example the user has opened a photo, a video, a document, a location or a venue or have listened to an audio or a voice message -- @chat_id Chat identifier of the message -- @message_id Identifier of the message with opened content local function openMessageContent(chat_id, message_id, dl_cb, cmd) tdcli_function ({ ID = "OpenMessageContent", chat_id_ = chat_id, message_id_ = message_id }, dl_cb, cmd) end M.openMessageContent = openMessageContent -- Returns existing chat corresponding to the given user -- @user_id User identifier local function createPrivateChat(user_id, dl_cb, cmd) tdcli_function ({ ID = "CreatePrivateChat", user_id_ = user_id }, dl_cb, cmd) end M.createPrivateChat = createPrivateChat -- Returns existing chat corresponding to the known group -- @group_id Group identifier local function createGroupChat(group_id, dl_cb, cmd) tdcli_function ({ ID = "CreateGroupChat", group_id_ = getChatId(group_id).ID }, dl_cb, cmd) end M.createGroupChat = createGroupChat -- Returns existing chat corresponding to the known channel -- @channel_id Channel identifier local function createChannelChat(channel_id, dl_cb, cmd) tdcli_function ({ ID = "CreateChannelChat", channel_id_ = getChatId(channel_id).ID }, dl_cb, cmd) end M.createChannelChat = createChannelChat -- Returns existing chat corresponding to the known secret chat -- @secret_chat_id SecretChat identifier local function createSecretChat(secret_chat_id, dl_cb, cmd) tdcli_function ({ ID = "CreateSecretChat", secret_chat_id_ = secret_chat_id }, dl_cb, cmd) end M.createSecretChat = createSecretChat -- Creates new group chat and send corresponding messageGroupChatCreate, returns created chat -- @user_ids Identifiers of users to add to the group -- @title Title of new group chat, 0-255 characters local function createNewGroupChat(user_ids, title, dl_cb, cmd) tdcli_function ({ ID = "CreateNewGroupChat", user_ids_ = user_ids, -- vector title_ = title }, dl_cb, cmd) end M.createNewGroupChat = createNewGroupChat -- Creates new channel chat and send corresponding messageChannelChatCreate, returns created chat -- @title Title of new channel chat, 0-255 characters -- @is_supergroup True, if supergroup chat should be created -- @about Information about the channel, 0-255 characters local function createNewChannelChat(title, is_supergroup, about, dl_cb, cmd) tdcli_function ({ ID = "CreateNewChannelChat", title_ = title, is_supergroup_ = is_supergroup, about_ = about }, dl_cb, cmd) end M.createNewChannelChat = createNewChannelChat -- Creates new secret chat, returns created chat -- @user_id Identifier of a user to create secret chat with local function createNewSecretChat(user_id, dl_cb, cmd) tdcli_function ({ ID = "CreateNewSecretChat", user_id_ = user_id }, dl_cb, cmd) end M.createNewSecretChat = createNewSecretChat -- Creates new channel supergroup chat from existing group chat and send corresponding messageChatMigrateTo and messageChatMigrateFrom. Deactivates group -- @chat_id Group chat identifier local function migrateGroupChatToChannelChat(chat_id, dl_cb, cmd) tdcli_function ({ ID = "MigrateGroupChatToChannelChat", chat_id_ = chat_id }, dl_cb, cmd) end M.migrateGroupChatToChannelChat = migrateGroupChatToChannelChat -- Changes chat title. -- Title can't be changed for private chats. -- Title will not change until change will be synchronized with the server. -- Title will not be changed if application is killed before it can send request to the server. -- There will be update about change of the title on success. Otherwise error will be returned -- @chat_id Chat identifier -- @title New title of a chat, 0-255 characters local function changeChatTitle(chat_id, title, dl_cb, cmd) tdcli_function ({ ID = "ChangeChatTitle", chat_id_ = chat_id, title_ = title }, dl_cb, cmd) end M.changeChatTitle = changeChatTitle -- Changes chat photo. -- Photo can't be changed for private chats. -- Photo will not change until change will be synchronized with the server. -- Photo will not be changed if application is killed before it can send request to the server. -- There will be update about change of the photo on success. Otherwise error will be returned -- @chat_id Chat identifier -- @photo New chat photo. You can use zero InputFileId to delete photo. Files accessible only by HTTP URL are not acceptable local function changeChatPhoto(chat_id, photo, dl_cb, cmd) tdcli_function ({ ID = "ChangeChatPhoto", chat_id_ = chat_id, photo_ = getInputFile(photo) }, dl_cb, cmd) end M.changeChatPhoto = changeChatPhoto -- Changes chat draft message -- @chat_id Chat identifier -- @draft_message New draft message, nullable local function changeChatDraftMessage(chat_id, reply_to_message_id, text, disable_web_page_preview, clear_draft, parse_mode, dl_cb, cmd) local TextParseMode = getParseMode(parse_mode) tdcli_function ({ ID = "ChangeChatDraftMessage", chat_id_ = chat_id, draft_message_ = { ID = "DraftMessage", reply_to_message_id_ = reply_to_message_id, input_message_text_ = { ID = "InputMessageText", text_ = text, disable_web_page_preview_ = disable_web_page_preview, clear_draft_ = clear_draft, entities_ = {}, parse_mode_ = TextParseMode, }, }, }, dl_cb, cmd) end M.changeChatDraftMessage = changeChatDraftMessage -- Adds new member to chat. -- Members can't be added to private or secret chats. -- Member will not be added until chat state will be synchronized with the server. -- Member will not be added if application is killed before it can send request to the server -- @chat_id Chat identifier -- @user_id Identifier of the user to add -- @forward_limit Number of previous messages from chat to forward to new member, ignored for channel chats local function addChatMember(chat_id, user_id, forward_limit, dl_cb, cmd) tdcli_function ({ ID = "AddChatMember", chat_id_ = chat_id, user_id_ = user_id, forward_limit_ = forward_limit or 50 }, dl_cb, cmd) end M.addChatMember = addChatMember -- Adds many new members to the chat. -- Currently, available only for channels. -- Can't be used to join the channel. -- Member will not be added until chat state will be synchronized with the server. -- Member will not be added if application is killed before it can send request to the server -- @chat_id Chat identifier -- @user_ids Identifiers of the users to add local function addChatMembers(chat_id, user_ids, dl_cb, cmd) tdcli_function ({ ID = "AddChatMembers", chat_id_ = chat_id, user_ids_ = user_ids -- vector }, dl_cb, cmd) end M.addChatMembers = addChatMembers -- Changes status of the chat member, need appropriate privileges. -- In channel chats, user will be added to chat members if he is yet not a member and there is less than 200 members in the channel. -- Status will not be changed until chat state will be synchronized with the server. -- Status will not be changed if application is killed before it can send request to the server -- @chat_id Chat identifier -- @user_id Identifier of the user to edit status, bots can be editors in the channel chats -- @status New status of the member in the chat -- status = Creator|Editor|Moderator|Member|Left|Kicked local function changeChatMemberStatus(chat_id, user_id, status, dl_cb, cmd) tdcli_function ({ ID = "ChangeChatMemberStatus", chat_id_ = chat_id, user_id_ = user_id, status_ = { ID = "ChatMemberStatus" .. status }, }, dl_cb, cmd) end M.changeChatMemberStatus = changeChatMemberStatus -- Returns information about one participant of the chat -- @chat_id Chat identifier -- @user_id User identifier local function getChatMember(chat_id, user_id, dl_cb, cmd) tdcli_function ({ ID = "GetChatMember", chat_id_ = chat_id, user_id_ = user_id }, dl_cb, cmd) end M.getChatMember = getChatMember -- Asynchronously downloads file from cloud. -- Updates updateFileProgress will notify about download progress. -- Update updateFile will notify about successful download -- @file_id Identifier of file to download local function downloadFile(file_id, dl_cb, cmd) tdcli_function ({ ID = "DownloadFile", file_id_ = file_id }, dl_cb, cmd) end M.downloadFile = downloadFile -- Stops file downloading. -- If file already downloaded do nothing. -- @file_id Identifier of file to cancel download local function cancelDownloadFile(file_id, dl_cb, cmd) tdcli_function ({ ID = "CancelDownloadFile", file_id_ = file_id }, dl_cb, cmd) end M.cancelDownloadFile = cancelDownloadFile -- Next part of a file was generated -- @generation_id Identifier of the generation process -- @ready Number of bytes already generated. Negative number means that generation has failed and should be terminated local function setFileGenerationProgress(generation_id, ready, dl_cb, cmd) tdcli_function ({ ID = "SetFileGenerationProgress", generation_id_ = generation_id, ready_ = ready }, dl_cb, cmd) end M.setFileGenerationProgress = setFileGenerationProgress -- Finishes file generation -- @generation_id Identifier of the generation process local function finishFileGeneration(generation_id, dl_cb, cmd) tdcli_function ({ ID = "FinishFileGeneration", generation_id_ = generation_id }, dl_cb, cmd) end M.finishFileGeneration = finishFileGeneration -- Generates new chat invite link, previously generated link is revoked. -- Available for group and channel chats. -- Only creator of the chat can export chat invite link -- @chat_id Chat identifier local function exportChatInviteLink(chat_id, dl_cb, cmd) tdcli_function ({ ID = "ExportChatInviteLink", chat_id_ = chat_id }, dl_cb, cmd) end M.exportChatInviteLink = exportChatInviteLink -- Checks chat invite link for validness and returns information about the corresponding chat -- @invite_link Invite link to check. Should begin with "https://telegram.me/joinchat/" local function checkChatInviteLink(link, dl_cb, cmd) tdcli_function ({ ID = "CheckChatInviteLink", invite_link_ = link }, dl_cb, cmd) end M.checkChatInviteLink = checkChatInviteLink -- Imports chat invite link, adds current user to a chat if possible. -- Member will not be added until chat state will be synchronized with the server. -- Member will not be added if application is killed before it can send request to the server -- @invite_link Invite link to import. Should begin with "https://telegram.me/joinchat/" local function importChatInviteLink(invite_link, dl_cb, cmd) tdcli_function ({ ID = "ImportChatInviteLink", invite_link_ = invite_link }, dl_cb, cmd) end M.importChatInviteLink = importChatInviteLink -- Adds user to black list -- @user_id User identifier local function blockUser(user_id, dl_cb, cmd) tdcli_function ({ ID = "BlockUser", user_id_ = user_id }, dl_cb, cmd) end M.blockUser = blockUser -- Removes user from black list -- @user_id User identifier local function unblockUser(user_id, dl_cb, cmd) tdcli_function ({ ID = "UnblockUser", user_id_ = user_id }, dl_cb, cmd) end M.unblockUser = unblockUser -- Returns users blocked by the current user -- @offset Number of users to skip in result, must be non-negative -- @limit Maximum number of users to return, can't be greater than 100 local function getBlockedUsers(offset, limit, dl_cb, cmd) tdcli_function ({ ID = "GetBlockedUsers", offset_ = offset, limit_ = limit }, dl_cb, cmd) end M.getBlockedUsers = getBlockedUsers -- Adds new contacts/edits existing contacts, contacts user identifiers are ignored. -- Returns list of corresponding users in the same order as input contacts. -- If contact doesn't registered in Telegram, user with id == 0 will be returned -- @contacts List of contacts to import/edit local function importContacts(phone_number, first_name, last_name, user_id, dl_cb, cmd) tdcli_function ({ ID = "ImportContacts", contacts_ = {[0] = { phone_number_ = tostring(phone_number), first_name_ = tostring(first_name), last_name_ = tostring(last_name), user_id_ = user_id }, }, }, dl_cb, cmd) end M.importContacts = importContacts -- Searches for specified query in the first name, last name and username of the known user contacts -- @query Query to search for, can be empty to return all contacts -- @limit Maximum number of users to be returned local function searchContacts(query, limit, dl_cb, cmd) tdcli_function ({ ID = "SearchContacts", query_ = query, limit_ = limit }, dl_cb, cmd) end M.searchContacts = searchContacts -- Deletes users from contacts list -- @user_ids Identifiers of users to be deleted local function deleteContacts(user_ids, dl_cb, cmd) tdcli_function ({ ID = "DeleteContacts", user_ids_ = user_ids -- vector }, dl_cb, cmd) end M.deleteContacts = deleteContacts -- Returns profile photos of the user. -- Result of this query can't be invalidated, so it must be used with care -- @user_id User identifier -- @offset Photos to skip, must be non-negative -- @limit Maximum number of photos to be returned, can't be greater than 100 local function getUserProfilePhotos(user_id, offset, limit, dl_cb, cmd) tdcli_function ({ ID = "GetUserProfilePhotos", user_id_ = user_id, offset_ = offset, limit_ = limit }, dl_cb, cmd) end M.getUserProfilePhotos = getUserProfilePhotos -- Returns stickers corresponding to given emoji -- @emoji String representation of emoji. If empty, returns all known stickers local function getStickers(emoji, dl_cb, cmd) tdcli_function ({ ID = "GetStickers", emoji_ = emoji }, dl_cb, cmd) end M.getStickers = getStickers -- Returns list of installed sticker sets without archived sticker sets -- @is_masks Pass true to return masks, pass false to return stickers local function getStickerSets(is_masks, dl_cb, cmd) tdcli_function ({ ID = "GetStickerSets", is_masks_ = is_masks }, dl_cb, cmd) end M.getStickerSets = getStickerSets -- Returns list of archived sticker sets -- @is_masks Pass true to return masks, pass false to return stickers -- @offset_sticker_set_id Identifier of the sticker set from which return the result -- @limit Maximum number of sticker sets to return local function getArchivedStickerSets(is_masks, offset_sticker_set_id, limit, dl_cb, cmd) tdcli_function ({ ID = "GetArchivedStickerSets", is_masks_ = is_masks, offset_sticker_set_id_ = offset_sticker_set_id, limit_ = limit }, dl_cb, cmd) end M.getArchivedStickerSets = getArchivedStickerSets -- Returns list of trending sticker sets local function getTrendingStickerSets(dl_cb, cmd) tdcli_function ({ ID = "GetTrendingStickerSets" }, dl_cb, cmd) end M.getTrendingStickerSets = getTrendingStickerSets -- Returns list of sticker sets attached to a file, currently only photos and videos can have attached sticker sets -- @file_id File identifier local function getAttachedStickerSets(file_id, dl_cb, cmd) tdcli_function ({ ID = "GetAttachedStickerSets", file_id_ = file_id }, dl_cb, cmd) end M.getAttachedStickerSets = getAttachedStickerSets -- Returns information about sticker set by its identifier -- @set_id Identifier of the sticker set local function getStickerSet(set_id, dl_cb, cmd) tdcli_function ({ ID = "GetStickerSet", set_id_ = set_id }, dl_cb, cmd) end M.getStickerSet = getStickerSet -- Searches sticker set by its short name -- @name Name of the sticker set local function searchStickerSet(name, dl_cb, cmd) tdcli_function ({ ID = "SearchStickerSet", name_ = name }, dl_cb, cmd) end M.searchStickerSet = searchStickerSet -- Installs/uninstalls or enables/archives sticker set. -- Official sticker set can't be uninstalled, but it can be archived -- @set_id Identifier of the sticker set -- @is_installed New value of is_installed -- @is_archived New value of is_archived local function updateStickerSet(set_id, is_installed, is_archived, dl_cb, cmd) tdcli_function ({ ID = "UpdateStickerSet", set_id_ = set_id, is_installed_ = is_installed, is_archived_ = is_archived }, dl_cb, cmd) end M.updateStickerSet = updateStickerSet -- Trending sticker sets are viewed by the user -- @sticker_set_ids Identifiers of viewed trending sticker sets local function viewTrendingStickerSets(sticker_set_ids, dl_cb, cmd) tdcli_function ({ ID = "ViewTrendingStickerSets", sticker_set_ids_ = sticker_set_ids -- vector }, dl_cb, cmd) end M.viewTrendingStickerSets = viewTrendingStickerSets -- Changes the order of installed sticker sets -- @is_masks Pass true to change masks order, pass false to change stickers order -- @sticker_set_ids Identifiers of installed sticker sets in the new right order local function reorderStickerSets(is_masks, sticker_set_ids, dl_cb, cmd) tdcli_function ({ ID = "ReorderStickerSets", is_masks_ = is_masks, sticker_set_ids_ = sticker_set_ids -- vector }, dl_cb, cmd) end M.reorderStickerSets = reorderStickerSets -- Returns list of recently used stickers -- @is_attached Pass true to return stickers and masks recently attached to photo or video files, pass false to return recently sent stickers local function getRecentStickers(is_attached, dl_cb, cmd) tdcli_function ({ ID = "GetRecentStickers", is_attached_ = is_attached }, dl_cb, cmd) end M.getRecentStickers = getRecentStickers -- Manually adds new sticker to the list of recently used stickers. -- New sticker is added to the beginning of the list. -- If the sticker is already in the list, at first it is removed from the list -- @is_attached Pass true to add the sticker to the list of stickers recently attached to photo or video files, pass false to add the sticker to the list of recently sent stickers -- @sticker Sticker file to add local function addRecentSticker(is_attached, sticker, dl_cb, cmd) tdcli_function ({ ID = "AddRecentSticker", is_attached_ = is_attached, sticker_ = getInputFile(sticker) }, dl_cb, cmd) end M.addRecentSticker = addRecentSticker -- Removes a sticker from the list of recently used stickers -- @is_attached Pass true to remove the sticker from the list of stickers recently attached to photo or video files, pass false to remove the sticker from the list of recently sent stickers -- @sticker Sticker file to delete local function deleteRecentSticker(is_attached, sticker, dl_cb, cmd) tdcli_function ({ ID = "DeleteRecentSticker", is_attached_ = is_attached, sticker_ = getInputFile(sticker) }, dl_cb, cmd) end M.deleteRecentSticker = deleteRecentSticker -- Clears list of recently used stickers -- @is_attached Pass true to clear list of stickers recently attached to photo or video files, pass false to clear the list of recently sent stickers local function clearRecentStickers(is_attached, dl_cb, cmd) tdcli_function ({ ID = "ClearRecentStickers", is_attached_ = is_attached }, dl_cb, cmd) end M.clearRecentStickers = clearRecentStickers -- Returns emojis corresponding to a sticker -- @sticker Sticker file identifier local function getStickerEmojis(sticker, dl_cb, cmd) tdcli_function ({ ID = "GetStickerEmojis", sticker_ = getInputFile(sticker) }, dl_cb, cmd) end M.getStickerEmojis = getStickerEmojis -- Returns saved animations local function getSavedAnimations(dl_cb, cmd) tdcli_function ({ ID = "GetSavedAnimations", }, dl_cb, cmd) end M.getSavedAnimations = getSavedAnimations -- Manually adds new animation to the list of saved animations. -- New animation is added to the beginning of the list. -- If the animation is already in the list, at first it is removed from the list. -- Only non-secret video animations with MIME type "video/mp4" can be added to the list -- @animation Animation file to add. Only known to server animations (i. e. successfully sent via message) can be added to the list local function addSavedAnimation(animation, dl_cb, cmd) tdcli_function ({ ID = "AddSavedAnimation", animation_ = getInputFile(animation) }, dl_cb, cmd) end M.addSavedAnimation = addSavedAnimation -- Removes animation from the list of saved animations -- @animation Animation file to delete local function deleteSavedAnimation(animation, dl_cb, cmd) tdcli_function ({ ID = "DeleteSavedAnimation", animation_ = getInputFile(animation) }, dl_cb, cmd) end M.deleteSavedAnimation = deleteSavedAnimation -- Returns up to 20 recently used inline bots in the order of the last usage local function getRecentInlineBots(dl_cb, cmd) tdcli_function ({ ID = "GetRecentInlineBots", }, dl_cb, cmd) end M.getRecentInlineBots = getRecentInlineBots -- Get web page preview by text of the message. -- Do not call this function to often -- @message_text Message text local function getWebPagePreview(message_text, dl_cb, cmd) tdcli_function ({ ID = "GetWebPagePreview", message_text_ = message_text }, dl_cb, cmd) end M.getWebPagePreview = getWebPagePreview -- Returns notification settings for a given scope -- @scope Scope to return information about notification settings -- scope = Chat(chat_id)|PrivateChats|GroupChats|AllChats| local function getNotificationSettings(scope, chat_id, dl_cb, cmd) tdcli_function ({ ID = "GetNotificationSettings", scope_ = { ID = 'NotificationSettingsFor' .. scope, chat_id_ = chat_id or nil }, }, dl_cb, cmd) end M.getNotificationSettings = getNotificationSettings -- Changes notification settings for a given scope -- @scope Scope to change notification settings -- @notification_settings New notification settings for given scope -- scope = Chat(chat_id)|PrivateChats|GroupChats|AllChats| local function setNotificationSettings(scope, chat_id, mute_for, show_preview, dl_cb, cmd) tdcli_function ({ ID = "SetNotificationSettings", scope_ = { ID = 'NotificationSettingsFor' .. scope, chat_id_ = chat_id or nil }, notification_settings_ = { ID = "NotificationSettings", mute_for_ = mute_for, sound_ = "default", show_preview_ = show_preview } }, dl_cb, cmd) end M.setNotificationSettings = setNotificationSettings -- Resets all notification settings to the default value. -- By default the only muted chats are supergroups, sound is set to 'default' and message previews are showed local function resetAllNotificationSettings(dl_cb, cmd) tdcli_function ({ ID = "ResetAllNotificationSettings" }, dl_cb, cmd) end M.resetAllNotificationSettings = resetAllNotificationSettings -- Uploads new profile photo for logged in user. -- Photo will not change until change will be synchronized with the server. -- Photo will not be changed if application is killed before it can send request to the server. -- If something changes, updateUser will be sent -- @photo_path Path to new profile photo local function setProfilePhoto(photo_path, dl_cb, cmd) tdcli_function ({ ID = "SetProfilePhoto", photo_path_ = photo_path }, dl_cb, cmd) end M.setProfilePhoto = setProfilePhoto -- Deletes profile photo. -- If something changes, updateUser will be sent -- @profile_photo_id Identifier of profile photo to delete local function deleteProfilePhoto(profile_photo_id, dl_cb, cmd) tdcli_function ({ ID = "DeleteProfilePhoto", profile_photo_id_ = profile_photo_id }, dl_cb, cmd) end M.deleteProfilePhoto = deleteProfilePhoto -- Changes first and last names of logged in user. -- If something changes, updateUser will be sent -- @first_name New value of user first name, 1-255 characters -- @last_name New value of optional user last name, 0-255 characters local function changeName(first_name, last_name, dl_cb, cmd) tdcli_function ({ ID = "ChangeName", first_name_ = first_name, last_name_ = last_name }, dl_cb, cmd) end M.changeName = changeName -- Changes about information of logged in user -- @about New value of userFull.about, 0-255 characters local function changeAbout(about, dl_cb, cmd) tdcli_function ({ ID = "ChangeAbout", about_ = about }, dl_cb, cmd) end M.changeAbout = changeAbout -- Changes username of logged in user. -- If something changes, updateUser will be sent -- @username New value of username. Use empty string to remove username local function changeUsername(username, dl_cb, cmd) tdcli_function ({ ID = "ChangeUsername", username_ = username }, dl_cb, cmd) end M.changeUsername = changeUsername -- Changes user's phone number and sends authentication code to the new user's phone number. -- Returns authStateWaitCode with information about sent code on success -- @phone_number New user's phone number in any reasonable format -- @allow_flash_call Pass True, if code can be sent via flash call to the specified phone number -- @is_current_phone_number Pass true, if the phone number is used on the current device. Ignored if allow_flash_call is False local function changePhoneNumber(phone_number, allow_flash_call, is_current_phone_number, dl_cb, cmd) tdcli_function ({ ID = "ChangePhoneNumber", phone_number_ = phone_number, allow_flash_call_ = allow_flash_call, is_current_phone_number_ = is_current_phone_number }, dl_cb, cmd) end M.changePhoneNumber = changePhoneNumber -- Resends authentication code sent to change user's phone number. -- Works only if in previously received authStateWaitCode next_code_type was not null. -- Returns authStateWaitCode on success local function resendChangePhoneNumberCode(dl_cb, cmd) tdcli_function ({ ID = "ResendChangePhoneNumberCode", }, dl_cb, cmd) end M.resendChangePhoneNumberCode = resendChangePhoneNumberCode -- Checks authentication code sent to change user's phone number. -- Returns authStateOk on success -- @code Verification code from SMS, voice call or flash call local function checkChangePhoneNumberCode(code, dl_cb, cmd) tdcli_function ({ ID = "CheckChangePhoneNumberCode", code_ = code }, dl_cb, cmd) end M.checkChangePhoneNumberCode = checkChangePhoneNumberCode -- Returns all active sessions of logged in user local function getActiveSessions(dl_cb, cmd) tdcli_function ({ ID = "GetActiveSessions", }, dl_cb, cmd) end M.getActiveSessions = getActiveSessions -- Terminates another session of logged in user -- @session_id Session identifier local function terminateSession(session_id, dl_cb, cmd) tdcli_function ({ ID = "TerminateSession", session_id_ = session_id }, dl_cb, cmd) end M.terminateSession = terminateSession -- Terminates all other sessions of logged in user local function terminateAllOtherSessions(dl_cb, cmd) tdcli_function ({ ID = "TerminateAllOtherSessions", }, dl_cb, cmd) end M.terminateAllOtherSessions = terminateAllOtherSessions -- Gives or revokes all members of the group editor rights. -- Needs creator privileges in the group -- @group_id Identifier of the group -- @anyone_can_edit New value of anyone_can_edit local function toggleGroupEditors(group_id, anyone_can_edit, dl_cb, cmd) tdcli_function ({ ID = "ToggleGroupEditors", group_id_ = getChatId(group_id).ID, anyone_can_edit_ = anyone_can_edit }, dl_cb, cmd) end M.toggleGroupEditors = toggleGroupEditors -- Changes username of the channel. -- Needs creator privileges in the channel -- @channel_id Identifier of the channel -- @username New value of username. Use empty string to remove username local function changeChannelUsername(channel_id, username, dl_cb, cmd) tdcli_function ({ ID = "ChangeChannelUsername", channel_id_ = getChatId(channel_id).ID, username_ = username }, dl_cb, cmd) end M.changeChannelUsername = changeChannelUsername -- Gives or revokes right to invite new members to all current members of the channel. -- Needs creator privileges in the channel. -- Available only for supergroups -- @channel_id Identifier of the channel -- @anyone_can_invite New value of anyone_can_invite local function toggleChannelInvites(channel_id, anyone_can_invite, dl_cb, cmd) tdcli_function ({ ID = "ToggleChannelInvites", channel_id_ = getChatId(channel_id).ID, anyone_can_invite_ = anyone_can_invite }, dl_cb, cmd) end M.toggleChannelInvites = toggleChannelInvites -- Enables or disables sender signature on sent messages in the channel. -- Needs creator privileges in the channel. -- Not available for supergroups -- @channel_id Identifier of the channel -- @sign_messages New value of sign_messages local function toggleChannelSignMessages(channel_id, sign_messages, dl_cb, cmd) tdcli_function ({ ID = "ToggleChannelSignMessages", channel_id_ = getChatId(channel_id).ID, sign_messages_ = sign_messages }, dl_cb, cmd) end M.toggleChannelSignMessages = toggleChannelSignMessages -- Changes information about the channel. -- Needs creator privileges in the broadcast channel or editor privileges in the supergroup channel -- @channel_id Identifier of the channel -- @about New value of about, 0-255 characters local function changeChannelAbout(channel_id, about, dl_cb, cmd) tdcli_function ({ ID = "ChangeChannelAbout", channel_id_ = getChatId(channel_id).ID, about_ = about }, dl_cb, cmd) end M.changeChannelAbout = changeChannelAbout -- Pins a message in a supergroup channel chat. -- Needs editor privileges in the channel -- @channel_id Identifier of the channel -- @message_id Identifier of the new pinned message -- @disable_notification True, if there should be no notification about the pinned message local function pinChannelMessage(channel_id, message_id, disable_notification, dl_cb, cmd) tdcli_function ({ ID = "PinChannelMessage", channel_id_ = getChatId(channel_id).ID, message_id_ = message_id, disable_notification_ = disable_notification }, dl_cb, cmd) end M.pinChannelMessage = pinChannelMessage -- Removes pinned message in the supergroup channel. -- Needs editor privileges in the channel -- @channel_id Identifier of the channel local function unpinChannelMessage(channel_id, dl_cb, cmd) tdcli_function ({ ID = "UnpinChannelMessage", channel_id_ = getChatId(channel_id).ID }, dl_cb, cmd) end M.unpinChannelMessage = unpinChannelMessage -- Reports some supergroup channel messages from a user as spam messages -- @channel_id Channel identifier -- @user_id User identifier -- @message_ids Identifiers of messages sent in the supergroup by the user, the list should be non-empty local function reportChannelSpam(channel_id, user_id, message_ids, dl_cb, cmd) tdcli_function ({ ID = "ReportChannelSpam", channel_id_ = getChatId(channel_id).ID, user_id_ = user_id, message_ids_ = message_ids -- vector }, dl_cb, cmd) end M.reportChannelSpam = reportChannelSpam -- Returns information about channel members or kicked from channel users. -- Can be used only if channel_full->can_get_members == true -- @channel_id Identifier of the channel -- @filter Kind of channel users to return, defaults to channelMembersRecent -- @offset Number of channel users to skip -- @limit Maximum number of users be returned, can't be greater than 200 -- filter = Recent|Administrators|Kicked|Bots local function getChannelMembers(channel_id, offset, filter, limit, dl_cb, cmd) if not limit or limit > 200 then limit = 200 end tdcli_function ({ ID = "GetChannelMembers", channel_id_ = getChatId(channel_id).ID, filter_ = { ID = "ChannelMembers" .. filter }, offset_ = offset, limit_ = limit }, dl_cb, cmd) end M.getChannelMembers = getChannelMembers -- Deletes channel along with all messages in corresponding chat. -- Releases channel username and removes all members. -- Needs creator privileges in the channel. -- Channels with more than 1000 members can't be deleted -- @channel_id Identifier of the channel local function deleteChannel(channel_id, dl_cb, cmd) tdcli_function ({ ID = "DeleteChannel", channel_id_ = getChatId(channel_id).ID }, dl_cb, cmd) end M.deleteChannel = deleteChannel -- Returns list of created public channels local function getCreatedPublicChannels(dl_cb, cmd) tdcli_function ({ ID = "GetCreatedPublicChannels" }, dl_cb, cmd) end M.getCreatedPublicChannels = getCreatedPublicChannels -- Closes secret chat -- @secret_chat_id Secret chat identifier local function closeSecretChat(secret_chat_id, dl_cb, cmd) tdcli_function ({ ID = "CloseSecretChat", secret_chat_id_ = secret_chat_id }, dl_cb, cmd) end M.closeSecretChat = closeSecretChat -- Returns user that can be contacted to get support local function getSupportUser(dl_cb, cmd) tdcli_function ({ ID = "GetSupportUser", }, dl_cb, cmd) end M.getSupportUser = getSupportUser -- Returns background wallpapers local function getWallpapers(dl_cb, cmd) tdcli_function ({ ID = "GetWallpapers", }, dl_cb, cmd) end M.getWallpapers = getWallpapers -- Registers current used device for receiving push notifications -- @device_token Device token -- device_token = apns|gcm|mpns|simplePush|ubuntuPhone|blackberry local function registerDevice(device_token, token, device_token_set, dl_cb, cmd) local dToken = {ID = device_token .. 'DeviceToken', token_ = token} if device_token_set then dToken = {ID = "DeviceTokenSet", token_ = device_token_set} -- tokens:vector<DeviceToken> end tdcli_function ({ ID = "RegisterDevice", device_token_ = dToken }, dl_cb, cmd) end M.registerDevice = registerDevice -- Returns list of used device tokens local function getDeviceTokens(dl_cb, cmd) tdcli_function ({ ID = "GetDeviceTokens", }, dl_cb, cmd) end M.getDeviceTokens = getDeviceTokens -- Changes privacy settings -- @key Privacy key -- @rules New privacy rules -- @privacyKeyUserStatus Privacy key for managing visibility of the user status -- @privacyKeyChatInvite Privacy key for managing ability of invitation of the user to chats -- @privacyRuleAllowAll Rule to allow all users -- @privacyRuleAllowContacts Rule to allow all user contacts -- @privacyRuleAllowUsers Rule to allow specified users -- @user_ids User identifiers -- @privacyRuleDisallowAll Rule to disallow all users -- @privacyRuleDisallowContacts Rule to disallow all user contacts -- @privacyRuleDisallowUsers Rule to disallow all specified users -- key = UserStatus|ChatInvite -- rules = AllowAll|AllowContacts|AllowUsers(user_ids)|DisallowAll|DisallowContacts|DisallowUsers(user_ids) local function setPrivacy(key, rule, allowed_user_ids, disallowed_user_ids, dl_cb, cmd) local rules = {[0] = {ID = 'PrivacyRule' .. rule}} if allowed_user_ids then rules = { { ID = 'PrivacyRule' .. rule }, [0] = { ID = "PrivacyRuleAllowUsers", user_ids_ = allowed_user_ids -- vector }, } end if disallowed_user_ids then rules = { { ID = 'PrivacyRule' .. rule }, [0] = { ID = "PrivacyRuleDisallowUsers", user_ids_ = disallowed_user_ids -- vector }, } end if allowed_user_ids and disallowed_user_ids then rules = { { ID = 'PrivacyRule' .. rule }, { ID = "PrivacyRuleAllowUsers", user_ids_ = allowed_user_ids }, [0] = { ID = "PrivacyRuleDisallowUsers", user_ids_ = disallowed_user_ids }, } end tdcli_function ({ ID = "SetPrivacy", key_ = { ID = 'PrivacyKey' .. key }, rules_ = { ID = "PrivacyRules", rules_ = rules }, }, dl_cb, cmd) end M.setPrivacy = setPrivacy -- Returns current privacy settings -- @key Privacy key -- key = UserStatus|ChatInvite local function getPrivacy(key, dl_cb, cmd) tdcli_function ({ ID = "GetPrivacy", key_ = { ID = "PrivacyKey" .. key }, }, dl_cb, cmd) end M.getPrivacy = getPrivacy -- Returns value of an option by its name. -- See list of available options on https://core.telegram.org/tdlib/options -- @name Name of the option local function getOption(name, dl_cb, cmd) tdcli_function ({ ID = "GetOption", name_ = name }, dl_cb, cmd) end M.getOption = getOption -- Sets value of an option. -- See list of available options on https://core.telegram.org/tdlib/options. -- Only writable options can be set -- @name Name of the option -- @value New value of the option local function setOption(name, option, value, dl_cb, cmd) tdcli_function ({ ID = "SetOption", name_ = name, value_ = { ID = 'Option' .. option, value_ = value }, }, dl_cb, cmd) end M.setOption = setOption -- Changes period of inactivity, after which the account of currently logged in user will be automatically deleted -- @ttl New account TTL local function changeAccountTtl(days, dl_cb, cmd) tdcli_function ({ ID = "ChangeAccountTtl", ttl_ = { ID = "AccountTtl", days_ = days }, }, dl_cb, cmd) end M.changeAccountTtl = changeAccountTtl -- Returns period of inactivity, after which the account of currently logged in user will be automatically deleted local function getAccountTtl(dl_cb, cmd) tdcli_function ({ ID = "GetAccountTtl", }, dl_cb, cmd) end M.getAccountTtl = getAccountTtl -- Deletes the account of currently logged in user, deleting from the server all information associated with it. -- Account's phone number can be used to create new account, but only once in two weeks -- @reason Optional reason of account deletion local function deleteAccount(reason, dl_cb, cmd) tdcli_function ({ ID = "DeleteAccount", reason_ = reason }, dl_cb, cmd) end M.deleteAccount = deleteAccount -- Returns current chat report spam state -- @chat_id Chat identifier local function getChatReportSpamState(chat_id, dl_cb, cmd) tdcli_function ({ ID = "GetChatReportSpamState", chat_id_ = chat_id }, dl_cb, cmd) end M.getChatReportSpamState = getChatReportSpamState -- Reports chat as a spam chat or as not a spam chat. -- Can be used only if ChatReportSpamState.can_report_spam is true. -- After this request ChatReportSpamState.can_report_spam became false forever -- @chat_id Chat identifier -- @is_spam_chat If true, chat will be reported as a spam chat, otherwise it will be marked as not a spam chat local function changeChatReportSpamState(chat_id, is_spam_chat, dl_cb, cmd) tdcli_function ({ ID = "ChangeChatReportSpamState", chat_id_ = chat_id, is_spam_chat_ = is_spam_chat }, dl_cb, cmd) end M.changeChatReportSpamState = changeChatReportSpamState -- Bots only. -- Informs server about number of pending bot updates if they aren't processed for a long time -- @pending_update_count Number of pending updates -- @error_message Last error's message local function setBotUpdatesStatus(pending_update_count, error_message, dl_cb, cmd) tdcli_function ({ ID = "SetBotUpdatesStatus", pending_update_count_ = pending_update_count, error_message_ = error_message }, dl_cb, cmd) end M.setBotUpdatesStatus = setBotUpdatesStatus -- Returns Ok after specified amount of the time passed -- @seconds Number of seconds before that function returns local function setAlarm(seconds, dl_cb, cmd) tdcli_function ({ ID = "SetAlarm", seconds_ = seconds }, dl_cb, cmd) end M.setAlarm = setAlarm -- Text message -- @text Text to send -- @disable_notification Pass true, to disable notification about the message, doesn't works in secret chats -- @from_background Pass true, if the message is sent from background -- @reply_markup Bots only. Markup for replying to message -- @disable_web_page_preview Pass true to disable rich preview for link in the message text -- @clear_draft Pass true if chat draft message should be deleted -- @entities Bold, Italic, Code, Pre, PreCode and TextUrl entities contained in the text. Non-bot users can't use TextUrl entities. Can't be used with non-null parse_mode -- @parse_mode Text parse mode, nullable. Can't be used along with enitities local function sendMessage(chat_id, reply_to_message_id, disable_notification, text, disable_web_page_preview, parse_mode) local TextParseMode = getParseMode(parse_mode) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = 1, reply_markup_ = nil, input_message_content_ = { ID = "InputMessageText", text_ = text, disable_web_page_preview_ = disable_web_page_preview, clear_draft_ = 0, entities_ = {}, parse_mode_ = TextParseMode, }, }, dl_cb, nil) end M.sendMessage = sendMessage -- Animation message -- @animation Animation file to send -- @thumb Animation thumb, if available -- @width Width of the animation, may be replaced by the server -- @height Height of the animation, may be replaced by the server -- @caption Animation caption, 0-200 characters local function sendAnimation(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, animation, width, height, caption, dl_cb, cmd) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, reply_markup_ = reply_markup, input_message_content_ = { ID = "InputMessageAnimation", animation_ = getInputFile(animation), --thumb_ = { --ID = "InputThumb", --path_ = path, --width_ = width, --height_ = height --}, width_ = width or '', height_ = height or '', caption_ = caption or '' }, }, dl_cb, cmd) end M.sendAnimation = sendAnimation -- Audio message -- @audio Audio file to send -- @album_cover_thumb Thumb of the album's cover, if available -- @duration Duration of audio in seconds, may be replaced by the server -- @title Title of the audio, 0-64 characters, may be replaced by the server -- @performer Performer of the audio, 0-64 characters, may be replaced by the server -- @caption Audio caption, 0-200 characters local function sendAudio(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, audio, duration, title, performer, caption, dl_cb, cmd) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, reply_markup_ = reply_markup, input_message_content_ = { ID = "InputMessageAudio", audio_ = getInputFile(audio), --album_cover_thumb_ = { --ID = "InputThumb", --path_ = path, --width_ = width, --height_ = height --}, duration_ = duration or '', title_ = title or '', performer_ = performer or '', caption_ = caption or '' }, }, dl_cb, cmd) end M.sendAudio = sendAudio -- Document message -- @document Document to send -- @thumb Document thumb, if available -- @caption Document caption, 0-200 characters local function sendDocument(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, document, caption, dl_cb, cmd) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, reply_markup_ = reply_markup, input_message_content_ = { ID = "InputMessageDocument", document_ = getInputFile(document), --thumb_ = { --ID = "InputThumb", --path_ = path, --width_ = width, --height_ = height --}, caption_ = caption }, }, dl_cb, cmd) end M.sendDocument = sendDocument -- Photo message -- @photo Photo to send -- @caption Photo caption, 0-200 characters local function sendPhoto(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, photo, caption, dl_cb, cmd) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, reply_markup_ = reply_markup, input_message_content_ = { ID = "InputMessagePhoto", photo_ = getInputFile(photo), added_sticker_file_ids_ = {}, width_ = 0, height_ = 0, caption_ = caption }, }, dl_cb, cmd) end M.sendPhoto = sendPhoto -- Sticker message -- @sticker Sticker to send -- @thumb Sticker thumb, if available local function sendSticker(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, sticker, dl_cb, cmd) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, reply_markup_ = reply_markup, input_message_content_ = { ID = "InputMessageSticker", sticker_ = getInputFile(sticker), --thumb_ = { --ID = "InputThumb", --path_ = path, --width_ = width, --height_ = height --}, }, }, dl_cb, cmd) end M.sendSticker = sendSticker -- Video message -- @video Video to send -- @thumb Video thumb, if available -- @duration Duration of video in seconds -- @width Video width -- @height Video height -- @caption Video caption, 0-200 characters local function sendVideo(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, video, duration, width, height, caption, dl_cb, cmd) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, reply_markup_ = reply_markup, input_message_content_ = { ID = "InputMessageVideo", video_ = getInputFile(video), --thumb_ = { --ID = "InputThumb", --path_ = path, --width_ = width, --height_ = height --}, added_sticker_file_ids_ = {}, duration_ = duration or '', width_ = width or '', height_ = height or '', caption_ = caption or '' }, }, dl_cb, cmd) end M.sendVideo = sendVideo -- Voice message -- @voice Voice file to send -- @duration Duration of voice in seconds -- @waveform Waveform representation of the voice in 5-bit format -- @caption Voice caption, 0-200 characters local function sendVoice(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, voice, duration, waveform, caption, dl_cb, cmd) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, reply_markup_ = reply_markup, input_message_content_ = { ID = "InputMessageVoice", voice_ = getInputFile(voice), duration_ = duration or '', waveform_ = waveform or '', caption_ = caption or '' }, }, dl_cb, cmd) end M.sendVoice = sendVoice -- Message with location -- @latitude Latitude of location in degrees as defined by sender -- @longitude Longitude of location in degrees as defined by sender local function sendLocation(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, latitude, longitude, dl_cb, cmd) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, reply_markup_ = reply_markup, input_message_content_ = { ID = "InputMessageLocation", location_ = { ID = "Location", latitude_ = latitude, longitude_ = longitude }, }, }, dl_cb, cmd) end M.sendLocation = sendLocation -- Message with information about venue -- @venue Venue to send -- @latitude Latitude of location in degrees as defined by sender -- @longitude Longitude of location in degrees as defined by sender -- @title Venue name as defined by sender -- @address Venue address as defined by sender -- @provider Provider of venue database as defined by sender. Only "foursquare" need to be supported currently -- @id Identifier of the venue in provider database as defined by sender local function sendVenue(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, latitude, longitude, title, address, id, dl_cb, cmd) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, reply_markup_ = reply_markup, input_message_content_ = { ID = "InputMessageVenue", venue_ = { ID = "Venue", location_ = { ID = "Location", latitude_ = latitude, longitude_ = longitude }, title_ = title, address_ = address, provider_ = 'foursquare', id_ = id }, }, }, dl_cb, cmd) end M.sendVenue = sendVenue -- User contact message -- @contact Contact to send -- @phone_number User's phone number -- @first_name User first name, 1-255 characters -- @last_name User last name -- @user_id User identifier if known, 0 otherwise local function sendContact(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, phone_number, first_name, last_name, user_id, dl_cb, cmd) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, reply_markup_ = reply_markup, input_message_content_ = { ID = "InputMessageContact", contact_ = { ID = "Contact", phone_number_ = phone_number, first_name_ = first_name, last_name_ = last_name, user_id_ = user_id }, }, }, dl_cb, cmd) end M.sendContact = sendContact -- Message with a game -- @bot_user_id User identifier of a bot owned the game -- @game_short_name Game short name local function sendGame(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, bot_user_id, game_short_name, dl_cb, cmd) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, reply_markup_ = reply_markup, input_message_content_ = { ID = "InputMessageGame", bot_user_id_ = bot_user_id, game_short_name_ = game_short_name }, }, dl_cb, cmd) end M.sendGame = sendGame -- Forwarded message -- @from_chat_id Chat identifier of the message to forward -- @message_id Identifier of the message to forward local function sendForwarded(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, from_chat_id, message_id, dl_cb, cmd) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, reply_markup_ = reply_markup, input_message_content_ = { ID = "InputMessageForwarded", from_chat_id_ = from_chat_id, message_id_ = message_id }, }, dl_cb, cmd) end M.sendForwarded = sendForwarded return M
gpl-3.0
Jennal/cocos2dx-3.2-qt
cocos/scripting/lua-bindings/auto/api/CardinalSplineTo.lua
7
1438
-------------------------------- -- @module CardinalSplineTo -- @extend ActionInterval -- @parent_module cc -------------------------------- -- @function [parent=#CardinalSplineTo] getPoints -- @param self -- @return point_table#point_table ret (return value: point_table) -------------------------------- -- @function [parent=#CardinalSplineTo] updatePosition -- @param self -- @param #vec2_table vec2 -------------------------------- -- @function [parent=#CardinalSplineTo] initWithDuration -- @param self -- @param #float float -- @param #point_table pointarray -- @param #float float -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#CardinalSplineTo] startWithTarget -- @param self -- @param #cc.Node node -------------------------------- -- @function [parent=#CardinalSplineTo] clone -- @param self -- @return CardinalSplineTo#CardinalSplineTo ret (return value: cc.CardinalSplineTo) -------------------------------- -- @function [parent=#CardinalSplineTo] reverse -- @param self -- @return CardinalSplineTo#CardinalSplineTo ret (return value: cc.CardinalSplineTo) -------------------------------- -- @function [parent=#CardinalSplineTo] update -- @param self -- @param #float float -------------------------------- -- @function [parent=#CardinalSplineTo] CardinalSplineTo -- @param self return nil
mit
stas2z/openwrt-witi
package/luci/modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/backupfiles.lua
75
2451
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. if luci.http.formvalue("cbid.luci.1._list") then luci.http.redirect(luci.dispatcher.build_url("admin/system/flashops/backupfiles") .. "?display=list") elseif luci.http.formvalue("cbid.luci.1._edit") then luci.http.redirect(luci.dispatcher.build_url("admin/system/flashops/backupfiles") .. "?display=edit") return end m = SimpleForm("luci", translate("Backup file list")) m:append(Template("admin_system/backupfiles")) if luci.http.formvalue("display") ~= "list" then f = m:section(SimpleSection, nil, translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade. Modified files in /etc/config/ and certain other configurations are automatically preserved.")) l = f:option(Button, "_list", translate("Show current backup file list")) l.inputtitle = translate("Open list...") l.inputstyle = "apply" c = f:option(TextValue, "_custom") c.rmempty = false c.cols = 70 c.rows = 30 c.cfgvalue = function(self, section) return nixio.fs.readfile("/etc/sysupgrade.conf") end c.write = function(self, section, value) value = value:gsub("\r\n?", "\n") return nixio.fs.writefile("/etc/sysupgrade.conf", value) end else m.submit = false m.reset = false f = m:section(SimpleSection, nil, translate("Below is the determined list of files to backup. It consists of changed configuration files marked by opkg, essential base files and the user defined backup patterns.")) l = f:option(Button, "_edit", translate("Back to configuration")) l.inputtitle = translate("Close list...") l.inputstyle = "link" d = f:option(DummyValue, "_detected") d.rawhtml = true d.cfgvalue = function(s) local list = io.popen( "( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " .. "/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " .. "opkg list-changed-conffiles ) | sort -u" ) if list then local files = { "<ul>" } while true do local ln = list:read("*l") if not ln then break else files[#files+1] = "<li>" files[#files+1] = luci.util.pcdata(ln) files[#files+1] = "</li>" end end list:close() files[#files+1] = "</ul>" return table.concat(files, "") end return "<em>" .. translate("No files found") .. "</em>" end end return m
gpl-2.0
ZyX-I/luassert
src/mock.lua
5
1402
-- module will return a mock module table, and will not register any assertions local spy = require 'luassert.spy' local stub = require 'luassert.stub' local function mock_apply(object, action) if type(object) ~= "table" then return end if spy.is_spy(object) then return object[action](object) end for k,v in pairs(object) do mock_apply(v, action) end return object end local mock mock = { new = function(object, dostub, func, self, key) local data_type = type(object) if data_type == "table" then if spy.is_spy(object) then -- this table is a function already wrapped as a spy, so nothing to do here else for k,v in pairs(object) do object[k] = mock.new(v, dostub, func, object, k) end end elseif data_type == "function" then if dostub then return stub(self, key, func) elseif self==nil then return spy.new(object) else return spy.on(self, key) end end return object end, clear = function(object) return mock_apply(object, "clear") end, revert = function(object) return mock_apply(object, "revert") end } return setmetatable(mock, { __call = function(self, ...) -- mock originally was a function only. Now that it is a module table -- the __call method is required for backward compatibility return mock.new(...) end })
mit
drcforbin/rwte
lua/util.lua
1
1588
local util = {} -- set the magic bit for a color value function util.truecolor(color) return color | 0x1000000 end function util.bench(func, samples, batch_size) local times = {} for j=1, samples do local t1 = os.clock() for i=1, batch_size do res = func() end times[#times+1] = os.clock() - t1 end return times end function util.stats(values, skip) local sum = values[skip + 1] local min = values[skip + 1] local max = values[skip + 1] for i=skip + 2, #values do local t = values[i] sum = sum + t if t < min then min = t end if max < t then max = t end end local count = (#values - skip) local mean = sum / count local delta = max - min sum = 0 for i=skip + 2, #values do local vm = values[i] - mean sum = sum + (vm * vm) end local var = sum / count local sd = math.sqrt(var) return { count = count, min = min, max = max, mean = mean, delta = delta, var = var, sd = sd } end function util.report_bench_stats(name, stats) local pcterr = stats.delta / stats.mean * 100 local bench_logger = logging.get("bench") bench_logger:info("Benchmark: " .. name) bench_logger:info(string.format("Average: %.5fs +/- %.5f (%.2f%%), Samples: %d", stats.mean, stats.delta, pcterr, stats.count)) bench_logger:info(string.format("Variance: %.5f, Std Dev: %.5f", stats.var, stats.sd)) end return util
mit
rlcevg/Zero-K
LuaUI/Widgets/camera_cofc.lua
1
88891
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Combo Overhead/Free Camera (experimental)", desc = "v0.138 Camera featuring 6 actions. Type \255\90\90\255/luaui cofc help\255\255\255\255 for help.", author = "CarRepairer, msafwan", date = "2011-03-16", --2014-Sept-25 license = "GNU GPL, v2 or later", layer = 1002, handler = true, enabled = false, } end include("keysym.h.lua") include("Widgets/COFCtools/Interpolate.lua") include("Widgets/COFCtools/TraceScreenRay.lua") --WG Exports: WG.COFC_SetCameraTarget: {number gx, number gy, number gz(, number smoothness(,boolean useSmoothMeshSetting(, number dist)))} -> {}, Set Camera target, ensures camera state caching works -- WG.COFC_SkyBufferProportion: {} -> number [0..1], proportion of maximum zoom height the camera is currently at. 0 is the ground, 1 is maximum zoom height. -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local init = true local trackmode = false --before options local thirdperson_trackunit = false -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- options_path = 'Settings/Camera/Camera Controls' local cameraFollowPath = 'Settings/Camera/Camera Following' local minimap_path = 'Settings/HUD Panels/Minimap' options_order = { 'helpwindow', 'topBottomEdge', 'leftRightEdge', 'middleMouseButton', 'lblZoom', -- 'zoomintocursor', -- 'zoomoutfromcursor', 'zoominfactor', 'zoomin', 'zoomoutfactor', 'zoomout', 'invertzoom', 'invertalt', 'tiltedzoom', 'zoomouttocenter', 'lblRotate', 'rotfactor', 'targetmouse', -- 'rotateonedge', 'inverttilt', 'groundrot', 'lblScroll', 'speedFactor', 'speedFactor_k', -- 'edgemove', 'invertscroll', 'smoothscroll', 'smoothmeshscroll', 'lblMisc', 'smoothness', 'fov', 'overviewmode', 'overviewset', 'rotatebackfromov', --'restrictangle', --'mingrounddist', 'resetcam', 'freemode', --following: 'lblFollowCursor', 'follow', 'lblFollowUnit', 'trackmode', 'persistenttrackmode', 'thirdpersontrack', 'lblFollowCursorZoom', 'followautozoom', 'followinscrollspeed', 'followoutscrollspeed', 'followzoominspeed', 'followzoomoutspeed', 'followzoommindist', 'followzoommaxdist', 'lblMisc2', 'enableCycleView', 'groupSelectionTapTimeout', } local OverviewAction = function() end local OverviewSetAction = function() end local SetFOV = function(fov) end local SelectNextPlayer = function() end local SetCenterBounds = function(cs) end options = { lblblank1 = {name='', type='label'}, lblRotate = {name='Rotation Behaviour', type='label'}, lblScroll = {name='Scroll Behaviour', type='label'}, lblZoom = {name='Zoom Behaviour', type='label'}, lblMisc = {name='Misc.', type='label'}, lblFollowCursor = {name='Cursor Following', type='label', path=cameraFollowPath}, lblFollowCursorZoom = {name='Auto-Zooming', type='label', path=cameraFollowPath}, lblFollowUnit = {name='Unit Following', type='label', path=cameraFollowPath}, lblMisc2 = {name='Misc.', type='label', path = cameraFollowPath}, topBottomEdge = { name = 'Top/Bottom Edge Behaviour', type = 'radioButton', value = 'pan', items = { {key = 'pan', name='Pan'}, {key = 'orbit', name='Rotate World'}, {key = 'rotate', name='Rotate Camera'}, {key = 'off', name='Off'}, }, }, leftRightEdge = { name = 'Left/Right Edge Behaviour', type = 'radioButton', value = 'pan', items = { {key = 'pan', name='Pan'}, {key = 'orbit', name='Rotate World'}, {key = 'rotate', name='Rotate Camera'}, {key = 'off', name='Off'}, }, }, middleMouseButton = { name = 'Middle Mouse Button Behaviour', type = 'radioButton', value = 'pan', items = { {key = 'pan', name='Pan'}, {key = 'orbit', name='Rotate World'}, {key = 'rotate', name='Rotate Camera'}, {key = 'off', name='Off'}, }, advanced = true, }, helpwindow = { name = 'COFCam Help', type = 'text', value = [[ Complete Overhead/Free Camera has six main actions... Zoom..... <Mousewheel> Tilt World..... <Ctrl> + <Mousewheel> Altitude..... <Alt> + <Mousewheel> Mouse Scroll..... <Middlebutton-drag> Rotate World..... <Ctrl> + <Middlebutton-drag> Rotate Camera..... <Alt> + <Middlebutton-drag> Additional actions: Keyboard: <arrow keys> replicate middlebutton drag while <pgup/pgdn> replicate mousewheel. You can use these with ctrl, alt & shift to replicate mouse camera actions. Use <Shift> to speed up camera movements. Reset Camera..... <Ctrl> + <Alt> + <Middleclick> ]], }, smoothscroll = { name = 'Smooth scrolling', desc = 'Use smoothscroll method when mouse scrolling.', type = 'bool', value = false, }, smoothmeshscroll = { name = 'Smooth Mesh Scrolling', desc = 'A smoother way to scroll. Applies to all types of mouse/keyboard scrolling.', type = 'bool', value = true, }, targetmouse = { name = 'Rotate world origin at cursor', desc = 'Rotate world using origin at the cursor rather than the center of screen.', type = 'bool', value = true, }, -- edgemove = { -- name = 'Scroll camera at edge', -- desc = 'Scroll camera when the cursor is at the edge of the screen.', -- springsetting = 'WindowedEdgeMove', -- type = 'bool', -- value = true, -- }, speedFactor = { name = 'Mouse scroll speed', desc = 'This speed applies to scrolling with the middle button.', type = 'number', min = 10, max = 40, value = 25, }, speedFactor_k = { name = 'Keyboard/edge scroll speed', desc = 'This speed applies to edge scrolling and keyboard keys.', type = 'number', min = 1, max = 50, value = 40, }, zoominfactor = { --should be lower than zoom-out-speed to help user aim tiny units name = 'Zoom-in speed', type = 'number', min = 0.1, max = 1, step = 0.05, value = 0.5, }, zoomoutfactor = { --should be higher than zoom-in-speed to help user escape to bigger picture name = 'Zoom-out speed', type = 'number', min = 0.1, max = 1, step = 0.05, value = 0.8, }, invertzoom = { name = 'Invert zoom', desc = 'Invert the scroll wheel direction for zooming.', type = 'bool', value = true, }, invertalt = { name = 'Invert altitude', desc = 'Invert the scroll wheel direction for altitude.', type = 'bool', value = false, }, inverttilt = { name = 'Invert tilt', desc = 'Invert the tilt direction when using ctrl+mousewheel.', type = 'bool', value = false, }, -- zoomoutfromcursor = { -- name = 'Zoom out from cursor', -- desc = 'Zoom out from the cursor rather than center of the screen.', -- type = 'bool', -- value = false, -- }, -- zoomintocursor = { -- name = 'Zoom in to cursor', -- desc = 'Zoom in to the cursor rather than the center of the screen.', -- type = 'bool', -- value = true, -- }, zoomin = { name = 'Zoom In', type = 'radioButton', value = 'toCursor', items = { {key = 'toCursor', name='To Cursor'}, {key = 'toCenter', name='To Screen Center'}, }, }, zoomout = { name = 'Zoom Out', type = 'radioButton', value = 'fromCenter', items = { {key = 'fromCursor', name='From Cursor'}, {key = 'fromCenter', name='From Screen Center'}, }, }, zoomouttocenter = { name = 'Zoom out to center', desc = 'Center the map as you zoom out.', type = 'bool', value = true, OnChange = function(self) local cs = Spring.GetCameraState() if cs.rx then SetCenterBounds(cs) -- Spring.SetCameraState(cs, options.smoothness.value) OverrideSetCameraStateInterpolate(cs,options.smoothness.value) end end, }, tiltedzoom = { name = 'Tilt camera while zooming', desc = 'Have the camera tilt while zooming. Camera faces ground when zoomed out, and looks out nearly parallel to ground when fully zoomed in', type = 'bool', value = true, }, rotfactor = { name = 'Rotation speed', type = 'number', min = 0.001, max = 0.020, step = 0.001, value = 0.005, }, -- rotateonedge = { -- name = "Rotate camera at edge", -- desc = "Rotate camera when the cursor is at the edge of the screen (edge scroll must be off).", -- type = 'bool', -- value = false, -- }, smoothness = { name = 'Smoothness', desc = "Controls how smooth the camera moves.", type = 'number', min = 0.0, max = 0.8, step = 0.1, value = 0.2, }, fov = { name = 'Field of View (Degrees)', --desc = "FOV (25 deg - 100 deg).", type = 'number', min = 10, max = 100, step = 5, value = Spring.GetCameraFOV(), springsetting = 'CamFreeFOV', --save stuff in springsetting. reference: epicmenu_conf.lua OnChange = function(self) SetFOV(self.value) end }, invertscroll = { name = "Invert scrolling direction", desc = "Invert scrolling direction (doesn't apply to smoothscroll).", type = 'bool', value = true, }, restrictangle = { name = "Restrict Camera Angle", desc = "If disabled you can point the camera upward, but end up with strange camera positioning.", type = 'bool', advanced = true, value = true, OnChange = function(self) init = true; end }, freemode = { name = "FreeMode (risky)", desc = "Be free. Camera movement not bound to map edge. USE AT YOUR OWN RISK!\nTips: press TAB if you get lost.", type = 'bool', advanced = true, value = false, OnChange = function(self) init = true; end, }, mingrounddist = { name = 'Minimum Ground Distance', desc = 'Getting too close to the ground allows strange camera positioning.', type = 'number', advanced = true, min = 0, max = 100, step = 1, value = 1, OnChange = function(self) init = true; end, }, overviewmode = { name = "COFC Overview", desc = "Go to overview mode, then restore view to cursor position.", type = 'button', hotkey = {key='tab', mod=''}, OnChange = function(self) OverviewAction() end, }, overviewset = { name = "Set Overview Viewpoint", desc = "Save the current view as the new overview mode viewpoint. Use 'Reset Camera' to remove it.", type = 'button', OnChange = function(self) OverviewSetAction() end, }, rotatebackfromov = { name = "Rotate Back From Overview", desc = "When returning from overview mode, rotate the camera to its original position (only applies when you have set an overview viewpoint).", type = 'bool', value = true, }, resetcam = { name = "Reset Camera", desc = "Reset the camera position and orientation. Map a hotkey or use <Ctrl> + <Alt> + <Middleclick>", type = 'button', -- OnChange defined later }, groundrot = { name = "Rotate When Camera Hits Ground", desc = "If world-rotation motion causes the camera to hit the ground, camera-rotation motion takes over. Doesn't apply in Free Mode.", type = 'bool', value = true, advanced = true, }, -- follow cursor follow = { name = "Follow player's cursor", desc = "Follow the cursor of the player you're spectating (needs Ally Cursor widget to be on). Mouse midclick to pause tracking for 4 second.", type = 'bool', value = false, hotkey = {key='l', mod='alt+'}, path = cameraFollowPath, OnChange = function(self) Spring.Echo("COFC: follow cursor " .. (self.value and "active" or "inactive")) end, }, followautozoom = { name = "Auto zoom", desc = "Auto zoom in and out while following player's cursor (zoom level will represent player's focus). \n\nDO NOT enable this if you want to control the zoom level yourself.", type = 'bool', value = false, path = cameraFollowPath, }, followinscrollspeed = { name = "On Screen Tracking Speed", desc = "Tracking speed while cursor is on-screen. \n\nRecommend: Lowest (prevent jerky movement)", type = 'number', min = 1, max = 14, step = 1, mid = (14+1)/2, value = 1, OnChange = function(self) Spring.Echo("COFC: " ..self.mid*2 - self.value .. " second") end, path = cameraFollowPath, }, followoutscrollspeed = { name = "Off Screen Tracking Speed", desc = "Tracking speed while cursor is off-screen. \n\nRecommend: Highest (prevent missed action)", type = 'number', min = 2, max = 15, step = 1, mid = (15+2)/2, value = 15, OnChange = function(self) Spring.Echo("COFC: " ..self.mid*2 - self.value .. " second") end, path = cameraFollowPath, }, followzoommindist = { name = "Closest Zoom", desc = "The closest zoom. Default: 500", type = 'number', min = 200, max = 10000, step = 100, value = 500, OnChange = function(self) Spring.Echo("COFC: " ..self.value .. " elmo") end, path = cameraFollowPath, }, followzoommaxdist = { name = "Farthest Zoom", desc = "The furthest zoom. Default: 2000", type = 'number', min = 200, max = 10000, step = 100, value = 2000, OnChange = function(self) Spring.Echo("COFC: " .. self.value .. " elmo") end, path = cameraFollowPath, }, followzoominspeed = { name = "Zoom-in Speed", desc = "Zoom-in speed when cursor is on-screen. Default: 50%", type = 'number', min = 0.1, max = 1, step = 0.05, value = 0.5, OnChange = function(self) Spring.Echo("COFC: " .. self.value*100 .. " percent") end, path = cameraFollowPath, }, followzoomoutspeed = { name = "Zoom-out Speed", desc = "Zoom-out speed when cursor is at screen edge and off-screen. Default: 50%", type = 'number', min = 0.1, max = 1, step = 0.05, value = 0.5, OnChange = function(self)Spring.Echo("COFC: " .. self.value*100 .. " percent") end, path = cameraFollowPath, }, -- end follow cursor -- follow unit trackmode = { name = "Activate Trackmode", desc = "Track the selected unit (mouse midclick to exit mode)", type = 'button', hotkey = {key='t', mod='alt+'}, path = cameraFollowPath, OnChange = function(self) if thirdperson_trackunit then --turn off 3rd person tracking if it is. Spring.SendCommands('trackoff') Spring.SendCommands('viewfree') thirdperson_trackunit = false end trackmode = true; Spring.Echo("COFC: Unit tracking ON") end, }, persistenttrackmode = { name = "Persistent trackmode state", desc = "Trackmode will not cancel when deselecting unit. Trackmode will always attempt to track newly selected unit. Press mouse midclick to cancel this mode.", type = 'bool', value = false, path = cameraFollowPath, }, thirdpersontrack = { name = "Enter 3rd Person Trackmode", desc = "3rd Person track the selected unit (mouse midclick to exit mode). Press arrow key to jump to nearby units, or move mouse to edge of screen to jump to current unit selection (will exit mode if no selection).", type = 'button', hotkey = {key='k', mod='alt+'}, path = cameraFollowPath, OnChange = function(self) local selUnits = Spring.GetSelectedUnits() if selUnits and selUnits[1] and thirdperson_trackunit ~= selUnits[1] then --check if 3rd Person into same unit or if there's any unit at all Spring.SendCommands('viewfps') Spring.SendCommands('track') thirdperson_trackunit = selUnits[1] local cs = Spring.GetCameraState() cs.px,cs.py,cs.pz =Spring.GetUnitPosition(selUnits[1]) --place FPS camera on the ground (prevent out of LOD case) cs.py = cs.py + 25 -- Spring.SetCameraState(cs,0) OverrideSetCameraStateInterpolate(cs,0) else Spring.SendCommands('trackoff') Spring.SendCommands('viewfree') thirdperson_trackunit = false end end, }, enableCycleView = { name = "Group recall cycle within group", type = 'bool', value = false, path = cameraFollowPath, desc = "If you tap the group numbers (1,2,3 etc.) it will move the camera position to different clusters of units within the group rather than to the average position of the entire group.", }, groupSelectionTapTimeout = { name = 'Group selection tap timeout', desc = "How quickly do you have to tap group numbers to move the camera? Smaller timeout means faster tapping.", type = 'number', min = 0.0, max = 5.0, step = 0.1, value = 2.0, path = cameraFollowPath, }, -- end follow unit } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local GL_LINES = GL.LINES local GL_GREATER = GL.GREATER local GL_POINTS = GL.POINTS local glBeginEnd = gl.BeginEnd local glColor = gl.Color local glLineWidth = gl.LineWidth local glVertex = gl.Vertex local glAlphaTest = gl.AlphaTest local glPointSize = gl.PointSize local glTexture = gl.Texture local glTexRect = gl.TexRect local red = { 1, 0, 0 } local green = { 0, 1, 0 } local black = { 0, 0, 0 } local white = { 1, 1, 1 } local spGetCameraState = Spring.GetCameraState local spGetCameraVectors = Spring.GetCameraVectors local spGetGroundHeight = Spring.GetGroundHeight local spGetSmoothMeshHeight = Spring.GetSmoothMeshHeight local spGetModKeyState = Spring.GetModKeyState local spGetMouseState = Spring.GetMouseState local spGetSelectedUnits = Spring.GetSelectedUnits local spGetUnitPosition = Spring.GetUnitPosition local spIsAboveMiniMap = Spring.IsAboveMiniMap local spSendCommands = Spring.SendCommands local spSetCameraState = Spring.SetCameraState local spSetMouseCursor = Spring.SetMouseCursor local spTraceScreenRay = Spring.TraceScreenRay local spWarpMouse = Spring.WarpMouse local spGetCameraDirection = Spring.GetCameraDirection local spGetTimer = Spring.GetTimer local spDiffTimers = Spring.DiffTimers local spGetUnitDefID = Spring.GetUnitDefID local spGetUnitSeparation = Spring.GetUnitSeparation local abs = math.abs local min = math.min local max = math.max local sqrt = math.sqrt local sin = math.sin local cos = math.cos local echo = Spring.Echo local helpText = {} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local ls_x, ls_y, ls_z --lockspot position local ls_dist, ls_have, ls_onmap --lockspot flag local tilting local overview_mode, last_rx, last_ry, last_ls_dist, ov_cs --overview_mode's variable local follow_timer = 0 local epicmenuHkeyComp = {} --for saving & reapply hotkey system handled by epicmenu.lua local initialBoundsSet = false -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local vsx, vsy = widgetHandler:GetViewSizes() local cx,cy = vsx * 0.5,vsy * 0.5 function widget:ViewResize(viewSizeX, viewSizeY) vsx = viewSizeX vsy = viewSizeY cx = vsx * 0.5 cy = vsy * 0.5 SetFOV(Spring.GetCameraFOV()) end local PI = 3.1415 --local TWOPI = PI*2 local HALFPI = PI/2 --local HALFPIPLUS = HALFPI+0.01 local HALFPIMINUS = HALFPI-0.01 local RADperDEGREE = PI/180 local fpsmode = false local mx, my = 0,0 local msx, msy = 0,0 local smoothscroll = false local springscroll = false local lockspringscroll = false local rotate, movekey local move, rot, move2 = {}, {}, {} local key_code = { left = 276, right = 275, up = 273, down = 274, pageup = 280, pagedown = 281, } local keys = { [276] = 'left', [275] = 'right', [273] = 'up', [274] = 'down', } local icon_size = 20 local cycle = 1 local camcycle = 1 local trackcycle = 1 local hideCursor = false local MWIDTH, MHEIGHT = Game.mapSizeX, Game.mapSizeZ local minX, minZ, maxX, maxZ = 0, 0, MWIDTH, MHEIGHT local mcx, mcz = MWIDTH / 2, MHEIGHT / 2 local mcy = spGetGroundHeight(mcx, mcz) local maxDistY = max(MHEIGHT, MWIDTH) * 2 local mapEdgeBuffer = 1000 --Tilt Zoom constants local onTiltZoomTrack = true local groundMin, groundMax = Spring.GetGroundExtremes() local topDownBufferZonePercent = 0.20 local groundBufferZone = 20 local topDownBufferZone = maxDistY * topDownBufferZonePercent local minZoomTiltAngle = 35 local angleCorrectionMaximum = 5 * RADperDEGREE local targetCenteringHeight = 1200 local mapEdgeProportion = 1.0/5.9 SetFOV = function(fov) local cs = spGetCameraState() -- Spring.Echo(fov .. " degree") local currentFOVhalf_rad = (fov/2) * RADperDEGREE mapEdgeBuffer = groundMax local mapFittingDistance = MHEIGHT/2 if vsy/vsx > MHEIGHT/MWIDTH then mapFittingDistance = (MWIDTH * vsy/vsx)/2 end local mapFittingEdge = mapFittingDistance/(1/(2 * mapEdgeProportion) - 1) -- map edge buffer is 1/5.9 of the length of the dimension fitted to screen mapEdgeBuffer = math.max(mapEdgeBuffer, mapFittingEdge) local mapLength = mapFittingDistance + mapEdgeBuffer maxDistY = mapLength/math.tan(currentFOVhalf_rad) --adjust maximum TAB/Overview distance based on camera FOV cs.fov = fov cs.py = overview_mode and maxDistY or math.min(cs.py, maxDistY) --Update Tilt Zoom Constants topDownBufferZone = maxDistY * topDownBufferZonePercent minZoomTiltAngle = (30 + 17 * math.tan(cs.fov/2 * RADperDEGREE)) * RADperDEGREE if cs.name == "free" then OverrideSetCameraStateInterpolate(cs,options.smoothness.value) else spSetCameraState(cs,0) end end local function SetSkyBufferProportion(cs) local _,cs_py,_ = Spring.GetCameraPosition() local topDownBufferZoneBottom = maxDistY - topDownBufferZone WG.COFC_SkyBufferProportion = min(max((cs_py - topDownBufferZoneBottom)/topDownBufferZone + 0.2, 0.0), 1.0) --add 0.2 to start fading little before the straight-down zoomout end do SetFOV(Spring.GetCameraFOV()) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local rotate_transit --switch for smoothing "rotate at mouse position instead of screen center" local last_move = spGetTimer() --switch for reseting lockspot for Edgescroll local thirdPerson_transit = spGetTimer() --switch for smoothing "3rd person trackmode edge screen scroll" -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function DetermineInitCameraState() local csOldpx, csOldpy, csOldpz = Spring.GetCameraPosition() local csOlddx, csOlddy, csOlddz = Spring.GetCameraDirection() local csOldrx = PI/2 - math.acos(csOlddy) local csOldry = math.atan2(csOlddx, -csOlddz) - PI spSendCommands("viewfree") local cs = spGetCameraState() -- if csOldpx == 0.0 * csOldpz == 0.0 then -- cs.px = MWIDTH/2 -- cs.pz = MHEIGHT/2 -- else cs.px = csOldpx cs.pz = csOldpz -- end cs.py = csOldpy cs.rx = csOldrx cs.ry = csOldry cs.rz = 0 return cs end local function GetMapBoundedCoords(x,z) --This should not use minX,minZ,maxX,maxZ bounds, as this is used specifically to keep things on the map if x < 0 then x = 0; end if x > MWIDTH then x=MWIDTH; end if z < 0 then z = 0; end if z > MHEIGHT then z = MHEIGHT; end return x,z end local function GetDist(x1,y1,z1, x2,y2,z2) local d1 = x2-x1 local d2 = y2-y1 local d3 = z2-z1 return sqrt(d1*d1 + d2*d2 + d3*d3) end local function explode(div,str) if (div=='') then return false end local pos,arr = 0,{} -- for each divider found for st,sp in function() return string.find(str,div,pos,true) end do table.insert(arr,string.sub(str,pos,st-1)) -- Attach chars left of current divider pos = sp + 1 -- Jump past current divider end table.insert(arr,string.sub(str,pos)) -- Attach chars right of last divider return arr end local function LimitZoom(a,b,c,sp,limit) --Check if anyone reach max speed local zox,zoy,zoz = a*sp,b*sp,c*sp local maxZoom = max(abs(zox),abs(zoy),abs(zoz)) --Limit speed maxZoom = min(maxZoom,limit) --Normalize local total = sqrt(zox^2+zoy^2+zoz^2) zox,zoy,zoz = zox/total,zoy/total,zoz/total --Reapply speed return zox*maxZoom,zoy*maxZoom,zoz*maxZoom end local function GetSmoothOrGroundHeight(x,z,checkFreeMode) --only ScrollCam seems to want to ignore this when FreeMode is on if options.smoothmeshscroll.value then return spGetSmoothMeshHeight(x, z) or 0 else if not (checkFreeMode and options.freemode.value) then return spGetGroundHeight(x, z) or 0 end end end local function GetMapBoundedGroundHeight(x,z) --out of map. Bound coordinate to within map x,z = GetMapBoundedCoords(x,z) return spGetGroundHeight(x,z) end local function GetMapBoundedSmoothOrGroundHeight(x,z) --out of map. Bound coordinate to within map x,z = GetMapBoundedCoords(x,z) return GetSmoothOrGroundHeight(x,z) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local scrnRay_cache = {result={0,0,0,0,0,0,0}, previous={fov=1,inclination=99,azimuth=299,x=9999,y=9999,plane=-100,sphere=-100}} local function OverrideTraceScreenRay(x,y,cs,planeToHit,sphereToHit,returnRayDistance) --this function provide an adjusted TraceScreenRay for null-space outside of the map (by msafwan) local viewSizeY = vsy local viewSizeX = vsx if not vsy or not vsx then viewSizeX, viewSizeY = widgetHandler:GetViewSizes() end --//Speedup//-- if scrnRay_cache.previous.fov==cs.fov and scrnRay_cache.previous.inclination == cs.rx and scrnRay_cache.previous.azimuth == cs.ry and scrnRay_cache.previous.x ==x and scrnRay_cache.previous.y == y and scrnRay_cache.previous.plane == planeToHit and scrnRay_cache.previous.sphere == sphereToHit then --if camera Sphere coordinate & mouse position not change then use cached value return scrnRay_cache.result[1], scrnRay_cache.result[2], scrnRay_cache.result[3], scrnRay_cache.result[4], scrnRay_cache.result[5], scrnRay_cache.result[6], scrnRay_cache.result[7] end local camPos = {px=cs.px,py=cs.py,pz=cs.pz} local camRot = {rx=cs.rx,ry=cs.ry,rz=cs.rz} local gx,gy,gz,rx,ry,rz,rayDist,cancelCache = TraceCursorToGround(viewSizeX,viewSizeY,{x=x,y=y} ,cs.fov, camPos, camRot,planeToHit,sphereToHit,returnRayDistance) --//caching for efficiency if not cancelCache then scrnRay_cache.result[1] = gx scrnRay_cache.result[2] = gy scrnRay_cache.result[3] = gz scrnRay_cache.result[4] = rx scrnRay_cache.result[5] = ry scrnRay_cache.result[6] = rz scrnRay_cache.result[7] = rayDist scrnRay_cache.previous.inclination =cs.rx scrnRay_cache.previous.azimuth = cs.ry scrnRay_cache.previous.x = x scrnRay_cache.previous.y = y scrnRay_cache.previous.fov = cs.fov scrnRay_cache.previous.plane = planeToHit scrnRay_cache.previous.sphere = sphereToHit end return gx,gy,gz,rx,ry,rz,rayDist end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --[[ --NOTE: is not yet used for the moment local function MoveRotatedCam(cs, mxm, mym) if not cs.dy then return cs end -- forward, up, right, top, bottom, left, right local camVecs = spGetCameraVectors() local cf = camVecs.forward local len = sqrt((cf[1] * cf[1]) + (cf[3] * cf[3])) local dfx = cf[1] / len local dfz = cf[3] / len local cr = camVecs.right local len = sqrt((cr[1] * cr[1]) + (cr[3] * cr[3])) local drx = cr[1] / len local drz = cr[3] / len local vecDist = (- cs.py) / cs.dy local ddx = (mxm * drx) + (mym * dfx) local ddz = (mxm * drz) + (mym * dfz) local gx1, gz1 = cs.px + vecDist*cs.dx, cs.pz + vecDist*cs.dz --note me: what does cs.dx mean? local gx2, gz2 = cs.px + vecDist*cs.dx + ddx, cs.pz + vecDist*cs.dz + ddz local extra = 500 if gx2 > MWIDTH + extra then ddx = MWIDTH + extra - gx1 elseif gx2 < 0 - extra then ddx = -gx1 - extra end if gz2 > MHEIGHT + extra then ddz = MHEIGHT - gz1 + extra elseif gz2 < 0 - extra then ddz = -gz1 - extra end cs.px = cs.px + ddx cs.pz = cs.pz + ddz return cs end --]] local function CorrectTraceTargetToSmoothMesh(cs,x,y,z) --Returns true if it corrected anything, false if no changes if cs.ry > 0 and options.smoothmeshscroll.value then --We couldn't tell Spring to trace to the smooth mesh point, so compensate with vector multiplication local y_smooth = spGetSmoothMeshHeight(x, z) or 0 local correction_vector_scale = 1 - (cs.py - y_smooth)/(cs.py - y) --Since cs.ry > 0, cs.py > y. We want real ground to smooth ground proportion local dx, dz = cs.px - x, cs.pz - z y = y_smooth x, z = x + dx * correction_vector_scale, z + dz * correction_vector_scale return true, x, y, z end return false, x, y, z end --Note: If the x,y is not pointing at an onmap point, this function traces a virtual ray to an -- offmap position using the camera direction and disregards the x,y parameters. local function VirtTraceRay(x,y, cs) local _, gpos = spTraceScreenRay(x, y, true, false,false, true) --only coordinate, NOT thru minimap, NOT include sky, ignore water surface if gpos then local gx, gy, gz = gpos[1], gpos[2], gpos[3] if gx < 0 or gx > MWIDTH or gz < 0 or gz > MHEIGHT then --out of map return false, gx, gy, gz else return true, gx, gy, gz end end if not cs or not cs.dy or cs.dy == 0 then return false, false end --[[ local vecDist = (- cs.py) / cs.dy local gx, gy, gz = cs.px + vecDist*cs.dx, cs.py + vecDist*cs.dy, cs.pz + vecDist*cs.dz --note me: what does cs.dx mean? --]] local gx,gy,gz = OverrideTraceScreenRay(x,y,cs,nil,nil,nil) --use override if spTraceScreenRay() do not have results --gy = spGetSmoothMeshHeight (gx,gz) return false, gx, gy, gz end SetCenterBounds = function(cs) -- if options.zoomouttocenter then Spring.Echo("zoomouttocenter.value: "..options.zoomouttocenter.value) end if options.zoomouttocenter.value --move camera toward center and ls_x --lockspot exist then scrnRay_cache.previous.fov = -999 --force reset cache (somehow cache value is used. Don't make sense at all...) local currentFOVhalf_rad = (cs.fov/2) * RADperDEGREE local maxDc = math.max((maxDistY - cs.py), 0)/(maxDistY - mapEdgeBuffer)-- * math.tan(currentFOVhalf_rad) * 1.5) -- Spring.Echo("MaxDC: "..maxDc) minX, minZ, maxX, maxZ = math.max(mcx - MWIDTH/2 * maxDc, 0), math.max(mcz - MHEIGHT/2 * maxDc, 0), math.min(mcx + MWIDTH/2 * maxDc, MWIDTH), math.min(mcz + MHEIGHT/2 * maxDc, MHEIGHT) local outOfBounds = false; if cs.rx > -HALFPI + 0.002 then --If we are not facing stright down, do a full raycast local _,gx,gy,gz = VirtTraceRay(cx, cy, cs) if gx < minX then cs.px = cs.px + (minX - gx); ls_x = ls_x + (minX - gx); outOfBounds = true end if gx > maxX then cs.px = cs.px + (maxX - gx); ls_x = ls_x + (maxX - gx); outOfBounds = true end if gz < minZ then cs.pz = cs.pz + (minZ - gz); ls_z = ls_z + (minZ - gz); outOfBounds = true end if gz > maxZ then cs.pz = cs.pz + (maxZ - gz); ls_z = ls_z + (maxZ - gz); outOfBounds = true end else --We can use camera x & z location in place of a raycast to find center when camera is pointed towards ground, as this is faster and more numerically stable if cs.px < minX then cs.px = minX; ls_x = minX; outOfBounds = true end if cs.px > maxX then cs.px = maxX; ls_x = maxX; outOfBounds = true end if cs.pz < minZ then cs.pz = minZ; ls_z = minZ; outOfBounds = true end if cs.pz > maxZ then cs.pz = maxZ; ls_z = maxZ; outOfBounds = true end end if outOfBounds then ls_y = GetMapBoundedGroundHeight(ls_x, ls_z) end else minX, minZ, maxX, maxZ = 0, 0, MWIDTH, MHEIGHT end -- Spring.Echo("Bounds: "..minX..", "..minZ..", "..maxX..", "..maxZ) end local function ComputeLockSpotParams(cs, gx, gy, gz, onmap) --Only compute from what is sent in, otherwise use pre-existing values if gx then ls_x,ls_y,ls_z = gx,gy,gz end if ls_x then local px,py,pz = cs.px,cs.py,cs.pz local dx,dy,dz = ls_x-px, ls_y-py, ls_z-pz if onmap then ls_onmap = onmap end ls_dist = sqrt(dx*dx + dy*dy + dz*dz) --distance to ground coordinate ls_have = true end end local function SetLockSpot2(cs, x, y, useSmoothMeshSetting) --set an anchor on the ground for camera rotation if ls_have then --if lockspot is locked return end local x, y = x, y if not x then x, y = cx, cy --center of screen end local onmap, gx,gy,gz = VirtTraceRay(x, y, cs) --convert screen coordinate to ground coordinate if useSmoothMeshSetting then _, gx,gy,gz = CorrectTraceTargetToSmoothMesh(cs, gx,gy,gz) end ComputeLockSpotParams(cs, gx, gy, gz, onmap) end local function UpdateCam(cs) local cs = cs if not (cs.rx and cs.ry and ls_dist) then --return cs return false end local alt = sin(cs.rx) * ls_dist local opp = cos(cs.rx) * ls_dist --OR same as: sqrt(ls_dist * ls_dist - alt * alt) cs.px = ls_x - sin(cs.ry) * opp cs.py = ls_y - alt cs.pz = ls_z - cos(cs.ry) * opp if not options.freemode.value then local gndheight = spGetGroundHeight(cs.px, cs.pz) + 10 if cs.py < gndheight then --prevent camera from going underground if options.groundrot.value then cs.py = gndheight else return false end end end return cs end local function GetZoomTiltAngle(gx, gz, cs, zoomin, rayDist) --[[ --FOR REFERENCE --plot of "sqrt(skyProportion) * (-2 * HALFPI / 3) - HALFPI / 3" O - - - - - - - - - - - - - - - - ->1 +skyProportion -18 | |x -36 | x | x -54 | x | x -72 | x | x -90 v -cam angle x --]] local groundHeight = groundMin --GetMapBoundedGroundHeight(gx, gz) + groundBufferZone local skyProportion = math.min(math.max((cs.py - groundHeight)/((maxDistY - topDownBufferZone) - groundHeight), 0.0), 1.0) local targetRx = sqrt(skyProportion) * (minZoomTiltAngle - HALFPI) - minZoomTiltAngle -- Ensure angle correction only happens by parts if the angle doesn't match the target, unless it is within a threshold -- If it isn't, make sure the correction only happens in the direction of the curve. -- Zooming in shouldn't make the camera face the ground more, and zooming out shouldn't focus more on the horizon if zoomin ~= nil and rayDist then if onTiltZoomTrack or math.abs(targetRx - cs.rx) < angleCorrectionMaximum then -- Spring.Echo("Within Bounds") onTiltZoomTrack = true return targetRx elseif targetRx > cs.rx and zoomin then -- Spring.Echo("Pulling on track for Zoomin") -- onTiltZoomTrack = true return cs.rx + angleCorrectionMaximum elseif targetRx < cs.rx and not zoomin then -- Spring.Echo("Pulling on track for Zoomout") -- onTiltZoomTrack = true if skyProportion < 1.0 and rayDist < (maxDistY - topDownBufferZone) then return cs.rx - angleCorrectionMaximum else return targetRx end end end -- Spring.Echo((onTiltZoomTrack and "On" or "Off").." tiltzoom track") if onTiltZoomTrack then return targetRx else return cs.rx end end local function ZoomTiltCorrection(cs, zoomin, mouseX,mouseY) if (mouseX==nil) then mouseX,mouseY = mouseX or vsx/2,mouseY or vsy/2 --if NIL, revert to center of screen end scrnRay_cache.previous.fov = -999 --force reset cache (somehow cache value is used. Don't make sense at all...) local gx,gy,gz,_,_,_,rayDist = OverrideTraceScreenRay(mouseX,mouseY, cs, nil,nil,true) -- if gx and not options.freemode.value then -- out of map. Bound zooming to within map -- gx,gz = GetMapBoundedCoords(gx,gz) -- end local targetRx = GetZoomTiltAngle(gx, gz, cs, zoomin, rayDist) cs.rx = targetRx local testgx,testgy,testgz = OverrideTraceScreenRay(mouseX, mouseY, cs, gy,nil,nil) -- if testgx and not options.freemode.value then -- out of map. Bound zooming to within map -- testgx,testgz = GetMapBoundedCoords(testgx, testgz) -- end -- Correct so that mouse cursor is hovering over the same point. -- Slight intentional overcorrection, helps the rotating camera keep the target in view -- Get proportion needed so that target location is centered in the view around when cs.py is targetCenteringHeight elmos above target, when zoomed from overview local centerwardDriftBase = (maxDistY - groundMin)/((maxDistY - groundMin) - (gy + targetCenteringHeight)) - 1 -- Spring.Echo(centerwardDriftBase) local centerwardVDriftFactor = ((mouseY - vsy/2)/(vsy/2) - 0.45) * centerwardDriftBase --Shift vertical overcorrection down, to compensate for camera tilt local centerwardHDriftFactor = (mouseX - vsx/2)/(vsx/2) * centerwardDriftBase * (vsx/vsy) --Adjust horizontal overcorrection for aspect ratio -- Ensure that both points are on the same plane by testing them from camera. This way the y value will always be positive, making div/0 checks possible local dgx, dgz, dtestx, dtestz = gx - cs.px, gz - cs.pz, testgx - cs.px, testgz - cs.pz local dyCorrection = 1 if cs.py > 0 then dyCorrection = (cs.py - gy)/max(cs.py - testgy, 0.001) end dtestx, dtestz = dtestx * dyCorrection, dtestz * dyCorrection local dx, dz = (dgx - dtestx), (dgz - dtestz) if zoomin or cs.py < topDownBufferZone then cs.px = cs.px + dx - abs(sin(cs.ry)) * centerwardVDriftFactor * dx + abs(cos(cs.ry)) * centerwardHDriftFactor * dz cs.pz = cs.pz + dz - abs(cos(cs.ry)) * centerwardVDriftFactor * dz - abs(sin(cs.ry)) * centerwardHDriftFactor * dx else cs.px = cs.px + dx cs.pz = cs.pz + dz end -- Spring.Echo("Cos(RY): "..math.cos(cs.ry)..", Sin(RY): "..math.sin(cs.ry)) return cs end local function SetCameraTarget(gx,gy,gz,smoothness,useSmoothMeshSetting,dist) --Note: this is similar to spSetCameraTarget() except we have control of the rules. --for example: native spSetCameraTarget() only work when camera is facing south at ~45 degree angle and camera height cannot have negative value (not suitable for underground use) if gx and gy and gz and not init then --just in case if smoothness == nil then smoothness = options.smoothness.value or 0 end local cs = GetTargetCameraState() SetLockSpot2(cs) --get lockspot at mid screen if there's none present if not ls_have then return end if dist then -- if a distance is specified, loosen bounds at first. They will be checked at the end ls_dist = dist ls_x, ls_y, ls_z = gx, gy, gz else -- otherwise, enforce bounds here to avoid the camera jumping around when moved with MMB or minimap over hilly terrain ls_x = min(max(gx, minX), maxX) --update lockpot to target destination ls_z = min(max(gz, minZ), maxZ) if useSmoothMeshSetting then ls_y = GetMapBoundedSmoothOrGroundHeight(ls_x, ls_z) else ls_y = GetMapBoundedGroundHeight(ls_x, ls_z) end end if options.tiltedzoom.value then local cstemp = UpdateCam(cs) if cstemp then cs.rx = GetZoomTiltAngle(ls_x, ls_z, cstemp) end end local oldPy = cs.py local cstemp = UpdateCam(cs) if cstemp then cs = cstemp end if not options.freemode.value then cs.py = min(cs.py, maxDistY) end --Ensure camera never goes higher than maxY SetCenterBounds(cs) -- spSetCameraState(cs, smoothness) --move OverrideSetCameraStateInterpolate(cs,smoothness) end end local function Zoom(zoomin, shift, forceCenter) local zoomin = zoomin if options.invertzoom.value then zoomin = not zoomin end local cs = GetTargetCameraState() --//ZOOMOUT FROM CURSOR, ZOOMIN TO CURSOR//-- if (not forceCenter) and ((zoomin and options.zoomin.value == 'toCursor') or ((not zoomin) and options.zoomout.value == 'fromCursor')) then local onmap, gx,gy,gz = VirtTraceRay(mx, my, cs) if gx and not options.freemode.value then --out of map. Bound zooming to within map gx,gz = GetMapBoundedCoords(gx,gz) end if gx then dx = gx - cs.px dy = gy - cs.py dz = gz - cs.pz else return false end local sp = (zoomin and options.zoominfactor.value or -options.zoomoutfactor.value) * (shift and 3 or 1) -- Spring.Echo("Zoom Speed: "..sp) local zox,zoy,zoz = LimitZoom(dx,dy,dz,sp,2000) local new_px = cs.px + zox --a zooming that get slower the closer you are to the target. local new_py = cs.py + zoy local new_pz = cs.pz + zoz -- Spring.Echo("Zoom Speed Vector: ("..zox..", "..zoy..", "..zoz..")") local groundMinimum = GetMapBoundedGroundHeight(new_px, new_pz) + 20 if not options.freemode.value then if new_py < groundMinimum then --zooming underground? sp = (groundMinimum - cs.py) / dy -- Spring.Echo("Zoom Speed at ground: "..sp) zox,zoy,zoz = LimitZoom(dx,dy,dz,sp,2000) new_px = cs.px + zox --a zooming that get slower the closer you are to the ground. new_py = cs.py + zoy new_pz = cs.pz + zoz -- Spring.Echo("Zoom Speed Vector: ("..zox..", "..zoy..", "..zoz..")") elseif (not zoomin) and new_py > maxDistY then --zoom out to space? sp = (maxDistY - cs.py) / dy -- Spring.Echo("Zoom Speed at sky: "..sp) zox,zoy,zoz = LimitZoom(dx,dy,dz,sp,2000) new_px = cs.px + zox --a zoom-out that get slower the closer you are to the ceiling? new_py = cs.py + zoy new_pz = cs.pz + zoz -- Spring.Echo("Zoom Speed Vector: ("..zox..", "..zoy..", "..zoz..")") end end if new_py == new_py then local boundedPy = (options.freemode.value and new_py) or min(max(new_py, groundMinimum), maxDistY - 10) cs.px = new_px-- * (boundedPy/math.max(new_py, 0.0001)) cs.py = boundedPy cs.pz = new_pz-- * (boundedPy/math.max(new_py, 0.0001)) --//SUPCOM camera zoom by Shadowfury333(Dominic Renaud): if options.tiltedzoom.value then cs = ZoomTiltCorrection(cs, zoomin, mx,my) end end --// -- ls_dist = cs.py -- spSetCameraState(cs, options.smoothness.value) ls_have = false -- return else --//ZOOMOUT FROM CENTER-SCREEN, ZOOMIN TO CENTER-SCREEN//-- local onmap, gx,gy,gz = VirtTraceRay(cx, cy, cs) if gx and not options.freemode.value then --out of map. Bound zooming to within map gx,gz = GetMapBoundedCoords(gx,gz) end ls_have = false --unlock lockspot -- SetLockSpot2(cs) --set lockspot -- if gx then --set lockspot -- ls_x,ls_y,ls_z = gx,gy,gz -- local px,py,pz = cs.px,cs.py,cs.pz -- local dx,dy,dz = ls_x-px, ls_y-py, ls_z-pz -- ls_onmap = onmap -- ls_dist = sqrt(dx*dx + dy*dy + dz*dz) --distance to ground coordinate -- ls_have = true -- end ComputeLockSpotParams(cs, gx, gy, gz, onmap) if not ls_have then return end -- if zoomin and not ls_onmap then --prevent zooming into null area (outside map) -- return -- end -- if not options.freemode.value and ls_dist >= maxDistY then -- return -- end local sp = (zoomin and -options.zoominfactor.value or options.zoomoutfactor.value) * (shift and 3 or 1) local ls_dist_new = ls_dist + max(min(ls_dist*sp,2000),-2000) -- a zoom in that get faster the further away from target (limited to -+2000) ls_dist_new = max(ls_dist_new, 20) if not options.freemode.value and ls_dist_new > maxDistY - gy then --limit camera distance to maximum distance -- return ls_dist_new = maxDistY - gy end ls_dist = ls_dist_new local cstemp = UpdateCam(cs) if cstemp and options.tiltedzoom.value then cstemp = ZoomTiltCorrection(cstemp, zoomin, nil) cstemp = UpdateCam(cstemp) end if cstemp then cs = cstemp; end end SetCenterBounds(cs) -- spSetCameraState(cs, options.smoothness.value) OverrideSetCameraStateInterpolate(cs,options.smoothness.value) return true end local function Altitude(up, s) ls_have = false onTiltZoomTrack = false local up = up if options.invertalt.value then up = not up end local cs = GetTargetCameraState() local py = max(1, abs(cs.py) ) local dy = py * (up and 1 or -1) * (s and 0.3 or 0.1) local new_py = py + dy if not options.freemode.value then if new_py < spGetGroundHeight(cs.px, cs.pz)+5 then new_py = spGetGroundHeight(cs.px, cs.pz)+5 elseif new_py > maxDistY then new_py = maxDistY end end cs.py = new_py SetCenterBounds(cs) -- spSetCameraState(cs, options.smoothness.value) OverrideSetCameraStateInterpolate(cs, options.smoothness.value) return true end --==End camera utility function^^ (a frequently used function. Function often used for controlling camera). local function ResetCam() local cs = spGetCameraState() cs.px = Game.mapSizeX/2 cs.py = maxDistY - 5 --Avoids flying off into nothingness when zooming out from cursor cs.pz = Game.mapSizeZ/2 cs.rx = -HALFPI cs.ry = PI SetCenterBounds(cs) -- spSetCameraState(cs, 0) OverrideSetCameraStateInterpolate(cs,0) ov_cs = nil onTiltZoomTrack = true end options.resetcam.OnChange = ResetCam OverviewSetAction = function() local cs = GetTargetCameraState() ov_cs = {} ov_cs.px = cs.px ov_cs.py = cs.py ov_cs.pz = cs.pz ov_cs.rx = cs.rx ov_cs.ry = cs.ry end OverviewAction = function() if not overview_mode then if thirdperson_trackunit then --exit 3rd person to show map overview spSendCommands('trackoff') spSendCommands('viewfree') end local cs = GetTargetCameraState() SetLockSpot2(cs) last_ls_dist = ls_dist last_rx = cs.rx last_ry = cs.ry if ov_cs then cs.px = ov_cs.px cs.py = ov_cs.py cs.pz = ov_cs.pz cs.rx = ov_cs.rx cs.ry = ov_cs.ry else cs.px = Game.mapSizeX/2 cs.py = maxDistY cs.pz = Game.mapSizeZ/2 cs.rx = -HALFPI end SetCenterBounds(cs) -- spSetCameraState(cs, 1) OverrideSetCameraStateInterpolate(cs,1) else --if in overview mode local cs = GetTargetCameraState() mx, my = spGetMouseState() local onmap, gx, gy, gz = VirtTraceRay(mx,my,cs) --create a lockstop point. if gx then --Note: Now VirtTraceRay can extrapolate coordinate in null space (no need to check for onmap) local cs = GetTargetCameraState() cs.rx = last_rx if ov_cs and last_ry and options.rotatebackfromov.value then cs.ry = last_ry end ls_dist = last_ls_dist ls_x = gx ls_z = gz ls_y = gy ls_have = true local cstemp = UpdateCam(cs) --set camera position & orientation based on lockstop point if cstemp then cs = cstemp; end SetCenterBounds(cs) -- spSetCameraState(cs, 1) OverrideSetCameraStateInterpolate(cs,1) end if thirdperson_trackunit then local selUnits = spGetSelectedUnits() --player's new unit to track if not (selUnits and selUnits[1]) then --if player has no new unit to track Spring.SelectUnitArray({thirdperson_trackunit}) --select the original unit selUnits = spGetSelectedUnits() end thirdperson_trackunit = false if selUnits and selUnits[1] then spSendCommands('viewfps') spSendCommands('track') -- re-issue 3rd person for selected unit thirdperson_trackunit = selUnits[1] local cs = GetTargetCameraState() cs.px,cs.py,cs.pz=spGetUnitPosition(selUnits[1]) --move camera to unit position so no "out of LOD" case cs.py= cs.py+25 --move up 25-elmo incase FPS camera stuck to unit's feet instead of tracking it (aesthetic) -- spSetCameraState(cs,0) OverrideSetCameraStateInterpolate(cs,0) end end end overview_mode = not overview_mode end --==End option menu function (function that is attached to epic menu button)^^ local offscreenTracking = false --state variable local function AutoZoomInOutToCursor() --options.followautozoom (auto zoom camera while in follow cursor mode) if smoothscroll or springscroll or rotate then return end local lclZoom = function(zoomin, smoothness,x,y,z) if not options.followautozoom.value then SetCameraTarget(x,y,z, smoothness) --track only return end local cs = GetTargetCameraState() ls_have = false --unlock lockspot SetLockSpot2(cs) --set lockspot if not ls_have then return end local sp = (zoomin and -1*options.followzoominspeed.value or options.followzoomoutspeed.value) local deltaDist = max(abs(ls_dist - abs(options.followzoommaxdist.value+options.followzoommindist.value)/2),10) --distance to midpoint local ls_dist_new = ls_dist + deltaDist*sp --zoom step: distance-to-midpoint multiplied by a zooming-multiplier ls_dist_new = max(ls_dist_new, options.followzoommindist.value) ls_dist_new = min(ls_dist_new, maxDistY,options.followzoommaxdist.value) ls_dist = ls_dist_new ls_x = x --update lockpot to target destination ls_y = y ls_z = z ls_have = true --lock lockspot if options.tiltedzoom.value and cs.name == "free" then --fixme: proper handling of a case where cam is not "free cam". --How to replicate: join a running game with autozoom & autotilt on, but DO NOT OPEN THE SPRING WINDOW, --allow for some catchup then open the Spring window to look at the game, the camera definitely already crashed. cs = ZoomTiltCorrection(cs, zoomin, nil) end local cstemp = UpdateCam(cs) if cstemp then cs = cstemp; end -- spSetCameraState(cs, smoothness) --track & zoom OverrideSetCameraStateInterpolate(cs,0) end local teamID = Spring.GetLocalTeamID() local _, playerID = Spring.GetTeamInfo(teamID) local pp = WG.alliedCursorsPos[ playerID ] if pp then local groundY = max(0,spGetGroundHeight(pp[1],pp[2])) local scrn_x,scrn_y = Spring.WorldToScreenCoords(pp[1],groundY,pp[2]) --get cursor's position on screen local scrnsize_X,scrnsize_Y = Spring.GetViewGeometry() --get current screen size if (scrn_x<scrnsize_X*4/6 and scrn_x>scrnsize_X*2/6) and (scrn_y<scrnsize_Y*4/6 and scrn_y>scrnsize_Y*2/6) then --if cursor near center: -- Spring.Echo("CENTER") local onscreenspeed = options.followinscrollspeed.mid*2 - options.followinscrollspeed.value --reverse value (ie: if 15 return 1, if 1 return 15, ect) lclZoom(true, onscreenspeed,pp[1], groundY, pp[2]) --zoom in & track offscreenTracking = nil elseif (scrn_x<scrnsize_X*5/6 and scrn_x>scrnsize_X*1/6) and (scrn_y<scrnsize_Y*5/6 and scrn_y>scrnsize_Y*1/6) then --if cursor between center & edge: do nothing -- Spring.Echo("MID") if not offscreenTracking then local onscreenspeed = options.followinscrollspeed.mid*2 - options.followinscrollspeed.value --reverse value (ie: if 15 return 1, if 1 return 15, ect) SetCameraTarget(pp[1], groundY, pp[2], onscreenspeed) --track else --continue off-screen tracking, but at fastest speed (bring cursor to center ASAP) local maxspeed = math.min(options.followoutscrollspeed.mid*2 - options.followoutscrollspeed.value,options.followinscrollspeed.mid*2 - options.followinscrollspeed.value) --the fastest speed available SetCameraTarget(pp[1], groundY, pp[2], maxspeed) --track end elseif (scrn_x<scrnsize_X*6/6 and scrn_x>scrnsize_X*0/6) and (scrn_y<scrnsize_Y*6/6 and scrn_y>scrnsize_Y*0/6) then --if cursor near edge: do -- Spring.Echo("EDGE") if not offscreenTracking then local onscreenspeed = options.followinscrollspeed.mid*2 - options.followinscrollspeed.value --reverse value (ie: if 15 return 1, if 1 return 15, ect) lclZoom(false, onscreenspeed,pp[1], groundY, pp[2]) --zoom out & track else --continue off-screen tracking, but at fastest speed (bring cursor to center ASAP) local maxspeed = math.min(options.followoutscrollspeed.mid*2 - options.followoutscrollspeed.value,options.followinscrollspeed.mid*2 - options.followinscrollspeed.value) --the fastest speed available lclZoom(false, maxspeed,pp[1], groundY, pp[2]) --zoom out & track end else --outside screen -- Spring.Echo("OUT") local offscreenspeed = options.followoutscrollspeed.mid*2 - options.followoutscrollspeed.value --reverse value (ie: if 15 return 1, if 1 return 15, ect) lclZoom(false, offscreenspeed,pp[1], groundY, pp[2]) --zoom out & track offscreenTracking = true end end end local function RotateCamera(x, y, dx, dy, smooth, lock) local cs = GetTargetCameraState() local cs1 = cs if cs.rx then cs.rx = cs.rx + dy * options.rotfactor.value cs.ry = cs.ry - dx * options.rotfactor.value --local max_rx = options.restrictangle.value and -0.1 or HALFPIMINUS local max_rx = HALFPIMINUS if cs.rx < -HALFPIMINUS then cs.rx = -HALFPIMINUS elseif cs.rx > max_rx then cs.rx = max_rx end -- [[ if trackmode then --rotate world instead of camera during trackmode (during tracking unit) lock = true --lock camera to lockspot while rotating ls_have = false -- SetLockSpot2(cs) --set lockspot to middle of screen local selUnits = spGetSelectedUnits() if selUnits and selUnits[1] then local x,y,z = spGetUnitPosition( selUnits[1] ) if x then --set lockspot to the unit ls_x,ls_y,ls_z = x,y,z local px,py,pz = cs.px,cs.py,cs.pz local dx,dy,dz = ls_x-px, ls_y-py, ls_z-pz ls_onmap = true ls_dist = sqrt(dx*dx + dy*dy + dz*dz) --distance to unit ls_have = true end end end --]] if lock and (ls_onmap or options.freemode.value) then --if have lock (ls_have ==true) and is either onmap or freemode (offmap) then update camera properties. local cstemp = UpdateCam(cs) if cstemp then cs = cstemp; else return end else ls_have = false end -- spSetCameraState(cs, smooth and options.smoothness.value or 0) OverrideSetCameraStateInterpolate(cs,smooth and options.smoothness.value or 0) end end local function ThirdPersonScrollCam(cs) --3rd person mode that allow you to jump between unit by edge scrolling (by msafwan) local detectionSphereRadiusAndPosition = { --This big spheres will fill a 90-degree cone and is used to represent a detection cone facing forward/left/right/backward. It's size will never exceed the 90-degree cone, but bigger sphere will always overlap halfway into smaller sphere and some empty space still exist on the side. --the first 25-elmo from unit is an empty space (which is really close to unit and thus needed no detection sphere) [1]={60,85}, --smaller sphere [2]={206,291}, --bigger sphere [3]={704,995}, [4]={2402,3397}, [5]={8201,11598}, [6]={28001,39599}, --90-degree cone } --local camVecs = spGetCameraVectors() local isSpec = Spring.GetSpectatingState() local teamID = (not isSpec and Spring.GetMyTeamID()) --get teamID ONLY IF not spec local foundUnit, foundUnitStructure local forwardOffset,backwardOffset,leftOffset,rightOffset if move.right then --content of move table is set in KeyPress(). Is global. Is used to start scrolling & rotation (initiated in Update()) rightOffset =true elseif move.up then forwardOffset = true elseif move.left then leftOffset =true elseif move.down then backwardOffset = true end local front, top, right = Spring.GetUnitVectors(thirdperson_trackunit) --get vector of current tracked unit local x,y,z = spGetUnitPosition(thirdperson_trackunit) y = y+25 for i=1, 3 do --create a (detection) sphere of increasing size to ~1600-elmo range in scroll direction local sphereCenterOffset = detectionSphereRadiusAndPosition[i][2] local sphereRadius = detectionSphereRadiusAndPosition[i][1] local offX_temp = (forwardOffset and sphereCenterOffset) or (backwardOffset and -sphereCenterOffset) or 0 --set direction where sphere must grow in x,y,z (global) direction. local offY_temp = 0 local offZ_temp = (rightOffset and sphereCenterOffset) or (leftOffset and -sphereCenterOffset) or 0 local offX = front[1]*offX_temp + top[1]*offY_temp + right[1]*offZ_temp --rotate (translate) the global right/left/forward/backward into a direction relative to current unit local offY = front[2]*offX_temp + top[2]*offY_temp + right[2]*offZ_temp local offZ = front[3]*offX_temp + top[3]*offY_temp + right[3]*offZ_temp local sphUnits = Spring.GetUnitsInSphere(x+offX,y+offY,z+offZ, sphereRadius,teamID) --create sphere that detect unit in area of this direction local lowestUnitSeparation = 9999 local lowestStructureSeparation = 9999 for i=1, #sphUnits do local unitID = sphUnits[i] Spring.SelectUnitArray({unitID}) --test select unit (in case its not selectable) local selUnits = spGetSelectedUnits() if selUnits and selUnits[1] then --find unit in that area local defID = spGetUnitDefID(unitID) local unitSeparation = spGetUnitSeparation (unitID, thirdperson_trackunit, true) if UnitDefs[defID] and UnitDefs[defID].speed >0 then if lowestUnitSeparation > unitSeparation then foundUnit = selUnits[1] lowestUnitSeparation = unitSeparation end elseif not foundUnitStructure then if lowestStructureSeparation > unitSeparation then foundUnitStructure = selUnits[1] lowestStructureSeparation = unitSeparation end end end end if foundUnit then break end -- i++ (increase size of detection sphere) & (increase distance of detection sphere away into selected direction) end if not foundUnit then --if no mobile unit in the area: use closest structure (as target) foundUnit = foundUnitStructure end if not foundUnit then --if no unit in the area: use current unit (as target) foundUnit = thirdperson_trackunit Spring.Echo("COFC: no unit in that direction to jump to!") end Spring.SelectUnitArray({foundUnit}) --give selection order to player spSendCommands('viewfps') spSendCommands('track') thirdperson_trackunit = foundUnit --remember current unitID cs.px,cs.py,cs.pz=spGetUnitPosition(foundUnit) --move FPS camera to ground level (prevent out of LOD problem where unit turn into icons) cs.py = cs.py+25 -- spSetCameraState(cs,0) OverrideSetCameraStateInterpolate(cs,0) thirdPerson_transit = spGetTimer() --block access to edge scroll until camera focus on unit end local function Tilt(s, dir) if not tilting then ls_have = false end tilting = true onTiltZoomTrack = false local cs = GetTargetCameraState() SetLockSpot2(cs) if not ls_have then return end local dir = dir * (options.inverttilt.value and -1 or 1) local speed = dir * (s and 30 or 10) RotateCamera(vsx * 0.5, vsy * 0.5, 0, speed, true, true) --smooth, lock return true end local function ScrollCam(cs, mxm, mym, smoothlevel) scrnRay_cache.previous.fov = -999 --force reset of offmap traceScreenRay cache. Reason: because offmap traceScreenRay use cursor position for calculation but scrollcam always have cursor at midscreen SetLockSpot2(cs, nil, nil, true) if not cs.dy or not ls_have then --echo "<COFC> scrollcam fcn fail" return end if not ls_onmap then smoothlevel = 0.5 end -- forward, up, right, top, bottom, left, right local camVecs = spGetCameraVectors() local cf = camVecs.forward local len = sqrt((cf[1] * cf[1]) + (cf[3] * cf[3])) --get hypotenus of x & z vector only local dfx = cf[1] / len local dfz = cf[3] / len local cr = camVecs.right local len = sqrt((cr[1] * cr[1]) + (cr[3] * cr[3])) local drx = cr[1] / len local drz = cr[3] / len -- The following code should be here and not in SetLockSpot2, -- but MouseMove springscroll (MMB scrolling, not smoothscroll) -- starts translating on all axes, rather than just x and z -- corrected, ls_x, ls_y, ls_z = CorrectTraceTargetToSmoothMesh(cs, ls_x, ls_y, ls_z) -- if corrected then ComputeLockSpotParams(cs) end local vecDist = (- cs.py) / cs.dy local ddx = (mxm * drx) + (mym * dfx) local ddz = (mxm * drz) + (mym * dfz) ls_x = ls_x + ddx ls_z = ls_z + ddz if not options.freemode.value then ls_x = min(ls_x, maxX-3) --limit camera movement, either to map area or (if options.zoomouttocenter.value is true) to a set distance from map center ls_x = max(ls_x, minX+3) --Do not replace with GetMapBoundedCoords or GetMapBoundedGroundHeight, those functions only (and should only) respect map area. ls_z = min(ls_z, maxZ-3) ls_z = max(ls_z, minZ+3) end ls_y = GetSmoothOrGroundHeight(ls_x, ls_z, true) local csnew = UpdateCam(cs) if csnew and options.tiltedzoom.value then csnew.rx = GetZoomTiltAngle(ls_x, ls_z, csnew) csnew = UpdateCam(csnew) end if csnew then if not options.freemode.value then csnew.py = min(csnew.py, maxDistY) end --Ensure camera never goes higher than maxY SetCenterBounds(csnew) --Should be done since cs.py changes, but stops camera movement southwards. TODO: Investigate this. -- spSetCameraState(csnew, smoothlevel) OverrideSetCameraStateInterpolate(csnew,smoothlevel) end end local function PeriodicWarning() local c_widgets, c_widgets_list = '', {} for name,data in pairs(widgetHandler.knownWidgets) do if data.active and ( name:find('SmoothScroll') or name:find('Hybrid Overhead') or name:find('Complete Control Camera') ) then c_widgets_list[#c_widgets_list+1] = name end end for i=1, #c_widgets_list do c_widgets = c_widgets .. c_widgets_list[i] .. ', ' end if c_widgets ~= '' then echo('<COFCam> *Periodic warning* Please disable other camera widgets: ' .. c_widgets) end end --==End camera control function^^ (functions that actually do camera control) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local missedMouseRelease = false function widget:Update(dt) local framePassed = math.ceil(dt/0.0333) --estimate how many gameframe would've passes based on difference in time?? if hideCursor then spSetMouseCursor('%none%') end local cs = spGetCameraState() --GetTargetCameraState() --//MISC fpsmode = cs.name == "fps" if init or ((cs.name ~= "free") and (cs.name ~= "ov") and not fpsmode) then -- spSendCommands("viewfree") cs = DetermineInitCameraState() init = false cs.tiltSpeed = 0 cs.scrollSpeed = 0 --cs.gndOffset = options.mingrounddist.value cs.gndOffset = options.freemode.value and 0 or 1 --this tell engine to block underground motion, ref: Spring\rts\Game\Camera\FreeController.cpp -- spSetCameraState(cs,0) OverrideSetCameraStateInterpolate(cs,0) end --//HANDLE TIMER FOR VARIOUS SECTION --timer to block tracking when using mouse if follow_timer > 0 then follow_timer = follow_timer - dt end --timer to block unit tracking trackcycle = trackcycle + framePassed if trackcycle >=6 then trackcycle = 0 --reset value to Zero (0) every 6th frame. Extra note: dt*trackcycle would be the estimated number of second elapsed since last reset. end --timer to block cursor tracking camcycle = camcycle + framePassed if camcycle >=12 then camcycle = 0 --reset value to Zero (0) every 12th frame. NOTE: a reset value a multiple of trackcycle's reset is needed to prevent conflict end --timer to block periodic warning cycle = cycle + framePassed if cycle >=32*15 then cycle = 0 --reset value to Zero (0) every 32*15th frame. end --//HANDLE TRACK UNIT --trackcycle = trackcycle%(6) + 1 --automatically reset "trackcycle" value to Zero (0) every 6th iteration. if (trackcycle == 0 and trackmode and not overview_mode and (follow_timer <= 0) and --disable tracking temporarily when middle mouse is pressed or when scroll is used for zoom not thirdperson_trackunit and not (rot.right or rot.left or rot.up or rot.down) and --cam rotation conflict with tracking, causing zoom-out bug. Rotation while tracking is handled in RotateCamera() but with less smoothing. (not rotate)) --update trackmode during non-rotating state (doing both will cause a zoomed-out bug) then local selUnits = spGetSelectedUnits() if selUnits and selUnits[1] then local vx,vy,vz = Spring.GetUnitVelocity(selUnits[1]) local x,y,z = spGetUnitPosition( selUnits[1] ) --MAINTENANCE NOTE: the following smooth value is obtained from trial-n-error. There's no formula to calculate and it could change depending on engine (currently Spring 91). --The following instruction explain how to get this smooth value: --1) reset Spring.SetCameraTarget to: (x+vx,y+vy,z+vz, 0.0333) --2) increase value A until camera motion is not jittery, then stop: (x+vx,y+vy,z+vz, 0.0333*A) --3) increase value B until unit center on screen, then stop: (x+vx*B,y+vy*B,z+vz*B, 0.0333*A) SetCameraTarget(x+vx*40,y+vy*40,z+vz*40, 0.0333*137) elseif (not options.persistenttrackmode.value) then --cancel trackmode when no more units is present in non-persistent trackmode. trackmode=false --exit trackmode Spring.Echo("COFC: Unit tracking OFF") end end --//HANDLE TRACK CURSOR --camcycle = camcycle%(12) + 1 --automatically reset "camcycle" value to Zero (0) every 12th iteration. if (camcycle == 0 and not trackmode and not overview_mode and (follow_timer <= 0) and --disable tracking temporarily when middle mouse is pressed or when scroll is used for zoom not thirdperson_trackunit and options.follow.value) --if follow selected player's cursor: then if WG.alliedCursorsPos then AutoZoomInOutToCursor() end end -- Periodic warning --cycle = cycle%(32*15) + framePassed --automatically reset "cycle" value to Zero (0) every 32*15th iteration. if cycle == 0 then PeriodicWarning() end cs = GetTargetCameraState() local use_lockspringscroll = lockspringscroll and not springscroll local a,c,m,s = spGetModKeyState() local fpsCompensationFactor = (60 * dt) --Normalize to 60fps --//HANDLE ROTATE CAMERA if (not thirdperson_trackunit and --block 3rd Person (rot.right or rot.left or rot.up or rot.down)) then cs = GetTargetCameraState() local speed = options.rotfactor.value * (s and 500 or 250) * fpsCompensationFactor if (rot.right or rot.left) and options.leftRightEdge.value == 'orbit' then SetLockSpot2(cs, vsx * 0.5, vsy * 0.5) end if rot.right then RotateCamera(vsx * 0.5, vsy * 0.5, speed, 0, true, ls_have) elseif rot.left then RotateCamera(vsx * 0.5, vsy * 0.5, -speed, 0, true, ls_have) end if (rot.up or rot.down) and options.topBottomEdge.value == 'orbit' then SetLockSpot2(cs, vsx * 0.5, vsy * 0.5) elseif options.topBottomEdge.value == 'rotate' then ls_have = false end if rot.up then RotateCamera(vsx * 0.5, vsy * 0.5, 0, speed, true, ls_have) elseif rot.down then RotateCamera(vsx * 0.5, vsy * 0.5, 0, -speed, true, ls_have) end ls_have = false end --//HANDLE MOVE CAMERA if (not thirdperson_trackunit and --block 3rd Person (smoothscroll or move.right or move.left or move.up or move.down or move2.right or move2.left or move2.up or move2.down or use_lockspringscroll)) then cs = GetTargetCameraState() local x, y, lmb, mmb, rmb = spGetMouseState() if (c) then return end local smoothlevel = 0 -- clear the velocities cs.vx = 0; cs.vy = 0; cs.vz = 0 cs.avx = 0; cs.avy = 0; cs.avz = 0 local mxm, mym = 0,0 local heightFactor = (cs.py/1000) if smoothscroll then --local speed = dt * options.speedFactor.value * heightFactor local speed = math.max( dt * options.speedFactor.value * heightFactor, 0.005 ) mxm = speed * (x - cx) mym = speed * (y - cy) elseif use_lockspringscroll then --local speed = options.speedFactor.value * heightFactor / 10 local speed = math.max( options.speedFactor.value * heightFactor / 10, 0.05 ) local dir = options.invertscroll.value and -1 or 1 mxm = speed * (x - mx) * dir mym = speed * (y - my) * dir spWarpMouse(cx, cy) else --edge screen scroll --local speed = options.speedFactor_k.value * (s and 3 or 1) * heightFactor local speed = math.max( options.speedFactor_k.value * (s and 3 or 1) * heightFactor * fpsCompensationFactor, 1 ) if move.right or move2.right then mxm = speed elseif move.left or move2.left then mxm = -speed end if move.up or move2.up then mym = speed elseif move.down or move2.down then mym = -speed end smoothlevel = options.smoothness.value if spDiffTimers(spGetTimer(),last_move)>1 then --if edge scroll is 'first time': unlock lockspot once ls_have = false end last_move = spGetTimer() end ScrollCam(cs, mxm, mym, smoothlevel) end mx, my = spGetMouseState() --//HANDLE MOUSE'S SCREEN-EDGE SCROLL/ROTATION if not (WG.IsGUIHidden and WG.IsGUIHidden()) then --not in mission or (in mission but) not GuiHidden() if options.leftRightEdge.value == 'pan' then move2.right = false --reset mouse move state move2.left = false if mx > vsx-2 then move2.right = true elseif mx < 2 then move2.left = true end elseif options.leftRightEdge.value == 'rotate' or options.leftRightEdge.value == 'orbit' then rot.right = false rot.left = false if mx > vsx-2 then rot.right = true elseif mx < 2 then rot.left = true end end if options.topBottomEdge.value == 'pan' then move2.up = false move2.down = false if my > vsy-2 then move2.up = true elseif my < 2 then move2.down = true end elseif options.topBottomEdge.value == 'rotate' or options.topBottomEdge.value == 'orbit' then rot.up = false rot.down = false if my > vsy-2 then rot.up = true elseif my < 2 then rot.down = true end end end --//HANDLE MOUSE/KEYBOARD'S 3RD-PERSON (TRACK UNIT) RETARGET if (thirdperson_trackunit and not overview_mode and --block 3rd person scroll when in overview mode (move.right or move.left or move.up or move.down or move2.right or move2.left or move2.up or move2.down or rot.right or rot.left or rot.up or rot.down)) --NOTE: engine exit 3rd-person trackmode if it detect edge-screen scroll, so we handle 3rd person trackmode scrolling here. then cs = GetTargetCameraState() if movekey and spDiffTimers(spGetTimer(),thirdPerson_transit)>=1 then --wait at least 1 second before 3rd Person to nearby unit, and only allow edge scroll for keyboard press ThirdPersonScrollCam(cs) --edge scroll to nearby unit else --not using movekey for 3rdPerson-edge-Scroll (ie:is using mouse, "move2" and "rot"): re-issue 3rd person local selUnits = spGetSelectedUnits() if selUnits and selUnits[1] then -- re-issue 3rd person for selected unit (we need to reissue this because in normal case mouse edge scroll will exit trackmode) spSendCommands('viewfps') spSendCommands('track') thirdperson_trackunit = selUnits[1] local x,y,z = spGetUnitPosition(selUnits[1]) if x and y and z then --unit position can be NIL if spectating with limited LOS cs.px,cs.py,cs.pz=x,y,z cs.py= cs.py+25 --move up 25-elmo incase FPS camera stuck to unit's feet instead of tracking it (aesthetic) -- spSetCameraState(cs,0) Spring.Echo("track retarget") OverrideSetCameraStateInterpolate(cs,0) end else --no unit selected: return to freeStyle camera spSendCommands('trackoff') spSendCommands('viewfree') thirdperson_trackunit = false end end end if missedMouseRelease and camcycle==0 then --Workaround/Fix for middle-mouse button release event not detected: --We request MouseRelease event for middle-mouse release in MousePress by returning "true", --but when 2 key is pressed at same time, the MouseRelease is called for the first key which is released (not necessarily middle-mouse button). --If that happen, we will loop here every half-second until the middle-mouse button is really released. local _,_, _, mmb = spGetMouseState() if (not mmb) then rotate = nil smoothscroll = false springscroll = false missedMouseRelease = false end end if not initialBoundsSet then initialBoundsSet = true if options.tiltedzoom.value then ResetCam() end end end function widget:GamePreload() if not initialBoundsSet then --Tilt zoom initial overhead view (Engine 91) initialBoundsSet = true if options.tiltedzoom.value then ResetCam() end end end function widget:MouseMove(x, y, dx, dy, button) if rotate then local smoothed if rotate_transit then --if "rotateAtCursor" flag is True, then this will run 'once' to smoothen camera motion if spDiffTimers(spGetTimer(),rotate_transit)<1 then --smooth camera for in-transit effect smoothed = true else rotate_transit = nil --cancel in-transit flag end end if abs(dx) > 0 or abs(dy) > 0 then RotateCamera(x, y, dx, dy, true, ls_have) end spWarpMouse(msx, msy) follow_timer = 0.6 --disable tracking for 1 second when middle mouse is pressed or when scroll is used for zoom elseif springscroll then if abs(dx) > 0 or abs(dy) > 0 then lockspringscroll = false end local dir = options.invertscroll.value and -1 or 1 local cs = GetTargetCameraState() local speed = options.speedFactor.value * cs.py/1000 / 10 local mxm = speed * dx * dir local mym = speed * dy * dir ScrollCam(cs, mxm, mym, 0) follow_timer = 0.6 --disable tracking for 1 second when middle mouse is pressed or when scroll is used for zoom end end function widget:MousePress(x, y, button) --called once when pressed, not repeated ls_have = false if (button == 2 and options.middleMouseButton.value == 'off') then return true end --overview_mode = false --if fpsmode then return end if lockspringscroll then lockspringscroll = false return true end -- Not Middle Click -- if (button ~= 2) then return false end follow_timer = 4 --disable tracking for 4 second when middle mouse is pressed or when scroll is used for zoom local a,ctrl,m,s = spGetModKeyState() spSendCommands('trackoff') spSendCommands('viewfree') if not (options.persistenttrackmode.value and (ctrl or a)) then --Note: wont escape trackmode if pressing Ctrl or Alt in persistent trackmode, else: always escape. if trackmode then Spring.Echo("COFC: Unit tracking OFF") end trackmode = false end thirdperson_trackunit = false -- Reset -- if a and ctrl then ResetCam() return true end -- Above Minimap -- if (spIsAboveMiniMap(x, y)) then return false end local cs = GetTargetCameraState() msx = x msy = y spSendCommands({'trackoff'}) rotate = false -- Rotate -- if a or options.middleMouseButton.value == 'rotate' then spWarpMouse(cx, cy) ls_have = false onTiltZoomTrack = false rotate = true return true end -- Rotate World -- if ctrl or options.middleMouseButton.value == 'orbit' then rotate_transit = nil onTiltZoomTrack = false if options.targetmouse.value then --if rotate world at mouse cursor: local onmap, gx, gy, gz = VirtTraceRay(x,y, cs) if gx and (options.freemode.value or onmap) then --Note: we don't block offmap position since VirtTraceRay() now work for offmap position. SetLockSpot2(cs,x,y) --set lockspot at cursor position --//update "ls_dist" with value from mid-screen's LockSpot because rotation is centered on mid-screen and not at cursor (cursor's "ls_dist" has bigger value than midscreen "ls_dist")//-- local _,cgx,cgy,cgz = VirtTraceRay(cx,cy,cs) --get ground position traced from mid of screen local dx,dy,dz = cgx-cs.px, cgy-cs.py, cgz-cs.pz ls_dist = sqrt(dx*dx + dy*dy + dz*dz) --distance to ground SetCameraTarget(gx,gy,gz,1) --transit to cursor position rotate_transit = spGetTimer() --trigger smooth in-transit effect in widget:MouseMove() end else SetLockSpot2(cs) --lockspot at center of screen end spWarpMouse(cx, cy) --move cursor to center of screen rotate = true msx = cx msy = cy return true end -- Scrolling -- if options.smoothscroll.value then spWarpMouse(cx, cy) smoothscroll = true else springscroll = true lockspringscroll = not lockspringscroll end return true end function widget:MouseRelease(x, y, button) if (button == 2) then rotate = nil smoothscroll = false springscroll = false return -1 else missedMouseRelease = true end end function widget:MouseWheel(wheelUp, value) if fpsmode then return end local alt,ctrl,m,shift = spGetModKeyState() if ctrl then return Tilt(shift, wheelUp and 1 or -1) elseif alt then if overview_mode then --cancel overview_mode if Overview_mode + descending local zoomin = not wheelUp if options.invertalt.value then zoomin = not zoomin end if zoomin then overview_mode = false else return; end-- skip wheel if Overview_mode + ascending end return Altitude(wheelUp, shift) end if overview_mode then --cancel overview_mode if Overview_mode + ZOOM-in local zoomin = not wheelUp if options.invertzoom.value then zoomin = not zoomin end if zoomin then overview_mode = false else return; end --skip wheel if Overview_mode + ZOOM-out end follow_timer = 0.6 --disable tracking for 1 second when middle mouse is pressed or when scroll is used for zoom return Zoom(not wheelUp, shift) end function widget:KeyPress(key, modifier, isRepeat) local intercept = GroupRecallFix(key, modifier, isRepeat) if intercept then return true end --ls_have = false tilting = false if thirdperson_trackunit then --move key for edge Scroll in 3rd person trackmode if keys[key] and not (modifier.ctrl or modifier.alt) then movekey = true move[keys[key]] = true end end if fpsmode then return end if keys[key] then if modifier.ctrl or modifier.alt then local cs = GetTargetCameraState() SetLockSpot2(cs) if not ls_have then return end local speed = (modifier.shift and 30 or 10) if key == key_code.right then RotateCamera(vsx * 0.5, vsy * 0.5, speed, 0, true, not modifier.alt) elseif key == key_code.left then RotateCamera(vsx * 0.5, vsy * 0.5, -speed, 0, true, not modifier.alt) elseif key == key_code.down then onTiltZoomTrack = false; RotateCamera(vsx * 0.5, vsy * 0.5, 0, -speed, true, not modifier.alt) elseif key == key_code.up then onTiltZoomTrack = false; RotateCamera(vsx * 0.5, vsy * 0.5, 0, speed, true, not modifier.alt) end return else movekey = true move[keys[key]] = true end elseif key == key_code.pageup then if modifier.ctrl then Tilt(modifier.shift, 1) return elseif modifier.alt then Altitude(true, modifier.shift) return else Zoom(true, modifier.shift, true) return end elseif key == key_code.pagedown then if modifier.ctrl then Tilt(modifier.shift, -1) return elseif modifier.alt then Altitude(false, modifier.shift) return else Zoom(false, modifier.shift, true) return end end tilting = false end function widget:KeyRelease(key) if keys[key] then move[keys[key]] = nil end if not (move.up or move.down or move.left or move.right) then movekey = nil end end local function DrawLine(x0, y0, c0, x1, y1, c1) glColor(c0); glVertex(x0, y0) glColor(c1); glVertex(x1, y1) end local function DrawPoint(x, y, c, s) --FIXME reenable later - ATIBUG glPointSize(s) glColor(c) glBeginEnd(GL_POINTS, glVertex, x, y) end function widget:DrawScreenEffects(vsx, vsy) --placed here so that its always called even when GUI is hidden Interpolate() end local screenFrame = 0 function widget:DrawScreen() SetSkyBufferProportion() --Reset Camera for tiltzoom at game start (Engine 92+) if screenFrame == 3 then --detect frame no.2 if options.tiltedzoom.value then ResetCam() end initialBoundsSet = true end screenFrame = screenFrame+1 hideCursor = false if not cx then return end local x, y if smoothscroll then x, y = spGetMouseState() glLineWidth(2) glBeginEnd(GL_LINES, DrawLine, x, y, green, cx, cy, red) glLineWidth(1) DrawPoint(cx, cy, black, 14) DrawPoint(cx, cy, white, 11) DrawPoint(cx, cy, black, 8) DrawPoint(cx, cy, red, 5) DrawPoint(x, y, { 0, 1, 0 }, 5) end local filefound if smoothscroll then --or (rotate and ls_have) then filefound = glTexture(LUAUI_DIRNAME .. 'Images/ccc/arrows.png') hideCursor = true --elseif rotate or lockspringscroll or springscroll then --filefound = glTexture(LUAUI_DIRNAME .. 'Images/ccc/arrows.png') end if filefound then if smoothscroll then glColor(0,1,0,1) elseif (rotate and ls_have) then glColor(1,0.6,0,1) elseif rotate then glColor(1,1,0,1) elseif lockspringscroll then glColor(1,0,0,1) elseif springscroll then if options.invertscroll.value then glColor(1,0,1,1) else glColor(0,1,1,1) end end glAlphaTest(GL_GREATER, 0) -- if not (springscroll and not lockspringscroll) then -- hideCursor = true -- end if smoothscroll then local icon_size2 = icon_size glTexRect(x-icon_size, y-icon_size2, x+icon_size, y+icon_size2) else glTexRect(cx-icon_size, cy-icon_size, cx+icon_size, cy+icon_size) end glTexture(false) glColor(1,1,1,1) glAlphaTest(false) end end function widget:Initialize() helpText = explode( '\n', options.helpwindow.value ) cx = vsx * 0.5 cy = vsy * 0.5 spSendCommands( 'unbindaction toggleoverview' ) spSendCommands( 'unbindaction trackmode' ) spSendCommands( 'unbindaction track' ) spSendCommands( 'unbindaction mousestate' ) --//disable screen-panning-mode toggled by 'backspace' key --Note: the following is for compatibility with epicmenu.lua's zkkey framework if WG.crude then if WG.crude.GetHotkey then epicmenuHkeyComp[1] = WG.crude.GetHotkey("toggleoverview") --get hotkey epicmenuHkeyComp[2] = WG.crude.GetHotkey("trackmode") epicmenuHkeyComp[3] = WG.crude.GetHotkey("track") epicmenuHkeyComp[4] = WG.crude.GetHotkey("mousestate") end if WG.crude.SetHotkey then WG.crude.SetHotkey("toggleoverview",nil) --unbind hotkey WG.crude.SetHotkey("trackmode",nil) WG.crude.SetHotkey("track",nil) WG.crude.SetHotkey("mousestate",nil) end end WG.COFC_SetCameraTarget = SetCameraTarget --for external use, so that minimap click works with COFC --for external use, so that minimap can scale when zoomed out WG.COFC_SkyBufferProportion = 0 spSendCommands("luaui disablewidget SmoothScroll") spSendCommands("luaui disablewidget SmoothCam") if WG.SetWidgetOption then WG.SetWidgetOption("Settings/Camera","Settings/Camera","Camera Type","COFC") --tell epicmenu.lua that we select COFC as our default camera (since we enabled it!) end end function widget:Shutdown() spSendCommands{"viewta"} spSendCommands( 'bind any+tab toggleoverview' ) spSendCommands( 'bind any+t track' ) spSendCommands( 'bind ctrl+t trackmode' ) spSendCommands( 'bind backspace mousestate' ) --//re-enable screen-panning-mode toggled by 'backspace' key --Note: the following is for compatibility with epicmenu.lua's zkkey framework if WG.crude and WG.crude.SetHotkey then WG.crude.SetHotkey("toggleoverview",epicmenuHkeyComp[1]) --rebind hotkey WG.crude.SetHotkey("trackmode",epicmenuHkeyComp[2]) WG.crude.SetHotkey("track",epicmenuHkeyComp[3]) WG.crude.SetHotkey("mousestate",epicmenuHkeyComp[4]) end WG.COFC_SetCameraTarget = nil WG.COFC_SkyBufferProportion = nil end function widget:TextCommand(command) if command == "cofc help" then for i, text in ipairs(helpText) do echo('<COFCam['.. i ..']> '.. text) end return true elseif command == "cofc reset" then ResetCam() return true end return false end function widget:UnitDestroyed(unitID) --transfer 3rd person trackmode to other unit or exit to freeStyle view if thirdperson_trackunit and thirdperson_trackunit == unitID then --return user to normal view if tracked unit is destroyed local isSpec = Spring.GetSpectatingState() local attackerID= Spring.GetUnitLastAttacker(unitID) if not isSpec then spSendCommands('trackoff') spSendCommands('viewfree') thirdperson_trackunit = false return end if Spring.ValidUnitID(attackerID) then --shift tracking toward attacker if it is alive (cinematic). Spring.SelectUnitArray({attackerID}) end local selUnits = spGetSelectedUnits()--test select unit if not (selUnits and selUnits[1]) then --if can't select, then, check any unit in vicinity local x,_,z = spGetUnitPosition(unitID) local units = Spring.GetUnitsInCylinder(x,z, 100) if units and units[1] then Spring.SelectUnitArray({units[1]}) end end selUnits = spGetSelectedUnits()--test select unit if selUnits and selUnits[1] and (not Spring.GetUnitIsDead(selUnits[1]) ) then --if we can select unit, and those unit is not dead in this frame, then: track them spSendCommands('viewfps') spSendCommands('track') thirdperson_trackunit = selUnits[1] local cs = GetTargetCameraState() cs.px,cs.py,cs.pz=spGetUnitPosition(selUnits[1]) cs.py= cs.py+25 --move up 25-elmo incase FPS camera stuck to unit's feet instead of tracking it (aesthetic) -- spSetCameraState(cs,0) OverrideSetCameraStateInterpolate(cs,0) else spSendCommands('trackoff') spSendCommands('viewfree') thirdperson_trackunit = false end end end -------------------------------------------------------------------------------- --Group Recall Fix--- (by msafwan, 9 Jan 2013) --Remake Spring's group recall to trigger ZK's custom Spring.SetCameraTarget (which work for freestyle camera mode). -------------------------------------------------------------------------------- local spGetUnitGroup = Spring.GetUnitGroup local spGetGroupList = Spring.GetGroupList --include("keysym.h.lua") local previousGroup =99 local currentIteration = 1 local currentIterations = {} local previousKey = 99 local previousTime = spGetTimer() local groupNumber = { [KEYSYMS.N_1] = 1, [KEYSYMS.N_2] = 2, [KEYSYMS.N_3] = 3, [KEYSYMS.N_4] = 4, [KEYSYMS.N_5] = 5, [KEYSYMS.N_6] = 6, [KEYSYMS.N_7] = 7, [KEYSYMS.N_8] = 8, [KEYSYMS.N_9] = 9, } function GroupRecallFix(key, modifier, isRepeat) if ( not modifier.ctrl and not modifier.alt and not modifier.meta) then --check key for group. Reference: unit_auto_group.lua by Licho local group if (key ~= nil and groupNumber[key]) then group = groupNumber[key] end if (group ~= nil) then local selectedUnit = spGetSelectedUnits() local groupCount = spGetGroupList() --get list of group with number of units in them if groupCount[group] ~= #selectedUnit then previousKey = key previousTime = spGetTimer() return false end for i=1,#selectedUnit do local unitGroup = spGetUnitGroup(selectedUnit[i]) if unitGroup~=group then previousKey = key previousTime = spGetTimer() return false end end if previousKey == key and (spDiffTimers(spGetTimer(),previousTime) > options.groupSelectionTapTimeout.value) then previousKey = key previousTime = spGetTimer() return true --but don't do anything. Only move camera after a double-tap (or more). end previousKey = key previousTime = spGetTimer() if options.enableCycleView.value then if (currentIterations[group]) then currentIteration = currentIterations[group] else currentIteration = 1 end local slctUnitUnordered = {} for i=1 , #selectedUnit do local unitID = selectedUnit[i] local x,y,z = spGetUnitPosition(unitID) slctUnitUnordered[unitID] = {x,y,z} end selectedUnit = nil local cluster, lonely = WG.OPTICS_cluster(slctUnitUnordered, 600,2, Spring.GetMyTeamID(),300) --//find clusters with atleast 2 unit per cluster and with at least within 300-elmo from each other with 600-elmo detection range if previousGroup == group then currentIteration = currentIteration +1 if currentIteration > (#cluster + #lonely) then currentIteration = 1 end -- else -- currentIteration = 1 end currentIterations[group] = currentIteration if currentIteration <= #cluster then local sumX, sumY,sumZ, unitCount,meanX, meanY, meanZ = 0,0 ,0 ,0 ,0,0,0 for unitIndex=1, #cluster[currentIteration] do local unitID = cluster[currentIteration][unitIndex] local x,y,z= slctUnitUnordered[unitID][1],slctUnitUnordered[unitID][2],slctUnitUnordered[unitID][3] --// get stored unit position sumX= sumX+x sumY = sumY+y sumZ = sumZ+z unitCount=unitCount+1 end meanX = sumX/unitCount --//calculate center of cluster meanY = sumY/unitCount meanZ = sumZ/unitCount SetCameraTarget(meanX, meanY, meanZ,0.5,true) else local unitID = lonely[currentIteration-#cluster] local slctUnit = slctUnitUnordered[unitID] if slctUnit ~= nil then --nil check. There seems to be a race condition or something which causes this unit to be nil sometimes local x,y,z= slctUnit[1],slctUnit[2],slctUnit[3] --// get stored unit position SetCameraTarget(x,y,z,0.5,true) end end cluster=nil slctUnitUnordered = nil else --conventional method: local sumX, sumY,sumZ, unitCount,meanX, meanY, meanZ = 0,0 ,0 ,0 ,0,0,0 for i=1, #selectedUnit do local unitID = selectedUnit[i] local x,y,z= spGetUnitPosition(unitID) sumX= sumX+x sumY = sumY+y sumZ = sumZ+z unitCount=unitCount+1 end meanX = sumX/unitCount --//calculate center meanY = sumY/unitCount meanZ = sumZ/unitCount SetCameraTarget(meanX, meanY, meanZ,0.5,true) --is overriden by Spring.SetCameraTarget() at cache.lua. end previousGroup= group return true end end end
gpl-2.0
ViolyS/RayUI_VS
Interface/AddOns/Skada/InlineDisplay.lua
1
21751
local L = LibStub("AceLocale-3.0"):GetLocale("Skada", false) local Skada = Skada local name = L["Inline bar display"] local mod = Skada:NewModule(name) local mybars = {} local barlibrary = { bars = {}, nextuuid = 1 } local leftmargin = 40 local ttactive = false local libwindow = LibStub("LibWindow-1.1") local media = LibStub("LibSharedMedia-3.0") mod.name = name mod.description = L["Inline display is a horizontal window style."] Skada:AddDisplaySystem("inline", mod) function serial(val, name, skipnewlines, depth) skipnewlines = skipnewlines or false depth = depth or 0 local tmp = string.rep("·", depth) if name then tmp = tmp .. name .. " = " end if type(val) == "table" then tmp = tmp .. "{" .. (not skipnewlines and "\n" or "") for k, v in pairs(val) do tmp = tmp .. serial(v, k, skipnewlines, depth + 1) .. "," .. (not skipnewlines and "\n" or "") end tmp = tmp .. string.rep(" ", depth) .. "}" elseif type(val) == "number" then tmp = tmp .. tostring(val) elseif type(val) == "string" then tmp = tmp .. string.format("%q", val) elseif type(val) == "boolean" then tmp = tmp .. (val and "true" or "false") else tmp = tmp .. "\"[inserializeable datatype:" .. type(val) .. "]\"" end return tmp end function mod:OnInitialize() end local function BarLeave(bar) local win, id, label = bar.win, bar.id, bar.text if ttactive then GameTooltip:Hide() ttactive = false end end local function showmode(win, id, label, mode) -- Add current mode to window traversal history. if win.selectedmode then tinsert(win.history, win.selectedmode) end -- Call the Enter function on the mode. if mode.Enter then mode:Enter(win, id, label) end -- Display mode. win:DisplayMode(mode) end local function BarClick(win, bar, button) local id, label = bar.valueid, bar.valuetext local click1 = win.metadata.click1 local click2 = win.metadata.click2 local click3 = win.metadata.click3 if button == "RightButton" and IsShiftKeyDown() then Skada:OpenMenu(win) elseif win.metadata.click then win.metadata.click(win, id, label, button) elseif button == "RightButton" then win:RightClick() elseif click2 and IsShiftKeyDown() then showmode(win, id, label, click2) elseif click3 and IsControlKeyDown() then showmode(win, id, label, click3) elseif click1 then showmode(win, id, label, click1) end end function mod:Create(window, isnew) if not window.frame then window.frame = CreateFrame("Frame", window.db.name.."InlineFrame", UIParent) window.frame.win = window window.frame:SetFrameLevel(5) if window.db.height==15 then window.db.height = 23 end--TODO: Fix dirty hack window.frame:SetHeight(window.db.height) window.frame:SetWidth(window.db.width or GetScreenWidth()) window.frame:ClearAllPoints() window.frame:SetPoint("BOTTOM", -1) window.frame:SetPoint("LEFT", -1) if window.db.background.color.a==51/255 then window.db.background.color = {r=255, b=250/255, g=250/255, a=1 } end end window.frame:EnableMouse() window.frame:SetScript("OnMouseDown", function(frame, button) if button == "RightButton" then window:RightClick() end end) -- Register with LibWindow-1.1. libwindow.RegisterConfig(window.frame, window.db) -- Restore window position. if isnew then libwindow.SavePosition(window.frame) else libwindow.RestorePosition(window.frame) end window.frame:EnableMouse(true) window.frame:SetMovable(true) window.frame:RegisterForDrag("LeftButton") window.frame:SetScript("OnDragStart", function(frame) if not window.db.barslocked then GameTooltip:Hide() frame.isDragging = true frame:StartMoving() end end) window.frame:SetScript("OnDragStop", function(frame) frame:StopMovingOrSizing() frame.isDragging = false libwindow.SavePosition(frame) end) local titlebg = CreateFrame("Frame", "InlineTitleBackground", window.frame) local title = window.frame:CreateFontString("frameTitle", 6) title:SetTextColor(self:GetFontColor(window.db)) --window.frame.fstitle:SetTextColor(255,255,255,1) title:SetFont(self:GetFont(window.db)) title:SetText(window.metadata.title or "Skada") title:SetWordWrap(false) title:SetJustifyH("LEFT") title:SetPoint("LEFT", leftmargin, -1) title:SetPoint("CENTER", 0, 0) title:SetHeight(window.db.height or 23) window.frame.fstitle = title window.frame.titlebg = titlebg titlebg:SetAllPoints(title) titlebg:EnableMouse(true) titlebg:SetScript("OnMouseDown", function(frame, button) if button == "RightButton" then Skada:SegmentMenu(window) end if button == "LeftButton" then Skada:ModeMenu(window) end end) local skadamenubuttonbackdrop = { bgFile = "Interface\\Buttons\\UI-OptionsButton", edgeFile = "Interface\\Buttons\\UI-OptionsButton", bgFile = nil, edgeFile = nil, tile = true, tileSize = 12, edgeSize = 0, insets = { left = 0, right = 0, top = 0, bottom = 0 } } local menu = CreateFrame("Button", "InlineFrameMenuButton", window.frame) menu:ClearAllPoints() menu:SetWidth(12) menu:SetHeight(12) menu:SetNormalTexture("Interface\\Buttons\\UI-OptionsButton") menu:SetHighlightTexture("Interface\\Buttons\\UI-OptionsButton", 1.0) menu:SetAlpha(0.5) menu:RegisterForClicks("LeftButtonUp", "RightButtonUp") menu:SetBackdropColor(window.db.title.textcolor.r,window.db.title.textcolor.g,window.db.title.textcolor.b,window.db.title.textcolor.a) menu:SetPoint("BOTTOMLEFT", window.frame, "BOTTOMLEFT", 6, window.db.height/2-8) menu:SetFrameLevel(9) menu:SetPoint("CENTER") menu:SetBackdrop(skadamenubuttonbackdrop) menu:SetScript("OnClick", function() Skada:OpenMenu(window) end) window.frame.menu = menu window.frame.skadamenubutton = title window.frame.barstartx = leftmargin + window.frame.fstitle:GetStringWidth() window.frame.win = window window.frame:EnableMouse(true) --create 20 barframes local temp = 25 repeat local bar = barlibrary:CreateBar(nil, window) barlibrary.bars[temp] = bar temp = temp - 1 until(temp < 1) self:Update(window) end function mod:Destroy(win) win.frame:Hide() win.frame = nil end function mod:Wipe(win) end function mod:SetTitle(win, title) win.frame.fstitle:SetText(title) win.frame.barstartx = leftmargin + win.frame.fstitle:GetStringWidth() + 20 end function barlibrary:CreateBar(uuid, win) local bar = {} bar.uuid = uuid or self.nextuuid bar.inuse = false bar.value = 0 bar.win = win bar.bg = CreateFrame("Frame", "bg"..bar.uuid, win.frame) bar.label = bar.bg:CreateFontString("label"..bar.uuid) bar.label:SetFont(mod:GetFont(win.db)) bar.label:SetTextColor(mod:GetFontColor(win.db)) bar.label:SetJustifyH("LEFT") bar.label:SetJustifyV("MIDDLE") bar.bg:EnableMouse(true) bar.bg:SetScript("OnMouseDown", function(frame, button) BarClick(win, bar, button) end) bar.bg:SetScript("OnEnter", function(frame, button) ttactive = true Skada:SetTooltipPosition(GameTooltip, win.frame) Skada:ShowTooltip(win, bar.valueid, bar.valuetext) end) bar.bg:SetScript("OnLeave", function(frame, button) if ttactive then GameTooltip:Hide() ttactive = false end end) if uuid then self.nextuuid = self.nextuuid + 1 end return bar end function barlibrary:Deposit (_bar) --strip the bar of variables _bar.inuse = false _bar.bg:Hide() _bar.value = 0 _bar.label:Hide() --place it at the front of the queue table.insert(barlibrary.bars, 1, _bar) --print("Depositing bar.uuid", _bar.uuid) end function barlibrary:Withdraw (win)--TODO: also pass parent and assign parent local db = win.db if #barlibrary.bars < 2 then --if barlibrary is empty, create a new bar to replace this bar local replacement = {} local uuid = 1 if #barlibrary.bars==0 then --No data uuid = 1 elseif #barlibrary.bars < 2 then uuid = barlibrary.bars[#barlibrary.bars].uuid + 1 else uuid = 1 print("|c0033ff99SkadaInline|r: THIS SHOULD NEVER HAPPEN") end replacement = self:CreateBar(uuid, win) --add the replacement bar to the end of the bar library table.insert(barlibrary.bars, replacement) end --mark the bar you will give away as in use & give it a barid barlibrary.bars[1].inuse = false barlibrary.bars[1].value = 0 barlibrary.bars[1].label:SetJustifyH("LEFT") --barlibrary.bars[1].label:SetJustifyV("CENTER") mod:ApplySettings(win) return table.remove(barlibrary.bars, 1) end function mod:RecycleBar(_bar) _bar.value = 0 --hide stuff _bar.label:Hide() _bar.bg:Hide() barlibrary:Deposit(_bar) end function mod:GetBar(win) return barlibrary:Withdraw(win) end function mod:UpdateBar(bar, bardata, db) local label = bardata.label if db.isusingclasscolors then if bardata.class then label = "|c" label = label..RAID_CLASS_COLORS[bardata.class].colorStr label = label..bardata.label label = label.."|r" end else label = bardata.label end if bardata.valuetext then if db.isonnewline and db.barfontsize*2 < db.height then label = label.."\n" else label = label.." - " end label = label..bardata.valuetext end bar.label:SetFont(mod:GetFont(db)) bar.label:SetText(label) bar.label:SetTextColor(mod:GetFontColor(db)) bar.value = bardata.value bar.class = bardata.class bar.valueid = bardata.id bar.valuetext = bardata.label return bar end function mod:Update(win) wd = win.dataset --purge nil values from dataset for i=#win.dataset, 1, -1 do if win.dataset[i].label==nil then table.remove(win.dataset, i) end end --TODO: Only if the number of bars changes --delete any current bars local i = #mybars while i > 0 do mod:RecycleBar(table.remove(mybars, i)) i = i - 1 end for k,bardata in pairs(win.dataset) do if bardata.id then --Update a fresh bar local _bar = mod:GetBar(win) table.insert(mybars, mod:UpdateBar(_bar, bardata, win.db)) end end --sort bars table.sort(mybars, function (bar1, bar2) if not bar1 or bar1.value==nil then return false elseif not bar2 or bar2.value==nil then return true else return bar1.value > bar2.value end end) -- TODO: fixed bars local yoffset = (win.db.height - win.db.barfontsize) / 2 local left = win.frame.barstartx + 40 for key, bar in pairs(mybars) do --set bar positions --TODO --bar.texture:SetTexture(255, 0, 0, 1.00) bar.bg:SetFrameLevel(9) bar.bg:SetHeight(win.db.height) bar.bg:SetPoint("BOTTOMLEFT", win.frame, "BOTTOMLEFT", left, 0) bar.label:SetHeight(win.db.height) bar.label:SetPoint("BOTTOMLEFT", win.frame, "BOTTOMLEFT", left, 0) bar.bg:SetWidth(bar.label:GetStringWidth()) --increment left value if win.db.fixedbarwidth then left = left + win.db.barwidth else left = left + bar.label:GetStringWidth() left = left + 15 end --show bar if (left + win.frame:GetLeft()) < win.frame:GetRight() then bar.bg:Show() bar.label:Show() else bar.bg:Hide() bar.label:Hide() end end end function mod:Show(win) win.frame:Show() end function mod:Hide(win) win.frame:Hide() end function mod:IsShown(win) return win.frame:IsShown() end function mod:OnMouseWheel(win, frame, direction) end function mod:CreateBar(win, name, label, maxValue, icon, o) --print("mod:CreateBar():TODO") local bar = {} bar.win = win return bar end function mod:GetFont(db) if db.isusingelvuiskin and ElvUI then if ElvUI then return ElvUI[1]["media"].normFont, db.barfontsize, nil else return nil end else return media:Fetch('font', db.barfont), db.barfontsize, db.barfontflags end end function mod:GetFontColor(db) if db.isusingelvuiskin and ElvUI then return 255,255,255,1 else return db.title.textcolor.r,db.title.textcolor.g,db.title.textcolor.b,db.title.textcolor.a end end function mod:ApplySettings(win) local f = win.frame local p = win.db -- --bars -- f:SetHeight(p.height) f:SetWidth(win.db.width or GetScreenWidth()) f.fstitle:SetTextColor(self:GetFontColor(p)) f.fstitle:SetFont(self:GetFont(p)) for k,bar in pairs(mybars) do --bar.label:SetFont(p.barfont,p.barfontsize,p.barfontflags ) bar.label:SetFont(self:GetFont(p)) bar.label:SetTextColor(self:GetFontColor(p)) bar.bg:EnableMouse(not p.clickthrough) end f.menu:SetPoint("BOTTOMLEFT", f, "BOTTOMLEFT", 6, win.db.height/2-8) f:EnableMouse(not p.clickthrough) f:SetScale(p.scale) -- --ElvUI -- if p.isusingelvuiskin and ElvUI then --bars f:SetHeight(p.height) f.fstitle:SetTextColor(255,255,255,1) --local _r, _g, _b = unpack(ElvUI[1]["media"].rgbvaluecolor) f.fstitle:SetFont(ElvUI[1]["media"].normFont, p.barfontsize, nil) for k,bar in pairs(mybars) do bar.label:SetFont(ElvUI[1]["media"].normFont, p.barfontsize, nil) bar.label:SetTextColor(255,255,255,1) end --background local fbackdrop = {} local borderR,borderG,borderB = unpack(ElvUI[1]["media"].bordercolor) local backdropR, backdropG, backdropB = unpack(ElvUI[1]["media"].backdropcolor) local backdropA = 0 if p.issolidbackdrop then backdropA = 1.0 else backdropA = 0.8 end local resolution = ({GetScreenResolutions()})[GetCurrentResolution()] local mult = 768/string.match(resolution, "%d+x(%d+)")/(max(0.64, min(1.15, 768/GetScreenHeight() or UIParent:GetScale()))) fbackdrop.bgFile = ElvUI[1]["media"].blankTex fbackdrop.edgeFile = ElvUI[1]["media"].blankTex fbackdrop.tile = false fbackdrop.tileSize = 0 fbackdrop.edgeSize = mult fbackdrop.insets = { left = 0, right = 0, top = 0, bottom = 0 } f:SetBackdrop(fbackdrop) f:SetBackdropColor(backdropR, backdropG, backdropB, backdropA) f:SetBackdropBorderColor(borderR, borderG, borderB, 1.0) else -- --background -- local fbackdrop = {} fbackdrop.bgFile = media:Fetch("background", p.background.texture) fbackdrop.tile = p.background.tile fbackdrop.tileSize = p.background.tilesize f:SetBackdrop(fbackdrop) f:SetBackdropColor(p.background.color.r,p.background.color.g,p.background.color.b,p.background.color.a) f:SetFrameStrata(p.strata) Skada:ApplyBorder(f, p.background.bordertexture, p.background.bordercolor, p.background.borderthickness) end end function mod:AddDisplayOptions(win, options) local db = win.db options.baroptions = { type = "group", name = "Text", order = 3, args = { isonnewline = { type = 'toggle', name = "Put values on new line.", desc = "New line:\nExac\n30.71M (102.1K)\n\nDivider:\nExac - 30.71M (102.7K)", get = function() return db.isonnewline end, set = function(win,key) db.isonnewline = key Skada:ApplySettings() end, order=0.0, }, isusingclasscolors = { type = 'toggle', name = "Use class colors", desc = "Class colors:\n|cFFF58CBAExac|r - 30.71M (102.7K)\nWithout:\nExac - 30.71M (102.7K)", get = function() return db.isusingclasscolors end, set = function(win,key) db.isusingclasscolors = key Skada:ApplySettings() end, order=0.05, }, barwidth = { type = 'range', name = "Width", desc = "Width of bars. This only applies if the 'Fixed bar width' option is used.", min=100, max=300, step=1.0, get = function() return db.barwidth end, set = function(win,key) db.barwidth = key Skada:ApplySettings() end, order=2, }, color = { type="color", name="Font Color", desc="Font Color. \nClick 'class color' to begin.", hasAlpha=true, get=function() local c = db.title.textcolor return c.r, c.g, c.b, c.a end, set=function(win, r, g, b, a) db.title.textcolor = {["r"] = r, ["g"] = g, ["b"] = b, ["a"] = a or 1.0 } Skada:ApplySettings() end, order=3.1, }, barfont = { type = 'select', dialogControl = 'LSM30_Font', name = L["Bar font"], desc = L["The font used by all bars."], values = AceGUIWidgetLSMlists.font, get = function() return db.barfont end, set = function(win,key) db.barfont = key Skada:ApplySettings() end, order=1, }, barfontsize = { type="range", name=L["Bar font size"], desc=L["The font size of all bars."], min=7, max=40, step=1, get=function() return db.barfontsize end, set=function(win, size) db.barfontsize = size Skada:ApplySettings() end, order=2, }, barfontflags = { type = 'select', name = L["Font flags"], desc = L["Sets the font flags."], values = {[""] = L["None"], ["OUTLINE"] = L["Outline"], ["THICKOUTLINE"] = L["Thick outline"], ["MONOCHROME"] = L["Monochrome"], ["OUTLINEMONOCHROME"] = L["Outlined monochrome"]}, get = function() return db.barfontflags end, set = function(win,key) db.barfontflags = key Skada:ApplySettings() end, order=3, }, clickthrough = { type="toggle", name=L["Clickthrough"], desc=L["Disables mouse clicks on bars."], order=20, get=function() return db.clickthrough end, set=function() db.clickthrough = not db.clickthrough Skada:ApplySettings() end, }, fixedbarwidth = { type="toggle", name=L["Fixed bar width"], desc=L["If checked, bar width is fixed. Otherwise, bar width depends on the text width."], order=21, get=function() return db.fixedbarwidth end, set=function() db.fixedbarwidth = not db.fixedbarwidth Skada:ApplySettings() end, }, } } options.elvuioptions = { type = "group", name = "ElvUI", order = 4, args = { isusingelvuiskin = { type = 'toggle', name = "Use ElvUI skin if avaliable.", desc = "Check this to use ElvUI skin instead. \nDefault: checked", get = function() return db.isusingelvuiskin end, set = function(win,key) db.isusingelvuiskin = key Skada:ApplySettings() end, order=0.1, }, issolidbackdrop = { type = 'toggle', name = "Use solid background.", desc = "Un-check this for an opaque background.", get = function() return db.issolidbackdrop end, set = function(win,key) db.issolidbackdrop = key Skada:ApplySettings() end, order=1.0, }, }, } options.frameoptions = Skada:FrameSettings(db, true) end
mit
rlcevg/Zero-K
units/destroyer.lua
4
6504
unitDef = { unitname = [[destroyer]], name = [[Daimyo]], description = [[Destroyer (Riot/Antisub)]], acceleration = 0.0417, activateWhenBuilt = true, brakeRate = 0.142, buildAngle = 16384, buildCostEnergy = 700, buildCostMetal = 700, builder = false, buildPic = [[destroyer.png]], buildTime = 700, canAttack = true, canGuard = true, canMove = true, canPatrol = true, category = [[SHIP]], collisionVolumeOffsets = [[0 0 3]], collisionVolumeScales = [[32 46 102]], collisionVolumeTest = 1, collisionVolumeType = [[box]], corpse = [[DEAD]], customParams = { description_fr = [[Destroyer]], description_pl = [[Niszczyciel]], description_de = [[Zerstörer]], helptext = [[The Daimyo class destroyer packs a wallop with its main gun, a powerful riot cannon. It also features missiles that can hit submarines and surface targets alike. The Daimyo is best attacked from afar, using surface ships or hovercraft with long-range weapons.]], helptext_pl = [[Glowna bronia Daimyo jest mocne dzialo; jest takze wyposazony w rakiety, ktore moga zanurzyc sie i uderzac w cele podwodne. Walczac przeciwko Daimyo, najlepiej atakowac z bezpiecznej odleglosci.]], extradrawrange = 420, }, explodeAs = [[BIG_UNITEX]], floater = true, footprintX = 4, footprintZ = 4, iconType = [[destroyer]], idleAutoHeal = 5, idleTime = 1800, mass = 320, maxDamage = 3300, maxVelocity = 2.9, minCloakDistance = 75, minWaterDepth = 10, movementClass = [[BOAT4]], noAutoFire = false, noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE]], objectName = [[destroyer.s3o]], script = [[destroyer.lua]], seismicSignature = 4, selfDestructAs = [[BIG_UNITEX]], side = [[ARM]], sightDistance = 500, sfxtypes = { explosiongenerators = { [[custom:LARGE_MUZZLE_FLASH_FX]], [[custom:PULVMUZZLE]], }, }, smoothAnim = true, sonarDistance = 700, turninplace = 0, turnRate = 311, waterline = 0, workerTime = 0, weapons = { { def = [[PLASMA]], badTargetCategory = [[GUNSHIP]], onlyTargetCategory = [[SWIM LAND SHIP SINK TURRET FLOAT GUNSHIP HOVER]], }, { def = [[MISSILE]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[SWIM FIXEDWING LAND SUB SINK TURRET FLOAT SHIP GUNSHIP HOVER]], }, }, weaponDefs = { PLASMA = { name = [[Medium Plasma Cannon]], accuracy = 200, areaOfEffect = 160, craterBoost = 1, craterMult = 2, damage = { default = 350, planes = 350, subs = 17.5, }, explosionGenerator = [[custom:bigbulletimpact]], impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, noSelfDamage = true, range = 350, reloadtime = 2, soundHit = [[weapon/cannon/cannon_hit2]], soundStart = [[weapon/cannon/heavy_cannon]], turret = true, weaponType = [[Cannon]], weaponVelocity = 330, }, MISSILE = { name = [[Destroyer Missiles]], areaOfEffect = 48, cegTag = [[missiletrailyellow]], craterBoost = 1, craterMult = 2, damage = { default = 160, subs = 160, }, edgeEffectiveness = 0.5, fireStarter = 100, fixedLauncher = true, flightTime = 4, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 2, model = [[wep_m_hailstorm.s3o]], noSelfDamage = true, range = 420, reloadtime = 2, smokeTrail = true, soundHit = [[weapon/missile/missile_fire12]], soundStart = [[weapon/missile/missile_fire10]], startVelocity = 100, tolerance = 4000, tracks = true, turnrate = 30000, turret = true, waterWeapon = true, weaponAcceleration = 300, weaponTimer = 1, weaponType = [[StarburstLauncher]], weaponVelocity = 1800, }, }, featureDefs = { DEAD = { description = [[Wreckage - Daimyo]], blocking = false, category = [[corpses]], collisionVolumeOffsets = [[0 0 3]], collisionVolumeScales = [[32 46 102]], collisionVolumeTest = 1, collisionVolumeType = [[box]], damage = 3300, energy = 0, featureDead = [[HEAP]], footprintX = 5, footprintZ = 5, height = [[4]], hitdensity = [[100]], metal = 280, object = [[destroyer_dead.s3o]], reclaimable = true, reclaimTime = 280, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, HEAP = { description = [[Debris - Daimyo]], blocking = false, category = [[heaps]], damage = 3300, energy = 0, featurereclamate = [[SMUDGE01]], footprintX = 4, footprintZ = 4, hitdensity = [[100]], metal = 140, object = [[debris4x4b.s3o]], reclaimable = true, reclaimTime = 140, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, }, } return lowerkeys({ destroyer = unitDef })
gpl-2.0
rlcevg/Zero-K
LuaUI/Widgets/chili_new/controls/screen.lua
8
7553
--- Screen module --- Screen fields. -- Inherits from Object. -- @see object.Object -- @table Screen -- @int[opt=0] x x position -- @int[opt=0] y y position -- @int[opt=0] width width -- @int[opt=0] height height -- @tparam control.Control activeControl active control -- @tparam control.Control focusedControl focused control -- @tparam control.Control hoveredControl hovered control Screen = Object:Inherit{ --Screen = Control:Inherit{ classname = 'screen', x = 0, y = 0, width = 0, height = 0, preserveChildrenOrder = true, activeControl = nil, focusedControl = nil, hoveredControl = nil, currentTooltip = nil, _lastHoveredControl = nil, _lastClicked = Spring.GetTimer(), _lastClickedX = 0, _lastClickedY = 0, } local this = Screen local inherited = this.inherited --//============================================================================= function Screen:New(obj) local vsx,vsy = gl.GetViewSizes() if ((obj.width or -1) <= 0) then obj.width = vsx end if ((obj.height or -1) <= 0) then obj.height = vsy end obj = inherited.New(self,obj) TaskHandler.RequestGlobalDispose(obj) obj:RequestUpdate() return obj end function Screen:OnGlobalDispose(obj) if CompareLinks(self.activeControl, obj) then self.activeControl = nil end if CompareLinks(self.hoveredControl, obj) then self.hoveredControl = nil end if CompareLinks(self._lastHoveredControl, obj) then self._lastHoveredControl = nil end if CompareLinks(self.focusedControl, obj) then self.focusedControl = nil end end --//============================================================================= --FIXME add new coordspace Device (which does y-invert) function Screen:ParentToLocal(x,y) return x, y end function Screen:LocalToParent(x,y) return x, y end function Screen:LocalToScreen(x,y) return x, y end function Screen:ScreenToLocal(x,y) return x, y end function Screen:ScreenToClient(x,y) return x, y end function Screen:ClientToScreen(x,y) return x, y end function Screen:IsRectInView(x,y,w,h) return (x <= self.width) and (x + w >= 0) and (y <= self.height) and (y + h >= 0) end --//============================================================================= function Screen:Resize(w,h) self.width = w self.height = h self:CallChildren("RequestRealign") end --//============================================================================= function Screen:Update(...) --//FIXME create a passive MouseMove event and use it instead? self:RequestUpdate() local hoveredControl = UnlinkSafe(self.hoveredControl) local activeControl = UnlinkSafe(self.activeControl) if hoveredControl and (not activeControl) then local x, y = Spring.GetMouseState() y = select(2,gl.GetViewSizes()) - y local cx,cy = hoveredControl:ScreenToLocal(x, y) hoveredControl:MouseMove(cx, cy, 0, 0) end end function Screen:IsAbove(x,y,...) local activeControl = UnlinkSafe(self.activeControl) if activeControl then return true end y = select(2,gl.GetViewSizes()) - y local hoveredControl = inherited.IsAbove(self,x,y,...) --// tooltip if not CompareLinks(hoveredControl, self._lastHoveredControl) then if self._lastHoveredControl then self._lastHoveredControl:MouseOut() end if hoveredControl then hoveredControl:MouseOver() end self.hoveredControl = MakeWeakLink(hoveredControl, self.hoveredControl) if (hoveredControl) then local control = hoveredControl --// find tooltip in hovered control or its parents while (not control.tooltip)and(control.parent) do control = control.parent end self.currentTooltip = control.tooltip else self.currentTooltip = nil end self._lastHoveredControl = self.hoveredControl elseif (self._lastHoveredControl) then self.currentTooltip = self._lastHoveredControl.tooltip end return (not not hoveredControl) end function Screen:MouseDown(x,y,...) y = select(2,gl.GetViewSizes()) - y local activeControl = inherited.MouseDown(self,x,y,...) self.activeControl = MakeWeakLink(activeControl, self.activeControl) if not CompareLinks(self.activeControl, self.focusedControl) then local focusedControl = UnlinkSafe(self.focusedControl) if focusedControl then focusedControl.state.focused = false focusedControl:FocusUpdate() --rename FocusLost() end self.focusedControl = nil if self.activeControl then self.focusedControl = MakeWeakLink(activeControl, self.focusedControl) self.focusedControl.state.focused = true self.focusedControl:FocusUpdate() --rename FocusGain() end end return (not not activeControl) end function Screen:MouseUp(x,y,...) y = select(2,gl.GetViewSizes()) - y local activeControl = UnlinkSafe(self.activeControl) if activeControl then local cx,cy = activeControl:ScreenToLocal(x,y) local now = Spring.GetTimer() local obj local hoveredControl = inherited.IsAbove(self,x,y,...) if CompareLinks(hoveredControl, activeControl) then --//FIXME send this to controls too, when they didn't `return self` in MouseDown! if (math.abs(x - self._lastClickedX)<3) and (math.abs(y - self._lastClickedY)<3) and (Spring.DiffTimers(now,self._lastClicked) < 0.45 ) --FIXME 0.45 := doubleClick time (use spring config?) then obj = activeControl:MouseDblClick(cx,cy,...) end if (obj == nil) then obj = activeControl:MouseClick(cx,cy,...) end end self._lastClicked = now self._lastClickedX = x self._lastClickedY = y obj = activeControl:MouseUp(cx,cy,...) or obj self.activeControl = nil return (not not obj) else return (not not inherited.MouseUp(self,x,y,...)) end end function Screen:MouseMove(x,y,dx,dy,...) y = select(2,gl.GetViewSizes()) - y local activeControl = UnlinkSafe(self.activeControl) if activeControl then local cx,cy = activeControl:ScreenToLocal(x,y) local obj = activeControl:MouseMove(cx,cy,dx,-dy,...) if (obj==false) then self.activeControl = nil elseif (not not obj)and(obj ~= activeControl) then self.activeControl = MakeWeakLink(obj, self.activeControl) return true else return true end end return (not not inherited.MouseMove(self,x,y,dx,-dy,...)) end function Screen:MouseWheel(x,y,...) y = select(2,gl.GetViewSizes()) - y local activeControl = UnlinkSafe(self.activeControl) if activeControl then local cx,cy = activeControl:ScreenToLocal(x,y) local obj = activeControl:MouseWheel(cx,cy,...) if (obj==false) then self.activeControl = nil elseif (not not obj)and(obj ~= activeControl) then self.activeControl = MakeWeakLink(obj, self.activeControl) return true else return true end end return (not not inherited.MouseWheel(self,x,y,...)) end function Screen:KeyPress(...) local focusedControl = UnlinkSafe(self.focusedControl) if focusedControl then return (not not focusedControl:KeyPress(...)) end return (not not inherited:KeyPress(...)) end function Screen:TextInput(...) local focusedControl = UnlinkSafe(self.focusedControl) if focusedControl then return (not not focusedControl:TextInput(...)) end return (not not inherited:TextInput(...)) end --//=============================================================================
gpl-2.0
rlcevg/Zero-K
effects/mary_sue.lua
25
5718
-- mary_sue_fireball1 -- mary_sue_fireball3 -- mary_sue -- mary_sue_fireball2 return { ["mary_sue_fireball1"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[1 1 1 0.01 0 0 0 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 10, particlelifespread = 0, particlesize = 15, particlesizespread = 0, particlespeed = 1, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[exp02_1]], }, }, }, ["mary_sue_fireball3"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 10, particlelifespread = 0, particlesize = 15, particlesizespread = 0, particlespeed = 1, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[exp02_3]], }, }, }, ["mary_sue"] = { frame1 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:MARY_SUE_FIREBALL1]], pos = [[0, 0, 0]], }, }, frame2 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 6.6, explosiongenerator = [[custom:MARY_SUE_FIREBALL2]], pos = [[0, 6.6, 0]], }, }, frame3 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 13.2, explosiongenerator = [[custom:MARY_SUE_FIREBALL3]], pos = [[0, 13.2, 0]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 25, ttl = 6, color = { [1] = 1, [2] = 0.69999998807907, [3] = 0.69999998807907, }, }, pikes = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.2, color = [[1.0,0.7,0]], dir = [[-15 r30,-15 r30,-15 r30]], length = 15, width = 5, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 2, ground = true, water = true, properties = { airdrag = 0.97, alwaysvisible = true, colormap = [[1 1 0 0.01 1 0.7 0.5 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 20, particlelife = 7.5, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 3, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["mary_sue_fireball2"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 10, particlelifespread = 0, particlesize = 15, particlesizespread = 0, particlespeed = 1, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[exp02_2]], }, }, }, }
gpl-2.0
stas2z/openwrt-witi
package/alt/luci-app-vsftpd/files/usr/lib/lua/luci/controller/vsftpd.lua
1
2064
--[[ LuCI - Lua Configuration Interface - vsftpd support Script by Admin @ NVACG.org (af_xj@hotmail.com , xujun@smm.cn) Some codes is based on luci-app-upnp, TKS. The Author of luci-app-upnp is Steven Barth <steven@midlink.org> and Jo-Philipp Wich <xm@subsignal.org> Licensed under the GPL License, Version 3.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.gnu.org/licenses/gpl.txt $Id$ ]]-- module("luci.controller.vsftpd",package.seeall) function index() require("luci.i18n") luci.i18n.loadc("vsftpd") if not nixio.fs.access("/etc/config/vsftpd") then return end local page = entry({"admin","services","vsftpd"},cbi("vsftpd"),_("FTP Service")) page.i18n="vsftpd" page.dependent=true entry({"admin","services","vsftpd","status"}, call("connection_status")).leaf = true end function connection_status() local cmd = io.popen("ps | grep vsftpd | grep -v grep | grep -v IDLE") if cmd then local conn = { } while true do local ln = cmd:read("*l") if not ln then break elseif ln:match("^.%d+.-%d+.%d+.%d+.%d+:.[a-z]+") then local num,ip,act = ln:match("^.(%d+).-(%d+.%d+.%d+.%d+):.([a-z]+)") if num and ip and act then num = tonumber(num) conn[#conn+1]= { num = num, ip = ip, user = "", act = act:upper(), file = "" } end elseif ln:match("^.%d+.-%d+.%d+.%d+.%d+/%w+:.%a+.[%w%p]+") then local num,ip,user,act,file = ln:match("^.(%d+).-(%d+.%d+.%d+.%d+)/(%w+):.(%u+).([%w%p]+)") if num and ip and act then num = tonumber(num) conn[#conn+1]= { num = num, ip = ip, user = user, act = act, file = file } end end end cmd:close() luci.http.prepare_content("application/json") luci.http.write_json(conn) end end
gpl-2.0
rlcevg/Zero-K
LuaUI/Widgets/gui_nukeButton.lua
3
17189
local versionNumber = "1.3.4" function widget:GetInfo() return { name = "Nuke Button Zero-K", desc = "[v" .. string.format("%s", versionNumber ) .. "] Displays Nuke Button", author = "very_bad_soldier / versus666", date = "July 19, 2009 / September 08, 2010", license = "GNU GPL v2", layer = 0, enabled = false } end --[[ Features: -multiple mod support -with one clic you select the next ready nuke silo for easy nuclear winter. ---- CHANGELOG ----- -- versus666, v1.3.4 (07jan2011) : added check to comply with F5. -- versus666, v1.3.3 (10nov2010) : added more precise tweakmode tooltip + placeholder name + nuke icon. -- versus666, v1.3.2 (04nov2010) : removed other mods support to avoid rants about widget being a BA widget, added check to disable ghost tooltips when no nuke is built. -- versus666, v1.3.1 (30oct2010) : added compatibility to CA1F -> need update when CA1F-> zero-K will be enforced. -- very_bad_soldier V1.0 : initial release. --]] -- CONFIGURATION local debug = false --generates debug message local updateInt = 1 --seconds for the ::update loop local baseFontSize = 14 local hideTooltips = true local intConfig = {} intConfig["fontSize"] = 12 intConfig["buttonSize"] = 25 --half the width intConfig["defaultScreenResY"] = 1050 --do not change intConfig["buttonCoords"] = {} intConfig["buttonCoords"][1] = {} intConfig["buttonCoords"][2] = {} intConfig["buttonCoords"]["progress"] = {} intConfig["mouseOver"] = false intConfig["nextNuke"] = nil --unitID of nextNuketoFire intConfig["leftClickTime"] = 0 intConfig["screenx"], intConfig["screeny"] = widgetHandler:GetViewSizes() -- END OF CONFIG -- Internal temp vars local readyNukeCount = 0 local highProgress = -1 local lastTime local nukeList = {} local curUnitList local config = {} config["buttonXPer"] = 0.935 config["buttonYPer"] = 0.765 --Game Config ------------------------------------ local unitList = {} unitList["ZK"] = {} --initialize table unitList["ZK"]["corsilo"] = {} --End local upper = string.upper local floor = math.floor local max = math.max local min = math.min local udefTab = UnitDefs local glColor = gl.Color local glDepthTest = gl.DepthTest local glTexture = gl.Texture --local glTexEnv = gl.TexEnv local glLineWidth = gl.LineWidth --local glPopMatrix = gl.PopMatrix --local glPushMatrix = gl.PushMatrix --local glTranslate = gl.Translate --local glFeatureShape = gl.FeatureShape local spGetGameSeconds = Spring.GetGameSeconds local spGetMyPlayerID = Spring.GetMyPlayerID local spGetPlayerInfo = Spring.GetPlayerInfo --local spGetAllFeatures = Spring.GetAllFeatures --local spGetFeaturePosition = Spring.GetFeaturePosition --local spGetFeatureDefID = Spring.GetFeatureDefID --local spGetMyAllyTeamID = Spring.GetMyAllyTeamID --local spGetFeatureAllyTeam = Spring.GetFeatureAllyTeam --local spGetFeatureTeam = Spring.GetFeatureTeam --local spGetUnitHealth = Spring.GetUnitHealth --local spGetFeatureHealth = Spring.GetFeatureHealth --local spGetFeatureResurrect = Spring.GetFeatureResurrect local spGetPositionLosState = Spring.GetPositionLosState local spGetUnitStockpile = Spring.GetUnitStockpile --local spIsUnitAllied = Spring.IsUnitAllied --local spGetUnitPosition = Spring.GetUnitPosition local spEcho = Spring.Echo local spGetUnitDefID = Spring.GetUnitDefID local spGetTeamUnits = Spring.GetTeamUnits local spGetMyTeamID = Spring.GetMyTeamID local spGetMouseState = Spring.GetMouseState local spGiveOrderToUnit = Spring.GiveOrderToUnit local spSelectUnitArray = Spring.SelectUnitArray local spGetGameSpeed = Spring.GetGameSpeed local spSetActiveCommand = Spring.SetActiveCommand --local DrawGhostFeatures --local DrawGhostSites --local ScanFeatures --local DeleteGhostFeatures --local DeleteGhostSites local ResetGl local CheckSpecState local printDebug --local GL_FILL = GL.FILL local GL_LINE_LOOP = GL.LINE_LOOP --local GL_TRIANGLE_STRIP = GL_TRIANGLE_STRIP --local glUnitShape = gl.UnitShape local glBeginEnd = gl.BeginEnd --local glBillboard = gl.Billboard --local glDrawGroundCircle = gl.DrawGroundCircle --local glDrawGroundQuad = gl.DrawGroundQuad local glTexRect = gl.TexRect local glText = gl.Text local glVertex = gl.Vertex --local glAlphaTest = gl.AlphaTest --local glBlending = gl.Blending local glRect = gl.Rect local IsGuiHidden = Spring.IsGUIHidden function widget:Initialize() ResizeButtonsToScreen() myPlayerID = spGetMyPlayerID() --spGetLocalTeamID() curModID = upper(Game.modShortName or "") if ( unitList[curModID] == nil ) then spEcho("<Nuke Icon>: Unsupported Game, shutting down...") widgetHandler:RemoveWidget() return end curUnitList = unitList[curModID] --add all already existing nukes searchAndAddNukes() end function widget:Update() local timef = spGetGameSeconds() local time = floor(timef) -- update timers once every <updateInt> seconds if (time % updateInt == 0 and time ~= lastTime) then lastTime = time --do update stuff: if ( CheckSpecState() == false ) then return false end highestLoadCount = 0 readyNukeCount = 0 highProgress = -1 --magic value: no active nukes for unitID, udefID in pairs( nukeList ) do local numStockpiled, numStockPQue = spGetUnitStockpile( unitID) local buildPercent = Spring.GetUnitRulesParam("gadgetStockpile",unitID); if ( buildPercent == nil ) then --unit seems to be gone, delete it deleteNuke( unitID ) else --save highest nuke stockpile progress readyNukeCount = readyNukeCount + numStockpiled if ( numStockPQue > 0 ) then highProgress = max( highProgress, buildPercent ) end end if ( numStockpiled > highestLoadCount ) then intConfig["nextNuke"] = unitID highestLoadCount = numStockpiled end end printDebug("<Nuke Icon>: HighProgress: " .. highProgress ) updateProgressLayer() end end function updateProgressLayer() --progress layer --fuck, replace half of the "buttonCurrentWidth" by "buttonCurrentHeight" intConfig["buttonCoords"]["progress"] = {} table.insert( intConfig["buttonCoords"]["progress"], { 0, 0 } ) table.insert( intConfig["buttonCoords"]["progress"], { 0, intConfig["buttonCurrentWidth"] } ) local localHP = highProgress localHP = max( 0, localHP ) if ( localHP < 0.875 ) then table.insert( intConfig["buttonCoords"]["progress"], { -intConfig["buttonCurrentWidth"], intConfig["buttonCurrentWidth"] } ) end if ( localHP < 0.625 ) then table.insert( intConfig["buttonCoords"]["progress"], { -intConfig["buttonCurrentWidth"], -intConfig["buttonCurrentWidth"] } ) end if ( localHP < 0.375 ) then table.insert( intConfig["buttonCoords"]["progress"], { intConfig["buttonCurrentWidth"], -intConfig["buttonCurrentWidth"] } ) end if ( localHP < 0.125 ) then table.insert( intConfig["buttonCoords"]["progress"], { intConfig["buttonCurrentWidth"], intConfig["buttonCurrentWidth"] } ) end local x=0 local y=0 if ( localHP < 0.125 ) then y = intConfig["buttonCurrentWidth"] x = intConfig["buttonCurrentWidth"] * localHP / 0.125 elseif ( localHP < 0.375 ) then y = intConfig["buttonCurrentWidth"] - 2 * intConfig["buttonCurrentWidth"] * ( localHP - 0.125 ) / 0.25 x = intConfig["buttonCurrentWidth"] elseif ( localHP < 0.625 ) then y = -intConfig["buttonCurrentWidth"] x = intConfig["buttonCurrentWidth"] - 2 * intConfig["buttonCurrentWidth"] * ( localHP - 0.375 ) / 0.25 elseif ( localHP < 0.875 ) then y = -intConfig["buttonCurrentWidth"] + 2* intConfig["buttonCurrentWidth"] * ( localHP - 0.625 ) / 0.25 x = -intConfig["buttonCurrentWidth"] elseif ( localHP < 1.0 ) then y = intConfig["buttonCurrentWidth"] x = -intConfig["buttonCurrentWidth"] + intConfig["buttonCurrentWidth"] * ( localHP - 0.875 ) / 0.125 end table.insert( intConfig["buttonCoords"]["progress"], { x,y } ) end function isMouseOver( mx, my ) if ( mx > intConfig["buttonCoords"][1]["x"] and mx < intConfig["buttonCoords"][2]["x"] ) then if ( my < intConfig["buttonCoords"][1]["y"] and my > intConfig["buttonCoords"][2]["y"] ) then return true end end return false end -- needed for GetTooltip function widget:IsAbove(x, y) if (not isMouseOver(x, y)) then return false end return true end function widget:GetTooltip(x, y) if hideTooltips then return end local text = "" if ( readyNukeCount > 0 ) then text = "Left-Click: Select next nuke\nDouble-Click: Aim next nuke" else text = "Loading Nuke: " .. string.format("%.2f", highProgress * 100) .. "%" end return text end function widget:DrawScreen() if not IsGuiHidden() then --printDebug("Count: " .. lastTime ) local mx,my,lmb,mmb,rmb = spGetMouseState() intConfig["mouseOver"] = false if ( isMouseOver( mx, my ) ) then intConfig["mouseOver"] = true end if ( highProgress > -1 or readyNukeCount > 0 ) then drawButton( ) end end end function widget:MousePress(x, y, button) if ( isMouseOver( x, y ) and readyNukeCount > 0 and button == 1 ) then local timeNow = spGetGameSeconds() spSelectUnitArray( { intConfig["nextNuke"] } , false ) local _,speedfac, _ = spGetGameSpeed() if ( timeNow < intConfig["leftClickTime"] + (0.5 * speedfac ) ) then --Spring.GiveOrderToUnit ( intConfig["nextNuke"], CMD.ATTACK, {500,500,500}, {} ) spSetActiveCommand( "Attack" ) end intConfig["leftClickTime"] = timeNow return true end end function widget:UnitDestroyed( unitID, unitDefID, unitTeam ) deleteNuke( unitID ) hideTooltips = true end function widget:UnitFinished( unitID, unitDefID, unitTeam ) if ( unitTeam == spGetMyTeamID() ) then addPossibleNuke( unitID, unitDefID ) end end function widget:UnitTaken( unitID, unitDefID, unitTeam, newTeam ) --Spring.Echo( "unitTeam: " .. unitTeam .. " newTeam: " .. newTeam ) if ( newTeam == spGetMyTeamID() ) then addPossibleNuke( unitID, unitDefID ) end end function widget:UnitGiven(unitID) deleteNuke( unitID ) hideTooltips = true end --End OF Callins function searchAndAddNukes() local allUnits = spGetTeamUnits(spGetMyTeamID()) for _, unitID in pairs(allUnits) do local unitDefID = spGetUnitDefID(unitID) if ( unitDefID ~= nil ) then addPossibleNuke( unitID, unitDefID ) else hideTooltips = true end end end --delete nuke from list if we know it function deleteNuke( unitID ) if ( nukeList[unitID] ~= nil ) then nukeList[unitID] = nil end end function addPossibleNuke( unitID, unitDefID ) local udef = UnitDefs[unitDefID] printDebug( "<Nuke Icon>: Name: " .. udef.name .. " UnitID: " .. unitID .. "udefid: " .. unitDefID ) if ( curUnitList[udef.name] ~= nil ) then printDebug("Nuke added!") nukeList[unitID] = udef.name hideTooltips = false end end local buttonConfig = {} buttonConfig["borderColor"] = { 0, 0, 0, 1.0 } buttonConfig["highlightColor"] = { 1.0, 0.0, 0.0, 1.0 } function widget:ViewResize(viewSizeX, viewSizeY) intConfig["screenx"] = viewSizeX intConfig["screeny"] = viewSizeY borderizeButtons() ResizeButtonsToScreen() end function ResizeButtonsToScreen() --printDebug("Old Width:" .. ButtonWidthOrg .. " vsy: " .. vsy ) intConfig["buttonCurrentWidth"] = ( intConfig["screeny"] / intConfig["defaultScreenResY"] ) * intConfig["buttonSize"] intConfig["buttonCurrentHeight"] = intConfig["buttonCurrentWidth"] intConfig["buttonCoords"][1]["x"] = intConfig["screenx"] * config["buttonXPer"] - intConfig["buttonCurrentWidth"] intConfig["buttonCoords"][1]["y"] = intConfig["screeny"] * config["buttonYPer"] + intConfig["buttonCurrentHeight"] intConfig["buttonCoords"][2]["x"] = intConfig["screenx"] * config["buttonXPer"] + intConfig["buttonCurrentWidth"] intConfig["buttonCoords"][2]["y"] = intConfig["screeny"] * config["buttonYPer"] - intConfig["buttonCurrentHeight"] intConfig["fontSize"] = baseFontSize * ( intConfig["screeny"] / intConfig["defaultScreenResY"] ) printDebug("Resizing: " .. intConfig["buttonCoords"][1]["x"] ) updateProgressLayer() end function drawButton( ) xmax = intConfig["buttonCoords"][1]["x"] ymax = intConfig["buttonCoords"][1]["y"] xmin = intConfig["buttonCoords"][2]["x"] ymin = intConfig["buttonCoords"][2]["y"] -- draw button body local bgColor = { 0.0, 0.0, 0.0 } -- draw colored background rectangle glColor( bgColor ) glTexture(false) glTexRect( xmin, ymin, xmax, ymax ) -- draw icon glColor( { 1.0, 1.0, 1.0} ) glTexture( ":n:LuaUI/Images/nuke_button_64.png" ) local texBorder = 0.75 glTexRect( xmin, ymin, xmax, ymax, 0.0, texBorder, texBorder, 0.0 ) glTexture(false) --draw the progress if ( highProgress >= 0 ) then DrawButtonProgress( intConfig["buttonCoords"][1]["x"] + intConfig["buttonCurrentWidth"], intConfig["buttonCoords"][1]["y"] - intConfig["buttonCurrentHeight"] ) end -- draw the outline if ( intConfig["mouseOver"] and readyNukeCount > 0 ) then glColor(buttonConfig["highlightColor"]) else glColor(buttonConfig["borderColor"]) end local function Draw() glVertex(xmin, ymin) glVertex(xmax, ymin) glVertex(xmax, ymax) glVertex(xmin, ymax) end glBeginEnd(GL_LINE_LOOP, Draw) local centerx = xmin - intConfig["buttonCurrentWidth"] glColor(1,0,0, alpha or 1) glText( readyNukeCount, centerx, ymin + intConfig["buttonCurrentHeight"] + 0.2 * intConfig["buttonCurrentHeight"], intConfig["fontSize"], "nc") glColor(1,1,1,1) if ( highProgress >= 0 ) then glColor(1 - highProgress, 1 * highProgress,0, alpha or 1) glText( string.format( "%.0f", highProgress * 100 ) .. "%", centerx + 0.1 * intConfig["buttonCurrentWidth"], ymin + 0.2 * intConfig["buttonCurrentHeight"], 0.9 * intConfig["fontSize"], "nc") glColor(1,1,1,1) end end function DrawButtonProgress( xcenter, ycenter ) glTexture(false) glColor( { .0, .0, .0, 0.7} ) local function Draw() for id, point in pairs( intConfig["buttonCoords"]["progress"] ) do glVertex( xcenter + point[1], ycenter + point[2] ) end end glBeginEnd(GL.TRIANGLE_FAN, Draw) end --Commons function ResetGl() glColor( { 1.0, 1.0, 1.0, 1.0 } ) glLineWidth( 1.0 ) glDepthTest(false) glTexture(false) end function CheckSpecState() local playerID = spGetMyPlayerID() local _, _, spec, _, _, _, _, _ = spGetPlayerInfo(playerID) if ( spec == true ) then spEcho("<Nuke Icon> Spectator mode. Widget removed.") widgetHandler:RemoveWidget() return false end return true end function printDebug( value ) if ( debug ) then if ( type( value ) == "boolean" ) then if ( value == true ) then spEcho( "true" ) else spEcho("false") end elseif ( type(value ) == "table" ) then spEcho("Dumping table:") for key,val in pairs(value) do spEcho(key,val) end else spEcho( value ) end end end --SAVE / LOAD CONFIG FILE function widget:GetConfigData() return config end function widget:SetConfigData(data) if (data ~= nil) then config = data ResizeButtonsToScreen() borderizeButtons() ResizeButtonsToScreen() end end --END OF LOAD SAVE --TWEAK MODE local inTweakDrag = false function widget:TweakMousePress(x,y,button) inTweakDrag = isMouseOver(x, y) --allows button movement when mouse moves return inTweakDrag end function widget:TweakMouseMove(x,y,dx,dy,button) if ( inTweakDrag == false ) then return end printDebug("Tweak") config["buttonXPer"] = config["buttonXPer"] + ( dx / intConfig["screenx"] ) config["buttonYPer"] = config["buttonYPer"] + ( dy / intConfig["screeny"] ) borderizeButtons() ResizeButtonsToScreen() end function borderizeButtons() if ( config["buttonXPer"] * intConfig["screenx"] - intConfig["buttonCurrentWidth"] < 0.0 ) then config["buttonXPer"] = 0.0 elseif( config["buttonXPer"] * intConfig["screenx"] + intConfig["buttonCurrentWidth"] > intConfig["screenx"] ) then config["buttonXPer"] = ( intConfig["screenx"] - intConfig["buttonCurrentWidth"] ) / intConfig["screenx"] end if ( config["buttonYPer"] * intConfig["screeny"] - intConfig["buttonCurrentHeight"] < 0.0 ) then config["buttonYPer"] = 0.0 elseif( config["buttonYPer"] * intConfig["screeny"] + intConfig["buttonCurrentHeight"] > intConfig["screeny"] ) then config["buttonYPer"] = ( intConfig["screeny"] - intConfig["buttonCurrentHeight"] ) / intConfig["screeny"] end end function widget:TweakMouseRelease(x,y,button) inTweakDrag = false end function widget:TweakDrawScreen() drawButton() glColor(0.0,0.0,1.0,0.5) glRect( intConfig["buttonCoords"][1]["x"], intConfig["buttonCoords"][2]["y"], intConfig["buttonCoords"][2]["x"], intConfig["buttonCoords"][1]["y"]) glColor(1,1,1,1) local centerx = xmin - intConfig["buttonCurrentWidth"] - 16 glText( "NUKE\nButton", centerx, ymin+12, intConfig["fontSize"]) end function widget:TweakIsAbove(x,y) return isMouseOver(x,y) end function widget:TweakGetTooltip(x,y) return 'Nuke Button Icon\n'.. 'Click and hold left mouse button\n'.. 'over button to drag\n' end --END OF TWEAK MODE
gpl-2.0
medialab-prado/Interactivos-15-Ego
minetest-ego/games/adventuretest/mods/moreblocks/nodes.lua
2
12304
--[[ More Blocks: node definitions Copyright (c) 2011-2015 Calinou and contributors. Licensed under the zlib license. See LICENSE.md for more information. --]] local S = moreblocks.intllib local sound_wood = default.node_sound_wood_defaults() local sound_stone = default.node_sound_stone_defaults() local sound_glass = default.node_sound_glass_defaults() local sound_leaves = default.node_sound_leaves_defaults() local function tile_tiles(name) local tex = "moreblocks_" ..name.. ".png" return {tex, tex, tex, tex, tex.. "^[transformR90", tex.. "^[transformR90"} end local nodes = { ["wood_tile"] = { description = S("Wooden Tile"), groups = {snappy = 1, choppy = 2, oddly_breakable_by_hand = 2, flammable = 3}, tiles = {"default_wood.png^moreblocks_wood_tile.png", "default_wood.png^moreblocks_wood_tile.png", "default_wood.png^moreblocks_wood_tile.png", "default_wood.png^moreblocks_wood_tile.png", "default_wood.png^moreblocks_wood_tile.png^[transformR90", "default_wood.png^moreblocks_wood_tile.png^[transformR90"}, sounds = sound_wood, }, ["wood_tile_flipped"] = { description = S("Wooden Tile"), groups = {snappy = 1, choppy = 2, oddly_breakable_by_hand = 2, flammable = 3}, tiles = {"default_wood.png^moreblocks_wood_tile.png^[transformR90", "default_wood.png^moreblocks_wood_tile.png^[transformR90", "default_wood.png^moreblocks_wood_tile.png^[transformR90", "default_wood.png^moreblocks_wood_tile.png^[transformR90", "default_wood.png^moreblocks_wood_tile.png^[transformR180", "default_wood.png^moreblocks_wood_tile.png^[transformR180"}, sounds = sound_wood, no_stairs = true, }, ["wood_tile_center"] = { description = S("Centered Wooden Tile"), groups = {snappy = 1, choppy = 2, oddly_breakable_by_hand = 2, flammable = 3}, tiles = {"default_wood.png^moreblocks_wood_tile_center.png"}, sounds = sound_wood, }, ["wood_tile_full"] = { description = S("Full Wooden Tile"), groups = {snappy = 1, choppy = 2, oddly_breakable_by_hand = 2, flammable = 3}, tiles = tile_tiles("wood_tile_full"), sounds = sound_wood, }, ["wood_tile_up"] = { description = S("Upwards Wooden Tile"), groups = {snappy = 1, choppy = 2, oddly_breakable_by_hand = 2, flammable = 3}, tiles = {"default_wood.png^moreblocks_wood_tile_up.png"}, sounds = sound_wood, no_stairs = true, }, ["wood_tile_down"] = { description = S("Downwards Wooden Tile"), groups = {snappy = 1, choppy = 2, oddly_breakable_by_hand = 2, flammable = 3}, tiles = {"default_wood.png^[transformR180^moreblocks_wood_tile_up.png^[transformR180"}, sounds = sound_wood, no_stairs = true, }, ["wood_tile_left"] = { description = S("Leftwards Wooden Tile"), groups = {snappy = 1, choppy = 2, oddly_breakable_by_hand = 2, flammable = 3}, tiles = {"default_wood.png^[transformR270^moreblocks_wood_tile_up.png^[transformR270"}, sounds = sound_wood, no_stairs = true, }, ["wood_tile_right"] = { description = S("Rightwards Wooden Tile"), groups = {snappy = 1, choppy = 2, oddly_breakable_by_hand = 2, flammable = 3}, tiles = {"default_wood.png^[transformR90^moreblocks_wood_tile_up.png^[transformR90"}, sounds = sound_wood, no_stairs = true, }, ["circle_stone_bricks"] = { description = S("Circle Stone Bricks"), groups = {cracky = 3}, sounds = sound_stone, }, ["grey_bricks"] = { description = S("Stone Bricks"), groups = {cracky = 3}, sounds = sound_stone, }, ["coal_stone_bricks"] = { description = S("Coal Stone Bricks"), groups = {cracky = 3}, sounds = sound_stone, }, ["iron_stone_bricks"] = { description = S("Iron Stone Bricks"), groups = {cracky = 3}, sounds = sound_stone, }, ["stone_tile"] = { description = S("Stone Tile"), groups = {cracky = 3}, sounds = sound_stone, }, ["split_stone_tile"] = { description = S("Split Stone Tile"), tiles = {"moreblocks_split_stone_tile_top.png", "moreblocks_split_stone_tile.png"}, groups = {cracky = 3}, sounds = sound_stone, }, ["split_stone_tile_alt"] = { description = S("Checkered Stone Tile"), groups = {cracky = 3}, sounds = sound_stone, }, ["tar"] = { description = S("Tar"), groups = {cracky = 2, tar_block = 1}, sounds = sound_stone, }, ["cobble_compressed"] = { description = S("Compressed Cobblestone"), groups = {cracky = 1}, sounds = sound_stone, }, ["plankstone"] = { description = S("Plankstone"), groups = {cracky = 3}, tiles = tile_tiles("plankstone"), sounds = sound_stone, }, ["iron_glass"] = { description = S("Iron Glass"), drawtype = "glasslike_framed_optional", --tiles = {"moreblocks_iron_glass.png", "moreblocks_iron_glass_detail.png"}, tiles = {"moreblocks_iron_glass.png"}, paramtype = "light", sunlight_propagates = true, groups = {snappy = 2, cracky = 3, oddly_breakable_by_hand = 3}, sounds = sound_glass, }, ["coal_glass"] = { description = S("Coal Glass"), drawtype = "glasslike_framed_optional", --tiles = {"moreblocks_coal_glass.png", "moreblocks_coal_glass_detail.png"}, tiles = {"moreblocks_coal_glass.png"}, paramtype = "light", sunlight_propagates = true, groups = {snappy = 2, cracky = 3, oddly_breakable_by_hand = 3}, sounds = sound_glass, }, ["clean_glass"] = { description = S("Clean Glass"), drawtype = "glasslike_framed_optional", --tiles = {"moreblocks_clean_glass.png", "moreblocks_clean_glass_detail.png"}, tiles = {"moreblocks_clean_glass.png"}, paramtype = "light", sunlight_propagates = true, groups = {snappy = 2, cracky = 3, oddly_breakable_by_hand = 3}, sounds = sound_glass, }, ["cactus_brick"] = { description = S("Cactus Brick"), groups = {cracky = 3}, sounds = sound_stone, }, ["cactus_checker"] = { description = S("Cactus Checker"), groups = {cracky = 3}, tiles = {"default_stone.png^moreblocks_cactus_checker.png", "default_stone.png^moreblocks_cactus_checker.png", "default_stone.png^moreblocks_cactus_checker.png", "default_stone.png^moreblocks_cactus_checker.png", "default_stone.png^moreblocks_cactus_checker.png^[transformR90", "default_stone.png^moreblocks_cactus_checker.png^[transformR90"}, sounds = sound_stone, }, ["empty_bookshelf"] = { description = S("Empty Bookshelf"), tiles = {"default_wood.png", "default_wood.png", "moreblocks_empty_bookshelf.png"}, groups = {snappy = 2, choppy = 3, oddly_breakable_by_hand = 2, flammable = 3}, sounds = sound_wood, no_stairs = true, }, ["coal_stone"] = { description = S("Coal Stone"), groups = {cracky = 3}, sounds = sound_stone, }, ["iron_stone"] = { description = S("Iron Stone"), groups = {cracky = 3}, sounds = sound_stone, }, ["coal_checker"] = { description = S("Coal Checker"), tiles = {"default_stone.png^moreblocks_coal_checker.png", "default_stone.png^moreblocks_coal_checker.png", "default_stone.png^moreblocks_coal_checker.png", "default_stone.png^moreblocks_coal_checker.png", "default_stone.png^moreblocks_coal_checker.png^[transformR90", "default_stone.png^moreblocks_coal_checker.png^[transformR90"}, groups = {cracky = 3}, sounds = sound_stone, }, ["iron_checker"] = { description = S("Iron Checker"), tiles = {"default_stone.png^moreblocks_iron_checker.png", "default_stone.png^moreblocks_iron_checker.png", "default_stone.png^moreblocks_iron_checker.png", "default_stone.png^moreblocks_iron_checker.png", "default_stone.png^moreblocks_iron_checker.png^[transformR90", "default_stone.png^moreblocks_iron_checker.png^[transformR90"}, groups = {cracky = 3}, sounds = sound_stone, }, ["trap_stone"] = { description = S("Trap Stone"), walkable = false, groups = {cracky = 3}, sounds = sound_stone, no_stairs = true, }, ["trap_glass"] = { description = S("Trap Glass"), drawtype = "glasslike_framed_optional", --tiles = {"moreblocks_trap_glass.png", "default_glass_detail.png"}, tiles = {"moreblocks_trap_glass.png"}, paramtype = "light", sunlight_propagates = true, walkable = false, groups = {snappy = 2, cracky = 3, oddly_breakable_by_hand = 3}, sounds = sound_glass, no_stairs = true, }, ["fence_jungle_wood"] = { description = S("Jungle Wood Fence"), drawtype = "fencelike", tiles = {"default_junglewood.png"}, inventory_image = "default_fence_overlay.png^default_junglewood.png^default_fence_overlay.png^[makealpha:255,126,126", wield_image = "default_fence_overlay.png^default_junglewood.png^default_fence_overlay.png^[makealpha:255,126,126", paramtype = "light", selection_box = { type = "fixed", fixed = {-1/7, -1/2, -1/7, 1/7, 1/2, 1/7}, }, groups = {snappy = 2, choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}, sounds = sound_wood, no_stairs = true, }, ["all_faces_tree"] = { description = S("All-faces Tree"), tiles = {"default_tree_top.png"}, groups = {tree = 1,snappy = 1, choppy = 2, oddly_breakable_by_hand = 1, flammable = 2}, sounds = sound_wood, furnace_burntime = 30, }, ["all_faces_jungle_tree"] = { description = S("All-faces Jungle Tree"), tiles = {"default_jungletree_top.png"}, groups = {tree = 1,snappy = 1, choppy = 2, oddly_breakable_by_hand = 1, flammable = 2}, sounds = sound_wood, furnace_burntime = 30, }, ["glow_glass"] = { description = S("Glow Glass"), drawtype = "glasslike_framed_optional", --tiles = {"moreblocks_glow_glass.png", "moreblocks_glow_glass_detail.png"}, tiles = {"moreblocks_glow_glass.png"}, paramtype = "light", sunlight_propagates = true, light_source = 11, groups = {snappy = 2, cracky = 3, oddly_breakable_by_hand = 3}, sounds = sound_glass, }, ["trap_glow_glass"] = { description = S("Trap Glow Glass"), drawtype = "glasslike_framed_optional", --tiles = {"moreblocks_trap_glass.png", "moreblocks_glow_glass_detail.png"}, tiles = {"moreblocks_trap_glass.png"}, paramtype = "light", sunlight_propagates = true, light_source = 11, walkable = false, groups = {snappy = 2, cracky = 3, oddly_breakable_by_hand = 3}, sounds = sound_glass, no_stairs = true, }, ["super_glow_glass"] = { description = S("Super Glow Glass"), drawtype = "glasslike_framed_optional", --tiles = {"moreblocks_super_glow_glass.png", "moreblocks_super_glow_glass_detail.png"}, tiles = {"moreblocks_super_glow_glass.png"}, paramtype = "light", sunlight_propagates = true, light_source = 15, groups = {snappy = 2, cracky = 3, oddly_breakable_by_hand = 3}, sounds = sound_glass, }, ["trap_super_glow_glass"] = { description = S("Trap Super Glow Glass"), drawtype = "glasslike_framed_optional", --tiles = {"moreblocks_trap_super_glow_glass.png", "moreblocks_super_glow_glass_detail.png"}, tiles = {"moreblocks_trap_super_glow_glass.png"}, paramtype = "light", sunlight_propagates = true, light_source = 15, walkable = false, groups = {snappy = 2, cracky = 3, oddly_breakable_by_hand = 3}, sounds = sound_glass, no_stairs = true, }, ["rope"] = { description = S("Rope"), drawtype = "signlike", inventory_image = "moreblocks_rope.png", wield_image = "moreblocks_rope.png", paramtype = "light", sunlight_propagates = true, paramtype2 = "wallmounted", walkable = false, climbable = true, selection_box = {type = "wallmounted",}, groups = {snappy = 3, flammable = 2}, sounds = sound_leaves, no_stairs = true, }, } for name, def in pairs(nodes) do def.tiles = def.tiles or {"moreblocks_" ..name.. ".png"} minetest.register_node("moreblocks:" ..name, def) minetest.register_alias(name, "moreblocks:" ..name) if not def.no_stairs then local groups = {} for k, v in pairs(def.groups) do groups[k] = v end stairsplus:register_all("moreblocks", name, "moreblocks:" ..name, { description = def.description, groups = groups, tiles = def.tiles, sunlight_propagates = def.sunlight_propagates, light_source = def.light_source, sounds = def.sounds, }) end end -- Items minetest.register_craftitem("moreblocks:sweeper", { description = S("Sweeper"), inventory_image = "moreblocks_sweeper.png", }) minetest.register_craftitem("moreblocks:jungle_stick", { description = S("Jungle Stick"), inventory_image = "moreblocks_junglestick.png", groups = {stick= 1}, }) minetest.register_craftitem("moreblocks:nothing", { inventory_image = "invisible.png", on_use = function() end, })
mit
joole/private-pkgs
luci/applications/luci-app-shadowsocks/files/luci/model/cbi/shadowsocks/servers-details.lua
3
2058
-- Copyright (C) 2016-2017 Jian Chang <aa65535@live.com> -- Licensed to the public under the GNU General Public License v3. local m, s, o local shadowsocks = "shadowsocks" local sid = arg[1] local encrypt_methods = { "rc4-md5", "aes-128-cfb", "aes-192-cfb", "aes-256-cfb", "aes-128-ctr", "aes-192-ctr", "aes-256-ctr", "aes-128-gcm", "aes-192-gcm", "aes-256-gcm", "camellia-128-cfb", "camellia-192-cfb", "camellia-256-cfb", "bf-cfb", "salsa20", "chacha20", "chacha20-ietf", "chacha20-ietf-poly1305", "xchacha20-ietf-poly1305", } local function support_fast_open() return luci.sys.exec("cat /proc/sys/net/ipv4/tcp_fastopen 2>/dev/null"):trim() == "3" end m = Map(shadowsocks, "%s - %s" %{translate("ShadowSocks"), translate("Edit Server")}) m.redirect = luci.dispatcher.build_url("admin/services/shadowsocks/servers") if m.uci:get(shadowsocks, sid) ~= "servers" then luci.http.redirect(m.redirect) return end -- [[ Edit Server ]]-- s = m:section(NamedSection, sid, "servers") s.anonymous = true s.addremove = false o = s:option(Value, "alias", translate("Alias(optional)")) o.rmempty = true if support_fast_open() then o = s:option(Flag, "fast_open", translate("TCP Fast Open")) o.rmempty = false end o = s:option(Value, "server", translate("Server Address")) o.datatype = "ipaddr" o.rmempty = false o = s:option(Value, "server_port", translate("Server Port")) o.datatype = "port" o.rmempty = false o = s:option(Value, "timeout", translate("Connection Timeout")) o.datatype = "uinteger" o.default = 60 o.rmempty = false o = s:option(Value, "password", translate("Password")) o.password = true o = s:option(Value, "key", translate("Directly Key")) o = s:option(ListValue, "encrypt_method", translate("Encrypt Method")) for _, v in ipairs(encrypt_methods) do o:value(v, v:upper()) end o.rmempty = false o = s:option(Value, "plugin", translate("Plugin Name")) o.placeholder = "eg: obfs-local" o = s:option(Value, "plugin_opts", translate("Plugin Arguments")) o.placeholder = "eg: obfs=http;obfs-host=www.bing.com" return m
gpl-2.0
ViolyS/RayUI_VS
Interface/AddOns/RayUI_Options/libs/AceGUI-3.0-SharedMediaWidgets/Libs/AceGUI-3.0/widgets/AceGUIContainer-Frame.lua
3
8912
--[[----------------------------------------------------------------------------- Frame Container -------------------------------------------------------------------------------]] local Type, Version = "Frame", 22 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local pairs, assert, type = pairs, assert, type local wipe = table.wipe -- WoW APIs local PlaySound = PlaySound local CreateFrame, UIParent = CreateFrame, UIParent -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: CLOSE --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function Button_OnClick(frame) PlaySound("gsTitleOptionExit") frame.obj:Hide() end local function Frame_OnClose(frame) frame.obj:Fire("OnClose") end local function Frame_OnMouseDown(frame) AceGUI:ClearFocus() end local function Title_OnMouseDown(frame) frame:GetParent():StartMoving() AceGUI:ClearFocus() end local function MoverSizer_OnMouseUp(mover) local frame = mover:GetParent() frame:StopMovingOrSizing() local self = frame.obj local status = self.status or self.localstatus status.width = frame:GetWidth() status.height = frame:GetHeight() status.top = frame:GetTop() status.left = frame:GetLeft() end local function SizerSE_OnMouseDown(frame) frame:GetParent():StartSizing("BOTTOMRIGHT") AceGUI:ClearFocus() end local function SizerS_OnMouseDown(frame) frame:GetParent():StartSizing("BOTTOM") AceGUI:ClearFocus() end local function SizerE_OnMouseDown(frame) frame:GetParent():StartSizing("RIGHT") AceGUI:ClearFocus() end local function StatusBar_OnEnter(frame) frame.obj:Fire("OnEnterStatusBar") end local function StatusBar_OnLeave(frame) frame.obj:Fire("OnLeaveStatusBar") end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self.frame:SetParent(UIParent) self.frame:SetFrameStrata("FULLSCREEN_DIALOG") self:SetTitle() self:SetStatusText() self:ApplyStatus() self:Show() end, ["OnRelease"] = function(self) self.status = nil wipe(self.localstatus) end, ["OnWidthSet"] = function(self, width) local content = self.content local contentwidth = width - 34 if contentwidth < 0 then contentwidth = 0 end content:SetWidth(contentwidth) content.width = contentwidth end, ["OnHeightSet"] = function(self, height) local content = self.content local contentheight = height - 57 if contentheight < 0 then contentheight = 0 end content:SetHeight(contentheight) content.height = contentheight end, ["SetTitle"] = function(self, title) self.titletext:SetText(title) self.titlebg:SetWidth((self.titletext:GetWidth() or 0) + 10) end, ["SetStatusText"] = function(self, text) self.statustext:SetText(text) end, ["Hide"] = function(self) self.frame:Hide() end, ["Show"] = function(self) self.frame:Show() end, -- called to set an external table to store status in ["SetStatusTable"] = function(self, status) assert(type(status) == "table") self.status = status self:ApplyStatus() end, ["ApplyStatus"] = function(self) local status = self.status or self.localstatus local frame = self.frame self:SetWidth(status.width or 700) self:SetHeight(status.height or 500) frame:ClearAllPoints() if status.top and status.left then frame:SetPoint("TOP", UIParent, "BOTTOM", 0, status.top) frame:SetPoint("LEFT", UIParent, "LEFT", status.left, 0) else frame:SetPoint("CENTER") end end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local FrameBackdrop = { bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background", edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border", tile = true, tileSize = 32, edgeSize = 32, insets = { left = 8, right = 8, top = 8, bottom = 8 } } local PaneBackdrop = { bgFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", tile = true, tileSize = 16, edgeSize = 16, insets = { left = 3, right = 3, top = 5, bottom = 3 } } local function Constructor() local frame = CreateFrame("Frame", nil, UIParent) frame:Hide() frame:EnableMouse(true) frame:SetMovable(true) frame:SetResizable(true) frame:SetFrameStrata("FULLSCREEN_DIALOG") frame:SetBackdrop(FrameBackdrop) frame:SetBackdropColor(0, 0, 0, 1) frame:SetMinResize(400, 200) frame:SetToplevel(true) frame:SetScript("OnHide", Frame_OnClose) frame:SetScript("OnMouseDown", Frame_OnMouseDown) local closebutton = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate") closebutton:SetScript("OnClick", Button_OnClick) closebutton:SetPoint("BOTTOMRIGHT", -27, 17) closebutton:SetHeight(20) closebutton:SetWidth(100) closebutton:SetText(CLOSE) local statusbg = CreateFrame("Button", nil, frame) statusbg:SetPoint("BOTTOMLEFT", 15, 15) statusbg:SetPoint("BOTTOMRIGHT", -132, 15) statusbg:SetHeight(24) statusbg:SetBackdrop(PaneBackdrop) statusbg:SetBackdropColor(0.1,0.1,0.1) statusbg:SetBackdropBorderColor(0.4,0.4,0.4) statusbg:SetScript("OnEnter", StatusBar_OnEnter) statusbg:SetScript("OnLeave", StatusBar_OnLeave) local statustext = statusbg:CreateFontString(nil, "OVERLAY", "GameFontNormal") statustext:SetPoint("TOPLEFT", 7, -2) statustext:SetPoint("BOTTOMRIGHT", -7, 2) statustext:SetHeight(20) statustext:SetJustifyH("LEFT") statustext:SetText("") local titlebg = frame:CreateTexture(nil, "OVERLAY") titlebg:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Header") titlebg:SetTexCoord(0.31, 0.67, 0, 0.63) titlebg:SetPoint("TOP", 0, 12) titlebg:SetWidth(100) titlebg:SetHeight(40) local title = CreateFrame("Frame", nil, frame) title:EnableMouse(true) title:SetScript("OnMouseDown", Title_OnMouseDown) title:SetScript("OnMouseUp", MoverSizer_OnMouseUp) title:SetAllPoints(titlebg) local titletext = title:CreateFontString(nil, "OVERLAY", "GameFontNormal") titletext:SetPoint("TOP", titlebg, "TOP", 0, -14) local titlebg_l = frame:CreateTexture(nil, "OVERLAY") titlebg_l:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Header") titlebg_l:SetTexCoord(0.21, 0.31, 0, 0.63) titlebg_l:SetPoint("RIGHT", titlebg, "LEFT") titlebg_l:SetWidth(30) titlebg_l:SetHeight(40) local titlebg_r = frame:CreateTexture(nil, "OVERLAY") titlebg_r:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Header") titlebg_r:SetTexCoord(0.67, 0.77, 0, 0.63) titlebg_r:SetPoint("LEFT", titlebg, "RIGHT") titlebg_r:SetWidth(30) titlebg_r:SetHeight(40) local sizer_se = CreateFrame("Frame", nil, frame) sizer_se:SetPoint("BOTTOMRIGHT") sizer_se:SetWidth(25) sizer_se:SetHeight(25) sizer_se:EnableMouse() sizer_se:SetScript("OnMouseDown",SizerSE_OnMouseDown) sizer_se:SetScript("OnMouseUp", MoverSizer_OnMouseUp) local line1 = sizer_se:CreateTexture(nil, "BACKGROUND") line1:SetWidth(14) line1:SetHeight(14) line1:SetPoint("BOTTOMRIGHT", -8, 8) line1:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") local x = 0.1 * 14/17 line1:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5) local line2 = sizer_se:CreateTexture(nil, "BACKGROUND") line2:SetWidth(8) line2:SetHeight(8) line2:SetPoint("BOTTOMRIGHT", -8, 8) line2:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") local x = 0.1 * 8/17 line2:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5) local sizer_s = CreateFrame("Frame", nil, frame) sizer_s:SetPoint("BOTTOMRIGHT", -25, 0) sizer_s:SetPoint("BOTTOMLEFT") sizer_s:SetHeight(25) sizer_s:EnableMouse(true) sizer_s:SetScript("OnMouseDown", SizerS_OnMouseDown) sizer_s:SetScript("OnMouseUp", MoverSizer_OnMouseUp) local sizer_e = CreateFrame("Frame", nil, frame) sizer_e:SetPoint("BOTTOMRIGHT", 0, 25) sizer_e:SetPoint("TOPRIGHT") sizer_e:SetWidth(25) sizer_e:EnableMouse(true) sizer_e:SetScript("OnMouseDown", SizerE_OnMouseDown) sizer_e:SetScript("OnMouseUp", MoverSizer_OnMouseUp) --Container Support local content = CreateFrame("Frame", nil, frame) content:SetPoint("TOPLEFT", 17, -27) content:SetPoint("BOTTOMRIGHT", -17, 40) local widget = { localstatus = {}, titletext = titletext, statustext = statustext, titlebg = titlebg, content = content, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end closebutton.obj, statusbg.obj = widget, widget return AceGUI:RegisterAsContainer(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
mit
Satoshi-t/Re-SBS
lua/ai/ol-ai.lua
1
28825
sgs.ai_skill_choice.olmiji_draw = function(self, choices) return "" .. self.player:getLostHp() end sgs.ai_skill_invoke.olmiji = function(self, data) if #self.friends == 0 then return false end for _, friend in ipairs(self.friends) do if not friend:hasSkill("manjuan") and not self:isLihunTarget(friend) then return true end end return false end sgs.ai_skill_askforyiji.olmiji = function(self, card_ids) local available_friends = {} for _, friend in ipairs(self.friends) do if not friend:hasSkill("manjuan") and not self:isLihunTarget(friend) then table.insert(available_friends, friend) end end local toGive, allcards = {}, {} local keep for _, id in ipairs(card_ids) do local card = sgs.Sanguosha:getCard(id) if not keep and (isCard("Jink", card, self.player) or isCard("Analeptic", card, self.player)) then keep = true else table.insert(toGive, card) end table.insert(allcards, card) end local cards = #toGive > 0 and toGive or allcards self:sortByKeepValue(cards, true) local id = cards[1]:getId() local card, friend = self:getCardNeedPlayer(cards, true) if card and friend and table.contains(available_friends, friend) then if friend:objectName() == self.player:objectName() then return nil, -1 else return friend, card:getId() end end if #available_friends > 0 then self:sort(available_friends, "handcard") for _, afriend in ipairs(available_friends) do if not self:needKongcheng(afriend, true) then if afriend:objectName() == self.player:objectName() then return nil, -1 else return afriend, id end end end self:sort(available_friends, "defense") if available_friends[1]:objectName() == self.player:objectName() then return nil, -1 else return available_friends[1], id end end return nil, -1 end sgs.ai_skill_use["@@bushi"] = function(self, prompt, method) local zhanglu = self.room:findPlayerBySkillName("bushi") if not zhanglu or zhanglu:getPile("rice"):length() < 1 then return "." end if self:isEnemy(zhanglu) and zhanglu:getPile("rice"):length() == 1 and zhanglu:isWounded() then return "." end if self:isFriend(zhanglu) and (not (zhanglu:getPile("rice"):length() == 1 and zhanglu:isWounded())) and self:getOverflow() > 1 then return "." end local cards = {} for _,id in sgs.qlist(zhanglu:getPile("rice")) do table.insert(cards,sgs.Sanguosha:getCard(id)) end self:sortByUseValue(cards, true) return "@BushiCard="..cards[1]:getEffectiveId() end sgs.ai_skill_use["@@midao"] = function(self, prompt, method) local judge = self.player:getTag("judgeData"):toJudge() local ids = self.player:getPile("rice") if self.room:getMode():find("_mini_46") and not judge:isGood() then return "@MidaoCard=" .. ids:first() end if self:needRetrial(judge) then local cards = {} for _,id in sgs.qlist(ids) do table.insert(cards,sgs.Sanguosha:getCard(id)) end local card_id = self:getRetrialCardId(cards, judge) if card_id ~= -1 then return "@MidaoCard=" .. card_id end end return "." end --[[ 技能:安恤(阶段技) 描述:你可以选择两名手牌数不同的其他角色,令其中手牌多的角色将一张手牌交给手牌少的角色,然后若这两名角色手牌数相等,你选择一项:1.摸一张牌;2.回复1点体力。 ]]-- --OlAnxuCard:Play anxu_skill = { name = "olanxu", getTurnUseCard = function(self, inclusive) if self.player:hasUsed("OlAnxuCard") then return nil elseif self.room:alivePlayerCount() > 2 then return sgs.Card_Parse("@OlAnxuCard=.") end end, } table.insert(sgs.ai_skills, anxu_skill) sgs.ai_skill_use_func["OlAnxuCard"] = function(card, use, self) -- end --room->askForExchange(playerA, "olanxu", 1, 1, false, QString("@olanxu:%1:%2").arg(source->objectName()).arg(playerB->objectName())) sgs.ai_skill_discard["olanxu"] = function(self, discard_num, min_num, optional, include_equip) local others = self.room:getOtherPlayers(self.player) local target = nil for _,p in sgs.qlist(others) do if p:hasFlag("olanxu_target") then target = nil break end end assert(target) local handcards = self.player:getHandcards() handcards = sgs.QList2Table(handcards) if self:isFriend(target) and not hasManjuanEffect(target) then self:sortByUseValue(handcards) return { handcards[1]:getEffectiveId() } end return self:askForDiscard("dummy", discard_num, min_num, optional, include_equip) end --room->askForChoice(source, "olanxu", choices) sgs.ai_skill_choice["olanxu"] = function(self, choices, data) local items = choices:split("+") if #items == 1 then return items[1] end return "recover" end --[[ 技能:追忆 描述:你死亡时,你可以令一名其他角色(除杀死你的角色)摸三张牌并回复1点体力。 ]]-- --[[ 技能:陈情 描述:每轮限一次,当一名角色处于濒死状态时,你可以令另一名其他角色摸四张牌,然后弃置四张牌。若其以此法弃置的四张牌花色各不相同,则视为该角色对濒死的角色使用一张【桃】 ]]-- --room->askForPlayerChosen(source, targets, "olchenqing", QString("@olchenqing:%1").arg(victim->objectName()), false, true) sgs.ai_skill_playerchosen["olchenqing"] = function(self, targets) local victim = self.room:getCurrentDyingPlayer() local help = false local careLord = false if victim then if self:isFriend(victim) then help = true elseif self.role == "renegade" and victim:isLord() and self.room:alivePlayerCount() > 2 then help = true careLord = true end end local friends, enemies = {}, {} for _,p in sgs.qlist(targets) do if self:isFriend(p) then table.insert(friends, p) else table.insert(enemies, p) end end local compare_func = function(a, b) local nA = a:getCardCount(true) local nB = b:getCardCount(true) if nA == nB then return a:getHandcardNum() > b:getHandcardNum() else return nA > nB end end if help and #friends > 0 then table.sort(friends, compare_func) for _,friend in ipairs(friends) do if not hasManjuanEffect(friend) then return friend end end end if careLord and #enemies > 0 then table.sort(enemies, compare_func) for _,enemy in ipairs(enemies) do if sgs.evaluatePlayerRole(enemy) == "loyalist" then return enemy end end end if #enemies > 0 then self:sort(enemies, "threat") for _,enemy in ipairs(enemies) do if hasManjuanEffect(enemy) then return enemy end end end if #friends > 0 then self:sort(friends, "defense") for _,friend in ipairs(friends) do if not hasManjuanEffect(friend) then return friend end end end end --room->askForExchange(target, "olchenqing", 4, 4, true, QString("@olchenqing-exchange:%1:%2").arg(source->objectName()).arg(victim->objectName()), false) sgs.ai_skill_discard["olchenqing"] = function(self, discard_num, min_num, optional, include_equip) local victim = self.room:getCurrentDyingPlayer() local help = false if victim then if self:isFriend(victim) then help = true elseif self.role == "renegade" and victim:isLord() and self.room:alivePlayerCount() > 2 then help = true end end local cards = self.room:getCards("he") cards = sgs.QList2Table(cards) self:sortByKeepValue(cards) if help then local peach_num = 0 local spade, heart, club, diamond = nil, nil, nil, nil for _,c in ipairs(cards) do if isCard("Peach", c, self.player) then peach_num = peach_num + 1 else local suit = c:getSuit() if not spade and suit == sgs.Card_Spade then spade = c:getEffectiveId() elseif not heart and suit == sgs.Card_Heart then heart = c:getEffectiveId() elseif not club and suit == sgs.Card_Club then club = c:getEffectiveId() elseif not diamond and suit == sgs.Card_Diamond then diamond = c:getEffectiveId() end end end if peach_num + victim:getHp() <= 0 then if spade and heart and club and diamond then return {spade, heart, club, diamond} end end end return self:askForDiscard("dummy", discard_num, min_num, optional, include_equip) end --[[ 技能:默识 描述:结束阶段开始时,你可以将一张手牌当你本回合出牌阶段使用的第一张基本或非延时类锦囊牌使用。然后,你可以将一张手牌当你本回合出牌阶段使用的第二张基本或非延时类锦囊牌使用。 ]]-- --[[ 技能:庸肆(锁定技) 描述:摸牌阶段开始时,你改为摸X张牌。锁定技,弃牌阶段开始时,你选择一项:1.弃置一张牌;2.失去1点体力。(X为场上势力数) ]]-- --room->askForDiscard(player, "olyongsi", 1, 1, true, true, "@olyongsi") sgs.ai_skill_discard["olyongsi"] = function(self, discard_num, min_num, optional, include_equip) if self:needToLoseHp() or getBestHp(self.player) > self.player:getHp() then return "." end return self:askForDiscard("dummy", discard_num, min_num, optional, include_equip) end --[[ 技能:觊玺(觉醒技) 描述:你的回合结束时,若你连续三回合没有失去过体力,则你加1点体力上限并回复1点体力,然后选择一项:1.获得技能“妄尊”;2.摸两张牌并获得当前主公的主公技。 ]]-- --room->askForChoice(player, "oljixi", choices.join("+")) sgs.ai_skill_choice["oljixi"] = function(self, choices, data) local items = choices:split("+") if #items == 1 then return items[1] end return "wangzun" end --[[ 技能:雷击 描述:当你使用或打出【闪】时,你可以令一名其他角色进行判定,若结果为:♠,你对该角色造成2点雷电伤害;♣,你回复1点体力,然后对该角色造成1点雷电伤害。 ]]-- --room->askForPlayerChosen(player, others, "olleiji", "@olleiji", true, true) sgs.ai_skill_playerchosen["olleiji"] = function(self, targets) -- end --[[ 技能:鬼道 描述:每当一名角色的判定牌生效前,你可以打出一张黑色牌替换之。 ]]-- --[[ 技能:黄天(主公技、阶段技) 描述:其他群雄角色的出牌阶段,该角色可以交给你一张【闪】或【闪电】。 ]]-- --[[ 技能:仁德 描述:出牌阶段,你可以将任意张手牌交给一名其他角色,然后你于此阶段内不能再次以此法交给该角色牌。当你以此法交给其他角色的牌数在同一阶段内首次达到两张或更多时,你回复1点体力 ]]-- local function OlRendeArrange(self, cards, friends, enemies, unknowns, arrange) if #enemies > 0 then self:sort(enemies, "hp") for _,card in ipairs(cards) do if card:isKindOf("Shit") then return enemies[1], card, "enemy" end end end if #friends > 0 then self:sort(friends, "defense") for _,friend in ipairs(friends) do local arranged = arrange[friend:objectName()] or {} if self:isWeak(friend) and friend:getHandcardNum() + #arranged < 3 then for _,card in ipairs(cards) do if card:isKindOf("Shit") then elseif isCard("Peach", card, friend) or isCard("Analeptic", card, friend) then return friend, card, "friend" elseif isCard("Jink", card, friend) and self:getEnemyNumBySeat(self.player, friend) > 0 then return friend, card, "friend" end end end end for _,friend in ipairs(friends) do local arranged = arrange[friend:objectName()] or {} if friend:getHp() <= 2 and friend:faceUp() then for _,card in ipairs(cards) do if card:isKindOf("Armor") then if not friend:getArmor() and not self:hasSkills("yizhong|bazhen|bossmanjia", friend) then local given = false for _,c in ipairs(arranged) do if c:isKindOf("Armor") then given = true break end end if not given then return friend, card, "friend" end end elseif card:isKindOf("DefensiveHorse") then if not friend:getDefensiveHorse() then local given = false for _,c in ipairs(arranged) do if c:isKindOf("DefensiveHorse") then given = true break end end if not given then return friend, card, "friend" end end end end end end for _,friend in ipairs(friends) do local arranged = arrange[friend:objectName()] or {} if friend:getHandcardNum() + #arranged < 4 then if friend:hasSkill("jijiu") then for _,card in ipairs(cards) do if card:isRed() then return friend, card, "friend" end end end if friend:hasSkill("jieyin") then return friend, cards[1], "friend" elseif friend:hasSkill("nosrenxin") and friend:isKongcheng() then return friend, cards[1], "friend" end end end for _,friend in ipairs(friends) do if self:hasSkills("wusheng|longdan|wushen|keji|chixin", friend) then local arranged = arrange[friend:objectName()] or {} if friend:getHandcardNum() + #arranged >= 2 and not self:hasCrossbowEffect(friend) then for _,card in ipairs(cards) do if card:isKindOf("Crossbow") then local given = false for _,c in ipairs(arranged) do if c:isKindOf("Crossbow") then given = true break end end if not given then return friend, card, "friend" end end end end end end for _,friend in ipairs(friends) do local arranged = arrange[friend:objectName()] or {} local has_crossbow = self:hasCrossbowEffect(friend) if not has_crossbow then for _,c in ipairs(arranged) do if c:isKindOf("Crossbow") then has_crossbow = true break end end end if has_crossbow or getKnownCard(friend, self.player, "Crossbow") > 0 then for _, p in ipairs(self.enemies) do if sgs.isGoodTarget(p, self.enemies, self) and friend:distanceTo(p) <= 1 then for _,card in ipairs(cards) do if isCard("Slash", card, friend) then return friend, card, "friend" end end end end end end local compareByAction = function(a, b) return self.room:getFront(a, b):objectName() == a:objectName() end table.sort(friends, compareByAction) for _,friend in ipairs(friends) do local flag = string.format("weapon_done_%s_%s", self.player:objectName(), friend:objectName()) if friend:faceUp() and not friend:hasFlag(flag) then local can_slash = false local others = self.room:getOtherPlayers(friend) for _,p in sgs.qlist(others) do if self:isEnemy(p) and sgs.isGoodTarget(p, self.enemies, self) then if friend:distanceTo(p) <= friend:getAttackRange() then can_slash = true break end end end if not can_slash then for _,p in sgs.qlist(others) do if self:isEnemy(p) and sgs.isGoodTarget(p, self.enemies, self) then local distance = friend:distanceTo(p) local range = friend:getAttackRange() if distance > range then for _,card in ipairs(cards) do if card:isKindOf("Weapon") then if not friend:getWeapon() then if distance <= range + (sgs.weapon_range[card:getClassName()] or 0) then self.room:setPlayerFlag(friend, flag) return friend, card, "friend" end end elseif card:isKindOf("OffensiveHorse") then if not friend:getOffensiveHorse() then if distance <= range + 1 then self.room:setPlayerFlag(friend, flag) return friend, card, "friend" end end end end end end end end end end local compareByNumber = function(a, b) return a:getNumber() > b:getNumber() end table.sort(cards, compareByNumber) for _,friend in ipairs(friends) do if friend:faceUp() then local skills = friend:getVisibleSkillList(true) for _,skill in sgs.qlist(skills) do local callback = sgs.ai_cardneed[skill:objectName()] if type(callback) == "function" then for _,card in ipairs(cards) do if callback(friend, card, self) then return friend, card, "friend" end end end end end end for _,card in ipairs(cards) do if card:isKindOf("Shit") then for _,friend in ipairs(friends) do if self:isWeak(friend) then elseif friend:hasSkill("jueqing") or card:getSuit() == sgs.Card_Spade then if friend:hasSkill("zhaxiang") then return friend, card, "friend" end elseif self:hasSkills("guixin|jieming|yiji|nosyiji|chengxiang|noschengxiang|jianxiong", friend) then return friend, card, "friend" end end end end if self.role == "lord" and self.player:hasLordSkill("jijiang") then for _,friend in ipairs(friends) do local arranged = arrange[friend:objectName()] or {} if friend:getKingdom() == "shu" and friend:getHandcardNum() + #arranged < 3 then for _,card in ipairs(cards) do if isCard("Slash", card, friend) then return friend, card, "friend" end end end end end end if #enemies > 0 then self:sort(enemies, "defense") for _,enemy in ipairs(enemies) do if enemy:hasSkill("kongcheng") and enemy:isKongcheng() then if not enemy:hasSkill("manjuan") then for _,card in ipairs(cards) do if isCard("Jink", card, enemy) then elseif card:isKindOf("Disaster") or card:isKindOf("Shit") then return enemy, card, "enemy" elseif card:isKindOf("Collateral") or card:isKindOf("AmazingGrace") then return enemy, card, "enemy" elseif card:isKindOf("OffensiveHorse") or card:isKindOf("Weapon") then return enemy, card, "enemy" end end end end end end local overflow = self:getOverflow() if #friends > 0 then for _,friend in ipairs(friends) do local arranged = arrange[friend:objectName()] or {} if self:willSkipPlayPhase(friend) then elseif self:hasSkills(sgs.priority_skill, friend) and friend:getHandcardNum() + #arranged <= 3 then if overflow - #arranged > 0 or self.player:getHandcardNum() - #arranged > 3 then return friend, cards[1], "friend" end end end end if overflow > 0 and #friends > 0 then for _,card in ipairs(cards) do local dummy_use = { isDummy = true, } if card:isKindOf("BasicCard") then self:useBasicCard(card, dummy_use) elseif card:isKindOf("EquipCard") then self:useEquipCard(card, dummy_use) elseif card:isKindOf("TrickCard") then self:useTrickCard(card, dummy_use) end if not dummy_use.card then self:sort(friends, "defense") return friends[1], card, "friend" end end end if arrange["count"] < 2 and self.player:getLostHp() > 0 and self.player:getHandcardNum() >= 2 and self:isWeak() then if #friends > 0 then return friends[1], cards[1], "friend" elseif #unknowns > 0 then self:sortByKeepValue(cards) for _,p in ipairs(unknowns) do if p:hasSkill("manjuan") then return p, cards[1], "unknown" end end self:sort(unknowns, "threat") return unknowns[#unknowns], cards[1], "unknown" elseif #enemies > 0 then for _,enemy in ipairs(enemies) do if enemy:hasSkill("manjuan") then return enemy, cards[1], "enemy" end end end end end local function resetPlayers(players, except) local result = {} for _,p in ipairs(players) do if not p:objectName() == except:objectName() then table.insert(result, p) end end return result end local rende_skill = { name = "olrende", getTurnUseCard = function(self, inclusive) if not self.player:isKongcheng() then return sgs.Card_Parse("@OlRendeCard=.") end end, } table.insert(sgs.ai_skills, rende_skill) sgs.ai_skill_use_func["OlRendeCard"] = function(card, use, self) local names = self.player:property("olrende"):toString():split("+") local others = self.room:getOtherPlayers(self.player) local friends, enemies, unknowns = {}, {}, {} local arrange = {} arrange["count"] = 0 for _,p in sgs.qlist(others) do local can_give = true for _,name in ipairs(names) do if name == p:objectName() then can_give = false break end end if can_give then arrange[p:objectName()] = {} if self:isFriend(p) then table.insert(friends, p) elseif self:isEnemy(p) then table.insert(enemies, p) else table.insert(unknowns, p) end end end local new_friends = {} for _,friend in ipairs(friends) do local exclude = false if self:needKongcheng(friend, true) or self:willSkipPlayPhase(friend) then exclude = true if self:hasSkills("keji|qiaobian|shensu", friend) then exclude = false elseif friend:getHp() - friend:getHandcardNum() >= 3 then exclude = false elseif friend:isLord() and self:isWeak(friend) and self:getEnemyNumBySeat(self.player, friend) >= 1 then exclude = false end end if not exclude and not hasManjuanEffect(friend) and self:objectiveLevel(friend) <= -2 then table.insert(new_friends, friend) end end friends = new_friends local overflow = self:getOverflow() if overflow <= 0 and #friends == 0 then return end local handcards = self.player:getHandcards() handcards = sgs.QList2Table(handcards) self:sortByUseValue(handcards) while true do if #handcards == 0 then break end local target, to_give, group = OlRendeArrange(self, handcards, friends, enemies, unknowns, arrange) if target and to_give and group then table.insert(arrange[target:objectName()], to_give) arrange["count"] = arrange["count"] + 1 handcards = self:resetCards(handcards, to_give) else break end end local max_count, max_name = 0, nil for name, cards in pairs(arrange) do if type(cards) == "table" then local count = #cards if count > max_count then max_count = count max_name = name end end end if max_count == 0 or not max_name then return end local max_target = nil for _,p in sgs.qlist(others) do if p:objectName() == max_name then max_target = p break end end if max_target and type(arrange[max_name]) == "table" and #arrange[max_name] > 0 then local to_use = {} for _,c in ipairs(arrange[max_name]) do table.insert(to_use, c:getEffectiveId()) end local card_str = "@OlRendeCard="..table.concat(to_use, "+") local acard = sgs.Card_Parse(card_str) assert(acard) use.card = acard if use.to then use.to:append(max_target) end end end sgs.ai_use_value.OlRendeCard = sgs.ai_use_value.RendeCard sgs.ai_use_priority.OlRendeCard = sgs.ai_use_priority.RendeCard sgs.ai_card_intention.OlRendeCard = sgs.ai_card_intention.RendeCard sgs.dynamic_value.benefit.OlRendeCard = true --[[ 技能:激将(主公技) 描述:每当你需要使用或打出一张【杀】时,你可以令其他蜀势力角色打出一张【杀】,视为你使用或打出之。 ]]-- sgs.ai_skill_invoke.olluoying = sgs.ai_skill_invoke.luoying sgs.ai_skill_askforag.olluoying = sgs.ai_skill_askforag.luoying
gpl-3.0
Jigoku/boxclip
src/entities/pickups.lua
1
5032
--[[ * Copyright (C) 2015 - 2022 Ricky K. Thomson * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * u should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. --]] pickups = {} pickups.magnet_power = 200 pickups.path = "data/images/pickups/" pickups.list = {} for _,pickup in ipairs(love.filesystem.getDirectoryItems(pickups.path)) do --possibly merge this into shared function .... --get file name without extension local name = pickup:match("^(.+)%..+$") --store list of prop names table.insert(pickups.list, name) --insert into editor menu table.insert(editor.entities, {name, "pickup"}) end --load the textures pickups.textures = textures:load(pickups.path) function pickups:add(x,y,type,dropped) for i,pickup in ipairs(pickups.list) do --maybe better way to do this? --loop over entity.list, find matching name -- then only insert when a match is found if pickup == type then local score = 0 if type == "gem" then score = "200" elseif type == "life" then score = "1000" elseif type == "magnet" then score = "1000" elseif type == "shield" then score = "1000" elseif type == "star" then score = "2500" end table.insert(world.entities.pickup, { x =x or 0, y =y or 0, w = self.textures[i]:getWidth(), h = self.textures[i]:getHeight(), group = "pickup", type = type, collected = false, dropped = dropped or false, attract = false, bounce = true, slot = i, colour = {love.math.random(0.75,1), love.math.random(0.75,1), love.math.random(0.75,1), 1.0}, xvel = 0, yvel = 0, score = score, }) print( "pickup added @ X:"..x.." Y: "..y) end end end function pickups:update(dt) for i, pickup in ipairs(world.entities.pickup) do if not pickup.collected then --pulls all gems to player when attract = true if pickup.attract then pickup.speed = pickup.speed + (pickups.magnet_power*2) *dt if player.alive then local angle = math.atan2(player.y+player.h/2 - pickup.h/2 - pickup.y, player.x+player.w/2 - pickup.w/2 - pickup.x) pickup.newX = pickup.x + (math.cos(angle) * pickup.speed * dt) pickup.newY = pickup.y + (math.sin(angle) * pickup.speed * dt) end else pickup.speed = 100 physics:applyGravity(pickup, dt) physics:applyVelocity(pickup,dt) physics:traps(pickup,dt) physics:platforms(pickup, dt) physics:crates(pickup, dt) end physics:update(pickup) if mode == "game" and not pickup.collected then if player.hasmagnet then if collision:check(player.x-pickups.magnet_power,player.y-pickups.magnet_power, player.w+(pickups.magnet_power*2),player.h+(pickups.magnet_power*2), pickup.x, pickup.y,pickup.w,pickup.h) then if not pickup.attract then pickup.attract = true end end end if player.alive and collision:check(player.x,player.y,player.w,player.h, pickup.x, pickup.y,pickup.w,pickup.h) then popups:add(pickup.x+pickup.w/2,pickup.y+pickup.h/2,"+"..pickup.score) console:print(pickup.group.."("..i..") collected") player:collect(pickup) pickup.collected = true end end end end end function pickups:draw() local count = 0 for i, pickup in ipairs(world.entities.pickup) do if not pickup.collected and world:inview(pickup) then count = count + 1 local texture = self.textures[pickup.slot] if pickup.type == "gem" then love.graphics.setColor(pickup.colour) love.graphics.draw(texture, pickup.x, pickup.y, 0, 1, 1) end if pickup.type == "life" then love.graphics.setColor(1,0,0, 1) love.graphics.draw(texture, pickup.x, pickup.y, 0, 1, 1) end if pickup.type == "magnet" then love.graphics.setColor(1,1,1, 1) love.graphics.draw(texture, pickup.x, pickup.y, 0, 1, 1) end if pickup.type == "shield" then love.graphics.setColor(1,1,1, 1) love.graphics.draw(texture, pickup.x, pickup.y, 0, 1, 1) end if pickup.type == "star" then love.graphics.setColor(1,1,1, 1) love.graphics.draw(texture, pickup.x, pickup.y, 0, 1, 1) end if editing or debug then pickups:drawdebug(pickup, i) end end end world.pickups = count end function pickups:drawdebug(pickup, i) love.graphics.setColor(0.39,1,0.39,0.39) love.graphics.rectangle( "line", pickup.x, pickup.y, pickup.w, pickup.h ) end function pickups:destroy(pickups, i) -- fade/collect animation can be added here table.remove(pickups, i) end
gpl-3.0
minetest-australopithecus/minetest-australopithecus
mods/core/mechanics/removetopping.lua
1
1571
--[[ Australopithecus, a game for Minetest. Copyright (C) 2015, Robert 'Bobby' Zenz This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA --]] local dirt = { name = "core:dirt" } -- Replaces nodes dirt if a node is placed above it. minetest.register_on_placenode(function(pos, newnode, placer, oldnode, itemstack, pointed_thing) if nodeutil.has_group(newnode, "preserves_below_node") or not nodeutil.is_walkable(newnode) or (nodeutil.has_group(newnode, "preserves_below_node_when_wallmounted") and wallmountedutil.is_wallmounted(newnode)) then -- If the node that is placed has either the needed group or is not -- walkable, it should not remove the topping. return end local pos_underneath = { x = pos.x, y = pos.y - 1, z = pos.z } local node = minetest.get_node(pos_underneath) if nodeutil.has_group(node, "becomes_dirt") then minetest.set_node(pos_underneath, dirt) end end)
lgpl-2.1
medialab-prado/Interactivos-15-Ego
minetest-ego/games/adventuretest/mods/bushes/cooking.lua
2
1952
-- Basket minetest.register_node("bushes:basket_empty", { description = "Basket", tiles = { "bushes_basket_empty_top.png", "bushes_basket_bottom.png", "bushes_basket_side.png" }, groups = { dig_immediate = 3 }, }) minetest.register_craft({ output = 'bushes:basket_empty', recipe = { { 'default:stick', 'default:stick', 'default:stick' }, { '', 'default:stick', '' }, }, }) -- Sugar minetest.register_craftitem("bushes:sugar", { description = "Sugar", inventory_image = "bushes_sugar.png", on_use = minetest.item_eat(1), }) minetest.register_craft({ output = 'bushes:sugar 1', recipe = { { 'default:papyrus', 'default:papyrus' }, }, }) -- Raw pie minetest.register_craftitem("bushes:berry_pie_raw", { description = "Raw berry pie", inventory_image = "bushes_berry_pie_raw.png", on_use = minetest.item_eat(3), }) minetest.register_craft({ output = 'bushes:berry_pie_raw 1', recipe = { { 'bushes:sugar', 'default:junglegrass', 'bushes:sugar' }, { 'bushes:strawberry', 'bushes:strawberry', 'bushes:strawberry' }, }, }) -- Cooked pie minetest.register_craftitem("bushes:berry_pie_cooked", { description = "Cooked berry pie", inventory_image = "bushes_berry_pie_cooked.png", on_use = minetest.item_eat(4), }) minetest.register_craft({ type = 'cooking', output = 'bushes:berry_pie_cooked', recipe = 'bushes:berry_pie_raw', cooktime = 30, }) -- Basket with pies minetest.register_node("bushes:basket_pies", { description = "Basket with pies", tiles = { "bushes_basket_full_top.png", "bushes_basket_bottom.png", "bushes_basket_side.png" }, on_use = minetest.item_eat(15), groups = { dig_immediate = 3 }, }) minetest.register_craft({ output = 'bushes:basket_pies 1', recipe = { { 'bushes:berry_pie_cooked', 'bushes:berry_pie_cooked', 'bushes:berry_pie_cooked' }, { '', 'bushes:basket_empty', '' }, }, })
mit
circlespainter/FrameworkBenchmarks
frameworks/Lua/lapis/web.lua
72
5957
local lapis = require("lapis") local db = require("lapis.db") local Model do local _obj_0 = require("lapis.db.model") Model = _obj_0.Model end local config do local _obj_0 = require("lapis.config") config = _obj_0.config end local insert do local _obj_0 = table insert = _obj_0.insert end local sort do local _obj_0 = table sort = _obj_0.sort end local min, random do local _obj_0 = math min, random = _obj_0.min, _obj_0.random end local Fortune do local _parent_0 = Model local _base_0 = { } _base_0.__index = _base_0 setmetatable(_base_0, _parent_0.__base) local _class_0 = setmetatable({ __init = function(self, ...) return _parent_0.__init(self, ...) end, __base = _base_0, __name = "Fortune", __parent = _parent_0 }, { __index = function(cls, name) local val = rawget(_base_0, name) if val == nil then return _parent_0[name] else return val end end, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 if _parent_0.__inherited then _parent_0.__inherited(_parent_0, _class_0) end Fortune = _class_0 end local World do local _parent_0 = Model local _base_0 = { } _base_0.__index = _base_0 setmetatable(_base_0, _parent_0.__base) local _class_0 = setmetatable({ __init = function(self, ...) return _parent_0.__init(self, ...) end, __base = _base_0, __name = "World", __parent = _parent_0 }, { __index = function(cls, name) local val = rawget(_base_0, name) if val == nil then return _parent_0[name] else return val end end, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 if _parent_0.__inherited then _parent_0.__inherited(_parent_0, _class_0) end World = _class_0 end local Benchmark do local _parent_0 = lapis.Application local _base_0 = { ["/"] = function(self) return { json = { message = "Hello, World!" } } end, ["/db"] = function(self) local w = World:find(random(1, 10000)) return { json = { id = w.id, randomNumber = w.randomnumber } } end, ["/queries"] = function(self) local num_queries = tonumber(self.params.queries) or 1 if num_queries < 2 then local w = World:find(random(1, 10000)) return { json = { { id = w.id, randomNumber = w.randomnumber } } } end local worlds = { } num_queries = min(500, num_queries) for i = 1, num_queries do local w = World:find(random(1, 10000)) insert(worlds, { id = w.id, randomNumber = w.randomnumber }) end return { json = worlds } end, ["/fortunes"] = function(self) self.fortunes = Fortune:select("") insert(self.fortunes, { id = 0, message = "Additional fortune added at request time." }) sort(self.fortunes, function(a, b) return a.message < b.message end) return { layout = false }, self:html(function() raw('<!DOCTYPE HTML>') return html(function() head(function() return title("Fortunes") end) return body(function() return element("table", function() tr(function() th(function() return text("id") end) return th(function() return text("message") end) end) local _list_0 = self.fortunes for _index_0 = 1, #_list_0 do local fortune = _list_0[_index_0] tr(function() td(function() return text(fortune.id) end) return td(function() return text(fortune.message) end) end) end end) end) end) end) end, ["/update"] = function(self) local num_queries = tonumber(self.params.queries) or 1 if num_queries == 0 then num_queries = 1 end local worlds = { } num_queries = min(500, num_queries) for i = 1, num_queries do local wid = random(1, 10000) local world = World:find(wid) world.randomnumber = random(1, 10000) world:update("randomnumber") insert(worlds, { id = world.id, randomNumber = world.randomnumber }) end if num_queries < 2 then return { json = { worlds[1] } } end return { json = worlds } end, ["/plaintext"] = function(self) return { content_type = "text/plain", layout = false }, "Hello, World!" end } _base_0.__index = _base_0 setmetatable(_base_0, _parent_0.__base) local _class_0 = setmetatable({ __init = function(self, ...) return _parent_0.__init(self, ...) end, __base = _base_0, __name = "Benchmark", __parent = _parent_0 }, { __index = function(cls, name) local val = rawget(_base_0, name) if val == nil then return _parent_0[name] else return val end end, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 if _parent_0.__inherited then _parent_0.__inherited(_parent_0, _class_0) end Benchmark = _class_0 return _class_0 end
bsd-3-clause
mrjon1/kpbot
plugins/img_google.lua
660
3196
do local mime = require("mime") local google_config = load_from_file('data/google.lua') local cache = {} --[[ local function send_request(url) local t = {} local options = { url = url, sink = ltn12.sink.table(t), method = "GET" } local a, code, headers, status = http.request(options) return table.concat(t), code, headers, status end]]-- local function get_google_data(text) local url = "http://ajax.googleapis.com/ajax/services/search/images?" url = url.."v=1.0&rsz=5" url = url.."&q="..URL.escape(text) url = url.."&imgsz=small|medium|large" if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end local res, code = http.request(url) if code ~= 200 then print("HTTP Error code:", code) return nil end local google = json:decode(res) return google end -- Returns only the useful google data to save on cache local function simple_google_table(google) local new_table = {} new_table.responseData = {} new_table.responseDetails = google.responseDetails new_table.responseStatus = google.responseStatus new_table.responseData.results = {} local results = google.responseData.results for k,result in pairs(results) do new_table.responseData.results[k] = {} new_table.responseData.results[k].unescapedUrl = result.unescapedUrl new_table.responseData.results[k].url = result.url end return new_table end local function save_to_cache(query, data) -- Saves result on cache if string.len(query) <= 7 then local text_b64 = mime.b64(query) if not cache[text_b64] then local simple_google = simple_google_table(data) cache[text_b64] = simple_google end end end local function process_google_data(google, receiver, query) if google.responseStatus == 403 then local text = 'ERROR: Reached maximum searches per day' send_msg(receiver, text, ok_cb, false) elseif google.responseStatus == 200 then local data = google.responseData if not data or not data.results or #data.results == 0 then local text = 'Image not found.' send_msg(receiver, text, ok_cb, false) return false end -- Random image from table local i = math.random(#data.results) local url = data.results[i].unescapedUrl or data.results[i].url local old_timeout = http.TIMEOUT or 10 http.TIMEOUT = 5 send_photo_from_url(receiver, url) http.TIMEOUT = old_timeout save_to_cache(query, google) else local text = 'ERROR!' send_msg(receiver, text, ok_cb, false) end end function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local text_b64 = mime.b64(text) local cached = cache[text_b64] if cached then process_google_data(cached, receiver, text) else local data = get_google_data(text) process_google_data(data, receiver, text) end end return { description = "Search image with Google API and sends it.", usage = "!img [term]: Random search an image with Google API.", patterns = { "^!img (.*)$" }, run = run } end
gpl-2.0
medialab-prado/Interactivos-15-Ego
minetest-ego/builtin/mainmenu/tab_multiplayer.lua
2
8128
--Minetest --Copyright (C) 2014 sapier -- --This program is free software; you can redistribute it and/or modify --it under the terms of the GNU Lesser General Public License as published by --the Free Software Foundation; either version 2.1 of the License, or --(at your option) any later version. -- --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --GNU Lesser General Public License for more details. -- --You should have received a copy of the GNU Lesser General Public License along --with this program; if not, write to the Free Software Foundation, Inc., --51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -------------------------------------------------------------------------------- local function get_formspec(tabview, name, tabdata) local render_details = core.is_yes(core.setting_getbool("public_serverlist")) local retval = "label[7.75,-0.15;" .. fgettext("Address / Port :") .. "]" .. "label[7.75,1.05;" .. fgettext("Name / Password :") .. "]" .. "field[8,0.75;3.4,0.5;te_address;;" .. core.formspec_escape(core.setting_get("address")) .. "]" .. "field[11.25,0.75;1.3,0.5;te_port;;" .. core.formspec_escape(core.setting_get("remote_port")) .. "]" .. "checkbox[0,4.85;cb_public_serverlist;" .. fgettext("Public Serverlist") .. ";" .. dump(core.setting_getbool("public_serverlist")) .. "]" if not core.setting_getbool("public_serverlist") then retval = retval .. "button[8,4.9;2,0.5;btn_delete_favorite;" .. fgettext("Delete") .. "]" end retval = retval .. "button[10,4.9;2,0.5;btn_mp_connect;" .. fgettext("Connect") .. "]" .. "field[8,1.95;2.95,0.5;te_name;;" .. core.formspec_escape(core.setting_get("name")) .. "]" .. "pwdfield[10.78,1.95;1.77,0.5;te_pwd;]" .. "box[7.73,2.35;4.3,2.28;#999999]" .. "textarea[8.1,2.4;4.26,2.6;;" if tabdata.fav_selected ~= nil and menudata.favorites[tabdata.fav_selected] ~= nil and menudata.favorites[tabdata.fav_selected].description ~= nil then retval = retval .. core.formspec_escape(menudata.favorites[tabdata.fav_selected].description,true) end retval = retval .. ";]" --favourites if render_details then retval = retval .. "tablecolumns[" .. "color,span=3;" .. "text,align=right;" .. -- clients "text,align=center,padding=0.25;" .. -- "/" "text,align=right,padding=0.25;" .. -- clients_max image_column(fgettext("Creative mode"), "creative") .. ",padding=1;" .. image_column(fgettext("Damage enabled"), "damage") .. ",padding=0.25;" .. image_column(fgettext("PvP enabled"), "pvp") .. ",padding=0.25;" .. "color,span=1;" .. "text,padding=1]" -- name else retval = retval .. "tablecolumns[text]" end retval = retval .. "table[-0.15,-0.1;7.75,5;favourites;" if #menudata.favorites > 0 then retval = retval .. render_favorite(menudata.favorites[1],render_details) for i=2,#menudata.favorites,1 do retval = retval .. "," .. render_favorite(menudata.favorites[i],render_details) end end if tabdata.fav_selected ~= nil then retval = retval .. ";" .. tabdata.fav_selected .. "]" else retval = retval .. ";0]" end return retval end -------------------------------------------------------------------------------- local function main_button_handler(tabview, fields, name, tabdata) if fields["te_name"] ~= nil then gamedata.playername = fields["te_name"] core.setting_set("name", fields["te_name"]) end if fields["favourites"] ~= nil then local event = core.explode_table_event(fields["favourites"]) if event.type == "DCL" then if event.row <= #menudata.favorites then if not is_server_protocol_compat_or_error(menudata.favorites[event.row].proto_min, menudata.favorites[event.row].proto_max) then return true end gamedata.address = menudata.favorites[event.row].address gamedata.port = menudata.favorites[event.row].port gamedata.playername = fields["te_name"] if fields["te_pwd"] ~= nil then gamedata.password = fields["te_pwd"] end gamedata.selected_world = 0 if menudata.favorites ~= nil then gamedata.servername = menudata.favorites[event.row].name gamedata.serverdescription = menudata.favorites[event.row].description end if gamedata.address ~= nil and gamedata.port ~= nil then core.setting_set("address",gamedata.address) core.setting_set("remote_port",gamedata.port) core.start() end end return true end if event.type == "CHG" then if event.row <= #menudata.favorites then local address = menudata.favorites[event.row].address local port = menudata.favorites[event.row].port if address ~= nil and port ~= nil then core.setting_set("address",address) core.setting_set("remote_port",port) end tabdata.fav_selected = event.row end return true end end if fields["key_up"] ~= nil or fields["key_down"] ~= nil then local fav_idx = core.get_table_index("favourites") if fav_idx ~= nil then if fields["key_up"] ~= nil and fav_idx > 1 then fav_idx = fav_idx -1 else if fields["key_down"] and fav_idx < #menudata.favorites then fav_idx = fav_idx +1 end end else fav_idx = 1 end if menudata.favorites == nil or menudata.favorites[fav_idx] == nil then tabdata.fav_selected = 0 return true end local address = menudata.favorites[fav_idx].address local port = menudata.favorites[fav_idx].port if address ~= nil and port ~= nil then core.setting_set("address",address) core.setting_set("remote_port",port) end tabdata.fav_selected = fav_idx return true end if fields["cb_public_serverlist"] ~= nil then core.setting_set("public_serverlist", fields["cb_public_serverlist"]) if core.setting_getbool("public_serverlist") then asyncOnlineFavourites() else menudata.favorites = core.get_favorites("local") end tabdata.fav_selected = nil return true end if fields["btn_delete_favorite"] ~= nil then local current_favourite = core.get_table_index("favourites") if current_favourite == nil then return end core.delete_favorite(current_favourite) menudata.favorites = order_favorite_list(core.get_favorites()) tabdata.fav_selected = nil core.setting_set("address","") core.setting_set("remote_port","30000") return true end if (fields["btn_mp_connect"] ~= nil or fields["key_enter"] ~= nil) and fields["te_address"] ~= nil and fields["te_port"] ~= nil then gamedata.playername = fields["te_name"] gamedata.password = fields["te_pwd"] gamedata.address = fields["te_address"] gamedata.port = fields["te_port"] local fav_idx = core.get_table_index("favourites") if fav_idx ~= nil and fav_idx <= #menudata.favorites and menudata.favorites[fav_idx].address == fields["te_address"] and menudata.favorites[fav_idx].port == fields["te_port"] then gamedata.servername = menudata.favorites[fav_idx].name gamedata.serverdescription = menudata.favorites[fav_idx].description if not is_server_protocol_compat_or_error(menudata.favorites[fav_idx].proto_min, menudata.favorites[fav_idx].proto_max)then return true end else gamedata.servername = "" gamedata.serverdescription = "" end gamedata.selected_world = 0 core.setting_set("address", fields["te_address"]) core.setting_set("remote_port",fields["te_port"]) core.start() return true end return false end local function on_change(type,old_tab,new_tab) if type == "LEAVE" then return end if core.setting_getbool("public_serverlist") then asyncOnlineFavourites() else menudata.favorites = core.get_favorites("local") end end -------------------------------------------------------------------------------- tab_multiplayer = { name = "multiplayer", caption = fgettext("Client"), cbf_formspec = get_formspec, cbf_button_handler = main_button_handler, on_change = on_change }
mit
EliHar/Pattern_recognition
torch1/extra/cudnn/SpatialCrossEntropyCriterion.lua
4
2958
require 'nn' local SpatialCrossEntropyCriterion, parent = torch.class('cudnn.SpatialCrossEntropyCriterion', 'nn.Criterion') --[[ This criterion does the SpatialCrossEntropyCriterion across the feature dimension for a N-channel image of HxW in size. It only supports mini-batches (4D input, 3D target) It does a LogSoftMax on the input (over the channel dimension), so no LogSoftMax is needed in the network at the end input = batchSize x nClasses x H x W target = batchSize x H x W ]]-- function SpatialCrossEntropyCriterion:__init(weights) parent.__init(self) self.slsm = cudnn.SpatialLogSoftMax() self.nll = nn.ClassNLLCriterion(weights) self.sizeAverage = true end local transpose = function(input) input = input:transpose(2,4):transpose(2,3):contiguous() -- bdhw -> bwhd -> bhwd input = input:view(input:size(1)*input:size(2)*input:size(3), input:size(4)) return input end local transposeBack = function(input, originalInput) input = input:view(originalInput:size(1), originalInput:size(3), originalInput:size(4), originalInput:size(2)) input = input:transpose(2,4):transpose(3,4):contiguous() -- bhwd -> bdwh -> bdhw return input end function SpatialCrossEntropyCriterion:updateOutput(input, target) assert(input:dim() == 4, 'mini-batch supported only') assert(target:dim() == 3, 'mini-batch supported only') assert(input:size(1) == target:size(1), 'input and target should be of same size') assert(input:size(3) == target:size(2), 'input and target should be of same size') assert(input:size(4) == target:size(3), 'input and target should be of same size') -- apply SpatialLogSoftMax to input self.slsm:updateOutput(input) -- Update submodule sizeAverage to make it consistent. self.nll.sizeAverage = self.sizeAverage -- fold the height and width dims into the mini-batch dim. self.nll:updateOutput(transpose(self.slsm.output), target:view(-1)) self.output = self.nll.output return self.output end function SpatialCrossEntropyCriterion:updateGradInput(input, target) assert(input:dim() == 4, 'mini-batch supported only') assert(target:dim() == 3, 'mini-batch supported only') assert(input:size(1) == target:size(1), 'input and target should be of same size') assert(input:size(3) == target:size(2), 'input and target should be of same size') assert(input:size(4) == target:size(3), 'input and target should be of same size') self.nll:updateGradInput(transpose(self.slsm.output), target:view(-1)) -- unfold the height and width dims back self.slsm:updateGradInput(input, transposeBack(self.nll.gradInput, input)) self.gradInput = self.slsm.gradInput return self.gradInput end function SpatialCrossEntropyCriterion:type(type) if type then self.nll:type(type) self.slsm:type(type) end parent.type(self, type) return self end
mit
cloudkick/ck-agent
extern/luasocket/src/tp.lua
146
3608
----------------------------------------------------------------------------- -- Unified SMTP/FTP subsystem -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: tp.lua,v 1.22 2006/03/14 09:04:15 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local string = require("string") local socket = require("socket") local ltn12 = require("ltn12") module("socket.tp") ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- TIMEOUT = 60 ----------------------------------------------------------------------------- -- Implementation ----------------------------------------------------------------------------- -- gets server reply (works for SMTP and FTP) local function get_reply(c) local code, current, sep local line, err = c:receive() local reply = line if err then return nil, err end code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) if not code then return nil, "invalid server reply" end if sep == "-" then -- reply is multiline repeat line, err = c:receive() if err then return nil, err end current, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) reply = reply .. "\n" .. line -- reply ends with same code until code == current and sep == " " end return code, reply end -- metatable for sock object local metat = { __index = {} } function metat.__index:check(ok) local code, reply = get_reply(self.c) if not code then return nil, reply end if base.type(ok) ~= "function" then if base.type(ok) == "table" then for i, v in base.ipairs(ok) do if string.find(code, v) then return base.tonumber(code), reply end end return nil, reply else if string.find(code, ok) then return base.tonumber(code), reply else return nil, reply end end else return ok(base.tonumber(code), reply) end end function metat.__index:command(cmd, arg) if arg then return self.c:send(cmd .. " " .. arg.. "\r\n") else return self.c:send(cmd .. "\r\n") end end function metat.__index:sink(snk, pat) local chunk, err = c:receive(pat) return snk(chunk, err) end function metat.__index:send(data) return self.c:send(data) end function metat.__index:receive(pat) return self.c:receive(pat) end function metat.__index:getfd() return self.c:getfd() end function metat.__index:dirty() return self.c:dirty() end function metat.__index:getcontrol() return self.c end function metat.__index:source(source, step) local sink = socket.sink("keep-open", self.c) local ret, err = ltn12.pump.all(source, sink, step or ltn12.pump.step) return ret, err end -- closes the underlying c function metat.__index:close() self.c:close() return 1 end -- connect with server and return c object function connect(host, port, timeout, create) local c, e = (create or socket.tcp)() if not c then return nil, e end c:settimeout(timeout or TIMEOUT) local r, e = c:connect(host, port) if not r then c:close() return nil, e end return base.setmetatable({c = c}, metat) end
apache-2.0
sanjeevtripurari/hue
tools/wrk-scripts/lib/uri-f570bf7.lua
22
6368
-- The MIT License (MIT) -- -- Copyright (c) 2014 Cyril David <cyx@cyx.is> -- Copyright (c) 2011-2013 Bertrand Mansion <bmansion@mamasam.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- == list of known and common scheme ports -- -- @see http://www.iana.org/assignments/uri-schemes.html -- local SERVICES = { acap = 674, cap = 1026, dict = 2628, ftp = 21, gopher = 70, http = 80, https = 443, iax = 4569, icap = 1344, imap = 143, ipp = 631, ldap = 389, mtqp = 1038, mupdate = 3905, news = 2009, nfs = 2049, nntp = 119, rtsp = 554, sip = 5060, snmp = 161, telnet = 23, tftp = 69, vemmi = 575, afs = 1483, jms = 5673, rsync = 873, prospero = 191, videotex = 516 } local LEGAL = { ["-"] = true, ["_"] = true, ["."] = true, ["!"] = true, ["~"] = true, ["*"] = true, ["'"] = true, ["("] = true, [")"] = true, [":"] = true, ["@"] = true, ["&"] = true, ["="] = true, ["+"] = true, ["$"] = true, [","] = true, [";"] = true -- can be used for parameters in path } -- aggressive caching of methods local gsub = string.gsub local char = string.char local byte = string.byte local upper = string.upper local lower = string.lower local format = string.format -- forward declaration of helper utilities local util = {} local function decode(str) local str = gsub(str, "+", " ") return (gsub(str, "%%(%x%x)", function(c) return char(tonumber(c, 16)) end)) end local function encode(str) return (gsub(str, "([^A-Za-z0-9%_%.%-%~])", function(v) return upper(format("%%%02x", byte(v))) end)) end -- Build a URL given a table with the fields: -- -- - scheme -- - user -- - password -- - host -- - port -- - path -- - query -- - fragment -- -- Example: -- -- local url = uri.build({ -- scheme = "http", -- host = "example.com", -- path = "/some/path" -- }) -- -- assert(url == "http://example.com/some/path") -- local function build(uri) local url = "" if uri.path then local path = uri.path gsub(path, "([^/]+)", function (s) return util.encode_segment(s) end) url = url .. tostring(path) end if uri.query then local qstring = tostring(uri.query) if qstring ~= "" then url = url .. "?" .. qstring end end if uri.host then local authority = uri.host if uri.port and uri.scheme and SERVICES[uri.scheme] ~= uri.port then authority = authority .. ":" .. uri.port end local userinfo if uri.user and uri.user ~= "" then userinfo = encode(uri.user) if uri.password then userinfo = userinfo .. ":" .. encode(uri.password) end end if userinfo and userinfo ~= "" then authority = userinfo .. "@" .. authority end if authority then if url ~= "" then url = "//" .. authority .. "/" .. gsub(url, "^/+", "") else url = "//" .. authority end end end if uri.scheme then url = uri.scheme .. ":" .. url end if uri.fragment then url = url .. "#" .. uri.fragment end return url end -- Parse the url into the designated parts. -- -- Depending on the url, the following parts will be available: -- -- - scheme -- - userinfo -- - user -- - password -- - authority -- - host -- - port -- - path -- - query -- - fragment -- -- Usage: -- -- local u = uri.parse("http://john:monkey@example.com/some/path#h1") -- -- assert(u.host == "example.com") -- assert(u.scheme == "http") -- assert(u.user == "john") -- assert(u.password == "monkey") -- assert(u.path == "/some/path") -- assert(u.fragment == "h1") -- local function parse(url) local uri = { query = nil } util.set_authority(uri, "") local url = tostring(url or "") url = gsub(url, "#(.*)$", function(v) uri.fragment = v return "" end) url = gsub(url, "^([%w][%w%+%-%.]*)%:", function(v) uri.scheme = lower(v) return "" end) url = gsub(url, "%?(.*)", function(v) uri.query = v return "" end) url = gsub(url, "^//([^/]*)", function(v) util.set_authority(uri, v) return "" end) uri.path = decode(url) return uri end function util.encode_segment(s) local function encode_legal(c) if LEGAL[c] then return c end return encode(c) end return gsub(s, "([^a-zA-Z0-9])", encode_legal) end -- set the authority part of the url -- -- The authority is parsed to find the user, password, port and host if available. -- @param authority The string representing the authority -- @return a string with what remains after the authority was parsed function util.set_authority(uri, authority) uri.authority = authority uri.port = nil uri.host = nil uri.userinfo = nil uri.user = nil uri.password = nil authority = gsub(authority, "^([^@]*)@", function(v) uri.userinfo = decode(v) return "" end) authority = gsub(authority, "^%[[^%]]+%]", function(v) -- ipv6 uri.host = v return "" end) authority = gsub(authority, ":([^:]*)$", function(v) uri.port = tonumber(v) return "" end) if authority ~= "" and not uri.host then uri.host = lower(authority) end if uri.userinfo then local userinfo = uri.userinfo userinfo = gsub(userinfo, ":([^:]*)$", function(v) uri.password = v return "" end) uri.user = userinfo end return authority end local uri = { build = build, parse = parse, encode = encode, decode = decode } return uri
apache-2.0
Mehranhpr/spam
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
abbasgh12345/Abbas01
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
AnahitaParsa/telemax
plugins/time.lua
771
2865
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Displays the local time in an area", usage = "!time [area]: Displays the local time in that area", patterns = {"^!time (.*)$"}, run = run }
gpl-2.0
dromozoa/dromozoa-regexp
dromozoa/regexp/automaton.lua
3
5463
-- Copyright (C) 2015 Tomoyuki Fujimori <moyu@dromozoa.com> -- -- This file is part of dromozoa-regexp. -- -- dromozoa-regexp is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- dromozoa-regexp is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with dromozoa-regexp. If not, see <http://www.gnu.org/licenses/>. local apply = require "dromozoa.commons.apply" local bitset = require "dromozoa.commons.bitset" local clone = require "dromozoa.commons.clone" local graph = require "dromozoa.graph" local locale = require "dromozoa.regexp.locale" local compile = require "dromozoa.regexp.automaton.compile" local decompile = require "dromozoa.regexp.automaton.decompile" local graphviz_visitor = require "dromozoa.regexp.automaton.graphviz_visitor" local normalize_assertions = require "dromozoa.regexp.automaton.normalize_assertions" local powerset_construction = require "dromozoa.regexp.automaton.powerset_construction" local product_construction = require "dromozoa.regexp.automaton.product_construction" local tokens = require "dromozoa.regexp.automaton.tokens" local to_ast = require "dromozoa.regexp.automaton.to_ast" local function collect(self, key) local count = self:count_vertex(key) if count == 0 then return nil elseif count == 1 then return apply(self:each_vertex(key)) else local u = self:create_vertex() local token for v in self:each_vertex(key) do token = tokens.union(token, v[key]) v[key] = nil if key == "start" then self:create_edge(u, v) else self:create_edge(v, u) end end u[key] = token return u end end local class = {} function class.decompile(data) return decompile(data, class()) end function class:start() if self:count_vertex("start") > 1 then error("only one start state allowed") end return apply(self:each_vertex("start")) end function class:can_minimize() local token for u in self:each_vertex("accept") do if token == nil then token = u.accept elseif token ~= u.accept then return false end end return true end function class:collect_starts() return collect(self, "start") end function class:collect_accepts() return collect(self, "accept") end function class:reverse() local that = class() local map = {} for a in self:each_vertex() do local b = that:create_vertex() map[a.id] = b.id b.start = a.accept b.accept = a.start end for a in self:each_edge() do that:create_edge(map[a.vid], map[a.uid]).condition = a.condition end that:collect_starts() return that end function class:remove_unreachables() local visitor = { finish_edge = function (_, e) if e.color == nil then e.color = 1 else e.color = 2 end end; } self:start():dfs(visitor) for v in self:each_vertex("accept") do v:dfs(visitor, "v") end for e in self:each_edge() do if e.color ~= 2 then e:remove() end end for u in self:each_vertex() do if u:is_isolated() then u:remove() end end self:clear_edge_properties("color") return self end function class:ignore_case() local that = clone(self) for e in that:each_edge("condition") do local condition = bitset() for k in e.condition:each() do condition:set(locale.toupper(k)):set(locale.tolower(k)) end e.condition = condition end return that:optimize() end function class:normalize_assertions() return normalize_assertions(self):apply() end function class:to_dfa() return powerset_construction(self, class()):apply() end function class:minimize() return self:reverse():to_dfa():reverse():to_dfa() end function class:optimize() if self:can_minimize() then return self:minimize() else return self:remove_unreachables():to_dfa() end end function class:branch(that) self:merge(that) self:collect_starts() return self:optimize() end function class:concat(that) local u = self:collect_accepts() u.accept = nil local map = self:merge(that) local v = self:get_vertex(map[that:start().id]) v.start = nil self:create_edge(u, v) return self:optimize() end function class:set_intersection(that) return product_construction(class()):apply(self, that, tokens.intersection):optimize() end function class:set_union(that) return product_construction(class()):apply(self, that, tokens.union):optimize() end function class:set_difference(that) return product_construction(class()):apply(self, that, tokens.difference):optimize() end function class:compile() return compile(self) end function class:to_ast() return to_ast(clone(self), class.super.syntax_tree()):apply() end function class:to_ere() return self:to_ast():denormalize():to_ere(true) end function class:write_graphviz(out) return graph.write_graphviz(self, out, graphviz_visitor()) end local metatable = { __index = class; } return setmetatable(class, { __index = graph; __call = function () return setmetatable(class.new(), metatable) end; })
gpl-3.0
rlcevg/Zero-K
effects/grav.lua
17
3193
-- grav return { ["grav"] = { drag = { air = true, class = [[CSimpleParticleSystem]], ground = true, water = true, properties = { airdrag = 1, colormap = [[1 .5 1 .1 0 0 0 0]], directional = true, emitrot = 0, emitrotspread = 120, emitvector = [[0,1,0]], gravity = [[0, 0, 0]], numparticles = 3, particlelife = 8, particlelifespread = 3, particlesize = 160, particlesizespread = 80, particlespeed = .1, particlespeedspread = 0, pos = [[0, 1.0, 0]], sizegrowth = -16, sizemod = 1, texture = [[chargeparticles]], }, }, --flash = { -- air = true, -- class = [[CSimpleParticleSystem]], -- count = 1, -- ground = true, -- water = true, -- properties = { -- airdrag = 0, -- colormap = [[0 0 0 .3 0 0 0 0]], -- directional = false, -- emitrot = 0, -- emitrotspread = 180, -- emitvector = [[0, 1, 0]], -- gravity = [[0, 0, 0]], -- numparticles = 1, -- particlelife = 15, -- particlelifespread = 8, -- particlesize = 120, -- particlesizespread = 60, -- particlespeed = 0, -- particlespeedspread = 0, -- pos = [[0, 0, 0]], -- sizegrowth = 1, -- sizemod = 1, -- texture = [[burncircle]], -- }, --}, sphere = { air = true, class = [[CSpherePartSpawner]], count = 1, ground = true, underwater = 1, water = true, properties = { alpha = 1, color = [[0,0,0]], expansionspeed = 7, ttl = 14, }, }, -- flashalt = { -- air = true, -- class = [[CBitmapMuzzleFlame]], -- count = 1, -- ground = true, -- water = true, -- properties = { -- colormap = [[0 0 0 .3 0 0 0 0]], -- dir = [[0 1 0]], -- fronttexture = [[burncircle]], -- frontoffset = 0, -- length = 100, -- pos = [[0, 0, 0]], -- sidetexture = [[burncircle]], -- size = 100, -- sizegrowth = 0, -- ttl = 15, -- }, -- }, -- groundflash = { -- air = true, -- circlealpha = 0.8, -- circlegrowth = 8, -- flashalpha = 0.8, -- flashsize = 140, -- ground = true, -- ttl = 17, -- water = true, -- color = { -- [1] = 0.1, -- [2] = 0.1, -- [3] = 0.1, -- }, -- }, }, }
gpl-2.0
EliHar/Pattern_recognition
torch1/pkg/torch/Tensor.lua
8
16317
-- additional methods for Storage local Storage = {} -- additional methods for Tensor local Tensor = {} -- types local types = {'Byte', 'Char', 'Short', 'Int', 'Long', 'Float', 'Double'} -- Lua 5.2 compatibility local log10 = math.log10 or function(x) return math.log(x, 10) end -- tostring() functions for Tensor and Storage local function Storage__printformat(self) if self:size() == 0 then return "", nil, 0 end local intMode = true local type = torch.typename(self) -- if type == 'torch.FloatStorage' or type == 'torch.DoubleStorage' then for i=1,self:size() do if self[i] ~= math.ceil(self[i]) then intMode = false break end end -- end local tensor = torch.DoubleTensor(torch.DoubleStorage(self:size()):copy(self), 1, self:size()):abs() local expMin = tensor:min() if expMin ~= 0 then expMin = math.floor(log10(expMin)) + 1 else expMin = 1 end local expMax = tensor:max() if expMax ~= 0 then expMax = math.floor(log10(expMax)) + 1 else expMax = 1 end local format local scale local sz if intMode then if expMax > 9 then format = "%11.4e" sz = 11 else format = "%SZd" sz = expMax + 1 end else if expMax-expMin > 4 then format = "%SZ.4e" sz = 11 if math.abs(expMax) > 99 or math.abs(expMin) > 99 then sz = sz + 1 end else if expMax > 5 or expMax < 0 then format = "%SZ.4f" sz = 7 scale = math.pow(10, expMax-1) else format = "%SZ.4f" if expMax == 0 then sz = 7 else sz = expMax+6 end end end end format = string.gsub(format, 'SZ', sz) if scale == 1 then scale = nil end return format, scale, sz end function Storage.__tostring__(self) local strt = {} local format,scale = Storage__printformat(self) if format:sub(2,4) == 'nan' then format = '%f' end if scale then table.insert(strt, string.format('%g', scale) .. ' *\n') for i = 1,self:size() do table.insert(strt, string.format(format, self[i]/scale) .. '\n') end else for i = 1,self:size() do table.insert(strt, string.format(format, self[i]) .. '\n') end end table.insert(strt, '[' .. torch.typename(self) .. ' of size ' .. self:size() .. ']\n') local str = table.concat(strt) return str end for _,type in ipairs(types) do local metatable = torch.getmetatable('torch.' .. type .. 'Storage') for funcname, func in pairs(Storage) do rawset(metatable, funcname, func) end end local function Tensor__printMatrix(self, indent) local format,scale,sz = Storage__printformat(self:storage()) if format:sub(2,4) == 'nan' then format = '%f' end -- print('format = ' .. format) scale = scale or 1 indent = indent or '' local strt = {indent} local nColumnPerLine = math.floor((80-#indent)/(sz+1)) -- print('sz = ' .. sz .. ' and nColumnPerLine = ' .. nColumnPerLine) local firstColumn = 1 local lastColumn = -1 while firstColumn <= self:size(2) do if firstColumn + nColumnPerLine - 1 <= self:size(2) then lastColumn = firstColumn + nColumnPerLine - 1 else lastColumn = self:size(2) end if nColumnPerLine < self:size(2) then if firstColumn ~= 1 then table.insert(strt, '\n') end table.insert(strt, 'Columns ' .. firstColumn .. ' to ' .. lastColumn .. '\n' .. indent) end if scale ~= 1 then table.insert(strt, string.format('%g', scale) .. ' *\n ' .. indent) end for l=1,self:size(1) do local row = self:select(1, l) for c=firstColumn,lastColumn do table.insert(strt, string.format(format, row[c]/scale)) if c == lastColumn then table.insert(strt, '\n') if l~=self:size(1) then if scale ~= 1 then table.insert(strt, indent .. ' ') else table.insert(strt, indent) end end else table.insert(strt, ' ') end end end firstColumn = lastColumn + 1 end local str = table.concat(strt) return str end local function Tensor__printTensor(self) local counter = torch.LongStorage(self:nDimension()-2) local strt = {''} local finished counter:fill(1) counter[1] = 0 while true do for i=1,self:nDimension()-2 do counter[i] = counter[i] + 1 if counter[i] > self:size(i) then if i == self:nDimension()-2 then finished = true break end counter[i] = 1 else break end end if finished then break end -- print(counter) if #strt > 1 then table.insert(strt, '\n') end table.insert(strt, '(') local tensor = self for i=1,self:nDimension()-2 do tensor = tensor:select(1, counter[i]) table.insert(strt, counter[i] .. ',') end table.insert(strt, '.,.) = \n') table.insert(strt, Tensor__printMatrix(tensor, ' ')) end return table.concat(strt) end function Tensor.__tostring__(self) local strt = {''} if self:nDimension() == 0 then table.insert(strt, '[' .. torch.typename(self) .. ' with no dimension]\n') else local tensor = torch.DoubleTensor():resize(self:size()):copy(self) if tensor:nDimension() == 1 then local format,scale,sz = Storage__printformat(tensor:storage()) if format:sub(2,4) == 'nan' then format = '%f' end if scale then table.insert(strt, string.format('%g', scale) .. ' *\n') for i = 1,tensor:size(1) do table.insert(strt, string.format(format, tensor[i]/scale) .. '\n') end else for i = 1,tensor:size(1) do table.insert(strt, string.format(format, tensor[i]) .. '\n') end end table.insert(strt, '[' .. torch.typename(self) .. ' of size ' .. tensor:size(1) .. ']\n') elseif tensor:nDimension() == 2 then table.insert(strt, Tensor__printMatrix(tensor)) table.insert(strt, '[' .. torch.typename(self) .. ' of size ' .. tensor:size(1) .. 'x' .. tensor:size(2) .. ']\n') else table.insert(strt, Tensor__printTensor(tensor)) table.insert(strt, '[' .. torch.typename(self) .. ' of size ') for i=1,tensor:nDimension() do table.insert(strt, tensor:size(i)) if i ~= tensor:nDimension() then table.insert(strt, 'x') end end table.insert(strt, ']\n') end end return table.concat(strt) end function Tensor.type(self,type) local current = torch.typename(self) if not type then return current end if type ~= current then local new = torch.getmetatable(type).new() if self:nElement() > 0 then new:resize(self:size()):copy(self) end return new else return self end end function Tensor.typeAs(self,tensor) return self:type(tensor:type()) end function Tensor.byte(self) return self:type('torch.ByteTensor') end function Tensor.char(self) return self:type('torch.CharTensor') end function Tensor.short(self) return self:type('torch.ShortTensor') end function Tensor.int(self) return self:type('torch.IntTensor') end function Tensor.long(self) return self:type('torch.LongTensor') end function Tensor.float(self) return self:type('torch.FloatTensor') end function Tensor.double(self) return self:type('torch.DoubleTensor') end function Tensor.real(self) return self:type(torch.getdefaulttensortype()) end function Tensor.expand(result,tensor,...) -- get sizes local sizes = {...} local t = torch.type(tensor) if (t == 'number' or t == 'torch.LongStorage') then table.insert(sizes,1,tensor) tensor = result result = tensor.new() end -- check type local size if torch.type(sizes[1])=='torch.LongStorage' then size = sizes[1] else size = torch.LongStorage(#sizes) for i,s in ipairs(sizes) do size[i] = s end end -- get dimensions local tensor_dim = tensor:dim() local tensor_stride = tensor:stride() local tensor_size = tensor:size() -- check nb of dimensions if #size ~= tensor:dim() then error('the number of dimensions provided must equal tensor:dim()') end -- create a new geometry for tensor: for i = 1,tensor_dim do if tensor_size[i] == 1 then tensor_size[i] = size[i] tensor_stride[i] = 0 elseif tensor_size[i] ~= size[i] then error('incorrect size: only supporting singleton expansion (size=1)') end end -- create new view, with singleton expansion: result:set(tensor:storage(), tensor:storageOffset(), tensor_size, tensor_stride) return result end torch.expand = Tensor.expand function Tensor.expandAs(result,tensor,template) if template then return result:expand(tensor,template:size()) end return result:expand(tensor:size()) end torch.expandAs = Tensor.expandAs function Tensor.repeatTensor(result,tensor,...) -- get sizes local sizes = {...} local t = torch.type(tensor) if (t == 'number' or t == 'torch.LongStorage') then table.insert(sizes,1,tensor) tensor = result result = tensor.new() end -- if not contiguous, then force the tensor to be contiguous if not tensor:isContiguous() then tensor = tensor:clone() end -- check type local size if torch.type(sizes[1])=='torch.LongStorage' then size = sizes[1] else size = torch.LongStorage(#sizes) for i,s in ipairs(sizes) do size[i] = s end end if size:size() < tensor:dim() then error('Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor') end local xtensor = tensor.new():set(tensor) local xsize = xtensor:size():totable() for i=1,size:size()-tensor:dim() do table.insert(xsize,1,1) end size = torch.DoubleTensor(xsize):cmul(torch.DoubleTensor(size:totable())):long():storage() xtensor:resize(torch.LongStorage(xsize)) result:resize(size) local urtensor = result.new(result) for i=1,xtensor:dim() do urtensor = urtensor:unfold(i,xtensor:size(i),xtensor:size(i)) end for i=1,urtensor:dim()-xtensor:dim() do table.insert(xsize,1,1) end xtensor:resize(torch.LongStorage(xsize)) local xxtensor = xtensor:expandAs(urtensor) urtensor:copy(xxtensor) return result end torch.repeatTensor = Tensor.repeatTensor --- One of the size elements can be -1, --- a new LongStorage is then returned. --- The length of the unspecified dimension --- is infered from the number of remaining elements. local function specifyFully(size, nElements) local nCoveredElements = 1 local remainingDim = nil local sizes = size:totable() for i = 1, #sizes do local wantedDimSize = sizes[i] if wantedDimSize == -1 then if remainingDim then error("Only one of torch.view dimensions can be -1.") end remainingDim = i else nCoveredElements = nCoveredElements * wantedDimSize end end if not remainingDim then return size end assert(nElements % nCoveredElements == 0, "The number of covered elements is not a multiple of all elements.") local copy = torch.LongStorage(sizes) copy[remainingDim] = nElements / nCoveredElements return copy end -- TODO : This should be implemented in TH and and wrapped. function Tensor.view(result, src, ...) local size = ... local view, tensor local function istensor(tensor) return torch.typename(tensor) and torch.typename(tensor):find('torch.*Tensor') end local function isstorage(storage) return torch.typename(storage) and torch.typename(storage) == 'torch.LongStorage' end if istensor(result) and istensor(src) and type(size) == 'number' then size = torch.LongStorage{...} view = result tensor = src elseif istensor(result) and istensor(src) and isstorage(size) then size = size view = result tensor = src elseif istensor(result) and isstorage(src) and size == nil then size = src tensor = result view = tensor.new() elseif istensor(result) and type(src) == 'number' then size = {...} table.insert(size,1,src) size = torch.LongStorage(size) tensor = result view = tensor.new() else local t1 = 'torch.Tensor, torch.Tensor, number [, number ]*' local t2 = 'torch.Tensor, torch.Tensor, torch.LongStorage' local t3 = 'torch.Tensor, torch.LongStorage' local t4 = 'torch.Tensor, number [, number ]*' error(string.format('torch.view, expected (%s) or\n (%s) or\n (%s)\n or (%s)', t1, t2, t3, t4)) end local origNElement = tensor:nElement() size = specifyFully(size, origNElement) assert(tensor:isContiguous(), "expecting a contiguous tensor") view:set(tensor:storage(), tensor:storageOffset(), size) if view:nElement() ~= origNElement then local inputSize = table.concat(tensor:size():totable(), "x") local outputSize = table.concat(size:totable(), "x") error(string.format("Wrong size for view. Input size: %s. Output size: %s", inputSize, outputSize)) end return view end torch.view = Tensor.view function Tensor.viewAs(result, src, template) if template and torch.typename(template) then return result:view(src, template:size()) elseif template == nil then template = src src = result result = src.new() return result:view(src, template:size()) else local t1 = 'torch.Tensor, torch.Tensor, torch.LongStorage' local t2 = 'torch.Tensor, torch.LongStorage' error(string.format('expecting (%s) or (%s)', t1, t2)) end end torch.viewAs = Tensor.viewAs function Tensor.split(result, tensor, splitSize, dim) if torch.type(result) ~= 'table' then dim = splitSize splitSize = tensor tensor = result result = {} else -- empty existing result table before using it for k,v in pairs(result) do result[k] = nil end end dim = dim or 1 local start = 1 while start <= tensor:size(dim) do local size = math.min(splitSize, tensor:size(dim) - start + 1) local split = tensor:narrow(dim, start, size) table.insert(result, split) start = start + size end return result end torch.split = Tensor.split function Tensor.chunk(result, tensor, nChunk, dim) if torch.type(result) ~= 'table' then dim = nChunk nChunk = tensor tensor = result result = {} end dim = dim or 1 local splitSize = math.ceil(tensor:size(dim)/nChunk) return torch.split(result, tensor, splitSize, dim) end torch.chunk = Tensor.chunk function Tensor.totable(tensor) local result = {} local dim = tensor:dim() if dim == 1 then tensor:apply(function(i) table.insert(result, i) end) elseif dim > 0 then for i = 1, tensor:size(1) do table.insert(result, tensor[i]:totable()) end end return result end torch.totable = Tensor.totable function Tensor.permute(tensor, ...) local perm = {...} local nDims = tensor:dim() assert(#perm == nDims, 'Invalid permutation') local j for i, p in ipairs(perm) do if p ~= i and p ~= 0 then j = i repeat assert(0 < perm[j] and perm[j] <= nDims, 'Invalid permutation') tensor = tensor:transpose(j, perm[j]) j, perm[j] = perm[j], 0 until perm[j] == i perm[j] = j end end return tensor end torch.permute = Tensor.permute for _,type in ipairs(types) do local metatable = torch.getmetatable('torch.' .. type .. 'Tensor') for funcname, func in pairs(Tensor) do rawset(metatable, funcname, func) end end
mit
rlcevg/Zero-K
units/chickenwurm.lua
3
4323
unitDef = { unitname = [[chickenwurm]], name = [[Wurm]], description = [[Burrowing Flamer (Assault/Riot)]], acceleration = 0.36, brakeRate = 0.205, buildCostEnergy = 0, buildCostMetal = 0, builder = false, buildPic = [[chickenwurm.png]], buildTime = 350, canAttack = true, canGuard = true, canMove = true, canPatrol = true, category = [[LAND]], customParams = { description_fr = [[Ver d'assaut souterrain]], description_de = [[Grabender Flammenwerfer (Sturm/Riot)]], description_pl = [[Zakopany miotacz ognia]], fireproof = 1, helptext = [[The Wurm "burrows" under the surface of the ground, revealing itself to hurl a ball of fire that immolates a large swathe of terrain. It can climb cliffs and surprise defense turrets, but is weak to assaults.]], helptext_fr = [[Ces poulets tenant partiellement de la taupe ont une particularité : ils savent mettre le feu où qu'ils aillent.]], helptext_de = [[Der Wurm "gräbt" sich unter die Bodenoberfläche und zeigt sich nur, wenn er Feuerbälle, die große Schneisen in das Gelände brennen, schleudert.]], helptext_pl = [[Wurm zagrzebuje sie pod ziemia i moze w ten sposob poruszac sie. Wychodzac z niej, ciska kule ognia, ktore podpalaja okolice. Moze tez wspinac sie na strome wzniesienia. Jego slabym punktem jest niska wytrzymalosc.]], }, explodeAs = [[CORPYRO_PYRO_DEATH]], footprintX = 4, footprintZ = 4, iconType = [[spidergeneric]], idleAutoHeal = 10, idleTime = 600, leaveTracks = true, mass = 231, maxDamage = 1500, maxSlope = 90, maxVelocity = 1.8, maxWaterDepth = 5000, minCloakDistance = 75, movementClass = [[ATKBOT3]], noAutoFire = false, noChaseCategory = [[TERRAFORM FIXEDWING GUNSHIP SATELLITE SUB STUPIDTARGET MINE]], objectName = [[chickenwurm.s3o]], power = 350, script = [[chickenwurm.lua]], seismicSignature = 4, selfDestructAs = [[CORPYRO_PYRO_DEATH]], sfxtypes = { explosiongenerators = { [[custom:blood_spray]], [[custom:blood_explode]], [[custom:dirt]], }, }, side = [[THUNDERBIRDS]], sightDistance = 384, smoothAnim = true, stealth = true, turnRate = 806, upright = false, workerTime = 0, weapons = { { def = [[NAPALM]], badTargetCategory = [[GUNSHIP]], mainDir = [[0 0 1]], maxAngleDif = 120, onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT GUNSHIP SHIP HOVER]], }, }, weaponDefs = { NAPALM = { name = [[Napalm Blob]], areaOfEffect = 128, burst = 1, burstrate = 0.01, craterBoost = 0, craterMult = 0, customParams = { setunitsonfire = "1", burntime = 180, area_damage = 1, area_damage_radius = 128, area_damage_dps = 30, area_damage_duration = 20, }, damage = { default = 50, planes = 50, subs = 2.5, }, explosionGenerator = [[custom:napalm_firewalker]], fireStarter = 120, impulseBoost = 0, impulseFactor = 0.2, intensity = 0.7, interceptedByShieldType = 1, range = 300, reloadtime = 6, rgbColor = [[0.8 0.3 0]], size = 4.5, sizeDecay = 0, soundHit = [[chickens/acid_hit]], soundStart = [[chickens/acid_fire]], sprayAngle = 1024, tolerance = 5000, turret = true, weaponTimer = 0.2, weaponType = [[Cannon]], weaponVelocity = 200, }, }, } return lowerkeys({ chickenwurm = unitDef })
gpl-2.0
avataronline/avatarclient
modules/client/client.lua
1
3361
local musicFilename = "/sounds/startup" local musicChannel = g_sounds.getChannel(1) function setMusic(filename) musicFilename = filename if not g_game.isOnline() then musicChannel:stop() musicChannel:enqueue(musicFilename, 3) end end function reloadScripts() g_textures.clearCache() g_modules.reloadModules() local script = '/' .. g_app.getCompactName() .. 'rc.lua' if g_resources.fileExists(script) then dofile(script) end local message = tr('All modules and scripts were reloaded.') modules.game_textmessage.displayGameMessage(message) end function startup() -- Play startup music (The Silver Tree, by Mattias Westlund) musicChannel:enqueue(musicFilename, 3) connect(g_game, { onGameStart = function() g_sounds.stopAll() end }) connect(g_game, { onGameEnd = function() modules.game_interface.getMapPanel():setMapShader(g_shaders.getDefaultMapShader()) g_sounds.stopAll() musicChannel:enqueue(musicFilename, 3) end }) -- Check for startup errors local errtitle = nil local errmsg = nil if g_graphics.getRenderer():lower():match('gdi generic') then errtitle = tr('Graphics card driver not detected') errmsg = tr('No graphics card detected, everything will be drawn using the CPU,\nthus the performance will be really bad.\nPlease update your graphics driver to have a better performance.') end -- Show entergame if errmsg or errtitle then local msgbox = displayErrorBox(errtitle, errmsg) msgbox.onOk = function() EnterGame.firstShow() end else EnterGame.firstShow() end end function init() connect(g_app, { onRun = startup, onExit = exit }) g_window.setMinimumSize({ width = 600, height = 480 }) g_sounds.preload(musicFilename) -- initialize in fullscreen mode on mobile devices if g_window.getPlatformType() == "X11-EGL" then g_window.setFullscreen(true) else -- window size local size = { width = 800, height = 600 } size = g_settings.getSize('window-size', size) g_window.resize(size) -- window position, default is the screen center local displaySize = g_window.getDisplaySize() local defaultPos = { x = (displaySize.width - size.width)/2, y = (displaySize.height - size.height)/2 } local pos = g_settings.getPoint('window-pos', defaultPos) pos.x = math.max(pos.x, 0) pos.y = math.max(pos.y, 0) g_window.move(pos) -- window maximized? local maximized = g_settings.getBoolean('window-maximized', false) if maximized then g_window.maximize() end end g_window.setTitle("Avatar Online") g_window.setIcon('/images/clienticon') -- poll resize events g_window.poll() g_keyboard.bindKeyDown('Ctrl+Shift+R', reloadScripts) -- generate machine uuid, this is a security measure for storing passwords if not g_crypt.setMachineUUID(g_settings.get('uuid')) then g_settings.set('uuid', g_crypt.getMachineUUID()) g_settings.save() end end function terminate() disconnect(g_app, { onRun = startup, onExit = exit }) -- save window configs g_settings.set('window-size', g_window.getUnmaximizedSize()) g_settings.set('window-pos', g_window.getUnmaximizedPos()) g_settings.set('window-maximized', g_window.isMaximized()) end function exit() g_logger.info("Exiting application..") end
mit
abdllhbyrktr/Urho3D
Source/Urho3D/LuaScript/pkgs/ToZerobraneStudioHook.lua
9
12213
-- -- Copyright (c) 2008-2017 the Urho3D project. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- Highly based on "ToDoxHook.lua", adjusted for Zerobrane Studio API format. -- Compatible with Zerobrane Studio 0.41+ (Zerobrane Studio 0.40 and below may have issues) --[[ Copy result in your Zerobrane Studio's folder "api/lua" and set it in your "interpreters" file with the filename (excluding it's lua extension) into the "api" table variable. ]]-- require "ToDoxHook" function printFunction(self,ident,close,isfunc) local func = {} func.mod = self.mod func.type = self.type func.ptr = self.ptr func.name = self.name func.lname = self.lname func.const = self.const func.cname = self.cname func.lname = self.lname if isfunc then func.name = func.lname end currentFunction = func local i = 1 while self.args[i] do self.args[i]:print(ident.." ",",") i = i + 1 end currentFunction = nil if currentClass == nil then table.insert(globalFunctions, func) else if func.name == "delete" then func.type = "void" end if currentClass.functions == nil then currentClass.functions = { func } else table.insert(currentClass.functions, func) end end end -- Workaround for Zerobrane Studio's tool-tip with overloaded functions function adjustClassesOverloadFuncs() for i, class in ipairs(classes) do if classes[i].functions ~= nil then for j, func in ipairs(classes[i].functions) do for k, searchfunc in ipairs(classes[i].functions) do -- don't apply on same if k ~= j and func.name == searchfunc.name then if classes[i].functions[j].overloads == nil then classes[i].functions[j].overloads = {} end table.insert(classes[i].functions[j].overloads, searchfunc) table.remove(classes[i].functions, k) adjustClassesOverloadFuncs() return end end end end end end function writeFunctionArgs(file, declarations) local count = table.maxn(declarations) for i = 1, count do local declaration = declarations[i] if declaration.type ~= "void" then -- add parameter type local param_str = declaration.type -- add pointer or reference if declaration.ptr ~= "" then param_str = param_str .. declaration.ptr end -- add parameter name param_str = param_str .. " " .. declaration.name -- add parameter default value if declaration.def ~= "" then param_str = param_str .. " = " .. declaration.def end local fixedParamStr = param_str:gsub([[(")]], [[\%1]]) file:write(fixedParamStr) end if i ~= count then file:write(", ") end end end function writeFunctionReturn(file, func) local return_str = "" if func.type ~= "" and func.type ~= "void" then return_str = return_str .. func.type end if func.ptr ~= "" then if func.type == "" and classname ~= nil then return_str = return_str .. classname end return_str = return_str .. func.ptr end file:write(return_str) end function writeInheritances(file, classname) for i, inheritance in ipairs(classes) do if inheritance.name == classname then if inheritance.functions ~= nil then for j, func in ipairs(inheritance.functions) do writeFunction(file, func, classname, true) end end if inheritance.properties ~= nil then for j, property in ipairs(inheritance.properties) do writeProperty(file, property) end end -- append inheritance functions & properties if inheritance.base ~= "" then writeInheritances(file, inheritance.base) end end end end function writeClasses(file) sortByName(classes) adjustClassesOverloadFuncs() file:write("\n\n -- Classes") for i, class in ipairs(classes) do file:write("\n " .. class.name .. " = {") if class.functions ~= nil or class.properties ~= nil then file:write("\n childs = {") end if class.functions ~= nil then for i, func in ipairs(class.functions) do writeFunction(file, func, class.name) end end if class.properties ~= nil then for i, property in ipairs(class.properties) do writeProperty(file, property) end end -- append inheritance functions & properties if class.base ~= "" then writeInheritances(file, class.base) end if class.functions ~= nil or class.properties ~= nil then file:write("\n },") end file:write("\n type = \"class\"") file:write("\n },") end end function writeEnumerates(file) sortByName(enumerates) file:write("\n\n -- Enumerations\n") for i, enumerate in ipairs(enumerates) do for i, value in ipairs(enumerate.values) do file:write("\n " .. value .. " = {") file:write("\n description = \"(Readonly) int for '" .. enumerate.name .. "'\",") file:write("\n type = \"value\"") file:write("\n },") end end end function writeFunction(file, func, classname, isInheritance, asFunc) -- ignore operators if func.name:find("^operator[=%+%-%*%(%)\\</]") == nil then -- ignore new/delete object if from inheritance if not ((func.name == classname or func.name == "new" or func.name == "delete") and isInheritance == true) then -- write function begin file:write("\n " .. func.name .. " = {") -- write parameters file:write("\n args = \"(") if func.declarations ~= nil then writeFunctionArgs(file, func.declarations) end file:write(")\",") -- write description preparation local isFirstDescription = true if func.overloads ~= nil or func.descriptions ~= nil then file:write("\n description = \"") end -- write overloaded parameters in description, if any if func.overloads ~= nil then for i, overload in ipairs(func.overloads) do if isFirstDescription == false then file:write(",\\n") else isFirstDescription = false end file:write("(") writeFunctionReturn(file, overload) file:write(") "..overload.name.." (") writeFunctionArgs(file, overload.declarations) file:write(")") end end -- write description if func.descriptions ~= nil then for i, description in ipairs(func.descriptions) do if isFirstDescription == false then file:write("\\n") else isFirstDescription = false end local fixedDescription = description:gsub([[(")]], [[\%1]]) file:write(fixedDescription) end end -- write description end if func.overloads ~= nil or func.descriptions ~= nil then file:write("\",") end -- write returns if func.type ~= "" or func.ptr ~= "" then file:write("\n returns = \"(") writeFunctionReturn(file, func) file:write(")\",") end -- write valuetype if func.ptr ~= "" then if func.type ~= "" then file:write("\n valuetype = \"" .. func.type:gsub("(const%s+)","") .. "\",") elseif classname ~= nil then file:write("\n valuetype = \"" .. classname .. "\",") end end -- write function end if asFunc == true then file:write("\n type = \"function\"") -- accepts auto-completion with ".", ":" and global else file:write("\n type = \"method\"") -- accepts auto-completion only with ":" end file:write("\n },") end end end function writeGlobalConstants(file) sortByName(globalConstants) file:write("\n\n -- Global Constants\n") for i, constant in ipairs(globalConstants) do file:write("\n " .. constant.name .. " = {") -- write valuetype if constant.ptr ~= "" then if constant.type ~= "" then file:write("\n valuetype = \"" .. constant.type:gsub("(const%s+)","") .. "\",") end end -- write description (type) file:write("\n description = \"" .. constant.type .. constant.ptr .. "\",") -- write constant end file:write("\n type = \"value\"") file:write("\n },") end end function writeGlobalConstants(file) sortByName(globalConstants) file:write("\n\n -- Global Constants\n") for i, constant in ipairs(globalConstants) do file:write("\n " .. constant.name .. " = {") -- write valuetype if constant.ptr ~= "" then if constant.type ~= "" then file:write("\n valuetype = \"" .. constant.type:gsub("(const%s+)","") .. "\",") end end -- write description (type) file:write("\n description = \"" .. constant.type .. constant.ptr .. "\",") -- write constant end file:write("\n type = \"value\"") file:write("\n },") end end function writeGlobalFunctions(file) sortByName(globalFunctions) file:write("\n\n -- Global Functions\n") for i, func in ipairs(globalFunctions) do writeFunction(file, func, nil, nil, true) end end function writeGlobalProperties(file) file:write("\n") for i, property in ipairs(globalProperties) do writeProperty(file, property) end end function writeProperty(file, property) file:write("\n " .. property.name .. " = {") -- write valuetype if property.ptr ~= "" then if property.type ~= "" then file:write("\n valuetype = \"" .. property.type:gsub("(const%s+)","") .. "\",") end end -- write description (type) if property.mod:find("tolua_readonly") == nil then file:write("\n description = \"" .. property.type .. property.ptr .. "") else file:write("\n description = \"(Readonly) " .. property.type .. property.ptr .. "") end -- write description if property.descriptions ~= nil then for i, description in ipairs(property.descriptions) do local fixedDescription = description:gsub([[(")]], [[\%1]]) file:write("\\n" .. fixedDescription) end end file:write("\",") -- write property end file:write("\n type = \"value\"") file:write("\n },") end function classPackage:print() curDir = getCurrentDirectory() if flags.o == nil then print("Invalid output filename"); return end local filename = flags.o local file = io.open(filename, "wt") file:write("-- Urho3D API generated on "..os.date('%Y-%m-%d')) file:write("\n\nlocal api = {") local i = 1 while self[i] do self[i]:print("","") i = i + 1 end printDescriptionsFromPackageFile(flags.f) writeClasses(file) writeEnumerates(file) writeGlobalFunctions(file) writeGlobalProperties(file) writeGlobalConstants(file) file:write("\n}\nreturn api\n") file:close() end
mit
drmingdrmer/mysql-proxy-xp
tests/suite/run-tests.lua
2
25475
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] -- vim:sw=4:noexpandtab --- -- a lua baed test-runner for the mysql-proxy -- -- to stay portable it is written in lua -- -- we require LFS (LuaFileSystem) require("lfs") require("glib2") require("posix") --- -- get the directory-name of a path -- -- @param filename path to create the directory name from function dirname(filename) local dirname = filename attr = assert(lfs.attributes(dirname)) if attr.mode == "directory" then return dirname end dirname = filename:gsub("/[^/]+$", "") attr = assert(lfs.attributes(dirname)) assert(attr.mode == "directory", "dirname("..filename..") failed: is ".. attr.mode) return dirname end --- -- get the file-name of a path -- -- @param filename path to create the directory name from function basename(filename) name = filename:gsub(".*/", "") return name end -- -- a set of user variables which can be overwritten from the environment -- local testdir = dirname(arg[0]) local USE_POPEN = os.getenv('USE_POPEN') or 1 local VERBOSE = os.getenv('TEST_VERBOSE') or os.getenv('VERBOSE') or os.getenv('DEBUG') or 0 VERBOSE = VERBOSE + 0 local FORCE_ON_ERROR = os.getenv('FORCE_ON_ERROR') or os.getenv('FORCE') local MYSQL_USER = os.getenv("MYSQL_USER") or "root" local MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD") or "" local MYSQL_HOST = os.getenv("MYSQL_HOST") or "127.0.0.1" local MYSQL_PORT = os.getenv("MYSQL_PORT") or "3306" local MYSQL_DB = os.getenv("MYSQL_DB") or "test" local MYSQL_TEST_BIN = os.getenv("MYSQL_TEST_BIN") or "mysqltest" local MYSQL_CLIENT_BIN = os.getenv("MYSQL_CLIENT_BIN") or "mysql" local TESTS_REGEX = os.getenv("TESTS_REGEX") -- -- Global variables that can be referenced from .options files -- -- TODO : add HOST variables for MASTER, SLAVE, CHAIN function get_port_base() local port_base_start = os.getenv("MYSQL_PROXY_START_PORT") or 32768 local port_base_end = os.getenv("MYSQL_PROXY_END_PORT") or 65535 local port_interval = 64 -- let's take the base port in steps of ... local range = port_base_end - port_base_start - port_interval math.randomseed(posix.getpid()) local rand = math.floor(math.random() * (math.ceil(range / port_interval))) local port_base = port_base_start + (rand * port_interval) print(("... using tcp-port = %d as start port"):format(port_base)) return port_base end local port_base = get_port_base() PROXY_HOST = os.getenv("PROXY_HOST") or "127.0.0.1" PROXY_PORT = os.getenv("PROXY_PORT") or tostring(port_base + 0) PROXY_MASTER_PORT = os.getenv("PROXY_MASTER_PORT") or tostring(port_base + 10) PROXY_SLAVE_PORT = os.getenv("PROXY_SLAVE_PORT") or tostring(port_base + 20) PROXY_CHAIN_PORT = os.getenv("PROXY_CHAIN_PORT") or tostring(port_base + 30) ADMIN_PORT = os.getenv("ADMIN_PORT") or tostring(port_base + 15) ADMIN_MASTER_PORT = os.getenv("ADMIN_MASTER_PORT") or tostring(port_base + 25) ADMIN_SLAVE_PORT = os.getenv("ADMIN_SLAVE_PORT") or tostring(port_base + 35) ADMIN_CHAIN_PORT = os.getenv("ADMIN_CHAIN_PORT") or tostring(port_base + 45) ADMIN_USER = os.getenv("ADMIN_USER") or "root" ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD") or "" ADMIN_DEFAULT_SCRIPT_FILENAME = os.getenv("ADMIN_DEFAULT_SCRIPT_FILENAME") or "" -- local PROXY_TMP_LUASCRIPT = os.getenv("PROXY_TMP_LUASCRIPT") or "/tmp/proxy.tmp.lua" local srcdir = os.getenv("srcdir") or testdir .. "/" local top_builddir = os.getenv("top_builddir") or testdir .. "/../" local builddir = os.getenv("builddir") or testdir .. "/" -- same as srcdir by default local PROXY_TRACE = os.getenv("PROXY_TRACE") or "" -- use it to inject strace or valgrind local PROXY_PARAMS = os.getenv("PROXY_PARAMS") or "" -- extra params local PROXY_BINPATH = os.getenv("PROXY_BINPATH") or top_builddir .. "/src/mysql-proxy" PROXY_LIBPATH = os.getenv("PROXY_LIBPATH") or top_builddir .. "/plugins/" local COVERAGE_LCOV = os.getenv("COVERAGE_LCOV") -- -- end of user-vars -- PROXY_PIDFILE = lfs.currentdir() .. "/mysql-proxy-test.pid" PROXY_MASTER_PIDFILE = lfs.currentdir() .. "/mysql-proxy-test-master.pid" PROXY_SLAVE_PIDFILE = lfs.currentdir() .. "/mysql-proxy-test-slave.pid" PROXY_CHAIN_PIDFILE = lfs.currentdir() .. "/mysql-proxy-test-chain.pid" PROXY_BACKEND_PIDFILE = lfs.currentdir() .. "/mysql-proxy-test-backend.pid" PROXY_TEST_BASEDIR = lfs.currentdir() DEFAULT_SCRIPT_FILENAME = "/tmp/dummy.lua" default_proxy_options = { ["proxy-backend-addresses"] = MYSQL_HOST .. ":" .. MYSQL_PORT, ["proxy-address"] = PROXY_HOST .. ":" .. PROXY_PORT, ["pid-file"] = PROXY_PIDFILE, ["proxy-lua-script"] = DEFAULT_SCRIPT_FILENAME, ["plugin-dir"] = PROXY_LIBPATH, ["basedir"] = PROXY_TEST_BASEDIR, } default_master_options = { ["proxy-backend-addresses"] = MYSQL_HOST .. ":" .. MYSQL_PORT, ["proxy-address"] = PROXY_HOST .. ":" .. PROXY_MASTER_PORT, ["pid-file"] = PROXY_MASTER_PIDFILE, ["proxy-lua-script"] = DEFAULT_SCRIPT_FILENAME, ["plugin-dir"] = PROXY_LIBPATH, ["basedir"] = PROXY_TEST_BASEDIR, } default_slave_options = { ["proxy-backend-addresses"] = MYSQL_HOST .. ":" .. MYSQL_PORT, ["proxy-address"] = PROXY_HOST .. ":" .. PROXY_SLAVE_PORT, ["pid-file"] = PROXY_SLAVE_PIDFILE, ["proxy-lua-script"] = DEFAULT_SCRIPT_FILENAME, ["plugin-dir"] = PROXY_LIBPATH, ["basedir"] = PROXY_TEST_BASEDIR, } tests_to_skip = {} local tests_to_skip_filename = 'tests_to_skip.lua' local proxy_list = {} default_proxy_name = 'default' local exitcode=0 --- -- print_verbose() -- -- prints a message if either the DEBUG or VERBOSE variables -- are set. -- -- @param msg the message being printed -- @param min_level the minimum verbosity level for printing the message (default 1) function print_verbose(msg, min_level) min_level = min_level or 1 if (VERBOSE >= min_level) then print (msg) end end --- -- check if the file exists and is readable function file_exists(f) return lfs.attributes(f) end --- -- create the default option file -- function make_default_options_file(fname) if file_exists(fname) then return end local fd = assert(io.open(fname, "w")) fd:write('start_proxy(default_proxy_name, default_proxy_options) \n') fd:close(); end --- -- copy a file -- -- @param dst filename of the destination -- @param src filename of the source function file_copy(dst, src) -- print_verbose("copying ".. src .. " to " .. dst) local src_fd = assert(io.open(src, "rb")) local content = src_fd:read("*a") src_fd:close(); local dst_fd = assert(io.open(dst, "wb+")) dst_fd:write(content); dst_fd:close(); end --- -- create a empty file -- -- if the file exists, it will be truncated to 0 -- -- @param dst filename to create and truncate function file_empty(dst) -- print_verbose("emptying " .. dst) local dst_fd = assert(io.open(dst, "wb+")) dst_fd:close(); end --- -- turn a option-table into a string -- -- the values are encoded and quoted for the shell -- -- @param tbl a option table -- @param sep the seperator, defaults to a space function options_tostring(tbl, sep) -- default value for sep sep = sep or " " assert(type(tbl) == "table") assert(type(sep) == "string") local s = "" for k, v in pairs(tbl) do local values -- if the value is a table, repeat the option if type(v) == "table" then values = v else values = { v } end for tk, tv in pairs(values) do local enc_value = tv:gsub("\\", "\\\\"):gsub("\"", "\\\"") s = s .. "--" .. k .. "=\"" .. enc_value .. "\" " end end -- print_verbose(" option: " .. s) return s end --- turns an option table into a string of environment variables -- function env_options_tostring(tbl) assert(type(tbl) == "table") local s = "" for k, v in pairs(tbl) do local enc_value = v:gsub("\\", "\\\\"):gsub("\"", "\\\"") s = s .. k .. "=\"" .. enc_value .. "\" " end return s end function os_execute(cmdline) print_verbose("$ " .. cmdline) return os.execute(cmdline) end --- -- get the PID from the pid file -- function get_pid(pid_file_name) -- the file may exist, but the PID may not be written yet local pid local rounds = 0 repeat local fh = assert(io.open(pid_file_name, 'r')) pid = fh:read("*n") fh:close() if not pid then glib2.usleep(200 * 1000) -- wait a bit until we get some content rounds = rounds + 1 if rounds > 10 then error(("reading PID from existing pid-file '%s' failed after waiting 2 sec"):format( pid_file_name)) end end until pid -- the PID we get here should be a number assert(type(pid) == "number") return pid end function wait_proc_up(pid_file) local rounds = 0 while not file_exists(pid_file) do glib2.usleep(200 * 1000) -- wait until the pid-file is created rounds = rounds + 1 print_verbose(("(wait_proc_up) pid-wait: %d rounds, (%s)"):format(rounds, pid_file)) if rounds > 1000 then error(("proxy failed to start: no pid-file %s"):format(pid_file)) end end local pid = get_pid(pid_file) rounds = 0 -- check that the process referenced in the PID-file is still up while 0 ~= os.execute("kill -0 ".. pid .." 2> /dev/null") do glib2.usleep(200 * 1000) -- wait until the pid-file is created rounds = rounds + 1 print_verbose(("(wait_proc_up) kill-wait: %d rounds, pid=%d (%s)"):format(rounds, pid, pid_file)) if rounds > 5 then error(("proxy seems to have crashed: pid=%d (%s)"):format(pid, pid_file)) end end end function proc_is_up(pid) return os.execute("kill -0 ".. pid .." 2> /dev/null") end function proc_stop(pid) return os.execute("kill -TERM ".. pid) end function wait_proc_down(pid_file) local rounds = 0 local pid = get_pid(pid_file) -- wait until the proc in the pid file is dead -- the shutdown takes at about 500ms while 0 == proc_is_up(pid) do glib2.usleep(200 * 1000) -- wait until process is gone rounds = rounds + 1 print_verbose(("(wait_proc_down) kill-wait: %d rounds, pid=%d (%s)"):format(rounds, pid, pid_file)) end end function stop_proxy() -- shut dowm the proxy -- -- win32 has tasklist and taskkill on the shell -- shuts down every proxy in the proxy list -- for proxy_name, proxy_options in pairs(proxy_list) do local pid pid_file = proxy_options['pid-file'] print_verbose ('stopping proxy ' .. proxy_name) pid = get_pid(pid_file) if proc_is_up(pid) then proc_stop(pid) else print("-- process "..proxy_name.." is already down") exitcode = -1 end end -- wait until they are all gone for proxy_name, proxy_options in pairs(proxy_list) do pid_file = proxy_options['pid-file'] wait_proc_down(pid_file) os.remove(pid_file) end -- -- empties the proxy list -- proxy_list = { } end function only_item ( tbl, item) local exists = false for i,v in pairs(tbl) do if i == item then exists = true else return false end end return exists end --- -- before_test() -- -- Executes a script with a base name like test_name and extension ".options" -- -- If there is no such file, the default options are used -- function before_test(basedir, test_name) local script_filename = basedir .. "/t/" .. test_name .. ".lua" local options_filename = basedir .. "/t/" .. test_name .. ".options" local has_option_file = file_exists(options_filename) if file_exists( script_filename) then if has_option_file then default_proxy_options['proxy-lua-script'] = script_filename print_verbose('using lua script directly ' .. script_filename) file_empty(DEFAULT_SCRIPT_FILENAME) else default_proxy_options['proxy-lua-script'] = DEFAULT_SCRIPT_FILENAME file_copy(DEFAULT_SCRIPT_FILENAME, script_filename) print_verbose('copying lua script to default ' .. script_filename) end else default_proxy_options['proxy-lua-script'] = DEFAULT_SCRIPT_FILENAME file_empty(DEFAULT_SCRIPT_FILENAME) print_verbose('using empty lua script') end global_basedir = basedir print_verbose ('current_dir ' .. basedir .. ' - script: ' .. default_proxy_options['proxy-lua-script'] ) -- -- executes the content of the options file -- if has_option_file then print_verbose('# using options file ' .. options_filename) stop_proxy() else -- -- if no option file is found, the default options file is executed -- options_filename = basedir .. "/t/default.options" print_verbose('#using default options file' .. options_filename) if only_item(proxy_list,'default') then print_verbose('reusing existing proxy') return end make_default_options_file(options_filename) end assert(loadfile(options_filename))() end function after_test() if only_item(proxy_list, 'default') then return end stop_proxy() end function alternative_execute (cmd) print_verbose(cmd) local fh = io.popen(cmd) assert(fh, 'error executing '.. cmd) local result = '' local line = fh:read() while line do result = result .. line line = fh:read() end fh:close() return result end function conditional_execute (cmd) if USE_POPEN then return alternative_execute(cmd) else return os_execute(cmd) end end --- -- run a test -- -- @param testname name of the test -- @return exit-code of mysql-test function run_test(filename, basedir) if not basedir then basedir = srcdir end local testname = assert(filename:match("t/(.+)\.test")) if tests_to_skip[testname] then print('skip ' .. testname ..' '.. (tests_to_skip[testname] or 'no reason given') ) return 0, 1 end before_test(basedir, testname) if VERBOSE > 1 then os.execute('echo -n "' .. testname .. ' " ; ' ) end local result = 0 local ret = conditional_execute( env_options_tostring({ ['MYSQL_USER'] = MYSQL_USER, ['MYSQL_PASSWORD'] = MYSQL_PASSWORD, ['PROXY_HOST'] = PROXY_HOST, ['PROXY_PORT'] = PROXY_PORT, ['PROXY_CHAIN_PORT'] = PROXY_CHAIN_PORT, ['MASTER_PORT'] = PROXY_MASTER_PORT, ['SLAVE_PORT'] = PROXY_SLAVE_PORT, }) .. ' ' .. MYSQL_TEST_BIN .. " " .. options_tostring({ user = MYSQL_USER, password = MYSQL_PASSWORD, database = MYSQL_DB, host = PROXY_HOST, port = PROXY_PORT, verbose = (VERBOSE > 0) and "TRUE" or "FALSE", -- pass down the verbose setting ["test-file"] = basedir .. "/t/" .. testname .. ".test", ["result-file"] = basedir .. "/r/" .. testname .. ".result", ["logdir"] = builddir, -- the .result dir might not be writable }) ) if USE_POPEN then assert(ret == 'ok' or ret =='not ok', 'unexpected result <' .. ret .. '>') if (ret == 'ok') then result = 0 elseif ret == 'not ok'then result = 1 end print(ret .. ' ' .. testname) else result = ret end after_test() return result, 0 end --- --sql_execute() -- -- Executes a SQL query in a given Proxy -- -- If no Proxy is indicated, the query is passed directly to the backend server -- -- @param query A SQL statement to execute, or a table of SQL statements -- @param proxy_name the name of the proxy that executes the query function sql_execute(queries, proxy_name) local ret = 0 assert(type(queries) == 'string' or type(queries) == 'table', 'invalid type for query' ) if type(queries) == 'string' then queries = {queries} end local query = '' for i, q in pairs(queries) do query = query .. ';' .. q end if proxy_name then -- -- a Proxy name is passed. -- The query is executed with the given proxy local opts = proxy_list[proxy_name] assert(opts,'proxy '.. proxy_name .. ' not active') assert(opts['proxy-address'],'address for proxy '.. proxy_name .. ' not found') local p_host, p_port = opts['proxy-address']:match('(%S+):(%S+)') ret = os_execute( MYSQL_CLIENT_BIN .. ' ' .. options_tostring({ user = MYSQL_USER, password = MYSQL_PASSWORD, database = MYSQL_DB, host = p_host, port = p_port, execute = query }) ) assert(ret == 0, 'error using mysql client ') else -- -- No proxy name was passed. -- The query is executed in the backend server -- ret = os_execute( MYSQL_CLIENT_BIN .. ' ' .. options_tostring({ user = MYSQL_USER, password = MYSQL_PASSWORD, database = MYSQL_DB, host = PROXY_HOST, port = MYSQL_PORT, execute = query }) ) end return ret end stop_proxy() -- the proxy needs the lua-script to exist -- file_empty(PROXY_TMP_LUASCRIPT) -- if the pid-file is still pointing to a active process, kill it --[[ if file_exists(PROXY_PIDFILE) then os.execute("kill -TERM `cat ".. PROXY_PIDFILE .." `") os.remove(PROXY_PIDFILE) end --]] if COVERAGE_LCOV then -- os_execute(COVERAGE_LCOV .. -- " --zerocounters --directory ".. srcdir .. "/../src/" ) end -- setting the include path -- -- this is the path containing the global Lua modules local GLOBAL_LUA_PATH = os.getenv('LUA_LDIR') or '/usr/share/lua/5.1/?.lua' -- this is the path containing the Proxy libraries local PROXY_LUA_PATH = os.getenv('LUA_PATH') or '/usr/local/share/?.lua' -- This is the path with specific libraries for the test suite local PRIVATE_LUA_PATH = arg[1] .. '/t/?.lua' -- This is the path with additional libraries that the user needs local LUA_USER_PATH = os.getenv('LUA_USER_PATH') or '../lib/?.lua' -- Building the final include path local INCLUDE_PATH = LUA_USER_PATH .. ';' .. PRIVATE_LUA_PATH .. ';' .. GLOBAL_LUA_PATH .. ';' .. PROXY_LUA_PATH --- -- start_proxy() -- -- starts an instance of MySQL Proxy -- -- @param proxy_name internal name of the proxy instance, for retrieval -- @param proxy_options the options to start the Proxy function start_proxy(proxy_name, proxy_options) -- start the proxy assert(type(proxy_options) == 'table') if not file_exists(proxy_options['proxy-lua-script']) then proxy_options['proxy-lua-script'] = global_basedir .. '/t/' .. proxy_options['proxy-lua-script'] end print_verbose("starting " .. proxy_name .. " with " .. options_tostring(proxy_options)) -- remove the old pid-file if it exists os.remove(proxy_options['pid-file']) -- if we are supposed to listen on a UNIX socket, remove it first, because we don't clean it up on exit! -- TODO: fix the code, instead of hacking around here! Bug#38415 if proxy_options['proxy-address'] == '/tmp/mysql-proxy-test.sock' then os.remove(proxy_options['proxy-address']) end -- os.execute("head " .. proxy_options['proxy-lua-script']) assert(os.execute( 'LUA_PATH="' .. INCLUDE_PATH .. '" ' .. PROXY_TRACE .. " " .. PROXY_BINPATH .. " " .. options_tostring( proxy_options) .. " &" )) -- wait until the proxy is up wait_proc_up(proxy_options['pid-file']) proxy_list[proxy_name] = proxy_options end --- -- simulate_replication() -- -- creates a fake master/slave by having two proxies -- pointing at the same backend -- -- you can alter those backends by changing -- the starting parameters -- -- @param master_options options for master -- @param slave_options options for slave function simulate_replication(master_options, slave_options) if not master_options then master_options = default_master_options end if not master_options['pid-file'] then master_options['pid-file'] = PROXY_MASTER_PIDFILE end if not slave_options then slave_options = default_slave_options end if not slave_options['pid-file'] then slave_options['pid-file'] = PROXY_SLAVE_PIDFILE end start_proxy('master', master_options) start_proxy('slave', slave_options) end --- -- chain_proxy() -- -- starts two proxy instances, with the first one is pointing to the -- default backend server, and the second one (with default ports) -- is pointing at the first proxy -- -- client -> proxy -> backend_proxy -> [ mysql-backend ] -- -- usually we use it to mock a server with a lua script (...-mock.lua) and -- the script under test in the proxy (...-test.lua) -- -- in case you want to start several backend_proxies, just provide a array -- as first param -- -- @param backend_lua_script -- @param second_lua_script -- @param use_replication uses a master proxy as backend function chain_proxy (backend_lua_scripts, second_lua_script, use_replication) local backends = { } if type(backend_lua_scripts) == "table" then backends = backend_lua_scripts else backends = { backend_lua_scripts } end local backend_addresses = { } for i, backend_lua_script in ipairs(backends) do backend_addresses[i] = PROXY_HOST .. ":" .. (PROXY_CHAIN_PORT + i - 1) backend_proxy_options = { ["proxy-backend-addresses"] = MYSQL_HOST .. ":" .. MYSQL_PORT, ["proxy-address"] = backend_addresses[i], ["pid-file"] = PROXY_CHAIN_PIDFILE .. i, ["proxy-lua-script"] = backend_lua_script or DEFAULT_SCRIPT_FILENAME, ["plugin-dir"] = PROXY_LIBPATH, ["basedir"] = PROXY_TEST_BASEDIR, ["log-level"] = (VERBOSE == 4) and "debug" or "critical", } -- -- if replication was not started, then it is started here -- if use_replication and (use_replication == true) then if (proxy_list['master'] == nil) then simulate_replication() end backend_proxy_options["proxy-backend-addresses"] = PROXY_HOST .. ':' .. PROXY_MASTER_PORT end start_proxy('backend_proxy' .. i, backend_proxy_options) end second_proxy_options = { ["proxy-backend-addresses"] = backend_addresses , ["proxy-address"] = PROXY_HOST .. ":" .. PROXY_PORT, ["pid-file"] = PROXY_PIDFILE, ["proxy-lua-script"] = second_lua_script or DEFAULT_SCRIPT_FILENAME, ["plugin-dir"] = PROXY_LIBPATH, ["basedir"] = PROXY_TEST_BASEDIR, ["log-level"] = (VERBOSE == 3) and "debug" or "critical", } start_proxy('second_proxy',second_proxy_options) end local num_tests = 0 local num_passes = 0 local num_skipped = 0 local num_fails = 0 local all_ok = true local failed_test = {} file_empty(DEFAULT_SCRIPT_FILENAME) -- -- if we have a argument, exectute the named test -- otherwise execute all tests we can find if #arg then for i, a in ipairs(arg) do local stat = assert(lfs.attributes(a)) if file_exists(a .. '/' .. tests_to_skip_filename) then assert(loadfile(a .. '/' .. tests_to_skip_filename))() end -- if it is a directory, execute all of them if stat.mode == "directory" then for file in lfs.dir(a .. "/t/") do if not TESTS_REGEX or file:match(TESTS_REGEX) then local testname = file:match("(.+\.test)$") if testname then print_verbose("# >> " .. testname .. " started") num_tests = num_tests + 1 local r, skipped = run_test("t/" .. testname, a) if (r == 0) then num_passes = num_passes + 1 - skipped else num_fails = num_fails + 1 all_ok = false table.insert(failed_test, testname) end num_skipped = num_skipped + skipped print_verbose("# << (exitcode = " .. r .. ")" ) if r ~= 0 and exitcode == 0 then exitcode = r end end if all_ok == false and (not FORCE_ON_ERROR) then break end end end else -- otherwise just this one test -- -- FIXME: base/ is hard-coded for now exitcode, skipped = run_test(a, "base/") num_skipped = num_skipped + skipped end end else for file in lfs.dir(srcdir .. "/t/") do local testname = file:match("(.+\.test)$") if testname then print_verbose("# >> " .. testname .. " started") num_tests = num_tests + 1 local r, skipped = run_test("t/" .. testname) num_skipped = num_skipped + skipped print_verbose("# << (exitcode = " .. r .. ")" ) if (r == 0) then num_passes = num_passes + 1 - skipped else all_ok = false num_fails = num_fails + 1 table.insert(failed_test, testname) end if r ~= 0 and exitcode == 0 then exitcode = r end if all_ok == false and (not FORCE_ON_ERROR) then break end end end end if all_ok ==false then print ("*** ERRORS OCCURRED - The following tests failed") for i,v in pairs(failed_test) do print(v ) end end -- -- prints test suite statistics print_verbose (string.format('tests: %d - skipped: %d (%4.1f%%) - passed: %d (%4.1f%%) - failed: %d (%4.1f%%)', num_tests, num_skipped, num_skipped / num_tests * 100, num_passes, num_passes / (num_tests - num_skipped) * 100, num_fails, num_fails / (num_tests - num_skipped) * 100)) -- -- stops any remaining active proxy -- stop_proxy() if COVERAGE_LCOV then os_execute(COVERAGE_LCOV .. " --quiet " .. " --capture --directory ".. srcdir .. "/../src/" .. " > " .. srcdir .. "/../tests.coverage.info" ) os_execute("genhtml " .. "--show-details " .. "--output-directory " .. srcdir .. "/../coverage/ " .. "--keep-descriptions " .. "--frames " .. srcdir .. "/../tests.coverage.info") end if exitcode == 0 then os.exit(0) else print_verbose("mysql-test exit-code: " .. exitcode) os.exit(-1) end
gpl-2.0
stas2z/openwrt-witi
package/luci/modules/luci-mod-admin-full/luasrc/controller/admin/uci.lua
40
1769
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.admin.uci", package.seeall) function index() local redir = luci.http.formvalue("redir", true) or luci.dispatcher.build_url(unpack(luci.dispatcher.context.request)) entry({"admin", "uci"}, nil, _("Configuration")) entry({"admin", "uci", "changes"}, call("action_changes"), _("Changes"), 40).query = {redir=redir} entry({"admin", "uci", "revert"}, call("action_revert"), _("Revert"), 30).query = {redir=redir} entry({"admin", "uci", "apply"}, call("action_apply"), _("Apply"), 20).query = {redir=redir} entry({"admin", "uci", "saveapply"}, call("action_apply"), _("Save &#38; Apply"), 10).query = {redir=redir} end function action_changes() local uci = luci.model.uci.cursor() local changes = uci:changes() luci.template.render("admin_uci/changes", { changes = next(changes) and changes }) end function action_apply() local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local changes = uci:changes() local reload = {} -- Collect files to be applied and commit changes for r, tbl in pairs(changes) do table.insert(reload, r) if path[#path] ~= "apply" then uci:load(r) uci:commit(r) uci:unload(r) end end luci.template.render("admin_uci/apply", { changes = next(changes) and changes, configs = reload }) end function action_revert() local uci = luci.model.uci.cursor() local changes = uci:changes() -- Collect files to be reverted for r, tbl in pairs(changes) do uci:load(r) uci:revert(r) uci:unload(r) end luci.template.render("admin_uci/revert", { changes = next(changes) and changes }) end
gpl-2.0
EliHar/Pattern_recognition
torch1/exe/luajit-rocks/luarocks/src/luarocks/fetch/hg.lua
14
2144
--- Fetch back-end for retrieving sources from HG. --module("luarocks.fetch.hg", package.seeall) local hg = {} local unpack = unpack or table.unpack local fs = require("luarocks.fs") local dir = require("luarocks.dir") local util = require("luarocks.util") --- Download sources for building a rock, using hg. -- @param rockspec table: The rockspec table -- @param extract boolean: Unused in this module (required for API purposes.) -- @param dest_dir string or nil: If set, will extract to the given directory. -- @return (string, string) or (nil, string): The absolute pathname of -- the fetched source tarball and the temporary directory created to -- store it; or nil and an error message. function hg.get_sources(rockspec, extract, dest_dir) assert(type(rockspec) == "table") assert(type(dest_dir) == "string" or not dest_dir) local hg_cmd = rockspec.variables.HG local ok, err_msg = fs.is_tool_available(hg_cmd, "Mercurial") if not ok then return nil, err_msg end local name_version = rockspec.name .. "-" .. rockspec.version -- Strip off special hg:// protocol type local url = rockspec.source.url:gsub("^hg://", "") local module = dir.base_name(url) local command = {hg_cmd, "clone", url, module} local tag_or_branch = rockspec.source.tag or rockspec.source.branch if tag_or_branch then command = {hg_cmd, "clone", "--rev", tag_or_branch, url, module} end local store_dir if not dest_dir then store_dir = fs.make_temp_dir(name_version) if not store_dir then return nil, "Failed creating temporary directory." end util.schedule_function(fs.delete, store_dir) else store_dir = dest_dir end local ok, err = fs.change_dir(store_dir) if not ok then return nil, err end if not fs.execute(unpack(command)) then return nil, "Failed cloning hg repository." end ok, err = fs.change_dir(module) if not ok then return nil, err end fs.delete(dir.path(store_dir, module, ".hg")) fs.delete(dir.path(store_dir, module, ".hgignore")) fs.pop_dir() fs.pop_dir() return module, store_dir end return hg
mit
nshermione/pingpongcocos2dx
proj.android-studio/app/assets/pingponggui-ccs/src/cocos/cocostudio/DeprecatedCocoStudioFunc.lua
61
3456
if nil == ccs then return end --tip local function deprecatedTip(old_name,new_name) print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********") end --functions of GUIReader will be deprecated begin local GUIReaderDeprecated = { } function GUIReaderDeprecated.shareReader() deprecatedTip("GUIReader:shareReader","ccs.GUIReader:getInstance") return ccs.GUIReader:getInstance() end GUIReader.shareReader = GUIReaderDeprecated.shareReader function GUIReaderDeprecated.purgeGUIReader() deprecatedTip("GUIReader:purgeGUIReader","ccs.GUIReader:destroyInstance") return ccs.GUIReader:destroyInstance() end GUIReader.purgeGUIReader = GUIReaderDeprecated.purgeGUIReader --functions of GUIReader will be deprecated end --functions of SceneReader will be deprecated begin local SceneReaderDeprecated = { } function SceneReaderDeprecated.sharedSceneReader() deprecatedTip("SceneReader:sharedSceneReader","ccs.SceneReader:getInstance") return ccs.SceneReader:getInstance() end SceneReader.sharedSceneReader = SceneReaderDeprecated.sharedSceneReader function SceneReaderDeprecated.purgeSceneReader(self) deprecatedTip("SceneReader:purgeSceneReader","ccs.SceneReader:destroyInstance") return self:destroyInstance() end SceneReader.purgeSceneReader = SceneReaderDeprecated.purgeSceneReader --functions of SceneReader will be deprecated end --functions of ccs.GUIReader will be deprecated begin local CCSGUIReaderDeprecated = { } function CCSGUIReaderDeprecated.purgeGUIReader() deprecatedTip("ccs.GUIReader:purgeGUIReader","ccs.GUIReader:destroyInstance") return ccs.GUIReader:destroyInstance() end ccs.GUIReader.purgeGUIReader = CCSGUIReaderDeprecated.purgeGUIReader --functions of ccs.GUIReader will be deprecated end --functions of ccs.ActionManagerEx will be deprecated begin local CCSActionManagerExDeprecated = { } function CCSActionManagerExDeprecated.destroyActionManager() deprecatedTip("ccs.ActionManagerEx:destroyActionManager","ccs.ActionManagerEx:destroyInstance") return ccs.ActionManagerEx:destroyInstance() end ccs.ActionManagerEx.destroyActionManager = CCSActionManagerExDeprecated.destroyActionManager --functions of ccs.ActionManagerEx will be deprecated end --functions of ccs.SceneReader will be deprecated begin local CCSSceneReaderDeprecated = { } function CCSSceneReaderDeprecated.destroySceneReader(self) deprecatedTip("ccs.SceneReader:destroySceneReader","ccs.SceneReader:destroyInstance") return self:destroyInstance() end ccs.SceneReader.destroySceneReader = CCSSceneReaderDeprecated.destroySceneReader --functions of ccs.SceneReader will be deprecated end --functions of CCArmatureDataManager will be deprecated begin local CCArmatureDataManagerDeprecated = { } function CCArmatureDataManagerDeprecated.sharedArmatureDataManager() deprecatedTip("CCArmatureDataManager:sharedArmatureDataManager","ccs.ArmatureDataManager:getInstance") return ccs.ArmatureDataManager:getInstance() end CCArmatureDataManager.sharedArmatureDataManager = CCArmatureDataManagerDeprecated.sharedArmatureDataManager function CCArmatureDataManagerDeprecated.purge() deprecatedTip("CCArmatureDataManager:purge","ccs.ArmatureDataManager:destoryInstance") return ccs.ArmatureDataManager:destoryInstance() end CCArmatureDataManager.purge = CCArmatureDataManagerDeprecated.purge --functions of CCArmatureDataManager will be deprecated end
apache-2.0
stas2z/openwrt-witi
package/luci/protocols/luci-proto-ipv6/luasrc/model/cbi/admin_network/proto_6to4.lua
72
1073
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local ipaddr, defaultroute, metric, ttl, mtu ipaddr = section:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Leave empty to use the current WAN address")) ipaddr.datatype = "ip4addr" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(9200)"
gpl-2.0
mightymadTV/gcraft
gcraft/entities/entities/base_ai/init.lua
3
2936
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include('shared.lua') include('schedules.lua') include('tasks.lua') -- Variables ENT.m_fMaxYawSpeed = 200 -- Max turning speed ENT.m_iClass = CLASS_CITIZEN_REBEL -- NPC Class AccessorFunc( ENT, "m_iClass", "NPCClass" ) AccessorFunc( ENT, "m_fMaxYawSpeed", "MaxYawSpeed" ) --[[--------------------------------------------------------- Name: OnTakeDamage Desc: Entity takes damage -----------------------------------------------------------]] function ENT:OnTakeDamage( dmginfo ) --[[ Msg( tostring(dmginfo) .. "\n" ) Msg( "Inflictor:\t" .. tostring(dmginfo:GetInflictor()) .. "\n" ) Msg( "Attacker:\t" .. tostring(dmginfo:GetAttacker()) .. "\n" ) Msg( "Damage:\t" .. tostring(dmginfo:GetDamage()) .. "\n" ) Msg( "Base Damage:\t" .. tostring(dmginfo:GetBaseDamage()) .. "\n" ) Msg( "Force:\t" .. tostring(dmginfo:GetDamageForce()) .. "\n" ) Msg( "Position:\t" .. tostring(dmginfo:GetDamagePosition()) .. "\n" ) Msg( "Reported Pos:\t" .. tostring(dmginfo:GetReportedPosition()) .. "\n" ) -- ?? --]] return true end --[[--------------------------------------------------------- Name: Use -----------------------------------------------------------]] function ENT:Use( activator, caller, type, value ) end --[[--------------------------------------------------------- Name: StartTouch -----------------------------------------------------------]] function ENT:StartTouch( entity ) end --[[--------------------------------------------------------- Name: EndTouch -----------------------------------------------------------]] function ENT:EndTouch( entity ) end --[[--------------------------------------------------------- Name: Touch -----------------------------------------------------------]] function ENT:Touch( entity ) end --[[--------------------------------------------------------- Name: GetRelationship Return the relationship between this NPC and the passed entity. If you don't return anything then the default disposition will be used. -----------------------------------------------------------]] function ENT:GetRelationship( entity ) --return D_NU; end --[[--------------------------------------------------------- Name: ExpressionFinished Called when an expression has finished. Duh. -----------------------------------------------------------]] function ENT:ExpressionFinished( strExp ) end --[[--------------------------------------------------------- Name: Think -----------------------------------------------------------]] function ENT:Think() end --[[--------------------------------------------------------- Name: GetAttackSpread How good is the NPC with this weapon? Return the number of degrees of inaccuracy for the NPC to use. -----------------------------------------------------------]] function ENT:GetAttackSpread( Weapon, Target ) return 0.1 end
gpl-2.0
rlcevg/Zero-K
units/armbrtha.lua
5
5821
unitDef = { unitname = [[armbrtha]], name = [[Big Bertha]], description = [[Strategic Plasma Cannon]], buildCostEnergy = 5000, buildCostMetal = 5000, builder = false, buildingGroundDecalDecaySpeed = 30, buildingGroundDecalSizeX = 6, buildingGroundDecalSizeY = 6, buildingGroundDecalType = [[armbrtha_aoplane.dds]], buildPic = [[ARMBRTHA.png]], buildTime = 5000, canAttack = true, canstop = [[1]], category = [[SINK]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[70 194 70]], collisionVolumeTest = 1, collisionVolumeType = [[cylY]], corpse = [[DEAD]], customParams = { description_de = [[Strategische Plasma Kanone]], description_fr = [[Canon ? Plasma Strat?gique]], description_pl = [[Strategiczne Dzialo Plazmowe]], helptext = [[The Bertha is a massive cannon that fires high-energy plasmoids across the map. Used appropriately, it can effectively suppress enemy operations from the safety of your base. Do not expect it to win battles alone for you, however.]], helptext_de = [[Die Bertha ist eine massive Kanone, welche hochenergetische Plasmoide über die Karte verschiesst. Angemessener Gebrauch der Waffe kann gengerische Operationen von der eigenen, sicheren Basis aus schnell unterdrücken. Trotzdem erwarte nicht, dass du nur dich diese Waffe die Schlachten gewinnen wirst.]], helptext_fr = [[Le Big Bertha est un canon ? plasma lourd, tr?s lourd. Un seul impact de son tir peut r?duire ? n?ant plusieurs unit?s ou structures. Sa port?e de tir op?rationnelle est immense et n'?gale que son co?t de construction et d'usage. En effet chaque tir consomme 300 unit?s d'?nergie. Notez que le Big Bertha effectue des tirs tendus. Autrement dit, pensez ? le placer en hauteur, ou le moindre relief servira de refuge ? l'ennemi.]], helptext_pl = [[Gruba Berta to masywne dzialo o ogromnym zasiegu. W dobrych rekach jest w stanie niweczyc wazne przedsiewziecia przeciwnika z bezpiecznego miejsca we wlasnej bazie. Nie jest jednak w stanie zastapic mobilnych jednostek i nie zapewni ci sama zwyciestwa.]], modelradius = [[35]], }, explodeAs = [[ATOMIC_BLAST]], footprintX = 4, footprintZ = 4, iconType = [[lrpc]], idleAutoHeal = 5, idleTime = 1800, levelGround = false, losEmitHeight = 90, maxDamage = 4800, maxSlope = 18, maxWaterDepth = 0, minCloakDistance = 150, noChaseCategory = [[FIXEDWING LAND SHIP SWIM GUNSHIP SUB HOVER]], objectName = [[armbrtha.s3o]], script = [[armbrtha.lua]], seismicSignature = 4, selfDestructAs = [[ATOMIC_BLAST]], sfxtypes = { explosiongenerators = { [[custom:ARMBRTHA_SHOCKWAVE]], [[custom:ARMBRTHA_SMOKE]], [[custom:ARMBRTHA_FLARE]], }, }, sightDistance = 660, useBuildingGroundDecal = true, yardMap = [[oooo oooo oooo oooo]], weapons = { { def = [[PLASMA]], badTargetCategory = [[GUNSHIP LAND SHIP HOVER SWIM]], onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP]], }, }, weaponDefs = { PLASMA = { name = [[Very Heavy Plasma Cannon]], accuracy = 500, areaOfEffect = 192, avoidFeature = false, avoidGround = false, cegTag = [[vulcanfx]], craterBoost = 0.25, craterMult = 0.5, customParams = { gatherradius = [[128]], smoothradius = [[96]], smoothmult = [[0.4]], }, damage = { default = 2002.4, subs = 100, }, explosionGenerator = [[custom:lrpc_expl]], fireTolerance = 1820, -- 10 degrees impulseBoost = 0.5, impulseFactor = 0.2, interceptedByShieldType = 1, noSelfDamage = true, range = 6200, reloadtime = 7, soundHit = [[weapon/cannon/lrpc_hit]], soundStart = [[weapon/cannon/big_begrtha_gun_fire]], turret = true, weaponType = [[Cannon]], weaponVelocity = 1100, }, }, featureDefs = { DEAD = { description = [[Wreckage - Big Bertha]], blocking = true, damage = 4800, energy = 0, featureDead = [[HEAP]], footprintX = 4, footprintZ = 4, metal = 2000, object = [[armbrtha_dead.s3o]], reclaimable = true, reclaimTime = 2000, }, HEAP = { description = [[Debris - Big Bertha]], blocking = false, damage = 4800, energy = 0, footprintX = 4, footprintZ = 4, metal = 1000, object = [[debris4x4c.s3o]], reclaimable = true, reclaimTime = 1000, }, }, } return lowerkeys({ armbrtha = unitDef })
gpl-2.0
firebitsbr/ettercap
src/lua/share/scripts/http_requests.lua
12
2720
--- -- -- Created by Ryan Linn and Mike Ryan -- Copyright (C) 2012 Trustwave Holdings, Inc. description = "Script to show HTTP requsts"; local http = require("http") local packet = require("packet") local bin = require("bit") hook_point = http.hook packetrule = function(packet_object) -- If this isn't a tcp packet, it's not really a HTTP request -- since we're hooked in the HTTP dissector, we can assume that this -- should never fail, but it's a good sanity check if packet.is_tcp(packet_object) == false then return false end return true end -- Here's your action. action = function(packet_object) local p = packet_object -- Parse the http data into an HTTP object local hobj = http.parse_http(p) -- If there's no http object, get out if hobj == nil then return end -- Get out session key for tracking req->reply pairs local session_id = http.session_id(p,hobj) -- If we can't track sessions, this won't work, get out if session_id == nil then return end -- We have a session, lets get our registry space local reg = ettercap.reg.create_namespace(session_id) -- If it's a request, save the request to the registry -- We'll need this for the response if hobj.request then reg.request = hobj -- we have a response object, let't put the log together elseif hobj.response then -- If we haven't seen the request, we don't have anything to share if not reg.request then return end -- Get the status code local code = hobj.status_code -- Build the request URL -- If we have a 2XX or 4XX or 5XX code, we won't need to log redirect -- so just log the request and code if code >= 200 and code < 300 or code >= 400 then ettercap.log("HTTP_REQ: %s:%d -> %s:%d %s %s %d (%s)\n", packet.dst_ip(p), packet.dst_port(p), packet.src_ip(p), packet.src_port(p), reg.request.verb ,reg.request.url , hobj.status_code, hobj.status_msg) -- These codes require redirect, so log the redirect as well elseif code >= 300 and code <= 303 then local redir = "" -- Get the redirect location if hobj.headers["Location"] then redir = hobj.headers["Location"] end -- Log the request/response with the redirect ettercap.log("HTTP_REQ: %s:%d -> %s:%d %s %s -> %s %d (%s)\n", packet.dst_ip(p), packet.dst_port(p), packet.src_ip(p), packet.src_port(p), reg.request.verb ,reg.request.url, redir, hobj.status_code, hobj.status_msg) end end end
gpl-2.0
Mehranhpr/spam
plugins/moderation.lua
336
9979
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then local username = v.username data[tostring(msg.to.id)] = { moderators = {[tostring(member_id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as moderator for this group.') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) else if data[tostring(msg.to.id)] then return 'Group is already added.' end if msg.from.username then username = msg.from.username else username = msg.from.print_name end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={[tostring(msg.from.id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Group has been added, and @'..username..' has been promoted as moderator for this group.' end end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Group has been added.' end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if not data[tostring(msg.to.id)] then return 'Group is not added.' end data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return 'Group has been removed' end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function admin_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) elseif mod_cmd == 'adminprom' then return admin_promote(receiver, member_username, member_id) elseif mod_cmd == 'admindem' then return admin_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = 'List of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message .. '- '..v..' [' ..k.. '] \n' end return message end local function admin_list(msg) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if next(data['admins']) == nil then --fix way return 'No admin available.' end local message = 'List for Bot admins:\n' for k,v in pairs(data['admins']) do message = message .. '- ' .. v ..' ['..k..'] \n' end return message end function run(msg, matches) if matches[1] == 'debug' then return debugs(msg) end if not is_chat_msg(msg) then return "Only works on group" end local mod_cmd = matches[1] local receiver = get_receiver(msg) if matches[1] == 'modadd' then return modadd(msg) end if matches[1] == 'modrem' then return modrem(msg) end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return "Only moderator can promote" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return "Only moderator can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then return modlist(msg) end if matches[1] == 'adminprom' then if not is_admin(msg) then return "Only sudo can promote user as admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'admindem' then if not is_admin(msg) then return "Only sudo can promote user as admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'adminlist' then if not is_admin(msg) then return 'Admin only!' end return admin_list(msg) end if matches[1] == 'chat_add_user' and msg.action.user.id == our_id then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end end return { description = "Moderation plugin", usage = { moderator = { "!promote <username> : Promote user as moderator", "!demote <username> : Demote user from moderator", "!modlist : List of moderators", }, admin = { "!modadd : Add group to moderation list", "!modrem : Remove group from moderation list", }, sudo = { "!adminprom <username> : Promote user as admin (must be done from a group)", "!admindem <username> : Demote user from admin (must be done from a group)", }, }, patterns = { "^!(modadd)$", "^!(modrem)$", "^!(promote) (.*)$", "^!(demote) (.*)$", "^!(modlist)$", "^!(adminprom) (.*)$", -- sudoers only "^!(admindem) (.*)$", -- sudoers only "^!(adminlist)$", "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_created)$", }, run = run, } end
gpl-2.0
anholt/ValyriaTear
img/sprites/map/npcs/npc_woman02_idle.lua
4
1055
-- Sprite animation file descriptor -- This file will describe the frames used to load the sprite animations -- This files is following a special format compared to other animation scripts. local ANIM_SOUTH = vt_map.MapMode.ANIM_SOUTH; local ANIM_NORTH = vt_map.MapMode.ANIM_NORTH; local ANIM_WEST = vt_map.MapMode.ANIM_WEST; local ANIM_EAST = vt_map.MapMode.ANIM_EAST; sprite_animation = { -- The file to load the frames from image_filename = "img/sprites/map/npcs/npc_woman02_spritesheet.png", -- The number of rows and columns of images, will be used to compute -- the images width and height, and also the frames number (row x col) rows = 4, columns = 6, -- The frames duration in milliseconds frames = { [ANIM_SOUTH] = { [0] = { id = 0, duration = 150 } }, [ANIM_NORTH] = { [0] = { id = 6, duration = 150 } }, [ANIM_WEST] = { [0] = { id = 12, duration = 150 } }, [ANIM_EAST] = { [0] = { id = 18, duration = 150 } } } }
gpl-2.0
Jigoku/boxclip
src/entities/enemies/blob.lua
1
3404
--[[ * Copyright (C) 2015 - 2022 Ricky K. Thomson * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * u should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. --]] blob = {} table.insert(enemies.list, "blob") table.insert(editor.entities, {"blob", "enemy"}) enemies.textures["blob"] = textures:load("data/images/enemies/blob/") function blob:worldInsert(x,y,movespeed,movedist,dir,name) local texture = enemies.textures[name][1] table.insert(world.entities.enemy, { movespeed = movespeed or 160, movedist = movedist or 300, movex = 1, dir = 0, xorigin = x, yorigin = y, x = love.math.random(x,x+movedist) or 0, y = y or 0, texture = texture, w = texture:getWidth(), h = texture:getHeight(), framecycle = 0, frame = 1, framedelay = 0.025, group = "enemy", type = name, xvel = 0, yvel = 0, dir = 0, alive = true, score = 100 }) end function blob:checkCollision(enemy, dt) physics:applyGravity(enemy, dt) physics:movex(enemy, dt) physics:crates(enemy,dt) physics:traps(enemy, dt) physics:platforms(enemy, dt) physics:update(enemy) -- NOT ACTIVE WHILST EDITING if mode == "game" and player.alive and collision:check(player.newX,player.newY,player.w,player.h, enemy.x+5,enemy.y+5,enemy.w-10,enemy.h-10) then -- if we land on top, kill enemy if collision:above(player,enemy) then if player.jumping or player.invincible or player.sliding then if player.y > enemy.y then player.yvel = -player.jumpheight elseif player.y < enemy.y then player.yvel = player.jumpheight end popups:add(enemy.x+enemy.w/2,enemy.y+enemy.h/2,"+"..enemy.score) player.score = player.score + enemy.score enemy.alive = false sound:play(sound.effects["kill"]) console:print(enemy.type .." killed") joystick:vibrate(0.5,0.5,0.5) return true else player:die(enemy.type) end end end end function blob:draw(enemy) love.graphics.setColor(1,1,1,1) if enemy.movespeed < 0 then love.graphics.draw(enemy.texture, enemy.x, enemy.y, 0, 1, 1) elseif enemy.movespeed > 0 then love.graphics.draw(enemy.texture, enemy.x+enemy.w, enemy.y, 0, -1, 1) end end function blob:drawdebug(enemy, i) --bounds love.graphics.setColor(1,0,0,1) love.graphics.rectangle("line", enemy.x+5, enemy.y+5, enemy.w-10, enemy.h-10) --hitbox love.graphics.setColor(1,0.78,0.39,1) love.graphics.rectangle("line", enemy.x, enemy.y, enemy.w, enemy.h) local texture = enemies.textures[enemy.type] love.graphics.setColor(1,0,1,0.19) love.graphics.rectangle("fill", enemy.xorigin, enemy.y, enemy.movedist+texture[(enemy.frame or 1)]:getWidth(), texture[(enemy.frame or 1)]:getHeight()) love.graphics.setColor(1,0,1,1) love.graphics.rectangle("line", enemy.xorigin, enemy.y, enemy.movedist+texture[(enemy.frame or 1)]:getWidth(), texture[(enemy.frame or 1)]:getHeight()) end
gpl-3.0
EliHar/Pattern_recognition
torch1/extra/fftw3/dev/create-init.lua
3
2992
-- Adapted from https://github.com/torch/sdl2-ffi/blob/master/dev/create-init.lua print[[ -- Do not change this file manually -- Generated with dev/create-init.lua local ffi = require 'ffi' local C = ffi.load('fftw3') local ok, Cf = pcall(function () return ffi.load('fftw3f') end) if not ok then print('Warning: float version of libfftw3: libfftw3f.(so/dylib) not found') end local fftw = {C=C} local fftwf = {Cf = Cf} fftw.float = fftwf require 'fftw3.cdefs' local defines = require 'fftw3.defines' defines.register_hashdefs(fftw, C) defines.register_hashdefsf(fftwf, Cf) local function register(luafuncname, funcname) local symexists, msg = pcall(function() local sym = C[funcname] end) if symexists then fftw[luafuncname] = C[funcname] end end local function registerf(luafuncname, funcname) local symexists, msg = pcall(function() local sym = Cf[funcname] end) if symexists then fftwf[luafuncname] = Cf[funcname] end end ]] local defined = {} local txt = io.open('cdefs.lua'):read('*all') for funcname in txt:gmatch('fftw_([^%=,%.%;<%s%(%)]+)%s*%(') do if funcname and not defined[funcname] then local luafuncname = funcname:gsub('^..', function(str) if str == 'RW' then return str else return string.lower(str:sub(1,1)) .. str:sub(2,2) end end) print(string.format("register('%s', 'fftw_%s')", luafuncname, funcname)) defined[funcname] = true end end print() for defname in txt:gmatch('fftw_([^%=,%.%;<%s%(%)|%[%]]+)') do if not defined[defname] then print(string.format("register('%s', 'fftw_%s')", defname, defname)) end end print() print() print() local definedf = {} for funcname in txt:gmatch('fftwf_([^%=,%.%;<%s%(%)]+)%s*%(') do if funcname and not definedf[funcname] then local luafuncname = funcname:gsub('^..', function(str) if str == 'RW' then return str else return string.lower(str:sub(1,1)) .. str:sub(2,2) end end) print(string.format("registerf('%s', 'fftwf_%s')", luafuncname, funcname)) definedf[funcname] = true end end print() for defname in txt:gmatch('fftwf_([^%=,%.%;<%s%(%)|%[%]]+)') do if not definedf[defname] then print(string.format("registerf('%s', 'fftwf_%s')", defname, defname)) end end print[[ return fftw ]]
mit
weirdouncle/QSanguosha-For-Hegemony-personal
lang/zh_CN/Package/StandardWeiGeneral.lua
5
7220
--[[******************************************************************** Copyright (c) 2013-2015 Mogara This file is part of QSanguosha-Hegemony. This game is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. See the LICENSE file for more details. Mogara *********************************************************************]] -- translation for Standard General Package return { -- 魏势力 ["#caocao"] = "魏武帝", ["caocao"] = "曹操", ["jianxiong"] = "奸雄", [":jianxiong"] = "每当你受到伤害后,你可以获得造成此伤害的牌。", ["#simayi"] = "狼顾之鬼", ["simayi"] = "司马懿", ["fankui"] = "反馈", [":fankui"] = "每当你受到伤害后,你可以获得来源的一张牌。", ["guicai"] = "鬼才", [":guicai"] = "每当一名角色的判定牌生效前,你可以打出手牌代替之。", ["@guicai-card"] = CommonTranslationTable["@askforretrial"], ["~guicai"] = "选择一张手牌→点击确定", ["#xiahoudun"] = "独眼的罗刹", ["xiahoudun"] = "夏侯惇", ["ganglie"] = "刚烈", [":ganglie"] = "每当你受到伤害后,你可以判定,若结果不为红桃,来源选择一项:1.弃置两张手牌;2.受到你造成的1点伤害。", ["#zhangliao"] = "前将军", ["zhangliao"] = "张辽", ["tuxi"] = "突袭", [":tuxi"] = "摸牌阶段开始时,你可以放弃摸牌并选择一至两名有手牌的其他角色,获得这些角色的各一张手牌。", ["@tuxi-card"] = "你可以发动“突袭”", ["~tuxi"] = "选择 1-2 名其他角色→点击确定", ["#xuchu"] = "虎痴", ["xuchu"] = "许褚", ["luoyi"] = "裸衣", [":luoyi"] = "摸牌阶段,你可以少摸一张牌,若如此做,每当你于此回合内使用【杀】或【决斗】对目标角色造成伤害时,此伤害+1。", ["#LuoyiBuff"] = "%from 的“<font color=\"yellow\"><b>裸衣</b></font>”效果被触发,伤害从 %arg 点增加至 %arg2 点", ["#guojia"] = "早终的先知", ["guojia"] = "郭嘉", ["tiandu"] = "天妒", [":tiandu"] = "每当你的判定牌生效后,你可以获得之。", ["yiji"] = "遗计", [":yiji"] = "每当你受到1点伤害后,你可以观看牌堆顶的两张牌,然后将其中的一张牌交给一名角色,将另一张牌交给一名角色。", ["#zhenji"] = "薄幸的美人", ["zhenji"] = "甄姬", ["illustrator:zhenji"] = "DH", ["luoshen"] = "洛神", [":luoshen"] = "准备阶段开始时,你可以判定,若结果为黑色,你可以重复此流程。最后你获得所有的黑色判定牌。", ["#luoshen-move"] = "洛神(将此牌置于处理区)", ["qingguo"] = "倾国", [":qingguo"] = "你可以将一张黑色手牌当【闪】使用或打出。", ["#xiahouyuan"] = "疾行的猎豹", ["xiahouyuan"] = "夏侯渊", ["shensu"] = "神速", [":shensu"] = "你可以跳过判定阶段和摸牌阶段,视为使用【杀】;你可以跳过出牌阶段并弃置一张装备牌,视为使用【杀】。", ["@shensu1"] = "你可以跳过判定阶段和摸牌阶段发动“神速”", ["@shensu2"] = "你可以跳过出牌阶段并弃置一张装备牌发动“神速”", ["~shensu1"] = "选择【杀】的目标角色→点击确定", ["~shensu2"] = "选择一张装备牌→选择【杀】的目标角色→点击确定", ["#zhanghe"] = "料敌机先", ["zhanghe"] = "张郃", ["illustrator:zhanghe"] = "张帅", ["qiaobian"] = "巧变", [":qiaobian"] = "你可以弃置一张手牌,跳过一个阶段(准备阶段和结束阶段除外)," .. "然后若你以此法:跳过摸牌阶段,你可以选择有手牌的一至两名其他角色,然后获得这些角色的各一张手牌;" .. "跳过出牌阶段,你可以将一名角色判定区/装备区里的一张牌置入另一名角色的判定区/装备区。", ["@qiaobian-2"] = "你可以依次获得一至两名其他角色的各一张手牌", ["@qiaobian-3"] = "你可以将场上的一张牌移动至另一名角色相应的区域内", ["#qiaobian"] = "你可以弃置 1 张手牌跳过 <font color='yellow'><b> %arg </b></font> 阶段", ["~qiaobian2"] = "选择 1-2 名其他角色→点击确定", ["~qiaobian3"] = "选择一名角色→点击确定", ["@qiaobian-to"] = "请选择移动【%arg】的目标角色", ["#xuhuang"] = "周亚夫之风", ["xuhuang"] = "徐晃", ["illustrator:xuhuang"] = "Tuu.", ["duanliang"] = "断粮", [":duanliang"] = "你可以将一张不为锦囊牌的黑色牌当【兵粮寸断】使用;你能对距离为2的角色使用【兵粮寸断】。", ["#caoren"] = "大将军", ["caoren"] = "曹仁", ["jushou"] = "据守", [":jushou"] = "结束阶段开始时,你可以摸三张牌,然后叠置。", ["#dianwei"] = "古之恶来", ["dianwei"] = "典韦", ["illustrator:dianwei"] = "小冷", ["qiangxi"] = "强袭", [":qiangxi"] = "出牌阶段限一次,你可以失去1点体力或弃置一张武器牌,并选择你攻击范围内的一名角色,对其造成1点伤害。", ["#xunyu"] = "王佐之才", ["xunyu"] = "荀彧", ["illustrator:xunyu"] = "LiuHeng", ["quhu"] = "驱虎", [":quhu"] = "出牌阶段限一次,你可以与一名体力值大于你的角色拼点:当你赢后,其对其攻击范围内你选择的一名角色造成1点伤害;当你没赢后,其对你造成1点伤害。", ["@quhu-damage"] = "请选择 %src 攻击范围内的一名角色", ["jieming"] = "节命", [":jieming"] = "每当你受到1点伤害后,你可以令一名角色将手牌补至X张(X为其体力上限且至多为5)。", ["jieming-invoke"] = "你可以发动“节命”<br/> <b>操作提示</b>: 选择一名角色→点击确定<br/>", ["#QuhuNoWolf"] = "%from “<font color=\"yellow\"><b>驱虎</b></font>”拼点赢,由于 %to 攻击范围内没有其他角色,结算中止", ["#caopi"] = "霸业的继承者", ["caopi"] = "曹丕", ["illustrator:caopi"] = "DH", ["xingshang"] = "行殇", [":xingshang"] = "每当其他角色死亡时,你可以获得其所有牌。", ["fangzhu"] = "放逐", [":fangzhu"] = "每当你受到伤害后,你可以令一名其他角色摸X张牌(X为你已损失的体力值),然后其叠置。", ["fangzhu-invoke"] = "你可以发动“放逐”<br/> <b>操作提示</b>: 选择一名其他角色→点击确定<br/>", ["#yuejin"] = "奋强突固", ["yuejin"] = "乐进", ["illustrator:yuejin"] = "巴萨小马", ["xiaoguo"] = "骁果", [":xiaoguo"] = "其他角色的结束阶段开始时,你可以弃置一张基本牌,令其选择一项:1.弃置一张装备牌;2.受到你造成的1点伤害。", ["@xiaoguo"] = "你可以弃置一张基本牌发动“骁果”", ["@xiaoguo-discard"] = "请弃置一张装备牌,否则受到 1 点伤害", }
gpl-3.0
rlcevg/Zero-K
units/armasp.lua
5
3428
unitDef = { unitname = [[armasp]], name = [[Air Repair/Rearm Pad]], description = [[Repairs and Rearms Aircraft, repairs at 2.5 e/s per pad]], acceleration = 0, activateWhenBuilt = true, brakeRate = 0, buildAngle = 0, buildCostEnergy = 350, buildCostMetal = 350, buildDistance = 6, builder = true, buildoptions = { }, buildPic = [[ARMASP.png]], buildTime = 350, category = [[UNARMED FLOAT]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[144 40 144]], collisionVolumeTest = 1, collisionVolumeType = [[box]], corpse = [[DEAD]], customParams = { pad_count = 4, description_de = [[Repariert automatisch eigene/verbündete Lufteinheiten, jedes Pad repariert mit 2.5 e/s]], description_pl = [[Stacja naprawy i dozbrajania samolotow, moc stanowiska 2.5 e/s]], helptext = [[The Air Repair/Rearm Pad repairs up to four aircraft at a time. It also refuels/rearms bombers.]], helptext_de = [[Das Air Repair/Rearm Pad repariert bis zu vier Flugzeuge gleichzeitig. Es befüllt und betankt außerdem die Bomber.]], helptext_pl = [[Ta Stacja moze naprawiac samoloty i odnawiac amunicje bombowcom. Posiada 4 stanowiska.]], removewait = 1, }, explodeAs = [[LARGE_BUILDINGEX]], footprintX = 9, footprintZ = 9, iconType = [[building]], idleAutoHeal = 5, idleTime = 1800, mass = 100000, maxDamage = 1860, maxSlope = 18, maxVelocity = 0, minCloakDistance = 150, objectName = [[airpad.s3o]], script = [[armasp.lua]], seismicSignature = 4, selfDestructAs = [[LARGE_BUILDINGEX]], showNanoSpray = false, side = [[ARM]], sightDistance = 273, turnRate = 0, waterline = 8, yardMap = [[ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo]], featureDefs = { DEAD = { description = [[Wreckage - Air Repair/Rearm Pad]], blocking = true, category = [[corpses]], damage = 1860, energy = 0, featureDead = [[HEAP]], featurereclamate = [[SMUDGE01]], footprintX = 9, footprintZ = 9, height = [[40]], hitdensity = [[100]], metal = 140, object = [[airpad_dead.s3o]], reclaimable = true, reclaimTime = 140, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, HEAP = { description = [[Debris - Air Repair/Rearm Pad]], blocking = false, category = [[heaps]], damage = 1860, energy = 0, featurereclamate = [[SMUDGE01]], footprintX = 1, footprintZ = 1, height = [[4]], hitdensity = [[100]], metal = 70, object = [[debris4x4a.s3o]], reclaimable = true, reclaimTime = 70, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, }, } return lowerkeys({ armasp = unitDef })
gpl-2.0
ViolyS/RayUI_VS
Interface/AddOns/RayUI/config/filters/raid.lua
1
45236
---------------------------------------------------------- -- Load RayUI Environment ---------------------------------------------------------- RayUI:LoadEnv("Raid") local function ClassBuff(id, point, color, anyUnit, onlyShowMissing) local r, g, b = unpack(color) return {["enabled"] = true, ["id"] = id, ["point"] = point, ["color"] = {["r"] = r, ["g"] = g, ["b"] = b}, ["anyUnit"] = anyUnit, ["onlyShowMissing"] = onlyShowMissing} end local function SpellName(id) local name = GetSpellInfo(id) if not name then R:Print("SpellID is not valid in raid aura list: "..id..".") return "Unknown" else return name end end local function Defaults(priorityOverride) return {["enable"] = true, ["priority"] = priorityOverride or 0, ["stackThreshold"] = 0} end _AuraWatchList = { PRIEST = { [194384] = ClassBuff(194384, "TOPRIGHT", {1, 0, 0.75}, true), -- Atonement [41635] = ClassBuff(41635, "BOTTOMRIGHT", {0.2, 0.7, 0.2}), -- Prayer of Mending [139] = ClassBuff(139, "BOTTOMLEFT", {0.4, 0.7, 0.2}), -- Renew [17] = ClassBuff(17, "TOPLEFT", {0.81, 0.85, 0.1}, true), -- Power Word: Shield [47788] = ClassBuff(47788, "LEFT", {221/255, 117/255, 0}, true), -- Guardian Spirit [33206] = ClassBuff(33206, "LEFT", {227/255, 23/255, 13/255}, true), -- Pain Suppression }, DRUID = { [774] = ClassBuff(774, "TOPRIGHT", {0.8, 0.4, 0.8}), -- Rejuvenation [155777] = ClassBuff(155777, "RIGHT", {0.8, 0.4, 0.8}), -- Germination [8936] = ClassBuff(8936, "BOTTOMLEFT", {0.2, 0.8, 0.2}), -- Regrowth [33763] = ClassBuff(33763, "TOPLEFT", {0.4, 0.8, 0.2}), -- Lifebloom [188550] = ClassBuff(188550, "TOPLEFT", {0.4, 0.8, 0.2}), -- Lifebloom T18 4pc [48438] = ClassBuff(48438, "BOTTOMRIGHT", {0.8, 0.4, 0}), -- Wild Growth [207386] = ClassBuff(207386, "TOP", {0.4, 0.2, 0.8}), -- Spring Blossoms [102352] = ClassBuff(102352, "LEFT", {0.2, 0.8, 0.8}), -- Cenarion Ward [200389] = ClassBuff(200389, "BOTTOM", {1, 1, 0.4}), -- Cultivation }, PALADIN = { [53563] = ClassBuff(53563, "TOPRIGHT", {0.7, 0.3, 0.7}), -- Beacon of Light [156910] = ClassBuff(156910, "TOPRIGHT", {0.7, 0.3, 0.7}), -- Beacon of Faith [200025] = ClassBuff(200025, "TOPRIGHT", {0.7, 0.3, 0.7}), -- Beacon of Virtue [1022] = ClassBuff(1022, "BOTTOMRIGHT", {0.2, 0.2, 1}, true), -- Hand of Protection [1044] = ClassBuff(1044, "BOTTOMRIGHT", {0.89, 0.45, 0}, true), -- Hand of Freedom [6940] = ClassBuff(6940, "BOTTOMRIGHT", {0.89, 0.1, 0.1}, true), -- Hand of Sacrifice [114163] = ClassBuff(114163, 'BOTTOMLEFT', {0.87, 0.7, 0.03}), -- Eternal Flame }, SHAMAN = { [61295] = ClassBuff(61295, "TOPRIGHT", {0.7, 0.3, 0.7}), -- Riptide }, MONK = { [119611] = ClassBuff(119611, "TOPLEFT", {0.8, 0.4, 0.8}), --Renewing Mist [116849] = ClassBuff(116849, "TOPRIGHT", {0.2, 0.8, 0.2}), -- Life Cocoon [124682] = ClassBuff(124682, "BOTTOMLEFT", {0.4, 0.8, 0.2}), -- Enveloping Mist [124081] = ClassBuff(124081, "BOTTOMRIGHT", {0.7, 0.4, 0}), -- Zen Sphere }, ROGUE = { [57934] = ClassBuff(57934, "TOPRIGHT", {227/255, 23/255, 13/255}), -- Tricks of the Trade }, WARRIOR = { [114030] = ClassBuff(114030, "TOPLEFT", {0.2, 0.2, 1}), -- Vigilance [3411] = ClassBuff(3411, "TOPRIGHT", {227/255, 23/255, 13/255}), -- Intervene }, PET = { [19615] = ClassBuff(19615, 'TOPLEFT', {227/255, 23/255, 13/255}, true), -- Frenzy [136] = ClassBuff(136, 'TOPRIGHT', {0.2, 0.8, 0.2}, true) --Mend Pet }, HUNTER = {}, --Keep even if it's an empty table, so a reference to G.unitframe.buffwatch[E.myclass][SomeValue] doesn't trigger error DEMONHUNTER = {}, WARLOCK = {}, MAGE = {}, DEATHKNIGHT = {}, } _ReverseTimerList = { } _RaidDebuffsList = { -- Ascending aura timer -- Add spells to this list to have the aura time count up from 0 -- NOTE: This does not show the aura, it needs to be in one of the other list too. ascending = { [89435] = Defaults(5), [89421] = Defaults(5), }, -- Any Zone debuffs = { [15007] = Defaults(16), -- Resurrection Sickness [39171] = Defaults(9), -- Mortal Strike [76622] = Defaults(9), -- Sunder Armor }, buffs = { --[871] = Defaults(15), -- Shield Wall }, -- Raid Debuffs instances = { [1147] = { -- Tomb of Sargeras -- Goroth [233279] = Defaults(), -- Shattering Star [230345] = Defaults(), -- Crashing Comet [231363] = Defaults(), -- Burning Armor [234264] = Defaults(), -- Melted Armor [233062] = Defaults(), -- Infernal Burning -- Demonic Inquisition [233430] = Defaults(), -- Ubearable Torment [233983] = Defaults(), -- Echoing Anguish -- Harjatan [231770] = Defaults(), -- Drenched [231998] = Defaults(), -- Jagged Abrasion [231729] = Defaults(), -- Aqueous Burst [234128] = Defaults(), -- Driven Assault -- Sisters of the Moon [236603] = Defaults(), -- Rapid Shot [234996] = Defaults(), -- Umbra Suffusion [234995] = Defaults(), -- Lunar Suffusion [236519] = Defaults(), -- Moon Burn [236697] = Defaults(), -- Deathly Screech [239264] = Defaults(), -- Lunar Flare (Tank) [236712] = Defaults(), -- Lunar Beacon [236304] = Defaults(), -- Incorporeal Shot [236550] = Defaults(), -- Discorporate (Tank) [236330] = Defaults(), -- Astral Vulnerability [236541] = Defaults(), -- Twilight Glaive [233263] = Defaults(), -- Embrace of the Eclipse -- Mistress Sassz'ine [230959] = Defaults(), -- Concealing Murk [232722] = Defaults(), -- Slicing Tornado [232913] = Defaults(), -- Befouling Ink [234621] = Defaults(), -- Devouring Maw [230201] = Defaults(), -- Burden of Pain (Tank) [230139] = Defaults(), -- Hydra Shot [232754] = Defaults(), -- Hydra Acid [230384] = Defaults(), -- Consuming Hunger [230358] = Defaults(), -- Thundering Shock -- The Desolate Host [236072] = Defaults(), -- Wailing Souls [236449] = Defaults(), -- Soulbind [236515] = Defaults(), -- Shattering Scream [235989] = Defaults(), -- Tormented Cries [236241] = Defaults(), -- Soul Rot [236361] = Defaults(), -- Spirit Chains [235968] = Defaults(), -- Grasping Darkness -- Maiden of Vigilance [235117] = Defaults(), -- Unstable Soul !needs review [240209] = Defaults(), -- Unstable Soul !needs review [235534] = Defaults(), -- Creator's Grace [235538] = Defaults(), -- Demon's Vigor [234891] = Defaults(), -- Wrath of the Creators [235569] = Defaults(), -- Hammer of Creation [235573] = Defaults(), -- Hammer of Obliteration [235213] = Defaults(), -- Light Infusion [235240] = Defaults(), -- Fel Infusion -- Fallen Avatar [239058] = Defaults(), -- Touch of Sargeras [239739] = Defaults(), -- Dark Mark [234059] = Defaults(), -- Unbound Chaos [240213] = Defaults(), -- Chaos Flames [236604] = Defaults(), -- Shadowy Blades [236494] = Defaults(), -- Desolate (Tank) -- Kil'jaeden [238999] = Defaults(), -- Darkness of a Thousand Souls [239216] = Defaults(), -- Darkness of a Thousand Souls (Dot) [239155] = Defaults(), -- Gravity Squeeze [234295] = Defaults(), -- Armageddon Rain [240908] = Defaults(), -- Armageddon Blast [239932] = Defaults(), -- Felclaws (Tank) [240911] = Defaults(), -- Armageddon Hail [238505] = Defaults(), -- Focused Dreadflame [238429] = Defaults(), -- Bursting Dreadflame [236710] = Defaults(), -- Shadow Reflection: Erupting [241822] = Defaults(), -- Choking Shadow [236555] = Defaults(), -- Deceiver's Veil }, [1114] = { -- Trial of Valor -- Odyn [227959] = Defaults(), -- Storm of Justice [227475] = Defaults(), -- Cleansing Flame [192044] = Defaults(), -- Expel Light [227781] = Defaults(), -- Glowing Fragment -- Guarm [228228] = Defaults(), -- Flame Lick [228248] = Defaults(), -- Frost Lick [228253] = Defaults(), -- Shadow Lick [227539] = Defaults(), -- Fiery Phlegm [227566] = Defaults(), -- Salty Spittle [227570] = Defaults(), -- Dark Discharge -- Helya [227903] = Defaults(), -- Orb of Corruption [228058] = Defaults(), -- Orb of Corrosion [228054] = Defaults(), -- Taint of the Sea [193367] = Defaults(), -- Fetid Rot [227982] = Defaults(), -- Bilewater Redox [228519] = Defaults(), -- Anchor Slam [202476] = Defaults(), -- Rabid [232450] = Defaults(), -- Corrupted Axion }, [1094] = { -- The Emerald Nightmare -- Nythendra [204504] = Defaults(1), -- Infested [205043] = Defaults(7), -- Infested mind [203096] = Defaults(6), -- Rot [204463] = Defaults(5), -- Volatile Rot [203045] = Defaults(2), -- Infested Ground [203646] = Defaults(3), -- Burst of Corruption -- Elerethe Renferal [210228] = Defaults(), -- Dripping Fangs [215307] = Defaults(), -- Web of Pain [215300] = Defaults(), -- Web of Pain [215460] = Defaults(), -- Necrotic Venom [213124] = Defaults(), -- Venomous Pool [210850] = Defaults(), -- Twisting Shadows [215489] = Defaults(), -- Venomous Pool -- Il'gynoth, Heart of the Corruption [208929] = Defaults(), -- Spew Corruption [210984] = Defaults(), -- Eye of Fate [209469] = Defaults(5), -- Touch of Corruption [208697] = Defaults(), -- Mind Flay -- Ursoc [198108] = Defaults(), -- Unbalanced [197943] = Defaults(), -- Overwhelm [204859] = Defaults(), -- Rend Flesh [205611] = Defaults(), -- Miasma [198006] = Defaults(), -- Focused Gaze [197980] = Defaults(), -- Nightmarish Cacophony -- Dragons of Nightmare [204731] = Defaults(1), -- Wasting Dread [203110] = Defaults(5), -- Slumbering Nightmare [207681] = Defaults(3), -- Nightmare Bloom [205341] = Defaults(5), -- Sleeping Fog [203770] = Defaults(4), -- Defiled Vines [203787] = Defaults(2), -- Volatile Infection -- Cenarius [210279] = Defaults(), -- Creeping Nightmares [213162] = Defaults(), -- Nightmare Blast [210315] = Defaults(), -- Nightmare Brambles [212681] = Defaults(), -- Cleansed Ground [211507] = Defaults(), -- Nightmare Javelin [211471] = Defaults(), -- Scorned Touch [211612] = Defaults(), -- Replenishing Roots [216516] = Defaults(), -- Ancient Dream -- Xavius [206005] = Defaults(), -- Dream Simulacrum [206651] = Defaults(), -- Darkening Soul [209158] = Defaults(), -- Blackening Soul [211802] = Defaults(), -- Nightmare Blades [206109] = Defaults(), -- Awakening to the Nightmare [209034] = Defaults(), -- Bonds of Terror [210451] = Defaults(), -- Bonds of Terror [208431] = Defaults(), -- Corruption: Descent into Madness [207409] = Defaults(), -- Madness [211634] = Defaults(), -- The Infinite Dark [208385] = Defaults(), -- Tainted Discharge }, [1088] = { -- The Nighthold -- Skorpyron [204766] = Defaults(), -- Energy Surge [214718] = Defaults(), -- Acidic Fragments [211801] = Defaults(), -- Volatile Fragments [204284] = Defaults(), -- Broken Shard (Protection) [204275] = Defaults(), -- Arcanoslash (Tank) [211659] = Defaults(), -- Arcane Tether (Tank debuff) [204483] = Defaults(), -- Focused Blast (Stun) -- Chronomatic Anomaly [206607] = Defaults(), -- Chronometric Particles (Tank stack debuff) [206609] = Defaults(), -- Time Release (Heal buff/debuff) [205653] = Defaults(), -- Passage of Time [225901] = Defaults(), -- Time Bomb [207871] = Defaults(), -- Vortex (Mythic) [212099] = Defaults(), -- Temporal Charge [219966] = Defaults(4), -- 时间释放(红) [219965] = Defaults(4), -- 时间释放(黄) [219964] = Defaults(4), -- 时间释放(绿) [206617] = Defaults(3), -- 时间炸弹 -- Trilliax [206488] = Defaults(), -- Arcane Seepage [206641] = Defaults(), -- Arcane Spear (Tank) [206798] = Defaults(), -- Toxic Slice [214672] = Defaults(), -- Annihilation [214573] = Defaults(), -- Stuffed [214583] = Defaults(), -- Sterilize [208910] = Defaults(), -- Arcing Bonds [206838] = Defaults(), -- Succulent Feast -- Spellblade Aluriel [212492] = Defaults(), -- Annihilate (Tank) [212494] = Defaults(), -- Annihilated (Main Tank debuff) [212587] = Defaults(), -- Mark of Frost [212531] = Defaults(), -- Mark of Frost (marked) [212530] = Defaults(), -- Replicate: Mark of Frost [212647] = Defaults(), -- Frostbitten [212736] = Defaults(), -- Pool of Frost [213085] = Defaults(), -- Frozen Tempest [213621] = Defaults(), -- Entombed in Ice [213148] = Defaults(), -- Searing Brand Chosen [213181] = Defaults(), -- Searing Brand Stunned [213166] = Defaults(), -- Searing Brand [213278] = Defaults(), -- Burning Ground [213504] = Defaults(), -- Arcane Fog -- Tichondrius [206480] = Defaults(), -- Carrion Plague [215988] = Defaults(), -- Carrion Nightmare [208230] = Defaults(), -- Feast of Blood [212794] = Defaults(), -- Brand of Argus [216685] = Defaults(), -- Flames of Argus [206311] = Defaults(), -- Illusionary Night [206466] = Defaults(), -- Essence of Night [216024] = Defaults(), -- Volatile Wound [216027] = Defaults(), -- Nether Zone [216039] = Defaults(), -- Fel Storm [216726] = Defaults(), -- Ring of Shadows [216040] = Defaults(), -- Burning Soul -- Krosus [206677] = Defaults(), -- Searing Brand [205344] = Defaults(), -- Orb of Destruction -- High Botanist Tel'arn [218503] = Defaults(), -- Recursive Strikes (Tank) [219235] = Defaults(), -- Toxic Spores [218809] = Defaults(), -- Call of Night [218342] = Defaults(), -- Parasitic Fixate [218304] = Defaults(), -- Parasitic Fetter [218780] = Defaults(), -- Plasma Explosion -- Star Augur Etraeus [205984] = Defaults(), -- Gravitaional Pull [214167] = Defaults(), -- Gravitaional Pull [214335] = Defaults(), -- Gravitaional Pull [206936] = Defaults(), -- Icy Ejection [206388] = Defaults(), -- Felburst [206585] = Defaults(), -- Absolute Zero [206398] = Defaults(), -- Felflame [206589] = Defaults(), -- Chilled [205649] = Defaults(), -- Fel Ejection [206965] = Defaults(), -- Voidburst [206464] = Defaults(), -- Coronal Ejection [207143] = Defaults(), -- Void Ejection [206603] = Defaults(), -- Frozen Solid [207720] = Defaults(), -- Witness the Void [216697] = Defaults(), -- Frigid Pulse -- Grand Magistrix Elisande [209166] = Defaults(), -- Fast Time [211887] = Defaults(), -- Ablated [209615] = Defaults(), -- Ablation [209244] = Defaults(), -- Delphuric Beam [209165] = Defaults(), -- Slow Time [209598] = Defaults(), -- Conflexive Burst [209433] = Defaults(), -- Spanning Singularity [209973] = Defaults(), -- Ablating Explosion [209549] = Defaults(), -- Lingering Burn [211261] = Defaults(), -- Permaliative Torment [208659] = Defaults(), -- Arcanetic Ring -- Gul'dan [210339] = Defaults(), -- Time Dilation [180079] = Defaults(), -- Felfire Munitions [206875] = Defaults(), -- Fel Obelisk (Tank) [206840] = Defaults(), -- Gaze of Vethriz [206896] = Defaults(), -- Torn Soul [206221] = Defaults(), -- Empowered Bonds of Fel [208802] = Defaults(), -- Soul Corrosion [212686] = Defaults(), -- Flames of Sargeras }, [1026] = { -- Hellfire Citadel -- Hellfire Assault [184369] = Defaults(5), -- Howling Axe (Target) [180079] = Defaults(5), -- Felfire Munitions -- Iron Reaver [179897] = Defaults(5), -- Blitz [185978] = Defaults(5), -- Firebomb Vulnerability [182373] = Defaults(5), -- Flame Vulnerability [182280] = Defaults(5), -- Artillery (Target) [182074] = Defaults(5), -- Immolation [182001] = Defaults(5), -- Unstable Orb -- Kormrok [187819] = Defaults(5), -- Crush [181345] = Defaults(5), -- Foul Crush -- Hellfire High Council [184360] = Defaults(5), -- Fel Rage [184449] = Defaults(5), -- Mark of the Necromancer [185065] = Defaults(5), -- Mark of the Necromancer [184450] = Defaults(5), -- Mark of the Necromancer [185066] = Defaults(5), -- Mark of the Necromancer [184676] = Defaults(5), -- Mark of the Necromancer [184652] = Defaults(5), -- Reap -- Kilrogg Deadeye [181488] = Defaults(5), -- Vision of Death [188929] = Defaults(5), -- Heart Seeker (Target) [180389] = Defaults(5), -- Heart Seeker (DoT) -- Gorefiend [179867] = Defaults(5), -- Gorefiend's Corruption [181295] = Defaults(5), -- Digest [179977] = Defaults(5), -- Touch of Doom [179864] = Defaults(5), -- Shadow of Death [179909] = Defaults(5), -- Shared Fate (self root) [179908] = Defaults(5), -- Shared Fate (other players root) -- Shadow-Lord Iskar [181957] = Defaults(5), -- Phantasmal Winds [182200] = Defaults(5), -- Fel Chakram [182178] = Defaults(5), -- Fel Chakram [182325] = Defaults(5), -- Phantasmal Wounds [185239] = Defaults(5), -- Radiance of Anzu [185510] = Defaults(5), -- Dark Bindings [182600] = Defaults(5), -- Fel Fire [179219] = Defaults(5), -- Phantasmal Fel Bomb [181753] = Defaults(5), -- Fel Bomb -- Soulbound Construct (Socrethar) [182038] = Defaults(5), -- Shattered Defenses [188666] = Defaults(5), -- Eternal Hunger (Add fixate, Mythic only) [189627] = Defaults(5), -- Volatile Fel Orb (Fixated) [180415] = Defaults(5), -- Fel Prison -- Tyrant Velhari [185237] = Defaults(5), -- Touch of Harm [185238] = Defaults(5), -- Touch of Harm [185241] = Defaults(5), -- Edict of Condemnation [180526] = Defaults(5), -- Font of Corruption -- Fel Lord Zakuun [181508] = Defaults(5), -- Seed of Destruction [181653] = Defaults(5), -- Fel Crystals (Too Close) [179428] = Defaults(5), -- Rumbling Fissure (Soak) [182008] = Defaults(5), -- Latent Energy (Cannot soak) [179407] = Defaults(5), -- Disembodied (Player in Shadow Realm) -- Xhul'horac [188208] = Defaults(5), -- Ablaze [186073] = Defaults(5), -- Felsinged [186407] = Defaults(5), -- Fel Surge [186500] = Defaults(5), -- Chains of Fel [186063] = Defaults(5), -- Wasting Void [186333] = Defaults(5), -- Void Surge -- Mannoroth [181275] = Defaults(5), -- Curse of the Legion [181099] = Defaults(5), -- Mark of Doom [181597] = Defaults(5), -- Mannoroth's Gaze [182006] = Defaults(5), -- Empowered Mannoroth's Gaze [181841] = Defaults(5), -- Shadowforce [182088] = Defaults(5), -- Empowered Shadowforce -- Archimonde [184964] = Defaults(5), -- Shackled Torment [186123] = Defaults(5), -- Wrought Chaos [185014] = Defaults(5), -- Focused Chaos [186952] = Defaults(5), -- Nether Banish [186961] = Defaults(5), -- Nether Banish [189891] = Defaults(5), -- Nether Tear [183634] = Defaults(5), -- Shadowfel Burst [189895] = Defaults(5), -- Void Star Fixate [190049] = Defaults(5), -- Nether Corruption }, [988] = { -- 黑石铸造厂 --格鲁尔 [155080] = Defaults(4), -- 煉獄切割 分担组DOT [155078] = Defaults(3), -- 压迫打击 普攻坦克易伤 [162322] = Defaults(5), -- 炼狱打击 吃刀坦克易伤 [155506] = Defaults(2), -- 石化 --奥尔高格 [156203] = Defaults(5), -- 呕吐黑石 远程躲 [156374] = Defaults(5), -- 爆炸裂片 近战躲 [156297] = Defaults(3), -- 酸液洪流 副坦克易伤 [173471] = Defaults(4), -- 酸液巨口 主坦克DOT [155900] = Defaults(2), -- 翻滚之怒 击倒 --爆裂熔炉 [156932] = Defaults(5), -- 崩裂 [178279] = Defaults(4), -- 炸弹 [155192] = Defaults(4), -- 炸弹 [176121] = Defaults(6), -- 不稳定的火焰 点名八码爆炸 [155196] = Defaults(2), -- 锁定 [155743] = Defaults(5), -- 熔渣池 [155240] = Defaults(3), -- 淬火 坦克易伤 [155242] = Defaults(3), -- 高热 三层换坦 [155225] = Defaults(5), -- 熔化 点名 [155223] = Defaults(5), -- 熔化 --汉斯加尔与弗兰佐克 [157139] = Defaults(3), -- 折脊碎椎 跳跃易伤 [160838] = Defaults(2), -- 干扰怒吼 [160845] = Defaults(2), -- 干扰怒吼 [160847] = Defaults(2), -- 干扰怒吼 [160848] = Defaults(2), -- 干扰怒吼 [155818] = Defaults(4), -- 灼热燃烧 场地边缘的火 --缚火者卡格拉兹 [154952] = Defaults(3), -- 锁定 [155074] = Defaults(1), -- 焦灼吐息 坦克易伤 [155049] = Defaults(2), -- 火焰链接 [154932] = Defaults(4), -- 熔岩激流 点名分摊 [155277] = Defaults(5), -- 炽热光辉 点名AOE [155314] = Defaults(1), -- 岩浆猛击 冲锋火线 [163284] = Defaults(2), -- 升腾烈焰 坦克DOT --克罗莫格 [156766] = Defaults(1), -- 扭曲护甲 坦克易伤 [157059] = Defaults(2), -- 纠缠之地符文 [161839] = Defaults(3), -- 破碎大地符文 [161923] = Defaults(3), -- 破碎大地符文 --兽王达玛克 [154960] = Defaults(4), -- 长矛钉刺 [155061] = Defaults(1), -- 狂乱撕扯 狼阶段流血 [162283] = Defaults(1), -- 狂乱撕扯 BOSS继承的流血 [154989] = Defaults(3), -- 炼狱吐息 [154981] = Defaults(5), -- 爆燃 秒驱 [155030] = Defaults(2), -- 炽燃利齿 龙阶段坦克易伤 [155236] = Defaults(2), -- 碾碎护甲 象阶段坦克易伤 [155499] = Defaults(3), -- 高热弹片 [155657] = Defaults(4), -- 烈焰灌注 [159044] = Defaults(1), -- 强震 [162277] = Defaults(1), -- 强震 --主管索戈尔 [155921] = Defaults(2), -- 点燃 坦克易伤 [165195] = Defaults(4), -- 实验型脉冲手雷 [156310] = Defaults(3), -- 熔岩震击 [159481] = Defaults(3), -- 延时攻城炸弹 [164380] = Defaults(2), -- 燃烧 [164280] = Defaults(2), -- 热能冲击 --钢铁女武神 [156631] = Defaults(2), -- 急速射击 [164271] = Defaults(3), -- 穿透射击 [158601] = Defaults(1), -- 主炮轰击 [156214] = Defaults(4), -- 震颤暗影 [158315] = Defaults(2), -- 暗影猎杀 [159724] = Defaults(3), -- 鲜血仪式 [158010] = Defaults(2), -- 浸血觅心者 [158692] = Defaults(1), -- 致命投掷 [158702] = Defaults(2), -- 锁定 [158683] = Defaults(3), -- 堕落之血 --Blackhand [156096] = Defaults(5), --MARKEDFORDEATH [156107] = Defaults(4), --IMPALED [156047] = Defaults(2), --SLAGGED [156401] = Defaults(4), --MOLTENSLAG [156404] = Defaults(3), --BURNED [158054] = Defaults(4), --SHATTERINGSMASH 158054 155992 159142 [156888] = Defaults(5), --OVERHEATED [157000] = Defaults(2), --ATTACHSLAGBOMBS }, [994] = { --悬槌堡 -- 1 卡加斯 [158986] = Defaults(2), -- 冲锋 [159178] = Defaults(5), -- 迸裂创伤 [162497] = Defaults(3), -- 搜寻猎物 [163130] = Defaults(3), -- 着火 -- 2 屠夫 [156151] = Defaults(3), -- 捶肉槌 [156147] = Defaults(5), -- 切肉刀 [156152] = Defaults(3), -- 龟裂创伤 [163046] = Defaults(4), -- 白鬼硫酸 -- 3 泰克图斯 [162346] = Defaults(4), -- 晶化弹幕 点名 [162370] = Defaults(3), -- 晶化弹幕 踩到 -- 4 布兰肯斯波 [163242] = Defaults(5), -- 感染孢子 [159426] = Defaults(5), -- 回春孢子 [163241] = Defaults(4), -- 溃烂 [159220] = Defaults(2), -- 死疽吐息 [160179] = Defaults(2), -- 蚀脑真菌 [165223] = Defaults(6), -- 爆裂灌注 [163666] = Defaults(3), -- 脉冲高热 -- 5 独眼魔双子 [155569] = Defaults(3), -- 受伤 [158241] = Defaults(4), -- 烈焰 [163372] = Defaults(4), -- 奥能动荡 [167200] = Defaults(3), -- 奥术致伤 [163297] = Defaults(3), -- 扭曲奥能 -- 6 克拉戈 [172813] = Defaults(5), -- 魔能散射:冰霜 [162185] = Defaults(5), -- 魔能散射:火焰 [162184] = Defaults(3), -- 魔能散射:暗影 [162186] = Defaults(2), -- 魔能散射:奥术 [161345] = Defaults(2), -- 压制力场 [161242] = Defaults(3), -- 废灵标记 [172886] = Defaults(4), -- 废灵璧垒 [172895] = Defaults(4), -- 魔能散射:邪能 点名 [172917] = Defaults(4), -- 魔能散射:邪能 踩到 [163472] = Defaults(2), -- 统御之力 -- 7 元首 [157763] = Defaults(3), -- 锁定 [159515] = Defaults(4), -- 狂莽突击 [156225] = Defaults(4), -- 烙印 [164004] = Defaults(4), -- 烙印:偏移 [164006] = Defaults(4), -- 烙印:强固 [164005] = Defaults(4), -- 烙印:复制 [158605] = Defaults(2), -- 混沌标记 [164176] = Defaults(2), -- 混沌标记:偏移 [164178] = Defaults(2), -- 混沌标记:强固 [164191] = Defaults(2), -- 混沌标记:复制 }, [953] = { --Siege of Orgrimmar --Immerseus [143297] = Defaults(5), --Sha Splash [143459] = Defaults(4), --Sha Residue [143524] = Defaults(4), --Purified Residue [143286] = Defaults(4), --Seeping Sha [143413] = Defaults(3), --Swirl [143411] = Defaults(3), --Swirl [143436] = Defaults(2), --Corrosive Blast (tanks) [143579] = Defaults(3), --Sha Corruption (Heroic Only) --Fallen Protectors [143239] = Defaults(4), --Noxious Poison [144176] = Defaults(2), --Lingering Anguish [143023] = Defaults(3), --Corrupted Brew [143301] = Defaults(2), --Gouge [143564] = Defaults(3), --Meditative Field [143010] = Defaults(3), --Corruptive Kick [143434] = Defaults(6), --Shadow Word:Bane (Dispell) [143840] = Defaults(6), --Mark of Anguish [143959] = Defaults(4), --Defiled Ground [143423] = Defaults(6), --Sha Sear [143292] = Defaults(5), --Fixate [144176] = Defaults(5), --Shadow Weakness [147383] = Defaults(4), --Debilitation (Heroic Only) --Norushen [146124] = Defaults(2), --Self Doubt (tanks) [146324] = Defaults(4), --Jealousy [144639] = Defaults(6), --Corruption [144850] = Defaults(5), --Test of Reliance [145861] = Defaults(6), --Self-Absorbed (Dispell) [144851] = Defaults(2), --Test of Confiidence (tanks) [146703] = Defaults(3), --Bottomless Pit [144514] = Defaults(6), --Lingering Corruption [144849] = Defaults(4), --Test of Serenity --Sha of Pride [144358] = Defaults(2), --Wounded Pride (tanks) [144843] = Defaults(3), --Overcome [146594] = Defaults(4), --Gift of the Titans [144351] = Defaults(6), --Mark of Arrogance [144364] = Defaults(4), --Power of the Titans [146822] = Defaults(6), --Projection [146817] = Defaults(5), --Aura of Pride [144774] = Defaults(2), --Reaching Attacks (tanks) [144636] = Defaults(5), --Corrupted Prison [144574] = Defaults(6), --Corrupted Prison [145215] = Defaults(4), --Banishment (Heroic) [147207] = Defaults(4), --Weakened Resolve (Heroic) [144574] = Defaults(6), --Corrupted Prison [144574] = Defaults(6), --Corrupted Prison --Galakras [146765] = Defaults(5), --Flame Arrows [147705] = Defaults(5), --Poison Cloud [146902] = Defaults(2), --Poison Tipped blades --Iron Juggernaut [144467] = Defaults(2), --Ignite Armor [144459] = Defaults(5), --Laser Burn [144498] = Defaults(5), --Napalm Oil [144918] = Defaults(5), --Cutter Laser [146325] = Defaults(6), --Cutter Laser Target --Kor'kron Dark Shaman [144089] = Defaults(6), --Toxic Mist [144215] = Defaults(2), --Froststorm Strike (Tank only) [143990] = Defaults(2), --Foul Geyser (Tank only) [144304] = Defaults(2), --Rend [144330] = Defaults(6), --Iron Prison (Heroic) --General Nazgrim [143638] = Defaults(6), --Bonecracker [143480] = Defaults(5), --Assassin's Mark [143431] = Defaults(6), --Magistrike (Dispell) [143494] = Defaults(2), --Sundering Blow (Tanks) [143882] = Defaults(5), --Hunter's Mark --Malkorok [142990] = Defaults(2), --Fatal Strike (Tank debuff) [142913] = Defaults(6), --Displaced Energy (Dispell) [142863] = Defaults(1), --Strong Ancient Barrier [142864] = Defaults(1), --Strong Ancient Barrier [142865] = Defaults(1), --Strong Ancient Barrier [143919] = Defaults(5), --Languish (Heroic) --Spoils of Pandaria [145685] = Defaults(2), --Unstable Defensive System [144853] = Defaults(3), --Carnivorous Bite [145987] = Defaults(5), --Set to Blow [145218] = Defaults(4), --Harden Flesh [145230] = Defaults(1), --Forbidden Magic [146217] = Defaults(4), --Keg Toss [146235] = Defaults(4), --Breath of Fire [145523] = Defaults(4), --Animated Strike [142983] = Defaults(6), --Torment (the new Wrack) [145715] = Defaults(3), --Blazing Charge [145747] = Defaults(5), --Bubbling Amber [146289] = Defaults(4), --Mass Paralysis --Thok the Bloodthirsty [143766] = Defaults(2), --Panic (tanks) [143773] = Defaults(2), --Freezing Breath (tanks) [143452] = Defaults(1), --Bloodied [146589] = Defaults(5), --Skeleton Key (tanks) [143445] = Defaults(6), --Fixate [143791] = Defaults(5), --Corrosive Blood [143777] = Defaults(3), --Frozen Solid (tanks) [143780] = Defaults(4), --Acid Breath [143800] = Defaults(5), --Icy Blood [143428] = Defaults(4), --Tail Lash --Siegecrafter Blackfuse [144236] = Defaults(4), --Pattern Recognition [144466] = Defaults(5), --Magnetic Crush [143385] = Defaults(2), --Electrostatic Charge (tank) [143856] = Defaults(6), --Superheated --Paragons of the Klaxxi [143617] = Defaults(5), --Blue Bomb [143701] = Defaults(5), --Whirling (stun) [143702] = Defaults(5), --Whirling [142808] = Defaults(6), --Fiery Edge [143609] = Defaults(5), --Yellow Sword [143610] = Defaults(5), --Red Drum [142931] = Defaults(2), --Exposed Veins [143619] = Defaults(5), --Yellow Bomb [143735] = Defaults(6), --Caustic Amber [146452] = Defaults(5), --Resonating Amber [142929] = Defaults(2), --Tenderizing Strikes [142797] = Defaults(5), --Noxious Vapors [143939] = Defaults(5), --Gouge [143275] = Defaults(2), --Hewn [143768] = Defaults(2), --Sonic Projection [142532] = Defaults(6), --Toxin: Blue [142534] = Defaults(6), --Toxin: Yellow [143279] = Defaults(2), --Genetic Alteration [143339] = Defaults(6), --Injection [142649] = Defaults(4), --Devour [146556] = Defaults(6), --Pierce [142671] = Defaults(6), --Mesmerize [143979] = Defaults(2), --Vicious Assault [143607] = Defaults(5), --Blue Sword [143614] = Defaults(5), --Yellow Drum [143612] = Defaults(5), --Blue Drum [142533] = Defaults(6), --Toxin: Red [143615] = Defaults(5), --Red Bomb [143974] = Defaults(2), --Shield Bash (tanks) --Garrosh Hellscream [144582] = Defaults(4), --Hamstring [144954] = Defaults(4), --Realm of Y'Shaarj [145183] = Defaults(2), --Gripping Despair (tanks) [144762] = Defaults(4), --Desecrated [145071] = Defaults(5), --Touch of Y'Sharrj [148718] = Defaults(4), --Fire Pit }, [930] = { -- Throne of Thunder --Trash [138349] = Defaults(7), -- Static Wound [137371] = Defaults(7), -- Thundering Throw --Horridon [136767] = Defaults(7), --Triple Puncture --Council of Elders [136922] = Defaults(9), --霜寒刺骨 [137650] = Defaults(8), --幽暗之魂 [137641] = Defaults(7), --Soul Fragment [137359] = Defaults(7), --Shadowed Loa Spirit Fixate [137972] = Defaults(7), --Twisted Fate --Tortos [136753] = Defaults(7), --Slashing Talons [137633] = Defaults(7), --Crystal Shell --Megaera [137731] = Defaults(7), --Ignite Flesh --Ji-Kun [138309] = Defaults(7), --Slimed --Durumu the Forgotten [133767] = Defaults(7), --Serious Wound [133768] = Defaults(7), --Arterial Cut --Primordius [136050] = Defaults(7), --Malformed Blood --Dark Animus [138569] = Defaults(7), --Explosive Slam --Iron Qon [134691] = Defaults(7), --Impale [134647] = Defaults(7), --Scorched --Twin Consorts [137440] = Defaults(7), --Icy Shadows [137408] = Defaults(7), --Fan of Flames [137360] = Defaults(7), --Corrupted Healing [137341] = Defaults(8), --Corrupted Healing --Lei Shen [135000] = Defaults(7), --Decapitate [139011] = Defaults(8), --Decapitate --Ra-den }, [897] = { -- Heart of Fear -- Imperial Vizier Zor'lok [122761] = Defaults(7), -- Exhale [122760] = Defaults(7), -- Exhale [123812] = Defaults(7), --Pheromones of Zeal [122740] = Defaults(7), --Convert (MC) [122706] = Defaults(7), --Noise Cancelling (AMZ) -- Blade Lord Ta'yak [123180] = Defaults(7), -- Wind Step [123474] = Defaults(7), --Overwhelming Assault [122949] = Defaults(7), --Unseen Strike [124783] = Defaults(7), --Storm Unleashed -- Garalon [123081] = Defaults(8), --Pungency [122774] = Defaults(7), --Crush -- [123423] = Defaults(8), --Weak Points -- Wind Lord Mel'jarak [121881] = Defaults(8), --Amber Prison [122055] = Defaults(7), --Residue [122064] = Defaults(7), --Corrosive Resin --Amber-Shaper Un'sok [121949] = Defaults(7), --Parasitic Growth [122784] = Defaults(7), --Reshape Life --Grand Empress Shek'zeer [123707] = Defaults(7), --Eyes of the Empress [125390] = Defaults(7), --Fixate [123788] = Defaults(8), --Cry of Terror [124097] = Defaults(7), --Sticky Resin [123184] = Defaults(8), --Dissonance Field [124777] = Defaults(7), --Poison Bomb [124821] = Defaults(7), --Poison-Drenched Armor [124827] = Defaults(7), --Poison Fumes [124849] = Defaults(7), --Consuming Terror [124863] = Defaults(7), --Visions of Demise [124862] = Defaults(7), --Visions of Demise: Target [123845] = Defaults(7), --Heart of Fear: Chosen [123846] = Defaults(7), --Heart of Fear: Lure [125283] = Defaults(7), --Sha Corruption }, [896] = { -- Mogu'shan Vaults -- The Stone Guard [116281] = Defaults(7), --Cobalt Mine Blast -- Feng the Accursed [116784] = Defaults(9), --Wildfire Spark [116374] = Defaults(7), --Lightning Charge [116417] = Defaults(8), --Arcane Resonance -- Gara'jal the Spiritbinder [122151] = Defaults(8), --Voodoo Doll [116161] = Defaults(7), --Crossed Over [116278] = Defaults(7), --Soul Sever -- The Spirit Kings --Meng the Demented [117708] = Defaults(7), --Maddening Shout --Subetai the Swift [118048] = Defaults(7), --Pillaged [118047] = Defaults(7), --Pillage: Target [118135] = Defaults(7), --Pinned Down [118163] = Defaults(7), --Robbed Blind --Zian of the Endless Shadow [118303] = Defaults(7), --Undying Shadow: Fixate -- Elegon [117949] = Defaults(7), --Closed Circuit [132222] = Defaults(8), --Destabilizing Energies -- Will of the Emperor --Jan-xi and Qin-xi [116835] = Defaults(7), --Devastating Arc [132425] = Defaults(7), --Stomp -- Rage [116525] = Defaults(7), --Focused Assault (Rage fixate) -- Courage [116778] = Defaults(7), --Focused Defense (fixate) [117485] = Defaults(7), --Impeding Thrust (slow debuff) -- Strength [116550] = Defaults(7), --Energizing Smash (knock down) -- Titan Spark (Heroic) [116829] = Defaults(7), --Focused Energy (fixate) }, [886] = { -- Terrace of Endless Spring -- Protectors of the Endless [118091] = Defaults(6), --Defiled Ground [117519] = Defaults(6), --Touch of Sha [111850] = Defaults(6), --Lightning Prison: Targeted [117436] = Defaults(7), --Lightning Prison: Stunned [118191] = Defaults(6), --Corrupted Essence [117986] = Defaults(7), --Defiled Ground: Stacks -- Tsulong [122768] = Defaults(7), --Dread Shadows [122777] = Defaults(7), --Nightmares (dispellable) [122752] = Defaults(7), --Shadow Breath [122789] = Defaults(7), --Sunbeam [123012] = Defaults(7), --Terrorize: 5% (dispellable) [123011] = Defaults(7), --Terrorize: 10% (dispellable) [123036] = Defaults(7), --Fright (dispellable) [122858] = Defaults(6), --Bathed in Light -- Lei Shi [123121] = Defaults(7), --Spray [123705] = Defaults(7), --Scary Fog -- Sha of Fear [119414] = Defaults(7), --Breath of Fear [129147] = Defaults(7), --Onimous Cackle [119983] = Defaults(7), --Dread Spray [120669] = Defaults(7), --Naked and Afraid [75683] = Defaults(7), --Waterspout [120629] = Defaults(7), --Huddle in Terror [120394] = Defaults(7), --Eternal Darkness [129189] = Defaults(7), --Sha Globe [119086] = Defaults(7), --Penetrating Bolt [119775] = Defaults(7), --Reaching Attack }, [824] = { -- Dragon Soul -- Morchok [103687] = Defaults(7), -- RA.dbush Armor(擊碎護甲) -- Zon'ozz [103434] = Defaults(7), -- Disrupting Shadows(崩解之影) -- Yor'sahj [105171] = Defaults(8), -- Deep Corruption(深度腐化) [109389] = Defaults(8), -- Deep Corruption(深度腐化) [105171] = Defaults(7), -- Deep Corruption(深度腐化) [104849] = Defaults(9), -- Void Bolt(虛無箭) -- Hagara [104451] = Defaults(7), --寒冰之墓 -- Ultraxion [109075] = Defaults(7), --凋零之光 -- Blackhorn [107567] = Defaults(7), --蠻橫打擊 [108043] = Defaults(8), --破甲攻擊 [107558] = Defaults(9), --衰亡 -- Spine [105479] = Defaults(7), --燃燒血漿 [105490] = Defaults(8), --熾熱之握 [106200] = Defaults(9), --血液腐化:大地 [106199] = Defaults(10), --血液腐化:死亡 -- Madness [105841] = Defaults(7), --退化咬擊 [105445] = Defaults(8), --極熾高熱 [106444] = Defaults(9), --刺穿 }, [800] = { -- Firelands -- Rageface [99947] = Defaults(6), -- Face Rage --Baleroc [99256] = Defaults(5), -- 折磨 [99257] = Defaults(6), -- 受到折磨 [99516] = Defaults(7), -- Countdown --Majordomo Staghelm [98535] = Defaults(5), -- Leaping Flames --Burning Orbs [98451] = Defaults(6), -- Burning Orb }, [752] = { -- Baradin Hold [88954] = Defaults(6), -- Consuming Darkness }, }, }
mit
EliHar/Pattern_recognition
torch1/install/share/lua/5.1/luarocks/type_check.lua
14
11451
--- Type-checking functions. -- Functions and definitions for doing a basic lint check on files -- loaded by LuaRocks. --module("luarocks.type_check", package.seeall) local type_check = {} package.loaded["luarocks.type_check"] = type_check local cfg = require("luarocks.cfg") local deps = require("luarocks.deps") type_check.rockspec_format = "1.1" local string_1 = { _type = "string" } local number_1 = { _type = "number" } local mandatory_string_1 = { _type = "string", _mandatory = true } -- Syntax for type-checking tables: -- -- A type-checking table describes typing data for a value. -- Any key starting with an underscore has a special meaning: -- _type (string) is the Lua type of the value. Default is "table". -- _version (string) is the minimum rockspec_version that supports this value. Default is "1.0". -- _mandatory (boolean) indicates if the value is a mandatory key in its container table. Default is false. -- For "string" types only: -- _pattern (string) is the string-matching pattern, valid for string types only. Default is ".*". -- For "table" types only: -- _any (table) is the type-checking table for unspecified keys, recursively checked. -- _more (boolean) indicates that the table accepts unspecified keys and does not type-check them. -- Any other string keys that don't start with an underscore represent known keys and are type-checking tables, recursively checked. local rockspec_types = { rockspec_format = string_1, package = mandatory_string_1, version = { _type = "string", _pattern = "[%w.]+-[%d]+", _mandatory = true }, description = { summary = string_1, detailed = string_1, homepage = string_1, license = string_1, maintainer = string_1, }, dependencies = { platforms = {}, -- recursively defined below _any = string_1, }, supported_platforms = { _any = string_1, }, external_dependencies = { platforms = {}, -- recursively defined below _any = { program = string_1, header = string_1, library = string_1, } }, source = { _mandatory = true, platforms = {}, -- recursively defined below url = mandatory_string_1, md5 = string_1, file = string_1, dir = string_1, tag = string_1, branch = string_1, module = string_1, cvs_tag = string_1, cvs_module = string_1, }, build = { platforms = {}, -- recursively defined below type = string_1, install = { lua = { _more = true }, lib = { _more = true }, conf = { _more = true }, bin = { _more = true } }, copy_directories = { _any = string_1, }, _more = true, _mandatory = true }, hooks = { platforms = {}, -- recursively defined below post_install = string_1, }, deploy = { _version = "1.1", wrap_bin_scripts = { _type = "boolean", _version = "1.1" }, } } type_check.rockspec_order = {"rockspec_format", "package", "version", { "source", { "url", "tag", "branch", "md5" } }, { "description", {"summary", "detailed", "homepage", "license" } }, "supported_platforms", "dependencies", "external_dependencies", { "build", {"type", "modules", "copy_directories", "platforms"} }, "hooks"} rockspec_types.build.platforms._any = rockspec_types.build rockspec_types.dependencies.platforms._any = rockspec_types.dependencies rockspec_types.external_dependencies.platforms._any = rockspec_types.external_dependencies rockspec_types.source.platforms._any = rockspec_types.source rockspec_types.hooks.platforms._any = rockspec_types.hooks local manifest_types = { repository = { _mandatory = true, -- packages _any = { -- versions _any = { -- items _any = { arch = mandatory_string_1, modules = { _any = string_1 }, commands = { _any = string_1 }, dependencies = { _any = string_1 }, -- TODO: to be extended with more metadata. } } } }, modules = { _mandatory = true, -- modules _any = { -- providers _any = string_1 } }, commands = { _mandatory = true, -- modules _any = { -- commands _any = string_1 } }, dependencies = { -- each module _any = { -- each version _any = { -- each dependency _any = { name = string_1, constraints = { _any = { no_upgrade = { _type = "boolean" }, op = string_1, version = { string = string_1, _any = number_1, } } } } } } } } local function check_version(version, typetbl, context) local typetbl_version = typetbl._version or "1.0" if deps.compare_versions(typetbl_version, version) then if context == "" then return nil, "Invalid rockspec_format version number in rockspec? Please fix rockspec accordingly." else return nil, context.." is not supported in rockspec format "..version.." (requires version "..typetbl_version.."), please fix the rockspec_format field accordingly." end end return true end local type_check_table --- Type check an object. -- The object is compared against an archetypical value -- matching the expected type -- the actual values don't matter, -- only their types. Tables are type checked recursively. -- @param version string: The version of the item. -- @param item any: The object being checked. -- @param typetbl any: The type-checking table for the object. -- @param context string: A string indicating the "context" where the -- error occurred (the full table path), for error messages. -- @return boolean or (nil, string): true if type checking -- succeeded, or nil and an error message if it failed. -- @see type_check_table local function type_check_item(version, item, typetbl, context) assert(type(version) == "string") local ok, err = check_version(version, typetbl, context) if not ok then return nil, err end local item_type = type(item) or "nil" local expected_type = typetbl._type or "table" if expected_type == "number" then if not tonumber(item) then return nil, "Type mismatch on field "..context..": expected a number" end elseif expected_type == "string" then if item_type ~= "string" then return nil, "Type mismatch on field "..context..": expected a string, got "..item_type end if typetbl._pattern then if not item:match("^"..typetbl._pattern.."$") then return nil, "Type mismatch on field "..context..": invalid value "..item.." does not match '"..typetbl._pattern.."'" end end elseif expected_type == "table" then if item_type ~= expected_type then return nil, "Type mismatch on field "..context..": expected a table" else return type_check_table(version, item, typetbl, context) end elseif item_type ~= expected_type then return nil, "Type mismatch on field "..context..": expected "..expected_type end return true end local function mkfield(context, field) if context == "" then return field end return context.."."..field end --- Type check the contents of a table. -- The table's contents are compared against a reference table, -- which contains the recognized fields, with archetypical values -- matching the expected types -- the actual values of items in the -- reference table don't matter, only their types (ie, for field x -- in tbl that is correctly typed, type(tbl.x) == type(types.x)). -- If the reference table contains a field called MORE, then -- unknown fields in the checked table are accepted. -- If it contains a field called ANY, then its type will be -- used to check any unknown fields. If a field is prefixed -- with MUST_, it is mandatory; its absence from the table is -- a type error. -- Tables are type checked recursively. -- @param version string: The version of tbl. -- @param tbl table: The table to be type checked. -- @param typetbl table: The type-checking table, containing -- values for recognized fields in the checked table. -- @param context string: A string indicating the "context" where the -- error occurred (such as the name of the table the item is a part of), -- to be used by error messages. -- @return boolean or (nil, string): true if type checking -- succeeded, or nil and an error message if it failed. type_check_table = function(version, tbl, typetbl, context) assert(type(version) == "string") assert(type(tbl) == "table") assert(type(typetbl) == "table") local ok, err = check_version(version, typetbl, context) if not ok then return nil, err end for k, v in pairs(tbl) do local t = typetbl[k] or typetbl._any if t then local ok, err = type_check_item(version, v, t, mkfield(context, k)) if not ok then return nil, err end elseif typetbl._more then -- Accept unknown field else if not cfg.accept_unknown_fields then return nil, "Unknown field "..k end end end for k, v in pairs(typetbl) do if k:sub(1,1) ~= "_" and v._mandatory then if not tbl[k] then return nil, "Mandatory field "..mkfield(context, k).." is missing." end end end return true end local function check_undeclared_globals(globals, typetbl) local undeclared = {} for glob, _ in pairs(globals) do if not (typetbl[glob] or typetbl["MUST_"..glob]) then table.insert(undeclared, glob) end end if #undeclared == 1 then return nil, "Unknown variable: "..undeclared[1] elseif #undeclared > 1 then return nil, "Unknown variables: "..table.concat(undeclared, ", ") end return true end --- Type check a rockspec table. -- Verify the correctness of elements from a -- rockspec table, reporting on unknown fields and type -- mismatches. -- @return boolean or (nil, string): true if type checking -- succeeded, or nil and an error message if it failed. function type_check.type_check_rockspec(rockspec, globals) assert(type(rockspec) == "table") if not rockspec.rockspec_format then rockspec.rockspec_format = "1.0" end local ok, err = check_undeclared_globals(globals, rockspec_types) if not ok then return nil, err end return type_check_table(rockspec.rockspec_format, rockspec, rockspec_types, "") end --- Type check a manifest table. -- Verify the correctness of elements from a -- manifest table, reporting on unknown fields and type -- mismatches. -- @return boolean or (nil, string): true if type checking -- succeeded, or nil and an error message if it failed. function type_check.type_check_manifest(manifest, globals) assert(type(manifest) == "table") local ok, err = check_undeclared_globals(globals, manifest_types) if not ok then return nil, err end return type_check_table("1.0", manifest, manifest_types, "") end return type_check
mit
renolike/LuaSrcDiet
src/llex.lua
2
12301
--[[-------------------------------------------------------------------- llex.lua: Lua 5.1 lexical analyzer in Lua This file is part of LuaSrcDiet, based on Yueliang material. Copyright (c) 2008,2011 Kein-Hong Man <keinhong@gmail.com> The COPYRIGHT file describes the conditions under which this software may be distributed. ----------------------------------------------------------------------]] --[[-------------------------------------------------------------------- -- NOTES: -- * This is a version of the native 5.1.x lexer from Yueliang 0.4.0, -- with significant modifications to handle LuaSrcDiet's needs: -- (1) llex.error is an optional error function handler -- (2) seminfo for strings include their delimiters and no -- translation operations are performed on them -- * ADDED shbang handling has been added to support executable scripts -- * NO localized decimal point replacement magic -- * NO limit to number of lines -- * NO support for compatible long strings (LUA_COMPAT_LSTR) ----------------------------------------------------------------------]] local base = _G module "llex" local string = base.require "string" local find = string.find local match = string.match local sub = string.sub ---------------------------------------------------------------------- -- initialize keyword list, variables ---------------------------------------------------------------------- local kw = {} for v in string.gmatch([[ and break do else elseif end false for function if in local nil not or repeat return then true until while]], "%S+") do kw[v] = true end -- see init() for module variables (externally visible): -- tok, seminfo, tokln local z, -- source stream sourceid, -- name of source I, -- position of lexer buff, -- buffer for strings ln -- line number ---------------------------------------------------------------------- -- add information to token listing ---------------------------------------------------------------------- local function addtoken(token, info) local i = #tok + 1 tok[i] = token seminfo[i] = info tokln[i] = ln end ---------------------------------------------------------------------- -- handles line number incrementation and end-of-line characters ---------------------------------------------------------------------- local function inclinenumber(i, is_tok) local sub = sub local old = sub(z, i, i) i = i + 1 -- skip '\n' or '\r' local c = sub(z, i, i) if (c == "\n" or c == "\r") and (c ~= old) then i = i + 1 -- skip '\n\r' or '\r\n' old = old..c end if is_tok then addtoken("TK_EOL", old) end ln = ln + 1 I = i return i end ---------------------------------------------------------------------- -- initialize lexer for given source _z and source name _sourceid ---------------------------------------------------------------------- function init(_z, _sourceid) z = _z -- source sourceid = _sourceid -- name of source I = 1 -- lexer's position in source ln = 1 -- line number tok = {} -- lexed token list* seminfo = {} -- lexed semantic information list* tokln = {} -- line numbers for messages* -- (*) externally visible thru' module -------------------------------------------------------------------- -- initial processing (shbang handling) -------------------------------------------------------------------- local p, _, q, r = find(z, "^(#[^\r\n]*)(\r?\n?)") if p then -- skip first line I = I + #q addtoken("TK_COMMENT", q) if #r > 0 then inclinenumber(I, true) end end end ---------------------------------------------------------------------- -- returns a chunk name or id, no truncation for long names ---------------------------------------------------------------------- function chunkid() if sourceid and match(sourceid, "^[=@]") then return sub(sourceid, 2) -- remove first char end return "[string]" end ---------------------------------------------------------------------- -- formats error message and throws error -- * a simplified version, does not report what token was responsible ---------------------------------------------------------------------- function errorline(s, line) local e = error or base.error e(string.format("%s:%d: %s", chunkid(), line or ln, s)) end local errorline = errorline ------------------------------------------------------------------------ -- count separators ("=") in a long string delimiter ------------------------------------------------------------------------ local function skip_sep(i) local sub = sub local s = sub(z, i, i) i = i + 1 local count = #match(z, "=*", i) i = i + count I = i return (sub(z, i, i) == s) and count or (-count) - 1 end ---------------------------------------------------------------------- -- reads a long string or long comment ---------------------------------------------------------------------- local function read_long_string(is_str, sep) local i = I + 1 -- skip 2nd '[' local sub = sub local c = sub(z, i, i) if c == "\r" or c == "\n" then -- string starts with a newline? i = inclinenumber(i) -- skip it end while true do local p, q, r = find(z, "([\r\n%]])", i) -- (long range match) if not p then errorline(is_str and "unfinished long string" or "unfinished long comment") end i = p if r == "]" then -- delimiter test if skip_sep(i) == sep then buff = sub(z, buff, I) I = I + 1 -- skip 2nd ']' return buff end i = I else -- newline buff = buff.."\n" i = inclinenumber(i) end end--while end ---------------------------------------------------------------------- -- reads a string ---------------------------------------------------------------------- local function read_string(del) local i = I local find = find local sub = sub while true do local p, q, r = find(z, "([\n\r\\\"\'])", i) -- (long range match) if p then if r == "\n" or r == "\r" then errorline("unfinished string") end i = p if r == "\\" then -- handle escapes i = i + 1 r = sub(z, i, i) if r == "" then break end -- (EOZ error) p = find("abfnrtv\n\r", r, 1, true) ------------------------------------------------------ if p then -- special escapes if p > 7 then i = inclinenumber(i) else i = i + 1 end ------------------------------------------------------ elseif find(r, "%D") then -- other non-digits i = i + 1 ------------------------------------------------------ else -- \xxx sequence local p, q, s = find(z, "^(%d%d?%d?)", i) i = q + 1 if s + 1 > 256 then -- UCHAR_MAX errorline("escape sequence too large") end ------------------------------------------------------ end--if p else i = i + 1 if r == del then -- ending delimiter I = i return sub(z, buff, i - 1) -- return string end end--if r else break -- (error) end--if p end--while errorline("unfinished string") end ------------------------------------------------------------------------ -- main lexer function ------------------------------------------------------------------------ function llex() local find = find local match = match while true do--outer local i = I -- inner loop allows break to be used to nicely section tests while true do--inner ---------------------------------------------------------------- local p, _, r = find(z, "^([_%a][_%w]*)", i) if p then I = i + #r if kw[r] then addtoken("TK_KEYWORD", r) -- reserved word (keyword) else addtoken("TK_NAME", r) -- identifier end break -- (continue) end ---------------------------------------------------------------- local p, _, r = find(z, "^(%.?)%d", i) if p then -- numeral if r == "." then i = i + 1 end local _, q, r = find(z, "^%d*[%.%d]*([eE]?)", i) i = q + 1 if #r == 1 then -- optional exponent if match(z, "^[%+%-]", i) then -- optional sign i = i + 1 end end local _, q = find(z, "^[_%w]*", i) I = q + 1 local v = sub(z, p, q) -- string equivalent if not base.tonumber(v) then -- handles hex test also errorline("malformed number") end addtoken("TK_NUMBER", v) break -- (continue) end ---------------------------------------------------------------- local p, q, r, t = find(z, "^((%s)[ \t\v\f]*)", i) if p then if t == "\n" or t == "\r" then -- newline inclinenumber(i, true) else I = q + 1 -- whitespace addtoken("TK_SPACE", r) end break -- (continue) end ---------------------------------------------------------------- local r = match(z, "^%p", i) if r then buff = i local p = find("-[\"\'.=<>~", r, 1, true) if p then -- two-level if block for punctuation/symbols -------------------------------------------------------- if p <= 2 then if p == 1 then -- minus local c = match(z, "^%-%-(%[?)", i) if c then i = i + 2 local sep = -1 if c == "[" then sep = skip_sep(i) end if sep >= 0 then -- long comment addtoken("TK_LCOMMENT", read_long_string(false, sep)) else -- short comment I = find(z, "[\n\r]", i) or (#z + 1) addtoken("TK_COMMENT", sub(z, buff, I - 1)) end break -- (continue) end -- (fall through for "-") else -- [ or long string local sep = skip_sep(i) if sep >= 0 then addtoken("TK_LSTRING", read_long_string(true, sep)) elseif sep == -1 then addtoken("TK_OP", "[") else errorline("invalid long string delimiter") end break -- (continue) end -------------------------------------------------------- elseif p <= 5 then if p < 5 then -- strings I = i + 1 addtoken("TK_STRING", read_string(r)) break -- (continue) end r = match(z, "^%.%.?%.?", i) -- .|..|... dots -- (fall through) -------------------------------------------------------- else -- relational r = match(z, "^%p=?", i) -- (fall through) end end I = i + #r addtoken("TK_OP", r) -- for other symbols, fall through break -- (continue) end ---------------------------------------------------------------- local r = sub(z, i, i) if r ~= "" then I = i + 1 addtoken("TK_OP", r) -- other single-char tokens break end addtoken("TK_EOS", "") -- end of stream, return -- exit here ---------------------------------------------------------------- end--while inner end--while outer end
mit