repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
PichotM/DarkRP
entities/weapons/unarrest_stick/shared.lua
2
3057
AddCSLuaFile() if CLIENT then SWEP.PrintName = "Unarrest Baton" SWEP.Slot = 1 SWEP.SlotPos = 3 end DEFINE_BASECLASS("stick_base") SWEP.Instructions = "Left click to unarrest\nRight click to switch batons" SWEP.IsDarkRPUnarrestStick = true SWEP.Spawnable = true SWEP.Category = "DarkRP (Utility)" SWEP.StickColor = Color(0, 255, 0) DarkRP.hookStub{ name = "canUnarrest", description = "Whether someone can unarrest another player.", parameters = { { name = "unarrester", description = "The player trying to unarrest someone.", type = "Player" }, { name = "unarrestee", description = "The player being unarrested.", type = "Player" } }, returns = { { name = "canUnarrest", description = "A yes or no as to whether the player can unarrest the other player.", type = "boolean" }, { name = "message", description = "The message that is shown when they can't unarrest the player.", type = "string" } }, realm = "Server" } -- Default for canUnarrest hook local hookCanUnarrest = {canUnarrest = fp{fn.Id, true}} function SWEP:Deploy() self.Switched = true return BaseClass.Deploy(self) end function SWEP:PrimaryAttack() BaseClass.PrimaryAttack(self) if CLIENT then return end self:GetOwner():LagCompensation(true) local trace = util.QuickTrace(self:GetOwner():EyePos(), self:GetOwner():GetAimVector() * 90, {self:GetOwner()}) self:GetOwner():LagCompensation(false) if IsValid(trace.Entity) and trace.Entity.onUnArrestStickUsed then trace.Entity:onUnArrestStickUsed(self:GetOwner()) return end local ent = self:GetOwner():getEyeSightHitEntity(nil, nil, function(p) return p ~= self:GetOwner() and p:IsPlayer() and p:Alive() end) if not ent then return end if not IsValid(ent) or not ent:IsPlayer() or (self:GetOwner():EyePos():DistToSqr(ent:GetPos()) > self.stickRange * self.stickRange) or not ent:getDarkRPVar("Arrested") then return end local canUnarrest, message = hook.Call("canUnarrest", hookCanUnarrest, self:GetOwner(), ent) if not canUnarrest then if message then DarkRP.notify(self:GetOwner(), 1, 5, message) end return end ent:unArrest(self:GetOwner()) DarkRP.notify(ent, 0, 4, DarkRP.getPhrase("youre_unarrested_by", self:GetOwner():Nick())) if self:GetOwner().SteamName then DarkRP.log(self:GetOwner():Nick() .. " (" .. self:GetOwner():SteamID() .. ") unarrested " .. ent:Nick(), Color(0, 255, 255)) end end function SWEP:startDarkRPCommand(usrcmd) if game.SinglePlayer() and CLIENT then return end if usrcmd:KeyDown(IN_ATTACK2) then if not self.Switched and self:GetOwner():HasWeapon("arrest_stick") then usrcmd:SelectWeapon(self:GetOwner():GetWeapon("arrest_stick")) end else self.Switched = false end end
mit
PichotM/DarkRP
gamemode/modules/hitmenu/cl_menu.lua
3
7300
local PANEL local minHitDistanceSqr = GM.Config.minHitDistance * GM.Config.minHitDistance --[[--------------------------------------------------------------------------- Hitman menu ---------------------------------------------------------------------------]] PANEL = {} AccessorFunc(PANEL, "hitman", "Hitman") AccessorFunc(PANEL, "target", "Target") AccessorFunc(PANEL, "selected", "Selected") function PANEL:Init() self.BaseClass.Init(self) self.btnClose = vgui.Create("DButton", self) self.btnClose:SetText("") self.btnClose.DoClick = function() self:Remove() end self.btnClose.Paint = function(panel, w, h) derma.SkinHook("Paint", "WindowCloseButton", panel, w, h) end self.icon = vgui.Create("SpawnIcon", self) self.icon:SetDisabled(true) self.icon.PaintOver = function(icon) icon:SetTooltip() end self.icon:SetTooltip() self.title = vgui.Create("DLabel", self) self.title:SetText(DarkRP.getPhrase("hitman")) self.name = vgui.Create("DLabel", self) self.price = vgui.Create("DLabel", self) self.playerList = vgui.Create("DScrollPanel", self) self.btnRequest = vgui.Create("HitmanMenuButton", self) self.btnRequest:SetText(DarkRP.getPhrase("hitmenu_request")) self.btnRequest.DoClick = function() if IsValid(self:GetTarget()) then RunConsoleCommand("darkrp", "requesthit", self:GetTarget():SteamID(), self:GetHitman():UserID()) self:Remove() end end self.btnCancel = vgui.Create("HitmanMenuButton", self) self.btnCancel:SetText(DarkRP.getPhrase("cancel")) self.btnCancel.DoClick = function() self:Remove() end self:SetSkin(GAMEMODE.Config.DarkRPSkin) self:InvalidateLayout() end function PANEL:Think() if not IsValid(self:GetHitman()) or self:GetHitman():GetPos():DistToSqr(LocalPlayer():GetPos()) > minHitDistanceSqr then self:Remove() return end -- update the price (so the hitman can't scam) self.price:SetText(DarkRP.getPhrase("priceTag", DarkRP.formatMoney(self:GetHitman():getHitPrice()), "")) self.price:SizeToContents() end function PANEL:PerformLayout() local w, h = self:GetSize() self:SetSize(500, 700) self:Center() self.btnClose:SetSize(24, 24) self.btnClose:SetPos(w - 24 - 5, 5) self.icon:SetSize(128, 128) self.icon:SetModel(self:GetHitman():GetModel()) self.icon:SetPos(20, 20) self.title:SetFont("ScoreboardHeader") self.title:SetPos(20 + 128 + 20, 20) self.title:SizeToContents(true) self.name:SizeToContents(true) self.name:SetText(DarkRP.getPhrase("name", self:GetHitman():Nick())) self.name:SetPos(20 + 128 + 20, 20 + self.title:GetTall()) self.price:SetFont("HUDNumber5") self.price:SetColor(Color(255, 0, 0, 255)) self.price:SetText(DarkRP.getPhrase("priceTag", DarkRP.formatMoney(self:GetHitman():getHitPrice()), "")) self.price:SetPos(20 + 128 + 20, 20 + self.title:GetTall() + 20) self.price:SizeToContents(true) self.playerList:SetPos(20, 20 + self.icon:GetTall() + 20) self.playerList:SetWide(self:GetWide() - 40) self.btnRequest:SetPos(20, h - self.btnRequest:GetTall() - 20) self.btnRequest:SetButtonColor(Color(0, 120, 30, 255)) self.btnCancel:SetPos(w - self.btnCancel:GetWide() - 20, h - self.btnCancel:GetTall() - 20) self.btnCancel:SetButtonColor(Color(140, 0, 0, 255)) self.playerList:StretchBottomTo(self.btnRequest, 20) self.BaseClass.PerformLayout(self) end function PANEL:Paint() local w, h = self:GetSize() surface.SetDrawColor(Color(0, 0, 0, 200)) surface.DrawRect(0, 0, w, h) end function PANEL:AddPlayerRows() local players = table.Copy(player.GetAll()) table.sort(players, function(a, b) local aTeam, bTeam, aNick, bNick = team.GetName(a:Team()), team.GetName(b:Team()), string.lower(a:Nick()), string.lower(b:Nick()) return aTeam == bTeam and aNick < bNick or aTeam < bTeam end) for k, v in pairs(players) do local canRequest = hook.Call("canRequestHit", DarkRP.hooks, self:GetHitman(), LocalPlayer(), v, self:GetHitman():getHitPrice()) if not canRequest then continue end local line = vgui.Create("HitmanMenuPlayerRow") line:SetPlayer(v) self.playerList:AddItem(line) line:SetWide(self.playerList:GetWide() - 100) line:Dock(TOP) line.DoClick = function() self:SetTarget(line:GetPlayer()) if IsValid(self:GetSelected()) then self:GetSelected():SetSelected(false) end line:SetSelected(true) self:SetSelected(line) end end end vgui.Register("HitmanMenu", PANEL, "DPanel") --[[--------------------------------------------------------------------------- Hitmenu button ---------------------------------------------------------------------------]] PANEL = {} AccessorFunc(PANEL, "btnColor", "ButtonColor") function PANEL:PerformLayout() self:SetSize(self:GetParent():GetWide() / 2 - 30, 100) self:SetFont("HUDNumber5") self:SetTextColor(Color(255, 255, 255, 255)) self.BaseClass.PerformLayout(self) end function PANEL:Paint() local w, h = self:GetSize() local col = self:GetButtonColor() or Color(0, 120, 30, 255) surface.SetDrawColor(col.r, col.g, col.b, col.a) surface.DrawRect(0, 0, w, h) end vgui.Register("HitmanMenuButton", PANEL, "DButton") --[[--------------------------------------------------------------------------- Player row ---------------------------------------------------------------------------]] PANEL = {} AccessorFunc(PANEL, "player", "Player") AccessorFunc(PANEL, "selected", "Selected", FORCE_BOOL) function PANEL:Init() self.lblName = vgui.Create("DLabel", self) self.lblName:SetMouseInputEnabled(false) self.lblName:SetColor(Color(255,255,255,200)) self.lblTeam = vgui.Create("DLabel", self) self.lblTeam:SetMouseInputEnabled(false) self.lblTeam:SetColor(Color(255,255,255,200)) self:SetText("") self:SetCursor("hand") end function PANEL:PerformLayout() local ply = self:GetPlayer() if not IsValid(ply) then self:Remove() return end self.lblName:SetFont("UiBold") self.lblName:SetText(DarkRP.deLocalise(ply:Nick())) self.lblName:SizeToContents() self.lblName:SetPos(10, 1) self.lblTeam:SetFont("UiBold") self.lblTeam:SetText((ply.DarkRPVars and DarkRP.deLocalise(ply:getDarkRPVar("job") or "")) or team.GetName(ply:Team())) self.lblTeam:SizeToContents() self.lblTeam:SetPos(self:GetWide() / 2, 1) end function PANEL:Paint() if not IsValid(self:GetPlayer()) then self:Remove() return end local color = team.GetColor(self:GetPlayer():Team()) color.a = self:GetSelected() and 70 or 255 surface.SetDrawColor(color) surface.DrawRect(0, 0, self:GetWide(), 20) end vgui.Register("HitmanMenuPlayerRow", PANEL, "Button") --[[--------------------------------------------------------------------------- Open the hit menu ---------------------------------------------------------------------------]] function DarkRP.openHitMenu(hitman) local frame = vgui.Create("HitmanMenu") frame:SetHitman(hitman) frame:AddPlayerRows() frame:SetVisible(true) frame:MakePopup() end
mit
haste/oUF
elements/stagger.lua
2
5884
--[[ # Element: Monk Stagger Bar Handles the visibility and updating of the Monk's stagger bar. ## Widget Stagger - A `StatusBar` used to represent the current stagger level. ## Sub-Widgets .bg - A `Texture` used as a background. It will inherit the color of the main StatusBar. ## Notes A default texture will be applied if the widget is a StatusBar and doesn't have a texture set. ## Sub-Widgets Options .multiplier - Used to tint the background based on the main widgets R, G and B values. Defaults to 1 (number)[0-1] ## Examples local Stagger = CreateFrame('StatusBar', nil, self) Stagger:SetSize(120, 20) Stagger:SetPoint('TOPLEFT', self, 'BOTTOMLEFT', 0, 0) -- Register with oUF self.Stagger = Stagger --]] if(select(2, UnitClass('player')) ~= 'MONK') then return end local _, ns = ... local oUF = ns.oUF -- sourced from FrameXML/Constants.lua local SPEC_MONK_BREWMASTER = SPEC_MONK_BREWMASTER or 1 -- sourced from FrameXML/MonkStaggerBar.lua local BREWMASTER_POWER_BAR_NAME = BREWMASTER_POWER_BAR_NAME or 'STAGGER' -- percentages at which bar should change color local STAGGER_YELLOW_TRANSITION = STAGGER_YELLOW_TRANSITION or 0.3 local STAGGER_RED_TRANSITION = STAGGER_RED_TRANSITION or 0.6 -- table indices of bar colors local STAGGER_GREEN_INDEX = STAGGER_GREEN_INDEX or 1 local STAGGER_YELLOW_INDEX = STAGGER_YELLOW_INDEX or 2 local STAGGER_RED_INDEX = STAGGER_RED_INDEX or 3 local function UpdateColor(element, cur, max) local colors = element.__owner.colors.power[BREWMASTER_POWER_BAR_NAME] local perc = cur / max local t if(perc >= STAGGER_RED_TRANSITION) then t = colors and colors[STAGGER_RED_INDEX] elseif(perc > STAGGER_YELLOW_TRANSITION) then t = colors and colors[STAGGER_YELLOW_INDEX] else t = colors and colors[STAGGER_GREEN_INDEX] end local r, g, b if(t) then r, g, b = t[1], t[2], t[3] if(b) then element:SetStatusBarColor(r, g, b) local bg = element.bg if(bg and b) then local mu = bg.multiplier or 1 bg:SetVertexColor(r * mu, g * mu, b * mu) end end end end local function Update(self, event, unit) if(unit and unit ~= self.unit) then return end local element = self.Stagger --[[ Callback: Stagger:PreUpdate() Called before the element has been updated. * self - the Stagger element --]] if(element.PreUpdate) then element:PreUpdate() end -- Blizzard code has nil checks for UnitStagger return local cur = UnitStagger('player') or 0 local max = UnitHealthMax('player') element:SetMinMaxValues(0, max) element:SetValue(cur) --[[ Override: Stagger:UpdateColor(cur, max) Used to completely override the internal function for updating the widget's colors. * self - the Stagger element * cur - the amount of staggered damage (number) * max - the player's maximum possible health value (number) --]] element:UpdateColor(cur, max) --[[ Callback: Stagger:PostUpdate(cur, max) Called after the element has been updated. * self - the Stagger element * cur - the amount of staggered damage (number) * max - the player's maximum possible health value (number) --]] if(element.PostUpdate) then element:PostUpdate(cur, max) end end local function Path(self, ...) --[[ Override: Stagger.Override(self, event, unit) Used to completely override the internal update function. * self - the parent object * event - the event triggering the update (string) * unit - the unit accompanying the event (string) --]] return (self.Stagger.Override or Update)(self, ...) end local function Visibility(self, event, unit) if(SPEC_MONK_BREWMASTER ~= GetSpecialization() or UnitHasVehiclePlayerFrameUI('player')) then if(self.Stagger:IsShown()) then self.Stagger:Hide() self:UnregisterEvent('UNIT_AURA', Path) end else if(not self.Stagger:IsShown()) then self.Stagger:Show() self:RegisterEvent('UNIT_AURA', Path) end return Path(self, event, unit) end end local function VisibilityPath(self, ...) --[[ Override: Stagger.OverrideVisibility(self, event, unit) Used to completely override the internal visibility toggling function. * self - the parent object * event - the event triggering the update (string) * unit - the unit accompanying the event (string) --]] return (self.Stagger.OverrideVisibility or Visibility)(self, ...) end local function ForceUpdate(element) return VisibilityPath(element.__owner, 'ForceUpdate', element.__owner.unit) end local function Enable(self) local element = self.Stagger if(element) then element.__owner = self element.ForceUpdate = ForceUpdate self:RegisterEvent('UNIT_DISPLAYPOWER', VisibilityPath) self:RegisterEvent('PLAYER_TALENT_UPDATE', VisibilityPath, true) if(element:IsObjectType('StatusBar') and not element:GetStatusBarTexture()) then element:SetStatusBarTexture([[Interface\TargetingFrame\UI-StatusBar]]) end if(not element.UpdateColor) then element.UpdateColor = UpdateColor end MonkStaggerBar:UnregisterEvent('PLAYER_ENTERING_WORLD') MonkStaggerBar:UnregisterEvent('PLAYER_SPECIALIZATION_CHANGED') MonkStaggerBar:UnregisterEvent('UNIT_DISPLAYPOWER') MonkStaggerBar:UnregisterEvent('UNIT_EXITED_VEHICLE') MonkStaggerBar:UnregisterEvent('UPDATE_VEHICLE_ACTIONBAR') element:Hide() return true end end local function Disable(self) local element = self.Stagger if(element) then element:Hide() self:UnregisterEvent('UNIT_AURA', Path) self:UnregisterEvent('UNIT_DISPLAYPOWER', VisibilityPath) self:UnregisterEvent('PLAYER_TALENT_UPDATE', VisibilityPath) MonkStaggerBar:RegisterEvent('PLAYER_ENTERING_WORLD') MonkStaggerBar:RegisterEvent('PLAYER_SPECIALIZATION_CHANGED') MonkStaggerBar:RegisterEvent('UNIT_DISPLAYPOWER') MonkStaggerBar:RegisterEvent('UNIT_EXITED_VEHICLE') MonkStaggerBar:RegisterEvent('UPDATE_VEHICLE_ACTIONBAR') end end oUF:AddElement('Stagger', VisibilityPath, Enable, Disable)
mit
LORgames/premake-core
modules/d/_preload.lua
3
4194
-- -- Name: d/_preload.lua -- Purpose: Define the D language API's. -- Author: Manu Evans -- Created: 2013/10/28 -- Copyright: (c) 2013-2015 Manu Evans and the Premake project -- -- TODO: -- MonoDevelop/Xamarin Studio has 'workspaces', which correspond to collections -- of Premake workspaces. If premake supports multiple workspaces, we should -- write out a workspace file... local p = premake local api = p.api -- -- Register the D extension -- p.D = "D" api.addAllowed("language", p.D) api.addAllowed("floatingpoint", "None") api.addAllowed("flags", { "CodeCoverage", "Color", "Documentation", "GenerateHeader", "GenerateJSON", "GenerateMap", "LowMem", "Profile", "Quiet", "RetainPaths", "SymbolsLikeC", "UnitTest", -- These are used by C++/D mixed $todo move them somewhere else? "flags2" "Dflags"? -- [Code Generation Flags] "UseLDC", "ProfileGC", "StackFrame", "StackStomp", "AllInstantiate", "BetterC", "Main", "PerformSyntaxCheckOnly", -- [Messages Flags] "ShowCommandLine", "Verbose", "ShowTLS", "ShowGC", "IgnorePragma", "ShowDependencies", }) -- -- Register some D specific properties -- api.register { name = "boundscheck", scope = "config", kind = "string", allowed = { "Default", "Off", "On", "SafeOnly", }, } api.register { name = "compilationmodel", scope = "config", kind = "string", allowed = { "Default", "File", "Package", -- TODO: this doesn't work with gmake!! "Project", }, } api.register { name = "checkaction", scope = "config", kind = "string", allowed = { "Default", "D", "C", "Halt", "Context", }, } api.register { name = "computetargets", scope = "config", kind = "list:string", } -- api.register { -- name = "debugcode", -- scope = "config", -- kind = "string", -- } api.register { name = "debugconstants", scope = "config", kind = "list:string", tokens = true, } api.register { name = "debuglevel", scope = "config", kind = "integer", } api.register { name = "dependenciesfile", scope = "config", kind = "path", tokens = true, } api.register { name = "deprecatedfeatures", scope = "config", kind = "string", allowed = { "Default", "Allow", "Warn", "Error", }, } api.register { name = "docdir", scope = "config", kind = "path", tokens = true, } api.register { name = "docname", scope = "config", kind = "string", tokens = true, } api.register { name = "headerdir", scope = "config", kind = "path", tokens = true, } api.register { name = "headername", scope = "config", kind = "string", tokens = true, } api.register { name = "jsonfile", scope = "config", kind = "path", tokens = true, } api.register { name = "importdirs", scope = "config", kind = "list:path", tokens = true, } api.register { name = "preview", scope = "config", kind = "list:string", allowed = { "dip25", "dip1000", "dip1008", "fieldwise", "markdown", "fixAliasThis", "intpromote", "dtorfields", }, } api.register { name = "revert", scope = "config", kind = "list:string", allowed = { "dip25", "import", }, } api.register { name = "stringimportdirs", scope = "config", kind = "list:path", tokens = true, } api.register { name = "transition", scope = "config", kind = "list:string", allowed = { "field", "checkimports", "complex", "tls", "vmarkdown", }, } api.register { name = "versionconstants", scope = "config", kind = "list:string", tokens = true, } api.register { name = "versionlevel", scope = "config", kind = "integer", } -- -- Provide information for the help output -- newoption { category = "compilers", trigger = "dc", value = "VALUE", description = "Choose a D compiler", allowed = { { "dmd", "Digital Mars (dmd)" }, { "gdc", "GNU GDC (gdc)" }, { "ldc", "LLVM LDC (ldc2)" }, } } -- -- Decide when to load the full module -- return function (cfg) return (cfg.language == p.D or cfg.language == "C" or cfg.language == "C++") end
bsd-3-clause
alireza1998/supergroup
plugins/face.lua
641
3073
local https = require("ssl.https") local ltn12 = require "ltn12" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(imageUrl) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?" local parameters = "attribute=gender%2Cage%2Crace" parameters = parameters .. "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" if jsonBody.error ~= nil then if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then response = response .. "The image is too big. Provide a smaller image." elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then response = response .. "Is that a valid url for an image?" else response = response .. jsonBody.error end elseif jsonBody.face == nil or #jsonBody.face == 0 then response = response .. "No faces found" else response = response .. #jsonBody.face .." face(s) found:\n\n" for k,face in pairs(jsonBody.face) do local raceP = "" if face.attribute.race.confidence > 85.0 then raceP = face.attribute.race.value:lower() elseif face.attribute.race.confidence > 50.0 then raceP = "(probably "..face.attribute.race.value:lower()..")" else raceP = "(posibly "..face.attribute.race.value:lower()..")" end if face.attribute.gender.confidence > 85.0 then response = response .. "There is a " else response = response .. "There may be a " end response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " " response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n" end end return response end local function run(msg, matches) --return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg') local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end return parseData(data) end return { description = "Who is in that photo?", usage = { "!face [url]", "!recognise [url]" }, patterns = { "^!face (.*)$", "^!recognise (.*)$" }, run = run }
gpl-2.0
Sasu98/Nerd-Gaming-Public
resources/NGModshop/vehicle.funcs.lua
4
2215
vehicleUpgrades = { names = { }, prices = { } } lowriders = { [536]=true, [575]=true, [534]=true, [567]=true, [535]=true, [576]=true, [412]=true } racers = { [562]=true, [565]=true, [559]=true, [561]=true, [560]=true, [558]=true } _getVehicleCompatibleUpgrades = getVehicleCompatibleUpgrades function getVehicleCompatibleUpgrades( veh ) local upgrs = _getVehicleCompatibleUpgrades( veh ) local upgrades = { } for k,v in ipairs( upgrs ) do if not ( v == 1004 or v == 1005 or v == 1013 or v == 1024 or v == 1023 or v == 1031 or v == 1040 or v == 1041 or v == 1099 or v == 1143 or v == 1145 or v == 1030 or v == 1120 or v == 1121 ) then table.insert( upgrades, v ) end end return upgrades end function isVehicleLowrider( vehicle ) local id = getElementModel( vehicle ) return lowriders[ id ] end function isVehicleRacer( vehicle ) local id = getElementModel( vehicle ) return racers[ id ] end function loadItems( ) local file_root = xmlLoadFile( "moditems.xml" ) local sub_node = xmlFindChild( file_root, "item", 0 ) local i = 1 while sub_node do vehicleUpgrades.names[ i ] = xmlNodeGetAttribute( sub_node, "name" ) vehicleUpgrades.prices[ i ] = xmlNodeGetAttribute( sub_node, "price" ) sub_node = xmlFindChild( file_root, "item", i ) i = i + 1 end end function getItemPrice( itemid ) if not itemid then return false end if itemid < 1000 or itemid > 1193 then return false elseif type( itemid ) ~= 'number' then return false end return vehicleUpgrades.prices[ itemid - 999 ] end function getItemName( itemid ) if not itemid then return false end if itemid > 1193 or itemid < 1000 then return false elseif type( itemid ) ~= 'number' then return false end return vehicleUpgrades.names[ itemid - 999 ] end function getItemIDFromName( itemname ) if not itemname then return false elseif type( itemname ) ~= 'string' then return false end for k,v in ipairs( vehicleUpgrades.names ) do if v == itemname then return k + 999 end end return false end
mit
Anarchid/Zero-K
units/chickenspire.lua
4
4043
return { chickenspire = { unitname = [[chickenspire]], name = [[Chicken Spire]], description = [[Static Artillery]], acceleration = 0, activateWhenBuilt = true, brakeRate = 0, buildCostEnergy = 0, buildCostMetal = 0, builder = false, buildingGroundDecalDecaySpeed = 30, buildingGroundDecalSizeX = 6, buildingGroundDecalSizeY = 6, buildingGroundDecalType = [[chickenspire_aoplane.dds]], buildPic = [[chickenspire.png]], buildTime = 2500, category = [[SINK]], collisionVolumeOffsets = [[0 48 0]], collisionVolumeScales = [[58 176 58]], collisionVolumeType = [[CylY]], customParams = { }, energyMake = 0, explodeAs = [[NOWEAPON]], floater = true, footprintX = 4, footprintZ = 4, highTrajectory = 1, iconType = [[staticarty]], idleAutoHeal = 5, idleTime = 1800, levelGround = false, maxDamage = 1500, maxSlope = 36, maxVelocity = 0, maxWaterDepth = 20, noAutoFire = false, noChaseCategory = [[FIXEDWING LAND SHIP SATELLITE SWIM GUNSHIP SUB HOVER]], objectName = [[spire.s3o]], onoffable = true, power = 2500, reclaimable = false, selfDestructAs = [[NOWEAPON]], script = [[chickenspire.lua]], sfxtypes = { explosiongenerators = { [[custom:blood_spray]], [[custom:blood_explode]], [[custom:dirt]], }, }, sightDistance = 512, sonarDistance = 512, turnRate = 0, upright = false, useBuildingGroundDecal = true, yardMap = [[oooooooooooooooo]], weapons = { { def = [[SLAMSPORE]], badTargetCategory = [[MOBILE]], onlyTargetCategory = [[LAND SINK TURRET SHIP SWIM FLOAT HOVER]], }, }, weaponDefs = { SLAMSPORE = { name = [[Slammer Spore]], areaOfEffect = 160, avoidFriendly = false, collideFriendly = false, craterBoost = 1, craterMult = 2, customParams = { light_radius = 0, }, damage = { default = 1000, }, dance = 60, explosionGenerator = [[custom:large_green_goo]], fireStarter = 0, flightTime = 30, groundbounce = 1, heightmod = 0.5, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 2, model = [[chickenegggreen_big.s3o]], projectiles = 4, range = 6300, reloadtime = 14, smokeTrail = true, startVelocity = 40, texture1 = [[none]], texture2 = [[sporetrail2]], tolerance = 10000, tracks = true, trajectoryHeight = 2, turnRate = 10000, turret = true, waterweapon = true, weaponAcceleration = 40, weaponType = [[MissileLauncher]], weaponVelocity = 750, wobble = 24000, }, }, } }
gpl-2.0
Bew78LesellB/awesome
tests/test-drawable-bgimage.lua
12
1633
local runner = require("_runner") local wibox = require("wibox") local beautiful = require("beautiful") local cairo = require("lgi").cairo local w = wibox { x = 10, y = 10, width = 20, height = 20, visible = true, bg = "#ff0000", } local callback_called local function callback(context, cr, width, height, arg) assert(type(context) == "table", type(context)) assert(type(context.dpi) == "number", context.dpi) assert(cairo.Context:is_type_of(cr), cr) assert(width == 20, width) assert(height == 20, height) assert(arg == "argument: 42", arg) callback_called = true end runner.run_steps({ -- Set some bg image function() local img = assert(beautiful.titlebar_close_button_normal) w:set_bgimage(img) return true end, -- Do nothing for a while iteration to give the repaint some time to happen function(arg) if arg == 3 then return true end end, -- Set some bg image function function() w:set_bgimage(callback, "argument: 42") return true end, -- Wait for the function to be done function() if callback_called then return true end end, }) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
lxl1140989/dmsdk
feeds/luci/applications/luci-statistics/luasrc/model/cbi/luci_statistics/iwinfo.lua
78
1089
--[[ Luci configuration model for statistics - collectd interface plugin configuration (c) 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local m, s, o m = Map("luci_statistics", translate("Wireless iwinfo Plugin Configuration"), translate("The iwinfo plugin collects statistics about wireless signal strength, noise and quality.")) s = m:section(NamedSection, "collectd_iwinfo", "luci_statistics") o = s:option(Flag, "enable", translate("Enable this plugin")) o.default = 0 o = s:option(Value, "Interfaces", translate("Monitor interfaces"), translate("Leave unselected to automatically determine interfaces to monitor.")) o.template = "cbi/network_ifacelist" o.widget = "checkbox" o.nocreate = true o:depends("enable", 1) o = s:option(Flag, "IgnoreSelected", translate("Monitor all except specified")) o.default = 0 o:depends("enable", 1) return m
gpl-2.0
iamgreaser/iceball
pkg/rakiru/flamethrower/gun_flamethrower.lua
4
7945
--[[ This file is derived from a part of Ice Lua Components. Ice Lua Components is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Ice Lua Components is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Ice Lua Components. If not, see <http://www.gnu.org/licenses/>. ]] -- TODO: Sound effects local thisid = ... if client then wav_flamethrower_shots = { skin_load("wav", "flamethrower-shot1.wav", DIR_FLAMETHROWER), skin_load("wav", "flamethrower-shot2.wav", DIR_FLAMETHROWER), skin_load("wav", "flamethrower-shot3.wav", DIR_FLAMETHROWER) } weapon_models[thisid] = model_load({ kv6 = { bdir = DIR_FLAMETHROWER, name = "flamethrower.kv6", scale = 2.0/128.0, }, }, {"kv6"}) end weapon_names[thisid] = "Flamethrower" local flame_particles = nil if client then flame_particles = { new_particle_model(250, 34, 0), new_particle_model(250, 128, 0), new_particle_model(250, 167, 0), new_particle_model(250, 200, 0), new_particle_model(250, 230, 0), } end return function (plr) local this = tpl_gun(plr, { -- We're abusing this - it's not actually the hit part, but the number of parts hit dmg = { head = 2, body = 4, legs = 5, }, ammo_clip = 200, ammo_reserve = 400, time_fire = 0.05, time_reload = 5, pellet_count = 0, range = 9, spread = 0.5, -- We null out the recoil function call anyway, but just in case I overlook that when refactoring guns... recoil_x = 0, recoil_y = 0, model = client and (weapon_models[thisid] {}), name = weapon_names[thisid], }) this.burn_dmg = 4 this.burn_time = 5 this.burn_tick_time = 0.5 this.flame_particle_count = 32 local sound_delay = 0.1 local last_tick_time = 0 local last_sound_time = last_tick_time - sound_delay if client then this.flame_particles = flame_particles end if server then this.hits = {} end local s_click = this.click function this.click(button, state, ...) -- inhibit RMB if button == 1 then -- LMB return s_click(button, state, ...) end end function this.prv_fire(sec_current) local xlen, ylen, zlen xlen, ylen, zlen = common.map_get_dims() net_send(nil, common.net_pack("BBB", PKT_PLR_GUN_SHOT, 0, 1)) -- FIYAH if client then this.play_sound() this.spray_fire() end -- Check if anyone is in our firing cone local sya = math.sin(plr.angy) local cya = math.cos(plr.angy) local sxa = math.sin(plr.angx) local cxa = math.cos(plr.angx) local fwx,fwy,fwz fwx,fwy,fwz = sya*cxa, sxa, cya*cxa local spread_limit = 1 - (this.cfg.spread / 2) local distance_limit = this.cfg.range * this.cfg.range for i=1,players.max do local p = players[i] if p and p ~= plr and p.alive then local dx = p.x-plr.x local dy = p.y-plr.y+0.1 local dz = p.z-plr.z local hits = 0 for j=1,3 do -- Distance squared - no need to sqrt it for this local dist = dx * dx + dy * dy + dz * dz if dist <= distance_limit then -- Check if we hit based on angle between crosshair and player part local dxn, dyn, dzn = vnorm(dx, dy, dz) local dot = vdot(dxn, dyn, dzn, fwx, fwy, fwz) if dot >= spread_limit then -- Finally, check we're not hitting them through a wall or something local d,cx1,cy1,cz1,cx2,cy2,cz2 = trace_map_ray_dist(plr.x + sya * 0.4, plr.y, plr.z + cya * 0.4, fwx, fwy, fwz, this.cfg.range) d = d or this.cfg.range d = d * d if d == nil or dist < d then hits = hits + 1 end end end -- No real hitboxes, just offsets from the head position (what do you mean you're smaller when you crouch?) dy = dy + 1.0 end if hits > 0 then net_send(nil, common.net_pack("BBB", PKT_PLR_GUN_HIT, i, hits)) plr.show_hit() end end end -- apply recoil -- No recoil on flamethrower -- plr.recoil(sec_current, this.cfg.recoil_y, this.cfg.recoil_x) end function this.hit_player(hit_player, hit_area) local dmg = this.cfg.dmg[({"head","body","legs"})[hit_area]] if dmg then hit_player.wpn_damage(hit_area, dmg, plr, "roasted") end if not hit_player.inwater then if this.hits[hit_player] == nil then this.hits[hit_player] = { burn_end = 0, time_left = this.burn_tick_time, } end -- Reset the burn end time, so they still burn for this.burn_time once they stop getting hit this.hits[hit_player].burn_end = 0 end end local s_tick = this.tick function this.tick(sec_current, sec_delta, ...) -- We store time left and tick it down instead of next_tick because of the way we do burn_end, and the ticks shouldn't be reset when burn_end is -- TODO: Check if player is in water if server then -- Keep a list of players to remove after we're done iterating local to_remove = {} for burning_player,burn_data in pairs(this.hits) do -- The lack of continue makes this block slightly weird if not burning_player.alive or burning_player.inwater then table.insert(to_remove, burning_player) else if burn_data.burn_end == 0 then -- First burn tick - set end time burn_data.burn_end = sec_current + this.burn_time end if sec_current >= burn_data.burn_end then table.insert(to_remove, burning_player) else burn_data.time_left = burn_data.time_left - sec_delta if burn_data.time_left <= 0 then burning_player.wpn_damage(2, this.burn_dmg, plr, "toasted") -- 2 is body, but it isn't actually used in that function anymore/yet burn_data.time_left = burn_data.time_left + this.burn_tick_time end end end end -- Remove players that are no longer burning for i=1,table.getn(to_remove) do this.hits[to_remove[i]] = nil end end if client then last_tick_time = sec_current end return s_tick(sec_current, sec_delta, ...) end function this.remote_client_fire(fire_type) if client then this.play_sound() this.spray_fire() end end function this.spray_fire() local range = this.cfg.range * 0.7 -- TODO: Come out of gun - doesn't really work when the gun position derps around the place depending on vertical view angle for i=1,(this.flame_particle_count) do local angy = plr.angy + (this.cfg.spread * (math.random() - 0.5)) local angx = plr.angx + (this.cfg.spread * (math.random() - 0.5)) local sya = math.sin(angy) local cya = math.cos(angy) local sxa = math.sin(angx) local cxa = math.cos(angx) local fwx,fwy,fwz fwx,fwy,fwz = sya*cxa, sxa, cya*cxa -- Random speed/life, dependent on each other for equal travel distance local speed = math.random() + 0.5 local life = 2.5 - (speed * 0.7) particles_add(new_particle{ x = plr.x, y = plr.y + 0.35, z = plr.z, vx = fwx * range * speed, vy = fwy * range * speed, vz = fwz * range * speed, model = flame_particles[math.random(table.getn(flame_particles))], size = math.random(15, 50), lifetime = 0.015 * range * life -- Magic number that makes it last about the right amount of time for the effective range }) end end function this.play_sound() if last_tick_time > last_sound_time + sound_delay then local sound = wav_flamethrower_shots[math.random(#wav_flamethrower_shots)] client.wav_play_global(sound, plr.x, plr.y, plr.z) last_sound_time = last_tick_time end end return this end
gpl-3.0
ivendrov/nn
CMul.lua
24
3600
local CMul, parent = torch.class('nn.CMul', 'nn.Module') function CMul:__init(...) parent.__init(self) local arg = {...} self.size = torch.LongStorage() local n = #arg if n == 1 and torch.type(arg[1]) == 'torch.LongStorage' then self.size:resize(#arg[1]):copy(arg[1]) else self.size:resize(n) for i=1,n do self.size[i] = arg[i] end end self.weight = torch.Tensor(self.size) self.gradWeight = torch.Tensor(self.size) self.output:resize(self.size) self:reset() end function CMul:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:nElement()) end self.weight:uniform(-stdv,stdv) end function CMul:updateOutput(input) -- lazy-initialize self._output = self._output or input.new() self._weight = self._weight or input.new() self._expand = self._expand or input.new() self._repeat = self._repeat or input.new() self.output:resizeAs(input):copy(input) if input:nElement() == self.weight:nElement() then self._output:view(self.output, -1) self._weight:view(self.weight, -1) self._output:cmul(self._weight) else local batchSize = input:size(1) self._output:view(self.output, batchSize, -1) self._weight:view(self.weight, 1, -1) self._expand:expandAs(self._weight, self._output) if torch.type(input) == 'torch.CudaTensor' then self._repeat:resizeAs(self._expand):copy(self._expand) self._output:cmul(self._repeat) else self._output:cmul(self._expand) end end return self.output end function CMul:updateGradInput(input, gradOutput) if not self.gradInput then return end self._gradOutput = self._gradOutput or input.new() self._gradInput = self._gradInput or input.new() self.gradInput:resizeAs(input):zero() if self.weight:nElement() == gradOutput:nElement() then self.gradInput:addcmul(1, self.weight, gradOutput) else local batchSize = input:size(1) self._gradOutput:view(gradOutput, batchSize, -1) self._gradInput:view(self.gradInput, batchSize, -1) self._weight:view(self.weight, 1, -1) self._expand:expandAs(self._weight, self._gradOutput) if torch.type(input) == 'torch.CudaTensor' then self._repeat:resizeAs(self._expand):copy(self._expand) self._gradInput:addcmul(1, self._repeat, self._gradOutput) else self._gradInput:addcmul(1, self._expand, self._gradOutput) end end return self.gradInput end function CMul:accGradParameters(input, gradOutput, scale) scale = scale or 1 self._input = self._input or input.new() self._gradWeight = self._gradWeight or input.new() self._sum = self._sum or input.new() if self.weight:nElement() == gradOutput:nElement() then self.gradWeight:addcmul(scale, input, gradOutput) else local batchSize = input:size(1) self._input:view(input, batchSize, -1) self._gradOutput:view(gradOutput, batchSize, -1) self._gradWeight:view(self.gradWeight, 1, -1) self._repeat:cmul(self._input, self._gradOutput) self._sum:sum(self._repeat, 1) self._gradWeight:add(scale, self._sum) end end function CMul:type(type, tensorCache) if type then self._input = nil self._output = nil self._weight = nil self._gradWeight = nil self._expand = nil self._repeat = nil self._sum = nil end return parent.type(self, type, tensorCache) end
bsd-3-clause
iamgreaser/iceball
pkg/base/mode/obj_tent.lua
4
5077
--[[ This file is part of Ice Lua Components. Ice Lua Components is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Ice Lua Components is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Ice Lua Components. If not, see <http://www.gnu.org/licenses/>. ]] if client then mdl_tent = model_load({ kv6 = { bdir = DIR_PKG_KV6, name = "flagpole.kv6", scale = 1.0/16.0, }, pmf = { bdir = DIR_PKG_PMF, name = "tent.pmf", }, }, {"kv6", "pmf"}) end function new_tent(settings) local this = {} this.this = this this.type = "tent" this.team = settings.team or -1 this.iid = settings.iid this.mspr = mspr_tent function this.tick(sec_current, sec_delta) local i if not server then return end if not this.spawned then return end -- set position local l = common.map_pillar_get( math.floor(this.x), math.floor(this.z)) local ty = l[1+(1)] if this.y ~= ty and this.visible then this.y = ty net_broadcast(nil, common.net_pack("BHhhhB", PKT_ITEM_POS, this.iid, this.x, this.y, this.z, this.get_flags())) end -- see if anyone is restocking for i=1,players.max do local plr = players[i] if plr then local dx = plr.x-this.x local dy = (plr.y+2.4)-this.y local dz = plr.z-this.z local dd = dx*dx+dy*dy+dz*dz if dd > 2*2 then plr = nil end end if plr then this.player_in_range(plr, sec_current) end end end function this.player_in_range(plr, sec_current) local restock = false local i for i=1,#plr.tools do restock = restock or plr.tools[i].need_restock() end restock = restock or plr.health ~= 100 restock = restock or plr.blocks ~= 100 restock = restock and plr.alive restock = restock and plr.team == this.team if restock then plr.tent_restock() end end function this.should_glow() return (players[players.current].team == this.team and players[players.current].has_intel) end function this.render() if client.gfx_stencil_test and this.should_glow() then client.gfx_stencil_test(true) -- PASS 1: set to 1 for enlarged model if shader_white then shader_white.push() end client.gfx_depth_mask(false) client.gfx_stencil_func("0", 1, 255) client.gfx_stencil_op("===") this.mdl_tent_outline.render_global( this.x, this.y, this.z, this.rotpos, 0, 0, 3) client.gfx_depth_mask(true) if shader_white then shader_white.pop() end -- PASS 2: set to 0 for regular model if shader_world then shader_world.push() end client.gfx_stencil_func("1", 0, 255) client.gfx_stencil_op(";==") this.mdl_tent.render_global( this.x, this.y, this.z, this.rotpos, 0, 0, 3) if shader_world then shader_world.pop() end -- PASS 3: draw red for stencil == 1; clear stencil client.gfx_stencil_func("==", 1, 255) client.gfx_stencil_op("000") local iw, ih = common.img_get_dims(img_fsrect) client.img_blit(img_fsrect, 0, 0, iw, ih, 0, 0, 0x7FFFFFFF) client.gfx_stencil_test(false) else this.mdl_tent.render_global( this.x, this.y, this.z, 0, 0, 0, 3) end end function this.prespawn() this.alive = false this.spawned = false this.visible = false end local function prv_spawn_cont1() this.alive = true this.spawned = true this.visible = true end function this.spawn() local xlen,ylen,zlen xlen,ylen,zlen = common.map_get_dims() while true do this.x = math.floor(math.random()*xlen/4.0)+0.5 this.z = math.floor((math.random()*0.5+0.25)*zlen)+0.5 if this.team == 1 then this.x = xlen - this.x end this.y = (common.map_pillar_get(this.x, this.z))[1+1] if this.y < ylen-1 then break end end prv_spawn_cont1() end function this.spawn_at(x,y,z) this.x = x + 0.5 this.y = y this.z = z + 0.5 prv_spawn_cont1() end function this.get_pos() return this.x, this.y, this.z end function this.set_pos_recv(x,y,z) this.x = x + 0.5 this.y = y this.z = z + 0.5 end function this.get_flags() local v = 0 if this.visible then v = v + 0x01 end return v end function this.set_flags_recv(v) this.visible = (bit_and(v, 0x01) ~= 0) end local _ local l = (this.team and teams[this.team].color_mdl) or {170, 170, 170} this.color = l this.color_icon = (this.team and teams[this.team].color_chat) or {255,255,255} if client then this.mdl_tent = mdl_tent({filt=function (r,g,b) if r == 0 and g == 0 and b == 0 then return this.color[1], this.color[2], this.color[3] else return r,g,b end end}) this.mdl_tent_outline = mdl_tent({inscale=6.0}) end this.prespawn() return this end
gpl-3.0
LORgames/premake-core
modules/vstudio/tests/vc2010/test_item_def_group.lua
14
1930
-- -- tests/actions/vstudio/vc2010/test_item_def_group.lua -- Check the item definition groups, containing compile and link flags. -- Copyright (c) 2013 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vs2010_item_def_group") local vc2010 = p.vstudio.vc2010 local project = p.project -- -- Setup -- local wks, prj function suite.setup() p.action.set("vs2010") wks, prj = test.createWorkspace() end local function prepare(buildcfg) local cfg = test.getconfig(prj, buildcfg or "Debug") vc2010.itemDefinitionGroup(cfg) end -- -- Check generation of opening element for typical C++ project. -- function suite.structureIsCorrect_onDefaultValues() prepare() test.capture [[ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> ]] end -- -- Makefile projects omit the condition and all contents. -- function suite.structureIsCorrect_onMakefile() kind "Makefile" prepare() test.capture [[ <ItemDefinitionGroup> </ItemDefinitionGroup> ]] end function suite.structureIsCorrect_onNone() kind "Makefile" prepare() test.capture [[ <ItemDefinitionGroup> </ItemDefinitionGroup> ]] end -- -- Because the item definition group for makefile projects is not -- tied to a particular condition, it should only get written for -- the first configuration. -- function suite.skipped_onSubsequentConfigs() kind "Makefile" prepare("Release") test.isemptycapture() end function suite.skipped_onSubsequentConfigs_onNone() kind "None" prepare("Release") test.isemptycapture() end -- -- Utility projects include buildlog -- function suite.utilityIncludesPath() kind "Utility" buildlog "MyCustomLogFile.log" prepare() test.capture [[ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <BuildLog> <Path>MyCustomLogFile.log</Path> </BuildLog> </ItemDefinitionGroup> ]] end
bsd-3-clause
Anarchid/Zero-K
scripts/tankaa.lua
5
3020
include "constants.lua" include "trackControl.lua" include "pieceControl.lua" local base, turret, guns, aim = piece("base", "turret", "guns", "aim") local barrels = {piece("barrel1", "barrel2")} local flares = {piece("flare1", "flare2")} local a1, a2, neck = piece("a1", "a2", "neck") local currentGun = 1 local isAiming = false local disarmed = false local stuns = {false, false, false} local SIG_AIM = 1 local function RestoreAfterDelay() SetSignalMask (SIG_AIM) Sleep (5000) Turn (turret, y_axis, 0, 1) Turn ( guns, x_axis, 0, 1) WaitForTurn (turret, y_axis) WaitForTurn ( guns, x_axis) isAiming = false end local StopPieceTurn = GG.PieceControl.StopTurn function Stunned(stun_type) stuns[stun_type] = true disarmed = true Signal (SIG_AIM) StopPieceTurn(turret, y_axis) StopPieceTurn( guns, x_axis) end function Unstunned(stun_type) stuns[stun_type] = false if not stuns[1] and not stuns[2] and not stuns[3] then disarmed = false StartThread(RestoreAfterDelay) end end function script.StartMoving() StartThread(TrackControlStartMoving) end function script.StopMoving() TrackControlStopMoving() end function script.AimFromWeapon() return aim end function script.QueryWeapon() return flares[currentGun] end function script.AimWeapon(num, heading, pitch) Signal (SIG_AIM) SetSignalMask (SIG_AIM) isAiming = true while disarmed do Sleep (33) end local slowMult = (Spring.GetUnitRulesParam (unitID, "baseSpeedMult") or 1) Turn (turret, y_axis, heading, 10*slowMult) Turn ( guns, x_axis, -pitch, 10*slowMult) WaitForTurn (turret, y_axis) WaitForTurn ( guns, x_axis) StartThread (RestoreAfterDelay) return true end function script.FireWeapon() EmitSfx(flares[currentGun], 1024) local barrel = barrels[currentGun] Move (barrel, z_axis, -14) Move (barrel, z_axis, 0, 21) currentGun = 3 - currentGun end function script.Create() local trax = {piece("tracks1", "tracks2", "tracks3", "tracks4")} Show(trax[1]) -- in case current != 1 before luarules reload Hide(trax[2]) Hide(trax[3]) Hide(trax[4]) InitiailizeTrackControl({ wheels = { large = {piece('wheels1', 'wheels2', 'wheels3')}, small = {piece('wheels4', 'wheels5', 'wheels6')}, }, tracks = trax, signal = 2, smallSpeed = math.rad(360), smallAccel = math.rad(60), smallDecel = math.rad(120), largeSpeed = math.rad(540), largeAccel = math.rad(90), largeDecel = math.rad(180), trackPeriod = 50, }) StartThread (GG.Script.SmokeUnit, unitID, {base, turret, guns}) end local explodables = {a1, a2, neck, turret, barrels[1], barrels[2]} function script.Killed (recentDamage, maxHealth) local severity = recentDamage / maxHealth local brutal = severity > 0.5 local sfx = SFX local explodeFX = sfx.FALL + (brutal and (sfx.SMOKE + sfx.FIRE) or 0) local rand = math.random for i = 1, #explodables do if rand() < severity then Explode (explodables[i], explodeFX) end end if brutal then Explode(base, sfx.SHATTER) return 2 else return 1 end end
gpl-2.0
cstroie/Pip
bgnum.lua
1
2153
-- LCD big numbers and symbols lcd = require("lcd") local bgnum = {} function bgnum:cls() -- Wrapper lcd:cls() end function bgnum:define() -- Define the big digits if BIG_CHARS ~= "bgnum" then lcd:defchar(0, "1f1f1f0000000000") lcd:defchar(1, "00000000001f1f1f") lcd:defchar(2, "1f1f000000001f1f") lcd:defchar(3, "1f1f000000000000") lcd:defchar(4, "0000000000001f1f") lcd:defchar(5, "0000010303010000") lcd:defchar(6, "0000101818100000") lcd:defchar(7, "0000000000000000") BIG_CHARS = "bgnum" end end function bgnum:write(digit, col) -- Write the digit at 'col' if digit == "0" then lcd:bigwrite("\255\003\255", "\255\004\255", col) elseif digit == "1" then lcd:bigwrite("\000\255\032", "\001\255\001", col) elseif digit == "2" then lcd:bigwrite("\000\002\255", "\255\004\001", col) elseif digit == "3" then lcd:bigwrite("\000\002\255", "\001\004\255", col) elseif digit == "4" then lcd:bigwrite("\255\004\255", "\032\032\255", col) elseif digit == "5" then lcd:bigwrite("\255\002\000", "\001\004\255", col) elseif digit == "6" then lcd:bigwrite("\255\002\000", "\255\004\255", col) elseif digit == "7" then lcd:bigwrite("\000\003\255", "\032\032\255", col) elseif digit == "8" then lcd:bigwrite("\255\002\255", "\255\004\255", col) elseif digit == "9" then lcd:bigwrite("\255\002\255", "\001\004\255", col) elseif digit == "C" then lcd:bigwrite("\255\003\000", "\255\004\001", col) elseif digit == "-" then lcd:bigwrite("\032\001\001", "\032\032\032", col) elseif digit == " " then lcd:bigwrite("\032\032\032", "\032\032\032", col) elseif digit == ":" then lcd:bigwrite("\005\006", "\005\006", col) elseif digit == "." then lcd:bigwrite("\032\032", "\005\006", col) elseif digit == "'" then lcd:bigwrite("\005\006", "\032\032", col) elseif digit == "%" then lcd:bigwrite("\005\006\001\000", "\001\000\005\006", col) end end function bgnum:bigwrite(text, cols) -- Write the text, big, at columns 'cols' for idx,col in ipairs(cols) do self:write(text:sub(idx, idx), col) end end return bgnum -- vim: set ft=lua ai ts=2 sts=2 et sw=2 sta nowrap nu :
gpl-3.0
dglynch/PremadeRoleMonitor
PremadeRoleMonitor.lua
1
9587
--[[ Copyright 2013 Dan Lynch This file is part of Premade Role Monitor. Premade Role Monitor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses>. This program is designed specifically to work with the World of Warcraft client. Therefore, if you modify this program, or any covered work, by linking or combining it with the World of Warcraft client (or a modified version of that client), you have permission to convey the resulting work. --]] local MAX_ROWS = 25; local SORT_ORDER = { -- a sensible order in which to sort players based on role(s) chosen INLINE_TANK_ICON, INLINE_TANK_ICON .. INLINE_DAMAGER_ICON, INLINE_TANK_ICON .. INLINE_HEALER_ICON .. INLINE_DAMAGER_ICON, INLINE_TANK_ICON .. INLINE_HEALER_ICON, INLINE_HEALER_ICON, INLINE_HEALER_ICON .. INLINE_DAMAGER_ICON, INLINE_DAMAGER_ICON, "" }; local PLAYERS_PER_ROLE_LFR = { [INLINE_TANK_ICON] = 2, [INLINE_HEALER_ICON] = 6, [INLINE_DAMAGER_ICON] = 17 }; local TOTAL_PLAYERS_LFR = 25; local active = false; -- are we currently updating role choices? local data = {}; local function prepareForReset() -- the next role choice we receive will force a reset of the data because -- it represents the start of a new role selection process active = false; end local function redrawFrame() if (active) then local rowIndex = 1; local tankOnlyCount = 0; local healerOnlyCount = 0; local damagerOnlyCount = 0; local nonTankCount = 0; local nonHealerCount = 0; local nonDamagerCount = 0; for i = 1, #SORT_ORDER do for name, rolesChosen in pairs(data) do if (rolesChosen == SORT_ORDER[i]) then local rowFrame = _G["PremadeRoleMonitorRow" .. rowIndex]; if (rowFrame == nil) then -- don't try to write to a non-existent row break; end rowFrame.name.text:SetText(name); rowFrame.name.name = name; rowFrame.chosenRoles:SetText(rolesChosen); rowFrame:Show(); rowIndex = rowIndex + 1; if (rolesChosen ~= "") then if (rolesChosen == INLINE_TANK_ICON) then tankOnlyCount = tankOnlyCount + 1; elseif (rolesChosen == INLINE_HEALER_ICON) then healerOnlyCount = healerOnlyCount + 1; elseif (rolesChosen == INLINE_DAMAGER_ICON) then damagerOnlyCount = damagerOnlyCount + 1; end if (not(string.find(rolesChosen, INLINE_TANK_ICON, 1, true))) then nonTankCount = nonTankCount + 1; end if (not(string.find(rolesChosen, INLINE_HEALER_ICON, 1, true))) then nonHealerCount = nonHealerCount + 1; end if (not(string.find(rolesChosen, INLINE_DAMAGER_ICON, 1, true))) then nonDamagerCount = nonDamagerCount + 1; end end end end end while (rowIndex <= MAX_ROWS) do -- blank the remaining rows local rowFrame = _G["PremadeRoleMonitorRow" .. rowIndex]; rowFrame.name.text:SetText(name); rowFrame.name.name = name; rowFrame.chosenRoles:SetText(rolesChosen); rowFrame:Show(); rowIndex = rowIndex + 1; end if (nonDamagerCount > TOTAL_PLAYERS_LFR - PLAYERS_PER_ROLE_LFR[INLINE_DAMAGER_ICON]) then PremadeRoleMonitorFrameWarning:SetText( "Too many non-" .. INLINE_DAMAGER_ICON); end if (nonHealerCount > TOTAL_PLAYERS_LFR - PLAYERS_PER_ROLE_LFR[INLINE_HEALER_ICON]) then PremadeRoleMonitorFrameWarning:SetText( "Too many non-" .. INLINE_HEALER_ICON); end if (nonTankCount > TOTAL_PLAYERS_LFR - PLAYERS_PER_ROLE_LFR[INLINE_TANK_ICON]) then PremadeRoleMonitorFrameWarning:SetText( "Too many non-" .. INLINE_TANK_ICON); end if (damagerOnlyCount > PLAYERS_PER_ROLE_LFR[INLINE_DAMAGER_ICON]) then PremadeRoleMonitorFrameWarning:SetText( "Too many " .. INLINE_DAMAGER_ICON .. "-only"); end if (healerOnlyCount > PLAYERS_PER_ROLE_LFR[INLINE_HEALER_ICON]) then PremadeRoleMonitorFrameWarning:SetText( "Too many " .. INLINE_HEALER_ICON .. "-only"); end if (tankOnlyCount > PLAYERS_PER_ROLE_LFR[INLINE_TANK_ICON]) then PremadeRoleMonitorFrameWarning:SetText( "Too many " .. INLINE_TANK_ICON .. "-only"); end PremadeRoleMonitorFrame:Show(); end end local function processChatMsgSystem(message) if (message == ERR_LFG_ROLE_CHECK_ABORTED) then prepareForReset(); elseif (message == ERR_LFG_ROLE_CHECK_FAILED) then prepareForReset(); elseif (message == ERR_LFG_ROLE_CHECK_FAILED_TIMEOUT) then prepareForReset(); elseif (message == ERR_LFG_ROLE_CHECK_FAILED_NOT_VIABLE) then prepareForReset(); elseif (message == ERR_LFG_JOINED_QUEUE) then prepareForReset(); elseif (message == ERR_LFG_JOINED_RF_QUEUE) then prepareForReset(); elseif (message == ERR_LFG_JOINED_SCENARIO_QUEUE) then prepareForReset(); elseif (message == ERR_LFG_LEFT_QUEUE) then prepareForReset(); elseif (message == ERR_LFG_PROPOSAL_DECLINED_PARTY) then prepareForReset(); elseif (message == ERR_LFG_PROPOSAL_DECLINED_SELF) then prepareForReset(); elseif (message == ERR_LFG_PROPOSAL_FAILED) then prepareForReset(); end end local function processGroupRosterUpdate() if (active) then local numGroupMembers = GetNumGroupMembers(); if (numGroupMembers > 1) then local raidMembers = {}; -- add all new raid members to the data structure for raidIndex = 1, numGroupMembers do local name = GetRaidRosterInfo(raidIndex); raidMembers[name] = true; if (data[name] == nil) then data[name] = ""; end end -- remove all former raid members from the data structure for name, _ in pairs(data) do if (raidMembers[name] == nil) then data[name] = nil; end end else -- we are not in a party or raid group prepareForReset(); end end end local function processRoleCheckRoleChosen(player, isTank, isHealer, isDamage) if (active == false) then -- this is a new role selection process so reset the data structure data = {}; PremadeRoleMonitorFrameWarning:SetText(""); active = true; processGroupRosterUpdate(); end local rolesChosen = ""; if (isTank) then rolesChosen = rolesChosen .. INLINE_TANK_ICON; end if (isHealer) then rolesChosen = rolesChosen .. INLINE_HEALER_ICON; end if (isDamage) then rolesChosen = rolesChosen .. INLINE_DAMAGER_ICON; end if (data[player] == nil) then -- this is a cross-realm player so we have to guess who it is for name, rc in pairs(data) do if (string.find(name, player, 1, true) == 1 and rc == "") then -- this is probably the right character player = name; break; end end end data[player] = rolesChosen; end function PremadeRoleMonitorFrame_OnLoad(self) self:RegisterEvent("LFG_ROLE_CHECK_ROLE_CHOSEN"); self:RegisterEvent("GROUP_ROSTER_UPDATE"); self:RegisterEvent("CHAT_MSG_SYSTEM"); local prevRowFrame = PremadeRoleMonitorRow1; for i = 2, MAX_ROWS do local rowFrame = CreateFrame("FRAME", "PremadeRoleMonitorRow" .. i, PremadeRoleMonitorFrame, "PremadeRoleMonitorRowTemplate"); rowFrame:SetPoint("TOPLEFT", prevRowFrame, "BOTTOMLEFT", 0, 0); rowFrame:SetPoint("TOPRIGHT", prevRowFrame, "BOTTOMRIGHT", 0, 0); prevRowFrame = rowFrame; end redrawFrame(); end function PremadeRoleMonitorFrame_OnEvent(self, event, ...) if (event == "LFG_ROLE_CHECK_ROLE_CHOSEN") then processRoleCheckRoleChosen(...); elseif (event == "GROUP_ROSTER_UPDATE") then processGroupRosterUpdate(); elseif (event == "CHAT_MSG_SYSTEM") then processChatMsgSystem(...); end redrawFrame(); end
gpl-3.0
Ractis/HookAndSlice
scripts/vscripts/DotaHS_MissionManager_RescueHostage.lua
1
11246
require( "DotaHS_Common" ) require( "DotaHS_Quest" ) require( "DotaHS_SpawnManager" ) require( "DotaHS_SpawnDirector" ) -------------------------------------------------------------------------------- if MissionManager_RescueHostage == nil then MissionManager_RescueHostage = class({}) MissionManager_RescueHostage.DeltaTime = 1.0 end -------------------------------------------------------------------------------- -- Pre-Initialize -------------------------------------------------------------------------------- function MissionManager_RescueHostage:PreInitialize() -- Inspect the map self._vHostageSpawnEntAry = self:_FindHostageSpawnEntities() -- Quests self._questReleasedHostages = CreateQuest( "ReleasedHostages" ) self._subquestReleasedHostages = CreateSubquestOf( self._questReleasedHostages ) Subquest_UpdateValue( self._subquestReleasedHostages, 0, 1 ) self._questEscapedHostages = CreateQuest( "EscapedHostages" ) self._subquestEscapedHostages = CreateSubquestOf( self._questEscapedHostages ) Subquest_UpdateValue( self._subquestEscapedHostages, 0, 1 ) -- CreateTimer DotaHS_CreateThink( "MissionManager_RescueHostage:OnUpdate", function () self:OnUpdate() return MissionManager_RescueHostage.DeltaTime end ) -- Register game event listeners ListenToGameEvent( 'entity_killed', Dynamic_Wrap(MissionManager_RescueHostage, "OnEntityKilled"), self ) end -------------------------------------------------------------------------------- -- Initialize -------------------------------------------------------------------------------- function MissionManager_RescueHostage:Initialize( kv ) self.vHostages = {} -- Array of hostage entities self.vHostagesArrested = {} -- Array of arrested hostage entities self.vHostagesReleasedOnce = {} -- Array of hostages that have been released at least once self.vPlayerPosition = {} -- PlayerID : PlayerPosition self.vPlayerHostages = {} -- PlayerID : [Array of Hostage entity] self.nTotalHostages = 1 self.nHostagesRemaining = 1 self.nHostagesReleasedOnce = 0 -- Num of hostages thas have been released at least once -- Spawn Hostages local numHostagesToSpawn = DotaHS_GetDifficultyValue( kv.NumHostages ) self:_RegisterHostages( self:_SpawnHostages( {unpack(self._vHostageSpawnEntAry)}, numHostagesToSpawn ) ) -- Dynamic values self.vChangeMonsterPool = kv.ChangeMonsterPool self.vChangeHordeIntervalReduction = kv.ChangeHordeIntervalReduction end -------------------------------------------------------------------------------- -- Finalize -------------------------------------------------------------------------------- function MissionManager_RescueHostage:Finalize() -- Clean up hostages for _,hostage in pairs( self.vHostages ) do if not hostage:IsNull() and hostage:IsAlive() then UTIL_RemoveImmediate( hostage ) end end self.vHostages = {} end -------------------------------------------------------------------------------- function MissionManager_RescueHostage:_RegisterHostages( vHostages ) self.vHostages = vHostages self.vHostagesArrested = {unpack(vHostages)} for k,hostage in pairs( vHostages ) do hostage.DotaHS_IsHostage = true hostage.DotaHS_HostageID = k hostage:FindAbilityByName( "dotahs_hostage_default" ):SetLevel(1) hostage:FindAbilityByName( "dotahs_hostage_arrested" ):SetLevel(1) hostage:FindAbilityByName( "dotahs_hostage_arrested" ):ToggleAbility() if not hostage:FindAbilityByName( "dotahs_hostage_arrested" ):GetToggleState() then self:_Log( "ARRESTED modifier is OFF !!" ) end end self.nTotalHostages = #vHostages self.nHostagesRemaining = #vHostages self:_Log( "Registered hostages : Num = " .. #vHostages ) self:_UpdateQuest() end -------------------------------------------------------------------------------- function MissionManager_RescueHostage:UpdatePlayersPosition( vPlayerPosition ) self.vPlayerPosition = vPlayerPosition end -------------------------------------------------------------------------------- function MissionManager_RescueHostage:OnUpdate() if not DotaHS_GlobalVars.bGameInProgress then return end -- Check to release arrested hostages for k,hostage in pairs( self.vHostagesArrested ) do local hostagePos = hostage:GetAbsOrigin() local hostageID = hostage.DotaHS_HostageID for playerID, playerPos in pairs( self.vPlayerPosition ) do local playerHero = DotaHS_PlayerIDToHeroEntity( playerID ) local dist = ( hostagePos - playerPos ):Length2D() if dist < 300 and playerHero:IsAlive() then self:_Log( "A hostage has been released." ) self:_Log( " Hostage ID = " .. hostageID ) self:_Log( " Player ID = " .. playerID ) -- Hostage has been released by the player hostage:FindAbilityByName( "dotahs_hostage_arrested" ):ToggleAbility() if hostage:FindAbilityByName( "dotahs_hostage_arrested" ):GetToggleState() then self:_Log( "ARRESTED modifier is ON !!" ) end -- Follow the player local hostagesFollowPlayer = self.vPlayerHostages[playerID] local target if hostagesFollowPlayer and #hostagesFollowPlayer > 0 then -- Already some hostages are following the player. target = hostagesFollowPlayer[#hostagesFollowPlayer] -- Get the tail hostage else -- Follow the player self.vPlayerHostages[playerID] = {} target = playerHero end -- Add to hostage list of the player table.insert( self.vPlayerHostages[playerID], hostage ) -- Execute follow command local order = { OrderType = DOTA_UNIT_ORDER_MOVE_TO_TARGET, UnitIndex = hostage:entindex(), TargetIndex = target:entindex(), } ExecuteOrderFromTable( order ) -- Remove from arrested hostage list table.remove( self.vHostagesArrested, k ) self:_UpdateQuest() -- Add to released hostage list if not self.vHostagesReleasedOnce[hostageID] then self.vHostagesReleasedOnce[hostageID] = hostage self.nHostagesReleasedOnce = self.nHostagesReleasedOnce + 1 self:_OnUpdateHostagesReleasedOnce() end break -- IMPORTANT!!! end end end -- Re-follow to the player for playerID,hostagesFollowPlayer in pairs( self.vPlayerHostages ) do if #hostagesFollowPlayer > 0 then -- Execute follow command local order = { OrderType = DOTA_UNIT_ORDER_MOVE_TO_TARGET, UnitIndex = hostagesFollowPlayer[1]:entindex(), TargetIndex = DotaHS_PlayerIDToHeroEntity( playerID ):entindex(), } ExecuteOrderFromTable( order ) end end -- Check to complete the rescue local nHostagesRemainingCurrent = 0 for k,hostage in pairs( self.vHostages ) do -- Is not escaped? if not hostage.DotaHS_IsEscaped then nHostagesRemainingCurrent = nHostagesRemainingCurrent + 1 end end if nHostagesRemainingCurrent ~= self.nHostagesRemaining then self.nHostagesRemaining = nHostagesRemainingCurrent self:_UpdateQuest() self:_Log( self.nHostagesRemaining .. " hostages remaining." ) end -- Complete mission if self.nHostagesRemaining <= 0 then -- self._questEscapedHostages:CompleteQuest() DotaHS_GlobalVars.bVictory = true end end -------------------------------------------------------------------------------- function MissionManager_RescueHostage:_OnUpdateHostagesReleasedOnce() self:_Log( self.nHostagesReleasedOnce .. " hostages have been released at least once." ) -- Change the monster pool if self.vChangeMonsterPool then local list = self.vChangeMonsterPool[tostring(self.nHostagesReleasedOnce)] if list then for original, new in pairs( list ) do SpawnManager:ChangeMonsterPool( original, new ) end end end -- Change horde interval if self.vChangeHordeIntervalReduction then local reduction = self.vChangeHordeIntervalReduction[tostring(self.nHostagesReleasedOnce)] if reduction then SpawnDirector:SetHordeIntervalReduction( tonumber(reduction) / 100 ) end end end -------------------------------------------------------------------------------- function MissionManager_RescueHostage:OnEntityKilled( event ) local killedUnit = EntIndexToHScript( event.entindex_killed ) if not killedUnit then return end if killedUnit:IsRealHero() then local playerID = DotaHS_HeroEntityToPlayerID( killedUnit ) -- Check following hostages local hostagesFollowPlayer = self.vPlayerHostages[playerID] if hostagesFollowPlayer and #hostagesFollowPlayer > 0 then -- Re-arrest the hostages for _,hostage in ipairs( hostagesFollowPlayer ) do self:_Log( "A hostage has been arrested." ) self:_Log( " Hostage ID = " .. hostage.DotaHS_HostageID ) self:_Log( " Player ID = " .. playerID ) hostage:FindAbilityByName( "dotahs_hostage_arrested" ):ToggleAbility() if not hostage:FindAbilityByName( "dotahs_hostage_arrested" ):GetToggleState() then self:_Log( "ARRESTED modifier is OFF !!" ) end -- Add to arrested hostage list table.insert( self.vHostagesArrested, hostage ) end -- Remove the list self.vPlayerHostages[playerID] = nil self:_UpdateQuest() end end end -------------------------------------------------------------------------------- function MissionManager_RescueHostage:_FindHostageSpawnEntities() -- Collect pool entities in the map local hostageSpawnEntAry = {} for _,v in pairs(Entities:FindAllByClassname( "info_target" )) do local entName = v:GetName() if string.find( entName, "hostage_spawn" ) == 1 then table.insert( hostageSpawnEntAry, v ) end end return hostageSpawnEntAry end -------------------------------------------------------------------------------- function MissionManager_RescueHostage:_SpawnHostages( hostageSpawnEntAry, numHostagesToSpawn ) local vHostages = {} if #hostageSpawnEntAry < numHostagesToSpawn then self:_Log( "Spawners for hostages are too few!" ) self:_Log( " Num Spawners : " .. #hostageSpawnEntAry ) self:_Log( " Num Hostages : " .. numHostagesToSpawn ) return {} end for i=1, numHostagesToSpawn do -- Choose a spawner local spawnerID = RandomInt( 1, #hostageSpawnEntAry ) local spawnerEnt = hostageSpawnEntAry[spawnerID] table.remove( hostageSpawnEntAry, spawnerID ) -- Spawn a hostage local hostage = CreateUnitByName( "npc_dotahs_hostage", spawnerEnt:GetAbsOrigin(), true, nil, nil, DOTA_TEAM_GOODGUYS ) hostage:SetAngles( 0, RandomFloat( 0, 360 ), 0 ) table.insert( vHostages, hostage ) end return vHostages end -------------------------------------------------------------------------------- function MissionManager_RescueHostage:_UpdateQuest() local releasedHostages = self.nTotalHostages - #self.vHostagesArrested Quest_UpdateValue( self._questReleasedHostages, releasedHostages, self.nTotalHostages ) Subquest_UpdateValue( self._subquestReleasedHostages, releasedHostages, self.nTotalHostages ) local escapedHostages = self.nTotalHostages - self.nHostagesRemaining Quest_UpdateValue( self._questEscapedHostages, escapedHostages, self.nTotalHostages ) Subquest_UpdateValue( self._subquestEscapedHostages, escapedHostages, self.nTotalHostages ) end -------------------------------------------------------------------------------- function MissionManager_RescueHostage:_Log( text ) print( "[Mission/RescueHostage] " .. text ) end
mit
Em30-tm-lua/team
plugins/rules.lua
28
2270
-------------------------------------------------- -- ____ ____ _____ -- -- | \| _ )_ _|___ ____ __ __ -- -- | |_ ) _ \ | |/ ·__| _ \_| \/ | -- -- |____/|____/ |_|\____/\_____|_/\/\_| -- -- -- -------------------------------------------------- -- -- -- Developers: @Josepdal & @MaSkAoS -- -- Support: @Skneos, @iicc1 & @serx666 -- -- -- -- Created by @Josepdal & @A7F -- -- -- -------------------------------------------------- local function set_rules_channel(msg, text) local rules = text local hash = 'channel:id:'..msg.to.id..':rules' redis:set(hash, rules) end local function del_rules_channel(chat_id) local hash = 'channel:id:'..chat_id..':rules' redis:del(hash) end local function init_def_rules(chat_id) local rules = 'ℹ️ Rules:\n' ..'1⃣ No Flood.\n' ..'2⃣ No Spam.\n' ..'3⃣ Try to stay on topic.\n' ..'4⃣ Forbidden any racist, sexual, homophobic or gore content.\n' ..'➡️ Repeated failure to comply with these rules will cause ban.' local hash='channel:id:'..chat_id..':rules' redis:set(hash, rules) end local function ret_rules_channel(msg) local chat_id = msg.to.id local hash = 'channel:id:'..msg.to.id..':rules' if redis:get(hash) then return redis:get(hash) else init_def_rules(chat_id) return redis:get(hash) end end local function run(msg, matches) if matches[1] == 'rules' then return ret_rules_channel(msg) elseif matches[1] == 'setrules' then if permissions(msg.from.id, msg.to.id, 'rules') then set_rules_channel(msg, matches[2]) return 'ℹ️ '..lang_text(msg.to.id, 'setRules') end elseif matches[1] == 'remrules' then if permissions(msg.from.id, msg.to.id, 'rules') then del_rules_channel(msg.to.id) return 'ℹ️ '..lang_text(msg.to.id, 'remRules') end end end return { patterns = { '^#(rules)$', '^#(setrules) (.+)$', '^#(remrules)$' }, run = run }
gpl-2.0
Mutos/SoC-Test-001
dat/events/neutral/shipwreck.lua
11
2074
--[[ -- Shipwreck Event -- -- Creates a wrecked ship that asks for help. If the player boards it, the event switches to the Space Family mission. -- See dat/missions/neutral/spacefamily.lua -- -- 12/02/2010 - Added visibility/highlight options for use in bigsystems (Anatolis) --]] lang = naev.lang() if lang == "es" then -- not translated atm else -- default english -- Text broadcastmsg = "SOS. This is %s. We are shipwrecked. Requesting immediate assistance." shipname = "August" --The ship will have a unique name end function create () -- The shipwrech will be a random trader vessel. r = rnd.rnd() if r > 0.95 then ship = "Trader Gawain" elseif r > 0.8 then ship = "Trader Mule" elseif r > 0.5 then ship = "Trader Koala" else ship = "Trader Llama" end -- Create the derelict. angle = rnd.rnd() * 2 * math.pi dist = rnd.rnd(2000, 3000) -- place it a ways out pos = vec2.new( dist * math.cos(angle), dist * math.sin(angle) ) p = pilot.add(ship, "dummy", pos) for k,v in ipairs(p) do v:setFaction("Derelict") v:disable() v:rename("Shipwrecked " .. shipname) -- Added extra visibility for big systems (A.) v:setVisplayer( true ) v:setHilight( true ) end hook.timer(3000, "broadcast") -- Set hooks hook.pilot( p[1], "board", "rescue" ) hook.pilot( p[1], "death", "destroyevent" ) hook.enter("endevent") hook.land("endevent") end function broadcast() -- Ship broadcasts an SOS every 10 seconds, until boarded or destroyed. if not p[1]:exists() then return end p[1]:broadcast( string.format(broadcastmsg, shipname), true ) bctimer = hook.timer(15000, "broadcast") end function rescue() -- Player boards the shipwreck and rescues the crew, this spawns a new mission. hook.rm(bctimer) naev.missionStart("The Space Family") evt.finish(true) end function destroyevent () evt.finish(true) end function endevent () evt.finish() end
gpl-3.0
Whit3Tig3R/bestspammbot2
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
satanevil/eski-creed
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
Sewerbird/blooming-suns
src_old/logic/mutate/MoveSelectionMutator.lua
1
1290
MoveSelectionMutator = {} MoveSelectionMutator.new = function (init) local init = init or {} local self = Mutator.new(init) self.units = init.units --units self.src = init.src --hex self.dst = init.dst --hex self.map = init.map --tilemap self.execute = function (state) local map = state.getTilemap(self.map) for i, unit in self.units do local mover = map.getHexAtIdx(self.src).getStack().getUnit(unit) local move_cost = map.terrain_connective_matrix[self.dst]['mpcost'][mover.move_method] mover.curr_movepoints = math.max(mover.curr_movepoints - (move_cost or 1), 0) local moved = map.getHexAtIdx[self.src].delocateUnit(unit) moved.location = self.dst map.getHexAtIdx[self.dst].relocateUnit(moved) end end self.undo = function (state) for i, unit in self.units do local mover = self.map.getHexAtIdx(self.dst).getStack().getUnit(unit) local move_cost = self.map.terrain_connective_matrix[self.dst]['mpcost'][mover.move_method] mover.curr_movepoints = math.max(mover.curr_movepoints + (move_cost or 1), 0) local moved = self.map.getHexAtIdx(self.dst).delocateUnit(mover) moved.location = self.src self.map.getHexAtIdx(self.sr).relocateUnit(moved) end end return self end
gpl-3.0
lxl1140989/dmsdk
feeds/packages/net/luci-app-ocserv/files/usr/lib/lua/luci/controller/ocserv.lua
15
2075
--[[ LuCI - Lua Configuration Interface Copyright 2014 Nikos Mavrogiannopoulos <n.mavrogiannopoulos@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.ocserv", package.seeall) function index() if not nixio.fs.access("/etc/config/ocserv") then return end local page page = entry({"admin", "services", "ocserv"}, alias("admin", "services", "ocserv", "main"), _("OpenConnect VPN")) page.dependent = true page = entry({"admin", "services", "ocserv", "main"}, cbi("ocserv/main"), _("Server Settings"), 200) page.dependent = true page = entry({"admin", "services", "ocserv", "users"}, cbi("ocserv/users"), _("User Settings"), 300) page.dependent = true entry({"admin", "services", "ocserv", "status"}, call("ocserv_status")).leaf = true entry({"admin", "services", "ocserv", "disconnect"}, call("ocserv_disconnect")).leaf = true end function ocserv_status() local ipt = io.popen("/usr/bin/occtl show users"); if ipt then local fwd = { } while true do local ln = ipt:read("*l") if not ln then break end local id, user, group, vpn_ip, ip, device, time, cipher, status = ln:match("^%s*(%d+)%s+([-_%w]+)%s+([%.%*-_%w]+)%s+([%:%.-_%w]+)%s+([%:%.-_%w]+)%s+([%:%.-_%w]+)%s+([%:%.-_%w]+)%s+([%:%.-_%w]+)%s+([%:%.-_%w]+).*") if id then fwd[#fwd+1] = { id = id, user = user, group = group, vpn_ip = vpn_ip, ip = ip, device = device, time = time, cipher = cipher, status = status } end end ipt:close() luci.http.prepare_content("application/json") luci.http.write_json(fwd) end end function ocserv_disconnect(num) local idx = tonumber(num) local uci = luci.model.uci.cursor() if idx and idx > 0 then luci.sys.call("/usr/bin/occtl disconnect id %d" % idx) luci.http.status(200, "OK") return end luci.http.status(400, "Bad request") end
gpl-2.0
b1v1r/ironbee
lua/example.lua
2
10838
-- ========================================================================= -- ========================================================================= -- Licensed to Qualys, Inc. (QUALYS) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- QUALYS 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. -- ========================================================================= -- ========================================================================= -- -- This is an example IronBee lua module. Essentially, this code is -- executed on load, allowing the developer to register other functions -- to get called when states fire at runtime. -- -- This example just registers a logging function for most states as well -- as a more complex function to execute when the request headers are -- ready to process. -- -- Author: Sam Baskinger <sbaskinger@qualys.com> -- Author: Brian Rectanus <brectanus@qualys.com> -- ========================================================================= -- =============================================== -- Get an IronBee module object, which is passed -- into the loading module as a parameter. This -- is used to access the IronBee Lua API. -- =============================================== local ibmod = ... -- =============================================== -- Register an IronBee configuration file -- directive that takes a single string parameter: -- -- LuaExampleDirective <string> -- =============================================== ibmod:register_param1_directive( "LuaExampleDirective", function(ib_module, module_config, name, param1) -- Log that we're configuring the module. ibmod:logInfo("Got directive %s=%s", name, param1) -- Configuration, in this case, is simply storing the string. module_config[name] = param1 end ) -- =============================================== -- Generic function to log an info message when -- an states fires. -- =============================================== local log_state = function(ib, state) ib:logInfo( "Handling state=%s: LuaExampleDirective=%s", ib.state_name, ib.config["LuaExampleDirective"]) return 0 end -- =============================================== -- This is called when a connection is started. -- =============================================== ibmod:conn_started_state(log_state) -- =============================================== -- This is called when a connection is opened. -- =============================================== ibmod:conn_opened_state(log_state) -- =============================================== -- This is called when a connection context was -- chosen and is ready to be handled. -- =============================================== ibmod:handle_context_conn_state(log_state) -- =============================================== -- This is called when the connection is ready to -- be handled. -- =============================================== ibmod:handle_connect_state(log_state) -- =============================================== -- This is called when the transaction starts. -- =============================================== ibmod:tx_started_state(log_state) -- =============================================== -- This is called when a request starts. -- =============================================== ibmod:request_started_state(log_state) -- =============================================== -- This is called when the transaction context -- is ready to be handled. -- =============================================== ibmod:handle_context_tx_state(log_state) -- =============================================== -- This is called when there is new request -- header data. -- =============================================== ibmod:request_header_data_state(log_state) -- =============================================== -- This is called when the request header data -- has all been received. -- =============================================== ibmod:request_header_finished_state(log_state) -- =============================================== -- This is called when the request headers are -- available to inspect. -- =============================================== ibmod:handle_request_header_state( function(ib) log_state(ib) -- You can get named fields. Scalar fields -- will return scalar values. local req_line = ib:get("request_line") ib:logInfo("REQUEST_LINE: %s=%s", type(req_line), tostring(req_line)) -- You can fetch collections as a table of name/value pairs: local req_headers = ib:get("request_headers") if type(req_headers) == 'table' then -- Loop over the key/field for k,f in pairs(req_headers) do if type(f) == 'table' then -- Fields come as (tables), which you can -- unpack into simple name/value pairs. -- -- TODO: Need to make this a bit cleaner name, val = unpack(f) ib:logInfo("REQUEST_HEADERS:%s=%s", tostring(name), tostring(val)) else ib:logInfo("REQUEST_HEADERS:%s=%s", k, f) end end end -- You can access individual subfields within collections directly -- via "name:subname" syntax, but these will come as a list -- of values (as more than one subname is always allowed): local http_host_header = ib:getValues("request_headers:host") ib:logInfo("First HTTP Host Header: %s", http_host_header[1]) -- Request cookies are a collection (table of field objects) -- similar to headers: local req_cookies = ib:get("request_cookies") if type(req_cookies) == 'table' then -- Loop over the key/field for k,f in pairs(req_cookies) do if type(f) == 'table' then -- Fields come as (tables), which you can -- unpack into simple name/value pairs. -- -- TODO: Need to make this a bit cleaner name, val = unpack(f) ib:logInfo("REQUEST_COOKIES:%s=%s", tostring(name), tostring(val)) else ib:logInfo("REQUEST_COOKIES:%s=%s", k, f) end end end return 0 end ) -- =============================================== -- This is called when the request body is -- available. -- =============================================== ibmod:request_body_data_state(log_state) -- =============================================== -- This is called when the complete request is -- ready to be handled. -- =============================================== ibmod:handle_request_state(log_state) -- =============================================== -- This is called when the request is finished. -- =============================================== ibmod:request_finished_state(log_state) -- =============================================== -- This is called when the transaction is ready -- to be processed. -- =============================================== ibmod:tx_process_state(log_state) -- =============================================== -- This is called when the response is started. -- =============================================== ibmod:response_started_state(log_state) -- =============================================== -- This is called when the response headers are -- available. -- =============================================== ibmod:handle_response_header_state(log_state) -- =============================================== -- This is called when the response headers are -- ready to be handled. -- =============================================== ibmod:response_header_data_state(log_state) -- =============================================== -- This is called when the response header data -- has all been received. -- =============================================== ibmod:response_header_finished_state(log_state) -- =============================================== -- This is called when the response body is -- available. -- =============================================== ibmod:response_body_data_state(log_state) -- =============================================== -- This is called when the complete response is -- ready to be handled. -- =============================================== ibmod:handle_response_state(log_state) -- =============================================== -- This is called when the response is finished. -- =============================================== ibmod:response_finished_state(log_state) -- =============================================== -- This is called after the transaction is done -- and any post processing can be done. -- =============================================== ibmod:handle_postprocess_state(log_state) -- =============================================== -- This is called after postprocess is complete, -- to allow for any post-transaction logging. -- =============================================== ibmod:handle_logging_state(log_state) -- =============================================== -- This is called when the transaction is -- finished. -- =============================================== ibmod:tx_finished_state(log_state) -- =============================================== -- This is called when a connection is closed. -- =============================================== ibmod:conn_closed_state(log_state) -- =============================================== -- This is called when the connection disconnect -- is ready to handle. -- =============================================== ibmod:handle_disconnect_state(log_state) -- =============================================== -- This is called when the connection is finished. -- =============================================== ibmod:conn_finished_state(log_state) -- =============================================== -- This is called when a logevent event has -- occurred. -- =============================================== ibmod:handle_logevent_state(log_state) -- Report success. ibmod:logInfo("Module loaded!") -- Return IB_OK. return 0
apache-2.0
PichotM/DarkRP
entities/weapons/ls_sniper/shared.lua
7
2644
AddCSLuaFile() if SERVER then AddCSLuaFile("cl_init.lua") end if CLIENT then SWEP.PrintName = "Silenced Sniper" SWEP.Author = "DarkRP Developers" SWEP.Slot = 0 SWEP.SlotPos = 0 SWEP.IconLetter = "n" killicon.AddFont("ls_sniper", "CSKillIcons", SWEP.IconLetter, Color(200, 200, 200, 255)) end DEFINE_BASECLASS("weapon_cs_base2") SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Category = "DarkRP (Weapon)" SWEP.ViewModel = "models/weapons/cstrike/c_snip_g3sg1.mdl" SWEP.WorldModel = "models/weapons/w_snip_g3sg1.mdl" SWEP.Weight = 3 SWEP.HoldType = "ar2" SWEP.Primary.Sound = Sound("Weapon_M4A1.Silenced") SWEP.Primary.Damage = 100 SWEP.Primary.Recoil = 0.03 SWEP.Primary.NumShots = 1 SWEP.Primary.Cone = 0.0001 - .05 SWEP.Primary.ClipSize = 25 SWEP.Primary.Delay = 0.7 SWEP.Primary.DefaultClip = 75 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "smg1" SWEP.IronSightsPos = Vector(0, 0, 0) -- this is just to make it disappear so it doesn't show up whilst scoped --[[--------------------------------------------------------------------------- SetupDataTables ---------------------------------------------------------------------------]] function SWEP:SetupDataTables() BaseClass.SetupDataTables(self) -- Int 0 = BurstBulletNum -- Int 1 = TotalUsedMagCount self:NetworkVar("Int", 2, "ScopeLevel") end --[[--------------------------------------------------------------------------- Reload ---------------------------------------------------------------------------]] function SWEP:Reload() if not IsValid(self:GetOwner()) then return end self:GetOwner():SetFOV(0, 0) self:SetScopeLevel(0) return BaseClass.Reload(self) end --[[--------------------------------------------------------------------------- SecondaryAttack ---------------------------------------------------------------------------]] local zoomFOV = {0, 0, 25, 5} function SWEP:SecondaryAttack() if not IsValid(self:GetOwner()) then return end if not self.IronSightsPos then return end self:SetNextSecondaryFire(CurTime() + 0.1) self:SetScopeLevel((self:GetScopeLevel() + 1) % 4) self:SetIronsights(self:GetScopeLevel() > 0) self:GetOwner():SetFOV(zoomFOV[self:GetScopeLevel() + 1], 0) end --[[--------------------------------------------------------------------------- Holster the weapon ---------------------------------------------------------------------------]] function SWEP:Holster() if not IsValid(self:GetOwner()) then return end self:GetOwner():SetFOV(0, 0) self:SetScopeLevel(0) self:SetIronsights(false) return BaseClass.Holster(self) end
mit
Sasu98/Nerd-Gaming-Public
resources/NGGlue/glue.lua
2
1801
function glue() local player = getLocalPlayer() if not getPedOccupiedVehicle(player) then local vehicle = getPedContactElement(player) if getElementType(vehicle) == "vehicle" then local px, py, pz = getElementPosition(player) local vx, vy, vz = getElementPosition(vehicle) local sx = px - vx local sy = py - vy local sz = pz - vz local rotpX = 0 local rotpY = 0 local rotpZ = getPedRotation(player) local rotvX,rotvY,rotvZ = getElementRotation(vehicle) local t = math.rad(rotvX) local p = math.rad(rotvY) local f = math.rad(rotvZ) local ct = math.cos(t) local st = math.sin(t) local cp = math.cos(p) local sp = math.sin(p) local cf = math.cos(f) local sf = math.sin(f) local z = ct*cp*sz + (sf*st*cp + cf*sp)*sx + (-cf*st*cp + sf*sp)*sy local x = -ct*sp*sz + (-sf*st*sp + cf*cp)*sx + (cf*st*sp + sf*cp)*sy local y = st*sz - sf*ct*sx + cf*ct*sy local rotX = rotpX - rotvX local rotY = rotpY - rotvY local rotZ = rotpZ - rotvZ local slot = getPedWeaponSlot(player) --outputDebugString("gluing ".. getPlayerName(player) .." to " .. getVehicleName(vehicle) .. "(offset: "..tostring(x)..","..tostring(y)..","..tostring(z).."; rotation:"..tostring(rotX)..","..tostring(rotY)..","..tostring(rotZ)..")") triggerServerEvent("gluePlayer", player, slot, vehicle, x, y, z, rotX, rotY, rotZ) unbindKey("x","down",glue) bindKey("x","down",unglue) bindKey("jump","down",unglue) end end end addCommandHandler("glue",glue) function unglue () local player = getLocalPlayer() triggerServerEvent("ungluePlayer", player) unbindKey("jump","down",unglue) unbindKey("x","down",unglue) bindKey("x","down",glue) end addCommandHandler("unglue",unglue) bindKey("x","down",glue)
mit
Sasu98/Nerd-Gaming-Public
resources/NGPlayerFunctions/server/teams.lua
2
1349
local teams = { { "Staff", 255, 140, 0 }, { "Criminals", 255, 0, 0 }, { "Law Enforcement", 0, 100, 255 }, { "Services", 255, 255, 0 }, { "Emergency", 0, 255, 255 }, { "Unemployed", 255, 92, 0 }, } local lawTeams = { ['Law Enforcement'] = true } local team = { } for i, v in ipairs ( teams ) do team[v[1]] = createTeam ( unpack ( v ) ) end function setTeam ( p, tem ) if ( p and getElementType ( p ) == 'player' and tem and type ( tem ) == 'string' ) then for i, v in ipairs ( teams ) do if ( v[1] == tem ) then return setPlayerTeam ( p, getTeamFromName ( v[1] ) ) end end end return false end addEventHandler ( "onResourceStop", root, function ( ) for i, v in ipairs ( getElementsByType ( 'player' ) ) do if ( getPlayerTeam ( v ) ) then setElementData ( v, "NGPlayers:SavedTeam", getTeamName ( getPlayerTeam ( v ) ) ) end end end ) addEventHandler ( 'onResourceStart', resourceRoot, function ( ) for i, v in ipairs ( getElementsByType ( 'player' ) ) do local t = getElementData ( v, 'NGPlayers:SavedTeam' ) if t and getTeamFromName ( t ) then setPlayerTeam ( v, getTeamFromName ( t ) ) else setPlayerTeam ( v, getTeamFromName ( t, "Unemployed" ) ) end end end ) function isTeamLaw ( team ) local team = tostring ( team ) if ( lawTeams[team] ) then return true end return false end
mit
LORgames/premake-core
modules/gmake2/tests/test_gmake2_linking.lua
12
5953
-- -- test_gmake2_linking.lua -- Validate the link step generation for makefiles. -- (c) 2016-2017 Jason Perkins, Blizzard Entertainment and the Premake project -- local suite = test.declare("gmake2_linking") local p = premake local gmake2 = p.modules.gmake2 local project = p.project -- -- Setup and teardown -- local wks, prj function suite.setup() _OS = "linux" wks, prj = test.createWorkspace() end local function prepare(calls) local cfg = test.getconfig(prj, "Debug") local toolset = p.tools.gcc p.callarray(gmake2.cpp, calls, cfg, toolset) end -- -- Check link command for a shared C++ library. -- function suite.links_onCppSharedLib() kind "SharedLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -shared -Wl,-soname=libMyProject.so -s LINKCMD = $(CXX) -o "$@" $(OBJECTS) $(RESOURCES) $(ALL_LDFLAGS) $(LIBS) ]] end function suite.links_onMacOSXCppSharedLib() _OS = "macosx" kind "SharedLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -dynamiclib -Wl,-install_name,@rpath/libMyProject.dylib -Wl,-x LINKCMD = $(CXX) -o "$@" $(OBJECTS) $(RESOURCES) $(ALL_LDFLAGS) $(LIBS) ]] end -- -- Check link command for a shared C library. -- function suite.links_onCSharedLib() language "C" kind "SharedLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -shared -Wl,-soname=libMyProject.so -s LINKCMD = $(CC) -o "$@" $(OBJECTS) $(RESOURCES) $(ALL_LDFLAGS) $(LIBS) ]] end -- -- Check link command for a static library. -- function suite.links_onStaticLib() kind "StaticLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LINKCMD = $(AR) -rcs "$@" $(OBJECTS) ]] end -- -- Check link command for the Utility kind. -- -- Utility projects should only run custom commands, and perform no linking. -- function suite.links_onUtility() kind "Utility" prepare { "linkCmd" } test.capture [[ LINKCMD = ]] end -- -- Check link command for a Mac OS X universal static library. -- function suite.links_onMacUniversalStaticLib() architecture "universal" kind "StaticLib" prepare { "ldFlags", "linkCmd" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LINKCMD = libtool -o "$@" $(OBJECTS) ]] end -- -- Check a linking to a sibling static library. -- function suite.links_onSiblingStaticLib() links "MyProject2" test.createproject(wks) kind "StaticLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LIBS += build/bin/Debug/libMyProject2.a LDDEPS += build/bin/Debug/libMyProject2.a ]] end -- -- Check a linking to a sibling shared library. -- function suite.links_onSiblingSharedLib() links "MyProject2" test.createproject(wks) kind "SharedLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -Wl,-rpath,'$$ORIGIN/../../build/bin/Debug' -s LIBS += build/bin/Debug/libMyProject2.so LDDEPS += build/bin/Debug/libMyProject2.so ]] end -- -- Check a linking to a sibling shared library using -l and -L. -- function suite.links_onSiblingSharedLibRelativeLinks() links "MyProject2" flags { "RelativeLinks" } test.createproject(wks) kind "SharedLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -Lbuild/bin/Debug -Wl,-rpath,'$$ORIGIN/../../build/bin/Debug' -s LIBS += -lMyProject2 LDDEPS += build/bin/Debug/libMyProject2.so ]] end function suite.links_onMacOSXSiblingSharedLib() _OS = "macosx" links "MyProject2" flags { "RelativeLinks" } test.createproject(wks) kind "SharedLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -Lbuild/bin/Debug -Wl,-rpath,'@loader_path/../../build/bin/Debug' -Wl,-x LIBS += -lMyProject2 LDDEPS += build/bin/Debug/libMyProject2.dylib ]] end -- -- Check a linking multiple siblings. -- function suite.links_onMultipleSiblingStaticLib() links "MyProject2" links "MyProject3" test.createproject(wks) kind "StaticLib" location "build" test.createproject(wks) kind "StaticLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LIBS += build/bin/Debug/libMyProject2.a build/bin/Debug/libMyProject3.a LDDEPS += build/bin/Debug/libMyProject2.a build/bin/Debug/libMyProject3.a ]] end -- -- Check a linking multiple siblings with link groups enabled. -- function suite.links_onSiblingStaticLibWithLinkGroups() links "MyProject2" links "MyProject3" linkgroups "On" test.createproject(wks) kind "StaticLib" location "build" test.createproject(wks) kind "StaticLib" location "build" prepare { "ldFlags", "libs", "ldDeps" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -s LIBS += -Wl,--start-group build/bin/Debug/libMyProject2.a build/bin/Debug/libMyProject3.a -Wl,--end-group LDDEPS += build/bin/Debug/libMyProject2.a build/bin/Debug/libMyProject3.a ]] end -- -- When referencing an external library via a path, the directory -- should be added to the library search paths, and the library -- itself included via an -l flag. -- function suite.onExternalLibraryWithPath() location "MyProject" links { "libs/SomeLib" } prepare { "ldFlags", "libs" } test.capture [[ ALL_LDFLAGS += $(LDFLAGS) -L../libs -s LIBS += -lSomeLib ]] end -- -- When referencing an external library with a period in the -- file name make sure it appears correctly in the LIBS -- directive. Currently the period and everything after it -- is stripped -- function suite.onExternalLibraryWithPathAndVersion() location "MyProject" links { "libs/SomeLib-1.1" } prepare { "libs", } test.capture [[ LIBS += -lSomeLib-1.1 ]] end
bsd-3-clause
Insurgencygame/LivingDead
TheLivingDeadv0.1.sdd/luarules/configs/UnitMaterials/1_normalmapping.lua
1
5171
-- $Id$ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local GetGameFrame=Spring.GetGameFrame local GetUnitHealth=Spring.GetUnitHealth local modulo=math.fmod local glUniform=gl.Uniform local sine =math.sin local maximum=math.max local GADGET_DIR = "LuaRules/Configs/" local function DrawUnit(unitID, material) glUniform(material.frameLoc, 2* maximum(0,sine(modulo(unitID,10)+GetGameFrame()/(modulo(unitID,7)+6)))) health,maxhealth=GetUnitHealth(unitID) glUniform(material.healthLoc, 2*maximum(0, (-2*health)/(maxhealth)+1) )--inverse of health, 0 if health is 100%-50%, goes to 1 by 0 health --// engine should still draw it (we just set the uniforms for the shader) return false end local materials = { normalMappedS3o = { shaderDefinitions = { "#define use_perspective_correct_shadows", "#define use_normalmapping", --"#define flip_normalmap", }, shader = include(GADGET_DIR .. "UnitMaterials/Shaders/default.lua"), usecamera = false, culling = GL.BACK, texunits = { [0] = '%%UNITDEFID:0', [1] = '%%UNITDEFID:1', [2] = '$shadow', [3] = '$specular', [4] = '$reflection', [5] = '%NORMALTEX', }, DrawUnit = DrawUnit, }, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Automated normalmap detection local unitMaterials = {} local function FindNormalmap(tex1, tex2) local normaltex --// check if there is a corresponding _normals.dds file if (VFS.FileExists(tex1)) then local basefilename = tex1:gsub("%....","") --[[if (tonumber(basefilename:sub(-1,-1))) then basefilename = basefilename:sub(1,-2) end]]-- -- This code removes trailing numbers, but many S44 units end in a number, e.g. SU-76 if (basefilename:sub(-1,-1) == "_") then basefilename = basefilename:sub(1,-2) end normaltex = basefilename .. "_normals.dds" if (not VFS.FileExists(normaltex)) then normaltex = nil end end --if FileExists --[[if (not normaltex) and tex2 and (VFS.FileExists(tex2)) then local basefilename = tex2:gsub("%....","") if (tonumber(basefilename:sub(-1,-1))) then basefilename = basefilename:sub(1,-2) end if (basefilename:sub(-1,-1) == "_") then basefilename = basefilename:sub(1,-2) end normaltex = basefilename .. "_normals.dds" if (not VFS.FileExists(normaltex)) then normaltex = nil end end --if FileExists ]] -- disable tex2 detection for S44 return normaltex end for i=1,#UnitDefs do local udef = UnitDefs[i] if (udef.customParams.normaltex and VFS.FileExists(udef.customParams.normaltex)) then unitMaterials[udef.name] = {"normalMappedS3o", NORMALTEX = udef.customParams.normaltex} elseif (udef.model.type == "s3o") then local modelpath = udef.model.path if (modelpath) then --// udef.model.textures is empty at gamestart, so read the texture filenames from the s3o directly local rawstr = VFS.LoadFile(modelpath) local header = rawstr:sub(1,60) local texPtrs = VFS.UnpackU32(header, 45, 2) local tex1,tex2 if (texPtrs[2] > 0) then tex2 = "unittextures/" .. rawstr:sub(texPtrs[2]+1, rawstr:len()-1) else texPtrs[2] = rawstr:len() end if (texPtrs[1] > 0) then tex1 = "unittextures/" .. rawstr:sub(texPtrs[1]+1, texPtrs[2]-1) end -- output units without tex2 --[[if not tex2 then Spring.Echo("CustomUnitShaders: " .. udef.name .. " no tex2") end]] local normaltex = FindNormalmap(tex1,tex2) if (normaltex and not unitMaterials[udef.name]) then unitMaterials[udef.name] = {"normalMappedS3o", NORMALTEX = normaltex} end end --if model elseif (udef.model.type == "obj") then local modelinfopath = udef.model.path if (modelinfopath) then modelinfopath = modelinfopath .. ".lua" if (VFS.FileExists(modelinfopath)) then local infoTbl = Include(modelinfopath) if (infoTbl) then local tex1 = "unittextures/" .. (infoTbl.tex1 or "") local tex2 = "unittextures/" .. (infoTbl.tex2 or "") -- output units without tex2 --[[if not tex2 then Spring.Echo("CustomUnitShaders: " .. udef.name .. " no tex2") end]] local normaltex = FindNormalmap(tex1,tex2) if (normaltex and not unitMaterials[udef.name]) then unitMaterials[udef.name] = {"normalMappedS3o", NORMALTEX = normaltex} end end end end end --elseif end --for -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- return materials, unitMaterials -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
lxl1140989/dmsdk
feeds/luci/applications/luci-diag-devinfo/luasrc/controller/luci_diag/devinfo_common.lua
76
5638
--[[ Luci diag - Diagnostics controller module (c) 2009 Daniel Dickinson 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 ]]-- module("luci.controller.luci_diag.devinfo_common", package.seeall) require("luci.i18n") require("luci.util") require("luci.sys") require("luci.cbi") require("luci.model.uci") local translate = luci.i18n.translate local DummyValue = luci.cbi.DummyValue local SimpleSection = luci.cbi.SimpleSection function index() return -- no-op end function run_processes(outnets, cmdfunc) i = next(outnets, nil) while (i) do outnets[i]["output"] = luci.sys.exec(cmdfunc(outnets, i)) i = next(outnets, i) end end function parse_output(devmap, outnets, haslink, type, mini, debug) local curnet = next(outnets, nil) while (curnet) do local output = outnets[curnet]["output"] local subnet = outnets[curnet]["subnet"] local ports = outnets[curnet]["ports"] local interface = outnets[curnet]["interface"] local netdevs = {} devlines = luci.util.split(output) if not devlines then devlines = {} table.insert(devlines, output) end local j = nil j = next(devlines, j) local found_a_device = false while (j) do if devlines[j] and ( devlines[j] ~= "" ) then found_a_device = true local devtable local row = {} devtable = luci.util.split(devlines[j], ' | ') row["ip"] = devtable[1] if (not mini) then row["mac"] = devtable[2] end if ( devtable[4] == 'unknown' ) then row["vendor"] = devtable[3] else row["vendor"] = devtable[4] end row["type"] = devtable[5] if (not mini) then row["model"] = devtable[6] end if (haslink) then row["config_page"] = devtable[7] end if (debug) then row["raw"] = devlines[j] end table.insert(netdevs, row) end j = next(devlines, j) end if not found_a_device then local row = {} row["ip"] = curnet if (not mini) then row["mac"] = "" end if (type == "smap") then row["vendor"] = luci.i18n.translate("No SIP devices") else row["vendor"] = luci.i18n.translate("No devices detected") end row["type"] = luci.i18n.translate("check other networks") if (not mini) then row["model"] = "" end if (haslink) then row["config_page"] = "" end if (debug) then row["raw"] = output end table.insert(netdevs, row) end local s if (type == "smap") then if (mini) then s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet) else local interfacestring = "" if ( interface ~= "" ) then interfacestring = ", " .. interface end s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet .. " (" .. subnet .. ":" .. ports .. interfacestring .. ")") end s.template = "diag/smapsection" else if (mini) then s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet) else local interfacestring = "" if ( interface ~= "" ) then interfacestring = ", " .. interface end s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet .. " (" .. subnet .. interfacestring .. ")") end end s:option(DummyValue, "ip", translate("IP Address")) if (not mini) then s:option(DummyValue, "mac", translate("MAC Address")) end s:option(DummyValue, "vendor", translate("Vendor")) s:option(DummyValue, "type", translate("Device Type")) if (not mini) then s:option(DummyValue, "model", translate("Model")) end if (haslink) then s:option(DummyValue, "config_page", translate("Link to Device")) end if (debug) then s:option(DummyValue, "raw", translate("Raw")) end curnet = next(outnets, curnet) end end function get_network_device(interface) local state = luci.model.uci.cursor_state() state:load("network") local dev return state:get("network", interface, "ifname") end function cbi_add_networks(field) uci.cursor():foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then field:value(section[".name"]) end end ) field.titleref = luci.dispatcher.build_url("admin", "network", "network") end function config_devinfo_scan(map, scannet) local o o = scannet:option(luci.cbi.Flag, "enable", translate("Enable")) o.optional = false o.rmempty = false o = scannet:option(luci.cbi.Value, "interface", translate("Interface")) o.optional = false luci.controller.luci_diag.devinfo_common.cbi_add_networks(o) local scansubnet scansubnet = scannet:option(luci.cbi.Value, "subnet", translate("Subnet")) scansubnet.optional = false o = scannet:option(luci.cbi.Value, "timeout", translate("Timeout"), translate("Time to wait for responses in seconds (default 10)")) o.optional = true o = scannet:option(luci.cbi.Value, "repeat_count", translate("Repeat Count"), translate("Number of times to send requests (default 1)")) o.optional = true o = scannet:option(luci.cbi.Value, "sleepreq", translate("Sleep Between Requests"), translate("Milliseconds to sleep between requests (default 100)")) o.optional = true end
gpl-2.0
LORgames/premake-core
modules/d/tests/test_gmake.lua
8
3517
--- -- d/tests/test_gmake.lua -- Automated test suite for gmake project generation. -- Copyright (c) 2011-2015 Manu Evans and the Premake project --- local suite = test.declare("d_make") local p = premake local m = p.modules.d local make = p.make local project = p.project --------------------------------------------------------------------------- -- Setup/Teardown --------------------------------------------------------------------------- local wks, prj, cfg function suite.setup() p.escaper(make.esc) wks = test.createWorkspace() end local function prepare() prj = p.workspace.getproject(wks, 1) end local function prepare_cfg(calls) prj = p.workspace.getproject(wks, 1) local cfg = test.getconfig(prj, "Debug") local toolset = p.tools.dmd p.callArray(calls, cfg, toolset) end -- -- Check project generation -- function suite.make_targetRules() prepare() m.make.targetRules(prj) test.capture [[ $(TARGET): $(SOURCEFILES) $(LDDEPS) @echo Building MyProject $(SILENT) $(BUILDCMD) $(POSTBUILDCMDS) ]] end function suite.make_targetRules_separateCompilation() compilationmodel "File" prepare() m.make.targetRules(prj) test.capture [[ $(TARGET): $(OBJECTS) $(LDDEPS) @echo Linking MyProject $(SILENT) $(LINKCMD) $(POSTBUILDCMDS) ]] end function suite.make_targetRules_mixedCompilation() configuration { "Release" } compilationmodel "File" prepare() m.make.targetRules(prj) test.capture [[ ifeq ($(config),debug) $(TARGET): $(SOURCEFILES) $(LDDEPS) @echo Building MyProject $(SILENT) $(BUILDCMD) $(POSTBUILDCMDS) endif ifeq ($(config),release) $(TARGET): $(OBJECTS) $(LDDEPS) @echo Linking MyProject $(SILENT) $(LINKCMD) $(POSTBUILDCMDS) endif ]] end function suite.make_fileRules() files { "blah.d" } prepare() m.make.dFileRules(prj) test.capture [[ ]] end function suite.make_fileRules_separateCompilation() files { "blah.d" } compilationmodel "File" prepare() m.make.dFileRules(prj) test.capture [[ $(OBJDIR)/blah.o: blah.d @echo $(notdir $<) $(SILENT) $(DC) $(ALL_DFLAGS) $(OUTPUTFLAG) -c $< ]] end function suite.make_fileRules_mixedCompilation() files { "blah.d" } configuration { "Release" } compilationmodel "File" prepare() m.make.dFileRules(prj) test.capture [[ $(OBJDIR)/blah.o: blah.d @echo $(notdir $<) $(SILENT) $(DC) $(ALL_DFLAGS) $(OUTPUTFLAG) -c $< ]] end function suite.make_objects() files { "blah.d" } prepare() m.make.objects(prj) test.capture [[ SOURCEFILES := \ blah.d \ ]] end function suite.make_objects_separateCompilation() files { "blah.d" } compilationmodel "File" prepare() m.make.objects(prj) test.capture [[ OBJECTS := \ $(OBJDIR)/blah.o \ ]] end function suite.make_objects_mixedCompilation() files { "blah.d" } configuration { "Release" } compilationmodel "File" files { "blah2.d" } prepare() m.make.objects(prj) test.capture [[ SOURCEFILES := \ blah.d \ OBJECTS := \ $(OBJDIR)/blah.o \ ifeq ($(config),release) SOURCEFILES += \ blah2.d \ OBJECTS += \ $(OBJDIR)/blah2.o \ endif ]] end -- -- Check configuration generation -- function suite.make_allRules() prepare_cfg({ m.make.allRules }) test.capture [[ all: $(TARGETDIR) prebuild prelink $(TARGET) @: ]] end function suite.make_allRules_separateCompilation() compilationmodel "File" prepare_cfg({ m.make.allRules }) test.capture [[ all: $(TARGETDIR) $(OBJDIR) prebuild prelink $(TARGET) @: ]] end
bsd-3-clause
cooper-lyt/HSAPI
lua/media.lua
1
7254
--author:medcl,m@medcl.net,http://log.medcl.net function table.contains(table, element) for _, value in pairs(table) do if value == element then return true end end return false end function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function exit_with_code(code) -- ngx.say(code) ngx.exit(code) return end function req_orig_file(file_url) local http = require"resty.http" local hc = http.new() local res, err = hc:request_uri(file_url) if res.status == 301 or res.status == 302 then file_url = string.match(res.body,'"(.+)"') res, err = hc:request_uri(file_url) end if res.status ~= 200 then return exit_with_code(404) else if res.body == nil then return exit_with_code(404) else if (res.body..'a') == 'a' then return exit_with_code(404) else ngx.say(res.body) ngx.flush(true) exit_with_code(200) return end end end end function save_orig_file(file_url,local_file_folder,local_file_path) local http = require"resty.http" local hc = http.new() local res, err = hc:request_uri(file_url) if res.status == 301 or res.status == 302 then file_url = string.match(res.body,'"(.+)"') res, err = hc:request_uri(file_url) end if res.status ~= 200 then return exit_with_code(404) else if res.body == nil then return exit_with_code(404) else if (res.body..'a') == 'a' then return exit_with_code(404) else local mkdir_command ="mkdir -p "..local_file_folder.." >/dev/null 2>&1 " os.execute(mkdir_command) file = io.open(local_file_path, "w"); if (file) then file:write(res.body); file:close(); else return exit_with_code(500) end end end end end function req_volume_server() -- TODO,get from weedfs,curl http://localhost:9333/dir/lookup?volumeId=3 end function process_img(file_volumn,file_id,file_size,file_url) local image_sizes = { "100x100", "80x80", "800x600", "40x40" ,"480x320","360x200","320x210","640x420","160x160","800x400","200x200"}; local scale_image_sizes = { "100x100s", "80x80s", "800x600s", "40x40s" ,"480x320s","360x200s","320x210s","640x420s","160x160s","800x400s","200x200s"}; local local_file_root = ngx.var.local_img_fs_root .."images/"; local local_file_in_folder = local_file_root .."orig/".. file_volumn .."/"; local local_file_in_path = local_file_in_folder.. file_id ..".jpg"; local local_file_out_folder = local_file_root.. file_size .."/" .. file_volumn .."/"; local local_file_out_path = local_file_out_folder.. file_id ..".jpg"; local local_file_out_rel_path = "/images/".. file_size .."/" .. file_volumn .."/".. file_id ..".jpg"; local mkdir_command ="mkdir -p "..local_file_out_folder.." >/dev/null 2>&1 " local convert_command; --return if has a local copy if(file_exists(local_file_out_path))then local file = io.open(local_file_out_path, "r"); if (file) then local content= file:read("*a"); file:close(); ngx.say(content) ngx.flush(true) return end end --get original file if file_size == "orig" then return req_orig_file(file_url) end if table.contains(scale_image_sizes, file_size) then file_size=string.sub(file_size, 1, -2) convert_command = "gm convert " .. local_file_in_path .. " -resize '" .. file_size .. "' -quality 90 " .. local_file_out_path .. ">/dev/null 2>&1 "; elseif (table.contains(image_sizes, file_size)) then convert_command = "gm convert " .. local_file_in_path .. " -thumbnail " .. file_size .. "^ -quality 90 -gravity center -extent " .. file_size .. " " .. local_file_out_path .. ">/dev/null 2>&1 "; else return exit_with_code(404) end --ngx.say('enter') if(not file_exists(local_file_in_path))then save_orig_file(file_url,local_file_in_folder,local_file_in_path) end os.execute(mkdir_command) os.execute(convert_command) if(file_exists(local_file_out_path))then local file = io.open(local_file_out_path, "r"); if (file) then local content= file:read("*a"); file:close(); ngx.say(content) ngx.flush(true) else return exit_with_code(500) end end end function process_audio(file_volumn,file_id,file_size,file_url) local audio_sizes = { "mp3" }; local local_file_root = ngx.var.local_audio_fs_root .."audios/"; local local_file_in_folder = local_file_root .."orig/".. file_volumn .."/"; local local_file_in_path = local_file_in_folder.. file_id ..".mp3"; local local_file_out_folder = local_file_root.. file_size .."/" .. file_volumn .."/"; local local_file_out_path = local_file_out_folder.. file_id ..".mp3"; local local_file_out_rel_path = "/audios/".. file_size .."/" .. file_volumn .."/".. file_id ..".mp3"; if(file_exists(local_file_out_path))then local file = io.open(local_file_out_path, "r"); if (file) then local content= file:read("*a"); file:close(); ngx.say(content) ngx.flush(true) return end end --get original file if file_size == "orig" then return req_orig_file(file_url) end if table.contains(audio_sizes, file_size) then if(not file_exists(local_file_in_path))then save_orig_file(file_url,local_file_in_folder,local_file_in_path) end if(file_exists(local_file_in_path))then local mkdir_command ="mkdir -p "..local_file_out_folder.." >/dev/null 2>&1 " local convert_command = "ffmpeg -i " .. local_file_in_path .. " -ab 64 " .. local_file_out_path .. " >/dev/null 2>&1 "; os.execute(mkdir_command) os.execute(convert_command) if(file_exists(local_file_out_path))then local file = io.open(local_file_out_path, "r"); if (file) then local content= file:read("*a"); file:close(); ngx.say(content) ngx.flush(true) else return exit_with_code(500) end end end else return exit_with_code(404) end end local file_volumn = ngx.var.arg_volumn local file_id = ngx.var.arg_id local file_url = ngx.var.weed_img_root_url .. file_volumn .. "," .. file_id local process_type = ngx.var.arg_type or "na"; local file_size = ngx.var.arg_size or "na"; if ngx.var.arg_size == nil or ngx.var.arg_volumn == nil or ngx.var.arg_id == nil then return exit_with_code(400) end if(process_type == "img") then process_img(file_volumn,file_id,file_size,file_url) elseif(process_type == "audio")then process_audio(file_volumn,file_id,file_size,file_url) end
apache-2.0
leonardowindbot/windbotscripts
dustbin/WindIcons.lua
2
2100
Icon = {} Icon.__index = Icon Icon.__class = "Icon" local _ICONS = {} -- dont even know if this works function Icon.New(x, y, w, h, drawType, borderSize, borderColor, image) local tbl = setmetatable( { id = -1, width = w, height = h, x = x, y = y, drawType = drawType or 'rect', borderSize = borderSize or 1, borderColor = borderColor or -1, image = image, }, Icon) _ICONS[#_ICONS + 1] = tbl tbl.id = #_ICONS return tbl end function Icon:SetPosition(posx, posy) self.x = posx self.y = posy _ICONS[self.id] = self end function Icon:SetDrawingType(drawType) self.drawType = drawType _ICONS[self.id] = self end function Icon:SetBorder(size, color) self.borderSize = size or 1 self.botderColor = color or -1 _ICONS[self.id] = self end function Icon:SetSize(w, h) self.w = w self.h = h _ICONS[self.id] = self end function Icon:SetFillImage(img) self.image = img _ICONS[self.id] = self end function Icon:Align(ref) local pos = {x = 0, y = 0} if ref then pos.x, pos.y = ref.x, ref.y else local dist = math.huge for _, icon in ipairs(_ICONS) do local distTemp = getdistancebetween(self.x, self.y, 0, icon.x, icon.y, 0) if icon.id ~= self.id and distTemp < dist then pos = icon dist = distTemp end end end if pos.x == 0 and pos.y == 0 then self.x, self.y = 0, 0 return end local distx, disty = math.abs(pos.x - self.x), math.abs(pos.y - self.y) if distx < disty then -- x-axis is closer if pos.x > self.x then -- current icon is right from the ref point self.x = (pos.x + pos.w + pos.borderSize) elseif pos.x < self.x then -- current icon is left from the ref point self.x = (pos.x - self.w - self.borderSize) end self.y = pos.y else if distx > disty then -- y-axis is closer if pos.y > self.y then -- current icon is above ref point self.y = (pos.y - self.h - self.borderSize) elseif pos.y < self.y then -- current icon is below ref point self.y = (pos.y + pos.h + pos.borderSize) end self.x = pos.x end return end function Icon:Draw() return true end
mit
Sasu98/Nerd-Gaming-Public
resources/NGJobs/criminal/vehicle_theft_c.lua
2
1331
-- NGJobs:Criminal:Theft:setWaypointsVisible local waypoints = { { 1597.08, -1551.65, 13.59}, { 2733.43, -1842.82, 9.97 }, { 748.28, -1343.59, 13.52 }, } local waypoint = { blip = { }, marker = { } } addEvent ( "NGJobs:Criminal:Theft:setWaypointsVisible", true ) addEventHandler ( "NGJobs:Criminal:Theft:setWaypointsVisible", root, function ( s ) if ( s ) then for i, v in pairs ( waypoint ) do for k, e in pairs ( v ) do destroyElement ( e ) end end waypoint = { blip = { }, marker = { } } for i, v in ipairs ( waypoints ) do local x, y, z = unpack ( v ) waypoint.blip[i] = createBlip ( x, y, z, 53 ) waypoint.marker[i] = createMarker ( x, y, z-1.3, "cylinder", 5, 255, 255, 0, 120 ) addEventHandler ( 'onClientMarkerHit', waypoint.marker[i], CriminalVehicleTheftCapture ) end else for i, v in pairs ( waypoint ) do for k, e in pairs ( v ) do destroyElement ( e ) end end waypoint = { blip = { }, marker = { } } end end ) function CriminalVehicleTheftCapture ( p ) if ( p and p == localPlayer and isPedInVehicle ( p ) ) then for i, v in pairs ( waypoint ) do for k, e in pairs ( v ) do destroyElement ( e ) end end waypoint = { blip = { }, marker = { } } triggerServerEvent ( "NGJobs:Criminal:Theft:onPlayerCaptureVehicle", localPlayer ) end end
mit
Anarchid/Zero-K
effects/gundam_heavybulletimpact.lua
25
4293
-- heavybulletimpact return { ["heavybulletimpact"] = { dirtg = { class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 0.7, alwaysvisible = true, colormap = [[0.1 0.1 0.1 1.0 0.5 0.4 0.3 1.0 0 0 0 0.0]], directional = true, emitrot = 90, emitrotspread = 0, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 5, particlelife = 10, particlelifespread = 10, particlesize = 2, particlesizespread = 5, particlespeed = 1, particlespeedspread = 3, pos = [[r-1 r1, 1, r-1 r1]], sizegrowth = 1.2, sizemod = 1.0, texture = [[dirt]], useairlos = true, }, }, dirtw1 = { class = [[CSimpleParticleSystem]], count = 1, water = true, properties = { airdrag = 0.9, alwaysvisible = true, colormap = [[0.9 0.9 0.9 1.0 0.5 0.5 0.9 0.0]], directional = true, emitrot = 90, emitrotspread = 0, emitvector = [[0, 1, 0]], gravity = [[0, -0.2, 0]], numparticles = 8, particlelife = 25, particlelifespread = 7, particlesize = 5, particlesizespread = 5, particlespeed = 1, particlespeedspread = 7, pos = [[r-1 r1, 1, r-1 r1]], sizegrowth = 1.2, sizemod = 1.0, texture = [[randdots]], useairlos = true, }, }, dirtw2 = { class = [[CSimpleParticleSystem]], count = 1, water = true, properties = { airdrag = 0.7, alwaysvisible = true, colormap = [[1.0 1.0 1.0 1.0 0.5 0.5 0.8 0.0]], directional = true, emitrot = 90, emitrotspread = 0, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 5, particlelife = 10, particlelifespread = 10, particlesize = 2, particlesizespread = 5, particlespeed = 1, particlespeedspread = 7, pos = [[r-1 r1, 1, r-1 r1]], sizegrowth = 1.2, sizemod = 1.0, texture = [[dirt]], useairlos = true, }, }, poof01 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 0.8, alwaysvisible = true, colormap = [[0.0 0.55 0.5 0.01 0 0 0 0.01]], directional = true, emitrot = 45, emitrotspread = 32, emitvector = [[dir]], gravity = [[0, 0, 0]], numparticles = 8, particlelife = 10, particlelifespread = 5, particlesize = 3, particlesizespread = 0, particlespeed = 2, particlespeedspread = 5, pos = [[0, 2, 0]], sizegrowth = 1, sizemod = 1.0, texture = [[flashside1]], useairlos = false, }, }, whiteglow = { air = true, class = [[heatcloud]], count = 1, ground = true, water = true, properties = { alwaysvisible = true, heat = 10, heatfalloff = 5, maxheat = 15, pos = [[0, 0, 0]], size = 1, sizegrowth = 20, speed = [[0, 0, 0]], texture = [[laserend]], }, }, }, }
gpl-2.0
ComputerNerd/Retro-Graphics-Toolkit
TMS9918.lua
1
6150
--[[ This file is part of Retro Graphics Toolkit Retro Graphics Toolkit is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. Retro Graphics Toolkit 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 Retro Graphics Toolkit. If not, see <http://www.gnu.org/licenses/>. Copyright Sega16 (or whatever you wish to call me) (2012-2020) --]] function tms9918Graphics1RemapTiles(projectIDX, attrsByTile, forceKeepAllUnique) local bgColLookFor = bit32.band(projects[projectIDX].palColTMS9918, 15) -- attrsByTile starts with a table in the form of attrsByTile[attr] = {list of tiles with this attribute} -- Force keep all means we should scan all true color tiles and keep all unique true color tiles. -- Create a new table in the form of sortedTiles[attr][rgbaData] = {list of old indices} local ct = projects[projectIDX].tiles local sortedTiles = {} -- First start with the forced attributes. local blankRGBAtile = string.rep('\0', ct.tcSize) local tilesAddedToList = {} -- Keep track of tiles added to the list. local blankTileSet = {} local function processAttr(atr) local bgcol = bit32.band(atr, 15) local fgcol = bit32.band(bit32.rshift(atr, 4), 15) if bgcol == bgColLookFor then bgcol = 0 end if (bgColLookFor == 0) and (bgcol == 1) then bgcol = 0 end if fgcol == bgColLookFor then fgcol = 0 end if (bgColLookFor == 0) and (fgcol == 1) then fgcol = 0 end local mic = math.min(bgcol, fgcol) local mxc = math.max(bgcol, fgcol) return bit32.bor(mic, bit32.lshift(mxc, 4)) end for attr, tileIndices in pairs(attrsByTile) do attr = processAttr(attr) for k, tileIdx in ipairs(tileIndices) do local rgbaData = ct[tileIdx].rgbaData if rgbaData == blankRGBAtile then blankTileSet[tileIdx] = true else if sortedTiles[attr] == nil then sortedTiles[attr] = {} end if sortedTiles[attr][rgbaData] == nil then sortedTiles[attr][rgbaData] = {} end table.insert(sortedTiles[attr][rgbaData], tileIdx) end tilesAddedToList[tileIdx] = true end end if forceKeepAllUnique then -- Then add any tiles not already in sortedTiles. for tileIdx = 1, #ct do if tilesAddedToList[tileIdx] == nil then local t = ct[tileIdx] local attr = processAttr(t.pixels[1]:getExtAttr()) -- The reason it's part of pixels is for Graphics II mode so it can be indexed by a y value. In Graphics I mode getExtAttr will return the same value regardless of the y value. local rgbaData = t.rgbaData if rgbaData == blankRGBAtile then blankTileSet[tileIdx] = true else if sortedTiles[attr] == nil then sortedTiles[attr] = {} end if sortedTiles[attr][rgbaData] == nil then sortedTiles[attr][rgbaData] = {} end table.insert(sortedTiles[attr][rgbaData], tileIdx) end end end end -- The last step is to build the final list. -- We create two tables, one containing the extended attributes and one containing the true color and regular tile data. tilesFinal = {} local blankTile = string.rep('\0', ct.tileSize) local blankTileList = {} for k, v in pairs(blankTileSet) do table.insert(blankTileList, k) end local hasBlankTile = false for attr, rgbaDataList in pairs(sortedTiles) do local tileCount = 0 for rgbaData, oldTileIndices in pairs(rgbaDataList) do tileCount = tileCount + 1 table.insert(tilesFinal, {attr, rgbaData, ct[oldTileIndices[1]].data, oldTileIndices}) end local tilesRemaining = tileCount % 8 if tilesRemaining > 0 then local tilesNeeded = 8 - tilesRemaining for pi = 1, tilesNeeded do hasBlankTile = true table.insert(tilesFinal, {attr, blankRGBAtile, blankTile, blankTileList}) end end end if not hasBlankTile then if projects[projectIDX]:have(project.pjHaveMap) then -- See if we need a blank tile. If the tilemap is not using a blank tile then we don't need it. local ctms = projects[projectIDX].tilemaps for tmi = 1, #ctms do local ctm = ctms[tmi] for y = 1, #ctm do local cty = ctm[y] for x = 1, #cty do local ctx = cty[x] if blankTileSet[ctx.tile] ~= nil then hasBlankTile = true end end end end if hasBlankTile then for pi = 1, 8 do table.insert(tilesFinal, {bgColLookFor, blankRGBAtile, blankTile, blankTileList}) end end end end local function sortTileList(a, b) if a[1] == b[1] then if a[2] == b[2] then return a[3] < b[3] else return a[2] < b[2] end else return a[1] < b[1] end end table.sort(tilesFinal, sortTileList) local oldTileIdxToNew = {} ct:setAmt(#tilesFinal) for newTileIdx, tileInfo in ipairs(tilesFinal) do local t = ct[newTileIdx] t.rgbaData = tileInfo[2] t.data = tileInfo[3] for unused, oldIdx in ipairs(tileInfo[4]) do oldTileIdxToNew[oldIdx] = newTileIdx end end -- Attempt to make the blank tiles match the background color. for newTileIdx, tileInfo in ipairs(tilesFinal) do local bgColFound = bit32.band(tileInfo[1], 15) if bgColLookFor == bgColFound then if tileInfo[2] == blankRGBAtile then for bi = 1, #blankTileList do oldTileIdxToNew[blankTileList[bi]] = newTileIdx end break end end end extAttrsFinal = {} for ti = 8, #tilesFinal, 8 do extAttrsFinal[math.floor(ti / 8)] = string.char(tilesFinal[ti][1]) end ct.extAttrs = table.concat(extAttrsFinal) if projects[projectIDX]:have(project.pjHaveMap) then local ctms = projects[projectIDX].tilemaps for tmi = 1, #ctms do local ctm = ctms[tmi] for y = 1, #ctm do local cty = ctm[y] for x = 1, #cty do local ctx = cty[x] if oldTileIdxToNew[ctx.tile] ~= nil then ctx.tile = oldTileIdxToNew[ctx.tile] end end end end end end
gpl-3.0
Anarchid/Zero-K
LuaUI/cache.lua
4
5025
-- Poisoning for Spring.* functions (caching, filtering, providing back compat) if not Spring.IsUserWriting then Spring.IsUserWriting = function() return false end end -- *etTeamColor local teamColor = {} -- GetVisibleUnits local visibleUnits = {} -- original functions local GetTeamColor = Spring.GetTeamColor local SetTeamColor = Spring.SetTeamColor local GetVisibleUnits = Spring.GetVisibleUnits local MarkerAddPoint = Spring.MarkerAddPoint -- Block line drawing widgets --local MarkerAddLine = Spring.MarkerAddLine --function Spring.MarkerAddLine(a,b,c,d,e,f,g) -- MarkerAddLine(a,b,c,d,e,f,true) --end local spGetProjectileTeamID = Spring.GetProjectileTeamID local spGetMyTeamID = Spring.GetMyTeamID local spAreTeamsAllied = Spring.AreTeamsAllied local spGetSpectatingState = Spring.GetSpectatingState local function FilterOutRestrictedProjectiles(projectiles) local isSpectator, hasFullView = spGetSpectatingState() if isSpectator and hasFullView then return projectiles end local i = 1 local n = #projectiles local myTeamID = spGetMyTeamID() while i <= n do local p = projectiles[i] local ownerTeamID = spGetProjectileTeamID(p) -- If the owner is allied with us, we shouldn't need to filter anything out if not spAreTeamsAllied(ownerTeamID, myTeamID) then projectiles[i] = projectiles[n] projectiles[n] = nil n = n - 1 i = i - 1 end i = i + 1 end return projectiles end local GetProjectilesInRectangle = Spring.GetProjectilesInRectangle function Spring.GetProjectilesInRectangle(x1, z1, x2, z2) local projectiles = GetProjectilesInRectangle(x1, z1, x2, z2) return FilterOutRestrictedProjectiles(projectiles) end -- Cutscenes apply F5 local IsGUIHidden = Spring.IsGUIHidden function Spring.IsGUIHidden() return IsGUIHidden() or (WG.Cutscene and WG.Cutscene.IsInCutscene()) end function Spring.GetTeamColor(teamid) if not teamColor[teamid] then teamColor[teamid] = { GetTeamColor(teamid) } end return unpack(teamColor[teamid]) end function Spring.MarkerAddPoint(x, y, z, t, b) MarkerAddPoint(x,y,z,t,true) end function Spring.SetTeamColor(teamid, r, g, b) -- set and cache SetTeamColor(teamid, r, g, b) teamColor[teamid] = { GetTeamColor(teamid) } end local spSetUnitNoSelect = Spring.SetUnitNoSelect function Spring.SetUnitNoSelect(unitID, value) return end local function buildIndex(teamID, radius, Icons) --local index = tostring(teamID)..":"..tostring(radius)..":"..tostring(Icons) local t = {} if teamID then t[#t + 1] = teamID end if radius then t[#t + 1] = radius end -- concat wants a table where all elements are strings or numbers if Icons then t[#t+1] = 1 end return table.concat(t, ":") end -- returns unitTable = { [1] = number unitID, ... } function Spring.GetVisibleUnits(teamID, radius, Icons) local index = buildIndex(teamID, radius, Icons) local currentFrame = Spring.GetGameFrame() -- frame is necessary (invalidates visibility; units can die or disappear outta LoS) local now = Spring.GetTimer() -- frame is not sufficient (eg. you can move the screen while game is paused) local visible = visibleUnits[index] if visible then local diff = Spring.DiffTimers(now, visible.time) if diff < 0.05 and currentFrame == visible.frame then return visible.units end else visibleUnits[index] = {} visible = visibleUnits[index] end local ret = GetVisibleUnits(teamID, radius, Icons) visible.units = ret visible.frame = currentFrame visible.time = now return ret end --Workaround for Spring.SetCameraTarget() not working in Freestyle mode. local SetCameraTarget = Spring.SetCameraTarget function Spring.SetCameraTarget(x, y, z, transTime) local cs = Spring.GetCameraState() if cs.mode == 4 then --if using Freestyle cam, especially when using "camera_cofc.lua" --"0.46364757418633" is the default pitch given to FreeStyle camera (the angle between Target->Camera->Ground, tested ingame) and is the only pitch that original "Spring.SetCameraTarget()" is based upon. --"cs.py-y" is the camera height. --"math.pi/2 + cs.rx" is the current pitch for Freestyle camera (the angle between Target->Camera->Ground). Freestyle camera can change its pitch by rotating in rx-axis. --The original equation is: "x/y = math.tan(rad)" which is solved for "x" local ori_zDist = math.tan(0.46364757418633) * (cs.py - y) --the ground distance (at z-axis) between default FreeStyle camera and the target. We know this is only for z-axis from our test. local xzDist = math.tan(math.pi / 2 + cs.rx) * (cs.py - y) --the ground distance (at xz-plane) between FreeStyle camera and the target. local xDist = math.sin(cs.ry) * xzDist ----break down "xzDist" into x and z component. local zDist = math.cos(cs.ry) * xzDist x = x - xDist --add current FreeStyle camera to x-component z = z - ori_zDist - zDist --remove default FreeStyle z-component, then add current Freestyle camera to z-component end if x and y and z then return SetCameraTarget(x, y, z, transTime) --return new results end end
gpl-2.0
DiamondLovesYou/skia-sys
tools/lua/bitmap_statistics.lua
207
1862
function string.startsWith(String,Start) return string.sub(String,1,string.len(Start))==Start end function string.endsWith(String,End) return End=='' or string.sub(String,-string.len(End))==End end local canvas = nil local num_perspective_bitmaps = 0 local num_affine_bitmaps = 0 local num_scaled_bitmaps = 0 local num_translated_bitmaps = 0 local num_identity_bitmaps = 0 local num_scaled_up = 0 local num_scaled_down = 0 function sk_scrape_startcanvas(c, fileName) canvas = c end function sk_scrape_endcanvas(c, fileName) canvas = nil end function sk_scrape_accumulate(t) -- dump the params in t, specifically showing the verb first, which we -- then nil out so it doesn't appear in tostr() if (string.startsWith(t.verb,"drawBitmap")) then matrix = canvas:getTotalMatrix() matrixType = matrix:getType() if matrixType.perspective then num_perspective_bitmaps = num_perspective_bitmaps + 1 elseif matrixType.affine then num_affine_bitmaps = num_affine_bitmaps + 1 elseif matrixType.scale then num_scaled_bitmaps = num_scaled_bitmaps + 1 if matrix:getScaleX() > 1 or matrix:getScaleY() > 1 then num_scaled_up = num_scaled_up + 1 else num_scaled_down = num_scaled_down + 1 end elseif matrixType.translate then num_translated_bitmaps = num_translated_bitmaps + 1 else num_identity_bitmaps = num_identity_bitmaps + 1 end end end function sk_scrape_summarize() io.write( "identity = ", num_identity_bitmaps, ", translated = ", num_translated_bitmaps, ", scaled = ", num_scaled_bitmaps, " (up = ", num_scaled_up, "; down = ", num_scaled_down, ")", ", affine = ", num_affine_bitmaps, ", perspective = ", num_perspective_bitmaps, "\n") end
bsd-3-clause
upndwn4par/android_external_skia
tools/lua/bitmap_statistics.lua
207
1862
function string.startsWith(String,Start) return string.sub(String,1,string.len(Start))==Start end function string.endsWith(String,End) return End=='' or string.sub(String,-string.len(End))==End end local canvas = nil local num_perspective_bitmaps = 0 local num_affine_bitmaps = 0 local num_scaled_bitmaps = 0 local num_translated_bitmaps = 0 local num_identity_bitmaps = 0 local num_scaled_up = 0 local num_scaled_down = 0 function sk_scrape_startcanvas(c, fileName) canvas = c end function sk_scrape_endcanvas(c, fileName) canvas = nil end function sk_scrape_accumulate(t) -- dump the params in t, specifically showing the verb first, which we -- then nil out so it doesn't appear in tostr() if (string.startsWith(t.verb,"drawBitmap")) then matrix = canvas:getTotalMatrix() matrixType = matrix:getType() if matrixType.perspective then num_perspective_bitmaps = num_perspective_bitmaps + 1 elseif matrixType.affine then num_affine_bitmaps = num_affine_bitmaps + 1 elseif matrixType.scale then num_scaled_bitmaps = num_scaled_bitmaps + 1 if matrix:getScaleX() > 1 or matrix:getScaleY() > 1 then num_scaled_up = num_scaled_up + 1 else num_scaled_down = num_scaled_down + 1 end elseif matrixType.translate then num_translated_bitmaps = num_translated_bitmaps + 1 else num_identity_bitmaps = num_identity_bitmaps + 1 end end end function sk_scrape_summarize() io.write( "identity = ", num_identity_bitmaps, ", translated = ", num_translated_bitmaps, ", scaled = ", num_scaled_bitmaps, " (up = ", num_scaled_up, "; down = ", num_scaled_down, ")", ", affine = ", num_affine_bitmaps, ", perspective = ", num_perspective_bitmaps, "\n") end
bsd-3-clause
Disslove77777/SSSS
plugins/logger.lua
28
1214
do local function pre_process(msg) if is_chat_msg(msg) then local logtxt = os.date('%F;%T', msg.date)..';'..msg.to.title..';'..msg.to.id ..';'..(msg.from.first_name or '')..(msg.from.last_name or '') ..';@'..(msg.from.username or '')..';'..msg.from.id..';' ..(msg.text or msg.media.type..':'..(msg.media.caption or ''))..'\n' local file = io.open('./data/logs/'..msg.to.id..'_log.csv', 'a') file:write(logtxt) file:close() end return msg end function run(msg, matches) if is_mod(msg.from.id, msg.to.id) then if matches[1] == 'get' then send_document('chat#id'..msg.to.id, './data/logs/'..msg.to.id..'_log.csv', ok_cb, false) elseif matches[1] == 'pm' then send_document('user#id'..msg.from.id, './data/logs/'..msg.to.id..'_log.csv', ok_cb, false) end end end return { description = 'Logging group messages.', usage = { '!log get : Send chat log to its chat group', '!log pm : Send chat log to private message' }, patterns = { '^!log (get)$', '^!log (pm)$' }, run = run, pre_process = pre_process } end
gpl-2.0
TylerR909/AppearanceSets_HideHelm
Libs/AceGUI-3.0/widgets/AceGUIContainer-DropDownGroup.lua
65
4515
--[[----------------------------------------------------------------------------- DropdownGroup Container Container controlled by a dropdown on the top. -------------------------------------------------------------------------------]] local Type, Version = "DropdownGroup", 21 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local assert, pairs, type = assert, pairs, type -- WoW APIs local CreateFrame = CreateFrame --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function SelectedGroup(self, event, value) local group = self.parentgroup local status = group.status or group.localstatus status.selected = value self.parentgroup:Fire("OnGroupSelected", value) end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self.dropdown:SetText("") self:SetDropdownWidth(200) self:SetTitle("") end, ["OnRelease"] = function(self) self.dropdown.list = nil self.status = nil for k in pairs(self.localstatus) do self.localstatus[k] = nil end end, ["SetTitle"] = function(self, title) self.titletext:SetText(title) self.dropdown.frame:ClearAllPoints() if title and title ~= "" then self.dropdown.frame:SetPoint("TOPRIGHT", -2, 0) else self.dropdown.frame:SetPoint("TOPLEFT", -1, 0) end end, ["SetGroupList"] = function(self,list,order) self.dropdown:SetList(list,order) end, ["SetStatusTable"] = function(self, status) assert(type(status) == "table") self.status = status end, ["SetGroup"] = function(self,group) self.dropdown:SetValue(group) local status = self.status or self.localstatus status.selected = group self:Fire("OnGroupSelected", group) end, ["OnWidthSet"] = function(self, width) local content = self.content local contentwidth = width - 26 if contentwidth < 0 then contentwidth = 0 end content:SetWidth(contentwidth) content.width = contentwidth end, ["OnHeightSet"] = function(self, height) local content = self.content local contentheight = height - 63 if contentheight < 0 then contentheight = 0 end content:SetHeight(contentheight) content.height = contentheight end, ["LayoutFinished"] = function(self, width, height) self:SetHeight((height or 0) + 63) end, ["SetDropdownWidth"] = function(self, width) self.dropdown:SetWidth(width) end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local PaneBackdrop = { bgFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", tile = true, tileSize = 16, edgeSize = 16, insets = { left = 3, right = 3, top = 5, bottom = 3 } } local function Constructor() local frame = CreateFrame("Frame") frame:SetHeight(100) frame:SetWidth(100) frame:SetFrameStrata("FULLSCREEN_DIALOG") local titletext = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal") titletext:SetPoint("TOPLEFT", 4, -5) titletext:SetPoint("TOPRIGHT", -4, -5) titletext:SetJustifyH("LEFT") titletext:SetHeight(18) local dropdown = AceGUI:Create("Dropdown") dropdown.frame:SetParent(frame) dropdown.frame:SetFrameLevel(dropdown.frame:GetFrameLevel() + 2) dropdown:SetCallback("OnValueChanged", SelectedGroup) dropdown.frame:SetPoint("TOPLEFT", -1, 0) dropdown.frame:Show() dropdown:SetLabel("") local border = CreateFrame("Frame", nil, frame) border:SetPoint("TOPLEFT", 0, -26) border:SetPoint("BOTTOMRIGHT", 0, 3) border:SetBackdrop(PaneBackdrop) border:SetBackdropColor(0.1,0.1,0.1,0.5) border:SetBackdropBorderColor(0.4,0.4,0.4) --Container Support local content = CreateFrame("Frame", nil, border) content:SetPoint("TOPLEFT", 10, -10) content:SetPoint("BOTTOMRIGHT", -10, 10) local widget = { frame = frame, localstatus = {}, titletext = titletext, dropdown = dropdown, border = border, content = content, type = Type } for method, func in pairs(methods) do widget[method] = func end dropdown.parentgroup = widget return AceGUI:RegisterAsContainer(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
mit
jerizm/kong
spec/03-plugins/07-ip-restriction/01-schema_spec.lua
11
2373
local schemas_validation = require "kong.dao.schemas_validation" local schema = require "kong.plugins.ip-restriction.schema" local v = schemas_validation.validate_entity describe("Plugin: ip-restriction (schema)", function() it("should accept a valid whitelist", function() assert(v({whitelist = {"127.0.0.1", "127.0.0.2"}}, schema)) end) it("should accept a valid blacklist", function() assert(v({blacklist = {"127.0.0.1", "127.0.0.2"}}, schema)) end) describe("errors", function() it("whitelist should not accept invalid types", function() local ok, err = v({whitelist = 12}, schema) assert.False(ok) assert.same({whitelist = "whitelist is not an array"}, err) end) it("whitelist should not accept invalid IPs", function() local ok, err = v({whitelist = "hello"}, schema) assert.False(ok) assert.same({whitelist = "cannot parse 'hello': Invalid IP"}, err) ok, err = v({whitelist = {"127.0.0.1", "127.0.0.2", "hello"}}, schema) assert.False(ok) assert.same({whitelist = "cannot parse 'hello': Invalid IP"}, err) end) it("blacklist should not accept invalid types", function() local ok, err = v({blacklist = 12}, schema) assert.False(ok) assert.same({blacklist = "blacklist is not an array"}, err) end) it("blacklist should not accept invalid IPs", function() local ok, err = v({blacklist = "hello"}, schema) assert.False(ok) assert.same({blacklist = "cannot parse 'hello': Invalid IP"}, err) ok, err = v({blacklist = {"127.0.0.1", "127.0.0.2", "hello"}}, schema) assert.False(ok) assert.same({blacklist = "cannot parse 'hello': Invalid IP"}, err) end) it("should not accept both a whitelist and a blacklist", function() local t = {blacklist = {"127.0.0.1"}, whitelist = {"127.0.0.2"}} local ok, err, self_err = v(t, schema) assert.False(ok) assert.is_nil(err) assert.equal("you cannot set both a whitelist and a blacklist", self_err.message) end) it("should not accept both empty whitelist and blacklist", function() local t = {blacklist = {}, whitelist = {}} local ok, err, self_err = v(t, schema) assert.False(ok) assert.is_nil(err) assert.equal("you must set at least a whitelist or blacklist", self_err.message) end) end) end)
apache-2.0
lxl1140989/dmsdk
feeds/luci/applications/luci-statistics/luasrc/statistics/i18n.lua
69
2405
--[[ Luci statistics - diagram i18n helper (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.statistics.i18n", package.seeall) require("luci.util") require("luci.i18n") Instance = luci.util.class() function Instance.__init__( self, graph ) self.i18n = luci.i18n self.graph = graph end function Instance._subst( self, str, val ) str = str:gsub( "%%H", self.graph.opts.host or "" ) str = str:gsub( "%%pn", val.plugin or "" ) str = str:gsub( "%%pi", val.pinst or "" ) str = str:gsub( "%%dt", val.dtype or "" ) str = str:gsub( "%%di", val.dinst or "" ) str = str:gsub( "%%ds", val.dsrc or "" ) return str end function Instance._translate( self, key, alt ) local val = self.i18n.string(key) if val ~= key then return val else return alt end end function Instance.title( self, plugin, pinst, dtype, dinst, user_title ) local title = user_title or "p=%s/pi=%s/dt=%s/di=%s" % { plugin, (pinst and #pinst > 0) and pinst or "(nil)", (dtype and #dtype > 0) and dtype or "(nil)", (dinst and #dinst > 0) and dinst or "(nil)" } return self:_subst( title, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.label( self, plugin, pinst, dtype, dinst, user_label ) local label = user_label or "dt=%s/di=%s" % { (dtype and #dtype > 0) and dtype or "(nil)", (dinst and #dinst > 0) and dinst or "(nil)" } return self:_subst( label, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.ds( self, source ) local label = source.title or self:_translate( string.format( "stat_ds_%s_%s_%s", source.type, source.instance, source.ds ), self:_translate( string.format( "stat_ds_%s_%s", source.type, source.instance ), self:_translate( string.format( "stat_ds_label_%s__%s", source.type, source.ds ), self:_translate( string.format( "stat_ds_%s", source.type ), source.type .. "_" .. source.instance:gsub("[^%w]","_") .. "_" .. source.ds ) ) ) ) return self:_subst( label, { dtype = source.type, dinst = source.instance, dsrc = source.ds } ) end
gpl-2.0
moteus/lua-log
test/test_basic.lua
3
9795
local HAS_RUNNER = not not lunit local lunit = require "lunit" local TEST_CASE = assert(lunit.TEST_CASE) local skip = lunit.skip or function() end local path = require "path" local utils = require "utils" local LUA, ARGS = utils.lua_args(arg) local PATH = path.fullpath(".") local DATE_PAT = "%d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d" local TESTDIR = ".test_log" local function exec_file(file) assert(path.isfile(file)) return utils.exec(PATH, LUA, '%s %s', ARGS, path.quote(file)) end local function exec_code(src) local tmpfile = path.tmpname() local f = assert(utils.write_file(tmpfile, src)) local a, b, c = exec_file(tmpfile) path.remove(tmpfile) return a, b, c end local _ENV = TEST_CASE'basic' do function test() local ok, status, msg = exec_code[[ local LOG = require"log".new('trace', require "log.writer.stdout".new() ) LOG.emerg("can not allocate memory") LOG.alert("can not allocate memory") LOG.fatal("can not allocate memory") LOG.error("file not found") LOG.warning("cache server is not started") LOG.notice("message has 2 file") LOG.info("new message is received") LOG.debug("message has 2 file") LOG.trace("message has 2 file") ]] assert_true(ok, msg) assert_match(DATE_PAT .. " %[EMERG%] can not allocate memory", msg) assert_match(DATE_PAT .. " %[ALERT%] can not allocate memory", msg) assert_match(DATE_PAT .. " %[FATAL%] can not allocate memory", msg) assert_match(DATE_PAT .. " %[ERROR%] file not found", msg) assert_match(DATE_PAT .. " %[WARNING%] cache server is not started", msg) assert_match(DATE_PAT .. " %[NOTICE%] message has 2 file", msg) assert_match(DATE_PAT .. " %[INFO%] new message is received", msg) assert_match(DATE_PAT .. " %[DEBUG%] message has 2 file", msg) assert_match(DATE_PAT .. " %[TRACE%] message has 2 file", msg) end function test_level() local ok, status, msg = exec_code[[ local LOG = require"log".new('notice', require "log.writer.stdout".new() ) LOG.emerg("can not allocate memory") LOG.alert("can not allocate memory") LOG.fatal("can not allocate memory") LOG.error("file not found") LOG.warning("cache server is not started") LOG.notice("message has 2 file") LOG.info("new message is received") LOG.debug("message has 2 file") LOG.trace("message has 2 file") ]] assert_true(ok, msg) assert_match(DATE_PAT .. " %[EMERG%] can not allocate memory", msg) assert_match(DATE_PAT .. " %[ALERT%] can not allocate memory", msg) assert_match(DATE_PAT .. " %[FATAL%] can not allocate memory", msg) assert_match(DATE_PAT .. " %[ERROR%] file not found", msg) assert_match(DATE_PAT .. " %[WARNING%] cache server is not started", msg) assert_match(DATE_PAT .. " %[NOTICE%] message has 2 file", msg) assert_not_match(DATE_PAT .. " %[INFO%] new message is received", msg) assert_not_match(DATE_PAT .. " %[DEBUG%] message has 2 file", msg) assert_not_match(DATE_PAT .. " %[TRACE%] message has 2 file", msg) end function test_formatter() local ok, status, msg = exec_code[[ local writer = require "log.writer.stdout".new() local LOG = require"log".new(writer, require "log.formatter.concat".new(':') ) local LOG_FMT = require"log".new(writer, require "log.formatter.format".new() ) LOG.info('new', 'message', 'is', 'received') LOG_FMT.notice("message has %d %s", 2, 'file') ]] assert_true(ok, msg) assert_match('new:message:is:received', msg) assert_match('message has 2 file', msg) end function test_async_zmq() local ok, status, msg = exec_code[[ local ztimer = require "lzmq.timer" local writer = require "log.writer.async.zmq".new('inproc://async.logger', "return require 'log.writer.stdout'.new()" ) ztimer.sleep(500) local LOG = require"log".new(writer) ztimer.sleep(500) LOG.fatal("can not allocate memory") ztimer.sleep(5000) require "lzmq.threads".context():destroy() ztimer.sleep(5000) ]] assert_true(ok, msg) assert_match('can not allocate memory', msg) end function test_async_udp() local ok, status, msg = exec_code[[ local writer = require "log.writer.async.udp".new('127.0.0.1', '5555', "return require 'log.writer.stdout'.new()" ) local LOG = require"log".new(writer) LOG.fatal("can not allocate memory") require 'lzmq.timer'.sleep(1000) ]] assert_true(ok, msg) assert_match('can not allocate memory', msg) end function test_async_lane() if _G.jit then return skip"FIXME: makes LuaLane work with LuaJIT" end local ok, status, msg = exec_code[[ local writer = require "log.writer.async.lane".new('lane.logger', "return require 'log.writer.stdout'.new()" ) local LOG = require"log".new(writer) LOG.fatal("can not allocate memory") require 'lzmq.timer'.sleep(1000) ]] assert_true(ok, msg) assert_match('can not allocate memory', msg) end function test_async_proxy() local ok, status, msg = exec_code[[ local zthreads = require "lzmq.threads" local ztimer = require 'lzmq.timer' -- create log thread local LOG = require"log".new( require "log.writer.async.zmq".new('inproc://async.logger', "return require 'log.writer.stdout'.new()" ) ) ztimer.sleep(500) -- log from separate thread via proxy local Thread = function() local LOG = require"log".new( require "log.writer.async.zmq".new('inproc://async.logger') ) LOG.error("(Thread) file not found") end local child_thread = zthreads.xrun(Thread):start() ztimer.sleep(500) LOG.fatal("can not allocate memory") child_thread:join() ztimer.sleep(5000) zthreads.context():destroy() ztimer.sleep(1500) ]] assert_true(ok, msg) assert_match('can not allocate memory', msg) assert_match('%(Thread%) file not found', msg) end function test_async_filter_le() local ok, status, msg = exec_code[[ local writer = require 'log.writer.stdout'.new() local Filter = require "log.writer.filter" local LOG = require"log".new( Filter.new('warning', writer) ) LOG.fatal("can not allocate memory") LOG.warning("cache server is not started") LOG.info("new message is received") require 'lzmq.timer'.sleep(1000) ]] assert_true(ok, msg) assert_match('can not allocate memory', msg) assert_match('cache server is not started', msg) assert_not_match('new message is received', msg) end function test_async_filter_eq() local ok, status, msg = exec_code[[ local writer = require 'log.writer.stdout'.new() local Filter = require "log.writer.filter.lvl.eq" local LOG = require"log".new( Filter.new('warning', writer) ) LOG.fatal("can not allocate memory") LOG.warning("cache server is not started") LOG.info("new message is received") require 'lzmq.timer'.sleep(1000) ]] assert_true(ok, msg) assert_not_match('can not allocate memory', msg) assert_match('cache server is not started', msg) assert_not_match('new message is received', msg) end function test_formatter_mix() local ok, status, msg = exec_code[[ local LOG = require"log".new('trace', require "log.writer.stdout".new(), require "log.formatter.mix".new() ) LOG.emerg("can not allocate memory") LOG.alert(function(str) return str end, "can not allocate memory") LOG.fatal("can not allocate %s", "memory") ]] assert_true(ok, msg) assert_match(DATE_PAT .. " %[EMERG%] can not allocate memory", msg) assert_match(DATE_PAT .. " %[ALERT%] can not allocate memory", msg) assert_match(DATE_PAT .. " %[FATAL%] can not allocate memory", msg) end end local _ENV = TEST_CASE'protected formatter' do function test_do_not_raise_error_nil_argument() local formatter = require "log.formatter.pformat".new() local msg assert_pass(function() msg = formatter("%d", nil) end) assert_string(msg) local expected = tostring(nil) assert_equal(expected, string.sub(msg,1, #expected)) assert_match('Error formatting log message', msg) end function test_do_not_raise_error_unknown_format() local formatter = require "log.formatter.pformat".new() local msg assert_pass(function() msg = formatter("%t", 10) end) assert_string(msg) local expected = "%t" assert_equal(expected, string.sub(msg,1, #expected)) assert_match('Error formatting log message', msg) end function test_do_not_raise_error_and_no_warning_nil_argument() local formatter = require "log.formatter.pformat".new(nil, true) local msg assert_pass(function() msg = formatter("%t", nil) end) assert_string(msg) local expected = '%t' assert_equal(expected, msg) end function test_do_not_raise_error_and_no_warning_unknown_format() local formatter = require "log.formatter.pformat".new(nil, true) local msg assert_pass(function() msg = formatter("%t", 10) end) assert_string(msg) local expected = '%t' assert_equal(expected, msg) end function test_do_not_raise_error_nil_argument_2() local formatter = require "log.formatter.pformat".new(true) local msg assert_pass(function() msg = formatter("%d", nil) end) assert_string(msg) local expected = tostring(nil) assert_equal(expected, string.sub(msg,1, #expected)) assert_match('Error formatting log message', msg) end function test_raise_error_unknown_format() local formatter = require "log.formatter.pformat".new(true) local msg = assert_error(function() msg = formatter("%t", 10) end) end end if not HAS_RUNNER then lunit.run() end
mit
TheWaffleDimension/lua-dungeon-crawler
game/classes/map_loader.lua
1
4173
local tml = {} local maps = {} local tilesets = {} function tml:getMap(name) end local function loadLayer(layerData) if not layerData then return nil end local layer = {} layer.name = tostring(layerData.name):lower() layer.type = layerData.type layer.x = layerData.x layer.y = layerData.y layer.offsetX = layerData.offsetx layer.offsetY = layerData.offsety layer.w = layerData.width layer.h = layerData.height layer.data = layerData.data layer.solid = false if layer.name == "solid" or layerData.properties["solid"] == true then layer.solid = true end layer.transparency = ( 1 - layerData.opacity) layer.visible = layerData.visible return layer end function tml:load(name) local map = {} local mapFile = require("assets.maps." .. name) map.id = mapFile.properties["id"] or nil if not tilesets[mapFile.tilesets[1].name] then map.tileset = mapFile.tilesets[1] local fileName = helper:stringSplit(map.tileset.image, "/")[#helper:stringSplit(map.tileset.image, "/")] map.tileset.image = love.graphics.newImage("assets/images/" .. fileName) tilesets[map.tileset.name] = map.tileset else map.tileset = tilesets[mapFile.tilesets[1].name] end map.layers = {} map.tiles = {} map.solid_tiles = {} map.tsX = mapFile.tilewidth map.tsY = mapFile.tileheight map.scaleFactor = tileSize / ((map.tsX + map.tsY)/2) map.properties = {} for i,v in pairs(mapFile.properties) do map.properties[tostring(i)] = v end map.quads = helper:generateQuads( math.floor(map.tsX), math.floor(map.tsY), map.tileset.image, map.tileset.spacing, map.tileset.margin ) for i,v in pairs(mapFile.layers) do local layer = loadLayer(v) if layer ~= nil then local numOfTilesInLayer = layer.w * layer.h for y = 0, layer.h - 1 do for x = 0, layer.w - 1 do local tile = {} tile.x = x tile.y = y tile.id = ((x + (y * layer.w)) + 1) tile.image = layer.data[tile.id] tile.layer = layer if tile.image ~= 0 then if layer.solid == true then table.insert(map.solid_tiles, tile) end map.tiles[tile.id * 10^((i - 1)*10)] = tile end end end table.insert(map.layers, layer) end end for i,v in pairs(map.solid_tiles) do world:add(v, ((v.x * map.tsX) + v.layer.offsetX) * map.scaleFactor * camera.scaleX, ((v.y * map.tsY) + v.layer.offsetY) * map.scaleFactor * camera.scaleY, tileSize*camera.scaleX, tileSize*camera.scaleY) end function map:draw(optionalScale) local skipped = {} optionalScale = optionalScale*2 or 1 for i,v in pairs(self.tiles) do if v.image ~= 0 then if v.layer.solid then table.insert(skipped, v) else love.graphics.draw(self.tileset.image, self.quads[v.image], ((v.x * self.tsX) + v.layer.offsetX) * optionalScale, ((v.y * self.tsY) + v.layer.offsetY) * optionalScale, 0, optionalScale, optionalScale) end end end for i,v in pairs(skipped) do if v.image ~= 0 then love.graphics.draw(self.tileset.image, self.quads[v.image], ((v.x * self.tsX) + v.layer.offsetX) * optionalScale, ((v.y * self.tsY) + v.layer.offsetY) * optionalScale, 0, optionalScale, optionalScale) end end end function map:update(dt) for i,v in pairs(self.solid_tiles) do --love.graphics.draw(self.tileset.image, self.quads[v.image], ((v.x * self.tsX) + v.layer.offsetX) * optionalScale, ((v.y * self.tsY) + v.layer.offsetY) * optionalScale, 0, optionalScale, optionalScale) local exists = world:hasItem(v) if exists then world:update(v, ((v.x * map.tsX) + v.layer.offsetX) * map.scaleFactor * camera.scaleX, ((v.y * map.tsY) + v.layer.offsetY) * map.scaleFactor * camera.scaleY, tileSize*camera.scaleX, tileSize*camera.scaleY) end end end function map:unload() for i,v in pairs(self.solid_tiles) do --love.graphics.draw(self.tileset.image, self.quads[v.image], ((v.x * self.tsX) + v.layer.offsetX) * optionalScale, ((v.y * self.tsY) + v.layer.offsetY) * optionalScale, 0, optionalScale, optionalScale) local exists = world:hasItem(v) if exists then world:remove(v) end end end table.insert(maps, map) return map end return tml
mit
TylerR909/AppearanceSets_HideHelm
Libs/AceComm-3.0/AceComm-3.0.lua
20
10890
--- **AceComm-3.0** allows you to send messages of unlimited length over the addon comm channels. -- It'll automatically split the messages into multiple parts and rebuild them on the receiving end.\\ -- **ChatThrottleLib** is of course being used to avoid being disconnected by the server. -- -- **AceComm-3.0** can be embeded into your addon, either explicitly by calling AceComm:Embed(MyAddon) or by -- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object -- and can be accessed directly, without having to explicitly call AceComm itself.\\ -- It is recommended to embed AceComm, otherwise you'll have to specify a custom `self` on all calls you -- make into AceComm. -- @class file -- @name AceComm-3.0 -- @release $Id: AceComm-3.0.lua 1107 2014-02-19 16:40:32Z nevcairiel $ --[[ AceComm-3.0 TODO: Time out old data rotting around from dead senders? Not a HUGE deal since the number of possible sender names is somewhat limited. ]] local MAJOR, MINOR = "AceComm-3.0", 9 local AceComm,oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceComm then return end local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0") local CTL = assert(ChatThrottleLib, "AceComm-3.0 requires ChatThrottleLib") -- Lua APIs local type, next, pairs, tostring = type, next, pairs, tostring local strsub, strfind = string.sub, string.find local match = string.match local tinsert, tconcat = table.insert, table.concat local error, assert = error, assert -- WoW APIs local Ambiguate = Ambiguate -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: LibStub, DEFAULT_CHAT_FRAME, geterrorhandler, RegisterAddonMessagePrefix AceComm.embeds = AceComm.embeds or {} -- for my sanity and yours, let's give the message type bytes some names local MSG_MULTI_FIRST = "\001" local MSG_MULTI_NEXT = "\002" local MSG_MULTI_LAST = "\003" local MSG_ESCAPE = "\004" -- remove old structures (pre WoW 4.0) AceComm.multipart_origprefixes = nil AceComm.multipart_reassemblers = nil -- the multipart message spool: indexed by a combination of sender+distribution+ AceComm.multipart_spool = AceComm.multipart_spool or {} --- Register for Addon Traffic on a specified prefix -- @param prefix A printable character (\032-\255) classification of the message (typically AddonName or AddonNameEvent), max 16 characters -- @param method Callback to call on message reception: Function reference, or method name (string) to call on self. Defaults to "OnCommReceived" function AceComm:RegisterComm(prefix, method) if method == nil then method = "OnCommReceived" end if #prefix > 16 then -- TODO: 15? error("AceComm:RegisterComm(prefix,method): prefix length is limited to 16 characters") end RegisterAddonMessagePrefix(prefix) return AceComm._RegisterComm(self, prefix, method) -- created by CallbackHandler end local warnedPrefix=false --- Send a message over the Addon Channel -- @param prefix A printable character (\032-\255) classification of the message (typically AddonName or AddonNameEvent) -- @param text Data to send, nils (\000) not allowed. Any length. -- @param distribution Addon channel, e.g. "RAID", "GUILD", etc; see SendAddonMessage API -- @param target Destination for some distributions; see SendAddonMessage API -- @param prio OPTIONAL: ChatThrottleLib priority, "BULK", "NORMAL" or "ALERT". Defaults to "NORMAL". -- @param callbackFn OPTIONAL: callback function to be called as each chunk is sent. receives 3 args: the user supplied arg (see next), the number of bytes sent so far, and the number of bytes total to send. -- @param callbackArg: OPTIONAL: first arg to the callback function. nil will be passed if not specified. function AceComm:SendCommMessage(prefix, text, distribution, target, prio, callbackFn, callbackArg) prio = prio or "NORMAL" -- pasta's reference implementation had different prio for singlepart and multipart, but that's a very bad idea since that can easily lead to out-of-sequence delivery! if not( type(prefix)=="string" and type(text)=="string" and type(distribution)=="string" and (target==nil or type(target)=="string") and (prio=="BULK" or prio=="NORMAL" or prio=="ALERT") ) then error('Usage: SendCommMessage(addon, "prefix", "text", "distribution"[, "target"[, "prio"[, callbackFn, callbackarg]]])', 2) end local textlen = #text local maxtextlen = 255 -- Yes, the max is 255 even if the dev post said 256. I tested. Char 256+ get silently truncated. /Mikk, 20110327 local queueName = prefix..distribution..(target or "") local ctlCallback = nil if callbackFn then ctlCallback = function(sent) return callbackFn(callbackArg, sent, textlen) end end local forceMultipart if match(text, "^[\001-\009]") then -- 4.1+: see if the first character is a control character -- we need to escape the first character with a \004 if textlen+1 > maxtextlen then -- would we go over the size limit? forceMultipart = true -- just make it multipart, no escape problems then else text = "\004" .. text end end if not forceMultipart and textlen <= maxtextlen then -- fits all in one message CTL:SendAddonMessage(prio, prefix, text, distribution, target, queueName, ctlCallback, textlen) else maxtextlen = maxtextlen - 1 -- 1 extra byte for part indicator in prefix(4.0)/start of message(4.1) -- first part local chunk = strsub(text, 1, maxtextlen) CTL:SendAddonMessage(prio, prefix, MSG_MULTI_FIRST..chunk, distribution, target, queueName, ctlCallback, maxtextlen) -- continuation local pos = 1+maxtextlen while pos+maxtextlen <= textlen do chunk = strsub(text, pos, pos+maxtextlen-1) CTL:SendAddonMessage(prio, prefix, MSG_MULTI_NEXT..chunk, distribution, target, queueName, ctlCallback, pos+maxtextlen-1) pos = pos + maxtextlen end -- final part chunk = strsub(text, pos) CTL:SendAddonMessage(prio, prefix, MSG_MULTI_LAST..chunk, distribution, target, queueName, ctlCallback, textlen) end end ---------------------------------------- -- Message receiving ---------------------------------------- do local compost = setmetatable({}, {__mode = "k"}) local function new() local t = next(compost) if t then compost[t]=nil for i=#t,3,-1 do -- faster than pairs loop. don't even nil out 1/2 since they'll be overwritten t[i]=nil end return t end return {} end local function lostdatawarning(prefix,sender,where) DEFAULT_CHAT_FRAME:AddMessage(MAJOR..": Warning: lost network data regarding '"..tostring(prefix).."' from '"..tostring(sender).."' (in "..where..")") end function AceComm:OnReceiveMultipartFirst(prefix, message, distribution, sender) local key = prefix.."\t"..distribution.."\t"..sender -- a unique stream is defined by the prefix + distribution + sender local spool = AceComm.multipart_spool --[[ if spool[key] then lostdatawarning(prefix,sender,"First") -- continue and overwrite end --]] spool[key] = message -- plain string for now end function AceComm:OnReceiveMultipartNext(prefix, message, distribution, sender) local key = prefix.."\t"..distribution.."\t"..sender -- a unique stream is defined by the prefix + distribution + sender local spool = AceComm.multipart_spool local olddata = spool[key] if not olddata then --lostdatawarning(prefix,sender,"Next") return end if type(olddata)~="table" then -- ... but what we have is not a table. So make it one. (Pull a composted one if available) local t = new() t[1] = olddata -- add old data as first string t[2] = message -- and new message as second string spool[key] = t -- and put the table in the spool instead of the old string else tinsert(olddata, message) end end function AceComm:OnReceiveMultipartLast(prefix, message, distribution, sender) local key = prefix.."\t"..distribution.."\t"..sender -- a unique stream is defined by the prefix + distribution + sender local spool = AceComm.multipart_spool local olddata = spool[key] if not olddata then --lostdatawarning(prefix,sender,"End") return end spool[key] = nil if type(olddata) == "table" then -- if we've received a "next", the spooled data will be a table for rapid & garbage-free tconcat tinsert(olddata, message) AceComm.callbacks:Fire(prefix, tconcat(olddata, ""), distribution, sender) compost[olddata] = true else -- if we've only received a "first", the spooled data will still only be a string AceComm.callbacks:Fire(prefix, olddata..message, distribution, sender) end end end ---------------------------------------- -- Embed CallbackHandler ---------------------------------------- if not AceComm.callbacks then AceComm.callbacks = CallbackHandler:New(AceComm, "_RegisterComm", "UnregisterComm", "UnregisterAllComm") end AceComm.callbacks.OnUsed = nil AceComm.callbacks.OnUnused = nil local function OnEvent(self, event, prefix, message, distribution, sender) if event == "CHAT_MSG_ADDON" then sender = Ambiguate(sender, "none") local control, rest = match(message, "^([\001-\009])(.*)") if control then if control==MSG_MULTI_FIRST then AceComm:OnReceiveMultipartFirst(prefix, rest, distribution, sender) elseif control==MSG_MULTI_NEXT then AceComm:OnReceiveMultipartNext(prefix, rest, distribution, sender) elseif control==MSG_MULTI_LAST then AceComm:OnReceiveMultipartLast(prefix, rest, distribution, sender) elseif control==MSG_ESCAPE then AceComm.callbacks:Fire(prefix, rest, distribution, sender) else -- unknown control character, ignore SILENTLY (dont warn unnecessarily about future extensions!) end else -- single part: fire it off immediately and let CallbackHandler decide if it's registered or not AceComm.callbacks:Fire(prefix, message, distribution, sender) end else assert(false, "Received "..tostring(event).." event?!") end end AceComm.frame = AceComm.frame or CreateFrame("Frame", "AceComm30Frame") AceComm.frame:SetScript("OnEvent", OnEvent) AceComm.frame:UnregisterAllEvents() AceComm.frame:RegisterEvent("CHAT_MSG_ADDON") ---------------------------------------- -- Base library stuff ---------------------------------------- local mixins = { "RegisterComm", "UnregisterComm", "UnregisterAllComm", "SendCommMessage", } -- Embeds AceComm-3.0 into the target object making the functions from the mixins list available on target:.. -- @param target target object to embed AceComm-3.0 in function AceComm:Embed(target) for k, v in pairs(mixins) do target[v] = self[v] end self.embeds[target] = true return target end function AceComm:OnEmbedDisable(target) target:UnregisterAllComm() end -- Update embeds for target, v in pairs(AceComm.embeds) do AceComm:Embed(target) end
mit
lxl1140989/dmsdk
feeds/luci/modules/freifunk/luasrc/model/cbi/freifunk/basics.lua
74
3518
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Manuel Munz <freifunk at somakoma de> 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 ]] local fs = require "luci.fs" local util = require "luci.util" local uci = require "luci.model.uci".cursor() local profiles = "/etc/config/profile_" m = Map("freifunk", translate ("Community")) c = m:section(NamedSection, "community", "public", nil, translate("These are the basic settings for your local wireless community. These settings define the default values for the wizard and DO NOT affect the actual configuration of the router.")) community = c:option(ListValue, "name", translate ("Community")) community.rmempty = false local list = { } local list = fs.glob(profiles .. "*") for k,v in ipairs(list) do local name = uci:get_first(v, "community", "name") or "?" local n = string.gsub(v, profiles, "") community:value(n, name) end n = Map("system", translate("Basic system settings")) function n.on_after_commit(self) luci.http.redirect(luci.dispatcher.build_url("admin", "freifunk", "basics")) end b = n:section(TypedSection, "system") b.anonymous = true hn = b:option(Value, "hostname", translate("Hostname")) hn.rmempty = false hn.datatype = "hostname" loc = b:option(Value, "location", translate("Location")) loc.rmempty = false loc.datatype = "minlength(1)" lat = b:option(Value, "latitude", translate("Latitude"), translate("e.g.") .. " 48.12345") lat.datatype = "float" lat.rmempty = false lon = b:option(Value, "longitude", translate("Longitude"), translate("e.g.") .. " 10.12345") lon.datatype = "float" lon.rmempty = false --[[ Opens an OpenStreetMap iframe or popup Makes use of resources/OSMLatLon.htm and htdocs/resources/osm.js ]]-- local class = util.class local ff = uci:get("freifunk", "community", "name") or "" local co = "profile_" .. ff local deflat = uci:get_first("system", "system", "latitude") or uci:get_first(co, "community", "latitude") or 52 local deflon = uci:get_first("system", "system", "longitude") or uci:get_first(co, "community", "longitude") or 10 local zoom = 12 if ( deflat == 52 and deflon == 10 ) then zoom = 4 end OpenStreetMapLonLat = luci.util.class(AbstractValue) function OpenStreetMapLonLat.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/osmll_value" self.latfield = nil self.lonfield = nil self.centerlat = "" self.centerlon = "" self.zoom = "0" self.width = "100%" --popups will ignore the %-symbol, "100%" is interpreted as "100" self.height = "600" self.popup = false self.displaytext="OpenStreetMap" --text on button, that loads and displays the OSMap self.hidetext="X" -- text on button, that hides OSMap end osm = b:option(OpenStreetMapLonLat, "latlon", translate("Find your coordinates with OpenStreetMap"), translate("Select your location with a mouse click on the map. The map will only show up if you are connected to the Internet.")) osm.latfield = "latitude" osm.lonfield = "longitude" osm.centerlat = uci:get_first("system", "system", "latitude") or deflat osm.centerlon = uci:get_first("system", "system", "longitude") or deflon osm.zoom = zoom osm.width = "100%" osm.height = "600" osm.popup = false osm.displaytext=translate("Show OpenStreetMap") osm.hidetext=translate("Hide OpenStreetMap") return m, n
gpl-2.0
Anarchid/Zero-K
LuaUI/Widgets/chili/Skins/Evolved/skin.lua
8
18360
--// ============================================================================= --// Skin local skin = { info = { name = "Evolved", version = "0.3", author = "jK", } } --// ============================================================================= --// skin.general = { focusColor = {0.94, 0.50, 0.23, 1}, borderColor = {1.0, 1.0, 1.0, 1.0}, font = { --font = SKINDIR .. "fonts/n019003l.pfb", color = {1, 1, 1, 1}, outlineColor = {0.05, 0.05, 0.05, 0.9}, outline = false, shadow = true, size = 13, }, --padding = {5, 5, 5, 5}, --// padding: left, top, right, bottom } skin.icons = { imageplaceholder = ":cl:placeholder.png", } skin.button = { TileImageBK = ":cl:tech_button_bright_small_bk.png", TileImageFG = ":cl:tech_button_bright_small_fg.png", tiles = {20, 14, 20, 14}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {0.20, 0.38, 0.46, 0.95}, focusColor = {0.20, 0.42, 0.50, 0.9}, borderColor = {0.20, 0.42, 0.50, 0.15}, pressBackgroundColor = {0.14, 0.365, 0.42, 0.85}, DrawControl = DrawButton, } skin.button_tiny = { TileImageBK = ":cl:tech_button_bright_tiny_bk.png", TileImageFG = ":cl:tech_button_bright_tiny_fg.png", tiles = {12, 12, 12, 12}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {0.20, 0.38, 0.46, 0.95}, focusColor = {0.20, 0.42, 0.50, 0.9}, borderColor = {0.20, 0.42, 0.50, 0.15}, pressBackgroundColor = {0.14, 0.365, 0.42, 0.85}, DrawControl = DrawButton, } skin.overlay_button = { TileImageBK = ":cl:tech_button_small_bk.png", TileImageFG = ":cl:tech_button_small_fg.png", tiles = {20, 14, 20, 14}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {0, 0, 0, 0.7}, focusColor = {0.94, 0.50, 0.23, 0.7}, borderColor = {1, 1, 1, 0}, DrawControl = DrawButton, } skin.overlay_button_tiny = { TileImageBK = ":cl:tech_button_tiny_bk.png", TileImageFG = ":cl:tech_button_tiny_fg.png", tiles = {12, 12, 12, 12}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {0, 0, 0, 0.7}, focusColor = {0.94, 0.50, 0.23, 0.7}, borderColor = {1, 1, 1, 0}, DrawControl = DrawButton, } skin.button_square = { TileImageBK = ":cl:tech_button_action_bk.png", TileImageFG = ":cl:tech_button_action_fg.png", tiles = {22, 22, 22, 22}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {0, 0, 0, 0.7}, focusColor = {0.94, 0.50, 0.23, 0.4}, borderColor = {1, 1, 1, 0}, DrawControl = DrawButton, } skin.button_tab = { -- yes these are reverted, but also a lie (see images), only one is used TileImageFG = ":cl:tech_tabbaritem_fg.png", TileImageBK = ":cl:tech_tabbaritem_bk.png", tiles = {10, 10, 10, 0}, --// tile widths: left, top, right, bottom padding = {1, 1, 1, 2}, -- since it's color multiplication, it's easier to control white color (1, 1, 1) than black color (0, 0, 0) to get desired results backgroundColor = {0, 0, 0, 1.0}, -- actually kill this anyway borderColor = {0.46, 0.54, 0.68, 0.4}, focusColor = {0.46, 0.54, 0.68, 1.0}, DrawControl = DrawButton, } skin.button_large = { TileImageBK = ":cl:tech_button_bk.png", TileImageFG = ":cl:tech_button_fg.png", tiles = {120, 60, 120, 60}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {0, 0, 0, 0.7}, focusColor = {0.94, 0.50, 0.23, 0.7}, borderColor = {1, 1, 1, 0}, DrawControl = DrawButton, } skin.button_highlight = { TileImageBK = ":cl:tech_button_bright_small_bk.png", TileImageFG = ":cl:tech_button_bright_small_fg.png", tiles = {20, 14, 20, 14}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {0.2, 0.25, 0.35, 0.7}, focusColor = {0.3, 0.375, 0.525, 0.5}, borderColor = {1, 1, 1, 0}, DrawControl = DrawButton, } skin.button_square = { TileImageBK = ":cl:tech_button_action_bk.png", TileImageFG = ":cl:tech_button_action_fg.png", tiles = {20, 14, 20, 14}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {0, 0, 0, 0.7}, focusColor = {0.94, 0.50, 0.23, 0.4}, borderColor = {1, 1, 1, 0}, DrawControl = DrawButton, } skin.action_button = { TileImageBK = ":cl:tech_button_bright_small_bk.png", TileImageFG = ":cl:tech_button_bright_small_fg.png", tiles = {20, 14, 20, 14}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {0.98, 0.48, 0.26, 0.65}, focusColor = {0.98, 0.48, 0.26, 0.9}, borderColor = {0.98, 0.48, 0.26, 0.15}, DrawControl = DrawButton, } skin.option_button = { TileImageBK = ":cl:tech_button_bright_small_bk.png", TileImageFG = ":cl:tech_button_bright_small_fg.png", tiles = {20, 14, 20, 14}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {0.21, 0.53, 0.60, 0.65}, focusColor = {0.21, 0.53, 0.60, 0.9}, borderColor = {0.21, 0.53, 0.60, 0.15}, DrawControl = DrawButton, } skin.negative_button = { TileImageBK = ":cl:tech_button_bright_small_bk.png", TileImageFG = ":cl:tech_button_bright_small_fg.png", tiles = {20, 14, 20, 14}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {0.85, 0.05, 0.25, 0.65}, focusColor = {0.85, 0.05, 0.25, 0.9}, borderColor = {0.85, 0.05, 0.25, 0.15}, DrawControl = DrawButton, } skin.button_disabled = { TileImageBK = ":cl:tech_button_bright_small_bk.png", TileImageFG = ":cl:tech_button_bright_small_fg.png", tiles = {20, 14, 20, 14}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {0.2, 0.2, 0.2, 0.65}, focusColor = {0, 0, 0, 0}, borderColor = {0.2, 0.2, 0.2, 0.15}, DrawControl = DrawButton, } skin.combobox = { TileImageBK = ":cl:combobox_ctrl.png", TileImageFG = ":cl:combobox_ctrl_fg.png", TileImageArrow = ":cl:combobox_ctrl_arrow.png", tiles = {22, 22, 48, 22}, padding = {10, 10, 24, 10}, backgroundColor = {1, 1, 1, 0.7}, borderColor = {1, 1, 1, 0}, DrawControl = DrawComboBox, } skin.combobox_window = { clone = "window"; TileImage = ":cl:combobox_wnd.png"; tiles = {2, 2, 2, 2}; padding = {4, 3, 3, 4}; } skin.combobox_scrollpanel = { clone = "scrollpanel"; borderColor = {1, 1, 1, 0}; padding = {0, 0, 0, 0}; } skin.combobox_item = { clone = "button"; borderColor = {1, 1, 1, 0}; } skin.checkbox = { TileImageFG = ":cl:checkbox_arrow.png", TileImageBK = ":cl:checkbox.png", TileImageFG_round = ":cl:radiobutton_checked.png", TileImageBK_round = ":cl:radiobutton.png", tiles = {3, 3, 3, 3}, boxsize = 13, DrawControl = DrawCheckbox, } skin.editbox = { hintFont = table.merge({color = {1, 1, 1, 0.7}}, skin.general.font), backgroundColor = {0.1, 0.1, 0.1, 0}, cursorColor = {1.0, 0.7, 0.1, 0.8}, focusColor = {1, 1, 1, 1}, borderColor = {1, 1, 1, 0.6}, TileImageBK = ":cl:panel2_bg.png", TileImageFG = ":cl:editbox_border.png", tiles = {2, 2, 2, 2}, cursorFramerate = 1, -- Per second DrawControl = DrawEditBox, } skin.textbox = { hintFont = table.merge({color = {1, 1, 1, 0.7}}, skin.general.font), TileImageBK = ":cl:panel2_bg.png", bkgndtiles = {14, 14, 14, 14}, TileImageFG = ":cl:panel2_border.png", tiles = {2, 2, 2, 2}, borderColor = {0.0, 0.0, 0.0, 0.0}, focusColor = {0.0, 0.0, 0.0, 0.0}, DrawControl = DrawEditBox, } skin.imagelistview = { imageFolder = "folder.png", imageFolderUp = "folder_up.png", --DrawControl = DrawBackground, colorBK = {1, 1, 1, 0.3}, colorBK_selected = {1, 0.7, 0.1, 0.8}, colorFG = {0, 0, 0, 0}, colorFG_selected = {1, 1, 1, 1}, imageBK = ":cl:node_selected_bw.png", imageFG = ":cl:node_selected.png", tiles = {9, 9, 9, 9}, DrawItemBackground = DrawItemBkGnd, } --[[ skin.imagelistviewitem = { imageFG = ":cl:glassFG.png", imageBK = ":cl:glassBK.png", tiles = {17, 15, 17, 20}, padding = {12, 12, 12, 12}, DrawSelectionItemBkGnd = DrawSelectionItemBkGnd, } --]] skin.panel = { TileImageBK = ":c:tech_overlaywindow.png", TileImageFG = ":cl:empty.png", tiles = {2, 2, 2, 2}, backgroundColor = {1, 1, 1, 0.7}, DrawControl = DrawPanel, } skin.panel_internal = { TileImageBK = ":c:tech_overlaywindow.png", TileImageFG = ":cl:empty.png", tiles = {2, 2, 2, 2}, backgroundColor = {1, 1, 1, 0.6}, DrawControl = DrawPanel, } skin.panel_button = { TileImageBK = ":cl:tech_button_bright_small_bk.png", TileImageFG = ":cl:tech_button_bright_small_fg.png", tiles = {20, 14, 20, 14}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {0.2, 0.25, 0.35, 0.7}, focusColor = {0.3, 0.375, 0.525, 0.5}, borderColor = {1, 1, 1, 0}, DrawControl = DrawPanel, } skin.panel_button_rounded = { TileImageBK = ":cl:tech_button_rounded.png", TileImageFG = ":cl:tech_buttonbk_rounded.png", tiles = {32, 32, 32, 32}, --// tile widths: left, top, right, bottom padding = {10, 10, 10, 10}, backgroundColor = {1, 1, 1, 1.0}, focusColor = {0.3, 0.375, 0.525, 0.5}, borderColor = {1, 1, 1, 0}, DrawControl = DrawPanel, } skin.panelSmall = { TileImageBK = ":cl:tech_button.png", TileImageFG = ":cl:empty.png", tiles = {2, 2, 2, 2}, DrawControl = DrawPanel, } skin.overlay_panel = { TileImageBK = ":c:tech_overlaywindow.png", TileImageFG = ":cl:empty.png", tiles = {2, 2, 2, 2}, --// tile widths: left, top, right, bottom backgroundColor = {1, 1, 1, 0.7}, DrawControl = DrawPanel, } local fancyBase = { TileImageFG = ":cl:empty.png", tiles = {32, 32, 32, 32}, DrawControl = DrawPanel, backgroundColor = {1, 1, 1, 1}, } local fancySmallBase = { TileImageFG = ":cl:empty.png", tiles = {16, 16, 16, 16}, DrawControl = DrawPanel, backgroundColor = {1, 1, 1, 1}, } local fancyPanels = { {"0100", {30, 8, 30, 1}, {0, 4, 0, 0}}, {"0110", {156, 36, 1, 1}, {0, 10, 0, 0}}, {"1100", {1, 36, 156, 1}, {0, 10, 0, 0}}, {"0120", {212, 36, 212, 1}, {6, 16, 0, 0}}, {"2100", {212, 36, 212, 1}, {0, 16, 6, 0}}, {"1011", {172, 1, 172, 37}, {8, 0, 8, 4}}, {"2011", {172, 1, 8, 37}, {4, 0, 8, 4}}, {"1021", {8, 1, 172, 37}, {8, 0, 4, 4}}, } local fancyPanelsSmall = { {"0011_small", {175, 1, 102, 10}, {12, 0, 0, 6}}, {"1001_small", {102, 1, 175, 10}, {0, 0, 12, 6}}, {"0110_small", {58, 36, 1, 1}, {12, 4, 0, 0}}, {"1100_small", {1, 36, 58, 1}, {0, 4, 12, 0}}, {"0120_small", {80, 36, 80, 1}, {0, 10, 0, 0}}, {"2100_small", {80, 36, 80, 1}, {0, 10, 0, 0}}, {"0001_small", {92, 1, 92, 10}, {0, 0, 0, 6}}, } local fancyPanelsLarge = { {"0110_large", {156, 36, 1, 1}, {11, 7, 0, 0}}, {"1100_large", {1, 36, 156, 1}, {0, 7, 11, 0}}, } local function LoadPanels(panelList) for i = 1, #panelList do if type(fancyPanels[i]) == "string" then local name = "panel_" .. panelList[i] skin[name] = Spring.Utilities.CopyTable(fancyBase) skin[name].TileImageBK = ":cl:" .. name .. ".png" else local name = "panel_" .. panelList[i][1] skin[name] = Spring.Utilities.CopyTable(fancyBase) skin[name].tiles = panelList[i][2] skin[name].padding = panelList[i][3] skin[name].TileImageBK = ":cl:" .. name .. ".png" end end end LoadPanels(fancyPanels) LoadPanels(fancyPanelsSmall) LoadPanels(fancyPanelsLarge) for i = 1, #fancyPanelsSmall do if type(fancyPanelsSmall[i]) == "string" then local name = "panel_" .. fancyPanelsSmall[i] skin[name] = Spring.Utilities.CopyTable(fancySmallBase) skin[name].TileImageBK = ":cl:" .. name .. ".png" else local name = "panel_" .. fancyPanelsSmall[i][1] skin[name] = Spring.Utilities.CopyTable(fancySmallBase) skin[name].tiles = fancyPanelsSmall[i][2] skin[name].padding = fancyPanelsSmall[i][3] skin[name].TileImageBK = ":cl:" .. name .. ".png" end end skin.progressbar = { TileImageFG = ":cl:tech_progressbar_full.png", TileImageBK = ":cl:tech_progressbar_empty.png", tiles = {14, 8, 14, 8}, fillPadding = {4, 3, 4, 3}, font = { shadow = true, }, DrawControl = DrawProgressbar, } skin.multiprogressbar = { fillPadding = {4, 3, 4, 3}, } skin.scrollpanel = { BorderTileImage = ":cl:panel2_border.png", bordertiles = {2, 2, 2, 2}, BackgroundTileImage = ":cl:panel2_bg.png", bkgndtiles = {14, 14, 14, 14}, TileImage = ":cl:tech_scrollbar.png", tiles = {7, 7, 7, 7}, KnobTileImage = ":cl:tech_scrollbar_knob.png", KnobTiles = {6, 8, 6, 8}, HTileImage = ":cl:tech_scrollbar.png", htiles = {7, 7, 7, 7}, HKnobTileImage = ":cl:tech_scrollbar_knob.png", HKnobTiles = {6, 8, 6, 8}, KnobColorSelected = {1, 0.7, 0.1, 0.8}, padding = {5, 5, 5, 0}, scrollbarSize = 11, DrawControl = DrawScrollPanel, DrawControlPostChildren = DrawScrollPanelBorder, } skin.trackbar = { TileImage = ":cl:trackbar.png", tiles = {16, 16, 16, 16}, --// tile widths: left, top, right, bottom ThumbImage = ":cl:trackbar_thumb.png", StepImage = ":cl:trackbar_step.png", hitpadding = {4, 4, 5, 4}, DrawControl = DrawTrackbar, } skin.treeview = { --ImageNode = ":cl:node.png", ImageNodeSelected = ":cl:node_selected.png", tiles = {9, 9, 9, 9}, ImageExpanded = ":cl:treeview_node_expanded.png", ImageCollapsed = ":cl:treeview_node_collapsed.png", treeColor = {1, 1, 1, 0.1}, DrawNode = DrawTreeviewNode, DrawNodeTree = DrawTreeviewNodeTree, } skin.window = { TileImage = ":c:tech_overlaywindow.png", tiles = {2, 2, 2, 2}, --// tile widths: left, top, right, bottom padding = {13, 13, 13, 13}, hitpadding = {4, 4, 4, 4}, captionColor = {1, 1, 1, 0.45}, color = {1, 1, 1, 0.7}, boxes = { resize = {-21, -21, -10, -10}, drag = {0, 0, "100%", 10}, }, NCHitTest = NCHitTestWithPadding, NCMouseDown = WindowNCMouseDown, NCMouseDownPostChildren = WindowNCMouseDownPostChildren, DrawControl = DrawWindow, DrawDragGrip = function() end, DrawResizeGrip = DrawResizeGrip, } skin.main_window_small = { TileImage = ":c:tech_mainwindow_small.png", tiles = {76, 40, 76, 40}, --// tile widths: left, top, right, bottom padding = {10, 6, 10, 6}, hitpadding = {4, 4, 4, 4}, captionColor = {1, 1, 1, 0.45}, backgroundColor = {0.1, 0.1, 0.1, 0.7}, boxes = { resize = {-23, -19, -12, -8}, drag = {0, 0, "100%", 10}, }, NCHitTest = NCHitTestWithPadding, NCMouseDown = WindowNCMouseDown, NCMouseDownPostChildren = WindowNCMouseDownPostChildren, DrawControl = DrawWindow, DrawDragGrip = function() end, DrawResizeGrip = DrawResizeGrip, } skin.main_window_small_tall = { TileImage = ":c:tech_mainwindow_small_tall.png", tiles = {40, 40, 40, 40}, --// tile widths: left, top, right, bottom padding = {10, 6, 10, 6}, hitpadding = {4, 4, 4, 4}, captionColor = {1, 1, 1, 0.45}, backgroundColor = {0.1, 0.1, 0.1, 0.7}, boxes = { resize = {-23, -19, -12, -8}, drag = {0, 0, "100%", 10}, }, NCHitTest = NCHitTestWithPadding, NCMouseDown = WindowNCMouseDown, NCMouseDownPostChildren = WindowNCMouseDownPostChildren, DrawControl = DrawWindow, DrawDragGrip = function() end, DrawResizeGrip = DrawResizeGrip, } skin.main_window_small_flat = { TileImage = ":c:tech_mainwindow_small_flat.png", tiles = {76, 30, 76, 30}, --// tile widths: left, top, right, bottom padding = {10, 6, 10, 6}, hitpadding = {4, 4, 4, 4}, captionColor = {1, 1, 1, 0.45}, backgroundColor = {0.1, 0.1, 0.1, 0.7}, boxes = { resize = {-23, -19, -12, -8}, drag = {0, 0, "100%", 10}, }, NCHitTest = NCHitTestWithPadding, NCMouseDown = WindowNCMouseDown, NCMouseDownPostChildren = WindowNCMouseDownPostChildren, DrawControl = DrawWindow, DrawDragGrip = function() end, DrawResizeGrip = DrawResizeGrip, } skin.main_window_small_very_flat = { TileImage = ":c:tech_mainwindow_small_very_flat.png", tiles = {76, 30, 76, 30}, --// tile widths: left, top, right, bottom padding = {10, 6, 10, 6}, hitpadding = {4, 4, 4, 4}, captionColor = {1, 1, 1, 0.45}, backgroundColor = {0.1, 0.1, 0.1, 0.7}, boxes = { resize = {-23, -19, -12, -8}, drag = {0, 0, "100%", 10}, }, NCHitTest = NCHitTestWithPadding, NCMouseDown = WindowNCMouseDown, NCMouseDownPostChildren = WindowNCMouseDownPostChildren, DrawControl = DrawWindow, DrawDragGrip = function() end, DrawResizeGrip = DrawResizeGrip, } skin.main_window_tall = { TileImage = ":c:tech_mainwindow_tall.png", tiles = {76, 40, 76, 40}, --// tile widths: left, top, right, bottom padding = {10, 6, 10, 6}, hitpadding = {4, 4, 4, 4}, captionColor = {1, 1, 1, 0.45}, backgroundColor = {0.1, 0.1, 0.1, 0.7}, boxes = { resize = {-23, -19, -12, -8}, drag = {0, 0, "100%", 10}, }, NCHitTest = NCHitTestWithPadding, NCMouseDown = WindowNCMouseDown, NCMouseDownPostChildren = WindowNCMouseDownPostChildren, DrawControl = DrawWindow, DrawDragGrip = function() end, DrawResizeGrip = DrawResizeGrip, } skin.main_window = { TileImage = ":c:tech_mainwindow.png", tiles = {176, 64, 176, 64}, --// tile widths: left, top, right, bottom padding = {10, 6, 10, 6}, hitpadding = {4, 4, 4, 4}, captionColor = {1, 1, 1, 0.45}, backgroundColor = {0.1, 0.1, 0.1, 0.7}, boxes = { resize = {-23, -19, -12, -8}, drag = {0, 0, "100%", 10}, }, NCHitTest = NCHitTestWithPadding, NCMouseDown = WindowNCMouseDown, NCMouseDownPostChildren = WindowNCMouseDownPostChildren, DrawControl = DrawWindow, DrawDragGrip = function() end, DrawResizeGrip = DrawResizeGrip, } skin.line = { TileImage = ":cl:tech_line.png", tiles = {0, 0, 0, 0}, TileImageV = ":cl:tech_line_vert.png", tilesV = {0, 0, 0, 0}, DrawControl = DrawLine, } skin.tabbar = { padding = {3, 1, 1, 0}, } skin.tabbaritem = { -- yes these are reverted, but also a lie (see images), only one is used TileImageFG = ":cl:tech_tabbaritem_fg.png", TileImageBK = ":cl:tech_tabbaritem_bk.png", tiles = {10, 10, 10, 0}, --// tile widths: left, top, right, bottom padding = {1, 1, 1, 2}, -- since it's color multiplication, it's easier to control white color (1, 1, 1) than black color (0, 0, 0) to get desired results backgroundColor = {0, 0, 0, 1.0}, -- actually kill this anyway borderColor = {0, 0, 0, 0}, focusColor = {0.46, 0.54, 0.68, 1.0}, DrawControl = DrawTabBarItem, } skin.control = skin.general --// ============================================================================= --// return skin
gpl-2.0
nnesse/b2l-tools
lgi/samples/gstvideo.lua
6
3219
#! /usr/bin/env lua -- -- Sample GStreamer application, based on public Vala GStreamer Video -- Example (http://live.gnome.org/Vala/GStreamerSample) -- local lgi = require 'lgi' local GLib = lgi.GLib local Gtk = lgi.Gtk local GdkX11 = lgi.GdkX11 local Gst = lgi.Gst if tonumber(Gst._version) >= 1.0 then local GstVideo = lgi.GstVideo end local app = Gtk.Application { application_id = 'org.lgi.samples.gstvideo' } local window = Gtk.Window { title = "LGI Based Video Player", Gtk.Box { orientation = 'VERTICAL', Gtk.DrawingArea { id = 'video', expand = true, width = 300, height = 150, }, Gtk.ButtonBox { orientation = 'HORIZONTAL', Gtk.Button { id = 'play', use_stock = true, label = Gtk.STOCK_MEDIA_PLAY, }, Gtk.Button { id = 'stop', use_stock = true, sensitive = false, label = Gtk.STOCK_MEDIA_STOP, }, Gtk.Button { id = 'quit', use_stock = true, label = Gtk.STOCK_QUIT, }, }, } } function window.child.quit:on_clicked() window:destroy() end local pipeline = Gst.Pipeline.new('mypipeline') local src = Gst.ElementFactory.make('autovideosrc', 'videosrc') local colorspace = Gst.ElementFactory.make('videoconvert', 'colorspace') or Gst.ElementFactory.make('ffmpegcolorspace', 'colorspace') local scale = Gst.ElementFactory.make('videoscale', 'scale') local rate = Gst.ElementFactory.make('videorate', 'rate') local sink = Gst.ElementFactory.make('xvimagesink', 'sink') pipeline:add_many(src, colorspace, scale, rate, sink) src:link_many(colorspace, scale, rate, sink) function window.child.play:on_clicked() pipeline.state = 'PLAYING' end function window.child.stop:on_clicked() pipeline.state = 'PAUSED' end local function bus_callback(bus, message) if message.type.ERROR then print('Error:', message:parse_error().message) Gtk.main_quit() end if message.type.EOS then print 'end of stream' end if message.type.STATE_CHANGED then local old, new, pending = message:parse_state_changed() print(string.format('state changed: %s->%s:%s', old, new, pending)) -- Set up sensitive state on buttons according to current state. -- Note that this is forwarded to mainloop, because bus callback -- can be called in some side thread and Gtk might not like to -- be controlled from other than main thread on some platforms. GLib.idle_add(GLib.PRIORITY_DEFAULT, function() window.child.play.sensitive = (new ~= 'PLAYING') window.child.stop.sensitive = (new == 'PLAYING') return GLib.SOURCE_REMOVE end) end if message.type.TAG then message:parse_tag():foreach( function(list, tag) print(('tag: %s = %s'):format(tag, tostring(list:get(tag)))) end) end return true end function window.child.video:on_realize() -- Retarget video output to the drawingarea. sink:set_window_handle(self.window:get_xid()) end function app:on_activate() window.application = app pipeline.bus:add_watch(GLib.PRIORITY_DEFAULT, bus_callback) window:show_all() end app:run { arg[0], ... } -- Must always set the pipeline to NULL before disposing it pipeline.state = 'NULL'
gpl-2.0
andwj/oblige-weird
scripts/brush.lua
1
21517
------------------------------------------------------------------------ -- BRUSHES and TRANSFORMS ------------------------------------------------------------------------ -- -- Oblige Level Maker -- -- Copyright (C) 2006-2014 Andrew Apted -- -- 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. -- ------------------------------------------------------------------------ Trans = {} brushlib = {} function raw_add_brush(brush) each C in brush do -- compatibility cruft if C.face then table.merge(C, C.face) C.face = nil end if C.x_offset then C.u1 = C.x_offset ; C.x_offset = nil end if C.y_offset then C.v1 = C.y_offset ; C.y_offset = nil end end gui.add_brush(brush) if GAME.add_brush_func then GAME.add_brush_func(brush) end end function raw_add_entity(ent) -- skip unknown entities (from wad-fab loader) if not ent.id then return end if GAME.format == "quake" then ent.mangle = ent.angles ; ent.angles = nil end if GAME.format == "doom" then -- this is mainly for Legacy (spawning things on 3D floors) -- it is OK for this to be NIL ent.fs_name = FRAGGLESCRIPT_THINGS[ent.id] end gui.add_entity(ent) if GAME.add_entity_func then GAME.add_entity_func(ent) end end function raw_add_model(model) assert(model.entity) model.entity.model = gui.q1_add_mapmodel(model) gui.add_entity(model.entity) if GAME.add_model_func then GAME.add_model_func(model) end end ------------------------------------------------------------------------ -- Transformative Geometry ------------------------------------------------------------------------ Trans.TRANSFORM = { -- mirror_x : flip horizontally (about given X) -- mirror_y : flip vertically (about given Y) -- groups_x : coordinate remapping groups -- groups_y -- groups_z -- scale_x : scaling factor -- scale_y -- scale_z -- rotate : angle in degrees, counter-clockwise, -- rotates about the origin -- add_x : translation, i.e. new origin coords -- add_y -- add_z -- fitted_x : size which a "fitted" prefab needs to become -- fitted_y -- fitted_z } function Trans.clear() Trans.TRANSFORM = {} end function Trans.set(T) Trans.TRANSFORM = T end function Trans.modify(what, value) Trans.TRANSFORM[what] = value end function Trans.remap_coord(groups, n) if not groups then return n end local T = #groups assert(T >= 1) if n <= groups[1].low then return n + (groups[1].low2 - groups[1].low) end if n >= groups[T].high then return n + (groups[T].high2 - groups[T].high) end local idx = 1 while (idx < T) and (n > groups[idx].high) do idx = idx + 1 end local G = groups[idx] return G.low2 + (n - G.low) * G.size2 / G.size; end function Trans.apply_xy(x, y) local T = Trans.TRANSFORM -- apply mirroring first if T.mirror_x then x = T.mirror_x * 2 - x end if T.mirror_y then y = T.mirror_y * 2 - y end -- apply groups if T.groups_x then x = Trans.remap_coord(T.groups_x, x) end if T.groups_y then y = Trans.remap_coord(T.groups_y, y) end -- apply scaling x = x * (T.scale_x or 1) y = y * (T.scale_y or 1) -- apply rotation if T.rotate then x, y = geom.rotate_vec(x, y, T.rotate) end -- apply translation last x = x + (T.add_x or 0) y = y + (T.add_y or 0) return x, y end function Trans.apply_z(z) local T = Trans.TRANSFORM -- apply groups if T.groups_z then z = Trans.remap_coord(T.groups_z, z) end -- apply scaling z = z * (T.scale_z or 1) -- apply translation last z = z + (T.add_z or 0) return z end function Trans.apply_slope(slope) if not slope then return nil end local T = Trans.TRANSFORM slope = table.copy(slope) slope.x1, slope.y1 = Trans.apply_xy(slope.x1, slope.y1) slope.x2, slope.y2 = Trans.apply_xy(slope.x2, slope.y2) slope.dz = slope.dz * (T.scale_z or 1) return slope end function Trans.apply_angle(ang) local T = Trans.TRANSFORM if not (T.rotate or T.mirror_x or T.mirror_y) then return ang end if T.mirror_x or T.mirror_y then local dx = math.cos(ang * math.pi / 180) local dy = math.sin(ang * math.pi / 180) if T.mirror_x then dx = -dx end if T.mirror_y then dy = -dy end ang = math.round(geom.calc_angle(dx, dy)) end if T.rotate then ang = ang + T.rotate end if ang >= 360 then ang = ang - 360 end if ang < 0 then ang = ang + 360 end return ang end function Trans.brush(coords) -- FIXME: mirroring -- apply transform coords = table.copy(coords) each C in coords do if C.x then C.x, C.y = Trans.apply_xy(C.x, C.y) elseif C.b then C.b = Trans.apply_z(C.b) elseif C.t then C.t = Trans.apply_z(C.t) end if C.slope then C.slope = Trans.apply_slope(C.slope) end end brushlib.collect_flags(coords) raw_add_brush(coords) end function Trans.old_brush(info, coords, z1, z2) ---??? if type(info) != "table" then ---??? info = get_mat(info) ---??? end -- check mirroring local reverse_it = false if Trans.TRANSFORM.mirror_x then reverse_it = not reverse_it end if Trans.TRANSFORM.mirror_y then reverse_it = not reverse_it end -- apply transform coords = table.deep_copy(coords) each C in coords do C.x, C.y = Trans.apply_xy(C.x, C.y) if C.w_face then C.face = C.w_face ; C.w_face = nil elseif info.w_face then C.face = info.w_face end end if reverse_it then -- make sure side properties (w_face, line_kind, etc) -- are associated with the correct vertex.... local x1 = coords[1].x local y1 = coords[1].y for i = 1, #coords-1 do coords[i].x = coords[i+1].x coords[i].y = coords[i+1].y end coords[#coords].x = x1 coords[#coords].y = y1 table.reverse(coords) end if z2 < EXTREME_H - 1 then table.insert(coords, { t=z2, face=info.t_face }) coords[#coords].special = info.sec_kind coords[#coords].tag = info.sec_tag end if z1 > -EXTREME_H + 1 then table.insert(coords, { b=z1, face=info.b_face }) if info.delta_z then coords[#coords].delta_z = info.delta_z end coords[#coords].special = info.sec_kind coords[#coords].tag = info.sec_tag end -- TODO !!! transform slope coords (z1 or z2 == table) -- gui.printf("coords=\n%s\n", table.tostr(coords,4)) local kind = info.kind or "solid" table.insert(coords, 1, { m=kind, mover=info.peg }) brushlib.collect_flags(coords) raw_add_brush(coords) end function Trans.entity(name, x, y, z, props) assert(name) if not props then props = {} end local info = GAME.ENTITIES[name] or GAME.MONSTERS[name] or GAME.WEAPONS[name] or GAME.PICKUPS[name] or GAME.NICE_ITEMS[name] if not info then gui.printf("\nLACKING ENTITY : %s\n\n", name) return end assert(info.id) x, y = Trans.apply_xy(x, y) z = Trans.apply_z (z) if info.delta_z then z = z + info.delta_z elseif PARAM.entity_delta_z then z = z + PARAM.entity_delta_z end if info.spawnflags then props.spawnflags = (props.spawnflags or 0) + info.spawnflags end local ent = table.copy(props) ent.id = info.id ent.x = x ent.y = y ent.z = z raw_add_entity(ent) end function Trans.quad(x1,y1, x2,y2, z1,z2, kind, w_face, p_face) if not w_face then -- convenient form: only a material name was given kind, w_face, p_face = Mat_normal(kind) end local coords = { { x=x1, y=y1, face=w_face }, { x=x2, y=y1, face=w_face }, { x=x2, y=y2, face=w_face }, { x=x1, y=y2, face=w_face }, } if z1 then table.insert(coords, { b=z1, face=p_face }) end if z2 then table.insert(coords, { t=z2, face=p_face }) end Trans.brush(kind, coords) end function Trans.rect_coords(x1, y1, x2, y2) return { { x=x2, y=y1 }, { x=x2, y=y2 }, { x=x1, y=y2 }, { x=x1, y=y1 }, } end function Trans.old_quad(info, x1,y1, x2,y2, z1,z2) Trans.old_brush(info, Trans.rect_coords(x1,y1, x2,y2), z1,z2) end function Trans.solid_quad(x1, y1, x2, y2, mat) local brush = brushlib.quad(x1, y1, x2, y2) brushlib.set_mat(brush, mat, mat) Trans.brush(brush) end function Trans.sky_quad(x1, y1, x2, y2, sky_h) local brush = brushlib.quad(x1, y1, x2, y2, sky_h) brhshlib.set_kind(brush, "sky") brushlib.set_mat(brush, "_SKY", "_SKY") Trans.brush(brush) end function Trans.spot_transform(x, y, z, dir) local ANGS = { [2]=0, [8]=180, [4]=270, [6]=90 } assert(x and y) return { add_x = x add_y = y add_z = z rotate = ANGS[dir or 2] } end function Trans.box_transform(x1, y1, x2, y2, z, dir) if not dir then dir = 2 end local XS = { [2]=x1, [8]= x2, [4]= x1, [6]=x2 } local YS = { [2]=y1, [8]= y2, [4]= y2, [6]=y1 } local ANGS = { [2]=0, [8]=180, [4]=270, [6]=90 } local T = {} T.add_x = XS[dir] T.add_y = YS[dir] T.add_z = z T.rotate = ANGS[dir] if geom.is_vert(dir) then T.fitted_x = x2 - x1 T.fitted_y = y2 - y1 else T.fitted_x = y2 - y1 T.fitted_y = x2 - x1 end T.bbox = { x1=x1, y1=y1, x2=x2, y2=y2 } return T end function Trans.edge_transform(x1,y1, x2,y2, z, side, long1, long2, deep, over) if side == 4 then x2 = x1 + deep ; x1 = x1 - over end if side == 6 then x1 = x2 - deep ; x2 = x2 + over end if side == 2 then y2 = y1 + deep ; y1 = y1 - over end if side == 8 then y1 = y2 - deep ; y2 = y2 + over end if side == 2 then x1 = x2 - long2 ; x2 = x2 - long1 end if side == 8 then x2 = x1 + long2 ; x1 = x1 + long1 end if side == 4 then y2 = y1 + long2 ; y1 = y1 + long1 end if side == 6 then y1 = y2 - long2 ; y2 = y2 - long1 end return Trans.box_transform(x1,y1, x2,y2, z, side) end function Trans.set_fitted_z(T, z1, z2) T.add_z = z1 T.fitted_z = z2 - z1 end ------------------------------------------------------------------------ -- Material System ------------------------------------------------------------------------ function Mat_prepare_trip() -- build the psychedelic mapping local m_before = {} local m_after = {} for m,def in pairs(GAME.MATERIALS) do if not def.sane and not def.rail_h and not (string.sub(m,1,1) == "_") and not (string.sub(m,1,2) == "SW") and not (string.sub(m,1,3) == "BUT") then table.insert(m_before, m) table.insert(m_after, m) end end rand.shuffle(m_after) LEVEL.psycho_map = {} for i = 1,#m_before do LEVEL.psycho_map[m_before[i]] = m_after[i] end end function Mat_lookup(name) if not name then name = "_ERROR" end if LEVEL.psychedelic and LEVEL.psycho_map[name] then name = LEVEL.psycho_map[name] end local mat = GAME.MATERIALS[name] -- special handling for DOOM switches if not mat and string.sub(name,1,3) == "SW2" then local sw1_name = "SW1" .. string.sub(name,4) mat = GAME.MATERIALS[sw1_name] if mat and mat.t == sw1_name then mat = { t=name, f=mat.f } -- create new SW2XXX material GAME.MATERIALS[name] = mat end end if not mat then gui.printf("\nLACKING MATERIAL : %s\n\n", name) mat = assert(GAME.MATERIALS["_ERROR"]) -- prevent further messages GAME.MATERIALS[name] = mat end return mat end function get_mat(wall, floor, ceil) if not wall then wall = "_ERROR" end local w_mat = Mat_lookup(wall) local f_mat = w_mat if floor then f_mat = Mat_lookup(floor) end local c_mat = f_mat if ceil then c_mat = Mat_lookup(ceil) end return { w_face = { tex=w_mat.t }, t_face = { tex=f_mat.f or f_mat.t }, b_face = { tex=c_mat.f or c_mat.t }, } end function Mat_normal(wall, floor) if not wall then wall = "_ERROR" end local w_mat = Mat_lookup(wall) local f_mat = w_mat if floor then f_mat = Mat_lookup(floor) end return "solid", { tex=w_mat.t }, { tex=f_mat.f or f_mat.t } end function get_sky() local mat = assert(GAME.MATERIALS["_SKY"]) return { kind = "sky" w_face = { tex=mat.t } t_face = { tex=mat.f or mat.t } b_face = { tex=mat.f or mat.t } } end function get_fake_sky() local mat = assert(GAME.MATERIALS["_SKY"]) local light if not LEVEL.is_dark then light = LEVEL.sky_bright - 8 end return { w_face = { tex=mat.t } t_face = { tex=mat.f or mat.t } b_face = { tex=mat.f or mat.t, light=light } } end function get_liquid(is_outdoor) assert(LEVEL.liquid) local mat = get_mat(LEVEL.liquid.mat) if not is_outdoor or LEVEL.is_dark then mat.t_face.light = LEVEL.liquid.light mat.b_face.light = LEVEL.liquid.light end mat.t_face.special = LEVEL.liquid.special mat.b_face.special = LEVEL.liquid.special return mat end function add_pegging(info, x_offset, y_offset, peg) info.w_face.x_offset = x_offset or 0 info.w_face.y_offset = y_offset or 0 info.peg = peg or 1 return info end function get_transform_for_seed_side(S, side, thick) if not thick then thick = S.thick[side] end local T = { } if side == 8 then T.rotate = 180 end if side == 4 then T.rotate = 270 end if side == 6 then T.rotate = 90 end if side == 2 then T.add_x, T.add_y = S.x1, S.y1 end if side == 4 then T.add_x, T.add_y = S.x1, S.y2 end if side == 6 then T.add_x, T.add_y = S.x2, S.y1 end if side == 8 then T.add_x, T.add_y = S.x2, S.y2 end return T, SEED_SIZE, thick end function get_transform_for_seed_center(S) local T = { } T.add_x = S.x1 + S.thick[4] T.add_y = S.y1 + S.thick[2] local long = S.x2 - S.thick[6] - T.add_x local deep = S.y2 - S.thick[8] - T.add_y return T, long, deep end function diagonal_coords(side, x1,y1, x2,y2) if side == 9 then return { { x=x2, y=y1 }, { x=x2, y=y2 }, { x=x1, y=y2 }, } elseif side == 7 then return { { x=x1, y=y2 }, { x=x1, y=y1 }, { x=x2, y=y2 }, } elseif side == 3 then return { { x=x2, y=y1 }, { x=x2, y=y2 }, { x=x1, y=y1 }, } elseif side == 1 then return { { x=x1, y=y2 }, { x=x1, y=y1 }, { x=x2, y=y1 }, } else error("bad side for diagonal_coords: " .. tostring(side)) end end function get_wall_coords(S, side, thick, pad) assert(side != 5) local x1, y1 = S.x1, S.y1 local x2, y2 = S.x2, S.y2 if side == 4 or side == 1 or side == 7 then x2 = x1 + (thick or S.thick[4]) if pad then x1 = x1 + pad end end if side == 6 or side == 3 or side == 9 then x1 = x2 - (thick or S.thick[6]) if pad then x2 = x2 - pad end end if side == 2 or side == 1 or side == 3 then y2 = y1 + (thick or S.thick[2]) if pad then y1 = y1 + pad end end if side == 8 or side == 7 or side == 9 then y1 = y2 - (thick or S.thick[8]) if pad then y2 = y2 - pad end end return Trans.rect_coords(x1,y1, x2,y2) end ------------------------------------------------------------------------ -- Brush Library ------------------------------------------------------------------------ DOOM_LINE_FLAGS = { blocked = 0x01 block_mon = 0x02 sound_block = 0x40 draw_secret = 0x20 draw_never = 0x80 draw_always = 0x100 pass_thru = 0x200 -- Boom } HEXEN_ACTIONS = { W1 = 0x0000, WR = 0x0200 -- walk S1 = 0x0400, SR = 0x0600 -- switch M1 = 0x0800, MR = 0x0A00 -- monster G1 = 0x0c00, GR = 0x0E00 -- gun / projectile B1 = 0x1000, BR = 0x1200 -- bump } function brushlib.quad(x1,y1, x2,y2, b,t) local coords = { { x=x1, y=y1 } { x=x2, y=y1 } { x=x2, y=y2 } { x=x1, y=y2 } } if b then table.insert(coords, { b=b }) end if t then table.insert(coords, { t=t }) end return coords end function brushlib.triangle(x1,y1, x2,y2, x3,y3, b,t) local coords = { { x=x1, y=y1 } { x=x2, y=y2 } { x=x3, y=y3 } } if b then table.insert(coords, { b=b }) end if t then table.insert(coords, { t=t }) end return coords end function brushlib.dump(brush, title) gui.debugf("%s:\n{\n", title or "Brush") each C in brush do local field_list = {} each name,val in C do local pos if name == "m" or name == "x" or name == "b" or name == "t" then pos = 1 elseif name == "y" then pos = 2 end if pos then table.insert(field_list, pos, name) else table.insert(field_list, name) end end local line = "" each name in field_list do local val = C[name] if _index > 1 then line = line .. ", " end line = line .. string.format("%s=%s", name, tostring(val)) end gui.debugf(" { %s }\n", line) end gui.debugf("}\n") end function brushlib.copy(brush) local newb = {} each C in brush do table.insert(newb, table.copy(C)) end return newb end function brushlib.mid_point(brush) local sum_x = 0 local sum_y = 0 local total = 0 each C in brush do if C.x then sum_x = sum_x + C.x sum_y = sum_y + C.y total = total + 1 end end if total == 0 then return 0, 0 end return sum_x / total, sum_y / total end function brushlib.bbox(brush) local x1, x2 = 9e9, -9e9 local y1, y2 = 9e9, -9e9 each C in brush do if C.x then x1 = math.min(x1, C.x) ; x2 = math.max(x2, C.x) y1 = math.min(y1, C.y) ; y2 = math.max(y2, C.y) end end assert(x1 < x2) assert(y1 < y2) return x1,y1, x2,y2 end function brushlib.set_kind(brush, kind, props) -- remove any existing kind for i = 1, #brush do if brush[i].m then table.remove(brush, i) break; end end local C = { m=kind } if props then table.merge(C, props) end table.insert(brush, 1, C) end function brushlib.xy_coord(brush, x, y, props) local C = { x=x, y=y } if props then table.merge(C, props) end table.insert(brush, C) return C end function brushlib.add_top(brush, z, mat) -- Note: assumes brush has no top already! table.insert(brush, { t=z, mat=mat }) end function brushlib.add_bottom(brush, z, mat) -- Note: assumes brush has no bottom already! table.insert(brush, { b=z, mat=mat }) end function brushlib.get_bottom_h(brush) each C in brush do if C.b then return C.b end end return nil -- none end function brushlib.get_top_h(brush) each C in brush do if C.t then return C.t end end return nil -- none end function brushlib.set_tex(brush, wall, flat) each C in brush do if wall and C.x and not C.tex then C.tex = wall end if flat and (C.b or C.t) and not C.tex then C.tex = flat end end end function brushlib.set_mat(brush, wall, flat) if wall then wall = Mat_lookup(wall) wall = assert(wall.t) end if flat then flat = Mat_lookup(flat) flat = assert(flat.f or flat.t) end brushlib.set_tex(brush, wall, flat) end function brushlib.set_line_flag(brush, key, value) each C in brush do if C.x then C[key] = value end end end function brushlib.collect_flags(coords) each C in coords do -- these flags only apply to linedefs if not C.x then continue end if GAME.format == "doom" then local flags = C.flags or 0 if C.act and PARAM.sub_format == "hexen" then local spac = HEXEN_ACTIONS[C.act] if not spac then error("Unknown act value: " .. tostring(C.act)) end flags = bit.bor(flags, spac) end each name,value in DOOM_LINE_FLAGS do if C[name] and C[name] != 0 then flags = bit.bor(flags, value) C[name] = nil end end if flags != 0 then C.flags = flags -- this makes sure the flags get applied if not C.special then C.special = 0 end end end end -- C end function brushlib.mark_sky(brush) brushlib.set_mat(brush, "_SKY", "_SKY") table.insert(brush, 1, { m="sky" }) end function brushlib.has_sky(brush) each C in brush do if C.mat == "_SKY" then return true end end return false end function brushlib.mark_liquid(brush) assert(LEVEL.liquid) brushlib.set_mat(brush, "_LIQUID", "_LIQUID") each C in brush do if C.b or C.t then C.special = LEVEL.liquid.special C.light = LEVEL.liquid.light end end end function brushlib.is_quad(brush) local x1,y1, x2,y2 = brushlib.bbox(brush) each C in brush do if C.x then if C.x > x1+0.1 and C.x < x2-0.1 then return false end if C.y > y1+0.1 and C.y < y2-0.1 then return false end end end return true end function brushlib.line_passes_through(brush, px1, py1, px2, py2) -- Note: returns false if line merely touches an edge local front, back each C in brush do if C.x then local d = geom.perp_dist(C.x, C.y, px1,py1, px2,py2) if d > 0.9 then front = true end if d < -0.9 then back = true end if front and back then return true end end end return false end
gpl-2.0
LuaDist2/ldoc
tests/example/style/simple.lua
7
1227
--------------- -- Markdown-flavoured and very simple no-structure style. -- -- Here the idea is to structure the document entirely with [Markdown](). -- -- Using the default markdown processor can be a little irritating: you are -- required to give a blank line before starting lists. The default stylesheet -- is not quite right, either. -- module 'mod' --- Combine two strings _first_ and _second_ in interesting ways. function combine(first,second) end --- Combine a whole bunch of strings. function combine_all(...) end --- -- Creates a constant capture. This pattern matches the empty string and -- produces all given values as its captured values. function lpeg.Cc([value, ...]) end --- Split a string _str_. Returns the first part and the second part, so that -- `combine(first,second)` is equal to _s_. function split(s) end --- Split a string _text_ into a table. -- Returns: -- -- - `name` the name of the text -- - `pairs` an array of pairs -- - `key` -- - `value` -- - `length` -- function split_table (text) end --- A table of useful constants. -- -- - `alpha` first correction factor -- - `beta` second correction factor -- -- @table constants
mit
Anarchid/Zero-K
scripts/pw_artefact.lua
8
1828
include 'constants.lua' local base = piece "base" local wheel = piece "wheel" local pumpcylinders = piece "pumpcylinders" local turret = piece "turret" local pump1 = piece "pump1" local pump2 = piece "pump2" local pump3 = piece "pump3" local function Initialize() Signal(1) SetSignalMask(2) Spin(wheel, y_axis, 3, 0.1) Spin(turret, y_axis, -1, 0.01) while (true) do Move(pumpcylinders, z_axis, -11, 15) Turn(pump1, x_axis, -1.4, 2) Turn(pump2, z_axis, -1.4, 2) Turn(pump3, z_axis, 1.4, 2) WaitForMove(pumpcylinders, z_axis) WaitForTurn(pump1, x_axis) WaitForTurn(pump2, z_axis) WaitForTurn(pump3, z_axis) Move(pumpcylinders, z_axis, 0, 15) Turn(pump1, x_axis, 0, 2) Turn(pump2, z_axis, 0, 2) Turn(pump3, z_axis, 0, 2) WaitForMove(pumpcylinders, z_axis) WaitForTurn(pump1, x_axis) WaitForTurn(pump2, z_axis) WaitForTurn(pump3, z_axis) end end local function Deinitialize() Signal(2) SetSignalMask(1) StopSpin(wheel, y_axis, 0.1) StopSpin(turret, y_axis, 0.1) end function script.Create() Turn(pump2, y_axis, -0.523598776) Turn(pump3, y_axis, 0.523598776) end function script.Activate() if Spring.GetUnitRulesParam(unitID, "planetwarsDisable") == 1 or GG.applyPlanetwarsDisable then return end StartThread(Initialize) end function script.Deactivate() StartThread(Deinitialize) end -- Invulnerability --function script.HitByWeapon() -- return 0 --end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity < 0.5 then Explode(base, SFX.NONE) Explode(turret, SFX.NONE) Explode(pumpcylinders, SFX.NONE) Explode(wheel, SFX.FALL) return 1 else Explode(base, SFX.SHATTER) Explode(turret, SFX.SHATTER) Explode(pumpcylinders, SFX.SHATTER) Explode(wheel, SFX.FALL + SFX.SMOKE + SFX.FIRE) return 2 end end
gpl-2.0
LORgames/premake-core
tests/base/test_criteria.lua
15
10408
-- -- tests/base/test_criteria.lua -- Test suite for the criteria matching API. -- Copyright (c) 2012-2015 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("criteria") local criteria = p.criteria -- -- Setup and teardown -- local crit -- -- A criteria with no terms should satisfy any context. -- function suite.matches_alwaysTrue_onNoFilterTerms() crit = criteria.new {} test.istrue(criteria.matches(crit, { configurations="Debug", system="Windows" })) end -- -- Should not match if any term is missing in the context. -- function suite.matches_fails_onMissingContext() crit = criteria.new { "system:Windows", "architecture:x86" } test.isfalse(criteria.matches(crit, { configurations="Debug", system="Windows" })) end -- -- Context terms must match the entire criteria term. -- function suite.matches_fails_onIncompleteTermMatch() crit = criteria.new { "platforms:win64" } test.isfalse(criteria.matches(crit, { platforms="win64 dll dcrt" })) end -- -- Wildcard matches should work. -- function suite.matches_passes_onPatternMatch() crit = criteria.new { "action:vs*" } test.istrue(criteria.matches(crit, { action="vs2005" })) end -- -- The "not" modifier should fail the test if the term is matched. -- function suite.matches_fails_onMatchWithNotModifier_afterPrefix() crit = criteria.new { "system:not windows" } test.isfalse(criteria.matches(crit, { system="windows" })) end function suite.matches_fails_onMatchWithNotModifier_beforePrefix() crit = criteria.new { "not system:windows" } test.isfalse(criteria.matches(crit, { system="windows" })) end function suite.matches_passes_onMissWithNotModifier_afterPrefix() crit = criteria.new { "system:not windows" } test.istrue(criteria.matches(crit, { system="linux" })) end function suite.matches_passes_onMissWithNotModifier_beforePrefix() crit = criteria.new { "not system:windows" } test.istrue(criteria.matches(crit, { system="linux" })) end function suite.matches_passes_onMissWithNotModifier_noPrefix() crit = criteria.new { "not debug" } test.istrue(criteria.matches(crit, { configurations="release" })) end -- -- The "or" modifier should pass if either term is present. -- function suite.matches_passes_onFirstOrTermMatched() crit = criteria.new { "system:windows or linux" } test.istrue(criteria.matches(crit, { system="windows" })) end function suite.matches_passes_onSecondOrTermMatched() crit = criteria.new { "system:windows or linux" } test.istrue(criteria.matches(crit, { system="linux" })) end function suite.matches_passes_onThirdOrTermMatched() crit = criteria.new { "system:windows or linux or vs2005" } test.istrue(criteria.matches(crit, { system="vs2005" })) end function suite.matches_fails_onNoOrTermMatched() crit = criteria.new { "system:windows or linux" } test.isfalse(criteria.matches(crit, { system="vs2005" })) end function suite.matches_passes_onMixedPrefixes_firstTermMatched_projectContext() crit = criteria.new { "system:windows or files:core*" } test.istrue(criteria.matches(crit, { system="windows" })) end function suite.matches_fails_onMixedPrefixes_firstTermMatched_fileContext() crit = criteria.new { "system:windows or files:core*" } test.isfalse(criteria.matches(crit, { system="windows", files="hello.cpp" })) end function suite.matches_passes_onMixedPrefixes_secondTermMatched() crit = criteria.new { "system:windows or files:core*" } test.istrue(criteria.matches(crit, { system="linux", files="coregraphics.cpp" })) end function suite.matches_fails_onMixedPrefixes_noTermMatched() crit = criteria.new { "system:windows or files:core*" } test.isfalse(criteria.matches(crit, { system="linux", files="hello.cpp" })) end -- -- The "not" modifier should fail on any match with an "or" modifier. -- function suite.matches_passes_onNotOrMatchesFirst() crit = criteria.new { "system:not windows or linux" } test.isfalse(criteria.matches(crit, { system="windows" })) end function suite.matches_passes_onNotOrMatchesSecond() crit = criteria.new { "system:windows or not linux" } test.isfalse(criteria.matches(crit, { system="linux" })) end -- -- The "not" modifier should succeed with "or" if there are no matches. -- function suite.matches_passes_onNoNotMatch() crit = criteria.new { "system:not windows or linux" } test.istrue(criteria.matches(crit, { system="macosx" })) end -- -- If the context specifies a filename, the filter must match it explicitly. -- function suite.matches_passes_onFilenameAndMatchingPattern() crit = criteria.new { "files:**.c", "system:windows" } test.istrue(criteria.matches(crit, { system="windows", files="hello.c" })) end function suite.matches_fails_onFilenameAndNoMatchingPattern() crit = criteria.new { "system:windows" } test.isfalse(criteria.matches(crit, { system="windows", files="hello.c" })) end -- -- Test criteria creation through a table. -- function suite.createCriteriaWithTable() crit = criteria.new { files = { "**.c" }, system = "windows" } test.istrue(criteria.matches(crit, { system="windows", files="hello.c" })) end function suite.createCriteriaWithTable2() crit = criteria.new { system = "not windows" } test.isfalse(criteria.matches(crit, { system="windows" })) end function suite.createCriteriaWithTable3() crit = criteria.new { system = "not windows or linux" } test.istrue(criteria.matches(crit, { system="macosx" })) end function suite.createCriteriaWithTable4() crit = criteria.new { system = "windows or linux" } test.istrue(criteria.matches(crit, { system="windows" })) end -- -- "Not" modifiers can also be used on filenames. -- function suite.matches_passes_onFilenameMissAndNotModifier() crit = criteria.new { "files:not **.c", "system:windows" } test.istrue(criteria.matches(crit, { system="windows", files="hello.h" })) end function suite.matches_fails_onFilenameHitAndNotModifier() crit = criteria.new { "files:not **.c", "system:windows" } test.isfalse(criteria.matches(crit, { system="windows", files="hello.c" })) end -- -- If context provides a list of values, match against them. -- function suite.matches_passes_termMatchesList() crit = criteria.new { "options:debug" } test.istrue(criteria.matches(crit, { options={ "debug", "logging" }})) end -- -- If no prefix is specified, default to "configurations". -- function suite.matches_usesDefaultPrefix_onSingleTerm() crit = criteria.new { "debug" } test.istrue(criteria.matches(crit, { configurations="debug" })) end -- -- These tests use the older, unprefixed style of filter terms. This -- approach will get phased out eventually, but are still included here -- for backward compatibility testing. -- function suite.matches_onEmptyCriteria_Unprefixed() crit = criteria.new({}, true) test.istrue(criteria.matches(crit, { "apple", "orange" })) end function suite.fails_onMissingContext_Unprefixed() crit = criteria.new({ "orange", "pear" }, true) test.isfalse(criteria.matches(crit, { "apple", "orange" })) end function suite.fails_onIncompleteMatch_Unprefixed() crit = criteria.new({ "win64" }, true) test.isfalse(criteria.matches(crit, { "win64 dll dcrt" })) end function suite.passes_onPatternMatch_Unprefixed() crit = criteria.new({ "vs*" }, true) test.istrue(criteria.matches(crit, { "vs2005" })) end function suite.fails_onNotMatch_Unprefixed() crit = criteria.new({ "not windows" }, true) test.isfalse(criteria.matches(crit, { "windows" })) end function suite.passes_onNotUnmatched_Unprefixed() crit = criteria.new({ "not windows" }, true) test.istrue(criteria.matches(crit, { "linux" })) end function suite.passes_onFirstOrTermMatched_Unprefixed() crit = criteria.new({ "windows or linux" }, true) test.istrue(criteria.matches(crit, { "windows" })) end function suite.passes_onSecondOrTermMatched_Unprefixed() crit = criteria.new({ "windows or linux" }, true) test.istrue(criteria.matches(crit, { "linux" })) end function suite.passes_onThirdOrTermMatched_Unprefixed() crit = criteria.new({ "windows or linux or vs2005" }, true) test.istrue(criteria.matches(crit, { "vs2005" })) end function suite.fails_onNoOrTermMatched_Unprefixed() crit = criteria.new({ "windows or linux" }, true) test.isfalse(criteria.matches(crit, { "vs2005" })) end function suite.passes_onNotOrMatchesFirst_Unprefixed() crit = criteria.new({ "not windows or linux" }, true) test.isfalse(criteria.matches(crit, { "windows" })) end function suite.passes_onNotOrMatchesSecond_Unprefixed() crit = criteria.new({ "windows or not linux" }, true) test.isfalse(criteria.matches(crit, { "linux" })) end function suite.passes_onNoNotMatch_Unprefixed() crit = criteria.new({ "not windows or linux" }, true) test.istrue(criteria.matches(crit, { "macosx" })) end function suite.passes_onFilenameAndMatchingPattern_Unprefixed() crit = criteria.new({ "**.c", "windows" }, true) test.istrue(criteria.matches(crit, { system="windows", files="hello.c" })) end function suite.fails_onFilenameAndNoMatchingPattern_Unprefixed() crit = criteria.new({ "windows" }, true) test.isfalse(criteria.matches(crit, { system="windows", files="hello.c" })) end function suite.fails_onFilenameAndNotModifier_Unprefixed() crit = criteria.new({ "not linux" }, true) test.isfalse(criteria.matches(crit, { system="windows", files="hello.c" })) end function suite.matches_passes_termMatchesList_Unprefixed() crit = criteria.new({ "debug" }, true) test.istrue(criteria.matches(crit, { options={ "debug", "logging" }})) end -- -- Should return nil and an error message on an invalid prefix. -- function suite.returnsNilAndError_onInvalidPrefix() crit, err = criteria.new { "gibble:Debug" } test.isnil(crit) test.isnotnil(err) end -- -- Should respect field value aliases, if present. -- function suite.passes_onAliasedValue() p.api.addAliases("system", { ["gnu-linux"] = "linux" }) crit = criteria.new { "system:gnu-linux" } test.istrue(criteria.matches(crit, { system="linux" })) end function suite.passes_onAliasedValue_withMixedCase() p.api.addAliases("system", { ["gnu-linux"] = "linux" }) crit = criteria.new { "System:GNU-Linux" } test.istrue(criteria.matches(crit, { system="linux" })) end
bsd-3-clause
Anarchid/Zero-K
LuaRules/Configs/StartBoxes/Comet Catcher Redux.lua
17
1056
return { [0] = { nameLong = "North", nameShort = "N", startpoints = { {3072,614}, {5120,614}, {1024,614}, }, boxes = { { {0,0}, {6144,0}, {6144,1229}, {0,1229}, }, }, }, [1] = { nameLong = "South", nameShort = "S", startpoints = { {3072,7578}, {1024,7578}, {5120,7578}, }, boxes = { { {0,6963}, {6144,6963}, {6144,8192}, {0,8192}, }, }, }, } --return { -- [0] = { -- nameLong = "West", -- nameShort = "W", -- startpoints = { -- {1024, 512}, -- {1024, 2048}, -- {1024, 3584}, -- {1024, 4864}, -- {1024, 6144}, -- {1024, 7680}, -- }, -- boxes = { -- { -- {0,0}, -- {1024,0}, -- {1024,8192}, -- {0,8192}, -- }, -- }, -- }, -- [1] = { -- nameLong = "East", -- nameShort = "E", -- startpoints = { -- {5120, 512}, -- {5120, 2048}, -- {5120, 3584}, -- {5120, 4864}, -- {5120, 6144}, -- {5120, 7680}, -- }, -- boxes = { -- { -- {5120,0}, -- {6144,0}, -- {6144,8192}, -- {5120,8192}, -- }, -- }, -- }, --}
gpl-2.0
makefu/nodemcu-firmware
lua_modules/bmp085/bmp085.lua
69
5037
-------------------------------------------------------------------------------- -- BMP085 I2C module for NODEMCU -- NODEMCU TEAM -- LICENCE: http://opensource.org/licenses/MIT -- Christee <Christee@nodemcu.com> -------------------------------------------------------------------------------- local moduleName = ... local M = {} _G[moduleName] = M --default value for i2c communication local id=0 --default oversampling setting local oss = 0 --CO: calibration coefficients table. local CO = {} -- read reg for 1 byte local function read_reg(dev_addr, reg_addr) i2c.start(id) i2c.address(id, dev_addr ,i2c.TRANSMITTER) i2c.write(id,reg_addr) i2c.stop(id) i2c.start(id) i2c.address(id, dev_addr,i2c.RECEIVER) local c=i2c.read(id,1) i2c.stop(id) return c end --write reg for 1 byte local function write_reg(dev_addr, reg_addr, reg_val) i2c.start(id) i2c.address(id, dev_addr, i2c.TRANSMITTER) i2c.write(id, reg_addr) i2c.write(id, reg_val) i2c.stop(id) end --get signed or unsigned 16 --parameters: --reg_addr: start address of short --signed: if true, return signed16 local function getShort(reg_addr, signed) local tH = string.byte(read_reg(0x77, reg_addr)) local tL = string.byte(read_reg(0x77, (reg_addr + 1))) local temp = tH*256 + tL if (temp > 32767) and (signed == true) then temp = temp - 65536 end return temp end -- initialize i2c --parameters: --d: sda --l: scl function M.init(d, l) if (d ~= nil) and (l ~= nil) and (d >= 0) and (d <= 11) and (l >= 0) and ( l <= 11) and (d ~= l) then sda = d scl = l else print("iic config failed!") return nil end print("init done") i2c.setup(id, sda, scl, i2c.SLOW) --get calibration coefficients. CO.AC1 = getShort(0xAA, true) CO.AC2 = getShort(0xAC, true) CO.AC3 = getShort(0xAE, true) CO.AC4 = getShort(0xB0) CO.AC5 = getShort(0xB2) CO.AC6 = getShort(0xB4) CO.B1 = getShort(0xB6, true) CO.B2 = getShort(0xB8, true) CO.MB = getShort(0xBA, true) CO.MC = getShort(0xBC, true) CO.MD = getShort(0xBE, true) end --get temperature from bmp085 --parameters: --num_10x: bool value, if true, return number of 0.1 centi-degree -- default value is false, which return a string , eg: 16.7 function M.getUT(num_10x) write_reg(0x77, 0xF4, 0x2E); tmr.delay(10000); local temp = getShort(0xF6) local X1 = (temp - CO.AC6) * CO.AC5 / 32768 local X2 = CO.MC * 2048/(X1 + CO.MD) local r = (X2 + X1 + 8)/16 if(num_10x == true) then return r else return ((r/10).."."..(r%10)) end end --get raw data of pressure from bmp085 --parameters: --oss: over sampling setting, which is 0,1,2,3. Default value is 0 function M.getUP_raw(oss) local os = 0 if ((oss == 0) or (oss == 1) or (oss == 2) or (oss == 3)) and (oss ~= nil) then os = oss end local ov = os * 64 write_reg(0x77, 0xF4, (0x34 + ov)); tmr.delay(30000); --delay 30ms, according to bmp085 document, wait time are: -- 4.5ms 7.5ms 13.5ms 25.5ms respectively according to oss 0,1,2,3 local MSB = string.byte(read_reg(0x77, 0xF6)) local LSB = string.byte(read_reg(0x77, 0xF7)) local XLSB = string.byte(read_reg(0x77, 0xF8)) local up_raw = (MSB*65536 + LSB *256 + XLSB)/2^(8 - os) return up_raw end --get calibrated data of pressure from bmp085 --parameters: --oss: over sampling setting, which is 0,1,2,3. Default value is 0 function M.getUP(oss) local os = 0 if ((oss == 0) or (oss == 1) or (oss == 2) or (oss == 3)) and (oss ~= nil) then os = oss end local raw = M.getUP_raw(os) local B5 = M.getUT(true) * 16 - 8; local B6 = B5 - 4000 local X1 = CO.B2 * (B6 * B6 /4096)/2048 local X2 = CO.AC2 * B6 / 2048 local X3 = X1 + X2 local B3 = ((CO.AC1*4 + X3)*2^os + 2)/4 X1 = CO.AC3 * B6 /8192 X2 = (CO.B1 * (B6 * B6 / 4096))/65536 X3 = (X1 + X2 + 2)/4 local B4 = CO.AC4 * (X3 + 32768) / 32768 local B7 = (raw -B3) * (50000/2^os) local p = B7/B4 * 2 X1 = (p/256)^2 X1 = (X1 *3038)/65536 X2 = (-7357 *p)/65536 p = p +(X1 + X2 + 3791)/16 return p end --get estimated data of altitude from bmp085 --parameters: --oss: over sampling setting, which is 0,1,2,3. Default value is 0 function M.getAL(oss) --Altitudi can be calculated by pressure refer to sea level pressure, which is 101325 --pressure changes 100pa corresponds to 8.43m at sea level return (M.getUP(oss) - 101325)*843/10000 end return M
mit
LORgames/premake-core
tests/project/test_config_maps.lua
32
3971
-- -- tests/project/test_config_maps.lua -- Test mapping from workspace to project configurations. -- Copyright (c) 2012-2014 Jason Perkins and the Premake project -- local suite = test.declare("project_config_maps") -- -- Setup and teardown -- local wks, prj, cfg function suite.setup() wks = workspace("MyWorkspace") configurations { "Debug", "Release" } end local function prepare(buildcfg, platform) prj = wks.projects[1] cfg = test.getconfig(prj, buildcfg or "Debug", platform) end -- -- When no configuration is specified in the project, the workspace -- settings should map directly to a configuration object. -- function suite.workspaceConfig_onNoProjectConfigs() project ("MyProject") prepare() test.isequal("Debug", cfg.buildcfg) end -- -- If a project configuration mapping exists, it should be taken into -- account when fetching the configuration object. -- function suite.appliesCfgMapping_onBuildCfgMap() project ("MyProject") configmap { ["Debug"] = "Development" } prepare() test.isequal("Development", cfg.buildcfg) end function suite.appliesCfgMapping_onPlatformMap() platforms { "Shared", "Static" } project ("MyProject") configmap { ["Shared"] = "DLL" } prepare("Debug", "Shared") test.isequal("DLL", cfg.platform) end -- -- If a configuration mapping exists, can also use the mapped value -- to fetch the configuration. -- function suite.fetchesMappedCfg_onBuildCfgMap() project ("MyProject") configmap { ["Debug"] = "Development" } prepare("Development") test.isequal("Development", cfg.buildcfg) end function suite.fetchesMappedCfg_onPlatformMap() platforms { "Shared", "Static" } project ("MyProject") configmap { ["Shared"] = "DLL" } prepare("Debug", "DLL") test.isequal("DLL", cfg.platform) end -- -- If the specified configuration has been removed from the project, -- then nil should be returned. -- function suite.returnsNil_onRemovedBuildCfg() project ("MyProject") removeconfigurations { "Debug" } prepare() test.isnil(cfg) end function suite.returnsNil_onRemovedPlatform() platforms { "Shared", "Static" } project ("MyProject") removeplatforms { "Shared" } prepare("Debug", "Shared") test.isnil(cfg) end -- -- Check mapping from a buildcfg-platform tuple to a simple single -- value platform configuration. -- function suite.canMap_tupleToSingle() platforms { "Win32", "Linux" } project ("MyProject") removeconfigurations "*" removeplatforms "*" configurations { "Debug Win32", "Release Win32", "Debug Linux", "Release Linux" } configmap { [{"Debug", "Win32"}] = "Debug Win32", [{"Debug", "Linux"}] = "Debug Linux", [{"Release", "Win32"}] = "Release Win32", [{"Release", "Linux"}] = "Release Linux" } prepare("Debug", "Linux") test.isequal("Debug Linux", cfg.buildcfg) end -- -- Check mapping from a buildcfg-platform tuple to new project -- configuration tuple. -- function suite.canMap_tupleToTuple() platforms { "Win32", "Linux" } project ("MyProject") removeconfigurations "*" removeplatforms "*" configurations { "Development", "Production" } platforms { "x86", "x86_64" } configmap { [{"Debug", "Win32"}] = { "Development", "x86" }, [{"Debug", "Linux"}] = { "Development", "x86_64" }, [{"Release", "Win32"}] = { "Production", "x86" }, [{"Release", "Linux"}] = { "Production", "x86_64" }, } prepare("Debug", "Linux") test.isequal({ "Development", "x86_64" }, { cfg.buildcfg, cfg.platform }) end -- -- To allow some measure of global configuration, config maps that are contained -- in configuration blocks are allowed to bubble up to the project level. -- function suite.canBubbleUp_onConfiguration() platforms { "XCUA", "XCUB" } filter { "platforms:CCU" } configmap { XCUA = "CCU", XCUB = "CCU" } project "MyProject" platforms { "CCU" } prepare("Debug", "XCUA") test.isequal({"Debug", "CCU"}, {cfg.buildcfg, cfg.platform}) end
bsd-3-clause
gbox3d/nodemcu-firmware
lua_modules/ds3231/ds3231-web.lua
84
1338
require('ds3231') port = 80 -- ESP-01 GPIO Mapping gpio0, gpio2 = 3, 4 days = { [1] = "Sunday", [2] = "Monday", [3] = "Tuesday", [4] = "Wednesday", [5] = "Thursday", [6] = "Friday", [7] = "Saturday" } months = { [1] = "January", [2] = "Febuary", [3] = "March", [4] = "April", [5] = "May", [6] = "June", [7] = "July", [8] = "August", [9] = "September", [10] = "October", [11] = "November", [12] = "December" } ds3231.init(gpio0, gpio2) srv=net.createServer(net.TCP) srv:listen(port, function(conn) second, minute, hour, day, date, month, year = ds3231.getTime() prettyTime = string.format("%s, %s %s %s %s:%s:%s", days[day], date, months[month], year, hour, minute, second) conn:send("HTTP/1.1 200 OK\nContent-Type: text/html\nRefresh: 5\n\n" .. "<!DOCTYPE HTML>" .. "<html><body>" .. "<b>ESP8266</b></br>" .. "Time and Date: " .. prettyTime .. "<br>" .. "Node ChipID : " .. node.chipid() .. "<br>" .. "Node MAC : " .. wifi.sta.getmac() .. "<br>" .. "Node Heap : " .. node.heap() .. "<br>" .. "Timer Ticks : " .. tmr.now() .. "<br>" .. "</html></body>") conn:on("sent",function(conn) conn:close() end) end )
mit
Anarchid/Zero-K
LuaUI/camain.lua
5
4061
-- $Id: camain.lua 3171 2008-11-06 09:06:29Z det $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- file: main.lua -- brief: the entry point from gui.lua, relays call-ins to the widget manager -- author: Dave Rodgers -- -- Copyright (C) 2007. -- Licensed under the terms of the GNU GPL, v2 or later. -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local vfsInclude = VFS.Include local vfsGame = VFS.GAME local spSendCommands = Spring.SendCommands spSendCommands("ctrlpanel LuaUI/ctrlpanel.txt") vfsInclude("LuaUI/utils.lua" , nil, vfsGame) vfsInclude("LuaUI/setupdefs.lua", nil, vfsGame) vfsInclude("LuaUI/savetable.lua", nil, vfsGame) vfsInclude("LuaUI/debug.lua" , nil, vfsGame) vfsInclude("LuaUI/modfonts.lua" , nil, vfsGame) vfsInclude("LuaUI/layout.lua" , nil, vfsGame) -- contains a simple LayoutButtons() vfsInclude("LuaUI/cawidgets.lua", nil, vfsGame) -- the widget handler spSendCommands("echo " .. LUAUI_VERSION) local gl = Spring.Draw -- easier to use ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- -- A few helper functions -- function Say(msg) spSendCommands('say ' .. msg) end ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- -- Update() -- called every frame -- activePage = 0 forceLayout = true function Update() local currentPage = Spring.GetActivePage() if (forceLayout or (currentPage ~= activePage)) then Spring.ForceLayoutUpdate() -- for the page number indicator forceLayout = false end activePage = currentPage fontHandler.Update() widgetHandler:Update() return end ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- -- WidgetHandler fixed calls -- function Shutdown() return widgetHandler:Shutdown() end function ConfigureLayout(command) return widgetHandler:ConfigureLayout(command) end function CommandNotify(id, params, options) return widgetHandler:CommandNotify(id, params, options) end function UnitCommandNotify(unitID, id, params, options) return widgetHandler:UnitCommandNotify(unitID, id, params, options) end function DrawScreen(vsx, vsy) return widgetHandler:DrawScreen() end function KeyPress(key, mods, isRepeat) return widgetHandler:KeyPress(key, mods, isRepeat) end function KeyRelease(key, mods) return widgetHandler:KeyRelease(key, mods) end function TextInput(utf8, ...) return widgetHandler:TextInput(utf8, ...) end function MouseMove(x, y, dx, dy, button) return widgetHandler:MouseMove(x, y, dx, dy, button) end function MousePress(x, y, button) return widgetHandler:MousePress(x, y, button) end function MouseRelease(x, y, button) return widgetHandler:MouseRelease(x, y, button) end function IsAbove(x, y) return widgetHandler:IsAbove(x, y) end function GetTooltip(x, y) return widgetHandler:GetTooltip(x, y) end function AddConsoleLine(msg, priority) return widgetHandler:AddConsoleLine(msg, priority) end function GroupChanged(groupID) return widgetHandler:GroupChanged(groupID) end local allModOptions = Spring.GetModOptions() function Spring.GetModOption(s,bool,default) if (bool) then local modOption = allModOptions[s] if (modOption==nil) then modOption = (default and "1") end return (modOption=="1") else local modOption = allModOptions[s] if (modOption==nil) then modOption = default end return modOption end end -- -- The unit (and some of the Draw) call-ins are handled -- differently (see LuaUI/widgets.lua / UpdateCallIns()) -- --------------------------------------------------------------------------------
gpl-2.0
gberger/PES-3
src/controllers/authentication_controller.lua
1
1936
--[[ Módulo responsável por ser o controlador das rotas autenticação de usuário Possui as seguintes funções: login: exibe página de login authenticate: verifica se a senha de usuário é válida logout: efetua o logout do usuário ]] local view = require('view') local Authentication = require('models/authentication') local M = { new = function(self) local controller = {} setmetatable(controller, {__index = self.metatable}) return controller end, } M.metatable = { --[[ Responsabilidade: Método para a rota de login Pré-Condição: * - Pós-Condição: * Retorna a página de login ]] login = function(self, params) return view.render("login.html.elua") end, --[[ Responsabilidade: Método para a rota de autenticação Pré-Condição: * Deve receber parametros da rota (senha, cookie, etc) Pós-Condição: * Retorna a página raiz ou retorna página de senha incorreta caso a senha esteja incorreta ]] authenticate = function(self, params) local auth = Authentication:new(params.cookie) if auth:login(params.password) then return view.redirect_to("/") else return view.render("login.html.elua", {args = {err = "Senha incorreta"}}) end end, --[[ Responsabilidade: Método para a rota de logout Pré-Condição: * Deve receber parametros da rota (cookie) Pós-Condição: * Retorna a página raiz ]] logout = function(self, params) local auth = Authentication:new(params.cookie) auth:logout() return view.redirect_to("/") end, --[[ Responsabilidade: Método para a rota de informação do usuário Pré-Condição: * Deve receber parametros da rota (cookie) Pós-Condição: * Retorna um json informando se o usuário está logado ou não ]] info = function(self, params) local auth = Authentication:new(params.cookie) return view.render_json{logged = auth:is_signedin()} end } return M
mit
Sasu98/Nerd-Gaming-Public
resources/NGModshop/cBlip.lua
2
1227
local locations = { } local shopBlips = { } local areBlipsEnabled = false; addEvent ( "NGModshop:sendClientShopLocations", true ); addEventHandler ( "NGModshop:sendClientShopLocations", root, function ( l ) locations = l; end ); addEvent ( "onClientPlayerLogin", true ); addEventHandler ( "onClientPlayerLogin", root, function ( ) setTimer ( function ( ) setBlipsEnabled ( exports.NGPhone:getSetting ( "usersetting_display_modshopblips" ) ); end, 1000, 1 ); end ); addEvent ( "onClientUserSettingChange", true ); addEventHandler ( "onClientUserSettingChange", root, function ( setting, value ) if ( setting == "usersetting_display_modshopblips" ) then if ( value and not areBlipsEnabled ) then setBlipsEnabled ( true ); elseif ( not value and areBlipsEnabled ) then setBlipsEnabled ( false ); end end end ); function setBlipsEnabled ( b ) if ( b and not areBlipsEnabled ) then for i, v in pairs ( locations ) do local x, y, z = unpack ( v ); shopBlips [ i ] = createBlip ( x, y, z, 27, 2, 255, 255, 255, 255, 0, 450 ) end elseif ( not b and areBlipsEnabled ) then for i, v in pairs ( shopBlips ) do destroyElement ( v ); end shopBlips = { } end areBlipsEnabled = b; end
mit
Anarchid/Zero-K
LuaUI/Widgets/unit_shapes.lua
4
24479
function widget:GetInfo() return { name = "UnitShapes", desc = "0.5.8.zk.02 Draws blended shapes around units and buildings", author = "Lelousius and aegis, modded Licho, CarRepairer, jK, Shadowfury333", date = "30.07.2010", license = "GNU GPL, v2 or later", layer = 2, enabled = true, detailsDefault = 1 } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function SetupCommandColors(state) if state then WG.widgets_handling_selection = (WG.widgets_handling_selection or 1) - 1 if WG.widgets_handling_selection > 0 then return end else WG.widgets_handling_selection = (WG.widgets_handling_selection or 0) + 1 end local alpha = state and 1 or 0 Spring.LoadCmdColorsConfig('unitBox 0 1 0 ' .. alpha) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local math_acos = math.acos local math_pi = math.pi local math_cos = math.cos local math_sin = math.sin local math_abs = math.abs local rad_con = 180 / math_pi local GL_KEEP = 0x1E00 local GL_REPLACE = 0x1E01 local spGetUnitIsDead = Spring.GetUnitIsDead local spGetUnitHeading = Spring.GetUnitHeading local spGetVisibleUnits = Spring.GetVisibleUnits local spGetSelectedUnits = Spring.GetSelectedUnits local spGetUnitDefID = Spring.GetUnitDefID local spIsUnitSelected = Spring.IsUnitSelected local spGetCameraPosition = Spring.GetCameraPosition local spGetGameFrame = Spring.GetGameFrame local spTraceScreenRay = Spring.TraceScreenRay local spGetMouseState = Spring.GetMouseState local SafeWGCall = function(fnName, param1) if fnName then return fnName(param1) else return nil end end local GetUnitUnderCursor = function(onlySelectable) return SafeWGCall(WG.PreSelection_GetUnitUnderCursor, onlySelectable) end local IsSelectionBoxActive = function() return SafeWGCall(WG.PreSelection_IsSelectionBoxActive) end local GetUnitsInSelectionBox = function() return SafeWGCall(WG.PreSelection_GetUnitsInSelectionBox) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local clearquad local shapes = {} local myTeamID = Spring.GetLocalTeamID() --local r,g,b = Spring.GetTeamColor(myTeamID) local r,g,b = 0.1, 1, 0.2 local rgba = {r,g,b,1} local yellow = {1,1,0.1,1} local teal = {0.1,1,1,1} local red = {1,0.2,0.1,1} local hoverColor = teal local circleDivs = 32 -- how precise circle? octagon by default local innersize = 0.9 -- circle scale compared to unit radius local selectinner = 1.5 local outersize = 1.8 -- outer fade size compared to circle scale (1 = no outer fade) local scalefaktor = 2.8 local rectangleFactor = 2.7 local CAlpha = 0.2 local hoverScaleDuration = 0.05 local hoverScaleStart = 0.95 local hoverScaleEnd = 1.0 local hoverRestedTime = 0.05 --Time in ms below which the player is assumed to be rapidly hovering over different units local hoverBufferDisplayTime = 0.05 --Time in ms to keep showing hover when starting box selection local hoverBufferScaleSuppressTime = 0.1 --Time in ms to stop box select from doing scale effect on a hovered unit local boxedScaleDuration = 0.05 local boxedScaleStart = 0.9 local boxedScaleEnd = 1.0 local colorout = { 1, 1, 1, 0 } -- outer color local colorin = { r, g, b, 1 } -- inner color local teamColors = {} local unitConf = {} ------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------ local lastBoxedUnits = {} local lastBoxedUnitsIDs = {} local selectedUnits = {} local visibleBoxed = {} local visibleAllySelUnits = {} local hoveredUnit = {} local hasVisibleAllySelections = false local forceUpdate = false ------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------ options_path = 'Settings/Interface/Selection/Selection Shapes' options_order = {'allyselectionlevel', 'showallyplayercolours', 'showhover', 'showinselectionbox', 'animatehover', 'animateselectionbox'} options = { allyselectionlevel = { name = 'Show Ally Selections', type = 'radioButton', items = { {name = 'Enabled',key='enabled', desc="Show selected unit of allies."}, {name = 'Commshare Only',key='commshare', desc="Show when sharing unit control."}, {name = 'Disabled',key='disabled', desc="Do not show any allied selection."}, }, value = 'commshare', OnChange = function(self) forceUpdate = true visibleAllySelUnits = {} end, }, showallyplayercolours = { name = 'Use Player Colors when Spectating', desc = 'Highlight allies\' selected units with their color.', type = 'bool', value = false, OnChange = function(self) forceUpdate = true end, noHotkey = true, }, showhover = { name = 'Highlight Hovered Unit', desc = 'Highlight the unit under your cursor.', type = 'bool', value = true, OnChange = function(self) hoveredUnit = {} end, noHotkey = true, }, showinselectionbox = { name = 'Highlight Units in Selection Box', desc = 'Highlight the units in the selection box.', type = 'bool', value = true, noHotkey = true, }, animatehover = { name = 'Animate Hover Shape', desc = '', type = 'bool', value = true, advanced = true, noHotkey = true, }, animateselectionbox = { name = 'Animate Shapes in Selection Box', desc = '', type = 'bool', value = true, advanced = true, noHotkey = true, } } ------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------ local lastCamX, lastCamY, lastCamZ local lastGameFrame = 0 local lastVisibleUnits, lastVisibleSelected, lastvisibleAllySelUnits -- local lastDrawtoolSetting = WG.drawtoolKeyPressed local hoverBuffer = 0 local hoverTime = 0 --how long we've been hovering local cursorIsOn = "self" local function GetBoxedUnits() --Mostly a helper function for the animation system local allBoxedUnits = GetUnitsInSelectionBox() local boxedUnits = {} local boxedUnitsIDs = {} if allBoxedUnits then for i=1, #allBoxedUnits do if #hoveredUnit > 0 and hoveredUnit[1].unitID == allBoxedUnits[i] then --Transfer hovered unit here to avoid flickering boxedUnits[#boxedUnits+1] = hoveredUnit[1] hoveredUnit = {} boxedUnitsIDs[allBoxedUnits[i]] = #boxedUnits elseif hoverBuffer > 0 or spIsUnitSelected(allBoxedUnits[i]) or not options.animateselectionbox.value then --don't scale if it just stopped being hovered over, reduces flicker effect boxedUnitsIDs[allBoxedUnits[i]] = #boxedUnits+1 boxedUnits[#boxedUnits+1] = {unitID = allBoxedUnits[i], scale = boxedScaleEnd} elseif not lastBoxedUnitsIDs[allBoxedUnits[i]] then boxedUnitsIDs[allBoxedUnits[i]] = #boxedUnits+1 boxedUnits[#boxedUnits+1] = {unitID = allBoxedUnits[i], startTime = Spring.GetTimer(), duration = boxedScaleDuration, startScale = boxedScaleStart, endScale = boxedScaleEnd} else boxedUnits[#boxedUnits+1] = lastBoxedUnits[lastBoxedUnitsIDs[allBoxedUnits[i]]] boxedUnitsIDs[allBoxedUnits[i]] = #boxedUnits end end end return boxedUnits, boxedUnitsIDs end local function HasVisibilityChanged() local camX, camY, camZ = spGetCameraPosition() local gameFrame = spGetGameFrame() if forceUpdate or (camX ~= lastCamX) or (camY ~= lastCamY) or (camZ ~= lastCamZ) or ((gameFrame - lastGameFrame) >= 15) or (#lastVisibleSelected > 0) or (#spGetSelectedUnits() > 0) then lastGameFrame = gameFrame lastCamX, lastCamY, lastCamZ = camX, camY, camZ return true end -- if WG.drawtoolKeyPressed ~= lastDrawtoolSetting then -- lastDrawtoolSetting = WG.drawtoolKeyPressed -- return true -- end return false end local function ShowAllySelection(unitID, myTeamID) if options.allyselectionlevel.value == "disabled" or (not WG.allySelUnits[unitID]) then return false end if options.allyselectionlevel.value == "enabled" then return true end local teamID = Spring.GetUnitTeam(unitID) return teamID == myTeamID end local function GetVisibleUnits() local visibleBoxed = {} if options.showinselectionbox.value then local boxedUnits, boxedUnitsIDs = GetBoxedUnits() if IsSelectionBoxActive() then --It's not worth rebuilding visible selected lists for selection box, but selection box needs to be updated per-frame local units = spGetVisibleUnits(-1, nil, false) for i = 1, #units do local unitID = units[i] if boxedUnitsIDs[units[i]] and not WG.drawtoolKeyPressed then visibleBoxed[#visibleBoxed+1] = boxedUnits[boxedUnitsIDs[unitID]] end end end lastBoxedUnits = boxedUnits lastBoxedUnitsIDs = boxedUnitsIDs end if (HasVisibilityChanged()) then local units = spGetVisibleUnits(-1, nil, false) --local visibleUnits = {} local visibleAllySelUnits = {} local visibleSelected = {} local myTeamID = Spring.GetMyTeamID() for i = 1, #units do local unitID = units[i] if (spIsUnitSelected(unitID)) then visibleSelected[#visibleSelected+1] = {unitID = unitID} end if ShowAllySelection(unitID, myTeamID) then local teamIDIndex = Spring.GetUnitTeam(unitID) if teamIDIndex then --Possible nil check failure if unit is destroyed while selected teamIDIndex = teamIDIndex+1 if Spring.GetSpectatingState() and not options.showallyplayercolours.value then teamIDIndex = 1 end if not visibleAllySelUnits[teamIDIndex] then visibleAllySelUnits[teamIDIndex] = {} end visibleAllySelUnits[teamIDIndex][#visibleAllySelUnits[teamIDIndex]+1] = {unitID = unitID, scale = 0.92} hasVisibleAllySelections = true end end end lastvisibleAllySelUnits = visibleAllySelUnits lastVisibleSelected = visibleSelected return visibleAllySelUnits, visibleSelected, visibleBoxed else return lastvisibleAllySelUnits, lastVisibleSelected, visibleBoxed end end local function GetHoveredUnit(dt) --Mostly a convenience function for the animation system local unitID = GetUnitUnderCursor(false) local hoveredUnit = hoveredUnit local cursorIsOn = cursorIsOn if unitID and not spIsUnitSelected(unitID) then if #hoveredUnit == 0 or unitID ~= hoveredUnit[#hoveredUnit].unitID then if hoverTime < hoverRestedTime or not options.animatehover.value then --Only animate hover effect if player is not rapidly changing hovered unit hoveredUnit[1] = {unitID = unitID, scale = hoverScaleEnd} else hoveredUnit[1] = {unitID = unitID, startTime = Spring.GetTimer(), duration = hoverScaleDuration, startScale = hoverScaleStart, endScale = hoverScaleEnd} end local teamID = Spring.GetUnitTeam(unitID) local myTeamID = Spring.GetMyTeamID() if teamID then if teamID == myTeamID then cursorIsOn = "self" elseif teamID and Spring.AreTeamsAllied(teamID, myTeamID) then cursorIsOn = "ally" else cursorIsOn = "enemy" end end hoverTime = 0 else hoverTime = math.min(hoverTime + dt, hoverRestedTime) end hoverBuffer = hoverBufferDisplayTime + hoverBufferScaleSuppressTime elseif hoverBuffer > 0 then hoverBuffer = math.max(hoverBuffer - dt, 0) if hoverBuffer <= hoverBufferScaleSuppressTime then --stop showing hover shape here, but if box selected within a short time don't do scale effect hoveredUnit = {} end if hoverBuffer < hoverBufferScaleSuppressTime then cursorIsOn = "self" --Don't change colour at the last second when over enemy end end return hoveredUnit, cursorIsOn end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Creating polygons: local function CreateDisplayLists(callback) local displayLists = {} local zeroColor = {0, 0, 0, 0} local CAlphaColor = {0, 0, 0, CAlpha} displayLists.select = callback.fading(colorin, colorout, outersize, selectinner) displayLists.invertedSelect = callback.fading(colorout, colorin, outersize, selectinner) displayLists.inner = callback.solid(zeroColor, innersize) displayLists.large = callback.solid(nil, selectinner) displayLists.kill = callback.solid(nil, outersize) displayLists.shape = callback.fading(zeroColor, CAlphaColor, innersize, selectinner) return displayLists end local function CreateCircleLists() local callback = {} function callback.fading(colorin, colorout, innersize, outersize) return gl.CreateList(function() gl.BeginEnd(GL.QUAD_STRIP, function() local radstep = (2.0 * math_pi) / circleDivs for i = 0, circleDivs do local a1 = (i * radstep) if (colorin) then gl.Color(colorin) end gl.Vertex(math_sin(a1)*innersize, 0, math_cos(a1)*innersize) if (colorout) then gl.Color(colorout) end gl.Vertex(math_sin(a1)*outersize, 0, math_cos(a1)*outersize) end end) end) end function callback.solid(color, size) return gl.CreateList(function() gl.BeginEnd(GL.TRIANGLE_FAN, function() local radstep = (2.0 * math_pi) / circleDivs if (color) then gl.Color(color) end gl.Vertex(0, 0, 0) for i = 0, circleDivs do local a1 = (i * radstep) gl.Vertex(math_sin(a1)*size, 0, math_cos(a1)*size) end end) end) end shapes.circle = CreateDisplayLists(callback) end local function CreatePolygonCallback(points, immediate) immediate = immediate or GL.POLYGON local callback = {} function callback.fading(colorin, colorout, innersize, outersize) local diff = outersize - innersize local steps = {} for i=1, #points do local p = points[i] local x, z = p[1]*outersize, p[2]*outersize local xs, zs = (math_abs(x)/x and x or 1), (math_abs(z)/z and z or 1) steps[i] = {x, z, xs, zs} end return gl.CreateList(function() gl.BeginEnd(GL.TRIANGLE_STRIP, function() for i=1, #steps do local step = steps[i] or steps[i-#steps] local nexts = steps[i+1] or steps[i-#steps+1] gl.Color(colorout) gl.Vertex(step[1], 0, step[2]) gl.Color(colorin) gl.Vertex(step[1] - diff*step[3], 0, step[2] - diff*step[4]) gl.Color(colorout) gl.Vertex(step[1] + (nexts[1]-step[1]), 0, step[2] + (nexts[2]-step[2])) gl.Color(colorin) gl.Vertex(nexts[1] - diff*nexts[3], 0, nexts[2] - diff*nexts[4]) end end) end) end function callback.solid(color, size) return gl.CreateList(function() gl.BeginEnd(immediate, function() if (color) then gl.Color(color) end for i=1, #points do local p = points[i] gl.Vertex(size*p[1], 0, size*p[2]) end end) end) end return callback end local function CreateSquareLists() local points = { {-1, 1}, {1, 1}, {1, -1}, {-1, -1} } local callback = CreatePolygonCallback(points, GL.QUADS) shapes.square = CreateDisplayLists(callback) end local function CreateTriangleLists() local points = { {0, -1.3}, {1, 0.7}, {-1, 0.7} } local callback = CreatePolygonCallback(points, GL.TRIANGLES) shapes.triangle = CreateDisplayLists(callback) end local function DestroyShape(shape) gl.DeleteList(shape.select) gl.DeleteList(shape.invertedSelect) gl.DeleteList(shape.inner) gl.DeleteList(shape.large) gl.DeleteList(shape.kill) gl.DeleteList(shape.shape) end function widget:Initialize() if not WG.allySelUnits then WG.allySelUnits = {} end CreateCircleLists() CreateSquareLists() CreateTriangleLists() for udid, unitDef in pairs(UnitDefs) do local xsize, zsize = unitDef.xsize, unitDef.zsize local scale = scalefaktor*( xsize^2 + zsize^2 )^0.5 local shape, xscale, zscale if unitDef.customParams and unitDef.customParams.selection_scale then local factor = (tonumber(unitDef.customParams.selection_scale) or 1) scale = scale*factor xsize = xsize*factor zsize = zsize*factor end if unitDef.isImmobile then shape = shapes.square xscale, zscale = rectangleFactor * xsize, rectangleFactor * zsize elseif (unitDef.canFly) then shape = shapes.triangle xscale, zscale = scale, scale else shape = shapes.circle xscale, zscale = scale, scale end unitConf[udid] = { shape = shape, xscale = xscale, zscale = zscale, noRotate = (unitDef.customParams.select_no_rotate and true) or false } if unitDef.customParams and unitDef.customParams.selection_velocity_heading then unitConf[udid].velocityHeading = true end end clearquad = gl.CreateList(function() local size = 1000 gl.BeginEnd(GL.QUADS, function() gl.Vertex( -size,0, -size) gl.Vertex( Game.mapSizeX+size,0, -size) gl.Vertex( Game.mapSizeX+size,0, Game.mapSizeZ+size) gl.Vertex( -size,0, Game.mapSizeZ+size) end) end) SetupCommandColors(false) end function widget:Shutdown() SetupCommandColors(true) gl.DeleteList(clearquad) for _, shape in pairs(shapes) do DestroyShape(shape) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local visibleSelected = {} local degrot = {} local HEADING_TO_RAD = 1/32768*math.pi local RADIANS_PER_COBANGLE = math.pi / 32768 local function UpdateUnitListScale(unitList) if not unitList then return end local now = Spring.GetTimer() for i=1, #unitList do local startScale = unitList[i].startScale local endScale = unitList[i].endScale local scaleDuration = unitList[i].duration if scaleDuration and scaleDuration > 0 then unitList[i].scale = startScale + math.min(Spring.DiffTimers(now, unitList[i].startTime) / scaleDuration, 1.0) * (endScale - startScale) elseif startScale then unitList[i].scale = startScale elseif not unitList[i].scale then --implicitly allows explicit scale to be set on unitList entry creation unitList[i].scale = 1.0 end end end local function UpdateUnitListRotation(unitList) if not unitList then return end for i = 1, #unitList do local unitID = unitList[i].unitID local udid = spGetUnitDefID(unitID) if udid and unitConf[udid].noRotate then degrot[unitID] = 0 elseif udid and unitConf[udid].velocityHeading then local vx,_,vz = Spring.GetUnitVelocity(unitID) if vx then local speed = vx*vx + vz*vz if speed > 0.25 then local velHeading = Spring.GetHeadingFromVector(vx, vz)*HEADING_TO_RAD degrot[unitID] = 180 + velHeading * rad_con end end else local heading = (not (spGetUnitIsDead(unitID)) and spGetUnitHeading(unitID) or 0) * RADIANS_PER_COBANGLE degrot[unitID] = 180 + heading * rad_con end end end function widget:Update(dt) if options.showhover.value then hoveredUnit, cursorIsOn = GetHoveredUnit(dt) end visibleAllySelUnits, visibleSelected, visibleBoxed = GetVisibleUnits() if #visibleBoxed > 0 then cursorIsOn = "self" end UpdateUnitListRotation(visibleSelected) local teams = Spring.GetTeamList() if Spring.GetSpectatingState() and options.showallyplayercolours.value then for i=1, #teams do if visibleAllySelUnits[teams[i]+1] then UpdateUnitListRotation(visibleAllySelUnits[teams[i]+1]) UpdateUnitListScale(visibleAllySelUnits[teams[i]+1]) end end elseif hasVisibleAllySelections then UpdateUnitListRotation(visibleAllySelUnits[1]) UpdateUnitListScale(visibleAllySelUnits[1]) end UpdateUnitListRotation(hoveredUnit) UpdateUnitListRotation(visibleBoxed) UpdateUnitListScale(visibleSelected) UpdateUnitListScale(hoveredUnit) UpdateUnitListScale(visibleBoxed) end function SetupUnitShapes() -- To fix Water gl.ColorMask(false,false,false,true) gl.BlendFunc(GL.ONE, GL.ONE) gl.Color(0,0,0,1) gl.DepthMask(false) --To fix other stencil effects leaving stencil data in gl.ColorMask(false,false,false,true) gl.StencilFunc(GL.ALWAYS, 0x00, 0xFF) gl.StencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE) -- Does not need to be drawn per Unit .. it covers the whole map gl.CallList(clearquad) end function DrawUnitShapes(unitList, color, underWorld) if not unitList[1] then return end -- Setup unit mask for later depth test against only units (don't test against map) -- gl.ColorMask(false,false,false,false) -- gl.DepthTest(GL.LEQUAL) -- gl.PolygonOffset(-1.0,-1.0) -- gl.StencilFunc(GL.ALWAYS, 0x01, 0xFF) -- gl.StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) -- local visibleUnits = spGetVisibleUnits(-1, nil, true) -- for i=1, #visibleUnits do -- gl.Unit(visibleUnits[i], true) -- end -- gl.DepthTest(false) -- Draw selection circles gl.Color(1,1,1,1) gl.Blending(true) gl.BlendFunc(GL.ONE_MINUS_SRC_ALPHA, GL.SRC_ALPHA) gl.ColorMask(false,false,false,true) if underWorld then gl.DepthTest(GL.GREATER) else gl.DepthTest(GL.LEQUAL) end gl.PolygonOffset(-1.0,-1.0) -- gl.StencilMask(0x01) gl.StencilFunc(GL.ALWAYS, 0x01, 0xFF) gl.StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) for i = 1, #unitList do local unitID = unitList[i].unitID local udid = spGetUnitDefID(unitID) local unit = unitConf[udid] local scale = unitList[i].scale or 1 if (unit) then gl.DrawListAtUnit(unitID, unit.shape.select, false, unit.xscale * scale, 1.0, unit.zscale * scale, degrot[unitID], 0, degrot[unitID], 0) end end gl.DepthTest(false) -- Here The inner of the selected circles are removed gl.Blending(false) gl.ColorMask(false,false,false,false) gl.StencilFunc(GL.ALWAYS, 0x0, 0xFF) gl.StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) for i=1, #unitList do local unitID = unitList[i].unitID local udid = spGetUnitDefID(unitID) local unit = unitConf[udid] local scale = unitList[i].scale or 1 if (unit) then gl.DrawListAtUnit(unitID, unit.shape.large, false, unit.xscale * scale, 1.0, unit.zscale * scale, degrot[unitID], 0, degrot[unitID], 0) end end -- gl.DepthTest(GL.LEQUAL) -- gl.PolygonOffset(-1.0,-1.0) for i=1, #unitList do --Correct underwater local unitID = unitList[i].unitID local _, y, _ = Spring.GetUnitViewPosition(unitID) if y and (y < 0) then gl.Unit(unitID, true) end end -- gl.PolygonOffset(0.0,0.0) -- gl.DepthTest(GL.LESS) -- for i=1, #visibleUnits do -- gl.Unit(visibleUnits[i], true) -- end -- gl.DepthTest(false) -- Really draw the Circles now gl.Color(color) gl.ColorMask(true,true,true,true) gl.Blending(true) gl.BlendFuncSeparate(GL.ONE_MINUS_DST_ALPHA, GL.DST_ALPHA, GL.ONE, GL.ONE) gl.StencilFunc(GL.EQUAL, 0x01, 0xFF) gl.StencilOp(GL_KEEP, GL.ZERO, GL.ZERO) gl.CallList(clearquad) gl.PolygonOffset(0.0,0.0) -- gl.StencilMask(0xFF) end local function DrawCircles(underWorld) if Spring.IsGUIHidden() then return end if (#visibleSelected + #hoveredUnit + #visibleBoxed == 0) and not hasVisibleAllySelections then return end gl.PushAttrib(GL_COLOR_BUFFER_BIT) gl.DepthTest(false) gl.StencilTest(true) hoverColor = cursorIsOn == "enemy" and red or (cursorIsOn == "ally" and yellow or teal) SetupUnitShapes() DrawUnitShapes(visibleSelected, rgba, underWorld) if not Spring.IsGUIHidden() then local spec, _, fullselect = Spring.GetSpectatingState() if spec and options.showallyplayercolours.value then if fullselect then hoverColor = teal end local teams = Spring.GetTeamList() for i=1, #teams do if visibleAllySelUnits[teams[i]+1] then local r,g,b = Spring.GetTeamColor(teams[i]) DrawUnitShapes(visibleAllySelUnits[teams[i]+1], {r,g,b,1}, underWorld) end end elseif visibleAllySelUnits[1] then DrawUnitShapes(visibleAllySelUnits[1], yellow, underWorld) end DrawUnitShapes(hoveredUnit, hoverColor, underWorld) DrawUnitShapes(visibleBoxed, hoverColor, underWorld) end gl.StencilFunc(GL.ALWAYS, 0x0, 0xFF) gl.StencilOp(GL_KEEP, GL_KEEP, GL_KEEP) gl.StencilTest(false) gl.Blending("reset") gl.Color(1,1,1,1) gl.PopAttrib() end function widget:DrawWorldPreUnit() DrawCircles(true) end function widget:DrawWorld() DrawCircles(false) end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
cburlacu/packages
net/smartsnmpd/files/mibs/interfaces.lua
158
4833
-- -- This file is part of SmartSNMP -- Copyright (C) 2014, Credo Semiconductor Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License along -- with this program; if not, write to the Free Software Foundation, Inc., -- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -- local mib = require "smartsnmp" require "ubus" require "uloop" uloop.init() local conn = ubus.connect() if not conn then error("Failed to connect to ubusd") end local if_cache = {} local if_status_cache = {} local if_index_cache = {} local last_load_time = os.time() local function need_to_reload() if os.time() - last_load_time >= 3 then last_load_time = os.time() return true else return false end end local function load_config() if need_to_reload() == true then if_cache = {} if_status_cache = {} if_index_cache = {} -- if description for k, v in pairs(conn:call("network.device", "status", {})) do if_status_cache[k] = {} end for name_ in pairs(if_status_cache) do for k, v in pairs(conn:call("network.device", "status", { name = name_ })) do if k == 'mtu' then if_status_cache[name_].mtu = v elseif k == 'macaddr' then if_status_cache[name_].macaddr = v elseif k == 'up' then if v == true then if_status_cache[name_].up = 1 else if_status_cache[name_].up = 2 end elseif k == 'statistics' then for item, stat in pairs(v) do if item == 'rx_bytes' then if_status_cache[name_].in_octet = stat elseif item == 'tx_bytes' then if_status_cache[name_].out_octet = stat elseif item == 'rx_errors' then if_status_cache[name_].in_errors = stat elseif item == 'tx_errors' then if_status_cache[name_].out_errors = stat elseif item == 'rx_dropped' then if_status_cache[name_].in_discards = stat elseif item == 'tx_dropped' then if_status_cache[name_].out_discards = stat end end end end end if_cache['desc'] = {} for name, status in pairs(if_status_cache) do table.insert(if_cache['desc'], name) for k, v in pairs(status) do if if_cache[k] == nil then if_cache[k] = {} end table.insert(if_cache[k], v) end end -- if index for i in ipairs(if_cache['desc']) do table.insert(if_index_cache, i) end end end mib.module_methods.or_table_reg("1.3.6.1.2.1.2", "The MIB module for managing Interfaces implementations") local ifGroup = { [1] = mib.ConstInt(function () load_config() return #if_index_cache end), [2] = { [1] = { [1] = mib.ConstIndex(function () load_config() return if_index_cache end), [2] = mib.ConstString(function (i) load_config() return if_cache['desc'][i] end), [4] = mib.ConstInt(function (i) load_config() return if_cache['mtu'][i] end), [6] = mib.ConstString(function (i) load_config() return if_cache['macaddr'][i] end), [8] = mib.ConstInt(function (i) load_config() return if_cache['up'][i] end), [10] = mib.ConstCount(function (i) load_config() return if_cache['in_octet'][i] end), [13] = mib.ConstCount(function (i) load_config() return if_cache['in_discards'][i] end), [14] = mib.ConstCount(function (i) load_config() return if_cache['in_errors'][i] end), [16] = mib.ConstCount(function (i) load_config() return if_cache['out_octet'][i] end), [19] = mib.ConstCount(function (i) load_config() return if_cache['out_discards'][i] end), [20] = mib.ConstCount(function (i) load_config() return if_cache['out_errors'][i] end), } } } return ifGroup
gpl-2.0
Sasu98/Nerd-Gaming-Public
resources/NGBank/bank_server.lua
2
6865
local bankLocations = { -- { x, y, z, int, dim, { out x, out y, out z } }, { 362.3, 173.67, 1008.38, 3, 1, { 914.21, -1001.5, 38.1 } }, { 362.3, 173.67, 1008.38, 3, 2, { 2474.86, 1021.09, 10.82 } }, { 362.3, 173.67, 1008.38, 3, 3, { -1705.67, 785.32, 24.89 } }, --{ 2478.19, 1013.93, 10.68, 0, 0, { 899.88, -984.7, 37.35 } }, -- for testing } local startingCash = 1000 local accounts = { } function doesBankAccountExist ( account ) if ( accounts[account] ) then return true else return false end end function createBankAccount ( name ) if ( not doesBankAccountExist ( name ) ) then exports['NGSQL']:db_exec ( "INSERT INTO bank_accounts ( Account, Balance ) VALUES ( ?, ? )", tostring ( name ), tostring ( startingCash ) ) accounts[tostring(name)] = tonumber ( startingCash ) return true end return false end function getBankAccounts ( ) return acounts; end function withdraw ( player, amount ) local acc = getPlayerAccount ( player ) if ( isGuestAccount ( acc ) ) then return false end local acc = getAccountName ( acc ) if ( not doesBankAccountExist ( acc ) ) then createBankAccount ( acc ) end accounts[acc] = accounts[acc] - amount givePlayerMoney ( player, amount ) local today = exports.NGPlayerFunctions:getToday ( ) local lg = getPlayerName ( player ).." withdrew $"..amount local serial = getPlayerSerial ( player ) local ip = getPlayerIP ( player ) exports.NGSQL:db_exec ( "INSERT INTO bank_transactions ( account, log, serial, ip, thetime ) VALUES ( ?, ?, ?, ?, ? )", acc, lg, serial, ip, today ) return true end function deposit ( player, ammount ) local acc = getPlayerAccount ( player ) if ( isGuestAccount ( acc ) ) then return false end local acc = getAccountName ( acc ) if ( not doesBankAccountExist ( acc ) ) then createBankAccount ( acc ) end takePlayerMoney ( player, amount ) accounts[acc] = accounts[acc] + amount return true end function getPlayerBank ( plr ) local acc = getPlayerAccount ( plr ) if ( isGuestAccount ( acc ) ) then return false end local acc = getAccountName ( acc ) if ( not doesBankAccountExist ( acc ) ) then createBankAccount ( acc ) end return accounts[acc] end function onBankMarkerHit ( p ) if ( p and getElementType ( p ) == 'player' and not isPedInVehicle ( p ) ) then if ( getElementInterior ( p ) == getElementInterior ( source ) and getElementDimension ( p ) == getElementDimension ( source ) ) then local acc = getPlayerAccount ( p ) if ( isGuestAccount ( acc ) ) then return false end local acc = getAccountName ( acc ) if ( not doesBankAccountExist ( acc ) ) then createBankAccount ( acc ) end triggerClientEvent ( p, 'NGBank:onClientEnterBank', p, accounts[acc], acc, source ) end end end local bankMarkers = { } addEventHandler ( "onResourceStart", resourceRoot, function ( ) exports['NGSQL']:db_exec ( "CREATE TABLE IF NOT EXISTS bank_accounts ( Account TEXT, Balance INT )" ) exports['NGSQL']:db_exec ( "CREATE TABLE IF NOT EXISTS bank_transactions ( account TEXT, log TEXT, serial TEXT, ip TEXT, thetime DATE )" ) local q = exports['NGSQL']:db_query ( "SELECT * FROM bank_accounts" ) for i, v in ipairs ( q ) do accounts[v['Account']] = tonumber ( v['Balance'] ) end for i, v in pairs ( bankLocations ) do local x, y, z, int, dim, out = unpack ( v ) bankMarkers[i] = createPickup ( x, y, z, 3, 1274, 200, 0 ) local bx, by, bz = unpack ( out ) createBlip ( bx, by, bz, 52 ) setElementInterior ( bankMarkers[i], int ) setElementDimension ( bankMarkers[i], dim ) addEventHandler ( "onPickupHit", bankMarkers[i], onBankMarkerHit ) end for i, v in ipairs ( getElementsByType ( 'player' ) ) do local acc = getAccountName ( getPlayerAccount ( v ) ) setElementData ( v, "NGBank:BankBalance", accounts[acc] or 0 ) end end ) function saveBankAccounts ( ) if ( getResourceState ( getResourceFromName ( "NGSQL" ) ) ~= "running" ) then return end for i, v in pairs ( accounts ) do exports['NGSQL']:db_exec ( "UPDATE bank_accounts SET Balance=? WHERE Account=?", tostring ( v ), tostring ( i ) ) end end addEventHandler ( "onResourceStop", resourceRoot, saveBankAccounts ) addEvent ( "NGBank:ModifyAccount", true ) addEventHandler ( "NGBank:ModifyAccount", root, function ( action, amount ) local acc = getPlayerAccount ( source ) if ( isGuestAccount ( acc ) ) then return exports['NGMessages']:sendClientMessage ( "Please login to use the bank system.", source, 200, 200, 200 ) end local acc = getAccountName ( acc ) local bankBalance = accounts[acc] if ( action == 'withdraw' ) then if ( bankBalance < amount ) then return exports['NGMessages']:sendClientMessage ( "You don't have that much money in your bank account.", source, 200, 200, 200 ) end accounts[acc] = accounts[acc] - amount givePlayerMoney ( source, amount ) exports['NGMessages']:sendClientMessage ( "You've withdrawn $"..tostring ( amount ).." from your bank account", source, 200, 200, 200 ) exports['NGLogs']:outputActionLog ( getPlayerName ( source ).." deposited $"..tostring(amount).." into his bank. (Total: $"..accounts[acc]..")" ) lg = getPlayerName ( source ).." withdrew $"..amount elseif ( action == 'deposit' ) then if ( amount > getPlayerMoney ( source ) ) then return exports['NGMessages']:sendClientMessage ( "You don't have that much money.", source, 200, 200, 200 ) end accounts[acc] = bankBalance + amount takePlayerMoney ( source, amount ) exports['NGMessages']:sendClientMessage ( "You've deposited $"..tostring ( amount ).." into your bank account.", source, 200, 200, 200 ) exports['NGLogs']:outputActionLog ( getPlayerName ( source ).." deposited $"..tostring(amount).." into his bank. (Total: $"..accounts[acc]..")" ) lg = getPlayerName ( source ).." deposited $"..amount end setElementData ( source, "NGBank:BankBalance", accounts[acc] ) triggerClientEvent ( source, "NGBanks:resfreshBankData", source, accounts[acc] ) -- log it local today = exports.NGPlayerFunctions:getToday ( ) local serial = getPlayerSerial ( source ) local ip = getPlayerIP ( source ) exports.NGSQL:db_exec ( "INSERT INTO bank_transactions ( account, log, serial, ip, thetime ) VALUES ( ?, ?, ?, ?, ? )", acc, lg, serial, ip, today ) end ) addEventHandler ( "onPlayerJoin", root, function ( ) setElementData ( source, "NGBank:BankBalance", 0 ) end ) addEventHandler ( "onPlayerLogin", root, function ( _, acc ) local acc = getAccountName ( acc ) setElementData ( source, "NGBank:BankBalance", accounts[acc] or 0 ) end ) function getAccountBalance ( account ) return accounts [ account ] end addEvent ( "NGBank->OnClientHitBankMarker", true ) addEventHandler ( "NGBank->OnClientHitBankMarker", root, function ( player, mark ) outputChatBox ( "Hi, "..getPlayerName ( player ) ) onBankMarkerHit ( player, mark ) end )
mit
fegimanam/crd
plugins/Boobs.lua
150
1613
do -- Recursive function local function getRandomButts(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.obutts.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt <= 3 then print('Cannot get that butts, trying another one...') return getRandomButts(attempt) end return 'http://media.obutts.ru/' .. data.preview end local function getRandomBoobs(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.oboobs.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt < 10 then print('Cannot get that boobs, trying another one...') return getRandomBoobs(attempt) end return 'http://media.oboobs.ru/' .. data.preview end local function run(msg, matches) local url = nil if matches[1] == "!boobs" then url = getRandomBoobs() end if matches[1] == "!butts" then url = getRandomButts() end if url ~= nil then local receiver = get_receiver(msg) send_photo_from_url(receiver, url) else return 'Error getting boobs/butts for you, please try again later.' end end return { description = "Gets a random boobs or butts pic", usage = { "!boobs: Get a boobs NSFW image. ًں”‍", "!butts: Get a butts NSFW image. ًں”‍" }, patterns = { "^!boobs$", "^!butts$" }, run = run } end
gpl-2.0
Mutos/StarsOfCall-NAEV
dat/events/npc/npc.lua
1
8153
--[[ -- Event for creating random characters in the spaceport bar. -- The random NPCs will tell the player things about the Naev universe in general, about their faction, or about the game itself. -- This file contains the mechanisms to retrieve and display the messages. -- Actual messages are dispatched in several smaller include files for different types of messages --]] -- Define the variables lang = naev.lang() civ_port = {} civ_name = "Civilian" msg_lore = {} -- Include tutorial information include "dat/events/tutorial/tutorial-common.lua" -- Used for referencing the tutorials -- Include common data include "dat/events/npc/common/descriptions.lua" -- NPCs generic descriptions include "dat/events/npc/common/tips.lua" -- Gameplay tips include "dat/events/npc/common/jumps.lua" -- Jump points information include "dat/events/npc/common/events.lua" -- Events hints and after-care include "dat/events/npc/common/missions.lua" -- Missions hints and after-care -- Include faction-specific data include "dat/events/npc/factions/general.lua" -- General portraits and lore messages include "dat/events/npc/factions/independent.lua" -- Portraits and lore messages related to the Independents include "dat/events/npc/factions/hoshinohekka.lua" -- Portraits and lore messages related to the Hoshi no Hekka include "dat/events/npc/factions/aktamanniskor.lua" -- Portraits and lore messages related to the Akta Manniskor include "dat/events/npc/factions/irilia.lua" -- Portraits and lore messages related to the Irilia Clan include "dat/events/npc/factions/arythem.lua" -- Portraits and lore messages related to the Arythem Clan include "dat/events/npc/factions/irmothem.lua" -- Portraits and lore messages related to the Irmothem Clan include "dat/events/npc/factions/coreleague.lua" -- Portraits and lore messages related to the Core League include "dat/events/npc/factions/danebanarchs.lua" -- Portraits and lore messages related to the Daneb Anarchs function create() -- Logic to decide what to spawn, if anything. -- TODO: Do not spawn any NPCs on restricted assets. local num_npc = rnd.rnd(1, 5) npcs = {} for i = 0, num_npc do spawnNPC() end -- End event on takeoff. hook.takeoff( "leave" ) end -- Spawns an NPC. function spawnNPC() local npcname = civ_name local factions = {} local func = nil -- Select a faction for the NPC. NPCs may not have a specific faction. for i, _ in pairs(msg_lore) do factions[#factions + 1] = i end local fac = "general" local select = rnd.rnd() if select >= (0.5) and planet.cur():faction() ~= nil then fac = planet.cur():faction():name() end -- Append the faction to the civilian name, unless there is no faction. if fac ~= "general" then npcname = fac .. " " .. civ_name end -- Select a portrait local portrait = getCivPortrait(fac) -- Select a description for the civilian. local desc = civ_desc[rnd.rnd(1, #civ_desc)] -- Select what this NPC should say. select = rnd.rnd() local msg if select <= 0.3 then -- Lore message. msg = getLoreMessage(fac) elseif select <= 0.55 then -- Jump point message. msg, func = getJmpMessage() elseif select <= 0.8 then -- Gameplay tip message. msg = getTipMessage() else -- Mission hint message. msg = getMissionLikeMessage() end local npcdata = {name = npcname, msg = msg, func = func} id = evt.npcAdd("talkNPC", npcname, portrait, desc, 10) npcs[id] = npcdata end -- Returns a lore message for the given faction. function getLoreMessage(fac) -- Get lore messages for the given faction local facmsg = msg_lore[fac] if fac == nil then -- print ( "\tLore messages : no Faction given" ) else -- print ( string.format( "\tLore messages : Faction = \"%s\"", fac )) end if facmsg == nil or #facmsg == 0 then -- print ( "\t\tLore messages : no messages for Faction, taking General" ) facmsg = msg_lore["general"] if facmsg == nil or #facmsg == 0 then -- print ( "\t\tLore messages : no message for Faction or General, finishing Event" ) evt.finish(false) end end -- DEBUG : -- print the # of lore messages found -- print ( string.format("\t\tLore messages : %i messages found", #facmsg)) -- Select a string, then remove it from the list of valid strings. This ensures all NPCs have something different to say. local select = rnd.rnd(1, #facmsg) local pick = facmsg[select] -- print ( string.format("\t\tLore messages : message selected : \"%s\"", pick, #facmsg)) table.remove(facmsg, select) -- print ( string.format("\t\tLore messages : %i messages at end of selection", #facmsg)) return pick end -- Returns a jump point message and updates jump point known status accordingly. If all jumps are known by the player, defaults to a lore message. function getJmpMessage() -- Collect a table of jump points in the system the player does NOT know. local mytargets = {} seltargets = seltargets or {} -- We need to keep track of jump points NPCs will tell the player about so there are no duplicates. for _, j in ipairs(system.cur():jumps(true)) do if not j:known() and not j:hidden() and not seltargets[j] then table.insert(mytargets, j) end end if #mytargets == 0 then -- The player already knows all jumps in this system. return getLoreMessage(), nil end -- All jump messages are valid always. if #msg_jmp == 0 then return getLoreMessage(), nil end local retmsg = msg_jmp[rnd.rnd(1, #msg_jmp)] local sel = rnd.rnd(1, #mytargets) local myfunc = function() mytargets[sel]:setKnown(true) mytargets[sel]:system():setKnown(true, false) end -- Don't need to remove messages from tables here, but add whatever jump point we selected to the "selected" table. seltargets[mytargets[sel]] = true return retmsg:format(mytargets[sel]:dest():name()), myfunc end -- Returns a tip message. function getTipMessage() -- All tip messages are valid always. if #msg_tip == 0 then return getLoreMessage() end local sel = rnd.rnd(1, #msg_tip) local pick = msg_tip[sel] table.remove(msg_tip, sel) return pick end -- Returns a mission hint message, a mission after-care message, OR a lore message if no missionlikes are left. function getMissionLikeMessage() if not msg_combined then msg_combined = {} -- Hints. -- Hint messages are only valid if the relevant mission has not been completed and is not currently active. for i, j in pairs(msg_mhint) do if not (player.misnDone(j[1]) or player.misnActive(j[1])) then msg_combined[#msg_combined + 1] = j[2] end end for i, j in pairs(msg_ehint) do if not(player.evtDone(j[1]) or player.evtActive(j[1])) then msg_combined[#msg_combined + 1] = j[2] end end -- After-care. -- After-care messages are only valid if the relevant mission has been completed. for i, j in pairs(msg_mdone) do if player.misnDone(j[1]) then msg_combined[#msg_combined + 1] = j[2] end end for i, j in pairs(msg_edone) do if player.evtDone(j[1]) then msg_combined[#msg_combined + 1] = j[2] end end end if #msg_combined == 0 then return getLoreMessage() else -- Select a string, then remove it from the list of valid strings. This ensures all NPCs have something different to say. local sel = rnd.rnd(1, #msg_combined) local pick pick = msg_combined[sel] table.remove(msg_combined, sel) return pick end end -- Returns a portrait for a given faction. function getCivPortrait(fac) -- Get a factional portrait if possible, otherwise fall back to the generic ones. if civ_port[fac] == nil or #civ_port[fac] == 0 then fac = "general" end return civ_port[fac][rnd.rnd(1, #civ_port[fac])] end function talkNPC(id) local npcdata = npcs[id] if npcdata.func then -- Execute NPC specific code npcdata.func() end tk.msg(npcdata.name, "\"" .. npcdata.msg .. "\"") end --[[ -- Event is over when player takes off. --]] function leave () evt.finish() end
gpl-3.0
Anarchid/Zero-K
LuaRules/Utilities/glVolumes.lua
8
10399
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Exported Functions: -- gl.Utilities.DrawMyBox(minX,minY,minZ, maxX,maxY,maxZ) -- gl.Utilities.DrawMyCylinder(x,y,z, height,radius,divs) -- gl.Utilities.DrawMyHollowCylinder(x,y,z, height,radius,innerRadius,divs) -- gl.Utilities.DrawGroundRectangle(x1,z1,x2,z2) -- gl.Utilities.DrawGroundCircle(x,z,radius) -- gl.Utilities.DrawGroundHollowCircle(x,z,radius,innerRadius) -- gl.Utilities.DrawVolume(vol_dlist) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if (not gl) then return end gl.Utilities = gl.Utilities or {} if gl.Utilities.DrawMyBox then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local min = math.min local max = math.max local sin = math.sin local cos = math.cos local floor = math.floor local TWO_PI = math.pi * 2 local glVertex = gl.Vertex GL.KEEP = 0x1E00 GL.INCR_WRAP = 0x8507 GL.DECR_WRAP = 0x8508 GL.INCR = 0x1E02 GL.DECR = 0x1E03 GL.INVERT = 0x150A local stencilBit1 = 0x01 local stencilBit2 = 0x10 -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gl.Utilities.DrawMyBox(minX,minY,minZ, maxX,maxY,maxZ) gl.BeginEnd(GL.QUADS, function() --// top glVertex(minX, maxY, minZ) glVertex(minX, maxY, maxZ) glVertex(maxX, maxY, maxZ) glVertex(maxX, maxY, minZ) --// bottom glVertex(minX, minY, minZ) glVertex(maxX, minY, minZ) glVertex(maxX, minY, maxZ) glVertex(minX, minY, maxZ) end) gl.BeginEnd(GL.QUAD_STRIP, function() --// sides glVertex(minX, maxY, minZ) glVertex(minX, minY, minZ) glVertex(minX, maxY, maxZ) glVertex(minX, minY, maxZ) glVertex(maxX, maxY, maxZ) glVertex(maxX, minY, maxZ) glVertex(maxX, maxY, minZ) glVertex(maxX, minY, minZ) glVertex(minX, maxY, minZ) glVertex(minX, minY, minZ) end) end function gl.Utilities.DrawMy3DTriangle(x1,z1, x2, z2, x3,z3, minY, maxY) gl.BeginEnd(GL.TRIANGLES, function() --// top glVertex(x1, maxY, z1) glVertex(x2, maxY, z2) glVertex(x3, maxY, z3) --// bottom glVertex(x1, minY, z1) glVertex(x3, minY, z3) glVertex(x2, minY, z2) end) gl.BeginEnd(GL.QUAD_STRIP, function() --// sides glVertex(x1, maxY, z1) glVertex(x1, minY, z1) glVertex(x2, maxY, z2) glVertex(x2, minY, z2) glVertex(x3, maxY, z3) glVertex(x3, minY, z3) glVertex(x1, maxY, z1) glVertex(x1, minY, z1) end) end local function CreateSinCosTable(divs) local sinTable = {} local cosTable = {} local divAngle = TWO_PI / divs local alpha = 0 local i = 1 repeat sinTable[i] = sin(alpha) cosTable[i] = cos(alpha) alpha = alpha + divAngle i = i + 1 until (alpha >= TWO_PI) sinTable[i] = 0.0 -- sin(TWO_PI) cosTable[i] = 1.0 -- cos(TWO_PI) return sinTable, cosTable end function gl.Utilities.DrawMyCylinder(x,y,z, height,radius,divs) divs = divs or 25 local sinTable, cosTable = CreateSinCosTable(divs) local bottomY = y - (height / 2) local topY = y + (height / 2) gl.BeginEnd(GL.TRIANGLE_STRIP, function() --// top for i = #sinTable, 1, -1 do glVertex(x + radius*sinTable[i], topY, z + radius*cosTable[i]) glVertex(x, topY, z) end --// degenerate glVertex(x, topY , z) glVertex(x, bottomY, z) glVertex(x, bottomY, z) --// bottom for i = #sinTable, 1, -1 do glVertex(x + radius*sinTable[i], bottomY, z + radius*cosTable[i]) glVertex(x, bottomY, z) end --// degenerate glVertex(x, bottomY, z) glVertex(x, bottomY, z+radius) glVertex(x, bottomY, z+radius) --// sides for i = 1, #sinTable do local rx = x + radius * sinTable[i] local rz = z + radius * cosTable[i] glVertex(rx, topY , rz) glVertex(rx, bottomY, rz) end end) end function gl.Utilities.DrawMyCircle(x,y,radius,divs) divs = divs or 25 local sinTable, cosTable = CreateSinCosTable(divs) gl.BeginEnd(GL.LINE_LOOP, function() for i = #sinTable, 1, -1 do glVertex(x + radius*sinTable[i], y + radius*cosTable[i], 0) end end) end function gl.Utilities.DrawMyHollowCylinder(x,y,z, height,radius,inRadius,divs) divs = divs or 25 local sinTable, cosTable = CreateSinCosTable(divs) local bottomY = y - (height / 2) local topY = y + (height / 2) gl.BeginEnd(GL.TRIANGLE_STRIP, function() --// top for i = 1, #sinTable do local sa = sinTable[i] local ca = cosTable[i] glVertex(x + inRadius*sa, topY, z + inRadius*ca) glVertex(x + radius*sa, topY, z + radius*ca) end --// sides for i = 1, #sinTable do local rx = x + radius * sinTable[i] local rz = z + radius * cosTable[i] glVertex(rx, topY , rz) glVertex(rx, bottomY, rz) end --// bottom for i = 1, #sinTable do local sa = sinTable[i] local ca = cosTable[i] glVertex(x + radius*sa, bottomY, z + radius*ca) glVertex(x + inRadius*sa, bottomY, z + inRadius*ca) end if (inRadius > 0) then --// inner sides for i = 1, #sinTable do local rx = x + inRadius * sinTable[i] local rz = z + inRadius * cosTable[i] glVertex(rx, bottomY, rz) glVertex(rx, topY , rz) end end end) end local heightMargin = 2000 local minheight, maxheight = Spring.GetGroundExtremes() --the returned values do not change even if we terraform the map local averageGroundHeight = (minheight + maxheight) / 2 local shapeHeight = heightMargin + (maxheight - minheight) + heightMargin local box = gl.CreateList(gl.Utilities.DrawMyBox,0,-0.5,0,1,0.5,1) function gl.Utilities.DrawGroundRectangle(x1,z1,x2,z2) if (type(x1) == "table") then local rect = x1 x1,z1,x2,z2 = rect[1],rect[2],rect[3],rect[4] end gl.PushMatrix() gl.Translate(x1, averageGroundHeight, z1) gl.Scale(x2-x1, shapeHeight, z2-z1) gl.Utilities.DrawVolume(box) gl.PopMatrix() end local triangles = {} function gl.Utilities.DrawGroundTriangle(args) if not triangles[args] then triangles[args] = gl.CreateList(gl.Utilities.DrawMy3DTriangle, args[1], args[2], args[3], args[4], args[5], args[6], -0.5, 0.5) end gl.PushMatrix() gl.Translate(0, averageGroundHeight, 0) gl.Scale(1, shapeHeight, 1) gl.Utilities.DrawVolume(triangles[args]) gl.PopMatrix() end local cylinder = gl.CreateList(gl.Utilities.DrawMyCylinder,0,0,0,1,1,35) function gl.Utilities.DrawGroundCircle(x,z,radius) gl.PushMatrix() gl.Translate(x, averageGroundHeight, z) gl.Scale(radius, shapeHeight, radius) gl.Utilities.DrawVolume(cylinder) gl.PopMatrix() end local circle = gl.CreateList(gl.Utilities.DrawMyCircle,0,0,1,35) function gl.Utilities.DrawCircle(x,y,radius) gl.PushMatrix() gl.Translate(x, y, 0) gl.Scale(radius, radius, 1) gl.Utilities.DrawVolume(circle) gl.PopMatrix() end -- See comment in DrawMergedVolume function gl.Utilities.DrawMergedGroundCircle(x,z,radius) gl.PushMatrix() gl.Translate(x, averageGroundHeight, z) gl.Scale(radius, shapeHeight, radius) gl.Utilities.DrawMergedVolume(cylinder) gl.PopMatrix() end local hollowCylinders = { [ 0 ] = cylinder, } local function GetHollowCylinder(radius, innerRadius) if (innerRadius >= 1) then innerRadius = min(innerRadius / radius, 1.0) end innerRadius = floor(innerRadius * 100 + 0.5) / 100 if (not hollowCylinders[innerRadius]) then hollowCylinders[innerRadius] = gl.CreateList(gl.Utilities.DrawMyHollowCylinder,0,0,0,1,1,innerRadius,35) end return hollowCylinders[innerRadius] end --// when innerRadius is < 1, its value is treated as relative to radius --// when innerRadius is >=1, its value is treated as absolute value in elmos function gl.Utilities.DrawGroundHollowCircle(x,z,radius,innerRadius) local hollowCylinder = GetHollowCylinder(radius, innerRadius) gl.PushMatrix() gl.Translate(x, averageGroundHeight, z) gl.Scale(radius, shapeHeight, radius) gl.Utilities.DrawVolume(hollowCylinder) gl.PopMatrix() end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gl.Utilities.DrawVolume(vol_dlist) gl.DepthMask(false) if (gl.DepthClamp) then gl.DepthClamp(true) end gl.StencilTest(true) gl.Culling(false) gl.DepthTest(true) gl.ColorMask(false, false, false, false) gl.StencilOp(GL.KEEP, GL.INCR, GL.KEEP) --gl.StencilOp(GL.KEEP, GL.INVERT, GL.KEEP) gl.StencilMask(1) gl.StencilFunc(GL.ALWAYS, 0, 1) gl.CallList(vol_dlist) gl.Culling(GL.FRONT) gl.DepthTest(false) gl.ColorMask(true, true, true, true) gl.StencilOp(GL.ZERO, GL.ZERO, GL.ZERO) gl.StencilMask(1) gl.StencilFunc(GL.NOTEQUAL, 0, 1) gl.CallList(vol_dlist) if (gl.DepthClamp) then gl.DepthClamp(false) end gl.StencilTest(false) -- gl.DepthTest(true) gl.Culling(false) end -- Make sure that you start with a clear stencil and that you -- clear it using gl.Clear(GL.STENCIL_BUFFER_BIT, 0) -- after finishing all the merged volumes function gl.Utilities.DrawMergedVolume(vol_dlist) gl.DepthMask(false) if (gl.DepthClamp) then gl.DepthClamp(true) end gl.StencilTest(true) gl.Culling(false) gl.DepthTest(true) gl.ColorMask(false, false, false, false) gl.StencilOp(GL.KEEP, GL.INVERT, GL.KEEP) --gl.StencilOp(GL.KEEP, GL.INVERT, GL.KEEP) gl.StencilMask(1) gl.StencilFunc(GL.ALWAYS, 0, 1) gl.CallList(vol_dlist) gl.Culling(GL.FRONT) gl.DepthTest(false) gl.ColorMask(true, true, true, true) gl.StencilOp(GL.KEEP, GL.INCR, GL.INCR) gl.StencilMask(3) gl.StencilFunc(GL.EQUAL, 1, 3) gl.CallList(vol_dlist) if (gl.DepthClamp) then gl.DepthClamp(false) end gl.StencilTest(false) -- gl.DepthTest(true) gl.Culling(false) end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
lxl1140989/dmsdk
feeds/luci/applications/luci-olsr/luasrc/model/cbi/olsr/olsrdplugins.lua
54
7297
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2009 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ip = require "luci.ip" local fs = require "nixio.fs" if arg[1] then mp = Map("olsrd", translate("OLSR - Plugins")) p = mp:section(TypedSection, "LoadPlugin", translate("Plugin configuration")) p:depends("library", arg[1]) p.anonymous = true ign = p:option(Flag, "ignore", translate("Enable")) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end lib = p:option(DummyValue, "library", translate("Library")) lib.default = arg[1] local function Range(x,y) local t = {} for i = x, y do t[#t+1] = i end return t end local function Cidr2IpMask(val) if val then for i = 1, #val do local cidr = ip.IPv4(val[i]) or ip.IPv6(val[i]) if cidr then val[i] = cidr:network():string() .. " " .. cidr:mask():string() end end return val end end local function IpMask2Cidr(val) if val then for i = 1, #val do local ip, mask = val[i]:gmatch("([^%s]+)%s+([^%s]+)")() local cidr if ip and mask and ip:match(":") then cidr = ip.IPv6(ip, mask) elseif ip and mask then cidr = ip.IPv4(ip, mask) end if cidr then val[i] = cidr:string() end end return val end end local knownPlParams = { ["olsrd_bmf.so.1.5.3"] = { { Value, "BmfInterface", "bmf0" }, { Value, "BmfInterfaceIp", "10.10.10.234/24" }, { Flag, "DoLocalBroadcast", "no" }, { Flag, "CapturePacketsOnOlsrInterfaces", "yes" }, { ListValue, "BmfMechanism", { "UnicastPromiscuous", "Broadcast" } }, { Value, "BroadcastRetransmitCount", "2" }, { Value, "FanOutLimit", "4" }, { DynamicList, "NonOlsrIf", "br-lan" } }, ["olsrd_dyn_gw.so.0.4"] = { { Value, "Interval", "40" }, { DynamicList, "Ping", "141.1.1.1" }, { DynamicList, "HNA", "192.168.80.0/24", IpMask2Cidr, Cidr2IpMask } }, ["olsrd_httpinfo.so.0.1"] = { { Value, "port", "80" }, { DynamicList, "Host", "163.24.87.3" }, { DynamicList, "Net", "0.0.0.0/0", Cidr2IpMask } }, ["olsrd_nameservice.so.0.3"] = { { DynamicList, "name", "my-name.mesh" }, { DynamicList, "hosts", "1.2.3.4 name-for-other-interface.mesh" }, { Value, "suffix", ".olsr" }, { Value, "hosts_file", "/path/to/hosts_file" }, { Value, "add_hosts", "/path/to/file" }, { Value, "dns_server", "141.1.1.1" }, { Value, "resolv_file", "/path/to/resolv.conf" }, { Value, "interval", "120" }, { Value, "timeout", "240" }, { Value, "lat", "12.123" }, { Value, "lon", "12.123" }, { Value, "latlon_file", "/var/run/latlon.js" }, { Value, "latlon_infile", "/var/run/gps.txt" }, { Value, "sighup_pid_file", "/var/run/dnsmasq.pid" }, { Value, "name_change_script", "/usr/local/bin/announce_new_hosts.sh" }, { DynamicList, "service", "http://me.olsr:80|tcp|my little homepage" }, { Value, "services_file", "/var/run/services_olsr" }, { Value, "services_change_script", "/usr/local/bin/announce_new_services.sh" }, { DynamicList, "mac", "xx:xx:xx:xx:xx:xx[,0-255]" }, { Value, "macs_file", "/path/to/macs_file" }, { Value, "macs_change_script", "/path/to/script" } }, ["olsrd_quagga.so.0.2.2"] = { { StaticList, "redistribute", { "system", "kernel", "connect", "static", "rip", "ripng", "ospf", "ospf6", "isis", "bgp", "hsls" } }, { ListValue, "ExportRoutes", { "only", "both" } }, { Flag, "LocalPref", "true" }, { Value, "Distance", Range(0,255) } }, ["olsrd_secure.so.0.5"] = { { Value, "Keyfile", "/etc/private-olsr.key" } }, ["olsrd_txtinfo.so.0.1"] = { { Value, "accept", "127.0.0.1" } }, ["olsrd_jsoninfo.so.0.0"] = { { Value, "accept", "127.0.0.1" }, { Value, "port", "9090" }, { Value, "UUIDFile", "/etc/olsrd/olsrd.uuid" }, }, ["olsrd_watchdog.so.0.1"] = { { Value, "file", "/var/run/olsrd.watchdog" }, { Value, "interval", "30" } }, ["olsrd_mdns.so.1.0.0"] = { { DynamicList, "NonOlsrIf", "lan" } }, ["olsrd_p2pd.so.0.1.0"] = { { DynamicList, "NonOlsrIf", "lan" }, { Value, "P2pdTtl", "10" } }, ["olsrd_arprefresh.so.0.1"] = {}, ["olsrd_dot_draw.so.0.3"] = {}, ["olsrd_dyn_gw_plain.so.0.4"] = {}, ["olsrd_pgraph.so.1.1"] = {}, ["olsrd_tas.so.0.1"] = {} } -- build plugin options with dependencies if knownPlParams[arg[1]] then for _, option in ipairs(knownPlParams[arg[1]]) do local otype, name, default, uci2cbi, cbi2uci = unpack(option) local values if type(default) == "table" then values = default default = default[1] end if otype == Flag then local bool = p:option( Flag, name, name ) if default == "yes" or default == "no" then bool.enabled = "yes" bool.disabled = "no" elseif default == "on" or default == "off" then bool.enabled = "on" bool.disabled = "off" elseif default == "1" or default == "0" then bool.enabled = "1" bool.disabled = "0" else bool.enabled = "true" bool.disabled = "false" end bool.optional = true bool.default = default bool:depends({ library = plugin }) else local field = p:option( otype, name, name ) if values then for _, value in ipairs(values) do field:value( value ) end end if type(uci2cbi) == "function" then function field.cfgvalue(self, section) return uci2cbi(otype.cfgvalue(self, section)) end end if type(cbi2uci) == "function" then function field.formvalue(self, section) return cbi2uci(otype.formvalue(self, section)) end end field.optional = true field.default = default --field:depends({ library = arg[1] }) end end end return mp else mpi = Map("olsrd", translate("OLSR - Plugins")) local plugins = {} mpi.uci:foreach("olsrd", "LoadPlugin", function(section) if section.library and not plugins[section.library] then plugins[section.library] = true end end ) -- create a loadplugin section for each found plugin for v in fs.dir("/usr/lib") do if v:sub(1, 6) == "olsrd_" then if not plugins[v] then mpi.uci:section( "olsrd", "LoadPlugin", nil, { library = v, ignore = 1 } ) end end end t = mpi:section( TypedSection, "LoadPlugin", translate("Plugins") ) t.anonymous = true t.template = "cbi/tblsection" t.override_scheme = true function t.extedit(self, section) local lib = self.map:get(section, "library") or "" return luci.dispatcher.build_url("admin", "services", "olsrd", "plugins") .. "/" .. lib end ign = t:option( Flag, "ignore", translate("Enabled") ) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end t:option( DummyValue, "library", translate("Library") ) return mpi end
gpl-2.0
sric0880/unity-framework
tools/build_lua/LuaEncoder/luajit_ios/x86/jit/bcsave.lua
41
18267
---------------------------------------------------------------------------- -- LuaJIT module to save/list bytecode. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module saves or lists the bytecode for an input file. -- It's run by the -b command line option. -- ------------------------------------------------------------------------------ local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local bit = require("bit") -- Symbol name prefix for LuaJIT bytecode. local LJBC_PREFIX = "luaJIT_BC_" ------------------------------------------------------------------------------ local function usage() io.stderr:write[[ Save LuaJIT bytecode: luajit -b[options] input output -l Only list bytecode. -s Strip debug info (default). -g Keep debug info. -n name Set module name (default: auto-detect from input name). -t type Set output file type (default: auto-detect from output name). -a arch Override architecture for object files (default: native). -o os Override OS for object files (default: native). -e chunk Use chunk string as input. -- Stop handling options. - Use stdin as input and/or stdout as output. File types: c h obj o raw (default) ]] os.exit(1) end local function check(ok, ...) if ok then return ok, ... end io.stderr:write("luajit: ", ...) io.stderr:write("\n") os.exit(1) end local function readfile(input) if type(input) == "function" then return input end if input == "-" then input = nil end return check(loadfile(input)) end local function savefile(name, mode) if name == "-" then return io.stdout end return check(io.open(name, mode)) end ------------------------------------------------------------------------------ local map_type = { raw = "raw", c = "c", h = "h", o = "obj", obj = "obj", } local map_arch = { x86 = true, x64 = true, arm = true, arm64 = true, ppc = true, mips = true, mipsel = true, } local map_os = { linux = true, windows = true, osx = true, freebsd = true, netbsd = true, openbsd = true, dragonfly = true, solaris = true, } local function checkarg(str, map, err) str = string.lower(str) local s = check(map[str], "unknown ", err) return s == true and str or s end local function detecttype(str) local ext = string.match(string.lower(str), "%.(%a+)$") return map_type[ext] or "raw" end local function checkmodname(str) check(string.match(str, "^[%w_.%-]+$"), "bad module name") return string.gsub(str, "[%.%-]", "_") end local function detectmodname(str) if type(str) == "string" then local tail = string.match(str, "[^/\\]+$") if tail then str = tail end local head = string.match(str, "^(.*)%.[^.]*$") if head then str = head end str = string.match(str, "^[%w_.%-]+") else str = nil end check(str, "cannot derive module name, use -n name") return string.gsub(str, "[%.%-]", "_") end ------------------------------------------------------------------------------ local function bcsave_tail(fp, output, s) local ok, err = fp:write(s) if ok and output ~= "-" then ok, err = fp:close() end check(ok, "cannot write ", output, ": ", err) end local function bcsave_raw(output, s) local fp = savefile(output, "wb") bcsave_tail(fp, output, s) end local function bcsave_c(ctx, output, s) local fp = savefile(output, "w") if ctx.type == "c" then fp:write(string.format([[ #ifdef _cplusplus extern "C" #endif #ifdef _WIN32 __declspec(dllexport) #endif const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname)) else fp:write(string.format([[ #define %s%s_SIZE %d static const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname)) end local t, n, m = {}, 0, 0 for i=1,#s do local b = tostring(string.byte(s, i)) m = m + #b + 1 if m > 78 then fp:write(table.concat(t, ",", 1, n), ",\n") n, m = 0, #b + 1 end n = n + 1 t[n] = b end bcsave_tail(fp, output, table.concat(t, ",", 1, n).."\n};\n") end local function bcsave_elfobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint32_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF32header; typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint64_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF64header; typedef struct { uint32_t name, type, flags, addr, ofs, size, link, info, align, entsize; } ELF32sectheader; typedef struct { uint32_t name, type; uint64_t flags, addr, ofs, size; uint32_t link, info; uint64_t align, entsize; } ELF64sectheader; typedef struct { uint32_t name, value, size; uint8_t info, other; uint16_t sectidx; } ELF32symbol; typedef struct { uint32_t name; uint8_t info, other; uint16_t sectidx; uint64_t value, size; } ELF64symbol; typedef struct { ELF32header hdr; ELF32sectheader sect[6]; ELF32symbol sym[2]; uint8_t space[4096]; } ELF32obj; typedef struct { ELF64header hdr; ELF64sectheader sect[6]; ELF64symbol sym[2]; uint8_t space[4096]; } ELF64obj; ]] local symname = LJBC_PREFIX..ctx.modname local is64, isbe = false, false if ctx.arch == "x64" or ctx.arch == "arm64" then is64 = true elseif ctx.arch == "ppc" or ctx.arch == "mips" then isbe = true end -- Handle different host/target endianess. local function f32(x) return x end local f16, fofs = f32, f32 if ffi.abi("be") ~= isbe then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end if is64 then local two32 = ffi.cast("int64_t", 2^32) function fofs(x) return bit.bswap(x)*two32 end else fofs = f32 end end -- Create ELF object and fill in header. local o = ffi.new(is64 and "ELF64obj" or "ELF32obj") local hdr = o.hdr if ctx.os == "bsd" or ctx.os == "other" then -- Determine native hdr.eosabi. local bf = assert(io.open("/bin/ls", "rb")) local bs = bf:read(9) bf:close() ffi.copy(o, bs, 9) check(hdr.emagic[0] == 127, "no support for writing native object files") else hdr.emagic = "\127ELF" hdr.eosabi = ({ freebsd=9, netbsd=2, openbsd=12, solaris=6 })[ctx.os] or 0 end hdr.eclass = is64 and 2 or 1 hdr.eendian = isbe and 2 or 1 hdr.eversion = 1 hdr.type = f16(1) hdr.machine = f16(({ x86=3, x64=62, arm=40, arm64=183, ppc=20, mips=8, mipsel=8 })[ctx.arch]) if ctx.arch == "mips" or ctx.arch == "mipsel" then hdr.flags = 0x50001006 end hdr.version = f32(1) hdr.shofs = fofs(ffi.offsetof(o, "sect")) hdr.ehsize = f16(ffi.sizeof(hdr)) hdr.shentsize = f16(ffi.sizeof(o.sect[0])) hdr.shnum = f16(6) hdr.shstridx = f16(2) -- Fill in sections and symbols. local sofs, ofs = ffi.offsetof(o, "space"), 1 for i,name in ipairs{ ".symtab", ".shstrtab", ".strtab", ".rodata", ".note.GNU-stack", } do local sect = o.sect[i] sect.align = fofs(1) sect.name = f32(ofs) ffi.copy(o.space+ofs, name) ofs = ofs + #name+1 end o.sect[1].type = f32(2) -- .symtab o.sect[1].link = f32(3) o.sect[1].info = f32(1) o.sect[1].align = fofs(8) o.sect[1].ofs = fofs(ffi.offsetof(o, "sym")) o.sect[1].entsize = fofs(ffi.sizeof(o.sym[0])) o.sect[1].size = fofs(ffi.sizeof(o.sym)) o.sym[1].name = f32(1) o.sym[1].sectidx = f16(4) o.sym[1].size = fofs(#s) o.sym[1].info = 17 o.sect[2].type = f32(3) -- .shstrtab o.sect[2].ofs = fofs(sofs) o.sect[2].size = fofs(ofs) o.sect[3].type = f32(3) -- .strtab o.sect[3].ofs = fofs(sofs + ofs) o.sect[3].size = fofs(#symname+1) ffi.copy(o.space+ofs+1, symname) ofs = ofs + #symname + 2 o.sect[4].type = f32(1) -- .rodata o.sect[4].flags = fofs(2) o.sect[4].ofs = fofs(sofs + ofs) o.sect[4].size = fofs(#s) o.sect[5].type = f32(1) -- .note.GNU-stack o.sect[5].ofs = fofs(sofs + ofs + #s) -- Write ELF object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_peobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint16_t arch, nsects; uint32_t time, symtabofs, nsyms; uint16_t opthdrsz, flags; } PEheader; typedef struct { char name[8]; uint32_t vsize, vaddr, size, ofs, relocofs, lineofs; uint16_t nreloc, nline; uint32_t flags; } PEsection; typedef struct __attribute((packed)) { union { char name[8]; uint32_t nameref[2]; }; uint32_t value; int16_t sect; uint16_t type; uint8_t scl, naux; } PEsym; typedef struct __attribute((packed)) { uint32_t size; uint16_t nreloc, nline; uint32_t cksum; uint16_t assoc; uint8_t comdatsel, unused[3]; } PEsymaux; typedef struct { PEheader hdr; PEsection sect[2]; // Must be an even number of symbol structs. PEsym sym0; PEsymaux sym0aux; PEsym sym1; PEsymaux sym1aux; PEsym sym2; PEsym sym3; uint32_t strtabsize; uint8_t space[4096]; } PEobj; ]] local symname = LJBC_PREFIX..ctx.modname local is64 = false if ctx.arch == "x86" then symname = "_"..symname elseif ctx.arch == "x64" then is64 = true end local symexport = " /EXPORT:"..symname..",DATA " -- The file format is always little-endian. Swap if the host is big-endian. local function f32(x) return x end local f16 = f32 if ffi.abi("be") then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end end -- Create PE object and fill in header. local o = ffi.new("PEobj") local hdr = o.hdr hdr.arch = f16(({ x86=0x14c, x64=0x8664, arm=0x1c0, ppc=0x1f2, mips=0x366, mipsel=0x366 })[ctx.arch]) hdr.nsects = f16(2) hdr.symtabofs = f32(ffi.offsetof(o, "sym0")) hdr.nsyms = f32(6) -- Fill in sections and symbols. o.sect[0].name = ".drectve" o.sect[0].size = f32(#symexport) o.sect[0].flags = f32(0x00100a00) o.sym0.sect = f16(1) o.sym0.scl = 3 o.sym0.name = ".drectve" o.sym0.naux = 1 o.sym0aux.size = f32(#symexport) o.sect[1].name = ".rdata" o.sect[1].size = f32(#s) o.sect[1].flags = f32(0x40300040) o.sym1.sect = f16(2) o.sym1.scl = 3 o.sym1.name = ".rdata" o.sym1.naux = 1 o.sym1aux.size = f32(#s) o.sym2.sect = f16(2) o.sym2.scl = 2 o.sym2.nameref[1] = f32(4) o.sym3.sect = f16(-1) o.sym3.scl = 2 o.sym3.value = f32(1) o.sym3.name = "@feat.00" -- Mark as SafeSEH compliant. ffi.copy(o.space, symname) local ofs = #symname + 1 o.strtabsize = f32(ofs + 4) o.sect[0].ofs = f32(ffi.offsetof(o, "space") + ofs) ffi.copy(o.space + ofs, symexport) ofs = ofs + #symexport o.sect[1].ofs = f32(ffi.offsetof(o, "space") + ofs) -- Write PE object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_machobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint32_t magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags; } mach_header; typedef struct { mach_header; uint32_t reserved; } mach_header_64; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint32_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint64_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command_64; typedef struct { char sectname[16], segname[16]; uint32_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2; } mach_section; typedef struct { char sectname[16], segname[16]; uint64_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2, reserved3; } mach_section_64; typedef struct { uint32_t cmd, cmdsize, symoff, nsyms, stroff, strsize; } mach_symtab_command; typedef struct { int32_t strx; uint8_t type, sect; int16_t desc; uint32_t value; } mach_nlist; typedef struct { uint32_t strx; uint8_t type, sect; uint16_t desc; uint64_t value; } mach_nlist_64; typedef struct { uint32_t magic, nfat_arch; } mach_fat_header; typedef struct { uint32_t cputype, cpusubtype, offset, size, align; } mach_fat_arch; typedef struct { struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[1]; mach_nlist sym_entry; uint8_t space[4096]; } mach_obj; typedef struct { struct { mach_header_64 hdr; mach_segment_command_64 seg; mach_section_64 sec; mach_symtab_command sym; } arch[1]; mach_nlist_64 sym_entry; uint8_t space[4096]; } mach_obj_64; typedef struct { mach_fat_header fat; mach_fat_arch fat_arch[2]; struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[2]; mach_nlist sym_entry; uint8_t space[4096]; } mach_fat_obj; ]] local symname = '_'..LJBC_PREFIX..ctx.modname local isfat, is64, align, mobj = false, false, 4, "mach_obj" if ctx.arch == "x64" then is64, align, mobj = true, 8, "mach_obj_64" elseif ctx.arch == "arm" then isfat, mobj = true, "mach_fat_obj" elseif ctx.arch == "arm64" then is64, align, isfat, mobj = true, 8, true, "mach_fat_obj" else check(ctx.arch == "x86", "unsupported architecture for OSX") end local function aligned(v, a) return bit.band(v+a-1, -a) end local be32 = bit.bswap -- Mach-O FAT is BE, supported archs are LE. -- Create Mach-O object and fill in header. local o = ffi.new(mobj) local mach_size = aligned(ffi.offsetof(o, "space")+#symname+2, align) local cputype = ({ x86={7}, x64={0x01000007}, arm={7,12}, arm64={0x01000007,0x0100000c} })[ctx.arch] local cpusubtype = ({ x86={3}, x64={3}, arm={3,9}, arm64={3,0} })[ctx.arch] if isfat then o.fat.magic = be32(0xcafebabe) o.fat.nfat_arch = be32(#cpusubtype) end -- Fill in sections and symbols. for i=0,#cpusubtype-1 do local ofs = 0 if isfat then local a = o.fat_arch[i] a.cputype = be32(cputype[i+1]) a.cpusubtype = be32(cpusubtype[i+1]) -- Subsequent slices overlap each other to share data. ofs = ffi.offsetof(o, "arch") + i*ffi.sizeof(o.arch[0]) a.offset = be32(ofs) a.size = be32(mach_size-ofs+#s) end local a = o.arch[i] a.hdr.magic = is64 and 0xfeedfacf or 0xfeedface a.hdr.cputype = cputype[i+1] a.hdr.cpusubtype = cpusubtype[i+1] a.hdr.filetype = 1 a.hdr.ncmds = 2 a.hdr.sizeofcmds = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)+ffi.sizeof(a.sym) a.seg.cmd = is64 and 0x19 or 0x1 a.seg.cmdsize = ffi.sizeof(a.seg)+ffi.sizeof(a.sec) a.seg.vmsize = #s a.seg.fileoff = mach_size-ofs a.seg.filesize = #s a.seg.maxprot = 1 a.seg.initprot = 1 a.seg.nsects = 1 ffi.copy(a.sec.sectname, "__data") ffi.copy(a.sec.segname, "__DATA") a.sec.size = #s a.sec.offset = mach_size-ofs a.sym.cmd = 2 a.sym.cmdsize = ffi.sizeof(a.sym) a.sym.symoff = ffi.offsetof(o, "sym_entry")-ofs a.sym.nsyms = 1 a.sym.stroff = ffi.offsetof(o, "sym_entry")+ffi.sizeof(o.sym_entry)-ofs a.sym.strsize = aligned(#symname+2, align) end o.sym_entry.type = 0xf o.sym_entry.sect = 1 o.sym_entry.strx = 1 ffi.copy(o.space+1, symname) -- Write Macho-O object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, mach_size)) bcsave_tail(fp, output, s) end local function bcsave_obj(ctx, output, s) local ok, ffi = pcall(require, "ffi") check(ok, "FFI library required to write this file type") if ctx.os == "windows" then return bcsave_peobj(ctx, output, s, ffi) elseif ctx.os == "osx" then return bcsave_machobj(ctx, output, s, ffi) else return bcsave_elfobj(ctx, output, s, ffi) end end ------------------------------------------------------------------------------ local function bclist(input, output) local f = readfile(input) require("jit.bc").dump(f, savefile(output, "w"), true) end local function bcsave(ctx, input, output) local f = readfile(input) local s = string.dump(f, ctx.strip) local t = ctx.type if not t then t = detecttype(output) ctx.type = t end if t == "raw" then bcsave_raw(output, s) else if not ctx.modname then ctx.modname = detectmodname(input) end if t == "obj" then bcsave_obj(ctx, output, s) else bcsave_c(ctx, output, s) end end end local function docmd(...) local arg = {...} local n = 1 local list = false local ctx = { strip = true, arch = jit.arch, os = string.lower(jit.os), type = false, modname = false, } while n <= #arg do local a = arg[n] if type(a) == "string" and string.sub(a, 1, 1) == "-" and a ~= "-" then table.remove(arg, n) if a == "--" then break end for m=2,#a do local opt = string.sub(a, m, m) if opt == "l" then list = true elseif opt == "s" then ctx.strip = true elseif opt == "g" then ctx.strip = false else if arg[n] == nil or m ~= #a then usage() end if opt == "e" then if n ~= 1 then usage() end arg[1] = check(loadstring(arg[1])) elseif opt == "n" then ctx.modname = checkmodname(table.remove(arg, n)) elseif opt == "t" then ctx.type = checkarg(table.remove(arg, n), map_type, "file type") elseif opt == "a" then ctx.arch = checkarg(table.remove(arg, n), map_arch, "architecture") elseif opt == "o" then ctx.os = checkarg(table.remove(arg, n), map_os, "OS name") else usage() end end end else n = n + 1 end end if list then if #arg == 0 or #arg > 2 then usage() end bclist(arg[1], arg[2] or "-") else if #arg ~= 2 then usage() end bcsave(ctx, arg[1], arg[2]) end end ------------------------------------------------------------------------------ -- Public module functions. return { start = docmd -- Process -b command line option. }
mit
lxl1140989/dmsdk
feeds/luci/applications/luci-statistics/luasrc/model/cbi/luci_statistics/interface.lua
78
1325
--[[ Luci configuration model for statistics - collectd interface plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") m = Map("luci_statistics", translate("Interface Plugin Configuration"), translate( "The interface plugin collects traffic statistics on " .. "selected interfaces." )) -- collectd_interface config section s = m:section( NamedSection, "collectd_interface", "luci_statistics" ) -- collectd_interface.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_interface.interfaces (Interface) interfaces = s:option( MultiValue, "Interfaces", translate("Monitor interfaces") ) interfaces.widget = "select" interfaces.size = 5 interfaces:depends( "enable", 1 ) for k, v in pairs(luci.sys.net.devices()) do interfaces:value(v) end -- collectd_interface.ignoreselected (IgnoreSelected) ignoreselected = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") ) ignoreselected.default = 0 ignoreselected:depends( "enable", 1 ) return m
gpl-2.0
lxl1140989/dmsdk
feeds/luci/applications/luci-minidlna/luasrc/controller/minidlna.lua
73
1448
--[[ LuCI - Lua Configuration Interface - miniDLNA support Copyright 2012 Gabor Juhos <juhosg@openwrt.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.minidlna", package.seeall) function index() if not nixio.fs.access("/etc/config/minidlna") then return end local page page = entry({"admin", "services", "minidlna"}, cbi("minidlna"), _("miniDLNA")) page.dependent = true entry({"admin", "services", "minidlna_status"}, call("minidlna_status")) end function minidlna_status() local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() local port = tonumber(uci:get_first("minidlna", "minidlna", "port")) local status = { running = (sys.call("pidof minidlna >/dev/null") == 0), audio = 0, video = 0, image = 0 } if status.running then local fd = sys.httpget("http://127.0.0.1:%d/" % (port or 8200), true) if fd then local html = fd:read("*a") if html then status.audio = (tonumber(html:match("Audio files: (%d+)")) or 0) status.video = (tonumber(html:match("Video files: (%d+)")) or 0) status.image = (tonumber(html:match("Image files: (%d+)")) or 0) end fd:close() end end luci.http.prepare_content("application/json") luci.http.write_json(status) end
gpl-2.0
Anarchid/Zero-K
scripts/zenith.lua
1
11667
include "constants.lua" local base = piece "base" local flare = piece "flare" local firept = piece "firept" local SOURCE_RANGE = 4000 -- size of the box which the emit point can be randomly placed in local SOURCE_HEIGHT = 9001 local HOVER_RANGE = 1600 local HOVER_HEIGHT = 2600 local AIM_RADIUS = 160 -- 6 minutes to reach capacity. local SPAWN_PERIOD = 1200 -- in milliseconds local METEOR_CAPACITY = 300 local fireRange = WeaponDefNames["zenith_meteor"].range local smokePiece = {base} local Vector = Spring.Utilities.Vector local projectiles = {} local projectileCount = 0 local oldestProjectile = 1 -- oldestProjectile is for when the projectile table is being cyclicly overridden. local tooltipProjectileCount = 0 -- a more correct but less useful count. local gravityWeaponDefID = WeaponDefNames["zenith_gravity_neg"].id local floatWeaponDefID = WeaponDefNames["zenith_meteor_float"].id local aimWeaponDefID = WeaponDefNames["zenith_meteor_aim"].id local fireWeaponDefID = WeaponDefNames["zenith_meteor"].id local uncontrolWeaponDefID = WeaponDefNames["zenith_meteor_uncontrolled"].id local timeToLiveDefs = { [floatWeaponDefID] = 180000, -- 10 minutes, timeout is handled manually with METEOR_CAPACITY. [aimWeaponDefID] = 300, -- Should only exist for 1.5 seconds [fireWeaponDefID] = 450, -- 15 seconds, gives time for a high wobbly meteor to hit the ground. [uncontrolWeaponDefID] = 900, -- 30 seconds, uncontrolled ones are slow } local gravityDefs = { [floatWeaponDefID] = -0.2, -- Gravity reduces the time taken to move from capture to the holding cloud. [aimWeaponDefID] = 0, -- No gravity, stops aim from being confused. [fireWeaponDefID] = 0.2, -- Pushes the meteor up a litte, makes an arcing effect. [uncontrolWeaponDefID] = -0.12, -- Gravity increases speed of fall and reduced size of drop impact zone. } local spGetUnitIsStunned = Spring.GetUnitIsStunned local spGetUnitRulesParam = Spring.GetUnitRulesParam local spSetUnitRulesParam = Spring.SetUnitRulesParam local spGetUnitCurrentCommand = Spring.GetUnitCurrentCommand local CMD_ATTACK = CMD.ATTACK local gaiaTeam = Spring.GetGaiaTeamID() local launchInProgress = false local isBlocked = true local currentlyEnabled = false local INLOS_ACCESS = {inlos = true} local ux, uy, uz local function IsDisabled() local state = Spring.GetUnitStates(unitID) if not (state and state.active) then return true end local x, _, z = Spring.GetUnitPosition(unitID) local y = Spring.GetGroundHeight(x, z) if y < -95 then return true end return spGetUnitIsStunned(unitID) or (spGetUnitRulesParam(unitID, "disarmed") == 1) end local function TransformMeteor(weaponDefID, proID, meteorTeamID, meteorOwnerID, x, y, z) -- Get old projectile attributes local px, py, pz = Spring.GetProjectilePosition(proID) local vx, vy, vz = Spring.GetProjectileVelocity(proID) Spring.DeleteProjectile(proID) -- Send new one in the right direction local newProID = Spring.SpawnProjectile(weaponDefID, { pos = {px, py, pz}, ["end"] = {x, y, z}, tracking = true, speed = {vx, vy, vz}, ttl = timeToLiveDefs[weaponDefID], gravity = gravityDefs[weaponDefID], team = meteorTeamID, owner = meteorOwnerID, }) if x then Spring.SetProjectileTarget(newProID, x, y, z) end return newProID end local function DropSingleMeteor(index) local proID = projectiles[index] -- Check that the projectile ID is still valid if Spring.GetProjectileDefID(proID) == floatWeaponDefID then TransformMeteor(uncontrolWeaponDefID, proID, gaiaTeam, nil) end end local function LoseControlOfMeteors() tooltipProjectileCount = 0 for i = 1, projectileCount do local proID = projectiles[i] -- Check that the projectile ID is still valid if Spring.GetProjectileDefID(proID) == floatWeaponDefID then tooltipProjectileCount = tooltipProjectileCount + 1 projectiles[i] = TransformMeteor(uncontrolWeaponDefID, proID, gaiaTeam, nil) end end Spring.SetUnitRulesParam(unitID, "meteorsControlled", tooltipProjectileCount, INLOS_ACCESS) end local function RegainControlOfMeteors() tooltipProjectileCount = 0 for i = 1, projectileCount do local proID = projectiles[i] -- Check that the projectile ID is still valid if Spring.GetProjectileDefID(proID) == uncontrolWeaponDefID then local ttl = Spring.GetProjectileTimeToLive(projectiles[i]) if ttl > 0 then tooltipProjectileCount = tooltipProjectileCount + 1 local hoverPos = Vector.PolarToCart(HOVER_RANGE*math.random()^2, 2*math.pi*math.random()) projectiles[i] = TransformMeteor(floatWeaponDefID, proID, gaiaTeam, nil, ux + hoverPos[1], uy + HOVER_HEIGHT, uz + hoverPos[2]) end end end Spring.SetUnitRulesParam(unitID, "meteorsControlled", tooltipProjectileCount, INLOS_ACCESS) end local function SpawnMeteor() local sourcePos = Vector.PolarToCart(SOURCE_RANGE*(1 - math.random()^2), 2*math.pi*math.random()) local hoverPos = Vector.PolarToCart(HOVER_RANGE*math.random()^2, 2*math.pi*math.random()) local proID = Spring.SpawnProjectile(floatWeaponDefID, { pos = {ux + sourcePos[1], uy + SOURCE_HEIGHT, uz + sourcePos[2]}, tracking = true, speed = {0, -1, 0}, ttl = 18000, -- 18000 = 10 minutes gravity = meteorGravity, team = gaiaTeam, }) Spring.SetProjectileTarget(proID, ux + hoverPos[1], uy + HOVER_HEIGHT, uz + hoverPos[2]) -- Drop meteor if there are too many. It is more fun this way. if projectileCount >= METEOR_CAPACITY then DropSingleMeteor(oldestProjectile) projectiles[oldestProjectile] = proID oldestProjectile = oldestProjectile + 1 if oldestProjectile > projectileCount then oldestProjectile = 1 end else projectileCount = projectileCount + 1 projectiles[projectileCount] = proID tooltipProjectileCount = tooltipProjectileCount + 1 Spring.SetUnitRulesParam(unitID, "meteorsControlled", tooltipProjectileCount, INLOS_ACCESS) end end local function UpdateEnabled(newEnabled) if currentlyEnabled == newEnabled then return end currentlyEnabled = newEnabled if currentlyEnabled then RegainControlOfMeteors() else LoseControlOfMeteors() isBlocked = true -- Block until a projectile is fired successfully. end end local function SpawnProjectileThread() GG.zenith_spawnBlocked = GG.zenith_spawnBlocked or {} while true do local reloadMult = spGetUnitRulesParam(unitID, "totalReloadSpeedChange") or 1 --Spring.SpawnProjectile(gravityWeaponDefID, { -- pos = {1000,1000,1000}, -- speed = {10, 0 ,10}, -- ttl = 100, -- maxRange = 1000, --}) --// Handle stun and slow -- reloadMult should be 0 only when disabled. while IsDisabled() do UpdateEnabled(false) Sleep(500) end EmitSfx(flare, 2049) Sleep(SPAWN_PERIOD/((reloadMult > 0 and reloadMult) or 1)) UpdateEnabled(not isBlocked) if currentlyEnabled then SpawnMeteor() end isBlocked = GG.zenith_spawnBlocked[unitID] GG.zenith_spawnBlocked[unitID] = false end end local function LaunchAll(x, z) -- Sanitize input x, z = Spring.Utilities.ClampPosition(x, z) local y = math.max(0, Spring.GetGroundHeight(x,z)) if Vector.AbsVal(ux - x, uz - z) > fireRange then return end launchInProgress = true local zenithTeamID = Spring.GetUnitTeam(unitID) -- Make the aiming projectiles. These projectiles have high turnRate -- so are able to rotate the wobbly float projectiles in the right -- direction. local aim = {} local aimCount = 0 for i = 1, projectileCount do local proID = projectiles[i] -- Check that the projectile ID is still valid if Spring.GetProjectileDefID(proID) == floatWeaponDefID then --// Shoot gravity beams at the new aim projectiles. Did not look great. --local px, py, pz = Spring.GetProjectilePosition(proID) --local dist = math.sqrt((px - ux)^2 + (py - uy)^2 + (pz - uz)^2) --local mult = 1000/dist --Spring.SpawnProjectile(gravityWeaponDefID, { -- pos = {ux, uy + 100, uz}, -- speed = {(px - ux)*mult, (py - uy)*mult, (pz - uz)*mult}, -- ttl = dist/1000, -- owner = unitID, -- maxRange = dist, --}) -- Projectile is valid, launch! aimCount = aimCount + 1 aim[aimCount] = TransformMeteor(aimWeaponDefID, proID, zenithTeamID, unitID, x, y, z) end end -- All projectiles were launched so there are none left. projectiles = {} projectileCount = 0 oldestProjectile = 1 tooltipProjectileCount = 0 Spring.SetUnitRulesParam(unitID, "meteorsControlled", tooltipProjectileCount, INLOS_ACCESS) -- Raw projectile manipulation doesn't create an event (needed for stuff like Fire Once) if aimCount > 0 then script.EndBurst(1) end -- Sleep to give time for the aim projectiles to turn Sleep(1500) -- Destroy the aim projectiles and create the speedy, low turnRate -- projectiles. for i = 1, aimCount do local proID = aim[i] -- Check that the projectile ID is still valid if Spring.GetProjectileDefID(proID) == aimWeaponDefID then -- Projectile is valid, launch! local aimOff = Vector.PolarToCart(AIM_RADIUS*math.random()^2, 2*math.pi*math.random()) TransformMeteor(fireWeaponDefID, proID, zenithTeamID, unitID, x + aimOff[1], y, z + aimOff[2]) end end launchInProgress = false end function OnLoadGame() local meteorCount = Spring.GetUnitRulesParam(unitID, "meteorsControlled") or 0 for i = 1, meteorCount do SpawnMeteor() end end function script.Create() spSetUnitRulesParam(unitID, "meteorSpawnBlocked", 0) if Spring.GetGameRulesParam("loadPurge") ~= 1 then Spring.SetUnitRulesParam(unitID, "meteorsControlled", 0, INLOS_ACCESS) end spSetUnitRulesParam(unitID, "meteorsControlledMax", METEOR_CAPACITY, INLOS_ACCESS) local x, _, z = Spring.GetUnitPosition(unitID) ux, uy, uz = x, Spring.GetGroundHeight(x, z), z Move(flare, y_axis, -110) Turn(flare, x_axis, math.rad(-90)) StartThread(GG.Script.SmokeUnit, unitID, smokePiece) StartThread(SpawnProjectileThread) -- Helpful for devving --local proj = Spring.GetProjectilesInRectangle(0,0, 10000, 10000) --for i = 1, #proj do -- Spring.SetProjectileCollision(proj[i]) --end end function script.QueryWeapon(num) return firept end function script.AimFromWeapon(num) return firept end function script.AimWeapon(num, heading, pitch) return (num ~= 2) --and (spGetUnitRulesParam(unitID, "lowpower") == 0) end function script.BlockShot(num, targetID) if launchInProgress then return true end if IsDisabled() then return true end local cmdID, _, _, cmdParam1, cmdParam2, cmdParam3 = spGetUnitCurrentCommand(unitID) if cmdID == CMD_ATTACK then if cmdParam3 then StartThread(LaunchAll, cmdParam1, cmdParam3) return true elseif not cmdParam2 then targetID = cmdParam1 end end if targetID then local x,y,z = Spring.GetUnitPosition(targetID) if x then local vx,_,vz = Spring.GetUnitVelocity(targetID) if vx then local dist = Vector.AbsVal(ux - x, uy + HOVER_HEIGHT - y, uz - z) -- Weapon speed is 53 elmos/frame but it has some acceleration. -- Add 22 frames for the aim time. It takes about 40 frames for every meteor -- to face the right way so an average meteor should take 20 frames. -- That was the reasoning, the final equation is just experimentation though. local travelTime = dist/80 + 10 -- in frames x = x + vx*travelTime z = z + vz*travelTime end x, z = x + vx*50, z + vz*50 StartThread(LaunchAll, x, z) end end return true end function script.Killed(recentDamage, maxHealth) LoseControlOfMeteors(); local severity = recentDamage/maxHealth if severity < 0.5 then Explode(base, SFX.NONE) return 1 else Explode(base, SFX.SHATTER) return 2 end end
gpl-2.0
Insurgencygame/LivingDead
TheLivingDeadv0.1.sdd/luaui/widgets/cmd_buildsplit.lua
1
3324
function widget:GetInfo() return { name = "Build Split", desc = "Splits builds over cons, and vice versa", author = "Niobium", version = "v1.0", date = "Jan 11, 2009", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end local floor = math.floor local spGetGameFrame = Spring.GetGameFrame local spGetSpecState = Spring.GetSpectatingState local spTestBuildOrder = Spring.TestBuildOrder local spGetSelUnitCount = Spring.GetSelectedUnitsCount local spGetSelUnitsSorted = Spring.GetSelectedUnitsSorted local spGiveOrderToUnit = Spring.GiveOrderToUnit local spGiveOrderToUnitArray = Spring.GiveOrderToUnitArray local uDefs = UnitDefs local buildID = 0 local buildLocs = {} local buildCount = 0 function widget:Initialize() if spGetGameFrame() > 0 then widget:GameStart() end end function widget:GameStart() local areSpec = spGetSpecState() if areSpec then widgetHandler:RemoveWidget(self) end end function widget:CommandNotify(cmdID, cmdParams, cmdOpts) -- 3 of 3 parameters if not (cmdID < 0 and cmdOpts.shift and cmdOpts.meta) then return false end -- Note: All multibuilds require shift if spGetSelUnitCount() < 2 then return false end --if #cmdParams < 4 then return false end -- Probably not possible, commented for now if spTestBuildOrder(-cmdID, cmdParams[1], cmdParams[2], cmdParams[3], cmdParams[4]) == 0 then return false end local areSpec = spGetSpecState() if areSpec then widgetHandler:RemoveWidget(self) return false end buildID = -cmdID buildOpts = cmdOpts buildCount = buildCount + 1 buildLocs[buildCount] = cmdParams return true end function widget:Update() -- 0 of 0 parameters if buildCount == 0 then return end local selUnits = spGetSelUnitsSorted() selUnits.n = nil local builders = {} local builderCount = 0 for uDefID, uIDs in pairs(selUnits) do local uBuilds = uDefs[uDefID].buildOptions for bi=1, #uBuilds do if uBuilds[bi] == buildID then for ui=1, #uIDs do builderCount = builderCount + 1 builders[builderCount] = uIDs[ui] end break end end end if buildCount > builderCount then local ratio = floor(buildCount / builderCount) local excess = buildCount - builderCount * ratio -- == buildCount % builderCount local buildingInd = 0 for bi=1, builderCount do for r=1, ratio do buildingInd = buildingInd + 1 spGiveOrderToUnit(builders[bi], -buildID, buildLocs[buildingInd], {"shift"}) end if bi <= excess then buildingInd = buildingInd + 1 spGiveOrderToUnit(builders[bi], -buildID, buildLocs[buildingInd], {"shift"}) end end else local ratio = floor(builderCount / buildCount) local excess = builderCount - buildCount * ratio -- == builderCount % buildCount local builderInd = 0 for bi=1, buildCount do local setUnits = {} local setCount = 0 for r=1, ratio do builderInd = builderInd + 1 setCount = setCount + 1 setUnits[setCount] = builders[builderInd] end if bi <= excess then builderInd = builderInd + 1 setCount = setCount + 1 setUnits[setCount] = builders[builderInd] end spGiveOrderToUnitArray(setUnits, -buildID, buildLocs[bi], {"shift"}) end end buildCount = 0 end
gpl-2.0
PichotM/DarkRP
entities/weapons/weapon_mp52/shared.lua
12
1074
AddCSLuaFile() if CLIENT then SWEP.PrintName = "MP5" SWEP.Author = "DarkRP Developers" SWEP.Slot = 2 SWEP.SlotPos = 0 SWEP.IconLetter = "x" killicon.AddFont("weapon_mp52", "CSKillIcons", SWEP.IconLetter, Color(255, 80, 0, 255)) end SWEP.Base = "weapon_cs_base2" SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Category = "DarkRP (Weapon)" SWEP.ViewModel = "models/weapons/cstrike/c_smg_mp5.mdl" SWEP.WorldModel = "models/weapons/w_smg_mp5.mdl" SWEP.Weight = 5 SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false SWEP.HoldType = "smg" SWEP.Primary.Sound = Sound("Weapon_MP5Navy.Single") SWEP.Primary.Recoil = 0.5 SWEP.Primary.Damage = 15 SWEP.Primary.NumShots = 1 SWEP.Primary.Cone = 0.005 SWEP.Primary.ClipSize = 32 SWEP.Primary.Delay = 0.08 SWEP.Primary.DefaultClip = 32 SWEP.Primary.Automatic = true SWEP.Primary.Ammo = "smg1" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" SWEP.IronSightsPos = Vector(-5.3, -7, 2.1) SWEP.IronSightsAng = Vector(0.9, 0.1, 0)
mit
bell07/minetest-smart_inventory
inventory_framework.lua
1
3664
local smartfs = smart_inventory.smartfs local maininv = smart_inventory.maininv local modpath = smart_inventory.modpath -- smartfs callback local inventory_form = smartfs.create("smart_inventory:main", function(state) -- enhanced object to the main inventory functions state.param.invobj = maininv.get(state.location.player) -- tabbed view controller local tab_controller = { _tabs = {}, active_name = nil, set_active = function(self, tabname) for name, def in pairs(self._tabs) do if name == tabname then def.button:setBackground("halo.png") def.view:setVisible(true) else def.button:setBackground(nil) def.view:setVisible(false) end end self.active_name = tabname end, tab_add = function(self, name, def) def.viewstate:size(20,10) --size of tab view self._tabs[name] = def end, get_active_name = function(self) return self.active_name end, } --set screen size state:size(20,12) state:label(1,0.2,"header","Smart Inventory") state:image(0,0,1,1,"header_logo", "logo.png") state:image_button(19,0,1,1,"exit", "","smart_inventory_exit_button.png", true):setTooltip("Close the inventory") local button_x = 0.1 table.sort(smart_inventory.registered_pages, function(a,b) if not a.sequence then return false elseif not b.sequence then return true elseif a.sequence > b.sequence then return false else return true end end) for _, def in ipairs(smart_inventory.registered_pages) do assert(def.smartfs_callback, "Callback function needed") assert(def.name, "Name is needed") local tabdef = {} local label if not def.label then label = "" else label = def.label end tabdef.button = state:button(button_x,11.2,1,1,def.name.."_button",label) if def.icon then tabdef.button:setImage(def.icon) end tabdef.button:setTooltip(def.tooltip) tabdef.button:onClick(function(self) tab_controller:set_active(def.name) if def.on_button_click then def.on_button_click(tabdef.viewstate) end end) tabdef.view = state:container(0,1,def.name.."_container") tabdef.viewstate = tabdef.view:getContainerState() def.smartfs_callback(tabdef.viewstate) tab_controller:tab_add(def.name, tabdef) button_x = button_x + 1 end tab_controller:set_active(smart_inventory.registered_pages[1].name) end) if minetest.settings:get_bool("smart_inventory_workbench_mode") then dofile(modpath.."/workbench.lua") smart_inventory.get_player_state = function(playername) -- check the inventory is shown local state = smartfs.opened[playername] if state and (not state.obsolete) and state.location.type == "player" and state.def.name == "smart_inventory:main" then return state end end else smartfs.set_player_inventory(inventory_form) smart_inventory.get_player_state = function(playername) return smartfs.inv[playername] end end -- pages list smart_inventory.registered_pages = {} -- add new page function smart_inventory.register_page(def) table.insert(smart_inventory.registered_pages, def) end -- smart_inventory.get_player_state(playername) defined above -- get state of active page function smart_inventory.get_page_state(pagename, playername) local rootstate = smart_inventory.get_player_state(playername) if not rootstate then return end local view = rootstate:get(pagename.."_container") if not view then return end return view:getContainerState() end -- get definition of registered page function smart_inventory.get_registered_page(pagename) for _, registred_page in ipairs(smart_inventory.registered_pages) do if registred_page.name == pagename then return registred_page end end end
lgpl-3.0
Anarchid/Zero-K
units/hoversonic.lua
3
3810
return { hoversonic = { unitname = [[hoversonic]], name = [[Morningstar]], description = [[Antisub Hovercraft]], acceleration = 0.24, activateWhenBuilt = true, brakeRate = 0.43, buildCostMetal = 300, builder = false, buildPic = [[hoversonic.png]], canGuard = true, canMove = true, canPatrol = true, category = [[HOVER]], corpse = [[DEAD]], customParams = { modelradius = [[25]], turnatfullspeed_hover = [[1]], }, explodeAs = [[BIG_UNITEX]], footprintX = 3, footprintZ = 3, iconType = [[hoverassault]], idleAutoHeal = 5, idleTime = 1800, maxDamage = 900, maxSlope = 36, maxVelocity = 3, movementClass = [[HOVER3]], noAutoFire = false, noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE SUB]], objectName = [[hovershotgun.s3o]], script = [[hovershotgun.cob]], selfDestructAs = [[BIG_UNITEX]], sfxtypes = { explosiongenerators = { [[custom:HEAVYHOVERS_ON_GROUND]], [[custom:RAIDMUZZLE]], }, }, sightDistance = 385, turninplace = 0, turnRate = 985, workerTime = 0, weapons = { { def = [[SONICGUN]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SUB SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { SONICGUN = { name = [[Sonic Blaster]], areaOfEffect = 70, avoidFeature = true, avoidFriendly = true, burnblow = true, craterBoost = 0, craterMult = 0, customParams = { slot = [[5]], muzzleEffectFire = [[custom:HEAVY_CANNON_MUZZLE]], miscEffectFire = [[custom:RIOT_SHELL_L]], lups_explodelife = 1.5, lups_explodespeed = 0.44, }, damage = { default = 175, planes = 175, }, cegTag = [[sonictrail]], explosionGenerator = [[custom:sonic]], edgeEffectiveness = 0.75, fireStarter = 150, impulseBoost = 60, impulseFactor = 0.5, interceptedByShieldType = 1, noSelfDamage = true, range = 303, reloadtime = 1.1, soundStart = [[weapon/sonicgun2]], soundHit = [[weapon/sonicgun_hit]], soundStartVolume = 6, soundHitVolume = 10, texture1 = [[sonic_glow]], texture2 = [[null]], texture3 = [[null]], rgbColor = {0, 0.5, 1}, thickness = 20, corethickness = 1, turret = true, weaponType = [[LaserCannon]], weaponVelocity = 700, waterweapon = true, duration = 0.15, }, }, featureDefs = { DEAD = { blocking = false, featureDead = [[HEAP]], footprintX = 3, footprintZ = 3, object = [[hoverassault_dead.s3o]], }, HEAP = { blocking = false, footprintX = 3, footprintZ = 3, object = [[debris3x3c.s3o]], }, }, } }
gpl-2.0
Sannis/tarantool
test/big/bitset.test.lua
7
4871
dofile('utils.lua') dofile('bitset.lua') create_space() ------------------------------------------------------------------------------ -- BitsetIndex: insert/delete ------------------------------------------------------------------------------ test_insert_delete(128) ------------------------------------------------------------------------------ -- BitsetIndex: ALL ------------------------------------------------------------------------------ clear() fill(1, 128) dump(box.index.BITS_ALL) box.space.tweedledum.index.bitset:count() ------------------------------------------------------------------------------ -- BitsetIndex: BITS_ALL_SET (single bit) ------------------------------------------------------------------------------ dump(box.index.BITS_ALL_SET, 0) box.space.tweedledum.index.bitset:count(0, { iterator = box.index.BITS_ALL_SET}) dump(box.index.BITS_ALL_SET, 1) box.space.tweedledum.index.bitset:count(1, { iterator = box.index.BITS_ALL_SET}) dump(box.index.BITS_ALL_SET, 2) box.space.tweedledum.index.bitset:count(2, { iterator = box.index.BITS_ALL_SET}) dump(box.index.BITS_ALL_SET, 8) box.space.tweedledum.index.bitset:count(8, { iterator = box.index.BITS_ALL_SET}) dump(box.index.BITS_ALL_SET, 128) box.space.tweedledum.index.bitset:count(128, { iterator = box.index.BITS_ALL_SET}) dump(box.index.BITS_ALL_SET, 1073741824) box.space.tweedledum.index.bitset:count(1073741824, { iterator = box.index.BITS_ALL_SET}) dump(box.index.BITS_ALL_SET, 2147483648) box.space.tweedledum.index.bitset:count(2147483648, { iterator = box.index.BITS_ALL_SET}) ------------------------------------------------------------------------------ -- BitsetIndex: BITS_ALL_SET (multiple bit) ------------------------------------------------------------------------------ dump(box.index.BITS_ALL_SET, 3) dump(box.index.BITS_ALL_SET, 7) dump(box.index.BITS_ALL_SET, 31) dump(box.index.BITS_ALL_SET, 5) dump(box.index.BITS_ALL_SET, 10) dump(box.index.BITS_ALL_SET, 27) dump(box.index.BITS_ALL_SET, 341) dump(box.index.BITS_ALL_SET, 2147483649) dump(box.index.BITS_ALL_SET, 4294967295) ------------------------------------------------------------------------------ -- BitsetIndex: BITS_ALL_NOT_SET (single bit) ------------------------------------------------------------------------------ dump(box.index.BITS_ALL_NOT_SET, 0) box.space.tweedledum.index.bitset:count(0, { iterator = box.index.BITS_ALL_NOT_SET}) dump(box.index.BITS_ALL_NOT_SET, 2) box.space.tweedledum.index.bitset:count(2, { iterator = box.index.BITS_ALL_NOT_SET}) dump(box.index.BITS_ALL_NOT_SET, 8) box.space.tweedledum.index.bitset:count(8, { iterator = box.index.BITS_ALL_NOT_SET}) dump(box.index.BITS_ALL_NOT_SET, 128) box.space.tweedledum.index.bitset:count(128, { iterator = box.index.BITS_ALL_NOT_SET}) dump(box.index.BITS_ALL_NOT_SET, 1073741824) box.space.tweedledum.index.bitset:count(1073741824, { iterator = box.index.BITS_ALL_NOT_SET}) dump(box.index.BITS_ALL_NOT_SET, 2147483648) box.space.tweedledum.index.bitset:count(2147483648, { iterator = box.index.BITS_ALL_NOT_SET}) ------------------------------------------------------------------------------ -- BitsetIndex: BITS_ALL_NOT_SET (multiple bit) ------------------------------------------------------------------------------ dump(box.index.BITS_ALL_NOT_SET, 3) box.space.tweedledum.index.bitset:count(3, { iterator = box.index.BITS_ALL_NOT_SET}) dump(box.index.BITS_ALL_NOT_SET, 7) box.space.tweedledum.index.bitset:count(7, { iterator = box.index.BITS_ALL_NOT_SET}) dump(box.index.BITS_ALL_NOT_SET, 10) box.space.tweedledum.index.bitset:count(10, { iterator = box.index.BITS_ALL_NOT_SET}) dump(box.index.BITS_ALL_NOT_SET, 27) box.space.tweedledum.index.bitset:count(27, { iterator = box.index.BITS_ALL_NOT_SET}) dump(box.index.BITS_ALL_NOT_SET, 85) box.space.tweedledum.index.bitset:count(85, { iterator = box.index.BITS_ALL_NOT_SET}) dump(box.index.BITS_ALL_NOT_SET, 4294967295) box.space.tweedledum.index.bitset:count(4294967295, { iterator = box.index.BITS_ALL_NOT_SET}) ------------------------------------------------------------------------------ -- BitsetIndex: BITS_ANY_SET (single bit) ------------------------------------------------------------------------------ dump(box.index.BITS_ANY_SET, 0) box.space.tweedledum.index.bitset:count(0, { iterator = box.index.BITS_ANY_SET}) dump(box.index.BITS_ANY_SET, 16) box.space.tweedledum.index.bitset:count(16, { iterator = box.index.BITS_ANY_SET}) dump(box.index.BITS_ANY_SET, 128) box.space.tweedledum.index.bitset:count(128, { iterator = box.index.BITS_ANY_SET}) ------------------------------------------------------------------------------ -- BitsetIndex: BITS_ANY_SET (multiple bit) ------------------------------------------------------------------------------ dump(box.index.BITS_ANY_SET, 7) dump(box.index.BITS_ANY_SET, 84) dump(box.index.BITS_ANY_SET, 113) drop_space()
bsd-2-clause
Whit3Tig3R/bestspammbot2
bot/utils.lua
239
13499
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end
gpl-2.0
amircheshme/megatron
bot/utils.lua
239
13499
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end
gpl-2.0
apkbox/asplite
asplite/util/bin2c.lua
2
4744
--[=[ // The MIT License (MIT) // // Copyright (c) 2013 Alex Kozlov // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]=] --[=[ Converts input file to a C array. --]=] local use_tabs = false; local indent = -1; local bytes_per_row = 8; local max_width = 0; local variable_name = 'data'; local template_file = nil; function PrintUsage() print(string.format('usage: %s [-t] [-i:N] [-n:N] [-w:N] [-v:<name>] [-c:<file>] input_file [output_file]', arg[0])); print(' -t Use tabs instead of spaces.'); print(' -i:N N indent data with N spaces/tabs (default 4 for spaces or 1 for tabs).'); print(' -n:N N number of bytes of data per row (default 8).'); print(' -w:N Maximum row width.'); print(' This option takes precendence over -n option. '); print(' -v:<name> Variable name (default "data").'); print(' -c:<file> Template file name.'); print(' Use ${data} for data placeholder.'); print(' Use ${size} for array size placeholder.'); print(' Use ${name} for variable name placeholder.'); end if #arg < 1 then PrintUsage(); os.exit(0); end args = {}; for i = 1, #arg do local option, value = string.match(arg[i], '^%-(%l):(%d*)'); if option and #value > 0 then if option == 'i' then indent = tonumber(value); elseif option == 'n' then bytes_per_row = tonumber(value); elseif option == 'w' then max_width = tonumber(value); end else option, value = string.match(arg[i], '^%-(%l):(.*)'); if option and #value > 0 then if option == 'v' and #value then variable_name = value; elseif option == 'c' and #value then template_file = value; end else option = string.match(arg[i], '^%-(%l)'); if option then if option == 't' then use_tabs = true; end else table.insert(args, arg[i]); end end end end if #args < 1 then print('error: missing input file name'); PrintUsage(); os.exit(1); end local template = 'unsigned char ${name}[${size}] = {\n${data}};\n'; if template_file then local tf = io.open(template_file, 'r'); if not tf then print('error: cannot open template file "' .. template_file .. '".'); os.exit(1); end template = tf:read('*a'); tf:close(); end local out = io.stdout; if #args > 1 then out = io.open(args[2], 'w'); if not out then print('error: cannot open output file "' .. args[2] .. '".'); os.exit(1); end end local bin = ''; local f = io.open(args[1], 'rb'); if f then bin = f:read('*a'); f:close(); else print('error: cannot open input file "' .. args[1] .. '".'); os.exit(1); end local indent_char = ' '; if use_tabs then indent_char = '\t'; if indent < 0 then indent = 1; end else if indent < 0 then indent = 4; end end local buffer = ''; local line = string.rep(indent_char, indent); local width = #line; for i = 1, #bin do local s = string.format('0x%02x', bin:byte(i)); if i < #bin then s = s .. ', '; end if max_width > 0 and width + #s >= max_width and #line > 0 then buffer = buffer .. line .. '\n'; line = string.rep(indent_char, indent) .. s; width = #line; else line = line .. s; width = width + #s; if max_width == 0 and (i % bytes_per_row) == 0 then if #line > 0 then buffer = buffer .. line .. '\n'; end line = string.rep(indent_char, indent); width = #line; end end end if #line > 0 then buffer = buffer .. line .. '\n'; end local content = string.gsub(template, '${name}', tostring(variable_name)); content = string.gsub(content, '${size}', tostring(#bin)); content = string.gsub(content, '${data}', buffer); out:write(content); if out ~= io.stdout then out:close(); end
mit
Anarchid/Zero-K
effects/gundam_burnteal.lua
25
3400
-- burnteal return { ["burnteal"] = { groundflash = { alwaysvisible = true, circlealpha = 1, circlegrowth = 3, flashalpha = 1, flashsize = 25, ttl = 8, color = { [1] = 0, [2] = 0.5, [3] = 0.5, }, }, poof01 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 0.8, alwaysvisible = true, colormap = [[0.0 1.0 1.0 0.04 0.2 0.9 0.9 0.01 0.1 0.8 0.8 0.01]], directional = true, emitrot = 45, emitrotspread = 32, emitvector = [[0, 1, 0]], gravity = [[0, -0.05, 0]], numparticles = 8, particlelife = 10, particlelifespread = 0, particlesize = 20, particlesizespread = 0, particlespeed = 5, particlespeedspread = 5, pos = [[0, 2, 0]], sizegrowth = 1, sizemod = 1.0, texture = [[flashside1]], useairlos = false, }, }, poof02 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, alwaysvisible = true, colormap = [[0.8 0.8 0.2 0.01 0.2 0.8 0.2 0.01 0.0 0.0 0.0 0.01]], directional = false, emitrot = 45, emitrotspread = 32, emitvector = [[0, 1, 0]], gravity = [[0, -0.005, 0]], numparticles = 8, particlelife = 5, particlelifespread = 8, particlesize = 10, particlesizespread = 0, particlespeed = 8, particlespeedspread = 3, pos = [[0, 2, 0]], sizegrowth = 0.8, sizemod = 1.0, texture = [[randdots]], useairlos = false, }, }, pop1 = { air = true, class = [[heatcloud]], count = 1, ground = true, water = true, properties = { alwaysvisible = true, heat = 10, heatfalloff = 1, maxheat = 10, pos = [[0, 5, 0]], size = 0.2, sizegrowth = 8, speed = [[0, 0, 0]], texture = [[novabg]], }, }, pop2 = { air = true, class = [[heatcloud]], count = 1, ground = true, water = true, properties = { alwaysvisible = true, heat = 10, heatfalloff = 1, maxheat = 15, pos = [[r-3 r3, 5, r-3 r3]], size = 0.2, sizegrowth = 3, speed = [[0, 1, 0]], texture = [[3explo]], }, }, }, }
gpl-2.0
helingping/Urho3D
bin/Data/LuaScripts/27_Urho2DPhysics.lua
24
7973
-- Urho2D physics sample. -- This sample demonstrates: -- - Creating both static and moving 2D physics objects to a scene -- - Displaying physics debug geometry require "LuaScripts/Utilities/Sample" function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_FREE) -- Hook up to the frame update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will -- show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates it -- is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically -- optimizing manner scene_:CreateComponent("Octree") scene_:CreateComponent("DebugRenderer") -- Create a scene node for the camera, which we will move around -- The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically) cameraNode = scene_:CreateChild("Camera") -- Set an initial position for the camera scene node above the plane cameraNode.position = Vector3(0.0, 0.0, -10.0) local camera = cameraNode:CreateComponent("Camera") camera.orthographic = true camera.orthoSize = graphics.height * PIXEL_SIZE camera.zoom = 1.2 * Min(graphics.width / 1280, graphics.height / 800) -- Set zoom according to user's resolution to ensure full visibility (initial zoom (1.2) is set for full visibility at 1280x800 resolution) -- Create 2D physics world component scene_:CreateComponent("PhysicsWorld2D") local boxSprite = cache:GetResource("Sprite2D", "Urho2D/Box.png") local ballSprite = cache:GetResource("Sprite2D", "Urho2D/Ball.png") -- Create ground. local groundNode = scene_:CreateChild("Ground") groundNode.position = Vector3(0.0, -3.0, 0.0) groundNode.scale = Vector3(200.0, 1.0, 0.0) -- Create 2D rigid body for gound local groundBody = groundNode:CreateComponent("RigidBody2D") local groundSprite = groundNode:CreateComponent("StaticSprite2D") groundSprite.sprite = boxSprite -- Create box collider for ground local groundShape = groundNode:CreateComponent("CollisionBox2D") -- Set box size groundShape.size = Vector2(0.32, 0.32) -- Set friction groundShape.friction = 0.5 local NUM_OBJECTS = 100 for i = 1, NUM_OBJECTS do local node = scene_:CreateChild("RigidBody") node.position = Vector3(Random(-0.1, 0.1), 5.0 + i * 0.4, 0.0) -- Create rigid body local body = node:CreateComponent("RigidBody2D") body.bodyType = BT_DYNAMIC local staticSprite = node:CreateComponent("StaticSprite2D") local shape = nil if i % 2 == 0 then staticSprite.sprite = boxSprite -- Create box shape = node:CreateComponent("CollisionBox2D") -- Set size shape.size = Vector2(0.32, 0.32) else staticSprite.sprite = ballSprite -- Create circle shape = node:CreateComponent("CollisionCircle2D") -- Set radius shape.radius = 0.16 end -- Set density shape.density = 1.0 -- Set friction shape.friction = 0.5 -- Set restitution shape.restitution = 0.1 end end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText("Use WASD keys and mouse to move, Use PageUp PageDown to zoom.") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera -- at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to -- use, but now we just use full screen and default render path configured in the engine command line options local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 4.0 -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 1.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, -1.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_PAGEUP) then local camera = cameraNode:GetComponent("Camera") camera.zoom = camera.zoom * 1.01 end if input:GetKeyDown(KEY_PAGEDOWN) then local camera = cameraNode:GetComponent("Camera") camera.zoom = camera.zoom * 0.99 end end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") -- Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample UnsubscribeFromEvent("SceneUpdate") end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"PAGEUP\" />" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"PAGEDOWN\" />" .. " </element>" .. " </add>" .. "</patch>" end
mit
ZKINGBOTZ/KING
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
mpranj/libelektra
src/bindings/swig/lua/tests/test_key.lua
3
3768
require("kdb") local key = kdb.Key("user:/foo/bar", kdb.KEY_VALUE, "value", kdb.KEY_META, "by", "manuel", kdb.KEY_META, "owner", "myowner" ) local bkey = kdb.Key("system:/bkey", kdb.KEY_FLAGS, kdb.KEY_BINARY, kdb.KEY_VALUE, "bvalue\0\0", kdb.KEY_END, kdb.KEY_META, "lost", "lost" ) -- ctor assert(swig_type(key) == "kdb::Key *") assert(swig_type(bkey) == "kdb::Key *") local k = kdb.Key() assert(swig_type(k) == "kdb::Key *") assert(k:isValid() == true) local k = kdb.Key("user:/foo") assert(swig_type(k) == "kdb::Key *") assert(k:isValid() == true) local k = kdb.Key(key) assert(swig_type(k) == "kdb::Key *") assert(k:isValid() == true) local k = kdb.Key(key:dup()) assert(swig_type(k) == "kdb::Key *") assert(k:isValid() == true) assert(k == key) k.name = "user:/copied" assert(k ~= key) -- operator assert(key ~= bkey) assert(kdb.Key(key) == key) assert(key == kdb.Key("user:/foo/bar", kdb.KEY_META, "owner", "myowner")) assert(kdb.Key() == kdb.Key()) assert(kdb.Key("user:/key1") ~= kdb.Key("user:/key2")) assert(kdb.Key("user:/key1") == kdb.Key("user:/key1")) assert(kdb.Key("user:/key1") ~= kdb.Key("user:/key2")) assert(kdb.Key("user:/key1") < kdb.Key("user:/key2")) assert(kdb.Key("user:/key1") <= kdb.Key("user:/key2")) assert(kdb.Key("user:/key2") > kdb.Key("user:/key1")) assert(kdb.Key("user:/key2") >= kdb.Key("user:/key1")) assert(tostring(key) == "user:/foo/bar") assert(tostring(bkey) == "system:/bkey") -- properties assert(key.name == "user:/foo/bar") assert(key.value == "value") assert(key.string == "value") assert(key.basename == "bar") assert(bkey.name == "system:/bkey") assert(bkey.value == "bvalue\0\0") assert(bkey.binary == "bvalue\0\0") assert(bkey.basename == "bkey") local k = kdb.Key("user:/key1", kdb.KEY_VALUE, "value") assert(k:isBinary() == false) assert(k:getMeta("binary") == nil) k.name = "system:/key2" k.basename = "key3" k.binary = "bvalue\0\0" assert(k.name == "system:/key3") assert(k.value == "bvalue\0\0") assert(k.binary == "bvalue\0\0") assert(k:isBinary() == true) assert(swig_type(k:getMeta("binary")) == "kdb::Key *") local k = kdb.Key("user:/key2") assert(pcall(function() k.name = "foo" end) == false) -- functions assert(key:isNull() == false) assert(bkey:isNull() == false) assert(key:isUser() == true) assert(bkey:isSystem() == true) assert(key:isString() == true) assert(bkey:isBinary() == true) assert(key:isBelow(kdb.Key("user:/foo"))) assert(key:isNameLocked() == false) assert(key:isValueLocked() == false) assert(key:isMetaLocked() == false) local k = kdb.Key("user:/key1", kdb.KEY_VALUE, "value") assert(k:get(), "value") k.binary = "bvalue\0\0" assert(k:get(), "bvalue\0\0") -- meta assert(swig_type(key:getMeta("owner")) == "kdb::Key *") assert(key:getMeta("owner").value == "myowner") assert(key:getMeta("owner").name == "meta:/owner") assert(key:getMeta("by").value == "manuel") assert(key:getMeta("by"):isNameLocked() == true) assert(key:getMeta("by"):isValueLocked() == true) assert(key:getMeta("by"):isMetaLocked() == true) assert(key:hasMeta("doesnt_exist") == false) assert(key:getMeta("doesnt_exist") == nil) assert(bkey:getMeta("binary"):isNull() == false) assert(bkey:getMeta("owner") == nil) local k = kdb.Key("user:/key1") k:setMeta("foo", "bar") assert(k:getMeta("foo").value == "bar") function item_cnt(...) local cnt = 0 for v in ... do cnt = cnt + 1 end return cnt end assert(item_cnt(key:getMeta()) == 2) assert(item_cnt(bkey:getMeta()) == 1) local k = kdb.Key("user:/a\\/b/c") assert(item_cnt(k:name_iterator()) == 3) assert(item_cnt(k:reverse_name_iterator()) == 3) assert(k:name_iterator()() == string.char(kdb.KEY_NS_USER)) assert(k:reverse_name_iterator()() == "c")
bsd-3-clause
Mutos/SoC-Test-001
dat/scripts/pilot/generic.lua
18
1641
--[[ -- @brief Adds an outfit from a list of outfits to the pilot. -- -- Outfits parameter should be something like: -- -- outfits = { -- "Laser Cannon", -- { "Unicorp Fury Launcher", { "Fury Missile", 10 } } -- } -- -- @param p Pilot to add outfits to. -- @param o Table to add what was added. -- @param outfits Table of outfits to add. Look at description for special formatting. --]] function pilot_outfitAdd( p, o, outfits ) local r = rnd.rnd(1, #outfits) if type(outfits[r]) == "string" then _insertOutfit( p, o, outfits[r], 1 ) elseif type(outfits[r]) == "table" then _insertOutfit( p, o, outfits[r][2][1], outfits[r][2][2] ) _insertOutfit( p, o, outfits[r][1], 1 ) -- Add launcher later end end function _insertOutfit( p, o, name, quantity ) local q = 0 -- If pilot actually exists, add outfit if type(p) == "userdata" then local i = quantity while i > 0 do local added = p:addOutfit( name ) if not added then break end i = i - 1 q = q + 1 end else q = quantity end -- Must have quantity if q > 0 then return end -- Try to find in table first for k,v in ipairs(o) do if v[1] == name then v[2] = v[2] + q return end end -- Insert table.insert( o, { name, q } ) end --[[ -- @brief Adds a set of outfit as generated by pilot_outfitAdd to a pilot. -- -- @param p Pilot to add set to. -- @param set Set of outfits to add. --]] function pilot_outfitAddSet( p, set ) for k,v in ipairs(set) do p:addOutfit( v ) end end
gpl-3.0
Anarchid/Zero-K
scripts/raveparty.lua
5
4450
include "pieceControl.lua" local base, turret, spindle, fakespindle = piece('base', 'turret', 'spindle', 'fakespindle') local guns = {} for i=1,6 do guns[i] = { center = piece('center'..i), sleeve = piece('sleeve'..i), barrel = piece('barrel'..i), flare = piece('flare'..i), y = 0, z = 0, } end local hpi = math.pi*0.5 local headingSpeed = math.rad(4) local pitchSpeed = math.rad(61) -- Float maths makes this exactly one revolution every 6 seconds. local spindleOffset = 0 local spindlePitch = 0 guns[5].y = 11 guns[5].z = 7 local dis = math.sqrt(guns[5].y^2 + guns[5].z) local ratio = math.tan(math.rad(60)) guns[6].y = guns[5].y + ratio*guns[5].z guns[6].z = guns[5].z - ratio*guns[5].y local dis6 = math.sqrt(guns[6].y^2 + guns[6].z^2) guns[6].y = guns[6].y*dis/dis6 guns[6].z = guns[6].z*dis/dis6 guns[4].y = guns[5].y - ratio*guns[5].z guns[4].z = guns[5].z + ratio*guns[5].y local dis4 = math.sqrt(guns[4].y^2 + guns[4].z^2) guns[4].y = guns[4].y*dis/dis4 guns[4].z = guns[4].z*dis/dis4 guns[1].y = -guns[4].y guns[1].z = -guns[4].z guns[2].y = -guns[5].y guns[2].z = -guns[5].z guns[3].y = -guns[6].y guns[3].z = -guns[6].z for i=1,6 do guns[i].ys = math.abs(guns[i].y) guns[i].zs = math.abs(guns[i].z) end local smokePiece = {spindle, turret} include "constants.lua" -- Signal definitions local SIG_AIM = 2 local gunNum = 1 local weaponNum = 1 local randomize = false function script.Create() StartThread(GG.Script.SmokeUnit, unitID, smokePiece) Turn(spindle, x_axis, spindleOffset + spindlePitch) for i = 1, 6 do Turn(guns[i].flare, x_axis, (math.rad(-60)* i + 1)) end end function script.Activate() randomize = true end function script.Deactivate() randomize = false end function script.HitByWeapon() if Spring.GetUnitRulesParam(unitID,"disarmed") == 1 then GG.PieceControl.StopTurn (turret, y_axis) GG.PieceControl.StopTurn (spindle, x_axis) end end local sleeper = {} for i = 1, 6 do sleeper[i] = false end function script.AimWeapon(num, heading, pitch) if (sleeper[num]) then return false end sleeper[num] = true while weaponNum ~= num do Sleep(10) end sleeper[num] = false Signal (SIG_AIM) SetSignalMask (SIG_AIM) while Spring.GetUnitRulesParam(unitID,"disarmed") == 1 do Sleep(10) end local curHead = select (2, Spring.UnitScript.GetPieceRotation(turret)) local headDiff = heading-curHead if math.abs(headDiff) > math.pi then headDiff = headDiff - math.abs(headDiff)/headDiff*2*math.pi end --Spring.Echo(headDiff*180/math.pi) if math.abs(headDiff) > hpi then heading = (heading+math.pi)%GG.Script.tau pitch = -pitch+math.pi end spindlePitch = -pitch local slowMult = (Spring.GetUnitRulesParam(unitID,"baseSpeedMult") or 1) Turn(turret, y_axis, heading, headingSpeed*slowMult) Turn(spindle, x_axis, spindlePitch+spindleOffset, pitchSpeed*slowMult) WaitForTurn(turret, y_axis) WaitForTurn(spindle, x_axis) return (Spring.GetUnitRulesParam(unitID,"disarmed") ~= 1) end function script.AimFromWeapon(num) return spindle end function script.QueryWeapon(num) return guns[gunNum].flare end local function gunFire(num) Move(guns[num].barrel, z_axis, guns[num].z*1.2, 8*guns[num].zs) Move(guns[num].barrel, y_axis, guns[num].y*1.2, 8*guns[num].ys) WaitForMove(guns[num].barrel, y_axis) Move(guns[num].barrel, z_axis, 0, 0.2*guns[num].zs) Move(guns[num].barrel, y_axis, 0, 0.2*guns[num].ys) end function script.Shot(num) --EmitSfx(base, 1024) BASE IS NOT CENTRAL EmitSfx(guns[gunNum].flare, 1025) EmitSfx(guns[gunNum].flare, 1026) StartThread(gunFire, gunNum) end function script.FireWeapon(num) Sleep(33) if randomize then weaponNum = math.random(1,6) else weaponNum = weaponNum + 1 if weaponNum > 6 then weaponNum = 1 end end gunNum = gunNum + 1 if gunNum > 6 then gunNum = 1 end spindleOffset = math.rad(60)*(gunNum - 1) end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= .25 then Explode(base, SFX.NONE) Explode(spindle, SFX.NONE) Explode(turret, SFX.NONE) return 1 elseif severity <= .50 then Explode(base, SFX.NONE) Explode(spindle, SFX.NONE) Explode(turret, SFX.NONE) return 1 elseif severity <= .99 then Explode(base, SFX.SHATTER) Explode(spindle, SFX.SHATTER) Explode(turret, SFX.SHATTER) return 2 else Explode(base, SFX.SHATTER) Explode(spindle, SFX.SHATTER) Explode(turret, SFX.SHATTER) return 2 end end
gpl-2.0
166MMX/OpenRA
mods/cnc/maps/nod03a/nod03a.lua
2
2671
NodUnits = { "bike", "e3", "e1", "bggy", "e1", "e3", "bike", "bggy" } FirstAttackWave = { "e1", "e1", "e1", "e2", } SecondThirdAttackWave = { "e1", "e1", "e2", } SendAttackWave = function(units, spawnPoint) Reinforcements.Reinforce(enemy, units, { spawnPoint }, DateTime.Seconds(1), function(actor) actor.AttackMove(PlayerBase.Location) end) end InsertNodUnits = function() Reinforcements.Reinforce(player, NodUnits, { NodEntry.Location, NodRallyPoint.Location }) Trigger.AfterDelay(DateTime.Seconds(9), function() Reinforcements.Reinforce(player, { "mcv" }, { NodEntry.Location, PlayerBase.Location }) end) end WorldLoaded = function() player = Player.GetPlayer("Nod") enemy = Player.GetPlayer("GDI") Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerWon(player, function() Media.PlaySpeechNotification(player, "Win") Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlayMovieFullscreen("desflees.vqa") end) end) Trigger.OnPlayerLost(player, function() Media.PlaySpeechNotification(player, "Lose") Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlayMovieFullscreen("flag.vqa") end) end) Media.PlayMovieFullscreen("dessweep.vqa", function() gdiObjective = enemy.AddPrimaryObjective("Eliminate all Nod forces in the area") nodObjective1 = player.AddPrimaryObjective("Capture the prison") nodObjective2 = player.AddSecondaryObjective("Destroy all GDI forces") end) Trigger.OnCapture(TechCenter, function() Trigger.AfterDelay(DateTime.Seconds(2), function() player.MarkCompletedObjective(nodObjective1) end) end) Trigger.OnKilled(TechCenter, function() player.MarkFailedObjective(nodObjective1) end) InsertNodUnits() Trigger.AfterDelay(DateTime.Seconds(20), function() SendAttackWave(FirstAttackWave, AttackWaveSpawnA.Location) end) Trigger.AfterDelay(DateTime.Seconds(50), function() SendAttackWave(SecondThirdAttackWave, AttackWaveSpawnB.Location) end) Trigger.AfterDelay(DateTime.Seconds(100), function() SendAttackWave(SecondThirdAttackWave, AttackWaveSpawnC.Location) end) end Tick = function() if player.HasNoRequiredUnits() then enemy.MarkCompletedObjective(gdiObjective) end if enemy.HasNoRequiredUnits() then player.MarkCompletedObjective(nodObjective2) end end
gpl-3.0
mridgers/clink
clink/app/scripts/self.lua
2
1763
-- Copyright (c) 2012 Martin Ridgers -- License: http://opensource.org/licenses/MIT -------------------------------------------------------------------------------- local nothing = clink.argmatcher() -------------------------------------------------------------------------------- local inject = clink.argmatcher() :addflags("--help", "--pid", "--profile", "--quiet", "--nolog") -------------------------------------------------------------------------------- local autorun_dashdash = clink.argmatcher() :addarg("--" .. inject) local autorun = clink.argmatcher() :addflags("--allusers", "--help") :addarg( "install" .. autorun_dashdash, "uninstall" .. nothing, "show" .. nothing, "set" ) -------------------------------------------------------------------------------- local function set_handler(word_index, line_state) local name = "" if word_index > 3 then name = line_state:getword(word_index - 1) end local ret = {} for line in io.popen('"'..CLINK_EXE..'" set --list '..name, "r"):lines() do table.insert(ret, line) end return ret end local set = clink.argmatcher() :addflags("--help") :addarg(set_handler) :addarg(set_handler) -------------------------------------------------------------------------------- local history = clink.argmatcher() :addflags("--help") :addarg( "add", "clear" .. nothing, "delete" .. nothing, "expand" ) -------------------------------------------------------------------------------- clink.argmatcher( "clink", "clink_x86.exe", "clink_x64.exe") :addarg( "autorun" .. autorun, "echo" .. nothing, "history" .. history, "info" .. nothing, "inject" .. inject, "set" .. set )
gpl-3.0
lxl1140989/dmsdk
feeds/luci/modules/base/luasrc/model/network.lua
47
33988
--[[ LuCI - Network model Copyright 2009-2010 Jo-Philipp Wich <xm@subsignal.org> 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 type, next, pairs, ipairs, loadfile, table = type, next, pairs, ipairs, loadfile, table local tonumber, tostring, math = tonumber, tostring, math local require = require local bus = require "ubus" local nxo = require "nixio" local nfs = require "nixio.fs" local ipc = require "luci.ip" local sys = require "luci.sys" local utl = require "luci.util" local dsp = require "luci.dispatcher" local uci = require "luci.model.uci" local lng = require "luci.i18n" module "luci.model.network" IFACE_PATTERNS_VIRTUAL = { } IFACE_PATTERNS_IGNORE = { "^wmaster%d", "^wifi%d", "^hwsim%d", "^imq%d", "^ifb%d", "^mon%.wlan%d", "^sit%d", "^gre%d", "^lo$" } IFACE_PATTERNS_WIRELESS = { "^wlan%d", "^wl%d", "^ath%d", "^%w+%.network%d" } protocol = utl.class() local _protocols = { } local _interfaces, _bridge, _switch, _tunnel local _ubus, _ubusnetcache, _ubusdevcache, _ubuswificache local _uci_real, _uci_state function _filter(c, s, o, r) local val = _uci_real:get(c, s, o) if val then local l = { } if type(val) == "string" then for val in val:gmatch("%S+") do if val ~= r then l[#l+1] = val end end if #l > 0 then _uci_real:set(c, s, o, table.concat(l, " ")) else _uci_real:delete(c, s, o) end elseif type(val) == "table" then for _, val in ipairs(val) do if val ~= r then l[#l+1] = val end end if #l > 0 then _uci_real:set(c, s, o, l) else _uci_real:delete(c, s, o) end end end end function _append(c, s, o, a) local val = _uci_real:get(c, s, o) or "" if type(val) == "string" then local l = { } for val in val:gmatch("%S+") do if val ~= a then l[#l+1] = val end end l[#l+1] = a _uci_real:set(c, s, o, table.concat(l, " ")) elseif type(val) == "table" then local l = { } for _, val in ipairs(val) do if val ~= a then l[#l+1] = val end end l[#l+1] = a _uci_real:set(c, s, o, l) end end function _stror(s1, s2) if not s1 or #s1 == 0 then return s2 and #s2 > 0 and s2 else return s1 end end function _get(c, s, o) return _uci_real:get(c, s, o) end function _set(c, s, o, v) if v ~= nil then if type(v) == "boolean" then v = v and "1" or "0" end return _uci_real:set(c, s, o, v) else return _uci_real:delete(c, s, o) end end function _wifi_iface(x) local _, p for _, p in ipairs(IFACE_PATTERNS_WIRELESS) do if x:match(p) then return true end end return false end function _wifi_state(key, val, field) if not next(_ubuswificache) then _ubuswificache = _ubus:call("network.wireless", "status", {}) or {} end local radio, radiostate for radio, radiostate in pairs(_ubuswificache) do local ifc, ifcstate for ifc, ifcstate in pairs(radiostate.interfaces) do if ifcstate[key] == val then return ifcstate[field] end end end end function _wifi_lookup(ifn) -- got a radio#.network# pseudo iface, locate the corresponding section local radio, ifnidx = ifn:match("^(%w+)%.network(%d+)$") if radio and ifnidx then local sid = nil local num = 0 ifnidx = tonumber(ifnidx) _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device == radio then num = num + 1 if num == ifnidx then sid = s['.name'] return false end end end) return sid -- looks like wifi, try to locate the section via state vars elseif _wifi_iface(ifn) then local sid = _wifi_state("ifname", ifn, "section") if not sid then _uci_state:foreach("wireless", "wifi-iface", function(s) if s.ifname == ifn then sid = s['.name'] return false end end) end return sid end end function _iface_virtual(x) local _, p for _, p in ipairs(IFACE_PATTERNS_VIRTUAL) do if x:match(p) then return true end end return false end function _iface_ignore(x) local _, p for _, p in ipairs(IFACE_PATTERNS_IGNORE) do if x:match(p) then return true end end return _iface_virtual(x) end function init(cursor) _uci_real = cursor or _uci_real or uci.cursor() _uci_state = _uci_real:substate() _interfaces = { } _bridge = { } _switch = { } _tunnel = { } _ubus = bus.connect() _ubusnetcache = { } _ubusdevcache = { } _ubuswificache = { } -- read interface information local n, i for n, i in ipairs(nxo.getifaddrs()) do local name = i.name:match("[^:]+") local prnt = name:match("^([^%.]+)%.") if _iface_virtual(name) then _tunnel[name] = true end if _tunnel[name] or not _iface_ignore(name) then _interfaces[name] = _interfaces[name] or { idx = i.ifindex or n, name = name, rawname = i.name, flags = { }, ipaddrs = { }, ip6addrs = { } } if prnt then _switch[name] = true _switch[prnt] = true end if i.family == "packet" then _interfaces[name].flags = i.flags _interfaces[name].stats = i.data _interfaces[name].macaddr = i.addr elseif i.family == "inet" then _interfaces[name].ipaddrs[#_interfaces[name].ipaddrs+1] = ipc.IPv4(i.addr, i.netmask) elseif i.family == "inet6" then _interfaces[name].ip6addrs[#_interfaces[name].ip6addrs+1] = ipc.IPv6(i.addr, i.netmask) end end end -- read bridge informaton local b, l for l in utl.execi("brctl show") do if not l:match("STP") then local r = utl.split(l, "%s+", nil, true) if #r == 4 then b = { name = r[1], id = r[2], stp = r[3] == "yes", ifnames = { _interfaces[r[4]] } } if b.ifnames[1] then b.ifnames[1].bridge = b end _bridge[r[1]] = b elseif b then b.ifnames[#b.ifnames+1] = _interfaces[r[2]] b.ifnames[#b.ifnames].bridge = b end end end return _M end function save(self, ...) _uci_real:save(...) _uci_real:load(...) end function commit(self, ...) _uci_real:commit(...) _uci_real:load(...) end function ifnameof(self, x) if utl.instanceof(x, interface) then return x:name() elseif utl.instanceof(x, protocol) then return x:ifname() elseif type(x) == "string" then return x:match("^[^:]+") end end function get_protocol(self, protoname, netname) local v = _protocols[protoname] if v then return v(netname or "__dummy__") end end function get_protocols(self) local p = { } local _, v for _, v in ipairs(_protocols) do p[#p+1] = v("__dummy__") end return p end function register_protocol(self, protoname) local proto = utl.class(protocol) function proto.__init__(self, name) self.sid = name end function proto.proto(self) return protoname end _protocols[#_protocols+1] = proto _protocols[protoname] = proto return proto end function register_pattern_virtual(self, pat) IFACE_PATTERNS_VIRTUAL[#IFACE_PATTERNS_VIRTUAL+1] = pat end function has_ipv6(self) return nfs.access("/proc/net/ipv6_route") end function add_network(self, n, options) local oldnet = self:get_network(n) if n and #n > 0 and n:match("^[a-zA-Z0-9_]+$") and not oldnet then if _uci_real:section("network", "interface", n, options) then return network(n) end elseif oldnet and oldnet:is_empty() then if options then local k, v for k, v in pairs(options) do oldnet:set(k, v) end end return oldnet end end function get_network(self, n) if n and _uci_real:get("network", n) == "interface" then return network(n) end end function get_networks(self) local nets = { } local nls = { } _uci_real:foreach("network", "interface", function(s) nls[s['.name']] = network(s['.name']) end) local n for n in utl.kspairs(nls) do nets[#nets+1] = nls[n] end return nets end function del_network(self, n) local r = _uci_real:delete("network", n) if r then _uci_real:delete_all("network", "alias", function(s) return (s.interface == n) end) _uci_real:delete_all("network", "route", function(s) return (s.interface == n) end) _uci_real:delete_all("network", "route6", function(s) return (s.interface == n) end) _uci_real:foreach("wireless", "wifi-iface", function(s) local net local rest = { } for net in utl.imatch(s.network) do if net ~= n then rest[#rest+1] = net end end if #rest > 0 then _uci_real:set("wireless", s['.name'], "network", table.concat(rest, " ")) else _uci_real:delete("wireless", s['.name'], "network") end end) end return r end function rename_network(self, old, new) local r if new and #new > 0 and new:match("^[a-zA-Z0-9_]+$") and not self:get_network(new) then r = _uci_real:section("network", "interface", new, _uci_real:get_all("network", old)) if r then _uci_real:foreach("network", "alias", function(s) if s.interface == old then _uci_real:set("network", s['.name'], "interface", new) end end) _uci_real:foreach("network", "route", function(s) if s.interface == old then _uci_real:set("network", s['.name'], "interface", new) end end) _uci_real:foreach("network", "route6", function(s) if s.interface == old then _uci_real:set("network", s['.name'], "interface", new) end end) _uci_real:foreach("wireless", "wifi-iface", function(s) local net local list = { } for net in utl.imatch(s.network) do if net == old then list[#list+1] = new else list[#list+1] = net end end if #list > 0 then _uci_real:set("wireless", s['.name'], "network", table.concat(list, " ")) end end) _uci_real:delete("network", old) end end return r or false end function get_interface(self, i) if _interfaces[i] or _wifi_iface(i) then return interface(i) else local ifc local num = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 if s['.name'] == i then ifc = interface( "%s.network%d" %{s.device, num[s.device] }) return false end end end) return ifc end end function get_interfaces(self) local iface local ifaces = { } local seen = { } local nfs = { } local baseof = { } -- find normal interfaces _uci_real:foreach("network", "interface", function(s) for iface in utl.imatch(s.ifname) do if not _iface_ignore(iface) and not _wifi_iface(iface) then seen[iface] = true nfs[iface] = interface(iface) end end end) for iface in utl.kspairs(_interfaces) do if not (seen[iface] or _iface_ignore(iface) or _wifi_iface(iface)) then nfs[iface] = interface(iface) end end -- find vlan interfaces _uci_real:foreach("network", "switch_vlan", function(s) if not s.device then return end local base = baseof[s.device] if not base then if not s.device:match("^eth%d") then local l for l in utl.execi("swconfig dev %q help 2>/dev/null" % s.device) do if not base then base = l:match("^%w+: (%w+)") end end if not base or not base:match("^eth%d") then base = "eth0" end else base = s.device end baseof[s.device] = base end local vid = tonumber(s.vid or s.vlan) if vid ~= nil and vid >= 0 and vid <= 4095 then local iface = "%s.%d" %{ base, vid } if not seen[iface] then seen[iface] = true nfs[iface] = interface(iface) end end end) for iface in utl.kspairs(nfs) do ifaces[#ifaces+1] = nfs[iface] end -- find wifi interfaces local num = { } local wfs = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local i = "%s.network%d" %{ s.device, num[s.device] } wfs[i] = interface(i) end end) for iface in utl.kspairs(wfs) do ifaces[#ifaces+1] = wfs[iface] end return ifaces end function ignore_interface(self, x) return _iface_ignore(x) end function get_wifidev(self, dev) if _uci_real:get("wireless", dev) == "wifi-device" then return wifidev(dev) end end function get_wifidevs(self) local devs = { } local wfd = { } _uci_real:foreach("wireless", "wifi-device", function(s) wfd[#wfd+1] = s['.name'] end) local dev for _, dev in utl.vspairs(wfd) do devs[#devs+1] = wifidev(dev) end return devs end function get_wifinet(self, net) local wnet = _wifi_lookup(net) if wnet then return wifinet(wnet) end end function add_wifinet(self, net, options) if type(options) == "table" and options.device and _uci_real:get("wireless", options.device) == "wifi-device" then local wnet = _uci_real:section("wireless", "wifi-iface", nil, options) return wifinet(wnet) end end function del_wifinet(self, net) local wnet = _wifi_lookup(net) if wnet then _uci_real:delete("wireless", wnet) return true end return false end function get_status_by_route(self, addr, mask) local _, object for _, object in ipairs(_ubus:objects()) do local net = object:match("^network%.interface%.(.+)") if net then local s = _ubus:call(object, "status", {}) if s and s.route then local rt for _, rt in ipairs(s.route) do if not rt.table and rt.target == addr and rt.mask == mask then return net, s end end end end end end function get_status_by_address(self, addr) local _, object for _, object in ipairs(_ubus:objects()) do local net = object:match("^network%.interface%.(.+)") if net then local s = _ubus:call(object, "status", {}) if s and s['ipv4-address'] then local a for _, a in ipairs(s['ipv4-address']) do if a.address == addr then return net, s end end end if s and s['ipv6-address'] then local a for _, a in ipairs(s['ipv6-address']) do if a.address == addr then return net, s end end end end end end function get_wannet(self) local net = self:get_status_by_route("0.0.0.0", 0) return net and network(net) end function get_wandev(self) local _, stat = self:get_status_by_route("0.0.0.0", 0) return stat and interface(stat.l3_device or stat.device) end function get_wan6net(self) local net = self:get_status_by_route("::", 0) return net and network(net) end function get_wan6dev(self) local _, stat = self:get_status_by_route("::", 0) return stat and interface(stat.l3_device or stat.device) end function network(name, proto) if name then local p = proto or _uci_real:get("network", name, "proto") local c = p and _protocols[p] or protocol return c(name) end end function protocol.__init__(self, name) self.sid = name end function protocol._get(self, opt) local v = _uci_real:get("network", self.sid, opt) if type(v) == "table" then return table.concat(v, " ") end return v or "" end function protocol._ubus(self, field) if not _ubusnetcache[self.sid] then _ubusnetcache[self.sid] = _ubus:call("network.interface.%s" % self.sid, "status", { }) end if _ubusnetcache[self.sid] and field then return _ubusnetcache[self.sid][field] end return _ubusnetcache[self.sid] end function protocol.get(self, opt) return _get("network", self.sid, opt) end function protocol.set(self, opt, val) return _set("network", self.sid, opt, val) end function protocol.ifname(self) local ifname if self:is_floating() then ifname = self:_ubus("l3_device") else ifname = self:_ubus("device") end if not ifname then local num = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local net for net in utl.imatch(s.network) do if net == self.sid then ifname = "%s.network%d" %{ s.device, num[s.device] } return false end end end end) end return ifname end function protocol.proto(self) return "none" end function protocol.get_i18n(self) local p = self:proto() if p == "none" then return lng.translate("Unmanaged") elseif p == "static" then return lng.translate("Static address") elseif p == "dhcp" then return lng.translate("DHCP client") else return lng.translate("Unknown") end end function protocol.type(self) return self:_get("type") end function protocol.name(self) return self.sid end function protocol.uptime(self) return self:_ubus("uptime") or 0 end function protocol.expires(self) local a = tonumber(_uci_state:get("network", self.sid, "lease_acquired")) local l = tonumber(_uci_state:get("network", self.sid, "lease_lifetime")) if a and l then l = l - (nxo.sysinfo().uptime - a) return l > 0 and l or 0 end return -1 end function protocol.metric(self) return tonumber(_uci_state:get("network", self.sid, "metric")) or 0 end function protocol.ipaddr(self) local addrs = self:_ubus("ipv4-address") return addrs and #addrs > 0 and addrs[1].address end function protocol.netmask(self) local addrs = self:_ubus("ipv4-address") return addrs and #addrs > 0 and ipc.IPv4("0.0.0.0/%d" % addrs[1].mask):mask():string() end function protocol.gwaddr(self) local _, route for _, route in ipairs(self:_ubus("route") or { }) do if route.target == "0.0.0.0" and route.mask == 0 then return route.nexthop end end end function protocol.dnsaddrs(self) local dns = { } local _, addr for _, addr in ipairs(self:_ubus("dns-server") or { }) do if not addr:match(":") then dns[#dns+1] = addr end end return dns end function protocol.ip6addr(self) local addrs = self:_ubus("ipv6-address") if addrs and #addrs > 0 then return "%s/%d" %{ addrs[1].address, addrs[1].mask } else addrs = self:_ubus("ipv6-prefix-assignment") if addrs and #addrs > 0 then return "%s/%d" %{ addrs[1].address, addrs[1].mask } end end end function protocol.gw6addr(self) local _, route for _, route in ipairs(self:_ubus("route") or { }) do if route.target == "::" and route.mask == 0 then return ipc.IPv6(route.nexthop):string() end end end function protocol.dns6addrs(self) local dns = { } local _, addr for _, addr in ipairs(self:_ubus("dns-server") or { }) do if addr:match(":") then dns[#dns+1] = addr end end return dns end function protocol.is_bridge(self) return (not self:is_virtual() and self:type() == "bridge") end function protocol.opkg_package(self) return nil end function protocol.is_installed(self) return true end function protocol.is_virtual(self) return false end function protocol.is_floating(self) return false end function protocol.is_empty(self) if self:is_floating() then return false else local rv = true if (self:_get("ifname") or ""):match("%S+") then rv = false end _uci_real:foreach("wireless", "wifi-iface", function(s) local n for n in utl.imatch(s.network) do if n == self.sid then rv = false return false end end end) return rv end end function protocol.add_interface(self, ifname) ifname = _M:ifnameof(ifname) if ifname and not self:is_floating() then -- if its a wifi interface, change its network option local wif = _wifi_lookup(ifname) if wif then _append("wireless", wif, "network", self.sid) -- add iface to our iface list else _append("network", self.sid, "ifname", ifname) end end end function protocol.del_interface(self, ifname) ifname = _M:ifnameof(ifname) if ifname and not self:is_floating() then -- if its a wireless interface, clear its network option local wif = _wifi_lookup(ifname) if wif then _filter("wireless", wif, "network", self.sid) end -- remove the interface _filter("network", self.sid, "ifname", ifname) end end function protocol.get_interface(self) if self:is_virtual() then _tunnel[self:proto() .. "-" .. self.sid] = true return interface(self:proto() .. "-" .. self.sid, self) elseif self:is_bridge() then _bridge["br-" .. self.sid] = true return interface("br-" .. self.sid, self) else local ifn = nil local num = { } for ifn in utl.imatch(_uci_real:get("network", self.sid, "ifname")) do ifn = ifn:match("^[^:/]+") return ifn and interface(ifn, self) end ifn = nil _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local net for net in utl.imatch(s.network) do if net == self.sid then ifn = "%s.network%d" %{ s.device, num[s.device] } return false end end end end) return ifn and interface(ifn, self) end end function protocol.get_interfaces(self) if self:is_bridge() or (self:is_virtual() and not self:is_floating()) then local ifaces = { } local ifn local nfs = { } for ifn in utl.imatch(self:get("ifname")) do ifn = ifn:match("^[^:/]+") nfs[ifn] = interface(ifn, self) end for ifn in utl.kspairs(nfs) do ifaces[#ifaces+1] = nfs[ifn] end local num = { } local wfs = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local net for net in utl.imatch(s.network) do if net == self.sid then ifn = "%s.network%d" %{ s.device, num[s.device] } wfs[ifn] = interface(ifn, self) end end end end) for ifn in utl.kspairs(wfs) do ifaces[#ifaces+1] = wfs[ifn] end return ifaces end end function protocol.contains_interface(self, ifname) ifname = _M:ifnameof(ifname) if not ifname then return false elseif self:is_virtual() and self:proto() .. "-" .. self.sid == ifname then return true elseif self:is_bridge() and "br-" .. self.sid == ifname then return true else local ifn for ifn in utl.imatch(self:get("ifname")) do ifn = ifn:match("[^:]+") if ifn == ifname then return true end end local wif = _wifi_lookup(ifname) if wif then local n for n in utl.imatch(_uci_real:get("wireless", wif, "network")) do if n == self.sid then return true end end end end return false end function protocol.adminlink(self) return dsp.build_url("admin", "network", "network", self.sid) end interface = utl.class() function interface.__init__(self, ifname, network) local wif = _wifi_lookup(ifname) if wif then self.wif = wifinet(wif) self.ifname = _wifi_state("section", wif, "ifname") end self.ifname = self.ifname or ifname self.dev = _interfaces[self.ifname] self.network = network end function interface._ubus(self, field) if not _ubusdevcache[self.ifname] then _ubusdevcache[self.ifname] = _ubus:call("network.device", "status", { name = self.ifname }) end if _ubusdevcache[self.ifname] and field then return _ubusdevcache[self.ifname][field] end return _ubusdevcache[self.ifname] end function interface.name(self) return self.wif and self.wif:ifname() or self.ifname end function interface.mac(self) return (self:_ubus("macaddr") or "00:00:00:00:00:00"):upper() end function interface.ipaddrs(self) return self.dev and self.dev.ipaddrs or { } end function interface.ip6addrs(self) return self.dev and self.dev.ip6addrs or { } end function interface.type(self) if self.wif or _wifi_iface(self.ifname) then return "wifi" elseif _bridge[self.ifname] then return "bridge" elseif _tunnel[self.ifname] then return "tunnel" elseif self.ifname:match("%.") then return "vlan" elseif _switch[self.ifname] then return "switch" else return "ethernet" end end function interface.shortname(self) if self.wif then return "%s %q" %{ self.wif:active_mode(), self.wif:active_ssid() or self.wif:active_bssid() } else return self.ifname end end function interface.get_i18n(self) if self.wif then return "%s: %s %q" %{ lng.translate("Wireless Network"), self.wif:active_mode(), self.wif:active_ssid() or self.wif:active_bssid() } else return "%s: %q" %{ self:get_type_i18n(), self:name() } end end function interface.get_type_i18n(self) local x = self:type() if x == "wifi" then return lng.translate("Wireless Adapter") elseif x == "bridge" then return lng.translate("Bridge") elseif x == "switch" then return lng.translate("Ethernet Switch") elseif x == "vlan" then return lng.translate("VLAN Interface") elseif x == "tunnel" then return lng.translate("Tunnel Interface") else return lng.translate("Ethernet Adapter") end end function interface.adminlink(self) if self.wif then return self.wif:adminlink() end end function interface.ports(self) local members = self:_ubus("bridge-members") if members then local _, iface local ifaces = { } for _, iface in ipairs(members) do ifaces[#ifaces+1] = interface(iface) end end end function interface.bridge_id(self) if self.br then return self.br.id else return nil end end function interface.bridge_stp(self) if self.br then return self.br.stp else return false end end function interface.is_up(self) return self:_ubus("up") or false end function interface.is_bridge(self) return (self:type() == "bridge") end function interface.is_bridgeport(self) return self.dev and self.dev.bridge and true or false end function interface.tx_bytes(self) local stat = self:_ubus("statistics") return stat and stat.tx_bytes or 0 end function interface.rx_bytes(self) local stat = self:_ubus("statistics") return stat and stat.rx_bytes or 0 end function interface.tx_packets(self) local stat = self:_ubus("statistics") return stat and stat.tx_packets or 0 end function interface.rx_packets(self) local stat = self:_ubus("statistics") return stat and stat.rx_packets or 0 end function interface.get_network(self) return self:get_networks()[1] end function interface.get_networks(self) if not self.networks then local nets = { } local _, net for _, net in ipairs(_M:get_networks()) do if net:contains_interface(self.ifname) or net:ifname() == self.ifname then nets[#nets+1] = net end end table.sort(nets, function(a, b) return a.sid < b.sid end) self.networks = nets return nets else return self.networks end end function interface.get_wifinet(self) return self.wif end wifidev = utl.class() function wifidev.__init__(self, dev) self.sid = dev self.iwinfo = dev and sys.wifi.getiwinfo(dev) or { } end function wifidev.get(self, opt) return _get("wireless", self.sid, opt) end function wifidev.set(self, opt, val) return _set("wireless", self.sid, opt, val) end function wifidev.name(self) return self.sid end function wifidev.hwmodes(self) local l = self.iwinfo.hwmodelist if l and next(l) then return l else return { b = true, g = true } end end function wifidev.get_i18n(self) local t = "Generic" if self.iwinfo.type == "wl" then t = "Broadcom" elseif self.iwinfo.type == "madwifi" then t = "Atheros" end local m = "" local l = self:hwmodes() if l.a then m = m .. "a" end if l.b then m = m .. "b" end if l.g then m = m .. "g" end if l.n then m = m .. "n" end return "%s 802.11%s Wireless Controller (%s)" %{ t, m, self:name() } end function wifidev.is_up(self) if _ubuswificache[self.sid] then return (_ubuswificache[self.sid].up == true) end local up = false _uci_state:foreach("wireless", "wifi-iface", function(s) if s.device == self.sid then if s.up == "1" then up = true return false end end end) return up end function wifidev.get_wifinet(self, net) if _uci_real:get("wireless", net) == "wifi-iface" then return wifinet(net) else local wnet = _wifi_lookup(net) if wnet then return wifinet(wnet) end end end function wifidev.get_wifinets(self) local nets = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device == self.sid then nets[#nets+1] = wifinet(s['.name']) end end) return nets end function wifidev.add_wifinet(self, options) options = options or { } options.device = self.sid local wnet = _uci_real:section("wireless", "wifi-iface", nil, options) if wnet then return wifinet(wnet, options) end end function wifidev.del_wifinet(self, net) if utl.instanceof(net, wifinet) then net = net.sid elseif _uci_real:get("wireless", net) ~= "wifi-iface" then net = _wifi_lookup(net) end if net and _uci_real:get("wireless", net, "device") == self.sid then _uci_real:delete("wireless", net) return true end return false end wifinet = utl.class() function wifinet.__init__(self, net, data) self.sid = net local num = { } local netid _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 if s['.name'] == self.sid then netid = "%s.network%d" %{ s.device, num[s.device] } return false end end end) local dev = _wifi_state("section", self.sid, "ifname") or netid self.netid = netid self.wdev = dev self.iwinfo = dev and sys.wifi.getiwinfo(dev) or { } self.iwdata = data or _uci_state:get_all("wireless", self.sid) or _uci_real:get_all("wireless", self.sid) or { } end function wifinet.get(self, opt) return _get("wireless", self.sid, opt) end function wifinet.set(self, opt, val) return _set("wireless", self.sid, opt, val) end function wifinet.mode(self) return _uci_state:get("wireless", self.sid, "mode") or "ap" end function wifinet.ssid(self) return _uci_state:get("wireless", self.sid, "ssid") end function wifinet.bssid(self) return _uci_state:get("wireless", self.sid, "bssid") end function wifinet.network(self) return _uci_state:get("wifinet", self.sid, "network") end function wifinet.id(self) return self.netid end function wifinet.name(self) return self.sid end function wifinet.ifname(self) local ifname = self.iwinfo.ifname if not ifname or ifname:match("^wifi%d") or ifname:match("^radio%d") then ifname = self.wdev end return ifname end function wifinet.get_device(self) if self.iwdata.device then return wifidev(self.iwdata.device) end end function wifinet.is_up(self) local ifc = self:get_interface() return (ifc and ifc:is_up() or false) end function wifinet.active_mode(self) local m = _stror(self.iwinfo.mode, self.iwdata.mode) or "ap" if m == "ap" then m = "Master" elseif m == "sta" then m = "Client" elseif m == "adhoc" then m = "Ad-Hoc" elseif m == "mesh" then m = "Mesh" elseif m == "monitor" then m = "Monitor" end return m end function wifinet.active_mode_i18n(self) return lng.translate(self:active_mode()) end function wifinet.active_ssid(self) return _stror(self.iwinfo.ssid, self.iwdata.ssid) end function wifinet.active_bssid(self) return _stror(self.iwinfo.bssid, self.iwdata.bssid) or "00:00:00:00:00:00" end function wifinet.active_encryption(self) local enc = self.iwinfo and self.iwinfo.encryption return enc and enc.description or "-" end function wifinet.assoclist(self) return self.iwinfo.assoclist or { } end function wifinet.frequency(self) local freq = self.iwinfo.frequency if freq and freq > 0 then return "%.03f" % (freq / 1000) end end function wifinet.bitrate(self) local rate = self.iwinfo.bitrate if rate and rate > 0 then return (rate / 1000) end end function wifinet.channel(self) return self.iwinfo.channel or tonumber(_uci_state:get("wireless", self.iwdata.device, "channel")) end function wifinet.signal(self) return self.iwinfo.signal or 0 end function wifinet.noise(self) return self.iwinfo.noise or 0 end function wifinet.country(self) return self.iwinfo.country or "00" end function wifinet.txpower(self) local pwr = (self.iwinfo.txpower or 0) return pwr + self:txpower_offset() end function wifinet.txpower_offset(self) return self.iwinfo.txpower_offset or 0 end function wifinet.signal_level(self, s, n) if self:active_bssid() ~= "00:00:00:00:00:00" then local signal = s or self:signal() local noise = n or self:noise() if signal < 0 and noise < 0 then local snr = -1 * (noise - signal) return math.floor(snr / 5) else return 0 end else return -1 end end function wifinet.signal_percent(self) local qc = self.iwinfo.quality or 0 local qm = self.iwinfo.quality_max or 0 if qc > 0 and qm > 0 then return math.floor((100 / qm) * qc) else return 0 end end function wifinet.shortname(self) return "%s %q" %{ lng.translate(self:active_mode()), self:active_ssid() or self:active_bssid() } end function wifinet.get_i18n(self) return "%s: %s %q (%s)" %{ lng.translate("Wireless Network"), lng.translate(self:active_mode()), self:active_ssid() or self:active_bssid(), self:ifname() } end function wifinet.adminlink(self) return dsp.build_url("admin", "network", "wireless", self.netid) end function wifinet.get_network(self) return self:get_networks()[1] end function wifinet.get_networks(self) local nets = { } local net for net in utl.imatch(tostring(self.iwdata.network)) do if _uci_real:get("network", net) == "interface" then nets[#nets+1] = network(net) end end table.sort(nets, function(a, b) return a.sid < b.sid end) return nets end function wifinet.get_interface(self) return interface(self:ifname()) end -- setup base protocols _M:register_protocol("static") _M:register_protocol("dhcp") _M:register_protocol("none") -- load protocol extensions local exts = nfs.dir(utl.libpath() .. "/model/network") if exts then local ext for ext in exts do if ext:match("%.lua$") then require("luci.model.network." .. ext:gsub("%.lua$", "")) end end end
gpl-2.0
lxl1140989/dmsdk
feeds/luci/modules/base/luasrc/cbi.lua
76
40152
--[[ LuCI - Configuration Bind Interface Description: Offers an interface for binding configuration values to certain data types. Supports value and range validation and basic dependencies. FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> 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. ]]-- module("luci.cbi", package.seeall) require("luci.template") local util = require("luci.util") require("luci.http") --local event = require "luci.sys.event" local fs = require("nixio.fs") local uci = require("luci.model.uci") local datatypes = require("luci.cbi.datatypes") local class = util.class local instanceof = util.instanceof FORM_NODATA = 0 FORM_PROCEED = 0 FORM_VALID = 1 FORM_DONE = 1 FORM_INVALID = -1 FORM_CHANGED = 2 FORM_SKIP = 4 AUTO = true CREATE_PREFIX = "cbi.cts." REMOVE_PREFIX = "cbi.rts." RESORT_PREFIX = "cbi.sts." FEXIST_PREFIX = "cbi.cbe." -- Loads a CBI map from given file, creating an environment and returns it function load(cbimap, ...) local fs = require "nixio.fs" local i18n = require "luci.i18n" require("luci.config") require("luci.util") local upldir = "/lib/uci/upload/" local cbidir = luci.util.libpath() .. "/model/cbi/" local func, err if fs.access(cbidir..cbimap..".lua") then func, err = loadfile(cbidir..cbimap..".lua") elseif fs.access(cbimap) then func, err = loadfile(cbimap) else func, err = nil, "Model '" .. cbimap .. "' not found!" end assert(func, err) local env = { translate=i18n.translate, translatef=i18n.translatef, arg={...} } setfenv(func, setmetatable(env, {__index = function(tbl, key) return rawget(tbl, key) or _M[key] or _G[key] end})) local maps = { func() } local uploads = { } local has_upload = false for i, map in ipairs(maps) do if not instanceof(map, Node) then error("CBI map returns no valid map object!") return nil else map:prepare() if map.upload_fields then has_upload = true for _, field in ipairs(map.upload_fields) do uploads[ field.config .. '.' .. (field.section.sectiontype or '1') .. '.' .. field.option ] = true end end end end if has_upload then local uci = luci.model.uci.cursor() local prm = luci.http.context.request.message.params local fd, cbid luci.http.setfilehandler( function( field, chunk, eof ) if not field then return end if field.name and not cbid then local c, s, o = field.name:gmatch( "cbid%.([^%.]+)%.([^%.]+)%.([^%.]+)" )() if c and s and o then local t = uci:get( c, s ) or s if uploads[c.."."..t.."."..o] then local path = upldir .. field.name fd = io.open(path, "w") if fd then cbid = field.name prm[cbid] = path end end end end if field.name == cbid and fd then fd:write(chunk) end if eof and fd then fd:close() fd = nil cbid = nil end end ) end return maps end -- -- Compile a datatype specification into a parse tree for evaluation later on -- local cdt_cache = { } function compile_datatype(code) local i local pos = 0 local esc = false local depth = 0 local stack = { } for i = 1, #code+1 do local byte = code:byte(i) or 44 if esc then esc = false elseif byte == 92 then esc = true elseif byte == 40 or byte == 44 then if depth <= 0 then if pos < i then local label = code:sub(pos, i-1) :gsub("\\(.)", "%1") :gsub("^%s+", "") :gsub("%s+$", "") if #label > 0 and tonumber(label) then stack[#stack+1] = tonumber(label) elseif label:match("^'.*'$") or label:match('^".*"$') then stack[#stack+1] = label:gsub("[\"'](.*)[\"']", "%1") elseif type(datatypes[label]) == "function" then stack[#stack+1] = datatypes[label] stack[#stack+1] = { } else error("Datatype error, bad token %q" % label) end end pos = i + 1 end depth = depth + (byte == 40 and 1 or 0) elseif byte == 41 then depth = depth - 1 if depth <= 0 then if type(stack[#stack-1]) ~= "function" then error("Datatype error, argument list follows non-function") end stack[#stack] = compile_datatype(code:sub(pos, i-1)) pos = i + 1 end end end return stack end function verify_datatype(dt, value) if dt and #dt > 0 then if not cdt_cache[dt] then local c = compile_datatype(dt) if c and type(c[1]) == "function" then cdt_cache[dt] = c else error("Datatype error, not a function expression") end end if cdt_cache[dt] then return cdt_cache[dt][1](value, unpack(cdt_cache[dt][2])) end end return true end -- Node pseudo abstract class Node = class() function Node.__init__(self, title, description) self.children = {} self.title = title or "" self.description = description or "" self.template = "cbi/node" end -- hook helper function Node._run_hook(self, hook) if type(self[hook]) == "function" then return self[hook](self) end end function Node._run_hooks(self, ...) local f local r = false for _, f in ipairs(arg) do if type(self[f]) == "function" then self[f](self) r = true end end return r end -- Prepare nodes function Node.prepare(self, ...) for k, child in ipairs(self.children) do child:prepare(...) end end -- Append child nodes function Node.append(self, obj) table.insert(self.children, obj) end -- Parse this node and its children function Node.parse(self, ...) for k, child in ipairs(self.children) do child:parse(...) end end -- Render this node function Node.render(self, scope) scope = scope or {} scope.self = self luci.template.render(self.template, scope) end -- Render the children function Node.render_children(self, ...) local k, node for k, node in ipairs(self.children) do node.last_child = (k == #self.children) node:render(...) end end --[[ A simple template element ]]-- Template = class(Node) function Template.__init__(self, template) Node.__init__(self) self.template = template end function Template.render(self) luci.template.render(self.template, {self=self}) end function Template.parse(self, readinput) self.readinput = (readinput ~= false) return Map.formvalue(self, "cbi.submit") and FORM_DONE or FORM_NODATA end --[[ Map - A map describing a configuration file ]]-- Map = class(Node) function Map.__init__(self, config, ...) Node.__init__(self, ...) self.config = config self.parsechain = {self.config} self.template = "cbi/map" self.apply_on_parse = nil self.readinput = true self.proceed = false self.flow = {} self.uci = uci.cursor() self.save = true self.changed = false if not self.uci:load(self.config) then error("Unable to read UCI data: " .. self.config) end end function Map.formvalue(self, key) return self.readinput and luci.http.formvalue(key) end function Map.formvaluetable(self, key) return self.readinput and luci.http.formvaluetable(key) or {} end function Map.get_scheme(self, sectiontype, option) if not option then return self.scheme and self.scheme.sections[sectiontype] else return self.scheme and self.scheme.variables[sectiontype] and self.scheme.variables[sectiontype][option] end end function Map.submitstate(self) return self:formvalue("cbi.submit") end -- Chain foreign config function Map.chain(self, config) table.insert(self.parsechain, config) end function Map.state_handler(self, state) return state end -- Use optimized UCI writing function Map.parse(self, readinput, ...) self.readinput = (readinput ~= false) self:_run_hooks("on_parse") if self:formvalue("cbi.skip") then self.state = FORM_SKIP return self:state_handler(self.state) end Node.parse(self, ...) if self.save then self:_run_hooks("on_save", "on_before_save") for i, config in ipairs(self.parsechain) do self.uci:save(config) end self:_run_hooks("on_after_save") if self:submitstate() and ((not self.proceed and self.flow.autoapply) or luci.http.formvalue("cbi.apply")) then self:_run_hooks("on_before_commit") for i, config in ipairs(self.parsechain) do self.uci:commit(config) -- Refresh data because commit changes section names self.uci:load(config) end self:_run_hooks("on_commit", "on_after_commit", "on_before_apply") if self.apply_on_parse then self.uci:apply(self.parsechain) self:_run_hooks("on_apply", "on_after_apply") else -- This is evaluated by the dispatcher and delegated to the -- template which in turn fires XHR to perform the actual -- apply actions. self.apply_needed = true end -- Reparse sections Node.parse(self, true) end for i, config in ipairs(self.parsechain) do self.uci:unload(config) end if type(self.commit_handler) == "function" then self:commit_handler(self:submitstate()) end end if self:submitstate() then if not self.save then self.state = FORM_INVALID elseif self.proceed then self.state = FORM_PROCEED else self.state = self.changed and FORM_CHANGED or FORM_VALID end else self.state = FORM_NODATA end return self:state_handler(self.state) end function Map.render(self, ...) self:_run_hooks("on_init") Node.render(self, ...) end -- Creates a child section function Map.section(self, class, ...) if instanceof(class, AbstractSection) then local obj = class(self, ...) self:append(obj) return obj else error("class must be a descendent of AbstractSection") end end -- UCI add function Map.add(self, sectiontype) return self.uci:add(self.config, sectiontype) end -- UCI set function Map.set(self, section, option, value) if type(value) ~= "table" or #value > 0 then if option then return self.uci:set(self.config, section, option, value) else return self.uci:set(self.config, section, value) end else return Map.del(self, section, option) end end -- UCI del function Map.del(self, section, option) if option then return self.uci:delete(self.config, section, option) else return self.uci:delete(self.config, section) end end -- UCI get function Map.get(self, section, option) if not section then return self.uci:get_all(self.config) elseif option then return self.uci:get(self.config, section, option) else return self.uci:get_all(self.config, section) end end --[[ Compound - Container ]]-- Compound = class(Node) function Compound.__init__(self, ...) Node.__init__(self) self.template = "cbi/compound" self.children = {...} end function Compound.populate_delegator(self, delegator) for _, v in ipairs(self.children) do v.delegator = delegator end end function Compound.parse(self, ...) local cstate, state = 0 for k, child in ipairs(self.children) do cstate = child:parse(...) state = (not state or cstate < state) and cstate or state end return state end --[[ Delegator - Node controller ]]-- Delegator = class(Node) function Delegator.__init__(self, ...) Node.__init__(self, ...) self.nodes = {} self.defaultpath = {} self.pageaction = false self.readinput = true self.allow_reset = false self.allow_cancel = false self.allow_back = false self.allow_finish = false self.template = "cbi/delegator" end function Delegator.set(self, name, node) assert(not self.nodes[name], "Duplicate entry") self.nodes[name] = node end function Delegator.add(self, name, node) node = self:set(name, node) self.defaultpath[#self.defaultpath+1] = name end function Delegator.insert_after(self, name, after) local n = #self.chain + 1 for k, v in ipairs(self.chain) do if v == after then n = k + 1 break end end table.insert(self.chain, n, name) end function Delegator.set_route(self, ...) local n, chain, route = 0, self.chain, {...} for i = 1, #chain do if chain[i] == self.current then n = i break end end for i = 1, #route do n = n + 1 chain[n] = route[i] end for i = n + 1, #chain do chain[i] = nil end end function Delegator.get(self, name) local node = self.nodes[name] if type(node) == "string" then node = load(node, name) end if type(node) == "table" and getmetatable(node) == nil then node = Compound(unpack(node)) end return node end function Delegator.parse(self, ...) if self.allow_cancel and Map.formvalue(self, "cbi.cancel") then if self:_run_hooks("on_cancel") then return FORM_DONE end end if not Map.formvalue(self, "cbi.delg.current") then self:_run_hooks("on_init") end local newcurrent self.chain = self.chain or self:get_chain() self.current = self.current or self:get_active() self.active = self.active or self:get(self.current) assert(self.active, "Invalid state") local stat = FORM_DONE if type(self.active) ~= "function" then self.active:populate_delegator(self) stat = self.active:parse() else self:active() end if stat > FORM_PROCEED then if Map.formvalue(self, "cbi.delg.back") then newcurrent = self:get_prev(self.current) else newcurrent = self:get_next(self.current) end elseif stat < FORM_PROCEED then return stat end if not Map.formvalue(self, "cbi.submit") then return FORM_NODATA elseif stat > FORM_PROCEED and (not newcurrent or not self:get(newcurrent)) then return self:_run_hook("on_done") or FORM_DONE else self.current = newcurrent or self.current self.active = self:get(self.current) if type(self.active) ~= "function" then self.active:populate_delegator(self) local stat = self.active:parse(false) if stat == FORM_SKIP then return self:parse(...) else return FORM_PROCEED end else return self:parse(...) end end end function Delegator.get_next(self, state) for k, v in ipairs(self.chain) do if v == state then return self.chain[k+1] end end end function Delegator.get_prev(self, state) for k, v in ipairs(self.chain) do if v == state then return self.chain[k-1] end end end function Delegator.get_chain(self) local x = Map.formvalue(self, "cbi.delg.path") or self.defaultpath return type(x) == "table" and x or {x} end function Delegator.get_active(self) return Map.formvalue(self, "cbi.delg.current") or self.chain[1] end --[[ Page - A simple node ]]-- Page = class(Node) Page.__init__ = Node.__init__ Page.parse = function() end --[[ SimpleForm - A Simple non-UCI form ]]-- SimpleForm = class(Node) function SimpleForm.__init__(self, config, title, description, data) Node.__init__(self, title, description) self.config = config self.data = data or {} self.template = "cbi/simpleform" self.dorender = true self.pageaction = false self.readinput = true end SimpleForm.formvalue = Map.formvalue SimpleForm.formvaluetable = Map.formvaluetable function SimpleForm.parse(self, readinput, ...) self.readinput = (readinput ~= false) if self:formvalue("cbi.skip") then return FORM_SKIP end if self:formvalue("cbi.cancel") and self:_run_hooks("on_cancel") then return FORM_DONE end if self:submitstate() then Node.parse(self, 1, ...) end local valid = true for k, j in ipairs(self.children) do for i, v in ipairs(j.children) do valid = valid and (not v.tag_missing or not v.tag_missing[1]) and (not v.tag_invalid or not v.tag_invalid[1]) and (not v.error) end end local state = not self:submitstate() and FORM_NODATA or valid and FORM_VALID or FORM_INVALID self.dorender = not self.handle if self.handle then local nrender, nstate = self:handle(state, self.data) self.dorender = self.dorender or (nrender ~= false) state = nstate or state end return state end function SimpleForm.render(self, ...) if self.dorender then Node.render(self, ...) end end function SimpleForm.submitstate(self) return self:formvalue("cbi.submit") end function SimpleForm.section(self, class, ...) if instanceof(class, AbstractSection) then local obj = class(self, ...) self:append(obj) return obj else error("class must be a descendent of AbstractSection") end end -- Creates a child field function SimpleForm.field(self, class, ...) local section for k, v in ipairs(self.children) do if instanceof(v, SimpleSection) then section = v break end end if not section then section = self:section(SimpleSection) end if instanceof(class, AbstractValue) then local obj = class(self, section, ...) obj.track_missing = true section:append(obj) return obj else error("class must be a descendent of AbstractValue") end end function SimpleForm.set(self, section, option, value) self.data[option] = value end function SimpleForm.del(self, section, option) self.data[option] = nil end function SimpleForm.get(self, section, option) return self.data[option] end function SimpleForm.get_scheme() return nil end Form = class(SimpleForm) function Form.__init__(self, ...) SimpleForm.__init__(self, ...) self.embedded = true end --[[ AbstractSection ]]-- AbstractSection = class(Node) function AbstractSection.__init__(self, map, sectiontype, ...) Node.__init__(self, ...) self.sectiontype = sectiontype self.map = map self.config = map.config self.optionals = {} self.defaults = {} self.fields = {} self.tag_error = {} self.tag_invalid = {} self.tag_deperror = {} self.changed = false self.optional = true self.addremove = false self.dynamic = false end -- Define a tab for the section function AbstractSection.tab(self, tab, title, desc) self.tabs = self.tabs or { } self.tab_names = self.tab_names or { } self.tab_names[#self.tab_names+1] = tab self.tabs[tab] = { title = title, description = desc, childs = { } } end -- Check whether the section has tabs function AbstractSection.has_tabs(self) return (self.tabs ~= nil) and (next(self.tabs) ~= nil) end -- Appends a new option function AbstractSection.option(self, class, option, ...) if instanceof(class, AbstractValue) then local obj = class(self.map, self, option, ...) self:append(obj) self.fields[option] = obj return obj elseif class == true then error("No valid class was given and autodetection failed.") else error("class must be a descendant of AbstractValue") end end -- Appends a new tabbed option function AbstractSection.taboption(self, tab, ...) assert(tab and self.tabs and self.tabs[tab], "Cannot assign option to not existing tab %q" % tostring(tab)) local l = self.tabs[tab].childs local o = AbstractSection.option(self, ...) if o then l[#l+1] = o end return o end -- Render a single tab function AbstractSection.render_tab(self, tab, ...) assert(tab and self.tabs and self.tabs[tab], "Cannot render not existing tab %q" % tostring(tab)) local k, node for k, node in ipairs(self.tabs[tab].childs) do node.last_child = (k == #self.tabs[tab].childs) node:render(...) end end -- Parse optional options function AbstractSection.parse_optionals(self, section) if not self.optional then return end self.optionals[section] = {} local field = self.map:formvalue("cbi.opt."..self.config.."."..section) for k,v in ipairs(self.children) do if v.optional and not v:cfgvalue(section) and not self:has_tabs() then if field == v.option then field = nil self.map.proceed = true else table.insert(self.optionals[section], v) end end end if field and #field > 0 and self.dynamic then self:add_dynamic(field) end end -- Add a dynamic option function AbstractSection.add_dynamic(self, field, optional) local o = self:option(Value, field, field) o.optional = optional end -- Parse all dynamic options function AbstractSection.parse_dynamic(self, section) if not self.dynamic then return end local arr = luci.util.clone(self:cfgvalue(section)) local form = self.map:formvaluetable("cbid."..self.config.."."..section) for k, v in pairs(form) do arr[k] = v end for key,val in pairs(arr) do local create = true for i,c in ipairs(self.children) do if c.option == key then create = false end end if create and key:sub(1, 1) ~= "." then self.map.proceed = true self:add_dynamic(key, true) end end end -- Returns the section's UCI table function AbstractSection.cfgvalue(self, section) return self.map:get(section) end -- Push events function AbstractSection.push_events(self) --luci.util.append(self.map.events, self.events) self.map.changed = true end -- Removes the section function AbstractSection.remove(self, section) self.map.proceed = true return self.map:del(section) end -- Creates the section function AbstractSection.create(self, section) local stat if section then stat = section:match("^[%w_]+$") and self.map:set(section, nil, self.sectiontype) else section = self.map:add(self.sectiontype) stat = section end if stat then for k,v in pairs(self.children) do if v.default then self.map:set(section, v.option, v.default) end end for k,v in pairs(self.defaults) do self.map:set(section, k, v) end end self.map.proceed = true return stat end SimpleSection = class(AbstractSection) function SimpleSection.__init__(self, form, ...) AbstractSection.__init__(self, form, nil, ...) self.template = "cbi/nullsection" end Table = class(AbstractSection) function Table.__init__(self, form, data, ...) local datasource = {} local tself = self datasource.config = "table" self.data = data or {} datasource.formvalue = Map.formvalue datasource.formvaluetable = Map.formvaluetable datasource.readinput = true function datasource.get(self, section, option) return tself.data[section] and tself.data[section][option] end function datasource.submitstate(self) return Map.formvalue(self, "cbi.submit") end function datasource.del(...) return true end function datasource.get_scheme() return nil end AbstractSection.__init__(self, datasource, "table", ...) self.template = "cbi/tblsection" self.rowcolors = true self.anonymous = true end function Table.parse(self, readinput) self.map.readinput = (readinput ~= false) for i, k in ipairs(self:cfgsections()) do if self.map:submitstate() then Node.parse(self, k) end end end function Table.cfgsections(self) local sections = {} for i, v in luci.util.kspairs(self.data) do table.insert(sections, i) end return sections end function Table.update(self, data) self.data = data end --[[ NamedSection - A fixed configuration section defined by its name ]]-- NamedSection = class(AbstractSection) function NamedSection.__init__(self, map, section, stype, ...) AbstractSection.__init__(self, map, stype, ...) -- Defaults self.addremove = false self.template = "cbi/nsection" self.section = section end function NamedSection.parse(self, novld) local s = self.section local active = self:cfgvalue(s) if self.addremove then local path = self.config.."."..s if active then -- Remove the section if self.map:formvalue("cbi.rns."..path) and self:remove(s) then self:push_events() return end else -- Create and apply default values if self.map:formvalue("cbi.cns."..path) then self:create(s) return end end end if active then AbstractSection.parse_dynamic(self, s) if self.map:submitstate() then Node.parse(self, s) end AbstractSection.parse_optionals(self, s) if self.changed then self:push_events() end end end --[[ TypedSection - A (set of) configuration section(s) defined by the type addremove: Defines whether the user can add/remove sections of this type anonymous: Allow creating anonymous sections validate: a validation function returning nil if the section is invalid ]]-- TypedSection = class(AbstractSection) function TypedSection.__init__(self, map, type, ...) AbstractSection.__init__(self, map, type, ...) self.template = "cbi/tsection" self.deps = {} self.anonymous = false end -- Return all matching UCI sections for this TypedSection function TypedSection.cfgsections(self) local sections = {} self.map.uci:foreach(self.map.config, self.sectiontype, function (section) if self:checkscope(section[".name"]) then table.insert(sections, section[".name"]) end end) return sections end -- Limits scope to sections that have certain option => value pairs function TypedSection.depends(self, option, value) table.insert(self.deps, {option=option, value=value}) end function TypedSection.parse(self, novld) if self.addremove then -- Remove local crval = REMOVE_PREFIX .. self.config local name = self.map:formvaluetable(crval) for k,v in pairs(name) do if k:sub(-2) == ".x" then k = k:sub(1, #k - 2) end if self:cfgvalue(k) and self:checkscope(k) then self:remove(k) end end end local co for i, k in ipairs(self:cfgsections()) do AbstractSection.parse_dynamic(self, k) if self.map:submitstate() then Node.parse(self, k, novld) end AbstractSection.parse_optionals(self, k) end if self.addremove then -- Create local created local crval = CREATE_PREFIX .. self.config .. "." .. self.sectiontype local origin, name = next(self.map:formvaluetable(crval)) if self.anonymous then if name then created = self:create(nil, origin) end else if name then -- Ignore if it already exists if self:cfgvalue(name) then name = nil; end name = self:checkscope(name) if not name then self.err_invalid = true end if name and #name > 0 then created = self:create(name, origin) and name if not created then self.invalid_cts = true end end end end if created then AbstractSection.parse_optionals(self, created) end end if self.sortable then local stval = RESORT_PREFIX .. self.config .. "." .. self.sectiontype local order = self.map:formvalue(stval) if order and #order > 0 then local sid local num = 0 for sid in util.imatch(order) do self.map.uci:reorder(self.config, sid, num) num = num + 1 end self.changed = (num > 0) end end if created or self.changed then self:push_events() end end -- Verifies scope of sections function TypedSection.checkscope(self, section) -- Check if we are not excluded if self.filter and not self:filter(section) then return nil end -- Check if at least one dependency is met if #self.deps > 0 and self:cfgvalue(section) then local stat = false for k, v in ipairs(self.deps) do if self:cfgvalue(section)[v.option] == v.value then stat = true end end if not stat then return nil end end return self:validate(section) end -- Dummy validate function function TypedSection.validate(self, section) return section end --[[ AbstractValue - An abstract Value Type null: Value can be empty valid: A function returning the value if it is valid otherwise nil depends: A table of option => value pairs of which one must be true default: The default value size: The size of the input fields rmempty: Unset value if empty optional: This value is optional (see AbstractSection.optionals) ]]-- AbstractValue = class(Node) function AbstractValue.__init__(self, map, section, option, ...) Node.__init__(self, ...) self.section = section self.option = option self.map = map self.config = map.config self.tag_invalid = {} self.tag_missing = {} self.tag_reqerror = {} self.tag_error = {} self.deps = {} self.subdeps = {} --self.cast = "string" self.track_missing = false self.rmempty = true self.default = nil self.size = nil self.optional = false end function AbstractValue.prepare(self) self.cast = self.cast or "string" end -- Add a dependencie to another section field function AbstractValue.depends(self, field, value) local deps if type(field) == "string" then deps = {} deps[field] = value else deps = field end table.insert(self.deps, {deps=deps, add=""}) end -- Generates the unique CBID function AbstractValue.cbid(self, section) return "cbid."..self.map.config.."."..section.."."..self.option end -- Return whether this object should be created function AbstractValue.formcreated(self, section) local key = "cbi.opt."..self.config.."."..section return (self.map:formvalue(key) == self.option) end -- Returns the formvalue for this object function AbstractValue.formvalue(self, section) return self.map:formvalue(self:cbid(section)) end function AbstractValue.additional(self, value) self.optional = value end function AbstractValue.mandatory(self, value) self.rmempty = not value end function AbstractValue.add_error(self, section, type, msg) self.error = self.error or { } self.error[section] = msg or type self.section.error = self.section.error or { } self.section.error[section] = self.section.error[section] or { } table.insert(self.section.error[section], msg or type) if type == "invalid" then self.tag_invalid[section] = true elseif type == "missing" then self.tag_missing[section] = true end self.tag_error[section] = true self.map.save = false end function AbstractValue.parse(self, section, novld) local fvalue = self:formvalue(section) local cvalue = self:cfgvalue(section) -- If favlue and cvalue are both tables and have the same content -- make them identical if type(fvalue) == "table" and type(cvalue) == "table" then local equal = #fvalue == #cvalue if equal then for i=1, #fvalue do if cvalue[i] ~= fvalue[i] then equal = false end end end if equal then fvalue = cvalue end end if fvalue and #fvalue > 0 then -- If we have a form value, write it to UCI local val_err fvalue, val_err = self:validate(fvalue, section) fvalue = self:transform(fvalue) if not fvalue and not novld then self:add_error(section, "invalid", val_err) end if fvalue and (self.forcewrite or not (fvalue == cvalue)) then if self:write(section, fvalue) then -- Push events self.section.changed = true --luci.util.append(self.map.events, self.events) end end else -- Unset the UCI or error if self.rmempty or self.optional then if self:remove(section) then -- Push events self.section.changed = true --luci.util.append(self.map.events, self.events) end elseif cvalue ~= fvalue and not novld then -- trigger validator with nil value to get custom user error msg. local _, val_err = self:validate(nil, section) self:add_error(section, "missing", val_err) end end end -- Render if this value exists or if it is mandatory function AbstractValue.render(self, s, scope) if not self.optional or self.section:has_tabs() or self:cfgvalue(s) or self:formcreated(s) then scope = scope or {} scope.section = s scope.cbid = self:cbid(s) Node.render(self, scope) end end -- Return the UCI value of this object function AbstractValue.cfgvalue(self, section) local value if self.tag_error[section] then value = self:formvalue(section) else value = self.map:get(section, self.option) end if not value then return nil elseif not self.cast or self.cast == type(value) then return value elseif self.cast == "string" then if type(value) == "table" then return value[1] end elseif self.cast == "table" then return { value } end end -- Validate the form value function AbstractValue.validate(self, value) if self.datatype and value then if type(value) == "table" then local v for _, v in ipairs(value) do if v and #v > 0 and not verify_datatype(self.datatype, v) then return nil end end else if not verify_datatype(self.datatype, value) then return nil end end end return value end AbstractValue.transform = AbstractValue.validate -- Write to UCI function AbstractValue.write(self, section, value) return self.map:set(section, self.option, value) end -- Remove from UCI function AbstractValue.remove(self, section) return self.map:del(section, self.option) end --[[ Value - A one-line value maxlength: The maximum length ]]-- Value = class(AbstractValue) function Value.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/value" self.keylist = {} self.vallist = {} end function Value.reset_values(self) self.keylist = {} self.vallist = {} end function Value.value(self, key, val) val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end -- DummyValue - This does nothing except being there DummyValue = class(AbstractValue) function DummyValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/dvalue" self.value = nil end function DummyValue.cfgvalue(self, section) local value if self.value then if type(self.value) == "function" then value = self:value(section) else value = self.value end else value = AbstractValue.cfgvalue(self, section) end return value end function DummyValue.parse(self) end --[[ Flag - A flag being enabled or disabled ]]-- Flag = class(AbstractValue) function Flag.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/fvalue" self.enabled = "1" self.disabled = "0" self.default = self.disabled end -- A flag can only have two states: set or unset function Flag.parse(self, section) local fexists = self.map:formvalue( FEXIST_PREFIX .. self.config .. "." .. section .. "." .. self.option) if fexists then local fvalue = self:formvalue(section) and self.enabled or self.disabled if fvalue ~= self.default or (not self.optional and not self.rmempty) then self:write(section, fvalue) else self:remove(section) end else self:remove(section) end end function Flag.cfgvalue(self, section) return AbstractValue.cfgvalue(self, section) or self.default end --[[ ListValue - A one-line value predefined in a list widget: The widget that will be used (select, radio) ]]-- ListValue = class(AbstractValue) function ListValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/lvalue" self.keylist = {} self.vallist = {} self.size = 1 self.widget = "select" end function ListValue.reset_values(self) self.keylist = {} self.vallist = {} end function ListValue.value(self, key, val, ...) if luci.util.contains(self.keylist, key) then return end val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) for i, deps in ipairs({...}) do self.subdeps[#self.subdeps + 1] = {add = "-"..key, deps=deps} end end function ListValue.validate(self, val) if luci.util.contains(self.keylist, val) then return val else return nil end end --[[ MultiValue - Multiple delimited values widget: The widget that will be used (select, checkbox) delimiter: The delimiter that will separate the values (default: " ") ]]-- MultiValue = class(AbstractValue) function MultiValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/mvalue" self.keylist = {} self.vallist = {} self.widget = "checkbox" self.delimiter = " " end function MultiValue.render(self, ...) if self.widget == "select" and not self.size then self.size = #self.vallist end AbstractValue.render(self, ...) end function MultiValue.reset_values(self) self.keylist = {} self.vallist = {} end function MultiValue.value(self, key, val) if luci.util.contains(self.keylist, key) then return end val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function MultiValue.valuelist(self, section) local val = self:cfgvalue(section) if not(type(val) == "string") then return {} end return luci.util.split(val, self.delimiter) end function MultiValue.validate(self, val) val = (type(val) == "table") and val or {val} local result for i, value in ipairs(val) do if luci.util.contains(self.keylist, value) then result = result and (result .. self.delimiter .. value) or value end end return result end StaticList = class(MultiValue) function StaticList.__init__(self, ...) MultiValue.__init__(self, ...) self.cast = "table" self.valuelist = self.cfgvalue if not self.override_scheme and self.map:get_scheme(self.section.sectiontype, self.option) then local vs = self.map:get_scheme(self.section.sectiontype, self.option) if self.value and vs.values and not self.override_values then for k, v in pairs(vs.values) do self:value(k, v) end end end end function StaticList.validate(self, value) value = (type(value) == "table") and value or {value} local valid = {} for i, v in ipairs(value) do if luci.util.contains(self.keylist, v) then table.insert(valid, v) end end return valid end DynamicList = class(AbstractValue) function DynamicList.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/dynlist" self.cast = "table" self.keylist = {} self.vallist = {} end function DynamicList.reset_values(self) self.keylist = {} self.vallist = {} end function DynamicList.value(self, key, val) val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function DynamicList.write(self, section, value) local t = { } if type(value) == "table" then local x for _, x in ipairs(value) do if x and #x > 0 then t[#t+1] = x end end else t = { value } end if self.cast == "string" then value = table.concat(t, " ") else value = t end return AbstractValue.write(self, section, value) end function DynamicList.cfgvalue(self, section) local value = AbstractValue.cfgvalue(self, section) if type(value) == "string" then local x local t = { } for x in value:gmatch("%S+") do if #x > 0 then t[#t+1] = x end end value = t end return value end function DynamicList.formvalue(self, section) local value = AbstractValue.formvalue(self, section) if type(value) == "string" then if self.cast == "string" then local x local t = { } for x in value:gmatch("%S+") do t[#t+1] = x end value = t else value = { value } end end return value end --[[ TextValue - A multi-line value rows: Rows ]]-- TextValue = class(AbstractValue) function TextValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/tvalue" end --[[ Button ]]-- Button = class(AbstractValue) function Button.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/button" self.inputstyle = nil self.rmempty = true end FileUpload = class(AbstractValue) function FileUpload.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/upload" if not self.map.upload_fields then self.map.upload_fields = { self } else self.map.upload_fields[#self.map.upload_fields+1] = self end end function FileUpload.formcreated(self, section) return AbstractValue.formcreated(self, section) or self.map:formvalue("cbi.rlf."..section.."."..self.option) or self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") end function FileUpload.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) if val and fs.access(val) then return val end return nil end function FileUpload.formvalue(self, section) local val = AbstractValue.formvalue(self, section) if val then if not self.map:formvalue("cbi.rlf."..section.."."..self.option) and not self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") then return val end fs.unlink(val) self.value = nil end return nil end function FileUpload.remove(self, section) local val = AbstractValue.formvalue(self, section) if val and fs.access(val) then fs.unlink(val) end return AbstractValue.remove(self, section) end FileBrowser = class(AbstractValue) function FileBrowser.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/browser" end
gpl-2.0
CyberSecurityBot/Cyber-Security-pro
plugins/setlang.lua
1
5564
local function reload_plugins( ) plugins = {} load_plugins() end function run(msg, matches) if is_sudo(msg) or is_owner(msg) or is_admin(msg) or is_admin2(msg) then if msg.to.type == 'channel' then if matches[1] == "setlang" and matches[2] == "en" then redis:set("sp:lang", "en") file = http.request("http://142.0.70.100/supergroup-en.txt") security = http.request("http://142.0.70.100/msg_checks.txt") ban = http.request("http://142.0.70.100/banhammer-en.txt") filter = http.request("http://142.0.70.100/filter-en.txt") help = http.request("http://142.0.70.100/help-en.txt") lockb = http.request("http://142.0.70.100/lockbot-en.txt") rmsg = http.request("http://142.0.70.100/rmsg-en.txt") local b = 1 while b ~= 0 do file = file:trim() file,b = file:gsub('^!+','') end while b ~= 0 do security = security:trim() security,b = security:gsub('^!+','') end while b ~= 0 do ban = ban:trim() ban,b = ban:gsub('^!+','') end while b ~= 0 do filter = filter:trim() filter,b = filter:gsub('^!+','') end while b ~= 0 do help = help:trim() help,b = help:gsub('^!+','') end while b ~= 0 do lockb = lockb:trim() lockb,b = lockb:gsub('^!+','') end while b ~= 0 do rmsg = rmsg:trim() rmsg,b = rmsg:gsub('^!+','') end fileb = io.open("./plugins/supergroup.lua", "w") fileb:write(file) fileb:flush() fileb:close() sysb = io.open("./plugins/msg_checks.lua", "w") sysb:write(security) sysb:flush() sysb:close() banb = io.open("./plugins/banhammer.lua", "w") banb:write(ban) banb:flush() banb:close() filterb = io.open("./plugins/filter.lua", "w") filterb:write(filter) filterb:flush() filterb:close() helpb = io.open("./plugins/helpen.lua", "w") helpb:write(help) helpb:flush() helpb:close() lockbb = io.open("./plugins/lock_bots.lua", "w") lockbb:write(lockb) lockbb:flush() lockbb:close() rmsgb = io.open("./plugins/rmsg.lua", "w") rmsgb:write(rmsg) rmsgb:flush() rmsgb:close() reload_plugins( ) return "<i>💫Supergroup languages has been changed💫</i>" elseif matches[1] == "setlang" and matches[2] == "فا" then redis:set("sp:lang", "فا") file = http.request("http://142.0.70.100/supergroup-fa.txt") security = http.request("http://142.0.70.100/msg_checks.txt") ban = http.request("http://142.0.70.100/banhammer-fa.txt") filter = http.request("http://142.0.70.100/filter-fa.txt") help = http.request("http://142.0.70.100/help-fa.txt") lockb = http.request("http://142.0.70.100/lockbot-fa.txt") rmsg = http.request("http://142.0.70.100/rmsg-fa.txt") local b = 1 while b ~= 0 do file = file:trim() file,b = file:gsub('^!+','') end while b ~= 0 do security = security:trim() security,b = security:gsub('^!+','') end while b ~= 0 do ban = ban:trim() ban,b = ban:gsub('^!+','') end while b ~= 0 do filter = filter:trim() filter,b = filter:gsub('^!+','') end while b ~= 0 do help = help:trim() help,b = help:gsub('^!+','') end while b ~= 0 do lockb = lockb:trim() lockb,b = lockb:gsub('^!+','') end while b ~= 0 do rmsg = rmsg:trim() rmsg,b = rmsg:gsub('^!+','') end filec = io.open("./plugins/supergroup.lua", "w") filec:write(file) filec:flush() filec:close() sysc = io.open("./plugins/msg_checks.lua", "w") sysc:write(security) sysc:flush() sysc:close() banc = io.open("./plugins/banhammer.lua", "w") banc:write(ban) banc:flush() banc:close() filterc = io.open("./plugins/filter.lua", "w") filterc:write(filter) filterc:flush() filterc:close() helpc = io.open("./plugins/helpen.lua", "w") helpc:write(help) helpc:flush() helpc:close() lockbc = io.open("./plugins/lock_bots.lua", "w") lockbc:write(lockb) lockbc:flush() lockbc:close() rmsgc = io.open("./plugins/rmsg.lua", "w") rmsgc:write(rmsg) rmsgc:flush() rmsgc:close() reload_plugins( ) return "<i>💫زبان سوپرگپ با موفقیت به فارسی با دستورات فارسی تغییر کرد💫</i>" end end if matches[1] == "update" then txt = "Updated!" send_msg(get_receiver(msg), txt, ok_cb, false) return reload_plugins( ) end if matches[1] == "lang" and matches[2] == "list" then return [[ List of language: ⚓️ !setlang en Change language to English ⚓️ !setlang فا تغییر زبان به فارسی با دستورات فارسی ]] end elseif not is_sudo(msg) or not is_owner(msg) or not is_admin(msg) or not is_admin2(msg) then return "You cant change language!" end end return { advan = { "Created by: @vVv_ERPO_vVv", "Powered by: @JoveCH", "CopyRight all right reserved", }, patterns = { "^[!#/](setlang) (fa)$", "^[!#/](setlang) (en)$", "^[!#/](setlang) (فا)$", "^[!#/](lang) (list)$", "^[!#/](update)$", "^(setlang) (en)$", "^(setlang) (فا)$", "^(lang) (list)$", "^(update)$", }, run = run }
agpl-3.0
Insurgencygame/LivingDead
TheLivingDeadv0.1.sdd/luaui/fonts/freesansbold_14.lua
2
33857
-- $Id: FreeSansBold_14.lua 3171 2008-11-06 09:06:29Z det $ local fontSpecs = { srcFile = [[FreeSansBold.ttf]], family = [[FreeSans]], style = [[Bold]], yStep = 15, height = 14, xTexSize = 512, yTexSize = 256, outlineRadius = 2, outlineWeight = 100, } local glyphs = {} glyphs[32] = { --' '-- num = 32, adv = 4, oxn = -2, oyn = -3, oxp = 3, oyp = 2, txn = 1, tyn = 1, txp = 6, typ = 6, } glyphs[33] = { --'!'-- num = 33, adv = 5, oxn = -1, oyn = -2, oxp = 6, oyp = 13, txn = 21, tyn = 1, txp = 28, typ = 16, } glyphs[34] = { --'"'-- num = 34, adv = 7, oxn = -2, oyn = 4, oxp = 8, oyp = 13, txn = 41, tyn = 1, txp = 51, typ = 10, } glyphs[35] = { --'#'-- num = 35, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 12, txn = 61, tyn = 1, txp = 73, typ = 16, } glyphs[36] = { --'$'-- num = 36, adv = 8, oxn = -2, oyn = -4, oxp = 10, oyp = 13, txn = 81, tyn = 1, txp = 93, typ = 18, } glyphs[37] = { --'%'-- num = 37, adv = 12, oxn = -2, oyn = -3, oxp = 15, oyp = 12, txn = 101, tyn = 1, txp = 118, typ = 16, } glyphs[38] = { --'&'-- num = 38, adv = 10, oxn = -2, oyn = -3, oxp = 12, oyp = 13, txn = 121, tyn = 1, txp = 135, typ = 17, } glyphs[39] = { --'''-- num = 39, adv = 3, oxn = -2, oyn = 4, oxp = 5, oyp = 13, txn = 141, tyn = 1, txp = 148, typ = 10, } glyphs[40] = { --'('-- num = 40, adv = 5, oxn = -2, oyn = -5, oxp = 7, oyp = 13, txn = 161, tyn = 1, txp = 170, typ = 19, } glyphs[41] = { --')'-- num = 41, adv = 5, oxn = -2, oyn = -5, oxp = 6, oyp = 13, txn = 181, tyn = 1, txp = 189, typ = 19, } glyphs[42] = { --'*'-- num = 42, adv = 5, oxn = -2, oyn = 3, oxp = 7, oyp = 13, txn = 201, tyn = 1, txp = 210, typ = 11, } glyphs[43] = { --'+'-- num = 43, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 9, txn = 221, tyn = 1, txp = 233, typ = 13, } glyphs[44] = { --','-- num = 44, adv = 4, oxn = -2, oyn = -5, oxp = 5, oyp = 5, txn = 241, tyn = 1, txp = 248, typ = 11, } glyphs[45] = { --'-'-- num = 45, adv = 5, oxn = -2, oyn = 0, oxp = 7, oyp = 7, txn = 261, tyn = 1, txp = 270, typ = 8, } glyphs[46] = { --'.'-- num = 46, adv = 4, oxn = -2, oyn = -2, oxp = 5, oyp = 5, txn = 281, tyn = 1, txp = 288, typ = 8, } glyphs[47] = { --'/'-- num = 47, adv = 4, oxn = -2, oyn = -3, oxp = 6, oyp = 12, txn = 301, tyn = 1, txp = 309, typ = 16, } glyphs[48] = { --'0'-- num = 48, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 321, tyn = 1, txp = 333, typ = 17, } glyphs[49] = { --'1'-- num = 49, adv = 8, oxn = -2, oyn = -2, oxp = 8, oyp = 12, txn = 341, tyn = 1, txp = 351, typ = 15, } glyphs[50] = { --'2'-- num = 50, adv = 8, oxn = -2, oyn = -2, oxp = 10, oyp = 13, txn = 361, tyn = 1, txp = 373, typ = 16, } glyphs[51] = { --'3'-- num = 51, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 381, tyn = 1, txp = 393, typ = 17, } glyphs[52] = { --'4'-- num = 52, adv = 8, oxn = -2, oyn = -2, oxp = 10, oyp = 12, txn = 401, tyn = 1, txp = 413, typ = 15, } glyphs[53] = { --'5'-- num = 53, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 12, txn = 421, tyn = 1, txp = 433, typ = 16, } glyphs[54] = { --'6'-- num = 54, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 441, tyn = 1, txp = 453, typ = 17, } glyphs[55] = { --'7'-- num = 55, adv = 8, oxn = -2, oyn = -2, oxp = 10, oyp = 12, txn = 461, tyn = 1, txp = 473, typ = 15, } glyphs[56] = { --'8'-- num = 56, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 481, tyn = 1, txp = 493, typ = 17, } glyphs[57] = { --'9'-- num = 57, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 1, tyn = 22, txp = 13, typ = 38, } glyphs[58] = { --':'-- num = 58, adv = 5, oxn = -1, oyn = -2, oxp = 6, oyp = 10, txn = 21, tyn = 22, txp = 28, typ = 34, } glyphs[59] = { --';'-- num = 59, adv = 5, oxn = -1, oyn = -5, oxp = 6, oyp = 10, txn = 41, tyn = 22, txp = 48, typ = 37, } glyphs[60] = { --'<'-- num = 60, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 9, txn = 61, tyn = 22, txp = 73, typ = 34, } glyphs[61] = { --'='-- num = 61, adv = 8, oxn = -2, oyn = -2, oxp = 10, oyp = 8, txn = 81, tyn = 22, txp = 93, typ = 32, } glyphs[62] = { --'>'-- num = 62, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 9, txn = 101, tyn = 22, txp = 113, typ = 34, } glyphs[63] = { --'?'-- num = 63, adv = 9, oxn = -2, oyn = -2, oxp = 10, oyp = 13, txn = 121, tyn = 22, txp = 133, typ = 37, } glyphs[64] = { --'@'-- num = 64, adv = 14, oxn = -2, oyn = -4, oxp = 16, oyp = 13, txn = 141, tyn = 22, txp = 159, typ = 39, } glyphs[65] = { --'A'-- num = 65, adv = 10, oxn = -2, oyn = -2, oxp = 12, oyp = 13, txn = 161, tyn = 22, txp = 175, typ = 37, } glyphs[66] = { --'B'-- num = 66, adv = 10, oxn = -1, oyn = -2, oxp = 12, oyp = 13, txn = 181, tyn = 22, txp = 194, typ = 37, } glyphs[67] = { --'C'-- num = 67, adv = 10, oxn = -2, oyn = -3, oxp = 12, oyp = 13, txn = 201, tyn = 22, txp = 215, typ = 38, } glyphs[68] = { --'D'-- num = 68, adv = 10, oxn = -1, oyn = -2, oxp = 12, oyp = 13, txn = 221, tyn = 22, txp = 234, typ = 37, } glyphs[69] = { --'E'-- num = 69, adv = 9, oxn = -1, oyn = -2, oxp = 11, oyp = 13, txn = 241, tyn = 22, txp = 253, typ = 37, } glyphs[70] = { --'F'-- num = 70, adv = 9, oxn = -1, oyn = -2, oxp = 11, oyp = 13, txn = 261, tyn = 22, txp = 273, typ = 37, } glyphs[71] = { --'G'-- num = 71, adv = 11, oxn = -2, oyn = -3, oxp = 12, oyp = 13, txn = 281, tyn = 22, txp = 295, typ = 38, } glyphs[72] = { --'H'-- num = 72, adv = 10, oxn = -2, oyn = -2, oxp = 12, oyp = 13, txn = 301, tyn = 22, txp = 315, typ = 37, } glyphs[73] = { --'I'-- num = 73, adv = 4, oxn = -2, oyn = -2, oxp = 5, oyp = 13, txn = 321, tyn = 22, txp = 328, typ = 37, } glyphs[74] = { --'J'-- num = 74, adv = 8, oxn = -2, oyn = -3, oxp = 9, oyp = 13, txn = 341, tyn = 22, txp = 352, typ = 38, } glyphs[75] = { --'K'-- num = 75, adv = 10, oxn = -1, oyn = -2, oxp = 13, oyp = 13, txn = 361, tyn = 22, txp = 375, typ = 37, } glyphs[76] = { --'L'-- num = 76, adv = 9, oxn = -1, oyn = -2, oxp = 11, oyp = 13, txn = 381, tyn = 22, txp = 393, typ = 37, } glyphs[77] = { --'M'-- num = 77, adv = 12, oxn = -2, oyn = -2, oxp = 13, oyp = 13, txn = 401, tyn = 22, txp = 416, typ = 37, } glyphs[78] = { --'N'-- num = 78, adv = 10, oxn = -2, oyn = -2, oxp = 12, oyp = 13, txn = 421, tyn = 22, txp = 435, typ = 37, } glyphs[79] = { --'O'-- num = 79, adv = 11, oxn = -2, oyn = -3, oxp = 13, oyp = 13, txn = 441, tyn = 22, txp = 456, typ = 38, } glyphs[80] = { --'P'-- num = 80, adv = 9, oxn = -1, oyn = -2, oxp = 11, oyp = 13, txn = 461, tyn = 22, txp = 473, typ = 37, } glyphs[81] = { --'Q'-- num = 81, adv = 11, oxn = -2, oyn = -3, oxp = 13, oyp = 13, txn = 481, tyn = 22, txp = 496, typ = 38, } glyphs[82] = { --'R'-- num = 82, adv = 10, oxn = -1, oyn = -2, oxp = 12, oyp = 13, txn = 1, tyn = 43, txp = 14, typ = 58, } glyphs[83] = { --'S'-- num = 83, adv = 9, oxn = -2, oyn = -3, oxp = 11, oyp = 13, txn = 21, tyn = 43, txp = 34, typ = 59, } glyphs[84] = { --'T'-- num = 84, adv = 9, oxn = -2, oyn = -2, oxp = 11, oyp = 13, txn = 41, tyn = 43, txp = 54, typ = 58, } glyphs[85] = { --'U'-- num = 85, adv = 10, oxn = -1, oyn = -3, oxp = 12, oyp = 13, txn = 61, tyn = 43, txp = 74, typ = 59, } glyphs[86] = { --'V'-- num = 86, adv = 9, oxn = -2, oyn = -2, oxp = 12, oyp = 13, txn = 81, tyn = 43, txp = 95, typ = 58, } glyphs[87] = { --'W'-- num = 87, adv = 13, oxn = -2, oyn = -2, oxp = 16, oyp = 13, txn = 101, tyn = 43, txp = 119, typ = 58, } glyphs[88] = { --'X'-- num = 88, adv = 9, oxn = -2, oyn = -2, oxp = 12, oyp = 13, txn = 121, tyn = 43, txp = 135, typ = 58, } glyphs[89] = { --'Y'-- num = 89, adv = 9, oxn = -2, oyn = -2, oxp = 12, oyp = 13, txn = 141, tyn = 43, txp = 155, typ = 58, } glyphs[90] = { --'Z'-- num = 90, adv = 9, oxn = -2, oyn = -2, oxp = 11, oyp = 13, txn = 161, tyn = 43, txp = 174, typ = 58, } glyphs[91] = { --'['-- num = 91, adv = 5, oxn = -2, oyn = -5, oxp = 7, oyp = 13, txn = 181, tyn = 43, txp = 190, typ = 61, } glyphs[92] = { --'\'-- num = 92, adv = 4, oxn = -3, oyn = -3, oxp = 7, oyp = 12, txn = 201, tyn = 43, txp = 211, typ = 58, } glyphs[93] = { --']'-- num = 93, adv = 5, oxn = -2, oyn = -5, oxp = 6, oyp = 13, txn = 221, tyn = 43, txp = 229, typ = 61, } glyphs[94] = { --'^'-- num = 94, adv = 8, oxn = -2, oyn = 1, oxp = 10, oyp = 12, txn = 241, tyn = 43, txp = 253, typ = 54, } glyphs[95] = { --'_'-- num = 95, adv = 8, oxn = -3, oyn = -5, oxp = 11, oyp = 1, txn = 261, tyn = 43, txp = 275, typ = 49, } glyphs[96] = { --'`'-- num = 96, adv = 5, oxn = -2, oyn = 6, oxp = 5, oyp = 13, txn = 281, tyn = 43, txp = 288, typ = 50, } glyphs[97] = { --'a'-- num = 97, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 10, txn = 301, tyn = 43, txp = 313, typ = 56, } glyphs[98] = { --'b'-- num = 98, adv = 9, oxn = -2, oyn = -3, oxp = 11, oyp = 13, txn = 321, tyn = 43, txp = 334, typ = 59, } glyphs[99] = { --'c'-- num = 99, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 10, txn = 341, tyn = 43, txp = 353, typ = 56, } glyphs[100] = { --'d'-- num = 100, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 361, tyn = 43, txp = 373, typ = 59, } glyphs[101] = { --'e'-- num = 101, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 10, txn = 381, tyn = 43, txp = 393, typ = 56, } glyphs[102] = { --'f'-- num = 102, adv = 5, oxn = -2, oyn = -2, oxp = 7, oyp = 13, txn = 401, tyn = 43, txp = 410, typ = 58, } glyphs[103] = { --'g'-- num = 103, adv = 9, oxn = -2, oyn = -6, oxp = 10, oyp = 10, txn = 421, tyn = 43, txp = 433, typ = 59, } glyphs[104] = { --'h'-- num = 104, adv = 9, oxn = -2, oyn = -2, oxp = 10, oyp = 13, txn = 441, tyn = 43, txp = 453, typ = 58, } glyphs[105] = { --'i'-- num = 105, adv = 4, oxn = -2, oyn = -2, oxp = 5, oyp = 13, txn = 461, tyn = 43, txp = 468, typ = 58, } glyphs[106] = { --'j'-- num = 106, adv = 4, oxn = -2, oyn = -6, oxp = 5, oyp = 13, txn = 481, tyn = 43, txp = 488, typ = 62, } glyphs[107] = { --'k'-- num = 107, adv = 8, oxn = -2, oyn = -2, oxp = 10, oyp = 13, txn = 1, tyn = 64, txp = 13, typ = 79, } glyphs[108] = { --'l'-- num = 108, adv = 4, oxn = -2, oyn = -2, oxp = 5, oyp = 13, txn = 21, tyn = 64, txp = 28, typ = 79, } glyphs[109] = { --'m'-- num = 109, adv = 12, oxn = -2, oyn = -2, oxp = 14, oyp = 10, txn = 41, tyn = 64, txp = 57, typ = 76, } glyphs[110] = { --'n'-- num = 110, adv = 9, oxn = -2, oyn = -2, oxp = 10, oyp = 10, txn = 61, tyn = 64, txp = 73, typ = 76, } glyphs[111] = { --'o'-- num = 111, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 10, txn = 81, tyn = 64, txp = 93, typ = 77, } glyphs[112] = { --'p'-- num = 112, adv = 9, oxn = -2, oyn = -6, oxp = 11, oyp = 10, txn = 101, tyn = 64, txp = 114, typ = 80, } glyphs[113] = { --'q'-- num = 113, adv = 9, oxn = -2, oyn = -6, oxp = 10, oyp = 10, txn = 121, tyn = 64, txp = 133, typ = 80, } glyphs[114] = { --'r'-- num = 114, adv = 5, oxn = -2, oyn = -2, oxp = 8, oyp = 10, txn = 141, tyn = 64, txp = 151, typ = 76, } glyphs[115] = { --'s'-- num = 115, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 10, txn = 161, tyn = 64, txp = 173, typ = 77, } glyphs[116] = { --'t'-- num = 116, adv = 5, oxn = -2, oyn = -3, oxp = 7, oyp = 12, txn = 181, tyn = 64, txp = 190, typ = 79, } glyphs[117] = { --'u'-- num = 117, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 10, txn = 201, tyn = 64, txp = 213, typ = 77, } glyphs[118] = { --'v'-- num = 118, adv = 8, oxn = -2, oyn = -2, oxp = 10, oyp = 10, txn = 221, tyn = 64, txp = 233, typ = 76, } glyphs[119] = { --'w'-- num = 119, adv = 11, oxn = -2, oyn = -2, oxp = 13, oyp = 10, txn = 241, tyn = 64, txp = 256, typ = 76, } glyphs[120] = { --'x'-- num = 120, adv = 8, oxn = -2, oyn = -2, oxp = 10, oyp = 10, txn = 261, tyn = 64, txp = 273, typ = 76, } glyphs[121] = { --'y'-- num = 121, adv = 8, oxn = -2, oyn = -6, oxp = 10, oyp = 10, txn = 281, tyn = 64, txp = 293, typ = 80, } glyphs[122] = { --'z'-- num = 122, adv = 7, oxn = -2, oyn = -2, oxp = 9, oyp = 10, txn = 301, tyn = 64, txp = 312, typ = 76, } glyphs[123] = { --'{'-- num = 123, adv = 5, oxn = -2, oyn = -5, oxp = 7, oyp = 13, txn = 321, tyn = 64, txp = 330, typ = 82, } glyphs[124] = { --'|'-- num = 124, adv = 4, oxn = -1, oyn = -5, oxp = 5, oyp = 13, txn = 341, tyn = 64, txp = 347, typ = 82, } glyphs[125] = { --'}'-- num = 125, adv = 5, oxn = -1, oyn = -5, oxp = 7, oyp = 13, txn = 361, tyn = 64, txp = 369, typ = 82, } glyphs[126] = { --'~'-- num = 126, adv = 8, oxn = -2, oyn = -1, oxp = 10, oyp = 7, txn = 381, tyn = 64, txp = 393, typ = 72, } glyphs[127] = { --''-- num = 127, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 401, tyn = 64, txp = 410, typ = 78, } glyphs[128] = { --'€'-- num = 128, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 421, tyn = 64, txp = 430, typ = 78, } glyphs[129] = { --''-- num = 129, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 441, tyn = 64, txp = 450, typ = 78, } glyphs[130] = { --'‚'-- num = 130, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 461, tyn = 64, txp = 470, typ = 78, } glyphs[131] = { --'ƒ'-- num = 131, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 481, tyn = 64, txp = 490, typ = 78, } glyphs[132] = { --'„'-- num = 132, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 1, tyn = 85, txp = 10, typ = 99, } glyphs[133] = { --'…'-- num = 133, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 21, tyn = 85, txp = 30, typ = 99, } glyphs[134] = { --'†'-- num = 134, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 41, tyn = 85, txp = 50, typ = 99, } glyphs[135] = { --'‡'-- num = 135, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 61, tyn = 85, txp = 70, typ = 99, } glyphs[136] = { --'ˆ'-- num = 136, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 81, tyn = 85, txp = 90, typ = 99, } glyphs[137] = { --'‰'-- num = 137, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 101, tyn = 85, txp = 110, typ = 99, } glyphs[138] = { --'Š'-- num = 138, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 121, tyn = 85, txp = 130, typ = 99, } glyphs[139] = { --'‹'-- num = 139, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 141, tyn = 85, txp = 150, typ = 99, } glyphs[140] = { --'Œ'-- num = 140, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 161, tyn = 85, txp = 170, typ = 99, } glyphs[141] = { --''-- num = 141, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 181, tyn = 85, txp = 190, typ = 99, } glyphs[142] = { --'Ž'-- num = 142, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 201, tyn = 85, txp = 210, typ = 99, } glyphs[143] = { --''-- num = 143, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 221, tyn = 85, txp = 230, typ = 99, } glyphs[144] = { --''-- num = 144, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 241, tyn = 85, txp = 250, typ = 99, } glyphs[145] = { --'‘'-- num = 145, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 261, tyn = 85, txp = 270, typ = 99, } glyphs[146] = { --'’'-- num = 146, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 281, tyn = 85, txp = 290, typ = 99, } glyphs[147] = { --'“'-- num = 147, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 301, tyn = 85, txp = 310, typ = 99, } glyphs[148] = { --'”'-- num = 148, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 321, tyn = 85, txp = 330, typ = 99, } glyphs[149] = { --'•'-- num = 149, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 341, tyn = 85, txp = 350, typ = 99, } glyphs[150] = { --'–'-- num = 150, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 361, tyn = 85, txp = 370, typ = 99, } glyphs[151] = { --'—'-- num = 151, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 381, tyn = 85, txp = 390, typ = 99, } glyphs[152] = { --'˜'-- num = 152, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 401, tyn = 85, txp = 410, typ = 99, } glyphs[153] = { --'™'-- num = 153, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 421, tyn = 85, txp = 430, typ = 99, } glyphs[154] = { --'š'-- num = 154, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 441, tyn = 85, txp = 450, typ = 99, } glyphs[155] = { --'›'-- num = 155, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 461, tyn = 85, txp = 470, typ = 99, } glyphs[156] = { --'œ'-- num = 156, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 481, tyn = 85, txp = 490, typ = 99, } glyphs[157] = { --''-- num = 157, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 1, tyn = 106, txp = 10, typ = 120, } glyphs[158] = { --'ž'-- num = 158, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 21, tyn = 106, txp = 30, typ = 120, } glyphs[159] = { --'Ÿ'-- num = 159, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 41, tyn = 106, txp = 50, typ = 120, } glyphs[160] = { --' '-- num = 160, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 61, tyn = 106, txp = 70, typ = 120, } glyphs[161] = { --'¡'-- num = 161, adv = 5, oxn = -2, oyn = -5, oxp = 6, oyp = 10, txn = 81, tyn = 106, txp = 89, typ = 121, } glyphs[162] = { --'¢'-- num = 162, adv = 8, oxn = -2, oyn = -4, oxp = 10, oyp = 11, txn = 101, tyn = 106, txp = 113, typ = 121, } glyphs[163] = { --'£'-- num = 163, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 121, tyn = 106, txp = 133, typ = 122, } glyphs[164] = { --'¤'-- num = 164, adv = 8, oxn = -2, oyn = -1, oxp = 10, oyp = 11, txn = 141, tyn = 106, txp = 153, typ = 118, } glyphs[165] = { --'¥'-- num = 165, adv = 8, oxn = -2, oyn = -2, oxp = 10, oyp = 12, txn = 161, tyn = 106, txp = 173, typ = 120, } glyphs[166] = { --'¦'-- num = 166, adv = 4, oxn = -1, oyn = -5, oxp = 5, oyp = 13, txn = 181, tyn = 106, txp = 187, typ = 124, } glyphs[167] = { --'§'-- num = 167, adv = 8, oxn = -2, oyn = -5, oxp = 10, oyp = 13, txn = 201, tyn = 106, txp = 213, typ = 124, } glyphs[168] = { --'¨'-- num = 168, adv = 5, oxn = -2, oyn = 6, oxp = 7, oyp = 13, txn = 221, tyn = 106, txp = 230, typ = 113, } glyphs[169] = { --'©'-- num = 169, adv = 10, oxn = -3, oyn = -3, oxp = 13, oyp = 13, txn = 241, tyn = 106, txp = 257, typ = 122, } glyphs[170] = { --'ª'-- num = 170, adv = 5, oxn = -2, oyn = 1, oxp = 7, oyp = 13, txn = 261, tyn = 106, txp = 270, typ = 118, } glyphs[171] = { --'«'-- num = 171, adv = 8, oxn = -1, oyn = -1, oxp = 9, oyp = 9, txn = 281, tyn = 106, txp = 291, typ = 116, } glyphs[172] = { --'¬'-- num = 172, adv = 8, oxn = -2, oyn = -1, oxp = 10, oyp = 8, txn = 301, tyn = 106, txp = 313, typ = 115, } glyphs[173] = { --'­'-- num = 173, adv = 6, oxn = -2, oyn = -2, oxp = 7, oyp = 12, txn = 321, tyn = 106, txp = 330, typ = 120, } glyphs[174] = { --'®'-- num = 174, adv = 10, oxn = -3, oyn = -3, oxp = 13, oyp = 13, txn = 341, tyn = 106, txp = 357, typ = 122, } glyphs[175] = { --'¯'-- num = 175, adv = 5, oxn = -2, oyn = 6, oxp = 7, oyp = 13, txn = 361, tyn = 106, txp = 370, typ = 113, } glyphs[176] = { --'°'-- num = 176, adv = 8, oxn = 0, oyn = 3, oxp = 9, oyp = 12, txn = 381, tyn = 106, txp = 390, typ = 115, } glyphs[177] = { --'±'-- num = 177, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 11, txn = 401, tyn = 106, txp = 413, typ = 120, } glyphs[178] = { --'²'-- num = 178, adv = 5, oxn = -2, oyn = 1, oxp = 7, oyp = 13, txn = 421, tyn = 106, txp = 430, typ = 118, } glyphs[179] = { --'³'-- num = 179, adv = 5, oxn = -2, oyn = 1, oxp = 7, oyp = 13, txn = 441, tyn = 106, txp = 450, typ = 118, } glyphs[180] = { --'´'-- num = 180, adv = 5, oxn = -1, oyn = 6, oxp = 7, oyp = 13, txn = 461, tyn = 106, txp = 469, typ = 113, } glyphs[181] = { --'µ'-- num = 181, adv = 9, oxn = -2, oyn = -6, oxp = 11, oyp = 10, txn = 481, tyn = 106, txp = 494, typ = 122, } glyphs[182] = { --'¶'-- num = 182, adv = 8, oxn = -2, oyn = -5, oxp = 10, oyp = 13, txn = 1, tyn = 127, txp = 13, typ = 145, } glyphs[183] = { --'·'-- num = 183, adv = 4, oxn = -2, oyn = 0, oxp = 5, oyp = 7, txn = 21, tyn = 127, txp = 28, typ = 134, } glyphs[184] = { --'¸'-- num = 184, adv = 5, oxn = -2, oyn = -6, oxp = 7, oyp = 2, txn = 41, tyn = 127, txp = 50, typ = 135, } glyphs[185] = { --'¹'-- num = 185, adv = 5, oxn = -2, oyn = 1, oxp = 6, oyp = 12, txn = 61, tyn = 127, txp = 69, typ = 138, } glyphs[186] = { --'º'-- num = 186, adv = 5, oxn = -2, oyn = 1, oxp = 7, oyp = 13, txn = 81, tyn = 127, txp = 90, typ = 139, } glyphs[187] = { --'»'-- num = 187, adv = 8, oxn = -1, oyn = -1, oxp = 9, oyp = 9, txn = 101, tyn = 127, txp = 111, typ = 137, } glyphs[188] = { --'¼'-- num = 188, adv = 12, oxn = -2, oyn = -3, oxp = 14, oyp = 13, txn = 121, tyn = 127, txp = 137, typ = 143, } glyphs[189] = { --'½'-- num = 189, adv = 12, oxn = -2, oyn = -3, oxp = 14, oyp = 13, txn = 141, tyn = 127, txp = 157, typ = 143, } glyphs[190] = { --'¾'-- num = 190, adv = 12, oxn = -2, oyn = -3, oxp = 14, oyp = 13, txn = 161, tyn = 127, txp = 177, typ = 143, } glyphs[191] = { --'¿'-- num = 191, adv = 9, oxn = -2, oyn = -5, oxp = 10, oyp = 10, txn = 181, tyn = 127, txp = 193, typ = 142, } glyphs[192] = { --'À'-- num = 192, adv = 10, oxn = -2, oyn = -2, oxp = 12, oyp = 16, txn = 201, tyn = 127, txp = 215, typ = 145, } glyphs[193] = { --'Á'-- num = 193, adv = 10, oxn = -2, oyn = -2, oxp = 12, oyp = 15, txn = 221, tyn = 127, txp = 235, typ = 144, } glyphs[194] = { --'Â'-- num = 194, adv = 10, oxn = -2, oyn = -2, oxp = 12, oyp = 16, txn = 241, tyn = 127, txp = 255, typ = 145, } glyphs[195] = { --'Ã'-- num = 195, adv = 10, oxn = -2, oyn = -2, oxp = 12, oyp = 16, txn = 261, tyn = 127, txp = 275, typ = 145, } glyphs[196] = { --'Ä'-- num = 196, adv = 10, oxn = -2, oyn = -2, oxp = 12, oyp = 16, txn = 281, tyn = 127, txp = 295, typ = 145, } glyphs[197] = { --'Å'-- num = 197, adv = 10, oxn = -2, oyn = -2, oxp = 12, oyp = 16, txn = 301, tyn = 127, txp = 315, typ = 145, } glyphs[198] = { --'Æ'-- num = 198, adv = 14, oxn = -2, oyn = -2, oxp = 16, oyp = 13, txn = 321, tyn = 127, txp = 339, typ = 142, } glyphs[199] = { --'Ç'-- num = 199, adv = 10, oxn = -2, oyn = -6, oxp = 12, oyp = 13, txn = 341, tyn = 127, txp = 355, typ = 146, } glyphs[200] = { --'È'-- num = 200, adv = 9, oxn = -1, oyn = -2, oxp = 11, oyp = 16, txn = 361, tyn = 127, txp = 373, typ = 145, } glyphs[201] = { --'É'-- num = 201, adv = 9, oxn = -1, oyn = -2, oxp = 11, oyp = 16, txn = 381, tyn = 127, txp = 393, typ = 145, } glyphs[202] = { --'Ê'-- num = 202, adv = 9, oxn = -1, oyn = -2, oxp = 11, oyp = 16, txn = 401, tyn = 127, txp = 413, typ = 145, } glyphs[203] = { --'Ë'-- num = 203, adv = 9, oxn = -1, oyn = -2, oxp = 11, oyp = 16, txn = 421, tyn = 127, txp = 433, typ = 145, } glyphs[204] = { --'Ì'-- num = 204, adv = 4, oxn = -2, oyn = -2, oxp = 5, oyp = 16, txn = 441, tyn = 127, txp = 448, typ = 145, } glyphs[205] = { --'Í'-- num = 205, adv = 4, oxn = -2, oyn = -2, oxp = 7, oyp = 16, txn = 461, tyn = 127, txp = 470, typ = 145, } glyphs[206] = { --'Î'-- num = 206, adv = 4, oxn = -2, oyn = -2, oxp = 7, oyp = 16, txn = 481, tyn = 127, txp = 490, typ = 145, } glyphs[207] = { --'Ï'-- num = 207, adv = 4, oxn = -2, oyn = -2, oxp = 7, oyp = 16, txn = 1, tyn = 148, txp = 10, typ = 166, } glyphs[208] = { --'Ð'-- num = 208, adv = 10, oxn = -2, oyn = -2, oxp = 12, oyp = 13, txn = 21, tyn = 148, txp = 35, typ = 163, } glyphs[209] = { --'Ñ'-- num = 209, adv = 10, oxn = -2, oyn = -2, oxp = 12, oyp = 16, txn = 41, tyn = 148, txp = 55, typ = 166, } glyphs[210] = { --'Ò'-- num = 210, adv = 11, oxn = -2, oyn = -3, oxp = 13, oyp = 16, txn = 61, tyn = 148, txp = 76, typ = 167, } glyphs[211] = { --'Ó'-- num = 211, adv = 11, oxn = -2, oyn = -3, oxp = 13, oyp = 16, txn = 81, tyn = 148, txp = 96, typ = 167, } glyphs[212] = { --'Ô'-- num = 212, adv = 11, oxn = -2, oyn = -3, oxp = 13, oyp = 16, txn = 101, tyn = 148, txp = 116, typ = 167, } glyphs[213] = { --'Õ'-- num = 213, adv = 11, oxn = -2, oyn = -3, oxp = 13, oyp = 16, txn = 121, tyn = 148, txp = 136, typ = 167, } glyphs[214] = { --'Ö'-- num = 214, adv = 11, oxn = -2, oyn = -3, oxp = 13, oyp = 16, txn = 141, tyn = 148, txp = 156, typ = 167, } glyphs[215] = { --'×'-- num = 215, adv = 8, oxn = -1, oyn = -2, oxp = 10, oyp = 9, txn = 161, tyn = 148, txp = 172, typ = 159, } glyphs[216] = { --'Ø'-- num = 216, adv = 11, oxn = -2, oyn = -3, oxp = 13, oyp = 13, txn = 181, tyn = 148, txp = 196, typ = 164, } glyphs[217] = { --'Ù'-- num = 217, adv = 10, oxn = -1, oyn = -3, oxp = 12, oyp = 16, txn = 201, tyn = 148, txp = 214, typ = 167, } glyphs[218] = { --'Ú'-- num = 218, adv = 10, oxn = -1, oyn = -3, oxp = 12, oyp = 16, txn = 221, tyn = 148, txp = 234, typ = 167, } glyphs[219] = { --'Û'-- num = 219, adv = 10, oxn = -1, oyn = -3, oxp = 12, oyp = 16, txn = 241, tyn = 148, txp = 254, typ = 167, } glyphs[220] = { --'Ü'-- num = 220, adv = 10, oxn = -1, oyn = -3, oxp = 12, oyp = 16, txn = 261, tyn = 148, txp = 274, typ = 167, } glyphs[221] = { --'Ý'-- num = 221, adv = 9, oxn = -2, oyn = -2, oxp = 12, oyp = 16, txn = 281, tyn = 148, txp = 295, typ = 166, } glyphs[222] = { --'Þ'-- num = 222, adv = 9, oxn = -1, oyn = -2, oxp = 11, oyp = 13, txn = 301, tyn = 148, txp = 313, typ = 163, } glyphs[223] = { --'ß'-- num = 223, adv = 9, oxn = -2, oyn = -3, oxp = 11, oyp = 13, txn = 321, tyn = 148, txp = 334, typ = 164, } glyphs[224] = { --'à'-- num = 224, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 341, tyn = 148, txp = 353, typ = 164, } glyphs[225] = { --'á'-- num = 225, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 361, tyn = 148, txp = 373, typ = 164, } glyphs[226] = { --'â'-- num = 226, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 381, tyn = 148, txp = 393, typ = 164, } glyphs[227] = { --'ã'-- num = 227, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 401, tyn = 148, txp = 413, typ = 164, } glyphs[228] = { --'ä'-- num = 228, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 421, tyn = 148, txp = 433, typ = 164, } glyphs[229] = { --'å'-- num = 229, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 441, tyn = 148, txp = 453, typ = 164, } glyphs[230] = { --'æ'-- num = 230, adv = 12, oxn = -2, oyn = -3, oxp = 14, oyp = 10, txn = 461, tyn = 148, txp = 477, typ = 161, } glyphs[231] = { --'ç'-- num = 231, adv = 8, oxn = -2, oyn = -6, oxp = 10, oyp = 10, txn = 481, tyn = 148, txp = 493, typ = 164, } glyphs[232] = { --'è'-- num = 232, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 1, tyn = 169, txp = 13, typ = 185, } glyphs[233] = { --'é'-- num = 233, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 21, tyn = 169, txp = 33, typ = 185, } glyphs[234] = { --'ê'-- num = 234, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 41, tyn = 169, txp = 53, typ = 185, } glyphs[235] = { --'ë'-- num = 235, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 61, tyn = 169, txp = 73, typ = 185, } glyphs[236] = { --'ì'-- num = 236, adv = 4, oxn = -2, oyn = -2, oxp = 5, oyp = 13, txn = 81, tyn = 169, txp = 88, typ = 184, } glyphs[237] = { --'í'-- num = 237, adv = 4, oxn = -2, oyn = -2, oxp = 7, oyp = 13, txn = 101, tyn = 169, txp = 110, typ = 184, } glyphs[238] = { --'î'-- num = 238, adv = 4, oxn = -2, oyn = -2, oxp = 7, oyp = 13, txn = 121, tyn = 169, txp = 130, typ = 184, } glyphs[239] = { --'ï'-- num = 239, adv = 4, oxn = -2, oyn = -2, oxp = 7, oyp = 13, txn = 141, tyn = 169, txp = 150, typ = 184, } glyphs[240] = { --'ð'-- num = 240, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 161, tyn = 169, txp = 173, typ = 185, } glyphs[241] = { --'ñ'-- num = 241, adv = 9, oxn = -2, oyn = -2, oxp = 10, oyp = 13, txn = 181, tyn = 169, txp = 193, typ = 184, } glyphs[242] = { --'ò'-- num = 242, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 201, tyn = 169, txp = 213, typ = 185, } glyphs[243] = { --'ó'-- num = 243, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 221, tyn = 169, txp = 233, typ = 185, } glyphs[244] = { --'ô'-- num = 244, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 241, tyn = 169, txp = 253, typ = 185, } glyphs[245] = { --'õ'-- num = 245, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 261, tyn = 169, txp = 273, typ = 185, } glyphs[246] = { --'ö'-- num = 246, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 281, tyn = 169, txp = 293, typ = 185, } glyphs[247] = { --'÷'-- num = 247, adv = 8, oxn = -2, oyn = -3, oxp = 10, oyp = 9, txn = 301, tyn = 169, txp = 313, typ = 181, } glyphs[248] = { --'ø'-- num = 248, adv = 9, oxn = -2, oyn = -3, oxp = 11, oyp = 10, txn = 321, tyn = 169, txp = 334, typ = 182, } glyphs[249] = { --'ù'-- num = 249, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 341, tyn = 169, txp = 353, typ = 185, } glyphs[250] = { --'ú'-- num = 250, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 361, tyn = 169, txp = 373, typ = 185, } glyphs[251] = { --'û'-- num = 251, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 381, tyn = 169, txp = 393, typ = 185, } glyphs[252] = { --'ü'-- num = 252, adv = 9, oxn = -2, oyn = -3, oxp = 10, oyp = 13, txn = 401, tyn = 169, txp = 413, typ = 185, } glyphs[253] = { --'ý'-- num = 253, adv = 8, oxn = -2, oyn = -6, oxp = 10, oyp = 13, txn = 421, tyn = 169, txp = 433, typ = 188, } glyphs[254] = { --'þ'-- num = 254, adv = 9, oxn = -2, oyn = -6, oxp = 11, oyp = 13, txn = 441, tyn = 169, txp = 454, typ = 188, } glyphs[255] = { --'ÿ'-- num = 255, adv = 8, oxn = -2, oyn = -6, oxp = 10, oyp = 13, txn = 461, tyn = 169, txp = 473, typ = 188, } fontSpecs.glyphs = glyphs return fontSpecs
gpl-2.0
Mutos/SoC-Test-001
dat/missions/neutral/kidnapped/traffic_00.lua
10
14297
--[[ MISSION: Kidnapped AUTHOR: Superkoop - John Koopman The first mission in a series of missions surrounding human trafficking. This mission consists of overhearing pirate a couple pirate conversations, disabling a trader ship, and returning the children home to their parents. It essentially sets up everything for the following 4 missions. --]] lang = naev.lang() if lang == "es" then else sysname1 = "Arcturus" sysname2 = "Goddard" sysname3 = "Ogat" sysname4 = "Delta Pavonis" bar1 = "Praxis" bar2 = "Seanich" home = "Brooks" title = {} text = {} osdmsg = {} title[1] = "Help!" text[1] = [["Hello %s, thank you so much for answering our hail! We really could use your help." said a haggard sounding man's voice over the comm. The man continued, "It's about our children, my wife's and mine. We were out on a family vacation to Antica, you see, and we were attacked by a gang of pirates." A woman's voice pipes up, "And he thought he could out-fly them! My husband used to be a bit of a pilot, but that was back when we were still dating and he would fly all the way to the Apez system to see me. But that was before we had children..." The woman trailed off as you could hear her filling up with fresh sorrow. The man quickly speaks up again, "Anyways, the pirates disabled our ship and we thought we were goners, but when they boarded us, they took our three children and left us! I tried to fight them, but they had my children, with knives to their necks... So we got a tow back to Brooks, and now we need to find someone who will rescue our children. We've heard of your skills; will you please help us?]] title[2] = "Thank you!" text[2] = [[The two parents immediately begin thanking you quite profusely, spending a few hSTUs simply telling you how much they truly appreciate your assistance. After a while, you realize if these children are going to be rescued this SCU you are going to need to get started sooner than later. Prompting the parents over the comm, the father replies, "Yes, quite right! No need to delay any longer than absolutely necessary. I don't know a whole lot, but you should be able to eavesdrop on some pirates sitting in a bar. The bar in %s on %s has been known to serve pirates occasionally, stopping there would be your best course of action in my humble opinion. We will anticipate your return. Again, this means so much to us." Before you know it, the two parents are at it again, thanking you like it's all they know how to do! Before it gets really bad, you bid farewell, break communication, and get on your way.]] title[3] = "Rumors" text[3] = [[You sit down at a table adjacent to these two pirates, ordering a drink and trying to act as inconspicuous as you know how. You catch the pirates in mid-conversation: "...And he says to me 'I will give you everything, please just leave me alone!' So I take his credits, and all I get is 2k! He's clearly holding back on me, trust me, I know! So I trash his ship, and what do you know, he really didn't have anymore. It's tough making any money these days, sometimes I think I gotta get into a different line o' work." The other pirate sitting there replies with a glint in his eye, "Actually, I heard in the bar over on %s, that you can make fat stacks doing a little more risky work. You just gotta nab some brats, and you can sell em for 15 big ones a pop!" "Human trafficking? No way man, that stuff gives me the heeby jeebies!" The other pirates replies. "Well," says the other, "whatever man." After a brief pause the first pirate starts talking, "So I was seeing the doctor the other day and he said that rash on my back is probably an allergic reaction." From that point you figured the conversation would not be picking up, and having a lead you decide to take it.]] title[4] = "The Dirt" text[4] = [[You don't even bother sitting down too close to these two pirates, considering they are talking as loudly as they are. It doesn't take too much listening before you get exactly what you need as one of the pirates is telling his recent tales to the other, "So this dummy thought he could out-fly me in his stupid Llama! So I took him off-line in like 2 STUs, got on that ship, and took the kids. The guy tried to fight back, but I stopped that quick enough. Then the woman says they was on a vacation, like I care! Ha! Morons think they can even bother to mess with me when I have work to do. "So I took the kids to the %s system, where they were loaded into this Trader Koala named the Progeny, clever name if you ask me! No one will ever even wonder what it's carrying, as it seems like the most innocent little guy flying around there. Little does everyone know it's waiting to fill up its load of brats!" Having listened to this dirt-bag who hurt this little family going on vacation, you feel like going over there and giving that pirate a good beating. But if you get yourself killed now you will never be able to save those children, and you don't even want to think what will happen to those children if you don't rescue them.]] title[5] = "You did it!" text[5] = [[After disabling the ship you take your small crew along with you and go in ready for a fight! But when you get on the small Koala you find only two men guarding it, and it turns out they are not prepared for fighting at all. They can drive a ship, but fighting is not their forte. After you tie them up, you go to the cargo hold to rescue the children. When you get there, you find a few more than three; there are probably a couple dozen! This is all probably just the tip of the iceberg, too. Either way, it's time to head back to %s and reunite the parents with their children.]] title[6] = "Reunited" text[6] = [[As soon as you step off the landing deck with a following of a couple dozen children the two parents you spoke over the comm with come running; from behind you hear a few children yelling, "Mom! Dad!" Three children shove their way out from the other kids and the parents and children meet in a big group of hugs, kisses, tears, and smiles from ear to ear. You and the children stand off to the side and watch one of the most beautiful reunions you have seen. After a little while the father approaches you, wiping a tear from his cheek he stands in front of you for a moment, then suddenly takes you in an embrace. Releasing you he says to you as he dries his eyes, "Thank you so much %s, you have no idea how much this means to my family. I would love to be able to repay you somehow, but I just have no idea how I can do so right now. You have rescued my children, and brought them back to me. Thank you isn't enough, but I'm afraid for now it's the best I can do. If there is anything I can ever do for you, feel free to ask me my friend." ]] title[7] = "Reunited" text[7] = [[You assure him that it is all right, and you will not hesitate to take him up on his offer. After a while the smile fades from his face and he says, "You know how happy my family is? Well, look at all these other children here who are still separated from their parents. I want to return them all home, but that will have to wait for another day. I'm also seriously considering trying to put a stop to some of this human trafficking, but that will take a lot of planning. For now, I want to be with my family. Come back soon though, if you'd be willing, I would like to get something organized." The father goes back to his children, and as you start walking back to your ship you notice the father and mother lavishing their children in love, and you look over at the other children now sitting around, looking on the loving family with envy. Sighing, you begin climbing into your ship as the mother runs up to you, "%s, wait a second! We know your name, but you don't know ours. I'm Janice." As she looks to her husband, who's talking animatedly with the children, she smiles and says, "My husband's name is Andrew. Thank you for everything." A tear rolls down her face as she looks at you with her bright hazel eyes and she kisses you on the cheek. You watch her return to her family, as a child jumps into her arms, and you climb up into your ship.]] declinetitle = "Another Time" declinetext = [[You can hear that the the man is quite disappointed as he says, "I'm sure you have a good reason not to want to help us, perhaps you have something else more pressing..." Before the comm is cut you can hear the woman beginning to sob and the man consoling her.]] failedtitle = "You killed the children" failedtext = [[Having just destroyed the kidnappers, you also just killed the children as well. As you sit there in space, with your head against the dash, a tear rolls down your cheek as you think of the parents and how their children are forever stolen from them. If only you could rewind and try again; you know the next time you would be more cautious. If only it were so easy...]] choice1 = "Rescue those children!" choice2 = "Politely refuse" pirbroadcast = [[You are damaging the goods! You are dead!]] -- Details for the mission mistitle = "Kidnapped" reward = "A Reunited Family" description = [[Search for the kidnapped children, then rescue the children and return them to their parents.]] --OSD osdtitle = "Kidnapped" osdmsg[1] = "Fly to the %s system and land on planet %s" osdmsg[2] = "Fly to the %s system and land on planet %s" osdmsg[3] = "Fly to the %s system and disable (do not destroy) that Koala!" osdmsg[4] = "Return the children to the %s system on planet %s" --NPCs pir1_disc = [[The two pirates seem to be talking rather quietly, but loud enough for you to overhear if you are careful.]] pir2_disc = [[The pirates have both drank their wallet's worth today, so overhearing shouldn't be too much of an issue.]] end function create() claimsystem = {system.get("Goddard")} if not misn.claim(claimsystem) then abort() end chosen = tk.choice(title[1], text[1]:format(player.name()), choice1, choice2) if chosen == 1 then accept() else tk.msg(declinetitle, declinetext) abort() end end function accept() misn.accept() var.push("traffic_00_active", true) tk.msg(title[2], text[2]:format(sysname3, bar1)) misn.setTitle(mistitle) misn.setReward(reward) misn.setDesc(description) osdmsg[1] = osdmsg[1]:format(sysname3, bar1) misn.osdCreate(osdtitle, {osdmsg[1]}) misn_mark = misn.markerAdd(system.get(sysname3), "low") eavesdropped1 = false eavesdropped2 = false rescued = false lhook = hook.land("land1", "land") hook.jumpin("jumpin") end function land1() if planet.cur() == planet.get(bar1) and not eavesdropped1 and not eavesdropped2 then bar1pir1 = misn.npcAdd("firstpirates", "Pirate", "neutral/thief1", pir1_disc) bar1pir2 = misn.npcAdd("firstpirates", "Pirate", "neutral/thief2", pir1_disc) end end function land2() if planet.cur() == planet.get(bar2) and eavesdropped1 and not eavesdropped2 then bar2pir1 = misn.npcAdd("secondpirates", "Pirate", "neutral/thief3", pir2_disc) bar2pir2 = misn.npcAdd("secondpirates", "Pirate", "neutral/thief1", pir2_disc) end end function firstpirates() tk.msg(title[3], text[3]:format(bar2)) misn.npcRm(bar1pir1) misn.npcRm(bar1pir2) osdmsg[2] = osdmsg[2]:format(sysname4, bar2) misn.osdCreate(osdtitle, {osdmsg[2]}) misn.markerMove(misn_mark, system.get(sysname4)) hook.rm(lhook) lhook = hook.land("land2", "land") eavesdropped1 = true end function secondpirates() tk.msg(title[4], text[4]:format(sysname2)) misn.npcRm(bar2pir1) misn.npcRm(bar2pir2) osdmsg[3] = osdmsg[3]:format(sysname2) misn.osdCreate(osdtitle, {osdmsg[3]}) misn.markerMove(misn_mark, system.get(sysname2)) hook.rm(lhook) eavesdropped2 = true end function jumpin() if eavesdropped1 and eavesdropped2 and system.cur() == system.get(sysname2) then kidnappers = pilot.add("Trader Koala", nil, planet.get("Zhiru"):pos() + vec2.new(-800,-800))[1] kidnappers:rename("Progeny") kidnappers:setFaction("Kidnappers") kidnappers:setHilight(true) kidnappers:setVisible(true) kidnappers:memory("aggressive", true) kidnappers:control() idlehook = hook.pilot(kidnappers, "idle", "idle") attackhook = hook.pilot(kidnappers, "attacked", "attackedkidnappers") hook.pilot(kidnappers, "exploded", "explodedkidnappers") hook.pilot(kidnappers, "board", "boardkidnappers") idle() end needpirates = true end function idle() kidnappers:goto(planet.get("Zhiru"):pos() + vec2.new( 800, 800), false) kidnappers:goto(planet.get("Zhiru"):pos() + vec2.new(-800, 800), false) kidnappers:goto(planet.get("Zhiru"):pos() + vec2.new(-800, -800), false) kidnappers:goto(planet.get("Zhiru"):pos() + vec2.new( 800, -800), false) end function attackedkidnappers() if kidnappers:exists() then kidnappers:runaway(player.pilot(), true) end if needpirates then bodyguard1 = pilot.add("Pirate Hyena", "pirate", vec2.new(800, 700))[1] bodyguard2 = pilot.add("Pirate Hyena", "pirate", vec2.new(-900, 600))[1] bodyguard3 = pilot.add("Pirate Hyena", "pirate", vec2.new(700, -500))[1] bodyguard1:control() bodyguard2:control() bodyguard3:control() bodyguard1:attack(player.pilot()) bodyguard2:attack(player.pilot()) bodyguard3:attack(player.pilot()) bodyguard1:broadcast(pirbroadcast, true) needpirates = false end end function explodedkidnappers() hook.timer(1500, "kidskilled") end function kidskilled() tk.msg(failedtitle, failedtext) misn.finish(false) end function boardkidnappers() tk.msg(title[5], text[5]:format(home)) osdmsg[4] = osdmsg[4]:format(sysname1, home) misn.osdCreate(osdtitle, {osdmsg[4]}) misn.markerMove(misn_mark, system.get(sysname1)) kidnappers:setHilight(false) kidnappers:hookClear() thekids = misn.cargoAdd("The Rescued Children", 0) player.unboard() lhook = hook.land("land3", "land") rescued = true end function land3() if planet.cur() == planet.get(home) and rescued then tk.msg(title[6], text[6]:format(player.name())) tk.msg(title[7], text[7]:format(player.name())) misn.finish(true) end end function abort() var.pop("traffic_00_active") misn.finish(false) end
gpl-3.0
nimaghorbani/dozdi2
plugins/google.lua
722
1037
local function googlethat(query) local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" local parameters = "q=".. (URL.escape(query) or "") -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults="" for key,val in ipairs(results) do stringresults=stringresults..val[1].." - "..val[2].."\n" end return stringresults end local function run(msg, matches) local results = googlethat(matches[1]) return stringlinks(results) end return { description = "Searches Google and send results", usage = "!google [terms]: Searches Google and send results", patterns = { "^!google (.*)$", "^%.[g|G]oogle (.*)$" }, run = run }
gpl-2.0
Anarchid/Zero-K
LuaUI/Configs/marking_menu_menu_athena.lua
8
1311
local menu_athena = { items = { { angle = -90, unit = "cloakcon", label = "Bots", items = { { angle= -45, unit = "spiderscout", }, { angle = -135, unit = "shieldraid", }, { angle = -180, unit = "cloakheavyraid", }, { angle = 0, unit = "cloakaa", }, { angle = 45, unit = "cloakassault", }, } }, { angle = 0, unit = "spiderskirm", label = "Walkers", items = { { angle = -90, unit = "cloaksnipe", }, { angle = 135, unit = "cloakjammer", }, { angle = -135, unit = "shieldshield", }, { angle = -45, unit = "spiderantiheavy" }, { angle = 90, unit = "amphtele", }, { angle = 45, unit = "jumpskirm" }, } }, { angle = 90, unit = "staticradar", label = "Support", items = { { angle = 45, unit = "staticheavyradar" }, { angle = 135, unit = "staticjammer" }, { angle = 180, unit = "staticcon" }, } }, { angle = 180, unit = "tankheavyraid", label = "Misc.", items = { { angle = 90, unit = "vehheavyarty" }, { angle = 135, unit = "striderantiheavy" }, { angle = -90, unit = "hoverassault" }, } }, } } return menu_athena
gpl-2.0
Sewerbird/blooming-suns
src_old/ui/component/PlanetsideTilemapCommandPanelComponent.lua
1
2191
--PlanetsideTilemapCommandPanelComponent PlanetsideTilemapCommandPanelComponent = {} PlanetsideTilemapCommandPanelComponent.new = function (init) local init = init or {} local self = { target = init.target or nil, description = init.description or "Commands", ui_rect = init.ui_rect or {x = 0, y = 0, w = 150, h = 50, rx = 0, ry = 0}, background_color = init.background_color or {50, 10, 70}, super = init.super or nil } --Logic self.promptEndTurn = function () self.super.promptEndTurn() end self.focusNextUnit = function () self.super.goToNext() end self.toNextWaypoint = function () self.super.toNextWaypoint() end --Subcomponents self.endTurnButton = ImmediateButtonComponent.new({ sprite = SpriteInstance.new({sprite = "EndTurn_UI"}), ui_rect = {x = self.ui_rect.x, y = self.ui_rect.y, w = 50, h = 50}, callback = self.promptEndTurn }) self.nextUnitButton = ImmediateButtonComponent.new({ sprite = SpriteInstance.new({sprite = "NextUnit_UI"}), ui_rect = {x = self.ui_rect.x + 56, y = self.ui_rect.y, w = 25, h = 25}, callback = self.focusNextUnit }) self.toWaypointButton = ImmediateButtonComponent.new({ sprite = SpriteInstance.new({sprite = "ToWaypoint_UI"}), ui_rect = {x = self.ui_rect.x + 56, y = self.ui_rect.y + 25, w = 25, h = 25}, callback = self.toNextWaypoint }) self.buttons = {self.endTurnButton, self.nextUnitButton, self.toWaypointButton} --Events self.onDraw = function () love.graphics.setColor(self.background_color) love.graphics.rectangle("fill",self.ui_rect.x, self.ui_rect.y, self.ui_rect.w, self.ui_rect.h) love.graphics.reset() for i, v in ipairs(self.buttons) do v.onDraw() end end self.onMousePressed = function (x, y, button) end self.onMouseReleased = function (x, y, button) x = x + self.ui_rect.x y = y + self.ui_rect.y for i, v in ipairs(self.buttons) do local tgt_rect = v.ui_rect if tgt_rect.x < x and tgt_rect.x + tgt_rect.w > x and tgt_rect.y < y and tgt_rect.y + tgt_rect.h > y then v.onClick(x, y, button) break; end end end return self end
gpl-3.0
helingping/Urho3D
Source/ThirdParty/toluapp/src/bin/lua/module.lua
44
1479
-- tolua: module class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- $Id: $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Module class -- Represents module. -- The following fields are stored: -- {i} = list of objects in the module. classModule = { classtype = 'module' } classModule.__index = classModule setmetatable(classModule,classContainer) -- register module function classModule:register (pre) pre = pre or '' push(self) output(pre..'tolua_module(tolua_S,"'..self.name..'",',self:hasvar(),');') output(pre..'tolua_beginmodule(tolua_S,"'..self.name..'");') local i=1 while self[i] do self[i]:register(pre..' ') i = i+1 end output(pre..'tolua_endmodule(tolua_S);') pop() end -- Print method function classModule:print (ident,close) print(ident.."Module{") print(ident.." name = '"..self.name.."';") local i=1 while self[i] do self[i]:print(ident.." ",",") i = i+1 end print(ident.."}"..close) end -- Internal constructor function _Module (t) setmetatable(t,classModule) append(t) return t end -- Constructor -- Expects two string representing the module name and body. function Module (n,b) local t = _Module(_Container{name=n}) push(t) t:parse(strsub(b,2,strlen(b)-1)) -- eliminate braces pop() return t end
mit
Insurgencygame/LivingDead
TheLivingDeadv0.1.sdd/gadg dev/Stealth_speed_state_1.7.lua
1
2584
function gadget:GetInfo() return { name = "Speed / Stealth state", desc = "Toggles a units speed and decloak range.", author = "Zealot", date = "18 March 2013", license = "GNU LGPL, v2.1 or later", layer = 100, -------------------------What does this do? enabled = true -- loaded by default? } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if (not gadgetHandler:IsSyncedCode()) then return end local EditUnitCmdDesc = Spring.EditUnitCmdDesc local FindUnitCmdDesc = Spring.FindUnitCmdDesc local InsertUnitCmdDesc = Spring.InsertUnitCmdDesc local GiveOrderToUnit = Spring.GiveOrderToUnit local SetUnitNeutral = Spring.SetUnitNeutral local GetUnitMoveTypeData = Spring.GetUnitMoveTypeData local SetGroundMoveTypeData = Spring.MoveCtrl.SetGroundMoveTypeData local SetUnitCloak = Spring.SetUnitCloak -----setup speedstealth command local CMD_SPEEDSTEALTH = 34581 local speedstealthCmdDesc = { id = CMD_SPEEDSTEALTH, name = "togglespeedstealth", action = "togglespeedstealth", type = CMDTYPE.ICON_MODE, tooltip = 'Toggle slow and stealthy or fast and non stealthy', params = {0, 'Slow', 'Normal', 'Fast'} } function gadget:UnitCreated(unitID, unitDefID, teamID, builderID) local ud = UnitDefs[unitDefID] if ud.canMove and ud.canCloak then InsertUnitCmdDesc(unitID, speedstealthCmdDesc) end end -----------enable the command function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions) if cmdID == CMD_SPEEDSTEALTH then local cmdDescID = FindUnitCmdDesc(unitID, CMD_SPEEDSTEALTH) if not cmdDescID then return false end if cmdParams[0] == 2 then SetUnitCloak(unitID, false, 125) elseif cmdParams[0] == 3 then SetUnitCloak(unitID, true, 250) elseif cmdParams[0] == 4 then SetUnitCloak(unitID, true, 800) end --you can't edit a single value in the params table for --editUnitCmdDesc, so we generate a new table local updatedCmdParams = { cmdParams[1], speedstealthCmdDesc.params[2], speedstealthCmdDesc.params[3], speedstealthCmdDesc.params[4] } Spring.EditUnitCmdDesc(unitID, cmdDescID, { params = updatedCmdParams}) return false end return true end
gpl-2.0
Disslove77777/SSSS
plugins/moderation.lua
29
12162
do local function check_member(extra, success, result) local data = extra.data for k,v in pairs(result.members) do if v.id ~= our_id then data[tostring(extra.msg.to.id)] = { moderators = {[tostring(v.id)] = '@'..v.username}, settings = { set_name = string.gsub(extra.msg.to.print_name, '_', ' '), lock_bots = 'no', lock_name = 'yes', lock_photo = 'no', lock_member = 'no', anti_flood = 'ban', welcome = 'group', sticker = 'ok', } } save_data(_config.moderation.data, data) return send_large_msg(get_receiver(extra.msg), 'You have been promoted as moderator for this group.') end end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted as moderator for this group.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been demoted from moderator of this group.') end local function admin_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted as admin.') end local function admin_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(extra, success, result) for k,v in pairs(result.members) do if v.username == extra.username then if extra.mod_cmd == 'promote' then return promote(extra.receiver, '@'..extra.username, v.id) elseif extra.mod_cmd == 'demote' then return demote(extra.receiver, '@'..extra.username, v.id) elseif extra.mod_cmd == 'adminprom' then return admin_promote(extra.receiver, '@'..extra.username, v.id) elseif extra.mod_cmd == 'admindem' then return admin_demote(extra.receiver, '@'..extra.username, v.id) end end end send_large_msg(extra.receiver, 'No user '..extra.username..' in this group.') end local function action_by_id(extra, success, result) if success == 1 then for k,v in pairs(result.members) do if extra.matches[2] == tostring(v.id) then if extra.matches[1] == 'promote' then return promote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id)) elseif extra.matches[1] == 'demote' then return demote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id)) elseif extra.matches[1] == 'adminprom' then return admin_promote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id)) elseif extra.matches[1] == 'admindem' then return admin_demote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id)) end end end send_large_msg('chat#id'..result.id, 'No user user#id'..extra.matches[2]..' in this group.') end end local function action_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' and not is_sudo(member_id) then if extra.msg.text == '!promote' then return promote(get_receiver(msg), member_username, member_id) elseif extra.msg.text == '!demote' then return demote(get_receiver(msg), member_username, member_id) elseif extra.msg.text == '!adminprom' then return admin_promote(get_receiver(msg), member_username, member_id) elseif extra.msg.text == '!admindem' then return admin_demote(get_receiver(msg), member_username, member_id) end else return 'Use This in Your Groups.' end end function run(msg, matches) local receiver = get_receiver(msg) if is_chat_msg(msg) then if is_mod(msg.from.id, msg.to.id) then if matches[1] == 'promote' then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) end if matches[2] then if string.match(matches[2], '^%d+$') then chat_info(receiver, action_by_id, {msg=msg, matches=matches}) elseif string.match(matches[2], '^@.+$') then local username = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username}) end end elseif matches[1] == 'demote' then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) end if matches[2] then if string.match(matches[2], '^%d+$') then demote(receiver, 'user_'..matches[2], matches[2]) elseif string.match(matches[2], '^@.+$') then local username = string.gsub(matches[2], '@', '') if username == msg.from.username then return 'You can\'t demote yourself.' else chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username}) end end end elseif matches[1] == 'modlist' then local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = 'List of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message .. '- '..v..' [' ..k.. '] \n' end return message end end if is_admin(msg.from.id, msg.to.id) then if matches[1] == 'adminprom' then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) end if matches[2] then if string.match(matches[2], '^%d+$') then chat_info(receiver, action_by_id, {msg=msg, matches=matches}) elseif matches[2] and string.match(matches[2], '^@.+$') then local username = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username}) end end elseif matches[1] == 'admindem' then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) end if matches[2] then if string.match(matches[2], '^%d+$') then admin_demote(receiver, 'user_'..matches[2], matches[2]) elseif string.match(matches[2], '^@.+$') then local username = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username}) end end elseif matches[1] == 'adminlist' then local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if next(data['admins']) == nil then --fix way return 'No admin available.' end for k,v in pairs(data['admins']) do message = 'List for Bot admins:\n'..'- '..v..' ['..k..'] \n' end return message end end else return 'Only works on group' end if matches[1] == 'chat_created' and msg.from.id == 0 then local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then chat_info(get_receiver(msg), check_member,{data=data, msg=msg}) else if data[tostring(msg.to.id)] then return 'Group is already added.' end local username = msg.from.username or msg.from.print_name -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={[tostring(msg.from.id)] = '@'..username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_bots = 'no', lock_name = 'yes', lock_photo = 'no', lock_member = 'no', anti_flood = 'ban', welcome = 'group', sticker = 'ok', } } save_data(_config.moderation.data, data) return 'Group has been added, and @'..username..' has been promoted as moderator for this group.' end end end return { description = 'Moderation plugin', usage = { moderator = { '!promote : If typed when replying, promote replied user as moderator', '!promote <user_id> : Promote user_id as moderator', '!promote @<username> : Promote username as moderator', '!demote : If typed when replying, demote replied user from moderator', '!demote <user_id> : Demote user_id from moderator', '!demote @<username> : Demote username from moderator', '!modlist : List of moderators' }, sudo = { '!adminprom : If typed when replying, promote replied user as admin.', '!adminprom <user_id> : Promote user_id as admin.', '!adminprom @<username> : Promote username as admin.', '!admindem : If typed when replying, demote replied user from admin.', '!admindem <user_id> : Demote user_id from admin.', '!admindem @<username> : Demote username from admin.' }, }, patterns = { '^!(admindem) (%d+)$', '^!(admindem) (.*)$', '^!(admindem)$', '^!(adminlist)$', '^!(adminprom) (%d+)$', '^!(adminprom) (.*)$', '^!(adminprom)$', '^!(demote) (.*)$', '^!(demote)$', '^!(modlist)$', '^!(promote) (.*)$', '^!(promote)$', '^!(promote) (%d+)$', '^!!tgservice (chat_add_user)$', '^!!tgservice (chat_created)$' }, run = run } end
gpl-2.0
Sasu98/Nerd-Gaming-Public
resources/NGDrugs/weed_client.lua
2
4343
drugs.Marijuana = { loaded = false, func = { }, var = { rasta = { { 0, 255, 0 }, { 255, 255, 0 }, { 255, 0, 0 } } }, info = { timePerDoce = 30, } } local weed = drugs.Marijuana function weed.func.load ( ) if ( not weed.loaded ) then weed.loaded = true if ( not isElement ( weed.var.music ) ) then weed.var.music = playSound ( "files/weed_music.mp3", true ) end if ( isElement ( weed.var.volTime ) ) then destroyElement ( weed.var.volTime ) end weed.var.recAlpha = 0 weed.var.recMode = "add" weed.var.imgMode = "small" weed.var.imgStart = getTickCount ( ) weed.var.vehTick = getTickCount ( ) weed.var.vehColors = { } for i, v in pairs ( getElementsByType ( "vehicle" ) ) do weed.var.vehColors [ v ] = { getVehicleColor ( v, true ) } local r, g, b = unpack ( weed.var.rasta [ math.random ( #weed.var.rasta ) ] ) local r2, g2, b2 = unpack ( weed.var.rasta [ math.random ( #weed.var.rasta ) ] ) setVehicleColor ( v, r, g, b, r2, g2, b2, r, g, b, r2, g2, b2 ) end setSkyGradient ( 255, 0, 0, 255, 0, 0 ) setGameSpeed ( 0.7 ) weed.var.healthTimer = setTimer ( function ( ) triggerServerEvent ( "NGDrugs:Module->Marijuana:updatePlayerHealth", localPlayer ) end, 1000, 0 ) triggerServerEvent ( "NGDrugs:Module->Core:setPlayerHeadText", localPlayer, "Stoned", { 120, 0, 255 } ) addEventHandler ( "onClientRender", root, weed.func.render ) end end function weed.func.unload ( ) if ( weed.loaded ) then triggerServerEvent ( "NGDrugs:Module->Core:destroyPlayerHeadText", localPlayer ) weed.loaded = false if ( isElement ( weed.var.music ) ) then weed.var.volTime = setTimer ( function ( ) if ( not isElement ( weed.var.music ) ) then killTimer ( weed.var.volTime ) else local v = getSoundVolume ( weed.var.music ) v = math.round ( v - 0.1, 1 ) if ( v <= 0 ) then destroyElement ( weed.var.music ) else setSoundVolume ( weed.var.music, v ) end end end, 200, 0 ) end if ( weed.var.vehColors ) then for i, v in pairs ( weed.var.vehColors ) do if ( isElement ( i ) ) then setVehicleColor ( i, unpack ( v ) ) end end end if ( isElement ( weed.var.healthTimer ) ) then killTImer ( weed.var.healthTimer ) end setGameSpeed ( 1 ) resetSkyGradient ( ) removeEventHandler ( "onClientRender", root, weed.func.render ) end end function weed.func.render ( ) if ( getTickCount ( ) - weed.var.vehTick >= 3000 ) then weed.var.vehTick = getTickCount ( ) for i, v in pairs ( getElementsByType ( "vehicle" ) ) do if ( not weed.var.vehColors [ v ] ) then weed.var.vehColors [ v ] = { getVehicleColor ( v ) } end local r, g, b = unpack ( weed.var.rasta [ math.random ( #weed.var.rasta ) ] ) local r2, g2, b2 = unpack ( weed.var.rasta [ math.random ( #weed.var.rasta ) ] ) setVehicleColor ( v, r, g, b, r2, g2, b2, r, g, b, r2, g2, b2 ) end end local a = weed.var.recAlpha if ( weed.var.recMode == "add" ) then a = a + 3 if ( a >= 90 ) then weed.var.recMode = "remove" end else a = a - 3 if ( a <= 10 ) then weed.var.recMode = "add" end end weed.var.recAlpha = a dxDrawRectangle ( 0, 0, sx_, sy_, tocolor ( 255, 255, 0, a ) ) local en = weed.var.imgStart + 1200 if ( getTickCount ( ) >= en ) then weed.var.imgStart = getTickCount ( ) if ( weed.var.imgMode == "small" ) then weed.var.imgMode = "big" else weed.var.imgMode = "small" end end local mode = weed.var.imgMode local elapsedTime = getTickCount() - weed.var.imgStart local duration = (weed.var.imgStart+1200) - weed.var.imgStart local prog = elapsedTime / duration if ( mode == "small" ) then w, h, _ = interpolateBetween ( sx_/1.4, sy_/1.4, 0, sx_/2, sy_/2, 0, prog, "InQuad" ) else w, h, _ = interpolateBetween ( sx_/2, sy_/2, 0, sx_/1.4, sy_/1.4, 0, prog, "OutQuad" ) end dxDrawImage ( (sx_/2-w/2), (sy_/2-h/2), w, h, "files/weed_icon.png", 0, 0, 0, tocolor ( 255, 255, 255, 120-weed.var.recAlpha ) ) end drugs.Marijuana = weed function math.round(number, decimals, method) decimals = decimals or 0 local factor = 10 ^ decimals if (method == "ceil" or method == "floor") then return math[method](number * factor) / factor else return tonumber(("%."..decimals.."f"):format(number)) end end
mit
Whit3Tig3R/bestspammbot2
plugins/btc.lua
289
1375
-- See https://bitcoinaverage.com/api local function getBTCX(amount,currency) local base_url = 'https://api.bitcoinaverage.com/ticker/global/' -- Do request on bitcoinaverage, the final / is critical! local res,code = https.request(base_url..currency.."/") if code ~= 200 then return nil end local data = json:decode(res) -- Easy, it's right there text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid -- If we have a number as second parameter, calculate the bitcoin amount if amount~=nil then btc = tonumber(amount) / tonumber(data.ask) text = text.."\n "..currency .." "..amount.." = BTC "..btc end return text end local function run(msg, matches) local cur = 'EUR' local amt = nil -- Get the global match out of the way if matches[1] == "!btc" then return getBTCX(amt,cur) end if matches[2] ~= nil then -- There is a second match amt = matches[2] cur = string.upper(matches[1]) else -- Just a EUR or USD param cur = string.upper(matches[1]) end return getBTCX(amt,cur) end return { description = "Bitcoin global average market value (in EUR or USD)", usage = "!btc [EUR|USD] [amount]", patterns = { "^!btc$", "^!btc ([Ee][Uu][Rr])$", "^!btc ([Uu][Ss][Dd])$", "^!btc (EUR) (%d+[%d%.]*)$", "^!btc (USD) (%d+[%d%.]*)$" }, run = run }
gpl-2.0