content
stringlengths
5
1.05M
--[[local Environment = {} local ServerScriptService = game:GetService("ServerScriptService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local Players = game:GetService("Players") local PhysicsService = game:GetService("PhysicsService") local Debris = game:GetService("Debris") local debug_module = require(script.Parent.misc.debug_module) local filtering_enabled_server = require(script.Parent.injected_methods.filtering_enabled_server) local instance_creation = require(script.Parent.injected_methods.instance_creation) local number_format = require(script.Parent.injected_methods.number_format) local CORE_MODULES = script.Parent.Parent.core_modules local SHARED_SOURCE = ReplicatedStorage:WaitForChild("GameShared") Environment.server_environment = {} function Environment:build_environment() -- container for the core server modules self.server_environment.core_modules = {} self.server_environment.references = {} self.server_environment.references.__index = self.server_environment.references -- core module categories self.server_environment.core_modules.services = {} self.server_environment.references.services = self.server_environment.core_modules.services self.server_environment.core_modules.classes = {} self.server_environment.references.classes = self.server_environment.core_modules.classes self.server_environment.core_modules.modules = {} self.server_environment.references.modules = self.server_environment.core_modules.modules self.server_environment.core_modules.shared_modules = {} self.server_environment.references.shared_modules = self.server_environment.core_modules.shared_modules -- methods self.server_environment.references.print_table = debug_module.print_table self.server_environment.references.signal_client = filtering_enabled_server.signal_client self.server_environment.references.signal_all_clients = filtering_enabled_server.signal_all_clients self.server_environment.references.register_event = filtering_enabled_server.register_event self.server_environment.references.register_function = filtering_enabled_server.register_function self.server_environment.references.create_instance = instance_creation.create_instance self.server_environment.references.update_instance = instance_creation.update_instance self.server_environment.references.format_number = number_format.format_number -- roblox services self.server_environment.references.server_script_service = ServerScriptService self.server_environment.references.players = Players self.server_environment.references.replicated_storage = ReplicatedStorage self.server_environment.references.physics_service = PhysicsService self.server_environment.references.debris = Debris end function extract_modules_from(options) for _, core_module in pairs(options.folder:GetChildren()) do if core_module:IsA("ModuleScript") then local required_module = require(core_module) Environment.server_environment.core_modules[options.core_module_container.Name][core_module.Name] = required_module Environment.server_environment.core_modules[options.core_module_container.Name][core_module.Name].children = {} extract_children_from_module { module = core_module; core_module_container = options.core_module_container; } setmetatable(required_module, Environment.server_environment.references) end end end function extract_children_from_module(options) for _, sub_module in pairs(options.module:GetDescendants()) do if sub_module:IsA("ModuleScript") then local required_sub_module = require(sub_module) Environment.server_environment.core_modules[options.core_module_container.Name][options.module.Name].children[sub_module.Name] = required_sub_module setmetatable(required_sub_module, Environment.server_environment.references) end end end function extract_core_modules(core_module_container) for _, core_module in pairs(core_module_container:GetChildren()) do if core_module:IsA("ModuleScript") then local required_module = require(core_module) Environment.server_environment.core_modules[core_module_container.Name][core_module.Name] = required_module Environment.server_environment.core_modules[core_module_container.Name][core_module.Name].children = {} extract_children_from_module { module = core_module; core_module_container = core_module_container; } setmetatable(required_module, Environment.server_environment.references) elseif core_module:IsA("Folder") then extract_modules_from { folder = core_module; core_module_container = core_module_container; } end end end function Environment:add_environment_contents() for _, core_module_container in pairs(CORE_MODULES:GetChildren()) do extract_core_modules(core_module_container) end extract_core_modules(SHARED_SOURCE.core_modules.modules) end function Environment:start_services() for _, service in pairs(self.server_environment.core_modules.services) do coroutine.wrap(function() if typeof(service.start) == "function" then service:start() end end)() end end return Environment --]]
-- Test puzzle local AquaShine = ... local love = love local flux = require("flux") local stars = require("expanding_stars") local lily = require("lily") -- 1 2 3 6 9 18 27 54 81 162 243 486 local PuzzleMain = {Segments = 18} local ButtonText = AquaShine.LoadModule("uielement.button_text") PuzzleMain.Size = 486 / PuzzleMain.Segments PuzzleMain.SegmentString = { [162] = "3 x 3", [81] = "6 x 6", [54] = "9 x 9", [27] = "18 x 18", [18] = "27 x 27" } function PuzzleMain.StartAvgColorThread(id) PuzzleMain.AvgColThread = love.thread.newThread [[ local li = require("love.image") local le = require("love.event") local imagedata = ... local w, h = imagedata:getDimensions() local size = w*h local coldiv = love._version >= "0.11.0" and size or 255 * size -- color range changes local col = {0, 0, 0} for i = 0, size - 1 do local r, g, b = imagedata:getPixel(i % w, math.floor(i / w)) col[1] = col[1] + r col[2] = col[2] + g col[3] = col[3] + b end le.push("stars_setcolor", col[1] / coldiv, col[2] / coldiv, col[3] / coldiv) return ]] PuzzleMain.AvgColThread:start(id) end -- Custom flux interpolation function PuzzleMain.CustomFluxInterpolation(p) return math.log10(p*90 + 10) - 1 end function PuzzleMain.Start(arg) local fd if arg.lovepath then lily.newImageData(arg.lovepath) :onError(function() print("Error loading image") end) :onComplete(PuzzleMain.MainStart) :setUserData(arg) else local image = assert(io.open(arg[1], "rb")) local fd = love.filesystem.newFileData(image:read("*a"), "_") lily.newImageData(fd) :onError(function() print("Error loading image") end) :onComplete(PuzzleMain.MainStart) :setUserData(arg) image:close() end PuzzleMain.Font = AquaShine.LoadFont(nil, 18) -- Vera sans end function PuzzleMain.MainStart(arg, image) local len = PuzzleMain.Size * PuzzleMain.Size -- Load image supplied by arg PuzzleMain.ImageData = image PuzzleMain.Image = love.graphics.newImage(image, {mipmaps = true}) PuzzleMain.ImageWH = {image:getDimensions()} -- Get puzzle size PuzzleMain.Segments = assert(tonumber(arg[2] or 81), "Invalid number specificed") assert(PuzzleMain.SegmentString[PuzzleMain.Segments], "Invalid segment specificed") PuzzleMain.Size = 486 / PuzzleMain.Segments PuzzleMain.StartAvgColorThread(PuzzleMain.ImageData) -- Initialize canvas and font PuzzleMain.Canvas = love.graphics.newCanvas(486, 486) -- Draw it to canvas PuzzleMain.Canvas:renderTo(PuzzleMain.Redraw) -- Create tons of Quads PuzzleMain.Quads = {} -- The actual position of specific index PuzzleMain.ShouldBeInIndex = {} PuzzleMain.SelectedIndex = -1 for i = 0, len - 1 do local x = i % PuzzleMain.Size local y = math.floor(i / PuzzleMain.Size) PuzzleMain.Quads[i] = love.graphics.newQuad( x * PuzzleMain.Segments, -- Position y * PuzzleMain.Segments, -- Position PuzzleMain.Segments, -- Quad size PuzzleMain.Segments, -- Quad size 486, 486 -- Reference size ) PuzzleMain.ShouldBeInIndex[i] = i end -- Create size string PuzzleMain.SizeString = string.format("Puzzle Size:\n%d x %d", PuzzleMain.Size, PuzzleMain.Size) -- Initialize PuzzleMain.ResetState() -- Node initialization PuzzleMain.MainNode = AquaShine.Node() PuzzleMain.ResetButton = ButtonText("Reset Puzzle", {1, 0.96, 0.38}, PuzzleMain.ResetState) PuzzleMain.ResetButton:setPosition(694, 188) PuzzleMain.MainNode:addChild(PuzzleMain.ResetButton) PuzzleMain.BackButton = ButtonText("Back", {1, 1, 1}, function() return AquaShine.LoadEntryPoint(":menu", {Segment = PuzzleMain.Segments}) end) PuzzleMain.BackButton:setPosition(16, 16) PuzzleMain.MainNode:addChild(PuzzleMain.BackButton) end -- Canvas redraw function function PuzzleMain.Redraw() love.graphics.draw(PuzzleMain.Image, 0, 0, 0, 486/PuzzleMain.ImageWH[1], 486/PuzzleMain.ImageWH[2]) end function PuzzleMain.DoneTween() local qt PuzzleMain.TweenInProgress = false -- Start swapping place and re-add to SpriteBatch qt = PuzzleMain.QuadTarget[1] PuzzleMain.Quads[qt[1]] = qt[2] qt = PuzzleMain.QuadTarget[2] PuzzleMain.Quads[qt[1]] = qt[2] -- Increase move PuzzleMain.Moves = PuzzleMain.Moves + 1 -- Check if it's complete PuzzleMain.IsPuzzleComplete = PuzzleMain.IsComplete() if PuzzleMain.IsPuzzleComplete then -- It's complete. Slowly clear the rectangle line and stop timer PuzzleMain.StartTimer = false flux.to(PuzzleMain.RectangleOpacity, 1000, {0}):ease("linear") end end -- Start move piece function PuzzleMain.StartTween(idx1, idx2) -- Set quad target PuzzleMain.QuadTarget[1] = {idx2, PuzzleMain.Quads[idx1]} PuzzleMain.QuadTarget[2] = {idx1, PuzzleMain.Quads[idx2]} PuzzleMain.Quads[idx1] = nil PuzzleMain.Quads[idx2] = nil PuzzleMain.XTween[1] = idx1 % PuzzleMain.Size PuzzleMain.XTween[2] = idx2 % PuzzleMain.Size PuzzleMain.YTween[1] = math.floor(idx1 / PuzzleMain.Size) PuzzleMain.YTween[2] = math.floor(idx2 / PuzzleMain.Size) PuzzleMain.ShouldBeInIndex[idx1], PuzzleMain.ShouldBeInIndex[idx2] = PuzzleMain.ShouldBeInIndex[idx2], PuzzleMain.ShouldBeInIndex[idx1] local destx, desty = {}, {} destx[1] = PuzzleMain.XTween[2] destx[2] = PuzzleMain.XTween[1] desty[1] = PuzzleMain.YTween[2] desty[2] = PuzzleMain.YTween[1] -- X position flux.to(PuzzleMain.XTween, 500, destx):ease("quadout"):oncomplete(PuzzleMain.DoneTween) -- Y position flux.to(PuzzleMain.YTween, 500, desty):ease("quadin") -- Scale flux.to(PuzzleMain.ScaleInfo, 250, {1.25}) :ease(PuzzleMain.CustomFluxInterpolation) :after(PuzzleMain.ScaleInfo, 250, {1}) :ease(PuzzleMain.CustomFluxInterpolation) -- Move distance local distlen = math.sqrt((PuzzleMain.XTween[1] - PuzzleMain.XTween[2]) ^ 2 + (PuzzleMain.YTween[2] - PuzzleMain.YTween[1]) ^ 2) flux.to(PuzzleMain.MoveDistance, 500, {PuzzleMain.MoveDistance[1] + distlen}):ease("linear") -- Flag tween is in progress PuzzleMain.TweenInProgress = true end function PuzzleMain.IsComplete() for i = 0, PuzzleMain.Size * PuzzleMain.Size - 1 do if PuzzleMain.ShouldBeInIndex[i] ~= i then return false end end return true end -- Reset state. Includes re-randomizing things. function PuzzleMain.ResetState() local len = PuzzleMain.Size * PuzzleMain.Size -- Auto solve for i = 0, len - 1 do local a = PuzzleMain.ShouldBeInIndex[i] repeat local b = PuzzleMain.ShouldBeInIndex[a] PuzzleMain.ShouldBeInIndex[a], PuzzleMain.ShouldBeInIndex[b] = PuzzleMain.ShouldBeInIndex[b], PuzzleMain.ShouldBeInIndex[a] PuzzleMain.Quads[a], PuzzleMain.Quads[b] = PuzzleMain.Quads[b], PuzzleMain.Quads[a] a = PuzzleMain.ShouldBeInIndex[i] until a == i end math.randomseed(os.time()) -- Randomize for i = 0, len - 1 do local rnd repeat rnd = math.random(0, len - 1) until rnd ~= i -- Swap PuzzleMain.ShouldBeInIndex[i], PuzzleMain.ShouldBeInIndex[rnd] = PuzzleMain.ShouldBeInIndex[rnd], PuzzleMain.ShouldBeInIndex[i] PuzzleMain.Quads[i], PuzzleMain.Quads[rnd] = PuzzleMain.Quads[rnd], PuzzleMain.Quads[i] end -- Variable init PuzzleMain.XTween = {0, 0} PuzzleMain.YTween = {0, 0} PuzzleMain.ScaleInfo = {1} PuzzleMain.QuadTarget = {} PuzzleMain.MoveDistance = {0} PuzzleMain.RectangleOpacity = {1} PuzzleMain.Timer = 0 PuzzleMain.Moves = 0 PuzzleMain.StartTimer = false PuzzleMain.IsPuzzleComplete = false end function PuzzleMain.Update(deltaT) stars.update(deltaT * 0.001) flux.update(deltaT) if PuzzleMain.StartTimer then PuzzleMain.Timer = PuzzleMain.Timer + deltaT * 0.001 end end function PuzzleMain.Draw() -- Draw stars stars.draw() -- If image is not loaded yet, display message if not(PuzzleMain.ImageData) then love.graphics.setFont(PuzzleMain.Font) love.graphics.print("Loading Image...", 364, 233) return end -- Push stack and initialize love.graphics.push("all") love.graphics.setLineWidth(1) love.graphics.setColor(1, 1, 1) love.graphics.rectangle("fill", 185, 0, 494, 486) -- Draw tiles for i = 0, PuzzleMain.Size * PuzzleMain.Size - 1 do if PuzzleMain.Quads[i] then local x = i % PuzzleMain.Size local y = math.floor(i / PuzzleMain.Size) love.graphics.draw(PuzzleMain.Canvas, PuzzleMain.Quads[i], 189 + x * PuzzleMain.Segments, y * PuzzleMain.Segments) if PuzzleMain.RectangleOpacity[1] > 0 and PuzzleMain.SelectedIndex ~= i then love.graphics.setColor(0, 0, 0, PuzzleMain.RectangleOpacity[1]) love.graphics.rectangle("line", 189 + x * PuzzleMain.Segments, y * PuzzleMain.Segments, PuzzleMain.Segments, PuzzleMain.Segments) end love.graphics.setColor(1, 1, 1) end end -- Draw selected line if PuzzleMain.RectangleOpacity[1] > 0 and PuzzleMain.SelectedIndex ~= -1 then love.graphics.rectangle( "line", 189 + (PuzzleMain.SelectedIndex % PuzzleMain.Size) * PuzzleMain.Segments, math.floor(PuzzleMain.SelectedIndex / PuzzleMain.Size) * PuzzleMain.Segments, PuzzleMain.Segments, PuzzleMain.Segments ) end -- Draw text love.graphics.setFont(PuzzleMain.Font) love.graphics.print(PuzzleMain.SizeString, 16, 188) love.graphics.print( string.format("Time:\n%02d:%02d.%03d", PuzzleMain.Timer / 60, PuzzleMain.Timer % 60, (PuzzleMain.Timer % 1)*1000), 16, 268 ) love.graphics.print(string.format("Moves:\n%d", PuzzleMain.Moves), 16, 348) love.graphics.print(string.format("Move Distance\nTotal: %.3f", PuzzleMain.MoveDistance[1]), 16, 428) -- Also draw object which is in transition if PuzzleMain.TweenInProgress then love.graphics.draw(PuzzleMain.Canvas, PuzzleMain.QuadTarget[1][2], 189 + PuzzleMain.XTween[1] * PuzzleMain.Segments, PuzzleMain.YTween[1] * PuzzleMain.Segments, 0, PuzzleMain.ScaleInfo[1]) love.graphics.draw(PuzzleMain.Canvas, PuzzleMain.QuadTarget[2][2], 189 + PuzzleMain.XTween[2] * PuzzleMain.Segments, PuzzleMain.YTween[2] * PuzzleMain.Segments, 0, PuzzleMain.ScaleInfo[1]) end -- Draw completed image love.graphics.draw(PuzzleMain.Image, 692, 314, 0, 160/PuzzleMain.ImageWH[1], 160/PuzzleMain.ImageWH[2]) -- Draw buttons PuzzleMain.MainNode:draw() -- Pop stack love.graphics.pop() end function PuzzleMain.Resize() if not(PuzzleMain.ImageData) then return end PuzzleMain.Canvas:renderTo(PuzzleMain.Redraw) end function PuzzleMain.MousePressed(x, y, b) if not(PuzzleMain.ImageData) then return end if PuzzleMain.TweenInProgress then return end if not(PuzzleMain.IsPuzzleComplete) then -- Only able interact when puzzle is incomplete if x >= 189 and x < 675 and y >= 0 and y < 486 then local tx = math.floor((x - 189) / PuzzleMain.Segments) local ty = math.floor(y / PuzzleMain.Segments) -- Start timer PuzzleMain.StartTimer = true -- Set index if PuzzleMain.SelectedIndex == -1 then PuzzleMain.SelectedIndex = tx + ty * PuzzleMain.Size else local idx = tx + ty * PuzzleMain.Size if idx ~= PuzzleMain.SelectedIndex then -- Move PuzzleMain.StartTween(PuzzleMain.SelectedIndex, idx) end PuzzleMain.SelectedIndex = -1 end else -- Invalidate PuzzleMain.SelectedIndex = -1 end end return PuzzleMain.MainNode:triggerEvent("MousePressed", x, y, b, false) end function PuzzleMain.MouseMoved(x, y, dx, dy) if not(PuzzleMain.ImageData) then return end if PuzzleMain.TweenInProgress then return end return PuzzleMain.MainNode:triggerEvent("MouseMoved", x, y, dx, dy, false) end function PuzzleMain.MouseReleased(x, y, b) if not(PuzzleMain.ImageData) then return end if PuzzleMain.TweenInProgress then return end return PuzzleMain.MainNode:triggerEvent("MouseReleased", x, y, b, false) end return PuzzleMain
local Spell = { Name = "Spell", Type = "System", Namespace = "C_Spell", Functions = { { Name = "DoesSpellExist", Type = "Function", Arguments = { { Name = "spellID", Type = "number", Nilable = false }, }, Returns = { { Name = "spellExists", Type = "bool", Nilable = false }, }, }, { Name = "GetMawPowerBorderAtlasBySpellID", Type = "Function", Arguments = { { Name = "spellID", Type = "number", Nilable = false }, }, Returns = { { Name = "rarityBorderAtlas", Type = "string", Nilable = false }, }, }, { Name = "IsSpellDataCached", Type = "Function", Arguments = { { Name = "spellID", Type = "number", Nilable = false }, }, Returns = { { Name = "isCached", Type = "bool", Nilable = false }, }, }, { Name = "RequestLoadSpellData", Type = "Function", Arguments = { { Name = "spellID", Type = "number", Nilable = false }, }, }, }, Events = { { Name = "SpellDataLoadResult", Type = "Event", LiteralName = "SPELL_DATA_LOAD_RESULT", Payload = { { Name = "spellID", Type = "number", Nilable = false }, { Name = "success", Type = "bool", Nilable = false }, }, }, }, Tables = { }, }; APIDocumentation:AddDocumentationTable(Spell);
local input = require('opus.input') local colors = _G.colors local fs = _G.fs local multishell = _ENV.multishell local os = _G.os local shell = _ENV.shell local term = _G.term local textutils = _G.textutils shell.setCompletionFunction(shell.getRunningProgram(), function(_, index, text) if index == 1 then return fs.complete(text, shell.dir(), true, false) end end) local tArgs = { ... } if #tArgs == 0 then error( "Usage: edit <path>" ) end -- Error checking local sPath = shell.resolve(tArgs[1]) local bReadOnly = fs.isReadOnly(sPath) if fs.exists(sPath) and fs.isDir(sPath) then error( "Cannot edit a directory." ) end if multishell then multishell.setTitle(multishell.getCurrent(), fs.getName(sPath)) end local x, y = 1, 1 local w, h = term.getSize() local scrollX = 0 local scrollY = 0 local lastPos = { x = 1, y = 1 } local tLines = { } local bRunning = true local sStatus = "" local isError local fileInfo local lastAction local dirty = { y = 1, ey = h } local mark = { } local searchPattern local undo = { chain = { }, pointer = 0 } local complete = { } local color = { textColor = '0', keywordColor = '4', commentColor = 'd', stringColor = 'e', bgColor = colors.black, highlightColor = colors.orange, cursorColor = colors.lime, errorBackground = colors.red, } if not term.isColor() then color = { textColor = '0', keywordColor = '8', commentColor = '8', stringColor = '8', bgColor = colors.black, highlightColor = colors.lightGray, cursorColor = colors.white, errorBackground = colors.gray, } end local keyMapping = { -- movement up = 'up', down = 'down', left = 'left', right = 'right', pageUp = 'pageUp', [ 'control-b' ] = 'pageUp', pageDown = 'pageDown', -- [ 'control-f' ] = 'pageDown', home = 'home', [ 'end' ] = 'toend', [ 'control-home' ] = 'top', [ 'control-end' ] = 'bottom', [ 'control-right' ] = 'word', [ 'control-left' ] = 'backword', [ 'scroll_up' ] = 'scroll_up', [ 'control-up' ] = 'scroll_up', [ 'scroll_down' ] = 'scroll_down', [ 'control-down' ] = 'scroll_down', [ 'mouse_click' ] = 'go_to', [ 'control-l' ] = 'goto_line', -- marking [ 'shift-up' ] = 'mark_up', [ 'shift-down' ] = 'mark_down', [ 'shift-left' ] = 'mark_left', [ 'shift-right' ] = 'mark_right', [ 'mouse_drag' ] = 'mark_to', [ 'shift-mouse_click' ] = 'mark_to', [ 'control-a' ] = 'mark_all', [ 'control-shift-right' ] = 'mark_word', [ 'control-shift-left' ] = 'mark_backword', [ 'shift-end' ] = 'mark_end', [ 'shift-home' ] = 'mark_home', [ 'mouse_down' ] = 'mark_anchor', -- editing delete = 'delete', backspace = 'backspace', enter = 'enter', char = 'char', paste = 'paste', tab = 'tab', [ 'control-z' ] = 'undo', [ 'control-space' ] = 'autocomplete', -- copy/paste [ 'control-x' ] = 'cut', [ 'control-c' ] = 'copy', -- [ 'control-shift-paste' ] = 'paste_internal', -- file [ 'control-s' ] = 'save', [ 'control-q' ] = 'exit', [ 'control-enter' ] = 'run', -- search [ 'control-f' ] = 'find_prompt', [ 'control-slash' ] = 'find_prompt', [ 'control-n' ] = 'find_next', -- misc [ 'control-g' ] = 'status', [ 'control-r' ] = 'refresh', [ 'control' ] = 'menu', } local messages = { menu = '^s: save, ^q: quit, ^enter: run', wrapped = 'search hit BOTTOM, continuing at TOP', } if w < 32 then messages = { menu = '^s = save, ^q = quit', wrapped = 'search wrapped', } end local function getFileInfo(path) local abspath = shell.resolve(path) local fi = { abspath = abspath, path = path, isNew = not fs.exists(abspath), dirExists = fs.exists(fs.getDir(abspath)), modified = false, } if fi.isDir then fi.isReadOnly = true else fi.isReadOnly = fs.isReadOnly(fi.abspath) end return fi end local function setStatus(pattern, ...) sStatus = string.format(pattern, ...) end local function setError(pattern, ...) setStatus(pattern, ...) isError = true end local function load(path) tLines = {} if fs.exists(path) then local file = io.open(path, "r") local sLine = file:read() while sLine do table.insert(tLines, sLine) sLine = file:read() end file:close() end if #tLines == 0 then table.insert(tLines, '') end fileInfo = getFileInfo(tArgs[1]) local name = fileInfo.path if w < 32 then name = fs.getName(fileInfo.path) end if fileInfo.isNew then if not fileInfo.dirExists then setStatus('"%s" [New DIRECTORY]', name) else setStatus('"%s" [New File]', name) end elseif fileInfo.isReadOnly then setStatus('"%s" [readonly] %dL, %dC', name, #tLines, fs.getSize(fileInfo.abspath)) else setStatus('"%s" %dL, %dC', name, #tLines, fs.getSize(fileInfo.abspath)) end end local function save( _sPath ) -- Create intervening folder local sDir = _sPath:sub(1, _sPath:len() - fs.getName(_sPath):len() ) if not fs.exists( sDir ) then fs.makeDir( sDir ) end -- Save local file = nil local function innerSave() file = fs.open( _sPath, "w" ) if file then for _,sLine in ipairs( tLines ) do file.write(sLine .. "\n") end else error( "Failed to open ".._sPath ) end end local ok, err = pcall( innerSave ) if file then file.close() end return ok, err end local function split(str, pattern) pattern = pattern or "(.-)\n" local t = {} local function helper(line) table.insert(t, line) return "" end helper((str:gsub(pattern, helper))) return t end local tKeywords = { ["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true, ["elseif"] = true, ["end"] = true, ["false"] = true, ["for"] = true, ["function"] = true, ["if"] = true, ["in"] = true, ["local"] = true, ["nil"] = true, ["not"] = true, ["or"] = true, ["repeat"] = true, ["return"] = true, ["then"] = true, ["true"] = true, ["until"]= true, ["while"] = true, } local function writeHighlighted(sLine, ny) local buffer = { fg = '', text = '', } local function tryWrite(line, regex, fgcolor) local match = line:match(regex) if match then local fg if type(fgcolor) == "string" then fg = fgcolor else fg = fgcolor(match) end buffer.text = buffer.text .. match buffer.fg = buffer.fg .. string.rep(fg, #match) return line:sub(#match + 1) end return nil end while #sLine > 0 do sLine = tryWrite(sLine, "^%-%-%[%[.-%]%]", color.commentColor ) or tryWrite(sLine, "^%-%-.*", color.commentColor ) or tryWrite(sLine, "^\".-[^\\]\"", color.stringColor ) or tryWrite(sLine, "^\'.-[^\\]\'", color.stringColor ) or tryWrite(sLine, "^%[%[.-%]%]", color.stringColor ) or tryWrite(sLine, "^[%w_]+", function(match) if tKeywords[match] then return color.keywordColor end return color.textColor end) or tryWrite(sLine, "^[^%w_]", color.textColor) end buffer.fg = buffer.fg .. '7' buffer.text = buffer.text .. '.' if mark.active and ny >= mark.y and ny <= mark.ey then local sx = 1 if ny == mark.y then sx = mark.x end local ex = #buffer.text if ny == mark.ey then ex = mark.ex end buffer.bg = string.rep('f', sx - 1) .. string.rep('7', ex - sx) .. string.rep('f', #buffer.text - ex + 1) else buffer.bg = string.rep('f', #buffer.text) end term.blit(buffer.text, buffer.fg, buffer.bg) end local function redraw() if dirty.y > 0 then term.setBackgroundColor(color.bgColor) for dy = 1, h do local sLine = tLines[dy + scrollY] if sLine ~= nil then if dy + scrollY >= dirty.y and dy + scrollY <= dirty.ey then term.setCursorPos(1 - scrollX, dy) term.clearLine() writeHighlighted(sLine, dy + scrollY) end else term.setCursorPos(1 - scrollX, dy) term.clearLine() end end end -- Draw status if #sStatus > 0 then if isError then term.setTextColor(colors.white) term.setBackgroundColor(color.errorBackground) else term.setTextColor(color.highlightColor) term.setBackgroundColor(colors.gray) end term.setCursorPos(1, h) term.clearLine() term.write(string.format(' %s ', sStatus)) end if not (w < 32 and #sStatus > 0) then local modifiedIndicator = ' ' if undo.chain[1] then modifiedIndicator = '*' end local str = string.format(' %d:%d %s', y, x, modifiedIndicator) term.setTextColor(color.highlightColor) term.setBackgroundColor(colors.gray) term.setCursorPos(w - #str + 1, h) term.write(str) end term.setTextColor(color.cursorColor) term.setCursorPos(x - scrollX, y - scrollY) dirty.y, dirty.ey = 0, 0 if #sStatus > 0 then sStatus = '' dirty.y = scrollY + h dirty.ey = dirty.y end isError = false end local function nextWord(line, cx) local result = { line:find("(%w+)", cx) } if #result > 1 and result[2] > cx then return result[2] + 1 elseif #result > 0 and result[1] == cx then result = { line:find("(%w+)", result[2] + 1) } if #result > 0 then return result[1] end end end local function hacky_read() local _oldSetCursorPos = term.setCursorPos local _oldGetCursorPos = term.getCursorPos term.setCursorPos = function(cx) return _oldSetCursorPos(cx, h) end term.getCursorPos = function() local cx = _oldGetCursorPos() return cx, 1 end local s, m = pcall(function() return _G.read() end) term.setCursorPos = _oldSetCursorPos term.getCursorPos = _oldGetCursorPos if s then return m end if m == 'Terminated' then bRunning = false end return '' end local actions local __actions = { input = function(prompt) term.setTextColor(color.highlightColor) term.setBackgroundColor(colors.gray) term.setCursorPos(1, h) term.clearLine() term.write(prompt) local str = hacky_read() term.setCursorBlink(true) input:reset() term.setCursorPos(x - scrollX, y - scrollY) actions.dirty_line(scrollY + h) return str end, undo = function() local last = table.remove(undo.chain) if last then undo.active = true actions[last.action](unpack(last.args)) undo.active = false else setStatus('Already at oldest change') end end, addUndo = function(entry) local last = undo.chain[#undo.chain] if last and last.action == entry.action then if last.action == 'deleteText' then if last.args[3] == entry.args[1] and last.args[4] == entry.args[2] then last.args = { last.args[1], last.args[2], entry.args[3], entry.args[4], last.args[5] .. entry.args[5] } else table.insert(undo.chain, entry) end else -- insertText (need to finish) table.insert(undo.chain, entry) end else table.insert(undo.chain, entry) end end, autocomplete = function() if lastAction ~= 'autocomplete' or not complete.results then local sLine = tLines[y]:sub(1, x - 1) local nStartPos = sLine:find("[a-zA-Z0-9_%.]+$") if nStartPos then sLine = sLine:sub(nStartPos) end if #sLine > 0 then complete.results = textutils.complete(sLine) else complete.results = { } end complete.index = 0 complete.x = x end if #complete.results == 0 then setError('No completions available') elseif #complete.results == 1 then actions.insertText(x, y, complete.results[1]) complete.results = nil elseif #complete.results > 1 then local prefix = complete.results[1] for n = 1, #complete.results do local result = complete.results[n] while #prefix > 0 do if result:find(prefix, 1, true) == 1 then break end prefix = prefix:sub(1, #prefix - 1) end end if #prefix > 0 then actions.insertText(x, y, prefix) complete.results = nil else if complete.index > 0 then actions.deleteText(complete.x, y, complete.x + #complete.results[complete.index], y) end complete.index = complete.index + 1 if complete.index > #complete.results then complete.index = 1 end actions.insertText(complete.x, y, complete.results[complete.index]) end end end, refresh = function() actions.dirty_all() mark.continue = mark.active setStatus('refreshed') end, menu = function() setStatus(messages.menu) mark.continue = mark.active end, goto_line = function() local lineNo = tonumber(actions.input('Line: ')) if lineNo then actions.go_to(1, lineNo) else setStatus('Invalid line number') end end, find = function(pattern, sx) local nLines = #tLines for i = 1, nLines + 1 do local ny = y + i - 1 if ny > nLines then ny = ny - nLines end local nx = tLines[ny]:lower():find(pattern, sx) if nx then if ny < y or ny == y and nx <= x then setStatus(messages.wrapped) end actions.go_to(nx, ny) actions.mark_to(nx + #pattern, ny) actions.go_to(nx, ny) return end sx = 1 end setError('Pattern not found') end, find_next = function() if searchPattern then actions.unmark() actions.find(searchPattern, x + 1) end end, find_prompt = function() local text = actions.input('/') if #text > 0 then searchPattern = text:lower() if searchPattern then actions.unmark() actions.find(searchPattern, x) end end end, save = function() if bReadOnly then setError("Access denied") else local ok = save(sPath) if ok then setStatus('"%s" %dL, %dC written', fileInfo.path, #tLines, fs.getSize(fileInfo.abspath)) else setError("Error saving to %s", sPath) end end end, exit = function() bRunning = false end, run = function() input:reset() local sTempPath = "/.temp" local ok = save(sTempPath) if ok then local nTask = shell.openTab(sTempPath) if nTask then shell.switchTab(nTask) else setError("Error starting Task") end os.sleep(0) fs.delete(sTempPath) else setError("Error saving to %s", sTempPath) end end, status = function() local modified = '' if undo.chain[1] then modified = '[Modified] ' end setStatus('"%s" %s%d lines --%d%%--', fileInfo.path, modified, #tLines, math.floor((y - 1) / (#tLines - 1) * 100)) end, dirty_line = function(dy) if dirty.y == 0 then dirty.y = dy dirty.ey = dy else dirty.y = math.min(dirty.y, dy) dirty.ey = math.max(dirty.ey, dy) end end, dirty_range = function(dy, dey) actions.dirty_line(dy) actions.dirty_line(dey or #tLines) end, dirty = function() actions.dirty_line(y) end, dirty_all = function() actions.dirty_line(1) actions.dirty_line(#tLines) end, mark_begin = function() actions.dirty() if not mark.active then mark.active = true mark.anchor = { x = x, y = y } end end, mark_finish = function() if y == mark.anchor.y then if x == mark.anchor.x then mark.active = false else mark.x = math.min(mark.anchor.x, x) mark.y = y mark.ex = math.max(mark.anchor.x, x) mark.ey = y end elseif y < mark.anchor.y then mark.x = x mark.y = y mark.ex = mark.anchor.x mark.ey = mark.anchor.y else mark.x = mark.anchor.x mark.y = mark.anchor.y mark.ex = x mark.ey = y end actions.dirty() mark.continue = mark.active end, unmark = function() if mark.active then actions.dirty_range(mark.y, mark.ey) mark.active = false end end, mark_anchor = function(nx, ny) actions.go_to(nx, ny) actions.unmark() actions.mark_begin() actions.mark_finish() end, mark_to = function(nx, ny) actions.mark_begin() actions.go_to(nx, ny) actions.mark_finish() end, mark_up = function() actions.mark_begin() actions.up() actions.mark_finish() end, mark_right = function() actions.mark_begin() actions.right() actions.mark_finish() end, mark_down = function() actions.mark_begin() actions.down() actions.mark_finish() end, mark_left = function() actions.mark_begin() actions.left() actions.mark_finish() end, mark_word = function() actions.mark_begin() actions.word() actions.mark_finish() end, mark_backword = function() actions.mark_begin() actions.backword() actions.mark_finish() end, mark_home = function() actions.mark_begin() actions.home() actions.mark_finish() end, mark_end = function() actions.mark_begin() actions.toend() actions.mark_finish() end, mark_all = function() mark.anchor = { x = 1, y = 1 } mark.active = true mark.continue = true mark.x = 1 mark.y = 1 mark.ey = #tLines mark.ex = #tLines[mark.ey] + 1 actions.dirty_all() end, setCursor = function() lastPos.x = x lastPos.y = y local screenX = x - scrollX local screenY = y - scrollY if screenX < 1 then scrollX = x - 1 actions.dirty_all() elseif screenX > w then scrollX = x - w actions.dirty_all() end if screenY < 1 then scrollY = y - 1 actions.dirty_all() elseif screenY > h - 1 then scrollY = y - (h - 1) actions.dirty_all() end end, top = function() actions.go_to(1, 1) end, bottom = function() y = #tLines x = #tLines[y] + 1 end, up = function() if y > 1 then x = math.min(x, #tLines[y - 1] + 1) y = y - 1 end end, down = function() if y < #tLines then x = math.min(x, #tLines[y + 1] + 1) y = y + 1 end end, tab = function() if mark.active then actions.delete() end actions.insertText(x, y, ' ') end, pageUp = function() actions.go_to(x, y - (h - 1)) end, pageDown = function() actions.go_to(x, y + (h - 1)) end, home = function() x = 1 end, toend = function() x = #tLines[y] + 1 end, left = function() if x > 1 then x = x - 1 elseif y > 1 then x = #tLines[y - 1] + 1 y = y - 1 else return false end return true end, right = function() if x < #tLines[y] + 1 then x = x + 1 elseif y < #tLines then x = 1 y = y + 1 end end, word = function() local nx = nextWord(tLines[y], x) if nx then x = nx elseif x < #tLines[y] + 1 then x = #tLines[y] + 1 elseif y < #tLines then x = 1 y = y + 1 end end, backword = function() if x == 1 then actions.left() else local sLine = tLines[y] local lx = 1 while true do local nx = nextWord(sLine, lx) if not nx or nx >= x then break end lx = nx end if not lx then x = 1 else x = lx end end end, insertText = function(sx, sy, text) x = sx y = sy local sLine = tLines[y] if not text:find('\n') then tLines[y] = sLine:sub(1, x - 1) .. text .. sLine:sub(x) actions.dirty_line(y) x = x + #text else local lines = split(text) local remainder = sLine:sub(x) tLines[y] = sLine:sub(1, x - 1) .. lines[1] actions.dirty_range(y, #tLines + #lines) x = x + #lines[1] for k = 2, #lines do y = y + 1 table.insert(tLines, y, lines[k]) x = #lines[k] + 1 end tLines[y] = tLines[y]:sub(1, x) .. remainder end if not undo.active then actions.addUndo( { action = 'deleteText', args = { sx, sy, x, y, text } }) end end, deleteText = function(sx, sy, ex, ey) x = sx y = sy if not undo.active then local text = actions.copyText(sx, sy, ex, ey) actions.addUndo( { action = 'insertText', args = { sx, sy, text } }) end local front = tLines[sy]:sub(1, sx - 1) local back = tLines[ey]:sub(ex, #tLines[ey]) for _ = 2, ey - sy + 1 do table.remove(tLines, y + 1) end tLines[y] = front .. back if sy ~= ey then actions.dirty_range(y) else actions.dirty() end end, copyText = function(csx, csy, cex, cey) local count = 0 local lines = { } for cy = csy, cey do local line = tLines[cy] if line then local cx = 1 local ex = #line if cy == csy then cx = csx end if cy == cey then ex = cex - 1 end local str = line:sub(cx, ex) count = count + #str table.insert(lines, str) end end return table.concat(lines, '\n'), count end, delete = function() if mark.active then actions.deleteText(mark.x, mark.y, mark.ex, mark.ey) else local nLimit = #tLines[y] + 1 if x < nLimit then actions.deleteText(x, y, x + 1, y) elseif y < #tLines then actions.deleteText(x, y, 1, y + 1) end end end, backspace = function() if mark.active then actions.delete() elseif actions.left() then actions.delete() end end, enter = function() local sLine = tLines[y] local _,spaces = sLine:find("^[ ]+") if not spaces then spaces = 0 end spaces = math.min(spaces, x - 1) if mark.active then actions.delete() end actions.insertText(x, y, '\n' .. string.rep(' ', spaces)) end, char = function(ch) if mark.active then actions.delete() end actions.insertText(x, y, ch) end, copy_marked = function() local text = actions.copyText(mark.x, mark.y, mark.ex, mark.ey) os.queueEvent('clipboard_copy', text) setStatus('shift-^v to paste') end, cut = function() if mark.active then actions.copy_marked() actions.delete() end end, copy = function() if mark.active then actions.copy_marked() mark.continue = true end end, paste = function(text) if mark.active then actions.delete() end if text then actions.insertText(x, y, text) setStatus('%d chars added', #text) else setStatus('Clipboard empty') end end, go_to = function(cx, cy) y = math.min(math.max(cy, 1), #tLines) x = math.min(math.max(cx, 1), #tLines[y] + 1) end, scroll_up = function() if scrollY > 0 then scrollY = scrollY - 1 actions.dirty_all() end mark.continue = mark.active end, scroll_down = function() local nMaxScroll = #tLines - (h-1) if scrollY < nMaxScroll then scrollY = scrollY + 1 actions.dirty_all() end mark.continue = mark.active end, } actions = __actions load(sPath) term.setCursorBlink(true) redraw() while bRunning do local sEvent, param, param2, param3 = os.pullEventRaw() local action if sEvent == 'terminate' then action = 'exit' elseif sEvent == 'multishell_focus' then -- opus only event input:reset() elseif sEvent == "mouse_click" or sEvent == 'mouse_drag' or sEvent == 'mouse_up' or sEvent == 'mouse_down' then local ie = input:translate(sEvent, param, param2, param3) if param3 < h or sEvent == 'mouse_drag' then if ie.code then action = keyMapping[ie.code] param = param2 + scrollX param2 = param3 + scrollY end end else local ie = input:translate(sEvent, param, param2) if ie then if ie.ch and #ie.ch == 1 then action = keyMapping.char param = ie.ch else action = keyMapping[ie.code] end end end if action then if not actions[action] then error('Invaid action: ' .. action) end local wasMarking = mark.continue mark.continue = false actions[action](param, param2) if action ~= 'menu' then lastAction = action end if x ~= lastPos.x or y ~= lastPos.y then actions.setCursor() end if not mark.continue and wasMarking then actions.unmark() end redraw() elseif sEvent == "term_resize" then w,h = term.getSize() actions.setCursor(x, y) actions.dirty_all() redraw() end end -- Cleanup term.setBackgroundColor(colors.black) term.setTextColor(colors.white) term.clear() term.setCursorBlink(false) term.setCursorPos(1, 1)
local _ local LAM = LibAddonMenu2 local function Init(mId, moduleName) local panelData = Init_ModulePanel(moduleName, "Writ Settings") LAM:RegisterAddonPanel("BETTERUI_"..mId, panelData) LAM:RegisterOptionControls("BETTERUI_"..mId, optionsTable) end function BETTERUI.Writs.InitModule(m_options) return m_options end local function OnCraftStation(eventCode, craftId, sameStation) if eventCode ~= 0 then -- 0 is an invalid code BETTERUI.Writs.Show(tonumber(craftId)) end end local function OnCloseCraftStation(eventCode) BETTERUI.Writs.Hide() end local function OnCraftItem(eventCode, craftId) if eventCode ~= 0 then -- 0 is an invalid code BETTERUI.Writs.Show(tonumber(craftId)) end end function BETTERUI.Writs.Setup() local tlw = BETTERUI.WindowManager:CreateTopLevelWindow("BETTERUI_TLW") local BETTERUI_WP = BETTERUI.WindowManager:CreateControlFromVirtual("BETTERUI_WritsPanel",tlw,"BETTERUI_WritsPanel") EVENT_MANAGER:RegisterForEvent(BETTERUI.name, EVENT_CRAFTING_STATION_INTERACT, OnCraftStation) EVENT_MANAGER:RegisterForEvent(BETTERUI.name, EVENT_END_CRAFTING_STATION_INTERACT, OnCloseCraftStation) EVENT_MANAGER:RegisterForEvent(BETTERUI.name, EVENT_CRAFT_COMPLETED, OnCraftItem) BETTERUI_WP:SetHidden(true) end
local K, C, L = unpack(select(2, ...)) if C["Minimap"].Enable ~= true then return end local _G = _G local CreateFrame = _G.CreateFrame local EasyMenu = _G.EasyMenu local HideUIPanel = _G.HideUIPanel local IsInGuild = _G.IsInGuild local PlaySound = _G.PlaySound local ShowUIPanel = _G.ShowUIPanel -- Create the minimap micro menu local menuFrame = CreateFrame("Frame", "MinimapRightClickMenu", UIParent) local menuList = { {text = _G.CHARACTER_BUTTON, func = function() ToggleCharacter("PaperDollFrame") end}, {text = _G.SPELLBOOK_ABILITIES_BUTTON, func = function() if not _G.SpellBookFrame:IsShown() then ShowUIPanel(_G.SpellBookFrame) else HideUIPanel(_G.SpellBookFrame) end end}, {text = _G.TALENTS_BUTTON, func = function() if not _G.TalentFrame then _G.TalentFrame_LoadUI() end if not TalentFrame:IsShown() then ShowUIPanel(TalentFrame) else HideUIPanel(TalentFrame) end end}, {text = _G.CHAT_CHANNELS, func = _G.ToggleChannelFrame}, {text = _G.TIMEMANAGER_TITLE, func = function() ToggleFrame(_G.TimeManagerFrame) end}, {text = _G.SOCIAL_LABEL, func = ToggleFriendsFrame}, {text = _G.GUILD, func = function() if IsInGuild() then ToggleFriendsFrame(3) else ToggleGuildFrame() end end}, {text = _G.MAINMENU_BUTTON, func = function() if not _G.GameMenuFrame:IsShown() then if _G.VideoOptionsFrame:IsShown() then _G.VideoOptionsFrameCancel:Click(); elseif _G.AudioOptionsFrame:IsShown() then _G.AudioOptionsFrameCancel:Click(); elseif _G.InterfaceOptionsFrame:IsShown() then _G.InterfaceOptionsFrameCancel:Click(); end CloseMenus(); CloseAllWindows() PlaySound(850) --IG_MAINMENU_OPEN ShowUIPanel(_G.GameMenuFrame); else PlaySound(854) --IG_MAINMENU_QUIT HideUIPanel(_G.GameMenuFrame); MainMenuMicroButton_SetNormal(); end end}, {text = _G.HELP_BUTTON, func = ToggleHelpFrame} } Minimap:SetScript("OnMouseUp", function(self, btn) menuFrame:Hide() local position = self:GetPoint() if btn == "MiddleButton" or (btn == "RightButton") then if InCombatLockdown() then _G.UIErrorsFrame:AddMessage(K.InfoColor.._G.ERR_NOT_IN_COMBAT) return end if position:match("LEFT") then EasyMenu(menuList, menuFrame, "cursor") else EasyMenu(menuList, menuFrame, "cursor", -160, 0) end else Minimap_OnClick(self) end end)
do function getModule(gui) -- TODO: Vertical resizing? local LineLayout = gui.internal.class() function LineLayout:init(parent, params) self.lines = {} self.parent = parent self.defaultParameters = { ["padding"] = 5, ["spacing"] = 5, } for k, v in pairs(params) do self.defaultParameters[k] = v end end function LineLayout:setParam(parameter, value) self.defaultParameters[parameter] = value end function LineLayout:newLine(params) self.lines[#self.lines+1] = {parameters = params or {}, widgets = {}} end function LineLayout:addWidget(widget, params) if #self.lines == 0 then error("LineLayout needs at least one line") end table.insert(self.lines[#self.lines].widgets, {object = widget, parameters = params or {}}) end function LineLayout:removeWidget(widget, removeEmptyLine) removeEmptyLine = removeEmptyLine ~= nil and removeEmptyLine or true for lineInd = #self.lines, 1, -1 do for widInd = #self.lines[lineInd].widgets, 1, -1 do if widget == self.lines[lineInd].widgets[widInd].object then table.remove(self.lines[lineInd].widgets, widInd) if #self.lines[lineInd].widgets == 0 and removeEmptyLine then table.remove(self.lines, lineInd) end return true end end end return false -- not found end function LineLayout:arrange() local parameterStack = gui.internal.Stack() parameterStack:push(self.defaultParameters) -- helper function so parameter won't just be replaced, but are pushed incrementally parameterStack.pushParams = function(self, params) self:push(gui.internal.tableDeepCopy(self:top())) gui.internal.addTableKeys(self:top(), params) end parameterStack.getParam = function(self, name) local matchLength, ret = 0, nil for k, v in pairs(self:top()) do local keyLen = k:len() if keyLen > matchLength and name:sub(1, keyLen) == k then ret = v matchLength = keyLen end end if ret == nil then error("Parameter " .. name .. " could not be evaluated.") end return ret end local cursorY = parameterStack:getParam("padding-top") for line = 1, #self.lines do parameterStack:pushParams(self.lines[line].parameters) local cursorX = parameterStack:getParam("padding-left") local totalWidth = self.parent.width local height = 0 local width = parameterStack:getParam("padding-left") + parameterStack:getParam("padding-right") local sizeUp = {} local sizeUpCount = 0 for index, widget in ipairs(self.lines[line].widgets) do if widget.object.visible then parameterStack:pushParams(widget.parameters) height = math.max(height, widget.object.height) sizeUp[index] = 0 -- because with numbers I don't need type conversion later if widget.object.minWidth or widget.object.maxWidth then width = width + (widget.object.minWidth or 0) sizeUp[index] = 1 sizeUpCount = sizeUpCount + 1 widget.object.width = widget.object.minWidth or 0 else width = width + widget.object.width end if index < #self.lines[line].widgets then width = width + parameterStack:getParam("spacing-horizontal") end parameterStack:pop() end end for index, widget in ipairs(self.lines[line].widgets) do if widget.object.visible then parameterStack:pushParams(widget.parameters) -- math.floor because thin lines don't like being drawn between pixels! (button-outlines would flicker) widget.object.position = {math.floor(cursorX), math.floor(cursorY + height/2 - widget.object.height/2)} widget.object:setParam("width", math.floor(widget.object.width + sizeUp[index] * math.max(0, (totalWidth - width)) / math.max(1, sizeUpCount))) cursorX = cursorX + widget.object.width + parameterStack:getParam("spacing-horizontal") parameterStack:pop() end end cursorY = cursorY + height + parameterStack:getParam("spacing-vertical") parameterStack:pop() end end gui.layouts = {} gui.layouts.LineLayout = LineLayout end return getModule end
#!/usr/bin/env luajit local file = io.open(..., "rb") -- This script handles the outer framing and encryption of a savefile. local isHeader = true local function hex(a) io.write(string.format(" %02x", a)) end while true do local entryHead = file:read(5) if not entryHead then return end if isHeader then print("header entry") else print("data entry") end io.write(" valid:") local valid = entryHead:byte(5) == 1 hex(entryHead:byte(5)) print() -- do we really need to check all 32-bits for an examination tool? yes? *fine* local entryLen = entryHead:byte(1) + (entryHead:byte(2) * 0x100) + (entryHead:byte(3) * 0x10000) + (entryHead:byte(4) * 0x1000000) local entryData = "" io.write(" raw:") for i = 1, entryLen do local bt = file:read(1) entryData = entryData .. bt hex(bt:byte()) end print() if valid and not isHeader then -- data entry, try to decode local key = 0x53 io.write(" key: ") for i = 1, entryData:byte(9) do io.write(string.char(bit.bxor(entryData:byte(9 + i), key))) key = (key + 9) % 256 end print() local dataBase = 14 + entryData:byte(9) io.write(" dat:") local other = "" local key = 0x3A for i = dataBase, #entryData do local val = bit.bxor(entryData:byte(i), key) if val >= 32 and val ~= 127 then other = other .. string.char(val) .. " " else other = other .. ". " end hex(val) key = (key + 9) % 256 end print() print(" dac: " .. other) end isHeader = false print() end
local Game = require('main.game') local migrators = { { version = 1, func = function(games) local gamesToRemove = { } for i, game in ipairs(games) do local remove = false if type(game.title) ~= 'string' or game.title:trim() == '' then remove = true end if type(game.path) ~= 'string' or game.path:trim() == '' then remove = true end if type(game.platform) ~= 'number' or game.platform < 0 or game.platform > 5 then remove = true end if remove then table.insert(gamesToRemove, game) else local _exp_0 = game.platform if 0 == _exp_0 then game.platformID = ENUMS.PLATFORM_IDS.STEAM elseif 1 == _exp_0 then game.platformID = ENUMS.PLATFORM_IDS.STEAM elseif 2 == _exp_0 then game.platformID = ENUMS.PLATFORM_IDS.GOG_GALAXY elseif 3 == _exp_0 then game.platformID = ENUMS.PLATFORM_IDS.SHORTCUTS elseif 4 == _exp_0 then game.platformID = ENUMS.PLATFORM_IDS.SHORTCUTS elseif 5 == _exp_0 then game.platformID = ENUMS.PLATFORM_IDS.BATTLENET end game.platformOverride = game.platformoverride game.platformoverride = nil game.hoursPlayed = game.hourstotal game.hourstotal = nil game.lastPlayed = tonumber(game.lastplayed) game.lastplayed = nil game.uninstalled = game.notinstalled game.notinstalled = nil game.processOverride = game.processoverride game.processoverride = nil if game.tags ~= nil then local tags = { } for key, tag in pairs(game.tags) do table.insert(tags, tag) end game.tags = tags end game.banner = nil game.bannererror = nil game.bannerurl = nil game.error = nil game.hourslast2weeks = nil game.ignoresbangs = nil game.invalidpatherror = nil end end for _index_0 = 1, #gamesToRemove do local game = gamesToRemove[_index_0] local i = table.find(games, game) table.remove(games, i) end end } } local Library do local _class_0 local _base_0 = { createBackup = function(self, path) local games = io.readJSON(path) local date = os.date('*t') games.backup = { year = date.year, month = date.month, day = date.day } local latestBackupPath = self.backupFilePattern:format(1) if io.fileExists(latestBackupPath) then local latestBackup = io.readJSON(latestBackupPath) if latestBackup.backup.year == date.year and latestBackup.backup.month == date.month and latestBackup.backup.day == date.day then return end for i = self.numBackups, 1, -1 do local backupPath = self.backupFilePattern:format(i) if io.fileExists(backupPath) then if i == self.numBackups then os.remove(io.absolutePath(backupPath)) else backupPath = io.absolutePath(backupPath) local target = io.absolutePath(self.backupFilePattern:format(i + 1)) os.rename(backupPath, target) end end end end return io.writeJSON(latestBackupPath, games) end, load = function(self) local paths do local _accum_0 = { } local _len_0 = 1 for i = 1, self.numBackups do _accum_0[_len_0] = self.backupFilePattern:format(i) _len_0 = _len_0 + 1 end paths = _accum_0 end table.insert(paths, 1, self.path) for _index_0 = 1, #paths do local path = paths[_index_0] if io.fileExists(path) then self:createBackup(path) local games = io.readJSON(path) local version = games.version or 0 if version > 0 then games = games.games end if type(games) ~= 'table' then games = { } end local migrated = self:migrate(games, version) do local _accum_0 = { } local _len_0 = 1 for _index_1 = 1, #games do local args = games[_index_1] _accum_0[_len_0] = Game(args) _len_0 = _len_0 + 1 end games = _accum_0 end if migrated then self:save(games) end return games end end return { } end, save = function(self, games) if games == nil then games = self.gamesSortedByGameID end return io.writeJSON(self.path, { version = self.version, games = games }) end, migrate = function(self, games, version) assert(type(version) == 'number' and version % 1 == 0, 'Expected the games version number to be an integer.') assert(version <= self.version, ('Unsupported games version. Expected version %d or earlier.'):format(self.version)) if version == self.version then return false end for _index_0 = 1, #migrators do local migrator = migrators[_index_0] if version < migrator.version then log("Migrating games.json from version " .. tostring(version) .. " to " .. tostring(migrator.version) .. ".") migrator.func(games) end end return true end, add = function(self, games) if games == nil then return false end assert(type(games) == 'table', 'shared.library.Library.add') if #games == 0 then return false end for _index_0 = 1, #games do local game = games[_index_0] assert(game.__class == Game, 'shared.library.Library.add') for i, oldGame in ipairs(self.oldGames) do if game:getPlatformID() == oldGame:getPlatformID() and game:getTitle() == oldGame:getTitle() then game:merge(oldGame) table.remove(self.oldGames, i) break end end game:setGameID(self.currentGameID) self.currentGameID = self.currentGameID + 1 table.insert(self.games, game) end return true end, finalize = function(self, platformEnabledStatus) assert(type(platformEnabledStatus) == 'table', 'shared.library.Library.finalize') self.platformEnabledStatus = platformEnabledStatus local _list_0 = self.oldGames for _index_0 = 1, #_list_0 do local game = _list_0[_index_0] game:setInstalled(false) game:setGameID(self.currentGameID) self.currentGameID = self.currentGameID + 1 table.insert(self.games, game) end self.oldGames = nil self.gamesSortedByGameID = table.shallowCopy(self.games) return table.sort(self.gamesSortedByGameID, function(a, b) return a.gameID < b.gameID end) end, update = function(self, updatedGame) local gameID = updatedGame:getGameID() local _list_0 = self.games for _index_0 = 1, #_list_0 do local game = _list_0[_index_0] if game:getGameID() == gameID then game:merge(updatedGame) return true end end return false end, sort = function(self, sorting, games) if games == nil then games = self.games end assert(type(sorting) == 'number' and sorting % 1 == 0, 'shared.library.Library.sort') local comp = nil local _exp_0 = sorting if ENUMS.SORTING_TYPES.ALPHABETICALLY == _exp_0 then comp = function(a, b) return a:getTitle():lower() < b:getTitle():lower() end elseif ENUMS.SORTING_TYPES.LAST_PLAYED == _exp_0 then comp = function(a, b) return a:getLastPlayed() > b:getLastPlayed() end elseif ENUMS.SORTING_TYPES.HOURS_PLAYED == _exp_0 then comp = function(a, b) return a:getHoursPlayed() > b:getHoursPlayed() end else assert(nil, 'Unknown sorting type.') end assert(type(comp) == 'function', 'shared.library.Library.sort') table.sort(games, comp) if games ~= self.games then return table.sort(self.games, comp) end end, fuzzySearch = function(self, str, pattern) assert(type(str) == 'string', 'shared.library.Library.fuzzySearch') assert(type(pattern) == 'string', 'shared.library.Library.fuzzySearch') local score = 0 if str == '' or pattern == '' then return score end local bonusPerfectMatch = 50 local bonusFirstMatch = 25 local bonusMatch = 10 local bonusMatchDistance = 10 local bonusConsecutiveMatches = 10 local bonusFirstWordMatch = 20 local penaltyNotMatch = -5 pattern = pattern:lower() str = str:lower() if str == pattern then score = score + bonusPerfectMatch end local patternChars = pattern:splitIntoChars() local strWords = str:splitIntoWords() local matchString matchString = function(_str, _patternChars) local matchIndex = _str:find(_patternChars[1]) if matchIndex ~= nil then score = score + (bonusFirstMatch / matchIndex) local matchIndices = { } table.insert(matchIndices, matchIndex) local consecutiveMatches = 0 for i, char in ipairs(_patternChars) do if i > 1 and matchIndices[i - 1] ~= nil then matchIndex = _str:find(char, matchIndices[i - 1] + 1) if matchIndex ~= nil then table.insert(matchIndices, matchIndex) score = score + bonusMatch local distance = matchIndex - matchIndices[i - 1] if distance == 1 then consecutiveMatches = consecutiveMatches + 1 else score = score + (consecutiveMatches * bonusConsecutiveMatches) consecutiveMatches = 0 end score = score + (bonusMatchDistance / distance) else score = score + (consecutiveMatches * bonusConsecutiveMatches) score = score + penaltyNotMatch consecutiveMatches = 0 end end end if consecutiveMatches > 0 then score = score + (consecutiveMatches * bonusConsecutiveMatches) end return true end return false end if not (matchString(str, patternChars)) then local min = 1 while not matchString(str, table.slice(patternChars, min)) and min < #patternChars do min = min + 1 end end if #strWords > 0 then local j = 1 for i, char in ipairs(patternChars) do if j <= #strWords and strWords[j]:find(char) == 1 then score = score + bonusFirstWordMatch j = j + 1 end end for _index_0 = 1, #strWords do local word = strWords[_index_0] matchString(word, patternChars) end end if score >= 0 then return score else return 0 end end, filter = function(self, filter, args) assert(type(filter) == 'number' and filter % 1 == 0, 'shared.library.Library.filter') local gamesToProcess = nil if args ~= nil and args.stack == true then assert(type(args.games) == 'table', 'shared.library.Library.filter') gamesToProcess = args.games args.games = nil table.insert(self.filterStack, { filter = filter, args = args }) else gamesToProcess = { } local _list_0 = self.games for _index_0 = 1, #_list_0 do local _continue_0 = false repeat local game = _list_0[_index_0] if not (self.platformEnabledStatus[game:getPlatformID()] == true) then _continue_0 = true break end if not game:isVisible() then if not (filter == ENUMS.FILTER_TYPES.HIDDEN) then _continue_0 = true break end elseif not game:isInstalled() then if not (filter == ENUMS.FILTER_TYPES.UNINSTALLED) then _continue_0 = true break end end table.insert(gamesToProcess, game) _continue_0 = true until true if not _continue_0 then break end end if filter == ENUMS.FILTER_TYPES.NONE then self.filterStack = { } else self.filterStack = { { filter = filter, args = args } } end end local games = nil local _exp_0 = filter if ENUMS.FILTER_TYPES.NONE == _exp_0 then games = gamesToProcess self.filterStack = { } elseif ENUMS.FILTER_TYPES.TITLE == _exp_0 then assert(type(args) == 'table', 'shared.library.Library.filter') assert(type(args.input) == 'string', 'shared.library.Library.filter') if args.input == '' then games = gamesToProcess else local temp = { } for _index_0 = 1, #gamesToProcess do local game = gamesToProcess[_index_0] table.insert(temp, { game = game, score = self:fuzzySearch(game:getTitle(), args.input) }) end table.sort(temp, function(a, b) return a.score > b.score end) do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #temp do local entry = temp[_index_0] _accum_0[_len_0] = entry.game _len_0 = _len_0 + 1 end games = _accum_0 end end elseif ENUMS.FILTER_TYPES.PLATFORM == _exp_0 then assert(type(args) == 'table', 'shared.library.Library.filter') assert(type(args.platformID) == 'number' and args.platformID % 1 == 0, 'shared.library.Library.filter') local platformID = args.platformID local platformOverride = args.platformOverride if platformOverride ~= nil then do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #gamesToProcess do local game = gamesToProcess[_index_0] if game:getPlatformID() == platformID and game:getPlatformOverride() == platformOverride then _accum_0[_len_0] = game _len_0 = _len_0 + 1 end end games = _accum_0 end else do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #gamesToProcess do local game = gamesToProcess[_index_0] if game:getPlatformID() == platformID and game:getPlatformOverride() == nil then _accum_0[_len_0] = game _len_0 = _len_0 + 1 end end games = _accum_0 end end elseif ENUMS.FILTER_TYPES.TAG == _exp_0 then assert(type(args) == 'table', 'shared.library.Library.filter') assert(type(args.tag) == 'string', 'shared.library.Library.filter') local tag = args.tag do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #gamesToProcess do local game = gamesToProcess[_index_0] if game:hasTag(tag) == true then _accum_0[_len_0] = game _len_0 = _len_0 + 1 end end games = _accum_0 end elseif ENUMS.FILTER_TYPES.HIDDEN == _exp_0 then assert(type(args) == 'table', 'shared.library.Library.filter') assert(type(args.state) == 'boolean', 'shared.library.Library.filter') local state = args.state do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #gamesToProcess do local game = gamesToProcess[_index_0] if game:isVisible() ~= state then _accum_0[_len_0] = game _len_0 = _len_0 + 1 end end games = _accum_0 end elseif ENUMS.FILTER_TYPES.UNINSTALLED == _exp_0 then assert(type(args) == 'table', 'shared.library.Library.filter') assert(type(args.state) == 'boolean', 'shared.library.Library.filter') local state = args.state do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #gamesToProcess do local game = gamesToProcess[_index_0] if game:isInstalled() ~= state then _accum_0[_len_0] = game _len_0 = _len_0 + 1 end end games = _accum_0 end elseif ENUMS.FILTER_TYPES.NO_TAGS == _exp_0 then assert(type(args) == 'table', 'shared.library.Library.filter') assert(type(args.state) == 'boolean', 'shared.library.Library.filter') if args.state then do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #gamesToProcess do local game = gamesToProcess[_index_0] if #game:getTags() == 0 and #game:getPlatformTags() == 0 then _accum_0[_len_0] = game _len_0 = _len_0 + 1 end end games = _accum_0 end else do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #gamesToProcess do local game = gamesToProcess[_index_0] if #game:getTags() > 0 or #game:getPlatformTags() > 0 then _accum_0[_len_0] = game _len_0 = _len_0 + 1 end end games = _accum_0 end end elseif ENUMS.FILTER_TYPES.RANDOM_GAME == _exp_0 then assert(type(args) == 'table', 'shared.library.Library.filter') assert(type(args.state) == 'boolean', 'shared.library.Library.filter') games = { gamesToProcess[math.random(1, #gamesToProcess)] } elseif ENUMS.FILTER_TYPES.NEVER_PLAYED == _exp_0 then assert(type(args) == 'table', 'shared.library.Library.filter') assert(type(args.state) == 'boolean', 'shared.library.Library.filter') do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #gamesToProcess do local game = gamesToProcess[_index_0] if game:getHoursPlayed() == 0 then _accum_0[_len_0] = game _len_0 = _len_0 + 1 end end games = _accum_0 end elseif ENUMS.FILTER_TYPES.HAS_NOTES == _exp_0 then assert(type(args) == 'table', 'shared.library.Library.filter') assert(type(args.state) == 'boolean', 'shared.library.Library.filter') do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #gamesToProcess do local game = gamesToProcess[_index_0] if game:getNotes() ~= nil then _accum_0[_len_0] = game _len_0 = _len_0 + 1 end end games = _accum_0 end else assert(nil, 'shared.library.Library.filter') end assert(type(games) == 'table', 'shared.library.Library.filter') self.processedGames = games end, getFilterStack = function(self) return self.filterStack end, get = function(self) if self.processedGames == nil then self:filter(ENUMS.FILTER_TYPES.NONE, nil) end local games = self.processedGames self.processedGames = nil return games end, replace = function(self, old, new) assert(old ~= nil and old.__class == Game, 'shared.library.Library.replace') assert(new ~= nil and new.__class == Game, 'shared.library.Library.replace') return table.replace(self.games, old, new) end, remove = function(self, game) local i = table.find(self.games, game) table.remove(self.games, i) return self:save() end } _base_0.__index = _base_0 _class_0 = setmetatable({ __init = function(self, settings, regularMode) if regularMode == nil then regularMode = true end assert(type(settings) == 'table', 'shared.library.Library') assert(type(regularMode) == 'boolean', 'shared.library.Library') self.version = 1 self.path = 'games.json' if regularMode then self.numBackups = settings:getNumberOfBackups() self.backupFilePattern = 'games_backup_%d.json' self.games = { } self.oldGames = self:load() self.currentGameID = 1 else local games = io.readJSON(self.path) do local _accum_0 = { } local _len_0 = 1 local _list_0 = games.games for _index_0 = 1, #_list_0 do local args = _list_0[_index_0] _accum_0[_len_0] = Game(args) _len_0 = _len_0 + 1 end self.games = _accum_0 end self.oldGames = { } end self.filterStack = { } self.processedGames = nil self.gamesSortedByGameID = nil end, __base = _base_0, __name = "Library" }, { __index = _base_0, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 Library = _class_0 end return Library
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf/protobuf" local DRAGONGROUPRECORDS2C_PB = require("DragonGroupRecordS2C_pb") local DRAGONGROUPROLELISTS2C_PB = require("DragonGroupRoleListS2C_pb") module('DragonGroupDB_pb') DRAGONGROUPDB = protobuf.Descriptor(); local DRAGONGROUPDB_RECORD_FIELD = protobuf.FieldDescriptor(); local DRAGONGROUPDB_ROLELIST_FIELD = protobuf.FieldDescriptor(); DRAGONGROUPDB_RECORD_FIELD.name = "record" DRAGONGROUPDB_RECORD_FIELD.full_name = ".KKSG.DragonGroupDB.record" DRAGONGROUPDB_RECORD_FIELD.number = 1 DRAGONGROUPDB_RECORD_FIELD.index = 0 DRAGONGROUPDB_RECORD_FIELD.label = 1 DRAGONGROUPDB_RECORD_FIELD.has_default_value = false DRAGONGROUPDB_RECORD_FIELD.default_value = nil DRAGONGROUPDB_RECORD_FIELD.message_type = DRAGONGROUPRECORDS2C_PB.DRAGONGROUPRECORDS2C DRAGONGROUPDB_RECORD_FIELD.type = 11 DRAGONGROUPDB_RECORD_FIELD.cpp_type = 10 DRAGONGROUPDB_ROLELIST_FIELD.name = "rolelist" DRAGONGROUPDB_ROLELIST_FIELD.full_name = ".KKSG.DragonGroupDB.rolelist" DRAGONGROUPDB_ROLELIST_FIELD.number = 2 DRAGONGROUPDB_ROLELIST_FIELD.index = 1 DRAGONGROUPDB_ROLELIST_FIELD.label = 1 DRAGONGROUPDB_ROLELIST_FIELD.has_default_value = false DRAGONGROUPDB_ROLELIST_FIELD.default_value = nil DRAGONGROUPDB_ROLELIST_FIELD.message_type = DRAGONGROUPROLELISTS2C_PB.DRAGONGROUPROLELISTS2C DRAGONGROUPDB_ROLELIST_FIELD.type = 11 DRAGONGROUPDB_ROLELIST_FIELD.cpp_type = 10 DRAGONGROUPDB.name = "DragonGroupDB" DRAGONGROUPDB.full_name = ".KKSG.DragonGroupDB" DRAGONGROUPDB.nested_types = {} DRAGONGROUPDB.enum_types = {} DRAGONGROUPDB.fields = {DRAGONGROUPDB_RECORD_FIELD, DRAGONGROUPDB_ROLELIST_FIELD} DRAGONGROUPDB.is_extendable = false DRAGONGROUPDB.extensions = {} DragonGroupDB = protobuf.Message(DRAGONGROUPDB)
-- https://modit.store -- ModFreakz QBCore = nil TriggerEvent("QBCore:GetObject", function(obj) QBCore = obj end) QBCore.Commands.Add("create:vehshop", "Create a Veh Shop",{}, false, function(source) TriggerClientEvent("VehicleShops:CreateNew",source) end, "admin") --[[ RegisterCommand("create:vehshop", function(source,args) TriggerClientEvent("VehicleShops:CreateNew",source) end,false) ]]
require 'torch' local ImageLoaderAsync = torch.class('ImageLoaderAsync') local threads = require 'threads' local ImageLoader = {} local ImageLoader_mt = { __index = ImageLoader } ---- Asynchronous image loader. local result = {} local H, W function ImageLoaderAsync:__init(dir, batchSize, options) if not batchSize then error('Predetermined batch size is required for asynchronous loader.') end options = options or {} local n = options.n or 1 -- upvalues H,W = options.H, options.W self.batchSize = batchSize self._type = 'torch.FloatTensor' -- initialize thread and its image loader self.threads = threads.Threads(n, function() imageLoader = ImageLoader:new(dir) if H ~= nil and W ~= nil then imageLoader:setWidthAndHeight(W,H) end end) -- get size self.threads:addjob( function() return imageLoader:size() end, function(size) result[1] = size end) self.threads:dojob() self._size = result[1] result[1] = nil -- add job for i=1,n do self.threads:addjob(self.__getBatchFromThread, self.__pushResult, self.batchSize) end end function ImageLoaderAsync:size() return self._size end function ImageLoaderAsync:type(type) if not type then return self._type else assert(torch.Tensor():type(type), 'Invalid type ' .. type .. '?') self._type = type end return self end function ImageLoaderAsync.__getBatchFromThread(batchSize) return imageLoader:nextBatch(batchSize) end function ImageLoaderAsync.__pushResult(batch) result[1] = batch end function ImageLoaderAsync:nextBatch() self.threads:addjob(self.__getBatchFromThread, self.__pushResult, self.batchSize) self.threads:dojob() local batch = result[1] result[1] = nil return batch:type(self._type) end ---- Implementation of the actual image loader. function ImageLoader:new(dir) require 'torch' require 'paths' require 'image' local imageLoader = {} setmetatable(imageLoader, ImageLoader_mt) local files = paths.dir(dir) local i=1 while i <= #files do if not string.find(files[i], 'jpg$') and not string.find(files[i], 'png$') and not string.find(files[i], 'ppm$')then table.remove(files, i) else i = i +1 end end imageLoader.dir = dir imageLoader.files = files imageLoader:rebatch() return imageLoader end function ImageLoader:size() return #self.files end function ImageLoader:rebatch() self.perm = torch.randperm(self:size()) self.idx = 1 end function ImageLoader:nextBatch(batchSize) local img = self:next() local batch = torch.FloatTensor(batchSize, 3, img:size(2), img:size(3)) batch[1] = img for i=2,batchSize do batch[i] = self:next() end return batch end function ImageLoader:next() -- load image local img = nil local name local numErr = 0 while true do if self.idx > self:size() then self:rebatch() end local i = self.perm[self.idx] self.idx = self.idx + 1 name = self.files[i] local loc = paths.concat(self.dir, name) local status,err = pcall(function() img = image.load(loc,3,'float') end) if status then if self.verbose then print('Loaded ' .. self.files[i]) end break else io.stderr:write('WARNING: Failed to load ' .. loc .. ' due to error: ' .. err .. '\n') end end -- preprocess local H, W = img:size(2), img:size(3) if self.W and self.H then img = image.scale(img, self.W, self.H) elseif self.len then img = image.scale(img, self.len) elseif self.max_len then if H > self.max_len or W > self.max_len then img = image.scale(img, self.max_len) end end H, W = img:size(2), img:size(3) if self.div then local Hc = math.floor(H / self.div) * self.div local Wc = math.floor(W / self.div) * self.div img = self:_randomCrop(img, Hc, Wc) end if self.bnw then img = image.rgb2yuv(img) img[2]:zero() img[3]:zero() img = image.yuv2rgb(img) end collectgarbage() return img, name, numErr end ---- Optional preprocessing function ImageLoader:setVerbose(verbose) verbose = verbose or true self.verbose = verbose end function ImageLoader:setWidthAndHeight(W,H) self.H = H self.W = W end function ImageLoader:setFitToHeightOrWidth(len) assert(len ~= nil) self.len = len self.max_len = nil end function ImageLoader:setMaximumSize(max_len) assert(max_len ~= nil) self.max_len = max_len self.len = nil end function ImageLoader:setDivisibleBy(div) assert(div ~= nil) self.div = div end function ImageLoader:_randomCrop(img, oheight, owidth) assert(img:dim()==3) local H,W = img:size(2), img:size(3) assert(oheight <= H) assert(owidth <= W) local y = torch.floor(torch.uniform(0, H-oheight+1)) local x = torch.floor(torch.uniform(0, W-owidth+1)) local crop_img = image.crop(img, x,y, x+owidth, y+oheight) return crop_img end function ImageLoader:setBlackNWhite(bool) if bool then self.bnw = true else self.bnw = false end end
if myHero.charName ~= "Katarina" then return end local player = myHero local playerPos = myHero.pos local Q = { Range = 625} local W = { Range = 340 } local E = { Range = 725 } local R = { Range = 550} local DaggerObj = { } local DaggerCount = 0 local DaggerStart = 0 local DaggerEnd = 0 local RCasting = false local Posis = Vector(0,0,0) local WPos = Vector(0,0,0) local DaggerPosition = Vector(0,0,0) local damage = 0 local AD = myHero.totalDamage local AP = myHero.ap local bAD = myHero.bonusDamage local _EnemyHeroes local function LoadingMenu() NicktKat = MenuElement({type = MENU, id = "Katarina", name = "[Nicky]Katarina"}) --Combo NicktKat:MenuElement({id = "Combo", name = "Combo", type = MENU}) NicktKat.Combo:MenuElement({id = "CQ", name = "Use [Q]", value = true}) NicktKat.Combo:MenuElement({id = "CW", name = "Use [W]", value = true}) NicktKat.Combo:MenuElement({id = "CE", name = "Use [E]", value = true}) NicktKat.Combo:MenuElement({id = "EAA", name = "Use [E + AA]", value = true}) NicktKat.Combo:MenuElement({id = "CR", name = "Use [R]", value = true}) --Steal NicktKat:MenuElement({id = "Killsteal", name = "Killsteal", type = MENU}) NicktKat.Killsteal:MenuElement({id ="KillQ", name = "Use [Q]", value = true}) NicktKat.Killsteal:MenuElement({id ="KillE", name = "Use [E]", value = true}) --Draw NicktKat:MenuElement({id = "OnDawings", name = "Dawings", type = MENU}) NicktKat.OnDawings:MenuElement({id ="DQ", name = "Draw [Q]", value = true}) NicktKat.OnDawings:MenuElement({id ="DE", name = "Draw [E]", value = true}) NicktKat.OnDawings:MenuElement({id ="CC", name = "Draw [Dagger]", value = true}) end local function CalcMagicDmg(target, amount, from) local from = from or player local target = target local amount = amount or 0 local targetMR = target.magicResist * math.ceil(from.magicPenPercent) - from.magicPen local dmgMul = 100 / (100 + targetMR) if dmgMul < 0 then dmgMul = 2 - (100 / (100 - magicResist)) end amount = amount * dmgMul return math.floor(amount) end local function GetEnemyHeroes() if _EnemyHeroes then return _EnemyHeroes end for i = 1, Game.HeroCount() do local unit = Game.Hero(i) if unit.isEnemy then if _EnemyHeroes == nil then _EnemyHeroes = {} end table.insert(_EnemyHeroes, unit) end end return {} end local function IsValidTarget(unit) if unit and unit.isEnemy and unit.valid and unit.isTargetable and not unit.dead and not unit.isImmortal and not (GotBuff(unit, 'FioraW') == 1) and not (GotBuff(unit, 'XinZhaoRRangedImmunity') == 1 and unit.distance < 450) and unit.visible then return true else return false end end local function HasBuff(unit, buffname) for i = 0, unit.buffCount do local buff = unit:GetBuff(i) if buff and buff.name == buffname and buff.count > 0 then return true end end return false end local function EnemysInrange(pos, range) local Count = 0 for i = 1, Game.HeroCount() do local Hero = Game.Hero(i) if not Hero.dead and Hero.isEnemy and Hero.pos:DistanceTo(pos, Hero.pos) < range then Count = Count + 1 end end return Count end local function GetComboOrb() if _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_COMBO] then return "Combo" end end local function GetLaneOrb() if _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_LANECLEARS] then return "LaneClear" elseif _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_JUNGLECLEAR] then return "LaneClear" end end local function GetDistanceSqr(p1, p2) local p2 = p2 or player local dx = p1.x - p2.x local dz = (p1.z or p1.y) - (p2.z or p2.y) return dx * dx + dz * dz end local function GetDistance(p1, p2) local squaredDistance = GetDistanceSqr(p1, p2) return math.sqrt(squaredDistance) end local function OnCreatObj() for i = 1, Game.ParticleCount() do local obj = Game.Particle(i) if obj then if obj.name == "W_Indicator_Ally" then if not table.contains(DaggerObj, obj.pos) then DaggerObj[obj.networkID] = {['obj'] = obj, ['start'] = Game.Timer() + 1.1, ['end'] = Game.Timer() + 5.1 } DaggerCount = DaggerCount + 1 end end end end end local function GetBestDaggerPoint(position, target) local targetPos = Vector(target.x, target.y, target.z) local positionPos = Vector(position.x, position.y, position.z) if GetDistanceSqr(targetPos, positionPos) <= 340 * 340 then return position end return positionPos:Extended(targetPos, 150) end local function LogicDistance(position, target) local targetPos = Vector(target.x, target.y, target.z) local positionPos = Vector(position.x, position.y, position.z) if GetDistanceSqr(targetPos, positionPos) < 340 * 340 then return position end return positionPos:Extended(targetPos, 200) end local function LogicInstance(position, target) local targetPos = Vector(target.x, target.y, target.z) local positionPos = Vector(position.x, position.y, position.z) if GetDistanceSqr(targetPos, positionPos) < 340 * 340 then return position end return positionPos:Extended(targetPos, -50) end local function ELogic(position, target) local targetPos = Vector(target.x, target.y, target.z) local positionPos = Vector(position.x, position.y, position.z) if GetDistanceSqr(targetPos, positionPos) < 340 * 340 then return position end return positionPos:Extended(targetPos, 50) end local function GetBestDaggerPoint(position, target) local targetPos = Vector(target.x, target.y, target.z) local positionPos = Vector(position.x, position.y, position.z) if GetDistanceSqr(targetPos, positionPos) < 340 * 340 then return position end return positionPos:Extended(targetPos, -150) end local function CastE(target) if NicktKat.Combo.EAA:Value() then if (DaggerCount == 0 and Game.CanUseSpell(0) == 0 and Game.CanUseSpell(1) == 0) and RCasting == false and GetDistance(target) > Q.Range and GetDistance(target) <= E.Range then Control.CastSpell(HK_E, target) end end for _, Adaga in pairs(DaggerObj) do if Adaga then local DaggerPos = Vector(Adaga) + (Vector(target) - Vector(Adaga)):Normalized() * 150 local DaggerPosExte = Vector(Adaga) + (Vector(target) - Vector(Adaga)):Normalized() * 200 local DaggerIsRange = Vector(Adaga) + (Vector(target) - Vector(Adaga)):Normalized() * 50 local DaggerRange = Vector(Adaga) + (Vector(target) - Vector(Adaga)):Normalized() * -50 local DaggerPos2 = Vector(Adaga) + (Vector(target) - Vector(Adaga)):Normalized() * -150 if GetBestDaggerPoint(Adaga, target) and GetDistance(target, Adaga) <= 450 then Control.CastSpell(HK_E, DaggerPos) elseif LogicDistance(Adaga, target) and GetDistance(target, Adaga) <= 450 then Control.CastSpell(HK_E, DaggerPosExte) elseif LogicInstance(Adaga, target) and GetDistance(target, Adaga) <= 450 then Control.CastSpell(HK_E, DaggerRange) elseif ELogic(Adaga, target) and GetDistance(target, Adaga) <= 450 then Control.CastSpell(HK_E, DaggerIsRange) elseif LogicInstance(Adaga, target) and GetDistance(target, Adaga) <= 450 then Control.CastSpell(HK_E, DaggerPos2) end end end end local function CastW() if WPos then Control.CastSpell(HK_W) return player.Posis end end local function CastQ(target) if GetDistance(target) <= 625 then Control.CastSpell(HK_Q, target) end end local function IsCombo() if _G.SDK.TargetSelector:GetTarget(1000) == nil then return end local target = _G.SDK.TargetSelector:GetTarget(1000) if target ~= nil and not target.dead and target.visible and target.isTargetable and IsValidTarget(target) then if Game.CanUseSpell(0) == 0 and GetDistance(target) <= Q.Range and RCasting == false then CastQ(target) end if Game.CanUseSpell(2) == 0 and (GetDistance(target) <= E.Range+340) and RCasting == false then CastE(target) end if Game.CanUseSpell(1) == 0 and GetDistance(target) <= W.Range and RCasting == false then CastW(target) end local HealtEne = target.health + target.shieldAP + target.shieldAD local dmg = CalcMagicDmg(player, unit, (((player:GetSpellData(_R).level * 25) - ((player:GetSpellData(_R).level - 1) * 12.5)) + (bAD * 0.22) + (AP * 0.19))) if HealtEne < dmg then if Game.CanUseSpell(3) == 0 and GetDistance(target) <= W.Range and RCasting == false then Control.CastSpell(HK_R, target) end end end end local function OnCancelR() if RCasting == true and #EnemysInrange(player.pos, 550 + 10) == 0 then Control.Move(mousePos) end end local function OnLoading() LoadingMenu() end local function OnTick() OnCreatObj() OnCancelR() if HasBuff(player, "katarinarsound") then RCasting = true _G.SDK.Orbwalker:SetAttack(false) _G.SDK.Orbwalker:SetMovement(false) else RCasting = false _G.SDK.Orbwalker:SetAttack(true) _G.SDK.Orbwalker:SetMovement(true) end if GetComboOrb() == 'Combo' then IsCombo() end end local function OnDraw() if not player.dead and player.visible then if NicktKat.OnDawings.DQ:Value() then Draw.Circle(myHero.pos, Q.Range, 0, Draw.Color(255, 255, 0, 0)) end if NicktKat.OnDawings.DE:Value() then Draw.Circle(myHero.pos, E.Range, 0, Draw.Color(255, 255, 0, 0)) end if NicktKat.OnDawings.CC:Value() then if (DaggerCount > 0) then for _, Adaga in pairs(DaggerObj) do if Adaga then Draw.Circle(Vector(Adaga), 340, 0, Draw.Color(255, 255, 0, 0)) end end end end end end Callback.Add("Tick", function() OnTick() end) Callback.Add("Load", function() OnLoading() end) Callback.Add("Draw", function() OnDraw() end)
local client = {}; local DRPC = script:FindFirstAncestor("DRPC"); local ActivityCreator = require(DRPC.src.generators.activityCreator); local Data = require(DRPC.src.dataHandler); function client.new(Http, _debug) local self = setmetatable({ Http = Http, _debug = _debug }, { __index = client }); return self; end; function client:Close() self.Enabled = false; self.Http:Post({ updateType = "CLOSE"; }); end; function client:SetActivity() return self.Http:Post({ updateType = "SET_ACTIVITY"; activity = ActivityCreator:Get(); }); end; function client:Open() self.Enabled = true; return self:SetActivity(); end; -- Initiate with cb -> callback(success<bool>, response<string>); function client:login(cb) local enabled = Data:Get("Enabled"); local success, reply; if enabled or enabled == nil then success, reply = self:Open(); else success = false; end; spawn(function() while 1 do wait(2.6); -- Accuracy un-necessary. if self.Enabled then self:SetActivity(); end; if self.Terminated then break; end; end; end); if cb then cb(success, reply); end; self.plugin.Unloading:Connect(function() self:Close(); end); end; return client;
local FACTION = Clockwork.faction:New("Incognito"); local PLUGIN = PLUGIN; FACTION.useFullName = true; FACTION.whitelist = true; FACTION.material = "halfliferp/factions/citizen"; -- Called when a player is transferred to the faction. function FACTION:OnTransferred(player, faction, name) if (Schema:PlayerIsCombine(player)) then if (name) then local models = self.models[ string.lower( player:QueryCharacter("gender") ) ]; if (models) then player:SetCharacterData("model", models[ math.random(#models) ], true); Clockwork.player:SetName(player, name, true); end; else return false, "You need to specify a name as the third argument!"; end; end; end; -- Called when a player's scoreboard class is needed. function PLUGIN:GetPlayerScoreboardClass(player) local faction1 = player:GetFaction(); local clientfaction = Clockwork.Client:GetFaction(); if (faction1 == FACTION_INCOG) then if (Clockwork.Client:GetFaction() == FACTION_INCOG) then return "Incognito faction"; -- Edit this part for the name on the scoreboard. elseif (Clockwork.Client:IsAdmin()) then return "Hidden Faction(ADMIN/OOC View)"; else return false; end; end; end; FACTION_INCOG = FACTION:Register();
data:extend( { { type = "item", name = "explosives-gunpowder", icon = "__base__/graphics/icons/explosives.png", flags = {"goes-to-main-inventory"}, subgroup = "dynamite", order = "a-1", stack_size = 200 }, { type = "recipe", name = "explosives-gunpowder", energy_required = 5, enabled = true, ingredients = { {type="item", name="sulfur", amount=6}, {type="item", name="coal", amount=19}, {type="item", name="salpeter", amount=75}, }, results= { {type="item", name="explosives-gunpowder", amount=100}, }, }, { type = "recipe", name = "explosives", energy_required = 5, enabled = false, category = "chemistry", subgroup = "coal-base", ingredients = { {type="item", name="sulfur", amount=1}, {type="item", name="coal", amount=1}, {type="fluid", name="water", amount=1}, }, result= "explosives" }, })
local o = vim.o local bo = vim.bo local wo = vim.wo -- Add your packages require "paq" { "savq/paq-nvim"; -- Let Paq manage itself "neovim/nvim-lspconfig"; -- Mind the semi-colons 'hrsh7th/nvim-cmp'; 'hrsh7th/cmp-nvim-lsp'; 'hrsh7th/cmp-buffer'; 'hrsh7th/cmp-path'; 'hrsh7th/cmp-vsnip'; 'hrsh7th/vim-vsnip'; 'ray-x/lsp_signature.nvim'; 'folke/which-key.nvim'; 'folke/trouble.nvim'; 'folke/todo-comments.nvim'; 'kyazdani42/nvim-web-devicons'; 'akinsho/bufferline.nvim'; 'simrat39/symbols-outline.nvim'; {"lervag/vimtex", opt=true}; 'jiangmiao/auto-pairs'; 'alaviss/nim.nvim'; 'ziglang/zig.vim'; 'simrat39/rust-tools.nvim'; 'nvim-treesitter/nvim-treesitter'; 'nvim-lua/popup.nvim'; 'nvim-lua/plenary.nvim'; 'nvim-telescope/telescope.nvim'; 'hoob3rt/lualine.nvim'; {'morhetz/gruvbox', as='gruvbox'}; } wo.number = true wo.wrap = false wo.relativenumber = true o.mouse = 'a' bo.tabstop = 4 bo.shiftwidth = 4 bo.softtabstop = 4 bo.expandtab = true vim.g.mapleader = " " vim.g.gruvbox_transparent_bg = 1 vim.cmd 'colorscheme gruvbox' require'lualine'.setup { options = {theme = 'gruvbox'}, } local lsp = require 'lspconfig' local set_keymap = function(mode, from, to) local opts = {noremap = true, silent = false} vim.api.nvim_set_keymap(mode, from, to, opts) end lsp.clangd.setup {} lsp.nimls.setup {} lsp.gopls.setup {} lsp.zls.setup {} lsp.denols.setup{} --lsp.rust_analyzer.setup {} local opts = { tools = { -- rust-tools options autoSetHints = true, hover_with_actions = true, inlay_hints = { show_parameter_hints = true, parameter_hints_prefix = "", other_hints_prefix = "", }, }, -- all the opts to send to nvim-lspconfig -- these override the defaults set by rust-tools.nvim -- see https://github.com/neovim/nvim-lspconfig/blob/master/CONFIG.md#rust_analyzer server = { -- on_attach is a callback called when the language server attachs to the buffer -- on_attach = on_attach, settings = { -- to enable rust-analyzer settings visit: -- https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/user/generated_config.adoc ["rust-analyzer"] = { -- enable clippy on save checkOnSave = { command = "clippy" }, } } }, } require('rust-tools').setup(opts) lsp.erlangls.setup{} local runtime_path = vim.split(package.path, ';') table.insert(runtime_path, "lua/?.lua") table.insert(runtime_path, "lua/?/init.lua") lsp.sumneko_lua.setup{ cmd = {"/usr/bin/lua-language-server", "-E", "/usr/share/lua-language-server/main.lua"}; settings = { Lua = { runtime = { -- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim) version = 'LuaJIT', -- Setup your lua path path = runtime_path, }, diagnostics = { -- Get the language server to recognize the `vim` global globals = {'vim'}, }, workspace = { -- Make the server aware of Neovim runtime files library = vim.api.nvim_get_runtime_file("", true), }, -- Do not send telemetry data containing a randomized but unique identifier telemetry = { enable = false, }, }, }, } lsp.vala_ls.setup{} lsp.pylsp.setup{} lsp.hls.setup{} lsp.texlab.setup{} require'nvim-treesitter.configs'.setup { ensure_installed = "maintained", -- one of "all", "maintained" (parsers with maintainers), or a list of languages ignore_install = { "javascript", "vue", "tsx" }, -- List of parsers to ignore installing highlight = { enable = true -- false will disable the whole extension }, } local cmp = require 'cmp' cmp.setup { snippet = { expand = function(args) vim.fn["vsnip#anonymous"](args.body) end, }, mapping = { ['<Tab>'] = cmp.mapping.select_next_item(), ['<S-Tab>'] = cmp.mapping.select_prev_item(), ['<CR>'] = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = true, }) }, sources = { { name = 'nvim_lsp' }, { name = 'buffer' }, { name = 'path' }, { name = 'vsnip' }, } } require "lsp_signature".setup() require "which-key".setup {} require "trouble".setup {} require "todo-comments".setup {} vim.opt.termguicolors = true require"bufferline".setup{} -- Telescope set_keymap('n', '<leader>ff', '<cmd>Telescope find_files find_command=fd,--hidden,--no-ignore,--exclude,*.git,--type,f<cr>') set_keymap('n', '<leader>fd', '<cmd>Telescope git_files<cr>') set_keymap('n', '<leader>fg', '<cmd>Telescope live_grep<cr>') set_keymap('n', '<leader>fb', '<cmd>Telescope buffers<cr>') set_keymap('n', '<leader>fh', '<cmd>Telescope help_tags<cr>') set_keymap('n', '<leader>fl', '<cmd>Telescope lsp_document_symbols<cr>') set_keymap('n', '<leader>fk', '<cmd>Telescope keymaps<cr>') set_keymap('n', '<leader>fm', '<cmd>Telescope heading<cr>') set_keymap('n', '<leader>fu', '<cmd>Telescope lsp_references<cr>') set_keymap('n', '<leader>gd', '<cmd>Telescope lsp_definitions<cr>') set_keymap('n', '<leader>ga', '<cmd>lua vim.lsp.buf.code_action()<cr>') vim.api.nvim_exec([[ " Use <Tab> and <S-Tab> to navigate through popup menu inoremap <expr> <Tab> pumvisible() ? "\<C-n>" : "\<Tab>" inoremap <expr> <S-Tab> pumvisible() ? "\<C-p>" : "\<S-Tab>" " Set completeopt to have a better completion experience set completeopt=menuone,noinsert,noselect " Avoid showing message extra message when using completion set shortmess+=c set updatetime=300 autocmd CursorHold * lua vim.lsp.diagnostic.show_line_diagnostics() ]], false) vim.api.nvim_exec([[ autocmd VimEnter * hi Normal ctermbg=NONE guibg=NONE ]],false)
SmoothyPlates.getDefaultConfig = function() return { ['version'] = SmoothyPlates.Vars.currVersion, ['options'] = { ['hideUnimportantPets'] = true, ['hideUnimportantTotems'] = true, ['absorbs'] = true }, ['modules'] = { ['Trinket'] = { ['active'] = true }, ['Interrupts'] = { ['active'] = true }, ['Healers'] = { ['active'] = true }, ['Auras'] = { ['active'] = true, ['customOptions'] = { ['spellSets'] = { HARMFUL = { key = 'HARMFUL', name = 'Harmful', isAuraType = true }, HELPFUL = { key = 'HELPFUL', name = 'Helpful', isAuraType = true }, PLAYER = { key = 'PLAYER', name = 'Cast By Player', isAuraType = true }, INCLUDE_NAME_PLATE_ONLY = { key = 'INCLUDE_NAME_PLATE_ONLY', name = 'Blizzard Nameplate Auras', isAuraType = true }, STEAL_OR_PURGE = { key = 'STEAL_OR_PURGE', name = 'Can steal or purge', isAuraType = true } }, ['auraSets'] = { STUNS = { key = 'STUNS', name = 'Stuns', active = true, default = true, whitelists = {STUNS = true}, blacklists = {} }, SILENCES = { key = 'SILENCES', name = 'Silences', active = true, default = true, showDuration = true, whitelists = {SILENCES = true}, blacklists = {} }, PVPAURAS = { key = 'PVPAURAS', name = 'PvP Auras (GaldiatorlosSA2)', active = true, default = true, whitelists = {PVPSPELLS = true}, blacklists = {SILENCES = true, STUNS = true} }, CASTBYPLAYER = { key = 'CASTBYPLAYER', name = 'Applied by Player', active = true, default = true, whitelists = {PLAYER = true}, blacklists = {SILENCES = true, STUNS = true} } } } } }, ['media'] = { ['FONT'] = 'Designosaur Regular', ['BAR'] = 'Glaze', ['PRED_BAR'] = 'Glaze' }, ['layout'] = { ['GENERAL'] = { ['scale'] = 1.1 }, ['CAST_TEXT'] = { ['y'] = -1, ['x'] = 2, ['anchor'] = 'LEFT', ['opacity'] = 1, ['size'] = 10 }, ['HEALTH'] = { ['y'] = 0, ['x'] = 0, ['anchor'] = 'CENTER', ['opacity'] = 1, ['height'] = 32, ['width'] = 120 }, ['HEALTH_TEXT'] = { ['y'] = -1, ['x'] = 0, ['anchor'] = 'CENTER', ['opacity'] = 1, ['size'] = 12 }, ['TARGET'] = { ['y'] = -2, ['x'] = 0, ['anchor'] = 'BOTTOM', ['opacity'] = 0.8, ['height'] = 20, ['width'] = 120, ['parent'] = 'Name' }, ['CAST'] = { ['y'] = -26, ['x'] = 0, ['anchor'] = 'BOTTOM', ['height'] = 24, ['opacity'] = 1, ['parent'] = 'PowerBar', ['width'] = 120 }, ['CAST_ICON'] = { ['y'] = 0, ['x'] = -26, ['height'] = 24, ['opacity'] = 1, ['anchor'] = 'LEFT', ['width'] = 24 }, ['HEALER_ICON'] = { ['y'] = 0, ['x'] = 0, ['anchor'] = 'TOPLEFT', ['height'] = 18, ['opacity'] = 1, ['parent'] = 'HealthBar', ['width'] = 18 }, ['NAME'] = { ['y'] = 14, ['x'] = 0, ['anchor'] = 'TOP', ['opacity'] = 1, ['parent'] = 'HealthBar', ['size'] = 12 }, ['RAID_ICON'] = { ['y'] = 100, ['x'] = 0, ['anchor'] = 'TOP', ['height'] = 42, ['opacity'] = 1, ['parent'] = 'Name', ['width'] = 42, ['level'] = 2 }, ['POWER'] = { ['y'] = -3, ['x'] = 0, ['hide border'] = 'n', ['parent'] = 'HealthBar', ['height'] = 4, ['opacity'] = 1, ['anchor'] = 'BOTTOM', ['width'] = 120 }, ['TRINKET'] = { ['y'] = 0, ['x'] = 0, ['anchor'] = 'TOPRIGHT', ['height'] = 18, ['opacity'] = 1, ['parent'] = 'HealthBar', ['width'] = 18, ['level'] = 1 }, ['INTERRUPT'] = { ['y'] = 0, ['x'] = 34, ['anchor'] = 'RIGHT', ['size'] = 35, ['opacity'] = 1, ['parent'] = 'HealthBar', ['level'] = 4, ['red border'] = false, ['glow'] = false }, ['AURAS_PVPAURAS'] = { ['y'] = 68, ['x'] = 0, ['anchor'] = 'TOPLEFT', ['size'] = 26, ['opacity'] = 1, ['parent'] = 'HealthBar', ['direction'] = 'RIGHT', ['duration'] = false, ['glow'] = false, ['count'] = false, ['level'] = 1 }, ['AURAS_CASTBYPLAYER'] = { ['y'] = 42, ['x'] = 0, ['anchor'] = 'TOPLEFT', ['size'] = 26, ['opacity'] = 1, ['parent'] = 'HealthBar', ['direction'] = 'RIGHT', ['duration'] = false, ['glow'] = false, ['count'] = false, ['level'] = 1 }, ['AURAS_SILENCES'] = { ['y'] = 0, ['x'] = 34, ['anchor'] = 'RIGHT', ['size'] = 35, ['opacity'] = 1, ['parent'] = 'HealthBar', ['direction'] = 'RIGHT', ['duration'] = true, ['glow'] = false, ['count'] = false, ['level'] = 1 }, ['AURAS_STUNS'] = { ['y'] = 0, ['x'] = -34, ['anchor'] = 'LEFT', ['size'] = 35, ['opacity'] = 1, ['parent'] = 'HealthBar', ['direction'] = 'LEFT', ['duration'] = true, ['glow'] = false, ['count'] = false, ['level'] = 1 } } } end SmoothyPlates.getOptionsStructure = function() return { { ['key'] = 'options', ['displayName'] = 'Options', ['options'] = { ['hideUnimportantPets'] = { ['type'] = 'BOOL', ['displayName'] = 'Hide unimportant creatures' }, ['hideUnimportantTotems'] = { ['type'] = 'BOOL', ['displayName'] = 'Hide unimportant totems' }, ['absorbs'] = { ['type'] = 'BOOL', ['displayName'] = 'Show absorbs' } } }, { ['key'] = 'modules', ['displayName'] = 'Modules', ['valuePath'] = 'active', ['options'] = { ['Trinket'] = { ['type'] = 'BOOL', ['displayName'] = 'Arena Trinket' }, ['Interrupts'] = { ['type'] = 'BOOL', ['displayName'] = 'Interrupts' }, ['Healers'] = { ['type'] = 'BOOL', ['displayName'] = 'Healers' }, ['Auras'] = { ['type'] = 'BOOL', ['displayName'] = 'Auras', ['customOptions'] = true } } }, { ['key'] = 'media', ['displayName'] = 'Media', ['options'] = { ['FONT'] = { ['value'] = 'Designosaur Regular', ['type'] = 'FONT', ['displayName'] = 'Font' }, ['BAR'] = { ['value'] = 'Glaze', ['type'] = 'BAR', ['displayName'] = 'Bar' }, ['PRED_BAR'] = { ['value'] = 'Glaze', ['type'] = 'BAR', ['displayName'] = 'Prediction Bar' } } } } end
local elol = false local sx, sy = guiGetScreenSize() local w1PosX, w1PosY = 0, sy/2-300 local currmenuposition = 1 local coreside = "menu" local kijelolt = 1 local animalva = false local myfont = dxCreateFont("files/font.ttf", 10) local current = 1 addEventHandler("onClientKey", root, function(k, v) if not v or not elol then return end if k == "arrow_r" then if coreside == "menu" then if currmenuposition < #menu then currmenuposition = currmenuposition +1 else currmenuposition = 1 end end elseif k == "arrow_l" then if coreside == "menu" then if currmenuposition > 1 then currmenuposition = currmenuposition -1 else currmenuposition = 5 end end elseif k == "arrow_d" then if coreside == "anims" then if kijelolt <= 5 then kijelolt = kijelolt + 1 else kijelolt = 1 end end elseif k == "arrow_u" then if coreside == "anims" then if kijelolt >= 2 then kijelolt = kijelolt - 1 else kijelolt = 6 end end elseif k == "enter" then if coreside == "menu" then coreside = "anims" elseif coreside == "anims" then animalva = true triggerServerEvent("applyanim", localPlayer, localPlayer, anims[currmenuposition][kijelolt][2], anims[currmenuposition][kijelolt][3], anims[currmenuposition][kijelolt][4], anims[currmenuposition][kijelolt][5], anims[currmenuposition][kijelolt][6], anims[currmenuposition][kijelolt][7] ) elol = false toggleAllControls(true) end elseif k == "backspace" then if coreside == "menu" then elol = false toggleAllControls(true) elseif coreside == "anims" then coreside = "menu" kijelolt = 1 end end end) bindKey("space", "down", function() if animalva then triggerServerEvent("stopanim", localPlayer, localPlayer) animalva = false end end) local panelelol = false local rotates = {-90, -45, 0, 45, 90, 135, 180, 225, 270} local fastanims = { {55,"N/A", "", "", -1, false, false, false}, {55,"Pensar", "COP_AMBIENT", "Coplook_think", -1, true, false, false}, {55,"Fumar", "SMOKING", "M_smkstnd_loop", -1, true, false, false}, {55,"Dançar", "DANCING", "dance_loop", -1, true, false, false}, {55,"Saudar", "GANGS", "hndshkba", -1, false, false, false}, {55,"Sentar", "INT_HOUSE", "LOU_In", -1, false, false, false}, {55,"Conversar", "GANGS", "prtial_gngtlkA", -1, true, false, false}, {55,"Sorrir", "RAPPING", "Laugh_01", -1, false, false, false}, } function renderfastaim() if not panelelol then return end local sx, sy = guiGetScreenSize() --createBlur() local w, h = 100, 100 local left, top = sx/2 - w/2, sy/2 - h/2 --dxDrawRectangle(sx/2 - 165/2, sy/2 + 195/2, 176, 3,tocolor(0, 0, 0, 210)) --dxDrawRectangle(sx/2 - 165/2, sy/2 + 138/2, 176, 3,tocolor(0, 0, 0, 210)) ---dxDrawRectangle(sx/2 + 181/2, sy/2 + 145/2, 3, 25,tocolor(0, 0, 0, 210)) --dxDrawRectangle(sx/2 - 166/2, sy/2 + 145/2, 3, 25,tocolor(0, 0, 0, 210)) dxDrawRectangle(sx/2 - 160/2, sy/2 + 145/2, 170, 25,tocolor(0, 0, 0, 190)) dxDrawText (fastanims[current][2] .. "",sx-150, sy/2 - 150/2 + 150, 150, 150, tocolor(255, 255, 255,255 ), 1.0, myfont, "center", "top", false, false, false, true) progress = (getTickCount() - asdtick) / 500 panelTopa = interpolateBetween ( top,0,0, top +220, 0, 0, progress,"InOutQuad" ) panelTopa1 = interpolateBetween ( top ,0,0, top-220, 0, 0, progress,"InOutQuad" ) panelTopa2 = interpolateBetween ( left,0,0, left - 220, 0, 0, progress,"InOutQuad" ) panelTopa3 = interpolateBetween ( left,0,0, left + 220, 0, 0, progress,"InOutQuad" ) panelTopa4 = interpolateBetween ( top,0,0, top + 165, 0, 0, progress,"InOutQuad" ) panelTopa5 = interpolateBetween ( left,0,0, left + 165, 0, 0, progress,"InOutQuad" ) panelTopa6 = interpolateBetween ( top,0,0, top - 165, 0, 0, progress,"InOutQuad" ) panelTopa7 = interpolateBetween ( left,0,0, left - 165, 0, 0, progress,"InOutQuad" ) dxDrawImage(sx/2 - 150/2, sy/2 - 150/2, 150, 150,"seta.png",rotates[current],0,0,tocolor(255,255,255,255),true) --dxDrawRectangle(left, panelTopa, w, h, tocolor(0, 0, 0, 200)) --dxDrawRectangle(panelTopa5, panelTopa4, w, h, tocolor(0, 0, 0, 200)) --dxDrawRectangle(panelTopa5, panelTopa6, w, h, tocolor(0, 0, 0, 200)) --dxDrawRectangle(panelTopa7, panelTopa6, w, h, tocolor(0, 0, 0, 200)) --dxDrawRectangle(panelTopa7, panelTopa4, w, h, tocolor(0, 0, 0, 200)) --dxDrawRectangle(panelTopa2, top, w, h, tocolor(0, 0, 0, 200)) --dxDrawRectangle(left, panelTopa1 , w, h, tocolor(0, 0, 0, 200)) --dxDrawRectangle(panelTopa3, top , w, h, tocolor(0, 0, 0, 200)) dxDrawImage(sx/2 - 98/2, sy/2 - 534/2, 98, 98,"images/Icon_Stop.png",0,0,tocolor(255,255,255,200)) dxDrawImage(sx/2 + 234/2, sy/2 - 426/2, 98, 98,"images/Icon_pensar.png",0,0,tocolor(255,255,255,200)) dxDrawImage(sx/2 + 344/2, sy/2 - 96/2, 98, 98,"images/Icon_fumar.png",0,0,tocolor(255,255,255,200)) dxDrawImage(sx/2 + 234/2, sy/2 + 236/2, 98, 98,"images/Icon_dance.png",0,0,tocolor(255,255,255,200)) dxDrawImage(sx/2 - 100/2, sy/2 + 350/2, 98, 98,"images/Icon_cumprimentar.png",0,0,tocolor(255,255,255,200)) dxDrawImage(sx/2 - 422/2, sy/2 + 240/2, 98, 98,"images/Icon_sentar.png",0,0,tocolor(255,255,255,200)) dxDrawImage(sx/2 - 534/2, sy/2 - 98/2, 98, 98,"images/Icon_conversar.png",0,0,tocolor(255,255,255,200)) dxDrawImage(sx/2 - 428/2, sy/2 - 432/2, 98, 98,"images/Icon_rir.png",0,0,tocolor(255,255,255,200)) if current == 1 then dxDrawImage(sx/2 - 98/2, sy/2 - 534/2, 98, 98,"images/Icon_Stop_1.png",0,0,tocolor(255,255,255,200)) elseif current == 2 then dxDrawImage(sx/2 + 234/2, sy/2 - 426/2, 98, 98,"images/Icon_pensar_1.png",0,0,tocolor(255,255,255,200)) elseif current == 3 then dxDrawImage(sx/2 + 344/2, sy/2 - 96/2, 98, 98,"images/Icon_fumar_1.png",0,0,tocolor(255,255,255,200)) elseif current == 4 then dxDrawImage(sx/2 + 234/2, sy/2 + 236/2, 98, 98,"images/Icon_dance_1.png",0,0,tocolor(255,255,255,200)) elseif current == 5 then dxDrawImage(sx/2 - 100/2, sy/2 + 350/2, 98, 98,"images/Icon_cumprimentar_1.png",0,0,tocolor(255,255,255,200)) elseif current == 6 then dxDrawImage(sx/2 - 422/2, sy/2 + 240/2, 98, 98,"images/Icon_sentar_1.png",0,0,tocolor(255,255,255,200)) elseif current == 7 then dxDrawImage(sx/2 - 534/2, sy/2 - 98/2, 98, 98,"images/Icon_conversar_1.png",0,0,tocolor(255,255,255,200)) elseif current == 8 then dxDrawImage(sx/2 - 428/2, sy/2 - 432/2, 98, 98,"images/Icon_rir_1.png",0,0,tocolor(255,255,255,200)) end end addEventHandler("onClientRender", root, renderfastaim) local animba = false bindKey("f2", "up", function() showChat(true) triggerServerEvent("applyfastanim", localPlayer, localPlayer, fastanims[current][3], fastanims[current][4], fastanims[current][5], fastanims[current][6], fastanims[current][7], fastanims[current][8], fastanims[current][9] ) animba = true setElementData(localPlayer, "opendashboard", false) panelelol = false current = 1 end) bindKey("f2", "down", function() if ( getElementData(localPlayer,"logado") ) then local theVehicle = getPedOccupiedVehicle ( localPlayer ) if ( theVehicle ) then return end setElementData(localPlayer, "opendashboard", true) asdtick = getTickCount() panelelol = true showChat(false) end end) bindKey("mouse_wheel_down", "down", function() if not panelelol then return end cancelEvent() if current <= 7 then current = current + 1 else current = 1 end playSound("files/som.mp3") end) bindKey("mouse_wheel_up", "down", function() if not panelelol then return end cancelEvent() if current >= 2 then current = current - 1 else current = 8 end playSound("song.mp3") end) bindKey("space", "down", function() triggerServerEvent("removeanim", localPlayer, localPlayer) end)
SellOMatic2DB = { ["profileKeys"] = { ["熊奶奶 - 屠魔山谷"] = "Default", }, }
local Commands = require("./Commands") local function embed(message, color_code) message:reply { embed = { title = "Commands List", description = "Showing Basic Cmds & Mod Cmds", fields = { { name = Commands[1].name, value = Commands[1].desc, inline = true }, { name = Commands[2].name, value = Commands[2].desc, inline = true }, { name = Commands[3].name, value = Commands[3].desc, inline = true }, { name = Commands[4].name, value = Commands[4].desc, inline = true }, { name = Commands[5].name, value = Commands[5].desc, inline = true }, { name = Commands[6].name, value = Commands[6].desc, inline = true }, { name = Commands[7].name, value = Commands[7].desc, inline = true }, { name = Commands[8].name, value = Commands[8].desc, inline = true }, { name = Commands[9].name, value = Commands[9].desc, inline = true }, { name = Commands[10].name, value = Commands[10].desc, inline = true }, }, footer = { text = "Commands shown: 10" }, color = color_code } } end return embed
-------------------------------------------------------------------------------- -- Module Declaration -- local mod, CL = BigWigs:NewBoss("The Violet Hold Trash", 608) if not mod then return end mod.displayName = CL.trash mod:RegisterEnableMob( 30658, -- Lieutenant Sinclari -- Bosses 29315, -- Erekem 29316, -- Moragg 29313, -- Ichoron 29266, -- Xevozz 29312, -- Lavanthor 29314, -- Zuramat the Obliterator -- Replacements mobs for above bosses. -- They spawn if you kill the above bosses but fail the encounter afterwards. -- You don't get to kill the same bosses again. 32226, -- Arakkoa Windwalker (Erekem) 32235, -- Chaos Watcher (Moragg) 32234, -- Swirling Water Revenant (Ichoron) 32231, -- Ethereal Wind Trader (Xevozz) 32237, -- Lava Hound (Lavanthor) 32230 -- Void Lord (Zuramat the Obliterator) ) -------------------------------------------------------------------------------- -- Locals -- local prevWave = 0 -------------------------------------------------------------------------------- -- Localization -- local L = mod:GetLocale() if L then L.portals = "Portals" L.portals_desc = "Information about portals." end -------------------------------------------------------------------------------- -- Initialization -- function mod:GetOptions() return { "portals", } end function mod:OnBossEnable() self:RegisterWidgetEvent(566, "UpdateWaveTimers") self:Death("BossDeaths", 29315, 29316, 29313, 29266, 29312, 29314, 32226, 32230, 32231, 32234, 32235, 32237) self:Death("Disable", 31134) end function mod:OnDisable() prevWave = 0 end -------------------------------------------------------------------------------- -- Event Handlers -- function mod:UpdateWaveTimers(id, text) local wave = text:match("(%d+).+18") if wave then local currentWave = tonumber(wave) if currentWave and currentWave ~= prevWave then prevWave = currentWave local portal = self:SpellName(216299) -- Portal if currentWave == 6 or currentWave == 12 then self:Message("portals", "yellow", "Info", CL.incoming:format(_G.BOSS), false) self:StopBar(CL.count:format(portal, currentWave)) elseif currentWave == 18 then self:UnregisterWidgetEvent(id) local cyanigosa = EJ_GetEncounterInfo(632) self:Message("portals", "yellow", "Info", CL.custom_sec:format(cyanigosa, 17), false) self:Bar("portals", 17, CL.count:format(portal, currentWave), "spell_arcane_portaldalaran") else -- The single mobs (Guardian/Keeper) are 15s, the groups are about 12s. The spawn in random so stick to 15s. self:Bar("portals", 15, CL.count:format(portal, currentWave), "spell_arcane_portaldalaran") self:Message("portals", "yellow", "Info", CL.custom_sec:format(CL.count:format(portal, currentWave), 15), false) self:Bar("portals", 134, CL.count:format(portal, currentWave+1), "spell_arcane_portaldalaran") -- 119s + 15s depending on spawn, sometimes it's 101s + 15s if the spawn is a group. Stick with 134s. end end end end function mod:BossDeaths() local count = prevWave+1 self:Bar("portals", count == 7 and 35 or 30, CL.count:format(self:SpellName(216299), count), "spell_arcane_portaldalaran") -- (20s or 15s) + 15s end
-- Example: Cursor Visibility function love.load() -- Hide mouse on startup. love.mouse.setVisible(false) local f = love.graphics.newFont(love._vera_ttf, 12) love.graphics.setFont(f) end -- Toggle cursor visibility. function love.keypressed(k) if k == "v" then if love.mouse.isVisible() then love.mouse.setVisible(false) else love.mouse.setVisible(true) end end end function love.draw() love.graphics.print("Press V to toggle visibility.", 50, 50) end
-------------------------------------------------------------------- --JoysticConfig require 'mock.tools.SDLJoystickMapping' -------------------------------------------------------------------- require 'mock.tools.TMXTool' require 'mock.tools.InputRecorder' require 'mock.tools.UserAction' --non coroutine action --------------------------------------------------------------------- --Stat require 'mock.tools.Stat' require 'mock.tools.GameSave' -- require 'mock.tools.Analytic' require 'mock.tools.Achievement' -- require 'mock.tools.HighscoreTable' -------------------------------------------------------------------- --Debug related require 'mock.tools.ProfilerHelper' -- require 'mock.tools.RemoteData' -- require 'mock.tools.DebugView' -- require 'tools.RemoteInput' -------------------------------------------------------------------- --Platform related -- require 'mock.tools.GameCenter' -- require 'tools.FacebookHelper' -------------------------------------------------------------------- --Math require 'mock.tools.Quaternion' require 'mock.tools.MeshHelper' require 'mock.tools.TextureHelper' require 'mock.tools.GridStruct' require 'mock.tools.SpatialGrid' require 'mock.tools.EntityAlignment' require 'mock.tools.PolygonHelper' -------------------------------------------------------------------- --color require 'mock.tools.NamedColors' -------------------------------------------------------------------- --TOOLS require 'mock.tools.SimpleAnimationPreset' require 'mock.tools.SimpleShakeAnimationPreset' require 'mock.tools.PlaceHolder' -- require 'mock.tools.TouchButton' -- require 'mock.tools.FakeInput' require 'mock.tools.DialogScript' -------------------------------------------------------------------- require 'mock.tools.I18N' require 'mock.tools.FieldAnimation'
local utils = {} utils.bg = "#000000" utils.fg = "#ffffff" utils.day_brightness = 0.3 ---Print a warning message to the user ---@param... string ---@return table function utils.warn(...) for _, msg in ipairs({ ... }) do vim.cmd('echohl WarningMsg | echom "OneDarkPro.nvim: ' .. msg .. '" | echohl NONE') end end ---Convert a hex color into an rgb ---@param hex_str string ---@return table local hex_to_rgb = function(hex_str) local hex = "[abcdef0-9][abcdef0-9]" local pat = "^#(" .. hex .. ")(" .. hex .. ")(" .. hex .. ")$" hex_str = string.lower(hex_str) assert(string.find(hex_str, pat) ~= nil, "hex_to_rgb: invalid hex_str: " .. tostring(hex_str)) local r, g, b = string.match(hex_str, pat) return { tonumber(r, 16), tonumber(g, 16), tonumber(b, 16) } end ---Blend colors together ---@param fg string foreground color ---@param bg string background color ---@param alpha number number between 0 and 1. 0 results in bg, 1 results in fg function utils.blend(fg, bg, alpha) bg = hex_to_rgb(bg) fg = hex_to_rgb(fg) local blendChannel = function(i) local ret = (alpha * fg[i] + ((1 - alpha) * bg[i])) return math.floor(math.min(math.max(0, ret), 255) + 0.5) end return string.format("#%02X%02X%02X", blendChannel(1), blendChannel(2), blendChannel(3)) end ---Darken a hex color ---@param hex string ---@param amount integer ---@param bg string ---@return table function utils.darken(hex, amount, bg) return utils.blend(hex, bg or utils.bg, math.abs(amount)) end ---Lighten a hex color ---@param hex string ---@param amount integer ---@param fg string ---@return table function utils.lighten(hex, amount, fg) return utils.blend(hex, fg or utils.fg, math.abs(amount)) end ---Merge many tables together ---@param... table ---@return table function utils.tbl_deep_extend(...) local lhs = {} for _, rhs in ipairs({ ... }) do for k, v in pairs(rhs) do if type(lhs[k]) == "table" and type(v) == "table" then lhs[k] = utils.tbl_deep_extend(lhs[k], v) else lhs[k] = v end end end return lhs end ---Set or override the default colors in the theme with the user's config ---@param colors table ---@param config table ---@return nil function utils.color_overrides(colors, config) if type(config.colors) == "table" then for key, value in pairs(config.colors) do -- check if the user has specified a table within the colors table if type(config.colors[key]) == "table" then -- only override colors if the key matches the name of the active theme if key == colors.name then for key, value in pairs(config.colors[key]) do utils.set_or_create_color(colors, key, value) end end else -- otherwise just set them utils.set_or_create_color(colors, key, value) end end end end ---Add a color to the colors table ---@param colors table ---@param key string ---@param value string ---@return nil function utils.set_or_create_color(colors, key, value) -- Patch: https://github.com/ful1e5/onedark.nvim/issues/6 if value:lower() == "none" then colors[key] = "NONE" elseif string.sub(value, 1, 1) == "#" then -- hex override colors[key] = value else -- create the new color colors[key] = colors[value] end end ---Create the highlight groups from the theme ---@param group string ---@param color table ---@return nil function utils.create_highlights(group, color) local style = color.style and "gui=" .. color.style or "gui=NONE" local fg = color.fg and "guifg=" .. color.fg or "guifg=NONE" local bg = color.bg and "guibg=" .. color.bg or "guibg=NONE" local sp = color.sp and "guisp=" .. color.sp or "" local hl = "highlight " .. group .. " " .. style .. " " .. fg .. " " .. bg .. " " .. sp if color.link and (color.fg == nil and color.bg == nil and color.sp == nil) then vim.cmd("highlight! link " .. group .. " " .. color.link) else vim.cmd(hl) end end ---Simple string interpolation. ---Example template: "${name} is ${value}" ---@param str string template string ---@param table table key value pairs to replace in the string ---@return table function utils.template(str, table) return (str:gsub("($%b{})", function(w) return table[w:sub(3, -2)] or w end)) end ---Template values in a table recursivly ---@param table table the table to be replaced ---@param values table the values to be replaced by the template strings in the table passed in ---@return table table function utils.template_table(table, values) -- if the value passed is a string the return templated resolved string if type(table) == "string" then return utils.template(table, values) end -- If the table passed in has a table then iterate though the children and call template table for key, value in pairs(table) do table[key] = utils.template_table(value, values) end return table end ---Set the theme's syntax ---@param highlight_groups table ---@return nil function utils.set_syntax(highlight_groups) for group, colors in pairs(highlight_groups) do utils.create_highlights(group, colors) end end ---Set the terminal colors ---@param theme table ---@return nil function utils.terminal(theme) vim.g.terminal_color_0 = theme.colors.black vim.g.terminal_color_1 = theme.colors.red vim.g.terminal_color_2 = theme.colors.green vim.g.terminal_color_3 = theme.colors.yellow vim.g.terminal_color_4 = theme.colors.blue vim.g.terminal_color_5 = theme.colors.purple vim.g.terminal_color_6 = theme.colors.cyan vim.g.terminal_color_7 = theme.colors.white vim.g.terminal_color_8 = theme.colors.black vim.g.terminal_color_9 = theme.colors.red vim.g.terminal_color_10 = theme.colors.green vim.g.terminal_color_11 = theme.colors.yellow vim.g.terminal_color_12 = theme.colors.blue vim.g.terminal_color_13 = theme.colors.purple vim.g.terminal_color_14 = theme.colors.cyan vim.g.terminal_color_15 = theme.colors.white end ---Pretty print a table ---@param tbl table ---@return string function utils.print_table(tbl) require("pl.pretty").dump(tbl) end ---Load the desired theme ---@param theme table ---@return nil function utils.load_theme(theme) -- Prevent double loading of the theme if vim.g.colors_name == "onedarkpro" and vim.g.onedarkpro_style == theme.colors.name then return end vim.cmd("hi clear") if vim.fn.exists("syntax_on") then vim.cmd("syntax reset") end vim.o.termguicolors = true vim.g.colors_name = "onedarkpro" vim.g.onedarkpro_style = theme.colors.name -- Replace color variables in the user's custom hlgroups local hlgroups = utils.template_table(theme.config.hlgroups, theme.colors) -- Merge the user's custom hlgroups with the theme's local adjusted_hlgroups = utils.tbl_deep_extend(theme.hlgroups, hlgroups) utils.set_syntax(adjusted_hlgroups) -- Colors for the Neovim terminal if theme.config.options.terminal_colors then utils.terminal(theme) end --[[ Due to recent configuration changes, we need to check if the user is using the "link =" annotations correcrtly. If not, warn them accordingly ]] local warn = 0 for _, colors in pairs(hlgroups) do for key, _ in pairs(colors) do if key ~= "fg" and key ~= "bg" and key ~= "sp" and key ~= "style" and key ~= "link" then warn = warn + 1 end end end if warn > 0 then utils.warn( "Directly referencing highlight groups has now changed. Please use the `link` keyword", "EXAMPLE: onedarkpro.setup({ hlgroups = { ModeMsg = { link = 'LineNr' } } })", "See https://github.com/olimorris/onedarkpro.nvim for more info", "-----------------------------------------------------------------------------------" ) end --[[ Warn the user about the deprecated cursorline option ]] if theme.config.highlight_cursorline then utils.warn( "`highlight_cursorline` has been moved into the options table of your config and is now deprecated", "EXAMPLE: onedarkpro.setup({ options = { highlight_cursorline = true } })", "See https://github.com/olimorris/onedarkpro.nvim for more info", "-----------------------------------------------------------------------------------" ) end if theme.config.options.highlight_cursorline then utils.warn( "`highlight_cursorline` has been renamed to `cursorline` and will soon be deprecated", "EXAMPLE: onedarkpro.setup({ options = { cursorline = true } })", "See https://github.com/olimorris/onedarkpro.nvim for more info", "-----------------------------------------------------------------------------------" ) end --[[ Warn the user about the deprecated transparent option ]] if theme.config.options.transparent then utils.warn( "The `transparent` option has been renamed to `transparency` and will soon be deprecated", "EXAMPLE: onedarkpro.setup({ options = { transparency = true } })", "See https://github.com/olimorris/onedarkpro.nvim for more info", "-----------------------------------------------------------------------------------" ) end -- Trigger the colorscheme autocommand vim.cmd([[doautocmd ColorScheme]]) end return utils
--[[ Desc: Avatar, a set of frame animations. Author: SerDing Since: 2018-09-22 Alter: 2020-03-11 ]] local _Frameani = require "entity.drawable.frameani" local _Layer = require("engine.graphics.drawable.layer") local _RESMGR = require("system.resource.resmgr") local _RESOURCE = require("engine.resource") ---@class Entity.Drawable.Avatar : Engine.Graphics.Drawable.Layer ---@field protected _aniMap table<string, Entity.Drawable.Frameani> ---@field protected _aniDatas table<string, table<string, Engine.Resource.AnimData>> ---@field protected _path string @ basic path for animData and images ---@field protected _subpath table<string, string> @ sprite subpath for dynamic mode ---@field protected _order table<string, number> ---@field protected _dynamic boolean local _Avatar = require("core.class")(_Layer) local _DEFAULT_KEY = "body" ---@param data table function _Avatar:Ctor(data) _Layer.Ctor(self) self._aniMap = {} self._aniDatas = {} self._path = data.path or "" self._subpath = data.subpath self._order = data.order self._dynamic = data.dynamic local keylist = (self._dynamic == true) and self._subpath or data.animPathSet for key,_ in pairs(keylist) do self:AddPart(key) end if self._dynamic == false then self._aniDatas = {} if data.animPathSet then for key, path in pairs(data.animPathSet) do self._aniDatas[key] = _RESOURCE.LoadAnimData(data.path .. path) end end self:Play() end if data.init then self:InitAnimDatas(data.init.animNameSet) self:Play(data.init.defaultAnim) end end function _Avatar:Update(dt, timeScale) for _,part in pairs(self._aniMap) do part:Update(dt, timeScale) end end ---@param name string function _Avatar:Play(name) for key, part in pairs(self._aniMap) do local data = (self._dynamic) and self._aniDatas[key][name] or self._aniDatas[key] part:Play(data, name) end end function _Avatar:SyncPart(key) local animName = self:GetPart()._aniName local part = self._aniMap[key] part:Play(self._aniDatas[key][animName], animName) part:Sync(self:GetPart()) end ---@param data table<string, string> @ new subpath data table function _Avatar:AddByData(data) for key, subpath in pairs(data) do if not self._aniMap[key] then self:AddPart(key) end self._subpath[key] = subpath end end ---@param animNameSet table<number, string> function _Avatar:InitAnimDatas(animNameSet) for part, subpath in pairs(self._subpath) do -- for i=1,#animPathSet do -- self._animDatas[part][animPathSet[i]] = _RESMGR.LoadAvatarAnimData(self._path .. animPathSet[i], self._path .. subpath) -- end self:LoadAnimDatas(part, animNameSet, subpath) end end function _Avatar:LoadAnimDatas(part, animNameSet, path) local subpath = path or self._subpath[part] for i=1,#animNameSet do self._aniDatas[part][animNameSet[i]] = _RESMGR.LoadAvatarAnimData(self._path .. animNameSet[i], self._path .. subpath) end end ---@param key string function _Avatar:AddPart(key) self._aniMap[key] = _Frameani.New() self._aniMap[key].order = self._order[key] self._aniDatas[key] = {} self:Add(self._aniMap[key]) ---@param partA Engine.Graphics.Drawable.Base ---@param partB Engine.Graphics.Drawable.Base local function _Sort(partA, partB) return partA.order < partB.order end _Layer.Sort(self, _Sort) end function _Avatar:GetPart(key) return self._aniMap[key or _DEFAULT_KEY] end function _Avatar:NextFrame() for _,part in pairs(self._aniMap) do part:NextFrame() end end function _Avatar:SetFrame(n) for _,part in pairs(self._aniMap) do part:SetFrame(n) end end function _Avatar:CallChildGetFunc(op) for _,part in pairs(self._aniMap) do return part[op](part) end end function _Avatar:GetFrame() return self:CallChildGetFunc("GetFrame") end function _Avatar:GetTick() return self:CallChildGetFunc("GetTick") end function _Avatar:TickEnd() return self:CallChildGetFunc("TickEnd") end ---@return table<int, Entity.Collider> function _Avatar:GetColliderGroup() local colliders = {} for _,v in pairs(self._aniMap) do local collider = v:GetCollider() if collider and not collider:IsEmpty() then colliders[#colliders + 1] = collider end end return colliders end function _Avatar:GetHeight(key) return self._aniMap[key or _DEFAULT_KEY]:GetWidth() end function _Avatar:GetHeight(key) return self._aniMap[key or _DEFAULT_KEY]:GetHeight() end return _Avatar
--------------------------------------------------------------------------------------------------- -- Proposal: -- https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0207-rpc-message-protection.md -- Description: -- Precondition: -- 1) App registered and activated, OnHMIStatus(FULL) -- 2) RPC needs protection, encryption_required parameters to App within app_policies = true and to the -- appropriate function_group (Base-4) = true -- In case: -- 1) HMI sends specific notification to SDL (see list below) -- SDL does: -- 1) resend this notification to mobile application (non-encrypted) -- In case: -- 1) RPC service 7 is started in protected mode -- 2) HMI sends specific notification to SDL (see list below) -- SDL does: -- 1) resend this notification to mobile application (encrypted) -- -- Excluded from force protection RPCs and Notifications: -- - RegisterAppInterface, SystemRequest, PutFile -- - OnPermissionsChange, OnSystemRequest --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('test_scripts/Security/RPCMessageProtection/common') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local Functions ]] local function rpcUnencryptedEncryptionNotRequired() common.getHMIConnection():SendNotification("BasicCommunication.OnSystemRequest", { requestType = "HTTP", fileName = "files/icon_png.png" }) common.getMobileSession():ExpectNotification("OnSystemRequest", { requestType = "HTTP" }) end local function rpcEncryptedEncryptionRequired() common.getHMIConnection():SendNotification("BasicCommunication.OnSystemRequest", { requestType = "HTTP", fileName = "files/icon_png.png" }) common.getMobileSession():ExpectEncryptedNotification("OnSystemRequest", { requestType = "HTTP" }) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Preloaded update", common.updatePreloadedPT, { true, true }) runner.Step("Start SDL, init HMI", common.start) runner.Step("Register App", common.registerAppWOPTU) runner.Step("Activate App", common.activateApp) runner.Title("Test") runner.Step("Non-encrypted OnSystemRequest, unprotected RPC, encrypted required", rpcUnencryptedEncryptionNotRequired) runner.Step("Start RPC Service protected", common.switchRPCServiceToProtected) runner.Step("Encrypted OnSystemRequest, protected RPC, encrypted required", rpcEncryptedEncryptionRequired) runner.Title("Postconditions") runner.Step("Clean sessions", common.cleanSessions) runner.Step("Stop SDL, restore SDL settings", common.postconditions)
-- Thanks Lars -- https://github.com/webpro/dotfiles/blob/master/etc/hammerspoon local function toggleApplication(name) local app = hs.application.find(name) if not app or app:isHidden() then hs.application.launchOrFocus(name) elseif hs.application.frontmostApplication() ~= app then app:activate() else app:hide() end end local function goLeft() local switcher = hs.window.switcher.new() switcher:previous() end local function goRight() local switcher = hs.window.switcher.new() switcher:next() end hs.hotkey.bind(mash, ",", function() toggleApplication("System Preferences") end) hs.hotkey.bind(mash, "c", function() toggleApplication("Google Chrome") end) hs.hotkey.bind(mash, "f", function() toggleApplication("Finder") end) hs.hotkey.bind(mash, "p", function() toggleApplication("Parallels Desktop") end) hs.hotkey.bind(mash, "t", function() toggleApplication("iTerm") end) hs.hotkey.bind(mash, "v", function() toggleApplication("Visual Studio Code - Insiders") end) hs.hotkey.bind(mash, "h", function() goLeft() end) hs.hotkey.bind(mash, "l", function() goRight() end) -- hs.hotkey.bind(mash, "h", switcher.previousWindow()) -- hs.hotkey.bind(mash, "j", function() toggleApplication("iTerm") end) -- hs.hotkey.bind(mash, "k", function() toggleApplication("iTerm") end) -- -- set up your windowfilter -- switcher = hs.window.switcher.new() -- default windowfilter: only visible windows, all Spaces -- switcher_space = hs.window.switcher.new(hs.window.filter.new():setCurrentSpace(true):setDefaultFilter{}) -- include minimized/hidden windows, current Space only -- switcher_browsers = hs.window.switcher.new{'Safari','Google Chrome'} -- specialized switcher for your dozens of browser windows :) -- -- -- bind to hotkeys; WARNING: at least one modifier key is required! -- hs.hotkey.bind('alt','tab','Next window', function()switcher:next()end) -- hs.hotkey.bind('alt-shift','tab','Prev window', function()switcher:previous()end) -- -- -- alternatively, call .nextWindow() or .previousWindow() directly (same as hs.window.switcher.new():next()) -- hs.hotkey.bind('alt','tab','Next window',hs.window.switcher.nextWindow) -- -- you can also bind to `repeatFn` for faster traversing -- hs.hotkey.bind('alt-shift','tab','Prev window',hs.window.switcher.previousWindow,nil,hs.window.switcher.previousWindow)
Weapon.PrettyName = "PP-19 Bizon" Weapon.WeaponID = "fas2_pp19" Weapon.DamageMultiplier = 1.5 Weapon.WeaponType = WEAPON_PRIMARY
psAdjustMachine={ start=function() _update60=updateInput player.pos=getInteractPos() player.vel=vec2(0,0) player.facing=sgn(whipMachine.pos.x-player.pos.x) player.anim=startAnim(pAnimAdjust) adjustSpeed=0 makeProjVis() end, stop=function() _update60=updateDefault trajLines=nil trajEnd=nil end, update=function() if (btnp(0)) flipMachine(-1) if (btnp(1)) flipMachine(1) if btnp(btnJump) then machineType() elseif btn(2) then adjustTraj(1) elseif btn(3) then adjustTraj(-1) else adjustSpeed=0 end end, checkTransition=function() if (btnp(btnWhip)) return psGround end, draw=function() for trajLine in all(trajLines) do line(8*trajLine[1].x,8*trajLine[1].y,8*trajLine[2].x,8*trajLine[2].y,1) end end } setmetatable(psAdjustMachine,ps) function machineType() sfx(28) typeIndex=indexOf(machineTypes,whipMachine.type) typeIndex+=1 if typeIndex>#machineTypes then typeIndex=1 end setMachineType(whipMachine,machineTypes[typeIndex]) makeProjVis() end function flipMachine(facing) setMachineFacing(whipMachine,facing) player.pos=getInteractPos() player.facing=facing makeProjVis() end function adjustTraj(direction) adjustSpeed=clamp(adjustSpeed+direction*0.00025,-0.0125,0.0125) changeTraj(whipMachine,adjustSpeed) makeProjVis() end function projVisCallback(proj) if counter==2 then nextLine={proj.pos} elseif counter==4 then add(nextLine,proj.pos) if (#(nextLine[1]-nextLine[2])<2) add(lines,nextLine) nextLine=nil elseif counter==6 then counter=0 end counter+=1 trajEnd=proj.pos end function makeProjVis() lines={} trajEnd=nil counter=0 traceDummyProj(whipMachine,projVisCallback) trajLines=lines end
--[[ lvim is the global options object Linters should be filled in as strings with either a global executable or a path to an executable ]] -- Plugins lvim.plugins = { {"fatih/vim-go"}, {"folke/todo-comments.nvim", requires = "nvim-lua/plenary.nvim", config = function() require("todo-comments").setup() end, }, { "phaazon/hop.nvim", event = "BufRead", config = function() require("hop").setup() end, }, { "tpope/vim-fugitive", cmd = { "G", "Git", "Gdiffsplit", "Gread", "Gwrite", "Ggrep", "GMove", "GDelete", "GBrowse", "GRemove", "GRename", "Glgrep", "Gedit" }, ft = {"fugitive"} }, { "iamcco/markdown-preview.nvim", run = "cd app && npm install", ft = "markdown", config = function() vim.g.mkdp_auto_start = 1 end, }, { "folke/persistence.nvim", event = "VimEnter", module = "persistence", config = function() require("persistence").setup { dir = vim.fn.expand(vim.fn.stdpath "config" .. "/session/"), options = { "buffers", "curdir", "tabpages", "winsize" }, } end, }, {"folke/tokyonight.nvim"}, { "ray-x/lsp_signature.nvim", config = function() require"lsp_signature".on_attach() end, event = "InsertEnter" }, { "folke/trouble.nvim", cmd = "TroubleToggle", }, { "filipdutescu/renamer.nvim", branch = 'master', requires = { {'nvim-lua/plenary.nvim'} }, config = function() require("renamer").setup { title = '+×', show_refs = true, padding = { top = 0, bottom = 0, left = 0, right = 0, }, } end, }, { 'wfxr/minimap.vim', run = "cargo install --locked code-minimap", cmd = {"Minimap", "MinimapClose", "MinimapToggle", "MinimapRefresh", "MinimapUpdateHighlight"}, config = function () vim.cmd ("let g:minimap_width = 10") vim.cmd ("let g:minimap_auto_start = 1") vim.cmd ("let g:minimap_auto_start_win_enter = 1") end, }, } -- My own config vim.opt.backup = false -- creates a backup file vim.opt.clipboard = "unnamedplus" -- allows neovim to access the system clipboard vim.opt.cmdheight = 2 -- more space in the neovim command line for displaying messages vim.opt.completeopt = { "menuone", "noselect" } vim.opt.colorcolumn = "99999" -- fixes indentline for now vim.opt.conceallevel = 0 -- so that `` is visible in markdown files vim.opt.fileencoding = "utf-8" -- the encoding written to a file vim.opt.foldmethod = "manual" -- folding set to "expr" for treesitter based folding vim.opt.foldexpr = "" -- set to "nvim_treesitter#foldexpr()" for treesitter based folding vim.opt.guifont = "monospace:h17" -- the font used in graphical neovim applications vim.opt.hidden = true -- required to keep multiple buffers and open multiple buffers vim.opt.hlsearch = true -- highlight all matches on previous search pattern vim.opt.ignorecase = true -- ignore case in search patterns vim.opt.mouse = "a" -- allow the mouse to be used in neovim vim.opt.pumheight = 10 -- pop up menu height vim.opt.showtabline = 2 -- always show tabs vim.opt.smartcase = true -- smart case vim.opt.smartindent = true -- make indenting smarter again vim.opt.splitbelow = true -- force all horizontal splits to go below current window vim.opt.splitright = true -- force all vertical splits to go to the right of current window vim.opt.swapfile = false -- creates a swapfile vim.opt.termguicolors = true -- set term gui colors (most terminals support this) vim.opt.timeoutlen = 100 -- time to wait for a mapped sequence to complete (in milliseconds) vim.opt.title = true -- set the title of window to the value of the titlestring -- vim.opt.titlestring = "%<%F%=%l/%L - LunarVim" -- what the title of the window will be set to vim.opt.titlestring = "LunarVim" -- what the title of the window will be set to -- vim.opt.undodir = "~/.config/lvim/undo" -- set an undo directory vim.opt.undofile = true -- enable persistent undo vim.opt.updatetime = 300 -- faster completion vim.opt.writebackup = false -- if a file is being edited by another program (or was written to file while editing with another program) it is not allowed to be edited vim.opt.expandtab = true -- convert tabs to spaces vim.opt.shiftwidth = 2 -- the number of spaces inserted for each indentation vim.opt.tabstop = 2 -- insert 2 spaces for a tab vim.opt.cursorline = true -- highlight the current line vim.opt.number = true -- set numbered lines vim.opt.relativenumber = false -- set relative numbered lines vim.opt.numberwidth = 4 -- set number column width to 2 {default 4} vim.opt.signcolumn = "yes" -- always show the sign column otherwise it would shift the text each time vim.opt.wrap = true -- display lines as one long line vim.opt.spelllang = "en" vim.opt.spell = false vim.opt.scrolloff = 8 -- is one of my fav vim.opt.sidescrolloff = 8 lvim.builtin.nvimtree.quit_on_open = 1 lvim.builtin.lualine.style = "default" lvim.lsp.diagnostics.virtual_text = true lvim.builtin.dashboard.custom_header = { " +++++++ xxxxxxx xxxxxxx", " +:::::+ x:::::x x:::::x ", " +:::::+ x:::::x x:::::x ", "+++++++:::::+++++++ x:::::xx:::::x ", "+:::::::::::::::::+ x::::::::::x ", "+:::::::::::::::::+ x::::::::::x ", "+++++++:::::+++++++ x:::::xx:::::x ", " +:::::+ x:::::x x:::::x ", " +:::::+ x:::::x x:::::x ", " +++++++ xxxxxxx xxxxxxx", } local status = { ["NORMAL"] = "am very normal :)", ["INSERT"] = " inserting shit ", ["COMMAND"] = " i command thee ", ["VISUAL"] = " soo visual ", ["V-LINE"] = "very visual line ", ["V-BLOCK"] = "very visual block", ["REPLACE"] = " replacing stuff ", ["SELECT"] = " selecting stuff ", } lvim.builtin.lualine.sections.lualine_a = { { "mode", fmt = function(mode) -- local status_val = status[mode] -- if status_val == nil then -- return mode -- end return status[mode] end }, } lvim.builtin.bufferline.options = { numbers = "ordinal", view = "multiwindow", number = "superscript", modified_icon = '●', left_trunc_marker = '', right_trunc_marker = '', max_name_length = 18, max_prefix_length = 25, -- prefix used when a buffer is deduplicated tab_size = 20, diagnostics ="nvim_lsp", show_buffer_close_icons = false, show_close_icon = false, diagnostics_indicator = function(count, level) local icon = level:match("error") and "" or "" return " " .. icon .. count end, separator_style = "thin", } lvim.builtin.lualine.options.theme = "tokyonight" lvim.builtin.which_key.mappings["f"] = { "<cmd>Telescope live_grep<CR>", "Find In Folder" } lvim.builtin.which_key.mappings["m"] = { "<cmd>MinimapToggle<CR>", "Toggle Minimap" } -- lvim.builtin.which_key.mappings["r"] = { "<cmd>RnvimrToggle<CR>", "Ranger File Navigator" } lvim.builtin.which_key.mappings["a"] = {"<cmd>lua vim.lsp.buf.code_action()<cr>", "Code Action" } lvim.builtin.which_key.mappings["h"] = { name = "Hop", l = { "<cmd>HopLine<cr>", "Hop to Line" }, w = { "<cmd>HopWord<cr>", "Hop to Word" }, c = { "<cmd>HopChar1<cr>", "Hop to Character" } } lvim.builtin.which_key.mappings["T"] = { name = "Trouble Diagnostics", t = { "<cmd>TodoTelescope<cr>", "Toggle Todo Telescope Menu" }, T = { "<cmd>TodoTrouble<cr>", "Toggle Todo Trouble Menu" }, w = { "<cmd>TroubleToggle lsp_workspace_diagnostics<cr>", "Workspace" }, d = { "<cmd>TroubleToggle lsp_document_diagnostics<cr>", "Document" }, q = { "<cmd>TroubleToggle quickfix<cr>", "Show Quickfix(s)" }, l = { "<cmd>TroubleToggle loclist<cr>", "Loclist" }, r = { "<cmd>TroubleToggle lsp_references<cr>", "References" }, } lvim.builtin.which_key.mappings["t"] = {"<cmd>TroubleToggle lsp_workspace_diagnostics<cr>", "Toggle Trouble Diagnostics" } lvim.builtin.which_key.mappings["l"]["r"] = {"<cmd>lua require('renamer').rename{empty=true,}<cr>", "Rename"} lvim.transparent_window = true vim.api.nvim_set_keymap('', '<up>', '<nop>',{ noremap = true, silent = true}) vim.api.nvim_set_keymap('', '<down>', '<nop>',{ noremap = true, silent = true}) vim.api.nvim_set_keymap('', '<left>', '<nop>',{ noremap = true, silent = true}) vim.api.nvim_set_keymap('', '<right>', '<nop>',{ noremap = true, silent = true}) lvim.keys.normal_mode["gh"] = "<cmd>lua vim.lsp.diagnostic.show_line_diagnostics({ show_header = false, border = 'single' })<CR>" -- general lvim.log.level = "warn" lvim.format_on_save = true lvim.lint_on_save = true lvim.colorscheme = "tokyonight" -- keymappings [view all the defaults by pressing <leader>Lk] lvim.leader = "space" -- add your own keymapping lvim.keys.normal_mode["<C-s>"] = ":w<cr>" -- unmap a default keymapping -- lvim.keys.normal_mode["<C-Up>"] = "" -- edit a default keymapping -- lvim.keys.normal_mode["<C-q>"] = ":q<cr>" -- Use which-key to add extra bindings with the leader-key prefix -- lvim.builtin.which_key.mappings["P"] = { "<cmd>lua require'telescope'.extensions.project.project{}<CR>", "Projects" } -- lvim.builtin.which_key.mappings["t"] = { -- name = "+Trouble", -- r = { "<cmd>Trouble lsp_references<cr>", "References" }, -- f = { "<cmd>Trouble lsp_definitions<cr>", "Definitions" }, -- d = { "<cmd>Trouble lsp_document_diagnostics<cr>", "Diagnosticss" }, -- q = { "<cmd>Trouble quickfix<cr>", "QuickFix" }, -- l = { "<cmd>Trouble loclist<cr>", "LocationList" }, -- w = { "<cmd>Trouble lsp_workspace_diagnostics<cr>", "Diagnosticss" }, -- } -- After changing plugin config exit and reopen LunarVim, Run :PackerInstall :PackerCompile lvim.builtin.dashboard.active = true lvim.builtin.terminal.active = true -- lvim.builtin.dap.active = true lvim.builtin.nvimtree.side = "left" lvim.builtin.nvimtree.show_icons.git = 0 -- if you don't want all the parsers change this to a table of the ones you want lvim.builtin.treesitter.ensure_installed = "maintained" lvim.builtin.treesitter.ignore_install = { "haskell" } lvim.builtin.treesitter.highlight.enabled = true -- generic LSP settings -- you can set a custom on_attach function that will be used for all the language servers -- See <https://github.com/neovim/nvim-lspconfig#keybindings-and-completion> -- lvim.lsp.on_attach_callback = function(client, bufnr) -- local function buf_set_option(...) -- vim.api.nvim_buf_set_option(bufnr, ...) -- end -- --Enable completion triggered by <c-x><c-o> -- buf_set_option("omnifunc", "v:lua.vim.lsp.omnifunc") -- end -- set a formatter if you want to override the default lsp one (if it exists) local formatters = require "lvim.lsp.null-ls.formatters" formatters.setup { -- { -- exe = "prettier", -- filetypes = {"typescript", "javascript", "html", "css", "json"}, -- args = {} -- }, { exe = "black", filetypes = {"python"}, args = {} }, } local linters = require "lvim.lsp.null-ls.linters" linters.setup { { exe = "flake8", filetypes = {"python"} }, }
register_tile({ name = "gas_n_go_sign", top_texture = "gas_n_go_sign_edge.png", bottom_texture = "gas_n_go_sign_edge.png", left_texture = "gas_n_go_sign_edge.png", front_texture = "gas_n_go_sign_1.png", back_texture = "gas_n_go_sign_2.png", rotation = true, }) register_tile({ name = "pole_blue", all_texture = "pole_blue.png", pole = true, }) register_tile({ name = "generic_gas_station_edge", all_texture = "generic_gas_station_edge.png", }) register_tile({ name = "generic_gas_station_roof", top_texture = "generic_gas_station_roof.png", bottom_texture = "generic_gas_station_roof.png", left_texture = "generic_gas_station_edge.png^[transformR90", right_texture = "generic_gas_station_edge.png^[transformR90", front_texture = "generic_gas_station_edge.png^[transformR90", back_texture = "generic_gas_station_edge.png^[transformR90", }) register_tile({ name = "glass", all_texture = "glass.png", glass = true, }) register_tile({ name = "generic_store_isle_empty", top_texture = "generic_store_isle_empty_top.png", bottom_texture = "generic_store_isle_empty_top.png", right_texture = "generic_store_isle_empty_side.png", left_texture = "generic_store_isle_empty_side.png", front_texture = "generic_store_isle_empty_front.png", back_texture = "generic_store_isle_empty_front.png", pixel_box_texture_size = 32, pixel_box = { -- center column { 15, 0, 0, 17, 32, 32 }, -- bottom shelf { 0, 30, 0, 32, 32, 32 }, -- top shelf { 0, 14, 0, 32, 16, 32 }, } }) register_tile({ name = "generic_store_isle_end_empty", top_texture = "generic_store_isle_end_empty_top.png", bottom_texture = "generic_store_isle_end_empty_top.png", right_texture = "generic_store_isle_end_empty_side.png^[transformFX", left_texture = "generic_store_isle_end_empty_side.png", front_texture = "generic_store_isle_end_empty_front.png", back_texture = "generic_store_isle_end_empty_front.png", pixel_box_texture_size = 32, pixel_box = { -- center column { 0, 0, 0, 2, 32, 32 }, -- bottom shelf { 0, 30, 0, 16, 32, 32 }, -- top shelf { 0, 14, 0, 16, 16, 32 }, } }) register_tile({ name = "chainlink_fence", left_texture = "chainlink_fence.png", right_texture = "chainlink_fence.png", front_texture = "chainlink_fence.png", back_texture = "chainlink_fence.png", fence = true, fence_connections = {"chainlink_fence", "chainlink_fence_pole"} }) register_tile({ name = "chainlink_fence_pole", all_texture = "chainlink_fence_pole.png", pole = true, }) register_tile({ name = "guardrail", all_texture = "guardrail.png", pixel_box_specific = { type = "connected", fixed = { { -0.1, -0.5, -0.1, 0.1, 0.5, 0.1 }, }, connect_front = { { 0, -0.1875, -0.5, 0, 0.4375, 0 }, { -0.0625, 0.1875, -0.5, 0.0625, 0.3125, 0 }, { -0.0625, -0.0625, -0.5, 0.0625, 0.0625, 0 }, }, -- z- connect_back = { { 0, -0.1875, 0.5, 0, 0.4375, 0 }, { -0.0625, 0.1875, 0.5, 0.0625, 0.3125, 0 }, { -0.0625, -0.0625, 0.5, 0.0625, 0.0625, 0 }, }, -- z+ connect_left = { { -0.5, -0.1875, 0, 0, 0.4375, 0 }, { -0.5, 0.1875, -0.0625, 0, 0.3125, 0.0625 }, { -0.5, -0.0625, -0.0625, 0, 0.0625, 0.0625 }, }, -- x- connect_right = { { 0.5, -0.1875, 0, 0, 0.4375, 0 }, { 0.5, 0.1875, -0.0625, 0, 0.3125, 0.0625 }, { 0.5, -0.0625, -0.0625, 0, 0.0625, 0.0625 }, }, -- x+ }, connects_to = {"guardrail"}, climb_over = true, }) register_tile({ name = "jersey_barrier", all_texture = "concrete.png", pixel_box_specific = { type = "connected", fixed = { { -0.35, -0.5, -0.35, 0.35, -0.4, 0.35 }, { -0.15, -0.5, -0.15, 0.15, 0.5, 0.15 } }, connect_front = { { -0.35, -0.5, -0.5, 0.35, -0.4, 0.35 }, { -0.15, -0.5, -0.5, 0.15, 0.5, 0.15 } }, -- z- connect_back = { { -0.35, -0.5, -0.35, 0.35, -0.4, 0.5 }, { -0.15, -0.5, -0.15, 0.15, 0.5, 0.5 } }, -- z+ connect_left = { { -0.5, -0.5, -0.35, 0.35, -0.4, 0.35 }, { -0.5, -0.5, -0.15, 0.15, 0.5, 0.15 } }, -- x- connect_right = { { -0.35, -0.5, -0.35, 0.5, -0.4, 0.35 }, { -0.15, -0.5, -0.15, 0.5, 0.5, 0.15 } }, -- x+ }, connects_to = {"jersey_barrier"}, climb_over = true, }) register_tile({ name = "gas_pump_bottom", top_texture = "gas_pump_top_side.png", bottom_texture = "gas_pump_top_side.png", right_texture = "gas_pump_bottom_side.png", left_texture = "gas_pump_bottom_side.png", front_texture = "gas_pump_bottom_front.png", back_texture = "gas_pump_bottom_front.png", pixel_box_texture_size = 32, pixel_box = { { 7, 0, 0, 25, 32, 32 }, } }) register_tile({ name = "gas_pump_top", top_texture = "gas_pump_top_side.png", bottom_texture = "gas_pump_top_side.png", right_texture = "gas_pump_top_side.png", left_texture = "gas_pump_top_side.png", front_texture = "gas_pump_top_front.png", back_texture = "gas_pump_top_front.png", pixel_box_texture_size = 32, pixel_box = { -- base { 7, 17, 0, 25, 32, 32 }, -- left support { 7, 0, 0, 25, 17, 2 }, -- right support { 7, 0, 30, 25, 17, 32 }, -- cover support { 7, 0, 0, 25, 2, 32 }, -- price sign { 16, 5, 4, 16, 17, 28 }, } }) register_tile({ name = "generic_counter", all_texture = "generic_counter.png", }) register_tile({ name = "outer_wall_blue", all_texture = "outer_wall_blue.png" }) register_tile({ name = "outer_wall_black", all_texture = "outer_wall_black.png" }) register_tile({ name = "outer_wall_green", all_texture = "outer_wall_green.png" }) register_tile({ name = "outer_wall_grey", all_texture = "outer_wall_grey.png" }) register_tile({ name = "outer_wall_orange", all_texture = "outer_wall_orange.png" }) register_tile({ name = "outer_wall_red", all_texture = "outer_wall_red.png" }) register_tile({ name = "outer_wall_white", all_texture = "outer_wall_white.png" }) register_tile({ name = "outer_wall_yellow", all_texture = "outer_wall_yellow.png" }) register_tile({ name = "ladder", front_texture = "ladder.png", back_texture = "ladder.png", left_texture = "ladder.png", right_texture = "ladder.png", top_texture = "ladder_top.png", bottom_texture = "ladder_top.png^[transformFY", ladder = true, pixel_box_texture_size = 32, pixel_box = { -- right side rail { 0, 0, 0, 3, 32, 3 }, -- left side rail { 29, 0, 0, 32, 32, 3 }, -- top rung { 3, 7, 0, 29, 9, 2 }, -- bottom rung { 3, 23, 0, 29, 25, 2 }, } })
local gpick = require('gpick') local options = {} local optionsUpdate = function(params) options.upperCase = params:getString('gpick.options.hex_case', 'upper') == 'upper' end gpick:setOptionChangeCallback(optionsUpdate) return options
--- -- A demonstration of pipes. --look for packages one folder up. package.path = package.path .. ";;;../?.lua" local sched=require 'sched' --require "log".setlevel('ALL') local stream=require 'stream' local astream=stream.new() -- sender -- sched.run(function() for i=1, 10 do local s='*'..i..'*' print('writing', s) astream:write(tostring(s)) sched.sleep (1) end end) --receiver sched.run(function() while true do sched.sleep(3) print("received", astream:read()) end end) sched.loop()
local allowCountdown = false; function onCreate() setProperty('gf.visible', false); makeLuaSprite('black', 'stages/intros/black', 0,0) setObjectCamera('black', 'camother') addLuaSprite('black', false) makeLuaSprite('circle', 'stages/intros/CircleTripleTrouble', 1280,0) setObjectCamera('circle', 'camother') addLuaSprite('circle', true) makeLuaSprite('text', 'stages/intros/TextTripleTrouble', -1280,0) setObjectCamera('text', 'camother') addLuaSprite('text', true) end function onStartCountdown() if allowCountdown == false then doTweenX('circlemove', 'circle', 0, 1, 'linear') doTweenX('textmove', 'text', 0, 1, 'linear') allowCountdown = true return Function_Stop; end return Function_Continue; end function onCountdownTick(counter) if counter == 0 then playSound('intro3', 1) end if counter == 1 then setProperty('countdownReady.x', -5000); playSound('intro2', 1) end if counter == 2 then setProperty('countdownSet.x', -5000); playSound('intro1', 1) end if counter == 3 then setProperty('countdownGo.x', -5000); playSound('introGo', 1) end end function onEvent(name) if name == 'switchnotes1' then noteTweenX('leftx', 4, defaultOpponentStrumX0, 0.01, 'easeInOut'); noteTweenX('downx', 5, defaultOpponentStrumX1, 0.01, 'easeInOut') noteTweenX('upx', 6, defaultOpponentStrumX2, 0.01, 'easeInOut') noteTweenX('rightx', 7, defaultOpponentStrumX3, 0.01, 'easeInOut') noteTweenX('oppleftx', 0, defaultPlayerStrumX0, 0.01, 'easeInOut'); noteTweenX('oppdownx', 1, defaultPlayerStrumX1, 0.01, 'easeInOut') noteTweenX('oppupx', 2, defaultPlayerStrumX2, 0.01, 'easeInOut') noteTweenX('opprightx', 3, defaultPlayerStrumX3, 0.01, 'easeInOut') end if name == 'switchnotes2' then noteTweenX('leftx', 4, defaultPlayerStrumX0, 0.01, 'easeInOut'); noteTweenX('downx', 5, defaultPlayerStrumX1, 0.01, 'easeInOut') noteTweenX('upx', 6, defaultPlayerStrumX2, 0.01, 'easeInOut') noteTweenX('rightx', 7, defaultPlayerStrumX3, 0.01, 'easeInOut') noteTweenX('oppleftx', 0, defaultOpponentStrumX0, 0.01, 'easeInOut'); noteTweenX('oppdownx', 1, defaultOpponentStrumX1, 0.01, 'easeInOut') noteTweenX('oppupx', 2, defaultOpponentStrumX2, 0.01, 'easeInOut') noteTweenX('opprightx', 3, defaultOpponentStrumX3, 0.01, 'easeInOut') end end function onTweenCompleted(tag) if tag == 'circlemove' then runTimer('wait', 1, 1) startCountdown() end end function onTimerCompleted(tag) if tag == 'wait' then doTweenAlpha('circlealpha', 'circle', 0, 1, 'linear') doTweenAlpha('textalpha', 'text', 0, 1, 'linear') doTweenAlpha('blackalpha', 'black', 0, 1, 'linear') end end function onEndSong() if isStoryMode and not seenCutscene then startVideo('soundtestcodes') seenCutscene = true return Function_Stop end return Function_Continue end
--- @classmod core.graphics.ShaderProgramSet --- ShaderProgramSets group programs into families. -- -- A model just needs to save the family name, which is then resolved by -- the used shader program set. -- E.g. there can be a family for static and one for animated models. -- -- Some effects, like shadow mapping, require models to be rendered -- with a special shader programs, that are adapted to the effect. -- -- @see core.graphics.ShaderProgram local engine = require 'engine' local class = require 'middleclass' local Object = class.Object local Scheduler = require 'core/Scheduler' local ShaderProgram = require 'core/graphics/ShaderProgram' local ShaderProgramSet = class('core/graphics/ShaderProgramSet') --- -- @param[type=core.graphics.ShaderProgram] defaultShaderProgram -- Shader program which is used as a fallback, if a the required family is not -- available in this set. -- function ShaderProgramSet:initialize( defaultShaderProgram ) assert(Object.isInstanceOf(defaultShaderProgram, ShaderProgram), 'Must be initialized with a default shader program.') self.handle = Scheduler.awaitCall(engine.CreateShaderProgramSet, defaultShaderProgram.handle) end function ShaderProgramSet:destroy() Scheduler.blindCall(engine.DestroyShaderProgramSet, self.handle) self.handle = nil end --- Register a shader program for a specific family. function ShaderProgramSet:setFamily( name, shaderProgram ) assert(Object.isInstanceOf(shaderProgram, ShaderProgram), 'Must be called with a shader program.') Scheduler.blindCall(engine.SetShaderProgramFamily, self.handle, name, shaderProgram.handle) end return ShaderProgramSet
require("lib/core") x = 0 for i=0, 10, 1 do x = x + 5 print(i) end assert(x, 50)
local Common = {} function Common.MakeSoundHandler(state, fxSource, effectPath) return function(self, eventType, eventData) local fx = cache:GetResource("Sound", effectPath) state:GetObject(fxSource):Play(fx) end end function Common.ButtonEvents(state, element, buttonName, clickMethod, hoverMethod) local button = element:GetChild(buttonName, true) if button ~= nil then state:SubscribeToEvent(button, "Released", clickMethod) state:SubscribeToEvent(button, "HoverBegin", hoverMethod) end end return Common
--[[ module: NightState author: DylanYang time: 2021-02-23 14:20:25 idea: advance: ]] local DayState = require("patterns.behavioral.state.DayState") local interface = require("patterns.behavioral.state.IState") local _M = Class("NightState", interface) _M.singleton = true local public = _M.public function public:DoClock(context, hour) -- 设置时间 if hour >= 9 and hour < 17 then return context:ChangeState(DayState.new()) end end function public:DoUse(context) -- 使用金库 context:RecordLog("紧急:晚上使用金库!") end function public:DoAlarm(context) -- 按下警铃 context:CallSecurityCenter("按下警铃(晚上)") end function public:DoPhone(context) -- 正常通话 context:CallSecurityCenter("晚上的通话录音") end function public:ToString() return "[晚上]" end function public:RandomTest() if random.nextFloat() < 0.5 then return 0 else local ran = random.nextFloat() if ran < 0.35 then return 1 elseif ran < 0.7 then return 2 else return 3 end end end return _M
local a = Const("a") local f = Const("f") local x = Var(0) assert(not f(a):has_free_var(0)) assert(f(a, x):has_free_var(0)) assert(not f(a, x):has_free_var(1, 3)) assert(f(a, Var(1)):has_free_var(1, 3)) assert(f(a, Var(2)):has_free_var(1, 3)) assert(not f(a, Var(3)):has_free_var(1, 3)) assert(not f(a, Var(4)):has_free_var(1, 3)) assert(f(a, Var(2)):lower_free_vars(2) == f(a, Var(0)))
local this = {} --------------------------------------------------------------------------------- -- Lists --------------------------------------------------------------------------------- this.Times = { } this.RouteSets = { } --------------------------------------------------------------------------------- -- Internal Functions --------------------------------------------------------------------------------- -- Get time table this.GetTimes = function( locationName ) return this.Times[locationName] end -- Get route sets table this.GetRouteSets = function( locationName ) return this.RouteSets[locationName] end --------------------------------------------------------------------------------- -- END --------------------------------------------------------------------------------- return this
return { name = "Quad9-Recommended", label = _("Quad 9 (Recommended)"), resolver_url = "https://dns.quad9.net/dns-query", bootstrap_dns = "9.9.9.9,149.112.112.112" }
--[[ Copyright (C) 2013 simplex This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]]-- local Lambda = wickerrequire 'paradigms.functional' local Logic = wickerrequire 'lib.logic' local Pred = wickerrequire 'lib.predicates' local myutils = wickerrequire 'utils' local ProtoComponent = pkgrequire 'base' local ConditionalTasker = Class(ProtoComponent, function(self) ProtoComponent._ctor(self) --[[ -- Main configurable parameters. -- Defines class defaults. --]] -- How long a new task will take to complete, in seconds. self:SetFullDelay(math.huge) -- Condition for tasking. self:SetConditionFn(Lambda.True) -- Task completion callback. self:SetOnCompleteFn(Lambda.Nil) -- Receives the entity, the status of the start attempt, -- as well as one more (optional) extra return value from the condition. self:SetOnTryStartFn(Lambda.Nil) --[[ -- End of main configurable parameters. --]] function self.TryStarter(inst) if Pred.IsOk(inst) and inst.components[self:GetComponentName()] then inst.components[self:GetComponentName()]:TryStart() end end end) function ConditionalTasker:new(inst) self.task = nil self.paused_delay = math.huge self.inst:DoTaskInTime(0, function(inst) if self:IsOkComponent() then self:TryStart() end end) end function ConditionalTasker:SetConditionFn(f) assert(f == nil or Pred.IsCallable(f)) self.condition_fn = f return f end function ConditionalTasker:GetConditionFn() assert( self.condition_fn ) return self.condition_fn end -- The return value is used as a boolean test for whether the tasker should immediately TryStart() again or not. function ConditionalTasker:SetOnCompleteFn(f) assert(f == nil or Pred.IsCallable(f)) self.oncomplete_fn = f return f end function ConditionalTasker:GetOnCompleteFn() assert( self.oncomplete_fn ) return self.oncomplete_fn end -- Receives a boolean as a second argument indicating whether the start was successful or not -- (i.e., if the condition passed or not) -- Receives as a third parameter the second return value from the condition test (if any). function ConditionalTasker:SetOnTryStartFn(f) assert(f == nil or Pred.IsCallable(f)) self.ontrystart_fn = f return f end function ConditionalTasker:GetOnTryStartFn(f) assert( self.ontrystart_fn ) return self.ontrystart_fn end function ConditionalTasker:SatisfiesCondition() return self:GetConditionFn()(self.inst) end function ConditionalTasker:HasTask() assert( Logic.IfAndOnlyIf(self:GetTargetTime(), not self.paused_delay) ) assert( Logic.Implies(self.task, self:GetTargetTime()) ) return self.task and true or false end function ConditionalTasker:GetTentativeRemainingTime() -- Just for the sanity checks. self:HasTask() return self.paused_delay or math.max(0, self:GetTargetTime() - GetTime()) end function ConditionalTasker:GetFactoredRemainingTime() return myutils.time.FactorTime( self:GetTentativeRemainingTime() ) end function ConditionalTasker:GetFullDelay() return self.full_delay end function ConditionalTasker:SetFullDelay(delay) assert(Pred.IsPositiveNumber(delay)) self.full_delay = delay return delay end function ConditionalTasker:GetTargetTime() return self.targettime end function ConditionalTasker:SetTargetTime(dt) assert(dt == nil or Pred.IsNumber(dt)) self.targettime = dt return dt end function ConditionalTasker:OnComplete() if self:SatisfiesCondition() then if self:GetOnCompleteFn()(self.inst) then self:TryStart() end else self:TryStart() end end function ConditionalTasker:GetDebugString() local t if not self:SatisfiesCondition() then t = {'(inactive)'} else t = {} if self:HasTask() then table.insert(t, '(active at ') table.insert(t, tostring(self:GetFactoredRemainingTime())) table.insert(t, ' remaining)') else if self:GetTargetTime() then table.insert(t, '(background updating at ') else table.insert(t, '(paused at ') end table.insert(t, tostring(self:GetFactoredRemainingTime())) table.insert(t, ' remaining)') end end return table.concat(t) end function ConditionalTasker:StartTask() if not self:HasTask() and self:GetTargetTime() < math.huge and self:IsOkComponent() -- and not self.inst:IsAsleep() then self:DebugSay('StartTask()') self.task = self.inst:DoTaskInTime(self:GetTentativeRemainingTime(), function() if self:IsOkComponent() then self:OnComplete() end end) end end function ConditionalTasker:StopTask() if self:HasTask() then self:DebugSay('StopTask()') self.task:Cancel() self.task = nil end end function ConditionalTasker:Unpause() -- Just for the sanity checks. self:HasTask() if not self:GetTargetTime() then assert( Pred.IsNonNegativeNumber(self.paused_delay) ) self:SetTargetTime(GetTime() + self.paused_delay) self.paused_delay = nil self:StartTask() end end function ConditionalTasker:Pause() -- Just for the sanity checks. self:HasTask() if self:GetTargetTime() then self:DebugSay( 'Pause()' ) self:StopTask() self.paused_delay = math.max(0, self:GetTargetTime() - GetTime()) self:SetTargetTime(nil) end end function ConditionalTasker:Reboot(daily) self:DebugSay('Reboot()', daily and ' DAILY' or nil) self:Pause() if self:SatisfiesCondition() then if self.paused_delay <= 0 then self:OnComplete() else if self.paused_delay == math.huge then self.paused_delay = self:GetFullDelay() end self:Unpause() end else self.paused_delay = math.huge end if self:Debug() then self:Say( self:GetDebugString() ) end end function ConditionalTasker:TryStart() if not self:IsOkComponent() then return end local b, data = self:SatisfiesCondition() self:DebugSay('TryStart() ', b and "passed" or "failed") self:GetOnTryStartFn()(self.inst, b, data) self:Reboot() end ConditionalTasker.Stop = ConditionalTasker.Pause function ConditionalTasker:DoDelta(dt) if self:Debug() then self:Say( 'DoDelta(', myutils.time.FactorTime(dt), ')' ) end self:Pause() self.paused_delay = math.max(0, self.paused_delay - dt) self:Reboot() return dt end function ConditionalTasker:LongUpdate(dt) self:DoDelta(dt) end function ConditionalTasker:OnEntityWake() self:DebugSay('OnEntityWake()') self:Reboot() end function ConditionalTasker:OnEntitySleep() self:DebugSay('OnEntitySleep()') self:Reboot() end local function dump_measure(x) assert(Pred.IsNonNegativeNumber(x)) return x == math.huge and -1 or x end local function load_measure(x) if x == nil or Pred.IsNonNegativeNumber(x) then return x else return math.huge end end function ConditionalTasker:OnSave() self:DebugSay('OnSave()') self:Pause() local data = { conditional_tasker_paused_delay = dump_measure(self.paused_delay), } self:Reboot() return data end function ConditionalTasker:OnLoad(data) self:DebugSay('OnLoad()') self:Stop() if data then self.paused_delay = math.min(load_measure(data.conditional_tasker_paused_delay) or math.huge, self:GetFullDelay()) end self:TryStart() end return ConditionalTasker
-- Dorea Plugin Loader -- YuKun Liu <mrxzx.info@gmail.com> -- https://dorea.mrxzx.info/ if not ROOT_PATH then ROOT_PATH = "." end if not PLUGIN_LOADER then PLUGIN_LOADER = {} end if not LOGGER_IN then LOGGER_IN = {} LOGGER_IN.info = function (message) print("[INFO] " .. message) end LOGGER_IN.trace = function (message) print("[TRACE] " .. message) end LOGGER_IN.debug = function (message) print("[DEBUG] " .. message) end LOGGER_IN.warn = function (message) print("[WARN] " .. message) end LOGGER_IN.error = function (message) print("[ERROR] " .. message) end end if not DB_MANAGER then DB_MANAGER = {} DB_MANAGER.select = function (_, db_name) LOGGER_IN.info("selet to `" .. db_name .. "`") end DB_MANAGER.setex = function (_, key, value, expire) LOGGER_IN.info("set data: " .. key .. ": " .. value .. " [" .. expire .. "]") end DB_MANAGER.get = function (_, key) LOGGER_IN.info("get data: " .. key) end DB_MANAGER.delete = function (_, key) LOGGER_IN.info("delete data: " .. key) end DB_MANAGER.cache = function (_, info) local state, dump = pcall(require, "dump") local message = "[> object <]" if state and dump ~= nil then message = dump(info) end LOGGER_IN.info("send a cache operation: " .. message) end end package.path = ROOT_PATH .. "/library/?.lua;" .. package.path MANAGER = require("manager") -- include plugin here for key, val in pairs(PLUGIN_LOADER) do MANAGER.load(key, val) end -- end to include MANAGER.load("example", {}) MANAGER.require(ROOT_PATH) -- rust call
local cjson = require 'cjson.safe' local logger = require 'hj212.logger' local base = require 'hj212.calc.base' local mgr = require 'hj212.calc.manager' local types = require 'hj212.types' local data_list = require 'hj212.calc.data_list' local LA = base:subclass('hj212.calc.LA') --[[ -- The COU is couting all sample values -- The AVG is COU / sample count --]] local max_sample_per_min = 30 function LA:initialize(station, id, mask, min, max, zs_calc) base.initialize(self, station, id, mask, min, max, zs_calc) --- Current hour samples self._hour_sample_list = data_list:new('timestamp', nil, max_sample_per_min * 60, function() self:log('error', 'LA hour sample data droped') end) --- Current day samples self._day_sample_list = data_list:new('timestamp', nil, max_sample_per_min * 60 * 24, function() self:log('error', 'LA day sample data droped') end) end function LA:load_from_db() base.load_from_db(self) if not self._db then return end local day_start_time = self:day_start() self:debug('load day sample data since', os.date('%c', day_start_time)) local sample_list, err = self._db:read_samples(day_start_time, self._start) if sample_list then self._day_sample_list:init(sample_list) local first_sample = self._day_sample_list:first() if first_sample then self:debug('loaded first day sample', os.date('%c', math.floor(first_sample.timestamp))) end else self:log('error', err) end local hour_start_time = self:hour_start() self:debug('load hour sample data since', os.date('%c', hour_start_time)) local sample_list, err = self._db:read_samples(hour_start_time, self._start) if sample_list then self._hour_sample_list:init(sample_list) local first_sample = self._hour_sample_list:first() if first_sample then self:debug('loaded first hour sample', os.date('%c', math.floor(first_sample.timestamp))) end else self:log('error', err) end end function LA:push(value, timestamp, value_z, flag, quality, ex_vals) if timestamp < self._last_calc_time then return nil, 'older value skipped ts:'..timestamp..' last:'..self._last_calc_time end return base.push(self, value, timestamp, value_z, flag, quality, ex_vals) end local function flag_can_calc(flag) if flag == nil then return true end if flag == types.FLAG.Normal or flag == types.FLAG.Overproof then return true end return false end local function get_la_value(list, percent) local count = #list if count == 0 then return 0 end local c = math.floor(count * (100 - percent) / 100) if c == 0 then c = 1 end return list[c].value or 0 end local function calc_la(list) local calc_list = {} for i, v in ipairs(list) do if flag_can_calc(v.flag) then calc_list[#calc_list + 1] = v end end local la = { L5 = 0, L10 = 0, L50 = 0, L90 = 0, L95 = 0, } if #calc_list == 0 then return la end table.sort(calc_list, function(a, b) return (a.value or 0) < (b.value or 0) end) la.L5 = get_la_value(calc_list, 5) la.L10 = get_la_value(calc_list, 10) la.L50 = get_la_value(calc_list, 50) la.L90 = get_la_value(calc_list, 90) la.L95 = get_la_value(calc_list, 95) return la end local function calc_la_day(list, is_day) local day_list = {} local night_list = {} for i, v in ipairs(list) do if is_day(v.timestamp) then day_list[#day_list + 1] = v else night_list[#night_list + 1] = v end end local la = calc_la(list) la.DAY = calc_la(day_list) la.NIGHT = calc_la(night_list) return la end local function calc_sample(list, start, etime) local flag = #list == 0 and types.FLAG.Connection or nil local val_cou = 0 local val_min = #list > 0 and list[1].value or 0 local val_max = val_min local val_t = 0 local last = start - 0.0001 -- make sure the asserts work properly for i, v in ipairs(list) do if flag_can_calc(v.flag) then assert(v.timestamp > last, string.format('Timestamp issue:%f\t%f', v.timestamp, last)) last = v.timestamp local val = v.value or 0 assert(type(val) == 'number', 'Type is not number but '..type(val)) val_min = val < val_min and val or val_min val_max = val > val_max and val or val_max val_cou = val_cou + (10 ^ (0.1 * val)) val_t = val_t + 1 --logger.log('debug', 'LA.calc_sample', val_cou, v.cou or val, val_min, val_max) end end local val_avg = val_t > 0 and 10 * math.log((val_cou / val_t), 10) or 0 --logger.log('debug', 'LA.calc_sample', #list, val_cou, val_avg, val_min, val_max) return { cou = val_cou, avg = val_avg, min = val_min, max = val_max, flag = flag, stime = start, -- Duration start etime = etime, -- Duration end LC = val_t, } end function LA:on_min_trigger(now, duration) local sample_list = self._sample_list local last = self._min_list:find(now) if last then return last end local start = base.calc_list_stime(sample_list, now, duration) while start < (now - duration) do local etime = start + duration local list = sample_list:pop(etime) if self._min_list:find(etime) then self:log('error', "LA: older sample value skipped", etime) local cjson = require 'cjson.safe' for _, v in pairs(list) do self:log('error', ' Skip: '..cjson.encode(v)) end else self:log('debug', 'LA: calculate older sample value', start, etime, #list, list[1].timestamp) local val = calc_sample(list, start, etime) self._min_list:append(val) end start = base.calc_list_stime(sample_list, now, duration) end assert(start == now - duration) local list = sample_list:pop(now) local val = calc_sample(list, start, now) local ex_vals, err = cjson.encode(calc_la(list)) if not ex_vals then self:log('error', 'Encode ex_vals failed', err) end val.ex_vals = ex_vals assert(self._min_list:append(val)) return val end local function calc_cou(list, start, etime) local flag = #list == 0 and types.FLAG.Connection or nil local last = start - 0.0001 -- make sure etime assets works properly local val_cou = 0 local val_t = 0 local val_min = #list > 0 and list[1].min local val_max = #list > 0 and list[1].max for i, v in ipairs(list) do assert(v.stime >= start, "Start time issue:"..v.stime..'\t'..start) assert(v.etime >= last, "Last time issue:"..v.etime..'\t'..last) last = v.etime val_min = v.min < val_min and v.min or val_min val_max = v.max > val_max and v.max or val_max val_cou = val_cou + v.cou val_t = val_t + v.LC end assert(last <= etime, 'last:'..last..'\tetime:'..etime) local val_avg = val_t > 0 and 10 * math.log((val_cou / val_t), 10) or 0 return { cou = val_cou, avg = val_avg, min = val_min, max = val_max, flag = flag, stime = start, etime = etime, LC = val_t, } end function LA:on_hour_trigger(now, duration) local sample_list = self._min_list local last = self._hour_list:find(now) if last then return last end local start = base.calc_list_stime(sample_list, now, duration) while start < (now - duration) do local etime = start + duration local list = sample_list:pop(etime) if self._hour_list:find(etime) then self:log('error', "LA: older min value skipped") local cjson = require 'cjson.safe' for _, v in pairs(list) do self:log('error', ' Skip: '..cjson.encode(v)) end else self:log('debug', 'LA: calculate older min value', start, etime, #list, list[1].stime) local val = calc_cou(list, start, etime) assert(self._hour_list:append(val)) end start = base.calc_list_stime(sample_list, now, duration) end assert(start == now - duration) local list = sample_list:pop(now) local val = calc_cou(list, start, now) local slist = self._hour_sample_list:pop(now) local ex_vals, err = cjson.encode(calc_la(slist)) if not ex_vals then self:log('error', 'Encode ex_vals failed', err) end val.ex_vals = ex_vals assert(self._hour_list:append(val)) return val end function LA:on_day_trigger(now, duration) local sample_list = self._hour_list local last = self._day_list:find(now) if last then return last end local start = base.calc_list_stime(sample_list, now, duration) while start < (now - duration) do local etime = start + duration local list = sample_list:pop(etime) if self._day_list:find(etime) then self:log('error', "LA: older hour value skipped") local cjson = require 'cjson.safe' for _, v in pairs(list) do self:log('error', ' Skip: '..cjson.encode(v)) end else self:log('debug', 'LA: calculate older hour value', start, etime, #list, list[1].stime) local val = calc_cou(list, start, etime) assert(self._day_list:append(val)) end start = base.calc_list_stime(sample_list, now, duration) end assert(start == now - duration) local list = sample_list:pop(now) local val = calc_cou(list, start, now) local slist = self._day_sample_list:pop(now) local station_la = self._station:LA() local ex_vals, err = cjson.encode(calc_la_day(slist, station_la.is_day)) if not ex_vals then self:log('error', 'Encode ex_vals failed', err) end val.ex_vals = ex_vals assert(self._day_list:append(val)) return val end return LA
require 'nn' require 'cunn' require 'gvnn' require 'optim' grad = require 'autograd' require('DataReader.lua') require('createModelBasicSinglescale.lua') require('createModelBasicMultiscale.lua') require('createModelSiameseSinglescale.lua') require('createModelSiameseMultiscale.lua') local c = require 'trepl.colorize' require 'opts.lua' opt = opt_parse(arg) print(opt) torch.manualSeed(opt.manualSeed) cutorch.setDevice(1) torch.setdefaulttensortype('torch.FloatTensor') if opt.model_no == 1 then model_name = 'Basic Singlescale' elseif opt.model_no == 2 then model_name = 'Basic Multiscale' elseif opt.model_no == 3 then model_name = 'Siamese Singlescale' elseif opt.model_no == 4 then model_name = 'Siamese Multiscale' end print(c.blue '==>' .. ' create model: ' .. model_name) if opt.model_no == 1 then Model = createModelBasicSinglescale(opt.height, opt.width) criterion = require('bss_criterion') elseif opt.model_no == 2 then Model = createModelBasicMultiscale(opt.height, opt.width) criterion = require('bms_criterion') elseif opt.model_no == 3 then Model = createModelSiameseSinglescale(opt.height, opt.width) criterion = require('sss_criterion') elseif opt.model_no == 4 then Model = createModelSiameseMultiscale(opt.height, opt.width) criterion = require('sms_criterion') end print(c.blue '==>' .. ' loading data') my_dataset = DataReader(opt.data_root, opt.num_channel, opt.height, opt.width, opt.tr_num, opt.batch_size, opt.gpu) if opt.gpu == 1 then Model:cuda() criterion:cuda() end --print(Model) optimState = {} optimiser = optim.adam parameters, gradParameters = Model:getParameters() print(string.format('number of parameters: %d', parameters:nElement())) optimConfig = { learningRate = opt.learningRate, beta1 = opt.beta1, beta2 = opt.beta2, epsilon = opt.epsilon } if opt.pretrained == 1 then local e_id = 50 print(c.blue '==>' .. ' loading parameters') local param_file = string.format('param_epoch_%d.t7', e_id) --local bn_file = string.format('bn_meanvar_epoch_%d.t7', e_id) local params = torch.load(paths.concat(opt.pretrained_root, param_file)) assert(params:nElement() == parameters:nElement(), string.format('%s: %d vs %d', 'loading parameters: dimension mismatch.', params:nElement(), parameters:nElement())) parameters:copy(params) -- load BN mean and std --local bn_mean, bn_std = table.unpack(torch.load(paths.concat(opt.pretrained_root, bn_file))) --for k, v in pairs(Model:findModules('nn.SpatialBatchNormalization')) do -- v.running_mean:copy(bn_mean[k]) -- v.running_var:copy(bn_std[k]) --end end epoch = epoch or 1 function train_siamese_singlescale() Model:training() -- learning rate decay if epoch == 10 then optimConfig.learningRate = optimConfig.learningRate / 2 end if epoch > 10 and (epoch - 10) % opt.epoch_step == 0 then optimConfig.learningRate = optimConfig.learningRate / 2 end print(c.blue '==>' .. " Epoch # " .. epoch .. ' [batch_size = ' .. opt.batch_size .. ']') local tic = torch.tic() local train_loss = 0 for iter = 1, opt.niter do xlua.progress(iter, opt.niter) local inputs_L, inputs_R, zero_target = my_dataset:next_batch() local inputTable = { inputs_L, inputs_R } local targetTable = { inputs_L, inputs_R, zero_target, zero_target, zero_target, zero_target } local feval = function(x) if x ~= parameters then parameters:copy(x) end --gradParameters:zero() Model:zeroGradParameters() local outputs = Model:forward(inputTable) local err = criterion:forward(outputs, targetTable) local dparams = criterion:backward(outputs, targetTable) Model:backward(inputTable, dparams) return err, gradParameters end local _, loss = optimiser(feval, parameters, optimConfig, optimState) train_loss = train_loss + loss[1] print(('Train loss ' .. loss[1])) end print(('Train loss: ' .. c.cyan '%.4f' .. ' \t time: %.2f s\t grad/param norm = %6.4e\t learning rate: %f'):format(train_loss / opt.niter, torch.toc(tic), gradParameters:norm() / parameters:norm(), optimConfig.learningRate)) trainLogger:add { train_loss / opt.niter, optimConfig.learningRate } epoch = epoch + 1 end function train_siamese_multiscale() Model:training() -- learning rate decay if epoch == 10 then optimConfig.learningRate = optimConfig.learningRate / 2 end if epoch > 10 and (epoch - 10) % opt.epoch_step == 0 then optimConfig.learningRate = optimConfig.learningRate / 2 end print(c.blue '==>' .. " Epoch # " .. epoch .. ' [batch_size = ' .. opt.batch_size .. ']') local tic = torch.tic() local train_loss = 0 for iter = 1, opt.niter do xlua.progress(iter, opt.niter) local inputs_L1, inputs_L2, _, inputs_R1, inputs_R2, _, zero_target1, zero_target2, _ = my_dataset:next_batch_multiscale() local inputTable = { inputs_L1, inputs_L2, inputs_R1, inputs_R2 } local targetTable = { inputs_L1, inputs_R1, zero_target1, zero_target1, zero_target1, zero_target1, inputs_L2, inputs_R2, zero_target2, zero_target2, zero_target2, zero_target2} local feval = function(x) if x ~= parameters then parameters:copy(x) end --gradParameters:zero() Model:zeroGradParameters() local outputs = Model:forward(inputTable) local err = criterion:forward(outputs, targetTable) local dparams = criterion:backward(outputs, targetTable) Model:backward(inputTable, dparams) return err, gradParameters end local _, loss = optimiser(feval, parameters, optimConfig, optimState) train_loss = train_loss + loss[1] print(('Train loss ' .. loss[1])) end print(('Train loss: ' .. c.cyan '%.4f' .. ' \t time: %.2f s\t grad/param norm = %6.4e\t learning rate: %f'):format(train_loss / opt.niter, torch.toc(tic), gradParameters:norm() / parameters:norm(), optimConfig.learningRate)) trainLogger:add { train_loss / opt.niter, optimConfig.learningRate } epoch = epoch + 1 end function train_basic_singlescale() Model:training() -- learning rate decay if epoch == 10 then optimConfig.learningRate = optimConfig.learningRate / 2 end if epoch > 10 and (epoch - 10) % opt.epoch_step == 0 then optimConfig.learningRate = optimConfig.learningRate / 2 end print(c.blue '==>' .. " Epoch # " .. epoch .. ' [batch_size = ' .. opt.batch_size .. ']') local tic = torch.tic() local train_loss = 0 for iter = 1, opt.niter do xlua.progress(iter, opt.niter) local inputs_L, inputs_R, zero_target = my_dataset:next_batch() local inputTable = { inputs_L, inputs_R } local targetTable = { inputs_L, zero_target } local feval = function(x) if x ~= parameters then parameters:copy(x) end --gradParameters:zero() Model:zeroGradParameters() local outputs = Model:forward(inputTable) local err = criterion:forward(outputs, targetTable) local dparams = criterion:backward(outputs, targetTable) Model:backward(inputTable, dparams) return err, gradParameters end local _, loss = optimiser(feval, parameters, optimConfig, optimState) train_loss = train_loss + loss[1] print(('Train loss ' .. loss[1])) end print(('Train loss: ' .. c.cyan '%.4f' .. ' \t time: %.2f s\t grad/param norm = %6.4e\t learning rate: %f'):format(train_loss / opt.niter, torch.toc(tic), gradParameters:norm() / parameters:norm(), optimConfig.learningRate)) trainLogger:add { train_loss / opt.niter, optimConfig.learningRate } epoch = epoch + 1 end function train_basic_multiscale() Model:training() -- learning rate decay if epoch == 10 then optimConfig.learningRate = optimConfig.learningRate / 2 end if epoch > 10 and (epoch - 10) % opt.epoch_step == 0 then optimConfig.learningRate = optimConfig.learningRate / 2 end print(c.blue '==>' .. " Epoch # " .. epoch .. ' [batch_size = ' .. opt.batch_size .. ']') local tic = torch.tic() local train_loss = 0 for iter = 1, opt.niter do xlua.progress(iter, opt.niter) local inputs_L1, inputs_L2, _, inputs_R1, inputs_R2, _, zero_target1, zero_target2, _ = my_dataset:next_batch_multiscale() local inputTable = { inputs_L1, inputs_L2, inputs_R1, inputs_R2 } local targetTable = { inputs_L1, zero_target1, inputs_L2, zero_target2 } local feval = function(x) if x ~= parameters then parameters:copy(x) end --gradParameters:zero() Model:zeroGradParameters() local outputs = Model:forward(inputTable) local err = criterion:forward(outputs, targetTable) local dparams = criterion:backward(outputs, targetTable) Model:backward(inputTable, dparams) return err, gradParameters end local _, loss = optimiser(feval, parameters, optimConfig, optimState) train_loss = train_loss + loss[1] print(('Train loss ' .. loss[1])) end print(('Train loss: ' .. c.cyan '%.4f' .. ' \t time: %.2f s\t grad/param norm = %6.4e\t learning rate: %f'):format(train_loss / opt.niter, torch.toc(tic), gradParameters:norm() / parameters:norm(), optimConfig.learningRate)) trainLogger:add { train_loss / opt.niter, optimConfig.learningRate } epoch = epoch + 1 end print('Model will be saved at ' .. opt.save) paths.mkdir(opt.save) trainLogger = optim.Logger(paths.concat(opt.save, 'train.log')) trainLogger:setNames { 'Train Loss', 'Learning Rate' } function logging() -- save model parameters every # epochs if epoch % 2 == 0 or epoch == opt.nepoch then local filename = paths.concat(opt.save, string.format('param_epoch_%d.t7', epoch)) print('==> saving parameters to ' .. filename) torch.save(filename, parameters) -- save bn statistics from training set filename = paths.concat(opt.save, string.format('bn_meanvar_epoch_%d.t7', epoch)) print('==> saving bn mean var to ' .. filename) local bn_mean = {} local bn_var = {} for k, v in pairs(Model:findModules('nn.SpatialBatchNormalization')) do bn_mean[k] = v.running_mean bn_var[k] = v.running_var end if #bn_mean > 0 then torch.save(filename, { bn_mean, bn_var }) end end end while epoch < opt.nepoch do if opt.model_no == 4 then train_siamese_multiscale() elseif opt.model_no == 3 then train_siamese_singlescale() elseif opt.model_no == 2 then train_basic_multiscale() elseif opt.model_no == 1 then train_basic_singlescale() end --evaluate() logging() if epoch % 2 == 0 then collectgarbage() end end
--Created by the QnEditor,do not modify.If not,you will die very nankan! local MAP = { var = { Image_shiled = 1, ImageBack = 2, View_bagBlank = 3, View_content_bag = 4, Button_record = 5, }, ui = { [1] = {"Image_shiled"}, [2] = {"ImageBack"}, [3] = {"ImageBack","Image_bg2","View_bagBlank"}, [4] = {"ImageBack","Image_bg2","View_content_bag"}, [5] = {"ImageBack","Button_record"}, }, func = { [2] = "onBindBlankFunc", [5] = "onBindToRecord", }, } return MAP;
local helper = {} --- Creates a new empty mesh. function helper.new_mesh() local mesh = {} mesh.vertexes = {} mesh.segments = {} mesh.colors = {} return mesh end --- Adds a line to a mesh. -- @params mesh table: a properly formated mesh. Possibly created with `new_mesh`. -- @params vertex table: a list of either 2D or 3D vertexes. The coordinates of the vertexes are floats. -- @params colors table: a list of colors. There should be as many colors as there are vertexes. -- @params close_loop boolean: whether the line should be a closed loop, with the first vertex being linked with the last vertex. function helper.add_line_to_mesh(mesh, vertexes, colors, close_loop) local vertex_count = #mesh.vertexes local color_count = #mesh.colors local segment_count = #mesh.segments local number_of_new_segments = #vertexes - 1 local segments = {} for i = 1, #vertexes do table.insert(mesh.vertexes, vertexes[i]) table.insert(mesh.colors, colors[i]) end table.insert(segments, vertex_count) for i = 1, number_of_new_segments do table.insert(segments, vertex_count + i) end if close_loop then table.insert(segments, vertex_count) end table.insert(mesh.segments, segments) end --- Adds distincts segments to a mesh. -- @params vertexes table: An array or vertexes. The vertexes {a,b,c,d} will draw 2 distinct segments: {a,b} and {c,d} -- @params colors table: a list of colors. There should be as many colors as there are vertexes. function helper.add_segments_to_mesh(mesh, vertexes, colors) vertex_count = #mesh.vertexes new_vertex_count = #vertexes if new_vertex_count % 2 ~= 0 then pewpew.print("Error: array's size should be even.") return end for i = 1, new_vertex_count do table.insert(mesh.vertexes, vertexes[i]) table.insert(mesh.colors, colors[i]) end for i = 0, new_vertex_count - 1, 2 do table.insert(mesh.segments, {vertex_count + i, vertex_count + i + 1}) end end function helper.add_computed_segments_to_mesh(mesh, number_of_points, compute_vertex_and_color, looping) local vertex_count = #mesh.vertexes local color_count = #mesh.colors local segment_count = #mesh.segments local vertex_index = vertex_count + 1 for i = 1, number_of_points do local vertex, color = compute_vertex_and_color(i) mesh.vertexes[vertex_index] = vertex mesh.colors[vertex_index] = color vertex_index = vertex_index + 1 end local segments = {} for i = 1, number_of_points do table.insert(segments, vertex_count + i - 1) end if looping then table.insert(segments, vertex_count) end table.insert(mesh.segments, segments) end function helper.add_horizontal_regular_polygon_to_mesh(mesh, center, radius, number_of_points, color, angle_offset) local compute = function(i) local angle = (i - 1) * 2 * math.pi / number_of_points local sin_angle, cos_angle = math.sincos(angle + angle_offset) return {center[1] + cos_angle * radius, center[2] + sin_angle * radius, center[3]}, color end helper.add_computed_segments_to_mesh(mesh, number_of_points, compute, true) end function helper.add_cube_to_mesh(mesh, center, side_length, color) local half = side_length / 2 local x = center[1] local y = center[2] local z = center[3] local a = {x - half, y - half, z - half} local b = {x - half, y + half, z - half} local c = {x + half, y + half, z - half} local d = {x + half, y - half, z - half} local e = {x - half, y - half, z + half} local f = {x - half, y + half, z + half} local g = {x + half, y + half, z + half} local h = {x + half, y - half, z + half} helper.add_line_to_mesh(mesh, {a, b, c, d}, {color, color, color, color}, true) helper.add_line_to_mesh(mesh, {e, f, g, h}, {color, color, color, color}, true) helper.add_line_to_mesh(mesh, {a, e}, {color, color}) helper.add_line_to_mesh(mesh, {b, f}, {color, color}) helper.add_line_to_mesh(mesh, {c, g}, {color, color}) helper.add_line_to_mesh(mesh, {d, h}, {color, color}) end function helper.add_vertical_cylinder_to_mesh(mesh, bottom_center, height, radius, number_of_points, color) local bottom_center = {bottom_center[1], bottom_center[2] , bottom_center[3]} local top_center = {bottom_center[1], bottom_center[2] , bottom_center[3] + height} local index_of_first_vertex = #mesh.vertexes helper.add_horizontal_regular_polygon_to_mesh(mesh, bottom_center, radius, number_of_points, color, 0) helper.add_horizontal_regular_polygon_to_mesh(mesh, top_center, radius, number_of_points, color, 0) -- Add the segments linking the 2 regular polygons for i=1,number_of_points do table.insert(mesh.segments, {index_of_first_vertex, index_of_first_vertex + number_of_points}) index_of_first_vertex = index_of_first_vertex + 1 end end return helper
-- vcrwire.lua -- babyjeans -- --- local VCRWire = VCRComponent:extend('VCRWire') function VCRWire:init(name, from, to, x, y, resources) self.super.init(self, name, x, y, resources) self.componentType = 'wire' end return VCRWire
--============================================================================= -- 大脚动作条按键绑定 --============================================================================= -- NULL_FUNCTION = function() end if (GetLocale() == "zhCN") then BINDING_HEADER_BIGFOOTBAR1 = "大脚1号动作条"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton1:LeftButton"] = "快捷键1"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton2:LeftButton"] = "快捷键2"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton3:LeftButton"] = "快捷键3"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton4:LeftButton"] = "快捷键4"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton5:LeftButton"] = "快捷键5"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton6:LeftButton"] = "快捷键6"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton7:LeftButton"] = "快捷键7"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton8:LeftButton"] = "快捷键8"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton9:LeftButton"] = "快捷键9"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton10:LeftButton"] = "快捷键10"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton11:LeftButton"] = "快捷键11"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton12:LeftButton"] = "快捷键12"; BINDING_HEADER_BIGFOOTBAR2 = "大脚2号动作条"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton1:LeftButton"] = "快捷键1"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton2:LeftButton"] = "快捷键2"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton3:LeftButton"] = "快捷键3"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton4:LeftButton"] = "快捷键4"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton5:LeftButton"] = "快捷键5"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton6:LeftButton"] = "快捷键6"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton7:LeftButton"] = "快捷键7"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton8:LeftButton"] = "快捷键8"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton9:LeftButton"] = "快捷键9"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton10:LeftButton"] = "快捷键10"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton11:LeftButton"] = "快捷键11"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton12:LeftButton"] = "快捷键12"; BINDING_HEADER_BIGFOOTBAR3 = "大脚3号动作条"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton1:LeftButton"] = "快捷键1"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton2:LeftButton"] = "快捷键2"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton3:LeftButton"] = "快捷键3"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton4:LeftButton"] = "快捷键4"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton5:LeftButton"] = "快捷键5"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton6:LeftButton"] = "快捷键6"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton7:LeftButton"] = "快捷键7"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton8:LeftButton"] = "快捷键8"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton9:LeftButton"] = "快捷键9"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton10:LeftButton"] = "快捷键10"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton11:LeftButton"] = "快捷键11"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton12:LeftButton"] = "快捷键12"; BINDING_HEADER_BIGFOOTBAR4 = "大脚4号动作条"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton1:LeftButton"] = "快捷键1"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton2:LeftButton"] = "快捷键2"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton3:LeftButton"] = "快捷键3"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton4:LeftButton"] = "快捷键4"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton5:LeftButton"] = "快捷键5"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton6:LeftButton"] = "快捷键6"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton7:LeftButton"] = "快捷键7"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton8:LeftButton"] = "快捷键8"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton9:LeftButton"] = "快捷键9"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton10:LeftButton"] = "快捷键10"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton11:LeftButton"] = "快捷键11"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton12:LeftButton"] = "快捷键12"; BINDING_HEADER_BIGFOOTBAR5 = "大脚5号动作条"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton1:LeftButton"] = "快捷键1"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton2:LeftButton"] = "快捷键2"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton3:LeftButton"] = "快捷键3"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton4:LeftButton"] = "快捷键4"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton5:LeftButton"] = "快捷键5"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton6:LeftButton"] = "快捷键6"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton7:LeftButton"] = "快捷键7"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton8:LeftButton"] = "快捷键8"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton9:LeftButton"] = "快捷键9"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton10:LeftButton"] = "快捷键10"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton11:LeftButton"] = "快捷键11"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton12:LeftButton"] = "快捷键12"; BINDING_HEADER_BIGFOOTBAR6 = "大脚6号动作条"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton1:LeftButton"] = "快捷键1"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton2:LeftButton"] = "快捷键2"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton3:LeftButton"] = "快捷键3"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton4:LeftButton"] = "快捷键4"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton5:LeftButton"] = "快捷键5"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton6:LeftButton"] = "快捷键6"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton7:LeftButton"] = "快捷键7"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton8:LeftButton"] = "快捷键8"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton9:LeftButton"] = "快捷键9"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton10:LeftButton"] = "快捷键10"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton11:LeftButton"] = "快捷键11"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton12:LeftButton"] = "快捷键12"; BINDING_HEADER_BIGFOOTBAR7 = "大脚7号动作条"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton1:LeftButton"] = "快捷键1"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton2:LeftButton"] = "快捷键2"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton3:LeftButton"] = "快捷键3"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton4:LeftButton"] = "快捷键4"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton5:LeftButton"] = "快捷键5"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton6:LeftButton"] = "快捷键6"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton7:LeftButton"] = "快捷键7"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton8:LeftButton"] = "快捷键8"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton9:LeftButton"] = "快捷键9"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton10:LeftButton"] = "快捷键10"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton11:LeftButton"] = "快捷键11"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton12:LeftButton"] = "快捷键12"; BINDING_HEADER_BIGFOOTBAR8 = "大脚8号动作条"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton1:LeftButton"] = "快捷键1"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton2:LeftButton"] = "快捷键2"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton3:LeftButton"] = "快捷键3"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton4:LeftButton"] = "快捷键4"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton5:LeftButton"] = "快捷键5"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton6:LeftButton"] = "快捷键6"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton7:LeftButton"] = "快捷键7"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton8:LeftButton"] = "快捷键8"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton9:LeftButton"] = "快捷键9"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton10:LeftButton"] = "快捷键10"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton11:LeftButton"] = "快捷键11"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton12:LeftButton"] = "快捷键12"; BINDING_HEADER_BIGFOOTBAR9 = "大脚9号动作条"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton1:LeftButton"] = "快捷键1"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton2:LeftButton"] = "快捷键2"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton3:LeftButton"] = "快捷键3"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton4:LeftButton"] = "快捷键4"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton5:LeftButton"] = "快捷键5"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton6:LeftButton"] = "快捷键6"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton7:LeftButton"] = "快捷键7"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton8:LeftButton"] = "快捷键8"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton9:LeftButton"] = "快捷键9"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton10:LeftButton"] = "快捷键10"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton11:LeftButton"] = "快捷键11"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton12:LeftButton"] = "快捷键12"; BINDING_HEADER_BIGFOOTBAR10 = "大脚10号动作条"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton1:LeftButton"] = "快捷键1"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton2:LeftButton"] = "快捷键2"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton3:LeftButton"] = "快捷键3"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton4:LeftButton"] = "快捷键4"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton5:LeftButton"] = "快捷键5"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton6:LeftButton"] = "快捷键6"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton7:LeftButton"] = "快捷键7"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton8:LeftButton"] = "快捷键8"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton9:LeftButton"] = "快捷键9"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton10:LeftButton"] = "快捷键10"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton11:LeftButton"] = "快捷键11"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton12:LeftButton"] = "快捷键12"; elseif (GetLocale() == "zhTW") then BINDING_HEADER_BIGFOOTBAR1 = "大脚1號動作條"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton1:LeftButton"] = "快捷鍵1"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton2:LeftButton"] = "快捷鍵2"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton3:LeftButton"] = "快捷鍵3"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton4:LeftButton"] = "快捷鍵4"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton5:LeftButton"] = "快捷鍵5"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton6:LeftButton"] = "快捷鍵6"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton7:LeftButton"] = "快捷鍵7"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton8:LeftButton"] = "快捷鍵8"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton9:LeftButton"] = "快捷鍵9"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton10:LeftButton"] = "快捷鍵10"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton11:LeftButton"] = "快捷鍵11"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton12:LeftButton"] = "快捷鍵12"; BINDING_HEADER_BIGFOOTBAR2 = "大脚2號動作條"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton1:LeftButton"] = "快捷鍵1"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton2:LeftButton"] = "快捷鍵2"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton3:LeftButton"] = "快捷鍵3"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton4:LeftButton"] = "快捷鍵4"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton5:LeftButton"] = "快捷鍵5"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton6:LeftButton"] = "快捷鍵6"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton7:LeftButton"] = "快捷鍵7"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton8:LeftButton"] = "快捷鍵8"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton9:LeftButton"] = "快捷鍵9"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton10:LeftButton"] = "快捷鍵10"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton11:LeftButton"] = "快捷鍵11"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton12:LeftButton"] = "快捷鍵12"; BINDING_HEADER_BIGFOOTBAR3 = "大脚3號動作條"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton1:LeftButton"] = "快捷鍵1"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton2:LeftButton"] = "快捷鍵2"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton3:LeftButton"] = "快捷鍵3"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton4:LeftButton"] = "快捷鍵4"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton5:LeftButton"] = "快捷鍵5"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton6:LeftButton"] = "快捷鍵6"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton7:LeftButton"] = "快捷鍵7"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton8:LeftButton"] = "快捷鍵8"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton9:LeftButton"] = "快捷鍵9"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton10:LeftButton"] = "快捷鍵10"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton11:LeftButton"] = "快捷鍵11"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton12:LeftButton"] = "快捷鍵12"; BINDING_HEADER_BIGFOOTBAR4 = "大脚4號動作條"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton1:LeftButton"] = "快捷鍵1"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton2:LeftButton"] = "快捷鍵2"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton3:LeftButton"] = "快捷鍵3"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton4:LeftButton"] = "快捷鍵4"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton5:LeftButton"] = "快捷鍵5"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton6:LeftButton"] = "快捷鍵6"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton7:LeftButton"] = "快捷鍵7"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton8:LeftButton"] = "快捷鍵8"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton9:LeftButton"] = "快捷鍵9"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton10:LeftButton"] = "快捷鍵10"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton11:LeftButton"] = "快捷鍵11"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton12:LeftButton"] = "快捷鍵12"; BINDING_HEADER_BIGFOOTBAR5 = "大脚5號動作條"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton1:LeftButton"] = "快捷鍵1"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton2:LeftButton"] = "快捷鍵2"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton3:LeftButton"] = "快捷鍵3"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton4:LeftButton"] = "快捷鍵4"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton5:LeftButton"] = "快捷鍵5"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton6:LeftButton"] = "快捷鍵6"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton7:LeftButton"] = "快捷鍵7"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton8:LeftButton"] = "快捷鍵8"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton9:LeftButton"] = "快捷鍵9"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton10:LeftButton"] = "快捷鍵10"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton11:LeftButton"] = "快捷鍵11"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton12:LeftButton"] = "快捷鍵12"; BINDING_HEADER_BIGFOOTBAR6 = "大脚6號動作條"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton1:LeftButton"] = "快捷鍵1"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton2:LeftButton"] = "快捷鍵2"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton3:LeftButton"] = "快捷鍵3"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton4:LeftButton"] = "快捷鍵4"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton5:LeftButton"] = "快捷鍵5"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton6:LeftButton"] = "快捷鍵6"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton7:LeftButton"] = "快捷鍵7"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton8:LeftButton"] = "快捷鍵8"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton9:LeftButton"] = "快捷鍵9"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton10:LeftButton"] = "快捷鍵10"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton11:LeftButton"] = "快捷鍵11"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton12:LeftButton"] = "快捷鍵12"; BINDING_HEADER_BIGFOOTBAR7 = "大脚7號動作條"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton1:LeftButton"] = "快捷鍵1"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton2:LeftButton"] = "快捷鍵2"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton3:LeftButton"] = "快捷鍵3"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton4:LeftButton"] = "快捷鍵4"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton5:LeftButton"] = "快捷鍵5"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton6:LeftButton"] = "快捷鍵6"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton7:LeftButton"] = "快捷鍵7"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton8:LeftButton"] = "快捷鍵8"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton9:LeftButton"] = "快捷鍵9"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton10:LeftButton"] = "快捷鍵10"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton11:LeftButton"] = "快捷鍵11"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton12:LeftButton"] = "快捷鍵12"; BINDING_HEADER_BIGFOOTBAR8 = "大脚8號動作條"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton1:LeftButton"] = "快捷鍵1"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton2:LeftButton"] = "快捷鍵2"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton3:LeftButton"] = "快捷鍵3"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton4:LeftButton"] = "快捷鍵4"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton5:LeftButton"] = "快捷鍵5"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton6:LeftButton"] = "快捷鍵6"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton7:LeftButton"] = "快捷鍵7"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton8:LeftButton"] = "快捷鍵8"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton9:LeftButton"] = "快捷鍵9"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton10:LeftButton"] = "快捷鍵10"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton11:LeftButton"] = "快捷鍵11"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton12:LeftButton"] = "快捷鍵12"; BINDING_HEADER_BIGFOOTBAR9 = "大脚9號動作條"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton1:LeftButton"] = "快捷鍵1"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton2:LeftButton"] = "快捷鍵2"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton3:LeftButton"] = "快捷鍵3"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton4:LeftButton"] = "快捷鍵4"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton5:LeftButton"] = "快捷鍵5"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton6:LeftButton"] = "快捷鍵6"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton7:LeftButton"] = "快捷鍵7"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton8:LeftButton"] = "快捷鍵8"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton9:LeftButton"] = "快捷鍵9"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton10:LeftButton"] = "快捷鍵10"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton11:LeftButton"] = "快捷鍵11"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton12:LeftButton"] = "快捷鍵12"; BINDING_HEADER_BIGFOOTBAR10 = "大脚10號動作條"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton1:LeftButton"] = "快捷鍵1"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton2:LeftButton"] = "快捷鍵2"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton3:LeftButton"] = "快捷鍵3"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton4:LeftButton"] = "快捷鍵4"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton5:LeftButton"] = "快捷鍵5"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton6:LeftButton"] = "快捷鍵6"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton7:LeftButton"] = "快捷鍵7"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton8:LeftButton"] = "快捷鍵8"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton9:LeftButton"] = "快捷鍵9"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton10:LeftButton"] = "快捷鍵10"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton11:LeftButton"] = "快捷鍵11"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton12:LeftButton"] = "快捷鍵12"; else BINDING_HEADER_BIGFOOTBAR1 = "BigFoot 1 Bar"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton1:LeftButton"] = "Action ActionButton 1"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton2:LeftButton"] = "Action ActionButton 2"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton3:LeftButton"] = "Action ActionButton 3"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton4:LeftButton"] = "Action ActionButton 4"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton5:LeftButton"] = "Action ActionButton 5"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton6:LeftButton"] = "Action ActionButton 6"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton7:LeftButton"] = "Action ActionButton 7"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton8:LeftButton"] = "Action ActionButton 8"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton9:LeftButton"] = "Action ActionButton 9"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton10:LeftButton"] = "Action ActionButton 10"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton11:LeftButton"] = "Action ActionButton 11"; _G["BINDING_NAME_CLICK BigFootBarFrame1ActionButton12:LeftButton"] = "Action ActionButton 12"; BINDING_HEADER_BIGFOOTBAR2 = "BigFoot 2 Bar"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton1:LeftButton"] = "Action ActionButton 1"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton2:LeftButton"] = "Action ActionButton 2"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton3:LeftButton"] = "Action ActionButton 3"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton4:LeftButton"] = "Action ActionButton 4"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton5:LeftButton"] = "Action ActionButton 5"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton6:LeftButton"] = "Action ActionButton 6"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton7:LeftButton"] = "Action ActionButton 7"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton8:LeftButton"] = "Action ActionButton 8"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton9:LeftButton"] = "Action ActionButton 9"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton10:LeftButton"] = "Action ActionButton 10"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton11:LeftButton"] = "Action ActionButton 11"; _G["BINDING_NAME_CLICK BigFootBarFrame2ActionButton12:LeftButton"] = "Action ActionButton 12"; BINDING_HEADER_BIGFOOTBAR3 = "BigFoot 3 Bar"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton1:LeftButton"] = "Action ActionButton 1"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton2:LeftButton"] = "Action ActionButton 2"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton3:LeftButton"] = "Action ActionButton 3"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton4:LeftButton"] = "Action ActionButton 4"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton5:LeftButton"] = "Action ActionButton 5"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton6:LeftButton"] = "Action ActionButton 6"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton7:LeftButton"] = "Action ActionButton 7"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton8:LeftButton"] = "Action ActionButton 8"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton9:LeftButton"] = "Action ActionButton 9"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton10:LeftButton"] = "Action ActionButton 10"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton11:LeftButton"] = "Action ActionButton 11"; _G["BINDING_NAME_CLICK BigFootBarFrame3ActionButton12:LeftButton"] = "Action ActionButton 12"; BINDING_HEADER_BIGFOOTBAR4 = "BigFoot 4 Bar"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton1:LeftButton"] = "Action ActionButton 1"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton2:LeftButton"] = "Action ActionButton 2"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton3:LeftButton"] = "Action ActionButton 3"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton4:LeftButton"] = "Action ActionButton 4"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton5:LeftButton"] = "Action ActionButton 5"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton6:LeftButton"] = "Action ActionButton 6"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton7:LeftButton"] = "Action ActionButton 7"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton8:LeftButton"] = "Action ActionButton 8"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton9:LeftButton"] = "Action ActionButton 9"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton10:LeftButton"] = "Action ActionButton 10"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton11:LeftButton"] = "Action ActionButton 11"; _G["BINDING_NAME_CLICK BigFootBarFrame4ActionButton12:LeftButton"] = "Action ActionButton 12"; BINDING_HEADER_BIGFOOTBAR5 = "BigFoot 5 Bar"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton1:LeftButton"] = "Action ActionButton 1"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton2:LeftButton"] = "Action ActionButton 2"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton3:LeftButton"] = "Action ActionButton 3"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton4:LeftButton"] = "Action ActionButton 4"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton5:LeftButton"] = "Action ActionButton 5"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton6:LeftButton"] = "Action ActionButton 6"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton7:LeftButton"] = "Action ActionButton 7"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton8:LeftButton"] = "Action ActionButton 8"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton9:LeftButton"] = "Action ActionButton 9"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton10:LeftButton"] = "Action ActionButton 10"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton11:LeftButton"] = "Action ActionButton 11"; _G["BINDING_NAME_CLICK BigFootBarFrame5ActionButton12:LeftButton"] = "Action ActionButton 12"; BINDING_HEADER_BIGFOOTBAR6 = "BigFoot 6 Bar"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton1:LeftButton"] = "Action ActionButton 1"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton2:LeftButton"] = "Action ActionButton 2"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton3:LeftButton"] = "Action ActionButton 3"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton4:LeftButton"] = "Action ActionButton 4"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton5:LeftButton"] = "Action ActionButton 5"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton6:LeftButton"] = "Action ActionButton 6"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton7:LeftButton"] = "Action ActionButton 7"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton8:LeftButton"] = "Action ActionButton 8"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton9:LeftButton"] = "Action ActionButton 9"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton10:LeftButton"] = "Action ActionButton 10"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton11:LeftButton"] = "Action ActionButton 11"; _G["BINDING_NAME_CLICK BigFootBarFrame6ActionButton12:LeftButton"] = "Action ActionButton 12"; BINDING_HEADER_BIGFOOTBAR7 = "BigFoot 7 Bar"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton1:LeftButton"] = "Action ActionButton 1"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton2:LeftButton"] = "Action ActionButton 2"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton3:LeftButton"] = "Action ActionButton 3"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton4:LeftButton"] = "Action ActionButton 4"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton5:LeftButton"] = "Action ActionButton 5"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton6:LeftButton"] = "Action ActionButton 6"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton7:LeftButton"] = "Action ActionButton 7"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton8:LeftButton"] = "Action ActionButton 8"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton9:LeftButton"] = "Action ActionButton 9"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton10:LeftButton"] = "Action ActionButton 10"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton11:LeftButton"] = "Action ActionButton 11"; _G["BINDING_NAME_CLICK BigFootBarFrame7ActionButton12:LeftButton"] = "Action ActionButton 12"; BINDING_HEADER_BIGFOOTBAR8 = "BigFoot 8 Bar"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton1:LeftButton"] = "Action ActionButton 1"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton2:LeftButton"] = "Action ActionButton 2"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton3:LeftButton"] = "Action ActionButton 3"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton4:LeftButton"] = "Action ActionButton 4"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton5:LeftButton"] = "Action ActionButton 5"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton6:LeftButton"] = "Action ActionButton 6"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton7:LeftButton"] = "Action ActionButton 7"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton8:LeftButton"] = "Action ActionButton 8"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton9:LeftButton"] = "Action ActionButton 9"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton10:LeftButton"] = "Action ActionButton 10"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton11:LeftButton"] = "Action ActionButton 11"; _G["BINDING_NAME_CLICK BigFootBarFrame8ActionButton12:LeftButton"] = "Action ActionButton 12"; BINDING_HEADER_BIGFOOTBAR9 = "BigFoot 9 Bar"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton1:LeftButton"] = "Action ActionButton 1"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton2:LeftButton"] = "Action ActionButton 2"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton3:LeftButton"] = "Action ActionButton 3"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton4:LeftButton"] = "Action ActionButton 4"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton5:LeftButton"] = "Action ActionButton 5"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton6:LeftButton"] = "Action ActionButton 6"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton7:LeftButton"] = "Action ActionButton 7"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton8:LeftButton"] = "Action ActionButton 8"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton9:LeftButton"] = "Action ActionButton 9"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton10:LeftButton"] = "Action ActionButton 10"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton11:LeftButton"] = "Action ActionButton 11"; _G["BINDING_NAME_CLICK BigFootBarFrame9ActionButton12:LeftButton"] = "Action ActionButton 12"; BINDING_HEADER_BIGFOOTBAR10 = "BigFoot 10 Bar"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton1:LeftButton"] = "Action ActionButton 1"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton2:LeftButton"] = "Action ActionButton 2"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton3:LeftButton"] = "Action ActionButton 3"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton4:LeftButton"] = "Action ActionButton 4"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton5:LeftButton"] = "Action ActionButton 5"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton6:LeftButton"] = "Action ActionButton 6"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton7:LeftButton"] = "Action ActionButton 7"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton8:LeftButton"] = "Action ActionButton 8"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton9:LeftButton"] = "Action ActionButton 9"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton10:LeftButton"] = "Action ActionButton 10"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton11:LeftButton"] = "Action ActionButton 11"; _G["BINDING_NAME_CLICK BigFootBarFrame10ActionButton12:LeftButton"] = "Action ActionButton 12"; end
local objc = require "objc/init" objc.import "AppKit" local NSPasteboardTypeString = "public.utf8-plain-text" local pasteboard = objc.NSPasteboard:generalPasteboard() pasteboard:declareTypes_owner_(objc.ns{NSPasteboardTypeString}, nil) function get() return pasteboard:stringForType_(NSPasteboardTypeString) end function set(text) local oldValue = get() pasteboard:setString_forType_(text, NSPasteboardTypeString) return oldValue end set('Hello World!') local contents = get() print(contents) -- => 'Hello World!'
local class = require("pl.class") local sfmt = string.format ---@class EntityLoader: Class ---@field dataSource DataSource ---@field config? table local M = class() function M:_init(dataSource, config) self.dataSource = dataSource self.config = config or {} end function M:setArea(name) self.config.area = name end function M:setBundle(name) self.config.bundle = name end function M:hasData() return self.dataSource:hasData(self.config) end function M:fetchAll() if not self.dataSource["fetchAll"] then error(sfmt("fetchAll not supported by %s", self.dataSource.name)) end return self.dataSource:fetchAll(self.config) end function M:fetch(id) assert(self.dataSource["fetch"], sfmt("fetch not supported by %s", self.dataSource.name)) return self.dataSource:fetch(self.config, id) end function M:replace(data) assert(self.dataSource["replace"], sfmt("replace not supported by %s", self.dataSource.name)) return self.dataSource:replace(self.config, data) end function M:update(id, data) assert(self.dataSource["update"], sfmt("update not supported by %s", self.dataSource.name)) return self.dataSource:update(self.config, id, data) end return M
object_tangible_deed_vehicle_deed_koro2_speeder_deed = object_tangible_deed_vehicle_deed_shared_koro2_speeder_deed:new { } ObjectTemplates:addTemplate(object_tangible_deed_vehicle_deed_koro2_speeder_deed, "object/tangible/deed/vehicle_deed/koro2_speeder_deed.iff")
local jobs = {} local time = 0.0 core.register_globalstep(function(dtime) time = time + dtime if #jobs < 1 then return end -- Iterate backwards so that we miss any new timers added by -- a timer callback, and so that we don't skip the next timer -- in the list if we remove one. for i = #jobs, 1, -1 do local job = jobs[i] if time >= job.expire then core.set_last_run_mod(job.mod_origin) job.func(unpack(job.arg)) table.remove(jobs, i) end end end) function core.after(after, func, ...) assert(tonumber(after) and type(func) == "function", "Invalid core.after invocation") jobs[#jobs + 1] = { func = func, expire = time + after, arg = {...}, mod_origin = core.get_last_run_mod() } end
----------------------------------------------------------------------------- -- An icon an RSS feed. -- -- Image (c) Mozilla Foundation -- License: LGPL ----------------------------------------------------------------------------- module(..., package.seeall) NODE = { prototype = "@Image", file_name = "feed.png", copyright = "Mozilla Foundation", title = "Feed Icon", file_type = "image/png", } NODE.content = [[ iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/ wD/oL2nkwAAAAlwSFlzAAAN1wAADdcBQiibeAAAAAd0SU1FB9kCEAInKD/ILUkAAAOZSURBVDjLtZ XdbxRVGMZ/55zZj+5sod00XdumgMXEigiJH6CgMeFaBMOd8dZETIg28c7/QYkk8hdwY6KiF8YbvYD Ykmhj0hJAS2q3pNZttlC6O/t55rxezO7M1sKNCXOxM3POnN955nnedxae0KF6F8uXzo+k8ukvBnz/ tFI6j4pmVfQTPaz6lsXXguuEtUY1+K4dtD+eunC5EoOXL50fyRX23BzIZou23kBphdKgtUIZuvfdM aNAg1LRvdLRJkKGrXK1HGxuH566cLmiATw/fXEgO1C0wf+DKqUwus3e0cFi2k9/BuAB5Ab9M7ZeRx lF7pWzpPcdQVrbuOoG4fptXGUJ5ZqPhSoFLhSwLbKD/jsxWKHzPVVKg8rkUJkces9TeBNHwIWEpRu EK9fA1h8JdVaQUDDG5AF0HEf39aVWwT1cR9r1JGJtME+fJPX6DGbs6GOhzgpItMSL13Y97SzPYlfm UBrM0Dhm/BBm32uoVBaVymIOn0OVisjKTzjrdkCdFaQfrBRxUN7IAVTWh8YmEqwT3v0HuTeHOXgKP Xk8Mm7/Gzg07s6PO6DOCmjpU6xUNxSFN3kU78DxqELr93Grs7i/5wmXfkCqa5jpM6A99P6T6K11Oq XfE7UOpGuu7hVzHF7SBahcATP9Ft6xD9ADBdhYILz1LT0jvedPg+cn0DDxWMeN1K1TuzpHZ+ErwrX fIGxH0/ki5uX3kcwwdm0B+9dsNO5l8J49FUOd4z9gkuKnXkHKi7g732NvXEQ2l6IHUj7mhXcRMbRv /4y0agCkp45BOo9z4KzrcRPFO4tfg5eBdoC7eQWp/NFVPoqefBXXbND+85e4TlPjz0XQRymOobkhv BMfkXrzU8z02zjr6Cx+g3SakfCDJ3Chol1ajLPwJg4lHvcr7m9TPf4iaqAQbTb2EpLai2sE2NX5aC y7Bz00QfiwQli7D4ApjCFhN8CdiiVuUxqb8a7SaeAadZwVwvLdRM3gaORpNQLr3CAiChGJP60eQGj DGsrklVKwsUio0+AXsaV5XKsZ1emDMp17iyB0N3O0SrdwjXqk0ksjrRaipBqDg+3a1fzw6HtataPe L/26q6Ok/YDg2pUkfQf1heuIu45IZEOm4NMItq7GVtigM7NVrpZtmN7V+/3F3w9NPBVEFJlhn45rl ZtNO7PrrymdT3+ezftnjWfyIlHpCESJJIHTmyM+SbUZ1L5uNTufPPPhl5s8yeNf5D/9vmf69QAAAA AASUVORK5CYII= ]]
function SpawnRegions() return { { name = "Woldren's Island", file = "media/maps/The Island/spawnpoints.lua" }, } end
--[[------------------------------------ LoveFS Dialogs v0.8 Pure Lua FileSystem Access - Loveframes interface Under the MIT license. copyright(c) 2012 Caldas Lopes aka linux-man --]]------------------------------------ require 'loveframes' local lovefs_dir = 'lovefs' local function normalize(str) local str2 = '' for n = 1, #str do if str:byte(n) < 128 then str2 = str2..str:sub(n, n) end end return str2 end dialog = {} dialog.__index = dialog function dialog:refresh() self.current:SetText(self.window_fs.current) self.list:Clear() if not self.jail then local i = loveframes.Create('button') i:SetSize(405, 25) i.image = up i:SetText('..') i.groupIndex = 1 i.OnClick = function(object) self.window.selectedFile = '' self.window_fs:cd(object:GetText()) self:refresh() end self.list:AddItem(i) end for _, d in ipairs(self.window_fs.dirs) do local i = loveframes.Create('button') i:SetSize(405, 25) i.image = folder i:SetText(d) i.groupIndex = 1 i.OnClick = function(object) self.window.selectedFile = '' if self.fileinput then self.fileinput.text = '' end self.window_fs:cd(object:GetText()) self:refresh() end self.list:AddItem(i) end for _, f in ipairs(self.window_fs.files) do local i = loveframes.Create('button') i:SetSize(405, 25) i.image = file i:SetText(f) i.groupIndex = 1 i.OnClick = function(object) if self.window_fs:isFile(object:GetText()) then self.window.selectedFile = object:GetText() if self.fileinput then self.fileinput:SetText(normalize(self.window.selectedFile)) end end end self.list:AddItem(i) end end function dialog:default() local WINDOW_WIDTH = 600 folder = love.graphics.newImage(lovefs_dir..'/inode-directory.png') file = love.graphics.newImage(lovefs_dir..'/text-plain.png') up = love.graphics.newImage(lovefs_dir..'/draw-arrow-up.png') openfolder = love.graphics.newImage(lovefs_dir..'/document-open-folder.png') self.window = loveframes.Create('frame') self.window:SetSize(WINDOW_WIDTH, 395) -- 415,395 self.window:Center() self.window.selectedFile = '' self.onOK = nil self.onItemSelect = nil --self.window:SetModal(true) --multichoice and tooltip don't play well with SetModal if not self.jail then local drives = loveframes.Create('multichoice', self.window) local tooltip = loveframes.Create('tooltip') tooltip:SetObject(drives) tooltip:SetPadding(5) tooltip:SetOffsets(5, -5) tooltip:SetText('Drives') drives:SetPos(5, 25+5) drives:SetSize(100, 25) drives:SetListHeight(100) drives:SetPadding(0) drives:SetSpacing(0) drives.OnChoiceSelected = function(object, choice) self.window.selectedFile = '' self.window_fs:cd(choice) self:refresh() end local _, drive for _, drive in ipairs(self.window_fs.drives) do drives:AddChoice(drive) end drives:SetChoice(self.window_fs.drives[1]) end self.current = loveframes.Create('button', self.window) local tooltip = loveframes.Create('tooltip') tooltip:SetObject(self.current) tooltip:SetPadding(5) tooltip:SetOffsets(5, -5) tooltip:SetText('Current Directory') if self.jail then self.current:SetPos(5, 25+5) self.current:SetSize(WINDOW_WIDTH - 10, 25) else self.current:SetPos(100+10, 25+5) self.current:SetSize(WINDOW_WIDTH - 115, 25) end self.current.image = openfolder self.current.checked = true self.current.enabled = false self.list = loveframes.Create('list', self.window) self.list:SetPos(5, 60) self.list:SetSize(WINDOW_WIDTH - 10, 300) self.list:SetDisplayType('vertical') self.list:SetPadding(0) self.list:SetSpacing(0) local cancel = loveframes.Create('button', self.window) cancel:SetPos(WINDOW_WIDTH-80-80, 360+5) cancel:SetSize(75, 25) cancel:SetText('Cancel') cancel.OnClick = function(object) self.window:Remove() self = nil end local ok = loveframes.Create('button', self.window) ok:SetPos(WINDOW_WIDTH-80, 360+5) ok:SetSize(75, 25) ok:SetText('OK') ok.OnClick = function(object) if self.window.selectedFile ~= '' then if self.window_fs.os == 'Windows' then self.window_fs.selectedFile = self.window_fs.current..'\\'..self.window.selectedFile else self.window_fs.selectedFile = self.window_fs.current..'/'..self.window.selectedFile end if self.onOK then self.onOK(self.window_fs.selectedFile) end self.window:Remove() self = nil end end end function loadDialog(window_fs, filters) local temp = {} setmetatable(temp, dialog) temp.window_fs = window_fs temp.jail = false temp:default() local tb_filters = {} local _, v if filters then for _,v in ipairs(filters) do table.insert(tb_filters, v) end end temp.window:SetName('Load File') local filter = loveframes.Create('multichoice', temp.window) local tooltip = loveframes.Create('tooltip') tooltip:SetObject(filter) tooltip:SetPadding(5) tooltip:SetOffsets(5, -5) tooltip:SetText('Filter') filter:SetPos(5, 360+5) filter:SetSize(245, 25) filter:SetListHeight(100) filter:SetPadding(0) filter:SetSpacing(0) filter.OnChoiceSelected = function(object, choice) if choice:find('|') then window_fs:setParam(choice:sub(choice:find('|') + 1)) else window_fs:setParam(choice) end temp:refresh() end local _, f for _, f in ipairs(tb_filters) do filter:AddChoice(f) end filter:SetChoice(tb_filters[1]) if tb_filters[1]:find('|') then window_fs:setParam(tb_filters[1]:sub(tb_filters[1]:find('|') + 1)) else window_fs:setParam(tb_filters[1]) end temp:refresh() return temp end function saveDialog(window_fs, filename) local temp = {} setmetatable(temp, dialog) temp.window_fs = window_fs temp.jail = true temp:default() temp.window:SetName('Save File') temp.fileinput = loveframes.Create('textinput', temp.window) local tooltip = loveframes.Create('tooltip') tooltip:SetObject(temp.fileinput) tooltip:SetPadding(5) tooltip:SetOffsets(5, -5) tooltip:SetText('Filename') temp.fileinput:SetPos(5, 360+5) temp.fileinput:SetSize(245, 25) if filename then temp.fileinput:SetText(filename) end temp.fileinput.OnTextChanged = function(object, text) temp.window.selectedFile = object:GetText() end temp:refresh() return temp end
hello = 'hello' -- local (accessible only in this scope) local world = ' world!' -- -- Functions -- -- declaring our function function say(text) print(text) end -- calling our function (note the .. operator to concatenate strings!) say(hello .. world) -- -- If statements -- if world == 'world' then print('world!') else print('hello!') end -- -- Loops -- -- while loop with counter local i = 10 while i > 0 do -- note the lack of -= and += i = i - 1 print(i) end -- for loop, decrements from 10 to 1 for j = 10, 1, -1 do print(j) end -- repeat (do-while) loop i = 10 repeat i = i - 1 print(i) until i == 0 -- -- Tables -- -- sort of like structs or hash tables in C, and like Python dictionaries local person = {} person.name = 'Colton Ogden' person.age = 26 person.height = 69.5 -- bracket and dot syntax to access table fields print(person['name']) print(person.name) -- iterate through table's key-value pairs and print both of each for key, value in pairs(person) do print(key, value) end
--[[ Copyright 2018 JobTeaser Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local resty_hmac = require('resty.hmac') local resty_sha256 = require('resty.sha256') local str = require('resty.string') local _M = { _VERSION = '0.1.2' } local function get_credentials () local access_key = os.getenv('AWS_ACCESS_KEY_ID') local secret_key = os.getenv('AWS_SECRET_ACCESS_KEY') return { access_key = access_key, secret_key = secret_key } end local function get_iso8601_basic(timestamp) return os.date('!%Y%m%dT%H%M%SZ', timestamp) end local function get_iso8601_basic_short(timestamp) return os.date('!%Y%m%d', timestamp) end local function get_derived_signing_key(keys, timestamp, region, service) local h_date = resty_hmac:new('AWS4' .. keys['secret_key'], resty_hmac.ALGOS.SHA256) h_date:update(get_iso8601_basic_short(timestamp)) local k_date = h_date:final() local h_region = resty_hmac:new(k_date, resty_hmac.ALGOS.SHA256) h_region:update(region) local k_region = h_region:final() local h_service = resty_hmac:new(k_region, resty_hmac.ALGOS.SHA256) h_service:update(service) local k_service = h_service:final() local h = resty_hmac:new(k_service, resty_hmac.ALGOS.SHA256) h:update('aws4_request') return h:final() end local function get_cred_scope(timestamp, region, service) return get_iso8601_basic_short(timestamp) .. '/' .. region .. '/' .. service .. '/aws4_request' end local function get_signed_headers() return 'host;x-amz-content-sha256;x-amz-date' end local function get_sha256_digest(s) local h = resty_sha256:new() h:update(s or '') return str.to_hex(h:final()) end local function get_hashed_canonical_request(timestamp, host, uri) local digest = get_sha256_digest(ngx.var.request_body) local canonical_request = ngx.var.request_method .. '\n' .. uri .. '\n' .. '\n' .. 'host:' .. host .. '\n' .. 'x-amz-content-sha256:' .. digest .. '\n' .. 'x-amz-date:' .. get_iso8601_basic(timestamp) .. '\n' .. '\n' .. get_signed_headers() .. '\n' .. digest return get_sha256_digest(canonical_request) end local function get_string_to_sign(timestamp, region, service, host, uri) return 'AWS4-HMAC-SHA256\n' .. get_iso8601_basic(timestamp) .. '\n' .. get_cred_scope(timestamp, region, service) .. '\n' .. get_hashed_canonical_request(timestamp, host, uri) end local function get_signature(derived_signing_key, string_to_sign) local h = resty_hmac:new(derived_signing_key, resty_hmac.ALGOS.SHA256) h:update(string_to_sign) return h:final(nil, true) end local function get_authorization(keys, timestamp, region, service, host, uri) local derived_signing_key = get_derived_signing_key(keys, timestamp, region, service) local string_to_sign = get_string_to_sign(timestamp, region, service, host, uri) local auth = 'AWS4-HMAC-SHA256 ' .. 'Credential=' .. keys['access_key'] .. '/' .. get_cred_scope(timestamp, region, service) .. ', SignedHeaders=' .. get_signed_headers() .. ', Signature=' .. get_signature(derived_signing_key, string_to_sign) return auth end local function get_service_and_region(host) local patterns = { {'s3.amazonaws.com', 's3', 'us-east-1'}, {'s3-external-1.amazonaws.com', 's3', 'us-east-1'}, {'s3%-([a-z0-9-]+)%.amazonaws%.com', 's3', nil} } for _,data in ipairs(patterns) do local region = host:match(data[1]) if region ~= nil and data[3] == nil then return data[2], region elseif region ~= nil then return data[2], data[3] end end return nil, nil end function _M.aws_set_headers(host, uri) local creds = get_credentials() local timestamp = tonumber(ngx.time()) local service, region = get_service_and_region(host) local auth = get_authorization(creds, timestamp, region, service, host, uri) ngx.req.set_header('Authorization', auth) ngx.req.set_header('Host', host) ngx.req.set_header('x-amz-date', get_iso8601_basic(timestamp)) end function _M.s3_set_headers(host, uri) _M.aws_set_headers(host, uri) ngx.req.set_header('x-amz-content-sha256', get_sha256_digest(ngx.var.request_body)) end return _M
--------------------------------------------------------------------------------------------------- -- User story: SubtleAlert cases -- Use case: SubtleAlert -- Item: VRSession interrupts SubtleAlert in progress -- -- Requirement summary: -- [SubtleAlert] ABORTED: request with UI portion interrupted by higher priority event -- -- Description: -- Mobile application sends valid SubtleAlert request with UI-related-params. HMI starts VR session -- during SubtleAlert dialog and sends ABORTED resultCode for UI.SubtleAlert -- Pre-conditions: -- a. HMI and SDL are started -- b. appID is registered and activated on SDL -- c. appID is currently in Full or Limited HMI level -- Steps: -- appID requests SubtleAlert with UI-related-params -- HMI starts VR session during SubtleAlert -- Expected: -- SDL validates parameters of the request -- SDL checks if UI interface is available on HMI -- SDL checks if SubtleAlert is allowed by Policies -- SDL checks if all parameters are allowed by Policies -- SDL transfers the UI.SubtleAlert part of request with allowed parameters to HMI -- SDL receives VR.Started notification and OnSystemContext(VRSESSION) from HMI -- SDL receives UI.SubtleAlert part of response from HMI with "ABORTED" result code -- SDL responds with (resultCode: ABORTED, success:false) to mobile application --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('test_scripts/API/SubtleAlertStyle/commonSubtleAlert') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local Variables ]] local putFileParams = { syncFileName = "icon.png", fileType = "GRAPHIC_PNG", persistentFile = false, systemFile = false } local iconFilePath = "files/icon.png" local requestParams = { alertText1 = "alertText1", alertText2 = "alertText2", alertIcon = { value = "icon.png", imageType = "DYNAMIC" } } local uiRequestParams = { alertStrings = { { fieldName = "subtleAlertText1", fieldText = requestParams.alertText1 }, { fieldName = "subtleAlertText2", fieldText = requestParams.alertText2 } }, alertType = "UI", alertIcon = requestParams.alertIcon, duration = 5000 } local allParams = { requestParams = requestParams, uiRequestParams = uiRequestParams } --[[ Local Functions ]] local function prepareParams(pParams) local params = common.cloneTable(pParams) params.uiRequestParams.appID = common.getHMIAppId() params.uiRequestParams.alertIcon.value = common.getPathToFileInAppStorage(putFileParams.syncFileName) return params end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Update Preloaded PT", common.updatePreloadedPT) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("Register App", common.registerApp) runner.Step("Activate App", common.activateApp) runner.Step("Upload icon file", common.putFile, { { requestParams = putFileParams, filePath = iconFilePath } }) runner.Title("Test") runner.Step("SubtleAlert interrupted by VR, ABORTED result", common.subtleAlertAbortedByVR, { allParams, prepareParams }) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
-- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you 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. -- module containing modsecurity to be used local ffi = require("ffi") ffi.cdef[[ typedef struct ModSecurity ModSecurity; ModSecurity* msc_init(); void msc_set_connector_info(ModSecurity *msc, const char *connector); void msc_cleanup(ModSecurity *msc); typedef struct Rules Rules; Rules* msc_create_rules_set(); int msc_rules_add_file(Rules *rules, const char *file, const char **error); int msc_rules_cleanup(Rules *rules); typedef struct Transaction Transaction; Transaction *msc_new_transaction(ModSecurity *ms, Rules *rules, void *logCbData); int msc_process_connection(Transaction *transaction, const char *client, int cPort, const char *server, int sPort); int msc_process_uri(Transaction *transaction, const char *uri, const char *protocol, const char *http_version); int msc_add_request_header(Transaction *transaction, const unsigned char *key, const unsigned char *value); int msc_process_request_headers(Transaction *transaction); int msc_process_request_body(Transaction *transaction); int msc_add_response_header(Transaction *transaction, const unsigned char *key, const unsigned char *value); int msc_process_response_headers(Transaction *transaction, int code, const char* protocol); int msc_process_response_body(Transaction *transaction); int msc_process_logging(Transaction *transaction); void msc_transaction_cleanup(Transaction *transaction); typedef struct ModSecurityIntervention_t { int status; int pause; char *url; char *log; int disruptive; } ModSecurityIntervention; int msc_intervention(Transaction *transaction, ModSecurityIntervention *it); ]] local msc = ffi.load("/usr/local/modsecurity/lib/libmodsecurity.so") return msc
EFFECT.Mat = Material( "effects/tool_tracer" ) function EFFECT:Init( data ) self.Position = data:GetStart() self.WeaponEnt = data:GetEntity() self.Attachment = data:GetAttachment() -- Keep the start and end pos - we're going to interpolate between them self.StartPos = self:GetTracerShootPos( self.Position, self.WeaponEnt, self.Attachment ) self.EndPos = data:GetOrigin() self.Alpha = 255 self.Life = 0 self:SetRenderBoundsWS( self.StartPos, self.EndPos ) end function EFFECT:Think() self.Life = self.Life + FrameTime() * 4 self.Alpha = 255 * ( 1 - self.Life ) return ( self.Life < 1 ) end function EFFECT:Render() if ( self.Alpha < 1 ) then return end render.SetMaterial( self.Mat ) local texcoord = math.Rand( 0, 1 ) local norm = (self.StartPos - self.EndPos) * self.Life self.Length = norm:Length() for i = 1, 3 do render.DrawBeam( self.StartPos - norm, -- Start self.EndPos, -- End 8, -- Width texcoord, -- Start tex coord texcoord + self.Length / 128, -- End tex coord color_white ) -- Color (optional) end render.DrawBeam( self.StartPos, self.EndPos, 8, texcoord, texcoord + ( ( self.StartPos - self.EndPos ):Length() / 128 ), Color( 255, 255, 255, 128 * ( 1 - self.Life ) ) ) end
-- THIS CONTENTS OF THIS FILE IS AUTO-GENERATED BY THE WOWACE PACKAGER -- Please use the Localization App on WoWAce to update this -- at http://www.wowace.com/projects/omen-threat-meter/localization/ -- Translation courtesy of Ben (Aesyl - US Tanaris) local AceLocale = LibStub:GetLibrary("AceLocale-3.0") local L = AceLocale:NewLocale("Omen", "esES") or AceLocale:NewLocale("Omen", "esMX") if not L then return end L["*Not in Party*"] = "*No está en el grupo*" L["|cffff0000Error:|r Omen cannot use shake warning if you have turned on nameplates at least once since logging in."] = "|cffff0000Error:|r Omen no puede usar el aviso de sacudida si ha activado las placas de nombre al menos una vez desde que ha iniciado." L["<Unknown>"] = "<Desconocido>" L["> Pull Aggro <"] = "> Tomar amenaza <" L["A collection of help pages"] = "Una colección de páginas útiles" L["Alpha"] = "Transparencia" L["Always Show Self"] = "Siempre mostrarme " L["Always show your threat bar on Omen (ignores class filter settings), showing your bar on the last row if necessary"] = "Siempre muestra tu barra de amenaza en Omen (ignora las opciones de filtros de clase), mostrando tu barra en la última fila si es necesario." L["Ambience"] = "Ambiente" L["Animate Bars"] = "Animar las barras" L["Attach to minimap"] = "Adherir a Minimapa" L["AUTO_SHOW/HIDE_NOTE"] = "Nota: Si usted muestra/oculta Omen manualmente, éste se mostrará o permanecerá oculto, independientemente de los ajustes de automostrar/ocultar hasta que llegues a la próxima zona, te unas o abandones un grupo o banda, o cambies cualquier ajuste de automostrar/ocultar." L["Autocollapse"] = "Autocontraer" L["Autocollapse Options"] = "Opciones de autocontraer" L["Background Color"] = "Color de fondo" L["Background Options"] = "Opciones de fondo" L["Background Texture"] = "Textura de fondo" L["Background Tile Size"] = "Tamaño del mosaico " L["Bar BG Color"] = "Color de fondo de las barras" L["Bar Height"] = "Altura de la barra" L["Bar Inset"] = "Recuadro de la barra" L["Bar Label Options"] = "Opciones de las etiquetas de las barras" L["Bar Settings"] = "Opciones de barra" L["Bar Spacing"] = "Espacio entre barras" L["Bar Texture"] = "Textura de barra" L["Border Color"] = "Color de borde" L["Border Texture"] = "Textura de borde" L["Border Thickness"] = "Grosor de borde" L["Causes Omen to play a chosen sound effect"] = "Hace que Omen reproduzca un efecto de sonido elegido." L["Causes the entire game world to shake momentarily. This option only works if nameplates are turned off."] = "Hace que toda la pantalla del juego tiemble brevemente. Esta opción sólo funciona si las placas de nombre están desactivadas." L["Causes the entire screen to flash red momentarily"] = "Hace que la pantalla entera destelle de rojo brevemente." L["Center"] = "Centro" L["Center Omen"] = "Centrar Omen" L["Clamp To Screen"] = "Anclar a la pantalla" L["Click Through"] = "Clic a través" L["Click|r to toggle the Omen window"] = "Haz clic|r para mostrar/ocultar la ventana de Omen" L["Collapse to show a minimum number of bars"] = "Contrae para mostrar un número reducido de barras." L["Configure"] = "Configurar" L["Configure bar settings."] = "Configurar las opciones de barra." L["Configure title bar settings."] = "Configurar opciones de la barra de título." L["Control the font size of the labels"] = "Controla el tamaño de la fuente de las etiquetas." L["Control the font size of the title text"] = "Controla el tamaño de la fuente del texto del título." L["Controls the frame strata of the main Omen window. Default: MEDIUM"] = "Controla la capa del marco de la ventana principal de Omen. Por defecto: MEDIUM" L["Controls the scaling of the main Omen window."] = "Controla la escala de la ventana principal de Omen." L["Controls the transparency of the main Omen window."] = "Controla la transparencia de la ventana principal de Omen." L["Controls whether the main Omen window can be dragged offscreen"] = "Controla si la ventana principal de Omen puede ser movida fuera de la pantalla." L["DEATHKNIGHT"] = "Caballero de la Muerte" --[[Translation missing --]] --[[ L["DEMONHUNTER"] = "Demon Hunter"--]] L["Disable while tanking"] = "Desactivar de tanque" L["DISABLE_WHILE_TANKING_DESC"] = "No dará ninguna alerta si Actitud defensiva, Forma de oso, Furia recta o Presencia de Sangre está activo." L["Display large numbers in Ks"] = "Muestra los números grandes en Ks." L["DRUID"] = "Druida" L["Enable Screen Flash"] = "Destello de pantalla" L["Enable Screen Shake"] = "Sacudida de pantalla" L["Enable Sound"] = "Activar sonido" L["Enable Warning Message"] = "Mensaje de aviso" L["FAQ Part 1"] = "FAQ parte 1" L["FAQ Part 2"] = "FAQ parte 2" L["Font"] = "Fuente" L["Font Color"] = "Color de fuente" L["Font Outline"] = "Borde de fuente" L["Font Size"] = "Tamaño de fuente" L["Frame Strata"] = "Capa del marco" L["Frame's background color"] = "Color del fondo del marco." L["Frame's border color"] = "Color del borde del marco." L["Frequently Asked Questions"] = "Preguntas frecuentes (FAQ)" L["FuBar Options"] = "Opciones de FuBar" L["General Settings"] = "Opciones generales" L["GENERAL_FAQ"] = [=[|cffffd200¿Qué diferencias hay entre Omen3 y Omen2?|r Omen3 cuenta completamente con el API de amenaza de Blizzard y eventos de amenaza. A diferencia de Omen2, no trata de calcular o extrapolar la amenaza. Omen2 era lo que llamábamos la biblioteca Threat-2.0. Esta biblioteca era responsable de observar el diario de combate, hechizos, ventajas, desventajas, actitudes, talentos y modificadores de equipo para calcular la amenaza de cada una individualmente. La amenaza se calculaba basándose en informaciones conocidas o aproximaciones de conductas observadas. Muchas informaciones, como los golpes por la espalda, se basaban en suposiciones. La biblioteca Threat-2.0 también incluía comunicación para transmitir su amenaza al resto de la banda mientras usaran también Threat-2.0. Esta información era usada para dar una muestra de información de amenaza que incluyera la banda entera. Desde el parche 3.0.2, Omen ya no hace estas cosas y una biblioteca de amenaza ya no es necesaria. Omen3 usa el monitor de amenaza de Blizzard para obtener los valores exactos de la amenaza de cada miembro. Esto significa que Omen3 no necesita sincronización de datos, analizar el diario de combate o intentar adivinar. Esto conlleva un aumento significativo en rendimiento con respecto al tráfico de red, uso de la CPU y de la memoria. La implementación de módulos por jefes específicos ya no es necesaria. Además esta implementación nueva permite la adición de la amenaza de NPCs. Sin embargo, hay desventajas; las actualizaciones son menos frecuentes, los detalles de amenaza no pueden obtenerse a menos que alguien en su banda esté apuntando al enemigo, y no es posible obtener amenaza de un enemigo con el que usted no está en combate. |cffffd200¿Cómo me deshago de las 2 líneas verticales de color gris de la mitad?|r Bloquea tu Omen. Bloquear Omen evita que sea movido o reescalado, como también previene que el tamaño de las columnas sea cambiado. Si no realizas esto, las 2 líneas grises verticales seguirán ahí para poder cambiar las columnas manualmente. |cffffd200¿Cómo hago que Omen3 se parezca a Omen2?|r Cambia la textura de fondo y textura de borde a "Blizzard Tooltip", cambia el color de fondo a negro (arrastra hacia abajo la barra de luminosidad), y el color de borde a azul. |cffffd200¿Por qué no me muestra la amenaza en un enemigo cuándo lo apunto, aun cuando él está en combate?|r El API de amenaza de Blizzard no devuelve datos de amenaza de un enemigo con el que no estás en combate directamente, porque no estarás en su lista de amenaza. Creemos que esto es un esfuerzo para reducir tráfico de red. |cffffd200¿Hay forma de sortear esta limitación de Blizzard? No poder ver la amenaza de mi mascota antes de que yo ataque me obliga a especular.|r No hay forma de sortear esta limitación excepto que nosotros especulemos por ti (que es exactamente lo que hacía Omen2). El objetivo de Omen3 es proveer información fiable sobre la amenaza, ya no intentamos especular por ti y en el camino reducir tus FPS. Ten algo de confianza en tu mascota/tanque, o sólo espera 2 segundos antes de atacar y usa un hechizo de poco daño como Lanza de Hielo para que puedas obtener unas lecturas iniciales de amenaza. ]=] L["GENERAL_FAQ2"] = [=[|cffffd200¿Podemos obtener de nuevo el modo de AOE?|r De nuevo, esto no es realmente posible sin adivinar valores de amenaza. La API de amenaza de Blizzard sólo nos permite consultar datos sobre la amenaza de las unidades que alguien de la banda este seleccionando. Esto significa que si hay 20 enemigos y sólo 6 de ellos son seleccionados por la banda, no hay manera de obtener datos exactos sobre la amenaza de los otros 14. Esto también es extremadamente complicado de adivinar sobre todo para la curación y beneficios (la amenaza se divide por el número de enemigos que están en combate), ya que los enemigos que se encuentran bajo efectos de control de masas (oveja, desterrar, porrazo, etc.) no tienen su tabla de amenaza modificados y el Addon no puede saber con fiabilidad el número de enemigos que están en combate. El adivinar de Omen2 es casi siempre equivocado. |cffffd200Las ventanas emergentes al pasar el ratón por encima de una unidad muestra un % de amenaza que no coincide con el % de amenaza reportado por Omen3. ¿Por qué?|r El porcentaje de amenaza de Blizzard se escala de 0% a 100%, por lo que siempre muestra agresividad en un 100%. Omen informa de los valores sin escala primas que tira porcentajes de agresividad al 110%, en combate cuerpo a cuerpo y 130% de otra manera. Por acuerdo universal, el objetivo principal de un grupo atraído por el tanque se define en 100% de amenaza. |cffffd200¿Hace Omen3 sincronización o analiza el registro de combate?|r No. Omen3 no intenta sincronizar o analizar el registro de combate. De momento no hay intenciones de hacerlo. |cffffd200Las actualizaciones de Omen son lentas...|r Omen3 actualiza los valores de amenaza que se ven tan a menudo como Blizzard actualiza los valores de amenaza para nosotros. De hecho, Blizzard actualiza aproximadamente una vez por segundo, que es mucho más rápido que lo que Omen2 usaba para sincronizar las actualizaciones. En Omen2, sólo transmitía su amenaza para el resto de la banda una vez cada 3 segundos (o 1.5 seg si es un tanque). |cffffd200¿Dónde puedo reportar errores o hacer sugerencias?|r http://forums.wowace.com/showthread.php?t=14249 |cffffd200¿Quién diseñó Omen3?|r El diseñador principal de Omen es Xinhuan (Reino Blackrock/Barthilas de EE.UU., Alianza). |cffffd200¿Aceptan donaciones de Paypal?|r Sí, por favor, envíalas a Xinhuan@Gmail.com.]=] L["Grow bars upwards"] = "Crecer hacia arriba" L["Heading background color"] = "Color de fondo de categorías" L["Heading BG Color"] = "Color de fondo de categorías" L["Height of each bar"] = "Altura de cada barra" L["Height of the title bar. The minimum height allowed is twice the background border thickness."] = "Altura de la barra de título. La altura mínima permitida es el doble del grosor del borde del fondo." L["Help File"] = "Archivo de ayuda" L["Hide minimap/FuBar icon"] = "Ocultar icono del Minimapa/FuBar" L["Hide Omen"] = "Ocultar Omen" L["Hide Omen entirely if it collapses to show 0 bars"] = "Oculta Omen completamente si al contraerse muestra cero barras." L["Hide Omen on 0 bars"] = "Ocultar con cero barras" L["However, hide Omen if any of the following are true (higher priority than the above)."] = "Sin embargo, oculta Omen si alguno de lo siguiente es verdadero (prioridad sobre lo anterior)." L["HUNTER"] = "Cazador" L["Ignore Player Pets"] = "Ignorar mascotas" L["IGNORE_PLAYER_PETS_DESC"] = [=[Indica a Omen que ignore las mascotas de los jugadores enemigos al determinar qué unidades debe mostrar en los datos de amenaza. Las mascotas de los jugadores mantienen una tabla de amenaza cuando se encuentran en modo |cffffff78Agresivo|r o |cffffff78Defensivo|r y se comportan de manera normal atacando al objetivo con la amenaza más alta. Si se le indica a la mascota que ataque a un objetivo específico, ésta mantiene su tabla de amenaza, pero permanece con el objetivo asignado el cual por definición tiene 100% de amenaza. Las mascotas de los jugadores pueden ser provocadas para forzarlas a que te ataquen. Las mascotas de los jugadores en modo |cffffff78Pasivo|r no tienen tabla de amenaza y la habilidad provocar no funciona en ellas, sólo atacarán a su objetivo asignado cuando se les indique hacerlo y lo harán sin ninguna tabla de amenaza. Cuando a una mascota se le indica |cffffff78Seguir|r al jugador, su tabla de amenaza es eliminada inmediatamente y deja de atacar su objetivo, aunque podría volver a adquirir un nuevo objetivo si se encuentra en modo agresivo/defensivo.]=] L["Invert Bar/Text Colors"] = "Invertir barras/texto" L["Left"] = "Izquierda" L["Lock Omen"] = "Bloquear Omen" L["Locks Omen in place and prevents it from being dragged or resized."] = "Bloquea Omen en el sitio y evita que sea arrastrado o redimensionado." L["MAGE"] = "Mago" L["Makes the Omen window non-interactive"] = "Hace la ventana de Omen no interactiva." L["Master"] = "Maestro" L["Max bars to show"] = "Máx. de barras a mostrar" L["Max number of bars to show"] = "Número máximo de barras que mostrará." L["Music"] = "Música" L["'My Bar' BG Color"] = "Color de fondo de \"Mi barra\"" L["Name"] = "Nombre" L["None"] = "Ninguno" L["Omen Quick Menu"] = "Menú rápido de Omen" L["OMEN_DESC"] = "Omen es un medidor ligero de amenaza que muestra la amenaza del enemigo con el que usted está en combate. Puede configurar cómo Omen se ve y funciona, y configurar perfiles diferentes para cada personaje." L["OMEN_SLASH_DESC"] = "Estos botones ejecutan las mismas funciones que los del comando /omen" L["OMEN_WARNINGS_DESC"] = "Esta sección te permite configurar cuándo y cómo Omen te notifica si tu amenaza es demasiada alta o si tomas la amenaza." L["Open Config"] = "Abrir configuración" L["Open Omen's configuration panel"] = "Abrir el panel de configuración de Omen" L["Open the configuration dialog"] = "Abrir el panel de configuración" L["Outline"] = "Borde" L["PALADIN"] = "Paladín" L["Passed %s%% of %s's threat!"] = "¡Pasado %s%% de %s de amenaza!" L["PET"] = "Mascota" L["Pet Bar Color"] = "Color de la barra de mascotas" L["Position"] = "Posición" L["PRIEST"] = "Sacerdote" L["Print a message to screen when you accumulate too much threat"] = "Muestra un mensaje en pantalla cuándo acumulas demasiada amenaza." L["Profiles"] = "Perfiles" L["Pull Aggro Bar Color"] = "Color de la barra de \"Tomar amenaza\"" L["Right"] = "Derecha" L["Right-click|r to open the options menu"] = "Haz clic con el botón derecho|r para abrir el menú de opciones" L["ROGUE"] = "Pícaro" L["Scale"] = "Escala" L["Sets how far inside the frame the threat bars will display from the 4 borders of the frame"] = "Controla a qué distancia de los cuatro bordes del marco se situarán las barras de amenaza." L["SFX"] = "SFX" L["SHAMAN"] = "Chamán" L["Short Numbers"] = "Números cortos" L["Show a bar for the amount of threat you will need to reach in order to pull aggro."] = "Muestra una barra que indica la amenaza que necesitas para tomar la amenaza y te ataquen." L["Show bars for these classes"] = "Mostrar barras para estas clases" L["Show Classes..."] = "Mostrar clases..." L["Show column headings"] = "Muestra las categorías sobre las columnas." L["Show Headings"] = "Mostrar categorías" L["Show icon"] = "Mostrar icono" L["Show minimap button"] = "Icono en el Minimapa" L["Show Omen"] = "Mostrar Omen" L["Show Omen when any of the following are true"] = "Muestra Omen cuándo cualquiera de lo siguiente es verdadero." L["Show Omen when you are alone"] = "Muestra Omen cuándo estás solo(a)." L["Show Omen when you are in a 5-man party"] = "Muestra Omen cuándo estás en un grupo de cinco miembros." L["Show Omen when you are in a raid"] = "Muestra Omen cuándo estas en una banda." L["Show Omen when you have a pet out"] = "Muestra Omen cuándo tienes una mascota fuera." L["Show Omen when..."] = "Mostrar Omen cuándo..." L["Show Pull Aggro Bar"] = "Barra Tomar amenaza" L["Show text"] = "Mostrar texto" L["Show the Omen minimap button"] = "Muestra el icono de Omen en el Minimapa." L["Show the Omen Title Bar"] = "Muestra la barra de título de Omen." L["Show Threat %"] = "Porcentaje de amenaza" L["Show threat per second values"] = "Muestra la amenaza por segundo (APS)." L["Show Threat Values"] = "Valores de amenaza" L["Show Title Bar"] = "Mostrar barra de título" L["Show TPS"] = "Mostrar APS" L["Show When..."] = "Mostrar cuando..." L["SHOW_CLASSES_DESC"] = "Mostrar barras de amenaza de Omen de las clases siguientes. Las clases de aquí se refieren solamente a las personas que están en tu grupo/banda a excepción de la opción 'No está en el grupo'." L["Slash Command"] = "Barras de comando" L["Smoothly animate bar changes"] = "Anima suavemente las barras." L["Sound Channel"] = "Canal de sonido" L["Sound to play"] = "Sonido a reproducir" L["Spacing between each bar"] = "Espacio entre cada barra." L["Switch the colors so that the bar background colors and the text colors are swapped."] = "Cambia los colores de modo que el fondo de la barra y el color del texto se intercambien." L["Tank Bar Color"] = "Color de la barra del tanque" L["Tells Omen to additionally check your 'focus' and 'focustarget' before your 'target' and 'targettarget' in that order for threat display."] = "Indica a Omen que adicionalmente revise tu 'foco' y 'objetivo de foco' antes que tu 'objetivo' y 'objetivo de objetivo\" en ese orden, en la ventana de amenaza." L["Tells Omen to enter Test Mode so that you can configure Omen's display much more easily."] = "Omen entra en Modo de prueba para que puedas configurar la ventana de Omen más fácilmente." L["Temp Threat Bar Color"] = "Color de barra de amenaza temporal" L["Test Mode"] = "Modo de prueba" L["Test warnings"] = "Prueba de aviso" L["Texture to use for the frame's background"] = "Textura usada en el fondo del marco." L["Texture to use for the frame's border"] = "Textura usada en el borde del marco." L["The background color for all threat bars"] = "El color de fondo para todas las barras de amenaza." L["The background color for pets"] = "El color de fondo para las barras de mascotas." L["The background color for players under the effects of Fade, Mirror Image, Tricks of the Trade and Misdirection"] = "El color de fondo para los jugadores bajo los efectos de Desvanecerse, Reflejo exacto, Mano de salvación con glifo, Secretos del oficio y Redirección." L["The background color for your Pull Aggro bar"] = "El color de fondo para tu barra de \"Tomar amenaza\"" L["The background color for your tank's threat bar"] = "El color de fondo de la barra de amenaza del tanque." L["The background color for your threat bar"] = "El color de fondo de tu barra de amenaza." L["The color of the labels"] = "El color de las etiquetas." L["The color of the title text"] = "El color del texto del título." L["The font that the labels will use"] = "La fuente que las etiquetas usarán." L["The font that the title text will use"] = "La fuente que el título usará." L["The outline that the labels will use"] = "El borde que las etiquetas usarán." L["The outline that the title text will use"] = "El borde que el texto del título usará." L["The size used to tile the background texture"] = "El tamaño usado para la textura del mosaico del fondo." L["The texture that the bar will use"] = "La textura que la barra usará." L["The thickness of the border"] = "El grosor del borde." L["Thick Outline"] = "Borde grueso" L["This section controls when Omen is automatically shown or hidden."] = "Esta sección controla cuando Omen se muestra u oculta automáticamente." L["Threat"] = "Amenaza" L["Threat [%]"] = "Amenaza [%]" L["Tile Background"] = "Fondo en mosaico " L["Tile the background texture"] = "Pone en mosaico la textura de fondo." L["Title Bar Background Options"] = "Opciones de fondo de la barra de título" L["Title Bar Height"] = "Altura de la barra de título" L["Title Bar Settings"] = "Barra de título" L["Title Text Options"] = "Opciones de texto del título" L["Toggle Focus"] = "Mostrar/ocultar foco" L["Toggle Omen"] = "Mostrar/ocultar" L["TPS"] = "APS" L["TPS Window"] = "Ventana de APS" L["TPS_WINDOW_DESC"] = "El cálculo de amenaza por segundo se basa en una ventana deslizante en tiempo real de los últimos X segundos." L["Turning this on will cause Omen to hide whenever you are in a battleground or arena."] = "Activar esto hace que Omen se oculte mientras estás en un campo de batalla o arena." L["Turning this on will cause Omen to hide whenever you are in a city or inn."] = "Activar esto hace que Omen se oculte cuando estés en una ciudad o posada." L["Turning this on will cause Omen to hide whenever you are not in combat."] = "Activar esto hace que Omen se oculte cuando no estés en combate." L["Use !ClassColors"] = "Usar !ClassColors" L["Use !ClassColors addon for class colors for the background color of threat bars"] = "Usa el Addon !ClassColors para los colores de fondo de las barras de amenaza." L["Use a different colored background for the tank's threat bar in Omen"] = "Usa un color de fondo diferente para la barra de amenaza del tanque en Omen." L["Use a different colored background for your threat bar in Omen"] = "Usa un color de fondo diferente para tu barra de amenaza en Omen." L["Use Auto Show/Hide"] = "Automostrar/ocultar" L["Use Class Colors"] = "Usar colores de clase" L["Use Focus Target"] = "Usar objetivo de foco" L["Use 'My Bar' color"] = "Color de tu barra" L["Use Same Background"] = "Usar el mismo fondo" L["Use standard class colors for the background color of threat bars"] = "Usa los colores de clase estándar para el color de fondo de las barras de amenaza." L["Use Tank Bar color"] = "Color del tanque" L["Use the same background settings for the title bar as the main window's background"] = "Usa las mismas opciones de fondo de la ventana principal en la barra de título." L["WARLOCK"] = "Brujo" L["Warning Settings"] = "Opciones de aviso" L["Warning Threshold %"] = "Umbral de aviso %" L["Warrior"] = "Guerrero" L["WARRIOR"] = "Guerrero" L["WARRIOR_FAQ"] = [=[La siguiente información está obtenida de |cffffd200http://www.tankspot.com/forums/f200/39775-wow-3-0-threat-values.html|r 02 de octubre 2008 (crédito a Satrina). Los números son para un personaje de nivel 80. |cffffd200Modificadores|r Actitud de batalla ________ x 80 Actitud rabiosa _____ x 80 Maestría táctica _____ x 121/142/163 Actitud defensiva _____ x 207.35 Nota que en nuestras estimaciones originales (que usamos ahora en WoW 2.0), comparábamos 1 daño a 1 amenaza, y usábamos 1.495 para representar el modificador multiplicador de actitud + desafío. Ahora vemos que el método de Blizzard es para usar el multiplicador sin decimales, así en 2.x habría estado x149 (quizás x149.5); es x207 (quizás 207.3) en 3.0. Supongo que esto es para permitir el transporte de números enteros en vez de decimales a través del Internet para mejorar el rendimiento. Parece que los valores de amenaza son multiplicados por 207.35 al servidor, pues redondeado. Si quiere usar el método 1 daño = 1 amenaza todavía; los modificadores de actitud son 0.8 y 2.0735, etc... |cffffd200Valores de Amenaza (modificadores de actitud aplica a menos que dijera otra cosa):|r Grito de batalla _________ 78 (divido) Rajar _______________ daño + 225 (divido) Grito de orden _____ 80 (divido) Arremetida de conmoción ______ daño solamente Escudo de daño ________ daño solamente Grito desmoralizador ___ 63 (divido) Devastar ____________ daño + 5% de AP Esquivar/Parar/Bloquear_____ 1 (en actitud defensiva solamente con Actitud defensiva mejorada) Golpe heroico ________ daño + 259 Salto heroico _________ 1.50 x daño Gana de ira ____________ 5 (sin modificador de actitud) Desgarrar _________________ daño solamente Revancha ______________ daño + 121 Azote de escudo __________ 36 Embate con escudo __________ daño + 770 Onda de choque ____________ daño solamente Embate _________________ daño + 140 Reflejo de hechizos ________ daño solamente Amenaza social _________ 0 Hender armadura ________ 345 + 5%AP Atronar _________ 1.85 x daño Vigilancia ____________ 10% de la amenaza del blanco (sin modificador de actitud) No gana amenaza por reflejar hechizos apuntado a sus aliados con Reflejo de hechizos mejorado. Cuándo refleja un hechizo por un aliado, el aliado gana la amenaza por el daño del hechizo. ]=] L["You are alone"] = "Estás solo(a)" L["You are in a battleground"] = "Estás en un campo de batalla" L["You are in a party"] = "Estás en un grupo" L["You are in a raid"] = "Estás en una banda" L["You are not in combat"] = "No estás en combate" L["You are resting"] = "Estás en una ciudad o posada" L["You have a pet"] = "Tienes una mascota"
-- ======= Copyright (c) 2003-2013, Unknown Worlds Entertainment, Inc. All rights reserved. ===== -- -- lua\Skulk.lua -- -- Created by: Charlie Cleveland (charlie@unknownworlds.com) -- Andreas Urwalek (andi@unknownworlds.com) -- -- ========= For more information, visit us at http://www.unknownworlds.com ===================== Script.Load("lua/Utility.lua") Script.Load("lua/Weapons/Alien/BiteLeap.lua") Script.Load("lua/Weapons/Alien/Parasite.lua") Script.Load("lua/Weapons/Alien/XenocideLeap.lua") Script.Load("lua/Weapons/Alien/ReadyRoomLeap.lua") Script.Load("lua/Alien.lua") Script.Load("lua/Mixins/BaseMoveMixin.lua") Script.Load("lua/Mixins/GroundMoveMixin.lua") Script.Load("lua/Mixins/CrouchMoveMixin.lua") Script.Load("lua/Mixins/JumpMoveMixin.lua") Script.Load("lua/CelerityMixin.lua") Script.Load("lua/Mixins/CameraHolderMixin.lua") Script.Load("lua/WallMovementMixin.lua") Script.Load("lua/DissolveMixin.lua") Script.Load("lua/BabblerClingMixin.lua") Script.Load("lua/TunnelUserMixin.lua") Script.Load("lua/RailgunTargetMixin.lua") Script.Load("lua/IdleMixin.lua") Script.Load("lua/SkulkVariantMixin.lua") class 'Skulk' (Alien) Skulk.kMapName = "skulk" Skulk.kModelName = PrecacheAsset("models/alien/skulk/skulk.model") local kViewModelName = PrecacheAsset("models/alien/skulk/skulk_view.model") local kSkulkAnimationGraph = PrecacheAsset("models/alien/skulk/skulk.animation_graph") -- Balance, movement, animation Skulk.kViewOffsetHeight = .55 Skulk.kHealth = kSkulkHealth Skulk.kArmor = kSkulkArmor local kDashSound = PrecacheAsset("sound/NS2.fev/alien/skulk/full_speed") local kLeapVerticalForce = 10.8 local kLeapTime = 0.2 local kLeapForce = 7.6 Skulk.kMaxSpeed = 7.25 Skulk.kSneakSpeedModifier = 0.66 local kMass = 45 -- ~100 pounds -- How big the spheres are that are casted out to find walls, "feelers". -- The size is calculated so the "balls" touch each other at the end of their range local kNormalWallWalkFeelerSize = 0.25 local kNormalWallWalkRange = 0.3 -- jump is valid when you are close to a wall but not attached yet at this range local kJumpWallRange = 0.4 local kJumpWallFeelerSize = 0.1 Skulk.kXExtents = .45 Skulk.kYExtents = .45 Skulk.kZExtents = .45 Skulk.kMaxSneakOffset = 0 --0.55 Skulk.kWallJumpInterval = 0.4 Skulk.kWallJumpForce = 6.4 -- scales down the faster you are Skulk.kMinWallJumpForce = 0.1 Skulk.kVerticalWallJumpForce = 4.3 Skulk.kWallJumpMaxSpeed = 11 Skulk.kWallJumpMaxSpeedCelerityBonus = 1.2 if Server then Script.Load("lua/Skulk_Server.lua", true) elseif Client then Script.Load("lua/Skulk_Client.lua", true) end local networkVars = { wallWalking = "compensated boolean", timeLastWallWalkCheck = "private compensated time", leaping = "compensated boolean", timeOfLeap = "private compensated time", timeOfLastJumpLand = "private compensated time", timeLastWallJump = "private compensated time", jumpLandSpeed = "private compensated float", dashing = "compensated boolean", timeOfLastPhase = "private time", -- sneaking (movement modifier) skulks starts to trail their body behind them sneakOffset = "compensated interpolated float (0 to 1 by 0.04)" } AddMixinNetworkVars(BaseMoveMixin, networkVars) AddMixinNetworkVars(GroundMoveMixin, networkVars) AddMixinNetworkVars(JumpMoveMixin, networkVars) AddMixinNetworkVars(CrouchMoveMixin, networkVars) AddMixinNetworkVars(CelerityMixin, networkVars) AddMixinNetworkVars(CameraHolderMixin, networkVars) AddMixinNetworkVars(DissolveMixin, networkVars) AddMixinNetworkVars(BabblerClingMixin, networkVars) AddMixinNetworkVars(TunnelUserMixin, networkVars) AddMixinNetworkVars(IdleMixin, networkVars) AddMixinNetworkVars(SkulkVariantMixin, networkVars) function Skulk:OnCreate() InitMixin(self, BaseMoveMixin, { kGravity = Player.kGravity }) InitMixin(self, GroundMoveMixin) InitMixin(self, JumpMoveMixin) InitMixin(self, CrouchMoveMixin) InitMixin(self, CelerityMixin) InitMixin(self, CameraHolderMixin, { kFov = kSkulkFov }) InitMixin(self, WallMovementMixin) InitMixin(self, SkulkVariantMixin) Alien.OnCreate(self) InitMixin(self, DissolveMixin) InitMixin(self, BabblerClingMixin) InitMixin(self, TunnelUserMixin) if Client then InitMixin(self, RailgunTargetMixin) self.timeDashChanged = 0 end self.wallWalking = false self.wallWalkingNormalGoal = Vector.yAxis self.leaping = false self.timeLastWallJump = 0 self.sneakOffset = 0 end function Skulk:OnInitialized() Alien.OnInitialized(self) -- Note: This needs to be initialized BEFORE calling SetModel() below -- as SetModel() will call GetHeadAngles() through SetPlayerPoseParameters() -- which will cause a script error if the Skulk is wall walking BEFORE -- the Skulk is initialized on the client. self.currentWallWalkingAngles = Angles(0.0, 0.0, 0.0) self:SetModel(self:GetVariantModel(), kSkulkAnimationGraph) if Client then self.currentCameraRoll = 0 self.goalCameraRoll = 0 self:AddHelpWidget("GUIEvolveHelp", 2) self:AddHelpWidget("GUISkulkParasiteHelp", 1) self:AddHelpWidget("GUISkulkLeapHelp", 2) self:AddHelpWidget("GUIMapHelp", 1) self:AddHelpWidget("GUITunnelEntranceHelp", 1) end InitMixin(self, IdleMixin) end function Skulk:GetCarapaceSpeedReduction() return kSkulkCarapaceSpeedReduction end function Skulk:GetCelerityArmorReduction() return kSkulkCelerityArmorReduction end function Skulk:OnDestroy() Alien.OnDestroy(self) if Client then if self.playingDashSound then Shared.StopSound(self, kDashSound) self.playingDashSound = false end end end function Skulk:GetBaseArmor() return Skulk.kArmor end function Skulk:GetCrouchSpeedScalar() return 0 end function Skulk:GetBaseHealth() return Skulk.kHealth end function Skulk:GetHealthPerBioMass() return kSkulkHealthPerBioMass end function Skulk:GetArmorFullyUpgradedAmount() return kSkulkArmorFullyUpgradedAmount end function Skulk:GetArmorCombinedAmount() return kSkulkCombinedArmor end function Skulk:GetMaxViewOffsetHeight() return Skulk.kViewOffsetHeight end function Skulk:GetCrouchShrinkAmount() return 0 end function Skulk:GetExtentsCrouchShrinkAmount() return 0 end function Skulk:OnLeap() local velocity = self:GetVelocity() * 0.5 local forwardVec = self:GetViewAngles():GetCoords().zAxis local newVelocity = velocity + GetNormalizedVectorXZ(forwardVec) * kLeapForce -- Add in vertical component. newVelocity.y = kLeapVerticalForce * forwardVec.y + kLeapVerticalForce * 0.5 + ConditionalValue(velocity.y < 0, velocity.y, 0) self:SetVelocity(newVelocity) self.leaping = true self.wallWalking = false self.jumping = true self:DisableGroundMove(0.2) self.timeOfLeap = Shared.GetTime() end function Skulk:GetRecentlyWallJumped() return self.timeLastWallJump + Skulk.kWallJumpInterval > Shared.GetTime() end function Skulk:GetCanWallJump() local wallWalkNormal = self:GetAverageWallWalkingNormal(kJumpWallRange, kJumpWallFeelerSize) if wallWalkNormal then return wallWalkNormal.y < 0.5 end return false end function Skulk:GetViewModelName() return self:GetVariantViewModel(self:GetVariant()) end function Skulk:GetCanJump() local canWallJump = self:GetCanWallJump() return self:GetIsOnGround() or canWallJump end function Skulk:GetIsWallWalking() return self.wallWalking end function Skulk:GetIsLeaping() return self.leaping end function Skulk:GetIsWallWalkingPossible() return not self:GetRecentlyJumped() and not self:GetCrouching() end local function PredictGoal(self, velocity) PROFILE("Skulk:PredictGoal") local goal = self.wallWalkingNormalGoal if velocity:GetLength() > 1 and not self:GetIsGround() then local movementDir = GetNormalizedVector(velocity) local trace = Shared.TraceCapsule(self:GetOrigin(), movementDir * 2.5, Skulk.kXExtents, 0, CollisionRep.Move, PhysicsMask.Movement, EntityFilterOne(self)) if trace.fraction < 1 and not trace.entity then goal = trace.normal end end return goal end function Skulk:GetPlayFootsteps() return self:GetVelocityLength() > .75 and self:GetIsOnGround() and self:GetIsAlive() and not self.movementModiferState end function Skulk:GetTriggerLandEffect() local xzSpeed = self:GetVelocity():GetLengthXZ() return Alien.GetTriggerLandEffect(self) and (not self.movementModiferState or xzSpeed > 7) end -- Update wall-walking from current origin function Skulk:PreUpdateMove(input, runningPrediction) PROFILE("Skulk:PreUpdateMove") --[[ local dashDesired = bit.band(input.commands, Move.MovementModifier) ~= 0 and self:GetVelocity():GetLength() > 4 if not self.dashing and dashDesired and self:GetEnergy() > 15 then self.dashing = true elseif self.dashing and not dashDesired then self.dashing = false end if self.dashing then self:DeductAbilityEnergy(input.time * 30) end if self:GetEnergy() == 0 then self.dashing = false end --]] if self:GetCrouching() then self.wallWalking = false end if self.wallWalking then -- Most of the time, it returns a fraction of 0, which means -- trace started outside the world (and no normal is returned) local goal = self:GetAverageWallWalkingNormal(kNormalWallWalkRange, kNormalWallWalkFeelerSize) if goal ~= nil then self.wallWalkingNormalGoal = goal self.wallWalking = true else self.wallWalking = false end end if not self:GetIsWallWalking() then -- When not wall walking, the goal is always directly up (running on ground). self.wallWalkingNormalGoal = Vector.yAxis end if self.leaping and Shared.GetTime() > self.timeOfLeap + kLeapTime then self.leaping = false end self.currentWallWalkingAngles = self:GetAnglesFromWallNormal(self.wallWalkingNormalGoal or Vector.yAxis) or self.currentWallWalkingAngles -- adjust the sneakOffset so sneaking skulks can look around corners without having to expose themselves too much local delta = input.time * math.min(1, self:GetVelocityLength()) if self.movementModiferState then if self.sneakOffset < Skulk.kMaxSneakOffset then self.sneakOffset = math.min(Skulk.kMaxSneakOffset, self.sneakOffset + delta) end else if self.sneakOffset > 0 then self.sneakOffset = math.max(0, self.sneakOffset - delta) end end end function Skulk:DisableRollPitchSmoothing() --do not change roll or pitch briefly after jumping to prevent twitchy wall movement return self.timeOfLastJump ~= nil and self.timeOfLastJump + .13 > Shared.GetTime() end function Skulk:GetRollSmoothRate() if self:DisableRollPitchSmoothing() then return 0 end return 5 end function Skulk:GetPitchSmoothRate() if self:DisableRollPitchSmoothing() then return 0 end return 3 end function Skulk:GetSlerpSmoothRate() return 5 end function Skulk:GetAngleSmoothRate() return 6 end function Skulk:GetCollisionSlowdownFraction() return 0.15 end function Skulk:GetDesiredAngles(deltaTime) return self.currentWallWalkingAngles end function Skulk:GetHeadAngles() if self:GetIsWallWalking() then -- When wallwalking, the angle of the body and the angle of the head is very different return self:GetViewAngles() else return self:GetViewAngles() end end function Skulk:GetAngleSmoothingMode() if self:GetIsWallWalking() then return "quatlerp" else return "euler" end end function Skulk:GetIsUsingBodyYaw() return not self:GetIsWallWalking() end function Skulk:OnJump( modifiedVelocity ) self.wallWalking = false local material = self:GetMaterialBelowPlayer() local currentSpeed = modifiedVelocity:GetLengthXZ() local maxWallJumpSpeed = self:GetMaxWallJumpSpeed() if currentSpeed > maxWallJumpSpeed * 0.95 then self:TriggerEffects("jump_best", {surface = material}) elseif currentSpeed > maxWallJumpSpeed * 0.75 then self:TriggerEffects("jump_good", {surface = material}) end self:TriggerEffects("jump", {surface = material}) end function Skulk:OnWorldCollision(normal, impactForce, newVelocity) PROFILE("Skulk:OnWorldCollision") self.wallWalking = self:GetIsWallWalkingPossible() and normal.y < 0.5 end function Skulk:GetMaxSpeed(possible) if possible then return Skulk.kMaxSpeed end local maxspeed = Skulk.kMaxSpeed if self.movementModiferState then maxspeed = maxspeed * Skulk.kSneakSpeedModifier end return maxspeed end function Skulk:ModifyCelerityBonus(celerityBonus) if self.movementModiferState then celerityBonus = celerityBonus * Skulk.kSneakSpeedModifier end return celerityBonus - self:GetCarapaceMovementScalar() end function Skulk:GetCelerityBonus() end function Skulk:GetMass() return kMass end function Skulk:OverrideUpdateOnGround(onGround) return onGround or self:GetIsWallWalking() end function Skulk:ModifyGravityForce(gravityTable) if self:GetIsWallWalking() and not self:GetCrouching() then gravityTable.gravity = 0 elseif self:GetIsOnGround() then gravityTable.gravity = 0 end end function Skulk:GetJumpHeight() return Skulk.kJumpHeight end function Skulk:GetPerformsVerticalMove() return self:GetIsWallWalking() end function Skulk:GetMaxWallJumpSpeed() local celerityMod = (GetHasCelerityUpgrade(self) and GetSpurLevel(self:GetTeamNumber()) or 0) * Skulk.kWallJumpMaxSpeedCelerityBonus/3.0 return (Skulk.kWallJumpMaxSpeed + celerityMod) - self:GetCarapaceMovementScalar() end function Skulk:ModifyJump(input, velocity, jumpVelocity) if self:GetCanWallJump() then local direction = input.move.z == -1 and -1 or 1 -- we add the bonus in the direction the move is going local viewCoords = self:GetViewAngles():GetCoords() self.bonusVec = viewCoords.zAxis * direction self.bonusVec.y = 0 self.bonusVec:Normalize() jumpVelocity.y = 3 + math.min(1, 1 + viewCoords.zAxis.y) * 2 local fraction = 1 - Clamp( velocity:GetLengthXZ() / self:GetMaxWallJumpSpeed(), 0, 1) local force = math.max(Skulk.kMinWallJumpForce, Skulk.kWallJumpForce * fraction) self.bonusVec:Scale(force) if not self:GetRecentlyWallJumped() then self.bonusVec.y = viewCoords.zAxis.y * Skulk.kVerticalWallJumpForce jumpVelocity:Add(self.bonusVec) end self.timeLastWallJump = Shared.GetTime() end end -- The Skulk movement should factor in the vertical velocity -- only when wall walking. function Skulk:GetMoveSpeedIs2D() return not self:GetIsWallWalking() end function Skulk:GetAcceleration() return 13 end function Skulk:GetAirControl() return 27 end function Skulk:GetGroundTransistionTime() return 0.1 end function Skulk:GetAirAcceleration() return 9 end function Skulk:GetAirFriction() return 0.055 - (GetHasCelerityUpgrade(self) and GetSpurLevel(self:GetTeamNumber()) or 0) * 0.009 end function Skulk:GetGroundFriction() return 11 end function Skulk:GetCanStep() return not self:GetIsWallWalking() end function Skulk:OnUpdateAnimationInput(modelMixin) PROFILE("Skulk:OnUpdateAnimationInput") Alien.OnUpdateAnimationInput(self, modelMixin) if self:GetIsLeaping() then modelMixin:SetAnimationInput("move", "leap") end modelMixin:SetAnimationInput("onwall", self:GetIsWallWalking() and not self:GetIsJumping()) end local function UpdateDashEffects(self) if Client then local dashing = self:GetVelocity():GetLengthXZ() > 8.7 if self.clientDashing ~= dashing then self.timeDashChanged = Shared.GetTime() self.clientDashing = dashing end local soundAllowed = not GetHasSilenceUpgrade(self) or self.silenceLevel < 3 if self:GetIsAlive() and dashing and not self.playingDashSound and (Shared.GetTime() - self.timeDashChanged) > 1 then local volume = GetHasSilenceUpgrade(self) and 1 - (self.silenceLevel / 3) or 1 local localPlayerScalar = Client.GetLocalPlayer() == self and 0.26 or 1 volume = volume * localPlayerScalar Shared.PlaySound(self, kDashSound, volume) self.playingDashSound = true elseif not self:GetIsAlive() or ( not dashing and self.playingDashSound ) then Shared.StopSound(self, kDashSound) self.playingDashSound = false end end end function Skulk:OnUpdate(deltaTime) Alien.OnUpdate(self, deltaTime) --UpdateDashEffects(self) end function Skulk:GetMovementSpecialTechId() return kTechId.Sneak end function Skulk:GetHasMovementSpecial() return self.movementModiferState end function Skulk:OnProcessMove(input) Alien.OnProcessMove(self, input) --UpdateDashEffects(self) end function Skulk:GetIsSmallTarget() return true end local kSkulkEngageOffset = Vector(0, 0.5, 0) function Skulk:GetEngagementPointOverride() return self:GetOrigin() + kSkulkEngageOffset end function Skulk:OnAdjustModelCoords(modelCoords) -- when sneaking, push the model back along the z-axis so the eyepoint of the model is actually close to the eyes. modelCoords.origin = modelCoords.origin - modelCoords.zAxis * self.sneakOffset return modelCoords end Shared.LinkClassToMap("Skulk", Skulk.kMapName, networkVars, true) if Server then Event.Hook("Console_skulk_sneak", function(client, dist) if Shared.GetTestsEnabled() then if dist then Skulk.kMaxSneakOffset = tonumber(dist) end Log("Skulk.kMaxSneakOffset = %s", Skulk.kMaxSneakOffset) end end) end -- Server
local url = request.path:match("/request/body(.*)") assert(url) assert(request.body) assert(type(request.body) == 'table') assert(type(request.body.tostring) == 'function') assert(type(request.body.toreader) == 'function') assert(type(request.body.tofile) == 'function') assert(not request.body.used) if url ~= '' then -- https://stackoverflow.com/q/978061/4418599 assert(request.method == 'post') end if url:find('^/string.*') then local b = math.tointeger(url:match('^/string(.*)')) local str if b == 1 then str = 'this is my string' elseif b == 2 then str = 'quavo, offset, and takeoff' else error('unknown flag, ' .. b) end assert(not request.body.used) assert(request.body.tostring() == str) assert(request.body.used == 'string') local function dofail() request.body.tostring() return true end local res, err = pcall(dofail) assert(not res) assert(err:find('.*already used.*')) return 17000 + b elseif url:find('^/tostring.*') then local b = math.tointeger(url:match('^/tostring(.*)')) local str if b == 1 then str = 'this is my string' elseif b == 2 then str = 'quavo, offset, and takeoff' else error('unknown flag, ' .. b) end assert(not request.body.used) assert(request.body.tostring() == str) assert(request.body.used == 'string') local function dofail() tostring(request.body) return true end local res, err = pcall(dofail) assert(not res) assert(err:find('.*already used.*')) return 17002 + b elseif url == '/toreader' then assert(not request.body.used) --- @type file local reader = request.body.toreader() assert(reader) assert(type(reader) == 'FILE*') assert(reader:read('l') == 'but it\'s tru tho') assert(reader:read('L') == 'ikno it\'s tru tho\n') assert(reader:read('a') == 'rep the north like I\'m Trudeau') assert(request.body.used == 'reader') local function dofail() request.body.toreader() return true end local res, err = pcall(dofail) assert(not res) assert(err:find('.*already used.*')) return 17005 elseif url == '/tofile' then assert(not request.body.used) local length = request.body.tofile(context.resPath 'rap.txt') assert(length == 654) assert(request.body.used == 'file') local function dofail() request.body.tofile('yeet') return true end local res, err = pcall(dofail) assert(not res) assert(err:find('.*already used.*')) return 17006 elseif url == '/tojson' then assert(not request.body.used) local movie = request.body.tojson() assert(request.body.used == 'json') local function dofail() request.body.tojson() return true end local res, err = pcall(dofail) assert(not res) assert(err:find('.*already used.*')) assert(movie.title == 'The Shawshank Redemption') assert(movie.director == 'Frank Darabont') assert(movie.screenplay == 'Stephen King') assert(movie.releasedate == 'September 22, 1994') local cast = movie.cast assert(#cast == 5) assert(cast[1] == 'Morgan Freeman') -- intentional skip assert(cast[3] == 'Clancy Brown') assert(cast[4] == 'Bob Gunton') assert(cast[5] == 'James Whitmore') return 17007 end return 17000
tool_damage = 0.5 local modpath = minetest.get_modpath("ks_tools") dofile(modpath.."/basic_materials.lua") dofile(modpath.."/wood_adze.lua") dofile(modpath.."/crafting.lua") dofile(modpath.."/stone_toolheads.lua") dofile(modpath.."/stone_tools.lua") dofile(modpath.."/cooking_tools.lua") minetest.register_tool("ks_tools:devtool", { description = "Developer Tool", inventory_image = "devtool.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=3, groupcaps={ chippable={times={[1]=0.0, [2]=0.0, [3]=0.0}, maxlevel=255}, diggable={times={[1]=0.0, [2]=0.0, [3]=0.0}, maxlevel=255}, choppable={times={[1]=0.0, [2]=0.0, [3]=0.0}, maxlevel=255}, sliceable={times={[1]=0.0, [2]=0.0, [3]=0.0}, maxlevel=255}, dig_immediate={times={[1]=0.0, [2]=0.0, [3]=0.0}, maxlevel=255}, grabbable={times={[1]=0.0}} }, damage_groups = {fleshy=100}, }, }) minetest.register_alias("devtool", "ks_tools:devtool") minetest.register_alias("coe", "chest_of_everything:chest") minetest.register_item(':', { type = 'none', wield_image = 'hand.png', wield_scale = {x = 1, y = 1, z = 4}, tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ sliceable={times={[1]=1, [2]=3}, maxlevel=1}, diggable={times={[1]=3}, maxlevel=1}, grabbable={times={[1]=0.0}} }, damage_groups = {fleshy=0} } })
local HttpMessage_t = {} local HttpMessage_mt = { __index = HttpMessage_t, } HttpMessage_t.AppendHeader = function(self, name, value) local header = self.Headers[name]; if not header or not value then return nil end self.Headers[name] = self.Headers[name]..value; end HttpMessage_t.AddHeader = function(self, name, value) if not name then return nil end name = name:lower(); local prevval = self.Headers[name] if prevval then value = prevval .. "," .. value end self.Headers [name] = value end HttpMessage_t.CopyHeaders = function(self, headers, exclusions) if not headers then return nil end exclusions = exclusions or {} for name, value in pairs(headers) do if not exclusions[name] then self:AddHeader(name, value) end end end HttpMessage_t.SetHeaders = function(self, headers) if not headers then self.Headers = {} return end for name, value in pairs(headers) do self:AddHeader(name, value); end end HttpMessage_t.GetHeader = function(self, name) -- BUGBUG -- This should be a cases insensitive compare instead -- of doing a 'tolower' return self.Headers[name:lower()]; end HttpMessage_t.ReadHeaders = function(self, stream) -- Read the headers -- and the expected blank line -- after them local headerline local err local prevname; while true do -- Read a line, terminated with crlf -- a 'nil' return would indicate either -- an error, or 'eof', so check the err headerline, err = stream:readLine(4096) if not headerline then return nil, err end if headerline == "" then return "" end -- parse the line to separate the name from the value local _,_, name, value = string.find (headerline, "^([^: ]+)%s*:%s*(.+)") --print("HEADER: ", name, value) if name then self:AddHeader(name, value) prevname = name elseif prevname then self:AppendHeader(prevname, value); end end return headerline, err end HttpMessage_t.WriteHeaders = function(self, stream) --print("HttpMessage_t.WriteHeaders() : ", self.Headers); if not self.Headers then return end local success, err for name,value in pairs(self.Headers) do --print("-- Header: ", name, value); --local hdr = string.format("%s: %s", value.name, value.value); local hdr = string.format("%s: %s", name, value); --print("-- Response Header: ", hdr); success, err = stream:writeLine(hdr); if err then return nil, err end end return success, err end return { HttpMessage_t = HttpMessage_t, }
function init() connect(g_game, { onGameStart = refresh, onGameEnd = hide }) ProtocolGame.registerExtendedOpcode(57, function(protocol, opcode, buffer) onTargetedHealthChange(protocol, opcode, buffer) end) targetedWindow = g_ui.loadUI('targeted', modules.game_interface.getMapPanel()) healthBar = targetedWindow:recursiveGetChildById('healthBar') portrait = targetedWindow:recursiveGetChildById('portrait') hide() end function terminate() disconnect(g_game, { onGameStart = refresh, onGameEnd = hide }) targetedWindow:destroy() end function show() targetedWindow:show() end function hide() targetedWindow:hide() end function onTargetedHealthChange(protocol, opcode, buffer) local targetHealth = tonumber(buffer:explode('|')[2]) local targetMaxHealth = tonumber(buffer:explode('|')[3]) local targetName = '' if tostring(buffer:explode('|')[1]) == 'none' then targetName = 'nothing' else targetName = tostring(buffer:explode('|')[1]) end if targetName == 'nothing' then hide() else show() end healthBar:setValue(targetHealth, 0, targetMaxHealth) healthBar:setText(targetHealth..'/'..targetMaxHealth) portrait:setImageSource('/images/game/pokemon/portraits/'..targetName) end
-- -- init.lua -- Initialize components -- require("components.topbar") require("components.exit_screen") require("components.lock_screen") require("components.window_switcher") require("components.floating_terminal")
local trim = require("lapis.util").trim_filter local Model = require("lapis.db.model").Model local Threads = Model:extend("threads") --- Create thread -- @tparam number board_id Board ID -- @tparam table flags List of thread flags -- @treturn boolean success -- @treturn string error function Threads:create_thread(board_id, flags) -- Trim white space trim(flags, { "sticky", "lock", "size_override", "save" }, false) local t = self:create { board_id = board_id, last_active = os.time(), sticky = flags.sticky, lock = flags.lock, size_override = flags.size_override, save = flags.save } if t then return t end return false, { "err_create_thread" } end --- Delete entire thread -- @tparam table session User session -- @tparam table thread Thread data -- @tparam table op Post data of op -- @treturn boolean success -- @treturn string error function Threads:delete_thread(session, thread, op) local success = false -- MODS = FAGS if type(session) == "table" and (session.admin or session.mod or session.janitor) then thread:delete() success = true -- Override password elseif type(session) == "string" and session == "override" then thread:delete() success = true -- Password has to match! elseif op and session.password and op.password == session.password then thread:delete() success = true end if success then return success else return false, { "err_delete_post", { op.post_id } } end end --- Get all threads from board -- @tparam number board_id Board ID -- @treturn table threads function Threads:get_threads(board_id) local sql = [[ where board_id = ? and archive = false order by sticky desc, last_active desc ]] return self:select(sql, board_id) end --- Get thread data -- @tparam number id Thread ID -- @treturn table thread function Threads:get_thread(id) return unpack(self:select("where id=?", id)) end --- Get page of threads -- @tparam number board_id Board ID -- @tparam number tpp Threads per page -- @tparam number page Page to pull from -- @treturn table threads -- @treturn number pages function Threads:get_page_threads(board_id, tpp, page) local sql = [[ where board_id = ? and archive = false order by sticky desc, last_active desc ]] local pages = self:paginated(sql, board_id,{ per_page = tpp }) return pages:get_page(page), pages:num_pages() end --- Get archived threads -- @tparam number board_id Board ID -- @treturn table threads function Threads:get_archived_threads(board_id) local sql = "where board_id=? and archive=true order by last_active desc" return self:select(sql, board_id) end --- Sticky a thread -- @tparam table thread Thread data -- @treturn boolean success -- @treturn string error function Threads:sticky_thread(thread) thread.sticky = true return thread:update("sticky") end --- Unsticky a thread -- @tparam table thread Thread data -- @treturn boolean success -- @treturn string error function Threads:unsticky_thread(thread) thread.sticky = false return thread:update("sticky") end --- Lock a thread -- @tparam table thread Thread data -- @treturn boolean success -- @treturn string error function Threads:lock_thread(thread) thread.lock = true return thread:update("lock") end --- Unlock a thread -- @tparam table thread Thread data -- @treturn boolean success -- @treturn string error function Threads:unlock_thread(thread) thread.lock = false return thread:update("lock") end --- Bump threads to archive -- @tparam number board_id Board ID -- @tparam number max_threads Maximum number of threads on this board -- @treturn boolean success -- @treturn string error function Threads:archive_threads(board_id, max_threads) local threads = self:get_threads(board_id) if #threads > max_threads then for i=max_threads+1, #threads do local _, err = self:archive_thread(threads[i]) if err then return false, err end end end end --- Archive a thread -- @tparam table thread Thread data -- @treturn boolean success -- @treturn string error function Threads:archive_thread(thread) thread.sticky = false thread.lock = true thread.archive = true thread.last_active = os.time() return thread:update("sticky", "lock", "archive", "last_active") end --- Find threads with no posts -- @treturn table threads function Threads:find_orphans() local sql = "where id not in (select distinct thread_id from posts)" return self:select(sql) end return Threads
----------------------------------- -- Area: FeiYin -- NPC: Strange Apparatus -- !pos -94 -15 220 204 ----------------------------------- function onTrade(player,npc,trade) player:startEvent(27, 0, 0, 1474, 0, 0, 0, 0, player:getZoneID()) end function onTrigger(player,npc) player:startEvent(25, 0, 0, 1474, 0, 0, 0, 0, player:getZoneID()) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
--Child Folders includeFile("custom_content/tangible/meatlump/event/serverobjects.lua") includeFile("custom_content/tangible/meatlump/hideout/serverobjects.lua") includeFile("custom_content/tangible/meatlump/reward/serverobjects.lua") -- Server Objects
--- jit-uuid -- Fast and dependency-free UUID library for LuaJIT/ngx_lua. -- @module jit-uuid -- @author Thibault Charbonnier -- @license MIT -- @release 0.0.7 local bit = require 'bit' local tohex = bit.tohex local band = bit.band local bor = bit.bor local _M = { _VERSION = '0.0.7' } ---------- -- seeding ---------- --- Seed the random number generator. -- Under the hood, this function calls `math.randomseed`. -- It makes sure to use the most appropriate seeding technique for -- the current environment, guaranteeing a unique seed. -- -- To guarantee unique UUIDs, you must have correctly seeded -- the Lua pseudo-random generator (with `math.randomseed`). -- You are free to seed it any way you want, but this function -- can do it for you if you'd like, with some added guarantees. -- -- @param[type=number] seed (Optional) A seed to use. If none given, will -- generate one trying to use the most appropriate technique. -- @treturn number `seed`: the seed given to `math.randomseed`. -- @usage -- local uuid = require 'resty.jit-uuid' -- uuid.seed() -- -- -- in ngx_lua, seed in the init_worker context: -- init_worker_by_lua { -- local uuid = require 'resty.jit-uuid' -- uuid.seed() -- } function _M.seed(seed) if not seed then if ngx then seed = ngx.time() + ngx.worker.pid() elseif package.loaded['socket'] and package.loaded['socket'].gettime then seed = package.loaded['socket'].gettime()*10000 else seed = os.time() end end math.randomseed(seed) return seed end ------------- -- validation ------------- do if ngx and string.find(ngx.config.nginx_configure(),'--with-pcre-jit',nil,true) then local type = type local re_find = ngx.re.find local regex = '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' --- Validate a string as a UUID. -- To be considered valid, a UUID must be given in its canonical -- form (hexadecimal digits including the hyphen characters). -- This function validates UUIDs disregarding their generation algorithm, -- and in a case-insensitive manner, but checks the variant field. -- -- Use JIT PCRE if available in OpenResty or fallbacks on Lua patterns. -- -- @param[type=string] str String to verify. -- @treturn boolean `valid`: true if valid UUID, false otherwise. -- @usage -- local uuid = require 'resty.jit-uuid' -- -- uuid.is_valid 'cbb297c0-a956-486d-ad1d-f9bZZZZZZZZZ' --> false -- uuid.is_valid 'cbb297c0-a956-486d-dd1d-f9b42df9465a' --> false (invalid variant) -- uuid.is_valid 'cbb297c0a956486dad1df9b42df9465a' --> false (no dashes) -- uuid.is_valid 'cbb297c0-a956-486d-ad1d-f9b42df9465a' --> true function _M.is_valid(str) -- it has proven itself efficient to first check the length with an -- evenly distributed set of valid and invalid uuid lengths. if type(str) ~= 'string' or #str ~= 36 then return false end return re_find(str, regex, 'ioj') ~= nil end else local match = string.match local d = '[0-9a-fA-F]' local p = '^' .. table.concat({ d:rep(8), d:rep(4), d:rep(4), '[89ab]' .. d:rep(3), d:rep(12) }, '%-') .. '$' function _M.is_valid(str) if type(str) ~= 'string' or #str ~= 36 then return false end return match(str, p) ~= nil end end end ---------------- -- v4 generation ---------------- do local fmt = string.format local random = math.random --- Generate a v4 UUID. -- v4 UUIDs are created from randomly generated numbers. -- -- @treturn string `uuid`: a v4 (randomly generated) UUID. -- @usage -- local uuid = require 'resty.jit-uuid' -- -- local u1 = uuid() ---> __call metamethod -- local u2 = uuid.generate_v4() function _M.generate_v4() return (fmt('%s%s%s%s-%s%s-%s%s-%s%s-%s%s%s%s%s%s', tohex(random(0, 255), 2), tohex(random(0, 255), 2), tohex(random(0, 255), 2), tohex(random(0, 255), 2), tohex(random(0, 255), 2), tohex(random(0, 255), 2), tohex(bor(band(random(0, 255), 0x0F), 0x40), 2), tohex(random(0, 255), 2), tohex(bor(band(random(0, 255), 0x3F), 0x80), 2), tohex(random(0, 255), 2), tohex(random(0, 255), 2), tohex(random(0, 255), 2), tohex(random(0, 255), 2), tohex(random(0, 255), 2), tohex(random(0, 255), 2), tohex(random(0, 255), 2))) end end ---------------- -- v3/v5 generation ---------------- do if ngx then local ffi = require 'ffi' local tonumber = tonumber local assert = assert local error = error local concat = table.concat local type = type local char = string.char local fmt = string.format local sub = string.sub local gmatch = ngx.re.gmatch local sha1_bin = ngx.sha1_bin local md5 = ngx.md5 local C = ffi.C local ffi_new = ffi.new local ffi_str = ffi.string local ffi_cast = ffi.cast local new_tab do local ok ok, new_tab = pcall(require, 'table.new') if not ok then new_tab = function(narr, nrec) return {} end end end ffi.cdef [[ typedef unsigned char u_char; typedef intptr_t ngx_int_t; u_char * ngx_hex_dump(u_char *dst, const u_char *src, size_t len); ngx_int_t ngx_hextoi(u_char *line, size_t n); ]] local str_type = ffi.typeof('uint8_t[?]') local u_char_type = ffi.typeof('u_char *') local function bin_tohex(s) local slen = #s local blen = slen * 2 local buf = ffi_new(str_type, blen) C.ngx_hex_dump(buf, s, slen) return ffi_str(buf, blen) end local function hex_to_i(s) local buf = ffi_cast(u_char_type, s) local n = tonumber(C.ngx_hextoi(buf, #s)) if n == -1 then error("could not convert hex to number") end return n end local buf = new_tab(16, 0) local function factory(namespace, hash_fn) if not _M.is_valid(namespace) then return nil, 'namespace must be a valid UUID' end local i = 0 local iter, err = gmatch(namespace, [[([\da-f][\da-f])]]) if not iter then return nil, 'could not create iter: ' .. err end while true do local m, err = iter() if err then return nil, err end if not m then break end i = i + 1 buf[i] = char(tonumber(m[0], 16)) end assert(i == 16, "invalid binary namespace buffer length") local ns = concat(buf) return function(name) if type(name) ~= 'string' then return nil, 'name must be a string' end local hash, ver, var = hash_fn(ns, name) return (fmt('%s-%s-%s%s-%s%s-%s', sub(hash, 1, 8), sub(hash, 9, 12), ver, sub(hash, 15, 16), var, sub(hash, 19, 20), sub(hash, 21, 32))) end end local function v3_hash(binary, name) local hash = md5(binary .. name) return hash, tohex(bor(band(hex_to_i(sub(hash, 13, 14)), 0x0F), 0x30), 2), tohex(bor(band(hex_to_i(sub(hash, 17, 18)), 0x3F), 0x80), 2) end local function v5_hash(binary, name) local hash = bin_tohex(sha1_bin(binary .. name)) return hash, tohex(bor(band(hex_to_i(sub(hash, 13, 14)), 0x0F), 0x50), 2), tohex(bor(band(hex_to_i(sub(hash, 17, 18)), 0x3F), 0x80), 2) end --- Instanciate a v3 UUID factory. -- @function factory_v3 -- Creates a closure generating namespaced v3 UUIDs. -- @param[type=string] namespace (must be a valid UUID according to `is_valid`) -- @treturn function `factory`: a v3 UUID generator. -- @treturn string `err`: a string describing an error -- @usage -- local uuid = require 'resty.jit-uuid' -- -- local fact = assert(uuid.factory_v3('e6ebd542-06ae-11e6-8e82-bba81706b27d')) -- -- local u1 = fact('hello') -- ---> 3db7a435-8c56-359d-a563-1b69e6802c78 -- -- local u2 = fact('foobar') -- ---> e8d3eeba-7723-3b72-bbc5-8f598afa6773 function _M.factory_v3(namespace) return factory(namespace, v3_hash) end --- Instanciate a v5 UUID factory. -- @function factory_v5 -- Creates a closure generating namespaced v5 UUIDs. -- @param[type=string] namespace (must be a valid UUID according to `is_valid`) -- @treturn function `factory`: a v5 UUID generator. -- @treturn string `err`: a string describing an error -- @usage -- local uuid = require 'resty.jit-uuid' -- -- local fact = assert(uuid.factory_v5('e6ebd542-06ae-11e6-8e82-bba81706b27d')) -- -- local u1 = fact('hello') -- ---> 4850816f-1658-5890-8bfd-1ed14251f1f0 -- -- local u2 = fact('foobar') -- ---> c9be99fc-326b-5066-bdba-dcd31a6d01ab function _M.factory_v5(namespace) return factory(namespace, v5_hash) end --- Generate a v3 UUID. -- v3 UUIDs are created from a namespace and a name (a UUID and a string). -- The same name and namespace result in the same UUID. The same name and -- different namespaces result in different UUIDs, and vice-versa. -- The resulting UUID is derived using MD5 hashing. -- -- This is a sugar function which instanciates a short-lived v3 UUID factory. -- It is an expensive operation, and intensive generation using the same -- namespaces should prefer allocating their own long-lived factory with -- `factory_v3`. -- -- @param[type=string] namespace (must be a valid UUID according to `is_valid`) -- @param[type=string] name -- @treturn string `uuid`: a v3 (namespaced) UUID. -- @treturn string `err`: a string describing an error -- @usage -- local uuid = require 'resty.jit-uuid' -- -- local u = uuid.generate_v3('e6ebd542-06ae-11e6-8e82-bba81706b27d', 'hello') -- ---> 3db7a435-8c56-359d-a563-1b69e6802c78 function _M.generate_v3(namespace, name) local fact, err = _M.factory_v3(namespace) if not fact then return nil, err end return fact(name) end --- Generate a v5 UUID. -- v5 UUIDs are created from a namespace and a name (a UUID and a string). -- The same name and namespace result in the same UUID. The same name and -- different namespaces result in different UUIDs, and vice-versa. -- The resulting UUID is derived using SHA-1 hashing. -- -- This is a sugar function which instanciates a short-lived v5 UUID factory. -- It is an expensive operation, and intensive generation using the same -- namespaces should prefer allocating their own long-lived factory with -- `factory_v5`. -- -- @param[type=string] namespace (must be a valid UUID according to `is_valid`) -- @param[type=string] name -- @treturn string `uuid`: a v5 (namespaced) UUID. -- @treturn string `err`: a string describing an error -- @usage -- local uuid = require 'resty.jit-uuid' -- -- local u = uuid.generate_v5('e6ebd542-06ae-11e6-8e82-bba81706b27d', 'hello') -- ---> 4850816f-1658-5890-8bfd-1ed14251f1f0 function _M.generate_v5(namespace, name) local fact, err = _M.factory_v5(namespace) if not fact then return nil, err end return fact(name) end else function _M.factory_v3() error('v3 UUID generation only supported in ngx_lua', 2) end function _M.generate_v3() error('v3 UUID generation only supported in ngx_lua', 2) end function _M.factory_v5() error('v5 UUID generation only supported in ngx_lua', 2) end function _M.generate_v5() error('v5 UUID generation only supported in ngx_lua', 2) end end end return setmetatable(_M, { __call = _M.generate_v4 })
local FuzzyFinderPrompt = require("mod.tools.api.FuzzyFinderPrompt") local Fs = require("api.Fs") local Elona122Map = require("mod.elona_sys.map_loader.Elona122Map") local UiMouseMenu = require("mod.mouse_ui.api.gui.UiMouseMenu") local UiMouseButton = require("mod.mouse_ui.api.gui.UiMouseButton") local IMapEditorPlugin = require("mod.map_editor.api.IMapEditorPlugin") local UiMouseMenuButton = require("mod.mouse_ui.api.gui.UiMouseMenuButton") local MapEditor122Plugin = class.class("MapEditor122Plugin", IMapEditorPlugin) function MapEditor122Plugin:init() end function MapEditor122Plugin:on_install(map_editor) local menu = UiMouseMenu:new { children = { UiMouseButton:new { text = "Load...", callback = function() self:act_load(map_editor) end }, } } local menu_button = UiMouseMenuButton:new { text = "1.22", id = "tools.122", menu = menu } map_editor.toolbar:find_menu("menu_plugin"):add_button(menu_button) end function MapEditor122Plugin:act_load(map_editor) local cands = Fs.iter_directory_items("mod/elona/map") :filter(function(i) return i:match("%.map$") end) :map(function(i) return i:gsub("%.map$", "") end) :to_list() local name, canceled = FuzzyFinderPrompt:new(cands):query() if canceled then return end local new_map = Elona122Map.generate(name) if new_map == nil then return nil end new_map.name = name local index = map_editor:add_map(new_map) map_editor:switch_to_map(index) end return MapEditor122Plugin
-- Load basic awesome libs. local awful = require("awful") local gears = require("gears") local menubar = require("menubar") local naughty = require("naughty") -- Widgets local wibox = require("wibox") local widget_utils = require("wibox.widget.base") local common = awful.widget.common -- Theming utilities. local layout = require("beautiful").get().bar_layout -- Helpers. local tags = require("tags") local clients = require("clients") local launcher = require("launcher") -- Event handlers. -- Track prompt size changes. local function track_prompt(scr) -- Correct size after each layout update. local w, h = scr.cmd_prompt.widget:get_preferred_size(scr) scr.cmd_box.width = w + 2 scr.cmd_box.height = h + 2 -- Make sure we do not head off-screen. awful.placement.no_offscreen(scr.cmd_box) end local global_screen = nil local function on_new_screen(scr) -- New screen. print(string.format("New screen: index=%d, width=%d, height=%d", scr.index, scr.geometry.width, scr.geometry.height)) if global_screen then debug_error("Only one screen supported per wm instance!") return end global_screen = scr local screen_width, screen_height = scr.geometry.width, scr.geometry.height -- Create a floating promptbox for each screen. local cmd_box = wibox({ontop=true, visible=false, opacity=0.82, type="dialog", x=0, y=0, width=4, height=4, screen=scr}) local cmd_prompt = awful.widget.prompt() cmd_prompt.widget:connect_signal("widget::layout_changed", function(w) track_prompt(scr) end) cmd_box:setup({ cmd_prompt, left = 1, right = 1, top = 1, bottom = 1, layout = wibox.container.margin }) scr.cmd_prompt = cmd_prompt scr.cmd_box = cmd_box -- Register all the tags. tags.init(scr) -- Generate the taglist widget. scr.taglist = tags.gen_widget(scr) launcher.register_taglist(scr.taglist) local taglist_height = select(2, scr.taglist:fit({}, screen_width, screen_height)) -- Generate the tasklist widget. scr.tasklist = clients.gen_widget(scr) -- Limit bar height. local wibar_height = taglist_height + layout.tasklist_height -- Create the wibar to hold the 'always visible' widgets. scr.bar = awful.wibar({ position = "top", height = wibar_height, screen = scr }) scr.bar:setup { layout = wibox.layout.grid, forced_num_cols = 1, forced_num_rows = 2, homogeneous = false, vertical_expand = false, horizontal_expand = true, -- Up { forced_width = scr.geometry.width, widget = wibox.container.background, { layout = wibox.layout.align.horizontal, { layout = wibox.layout.fixed.horizontal, { -- TODO: add system monitors id = "placeholder", markup = "", widget = wibox.widget.textbox } }, { scr.taglist, widget = wibox.container.place }, { awful.widget.keyboardlayout(), { -- Constraint systray, as some apps extend over to the tasklist area. layout = wibox.container.constraint, height = taglist_height, strategy = "max", wibox.widget.systray() }, wibox.widget.textclock(), -- Global/Current client title bar buttons. { id = "global_close", image = layout.close_image, resize_allowed = true, forced_height = taglist_height, buttons = awful.button({}, 1, nil, function(...) f = client.focus if f then f:kill() end end), widget = wibox.widget.imagebox }, layout = wibox.layout.fixed.horizontal } }, }, -- Down scr.tasklist } -- Extra events. local global_close = scr.bar:get_children_by_id("global_close")[1] global_close:connect_signal("mouse::enter", function(w) w.image = layout.close_hover_image end) global_close:connect_signal("mouse::leave", function(w) w.image = layout.close_image end) local last_x, last_y = -1, -1 -- Awesome does not distribute mouse::move events to widgets automatically, so we do this ourselves. scr.bar:connect_signal("mouse::move", function(wibox, x, y) -- By default we receive mouse events as fast as possible, so we rate limit them here. if last_x == x and last_y == y then return else last_x = x last_y = y end local widgets = wibox:find_widgets(x, y) for _, wt in ipairs(widgets) do local w = wt.widget if w and w._on_mouse_move then -- Stop on the first one which returns true. if w:_on_mouse_move(x - wt.x, y - wt.y) then return end end end end) -- Report final wibar layout. print(string.format("Wibar: w:%d, h:%d", scr.bar.width, scr.bar.height)) end -- Event registration. awful.screen.connect_for_each_screen(on_new_screen)
local M = require 'osprocess.core' -- ex.parsecommandline function M.parsecommandline(commandline) local lpeg = require 'lpeg' local field = lpeg.C('\"' * (lpeg.P(1) - '\"')^0 * '\"' + (1 - lpeg.P' ')^0) return lpeg.Ct(field * (lpeg.P(' ')^1 * field)^0 * -1):match(commandline) end -- ex.popen function M.popen(args, binary) local out_rd, out_wr = M.pipe(not binary) args.stdout = out_wr if args.stderr_to_stdout then args.stderr = out_wr end local proc, err = M.spawn(args) out_wr:close() if not proc then out_rd:close() return proc, err end return proc, out_rd end -- ex.lines function M.lines(args, binary) local proc, input = M.popen(args, not binary) return function() local line = input:read("*l") if line then return line end input:close() args.exitcode = proc:wait() end end -- ex.rawlines function M.rawlines(args, binary) local proc, input = M.popen(args, not binary) return function() local line = input:read(100) if line then return line end input:close() args.exitcode = proc:wait() end end -- ex.popen2() function M.popen2(args, binary) local in_rd, in_wr = M.pipe(not binary) local out_rd, out_wr = M.pipe(not binary) args.stdin = in_rd args.stdout = out_wr if args.stderr_to_stdout then args.stderr = out_wr end local proc, err = M.spawn(args) in_rd:close(); out_wr:close() if not proc then in_wr:close(); out_rd:close() return proc, err end return proc, out_rd, in_wr end -- ex.collectlines function M.collectlines(args) local lines = {} for line in M.lines(args) do lines[#lines + 1] = line end args.lines = lines return lines end return M
local Event = require 'utils.event' local RPG_Settings = require 'rpg.table' local RPG = require 'rpg.functions' Event.on_init( function() RPG.rpg_reset_all_players() end ) Event.on_nth_tick( 60, function() if settings.global.comfy_enable_health_and_mana_bars.value then RPG_Settings.enable_health_and_mana_bars(true) else RPG_Settings.enable_health_and_mana_bars(false) end if settings.global.comfy_enable_mana.value then RPG_Settings.enable_mana(true) else RPG_Settings.enable_mana(false) end if settings.global.comfy_enable_explosive_bullets.value then RPG_Settings.enable_explosive_bullets_globally(true) else RPG_Settings.enable_explosive_bullets_globally(false) end if settings.global.comfy_enable_flame_boots.value then RPG_Settings.enable_flame_boots(true) else RPG_Settings.enable_flame_boots(false) end if settings.global.comfy_enable_stone_path.value then RPG_Settings.enable_stone_path(true) else RPG_Settings.enable_stone_path(false) end if settings.global.comfy_enable_one_punch_globally.value then RPG_Settings.enable_one_punch_globally(true) else RPG_Settings.enable_one_punch_globally(false) end if settings.global.comfy_disable_spell_cooldown.value then RPG_Settings.disable_cooldowns_on_spells() else RPG_Settings.rebuild_spells() end if settings.global.comfy_personal_tax_rate.value then local value = settings.global.comfy_personal_tax_rate.value RPG_Settings.personal_tax_rate(value) else RPG_Settings.personal_tax_rate(0.3) end if settings.global.comfy_enable_debug.value then RPG_Settings.toggle_debug() else RPG_Settings.toggle_debug() end end ) require 'rpg.main'
Player = {} Player.Kick = function(player, responsiblePlayer, reason) kickPlayer(player, responsiblePlayer, reason) end
--[[ Representation of a console, which can display text, and act as the general canvas for a Terminal program ]] local ffi = require("ffi") local C = ffi.C local bit = require("bit") local band, bor = bit.band, bit.bor local bnot = bit.bnot local unicode = require("unicode") local exports = {} local TSM_SCREEN_INSERT_MODE = 0x01; local TSM_SCREEN_AUTO_WRAP = 0x02; local TSM_SCREEN_REL_ORIGIN = 0x04; local TSM_SCREEN_INVERSE = 0x08; local TSM_SCREEN_HIDE_CURSOR = 0x10; local TSM_SCREEN_FIXED_POS = 0x20; local TSM_SCREEN_ALTERNATE = 0x40; ffi.cdef[[ typedef uint32_t tsm_age_t; typedef uint32_t tsm_symbol_t; ]] local SymbolTable = { -- unsigned long ref; -- uint32_t next_id; -- struct shl_array *index; -- struct shl_htable symbols; } function SymbolTable.new(self) local obj = { ref = 1; next_id = TSM_UCS4_MAX + 2; symbols = {}; } setmetatable(obj, SymbolTable_mt) return obj end function SymbolTable.make(self, ucs4) if ucs4 > UNICODE_UCS4_MAX then return 0; end return ucs4 end function SymbolTable.append(self, sym, ucs4) end function SymbolTable.get(self, sym, size) end function SymbolTable.getWidth(self, sym) local ch, len = self:get(sym) if len == 0 then return 0; end return tsm_ucs4_get_width(ch) end -- const uint32_t * get(tsm_symbol_t *sym, size_t *size); -- tsm_symbol_t make(uint32_t ucs4); -- tsm_symbol_t append(tsm_symbol_t sym, uint32_t ucs4); ffi.cdef[[ enum attr_style { bold = 0x01, underline = 0x02, inverse = 0x04, protect = 0x08, blink = 0x10 }; ]] ffi.cdef[[ struct tsm_screen_attr { int8_t fccode; /* foreground color code or <0 for rgb */ int8_t bccode; /* background color code or <0 for rgb */ uint8_t fr; /* foreground red */ uint8_t fg; /* foreground green */ uint8_t fb; /* foreground blue */ uint8_t br; /* background red */ uint8_t bg; /* background green */ uint8_t bb; /* background blue */ unsigned int bold : 1; /* bold character */ unsigned int underline : 1; /* underlined character */ unsigned int inverse : 1; /* inverse colors */ unsigned int protect : 1; /* cannot be erased */ unsigned int blink : 1; /* blinking character */ }; ]] tsm_screen_attr = ffi.typeof("struct tsm_screen_attr") ffi.metatype(tsm_screen_attr, { __new = function(ct,...) local obj = ffi.new(ct, ...); obj.fccode = -1; obj.bccode = -1; obj.fr = 255; obj.fg = 255; obj.fb = 255; obj.br = 0; obj.bg = 0; obj.bb = 0; obj.bold = 0; obj.underline = 0; obj.inverse = 0; obj.protect = 0; obj.blink = 0; return obj; end; }) ffi.cdef[[ struct cell { tsm_symbol_t ch; // stored character size_t width; // character width struct tsm_screen_attr attr; // cell attributes tsm_age_t age; // age of the single cell }; ]] local cell = ffi.typeof("struct cell") ffi.metatype("struct cell", { __new = function(ct, con) local obj = ffi.new("struct cell"); if not con then obj.ch = 0; obj.width = 1; obj.age = 0; else obj:init(con) end return obj; end; __index = { init = function(self, con) self.ch = 0; self.width = 1; self.age = con.age_cnt; self.attr = con.def_attr; end; } }) local line = {} setmetatable(line, { __call = function(self, ...) return self:new(...) end; }) local line_mt = { __index = line; } function line.new(self, con, width) local obj = { next = nil; prev = nil; size = width; age = con.age_cnt; sb_id = 0; cells = ffi.new("struct cell[?]", width) } setmetatype(obj, line_mt) return obj end function line.initCells(self, con) for i=0, self.size-1 do self.cells[i]:init(con); end end function line.resize(self, con, width) local tmp; if width == 0 then return false, "invalid width"; end if self.size < width then tmp = ffi.new("cell[?]", width) if not tmp then return false, "not enough memory" end -- copy all current cells for i=0,self.size-1 do tmp[i] = self.cells[i]; end self.cells = tmp -- initialize new cells while self.size < width do self.cells[size]:init(con) self.size = self.size + 1; end end return true; end local SELECTION_TOP = -1; local selection_pos = {} local selection_pos_mt = { __index = selection_pos; } function selection_pos.new(self, line, x, y) local obj = { line = line; x = x or 0; y = y or 0; } setmetatable(obj, selection_pos_mt) return obj; end local ScrollbackBuffer ={} setmetatable(ScrollbackBuffer, { __call = function(self, ...) return self:new(...) end; }) local ScrollbackBuffer_mt = { __index = ScrollbackBuffer; } function ScrollbackBuffer.new(self, con, lmax) obj = obj or { con = con; sb_count = 0; -- number of lines in sb sb_first = nil; -- first line; was moved first sb_last = nil; -- last line; was moved last sb_max = 0; -- max-limit of lines in sb sb_pos = nil; -- current position in sb or NULL sb_last_id = 0; -- last id given to sb-line } setmetatable(obj, ScrollbackBuffer_mt); obj:setMax(lmax) return obj end function ScrollbackBuffer.getCount(self) return self.sb_count; end function ScrollbackBuffer.getFirst(self) return self.sb_first; end function ScrollbackBuffer.getLast(self) return self.sb_last; end function ScrollbackBuffer.getLastId(self) return self.sb_last_id; end function ScrollbackBuffer.getMax(self) return self.sb_max; end function ScrollbackBuffer.getPosition(self) return self.sb_pos; end function ScrollbackBuffer.setFirst(self, aline) self.sb_first = aline; end function ScrollbackBuffer.setLast(self, aline) self.sb_last = aline; end function ScrollbackBuffer.setMax(self, num) self.con:incrementAge(); self.con:alignAge(); local aline; while (self.sb_count > num) do aline = self.sb_first; self.sb_first = aline.next; if line.next then line.next.prev = nil; else self.sb_last = nil; end self.sb_count = self.sb_count - 1; if self.sb_pos == aline then self.sb_pos = self.sb_first; end if (self.con:getSelection():isActive()) then if (self.con:getSelection():getStart().line == aline) then self.con:getSelection():getStart().line = nil; self.con:getSelection():getStart().y = SELECTION_TOP; end if (self.con:getSelection():getEnd().line == aline) then self.con:getSelection():getEnd().line = nil; self.con:getSelection():getEnd().y = SELECTION_TOP; end end -- delete aline end self.sb_max = num; end function ScrollbackBuffer.setPosition(self, pos) self.sb_pos = pos; end function ScrollbackBuffer.decrementCount(self) self.sb_count = self.sb_count - 1; return self.sb_count; end function ScrollbackBuffer.incrementCount(self) self.sb_count = self.sb_count + 1; return self.sb_count; end function ScrollbackBuffer.incrementLastId(self) self.sb_last_id = self.sb_last_id + 1; return self.sb_last_id; end function ScrollbackBuffer.reset(self) self.con:incrementAge(); self.sb_pos = nil; return true; end function ScrollbackBuffer.clear(self) self.con:incrementAge(); -- by unhooking the lines, we'll just let the garbage -- collector clean them up over time. self.sb_first = nil; self.sb_last = nil; self.sb_count = 0; self.sb_pos = nil; return true; end function ScrollbackBuffer.down(self, num) if num < 1 then return false, "number must be greater than 0" end self.con:incrementAge(); while num > 0 do if self.sb_pos then self.sb_pos = self.sb_pos.next; else return ; end num = num - 1; end end function ScrollbackBuffer.up(self, num) if num < 1 then return false, "number must be greater than 0" end self.con:incrementAge(); while (num > 0) do if self.sb_pos then if not self.sb_pos.prev then return end self.sb_pos = self.sb_pos.prev; elseif not self.sb_last then return else self.sb_pos = self.sb_last; end num = num -1; end end function ScrollbackBuffer.pageUp(self, num) if num < 1 then return false; end self.con:incrementAge(); return self:up(num * self.con:getHeight()) end function ScrollbackBuffer.pageDown(self, num) if num < 1 then return false; end self.con:incrementAge(); return self:down(num * self.con:getHeight()) end local tsm_screen = {} setmetatable(tsm_screen, { __call = function(self, ...) return self:new(...) end; }) local tsm_screen_mt = { __index = tsm_screen; } local uint = ffi.typeof("unsigned int") local size_t = ffi.typeof("size_t") function tsm_screen.new(self, obj) --llog_submit_t llog; --void *llog_data; obj = obj or { ref = size_t(); opts = uint(); flags = uint(); sym_table = SymbolTable(); -- default attributes for new cells def_attr = tsm_scrren_attr(); -- aging age = 0ULL; -- whole screen age age_cnt = 0ULL; -- current age counter age_reset = 0; -- age overflow flag -- current buffer size_x = 0; -- width of screen size_y = 0; -- height of screen margin_top = 0; -- top-margin index margin_bottom = 0; -- bottom-margin index line_num = 0; -- real number of allocated lines lines = nil; -- active lines; copy of main/alt main_lines = nil; -- real main lines alt_lines = nil; -- real alternative lines -- scroll-back buffer sb_count = 0; -- number of lines in sb sb_first = nil; -- first line; was moved first sb_last = nil; -- last line; was moved last sb_max = 0; -- max-limit of lines in sb sb_pos = nil; -- current position in sb or NULL sb_last_id = 0; -- last id given to sb-line -- cursor: positions are always in-bound, but cursor_x might be -- bigger than size_x if new-line is pending cursor_x = 0; -- current cursor x-pos cursor_y = 0; -- current cursor y-pos -- tab ruler tab_ruler = nil; -- tab-flag for all cells of one row -- selection sel_active = false; sel_start = selection_pos(); sel_end = selection_pos(); } setmetatable(obj, tsm_screen_mt) return obj end --[[ /* Console A class encapsulating the concept and rendering of a generic console. This class has the simple writing functions necessary to put symbols on the screen in a structured manner. Construction of a more complex virtual terminal requires parsing input and interpreting the commands, turning them into console instructions. This console object assumes it is drawing into the general drawproc window, so it makes use of the global drawproc drawing calls, such as 'text()'. */ --]] local Console = {} local Console_mt = { __index = Console; } function Console.init(self, obj, width, height) if not obj then return nil; end obj.screen = tsm_screen(); self.screen.ref = 1; setmetatable(obj, Console_mt) --obj.Width = width; --obj.Height = height; obj:resize(width, height) end function Console.new(self, width, height) local obj = {} obj.defaultattr = tsm_screen_attr(); obj.scrollBuffer = ScrollbackBuffer(); obj.selection = ScreenSelection(); return self:init(ob, width, height) end --[[ // internal routines int _init(const size_t width, const size_t height); void eraseRegion(unsigned int x_from, unsigned int y_from, unsigned int x_to, unsigned int y_to, bool protect); void link_to_scrollback(struct line *aline); void scrollScreenUp(size_t num); void scrollScreenDown(size_t num); public: // Construction Console(const size_t width, const size_t height); ~Console(); void incrementAge(); --]] function Console.alignAge(self) self.screen.age = self.screen.age_cnt; return true; end function Console.getLines(sekf) return self.screen.lines; end function Console.getScrollbackBuffer(self) return self.scrollBuffer; end function Console.getSelection() return self.selection; end --[[ void setFlags(unsigned int flags); void resetFlags(unsigned int flags); unsigned int getFlags() const; -]] function Console.setOptions(self, opts) if not opts or opts == 0 then return false; end self.screen.opts = bor(self.screen.opts, opts) return true; end function Console.resetOptions(self, opts) if not opts or opts == 0 then return false; end self.screen.opts = band(self.screen.opts, bnot(opts)); return true; end function Console.getOptions(self) return self.screen.opts; end --[[ void setDefaultAttribute(const struct tsm_screen_attr & attr); void reset(); int resize(size_t x, size_t y); int createNewLine(struct line **out, size_t width); --]] -- Various screen attributes function Console.getCursorX(self) return self.screen.cursor_x; end function Console.getCursorY(self) return self.screen.cursor_y; end function Console.getWidth(self) return self.screen.size_x; end function Console.getHeight(self) return self.screen.size_y; end --[[ // writing text void writeSymbolAt(size_t x, size_t y, tsm_symbol_t ch, unsigned int len, const struct tsm_screen_attr *attr); void writeSymbol(tsm_symbol_t ch, const struct tsm_screen_attr *attr); --]] function Console.writeSymbolAt(self, x, y, ch, len, attr) if len == 0 then return; end if (x >= self.screen.size_x or y >= self.screen.size_y) then --llog_warning(con, "writing beyond buffer boundary"); return; end local line = self.screen.lines[y]; if (band(self.screen.flags, TSM_SCREEN_INSERT_MODE)~=0 and x < (self.screen.size_x - len)) then line.age = self.screen.age_cnt; -- move all the elements to the right by one -- BUGBUG -- do this in a simple loop memmove(&line->cells[x + len], &line->cells[x], sizeof(struct cell) * (screen.size_x - len - x)); end line.cells[x].age = self.screen.age_cnt; line.cells[x].ch = ch; line.cells[x].width = len; line.cells[x].attr = attr; --memcpy(&line.cells[x].attr, attr, sizeof(*attr)); local i = 1; while i < len and i + x < self.screen.size_x do line.cells[x + i].age = self.screen.age_cnt; line.cells[x + i].width = 0; i = i + 1; end end --[[ writeSymbol(ch, attr) write the given symbol at the current screen cursor location --]] function Console.writeSymbol(self, ch, attr) local len = screen.sym_table:getWidth(ch); if len == 0 then return; end self:incrementAge(); local last = 0; if (self.screen.cursor_y <= self.screen.margin_bottom or self.screen.cursor_y >= self.screen.size_y) then last = self.screen.margin_bottom; else last = self.screen.size_y - 1; end if (screen.cursor_x >= screen.size_x) then if band(screen.flags, TSM_SCREEN_AUTO_WRAP) ~= 0 then self:moveCursor(0, self.screen.cursor_y + 1); else self:moveCursor(self.screen.size_x - 1, self.screen.cursor_y); end end if (self.screen.cursor_y > last) then self:moveCursor(screen.cursor_x, last); self:scrollUp(1); end self:writeSymbolAt(self.screen.cursor_x, self.screen.cursor_y, ch, len, attr); self:moveCursor(self.screen.cursor_x + len, self.screen.cursor_y); end -- null terminated strings, or lua strings? -- need to decide. Maybe add a specific -- writeCString? -- BUGBUG function Console.writeCString(self, str) local idx = 0; while (str[idx] ~= 0) do self:writeSymbol(str[idx], self.defaultattr); idx = idx + 1; end end function Console.write(self, str) local n = #str str = ffi.cast("const char *", str) for counter=1,n do self:writeSymbol(str[counter-1], self.defaultattr); idx = idx + 1; end end function Console.writeLine(self, str) self:write(str); self:newline(); return true; end --[[ // Erasing parts of screen void eraseScreen(bool protect); void eraseCursor(); void eraseChars( size_t num); void eraseCursorToEnd( bool protect); void eraseHomeToCursor( bool protect); void eraseCurrentLine( bool protect); void eraseScreenToCursor( bool protect); void eraseCursorToScreen( bool protect); --]] --[[ // Deleting and inserting chars and lines void deleteChars(size_t num); void insertChars(size_t num); void deleteLines(size_t num); void insertLines(size_t num); --]] function Console.newline(self) self:incrementAge(); self:moveDown(1, true); self:moveLineHome(); end local function get_cursor_cell(con) local cur_x = con.cursor_x; if (cur_x >= con.size_x) then cur_x = con.size_x - 1; end local cur_y = con.cursor_y; if (cur_y >= con.size_y) then cur_y = con.size_y - 1; end return con.lines[cur_y].cells[cur_x]; end function Console.moveCursor(self, x, y) -- if cursor is hidden, just move it if band(self.screen.flags , TSM_SCREEN_HIDE_CURSOR) ~= 0 then self.screen.cursor_x = x; self.screen.cursor_y = y; return; end -- If cursor is visible, we have to mark the current and the new cell -- as changed by resetting their age. We skip it if the cursor-position -- didn't actually change. if (self.screen.cursor_x == x and self.screen.cursor_y == y) then return; end local c = get_cursor_cell(self.screen); c.age = self.screen.age_cnt; self.screen.cursor_x = x; self.screen.cursor_y = y; c = get_cursor_cell(self.screen); c.age = self.screen.age_cnt; end function Console.moveTo(self, x, y) self:incrementAge(); local last; if band(self.screen.flags, TSM_SCREEN_REL_ORIGIN) ~= 0 then last = self.screen.margin_bottom; else last = self.screen.size_y - 1; end x = self:to_abs_x(self.screen, x) if x >= self:getWidth() then x = self.screen.size_x - 1; end y = self:to_abs_y(self.screen, y); if y > last then y = last; end self:moveCursor(x,y) end --[[ void moveDown(size_t num, bool scroll); void moveUp(size_t num, bool scroll); void moveLeft(size_t num); void moveRight(size_t num); --]] function Console.moveLineEnd(self) self:incrementAge(); self:moveCursor(self.screen.size_x - 1, self.screen.cursor_y); end function Console.moveLineHome(self) self:incrementAge(); self:moveCursor(0, self.screen.cursor_y); end --[[ // Scrolling Control void setMaxScrollback(size_t num); void scrollBufferUp(size_t num); void scrollBufferDown(size_t num); void scrollUp(size_t num); void scrollDown(size_t num); // Margins int setMargins(size_t top, size_t bottom); // Tabbing void setTabstop(); void resetTabstop(); void resetAllTabstops(); void tabLeft(size_t num); void tabRight(size_t num); // Drawing current state of screen tsm_age_t drawScreen(void *data); }; --]] function Console.draw(self, ctx) end return Console
jsonInterface = require("jsonInterface") Database = require("database") local BaseCell = require("cell.base") local Cell = class("Cell", BaseCell) function Cell:__init(cellDescription) BaseCell.__init(self, cellDescription) -- Replace characters not allowed in filenames self.cellFile = cellDescription self.cellFile = string.gsub(self.cellFile, ":", ";") self.cellFile = self.cellFile .. ".json" if self.hasEntry == nil then local home = os.getenv("MOD_DIR").."/cell/" local file = io.open(home .. self.cellFile, "r") if file ~= nil then io.close() self.hasEntry = true else self.hasEntry = false end end end function Cell:CreateEntry() jsonInterface.save("cell/" .. self.cellFile, self.data) self.hasEntry = true end function Cell:Save() if self.hasEntry then jsonInterface.save("cell/" .. self.cellFile, self.data) end end function Cell:Load() self.data = jsonInterface.load("cell/" .. self.cellFile) -- JSON doesn't allow numerical keys, but we use them, so convert -- all string number keys into numerical keys tableHelper.fixNumericalKeys(self.data) end return Cell
--***************************************************************************** --* Author: RJP Computing <rjpcomputing@gmail.com> --* Date: 02/04/2007 --* Version: 1.00-beta --* Copyright (C) 2007 RJP Computing --* --* This program is free software; you can redistribute it and/or --* modify it under the terms of the GNU General Public License --* as published by the Free Software Foundation; either version 2 --* of the License, or (at your option) any later version. --* --* This program is distributed in the hope that it will be useful, --* but WITHOUT ANY WARRANTY; without even the implied warranty of --* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --* GNU General Public License for more details. --* --* You should have received a copy of the GNU General Public License --* along with this program; if not, write to the Free Software --* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --* --* NOTES: --* - use the '/' slash for all paths. --* - call ConfigureWxWidgets() after your project is setup, not before. --***************************************************************************** -- Package options addoption( "unicode", "Use the Unicode character set" ) addoption( "with-wx-shared", "Link against wxWidgets as a shared library" ) -- Configure a C/C++ package to use wxWidgets function ConfigureWxWidgets( package, altTargetName, wxVer, wxVerMinor ) -- Check to make sure that the package is valid. assert( type( package ) == "table" ) -- Set the default values. local targetName = altTargetName or "" local wx_ver = wxVer or "28" local wx_ver_minor = wxVerMinor or "0" -- Set object output directory. if ( options["unicode"] ) then package.config["Debug"].objdir = ".objsud" package.config["Release"].objdir = ".objsu" else package.config["Debug"].objdir = ".objsd" package.config["Release"].objdir = ".objs" end -- Set the default targetName if none is specified. -- NOTE: Not needed for wxWidgets, just for convienance. if ( string.len( targetName ) == 0 ) then targetName = package.name end if ( options["unicode"] ) then table.insert( package.buildflags, "unicode" ) end if ( target == "cb-gcc" or target == "gnu" ) then table.insert( package.config["Debug"].buildoptions, "-O0" ) end -- Set the defines. if ( options["with-wx-shared"] ) then table.insert( package.defines, "WXUSINGDLL" ) end if ( options["unicode"] ) then table.insert( package.defines, { "UNICODE", "_UNICODE" } ) end table.insert( package.defines, "__WX__" ) table.insert( package.config["Debug"].defines, { "DEBUG", "_DEBUG", "__WXDEBUG__" } ) table.insert( package.config["Release"].defines, { "NDEBUG" } ) if ( OS == "windows" ) then -- ******* WINDOWS SETUP *********** -- * Settings that are Windows specific. -- ********************************* -- Set wxWidgets include paths if ( target == "cb-gcc" ) then table.insert( package.includepaths, { "$(#WX.include)" } ) else table.insert( package.includepaths, { "$(WXWIN)/include" } ) end -- Set the correct 'setup.h' include path. if ( options["with-wx-shared"] ) then if ( options["unicode"] ) then if ( target == "cb-gcc" ) then table.insert( package.config["Debug"].includepaths, "$(#WX.lib)/gcc_dll/mswud" ) table.insert( package.config["Release"].includepaths, "$(#WX.lib)/gcc_dll/mswu" ) elseif ( target == "gnu" ) then table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/gcc_dll/mswud" ) table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/gcc_dll/mswu" ) else table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/vc_dll/mswud" ) table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/vc_dll/mswu" ) end else if ( target == "cb-gcc" ) then table.insert( package.config["Debug"].includepaths, "$(#WX.lib)/gcc_dll/mswd" ) table.insert( package.config["Release"].includepaths, "$(#WX.lib)/gcc_dll/msw" ) elseif ( target == "gnu" ) then table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/gcc_dll/mswd" ) table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/gcc_dll/msw" ) else table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/vc_dll/mswd" ) table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/vc_dll/msw" ) end end else if ( options["unicode"] ) then if ( target == "cb-gcc" ) then table.insert( package.config["Debug"].includepaths, "$(#WX.lib)/gcc_lib/mswud" ) table.insert( package.config["Release"].includepaths, "$(#WX.lib)/gcc_lib/mswu" ) elseif ( target == "gnu" ) then table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/gcc_lib/mswud" ) table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/gcc_lib/mswu" ) else table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/vc_lib/mswud" ) table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/vc_lib/mswu" ) end else if ( target == "cb-gcc" ) then table.insert( package.config["Debug"].includepaths, "$(#WX.lib)/gcc_lib/mswd" ) table.insert( package.config["Release"].includepaths, "$(#WX.lib)/gcc_lib/msw" ) elseif ( target == "gnu" ) then table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/gcc_lib/mswd" ) table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/gcc_lib/msw" ) else table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/vc_lib/mswd" ) table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/vc_lib/msw" ) end end end -- Set the linker options. if ( options["with-wx-shared"] ) then if ( target == "cb-gcc" ) then table.insert( package.libpaths, "$(#WX.lib)/gcc_dll" ) elseif ( target == "gnu" ) then table.insert( package.libpaths, "$(WXWIN)/lib/gcc_dll" ) else table.insert( package.libpaths, "$(WXWIN)/lib/vc_dll" ) end else if ( target == "cb-gcc" ) then table.insert( package.libpaths, "$(#WX.lib)/gcc_lib" ) elseif ( target == "gnu" ) then table.insert( package.libpaths, "$(WXWIN)/lib/gcc_lib" ) else table.insert( package.libpaths, "$(WXWIN)/lib/vc_lib" ) end end -- Set wxWidgets libraries to link. if ( options["unicode"] ) then table.insert( package.config["Release"].links, "wxmsw"..wx_ver.."u" ) table.insert( package.config["Debug"].links, "wxmsw"..wx_ver.."ud" ) else table.insert( package.config["Release"].links, "wxmsw"..wx_ver ) table.insert( package.config["Debug"].links, "wxmsw"..wx_ver.."d" ) end -- Set the Windows defines. table.insert( package.defines, { "__WXMSW__", "WIN32", "_WINDOWS" } ) -- Set the targets. if ( package.kind == "winexe" or package.kind == "exe" ) then package.config["Release"].target = targetName package.config["Debug"].target = targetName.."d" else if ( target == "cb-gcc" or target == "gnu" ) then if ( options["unicode"] ) then package.config["Debug"].target = "wxmsw"..wx_ver..wx_ver_minor.."umd_"..targetName.."_gcc" package.config["Release"].target = "wxmsw"..wx_ver..wx_ver_minor.."um_"..targetName.."_gcc" else package.config["Debug"].target = "wxmsw"..wx_ver..wx_ver_minor.."md_"..targetName.."_gcc" package.config["Release"].target = "wxmsw"..wx_ver..wx_ver_minor.."m_"..targetName.."_gcc" end else if ( options["unicode"] ) then package.config["Debug"].target = "wxmsw"..wx_ver..wx_ver_minor.."umd_"..targetName.."_vc" package.config["Release"].target = "wxmsw"..wx_ver..wx_ver_minor.."um_"..targetName.."_vc" else package.config["Debug"].target = "wxmsw"..wx_ver..wx_ver_minor.."md_"..targetName.."_vc" package.config["Release"].target = "wxmsw"..wx_ver..wx_ver_minor.."m_"..targetName.."_vc" end end end else -- ******* LINUX SETUP ************* -- * Settings that are Linux specific. -- ********************************* -- Ignore resource files in Linux. table.insert( package.excludes, matchrecursive( "*.rc" ) ) -- Set wxWidgets build options. table.insert( package.config["Debug"].buildoptions, "`wx-config "..debug_option.." --cflags`" ) table.insert( package.config["Release"].buildoptions, "`wx-config --debug=no --cflags`" ) -- Set the wxWidgets link options. table.insert( package.config["Debug"].linkoptions, "`wx-config "..debug_option.." --libs`" ) table.insert( package.config["Release"].linkoptions, "`wx-config --libs`" ) -- Set the Linux defines. table.insert( package.defines, "__WXGTK__" ) -- Set the targets. if ( package.kind == "winexe" or package.kind == "exe" ) then package.config["Release"].target = targetName package.config["Debug"].target = targetName.."d" else package.config["Debug"].target = "`wx-config "..debug_option.." --basename`_"..targetName.."-`wx-config --release`" package.config["Release"].target = "`wx-config --basename`_"..targetName.."-`wx-config --release`" end end end
stdout = {} function stdout.r(msg) io.write("\r" .. msg) io.flush() end
-- Luagit2's Graph Module Tests local fixer = require("Fixtures.fix_repo") describe(" Graph Methods Tests ", function() local luagit2 = require("luagit2") local repo_path = "Fixtures/WORKON_REPO" setup(function() luagit2.init() end) before_each(function() fixer.set_repo("new_test_repo") repo = luagit2.repository_open(repo_path) end) after_each(function() luagit2.repository_free(repo) fixer.set_back() end) teardown(function() luagit2.shutdown() end) it("Tests git graph ahead-behind",function() -- Lets Pick two commmits differing by one commit in between. local commit_id_str_ahead = "108ddee361877aa5c044d89d8dd232b8fd0f8992" local commit_id_str_behind = "5b5b025afb0b4c913b4c338a42934a3863bf3644" local commit_id_ahead = luagit2.oid_fromstr(commit_id_str_ahead) local commit_id_behind = luagit2.oid_fromstr(commit_id_str_behind) local ahead_by , behind_by = luagit2.graph_ahead_behind(repo,commit_id_ahead,commit_id_behind) -- The newer commit is ahead of old commit by 2. -- thus these values should match. assert.are.same(2,ahead_by) assert.are.same(0,behind_by) end) it("Tests git graph is_decendent ",function() -- Lets Pick two commmits differing by one commit in between. -- therefore one commit is true ancestor of other. local commit_id_str = "108ddee361877aa5c044d89d8dd232b8fd0f8992" local commit_id_str_ancestor = "5b5b025afb0b4c913b4c338a42934a3863bf3644" local commit_id = luagit2.oid_fromstr(commit_id_str) local commit_id_ancestor = luagit2.oid_fromstr(commit_id_str_ancestor) local is_decendent = luagit2.graph_descendant_of(repo,commit_id,commit_id_ancestor) -- Check assert.is_true(is_decendent) end) end)
pfUI:RegisterModule("afkcam", 20400, function () local MARKED_AFK_CAPTURE = SanitizePattern(MARKED_AFK_MESSAGE) local social_chats = { "CHAT_MSG_SAY", "CHAT_MSG_WHISPER", "CHAT_MSG_PARTY", "CHAT_MSG_RAID", "CHAT_MSG_RAID_LEADER", "CHAT_MSG_RAID_WARNING", "CHAT_MSG_GUILD", "CHAT_MSG_OFFICER" } local afkcam = CreateFrame("Frame", "pfAFKCam", WorldFrame) local overlay = CreateFrame("Button", "pfAFKCamOverlay", afkcam) overlay.top = overlay:CreateTexture("pfAFKGradientTop", "BACKGROUND") overlay.top:SetPoint("TOPLEFT", overlay, "TOPLEFT") overlay.top:SetPoint("TOPRIGHT", overlay, "TOPRIGHT") overlay.top:SetHeight(100) overlay.top:SetTexture(1,1,1,1) overlay.top:SetGradientAlpha("VERTICAL", 0,0,0,0, 0,0,0,1) overlay.bottom = overlay:CreateTexture("pfAFKGradientTop", "BACKGROUND") overlay.bottom:SetPoint("BOTTOMLEFT", overlay, "BOTTOMLEFT") overlay.bottom:SetPoint("BOTTOMRIGHT", overlay, "BOTTOMRIGHT") overlay.bottom:SetHeight(100) overlay.bottom:SetTexture(1,1,1,1) overlay.bottom:SetGradientAlpha("VERTICAL", 0,0,0,1, 0,0,0,0) overlay:SetFrameStrata("DIALOG") overlay:SetAllPoints(WorldFrame) overlay:SetScript("OnMouseUp",function() SendChatMessage("","AFK") this._parent:stop() end) overlay:SetScript("OnShow", function() this:EnableKeyboard(true) end) overlay:SetScript("OnHide", function() this:EnableKeyboard(false) end) overlay:SetScript("OnKeyUp",function() SendChatMessage("","AFK") this._parent:stop() end) overlay:Hide() local chat = CreateFrame("ScrollingMessageFrame", "pfAFKCamChat", overlay) chat:EnableMouse(false) chat:EnableMouseWheel(true) chat:SetHeight(150) chat:SetWidth(500) chat:SetPoint("BOTTOMLEFT",overlay,"BOTTOMLEFT", 10, 10) chat:SetTimeVisible(1800.0) chat:SetMaxLines(500) chat:SetFading(false) chat:SetJustifyH("LEFT") chat:SetFont(pfUI.font_default, C.global.font_size + 1, "OUTLINE") chat:SetScript("OnEvent", function() if not this:IsVisible() then return end local info = _G.ChatTypeInfo[string.gsub(event,"CHAT_MSG_","")] if not info then return end local class = GetUnitData(arg2 or "") local author, msg if class and class ~= UNKNOWN then local class_color = rgbhex(RAID_CLASS_COLORS[class]) author = string.format("%s%s|r",class_color,arg2) else author = arg2 end msg = string.format("%s|cffffffff:|r %s",author,arg1) this:AddMessage(msg, info.r, info.g, info.b, 1.0) end) for _,ctype in ipairs(social_chats) do chat:RegisterEvent(ctype) end chat:SetScript("OnMouseWheel",function() if arg1 > 0 then this:ScrollUp() else this:ScrollDown() end end) overlay.chat = chat overlay._parent = afkcam afkcam.overlay = overlay local clock = CreateFrame("Frame", "pfAFKClock", overlay) clock:SetAllPoints(overlay) clock.time = clock:CreateFontString("Status", "OVERLAY") clock.time:SetFont("Interface\\AddOns\\pfUI\\fonts\\Hooge.ttf", 32, "THICKOUTLINE") clock.time:SetJustifyH("CENTER") clock.time:SetPoint("TOP", 0, -10) clock:SetScript("OnUpdate", function() local h, m = GetGameTime() local noon = "AM" local time = "" if C.global.twentyfour == "0" then if C.global.servertime == "1" then if h > 12 then h = h - 12 noon = "PM" end time = string.format("%.2d|cff33ffcc:|r%.2d %s", h, m, noon) else time = date("%I|cff33ffcc:|r%M %p") end clock.time:SetText(time) else if C.global.servertime == "1" then time = string.format("%.2d|cff33ffcc:|r%.2d", h, m) else time = date("%H|cff33ffcc:|r%M") end end clock.time:SetText(time) end) function afkcam:start() afkcam._speed = GetCVar("cameraYawMoveSpeed") afkcam._ownname = GetCVar("UnitNameOwn") afkcam._ui_visible = UIParent:IsVisible() SaveView(4) if afkcam._ui_visible then CloseAllWindows() UIParent:Hide() end if afkcam._ownname == "0" then SetCVar("UnitNameOwn", "1") end SetCVar("cameraYawMoveSpeed","8") MoveViewRightStart() afkcam.overlay:Show() afkcam.overlay.chat:Clear() afkcam._spinning = true end function afkcam:stop() MoveViewRightStop() SetCVar("cameraYawMoveSpeed",afkcam._speed) SetCVar("UnitNameOwn", afkcam._ownname) SetView(4) SetCVar("cameraCustomViewSmoothing", "1") if not UIParent:IsVisible() and afkcam._ui_visible then UIParent:Show() end if pfUI.uf.player then pfUI.uf:RefreshUnit(pfUI.uf.player, "all") end afkcam.overlay:Hide() afkcam._spinning = false end local delay = CreateFrame("Frame") delay:Hide() delay:RegisterEvent("AUCTION_ITEM_LIST_UPDATE") delay:SetScript("OnEvent", function() this.delay = GetTime() + 5 end) delay:SetScript("OnUpdate", function() if ( this.tick or 0) > GetTime() then return else this.tick = GetTime() + 1 end local name = UnitName("player") local cast = UnitCastingInfo(name) if not cast then cast = UnitChannelInfo(name) end if not this.delay then this.delay = 0 end if cast then this.delay = GetTime() + 5 end if this.delay < GetTime() then afkcam:start() this:Hide() end end) afkcam:SetScript("OnEvent", function() if event == "CHAT_MSG_SYSTEM" then if (arg1 == _G.MARKED_AFK) or strfind(arg1, MARKED_AFK_CAPTURE) then delay:Show() elseif (arg1 == _G.CLEARED_AFK) then delay:Hide() this:stop() end else if this._spinning then delay:Hide() this:stop() end end end) afkcam:RegisterEvent("CHAT_MSG_SYSTEM") afkcam:RegisterEvent("PLAYER_REGEN_DISABLED") afkcam:RegisterEvent("PLAYER_LEAVING_WORLD") -- reseting cvars on PLAYER_LOGOUT crashes the client ¯\_(ツ)_/¯ end)
-- -- SmartMet NWC parameters -- -- Create cloud layer data for SNWC from 'own' total cloudiness and -- cloud layers from Smartmet data. -- local MISS = missing local editor_prod = producer(181, "SMARTMET") editor_prod:SetCentre(86) editor_prod:SetProcess(181) local editor_origintime = raw_time(radon:GetLatestTime(editor_prod, "", 0)) local editor_time = forecast_time(editor_origintime, current_time:GetValidDateTime()) local H0 = level(HPLevelType.kHeight, 0) local CC = luatool:FetchWithType(current_time, H0, param("N-0TO1"), current_forecast_type) local CH = luatool:FetchWithType(current_time, H0, param("NH-0TO1"), current_forecast_type) local CM = luatool:FetchWithType(current_time, H0, param("NM-0TO1"), current_forecast_type) local CL = luatool:FetchWithType(current_time, H0, param("NL-0TO1"), current_forecast_type) if not CC or not CH or not CM or not CL then return end local _CH = {} local _CM = {} local _CL = {} for i=1, #CC do local cc = CC[i] local ch = CH[i] local cm = CM[i] local cl = CL[i] _CH[i] = ch _CM[i] = cm _CL[i] = cl -- From 'DBChecker' -- Lisätään ala-, keski- tai yläpilviä niin että jokin kerroksista on sama kuin kokonaispilvisyys. -- Valinta tehdään sen mukaan mitä on jo alunperin enemmän. -- Tehdään ensin alapilville if (cl < cc and cl >= cm and cl >= ch) then _CL[i] = cc end -- ja keskipilville if (cm < cc and cl < cm and ch < cm) then _CM[i] = cc end -- lopuksi lisätään yläpilviä if (cm < cc and cl < ch and cm < ch) then _CH[i] = cc end -- Vähennetään ala- ja keskipilviä, jos ne ovat suurempia kuin kokonaispilvisyys. _CL[i] = math.min(cl, cc) _CM[i] = math.min(cm, cc) end result:SetParam(param("NH-0TO1")) result:SetValues(_CH) luatool:WriteToFile(result) result:SetParam(param("NM-0TO1")) result:SetValues(_CM) luatool:WriteToFile(result) result:SetParam(param("NL-0TO1")) result:SetValues(_CL) luatool:WriteToFile(result)
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ========== PlaceObj('Scenario', { 'name', "Mystery 6", 'file_name', "Mystery_6", }, { PlaceObj('ScenarioSequence', { 'name', "Start", 'autostart', true, }, { PlaceObj('SA_Exec', { 'expression', '_missionSponsor = GetMissionSponsor().display_name or ""', }), PlaceObj('SA_WaitExpression', { 'expression', "UICity.labels.Colonist and #UICity.labels.Colonist >= 100", 'duration', 1000, }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 3750000, 'rand_duration', 3750000, }), PlaceObj('SA_Exec', { 'expression', 'Msg("MysteryBegin")', }), PlaceObj('SA_WaitMessage', { 'title', T(6249, --[[Scenario Mystery 6 title]] "Marsgate: It Came From Earth"), 'voiced_text', T(7256, --[[voice:narrator]] "We’ve observed an unknown object on a rapid trajectory from Earth towards Mars."), 'text', T(6250, --[[Scenario Mystery 6 text]] "We have contacted our partners back on Earth, but have so far received no insight on this mysterious object. Observations at this level suggest an artificial origin but flight schedules indicate no inbound science mission."), 'image', "UI/Messages/marsgate_mystery_01.tga", 'choice1', T(6251, --[[Scenario Mystery 6 choice1]] "Pester those guys until you shake off some answers – we need to know what the heck they’ve thrown our way."), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7490, --[[Scenario Mystery 6 text]] "An unknown object of artificial origin has been detected to be inbound towards Mars from Earth."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 750000, 'rand_duration', 1500000, }), PlaceObj('SA_WaitMessage', { 'title', T(6252, --[[Scenario Mystery 6 title]] "Marsgate: EsoCorp"), 'voiced_text', T(7257, --[[voice:narrator]] "Mission Control’s received a direct communique from EsoCorp, one of Earth’s largest tech conglomerates. It reads:"), 'text', T(6253, --[[Scenario Mystery 6 text]] "“Please be advised that Object 6Ez-3 will be operating within a respectful distance of your mission. You are not to approach Object 6Ez-3 under any circumstance, under threat of legal and other punitive measures.”\n\nNothing further was added and no effort to even mimic adherence to standard protocol guidelines was made. Our Earth partners are giving their best to question EsoCorp and get to the bottom of this."), 'image', "UI/Messages/marsgate_mystery_01.tga", 'choice1', T(6254, --[[Scenario Mystery 6 choice1]] "Who do these guys think they are!?"), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7491, --[[Scenario Mystery 6 text]] "One of Earth’s largest tech conglomerates, EsoCorp, has confirmed ownership of the mysterious craft and has issued a warning to stay away."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 750000, 'rand_duration', 1500000, }), PlaceObj('SA_Exec', { 'expression', 'PlaceObject("AttackRover", {city = UICity})', }), PlaceObj('SA_WaitMessage', { 'title', T(6255, --[[Scenario Mystery 6 title]] "Marsgate: Motives Unknown"), 'voiced_text', T(7258, --[[voice:narrator]] "Object 6Ez-3 has made impact on the surface, not too far from base. Our readings suggest it’s intact and operational."), 'text', T(6256, --[[Scenario Mystery 6 text]] "So far we can deduce it is only patrolling the area, as we can’t detect sophisticated science instruments from this observation range.\n\nThe landing, however, was seen by some of our Colonists and questions are being raised – questions we currently can’t answer. Our Earth partners have so far fallen short from picking up on any new information and are currently preparing to take the issue to the UN."), 'image', "UI/Messages/marsgate_mystery_01.tga", 'choice1', T(6257, --[[Scenario Mystery 6 choice1]] "Soon we may have to take things into our own hands."), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7492, --[[Scenario Mystery 6 text]] "The mysterious vehicle has made touchdown on Mars and has begun operating in secrecy."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Rover Malfunctions", }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Malfunctioned Rovers: Counter", }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 3750000, 'rand_duration', 1500000, }), PlaceObj('SA_Repeat', { 'sa_id', 1, 'expression', "4", 'end_block', 2, }), PlaceObj('SA_Exec', { 'expression', 'PlaceObject("AttackRover", {city = UICity})', }), PlaceObj('SA_WaitMarsTime', { 'duration', 150000, 'rand_duration', 150000, }), PlaceObj('SA_Block', { 'sa_id', 2, 'parent', 1, }), PlaceObj('SA_WaitMessage', { 'title', T(6258, --[[Scenario Mystery 6 title]] "Marsgate: A Silent Invasion"), 'voiced_text', T(7259, --[[voice:narrator]] "We detect and monitor four more objects as they parachute down and make landfall, every one of them bearing a resemblance to Object 6Ez-3."), 'text', T(6259, --[[Scenario Mystery 6 text]] "EsoCorp is totally silent about this second batch of what we believe to be some sort of surveying rovers.\n\nMore Colonists have witnessed the landings and are openly concerned about what they perceive to be an invasion."), 'image', "UI/Messages/marsgate_mystery_02.tga", 'choice1', T(6260, --[[Scenario Mystery 6 choice1]] "Calm the general public down. We need answers!"), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7493, --[[Scenario Mystery 6 text]] "More of the mysterious vehicles have landed on Mars and are a becoming a cause for concern among our Colonists."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 750000, }), PlaceObj('SA_WaitExpression', { 'expression', "_malfunctions >= 1", }), PlaceObj('SA_WaitMessage', { 'title', T(6261, --[[Scenario Mystery 6 title]] "Marsgate: Take It or Leave It"), 'voiced_text', T(7260, --[[voice:narrator]] "EsoCorp’s stopped giving us the silent treatment, but it’s clear from their message they’re not going to answer our questions."), 'text', T(6262, --[[Scenario Mystery 6 text]] "They propose a deal - we fix one of their malfunctioning rovers and they provide a generous (as they put it) funding injection. Their legal team has also warned that any mission should be strictly for repairs and further inspection of the vehicle will be taken as an illegal act.\n\nIn other words, if we wish, we can send drones to fix their rover but nothing that can evaluate its purpose – like a rover – and we will be paid for the effort.\n\n<effect>Malfunctioning EsoCorp rovers can now be repaired by Drones."), 'image', "UI/Messages/marsgate_mystery_01.tga", 'choice1', T(6263, --[[Scenario Mystery 6 choice1]] "Not suspicious at all."), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7494, --[[Scenario Mystery 6 text]] "EsoCorp has broken the silence and has offered us a handsome reward for repairing one of its vehicles."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_Exec', { 'expression', "UICity.mystery.enable_rover_repair = true", }), PlaceObj('SA_Exec', { 'expression', "_repairedRoverReward = 500 * 1000000", }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Repaired Rover: Rewards", }), PlaceObj('SA_WaitExpression', { 'expression', "_malfunctions >= 2", }), PlaceObj('SA_WaitTime', { 'duration', 500, }), PlaceObj('SA_WaitMsg', { 'msg', "AttackRoverMalfunctioned", 'register', "_specialMalfunctionedRover", }), PlaceObj('SA_WaitMessage', { 'title', T(6264, --[[Scenario Mystery 6 title]] "Marsgate: Fixing a Perfect Design"), 'voiced_text', T(7261, --[[voice:narrator]] "People who aim for perfection learn soon enough that it’s a moving target. Guess EsoCorp didn’t aim high enough."), 'text', T(6265, --[[Scenario Mystery 6 text]] 'EsoCorp is having obvious issues with their mysterious rovers as they seem to be malfunctioning one after the other. Instead of admitting the faults in their predictions about the rough Martian conditions, the EsoCorp team has sent us a message which, quote, "gives the Martian Colony Command the rare privilege of sending one of our more analytical vehicles to look into the most certainly small miscalculation that causes these temporary annoyances.” End quote.\n\nFurthermore - they go on to remind us that, by choosing to analyze their broken vehicles, we have an understanding not to dig beyond any obvious logistical shortcomings in their design and agree to full and utter discretion.\n\n<effect>An Anomaly has appeared next to a malfunctioned vehicle.'), 'image', "UI/Messages/marsgate_mystery_01.tga", 'choice1', T(6266, --[[Scenario Mystery 6 choice1]] "An interesting opportunity has presented itself."), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7495, --[[Scenario Mystery 6 text]] "EsoCorp has requested us to analyze the faults in their vehicles. They have been explicitly clear and menacing as to us not delving deeper into the rover’s design and purpose."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_Exec', { 'expression', "_specialMalfunctionedRover.can_repair = false", }), PlaceObj('SA_Exec', { 'expression', "roverPos = _specialMalfunctionedRover:GetPos()", }), PlaceObj('SA_SpawnAnomaly', { 'description', T(7262, --[[Scenario Mystery 6 description]] "Analyze the reason for the constant rover breakdowns."), 'check_passability', false, 'check_buildable', false, 'random_pos_label_dist', 1000, 'register_placement_pos', "roverPos", 'store_obj', "anomaly", 'display_name', T(7263, --[[Scenario Mystery 6 display_name]] "EsoCorp Rover Problems"), 'sequence_list', "Mystery 6", 'sequence', "Anomaly 1: Effects", }), PlaceObj('SA_Exec', { 'expression', "_anomalyAnalyzed = false", }), PlaceObj('SA_Exec', { 'expression', "_timeExpired = false", }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Wait Time", }), PlaceObj('SA_WaitExpression', { 'expression', "_anomalyAnalyzed == true or _timeExpired == true", }), PlaceObj('SA_CheckExpression', { 'sa_id', 25, 'Form', "if-then-else", 'end_block', 27, 'else_block', 26, 'expression', "_anomalyAnalyzed == true", }), PlaceObj('SA_StopSequence', { 'sequence_list', "Mystery 6", 'sequence', "Wait Time", }), PlaceObj('SA_WaitChoice', { 'title', T(6267, --[[Scenario Mystery 6 title]] "Marsgate: The Path Splits"), 'voiced_text', T(7264, --[[voice:narrator]] "A little knowledge is a dangerous thing. But there’s a man out there who has so much of it that he can’t be touched."), 'text', T(6268, --[[Scenario Mystery 6 text]] "A quick scan of the mysterious vehicle was enough to encounter several design flaws that made it comically ill-equipped for Mars. However, the scan also revealed a poor attempt to disguise the true nature of these rovers. Despite having remained a mystery so far, the effort to hide its military origin could not hold up under a close examination. These rovers seem, without a doubt, weapons most probably tasked to use Mars as a testing ground – setting an extremely dangerous precedent, among other obvious problems. \n\nBy allowing us to analyze their vehicles, EsoCorp are also without a doubt issuing us a threat, and they seem comfortable enough with the notion that we will feel threatened enough to comply and keep our findings a secret. For, as issue-riddled as these rovers are, they are numerous and still pack enough fire power to disrupt our Colony, which has its hands full surviving Mars as it is.\n\nAs cynical as this all seems to be, we must take into consideration that we have no military capacity whatsoever, and choosing to challenge them might put the lives of everyone on Mars in danger."), 'image', "UI/Messages/marsgate_mystery_01.tga", 'choice1', T(6269, --[[Scenario Mystery 6 choice1]] "This breaks all international, not to mention interplanetary treaties! We’re going to expose it!"), 'choice2', T(6270, --[[Scenario Mystery 6 choice2]] "I say we call their bluff and make them buy our partnership."), 'choice3', T(6271, --[[Scenario Mystery 6 choice3]] "Our mission is too great to jeopardize this way. We’ll weather it out, just like we would a regular dust storm."), }), PlaceObj('SA_WaitChoiceCheck', { 'sa_id', 3, 'end_block', 4, }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 750000, 'rand_duration', 1500000, }), PlaceObj('SA_WaitMessage', { 'title', T(6272, --[[Scenario Mystery 6 title]] "Marsgate: Whistleblower's Pride"), 'voiced_text', T(7265, --[[voice:narrator]] "It’s done. We sent the data dump we collected from EsoCorp’s rover to Earth."), 'text', T(6273, --[[Scenario Mystery 6 text]] "We mixed it with the atmospheric and topographical data of Mars, the basic stuff you’d base your rover design on, so we know we’re safe from EsoCorp digging it up even if they do intercept the transmission.\n \nAlthough this puts us at a momentary disadvantage, we’re all proud to have done the right thing. This is the message we’ve sent to the power-hungry conglomerates back on Earth – we are leaving the old ways behind and the future will not be built on our capacity for war."), 'image', "UI/Messages/marsgate_mystery_01.tga", 'choice1', T(6274, --[[Scenario Mystery 6 choice1]] "It is time we reveal this to our citizens and brace ourselves for whatever is to come."), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7496, --[[Scenario Mystery 6 text]] "We have discovered that EsoCorp is testing military vehicles on Mars which goes against established interplanetary and international laws. Faced with a tough choice, we decided to expose the crime."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 7500000, 'rand_duration', 1500000, }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Alternative Path 1", 'wait', true, }), PlaceObj('SA_Block', { 'sa_id', 4, 'parent', 3, }), PlaceObj('SA_WaitChoiceCheck', { 'sa_id', 5, 'end_block', 6, 'value', 2, }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 750000, 'rand_duration', 1500000, }), PlaceObj('SA_WaitChoice', { 'title', T(6275, --[[Scenario Mystery 6 title]] "Marsgate: Sealing the Deal"), 'voiced_text', T(7266, --[[voice:narrator]] "We’ve received a message from EsoCorp:"), 'text', T(6276, --[[Scenario Mystery 6 text]] "“State your terms.”\n\nNever gotten a response that fast before. Most likely they thought we’d just take an insult lying down. Not to mention the risk. Though I’m pretty sure we’ll be on the wrong side of history if this gets out."), 'image', "UI/Messages/marsgate_mystery_01.tga", 'choice1', T(6277, --[[Scenario Mystery 6 choice1]] "Earth really dragged their feet on this one. We’ll need to manage this ourselves. (<funding(500000000)> Funding)"), 'choice2', T(6278, --[[Scenario Mystery 6 choice2]] "It wasn’t worth risking our Colonists. Not when we’re this underpowered. (Gain 30 Rare Metals)"), 'choice3', T(6279, --[[Scenario Mystery 6 choice3]] "The strong always get what they want. Hey, at least we got something out of it. (Receive Breakthrough tech)"), }), PlaceObj('SA_WaitChoiceCheck', { 'sa_id', 11, 'end_block', 12, }), PlaceObj('SA_Exec', { 'expression', "funding = 500 * 1000000", }), PlaceObj('SA_ChangeFunding', { 'funding', "funding", }), PlaceObj('SA_CustomNotification', { 'id', "Mystery6Reward", 'text', T(7267, --[[Scenario Mystery 6 text]] "<funding(reg_param1)>"), 'reg_param1', "funding", }), PlaceObj('SA_Block', { 'sa_id', 12, 'parent', 11, }), PlaceObj('SA_WaitChoiceCheck', { 'sa_id', 13, 'end_block', 14, 'value', 2, }), PlaceObj('SA_Exec', { 'expression', "amountPreciousMetals = 30 * const.ResourceScale", }), PlaceObj('SA_Exec', { 'expression', 'PlaceResourceStockpile_Delayed(roverPos, "PreciousMetals", 30 * const.ResourceScale, 0, true)', }), PlaceObj('SA_CustomNotification', { 'id', "Mystery6Reward", 'text', T(7570, --[[Scenario Mystery 6 text]] "<preciousmetals(reg_param1)>"), 'reg_param1', "amountPreciousMetals", 'pos_reg', "roverPos", }), PlaceObj('SA_Block', { 'sa_id', 14, 'parent', 13, }), PlaceObj('SA_WaitChoiceCheck', { 'sa_id', 15, 'end_block', 16, 'value', 3, }), PlaceObj('SA_RevealTech', nil), PlaceObj('SA_CustomNotification', { 'id', "Mystery6Reward", 'text', T(7268, --[[Scenario Mystery 6 text]] "Random Breakthrough Tech"), }), PlaceObj('SA_Block', { 'sa_id', 16, 'parent', 15, }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7497, --[[Scenario Mystery 6 text]] "We have discovered that EsoCorp is testing military vehicles on Mars which goes against established interplanetary and international laws. Faced with a tough choice, we decided to blackmail EsoCorp."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 11250000, 'rand_duration', 3750000, }), PlaceObj('SA_Exec', { 'expression', "_renegadesPercentage = 15", }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Alternative Path 2", 'wait', true, }), PlaceObj('SA_Block', { 'sa_id', 6, 'parent', 5, }), PlaceObj('SA_WaitChoiceCheck', { 'sa_id', 7, 'end_block', 8, 'value', 3, }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 750000, 'rand_duration', 1500000, }), PlaceObj('SA_WaitMessage', { 'title', T(6280, --[[Scenario Mystery 6 title]] "Marsgate: Silence of the Lambs"), 'voiced_text', T(7269, --[[voice:narrator]] "Play with a tiger, you're going to get the claws."), 'text', T(6281, --[[Scenario Mystery 6 text]] "We have sent EsoCorp our report on the rovers design flaws while carefully playing dumb to our having found out the rover’s true nature. EsoCorp’s sent us some funds as a reward. They’re also trying to pretend there’s a million-in-one chance we didn’t see right through their half-assed... Er, insufficient attempt to conceal military vehicles.\n\nTo recap - we’ve shown our willingness to keep EsoCorp's secret safe and they have acknowledged that their blunt threat was received as intended."), 'image', "UI/Messages/marsgate_mystery_01.tga", 'choice1', T(6282, --[[Scenario Mystery 6 choice1]] "No escaping our worst impulses no matter how far you get from Earth."), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7498, --[[Scenario Mystery 6 text]] "We have discovered that EsoCorp is testing military vehicles on Mars which goes against established interplanetary and international laws. Faced with a tough choice, we decided to pretend we saw nothing, fearing repercussions."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 11250000, 'rand_duration', 3750000, }), PlaceObj('SA_Exec', { 'expression', "_renegadesPercentage = 5", }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Alternative Path 2", 'wait', true, }), PlaceObj('SA_Block', { 'sa_id', 8, 'parent', 7, }), PlaceObj('SA_Block', { 'sa_id', 26, 'parent', 25, 'is_else', true, }), PlaceObj('SA_DestroyObjects', { 'obj_reg', "anomaly", 'destroy_all', true, }), PlaceObj('SA_StopSequence', { 'sequence_list', "Mystery 6", 'sequence', "Anomaly 1: Effects", }), PlaceObj('SA_Exec', { 'expression', "_renegadesPercentage = 5", }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Alternative Path 2", 'wait', true, }), PlaceObj('SA_Block', { 'sa_id', 27, 'parent', 25, }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 7500000, 'rand_duration', 3750000, }), PlaceObj('SA_WaitMessage', { 'title', T(6300, --[[Scenario Mystery 6 title]] "Marsgate: The Day We Feared"), 'voiced_text', T(7270, --[[voice:narrator]] "We’ve detected multiple unidentified objects on a trajectory towards Mars. Towards us, actually."), 'text', T(6301, --[[Scenario Mystery 6 text]] "They’re all built to EsoCorp’s specs. Just with some subtle differences thrown in. Our running hypothesis is that they’re some sort of advanced prototype. EsoCorp’s decided they want to shut down all communication, which means we can’t confirm nor deny the following:\n\nTheir movements are scattered. Dangerous. That means it’s likely a rush job aimed at hurting us for blowing the whistle on the whole “Marsgate” thing. That’s to say EsoCorp’s got a hankering for revenge. \n\nWe’ve put forward several proposals as to how we might deal with the impending attack. We’ll need our scientists working full steam on this. We cannot stress strongly enough the need to shift resources towards this end. We’ve got a word for situations like this. Critical.\n\n<effect>The Defense Turret is now available for Research."), 'image', "UI/Messages/marsgate_mystery_02.tga", 'choice1', T(6302, --[[Scenario Mystery 6 choice1]] "We need to warn the Colonists. Get our defenses up."), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7499, --[[Scenario Mystery 6 text]] "EsoCorp has decided to take revenge on us and is attacking the Colony! Our scientists have proposed defensive countermeasures."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_Repeat', { 'sa_id', 17, 'expression', "8", 'end_block', 18, }), PlaceObj('SA_Exec', { 'expression', 'PlaceObject("AttackRover", {city = UICity})', }), PlaceObj('SA_Block', { 'sa_id', 18, 'parent', 17, }), PlaceObj('SA_StopSequence', { 'sequence_list', "Mystery 6", 'sequence', "Rover Malfunctions", }), PlaceObj('SA_RevealTech', { 'tech', "DefenseTower", }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Research 1: Effects", }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 1440000, 'rand_duration', 720000, }), PlaceObj('SA_WaitMessage', { 'title', T(6306, --[[Scenario Mystery 6 title]] "Marsgate: The First Wave"), 'voiced_text', T(7272, --[[voice:narrator]] "The first attack is on its way! Brace yourselves!"), 'text', T(7271, --[[Scenario Mystery 6 text]] "All stations on Red Alert!"), 'image', "UI/Messages/marsgate_mystery_02.tga", 'choice1', T(6308, --[[Scenario Mystery 6 choice1]] "This moment has been coming for a long time."), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7500, --[[Scenario Mystery 6 text]] "EsoCorp has sent a wave of attack rovers."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_Exec', { 'expression', "UICity.mystery.can_shoot_rovers = true", }), PlaceObj('SA_HostileRoverCommand', { 'Command', "Attack", 'Param', 1, }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 1440000, }), PlaceObj('SA_WaitMessage', { 'title', T(6309, --[[Scenario Mystery 6 title]] "Marsgate: The Second Wave"), 'voiced_text', T(7273, --[[voice:narrator]] "The invasion was unrelenting. Our only choice was to fight to survive or fall to the tide of violence."), 'text', T(6310, --[[Scenario Mystery 6 text]] "EsoCorp just sent us a whole bunch of rovers. They’re quick to enter formation for a second attack. Hostilities will resume any minute now."), 'image', "UI/Messages/marsgate_mystery_02.tga", 'choice1', T(6311, --[[Scenario Mystery 6 choice1]] "Here we go again!"), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7501, --[[Scenario Mystery 6 text]] "EsoCorp has sent a second attack wave."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_Repeat', { 'sa_id', 19, 'expression', "8", 'end_block', 20, }), PlaceObj('SA_PlaceObject', { 'check_dome', "outside", 'check_terran_deposit', false, 'class_name', "AttackRover", 'use_random_pos', true, }), PlaceObj('SA_Block', { 'sa_id', 20, 'parent', 19, }), PlaceObj('SA_WaitMarsTime', { 'duration', 30000, }), PlaceObj('SA_HostileRoverCommand', { 'Command', "Attack", 'Param', 3, }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Random Attacks: Repeater", }), PlaceObj('SA_WaitMsg', { 'msg', "AttackRoverDead", }), PlaceObj('SA_WaitMessage', { 'title', T(6312, --[[Scenario Mystery 6 title]] "Marsgate: Using Their Own Stones Against Them"), 'voiced_text', T(7274, --[[voice:narrator]] "Live by the sword, die by the sword. Or the weaponized rover. Same difference."), 'text', T(6313, --[[Scenario Mystery 6 text]] "The EsoCorp rovers we destroy can be repaired and used against the enemy, or salvaged for resources. What’s more, they can protect anything in their range against meteors."), 'image', "UI/Messages/marsgate_mystery_02.tga", 'choice1', T(6311, --[[Scenario Mystery 6 choice1]] "Here we go again!"), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7502, --[[Scenario Mystery 6 text]] "We have successfully hijacked and repaired a destroyed EsoCorp rover. This ought to help our defenses."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_Exec', { 'expression', "UICity.mystery.enable_rover_repair = true", }), PlaceObj('SA_Exec', { 'expression', "UICity.mystery.reclaim_repaired_rovers = true", }), PlaceObj('SA_WaitExpression', { 'expression', "UICity.labels.HostileAttackRovers and #UICity.labels.HostileAttackRovers <= 0", }), PlaceObj('SA_StopSequence', { 'sequence_list', "Mystery 6", 'sequence', "Random Attacks: Repeater", }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Grant Wonder Tech", 'wait', true, }), PlaceObj('SA_WaitChoice', { 'title', T(6314, --[[Scenario Mystery 6 title]] "Marsgate: The Fall of EsoCorp"), 'voiced_text', T(7275, --[[voice:narrator]] "EsoCorp is done, its rovers either smoldering piles of scrap or under our total control."), 'text', T(6315, --[[Scenario Mystery 6 text]] "An attack from Earth. Never thought we’d see the day. Has this caused a rift between our two worlds? Wounds are too fresh to tell how deep they go. Might we have a chance we can walk them off and move forward together? Too early to tell, really.\n\nBack on Earth, EsoCorp executives have been arrested and the company has been shut down in many major nations. This will certainly cause economic upheaval, but the ruling parties have deemed it necessary to send a message for all future warlords: Space is neither up for military conquest nor a test ground for weapons. Developing space-oriented war machines still remains against the rules, and we will continue to pretend that this was just a fluke. Humanity has shed its need for war with grace. \n\nLooking at the smoking battlefield, so far from Earth, we can’t help but wonder if this is indeed the case. This, however, brings us to our next question. Do we destroy the prototype weapons made for the Martian environment and salvage what resources we can from the rovers, or do we keep the technology in anticipation of another “fluke”?\n\n<effect>Gained new technology, <em><reg_param1></em>"), 'image', "UI/Messages/marsgate_mystery_02.tga", 'reg_param1', "_grantedTech", 'choice1', T(6316, --[[Scenario Mystery 6 choice1]] "Put 6Ez-3 on display, destroy the rest."), 'choice2', T(6317, --[[Scenario Mystery 6 choice2]] "We would be fools to be caught so defenseless once again."), }), PlaceObj('SA_WaitChoiceCheck', { 'sa_id', 21, 'end_block', 22, }), PlaceObj('SA_DestroyObjects', { 'obj_class', "AttackRover", 'destroy_all', true, }), PlaceObj('SA_Exec', { 'expression', 'Msg("MysteryEnd", "destroyed rovers")', }), PlaceObj('SA_Block', { 'sa_id', 22, 'parent', 21, }), PlaceObj('SA_WaitChoiceCheck', { 'sa_id', 23, 'end_block', 24, 'value', 2, }), PlaceObj('SA_Exec', { 'expression', 'Msg("MysteryEnd", "kept rovers")', }), PlaceObj('SA_Block', { 'sa_id', 24, 'parent', 23, }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7503, --[[Scenario Mystery 6 text]] "EsoCorp’s rovers have been neutralized. The Marsgate affair has ended as all EsoCorp executives have been arrested by the authorities on Earth."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_UnlockAchievement', { 'achievement', "CompletedMystery6", }), PlaceObj('SA_CustomNotification', { 'id', "MysteryLog", 'popup_register', "_MarsgateMysteryLog", 'dismissable', "dismissable", }), }), PlaceObj('ScenarioSequence', { 'name', "Alternative Path 1", }, { PlaceObj('SA_WaitMessage', { 'title', T(6283, --[[Scenario Mystery 6 title]] "Marsgate"), 'voiced_text', T(7276, --[[voice:narrator]] "We blew the whistle on EsoCorp’s dealings and every news agency on Earth sunk their teeth right in. This ought to be interesting."), 'text', T(6284, --[[Scenario Mystery 6 text]] "Governments and international organizations are furious with EsoCorp’s subterfuge and forbidden military experiments and people were fast to dub the scandal “Marsgate”. As the blame game is unraveling, we can’t help but notice that all channels EsoCorp barely used to communicate with us have now been totally taken offline. Our sponsors from Earth are promising us compensation and guaranteeing protection from EsoCorp, but we fear they may not be able to help fast enough if EsoCorp decides to take revenge.\n\nThis being said, you will have to take part in an upcoming UN trial as the main witness to this whole gruesome affair.\n\n<effect>You can’t repair any more EsoCorp rovers."), 'image', "UI/Messages/marsgate_mystery_01.tga", 'choice1', T(6285, --[[Scenario Mystery 6 choice1]] "Time to walk the walk."), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7504, --[[Scenario Mystery 6 text]] "Marsgate has exploded. We are given a heads up that a UN trial will begin soon."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_Exec', { 'expression', "UICity.mystery.enable_rover_repair = false", }), PlaceObj('SA_StopSequence', { 'sequence_list', "Mystery 6", 'sequence', "Repaired Rover: Rewards", }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 750000, 'rand_duration', 1500000, }), PlaceObj('SA_WaitChoice', { 'title', T(7277, --[[Scenario Mystery 6 title]] "Marsgate: The Trial of the Century"), 'voiced_text', T(7278, --[[voice:narrator]] "The UN trial is about to start. You can guarantee they’re all hot under the collar."), 'text', T(6287, --[[Scenario Mystery 6 text]] "Joining the legal proceedings against the entity known as EsoCorp by satellite link is the head of the Mars Colony Project as a representative of <reg_param1> and the main victim in “Marsgate” other than the total disregarding of international and interplanetary treaties. The treaties, which are in place to discourage the militarization of any human endeavors in space, are held to be of utter importance by all present parties, except the defendant, and thus the transgression is seen as most grievous. \n\nBecause communication with Mars is not at its peak at this time and will take too long for a proper discussion, know that our sponsors have shared your overall stance on the whole affair. Still, as the final verdict draws near we have decided it best if you say in your own words the implications of EsoCorp’s secretive and illegal military testing operations on Mars. "), 'image', "UI/Messages/marsgate_mystery_01.tga", 'reg_param1', "_missionSponsor", 'choice1', T(7279, --[[Scenario Mystery 6 choice1]] "Humanity can do better."), 'choice2', T(7280, --[[Scenario Mystery 6 choice2]] "The risk was great, but we did the right thing."), }), PlaceObj('SA_WaitChoiceCheck', { 'sa_id', 1, 'end_block', 2, }), PlaceObj('SA_Exec', { 'expression', "applicants = 3", }), PlaceObj('SA_WaitMessage', { 'title', T(7281, --[[Scenario Mystery 6 title]] "Marsgate: A Harsh Message"), 'voiced_text', T(7282, --[[voice:narrator]] "It was time for humanity to come to grips with the fact that violence only breeds more violence. And that’s exactly what we told them."), 'text', T(6290, --[[Scenario Mystery 6 text]] "EsoCorp put the lives of people, who brave an unforgiving world in the name of humanity, in danger with nothing more than profit in mind. A harsh verdict today will stand as testament to humanity reaching the maturity needed to spread amidst the stars.\n\n<effect><reg_param1> Applicants with rare traits are available on Earth"), 'image', "UI/Messages/marsgate_mystery_01.tga", 'start_minimized', false, 'reg_param1', "applicants", }), PlaceObj('SA_AddApplicants', { 'Number', "applicants", 'Trait', "random_rare", }), PlaceObj('SA_Block', { 'sa_id', 2, 'parent', 1, }), PlaceObj('SA_WaitChoiceCheck', { 'sa_id', 3, 'end_block', 4, 'value', 2, }), PlaceObj('SA_Exec', { 'expression', "funding = 1500 * 1000000", }), PlaceObj('SA_WaitMessage', { 'title', T(7283, --[[Scenario Mystery 6 title]] "Marsgate: A Message of Hope"), 'voiced_text', T(7282, --[[voice:narrator]] "It was time for humanity to come to grips with the fact that violence only breeds more violence. And that’s exactly what we told them."), 'text', T(6291, --[[Scenario Mystery 6 text]] "We of Mars, who have denounced any militarization, have chosen to move on from the ways of the past and shape our new home into a place where military conflict is a thing of myth and legend. In doing so, we place our trust that this idea will resonate with all people back on Earth, our home world, and bring humanity not only to another planet, but to another level of evolution. Yet this incident has shown us that we may not do so without help from Mother Earth, and this trial today has renewed our hope that our vision for the future is not entirely wishful thinking.\n\n<effect>Gained <funding(reg_param1)> Funding"), 'image', "UI/Messages/marsgate_mystery_01.tga", 'start_minimized', false, 'reg_param1', "funding", }), PlaceObj('SA_ChangeFunding', { 'funding', "funding", }), PlaceObj('SA_Block', { 'sa_id', 4, 'parent', 3, }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7505, --[[Scenario Mystery 6 text]] "The UN has praised and rewarded us for our brave and risky move to expose EsoCorp."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), }), PlaceObj('ScenarioSequence', { 'name', "Alternative Path 2", }, { PlaceObj('SA_WaitMessage', { 'title', T(6292, --[[Scenario Mystery 6 title]] "Marsgate"), 'voiced_text', T(7284, --[[voice:narrator]] "The cat’s out of the bag. One of our bolder Colonists took it upon himself to do what we couldn’t – expose EsoCorp and their dirty dealings on Mars."), 'text', T(6293, --[[Scenario Mystery 6 text]] "The lengths he has taken to circumvent our detection not only by EsoCorp, but that of Mission Control as well, shows us painstakingly that we have failed him and probably many others like him. In their eyes we were playing for the other team. It puts us all to shame. Many citizens are showing their discontent with our Colony now that our own actions have been exposed, and back on Earth this whole ordeal is blowing up to mind boggling proportions. It has been dubbed “Marsgate” and we are accused of being compliant in the breaking of international and interplanetary treaties by the UN. \n\nPopular pressure has prompted that a trial start as quickly as possible. You will be required to defend our actions via satellite link.\n\n<effect>You can’t repair any more EsoCorp rovers."), 'image', "UI/Messages/marsgate_mystery_01.tga", 'choice1', T(7285, --[[Scenario Mystery 6 choice1]] "We only wanted to protect them, right?"), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7506, --[[Scenario Mystery 6 text]] "Marsgate has exploded. One of our citizens has exposed EsoCorp and our involvement in the affair."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), PlaceObj('SA_Exec', { 'expression', "UICity.mystery.enable_rover_repair = false", }), PlaceObj('SA_StopSequence', { 'sequence_list', "Mystery 6", 'sequence', "Repaired Rover: Rewards", }), PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 750000, 'rand_duration', 1500000, }), PlaceObj('SA_Exec', { 'expression', "renegades = UICity.labels.Colonist and #UICity.labels.Colonist > 0 and (#UICity.labels.Colonist * _renegadesPercentage / 100) or 0", }), PlaceObj('SA_WaitChoice', { 'title', T(6286, --[[Scenario Mystery 6 title]] "Marsgate: Wrong Side of History"), 'voiced_text', T(7286, --[[voice:narrator]] "The UN trial is about to start... I can already feel the water heating up."), 'text', T(6287, --[[Scenario Mystery 6 text]] "Joining the legal proceedings against the entity known as EsoCorp by satellite link is the head of the Mars Colony Project as a representative of <reg_param1> and the main victim in “Marsgate” other than the total disregarding of international and interplanetary treaties. The treaties, which are in place to discourage the militarization of any human endeavors in space, are held to be of utter importance by all present parties, except the defendant, and thus the transgression is seen as most grievous. \n\nBecause communication with Mars is not at its peak at this time and will take too long for a proper discussion, know that our sponsors have shared your overall stance on the whole affair. Still, as the final verdict draws near we have decided it best if you say in your own words the implications of EsoCorp’s secretive and illegal military testing operations on Mars. "), 'image', "UI/Messages/marsgate_mystery_01.tga", 'reg_param1', "_missionSponsor", 'choice1', T(6288, --[[Scenario Mystery 6 choice1]] "At the end of the day, it is Earth that has failed us by allowing this whole thing in the first place."), 'choice2', T(6289, --[[Scenario Mystery 6 choice2]] "You want the truth? You can’t handle the truth!"), }), PlaceObj('SA_WaitChoiceCheck', { 'sa_id', 1, 'end_block', 2, }), PlaceObj('SA_WaitMessage', { 'title', T(7287, --[[Scenario Mystery 6 title]] "Marsgate: The Blame Game"), 'voiced_text', T(7288, --[[voice:narrator]] "A tough moment. We tried our best not to fan the flames."), 'text', T(6296, --[[Scenario Mystery 6 text]] "EsoCorp put the lives of people, who brave an unforgiving world in the name of humanity, in danger with nothing more than profit in mind. We at Mission Control, on the other hand, are tasked with protecting the mission and the lives of all people taking part in it, so we did what we saw fit in order to see our duties are met. With guns pointing at our life support equipment and the closest help 3 million miles away, we were left with little choice and we stand by our decision. Why EsoCorp was able to send these rovers all the way to Mars without being detected from Earth is beyond us and we, the people of Mars, feel let down by Earth today.\n\n<effect><reg_param1> Colonists became Renegades."), 'image', "UI/Messages/marsgate_mystery_01.tga", 'start_minimized', false, 'reg_param1', "renegades", 'choice1', T(6294, --[[Scenario Mystery 6 choice1]] "OK"), }), PlaceObj('SA_Block', { 'sa_id', 2, 'parent', 1, }), PlaceObj('SA_WaitChoiceCheck', { 'sa_id', 3, 'end_block', 4, 'value', 2, }), PlaceObj('SA_WaitMessage', { 'title', T(7289, --[[Scenario Mystery 6 title]] "Marsgate: What Can Change the Nature of Man?"), 'voiced_text', T(7290, --[[voice:narrator]] "This was bound to happen. We gave them the whole truth and nothing but the truth, whether they wanted it or not."), 'text', T(6297, --[[Scenario Mystery 6 text]] "EsoCorp came to Mars with force, deployed in our vicinity, breaking every law and basically putting a gun to our heads. It was a classic story of the strong bullying the weak, or in this case, someone completely unprepared for such an event. In a way it was a stab in the back, as we idolized Earth as a source of safety while we had to wrestle with the unforgiving calamities of Mars. \n\nWe did not like it, but we came to the realization that it was only a matter of time before this happened and that it was better to have a strong ally. We are pioneers on a new frontier, opening countless possibilities and space for humans to be, well, humans. If it was not EsoCorp today, it would have been someone else tomorrow, I assure you. And that someone else might have come at different circumstances and not offered us, albeit indirectly, a way to stay on their good side. At the end of day, we may have changed planets, but we are still humans, with all the blessings and curses this fact carries in itself.\n\n<effect><reg_param1> Colonists became Renegades."), 'image', "UI/Messages/marsgate_mystery_01.tga", 'start_minimized', false, 'reg_param1', "renegades", 'choice1', T(6294, --[[Scenario Mystery 6 choice1]] "OK"), }), PlaceObj('SA_Block', { 'sa_id', 4, 'parent', 3, }), PlaceObj('SA_AddTrait', { 'Label', "Colonist", 'Number', "renegades", 'Trait', "Renegade", }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7507, --[[Scenario Mystery 6 text]] "The UN has shown some understanding of the difficult situation we were put in but has fined the Colony nonetheless. The resulting loss of reputation diverted many Applicants from the project."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), }), PlaceObj('ScenarioSequence', { 'name', "Anomaly 1: Effects", }, { PlaceObj('SA_Exec', { 'expression', "_anomalyAnalyzed = true", }), PlaceObj('SA_Exec', { 'expression', "_specialMalfunctionedRover.can_repair = true", }), }), PlaceObj('ScenarioSequence', { 'name', "Wait Time", }, { PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 3750000, 'rand_duration', 3750000, }), PlaceObj('SA_Exec', { 'expression', "_timeExpired = true", }), PlaceObj('SA_Exec', { 'expression', "_specialMalfunctionedRover.can_repair = true", }), }), PlaceObj('ScenarioSequence', { 'name', "Research 1: Effects", }, { PlaceObj('SA_WaitResearch', { 'Field', "Mysteries", 'Research', "DefenseTower", 'State', "Researched", }), PlaceObj('SA_WaitMessage', { 'title', T(6303, --[[Scenario Mystery 6 title]] "Marsgate: Missile Envy"), 'voiced_text', T(7291, --[[voice:narrator]] "Fight fire with fire! Well, rockets. You know what I mean."), 'text', T(6304, --[[Scenario Mystery 6 text]] "We can now build laser-targeting missile defense systems. This will help us mount a defense against the incoming attacks."), 'image', "UI/Messages/marsgate_mystery_02.tga", 'choice1', T(6305, --[[Scenario Mystery 6 choice1]] "This ought to give us a fighting chance."), }), PlaceObj('SA_AppendToLog', { 'register', "_MarsgateMysteryLog", 'text', T(7508, --[[Scenario Mystery 6 text]] "In an attempt to counter the attacks we designed missile turrets tasked with repulsing all incoming attacks."), }), PlaceObj('SA_RunSequence', { 'sequence_list', "Mystery 6", 'sequence', "Update Mystery Log", }), }), PlaceObj('ScenarioSequence', { 'name', "Rover Malfunctions", 'loop', true, }, { PlaceObj('SA_WaitMarsTime', { 'wait_type', "Sols", 'duration', 2880000, 'rand_duration', 2160000, }), PlaceObj('SA_Exec', { 'expression', 'local t = UICity.labels.HostileAttackRovers\nif #t > 0 then\nt[UICity:Random(#t)+1]:SetCommand("Malfunction")\nend', }), }), PlaceObj('ScenarioSequence', { 'name', "Malfunctioned Rovers: Counter", }, { PlaceObj('SA_Exec', { 'expression', "_malfunctions = 0", }), PlaceObj('SA_Repeat', { 'sa_id', 1, 'end_block', 2, }), PlaceObj('SA_WaitMsg', { 'msg', "AttackRoverMalfunctioned", }), PlaceObj('SA_Exec', { 'expression', "_malfunctions = _malfunctions + 1", }), PlaceObj('SA_WaitTime', { 'duration', 500, }), PlaceObj('SA_Block', { 'sa_id', 2, 'parent', 1, }), }), PlaceObj('ScenarioSequence', { 'name', "Repaired Rover: Rewards", 'loop', true, }, { PlaceObj('SA_WaitMsg', { 'msg', "AttackRoverRepaired", }), PlaceObj('SA_WaitTime', { 'duration', 3000, }), PlaceObj('SA_ChangeFunding', { 'funding', "_repairedRoverReward", }), PlaceObj('SA_CustomNotification', { 'id', "Mystery6Reward", 'text', T(7292, --[[Scenario Mystery 6 text]] "<funding(reg_param1)>"), 'reg_param1', "_repairedRoverReward", }), }), PlaceObj('ScenarioSequence', { 'name', "Random Attacks: Repeater", 'loop', true, }, { PlaceObj('SA_WaitMarsTime', { 'duration', 360000, 'rand_duration', 360000, }), PlaceObj('SA_Exec', { 'expression', "attackers = UICity.labels.HostileAttackRovers and #UICity.labels.HostileAttackRovers or 0", }), PlaceObj('SA_HostileRoverCommand', { 'Number', "attackers", 'Command', "Attack", 'Param', 1, }), }), PlaceObj('ScenarioSequence', { 'name', "Update Mystery Log", }, { PlaceObj('SA_CustomNotification', { 'id', "MysteryLog", 'popup_register', "_MarsgateMysteryLog", }), }), PlaceObj('ScenarioSequence', { 'name', "Grant Wonder Tech", }, { PlaceObj('SA_Exec', { 'expression', "tech_id = GrantWonderTech()", }), PlaceObj('SA_Exec', { 'expression', "_grantedTech = TechDef[tech_id].display_name", }), }), })
i = 0 while true do i = i + 1 if i > 10 then break end end
local abs, min, max, atan2 = math.abs, math.min, math.max, math.atan2 local push = table.insert local tbl = Libs.tbl local Vec = _Require_relative(..., 'lib.DeWallua.vector-light',1) local Shape = _Require_relative(...,"Shape") ---@class ConvexPolygon : Shape ConvexPolygon = Shape:extend() ConvexPolygon.name = 'convex' -- Recursive function that returns a list of {x=#,y=#} coordinates given a list of procedural, ccw coordinate pairs local function to_verts(vertices, x, y, ...) if not (x and y) then return vertices end vertices[#vertices + 1] = {x = x, y = y} -- , dx = 0, dy = 0} -- set vertex return to_verts(vertices, ...) end local function to_vertices(vertices, x, ...) return type(x) == 'table'and to_verts(vertices, unpack(x)) or to_verts(vertices, x,...) end -- Test if 3 points are collinear (do they not make a triangle?) local function is_collinear(a, b, c) return abs(Vec.det(a.x-c.x, a.y-c.y, b.x-c.x,b.y-c.y)) <= 1e-32 end -- Test if 3 points make a ccw turn (same as collinear function, but checks for >= 0) local function is_ccw(p, q, r) return Vec.det(q.x-p.x, q.y-p.y, r.x-p.x, r.y-p.y) >= 0 end -- Remove vertices that are collinear local function trim_collinear(vertices) local trimmed = {} local i, j = #vertices-1, #vertices for k = 1, #vertices do if not is_collinear(vertices[i], vertices[j], vertices[k]) then trimmed[#trimmed+1] = vertices[j] end i,j = j,k end return trimmed end -- Two lines, a-b and c-d, intersect if their endpoints lie on different sides wrt each other local function are_lines_intersecting(a,b, c,d) return is_ccw(a,b,c) ~= is_ccw(a,b,d) and is_ccw(a,c,d) ~= is_ccw(b,c,d) end -- Checks for physical intersection of lines within polygon's vertices local function self_intersecting(vertices) local a, b = nil, vertices[#vertices] for i = 1, #vertices-2 do a, b = b, vertices[i] for j = i+1, #vertices-1 do local c, d = vertices[j], vertices[j+1] if are_lines_intersecting(a,b, c,d) then return true end end end return false end -- Check if points are convex by verifying all groups of 3 points make a ccw winding local function is_convex(vertices) local i, j = #vertices-1, #vertices for k = 1, #vertices do -- Convex polygons always make a ccw turn if not is_ccw(vertices[i], vertices[j], vertices[k]) then return false end -- Cycle i to j, j to k i,j = j,k end -- Made it out, must be convex return true end -- Enforce counter-clockwise points order using graham scan sort local function order_points_ccw(vertices) -- Find reference point to calculate cw/ccw from (left-most x, lowest y) local p_ref = vertices[1] for i = 2, #vertices do -- if vertices[i].x < ref.x then ref.x = vertices[i].x else ref.x = ref.x --p_ref.x = (vertices[i].x < p_ref.x) and vertices.x or p_ref.x; if vertices[i].y < p_ref.y then p_ref = vertices[i] elseif vertices[i].y == p_ref.y then if vertices[i].x < p_ref.x then p_ref = vertices[i] end end end -- Declare table.sort function -- p_ref is an upvalue (within scope), so it can be accessed from table.sort local function sort_ccw(v1,v2) -- if v1 is p_ref, then it should win the sort automatically if v1.x == p_ref.x and v1.y == p_ref.y then return true elseif v2.x == p_ref.x and v2.y == p_ref.y then -- if v2 is p_ref, then v1 should lose the sort automatically return false end -- Else compare polar angles local a1 = atan2(v1.y - p_ref.y, v1.x - p_ref.x) -- angle between x axis and line from p_ref to v1 local a2 = atan2(v2.y - p_ref.y, v2.x - p_ref.x) -- angle between x axis and line from p_ref to v1 if a1 < a2 then return true -- true means first arg wins the sort (v1 in our case) elseif a1 == a2 then -- points have same angle, so choose the point furthest from p_ref -- Compute points' distances local m1 = Vec.dist(v1.x,v1.y, p_ref.x,p_ref.y) local m2 = Vec.dist(v2.x,v2.y, p_ref.x,p_ref.y) if m1 > m2 then -- Pick the furthest point to win return true -- v1 is fatrther, so it wins the sort end end end -- Sort a copy of vertices. If convex, then apply the sort to the original, else return false local vertices_clone = tbl.shallow_copy(vertices, {}) -- Sort table, Check if convex table.sort(vertices_clone, sort_ccw) local good_sort = is_convex(vertices_clone) -- Return our investigation return good_sort and true, table.sort(vertices, sort_ccw) or not true end ---Calculate polygon area using shoelace algorithm ---@return number area function ConvexPolygon:calcArea() local vertices = self.vertices -- Initialize p and q so we can wrap around in the loop local p, q = vertices[#vertices], vertices[1] -- a is the signed area of the triangle formed by the two legs of p.x-q.x and p.y-q.y - it is our weighting local a = Vec.det(p.x,p.y, q.x,q.y) -- signed_area is the total signed area of all triangles local area = a for i = 2, #vertices do -- Now assign p to q, q to next p, q = q, vertices[i] a = Vec.det(p.x,p.y, q.x,q.y) area = area + a end self.area = area * 0.5 return self.area end ---Calculate centroid and area of the polygon at the _same_ time ---@return number area ---@return table centroid function ConvexPolygon:calcAreaCentroid() local vertices = self.vertices -- Initialize p and q so we can wrap around in the loop local p, q = vertices[#vertices], vertices[1] -- a is the area of the triangle formed by the two legs of p.x-q.x and p.y-q.y - it is our weighting local a = Vec.det(p.x,p.y, q.x,q.y) -- area is the total area of all triangles self.area = a self.centroid = {x = (p.x+q.x)*a, y = (p.y+q.y)*a} for i = 2, #vertices do -- Now cycle p to q, q to next vertex p, q = q, vertices[i] a = Vec.det(p.x,p.y, q.x,q.y) self.centroid.x, self.centroid.y = self.centroid.x + (p.x+q.x)*a, self.centroid.y + (p.y+q.y)*a self.area = self.area + a end self.area = self.area * 0.5 self.centroid.x = self.centroid.x / (6*self.area); self.centroid.y = self.centroid.y / (6*self.area); return self.area, self.centroid end ---Calculate polygon radius ---@return number radius function ConvexPolygon:calcRadius() local vertices, radius = self.vertices, 0 for i = 1,#vertices do radius = max(radius, Vec.dist(vertices[i].x,vertices[i].y, self.centroid.x, self.centroid.y)) end self.radius = radius return self.radius end ---Get polygon bounding box ---@return number x, number y, number dx, number dy minimum x/y, width, and height function ConvexPolygon:getBbox() local min_x, max_x, min_y, max_y = self.vertices[1].x,self.vertices[1].x, self.vertices[1].y, self.vertices[1].y local x, y--, bbox for __, vertex in ipairs(self.vertices) do x, y = vertex.x, vertex.y if x < min_x then min_x = x end if x > max_x then max_x = x end if y < min_y then min_y = y end if y > max_y then max_y = y end end -- Return rect info as separate values (don't create a table (aka garbage)!) return min_x, min_y, max_x-min_x, max_y-min_y end ---Return unpacked vertices ---@return number[] ... variable list used to construct the polygon function ConvexPolygon:unpack() local v = {} for i = 1,#self.vertices do v[2*i-1] = self.vertices[i].x v[2*i] = self.vertices[i].y end return unpack(v) end -- Create new Polygon object ---@vararg number x,y tuples ---@param x number ---@param y number function ConvexPolygon:new(x,y, ...) self.vertices = to_vertices({}, x,y, ...) assert(#self.vertices >= 3, "Need at least 3 non collinear points to build polygon (got "..#self.vertices..")") if not is_convex(self.vertices) then assert(order_points_ccw(self.vertices), 'Points cannot be ordered into a convex shape') end trim_collinear(self.vertices) assert(not self_intersecting(self.vertices), 'Ordered points still self-intersecting') self.centroid = {x=0,y=0} self.area = 0 self.radius = 0 self.angle = 0 self:calcAreaCentroid() self:calcRadius() end local function iter_edges(shape, i) i = i + 1 local v = shape.vertices if i <= #v then local j = i < #v and i+1 or 1 return i, {v[i].x, v[i].y, v[j].x, v[j].y} end end ---Edge Iterator ---@return function ---@return ConvexPolygon ---@return number function ConvexPolygon:ipairs() return iter_edges, self, 0 end local function iter_vecs(shape, i) i = i + 1 local v = shape.vertices if i <= #v then local j = i < #v and i+1 or 1 return i, {x = v[j].x - v[i].x, y = v[j].y - v[i].y} end end ---Iterate over edge vectors ---@return function ---@return ConvexPolygon ---@return number function ConvexPolygon:vecs() return iter_vecs, self, 0 end ---Translate by displacement vector ---@param dx number ---@param dy number ---@return ConvexPolygon self function ConvexPolygon:translate(dx, dy) -- Translate each vertex by dx, dy local vertices = self.vertices for i = 1, #vertices do vertices[i].x = vertices[i].x + dx vertices[i].y = vertices[i].y + dy end -- Translate centroid self.centroid.x = self.centroid.x + dx self.centroid.y = self.centroid.y + dy return self end ---Rotate by specified radians ---@param angle number radians ---@param refx number reference x-coordinate ---@param refy number reference y-coordinate ---@return ConvexPolygon self function ConvexPolygon:rotate(angle, refx, refy) -- Default to centroid as ref-point refx = refx or self.centroid.x refy = refy or self.centroid.y -- Rotate each vertex about ref-point for i = 1, #self.vertices do local v = self.vertices[i] v.x, v.y = Vec.add(refx, refy, Vec.rotate(angle, v.x-refx, v.y - refy)) end self.centroid.x, self.centroid.y = Vec.add(refx, refy, Vec.rotate(angle, self.centroid.x-refx, self.centroid.y-refy)) self.angle = self.angle + angle return self end --- scale helper function local function scale_p(x,y, sf,rx,ry) return Vec.add(rx, ry, Vec.mul(sf, x-rx, y - ry)) end ---Scale polygon ---@param sf number scale factor ---@param refx number reference x-coordinate ---@param refy number reference y-coordinate ---@return ConvexPolygon self function ConvexPolygon:scale(sf, refx, refy) -- Default to centroid as ref-point local c = self.centroid refx = refx or c.x refy = refy or c.y -- Push each vertex out from the ref point by scale-factor for i = 1, #self.vertices do local v = self.vertices[i] v.x, v.y = scale_p(v.x,v.y, sf,refx,refy) end c.x, c.y = scale_p(c.x, c.y, sf, refx, refy) -- Recalculate area, and radius self.area = self.area * sf * sf self.radius = self.radius * sf return self end ---Project polygon along normalized vector ---@param nx number normalized x-component ---@param ny number normalized y-component ---@return number minimum, number maximumum smallest, largest projection function ConvexPolygon:project(nx,ny) local vertices = self.vertices local proj_x, proj_y local p, min_dot, max_dot -- Project each point onto vector <nx, ny> proj_x, proj_y = vertices[1].x, vertices[1].y -- Init our min/max dot products (Can't init to random value) min_dot = Vec.dot(proj_x,proj_y, nx,ny) max_dot = min_dot -- Create new projection vectors, dot-prod them with the input vector, and return the min/max for i = 2, #vertices do proj_x, proj_y = vertices[i].x , vertices[i].y p = Vec.dot(proj_x,proj_y, nx,ny) if p < min_dot then min_dot = p elseif p > max_dot then max_dot = p end end return min_dot, max_dot end ---Get an edge by index ---@param i number ---@return table {x1,y1, x2,y2} function ConvexPolygon:getEdge(i) if i > #self.vertices then return false end local verts = self.vertices local j = i < #verts and i+1 or 1 local p1, p2 = verts[i], verts[j] return {p1.x, p1.y, p2.x, p2.y} end --- Need this to test if a shape is completely inside ---@param point Point function ConvexPolygon:containsPoint(point) local vertices = self.vertices local winding = 0 local p, q = vertices[#vertices], vertices[1] for i = 1, #vertices do if p.y < point.y then if q.y > point.y and is_ccw(p,q, point) then winding = winding + 1 end else if q.y < point.y and not is_ccw(p,q, point) then winding = winding - 1 end end end return winding ~= 0 end ---Project each individual edge instead of using self:project like in Circle ---@param x number ray origin ---@param y number ray origin ---@param dx number normalized x component ---@param dy number normalized y component ---@return boolean hit function ConvexPolygon:rayIntersects(x,y, dx,dy) dx, dy = Vec.perpendicular(dx,dy) local d = Vec.dot(x,y, dx,dy) for i, edge in self:ipairs() do local e1 = Vec.dot(edge[1],edge[2], dx,dy) local e2 = Vec.dot(edge[3],edge[4], dx,dy) if (e1-d) * (e2-d) <= 0 then return true end end return false end -- https://stackoverflow.com/a/32146853/12135804 ---Return all intersections as distances along ray ---@param x number ray origin ---@param y number ray origin ---@param dx number normalized x component ---@param dy number normalized y component ---@param ts table ---@return table | nil intersections function ConvexPolygon:rayIntersections(x,y, dx,dy, ts) local v1x, v1y, v2x, v2y local nx, ny = -dy, dx ts = ts or {} for i, edge in self:ipairs() do v1x, v1y = Vec.sub(x, y, edge[1], edge[2]) v2x, v2y = Vec.sub(edge[3], edge[4], edge[1], edge[2]) local dot = Vec.dot(v2x, v2y, nx, ny) if abs(dot) < 0.0001 then break end local t1 = Vec.det(v2x,v2y, v1x,v1y) / dot local t2 = Vec.dot(v1x,v1y, nx,ny) / dot if t1 >= 0 and (t2 >= 0 and t2 <= 1) then push(ts, t1) end end return #ts > 0 and ts or nil end ConvexPolygon._get_verts = ConvexPolygon.unpack -- ------------------]] Polygon Merging [[------------------ -- -- Use spatial-coordinate search to detect if two polygons -- share a coordinate pair (means have an incident face) local function get_incident_edge(poly1, poly2) -- Define hash table local p_map = {} -- Iterate over poly_1's vertices, add x/y coords as keys to pmap local v1 = poly1.vertices for i = 1, #v1 do local key = v1[i].x..'-'..v1[i].y p_map[key] = i end -- Now look through poly_2's vertices and see if there's a match local v2 = poly2.vertices local i = #v2 for j = 1, #v2 do -- Set p and q to reference poly_2's vertices at i and j local p, q = v2[i], v2[j] local kp, kq = p.x..'-'..p.y, q.x..'-'..q.y -- Access p_map based on line p-q's two coordinates if p_map[kp] and p_map[kq] then -- Return the indices of the edge in both polygons return p_map[kp],p_map[kq], i,j end i = j end -- No incident edge return false end -- Given two convex polygons, merge them together -- So long as the new polygon is also convex ---@param poly1 ConvexPolygon ---@param poly2 ConvexPolygon ---@return ConvexPolygon | boolean local function merge_convex_incident(poly1, poly2) if not poly2.vertices then return false end -- Find an incident edge between the two polygons local i_1,j_1, i_2,j_2 = get_incident_edge(poly1, poly2) if not i_1 then return false end local v1, v2 = poly1.vertices, poly2.vertices local union = {} -- Loop through the vertices of poly_1 and add applicable points to the union for i = 1, #v1 do -- Skip the vertex if it's part of the poly_2's half of the incident edge if i ~= j_1 then push(union, v1[i].x) push(union, v1[i].y) end end -- Do the same for poly2 for i = 1, #v2 do if i ~= i_2 then push(union, v2[i].x) push(union, v2[i].y) end end local new_verts = to_vertices({},unpack(union)) order_points_ccw(new_verts) return is_convex(new_verts) and ConvexPolygon(unpack(union)) or not true end ConvexPolygon.merge = merge_convex_incident ---Contact Functions function ConvexPolygon:getSupport(nx,ny) local maxd, index = -math.huge , 1 for i, point in ipairs(self.vertices) do local projection = Vec.dot(point.x,point.y, nx,ny) if projection > maxd then maxd = projection index = i end end return index end ---Get the edge involved in a collision ---@param nx number normalized x dir ---@param ny number normalized y dir ---@return table Max-Point ---@return table Edge function ConvexPolygon:getFeature(nx,ny) local verts = self.vertices -- get farthest point in direction of normal local index = self:getSupport(nx,ny) -- test adjacent points to find edge most perpendicular to normal local v = verts[index] local i0 = index - 1 >= 1 and index - 1 or #verts local i1 = index + 1 <= #verts and index + 1 or 1 local v0 = verts[i0] local v1 = verts[i1] local gx,gy = Vec.normalize( Vec.sub(v.x,v.y, v0.x,v0.y) ) local hx,hy = Vec.normalize( Vec.sub(v.x,v.y, v1.x,v1.y) ) if math.abs(Vec.dot(gx,gy, nx,ny)) <= math.abs(Vec.dot(hx,hy, nx,ny)) then return {x=v.x,y=v.y}, {{x=v0.x,y=v0.y}, {x=v.x,y=v.y}} else return {x=v.x,y=v.y}, {{x=v.x,y=v.y}, {x=v1.x,y=v1.y}} end end if love and love.graphics then ---Draw polygon w/ LOVE ---@param mode string fill/line function ConvexPolygon:draw(mode) -- default fill to "line" mode = mode or "line" love.graphics.polygon(mode, self:_get_verts()) end end return ConvexPolygon
local settings = {} table.insert(settings, { type = "int-setting", name = "spice-rack-turret-inspector-debug-mode", order = "a", setting_type = "runtime-global", default_value = 0, allowed_values = { 0, 1, 2, 3, 4 } }) table.insert(settings, { type = "bool-setting", name = "spice-rack-turret-inspector-show-turret-warnings", order = "b", setting_type = "runtime-per-user", default_value = true, }) table.insert(settings, { type = "int-setting", name = "spice-rack-turret-inspector-ammo-low", order = "c", setting_type = "runtime-per-user", default_value = 7, minimum_value = 0, maximum_value = 200, }) table.insert(settings, { type = "int-setting", name = "spice-rack-turret-inspector-ammo-almost-empty", order = "d", setting_type = "runtime-per-user", default_value = 3, minimum_value = 0, maximum_value = 200, }) data:extend(settings)
-- ---------------------------------------------------------------------------- -- Copyright (c) 2012-2020 HERE Global B.V. and its affiliate(s). -- All rights reserved. -- The use of this software is conditional upon having a separate agreement -- with a HERE company for the use or utilization of this software. In the -- absence of such agreement, the use of the software is not allowed. -- ---------------------------------------------------------------------------- -- Voice Skin: None -- Warner beeps only description = "" output_type = "audio" speaker = "" gender = "f" travel_mode = "1" language = "None" marc_code = "" language_id = "100" id = "100003001" config_file = "none/config.lua" audio_files_path = "none/none" audio_files_version = "0.3.0.2012060601" feature_list = { "metric", "imperial_uk", "imperial_us" } client_range = "[client >= 1.4.6.0 ]" misc = { ["beep_sound"] = "beep", ["over_speed_limit_wav"] = "g5war_speed_limit_soft4edit9" }
--Take a signal (set in the first block) and turn it into it's corresponding signal (set in the second block). --code is from UsefulCombinators and is a temporary reminder of what to do. classes["transformer-combinator"] = { on_click = function(player, object) local gui = player.gui.center if gui["uc"]["converter-combinator"]["from"].elem_value and gui["uc"]["converter-combinator"]["from"].elem_value.name then object.meta.params[1] = {signal = gui["uc"]["converter-combinator"]["from"].elem_value} else object.meta.params[1] = {type = "virtual"} end if gui["uc"]["converter-combinator"]["to"].elem_value and gui["uc"]["converter-combinator"]["to"].elem_value.name then object.meta.params[2] = {signal = gui["uc"]["converter-combinator"]["to"].elem_value} else object.meta.params[2] = {type = "virtual"} end end, on_key = function(player, object) if not (player.gui.center["uc"]) then local params = object.meta.params local gui = player.gui.center local uc = gui.add{type = "frame", name = "uc", caption = "Converter Combinator"} local layout = uc.add{type = "table", name = "converter-combinator", colspan = 4} layout.add{type = "label", caption = "From: "} if params[1].signal and params[1].signal.name then layout.add{type = "choose-elem-button", name = "from", elem_type = "signal", signal = params[1].signal} else layout.add{type = "choose-elem-button", name = "from", elem_type = "signal"} end layout.add{type = "label", caption = "To: "} if params[2].signal and params[2].signal.name then layout.add{type = "choose-elem-button", name = "to", elem_type = "signal", signal = params[2].signal} else layout.add{type = "choose-elem-button", name = "to", elem_type = "signal"} end layout.add{type = "button", name = "uc-exit", caption = "Ok"} end end, on_place = function(entity) return { meta = { entity = entity, params = { {signal = {type = "virtual"}}, {signal = {type = "virtual"}} } } } end, on_destroy = function() end, on_tick = function(object) local control = object.meta.entity.get_control_behavior() if control then local params = object.meta.params if params[2].signal then if control.enabled then local slots = {} if params[2].signal.name then table.insert(slots, {signal = params[2].signal, count = get_count(control, params[1].signal), index = 1}) end control.parameters = { parameters = slots } end else control.parameters = { parameters = {} } end end end } function get_count(control, signal) if not signal then return 0 end local red = control.get_circuit_network(defines.wire_type.red) local green = control.get_circuit_network(defines.wire_type.green) local val = 0 if red then val = red.get_signal(signal) or 0 end if green then val = val + (green.get_signal(signal) or 0) end return val end function get_signals(control) local red = control.get_circuit_network(defines.wire_type.red) local green = control.get_circuit_network(defines.wire_type.green) local network = {} if red and red.signals then for _,v in pairs(red.signals) do if v.signal.name then network[v.signal.name] = v end end end if green and green.signals then for _,v in pairs(green.signals) do if v.signal.name then network[v.signal.name] = v end end end return network end
--******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** --takes in a data file and implements logic for returning batches from it. local Batcher = torch.class('Batcher') function Batcher:__init(filePath, batchSize, shuffle) print(filePath) local loadedData = torch.load(filePath) print(loadedData) self.labels = loadedData.labels self.data = loadedData.data self.classId = loadedData.classId self.doShuffle = shuffle if (self.labels:dim() == 1) then -- print("in batch") -- print(self.labels) self.labelDimension = 1 -- self.labels = self.labels:mul(-1):add(2) -- print(self.labels) else self.labelDimension = self.labels:size(2) end self.numPaths = self.data:size(2) self.numTokensInPath = self.data:size(3) self.numFeatureTemplates = self.data:size(4) if self.doShuffle then self:shuffle() end --first shuffle self.batchSize = batchSize self.curStart = 1 end function Batcher:shuffle() if(self.doShuffle) then local inds = torch.randperm(self.labels:size(1)):long() self.labels = self.labels:index(1,inds) self.data = self.data:index(1,inds) end end function Batcher:getBatch() local dataSize = self.labels:size(1) local startIndex = self.curStart if startIndex > dataSize then return nil end local endIndex = math.min(startIndex+self.batchSize-1, dataSize) local currBatchSize = endIndex - startIndex + 1 local batchLabels = self.labels:narrow(1, startIndex, currBatchSize) local batchData = self.data:narrow(1, startIndex, currBatchSize) self.curStart = endIndex + 1 return batchLabels, batchData end function Batcher:reset() self.curStart = 1 if self.doShuffle then self:shuffle() end end --return all the dimensions except the first dimension of the data because they are fixed and will be used to preallocate tensors in gpu. function Batcher:getSizes() return self.labelDimension, self.numPaths, self.numTokensInPath, self.numFeatureTemplates end --return the classId associated with this batcher function Batcher:getClassId() return self.classId end
set('ninja_required_version', '1.8') set('basedir', basedir) set('builddir', config.builddir) set('dir', '$basedir') set('outdir', '$builddir') set('repo', config.repo.path) set('repo_flags', config.repo.flags) set('repo_tag', config.repo.tag) set('repo_branch', config.repo.branch) include '$basedir/rules.ninja' toolchain(config.target) subgen 'probe' subgen 'pkg' build('awk', '$outdir/root.perms', {'$outdir/tree.fspec', '|', '$basedir/scripts/perms.awk'}, { expr='-f $basedir/scripts/perms.awk', }) gitfile('.perms', '644', '$outdir/root.perms') build('git-init', '$outdir/root.stamp') build('git-tree', '$outdir/root.tree', {'$outdir/root.index', '|', '$basedir/scripts/tree.sh', '||', '$outdir/root.stamp'}) build('git-commit', '$outdir/root.commit', {'|', '$outdir/root.tree'}) build('phony', 'commit', '$builddir/root.commit') build('fspec-sort', '$outdir/root.fspec', {'$outdir/tree.fspec', '|', '$builddir/pkg/fspec-sync/host/fspec-sort'}) build('fspec-tar', '$outdir/root.tar.zst', {'$outdir/root.fspec', '|', '$builddir/pkg/fspec-sync/host/fspec-tar'}) --build('awk', '$outdir/root.sqfslist', {'$outdir/root.fspec', '|', '$basedir/scripts/squashfs.awk'}, { -- expr='-f $basedir/scripts/squashfs.awk', --}) --rule('gensquashfs', 'gensquashfs -F $in -D . -f -c gzip $out') --build('gensquashfs', '$outdir/root.squashfs', {'$outdir/root.sqfslist'}) build('phony', 'build.ninja', 'ninja', {generator='1'}) io.write('default $builddir/root.tree\n')
object_tangible_furniture_base_flag_city_base = object_tangible_furniture_base_shared_flag_city_base:new { } ObjectTemplates:addTemplate(object_tangible_furniture_base_flag_city_base, "object/tangible/furniture/base/flag_city_base.iff")
local U = require "togo.utility" local O = require "Quanta.Object" local Match = require "Quanta.Match" local Measurement = require "Quanta.Measurement" local Unit = require "Quanta.Unit" local Entity = require "Quanta.Entity" local Dialect = require "Dialect" local M = U.module(...) M.Property = U.class(M.Property) function M.Property:__init(value, encrypted) self.value = U.type_assert(value, "string", true) self.encrypted = U.type_assert(encrypted, "boolean", true) or false end function M.Property:to_object(obj, serialized_name) if self.value ~= nil and self.value ~= "" then local value_obj = O.push_child(obj) O.set_name(value_obj, serialized_name) O.set_string(value_obj, self.value) if self.encrypted then O.set_string_type(value_obj, "enc") end end end function M.Property.adapt_pattern(property_name) return Match.Pattern{ name = property_name, vtype = O.Type.string, acceptor = function(context, thing, obj) local self = thing.data[property_name] self.value = O.string(obj) local string_type = O.string_type(obj) if string_type == "enc" then self.encrypted = true elseif string_type == "" then self.encrypted = false else return Match.Error("string type '%s' not recognized; must be none or 'enc'", string_type) end end, } end M.Account = Dialect.make_entity( M, "Account", function(class) function class.Source:__init(source) self.email = M.Property() self.misc = M.Property() self.uid = M.Property() self.pwd = M.Property() end function class.Source:to_object(source, obj) self.email:to_object(obj, "email") self.misc:to_object(obj, "misc") self.uid:to_object(obj, "uid") self.pwd:to_object(obj, "pwd") end class.Source.t_body:add({ M.Property.adapt_pattern("email"), M.Property.adapt_pattern("misc"), M.Property.adapt_pattern("uid"), M.Property.adapt_pattern("pwd"), }) end) return M
--[[ Author: your name Date: 2019-11-11 09:33:07 LastEditTime: 2021-01-14 18:50:06 LastEditors: Please set LastEditors Description: In User Settings Edit FilePath: \luci-app-vssr\luasrc\model\cbi\vssr\socks5.lua --]] local vssr = 'vssr' local uci = luci.model.uci.cursor() local server_table = {} local sys = require 'luci.sys' m = Map(vssr) -- [[ SOCKS5 Proxy ]]-- if nixio.fs.access('/usr/bin/xray') then s = m:section(TypedSection, 'socks5_proxy', translate('Xray SOCKS5 Proxy')) s.anonymous = true o = s:option(Flag, 'enable_server', translate('Enable Servers')) o.rmempty = false o = s:option(Flag, 'enable_auth', translate('Enable Auth')) o.rmempty = false o = s:option(Value, 'Socks_user', translate('Socks user')) o.default = 'user' o.rmempty = true o:depends('enable_auth', '1') o = s:option(Value, 'Socks_pass', translate('Socks pass')) o.default = 'password' o.password = true o.rmempty = true o:depends('enable_auth', '1') o = s:option(Value, 'local_port', translate('Local Port')) o.datatype = 'port' o.default = 1080 o.rmempty = false end -- [[ Http Proxy ]]-- if nixio.fs.access('/usr/bin/xray') then s = m:section(TypedSection, 'http_proxy', translate('Xray HTTP Proxy')) s.anonymous = true o = s:option(Flag, 'enable_server', translate('Enable Servers')) o.rmempty = false o = s:option(Flag, 'enable_auth', translate('Enable Auth')) o.rmempty = false o = s:option(Value, 'http_user', translate('HTTP user')) o.default = 'user' o.rmempty = true o:depends('enable_auth', '1') o = s:option(Value, 'http_pass', translate('HTTP pass')) o.default = 'password' o.password = true o.rmempty = true o:depends('enable_auth', '1') o = s:option(Value, 'local_port', translate('Local Port')) o.datatype = 'port' o.default = 1088 o.rmempty = false end return m
--- --- JMQuickBanking --- --[[ Variable declaration ]] --- -- @field name -- @field savedVariablesName -- local Config = { name = 'JMQuickBanking', savedVariablesName = 'JMQuickBankingSavedVariables', } local SavedVariables = {} -- QuickBankingLibrary local QBL = {} QBL.getItems = function (bagId) local items = {} local bagSize = GetBagSize(bagId) -- StackBag(bagId) for index = 0, bagSize do local type = GetItemType(bagId, index) if type ~= ITEMTYPE_NONE then local name = GetItemName(bagId, index) local filter = GetItemFilterTypeInfo(bagId, index) local link = GetItemLink(bagId, index, LINK_STYLE_DEFAULT) local _, stack, _, _, _, _ = GetItemInfo(bagId, index) table.insert(items, { type = type, name = name, filter = filter, link = link, stack = stack, }) end end -- d(items) return items end --[[ Initialize ]] --- -- Start of the addon -- local function Initialize() -- Load the saved variables SavedVariables = ZO_SavedVars:NewAccountWide(Config.savedVariablesName, 1, nil, { --buyList = {}, }) --BuyList = SavedVariables.buyList EVENT_MANAGER:RegisterForEvent(Config.name, EVENT_OPEN_BANK, function () end) EVENT_MANAGER:RegisterForEvent(Config.name, EVENT_CLOSE_BANK, function () end) EVENT_MANAGER:RegisterForEvent(Config.name, EVENT_BANK_IS_FULL, function () end) EVENT_MANAGER:RegisterForEvent(Config.name, EVENT_INVENTORY_BOUGHT_BANK_SPACE, function () end) zo_callLater(function () QBL.getItems(BAG_BACKPACK) end, 5000) end --[[ Api ]] --- -- Making some functions public -- JMQuickBanking = { -- No API calls yet } --[[ Events ]] --- Adding the initialize handler EVENT_MANAGER:RegisterForEvent( Config.name, EVENT_ADD_ON_LOADED, function (event, addonName) if addonName ~= Config.name then return end Initialize() EVENT_MANAGER:UnregisterForEvent(Config.name, EVENT_ADD_ON_LOADED) end )
--- Example superclass for inheritance example. Intended for OOP. -- @classmod Animal -- @author colbert2677 local Animal = {} Animal.ClassName = "Animal" Animal.__index = Animal function Animal:__tostring() return self.ClassName end function Animal.new(name, species) local self = setmetatable({ Species = species, Name = name, }, Animal) return self end --- Only for demonstration's sake. Please just directly set properties. Don't take after this example. function Animal:ChangeName(newName) local oldName = self.Name self.Name = newName print(self.Name .. " changed their name from " .. oldName .. "!") end function Animal:Destroy() -- Must lose references afterward setmetatable(self, nil) end return Animal
local Tree = {} local index = 0 function Tree.initTree(rootValue) if #Tree < 1 then table.insert(Tree, { index = index, value = rootValue, visited = false, children = {} }) index = index + 1 return true else print('Could not initialized Tree. Length greater than zero.') return false end end function Tree.getRoot() if #Tree > 0 then return Tree[1] else print('Tree not initialized.') return nil end end function Tree.putNode(node, value) if node then table.insert(node.children, { index = index, value = value, visited = false, children = {} }) index = index + 1 return true else print('Could not insert at root element.' .. value) assert() return false end end function Tree.getUnvisited(node) local left = node.children[1] local center = node.children[2] local right = node.children[3] if not node.visited then return node end local nodeunvisited = nil if right and Tree.getUnvisited(right) then nodeunvisited = Tree.getUnvisited(right) end if center and Tree.getUnvisited(center) then nodeunvisited = Tree.getUnvisited(center) end if left and Tree.getUnvisited(left) then nodeunvisited = Tree.getUnvisited(left) end return nodeunvisited end function Tree.postOrder(node) local left = node.children[1] local center = node.children[2] local right = node.children[3] if left then Tree.postOrder(left) end if center then Tree.postOrder(center) end if right then Tree.postOrder(right) end print(node.value) end function Tree.derive(node, production) local lastUnvisited = Tree.getUnvisited(Tree.getRoot()) for i = 1, #production do Tree.putNode(node, string.sub(production, i,i)) end node.visited = true end function Tree.match(node, input) if node.value ~= input then Tree.derive(node, input) end local newUnvisited = Tree.getUnvisited(Tree.getRoot()) if newUnvisited.value == input then newUnvisited.visited = true end end -- Tree.initTree('S') -- Tree.derive(Tree.getUnvisited(Tree.getRoot()),'V=E') -- Tree.derive(Tree.getUnvisited(Tree.getRoot()),'@') -- Tree.match(Tree.getUnvisited(Tree.getRoot()), 'x') -- Tree.match(Tree.getUnvisited(Tree.getRoot()), '=') -- Tree.derive(Tree.getUnvisited(Tree.getRoot()),'TF') -- Tree.derive(Tree.getUnvisited(Tree.getRoot()),'Z') -- Tree.derive(Tree.getUnvisited(Tree.getRoot()),'#') -- Tree.match(Tree.getUnvisited(Tree.getRoot()), '3') -- Tree.match(Tree.getUnvisited(Tree.getRoot()), '&') -- Tree.postOrder(Tree.getRoot()) return Tree
-------简单数据------- local tab ={} tab["Himi"] = "himigame.com" --数据转json local cjson = require "cjson" local jsonData = cjson.encode(tab) print(jsonData) -- 打印结果: {"Himi":"himigame.com"} --json转数据 local data = cjson.decode(jsonData) print(data.Himi) -- 打印结果: himigame.com