content
stringlengths
5
1.05M
function onCreate() -- background shit makeLuaSprite('back', 'bg/lightwall', -340, -50); setLuaSpriteScrollFactor('back', 0.94, 0.94); scaleObject('back', 0.77, 0.77); addLuaSprite('back', false); makeLuaSprite('floor', 'bg/lightflooring', -240, -10); setLuaSpriteScrollFactor('floor', 0.94, 0.94); scaleObject('floor', 0.7, 0.7); addLuaSprite('floor', false); makeLuaSprite('chair', 'bg/ScruffyBG_chair', -240, -10); setLuaSpriteScrollFactor('chair', 0.94, 0.94); scaleObject('chair', 0.7, 0.7); addLuaSprite('chair', false); makeLuaSprite('desk', 'bg/ScruffyBG_desk', -240, -10); setLuaSpriteScrollFactor('desk', 0.94, 0.94); scaleObject('desk', 0.7, 0.7); addLuaSprite('desk', false); close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end
local ADDON, Engine = ... -- Lua API local abs = math.abs local assert, error = assert, error local floor = math.floor local ipairs, pairs = ipairs, pairs local pcall = pcall local print = print local select, type = select, type local setmetatable = setmetatable local tonumber, tostring = tonumber, tostring local strjoin, strmatch = string.join, string.match local tconcat = table.concat -- WOW API local GetBuildInfo = GetBuildInfo local GetCurrentResolution = GetCurrentResolution local GetCVar, SetCVar = GetCVar, SetCVar local GetCVarBool = GetCVarBool local GetLocale = GetLocale local GetScreenHeight = GetScreenHeight local GetScreenWidth = GetScreenWidth local GetScreenResolutions = GetScreenResolutions local InCombatLockdown, UnitAffectingCombat = InCombatLockdown, UnitAffectingCombat local IsLoggedIn = IsLoggedIn local IsMacClient = IsMacClient local StaticPopup_Show = StaticPopup_Show local StaticPopupDialogs = StaticPopupDialogs --~ local GetTime, C_TimerAfter = GetTime, C_Timer.After -- Engine Locals local events = {} -- event registry local timers = {} -- timer registry local configs = {} -- config registry saved between sessions local static_configs = {} -- static configurations set by the modules local handlers = {} -- handler registry local handler_elements = {} -- handler element registry local handler_elements_enabled_state = {} -- registry to "reverse" the enable/disable status of handler elements local modules = {} -- module registry local module_widgets = {} -- module widget registry local module_load_priority = { HIGH = {}, NORMAL = {}, LOW = {} } -- module load priorities local priority_hash = { HIGH = true, NORMAL = true, LOW = true } -- hashed priority table, for faster validity checks local priority_index = { "HIGH", "NORMAL", "LOW" } -- indexed/ordered priority table local default_module_priority = "NORMAL" -- default load priority for new modules local initialized_objects = {} -- hash table for initialized objects local enabled_objects = {} -- hash table for enabled modules, widgets and handler elements local object_name = {} -- table to hold the display names (ID) of all handlers, modules, widgets and elements local object_type = {} -- table to quickly look up what sort of object we're working with (handler, module, widget, element) local stack = {} -- local table stack for indexed tables local queue = {} -- queued function calls for the secure out of combat wrapper local scale = {} -- screen resolution and UI scale data local L = Engine:GetLocale() local BUILD = tonumber((select(2, GetBuildInfo()))) -- current game client build -- flags to track combat lockdown local _incombat = UnitAffectingCombat("player") local _inlockdown = InCombatLockdown() -- expansion and patch to game client build translation table local game_versions = { ["The Burning Crusade"] = 8606, ["TBC"] = 8606, -- using latest patch ["Before the Storm"] = 6180, ["2.0.0"] = 6080, -- download content only ["2.0.1"] = 6180, -- this is the "real" TBC patch, that came on DVDs, had Lua 5.1.1 and more. ["2.0.3"] = 6299, -- dark portal opening event ["2.0.4"] = 6314, ["2.0.5"] = 6320, ["2.0.6"] = 6337, ["2.0.7"] = 6383, ["2.0.8"] = 6403, ["2.0.9"] = 6403, -- only Chinese localization changes, but never released ["2.0.10"] = 6448, ["2.0.11"] = 6448, -- the actual release of the Chinese localization changes planned for 2.0.9 ["2.0.12"] = 6546, ["The Black Temple"] = 6692, ["2.1.0"] = 6692, ["2.1.0a"] = 6729, ["2.1.1"] = 6739, ["2.1.2"] = 6803, ["2.1.3"] = 6898, ["2.1.4"] = 6898, -- asian localization stuff again ["Voice Chat!"] = 7272, ["2.2.0"] = 7272, ["2.2.2"] = 7318, ["2.2.3"] = 7359, ["The Gods of Zul’Aman"] = 7561, ["2.3.0"] = 7561, ["2.3.2"] = 7741, ["2.3.3"] = 7799, ["Fury of the Sunwell"] = 8089, ["2.4.0"] = 8089, ["2.4.1"] = 8125, ["2.4.2"] = 8209, ["2.4.3"] = 8606, ["Wrath of the Lich King"] = 12340, ["WotLK"] = 12340, -- using latest patch ["Echoes of Doom"] = 9056, ["3.0.2"] = 9056, ["3.0.3"] = 9183, ["3.0.8"] = 9464, ["3.0.8a"] = 9506, ["3.0.9"] = 9551, ["Secrets of Ulduar"] = 9767, ["3.1.0"] = 9767, ["3.1.1"] = 9806, ["3.1.1a"] = 9835, ["3.1.2"] = 9901, ["3.1.3"] = 9947, ["Call of the Crusade"] = 10192, ["3.2.0"] = 10192, ["3.2.0a"] = 10314, ["3.2.2"] = 10482, ["3.2.2a"] = 10505, ["Fall of the Lich King"] = 10958, ["3.3.0"] = 10958, ["3.3.0a"] = 11159, ["3.3.2"] = 11403, ["3.3.3"] = 11685, ["3.3.3a"] = 11723, ["Defending the Ruby Sanctum"] = 12213, ["3.3.5"] = 12213, ["3.3.5a"] = 12340, ["Cataclysm"] = 15595, ["Cata"] = 15595, -- using latest patch ["Cataclysm Systems"] = 13164, ["4.0.1"] = 13164, ["4.0.1a"] = 13205, ["4.0.3"] = 13287, ["The Shattering"] = 13329, ["4.0.3a"] = 13329, ["4.0.6"] = 13596, ["4.0.6a"] = 13623, ["Rise of the Zandalari"] = 13914, ["4.1.0"] = 13914, ["4.1.0a"] = 14007, ["Rage of the Firelands"] = 14333, ["4.2.0"] = 14333, ["4.2.0a"] = 14480, ["4.2.2"] = 14545, ["Hour of Twilight"] = 15005, ["4.3.0"] = 15005, ["4.3.0a"] = 15050, ["4.3.2"] = 15211, ["4.3.3"] = 15354, ["4.3.4"] = 15595, ["Mists of Pandaria"] = 18414, ["MoP"] = 18414, -- using latest patch ["5.0.4"] = 16016, ["5.0.5"] = 16048, ["5.0.5a"] = 16057, ["5.0.5b"] = 16135, ["Landfall"] = 16309, ["5.1.0"] = 16309, ["5.1.0a"] = 16357, ["The Thunder King"] = 16650, ["5.2.0"] = 16650, -- 16826 ["Escalation"] = 17128, ["5.3.0"] = 17128, ["Siege of Orgrimmar"] = 17399, ["5.4.0"] = 17399, ["5.4.1"] = 17538, ["5.4.2"] = 17688, ["5.4.7"] = 18019, ["5.4.8"] = 18414, ["Warlords of Draenor"] = 20779, ["WoD"] = 20779, -- using 6.2.3, not latest ["The Iron Tide"] = 19034, ["6.0.2"] = 19034, ["6.0.3"] = 19243, ["6.0.3a"] = 19243, ["6.0.3b"] = 19342, ["Garrisons Update"] = 19702, ["6.1.0"] = 19702, ["6.1.2"] = 19865, ["Fury of Hellfire"] = 20173, ["6.2.0"] = 20173, ["6.2.0a"] = 20338, ["6.2.2"] = 20444, ["6.2.2a"] = 20574, ["6.2.3"] = 20779, ["6.2.3a"] = 20886, ["6.2.4"] = 21345, ["6.2.4a"] = 21463, ["6.2.4a"] = 21463, ["6.2.4a"] = 21463, ["6.2.4a"] = 21742, ["Legion"] = 21996, ["7.0.3"] = 21996 } DiabolicUI_DB = {} -- saved variables -- one frame is all we need local Frame = CreateFrame("Frame", nil, WorldFrame) -- parented to world frame to keep running even if the UI is hidden -- or... actually we need two frames. -_- -- This one is for UI positioning, because sometimes (multimonitor setups etc) UIParent won't work. local UICenter = CreateFrame("Frame", nil, UIParent) UICenter:SetFrameLevel(UIParent:GetFrameLevel()) UICenter:SetSize(UIParent:GetSize()) UICenter:SetPoint("CENTER", UIParent, "CENTER") ------------------------------------------------------------- -- Utility Functions ------------------------------------------------------------- -- syntax check (A shout-out to Haste for this one!) local check = function(self, value, num, ...) assert(type(num) == "number", L["Bad argument #%d to '%s': %s expected, got %s"]:format(2, "Check", "number", type(num))) for i = 1,select("#", ...) do if type(value) == select(i, ...) then return end end local types = strjoin(", ", ...) local name = strmatch(debugstack(2, 2, 0), ": in function [`<](.-)['>]") error(L["Bad argument #%d to '%s': %s expected, got %s"]:format(num, name, types, type(value)), 3) end -- error handling to keep the Engine running local protected_call = function(...) local _, catch = pcall(...) if catch and GetCVarBool("scriptErrors") then ScriptErrorsFrame_OnError(catch, false) end end -- wipe a table and push it to the stack local push = function(tbl) if #tbl > 0 then for i = #tbl, 1, -1 do tbl[i] = nil end end stack[#stack + 1] = tbl end -- pull a table from the stack, or create a new one local pop = function() if #stack > 0 then local tbl = stack[#stack] stack[#stack] = nil return tbl end return {} end local round = function(n, accuracy) return (floor(n*accuracy))/accuracy end local compare = function(a, b, accuracy) return not(abs(a-b) > 1/accuracy) end ------------------------------------------------------------- -- Event & OnUpdate Handler ------------------------------------------------------------- -- script handler for Frame's OnEvent local OnEvent = function(self, event, ...) local event_registry = events[event] if not event_registry then return end -- iterate engine events first local engine = Engine local engine_events = event_registry[engine] if engine_events then for index,func in ipairs(engine_events) do if type(func) == "string" then if engine[func] then engine[func](engine, event, ...) else return error(L["The Engine has no method named '%s'!"]:format(func)) end else func(engine, event, ...) end end end -- iterate handlers for name,handler in pairs(handlers) do if enabled_objects[handler] then local handler_events = event_registry[handler] if handler_events then for index,func in ipairs(handler_events) do if type(func) == "string" then if handler[func] then handler[func](handler, event, ...) else return error(L["The handler '%s' has no method named '%s'!"]:format(tostring(handler), func)) end else func(handler, event, ...) end end end -- iterate the elements registered to the current handler local elementPool = handler_elements[handler] for name,element in pairs(elementPool) do local element_events = event_registry[element] if element_events then for index,func in ipairs(element_events) do if type(func) == "string" then if element[func] then element[func](element, event, ...) else return error(L["The handler element '%s' has no method named '%s'!"]:format(tostring(element), func)) end else func(element, event, ...) end end end end end end -- iterate module events and fire according to priorities for index,priority in ipairs(priority_index) do for name,module in pairs(module_load_priority[priority]) do if enabled_objects[module] then local module_events = event_registry[module] if module_events then for index,func in ipairs(module_events) do if type(func) == "string" then if module[func] then module[func](module, event, ...) else return error(L["The module '%s' has no method named '%s'!"]:format(tostring(module), func)) end else func(module, event, ...) end end end -- iterate the widgets registered to the current module local widgetPool = module_widgets[module] for name,widget in pairs(widgetPool) do local widget_events = event_registry[widget] if widget_events then for index,func in ipairs(widget_events) do if type(func) == "string" then if widget[func] then widget[func](widget, event, ...) else return error(L["The module widget '%s' has no method named '%s'!"]:format(tostring(widget), func)) end else func(widget, event, ...) end end end end end end end end -- script handler for Frame's OnUpdate local OnUpdate = function(self, elapsed, ...) end -- engine and object methods local Fire = function(self, message, ...) self:Check(message, 1, "string") local event_registry = events[message] if not event_registry then return end -- iterate engine messages first local engine = Engine local engine_events = event_registry[engine] if engine_events then for index,func in ipairs(engine_events) do if type(func) == "string" then if engine[func] then engine[func](engine, message, ...) else return error(L["The Engine has no method named '%s'!"]:format(func)) end else func(engine, message, ...) end end end -- iterate handlers for name,handler in pairs(handlers) do if enabled_objects[handler] then local handler_events = event_registry[handler] if handler_events then for index,func in ipairs(handler_events) do if type(func) == "string" then if handler[func] then handler[func](handler, message, ...) else return error(L["The handler '%s' has no method named '%s'!"]:format(tostring(handler), func)) end else func(handler, message, ...) end end end end end -- iterate module messages and fire according to priorities for index,priority in ipairs(priority_index) do for name,module in pairs(module_load_priority[priority]) do if enabled_objects[module] then local module_events = event_registry[module] if module_events then for index,func in ipairs(module_events) do if type(func) == "string" then if module[func] then module[func](module, message, ...) else return error(L["The module '%s' has no method named '%s'!"]:format(tostring(module), func)) end else func(module, message, ...) end end end end end end end local RegisterEvent = function(self, event, func) self:Check(event, 1, "string") self:Check(func, 2, "string", "function", "nil") if not events[event] then events[event] = {} end if not events[event][self] then events[event][self] = {} end if not Frame:IsEventRegistered(event) then Frame:RegisterEvent(event) if not Frame.event_registry then Frame.event_registry = {} end if not Frame.event_registry[event] then Frame.event_registry[event] = 0 end Frame.event_registry[event] = Frame.event_registry[event] + 1 end if func == nil then func = "Update" end for i = 1, #events[event][self] do if events[event][self][i] == func then -- avoid duplicate calls to the same function return end end events[event][self][#events[event][self] + 1] = func end local IsEventRegistered = function(self, event, func) self:Check(event, 1, "string") self:Check(func, 2, "string", "function", "nil") if not Frame:IsEventRegistered(event) then return false end if not(events[event] and events[event][self]) then return false end if func == nil then func = "Update" end for i = 1, #events[event][self] do if events[event][self][i] == func then return true end end return false end local UnregisterEvent = function(self, event, func) self:Check(event, 1, "string") self:Check(func, 2, "string", "function", "nil") if not events[event] then return error(L["The event '%' isn't currently registered to any object."]:format(event)) end if not events[event][self] then return error(L["The event '%' isn't currently registered to the object '%s'."]:format(event, tostring(self))) end if func == nil then func = "Update" end for i = #events[event][self], 1, -1 do if events[event][self][i] == func then events[event][self][i] = nil if Frame.event_registry and Frame.event_registry[event] then Frame.event_registry[event] = Frame.event_registry[event] - 1 if Frame.event_registry[event] == 0 then Frame:UnregisterEvent(event) end end return end end if type(func) == "string" then if func == "Update" then return error(L["Attempting to unregister the general occurence of the event '%s' in the object '%s', when no such thing has been registered. Did you forget to add function or method name to UnregisterEvent?"]:format(event, tostring(self))) else return error(L["The method named '%s' isn't registered for the event '%s' in the object '%s'."]:format(func, event, tostring(self))) end else return error(L["The function call assigned to the event '%s' in the object '%s' doesn't exist."]:format(event, tostring(self))) end end local RegisterMessage = function(self, message, func) self:Check(message, 1, "string") self:Check(func, 2, "string", "function", "nil") if not events[message] then events[message] = {} end if not events[message][self] then events[message][self] = {} end if func == nil then func = "Update" end for i = 1, #events[message][self] do if events[message][self][i] == func then -- avoid duplicate calls to the same function return end end events[message][self][#events[message][self] + 1] = func end local IsMessageRegistered = function(self, message, func) self:Check(message, 1, "string") self:Check(func, 2, "string", "function", "nil") if not(events[message] and events[message][self]) then return false end if func == nil then func = "Update" end for i = 1, #events[message][self] do if events[message][self][i] == func then return true end end return false end local UnregisterMessage = function(self, message, func) self:Check(message, 1, "string") self:Check(func, 2, "string", "function", "nil") if not events[message] then return error(L["The message '%' isn't currently registered to any object."]:format(message)) end if not events[message][self] then return error(L["The message '%' isn't currently registered to the object '%s'."]:format(message, tostring(self))) end if func == nil then func = "Update" end for i = #events[message][self], 1, -1 do if events[message][self][i] == func then events[message][self][i] = nil if Frame.event_registry and Frame.event_registry[message] then Frame.event_registry[message] = Frame.event_registry[message] - 1 if Frame.event_registry[message] == 0 then Frame:UnregisterEvent(message) end end return end end if type(func) == "string" then if func == "Update" then return error(L["Attempting to unregister the general occurence of the message '%s' in the object '%s', when no such thing has been registered. Did you forget to add function or method name to UnregisterMessage?"]:format(event, tostring(self))) else return error(L["The method named '%s' isn't registered for the message '%s' in the object '%s'."]:format(func, message, tostring(self))) end else return error(L["The function call assigned to the message '%s' in the object '%s' doesn't exist."]:format(message, tostring(self))) end end ------------------------------------------------------------- -- Timers ------------------------------------------------------------- -- create a new timer object local new_timer = function(owner, method, delay, loop, ...) end local ScheduleTimer = function(self, method, delay, ...) self:Check(method, 1, "string", "function") self:Check(delay, 2, "number") if not timers[self] then timers[self] = {} end local timer = new_timer(owner, method, delay, false, ...) timers[self][timer] = method return timer end local ScheduleRepeatingTimer = function(self, method, callback, ...) self:Check(method, 1, "string", "function") self:Check(delay, 2, "number") if not timers[self] then timers[self] = {} end local timer = new_timer(owner, method, delay, true, ...) timers[self][timer] = method return timer end local CancelTimer = function(self, id) if not timers[self] then return end end local CancelAllTimers = function(self) if not timers[self] then return end end ------------------------------------------------------------- -- Config ------------------------------------------------------------- local copyTable copyTable = function(source, target) local new = target or {} for i,v in pairs(source) do if type(v) == "table" then if new[i] and type(new[i] == "table") then new[i] = copyTable(source[i], new[i]) else new[i] = copyTable(source[i]) -- deep copy end else new[i] = source[i] end end return new end Engine.ParseSavedVariables = function(self) --wipe(DiabolicUI_DB) -- fixing format changes during development. leave commented out. -- Fix broken saved settings for name,data in pairs(DiabolicUI_DB) do for i,v in pairs(DiabolicUI_DB[name]) do if i ~= "profiles" then i = nil end end end -- Merge and/or overwrite current configs with stored settings. -- *doesn't matter that we mess up any links by replacing the tables, -- because this all happens before any module's OnInit or OnEnable, -- meaning if the modules do it right, they haven't fetched their config or db yet. for name,data in pairs(DiabolicUI_DB) do if data.profiles and configs[name] and configs[name].profiles then -- add stored realm dbs to our db if data.profiles.realm then for realm,realmdata in pairs(data.profiles.realm) do configs[name].profiles.realm[realm] = copyTable(data.profiles.realm[realm], configs[name].profiles.realm[realm]) end end -- add stored faction dbs to our db if data.profiles.faction then for faction,factiondata in pairs(data.profiles.faction) do configs[name].profiles.faction[faction] = copyTable(data.profiles.faction[faction], configs[name].profiles.faction[faction]) end end -- add stored character dbs to our db if data.profiles.character then for char,chardata in pairs(data.profiles.character) do configs[name].profiles.character[char] = copyTable(data.profiles.character[char], configs[name].profiles.character[char]) end end -- global config if data.profiles.global then configs[name].profiles.global = copyTable(data.profiles.global, configs[name].profiles.global) end end end -- Point the saved variables to our configs. -- *This isn't redundant, because there can be new configs here -- that hasn't previously been saved either because of me adding a new module, -- or because it's the first time running the addon. for name,data in pairs(configs) do DiabolicUI_DB[name] = { profiles = configs[name].profiles } end end local NewConfig = function(self, name, config) self:Check(name, 1, "string") self:Check(config, 2, "table") if configs[name] then return error(L["The config '%s' already exists!"]:format(name)) end local faction = UnitFactionGroup("player") local realm = GetRealmName() local character = UnitName("player") configs[name] = { defaults = copyTable(config), profiles = { realm = { [realm] = copyTable(config) }, faction = { [faction] = copyTable(config) }, character = { [character.."-"..realm] = copyTable(config) }, -- we need the realm name here to avoid duplicates global = copyTable(config) } } end -- if the 'profile' argument is left out, the 'global' profile will be returned local GetConfig = function(self, name, profile, option) self:Check(name, 1, "string") self:Check(profile, 2, "string", "nil") self:Check(option, 3, "string", "nil") if not configs[name] then return error(L["The config '%s' doesn't exist!"]:format(name)) end local config if profile == "realm" then config = configs[name].profiles.realm[(GetRealmName())] elseif profile == "character" then config = configs[name].profiles.character[UnitName("player").."-"..GetRealmName()] elseif profile == "faction" then config = configs[name].profiles.faction[(UnitFactionGroup("player"))] elseif not profile then config = configs[name].profiles.global end if not config then return error(L["The config '%s' doesn't have a profile named '%s'!"]:format(name, profile)) end return config end local GetConfigDefaults = function(self, name) self:Check(name, 1, "string") if not configs[name] then return error(L["The config '%s' doesn't exist!"]:format(name)) end return configs[name].defaults end local GetStaticConfig = function(self, name) self:Check(name, 1, "string") if not static_configs[name] then return error(L["The static config '%s' doesn't exist!"]:format(name)) end return static_configs[name] end local NewStaticConfig = function(self, name, config) self:Check(name, 1, "string") self:Check(config, 2, "table") if static_configs[name] then return error(L["The static config '%s' already exists!"]:format(name)) end static_configs[name] = copyTable(config) end ------------------------------------------------------------- -- Secure/OutOfCombat Wrapper ------------------------------------------------------------- local safecall = function(func, ...) -- perform the function right away when not in combat if not _incombat then if queue[func] then -- check if the function has been previously queued during combat push(queue[func]) -- push the table to the stack queue[func] = nil -- remove the element from the queue end func(...) return end if not _inlockdown then _inlockdown = InCombatLockdown() -- still in PLAYER_REGEN_DISABLED? if not _inlockdown then if queue[func] then -- check if the function has been previously queued during combat push(queue[func]) -- push the table to the stack queue[func] = nil -- remove the element from the queue end func(...) return end end -- we're still in combat, combat has ended but the event hasn't fired yet. -- we need to queue the function call. -- if it has been previously queued, we simply update the arguments if queue[func] then local tbl, oldArgs = queue[func], #queue[func] local numArgs = select("#", ...) for i = 1, numArgs do tbl[i] = select(i, ...) -- give each argument its own entry end if oldArgs > numArgs then for i = oldArgs + 1, numArgs do tbl[i] = nil -- kill of excess args from the previous queue, if any end end else local tbl = pop() -- request a fresh table from the stack local numArgs = select("#", ...) for i = 1, numArgs do tbl[i] = select(i, ...) -- give each argument its own entry end -- To avoid multiple calls of the same function, -- we use the actual function as the key. -- -- Note: This isn't guaranteed to work, though, since a function -- can easily be copied when passed, and thus we can still get -- multiple calls to the same function. -- So I should rewrite the whole freaking system to use -- some kind of unique IDs. Major TODO. -_- queue[func] = tbl end end local combat_starts = function(self, event, ...) _incombat = true -- combat starts end local combat_ends = function(self, event, ...) _incombat = false _inlockdown = false for func,args in pairs(queue) do if func then local args = args func(unpack(args)) if queue[func] then -- the previous function may have deleted itself push(queue[func]) -- push the table to the stack queue[func] = nil -- remove the element from the queue elseif args then -- the table might still be there, even if the reference is gone push(args) -- push the table to the stack end end end end -- Local wrapper function to turn a function into a safecall -- that will be queued to combat end if called while -- the player or the player's pet or minion is in combat. local wrap = function(self, func) return function(...) return safecall(func, ...) end end ------------------------------------------------------------- ------------------------------------------------------------- -- Prototypes ------------------------------------------------------------- ------------------------------------------------------------- -- default event handler local Update = function(self, event, ...) if not enabled_objects[self] then return end if self[event] then return self[event](self, event, ...) end if self.OnEvent then return self:OnEvent(event, ...) end end local Init = function(self, ...) if not initialized_objects[self] then initialized_objects[self] = true if self.OnInit then return self:OnInit(...) end end end local Enable = function(self, ...) if not enabled_objects[self] then enabled_objects[self] = true if self.OnEnable then return self:OnEnable(...) end end end local Disable = function(self, ...) if enabled_objects[self] then enabled_objects[self] = false if self.OnDisable then return self:OnDisable(...) end end end local IsEnabled = function(self) return enabled_objects[self] end local GetHandler = function(self, name, silent) self:Check(name, 1, "string") self:Check(silent, 2, "boolean", "nil") if handlers[name] then return handlers[name] end if not silent then return error(L["Bad argument #%d to '%s': No handler named '%s' exist!"]:format(1, "Get", name)) end end local GetModule = function(self, name, silent) self:Check(name, 1, "string") self:Check(silent, 2, "boolean", "nil") if modules[name] then return modules[name] end if not silent then return error(L["Bad argument #%d to '%s': No module named '%s' exist!"]:format(1, "Get", name)) end end -- core object that all inherits from local core_prototype = { Check = check, Update = Update, Enable = wrap(Engine, Enable), Disable = wrap(Engine, Disable), IsEnabled = IsEnabled, RegisterEvent = RegisterEvent, RegisterMessage = RegisterMessage, UnregisterEvent = UnregisterEvent, UnregisterMessage = UnregisterMessage, IsEventRegistered = IsEventRegistered, IsMessageRegistered = IsMessageRegistered, GetHandler = GetHandler, GetModule = GetModule, NewConfig = NewConfig, GetConfig = GetConfig, NewStaticConfig = NewStaticConfig, GetStaticConfig = GetStaticConfig, Wrap = wrap } local core_meta = { __index = core_prototype, __tostring = function(t) return object_name[t] end } -- Handlers & Elements ------------------------------------------------------------- -- Handlers are the parts of the engine that function as libraries. -- They are loaded before any modules, and any events or messages -- are sent to the handlers before the modules. -- This is intentional. ------------------------------------------------------------- -- handler element prototypes local element_prototype = setmetatable({}, core_meta) local element_unsecure_prototype = setmetatable({ Enable = Enable, Disable = Disable }, { __index = element_prototype }) local element_meta = { __index = element_prototype, __tostring = function(t) return object_name[t] end } local element_unsecure_meta = { __index = element_unsecure_prototype } -- handler prototype local handler_prototype = setmetatable({ GetElement = function(self, name, ...) self:Check(name, 1, "string") local elementPool = handler_elements[self] return elementPool[name] end, -- Handler elements are by default blocked from usage in combat. -- To avoid this behavior the 'make_unsecure' flag must be set to -- 'true' during element creation! SetElement = function(self, name, template, make_unsecure) self:Check(name, 1, "string") self:Check(template, 2, "table", "nil", "boolean") self:Check(make_unsecure, 3, "boolean", "nil") if make_unsecure == nil and type(template) == "boolean" then make_unsecure = template template = nil end local elementPool = handler_elements[self] if elementPool[name] then return error(L["The element '%s' is already registered to the '%s' handler!"]:format(name, tostring(self))) end local element = setmetatable(template or {}, make_unsecure and element_unsecure_meta or element_meta) object_name[element] = name object_type[element] = "element" if handler_elements_enabled_state[self] then enabled_objects[element] = true end elementPool[name] = element return element end, SetElementDefaultEnabledState = function(self, state) handler_elements_enabled_state[self] = state end, IterateElements = function(self) return pairs(handler_elements[self]) end }, core_meta) local handler_meta = { __index = handler_prototype, __tostring = function(t) return object_name[t] end } -- Modules & Widgets -- *not considered part of the engine ------------------------------------------------------------- -- module widget prototype local widget_prototype = setmetatable({ Init = Init, }, core_meta) local widget_unsecure_prototype = setmetatable({ Enable = Enable, Disable = Disable }, { __index = widget_prototype }) local widget_meta = { __index = widget_prototype, __tostring = function(t) return object_name[t] end } local widget_unsecure_meta = { __index = widget_unsecure_prototype, __tostring = function(t) return object_name[t] end } -- module prototype local module_prototype = setmetatable({ Init = Init, GetWidget = function(self, name, ...) self:Check(name, 1, "string") local widgetPool = module_widgets[self] return widgetPool[name] end, SetWidget = function(self, name, make_unsecure) self:Check(name, 1, "string") self:Check(make_unsecure, 2, "boolean", "nil") local widgetPool = module_widgets[self] if widgetPool[name] then return error(L["The widget '%s' is already registered to the '%s' module!"]:format(name, tostring(self))) end local widget = setmetatable({}, make_unsecure and widget_unsecure_meta or widget_meta) object_name[widget] = name -- store the name object_type[widget] = "widget" -- store the object type widgetPool[name] = widget return widget end }, core_meta) local module_unsecure_prototype = setmetatable({ Enable = Enable, Disable = Disable }, { __index = module_prototype }) local module_meta = { __index = module_prototype, __tostring = function(t) return object_name[t] end } local module_unsecure_meta = { __index = module_unsecure_prototype, __tostring = function(t) return object_name[t] end } ------------------------------------------------------------- ------------------------------------------------------------- -- Engine ------------------------------------------------------------- ------------------------------------------------------------- Engine.GetBuildFor = function(self, buildOrVersion) return game_versions[buildOrVersion] end -- The one function to rule them all. -- This is how I simply my client version compability checks. Engine.IsBuild = function(self, buildOrVersion, exact) local client_build = tonumber(buildOrVersion) if client_build then if exact then return client_build == BUILD else return client_build <= BUILD end elseif type(buildOrVersion) == "string" then if exact then return self:GetBuildFor(buildOrVersion) == BUILD else return self:GetBuildFor(buildOrVersion) <= BUILD end end end -- Matching the pre-MoP return arguments of the Blizzard API call Engine.GetAddOnInfo = function(self, index) local name, title, notes, enabled, loadable, reason, security if self:IsBuild("6.0.2") then name, title, notes, loadable, reason, security, newVersion = GetAddOnInfo(index) enabled = not(GetAddOnEnableState(UnitName("player"), index) == 0) -- not a boolean, messed that one up! o.O else name, title, notes, enabled, loadable, reason, security = GetAddOnInfo(index) end return name, title, notes, enabled, loadable, reason, security end -- Check if an addon is enabled in the addon listing Engine.IsAddOnEnabled = function(self, target) local target = strlower(target) for i = 1,GetNumAddOns() do local name, title, notes, enabled, loadable, reason, security = self:GetAddOnInfo(i) if strlower(name) == target then if enabled then return true end end end end -- Check if an addon exists in the addon listing and loadable on demand Engine.IsAddOnLoadable = function(self, target) local target = strlower(target) for i = 1,GetNumAddOns() do local name, title, notes, enabled, loadable, reason, security = self:GetAddOnInfo(i) if strlower(name) == target then if loadable then return true end end end end -- define a new handler/library Engine.NewHandler = function(self, name) self:Check(name, 1, "string") if handlers[name] then return error(L["A handler named '%s' is already registered!"]:format(name)) end local handler = setmetatable({}, handler_meta) handler_elements[handler] = {} -- local elementpool for the handler object_name[handler] = name -- store the handler name for easier reference object_type[handler] = "handler" -- store the object type handlers[name] = handler return handler end -- create a new user module -- *set load_priority to "LOW" to delay OnEnable until after PLAYER_LOGIN! Engine.NewModule = function(self, name, load_priority, make_unsecure) self:Check(name, 1, "string") self:Check(load_priority, 2, "string", "nil") self:Check(make_unsecure, 3, "boolean", "nil") if handlers[name] then return error(L["Bad argument #%d to '%s': The name '%s' is reserved for a handler!"]:format(1, "New", name)) end if modules[name] then return error(L["Bad argument #%d to '%s': A module named '%s' already exists!"]:format(1, "New", name)) end if load_priority and not priority_hash[load_priority] then return error(L["Bad argument #%d to '%s': The load priority '%s' is invalid! Valid priorities are: %s"]:format(5, "New", load_priority, tconcat(priority_index, ", "))) end if not load_priority then load_priority = default_module_priority end local module = setmetatable({}, make_unsecure and module_unsecure_meta or module_meta) module_widgets[module] = {} -- local widgetpool for the module object_name[module] = name -- store the module name for easier reference object_type[module] = "module" -- store the object type module_load_priority[load_priority][name] = module -- store the module load priority modules[name] = module -- insert the new module into the registry return module end -- perform a function or method on all registered modules Engine.ForAll = function(self, func, priority_filter, ...) self:Check(func, 1, "string", "function") self:Check(func, 2, "string", "nil") -- if a valid priority filter is set, only modules of that given priority will be called if priority_filter then if not priority_hash[priority_filter] then return error(L["Bad argument #%d to '%s': The load priority '%s' is invalid! Valid priorities are: %s"]:format(2, "ForAll", priority_filter, tconcat(priority_index, ", "))) end for name,module in pairs(module_load_priority[priority_filter]) do if type(func) == "string" then if module[func] then --protected_call(module[func], module, ...) module[func](module, ...) end else --protected_call(func, module, ...) func(module, ...) end end return end -- if no priority filter is set, we iterate through all modules, but still by priority for index,priority in ipairs(priority_index) do for name,module in pairs(module_load_priority[priority]) do if type(func) == "string" then if module[func] then --protected_call(module[func], module, ...) module[func](module, ...) end else --protected_call(func, module, ...) func(module, ...) end end end end do local loaded, variables Engine.PreInit = function(self, event, ...) if event == "ADDON_LOADED" then local arg1 = ... if arg1 == ADDON then loaded = true self:UnregisterEvent("ADDON_LOADED", "PreInit") end elseif event == "VARIABLES_LOADED" then variables = true self:UnregisterEvent("VARIABLES_LOADED", "PreInit") end if variables and loaded then if not IsLoggedIn() then self:RegisterEvent("PLAYER_LOGIN", "Enable") end return self:Init(event, ADDON) end end end Engine.GetFrame = function(self) return UICenter end Engine.ReloadUI = function(self) local PopUpMessage = self:GetHandler("PopUpMessage") if not PopUpMessage:GetPopUp("ENGINE_GENERAL_RELOADUI") then PopUpMessage:RegisterPopUp("ENGINE_GENERAL_RELOADUI", { title = L["Reload Needed"], text = L["The user interface has to be reloaded for the changes to be applied.|n|nDo you wish to do this now?"], button1 = L["Accept"], button2 = L["Cancel"], OnAccept = function() ReloadUI() end, OnCancel = function() end, timeout = 0, exclusive = 1, whileDead = 1, hideOnEscape = false }) end PopUpMessage:ShowPopUp("ENGINE_GENERAL_RELOADUI", self:GetStaticConfig("UI").popup) end Engine.UpdateScale = function(self) local accuracy = 1e4 local compare_accuracy = 1e4 -- anything more than 2 decimals will spam reloads on every video options frame opening local pixelperfect_minimum_width = 1600 --1920 -- for anything less than this, UI (down)scaling will always be used local widescreen = 1.6 -- minimum aspect ratio for a screen to be considered widescreen local resolution if Engine:IsBuild("Legion") then local monitorIndex = (tonumber(GetCVar("gxMonitor")) or 0) + 1 resolution = select(GetCurrentResolution(monitorIndex), GetScreenResolutions(monitorIndex)) else resolution = ({GetScreenResolutions()})[GetCurrentResolution()] end local screen_width = tonumber(strmatch(resolution, "(%d+)x%d+")) local screen_height = tonumber(strmatch(resolution, "%d+x(%d+)")) local using_scale = tonumber(GetCVar("useUiScale")) local aspect_ratio = round(screen_width / screen_height, accuracy) -- Somebody using AMD EyeFinity? -- *we're blatently assuming we're talking about 3x widescreen monitors, -- and we will simply ignore all other setups. local virtual_width if aspect_ratio >= 3*widescreen then if screen_width >= 9840 then virtual_width = 3280 end -- WQSXGA if screen_width >= 7680 and screen_width < 9840 then virtual_width = 2560 end -- WQXGA if screen_width >= 5760 and screen_width < 7680 then virtual_width = 1920 end -- WUXGA & HDTV if screen_width >= 5040 and screen_width < 5760 then virtual_width = 1680 end -- WSXGA+ if screen_width >= 4800 and screen_width < 5760 and screen_height == 900 then virtual_width = 1600 end -- UXGA & HD+ if screen_width >= 4320 and screen_width < 4800 then virtual_width = 1440 end -- WSXGA if screen_width >= 4080 and screen_width < 4320 then virtual_width = 1360 end -- WXGA if screen_width >= 3840 and screen_width < 4080 then virtual_width = 1280 end -- SXGA & SXGA (UVGA) & WXGA & HDTV end -- resize our UIParent clone -- *if the player has a triple monitor EyeFinity setup, -- our frame will thus be locked to the center monitor. if virtual_width then -- UICenter is parent to a lot of secure frames, and thus it will become secure itself. -- So we need to wrap these calls in our out-of-combat handler, to avoid taint! self:Wrap(function() UICenter:SetSize(virtual_width, screen_height) end)() screen_width = virtual_width else self:Wrap(function() UICenter:SetSize(UIParent:GetSize()) end)() end -- If the user previously has been queried, -- and chosen to handle the UI scale themself, -- then we simply and silenty exit this. local db = self:GetConfig("UI") if db.hasbeenqueried and not db.autoscale then return end local highres_wide_scale = round(768/screen_height, accuracy) local lowres_wide_scale = round(768/1080, accuracy) local lowres_box_scale = round(768/1200, accuracy) local PopUpMessage = self:GetHandler("PopUpMessage") if not PopUpMessage:GetPopUp("ENGINE_UISCALE_RELOAD_NEEDED") then PopUpMessage:RegisterPopUp("ENGINE_UISCALE_RELOAD_NEEDED", { title = L["Attention!"], text = L["The UI scale is wrong, so the graphics might appear fuzzy or pixelated. If you choose to ignore it, you won't be asked about this issue again.|n|nFix this issue now?"], button1 = L["Accept"], button2 = L["Ignore"], OnAccept = function() -- In WoD all cvars became protected in combat, -- so to be safe and not sorry we're using our -- out of combat wrapper here. Engine:Wrap(function() if Engine:IsBuild("Cata") then if screen_width >= pixelperfect_minimum_width then -- In Cataclysm the scaling system changed, -- and it's sufficient to simply turn off uiscaling for pixel perfection here. if using_scale == 1 then SetCVar("useUiScale", "0") end else -- Even in Cataclysm we still need scaling for tiny resolutions, though. if using_scale ~= 1 then SetCVar("useUiScale", "1") end local current_scale = round(tonumber(GetCVar("uiScale")), accuracy) local correct_scale if screen_width >= pixelperfect_minimum_width then correct_scale = highres_wide_scale else if aspect_ratio >= widescreen then correct_scale = lowres_wide_scale else correct_scale = lowres_box_scale end end if not compare(current_scale, correct_scale, compare_accuracy) then SetCVar("uiScale", correct_scale) end end else -- Prior to Cataclysm we needed uiscaling at all times for pixel perfection if using_scale ~= 1 then SetCVar("useUiScale", "1") end -- The required uiscale for pixel perfection was dependant upon resolution, -- and had to be calculated after the events PLAYER_ALIVE and VARIABLES_LOADED had fired! local current_scale = round(tonumber(GetCVar("uiScale")), accuracy) local correct_scale if screen_width >= pixelperfect_minimum_width then correct_scale = highres_wide_scale else if aspect_ratio >= widescreen then correct_scale = lowres_wide_scale else correct_scale = lowres_box_scale end end if not compare(current_scale, correct_scale, compare_accuracy) then SetCVar("uiScale", correct_scale) end end local db = Engine:GetConfig("UI") db.autoscale = true db.hasbeenqueried = true -- From a graphic point of view it would have been sufficient -- to simply reload the graphics engine with RestartGx(), -- but since changing the uiScale cvar can taint the worldmap -- it's safer with a complete reload here. ReloadUI() end)() end, OnCancel = function() print(L["You can re-enable the auto scaling by typing |cff448800/diabolic autoscale|r in the chat at any time."]) local db = Engine:GetConfig("UI") if db.hasbeenqueried then db.autoscale = false Engine:ReloadUI() else db.autoscale = false db.hasbeenqueried = true end end, timeout = 0, exclusive = 1, whileDead = 1, hideOnEscape = false }) end -------------------------------------------------------------------------------------------------- -- Set up the game client for pixel perfection -------------------------------------------------------------------------------------------------- local fix local popup = PopUpMessage:GetPopUp("ENGINE_UISCALE_RELOAD_NEEDED") if self:IsBuild("Cata") then if screen_width >= pixelperfect_minimum_width then -- In Cataclysm the scaling system changed, -- and it's sufficient to simply turn off uiscaling for pixel perfection here. if using_scale == 1 then popup.text = L["UI scaling is activated and needs to be disabled, otherwise you'll might get fuzzy borders or pixelated graphics. If you choose to ignore it and handle the UI scaling yourself, you won't be asked about this issue again.|n|nFix this issue now?"] fix = true end else -- Even in Cataclysm we still need scaling for tiny resolutions, though. if using_scale ~= 1 then popup.text = L["UI scaling was turned off but needs to be enabled, otherwise you'll might get fuzzy borders or pixelated graphics. If you choose to ignore it and handle the UI scaling yourself, you won't be asked about this issue again.|n|nFix this issue now?"] fix = true end local current_scale = round(tonumber(GetCVar("uiScale")), accuracy) local correct_scale if screen_width >= pixelperfect_minimum_width then correct_scale = highres_wide_scale else if aspect_ratio >= widescreen then correct_scale = lowres_wide_scale else correct_scale = lowres_box_scale end end if not compare(current_scale, correct_scale, compare_accuracy) then if screen_width >= pixelperfect_minimum_width then popup.text = L["The UI scale is wrong, so the graphics might appear fuzzy or pixelated. If you choose to ignore it and handle the UI scaling yourself, you won't be asked about this issue again.|n|nFix this issue now?"] else popup.text = L["Your resolution is too low for this UI, but the UI scale can still be adjusted to make it fit. If you choose to ignore it and handle the UI scaling yourself, you won't be asked about this issue again.|n|nFix this issue now?"] end fix = true end end else -- Prior to Cataclysm we needed uiscaling at all times for pixel perfection if using_scale ~= 1 then popup.text = L["UI scaling was turned off but needs to be enabled, otherwise you'll might get fuzzy borders or pixelated graphics. If you choose to ignore it and handle the UI scaling yourself, you won't be asked about this issue again.|n|nFix this issue now?"] fix = true end local current_scale = round(tonumber(GetCVar("uiScale")), accuracy) local correct_scale if screen_width >= pixelperfect_minimum_width then correct_scale = highres_wide_scale else if aspect_ratio >= 1.6 then correct_scale = lowres_wide_scale else correct_scale = lowres_box_scale end end if not compare(current_scale, correct_scale, compare_accuracy) then if screen_width >= pixelperfect_minimum_width then popup.text = L["The UI scale is wrong, so the graphics might appear fuzzy or pixelated. If you choose to ignore it and handle the UI scaling yourself, you won't be asked about this issue again.|n|nFix this issue now?"] else popup.text = L["Your resolution is too low for this UI, but the UI scale can still be adjusted to make it fit. If you choose to ignore it and handle the UI scaling yourself, you won't be asked about this issue again.|n|nFix this issue now?"] end fix = true end end if fix then -- Note: -- The Engine calls a specific stylesheet here, and semantically it shouldn't. -- Not really any good way of avoiding it, though. -- So we'll just have to settle for being able -- to shield the Handlers from the stylesheets instead. PopUpMessage:ShowPopUp("ENGINE_UISCALE_RELOAD_NEEDED", self:GetStaticConfig("UI").popup) end if db.autoscale and db.hasbeenqueried then self:KillBlizzard() end end do local only_once Engine.KillBlizzard = wrap(Engine, function(self) if only_once then return end -- Killing the UI scale checkbox and slider will prevent blizzards' UI -- from slightly modifying the stored scale everytime we enter the video options. -- If we don't do this, the user will either get spammed with reload requests, -- or the scale will eventually become slightly wrong, and the graphics slightly fuzzy. if self:IsBuild("Cata") then self:GetHandler("BlizzardUI"):GetElement("Menu_Option"):Remove(true, "Advanced_UIScaleSlider") self:GetHandler("BlizzardUI"):GetElement("Menu_Option"):Remove(true, "Advanced_UseUIScale") elseif self:IsBuild("WotLK") then self:GetHandler("BlizzardUI"):GetElement("Menu_Option"):Remove(true, "VideoOptionsResolutionPanelUseUIScale") self:GetHandler("BlizzardUI"):GetElement("Menu_Option"):Remove(true, "VideoOptionsResolutionPanelUIScaleSlider") end only_once = true end) end -- called when the addon is fully loaded Engine.Init = function(self, event, ...) local arg1 = ... if arg1 ~= ADDON then return end -- update stored settings (needs to happen before init) self:ParseSavedVariables() -- Might as well do this if self:IsBuild("MoP") then RegisterStateDriver(UICenter, "visibility", "[petbattle]hide;show") end -- initialize all handlers here for name, handler in pairs(handlers) do handler:Enable() end -- register UI scaling events self:RegisterEvent("UI_SCALE_CHANGED", "UpdateScale") self:RegisterEvent("DISPLAY_SIZE_CHANGED", "UpdateScale") if VideoOptionsFrameApply then VideoOptionsFrameApply:HookScript("OnClick", function() Engine:UpdateScale() end) end if VideoOptionsFrameOkay then VideoOptionsFrameOkay:HookScript("OnClick", function() Engine:UpdateScale() end) end -- initial UI scale update self:UpdateScale() -- add the chat command to toggle auto scaling of the UI local ChatCommand = self:GetHandler("ChatCommand") ChatCommand:Register("autoscale", function() local db = self:GetConfig("UI") db.autoscale = not db.autoscale db.hasbeenqueried = true if db.autoscale then print(L["Auto scaling of the UI has been enabled."]) else print(L["Auto scaling of the UI has been disabled."]) Engine:ReloadUI() -- to get back the UI scale slider end self:UpdateScale() end) -- Add a command to reset setups to their default state. -- TODO: Make it possible for the modules to add -- these functions in themselves. ChatCommand:Register("resetsetup", function() -- UI scale local db = self:GetConfig("UI") db.hasbeenqueried = false db.autoscale = true self:UpdateScale() -- chat window autoposition db = self:GetConfig("ChatWindows") db.hasbeenqueried = false db.autoposition = true self:GetModule("ChatWindows"):PositionChatFrames() end) -- initialize all modules for i = 1, #priority_index do self:ForAll("Init", priority_index[i], event, ...) end -- enable all objects of NORMAL and HIGH priority for i = 1, 2 do self:ForAll("Enable", priority_index[i], event, ...) end initialized_objects[self] = true -- this could happen on WotLK clients if IsLoggedIn() and not self:IsEnabled() then self:Enable() end end Engine.IsInitialized = function(self) return initialized_objects[self] end -- called after the player has logged in Engine.Enable = function(self, event, ...) if not self:IsInitialized() then -- Since the :Init() procedure will call this function, -- we need to return to avoid duplicate calls return self:Init("Forced", ADDON) end -- enable all objects of LOW priority for i = 3, #priority_index do self:ForAll("Enable", priority_index[i], event, ...) end enabled_objects[self] = true end Engine.IsEnabled = function(self) return enabled_objects[self] end local offworld_status Engine.UpdateOffWorld = function(self, event, ...) if event == "PLAYER_LEAVING_WORLD" then offworld_status = true elseif event == "PLAYER_ENTERING_WORLD" then offworld_status = false end end Engine.IsOffWorld = function(self) return offworld_status end -- add general API calls to the Engine -- *TODO: make a better system for inheritance here Engine.Check = check Engine.Wrap = wrap Engine.Fire = Fire Engine.RegisterEvent = RegisterEvent Engine.RegisterMessage = RegisterMessage Engine.IsEventRegistered = IsEventRegistered Engine.IsMessageRegistered = IsMessageRegistered Engine.UnregisterEvent = UnregisterEvent Engine.UnregisterMessage = UnregisterMessage Engine.GetHandler = GetHandler Engine.GetModule = GetModule Engine.NewConfig = NewConfig Engine.GetConfig = GetConfig Engine.NewStaticConfig = NewStaticConfig Engine.GetStaticConfig = GetStaticConfig -- finalize the Engine and write protect it local protected_meta = { __newindex = function(self) return error(L["The Engine can't be tampered with!"]) end, __metatable = false } (function(tbl) local old_meta = getmetatable(tbl) if old_meta then local new_meta = {} for i,v in pairs(old_meta) do new_meta[i] = v end for i,v in pairs(protected_meta) do new_meta[i] = v end return setmetatable(tbl, new_meta) else return setmetatable(tbl, protected_meta) end end)(Engine) -- register combat tracking events for our safecall wrapper Engine:RegisterEvent("PLAYER_REGEN_DISABLED", combat_starts) Engine:RegisterEvent("PLAYER_REGEN_ENABLED", combat_ends) -- register basic startup events with our event handler if Engine:IsBuild("Cata") then Engine:RegisterEvent("ADDON_LOADED", "Init") Engine:RegisterEvent("PLAYER_LOGIN", "Enable") else Engine:RegisterEvent("ADDON_LOADED", "PreInit") Engine:RegisterEvent("VARIABLES_LOADED", "PreInit") end Engine:RegisterEvent("PLAYER_ENTERING_WORLD", "UpdateOffWorld") Engine:RegisterEvent("PLAYER_LEAVING_WORLD", "UpdateOffWorld") -- apply scripts to our event/update frame Frame:SetScript("OnEvent", OnEvent) Frame:SetScript("OnUpdate", OnUpdate) -- fix some weird MoP bug I can't really explain if Engine:IsBuild("MoP") and not Engine:IsBuild("WoD") then if not C_AuthChallenge then DisableAddOn("Blizzard_AuthChallengeUI") end end
local Config = require "ardoises.config" local Cookie = require "resty.cookie" local Gettime = require "socket".gettime local Http = require "ardoises.jsonhttp.resty-redis" local Hmac = require "openssl.hmac" local Json = require "rapidjson" local Jwt = require "resty.jwt" local Keys = require "ardoises.server.keys" local Lustache = require "lustache" local Patterns = require "ardoises.patterns" local Redis = require "resty.redis" local Url = require "net.url" local function localrepo (var) return { owner = { login = var.owner }, name = var.name, full_name = var.owner .. "/" .. var.name, default_branch = var.branch, permissions = { admin = true, push = true, pull = true, }, } end -- http://25thandclement.com/~william/projects/luaossl.pdf local function tohex (b) local x = "" for i = 1, #b do x = x .. string.format ("%.2x", string.byte (b, i)) end return x end local function wrap (f) return function () local redis = Redis:new () if not redis:connect (Config.redis.url.host, Config.redis.url.port) then return ngx.exit (ngx.HTTP_INTERNAL_SERVER_ERROR) end local ok, result = xpcall (function () return f { redis = redis, } end, function (err) print (tostring (err)) print (debug.traceback ()) end) redis:close () if not ok then return ngx.exit (ngx.HTTP_INTERNAL_SERVER_ERROR) elseif not result then return elseif result.redirect then return ngx.redirect (result.redirect) else return ngx.exit (result.status) end end end local Server = {} function Server.template (what, data) data = data or {} local file = assert (io.open ("/static/" .. what .. ".template", "r")) local template = assert (file:read "*a") assert (file:close ()) data.configuration = Json.encode (data) return Lustache:render (template, data) end local function register () local query = ngx.req.get_uri_args () if query.code and query.state then _G.ngx.header ["Content-type"] = "text/html" ngx.say (Server.template ("index", { server = Url.build (Config.ardoises.url), code = "ardoises.www.register", query = Json.encode (query), })) ngx.exit (ngx.HTTP_OK) end return true end Server.register = wrap (function (context) local query = ngx.req.get_uri_args () if not query.code and not query.state then return { status = ngx.HTTP_BAD_REQUEST } end local token = Jwt:verify (Config.github.secret, query.state) if not token or not token.payload or not token.payload.csrf then return { status = ngx.HTTP_UNAUTHORIZED } end local lock = Keys.lock "register" while true do if context.redis:setnx (lock, "locked") == 1 then context.redis:expire (lock, Config.locks.timeout) break end ngx.sleep (0.1) end local user, result, status result, status = Http { cache = true, url = "https://github.com/login/oauth/access_token", method = "POST", headers = { ["Accept" ] = "application/json", ["User-Agent"] = "Ardoises", }, body = { client_id = Config.github.id, client_secret = Config.github.secret, state = query.state, code = query.code, }, } context.redis:del (Keys.lock "register") if status ~= ngx.HTTP_OK or not result.access_token then return { status = ngx.HTTP_INTERNAL_SERVER_ERROR } end user, status = Http { url = "https://api.github.com/user", method = "GET", headers = { ["Accept" ] = "application/vnd.github.v3+json", ["Authorization"] = "token " .. result.access_token, ["User-Agent" ] = "Ardoises", }, } if status ~= ngx.HTTP_OK then return { status = ngx.HTTP_INTERNAL_SERVER_ERROR } end local key = Keys.user (user) user.tokens = { github = result.access_token, ardoises = Jwt:sign (Config.github.secret, { header = { typ = "JWT", alg = "HS256", }, payload = { login = user.login, }, }), } context.redis:set (key, Json.encode (user)) -- FIXME -- local cookie = Cookie:new () -- cookie:set { -- key = "Ardoises-Token", -- expires = nil, -- httponly = true, -- secure = true, -- samesite = "Strict", -- value = user.tokens.ardoises, -- } ngx.say (Json.encode { user = user, cookie = { key = "Ardoises-Token", expires = nil, httponly = true, secure = true, samesite = "Strict", value = user.tokens.ardoises, }, }) return { status = ngx.HTTP_OK } end) function Server.authenticate (context, options) local ok, err = register (context) if not ok then return nil, err end local user user, err = (function () local headers = ngx.req.get_headers () local cookie = Cookie:new () local field = cookie:get "Ardoises-Token" local header = field and "token " .. field or headers ["Authorization"] if not header then return nil, ngx.HTTP_UNAUTHORIZED end local token = Patterns.authorization:match (header) if not token then return nil, ngx.HTTP_UNAUTHORIZED end local jwt = Jwt:verify (Config.github.secret, token) if not jwt then return nil, ngx.HTTP_UNAUTHORIZED end local info = context.redis:get (Keys.user (jwt.payload)) if info == ngx.null or not info then return nil, ngx.HTTP_INTERNAL_SERVER_ERROR end info = Json.decode (info) if not info then return nil, ngx.HTTP_INTERNAL_SERVER_ERROR end return info end) () if not user and not (options or {}).optional then local url = Url.parse (Url.build (Config.ardoises.url)) url.path = "/login" url.query.redirect_uri = ngx.var.request_uri context.redis:close () return ngx.redirect (Url.build (url)) end return user, err end Server.root = wrap (function (context) local user = Server.authenticate (context, { optional = true, }) if user then return { redirect = "/dashboard" } else return { redirect = "/overview" } end end) Server.dashboard = wrap (function (context) local user, err = Server.authenticate (context) if not user then return { status = err } end _G.ngx.header ["Content-type"] = "text/html" ngx.say (Server.template ("index", { server = Url.build (Config.ardoises.url), user = user, code = "ardoises.www.dashboard", })) return { status = ngx.HTTP_OK } end) Server.overview = wrap (function (context) local user = Server.authenticate (context, { optional = true, }) _G.ngx.header ["Content-type"] = "text/html" ngx.say (Server.template ("index", { server = Url.build (Config.ardoises.url), user = user, code = "ardoises.www.overview", })) return { status = ngx.HTTP_OK } end) Server.view = wrap (function (context) local user, err = Server.authenticate (context) if not user then return { status = err } end local repository if ngx.var.owner == "-" then repository = localrepo (ngx.var) else -- get repository: local rkey = Keys.repository { owner = { login = ngx.var.owner }, name = ngx.var.name, } repository = context.redis:get (rkey) if repository == ngx.null or not repository then return { status = ngx.HTTP_NOT_FOUND } end repository = assert (Json.decode (repository)) -- check collaborator: local ckey = Keys.collaborator ({ owner = { login = ngx.var.owner }, name = ngx.var.name, }, user) local collaboration = context.redis:get (ckey) if collaboration == ngx.null or not collaboration then if repository.private then return { status = ngx.HTTP_FORBIDDEN } end else collaboration = assert (Json.decode (collaboration)) repository = collaboration.repository end end -- answer: _G.ngx.header ["Content-type"] = "text/html" ngx.say (Server.template ("index", { server = Url.build (Config.ardoises.url), user = user, repository = repository, branch = ngx.var.branch, code = "ardoises.www.editor", })) return { status = ngx.HTTP_OK } end) Server.login = wrap (function () local query = ngx.req.get_uri_args () local url = Url.parse "https://github.com/login/oauth/authorize" local redirect = Url.parse (Url.build (Config.ardoises.url)) redirect.path = query.redirect_uri or "/" url.query.redirect_uri = Url.build (redirect) url.query.client_id = Config.github.id url.query.scope = "user:email admin:repo_hook" url.query.state = Jwt:sign (Config.github.secret, { header = { typ = "JWT", alg = "HS256", }, payload = { csrf = true, }, }) return { redirect = Url.build (url) } end) Server.logout = wrap (function () local cookie = Cookie:new () cookie:set { key = "Ardoises-Token", value = "deleted", expires = "Thu, 01 Jan 1970 00:00:00 GMT", httponly = true, secure = true, samesite = "Strict", } return { redirect = "/" } end) Server.my_user = wrap (function (context) local user, err = Server.authenticate (context) if not user then return { status = err } end ngx.say (Json.encode { login = user.login, name = user.name, company = user.company, location = user.location, bio = user.bio, avatar_url = user.avatar_url, tokens = user.tokens, }) return { status = ngx.HTTP_OK } end) Server.my_ardoises = wrap (function (context) local user, err = Server.authenticate (context) if not user then return { status = err } end local seen = {} local result = {} -- find collaborators in database: local cursor = 0 repeat local res = context.redis:scan (cursor, "match", Keys.collaborator ({ owner = { login = "*" }, name = "*", }, user), "count", 100) if res == ngx.null or not res then break end cursor = res [1] local keys = res [2] for _, key in ipairs (keys) do local entry = context.redis:get (key) if entry ~= ngx.null and entry then entry = Json.decode (entry) local repository = context.redis:get (Keys.repository (entry.repository)) entry.repository = Json.decode (repository) result [#result+1] = entry seen [entry.repository.full_name] = true end end until cursor == "0" -- find public repositories: cursor = 0 repeat local res = context.redis:scan (cursor, "match", Keys.repository { owner = { login = "*" }, name = "*", }, "count", 100) if res == ngx.null or not res then break end cursor = res [1] local keys = res [2] for _, key in ipairs (keys) do local repository = context.redis:get (key) if repository ~= ngx.null and repository then repository = Json.decode (repository) if not seen [repository.full_name] and not repository.private then local collaborator = Json.decode (Json.encode (user)) collaborator.permissions = { pull = true, push = false, admin = false, } result [#result+1] = { repository = repository, collaborator = collaborator, } seen [repository.full_name] = true end end end until cursor == "0" ngx.say (Json.encode (result)) return { status = ngx.HTTP_OK } end) Server.my_tools = wrap (function (context) local user, err = Server.authenticate (context) if not user then return { status = err } end local result = {} -- find tools in database: local cursor = 0 repeat local res = context.redis:scan (cursor, "match", Keys.tool (user, { id = "*" }), "count", 100) if res == ngx.null or not res then break end cursor = res [1] local keys = res [2] for _, key in ipairs (keys) do local entry = context.redis:get (key) if entry ~= ngx.null and entry then result [#result+1] = Json.decode (entry) end end until cursor == "0" ngx.say (Json.encode (result)) return { status = ngx.HTTP_OK } end) Server.editor = wrap (function (context) local user, err = Server.authenticate (context) if not user then return { status = err } end if ngx.var.owner == "-" then local token = Jwt:sign (Config.github.secret, { header = { typ = "JWT", alg = "HS256", }, payload = { login = user.login, ardoise = Lustache:render ("{{{owner}}}/{{{name}}}:{{{branch}}}", ngx.var), }, }) local repo = localrepo (ngx.var) ngx.say (Json.encode { token = token, repository = repo, branch = ngx.var.branch, editor_url = Lustache:render ("wss://{{{domain}}}.localtunnel.me", { domain = ngx.var.branch, }), }) return { status = ngx.HTTP_OK } end -- get repository: local rkey = Keys.repository { owner = { login = ngx.var.owner }, name = ngx.var.name, } local repository = context.redis:get (rkey) if repository == ngx.null or not repository then return { status = ngx.HTTP_NOT_FOUND } end repository = assert (Json.decode (repository)) -- check collaborator: local ckey = Keys.collaborator ({ owner = { login = ngx.var.owner }, name = ngx.var.name, }, user) local collaboration = context.redis:get (ckey) if collaboration == ngx.null or not collaboration then collaboration = nil if repository.private then return { status = ngx.HTTP_FORBIDDEN } end else collaboration = assert (Json.decode (collaboration)) repository = collaboration.repository end -- get editor: local lock = Keys.lock (Lustache:render ("editor:{{{owner}}}/{{{name}}}/{{{branch}}}", ngx.var)) while true do if context.redis:setnx (lock, "locked") == 1 then context.redis:expire (lock, Config.locks.timeout) break end ngx.sleep (0.1) end local key = Keys.editor ({ owner = { login = ngx.var.owner }, name = ngx.var.name, }, ngx.var.branch) local editor = context.redis:get (key) if editor == ngx.null or not editor then local info, status = Http { url = Lustache:render ("http://{{{host}}}:{{{port}}}/containers/{{{id}}}/json", { host = Config.docker.url.host, port = Config.docker.url.port, id = Config.docker.container, }), method = "GET", } assert (status == ngx.HTTP_OK, status) local _, network = next (info.NetworkSettings.Networks) local ninfo, nstatus = Http { url = Lustache:render ("http://{{{host}}}:{{{port}}}/networks/{{{id}}}", { host = Config.docker.url.host, port = Config.docker.url.port, id = network.NetworkID, }), method = "GET", } assert (nstatus == ngx.HTTP_OK, nstatus) local container for id, v in pairs (ninfo.Containers) do if v.Name:match "clean" then container = id break end end local cinfo, cstatus = Http { url = Lustache:render ("http://{{{host}}}:{{{port}}}/containers/{{{id}}}/json", { host = Config.docker.url.host, port = Config.docker.url.port, id = container, }), method = "GET", } assert (cstatus == ngx.HTTP_OK, cstatus) local service service, status = Http { url = Lustache:render ("http://{{{host}}}:{{{port}}}/containers/create", { host = Config.docker.url.host, port = Config.docker.url.port, }), method = "POST", timeout = 120, body = { Entrypoint = "lua", Cmd = { "-l", "ardoises.editor.bin", }, Image = cinfo.Image, ExposedPorts = { ["8080/tcp"] = {}, }, Volumes = cinfo.Config.Volumes, HostConfig = { PublishAllPorts = false, NetworkMode = info.HostConfig.NetworkMode, Binds = cinfo.HostConfig.Binds, }, Env = { "ARDOISES_URL=" .. Url.build (Config.ardoises.url), "ARDOISES_BRANCH=" .. Lustache:render ("{{{owner}}}/{{{name}}}:{{{branch}}}", ngx.var), "ARDOISES_TOKEN=" .. Config.github.token, }, }, } assert (status == ngx.HTTP_CREATED, status) local created_at = Gettime () local _ _, status = Http { method = "POST", timeout = 120, url = Lustache:render ("http://{{{host}}}:{{{port}}}/containers/{{{id}}}/start", { host = Config.docker.url.host, port = Config.docker.url.port, id = service.Id, }), } assert (status == ngx.HTTP_NO_CONTENT, status) local start = Gettime () local docker_url = Lustache:render ("http://{{{host}}}:{{{port}}}/containers/{{{id}}}", { host = Config.docker.url.host, port = Config.docker.url.port, id = service.Id, }) context.redis:set (key, Json.encode { repository = repository, docker_id = service.Id, created_at = created_at, }) while Gettime () - start <= 120 do info, status = Http { method = "GET", url = docker_url .. "/json", } assert (status == ngx.HTTP_OK, status) if info.State.Running then _, network = next (info.NetworkSettings.Networks) context.redis:set (key, Json.encode { repository = repository, docker_id = service.Id, created_at = created_at, started_at = Gettime (), target_url = Lustache:render ("http://{{{host}}}:8080", { host = network.IPAddress, }), editor_url = Url.build { scheme = "wss", host = Config.ardoises.url.host, port = Config.ardoises.url.port, path = Lustache:render ("/websockets/{{{owner}}}/{{{name}}}/{{{branch}}}", { owner = ngx.var.owner, name = ngx.var.name, branch = ngx.var.branch, }), }, }) break elseif info.State.Dead then assert (false) else _G.ngx.sleep (1) end end end context.redis:del (lock) editor = context.redis:get (key) if editor == ngx.null or not editor then return { status = ngx.HTTP_NOT_FOUND } end editor = assert (Json.decode (editor)) if not editor.target_url or not editor.editor_url then return { status = ngx.HTTP_NOT_FOUND } end local token = Jwt:sign (Config.github.secret, { header = { typ = "JWT", alg = "HS256", }, payload = { login = user.login, ardoise = Lustache:render ("{{{owner}}}/{{{name}}}:{{{branch}}}", ngx.var), }, }) repository.permissions = collaboration and collaboration.collaborator.permissions or repository.permissions ngx.say (Json.encode { token = token, repository = repository, branch = ngx.var.branch, editor_url = editor.editor_url, }) return { status = ngx.HTTP_OK } end) Server.check_token = wrap (function (context) local headers = ngx.req.get_headers () local header = headers ["Authorization"] if not header then return { status = ngx.HTTP_UNAUTHORIZED } end local token = Patterns.authorization:match (header) if not token then return { status = ngx.HTTP_UNAUTHORIZED } end token = Jwt:verify (Config.github.secret, token) if not token or not token.payload then return { status = ngx.HTTP_UNAUTHORIZED } end local branch = Patterns.branch:match (token.payload.ardoise) if branch.owner == "-" then ngx.say (Json.encode { user = { login = "-" }, repository = localrepo { owner = branch.owner, name = branch.repository, branch = branch.branch, }, }) return { status = ngx.HTTP_OK } end local user = context.redis:get (Keys.user (token.payload)) if user == ngx.null or not user then return { status = ngx.HTTP_UNAUTHORIZED } end user = assert (Json.decode (user)) do local emails, status = Http { url = "https://api.github.com/user/emails", method = "GET", headers = { ["Accept" ] = "application/vnd.github.v3+json", ["Authorization"] = "token " .. tostring (user.tokens.github), ["User-Agent" ] = "Ardoises", }, } if status ~= 200 then return { status = ngx.HTTP_UNAUTHORIZED } end for _, t in ipairs (emails) do if t.primary then user.email = t.email end end end assert (user.email) do local repository, status = Http { url = Lustache:render ("https://api.github.com/repos/{{{owner}}}/{{{name}}}", { owner = branch.owner, name = branch.repository, }), method = "GET", headers = { ["Accept" ] = "application/vnd.github.v3+json", ["Authorization"] = "token " .. tostring (user.tokens.github), ["User-Agent" ] = "Ardoises", }, } if status ~= 200 then return { status = ngx.HTTP_UNAUTHORIZED } end ngx.say (Json.encode { user = user, repository = repository, }) end return { status = ngx.HTTP_OK } end) Server.websocket = wrap (function (context) local key = Keys.editor ({ owner = { login = ngx.var.owner }, name = ngx.var.name, }, ngx.var.branch) local editor = context.redis:get (key) if editor == ngx.null or not editor then return { status = ngx.HTTP_NOT_FOUND } end editor = assert (Json.decode (editor)) if not editor.target_url then return { status = ngx.HTTP_NOT_FOUND } end _G.ngx.var.target = editor.target_url end) Server.webhook = wrap (function (context) ngx.req.read_body () local hmac = Hmac.new (Config.github.secret) local headers = ngx.req.get_headers () local data = ngx.req.get_body_data () if not data then local filename = ngx.req.get_body_file () if filename then local file = io.open (filename, "r") data = assert (file:read "*a") assert (file:close ()) end end if not data then return { status = ngx.HTTP_BAD_REQUEST } end if "sha1=" .. tohex (hmac:final (data)) ~= headers ["X-Hub-Signature"] then return { status = ngx.HTTP_BAD_REQUEST } end data = assert (Json.decode (data)) local repository = data.repository if not repository then return { status = ngx.HTTP_OK } end local lock = Keys.lock (repository.full_name) while true do if context.redis:setnx (lock, "locked") == 1 then context.redis:expire (lock, Config.locks.timeout) break end ngx.sleep (0.1) end -- delete collaborators in database: local cursor = 0 repeat local res = context.redis:scan (cursor, "match", Keys.collaborator (repository, { login = "*" }), "count", 100) if res == ngx.null or not res then break end cursor = res [1] local keys = res [2] for _, key in ipairs (keys) do context.redis:del (key) end until cursor == "0" -- update data: local collaborators, status = Http { url = repository.collaborators_url:gsub ("{/collaborator}", ""), method = "GET", headers = { ["Accept" ] = "application/vnd.github.v3+json", ["Authorization"] = "token " .. Config.github.token, ["User-Agent" ] = "Ardoises", }, } if status >= 300 and status < 500 then -- delete repository: context.redis:del (Keys.repository (repository)) -- delete webhook(s): local function create () local user = context.redis:get (Keys.user (repository.owner)) if user == ngx.null or not user then return end user = Json.decode (user) if not user then return end local webhooks, wh_status = Http { url = repository.hooks_url, method = "GET", headers = { ["Accept" ] = "application/vnd.github.v3+json", ["Authorization"] = "token " .. user.tokens.github, ["User-Agent" ] = "Ardoises", }, } if wh_status ~= 200 then return end for _, hook in ipairs (webhooks) do if hook.config.url:find (Url.build (Config.ardoises.url), 1, true) then Http { url = hook.url, method = "DELETE", headers = { ["Accept" ] = "application/vnd.github.v3+json", ["Authorization"] = "token " .. user.tokens.github, ["User-Agent" ] = "Ardoises", }, } end end end create () elseif status == 200 then -- update readme: local readme readme, status = Http { url = repository.url .. "/readme", method = "GET", headers = { ["Accept" ] = "application/vnd.github.3.html", ["Authorization"] = "token " .. Config.github.token, ["User-Agent" ] = "Ardoises", }, } if status == ngx.HTTP_OK then repository.readme = readme end -- get branches: local branches branches, status = Http { url = repository.branches_url:gsub ("{/branch}", ""), method = "GET", headers = { ["Accept" ] = "application/vnd.github.loki-preview+json", ["Authorization"] = "token " .. Config.github.token, ["User-Agent" ] = "Ardoises", }, } assert (status == ngx.HTTP_OK, status) repository.branches = branches for _, branch in ipairs (branches) do -- update readme: readme, status = Http { url = repository.url .. "/readme", query = { ref = branch.name }, method = "GET", headers = { ["Accept" ] = "application/vnd.github.3.html", ["Authorization"] = "token " .. Config.github.token, ["User-Agent" ] = "Ardoises", }, } if status == ngx.HTTP_OK then branch.readme = readme end end -- update repository: context.redis:set (Keys.repository (repository), Json.encode (repository)) -- update collaborators: for _, collaborator in ipairs (collaborators) do local key = Keys.collaborator (repository, collaborator) context.redis:set (key, Json.encode { repository = { owner = { login = repository.owner.login }, name = repository.name, }, collaborator = collaborator, }) end end context.redis:del (Keys.lock (repository.full_name)) return { status = ngx.HTTP_OK } end) return Server
---------------------------------------------------------------------------------- -- Total RP 3 -- Popups API -- --------------------------------------------------------------------------- -- Copyright 2014 Sylvain Cossement (telkostrasz@telkostrasz.be) -- -- 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. ---------------------------------------------------------------------------------- -- Public accessor TRP3_API.popup = {}; -- Lua imports local table = table; -- imports local Utils = TRP3_API.utils; local loc = TRP3_API.loc; local initList = TRP3_API.ui.list.initList; local tinsert, tremove, _G, pairs, wipe, math, assert = tinsert, tremove, _G, pairs, wipe, math, assert; local handleMouseWheel = TRP3_API.ui.list.handleMouseWheel; local setTooltipForFrame, setTooltipForSameFrame = TRP3_API.ui.tooltip.setTooltipForFrame, TRP3_API.ui.tooltip.setTooltipForSameFrame; local hooksecurefunc, GetItemIcon, IsControlKeyDown = hooksecurefunc, GetItemIcon, IsControlKeyDown; local getIconList, getIconListSize, getImageList, getImageListSize, getMusicList, getMusicListSize; local hexaToNumber, numberToHexa = TRP3_API.utils.color.hexaToNumber, TRP3_API.utils.color.numberToHexa; local strconcat = strconcat; local safeMatch = TRP3_API.utils.str.safeMatch; local displayDropDown = TRP3_API.ui.listbox.displayDropDown; local max = math.max; --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- Static popups definition --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* StaticPopupDialogs["TRP3_INFO"] = { button1 = OKAY, timeout = false, whileDead = true, hideOnEscape = true }; StaticPopupDialogs["TRP3_CONFIRM"] = { button1 = ACCEPT, button2 = CANCEL, OnAccept = function(self) if StaticPopupDialogs["TRP3_CONFIRM"].trp3onAccept then StaticPopupDialogs["TRP3_CONFIRM"].trp3onAccept(); end end, OnCancel = function(arg1,arg2) if StaticPopupDialogs["TRP3_CONFIRM"].trp3onCancel then StaticPopupDialogs["TRP3_CONFIRM"].trp3onCancel(); end end, timeout = false, whileDead = true, hideOnEscape = true, showAlert = true, }; StaticPopupDialogs["TRP3_YES_NO"] = { button1 = YES, button2 = NO, OnAccept = function(self) if StaticPopupDialogs["TRP3_YES_NO"].trp3onAccept then StaticPopupDialogs["TRP3_YES_NO"].trp3onAccept(); end end, OnCancel = function(self) if StaticPopupDialogs["TRP3_YES_NO"].trp3onCancel then StaticPopupDialogs["TRP3_YES_NO"].trp3onCancel(); end end, timeout = false, whileDead = true, hideOnEscape = true, showAlert = true, } StaticPopupDialogs["TRP3_YES_NO_CUSTOM"] = { button1 = YES, button2 = NO, OnAccept = function(self) if StaticPopupDialogs["TRP3_YES_NO_CUSTOM"].trp3onAccept then StaticPopupDialogs["TRP3_YES_NO_CUSTOM"].trp3onAccept(); end end, OnCancel = function(self) if StaticPopupDialogs["TRP3_YES_NO_CUSTOM"].trp3onCancel then StaticPopupDialogs["TRP3_YES_NO_CUSTOM"].trp3onCancel(); end end, timeout = false, whileDead = true, hideOnEscape = true, showAlert = true, } StaticPopupDialogs["TRP3_INPUT_TEXT"] = { button1 = ACCEPT, button2 = CANCEL, OnShow = function(self) _G[self:GetName().."EditBox"]:SetNumeric(false); -- Remove letters limit that other add-ons might have added but not cleaned _G[self:GetName().."EditBox"]:SetMaxLetters(0); end, OnAccept = function(self) if StaticPopupDialogs["TRP3_INPUT_TEXT"].trp3onAccept then StaticPopupDialogs["TRP3_INPUT_TEXT"].trp3onAccept(_G[self:GetName().."EditBox"]:GetText()); end end, OnCancel = function(arg1,arg2) if StaticPopupDialogs["TRP3_INPUT_TEXT"].trp3onCancel then StaticPopupDialogs["TRP3_INPUT_TEXT"].trp3onCancel(); end end, EditBoxOnEnterPressed = function(self) self:GetParent().button1:GetScript("OnClick")(self:GetParent().button1); end, EditBoxOnEscapePressed = function(self) self:GetParent().button2:GetScript("OnClick")(self:GetParent().button2); end, timeout = false, whileDead = true, hideOnEscape = true, hasEditBox = true, }; StaticPopupDialogs["TRP3_INPUT_NUMBER"] = { button1 = ACCEPT, button2 = CANCEL, OnShow = function(self) _G[self:GetName().."EditBox"]:SetNumeric(true); end, OnAccept = function(self) if StaticPopupDialogs["TRP3_INPUT_NUMBER"].trp3onAccept then StaticPopupDialogs["TRP3_INPUT_NUMBER"].trp3onAccept(_G[self:GetName().."EditBox"]:GetNumber()); end end, OnHide = function(self) _G[self:GetName().."EditBox"]:SetNumeric(false); end, OnCancel = function(arg1,arg2) if StaticPopupDialogs["TRP3_INPUT_NUMBER"].trp3onCancel then StaticPopupDialogs["TRP3_INPUT_NUMBER"].trp3onCancel(); end end, EditBoxOnEnterPressed = function(self) self:GetParent().button1:GetScript("OnClick")(self:GetParent().button1); end, EditBoxOnEscapePressed = function(self) self:GetParent().button2:GetScript("OnClick")(self:GetParent().button2); end, timeout = false, whileDead = true, hideOnEscape = true, hasEditBox = true, }; --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- Static popups methods --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- local POPUP_HEAD = "|TInterface\\AddOns\\totalRP3\\resources\\trp3logo:113:263|t\n \n"; local POPUP_HEAD = "Total RP 3\n \n"; -- Show a simple alert with a OK button. function TRP3_API.popup.showAlertPopup(text) StaticPopupDialogs["TRP3_INFO"].text = POPUP_HEAD..text; local dialog = StaticPopup_Show("TRP3_INFO"); if dialog then dialog:ClearAllPoints(); dialog:SetPoint("CENTER", UIParent, "CENTER"); end end function TRP3_API.popup.showConfirmPopup(text, onAccept, onCancel) StaticPopupDialogs["TRP3_CONFIRM"].text = POPUP_HEAD..text.."\n\n"; StaticPopupDialogs["TRP3_CONFIRM"].trp3onAccept = onAccept; StaticPopupDialogs["TRP3_CONFIRM"].trp3onCancel = onCancel; local dialog = StaticPopup_Show("TRP3_CONFIRM"); if dialog then dialog:ClearAllPoints(); dialog:SetPoint("CENTER", UIParent, "CENTER"); end end function TRP3_API.popup.showYesNoPopup(text, onAccept, onCancel) StaticPopupDialogs["TRP3_YES_NO"].text = POPUP_HEAD..text.."\n\n"; StaticPopupDialogs["TRP3_YES_NO"].trp3onAccept = onAccept; StaticPopupDialogs["TRP3_YES_NO"].trp3onCancel = onCancel; local dialog = StaticPopup_Show("TRP3_YES_NO"); if dialog then dialog:ClearAllPoints(); dialog:SetPoint("CENTER", UIParent, "CENTER"); end end function TRP3_API.popup.showCustomYesNoPopup(text, yesText, noText, onAccept, onCancel) StaticPopupDialogs["TRP3_YES_NO_CUSTOM"].button1 = yesText; StaticPopupDialogs["TRP3_YES_NO_CUSTOM"].button2 = noText; StaticPopupDialogs["TRP3_YES_NO_CUSTOM"].text = text; StaticPopupDialogs["TRP3_YES_NO_CUSTOM"].trp3onAccept = onAccept; StaticPopupDialogs["TRP3_YES_NO_CUSTOM"].trp3onCancel = onCancel; local dialog = StaticPopup_Show("TRP3_YES_NO_CUSTOM"); if dialog then dialog:ClearAllPoints(); dialog:SetPoint("CENTER", UIParent, "CENTER"); end end function TRP3_API.popup.showTextInputPopup(text, onAccept, onCancel, default) StaticPopupDialogs["TRP3_INPUT_TEXT"].text = POPUP_HEAD..text.."\n\n"; StaticPopupDialogs["TRP3_INPUT_TEXT"].trp3onAccept = onAccept; StaticPopupDialogs["TRP3_INPUT_TEXT"].trp3onCancel = onCancel; local dialog = StaticPopup_Show("TRP3_INPUT_TEXT"); if dialog then dialog:ClearAllPoints(); dialog:SetPoint("CENTER", UIParent, "CENTER"); _G[dialog:GetName().."EditBox"]:SetText(default or ""); _G[dialog:GetName().."EditBox"]:HighlightText(); end end function TRP3_API.popup.showNumberInputPopup(text, onAccept, onCancel, default) StaticPopupDialogs["TRP3_INPUT_NUMBER"].text = POPUP_HEAD..text.."\n\n"; StaticPopupDialogs["TRP3_INPUT_NUMBER"].trp3onAccept = onAccept; StaticPopupDialogs["TRP3_INPUT_NUMBER"].trp3onCancel = onCancel; local dialog = StaticPopup_Show("TRP3_INPUT_NUMBER"); if dialog then dialog:ClearAllPoints(); dialog:SetPoint("CENTER", UIParent, "CENTER"); _G[dialog:GetName().."EditBox"]:SetNumber(default or false); _G[dialog:GetName().."EditBox"]:HighlightText(); end end --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- Dynamic popup --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* local TRP3_PopupsFrame = TRP3_PopupsFrame; local function showPopup(popup) for _, frame in pairs({TRP3_PopupsFrame:GetChildren()}) do frame:Hide(); end TRP3_PopupsFrame:Show(); popup:Show(); end local function hidePopups() TRP3_PopupsFrame:Hide(); end TRP3_API.popup.hidePopups = hidePopups; --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- Music browser --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* local TRP3_MusicBrowser = TRP3_MusicBrowser; local musicWidgetTab = {}; local filteredMusicList; local function decorateMusic(lineFrame, musicURL) musicURL = filteredMusicList[musicURL]; local musicName = musicURL:reverse(); musicName = (musicName:sub(1, musicName:find("%\\")-1)):reverse(); setTooltipForFrame(lineFrame, lineFrame, "RIGHT", 0, -30, musicName, ("|cff00ff00%s\n\n|cffff9900%s: |cffffffff%s\n|cffff9900%s: |cffffffff%s"):format(musicURL, loc.CM_L_CLICK, loc.REG_PLAYER_ABOUT_MUSIC_SELECT2, loc.CM_R_CLICK, loc.REG_PLAYER_ABOUT_MUSIC_LISTEN)); _G[lineFrame:GetName().."Text"]:SetText(musicName); lineFrame.musicURL = musicURL; end local function onMusicClick(lineFrame, mousebutton) if mousebutton == "LeftButton" then hidePopups(); TRP3_MusicBrowser:Hide(); if TRP3_MusicBrowserContent.callback then TRP3_MusicBrowserContent.callback(lineFrame.musicURL); end elseif lineFrame.musicURL then Utils.music.playMusic(lineFrame.musicURL); end end local function filteredMusicBrowser() local filter = TRP3_MusicBrowserFilterBox:GetText(); if filteredMusicList and filteredMusicList ~= getMusicList() then -- Remove previous filtering if is not full list wipe(filteredMusicList); filteredMusicList = nil; end filteredMusicList = getMusicList(filter); -- Music tab is unfiltered TRP3_MusicBrowserTotal:SetText( (#filteredMusicList) .. " / " .. getMusicListSize() ); initList( { widgetTab = musicWidgetTab, decorate = decorateMusic }, filteredMusicList, TRP3_MusicBrowserContentSlider ); end local function initMusicBrowser() handleMouseWheel(TRP3_MusicBrowserContent, TRP3_MusicBrowserContentSlider); TRP3_MusicBrowserContentSlider:SetValue(0); -- Create lines for line = 0, 8 do local lineFrame = CreateFrame("Button", "TRP3_MusicBrowserButton_"..line, TRP3_MusicBrowserContent, "TRP3_MusicBrowserLine"); lineFrame:SetPoint("TOP", TRP3_MusicBrowserContent, "TOP", 0, -10 + (line * (-31))); lineFrame:SetScript("OnClick", onMusicClick); tinsert(musicWidgetTab, lineFrame); end TRP3_MusicBrowserFilterBox:SetScript("OnTextChanged", filteredMusicBrowser); TRP3_MusicBrowserTitle:SetText(loc.UI_MUSIC_BROWSER); TRP3_MusicBrowserFilterBoxText:SetText(loc.UI_FILTER); TRP3_MusicBrowserFilterStop:SetText(loc.REG_PLAYER_ABOUT_MUSIC_STOP); filteredMusicBrowser(); end local function showMusicBrowser(callback) TRP3_MusicBrowserContent.callback = callback; TRP3_MusicBrowserFilterBox:SetText(""); TRP3_MusicBrowserFilterBox:SetFocus(); end --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- Icon browser --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* local TRP3_IconBrowser = TRP3_IconBrowser; local iconWidgetTab = {}; local filteredIconList; local ui_IconBrowserContent = TRP3_IconBrowserContent; local function decorateIcon(icon, index) icon:SetNormalTexture("Interface\\ICONS\\"..filteredIconList[index]); icon:SetPushedTexture("Interface\\ICONS\\"..filteredIconList[index]); setTooltipForFrame(icon, TRP3_IconBrowser, "RIGHT", 0, -100, Utils.str.icon(filteredIconList[index], 75), filteredIconList[index]); icon.index = index; end local function onIconClick(icon) TRP3_API.popup.hideIconBrowser(); if ui_IconBrowserContent.onSelectCallback then ui_IconBrowserContent.onSelectCallback(filteredIconList[icon.index], icon); end end local function onIconClose() TRP3_API.popup.hideIconBrowser(); if ui_IconBrowserContent.onCancelCallback then ui_IconBrowserContent.onCancelCallback(); end end local function filteredIconBrowser() local filter = TRP3_IconBrowserFilterBox:GetText(); if filteredIconList and filteredIconList ~= getIconList() then -- Remove previous filtering if is not full list wipe(filteredIconList); filteredIconList = nil; end filteredIconList = getIconList(filter); TRP3_IconBrowserTotal:SetText( (#filteredIconList) .. " / " .. getIconListSize() ); initList( { widgetTab = iconWidgetTab, decorate = decorateIcon }, filteredIconList, TRP3_IconBrowserContentSlider ); end local function initIconBrowser() handleMouseWheel(ui_IconBrowserContent, TRP3_IconBrowserContentSlider); TRP3_IconBrowserContentSlider:SetValue(0); -- Create icons local row, column; for row = 0, 5 do for column = 0, 7 do local button = CreateFrame("Button", "TRP3_IconBrowserButton_"..row.."_"..column, ui_IconBrowserContent, "TRP3_IconBrowserButton"); button:ClearAllPoints(); button:SetPoint("TOPLEFT", ui_IconBrowserContent, "TOPLEFT", 15 + (column * 45), -15 + (row * (-45))); button:SetScript("OnClick", onIconClick); tinsert(iconWidgetTab, button); end end TRP3_IconBrowserFilterBox:SetScript("OnTextChanged", filteredIconBrowser); TRP3_IconBrowserClose:SetScript("OnClick", onIconClose); TRP3_IconBrowserTitle:SetText(loc.UI_ICON_BROWSER); TRP3_IconBrowserFilterBoxText:SetText(loc.UI_FILTER); filteredIconBrowser(); end local function showIconBrowser(onSelectCallback, onCancelCallback, scale) ui_IconBrowserContent.onSelectCallback = onSelectCallback; ui_IconBrowserContent.onCancelCallback = onCancelCallback; TRP3_IconBrowserFilterBox:SetText(""); TRP3_IconBrowserFilterBox:SetFocus(); TRP3_IconBrowser:SetScale(scale or 1); end function TRP3_API.popup.hideIconBrowser() hidePopups(); TRP3_IconBrowser:Hide(); end --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- Companion browser --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* local TRP3_CompanionBrowser = TRP3_CompanionBrowser; local companionWidgetTab = {}; local filteredCompanionList = {}; local ui_CompanionBrowserContent = TRP3_CompanionBrowserContent; local GetNumPets, GetPetInfoByIndex = C_PetJournal.GetNumPets, C_PetJournal.GetPetInfoByIndex; local GetMountIDs, GetMountInfoByID = C_MountJournal.GetMountIDs, C_MountJournal.GetMountInfoByID; local currentCompanionType; local function onCompanionClick(button) TRP3_CompanionBrowser:Hide(); hidePopups(); if ui_CompanionBrowserContent.onSelectCallback then ui_CompanionBrowserContent.onSelectCallback(filteredCompanionList[button.index], currentCompanionType, button); end end local function onCompanionClose() TRP3_CompanionBrowser:Hide(); hidePopups(); if ui_CompanionBrowserContent.onCancelCallback then ui_CompanionBrowserContent.onCancelCallback(); end end local function decorateCompanion(button, index) local name, icon = filteredCompanionList[index][1], filteredCompanionList[index][2]; local description, speciesName = filteredCompanionList[index][3], filteredCompanionList[index][4]; button:SetNormalTexture(icon); button:SetPushedTexture(icon); local text = "|cffffff00" .. speciesName .. "|r"; if description and description:len() > 0 then text = text .. "\n\"" .. description .. "\""; end setTooltipForFrame(button, TRP3_CompanionBrowser, "RIGHT", 0, -100, "|T" .. icon .. ":40|t " .. name, text); button.index = index; end local function nameComparator(elem1, elem2) return elem1[1] < elem2[1]; end local function getWoWCompanionFilteredList(filter) local count = 0; wipe(filteredCompanionList); if currentCompanionType == TRP3_API.ui.misc.TYPE_BATTLE_PET then -- Battle pets local numPets, numOwned = GetNumPets(); for i = 1, numPets do local petID, speciesID, owned, customName, level, favorite, isRevoked, speciesName, icon, petType, companionID, tooltip, description = GetPetInfoByIndex(i); -- Only renamed pets can be bound if customName and (filter:len() == 0 or safeMatch(customName:lower(), filter)) then tinsert(filteredCompanionList, {customName, icon, description, speciesName}); count = count + 1; end end elseif currentCompanionType == TRP3_API.ui.misc.TYPE_MOUNT then -- Mounts for i, id in pairs(GetMountIDs()) do local creatureName, spellID, icon, active, _, _, _, _, _, _, isCollected = GetMountInfoByID(id); if isCollected and creatureName and (filter:len() == 0 or safeMatch(creatureName:lower(), filter)) then local _, description = C_MountJournal.GetMountInfoExtraByID(id); tinsert(filteredCompanionList, {creatureName, icon, description, loc.PR_CO_MOUNT, spellID, id}); count = count + 1; end end end table.sort(filteredCompanionList, nameComparator); return count; end local function filteredCompanionBrowser() local filter = TRP3_CompanionBrowserFilterBox:GetText():lower(); local isOk = TRP3_API.utils.str.safeMatch("", filter) ~= nil; local totalCompanionCount = getWoWCompanionFilteredList(isOk and filter or ""); TRP3_CompanionBrowserTotal:SetText( (#filteredCompanionList) .. " / " .. totalCompanionCount ); initList( { widgetTab = companionWidgetTab, decorate = decorateCompanion }, filteredCompanionList, TRP3_CompanionBrowserContentSlider ); end local function initCompanionBrowser() handleMouseWheel(ui_CompanionBrowserContent, TRP3_CompanionBrowserContentSlider); TRP3_CompanionBrowserContentSlider:SetValue(0); -- Create icons local row, column; for row = 0, 5 do for column = 0, 7 do local button = CreateFrame("Button", "TRP3_CompanionBrowserButton_"..row.."_"..column, ui_CompanionBrowserContent, "TRP3_IconBrowserButton"); button:ClearAllPoints(); button:SetPoint("TOPLEFT", ui_CompanionBrowserContent, "TOPLEFT", 15 + (column * 45), -15 + (row * (-45))); button:SetScript("OnClick", onCompanionClick); tinsert(companionWidgetTab, button); end end TRP3_CompanionBrowserFilterBox:SetScript("OnTextChanged", filteredCompanionBrowser); TRP3_CompanionBrowserClose:SetScript("OnClick", onCompanionClose); setTooltipForSameFrame(TRP3_CompanionBrowserFilterHelp, "TOPLEFT", 0, 0, "|TInterface\\ICONS\\icon_petfamily_beast:25|t " .. loc.UI_COMPANION_BROWSER_HELP ,loc.UI_COMPANION_BROWSER_HELP_TT); TRP3_CompanionBrowserFilterBoxText:SetText(loc.UI_FILTER); end function TRP3_API.popup.showCompanionBrowser(onSelectCallback, onCancelCallback, companionType) currentCompanionType = companionType or TRP3_API.ui.misc.TYPE_BATTLE_PET; if currentCompanionType == TRP3_API.ui.misc.TYPE_BATTLE_PET then TRP3_CompanionBrowserTitle:SetText(loc.REG_COMPANION_BROWSER_BATTLE); TRP3_CompanionBrowserFilterHelp:Show(); TRP3_RefreshTooltipForFrame(TRP3_CompanionBrowserFilterHelp); else TRP3_CompanionBrowserTitle:SetText(loc.REG_COMPANION_BROWSER_MOUNT); TRP3_CompanionBrowserFilterHelp:Hide(); end ui_CompanionBrowserContent.onSelectCallback = onSelectCallback; ui_CompanionBrowserContent.onCancelCallback = onCancelCallback; TRP3_CompanionBrowserFilterBox:SetText(""); filteredCompanionBrowser(); showPopup(TRP3_CompanionBrowser); TRP3_CompanionBrowserFilterBox:SetFocus(); if currentCompanionType == TRP3_API.ui.misc.TYPE_BATTLE_PET then TRP3_RefreshTooltipForFrame(TRP3_CompanionBrowserFilterHelp); end end --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- Color browser --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* local TRP3_ColorBrowser, TRP3_ColorBrowserColor = TRP3_ColorBrowser, TRP3_ColorBrowserColor; local toast = TRP3_API.ui.tooltip.toast; local Color, ColorManager = TRP3_API.Ellyb.Color, TRP3_API.Ellyb.ColorManager; local COLOR_PRESETS_BASIC = { { CO = ColorManager.RED, TX = loc.CM_RED}, { CO = ColorManager.ORANGE, TX = loc.CM_ORANGE}, { CO = ColorManager.YELLOW, TX = loc.CM_YELLOW}, { CO = ColorManager.GREEN, TX = loc.CM_GREEN}, { CO = ColorManager.CYAN, TX = loc.CM_CYAN}, { CO = ColorManager.BLUE, TX = loc.CM_BLUE}, { CO = ColorManager.PURPLE, TX = loc.CM_PURPLE}, { CO = ColorManager.PINK, TX = loc.CM_PINK}, { CO = ColorManager.WHITE, TX = loc.CM_WHITE}, { CO = ColorManager.GREY, TX = loc.CM_GREY}, { CO = ColorManager.BLACK, TX = loc.CM_BLACK}, } local COLOR_PRESETS_CLASS = { { CO = ColorManager.HUNTER, TX = ({GetClassInfo(3)})[1]}, { CO = ColorManager.WARLOCK, TX = ({GetClassInfo(9)})[1]}, { CO = ColorManager.PRIEST, TX = ({GetClassInfo(5)})[1]}, { CO = ColorManager.PALADIN, TX = ({GetClassInfo(2)})[1]}, { CO = ColorManager.MAGE, TX = ({GetClassInfo(8)})[1]}, { CO = ColorManager.ROGUE, TX = ({GetClassInfo(4)})[1]}, { CO = ColorManager.DRUID, TX = ({GetClassInfo(11)})[1]}, { CO = ColorManager.SHAMAN, TX = ({GetClassInfo(7)})[1]}, { CO = ColorManager.WARRIOR, TX = ({GetClassInfo(1)})[1]}, { CO = ColorManager.DEATHKNIGHT, TX = ({GetClassInfo(6)})[1]}, { CO = ColorManager.MONK, TX = ({GetClassInfo(10)})[1]}, { CO = ColorManager.DEMONHUNTER, TX = ({GetClassInfo(12)})[1]}, } table.sort(COLOR_PRESETS_CLASS, function(a,b) return a.TX<b.TX end) local COLOR_PRESETS_RESOURCES = { { CO = ColorManager.POWER_MANA, TX = MANA}, { CO = ColorManager.POWER_RAGE, TX = RAGE}, { CO = ColorManager.POWER_FOCUS, TX = FOCUS}, { CO = ColorManager.POWER_ENERGY, TX = ENERGY}, { CO = ColorManager.POWER_COMBO_POINTS, TX = COMBO_POINTS}, { CO = ColorManager.POWER_RUNES, TX = RUNES}, { CO = ColorManager.POWER_RUNIC_POWER, TX = RUNIC_POWER}, { CO = ColorManager.POWER_SOUL_SHARDS, TX = SOUL_SHARDS}, { CO = ColorManager.POWER_LUNAR_POWER, TX = LUNAR_POWER}, { CO = ColorManager.POWER_HOLY_POWER, TX = HOLY_POWER}, { CO = ColorManager.POWER_MAELSTROM, TX = MAELSTROM}, { CO = ColorManager.POWER_INSANITY, TX = INSANITY}, { CO = ColorManager.POWER_CHI, TX = CHI}, { CO = ColorManager.POWER_ARCANE_CHARGES, TX = ARCANE_CHARGES}, { CO = ColorManager.POWER_FURY, TX = FURY}, { CO = ColorManager.POWER_PAIN, TX = PAIN}, { CO = ColorManager.POWER_AMMOSLOT, TX = AMMOSLOT}, { CO = ColorManager.POWER_FUEL, TX = FUEL}, } table.sort(COLOR_PRESETS_RESOURCES, function(a,b) return a.TX<b.TX end) local COLOR_PRESETS_ITEMS = { { CO = ColorManager.ITEM_POOR, TX = ITEM_QUALITY0_DESC}, { CO = ColorManager.ITEM_COMMON, TX = ITEM_QUALITY1_DESC}, { CO = ColorManager.ITEM_UNCOMMON, TX = ITEM_QUALITY2_DESC}, { CO = ColorManager.ITEM_RARE, TX = ITEM_QUALITY3_DESC}, { CO = ColorManager.ITEM_EPIC, TX = ITEM_QUALITY4_DESC}, { CO = ColorManager.ITEM_LEGENDARY, TX = ITEM_QUALITY5_DESC}, { CO = ColorManager.ITEM_ARTIFACT, TX = ITEM_QUALITY6_DESC}, { CO = ColorManager.ITEM_HEIRLOOM, TX = ITEM_QUALITY7_DESC}, { CO = ColorManager.ITEM_WOW_TOKEN, TX = ITEM_QUALITY8_DESC}, } ---@param color Color local function getPresetForColor(color) local hexa = "#" .. color:GenerateHexadecimalColor(true); for k, color in pairs(TRP3_Colors) do if color.CO == hexa then return color, k; end end return false; end local function saveCustomColor(color, name, indexToUpdate) TRP3_ColorBrowserEditBox:ClearFocus(); local hexaColorCode = "#" .. color:GenerateHexadecimalColor(true); if (name == "") then name = hexaColorCode; end if not indexToUpdate then for index, preset in pairs(TRP3_Colors) do if (Color(preset.CO):IsEqualTo(color)) then indexToUpdate = index; break end end end if (indexToUpdate) then TRP3_Colors[indexToUpdate].TX = name; else tinsert(TRP3_Colors, { CO = hexaColorCode, TX = name }); table.sort(TRP3_Colors, function(a, b) return ColorManager.compareHSL(Color(a.CO), Color(b.CO)) end) end end local function deleteCustomColorAtIndex(indexToDelete) if (indexToDelete) then tremove(TRP3_Colors, indexToDelete); end end local function colorPresetsDropDownSelection(hexValue) if hexValue == "SAVE" then TRP3_API.popup.showTextInputPopup(loc.BW_CUSTOM_NAME .. "\n\n" .. loc.BW_CUSTOM_NAME_TT, function(text) saveCustomColor(Color(TRP3_ColorBrowser.red, TRP3_ColorBrowser.green, TRP3_ColorBrowser.blue), text); end); elseif hexValue == "RENAME" then local existingPreset, index = getPresetForColor(Color(TRP3_ColorBrowser.red, TRP3_ColorBrowser.green, TRP3_ColorBrowser.blue)); TRP3_API.popup.showTextInputPopup(loc.BW_CUSTOM_NAME .. "\n\n" .. loc.BW_CUSTOM_NAME_TT, function(text) saveCustomColor(Color(TRP3_ColorBrowser.red, TRP3_ColorBrowser.green, TRP3_ColorBrowser.blue), text, index); end, nil, existingPreset.TX); elseif hexValue == "DELETE" then local existingPreset, index = getPresetForColor(Color(TRP3_ColorBrowser.red, TRP3_ColorBrowser.green, TRP3_ColorBrowser.blue)); deleteCustomColorAtIndex(index) else local r, g, b = ColorManager.hexaToNumber(hexValue); TRP3_ColorBrowser.red = r; TRP3_ColorBrowser.green = g; TRP3_ColorBrowser.blue = b; TRP3_ColorBrowserColor:SetColorRGB(r, g, b); TRP3_ColorBrowserSwatch:SetColorTexture(r, g, b); end end local function colorPresetsDropDown() local values = {}; local values_basic = {}; tinsert(values, { Ellyb.ColorManager.YELLOW(loc.BW_COLOR_PRESET_TITLE)}); local existingPreset = getPresetForColor(Color(TRP3_ColorBrowser.red, TRP3_ColorBrowser.green, TRP3_ColorBrowser.blue)); if existingPreset then local coloredText = Color(existingPreset.CO):WrapTextInColorCode(existingPreset.TX); tinsert(values, { loc.BW_COLOR_PRESET_RENAME:format(coloredText), "RENAME" }); tinsert(values, { loc.BW_COLOR_PRESET_DELETE:format(coloredText), "DELETE" }); else tinsert(values, { loc.BW_COLOR_PRESET_SAVE, "SAVE" }); end tinsert(values, { "" }); -- Separator for index, preset in pairs(COLOR_PRESETS_BASIC) do tinsert(values_basic, { preset.CO:WrapTextInColorCode(preset.TX), preset.CO:GenerateHexadecimalColor() }); end tinsert(values, {loc.UI_COLOR_BROWSER_PRESETS_BASIC, values_basic}); local values_classes = {}; for index, preset in pairs(COLOR_PRESETS_CLASS) do tinsert(values_classes, { preset.CO:WrapTextInColorCode(preset.TX), preset.CO:GenerateHexadecimalColor() }); end tinsert(values, {loc.UI_COLOR_BROWSER_PRESETS_CLASSES, values_classes}); local values_resources = {}; for index, preset in pairs(COLOR_PRESETS_RESOURCES) do tinsert(values_resources, { preset.CO:WrapTextInColorCode(preset.TX), preset.CO:GenerateHexadecimalColor() }); end tinsert(values, {loc.UI_COLOR_BROWSER_PRESETS_RESOURCES, values_resources}); local values_items = {}; for index, preset in pairs(COLOR_PRESETS_ITEMS) do tinsert(values_items, { preset.CO:WrapTextInColorCode(preset.TX), preset.CO:GenerateHexadecimalColor() }); end tinsert(values, {loc.UI_COLOR_BROWSER_PRESETS_ITEMS, values_items}); local values_custom = {}; for index, preset in pairs(TRP3_Colors) do tinsert(values_custom, { Color(preset.CO):WrapTextInColorCode(preset.TX), preset.CO }); end tinsert(values, {loc.UI_COLOR_BROWSER_PRESETS_CUSTOM, values_custom}); displayDropDown(TRP3_ColorBrowserPresets, values, colorPresetsDropDownSelection, 0, true); end local function initColorBrowser() TRP3_ColorBrowserSelect:SetText(loc.UI_COLOR_BROWSER_SELECT); TRP3_ColorBrowserTitle:SetText(loc.UI_COLOR_BROWSER); TRP3_ColorBrowserPresets:SetText(loc.UI_COLOR_BROWSER_PRESETS); if not TRP3_Colors then TRP3_Colors = {}; end TRP3_ColorBrowserEditBoxText:SetText("Code"); setTooltipForSameFrame(TRP3_ColorBrowserEditBoxHelp, "RIGHT", 0, 5, loc.BW_COLOR_CODE, loc.BW_COLOR_CODE_TT); TRP3_ColorBrowserEditBox:SetScript("OnEnterPressed", function(self) if self:GetText():match("^%x%x%x%x%x%x$") or self:GetText():match("^#%x%x%x%x%x%x$") then -- Checks that it is a 6 figures hexadecimal number (with or without a #) local r, g, b = ColorManager.hexaToNumber(self:GetText()); TRP3_ColorBrowser.red = r; TRP3_ColorBrowser.green = g; TRP3_ColorBrowser.blue = b; TRP3_ColorBrowserColor:SetColorRGB(r, g, b); TRP3_ColorBrowserSwatch:SetColorTexture(r, g, b); self:ClearFocus(); else toast(loc.BW_COLOR_CODE_ALERT, 1); end end); TRP3_ColorBrowserColor:SetScript("OnColorSelect", function(self, r, g, b) TRP3_ColorBrowserEditBox:ClearFocus(); TRP3_ColorBrowserSwatch:SetColorTexture(r, g, b); TRP3_ColorBrowser.red = r; TRP3_ColorBrowser.green = g; TRP3_ColorBrowser.blue = b; TRP3_ColorBrowserEditBox:SetText(("#%.2x%.2x%.2x"):format(r * 255, g * 255, b * 255):upper()); end); TRP3_ColorBrowserSelect:SetScript("OnClick", function() hidePopups(); TRP3_ColorBrowser:Hide(); if TRP3_ColorBrowser.callback ~= nil then TRP3_ColorBrowser.callback((TRP3_ColorBrowser.red or 1) * 255, (TRP3_ColorBrowser.green or 1) * 255, (TRP3_ColorBrowser.blue or 1) * 255); end end); TRP3_ColorBrowserPresets:SetScript("OnClick", colorPresetsDropDown); end local function showColorBrowser(callback, red, green, blue) TRP3_ColorBrowserColor:SetColorRGB((red or 255) / 255, (green or 255) / 255, (blue or 255) / 255); TRP3_ColorBrowser.callback = callback; end function TRP3_ColorButtonLoad(self) self:RegisterForClicks("LeftButtonUp", "RightButtonUp"); self.setColor = function(red, green, blue) self.red = red; self.green = green; self.blue = blue; if red and green and blue then _G[self:GetName() .. "SwatchBg"]:SetColorTexture(red / 255, green / 255, blue / 255); _G[self:GetName() .. "SwatchBgHighlight"]:SetVertexColor(red / 255, green / 255, blue / 255); else _G[self:GetName() .. "SwatchBg"]:SetTexture("Interface\\ICONS\\icon_petfamily_mechanical"); _G[self:GetName() .. "SwatchBgHighlight"]:SetVertexColor(1.0, 1.0, 1.0); end if self.onSelection then self.onSelection(red, green, blue); end _G[self:GetName() .. "BlinkAnimate"]:Play(); _G[self:GetName() .. "BlinkAnimate"]:Finish(); end self.setColor(); end function TRP3_API.popup.showDefaultColorPicker(popupArgs) local setColor, r, g, b = unpack(popupArgs); ColorPickerFrame:SetColorRGB((r or 255) / 255, (g or 255) / 255, (b or 255) / 255); ColorPickerFrame.hasOpacity = false; ColorPickerFrame.opacity = 1; -- func is called every time the color is changed, whereas opacityFunc is only called when changing opacity or pressing OKAY -- Since we don't have opacity, I put the callback on opacityFunc to have the same behaviour as TRP3 color picker. ColorPickerFrame.func = function() end ColorPickerFrame.opacityFunc = function() local newR, newG, newB = ColorPickerFrame:GetColorRGB(); setColor(newR * 255, newG * 255, newB * 255); end ColorPickerFrame.cancelFunc = function() setColor(r, g, b); end ShowUIPanel(ColorPickerFrame); end --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- Image browser --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* local imageWidgetTab = {}; local filteredImageList = {}; local TRP3_ImageBrowser = TRP3_ImageBrowser; local function onImageSelect() assert(TRP3_ImageBrowserContent.currentImage, "No current image ..."); hidePopups(); TRP3_ImageBrowser:Hide(); if TRP3_ImageBrowser.callback then TRP3_ImageBrowser.callback(filteredImageList[TRP3_ImageBrowserContent.currentImage]); end end local function decorateImage(texture, index) local image = filteredImageList[index]; local ratio = image.height / image.width; local maxSize = max(texture:GetHeight(), texture:GetWidth()); if ratio > 1 then texture:SetHeight(maxSize); texture:SetWidth(texture:GetHeight() / ratio); else texture:SetWidth(maxSize); texture:SetHeight(texture:GetWidth() * ratio); end texture:SetTexture(image.url); TRP3_ImageBrowserContentURL:SetText(image.url:sub(11)); TRP3_ImageBrowserContent.currentImage = index; end local function filteredImageBrowser() local filter = TRP3_ImageBrowserFilterBox:GetText(); filteredImageList = getImageList(filter); local size = #filteredImageList; TRP3_ImageBrowserTotal:SetText( size .. " / " .. getImageListSize() ); if size > 0 then TRP3_ImageBrowserSelect:Enable(); else TRP3_ImageBrowserSelect:Disable(); end initList( { widgetTab = imageWidgetTab, decorate = decorateImage }, filteredImageList, TRP3_ImageBrowserContentSlider ); end local function initImageBrowser() handleMouseWheel(TRP3_ImageBrowserContent, TRP3_ImageBrowserContentSlider); TRP3_ImageBrowserContentSlider:SetValue(0); TRP3_ImageBrowserFilterBox:SetScript("OnTextChanged", filteredImageBrowser); TRP3_ImageBrowserSelect:SetScript("OnClick", onImageSelect); tinsert(imageWidgetTab, TRP3_ImageBrowserContentTexture); TRP3_ImageBrowserTitle:SetText(loc.UI_IMAGE_BROWSER); TRP3_ImageBrowserFilterBoxText:SetText(loc.UI_FILTER); TRP3_ImageBrowserSelect:SetText(loc.UI_IMAGE_SELECT); filteredImageBrowser(); end local function showImageBrowser(callback, externalFrame) TRP3_ImageBrowser.callback = callback; end --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- INIT --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* function TRP3_API.popup.init() getIconList, getIconListSize = TRP3_API.utils.resources.getIconList, TRP3_API.utils.resources.getIconListSize; getImageList, getImageListSize = TRP3_API.utils.resources.getImageList, TRP3_API.utils.resources.getImageListSize; getMusicList, getMusicListSize = TRP3_API.utils.resources.getMusicList, TRP3_API.utils.resources.getMusicListSize; initIconBrowser(); initCompanionBrowser(); initMusicBrowser(); initColorBrowser(); initImageBrowser(); end --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- POPUP REFACTOR --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* local tostring, type, unpack = tostring, type, unpack; TRP3_API.popup.IMAGES = "images"; TRP3_API.popup.ICONS = "icons"; TRP3_API.popup.COLORS = "colors"; TRP3_API.popup.MUSICS = "musics"; TRP3_API.popup.COMPANIONS = "companions"; local POPUP_STRUCTURE = { [TRP3_API.popup.IMAGES] = { frame = TRP3_ImageBrowser, showMethod = showImageBrowser, }, [TRP3_API.popup.COLORS] = { frame = TRP3_ColorBrowser, showMethod = showColorBrowser, }, [TRP3_API.popup.ICONS] = { frame = TRP3_IconBrowser, showMethod = showIconBrowser, }, [TRP3_API.popup.MUSICS] = { frame = TRP3_MusicBrowser, showMethod = showMusicBrowser, }, [TRP3_API.popup.COMPANIONS] = { frame = TRP3_CompanionBrowser, showMethod = TRP3_API.popup.showCompanionBrowser, } } TRP3_API.popup.POPUPS = POPUP_STRUCTURE; function TRP3_API.popup.showPopup(popupID, popupPosition, popupArgs) assert(popupID and POPUP_STRUCTURE[popupID], "Unknown popupID: " .. tostring(popupID)); assert(popupPosition == nil or type(popupPosition) == "table", "PopupPosition must be a table or be nil"); assert(popupArgs == nil or type(popupArgs) == "table", "PopupArgs must be a table or be nil"); local popup = POPUP_STRUCTURE[popupID]; popup.frame:ClearAllPoints(); if popupPosition and popupPosition.parent then popup.frame:SetParent(popupPosition.parent); popup.frame:SetPoint(popupPosition.point or "CENTER", popupPosition.parent, popupPosition.parentPoint or "CENTER", 0, 0); popup.frame:SetFrameLevel(popupPosition.parent:GetFrameLevel() + 20); popup.frame:Show(); else popup.frame:SetParent(TRP3_PopupsFrame); popup.frame:SetPoint("CENTER", 0, 0); for _, frame in pairs({TRP3_PopupsFrame:GetChildren()}) do frame:Hide(); end TRP3_PopupsFrame:Show(); popup.frame:Show(); end if popup.showMethod then popup.showMethod(unpack(popupArgs)); end end
local StopWatch = require ("StopWatch"); local sw = StopWatch(); while(true) do print(sw:Seconds()) end
-- Dialogue for NPC "npc_thea" loadDialogue = function(DL) DL:createChoiceNode(0) if (not DL:isConditionFulfilled("npc_thea", "who_are_you")) then DL:addChoice(1, "DL_Choice_WhoAreYou") -- Who are you? end if (not DL:isConditionFulfilled("npc_thea", "what_are_you_doing")) then DL:addChoice(10, "DL_Choice_WhatAreYouDoing") -- What are you doing here? end if (not DL:isConditionFulfilled("npc_thea", "mages")) then DL:addChoice(30, "DL_Choice_Mages") -- What do you think about mages? end if (not DL:isConditionFulfilled("npc_thea", "gandria") and DL:isConditionFulfilled("npc_thea", "what_are_you_doing")) then DL:addChoice(40, "DL_Choice_Gandria") -- What do you know about the city Gandria? end if (DL:isQuestState("theas_dream", "started") and DL:isQuestDescriptionUnlocked("theas_dream", 1)) then DL:addChoice(50, "DL_Choice_Syrah") -- I found a job for you in Gandria. end DL:addChoice(-1, "") -- "" DL:addNode() if (not DL:isConditionFulfilled("npc_thea", "who_are_you")) then DL:createNPCNode(1, 2, "DL_Thea_IAm") -- My name is Thea... and you? DL:addConditionProgress("npc_thea", "who_are_you") DL:addNode() DL:createChoiceNode(2) DL:addChoice(3, "DL_Choice_Cendric") -- I'm Cendric. Nice to meet you. DL:addChoice(4, "DL_Choice_DoesntMatter") -- My name isn't of importance. DL:addNode() DL:createNPCNode(3, -2, "DL_Thea_Nice") -- Nice to meet you, too! DL:addNode() DL:createNPCNode(4, -2, "DL_Thea_Pity") -- Pity, I would have loved to know it. DL:addNode() end if (not DL:isConditionFulfilled("npc_thea", "what_are_you_doing")) then DL:createNPCNode(10, 11, "DL_Thea_WhatAmIDoing") -- I had to deliver some goods from the farmers and then decided to stay for a while. DL:addNode() DL:createChoiceNode(11) if (not DL:isConditionFulfilled("npc_thea", "traveling_alone")) then DL:addChoice(12, "DL_Choice_VeryAlone") -- You are traveling alone? end if (not DL:isConditionFulfilled("npc_thea", "work_farmers")) then DL:addChoice(13, "DL_Choice_WorkForFarmers") -- Do you work for the farmers? end if (DL:isConditionFulfilled("npc_thea", "work_farmers") or DL:isConditionFulfilled("npc_thea", "traveling_alone")) then DL:addChoice(16, "DL_Choice_WhatIsDangerous") -- What is dangerous out here, then? end DL:addNode() DL:createNPCNode(12, 11, "DL_Thea_VeryAlone") -- Yes, I always travel on my own. But it has become dangerous lately outside of the city walls of Gandria. I'd rather take someone with me in the future. DL:addConditionProgress("npc_thea", "traveling_alone"); DL:gotoNode(11) DL:addNode() DL:createNPCNode(13, 11, "DL_Thea_WorkForFarmers") -- Yes, I'm a maid at Ivo's farm. But I'd rather find work in the city of Gandria. It's safe there, at least. DL:addConditionProgress("npc_thea", "work_farmers"); DL:changeQuestState("theas_dream","started") DL:gotoNode(11) DL:addNode() DL:createNPCNode(16, 17, "DL_Thea_Beast") -- There is a beast lurking around, and it must be pretty hungry, as most of our sheeps are gone. DL:addNode() DL:createNPCNode(17, 18, "DL_Thea_Beast2") -- Nobody has really seen it so far but I swear, I've seen a huge shadow disappear into the North last night. DL:addNode() DL:createNPCNode(18, -2, "DL_Thea_Beast3") -- And in the morning, another sheep was missing. if (not DL:isQuestState("monster_problem", "started")) then DL:changeQuestState("monster_problem","started") end DL:addQuestDescription("monster_problem", 1) DL:addConditionProgress("npc_thea", "what_are_you_doing") DL:addNode() end if (not DL:isConditionFulfilled("npc_thea", "mages")) then DL:createNPCNode(30, 31, "DL_Thea_Mages") -- Well, most of them are quite reasonable people. They lead our kingdom, at least. DL:addConditionProgress("npc_thea", "mages") DL:addNode() DL:createNPCNode(31, -2, "DL_Thea_Mages2") -- And I really think that we own them much - the farmer Ivo told me that in the past, there were even mages that controlled the weather to help farmers like him. DL:addNode() end if (not DL:isConditionFulfilled("npc_thea", "gandria") and DL:isConditionFulfilled("npc_thea", "what_are_you_doing")) then DL:createNPCNode(40, -1, "DL_Thea_Gandria") -- It's the capital city of our kingdom. Where the king resides - and all the important people, of course. Ah, I wish I could live there! DL:addConditionProgress("npc_thea", "gandria") DL:addNode() end if (DL:isQuestState("theas_dream", "started") and DL:isQuestDescriptionUnlocked("theas_dream", 1)) then DL:createCendricNode(50, 51, "DL_Cendric_Syrah") -- The alchemist Syrah would take you as an apprentice. DL:addNode() DL:createNPCNode(51, 52, "DL_Thea_Syrah") -- Oh, really? I always wanted to work with herbs and potions. Thank you so much! DL:addNode() DL:createNPCNode(52, 53, "DL_Thea_Syrah2") -- I'll tell Ivo and then travel to Gandria as fast as possible. DL:addNode() DL:createNPCNode(53, -2, "DL_Thea_Syrah3") -- Don't forget to visit me when I'm there! DL:addQuestDescription("theas_dream", 2) DL:changeQuestState("theas_dream", "completed") DL:addNode() end DL:setRoot(0) end
-- The queue for the rendered icons. renderdIcons = renderdIcons or {} -- To make making inventory variant, This must be followed up. function renderNewIcon(panel, itemTable) -- re-render icons if ((itemTable.iconCam and !renderdIcons[string.lower(itemTable.model)]) or itemTable.forceRender) then local iconCam = itemTable.iconCam iconCam = { cam_pos = iconCam.pos, cam_ang = iconCam.ang, cam_fov = iconCam.fov, } renderdIcons[string.lower(itemTable.model)] = true panel.Icon:RebuildSpawnIconEx( iconCam ) end end local PANEL = {} function PANEL:Init() self:Droppable("inv") end function PANEL:PaintOver(w, h) local itemTable = nut.item.instances[self.itemID] if (self.waiting and self.waiting > CurTime()) then local wait = (self.waiting - CurTime()) / self.waitingTime surface.SetDrawColor(255, 255, 255, 100*wait) surface.DrawRect(0, 0, w, h) end if (itemTable and itemTable.paintOver) then local w, h = self:GetSize() itemTable.paintOver(self, itemTable, w, h) end end function PANEL:ExtraPaint(w, h) end function PANEL:Paint(w, h) --рисуем ячейки local parent = self:GetParent() self:ExtraPaint(w, h) end function PANEL:wait(time) time = math.abs(time) or .2 self.waiting = CurTime() + time self.waitingTime = time end function PANEL:isWaiting() if (self.waiting and self.waitingTime) then return (self.waiting and self.waiting > CurTime()) end end vgui.Register("nutItemIcon", PANEL, "SpawnIcon") local CPANEL = {} function CPANEL:Init() self:Droppable("inv") end function CPANEL:PaintOver(w, h) local itemTable = nut.item.instances[self.itemID] if (self.waiting and self.waiting > CurTime()) then local wait = (self.waiting - CurTime()) / self.waitingTime surface.SetDrawColor(255, 255, 255, 100*wait) surface.DrawRect(0, 0, w, h) end if (itemTable and itemTable.paintOver) then local w, h = self:GetSize() itemTable.paintOver(self, itemTable, w, h) end end function CPANEL:ExtraPaint(w, h) end function CPANEL:Paint(w, h) --рисуем ячейки local parent = self:GetParent() surface.SetDrawColor( 205, 160, 10, 8 ) surface.DrawRect( 0, 0, w, h ) surface.SetDrawColor( 205, 100, 10, 10 ) surface.SetMaterial( Material("vgui/gradient-d") ) surface.DrawTexturedRect( 0, 0, w, h ) if self:IsHovered() then surface.SetDrawColor( 255, 255, 255, 10 ) surface.DrawRect( 0, 0, w, h ) end self:ExtraPaint(w, h) end function CPANEL:wait(time) time = math.abs(time) or .2 self.waiting = CurTime() + time self.waitingTime = time end function CPANEL:isWaiting() if (self.waiting and self.waitingTime) then return (self.waiting and self.waiting > CurTime()) end end vgui.Register("nutItemIcon_inv", CPANEL, "SpawnIcon") PANEL = {} function PANEL:Init() self:MakePopup() self:Center() self:ShowCloseButton(false) self:SetDraggable(true) self:SetTitle("") self.panels = {} end function PANEL:OnRemove() if (self.childPanels) then for k, v in ipairs(self.childPanels) do if (v != self) then v:Remove() end end end end function PANEL:viewOnly() self.viewOnly = true for id, icon in pairs(self.panels) do icon.OnMousePressed = nil icon.OnMouseReleased = nil icon.doRightClick = nil end end function PANEL:setInventory(inventory) if (inventory.slots) then if (IsValid(nut.gui.inv1) and nut.gui.inv1.childPanels and inventory != LocalPlayer():getChar():getInv()) then table.insert(nut.gui.inv1.childPanels, self) end self.invID = inventory:getID() self:SetSize(ScrW()*0.05, ScrH()*0.05) self:setGridSize(inventory:getSize()) for x, items in pairs(inventory.slots) do for y, data in pairs(items) do if (!data.id) then continue end local item = nut.item.instances[data.id] if (item and !IsValid(self.panels[item.id])) then local icon = self:addIcon(item.model or "models/props_junk/popcan01a.mdl", x, y, item.width, item.height) if (IsValid(icon)) then local newTooltip = hook.Run("OverrideItemTooltip", self, data, item) if (newTooltip) then icon:SetToolTip(newTooltip) else icon:SetToolTip( Format(nut.config.itemFormat, L(item.name), item:getDesc() or "") ) end icon.itemID = item.id self.panels[item.id] = icon end end end end end self:Center() end function PANEL:setGridSize(w, h) self.gridW = w self.gridH = h --self:SetSize(w * ScrW() * 0.032 + ScrW() * 0.05, h * ScrH() * 0.053 + ScrH() * 0.28) --self:SetSize(w * 64 + 8, h * 64 + 31) self:SetSize(w * ScrW() * 0.032 + ScrW() * 0.05, h * ScrH() * 0.053 + ScrH() * 0.205) self:buildSlots() end function PANEL:buildSlots() self.slots = self.slots or {} local function PaintSlot(slot, w, h) surface.SetDrawColor(0, 0, 0, 250) surface.DrawOutlinedRect(0, 0, w, h) surface.SetDrawColor(40, 40, 45, 240) surface.DrawRect(0, 0, w, h) surface.SetDrawColor( 0, 0, 0, 255 ) surface.SetMaterial( Material("vgui/gradient-d") ) surface.DrawTexturedRect( 0, -ScrH()*0.05, w, ScrH()*0.18 ) surface.SetDrawColor( 55, 55, 65, 90 ) surface.DrawOutlinedRect( 0, 0, w, h ) surface.SetDrawColor( 55, 55, 65, 90 ) surface.DrawOutlinedRect( 0, 0, w, 0 ) end for k, v in ipairs(self.slots) do for k2, v2 in ipairs(v) do v2:Remove() end end self.slots = {} for x = 1, self.gridW do self.slots[x] = {} for y = 1, self.gridH do local slot = self:Add("DPanel") slot:SetZPos(-999) --slot:SetZPos(-999) похуй slot.gridX = x slot.gridY = y slot:SetPos((x - 1) * ScrW() * 0.03392 + ScrW() * 0.017, (y - 1) * ScrH() * 0.056 + ScrH() * 0.085) --slot:SetPos((x - 1) * 64 + 4, (y - 1) * 64 + 27) slot:SetSize(ScrW() * 0.03392, ScrH() * 0.056) --slot:SetSize(64, 64) slot.Paint = PaintSlot self.slots[x][y] = slot end end end --[[slot:SetPos((x - 1) * 64 + 4, (y - 1) * 64 + 27) x - 1 - смещение инвентаря влево y - 1 - смещение инвентаря вверх + 4 - отступ по горизонтали от гамки + 27 - отступ сверху 64 и 64 - размеры ячеек в пикселях, должлы быть равны размерам из SetSize ]] local activePanels = {} function PANEL:Paint(w, h) --рисуем панель инвентаря nut.util.drawBlur(self, 10) surface.SetDrawColor(Color( 20, 20, 20, 220)) surface.DrawRect( 0, 0, w, h ) surface.DrawOutlinedRect(0, 0, w, h) surface.SetDrawColor(0, 0, 14, 150) surface.DrawRect(ScrW() * 0, ScrH() * 0, ScrW() * 0.41, ScrH() * 0.033) surface.SetDrawColor(Color( 30, 30, 30, 90)) surface.DrawOutlinedRect(ScrW() * 0, ScrH() * 0, ScrW() * 0.41, ScrH() * 0.033) --шапка draw.DrawText("Инвентарь", "Roh20", ScrW() * 0.005, ScrH() * 0.003, Color(255, 255, 255, 210), TEXT_ALIGN_LEFT ) surface.SetDrawColor(Color( 138, 149, 151, 60)) surface.DrawLine(ScrW() * 0.018, ScrH() * 0.0325, ScrW() * 0.29, ScrH() * 0.0325) surface.SetDrawColor(Color( 0, 33, 55, 210)) surface.DrawRect(ScrW() * 0.017, ScrH() * 0.059, ScrW() * 0.2715, ScrH() * 0.027) --верхняя панель крафта surface.SetDrawColor( Color(80, 80, 80, 255) ) surface.DrawRect( ScrW() * 0.017, ScrH() * 0.059, math.Clamp(((ScrW()*0.27)*(LocalPlayer():GetWeight()/(nut.config.get("maxWeight") + LocalPlayer():GetWeightAddition()))), 0, ScrW() * 0.2715), ScrH() * 0.027 ) surface.SetDrawColor( Color(125, 105, 0, 255) ) surface.SetMaterial( Material("lgh/circle_gradient.png") ) surface.DrawTexturedRectUV( ScrW() * 0.13, ScrH() * 0.061, ScrW() * 0.05, ScrH() * 0.04, 1, 0.9, 0, 0.3 ) draw.DrawText(LocalPlayer():GetWeight() .."/".. (nut.config.get("maxWeight") + LocalPlayer():GetWeightAddition()), "Roh10", ScrW() * 0.15, ScrH() * 0.064, Color(255, 255, 255, 210), TEXT_ALIGN_CENTER ) draw.DrawText("Рюкзак", "Roh20", ScrW() * 0.02, ScrH() * 0.06, Color(255, 255, 255, 210), TEXT_ALIGN_LEFT ) surface.SetDrawColor(Color( 0, 0, 0, 255)) surface.DrawOutlinedRect(ScrW() * 0.0165, ScrH() * 0.059, ScrW() * 0.273, ScrH() * 0.53) --обводка модели игрока surface.SetDrawColor( Color(125, 105, 0, 40) ) surface.SetMaterial( Material("lgh/circle_gradient.png") ) surface.DrawTexturedRectUV( -ScrW() * 0.01, ScrH() * 0.657, ScrW() * 0.35, ScrH() * 0.032, 1, 0.9, 0, 0.3 ) end function PANEL:PaintOver(w, h) --рисуем поверх local item = nut.item.held if (IsValid(item)) then local mouseX, mouseY = self:LocalCursorPos() local dropX, dropY = math.ceil((mouseX - ScrW() * 0.017 - (item.gridW - 1) * 32) / 51), math.ceil((mouseY - ScrH() * 0.085 - (item.gridH - 1) * 32) / 51) if ((mouseX < -w*0.05 or mouseX > w*1.05) or (mouseY < h*0.05 or mouseY > h*1.05)) then activePanels[self] = nil else activePanels[self] = true end item.dropPos = item.dropPos or {} if (item.dropPos[self]) then item.dropPos[self].item = nil end for x = 0, item.gridW - 1 do for y = 0, item.gridH - 1 do local x2, y2 = dropX + x, dropY + y -- Is Drag and Drop icon is in the Frame? if (self.slots[x2] and IsValid(self.slots[x2][y2])) then local bool = self:isEmpty(x2, y2, item) surface.SetDrawColor(0, 0, 255, 10) if (x == 0 and y == 0) then item.dropPos[self] = {x = (x2 - 1)*ScrW() * 0.03392 + ScrW() * 0.017, y = (y2 - 1)*ScrH() * 0.056 + ScrH() * 0.085, x2 = x2, y2 = y2} --[[{x = (x2 - 1)*64 + 4, y = (y2 - 1)*64 + 27, x2 = x2, y2 = y2} Сетка перетаскивания, должна быть равна обычной сетке x2 - 1 - смещение инвентаря влево y2 - 1 - смещение инвентаря вверх + 4 - отступ по горизонтали от гамки + 27 - отступ сверху 64 и 64 - размеры ячеек в пикселях, должлы быть равны размерам из SetSize ]] end if (bool) then surface.SetDrawColor(0, 255, 0, 10) else surface.SetDrawColor(255, 255, 0, 10) if (self.slots[x2] and self.slots[x2][y2] and item.dropPos[self]) then item.dropPos[self].item = self.slots[x2][y2].item end end surface.DrawRect((x2 - 1)*ScrW() * 0.03392 + ScrW() * 0.017, (y2 - 1)*ScrH() * 0.056 + ScrH() * 0.085, ScrW() * 0.03392, ScrH() * 0.056) --[[{x = (x2 - 1)*64 + 4, y = (y2 - 1)*64 + 27, x2 = x2, y2 = y2} Рисуем сетку перетаскивания, должна быть равна обычной сетке x2 - 1 - смещение инвентаря влево y2 - 1 - смещение инвентаря вверх + 4 - отступ по горизонтали от гамки + 27 - отступ сверху 64 и 64 - размеры ячеек в пикселях, должлы быть равны размерам из SetSize ]] else if (item.dropPos) then item.dropPos[self] = nil end end end end end end function PANEL:isEmpty(x, y, this) return (!IsValid(self.slots[x][y].item) or self.slots[x][y].item == this) end function PANEL:onTransfer(oldX, oldY, x, y, oldInventory, noSend) local inventory = nut.item.inventories[oldInventory.invID] local inventory2 = nut.item.inventories[self.invID] local item if (inventory) then item = inventory:getItemAt(oldX, oldY) if (!item) then return false end if (hook.Run("CanItemBeTransfered", item, nut.item.inventories[oldInventory.invID], nut.item.inventories[self.invID]) == false) then return false, "notAllowed" end if (item.onCanBeTransfered and item:onCanBeTransfered(inventory, inventory != inventory2 and inventory2 or nil) == false) then return false end end if (!noSend) then if (self != oldInventory) then netstream.Start("invMv", oldX, oldY, x, y, oldInventory.invID, self.invID) else netstream.Start("invMv", oldX, oldY, x, y, oldInventory.invID) end end if (inventory) then inventory.slots[oldX][oldY] = nil end if (item and inventory2) then inventory2.slots[x] = inventory2.slots[x] or {} inventory2.slots[x][y] = item end end function PANEL:addIcon(model, x, y, w, h, skin) w = w or 1 h = h or 1 if (self.slots[x] and self.slots[x][y]) then local panel = self:Add("nutItemIcon_inv") panel:SetSize(w * ScrW() * 0.03392, h * ScrH() * 0.056) panel:SetZPos(999) panel:InvalidateLayout(true) panel:SetModel(model, skin) panel:SetPos(self.slots[x][y]:GetPos()) panel.gridX = x panel.gridY = y panel.gridW = w panel.gridH = h --[[panel.Paint = function(self, w, h) surface.SetDrawColor( 205, 160, 10, 8 ) surface.DrawRect( 0, 0, w, h ) if self:IsHovered() then surface.SetDrawColor( 255, 255, 255, 30 ) surface.DrawRect( 0, 0, w, h ) end end]] --[[panel:SetSize(w * 64, h * 64) Размеры иконок, должны быть равна обычной сетке 64 и 64 - размеры иконок в пикселях, должлы быть равны размерам из SetSize ]] local inventory = nut.item.inventories[self.invID] if (!inventory) then return end panel.inv = inventory local itemTable = inventory:getItemAt(panel.gridX, panel.gridY) panel.itemTable = itemTable if (self.panels[itemTable:getID()]) then self.panels[itemTable:getID()]:Remove() end --if (itemTable.exRender) then panel.Icon:SetVisible(false) panel.ExtraPaint = function(self, x, y) local exIcon = ikon:getIcon(itemTable.uniqueID) if (exIcon) then surface.SetMaterial(exIcon) surface.SetDrawColor(color_white) surface.DrawTexturedRect(0, 0, x, y) else ikon:renderIcon( itemTable.uniqueID, itemTable.width, itemTable.height, itemTable.model, itemTable.iconCam ) end end --else --renderNewIcon(panel, itemTable) --end panel.move = function(this, data, inventory, noSend) local oldX, oldY = this.gridX, this.gridY local oldParent = this:GetParent() if (inventory:onTransfer(oldX, oldY, data.x2, data.y2, oldParent, noSend) == false) then return end data.x = data.x or (data.x2 - 1)*ScrW() * 0.03392 + ScrW() * 0.017 data.y = data.y or (data.y2 - 1)*ScrH() * 0.056 + ScrH() * 0.085 --[[ data.x = data.x or (data.x2 - 1)*64 + 4 data.y = data.y or (data.y2 - 1)*64 + 27 64 и 64 - размеры в пикселях 4 и 27 - отступы ]] this.gridX = data.x2 this.gridY = data.y2 this.invID = inventory.invID this:SetParent(inventory) this:SetPos(data.x, data.y) if (this.slots) then for k, v in ipairs(this.slots) do if (IsValid(v) and v.item == this) then v.item = nil end end end this.slots = {} for x = 1, this.gridW do for y = 1, this.gridH do local slot = inventory.slots[this.gridX + x-1][this.gridY + y-1] slot.item = this this.slots[#this.slots + 1] = slot end end end panel.OnMousePressed = function(this, code) if (code == MOUSE_LEFT) then if (input.IsKeyDown(KEY_LCONTROL) or input.IsKeyDown(KEY_RCONTROL)) then local func = itemTable.functions if (func) then local use local comm for k, v in pairs(USABLE_FUNCS or {}) do comm = v use = func[comm] if (use and use.onCanRun) then if (use.onCanRun(itemTable) == false) then continue end end if (use) then break end end if (!use) then return end if (use.onCanRun) then if (use.onCanRun(itemTable) == false) then itemTable.player = nil return end end itemTable.player = LocalPlayer() local send = true if (use.onClick) then send = use.onClick(itemTable) end if (use.sound) then surface.PlaySound(use.sound) end if (send != false) then netstream.Start("invAct", comm, itemTable.id, self.invID) end itemTable.player = nil end else this:DragMousePress(code) this:MouseCapture(true) nut.item.held = this end elseif (code == MOUSE_RIGHT and this.doRightClick) then this:doRightClick() end end panel.OnMouseReleased = function(this, code) if (code == MOUSE_LEFT and nut.item.held == this) then local data = this.dropPos this:DragMouseRelease(code) this:MouseCapture(false) this:SetZPos(99) nut.item.held = nil if (table.Count(activePanels) == 0) then local item = this.itemTable local inv = this.inv if (item and inv) then netstream.Start("invAct", "drop", item.id, inv:getID(), item.id) end return false end activePanels = {} if (data) then local inventory = table.GetFirstKey(data) if (IsValid(inventory)) then data = data[inventory] if (IsValid(data.item)) then inventory = panel.inv if (inventory) then local targetItem = data.item.itemTable if (targetItem) then -- to make sure... if (targetItem.id == itemTable.id) then return end if (itemTable.functions) then local combine = itemTable.functions.combine -- does the item has the combine feature? if (combine) then itemTable.player = LocalPlayer() -- canRun == can item combine into? if (combine.onCanRun and (combine.onCanRun(itemTable, targetItem.id) != false)) then netstream.Start("invAct", "combine", itemTable.id, inventory:getID(), targetItem.id) end itemTable.player = nil end end end end else local oldX, oldY = this.gridX, this.gridY if (oldX != data.x2 or oldY != data.y2 or inventory != self) then this:move(data, inventory) end end end end end end panel.doRightClick = function(this) if (itemTable) then itemTable.player = LocalPlayer() local menu = DermaMenu() local override = hook.Run("OnCreateItemInteractionMenu", panel, menu, itemTable) if (override == true) then if (menu.Remove) then menu:Remove() end return end for k, v in SortedPairs(itemTable.functions) do if (k == "combine") then continue end -- we don't need combine on the menu mate. if (v.onCanRun) then if (v.onCanRun(itemTable) == false) then itemTable.player = nil continue end end -- is Multi-Option Function if (v.isMulti) then local subMenu, subMenuOption = menu:AddSubMenu(L(v.name or k), function() itemTable.player = LocalPlayer() local send = true if (v.onClick) then send = v.onClick(itemTable) end if (v.sound) then surface.PlaySound(v.sound) end if (send != false) then netstream.Start("invAct", k, itemTable.id, self.invID) end itemTable.player = nil end) subMenuOption:SetImage(v.icon or "icon16/brick.png") if (v.multiOptions) then local options = isfunction(v.multiOptions) and v.multiOptions(itemTable, LocalPlayer()) or v.multiOptions for _, sub in pairs(options) do subMenu:AddOption(L(sub.name or "subOption"), function() itemTable.player = LocalPlayer() local send = true if (v.onClick) then send = v.onClick(itemTable) end if (v.sound) then surface.PlaySound(v.sound) end if (send != false) then netstream.Start("invAct", k, itemTable.id, self.invID, sub.data) end itemTable.player = nil end) end end else menu:AddOption(L(v.name or k), function() itemTable.player = LocalPlayer() local send = true if (v.onClick) then send = v.onClick(itemTable) end if (v.sound) then surface.PlaySound(v.sound) end if (send != false) then netstream.Start("invAct", k, itemTable.id, self.invID) end itemTable.player = nil end):SetImage(v.icon or "icon16/brick.png") end end menu:Open() itemTable.player = nil end end panel.slots = {} for i = 0, w - 1 do for i2 = 0, h - 1 do local slot = self.slots[x + i] and self.slots[x + i][y + i2] if (IsValid(slot)) then slot.item = panel panel.slots[#panel.slots + 1] = slot else for k, v in ipairs(panel.slots) do v.item = nil end panel:Remove() return end end end return panel end end vgui.Register("nutInventory", PANEL, "DFrame") hook.Add("PostRenderVGUI", "nutInvHelper", function() local pnl = nut.gui.inv1 hook.Run("PostDrawInventory", pnl) end)
inspect = require("app.libs.inspect") require("app.config.error_code") require "app.libs.log_api" local app = require("app.server") app:run()
local hit_effect = { red = 0, shift_radius = 0, static_str = 0 } Player = Entity("Player",{ hitbox=true, reaction="cross", animations={ "robot_stand", "robot_walk", "robot_hit" }, align="center", --z=5, collision=function(self, i) if i.other.tag == "Ball" and i.other:is_colliding(self) then -- change frame self.is_hit = true -- visual effect hit_effect.red = 40 hit_effect.shift_radius = 10 hit_effect.static_str = 10 if self.hit_effect_tween then self.hit_effect_tween:destroy() end self.hit_effect_tween = Tween(1, hit_effect, { red=0, shift_radius=0, static_str=0 }) -- audio effect Audio.play('hit') end end, update = function(self, dt) local d = 150 self.hspeed = 0 self.vspeed = 0 -- basic movement Joystick.use(1) if Input.pressed('left') then self.hspeed = self.hspeed - d end if Input.pressed('right') then self.hspeed = self.hspeed + d end if Input.pressed('up') then self.vspeed = self.vspeed - d end if Input.pressed('down') then self.vspeed = self.vspeed + d end -- animation control if Input.pressed('left','right','up','down') then self.animation = 'robot_walk' else self.animation = 'robot_stand' end if self.is_hit then self.animation = 'robot_hit' self.is_hit = false end -- mirror player image if Input.pressed('left') then self.scalex = -1 end if Input.pressed('right') then self.scalex = 1 end Joystick.use() Game.effect:set("chroma shift", "radius", hit_effect.shift_radius) Game.effect:set("static", "strength", {hit_effect.static_str, 0}) end, draw = function(self, d) d() Draw{ { 'reset' }, -- prevent the square from drawing relative to the player { 'color', 'red', hit_effect.red/100 }, { 'rect', 'fill', 0, 0, Game.width, Game.height } } end })
local _, ns = ... local B, C, L, DB, P = unpack(ns) local M = P:RegisterModule("Misc") local strmatch, format, tonumber, select = string.match, string.format, tonumber, select M.MiscList = {} function M:RegisterMisc(name, func) if not M.MiscList[name] then M.MiscList[name] = func end end function M:OnLogin() for name, func in next, M.MiscList do if name and type(func) == "function" then local _, catch = pcall(func) P:ThrowError(catch, format("%s Misc", name)) end end end
-- module Data.Semigroup local exports = {} exports.concatString = function (s1) return function (s2) return s1 .. s2 end end exports.concatArray = function (xs) return function (ys) local result = copyTable(xs) for i=1, #ys do result[#result+1] = ys[i] end return result end end return exports
return { fadeOut = 1.5, mode = 2, id = "TIANCHENGHUODONG17", once = true, fadeType = 1, continueBgm = true, fadein = 1.5, scripts = { { expression = 2, side = 0, nameColor = "#a9f548", actor = 305070, dir = -1, stopbgm = true, say = "{namecode:161},你究竟在想什么!现在来参加这种演习你…", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 304050, side = 1, nameColor = "#ff0000", dir = 1, say = "{namecode:140}已经都告诉你了吧?我身体的状况…留给我的时间已经不多了。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 2, nameColor = "#ff0000", side = 1, actor = 304050, dir = 1, say = "这个世界将会改变,大舰巨炮的时代将会逐步走向终结吧…", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 2, nameColor = "#ff0000", side = 1, actor = 304050, dir = 1, say = "未来…是属于航空母舰的时代。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 304050, side = 1, nameColor = "#ff0000", dir = 1, say = "…也许你可能会笑,不过我真的很想再以战列巡洋舰的身份尽情地奏响主炮!…哪怕只有最后一次也好。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 2, nameColor = "#ff0000", side = 1, actor = 304050, dir = 1, say = "因此,我选择了前来参加这场演习。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 2, nameColor = "#a9f548", side = 0, actor = 305070, dir = -1, say = "……", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 2, nameColor = "#ff0000", side = 1, actor = 304050, dir = 1, say = "来吧,{namecode:92},你不是视我为“一生的对手”么,你可还一次都没有赢过我哦?", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 2, nameColor = "#ff0000", side = 1, actor = 304050, dir = 1, say = "如果你敢放水,我一生都不会原谅你的。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 3, nameColor = "#a9f548", side = 0, actor = 305070, dir = -1, say = "……我明白了。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 3, nameColor = "#a9f548", side = 0, actor = 305070, dir = -1, say = "能拥有这像你这样直到最后都在贯彻理念的对手,我可真是幸运呢。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 305070, side = 0, nameColor = "#a9f548", dir = -1, say = "<size=52.5>{namecode:92}级战列舰首舰——{namecode:92}号!</size>", painting = { alpha = 0.3, time = 1 } }, { expression = 2, nameColor = "#ff0000", side = 1, actor = 304050, dir = 1, say = "<size=52.5>{namecode:161}级战列巡洋舰——{namecode:161}号!</size>", painting = { alpha = 0.3, time = 1 } }, { actor = 305070, nameColor = "#a9f548", side = 0, hideOther = true, dir = -1, actorName = "{namecode:92}&{namecode:161}", say = "<size=60>参上!!!</size>", bgm = "theme", subActors = { { dir = -1, actor = 304050, pos = { x = -1030.5 } } } } } }
local M = {} M.NONE = "none" M.ERROR = "error" M.USI = "usi" M.USIOK = "usiok" M.ISREADY = "isready" M.READYOK = "readyok" M.OPTION = "option" M.SETOPTION = "setoption" M.USINEWGAME = "usinewgame" M.POSITION = "position" M.GO = "go" M.STOP = "stop" M.PONDERHIT = "ponderhit" M.QUIT = "quit" M.GAMEOVER = "gameover" M.ID = "id" M.BESTMOVE = "bestmove" M.INFO = "info" M.CHECKMATE = "checkmate" return M
salt = bcrypt.gen_salt() hash = bcrypt.hashpw("my-password", salt) assert(bcrypt.hashpw("my-password", hash) == hash)
local vnet = GLib.vnet GLib.Transfers = {} GLib.Transfers.InboundTransfers = {} GLib.Transfers.OutboundTransfers = {} GLib.Transfers.Requests = {} GLib.Transfers.Handlers = {} GLib.Transfers.InitialPacketHandlers = {} GLib.Transfers.RequestHandlers = {} GLib.Transfers.NextTransferId = 1 if SERVER then util.AddNetworkString ("glib_cancel_transfer") util.AddNetworkString ("glib_transfer") util.AddNetworkString ("glib_transfer_request") util.AddNetworkString ("glib_transfer_request_response") end local function EndPacket (packet, userId) if CLIENT then packet:AddServer() packet:Send() elseif SERVER then if userId == GLib.GetEveryoneId () then packet:Broadcast() else for _, v in ipairs (player.GetAll ()) do if GLib.GetPlayerId (v) == userId then packet:AddTargets (v) packet:Send() return end end end end end local function EndNetMessage (userId) if CLIENT then net.SendToServer () elseif SERVER then if userId == GLib.GetEveryoneId () then net.Broadcast () else for _, v in ipairs (player.GetAll ()) do if GLib.GetPlayerId (v) == userId then net.Send (v) return end end GLib.Error ("GLib.Transfers : Unknown userId " .. userId .. "!") end end end net.Receive ("glib_cancel_transfer", function (_, ply) local userId = SERVER and GLib.GetPlayerId (ply) or "Server" local transferId = net.ReadUInt (32) local outboundTransfer = GLib.Transfers.OutboundTransfers [userId .. "/" .. transferId] if not outboundTransfer then return end -- print ("GLib.Transfers : Outbound transfer " .. outboundTransfer:GetDisplayId () .. " cancelled.") GLib.Transfers.OutboundTransfers [userId .. "/" .. transferId] = nil end ) vnet.Watch("glib_transfer", function(packet) local userId = isbool(packet.Source) and "Server" or GLib.GetPlayerId (packet.Source) local messageType = packet:Int () local transferId = packet:Int () local inboundTransfer = nil if messageType == 1 then -- New inbound transfer local channelName = packet:String () if not GLib.Transfers.Handlers [channelName] then -- Unknown channel, do not want GLib.Transfers.CancelUnknownTransfer (userId, transferId) return end if GLib.Transfers.InboundTransfers [userId .. "/" .. transferId] and GLib.Transfers.InboundTransfers [userId .. "/" .. transferId]:GetRequestId () then -- Transfer was previously requested inboundTransfer = GLib.Transfers.InboundTransfers [userId .. "/" .. transferId] else -- New transfer inboundTransfer = GLib.Transfers.InboundTransfer (transferId) inboundTransfer:SetChannelName (channelName) inboundTransfer:SetSourceId (userId) GLib.Transfers.InboundTransfers [userId .. "/" .. transferId] = inboundTransfer end -- Deserialize first chunk local inBuffer = GLib.StringInBuffer (packet:String()) inboundTransfer:DeserializeFirstChunk (inBuffer) -- Call initial packet handler local initialPacketHandler = GLib.Transfers.InitialPacketHandlers [channelName] if initialPacketHandler then local continueTransfer = initialPacketHandler (userId, inboundTransfer:GetFirstChunk ()) if continueTransfer == false then GLib.Transfers.CancelInboundTransfer (userId, transferId) return end end elseif messageType == 2 then -- Continuation of a transfer inboundTransfer = GLib.Transfers.InboundTransfers [userId .. "/" .. transferId] if not inboundTransfer then -- Unknown transfer, do not want GLib.Transfers.CancelUnknownInboundTransfer (userId, transferId) return end -- Deserialize chunk local inBuffer = GLib.StringInBuffer (packet:String()) inboundTransfer:DeserializeNextChunk (inBuffer) end if inboundTransfer:IsFinished () then -- Transfer finished GLib.Transfers.InboundTransfers [userId .. "/" .. inboundTransfer:GetId ()] = nil -- Call handlers inboundTransfer:DispatchEvent ("Finished") local handler = GLib.Transfers.Handlers [inboundTransfer:GetChannelName ()] if handler then handler (inboundTransfer:GetSourceId (), inboundTransfer:GetData ()) end end end) local function HandleTransferRequest (userId, channelName, requestId, data) local requestHandler = GLib.Transfers.RequestHandlers [channelName] local requestAccepted, responseData = false, "" if requestHandler then requestAccepted, responseData = requestHandler (userId, data) responseData = responseData or "" responseData = tostring (responseData) end local packet = vnet.CreatePacket("glib_transfer_request_response") packet:Int(requestId) if requestAccepted then local outboundTransfer = GLib.Transfers.Send (userId, channelName, responseData) packet:Int (1) packet:Int (outboundTransfer:GetId ()) else packet:Int (0) packet:String (responseData) end local ply for k, v in pairs(player.GetAll()) do if GLib.GetPlayerId (v) == userId then ply = v break end end packet:AddTargets(ply) packet:Send() end vnet.Watch("glib_transfer_request", function(packet) local userId = isbool(packet.Source) and "Server" or GLib.GetPlayerId (packet.Source) local channelName = packet:String() local requestId = packet:Int() local data = packet:String() HandleTransferRequest (userId, channelName, requestId, data) end ) vnet.Watch("glib_transfer_request_response", function(packet) local userId = isbool(packet.Source) and "Server" or GLib.GetPlayerId (packet.Source) local requestId = packet:Int() local requestAccepted = packet:Int() == 1 local transferId = nil local rejectionData = nil if requestAccepted then transferId = packet:Int() else rejectionData = packet:String() end local inboundTransfer = GLib.Transfers.Requests [userId .. "/" .. requestId] GLib.Transfers.Requests [userId .. "/" .. requestId] = nil if not inboundTransfer then -- Cancel the transfer, we have no knowledge of this place. if requestAccepted then GLib.Transfers.CancelUnknownInboundTransfer (userId, transferId) end return end if requestAccepted then inboundTransfer:SetId (transferId) GLib.Transfers.InboundTransfers [userId .. "/" .. inboundTransfer:GetId ()] = inboundTransfer inboundTransfer:DispatchEvent ("RequestAccepted", inboundTransfer:GetId ()) else inboundTransfer:DispatchEvent ("RequestRejected", rejectionData) end end ) timer.Create ("GLib.Transfers", 1, 0, function () for _, inboundTransfer in pairs (GLib.Transfers.InboundTransfers) do if not inboundTransfer:IsSourceValid () then GLib.Transfers.InboundTransfers [inboundTransfer:GetSourceId () .. "/" .. inboundTransfer:GetId ()] = nil end end for _, outboundTransfer in pairs (GLib.Transfers.OutboundTransfers) do if not outboundTransfer:IsDestinationValid () then GLib.Transfers.OutboundTransfers [outboundTransfer:GetDestinationId () .. "/" .. outboundTransfer:GetId ()] = nil else local outBuffer = GLib.StringOutBuffer () local packet = vnet.CreatePacket("glib_transfer") if not outboundTransfer:IsStarted () then packet:Int(1) packet:Int(outboundTransfer:GetId ()) packet:String (outboundTransfer:GetChannelName ()) outboundTransfer:SerializeFirstChunk (outBuffer) else packet:Int(2) packet:Int (outboundTransfer:GetId ()) outboundTransfer:SerializeNextChunk (outBuffer) end packet:String (outBuffer:GetString ()) EndPacket(packet, outboundTransfer:GetDestinationId ()) if outboundTransfer:IsFinished () then GLib.Transfers.OutboundTransfers [outboundTransfer:GetDestinationId () .. "/" .. outboundTransfer:GetId ()] = nil end end end end ) function GLib.Transfers.CancelInboundTransfer (userId, transferId) if not GLib.Transfers.InboundTransfers [userId .. "/" .. transferId] then GLib.Error ("GLib.Transferse.CancelInboundTransfer : This function should not be used for unknown inbound transfers.") end GLib.Transfers.InboundTransfers [userId .. "/" .. transferId] = nil GLib.Transfers.CancelUnknownInboundTransfer (userId, transferId) end function GLib.Transfers.CancelUnknownInboundTransfer (userId, transferId) net.Start ("glib_cancel_transfer") net.WriteUInt (transferId, 32) EndNetMessage (userId) end function GLib.Transfers.Send (userId, channelName, data) local outboundTransfer = GLib.Transfers.OutboundTransfer (GLib.Transfers.NextTransferId, data) GLib.Transfers.NextTransferId = GLib.Transfers.NextTransferId + 1 GLib.Transfers.OutboundTransfers [userId .. "/" .. outboundTransfer:GetId ()] = outboundTransfer outboundTransfer:SetChannelName (channelName) outboundTransfer:SetDestinationId (userId) return outboundTransfer end function GLib.Transfers.Request (userId, channelName, data) local inboundTransfer = GLib.Transfers.InboundTransfer () inboundTransfer:SetRequestId (GLib.Transfers.NextTransferId) GLib.Transfers.NextTransferId = GLib.Transfers.NextTransferId + 1 GLib.Transfers.Requests [userId .. "/" .. inboundTransfer:GetRequestId ()] = inboundTransfer inboundTransfer:SetChannelName (channelName) inboundTransfer:SetSourceId (userId) if util.NetworkStringToID ("glib_transfer_request") == 0 then GLib.CallDelayed ( function () GLib.Transfers.Requests [userId .. "/" .. inboundTransfer:GetRequestId ()] = nil inboundTransfer:DispatchEvent ("RequestRejected", "") end ) else data = data or "" local packet = vnet.CreatePacket("glib_transfer_request") packet:String(channelName) packet:Int(inboundTransfer:GetRequestId()) packet:String(data) EndPacket(packet, userId) end return inboundTransfer end function GLib.Transfers.RegisterHandler (channelName, handler) GLib.Transfers.Handlers [channelName] = handler end function GLib.Transfers.RegisterInitialPacketHandler (channelName, handler) GLib.Transfers.InitialPacketHandlers [channelName] = handler end function GLib.Transfers.RegisterRequestHandler (channelName, handler) GLib.Transfers.RequestHandlers [channelName] = handler end
SCONFIG = L2TConfig.GetConfig(); moveDistance = 30; ShowToClient("Q3", "Quest Searching for the Mysterious Power - Started"); LearnAllSkills(); MoveTo(-111432, 255835, -1443, moveDistance); MoveTo(-111399, 255866, -1443, moveDistance); TargetNpc("Shannon", 32974); Talk(); ClickAndWait("talk_select", "Quest"); ClickAndWait("quest_choice?choice=3&option=1", "[532201]"); ClickAndWait("menu_select?ask=10322&reply=1", "\"And why would you do that?\""); ClickAndWait("quest_accept?quest_id=10322", "\"I just want to get stronger.\""); ClearTargets(); MoveTo(-111399, 255866, -1443, moveDistance); MoveTo(-111778, 255334, -1441, moveDistance); MoveTo(-111961, 255174, -1441, moveDistance); MoveTo(-111965, 255143, -1440, moveDistance); MoveTo(-112138, 254578, -1484, moveDistance); MoveTo(-111701, 254069, -1673, moveDistance); MoveTo(-110783, 253616, -1788, moveDistance); MoveTo(-110759, 253484, -1739, moveDistance); TargetNpc("Evain", 33464); Talk(); ClickAndWait("talk_select", "Quest"); ClickAndWait("quest_choice?choice=0&option=1", "[532202]"); ClearTargets(); MoveTo(-110759, 253484, -1739, moveDistance); MoveTo(-110759, 253632, -1789, moveDistance); SCONFIG.melee.me.enabled = true; SCONFIG.melee.me.attackRange = 50; SCONFIG.targeting.option = L2TConfig.ETargetingType.TT_RANGE_FROM_POINT; SCONFIG.targeting.centerPoint.X = -111271; SCONFIG.targeting.centerPoint.Y = 253574; SCONFIG.targeting.centerPoint.Z = -1753; SCONFIG.targeting.rangeType = L2TConfig.ETargetingRangeType.TRT_SQUERE; SCONFIG.targeting.range = 700; SetPause(false); repeat Sleep(1000); until GetQuestManager():GetQuestProgress(10322) == 3; -- Quest state changed, ID: 10322, STATE: 3 SetPause(true); ClearTargets(); MoveTo(-111446, 253630, -1741, moveDistance); MoveTo(-110891, 253655, -1780, moveDistance); MoveTo(-110783, 253609, -1788, moveDistance); MoveTo(-110761, 253483, -1739, moveDistance); TargetNpc("Evain", 33464); Talk(); ClickAndWait("talk_select", "Quest"); ClickAndWait("quest_choice?choice=2&option=1", "[532202]"); ClearTargets(); MoveTo(-110761, 253483, -1739, moveDistance); MoveTo(-110725, 253646, -1791, moveDistance); TargetNpc("Newbie Helper", 32981); Talk(); ClickAndWait("talk_select", "Quest"); ClickAndWait("menu_select?ask=10322&reply=1", "\"I'll do anything to get stronger!\""); ClearTargets(); MoveTo(-110725, 253646, -1791, moveDistance); MoveTo(-110934, 253648, -1777, moveDistance); SetPause(false); repeat Sleep(1000); until GetQuestManager():GetQuestProgress(10322) == 6; -- Quest state changed, ID: 10322, STATE: 6 SetPause(true); MoveTo(-111433, 253511, -1754, moveDistance); MoveTo(-111393, 253521, -1755, moveDistance); MoveTo(-111273, 253609, -1753, moveDistance); MoveTo(-110842, 253654, -1784, moveDistance); MoveTo(-110752, 253524, -1739, moveDistance); MoveTo(-110755, 253477, -1739, moveDistance); TargetNpc("Evain", 33464); Talk(); ClickAndWait("talk_select", "Quest"); ClickAndWait("quest_choice?choice=5&option=1", "[532202]"); ClearTargets(); MoveTo(-110755, 253477, -1739, moveDistance); Sleep(500); UseItem(7818); -- Apprentice Adventurer's Knife Sleep(500); ShowToClient("Q3", "Quest Searching for the Mysterious Power - Finished");
local coins = 23254 function onUse(cid, item, frompos, item2, topos) if getPlayerStorageValue(cid, coins) >= 1 then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "You have "..getPlayerStorageValue(cid, coins).." cassino coins left.") return true end doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "You don't have any cassino coins. To buy coins, order at celadon's cassino.") return true end
#!/usr/bin/env tarantool local fio = require("fio") local ffi = require("ffi") local parserConst = require("sqlparserConst") local sqlgen = require("sqlgen") local hFilePath = debug.getinfo(1, "S").source hFilePath = fio.dirname(hFilePath:sub(2)) hFilePath = fio.pathjoin(hFilePath, "LuaDataTypes.h") local hFile, err = fio.open(hFilePath, "O_RDONLY") if hFile == nil then error(("Can not open file '%s': %s"):format(hFilePath, tostring(err))) end local ok, cDefs = pcall(hFile.read, hFile) hFile:close() if not ok then error(cDefs) end ffi.cdef(cDefs) ffi.cdef[[ LuaSQLParserResult* parseSql(const char* query); void finalize(LuaSQLParserResult* result); ]] local package = package.search("libsqlparser") local sqlParserLib = ffi.load(package) local getExpr local getExprArr local getJoinDefinition local getAlias local getTableRef local getGroupByDescription local getSetOperation local getOrderDescription local getWithDescription local getLimitDescription local getSelectStatement local getSQLStatement local getSQLParserResult local function getArr(cdata, count, getItem, params) if cdata == nil then return nil end count = tonumber(count) local arr = { } for i = 0, count - 1 do table.insert(arr, getItem(cdata[i], params)) end return arr end local function getStr(cdata) if cdata == nil then return nil end return ffi.string(cdata) end local function getOperatorArity(opType) if opType == nil then return nil end local OperatorType = parserConst.OperatorType if opType == OperatorType.None then return 0 end if opType == OperatorType.Between then return 3 end if opType == OperatorType.Case or opType == OperatorType.CaseListElement then return -1 end if opType >= OperatorType.Plus and opType <= OperatorType.Concat then return 2 end if opType >= OperatorType.Not and opType <= OperatorType.Exists then return 1 end return nil end getExpr = function(cdata, params) if cdata == nil then return nil end local expr = { } local exprType = parserConst.getExprTypeStr(cdata.type) expr.type = exprType if exprType == "parameter" then table.insert(params, expr) end expr.expr = getExpr(cdata.expr, params) expr.expr2 = getExpr(cdata.expr2, params) expr.exprList = getExprArr(cdata.exprList, cdata.exprListSize, params) expr.select = getSelectStatement(cdata.select, params) expr.name = getStr(cdata.name) expr.table = getStr(cdata.table) expr.alias = getStr(cdata.alias) if exprType == "literalFloat" then expr.value = tonumber(cdata.fval) elseif exprType == "literalString" then expr.value = getStr(cdata.name) elseif exprType == "literalInt" then expr.value = tonumber(cdata.ival) expr.isBoolLiteral = (cdata.isBoolLiteral == true) elseif exprType == "literalNull" then expr.value = box.NULL elseif exprType == "parameter" then expr.paramId = tonumber(cdata.ival) elseif exprType == "functionRef" then expr.distinct = cdata.distinct local datetimeField = tonumber(cdata.datetimeField) if cdata.datetimeField > 0 then expr.datetimeField = parserConst.getDatetimeFieldStr(datetimeField) end local columnType = tonumber(cdata.columnType) if columnType > 0 then expr.columnType = parserConst.getColumnTypeStr(columnType) end local columnLength = tonumber(cdata.columnLength) if columnLength > 0 then expr.columnLength = columnLength end elseif exprType == "operator" then local opTypeNum = tonumber(cdata.opType) expr.name = parserConst.getOperatorTypeStr(opTypeNum) expr.arity = getOperatorArity(opTypeNum) elseif exprType == "arrayIndex" then expr.index = tonumber(cdata.ival) end return expr end getExprArr = function(cdata, count, params) return getArr(cdata, count, getExpr, params) end getJoinDefinition = function(cdata, params) if cdata == nil then return nil end local joinDefinition = { } joinDefinition.left = getTableRef(cdata.left, params) joinDefinition.right = getTableRef(cdata.right, params) joinDefinition.condition = getExpr(cdata.condition, params) joinDefinition.type = parserConst.getJoinTypeStr(cdata.type) return joinDefinition end getAlias = function(cdata) if cdata == nil then return nil end local alias = { } alias.name = getStr(cdata.name) alias.columns = getArr(cdata.columns, cdata.columnCount, getStr) return alias end getTableRef = function(cdata, params) if cdata == nil then return nil end local tableRef = { } tableRef.type = parserConst.getTableRefTypeStr(cdata.type) tableRef.schema = getStr(cdata.schema) tableRef.name = getStr(cdata.name) tableRef.alias = getAlias(cdata.alias) tableRef.select = getSelectStatement(cdata.select, params) tableRef.list = getArr(cdata.list, cdata.listSize, getTableRef, params) tableRef.join = getJoinDefinition(cdata.join, params) return tableRef end getGroupByDescription = function(cdata, params) if cdata == nil then return nil end local groupBy = { } groupBy.columns = getExprArr(cdata.columns, cdata.columnCount, params) groupBy.having = getExpr(cdata.having, params) return groupBy end getSetOperation = function(cdata, params) if cdata == nil then return nil end local setOp = { } setOp.setType = parserConst.getSetTypeStr(cdata.setType) setOp.isAll = cdata.isAll setOp.nestedSelectStatement = getSelectStatement( cdata.nestedSelectStatement, params) setOp.resultOrder = getArr(cdata.resultOrder, cdata.resultOrderCount, getOrderDescription, params) setOp.resultLimit = getLimitDescription(cdata.resultLimit, params) return setOp end getOrderDescription = function(cdata, params) if cdata == nil then return nil end local orderDesc = { } orderDesc.type = parserConst.getOrderTypeStr(cdata.type) orderDesc.expr = getExpr(cdata.expr, params) return orderDesc end getWithDescription = function(cdata, params) if cdata == nil then return nil end local withDesc = { } withDesc.alias = getStr(cdata.alias) withDesc.select = getSelectStatement(cdata.select, params) return withDesc end getLimitDescription = function(cdata, params) if cdata == nil then return nil end local limitDesc = { } limitDesc.limit = getExpr(cdata.limit, params) limitDesc.offset = getExpr(cdata.offset, params) return limitDesc end getSelectStatement = function(cdata, params) if cdata == nil then return nil end local statement = { } statement.fromTable = getTableRef(cdata.fromTable, params) statement.selectDistinct = cdata.selectDistinct statement.selectList = getExprArr(cdata.selectList, cdata.selectListSize, params) statement.whereClause = getExpr(cdata.whereClause, params) statement.groupBy = getGroupByDescription(cdata.groupBy, params) statement.setOperations = getArr(cdata.setOperations, cdata.setOperationCount, getSetOperation, params) statement.order = getArr(cdata.order, cdata.orderCount, getOrderDescription, params) statement.withDescriptions = getArr(cdata.withDescriptions, cdata.withDescriptionCount, getWithDescription, params) statement.limit = getLimitDescription(cdata.limit, params) return statement end getSQLStatement = function(cdata, params) if cdata == nil then return nil end local statement local statementType = parserConst.getStatementTypeStr(cdata.type) if statementType == "select" then local cdataEx = ffi.cast("LuaSelectStatement*", cdata) statement = getSelectStatement(cdataEx, params) else statement = { } end statement.type = statementType statement.stringLength = statement.stringLength statement.hints = getExprArr(cdata.hints, cdata.hintCount, params) return statement end getSQLParserResult = function(cdata) if cdata == nil then return nil end local result = { } result.isValid = cdata.isValid result.parameters = { } result.statements = getArr(cdata.statements, cdata.statementCount, getSQLStatement, result.parameters) table.sort(result.parameters, function(a, b) return a.paramId < b.paramId end) result.errorMsg = getStr(cdata.errorMsg) result.errorLine = tonumber(cdata.errorLine) result.errorColumn = tonumber(result.errorColumn) return result end local function parse(query) assert(query ~= nil, "sqlparser: SQL query string is not specified") local cdata = sqlParserLib.parseSql(query) local obj = getSQLParserResult(cdata) sqlParserLib.finalize(cdata) return obj end return { parse = parse, tostring = sqlgen.generate }
Locales['en'] = { -- global menus ['not_enough_in_society'] = 'there\'s not enough of ~r~that item~s~ in the society!', ['player_cannot_hold'] = 'you do ~r~not~s~ have enough ~y~free space~s~ in your inventory!', ['vehicle_belongs'] = 'a vehicle with plate ~y~%s~s~ now belongs to ~b~you~s~', ['broke_company'] = 'you do not have enough money in the company account', ['license_missing'] = 'you don\'t have a driver\'s license!', ['buy_vehicle_shop'] = 'do you want to purchase %s for $%s?', ['buy_vehicle'] = 'buy vehicle', ['car_dealer'] = 'car Dealership', ['shop_awaiting_model'] = 'the vehicle is currently loading, please wait', ['create_bill'] = 'create bill', ['dealer_boss'] = 'car Dealer - Boss', ['delivered'] = 'the vehicle has been ~g~delivered~s~ to the dealer', ['depop_vehicle'] = 'return vehicle to garage', ['return_provider'] = 'return vehicle to provider', ['get_rented_vehicles'] = 'vehicles for rent', ['no_current_vehicle'] = 'you do not currently have a vehicle on display', ['invalid_amount'] = 'invalid amount', ['invoice_amount'] = 'invoice amount', ['no'] = 'no', ['yes'] = 'yes', ['no_players'] = 'there is no players near you', ['not_enough_money'] = 'you do not have enough money', ['not_rental'] = 'this is not a ~r~rental vehicle~s~', ['not_yours'] = 'this vehicle does not belong to you', ['paid_rental'] = 'you have paid ~g~$%s~s~ for renting a vehicle with plate ~y~%s~s~', ['paid_rental_evicted'] = 'you could not afford to pay ~g~$%s~s~ for your rented vehicle with plate ~y~%s~s~, it has been returned to the dealership', ['pop_vehicle'] = 'put out vehicle for sale', ['rent_vehicle'] = 'car Dealer - Vehicles for rent', ['return_provider_menu'] = 'car Dealer - Return vehicle to provider', ['rental_amount'] = 'rental amount', ['sell_menu'] = 'press ~INPUT_CONTEXT~ to sell your ~y~%s~s~ for ~g~$%s~s~', ['set_vehicle_owner_rent'] = 'rent vehicle', ['set_vehicle_owner_sell'] = 'sell vehicle', ['shop_menu'] = 'press ~INPUT_CONTEXT~ to access the menu', ['generic_shopitem'] = '$%s', ['vehicle_dealer'] = 'vehicle - Car Dealer', ['vehicle_menu'] = 'press ~INPUT_CONTEXT~ to give back the rented vehicle', ['vehicle_purchased'] = 'you bought a vehicle', ['vehicle_set_owned'] = 'vehicle ~y~%s~s~ has been assigned to ~b~%s~s~', ['vehicle_set_rented'] = 'vehicle ~y~%s~s~ has been rented to ~b~%s~s~', ['vehicle_sold_for'] = 'the ~b~%s~s~ has been ~y~sold~s~ for ~g~$%s~s~', ['vehicle_sold_to'] = 'the vehicle with plate ~y~%s~s~ has been sold to ~b~%s~s~', ['deposit_stock'] = 'deposit stock', ['take_stock'] = 'withdraw stock', ['dealership_stock'] = 'dealership Stock', ['amount'] = 'amount', ['quantity_invalid'] = 'that\'s an invalid quantity', ['inventory'] = 'inventory', ['dealership'] = 'car Dealer', ['dealer_customers'] = 'dealer customers', ['have_withdrawn'] = 'you have withdrawn ~y~x%s~s~ ~b~%s~s~', ['have_deposited'] = 'you have deposited ~y~x%s~s~ ~b~%s~s~', ['boss_actions'] = 'boss actions', -- sold vehicles ['boss_sold'] = 'list of sold vehicles', ['customer_client'] = 'customer name', ['customer_model'] = 'car model', ['customer_plate'] = 'car plate', ['customer_soldby'] = 'sold by', ['customer_date'] = 'date', }
music = "Muttrace.ogg" function start() out = Portal:new{x=3, y=7} shopkeep = Object:new{x=3, y=2, anim_set="Doggy", person=true} setObjectDirection(shopkeep.id, DIRECTION_SOUTH) shop = Object:new{x=3, y=3} end function stop() end function update(step) if (out:update()) then change_areas("Muttrace", 20, 8, DIRECTION_SOUTH) end end function activate_shop() doDialogue("Shopkeeper: Everything is on sale for you my friend.\n", true) doShop("Shopkeep", "Muttrace_shopkeeper", 5, ITEM_LIGHT_SWORD, 500, ITEM_LIGHT_STAFF, 500, ITEM_LIGHT_HELMET, 500, ITEM_LIGHT_ARMOR, 500, ITEM_LIGHT_BOOTS, 500) end function activate(activator, activated) if (activated == shop.id) then activate_shop() end end function activate_any(tx, ty) local px, py = getObjectPosition(0) if (px == 3 and py == 4 and tx == 3 and ty == 2) then setObjectDirection(0, DIRECTION_NORTH); activate_shop() return true end return false end function collide(id1, id2) end
#include "umf/umf_meta.lua" #include "umf/umf_utils.lua" local VEC_MIN = Vec(-math.huge, -math.huge, -math.huge) local VEC_MAX = Vec(math.huge, math.huge, math.huge) -- UI functions function UiDrawLine(dx, dy, r, g, b, a) UiPush() UiColor(r, g, b, a) UiRotate(math.atan2(-dy, dx) * 180 / math.pi) UiRect((dx * dx + dy * dy) ^ .5, 1) UiPop() end function UiEmptyButton(w, h, backColor) UiAlign("left") local info = {UiIsMouseInRect(w, h), InputPressed("lmb"), InputDown("lmb")} local colorOffset = (info[1] and info[3]) and .1 or 0 -- Button background UiPush() UiColor(backColor[1] - colorOffset, backColor[2] - colorOffset, backColor[3] - colorOffset, backColor[4] ~= nil and backColor[4] or 1) UiRect(w, h) UiPop() return info end function UiTextedButton(text, align, w, h, backColor, textColor) local info = UiEmptyButton(w, h, backColor) local colorOffset = (info[1] and info[3]) and .1 or 0 -- Button text UiPush() UiTranslate(w / 2 + ((info[1] and info[3]) and 2 or 0), h / 2 + ((info[1] and info[3]) and 2 or 0)) UiAlign(align) UiColor(textColor[1] + colorOffset, textColor[2] + colorOffset, textColor[3] + colorOffset, textColor[4] ~= nil and textColor[4] or 1) UiText(text) UiPop() return info[1] and info[2], info[1] and info[3] end function UiColoredSlider(value, rangeMin, rangeMax, w, h, backColor, sliderColor) local info = {UiIsMouseInRect(w, h), InputPressed("lmb"), InputDown("lmb")} UiPush() -- Slider background UiAlign("left") UiColor(backColor[1], backColor[2], backColor[3], backColor[4] ~= nil and backColor[4] or 1) UiRect(w, h) UiPop() -- Slider button local valueWidth = w / rangeMax local widthValue = rangeMax / w local x = (info[1] and info[3]) and UiGetMousePos() or (valueWidth * value) UiPush() UiWindow(x, h, true) UiColor(sliderColor[1], sliderColor[2], sliderColor[3], sliderColor[4]) UiRect(x - 8, h) UiTranslate(x - 8) UiColor(sliderColor[1] + .1, sliderColor[2] + .1, sliderColor[3] + .1, sliderColor[4]) UiRect(16, h) UiPop() UiPush() UiAlign("center middle") UiTranslate(w / 2, h / 2) UiColor(1, 1, 1, 1) UiFont("bold.ttf", 18) UiText(value) UiPop() return widthValue * x end function UiColorPicker(lastColor, scale) local size = (480 * scale) local mouseX, mouseY = UiGetMousePos() local positions = (UiIsMouseInRect(size, size) and InputDown("lmb")) and {1 / size * math.min(math.max(mouseX, 0), size), 1, 1 / size * math.min(math.max(mouseY, 0), size)} or lastColor local color = visual.hslrgb(positions[1], positions[2], positions[3]) UiPush() UiScale(scale) UiColor(1, 1, 1, 1) UiImage("assets/gfx/palette/palette.png") UiPush() local invserseColorLightness = visual.hslrgb(0, 0, 1 - positions[3]) UiAlign("center middle") UiTranslate(480 * positions[1], 480 * positions[3]) UiScale(.1 / scale) UiColor(invserseColorLightness[1], invserseColorLightness[2], invserseColorLightness[3]) UiImage("assets/gfx/palette/palette_pointer.png") UiPop() UiPop() return positions end function UiInformationCounter(x, y, scale, data, options) UiPush() local color = visual.hslrgb(options.counter.textColor[1][1], options.counter.textColor[1][2], options.counter.textColor[1][3]) local xAlignments = {"left", "center", "right"} local yAlignments = {"top", "middle", "bottom"} local xAlignment = Round(2 * options.counter.position[1] / UiWidth()) local yAlignment = Round(2 * options.counter.position[2] / UiHeight()) local enabledCounts = 0 local counts = {{options.counter.frameCount, CalculateFrameAccuracy(data[4], options), "FPS"}, {options.counter.bodyCount, data[5], "BOD"}, {options.counter.shapeCount, data[6], "SHA"}, {options.counter.fireCount, data[7], "FIR"}} for enabledCountsIteration = 1, #counts do enabledCounts = enabledCounts + (counts[enabledCountsIteration][1] and 1 or 0) end -- Draw the counter background local backgroundSize = 15 * enabledCounts * scale + (enabledCounts > 0 and 5 or 0) * scale local backgroundColor = visual.hslrgb(options.counter.backColor[1][1], options.counter.backColor[1][2], options.counter.backColor[1][3]) UiAlign(xAlignments[xAlignment + 1] .. yAlignments[yAlignment + 1]) UiTranslate(options.counter.position[1] + x, options.counter.position[2] + y) UiColor(backgroundColor[1], backgroundColor[2], backgroundColor[3], options.counter.backColor[2]) UiRect(60 * scale, backgroundSize) -- Configure counter text sizes and color UiAlign("left middle") UiTranslate(-30 * xAlignment * scale, -backgroundSize * (yAlignment / 2) + 10 * options.counter.size) UiFont("bold.ttf", options.counter.textSize * scale) UiColor(color[1], color[2], color[3], options.counter.textColor[2]) for countIteration = 1, #counts do local count = counts[countIteration] if count[1] then UiPush() UiFont("bold.ttf", options.counter.textSize * scale - 4 * math.floor(count[2] / 10000)) UiText(count[2]) UiAlign("right") UiTranslate(60 * scale, 0) UiFont("bold.ttf", 8 * scale) UiText(count[3]) UiPop() UiTranslate(0, 15 * scale) end end UiPop() end -- Global functions function Clone(object) return util.unserialize(util.serialize(object)) end function GetBodies(min, max, require) QueryRequire(require and require or "") return QueryAabbBodies(min and min or VEC_MIN, max and max or VEC_MAX) end function GetBodyCount(min, max, require) QueryRequire(require and require or "") return #QueryAabbBodies(min and min or VEC_MIN, max and max or VEC_MAX) end function GetShapes(min, max, require) return QueryAabbShapes(min and min or VEC_MIN, max and max or VEC_MAX) end function GetShapeCount(min, max, require) return #QueryAabbShapes(min and min or VEC_MIN, max and max or VEC_MAX) end -- Mathematical functions function Round(value, decimals, overflow) decimals = decimals or 0 overflow = overflow or .5 return math.floor((value + overflow) * 10 ^ decimals) / 10 ^ decimals end function CalculateFrameAccuracy(framesPerSecond, options) local accuracy = math.pow(10, framesPerSecond >= 100 and math.max(options.counter.accuracy - 1, 0) or options.counter.accuracy) return math.floor(framesPerSecond * accuracy) / accuracy end
require("awful") require("awful.rules") require("beautiful") require("naughty") require("keygrabber") require("vicious") require("bobroutils") require("tbar") require("rsi") require("rodentbane") --require("debug") -- {{{ Variable definitions -- Themes define colours, icons, and wallpapers beautiful.init("/home/bobrov/.config/awesome/theme/theme.lua") -- This is used later as the default terminal and editor to run. terminal = "urxvtc" editor = os.getenv("EDITOR") or "vim" editor_cmd = terminal .. " -e " .. editor modkey = "Mod4" naughty.config.margin = 10 naughty.config.height = 30 naughty.config.width = 300 -- {{{ Tags -- Define tags table. tags = {} for s = 1, screen.count() do local tt = awful.tag({"main", "con", "gimp"}, s) tags[s] = {} tags[s]["main"] = tt[1] tags[s]["con"] = tt[2] tags[s]["gimp"] = tt[3] screen[s]:tags(tt) awful.layout.set(awful.layout.suit.max, tags[s]["main"]) awful.layout.set(awful.layout.suit.max, tags[s]["con"]) awful.layout.set(awful.layout.suit.max, tags[s]["gimp"]) tags[s]["main"].selected = true end -- }}} -- {{{ Menu -- Create a laucher widget and a main menu myawesomemenu = { { "manual", terminal .. " -e man awesome" }, { "edit config", editor_cmd .. " " .. awful.util.getdir("config") .. "/rc.lua" }, { "restart", awesome.restart }, { "quit", awesome.quit } } mymainmenu = awful.menu({ items = { { "awesome", myawesomemenu, beautiful.awesome_icon }, { "open terminal", terminal } } }) mylauncher = awful.widget.launcher({ image = image(beautiful.awesome_icon), menu = mymainmenu }) -- }}} -- {{{ Wibox -- Create a textclock widget mytextclock = awful.widget.textclock({align = "right"}, "%H:%M", 10) awful.widget.layout.margins[mytextclock] = { right = 1 } -- Create a systray mysystray = widget({ type = "systray" }) awful.widget.layout.margins[mysystray] = { left = 4 } -- Create a wibox for each screen and add it mywibox = {} mypromptbox = {} mylayoutbox = {} mytaglist = {} mytaglist.buttons = awful.util.table.join( awful.button({ }, 1, awful.tag.viewonly), awful.button({ modkey }, 1, awful.client.movetotag) ) mytasklist = {} mytasklist.buttons = awful.util.table.join( awful.button({ }, 2, function (c) c:kill() end), awful.button({ }, 1, function (c) if not c:isvisible() then awful.tag.viewonly(c:tags()[1]) end client.focus = c c:raise() end) ) cpuwidget = awful.widget.graph() cpuwidget:set_width(40) cpuwidget:set_height(16) cpuwidget:set_background_color(beautiful.bg_normal) cpuwidget:set_color('#FF5656') cpuwidget:set_gradient_colors({ '#FF5656', '#88A175', '#AECF96' }) cpuwidget.layout = awful.widget.layout.horizontal.rightleft awful.widget.layout.margins[cpuwidget.widget] = { top = 1, left = 3, right = 5 } vicious.register(cpuwidget, vicious.widgets.cpu, '$1', 1) for s = 1, screen.count() do mypromptbox[s] = awful.widget.prompt({ layout = awful.widget.layout.horizontal.leftright }) mytaglist[s] = awful.widget.taglist(s, awful.widget.taglist.label.all, mytaglist.buttons) -- Create a tasklist widget mytasklist[s] = awful.widget.tasklist(function(c) local text, bg, status_image, icon = awful.widget.tasklist.label.currenttags(c, s) return text, bg, status_image, nil end, mytasklist.buttons) -- Create the wibox mywibox[s] = awful.wibox({ position = "top", screen = s}) -- Add widgets to the wibox - order matters mywibox[s].widgets = { { mytaglist[s], mylauncher, mypromptbox[s], layout = awful.widget.layout.horizontal.leftright }, { s == 1 and mysystray or nil, mytextclock, cpuwidget, layout = awful.widget.layout.horizontal.rightleft }, mytasklist[s], layout = awful.widget.layout.horizontal.leftright } end -- }}} -- {{{ Key bindings globalkeys = awful.util.table.join( awful.key({ modkey, }, "j", function () awful.client.focus.byidx( 1) if client.focus then client.focus:raise() end end), awful.key({ modkey, }, "k", function () awful.client.focus.byidx(-1) if client.focus then client.focus:raise() end end), awful.key({ modkey, }, "u", awful.client.urgent.jumpto), awful.key({ modkey, "Control" }, "r", awesome.restart), awful.key({ modkey, "Shift" }, "q", awesome.quit), awful.key({ modkey, }, "c", rodentbane.start), -- Prompt awful.key({ modkey }, "r", function () mypromptbox[mouse.screen]:run() end), -- My Keys awful.key({ modkey }, "b", rsi.start_rest ), awful.key({ modkey }, "Left", function() awful.tag.viewprev(); check_focus() end ), awful.key({ modkey }, "Right", function() awful.tag.viewnext(); check_focus() end ), awful.key({ modkey }, "[", function() awful.util.spawn("mpc volume -2") end), awful.key({ modkey }, "]", function() awful.util.spawn("mpc volume +2") end), awful.key({ modkey }, "p", function() awful.util.spawn("mpc toggle") end), awful.key({}, "XF86MonBrightnessUp", function() awful.util.spawn("sudo backlight up") end), awful.key({}, "XF86MonBrightnessDown", function() awful.util.spawn("sudo backlight down") end), awful.key({modkey}, "n", function() spawn_or_raise("urxvtc -name mutt -e mutt", match_client{instance='mutt'}) end), awful.key({"Control", "Mod1"}, "p", function() spawn_or_raise("urxvtc -name ncmpcpp -e ncmpcpp", match_client{instance='ncmpcpp'}) end), awful.key({modkey}, "i", function() spawn_or_raise("urxvtc -name weechat -e weechat-curses", match_client{instance='weechat'}) end), awful.key({"Control", "Mod1"}, "m", function() spawn_or_raise("urxvtc -name amixer -e alsamixer", match_client{instance='amixer'}) end), awful.key({"Mod4"}, "e", function() awful.util.spawn("awesome-menu.sh") end), awful.key({"Control", "Mod1"}, "x", function() awful.util.spawn(terminal) end), awful.key({"Control", "Mod1"}, "\\", function() root.cursor("left_ptr") end), awful.key({ modkey }, "Tab", function () local hist = focus_history_without_modal_transients(1) if #hist < 2 then return end client.focus = hist[2] hist[2]:raise() local lastidx = 2 local first_client = hist[1] keygrabber.run(function(mod, key, event) if key == 'Super_L' and event == 'release' then if client.focus ~= first_client then awful.client.focus.history.add(first_client) if client.focus.modal and client.focus.transient_for then awful.client.focus.history.add(client.focus.transient_for) end awful.client.focus.history.add(client.focus) end return false end if key == 'Tab' and event == 'press' then lastidx = lastidx + 1 if lastidx > #hist then lastidx = 1 end client.focus = hist[lastidx] hist[lastidx]:raise() end return true end) end), awful.key({"Control", "Mod1"}, "c", function() if awful.tag.selected() ~= tags[1]["con"] then prev_selected_tag = awful.tag.selected() if nil == next(tags[1]["con"]:clients()) then awful.util.spawn(terminal) else awful.tag.viewonly(tags[1]["con"]) check_focus(nil) end else if prev_selected_tag then awful.tag.viewonly(prev_selected_tag) check_focus(nil) else awful.tag.viewonly(tags[1]["main"]) check_focus(nil) end end end ), awful.key({"Control", "Mod1"}, "=", function() local c = awful.mouse.client_under_pointer() naughty.notify({ text = "class: " .. c.class .. "\nname: " .. c.name .. "\ninstance: " .. c.instance .. "\nrole: " .. tostring(c.role) .. "\ntype: " .. c.type .. "\nfloat: " .. tostring(isfloating(c)), timeout = 5, hover_timeout = 0.5, width = 500, }) end), awful.key({"Control", "Mod1"}, "]", function() local c = awful.mouse.client_under_pointer() c:tags({tags[1]["gimp"]}) awful.tag.viewmore(c:tags(), 1) c:geometry{width=864, height=486, x=30, y=30} awful.placement.centered(c) client.focus = c c:raise() end) ) clientkeys = awful.util.table.join( awful.key({ modkey, "Shift" }, "c", function (c) c:kill() end), awful.key({ modkey, "Control" }, "space", floating_toggle ), awful.key({ modkey, }, "t", function (c) c.ontop = not c.ontop end) ) clientbuttons = awful.util.table.join( awful.button({ }, 1, function (c) client.focus = c; c:raise() end), awful.button({ modkey }, 1, awful.mouse.client.move), awful.button({ modkey }, 3, awful.mouse.client.resize)) -- Set keys root.keys(globalkeys) -- }}} conkeys = awful.util.table.join(clientkeys, awful.key({"Shift"}, "Left", function (c) awful.client.focus.byidx(-1); client.focus:raise() end), awful.key({"Shift"}, "Right",function (c) awful.client.focus.byidx(1); client.focus:raise() end) ) -- Handles tab key to fast switch between gimp image and tollboxes windows gimp_box_keys = awful.util.table.join(clientkeys, awful.key({}, "Tab", function (c) local boxes = get_clients(function(c) return c.role=="gimp-toolbox" or c.role=="gimp-dock" end) local boxes_are_visible = true for _, c in pairs(boxes) do if not c.above then boxes_are_visible = false break end end if boxes_are_visible then for _, c in pairs(boxes) do c.below = true end local c = get_client(match_client{role="gimp-image-window"}) if c then client.focus = c end else for _, c in pairs(boxes) do c.above = true end end end) ) -- {{{ Rules awful.rules.rules = { -- All clients will match this rule. { rule = { }, properties = { border_width = beautiful.border_width, border_color = beautiful.border_normal, focus = true, keys = clientkeys, buttons = clientbuttons } }, { rule = { }, properties = { tag = tags[1]["main"], switchtotag = true, floating = true } }, { rule = { class = "URxvt" }, properties = { tag = tags[1]["con"], keys = conkeys, switchtotag = true, size_hints_honor = false, border_width = 0, floating = false } }, { rule = { class = "Gimp" }, properties = { tag = tags[1]["gimp"] } }, { rule = { instance = "gimp", type = "dialog" }, properties = { above = true } }, { rule = { role = "gimp-image-window" }, properties = { keys = gimp_box_keys, border_width = 0, floating = false, } }, { rule = { role = "gimp-toolbox" }, properties = { size_hints_honor = false, skip_taskbar = true, focus = false, keys = gimp_box_keys, geometry = {x=0, y=19, height=562, width=400}, below = true } }, { rule = { role = "gimp-dock" }, properties = { size_hints_honor = false, skip_taskbar = true, focus = false, keys = gimp_box_keys, geometry = {x=624, y=19, height=562, width=400}, below = true } }, { rule = { class = "Opera", instance = "opera" }, properties = { border_width = 0, floating = false } }, { rule = { class = "luakit", instance = "luakit" }, properties = { border_width = 0, floating = false } }, { rule = { class = "Namoroka", role = "browser" }, properties = { border_width = 0, floating = false } }, { rule = { class = "Firefox", role = "browser" }, properties = { border_width = 0, floating = false } }, { rule = { class = "Snaked", role = "Editor" }, properties = { border_width = 0, floating = false } }, { rule = { modal = true }, properties = { skip_taskbar = true, floating = true } }, } -- }}} -- {{{ Signals -- Signal function to execute when a new client appears. client.add_signal("manage", function (c, startup) if update_titlebar(c) then if not c.size_hints.user_position and not c.size_hints.program_position then awful.placement.centered(c) end end c:add_signal("property::floating", update_titlebar) end) client.add_signal("focus", function(c) c.border_color = beautiful.border_focus update_titlebar(c) end) client.add_signal("unfocus", function(c) c.border_color = beautiful.border_normal update_titlebar(c) end) -- }}} function update_titlebar(c) local should_have_tb = isfloating(c) if c.titlebar and not should_have_tb then tbar.remove(c) end if not c.titlebar and should_have_tb then tbar.add(c, { modkey = modkey }) end if not c.modal then c.skip_taskbar = should_have_tb and client.focus == c end return should_have_tb end -- Clock stuff local calendar = nil local offset = 0 function remove_calendar() if calendar ~= nil then naughty.destroy(calendar) calendar = nil offset = 0 end end function add_calendar(inc_offset) local save_offset = offset remove_calendar() offset = save_offset + inc_offset local datespec = os.date("*t") datespec = datespec.year * 12 + datespec.month - 1 + offset datespec = (datespec % 12 + 1) .. " " .. math.floor(datespec / 12) local cal = awful.util.pread("cal -m " .. datespec) cal = string.gsub(cal, "^%s*(.-)%s*$", "%1") calendar = naughty.notify({ text = string.format('<span font_desc="%s">%s</span>', "monospace", os.date("%a, %d %B %Y") .. "\n" .. cal), timeout = 0, hover_timeout = 0.5, width = 170, }) end -- change clockbox for your clock widget (e.g. mytextclock) mytextclock:add_signal("mouse::enter", function() add_calendar(0) end) mytextclock:add_signal("mouse::leave", remove_calendar) mytextclock:buttons(awful.util.table.join( awful.button({ }, 4, function() add_calendar(-1) end), awful.button({ }, 5, function() add_calendar(1) end) )) local new_im_message = false imtimer = timer({ timeout = 5 }) imtimer:add_signal("timeout", function() local im_message = false f = io.open('/home/bobrov/.mcabber/mcabber.state') if f ~= nil then im_message = true f:close() end if new_im_message ~= im_message then new_im_message = im_message c = get_client(match_client{instance='mcabber'}) if c ~= nil then c.urgent = new_im_message end end end) -- imtimer:start() rsi.run()
function Spawn( entityKeyValues ) thisEntity._abilitySilence = thisEntity:FindAbilityByName( "ability_boss3_silence" ) thisEntity._abilitySummon = AICore:FindAbility(thisEntity, "ability_boss3_summom_healer" ) thisEntity._abilityBattleHunger = AICore:FindAbility(thisEntity, "ability_boss2_battle_hunger" ) thisEntity._abilityBattleHunger:StartCooldown(20) thisEntity._abilitySummonAuraguy = AICore:FindAbility(thisEntity, "ability_boss3_summom_auraguy" ) thisEntity._abilitySummonAuraguy:StartCooldown(25) thisEntity:SetContextThink( "BossThink", BossThink, 5 ) end function BossThink() if thisEntity:IsNull() or not thisEntity:IsAlive() then return nil end if thisEntity._abilitySummon:IsFullyCastable() then AICore:CastAbilityNoTarget(thisEntity, thisEntity._abilitySummon) elseif thisEntity._abilitySummonAuraguy:IsFullyCastable() then AICore:CastAbilityNoTarget(thisEntity, thisEntity._abilitySummonAuraguy) elseif thisEntity._abilityBattleHunger:IsFullyCastable() then AICore:CastAbilityNoTarget(thisEntity, thisEntity._abilityBattleHunger) elseif thisEntity._abilitySilence:IsFullyCastable() then local units = AICore:BotFindEnemies(thisEntity:GetOrigin(), 900) if #units > 0 then AICore:CastAbilityPosition(thisEntity, thisEntity._abilitySilence, units[1]:GetOrigin()) end end return 1 end
--- binary 0011 1111 which represents the utf-8 continue mask local CONT_MASK = 63 local Buffer = {} Buffer.__index = Buffer function Buffer.new(s) local ret = { stream = s, current_idx = 1, len = #s, } setmetatable(ret, Buffer) return ret end ---Check if the buffer has reached the last character function Buffer:at_end() return self.current_idx >= self.len end function Buffer:current_char() return string.sub(self.stream, self.current_idx, self.current_idx) end ---Get the current byte function Buffer:current_byte() return string.byte(self.stream, self.current_idx, self.current_idx) end ---Get the next byte, with no regard for any string encoding ---returns nil,string if idx is past the end of the buffer ---@return number|nil, string|nil function Buffer:next_byte() local idx = self.current_idx + 1 if idx >= self.len then return nil, 'At EOF' end return string.byte(self.stream, idx, idx) end ---Move the buffer forward a number of bytes, returning the substring ---that was just passed. Returns nil, string ct would move past the end of the buffer ---@param ct number The number of bytes to move forward ---@return string|nil,string|nil function Buffer:advance(ct) local new_idx = self.current_idx + ct if new_idx > self.len then return nil, 'Would pass EOF' end local s s = string.sub(self.stream, self.current_idx, new_idx-1) -- if ct == 1 then -- s = string.sub(self.stream, self.current_idx, self.current_idx) -- else -- end self.current_idx = new_idx return s end ---Check if the buffer currently starts with the provided string ---@param s string The string to match ---@return boolean function Buffer:starts_with(s) local sub = string.sub(self.stream, self.current_idx) local start, _stop = string.find( sub, string.format('^%s', s) ) return start ~= nil end function Buffer:at_cdata_start() local slice = string.sub( self.stream, self.current_idx, self.current_idx + #'<![CDATA') return slice == '<![CDATA[' end ---Consume the provided string, if the buffer isn't at ---the current string will return nil, string ---@param s string The string to match ---@return string|nil,string|nil function Buffer:consume_str(s) local s2 = string.match(self.stream, string.format('^%s', s), self.current_idx) if not s2 or s2 == '' then return nil, string.format('mismatched consume: "%s" vs "%s"', s, s2) end self:advance(#s2) return s2 end --- Consume bytes while the closure returns true ---@param f fun(b:string):boolean ---@return string|nil,string|nil function Buffer:consume_while(f) local pos = self.current_idx while not self:at_end() do local slice = string.sub(self.stream, pos, pos) if f(slice) then pos = pos + 1 else local ret = string.sub(self.stream, self.current_idx, pos - 1) self:advance(pos - self.current_idx) return ret end end end function Buffer:consume_until(s) local slice = string.sub(self.stream, self.current_idx) local start, stop = string.find(slice, s) if start == nil then return nil, 'pattern not found' end local ret = string.sub(slice, 1, start-1) self.current_idx = self.current_idx + #ret return ret end --- Accumulate and mask the continue byte ---@param acc number The number to accumulate into ---@param b number The byte to accumulate local function acc_cont_byte(acc, b) return (acc << 6) | (b & CONT_MASK) end --- Returns a utf-8 encoded --- character as an up to 4 byte integer function Buffer:next_utf8_int() local idx = self.current_idx local x = string.byte(self.stream, idx, idx) or 0 if x < 128 then return x, 1 end local len = 4 if x < 0xE0 then -- 0xE0 == 1110 0000 len = 2 elseif x < 0xF0 then -- 0xF0 == 1111 0000 len = 3 end local y, z, w = string.byte(self.stream, idx + 2, idx + len + 2) local init = x & (0x7F >> 2) if len == 2 then return acc_cont_byte(init, y or 0), len end local y_z = acc_cont_byte(y & CONT_MASK, z or 0) if len == 3 then return (init << 12) | y_z, len end local y_z_w = acc_cont_byte(y_z, w or 0) return (init & 7) << 18 | y_z_w, len end function Buffer:skip_whitespace() local whitespace = string.match(self.stream, '^%s*', self.current_idx) self:advance(#whitespace) return #whitespace > 0 end function Buffer:at_space() return string.find(self.stream, '^%s', self.current_idx) ~= nil end return Buffer
local tnt = require 'torchnet.env' local tds = require 'tds' local tester local test = torch.TestSuite() function test.DatasetIterator() local d = tnt.TableDataset{data = {1, 2, 3, 4, 5, 6}} local itr = tnt.DatasetIterator(d) local count = 0 for sample in itr:run() do count = count + 1 tester:eq(sample, count) end tester:eq(count, 6) end function test.DatasetIterator_filter() local d = tnt.TableDataset{data = {1, 2, 3, 4, 5, 6}} local itr = tnt.DatasetIterator{ dataset = d, filter = function(x) return x % 2 == 0 end, } local count = 0 for sample in itr:run() do count = count + 1 tester:eq(sample, count * 2, 'error at ' .. count) end tester:eq(count, 3) end function test.DatasetIterator_transform() local d = tnt.TableDataset{data = {1, 2, 3, 4, 5, 6}} local itr = tnt.DatasetIterator{ dataset = d, transform = function(x) return x - 1 end, } local count = 0 for sample in itr:run() do count = count + 1 tester:eq(sample, count - 1, 'error at ' .. count) end tester:eq(count, 6) end function test.DatasetIterator_exec() local itr = tnt.TableDataset{data = torch.range(1, 100):totable()} :shuffle() :transform(function(i) return i end) :iterator() local output1 = {} local output2 = {} for value in itr:run() do table.insert(output1, value) end itr:exec('resample') for value in itr:run() do table.insert(output2, value) end tester:ne(output1, output2, 'dataset not shuffled') table.sort(output1) table.sort(output2) tester:eq(output1, torch.range(1, 100):totable(), 'output1 incorrect') tester:eq(output2, torch.range(1, 100):totable(), 'output2 incorrect') end function test.DatasetIterator_perm() local d = tnt.TableDataset{data = {1, 2, 3, 4, 5, 6}} local itr = tnt.DatasetIterator{ dataset = d, perm = function(x) return (x % 6) + 1 end, } local count = 0 for sample in itr:run() do count = count + 1 tester:eq(sample, (count % 6) + 1, 'error at ' .. count) end tester:eq(count, 6) end function test.ParallelDatasetIterator() local d = tnt.TableDataset{data = {1, 2, 3, 4, 5, 6}} local itr = tnt.ParallelDatasetIterator{ closure = function() return d end, init = function() require 'torchnet' end, nthread = 3, } local count = 0 local present = {} for sample in itr:run() do tester:eq(present[sample], nil, 'duplicate sample: ' .. tostring(sample)) present[sample] = true count = count + 1 end tester:eq(count, d:size()) for i = 1, d:size() do tester:eq(present[i], true, 'missing sample: ' .. tostring(i)) end end function test.ParallelDatasetIterator_ordered() -- Create a dataset in which the second item is likely to be returned out -- of order local tds = require 'tds' local c = tds.AtomicCounter(0) local d = tnt.TableDataset{data = {1, 2, 3, 4, 5, 6}}:transform(function(s) if s == 2 then repeat until c:get() ~= 0 elseif s > 2 then c:inc() end return s end) local itr = tnt.ParallelDatasetIterator{ closure = function() return d end, init = function() require 'torchnet'; require 'tds' end, nthread = 3, ordered = true, } local count = 0 for sample in itr:run() do count = count + 1 tester:eq(sample, count, 'sample out of order') end tester:eq(count, d:size()) end return function(_tester_) tester = _tester_ return test end
--[[-- h1 four.Camera A camera defines a view volume of world space. --]]-- local lub = require 'lub' local four = require 'four' local lib = lub.class 'four.Camera' local V2 = four.V2 local V3 = four.V3 local M4 = four.M4 local Quat = four.Quat -- Projection parameters/matrix synchronization local function setOrthoMatrix(tv) local near, far = V2.tuple(tv.range) local hw = near * math.tan (tv.fov / 2) local hh = hw / tv.aspect tv.projection_matrix = M4.ortho(-hw, hw, -hh, hh, near, far) end local function setPerspMatrix(tv) local near, far = V2.tuple(tv.range) local hw = near * math.tan (tv.fov / 2) local hh = hw / tv.aspect tv.projection_matrix = M4.persp(-hw, hw, -hh, hh, near, far) end local function syncProjectionMatrix(tv) if tv.projection == lib.PERSPECTIVE then setPerspMatrix(tv) elseif tv.projection == lib.ORTHOGRAPHIC then setOrthoMatrix(tv) elseif tv.projection == lib.CUSTOM then return else assert(false) end end local is_projection_key = { projection = true, range = true, fov = true, aspect = true, projection_matrix = true } function lib.__index(t, k) if k == "tv" then return rawget(t, k) elseif is_projection_key[k] then local tv = t.tv if k == "projection_matrix" and tv.dirty_matrix then syncProjectionMatrix(tv) end return tv[k] else return lib[k] end end function lib.__newindex(t, k, v) if not is_projection_key[k] then rawset(t,k,v) else local tv = t.tv if k == "projection_matrix" then if tv.projection == lib.CUSTOM then tv[k] = v else error("Cannot set projection matrix on non-custom projection camera") end else tv.projection_dirty = true; tv[k] = v end end end setmetatable(lib, { __call = function(lib, def) return lib.new(def) end }) -- h2. Camera projection types lib.ORTHOGRAPHIC = 1 lib.PERSPECTIVE = 2 lib.CUSTOM = 3 -- h2. Constructor --[[-- @Camera(def)@ is a new camera object. @def@ keys: * @transform@, defines the location and orientation of the camera. Default transform lies at the origin and looks down the z-axis. * @projection@, the kind of projection to use (defaults to @PERSPECTIVE@). * @range@, for non-@CUSTOM@ projections defines the near and far clip plane (defaults to @V2(1, 100)@). Clip planes are perpendicular to the camera direction and are defined relative to the camera position. * @fov@, for non-@CUSTOM@ projections defines the horizontal field of view (defaults to @math.pi / 4@) * @aspect@, for non-@CUSTOM@ projections, defines the camera width/height ratio * @viewport@, table with @origin@ and @size@ keys defining the viewport in normalized screen coordinates of the renderer. Defaults covers the whole renderer viewport. * @background@, TODO * @effect_override@, specifies an effect to use instead of the renderable's Effects. --]]-- function lib.new(def) local self = { transform = four.Transform (), tv = { projection = lib.PERSPECTIVE, range = V2(1, 100), fov = math.pi / 4, aspect = 16 / 9, dirty_matrix = true, projection_matrix = M4.id ()}, viewport = { origin = four.V2.zero (), size = four.V2(1.0, 1.0) }, background = { color = four.Color.black (), depth = 1.0 }, -- Custom culling fun, e.g. omit renderable with a given key defined. cull = function (renderable) return false end, -- custom culling fun effect_override = nil, -- Override all renderable's effects } setmetatable(self, lib) if def then self:set(def) end return self end function lib:set(def) if def.transform ~= nil then self.transform = def.transform end if def.projection ~= nil then self.projection = def.projection end if def.range ~= nil then self.range = def.range end if def.fov ~= nil then self.fov = def.fov end if def.aspect ~= nil then self.aspect = def.aspect end if def.projection_matrix ~= nil then self.projection_matrix = def.projection_matrix end if def.background ~= nil then if def.background.color ~= nil then self.background.color = def.background.color end if def.background.depth ~= nil then self.background.depth = def.background.depth end end if def.viewport ~= nil then self.viewport = def.viewport end if def.effect_override ~= nil then self.effect_override = def.effect_override end end --[[-- c:screenToDevice(pos) is the normalized device coordinates of the normalized screen coordinates @pos@ in @c@. --]]-- function lib:screenToDevice(pos) local nvp = V2.div(pos - self.viewport.origin, self.viewport.size) return 2 * nvp - V2(1,1) end return lib
-- -- Author: Yiran WANG -- Date: 2014-08-05 16:18:35 -- local Formulas = require "Formulas" local Macros = require "Macros" local F_FeverBar = class("F_FeverBar") function F_FeverBar:ctor ( params ) -- self.Progress = {} -- self.fullPercentage = params.fullPercentage or 100 -- self.emptyPercentage = params.emptyPercentage or 0 -- print("percentage",self.Progress:getPercentage()) local x = params.x or 0 local y = params.y or 0 self:setPosition(x,y) self.comboParams = params.comboParams self.totalSections = #self.comboParams.capacity -- for i=1,self.totalSections do -- self.Progress[i] = display.newProgressTimer(params.fileName, kCCProgressTimerTypeBar) -- self.Progress[i]:setBarChangeRate(ccp(1, 0)) -- self.Progress[i]:setZOrder(100 - i) -- self:addChild(self.Progress[i]) -- end self.totalCounts = self.comboParams.capacity[#self.comboParams.capacity] self.displayCounts = 0 self.counts = 0 self.currentSection = 0 self.displayCurrentSection = 0 local xulicao = display.newSprite("xuLi0.png") self.size = xulicao:getContentSize() local PUSH_BUTTON_IMAGES = { -- normal = "Button01.png", -- pressed = "Button01Pressed.png", -- disabled = "Button01Disabled.png", -- altered by Yi normal = "xuLi3.png", pressed = "xuLi1.png", disabled = "xuLi0.png" } self.releaseButton = cc.ui.UIPushButton.new(PUSH_BUTTON_IMAGES, {scale9 = true}) :setButtonSize(self.size.width,self.size.height) -- :setButtonLabel("normal", ui.newTTFLabel({ -- text = "Normal", -- size = 18 -- })) -- :setButtonLabel("pressed", ui.newTTFLabel({ -- text = "Pressed", -- size = 18, -- color = ccc3(255, 64, 64) -- })) -- :setButtonLabel("disabled", ui.newTTFLabel({ -- text = "Disabled", -- size = 18, -- color = ccc3(0, 0, 0) -- })) :onButtonClicked(function(event) self:releaseCounts() end) :align(display.LEFT_CENTER, 0, 0) :addTo(self) -- self:setPercentage(0) self:refreshButtonState() self.battleField = params.battleField self:setTouchCaptureEnabled(true) end function F_FeverBar:setCountBy(count, counttype, time) if counttype == "display" then self.displayCounts = self.displayCounts + count if self.displayCounts < 0 then self.displayCounts = 0 elseif self.displayCounts > self.totalCounts then self.displayCounts = self.totalCounts end local sectionBefore = self.displayCurrentSection local newSection = self:getSectionByCounts(self.displayCounts) if newSection ~= sectionBefore then print("new section!", newSection) self.displayCurrentSection = newSection end self:refreshButtonState() else self.counts = self.counts + count if self.counts < 0 then self.counts = 0 elseif self.counts > self.totalCounts then self.counts = self.totalCounts end local sectionBefore = self.currentSection local newSection = self:getSectionByCounts(self.counts) if newSection ~= sectionBefore then print("new section at", time) self.currentSection = newSection self.battleField:refreshFeverBuff(time) end end end function F_FeverBar:refreshButtonState() if self.displayCurrentSection == self.totalSections then print("set button enable") self.releaseButton:setButtonEnabled(true) else print("set button disable") self.releaseButton:setButtonEnabled(false) end end function F_FeverBar:releaseCounts( ) if self.comboParams.release.releaseType == "damage" then local totalDamage = 0 for index, checkfighter in pairs(self.battleField.currentFighters["Friend"]) do totalDamage = totalDamage + Formulas.getBaseValue(checkfighter.calculatingParams, "Atk") * (1 + Formulas.getRatioValue(checkfighter.calculatingParams, "Atk")) end for index, checkfighter in pairs(self.battleField.currentFighters["Enemy"]) do self.battleField:addProcess(Macros.Instance, checkfighter.changeCurrentHpBy, {checkfighter, -totalDamage * self.comboParams.release.releaseValue, Macros.Instance}) end else for index, checkfighter in pairs(self.battleField.currentFighters["Friend"]) do self.battleField:addProcess(Macros.Instance, checkfighter.changeCurrentHpBy, {checkfighter, checkfighter.totalHp * self.comboParams.release.releaseValue, Macros.Instance}) end end self:playReleaseAnimation() self:setCountBy(-self.totalCounts, "value", Macros.Instance) self:setCountBy(-self.totalCounts, "display") end function F_FeverBar:playReleaseAnimation() end function F_FeverBar:getSectionByCounts(counts) local section = 0 for i=1,self.totalSections do if counts >= self.comboParams.capacity[i] then section = i end end return section end -- function F_FeverBar:setPercentage( percentage ) -- local convertedPercentage = self.emptyPercentage + (self.fullPercentage - self.emptyPercentage) * percentage -- self.Progress:setPercentage(convertedPercentage) -- end return F_FeverBar
return { no_consumer = true, fields = { card_number_field = {required = true, type = "string"}, card_expiry_month_field = {required = true, type = "string"}, card_expiry_year_field = {required = true, type = "string"}, card_cvv_field = {required = true, type = "string"}, tokenizer_url = {required = true, type = "string"}, card_token_output_field = {required = true, type = "string"}, } }
--[[ { file = "file path relative to Data Files\Sound", subtitle = "what it says" }, ]] local voices = { argonian = { female = { ["sneaking"] = { { file = "vo\\a\\f\\Hlo_AF000a.mp3", subtitle = "What?" }, { file = "vo\\a\\f\\Idl_AF007.mp3", subtitle = "What was that?" }, { file = "vo\\a\\f\\Idl_AF001.mp3", subtitle = "Sniff." }, { file = "vo\\a\\f\\Hlo_AF107.mp3", subtitle = "Your crimes are known to us." }, { file = "vo\\a\\f\\Hlo_AF106.mp3", subtitle = "You make a name for yourself, criminal." }, { file = "vo\\a\\f\\Hlo_AF040.mp3", subtitle = "Is there nothing for you to do?" }, { file = "vo\\a\\f\\Hlo_AF027.mp3", subtitle = "Must you make a pest of yourself?" } }, ["stop_sneaking"] = { { file = "vo\\a\\f\\Srv_AF003.mp3", subtitle = "You should leave." }, { file = "vo\\a\\f\\Srv_AF012.mp3", subtitle = "Leave! Before I eat it!" }, { file = "vo\\a\\f\\Srv_AF010.mp3", subtitle = "It should go away and die!" }, { file = "vo\\a\\f\\Hlo_AF000c.mp3", subtitle = "Humph." }, { file = "vo\\a\\f\\Hlo_AF000b.mp3", subtitle = "Humph." }, { file = "vo\\a\\f\\Thf_AF003.mp3", subtitle = "Hiss." }, { file = "vo\\a\\f\\Hlo_AF000e.mp3", subtitle = "Get out of here!" } }, ["stop_following"] = { { file = "vo\\a\\f\\Hlo_AF019.mp3", subtitle = "You hardly seem worth the trouble, criminal." }, { file = "vo\\a\\f\\Hlo_AF000b.mp3", subtitle = "Humph." }, { file = "vo\\a\\f\\Hlo_AF000c.mp3", subtitle = "Humph." }, { file = "vo\\a\\f\\Hlo_AF000d.mp3", subtitle = "I won't waste my time on the likes of you." }, { file = "vo\\a\\f\\Hlo_AF000e.mp3", subtitle = "Get out of here!" }, { file = "vo\\a\\f\\Thf_AF003.mp3", subtitle = "Hiss." } }, ["join_combat"] = { { file = "vo\\a\\f\\Hlo_AF017.mp3", subtitle = "Your life is mine!" }, { file = "vo\\a\\f\\Hlo_AF014.mp3", subtitle = "Kill it!" }, { file = "vo\\a\\f\\Hlo_AF014.mp3", subtitle = "Rip it apart!" }, { file = "vo\\a\\f\\Hlo_AF012.mp3", subtitle = "Bleed!" }, { file = "vo\\a\\f\\Atk_AF010.mp3", subtitle = "Hahahaha." } } }, male = { ["sneaking"] = { { file = "vo\\a\\m\\Flw_AM001.mp3", subtitle = "Where are you going?" }, { file = "vo\\a\\m\\Thf_AM005.mp3", subtitle = "I see you!" }, { file = "vo\\a\\m\\Hlo_AM106.mp3", subtitle = "You make a name for yourself, criminal." }, { file = "vo\\a\\m\\Hlo_AM107.mp3", subtitle = "Your crimes are known to us." }, { file = "vo\\a\\m\\Hlo_AM056.mp3", subtitle = "Sniff. This scent is new." }, { file = "vo\\a\\m\\Hlo_AM040.mp3", subtitle = "Is there nothing for you to do?" }, { file = "vo\\a\\m\\Hlo_AM027.mp3", subtitle = "Must you make a pest of yourself?" } }, ["stop_sneaking"] = { { file = "vo\\a\\m\\Srv_AM012.mp3", subtitle = "Leave! Before I eat it!" }, { file = "vo\\a\\m\\Srv_AM009.mp3", subtitle = "It should go away and die!" }, { file = "vo\\a\\m\\Hlo_AM046.mp3", subtitle = "Crime doesn't suit you, friend." }, { file = "vo\\a\\m\\Hlo_AM022.mp3", subtitle = "Be gone!" } }, ["stop_following"] = { { file = "vo\\a\\m\\Hlo_AM019.mp3", subtitle = "You hardly seem worth the trouble, criminal." }, { file = "vo\\a\\m\\Hlo_AM018.mp3", subtitle = "Get away, criminal." }, { file = "vo\\a\\m\\Hlo_AM022.mp3", subtitle = "Be gone!" } }, ["join_combat"] = { { file = "vo\\a\\m\\bAtk_AM002.mp3", subtitle = "Your head will be my new trophy!" }, { file = "vo\\a\\m\\bAtk_AM005.mp3", subtitle = "Your cursed bloodline ends here!" }, { file = "vo\\a\\m\\Atk_AM010.mp3", subtitle = "Bash!" }, { file = "vo\\a\\m\\Atk_AM011.mp3", subtitle = "Kill!" }, { file = "vo\\a\\m\\Atk_AM012.mp3", subtitle = "It will die!" }, { file = "vo\\a\\m\\Atk_AM013.mp3", subtitle = "Suffer!" }, { file = "vo\\a\\m\\Atk_AM014.mp3", subtitle = "Die!" } } } }, breton = { female = { ["sneaking"] = { { file = "vo\\b\\f\\Srv_BF006.mp3", subtitle = "I don't like you here, outlander." }, { file = "vo\\b\\f\\Hlo_BF026.mp3", subtitle = "Well, this should be interesting." }, { file = "vo\\b\\f\\Hlo_BF106.mp3", subtitle = "You would be wise to give up crime. It doesn't suit you." } }, ["stop_sneaking"] = { { file = "vo\\b\\f\\Srv_BF024.mp3", subtitle = "Do not waste my time." }, { file = "vo\\b\\f\\Idl_BF001.mp3", subtitle = "What was that about?" }, { file = "vo\\b\\f\\Hlo_BF017.mp3", subtitle = "What a revolting display." }, { file = "vo\\b\\f\\Hlo_BF000b.mp3", subtitle = "Humph." }, { file = "vo\\b\\f\\Hlo_BF000c.mp3", subtitle = "Humph." } }, ["stop_following"] = { { file = "vo\\b\\f\\Srv_BF024.mp3", subtitle = "Do not waste my time." }, { file = "vo\\b\\f\\Srv_BF003.mp3", subtitle = "You are repulsive, please go away." }, { file = "vo\\b\\f\\Hlo_BF025.mp3", subtitle = "No, I don't have time for you." }, { file = "vo\\b\\f\\Hlo_BF001.mp3", subtitle = "I think you should go elsewhere." }, { file = "vo\\b\\f\\Hlo_BF056.mp3", subtitle = "I am busy, so, if you will excuse me." } }, ["join_combat"] = { { file = "vo\\b\\f\\Atk_BF013.mp3", subtitle = "I should have killed you sooner!" }, { file = "vo\\b\\f\\Atk_BF009.mp3", subtitle = "Soon you'll be reduced to dust!" }, { file = "vo\\b\\f\\Atk_BF006.mp3", subtitle = "Death awaits you!" }, { file = "vo\\b\\f\\Atk_BF004.mp3", subtitle = "You'll be dead soon!" }, { file = "vo\\b\\f\\Atk_BF008.mp3", subtitle = "You should have run while you had a chance!" } } }, male = { ["sneaking"] = { { file = "vo\\b\\m\\Flw_BM001.mp3", subtitle = "Where are you going?" }, { file = "vo\\b\\m\\Hlo_BM105.mp3", subtitle = "You'd be wise to stay out of trouble, friend." }, { file = "vo\\b\\m\\Hlo_BM106.mp3", subtitle = "You would be wise to give up crime. It doesn't suit you." }, { file = "vo\\b\\m\\Srv_BM006.mp3", subtitle = "I'm watching you." } }, ["stop_sneaking"] = { { file = "vo\\b\\m\\Hlo_BM025.mp3", subtitle = "I don't have time for you." }, { file = "vo\\b\\m\\Srv_BM012.mp3", subtitle = "Do not waste my time." }, { file = "vo\\b\\m\\Hlo_BM017.mp3", subtitle = "What a revolting display." }, { file = "vo\\b\\m\\Hlo_BM000b.mp3", subtitle = "Humph." }, { file = "vo\\b\\m\\Hlo_BM000c.mp3", subtitle = "Humph." } }, ["stop_following"] = { { file = "vo\\b\\m\\Hlo_BM029.mp3", subtitle = "This is becoming most unpleasant." }, { file = "vo\\b\\m\\Hlo_BM028.mp3", subtitle = "You are beginning to annoy me." }, { file = "vo\\b\\m\\Hlo_BM025.mp3", subtitle = "I don't have time for you." }, { file = "vo\\b\\m\\Srv_BM012.mp3", subtitle = "Do not waste my time." }, { file = "vo\\b\\m\\Srv_BM003.mp3", subtitle = "You are repulsive. Please, go away." } }, ["join_combat"] = { { file = "vo\\b\\m\\CrAtk_BM005.mp3", subtitle = "Die!" }, { file = "vo\\b\\m\\Atk_BM013.mp3", subtitle = "I should have killed you sooner!" }, { file = "vo\\b\\m\\Atk_BM009.mp3", subtitle = "Soon you'll be reduced to dust!" }, { file = "vo\\b\\m\\Atk_BM006.mp3", subtitle = "Death awaits you!" }, { file = "vo\\b\\m\\Atk_BM004.mp3", subtitle = "You'll be dead soon!" } } } }, ["dark elf"] = { female = { ["sneaking"] = { { file = "vo\\d\\f\\Hlo_DF165.mp3", subtitle = "There are better ways than theft to earn a coin, outlander." }, { file = "vo\\d\\f\\Hlo_DF164.mp3", subtitle = "I find your crimes distasteful, outlander. Perhaps you should leave." }, { file = "vo\\d\\f\\tHlo_DF009.mp3", subtitle = "Who do you think you are?" } }, ["stop_sneaking"] = { { file = "vo\\d\\f\\Srv_DF045.mp3", subtitle = "Do not waste my time." }, { file = "vo\\d\\f\\Hlo_DF037.mp3", subtitle = "Annoying outlanders." }, { file = "vo\\d\\f\\Hlo_DF035.mp3", subtitle = "Keep moving, scum." }, { file = "vo\\d\\f\\tIdl_DF015.mp3", subtitle = "Damn foreigners..." } }, ["stop_following"] = { { file = "vo\\d\\f\\Srv_DF033.mp3", subtitle = "I find you foul and disgusting. Leave now." }, { file = "vo\\d\\f\\Srv_DF045.mp3", subtitle = "Do not waste my time." }, { file = "vo\\d\\f\\Hlo_DF094.mp3", subtitle = "I've got better things to do, so, if you don't mind, let's move this along." }, { file = "vo\\d\\f\\Hlo_DF046.mp3", subtitle = "If you'll excuse me, I don't have time for you right now. Or ever." }, { file = "vo\\d\\f\\Hlo_DF045.mp3", subtitle = "I'm late for an appointment. Hopefully somewhere away from you." }, { file = "vo\\d\\f\\Hlo_DF037.mp3", subtitle = "Annoying outlanders." } }, ["join_combat"] = { { file = "vo\\d\\f\\Atk_DF002.mp3", subtitle = "Your life's end is approaching." }, { file = "vo\\d\\f\\Atk_DF001.mp3", subtitle = "Now you die." }, { file = "vo\\d\\f\\Atk_DF005.mp3", subtitle = "This is the end of you, s'wit." }, { file = "vo\\d\\f\\Atk_DF008.mp3", subtitle = "You will suffer greatly!" }, { file = "vo\\d\\f\\Atk_DF003.mp3", subtitle = "Die, fetcher." }, { file = "vo\\d\\f\\Atk_DF004.mp3", subtitle = "You n'wah!" }, { file = "vo\\d\\f\\Hlo_DF027.mp3", subtitle = "Filthy s'wit!" }, { file = "vo\\d\\f\\Atk_DF013.mp3", subtitle = "Surrender your life to me and I will end your pain!" }, { file = "vo\\d\\f\\bAtk_DF002.mp3", subtitle = "Your head will be my new trophy!" }, { file = "vo\\d\\f\\bAtk_DF004.mp3", subtitle = "I've fought guars more ferocious than you!" }, { file = "vo\\d\\f\\bAtk_DF005.mp3", subtitle = "Your cursed bloodline ends here!" } } }, male = { ["sneaking"] = { { file = "vo\\d\\m\\Flw_DM001.mp3", subtitle = "Where are you going?" }, { file = "vo\\d\\m\\Idl_DM007.mp3", subtitle = "What was that?" }, { file = "vo\\d\\m\\Hlo_DM165.mp3", subtitle = "There are better ways than theft to earn a coin, outlander." } }, ["stop_sneaking"] = { { file = "vo\\d\\m\\Hlo_DM021.mp3", subtitle = "Bothersome creature." }, { file = "vo\\d\\m\\Hlo_DM001.mp3", subtitle = "Go away." }, { file = "vo\\d\\m\\Hlo_DM000b.mp3", subtitle = "Humph." }, { file = "vo\\d\\m\\Hlo_DM000c.mp3", subtitle = "Hmmph." } }, ["stop_following"] = { { file = "vo\\d\\m\\Hlo_DM111.mp3", subtitle = "Move along, outlander." }, { file = "vo\\d\\m\\Hlo_DM035.mp3", subtitle = "Keep moving, scum." }, { file = "vo\\d\\m\\Hlo_DM021.mp3", subtitle = "Bothersome creature." }, { file = "vo\\d\\m\\Hlo_DM000b.mp3", subtitle = "Humph." }, { file = "vo\\d\\m\\Hlo_DM000c.mp3", subtitle = "Hmmph." } }, ["join_combat"] = { { file = "vo\\d\\m\\CrAtk_AM005.mp3", subtitle = "Die!" }, { file = "vo\\d\\m\\CrAtk_AM005.mp3", subtitle = "Die!" }, { file = "vo\\d\\m\\Atk_DM005.mp3", subtitle = "This is the end of you, s'wit." }, { file = "vo\\d\\m\\Atk_DM002.mp3", subtitle = "Your life's end is approaching." }, { file = "vo\\d\\m\\Atk_DM001.mp3", subtitle = "Now you die." } } } }, ["high elf"] = { female = { ["sneaking"] = { { file = "vo\\h\\f\\Srv_HF012.mp3", subtitle = "If you don't leave now you will wish you had." }, { file = "vo\\h\\f\\Hlo_HF106.mp3", subtitle = "I won't tolerate any thievery if that's what you're thinking." }, { file = "vo\\h\\f\\Hlo_HF047.mp3", subtitle = "Keep your hands where I can see them, thief." } }, ["stop_sneaking"] = { { file = "vo\\h\\f\\Srv_HF003.mp3", subtitle = "Don't waste my time." }, { file = "vo\\h\\f\\Hlo_HF000b.mp3", subtitle = "Hmph!" }, { file = "vo\\h\\f\\Hlo_HF000c.mp3", subtitle = "Hmph!" }, { file = "vo\\h\\f\\Hlo_HF000e.mp3", subtitle = "Get out of here." } }, ["stop_following"] = { { file = "vo\\h\\f\\Hlo_HF059.mp3", subtitle = "My patience is limited." }, { file = "vo\\h\\f\\Hlo_HF028.mp3", subtitle = "You creatures are all the same." }, { file = "vo\\h\\f\\Hlo_HF000d.mp3", subtitle = "Clearly, you are an idiot." }, { file = "vo\\h\\f\\Hlo_HF001.mp3", subtitle = "I haven't any time for you now." }, { file = "vo\\h\\f\\Hlo_HF000e.mp3", subtitle = "Get out of here." }, { file = "vo\\h\\f\\Idl_HF002.mp3", subtitle = "If that creature visits again, I think I'll have choice words to say." } }, ["join_combat"] = { { file = "vo\\h\\f\\CrAtk_HF005.mp3", subtitle = "Die!" }, { file = "vo\\h\\f\\Atk_HF013.mp3", subtitle = "You'll soon be nothing more than a bad memory!" }, { file = "vo\\h\\f\\Atk_HF014.mp3", subtitle = "I shall enjoy watching you take your last breath." }, { file = "vo\\h\\f\\Atk_HF012.mp3", subtitle = "Embrace your demise!" } } }, male = { ["sneaking"] = { { file = "vo\\h\\m\\Hlo_HM106.mp3", subtitle = "I won't tolerate any thievery if that's what you're thinking." }, { file = "vo\\h\\m\\Hlo_HM047.mp3", subtitle = "Keep your hands where I can see them, thief." }, { file = "vo\\h\\m\\Srv_HM012.mp3", subtitle = "If I see you shoplift, you will pay with your life!" }, { file = "vo\\h\\m\\Hlo_HM089.mp3", subtitle = "Do you want something?" } }, ["stop_sneaking"] = { { file = "vo\\h\\m\\Hlo_HM028.mp3", subtitle = "You creatures are all the same." }, { file = "vo\\h\\m\\Srv_HM003.mp3", subtitle = "Don't waste my time." }, { file = "vo\\h\\m\\Srv_HM006.mp3", subtitle = "You try my patience." }, { file = "vo\\h\\m\\Hlo_HM000c.mp3", subtitle = "Humph!" } }, ["stop_following"] = { { file = "vo\\h\\m\\Hlo_HM059.mp3", subtitle = "My patience is limited." }, { file = "vo\\h\\m\\Srv_HM006.mp3", subtitle = "You try my patience." }, { file = "vo\\h\\m\\Hlo_HM001.mp3", subtitle = "I haven't any time for you now." }, { file = "vo\\h\\m\\Hlo_HM000d.mp3", subtitle = "I won't waste my time on the likes of you!" }, { file = "vo\\h\\m\\Hlo_HM000c.mp3", subtitle = "Humph!" } }, ["join_combat"] = { { file = "vo\\h\\m\\Atk_HM014.mp3", subtitle = "I shall enjoy watching you take your last breath." }, { file = "vo\\h\\m\\Atk_HM013.mp3", subtitle = "You'll soon be nothing more than a bad memory!" }, { file = "vo\\h\\m\\Atk_HM012.mp3", subtitle = "Embrace your demise!" }, { file = "vo\\h\\m\\Atk_HM007.mp3", subtitle = "You will die in disgrace." } } } }, imperial = { female = { ["sneaking"] = { { file = "vo\\i\\f\\Srv_IF009.mp3", subtitle = "I've got my eye on you." }, { file = "vo\\i\\f\\Hlo_IF128.mp3", subtitle = "Stay out of trouble and you'll have none from me." }, { file = "vo\\i\\f\\Hlo_IF057.mp3", subtitle = "Stay out of trouble, and you won't get hurt." }, { file = "vo\\i\\f\\Hlo_IF071.mp3", subtitle = "Watch your step." }, { file = "vo\\i\\f\\Hlo_IF070.mp3", subtitle = "Don't try anything funny." }, { file = "vo\\i\\f\\Hlo_IF007.mp3", subtitle = "Are you here to start trouble, or are you just stupid?" }, { file = "vo\\i\\f\\tHlo_IF003.mp3", subtitle = "Crime doesn't pay." } }, ["stop_sneaking"] = { { file = "vo\\i\\f\\Hlo_IF011.mp3", subtitle = "So tiresome." }, { file = "vo\\i\\f\\Idl_IF002.mp3", subtitle = "I don't know if I like this." }, { file = "vo\\i\\f\\Hlo_IF006.mp3", subtitle = "What a pathetic excuse for a criminal." } }, ["stop_following"] = { { file = "vo\\i\\f\\Srv_IF021.mp3", subtitle = "I think we're done here. Please leave." }, { file = "vo\\i\\f\\Hlo_IF011.mp3", subtitle = "So tiresome." }, { file = "vo\\i\\f\\Hlo_IF006.mp3", subtitle = "What a pathetic excuse for a criminal." }, { file = "vo\\i\\f\\Hlo_IF000d.mp3", subtitle = "I wouldn't waste my time on the likes of you!" }, { file = "vo\\i\\f\\bIdl_IF003.mp3", subtitle = "My mother warned me about mooks like you." }, { file = "vo\\i\\f\\bIdl_IF013.mp3", subtitle = "[Wide yawn.]" } }, ["join_combat"] = { { file = "vo\\i\\f\\Atk_IF010.mp3", subtitle = "Die, scoundrel!" }, { file = "vo\\i\\f\\Atk_IF014.mp3", subtitle = "This is pointless, give in!" }, { file = "vo\\i\\f\\Atk_IF005.mp3", subtitle = "You won't escape me that easily!" }, { file = "vo\\i\\f\\bAtk_IF005.mp3", subtitle = "Your head will be my new trophy!" }, { file = "vo\\i\\f\\bAtk_IF008.mp3", subtitle = "Your cursed bloodline ends here!" } } }, male = { ["sneaking"] = { { file = "vo\\i\\m\\Hlo_IM007.mp3", subtitle = "Are you here to start trouble, or are you just stupid?" }, { file = "vo\\i\\m\\Flw_IM001.mp3", subtitle = "Where are you going?" }, { file = "vo\\i\\m\\Hlo_IM057.mp3", subtitle = "Stay out of trouble and you won't get hurt." } }, ["stop_sneaking"] = { { file = "vo\\i\\m\\bIdl_IM028.mp3", subtitle = "Just as well..." }, { file = "vo\\i\\m\\Hlo_IM000e.mp3", subtitle = "Get out of here." }, { file = "vo\\i\\m\\Srv_IM027.mp3", subtitle = "You are a nuisance to me. Please leave." } }, ["stop_following"] = { { file = "vo\\i\\m\\Hlo_IM000e.mp3", subtitle = "Get out of here." }, { file = "vo\\i\\m\\Srv_IM027.mp3", subtitle = "You are a nuisance to me. Please leave." }, { file = "vo\\i\\m\\Hlo_IM006.mp3", subtitle = "What a pathetic excuse for a criminal!" } }, ["join_combat"] = { { file = "vo\\i\\m\\Atk_IM009.mp3", subtitle = "Die, scoundrel!" }, { file = "vo\\i\\m\\CrAtk_IM005.mp3", subtitle = "Die!" }, { file = "vo\\i\\m\\Atk_IM010.mp3", subtitle = "You're hardly a match for me!" }, { file = "vo\\i\\m\\Atk_IM007.mp3", subtitle = "Let's see what you're made of!" }, { file = "vo\\i\\m\\Hlo_IM004.mp3", subtitle = "Since you're already on death's door, may I open it for you?" }, { file = "vo\\i\\m\\Hlo_IM018.mp3", subtitle = "You're a disgrace to the Empire." }, { file = "vo\\i\\m\\Hlo_IM000d.mp3", subtitle = "You're about to find more trouble than you can possibly imagine." } } } }, khajiit = { female = { ["sneaking"] = { { file = "vo\\k\\f\\Hlo_KF106.mp3", subtitle = "You are too easily caught." }, { file = "vo\\k\\f\\Hlo_KF041.mp3", subtitle = "Why is it here?" }, { file = "vo\\k\\f\\Hlo_KF019.mp3", subtitle = "You are trouble. Khajiit know this." }, { file = "vo\\k\\f\\Hlo_KF017.mp3", subtitle = "Does it want to feel Khajiiti claws?" } }, ["stop_sneaking"] = { { file = "vo\\k\\f\\Hlo_KF016.mp3", subtitle = "Disgusting thing. Leave now." }, { file = "vo\\k\\f\\Hlo_KF053.mp3", subtitle = "You do not please us." }, { file = "vo\\k\\f\\Hlo_KF021.mp3", subtitle = "It will leave. Now." }, { file = "vo\\k\\f\\Hlo_KF000b.mp3", subtitle = "Hmmph!" }, { file = "vo\\k\\f\\Hlo_KF000c.mp3", subtitle = "Grrfph!" } }, ["stop_following"] = { { file = "vo\\k\\f\\Srv_KF009.mp3", subtitle = "Annoying creature! It should go away." }, { file = "vo\\k\\f\\Hlo_KF016.mp3", subtitle = "Disgusting thing. Leave now." }, { file = "vo\\k\\f\\Hlo_KF000d.mp3", subtitle = "I won't waste my time on the likes of you." }, { file = "vo\\k\\f\\Hlo_KF026.mp3", subtitle = "So little manners, so little time." } }, ["join_combat"] = { { file = "vo\\k\\f\\Atk_KF014.mp3", subtitle = "This one is no more." }, { file = "vo\\k\\f\\Atk_KF015.mp3", subtitle = "This one is no more." }, { file = "vo\\k\\f\\CrAtk_KF005.mp3", subtitle = "Die!" }, { file = "vo\\k\\f\\Atk_KF010.mp3", subtitle = "So small and tasty. I will enjoy eating you." }, { file = "vo\\k\\f\\Fle_KF004.mp3", subtitle = "You had your chance!" } } }, male = { ["sneaking"] = { { file = "vo\\k\\m\\Hlo_KM041.mp3", subtitle = "Why is it here?" }, { file = "vo\\k\\m\\Hlo_KM106.mp3", subtitle = "You are too easily caught." }, { file = "vo\\k\\m\\Hlo_KM019.mp3", subtitle = "You are trouble. Khajiit know this." }, { file = "vo\\k\\m\\Hlo_KM017.mp3", subtitle = "Does it want to feel Khajiiti claws?" } }, ["stop_sneaking"] = { { file = "vo\\k\\m\\Srv_KM006.mp3", subtitle = "This one should leave." }, { file = "vo\\k\\m\\Hlo_KM053.mp3", subtitle = "You do not please us." }, { file = "vo\\k\\m\\Hlo_KM021.mp3", subtitle = "It will leave. Now." }, { file = "vo\\k\\m\\Hlo_KM016.mp3", subtitle = "Disgusting thing. Leave now." } }, ["stop_following"] = { { file = "vo\\k\\m\\Hlo_KM022.mp3", subtitle = "Go away! Do not come back!" }, { file = "vo\\k\\m\\Hlo_KM053.mp3", subtitle = "You do not please us." }, { file = "vo\\k\\m\\Hlo_KM016.mp3", subtitle = "Disgusting thing. Leave now." }, { file = "vo\\k\\m\\Hlo_KM026.mp3", subtitle = "So little manners, so little time." } }, ["join_combat"] = { { file = "vo\\k\\m\\Atk_KM014.mp3", subtitle = "This one is no more." }, { file = "vo\\k\\m\\Atk_KM015.mp3", subtitle = "This one is no more!" }, { file = "vo\\k\\m\\Atk_KM010.mp3", subtitle = "So small and tasty. I will enjoy eating you." }, { file = "vo\\k\\m\\bAtk_KM004.mp3", subtitle = "I’ve fought guars more ferocious than you!" } } } }, nord = { female = { ["sneaking"] = { { file = "vo\\n\\f\\Hlo_NF106.mp3", subtitle = "Hmm. You're not here to start trouble, are you?" }, { file = "vo\\n\\f\\Hlo_NF087.mp3", subtitle = "What's this all about?" }, { file = "vo\\n\\f\\Hlo_NF059.mp3", subtitle = "You like to walk a fine line, don't you?" }, { file = "vo\\n\\f\\Hlo_NF047.mp3", subtitle = "I've got no patience for petty criminals. Move on." } }, ["stop_sneaking"] = { { file = "vo\\n\\f\\Srv_NF009.mp3", subtitle = "You must be joking! Go away!" }, { file = "vo\\n\\f\\Hlo_NF077.mp3", subtitle = "On your way." }, { file = "vo\\n\\f\\Hlo_NF030.mp3", subtitle = "I think you should keep walking." }, { file = "vo\\n\\f\\Hlo_NF022.mp3", subtitle = "Get out of here before you get hurt." } }, ["stop_following"] = { { file = "vo\\n\\f\\Hlo_NF055.mp3", subtitle = "By the gods! You tourists are a nuisance!" }, { file = "vo\\n\\f\\Hlo_NF022.mp3", subtitle = "Get out of here before you get hurt." }, { file = "vo\\n\\f\\Hlo_NF000d.mp3", subtitle = "I won't waste my time on the likes of you." }, { file = "vo\\n\\f\\bIdl_NF021.mp3", subtitle = "[Wide yawn.]" } }, ["join_combat"] = { { file = "vo\\n\\f\\CrAtk_NF005.mp3", subtitle = "Die!" }, { file = "vo\\n\\f\\Atk_NF015.mp3", subtitle = "Face death!" }, { file = "vo\\n\\f\\Atk_NF007.mp3", subtitle = "I will bathe in your blood." }, { file = "vo\\n\\f\\Atk_NF004.mp3", subtitle = "Fool!" }, { file = "vo\\n\\f\\bAtk_NF002.mp3", subtitle = "Your cursed bloodline ends here!" } } }, male = { ["sneaking"] = { { file = "vo\\n\\m\\Hlo_NM106.mp3", subtitle = "Hello. Hmm. You're not here to start trouble, are you?" }, { file = "vo\\n\\m\\Hlo_NM087.mp3", subtitle = "What's this all about?" }, { file = "vo\\n\\m\\Hlo_NM059.mp3", subtitle = "You like to dance close to the fire, don't you?" }, { file = "vo\\n\\m\\Hlo_NM047.mp3", subtitle = "I've got no patience for petty criminals. Move on." } }, ["stop_sneaking"] = { { file = "vo\\n\\m\\Hlo_NM077.mp3", subtitle = "On your way." }, { file = "vo\\n\\m\\Hlo_NM017.mp3", subtitle = "You must be joking." }, { file = "vo\\n\\m\\Hlo_NM022.mp3", subtitle = "Get out of here, before you get hurt!" }, { file = "vo\\n\\m\\Hlo_NM022.mp3", subtitle = "Get out of here, before you get hurt!" } }, ["stop_following"] = { { file = "vo\\n\\m\\Hlo_NM055.mp3", subtitle = "By the gods! You tourists are a nuisance!" }, { file = "vo\\n\\m\\Hlo_NM022.mp3", subtitle = "Get out of here before you get hurt." }, { file = "vo\\n\\m\\Srv_NM003.mp3", subtitle = "Do not waste my time!" }, { file = "vo\\n\\m\\bIdl_NM016.mp3", subtitle = "[Wide yawn.]" } }, ["join_combat"] = { { file = "vo\\n\\m\\Atk_NM020.mp3", subtitle = "It will be your blood here, not mine!" }, { file = "vo\\n\\m\\Atk_NM007.mp3", subtitle = "I will bathe in your blood." }, { file = "vo\\n\\m\\Atk_NM004.mp3", subtitle = "Fool!" }, { file = "vo\\n\\m\\bAtk_NM002.mp3", subtitle = "Your cursed bloodline ends here!" } } } }, orc = { female = { ["sneaking"] = { { file = "vo\\o\\f\\Hlo_OF018.mp3", subtitle = "We cut off the hand that steals. Know this, thief." }, { file = "vo\\o\\f\\Hlo_OF106.mp3", subtitle = "I know of your taste for crime. Be warned." }, { file = "vo\\o\\f\\Hlo_OF044.mp3", subtitle = "What are you supposed to be?" }, { file = "vo\\o\\f\\Idl_OF009.mp3", subtitle = "Finally something interesting." } }, ["stop_sneaking"] = { { file = "vo\\o\\f\\Srv_OF003.mp3", subtitle = "Get out! You'll give this place a bad name." }, { file = "vo\\o\\f\\Hlo_OF056.mp3", subtitle = "Do not waste my time." }, { file = "vo\\o\\f\\Hlo_OF023.mp3", subtitle = "I haven't time for fools." }, { file = "vo\\o\\f\\Hlo_OF026.mp3", subtitle = "So annoying." } }, ["stop_following"] = { { file = "vo\\o\\f\\Hlo_OF056.mp3", subtitle = "Do not waste my time." }, { file = "vo\\o\\f\\Hlo_OF026.mp3", subtitle = "So annoying." }, { file = "vo\\o\\f\\Hlo_OF025.mp3", subtitle = "You're hardly worth my time." }, { file = "vo\\o\\f\\Hlo_OF023.mp3", subtitle = "I haven't time for fools." } }, ["join_combat"] = { { file = "vo\\o\\f\\CrAtk_OF005.mp3", subtitle = "Die!" }, { file = "vo\\o\\f\\Atk_OF015.mp3", subtitle = "Our blood is made for fighting!" }, { file = "vo\\o\\f\\Atk_OF005.mp3", subtitle = "Now you die." }, { file = "vo\\o\\f\\Atk_OF003.mp3", subtitle = "No surrender! No mercy!" } } }, male = { ["sneaking"] = { { file = "vo\\o\\m\\Hlo_OM018.mp3", subtitle = "We cut of the hand that steals. Know this, thief." }, { file = "vo\\o\\m\\Hlo_OM106.mp3", subtitle = "I know of your taste for crime. Be warned." }, { file = "vo\\o\\m\\Hlo_OM055.mp3", subtitle = "What are you doing?" }, { file = "vo\\o\\m\\Hlo_OM024.mp3", subtitle = "Do you seek a fight with me? If not, leave." } }, ["stop_sneaking"] = { { file = "vo\\o\\m\\Srv_OM006.mp3", subtitle = "Bother me again and I'll rip your arm off." }, { file = "vo\\o\\m\\Hlo_OM056.mp3", subtitle = "Do not waste my time." }, { file = "vo\\o\\m\\Hlo_OM026.mp3", subtitle = "Annoying creature." }, { file = "vo\\o\\m\\Hlo_OM023.mp3", subtitle = "I haven't time for fools." } }, ["stop_following"] = { { file = "vo\\o\\m\\Srv_OM006.mp3", subtitle = "Bother me again and I'll rip your arm off." }, { file = "vo\\o\\m\\Hlo_OM056.mp3", subtitle = "Do not waste my time." }, { file = "vo\\o\\m\\Hlo_OM025.mp3", subtitle = "You're hardly worth my time." }, { file = "vo\\o\\m\\Hlo_OM023.mp3", subtitle = "I haven't time for fools." } }, ["join_combat"] = { { file = "vo\\o\\m\\CrAtk_OM005.mp3", subtitle = "Die!" }, { file = "vo\\o\\m\\Atk_OM015.mp3", subtitle = "Our blood is made for fighting!" }, { file = "vo\\o\\m\\Atk_OM011.mp3", subtitle = "I will kill you quickly." }, { file = "vo\\o\\m\\Atk_OM013.mp3", subtitle = "Your bones will be my dinner." } } } }, redguard = { female = { ["sneaking"] = { { file = "vo\\r\\f\\Hlo_RF118.mp3", subtitle = "Well, what have we here?" }, { file = "vo\\r\\f\\Hlo_RF106.mp3", subtitle = "You might consider a less hazardous profession, thief." }, { file = "vo\\r\\f\\Hlo_RF055.mp3", subtitle = "There's something not right about you. Maybe you should go." }, { file = "vo\\r\\f\\Hlo_RF054.mp3", subtitle = "How do I know you're not up to something devious?" }, { file = "vo\\r\\f\\Hlo_RF024.mp3", subtitle = "If you're looking for trouble, you're getting very warm." }, { file = "vo\\r\\f\\Thf_RF001.mp3", subtitle = "Not on my watch, thief." } }, ["stop_sneaking"] = { { file = "vo\\r\\f\\Hlo_RF027.mp3", subtitle = "Keep walking." }, { file = "vo\\r\\f\\Hlo_RF022.mp3", subtitle = "Get lost." }, { file = "vo\\r\\f\\Hlo_RF001.mp3", subtitle = "I think it would be best if you leave. Now." }, { file = "vo\\r\\f\\Hlo_RF000b.mp3", subtitle = "Humph." } }, ["stop_following"] = { { file = "vo\\r\\f\\Hlo_RF046.mp3", subtitle = "I don't want any part of this. Whatever it is." }, { file = "vo\\r\\f\\Hlo_RF000b.mp3", subtitle = "Humph." }, { file = "vo\\r\\f\\Hlo_RF000d.mp3", subtitle = "I won't waste my time on the likes of you." }, { file = "vo\\r\\f\\Atk_RF004.mp3", subtitle = "Stupid fetcher!" } }, ["join_combat"] = { { file = "vo\\r\\f\\CrAtk_RF005.mp3", subtitle = "Die!" }, { file = "vo\\r\\f\\Atk_RF010.mp3", subtitle = "You'll be dead soon." }, { file = "vo\\r\\f\\Atk_RF014.mp3", subtitle = "Run or die!" }, { file = "vo\\r\\f\\Atk_RF007.mp3", subtitle = "Run while you can." } } }, male = { ["sneaking"] = { { file = "vo\\r\\m\\Hlo_RM118.mp3", subtitle = "Well, what have we here?" }, { file = "vo\\r\\m\\Hlo_RM106.mp3", subtitle = "You might consider a less hazardous profession, thief." }, { file = "vo\\r\\m\\Hlo_RM055.mp3", subtitle = "There's something not right about you. Maybe you should go." }, { file = "vo\\r\\m\\Hlo_RM054.mp3", subtitle = "How do I know you're not up to something devious?" }, { file = "vo\\r\\m\\Hlo_RM024.mp3", subtitle = "If you're looking for trouble, you're getting very warm." }, { file = "vo\\r\\m\\Thf_RM001.mp3", subtitle = "Not on my watch, thief." } }, ["stop_sneaking"] = { { file = "vo\\r\\m\\Hlo_RM027.mp3", subtitle = "Keep walking." }, { file = "vo\\r\\m\\Hlo_RM022.mp3", subtitle = "Get lost." }, { file = "vo\\r\\m\\Hlo_RM001.mp3", subtitle = "I think it would be best if you leave. Now." }, { file = "vo\\r\\m\\Fle_RM002.mp3", subtitle = "We're done here." } }, ["stop_following"] = { { file = "vo\\r\\m\\Hlo_RM046.mp3", subtitle = "I don't want any part of this. Whatever it is." }, { file = "vo\\r\\m\\Hlo_RM044.mp3", subtitle = "Stop wasting my time with your foolishness!" }, { file = "vo\\r\\m\\Hlo_RM022.mp3", subtitle = "Get lost." }, { file = "vo\\r\\m\\Srv_RM003.mp3", subtitle = "It ... should leave!" } }, ["join_combat"] = { { file = "vo\\r\\m\\Atk_RM016.mp3", subtitle = "I hope you suffer!" }, { file = "vo\\r\\m\\Atk_RM010.mp3", subtitle = "You'll be dead soon." }, { file = "vo\\r\\m\\Atk_RM014.mp3", subtitle = "Here it comes!" }, { file = "vo\\r\\m\\Atk_RM007.mp3", subtitle = "Run while you can." } } } }, ["wood elf"] = { female = { ["sneaking"] = { { file = "vo\\w\\f\\Hlo_WF106.mp3", subtitle = "Criminals should dealt with harshly, don't you think?" }, { file = "vo\\w\\f\\Hlo_WF083.mp3", subtitle = "What is this about?" }, { file = "vo\\w\\f\\Hlo_WF024.mp3", subtitle = "You'll get more than you bargained for from me." }, { file = "vo\\w\\f\\Hlo_WF000d.mp3", subtitle = "You don't want to see me angry." } }, ["stop_sneaking"] = { { file = "vo\\w\\f\\Hlo_WF025.mp3", subtitle = "I really don't want you around here." }, { file = "vo\\w\\f\\Hlo_WF023.mp3", subtitle = "Useless tourists." }, { file = "vo\\w\\f\\Hlo_WF028.mp3", subtitle = "I don't like you much, stranger." }, { file = "vo\\w\\f\\Hlo_WF019.mp3", subtitle = "You're a disgrace." } }, ["stop_following"] = { { file = "vo\\w\\f\\Srv_WF009.mp3", subtitle = "You offend me!" }, { file = "vo\\w\\f\\Atk_WF002.mp3", subtitle = "Fetcher!" }, { file = "vo\\w\\f\\Hlo_WF055.mp3", subtitle = "Too much trouble. Must be going now." }, { file = "vo\\w\\f\\Hlo_WF054.mp3", subtitle = "I'm sure this is important, but I really must go." } }, ["join_combat"] = { { file = "vo\\w\\f\\CrAtk_WF005.mp3", subtitle = "Die!" }, { file = "vo\\w\\f\\Atk_WF001.mp3", subtitle = "Now you're going to get it." }, { file = "vo\\w\\f\\Atk_WF009.mp3", subtitle = "One of us will die here and it won't be me." }, { file = "vo\\w\\f\\Atk_WF008.mp3", subtitle = "Run while you can." } } }, male = { ["sneaking"] = { { file = "vo\\w\\m\\Hlo_WM106.mp3", subtitle = "Criminals should dealt with harshly, don't you think?" }, { file = "vo\\w\\m\\Hlo_WM083.mp3", subtitle = "What is this about?" }, { file = "vo\\w\\m\\Hlo_WM024.mp3", subtitle = "You'll get more than you bargained for from me." }, { file = "vo\\w\\m\\Hlo_WM046.mp3", subtitle = "The laws are harsh for thieves. Including yourself." } }, ["stop_sneaking"] = { { file = "vo\\w\\m\\Hlo_WM025.mp3", subtitle = "I really don't want you around here." }, { file = "vo\\w\\m\\Hlo_WM023.mp3", subtitle = "Useless tourists." }, { file = "vo\\w\\m\\Hlo_WM028.mp3", subtitle = "I don't like you much." }, { file = "vo\\w\\m\\Hlo_WM019.mp3", subtitle = "You're a disgrace." } }, ["stop_following"] = { { file = "vo\\w\\m\\Hlo_WM027.mp3", subtitle = "Can't you find someone else to bother?" }, { file = "vo\\w\\m\\Atk_WM002.mp3", subtitle = "Fetcher!" }, { file = "vo\\w\\m\\Hlo_WM055.mp3", subtitle = "Too much trouble. Must be going now." }, { file = "vo\\w\\m\\Hlo_WM054.mp3", subtitle = "I'm sure this is important, but I really must go." } }, ["join_combat"] = { { file = "vo\\w\\m\\Atk_WM003.mp3", subtitle = "You don't deserve to live." }, { file = "vo\\w\\m\\Atk_WM001.mp3", subtitle = "Now you're going to get it." }, { file = "vo\\w\\m\\Atk_WM009.mp3", subtitle = "One of us will die here and it won't be me." }, { file = "vo\\w\\m\\Atk_WM008.mp3", subtitle = "Run while you can." } } } }, ordinator = { male = { ["sneaking"] = { { file = "vo\\ord\\Hlo_ORM008.mp3", subtitle = "Watch yourself. We'll have no trouble here." }, { file = "vo\\ord\\Hlo_ORM004.mp3", subtitle = "If you're here for trouble, you'll get more than you bargained for." }, { file = "vo\\ord\\Hlo_ORM003.mp3", subtitle = "We're watching you. Scum." } }, ["stop_sneaking"] = { { file = "vo\\ord\\Hlo_ORM001.mp3", subtitle = "Grrrr." }, { file = "vo\\ord\\Hlo_ORM009.mp3", subtitle = "Go on about your business." }, { file = "vo\\ord\\Hlo_ORM007.mp3", subtitle = "Keep moving." }, { file = "vo\\ord\\Hlo_ORM011.mp3", subtitle = "Move along." } }, ["stop_following"] = { { file = "vo\\ord\\Hlo_ORM011.mp3", subtitle = "Move along." }, { file = "vo\\ord\\Hlo_ORM009.mp3", subtitle = "Go on about your business." }, { file = "vo\\ord\\Hlo_ORM007.mp3", subtitle = "Keep moving." }, { file = "vo\\ord\\Hlo_ORM002.mp3", subtitle = "Go. Now." } }, ["join_combat"] = { { file = "vo\\ord\\Atk_ORM002.mp3", subtitle = "Fool!" }, { file = "vo\\ord\\Atk_ORM003.mp3", subtitle = "You have sealed your fate!" }, { file = "vo\\ord\\Atk_ORM004.mp3", subtitle = "You cannot escape the righteous!" }, { file = "vo\\ord\\Atk_ORM005.mp3", subtitle = "You will pay with your blood!" }, { file = "vo\\ord\\Atk_ORM001.mp3", subtitle = "May our Lords be merciful!" } } } } } -- TR voices voices["t_els_cathay"] = voices.khajiit voices["t_els_cathay-raht"] = voices.khajiit voices["t_els_ohmes"] = voices.khajiit voices["t_els_ohmes-raht"] = voices.khajiit voices["t_els_suthay"] = voices.khajiit voices["t_sky_reachman"] = voices.breton -- todo: combine Nord + Breton -- actually that would be weird so I guess this is fine voices["t_pya_seaelf"] = voices["high elf"] -- todo: something better return voices
return function(scene, dt) for entity in pairs(scene:entities_with('animation', 'remove_when_animation_complete')) do if entity.animation:is_complete() then scene:remove_entity(entity) end end end
-- Copyright 2022 SmartThings -- -- 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. -- Mock out globals local test = require "integration_test" local clusters = require "st.zigbee.zcl.clusters" local OnOff = clusters.OnOff local capabilities = require "st.capabilities" local zigbee_test_utils = require "integration_test.zigbee_test_utils" local t_utils = require "integration_test.utils" local mock_simple_device = test.mock_device.build_test_zigbee_device( { profile = t_utils.get_profile_definition("switch-3.yml"), fingerprinted_endpoint_id = 0x01 } ) zigbee_test_utils.prepare_zigbee_env_info() local function test_init() test.mock_device.add_test_device(mock_simple_device) zigbee_test_utils.init_noop_health_check_timer() end test.set_test_init_function(test_init) test.register_message_test( "Reported on off status should be handled: on ep 1", { { channel = "zigbee", direction = "receive", message = { mock_simple_device.id, OnOff.attributes.OnOff:build_test_attr_report(mock_simple_device, true):from_endpoint(0x01) } }, { channel = "capability", direction = "send", message = mock_simple_device:generate_test_message("switch1", capabilities.switch.switch.on()) } } ) test.register_message_test( "Reported on off status should be handled: on ep 2", { { channel = "zigbee", direction = "receive", message = { mock_simple_device.id, OnOff.attributes.OnOff:build_test_attr_report(mock_simple_device, true):from_endpoint(0x02) } }, { channel = "capability", direction = "send", message = mock_simple_device:generate_test_message("switch2", capabilities.switch.switch.on()) } } ) test.register_message_test( "Reported on off status should be handled: on ep 3", { { channel = "zigbee", direction = "receive", message = { mock_simple_device.id, OnOff.attributes.OnOff:build_test_attr_report(mock_simple_device, true):from_endpoint(0x03) } }, { channel = "capability", direction = "send", message = mock_simple_device:generate_test_message("switch3", capabilities.switch.switch.on()) } } ) test.register_message_test( "Reported on off status should be handled: off ep 1", { { channel = "zigbee", direction = "receive", message = { mock_simple_device.id, OnOff.attributes.OnOff:build_test_attr_report(mock_simple_device, false):from_endpoint(0x01) } }, { channel = "capability", direction = "send", message = mock_simple_device:generate_test_message("switch1", capabilities.switch.switch.off()) } } ) test.register_message_test( "Capability command switch on should be handled", { { channel = "capability", direction = "receive", message = { mock_simple_device.id, { capability = "switch", component = "switch3", command = "on", args = { } } } }, { channel = "zigbee", direction = "send", message = { mock_simple_device.id, OnOff.server.commands.On(mock_simple_device):to_endpoint(0x03) } } } ) test.run_registered_tests()
require 'dp' local SaveModel, parent = torch.class("dp.SaveModel","dp.SaveToFile") SaveModel.isSaveModel = true function SaveModel:__init(config) parent.__init(self) end function SaveModel:save(subject, current_error) assert(subject, "SaveModel: subject is nil") local subject_path = subject:id():toPath() local save_dir = paths.concat(self._save_dir, subject_path) local model_dir = paths.concat(save_dir, 'model') --creates directories if required os.execute('mkdir -p ' .. model_dir) model_name = model_name or 'model.dat' local filename = paths.concat(model_dir, 'model.dat') dp.vprint(self._verbose, 'SaveModel: saving to '.. filename..' with validation error of '..current_error) torch.save(filename, {validation_error = current_error, model = subject._model}) end --[[ function SaveModel:doneExperiment(report) dp.vprint(self._verbose, 'Saving the model of the last epoch...') self:save(self._subject,0,"final_model.dat") end --]]
-- See LICENSE for terms local WaitMsg = WaitMsg local CreateRealTimeThread = CreateRealTimeThread local function UpdateList(dlg) WaitMsg("OnRender") if not dlg.idPOIList then return end local const = const --~ ex(buttons) local buttons = dlg.idPOIList or "" for i = 1, #buttons do local button = buttons[i] local context = button.context button.RolloverTemplate = "Rollover" button.RolloverTitle = context.display_name and T(context.display_name) or T(126095410863, "Info") local desc = context.description and T(context.description) .. "\n\n" or "" local str_resources = "" local str_time = "" local str_outcome = "" local str_rocket = "" local spot = context.spot_type -- show res needed if spot == "project" then local resources = context:GetRocketResources() if next(resources) then local inventory = {} local c = 0 for j = 1, #resources do local text = resources[j]:GetText() if text ~= "" then c = c + 1 inventory[c] = text end end if c > 0 then str_resources = T(387987656324, "Additional Inventory") .. "<right>" .. table.concat(inventory, " ") end end elseif spot == "anomaly" then local requirements = context.requirements if next(requirements) then local inventory = {} local c = 0 if requirements.num_crew then local specialization = const.ColonistSpecialization[requirements.crew_specialization] local name = specialization and specialization.display_name or T(3609, "Any") c = c + 1 inventory[c] = T{11539, "<colonist(colonists)>", colonists = requirements.num_crew} .. " " .. name end if requirements.num_drones or requirements.rover_type then if requirements.num_drones then c = c + 1 inventory[c] = T{11180, "<drone(num)>", num = requirements.num_drones} end if requirements.rover_type then c = c + 1 inventory[c] = g_Classes[requirements.rover_type].display_name end end if requirements.required_resources then local resources = requirements.required_resources or "" for j = 1, #resources do local text = resources[j]:GetText() if text ~= "" then c = c + 1 inventory[c] = text end end end str_resources = T(387987656324, "Additional Inventory") .. "<right>" .. table.concat(inventory, " ") end end local newline = (str_resources == "" and "" or "\n") -- time it'll take if spot == "project" or spot == "anomaly" then -- change colour of stuff with a rocket "on the way" if IsValid(context.rocket) then button.idText:SetTextStyle("Action") str_rocket = newline .. "<left>" .. T(1685, "Rocket") .. "<right>" .. T{"<DisplayName>", context.rocket} end if not context.rocket and context.expedition_time then str_time = context.expedition_time elseif not context.rocket or not context.rocket.expedition_return_time then str_time = RocketExpedition.ExpeditionTime * 2 end if str_time ~= "" then str_time = newline .. "<left>" .. T(874227567877, "Expedition time") .. "<right>" .. T{11604, "<time(time)>", time = str_time} end end -- what you get if context.ShowOutcomeText and context:ShowOutcomeText() then str_outcome = newline .. "<left>" .. T(130571839539, "Outcome") .. "<right>" .. context:GetOutcomeText() end button:SetRolloverText(desc .. str_resources .. str_time .. str_outcome .. str_rocket) end end local orig_GetSortedMarsPointsOfInterest = GetSortedMarsPointsOfInterest function GetSortedMarsPointsOfInterest(...) if Dialogs.PlanetaryView then CreateRealTimeThread(UpdateList, Dialogs.PlanetaryView) end return orig_GetSortedMarsPointsOfInterest(...) end
dofile("table_show.lua") dofile("urlcode.lua") local urlparse = require("socket.url") local http = require("socket.http") JSON = (loadfile "JSON.lua")() local item_dir = os.getenv("item_dir") local warc_file_base = os.getenv("warc_file_base") local item_type = nil local item_name = nil local item_value = nil local item_wiki = nil local selftext = nil if urlparse == nil or http == nil then io.stdout:write("socket not corrently installed.\n") io.stdout:flush() abortgrab = true end local url_count = 0 local tries = 0 local downloaded = {} local addedtolist = {} local abortgrab = false local outlinks = {} local discovered_items = {} local bad_items = {} local ids = {} for ignore in io.open("ignore-list", "r"):lines() do downloaded[ignore] = true end abort_item = function(item) abortgrab = true if not item then item = item_name end if not bad_items[item] then io.stdout:write("Aborting item " .. item .. ".\n") io.stdout:flush() bad_items[item] = true end end read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end processed = function(url) if downloaded[url] or addedtolist[url] then return true end return false end discover_item = function(item) discovered_items[item] = true end allowed = function(url, parenturl) if string.match(url, "[%?&]mobileaction=") or string.match(url, "/wiki/Special:[A-Za-z0-9]+[^A-Za-z0-9]") or string.match(url, "/wiki/[^%?&]+%?.*oldid=") or string.match(url, "/wiki/[^%?&]+%?.*diff=") or string.match(url, "/wiki/[^%?&]+%?.*dir=") or string.match(url, "/wiki/[^%?&]+%?.*offset=") or string.match(url, "/wiki/[^%?&]+%?.*action=edit") or string.match(url, "/wiki/[^%?&]+%?.*action=history") or string.match(url, "^https?://[^/]*fandom%.com/signin") or string.match(url, "^https?://[^/]*fandom%.com/register") then return false end if not ( string.match(url, "^https?://[^/]*fandom%.com") or string.match(url, "^https?://[^/]*wikia%.org") or string.match(url, "^https?://[^/]*wikia%.com") or string.match(url, "^https?://[^/]*nocookie%.net/") ) then local temp = "" for c in string.gmatch(url, "(.)") do local b = string.byte(c) if b < 32 or b > 126 then c = string.format("%%%02X", b) end temp = temp .. c end outlinks[string.match(temp, "^([^%s]+)")] = true return false end local user = string.match(url, "/wiki/User:([^%?&]+)") if user then discover_item("user:" .. item_wiki .. ":" .. user) end local fandom_wiki = string.match(url, "^https?://([^%.]+)%.fandom%.com/") if fandom_wiki and fandom_wiki ~= item_wiki then return false end local tested = {} for s in string.gmatch(url, "([^/]+)") do if tested[s] == nil then tested[s] = 0 end if tested[s] == 6 then return false end tested[s] = tested[s] + 1 end if string.match(url, "^https://[^%.]+.wikia.nocookie.net/") then if item_type == "url" then return true end discover_item("url:" .. url) return false end local wiki_page = string.match(url, "/wiki/([^%?&]+)") if wiki_page and ( ids[urlparse.unescape(wiki_page)] or (item_type == "base" and string.match(wiki_page, "^Special:")) ) then return true end if item_type == "base" and ( string.match(url, "api%.php%?.*action=query") or string.match(url, "api%.php$") or string.match(url, "^https?://[^/]+/f$") or string.match(url, "controller=DiscussionThread") or string.match(url, "^https?://([^/]*)%.[^%.]+%.[^%.]+/") == item_wiki ) then return true end if item_type == "page" and string.match(url, "controller=ArticleCommentsController") then return true end if string.match(url, "controller=Fandom") or string.match(url, "controller=RecirculationApi") or string.match(url, "controller=Lightbox") then return true end if item_type == "f" or item_type == "page" then for s in string.gmatch(url, "([0-9]+)") do if ids[s] then return true end end end return false end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] if item_type == "url" then return false end if not processed(url) and allowed(url, parent["url"]) then addedtolist[url] = true return true end return false end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil downloaded[url] = true if item_type == "url" then return urls end local function decode_codepoint(newurl) newurl = string.gsub( newurl, "\\[uU]([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])", function (s) return unicode_codepoint_as_utf8(tonumber(s, 16)) end ) return newurl end local function check(newurl) if string.match(newurl, "^https?://[^%.]+%.fandom%.com") and not string.match(newurl, "%.php") then check(string.gsub(newurl, "^(https?://[^%.]+%.)fandom%.com", "%1wikia%.org")) check(string.gsub(newurl, "^(https?://[^%.]+%.)fandom%.com", "%1wikia%.com")) end if string.match(newurl, "%%22") then return nil end newurl = decode_codepoint(newurl) local origurl = url local url = string.match(newurl, "^([^#]+)") local url_ = string.match(url, "^(.-)[%.\\]*$") while string.find(url_, "&amp;") do url_ = string.gsub(url_, "&amp;", "&") end if not processed(url_) and string.match(url_, "^https?://[^/%.]+%..+") and allowed(url_, origurl) then table.insert(urls, { url=url_ }) addedtolist[url_] = true addedtolist[url] = true end end local function checknewurl(newurl) newurl = decode_codepoint(newurl) if string.match(newurl, "['\"><]") then return nil end if string.match(newurl, "^https?:////") then check(string.gsub(newurl, ":////", "://")) elseif string.match(newurl, "^https?://") then check(newurl) elseif string.match(newurl, "^https?:\\/\\?/") then check(string.gsub(newurl, "\\", "")) elseif string.match(newurl, "^\\/\\/") then checknewurl(string.gsub(newurl, "\\", "")) elseif string.match(newurl, "^//") then check(urlparse.absolute(url, newurl)) elseif string.match(newurl, "^\\/") then checknewurl(string.gsub(newurl, "\\", "")) elseif string.match(newurl, "^/") then check(urlparse.absolute(url, newurl)) elseif string.match(newurl, "^%.%./") then if string.match(url, "^https?://[^/]+/[^/]+/") then check(urlparse.absolute(url, newurl)) else checknewurl(string.match(newurl, "^%.%.(/.+)$")) end elseif string.match(newurl, "^%./") then check(urlparse.absolute(url, newurl)) end end local function checknewshorturl(newurl) newurl = decode_codepoint(newurl) if string.match(newurl, "^%?") then check(urlparse.absolute(url, newurl)) elseif not ( string.match(newurl, "^https?:\\?/\\?//?/?") or string.match(newurl, "^[/\\]") or string.match(newurl, "^%./") or string.match(newurl, "^[jJ]ava[sS]cript:") or string.match(newurl, "^[mM]ail[tT]o:") or string.match(newurl, "^vine:") or string.match(newurl, "^android%-app:") or string.match(newurl, "^ios%-app:") or string.match(newurl, "^data:") or string.match(newurl, "^irc:") or string.match(newurl, "^%${") ) then check(urlparse.absolute(url, newurl)) end end if allowed(url) and status_code < 300 and not string.match(url, "^https://[^%.]+.wikia.nocookie.net/") then html = read_file(file) if string.match(url, "/api%.php%?action=query&pageids=[0-9]+&format=json$") then local title = JSON:decode(html)["query"]["pages"][item_value]["title"] if not title then return urls end local base = string.match(url, "^(https?://[^/]+/)") check(base .. "index.php?curid=" .. item_value) ids[title] = true title = urlparse.escape(title) ids[title] = true check(base .. "wiki/" .. title) check(base .. "wikia.php?controller=ArticleCommentsController&method=getCommentCount&namespace=0&title=" .. title .. "&hideDeleted=true") check(base .. "wikia.php?controller=ArticleCommentsController&method=getComments&title=" .. title .. "&namespace=0&hideDeleted=true") title = string.gsub(title, "%%20", "%+") ids[title] = true check(base .. "wiki/" .. title) check(base .. "wikia.php?controller=ArticleCommentsController&method=getCommentCount&namespace=0&title=" .. title .. "&hideDeleted=true") check(base .. "wikia.php?controller=ArticleCommentsController&method=getComments&title=" .. title .. "&namespace=0&hideDeleted=true") end if string.match(url, "^https?://[^/]*/wiki/[^%?&]") then local data = string.match(html, "<script>var%s+_plc%s*=%s*({.-});[^<]*</script>") if data then data = JSON:decode(data) if data["pgId"] == item_value and not string.match(url, "[%?&]file=") then for image_key in string.gmatch(html, 'data%-image%-key="([^"]+)') do local newurl = url local base = string.match(url, "^(https?://[^/]+/)") if string.match(url, "%?") then newurl = newurl .. "&" else newurl = newurl .. "?" end newurl = newurl .. "file=" .. image_key check(newurl) check(base .. "wikia.php?controller=Lightbox&method=getMediaDetail&fileTitle=" .. image_key .. "&format=json") end end end end if string.match(url, "^https?://[^/]+/api%.php$") then for _, name in pairs({"allpages", "allimages", "allinfoboxes"}) do check(url .. "?action=query&list=" .. name .. "&format=json") end local base = string.match(url, "^(https?://[^/]+/)") check(base .. "wiki/Special:SpecialPages") check(base .. "f") check(base .. "wikia.php?controller=RecirculationApi&method=getFandomArticles&limit=9") check(base .. "wikia.php?controller=RecirculationApi&method=getLatestThreads&_lang=en") check(base .. "wikia.php?controller=Lightbox&method=lightboxModalContent&format=html&lightboxVersion=&userLang=en") check(base .. "wikia.php?controller=Lightbox&method=getTotalWikiImages&count=0&format=json&inclusive=true") check(base .. "wikia.php?controller=Fandom%5CFandomDesktop%5CRail%5CRailController&method=renderLazyContentsAnon&modules%5B%5D=Fandom%5CFandomDesktop%5CRail%5CPopularPagesModuleService&fdRightRail=&uselang=&useskin=fandomdesktop:") check(base) end if string.match(url, "/api%.php%?.*action=query") then local json = JSON:decode(html) if json["continue"] then for key, value in pairs(json["continue"]) do if key ~= "continue" then value = string.gsub(urlparse.escape(value), "%%", "%%%%") if string.match(url, "[%?&]" .. key .. "=") then check(string.gsub(url, "([%?&]" .. key .. "=)[^%?&]+", "%1" .. value)) else check(string.gsub(url, "(&format=json)", "&" .. key .. "=" .. value .. "%1")) end end end end local largest = 0 for _, pattern in pairs({'"pageid"%s*:%s*"?([0-9]+)"?', "[%?&]curid=([0-9]+)"}) do for pageid in string.gmatch(html, pattern) do pageid = tonumber(pageid) if pageid > largest then largest = pageid end end end for i=0,largest do discover_item("page:" .. item_wiki .. ":" .. tostring(i)) end end if string.match(url, "^/f/p/[0-9]+$") then check("https://lgbta.fandom.com/wikia.php?limit=6&sortBy=trending&responseGroup=small&viewableOnly=true&excludedThreads=" .. item_value .. "&controller=DiscussionThread&method=getThreads") end if string.match(url, "/wikia%.php%?.*controller=DiscussionThread") then local json = JSON:decode(html) if item_type == "f" then for _, data in pairs(json["_embedded"]["doc:posts"]) do ids[data["id"]] = true check("https://lgbta.fandom.com/f/p/" .. item_value .. "/r/" .. data["id"]) end elseif item_type == "base" then for _, data in pairs(json["_embedded"]["threads"]) do discover_item("f:" .. item_wiki .. ":" .. data["id"]) end end end if string.match(url, "wikia%.php") then for user in string.gmatch(html, '"name"%s*:%s*"([^"]+)"') do discover_item("user:" .. item_wiki .. ":" .. user) end end for newurl in string.gmatch(string.gsub(html, "&quot;", '"'), '([^"]+)') do checknewurl(newurl) end for newurl in string.gmatch(string.gsub(html, "&#039;", "'"), "([^']+)") do checknewurl(newurl) end for newurl in string.gmatch(html, ">%s*([^<%s]+)") do checknewurl(newurl) end for newurl in string.gmatch(html, "[^%-]href='([^']+)'") do checknewshorturl(newurl) end for newurl in string.gmatch(html, '[^%-]href="([^"]+)"') do checknewshorturl(newurl) end for newurl in string.gmatch(html, ":%s*url%(([^%)]+)%)") do checknewurl(newurl) end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. " \n") io.stdout:flush() local wiki = string.match(url["url"], "^https?://([^%.]+)%.fandom%.com/api%.php$") local type_ = nil if wiki then type_ = "base" value = nil end if not wiki then wiki, value = string.match(url["url"], "^https?://([^%.]+)%.fandom%.com/api%.php%?action=query&pageids=([0-9]+)&format=json$") type_ = "page" end if not wiki then wiki, value = string.match(url["url"], "^https?://([^%.]+)%.fandom%.com/f/p/([0-9]+)$") type_ = "f" end if not wiki and string.match(url["url"], "^https://[^%.]+.wikia.nocookie.net/")then wiki = url["url"] type_ = "url" end if wiki then abortgrab = false item_type = type_ item_wiki = wiki item_value = value item_name = item_type .. ":" .. item_wiki if item_value then ids[item_value] = true item_name = item_name .. ":" .. item_value end print("Archiving item " .. item_name) end if status_code == 204 then return wget.actions.EXIT end if status_code >= 300 and status_code <= 399 then local newloc = urlparse.absolute(url["url"], http_stat["newloc"]) if string.match(url["url"], "/wiki/") and string.match(newloc, "/wiki/") then ids[string.match(newloc, "/wiki/([^%?&]+)")] = true end if processed(newloc) or not allowed(newloc, url["url"]) then tries = 0 return wget.actions.EXIT end end if (status_code >= 200 and status_code <= 399) then downloaded[url["url"]] = true downloaded[string.gsub(url["url"], "https?://", "http://")] = true end if abortgrab then abort_item() return wget.actions.EXIT end if status_code >= 500 or (status_code >= 400 and status_code ~= 404) or status_code == 0 then io.stdout:write("Server returned " .. http_stat.statcode .. " (" .. err .. "). Sleeping.\n") io.stdout:flush() local maxtries = 8 if not allowed(url["url"]) then maxtries = 0 end if tries >= maxtries then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 if allowed(url["url"]) then return wget.actions.ABORT else return wget.actions.EXIT end end os.execute("sleep " .. math.floor(math.pow(2, tries))) tries = tries + 1 return wget.actions.CONTINUE end tries = 0 local sleep_time = 0 if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end wget.callbacks.finish = function(start_time, end_time, wall_time, numurls, total_downloaded_bytes, total_download_time) local file = io.open(item_dir .. "/" .. warc_file_base .. "_bad-items.txt", "w") for url, _ in pairs(bad_items) do file:write(url .. "\n") end file:close() for key, data in pairs({ ["fandom-yeogkicq6a1f1cs"] = discovered_items, ["urls-nbv5q13ie6jf4br"] = outlinks }) do local items = nil for item, _ in pairs(data) do print("found item", item) if items == nil then items = item else items = items .. "\0" .. item end end if items ~= nil then local tries = 0 while tries < 10 do local body, code, headers, status = http.request( "http://blackbird-amqp.meo.ws:23038/" .. key .. "/", items ) if code == 200 or code == 409 then break end io.stdout:write("Could not queue items.\n") io.stdout:flush() os.execute("sleep " .. math.floor(math.pow(2, tries))) tries = tries + 1 end if tries == 10 then abort_item() end end end end wget.callbacks.before_exit = function(exit_status, exit_status_string) if abortgrab then abort_item() end return exit_status end
ITEM.name = "Bag" ITEM.desc = "A bag to hold more items." ITEM.model = "models/props_c17/suitcase001a.mdl" ITEM.category = "Storage" ITEM.weight = -5 function ITEM:onRegistered() if (isnumber(self.invWidth) and isnumber(self.invHeight)) then self.weight = -1 * self.invWidth * self.invHeight end end
function Flow_ClassifyEncryptedTraffic (msg, ruleEngine) -- Adds a metadata field if the traffic uses a knwon encryption classification require 'LOG' -- list of known crypto protocols if (cryptoProtocols == nil) then cryptoProtocols = {"ipsec","ssl", "ssh", "sftp", "rdp"} end -- if you need to increase efficiency then you can -- put the logic inside a check for if (IsFinalLongFlow(msg) or IsFinalShortFlow(msg)) then -- path string will look something like /tcp/ssl/https local appPath = GetString(msg, "internal", "applicationpath") -- iterate over crypto protocols for k,v in pairs(cryptoProtocols) do if (string.find(appPath,v)) then SetCustomField(msg, "EncryptedTraffic", "true") SetCustomField(msg, "EncryptedTrafficType", v) return end end end end
-- TODO(subeet) -- 1. [ ] get the folder path -- 2. [ ] get the file base name local M = {} return M
local Tunnel = module('_core', 'libs/Tunnel') local Proxy = module('_core', 'libs/Proxy') local hpp = Tunnel.getInterface("hpp_invHUD") API = Proxy.getInterface('API') cAPI = Tunnel.getInterface('cAPI') local capacity = 0 local weight = 0 Citizen.CreateThread(function() while true do Citizen.Wait(3000) capacity = hpp.getCapacity() weight = hpp.getWeight() end end) Citizen.CreateThread(function() while true do Citizen.Wait(1) if weight ~= nil and capacity ~= 0 then if weight ~= nil and capacity ~= nil then if weight >= capacity then drawTxt("INVENTÁRIO: ~r~"..weight.."kg~w~ / "..capacity.."kg",4,0.92,0.934,0.36,255,255,255,240) end if weight >= capacity * 0.7 and weight < capacity then drawTxt("INVENTÁRIO: ~y~"..weight.."kg~w~ / "..capacity.."kg",4,0.92,0.934,0.36,255,255,255,240) end if weight < capacity * 0.7 then drawTxt("INVENTÁRIO: ~g~"..weight.."kg~w~ / "..capacity.."kg",4,0.92,0.934,0.36,255,255,255,240) end end end end end) function drawTxt(text,font,x,y,scale,r,g,b,a) SetTextFont(font) SetTextScale(scale,scale) SetTextColour(r,g,b,a) SetTextOutline() SetTextCentre(1) SetTextEntry("STRING") AddTextComponentString(text) DrawText(x,y) end
FancyProgress = {} FancyProgress.__index = FancyProgress function FancyProgress.create(minval, maxval, bgName, x, y, width, height, barName, barOffsetX, barOffsetY, barWidth, barHeight) local screenWidth, screenHeight = guiGetScreenSize() if screenWidth < 1280 and screenHeight < 1024 then x = resAdjust(x) y = resAdjust(y) width = resAdjust(width) height = resAdjust(height) barOffsetX = resAdjust(barOffsetX) barOffsetY = resAdjust(barOffsetY) barWidth = resAdjust(barWidth) barHeight = resAdjust(barHeight) end if x < 0 then x = screenWidth - width + x end if y < 0 then y = screenHeight - height + y end return setmetatable( { background = guiCreateStaticImage(x, y, width, height, bgName, false, nil), bar = guiCreateStaticImage(x + barOffsetX, y + barOffsetY, barWidth, barHeight, barName, false, nil), width = barWidth, height = barHeight, min = minval, max = maxval, range = maxval - minval, progress = maxval }, FancyProgress ) end function FancyProgress:setProgress(progress) if not progress then progress = 0 end if progress < self.min then progress = self.min elseif progress > self.max then progress = self.max end if progress ~= self.progress then guiSetSize(self.bar, math.floor((progress-self.min)*self.width/self.range), self.height, false) self.progress = progress end end function FancyProgress:show() guiSetVisible(self.background, true) guiSetVisible(self.bar, true) end function FancyProgress:hide() guiSetVisible(self.background, false) guiSetVisible(self.bar, false) end function FancyProgress:destroy() destroyElement(self.background) self.background = nil destroyElement(self.bar) self.bar = nil end
local M = {} M.__index = M --- Switch by whether mapping has filetype matched with the buffer's filetype. --- @param mapping function|table: |stlparts.nvim-types-component| --- @param default function|table: |stlparts.nvim-types-component| --- @return table: |stlparts.nvim-types-component| function M.new(mapping, default) local tbl = { _mapping = vim.tbl_map(function(c) return require("stlparts.core.component").get(c) end, mapping), _default = require("stlparts.core.component").get(default), } return setmetatable(tbl, M) end function M.build(self, ctx) local bufnr = vim.api.nvim_win_get_buf(ctx.window_id) local filetype = vim.bo[bufnr].filetype local specific = self._mapping[filetype] if specific then return specific:build(ctx) end return self._default:build(ctx) end return M
local MODULE = PAW_MODULE('lib') local Colors = MODULE.Config.Colors local PANEL = {} function PANEL:Init() self:TDLib() :ClearPaint() :Background(Colors.Button) end function PANEL:AddOption( strText, funcFunction ) local pnl = vgui.Create( 'Paws.MenuOption', self ) pnl:SetMenu( self ) pnl:SetText( strText ) if ( funcFunction ) then pnl.DoClick = funcFunction end self:AddPanel( pnl ) return pnl end function PANEL:AddSubMenu( strText, funcFunction ) local pnl = vgui.Create( 'Paws.MenuOption', self ) local SubMenu = pnl:AddSubMenu( strText, funcFunction ) pnl:SetText( strText ) if ( funcFunction ) then pnl.DoClick = funcFunction end self:AddPanel( pnl ) return SubMenu, pnl end vgui.Register('Paws.Menu', PANEL, 'DMenu')
function __TS__OptionalChainAccess(____table, key) if ____table then return ____table[key] end return nil end
local Root = script:FindFirstAncestor('MazeGeneratorPlugin') local Roact = require(Root:WaitForChild('Roact')) local M = require(Root.M) local createElement = Roact.createElement local function UIPadding(props) local padding = props.padding local paddingProp = UDim.new(0, padding) return createElement( 'UIPadding', M.extend( { PaddingBottom = paddingProp, PaddingLeft = paddingProp, PaddingRight = paddingProp, PaddingTop = paddingProp, }, M.omit(props, 'padding') ) ) end return UIPadding
insulate("Generic:withTags()", function() require "init" require "spec.mocks" require "spec.asserts" it("creates a valid tagged object", function() local station = SpaceStation() Generic:withTags(station) assert.is_true(Generic:hasTags(station)) end) it("allows to set tags in the constructor", function() local station = SpaceStation() Generic:withTags(station, "foo", "bar", "baz") assert.is_true(Generic:hasTags(station)) assert.is_same(3, Util.size(station:getTags())) end) it("fails if the first argument is a number", function() assert.has_error(function() Generic:withTags(42) end) end) it("fails if a tag is not a string", function() assert.has_error(function() Generic:withTags(station, "foo", "bar", 42) end) end) describe(":getTags()", function() it("returns all tags set in the constructor", function() local station = SpaceStation() Generic:withTags(station, "foo", "bar") local tags = station:getTags() assert.contains_value("foo", tags) assert.contains_value("bar", tags) end) it("does not allow to manipulate the tags", function() local station = SpaceStation() Generic:withTags(station, "foo", "bar") local tags = station:getTags() table.insert(tags, "fake") tags = station:getTags() assert.not_contains_value("fake", tags) end) it("does not return the same tag twice", function() local station = SpaceStation() Generic:withTags(station, "foo", "bar", "bar", "bar") local tags = station:getTags() assert.is_same(2, Util.size(tags)) assert.contains_value("foo", tags) assert.contains_value("bar", tags) end) end) describe(":hasTag()", function() it("returns true if a tag was set in the constructor and false if not", function() local station = SpaceStation() Generic:withTags(station, "foo", "bar") assert.is_true(station:hasTag("foo")) assert.is_true(station:hasTag("bar")) assert.is_false(station:hasTag("fake")) end) it("fails if a non-string tag is given", function() local station = SpaceStation() Generic:withTags(station, "foo", "bar") assert.has_error(function() station:hasTag(42) end) end) end) describe(":addTag()", function() it("adds a tag", function() local station = SpaceStation() Generic:withTags(station, "foo", "bar") station:addTag("baz") assert.is_true(station:hasTag("baz")) assert.contains_value("baz", station:getTags()) end) it("fails if a number is given", function() local station = SpaceStation() Generic:withTags(station, "foo", "bar") assert.has_error(function() station:addTag(42) end) end) end) describe(":addTags()", function() it("allows to batch add tags", function() local station = SpaceStation() Generic:withTags(station) station:addTags("foo", "bar", "baz") assert.is_true(station:hasTag("foo")) assert.is_true(station:hasTag("bar")) assert.is_true(station:hasTag("baz")) assert.contains_value("foo", station:getTags()) assert.contains_value("baz", station:getTags()) assert.contains_value("bar", station:getTags()) end) end) describe(":removeTag()", function() it("removes a tag if it was set before", function() local station = SpaceStation() Generic:withTags(station, "foo", "bar", "baz") station:removeTag("baz") local tags = station:getTags() assert.is_false(station:hasTag("baz")) assert.not_contains_value("baz", tags) assert.is_same(2, Util.size(tags)) end) it("fails silently if the tag was not set", function() local station = SpaceStation() Generic:withTags(station, "foo", "bar") station:removeTag("baz") local tags = station:getTags() assert.is_false(station:hasTag("baz")) assert.not_contains_value("baz", tags) assert.is_same(2, Util.size(tags)) end) it("fails if a number is given", function() local station = SpaceStation() Generic:withTags(station, "foo", "bar") assert.has_error(function() station:removeTag(42) end) end) end) describe(":removeTags()", function() it("allows to batch remove tags", function() local station = SpaceStation() Generic:withTags(station, "foo", "bar", "baz") station:removeTags("bar", "baz") assert.is_true(station:hasTag("foo")) assert.is_false(station:hasTag("bar")) assert.is_false(station:hasTag("baz")) assert.contains_value("foo", station:getTags()) assert.not_contains_value("baz", station:getTags()) assert.not_contains_value("bar", station:getTags()) end) end) end)
function readADC_SingleEnded(channel, cb) if channel > 3 then return 0 end local ADDR = 0x48 local ADS1115_CONVERTIONDELAY = 8 local ADS1015_REG_POINTER_MASK = 0x03 local ADS1015_REG_POINTER_CONVERT = 0x00 local ADS1015_REG_POINTER_CONFIG = 0x01 local ADS1015_REG_POINTER_LOWTHRESH = 0x02 local ADS1015_REG_POINTER_HITHRESH = 0x03 local ADS1015_REG_CONFIG_MUX_SINGLE_0 = 0x4000 local ADS1015_REG_CONFIG_MUX_SINGLE_1 = 0x5000 local ADS1015_REG_CONFIG_MUX_SINGLE_2 = 0x6000 local ADS1015_REG_CONFIG_MUX_SINGLE_3 = 0x7000 local ADS1015_REG_CONFIG_OS_SINGLE = 0x8000 local ADS1015_REG_CONFIG_CQUE_NONE = 0x0003 local ADS1015_REG_CONFIG_CLAT_NONLAT = 0x0000 local ADS1015_REG_CONFIG_CPOL_ACTVLOW = 0x0000 local ADS1015_REG_CONFIG_CMODE_TRAD = 0x0000 local ADS1015_REG_CONFIG_DR_1600SPS = 0x0080 local ADS1015_REG_CONFIG_MODE_SINGLE = 0x0100 local config = 0 config = bit.bor(config, ADS1015_REG_CONFIG_CQUE_NONE) config = bit.bor(config, ADS1015_REG_CONFIG_CLAT_NONLAT) config = bit.bor(config, ADS1015_REG_CONFIG_CPOL_ACTVLOW) config = bit.bor(config, ADS1015_REG_CONFIG_CMODE_TRAD) config = bit.bor(config, ADS1015_REG_CONFIG_DR_1600SPS) config = bit.bor(config, ADS1015_REG_CONFIG_MODE_SINGLE) if channel == 0 then config = bit.bor(config, ADS1015_REG_CONFIG_MUX_SINGLE_0) elseif channel == 1 then config = bit.bor(config, ADS1015_REG_CONFIG_MUX_SINGLE_1) elseif channel == 2 then config = bit.bor(config, ADS1015_REG_CONFIG_MUX_SINGLE_2) elseif channel == 3 then config = bit.bor(config, ADS1015_REG_CONFIG_MUX_SINGLE_3) end config = bit.bor(config, ADS1015_REG_CONFIG_OS_SINGLE) require('writeRegister') writeRegister(ADDR, ADS1015_REG_POINTER_CONFIG, config) package.loaded['writeRegister'] = nil writeRegister = nil tmr.delay(ADS1115_CONVERTIONDELAY) require('readRegister') local value = readRegister(ADDR, ADS1015_REG_POINTER_CONVERT) package.loaded['readRegister'] = nil readRegister = nil ADS1115_CONVERTIONDELAY = nil ADS1015_REG_POINTER_MASK = nil ADS1015_REG_POINTER_CONVERT = nil ADS1015_REG_POINTER_CONFIG = nil ADS1015_REG_POINTER_LOWTHRESH = nil ADS1015_REG_POINTER_HITHRESH = nil ADS1015_REG_CONFIG_MUX_SINGLE_0 = nil ADS1015_REG_CONFIG_MUX_SINGLE_1 = nil ADS1015_REG_CONFIG_MUX_SINGLE_2 = nil ADS1015_REG_CONFIG_MUX_SINGLE_3 = nil ADS1015_REG_CONFIG_OS_SINGLE = nil ADS1015_REG_CONFIG_CQUE_NONE = nil ADS1015_REG_CONFIG_CLAT_NONLAT = nil ADS1015_REG_CONFIG_CPOL_ACTVLOW = nil ADS1015_REG_CONFIG_CMODE_TRAD = nil ADS1015_REG_CONFIG_DR_1600SPS = nil ADS1015_REG_CONFIG_MODE_SINGLE = nil return value end
local Collapse, parent = torch.class('nn.Collapse', 'nn.Module') -- collapses non-batch dims function Collapse:__init(nInputDim) parent.__init(self) self.nInputDim = nInputDim end function Collapse:updateOutput(input) if not input:isContiguous() then self._input = self._input or input.new() self._input:resize(input:size()):copy(input) input = self._input end if input:dim() > self.nInputDim then self.output:view(input,input:size(1),-1) else self.output:view(input,-1) end return self.output end function Collapse:updateGradInput(input, gradOutput) self.gradInput:view(gradOutput, input:size()) return self.gradInput end function Collapse:clearState() self._input = nil end
local helpers = require('test.functional.helpers')(after_each) local clear = helpers.clear local funcs = helpers.funcs local eval, eq = helpers.eval, helpers.eq local execute = helpers.execute local nvim = helpers.nvim local exc_exec = helpers.exc_exec describe('msgpack*() functions', function() before_each(clear) local obj_test = function(msg, obj) it(msg, function() nvim('set_var', 'obj', obj) eq(obj, eval('msgpackparse(msgpackdump(g:obj))')) end) end -- Regression test: msgpack_list_write was failing to write buffer with zero -- length. obj_test('are able to dump and restore {"file": ""}', {{file=''}}) -- Regression test: msgpack_list_write was failing to write buffer with NL at -- the end. obj_test('are able to dump and restore {0, "echo mpack"}', {{0, 'echo mpack'}}) obj_test('are able to dump and restore "Test\\n"', {'Test\n'}) -- Regression test: msgpack_list_write was failing to write buffer with NL -- inside. obj_test('are able to dump and restore "Test\\nTest 2"', {'Test\nTest 2'}) -- Test that big objects (requirement: dump to something that is bigger then -- IOSIZE) are also fine. This particular object is obtained by concatenating -- 5 identical shada files. local big_obj = { 1, 1436711454, 78, { encoding="utf-8", max_kbyte=10, pid=19269, version="NVIM 0.0.0-alpha+201507121634" }, 8, 1436711451, 40, { file="/home/zyx/.nvim/shada/main.shada" }, 8, 1436711391, 8, { file="" }, 4, 1436700940, 30, { 0, "call mkdir('/tmp/tty/tty')" }, 4, 1436701355, 35, { 0, "call mkdir('/tmp/tty/tty', 'p')" }, 4, 1436701368, 24, { 0, "call mkdir('/', 'p')" }, 4, 1436701375, 26, { 0, "call mkdir('/tty/tty')" }, 4, 1436701383, 30, { 0, "call mkdir('/tty/tty/tty')" }, 4, 1436701407, 35, { 0, "call mkdir('/usr/tty/tty', 'p')" }, 4, 1436701666, 35, { 0, "call mkdir('/tty/tty/tty', 'p')" }, 4, 1436708101, 25, { 0, "echo msgpackdump([1])" }, 4, 1436708966, 6, { 0, "cq" }, 4, 1436709606, 25, { 0, "echo msgpackdump([5])" }, 4, 1436709610, 26, { 0, "echo msgpackdump([10])" }, 4, 1436709615, 31, { 0, "echo msgpackdump([5, 5, 5])" }, 4, 1436709618, 35, { 0, "echo msgpackdump([5, 5, 5, 10])" }, 4, 1436709634, 57, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1}]])" }, 4, 1436709651, 67, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1, \"def\": 0}]])" }, 4, 1436709660, 70, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1, \"def\": 0}], 0])" }, 4, 1436710095, 29, { 0, "echo msgpackparse([\"\\n\"])" }, 4, 1436710100, 28, { 0, "echo msgpackparse([\"j\"])" }, 4, 1436710109, 31, { 0, "echo msgpackparse([\"\", \"\"])" }, 4, 1436710424, 33, { 0, "echo msgpackparse([\"\", \"\\n\"])" }, 4, 1436710428, 32, { 0, "echo msgpackparse([\"\", \"j\"])" }, 4, 1436711142, 14, { 0, "echo mpack" }, 4, 1436711196, 45, { 0, "let lengths = map(mpack[:], 'len(v:val)')" }, 4, 1436711206, 16, { 0, "echo lengths" }, 4, 1436711244, 92, { 0, ("let sum = len(lengths) - 1 | call map(copy(lengths), " .. "'extend(g:, {\"sum\": sum + v:val})')") }, 4, 1436711245, 12, { 0, "echo sum" }, 4, 1436711398, 10, { 0, "echo s" }, 4, 1436711404, 41, { 0, "let mpack = readfile('/tmp/foo', 'b')" }, 4, 1436711408, 41, { 0, "let shada_objects=msgpackparse(mpack)" }, 4, 1436711415, 22, { 0, "echo shada_objects" }, 4, 1436711451, 30, { 0, "e ~/.nvim/shada/main.shada" }, 4, 1436711454, 6, { 0, "qa" }, 4, 1436711442, 9, { 1, "test", 47 }, 4, 1436711443, 15, { 1, "aontsuesan", 47 }, 2, 1436711443, 38, { hlsearch=1, pat="aontsuesan", smartcase=1 }, 2, 0, 31, { islast=0, pat="", smartcase=1, sub=1 }, 3, 0, 3, { "" }, 10, 1436711451, 40, { file="/home/zyx/.nvim/shada/main.shada" }, 1, 1436711454, 78, { encoding="utf-8", max_kbyte=10, pid=19269, version="NVIM 0.0.0-alpha+201507121634" }, 8, 1436711451, 40, { file="/home/zyx/.nvim/shada/main.shada" }, 8, 1436711391, 8, { file="" }, 4, 1436700940, 30, { 0, "call mkdir('/tmp/tty/tty')" }, 4, 1436701355, 35, { 0, "call mkdir('/tmp/tty/tty', 'p')" }, 4, 1436701368, 24, { 0, "call mkdir('/', 'p')" }, 4, 1436701375, 26, { 0, "call mkdir('/tty/tty')" }, 4, 1436701383, 30, { 0, "call mkdir('/tty/tty/tty')" }, 4, 1436701407, 35, { 0, "call mkdir('/usr/tty/tty', 'p')" }, 4, 1436701666, 35, { 0, "call mkdir('/tty/tty/tty', 'p')" }, 4, 1436708101, 25, { 0, "echo msgpackdump([1])" }, 4, 1436708966, 6, { 0, "cq" }, 4, 1436709606, 25, { 0, "echo msgpackdump([5])" }, 4, 1436709610, 26, { 0, "echo msgpackdump([10])" }, 4, 1436709615, 31, { 0, "echo msgpackdump([5, 5, 5])" }, 4, 1436709618, 35, { 0, "echo msgpackdump([5, 5, 5, 10])" }, 4, 1436709634, 57, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1}]])" }, 4, 1436709651, 67, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1, \"def\": 0}]])" }, 4, 1436709660, 70, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1, \"def\": 0}], 0])" }, 4, 1436710095, 29, { 0, "echo msgpackparse([\"\\n\"])" }, 4, 1436710100, 28, { 0, "echo msgpackparse([\"j\"])" }, 4, 1436710109, 31, { 0, "echo msgpackparse([\"\", \"\"])" }, 4, 1436710424, 33, { 0, "echo msgpackparse([\"\", \"\\n\"])" }, 4, 1436710428, 32, { 0, "echo msgpackparse([\"\", \"j\"])" }, 4, 1436711142, 14, { 0, "echo mpack" }, 4, 1436711196, 45, { 0, "let lengths = map(mpack[:], 'len(v:val)')" }, 4, 1436711206, 16, { 0, "echo lengths" }, 4, 1436711244, 92, { 0, ("let sum = len(lengths) - 1 | call map(copy(lengths), " .. "'extend(g:, {\"sum\": sum + v:val})')") }, 4, 1436711245, 12, { 0, "echo sum" }, 4, 1436711398, 10, { 0, "echo s" }, 4, 1436711404, 41, { 0, "let mpack = readfile('/tmp/foo', 'b')" }, 4, 1436711408, 41, { 0, "let shada_objects=msgpackparse(mpack)" }, 4, 1436711415, 22, { 0, "echo shada_objects" }, 4, 1436711451, 30, { 0, "e ~/.nvim/shada/main.shada" }, 4, 1436711454, 6, { 0, "qa" }, 4, 1436711442, 9, { 1, "test", 47 }, 4, 1436711443, 15, { 1, "aontsuesan", 47 }, 2, 1436711443, 38, { hlsearch=1, pat="aontsuesan", smartcase=1 }, 2, 0, 31, { islast=0, pat="", smartcase=1, sub=1 }, 3, 0, 3, { "" }, 10, 1436711451, 40, { file="/home/zyx/.nvim/shada/main.shada" }, 1, 1436711454, 78, { encoding="utf-8", max_kbyte=10, pid=19269, version="NVIM 0.0.0-alpha+201507121634" }, 8, 1436711451, 40, { file="/home/zyx/.nvim/shada/main.shada" }, 8, 1436711391, 8, { file="" }, 4, 1436700940, 30, { 0, "call mkdir('/tmp/tty/tty')" }, 4, 1436701355, 35, { 0, "call mkdir('/tmp/tty/tty', 'p')" }, 4, 1436701368, 24, { 0, "call mkdir('/', 'p')" }, 4, 1436701375, 26, { 0, "call mkdir('/tty/tty')" }, 4, 1436701383, 30, { 0, "call mkdir('/tty/tty/tty')" }, 4, 1436701407, 35, { 0, "call mkdir('/usr/tty/tty', 'p')" }, 4, 1436701666, 35, { 0, "call mkdir('/tty/tty/tty', 'p')" }, 4, 1436708101, 25, { 0, "echo msgpackdump([1])" }, 4, 1436708966, 6, { 0, "cq" }, 4, 1436709606, 25, { 0, "echo msgpackdump([5])" }, 4, 1436709610, 26, { 0, "echo msgpackdump([10])" }, 4, 1436709615, 31, { 0, "echo msgpackdump([5, 5, 5])" }, 4, 1436709618, 35, { 0, "echo msgpackdump([5, 5, 5, 10])" }, 4, 1436709634, 57, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1}]])" }, 4, 1436709651, 67, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1, \"def\": 0}]])" }, 4, 1436709660, 70, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1, \"def\": 0}], 0])" }, 4, 1436710095, 29, { 0, "echo msgpackparse([\"\\n\"])" }, 4, 1436710100, 28, { 0, "echo msgpackparse([\"j\"])" }, 4, 1436710109, 31, { 0, "echo msgpackparse([\"\", \"\"])" }, 4, 1436710424, 33, { 0, "echo msgpackparse([\"\", \"\\n\"])" }, 4, 1436710428, 32, { 0, "echo msgpackparse([\"\", \"j\"])" }, 4, 1436711142, 14, { 0, "echo mpack" }, 4, 1436711196, 45, { 0, "let lengths = map(mpack[:], 'len(v:val)')" }, 4, 1436711206, 16, { 0, "echo lengths" }, 4, 1436711244, 92, { 0, ("let sum = len(lengths) - 1 | call map(copy(lengths), " .. "'extend(g:, {\"sum\": sum + v:val})')") }, 4, 1436711245, 12, { 0, "echo sum" }, 4, 1436711398, 10, { 0, "echo s" }, 4, 1436711404, 41, { 0, "let mpack = readfile('/tmp/foo', 'b')" }, 4, 1436711408, 41, { 0, "let shada_objects=msgpackparse(mpack)" }, 4, 1436711415, 22, { 0, "echo shada_objects" }, 4, 1436711451, 30, { 0, "e ~/.nvim/shada/main.shada" }, 4, 1436711454, 6, { 0, "qa" }, 4, 1436711442, 9, { 1, "test", 47 }, 4, 1436711443, 15, { 1, "aontsuesan", 47 }, 2, 1436711443, 38, { hlsearch=1, pat="aontsuesan", smartcase=1 }, 2, 0, 31, { islast=0, pat="", smartcase=1, sub=1 }, 3, 0, 3, { "" }, 10, 1436711451, 40, { file="/home/zyx/.nvim/shada/main.shada" }, 1, 1436711454, 78, { encoding="utf-8", max_kbyte=10, pid=19269, version="NVIM 0.0.0-alpha+201507121634" }, 8, 1436711451, 40, { file="/home/zyx/.nvim/shada/main.shada" }, 8, 1436711391, 8, { file="" }, 4, 1436700940, 30, { 0, "call mkdir('/tmp/tty/tty')" }, 4, 1436701355, 35, { 0, "call mkdir('/tmp/tty/tty', 'p')" }, 4, 1436701368, 24, { 0, "call mkdir('/', 'p')" }, 4, 1436701375, 26, { 0, "call mkdir('/tty/tty')" }, 4, 1436701383, 30, { 0, "call mkdir('/tty/tty/tty')" }, 4, 1436701407, 35, { 0, "call mkdir('/usr/tty/tty', 'p')" }, 4, 1436701666, 35, { 0, "call mkdir('/tty/tty/tty', 'p')" }, 4, 1436708101, 25, { 0, "echo msgpackdump([1])" }, 4, 1436708966, 6, { 0, "cq" }, 4, 1436709606, 25, { 0, "echo msgpackdump([5])" }, 4, 1436709610, 26, { 0, "echo msgpackdump([10])" }, 4, 1436709615, 31, { 0, "echo msgpackdump([5, 5, 5])" }, 4, 1436709618, 35, { 0, "echo msgpackdump([5, 5, 5, 10])" }, 4, 1436709634, 57, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1}]])" }, 4, 1436709651, 67, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1, \"def\": 0}]])" }, 4, 1436709660, 70, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1, \"def\": 0}], 0])" }, 4, 1436710095, 29, { 0, "echo msgpackparse([\"\\n\"])" }, 4, 1436710100, 28, { 0, "echo msgpackparse([\"j\"])" }, 4, 1436710109, 31, { 0, "echo msgpackparse([\"\", \"\"])" }, 4, 1436710424, 33, { 0, "echo msgpackparse([\"\", \"\\n\"])" }, 4, 1436710428, 32, { 0, "echo msgpackparse([\"\", \"j\"])" }, 4, 1436711142, 14, { 0, "echo mpack" }, 4, 1436711196, 45, { 0, "let lengths = map(mpack[:], 'len(v:val)')" }, 4, 1436711206, 16, { 0, "echo lengths" }, 4, 1436711244, 92, { 0, ("let sum = len(lengths) - 1 | call map(copy(lengths), " .. "'extend(g:, {\"sum\": sum + v:val})')") }, 4, 1436711245, 12, { 0, "echo sum" }, 4, 1436711398, 10, { 0, "echo s" }, 4, 1436711404, 41, { 0, "let mpack = readfile('/tmp/foo', 'b')" }, 4, 1436711408, 41, { 0, "let shada_objects=msgpackparse(mpack)" }, 4, 1436711415, 22, { 0, "echo shada_objects" }, 4, 1436711451, 30, { 0, "e ~/.nvim/shada/main.shada" }, 4, 1436711454, 6, { 0, "qa" }, 4, 1436711442, 9, { 1, "test", 47 }, 4, 1436711443, 15, { 1, "aontsuesan", 47 }, 2, 1436711443, 38, { hlsearch=1, pat="aontsuesan", smartcase=1 }, 2, 0, 31, { islast=0, pat="", smartcase=1, sub=1 }, 3, 0, 3, { "" }, 10, 1436711451, 40, { file="/home/zyx/.nvim/shada/main.shada" }, 1, 1436711454, 78, { encoding="utf-8", max_kbyte=10, pid=19269, version="NVIM 0.0.0-alpha+201507121634" }, 8, 1436711451, 40, { file="/home/zyx/.nvim/shada/main.shada" }, 8, 1436711391, 8, { file="" }, 4, 1436700940, 30, { 0, "call mkdir('/tmp/tty/tty')" }, 4, 1436701355, 35, { 0, "call mkdir('/tmp/tty/tty', 'p')" }, 4, 1436701368, 24, { 0, "call mkdir('/', 'p')" }, 4, 1436701375, 26, { 0, "call mkdir('/tty/tty')" }, 4, 1436701383, 30, { 0, "call mkdir('/tty/tty/tty')" }, 4, 1436701407, 35, { 0, "call mkdir('/usr/tty/tty', 'p')" }, 4, 1436701666, 35, { 0, "call mkdir('/tty/tty/tty', 'p')" }, 4, 1436708101, 25, { 0, "echo msgpackdump([1])" }, 4, 1436708966, 6, { 0, "cq" }, 4, 1436709606, 25, { 0, "echo msgpackdump([5])" }, 4, 1436709610, 26, { 0, "echo msgpackdump([10])" }, 4, 1436709615, 31, { 0, "echo msgpackdump([5, 5, 5])" }, 4, 1436709618, 35, { 0, "echo msgpackdump([5, 5, 5, 10])" }, 4, 1436709634, 57, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1}]])" }, 4, 1436709651, 67, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1, \"def\": 0}]])" }, 4, 1436709660, 70, { 0, "echo msgpackdump([5, 5, 5, 10, [10, 20, {\"abc\": 1, \"def\": 0}], 0])" }, 4, 1436710095, 29, { 0, "echo msgpackparse([\"\\n\"])" }, 4, 1436710100, 28, { 0, "echo msgpackparse([\"j\"])" }, 4, 1436710109, 31, { 0, "echo msgpackparse([\"\", \"\"])" }, 4, 1436710424, 33, { 0, "echo msgpackparse([\"\", \"\\n\"])" }, 4, 1436710428, 32, { 0, "echo msgpackparse([\"\", \"j\"])" }, 4, 1436711142, 14, { 0, "echo mpack" }, 4, 1436711196, 45, { 0, "let lengths = map(mpack[:], 'len(v:val)')" }, 4, 1436711206, 16, { 0, "echo lengths" }, 4, 1436711244, 92, { 0, ("let sum = len(lengths) - 1 | call map(copy(lengths), " .. "'extend(g:, {\"sum\": sum + v:val})')") }, 4, 1436711245, 12, { 0, "echo sum" }, 4, 1436711398, 10, { 0, "echo s" }, 4, 1436711404, 41, { 0, "let mpack = readfile('/tmp/foo', 'b')" }, 4, 1436711408, 41, { 0, "let shada_objects=msgpackparse(mpack)" }, 4, 1436711415, 22, { 0, "echo shada_objects" }, 4, 1436711451, 30, { 0, "e ~/.nvim/shada/main.shada" }, 4, 1436711454, 6, { 0, "qa" }, 4, 1436711442, 9, { 1, "test", 47 }, 4, 1436711443, 15, { 1, "aontsuesan", 47 }, 2, 1436711443, 38, { hlsearch=1, pat="aontsuesan", smartcase=1 }, 2, 0, 31, { islast=0, pat="", smartcase=1, sub=1 }, 3, 0, 3, { "" }, 10, 1436711451, 40, { file="/home/zyx/.nvim/shada/main.shada" } } obj_test('are able to dump and restore rather big object', big_obj) obj_test('are able to dump and restore floating-point value', {0.125}) it('can restore and dump UINT64_MAX', function() execute('let dumped = ["\\xCF" . repeat("\\xFF", 8)]') execute('let parsed = msgpackparse(dumped)') execute('let dumped2 = msgpackdump(parsed)') eq(1, eval('type(parsed[0]) == type(0) ' .. '|| parsed[0]._TYPE is v:msgpack_types.integer')) if eval('type(parsed[0]) == type(0)') == 1 then eq(1, eval('0xFFFFFFFFFFFFFFFF == parsed[0]')) else eq({_TYPE={}, _VAL={1, 3, 0x7FFFFFFF, 0x7FFFFFFF}}, eval('parsed[0]')) end eq(1, eval('dumped ==# dumped2')) end) it('can restore and dump INT64_MIN', function() execute('let dumped = ["\\xD3\\x80" . repeat("\\n", 7)]') execute('let parsed = msgpackparse(dumped)') execute('let dumped2 = msgpackdump(parsed)') eq(1, eval('type(parsed[0]) == type(0) ' .. '|| parsed[0]._TYPE is v:msgpack_types.integer')) if eval('type(parsed[0]) == type(0)') == 1 then eq(1, eval('-0x8000000000000000 == parsed[0]')) else eq({_TYPE={}, _VAL={-1, 2, 0, 0}}, eval('parsed[0]')) end eq(1, eval('dumped ==# dumped2')) end) it('can restore and dump BIN string with zero byte', function() execute('let dumped = ["\\xC4\\x01\\n"]') execute('let parsed = msgpackparse(dumped)') execute('let dumped2 = msgpackdump(parsed)') eq({{_TYPE={}, _VAL={'\n'}}}, eval('parsed')) eq(1, eval('parsed[0]._TYPE is v:msgpack_types.binary')) eq(1, eval('dumped ==# dumped2')) end) it('can restore and dump STR string with zero byte', function() execute('let dumped = ["\\xA1\\n"]') execute('let parsed = msgpackparse(dumped)') execute('let dumped2 = msgpackdump(parsed)') eq({{_TYPE={}, _VAL={'\n'}}}, eval('parsed')) eq(1, eval('parsed[0]._TYPE is v:msgpack_types.string')) eq(1, eval('dumped ==# dumped2')) end) it('can restore and dump BIN string with NL', function() execute('let dumped = ["\\xC4\\x01", ""]') execute('let parsed = msgpackparse(dumped)') execute('let dumped2 = msgpackdump(parsed)') eq({"\n"}, eval('parsed')) eq(1, eval('dumped ==# dumped2')) end) it('dump and restore special mapping with floating-point value', function() execute('let todump = {"_TYPE": v:msgpack_types.float, "_VAL": 0.125}') eq({0.125}, eval('msgpackparse(msgpackdump([todump]))')) end) end) describe('msgpackparse() function', function() before_each(clear) it('restores nil as v:null', function() execute('let dumped = ["\\xC0"]') execute('let parsed = msgpackparse(dumped)') eq('[v:null]', eval('string(parsed)')) end) it('restores boolean false as v:false', function() execute('let dumped = ["\\xC2"]') execute('let parsed = msgpackparse(dumped)') eq({false}, eval('parsed')) end) it('restores boolean true as v:true', function() execute('let dumped = ["\\xC3"]') execute('let parsed = msgpackparse(dumped)') eq({true}, eval('parsed')) end) it('restores FIXSTR as special dict', function() execute('let dumped = ["\\xa2ab"]') execute('let parsed = msgpackparse(dumped)') eq({{_TYPE={}, _VAL={'ab'}}}, eval('parsed')) eq(1, eval('g:parsed[0]._TYPE is v:msgpack_types.string')) end) it('restores BIN 8 as string', function() execute('let dumped = ["\\xC4\\x02ab"]') eq({'ab'}, eval('msgpackparse(dumped)')) end) it('restores FIXEXT1 as special dictionary', function() execute('let dumped = ["\\xD4\\x10", ""]') execute('let parsed = msgpackparse(dumped)') eq({{_TYPE={}, _VAL={0x10, {"", ""}}}}, eval('parsed')) eq(1, eval('g:parsed[0]._TYPE is v:msgpack_types.ext')) end) it('restores MAP with BIN key as special dictionary', function() execute('let dumped = ["\\x81\\xC4\\x01a\\xC4\\n"]') execute('let parsed = msgpackparse(dumped)') eq({{_TYPE={}, _VAL={{'a', ''}}}}, eval('parsed')) eq(1, eval('g:parsed[0]._TYPE is v:msgpack_types.map')) end) it('restores MAP with duplicate STR keys as special dictionary', function() execute('let dumped = ["\\x82\\xA1a\\xC4\\n\\xA1a\\xC4\\n"]') execute('let parsed = msgpackparse(dumped)') eq({{_TYPE={}, _VAL={ {{_TYPE={}, _VAL={'a'}}, ''}, {{_TYPE={}, _VAL={'a'}}, ''}}} }, eval('parsed')) eq(1, eval('g:parsed[0]._TYPE is v:msgpack_types.map')) eq(1, eval('g:parsed[0]._VAL[0][0]._TYPE is v:msgpack_types.string')) eq(1, eval('g:parsed[0]._VAL[1][0]._TYPE is v:msgpack_types.string')) end) it('restores MAP with MAP key as special dictionary', function() execute('let dumped = ["\\x81\\x80\\xC4\\n"]') execute('let parsed = msgpackparse(dumped)') eq({{_TYPE={}, _VAL={{{}, ''}}}}, eval('parsed')) eq(1, eval('g:parsed[0]._TYPE is v:msgpack_types.map')) end) it('msgpackparse(systemlist(...)) does not segfault. #3135', function() local cmd = "sort(keys(msgpackparse(systemlist('" ..helpers.nvim_prog.." --api-info'))[0]))" eval(cmd) eval(cmd) -- do it again (try to force segfault) local api_info = eval(cmd) -- do it again eq({'error_types', 'functions', 'types', 'version'}, api_info) end) it('fails when called with no arguments', function() eq('Vim(call):E119: Not enough arguments for function: msgpackparse', exc_exec('call msgpackparse()')) end) it('fails when called with two arguments', function() eq('Vim(call):E118: Too many arguments for function: msgpackparse', exc_exec('call msgpackparse(["", ""], 1)')) end) it('fails to parse a string', function() eq('Vim(call):E686: Argument of msgpackparse() must be a List', exc_exec('call msgpackparse("abcdefghijklmnopqrstuvwxyz")')) end) it('fails to parse a number', function() eq('Vim(call):E686: Argument of msgpackparse() must be a List', exc_exec('call msgpackparse(127)')) end) it('fails to parse a dictionary', function() eq('Vim(call):E686: Argument of msgpackparse() must be a List', exc_exec('call msgpackparse({})')) end) it('fails to parse a funcref', function() eq('Vim(call):E686: Argument of msgpackparse() must be a List', exc_exec('call msgpackparse(function("tr"))')) end) it('fails to parse a partial', function() execute('function T() dict\nendfunction') eq('Vim(call):E686: Argument of msgpackparse() must be a List', exc_exec('call msgpackparse(function("T", [1, 2], {}))')) end) it('fails to parse a float', function() eq('Vim(call):E686: Argument of msgpackparse() must be a List', exc_exec('call msgpackparse(0.0)')) end) end) describe('msgpackdump() function', function() before_each(clear) it('dumps string as BIN 8', function() nvim('set_var', 'obj', {'Test'}) eq({"\196\004Test"}, eval('msgpackdump(obj)')) end) it('can dump generic mapping with generic mapping keys and values', function() execute('let todump = {"_TYPE": v:msgpack_types.map, "_VAL": []}') execute('let todumpv1 = {"_TYPE": v:msgpack_types.map, "_VAL": []}') execute('let todumpv2 = {"_TYPE": v:msgpack_types.map, "_VAL": []}') execute('call add(todump._VAL, [todumpv1, todumpv2])') eq({'\129\128\128'}, eval('msgpackdump([todump])')) end) it('can dump v:true', function() eq({'\195'}, funcs.msgpackdump({true})) end) it('can dump v:false', function() eq({'\194'}, funcs.msgpackdump({false})) end) it('can v:null', function() execute('let todump = v:null') end) it('can dump special bool mapping (true)', function() execute('let todump = {"_TYPE": v:msgpack_types.boolean, "_VAL": 1}') eq({'\195'}, eval('msgpackdump([todump])')) end) it('can dump special bool mapping (false)', function() execute('let todump = {"_TYPE": v:msgpack_types.boolean, "_VAL": 0}') eq({'\194'}, eval('msgpackdump([todump])')) end) it('can dump special nil mapping', function() execute('let todump = {"_TYPE": v:msgpack_types.nil, "_VAL": 0}') eq({'\192'}, eval('msgpackdump([todump])')) end) it('can dump special ext mapping', function() execute('let todump = {"_TYPE": v:msgpack_types.ext, "_VAL": [5, ["",""]]}') eq({'\212\005', ''}, eval('msgpackdump([todump])')) end) it('can dump special array mapping', function() execute('let todump = {"_TYPE": v:msgpack_types.array, "_VAL": [5, [""]]}') eq({'\146\005\145\196\n'}, eval('msgpackdump([todump])')) end) it('can dump special UINT64_MAX mapping', function() execute('let todump = {"_TYPE": v:msgpack_types.integer}') execute('let todump._VAL = [1, 3, 0x7FFFFFFF, 0x7FFFFFFF]') eq({'\207\255\255\255\255\255\255\255\255'}, eval('msgpackdump([todump])')) end) it('can dump special INT64_MIN mapping', function() execute('let todump = {"_TYPE": v:msgpack_types.integer}') execute('let todump._VAL = [-1, 2, 0, 0]') eq({'\211\128\n\n\n\n\n\n\n'}, eval('msgpackdump([todump])')) end) it('fails to dump a function reference', function() execute('let Todump = function("tr")') eq('Vim(call):E5004: Error while dumping msgpackdump() argument, index 0, itself: attempt to dump function reference', exc_exec('call msgpackdump([Todump])')) end) it('fails to dump a partial', function() execute('function T() dict\nendfunction') execute('let Todump = function("T", [1, 2], {})') eq('Vim(call):E5004: Error while dumping msgpackdump() argument, index 0, itself: attempt to dump function reference', exc_exec('call msgpackdump([Todump])')) end) it('fails to dump a function reference in a list', function() execute('let todump = [function("tr")]') eq('Vim(call):E5004: Error while dumping msgpackdump() argument, index 0, index 0: attempt to dump function reference', exc_exec('call msgpackdump([todump])')) end) it('fails to dump a recursive list', function() execute('let todump = [[[]]]') execute('call add(todump[0][0], todump)') eq('Vim(call):E5005: Unable to dump msgpackdump() argument, index 0: container references itself in index 0, index 0, index 0', exc_exec('call msgpackdump([todump])')) end) it('fails to dump a recursive dict', function() execute('let todump = {"d": {"d": {}}}') execute('call extend(todump.d.d, {"d": todump})') eq('Vim(call):E5005: Unable to dump msgpackdump() argument, index 0: container references itself in key \'d\', key \'d\', key \'d\'', exc_exec('call msgpackdump([todump])')) end) it('can dump dict with two same dicts inside', function() execute('let inter = {}') execute('let todump = {"a": inter, "b": inter}') eq({"\130\161a\128\161b\128"}, eval('msgpackdump([todump])')) end) it('can dump list with two same lists inside', function() execute('let inter = []') execute('let todump = [inter, inter]') eq({"\146\144\144"}, eval('msgpackdump([todump])')) end) it('fails to dump a recursive list in a special dict', function() execute('let todump = {"_TYPE": v:msgpack_types.array, "_VAL": []}') execute('call add(todump._VAL, todump)') eq('Vim(call):E5005: Unable to dump msgpackdump() argument, index 0: container references itself in index 0', exc_exec('call msgpackdump([todump])')) end) it('fails to dump a recursive (key) map in a special dict', function() execute('let todump = {"_TYPE": v:msgpack_types.map, "_VAL": []}') execute('call add(todump._VAL, [todump, 0])') eq('Vim(call):E5005: Unable to dump msgpackdump() argument, index 0: container references itself in index 1', exc_exec('call msgpackdump([todump])')) end) it('fails to dump a recursive (val) map in a special dict', function() execute('let todump = {"_TYPE": v:msgpack_types.map, "_VAL": []}') execute('call add(todump._VAL, [0, todump])') eq('Vim(call):E5005: Unable to dump msgpackdump() argument, index 0: container references itself in key 0 at index 0 from special map', exc_exec('call msgpackdump([todump])')) end) it('fails to dump a recursive (key) map in a special dict, _VAL reference', function() execute('let todump = {"_TYPE": v:msgpack_types.map, "_VAL": [[[], []]]}') execute('call add(todump._VAL[0][0], todump._VAL)') eq('Vim(call):E5005: Unable to dump msgpackdump() argument, index 0: container references itself in key [[[[...@0], []]]] at index 0 from special map, index 0', exc_exec('call msgpackdump([todump])')) end) it('fails to dump a recursive (val) map in a special dict, _VAL reference', function() execute('let todump = {"_TYPE": v:msgpack_types.map, "_VAL": [[[], []]]}') execute('call add(todump._VAL[0][1], todump._VAL)') eq('Vim(call):E5005: Unable to dump msgpackdump() argument, index 0: container references itself in key [] at index 0 from special map, index 0', exc_exec('call msgpackdump([todump])')) end) it('fails to dump a recursive (val) special list in a special dict', function() execute('let todump = {"_TYPE": v:msgpack_types.array, "_VAL": []}') execute('call add(todump._VAL, [0, todump._VAL])') eq('Vim(call):E5005: Unable to dump msgpackdump() argument, index 0: container references itself in index 0, index 1', exc_exec('call msgpackdump([todump])')) end) it('fails when called with no arguments', function() eq('Vim(call):E119: Not enough arguments for function: msgpackdump', exc_exec('call msgpackdump()')) end) it('fails when called with two arguments', function() eq('Vim(call):E118: Too many arguments for function: msgpackdump', exc_exec('call msgpackdump(["", ""], 1)')) end) it('fails to dump a string', function() eq('Vim(call):E686: Argument of msgpackdump() must be a List', exc_exec('call msgpackdump("abcdefghijklmnopqrstuvwxyz")')) end) it('fails to dump a number', function() eq('Vim(call):E686: Argument of msgpackdump() must be a List', exc_exec('call msgpackdump(127)')) end) it('fails to dump a dictionary', function() eq('Vim(call):E686: Argument of msgpackdump() must be a List', exc_exec('call msgpackdump({})')) end) it('fails to dump a funcref', function() eq('Vim(call):E686: Argument of msgpackdump() must be a List', exc_exec('call msgpackdump(function("tr"))')) end) it('fails to dump a partial', function() execute('function T() dict\nendfunction') eq('Vim(call):E686: Argument of msgpackdump() must be a List', exc_exec('call msgpackdump(function("T", [1, 2], {}))')) end) it('fails to dump a float', function() eq('Vim(call):E686: Argument of msgpackdump() must be a List', exc_exec('call msgpackdump(0.0)')) end) it('fails to dump special value', function() for _, val in ipairs({'v:true', 'v:false', 'v:null'}) do eq('Vim(call):E686: Argument of msgpackdump() must be a List', exc_exec('call msgpackdump(' .. val .. ')')) end end) it('can dump NULL string', function() eq({'\196\n'}, eval('msgpackdump([$XXX_UNEXISTENT_VAR_XXX])')) eq({'\196\n'}, eval('msgpackdump([{"_TYPE": v:msgpack_types.binary, "_VAL": [$XXX_UNEXISTENT_VAR_XXX]}])')) eq({'\160'}, eval('msgpackdump([{"_TYPE": v:msgpack_types.string, "_VAL": [$XXX_UNEXISTENT_VAR_XXX]}])')) end) it('can dump NULL list', function() eq({'\144'}, eval('msgpackdump([v:_null_list])')) end) it('can dump NULL dictionary', function() eq({'\128'}, eval('msgpackdump([v:_null_dict])')) end) end)
--- @class GCTakeDamageInfo --- A class used to store and modify all the data concerning a damage event. --- An empty CTakeDamageInfo object can be created with Global.DamageInfo --- List of hooks that this object is passed to: --- * ENTITY:OnTakeDamage --- * GM:DoPlayerDeath --- * GM:EntityTakeDamage --- * GM:OnDamagedByExplosion --- * GM:ScaleNPCDamage --- * GM:ScalePlayerDamage --- * NEXTBOT:OnInjured --- * NEXTBOT:OnKilled --- * NEXTBOT:OnOtherKilled --- List of functions that use this object: --- * util.BlastDamageInfo --- * Entity:TakeDamageInfo --- * Entity:TakePhysicsDamage --- * Entity:DispatchTraceAttack local GCTakeDamageInfo = {} --- Increases the damage by damageIncrease. --- @param damageIncrease number @The damage to add. function GCTakeDamageInfo:AddDamage(damageIncrease) end --- Returns the ammo type used by the weapon that inflicted the damage. --- @return number @Ammo type ID function GCTakeDamageInfo:GetAmmoType() end --- Returns the attacker ( character who originated the attack ), for example a player or an NPC that shot the weapon. --- @return GEntity @The attacker function GCTakeDamageInfo:GetAttacker() end --- Returns the initial unmodified by skill level ( game.GetSkillLevel ) damage. --- @return number @baseDamage function GCTakeDamageInfo:GetBaseDamage() end --- Returns the total damage. --- @return number @damage function GCTakeDamageInfo:GetDamage() end --- Gets the current bonus damage. --- @return number @Bonus damage function GCTakeDamageInfo:GetDamageBonus() end --- Gets the custom damage type. This is used by Day of Defeat: Source and Team Fortress 2 for extended damage info, but isn't used in Garry's Mod by default. --- @return number @The custom damage type function GCTakeDamageInfo:GetDamageCustom() end --- Returns a vector representing the damage force. --- Can be set with CTakeDamageInfo:SetDamageForce. --- @return GVector @The damage force function GCTakeDamageInfo:GetDamageForce() end --- Returns the position where the damage was or is going to be applied to. --- Can be set using CTakeDamageInfo:SetDamagePosition. --- @return GVector @The damage position function GCTakeDamageInfo:GetDamagePosition() end --- Returns a bitflag which indicates the damage type(s) of the damage. --- Consider using CTakeDamageInfo:IsDamageType instead. Value returned by this function can contain multiple damage types. --- @return number @Damage type(s), a combination of Enums/DMG function GCTakeDamageInfo:GetDamageType() end --- Returns the inflictor of the damage. This is not necessarily a weapon. --- For hitscan weapons this is the weapon. --- For projectile weapons this is the projectile. --- For a more reliable method of getting the weapon that damaged an entity, use GetAttacker with GetActiveWeapon. --- @return GEntity @The inflictor function GCTakeDamageInfo:GetInflictor() end --- Returns the maximum damage. --- @return number @maxDmg function GCTakeDamageInfo:GetMaxDamage() end --- Returns the initial, unmodified position where the damage occured. --- @return GVector @position function GCTakeDamageInfo:GetReportedPosition() end --- Returns true if the damage was caused by a bullet. --- @return boolean @isBulletDmg function GCTakeDamageInfo:IsBulletDamage() end --- Returns whenever the damageinfo contains the damage type specified. --- @param dmgType number @Damage type to test --- @return boolean @Whether this damage contains specified damage type or not function GCTakeDamageInfo:IsDamageType(dmgType) end --- Returns whenever the damageinfo contains explosion damage. --- @return boolean @isExplDamage function GCTakeDamageInfo:IsExplosionDamage() end --- Returns whenever the damageinfo contains fall damage. --- @return boolean @isFallDmg function GCTakeDamageInfo:IsFallDamage() end --- Scales the damage by the given value. --- @param scale number @Value to scale the damage with. function GCTakeDamageInfo:ScaleDamage(scale) end --- Changes the ammo type used by the weapon that inflicted the damage. --- @param ammoType number @Ammo type ID function GCTakeDamageInfo:SetAmmoType(ammoType) end --- Sets the attacker ( character who originated the attack ) of the damage, for example a player or an NPC. --- @param ent GEntity @The entity to be set as the attacker. function GCTakeDamageInfo:SetAttacker(ent) end --- Sets the amount of damage. --- @param damage number @The value to set the absolute damage to. function GCTakeDamageInfo:SetDamage(damage) end --- Sets the bonus damage. Bonus damage isn't automatically applied, so this will have no outer effect by default. --- @param damage number @The extra damage to be added. function GCTakeDamageInfo:SetDamageBonus(damage) end --- Sets the custom damage type. This is used by Day of Defeat: Source and Team Fortress 2 for extended damage info, but isn't used in Garry's Mod by default. --- @param DamageType number @Any integer - can be based on your own custom enums. function GCTakeDamageInfo:SetDamageCustom(DamageType) end --- Sets the directional force of the damage. --- @param force GVector @The vector to set the force to. function GCTakeDamageInfo:SetDamageForce(force) end --- Sets the position of where the damage gets applied to. --- @param pos GVector @The position where the damage will be applied. function GCTakeDamageInfo:SetDamagePosition(pos) end --- Sets the damage type. --- @param type number @The damage type, see Enums/DMG. function GCTakeDamageInfo:SetDamageType(type) end --- Sets the inflictor of the damage for example a weapon. --- For hitscan/bullet weapons this should the weapon. --- For projectile ( rockets, etc ) weapons this should be the projectile. --- @param inflictor GEntity @The new inflictor. function GCTakeDamageInfo:SetInflictor(inflictor) end --- Sets the maximum damage the object can cause. --- @param maxDamage number @Maximum damage value. function GCTakeDamageInfo:SetMaxDamage(maxDamage) end --- Sets the origin of the damage. --- @param pos GVector @The location of where the damage is originating function GCTakeDamageInfo:SetReportedPosition(pos) end --- Subtracts the specified amount from the damage. --- @param damage number @Value to subtract. function GCTakeDamageInfo:SubtractDamage(damage) end
--[[ Entity info ]] ENT.Base = "base_gmodentity" ENT.Type = "anim" ENT.Category = "Respawn Point" ENT.Spawnable = true ENT.PrintName = "Respawn Point" ENT.Author = "Mailz" ENT.Contact = "Steam" ENT.Purpose = "Allow players set their custom spawn points" ENT.Instructions = "Spawn and press 'E' to register your spawnpoint. After respawning device will be deactivated for 60s. Avoid device damage." --[[ Shared values (all in one place) ]] RespawnPoint = RespawnPoint or {} -- Constants RespawnPoint.RechargeTime = 60 -- seconds RespawnPoint.MaxHP = 80 RespawnPoint.LowHP = 25 -- State RespawnPoint.DISCHARGED = 0 RespawnPoint.CHARGED = 1 RespawnPoint.UNASSIGNED = 2 -- Sound tables RespawnPoint.TeleportSounds = { "ambient/machines/teleport1.wav", "ambient/machines/teleport3.wav", "ambient/machines/teleport4.wav", } RespawnPoint.SparkSounds = { "ambient/energy/spark1.wav", "ambient/energy/spark2.wav", "ambient/energy/spark3.wav", "ambient/energy/spark4.wav", "ambient/energy/spark5.wav", "ambient/energy/spark6.wav", } RespawnPoint.ExplodeSounds = { "ambient/levels/labs/electric_explosion1.wav", "ambient/levels/labs/electric_explosion2.wav", "ambient/levels/labs/electric_explosion3.wav", "ambient/levels/labs/electric_explosion4.wav", "ambient/levels/labs/electric_explosion5.wav", } -- (Indicator) colors table RespawnPoint.IndicatorColor = {} RespawnPoint.IndicatorColor[RespawnPoint.UNASSIGNED] = Color(127, 127, 127, 127) RespawnPoint.IndicatorColor[RespawnPoint.DISCHARGED] = Color(255, 192, 0, 127) RespawnPoint.IndicatorColor[RespawnPoint.CHARGED] = Color(0, 63, 255, 127)
AddCSLuaFile() resource.AddFile("materials/deaf-icon.png") if (CLIENT) then local drawDeaf = false local deafIcon = Material("materials/deaf-icon.png") net.Receive("drawDeaf",function() drawDeaf = net.ReadBool() end) hook.Add( "HUDPaint", "ttt_dcrdint_HUDPaint", function() if (!drawDeaf) then return end surface.SetDrawColor(255, 255, 255, 255) surface.SetMaterial(deafIcon) surface.DrawTexturedRect(0, 0, 64, 64) end ) return end util.AddNetworkString("drawDeaf") CreateConVar("ttt_dcrdint_host", "localhost", FCVAR_ARCHIVE + FCVAR_NOTIFY, "Sets the node server address.") CreateConVar("ttt_dcrdint_port", "37405", FCVAR_ARCHIVE + FCVAR_NOTIFY, "Sets the node server port.") CreateConVar("ttt_dcrdint_name", "[TTT Discord Immersion] ", FCVAR_ARCHIVE + FCVAR_NOTIFY, "Sets the Plugin Prefix for helpermessages.") --The name which will be displayed in front of any Message CreateConVar("ttt_dcrdint_cachefile", "ttt_dcrdint.dat", FCVAR_ARCHIVE + FCVAR_NOTIFY, "Sets the cache file used tro store discord and steam ids that have been paired.") CreateConVar("ttt_dcrdint_bottries", 4, FCVAR_ARCHIVE + FCVAR_NOTIFY, "Sets the amount of times the addon should try and communicate with the discord bot server.") CreateConVar("ttt_dcrdint_enabled", 1, FCVAR_ARCHIVE + FCVAR_NOTIFY, "Enable or disables the addon.") CreateConVar("ttt_dcrdint_phoenixdeafen", 1, FCVAR_ARCHIVE + FCVAR_NOTIFY, "Enables or disables the deafening of the phoenix on first death.") phoenixDead = {} deafened = {} currentlyPrep = false denyDeafen = true print("DISCORD INTEGRATION ENABLED") idTable = {} idTable_raw = file.Read( GetConVar("ttt_dcrdint_cachefile"):GetString(), "DATA" ) if (idTable_raw) then idTable = util.JSONToTable(idTable_raw) end function printCon(message, error) if error then prefix = "[WARN] - "..GetConVar("ttt_dcrdint_name"):GetString() else prefix = GetConVar("ttt_dcrdint_name"):GetString() end print(prefix..message) end function saveIDs() file.Write( GetConVar("ttt_dcrdint_cachefile"):GetString(), util.TableToJSON(idTable)) end function GET(req,params,cb,tries) httpAdress = ("http://"..GetConVar("ttt_dcrdint_host"):GetString()..":"..GetConVar("ttt_dcrdint_port"):GetString()) http.Fetch(httpAdress,function(res) --print(res) cb(util.JSONToTable(res)) end,function(err) print("["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."Request to bot failed. Is the bot running?") print("Err: "..err) if (!tries) then tries = GetConVar("ttt_dcrdint_bottries"):GetInt() end if (tries != 0) then GET(req,params,cb, tries-1) end end,{req=req,params=util.TableToJSON(params)}) end function sendClientIconInfo(ply,deaf) net.Start("drawDeaf") net.WriteBool(deaf) net.Send(ply) end function sendClientIconInfoAll(deaf) net.Start("drawDeaf") net.WriteBool(deaf) net.Broadcast() end function isDeafened(ply) return deafened[ply] end function idString() idStringBuilder = "" firstItteration = true for _, ply in ipairs(player.GetAll()) do for steam, discordID in pairs(idTable) do if ply:SteamID() == steam then print(steam.." True") if firstItteration then idStringBuilder = discordID firstItteration = false else print(steam.." False") idStringBuilder = idStringBuilder..",;,"..discordID end end end end return idStringBuilder end function unDeafen(ply) if (idTable[ply:SteamID()]) then GET("undeafen",{ids=idTable[ply:SteamID()]}, function(res) if (res.success) then if (ply ~= nil) then ply:PrintMessage(HUD_PRINTCENTER,"["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."You're not deafened in discord!") end sendClientIconInfo(ply,false) deafened[ply] = false else print("["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."Error: "..res.error) end end) end end function deafenAll() if (!denyDeafen) then if (!currentlyPrep) then GET("deafen", {ids=idString()}, function(res) if (res.success) then PrintMessage(HUD_PRINTCENTER,"["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."You're deafened in discord!") sendClientIconInfoAll(true) for i=#deafened -1, 0, -1 do deafened[i] = true end else print("["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."Error: "..res.error) end end) end end end function deafen(ply) if (!denyDeafen) then if (!currentlyPrep) then GET("deafen", {ids=idTable[ply:SteamID()]}, function(res) if (res.success) then ply:PrintMessage(HUD_PRINTCENTER,"["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."You're deafened in discord!") sendClientIconInfo(ply, true) deafened[ply] = true else print("["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."Error: "..res.error) end end) end end end function unDeafenAll() GET("undeafen",{ids=idString()}, function(res) if (res.success) then PrintMessage(HUD_PRINTCENTER,"["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."You're not deafened in discord!") sendClientIconInfoAll(false) for i = #deafened -1, 0, -1 do deafened[i] = false end else print("["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."Error: "..res.error) end end) end function commonRoundState() if gmod.GetGamemode().Name == "Trouble in Terrorist Town" or gmod.GetGamemode().Name == "TTT2 (Advanced Update)" then -- Round state 3 => Game is running return ((GetRoundState() == 3) and 1 or 0) end if gmod.GetGamemode().Name == "Murder" then -- Round state 1 => Game is running return ((gmod.GetGamemode():GetRound() == 1) and 1 or 0) end -- Round state could not be determined return -1 end hook.Add("PlayerSay", "ttt_dcrdint_PlayerSay", function(ply,msg) if (string.sub(msg,1,9) != '!discord ') then return end tag = string.sub(msg,10) tag_utf8 = "" for p, c in utf8.codes(tag) do tag_utf8 = string.Trim(tag_utf8.." "..c) end GET("connect",{tag=tag_utf8},function(res) if (res.answer == 0) then ply:PrintMessage(HUD_PRINTTALK,"["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."No guild member with a discord tag like '"..tag.."' found.") end if (res.answer == 1) then ply:PrintMessage(HUD_PRINTTALK,"["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."Found more than one user with a discord tag like '"..tag.."'. Please specify!") end if (res.tag && res.id) then ply:PrintMessage(HUD_PRINTTALK,"["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."SteamID '"..ply:SteamID().."' successfully bound to Discord tag '"..res.tag.."'") idTable[ply:SteamID()] = res.id saveIDs() end end) return "" end) function playerdeath(ply, attacker, dmg) if GetConVar("ttt_dcrdint_phoenixdeafen"):GetBool() then if ply:GetRole() == ROLE_RESURRECTOR or ply:GetRole() == ROLE_PHOENIX then if !phoenixDead[ply] then phoenixDead[ply] = true return end end end if (attacker.IsPlayer() and attacker ~= ply) then if attacker:GetRole() == ROLE_INFECTED then return end if ply:GetRole() == ROLE_JESTER then return end end unDeafen(ply) end hook.Add("PlayerInitialSpawn", "ttt_dcrdint_PlayerInitialSpawn", function(ply) if (idTable[ply:SteamID()]) then ply:PrintMessage(HUD_PRINTTALK,"["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."You are connected with discord.") else ply:PrintMessage(HUD_PRINTTALK,"["..GetConVar("ttt_dcrdint_name"):GetString().."] ".."You are not connected with discord. Write '!discord DISCORDTAG' in the chat. E.g. '!discord marcel.js#4402'") end end) hook.Add("PlayerDisconnected", "ttt_dcrdint_PlayerDisconnected", function(ply) if GetConVar("ttt_dcrdint_enabled"):GetBool() then unDeafen(ply) end end) hook.Add("ShutDown","ttt_dcrdint_ShutDown", function() if GetConVar("ttt_dcrdint_enabled"):GetBool() then unDeafenAll() end end) hook.Add("TTTEndRound", "ttt_dcrdint_TTTEndRound", function() if GetConVar("ttt_dcrdint_enabled"):GetBool() then denyDeafen = true unDeafenAll() phoenixDead = {} end end) hook.Add("OnEndRound", "ttt_dcrdint_OnEndRound", function() if GetConVar("ttt_dcrdint_enabled"):GetBool() then denyDeafen = true unDeafenAll() end end) hook.Add("TTTBeginRound", "ttt_dcrdint_TTTBeginRound", function() if GetConVar("ttt_dcrdint_enabled"):GetBool() then deafenAll() end end) hook.Add("OnStartRound", "ttt_dcrdint_OnStartRound", function() if GetConVar("ttt_dcrdint_enabled"):GetBool() then deafenAll() end end) hook.Add("DoPlayerDeath", "ttt_dcrdint_DoPlayerDeath", function(ply, attacker, dmg) if GetConVar("ttt_dcrdint_enabled"):GetBool() then if (commonRoundState() == 1) then playerdeath(ply, attacker, dmg) end end end) hook.Add("TTTBeginRound", "ttt_dcrdint_TTTBeginRound", function() if GetConVar("ttt_dcrdint_enabled"):GetBool() then denyDeafen = false currentlyPrep = false deafenAll() end end) hook.Add("PlayerSpawn", "ttt_dcrdint_PlayerSpawn", function(ply) if GetConVar("ttt_dcrdint_enabled"):GetBool() then deafen(ply) end end) hook.Add("TTTPrepareRound", "ttt_dcrdint_TTTPrepareRound", function() if GetConVar("ttt_dcrdint_enabled"):GetBool() then denyDeafen = true currentlyPrep = true end end)
function make_test(group, name, fileglob) local pc_proj = precore.make_project( group .. "_" .. name, "C++", "ConsoleApp", "./", "obj/", nil, nil ) configuration {} targetname(name) includedirs { precore.subst("${ROOT}/include") } files {fileglob} libdirs {precore.subst("${ROOT}/lib")} links {"magic"} end function make_tests(group, tests) for name, fileglob in pairs(tests) do make_test(group, name, fileglob) end end precore.make_solution( "test_solution", {"debug", "release"}, {"native"} ) precore.import("general")
--- Utilities used by other modules. --- @module haproxy.util local M = {} --- Calls uname to return the current operating system. -- @treturn string function M.uname() local f = assert(io.popen('uname -s', 'r')) local os_name = assert(f:read('*a')) f:close() return os_name end --- Return whether a table contains the named function. -- @tparam table obj to inspect -- @tparam string method function name to check -- @treturn boolean function M.has_function(obj, method) return type(obj) == 'table' and obj[method] and type(obj[method]) == 'function' end return M
-- Folder name that the code base is held in. This must be confirmed before generating the solution. MainFolder = "Source" ModuleFolder = "Library.Modules" -- load functions dofile "Functions.lua" workspace "Library" location "../.." architecture "x86_64" startproject "Library" configurations { "Debug", "Release", "Dist" } flags { "MultiProcessorCompile" } outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}" -- Build Library dofile "Library.lua" -- Build Library.Business dofile "Library.Business.lua" -- Build Library.Core dofile "Library.Core.lua" -- Build Modules group "Modules" ModuleFolder = "%{wks.name}.Modules" -- Build Browser dofile "Library.Module.Browser.lua" -- Build PDF Viewer dofile "Library.Module.PDFViewer.lua"
ITEM.name = "Crystal Meth" ITEM.model = "models/katharsmodels/contraband/metasync/blue_sky.mdl" ITEM.desc = "A highly addictive drug that's inhaled" ITEM.duration = 100 ITEM.price = 20 ITEM.attribBoosts = { ["end"] = -2, ["stm"] = 3, } local effectText = { "You feel very alert yet paranoid and aggressive.", } ITEM:hook("_use", function(item) item.player:EmitSound("items/battery_pickup.wav") item.player:ChatPrint(table.Random(effectText)) item.player:ScreenFade(1, Color(255, 255, 255, 255), 3, 0) end)
object_tangible_loot_creature_loot_generic_humanoid_arm_bone = object_tangible_loot_creature_loot_generic_shared_humanoid_arm_bone:new { } ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_generic_humanoid_arm_bone, "object/tangible/loot/creature/loot/generic/humanoid_arm_bone.iff")
--[[Compys(TM) TapFAT Shared Library v1.54 for MineOS 2021 (C) Compys S&N Systems This is a driver library for a "Tape File Allocation Table" (or "TapFAT") system With this system you can use Computronics Tapes as a file storage like Floppy The first 8Kb of a space is reserved for special FAT with info about files on tape Data fragmentation is supported to more effective space allocation on a tape ]] local component = require("component") local fs = require("filesystem") local sz = require("text") local ser = function(value) local id = "^[%a_][%w_]*$" local ts = {} local result_pack = {} local function recurse(current_value, depth) local t = type(current_value) if t == "number" then if current_value ~= current_value then table.insert(result_pack, "0/0") elseif current_value == math.huge then table.insert(result_pack, "math.huge") elseif current_value == -math.huge then table.insert(result_pack, "-math.huge") else table.insert(result_pack, tostring(current_value)) end elseif t == "string" then table.insert(result_pack, (string.format("%q", current_value):gsub("\\\n","\\n"))) elseif t == "nil" or t == "boolean" then table.insert(result_pack, tostring(current_value)) elseif t == "table" then ts[current_value] = true local f local mt = getmetatable(current_value) f = table.pack((mt and mt.__pairs or pairs)(current_value)) local i = 1 local first = true table.insert(result_pack, "{") for k, v in table.unpack(f) do if not first then table.insert(result_pack, ",") end first = nil local tk = type(k) if tk == "number" and k == i then i = i + 1 recurse(v, depth + 1) else if tk == "string" and string.match(k, id) then table.insert(result_pack, k) else table.insert(result_pack, "[") recurse(k, depth + 1) table.insert(result_pack, "]") end table.insert(result_pack, "=") recurse(v, depth + 1) end end ts[current_value] = nil table.insert(result_pack, "}") else error("unsupported type: " .. t,0) end end recurse(value, 1) local result = table.concat(result_pack) return result end local unser = sz.deserialize local filedescript = {} local function segments(path) local parts = {} for part in path:gmatch("[^\\/]+") do local current, up = part:find("^%.?%.$") if current then if up == 2 then table.remove(parts) end else table.insert(parts, part) end end return parts end local function copytb(source) local result = {} for k, p in pairs(source) do result[k] = p end return result end local function gettim(driveprops) if not driveprops.stordate then return 0 end local name = '/Temporary/lt' local f = fs.open(name, "w") f:close() local time = fs.lastModified(name) fs.remove(name) return math.ceil(time) end local function oprval(ptab, filtab, wrt, val) if #ptab < 1 then return filtab end local i = 1 local scan = filtab while i < #ptab do if scan[ptab[i]] == nil then return false end scan = scan[ptab[i]] i = i+1 end if not wrt then return scan[ptab[i]] or false else scan[ptab[i]] = val return true end end local function setval(ptab, filtab, val) return oprval(ptab, filtab, true, val) end local function allocd(filtab, space) space = space or 0 for _, elem in pairs(filtab) do if type(elem) == "table" then if elem[1] == -1 then space = allocd(elem, space) else space = space + elem[1] end end end return space end local function mkrdir(ptab, filtab, driveprops, num) if num > #ptab then return true end local checks = {} local i = 0 while i<num do table.insert(checks, ptab[i+1]) i = i+1 end dir = oprval(checks, filtab) if dir == false then setval(checks, filtab, {-1, gettim(driveprops)}) end return mkrdir(ptab, filtab, driveprops, num+1) end local function remdir(fil, fat, seg) for k, file in pairs(fil) do if type(k) ~= 'number' then if file[1] == -1 then local cseg = copytb(seg) table.insert(cseg, k) local sfil = oprval(cseg, fat[1]) if not sfil then return sfil end if not remdir(sfil, fat, cseg) then return false end else for _, block in pairs(file[3]) do table.insert(fat[2], block) end end end end setval(seg, fat[1], nil) return true end local function findblock(blocks, pos) local i = 0 local bsiz = 0 while i < #blocks do i = i+1 local psiz = bsiz bsiz = bsiz + blocks[i][2] if psiz <= pos and bsiz >= pos then return i end end return false end local function blockssiz(fb, lb, fil) local bsiz = 0 while fb <= lb do bsiz = bsiz + fil[3][fb][2] fb = fb+1 end return bsiz end local function custsr(a, b) if a[1] < b[1] then return true else return false end end local function wrinew(fil, fat, stb, data, address) while true do if #fat[2] == 0 then fil[1] = blockssiz(1, #fil[3], fil) local res, err = stb(fat) if not res then return res, err else return true end elseif fat[2][1][2] < #data then table.insert(fil[3], {fat[2][1][1], fat[2][1][2]}) component.invoke(address, "seek", -math.huge) component.invoke(address, "seek", fat[2][1][1]) component.invoke(address, "write", data:sub(0,fat[2][1][2])) data = data:sub(fat[2][1][2]+1) table.remove(fat[2], 1) else table.insert(fil[3], {fat[2][1][1], #data}) component.invoke(address, "seek", -math.huge) component.invoke(address, "seek", fat[2][1][1]) component.invoke(address, "write", data) if #data == fat[2][1][2] then table.remove(fat[2], 1) else fat[2][1][1] = fat[2][1][1]+#data fat[2][1][2] = fat[2][1][2]-#data end break end end return 1 end local function wrialloc(fil, data, address, seek) local strtbl = findblock(fil[3], seek) local endbl = #fil[3] if not endbl then endbl = #fil[3] end component.invoke(address, "seek", fil[3][strtbl][1]+seek-blockssiz(1, strtbl-1, fil)) component.invoke(address, "write", data:sub(0,fil[3][strtbl][2])) data = data:sub(fil[3][strtbl][2]) strtbl = strtbl + 1 while strtbl < endbl + 1 do component.invoke(address, "seek", -math.huge) component.invoke(address, "seek", fil[3][strtbl][1]) component.invoke(address, "write", data:sub(0,fil[3][strtbl][2])) data = data:sub(fil[3][strtbl][2]) strtbl = strtbl + 1 end end local lzsscom, lzssdcom if require("computer").getArchitecture() == "Lua 5.3" then lzsscom, lzssdcom = load([[return function(input) local offset, output = 1, {} local window = '' local function search() for i = 18, 3, -1 do local str = string.sub(input, offset, offset + i - 1) local pos = string.find(window, str, 1, true) if pos then return pos, str end end end while offset <= #input do local flags, buffer = 0, {} for i = 0, 7 do if offset <= #input then local pos, str = search() if pos and #str >= 3 then local tmp = ((pos - 1) << 4) | (#str - 3) buffer[#buffer + 1] = string.pack('>I2', tmp) else flags = flags | (1 << i) str = string.sub(input, offset, offset) buffer[#buffer + 1] = str end window = string.sub(window .. str, -4096) offset = offset + #str else break end end if #buffer > 0 then output[#output + 1] = string.char(flags) output[#output + 1] = table.concat(buffer) end end return table.concat(output) end, function(input) local offset, output = 1, {} local window = '' while offset <= #input do local flags = string.byte(input, offset) offset = offset + 1 for i = 1, 8 do local str = nil if (flags & 1) ~= 0 then if offset <= #input then str = string.sub(input, offset, offset) offset = offset + 1 end else if offset + 1 <= #input then local tmp = string.unpack('>I2', input, offset) offset = offset + 2 local pos = (tmp >> 4) + 1 local len = (tmp & (15)) + 3 str = string.sub(window, pos, pos + len - 1) end end flags = flags >> 1 if str then output[#output + 1] = str window = string.sub(window .. str, -4096) end end end return table.concat(output) end]])() end local tapfat = {} function tapfat.proxy(address) local found = false for k,v in component.list("tape_drive") do if k == address and v == "tape_drive" then found = true break end end if not found then error("No such component",2) end local driveprops = {tabcom = false, stordate = true} component.invoke(address, "seek", -math.huge) local proxyObj = {} proxyObj.type = "filesystem" proxyObj.driveAddress = address proxyObj.address = address:gsub("-","") .. "-tap" proxyObj.isReady = function() return component.invoke(address, "isReady") end proxyObj.setDriveProperty = function(proptype, value) checkArg(1,proptype,"string") checkArg(2,value,"number","string","boolean") if driveprops[proptype] == nil then return nil, 'Invalid property' end driveprops[proptype] = value return true end proxyObj.getDriveProperty = function(proptype) checkArg(1,proptype,"string") if driveprops[proptype] == nil then return nil, 'Invalid property' end return driveprops[proptype] end proxyObj.getTable = function() if not proxyObj.isReady() then return nil, 'Device is not ready' end component.invoke(address, "seek", -math.huge) local tabsec = component.invoke(address, "read", 8192) local rawtm if tabsec:sub(0,2) == "{{" then rawtm = tabsec:match("[^\0]+") elseif tabsec:sub(3,4) == "\120\156" then if not component.isAvailable('data') then return nil, 'inflate: Data card required' end if not string.unpack then return nil, 'string.unpack: Lua 5.3 required' end rawtm = component.data.inflate(string.unpack('s2', tabsec)) elseif tabsec:sub(0,2) ~= "\0\0" then if not lzssdcom then return nil, 'LZSS decompression: Lua 5.3 required' end rawtm = lzssdcom(string.unpack('s2', tabsec)) end if not rawtm or rawtm == "" then return nil, 'FAT corrupted: table not found' end local uns, err = unser(rawtm) if not uns then return nil, 'FAT corrupted: '..(err or 'unknown reason') else return uns end end proxyObj.setTable = function(tab) checkArg(1,tab,"table") if not proxyObj.isReady() then return nil, 'Device is not ready' end local tstr = ser(tab) if driveprops.tabcom == 1 then if not lzsscom then return nil, 'LZSS compression: Lua 5.3 required' end tstr = string.pack('s2', lzsscom(tstr)) elseif driveprops.tabcom == 2 then if not component.isAvailable('data') then return nil, 'deflate: Data card required' end if not string.pack then return nil, 'string.pack: Lua 5.3 required' end tstr = string.pack('s2', component.data.deflate(tstr)) end if #tstr > 8192 then return nil, 'Not enough space for FAT' end if #tstr ~= 8192 then tstr = tstr.."\0" end component.invoke(address, "seek", -math.huge) component.invoke(address, "write", tstr) return #tstr end proxyObj.format = function(fast) fast = fast or false checkArg(1,fast,"boolean") if not proxyObj.isReady() then return nil, 'Device is not ready' end local siz = component.invoke(address, "getSize") if not fast then component.invoke(address, "seek", -math.huge) local ns = string.rep("\0", 8192) for i = 1, siz + 8191, 8192 do component.invoke(address, "write", ns) end end local res, err = proxyObj.setTable({{}, {{8192, math.ceil(siz)-8192}}}) if not res then return res, err else if component.invoke(address, "getLabel") == "" then component.invoke(address, "setLabel", "TapFAT Data Tape") end return true end end proxyObj.isDirectory = function(path) checkArg(1,path,"string") if not proxyObj.isReady() then return nil, 'Device is not ready' end if path == '' then return true end local seg = segments(path) local fat, reas = proxyObj.getTable() if not fat then return fat, reas end local list = oprval(seg, fat[1]) if type(list) ~= 'table' then return false end if list[1] == -1 then return true else return false end end proxyObj.lastModified = function(path) checkArg(1,path,"string") if not proxyObj.isReady() then return nil, 'Device is not ready' end local fat, reas = proxyObj.getTable() if not fat then return fat, reas end local seg = segments(path) local fil = oprval(seg, fat[1]) if not fil then return 0 end return fil[2] or 0 end proxyObj.list = function(path) checkArg(1,path,"string") if not proxyObj.isReady() then return nil, 'Device is not ready' end local fat, reas = proxyObj.getTable() if not fat then return fat, reas end local seg = segments(path) local rlist = oprval(seg, fat[1]) if rlist == false then return nil, 'no such file or directory: '..path end local list = {} if rlist[1] ~= -1 and #seg ~= 0 then return {seg[#seg], n=1} end for k, p in pairs(rlist) do if type(k) ~= 'number' then if p[1] == -1 then table.insert(list, k..'/') else table.insert(list, k) end end end list.n = #list return list end proxyObj.spaceTotal = function() if not proxyObj.isReady() then return nil, 'Device is not ready' end return component.invoke(address, "getSize")-8193 end proxyObj.open = function(path,mode) mode = mode or 'r' checkArg(1,path,"string") checkArg(2,mode,"string") if not proxyObj.isReady() then return nil, 'Device is not ready' end local descrpt local fat, reas = proxyObj.getTable() if not fat then return fat, reas end local seg = segments(path) if mode ~= "r" and mode ~= "rb" and mode ~= "w" and mode ~= "wb" and mode ~= "a" and mode ~= "ab" then error("unsupported mode",2) end local work = true while work do descrpt = math.random(1000000000,9999999999) if filedescript[descrpt] == nil then if mode == "r" or mode == "rb" then local fildat = oprval(seg, fat[1]) if not fildat or fildat[1] == -1 then return nil, path end filedescript[descrpt] = { seek = 0, mode = 'r', path = seg } elseif mode == "w" or mode == "wb" then filedescript[descrpt] = { seek = 0, mode = 'w', path = seg } local fildat = oprval(seg, fat[1]) if fildat then for _, blk in pairs(fildat[3]) do table.insert(fat[2], blk) end table.sort(fat[2], custsr) local curb = 1 while curb < #fat[2] do if fat[2][curb][1]+fat[2][curb][2] == fat[2][curb+1][1] then fat[2][curb][2] = fat[2][curb][2]+fat[2][curb+1][2] table.remove(fat[2], curb+1) else curb = curb + 1 end end elseif #fat[2] == 0 then return nil, "not enough space" end if not setval(seg, fat[1], {0, gettim(driveprops), {}}) then return false end elseif mode == "a" or mode == "ab" then local fildat = oprval(seg, fat[1]) local sz if not fildat then if not setval(seg, fat[1], {0, gettim(driveprops), {}}) then return false end else sz = fildat[1]+1 end filedescript[descrpt] = { seek = sz, mode = 'a', path = seg } end work = false end end if mode == "a" or mode == "ab" or mode == "w" or mode == "wb" then local res, err = proxyObj.setTable(fat) if not res then return res, err else return descrpt end else return descrpt end end proxyObj.remove = function(path) checkArg(1,path,"string") if not proxyObj.isReady() then return nil, 'Device is not ready' end if path == '' then return false end local fat, reas = proxyObj.getTable() if not fat then return fat, reas end local seg = segments(path) local fil = oprval(seg, fat[1]) if fil == false then return false end if fil[1] == -1 then remdir(fil, fat, seg) else for _, block in pairs(fil[3]) do table.insert(fat[2], block) end setval(seg, fat[1], nil) end table.sort(fat[2], custsr) local curb = 1 while curb < #fat[2] do if fat[2][curb][1]+fat[2][curb][2] == fat[2][curb+1][1] then fat[2][curb][2] = fat[2][curb][2]+fat[2][curb+1][2] table.remove(fat[2], curb+1) else curb = curb + 1 end end local res, err = proxyObj.setTable(fat) if not res then return res, err else return true end end proxyObj.rename = function(path, newpath) checkArg(1,path,"string") checkArg(1,newpath,"string") if not proxyObj.isReady() then return nil, 'Device is not ready' end local fat, reas = proxyObj.getTable() if not fat then return fat, reas end local seg = segments(path) local seg2 = segments(newpath) local fil = oprval(seg, fat[1]) local fil2 = oprval(seg2, fat[1]) if not fil or fil2 then return false end if fil[1] ~= -1 then seg2 = segments(newpath) end setval(seg, fat[1], nil) if not setval(seg2, fat[1], fil) then return false end local res, err = proxyObj.setTable(fat) if not res then return res, err else return true end end proxyObj.read = function(fd, count) count = count or 1 checkArg(1,fd,"number") checkArg(2,count,"number") if not proxyObj.isReady() then return nil, 'Device is not ready' end if filedescript[fd] == nil or filedescript[fd].mode ~= "r" then return nil, "bad file descriptor" end local fat, reas = proxyObj.getTable() if not fat then return fat, reas end local fil = oprval(filedescript[fd].path, fat[1]) if not fil then filedescript[fd] = nil return nil, "bad file descriptor" end if fil[1] == 0 or fil[1] < filedescript[fd].seek+1 then return nil end if fil[1] >= filedescript[fd].seek+1 and fil[1] < filedescript[fd].seek+count then count = fil[1]-filedescript[fd].seek end component.invoke(address, "seek", -math.huge) local strtbl = findblock(fil[3], filedescript[fd].seek) local endbl = findblock(fil[3], filedescript[fd].seek + count) if not endbl then endbl = #fil[3] end component.invoke(address, "seek", fil[3][strtbl][1]+filedescript[fd].seek-blockssiz(1, strtbl-1, fil)) local data = component.invoke(address, "read", fil[3][strtbl][2]) strtbl = strtbl + 1 while strtbl < endbl + 1 do component.invoke(address, "seek", -math.huge) component.invoke(address, "seek", fil[3][strtbl][1]) data = data..component.invoke(address, "read", fil[3][strtbl][2]) strtbl = strtbl + 1 end data = data:sub(0, count) filedescript[fd].seek = filedescript[fd].seek + #data return data end proxyObj.close = function(fd) checkArg(1,fd,"number") if not proxyObj.isReady() then return nil, 'Device is not ready' end if filedescript[fd] == nil then return nil, "bad file descriptor" end filedescript[fd] = nil end proxyObj.getLabel = function() if not proxyObj.isReady() then return 'TapFAT Drive' end return component.invoke(address, "getLabel") end proxyObj.seek = function(fd,kind,offset) checkArg(1,fd,"number") checkArg(2,kind,"string") checkArg(3,offset,"number") if not proxyObj.isReady() then return nil, 'Device is not ready' end if filedescript[fd] == nil then return nil, "bad file descriptor" end if kind ~= "set" and kind ~= "cur" and kind ~= "end" then error("invalid mode",2) end if offset < 0 then return nil, "Negative seek offset" end local newpos if kind == "set" then newpos = offset elseif kind == "cur" then newpos = filedescript[fd].seek + offset elseif kind == "end" then newpos = component.invoke(address, "getSize") + offset - 1 end filedescript[fd].seek = math.min(math.max(newpos, 0), component.invoke(address, "getSize") - 1) return filedescript[fd].seek end proxyObj.size = function(path) checkArg(1,path,"string") if not proxyObj.isReady() then return nil, 'Device is not ready' end if path == '' then return 0 end local fat, reas = proxyObj.getTable() if not fat then return fat, reas end local seg = segments(path) local fil = oprval(seg, fat[1]) if not fil or fil[1] == -1 then return 0 end return fil[1] end proxyObj.isReadOnly = function() if not proxyObj.isReady() then return nil, 'Device is not ready' end return false end proxyObj.setLabel = function(newlabel) if not proxyObj.isReady() then return nil, 'Device is not ready' end component.invoke(address, "setLabel", newlabel) return newlabel end proxyObj.makeDirectory = function(path) checkArg(1,path,"string") if not proxyObj.isReady() then return nil, 'Device is not ready' end local fat, reas = proxyObj.getTable() if not fat then return fat, reas end local seg = segments(path) mkrdir(seg, fat[1], driveprops, 1) local res, err = proxyObj.setTable(fat) if not res then return res, err else return true end end proxyObj.exists = function(path) checkArg(1,path,"string") if not proxyObj.isReady() then return nil, 'Device is not ready' end if path == '' then return true end local seg = segments(path) local fat, reas = proxyObj.getTable() if not fat then return fat, reas end local list = oprval(seg, fat[1]) if list then return true else return list end end proxyObj.spaceUsed = function() if not proxyObj.isReady() then return nil, 'Device is not ready' end local fat, reas = proxyObj.getTable() if not fat then return fat, reas end return allocd(fat[1]) end proxyObj.write = function(fd,data) checkArg(1,fd,"number") checkArg(2,data,"string") if not proxyObj.isReady() then return nil, 'Device is not ready' end if filedescript[fd] == nil or filedescript[fd].mode == "r" then return nil, "bad file descriptor" end local fat, reas = proxyObj.getTable() if not fat then return fat, reas end if #fat[2] == 0 then return nil, "not enough space" end local seg = filedescript[fd].path local fil = oprval(seg, fat[1]) filedescript[fd].seek = filedescript[fd].seek + #data if filedescript[fd].seek > fil[1] or #fil[3] == 0 then fil[1] = fil[1] + #data local res, err = wrinew(fil, fat, proxyObj.setTable, data, address) if not res then return res, err elseif res ~= 1 then return true end elseif filedescript[fd].seek + #data > fil[1] then fil[1] = filedescript[fd].seek + #data wrialloc(fil, data, address, filedescript[fd].seek) local res, err = wrinew(fil, fat, proxyObj.setTable, data, address) if not res then return res, err elseif res ~= 1 then return true end else wrialloc(fil, data, address, filedescript[fd].seek) end local curb = 1 while curb < #fil[3] do if fil[3][curb][1]+fil[3][curb][2] == fil[3][curb+1][1] then fil[3][curb][2] = fil[3][curb][2]+fil[3][curb+1][2] table.remove(fil[3], curb+1) else curb = curb + 1 end end setval(seg, fat[1], fil) local res, err = proxyObj.setTable(fat) if not res then return res, err else return true end end return proxyObj end return tapfat
------------------------------------------------------------------------------- -- Copyright(C) machine stdio -- -- Author: donney -- -- Email: donney_luck@sina.cn -- -- Date: 2021-05-25 -- -- Description: service room -- -- Modification: null -- ------------------------------------------------------------------------------- require("base.init") local name, id = ... local s = require "faci.service" s.init(name, id)
AddCSLuaFile() function EFFECT:Init(data) self.Start = data:GetOrigin() self.size = 4000 self.Emitter = ParticleEmitter(self.Start) for i = 1, 30 do local vec = VectorRand() local p = self.Emitter:Add("effects/fleck_cement" .. math.random(1, 2), self.Start) p:SetDieTime(math.random(1, 15)) p:SetStartAlpha(math.random(50, 150)) p:SetEndAlpha(0) p:SetStartSize(math.random(1, 3)) p:SetRoll(math.Rand(-10, 10)) p:SetRollDelta(math.Rand(-10, 10)) p:SetEndSize(0) p:SetVelocity(vec * 450) p:SetGravity(Vector(0, 0, -50)) p:SetColor(0, 0, 0) end for i = 1, 10 do local vec = VectorRand() local p = self.Emitter:Add("particle/smokesprites_000" .. math.random(1, 9), self.Start + vec) p:SetDieTime(math.random(2, 3)) p:SetStartAlpha(math.random(50, 150)) p:SetEndAlpha(0) p:SetStartSize(20) --p:SetRoll(math.Rand(-10, 10)) p:SetRollDelta(math.Rand(-1, 1)) p:SetEndSize(80) p:SetVelocity(vec * 40) p:SetGravity(Vector(0, 0, 20)) p:SetCollide(true) p:SetColor(50, 50, 20) end for i = 3, math.random(3, 6) do local vec = VectorRand() for a = 1, math.random(4, 8) do local p = self.Emitter:Add("particle/smokesprites_000" .. math.random(1, 3), self.Start + vec * 15) p:SetDieTime(math.Rand(0.6, 1.5)) p:SetStartAlpha(math.random(40, 80)) p:SetEndAlpha(0) p:SetStartSize(20) p:SetRoll(math.Rand(-180, 180)) --p:SetRollDelta(math.Rand(-1, 1)) p:SetEndSize(150) p:SetVelocity(((self.Start + vec * a * 15) - self.Start):GetNormal() * a * 200) p:SetAirResistance(300 + a * 20) p:SetCollide(true) p:SetColor(0, 0, 0) local p = self.Emitter:Add("particles/fir21", self.Start + vec * a * math.Rand(10, 18) + VectorRand() * 40) p:SetDieTime(0.05) p:SetStartAlpha(40) p:SetEndAlpha(0) p:SetStartSize(20) p:SetRoll(math.Rand(-10, 10)) p:SetRollDelta(math.Rand(-1, 1)) p:SetEndSize(70) p:SetVelocity(((self.Start + vec * a * 15) - self.Start):GetNormal() * 500) p:SetAirResistance(20) p:SetColor(200, 150, 0) end end for i = 1, 30 do local vec = VectorRand() local p = self.Emitter:Add("particles/fir21", self.Start + vec * 25) p:SetDieTime(0.1) p:SetStartAlpha(60) p:SetEndAlpha(0) p:SetStartSize(20) p:SetRoll(math.Rand(-10, 10)) p:SetRollDelta(math.Rand(-0.5, 0.5)) p:SetEndSize(60) p:SetVelocity(vec * 155) p:SetAirResistance(40) p:SetColor(255, 200, 0) end self.Emitter:Finish() end function EFFECT:Think() self.size = self.size - 500 return self.size > 0 end function EFFECT:Render() render.SetMaterial(Material("sprites/light_ignorez")) render.DrawSprite(self.Start, self.size*2, self.size, Color(255, 100, 0, 50)) end
-- invalid user test wrk.method = "POST" wrk.body = '--------------------------12345\r\nContent-Disposition: form-data; name="data"\r\n\r\n{"phone_number":"09336521656","device_id":"dev"}\r\n--------------------------12345--\r\n' wrk.headers["Content-Type"] = "multipart/form-data; boundary=------------------------12345" function response(status, headers, body) print(body) end
function camInit(x1,y1,x2,y2) cam = {x = 0,y = 0, vx = 0, vy = 0, real = {x = 0, y = 0}, scale = 1, a = camera.new(x1, y1, x2, y2), zoom = 100, update = function (dt) local check = false for i,v in ipairs (craft) do if v.control then cam.x, cam.y = v.x+(math.abs(v.vx)*math.sin(v.angle))/3, v.y-(math.abs(v.vy)*math.cos(v.angle))/3 end end cam.a:setPosition((cam.x),(cam.y)) cam.real.x,cam.real.y = cam.a:getPosition() cam.a:setScale(cam.scale) end } end
require("prototypes.constants") --//////////////////////////////////////// --MSR Entity --//////////////////////////////////////// data:extend({ { burner = { burnt_inventory_size = 0, effectivity = 0.55, fuel_inventory_size = 1, fuel_category = "msr-nuclear", smoke = { { --Cooling tower in bottom-left. east_position = { -6, -- 5 to 15 == more east 0 -17.5 -- -30 to -40 == more north }, frequency = 8, name = "msr-cooling-tower-smoke", --Cooling tower in bottom-right. north_position = { 16, -17.5 }, --Cooling tower upper-left south_position = { -6, -40 }, --Cooling tower upper-right west_position = { 16, -40 }, slow_down_factor = 1, starting_frame_deviation = 60, starting_vertical_speed = 0.08 } }, }, collision_box = { { -29.900000000000001, -29.900000000000001 }, { 29.900000000000001, 29.900000000000001 } }, corpse = "steam-engine-remnants", dying_explosion = "medium-explosion", effectivity = .55, energy_source = { type = "electric", --While underground, we are still dumping waste underground, and that waste his HIGHLY pollutant. emissions_per_minute = 5, usage_priority = "primary-output" }, map_color = {119, 255, 56, 255}, fast_replaceable_group = "msr", flags = { "placeable-neutral", "player-creation" }, --For sanity's sake, the animation direction is based on which way the turbine hall is pointing. animation = { north = { layers = { { filename = "__NuclearRebalance__/graphics/entity/e-msr-n.png", frame_count = 1, width = 586, height = 703, hr_version = nil, line_length = 1, shift = { 0, -5.25 }, scale = 3.18, }, { draw_as_shadow = true, filename = "__NuclearRebalance__/graphics/entity/e-msr-n-shadow.png", frame_count = 1, width = 996, height = 597, hr_version = nil, line_length = 1, shift = { 20.25, 0 }, scale = 3.18 }, } }, --new east = { layers = { { filename = "__NuclearRebalance__/graphics/entity/e-msr-e.png", frame_count = 1, width = 586, height = 707, hr_version = nil, line_length = 1, shift = { 0, -6 }, scale = 3.2, }, { draw_as_shadow = true, filename = "__NuclearRebalance__/graphics/entity/e-msr-e-shadow.png", frame_count = 1, width = 770, height = 604, hr_version = nil, line_length = 1, shift = { 9.25, -1 -- was -.5 }, scale = 3.2 }} }, --Blender note: Multiply Y axis by 1.36 to get correct scaling. south = { layers = { { filename = "__NuclearRebalance__/graphics/entity/e-msr-s.png", frame_count = 1, width = 586, height = 920, hr_version = nil, line_length = 1, shift = { 0, -17 }, scale = 3.2, }, { draw_as_shadow = true, filename = "__NuclearRebalance__/graphics/entity/e-msr-s-shadow.png", frame_count = 1, width = 782, height = 707, hr_version = nil, line_length = 1, shift = { 9.8125, -6.5 }, scale = 3.2 }, } }, west = { layers = { { filename = "__NuclearRebalance__/graphics/entity/e-msr-w.png", frame_count = 1, width = 587, height = 925, hr_version = nil, line_length = 1, shift = { 0, -16.5 }, scale = 3.18, }, { draw_as_shadow = true, filename = "__NuclearRebalance__/graphics/entity/e-msr-w-shadow.png", frame_count = 1, width = 1008, height = 705, hr_version = nil, line_length = 1, shift = { 21, -5.5 }, scale = 3.18 }} } }, icon = "__NuclearRebalance__/graphics/icons/msr/i-msr.png", icon_size = 128, max_health = 7000, max_power_output = tostring(msr_target_power_output_gw) .. "GW", min_perceived_performance = 0.25, minable = { mining_time = 30, result = "msr" }, name = "msr", performance_to_sound_speedup = 0.5, selection_box = { { -29.5, -29.5 }, { 29.5, 29.5 } }, type = "burner-generator", vehicle_impact_sound = { filename = "__base__/sound/car-stone-impact.ogg", volume = 0.65 } } })
AddCSLuaFile() ENT.Type = "anim" ENT.Base = "base_gmodentity" ENT.PrintName = "Grenade_Ent" ENT.Author = "Zenolisk" ENT.Contact = "" ENT.Purpose = "" ENT.Instructions = "" ENT.Spawnable = true ENT.Category = "Rebellion" if SERVER then function ENT:Initialize() -- Boiler plate self.Entity:SetModel( "models/props_junk/garbage_plasticbottle001a.mdl" ) self.Entity:PhysicsInit(SOLID_VPHYSICS) self.Entity:SetMoveType(MOVETYPE_VPHYSICS) self.Entity:SetSolid(SOLID_VPHYSICS) local phys = self:GetPhysicsObject() if (phys:IsValid()) then phys:Wake() end timer.Simple(3, function() if IsValid(self.Entity) then self:Destruct() end end) end function ENT:Use( activator, caller ) end function ENT:Destruct() self:EmitSound( "ambient/explosions/explode_" .. math.random( 1, 9 ) .. ".wav" ) local d = DamageInfo() d:SetDamage( 35 ) d:SetDamageType( DMG_CLUB ) d:SetAttacker(self) util.BlastDamageInfo(d, self:GetPos(), 250) local vPoint = self:GetPos() local effectdata = EffectData() effectdata:SetStart(vPoint) effectdata:SetOrigin(vPoint) effectdata:SetScale(0.1) util.Effect("Explosion", effectdata) for i=1,5 do local mini = ents.Create("reb_grenade_mini_ent") mini:SetPos(self:GetPos() + Vector(math.random(5,10),math.random(5,10),math.random(5,15))) mini:Spawn() local phys = mini:GetPhysicsObject() phys:ApplyForceCenter(Vector(math.random(-1000,1000),math.random(-1000,1000),math.random(1000,2000))) end self:Remove() end function ENT:PhysicsCollide(data, phys) if data.Speed > 50 then self.Entity:EmitSound( Format( "physics/metal/metal_grenade_impact_hard%s.wav", math.random( 1, 3 ) ) ) end local impulse = -data.Speed * data.HitNormal * 0.1 + (data.OurOldVelocity * -0.1) phys:ApplyForceCenter(impulse) end else --CL code end
local State = require("stateBase") local ConcreteState2 = State:new() function ConcreteState2:handle(context) print(context:getHour()) print("ConcreteState2:handle") end return ConcreteState2
-- Enter the button number, you want to use for simple trim here simple_trim_button = 330 -- edit the factor, to define simple_trim's sensibility stg_trim_factor = 1.0 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- leave the rest of the file as it is, if you are not a Lua programmer -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- global variables we need -- all global variables start with 'stg_' to avoid conflicts with other scripts stg_elv_axis = 1 stg_rud_axis = 2 stg_ail_axis = 3 -- defining the datarefs we need DataRef("xp_override_joystick", "sim/operation/override/override_joystick", "writable") DataRef("xp_ail_trim", "sim/flightmodel/controls/ail_trim", "writable") DataRef("xp_elv_trim", "sim/flightmodel/controls/elv_trim", "writable") DataRef("xp_rud_trim", "sim/flightmodel/controls/rud_trim", "writable") -- as we do not know where the axis are located to, we have to find it out -- datarefs' names starts with std_ function simple_trim_init() local axis_function_type_is = 0 local i -- take a look where the right axis are for i = 0, 99 do axis_function_type_is = get("sim/joystick/joystick_axis_assignments", i) if axis_function_type_is == 1 then DataRef("std_elv_value", "sim/joystick/joystick_axis_values", "readonly", i) end if axis_function_type_is == 2 then DataRef("std_ail_value", "sim/joystick/joystick_axis_values", "readonly", i) end if axis_function_type_is == 3 then DataRef("std_rud_value", "sim/joystick/joystick_axis_values", "readonly", i) end end end function simple_trim() -- we will only work when the button is down if not button(simple_trim_button) and not last_button(simple_trim_button) then return end -- we start overriding on first press if button(simple_trim_button) and not last_button(simple_trim_button) then xp_override_joystick = 1 end -- don't forget to reset the override when finished if not button(simple_trim_button) and last_button(simple_trim_button) then xp_override_joystick = 0 end -- while trimming we will write the axis values into the trim datarefs -- the axis values run from 0.0 to 1.0, but the trim values run from -1.0 to 1.0 if button(simple_trim_button) and last_button(simple_trim_button) then xp_ail_trim = (std_ail_value * 2.0 - 1.0) * stg_trim_factor xp_rud_trim = (std_rud_value * 2.0 - 1.0) * stg_trim_factor xp_elv_trim = (std_elv_value * 2.0 - 1.0) * stg_trim_factor end -- store the last value to check out state stg_last_button = simple_trim_button end simple_trim_init() do_every_frame("simple_trim()")
object_tangible_loot_loot_schematic_marauder_s02_helmet_schematic = object_tangible_loot_loot_schematic_shared_marauder_s02_helmet_schematic:new { templateType = LOOTSCHEMATIC, customName = "Marauder Armor Helmet Schematic", objectMenuComponent = "LootSchematicMenuComponent", attributeListComponent = "LootSchematicAttributeListComponent", requiredSkill = "crafting_armorsmith_master", targetDraftSchematic = "object/draft_schematic/clothing/shared_clothing_armor_marauder_s02_helmet.iff", targetUseCount = 1 } ObjectTemplates:addTemplate(object_tangible_loot_loot_schematic_marauder_s02_helmet_schematic, "object/tangible/loot/loot_schematic/marauder_s02_helmet_schematic.iff")
return require('local_chain')
-- local log = require("hs.logger").new("t_binding") -- local inspect = require("hs.inspect") local require = require local test = require("cp.test") local binding = require("binding") local parameter = require("parameter") return test.suite("binding"):with { test("new", function() local o = binding.new("Foo") ok(o ~= nil) ok(eq(o.name, "Foo")) end), test("member", function() local p1 = parameter.new(0x01) local p2 = parameter.new(0x02) local o = binding.new("Foo") o:member(p1) o:member(p2) ok(eq(o.name, "Foo")) ok(eq(o._members, {p1, p2})) ok(eq(tostring(o:xml()), [[<Binding name="Foo"><Member id="0x00000001"/><Member id="0x00000002"/></Binding>]])) end), test("members", function() local p1 = parameter.new(0x01) local p2 = parameter.new(0x02) local o = binding.new("Foo") o:members(p1, p2) ok(eq(o.name, "Foo")) ok(eq(o._members, {p1, p2})) ok(eq(tostring(o:xml()), [[<Binding name="Foo"><Member id="0x00000001"/><Member id="0x00000002"/></Binding>]])) end), }
--[[ This file is part of zlib. It is subject to the licence terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/pallene-modules/zlib/master/COPYRIGHT. No part of zlib, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. Copyright © 2015 The developers of zlib. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/pallene-modules/zlib/master/COPYRIGHT. ]]--
--bios modem = component.proxy(component.list("modem")()) function sleep(n) local deadline = computer.uptime() + (n or 0) repeat computer.pullSignal(deadline - computer.uptime()) until computer.uptime() >= deadline end env = {require = require, drone = component.proxy(component.list("drone")()), addUser = computer.addUser, setArchitecture = computer.setArchitecture, beep = computer.beep, sleep = sleep} PORT = 5 energy = 5000 clock = os.clock started = false code = "while true do beep() sleep(1) end" GMAddr = "" modem.open(PORT) -------------------Thread------------------ computer.SingleThread = computer.pullSignal local thread = {} local mainThread local timeouts local function MultiThread( _timeout ) if coroutine.running()==mainThread then local mintime = _timeout or math.huge local co=next(timeouts) while co do if coroutine.status( co ) == "dead" then timeouts[co],co=nil,next(timeouts,co) else if timeouts[co] < mintime then mintime=timeouts[co] end co=next(timeouts,co) end end if not next(timeouts) then computer.pullSignal=computer.SingleThread computer.pushSignal("AllThreadsDead") end local event={computer.SingleThread(mintime)} local ok, param for co in pairs(timeouts) do ok, param = coroutine.resume( co, table.unpack(event) ) if not ok then timeouts={} error( param ) else timeouts[co] = param or math.huge end end return table.unpack(event) else return coroutine.yield( _timeout ) end end function thread.init() mainThread=coroutine.running() timeouts={} end function thread.create(f,...) computer.pullSignal=MultiThread local co=coroutine.create(f) timeouts[co]=math.huge local ok, param = coroutine.resume( co, ... ) if not ok then timeouts={} error( param ) else timeouts[co] = param or math.huge end return co end function thread.kill(co) timeouts[co]=nil end function thread.killAll() timeouts={} computer.pullSignal=computer.SingleThread end function thread.waitForAll() repeat until MultiThread()=="AllThreadsDead" end thread.init() ------------------------------------------- function sendMsg(str) modem.send(GMAddr, PORT, str) end function startCode() started = true assert(load(code, nil, nil, env))() started = false end function stopCode() if codeTH ~= nil then started = false thread.kill(codeTH) codeTH = nil else sendMsg("rip") started = false end end function energyTick() while true do if started then energy = energy-0.4 if energy<1 then stopCode() backToHome() end end sleep(0.05) end end function backToHome() --home end function main() while true do msg = {computer.pullSignal()} if msg[6] == "ping" then if started then sendMsg("pong") end elseif msg[6] == "code" then if load(msg[7]) ~= nil then code=msg[7] else sendMsg("Syntax error") end elseif msg[6] == "start" then if code ~= "" and started == false then codeTH = thread.create(startCode) else sendMsg("Code not found") end elseif msg[6] == "stop" then stopCode() elseif msg[6] == "home" then backToHome() end sleep(0.05) end end thread.create(main) thread.create(energyTick) thread.waitForAll()
require "CommonUtils" require "NSData" class(StringUtils); function StringUtils.appendingPathComponent(path, component) return runtime::invokeClassMethod("LIStringUtils", "appendingPath:component:", path, component); end function StringUtils.md5(str) return runtime::invokeClassMethod("LIStringUtils", "md5ForString:", str); end function StringUtils.removeUnicodeCharsFromString(str) return runtime::invokeClassMethod("LIStringUtils", "removeAllUnicode:", str); end function StringUtils.trim(str) return runtime::invokeClassMethod("LIStringUtils", "trim:", str); end function StringUtils.hasPrefix(str, prefix) return toLuaBool(runtime::invokeClassMethod("LIStringUtils", "string:hasPrefix:", str, prefix)); end function StringUtils.length(str) return tonumber(runtime::invokeClassMethod("LIStringUtils", "length:", str)); end function StringUtils.equals(str1, str2) return toLuaBool(runtime::invokeClassMethod("LIStringUtils", "equals:with:", str1, str2)); end function StringUtils.toString(str) if str.id then str = str:id(); end return runtime::invokeClassMethod("LIStringUtils", "objectToString:", str); end function StringUtils.UTF8StringFromData(data) return runtime::invokeClassMethod("LIStringUtils", "UTF8StringFromData:", data:id()); end function StringUtils.dataFromUTF8String(str) local dataId = runtime::invokeClassMethod("LIStringUtils", "dataFromUTF8String:", str); return NSData:get(dataId); end function StringUtils.find(str, matching, fromIndex--[[option]], reverse--[[option]]) if fromIndex == nil then fromIndex = 0; end if reverse == nil then reverse = false; end return tonumber(runtime::invokeClassMethod("LIStringUtils", "find:matching:fromIndex:reverse", str, matching, fromIndex, toObjCBool(reverse))); end function StringUtils.substring(str, beginIndex, endIndex) return runtime::invokeClassMethod("LIStringUtils", "substring:beginIndex:endIndex:", str, beginIndex, endIndex); end function StringUtils.replace(str, matching, replacement, compareOptions--[[option]], beginIndex--[[option]], endIndex--[[option]]) if compareOptions == nil then compareOptions = 1; end if beginIndex == nil then beginIndex = 0; end if endIndex == nil then endIndex = StringUtils.length(str); end return runtime::invokeClassMethod("LIStringUtils", "replace:matching:replacement:compareOptions:beginIndex:endIndex:", str, matching, replacement, compareOptions, beginIndex, endIndex); end function StringUtils.compare(str1, str2) return tonumber(string::invokeMethod(str1, "compare:", str2)); end function StringUtils.sizeWithFont(str, font, constrainedToWidth, constrainedToHeight) return unpackCStruct(string::invokeMethod(str, "sizeWithFont:constrainedToSize:", font:id(), toCStruct(constrainedToWidth, constrainedToHeight))); end
--死境战壕 local m=14000105 local cm=_G["c"..m] function cm.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCondition(cm.actcon) e1:SetTarget(cm.target) e1:SetOperation(cm.activate) c:RegisterEffect(e1) --summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(m,0)) e2:SetCategory(CATEGORY_SUMMON) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_SPSUMMON_SUCCESS) e2:SetProperty(EFFECT_FLAG_DELAY) e2:SetRange(LOCATION_FZONE) e2:SetCountLimit(1) e2:SetTarget(cm.sumtg) e2:SetOperation(cm.sumop) c:RegisterEffect(e2) --cannot activate local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD) e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e3:SetCode(EFFECT_CANNOT_ACTIVATE) e3:SetRange(LOCATION_FZONE) e3:SetTargetRange(1,1) e3:SetValue(cm.aclimit) c:RegisterEffect(e3) end function cm.BRAVE(c) local m=_G["c"..c:GetCode()] return m and m.named_with_brave end function cm.setfilter(c,e,tp) return c:IsFaceup() and c:GetSequence()<5 end function cm.actcon(e) local tp=e:GetHandlerPlayer() return not Duel.IsExistingMatchingCard(cm.setfilter,tp,LOCATION_SZONE,0,1,nil) end function cm.filter(c) return cm.BRAVE(c) and not c:IsForbidden() end function cm.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(cm.filter,tp,LOCATION_DECK,0,1,nil) and Duel.GetLocationCount(tp,LOCATION_SZONE)>0 end end function cm.activate(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOFIELD) local g=Duel.SelectMatchingCard(tp,cm.filter,tp,LOCATION_DECK,0,1,1,nil) local tc=g:GetFirst() if tc then Duel.MoveToField(tc,tp,tp,LOCATION_SZONE,POS_FACEDOWN,true) Duel.ConfirmCards(1-tp,tc) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetCode(EFFECT_CHANGE_TYPE) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetReset(RESET_EVENT+RESETS_STANDARD-RESET_TURN_SET) e1:SetValue(TYPE_SPELL+TYPE_CONTINUOUS) tc:RegisterEffect(e1) end end function cm.sfilter(c,e,tp) return c:GetSummonPlayer()==1-tp and (not e or c:IsRelateToEffect(e)) end function cm.sumfilter(c) return cm.BRAVE(c) and c:IsSummonable(true,nil,1) end function cm.sumtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return eg:IsExists(cm.sfilter,1,nil,nil,tp) and Duel.IsExistingMatchingCard(cm.sumfilter,tp,LOCATION_HAND+LOCATION_SZONE,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_SUMMON,nil,1,0,0) end function cm.sumop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SUMMON) local g=Duel.SelectMatchingCard(tp,cm.sumfilter,tp,LOCATION_HAND+LOCATION_SZONE,0,1,1,nil) local tc=g:GetFirst() if tc then Duel.Summon(tp,tc,true,nil,1) end end function cm.aclimit(e,re,tp) if not re:IsHasType(EFFECT_TYPE_ACTIVATE) or not re:IsActiveType(TYPE_SPELL+TYPE_TRAP) then return false end local c=re:GetHandler() return not c:IsLocation(LOCATION_SZONE) end
local al = legato.al --[[ main ]]-- local filename = '/data/mysha.pcx' local display = al.create_display(640, 480) local subbitmap = al.create_sub_bitmap(al.get_backbuffer(display), 50, 50, 640 - 50, 480 - 50) local overlay = al.create_sub_bitmap(al.get_backbuffer(display), 100, 100, 300, 50) al.set_window_title(display, filename) local bitmap = assert(al.load_bitmap(filename)) local font = assert(al.create_builtin_font()) al.set_new_bitmap_flags({memory_bitmap = true}) local buffer = al.create_bitmap(640, 480) local buffer_subbitmap = al.create_sub_bitmap(buffer, 50, 50, 640 - 50, 480 - 50) local soft_font = al.create_builtin_font() local timer = al.create_timer(1.0 / 60.0) local queue = al.create_event_queue() al.register_event_source(queue, 'keyboard') al.register_event_source(queue, display) al.register_event_source(queue, timer) al.start_timer(timer) local w, h = al.get_bitmap_size(bitmap) al.set_target_bitmap(overlay) local transform = al.create_transform() al.identity_transform(transform) al.rotate_transform(transform, -0.06) al.use_transform(transform) local redraw = false local blend = false local software = false local use_subbitmap = false while true do local event = al.wait_for_event(queue) if event then if event.type == 'display_close' then return elseif event.type == 'timer' then redraw = true elseif event.type == 'key_down' then if event.keycode == al.keys.L then blend = not blend elseif event.keycode == al.keys.B then use_subbitmap = not use_subbitmap elseif event.keycode == al.keys.S then software = not software if software then local t = al.create_transform() al.identity_transform(t) al.use_transform(t) end elseif event.keycode == al.keys.ESCAPE then return else print(event.keycode, collectgarbage('count')) end end end if redraw and al.is_event_queue_empty(queue) then redraw = false local t = 3.0 + al.get_time() al.set_blender('add', 'one', 'one') local tint if blend then tint = al.map_rgb_f(0.5, 0.5, 0.5, 0.5) else tint = al.map_rgb_f(1, 1, 1, 1) end if software then if use_subbitmap then al.set_target_bitmap(buffer) al.clear_to_color(al.map_rgb_f(1, 0, 0)) al.set_target_bitmap(buffer_subbitmap) else al.set_target_bitmap(buffer) end else if use_subbitmap then al.set_target_backbuffer(display) al.clear_to_color(al.map_rgb_f(1, 0, 0)) al.set_target_bitmap(subbitmap) else al.set_target_backbuffer(display) end end -- Set the transformation on the target bitmap al.identity_transform(transform) al.translate_transform(transform, -640 / 2, -480 / 2) al.scale_transform(transform, 0.15 + math.sin(t / 5), 0.15 + math.cos(t / 5)) al.rotate_transform(transform, t / 50) al.translate_transform(transform, 640 / 2, 480 / 2) al.use_transform(transform) -- Draw some stuff al.clear_to_color(al.map_rgb_f(0, 0, 0)) al.draw_tinted_bitmap(bitmap, tint, 0, 0, 0) al.draw_tinted_scaled_bitmap(bitmap, tint, w / 4, h / 4, w / 2, h / 2, w, 0, w / 2, h / 4, 0) al.draw_tinted_bitmap_region(bitmap, tint, w / 4, h / 4, w / 2, h / 2, 0, h, {flip_vertical = true}) al.draw_tinted_scaled_rotated_bitmap(bitmap, tint, w / 2, h / 2, w + w / 2, h + h / 2, 0.7, 0.7, 0.3, 0) al.draw_pixel(w + w / 2, h + h / 2, al.map_rgb_f(0, 1, 0)) al.put_pixel(w + w / 2 + 2, h + h / 2 + 2, al.map_rgb_f(0, 1, 1)) al.draw_circle(w, h, 50, al.map_rgb_f(1, 0.5, 0), 3) al.set_blender('add', 'one', 'zero') if software then al.draw_text(soft_font, al.map_rgb_f(1, 1, 1, 1), 640 / 2, 430, "Software Rendering", {centre = true}) al.set_target_backbuffer(display) al.draw_bitmap(buffer, 0, 0, 0) else al.draw_text(font, al.map_rgb_f(1, 1, 1, 1), 640 / 2, 430, "Hardware Rendering", {centre = true}) end -- Each target bitmap has its own transformation matrix, so this -- overlay is unaffected by the transformations set earlier. al.set_target_bitmap(overlay) al.set_blender('add', 'one', 'one') al.draw_text(font, al.map_rgb_f(1, 1, 0, 1), 0, 10, "hello!") al.set_target_backbuffer(display) al.flip_display() end end
return Def.Quad{ InitCommand=function(self) self:zoomto(256,104):diffuse(PlayerColor(PLAYER_1)):diffusealpha(0.75):fadeleft(0.2):faderight(0.2) end; };
local utils = require "spine.utils" local Slot = {} function Slot.new (slotData, skeleton, bone) if not slotData then error("slotData cannot be nil", 2) end if not skeleton then error("skeleton cannot be nil", 2) end if not bone then error("bone cannot be nil", 2) end local self = { data = slotData, skeleton = skeleton, bone = bone } function self:setColor (r, g, b, a) self.r = r self.g = g self.b = b self.a = a end function self:setAttachment (attachment) if self.attachment and self.attachment ~= attachment and self.skeleton.images[self.attachment] then self.skeleton.images[self.attachment]:removeSelf() self.skeleton.images[self.attachment] = nil end self.attachment = attachment self.attachmentTime = self.skeleton.time end function self:setAttachmentTime (time) self.attachmentTime = self.skeleton.time - time end function self:getAttachmentTime () return self.skeleton.time - self.attachmentTime end function self:setToBindPose () local data = self.data self:setColor(data.r, data.g, data.b, data.a) local attachment if data.attachmentName then attachment = self.skeleton:getAttachment(data.name, data.attachmentName) end self:setAttachment(attachment) end self:setColor(255, 255, 255, 255) return self end return Slot
--[[ Copyright 2019 Nyapaw © 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. ------- MergeSort.Sort(<Table> Array) Sorts the array lexicographically (string) or numerically (number) from least to greatest. MergeSort.Sort(<Table> Array, [<Callback> SortingFunction]) Sorts the array with a callback; given two parameters, the function must return a boolean from comparing one to the other. Sorts in chronological order if first is greater than second, reverse vise-versa. --]] local MergeSort = {}; local function Merge(refArray, Array, lowerHalf, upperHalf, Callback) local lC, rC = 1, 1; --// Note that these functions aren't used to save lines of code, it makes unnecessary calls. --// https://devforum.roblox.com/t/why-i-dont-sleep-micro-macro-optimizing-mega-guide/71543 --[[ local function add_rC() table.insert(Array, upperHalf[rC]); rC = rC + 1; end; local function add_lC() table.insert(Array, lowerHalf[lC]); lC = lC + 1; end; ]] while ((lC + rC) < (#lowerHalf + #upperHalf + 2)) do if (rC > #upperHalf) then while (lC <= #lowerHalf) do table.insert(Array, lowerHalf[lC]); --// add_lC() lC = lC + 1; end; break; elseif (lC > #lowerHalf) then while (rC <= #upperHalf) do table.insert(Array, upperHalf[rC]); --// add_rC() rC = rC + 1; end; break; end; if (Callback) then if (Callback(lowerHalf[lC], upperHalf[rC])) then table.insert(Array, lowerHalf[lC]); lC = lC + 1; else table.insert(Array, upperHalf[rC]); rC = rC + 1; end; else if (lowerHalf[lC] < upperHalf[rC]) then table.insert(Array, lowerHalf[lC]); lC = lC + 1; else table.insert(Array, upperHalf[rC]); rC = rC + 1; end; end; end; end; local function arrFromRange(Array, lowerB, upperB) local Arr = {}; for i = lowerB, upperB do table.insert(Arr, Array[i]); end; return Arr; end; local function Sort(refArray, lowerB, upperB, Callback) if (lowerB >= upperB) then return arrFromRange(refArray, lowerB, upperB); end; local mPt = math.floor((lowerB + upperB)*.5); local lArr = Sort(refArray, lowerB, mPt, Callback); local rArr = Sort(refArray, mPt + 1, upperB, Callback); local tempArr = {}; Merge(refArray, tempArr, lArr, rArr, Callback); return tempArr; end; function MergeSort.Sort(Array, Callback) return Sort(Array, 1, #Array, Callback); end; return MergeSort;
--[[--------------------------------------------------------- Super Cooking Panic for Garry's Mod by Xperidia (2020) -----------------------------------------------------------]] include("sh_player.lua") AddCSLuaFile("cl_player.lua") --[[--------------------------------------------------------- Called once on the player's first spawn -----------------------------------------------------------]] function GM:PlayerInitialSpawn(ply, transiton) if not ply:IsBot() then ply:SetTeam(TEAM_UNASSIGNED) else self:AutoTeam(ply) end if not game.IsDedicated() and ply:IsListenServerHost() then ply:SetNWBool("IsListenServerHost", true) end self:UpdateClientRoundValues(ply) end --[[--------------------------------------------------------- Name: gamemode:PlayerSpawn() Desc: Called when a player spawns -----------------------------------------------------------]] function GM:PlayerSpawn(ply, transiton) -- -- If the player doesn't have a team in a TeamBased game -- then spawn him as a spectator -- if self.TeamBased and (ply:Team() == TEAM_SPECTATOR or ply:Team() == TEAM_UNASSIGNED) then self:PlayerSpawnAsSpectator(ply) return end -- Stop observer mode ply:UnSpectate() local classes = team.GetClass(ply:Team()) player_manager.SetPlayerClass(ply, classes[math.random(1, #classes)]) player_manager.OnPlayerSpawn(ply, transiton) player_manager.RunClass(ply, "Spawn") hook.Call("PlayerLoadout", GAMEMODE, ply) -- Set player model hook.Call("PlayerSetModel", GAMEMODE, ply) ply:SetupHands() end --[[--------------------------------------------------------- Name: gamemode:PlayerDeathThink(player) Desc: Called when the player is waiting to respawn -----------------------------------------------------------]] function GM:PlayerDeathThink(ply) if ply.oldteam and (ply.oldteam == TEAM_SPECTATOR or ply.oldteam == TEAM_UNASSIGNED) then ply:Spawn() ply.oldteam = nil elseif not ply.NextSpawnTime or ply.NextSpawnTime <= CurTime() then ply:Spawn() end end --[[--------------------------------------------------------- Name: gamemode:DoPlayerDeath( ) Desc: Carries out actions when the player dies -----------------------------------------------------------]] function GM:DoPlayerDeath(ply, attacker, dmginfo) if not ply.GoneToRagdoll then ply:CreateRagdoll() else ply.GoneToRagdoll = nil end ply:PerfomCleanUP() ply:AddDeaths(1) end --[[--------------------------------------------------------- Name: gamemode:PlayerDeathSound() Desc: Return true to not play the default sounds -----------------------------------------------------------]] function GM:PlayerDeathSound() return true end --[[--------------------------------------------------------- Name: gamemode:PlayerShouldTakeDamage Return true if this player should take damage from this attacker -----------------------------------------------------------]] function GM:PlayerShouldTakeDamage(ply, attacker) if ply.GoneToRagdoll then return true elseif not GetConVar("mp_friendlyfire"):GetBool() and attacker:IsPlayer() and ply:Team() == attacker:Team() and ply ~= attacker then return false end return true end --[[--------------------------------------------------------- Name: gamemode:PlayerHurt( ) Desc: Called when a player is hurt. -----------------------------------------------------------]] function GM:PlayerHurt(player, attacker, healthleft, healthtaken) end --[[--------------------------------------------------------- Name: ply:GrabIngredient( ent ) Desc: Player will try to grab ent -----------------------------------------------------------]] function GM.PlayerMeta:GrabIngredient(ingredient) if not GAMEMODE:IsValidGamerMoment() then return end if not self:IsValidPlayingState() then return end local cur_ingredient = self:GetHeldIngredient() if IsValid(cur_ingredient) then return end if ingredient:IsTrap() and ingredient:Team() ~= self:Team() then return ingredient:DoTheTrap(self) end if ingredient:IsIngredient() then if ingredient:IsNPC() then ingredient = ingredient:GoToRagdoll(self) end self:SetHeldIngredient(ingredient) ingredient:SetOwner(self) ingredient:SetCollisionGroup(COLLISION_GROUP_DEBRIS) ingredient:SetRenderMode(RENDERMODE_NONE) ingredient:DrawShadow(false) self:EmitSound("scookp_ingredient_grab") GAMEMODE:DebugLog(self:GetName() .. " grabbed ingredient " .. ingredient:GetClass() .. ": " .. ingredient:GetModel()) end end --[[--------------------------------------------------------- Name: ply:DropHeldIngredient( bool forward ) Desc: Player will drop their ingredient -----------------------------------------------------------]] function GM.PlayerMeta:DropHeldIngredient(forward) if not self.GetHeldIngredient then return nil end local ingredient = self:GetHeldIngredient() if IsValid(ingredient) then ingredient:SetOwner(NULL) ingredient:SetCollisionGroup(COLLISION_GROUP_NONE) ingredient:SetRenderMode(RENDERMODE_NORMAL) ingredient:DrawShadow(true) self:SetHeldIngredient(NULL) if forward then if not ingredient:IsNPC() then ingredient:SetAngles(self:EyeAngles()) end local trace = GAMEMODE:GetConvPlayerTrace(self) GAMEMODE:SetFeelGoodPos(ingredient, trace) ingredient:PhysWake() ingredient:Activate() else ingredient:SetPos(self:GetPos()) ingredient:PhysWake() ingredient:Activate() end self:EmitSound("scookp_ingredient_release") GAMEMODE:DebugLog(self:GetName() .. " dropped held ingredient " .. ingredient:GetClass() .. ": " .. ingredient:GetModel()) end return ingredient end --[[--------------------------------------------------------- Name: player:PerfomCleanUP() Desc: Clean up player -----------------------------------------------------------]] function GM.PlayerMeta:PerfomCleanUP() self:DropHeldIngredient() self:DropPowerUP() for _, wep in pairs(self:GetWeapons()) do self:DropWeapon(wep) end end --[[--------------------------------------------------------- Name: gamemode:PlayerDisconnected() Desc: Player has disconnected from the server. -----------------------------------------------------------]] function GM:PlayerDisconnected(ply) if player.GetCount() <= 1 and not self:AreTeamsPopulated() then self:SetRoundState(RND_NULL) end end --[[--------------------------------------------------------- Name: gamemode:SetupPlayerVisibility() Desc: Add extra positions to the player's PVS -----------------------------------------------------------]] function GM:SetupPlayerVisibility(pPlayer, pViewEntity) for _, v in pairs(ents.FindByClass("scookp_cooking_pot")) do if pPlayer:Team() == v:Team() then AddOriginToPVS(v:GetPos()) end end end --[[--------------------------------------------------------- Name: gamemode:IsSpawnpointSuitable(player) Desc: Find out if the spawnpoint is suitable or not -----------------------------------------------------------]] function GM:IsSpawnpointSuitable(ply, spawnpointent, bMakeSuitable) local Pos = spawnpointent:GetPos() -- Note that we're searching the default hull size here for a player in the way of our spawning. -- This seems pretty rough, seeing as our player's hull could be different.. but it should do the job -- (HL2DM kills everything within a 128 unit radius) local Ents = ents.FindInBox( Pos + Vector(-16, -16, 0), Pos + Vector(16, 16, 64) ) if ply:Team() == TEAM_SPECTATOR then return true end local Blockers = 0 for _, v in pairs(Ents) do if IsValid(v) and v ~= ply and v:GetClass() == "player" and v:Alive() then Blockers = Blockers + 1 if bMakeSuitable then v:Kill() end elseif IsValid(v) and v:GetClass() == "scookp_cooking_pot" then Blockers = Blockers + 1 end end if bMakeSuitable then return true end if Blockers > 0 then return false end return true end
local GameConst = require 'scripts.game-const' local Parser = {} local types = GameConst.code.type function Parser.bcheck(a, b) return bit.band(a, b) ~= 0 end function Parser.match_msb(a, b) local n = bit.band(a, b) if n == 0 then return 0 end local msb = 1 while n > 1 do n = bit.rshift(n, 1) msb = bit.lshift(msb, 1) end return msb end function Parser.match_lsb(a, b) local n = bit.band(a, b) return bit.band(n, -n) end function Parser.bits(n) return coroutine.wrap(function() local b = 1 while n > 0 do if Parser.bcheck(n, 1) then coroutine.yield(b) end n = bit.rshift(n, 1) b = bit.lshift(b, 1) end end) end function Parser.get_scales(data) local sc = data.level local lsc = bit.rshift(bit.band(sc, 0xFF000000), 24) local rsc = bit.rshift(bit.band(sc, 0x00FF0000), 16) return lsc, rsc end function Parser.get_levelrank(data) local lvlrank = bit.band(data.level, 0x0000FFFF) return lvlrank > 0 and lvlrank <= 12 and lvlrank or nil end function Parser.get_link_rating(data) return bit.band(data.level, 0x0000FFFF) end function Parser.get_link_arrows(data) return bit.band(data.def, GameConst.code.link.ALL) end local effect_pattern = "^.*%[%s*[pP]endulum%s+[eE]ffect%s*%]%s*(.-)%s*[-_][-_][-_]+%s*" .. "%[%s*%a+%s+%a+%s*%]%s*(.-)%s*$" local na_pattern = "^%s*[-_]%s*[nN]%s*/%s*[aA]%s*[-_]%s*$" function Parser.get_effects(data) if Parser.bcheck(data.type, types.PENDULUM) then local pe, me = data.desc:match(effect_pattern) if not pe then return data.desc end if pe:match(na_pattern) then pe = "" end if me:match(na_pattern) then me = "" end return me, pe else return data.desc end end function Parser.get_race(data) local race = Parser.match_lsb(data.race, GameConst.code.race.ALL) return GameConst.name.race[race] end local sumtypes = types.FUSION + types.LINK + types.RITUAL + types.SYNCHRO + types.XYZ function Parser.get_sumtype(data) local sumtype = Parser.match_lsb(data.type, sumtypes) return GameConst.name.type[sumtype] end local abilities = types.FLIP + types.GEMINI + types.SPIRIT + types.TOON + types.UNION function Parser.get_ability(data) local ability = Parser.match_lsb(data.type, abilities) return GameConst.name.type[ability] end return Parser
local ffi = require("cffi") ffi.cdef [[ typedef struct foo { int x; int y; } foo; ]] local foo = ffi.metatype("foo", { __index = { sum = function(self) return self.x + self.y end } }) local x = foo(5, 10) assert(x.x == 5) assert(x.y == 10) assert(x:sum() == 15)
local present, bufremove = pcall(require, "mini.bufremove") if not present then return end bufremove.setup()
local skynet = require "skynet" local redis = require "redis" skynet.start(function() local db = redis.connect "main" db:batch "write" -- ignore results db:set("A", "hello") db:set("B", "world") db:batch "end" db:batch "read" db:get("A") db:get("B") local r = db:batch "end" -- return all results in a table for k,v in pairs(r) do print(k,v) end print(db:exists "A") print(db:get "A") print(db:set("A","hello world")) print(db:get("A")) skynet.exit() end)
return { { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onAttach", "onStack" }, arg_list = { rant = 100, target = "TargetSelf", skill_id = 13891 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onAttach", "onStack" }, arg_list = { rant = 200, target = "TargetSelf", skill_id = 13891 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onAttach", "onStack" }, arg_list = { rant = 300, target = "TargetSelf", skill_id = 13891 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onAttach", "onStack" }, arg_list = { rant = 400, target = "TargetSelf", skill_id = 13891 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onAttach", "onStack" }, arg_list = { rant = 500, target = "TargetSelf", skill_id = 13891 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onAttach", "onStack" }, arg_list = { rant = 600, target = "TargetSelf", skill_id = 13891 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onAttach", "onStack" }, arg_list = { rant = 700, target = "TargetSelf", skill_id = 13891 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onAttach", "onStack" }, arg_list = { rant = 800, target = "TargetSelf", skill_id = 13891 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onAttach", "onStack" }, arg_list = { rant = 900, target = "TargetSelf", skill_id = 13891 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onAttach", "onStack" }, arg_list = { rant = 1000, target = "TargetSelf", skill_id = 13891 } } } }, init_effect = "", name = "", time = 0.1, picture = "", desc = "概率触发器", stack = 1, id = 13893, icon = 13890, last_effect = "", effect_list = { { type = "BattleBuffCastSkill", trigger = { "onAttach", "onStack" }, arg_list = { rant = 100, target = "TargetSelf", skill_id = 13891 } } } }
local M = {} M.config = function() rvim.builtin.dap = { active = true, on_config_done = nil, breakpoint = { text = "", texthl = "LspDiagnosticsSignError", linehl = "", numhl = "", }, breakpoint_rejected = { text = "", texthl = "LspDiagnosticsSignHint", linehl = "", numhl = "", }, stopped = { text = "", texthl = "LspDiagnosticsSignInformation", linehl = "DiagnosticUnderlineInfo", numhl = "LspDiagnosticsSignInformation", }, } end M.setup = function() local dap = require "dap" vim.fn.sign_define("DapBreakpoint", rvim.builtin.dap.breakpoint) vim.fn.sign_define("DapBreakpointRejected", rvim.builtin.dap.breakpoint_rejected) vim.fn.sign_define("DapStopped", rvim.builtin.dap.stopped) dap.defaults.fallback.terminal_win_cmd = "50vsplit new" rvim.builtin.which_key.mappings["d"] = { name = "Debug", t = { "<cmd>lua require'dap'.toggle_breakpoint()<cr>", "Toggle Breakpoint" }, b = { "<cmd>lua require'dap'.step_back()<cr>", "Step Back" }, c = { "<cmd>lua require'dap'.continue()<cr>", "Continue" }, C = { "<cmd>lua require'dap'.run_to_cursor()<cr>", "Run To Cursor" }, d = { "<cmd>lua require'dap'.disconnect()<cr>", "Disconnect" }, g = { "<cmd>lua require'dap'.session()<cr>", "Get Session" }, i = { "<cmd>lua require'dap'.step_into()<cr>", "Step Into" }, o = { "<cmd>lua require'dap'.step_over()<cr>", "Step Over" }, u = { "<cmd>lua require'dap'.step_out()<cr>", "Step Out" }, p = { "<cmd>lua require'dap'.pause.toggle()<cr>", "Pause" }, r = { "<cmd>lua require'dap'.repl.toggle()<cr>", "Toggle Repl" }, s = { "<cmd>lua require'dap'.continue()<cr>", "Start" }, q = { "<cmd>lua require'dap'.close()<cr>", "Quit" }, } end return M
-- exxec return { ["exxec"] = { yuped = { air = true, class = [[CSimpleGroundFlash]], count = 1, ground = true, water = true, properties = { alwaysvisible = true, colormap = [[0.3 0.3 0.8 0.31 0.2 0.2 0.6 0.31 0.0 0.0 0.0 0.0]], size = 33, sizegrowth = -0.3, texture = [[groundflash]], ttl = 100, }, }, glow = { air = true, count = 2, class = [[heatcloud]], ground = true, water = true, properties = { heat = 20, heatfalloff = 0.70, maxheat = 20, pos = [[0, 0.0, 0]], size = [[4.0 r1]], sizegrowth = [[0.09 r.16]], sizemod = 0, sizemodmod = 0, speed = [[0.05 r-0.1, 0.05 r-0.1, 0.05 r-0.1]], texture = [[bluenovaexplo]], useairlos = false, }, }, spark1 = { air = false, class = [[CSimpleParticleSystem]], count = 1, ground = false, water = false, unit = 1, properties = { airdrag = 0.95, colormap = [[0.3 0.3 0.8 .02 0.3 0.3 0.8 .01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = [[r360 r-360 r360]], emitvector = [[0, 1, 0]], gravity = [[0, -.25 r0.15 r-1, 0]], numparticles = 18, particlelife = 7, particlelifespread = 20, particlesize = 1, particlesizespread = 2, particlespeed = 2, particlespeedspread = 3, pos = [[0, 3, 0]], sizegrowth = [[0.0 r.05]], sizemod = 1.0, texture = [[Plasma]], useairlos = true, }, }, }, }
local Prerequisites = {} function Prerequisites.InAttackRange(action, prerequisite, agent, target, dt) local attack = Utils.getChild(agent, action) if attack then local range = attack:get("AttackRange") local agentPosition = agent:get("Position") local targetPosition = target:get("Position") local distance = (agentPosition:toVector() - targetPosition:toVector()):len() local distance = distance - agent:get("Circle").radius - target:get("Circle").radius if(distance < 0) then distance = 0 end if (distance < range.max and distance > range.min) then return true end end return false end function Prerequisites.InDangerRange(action, prerequisite, agent, target, dt) local agentPosition = agent:get("Position") local targetPosition = target:get("Position") local distance = (agentPosition:toVector() - targetPosition:toVector()):len() local distance = distance - agent:get("Circle").radius - target:get("Circle").radius if (distance < 200) then return true end return false end function Prerequisites.AttackAvailable(action, prerequisite, agent, target, dt) local attack = Utils.getChild(agent, prerequisite.target) local globalTimer = agent:get("Timer") if attack then local attackTimer = attack:get("Timer") if (attackTimer.cooldown <= 0 and globalTimer.cooldown <= 0) then return true end end return false end return Prerequisites
local TDKP_Tests = {} _G["TDKP_Tests"] = TDKP_Tests function TDKP_Tests:RunTests() if WoWUnit == nil then return end local AreEqual, Exists, Replace = WoWUnit.AreEqual, WoWUnit.Exists, WoWUnit.Replace local Tests = WoWUnit:NewGroup("TurboDKP") function Tests:ApplyBiddingCaps1() AreEqual(pack(100, 50), pack(TDKP_WinnerCalculator:ApplyBiddingCaps({bidAmount=100}, {bidAmount=50}, -1, -1, -1, -1))) end function Tests:ApplyBiddingCaps2() AreEqual(pack(100, 150), pack(TDKP_WinnerCalculator:ApplyBiddingCaps({bidAmount=100}, {bidAmount=150}, 50, -1, -1, 50))) end function Tests:ApplyBiddingCaps3() AreEqual(pack(49, 150), pack(TDKP_WinnerCalculator:ApplyBiddingCaps({bidAmount=100}, {bidAmount=150}, 49, -1, -1, 50))) end function Tests:ApplyBiddingCaps4() AreEqual(pack(50, 69), pack(TDKP_WinnerCalculator:ApplyBiddingCaps({bidAmount=100}, {bidAmount=69}, 50, 150, -1, -1))) end function Tests:ApplyBiddingCaps5() AreEqual(pack(50, 51), pack(TDKP_WinnerCalculator:ApplyBiddingCaps({bidAmount=55}, {bidAmount=51}, -1, -1, 50, -1))) end function Tests:ApplyBiddingCaps6() AreEqual(pack(100, 150), pack(TDKP_WinnerCalculator:ApplyBiddingCaps({bidAmount=100}, {bidAmount=150}, -1, -1, 50, 50))) end function Tests:ApplyBiddingCaps7() AreEqual(pack(102, 101), pack(TDKP_WinnerCalculator:ApplyBiddingCaps({bidAmount=102}, {bidAmount=101}, 150, 50, 50, -1))) end function Tests:ApplyBiddingCaps8() AreEqual(pack(100, 48), pack(TDKP_WinnerCalculator:ApplyBiddingCaps({bidAmount=100}, {bidAmount=101}, 103, 48, 49, 102))) end WoWUnit:RunTests("PLAYER_LOGIN") end
--[[ Copyright (c) 2009 Edvin "Lego3" Linge 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 room = {} room.id = "slack_tongue" room.vip_must_visit = false room.level_config_id = 20 room.class = "SlackTongueRoom" room.name = _S.rooms_short.tongue_clinic room.long_name = _S.rooms_long.tongue_clinic room.tooltip = _S.tooltip.rooms.tongue_clinic room.objects_additional = { "extinguisher", "radiator", "plant", "bin" } room.objects_needed = { slicer = 1 } room.build_preview_animation = 932 room.categories = { clinics = 2, } room.minimum_size = 4 room.wall_type = "blue" room.floor_tile = 17 room.required_staff = { Doctor = 1, } room.maximum_staff = room.required_staff room.call_sound = "reqd005.wav" room.handyman_call_sound = "maint004.wav" class "SlackTongueRoom" (Room) ---@type SlackTongueRoom local SlackTongueRoom = _G["SlackTongueRoom"] function SlackTongueRoom:SlackTongueRoom(...) self:Room(...) end function SlackTongueRoom:commandEnteringPatient(patient) local staff = self.staff_member local slicer, pat_x, pat_y = self.world:findObjectNear(patient, "slicer") local stf_x, stf_y = slicer:getSecondaryUsageTile() staff:setNextAction(WalkAction(stf_x, stf_y)) staff:queueAction(IdleAction():setDirection(slicer.direction == "north" and "east" or "south")) patient:setNextAction(WalkAction(pat_x, pat_y)) local after_use_slack_tongue = --[[persistable:slack_tongue_after_use]] function() if patient.humanoid_class == "Slack Male Patient" then patient:setType "Standard Male Patient" -- Change to normal head else patient:setLayer(0, patient.layers[0] - 8) -- Change to normal head end -- if no other actions for staff member meander in room if #staff.action_queue == 1 then staff:setNextAction(MeanderAction()) else staff:finishAction(staff:getCurrentAction()) end self:dealtWithPatient(patient) end patient:queueAction(MultiUseObjectAction(slicer, staff):setAfterUse(after_use_slack_tongue)) return Room.commandEnteringPatient(self, patient) end return room
require 'paths' require 'rnn' require 'optim' local dl = require 'dataload' version = 2 --[[ command line arguments ]]-- cmd = torch.CmdLine() cmd:text() cmd:text('Train a Language Model on PennTreeBank dataset using RNN or LSTM or GRU') cmd:text('Example:') cmd:text('th recurrent-language-model.lua --cuda --device 2 --progress --cutoff 4 --seqlen 10') cmd:text("th recurrent-language-model.lua --progress --cuda --lstm --seqlen 20 --hiddensize '{200,200}' --batchsize 20 --startlr 1 --cutoff 5 --maxepoch 13 --schedule '{[5]=0.5,[6]=0.25,[7]=0.125,[8]=0.0625,[9]=0.03125,[10]=0.015625,[11]=0.0078125,[12]=0.00390625}'") cmd:text("th recurrent-language-model.lua --progress --cuda --lstm --seqlen 35 --uniform 0.04 --hiddensize '{1500,1500}' --batchsize 20 --startlr 1 --cutoff 10 --maxepoch 50 --schedule '{[15]=0.87,[16]=0.76,[17]=0.66,[18]=0.54,[19]=0.43,[20]=0.32,[21]=0.21,[22]=0.10}' -dropout 0.65") cmd:text('Options:') -- training cmd:option('--startlr', 0.05, 'learning rate at t=0') cmd:option('--minlr', 0.00001, 'minimum learning rate') cmd:option('--saturate', 400, 'epoch at which linear decayed LR will reach minlr') cmd:option('--schedule', '', 'learning rate schedule. e.g. {[5] = 0.004, [6] = 0.001}') cmd:option('--momentum', 0.9, 'momentum') cmd:option('--adam', false, 'use ADAM instead of SGD as optimizer') cmd:option('--adamconfig', '{0, 0.999}', 'ADAM hyperparameters beta1 and beta2') cmd:option('--maxnormout', -1, 'max l2-norm of each layer\'s output neuron weights') cmd:option('--cutoff', -1, 'max l2-norm of concatenation of all gradParam tensors') cmd:option('--batchSize', 32, 'number of examples per batch') cmd:option('--cuda', false, 'use CUDA') cmd:option('--device', 1, 'sets the device (GPU) to use') cmd:option('--maxepoch', 1000, 'maximum number of epochs to run') cmd:option('--earlystop', 50, 'maximum number of epochs to wait to find a better local minima for early-stopping') cmd:option('--progress', false, 'print progress bar') cmd:option('--silent', false, 'don\'t print anything to stdout') cmd:option('--uniform', 0.1, 'initialize parameters using uniform distribution between -uniform and uniform. -1 means default initialization') -- rnn layer cmd:option('--lstm', false, 'use Long Short Term Memory (nn.LSTM instead of nn.Recurrent)') cmd:option('--bn', false, 'use batch normalization. Only supported with --lstm') cmd:option('--gru', false, 'use Gated Recurrent Units (nn.GRU instead of nn.Recurrent)') cmd:option('--mfru', false, 'use Multi-function Recurrent Unit (nn.MuFuRu instead of nn.Recurrent)') cmd:option('--seqlen', 5, 'sequence length : back-propagate through time (BPTT) for this many time-steps') cmd:option('--inputsize', -1, 'size of lookup table embeddings. -1 defaults to hiddensize[1]') cmd:option('--hiddensize', '{200}', 'number of hidden units used at output of each recurrent layer. When more than one is specified, RNN/LSTMs/GRUs are stacked') cmd:option('--dropout', 0, 'apply dropout with this probability after each rnn layer. dropout <= 0 disables it.') -- data cmd:option('--batchsize', 32, 'number of examples per batch') cmd:option('--trainsize', -1, 'number of train examples seen between each epoch') cmd:option('--validsize', -1, 'number of valid examples used for early stopping and cross-validation') cmd:option('--savepath', paths.concat(dl.SAVE_PATH, 'rnnlm'), 'path to directory where experiment log (includes model) will be saved') cmd:option('--id', '', 'id string of this experiment (used to name output file) (defaults to a unique id)') cmd:text() local opt = cmd:parse(arg or {}) opt.hiddensize = loadstring(" return "..opt.hiddensize)() opt.schedule = loadstring(" return "..opt.schedule)() opt.adamconfig = loadstring(" return "..opt.adamconfig)() opt.inputsize = opt.inputsize == -1 and opt.hiddensize[1] or opt.inputsize if not opt.silent then table.print(opt) end opt.id = opt.id == '' and ('ptb' .. ':' .. dl.uniqueid()) or opt.id if opt.cuda then require 'cunn' cutorch.setDevice(opt.device) end --[[ data set ]]-- local trainset, validset, testset = dl.loadPTB({opt.batchsize,1,1}) if not opt.silent then print("Vocabulary size : "..#trainset.ivocab) print("Train set split into "..opt.batchsize.." sequences of length "..trainset:size()) end --[[ language model ]]-- local lm = nn.Sequential() -- input layer (i.e. word embedding space) local lookup = nn.LookupTable(#trainset.ivocab, opt.inputsize) lookup.maxOutNorm = -1 -- prevent weird maxnormout behaviour lm:add(lookup) -- input is seqlen x batchsize if opt.dropout > 0 and not opt.gru then -- gru has a dropout option lm:add(nn.Dropout(opt.dropout)) end lm:add(nn.SplitTable(1)) -- tensor to table of tensors -- rnn layers local stepmodule = nn.Sequential() -- applied at each time-step local inputsize = opt.inputsize for i,hiddensize in ipairs(opt.hiddensize) do local rnn if opt.gru then -- Gated Recurrent Units rnn = nn.GRU(inputsize, hiddensize, nil, opt.dropout/2) elseif opt.lstm then -- Long Short Term Memory units require 'nngraph' nn.FastLSTM.usenngraph = true -- faster nn.FastLSTM.bn = opt.bn rnn = nn.FastLSTM(inputsize, hiddensize) elseif opt.mfru then -- Multi Function Recurrent Unit rnn = nn.MuFuRu(inputsize, hiddensize) else -- simple recurrent neural network local rm = nn.Sequential() -- input is {x[t], h[t-1]} :add(nn.ParallelTable() :add(i==1 and nn.Identity() or nn.Linear(inputsize, hiddensize)) -- input layer :add(nn.Linear(hiddensize, hiddensize))) -- recurrent layer :add(nn.CAddTable()) -- merge :add(nn.Sigmoid()) -- transfer rnn = nn.Recurrence(rm, hiddensize, 1) end stepmodule:add(rnn) if opt.dropout > 0 then stepmodule:add(nn.Dropout(opt.dropout)) end inputsize = hiddensize end -- output layer stepmodule:add(nn.Linear(inputsize, #trainset.ivocab)) stepmodule:add(nn.LogSoftMax()) -- encapsulate stepmodule into a Sequencer lm:add(nn.Sequencer(stepmodule)) -- remember previous state between batches lm:remember((opt.lstm or opt.gru or opt.mfru) and 'both' or 'eval') if not opt.silent then print"Language Model:" print(lm) end if opt.uniform > 0 then for k,param in ipairs(lm:parameters()) do param:uniform(-opt.uniform, opt.uniform) end end --[[ loss function ]]-- local crit = nn.ClassNLLCriterion() -- target is also seqlen x batchsize. local targetmodule = nn.SplitTable(1) if opt.cuda then targetmodule = nn.Sequential() :add(nn.Convert()) :add(targetmodule) end local criterion = nn.SequencerCriterion(crit) --[[ CUDA ]]-- if opt.cuda then lm:cuda() criterion:cuda() targetmodule:cuda() end --[[ experiment log ]]-- -- is saved to file every time a new validation minima is found local xplog = {} xplog.opt = opt -- save all hyper-parameters and such xplog.dataset = 'PennTreeBank' xplog.vocab = trainset.vocab -- will only serialize params xplog.model = nn.Serial(lm) xplog.model:mediumSerial() xplog.criterion = criterion xplog.targetmodule = targetmodule -- keep a log of NLL for each epoch xplog.trainppl = {} xplog.valppl = {} -- will be used for early-stopping xplog.minvalppl = 99999999 xplog.epoch = 0 local params, grad_params = lm:getParameters() local adamconfig = { beta1 = opt.adamconfig[1], beta2 = opt.adamconfig[2], } local ntrial = 0 paths.mkdir(opt.savepath) local epoch = 1 opt.lr = opt.startlr opt.trainsize = opt.trainsize == -1 and trainset:size() or opt.trainsize opt.validsize = opt.validsize == -1 and validset:size() or opt.validsize while opt.maxepoch <= 0 or epoch <= opt.maxepoch do print("") print("Epoch #"..epoch.." :") -- 1. training sgdconfig = { learningRate = opt.lr, momentum = opt.momentum } local a = torch.Timer() lm:training() local sumErr = 0 -- local sumErr = 0 for i, inputs, targets in trainset:subiter(opt.seqlen, opt.trainsize) do local curTargets = targetmodule:forward(targets) local curInputs = inputs local function feval(x) if x ~= params then params:copy(x) end grad_params:zero() -- forward local outputs = lm:forward(curInputs) local err = criterion:forward(outputs, curTargets) sumErr = sumErr + err -- backward local gradOutputs = criterion:backward(outputs, curTargets) lm:zeroGradParameters() lm:backward(curInputs, gradOutputs) -- gradient clipping if opt.cutoff > 0 then local norm = lm:gradParamClip(opt.cutoff) -- affects gradParams opt.meanNorm = opt.meanNorm and (opt.meanNorm*0.9 + norm*0.1) or norm end return err, grad_params end if opt.adam then local _, loss = optim.adam(feval, params, adamconfig) else local _, loss = optim.sgd(feval, params, sgdconfig) end if opt.progress then xlua.progress(math.min(i + opt.seqlen, opt.trainsize), opt.trainsize) end if i % 1000 == 0 then collectgarbage() end end -- learning rate decay if opt.schedule then opt.lr = opt.schedule[epoch] or opt.lr else opt.lr = opt.lr + (opt.minlr - opt.startlr)/opt.saturate end opt.lr = math.max(opt.minlr, opt.lr) if not opt.silent then print("learning rate", opt.lr) if opt.meanNorm then print("mean gradParam norm", opt.meanNorm) end end if cutorch then cutorch.synchronize() end local speed = a:time().real/opt.trainsize print(string.format("Speed : %f sec/batch ", speed)) local ppl = torch.exp(sumErr/opt.trainsize) print("Training PPL : "..ppl) xplog.trainppl[epoch] = ppl -- 2. cross-validation lm:evaluate() local sumErr = 0 for i, inputs, targets in validset:subiter(opt.seqlen, opt.validsize) do targets = targetmodule:forward(targets) local outputs = lm:forward(inputs) local err = criterion:forward(outputs, targets) sumErr = sumErr + err end local ppl = torch.exp(sumErr/opt.validsize) -- Perplexity = exp( sum ( NLL ) / #w) print("Validation PPL : "..ppl) xplog.valppl[epoch] = ppl ntrial = ntrial + 1 -- early-stopping if ppl < xplog.minvalppl then -- save best version of model xplog.minvalppl = ppl xplog.epoch = epoch local filename = paths.concat(opt.savepath, opt.id..'.t7') print("Found new minima. Saving to "..filename) torch.save(filename, xplog) ntrial = 0 elseif ntrial >= opt.earlystop then print("No new minima found after "..ntrial.." epochs.") print("Stopping experiment.") break end collectgarbage() epoch = epoch + 1 end print("Evaluate model using : ") print("th scripts/evaluate-rnnlm.lua --xplogpath "..paths.concat(opt.savepath, opt.id..'.t7')..(opt.cuda and ' --cuda' or ''))
return { bg = "#202328", fg = "#bbc2cf", aqua = "#3affdb", beige = "#f5c06f", blue = "#51afef", brown = "#905532", cyan = "#008080", darkblue = "#081633", darkorange = "#f16529", green = "#98be65", grey = "#8c979a", lightblue = "#5fd7ff", lightgreen = "#31b53e", magenta = "#c678dd", orange = "#d4843e", pink = "#cb6f6f", purple = "#834f79", red = "#ae403f", salmon = "#ee6e73", violet = "#a9a1e1", white = "#eff0f1", yellow = "#f09f17", black = "#000000" }
object_mobile_hoth_collector = object_mobile_shared_hoth_collector:new { } ObjectTemplates:addTemplate(object_mobile_hoth_collector, "object/mobile/hoth_collector.iff")
local core, smoketest = core, smoketest local sam = smoketest.sam local function is_testable(name, def) local privs = def.privs if privs.server or privs.ban or privs.kick or privs.rollback or privs.password then return false end return true end local function describe_chatcommand(name, def) if is_testable(name, def) then describe("/" .. name, function() it("can be called from virtual players", function() def.func(sam:get_player_name(), "") end) end) end end -- describe anything registered so far for name, def in pairs(core.chatcommands) do describe_chatcommand(name, def) end -- describe anything registered from now on, too local register_chatcommand = core.register_chatcommand core.register_chatcommand = function(cmd, def) register_chatcommand(cmd, def) describe_chatcommand(cmd, def) end
-- inoremap <silent><expr> <C-Space> compe#complete() -- inoremap <silent><expr> <CR> compe#confirm('<CR>') -- inoremap <silent><expr> <C-e> compe#close('<C-e>') -- inoremap <silent><expr> <C-f> compe#scroll({ 'delta': +4 }) -- inoremap <silent><expr> <C-d> compe#scroll({ 'delta': -4 }) H.keymap('i', '<C-space>', 'compe#complete()', {silent = true, expr = true, noremap = true}) H.keymap('i', '<cr>', 'compe#confirm(\'<CR>\')', {silent = true, expr = true}) H.keymap('i', '<c-e>', 'compe#close(\'<C-e>\')', {silent = true, expr = true})
-- GGNN for making a sequence of graph level predictions. Designed for -- bAbI task 19. -- -- This is a variant where the graph level output and the node annotation -- output share the same propagation network. -- -- Yujia Li, 04/2016 -- local GraphLevelSequenceSharePropagationGGNN = torch.class('ggnn.GraphLevelSequenceSharePropagationGGNN') -- propagation_net is a BaseGGNN -- graph_level_output_net is a GraphLevelOutputNet -- annotation_output_net is a PerNodeOutputNet function GraphLevelSequenceSharePropagationGGNN:__init(propagation_net, graph_level_output_net, annotation_output_net) self.propagation_net = propagation_net self.graph_level_output_net = graph_level_output_net self.annotation_output_net = annotation_output_net assert(propagation_net.annotation_dim == graph_level_output_net.annotation_dim) assert(propagation_net.annotation_dim == annotation_output_net.annotation_dim) assert(propagation_net.state_dim == graph_level_output_net.state_dim) assert(propagation_net.state_dim == annotation_output_net.state_dim) self.n_classes = self.graph_level_output_net.n_classes end -- n_pred_steps is the number of prediction steps -- n_prop_steps is the number of propagation steps for each prediction -- function GraphLevelSequenceSharePropagationGGNN:forward(edges_list, n_pred_steps, n_prop_steps, annotations_list) self.n_pred_steps = n_pred_steps self.n_prop_steps = n_prop_steps if self.slices == nil then self.slices = {} end if #self.slices < n_pred_steps then for i=#self.slices+1, n_pred_steps do local pnet = self.propagation_net:create_share_param_copy() local glnet = self.graph_level_output_net:create_share_param_copy() local anet = self.annotation_output_net:create_share_param_copy() self.slices[i] = {pnet=pnet, glnet=glnet, anet=anet} end end if self.graph_level_output == nil then self.graph_level_output = torch.Tensor() end local annotations_list_input = annotations_list for t=1,n_pred_steps do local nodereps = self.slices[t].pnet:forward(edges_list, n_prop_steps, annotations_list_input) -- node representations local nodeanno = self.slices[t].pnet._annotations -- node annotation matrix local n_nodes_list = self.slices[t].pnet.n_nodes_list local gl_out = self.slices[t].glnet:forward(nodereps, nodeanno, n_nodes_list) if t < n_pred_steps then local a_out = self.slices[t].anet:forward(nodereps, nodeanno, n_nodes_list) annotations_list_input = a_out end if t == 1 then edges_list = self.slices[t].pnet.a_list -- get the adjacency matrices to save time self.n_graphs = self.slices[t].pnet.n_graphs self.graph_level_output:resize(self.n_graphs, self.n_classes * n_pred_steps) end self.graph_level_output:narrow(2, (t-1) * self.n_classes + 1, self.n_classes):copy(gl_out) end return self.graph_level_output end function GraphLevelSequenceSharePropagationGGNN:predict(edges_list, n_pred_steps, n_prop_steps, annotations_list) local output = self:forward(edges_list, n_pred_steps, n_prop_steps, annotations_list) output:resize(self.n_graphs * n_pred_steps, self.n_classes) local _, idx = output:max(2) return idx:resize(self.n_graphs, n_pred_steps) end function GraphLevelSequenceSharePropagationGGNN:backward(graph_level_grad) assert(graph_level_grad:size(1) == self.n_graphs) assert(graph_level_grad:size(2) == self.n_classes * self.n_pred_steps) local a_grad, r_grad -- annotation and node representation gradients for t=self.n_pred_steps,1,-1 do local gl_grad = graph_level_grad:narrow(2,(t-1) * self.n_classes + 1, self.n_classes) local gl_r_grad, gl_a_grad = self.slices[t].glnet:backward(gl_grad) if t < self.n_pred_steps then local a_r_grad, a_a_grad = self.slices[t].anet:backward(a_grad) gl_r_grad:add(a_r_grad) gl_a_grad:add(a_a_grad) end r_grad = gl_r_grad a_grad = gl_a_grad a_grad:add(self.slices[t].pnet:backward(r_grad)) end return a_grad end function GraphLevelSequenceSharePropagationGGNN:getParameters() local params, grad_params = self:parameters() return nn.Module.flatten(params), nn.Module.flatten(grad_params) end function GraphLevelSequenceSharePropagationGGNN:parameters() local w, gw = self.propagation_net:parameters() local aw, agw = self.graph_level_output_net:parameters() for i=1,#aw do table.insert(w, aw[i]) table.insert(gw, agw[i]) end aw, agw = self.annotation_output_net:parameters() for i=1,#aw do table.insert(w, aw[i]) table.insert(gw, agw[i]) end return w, gw end function GraphLevelSequenceSharePropagationGGNN:print_model() print('[Propagation Net]') self.propagation_net:print_model() print('[GraphLevel Output Net]:') self.graph_level_output_net:print_model() print('[Annotation Output Net]:') self.annotation_output_net:print_model() end ---------- model I/O ----------- function GraphLevelSequenceSharePropagationGGNN:get_constructor_param_dict() return { state_dim = self.propagation_net.state_dim, annotation_dim = self.propagation_net.annotation_dim, prop_net_h_sizes = self.propagation_net.prop_net_h_sizes, n_edge_types = self.propagation_net.n_edge_types, gl_output_net_sizes = self.graph_level_output_net.output_net_sizes, a_output_net_h_sizes = self.annotation_output_net.output_net_h_sizes } end function ggnn.load_graph_level_seq_share_prop_ggnn_from_file(model_file) local d = torch.load(model_file) local propagation_net = ggnn.BaseGGNN( d['state_dim'], d['annotation_dim'], d['prop_net_h_sizes'], d['n_edge_types']) local graph_level_output_net = ggnn.GraphLevelOutputNet( d['state_dim'], d['annotation_dim'], d['gl_output_net_sizes']) local annotation_output_net = ggnn.PerNodeOutputNet( d['state_dim'], d['annotation_dim'], d['a_output_net_h_sizes']) local glseqnet = ggnn.GraphLevelSequenceSharePropagationGGNN(propagation_net, graph_level_output_net, annotation_output_net) local w, _ = glseqnet:getParameters() w:copy(d['params']) return glseqnet end
RegisterCommand('ooc', function(source, args) local LocalPlayer = exports["npc-core"]:getModule("LocalPlayer") local Player = LocalPlayer:getCurrentCharacter() local cid = exports['isPed']:isPed('cid') local firstname = Player.first_name local lastname = Player.last_name local dob = Player.dob local gender = Player.gender local text = '' -- edit here if you want to change the language : EN: the person / FR: la personne for i = 1,#args do text = text .. ' ' .. args[i] end TriggerServerEvent('chat:oocmessage', cid, firstname, lastname, dob, gender, text) end) RegisterNetEvent('sendProximityMessage') AddEventHandler('sendProximityMessage', function(id, name, message) local myId = PlayerId() local pid = GetPlayerFromServerId(id) if pid == myId then TriggerEvent('chatMessage', "^4" .. name .. "", {0, 153, 204}, "^7 " .. message) elseif GetDistanceBetweenCoords(GetEntityCoords(GetPlayerPed(myId)), GetEntityCoords(GetPlayerPed(pid)), true) < 19.999 then TriggerEvent('chatMessage', "^4" .. name .. "", {0, 153, 204}, "^7 " .. message) end end) RegisterNetEvent('sendProximityMessageMe') AddEventHandler('sendProximityMessageMe', function(id, name, message) local myId = PlayerId() local pid = GetPlayerFromServerId(id) if pid == myId then TriggerEvent('chatMessage', "", {255, 0, 0}, " ^6 " .. name .." ".."^6 " .. message) elseif GetDistanceBetweenCoords(GetEntityCoords(GetPlayerPed(myId)), GetEntityCoords(GetPlayerPed(pid)), true) < 19.999 then TriggerEvent('chatMessage', "", {255, 0, 0}, " ^6 " .. name .." ".."^6 " .. message) end end) RegisterNetEvent('sendProximityMessageDo') AddEventHandler('sendProximityMessageDo', function(id, name, message) local myId = PlayerId() local pid = GetPlayerFromServerId(id) if pid == myId then TriggerEvent('chatMessage', "", {255, 0, 0}, " ^0* " .. name .." ".."^0 " .. message) elseif GetDistanceBetweenCoords(GetEntityCoords(GetPlayerPed(myId)), GetEntityCoords(GetPlayerPed(pid)), true) < 19.999 then TriggerEvent('chatMessage', "", {255, 0, 0}, " ^0* " .. name .." ".."^0 " .. message) end end) Citizen.CreateThread(function() TriggerEvent('chat:addSuggestion', '/911', 'Emergency! Tell the Police or EMS your situation (Can do when dead)') TriggerEvent('chat:addSuggestion', '/311', 'None-Emergency! Tell the Police or EMS your situation (Can do when dead)') TriggerEvent('chat:addSuggestion', '/911r', 'Reply to a 911 Call if You are Police or EMS') TriggerEvent('chat:addSuggestion', '/311r', 'Reply to a 311 Call if You are Police or EMS') end) RegisterCommand('911', function(source, args) TriggerServerEvent('911', args, exports['isPed']:isPed('cid')) local LocalPlayer = exports["npc-core"]:getModule("LocalPlayer") local Player = LocalPlayer:getCurrentCharacter() local firstname = Player.first_name local lastname = Player.last_name local phone_number = Player.phone_number local job = exports['isPed']:isPed('job') local cid = exports['isPed']:isPed('cid') local message = "" local id = GetPlayerFromServerId() for k,v in ipairs(args) do message = message .. " " .. v end -- TriggerEvent('chatMessage', '911 | ' .. firstname .. " | " .. lastname .. " # " .. phone_number, 3, tostring(message)) end) RegisterCommand('911r', function(source, args) TriggerServerEvent('911r', args, exports['isPed']:isPed('cid')) end) RegisterCommand('311r', function(source, args) TriggerServerEvent('311r', args, exports['isPed']:isPed('cid')) end) RegisterCommand('311', function(source, args) TriggerServerEvent('311', args, exports['isPed']:isPed('cid')) local LocalPlayer = exports["npc-core"]:getModule("LocalPlayer") local Player = LocalPlayer:getCurrentCharacter() local firstname = Player.first_name local lastname = Player.last_name local phone_number = Player.phone_number local job = exports['isPed']:isPed('job') local cid = exports['isPed']:isPed('cid') local message = "" for k,v in ipairs(args) do message = message .. " " .. v end -- TriggerEvent('chatMessage', '311 | ' .. firstname .. " | " .. lastname .. " # " .. phone_number, 3, tostring(message)) end) RegisterNetEvent('npc-911:display') AddEventHandler('npc-911:display', function(firstname, lastname, phonenumber, message, src) if exports['isPed']:isPed('job') == 'Police' then TriggerEvent('chatMessage', '911 | ( '.. src .. ' ) ' .. firstname .. " | " .. lastname .. " #" .. phonenumber, 2, tostring(message)) TriggerEvent("callsound") PlaySoundFrontend(-1, "Event_Start_Text", "GTAO_FM_Events_Soundset", 0) elseif exports['isPed']:isPed('job') == 'EMS' then TriggerEvent('chatMessage', '911 | ( '.. src .. ' ) ' .. firstname .. " | " .. lastname .. " #" .. phonenumber, 2, tostring(message)) TriggerEvent("callsound") PlaySoundFrontend(-1, "Event_Start_Text", "GTAO_FM_Events_Soundset", 0) end end) RegisterNetEvent('npc-311:display') AddEventHandler('npc-311:display', function(firstname, lastname, phonenumber, message, src) if exports['isPed']:isPed('job') == 'Police' then TriggerEvent('chatMessage', '311 | ( '.. src .. ' ) ' .. firstname .. " | " .. lastname .. " #" .. phonenumber, 2, tostring(message)) elseif exports['isPed']:isPed('job') == 'Police' then TriggerEvent('chatMessage', '311 | ( '.. src .. ' ) ' .. firstname .. " | " .. lastname .. " #" .. phonenumber, 2, tostring(message)) end end) RegisterNetEvent('npc-911r:display') AddEventHandler('npc-911r:display', function(target, firstname, lastname, phonenumber, message) if exports['isPed']:isPed('job') == 'Police' then TriggerEvent('chatMessage', '911r -> | ' .. target .. " | " .. firstname .. " | " .. lastname .. " # " .. phonenumber, 3, tostring(message)) elseif exports['isPed']:isPed('job') == 'Police' then TriggerEvent('chatMessage', '911r -> | ' .. target .. " | " .. firstname .. " | " .. lastname .. " # " .. phonenumber, 3, tostring(message)) end end) RegisterNetEvent('npc-311r:display') AddEventHandler('npc-311r:display', function(target, firstname, lastname, phonenumber, message) if exports['isPed']:isPed('job') == 'Police' then TriggerEvent('chatMessage', '311r -> | ' .. target .. " | " .. firstname .. " | " .. lastname .. " # " .. phonenumber, 3, tostring(message)) elseif exports['isPed']:isPed('job') == 'Police' then TriggerEvent('chatMessage', '311r -> | ' .. target .. " | " .. firstname .. " | " .. lastname .. " # " .. phonenumber, 3, tostring(message)) end end) -- RegisterNetEvent('npc-chat:911obtain') -- AddEventHandler('npc-chat:911obtain', function(message) -- local LocalPlayer = exports["npc-core"]:getModule("LocalPlayer") -- local Player = LocalPlayer:getCurrentCharacter() -- local name = Player.first_name .. ' ' .. Player.last_name -- local phone_number = Player.phone_number -- local job = exports['isPed']:isPed('job') -- local cid = exports['isPed']:isPed('cid') -- print('yerr') -- if job == 'Police' then -- TriggerEvent('chatMessage', '911 | ' .. Player.first_name .. " | " .. Player.last_name .. " # " .. phone_number, 3, tostring(message)) -- end -- end) -- TriggerClientEvent("chatMessage", src, "911 | " .. char.first_name .. " | " .. char.last_name .. " # " .. phonenumber, 3, tostring(message))
local function should_error_code(code) local fn = assert(loadstring(code, "should_error_code")) local ok = pcall(fn) assert(not ok, string.format("the code should get error but not, code: %s", code)) end should_error_code [[io.open("anonymous.file")]] should_error_code [[os.open("anonymous.file")]] should_error_code [[_G["io"].open("anonymous.file")]] should_error_code [[_G["os"].open("anonymous.file")]] local fn = assert(loadstring [[ return arg_env.a + arg_env.b ]]) local load_env = { arg_env = { a = 1, b = 2 } } fn = setfenv(fn, load_env) assert(fn() == 3)
----------------------------------- -- Ability: Warding Circle -- Grants resistance, defense, and attack against Demons to party members within the area of effect. -- Obtained: Samurai Level 5 -- Recast Time: 5:00 -- Duration: 3:00 ----------------------------------- require("scripts/globals/settings") require("scripts/globals/status") ----------------------------------- function onAbilityCheck(player,target,ability) return 0,0 end function onUseAbility(player,target,ability) local duration = 180 + player:getMod(tpz.mod.WARDING_CIRCLE_DURATION) target:addStatusEffect(tpz.effect.WARDING_CIRCLE,15,0,duration) end
--[[ Desc: Gorecross state Author: SerDing Since: 2017-07-28 Alter: 2020-02-04 ]] local _Base = require("entity.states.base") ---@class Entity.State.Swordman.GoreCross : Entity.State.Base ---@field protected _effectTicks table<number, number> ---@field protected _attackTicks table<number, number> local _GoreCross = require("core.class")(_Base) function _GoreCross:Ctor(data, ...) _Base.Ctor(self, data, ...) self.skillID = 64 self._effectTicks = data.effectTicks self._attackTicks = data.attackTicks end function _GoreCross:Enter() _Base.Enter(self) _Base.PlaySound(self._soundDataSet.voice) ---@param effect Entity self._NewProjectile = function(effect) local t = effect.transform local param = { x = t.position.x + t.direction * effect.render.renderObj:GetWidth() * 0.65, y = t.position.y, z = t.position.z - effect.render.renderObj:GetHeight() / 2, direction = t.direction, master = self._entity, camp = self._entity.identity.camp, } _Base.NewEntity(self._entityDataSet[3], param) end local param = { master = self._entity } _Base.NewEntity(self._entityDataSet[1], param) self._crossEffect = _Base.NewEntity(self._entityDataSet[2], param) -- self._crossEffect.identity.destroyEvent:AddListener(self._crossEffect, self._NewProjectile) self._combat:SetSoundGroup(self._soundDataSet.hitting) self._combat:StartAttack(self._attackDataSet[1]) end function _GoreCross:Update(dt) local tick = self._body:GetTick() if tick == self._effectTicks[1] or tick == self._effectTicks[2] then _Base.PlaySound(self._soundDataSet.swing[1]) elseif tick == self._effectTicks[3] then _Base.PlaySound(self._soundDataSet.swing[2]) end if tick == self._attackTicks[1] then self._combat:StartAttack(self._attackDataSet[2]) end if self._crossEffect and self._crossEffect.render.renderObj:GetTick() == self._effectTicks[3] then self._NewProjectile(self._crossEffect) self._crossEffect.identity:StartDestroy() self._crossEffect = nil end _Base.AutoTransitionAtEnd(self) end function _GoreCross:Exit() self._projectile = nil _Base.Exit(self) end return _GoreCross
local fn = require('tmux.lib.fn') local M = {} local function restore_zoom() if vim.fn.exists('t:tmux_pane_zoom') == 1 then vim.cmd(vim.api.nvim_tabpage_get_var(0, 'tmux_pane_zoom')) vim.api.nvim_tabpage_del_var(0, 'tmux_pane_zoom') end end M.display_message = function (opts) opts = opts or {} local message = '' for key, value in pairs(opts) do if type(key) == 'number' then message = value end end return fn.nested(2, function () if message == '' then return end print(message) end) end M.display = M.display_message M.next_layout = function () return fn.nested(2, function () restore_zoom() vim.cmd('wincmd =') end) end M.new_window = function () return fn.nested(2, function () vim.cmd('tabnew +terminal') end) end M.neww = M.new_window M.rename_window = function (opts) opts = opts or {} local new_name = '' for key, value in pairs(opts) do if type(key) == 'number' then new_name = value end end return fn.nested(2, function (P) if new_name == '' then return end vim.api.nvim_buf_set_var(0, 'term_title', new_name) end) end M.renamew = M.rename_window M.rotate_window = function (opts) opts = opts or {} for key, value in pairs(opts) do if type(key) == 'number' then if value == 'U' then return fn.nested(2, function () restore_zoom() vim.cmd('wincmd R') end) end end end return fn.nested(2, function () restore_zoom() vim.cmd('wincmd r') end) end M.previous_window = function () return fn.nested(2, function () vim.cmd('tabprevious') end) end M.prev = M.pervious_window M.next_window = function () return fn.nested(2, function () vim.cmd('tabnext') end) end M.next = M.next_window M.last_window = function () return fn.nested(2, function (P) if P.last.tabpage ~= nil and P.last.tabpage <= #vim.api.nvim_list_tabpages() then vim.cmd('tabnext ' .. P.last.tabpage) else M.display_message({ 'No last window' })(P)() end end) end M.last = M.last_window M.select_window = function (opts) opts = opts or {} if opts.t then return fn.nested(2, function (P) local target_window = opts.t + P.index_offset if 0 < target_window and target_window <= #vim.api.nvim_list_tabpages() then vim.cmd('tabnext ' .. target_window) end end) end for key, value in pairs(opts) do if type(key) == 'number' then if value == 'l' then return M.last_window() elseif value == 'n' then return M.next_window() elseif value == 'p' then return M.previous_window() end end end return fn.nested(2) end M.selectw = M.select_window M.split_window = function (opts) opts = opts or {} for key, value in pairs(opts) do if type(key) == 'number' then if value == 'h' then return fn.nested(2, function () restore_zoom() vim.cmd('split | terminal') end) elseif value == 'v' then return fn.nested(2, function () restore_zoom() vim.cmd('vsplit | terminal') end) end end end return fn.nested(2) end M.splitw = M.split_window M.kill_window = function () return fn.nested(2, function () vim.cmd('tabclose!') end) end M.killw = M.kill_window M.confirm_before = function (opts) opts = opts or {} local cb = nil local prompt = opts.p or 'input: ' for key, value in pairs(opts) do if type(key) == 'number' then if type(value) == 'function' then cb = value end end end if cb then return fn.nested(2, function (P, M) local prompt_text = prompt if type(prompt_text) == 'function' then prompt_text = prompt_text() end if P.confirm(prompt_text, '&y\n&n', 2) == 1 then cb(P)(M) end end) end return fn.nested(2) end M.confirm = M.confirm_before M.command_prompt = function (opts) opts = opts or {} local cb = nil local placeholders = {} local prompts = { '' } if type(opts.I) == 'table' then placeholders = opts.I elseif opts.I ~= nil then placeholders = { opts.I } end if type(opts.p) == 'table' then prompts = opts.p elseif opts.p ~= nil then prompts = { opts.p } end for key, value in pairs(opts) do if type(key) == 'number' then if type(value) == 'function' then cb = value end end end if cb then return fn.nested(2, function (P, M) local outputs = {} for index, prompt in ipairs(prompts) do local prompt_text = prompt or '' local placeholder_text = placeholders[index] or '' if type(prompt_text) == 'function' then prompt_text = prompt_text() end if type(placeholder_text) == 'function' then placeholder_text = placeholder_text() end table.insert(outputs, P.input(prompt_text, placeholder_text)) end cb(outputs)(P)(M) end) else return fn.nested(2, function () vim.cmd('stopinsert') vim.api.nvim_feedkeys(':', 'n', true) end) end end M.send_prefix = function () return fn.nested(2, function (P) local prefix = vim.api.nvim_replace_termcodes(P.prefix, true, true, true) vim.api.nvim_feedkeys(prefix, 't', true) end) end M.break_pane = function (opts) opts = opts or {} local source = function () if opts.s ~= nil then return opts.s else return vim.fn.winnr() end end local keep_active = false for key, value in pairs(opts) do if type(key) == 'number' then if value == 'd' then keep_active = true end end end return fn.nested(2, function (P) if vim.fn.winnr('$') == 1 then return end local current_tab = vim.fn.tabpagenr() local src = source() restore_zoom() vim.cmd(src..'wincmd w') vim.cmd('wincmd T') if keep_active then vim.cmd('tabnext ' .. current_tab) end end) end M.breakp = M.break_pane M.last_pane = function () return fn.nested(2, function (P) local winid = vim.fn.winnr('#') if winid == 0 then M.display_message({ 'No last pane' })(P)() else vim.cmd(winid..'wincmd w') end end) end M.lastp = M.last_pane M.select_pane = function (opts) opts = opts or {} if opts.t == ':.+' then return fn.nested(2, function () restore_zoom() vim.cmd('wincmd w') end) end for key, value in pairs(opts) do if type(key) == 'number' then if value == 'L' then return fn.nested(2, function () restore_zoom() vim.cmd('wincmd h') end) elseif value == 'D' then return fn.nested(2, function () restore_zoom() vim.cmd('wincmd j') end) elseif value == 'U' then return fn.nested(2, function () restore_zoom() vim.cmd('wincmd k') end) elseif value == 'R' then return fn.nested(2, function () restore_zoom() vim.cmd('wincmd l') end) end end end return fn.nested(2) end M.selectp = M.select_pane M.swap_pane = function (opts) opts = opts or {} local source = function () if opts.s ~= nil then return opts.s elseif P.mark.win == nil then return vim.fn.winnr() else -- TODO: this mark win-ID is incomplete, it need to combine with tab-ID -- to refer to a specific window (pane) in a specific tabpage (window) return P.mark.win end end local target = function () if opts.t == nil then return vim.fn.winnr() else return opts.t end end local op = nil local keep_active = false for key, value in pairs(opts) do if type(key) == 'number' then if value == 'D' or value == 'U' then source = function () if opts.t ~= nil then vim.cmd(opts.t..'wincmd w') end return vim.fn.winnr() end op = function () if value == 'D' then vim.cmd('wincmd w') else vim.cmd('wincmd W') end end target = function () return vim.fn.winnr() end elseif value == 'd' then keep_active = true end end end return fn.nested(2, function (P) local src = source() if op ~= nil then op() end local tgt = target() if src ~= tgt then restore_zoom() vim.cmd(tgt..'wincmd w') local target_buffer = vim.fn.bufnr() vim.cmd(src..'wincmd w') local source_buffer = vim.fn.bufnr() vim.cmd('hide buffer '..target_buffer) vim.cmd(tgt..'wincmd w') vim.cmd('hide buffer '..source_buffer) if keep_active then vim.cmd(src..'wincmd w') end end end) end M.swapp = swap_pane M.resize_pane = function (opts) opts = opts or {} local sign = '+' local value = opts.L or opts.R or opts.x or opts.y or 1 local expression = {} if opts.L or opts.R or opts.x then table.insert(expression, 'vertical') end if opts.L or opts.D then sign = '-' elseif opts.x or opts.y then sign = '' end local toggle_zoom = false for key, value in pairs(opts) do if type(key) == 'number' then if value == 'Z' then toggle_zoom = true end end end if toggle_zoom then return fn.nested(2, function (P) if vim.fn.exists('t:tmux_pane_zoom') == 1 then restore_zoom() elseif vim.fn.winnr('$') > 1 then vim.api.nvim_tabpage_set_var(0, 'tmux_pane_zoom', vim.fn.winrestcmd()) vim.cmd('vertical resize | resize') end end) end table.insert(expression, 'resize') if value ~= 0 then table.insert(expression, string.format('%s%d', sign, value)) end local command = table.concat(expression, ' ') return fn.nested(2, function () restore_zoom() vim.cmd(command) end) end M.resizep = M.resize_pane M.kill_pane = function (opts) return fn.nested(2, function (P) local has_tabs = vim.fn.tabpagenr('$') > 1 local has_windows = false local current_buffer = vim.api.nvim_get_current_buf() local wins = vim.api.nvim_list_wins() for _, win in ipairs(wins) do local buffer = vim.api.nvim_win_get_buf(win) local buffer_type = vim.api.nvim_buf_get_option(buffer, 'buftype') if current_buffer ~= buffer and buffer_type == 'terminal' then has_windows = true break end end restore_zoom() if has_windows then vim.cmd([[exe 'bdelete! '..expand('<abuf>')]]) elseif has_tabs then vim.cmd('quit!') elseif P.last.status == -1 then -- terminal is killed vim.cmd('cquit! 1') else vim.cmd('cquit! ' .. P.last.status) end end) end M.kill_p = M.kill_pane M.copy_mode = function () return fn.nested(2, function () vim.cmd('stopinsert') end) end M.paste_buffer = function () return fn.nested(2, function () vim.cmd('put') end) end M.cancel = function () return fn.nested(2, function () local mode = vim.fn.mode() local vblock = vim.api.nvim_replace_termcodes('<C-v>', true, true, true) if mode == 'v' or mode == 'V' or mode == vblock then vim.api.nvim_feedkeys(mode, 'n', true) end vim.cmd('nohlsearch') vim.cmd('startinsert!') end) end return M
-- two toolchain -- module function dep(namespace, name, cppmodule, usage_decl, deps) local m = { project = nil, cppmodule = cppmodule, namespace = namespace, name = name, dotname = string.gsub(name, "-", "."), idname = string.gsub(name, "-", "_"), usage_decl = usage_decl, deps = deps, } if namespace then m.dotname = namespace .. "." .. m.dotname m.idname = namespace .. "_" .. m.idname end m.project = project(m.idname) m.lib = { name = project().name, links = {}, kind = "StaticLib", } if cppmodule then modules(m) end return m end function module(namespace, name, rootpath, subpath, self_decl, usage_decl, reflect, deps, nomodule) local m = { project = nil, cppmodule = true, namespace = namespace, name = name, dotname = string.gsub(name, "-", "."), idname = string.gsub(name, "-", "_"), root = rootpath, subdir = subpath, path = path.join(rootpath, subpath), decl = decl, self_decl = self_decl, usage_decl = usage_decl, reflect = reflect, unity = false, deps = deps or {}, nomodule = nomodule, } if namespace then m.dotname = namespace .. "." .. m.dotname m.idname = namespace .. "_" .. m.idname end if not nomodule then table.insert(MODULES, m) end if reflect and not NO_REFL then m.refl = refl(m) end return m end function refl(m, force_project) deps = { two.infra, two.type, two.pool, two.refl } table.extend(deps, m.deps) table.extend(deps, { m }) for _, m in ipairs(m.deps) do if m.refl then table.insert(deps, m.refl) end end m.refl = module(m.namespace, m.name .. "-refl", m.root, path.join("meta", m.subdir), nil, m.usage_decl, false, deps, true) m.refl.headers = { path.join(m.root, "meta", string.gsub(m.name, "-", ".") .. ".meta.h") } m.refl.sources = { path.join(m.root, "meta", string.gsub(m.name, "-", ".") .. ".meta.cpp") } m.decl = refl_decl m.refl.force_project = force_project m.refl.reflected = m return m.refl end function link(lib, dep) --print(" links " .. dep.name) table.insert(lib.links, dep) links(dep.name) -- binaries don't export anything, and we only export from linked static libs if dep.kind == "StaticLib" then for _, m in ipairs(dep.modules or {}) do if lib.kind == "ConsoleApp" then defines { m.idname:upper() .. "_EXPORT=" } else defines { m.idname:upper() .. "_EXPORT=TWO_EXPORT" } end end end for _, deplink in ipairs(dep.links) do local dyntostatic = dep.kind ~= "StaticLib" and deplink.kind == "StaticLib" if dyntostatic and not NO_SHARED_LIBS then table.insert(lib.links, deplink) end end end function depend(lib, m) --print(" depends on " .. m.dotname) if m.header_only then defines { m.idname:upper() .. "_EXPORT=" } if m.self_decl then m.self_decl() end else if lib.name ~= m.lib.name and not table.contains(lib.links, m.lib) then link(lib, m.lib) end end if m.usage_decl then m.usage_decl() end end function decl(m) includedirs { m.root, } if m.headers then files(m.headers) else files { path.join(m.path, "**.h"), path.join(m.path, "**.hpp"), } end if m.sources then files(m.sources) else files { path.join(m.path, "**.cpp"), } end local cpps = os.matchfiles(path.join(m.path, "**.cpp")) mxx(cpps, m) defines { m.idname:upper() .. "_LIB" } defines { m.idname:upper() .. "_EXPORT=TWO_EXPORT" } --vpaths { [name] = { "**.h", "**.cpp" } } modules(m) if m.self_decl then m.self_decl() end if m.usage_decl then m.usage_decl() end if _OPTIONS["gcc"] == "asmjs" and _OPTIONS["jsbind"] and m.reflect then files { path.join(m.root, "bind", string.gsub(m.name, "-", ".") .. ".c.cpp") } end end function refl_decl(m, as_project) if as_project and not m.force_project then project(m.reflected.idname) end decl(m, as_project or m.force_project) end function lib(name, modules, libkind, optdeps, norefl) print("lib " .. name) local lib = { name = name, kind = libkind, modules = {}, links = {}, } lib.project = project(name) kind(libkind) for _, m in pairs(modules or {}) do --print(" module " .. m.dotname) table.insert(lib.modules, m) m.lib = lib m.decl(m) if m.refl and not norefl then table.insert(lib.modules, m.refl) m.refl.lib = lib m.refl.decl(m.refl) end end local deps = table.union(modules, optdeps or {}) lib.deps = table.inverse(sort_topological(deps, 'deps')) for _, m in ipairs(lib.deps) do if m ~= null then depend(lib, m) end end return lib end function libs(modules, libkind, deps) for k, m in pairs(modules) do m.lib = lib(m.idname, { m }, libkind, deps, true) if m.refl then m.refl.lib = lib(m.refl.idname, { m.refl }, libkind, deps) table.insert(modules, m.refl) end end end function unity(m) m.headers = { path.join(m.root, m.namespace, string.gsub(m.name, "-", ".") .. ".h") } m.sources = { path.join(m.root, m.namespace, string.gsub(m.name, "-", ".") .. ".cpp") } m.header_only = true if m.refl then unity(m.refl) end end
local mod = DBM:NewMod(1209, "DBM-Party-WoD", 5, 556) local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 12458 $"):sub(12, -3)) mod:SetCreatureID(84550) mod:SetEncounterID(1752)--TODO: VERIFY, "Boss 4" isn't descriptive enough mod:SetZone() mod:SetReCombatTime(120, 3)--this boss can quickly re-enter combat if boss reset occurs. mod:RegisterCombat("combat_emotefind", L.Pull) mod:RegisterEventsInCombat( "SPELL_CAST_START 169248 169233 169382", "SPELL_PERIODIC_DAMAGE 169223", "SPELL_ABSORBED 169223", "UNIT_DIED", "UNIT_TARGETABLE_CHANGED" ) --TODO, figure out why the hell emote pull doesn't work. Text is correct. local warnToxicSpiderling = mod:NewAddsLeftAnnounce("ej10492", 2, "Interface\\ICONS\\Spell_Nature_Web") --local warnVenomCrazedPaleOne = mod:NewSpellAnnounce("ej10502", 3)--I can't find a way to detect these, at least not without flat out scanning all DAMAGE events but that's too much work. local warnInhale = mod:NewSpellAnnounce(169233, 3) local warnPhase2 = mod:NewPhaseAnnounce(2, 2) local warnConsume = mod:NewSpellAnnounce(169248, 4) local warnGaseousVolley = mod:NewSpellAnnounce(169248, 3) local specWarnVenomCrazedPaleOne = mod:NewSpecialWarningSwitch("ej10502", "-Healer") --local specWarnConsume = mod:NewSpecialWarningSpell(169248) local specWarnGaseousVolley = mod:NewSpecialWarningSpell(169382, nil, nil, nil, 2) local specWarnToxicGas = mod:NewSpecialWarningMove(169223) local voiceConsume = mod:NewVoice(169248) local voicePhaseChange = mod:NewVoice(nil, nil, DBM_CORE_AUTO_VOICE2_OPTION_TEXT) mod.vb.spiderlingCount = 4 mod.vb.phase2 = false function mod:OnCombatStart(delay) self.vb.spiderlingCount = 4 self.vb.phase2 = false end function mod:SPELL_CAST_START(args) local spellId = args.spellId if spellId == 169233 then warnInhale:Show() elseif spellId == 169248 then warnConsume:Show() specWarnVenomCrazedPaleOne:Show() voiceConsume:Play("killmob") elseif spellId == 169382 then warnGaseousVolley:Show() specWarnGaseousVolley:Show() end end function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId) if spellId == 169223 and destGUID == UnitGUID("player") and self:AntiSpam(2) then specWarnToxicGas:Show() end end mod.SPELL_ABSORBED = mod.SPELL_PERIODIC_DAMAGE function mod:UNIT_DIED(args) local cid = self:GetCIDFromGUID(args.destGUID) if cid == 84552 then self.vb.spiderlingCount = self.vb.spiderlingCount - 1 if self.vb.spiderlingCount > 0 then--Don't need to warn 0, phase 2 kind of covers that 1.4 seconds later. warnToxicSpiderling:Show(self.vb.spiderlingCount) end end end function mod:UNIT_TARGETABLE_CHANGED() if not self.vb.phase2 then self.vb.phase2 = true warnPhase2:Show() voicePhaseChange:Play("ptwo") end end
------------------------------------------------------------------ -- lib.lua -- Author : Xin Zhang -- Version : 1.0.0.0 -- Date : 2011-10-16 -- Description: ------------------------------------------------------------------ local strModuleName = "lib"; ------------------------------------------- require("config.language.ZH_CN.MagicConfig"); require("config.language.ZH_CN.HelpInfoConfig"); require("config.language.ZH_CN.RoleInfoConfig"); require("config.language.ZH_CN.SkillInfoConfig"); require("config.language.ZH_CN.GuideConfigInfo");