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
unusualcrow/redead_reloaded
entities/entities/sent_radiation/init.lua
1
1524
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") ENT.Scale = 1 ENT.Distance = 300 function ENT:Initialize() self:SetMoveType(MOVETYPE_NONE) self:SetSolid(SOLID_NONE) self:SetCollisionGroup(COLLISION_GROUP_DEBRIS_TRIGGER) self:SetNotSolid(true) self:DrawShadow(false) self:SetCollisionBounds(Vector(-60, -60, -60), Vector(60, 60, 60)) self:PhysicsInitBox(Vector(-60, -60, -60), Vector(60, 60, 60)) self:SetNWInt("Distance", self.Distance) self.DieTime = CurTime() + 30 end function ENT:SetDistance(num) self.Distance = num end function ENT:SetLifeTime(num) self.LifeTime = num end function ENT:OnRemove() end function ENT:Think() if self.DieTime < CurTime() then self:Remove() end self.Scale = (self.DieTime - CurTime()) / 30 for k, v in pairs(team.GetPlayers(TEAM_ARMY)) do local dist = v:GetPos():Distance(self:GetPos()) if dist < (self.Distance * self.Scale) + 100 then if dist < (self.Distance * self.Scale) and (v.RadAddTime or 0) < CurTime() then v.RadAddTime = CurTime() + 8 v:AddRadiation(1) end if (v.NextRadSound or 0) < CurTime() then local scale = math.Clamp(((self.Distance * self.Scale) + 100 - dist) / (self.Distance * self.Scale), 0.1, 1.0) v.NextRadSound = CurTime() + 1 - scale v:EmitSound(table.Random(GAMEMODE.Geiger), 100, math.random(80, 90) + scale * 20) v:NoticeOnce("A radioactive deposit is nearby", GAMEMODE.Colors.Blue) end end end end function ENT:UpdateTransmitState() return TRANSMIT_ALWAYS end
mit
CrazyEddieTK/Zero-K
LuaUI/Widgets/gui_attack_aoe.lua
4
23803
-- $Id: gui_attack_aoe.lua 3823 2009-01-19 23:40:49Z evil4zerggin $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local versionNumber = "v3.1" function widget:GetInfo() return { name = "Attack AoE", desc = versionNumber .. " Cursor indicator for area of effect and scatter when giving attack command.", author = "Evil4Zerggin", date = "26 September 2008", license = "GNU LGPL, v2.1 or later", layer = 1, enabled = true -- loaded by default? } end -------------------------------------------------------------------------------- --config -------------------------------------------------------------------------------- local numScatterPoints = 32 local aoeColor = {1, 0, 0, 1} local aoeLineWidthMult = 64 local scatterColor = {1, 1, 0, 1} local scatterLineWidthMult = 1024 local circleDivs = 64 local minSpread = 8 --weapons with this spread or less are ignored local numAoECircles = 9 local pointSizeMult = 2048 -------------------------------------------------------------------------------- --vars -------------------------------------------------------------------------------- local aoeDefInfo = {} local dgunInfo = {} local unitAoeDefs = {} local unitDgunDefs = {} local unitHasBeenSetup = {} local aoeUnitInfo local dgunUnitInfo local aoeUnitID local dgunUnitID local selUnitID local circleList local secondPart = 0 local mouseDistance = 1000 local extraDrawRange local sumoSelected = false -------------------------------------------------------------------------------- --speedups -------------------------------------------------------------------------------- local GetActiveCommand = Spring.GetActiveCommand local GetCameraPosition = Spring.GetCameraPosition local GetFeaturePosition = Spring.GetFeaturePosition local GetGroundHeight = Spring.GetGroundHeight local GetMouseState = Spring.GetMouseState local GetSelectedUnitsSorted = Spring.GetSelectedUnitsSorted local GetUnitPosition = Spring.GetUnitPosition local GetUnitRadius = Spring.GetUnitRadius local GetUnitStates = Spring.GetUnitStates local TraceScreenRay = Spring.TraceScreenRay local CMD_ATTACK = CMD.ATTACK local CMD_MANUALFIRE = CMD.MANUALFIRE local g = Game.gravity local GAME_SPEED = 30 local g_f = g / GAME_SPEED / GAME_SPEED local glBeginEnd = gl.BeginEnd local glCallList = gl.CallList local glCreateList = gl.CreateList local glColor = gl.Color local glDeleteList = gl.DeleteList local glDepthTest = gl.DepthTest local glDrawGroundCircle = gl.DrawGroundCircle local glLineWidth = gl.LineWidth local glPointSize = gl.PointSize local glPopMatrix = gl.PopMatrix local glPushMatrix = gl.PushMatrix local glRotate = gl.Rotate local glScale = gl.Scale local glTranslate = gl.Translate local glVertex = gl.Vertex local GL_LINES = GL.LINES local GL_LINE_LOOP = GL.LINE_LOOP local GL_POINTS = GL.POINTS local PI = math.pi local atan = math.atan local cos = math.cos local sin = math.sin local floor = math.floor local max = math.max local min = math.min local sqrt = math.sqrt VFS.Include("LuaRules/Configs/customcmds.h.lua") local sumoDefID = UnitDefNames.jumpsumo.id local sumoAoE = WeaponDefNames.jumpsumo_landing.damageAreaOfEffect local sumoEE = WeaponDefNames.jumpsumo_landing.edgeEffectiveness -------------------------------------------------------------------------------- --utility functions -------------------------------------------------------------------------------- local function ToBool(x) return x and x ~= 0 and x ~= "false" end local function Normalize(x, y, z) local mag = sqrt(x*x + y*y + z*z) if (mag == 0) then return nil else return x/mag, y/mag, z/mag, mag end end local function VertexList(points) for i, point in pairs(points) do glVertex(point) end end local function GetMouseTargetPosition() local mx, my = GetMouseState() local mouseTargetType, mouseTarget = TraceScreenRay(mx, my, false, true) if (mouseTargetType == "ground") then return mouseTarget[1], mouseTarget[2], mouseTarget[3] elseif (mouseTargetType == "unit") then return GetUnitPosition(mouseTarget) elseif (mouseTargetType == "feature") then local _, coords = TraceScreenRay(mx, my, true, true) if coords and coords[3] then return coords[1], coords[2], coords[3] else return GetFeaturePosition(mouseTarget) end else return nil end end local function GetMouseDistance() local cx, cy, cz = GetCameraPosition() local mx, my, mz = GetMouseTargetPosition() if (not mx) then return nil end local dx = cx - mx local dy = cy - my local dz = cz - mz return sqrt(dx*dx + dy*dy + dz*dz) end local function UnitCircleVertices() for i = 1, circleDivs do local theta = 2 * PI * i / circleDivs glVertex(cos(theta), 0, sin(theta)) end end local function DrawUnitCircle() glBeginEnd(GL_LINE_LOOP, UnitCircleVertices) end local function DrawCircle(x, y, z, radius) glPushMatrix() glTranslate(x, y, z) glScale(radius, radius, radius) glCallList(circleList) glPopMatrix() end local function GetSecondPart(offset) local result = secondPart + (offset or 0) return result - floor(result) end -------------------------------------------------------------------------------- --initialization -------------------------------------------------------------------------------- local function getWeaponInfo(weaponDef, unitDef) local retData local weaponType = weaponDef.type local scatter = weaponDef.accuracy + weaponDef.sprayAngle local aoe = weaponDef.damageAreaOfEffect local cost = unitDef.metalCost local waterWeapon = weaponDef.waterWeapon local ee = weaponDef.edgeEffectiveness if (weaponDef.cylinderTargetting >= 100) then retData = {type = "orbital", scatter = scatter} elseif (weaponType == "Cannon") then retData = { type = "ballistic", scatter = scatter, v = (weaponDef.customParams.weaponvelocity or 0), range = weaponDef.range, mygravity = weaponDef.customParams and weaponDef.customParams.mygravity and weaponDef.customParams.mygravity*800 } elseif (weaponType == "MissileLauncher") then local turnRate = 0 if (weaponDef.tracks) then turnRate = weaponDef.turnRate end if (weaponDef.wobble > turnRate * 1.4) then scatter = (weaponDef.wobble - weaponDef.turnRate) * (weaponDef.customParams.weaponvelocity or 0) * 16 local rangeScatter = (8 * weaponDef.wobble - weaponDef.turnRate) retData = {type = "wobble", scatter = scatter, rangeScatter = rangeScatter, range = weaponDef.range} elseif (weaponDef.wobble > turnRate) then scatter = (weaponDef.wobble - weaponDef.turnRate) * (weaponDef.customParams.weaponvelocity or 0) * 16 retData = {type = "wobble", scatter = scatter} elseif (weaponDef.tracks) then retData = {type = "tracking"} else retData = {type = "direct", scatter = scatter, range = weaponDef.range} end elseif (weaponType == "AircraftBomb") then retData = {type = "dropped", scatter = scatter, v = unitDef.speed, h = unitDef.wantedHeight, salvoSize = weaponDef.salvoSize, salvoDelay = weaponDef.salvoDelay} elseif (weaponType == "StarburstLauncher") then if (weaponDef.tracks) then retData = {type = "tracking"} else retData = {type = "cruise", range = weaponDef.range} end elseif (weaponType == "TorpedoLauncher") then if (weaponDef.tracks) then retData = {type = "tracking"} else retData = {type = "direct", scatter = scatter, range = weaponDef.range} end elseif (weaponType == "Flame" or weaponDef.noExplode) then retData = {type = "noexplode", range = weaponDef.range} else retData = {type = "direct", scatter = scatter, range = weaponDef.range} end if not weaponDef.impactOnly then retData.aoe = aoe else retData.aoe = 0 end retData.cost = cost retData.mobile = not unitDef.isImmobile retData.waterWeapon = waterWeapon retData.ee = ee return retData end local function SetupUnit(unitDef, unitID) if (not unitDef.weapons) then return end local weapon1, weapon2, manualfireWeapon, rangeMult if unitID then weapon1 = Spring.GetUnitRulesParam(unitID, "comm_weapon_num_1") weapon2 = Spring.GetUnitRulesParam(unitID, "comm_weapon_num_2") local manual1 = Spring.GetUnitRulesParam(unitID, "comm_weapon_manual_1") == 1 local manual2 = Spring.GetUnitRulesParam(unitID, "comm_weapon_manual_2") == 1 if manual1 then manualfireWeapon = weapon1 elseif manual2 then manualfireWeapon = weapon2 end rangeMult = Spring.GetUnitRulesParam(unitID, "comm_range_mult") end local retDgunInfo local retAoeInfo local maxSpread = minSpread local maxWeaponDef for num, weapon in ipairs(unitDef.weapons) do if (weapon.weaponDef) and ((not unitID) or num == weapon1 or num == weapon2) then local weaponDef = WeaponDefs[weapon.weaponDef] if (weaponDef) then local aoe = weaponDef.damageAreaOfEffect if (weaponDef.manualFire and unitDef.canManualFire) or num == manualfireWeapon then retDgunInfo = getWeaponInfo(weaponDef, unitDef) if retDgunInfo.range then if weaponDef.customParams.truerange then retDgunInfo.range = tonumber(weaponDef.customParams.truerange) end if weaponDef.customParams.gui_draw_range then retDgunInfo.range = tonumber(weaponDef.customParams.gui_draw_range) end if rangeMult then retDgunInfo.range = retDgunInfo.range * rangeMult end end elseif (not weaponDef.isShield and not ToBool(weaponDef.interceptor) and not ToBool(weaponDef.customParams.hidden) and (aoe > maxSpread or weaponDef.range * (weaponDef.accuracy + weaponDef.sprayAngle) > maxSpread )) then maxSpread = max(aoe, weaponDef.range * (weaponDef.accuracy + weaponDef.sprayAngle)) maxWeaponDef = weaponDef end end end end if (maxWeaponDef) then retAoeInfo = getWeaponInfo(maxWeaponDef, unitDef) if maxWeaponDef.customParams.gui_draw_range then retAoeInfo.range = tonumber(maxWeaponDef.customParams.gui_draw_range) end if retAoeInfo.range and rangeMult then retAoeInfo.range = retAoeInfo.range * rangeMult end end return retAoeInfo, retDgunInfo end local function SetupDisplayLists() circleList = glCreateList(DrawUnitCircle) end local function DeleteDisplayLists() glDeleteList(circleList) end -------------------------------------------------------------------------------- --updates -------------------------------------------------------------------------------- local function UpdateSelection() local sel = GetSelectedUnitsSorted() local maxCost = 0 dgunUnitInfo = nil aoeUnitInfo = nil dgunUnitID = nil aoeUnitID = nil sumoSelected = false for unitDefID, unitIDs in pairs(sel) do if unitDefID ~= "n" then if unitDefID == sumoDefID then sumoSelected = true end local unitID = unitIDs[1] local dynamicComm = Spring.GetUnitRulesParam(unitID, "comm_level") if dynamicComm and not unitHasBeenSetup[unitID] then unitAoeDefs[unitID], unitDgunDefs[unitID] = SetupUnit(UnitDefs[unitDefID], unitID) unitHasBeenSetup[unitID] = true end if (dgunInfo[unitDefID]) then dgunUnitInfo = unitDgunDefs[unitID] or ((not dynamicComm) and dgunInfo[unitDefID]) dgunUnitID = unitID end if (aoeDefInfo[unitDefID]) then local currCost = UnitDefs[unitDefID].metalCost * #unitIDs if (currCost > maxCost) then maxCost = currCost aoeUnitInfo = unitAoeDefs[unitID] or ((not dynamicComm) and aoeDefInfo[unitDefID]) aoeUnitID = unitID end end local extraDrawParam = Spring.GetUnitRulesParam(unitID, "secondary_range") if extraDrawParam then extraDrawRange = extraDrawParam else extraDrawRange = UnitDefs[unitDefID] and UnitDefs[unitDefID].customParams and UnitDefs[unitDefID].customParams.extradrawrange end if extraDrawRange then selUnitID = unitID end end end end -------------------------------------------------------------------------------- --aoe -------------------------------------------------------------------------------- local function DrawAoE(tx, ty, tz, aoe, ee, alphaMult, offset) glLineWidth(math.max(0.05, aoeLineWidthMult * aoe / mouseDistance)) for i = 1, numAoECircles do local proportion = i / (numAoECircles + 1) local radius = aoe * proportion local alpha = aoeColor[4] * (1 - proportion) / (1 - proportion * ee) * (1 - GetSecondPart(offset or 0)) * (alphaMult or 1) glColor(aoeColor[1], aoeColor[2], aoeColor[3], alpha) DrawCircle(tx, ty, tz, radius) end glColor(1,1,1,1) glLineWidth(1) end -------------------------------------------------------------------------------- --dgun/noexplode -------------------------------------------------------------------------------- local function DrawNoExplode(aoe, fx, fy, fz, tx, ty, tz, range) local dx = tx - fx local dy = ty - fy local dz = tz - fz local bx, by, bz, dist = Normalize(dx, dy, dz) if (not bx or dist > range) then return end local br = sqrt(bx*bx + bz*bz) local wx = -aoe * bz / br local wz = aoe * bx / br local ex = range * bx / br local ez = range * bz / br local vertices = {{fx + wx, fy, fz + wz}, {fx + ex + wx, ty, fz + ez + wz}, {fx - wx, fy, fz - wz}, {fx + ex - wx, ty, fz + ez - wz}} local alpha = (1 - GetSecondPart()) * aoeColor[4] glColor(aoeColor[1], aoeColor[2], aoeColor[3], alpha) glLineWidth(scatterLineWidthMult / mouseDistance) glBeginEnd(GL_LINES, VertexList, vertices) glColor(1,1,1,1) glLineWidth(1) end -------------------------------------------------------------------------------- --ballistics -------------------------------------------------------------------------------- local function GetBallisticVector(v, mg, dx, dy, dz, trajectory, range) local dr_sq = dx*dx + dz*dz local dr = sqrt(dr_sq) if (dr > range) then return nil end local d_sq = dr_sq + dy*dy if (d_sq == 0) then return 0, v * trajectory, 0 end local root1 = v*v*v*v - 2*v*v*mg*dy - mg*mg*dr_sq if (root1 < 0) then return nil end local root2 = 2*dr_sq*d_sq*(v*v - mg*dy - trajectory*sqrt(root1)) if (root2 < 0) then return nil end local vr = sqrt(root2)/(2*d_sq) local vy if (r == 0 or vr == 0) then vy = v else vy = vr*dy/dr + dr*mg/(2*vr) end local bx = dx*vr/dr local bz = dz*vr/dr local by = vy return Normalize(bx, by, bz) end local function GetBallisticImpactPoint(v, mg_f, fx, fy, fz, bx, by, bz) local v_f = v / GAME_SPEED local vx_f = bx * v_f local vy_f = by * v_f local vz_f = bz * v_f local px = fx local py = fy local pz = fz local ttl = 4 * v_f / mg_f for i = 1, ttl do px = px + vx_f py = py + vy_f pz = pz + vz_f vy_f = vy_f - mg_f local gwh = max(GetGroundHeight(px, pz), 0) if (py < gwh) then local interpolate = min((py - gwh) / vy_f, 1) local x = px - interpolate * vx_f local z = pz - interpolate * vz_f return {x, max(GetGroundHeight(x, z), 0), z} end end return {px, py, pz} end --v: weaponvelocity --trajectory: +1 for high, -1 for low local function DrawBallisticScatter(scatter, v, mygravity ,fx, fy, fz, tx, ty, tz, trajectory, range) if (scatter == 0) then return end local dx = tx - fx local dy = ty - fy local dz = tz - fz if (dx == 0 and dz == 0) then return end local mg = mygravity or g local bx, by, bz = GetBallisticVector(v, mg, dx, dy, dz, trajectory, range) --don't draw anything if out of range if (not bx) then return end local br = sqrt(bx*bx + bz*bz) --bars local rx = dx / br local rz = dz / br local wx = -scatter * rz local wz = scatter * rx local barLength = sqrt(wx*wx + wz*wz) --length of bars local barX = 0.5 * barLength * bx / br local barZ = 0.5 * barLength * bz / br local sx = tx - barX local sz = tz - barZ local lx = tx + barX local lz = tz + barZ local wsx = -scatter * (rz - barZ) local wsz = scatter * (rx - barX) local wlx = -scatter * (rz + barZ) local wlz = scatter * (rx + barX) local bars = {{tx + wx, ty, tz + wz}, {tx - wx, ty, tz - wz}, {sx + wsx, ty, sz + wsz}, {lx + wlx, ty, lz + wlz}, {sx - wsx, ty, sz - wsz}, {lx - wlx, ty, lz - wlz}} local scatterDiv = scatter / numScatterPoints local vertices = {} local mg_f = mg / GAME_SPEED / GAME_SPEED --trace impact points for i = -numScatterPoints, numScatterPoints do local currScatter = i * scatterDiv local currScatterCos = sqrt(1 - currScatter * currScatter) local rMult = currScatterCos - by * currScatter / br local bx_c = bx * rMult local by_c = by * currScatterCos + br * currScatter local bz_c = bz * rMult vertices[i+numScatterPoints+1] = GetBallisticImpactPoint(v, mg_f, fx, fy, fz, bx_c, by_c, bz_c) end glLineWidth(scatterLineWidthMult / mouseDistance) -- FIXME ATIBUG glPointSize(pointSizeMult / mouseDistance) glColor(scatterColor) glDepthTest(false) glBeginEnd(GL_LINES, VertexList, bars) glBeginEnd(GL_POINTS, VertexList, vertices) glDepthTest(true) glColor(1,1,1,1) -- FIXME ATIBUG glPointSize(1) glLineWidth(1) end -------------------------------------------------------------------------------- --wobble -------------------------------------------------------------------------------- local function DrawWobbleScatter(scatter, fx, fy, fz, tx, ty, tz, rangeScatter, range) local dx = tx - fx local dy = ty - fy local dz = tz - fz local bx, by, bz, d = Normalize(dx, dy, dz) glColor(scatterColor) glLineWidth(scatterLineWidthMult / mouseDistance) if d and range then if d <= range then DrawCircle(tx, ty, tz, rangeScatter * d + scatter) end else DrawCircle(tx, ty, tz, scatter) end glColor(1,1,1,1) glLineWidth(1) end -------------------------------------------------------------------------------- --direct -------------------------------------------------------------------------------- local function DrawDirectScatter(scatter, fx, fy, fz, tx, ty, tz, range, unitRadius) local dx = tx - fx local dy = ty - fy local dz = tz - fz local bx, by, bz, d = Normalize(dx, dy, dz) if (not bx or d == 0 or d > range) then return end local ux = bx * unitRadius / sqrt(1 - by*by) local uz = bz * unitRadius / sqrt(1 - by*by) local cx = -scatter * uz local cz = scatter * ux local wx = -scatter * dz / sqrt(1 - by*by) local wz = scatter * dx / sqrt(1 - by*by) local vertices = {{fx + ux + cx, fy, fz + uz + cz}, {tx + wx, ty, tz + wz}, {fx + ux - cx, fy, fz + uz - cz}, {tx - wx, ty, tz - wz}} glColor(scatterColor) glLineWidth(scatterLineWidthMult / mouseDistance) glBeginEnd(GL_LINES, VertexList, vertices) glColor(1,1,1,1) glLineWidth(1) end -------------------------------------------------------------------------------- --dropped -------------------------------------------------------------------------------- local function DrawDroppedScatter(aoe, ee, scatter, v, fx, fy, fz, tx, ty, tz, salvoSize, salvoDelay) local dx = tx - fx local dz = tz - fz local bx, _, bz = Normalize(dx, 0, dz) if (not bx) then return end local vertices = {} local currScatter = scatter * v * sqrt(2*fy/g) local alphaMult = min(v * salvoDelay / aoe, 1) for i=1,salvoSize do local delay = salvoDelay * (i - (salvoSize + 1) / 2) local dist = v * delay local px_c = dist * bx + tx local pz_c = dist * bz + tz local py_c = max(GetGroundHeight(px_c, pz_c), 0) DrawAoE(px_c, py_c, pz_c, aoe, ee, alphaMult, -delay) glColor(scatterColor[1], scatterColor[2], scatterColor[3], scatterColor[4] * alphaMult) glLineWidth(scatterLineWidthMult / mouseDistance) DrawCircle(px_c, py_c, pz_c, currScatter) end glColor(1,1,1,1) glLineWidth(1) end -------------------------------------------------------------------------------- --orbital -------------------------------------------------------------------------------- local function DrawOrbitalScatter(scatter, tx, ty, tz) glColor(scatterColor) glLineWidth(scatterLineWidthMult / mouseDistance) DrawCircle(tx, ty, tz, scatter) glColor(1,1,1,1) glLineWidth(1) end -------------------------------------------------------------------------------- --callins -------------------------------------------------------------------------------- function widget:Initialize() for unitDefID, unitDef in pairs(UnitDefs) do aoeDefInfo[unitDefID], dgunInfo[unitDefID] = SetupUnit(unitDef) end SetupDisplayLists() end function widget:Shutdown() DeleteDisplayLists() end function widget:DrawWorld() mouseDistance = GetMouseDistance() or 1000 local tx, ty, tz = GetMouseTargetPosition() if (not tx) then return end local _, cmd, _ = GetActiveCommand() local info, unitID if extraDrawRange and selUnitID and cmd == CMD_ATTACK then local _,_,_,fx, fy, fz = GetUnitPosition(selUnitID, true) if fx then glColor(1, 0.35, 0.35, 0.75) glLineWidth(1) glDrawGroundCircle(fx, fy, fz, extraDrawRange, 50) glColor(1,1,1,1) end end if (cmd == CMD_ATTACK and aoeUnitInfo) then info = aoeUnitInfo unitID = aoeUnitID elseif (cmd == CMD_MANUALFIRE and dgunUnitInfo) then info = dgunUnitInfo local extraDrawParam = Spring.GetUnitRulesParam(dgunUnitID, "secondary_range") if extraDrawParam then info.range = extraDrawParam end unitID = dgunUnitID elseif (cmd == CMD_JUMP and sumoSelected) then DrawAoE(tx, ty, tz, sumoAoE, sumoEE) return else return end local _,_,_,fx, fy, fz = GetUnitPosition(unitID, true) if (not fx) then return end if (not info.mobile) then fy = fy + GetUnitRadius(unitID) end if (not info.waterWeapon) then ty = max(0, ty) end local weaponType = info.type if (weaponType == "noexplode") then DrawNoExplode(info.aoe, fx, fy, fz, tx, ty, tz, info.range) elseif (weaponType == "ballistic") then local states = GetUnitStates(unitID) local trajectory if (states and states.trajectory) then trajectory = 1 else trajectory = -1 end DrawAoE(tx, ty, tz, info.aoe, info.ee) DrawBallisticScatter(info.scatter, info.v, info.mygravity, fx, fy, fz, tx, ty, tz, trajectory, info.range) elseif (weaponType == "tracking") then DrawAoE(tx, ty, tz, info.aoe, info.ee) elseif (weaponType == "direct") then DrawAoE(tx, ty, tz, info.aoe, info.ee) DrawDirectScatter(info.scatter, fx, fy, fz, tx, ty, tz, info.range, GetUnitRadius(unitID)) elseif (weaponType == "dropped") then DrawDroppedScatter(info.aoe, info.ee, info.scatter, info.v, fx, info.h, fz, tx, ty, tz, info.salvoSize, info.salvoDelay) elseif (weaponType == "wobble") then DrawAoE(tx, ty, tz, info.aoe, info.ee) DrawWobbleScatter(info.scatter, fx, fy, fz, tx, ty, tz, info.rangeScatter, info.range) elseif (weaponType == "orbital") then DrawAoE(tx, ty, tz, info.aoe, info.ee) DrawOrbitalScatter(info.scatter, tx, ty, tz) elseif (weaponType == "dontdraw") then -- don't draw anything foo else DrawAoE(tx, ty, tz, info.aoe, info.ee) end if (cmd == CMD_MANUALFIRE) then glColor(1, 0, 0, 0.75) glLineWidth(1) glDrawGroundCircle(fx, fy, fz, info.range, circleDivs) glColor(1,1,1,1) end end function widget:UnitDestroyed(unitID) unitAoeDefs[unitID] = nil unitDgunDefs[unitID] = nil unitHasBeenSetup[unitID] = nil end function widget:SelectionChanged(sel) UpdateSelection() end function widget:Update(dt) secondPart = secondPart + dt secondPart = secondPart - floor(secondPart) end
gpl-2.0
Playermet/luajit-sqlite
examples/base.lua
1
2731
local sqlite = require 'sqlite3' ('sqlite3') local SQLITE = sqlite.const local code, db = sqlite.open(':memory:') if code ~= SQLITE.OK then print('Error: ' .. db:errmsg()) os.exit() end code = sqlite.exec(db, [[ CREATE TABLE People ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER ); ]]) do -- Create and use prepared statement -- Don't forget to finalize after using local some_data = { { name = 'Alex', age = 35 }; { name = 'Eric', age = 27 }; { name = 'Paul', age = 29 }; } local code, stmt = sqlite.prepare_v2(db, [[ INSERT INTO People (name, age) VALUES (?, ?); ]]) for _, row in pairs(some_data) do sqlite.bind_text(stmt, 1, row.name) sqlite.bind_int(stmt, 2, row.age) sqlite.step(stmt) sqlite.reset(stmt) end sqlite.finalize(stmt) end do -- Using prepared statement in simplified way -- Statement prepared and finalized automatically local another_data = { { name = 'John', age = 24 }; { name = 'Steve', age = 32 }; { name = 'Gary', age = 26 }; } code = sqlite.using_stmt(db, 'INSERT INTO People (name, age) VALUES (?, ?);', function (db, stmt) for _, row in pairs(another_data) do sqlite.bind_text(stmt, 1, row.name) sqlite.bind_int(stmt, 2, row.age) sqlite.step(stmt) sqlite.reset(stmt) end end) end do -- Retrieving results from query in loop -- Statement managed fully automatically print('All people: ') for stmt in sqlite.using_stmt_iter(db, 'SELECT id, name, age FROM People;') do print(sqlite.column_int(stmt, 0), sqlite.column_text(stmt, 1), sqlite.column_int(stmt, 2)) end end do -- Retrieving results from query in callback -- Statement managed fully automatically -- Invokes callback for every result row print('Older than 27 years: ') sqlite.using_stmt_loop(db, 'SELECT name, age FROM People WHERE age > 27;', function (db, stmt) print(sqlite.column_text(stmt, 0), sqlite.column_int(stmt, 1)) end) end do -- Retrieving results from manualy prepared statement in loop local code, stmt = sqlite.prepare_v2(db, [[ SELECT name, age FROM People WHERE age < 27; ]]) print('Younger than 27 years: ') for _ in sqlite.stmt_iter(stmt) do print(sqlite.column_text(stmt, 0), sqlite.column_int(stmt, 1)) end stmt:finalize() end do -- Retrieving results from manualy prepared statement in callback -- Invokes callback for every result row local code, stmt = sqlite.prepare_v2(db, [[ SELECT name, age FROM People WHERE age == 27; ]]) print('Exact 27 years: ') sqlite.stmt_loop(stmt, function (stmt) print(sqlite.column_text(stmt, 0), sqlite.column_int(stmt, 1)) end) stmt:finalize() end db:close()
mit
waylon531/RogueRacing
libs/LOVEly-tiles-master/drawlist.lua
3
3936
local getIndex = function(self,the_layer) for i,layer in ipairs(self.layers) do if layer == the_layer then return i end end end local t = setmetatable({},{__call = function(self,...) return self.new(...) end}) t.__call = function(self,name) return self:getLayer(name) end t.__index = t function t.new() local d = { layers = {}, settings = {}, x = 0, y = 0, properties= {}, atlases = {}, } return setmetatable(d,t) end function t:getLayer(name) return self.settings[name] and self.settings[name].layer end function t:insert(name,layer,xtranscale,ytranscale,isDrawable) xtranscale= xtranscale or 1 ytranscale= ytranscale or xtranscale table.insert(self.layers,layer) local t = self.settings[name] or {} self.settings[name] = t self.settings[layer]= t t.isDrawable = isDrawable== nil and true or isDrawable t.xtranscale = xtranscale t.ytranscale = ytranscale t.layer = layer end function t:remove(name) local the_layer = self:getLayer(name) for i,layer in ipairs(self.layers) do if layer == the_layer then table.remove(self.layers,i) break end end self.settings[name] = nil self.settings[the_layer] = nil return the_layer end function t:clear() self.layers = {} self.settings = {} self.x,self.y = 0,0 end function t:swap(name1,name2) local layer1 = self:getLayer(name1) local layer2 = self:getLayer(name2) local i1,i2 for i,layer in ipairs(self.layers) do if layer == layer1 then i1 = i end if layer == layer2 then i2 = i end if i1 and i2 then break end end self.layers[i1],self.layers[i2] = layer2,layer1 end local directions = { down = function(layers,index) if index < 1 then return end layers[index-1],layers[index] = layers[index],layers[index-1] end, up = function(layers,index) if index == #layers then return end layers[index+1],layers[index] = layers[index],layers[index+1] end, top = function(layers,index) table.insert(layers, table.remove(layers,index) ) end, bottom = function(layers,index) table.insert(layers, 1, table.remove(layers,index) ) end, } function t:move(name,direction) assert(directions[direction],'Invalid direction') local index = getIndex(self:getLayer(name)) directions[direction](self.layers,index) end function t:sort(func) table.sort(self.layers,func) end function t:setDrawable(name,bool) if bool == nil then error('expected true or false for drawable') end self.settings[name].isDrawable = bool end function t:isDrawable(name) return self.settings[name].isDrawable end function t:translate(dx,dy) self.x,self.y = self.x+dx,self.y+dy end function t:setTranslation(x,y) self.x,self.y = x,y end function t:getTranslation() return self.x,self.y end function t:setTranslationScale(name,xscale,yscale) self.settings[name].xtranscale = xscale self.settings[name].ytranscale = yscale or xscale end function t:getTranslationScale(name) return self.settings[name].xtranscale, self.settings[name].ytranscale end function t:iterate() return ipairs(self.layers) end function t:callback(callback_name,...) if callback_name == 'draw' then return t.draw(self,...) end for i,layer in ipairs(self.layers) do if layer[callback_name] then layer[callback_name](layer,...) end end end function t:draw(...) local set = self.settings for i,layer in ipairs(self.layers) do love.graphics.push() local xscale = self.settings[layer].xtranscale local yscale = self.settings[layer].ytranscale local dx,dy = xscale*self.x, yscale*self.y love.graphics.translate(dx,dy) if set[layer].isDrawable then if layer.draw then layer:draw(...) end end love.graphics.pop() end end -- #################################### -- TMX RELATED FUNCTIONS -- #################################### function t:getAtlas(name) return self.atlases[name] end function t:getMapProperties() return self.properties end return t
mit
czfshine/Don-t-Starve
data/DLC0001/scripts/prefabs/rubble.lua
1
3268
local assets = { Asset("ANIM", "anim/ruins_rubble.zip"), } local prefabs = { "rocks", "thulecite", "cutstone", "trinket_6", "gears", "nightmarefuel", "greengem", "orangegem", "yellowgem", "collapse_small", } local function workcallback(inst, worker, workleft) local pt = Point(inst.Transform:GetWorldPosition()) if workleft <= 0 then inst.SoundEmitter:PlaySound("dontstarve/wilson/rock_break") inst.components.lootdropper:DropLoot() SpawnPrefab("collapse_small").Transform:SetPosition(inst.Transform:GetWorldPosition()) inst:Remove() else if workleft < TUNING.ROCKS_MINE*(1/3) then inst.AnimState:PlayAnimation("low") elseif workleft < TUNING.ROCKS_MINE*(2/3) then inst.AnimState:PlayAnimation("med") else inst.AnimState:PlayAnimation("full") end end end local function common_fn() local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() inst.entity:AddSoundEmitter() inst.AnimState:SetBank("rubble") inst.AnimState:SetBuild("ruins_rubble") MakeObstaclePhysics(inst, 1.) --local minimap = inst.entity:AddMiniMapEntity() --minimap:SetIcon( "rock.png" ) inst:AddComponent("lootdropper") inst.components.lootdropper:SetLoot({"rocks"}) inst.components.lootdropper.numrandomloot = 1 inst.components.lootdropper:AddRandomLoot("rocks" , 0.99) inst.components.lootdropper:AddRandomLoot("cutstone" , 0.10) inst.components.lootdropper:AddRandomLoot("trinket_6" , 0.10) -- frayed wires inst.components.lootdropper:AddRandomLoot("gears" , 0.01) inst.components.lootdropper:AddRandomLoot("greengem" , 0.01) inst.components.lootdropper:AddRandomLoot("yellowgem" , 0.01) inst.components.lootdropper:AddRandomLoot("orangegem" , 0.01) inst.components.lootdropper:AddRandomLoot("nightmarefuel" , 0.01) if GetWorld() and GetWorld():IsCave() and GetWorld().topology.level_number == 2 then -- ruins inst.components.lootdropper:AddRandomLoot("thulecite" , 0.01) end inst:AddComponent("workable") inst.components.workable:SetWorkAction(ACTIONS.MINE) inst.components.workable:SetOnWorkCallback(workcallback) inst:AddComponent("inspectable") inst.components.inspectable.nameoverride = "rubble" MakeSnowCovered(inst, .01) return inst end local function rubble_fn(Sim) local inst = common_fn() inst.AnimState:PlayAnimation("full") inst.components.workable:SetWorkLeft(TUNING.ROCKS_MINE) return inst end local function rubble_med_fn(Sim) local inst = common_fn() inst.AnimState:PlayAnimation("med") inst.components.workable:SetWorkLeft(TUNING.ROCKS_MINE) inst.components.workable:WorkedBy(inst, TUNING.ROCKS_MINE * 0.34) return inst end local function rubble_low_fn(Sim) local inst = common_fn() inst.AnimState:PlayAnimation("low") inst.components.workable:SetWorkLeft(TUNING.ROCKS_MINE) inst.components.workable:WorkedBy(inst, TUNING.ROCKS_MINE * 0.67) return inst end return Prefab("cave/objects/rocks/rubble", rubble_fn, assets, prefabs), Prefab("forest/objects/rocks/rubble_med", rubble_med_fn, assets, prefabs), Prefab("forest/objects/rocks/rubble_low", rubble_low_fn, assets, prefabs)
gpl-2.0
nvoron23/tarantool
src/lua/fio.lua
1
4841
-- fio.lua (internal file) local fio = require('fio') local ffi = require('ffi') ffi.cdef[[ int umask(int mask); char *dirname(char *path); ]] local internal = fio.internal fio.internal = nil local function sprintf(fmt, ...) if select('#', ...) == 0 then return fmt end return string.format(fmt, ...) end local fio_methods = {} fio_methods.read = function(self, size) if size == nil then return '' end return internal.read(self.fh, tonumber(size)) end fio_methods.write = function(self, data) data = tostring(data) local res = internal.write(self.fh, data, #data) return res >= 0 end fio_methods.pwrite = function(self, data, offset) data = tostring(data) local len = #data if len == 0 then return true end if offset == nil then offset = 0 else offset = tonumber(offset) end local res = internal.pwrite(self.fh, data, len, offset) return res >= 0 end fio_methods.pread = function(self, len, offset) if len == nil then return '' end if offset == nil then offset = 0 end return internal.pread(self.fh, tonumber(len), tonumber(offset)) end fio_methods.truncate = function(self, length) if length == nil then length = 0 end return internal.ftruncate(self.fh, length) end fio_methods.seek = function(self, offset, whence) if whence == nil then whence = 'SEEK_SET' end if type(whence) == 'string' then if fio.c.seek[whence] == nil then error(sprintf("Unknown whence: %s", whence)) end whence = fio.c.seek[whence] else whence = tonumber(whence) end local res = internal.lseek(self.fh, tonumber(offset), whence) if res < 0 then return nil end return tonumber(res) end fio_methods.close = function(self) return internal.close(self.fh) end fio_methods.fsync = function(self) return internal.fsync(self.fh) end fio_methods.fdatasync = function(self) return internal.fdatasync(self.fh) end fio_methods.stat = function(self) return internal.fstat(self.fh) end local fio_mt = { __index = fio_methods } fio.open = function(path, flags, mode) local iflag = 0 local imode = 0 if type(flags) ~= 'table' then flags = { flags } end if type(mode) ~= 'table' then mode = { mode } end for _, flag in pairs(flags) do if type(flag) == 'number' then iflag = bit.bor(iflag, flag) else if fio.c.flag[ flag ] == nil then error(sprintf("Unknown flag: %s", flag)) end iflag = bit.bor(iflag, fio.c.flag[ flag ]) end end for _, m in pairs(mode) do if type(m) == 'string' then if fio.c.mode[m] == nil then error(sprintf("Unknown mode: %s", m)) end imode = bit.bor(imode, fio.c.mode[m]) else imode = bit.bor(imode, tonumber(m)) end end local fh = internal.open(tostring(path), iflag, imode) if fh < 0 then return nil end fh = { fh = fh } setmetatable(fh, fio_mt) return fh end fio.pathjoin = function(path, ...) path = tostring(path) if path == nil or path == '' then error("Empty path part") end for i = 1, select('#', ...) do if string.match(path, '/$') ~= nil then path = string.gsub(path, '/$', '') end local sp = select(i, ...) if sp == nil then error("Undefined path part") end if sp == '' or sp == '/' then error("Empty path part") end if string.match(sp, '^/') ~= nil then sp = string.gsub(sp, '^/', '') end if sp ~= '' then path = path .. '/' .. sp end end if string.match(path, '/$') ~= nil and #path > 1 then path = string.gsub(path, '/$', '') end return path end fio.basename = function(path, suffix) if path == nil then return nil end path = tostring(path) path = string.gsub(path, '.*/', '') if suffix ~= nil then suffix = tostring(suffix) if #suffix > 0 then suffix = string.gsub(suffix, '(.)', '[%1]') path = string.gsub(path, suffix, '') end end return path end fio.dirname = function(path) if path == nil then return nil end path = tostring(path) path = ffi.new('char[?]', #path, path) return ffi.string(ffi.C.dirname(path)) end fio.umask = function(umask) if umask == nil then local old = ffi.C.umask(0) ffi.C.umask(old) return old end umask = tonumber(umask) return ffi.C.umask(tonumber(umask)) end return fio
bsd-2-clause
CrazyEddieTK/Zero-K
units/chicken_digger_b.lua
5
3435
unitDef = { unitname = [[chicken_digger_b]], name = [[Digger (burrowed)]], description = [[Burrowing Scout/Raider]], acceleration = 0.26, activateWhenBuilt = false, brakeRate = 0.205, buildCostEnergy = 0, buildCostMetal = 0, builder = false, buildPic = [[chicken_digger.png]], buildTime = 40, canGuard = true, canMove = true, canPatrol = true, category = [[LAND BURROWED]], customParams = { statsname = "chicken_digger", }, explodeAs = [[SMALL_UNITEX]], fireState = 1, floater = false, footprintX = 2, footprintZ = 2, iconType = [[chicken]], idleAutoHeal = 20, idleTime = 300, leaveTracks = false, maxDamage = 180, maxSlope = 72, maxVelocity = 0.9, maxWaterDepth = 15, minCloakDistance = 75, movementClass = [[TKBOT2]], noAutoFire = false, noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE GUNSHIP SUB]], objectName = [[chicken_digger_b.s3o]], onoffable = true, power = 40, selfDestructAs = [[SMALL_UNITEX]], sfxtypes = { explosiongenerators = { [[custom:emg_shells_l]], [[custom:flashmuzzle1]], [[custom:dirt]], }, }, sightDistance = 0, stealth = true, trackOffset = 0, trackStrength = 6, trackStretch = 1, trackType = [[ComTrack]], trackWidth = 18, turnRate = 806, upright = false, waterline = 8, workerTime = 0, weapons = { { def = [[WEAPON]], mainDir = [[0 0 1]], maxAngleDif = 120, onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER]], }, }, weaponDefs = { WEAPON = { name = [[Claws]], alphaDecay = 0.1, areaOfEffect = 8, colormap = [[1 0.95 0.4 1 1 0.95 0.4 1 0 0 0 0.01 1 0.7 0.2 1]], craterBoost = 0, craterMult = 0, damage = { default = 80, planes = 80, subs = 4, }, explosionGenerator = [[custom:EMG_HIT]], impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, intensity = 0.7, interceptedByShieldType = 1, noGap = false, noSelfDamage = true, range = 100, reloadtime = 1.2, rgbColor = [[1 0.95 0.4]], separation = 1.5, size = 1.75, sizeDecay = 0, soundHit = [[chickens/chickenbig2]], soundStart = [[chickens/chicken]], sprayAngle = 1180, stages = 10, targetborder = 1, tolerance = 5000, turret = true, weaponType = [[Cannon]], weaponVelocity = 500, }, }, } return lowerkeys({ chicken_digger_b = unitDef })
gpl-2.0
TimSimpson/Macaroni
Next/Tests/Features/ConstructorOverloading/manifest.lua
2
1048
require "os" require "Macaroni.Model.Library" upper = getUpperLibrary(); id = { group=upper.Group, name=upper.Name .. ".LanguageFeatures.ConstructorOverloading", version=upper.Version } description="Proof of concept which overloads the Constructor of a class in various ways." -- source "Source" -- output = "GeneratedSource" dependency {group="Macaroni", name="Boost-filesystem", version="1.52"} dependency {group="Macaroni", name="Boost-smart_ptr", version="1.52"} dependency {group="Macaroni", name="CppStd", version="2003"} function generate() print "A call was made to GENERATE!!!\n\n" run("HtmlView"); run "InterfaceMh" run "Cpp" end jamArgs = { ExcludePattern = "Main.cpp .svn *Test.cpp", Tests = {"Test.cpp"} }; function build() run("BoostBuild", jamArgs) end function test() print("HI") -- args = { ExcludePattern=jamArgs.ExcludePattern, -- ExtraTargets=jamArgs.ExtraTargets, -- --CmdLine="test" -- } run("BoostBuild", jamArgs); -- args); end function install() end
apache-2.0
CrazyEddieTK/Zero-K
LuaUI/Widgets/dbg_devcommands.lua
4
12448
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Dev Commands", desc = "v0.011 Dev Commands", author = "CarRepairer", date = "2011-11-17", license = "GPLv2", layer = 5, enabled = false, -- loaded by default? } end VFS.Include("LuaRules/Configs/customcmds.h.lua") -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Mission Creation local recentlyExported = false local BUILD_RESOLUTION = 16 local function SanitizeBuildPositon(x, z, ud, facing) local oddX = (ud.xsize % 4 == 2) local oddZ = (ud.zsize % 4 == 2) if facing % 2 == 1 then oddX, oddZ = oddZ, oddX end if oddX then x = math.floor((x + 8)/BUILD_RESOLUTION)*BUILD_RESOLUTION - 8 else x = math.floor(x/BUILD_RESOLUTION)*BUILD_RESOLUTION end if oddZ then z = math.floor((z + 8)/BUILD_RESOLUTION)*BUILD_RESOLUTION - 8 else z = math.floor(z/BUILD_RESOLUTION)*BUILD_RESOLUTION end return x, z end local function GetUnitFacing(unitID) return math.floor(((Spring.GetUnitHeading(unitID) or 0)/16384 + 0.5)%4) end local function GetFeatureFacing(unitID) return math.floor(((Spring.GetFeatureHeading(unitID) or 0)/16384 + 0.5)%4) end local commandNameMap = { [CMD.PATROL] = "PATROL", [CMD_RAW_MOVE] = "RAW_MOVE", [CMD_JUMP] = "JUMP", [CMD.ATTACK] = "ATTACK", [CMD.MOVE] = "MOVE", [CMD.GUARD] = "GUARD", [CMD.FIGHT] = "FIGHT", } local function GetCommandString(index, command) local cmdID = command.id if not commandNameMap[cmdID] then return end if not (command.params[1] and command.params[3]) then return end local commandString = [[{cmdID = planetUtilities.COMMAND.]] .. commandNameMap[cmdID] commandString = commandString .. [[, pos = {]] .. math.floor(command.params[1]) .. ", " .. math.floor(command.params[3]) .. [[}]] if index > 1 then commandString = commandString .. [[, options = {"shift"}]] end return commandString .. [[},]] end local function ProcessUnitCommands(inTabs, commands, unitID, mobileUnit) if mobileUnit and ((commands[1] and commands[1].id == CMD.PATROL) or (commands[2] and commands[2].id == CMD.PATROL)) then local fullCommandString for i = 1, #commands do local command = commands[i] if command.id == CMD.PATROL and command.params[1] and command.params[3] then fullCommandString = (fullCommandString or "") .. inTabs .. "\t" .. [[{]] .. math.floor(command.params[1]) .. ", " .. math.floor(command.params[3]) .. [[},]] .. "\n" end end if fullCommandString then return inTabs .. [[patrolRoute = {]] .. "\n" .. fullCommandString .. inTabs .. "},\n" end end local fullCommandString for i = 1, #commands do local commandString = GetCommandString(i, commands[i]) if commandString then fullCommandString = (fullCommandString or "") .. inTabs .. "\t" .. commandString .. "\n" end end if fullCommandString then return inTabs .. [[commands = {]] .. "\n" .. fullCommandString .. inTabs .. "},\n" end end local function GetUnitString(unitID, tabs, sendCommands) local ud = UnitDefs[Spring.GetUnitDefID(unitID)] local x, y, z = Spring.GetUnitPosition(unitID) local facing = 0 if ud.isImmobile then facing = Spring.GetUnitBuildFacing(unitID) x, z = SanitizeBuildPositon(x, z, ud, facing) else facing = GetUnitFacing(unitID) end local build = select(5, Spring.GetUnitHealth(unitID)) local inTabs = tabs .. "\t\t" local unitString = tabs .. "\t{\n" unitString = unitString .. inTabs .. [[name = "]] .. ud.name .. [[",]] .. "\n" unitString = unitString .. inTabs .. [[x = ]] .. math.floor(x) .. [[,]] .. "\n" unitString = unitString .. inTabs .. [[z = ]] .. math.floor(z) .. [[,]] .. "\n" unitString = unitString .. inTabs .. [[facing = ]] .. facing .. [[,]] .. "\n" if build and build < 1 then unitString = unitString .. inTabs .. [[buildProgress = ]] .. math.floor(build*10000)/10000 .. [[,]] .. "\n" end if ud.isImmobile then local origHeight = Spring.GetGroundOrigHeight(x, z) if ud.floatOnWater and (origHeight < 0) then origHeight = 0 end if math.abs(origHeight - y) > 5 then unitString = unitString .. inTabs .. [[terraformHeight = ]] .. math.floor(y) .. [[,]] .. "\n" end end if sendCommands then local commands = Spring.GetUnitCommands(unitID, -1) if commands and #commands > 0 then local commandString = ProcessUnitCommands(inTabs, commands, unitID, not ud.isImmobile) if commandString then unitString = unitString .. commandString end end end return unitString .. tabs .. "\t}," end local function GetFeatureString(fID) local fx, _, fz = Spring.GetFeaturePosition(fID) local fd = FeatureDefs[Spring.GetFeatureDefID(fID)] local tabs = "\t\t\t\t" local inTabs = tabs .. "\t" local unitString = tabs .. "{\n" unitString = unitString .. inTabs .. [[name = "]] .. fd.name .. [[",]] .. "\n" unitString = unitString .. inTabs .. [[x = ]] .. math.floor(fx) .. [[,]] .. "\n" unitString = unitString .. inTabs .. [[z = ]] .. math.floor(fz) .. [[,]] .. "\n" unitString = unitString .. inTabs .. [[facing = ]] .. GetFeatureFacing(fID) .. [[,]] .. "\n" return unitString .. tabs.. "}," end local function ExportTeamUnitsForMission(teamID, sendCommands) local units = Spring.GetTeamUnits(teamID) if not (units and #units > 0) then return end local tabs = (teamID == 0 and "\t\t\t\t") or "\t\t\t\t\t" Spring.Echo("====== Unit export team " .. (teamID or "??") .. " ======") for i = 1, 20 do Spring.Echo("= - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - =") end local unitsString = tabs .. "startUnits = {\n" for i = 1, #units do Spring.Echo(GetUnitString(units[i], tabs, sendCommands)) end --unitsString = unitsString .. tabs .. "}" --Spring.Echo(unitsString) end local function ExportUnitsForMission(sendCommands) if recentlyExported then return end local teamList = Spring.GetTeamList() Spring.Echo("================== ExportUnitsForMission ==================") for i = 1, #teamList do ExportTeamUnitsForMission(teamList[i], sendCommands) end recentlyExported = 1 end local function ExportUnitsAndCommandsForMission() ExportUnitsForMission(true) end local function ExportFeaturesForMission() Spring.Echo("================== ExportFeaturesForMission ==================") local features = Spring.GetAllFeatures() for i = 1, #features do Spring.Echo(GetFeatureString(features[i])) end end local unitToMove = 0 local recentlyMovedUnit = false local function MoveUnitRaw(snap) local units = Spring.GetSelectedUnits() if not (units and units[1]) then return end if not recentlyMovedUnit then unitToMove = unitToMove + 1 if unitToMove > #units then unitToMove = 1 end recentlyMovedUnit = options.moveUnitDelay.value end local unitID = units[unitToMove] local unitDefID = Spring.GetUnitDefID(unitID) local ud = unitDefID and UnitDefs[unitDefID] if not ud then return end local mx, my = Spring.GetMouseState() local trace, pos = Spring.TraceScreenRay(mx, my, true, false, false, true) if not (trace == "ground" and pos) then return end local x, z = math.floor(pos[1]), math.floor(pos[3]) if snap or ud.isImmobile then local facing = Spring.GetUnitBuildFacing(unitID) x, z = SanitizeBuildPositon(x, z, ud, facing) end Spring.SendCommands("luarules moveunit " .. unitID .. " " .. x .. " " .. z) end local function MoveUnit() MoveUnitRaw(false) end local function MoveUnitSnap() MoveUnitRaw(true) end local function DestroyUnit() local units = Spring.GetSelectedUnits() if not units then return end for i = 1, #units do Spring.SendCommands("luarules destroyunit " .. units[i]) end end local function RotateUnit(add) local units = Spring.GetSelectedUnits() if not units then return end for i = 1, #units do local unitDefID = Spring.GetUnitDefID(units[i]) local ud = unitDefID and UnitDefs[unitDefID] if ud then local facing if ud.isImmobile then facing = Spring.GetUnitBuildFacing(units[i]) else facing = GetUnitFacing(units[i]) end facing = (facing + add)%4 Spring.SendCommands("luarules rotateunit " .. units[i] .. " " .. facing) end end end local function RotateUnitLeft() RotateUnit(1) end local function RotateUnitRight() RotateUnit(-1) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:Update(dt) if recentlyExported then recentlyExported = recentlyExported - dt if recentlyExported < 0 then recentlyExported = false end end if recentlyMovedUnit then recentlyMovedUnit = recentlyMovedUnit - dt if recentlyMovedUnit < 0 then recentlyMovedUnit = false end end end local doCommandEcho = false function widget:CommandNotify(cmdID, params, options) if doCommandEcho then Spring.Echo("cmdID", cmdID) Spring.Utilities.TableEcho(params, "params") Spring.Utilities.TableEcho(options, "options") end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- options_path = 'Settings/Toolbox/Dev Commands' options = { cheat = { name = "Cheat", type = 'button', action = 'cheat', }, nocost = { name = "No Cost", type = 'button', action = 'nocost', }, spectator = { name = "Spectator", type = 'button', action = 'spectator', }, godmode = { name = "Godmode", type = 'button', action = 'godmode', }, testunit = { name = "Spawn Testunit", type = 'button', action = 'give testunit', }, luauireload = { name = "Reload LuaUI", type = 'button', action = 'luaui reload', }, luarulesreload = { name = "Reload LuaRules", type = 'button', action = 'luarules reload', }, debug = { name = "Debug", type = 'button', action = 'debug', }, debugcolvol = { name = "Debug Colvol", type = 'button', action = 'debugcolvol', }, debugpath = { name = "Debug Path", type = 'button', action = 'debugpath', }, singlestep = { name = "Single Step", type = 'button', action = 'singlestep', }, printunits = { name = "Print Units", type = 'button', OnChange = function(self) for i=1,#UnitDefs do local ud = UnitDefs[i] local name = ud.name Spring.Echo("'" .. name .. "',") end end, }, printunitnames = { name = "Print Unit Names", type = 'button', OnChange = function(self) for i=1,#UnitDefs do local ud = UnitDefs[i] local name = ud.humanName Spring.Echo("'" .. name .. "',") end end, }, echoCommand = { name = 'Echo Given Commands', type = 'bool', value = false, OnChange = function(self) doCommandEcho = self.value end, }, missionexport = { name = "Mission Units Export", type = 'button', action = 'mission_units_export', OnChange = ExportUnitsForMission, }, missionexportcommands = { name = "Mission Unit Export (Commands)", type = 'button', action = 'mission_unit_commands_export', OnChange = ExportUnitsAndCommandsForMission, }, missionexportfeatures = { name = "Mission Feature Export", type = 'button', action = 'mission_features_export', OnChange = ExportFeaturesForMission, }, moveUnit = { name = "Move Unit", desc = "Move selected unit to the mouse cursor.", type = 'button', action = 'debug_move_unit', OnChange = MoveUnit, }, moveUnitSnap = { name = "Move Unit Snap", desc = "Move selected unit to the mouse cursor. Snaps to grid.", type = 'button', action = 'debug_move_unit_snap', OnChange = MoveUnitSnap, }, moveUnitDelay = { name = "Move Unit Repeat Time", type = "number", value = 0.1, min = 0.01, max = 0.4, step = 0.01, }, destroyUnit = { name = "Destroy Units", desc = "Destroy selected units (gentle).", type = 'button', action = 'debug_destroy_unit', OnChange = DestroyUnit, }, RotateUnitLeft = { name = "Rotate Unit Anticlockwise", type = 'button', action = 'debug_rotate_unit_anticlockwise', OnChange = RotateUnitLeft, }, RotateUnitRight = { name = "Rotate Unit Clockwise", type = 'button', action = 'debug_rotate_unit_clockwise', OnChange = RotateUnitRight, }, }
gpl-2.0
timroes/awesome
tests/test-spawn-snid.lua
8
1615
--- Tests for spawn's startup notifications. local runner = require("_runner") local test_client = require("_client") local manage_called, c_snid client.connect_signal("manage", function(c) manage_called = true c_snid = c.startup_id assert(c.machine == awesome.hostname, tostring(c.machine) .. " ~= " .. tostring(awesome.hostname)) end) local snid local num_callbacks = 0 local function callback(c) assert(c.startup_id == snid) num_callbacks = num_callbacks + 1 end local steps = { function(count) if count == 1 then snid = test_client("foo", "bar", true) elseif manage_called then assert(snid) assert(snid == c_snid) return true end end, -- Test that c.startup_id is nil for a client without startup notifications, -- and especially not the one from the previous spawn. function(count) if count == 1 then manage_called = false test_client("bar", "foo", false) elseif manage_called then assert(c_snid == nil, "c.startup_snid should be nil!") return true end end, function(count) if count == 1 then manage_called = false snid = test_client("baz", "barz", false, callback) elseif manage_called then assert(snid) assert(snid == c_snid) assert(num_callbacks == 1, num_callbacks) return true end end, } runner.run_steps(steps) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
CrazyEddieTK/Zero-K
LuaUI/Widgets/api_i18n.lua
6
3402
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --[[ Example: local tr local hellWorld function widget:Initialize() tr=WG.initializeTranslation(GetInfo().name,langCallback) hellWorld=tr("helloworld") end ... ... function foo() Spring.Echo(hellWorld) end ... ... function langCallback() hellWorld=tr("helloworld") end ]]-- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "i18n", desc = "Internationalization library for Spring", author = "gajop banana_Ai", date = "WIP", license = "GPLv2", version = "0.1", layer = -math.huge, enabled = true, -- loaded by default? handler = true, api = true, alwaysStart = true, } end VFS.Include("LuaUI/Utilities/json.lua"); local langValue="en" local langListeners={} local translationExtras = { -- lists databases to be merged into the main one units = {"campaign_units", "pw_units"}, interface = {"common", "healthbars", "resbars"}, } local translations = { units = true, interface = true, missions = true, } local function addListener(l, widgetName) if l and type(l)=="function" then local okay, err = pcall(l) if okay then langListeners[widgetName]=l else Spring.Echo("i18n API subscribe failed: " .. widgetName .. "\nCause: " .. err) end end end local function loadLocale(i18n,database,locale) local path="Luaui/Configs/lang/"..database.."."..locale..".json" if VFS.FileExists(path, VFS.ZIP) then local lang=Spring.Utilities.json.decode(VFS.LoadFile(path, VFS.ZIP)) local t={} t[locale]=lang i18n.load(t) return true end Spring.Echo("Cannot load locale \""..locale.."\" for "..database) return false end local function fireLangChange() for db, trans in pairs(translations) do if not trans.locales[langValue] then local extras = translationExtras[db] if extras then for i = 1, #extras do loadLocale(trans.i18n, extras[i], langValue) end end loadLocale(trans.i18n, db, langValue) trans.locales[langValue] = true end trans.i18n.setLocale(langValue) end for w,f in pairs(langListeners) do local okay,err=pcall(f) if not okay then Spring.Echo("i18n API update failed: " .. w .. "\nCause: " .. err) langListeners[w]=nil end end end local function lang (newLang) if not newLang then return langValue elseif langValue ~= newLang then langValue = newLang fireLangChange() end end local function initializeTranslation(database) local trans = { i18n = VFS.Include("LuaUI/i18nlib/i18n/init.lua", nil, VFS.DEF_MODE), locales = {en = true}, } loadLocale(trans.i18n,database,"en") local extras = translationExtras[database] if extras then for i = 1, #extras do loadLocale(trans.i18n, extras[i], "en") end end return trans end local function shutdownTranslation(widget_name) langListeners[widget_name]=nil end local function Translate (db, text, data) return translations[db].i18n(text, data) end WG.lang = lang WG.InitializeTranslation = addListener WG.ShutdownTranslation = shutdownTranslation WG.Translate = Translate for db in pairs(translations) do translations[db] = initializeTranslation (db) end
gpl-2.0
ETegro/Inquisitor
client/remotetesting/luas/several_lvm.lua
1
3725
--[[ aStor2 -- storage area network configurable via Web-interface Copyright (C) 2009-2012 ETegro Technologies, PLC Vladimir Petukhov <vladimir.petukhov@etegro.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] TestCreate = {} PS_IDS = nil function TestCreate:test_get_physicals() local physicals = einarc.Physical.list() PS_IDS = common.keys( physicals ) assert( #PS_IDS > 0 ) end LOGICALS = nil function TestCreate:test_create_logicals() for _, physical_id in pairs( PS_IDS ) do einarc.Logical.add( "passthrough", { physical_id } ) print( physical_id ) end LOGICALS = einarc.Logical.list() assert( LOGICALS ) assertEquals( #common.keys( LOGICALS ), #PS_IDS ) end PHYSICAL_VOLUMES = nil function TestCreate:test_create_physical_volumes() for _, logical in pairs( LOGICALS ) do lvm.PhysicalVolume.create( logical.device ) print( logical.device ) end lvm.PhysicalVolume.rescan() PHYSICAL_VOLUMES = lvm.PhysicalVolume.list() assert( PHYSICAL_VOLUMES ) assertEquals( #common.keys( PHYSICAL_VOLUMES ), #common.keys( LOGICALS ) ) end VOLUME_GROUPS = nil function TestCreate:test_create_volume_groups() for _, physical_volume in pairs( PHYSICAL_VOLUMES ) do lvm.VolumeGroup.create( { physical_volume } ) print( physical_volume.device ) end lvm.PhysicalVolume.rescan() lvm.VolumeGroup.rescan() PHYSICAL_VOLUMES = lvm.PhysicalVolume.list() assert( PHYSICAL_VOLUMES ) VOLUME_GROUPS = lvm.VolumeGroup.list( PHYSICAL_VOLUMES ) assert( VOLUME_GROUPS ) assertEquals( #common.keys( VOLUME_GROUPS ), #common.keys( PHYSICAL_VOLUMES ) ) end LOGICAL_VOLUMES = nil function TestCreate:test_create_logical_volumes() local number_of_logical_volumes = 2 for _, volume_group in pairs( VOLUME_GROUPS ) do local max_logical_volumes = volume_group.total / volume_group.extent assert( number_of_logical_volumes <= max_logical_volumes ) local logical_volume_size = 1 * volume_group.extent for v = 1, number_of_logical_volumes do volume_group:logical_volume( random_name(), logical_volume_size ) print( volume_group.name ) end end lvm.LogicalVolume.rescan() LOGICAL_VOLUMES = lvm.LogicalVolume.list( VOLUME_GROUPS ) assert( LOGICAL_VOLUMES ) assertEquals( #common.keys( LOGICAL_VOLUMES ), ( #common.keys( VOLUME_GROUPS ) * number_of_logical_volumes ) ) end function TestCreate:test_create_iqns() for _, logical_volume in pairs( LOGICAL_VOLUMES ) do local access_pattern = scst.AccessPattern:new( { name = random_name(), targetdriver = "iscsi", lun = 1, enabled = true, readonly = false } ) access_pattern = access_pattern:save() access_pattern:bind( logical_volume.device ) scst.Daemon.apply() end local access_pattern = scst.AccessPattern.list() assert( access_pattern ) assertEquals( #common.keys( access_pattern ), #common.keys( LOGICAL_VOLUMES ) ) end LuaUnit:run( "TestCreate:test_get_physicals", "TestCreate:test_create_logicals", "TestCreate:test_create_physical_volumes", "TestCreate:test_create_volume_groups", "TestCreate:test_create_logical_volumes", "TestCreate:test_create_iqns" )
gpl-3.0
CrazyEddieTK/Zero-K
gamedata/modularcomms/weapons/torpedo.lua
17
1427
local name = "commweapon_torpedo" local weaponDef = { name = [[Torpedo Launcher]], areaOfEffect = 16, avoidFriendly = false, bouncerebound = 0.5, bounceslip = 0.5, burnblow = true, collideFriendly = false, craterBoost = 0, craterMult = 0, customParams = { badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[SWIM FIXEDWING LAND SUB SINK TURRET FLOAT SHIP GUNSHIP HOVER]], slot = [[5]], }, damage = { default = 220, subs = 220, }, explosionGenerator = [[custom:TORPEDO_HIT]], flightTime = 6, groundbounce = 1, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, model = [[wep_t_longbolt.s3o]], numbounce = 4, noSelfDamage = true, range = 330, reloadtime = 3.5, soundHit = [[explosion/wet/ex_underwater]], soundStart = [[weapon/torpedo]], startVelocity = 90, tracks = true, turnRate = 10000, turret = true, waterWeapon = true, weaponAcceleration = 25, weaponType = [[TorpedoLauncher]], weaponVelocity = 140, } return name, weaponDef
gpl-2.0
blueyed/awesome
spec/awful/keyboardlayout_spec.lua
11
3466
--------------------------------------------------------------------------- -- @author Uli Schlachter -- @copyright 2015 Uli Schlachter and Kazunobu Kuriyama --------------------------------------------------------------------------- local kb = require("awful.widget.keyboardlayout") describe("awful.widget.keyboardlayout get_groups_from_group_names", function() it("nil", function() assert.is_nil(kb.get_groups_from_group_names(nil)) end) local tests = { -- possible worst cases [""] = { }, ["empty"] = { }, ["empty(basic)"] = { }, -- contrived cases for robustness test ["pc()+de+jp+group()"] = { { file = "de", group_idx = 1 }, { file = "jp", group_idx = 1 } }, ["us(altgr-intl)"] = { { file = "us", group_idx = 1, section = "altgr-intl" } }, -- possible eight variations of a single term ["de"] = { { file = "de", group_idx = 1 } }, ["de:2" ] = { { file = "de", group_idx = 2 } }, ["de(nodeadkeys)"] = { { file = "de", group_idx = 1, section = "nodeadkeys" } }, ["de(nodeadkeys):2"] = { { file = "de", group_idx = 2, section = "nodeadkeys" } }, ["macintosh_vndr/de"] = { { file = "de", group_idx = 1, vendor = "macintosh_vndr" } }, ["macintosh_vndr/de:2"] = { { file = "de", group_idx = 2, vendor = "macintosh_vndr" } }, ["macintosh_vndr/de(nodeadkeys)"] = { { file = "de", group_idx = 1, vendor = "macintosh_vndr", section = "nodeadkeys" } }, ["macintosh_vndr/de(nodeadkeys):2"] = { { file = "de", group_idx = 2, vendor = "macintosh_vndr", section = "nodeadkeys" } }, -- multiple terms ["pc+de"] = { { file = "de", group_idx = 1 } }, ["pc+us+inet(evdev)+terminate(ctrl_alt_bksp)"] = { { file = "us", group_idx = 1 } }, ["pc(pc105)+us+group(caps_toggle)+group(ctrl_ac)"] = { { file = "us", group_idx = 1 } }, ["pc+us(intl)+inet(evdev)+group(win_switch)"] = { { file = "us", group_idx = 1, section = "intl" } }, ["macintosh_vndr/apple(alukbd)+macintosh_vndr/jp(usmac)"] = { { file = "jp", group_idx = 1, vendor = "macintosh_vndr", section = "usmac" }, }, -- multiple layouts ["pc+jp+us:2+inet(evdev)+capslock(hyper)"] = { { file = "jp", group_idx = 1 }, { file = "us", group_idx = 2 } }, ["pc+us+ru:2+de:3+ba:4+inet"] = { { file = "us", group_idx = 1 }, { file = "ru", group_idx = 2 }, { file = "de", group_idx = 3 }, { file = "ba", group_idx = 4 }, }, ["macintosh_vndr/apple(alukbd)+macintosh_vndr/jp(usmac)+macintosh_vndr/jp(mac):2+group(shifts_toggle)"] = { { file = "jp", group_idx = 1, vendor = "macintosh_vndr", section = "usmac" }, { file = "jp", group_idx = 2, vendor = "macintosh_vndr", section = "mac" }, }, } for arg, expected in pairs(tests) do it(arg, function() assert.is.same(expected, kb.get_groups_from_group_names(arg)) end) end end) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
timroes/awesome
spec/awful/keyboardlayout_spec.lua
11
3466
--------------------------------------------------------------------------- -- @author Uli Schlachter -- @copyright 2015 Uli Schlachter and Kazunobu Kuriyama --------------------------------------------------------------------------- local kb = require("awful.widget.keyboardlayout") describe("awful.widget.keyboardlayout get_groups_from_group_names", function() it("nil", function() assert.is_nil(kb.get_groups_from_group_names(nil)) end) local tests = { -- possible worst cases [""] = { }, ["empty"] = { }, ["empty(basic)"] = { }, -- contrived cases for robustness test ["pc()+de+jp+group()"] = { { file = "de", group_idx = 1 }, { file = "jp", group_idx = 1 } }, ["us(altgr-intl)"] = { { file = "us", group_idx = 1, section = "altgr-intl" } }, -- possible eight variations of a single term ["de"] = { { file = "de", group_idx = 1 } }, ["de:2" ] = { { file = "de", group_idx = 2 } }, ["de(nodeadkeys)"] = { { file = "de", group_idx = 1, section = "nodeadkeys" } }, ["de(nodeadkeys):2"] = { { file = "de", group_idx = 2, section = "nodeadkeys" } }, ["macintosh_vndr/de"] = { { file = "de", group_idx = 1, vendor = "macintosh_vndr" } }, ["macintosh_vndr/de:2"] = { { file = "de", group_idx = 2, vendor = "macintosh_vndr" } }, ["macintosh_vndr/de(nodeadkeys)"] = { { file = "de", group_idx = 1, vendor = "macintosh_vndr", section = "nodeadkeys" } }, ["macintosh_vndr/de(nodeadkeys):2"] = { { file = "de", group_idx = 2, vendor = "macintosh_vndr", section = "nodeadkeys" } }, -- multiple terms ["pc+de"] = { { file = "de", group_idx = 1 } }, ["pc+us+inet(evdev)+terminate(ctrl_alt_bksp)"] = { { file = "us", group_idx = 1 } }, ["pc(pc105)+us+group(caps_toggle)+group(ctrl_ac)"] = { { file = "us", group_idx = 1 } }, ["pc+us(intl)+inet(evdev)+group(win_switch)"] = { { file = "us", group_idx = 1, section = "intl" } }, ["macintosh_vndr/apple(alukbd)+macintosh_vndr/jp(usmac)"] = { { file = "jp", group_idx = 1, vendor = "macintosh_vndr", section = "usmac" }, }, -- multiple layouts ["pc+jp+us:2+inet(evdev)+capslock(hyper)"] = { { file = "jp", group_idx = 1 }, { file = "us", group_idx = 2 } }, ["pc+us+ru:2+de:3+ba:4+inet"] = { { file = "us", group_idx = 1 }, { file = "ru", group_idx = 2 }, { file = "de", group_idx = 3 }, { file = "ba", group_idx = 4 }, }, ["macintosh_vndr/apple(alukbd)+macintosh_vndr/jp(usmac)+macintosh_vndr/jp(mac):2+group(shifts_toggle)"] = { { file = "jp", group_idx = 1, vendor = "macintosh_vndr", section = "usmac" }, { file = "jp", group_idx = 2, vendor = "macintosh_vndr", section = "mac" }, }, } for arg, expected in pairs(tests) do it(arg, function() assert.is.same(expected, kb.get_groups_from_group_names(arg)) end) end end) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
unusualcrow/redead_reloaded
gamemode/events/fallout.lua
1
1514
local EVENT = {} EVENT.Chance = 0.50 EVENT.Type = EVENT_BAD EVENT.TimeText = {"30 seconds", "1 minute"} EVENT.Times = {30, 60} function EVENT:Start() local num = math.random(1, 2) EVENT.Delay = CurTime() + 15 EVENT.RadTime = CurTime() + EVENT.Times[num] + 15 EVENT.RadDelay = 0 for k, v in pairs(team.GetPlayers(TEAM_ARMY)) do v:Notice("Nuclear fallout contamination is imminent", GAMEMODE.Colors.White, 7) v:Notice("Enter a building to avoid radiation poisoning", GAMEMODE.Colors.White, 7, 2) v:Notice("The atmospheric fallout will subside in " .. EVENT.TimeText[num], GAMEMODE.Colors.White, 7, 15) v:Notice("Atmospheric radioactivity levels are now safe", GAMEMODE.Colors.White, 7, EVENT.Times[num] + 15) end timer.Simple(15, function() SetGlobalBool("Radiation", true) end) end function EVENT:Think() if EVENT.Delay < CurTime() then if EVENT.RadDelay < CurTime() then EVENT.RadDelay = CurTime() + 1 for k, v in pairs(team.GetPlayers(TEAM_ARMY)) do if not v:IsIndoors() then if math.random(1, 2) == 1 then v:EmitSound(table.Random(GAMEMODE.Geiger), 100, math.random(90, 110)) end if math.random(1, 5) == 1 then v:AddRadiation(1) end else if math.random(1, 6) == 1 then v:EmitSound(table.Random(GAMEMODE.Geiger), 100, math.random(120, 140)) end end end end end end function EVENT:EndThink() return EVENT.RadTime < CurTime() end function EVENT:End() SetGlobalBool("Radiation", false) end event.Register(EVENT)
mit
AllAboutEE/nodemcu-firmware
lua_examples/email/read_email_imap.lua
82
4543
--- -- Working Example: https://www.youtube.com/watch?v=PDxTR_KJLhc -- @author Miguel (AllAboutEE.com) -- @description This example will read the first email in your inbox using IMAP and -- display it through serial. The email server must provided unecrypted access. The code -- was tested with an AOL and Time Warner cable email accounts (GMail and other services who do -- not support no SSL access will not work). require("imap") local IMAP_USERNAME = "email@domain.com" local IMAP_PASSWORD = "password" -- find out your unencrypted imap server and port -- from your email provided i.e. google "[my email service] imap settings" for example local IMAP_SERVER = "imap.service.com" local IMAP_PORT = "143" local IMAP_TAG = "t1" -- You do not need to change this local IMAP_DEBUG = true -- change to true if you would like to see the entire conversation between -- the ESP8266 and IMAP server local SSID = "ssid" local SSID_PASSWORD = "password" local count = 0 -- we will send several IMAP commands/requests, this variable helps keep track of which one to send -- configure the ESP8266 as a station wifi.setmode(wifi.STATION) wifi.sta.config(SSID,SSID_PASSWORD) wifi.sta.autoconnect(1) -- create an unencrypted connection local imap_socket = net.createConnection(net.TCP,0) --- -- @name setup -- @description A call back function used to begin reading email -- upon sucessfull connection to the IMAP server function setup(sck) -- Set the email user name and password, IMAP tag, and if debugging output is needed imap.config(IMAP_USERNAME, IMAP_PASSWORD, IMAP_TAG, IMAP_DEBUG) imap.login(sck) end imap_socket:on("connection",setup) -- call setup() upon connection imap_socket:connect(IMAP_PORT,IMAP_SERVER) -- connect to the IMAP server local subject = "" local from = "" local message = "" --- -- @name do_next -- @description A call back function for a timer alarm used to check if the previous -- IMAP command reply has been processed. If the IMAP reply has been processed -- this function will call the next IMAP command function necessary to read the email function do_next() -- Check if the IMAP reply was processed if(imap.response_processed() == true) then -- The IMAP reply was processed if (count == 0) then -- After logging in we need to select the email folder from which we wish to read -- in this case the INBOX folder imap.examine(imap_socket,"INBOX") count = count + 1 elseif (count == 1) then -- After examining/selecting the INBOX folder we can begin to retrieve emails. imap.fetch_header(imap_socket,imap.get_most_recent_num(),"SUBJECT") -- Retrieve the SUBJECT of the first/newest email count = count + 1 elseif (count == 2) then subject = imap.get_header() -- store the SUBJECT response in subject imap.fetch_header(imap_socket,imap.get_most_recent_num(),"FROM") -- Retrieve the FROM of the first/newest email count = count + 1 elseif (count == 3) then from = imap.get_header() -- store the FROM response in from imap.fetch_body_plain_text(imap_socket,imap.get_most_recent_num()) -- Retrieve the BODY of the first/newest email count = count + 1 elseif (count == 4) then body = imap.get_body() -- store the BODY response in body imap.logout(imap_socket) -- Logout of the email account count = count + 1 else -- display the email contents -- create patterns to strip away IMAP protocl text from actual message pattern1 = "(\*.+\}\r\n)" -- to remove "* n command (BODY[n] {n}" pattern2 = "(%)\r\n.+)" -- to remove ") t1 OK command completed" from = string.gsub(from,pattern1,"") from = string.gsub(from,pattern2,"") print(from) subject = string.gsub(subject,pattern1,"") subject = string.gsub(subject,pattern2,"") print(subject) body = string.gsub(body,pattern1,"") body = string.gsub(body,pattern2,"") print("Message: " .. body) tmr.stop(0) -- Stop the timer alarm imap_socket:close() -- close the IMAP socket collectgarbage() -- clean up end end end -- A timer alarm is sued to check if an IMAP reply has been processed tmr.alarm(0,1000,1, do_next)
mit
TimSimpson/Macaroni
Main/App/Source/main/lua/ReplCommand.lua
2
4796
-------------------------------------------------------------------------------- -- Copyright 2011 Tim Simpson -- -- 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. -------------------------------------------------------------------------------- -- Generates the REPL handler. require "Macaroni.Model.AnnotationTable"; require "Macaroni.Model.AnnotationValue"; require "Macaroni.Model.Context"; require "Macaroni.Model.FileName"; require "Macaroni.IO.GeneratedFileWriter"; require "Macaroni.IO.Path"; require "Macaroni.Model.Source"; if Macaroni == nil then FileName = require "Macaroni.Model.FileName"; Source = require "Macaroni.Model.Source"; else -- lua 5.1 FileName = Macaroni.Model.FileName; Source = Macaroni.Model.Source; end findFunctions = function(node) if (node == nil) then error("Node cannot be nil.", 2); end local rtn = {}; for i = 1, #node.Children do local child = node.Children[i]; if (child.Member ~= nil and child.Member.TypeName == "Function") then for j = 1, #child.Children do local fon = child.Children[j]; -- FunctionOverload node if (fon.Member ~= nil and fon.Member.TypeName == 'FunctionOverload') then local attr = fon.Annotations[ "Macaroni::Environment::ReplCommand"]; if attr ~= nil then rtn[#rtn + 1] = { fon=fon, name=attr.ValueAsTable["Name"].ValueAsString, summary=attr.ValueAsTable["Summary"].ValueAsString, } end end end end end return rtn; end function GetMethod(name) if name == "Generate" then return { Run = function(args) G2(args.context) end }; end end function Generate(library, path) local context = library.Context; G2(context) end function G2(context) local root = context.Root; local node = root:Find("Macaroni::Environment::Environment"); local fns = findFunctions(node) -- local newFuncNode= node:FindOrCreate("replCommand"); -- local axiom = Axiom.LuaCreate("Macaroni::Environment::ReplCommand") local source = nil; if MACARONI_VERSION == "0.1.0.23" then source = Source.Create(FileName.Create("ReplCommand.lua"), 0, 0); else source = Source.Create(FileName.CreateNonPhysical("ReplCommand.lua"), 0, 0); end -- local reason = Reason.Create(axiom, source) -- local func = Function.Create(newFuncNode, reason); -- local fo1 = FunctionOverload.Create(func, false, Access.Private, -- true, false, rtnType, -- false, false, self.reason); local fNode = node:Find("replCommand"); local foNode = fNode.Children[1]; local fo1 = foNode.Member; local fo2 = node:Find("showHelp").Children[1].Member; local doElse; helpDoc = {}; helpDoc[#helpDoc + 1] = "Commands:"; methodBody = {}; -- Sort the table (this is probably overkill...) local names = {} for i, v in ipairs(fns) do table.insert(names, v.name) end table.sort(names) local sorted = {} for i, v in ipairs(names) do for j, v2 in ipairs(fns) do if v2.name == v then table.insert(sorted, v2) end end end for i, v in ipairs(sorted) do if doElse then methodBody[#methodBody + 1] = "else "; else doElse = true end methodBody[#methodBody + 1] = [[ if (line == "]] .. v.name .. [[" ) { return ]] .. v.fon.Node.Name .. [[(line); } ]]; helpDoc[#helpDoc + 1] = " * " .. v.name .. " - " .. v.summary end methodBody[#methodBody + 1] = "return false;" fo1:SetCodeBlock(table.concat(methodBody, "\n\t"), source, false); fo2:SetCodeBlock([[ output->WriteLine("]] .. table.concat(helpDoc, [["); output->WriteLine("]]) .. [["); return true; ]], source, false); end
apache-2.0
SorBlackPlus/Anti-spam
plugins/warn.lua
1
9629
local dataLoad = load_data(_config.moderation.data) -- Set local function limitWarn(msg, maxNum) if tonumber(maxNum) < 1 or tonumber(maxNum) > 10 then return '*Warning Range is between* [ `0 - 10` ].' end local warnLimit = maxNum dataLoad[tostring(msg.chat_id_)]['settings']['warning_max'] = warnLimit save_data(_config.moderation.data, dataLoad) return '*Warning Range Has Been Set to* [`'..maxNum..'`]' end -- Get local function getMax(msg) local chat = chat_id local warnLimit = dataLoad[tostring(msg.chat_id_)]['settings']['warning_max'] if not warnLimit then local warnNum = 10 dataLoad[tostring(chat)]['settings']['warning_max'] = tostring(warnNum) return '*Warning not set! But I set to* [ `10` ]' end return '*Warning Range is* [ `'..warnLimit..'` ]' end -- /warn local function warnUser(user_id, chat_id) if is_mod1(chat_id, user_id) or user_id == tonumber(our_id) then return else local chat = chat_id local warnLimit = dataLoad[tostring(chat)]['settings']['warning_max'] local wUser = redis:hget(user_id..'warning'..chat_id, chat_id) if not wUser or wUser == '0' then redis:hset(user_id..'warning'..chat_id, chat_id, '1') tdcli.sendMessage(chat_id, 0, 1, '*Warning Level Is:* `1`', 1, 'md') else gWarn = tonumber(wUser) + 1 redis:hset(user_id..'warning'..chat_id, chat_id, gWarn) if tonumber(gWarn) >= tonumber(warnLimit) then kick_user(user_id, chat_id) redis:hset(user_id..'warning'..chat_id, chat_id, '0') else tdcli.sendMessage(chat_id, 0, 1, '*Warning Level Is:* `'..tostring(gWarn)..'`', 1, 'md') end end end end local function warnByReply(arg, data) if gp_type(chat) == "channel" or gp_type(chat) == "chat" then local function getIDreply(arg, data) if is_mod1(arg.chat_id, data.id_) or data.id_ == tonumber(our_id) then return else return warnUser(data.id_, arg.chat_id) end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, getIDreply, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) else return end end local function warnByUsername(arg, data) if arg.username then if is_mod1(arg.chat_id, data.id_) or data.id_ == tonumber(our_id) then return else warnUser(data.id_, arg.chat_id) end else return '_Can\'t find this username_' end end -- /unwarn local function unWarnUser(user_id, chat_id) if is_mod1(chat_id, user_id) or user_id == tonumber(our_id) then return else local wUser = redis:hget(user_id..'warning'..chat_id, chat_id) if not wUser or wUser == '0' then return '_This user don\'t have warning._' else gWarn = tonumber(wUser) - 1 redis:hset(user_id..'warning'..chat_id, chat_id, gWarn) tdcli.sendMessage(chat_id, 0, 1, '*Warning Level Is:* `'..tostring(gWarn)..'`', 1, 'md') end end end local function unWarnByReply(arg, data) if gp_type(chat) == "channel" or gp_type(chat) == "chat" then local function getIDreply(arg, data) if is_mod1(arg.chat_id, data.id_) or data.id_ == tonumber(our_id) then return else return unWarnUser(data.id_, arg.chat_id) end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, getIDreply, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) else return end end local function unWarnByUsername(arg, data) if gp_type(chat) == "channel" or gp_type(chat) == "chat" then if arg.username then if is_mod1(arg.chat_id, data.id_) or data.id_ == tonumber(our_id) then return else unWarnUser(data.id_, arg.chat_id) end else return '_Can\'t find this username_' end end end -- /unwarnall local function unWarnAllUser(user_id, chat_id) if is_mod1(chat_id, user_id) or user_id == tonumber(our_id) then return else local wUser = redis:hget(user_id..'warning'..chat_id, chat_id) if not wUser or wUser == '0' then return '_This user don\'t have warning._' else redis:hset(user_id..'warning'..chat_id, chat_id, '0') tdcli.sendMessage(chat_id, 0, 1, '_User Warnings Has Been Cleard!_', 1, 'md') end end end local function unWarnAllByReply(arg, data) if gp_type(chat) == "channel" or gp_type(chat) == "chat" then local function getIDreply(arg, data) if is_mod1(arg.chat_id, data.id_) or data.id_ == tonumber(our_id) then return else return unWarnAllUser(data.id_, arg.chat_id) end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, getIDreply, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) else return end end local function unWarnAllByUsername(arg, data) if arg.username then if is_mod1(arg.chat_id, data.id_) or data.id_ == tonumber(our_id) then return else unWarnAllUser(data.id_, arg.chat_id) end else return '_Can\'t find this username._' end end -- /getwarn local function getWarnUser(user_id, chat_id) local wUser = redis:hget(user_id..'warning'..chat_id, chat_id) tdcli.sendMessage(chat_id, 0, 1, '*Warning Level Is:* `'..tostring(wUser)..'`', 1, 'md') end local function getWarnByReply(arg, data) if gp_type(chat) == "channel" or gp_type(chat) == "chat" then local function getIDreply(arg, data) if is_mod1(arg.chat_id, data.id_) or data.id_ == tonumber(our_id) then return else getWarnUser(data.id_, arg.chat_id) end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, getIDreply, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) else return end end local function getWarnByUsername(arg, data) if arg.username then if is_mod1(arg.chat_id, data.id_) or data.id_ == tonumber(our_id) then return else getWarnUser(data.id_, arg.chat_id) end else return '_Can\'t find a user with that username._' end end -------------Commands------------ local function run(msg, matches) local warnLimit = dataLoad[tostring(msg.chat_id_)]['settings']['warning_max'] if is_mod(msg) then if warnLimit then if matches[1]:lower() == 'getmax' then local msg = getMax(msg) return msg end if matches[1]:lower() == 'warnmax' and matches[2] then local msg = limitWarn(msg, matches[2]) return msg end if matches[1]:lower() == 'getwarn' then if tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, getWarnByReply, {chat_id=msg.chat_id_}) elseif string.match(matches[2], '^%d+$') then if not matches[2] then return end if tonumber(matches[2]) == tonumber(our_id) then return end getWarnUser(matches[2], msg.chat_id_) else tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, getWarnByUsername, {chat_id=msg.chat_id_,username=matches[2]}) end end if matches[1]:lower() == 'warn' then if tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, warnByReply, {chat_id=msg.chat_id_}) elseif string.match(matches[2], '^%d+$') then if not matches[2] then return end if tonumber(matches[2]) == tonumber(our_id) then return end warnUser(matches[2], msg.chat_id_) else tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, warnByUsername, {chat_id=msg.chat_id_,username=matches[2]}) end end if matches[1]:lower() == 'unwarn' then if tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, unWarnByReply, {chat_id=msg.chat_id_}) elseif string.match(matches[2], '^%d+$') then if not matches[2] then return end if tonumber(matches[2]) == tonumber(our_id) then return end unWarnUser(matches[2], msg.chat_id_) else tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, unWarnByUsername, {chat_id=msg.chat_id_,username=matches[2]}) end end if matches[1]:lower() == 'unwarnall' then if tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, unWarnAllByReply, {chat_id=msg.chat_id_}) elseif string.match(matches[2], '^%d+$') then if not matches[2] then return end if tonumber(matches[2]) == tonumber(our_id) then return end unWarnAllUser(matches[2], msg.chat_id_) else tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, unWarnAllByUsername, {chat_id=msg.chat_id_,username=matches[2]}) end end else if matches[1]:lower() == 'warnmax' and matches[2] then local msg = limitWarn(msg, matches[2]) return msg else return '_First Set Warning Range!_' end end end end return { patterns = { "^[!/#]([Ww][Aa][Rr][Nn][Mm][Aa][Xx]) (%d+)$", "^[!/#]([Gg][Ee][Tt][Mm][Aa][Xx])$", "^[!/#]([Ww][Aa][Rr][Nn]) (.*)$", "^[!/#]([Ww][Aa][Rr][Nn])$", "^[!/#]([Uu][Nn][Ww][Aa][Rr][Nn])$", "^[!/#]([Uu][Nn][Ww][Aa][Rr][Nn]) (.*)$", "^[!/#]([Gg][Ee][Tt][Ww][Aa][Rr][Nn]) (.*)$", "^[!/#]([Gg][Ee][Tt][Ww][Aa][Rr][Nn])$", "^[!/#]([Uu][Nn][Ww][Aa][Rr][Nn][Aa][Ll][Ll])$", "^[!/#]([Uu][Nn][Ww][Aa][Rr][Nn][Aa][Ll][Ll]) (.*)$", }, run = run } --By #SorBlack :):| --channel: @PrimeTeam
gpl-3.0
victorperin/tibia-server
data/npc/scripts/Oliver.lua
2
1949
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local function creatureSayCallback(cid, type, msg) local player = Player(cid) if not npcHandler:isFocused(cid) then return false elseif(msgcontains(msg, "report")) then if(player:getStorageValue(Storage.InServiceofYalahar.Questline) == 8 or player:getStorageValue(Storage.InServiceofYalahar.Questline) == 12) then npcHandler:say("Nobody knows the trouble I've seen .. <tells a quite detailed report>. ", cid) player:setStorageValue(Storage.InServiceofYalahar.Questline, player:getStorageValue(Storage.InServiceofYalahar.Questline) + 1) player:setStorageValue(Storage.InServiceofYalahar.Mission02, player:getStorageValue(Storage.InServiceofYalahar.Mission02) + 1) -- StorageValue for Questlog "Mission 02: Watching the Watchmen" npcHandler.topic[cid] = 0 end elseif(msgcontains(msg, "pass")) then npcHandler:say("You can {pass} either to the {Factory Quarter} or {Sunken Quarter}. Which one will it be?", cid) npcHandler.topic[cid] = 1 elseif(msgcontains(msg, "factory")) then if(npcHandler.topic[cid] == 1) then player:teleportTo({x=32895, y=31231, z=7}) doSendMagicEffect({x=32895, y=31231, z=7}, CONST_ME_TELEPORT) npcHandler.topic[cid] = 0 end elseif(msgcontains(msg, "sunken")) then if(npcHandler.topic[cid] == 1) then player:teleportTo({x=32895, y=31226, z=7}) doSendMagicEffect({x=32895, y=31226, z=7}, CONST_ME_TELEPORT) npcHandler.topic[cid] = 0 end end return true end npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
apache-2.0
victorperin/tibia-server
data/npc/scripts/Servant Sentry.lua
1
1189
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local function creatureSayCallback(cid, type, msg) if(not npcHandler:isFocused(cid)) then return false end local player = Player(cid) if(msgcontains(msg, "help")) then if player:getStorageValue(985) < 1 then npcHandler:say("Defeat. {Slime}. We. Will. Why. Did. You. Kill. Us? Do. You. Want. To. Rectify. And. Help?", cid) npcHandler.topic[cid] = 1 end elseif(msgcontains(msg, "yes")) then if(npcHandler.topic[cid] == 1) then player:setStorageValue(985, 1) player:addItem(13601, 1) npcHandler:say("Then. Take. This. Gobbler. Always. Hungry. Eats. Slime. Fungus. Go. ", cid) npcHandler.topic[cid] = 0 end end return true end npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
apache-2.0
czfshine/Don-t-Starve
data/DLC0001/scripts/widgets/hoverer.lua
1
4988
local Text = require "widgets/text" local Widget = require "widgets/widget" require("constants") local YOFFSETUP = 40 local YOFFSETDOWN = 30 local XOFFSET = 10 local HoverText = Class(Widget, function(self, owner) Widget._ctor(self, "HoverText") self.owner = owner self.isFE = false self:SetClickable(false) --self:MakeNonClickable() self.text = self:AddChild(Text(UIFONT, 30)) self.text:SetPosition(0,YOFFSETUP,0) self.secondarytext = self:AddChild(Text(UIFONT, 30)) self.secondarytext:SetPosition(0,-YOFFSETDOWN,0) self:FollowMouseConstrained() self:StartUpdating() end) function HoverText:OnUpdate() local using_mouse = self.owner.components and self.owner.components.playercontroller:UsingMouse() if using_mouse ~= self.shown then if using_mouse then self:Show() else self:Hide() end end if not self.shown then return end local str = nil local colour = nil if self.isFE == false then str = self.owner.HUD.controls:GetTooltip() or self.owner.components.playercontroller:GetHoverTextOverride() if self.owner.HUD.controls:GetTooltip() then colour = self.owner.HUD.controls:GetTooltipColour() end else str = self.owner:GetTooltip() end local secondarystr = nil if not str and self.isFE == false then local lmb = self.owner.components.playercontroller:GetLeftMouseAction() if lmb then str = lmb:GetActionString() if not colour and lmb.target then colour = (lmb.target and lmb.target:GetIsWet()) and WET_TEXT_COLOUR or NORMAL_TEXT_COLOUR if lmb.invobject and not (lmb.invobject.components.weapon or lmb.invobject.components.tool) then colour = (lmb.invobject and lmb.invobject:GetIsWet()) and WET_TEXT_COLOUR or NORMAL_TEXT_COLOUR end elseif not colour and lmb.invobject then colour = (lmb.invobject and lmb.invobject:GetIsWet()) and WET_TEXT_COLOUR or NORMAL_TEXT_COLOUR end if lmb.target and lmb.invobject == nil and lmb.target ~= lmb.doer then local name = lmb.target:GetDisplayName() or (lmb.target.components.named and lb.target.components.named.name) if name then local adjective = lmb.target:GetAdjective() if adjective then str = str.. " " .. adjective .. " " .. name else str = str.. " " .. name end if lmb.target.components.stackable and lmb.target.components.stackable.stacksize > 1 then str = str .. " x" .. tostring(lmb.target.components.stackable.stacksize) end if lmb.target.components.inspectable and lmb.target.components.inspectable.recordview and lmb.target.prefab then ProfileStatsSet(lmb.target.prefab .. "_seen", true) end end end end local rmb = self.owner.components.playercontroller:GetRightMouseAction() if rmb then secondarystr = STRINGS.RMB .. ": " .. rmb:GetActionString() end end if not colour then colour = NORMAL_TEXT_COLOUR end if str then self.text:SetColour(colour[1], colour[2], colour[3], colour[4]) self.text:SetString(str) self.text:Show() else self.text:SetColour(colour[1], colour[2], colour[3], colour[4]) self.text:Hide() end if secondarystr then YOFFSETUP = -80 YOFFSETDOWN = -50 self.secondarytext:SetString(secondarystr) self.secondarytext:Show() else self.secondarytext:Hide() end local changed = (self.str ~= str) or (self.secondarystr ~= secondarystr) self.str = str self.secondarystr = secondarystr if changed then local pos = TheInput:GetScreenPosition() self:UpdatePosition(pos.x, pos.y) end end function HoverText:UpdatePosition(x,y) local scale = self:GetScale() local scr_w, scr_h = TheSim:GetScreenSize() local w = 0 local h = 0 if self.text and self.str then local w0, h0 = self.text:GetRegionSize() w = math.max(w, w0) h = math.max(h, h0) end if self.secondarytext and self.secondarystr then local w1, h1 = self.secondarytext:GetRegionSize() w = math.max(w, w1) h = math.max(h, h1) end w = w*scale.x h = h*scale.y x = math.max(x, w/2 + XOFFSET) x = math.min(x, scr_w - w/2 - XOFFSET) y = math.max(y, h/2 + YOFFSETDOWN*scale.y) y = math.min(y, scr_h - h/2 - YOFFSETUP*scale.x) self:SetPosition(x,y,0) end function HoverText:FollowMouseConstrained() if not self.followhandler then self.followhandler = TheInput:AddMoveHandler(function(x,y) self:UpdatePosition(x,y) end) local pos = TheInput:GetScreenPosition() self:UpdatePosition(pos.x, pos.y) end end return HoverText
gpl-2.0
SorBlackPlus/Anti-spam
libs/serpent.lua
656
7877
local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is not nil for numerical keys return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself seen[t] = insref or spath if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end ttype = type(t) end -- new value falls through to be serialized if ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath local ok, res = pcall(string.dump, t) local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or "((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level)) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function deserialize(data, opts) local env = (opts and opts.safe == false) and G or setmetatable({}, { __index = function(t,k) return t end, __call = function(t,...) error("cannot call functions") end }) local f, res = (loadstring or load)('return '..data, nil, nil, env) if not f then f, res = (loadstring or load)(data, nil, nil, env) end if not f then return f, res end if setfenv then setfenv(f, env) end return pcall(f) end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, load = deserialize, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
gpl-3.0
repstd/modified_vlc
share/lua/intf/http.lua
9
10566
--[==========================================================================[ http.lua: HTTP interface module for VLC --[==========================================================================[ Copyright (C) 2007-2009 the VideoLAN team $Id$ Authors: Antoine Cellerier <dionoea at videolan dot org> 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. --]==========================================================================] --[==========================================================================[ Configuration options: * dir: Directory to use as the http interface's root. * no_error_detail: If set, do not print the Lua error message when generating a page fails. * no_index: If set, don't build directory indexes --]==========================================================================] require "common" vlc.msg.info("Lua HTTP interface") open_tag = "<?vlc" close_tag = "?>" -- TODO: use internal VLC mime lookup function for mimes not included here local mimes = { txt = "text/plain", json = "text/plain", html = "text/html", xml = "text/xml", js = "text/javascript", css = "text/css", png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", ico = "image/x-icon", } function escape(s) return (string.gsub(s,"([%^%$%%%.%[%]%*%+%-%?])","%%%1")) end function process_raw(filename) local input = io.open(filename):read("*a") -- find the longest [===[ or ]=====] type sequence and make sure that -- we use one that's longer. local str="X" for str2 in string.gmatch(input,"[%[%]]=*[%[%]]") do if #str < #str2 then str = str2 end end str=string.rep("=",#str-1) --[[ FIXME: <?xml version="1.0" encoding="charset" standalone="yes" ?> is still a problem. The closing '?>' needs to be printed using '?<?vlc print ">" ?>' to prevent a parse error. --]] local code0 = string.gsub(input,escape(close_tag)," print(["..str.."[") local code1 = string.gsub(code0,escape(open_tag),"]"..str.."]) ") local code = "print(["..str.."["..code1.."]"..str.."])" --[[ Uncomment to debug if string.match(filename,"vlm_cmd.xml$") then io.write(code) io.write("\n") end --]] return assert(loadstring(code,filename)) end function process(filename) local mtime = 0 -- vlc.net.stat(filename).modification_time local func = false -- process_raw(filename) return function(...) local new_mtime = vlc.net.stat(filename).modification_time if new_mtime ~= mtime then -- Re-read the file if it changed if mtime == 0 then vlc.msg.dbg("Loading `"..filename.."'") else vlc.msg.dbg("Reloading `"..filename.."'") end func = process_raw(filename) mtime = new_mtime end return func(...) end end function callback_error(path,url,msg) local url = url or "&lt;page unknown&gt;" return [[<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Error loading ]]..url..[[</title> </head> <body> <h1>Error loading ]]..url..[[</h1><pre>]]..(config.no_error_detail and "Remove configuration option `no_error_detail' on the server to get more information." or tostring(msg))..[[</pre> <p> <a href="http://www.videolan.org/">VideoLAN</a><br/> <a href="http://www.lua.org/manual/5.1/">Lua 5.1 Reference Manual</a> </p> </body> </html>]] end function dirlisting(url,listing,acl_) local list = {} for _,f in ipairs(listing) do if not string.match(f,"^%.") then table.insert(list,"<li><a href='"..f.."'>"..f.."</a></li>") end end list = table.concat(list) local function callback() return [[<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Directory listing ]]..url..[[</title> </head> <body> <h1>Directory listing ]]..url..[[</h1><ul>]]..list..[[</ul> </body> </html>]] end return h:file(url,"text/html",nil,nil,acl_,callback,nil) end -- FIXME: Experimental art support. Needs some cleaning up. function callback_art(data, request, args) local art = function(data, request) local num = nil if args ~= nil then num = string.gmatch(args, "item=(.*)") if num ~= nil then num = num() end end local item if num == nil then item = vlc.input.item() else item = vlc.playlist.get(num).item end local metas = item:metas() local filename = vlc.strings.decode_uri(string.gsub(metas["artwork_url"],"file://","")) local size = vlc.net.stat(filename).size local ext = string.match(filename,"%.([^%.]-)$") local raw = io.open(filename):read("*a") local content = [[Content-Type: ]]..mimes[ext]..[[ Content-Length: ]]..size..[[ ]]..raw..[[ ]] return content end local ok, content = pcall(art, data, request) if not ok then return [[Status: 404 Content-Type: text/plain Content-Length: 5 Error ]] end return content end function file(h,path,url,acl_,mime) local generate_page = process(path) local callback = function(data,request) -- FIXME: I'm sure that we could define a real sandbox -- redefine print local page = {} local function pageprint(...) for i=1,select("#",...) do if i== 1 then table.insert(page,tostring(select(i,...))) else table.insert(page," "..tostring(select(i,...))) end end end _G._GET = parse_url_request(request) local oldprint = print print = pageprint local ok, msg = pcall(generate_page) -- reset print = oldprint if not ok then return callback_error(path,url,msg) end return table.concat(page) end return h:file(url or path,mime,nil,nil,acl_,callback,nil) end function rawfile(h,path,url,acl_) local filename = path local mtime = 0 -- vlc.net.stat(filename).modification_time local page = false -- io.open(filename):read("*a") local callback = function(data,request) local new_mtime = vlc.net.stat(filename).modification_time if mtime ~= new_mtime then -- Re-read the file if it changed if mtime == 0 then vlc.msg.dbg("Loading `"..filename.."'") else vlc.msg.dbg("Reloading `"..filename.."'") end page = io.open(filename,"rb"):read("*a") mtime = new_mtime end return page end return h:file(url or path,nil,nil,nil,acl_,callback,nil) end function parse_url_request(request) if not request then return {} end local t = {} for k,v in string.gmatch(request,"([^=&]+)=?([^=&]*)") do local k_ = vlc.strings.decode_uri(k) local v_ = vlc.strings.decode_uri(v) if t[k_] ~= nil then local t2 if type(t[k_]) ~= "table" then t2 = {} table.insert(t2,t[k_]) t[k_] = t2 else t2 = t[k_] end table.insert(t2,v_) else t[k_] = v_ end end return t end local function find_datadir(name) local list = vlc.config.datadir_list(name) for _, l in ipairs(list) do local s = vlc.net.stat(l) if s then return l end end error("Unable to find the `"..name.."' directory.") end http_dir = config.dir or find_datadir("http") do local oldpath = package.path package.path = http_dir.."/?.lua" local ok, err = pcall(require,"custom") if not ok then vlc.msg.warn("Couldn't load "..http_dir.."/custom.lua",err) else vlc.msg.dbg("Loaded "..http_dir.."/custom.lua") end package.path = oldpath end local files = {} local function load_dir(dir,root,parent_acl) local root = root or "/" local has_index = false local my_acl = parent_acl do local af = dir.."/.hosts" local s = vlc.net.stat(af) if s and s.type == "file" then -- We found an acl my_acl = vlc.acl(false) my_acl:load_file(af) end end local d = vlc.net.opendir(dir) for _,f in ipairs(d) do if not string.match(f,"^%.") then local s = vlc.net.stat(dir.."/"..f) if s.type == "file" then local url if f == "index.html" then url = root has_index = true else url = root..f end local ext = string.match(f,"%.([^%.]-)$") local mime = mimes[ext] -- print(url,mime) if mime and string.match(mime,"^text/") then table.insert(files,file(h,dir.."/"..f,url,my_acl,mime)) else table.insert(files,rawfile(h,dir.."/"..f,url,my_acl)) end elseif s.type == "dir" then load_dir(dir.."/"..f,root..f.."/",my_acl) end end end if not has_index and not config.no_index then -- print("Adding index for", root) table.insert(files,dirlisting(root,d,my_acl)) end return my_acl end if config.host then vlc.msg.err("\""..config.host.."\" HTTP host ignored") local port = string.match(config.host, ":(%d+)[^]]*$") vlc.msg.info("Pass --http-host=IP "..(port and "and --http-port="..port.." " or "").."on the command line instead.") end h = vlc.httpd() local root_acl = load_dir( http_dir ) local a = h:handler("/art",nil,nil,root_acl,callback_art,nil) while not vlc.misc.lock_and_wait() do end -- everything happens in callbacks
gpl-2.0
CrazyEddieTK/Zero-K
LuaUI/Widgets/chili/Controls/object.lua
5
22162
--//============================================================================= Object = { classname = 'object', --x = 0, --y = 0, --width = 10, --height = 10, defaultWidth = 10, --FIXME really needed? defaultHeight = 10, visible = true, --hidden = false, --// synonym for above preserveChildrenOrder = false, --// if false adding/removing children is much faster, but also the order (in the .children array) isn't reliable anymore children = {}, children_hidden = {}, childrenByName = CreateWeakTable(), OnDispose = {}, OnClick = {}, OnDblClick = {}, OnMouseDown = {}, OnMouseUp = {}, OnMouseMove = {}, OnMouseWheel = {}, OnMouseOver = {}, OnMouseOut = {}, OnKeyPress = {}, OnTextInput = {}, OnFocusUpdate = {}, OnHide = {}, OnShow = {}, OnOrphan = {}, OnParent = {}, OnParentPost = {}, -- Called after parent is set disableChildrenHitTest = false, --// if set childrens are not clickable/draggable etc - their mouse events are not processed } do local __lowerkeys = {} Object.__lowerkeys = __lowerkeys for i,v in pairs(Object) do if (type(i)=="string") then __lowerkeys[i:lower()] = i end end end local this = Object local inherited = this.inherited --//============================================================================= --// used to generate unique objects names local cic = {} local function GetUniqueId(classname) local ci = cic[classname] or 0 cic[classname] = ci + 1 return ci end --//============================================================================= function Object:New(obj) obj = obj or {} --// check if the user made some lower-/uppercase failures for i,v in pairs(obj) do if (not self[i])and(isstring(i)) then local correctName = self.__lowerkeys[i:lower()] if (correctName)and(obj[correctName] == nil) then obj[correctName] = v end end end --// give name if (not obj.name) then obj.name = self.classname .. GetUniqueId(self.classname) end --// make an instance for i,v in pairs(self) do --// `self` means the class here and not the instance! if (i ~= "inherited") then local t = type(v) local ot = type(obj[i]) if (t=="table")or(t=="metatable") then if (ot == "nil") then obj[i] = {}; ot = "table"; end if (ot ~= "table")and(ot ~= "metatable") then Spring.Echo("Chili: " .. obj.name .. ": Wrong param type given to " .. i .. ": got " .. ot .. " expected table.") obj[i] = {} end table.merge(obj[i],v) if (t=="metatable") then setmetatable(obj[i], getmetatable(v)) end elseif (ot == "nil") then obj[i] = v end end end setmetatable(obj,{__index = self}) --// auto dispose remaining Dlists etc. when garbage collector frees this object local hobj = MakeHardLink(obj) --// handle children & parent local parent = obj.parent if (parent) then obj.parent = nil --// note: we are using the hardlink here, --// else the link could get gc'ed and dispose our object parent:AddChild(hobj) end local cn = obj.children obj.children = {} for i=1,#cn do obj:AddChild(cn[i],true) end --// sets obj._widget DebugHandler:RegisterObject(obj) return hobj end -- calling this releases unmanaged resources like display lists and disposes of the object -- children are disposed too -- todo: use scream, in case the user forgets -- nil -> nil function Object:Dispose(_internal) if (not self.disposed) then --// check if the control is still referenced (if so it would indicate a bug in chili's gc) if _internal then if self._hlinks and next(self._hlinks) then local hlinks_cnt = table.size(self._hlinks) local i,v = next(self._hlinks) if hlinks_cnt > 1 or (v ~= self) then --// check if user called Dispose() directly Spring.Echo(("Chili: tried to dispose \"%s\"! It's still referenced %i times!"):format(self.name, hlinks_cnt)) end end end self:CallListeners(self.OnDispose) self.disposed = true TaskHandler.RemoveObject(self) --DebugHandler:UnregisterObject(self) --// not needed if (UnlinkSafe(self.parent)) then self.parent:RemoveChild(self) end self:SetParent(nil) self:ClearChildren() end end function Object:AutoDispose() self:Dispose(true) end function Object:Clone() local newinst = {} -- FIXME return newinst end function Object:Inherit(class) class.inherited = self for i,v in pairs(self) do if (class[i] == nil)and(i ~= "inherited")and(i ~= "__lowerkeys") then t = type(v) if (t == "table") --[[or(t=="metatable")--]] then class[i] = table.shallowcopy(v) else class[i] = v end end end local __lowerkeys = {} class.__lowerkeys = __lowerkeys for i,v in pairs(class) do if (type(i)=="string") then __lowerkeys[i:lower()] = i end end --setmetatable(class,{__index=self}) return class end --//============================================================================= function Object:SetParent(obj) obj = UnlinkSafe(obj) local typ = type(obj) if (typ ~= "table") then self.parent = nil self:CallListeners(self.OnOrphan, self) return end self:CallListeners(self.OnParent, self) -- Children always appear to visible when they recieve new parents because they -- are added to the visible child list. self.visible = true self.hidden = false self.parent = MakeWeakLink(obj, self.parent) self:Invalidate() self:CallListeners(self.OnParentPost, self) end function Object:AddChild(obj, dontUpdate, index) local objDirect = UnlinkSafe(obj) if (self.children[objDirect]) then Spring.Echo(("Chili: tried to add multiple times \"%s\" to \"%s\"!"):format(obj.name, self.name)) return end local hobj = MakeHardLink(objDirect) if (obj.name) then if (self.childrenByName[obj.name]) then error(("Chili: There is already a control with the name `%s` in `%s`!"):format(obj.name, self.name)) return end self.childrenByName[obj.name] = hobj end if UnlinkSafe(obj.parent) then obj.parent:RemoveChild(obj) end obj:SetParent(self) local children = self.children if index and (index <= #children) then for i,v in pairs(children) do -- remap hardlinks and objects if type(v) == "number" and v >= index then children[i] = v + 1 end end table.insert(children, index, objDirect) else local i = #children+1 children[i] = objDirect children[hobj] = i children[objDirect] = i end self:Invalidate() end function Object:RemoveChild(child) if not isindexable(child) then return child end if CompareLinks(child.parent,self) then child:SetParent(nil) end local childDirect = UnlinkSafe(child) if (self.children_hidden[childDirect]) then self.children_hidden[childDirect] = nil return true end if (not self.children[childDirect]) then --Spring.Echo(("Chili: tried remove none child \"%s\" from \"%s\"!"):format(child.name, self.name)) --Spring.Echo(DebugHandler.Stacktrace()) return false end if (child.name) then self.childrenByName[child.name] = nil end for i,v in pairs(self.children) do if CompareLinks(childDirect,i) then self.children[i] = nil end end local children = self.children local cn = #children for i=1,cn do if CompareLinks(childDirect,children[i]) then if (self.preserveChildrenOrder) then --// slow table.remove(children, i) else --// fast children[i] = children[cn] children[cn] = nil end children[child] = nil --FIXME (unused/unuseful?) children[childDirect] = nil self:Invalidate() return true end end return false end function Object:ClearChildren() --// make it faster local old = self.preserveChildrenOrder self.preserveChildrenOrder = false --// remove all children for i=1,#self.children_hidden do self:ShowChild(self.children_hidden[i]) end for i=#self.children,1,-1 do self:RemoveChild(self.children[i]) end --// restore old state self.preserveChildrenOrder = old end function Object:IsEmpty() return (not self.children[1]) end --//============================================================================= function Object:HideChild(obj) --FIXME cause of performance reasons it would be usefull to use the direct object, but then we need to cache the link somewhere to avoid the auto calling of dispose local objDirect = UnlinkSafe(obj) if (not self.children[objDirect]) then --if (self.debug) then Spring.Echo("Chili: tried to hide a non-child (".. (obj.name or "") ..")") --end return end if (self.children_hidden[objDirect]) then --if (self.debug) then Spring.Echo("Chili: tried to hide the same child multiple times (".. (obj.name or "") ..")") --end return end local hobj = MakeHardLink(objDirect) local pos = {hobj, 0, nil, nil} local children = self.children local cn = #children for i=1,cn+1 do if CompareLinks(objDirect,children[i]) then pos = {hobj, i, MakeWeakLink(children[i-1]), MakeWeakLink(children[i+1])} break end end self:RemoveChild(obj) self.children_hidden[objDirect] = pos obj.parent = self end function Object:ShowChild(obj) --FIXME cause of performance reasons it would be usefull to use the direct object, but then we need to cache the link somewhere to avoid the auto calling of dispose local objDirect = UnlinkSafe(obj) if (not self.children_hidden[objDirect]) then --if (self.debug) then Spring.Echo("Chili: tried to show a non-child (".. (obj.name or "") ..")") --end return end if (self.children[objDirect]) then --if (self.debug) then Spring.Echo("Chili: tried to show the same child multiple times (".. (obj.name or "") ..")") --end return end local params = self.children_hidden[objDirect] self.children_hidden[objDirect] = nil local children = self.children local cn = #children if (params[3]) then for i=1,cn do if CompareLinks(params[3],children[i]) then self:AddChild(obj) self:SetChildLayer(obj,i+1) return true end end end self:AddChild(obj) self:SetChildLayer(obj,params[2]) return true end function Object:SetVisibility(visible) if self.visible == visible then return end if (visible) then self.parent:ShowChild(self) else self.parent:HideChild(self) end self.visible = visible self.hidden = not visible end function Object:Hide() local wasHidden = self.hidden self:SetVisibility(false) if not wasHidden then self:CallListeners(self.OnHide, self) end end function Object:Show() local wasVisible = not self.hidden self:SetVisibility(true) if not wasVisible then self:CallListeners(self.OnShow, self) end end function Object:ToggleVisibility() self:SetVisibility(not self.visible) end --//============================================================================= function Object:SetChildLayer(child,layer) child = UnlinkSafe(child) local children = self.children if layer < 0 then layer = layer + #children + 1 end layer = math.min(layer, #children) --// it isn't at the same pos anymore, search it! for i=1,#children do if CompareLinks(children[i], child) then table.remove(children,i) break end end table.insert(children,layer,child) self:Invalidate() end function Object:SetLayer(layer) if (self.parent) then (self.parent):SetChildLayer(self, layer) end end function Object:SendToBack() self:SetLayer(-1) end function Object:BringToFront() self:SetLayer(1) end --//============================================================================= function Object:InheritsFrom(classname) if (self.classname == classname) then return true elseif not self.inherited then return false else return self.inherited.InheritsFrom(self.inherited,classname) end end --//============================================================================= function Object:GetChildByName(name) local cn = self.children for i=1,#cn do if (name == cn[i].name) then return cn[i] end end for c in pairs(self.children_hidden) do if (name == c.name) then return MakeWeakLink(c) end end end --// Backward-Compability Object.GetChild = Object.GetChildByName --// Resursive search to find an object by its name function Object:GetObjectByName(name) local r = self.childrenByName[name] if r then return r end for i=1,#self.children do local c = self.children[i] if (name == c.name) then return c else local result = c:GetObjectByName(name) if (result) then return result end end end for c in pairs(self.children_hidden) do if (name == c.name) then return MakeWeakLink(c) else local result = c:GetObjectByName(name) if (result) then return result end end end end --// Climbs the family tree and returns the first parent that satisfies a --// predicate function or inherites the given class. --// Returns nil if not found. function Object:FindParent(predicate) if not self.parent then return -- not parent with such class name found, return nil elseif (type(predicate) == "string" and (self.parent):InheritsFrom(predicate)) or (type(predicate) == "function" and predicate(self.parent)) then return self.parent else return self.parent:FindParent(predicate) end end function Object:IsDescendantOf(object, _already_unlinked) if (not _already_unlinked) then object = UnlinkSafe(object) end if (UnlinkSafe(self) == object) then return true end if (self.parent) then return (self.parent):IsDescendantOf(object, true) end return false end function Object:IsAncestorOf(object, _level, _already_unlinked) _level = _level or 1 if (not _already_unlinked) then object = UnlinkSafe(object) end local children = self.children for i=1,#children do if (children[i] == object) then return true, _level end end _level = _level + 1 for i=1,#children do local c = children[i] local res,lvl = c:IsAncestorOf(object, _level, true) if (res) then return true, lvl end end return false end --//============================================================================= function Object:CallListeners(listeners, ...) for i=1,#listeners do local eventListener = listeners[i] if eventListener(self, ...) then return true end end end function Object:CallListenersInverse(listeners, ...) for i=#listeners,1,-1 do local eventListener = listeners[i] if eventListener(self, ...) then return true end end end function Object:CallChildren(eventname, ...) local children = self.children for i=1,#children do local child = children[i] if (child) then local obj = child[eventname](child, ...) if (obj) then return obj end end end end function Object:CallChildrenInverse(eventname, ...) local children = self.children for i=#children,1,-1 do local child = children[i] if (child) then local obj = child[eventname](child, ...) if (obj) then return obj end end end end function Object:CallChildrenInverseCheckFunc(checkfunc,eventname, ...) local children = self.children for i=#children,1,-1 do local child = children[i] if (child)and(checkfunc(self,child)) then local obj = child[eventname](child, ...) if (obj) then return obj end end end end local function InLocalRect(cx,cy,w,h) return (cx>=0)and(cy>=0)and(cx<=w)and(cy<=h) end function Object:CallChildrenHT(eventname, x, y, ...) if self.disableChildrenHitTest then return nil end local children = self.children for i=1,#children do local c = children[i] if (c) then local cx,cy = c:ParentToLocal(x,y) if InLocalRect(cx,cy,c.width,c.height) and c:HitTest(cx,cy) then local obj = c[eventname](c, cx, cy, ...) if (obj) then return obj end end end end end function Object:CallChildrenHTWeak(eventname, x, y, ...) if self.disableChildrenHitTest then return nil end local children = self.children for i=1,#children do local c = children[i] if (c) then local cx,cy = c:ParentToLocal(x,y) if InLocalRect(cx,cy,c.width,c.height) then local obj = c[eventname](c, cx, cy, ...) if (obj) then return obj end end end end end --//============================================================================= function Object:RequestUpdate() --// we have something todo in Update --// so we register this object in the taskhandler TaskHandler.RequestUpdate(self) end function Object:Invalidate() --FIXME should be Control only end function Object:Draw() self:CallChildrenInverse('Draw') end function Object:TweakDraw() self:CallChildrenInverse('TweakDraw') end --//============================================================================= function Object:LocalToParent(x,y) return x + self.x, y + self.y end function Object:ParentToLocal(x,y) return x - self.x, y - self.y end Object.ParentToClient = Object.ParentToLocal Object.ClientToParent = Object.LocalToParent function Object:LocalToClient(x,y) return x,y end -- LocalToScreen does not do what it says it does because -- self:LocalToParent(x,y) = 2*self.x, 2*self.y -- However, too much chili depends on the current LocalToScreen -- so this working version exists for widgets. function Object:CorrectlyImplementedLocalToScreen(x,y) if (not self.parent) then return x,y end return (self.parent):ClientToScreen(x,y) end function Object:LocalToScreen(x,y) if (not self.parent) then return x,y end return (self.parent):ClientToScreen(self:LocalToParent(x,y)) end function Object:UnscaledLocalToScreen(x,y) if (not self.parent) then return x,y end --Spring.Echo((not self.parent) and debug.traceback()) return (self.parent):UnscaledClientToScreen(self:LocalToParent(x,y)) end function Object:ClientToScreen(x,y) if (not self.parent) then return self:ClientToParent(x,y) end return (self.parent):ClientToScreen(self:ClientToParent(x,y)) end function Object:UnscaledClientToScreen(x,y) if (not self.parent) then return self:ClientToParent(x,y) end return (self.parent):UnscaledClientToScreen(self:ClientToParent(x,y)) end function Object:ScreenToLocal(x,y) if (not self.parent) then return self:ParentToLocal(x,y) end return self:ParentToLocal((self.parent):ScreenToClient(x,y)) end function Object:ScreenToClient(x,y) if (not self.parent) then return self:ParentToClient(x,y) end return self:ParentToClient((self.parent):ScreenToClient(x,y)) end function Object:LocalToObject(x, y, obj) if CompareLinks(self,obj) then return x, y end if (not self.parent) then return -1,-1 end x, y = self:LocalToParent(x, y) return self.parent:LocalToObject(x, y, obj) end function Object:IsVisibleOnScreen() if (not self.parent) or (not self.visible) then return false end return (self.parent):IsVisibleOnScreen() end --//============================================================================= function Object:_GetMaxChildConstraints(child) return 0, 0, self.width, self.height end --//============================================================================= function Object:HitTest(x,y) if not self.disableChildrenHitTest then local children = self.children for i=1,#children do local c = children[i] if (c) then local cx,cy = c:ParentToLocal(x,y) if InLocalRect(cx,cy,c.width,c.height) then local obj = c:HitTest(cx,cy) if (obj) then return obj end end end end end return false end function Object:IsAbove(x, y, ...) return self:HitTest(x,y) end function Object:MouseMove(...) if (self:CallListeners(self.OnMouseMove, ...)) then return self end return self:CallChildrenHT('MouseMove', ...) end function Object:MouseDown(...) if (self:CallListeners(self.OnMouseDown, ...)) then return self end return self:CallChildrenHT('MouseDown', ...) end function Object:MouseUp(...) if (self:CallListeners(self.OnMouseUp, ...)) then return self end return self:CallChildrenHT('MouseUp', ...) end function Object:MouseClick(...) if (self:CallListeners(self.OnClick, ...)) then return self end return self:CallChildrenHT('MouseClick', ...) end function Object:MouseDblClick(...) if (self:CallListeners(self.OnDblClick, ...)) then return self end return self:CallChildrenHT('MouseDblClick', ...) end function Object:MouseWheel(...) if (self:CallListeners(self.OnMouseWheel, ...)) then return self end return self:CallChildrenHTWeak('MouseWheel', ...) end function Object:MouseOver(...) if (self:CallListeners(self.OnMouseOver, ...)) then return self end end function Object:MouseOut(...) if (self:CallListeners(self.OnMouseOut, ...)) then return self end end function Object:KeyPress(...) if (self:CallListeners(self.OnKeyPress, ...)) then return self end return false end function Object:TextInput(...) if (self:CallListeners(self.OnTextInput, ...)) then return self end return false end function Object:FocusUpdate(...) if (self:CallListeners(self.OnFocusUpdate, ...)) then return self end return false end --//=============================================================================
gpl-2.0
wtof1996/TI-Lua_String_Library_Extension
V1/samples/ctype_sample_non_assert.lua
1
1249
--[[ #FreInclude <ctype\ctype.lua> ]]-- --[[ This is a sample which shows how to use ctype lib. In this sample, user only can input digits to display on the screen. P.S:You'd better use this with iLua. ]]-- charStack = {}; errString = ""; function on.charIn(char) local res, err = ctype.isdigit(char); if(err ~= nil) then if(err == ctype.exception.invChar)then errString ="Invalid character, please try again."; elseif(err == ctype.exception.invType) then errString ="Invalid type, please try again."; elseif(err == ctype.exception.longString) then errString = "Input is too long, please try again."; end elseif(res == true) then table.insert(charStack, char); errString = ""; end platform.window:invalidate(); end function on.backspaceKey() table.remove(charStack); platform.window:invalidate(); end function on.paint(gc) gc:setColorRGB(0xffffff); gc:fillRect(0, 0, 320, 240); gc:setColorRGB(0x000000); gc:drawString("Input some character:", 0, 20); gc:drawString(table.concat(charStack), 0, 100); if(errString ~= "") then gc:drawString("error:" .. errString, 0, 150); end end
apache-2.0
project-asap/IReS-Platform
resources/unusedAsapLibraryComponents/Maxim/operators/WINDM_Join_CDR_VORONOI_Postgres/WIND_Join_CDR_VORONOI_Postgres.lua
3
1243
-- General configuration of the operators belonging to Wind_Demo_o_Postgres workflow BASE = "${JAVA_HOME}/bin/java -Xms64m -Xmx128m com.cloudera.kitten.appmaster.ApplicationMaster" TIMEOUT = -1 MEMORY = 1024 CORES = 1 LABELS = "postgres" EXECUTION_NODE_LOCATION = "hdp1" -- Specific configuration of operator OPERATOR = "WIND_Join_CDR_VORONOI_Postgres" SCRIPT = OPERATOR .. ".sh" SHELL_COMMAND = "./" .. SCRIPT -- The actual distributed shell job. operator = yarn { name = "Execute " .. OPERATOR .. " Operator", timeout = TIMEOUT, memory = MEMORY, cores = CORES, labels = LABELS, nodes = EXECUTION_NODE_LOCATION, master = { env = base_env, resources = base_resources, command = { base = BASE, args = { "-conf job.xml" }, } }, container = { instances = CONTAINER_INSTANCES, env = base_env, stageout = {"output"}, resources = { ["WIND_Join_CDR_VORONOI_Postgres.sh"] = { file = "asapLibrary/operators/WIND_Join_CDR_VORONOI_Postgres/WIND_Join_CDR_VORONOI_Postgres.sh", type = "file", -- other value: 'archive' visibility = "application", -- other values: 'private', 'public' } }, command = { base = SHELL_COMMAND } } }
apache-2.0
project-asap/IReS-Platform
resources/unusedAsapLibraryComponents/Maxim/operators/WIND_Join_CDR_VORONOI_Postgres/WIND_Join_CDR_VORONOI_Postgres.lua
3
1243
-- General configuration of the operators belonging to Wind_Demo_o_Postgres workflow BASE = "${JAVA_HOME}/bin/java -Xms64m -Xmx128m com.cloudera.kitten.appmaster.ApplicationMaster" TIMEOUT = -1 MEMORY = 1024 CORES = 1 LABELS = "postgres" EXECUTION_NODE_LOCATION = "hdp1" -- Specific configuration of operator OPERATOR = "WIND_Join_CDR_VORONOI_Postgres" SCRIPT = OPERATOR .. ".sh" SHELL_COMMAND = "./" .. SCRIPT -- The actual distributed shell job. operator = yarn { name = "Execute " .. OPERATOR .. " Operator", timeout = TIMEOUT, memory = MEMORY, cores = CORES, labels = LABELS, nodes = EXECUTION_NODE_LOCATION, master = { env = base_env, resources = base_resources, command = { base = BASE, args = { "-conf job.xml" }, } }, container = { instances = CONTAINER_INSTANCES, env = base_env, stageout = {"output"}, resources = { ["WIND_Join_CDR_VORONOI_Postgres.sh"] = { file = "asapLibrary/operators/WIND_Join_CDR_VORONOI_Postgres/WIND_Join_CDR_VORONOI_Postgres.sh", type = "file", -- other value: 'archive' visibility = "application", -- other values: 'private', 'public' } }, command = { base = SHELL_COMMAND } } }
apache-2.0
CrazyEddieTK/Zero-K
units/turretaafar.lua
5
4394
unitDef = { unitname = [[turretaafar]], name = [[Chainsaw]], description = [[Long-Range Anti-Air Missile Battery]], acceleration = 0, brakeRate = 0, buildCostMetal = 900, builder = false, buildingGroundDecalDecaySpeed = 30, buildingGroundDecalSizeX = 3.6, buildingGroundDecalSizeY = 3.6, buildingGroundDecalType = [[turretaafar_aoplane.dds]], buildPic = [[turretaafar.png]], category = [[FLOAT]], collisionVolumeOffsets = [[0 12 0]], collisionVolumeScales = [[58 76 58]], collisionVolumeType = [[CylY]], corpse = [[DEAD]], customParams = { aimposoffset = [[0 10 0]], modelradius = [[19]], }, explodeAs = [[LARGE_BUILDINGEX]], floater = true, footprintX = 4, footprintZ = 4, iconType = [[staticskirmaa]], idleAutoHeal = 5, idleTime = 1800, losEmitHeight = 40, maxDamage = 2500, maxSlope = 18, maxVelocity = 0, maxWaterDepth = 5000, minCloakDistance = 150, noAutoFire = false, noChaseCategory = [[FIXEDWING LAND SINK TURRET SHIP SATELLITE SWIM GUNSHIP FLOAT SUB HOVER]], objectName = [[armcir.s3o]], script = [[turretaafar.lua]], selfDestructAs = [[LARGE_BUILDINGEX]], sightDistance = 702, turnRate = 0, useBuildingGroundDecal = true, workerTime = 0, yardMap = [[oooooooooooooooo]], sfxtypes = { explosiongenerators = { [[custom:light_red_short]], [[custom:light_green_short]], [[custom:light_blue_short]], }, }, weapons = { { def = [[MISSILE]], --badTargetCategory = [[GUNSHIP]], onlyTargetCategory = [[FIXEDWING GUNSHIP]], }, }, weaponDefs = { MISSILE = { name = [[Long-Range SAM]], areaOfEffect = 24, canattackground = false, cegTag = [[chainsawtrail]], craterBoost = 0, craterMult = 0, cylinderTargeting = 1, customParams = { isaa = [[1]], light_color = [[0.6 0.7 0.7]], light_radius = 420, }, damage = { default = 22.51, planes = 225.1, subs = 12.5, }, explosionGenerator = [[custom:MISSILE_HIT_PIKES_160]], fireStarter = 20, flightTime = 4, impactOnly = true, impulseBoost = 0.123, impulseFactor = 0.0492, interceptedByShieldType = 2, model = [[wep_m_phoenix.s3o]], noSelfDamage = true, range = 1800, reloadtime = 1, smokeTrail = true, soundHit = [[weapon/missile/med_aa_hit]], soundStart = [[weapon/missile/med_aa_fire]], soundTrigger = true, startVelocity = 550, texture2 = [[AAsmoketrail]], tolerance = 16000, tracks = true, turnRate = 55000, turret = true, waterweapon = true, weaponAcceleration = 550, weaponType = [[MissileLauncher]], weaponVelocity = 800, }, }, featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 4, footprintZ = 4, object = [[chainsaw_d.dae]], }, HEAP = { blocking = false, footprintX = 3, footprintZ = 3, object = [[debris3x3a.s3o]], }, }, } return lowerkeys({ turretaafar = unitDef })
gpl-2.0
nonconforme/Urho3DEditor
Prime/Data/Data/LuaScripts/17_SceneReplication.lua
2
15544
-- Scene network replication example. -- This sample demonstrates: -- - Creating a scene in which network clients can join -- - Giving each client an object to control and sending the controls from the clients to the server, -- where the authoritative simulation happens -- - Controlling a physics object's movement by applying forces require "LuaScripts/Utilities/Sample" -- UDP port we will use local SERVER_PORT = 2345 -- Control bits we define local CTRL_FORWARD = 1 local CTRL_BACK = 2 local CTRL_LEFT = 4 local CTRL_RIGHT = 8 local scene_ = nil local cameraNode = nil local instructionsText = nil local buttonContainer = nil local textEdit = nil local connectButton = nil local disconnectButton = nil local startServerButton = nil local clients = {} local yaw = 0.0 local pitch = 1.0 local clientObjectID = 0 function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateUI() -- Setup the viewport for displaying the scene SetupViewport() -- Hook up to necessary events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create octree and physics world with default settings. Create them as local so that they are not needlessly replicated -- when a client connects scene_:CreateComponent("Octree", LOCAL) scene_:CreateComponent("PhysicsWorld", LOCAL) -- All static scene content and the camera are also created as local, so that they are unaffected by scene replication and are -- not removed from the client upon connection. Create a Zone component first for ambient lighting & fog control. local zoneNode = scene_:CreateChild("Zone", LOCAL) local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.1, 0.1, 0.1) zone.fogStart = 100.0 zone.fogEnd = 300.0 -- Create a directional light without shadows local lightNode = scene_:CreateChild("DirectionalLight", LOCAL) lightNode.direction = Vector3(0.5, -1.0, 0.5) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.color = Color(0.2, 0.2, 0.2) light.specularIntensity = 1.0 -- Create a "floor" consisting of several tiles. Make the tiles physical but leave small cracks between them for y = -20, 20 do for x = -20, 20 do local floorNode = scene_:CreateChild("FloorTile", LOCAL) floorNode.position = Vector3(x * 20.2, -0.5, y * 20.2) floorNode.scale = Vector3(20.0, 1.0, 20.0) local floorObject = floorNode:CreateComponent("StaticModel") floorObject.model = cache:GetResource("Model", "Models/Box.mdl") floorObject.material = cache:GetResource("Material", "Materials/Stone.xml") local body = floorNode:CreateComponent("RigidBody") body.friction = 1.0 local shape = floorNode:CreateComponent("CollisionShape") shape:SetBox(Vector3(1.0, 1.0, 1.0)) end end -- Create the camera. Limit far clip distance to match the fog cameraNode = scene_:CreateChild("Camera", LOCAL) local camera = cameraNode:CreateComponent("Camera") camera.farClip = 300.0 -- Set an initial position for the camera scene node above the plane cameraNode.position = Vector3(0.0, 5.0, 0.0) end function CreateUI() local uiStyle = cache:GetResource("XMLFile", "UI/DefaultStyle.xml") -- Set style to the UI root so that elements will inherit it ui.root.defaultStyle = uiStyle -- Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will -- control the camera, and when visible, it will point the raycast target local cursor = ui.root:CreateChild("Cursor") cursor:SetStyleAuto(uiStyle) ui.cursor = cursor -- Set starting position of the cursor at the rendering window center cursor:SetPosition(graphics.width / 2, graphics.height / 2) -- Construct the instructions text element instructionsText = ui.root:CreateChild("Text") instructionsText:SetText("Use WASD keys to move and RMB to rotate view") instructionsText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- Position the text relative to the screen center instructionsText.horizontalAlignment = HA_CENTER instructionsText.verticalAlignment = VA_CENTER instructionsText:SetPosition(0, graphics.height / 4) -- Hide until connected instructionsText.visible = false buttonContainer = ui.root:CreateChild("UIElement") buttonContainer:SetFixedSize(500, 20) buttonContainer:SetPosition(20, 20) buttonContainer.layoutMode = LM_HORIZONTAL textEdit = buttonContainer:CreateChild("LineEdit") textEdit:SetStyleAuto() connectButton = CreateButton("Connect", 90) disconnectButton = CreateButton("Disconnect", 100) startServerButton = CreateButton("Start Server", 110) UpdateButtons() end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function SubscribeToEvents() -- Subscribe to fixed timestep physics updates for setting or applying controls SubscribeToEvent("PhysicsPreStep", "HandlePhysicsPreStep") -- Subscribe HandlePostUpdate() method for processing update events. Subscribe to PostUpdate instead -- of the usual Update so that physics simulation has already proceeded for the frame, and can -- accurately follow the object with the camera SubscribeToEvent("PostUpdate", "HandlePostUpdate") -- Subscribe to button actions SubscribeToEvent(connectButton, "Released", "HandleConnect") SubscribeToEvent(disconnectButton, "Released", "HandleDisconnect") SubscribeToEvent(startServerButton, "Released", "HandleStartServer") -- Subscribe to network events SubscribeToEvent("ServerConnected", "HandleConnectionStatus") SubscribeToEvent("ServerDisconnected", "HandleConnectionStatus") SubscribeToEvent("ConnectFailed", "HandleConnectionStatus") SubscribeToEvent("ClientConnected", "HandleClientConnected") SubscribeToEvent("ClientDisconnected", "HandleClientDisconnected") -- This is a custom event, sent from the server to the client. It tells the node ID of the object the client should control SubscribeToEvent("ClientObjectID", "HandleClientObjectID") end function CreateButton(text, width) local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf") local button = buttonContainer:CreateChild("Button") button:SetStyleAuto() button:SetFixedWidth(width) local buttonText = button:CreateChild("Text") buttonText:SetFont(font, 12) buttonText:SetAlignment(HA_CENTER, VA_CENTER) buttonText:SetText(text) return button end function UpdateButtons() local serverConnection = network:GetServerConnection() local serverRunning = network.serverRunning -- Show and hide buttons so that eg. Connect and Disconnect are never shown at the same time connectButton.visible = serverConnection == nil and not serverRunning disconnectButton.visible = serverConnection ~= nil or serverRunning startServerButton.visible = serverConnection == nil and not serverRunning textEdit.visible = serverConnection == nil and not serverRunning end function CreateControllableObject() -- Create the scene node & visual representation. This will be a replicated object local ballNode = scene_:CreateChild("Ball") ballNode.position = Vector3(Random(40.0) - 20.0, 5.0, Random(40.0) - 20.0) ballNode:SetScale(0.5) local ballObject = ballNode:CreateComponent("StaticModel") ballObject.model = cache:GetResource("Model", "Models/Sphere.mdl") ballObject.material = cache:GetResource("Material", "Materials/StoneSmall.xml") -- Create the physics components local body = ballNode:CreateComponent("RigidBody") body.mass = 1.0 body.friction = 1.0 -- In addition to friction, use motion damping so that the ball can not accelerate limitlessly body.linearDamping = 0.5 body.angularDamping = 0.5 local shape = ballNode:CreateComponent("CollisionShape") shape:SetSphere(1.0) -- Create a random colored point light at the ball so that can see better where is going local light = ballNode:CreateComponent("Light") light.range = 3.0 light.color = Color(0.5 + RandomInt(2) * 0.5, 0.5 + RandomInt(2) * 0.5, 0.5 + RandomInt(2) * 0.5) return ballNode end function MoveCamera() -- Right mouse button controls mouse cursor visibility: hide when pressed ui.cursor.visible = not input:GetMouseButtonDown(MOUSEB_RIGHT) -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch and only move the camera -- when the cursor is hidden if not ui.cursor.visible then local mouseMove = input.mouseMove yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, 1.0, 90.0) end -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) -- Only move the camera / show instructions if we have a controllable object local showInstructions = false if clientObjectID ~= 0 then local ballNode = scene_:GetNode(clientObjectID) if ballNode ~= nil then local CAMERA_DISTANCE = 5.0 -- Move camera some distance away from the ball cameraNode.position = ballNode.position + cameraNode.rotation * Vector3(0.0, 0.0, -1.0) * CAMERA_DISTANCE showInstructions = true end end instructionsText.visible = showInstructions end function HandlePostUpdate(eventType, eventData) -- We only rotate the camera according to mouse movement since last frame, so do not need the time step MoveCamera() end function HandlePhysicsPreStep(eventType, eventData) -- This function is different on the client and server. The client collects controls (WASD controls + yaw angle) -- and sets them to its server connection object, so that they will be sent to the server automatically at a -- fixed rate, by default 30 FPS. The server will actually apply the controls (authoritative simulation.) local serverConnection = network:GetServerConnection() -- Client: collect controls if serverConnection ~= nil then local controls = Controls() -- Copy mouse yaw controls.yaw = yaw -- Only apply WASD controls if there is no focused UI element if ui.focusElement == nil then controls:Set(CTRL_FORWARD, input:GetKeyDown(KEY_W)) controls:Set(CTRL_BACK, input:GetKeyDown(KEY_S)) controls:Set(CTRL_LEFT, input:GetKeyDown(KEY_A)) controls:Set(CTRL_RIGHT, input:GetKeyDown(KEY_D)) end serverConnection.controls = controls -- In case the server wants to do position-based interest management using the NetworkPriority components, we should also -- tell it our observer (camera) position. In this sample it is not in use, but eg. the NinjaSnowWar game uses it serverConnection.position = cameraNode.position -- Server: apply controls to client objects elseif network.serverRunning then for i, v in ipairs(clients) do local connection = v.connection -- Get the object this connection is controlling local ballNode = v.object local body = ballNode:GetComponent("RigidBody") -- Torque is relative to the forward vector local rotation = Quaternion(0.0, connection.controls.yaw, 0.0) local MOVE_TORQUE = 3.0 -- Movement torque is applied before each simulation step, which happen at 60 FPS. This makes the simulation -- independent from rendering framerate. We could also apply forces (which would enable in-air control), -- but want to emphasize that it's a ball which should only control its motion by rolling along the ground if connection.controls:IsDown(CTRL_FORWARD) then body:ApplyTorque(rotation * Vector3(1.0, 0.0, 0.0) * MOVE_TORQUE) end if connection.controls:IsDown(CTRL_BACK) then body:ApplyTorque(rotation * Vector3(-1.0, 0.0, 0.0) * MOVE_TORQUE) end if connection.controls:IsDown(CTRL_LEFT) then body:ApplyTorque(rotation * Vector3(0.0, 0.0, 1.0) * MOVE_TORQUE) end if connection.controls:IsDown(CTRL_RIGHT) then body:ApplyTorque(rotation * Vector3(0.0, 0.0, -1.0) * MOVE_TORQUE) end end end end function HandleConnect(eventType, eventData) local address = textEdit.text if address == "" then address = "localhost" -- Use localhost to connect if nothing else specified end -- Connect to server, specify scene to use as a client for replication clientObjectID = 0 -- Reset own object ID from possible previous connection network:Connect(address, SERVER_PORT, scene_) UpdateButtons() end function HandleDisconnect(eventType, eventData) local serverConnection = network.serverConnection -- If we were connected to server, disconnect. Or if we were running a server, stop it. In both cases clear the -- scene of all replicated content, but let the local nodes & components (the static world + camera) stay if serverConnection ~= nil then serverConnection:Disconnect() scene_:Clear(true, false) clientObjectID = 0 -- Or if we were running a server, stop it elseif network.serverRunning then network:StopServer() scene_:Clear(true, false) end UpdateButtons() end function HandleStartServer(eventType, eventData) network:StartServer(SERVER_PORT) UpdateButtons() end function HandleConnectionStatus(eventType, eventData) UpdateButtons() end function HandleClientConnected(eventType, eventData) -- When a client connects, assign to scene to begin scene replication local newConnection = eventData:GetPtr("Connection", "Connection") newConnection.scene = scene_ -- Then create a controllable object for that client local newObject = CreateControllableObject() local newClient = {} newClient.connection = newConnection newClient.object = newObject table.insert(clients, newClient) -- Finally send the object's node ID using a remote event local remoteEventData = VariantMap() remoteEventData:SetInt("ID", newObject.ID) newConnection:SendRemoteEvent("ClientObjectID", true, remoteEventData) end function HandleClientDisconnected(eventType, eventData) -- When a client disconnects, remove the controlled object local connection = eventData:GetPtr("Connection", "Connection") for i, v in ipairs(clients) do if v.connection == connection then v.object:Remove() table.remove(clients, i) break end end end function HandleClientObjectID(eventType, eventData) clientObjectID = eventData:GetUInt("ID") end
mit
alobaidy98/ahmed.Dev
plugins/taks.lua
3
1481
do local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local function get_weather(location) print("Finding weather in ", location) local url = BASE_URL url = url..'?q='..location..'&APPID=5f5d8da1984bd84dcff8ee7cb1abebb5' url = url..'&units=metric' local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'The temperature in '..city ..' (' ..country..')' ..'\nis '..weather.main.temp..' °C' local conditions = 'Current conditions are: ' .. weather.weather[1].description if weather.weather[1].main == 'Clear' then conditions = conditions .. ' ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. ' ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. ' ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. ' ☔☔☔☔' end return temp .. '\n' .. conditions end local function run(msg, matches) local city = 'Madrid,ES' if matches[1] ~= 'weather' then city = matches[1] end local text = get_weather(city) if not text then text = 'Can\'t get weather from that city.' end return text end return { description = "weather in that city (Madrid is default)", usage = "weather (city)", patterns = { "^weather$", "weather (.*)$" }, run = run } end
gpl-3.0
CrazyEddieTK/Zero-K
LuaRules/Configs/StartBoxes/Akilon Wastelands ZK v1.lua
11
19588
return { [0] = { boxes = { { {6950, 6435}, {6804, 6292}, {6794, 6284}, {6783, 6283}, {6781, 6294}, {6782, 6304}, {6779, 6315}, {6770, 6326}, {6761, 6336}, {6754, 6347}, {6743, 6354}, {6733, 6357}, {6722, 6359}, {6712, 6360}, {6702, 6360}, {6691, 6359}, {6681, 6359}, {6671, 6360}, {6660, 6362}, {6650, 6361}, {6640, 6362}, {6630, 6365}, {6619, 6367}, {6608, 6367}, {6598, 6367}, {6588, 6368}, {6578, 6370}, {6546, 6377}, {6536, 6381}, {6525, 6386}, {6516, 6396}, {6506, 6402}, {6496, 6412}, {6490, 6422}, {6481, 6432}, {6471, 6439}, {6461, 6445}, {6451, 6456}, {6446, 6467}, {6445, 6477}, {6444, 6495}, {6445, 6506}, {6445, 6516}, {6445, 6527}, {6444, 6537}, {6440, 6547}, {6432, 6557}, {6424, 6568}, {6414, 6577}, {6403, 6585}, {6394, 6595}, {6383, 6605}, {6378, 6616}, {6371, 6626}, {6367, 6637}, {6355, 6674}, {6349, 6686}, {6341, 6696}, {6331, 6707}, {6322, 6718}, {6313, 6728}, {6304, 6738}, {6294, 6748}, {6283, 6758}, {6273, 6767}, {6264, 6777}, {6258, 6788}, {6258, 6798}, {6256, 6808}, {6256, 6819}, {6256, 6830}, {6257, 6840}, {6256, 6851}, {6255, 6862}, {6255, 6873}, {6255, 6883}, {6256, 6895}, {6256, 6907}, {6256, 6919}, {6257, 6945}, {6257, 6956}, {6257, 6967}, {6252, 6977}, {6246, 6987}, {6239, 6997}, {6230, 7009}, {6219, 7020}, {6209, 7030}, {6199, 7038}, {6188, 7045}, {6182, 7055}, {6181, 7065}, {6178, 7075}, {6176, 7087}, {6173, 7098}, {6171, 7109}, {6169, 7119}, {6156, 7149}, {6148, 7159}, {6136, 7168}, {6123, 7179}, {6112, 7184}, {6105, 7195}, {6095, 7206}, {6084, 7217}, {6075, 7227}, {6065, 7236}, {6055, 7248}, {6044, 7260}, {6037, 7272}, {6029, 7283}, {6018, 7293}, {6009, 7303}, {6005, 7313}, {5998, 7324}, {5992, 7335}, {5991, 7346}, {5992, 7356}, {5992, 7366}, {5993, 7377}, {5993, 7387}, {5994, 7398}, {5994, 7408}, {5997, 7419}, {6001, 7430}, {6009, 7443}, {6014, 7454}, {6023, 7464}, {6029, 7475}, {6037, 7486}, {6043, 7497}, {6047, 7509}, {6050, 7520}, {6051, 7531}, {6054, 7542}, {6058, 7553}, {6063, 7563}, {6067, 7575}, {6074, 7586}, {6083, 7596}, {6093, 7603}, {6104, 7608}, {6114, 7614}, {6126, 7620}, {6138, 7622}, {6148, 7622}, {6160, 7622}, {6171, 7622}, {6183, 7621}, {6194, 7620}, {6205, 7620}, {6217, 7619}, {6229, 7619}, {6240, 7620}, {6251, 7620}, {6261, 7621}, {6271, 7619}, {6281, 7611}, {6290, 7601}, {6299, 7590}, {6305, 7579}, {6313, 7569}, {6323, 7562}, {6334, 7554}, {6345, 7550}, {6355, 7549}, {6365, 7547}, {6376, 7543}, {6382, 7533}, {6387, 7520}, {6387, 7510}, {6389, 7500}, {6391, 7489}, {6393, 7478}, {6398, 7468}, {6409, 7458}, {6420, 7451}, {6431, 7445}, {6442, 7442}, {6453, 7440}, {6463, 7437}, {6475, 7434}, {6488, 7434}, {6498, 7434}, {6510, 7433}, {6522, 7433}, {6534, 7433}, {6547, 7434}, {6559, 7438}, {6574, 7441}, {6587, 7445}, {6597, 7448}, {6623, 7450}, {6633, 7453}, {6644, 7456}, {6654, 7460}, {6666, 7469}, {6676, 7478}, {6685, 7489}, {6689, 7500}, {6693, 7514}, {6695, 7527}, {6695, 7537}, {6698, 7549}, {6700, 7560}, {6702, 7572}, {6704, 7584}, {6711, 7595}, {6719, 7607}, {6728, 7618}, {6738, 7628}, {6750, 7638}, {6760, 7649}, {6768, 7660}, {6778, 7671}, {6789, 7682}, {6799, 7694}, {6809, 7705}, {6818, 7716}, {6827, 7727}, {6833, 7737}, {6840, 7749}, {6847, 7760}, {6854, 7771}, {6860, 7781}, {6865, 7796}, {6872, 7807}, {6878, 7819}, {6887, 7829}, {6897, 7838}, {6909, 7847}, {6920, 7853}, {6931, 7859}, {6942, 7864}, {6952, 7865}, {6963, 7865}, {6974, 7865}, {6985, 7861}, {6995, 7856}, {7007, 7852}, {7018, 7852}, {7029, 7852}, {7040, 7856}, {7051, 7859}, {7062, 7859}, {7075, 7862}, {7088, 7864}, {7099, 7865}, {7110, 7868}, {7121, 7868}, {7132, 7868}, {7144, 7867}, {7155, 7863}, {7166, 7860}, {7178, 7856}, {7189, 7854}, {7200, 7849}, {7212, 7839}, {7221, 7828}, {7228, 7817}, {7238, 7807}, {7248, 7801}, {7259, 7796}, {7269, 7797}, {7280, 7803}, {7291, 7808}, {7305, 7815}, {7315, 7824}, {7325, 7834}, {7337, 7842}, {7347, 7846}, {7357, 7849}, {7368, 7852}, {7379, 7855}, {7390, 7853}, {7401, 7849}, {7412, 7848}, {7440, 7845}, {7451, 7843}, {7462, 7842}, {7473, 7842}, {7484, 7843}, {7494, 7846}, {7504, 7848}, {7515, 7851}, {7525, 7855}, {7536, 7858}, {7546, 7864}, {7556, 7870}, {7567, 7874}, {7583, 7884}, {7594, 7884}, {7605, 7883}, {7615, 7875}, {7624, 7864}, {7632, 7854}, {7641, 7844}, {7650, 7834}, {7656, 7824}, {7657, 7813}, {7657, 7802}, {7658, 7792}, {7666, 7762}, {7674, 7749}, {7684, 7739}, {7695, 7728}, {7706, 7722}, {7716, 7720}, {7729, 7720}, {7740, 7722}, {7750, 7725}, {7762, 7728}, {7773, 7733}, {7783, 7741}, {7791, 7752}, {7801, 7761}, {7812, 7757}, {7822, 7747}, {7847, 7717}, {7857, 7709}, {7868, 7700}, {7879, 7695}, {7889, 7692}, {7899, 7686}, {7905, 7675}, {7907, 7665}, {7907, 7654}, {7903, 7644}, {7901, 7633}, {7900, 7622}, {7903, 7592}, {7909, 7581}, {7919, 7572}, {7930, 7563}, {7940, 7556}, {7951, 7549}, {7962, 7546}, {7973, 7544}, {7983, 7542}, {7994, 7539}, {8005, 7532}, {8013, 7522}, {8017, 7512}, {8019, 7501}, {8021, 7490}, {8024, 7478}, {8026, 7467}, {8028, 7431}, {8029, 7420}, {8030, 7410}, {8036, 7399}, {8045, 7388}, {8053, 7377}, {8057, 7367}, {8058, 7355}, {8059, 7345}, {8059, 7333}, {8057, 7321}, {8053, 7310}, {8046, 7300}, {8039, 7290}, {8034, 7280}, {8027, 7268}, {8020, 7258}, {8014, 7248}, {7973, 7179}, {7969, 7169}, {7962, 7159}, {7960, 7148}, {7958, 7137}, {7957, 7126}, {7957, 7116}, {7959, 7104}, {7962, 7094}, {7968, 7083}, {7978, 7073}, {7988, 7061}, {7999, 7050}, {8010, 7042}, {8020, 7033}, {8029, 7021}, {8034, 7011}, {8039, 7001}, {8044, 6988}, {8048, 6978}, {8052, 6967}, {8054, 6956}, {8066, 6921}, {8067, 6910}, {8066, 6900}, {8065, 6889}, {8063, 6879}, {8056, 6869}, {8048, 6859}, {8037, 6848}, {8027, 6838}, {8018, 6828}, {8009, 6817}, {8003, 6806}, {7994, 6794}, {7986, 6783}, {7979, 6772}, {7975, 6761}, {7971, 6750}, {7966, 6738}, {7947, 6679}, {7940, 6668}, {7933, 6656}, {7928, 6646}, {7925, 6634}, {7917, 6622}, {7912, 6611}, {7910, 6600}, {7908, 6588}, {7906, 6578}, {7907, 6567}, {7907, 6554}, {7907, 6544}, {7910, 6532}, {7913, 6519}, {7917, 6509}, {7923, 6498}, {7929, 6487}, {7934, 6473}, {7938, 6463}, {7941, 6453}, {7946, 6441}, {7951, 6428}, {7957, 6418}, {7967, 6407}, {7976, 6397}, {7987, 6388}, {8007, 6374}, {8019, 6369}, {8030, 6366}, {8040, 6362}, {8050, 6359}, {8055, 6348}, {8045, 6340}, {8034, 6333}, {8024, 6326}, {8013, 6317}, {8003, 6309}, {7993, 6300}, {7982, 6289}, {7971, 6279}, {7962, 6268}, {7952, 6257}, {7941, 6248}, {7913, 6227}, {7903, 6221}, {7893, 6216}, {7883, 6209}, {7872, 6203}, {7862, 6195}, {7852, 6203}, {7845, 6213}, {7836, 6223}, {7825, 6230}, {7814, 6236}, {7804, 6242}, {7793, 6248}, {7782, 6250}, {7771, 6253}, {7761, 6253}, {7750, 6253}, {7739, 6252}, {7729, 6251}, {7717, 6245}, {7706, 6240}, {7695, 6233}, {7684, 6228}, {7674, 6221}, {7664, 6214}, {7652, 6204}, {7642, 6195}, {7633, 6184}, {7625, 6173}, {7617, 6162}, {7609, 6151}, {7604, 6137}, {7600, 6127}, {7588, 6111}, {7576, 6107}, {7565, 6097}, {7555, 6091}, {7544, 6083}, {7533, 6075}, {7521, 6067}, {7510, 6059}, {7499, 6052}, {7488, 6050}, {7478, 6048}, {7467, 6045}, {7455, 6041}, {7444, 6038}, {7433, 6034}, {7421, 6032}, {7410, 6028}, {7400, 6023}, {7390, 6014}, {7380, 6006}, {7369, 5996}, {7361, 5985}, {7354, 5972}, {7348, 5962}, {7340, 5951}, {7329, 5932}, {7318, 5924}, {7306, 5918}, {7295, 5910}, {7284, 5904}, {7273, 5899}, {7261, 5891}, {7252, 5881}, {7244, 5871}, {7234, 5859}, {7226, 5849}, {7218, 5839}, {7212, 5828}, {7209, 5816}, {7206, 5806}, {7196, 5798}, {7185, 5796}, {7174, 5802}, {7164, 5807}, {7159, 5817}, {7158, 5828}, {7159, 5839}, {7162, 5849}, {7168, 5861}, {7175, 5872}, {7184, 5883}, {7192, 5894}, {7201, 5905}, {7211, 5916}, {7221, 5925}, {7231, 5936}, {7241, 5949}, {7250, 5959}, {7269, 5980}, {7278, 5991}, {7287, 6003}, {7294, 6013}, {7302, 6023}, {7308, 6036}, {7311, 6046}, {7313, 6058}, {7315, 6070}, {7315, 6080}, {7315, 6091}, {7311, 6102}, {7307, 6114}, {7302, 6125}, {7297, 6136}, {7288, 6147}, {7039, 6417}, {7030, 6427}, {7018, 6434}, {7007, 6442}, {6995, 6445}, {6985, 6447}, {6974, 6446}, {6956, 6439}, }, }, startpoints = { {7300, 7300}, }, nameLong = "South-East", nameShort = "SE", }, [1] = { boxes = { { {1013, 2302}, {929, 2202}, {923, 2192}, {920, 2181}, {920, 2171}, {922, 2160}, {925, 2149}, {934, 2139}, {945, 2133}, {957, 2125}, {1256, 1815}, {1267, 1809}, {1278, 1806}, {1289, 1805}, {1299, 1808}, {1309, 1818}, {1386, 1892}, {1397, 1899}, {1407, 1893}, {1408, 1883}, {1408, 1873}, {1408, 1863}, {1411, 1852}, {1419, 1842}, {1429, 1834}, {1440, 1827}, {1450, 1821}, {1461, 1817}, {1473, 1812}, {1484, 1810}, {1494, 1809}, {1504, 1807}, {1515, 1805}, {1580, 1795}, {1592, 1793}, {1603, 1790}, {1613, 1785}, {1624, 1783}, {1635, 1781}, {1646, 1780}, {1660, 1777}, {1671, 1776}, {1682, 1776}, {1693, 1776}, {1704, 1776}, {1715, 1772}, {1723, 1761}, {1719, 1750}, {1716, 1739}, {1712, 1729}, {1710, 1719}, {1707, 1647}, {1712, 1629}, {1725, 1612}, {1825, 1536}, {1873, 1502}, {1889, 1486}, {1898, 1475}, {1903, 1464}, {1908, 1453}, {1912, 1442}, {1917, 1431}, {1922, 1421}, {1927, 1410}, {1930, 1398}, {1932, 1387}, {1933, 1377}, {1934, 1366}, {1930, 1355}, {1926, 1345}, {1921, 1334}, {1912, 1323}, {1901, 1312}, {1891, 1303}, {1884, 1293}, {1880, 1282}, {1878, 1270}, {1879, 1259}, {1880, 1248}, {1883, 1238}, {1888, 1227}, {1898, 1217}, {1981, 1154}, {2039, 1121}, {2063, 1114}, {2073, 1109}, {2080, 1099}, {2085, 1088}, {2087, 1078}, {2088, 1067}, {2089, 1055}, {2089, 1044}, {2086, 1033}, {2085, 1023}, {2085, 1012}, {2090, 991}, {2095, 981}, {2106, 971}, {2116, 964}, {2182, 922}, {2192, 915}, {2199, 903}, {2200, 893}, {2199, 883}, {2192, 872}, {2182, 864}, {2175, 854}, {2173, 842}, {2171, 832}, {2170, 822}, {2165, 808}, {2155, 800}, {2144, 792}, {2134, 785}, {2123, 778}, {2113, 774}, {2103, 771}, {2092, 766}, {2082, 756}, {2071, 746}, {2067, 736}, {2065, 726}, {2064, 715}, {2061, 705}, {2058, 694}, {2055, 629}, {2051, 619}, {2044, 608}, {2034, 604}, {2024, 603}, {2014, 603}, {2004, 601}, {1992, 599}, {1982, 597}, {1971, 593}, {1960, 588}, {1928, 569}, {1918, 565}, {1908, 563}, {1897, 563}, {1888, 573}, {1885, 584}, {1882, 594}, {1878, 605}, {1846, 649}, {1796, 702}, {1785, 711}, {1774, 717}, {1764, 723}, {1756, 734}, {1749, 744}, {1745, 755}, {1739, 765}, {1730, 775}, {1720, 783}, {1710, 788}, {1699, 794}, {1688, 799}, {1677, 801}, {1667, 803}, {1655, 805}, {1645, 806}, {1635, 808}, {1624, 808}, {1613, 808}, {1602, 806}, {1591, 803}, {1581, 799}, {1570, 795}, {1559, 791}, {1549, 787}, {1537, 782}, {1524, 775}, {1514, 770}, {1504, 764}, {1493, 754}, {1485, 743}, {1475, 732}, {1470, 720}, {1467, 708}, {1465, 697}, {1453, 641}, {1447, 631}, {1441, 620}, {1434, 610}, {1429, 599}, {1422, 588}, {1417, 578}, {1410, 567}, {1403, 556}, {1396, 546}, {1387, 534}, {1377, 526}, {1365, 516}, {1354, 508}, {1343, 499}, {1332, 492}, {1300, 464}, {1290, 453}, {1282, 443}, {1276, 432}, {1272, 421}, {1269, 411}, {1267, 400}, {1265, 390}, {1263, 379}, {1260, 368}, {1255, 357}, {1251, 347}, {1248, 336}, {1242, 325}, {1236, 314}, {1230, 303}, {1222, 293}, {1212, 284}, {1202, 282}, {1191, 284}, {1186, 295}, {1181, 306}, {1175, 317}, {1168, 327}, {1162, 337}, {1152, 347}, {1140, 358}, {1129, 366}, {1119, 374}, {1107, 381}, {1096, 388}, {1086, 394}, {1075, 402}, {1064, 407}, {1054, 412}, {1044, 416}, {1033, 418}, {1021, 422}, {1008, 424}, {995, 425}, {985, 426}, {973, 426}, {963, 425}, {952, 424}, {942, 422}, {931, 421}, {921, 418}, {911, 416}, {871, 396}, {859, 388}, {849, 380}, {838, 372}, {828, 366}, {818, 363}, {808, 357}, {798, 352}, {785, 346}, {775, 342}, {765, 340}, {754, 337}, {742, 337}, {732, 337}, {722, 337}, {712, 337}, {701, 336}, {690, 332}, {679, 331}, {666, 330}, {655, 330}, {644, 340}, {635, 351}, {630, 361}, {629, 372}, {628, 382}, {628, 392}, {626, 404}, {625, 415}, {619, 426}, {613, 436}, {608, 446}, {596, 453}, {586, 455}, {574, 459}, {562, 462}, {551, 465}, {540, 467}, {528, 471}, {517, 475}, {505, 478}, {493, 483}, {483, 489}, {471, 494}, {459, 497}, {448, 502}, {437, 506}, {425, 507}, {415, 506}, {403, 499}, {393, 491}, {383, 485}, {372, 477}, {362, 468}, {352, 474}, {349, 484}, {349, 494}, {350, 505}, {350, 516}, {350, 526}, {350, 536}, {351, 547}, {352, 557}, {351, 567}, {350, 578}, {346, 589}, {338, 599}, {330, 610}, {321, 620}, {308, 629}, {298, 637}, {287, 641}, {277, 644}, {267, 647}, {257, 650}, {246, 652}, {235, 654}, {225, 656}, {214, 663}, {203, 673}, {194, 684}, {184, 694}, {181, 704}, {180, 715}, {180, 725}, {179, 737}, {179, 749}, {181, 760}, {186, 770}, {191, 781}, {195, 797}, {196, 808}, {196, 819}, {193, 830}, {188, 841}, {182, 851}, {174, 862}, {163, 872}, {152, 880}, {142, 888}, {134, 898}, {129, 909}, {124, 919}, {120, 929}, {115, 940}, {114, 951}, {118, 962}, {119, 972}, {125, 1004}, {125, 1014}, {126, 1026}, {126, 1037}, {126, 1047}, {128, 1057}, {131, 1068}, {137, 1079}, {142, 1089}, {148, 1102}, {151, 1112}, {155, 1122}, {160, 1133}, {161, 1152}, {163, 1163}, {166, 1174}, {166, 1185}, {165, 1197}, {164, 1208}, {163, 1218}, {163, 1229}, {163, 1239}, {163, 1249}, {167, 1259}, {175, 1269}, {183, 1280}, {190, 1291}, {197, 1301}, {203, 1312}, {206, 1322}, {209, 1332}, {211, 1343}, {212, 1354}, {214, 1366}, {215, 1377}, {216, 1388}, {217, 1400}, {218, 1410}, {218, 1420}, {217, 1430}, {215, 1440}, {214, 1451}, {217, 1462}, {227, 1473}, {238, 1479}, {255, 1487}, {268, 1495}, {279, 1504}, {288, 1515}, {293, 1525}, {300, 1537}, {303, 1547}, {306, 1565}, {306, 1577}, {307, 1587}, {308, 1598}, {314, 1609}, {318, 1621}, {322, 1631}, {327, 1642}, {330, 1652}, {331, 1664}, {331, 1674}, {328, 1685}, {326, 1696}, {315, 1707}, {305, 1718}, {299, 1729}, {264, 1751}, {255, 1761}, {245, 1769}, {239, 1780}, {249, 1791}, {261, 1799}, {271, 1807}, {282, 1815}, {291, 1825}, {298, 1837}, {300, 1848}, {303, 1861}, {304, 1873}, {307, 1884}, {310, 1895}, {314, 1945}, {316, 1955}, {319, 1966}, {320, 1976}, {320, 1987}, {320, 1998}, {318, 2009}, {315, 2019}, {326, 2017}, {336, 2008}, {346, 2002}, {356, 1999}, {367, 1997}, {377, 1995}, {387, 1991}, {398, 1990}, {408, 1986}, {420, 1977}, {431, 1969}, {442, 1963}, {453, 1960}, {463, 1959}, {474, 1958}, {484, 1958}, {497, 1960}, {509, 1961}, {519, 1962}, {529, 1964}, {540, 1966}, {553, 1971}, {565, 1977}, {575, 1986}, {585, 1997}, {594, 2008}, {599, 2019}, {603, 2029}, {605, 2040}, {606, 2052}, {606, 2062}, {606, 2074}, {617, 2080}, {627, 2081}, {638, 2083}, {648, 2085}, {659, 2085}, {669, 2088}, {680, 2091}, {690, 2094}, {700, 2097}, {711, 2093}, {720, 2081}, {730, 2071}, {749, 2059}, {762, 2059}, {775, 2059}, {786, 2059}, {798, 2057}, {809, 2057}, {819, 2058}, {829, 2062}, {840, 2068}, {851, 2074}, {859, 2084}, {863, 2094}, {866, 2105}, {868, 2117}, {869, 2128}, {869, 2139}, {864, 2150}, {856, 2160}, {845, 2169}, {835, 2177}, {824, 2186}, {816, 2196}, {822, 2206}, {899, 2274}, {906, 2284}, {910, 2296}, {914, 2307}, {918, 2317}, {922, 2327}, {926, 2338}, {932, 2348}, {941, 2358}, {951, 2367}, {962, 2376}, {973, 2386}, {982, 2396}, {989, 2406}, {999, 2417}, {1009, 2427}, {1019, 2435}, {1022, 2425}, {1031, 2415}, {1037, 2405}, {1048, 2395}, {1059, 2386}, {1069, 2376}, {1068, 2366}, {1062, 2354}, {1055, 2343}, {1044, 2333}, {1033, 2323}, {1019, 2310}, }, }, startpoints = { {800, 800}, }, nameLong = "North-West", nameShort = "NW", }, }, { 2 }
gpl-2.0
czfshine/Don-t-Starve
data/scripts/brains/butterflybrain.lua
1
1760
require "behaviours/runaway" require "behaviours/wander" require "behaviours/doaction" require "behaviours/findflower" require "behaviours/panic" local RUN_AWAY_DIST = 5 local STOP_RUN_AWAY_DIST = 10 local POLLINATE_FLOWER_DIST = 10 local SEE_FLOWER_DIST = 30 local MAX_WANDER_DIST = 20 local function NearestFlowerPos(inst) local flower = GetClosestInstWithTag("flower", inst, SEE_FLOWER_DIST) if flower and flower:IsValid() then return Vector3(flower.Transform:GetWorldPosition() ) end end local function GoHomeAction(inst) local flower = GetClosestInstWithTag("flower", inst, SEE_FLOWER_DIST) if flower and flower:IsValid() then return BufferedAction(inst, flower, ACTIONS.GOHOME, nil, Vector3(flower.Transform:GetWorldPosition() )) end end local ButterflyBrain = Class(Brain, function(self, inst) Brain._ctor(self, inst) end) function ButterflyBrain:OnStart() local clock = GetClock() local root = PriorityNode( { WhileNode( function() return self.inst.components.health.takingfiredamage end, "OnFire", Panic(self.inst)), RunAway(self.inst, "scarytoprey", RUN_AWAY_DIST, STOP_RUN_AWAY_DIST), IfNode(function() return clock and not clock:IsDay() end, "IsNight", DoAction(self.inst, GoHomeAction, "go home", true )), IfNode(function() return self.inst.components.pollinator:HasCollectedEnough() end, "IsFullOfPollen", DoAction(self.inst, GoHomeAction, "go home", true )), FindFlower(self.inst), Wander(self.inst, NearestFlowerPos, MAX_WANDER_DIST) },1) self.bt = BT(self.inst, root) end return ButterflyBrain
gpl-2.0
CrazyEddieTK/Zero-K
LuaUI/Configs/zk_keys.lua
2
5833
return { -- yyyymmdd -- if newer than user's, overwrite ALL zir zk_keys -- else just add any that are missing from local config ["date"] = 20130630, -- all default ZK keybinds. ["keybinds"] = { { "togglecammode", "Ctrl+backspace",}, { "togglecammode", "Shift+backspace",}, { "edit_backspace", "Any+backspace",}, { "toggleoverview", "Ctrl+tab",}, { "edit_complete", "Any+tab",}, { "chatally", {"Alt+enter", "Alt+numpad_enter"}, }, { "chatswitchally", {"Alt+enter", "Alt+numpad_enter"}, }, { "chatall", {"Ctrl+enter", "Ctrl+numpad_enter"}, }, { "chatswitchall", {"Ctrl+enter", "Ctrl+numpad_enter"}, }, { "chatspec", "None"}, { "chatswitchspec", "None"}, { "chat", {"Any+enter", "Any+numpad_enter"}, }, { "edit_return", {"Any+enter", "Any+numpad_enter"}, }, { "pause", "pause",}, { "crudemenu", "esc",}, { "exitwindow", "shift+esc",}, { "quitforce", "Ctrl+Shift+esc",}, { "edit_escape", "Any+escape",}, { "speedup", { "Any++","Any+=","Any+numpad+"}, }, { "prevmenu", ",",}, { "decguiopacity", "Shift+,",}, { "slowdown", {"Any+-","Any+numpad-",}, }, { "nextmenu", ".",}, { "incguiopacity", "Shift+.",}, { "specteam 9", "0",}, { "specteam 19", "Ctrl+0",}, { "group0", "Any+0",}, { "specteam 0", "1",}, { "specteam 10", "Ctrl+1",}, { "group1", "Any+1",}, { "specteam 1", "2",}, { "specteam 11", "Ctrl+2",}, { "group2", "Any+2",}, { "specteam 2", "3",}, { "specteam 12", "Ctrl+3",}, { "group3", "Any+3",}, { "specteam 3", "4",}, { "specteam 13", "Ctrl+4",}, { "group4", "Any+4",}, { "specteam 4", "5",}, { "specteam 14", "Ctrl+5",}, { "group5", "Any+5",}, { "specteam 5", "6",}, { "specteam 15", "Ctrl+6",}, { "group6", "Any+6",}, { "specteam 6", "7",}, { "specteam 16", "Ctrl+7",}, { "group7", "Any+7",}, { "specteam 7", "8",}, { "specteam 17", "Ctrl+8",}, { "group8", "Any+8",}, { "specteam 8", "9",}, { "specteam 18", "Ctrl+9",}, { "group9", "Any+9",}, { "buildfacing inc", {"Any+insert", "[", "Shift+[",}, }, { "drawinmap", { "Any+\\", "Any+`", "Any+0xa7", "Any+^", }, }, { "clearmapmarks", "Alt+`"}, { "buildfacing dec", {"Any+delete", "]","Shift+]",}, }, { "attack", "f",}, { "areaattack", "Alt+a",}, { "debug", "Ctrl+Alt+n",}, { "debugcolvol", "Ctrl+Alt+b",}, { "repeat", "ctrl+r"}, { "priority", "ctrl+q"}, { "selfd", "C+d",}, { "selectcomm", "ctrl+c",}, { "manualfire", "d",}, { "oneclickwep", "d",}, { "placebeacon", "d",}, { "reclaim", "e",}, { "fight", "a",}, { "forcestart", "Alt+f",}, --{ "guard", "g",}, { "areaguard", "g",}, { "gameinfo", "Ctrl+Alt+i",}, { "wantcloak", "k",}, { "togglelos", "Ctrl+l",}, { "loadunits", "l",}, { "loadselected", "l",}, { "rawmove", "m",}, { "singlestep", "Alt+o",}, { "patrol", "p",}, { "groupclear", "Shift+q",}, { "repair", "r",}, { "stop", "s",}, { "stopproduction", "ctrl+s",}, { "globalbuildcancel", "alt+s",}, { "unloadunits", "u",}, { "pastetext", "Ctrl+v",}, { "wait", "ctrl+w",}, { "areamex", "w",}, { "onoff", "o",}, { "pushpull", "o",}, { "buildspacing dec", "Any+x",}, { "buildspacing inc", "Any+z",}, { "edit_delete", "Any+delete",}, { "edit_prev_line", "Any+up",}, { "moveforward", "Any+up",}, { "edit_next_line", "Any+down",}, { "moveback", "Any+down",}, { "edit_end", "Alt+right",}, { "edit_next_word", "Ctrl+right",}, { "edit_next_char", "Any+right",}, { "moveright", "Any+right",}, { "edit_home", "Alt+left",}, { "edit_prev_word", "Ctrl+left",}, { "edit_prev_char", "Any+left",}, { "moveleft", "Any+left",}, { "increaseviewradius", "home",}, { "edit_home", "Any+home",}, { "decreaseviewradius", "end",}, { "edit_end", "Any+end",}, { "moveup", "Any+pageup",}, { "movedown", "Any+pagedown",}, { "showelevation", "f1",}, { "togglestatsgraph", "A+f1"}, { "showpathtraversability", "f2",}, { "lastmsgpos", "f3",}, { "showeco", "f4",}, { "showmetalmap", "None"}, { "HideInterface", "None",}, { "hideinterfaceandcursor", "ctrl+f5",}, { "NoSound", "Any+f6",}, { "DynamicSky", "Any+f7",}, { "savegame", "Ctrl+Shift+f8",}, { "luaui showhealthbars", "alt+f9",}, { "showhealthbars", "alt+f9",}, { "createvideo", "Ctrl+Shift+f10",}, { "viewlobby", "f11",}, { "luaui tweakgui", "C+f11",}, { "epic_chili_widget_selector_widgetlist_2", "alt+f11",}, { "screenshot png", "f12",}, { "screenshot jpg", "ctrl+f12"}, { "settargetcircle", "t",}, { "resurrect", "t",}, { "jump", "j",}, { "select AllMap++_ClearSelection_SelectAll+", "ctrl+a",}, { "selectidlecon_all", "ctrl+b",}, { "select PrevSelection+_Not_RelativeHealth_30+_ClearSelection_SelectAll+", "ctrl+e",}, { "select AllMap+_Not_Builder_Not_Building+_ClearSelection_SelectAll+", "ctrl+f",}, { "select AllMap+_NameContain_Raptor+_ClearSelection_SelectAll+", "ctrl+g",}, { "select PrevSelection+_Idle+_ClearSelection_SelectAll+", "ctrl+i",}, { "select AllMap+_Not_Builder_Not_Building_Not_Transport_Aircraft_Radar+_ClearSelection_SelectAll+", "ctrl+s",}, { "select AllMap+_Not_Builder_Not_Building_Transport_Aircraft+_ClearSelection_SelectAll+", "ctrl+t",}, { "selectidlecon", "z",}, { "select Visible+_InPrevSel+_ClearSelection_SelectAll+", "ctrl+x",}, { "select AllMap+_InPrevSel+_ClearSelection_SelectAll+", "ctrl+z",}, { "epic_chili_integral_menu_tab_economy", "any+x",}, { "epic_chili_integral_menu_tab_defence", "any+c",}, { "epic_chili_integral_menu_tab_special", "any+v",}, { "epic_chili_integral_menu_tab_factory", "any+b",}, { "epic_chili_integral_menu_tab_units", "any+n",}, { "exitwindow", "s+escape",}, { "crudesubmenu", "f10"}, { "epic_chili_pro_console_enableconsole", "f8"}, { "epic_chili_share_menu_v1.22_sharemenu", "tab"}, }, }
gpl-2.0
czfshine/Don-t-Starve
data/scripts/widgets/text.lua
1
1600
local Widget = require "widgets/widget" local Text = Class(Widget, function(self, font, size, text) Widget._ctor(self, "Text") self.inst.entity:AddTextWidget() self.inst.TextWidget:SetFont(font) self.inst.TextWidget:SetSize(size) if text then self:SetString( text ) end end) function Text:__tostring() return string.format("%s - %s", self.name, self.string or "") end function Text:SetColour(r,g,b,a) if type(r) == "number" then self.inst.TextWidget:SetColour(r, g, b, a) else self.inst.TextWidget:SetColour(r[1], r[2], r[3], r[4]) end end function Text:SetHorizontalSqueeze( squeeze ) self.inst.TextWidget:SetHorizontalSqueeze(squeeze) end function Text:SetAlpha(a) self.inst.TextWidget:SetColour(1,1,1, a) end function Text:SetFont(font) self.inst.TextWidget:SetFont(font) end function Text:SetSize(sz) self.inst.TextWidget:SetSize(sz) end function Text:SetRegionSize(w,h) self.inst.TextWidget:SetRegionSize(w,h) end function Text:GetRegionSize() return self.inst.TextWidget:GetRegionSize() end function Text:SetString(str) self.string = str self.inst.TextWidget:SetString(str or "") end function Text:GetString() --print("Text:GetString()", self.inst.TextWidget:GetString()) return self.inst.TextWidget:GetString() or "" end function Text:SetVAlign(anchor) self.inst.TextWidget:SetVAnchor(anchor) end function Text:SetHAlign(anchor) self.inst.TextWidget:SetHAnchor(anchor) end function Text:EnableWordWrap(enable) self.inst.TextWidget:EnableWordWrap(enable) end return Text
gpl-2.0
zhujunsan/nodemcu-firmware
lua_examples/email/send_email_smtp.lua
82
4640
--- -- Working Example: https://www.youtube.com/watch?v=CcRbFIJ8aeU -- @description a basic SMTP email example. You must use an account which can provide unencrypted authenticated access. -- This example was tested with an AOL and Time Warner email accounts. GMail does not offer unecrypted authenticated access. -- To obtain your email's SMTP server and port simply Google it e.g. [my email domain] SMTP settings -- For example for timewarner you'll get to this page http://www.timewarnercable.com/en/support/faqs/faqs-internet/e-mailacco/incoming-outgoing-server-addresses.html -- To Learn more about SMTP email visit: -- SMTP Commands Reference - http://www.samlogic.net/articles/smtp-commands-reference.htm -- See "SMTP transport example" in this page http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol -- @author Miguel require("base64") -- The email and password from the account you want to send emails from local MY_EMAIL = "esp8266@domain.com" local EMAIL_PASSWORD = "123456" -- The SMTP server and port of your email provider. -- If you don't know it google [my email provider] SMTP settings local SMTP_SERVER = "smtp.server.com" local SMTP_PORT = "587" -- The account you want to send email to local mail_to = "to_email@domain.com" -- Your access point's SSID and password local SSID = "ssid" local SSID_PASSWORD = "password" -- configure ESP as a station wifi.setmode(wifi.STATION) wifi.sta.config(SSID,SSID_PASSWORD) wifi.sta.autoconnect(1) -- These are global variables. Don't change their values -- they will be changed in the functions below local email_subject = "" local email_body = "" local count = 0 local smtp_socket = nil -- will be used as socket to email server -- The display() function will be used to print the SMTP server's response function display(sck,response) print(response) end -- The do_next() function is used to send the SMTP commands to the SMTP server in the required sequence. -- I was going to use socket callbacks but the code would not run callbacks after the first 3. function do_next() if(count == 0)then count = count+1 local IP_ADDRESS = wifi.sta.getip() smtp_socket:send("HELO "..IP_ADDRESS.."\r\n") elseif(count==1) then count = count+1 smtp_socket:send("AUTH LOGIN\r\n") elseif(count == 2) then count = count + 1 smtp_socket:send(base64.enc(MY_EMAIL).."\r\n") elseif(count == 3) then count = count + 1 smtp_socket:send(base64.enc(EMAIL_PASSWORD).."\r\n") elseif(count==4) then count = count+1 smtp_socket:send("MAIL FROM:<" .. MY_EMAIL .. ">\r\n") elseif(count==5) then count = count+1 smtp_socket:send("RCPT TO:<" .. mail_to ..">\r\n") elseif(count==6) then count = count+1 smtp_socket:send("DATA\r\n") elseif(count==7) then count = count+1 local message = string.gsub( "From: \"".. MY_EMAIL .."\"<"..MY_EMAIL..">\r\n" .. "To: \"".. mail_to .. "\"<".. mail_to..">\r\n".. "Subject: ".. email_subject .. "\r\n\r\n" .. email_body,"\r\n.\r\n","") smtp_socket:send(message.."\r\n.\r\n") elseif(count==8) then count = count+1 tmr.stop(0) smtp_socket:send("QUIT\r\n") else smtp_socket:close() end end -- The connectted() function is executed when the SMTP socket is connected to the SMTP server. -- This function will create a timer to call the do_next function which will send the SMTP commands -- in sequence, one by one, every 5000 seconds. -- You can change the time to be smaller if that works for you, I used 5000ms just because. function connected(sck) tmr.alarm(0,5000,1,do_next) end -- @name send_email -- @description Will initiated a socket connection to the SMTP server and trigger the connected() function -- @param subject The email's subject -- @param body The email's body function send_email(subject,body) count = 0 email_subject = subject email_body = body smtp_socket = net.createConnection(net.TCP,0) smtp_socket:on("connection",connected) smtp_socket:on("receive",display) smtp_socket:connect(SMTP_PORT,SMTP_SERVER) end -- Send an email send_email( "ESP8266", [[Hi, How are your IoT projects coming along? Best Wishes, ESP8266]])
mit
czfshine/Don-t-Starve
mods/Cretaceous/wicker/math/probability/markovchain.lua
6
5689
--- -- @description Implements a discrete Markov Chain over a finite set of states. -- @author simplex local Lambda = wickerrequire 'paradigms.functional' local Pred = wickerrequire 'lib.predicates' local table = wickerrequire 'utils.table' --- -- The markov chain class. -- -- @class table -- @name MarkovChain -- local MarkovChain = Class(function(self) -- Current state. self.state = nil -- Transition matrix. But instead of numerical indexes, it is indexed -- by the states directly, as a hash map of hash maps. self.P = {} end) Pred.IsMarkovChain = Pred.IsInstanceOf(MarkovChain) local function _(self) if not Pred.IsMarkovChain(self) then return error("Markov Chain expected as `self'.", 2) end end --- -- @class function -- -- Returns the transition function, which is called on a state change, -- receiving the old state followed by the new. -- -- @return the transition function. function MarkovChain:GetTransitionFn() _(self) return self.transitionfn or Lambda.Nil end --- -- Sets the transition function. -- -- @param fn The new transition function. function MarkovChain:SetTransitionFn(fn) _(self) self.transitionfn = fn end --- -- @return An iterator triple over the states. function MarkovChain:States() _(self) return table.keys(self.P) end --- -- @return The current state. function MarkovChain:GetState() _(self) return self.state end MarkovChain.GetCurrentState = MarkovChain.GetState --- -- Returns whether the argument is a state. function MarkovChain:IsState(s) _(self) return self.P[s] ~= nil end --- -- Adds a new state. function MarkovChain:AddState(s) _(self) self.P[s] = self.P[s] or {} end --- -- Removes a given state. function MarkovChain:RemoveState(s) _(self) for _, edges in pairs(Q) do edges[s] = nil end Q[s] = nil end --- -- Sets the initial state. If not present already, it is added. function MarkovChain:SetInitialState(s) _(self) self:AddState(s) self.state = s end --- -- Goes to a target state, calling the transition function if the target -- state differs from the current one. function MarkovChain:GoTo(t) _(self) local s = self.state if s ~= t then assert( self:IsState(t), "Invalid target state." ) self.state = t self:GetTransitionFn()(s, t) end end --- -- @class function -- -- GoTo alias. -- -- @see Goto MarkovChain.GoToState = MarkovChain.GoTo --- -- Sets the transition probability (for a single step) from u to v. -- -- @param u The initial state. -- @param v The target state. -- @param p The probability of going from u to v. -- @param symmetric Whether the same probability should be attached to going from v to u. function MarkovChain:SetTransitionProbability(u, v, p, symmetric) _(self) assert( self:IsState(u), "Invalid origin state." ) assert( self:IsState(v), "Invalid target state." ) assert( u ~= v, "The origin can't be the same as the target." ) assert( p == nil or Pred.IsNonNegativeNumber(p) or Pred.IsCallable(p), "The transition rate should be nil, non-negative or a function." ) if p == 0 then p = nil end self.P[u][v] = p if symmetric then self:SetTransitionProbability(v, u, p, false) end end --- -- Processes a chain specification in table format. function MarkovChain:ProcessSpecs(specs) _(self) self:SetInitialState( assert( specs[1], "Initial state not given." ) ) for pair, p in pairs(specs) do if pair ~= 1 then assert( Pred.IsTable(pair) and #pair == 2, "State pair expected as spec key." ) local u, v = unpack(pair) self:AddState(u) self:AddState(v) self:SetTransitionProbability(u, v, p) end end end --- -- Steps the markov chain. function MarkovChain:Step() _(self) local p = math.random() for u, q in pairs(self.P[self:GetState()]) do if Pred.IsCallable(q) then q = q() end if p < q then self:GoTo(u) break else p = p - q end end end MarkovChain.__call = MarkovChain.Step --- -- Returns a debug string. function MarkovChain:__tostring() local states = Lambda.CompactlyInjectInto({}, table.keys(self.P)) local states_str = Lambda.CompactlyMapInto(tostring, {}, ipairs(states)) local max_len = Lambda.MaximumOf(string.len, ipairs(states_str)) states_str = Lambda.CompactlyMap(function(v) return v..(" "):rep(max_len - #v) end, ipairs(states_str)) local pad_str = (" "):rep(max_len) local lines = {} table.insert(lines, table.concat( Lambda.CompactlyInjectInto({pad_str}, ipairs(states_str)) , " ")) local fmt_str = "%"..max_len..".3f" for i, s in ipairs(states) do local leftover = 1 - Lambda.Fold(Lambda.Add, table.values(self.P[s])) table.insert(lines, table.concat( Lambda.CompactlyMapInto(function(t, j) local val if i == j then val = leftover else val = self.P[s][t] end if val then return fmt_str:format(val) else return ("?"):rep(max_len) end end, {states_str[i]}, ipairs(states)) , " ")) end return table.concat(lines, "\n") end local function GenerateMethodAliases() local affix_aliases = { State = {"Node"}, TransitionProbability = {"EdgeWeight"}, } local new_methods = {} for k, v in pairs(MarkovChain) do if type(k) == "string" and type(v) == "function" and not k:match("^_") then for affix, repl_table in pairs(affix_aliases) do local prefix, suffix = k:match("^(.*)" .. affix .. "(.*)$") if prefix then for _, repl in ipairs(repl_table) do local new_name = prefix .. repl .. suffix if MarkovChain[new_name] == nil then assert( new_methods[new_name] == nil ) new_methods[new_name] = v end end end end end end for k, v in pairs(new_methods) do MarkovChain[k] = v end end GenerateMethodAliases() return MarkovChain
gpl-2.0
XLILT/vstruct
ast.lua
6
4980
-- Abstract Syntax Tree module for vstruct -- This module implements the parser for vstruct format definitions. It is a -- fairly simple recursive-descent parser that constructs an AST using Lua -- tables, and then generates lua source from it. -- See ast/*.lua for the implementations of various node types in the AST, -- and see lexer.lua for the implementation of the lexer. -- Copyright (c) 2011 Ben "ToxicFrog" Kelly local vstruct = require "vstruct" local lexer = require "vstruct.lexer" local ast = {} local cache = {} -- load the implementations of the various AST node types for _,node in ipairs { "IO", "List", "Name", "Table", "Repeat", "Root", "Bitpack" } do ast[node] = require ((...).."."..node) end -- given a source string, compile it -- returns a table containing pack and unpack functions and the original -- source - see README#vstruct.compile for a description. -- -- if (vstruct.cache) is non-nil, will return the cached version, if present -- if (vstruct.cache) is true, will create a new cache entry, if needed function ast.parse(source) local lex = lexer(source) local root = ast.List() for node in (function() return ast.next(lex) end) do root:append(node) end return ast.Root(root) end -- used by the rest of the parser to report syntax errors function ast.error(lex, expected) error("vstruct: parsing format string at "..lex.where()..": expected "..expected..", got "..lex.peek().type) end -- Everything below this line is internal to the recursive descent parser function ast.io(lex) local io = ast.raw_io(lex) if io.hasvalue then return ast.Name(nil, io) else return io end end function ast.raw_io(lex) local name = lex.next().text local next = lex.peek() if next and next.type == "number" and not lex.whitespace() then return ast.IO(name, lex.next().text) else return ast.IO(name, nil) end end function ast.key(lex) local name = lex.next().text local next = lex.peek() if next.type == "io" then local io = ast.raw_io(lex) if not io.hasvalue then ast.error(lex, "value (io specifier or table) - format '"..name.."' has no value") end return ast.Name(name, io) elseif next.type == "{" then return ast.Name(name, ast.raw_table(lex)) else ast.error(lex, "value (io specifier or table)") end end function ast.next(lex) local tok = lex.peek() if tok.type == "EOF" then return nil end if tok.type == '(' then return ast.group(lex) elseif tok.type == '{' then return ast.table(lex) elseif tok.type == '[' then return ast.bitpack(lex) elseif tok.type == "io" then return ast.io(lex) elseif tok.type == "key" then return ast.key(lex) elseif tok.type == "number" then return ast.repetition(lex) elseif tok.type == "control" then return ast.control(lex) elseif tok.type == "splice" then return ast.splice(lex) else ast.error(lex, "'(', '{', '[', name, number, control, or io specifier") end end function ast.next_until(lex, type) return function() local tok = lex.peek() if tok.type == 'EOF' then ast.error(lex, type) end if tok.type == type then return nil end return ast.next(lex) end end function ast.splice(lex) local name = lex.next().text local root = vstruct.registry[name] if not root then error("vstruct: attempt to splice in format '"..name.."', which is not registered") end return root[1] end function ast.repetition(lex) local count = tonumber(lex.next().text) ast.require(lex, "*"); return ast.Repeat(count, ast.next(lex)) end function ast.group(lex) ast.require(lex, '(') local group = ast.List() group.tag = "group" for next in ast.next_until(lex, ')') do group:append(next) end ast.require(lex, ')') return group end function ast.table(lex) return ast.Name(nil, ast.raw_table(lex)) end function ast.raw_table(lex) ast.require(lex, '{') local group = ast.Table() for next in ast.next_until(lex, '}') do group:append(next) end ast.require(lex, '}') return group end function ast.bitpack(lex) ast.require(lex, "[") local bitpack = ast.Bitpack(tonumber(ast.require(lex, "number").text)) ast.require(lex, "|") for next in ast.next_until(lex, ']') do bitpack:append(next) end ast.require(lex, "]") bitpack:finalize() return bitpack end function ast.require(lex, type) local t = lex.next() if t.type ~= type then ast.error(lex, type) end return t end return ast --[[ format -> commands command -> repeat | bitpack | group | named | value | control | splice repeat -> NUMBER '*' command | command '*' NUMBER bitpack -> '[' NUMBER '|' commands ']' group -> '(' commands ')' named -> NAME ':' value value -> table | primitive table -> '{' commands '}' splice -> '&' NAME primitive -> ATOM NUMBERS control -> SEEK NUMBER | ENDIANNESS --]]
mit
mamadtnt/erfan
plugins/Banhammer.lua
4
10464
local function is_user_whitelisted(id) local hash = 'whitelist:user#id'..id local white = redis:get(hash) or false return white end local function is_chat_whitelisted(id) local hash = 'whitelist:chat#id'..id local white = redis:get(hash) or false return white end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function superban_user(user_id, chat_id) -- Save to redis local hash = 'superbanned:'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function is_super_banned(user_id) local hash = 'superbanned:'..user_id local superbanned = redis:get(hash) return superbanned or false end local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local user_id = msg.from.id local chat_id = msg.to.id local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, chat_id) if superbanned then print('SuperBanned user talking!') superban_user(user_id, chat_id) msg.text = '' end if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end -- WHITELIST local hash = 'whitelist:enabled' local whitelist = redis:get(hash) local issudo = is_sudo(msg) -- Allow all sudo users even if whitelist is allowed if whitelist and not issudo then print('Whitelist enabled and not sudo') -- Check if user or chat is whitelisted local allowed = is_user_whitelisted(msg.from.id) if not allowed then print('User '..msg.from.id..' not whitelisted') if msg.to.type == 'chat' then allowed = is_chat_whitelisted(msg.to.id) if not allowed then print ('Chat '..msg.to.id..' not whitelisted') else print ('Chat '..msg.to.id..' whitelisted :)') end end else print('User '..msg.from.id..' allowed :)') end if not allowed then msg.text = '' end else print('Whitelist not enabled or is sudo') end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'superban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!') return superban_user(member_id, chat_id) elseif get_cmd == 'whitelist user' then local hash = 'whitelist:user#id'..member_id redis:set(hash, true) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted') elseif get_cmd == 'whitelist delete user' then local hash = 'whitelist:user#id'..member_id redis:del(hash) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist') end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1] == 'bye' then kick_user(msg.from.id, msg.to.id) end if not is_momod(msg) then return nil end local receiver = get_receiver(msg) if matches[4] then get_cmd = matches[1]..' '..matches[2]..' '..matches[3] elseif matches[3] then get_cmd = matches[1]..' '..matches[2] else get_cmd = matches[1] end if matches[1] == 'ban' then local user_id = matches[3] local chat_id = msg.to.id if msg.to.type == 'chat' then if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then ban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end else return 'This isn\'t a chat group' end end if matches[1] == 'superban' and is_admin(msg) then local user_id = matches[3] local chat_id = msg.to.id if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then superban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' globally banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'superbanned:'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if matches[1] == 'whitelist' then if matches[2] == 'enable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:set(hash, true) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then if string.match(matches[4], '^%d+$') then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' else local member = string.gsub(matches[4], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'delete' and matches[3] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:del(hash) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist' end end end return { description = "Plugin to manage bans, kicks and white/black lists.", usage = { user = "!kickme : Exit from group", moderator = { "!whitelist <enable>/<disable> : Enable or disable whitelist mode", "!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled", "!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled", "!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled", "!whitelist delete user <user_id> : Remove user from whitelist", "!whitelist delete chat : Remove chat from whitelist", "!ban user <user_id> : Kick user from chat and kicks it if joins chat again", "!ban user <username> : Kick user from chat and kicks it if joins chat again", "!ban delete <user_id> : Unban user", "!kick <user_id> : Kick user from chat group by id", "!kick <username> : Kick user from chat group by username", }, admin = { "!superban user <user_id> : Kick user from all chat and kicks it if joins again", "!superban user <username> : Kick user from all chat and kicks it if joins again", "!superban delete <user_id> : Unban user", }, }, patterns = { "^!(whitelist) (enable)$", "^!(whitelist) (disable)$", "^!(whitelist) (user) (.*)$", "^!(whitelist) (chat)$", "^!(whitelist) (delete) (user) (.*)$", "^!(whitelist) (delete) (chat)$", "^!(ban) (user) (.*)$", "^!(ban) (delete) (.*)$", "^!(superban) (user) (.*)$", "^!(superban) (delete) (.*)$", "^!(kick) (.*)$", "^(bye)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
rzh/mongocraft
world/Plugins/Core/web_chat.lua
6
11601
local CHAT_HISTORY = 50 local LastMessageID = 0 local JavaScript = [[ <script type="text/javascript"> function createXHR() { var request = false; try { request = new ActiveXObject('Msxml2.XMLHTTP'); } catch (err2) { try { request = new ActiveXObject('Microsoft.XMLHTTP'); } catch (err3) { try { request = new XMLHttpRequest(); } catch (err1) { request = false; } } } return request; } function OpenPage( url, postParams, callback ) { var xhr = createXHR(); xhr.onreadystatechange=function() { if (xhr.readyState == 4) { callback( xhr ) } }; xhr.open( (postParams!=null)?"POST":"GET", url , true); if( postParams != null ) { xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); } xhr.send(postParams); } function LoadPageInto( url, postParams, storage ) { OpenPage( url, postParams, function( xhr ) { var ScrollBottom = storage.scrollTop + storage.offsetHeight; var bAutoScroll = (ScrollBottom >= storage.scrollHeight); // Detect whether we scrolled to the bottom of the div results = xhr.responseText.split("<<divider>>"); if( results[2] != LastMessageID ) return; // Check if this message was meant for us LastMessageID = results[1]; if( results[0] != "" ) { storage.innerHTML += results[0]; if( bAutoScroll == true ) { storage.scrollTop = storage.scrollHeight; } } } ); return false; } function SendChatMessage() { var MessageContainer = document.getElementById('ChatMessage'); if( MessageContainer.value == "" ) return; var postParams = "ChatMessage=" + MessageContainer.value; OpenPage( "/~webadmin/Core/Chat/", postParams, function( xhr ) { RefreshChat(); } ); MessageContainer.value = ""; } function RefreshChat() { var postParams = "JustChat=true&LastMessageID=" + LastMessageID; LoadPageInto("/~webadmin/Core/Chat/", postParams, document.getElementById('ChatDiv')); } setInterval(RefreshChat, 1000); window.onload = RefreshChat; var LastMessageID = 0; </script> ]] -- Array of {PluginName, FunctionName} tables local OnWebChatCallbacks = {} local ChatLogMessages = {} local WebCommands = {} local ltNormal = 1 local ltInfo = 2 local ltWarning = 3 local ltError = 4 -- Adds Webchat callback, plugins can return true to -- prevent message from appearing / being processed -- by further callbacks -- OnWebChat(Username, Message) function AddWebChatCallback(PluginName, FunctionName) for k, v in pairs(OnWebChatCallbacks) do if v[1] == PluginName and v[2] == FunctionName then return false end end table.insert(OnWebChatCallbacks, {PluginName, FunctionName}) return true end -- Removes webchat callback function RemoveWebChatCallback(PluginName, FunctionName) for i = #OnWebChatCallbacks, 0, -1 do if OnWebChatCallbacks[i][1] == PluginName and OnWebChatCallbacks[i][2] == FunctionName then table.remove(OnWebChatCallbacks, i) return true end end return false end -- Checks the chatlogs to see if the size gets too big. function TrimWebChatIfNeeded() while( #ChatLogMessages > CHAT_HISTORY ) do table.remove( ChatLogMessages, 1 ) end end -- Adds a plain message to the chat log -- The a_WebUserName parameter can be either a string(name) to send it to a certain webuser or nil to send it to every webuser. function WEBLOG(a_Message, a_WebUserName) LastMessageID = LastMessageID + 1 table.insert(ChatLogMessages, {timestamp = os.date("[%Y-%m-%d %H:%M:%S]", os.time()), webuser = a_WebUserName, message = a_Message, id = LastMessageID, logtype = ltNormal}) TrimWebChatIfNeeded() end -- Adds a yellow-ish message to the chat log. -- The a_WebUserName parameter can be either a string(name) to send it to a certain webuser or nil to send it to every webuser. function WEBLOGINFO(a_Message, a_WebUserName) LastMessageID = LastMessageID + 1 table.insert(ChatLogMessages, {timestamp = os.date("[%Y-%m-%d %H:%M:%S]", os.time()), webuser = a_WebUserName, message = a_Message, id = LastMessageID, logtype = ltInfo}) TrimWebChatIfNeeded() end -- Adds a red message to the chat log -- The a_WebUserName parameter can be either a string(name) to send it to a certain webuser or nil to send it to every webuser. function WEBLOGWARN(a_Message, a_WebUserName) LastMessageID = LastMessageID + 1 table.insert(ChatLogMessages, {timestamp = os.date("[%Y-%m-%d %H:%M:%S]", os.time()), webuser = a_WebUserName, message = a_Message, id = LastMessageID, logtype = ltWarning}) TrimWebChatIfNeeded() end -- Adds a message with a red background to the chat log -- The a_WebUserName parameter can be either a string(name) to send it to a certain webuser or nil to send it to every webuser. function WEBLOGERROR(a_Message, a_WebUserName) LastMessageID = LastMessageID + 1 table.insert(ChatLogMessages, {timestamp = os.date("[%Y-%m-%d %H:%M:%S]", os.time()), webuser = a_WebUserName, message = a_Message, id = LastMessageID, logtype = ltError}) TrimWebChatIfNeeded() end -- This function allows other plugins to add new commands to the webadmin. -- a_CommandString is the the way you call the command ("/help") -- a_HelpString is the message that tells you what the command does ("Shows a list of all the possible commands") -- a_PluginName is the name of the plugin binding the command ("Core") -- a_CallbackName is the name if the function that will be called when the command is executed ("HandleWebHelpCommand") function BindWebCommand(a_CommandString, a_HelpString, a_PluginName, a_CallbackName) assert(type(a_CommandString) == 'string') assert(type(a_PluginName) == 'string') assert(type(a_CallbackName) == 'string') -- Check if the command is already bound. Return false with an error message if. for Idx, CommandInfo in ipairs(WebCommands) do if (CommandInfo.Command == a_CommandString) then return false, "That command is already bound to a plugin called \"" .. CommandInfo.PluginName .. "\"." end end -- Insert the command into the array and return true table.insert(WebCommands, {CommandString = a_CommandString, HelpString = a_HelpString, PluginName = a_PluginName, CallbackName = a_CallbackName}) return true end -- Used by the webadmin to use /help function HandleWebHelpCommand(a_User, a_Message) local Content = "Available Commands:" for Idx, CommandInfo in ipairs(WebCommands) do if (CommandInfo.HelpString ~= "") then Content = Content .. '<br />' .. CommandInfo.CommandString .. '&ensp; - &ensp;' .. CommandInfo.HelpString end end WEBLOG(Content, a_User) return true end -- Used by the webadmin to reload the server function HandleWebReloadCommand(a_User, a_Message) cPluginManager:Get():ReloadPlugins() WEBLOG("Reloading Plugins", a_User) return true end -- Register some basic commands BindWebCommand("/help", "Shows a list of all the possible commands", "Core", "HandleWebHelpCommand") BindWebCommand("/reload", "Reloads all the plugins", "Core", "HandleWebReloadCommand") -- Add a chatmessage from a player to the chatlog function OnChat(a_Player, a_Message) WEBLOG("[" .. a_Player:GetName() .. "]: " .. a_Message) end --- Removes html tags --- Creates a tag when http(s) links are send. --- It does this by selecting all the characters between "http(s)://" and a space, and puts an anker tag around it. local function ParseMessage(a_Message) local function PlaceString(a_Url) return '<a href="' .. a_Url .. '" target="_blank">' .. a_Url .. '</a>' end a_Message = a_Message:gsub("<", "&lt;"):gsub(">", "&gt;"):gsub("=", "&#61;"):gsub('"', "&#34;"):gsub("'", "&#39;"):gsub("&", "&amp;") a_Message = a_Message:gsub('http://[^%s]+', PlaceString):gsub('https://[^%s]+', PlaceString) return a_Message end function HandleRequest_Chat( Request ) -- The webadmin asks if there are new messages. if( Request.PostParams["JustChat"] ~= nil ) then local LastIdx = tonumber(Request.PostParams["LastMessageID"] or 0) or 0 local Content = "" -- Go through each message to see if they are older then the last message, and add them to the content for key, MessageInfo in pairs(ChatLogMessages) do if( MessageInfo.id > LastIdx ) then if (not MessageInfo.webuser or (MessageInfo.webuser == Request.Username)) then local Message = MessageInfo.timestamp .. ' ' .. ParseMessage(MessageInfo.message) if (MessageInfo.logtype == ltNormal) then Content = Content .. Message .. "<br />" elseif (MessageInfo.logtype == ltInfo) then Content = Content .. '<span style="color: #FE9A2E;">' .. Message .. '</span><br />' elseif (MessageInfo.logtype == ltWarning) then Content = Content .. '<span style="color: red;">' .. Message .. '</span><br />' elseif (MessageInfo.logtype == ltError) then Content = Content .. '<span style="background-color: red; color: black;">' .. Message .. '</span><br />' end end end end Content = Content .. "<<divider>>" .. LastMessageID .. "<<divider>>" .. LastIdx return Content end -- Check if the webuser send a chat message. if( Request.PostParams["ChatMessage"] ~= nil ) then local Split = StringSplit(Request.PostParams["ChatMessage"]) local CommandExecuted = false -- Check if the message was actualy a command for Idx, CommandInfo in ipairs(WebCommands) do if (CommandInfo.CommandString == Split[1]) then -- cPluginManager:CallPlugin doesn't support calling yourself, so we have to check if the command is from the Core. if (CommandInfo.PluginName == "Core") then if (not _G[CommandInfo.CallbackName](Request.Username, Request.PostParams["ChatMessage"])) then WEBLOG("Something went wrong while calling \"" .. CommandInfo.CallbackName .. "\" From \"" .. CommandInfo.PluginName .. "\".", Request.Username) end else if (not cPluginManager:CallPlugin(CommandInfo.PluginName, CommandInfo.CallbackName, Request.Username, Request.PostParams["ChatMessage"])) then WEBLOG("Something went wrong while calling \"" .. CommandInfo.CallbackName .. "\" From \"" .. CommandInfo.PluginName .. "\".", Request.Username) end end return "" end end -- If the message starts with a '/' then the message is a command, but since it wasn't executed a few lines above the command didn't exist if (Request.PostParams["ChatMessage"]:sub(1, 1) == "/") then WEBLOG('Unknown Command "' .. Request.PostParams["ChatMessage"] .. '"', nil) return "" end -- Broadcast the message to the server for k, v in pairs(OnWebChatCallbacks) do if cPluginManager:CallPlugin(v[1], v[2], Request.Username, Request.PostParams["ChatMessage"]) then return "" end end cRoot:Get():BroadcastChat(cCompositeChat("[WEB] <" .. Request.Username .. "> " .. Request.PostParams["ChatMessage"]):UnderlineUrls()) -- Add the message to the chatlog WEBLOG("[WEB] [" .. Request.Username .. "]: " .. Request.PostParams["ChatMessage"]) return "" end local Content = JavaScript Content = Content .. [[ <div style="font-family: Courier; border: 1px solid #DDD; padding: 10px; width: 97%; height: 400px; overflow: scroll;" id="ChatDiv"></div> <input type="text" id="ChatMessage" onKeyPress="if (event.keyCode == 13) { SendChatMessage(); }"><input type="submit" value="Submit" onClick="SendChatMessage();"> ]] return Content end
apache-2.0
KenMGJ/advent-of-code
lua/complex.lua
1
1136
complex = {} local calculated = {} local private = {} function private.complexToString(t) local sym = "" if t.i >= 0 then sym = "+" end return t.r .. sym .. t.i .. "i" end function complex.new (r, i) -- We want to make sure that for r == r and i == i that new == new local create = false if calculated[r] == nil then calculated[r] = {} create = true elseif calculated[r][i] == nil then create = true end if create then local c = { r = r, i = i } setmetatable( c, { __tostring = private.complexToString } ) calculated[r][i] = c end return calculated[r][i] end -- defines a constant `i' complex.i = complex.new(0, 1) function complex.add (c1, c2) return complex.new(c1.r + c2.r, c1.i + c2.i) end function complex.sub (c1, c2) return complex.new(c1.r - c2.r, c1.i - c2.i) end function complex.mul (c1, c2) return complex.new(c1.r*c2.r - c1.i*c2.i, c1.r*c2.i + c1.i*c2.r) end function complex.inv (c) local n = c.r^2 + c.i^2 return complex.new(c.r/n, -c.i/n) end return complex
mit
Ameeralasdee/FROLA
libs/lua-redis.lua
580
35599
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis
gpl-3.0
mcdooda/The-Global-Scourge
mods/menu/scripts/game.lua
1
1647
local Menu = require 'data/scripts/menu' local Alert = require 'data/scripts/alert' local CameraTools = require 'data/scripts/cameratools' local Fade = require 'data/scripts/fade' CameraTools.lookAtCenter() Camera.lock() Sound.preloadMusic('music.mp3') Sound.preloadSample('voice.wav') Sound.preloadSample('build.wav') Sound.preloadSample('explosion.wav') Sound.preloadSample('loot.wav') Sound.setMusicVolume(0.5) Sound.fadeInMusic('menu.mp3', 5) Input.onKeyDown(Input.ESCAPE, Game.exit) local sin = math.sin local mapTiles = Map.getTiles() Timer.new( 0.02, true, function(timer, age) for _, tile in pairs(mapTiles) do local x, y = Tile.getPosition(tile) local amplitude = math.exp(-age + 1) + 0.2 Tile.setZ(tile, sin(age * 5 + x - y) * amplitude) end end ) local function openMenu() local menu = Menu:new(nil, 'Campagne', function() Fade.appear(2) Timer.new( 2, false, function() Game.load('mods/tutorial1') end ) end, --'Partie rapide', function() end, 'Crédits', function() Alert:new( { 'Auteurs de The Global Scourge :', 'Programmation par Nicolas Dodelier', 'Graphismes par Tom Rouillard et Jon Rouillard', 'Musique libre par Boris Descombes Croset' }, 'Fermer', openMenu ) end, 'Quitter', Game.exit ) menu:setPosition { x = 0, y = -150 } end openMenu() Widget.new { image = 'data/game/interface/tgs.png', anchor = Widget.BOTTOM + Widget.RIGHT, pixelPerfect = true, position = { x = -10, y = 10 } } Widget.new { image = 'data/game/interface/logo.png', anchor = Widget.CENTERX + Widget.CENTERY, pixelPerfect = true }
gpl-2.0
StoneDot/luasocket
test/httptest.lua
19
11480
-- needs Alias from /home/c/diego/tec/luasocket/test to -- "/luasocket-test" and "/luasocket-test/" -- needs ScriptAlias from /home/c/diego/tec/luasocket/test/cgi -- to "/luasocket-test-cgi" and "/luasocket-test-cgi/" -- needs "AllowOverride AuthConfig" on /home/c/diego/tec/luasocket/test/auth local socket = require("socket") local http = require("socket.http") local url = require("socket.url") local mime = require("mime") local ltn12 = require("ltn12") -- override protection to make sure we see all errors -- socket.protect = function(s) return s end dofile("testsupport.lua") local host, proxy, request, response, index_file local ignore, expect, index, prefix, cgiprefix, index_crlf http.TIMEOUT = 10 local t = socket.gettime() --host = host or "diego.student.princeton.edu" --host = host or "diego.student.princeton.edu" host = host or "localhost" proxy = proxy or "http://localhost:3128" prefix = prefix or "/luasocket-test" cgiprefix = cgiprefix or "/luasocket-test-cgi" index_file = "index.html" -- read index with CRLF convention index = readfile(index_file) local check_result = function(response, expect, ignore) for i,v in pairs(response) do if not ignore[i] then if v ~= expect[i] then local f = io.open("err", "w") f:write(tostring(v), "\n\n versus\n\n", tostring(expect[i])) f:close() fail(i .. " differs!") end end end for i,v in pairs(expect) do if not ignore[i] then if v ~= response[i] then local f = io.open("err", "w") f:write(tostring(response[i]), "\n\n versus\n\n", tostring(v)) v = string.sub(type(v) == "string" and v or "", 1, 70) f:close() fail(i .. " differs!") end end end print("ok") end local check_request = function(request, expect, ignore) local t if not request.sink then request.sink, t = ltn12.sink.table() end request.source = request.source or (request.body and ltn12.source.string(request.body)) local response = {} response.code, response.headers, response.status = socket.skip(1, http.request(request)) if t and #t > 0 then response.body = table.concat(t) end check_result(response, expect, ignore) end ------------------------------------------------------------------------ io.write("testing request uri correctness: ") local forth = cgiprefix .. "/request-uri?" .. "this+is+the+query+string" local back, c, h = http.request("http://" .. host .. forth) if not back then fail(c) end back = url.parse(back) if similar(back.query, "this+is+the+query+string") then print("ok") else fail(back.query) end ------------------------------------------------------------------------ io.write("testing query string correctness: ") forth = "this+is+the+query+string" back = http.request("http://" .. host .. cgiprefix .. "/query-string?" .. forth) if similar(back, forth) then print("ok") else fail("failed!") end ------------------------------------------------------------------------ io.write("testing document retrieval: ") request = { url = "http://" .. host .. prefix .. "/index.html" } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing redirect loop: ") request = { url = "http://" .. host .. cgiprefix .. "/redirect-loop" } expect = { code = 302 } ignore = { status = 1, headers = 1, body = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing invalid url: ") local r, e = http.request{url = host .. prefix} assert(r == nil and e == "invalid host ''") r, re = http.request(host .. prefix) assert(r == nil and e == re, tostring(r) ..", " .. tostring(re) .. " vs " .. tostring(e)) print("ok") io.write("testing invalid empty port: ") request = { url = "http://" .. host .. ":" .. prefix .. "/index.html" } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing post method: ") -- wanted to test chunked post, but apache doesn't support it... request = { url = "http://" .. host .. cgiprefix .. "/cat", method = "POST", body = index, -- remove content-length header to send chunked body headers = { ["content-length"] = string.len(index) } } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ --[[ io.write("testing proxy with post method: ") request = { url = "http://" .. host .. cgiprefix .. "/cat", method = "POST", body = index, headers = { ["content-length"] = string.len(index) }, proxy= proxy } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ]] ------------------------------------------------------------------------ io.write("testing simple post function: ") back = http.request("http://" .. host .. cgiprefix .. "/cat", index) assert(back == index) print("ok") ------------------------------------------------------------------------ io.write("testing ltn12.(sink|source).file: ") request = { url = "http://" .. host .. cgiprefix .. "/cat", method = "POST", source = ltn12.source.file(io.open(index_file, "rb")), sink = ltn12.sink.file(io.open(index_file .. "-back", "wb")), headers = { ["content-length"] = string.len(index) } } expect = { code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) back = readfile(index_file .. "-back") assert(back == index) os.remove(index_file .. "-back") ------------------------------------------------------------------------ io.write("testing ltn12.(sink|source).chain and mime.(encode|decode): ") local function b64length(len) local a = math.ceil(len/3)*4 local l = math.ceil(a/76) return a + l*2 end local source = ltn12.source.chain( ltn12.source.file(io.open(index_file, "rb")), ltn12.filter.chain( mime.encode("base64"), mime.wrap("base64") ) ) local sink = ltn12.sink.chain( mime.decode("base64"), ltn12.sink.file(io.open(index_file .. "-back", "wb")) ) request = { url = "http://" .. host .. cgiprefix .. "/cat", method = "POST", source = source, sink = sink, headers = { ["content-length"] = b64length(string.len(index)) } } expect = { code = 200 } ignore = { body_cb = 1, status = 1, headers = 1 } check_request(request, expect, ignore) back = readfile(index_file .. "-back") assert(back == index) os.remove(index_file .. "-back") ------------------------------------------------------------------------ io.write("testing http redirection: ") request = { url = "http://" .. host .. prefix } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ --[[ io.write("testing proxy with redirection: ") request = { url = "http://" .. host .. prefix, proxy = proxy } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ]] ------------------------------------------------------------------------ io.write("testing automatic auth failure: ") request = { url = "http://really:wrong@" .. host .. prefix .. "/auth/index.html" } expect = { code = 401 } ignore = { body = 1, status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing http redirection failure: ") request = { url = "http://" .. host .. prefix, redirect = false } expect = { code = 301 } ignore = { body = 1, status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing document not found: ") request = { url = "http://" .. host .. "/wrongdocument.html" } expect = { code = 404 } ignore = { body = 1, status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing auth failure: ") request = { url = "http://" .. host .. prefix .. "/auth/index.html" } expect = { code = 401 } ignore = { body = 1, status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing manual basic auth: ") request = { url = "http://" .. host .. prefix .. "/auth/index.html", headers = { authorization = "Basic " .. (mime.b64("luasocket:password")) } } expect = { code = 200, body = index } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing automatic basic auth: ") request = { url = "http://luasocket:password@" .. host .. prefix .. "/auth/index.html" } expect = { code = 200, body = index } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing auth info overriding: ") request = { url = "http://really:wrong@" .. host .. prefix .. "/auth/index.html", user = "luasocket", password = "password" } expect = { code = 200, body = index } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing cgi output retrieval (probably chunked...): ") request = { url = "http://" .. host .. cgiprefix .. "/cat-index-html" } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ local body io.write("testing simple request function: ") body = http.request("http://" .. host .. prefix .. "/index.html") assert(body == index) print("ok") ------------------------------------------------------------------------ io.write("testing HEAD method: ") local r, c, h = http.request { method = "HEAD", url = "http://www.tecgraf.puc-rio.br/~diego/" } assert(r and h and (c == 200), c) print("ok") ------------------------------------------------------------------------ io.write("testing host not found: ") local c, e = socket.connect("example.invalid", 80) local r, re = http.request{url = "http://example.invalid/does/not/exist"} assert(r == nil and e == re, tostring(r) .. " " .. tostring(re)) r, re = http.request("http://example.invalid/does/not/exist") assert(r == nil and e == re) print("ok") ------------------------------------------------------------------------ print("passed all tests") os.remove("err") print(string.format("done in %.2fs", socket.gettime() - t))
mit
abbasgh12345/abbasbotfinall
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
czfshine/Don-t-Starve
data/scripts/prefabs/cookpot.lua
1
6156
require "prefabutil" local cooking = require("cooking") local assets= { Asset("ANIM", "anim/cook_pot.zip"), Asset("ANIM", "anim/cook_pot_food.zip"), } local prefabs = {} for k,v in pairs(cooking.recipes.cookpot) do table.insert(prefabs, v.name) end local function onhammered(inst, worker) if inst.components.stewer.product and inst.components.stewer.done then inst.components.lootdropper:AddChanceLoot(inst.components.stewer.product, 1) end inst.components.lootdropper:DropLoot() SpawnPrefab("collapse_small").Transform:SetPosition(inst.Transform:GetWorldPosition()) inst.SoundEmitter:PlaySound("dontstarve/common/destroy_metal") inst:Remove() end local function onhit(inst, worker) inst.AnimState:PlayAnimation("hit_empty") if inst.components.stewer.cooking then inst.AnimState:PushAnimation("cooking_loop") elseif inst.components.stewer.done then inst.AnimState:PushAnimation("idle_full") else inst.AnimState:PushAnimation("idle_empty") end end local slotpos = { Vector3(0,64+32+8+4,0), Vector3(0,32+4,0), Vector3(0,-(32+4),0), Vector3(0,-(64+32+8+4),0)} local widgetbuttoninfo = { text = "Cook", position = Vector3(0, -165, 0), fn = function(inst) inst.components.stewer:StartCooking() end, validfn = function(inst) return inst.components.stewer:CanCook() end, } local function itemtest(inst, item, slot) if cooking.IsCookingIngredient(item.prefab) then return true end end --anim and sound callbacks local function ShowProduct(inst) if not inst:HasTag("burnt") then local product = inst.components.stewer.product if IsModCookingProduct(inst.prefab, product) then inst.AnimState:OverrideSymbol("swap_cooked", product, product) else inst.AnimState:OverrideSymbol("swap_cooked", "cook_pot_food", product) end end end local function startcookfn(inst) inst.AnimState:PlayAnimation("cooking_loop", true) --play a looping sound inst.SoundEmitter:KillSound("snd") inst.SoundEmitter:PlaySound("dontstarve/common/cookingpot_rattle", "snd") inst.Light:Enable(true) end local function onopen(inst) inst.AnimState:PlayAnimation("cooking_pre_loop", true) inst.SoundEmitter:PlaySound("dontstarve/common/cookingpot_open", "open") inst.SoundEmitter:PlaySound("dontstarve/common/cookingpot", "snd") end local function onclose(inst) if not inst.components.stewer.cooking then inst.AnimState:PlayAnimation("idle_empty") inst.SoundEmitter:KillSound("snd") end inst.SoundEmitter:PlaySound("dontstarve/common/cookingpot_close", "close") end local function donecookfn(inst) inst.AnimState:PlayAnimation("cooking_pst") inst.AnimState:PushAnimation("idle_full") ShowProduct(inst) inst.SoundEmitter:KillSound("snd") inst.SoundEmitter:PlaySound("dontstarve/common/cookingpot_finish", "snd") inst.Light:Enable(false) --play a one-off sound end local function continuedonefn(inst) inst.AnimState:PlayAnimation("idle_full") ShowProduct(inst) end local function continuecookfn(inst) inst.AnimState:PlayAnimation("cooking_loop", true) --play a looping sound inst.Light:Enable(true) inst.SoundEmitter:PlaySound("dontstarve/common/cookingpot_rattle", "snd") end local function harvestfn(inst) inst.AnimState:PlayAnimation("idle_empty") end local function getstatus(inst) if inst.components.stewer.cooking and inst.components.stewer:GetTimeToCook() > 15 then return "COOKING_LONG" elseif inst.components.stewer.cooking then return "COOKING_SHORT" elseif inst.components.stewer.done then return "DONE" else return "EMPTY" end end local function onfar(inst) inst.components.container:Close() end local function onbuilt(inst) inst.AnimState:PlayAnimation("place") inst.AnimState:PushAnimation("idle_empty") end local function fn(Sim) local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddSoundEmitter() local minimap = inst.entity:AddMiniMapEntity() minimap:SetIcon( "cookpot.png" ) local light = inst.entity:AddLight() inst.Light:Enable(false) inst.Light:SetRadius(.6) inst.Light:SetFalloff(1) inst.Light:SetIntensity(.5) inst.Light:SetColour(235/255,62/255,12/255) --inst.Light:SetColour(1,0,0) inst:AddTag("structure") MakeObstaclePhysics(inst, .5) inst.AnimState:SetBank("cook_pot") inst.AnimState:SetBuild("cook_pot") inst.AnimState:PlayAnimation("idle_empty") inst:AddComponent("stewer") inst.components.stewer.onstartcooking = startcookfn inst.components.stewer.oncontinuecooking = continuecookfn inst.components.stewer.oncontinuedone = continuedonefn inst.components.stewer.ondonecooking = donecookfn inst.components.stewer.onharvest = harvestfn inst:AddComponent("container") inst.components.container.itemtestfn = itemtest inst.components.container:SetNumSlots(4) inst.components.container.widgetslotpos = slotpos inst.components.container.widgetanimbank = "ui_cookpot_1x4" inst.components.container.widgetanimbuild = "ui_cookpot_1x4" inst.components.container.widgetpos = Vector3(200,0,0) inst.components.container.side_align_tip = 100 inst.components.container.widgetbuttoninfo = widgetbuttoninfo inst.components.container.acceptsstacks = false inst.components.container.type = "cooker" inst.components.container.onopenfn = onopen inst.components.container.onclosefn = onclose inst:AddComponent("inspectable") inst.components.inspectable.getstatus = getstatus inst:AddComponent("playerprox") inst.components.playerprox:SetDist(3,5) inst.components.playerprox:SetOnPlayerFar(onfar) inst:AddComponent("lootdropper") inst:AddComponent("workable") inst.components.workable:SetWorkAction(ACTIONS.HAMMER) inst.components.workable:SetWorkLeft(4) inst.components.workable:SetOnFinishCallback(onhammered) inst.components.workable:SetOnWorkCallback(onhit) MakeSnowCovered(inst, .01) inst:ListenForEvent( "onbuilt", onbuilt) return inst end return Prefab( "common/cookpot", fn, assets, prefabs), MakePlacer( "common/cookpot_placer", "cook_pot", "cook_pot", "idle_empty" )
gpl-2.0
ranisalt/forgottenserver
data/scripts/actions/others/belongings_of_a_deceased_shargon.lua
7
1220
local config = { {chanceFrom = 0, chanceTo = 2500, itemId = 5741}, -- skull helmet {chanceFrom = 2501, chanceTo = 5000, itemId = 2160}, -- crystal coin {chanceFrom = 5001, chanceTo = 7500, itemId = 2436}, -- skull staff {chanceFrom = 7501, chanceTo = 10000, itemId = 9969} -- black skull } local belongingsShargon = Action() function belongingsShargon.onUse(player, item, fromPosition, target, toPosition, isHotkey) local chance = math.random(0, 10000) for i = 1, #config do local randomItem = config[i] if chance >= randomItem.chanceFrom and chance <= randomItem.chanceTo then local gift = randomItem.itemId local count = randomItem.count or 1 if type(count) == "table" then count = math.random(count[1], count[2]) end player:addItem(gift, count) local itemType = ItemType(gift) player:say("You found " .. (count > 1 and count or (itemType:getArticle() ~= "" and itemType:getArticle() or "")) .. " " .. (count > 1 and itemType:getPluralName() or itemType:getName()) .. " in the bag.", TALKTYPE_MONSTER_SAY) item:getPosition():sendMagicEffect(CONST_ME_POFF) item:remove(1) return true end end return false end belongingsShargon:id(23705) belongingsShargon:register()
gpl-2.0
czfshine/Don-t-Starve
data/DLC0001/scripts/prefabs/world.lua
1
5190
local groundtiles = require "worldtiledefs" local common_prefabs = { "minimap", "evergreen", "evergreen_normal", "evergreen_short", "evergreen_tall", "evergreen_sparse", "evergreen_sparse_normal", "evergreen_sparse_short", "evergreen_sparse_tall", "evergreen_burnt", "evergreen_stump", "sapling", "berrybush", "berrybush2", "grass", "rock1", "rock2", "rock_flintless", "tallbirdnest", "hound", "firehound", "icehound", "krampus", "mound", "pigman", "pighouse", "pigking", "mandrake", "chester", "rook", "bishop", "knight", "goldnugget", "crow", "robin", "robin_winter", "butterfly", "flint", "log", "spiderden", "spawnpoint", "fireflies", "turf_road", "turf_rocky", "turf_marsh", "turf_savanna", "turf_dirt", "turf_forest", "turf_grass", "turf_cave", "turf_fungus", "turf_sinkhole", "turf_underrock", "turf_mud", "skeleton", "insanityrock", "sanityrock", "basalt", "basalt_pillar", "houndmound", "houndbone", "pigtorch", "red_mushroom", "green_mushroom", "blue_mushroom", "mermhouse", "flower_evil", "blueprint", "lockedwes", "wormhole_limited_1", "diviningrod", "diviningrodbase", "splash_ocean", "maxwell_smoke", "chessjunk1", "chessjunk2", "chessjunk3", "statue_transition_2", "statue_transition", "glommer", "moose", "mossling", "lightninggoat", "bearger", "smoke_plant", "acorn", "deciduoustree", "deciduoustree_normal", "deciduoustree_tall", "deciduoustree_short", "deciduoustree_burnt", "deciduoustree_stump", "buzzardspawner", "cactus", "dragonfly", "webberskull", "catcoonhat", "catcoon", "catcoonden", "statueglommer", "warg", "armordragonfly", "beargervest", "featherfan", } local assets = { Asset("SOUND", "sound/sanity.fsb"), Asset("SOUND", "sound/amb_stream.fsb"), Asset("SHADER", "shaders/uifade.ksh"), } for k,v in pairs(groundtiles.assets) do table.insert(assets, v) end --[[ Stick your username in here and use dprint to only print output when you're running the game --]] if CHEATS_ENABLED and TheSim:GetUsersName() == "David Forsey" then global("CHEATS_KEEP_SAVE") global("CHEATS_ENABLE_DPRINT") global("DPRINT_USERNAME") DPRINT_USERNAME = TheSim:GetUsersName() end --er.... huh? function PlayCreatureSound(inst, sound, creature) local creature = creature or inst.soundgroup or inst.prefab inst.SoundEmitter:PlaySound("dontstarve/creatures/" .. creature .. "/" .. sound) end function onremove(inst) inst.minimap:Remove() end local function fn(Sim) local inst = CreateEntity() inst:AddTag( "ground" ) inst:AddTag( "NOCLICK" ) inst.entity:SetCanSleep(false) inst.persists = false local trans = inst.entity:AddTransform() local map = inst.entity:AddMap() local pathfinder = inst.entity:AddPathfinder() local groundcreep = inst.entity:AddGroundCreep() local sound = inst.entity:AddSoundEmitter() for i, data in ipairs( groundtiles.ground ) do local tile_type, props = unpack( data ) local layer_name = props.name local handle = MapLayerManager:CreateRenderLayer( tile_type, --embedded map array value resolvefilepath(GroundAtlas( layer_name )), resolvefilepath(GroundImage( layer_name )), resolvefilepath(props.noise_texture) ) map:AddRenderLayer( handle ) -- TODO: When this object is destroyed, these handles really should be freed. At this time, this is not an -- issue because the map lifetime matches the game lifetime but if this were to ever change, we would have -- to clean up properly or we leak memory end for i, data in ipairs( groundtiles.creep ) do local tile_type, props = unpack( data ) local handle = MapLayerManager:CreateRenderLayer( tile_type, resolvefilepath(GroundAtlas( props.name )), resolvefilepath(GroundImage( props.name )), resolvefilepath(props.noise_texture ) ) groundcreep:AddRenderLayer( handle ) end local underground_layer = groundtiles.underground[1][2] local underground_handle = MapLayerManager:CreateRenderLayer( GROUND.UNDERGROUND, resolvefilepath(GroundAtlas( underground_layer.name )), resolvefilepath(GroundImage( underground_layer.name )), resolvefilepath(underground_layer.noise_texture) ) map:SetUndergroundRenderLayer( underground_handle ) map:SetImpassableType( GROUND.IMPASSABLE ) --common stuff inst.IsCave = function() return inst:HasTag("cave") end inst.IsRuins = function() return inst:HasTag("cave") and inst:HasTag("ruin") end --clock is now added at the sub-prefab level (forest.lua, cave.lua) inst:AddComponent("groundcreep") inst:AddComponent("ambientsoundmixer") inst:AddComponent("age") inst:AddComponent("moisturemanager") inst:AddComponent("inventorymoisture") inst.minimap = SpawnPrefab("minimap") inst.OnRemoveEntity = onremove return inst end return Prefab( "worlds/world", fn, assets, common_prefabs, true)
gpl-2.0
czfshine/Don-t-Starve
data/DLC0001/scripts/prefabs/birdcage.lua
1
7421
require "prefabutil" local assets= { Asset("ANIM", "anim/bird_cage.zip"), Asset("ANIM", "anim/crow_build.zip"), Asset("ANIM", "anim/robin_build.zip"), Asset("ANIM", "anim/robin_winter_build.zip"), } local prefabs = { "bird_egg", -- everything it can "produce" and might need symbol swaps from "crow", "robin", "robin_winter", "collapse_small", } local bird_symbols= { "crow_beak", "crow_body", "crow_eye", "crow_leg", "crow_wing", "tail_feather", } local function ShouldAcceptItem(inst, item) local seed_name = string.lower(item.prefab .. "_seeds") local can_accept = item.components.edible and (Prefabs[seed_name] or item.prefab == "seeds" or item.components.edible.foodtype == "MEAT") if item.prefab == "egg" or item.prefab == "bird_egg" or item.prefab == "rottenegg" or item.prefab == "monstermeat" then can_accept = false end return can_accept end local function OnRefuseItem(inst, item) inst.AnimState:PlayAnimation("flap") inst.SoundEmitter:PlaySound("dontstarve/birds/wingflap_cage") inst.AnimState:PushAnimation("idle_bird") end local function OnGetItemFromPlayer(inst, giver, item) if inst.components.sleeper and inst.components.sleeper:IsAsleep() then inst.components.sleeper:WakeUp() end if item.components.edible then local seed_name = string.lower(item.prefab .. "_seeds") local can_accept = Prefabs[seed_name] or item.prefab == "seeds" or item.components.edible.foodtype == "MEAT" if can_accept then inst.AnimState:PlayAnimation("peck") inst.AnimState:PushAnimation("peck") inst.AnimState:PushAnimation("peck") inst.AnimState:PushAnimation("hop") inst.AnimState:PushAnimation("idle_bird", true) inst:DoTaskInTime(60*FRAMES, function() if item.components.edible.foodtype == "MEAT" then inst.components.lootdropper:SpawnLootPrefab("bird_egg") else if Prefabs[seed_name] then local num_seeds = math.random(2) for k = 1, num_seeds do inst.components.lootdropper:SpawnLootPrefab(seed_name) end if math.random() < .5 then inst.components.lootdropper:SpawnLootPrefab("seeds") end else inst.components.lootdropper:SpawnLootPrefab("seeds") end end if inst.components.occupiable and inst.components.occupiable.occupant and inst.components.occupiable.occupant:IsValid() and inst.components.occupiable.occupant.components.perishable then print("EAT!") inst.components.occupiable.occupant.components.perishable:SetPercent(1) end end) end end end local function DoIdle(inst) local r = math.random() if r < .5 then inst.AnimState:PlayAnimation("caw") if inst.chirpsound then inst.SoundEmitter:PlaySound(inst.chirpsound) end elseif r < .6 then inst.AnimState:PlayAnimation("flap") inst.SoundEmitter:PlaySound("dontstarve/birds/wingflap_cage") else inst.AnimState:PlayAnimation("hop") end inst.AnimState:PushAnimation("idle_bird") end local function StopIdling(inst) if inst.idletask then inst.idletask:Cancel() inst.idletask = nil end end local function StartIdling(inst) inst.idletask = inst:DoPeriodicTask(6, DoIdle) end local function ShouldSleep(inst) if inst.components.occupiable:IsOccupied() then return GetClock():IsNight() else return false end end local function ShouldWake(inst) return GetClock():IsDay() end local function onoccupied(inst, bird) if bird.components.perishable then bird.components.perishable:StopPerishing() end inst:AddComponent("sleeper") inst.components.sleeper:SetSleepTest(ShouldSleep) inst.components.sleeper:SetWakeTest(ShouldWake) inst.components.trader:Enable() for k,v in pairs(bird_symbols) do inst.AnimState:OverrideSymbol(v, bird.prefab .. "_build", v) end inst.chirpsound = bird.sounds and bird.sounds.chirp inst.AnimState:PlayAnimation("flap") inst.AnimState:PushAnimation("idle_bird", true) StartIdling(inst) end local function onemptied(inst, bird) inst:RemoveComponent("sleeper") StopIdling(inst) inst.components.trader:Disable() for k,v in pairs(bird_symbols) do inst.AnimState:ClearOverrideSymbol(v) end inst.AnimState:PlayAnimation("idle", true) end local function onhammered(inst, worker) --[[ inst.components.container:DropEverything() SpawnPrefab("collapse_small").Transform:SetPosition(inst.Transform:GetWorldPosition()) inst.SoundEmitter:PlaySound("dontstarve/common/destroy_wood") --]] if inst.components.occupiable:IsOccupied() then local item = inst.components.occupiable:Harvest() if item then item.Transform:SetPosition(inst.Transform:GetWorldPosition()) item.components.inventoryitem:OnDropped() end end inst.components.lootdropper:DropLoot() inst:Remove() end local function onhit(inst, worker) if inst.components.occupiable:IsOccupied() then inst.AnimState:PlayAnimation("hit_bird") inst.AnimState:PushAnimation("flap") inst.SoundEmitter:PlaySound("dontstarve/birds/wingflap_cage") inst.AnimState:PushAnimation("idle_bird", true) else inst.AnimState:PlayAnimation("hit_idle") inst.AnimState:PushAnimation("idle") end --inst.components.container:Close() end local function testfn(inst, guy) return guy:HasTag("bird") end local function onbuilt(inst) inst.AnimState:PlayAnimation("place") inst.AnimState:PushAnimation("idle") end local function GoToSleep(inst) if inst.components.occupiable:IsOccupied() then StopIdling(inst) inst.AnimState:PlayAnimation("sleep_pre") inst.AnimState:PushAnimation("sleep_loop", true) end end local function WakeUp(inst) if inst.components.occupiable:IsOccupied() then inst.AnimState:PlayAnimation("sleep_pst") inst.AnimState:PushAnimation("idle_bird", true) StartIdling(inst) end end local function fn(Sim) local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddSoundEmitter() MakeObstaclePhysics(inst, .5 ) local minimap = inst.entity:AddMiniMapEntity() minimap:SetIcon( "birdcage.png" ) inst.AnimState:SetBank("birdcage") inst.AnimState:SetBuild("bird_cage") inst.AnimState:PlayAnimation("idle") inst:AddTag("structure") inst:AddComponent("inspectable") inst:AddComponent("lootdropper") inst:AddComponent("occupiable") inst.components.occupiable.occupytestfn = testfn inst.components.occupiable.onoccupied = onoccupied inst.components.occupiable.onemptied = onemptied inst:AddComponent("workable") inst.components.workable:SetWorkAction(ACTIONS.HAMMER) inst.components.workable:SetWorkLeft(4) inst.components.workable:SetOnFinishCallback(onhammered) inst.components.workable:SetOnWorkCallback(onhit) inst:AddComponent("trader") inst.components.trader:SetAcceptTest(ShouldAcceptItem) inst.components.trader.onaccept = OnGetItemFromPlayer inst.components.trader.onrefuse = OnRefuseItem inst.components.trader:Disable() MakeSnowCovered(inst, .01) inst:ListenForEvent( "onbuilt", onbuilt) inst:ListenForEvent("gotosleep", function(inst) GoToSleep(inst) end) inst:ListenForEvent("onwakeup", function(inst) WakeUp(inst) end) return inst end return Prefab( "common/birdcage", fn, assets, prefabs), MakePlacer("common/birdcage_placer", "birdcage", "bird_cage", "idle")
gpl-2.0
czfshine/Don-t-Starve
examples/mod例子-人物/modmain.lua
4
1673
PrefabFiles = { "wod", } Assets = { Asset( "IMAGE", "images/saveslot_portraits/wod.tex" ), Asset( "ATLAS", "images/saveslot_portraits/wod.xml" ), Asset( "IMAGE", "images/selectscreen_portraits/wod.tex" ), Asset( "ATLAS", "images/selectscreen_portraits/wod.xml" ), Asset( "IMAGE", "images/selectscreen_portraits/wod_silho.tex" ), Asset( "ATLAS", "images/selectscreen_portraits/wod_silho.xml" ), Asset( "IMAGE", "bigportraits/wod.tex" ), Asset( "ATLAS", "bigportraits/wod.xml" ), } -- strings! Any "WOD" below would have to be replaced by the prefab name of your character. -- The character select screen lines -- note: these are lower-case character name GLOBAL.STRINGS.CHARACTER_TITLES.wod = "The Template" GLOBAL.STRINGS.CHARACTER_NAMES.wod = "Wod" -- Note! This line is especially important as some parts of the game require -- the character to have a valid name. GLOBAL.STRINGS.CHARACTER_DESCRIPTIONS.wod = "* An example of how to create a mod character." GLOBAL.STRINGS.CHARACTER_QUOTES.wod = "\"I am a blank slate.\"" -- You can also add any kind of custom dialogue that you would like. Don't forget to make -- categores that don't exist yet using = {} -- note: these are UPPER-CASE charcacter name GLOBAL.STRINGS.CHARACTERS.WOD = {} GLOBAL.STRINGS.CHARACTERS.WOD.DESCRIBE = {} GLOBAL.STRINGS.CHARACTERS.WOD.DESCRIBE.EVERGREEN = "A template description of a tree." -- Let the game know Wod is a male, for proper pronouns during the end-game sequence. -- Possible genders here are MALE, FEMALE, or ROBOT table.insert(GLOBAL.CHARACTER_GENDERS.MALE, "wod") AddModCharacter("wod")
gpl-2.0
Kubuxu/cjdns
contrib/lua/cjdns/config.lua
34
1851
-- Cjdns admin module for Lua -- Written by Philip Horger common = require 'cjdns/common' ConfigFile = {} ConfigFile.__index = ConfigFile common.ConfigFile = ConfigFile function ConfigFile.new(path, no_init) local values = { path = path, text = "", contents = {}, } setmetatable(values, ConfigFile) if (not no_init) then values:reload() end return values end function ConfigFile:reload() self:read() self:parse() end function ConfigFile:read(path) path = path or self.path local f = assert(io.open(self.path, 'r')) self.text = assert(f:read("*all")) f:close() self.text, _ = self.text:gsub("//[^\n]*\n", "") -- Single line comments self.text, _ = self.text:gsub("/%*.-%*/", "") -- Multi-line comments end function ConfigFile:parse() local obj, pos, err = dkjson.decode(self.text) assert(err == nil, err) -- If there is an error, die and print it self.contents = obj end function ConfigFile:save(path) -- Saving will obliterate comments, and table output type is inferred by -- table contents, since Lua does not distinguish between [] and {} path = path or self.path local savetext = assert(dkjson.encode(self.contents, { indent = true })) local f = assert(io.open(path, 'w')) f:write(savetext) f:close() end function ConfigFile:makeInterface() local ai = common.AdminInterface.new({ config = self }) self:applyToInterface(ai) return ai end function ConfigFile:applyToInterface(ai) local adminstuff = assert(self.contents.admin) local bind = assert(adminstuff.bind) local bindsplit = assert(bind:find(":")) ai.password = assert(adminstuff.password) ai.host = bind:sub(0, bindsplit - 1) ai.port = bind:sub(bindsplit + 1) ai.config = self end
gpl-3.0
andywingo/snabbswitch
src/apps/packet_filter/pcap_filter.lua
13
4219
module(...,package.seeall) local app = require("core.app") local link = require("core.link") local lib = require("core.lib") local packet = require("core.packet") local config = require("core.config") local conntrack = require("apps.packet_filter.conntrack") local pf = require("pf") -- pflua PcapFilter = {} -- PcapFilter is an app that drops all packets that don't match a -- specified filter expression. -- -- Optionally, connections can be statefully tracked, so that if one -- packet for a TCP/UDP session is accepted then future packets -- matching this session are also accepted. -- -- conf: -- filter = string expression specifying which packets to accept -- syntax: http://www.tcpdump.org/manpages/pcap-filter.7.html -- state_table = optional string name to use for stateful-tracking table function PcapFilter:new (conf) assert(conf.filter, "PcapFilter conf.filter parameter missing") local o = { -- XXX Investigate the latency impact of filter compilation. accept_fn = pf.compile_filter(conf.filter), state_table = conf.state_table or false } if conf.state_table then conntrack.define(conf.state_table) end return setmetatable(o, { __index = PcapFilter }) end function PcapFilter:push () local i = assert(self.input.input or self.input.rx, "input port not found") local o = assert(self.output.output or self.output.tx, "output port not found") while not link.empty(i) do local p = link.receive(i) local spec = self.state_table and conntrack.spec(p.data) if spec and spec:check(self.state_table) then link.transmit(o, p) elseif self.accept_fn(p.data, p.length) then if spec then spec:track(self.state_table) end link.transmit(o, p) else packet.free(p) end end end -- Testing local pcap = require("apps.pcap.pcap") local basic_apps = require("apps.basic.basic_apps") -- This is a simple blind regression test to detect unexpected changes -- in filtering behavior. -- -- The PcapFilter app is glue. Instead of having major unit tests of -- its own it depends on separate testing of pflua and conntrack. function selftest () print("selftest: pcap_filter") selftest_run(false, 3.726, 0.0009) selftest_run(true, 7.453, 0.001) print("selftest: ok") end -- Run a selftest in stateful or non-stateful mode and expect a -- specific rate of acceptance from the test trace file. function selftest_run (stateful, expected, tolerance) app.configure(config.new()) conntrack.clear() local pcap_filter = require("apps.packet_filter.pcap_filter") local v6_rules = [[ (icmp6 and src net 3ffe:501:0:1001::2/128 and dst net 3ffe:507:0:1:200:86ff:fe05:8000/116) or (ip6 and udp and src net 3ffe:500::/28 and dst net 3ffe:0501:4819::/64 and src portrange 2397-2399 and dst port 53) ]] local c = config.new() local state_table = stateful and "selftest" config.app(c, "source", pcap.PcapReader, "apps/packet_filter/samples/v6.pcap") config.app(c, "repeater", basic_apps.Repeater ) config.app(c,"pcap_filter", pcap_filter.PcapFilter, {filter=v6_rules, state_table = state_table}) config.app(c, "sink", basic_apps.Sink ) config.link(c, "source.output -> repeater.input") config.link(c, "repeater.output -> pcap_filter.input") config.link(c, "pcap_filter.output -> sink.input") app.configure(c) print(("Run for 1 second (stateful = %s)..."):format(stateful)) local deadline = lib.timer(1e9) repeat app.breathe() until deadline() app.report({showlinks=true}) local sent = link.stats(app.app_table.pcap_filter.input.input).rxpackets local accepted = link.stats(app.app_table.pcap_filter.output.output).txpackets local acceptrate = accepted * 100 / sent if acceptrate >= expected and acceptrate <= expected+tolerance then print(("ok: accepted %.4f%% of inputs (within tolerance)"):format(acceptrate)) else print(("error: accepted %.4f%% (expected %.3f%% +/- %.5f)"):format( acceptrate, expected, tolerance)) error("selftest failed") end end
apache-2.0
cloudwu/skynet
examples/login/logind.lua
29
1663
local login = require "snax.loginserver" local crypt = require "skynet.crypt" local skynet = require "skynet" local server = { host = "127.0.0.1", port = 8001, multilogin = false, -- disallow multilogin name = "login_master", } local server_list = {} local user_online = {} local user_login = {} function server.auth_handler(token) -- the token is base64(user)@base64(server):base64(password) local user, server, password = token:match("([^@]+)@([^:]+):(.+)") user = crypt.base64decode(user) server = crypt.base64decode(server) password = crypt.base64decode(password) assert(password == "password", "Invalid password") return server, user end function server.login_handler(server, uid, secret) print(string.format("%s@%s is login, secret is %s", uid, server, crypt.hexencode(secret))) local gameserver = assert(server_list[server], "Unknown server") -- only one can login, because disallow multilogin local last = user_online[uid] if last then skynet.call(last.address, "lua", "kick", uid, last.subid) end if user_online[uid] then error(string.format("user %s is already online", uid)) end local subid = tostring(skynet.call(gameserver, "lua", "login", uid, secret)) user_online[uid] = { address = gameserver, subid = subid , server = server} return subid end local CMD = {} function CMD.register_gate(server, address) server_list[server] = address end function CMD.logout(uid, subid) local u = user_online[uid] if u then print(string.format("%s@%s is logout", uid, u.server)) user_online[uid] = nil end end function server.command_handler(command, ...) local f = assert(CMD[command]) return f(...) end login(server)
mit
ioiasff/creawq
plugins/stats.lua
1
4005
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'creedbot' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /killerbot ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "killerbot" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (killerbot)",-- Put everything you like :) "^[!/]([Kk]illerbot)"-- Put everything you like :) }, run = run } end
gpl-2.0
starkos/premake-core
modules/vstudio/tests/vc200x/test_debug_settings.lua
12
2491
-- -- tests/actions/vstudio/vc200x/test_debugdir.lua -- Validate handling of the working directory for debugging. -- Copyright (c) 2011-2013 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vstudio_vs200x_debugdir") local vc200x = p.vstudio.vc200x local project = p.project -- -- Setup -- local wks, prj function suite.setup() p.action.set("vs2005") p.escaper(p.vstudio.vs2005.esc) wks, prj = test.createWorkspace() end local function prepare() local cfg = test.getconfig(prj, "Debug") vc200x.debugSettings(cfg) end -- -- If no debug settings are specified, an empty block should be generated. -- function suite.emptyBlock_onNoSettings() prepare() test.isemptycapture() end -- -- If a debug command is provided, it should be specified relative to -- the project. -- function suite.debugCommand_onRelativePath() location "build" debugcommand "bin/emulator.exe" prepare() test.capture [[ Command="..\bin\emulator.exe" ]] end -- -- If a working directory is provided, it should be specified relative to -- the project. -- function suite.workingDir_onRelativePath() location "build" debugdir "bin/debug" prepare() test.capture [[ WorkingDirectory="..\bin\debug" ]] end -- -- Make sure debug arguments are being written. -- function suite.commandArguments_onDebugArgs() debugargs { "arg1", "arg2" } prepare() test.capture [[ CommandArguments="arg1 arg2" ]] end -- -- Make sure environment variables are being written. -- function suite.environmentVarsSet_onDebugEnvs() debugenvs { "key=value" } prepare() test.capture [[ Environment="key=value" ]] end -- -- Make sure quotes around environment variables are properly escaped. -- function suite.environmentVarsEscaped_onQuotes() debugenvs { 'key="value"' } prepare() test.capture [[ Environment="key=&quot;value&quot;" ]] end -- -- If multiple environment variables are specified, make sure they get -- separated properly. -- function suite.environmentVars_onMultipleValues() debugenvs { "key=value", "foo=bar" } prepare() test.capture [[ Environment="key=value&#x0A;foo=bar" ]] end -- -- Make sure that environment merging is turned off if the build -- flag is set. -- function suite.environmentVarsSet_onDebugEnvsAndDebugEnvsDontMerge() debugenvs { "key=value" } flags { "DebugEnvsDontMerge" } prepare() test.capture [[ Environment="key=value" EnvironmentMerge="false" ]] end
bsd-3-clause
kasperlewau/casketUI
BattlegroundTargets/BattlegroundTargets-localization-zhCN.lua
1
1748
-- -------------------------------------------------------------------------- -- -- BattlegroundTargets zhCN Localization (Thanks ananhaid) -- -- Please make sure to save this file as UTF-8. ¶ -- -- -------------------------------------------------------------------------- -- if GetLocale() ~= "zhCN" then return end local L, _, prg = {}, ... if prg.L then L = prg.L else prg.L = L end L["Open Configuration"] = "打开配置面板" L["Close Configuration"] = "关闭配置" L["Configuration"] = "配置" L["Independent Positioning"] = "独立定位" L["Layout"] = "布局" L["Summary"] = "摘要" L["Copy this settings to %s"] = "复制此设置到 %s" L["Class Icon"] = "职业图标" L["Realm"] = "服务器" L["Leader"] = "领袖" L["Flag"] = true L["Main Assist Target"] = "主助理目标" L["Target Count"] = "目标计数" L["Health Bar"] = "生命条" L["Percent"] = "百分比" L["Range"] = "范围" L["This option uses the CombatLog to check range."] = "此选项使用战斗记录检查范围。" L["This option uses a pre-defined spell to check range:"] = "此选项使用预定法术范围检查:" L["Mix"] = "混合" L["if you are attacked only"] = "仅自身被攻击" L["(class dependent)"] = "(以职业)" L["Disable this option if you have CPU/FPS problems in combat."] = "当你 CPU/帧数在战斗中出现问题时禁用此选项。" L["Sort By"] = "排序" L["Text"] = "文本" L["Number"] = "编号" L["Scale"] = "缩放" L["Width"] = "宽度" L["Height"] = "高度" L["Options"] = "选项" L["General Settings"] = "总体设定" L["Show Minimap-Button"] = "显示小地图图标" L["click & move"] = "点击移动"
mit
zhujunsan/nodemcu-firmware
lua_modules/bh1750/bh1750.lua
89
1372
-- *************************************************************************** -- BH1750 module for ESP8266 with nodeMCU -- BH1750 compatible tested 2015-1-22 -- -- Written by xiaohu -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** local moduleName = ... local M = {} _G[moduleName] = M --I2C slave address of GY-30 local GY_30_address = 0x23 -- i2c interface ID local id = 0 --LUX local l --CMD local CMD = 0x10 local init = false --Make it more faster local i2c = i2c function M.init(sda, scl) i2c.setup(id, sda, scl, i2c.SLOW) --print("i2c ok..") init = true end local function read_data(ADDR, commands, length) i2c.start(id) i2c.address(id, ADDR, i2c.TRANSMITTER) i2c.write(id, commands) i2c.stop(id) i2c.start(id) i2c.address(id, ADDR,i2c.RECEIVER) tmr.delay(200000) c = i2c.read(id, length) i2c.stop(id) return c end local function read_lux() dataT = read_data(GY_30_address, CMD, 2) --Make it more faster UT = dataT:byte(1) * 256 + dataT:byte(2) l = (UT*1000/12) return(l) end function M.read() if (not init) then print("init() must be called before read.") else read_lux() end end function M.getlux() return l end return M
mit
alinfrat/robot
plugins/owners.lua
68
12477
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1]..':'..user_id redis:del(hash) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
otalk/sdp-jingle-table
src/jingle.lua
1
3939
package.path = '../../lua-otalk/?.lua;' .. package.path local M = {} local helpers = require "helpers" local converter = require "converter" local NS = "urn:xmpp:jingle:1" local GROUPNS = "urn:xmpp:jingle:apps:grouping:0" local INFONS = "urn:xmpp:jingle:apps:rtp:info:1" function jingleToTable(element) local jingle = {} jingle.action = helpers.getAttribute(element, "action") jingle.initiator = helpers.getAttribute(element, "initiator") jingle.responder = helpers.getAttribute(element, "responder") jingle.sid = helpers.getAttribute(element, "sid") jingle.contents = helpers.getChildren(element, "content", NS) jingle.groups = helpers.getChildren(element, "group", GROUPNS) jingle.muteGroup = helpers.getChildren(element, "mute", INFONS) jingle.unmuteGroup = helpers.getChildren(element, "unmute", INFONS) return jingle end function tableToJingle(jingle) local element = stanza.stanza("jingle") local attrs = { xmlns = NS, action = jingle.action, initiator = jingle.initiator, responder = jingle.responder, sid = jingle.sid } helpers.setAttributes(element, attrs) helpers.addChildren(element, jingle, "contents", "content", NS) helpers.addChildren(element, jingle, "groups", "group", GROUPNS) helpers.addChildren(element, jingle, "muteGroup", "mute", INFONS) helpers.addChildren(element, jingle, "unmuteGroup", "unmute", INFONS) return element end function contentToTable(element) local content = {} content.creator = helpers.getAttribute(element, "creator") content.disposition = helpers.getAttribute(element, "disposition", "session") content.name = helpers.getAttribute(element, "name") content.senders = helpers.getAttribute(element, "senders", "both") for child in helpers.childtags(element) do if child.name == "description" then local toTable if child.attr.xmlns and child.attr.xmlns == "http://talky.io/ns/datachannel" then toTable = converter.toTable("description", "http://talky.io/ns/datachannel") else toTable = converter.toTable("description", "urn:xmpp:jingle:apps:rtp:1") end if toTable then local description = toTable(child) if description then content.description = description end end elseif child.name == "transport" then local toTable = converter.toTable("transport", "urn:xmpp:jingle:transports:ice-udp:1") if toTable then local transport = toTable(child) if transport then content.transport = transport end end end end return content end function tableToContent(content) local element = stanza.stanza("content") local attrs = { xmlns = NS, creator = content.creator, disposition = content.disposition, name = content.name, senders = content.senders } helpers.setAttributes(element, attrs) local description = content.description if description then local toStanza if description.descType == "datachannel" then toStanza = converter.toStanza("description", "http://talky.io/ns/datachannel") else toStanza = converter.toStanza("description", "urn:xmpp:jingle:apps:rtp:1") end element:add_child(toStanza(description)) end if content.transport then toStanza = converter.toStanza("transport", "urn:xmpp:jingle:transports:ice-udp:1") element:add_child(toStanza(content.transport)) end return element end function M.registerJingle(converter) converter.register("jingle", NS, { toTable = jingleToTable, toStanza = tableToJingle }) end function M.registerContent(converter) converter.register("content", NS, { toTable = contentToTable, toStanza = tableToContent }) end return M
mit
AllAboutEE/nodemcu-firmware
lua_examples/send_text_message.lua
75
3151
--[[ 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. ]]-- -- Your access point's SSID and password local SSID = "xxxxxx" local SSID_PASSWORD = "xxxxxx" -- configure ESP as a station wifi.setmode(wifi.STATION) wifi.sta.config(SSID,SSID_PASSWORD) wifi.sta.autoconnect(1) local TWILIO_ACCOUNT_SID = "xxxxxx" local TWILIO_TOKEN = "xxxxxx" local HOST = "iot-https-relay.appspot.com" -- visit http://iot-https-relay.appspot.com/ to learn more about this service -- Please be sure to understand the security issues of using this relay app and use at your own risk. local URI = "/twilio/Messages.json" function build_post_request(host, uri, data_table) local data = "" for param,value in pairs(data_table) do data = data .. param.."="..value.."&" end request = "POST "..uri.." HTTP/1.1\r\n".. "Host: "..host.."\r\n".. "Connection: close\r\n".. "Content-Type: application/x-www-form-urlencoded\r\n".. "Content-Length: "..string.len(data).."\r\n".. "\r\n".. data print(request) return request end local function display(sck,response) print(response) end -- When using send_sms: the "from" number HAS to be your twilio number. -- If you have a free twilio account the "to" number HAS to be your twilio verified number. local function send_sms(from,to,body) local data = { sid = TWILIO_ACCOUNT_SID, token = TWILIO_TOKEN, Body = string.gsub(body," ","+"), From = from, To = to } socket = net.createConnection(net.TCP,0) socket:on("receive",display) socket:connect(80,HOST) socket:on("connection",function(sck) local post_request = build_post_request(HOST,URI,data) sck:send(post_request) end) end function check_wifi() local ip = wifi.sta.getip() if(ip==nil) then print("Connecting...") else tmr.stop(0) print("Connected to AP!") print(ip) -- send a text message with the text "Hello from your esp8266" send_sms("15558889944","15559998845","Hello from your ESP8266") end end tmr.alarm(0,7000,1,check_wifi)
mit
maximus0/thrift
lib/lua/Thrift.lua
10
6622
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- ---- namespace thrift --thrift = {} --setmetatable(thrift, {__index = _G}) --> perf hit for accessing global methods --setfenv(1, thrift) package.cpath = package.cpath .. ';bin/?.so' -- TODO FIX function ttype(obj) if type(obj) == 'table' and obj.__type and type(obj.__type) == 'string' then return obj.__type end return type(obj) end function terror(e) if e and e.__tostring then error(e:__tostring()) return end error(e) end version = 1.0 TType = { STOP = 0, VOID = 1, BOOL = 2, BYTE = 3, I08 = 3, DOUBLE = 4, I16 = 6, I32 = 8, I64 = 10, STRING = 11, UTF7 = 11, STRUCT = 12, MAP = 13, SET = 14, LIST = 15, UTF8 = 16, UTF16 = 17 } TMessageType = { CALL = 1, REPLY = 2, EXCEPTION = 3, ONEWAY = 4 } -- Recursive __index function to achive inheritance function __tobj_index(self, key) local v = rawget(self, key) if v ~= nil then return v end local p = rawget(self, '__parent') if p then return __tobj_index(p, key) end return nil end -- Basic Thrift-Lua Object __TObject = { __type = '__TObject', __mt = { __index = __tobj_index } } function __TObject:new(init_obj) local obj = {} if ttype(obj) == 'table' then obj = init_obj end -- Use the __parent key and the __index function to achieve inheritance obj.__parent = self setmetatable(obj, __TObject.__mt) return obj end -- Return a string representation of any lua variable function thrift_print_r(t) local ret = '' local ltype = type(t) if (ltype == 'table') then ret = ret .. '{ ' for key,value in pairs(t) do ret = ret .. tostring(key) .. '=' .. thrift_print_r(value) .. ' ' end ret = ret .. '}' elseif ltype == 'string' then ret = ret .. "'" .. tostring(t) .. "'" else ret = ret .. tostring(t) end return ret end -- Basic Exception TException = __TObject:new{ message, errorCode, __type = 'TException' } function TException:__tostring() if self.message then return string.format('%s: %s', self.__type, self.message) else local message if self.errorCode and self.__errorCodeToString then message = string.format('%d: %s', self.errorCode, self:__errorCodeToString()) else message = thrift_print_r(self) end return string.format('%s:%s', self.__type, message) end end TApplicationException = TException:new{ UNKNOWN = 0, UNKNOWN_METHOD = 1, INVALID_MESSAGE_TYPE = 2, WRONG_METHOD_NAME = 3, BAD_SEQUENCE_ID = 4, MISSING_RESULT = 5, INTERNAL_ERROR = 6, PROTOCOL_ERROR = 7, INVALID_TRANSFORM = 8, INVALID_PROTOCOL = 9, UNSUPPORTED_CLIENT_TYPE = 10, errorCode = 0, __type = 'TApplicationException' } function TApplicationException:__errorCodeToString() if self.errorCode == self.UNKNOWN_METHOD then return 'Unknown method' elseif self.errorCode == self.INVALID_MESSAGE_TYPE then return 'Invalid message type' elseif self.errorCode == self.WRONG_METHOD_NAME then return 'Wrong method name' elseif self.errorCode == self.BAD_SEQUENCE_ID then return 'Bad sequence ID' elseif self.errorCode == self.MISSING_RESULT then return 'Missing result' elseif self.errorCode == self.INTERNAL_ERROR then return 'Internal error' elseif self.errorCode == self.PROTOCOL_ERROR then return 'Protocol error' elseif self.errorCode == self.INVALID_TRANSFORM then return 'Invalid transform' elseif self.errorCode == self.INVALID_PROTOCOL then return 'Invalid protocol' elseif self.errorCode == self.UNSUPPORTED_CLIENT_TYPE then return 'Unsupported client type' else return 'Default (unknown)' end end function TException:read(iprot) iprot:readStructBegin() while true do local fname, ftype, fid = iprot:readFieldBegin() if ftype == TType.STOP then break elseif fid == 1 then if ftype == TType.STRING then self.message = iprot:readString() else iprot:skip(ftype) end elseif fid == 2 then if ftype == TType.I32 then self.errorCode = iprot:readI32() else iprot:skip(ftype) end else iprot:skip(ftype) end iprot:readFieldEnd() end iprot:readStructEnd() end function TException:write(oprot) oprot:writeStructBegin('TApplicationException') if self.message then oprot:writeFieldBegin('message', TType.STRING, 1) oprot:writeString(self.message) oprot:writeFieldEnd() end if self.errorCode then oprot:writeFieldBegin('type', TType.I32, 2) oprot:writeI32(self.errorCode) oprot:writeFieldEnd() end oprot:writeFieldStop() oprot:writeStructEnd() end -- Basic Client (used in generated lua code) __TClient = __TObject:new{ __type = '__TClient', _seqid = 0 } function __TClient:new(obj) if ttype(obj) ~= 'table' then error('TClient must be initialized with a table') end -- Set iprot & oprot if obj.protocol then obj.iprot = obj.protocol obj.oprot = obj.protocol obj.protocol = nil elseif not obj.iprot then error('You must provide ' .. ttype(self) .. ' with an iprot') end if not obj.oprot then obj.oprot = obj.iprot end return __TObject.new(self, obj) end function __TClient:close() self.iprot.trans:close() self.oprot.trans:close() end -- Basic Processor (used in generated lua code) __TProcessor = __TObject:new{ __type = '__TProcessor' } function __TProcessor:new(obj) if ttype(obj) ~= 'table' then error('TProcessor must be initialized with a table') end -- Ensure a handler is provided if not obj.handler then error('You must provide ' .. ttype(self) .. ' with a handler') end return __TObject.new(self, obj) end
apache-2.0
starkos/premake-core
modules/vstudio/tests/vc2010/test_extension_settings.lua
16
1709
-- -- tests/actions/vstudio/vc2010/test_extension_settings.lua -- Check the import extension settings block of a VS 2010 project. -- Copyright (c) 2014 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vs2010_extension_settings") local vc2010 = p.vstudio.vc2010 local project = p.project -- -- Setup -- local wks function suite.setup() p.action.set("vs2010") rule "MyRules" rule "MyOtherRules" wks = test.createWorkspace() end local function prepare() local prj = test.getproject(wks) vc2010.importExtensionSettings(prj) end -- -- Writes an empty element when no custom rules are specified. -- function suite.structureIsCorrect_onDefaultValues() prepare() test.capture [[ <ImportGroup Label="ExtensionSettings"> </ImportGroup> ]] end -- -- Writes entries for each project scoped custom rules path. -- function suite.addsImport_onEachRulesFile() rules { "MyRules", "MyOtherRules" } prepare() test.capture [[ <ImportGroup Label="ExtensionSettings"> <Import Project="MyRules.props" /> <Import Project="MyOtherRules.props" /> </ImportGroup> ]] end -- -- Rule files use a project relative path. -- function suite.usesProjectRelativePaths() rules "MyRules" location "build" prepare() test.capture [[ <ImportGroup Label="ExtensionSettings"> <Import Project="..\MyRules.props" /> </ImportGroup> ]] end -- -- the asm 'file category' should add the right settings. -- function suite.hasAssemblyFiles() files { "test.asm" } location "build" prepare() test.capture [[ <ImportGroup Label="ExtensionSettings"> <Import Project="$(VCTargetsPath)\BuildCustomizations\masm.props" /> </ImportGroup> ]] end
bsd-3-clause
victorperin/tibia-server
data/creaturescripts/scripts/others/login.lua
1
1533
function onLogin(cid) local player = Player(cid) local loginStr = "Welcome to " .. configManager.getString(configKeys.SERVER_NAME) .. "!" if player:getLastLoginSaved() <= 0 then loginStr = loginStr .. " Please choose your outfit." player:sendTutorial(1) else if loginStr ~= "" then player:sendTextMessage(MESSAGE_STATUS_DEFAULT, loginStr) end loginStr = string.format("Your last visit was on %s.", os.date("%a %b %d %X %Y", player:getLastLoginSaved())) end player:sendTextMessage(MESSAGE_STATUS_DEFAULT, loginStr) player:registerEvent("PlayerDeath") player:registerEvent("bigfootBurdenQuestVesperoth") player:registerEvent("bigfootBurdenQuestWarzone") player:registerEvent("bigfootBurdenQuestWeeper") player:registerEvent("bigfootBurdenQuestWiggler") player:registerEvent("bossSummoning") player:registerEvent("theNewFrontierQuestShardOfCorruption") player:registerEvent("theNewFrontierQuestTirecz") player:registerEvent("inServiceOfYalaharQuestsDiseased") player:registerEvent("inServiceOfYalaharQuestsAzerus") player:registerEvent("inServiceOfYalaharQuestsQuara") player:registerEvent("inquisitionQuestBosses") player:registerEvent("inquisitionQuestUngreez") player:registerEvent("killingInTheNameOfQuestKills") player:registerEvent("masterVoiceQuest") player:registerEvent("elementalspheresquestOverlords") player:registerEvent("SvargrondArenaKill") player:registerEvent("AdvanceSave") player:registerEvent("StorageConversion") player:registerEvent("rookgaardCockroach") return true end
apache-2.0
czfshine/Don-t-Starve
data/scripts/prefabs/fire.lua
1
2052
local assets = { Asset("ANIM", "anim/fire.zip"), Asset("SOUND", "sound/common.fsb"), } local heats = { 30, 70, 120, 180, 220 } local function GetHeatFn(inst) return heats[inst.components.firefx.level] or 20 end local firelevels = { {anim="level1", sound="dontstarve/common/campfire", radius=2, intensity=.75, falloff=.33, colour = {197/255,197/255,170/255}, soundintensity=.1}, {anim="level2", sound="dontstarve/common/campfire", radius=3, intensity=.8, falloff=.33, colour = {255/255,255/255,192/255}, soundintensity=.3}, {anim="level3", sound="dontstarve/common/campfire", radius=4, intensity=.8, falloff=.33, colour = {255/255,255/255,192/255}, soundintensity=.6}, {anim="level4", sound="dontstarve/common/campfire", radius=5, intensity=.9, falloff=.25, colour = {255/255,190/255,121/255}, soundintensity=1}, {anim="level4", sound="dontstarve/common/forestfire", radius=6, intensity=.9, falloff=.2, colour = {255/255,190/255,121/255}, soundintensity=1}, } local function fn(Sim) local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() local sound = inst.entity:AddSoundEmitter() local light = inst.entity:AddLight() anim:SetBloomEffectHandle( "shaders/anim.ksh" ) anim:SetBank("fire") anim:SetBuild("fire") inst.AnimState:SetRayTestOnBB(true) inst:AddTag("fx") inst:AddComponent("firefx") inst.components.firefx.levels = firelevels inst.components.firefx.extinguishsoundtest = function() local x,y,z = inst.Transform:GetWorldPosition() local ents = TheSim:FindEntities(x,y,z, 5) local fireyness = 0 for k,v in pairs(ents) do if v ~= inst and v.components.firefx and v.components.firefx.level then fireyness = fireyness + v.components.firefx.level end end return fireyness < 5 end inst:AddComponent("heater") inst.components.heater.heatfn = GetHeatFn anim:SetFinalOffset(-1) return inst end return Prefab( "common/fx/fire", fn, assets)
gpl-2.0
czfshine/Don-t-Starve
data/scripts/map/static_layouts/skeleton_hunter_swamp.lua
1
10337
return { version = "1.1", luaversion = "5.1", orientation = "orthogonal", width = 24, height = 24, tilewidth = 16, tileheight = 16, properties = {}, tilesets = { { name = "tiles", firstgid = 1, tilewidth = 64, tileheight = 64, spacing = 0, margin = 0, image = "../../../../tools/tiled/dont_starve/tiles.png", imagewidth = 512, imageheight = 128, properties = {}, tiles = {} } }, layers = { { type = "tilelayer", name = "BG_TILES", x = 0, y = 0, width = 24, height = 24, visible = true, opacity = 1, properties = {}, encoding = "lua", data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0 } }, { type = "objectgroup", name = "FG_OBJECTS", visible = true, opacity = 1, properties = {}, objects = { { name = "", type = "skeleton", shape = "rectangle", x = 193, y = 206, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "beefalohat", shape = "rectangle", x = 235, y = 236, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "beefalowool", shape = "rectangle", x = 179, y = 248, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "beefalowool", shape = "rectangle", x = 144, y = 150, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "beefalowool", shape = "rectangle", x = 227, y = 185, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "houndbone", shape = "rectangle", x = 229, y = 150, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "houndbone", shape = "rectangle", x = 202, y = 142, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "houndbone", shape = "rectangle", x = 133, y = 228, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "houndstooth", shape = "rectangle", x = 103, y = 194, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "houndstooth", shape = "rectangle", x = 113, y = 153, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "houndstooth", shape = "rectangle", x = 278, y = 210, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "houndstooth", shape = "rectangle", x = 271, y = 167, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "spear", shape = "rectangle", x = 181, y = 172, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 48, y = 288, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 80, y = 320, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 128, y = 336, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 181, y = 354, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 233, y = 355, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 272, y = 336, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 304, y = 304, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 336, y = 272, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 352, y = 224, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 352, y = 176, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 336, y = 128, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 304, y = 80, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 256, y = 48, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 190, y = 37, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 120, y = 47, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 72, y = 81, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 32, y = 128, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 16, y = 176, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "tentacle", shape = "rectangle", x = 28, y = 238, width = 0, height = 0, visible = true, properties = {} } } } } }
gpl-2.0
Teino1978-Corp/Teino1978-Corp-texlive.js
texlive/texmf-dist/tex/latex/latexconfig/lualatexquotejobname.lua
7
1031
-- $Id: lualatexquotejobname.tex 22957 2011-06-13 20:49:26Z mpg $ -- Manuel Pegourie-Gonnard, originally written 2010. WTFPL v2. -- -- Goal: see lualatexquotejobname.tex -- -- Cache the results of previous calls, not so much for the speed gain which -- probably doesn't matter, but to avoid repeated error messages. local jobname_cache = {} callback.register('process_jobname', function(jobname) -- use a cached version if available local cached = jobname_cache[jobname] if cached ~= nil then return cached end -- remove the quotes in jobname local clean, n_quotes = jobname:gsub([["]], [[]]) -- complain if they wasn't an even number of quotes (aka unbalanced) if n_quotes % 2 ~= 0 then texio.write_nl('! Unbalanced quotes in jobname: ' .. jobname ) end -- add quotes around the cleaned up jobname if necessary if jobname:find(' ') then clean = '"' .. clean .. '"' end -- remember the result before returning jobname_cache[jobname] = clean return clean end)
gpl-2.0
CrazyEddieTK/Zero-K
LuaRules/Gadgets/unit_jugglenaut_juggle.lua
4
9112
function gadget:GetInfo() return { name = "Old Jugglenaut Juggle", desc = "Implementes special weapon Juggling for Old Jugglenaut", author = "Google Frog", date = "1 April 2011", license = "GNU GPL, v2 or later", layer = 0, enabled = false -- loaded by default? } end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- if (gadgetHandler:IsSyncedCode()) then -- synced ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local getMovetype = Spring.Utilities.getMovetype local throwWeaponID = {} local throwWeaponName = {} local throwShooterID = { -- [UnitDefNames["gorg"].id] = true } for i=1,#WeaponDefs do local wd = WeaponDefs[i] if wd.customParams and wd.customParams.massliftthrow then Script.SetWatchWeapon(wd.id,true) throwWeaponID[wd.id] = true throwWeaponName[wd.name] = wd.id end end local moveTypeByID = {} for i=1,#UnitDefs do local ud = UnitDefs[i] moveTypeByID[i] = getMovetype(ud) end ------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------- local RISE_TIME = 25 local FLING_TIME = 35 local UPDATE_FREQUENCY = 2 local RISE_HEIGHT = 180 local COLLLECT_RADIUS = 260 ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local gorgs = {} local flying = {} local flyingByID = {data = {}, count = 0} ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local function distance(x1,y1,z1,x2,y2,z2) return math.sqrt((x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2) end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local function removeFlying(unitID) flying[flyingByID.data[flyingByID.count] ].index = flying[unitID].index flyingByID.data[flying[unitID].index] = flyingByID.data[flyingByID.count] flyingByID.data[flyingByID.count] = nil flying[unitID] = nil flyingByID.count = flyingByID.count - 1 SendToUnsynced("removeFlying", unitID) end local function addFlying(unitID, frame, dx, dy, dz, height, parentDis) if flying[unitID] then removeFlying(unitID) end local unitDefID = Spring.GetUnitDefID(unitID) local ux, uy, uz = Spring.GetUnitPosition(unitID) if unitDefID and ux and moveTypeByID[unitDefID] and moveTypeByID[unitDefID] == 2 then local frame = frame or Spring.GetGameFrame() local dis = distance(ux,uy,uz,dx,dy,dz) local riseFrame = frame + RISE_TIME + dis*0.2 local flingFrame = frame + FLING_TIME + dis*0.2 + (dis - parentDis > -50 and (dis - parentDis + 50)*0.02 or 0) local flingDuration = flingFrame - riseFrame flyingByID.count = flyingByID.count + 1 flyingByID.data[flyingByID.count] = unitID flying[unitID] = { index = flyingByID.count, riseFrame = riseFrame, flingFrame = flingFrame, flingDuration = flingDuration, riseTimer = 3, dx = dx, dy = dy, dz = dz, fx = ux, fy = height, fz = uz, } SendToUnsynced("addFlying", unitID, unitDefID) end end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function gadget:Explosion(weaponID, px, py, pz, ownerID) if throwWeaponID[weaponID] and ownerID then local frame = Spring.GetGameFrame() local sx,sy,sz = Spring.GetUnitPosition(ownerID) py = Spring.GetGroundHeight(px,pz) + 20 Spring.SpawnCEG("riotballgrav", sx, sy, sz, 0, 1, 0, COLLLECT_RADIUS) local units = Spring.GetUnitsInSphere(sx, sy, sz, COLLLECT_RADIUS) local parentDis = distance(sx, sy, sz, px,py,pz) for i = 1, #units do local unitID = units[i] if unitID ~= ownerID then local ux, uy, uz = Spring.GetUnitPosition(unitID) local tx, ty, tz = px + (ux-sx)*0.4, py + (uy-sy)*0.4, pz + (uz-sz)*0.4 local mag = distance(sx, sy, sz, tx, ty, tz) tx, ty, tz = (tx-sx)*parentDis/mag + sx, (ty-sy)*parentDis/mag + sy, (tz-sz)*parentDis/mag + sz addFlying(unitID, frame, tx, ty, tz, sy + RISE_HEIGHT, parentDis) end end end return false end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function gadget:GameFrame(f) if f%UPDATE_FREQUENCY == 0 then local i = 1 while i <= flyingByID.count do local unitID = flyingByID.data[i] if Spring.ValidUnitID(unitID) then local data = flying[unitID] local vx, vy, vz = Spring.GetUnitVelocity(unitID) local ux, uy, uz = Spring.GetUnitPosition(unitID) if f < data.riseFrame then Spring.AddUnitImpulse(unitID, -vx*0.02, (data.fy - uy)*0.01*(2-vy), -vz*0.02) if data.riseTimer then if data.riseTimer < 0 then Spring.SetUnitRotation(unitID,math.random()*2-1,math.random()*0.2-0.1,math.random()*2-1) data.riseTimer = false else data.riseTimer = data.riseTimer - 1 end end i = i + 1 elseif f < data.flingFrame then local dis = distance(data.dx,data.dy,data.dz,ux,uy,uz) local mult = ((data.flingFrame - f)*2/data.flingDuration)^1.8 * 2.5/dis Spring.AddUnitImpulse(unitID, (data.dx - ux)*mult, (data.dy - uy)*mult, (data.dz - uz)*mult) i = i + 1 else removeFlying(unitID) end else removeFlying(unitID) end end end end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function gadget:UnitCreated(unitID, unitDefID) if throwShooterID[unitDefID] then gorgs[unitID] = true end end function gadget:UnitDestroyed(unitID, unitDefID) if gorgs[unitID] then gorgs[unitID] = nil end end function gadget:Initialize() for _, unitID in ipairs(Spring.GetAllUnits()) do local unitDefID = Spring.GetUnitDefID(unitID) local teamID = Spring.GetUnitTeam(unitID) gadget:UnitCreated(unitID, unitDefID, teamID) end end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- else --unsynced ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local Lups local SYNCED = SYNCED local particleIDs = {} local flyFX = { --{class='UnitPieceLight', options={ delay=24, life=math.huge } }, {class='StaticParticles', options={ life = 30, colormap = { {0.2, 0.1, 1, 0.01} }, texture = 'bitmaps/GPL/groundflash.tga', sizeMod = 4, repeatEffect = true, } }, --{class='SimpleParticles', options={ --FIXME -- life = 50, -- speed = 0.65, -- colormap = { {0.2, 0.1, 1, 1} }, -- texture = 'bitmaps/PD/chargeparticles.tga', -- partpos = "0,0,0", -- count = 15, -- rotSpeed = 1, -- rotSpeedSpread = -2, -- rotSpread = 360, -- sizeGrowth = -0.05, -- emitVector = {0,1,0}, -- emitRotSpread = 60, -- delaySpread = 180, -- sizeMod = 10, -- } --}, {class='ShieldSphere', options={ life = math.huge, sizeMod = 1.5, colormap1 = { {0.2, 0.1, 1, 0.4} }, colormap2 = { {0.2, 0.1, 1, 0.08} } } } } local function addFlying(_, unitID, unitDefID) particleIDs[unitID] = {} local teamID = Spring.GetUnitTeam(unitID) local allyTeamID = Spring.GetUnitAllyTeam(unitID) local radius = Spring.GetUnitRadius(unitID) local height = Spring.GetUnitHeight(unitID) for i,fx in pairs(flyFX) do fx.options.unit = unitID fx.options.unitDefID = unitDefID fx.options.team = teamID fx.options.allyTeam = allyTeamID fx.options.size = radius * (fx.options.sizeMod or 1) fx.options.pos = {0, height/2, 0} particleIDs[unitID][#particleIDs[unitID] + 1] = Lups.AddParticles(fx.class,fx.options) end end local function removeFlying(_, unitID) for i=1,#particleIDs[unitID] do Lups.RemoveParticles(particleIDs[unitID][i]) end end function gadget:Initialize() gadgetHandler:AddSyncAction("addFlying", addFlying) gadgetHandler:AddSyncAction("removeFlying", removeFlying) end function gadget:Update() if (not Lups) then Lups = GG['Lups'] end end function gadget:Shutdown() gadgetHandler.RemoveSyncAction("addFlying") gadgetHandler.RemoveSyncAction("removeFlying") end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- end
gpl-2.0
UristMcEngineer/Michels-Medieval-Mod
mmm/mods/creative/init.lua
2
5849
-- minetest/creative/init.lua creative_inventory = {} creative_inventory.creative_inventory_size = 0 -- Create detached creative inventory after loading all mods minetest.after(0, function() local inv = minetest.create_detached_inventory("creative", { allow_move = function(inv, from_list, from_index, to_list, to_index, count, player) if minetest.setting_getbool("creative_mode") then return count else return 0 end end, allow_put = function(inv, listname, index, stack, player) return 0 end, allow_take = function(inv, listname, index, stack, player) if minetest.setting_getbool("creative_mode") then return -1 else return 0 end end, on_move = function(inv, from_list, from_index, to_list, to_index, count, player) end, on_put = function(inv, listname, index, stack, player) end, on_take = function(inv, listname, index, stack, player) --print(player:get_player_name().." takes item from creative inventory; listname="..dump(listname)..", index="..dump(index)..", stack="..dump(stack)) if stack then minetest.log("action", player:get_player_name().." takes "..dump(stack:get_name()).." from creative inventory") --print("stack:get_name()="..dump(stack:get_name())..", stack:get_count()="..dump(stack:get_count())) end end, }) local creative_list = {} for name,def in pairs(minetest.registered_items) do if (not def.groups.not_in_creative_inventory or def.groups.not_in_creative_inventory == 0) and def.description and def.description ~= "" then table.insert(creative_list, name) end end table.sort(creative_list) inv:set_size("main", #creative_list) for _,itemstring in ipairs(creative_list) do inv:add_item("main", ItemStack(itemstring)) end creative_inventory.creative_inventory_size = #creative_list --print("creative inventory size: "..dump(creative_inventory.creative_inventory_size)) end) -- Create the trash field local trash = minetest.create_detached_inventory("creative_trash", { -- Allow the stack to be placed and remove it in on_put() -- This allows the creative inventory to restore the stack allow_put = function(inv, listname, index, stack, player) if minetest.setting_getbool("creative_mode") then return stack:get_count() else return 0 end end, on_put = function(inv, listname, index, stack, player) inv:set_stack(listname, index, "") end, }) trash:set_size("main", 1) creative_inventory.set_creative_formspec = function(player, start_i, pagenum) pagenum = math.floor(pagenum) local pagemax = math.floor((creative_inventory.creative_inventory_size-1) / (6*4) + 1) player:set_inventory_formspec( "size[13,7.5]".. --"image[6,0.6;1,2;player.png]".. default.gui_bg.. default.gui_bg_img.. default.gui_slots.. "list[current_player;main;5,3.5;8,1;]".. "list[current_player;main;5,4.75;8,3;8]".. "list[current_player;craft;8,0;3,3;]".. "list[current_player;craftpreview;12,1;1,1;]".. "image[11,1;1,1;gui_furnace_arrow_bg.png^[transformR270]".. "list[detached:creative;main;0.3,0.5;4,6;"..tostring(start_i).."]".. "label[2.0,6.55;"..tostring(pagenum).."/"..tostring(pagemax).."]".. "button[0.3,6.5;1.6,1;creative_prev;<<]".. "button[2.7,6.5;1.6,1;creative_next;>>]".. "listring[current_player;main]".. "listring[current_player;craft]".. "listring[current_player;main]".. "listring[detached:creative;main]".. "label[5,1.5;Trash:]".. "list[detached:creative_trash;main;5,2;1,1;]".. default.get_hotbar_bg(5,3.5) ) end minetest.register_on_joinplayer(function(player) -- If in creative mode, modify player's inventory forms if not minetest.setting_getbool("creative_mode") then return end creative_inventory.set_creative_formspec(player, 0, 1) end) minetest.register_on_player_receive_fields(function(player, formname, fields) if not minetest.setting_getbool("creative_mode") then return end -- Figure out current page from formspec local current_page = 0 local formspec = player:get_inventory_formspec() local start_i = string.match(formspec, "list%[detached:creative;main;[%d.]+,[%d.]+;[%d.]+,[%d.]+;(%d+)%]") start_i = tonumber(start_i) or 0 if fields.creative_prev then start_i = start_i - 4*6 end if fields.creative_next then start_i = start_i + 4*6 end if start_i < 0 then start_i = start_i + 4*6 end if start_i >= creative_inventory.creative_inventory_size then start_i = start_i - 4*6 end if start_i < 0 or start_i >= creative_inventory.creative_inventory_size then start_i = 0 end creative_inventory.set_creative_formspec(player, start_i, start_i / (6*4) + 1) end) if minetest.setting_getbool("creative_mode") then local digtime = 0.5 minetest.register_item(":", { type = "none", wield_image = "wieldhand.png", wield_scale = {x=1,y=1,z=2.5}, range = 10, tool_capabilities = { full_punch_interval = 0.5, max_drop_level = 3, groupcaps = { crumbly = {times={[1]=digtime, [2]=digtime, [3]=digtime}, uses=0, maxlevel=3}, cracky = {times={[1]=digtime, [2]=digtime, [3]=digtime}, uses=0, maxlevel=3}, snappy = {times={[1]=digtime, [2]=digtime, [3]=digtime}, uses=0, maxlevel=3}, choppy = {times={[1]=digtime, [2]=digtime, [3]=digtime}, uses=0, maxlevel=3}, oddly_breakable_by_hand = {times={[1]=digtime, [2]=digtime, [3]=digtime}, uses=0, maxlevel=3}, }, damage_groups = {fleshy = 10}, } }) minetest.register_on_placenode(function(pos, newnode, placer, oldnode, itemstack) return true end) function minetest.handle_node_drops(pos, drops, digger) if not digger or not digger:is_player() then return end local inv = digger:get_inventory() if inv then for _,item in ipairs(drops) do item = ItemStack(item):get_name() if not inv:contains_item("main", item) then inv:add_item("main", item) end end end end end
gpl-3.0
czfshine/Don-t-Starve
data/scripts/stategraphs/SGbeardbunnyman.lua
1
7537
require("stategraphs/commonstates") local actionhandlers = { ActionHandler(ACTIONS.EAT, "eat"), ActionHandler(ACTIONS.PICKUP, "pickup"), } local events = { CommonHandlers.OnStep(), CommonHandlers.OnLocomote(true,true), CommonHandlers.OnSleep(), CommonHandlers.OnFreeze(), CommonHandlers.OnAttack(), CommonHandlers.OnAttacked(), CommonHandlers.OnDeath(), EventHandler("transformwere", function(inst) if inst.components.health:GetPercent() > 0 then inst.sg:GoToState("transformWere") end end), EventHandler("giveuptarget", function(inst, data) if data.target then inst.sg:GoToState("howl") end end), EventHandler("newcombattarget", function(inst, data) if data.target and not inst.sg:HasStateTag("busy") then if math.random() < 0.3 then inst.sg:GoToState("howl") else inst.SoundEmitter:PlaySound("dontstarve/creatures/werepig/idle") end end end), } local states= { State{ name = "death", tags = {"busy"}, onenter = function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/werepig/grunt") inst.AnimState:PlayAnimation("death") inst.components.locomotor:StopMoving() RemovePhysicsColliders(inst) inst.components.lootdropper:DropLoot(Vector3(inst.Transform:GetWorldPosition())) end, }, State{ name = "howl", tags = {"busy"}, onenter = function(inst) inst.Physics:Stop() inst.AnimState:PlayAnimation("beard_idle_loop") end, timeline = { TimeEvent(20*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/werepig/howl") end), }, events= { EventHandler("animover", function(inst) inst.sg:GoToState("idle") end), }, }, State{ name = "transformWere", tags = {"transform", "busy"}, onenter = function(inst) inst.Physics:Stop() inst.SoundEmitter:PlaySound("dontstarve/creatures/werepig/transformToWere") inst.AnimState:SetBuild(inst.build) inst.AnimState:PlayAnimation("transform_rabbit_beard") end, onexit = function(inst) inst.AnimState:SetBuild("manrabbit_beard_build") end, events= { EventHandler("animover", function(inst) inst.components.sleeper:WakeUp() inst.sg:GoToState("idle") end ), }, }, State{ name = "idle", tags = {"idle", "canrotate"}, onenter = function(inst, pushanim) inst.Physics:Stop() if pushanim then if type(pushanim) == "string" then inst.AnimState:PlayAnimation(pushanim) end inst.AnimState:PushAnimation("beard_idle_loop", true) else inst.AnimState:PlayAnimation("beard_idle_loop", true) end end, }, State{ name = "attack", tags = {"attack", "busy"}, onenter = function(inst) inst.components.combat:StartAttack() inst.Physics:Stop() inst.AnimState:PlayAnimation("beard_atk_pre") inst.AnimState:PushAnimation("beard_atk", false) end, timeline= { TimeEvent(15*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/werepig/attack") end), TimeEvent(16*FRAMES, function(inst) inst.components.combat:DoAttack() end), }, events= { EventHandler("animqueueover", function(inst) if not inst.components.combat.target and math.random() < 0.3 then inst.sg:GoToState("idle") else inst.sg:GoToState("idle") end end ), }, }, State{ name = "run_start", tags = {"moving", "running", "canrotate"}, onenter = function(inst) inst.components.locomotor:RunForward() inst.AnimState:PlayAnimation("beard_run_pre") end, events= { EventHandler("animover", function(inst) inst.sg:GoToState("run") end ), }, }, State{ name = "run", tags = {"moving", "running", "canrotate"}, onenter = function(inst) inst.components.locomotor:RunForward() inst.AnimState:PlayAnimation("beard_run_loop") end, timeline = { TimeEvent(0*FRAMES, PlayFootstep ), TimeEvent(10*FRAMES, PlayFootstep ), }, events= { EventHandler("animover", function(inst) inst.sg:GoToState("run") end ), }, }, State{ name = "run_stop", tags = {"canrotate"}, onenter = function(inst) inst.Physics:Stop() inst.AnimState:PlayAnimation("beard_run_pst") end, events= { EventHandler("animover", function(inst) inst.sg:GoToState("idle") end ), }, }, State{ name = "walk_start", tags = {"moving", "canrotate"}, onenter = function(inst) inst.components.locomotor:WalkForward() inst.AnimState:PlayAnimation("beard_walk_pre") end, events= { EventHandler("animover", function(inst) inst.sg:GoToState("walk") end ), }, }, State{ name = "walk", tags = {"moving", "canrotate"}, onenter = function(inst) inst.components.locomotor:WalkForward() inst.AnimState:PlayAnimation("beard_walk_loop") end, timeline = { TimeEvent(0*FRAMES, PlayFootstep), TimeEvent(12*FRAMES, PlayFootstep), }, events= { EventHandler("animover", function(inst) inst.sg:GoToState("walk") end ), }, }, State{ name = "walk_stop", tags = {"canrotate"}, onenter = function(inst) inst.Physics:Stop() inst.AnimState:PlayAnimation("beard_walk_pst") end, events= { EventHandler("animover", function(inst) inst.sg:GoToState("idle") end ), }, }, State{ name = "eat", tags = {"busy"}, onenter = function(inst) inst.Physics:Stop() inst.AnimState:PlayAnimation("eat") end, timeline= { TimeEvent(20*FRAMES, function(inst) inst:PerformBufferedAction() end), }, events= { EventHandler("animover", function(inst) if not inst.components.combat.target or math.random() < 0.3 then inst.sg:GoToState("howl") else inst.sg:GoToState("idle") end end ), }, }, State{ name = "hit", tags = {"busy"}, onenter = function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/werepig/hurt") inst.AnimState:PlayAnimation("hit") inst.Physics:Stop() end, events= { EventHandler("animover", function(inst) inst.sg:GoToState("idle") end ), }, }, } CommonStates.AddSleepStates(states, { sleeptimeline = { TimeEvent(35*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/werepig/sleep") end ), }, }) CommonStates.AddFrozenStates(states) CommonStates.AddSimpleActionState(states, "eat", "eat", 20*FRAMES, {"busy"}) return StateGraph("beardpig", states, events, "idle", actionhandlers)
gpl-2.0
JordyMoos/JMShopkeeper
JMShopkeeper.lua
1
5965
--- --- JMShopkeeper --- --[[ Variable declaration ]] --- -- @field name -- @field savedVariablesName -- local Config = { name = 'JMShopkeeper', savedVariablesName = 'JMShopkeeperSavedVariables', } --- -- Parser object -- local Parser = {} local ToggleStatus = 'sales' --[[ Result table ]] --- -- local ResultTable = { position = 1, rowList = {}, rowCount = 20 } local ParsedData = { saleList = {}, buyList = {}, guildList = {}, } --- -- function ResultTable:initialize() -- Create the result rows for rowIndex = 1, self.rowCount do local row = CreateControlFromVirtual( 'JMShopkeeperResultRow', JMShopkeeperGuiMainWindowResultBackground, 'JMShopkeeperResultRow', rowIndex ); row:SetSimpleAnchorParent(5, (row:GetHeight() + 2) * (rowIndex - 1)) row:SetHidden(false) self.rowList[rowIndex] = row end -- Enable scrolling over the result rows JMShopkeeperGuiMainWindowResultBackground:SetMouseEnabled(true) JMShopkeeperGuiMainWindowResultBackground:SetHandler("OnMouseWheel", function(_, direction) ResultTable:onScrolled(direction) end) -- Let the fetch button work JMShopkeeperGuiMainWindowFetchButton:SetHandler('OnClicked', function() Parser:parse() end) -- Let toggle button work JMShopkeeperGuiMainWindowToggleButton:SetHandler('OnClicked', function() if ToggleStatus == 'sales' then ToggleStatus = 'buys' else ToggleStatus = 'sales' end ResultTable:draw() ResultTable:resetPosition() end) local saleList = JMGuildSaleHistoryTracker.getSalesFromUser("@Player") end --- -- function ResultTable:resetPosition() self.position = 0 end --- -- function ResultTable:onScrolled(direction) self:adjustPosition(direction) self:draw() end --- -- @param direction -- function ResultTable:adjustPosition(direction) local newPosition = self.position + direction; local maxPosition = #ParsedData.saleList if ToggleStatus == 'buys' then maxPosition = #ParsedData.buyList end if (newPosition > maxPosition - self.rowCount) then newPosition = maxPosition - self.rowCount end if (newPosition < 1) then newPosition = 0 end self.position = newPosition; end --- -- function ResultTable:draw() for rowIndex = 1, self.rowCount do if ToggleStatus == 'sales' then local sale = ParsedData.saleList[rowIndex + self.position] if (sale == nil) then return end local icon = GetItemLinkInfo(sale.itemLink) local resultRow = self.rowList[rowIndex] resultRow:GetNamedChild('ID'):SetText((rowIndex + self.position)) resultRow:GetNamedChild('Buyer'):SetText(sale.buyer) resultRow:GetNamedChild('Guild'):SetText(sale.guildName) resultRow:GetNamedChild('Icon'):SetTexture(icon) resultRow:GetNamedChild('Item'):SetText(zo_strformat('<<t:1>>', sale.itemLink)) resultRow:GetNamedChild('Price'):SetText(sale.price) resultRow:GetNamedChild('Quantity'):SetText(sale.quantity) resultRow:GetNamedChild('Time'):SetText(ZO_FormatDurationAgo(GetTimeStamp() - sale.saleTimestamp)) else local sale = ParsedData.buyList[rowIndex + self.position] if (sale == nil) then return end local icon = GetItemLinkInfo(sale.itemLink) local resultRow = self.rowList[rowIndex] resultRow:GetNamedChild('ID'):SetText((rowIndex + self.position)) resultRow:GetNamedChild('Buyer'):SetText(sale.seller) resultRow:GetNamedChild('Guild'):SetText(sale.guildName) resultRow:GetNamedChild('Icon'):SetTexture(icon) resultRow:GetNamedChild('Item'):SetText(zo_strformat('<<t:1>>', sale.itemLink)) resultRow:GetNamedChild('Price'):SetText(sale.price) resultRow:GetNamedChild('Quantity'):SetText(sale.quantity) resultRow:GetNamedChild('Time'):SetText(ZO_FormatDurationAgo(GetTimeStamp() - sale.saleTimestamp)) end end -- JMShopkeeperResultPaginationSummary:SetText((self.position + 1) .. ' - ' .. (self.position + self.rowCount) .. ' of ' .. #ParsedData.saleList) end --[[ Parser ]] function Parser:parse() d('Parsing') local salesList = JMGuildSaleHistoryTracker.getSalesFromUser(GetDisplayName()) table.sort(salesList, function(a, b) return a.saleTimestamp > b.saleTimestamp end) local guildList = {} for _, sale in pairs(salesList) do if not guildList[sale.guildName] then guildList[sale.guildName] = 0 end guildList[sale.guildName] = guildList[sale.guildName] + 1 end d(guildList) ParsedData.guildList = guildList ParsedData.saleList = salesList -- Buys Parser:parseBuyList() ResultTable:resetPosition() ResultTable:draw() end --- -- function Parser:parseBuyList() local buyList = JMGuildBuyHistoryTracker.getAll(GetDisplayName()) table.sort(buyList, function(a, b) return a.saleTimestamp > b.saleTimestamp end) ParsedData.buyList = buyList end --[[ Initialize ]] --- -- Start of the addon -- local function Initialize() ResultTable:initialize() end --[[ Events ]] --- Adding the initialize handler EVENT_MANAGER:RegisterForEvent( Config.name, EVENT_ADD_ON_LOADED, function (event, addonName) if addonName ~= Config.name then return end Initialize() EVENT_MANAGER:UnregisterForEvent(Config.name, EVENT_ADD_ON_LOADED) end ) --- -- SLASH_COMMANDS['/jm_sk'] = function() JMShopkeeperGuiMainWindow:ToggleHidden() JMShopkeeperGuiMainWindow:BringWindowToTop() end
mit
Blu3wolf/Treefarm-AC
prototypes/buildingPrototypes.lua
1
11050
require ("prototypes.pipeConnectors") require ("util") data:extend( { -- ITEMS { type = "item", name = "tf-cokery", icon = "__Treefarm-AC__/graphics/icons/cokery.png", flags = {"goes-to-quickbar"}, subgroup = "tf-buildings", order = "a[cokery]", place_result = "tf-cokery-dummy", stack_size = 10 }, { type = "item", name = "tf-stone-crusher", icon = "__Treefarm-AC__/graphics/icons/stone-crusher.png", flags = {"goes-to-quickbar"}, subgroup = "tf-buildings", order = "a[stone-crusher]", place_result = "tf-stone-crusher", stack_size = 10 }, { type = "item", name = "tf-bioreactor", icon = "__Treefarm-AC__/graphics/icons/bioreactor.png", flags = {"goes-to-quickbar"}, subgroup = "tf-buildings", order = "a[bioreactor]", place_result = "tf-bioreactor", stack_size = 10 }, { type = "item", name = "tf-biolab", icon = "__Treefarm-AC__/graphics/icons/biolab.png", flags = {"goes-to-quickbar"}, subgroup = "tf-buildings", order = "a[biolab]", place_result = "tf-biolab", stack_size = 10 }, --RECIPES { type = "recipe", name = "tf-cokery", ingredients = {{"stone-furnace",1},{"steel-plate",10}}, result = "tf-cokery", result_count = 1, enabled = "false" }, { type = "recipe", name = "tf-stone-crusher", ingredients = {{"iron-plate",10},{"steel-plate",10},{"copper-cable",5},{"iron-gear-wheel",5}}, result = "tf-stone-crusher", enabled = "false", result_count = 1 }, { type = "recipe", name = "tf-bioreactor", ingredients = {{"assembling-machine-1",1},{"steel-plate",5},{"electronic-circuit",5}}, result = "tf-bioreactor", enabled = "false", result_count = 1 }, { type = "recipe", name = "tf-biolab", ingredients = { {"steel-plate", 5}, {"iron-gear-wheel", 5}, {"electronic-circuit", 5}, {"pipe", 5} }, result = "tf-biolab", enabled = "false", result_count = 1 }, --ENTITIES -- COKERY { type = "container", name = "tf-cokery-dummy", icon = "__Treefarm-AC__/graphics/icons/cokery.png", flags = {"placeable-neutral","placeable-player", "player-creation"}, minable = {hardness = 0.2, mining_time = 0.5, result = "tf-cokery"}, max_health = 200, corpse = "big-remnants", resistances = {{type = "fire", percent = 70}}, collision_box = {{-1.4, -2.0}, {1.4, 2.4}}, selection_box = {{-1.5, -2.5}, {1.5, 2.5}}, inventory_size = 1, picture = { filename = "__Treefarm-AC__/graphics/entities/cokery/cokery-idle.png", priority = "extra-high", width = 100, height = 160, shift = {0.0, 0.0} } }, { type = "assembling-machine", name = "tf-cokery", icon = "__Treefarm-AC__/graphics/icons/cokery.png", flags = {"placeable-neutral","placeable-player", "player-creation"}, order = "a[cokery]", minable = {hardness = 0.2, mining_time = 0.5, result = "tf-cokery"}, max_health = 200, corpse = "big-remnants", resistances = {{type = "fire", percent = 70}}, collision_box = {{-1.4, -2.0}, {1.4, 2.4}}, selection_box = {{-1.5, -2.5}, {1.5, 2.5}}, module_slots = 2, allowed_effects = {"consumption", "speed"}, animation = { north = { filename = "__Treefarm-AC__/graphics/entities/cokery/cokery-idle.png", width = 100, height = 160, frame_count = 1, line_length = 1, shift = {0, 0} }, south = { filename = "__Treefarm-AC__/graphics/entities/cokery/cokery-idle.png", width = 100, height = 160, frame_count = 1, line_length = 1, shift = {0, 0} }, west = { filename = "__Treefarm-AC__/graphics/entities/cokery/cokery-idle.png", width = 100, height = 160, frame_count = 1, line_length = 1, shift = {0, 0} }, east = { filename = "__Treefarm-AC__/graphics/entities/cokery/cokery-idle.png", width = 100, height = 160, frame_count = 1, line_length = 1, shift = {0, 0} } }, working_visualisations = { { north_position = { 0.0, 0.0}, south_position = { 0.0, 0.0}, west_position = { 0.0, 0.0}, --{ 1.3, -2.0}, east_position = { 0.0, 0.0}, --{ 1.3, -2.0}, animation = { filename = "__Treefarm-AC__/graphics/entities/cokery/cokery-anim.png", frame_count = 28, line_length = 14, width = 100, height = 160, scale = 1.0, shift = {0, 0}, animation_speed = 0.1 } } }, crafting_categories = {"treefarm-mod-smelting"}, energy_source = { type = "electric", input_priority = "secondary", usage_priority = "secondary-input", emissions = 6 / 3 }, energy_usage = "6W", crafting_speed = 2, ingredient_count = 1 }, -- STONECRUSHER { type = "furnace", name = "tf-stone-crusher", icon = "__Treefarm-AC__/graphics/icons/stone-crusher.png", flags = {"placeable-neutral","player-creation"}, minable = {hardness = 0.2,mining_time = 0.5,result = "tf-stone-crusher"}, max_health = 100, corpse = "big-remnants", dying_explosion = "medium-explosion", module_slots = 1, resistances = {{type = "fire",percent = 70}}, working_sound = { sound = { filename = "__base__/sound/assembling-machine-t1-1.ogg", volume = 0.7 }, apparent_volume = 1.5 }, collision_box = {{-0.9,-0.9},{0.9,0.9}}, selection_box = {{-1.0,-1.0},{1.0,1.0}}, animation = { filename = "__Treefarm-AC__/graphics/entities/stone-crusher/stone-crusher-off-anim.png", priority = "high", width = 65, height = 78, frame_count = 1, animation_speed = 0.5, shift = {0.0, -0.1} }, working_visualisations = { filename = "__Treefarm-AC__/graphics/entities/stone-crusher/stone-crusher-anim.png", priority = "high", width = 65, height = 78, frame_count = 11, animation_speed = 0.18 / 2.5, shift = {0.0, -0.1} }, crafting_categories = {"treefarm-mod-crushing"}, result_inventory_size = 1, source_inventory_size = 1, crafting_speed = 1, energy_source = { type = "electric", usage_priority = "secondary-input", emissions = 0.05 / 1.5 }, energy_usage = "50kW" }, -- BIOREACTOR { type = "assembling-machine", name = "tf-bioreactor", icon = "__Treefarm-AC__/graphics/icons/bioreactor.png", flags = {"placeable-neutral", "player-creation"}, minable = {hardness = 0.2, mining_time = 0.5, result = "tf-bioreactor"}, max_health = 100, corpse = "big-remnants", fluid_boxes = { { production_type = "input", pipe_picture = assembler2pipepicturesBioreactor(), pipe_covers = pipecoverspicturesBioreactor(), base_area = 10, base_level = -1, pipe_connections = {{ type="input", position = {0, -2} }} }, { production_type = "input", pipe_picture = assembler2pipepicturesBioreactor(), pipe_covers = pipecoverspicturesBioreactor(), base_area = 10, base_level = -1, pipe_connections = {{ type="input", position = {2, 0} }} }, { production_type = "input", pipe_picture = assembler2pipepicturesBioreactor(), pipe_covers = pipecoverspicturesBioreactor(), base_area = 10, base_level = -1, pipe_connections = {{ type="input", position = {0, 2} }} }, { production_type = "output", pipe_picture = assembler2pipepicturesBioreactor(), pipe_covers = pipecoverspicturesBioreactor(), base_area = 10, base_level = 1, pipe_connections = {{ type="output", position = {-2, -1} }} }, { production_type = "output", pipe_picture = assembler2pipepicturesBioreactor(), pipe_covers = pipecoverspicturesBioreactor(), base_area = 10, base_level = 1, pipe_connections = {{ type="output", position = {-2, 1} }} }, off_when_no_fluid_recipe = false }, collision_box = {{-1.2, -1.2}, {1.2, 1.2}}, selection_box = {{-1.5, -1.5}, {1.5, 1.5}}, animation = { filename = "__Treefarm-AC__/graphics/entities/bioreactor/bioreactor.png", priority = "high", width = 128, height = 150, frame_count = 26, line_length = 13, animation_speed = 0.4, shift = {0.55, -0.33} }, energy_source = { type = "electric", usage_priority = "secondary-input" }, crafting_categories = {"treefarm-mod-bioreactor"}, ingredient_count = 3, crafting_speed = 1, energy_usage = "10kW" }, -- BIOLAB { type = "assembling-machine", name = "tf-biolab", icon = "__Treefarm-AC__/graphics/icons/biolab.png", flags = {"placeable-neutral","placeable-player", "player-creation"}, minable = {hardness = 0.2, mining_time = 0.5, result = "tf-biolab"}, max_health = 300, corpse = "big-remnants", collision_box = {{-1.4, -1.4}, {1.4, 1.4}}, selection_box = {{-1.5, -1.5}, {1.5, 1.5}}, module_slots = 2, allowed_effects = {"consumption", "speed", "productivity", "pollution"}, animation = { filename = "__Treefarm-AC__/graphics/entities/biolab/biolab.png", width = 128, height = 128, frame_count = 16, line_length = 4, shift = {0.65, -0.25}, scale = 1.2, animation_speed = 0.25 }, working_visualisations = { { north_position = {0.94, -0.73}, west_position = {-0.3, 0.02}, south_position = {-0.97, -1.47}, east_position = {0.05, -1.46}, animation = { filename = "__Treefarm-AC__/graphics/icons/empty.png", frame_count = 1, width = 32, height = 32, animation_speed = 0.15 } }, { north_position = {1.4, -0.23}, west_position = {-0.3, 0.55}, south_position = {-1, -1}, east_position = {0.05, -0.96}, north_animation = { filename = "__Treefarm-AC__/graphics/icons/empty.png", frame_count = 1, width = 32, height = 32, animation_speed = 0.15 }, west_animation = { filename = "__Treefarm-AC__/graphics/icons/empty.png", frame_count = 1, width = 32, height = 32, animation_speed = 0.15 }, south_animation = { filename = "__Treefarm-AC__/graphics/icons/empty.png", frame_count = 1, width = 32, height = 32, animation_speed = 0.15 } } }, crafting_speed = 1, energy_source = { type = "electric", usage_priority = "secondary-input" }, energy_usage = "180kW", ingredient_count = 4, crafting_categories = {"treefarm-mod-biolab"}, fluid_boxes = { { production_type = "input", pipe_covers = pipecoverspictures(), base_area = 10, base_level = -1, pipe_connections = {{ type="input", position = {-1, -2} }} }, { production_type = "input", pipe_covers = pipecoverspictures(), base_area = 10, base_level = -1, pipe_connections = {{ type="input", position = {1, -2} }} }, { production_type = "output", pipe_covers = pipecoverspictures(), base_level = 1, pipe_connections = {{ position = {-1, 2} }} }, { production_type = "output", pipe_covers = pipecoverspictures(), base_level = 1, pipe_connections = {{ position = {1, 2} }} } } } } )
gpl-2.0
Jordach/Vox
mods/wool/init.lua
8
1786
-- minetest/wool/init.lua -- Backwards compatibility with jordach's 16-color wool mod minetest.register_alias("wool:dark_blue", "wool:blue") minetest.register_alias("wool:gold", "wool:yellow") local wool = {} -- This uses a trick: you can first define the recipes using all of the base -- colors, and then some recipes using more specific colors for a few non-base -- colors available. When crafting, the last recipes will be checked first. wool.dyes = { {"white", "White", nil}, {"grey", "Grey", "basecolor_grey"}, {"black", "Black", "basecolor_black"}, {"red", "Red", "basecolor_red"}, {"yellow", "Yellow", "basecolor_yellow"}, {"green", "Green", "basecolor_green"}, {"cyan", "Cyan", "basecolor_cyan"}, {"blue", "Blue", "basecolor_blue"}, {"magenta", "Magenta", "basecolor_magenta"}, {"orange", "Orange", "excolor_orange"}, {"violet", "Violet", "excolor_violet"}, {"brown", "Brown", "unicolor_dark_orange"}, {"pink", "Pink", "unicolor_light_red"}, {"dark_grey", "Dark Grey", "unicolor_darkgrey"}, {"dark_green", "Dark Green", "unicolor_dark_green"}, } for _, row in ipairs(wool.dyes) do local name = row[1] local desc = row[2] local craft_color_group = row[3] -- Node Definition minetest.register_node("wool:"..name, { description = desc.." Wool", tiles = {"wool_"..name..".png"}, groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1}, sounds = default.node_sound_defaults(), }) if craft_color_group then -- Crafting from dye and white wool minetest.register_craft({ type = "shapeless", output = 'wool:'..name, recipe = {'group:dye,'..craft_color_group, 'group:wool'}, }) end end
lgpl-2.1
czfshine/Don-t-Starve
data/DLC0001/scripts/prefabs/bedroll_furry.lua
1
2517
local assets= { Asset("ANIM", "anim/swap_bedroll_furry.zip"), } local function onsleep(inst, sleeper) local br = nil if inst.components.stackable then br = inst.components.stackable:Get() else br = inst end if br and br.components.finiteuses then if br.components.finiteuses:GetUses() <= 1 then br:Remove() br.persists = false end end GetPlayer().HUD:Hide() TheFrontEnd:Fade(false,1) inst:DoTaskInTime(1.2, function() TheFrontEnd:Fade(true,1) GetPlayer().HUD:Show() sleeper.sg:GoToState("wakeup") if sleeper.components.hunger then -- Check SGwilson, state "bedroll", if you change this value sleeper.components.hunger:DoDelta(-TUNING.CALORIES_HUGE, false, true) end if sleeper.components.sanity then sleeper.components.sanity:DoDelta(TUNING.SANITY_HUGE, false) end if sleeper.components.health then sleeper.components.health:DoDelta(TUNING.HEALING_MEDLARGE, false, "bedroll", true) end if sleeper.components.temperature then if sleeper.components.temperature.current < TUNING.TARGET_SLEEP_TEMP then sleeper.components.temperature:SetTemperature(TUNING.TARGET_SLEEP_TEMP) elseif sleeper.components.temperature.current > TUNING.TARGET_SLEEP_TEMP * 1.5 then sleeper.components.temperature:SetTemperature(sleeper.components.temperature.current + (TUNING.TARGET_SLEEP_TEMP * .5)) end end GetClock():MakeNextDay() end) end local function onuse() GetPlayer().AnimState:OverrideSymbol("swap_bedroll", "swap_bedroll_furry", "bedroll_furry") end local function fn(Sim) local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() MakeInventoryPhysics(inst) anim:SetBank("swap_bedroll_furry") anim:SetBuild("swap_bedroll_furry") anim:PlayAnimation("idle") inst:AddComponent("inspectable") inst:AddComponent("inventoryitem") inst:AddComponent("finiteuses") inst.components.finiteuses:SetConsumption(ACTIONS.SLEEPIN, 1) inst.components.finiteuses:SetMaxUses(3) inst.components.finiteuses:SetUses(3) inst:AddComponent("fuel") inst.components.fuel.fuelvalue = TUNING.LARGE_FUEL MakeSmallBurnable(inst, TUNING.LONG_BURNABLE) MakeSmallPropagator(inst) inst.components.burnable:MakeDragonflyBait(3) inst:AddComponent("sleepingbag") inst.components.sleepingbag.onsleep = onsleep inst.onuse = onuse return inst end return Prefab( "common/inventory/bedroll_furry", fn, assets)
gpl-2.0
AmirPGA/P.G.A_Black
plugins/owners.lua
284
12473
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
woftles/Opengario
oop.lua
1
2740
function class(inheritsFrom, ro) local c = {} local c_mt = {__index = c, __tostring = function(obj) if obj.tostring then return obj:tostring() end end} if ro then roClass(c, c_mt, ro) end function c.new(...) local obj = setmetatable({}, c_mt) if obj.init then obj:init(...) end return obj end function c.super() return inheritsFrom end function c.instanceOf(class) return c == class or inheritsFrom and inheritsFrom.instanceOf(class) end if inheritsFrom then if not inheritsFrom.instanceOf then error("Bad superclass.") end setmetatable(c, {__index = inheritsFrom}) end return c end function roClass(c, c_mt, ro) c.readonly = ro c_mt.__index = function(tab, key) return tab.readonly[key] or (tab.super() or {})[key] or rawget(tab, key) end c_mt.__newindex = function(tab, key, val) if ro[key] then error("Cannot modify read-only value.") else rawset(tab, key, val) end end end Connection = class() function Connection:init(event, func) if not func then error("No function to connect.") end self.event = event self.fire = func end function Connection:disconnect() for i, c in pairs(self.event.connections) do if c == self then table.remove(self.event.connections, i) return end end end Event = class() function Event:init() self.connections = {} end function Event:fire(...) for i, c in pairs(self.connections) do c.fire(...) end end function Event:connect(func) local c = Connection.new(self, func) table.insert(self.connections, c) return c end List = class() function List:init(isWeak) self.table = isWeak and setmetatable({}, {_mode = "kv"}) or {} end function List:get() return self.table end function List:add(...) table.insert(self.table, ...) end function List:remove(...) return table.remove(self.table, ...) end function List:removeValue(obj) for i = 1, #self.table do if self.table[i] == obj then return table.remove(self.table, i) end end end TaskScheduler = class() TaskScheduler.timer = 0 function TaskScheduler:init() self.schedule = {} end --t is the time delayed, func is a function, additional arguments are called with the function. function TaskScheduler:delay(t, func, ...) local t0 = self.timer if not self.schedule[t + t0] then self.schedule[t + t0] = {} end table.insert(self.schedule[t + t0], {func, {...}}) end function TaskScheduler:update(s) self.timer = self.timer + s local t0 = self.timer for i, funcs in pairs(self.schedule) do if i <= t0 then for j, fpair in pairs(funcs) do fpair[1](unpack(fpair[2])) end self.schedule[i] = nil end end end
gpl-2.0
czfshine/Don-t-Starve
data/DLC0001/scripts/components/playercontroller.lua
1
36961
require "class" local easing = require "easing" local trace = function() end local START_DRAG_TIME = (1/30)*8 local PlayerController = Class(function(self, inst) self.inst = inst self.enabled = true self.handler = TheInput:AddGeneralControlHandler(function(control, value) self:OnControl(control, value) end) self.inst:StartUpdatingComponent(self) self.draggingonground = false self.startdragtestpos = nil self.startdragtime = nil self.inst:ListenForEvent("buildstructure", function(inst, data) self:OnBuild() end, GetPlayer()) self.inst:ListenForEvent("equip", function(inst, data) self:OnEquip(data) end, GetPlayer() ) self.inst:ListenForEvent("unequip", function(inst, data) self:OnUnequip(data) end, GetPlayer() ) self.reticule = nil self.terraformer = nil self.LMBaction = nil self.RMBaction = nil self.mousetimeout = 10 self.time_direct_walking = 0 self.deploy_mode = not TheInput:ControllerAttached() --TheInput:AddMoveHandler(function(x,y) self.using_mouse = true self.mousetimeout = 3 end) end) function PlayerController:OnBuild() self:CancelPlacement() end function PlayerController:IsEnabled() return self.enabled and self.inst.HUD and not self.inst.HUD:IsControllerCraftingOpen() and not self.inst.HUD:IsControllerInventoryOpen() end function PlayerController:OnEquip(data) local controller_mode = TheInput:ControllerAttached() --Blink Staff if data.item.components.reticule and data.eslot == EQUIPSLOTS.HANDS then self.reticule = data.item.components.reticule if controller_mode and self.reticule and not self.reticule.reticule then self.reticule:CreateReticule() end end end function PlayerController:OnUnequip(data) if self.reticule and data.item.components.reticule and data.eslot == EQUIPSLOTS.HANDS then self.reticule:DestroyReticule() self.reticule = nil end end function PlayerController:OnControl(control, down) if not self:IsEnabled() then return end if not IsPaused() then if control == CONTROL_PRIMARY then self:OnLeftClick(down) return elseif control == CONTROL_SECONDARY then self:OnRightClick(down) return end if down then if self.placer_recipe and control == CONTROL_CANCEL then self:CancelPlacement() else if control == CONTROL_INSPECT then self:DoInspectButton() elseif control == CONTROL_ACTION then self:DoActionButton() elseif control == CONTROL_ATTACK then self:DoAttackButton() elseif control == CONTROL_CONTROLLER_ALTACTION then self:DoControllerAltAction() elseif control == CONTROL_CONTROLLER_ACTION then self:DoControllerAction() elseif control == CONTROL_CONTROLLER_ATTACK then self:DoControllerAttack() end local inv_obj = self:GetCursorInventoryObject() if inv_obj then local is_equipped = (inv_obj.components.equippable and inv_obj.components.equippable:IsEquipped()) if control == CONTROL_INVENTORY_DROP then self.inst.components.inventory:DropItem(inv_obj, true) elseif control == CONTROL_INVENTORY_EXAMINE then self.inst.components.locomotor:PushAction( BufferedAction(self.inst, inv_obj, ACTIONS.LOOKAT)) elseif control == CONTROL_INVENTORY_USEONSELF and is_equipped then self.inst.components.locomotor:PushAction( BufferedAction(self.inst, nil, ACTIONS.UNEQUIP, inv_obj)) elseif control == CONTROL_INVENTORY_USEONSELF and not is_equipped then if inv_obj.components.deployable and not self.deploy_mode and inv_obj.components.inventoryitem:GetGrandOwner() == self.inst then self.deploy_mode = true else if not self.inst.sg:HasStateTag("busy") then self.inst.components.locomotor:PushAction(self:GetItemSelfAction(inv_obj), true) end end elseif control == CONTROL_INVENTORY_USEONSCENE and not is_equipped then if inv_obj.components.inventoryitem:GetGrandOwner() ~= self.inst then self.inst.components.inventory:GiveItem(inv_obj) else self:DoAction(self:GetItemUseAction(inv_obj)) end elseif control == CONTROL_INVENTORY_USEONSCENE and is_equipped then local action = self:GetItemSelfAction(inv_obj) if action.action ~= ACTIONS.UNEQUIP then self.inst.components.locomotor:PushAction(action) end end end end end end end function PlayerController:GetCursorInventoryObject() if self.inst.HUD and self.inst.HUD.controls and self.inst.HUD.controls.inv then return self.inst.HUD.controls.inv:GetCursorItem() end end function PlayerController:DoControllerAction() self.time_direct_walking = 0 if self.placer then if self.placer.components.placer.can_build then self.inst.components.builder:MakeRecipe(self.placer_recipe, Vector3(self.placer.Transform:GetWorldPosition())) return true end elseif self.deployplacer then if self.deployplacer.components.placer.can_build then local act = self.deployplacer.components.placer:GetDeployAction() act.distance = 1 self:DoAction(act) end elseif self.controller_target then self:DoAction( self:GetSceneItemControllerAction(self.controller_target) ) end end function PlayerController:DoControllerAltAction() self.time_direct_walking = 0 if self.placer_recipe then self:CancelPlacement() return end if self.deployplacer then self:CancelDeployPlacement() return end local l, r = self:GetGroundUseAction() if r then self:DoAction(r) return end if self.controller_target then local l, r = self:GetSceneItemControllerAction(self.controller_target) self:DoAction( r ) end end function PlayerController:DoControllerAttack() self.time_direct_walking = 0 local attack_target = self.controller_attack_target if attack_target and self.inst.components.combat.target ~= attack_target then local action = BufferedAction(self.inst, attack_target, ACTIONS.ATTACK) self.inst.components.locomotor:PushAction(action, true) elseif not attack_target and not self.inst.components.combat.target then local action = BufferedAction(self.inst, nil, ACTIONS.FORCEATTACK) self.inst.components.locomotor:PushAction(action, true) else return -- already doing it! end end function PlayerController:RotLeft() local rotamount = 45 ---90-- GetWorld():IsCave() and 22.5 or 45 if TheCamera:CanControl() then if IsPaused() then if GetWorld().minimap.MiniMap:IsVisible() then TheCamera:SetHeadingTarget(TheCamera:GetHeadingTarget() - rotamount) TheCamera:Snap() end else TheCamera:SetHeadingTarget(TheCamera:GetHeadingTarget() - rotamount) --UpdateCameraHeadings() end end end function PlayerController:RotRight() local rotamount = 45 --90--GetWorld():IsCave() and 22.5 or 45 if TheCamera:CanControl() then if IsPaused() then if GetWorld().minimap.MiniMap:IsVisible() then TheCamera:SetHeadingTarget(TheCamera:GetHeadingTarget() + rotamount) TheCamera:Snap() end else TheCamera:SetHeadingTarget(TheCamera:GetHeadingTarget() + rotamount) --UpdateCameraHeadings() end end end function PlayerController:OnRemoveEntity() self.handler:Remove() end function PlayerController:GetHoverTextOverride() if self.placer_recipe then return STRINGS.UI.HUD.BUILD.. " " .. ( STRINGS.NAMES[string.upper(self.placer_recipe.name)] or STRINGS.UI.HUD.HERE ) end end function PlayerController:CancelPlacement() if self.placer then self.placer:Remove() self.placer = nil end self.placer_recipe = nil end function PlayerController:CancelDeployPlacement() self.deploy_mode = not TheInput:ControllerAttached() if self.deployplacer then self.deployplacer:Remove() self.deployplacer = nil end end function PlayerController:StartBuildPlacementMode(recipe, testfn) self.placer_recipe = recipe if self.placer then self.placer:Remove() self.placer = nil end self.placer = SpawnPrefab(recipe.placer) self.placer.components.placer:SetBuilder(self.inst, recipe) self.placer.components.placer.testfn = testfn end function PlayerController:Enable(val) self.enabled = val end function PlayerController:GetAttackTarget(force_attack) local x,y,z = self.inst.Transform:GetWorldPosition() local rad = self.inst.components.combat:GetAttackRange() if not self.directwalking then rad = rad + 6 end --for autowalking --To deal with entity collision boxes we need to pad the radius. local nearby_ents = TheSim:FindEntities(x,y,z, rad + 5) local tool = self.inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HANDS) local has_weapon = tool and tool.components.weapon local playerRad = self.inst.Physics:GetRadius() for k,guy in ipairs(nearby_ents) do if guy ~= self.inst and guy:IsValid() and not guy:IsInLimbo() and not (guy.sg and guy.sg:HasStateTag("invisible")) and guy.components.health and not guy.components.health:IsDead() and guy.components.combat and guy.components.combat:CanBeAttacked(self.inst) and not (guy.components.follower and guy.components.follower.leader == self.inst) and --Now we ensure the target is in range. distsq(guy:GetPosition(), self.inst:GetPosition()) <= math.pow(rad + playerRad + guy.Physics:GetRadius() + 0.1 , 2) then if (guy:HasTag("monster") and has_weapon) or guy:HasTag("hostile") or self.inst.components.combat:IsRecentTarget(guy) or guy.components.combat.target == self.inst or force_attack then return guy end end end end -- function PlayerController:DoAttackButton() local attack_target = self:GetAttackTarget(TheInput:IsControlPressed(CONTROL_FORCE_ATTACK)) if attack_target and self.inst.components.combat.target ~= attack_target then local action = BufferedAction(self.inst, attack_target, ACTIONS.ATTACK) self.inst.components.locomotor:PushAction(action, true) else return -- already doing it! end end function PlayerController:GetActionButtonAction() if self.actionbuttonoverride then return self.actionbuttonoverride(self.inst) end if self:IsEnabled() and not (self.inst.sg:HasStateTag("working") or self.inst.sg:HasStateTag("doing")) then local tool = self.inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HANDS) --bug catching (has to go before combat) if tool and tool.components.tool and tool.components.tool:CanDoAction(ACTIONS.NET) then local target = FindEntity(self.inst, 5, function(guy) return guy.components.health and not guy.components.health:IsDead() and guy.components.workable and guy.components.workable.action == ACTIONS.NET end) if target then return BufferedAction(self.inst, target, ACTIONS.NET, tool) end end --catching local rad = 8 local projectile = FindEntity(self.inst, rad, function(guy) return guy.components.projectile and guy.components.projectile:IsThrown() and self.inst.components.catcher and self.inst.components.catcher:CanCatch() end) if projectile then return BufferedAction(self.inst, projectile, ACTIONS.CATCH) end rad = self.directwalking and 3 or 6 --pickup local pickup = FindEntity(self.inst, rad, function(guy) return (guy.components.inventoryitem and guy.components.inventoryitem.canbepickedup) or (tool and tool.components.tool and guy.components.workable and guy.components.workable.workable and tool.components.tool:CanDoAction(guy.components.workable.action)) or (guy.components.pickable and guy.components.pickable:CanBePicked() and guy.components.pickable.caninteractwith) or (guy.components.stewer and guy.components.stewer.done) or (guy.components.crop and guy.components.crop:IsReadyForHarvest()) or (guy.components.harvestable and guy.components.harvestable:CanBeHarvested()) or (guy.components.trap and guy.components.trap.issprung) or (guy.components.dryer and guy.components.dryer:IsDone()) or (guy.components.activatable and guy.components.activatable.inactive) end) local has_active_item = self.inst.components.inventory:GetActiveItem() ~= nil if pickup and not has_active_item then local action = nil if (tool and tool.components.tool and pickup.components.workable and pickup.components.workable.workable and tool.components.tool:CanDoAction(pickup.components.workable.action)) then action = pickup.components.workable.action elseif pickup.components.trap and pickup.components.trap.issprung then action = ACTIONS.CHECKTRAP elseif pickup.components.activatable and pickup.components.activatable.inactive then action = ACTIONS.ACTIVATE elseif pickup.components.inventoryitem and pickup.components.inventoryitem.canbepickedup then action = ACTIONS.PICKUP elseif pickup.components.pickable and pickup.components.pickable:CanBePicked() then action = ACTIONS.PICK elseif pickup.components.harvestable and pickup.components.harvestable:CanBeHarvested() then action = ACTIONS.HARVEST elseif pickup.components.crop and pickup.components.crop:IsReadyForHarvest() then action = ACTIONS.HARVEST elseif pickup.components.dryer and pickup.components.dryer:IsDone() then action = ACTIONS.HARVEST elseif pickup.components.stewer and pickup.components.stewer.done then action = ACTIONS.HARVEST end if action then local ba = BufferedAction(self.inst, pickup, action, tool) --ba.distance = self.directwalking and rad or 1 return ba end end end end function PlayerController:DoActionButton() --do the placement if self.placer then if self.placer.components.placer.can_build then self.inst.components.builder:MakeRecipe(self.placer_recipe, Vector3(self.placer.Transform:GetWorldPosition())) return true end else local ba = self:GetActionButtonAction() if ba then self.inst.components.locomotor:PushAction(ba, true) end return true end end function PlayerController:DoInspectButton() if self.controller_target and GetPlayer():CanExamine() then self.inst.components.locomotor:PushAction( BufferedAction(self.inst, self.controller_target, ACTIONS.LOOKAT)) end return true end function PlayerController:UsingMouse() if TheInput:ControllerAttached() then return false else return true end end function PlayerController:OnUpdate(dt) if not TheInput:IsControlPressed(CONTROL_PRIMARY) then if self.draggingonground then self.draggingonground = false TheFrontEnd:LockFocus(false) self.startdragtime = nil end end local controller_mode = TheInput:ControllerAttached() if not self:IsEnabled() then if self.directwalking then self.inst.components.locomotor:Stop() self.directwalking = false end if self.placer then self.placer:Remove() self.placer = nil end self:CancelDeployPlacement() if self.reticule and self.reticule.reticule then self.reticule.reticule:Hide() end if self.terraformer then self.terraformer:Remove() self.terraformer = nil end return end local new_highlight = nil if controller_mode then self:UpdateControllerInteractionTarget(dt) self:UpdateControllerAttackTarget(dt) new_highlight = self.controller_target else self.LMBaction, self.RMBaction = self.inst.components.playeractionpicker:DoGetMouseActions() new_highlight = (self.LMBaction and self.LMBaction.target) or (self.RMBaction and self.RMBaction.target) self.controller_attack_target = nil end if new_highlight ~= self.highlight_guy then if self.highlight_guy and self.highlight_guy:IsValid() then if self.highlight_guy.components.highlight then self.highlight_guy.components.highlight:UnHighlight() end end self.highlight_guy = new_highlight end if self.highlight_guy and self.highlight_guy:IsValid() then if not self.highlight_guy.components.highlight then self.highlight_guy:AddComponent("highlight") end local override = self.highlight_guy.highlight_override if override then self.highlight_guy.components.highlight:Highlight(override[1], override[2], override[3]) else self.highlight_guy.components.highlight:Highlight() end else self.highlight_guy = nil end self:DoCameraControl() local active_item = self.inst.components.inventory:GetActiveItem() if not controller_mode then if self.reticule then self.reticule:DestroyReticule() self.reticule = nil end end local placer_item = nil if controller_mode then placer_item = self:GetCursorInventoryObject() else placer_item = active_item end local show_deploy_placer = placer_item and ( placer_item.components.deployable and self.deploy_mode ) and self.placer == nil if show_deploy_placer then local placer_name = placer_item.components.deployable.placer or ((placer_item.prefab or "") .. "_placer") if self.deployplacer and self.deployplacer.prefab ~= placer_name then self:CancelDeployPlacement() end if not self.deployplacer then self.deployplacer = SpawnPrefab(placer_name) if self.deployplacer then self.deployplacer.components.placer:SetBuilder(self.inst, nil, placer_item) self.deployplacer.components.placer.testfn = function(pt) return placer_item.components.deployable:CanDeploy(pt) end self.deployplacer.components.placer:OnUpdate(0) --so that our position is accurate on the first frame end end else self:CancelDeployPlacement() end local terraform = false if controller_mode then local l, r = self:GetGroundUseAction() terraform = r and r.action == ACTIONS.TERRAFORM else local action_r = self:GetRightMouseAction() terraform = action_r and action_r.action == ACTIONS.TERRAFORM and action_r end local show_rightaction_reticule = self.placer == nil and self.deployplacer == nil if show_rightaction_reticule then if terraform and not self.terraformer then self.terraformer = SpawnPrefab("gridplacer") if self.terraformer then self.terraformer.components.placer:SetBuilder(GetPlayer()) self.terraformer.components.placer:OnUpdate(0) end elseif not terraform and self.terraformer then self.terraformer:Remove() self.terraformer = nil end if self.reticule and self.reticule.reticule then self.reticule.reticule:Show() end else if self.terraformer then self.terraformer:Remove() self.terraformer = nil end if self.reticule and self.reticule.reticule then self.reticule.reticule:Hide() end end if self.startdragtime and not self.draggingonground and TheInput:IsControlPressed(CONTROL_PRIMARY) then local now = GetTime() if now - self.startdragtime > START_DRAG_TIME then TheFrontEnd:LockFocus(true) self.draggingonground = true end end if self.draggingonground and TheFrontEnd:GetFocusWidget() ~= self.inst.HUD then TheFrontEnd:LockFocus(false) self.draggingonground = false self.inst.components.locomotor:Stop() end if not self.inst.sg:HasStateTag("busy") then if self.draggingonground then local pt = TheInput:GetWorldPosition() local dst = distsq(pt, Vector3(self.inst.Transform:GetWorldPosition())) if dst > 1 then local angle = self.inst:GetAngleToPoint(pt) self.inst:ClearBufferedAction() self.inst.components.locomotor:RunInDirection(angle) end self.directwalking = false else self:DoDirectWalking(dt) end end --do automagic control repeats if self.inst.sg:HasStateTag("idle") then if TheInput:IsControlPressed(CONTROL_ACTION) then self:OnControl(CONTROL_ACTION, true) elseif TheInput:IsControlPressed(CONTROL_CONTROLLER_ACTION) then self:OnControl(CONTROL_CONTROLLER_ACTION, true) end end if not self.inst.sg:HasStateTag("busy") and not self.directwalking then if TheInput:IsControlPressed(CONTROL_ATTACK) then self:OnControl(CONTROL_ATTACK, true) elseif TheInput:IsControlPressed(CONTROL_CONTROLLER_ATTACK) then self:OnControl(CONTROL_CONTROLLER_ATTACK, true) end end end function PlayerController:GetWorldControllerVector() local xdir = TheInput:GetAnalogControlValue(CONTROL_MOVE_RIGHT) - TheInput:GetAnalogControlValue(CONTROL_MOVE_LEFT) local ydir = TheInput:GetAnalogControlValue(CONTROL_MOVE_UP) - TheInput:GetAnalogControlValue(CONTROL_MOVE_DOWN) local deadzone = .3 if math.abs(xdir) < deadzone and math.abs(ydir) < deadzone then xdir = 0 ydir = 0 end if xdir ~= 0 or ydir ~= 0 then local CameraRight = TheCamera:GetRightVec() local CameraDown = TheCamera:GetDownVec() local dir = CameraRight * xdir - CameraDown * ydir dir = dir:GetNormalized() return dir end end function PlayerController:CanAttackWithController(target) return target ~= self.inst and target:IsValid() and (target.components.health and target.components.health.currenthealth > 0) and not target:IsInLimbo() and not target:HasTag("wall") and not (target.sg and target.sg:HasStateTag("invisible")) and target.components.health and not target.components.health:IsDead() and target.components.combat and target.components.combat:CanBeAttacked(self.inst) end local must_have_attack ={"HASCOMBATCOMPONENT"} local cant_have_attack ={"FX", "NOCLICK", "DECOR", "INLIMBO"} function PlayerController:UpdateControllerAttackTarget(dt) if self.controllerattacktargetage then self.controllerattacktargetage = self.controllerattacktargetage + dt end --if self.controller_attack_target and self.controllerattacktargetage and self.controllerattacktargetage < .3 then return end local heading_angle = -(self.inst.Transform:GetRotation()) local dir = Vector3(math.cos(heading_angle*DEGREES),0, math.sin(heading_angle*DEGREES)) local me_pos = Vector3(self.inst.Transform:GetWorldPosition()) local min_rad = 4 local max_range = self.inst.components.combat:GetAttackRange() + 3 local rad = 8 if self.controller_attack_target and self.controller_attack_target:IsValid() and self:CanAttackWithController(self.controller_attack_target) then local distsq = self.inst:GetDistanceSqToInst(self.controller_attack_target) if distsq <= max_range*max_range then rad = math.min(rad, math.sqrt(distsq) * .5) end end local x,y,z = me_pos:Get() local nearby_ents = TheSim:FindEntities(x,y,z, rad, must_have_attack, cant_have_attack) local target = nil local target_score = nil local target_action = nil if self.controller_attack_target then table.insert(nearby_ents, self.controller_attack_target) end for k,v in pairs(nearby_ents) do local canattack = self:CanAttackWithController(v) if canattack then local px,py,pz = v.Transform:GetWorldPosition() local ox,oy,oz = px - me_pos.x, py - me_pos.y, pz - me_pos.z local dsq = ox*ox + oy*oy +oz*oz local dist = dsq > 0 and math.sqrt(dsq) or 0 local dot = 0 if dist > 0 then local nx, ny, nz = ox/dist, oy/dist, oz/dist dot = nx*dir.x + ny*dir.y + nz*dir.z end if (dist < min_rad or dot > 0) and dist < max_range then local score = (1 + dot)* (1 / math.max(min_rad*min_rad, dsq)) if (v.components.follower and v.components.follower.leader == self.inst) or self.inst.components.combat:IsAlly(v) then score = score * .25 elseif v:HasTag("monster") then score = score * 4 end if v.components.combat.target == self.inst then score = score * 6 end if self.controller_attack_target == v then score = score * 10 end if not target or target_score < score then target = v target_score = score end end end end if not target and self.controller_target and self.controller_target:HasTag("wall") and self.controller_target.components.health and self.controller_target.components.health.currenthealth > 0 then target = self.controller_target end if target ~= self.controller_attack_target then self.controller_attack_target = target self.controllerattacktargetage = 0 end end function PlayerController:UpdateControllerInteractionTarget(dt) if self.controller_target and (not self.controller_target:IsValid() or self.controller_target:IsInLimbo() or self.controller_target:HasTag("NOCLICK")) then self.controller_target = nil end if self.placer or ( self.deployplacer and self.deploy_mode ) then self.controller_target = nil self.controllertargetage = 0 return end if self.controllertargetage then self.controllertargetage = self.controllertargetage + dt end if self.controllertargetage and self.controllertargetage < .2 then return end local heading_angle = -(self.inst.Transform:GetRotation()) local dir = Vector3(math.cos(heading_angle*DEGREES),0, math.sin(heading_angle*DEGREES)) local me_pos = Vector3(self.inst.Transform:GetWorldPosition()) local inspect_rad = .75 local min_rad = 1.5 local max_rad = 6 local rad = max_rad if self.controller_target and self.controller_target:IsValid() then local dsq = self.inst:GetDistanceSqToInst(self.controller_target) rad = math.max(min_rad, math.min(rad, math.sqrt(dsq))) end local x,y,z = me_pos:Get() local nearby_ents = TheSim:FindEntities(x,y,z, rad, nil, {"FX", "NOCLICK", "DECOR", "INLIMBO"}) if self.controller_target and not self.controller_target:IsInLimbo() then table.insert(nearby_ents, self.controller_target) --may double add.. should be harmless? end local target = nil local target_score = nil local target_action = nil local target_dist = nil for k,v in pairs(nearby_ents) do if v ~= self.inst then local px,py,pz = v.Transform:GetWorldPosition() local ox,oy,oz = px - me_pos.x, py-me_pos.y, pz-me_pos.z local dsq = ox*ox + oy*oy +oz*oz local already_target = self.controller_target == v or self.controller_attack_target == v local should_consider = dsq < min_rad*min_rad or (ox*dir.x + oy*dir.y +oz*dir.z) > 0 or already_target if dsq > max_rad*max_rad then should_consider = false end if should_consider then local dist = dsq > 0 and math.sqrt(dsq) or 0 local dot = 0 if dist > 0 then local nx, ny, nz = ox/dist, oy/dist, oz/dist dot = nx*dir.x + ny*dir.y + nz*dir.z end --keep the angle component between [0..1] local angle_component = (dot + 1)/2 --distance doesn't matter when you're really close, and then attenuates down from 1 as you get farther away local dist_component = dsq < min_rad*min_rad and 1 or (1 / (dsq/(min_rad*min_rad))) local add = 0 --for stuff that's *really* close - ie, just dropped if dsq < .25*.25 then add = 1 end local mult = 1 if v == self.controller_target and not v:HasTag("wall") then mult = 1.5--just a little hysteresis end local score = angle_component*dist_component*mult + add --print (v, angle_component, dist_component, mult, add, score) if not target_score or score > target_score or not target_action then --this is kind of expensive, so ideally we don't get here for many objects local l,r = self:GetSceneItemControllerAction(v) local action = l or r if not action then local inv_obj = self:GetCursorInventoryObject() if inv_obj then action = self:GetItemUseAction(inv_obj, v) end end if ((action or v.components.inspectable) and (not target_score or score > target_score)) --better real action --or ((action or v.components.inspectable) and ((not target or (target and not target_action)) )) --it's inspectable, so it's better than nothing --or (target and not target_action and action and not( dist > inspect_rad and target_dist < inspect_rad)) --replacing an inspectable with an actual action then target = v target_dist = dist target_score = score target_action = action end end end end end if target ~= self.controller_target then self.controller_target = target self.controllertargetage = 0 end end function PlayerController:DoDirectWalking(dt) local dir = self:GetWorldControllerVector() if dir then local ang = -math.atan2(dir.z, dir.x)/DEGREES self.inst:ClearBufferedAction() self.inst.components.locomotor:SetBufferedAction(nil) self.inst.components.locomotor:RunInDirection(ang) if not self.directwalking then self.time_direct_walking = 0 end self.directwalking = true self.time_direct_walking = self.time_direct_walking + dt if self.time_direct_walking > .2 then if not self.inst.sg:HasStateTag("attack") then self.inst.components.combat:SetTarget(nil) end end else if self.directwalking then self.inst.components.locomotor:Stop() self.directwalking = false end end end function PlayerController:WalkButtonDown() return TheInput:IsControlPressed(CONTROL_MOVE_UP) or TheInput:IsControlPressed(CONTROL_MOVE_DOWN) or TheInput:IsControlPressed(CONTROL_MOVE_LEFT) or TheInput:IsControlPressed(CONTROL_MOVE_RIGHT) end function PlayerController:DoCameraControl() --camera controls local time = GetTime() local ROT_REPEAT = .25 local ZOOM_REPEAT = .1 if TheCamera:CanControl() then if not self.lastrottime or time - self.lastrottime > ROT_REPEAT then if TheInput:IsControlPressed(CONTROL_ROTATE_LEFT) then self:RotLeft() self.lastrottime = time elseif TheInput:IsControlPressed(CONTROL_ROTATE_RIGHT) then self:RotRight() self.lastrottime = time end end if not self.lastzoomtime or time - self.lastzoomtime > ZOOM_REPEAT then if TheInput:IsControlPressed(CONTROL_ZOOM_IN) then TheCamera:ZoomIn() self.lastzoomtime = time elseif TheInput:IsControlPressed(CONTROL_ZOOM_OUT) then TheCamera:ZoomOut() self.lastzoomtime = time end end end end function PlayerController:OnLeftUp() if not self:IsEnabled() then return end if self.draggingonground then if not self:WalkButtonDown() then self.inst.components.locomotor:Stop() end self.draggingonground = false TheFrontEnd:LockFocus(false) end self.startdragtime = nil end function PlayerController:DoAction(buffaction) if buffaction then if self.inst.bufferedaction then if self.inst.bufferedaction.action == buffaction.action and self.inst.bufferedaction.target == buffaction.target then return; end end if buffaction.target then if not buffaction.target.components.highlight then buffaction.target:AddComponent("highlight") end buffaction.target.components.highlight:Flash(.2, .125, .1) end if buffaction.invobject and buffaction.invobject.components.equippable and buffaction.invobject.components.equippable.equipslot == EQUIPSLOTS.HANDS and (buffaction.action ~= ACTIONS.DROP and buffaction.action ~= ACTIONS.STORE) then if not buffaction.invobject.components.equippable.isequipped then self.inst.components.inventory:Equip(buffaction.invobject) end if self.inst.components.inventory:GetActiveItem() == buffaction.invobject then self.inst.components.inventory:SetActiveItem(nil) end end self.inst.components.locomotor:PushAction(buffaction, true) end end function PlayerController:OnLeftClick(down) if not self:UsingMouse() then return end if not down then return self:OnLeftUp() end self.startdragtime = nil if not self:IsEnabled() then return end if TheInput:GetHUDEntityUnderMouse() then self:CancelPlacement() return end if self.placer_recipe and self.placer then --do the placement if self.placer.components.placer.can_build then self.inst.components.builder:MakeRecipe(self.placer_recipe, TheInput:GetWorldPosition()) self:CancelPlacement() end return end self.inst.components.combat.target = nil if self.inst.inbed then self.inst.inbed.components.bed:StopSleeping() return end local action = self:GetLeftMouseAction() if action then self:DoAction( action ) else self:DoAction( BufferedAction(self.inst, nil, ACTIONS.WALKTO, nil, TheInput:GetWorldPosition()) ) local clicked = TheInput:GetWorldEntityUnderMouse() if not clicked then self.startdragtime = GetTime() end end end function PlayerController:OnRightClick(down) if not self:UsingMouse() then return end if not down then return end self.startdragtime = nil if self.placer_recipe then self:CancelPlacement() return end if not self:IsEnabled() then return end if TheInput:GetHUDEntityUnderMouse() then return end if not self:GetRightMouseAction() then self.inst.components.inventory:ReturnActiveItem() end if self.inst.inbed then self.inst.inbed.components.bed:StopSleeping() return end local action = self:GetRightMouseAction() if action then self:DoAction(action ) end end function PlayerController:ShakeCamera(inst, shakeType, duration, speed, maxShake, maxDist) local distSq = self.inst:GetDistanceSqToInst(inst) local t = math.max(0, math.min(1, distSq / (maxDist*maxDist) ) ) local scale = easing.outQuad(t, maxShake, -maxShake, 1) if scale > 0 then TheCamera:Shake(shakeType, duration, speed, scale) end end function PlayerController:GetLeftMouseAction( ) return self.LMBaction end function PlayerController:GetRightMouseAction( ) return self.RMBaction end function PlayerController:GetItemSelfAction(item) if not item then return end local lmb = self.inst.components.playeractionpicker:GetInventoryActions(item, false) local rmb = self.inst.components.playeractionpicker:GetInventoryActions(item, true) local action = (rmb and rmb[1]) or (lmb and lmb[1]) if action.action ~= ACTIONS.LOOKAT then return action end end function PlayerController:GetSceneItemControllerAction(item) local lmb, rmb = nil, nil local acts = self.inst.components.playeractionpicker:GetClickActions(item) if acts and #acts > 0 then local action = acts[1] if action.action ~= ACTIONS.LOOKAT and action.action ~= ACTIONS.ATTACK and action.action ~= ACTIONS.WALKTO then lmb = acts[1] end end acts = self.inst.components.playeractionpicker:GetRightClickActions(item) if acts and #acts > 0 then local action = acts[1] if action.action ~= ACTIONS.LOOKAT and action.action ~= ACTIONS.ATTACK and action.action ~= ACTIONS.WALKTO then rmb = action end end if rmb and lmb and rmb.action == lmb.action then rmb = nil end return lmb, rmb end function PlayerController:GetGroundUseAction() local position = (self.reticule and self.reticule.targetpos) or (self.terraformer and self.terraformer:GetPosition()) or (self.placer and self.placer:GetPosition()) or (self.deployplacer and self.deployplacer:GetPosition()) or self.inst:GetPosition() --local position = Vector3(self.inst.Transform:GetWorldPosition()) local tile = GetWorld().Map:GetTileAtPoint(position.x, position.y, position.z) local passable = tile ~= GROUND.IMPASSABLE if passable then local equipitem = self.inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HANDS) if equipitem then local l, r = self.inst.components.playeractionpicker:GetPointActions(position, equipitem, false), self.inst.components.playeractionpicker:GetPointActions(position, equipitem, true) l = l and l[1] r = r and r[1] if l and l.action == ACTIONS.DROP then l = nil end if l or r then if l and l.action == ACTIONS.TERRAFORM then l.distance = 2 end if r and r.action == ACTIONS.TERRAFORM then r.distance = 2 end return l, r end end end end function PlayerController:GetItemUseAction(active_item, target) if not active_item then return end target = target or self.controller_target if target then local lmb = self.inst.components.playeractionpicker:GetUseItemActions(target, active_item, false) local rmb = self.inst.components.playeractionpicker:GetUseItemActions(target, active_item, true) local act= (rmb and rmb[1]) or (lmb and lmb[1]) if act and active_item.components.tool and active_item.components.equippable and active_item.components.tool:CanDoAction(act.action)then return end if act and act.action == ACTIONS.STORE and target and target.components.inventoryitem and target.components.inventoryitem:GetGrandOwner() == self.inst then return end if act and act.action ~= ACTIONS.COMBINESTACK and act and act.action ~= ACTIONS.ATTACK then return act end end end return PlayerController
gpl-2.0
timroes/awesome
lib/wibox/layout/init.lua
6
1058
--------------------------------------------------------------------------- --- Collection of layouts that can be used in widget boxes -- -- @author Uli Schlachter -- @copyright 2010 Uli Schlachter -- @classmod wibox.layout --------------------------------------------------------------------------- local base = require("wibox.widget.base") return setmetatable({ fixed = require("wibox.layout.fixed"); align = require("wibox.layout.align"); flex = require("wibox.layout.flex"); rotate = require("wibox.layout.rotate"); manual = require("wibox.layout.manual"); margin = require("wibox.layout.margin"); mirror = require("wibox.layout.mirror"); constraint = require("wibox.layout.constraint"); scroll = require("wibox.layout.scroll"); ratio = require("wibox.layout.ratio"); stack = require("wibox.layout.stack"); grid = require("wibox.layout.grid"); }, {__call = function(_, args) return base.make_widget_declarative(args) end}) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
blueyed/awesome
lib/awful/completion.lua
1
8061
--------------------------------------------------------------------------- --- Completion module. -- -- This module store a set of function using shell to complete commands name. -- -- @author Julien Danjou &lt;julien@danjou.info&gt; -- @author Sébastien Gross &lt;seb-awesome@chezwam.org&gt; -- @copyright 2008 Julien Danjou, Sébastien Gross -- @module awful.completion --------------------------------------------------------------------------- local gfs = require("gears.filesystem") -- Grab environment we need local io = io local os = os local table = table local math = math local print = print local pairs = pairs local string = string local gears_debug = require("gears.debug") local completion = {} -- mapping of command/completion function local bashcomp_funcs = {} local bashcomp_src = "@SYSCONFDIR@/bash_completion" --- Enable programmable bash completion in awful.completion.bash at the price of -- a slight overhead. -- @param src The bash completion source file, /etc/bash_completion by default. function completion.bashcomp_load(src) if src then bashcomp_src = src end local c, err = io.popen("/usr/bin/env bash -c 'source " .. bashcomp_src .. "; complete -p'") if c then while true do local line = c:read("*line") if not line then break end -- if a bash function is used for completion, register it if line:match(".* -F .*") then bashcomp_funcs[line:gsub(".* (%S+)$","%1")] = line:gsub(".*-F +(%S+) .*$", "%1") end end c:close() else print(err) end end local function bash_escape(str) str = str:gsub(" ", "\\ ") str = str:gsub("%[", "\\[") str = str:gsub("%]", "\\]") str = str:gsub("%(", "\\(") str = str:gsub("%)", "\\)") return str end completion.default_shell = nil --- Use shell completion system to complete commands and filenames. -- @tparam string command The command line. -- @tparam number cur_pos The cursor position. -- @tparam number ncomp The element number to complete. -- @tparam[opt=based on SHELL] string shell The shell to use for completion. -- Supports "bash" and "zsh". -- @treturn string The new command. -- @treturn number The new cursor position. -- @treturn table The table with all matches. function completion.shell(command, cur_pos, ncomp, shell) local wstart = 1 local wend = 1 local words = {} local cword_index = 0 local cword_start = 0 local cword_end = 0 local i = 1 local comptype = "file" local function str_starts(str, start) return string.sub(str, 1, string.len(start)) == start end -- do nothing if we are on a letter, i.e. not at len + 1 or on a space if cur_pos ~= #command + 1 and command:sub(cur_pos, cur_pos) ~= " " then return command, cur_pos elseif #command == 0 then return command, cur_pos end while wend <= #command do wend = command:find(" ", wstart) if not wend then wend = #command + 1 end table.insert(words, command:sub(wstart, wend - 1)) if cur_pos >= wstart and cur_pos <= wend + 1 then cword_start = wstart cword_end = wend cword_index = i end wstart = wend + 1 i = i + 1 end if cword_index == 1 then comptype = "command" end local shell_cmd if not shell then if not completion.default_shell then local env_shell = os.getenv('SHELL') if not env_shell then gears_debug.print_warning('SHELL not set in environment, falling back to bash.') completion.default_shell = 'bash' elseif env_shell:match('zsh$') then completion.default_shell = 'zsh' else completion.default_shell = 'bash' end end shell = completion.default_shell end if shell == 'zsh' then if comptype == "file" then -- NOTE: ${~:-"..."} turns on GLOB_SUBST, useful for expansion of -- "~/" ($HOME). ${:-"foo"} is the string "foo" as var. shell_cmd = "/usr/bin/env zsh -c 'local -a res; res=( ${~:-" .. string.format('%q', words[cword_index]) .. "}*(N) ); " .. "print -ln -- ${res[@]}'" else -- Check commands, aliases, builtins, functions and reswords. -- Adds executables and non-empty dirs from $PWD (pwd_exe). shell_cmd = "/usr/bin/env zsh -c 'local -a res pwd_exe; ".. "pwd_exe=(*(N*:t) *(NF:t)); ".. "res=( ".. "\"${(k)commands[@]}\" \"${(k)aliases[@]}\" \"${(k)builtins[@]}\" \"${(k)functions[@]}\" ".. "\"${(k)reswords[@]}\" ".. "./${^${pwd_exe}} ".. "); ".. "print -ln -- ${(M)res[@]:#" .. string.format('%q', words[cword_index]) .. "*}'" end else if bashcomp_funcs[words[1]] then -- fairly complex command with inline bash script to get the possible completions shell_cmd = "/usr/bin/env bash -c 'source " .. bashcomp_src .. "; " .. "__print_completions() { for ((i=0;i<${#COMPREPLY[*]};i++)); do echo ${COMPREPLY[i]}; done }; " .. "COMP_WORDS=(" .. command .."); COMP_LINE=\"" .. command .. "\"; " .. "COMP_COUNT=" .. cur_pos .. "; COMP_CWORD=" .. cword_index-1 .. "; " .. bashcomp_funcs[words[1]] .. "; __print_completions'" else shell_cmd = "/usr/bin/env bash -c 'compgen -A " .. comptype .. " " .. string.format('%q', words[cword_index]) .. "'" end end local c, err = io.popen(shell_cmd .. " | sort -u") local output = {} if c then while true do local line = c:read("*line") if not line then break end if str_starts(line, "./") and gfs.is_dir(line) then line = line .. "/" end table.insert(output, bash_escape(line)) end c:close() else print(err) end -- no completion, return if #output == 0 then return command, cur_pos end -- cycle while ncomp > #output do ncomp = ncomp - #output end local str = command:sub(1, cword_start - 1) .. output[ncomp] .. command:sub(cword_end) cur_pos = cword_start + #output[ncomp] return str, cur_pos, output end --- Run a generic completion. -- For this function to run properly the awful.completion.keyword table should -- be fed up with all keywords. The completion is run against these keywords. -- @param text The current text the user had typed yet. -- @param cur_pos The current cursor position. -- @param ncomp The number of yet requested completion using current text. -- @param keywords The keywords table uised for completion. -- @return The new match, the new cursor position, the table of all matches. function completion.generic(text, cur_pos, ncomp, keywords) -- luacheck: no unused args -- The keywords table may be empty if #keywords == 0 then return text, #text + 1 end -- if no text had been typed yet, then we could start cycling around all -- keywords with out filtering and move the cursor at the end of keyword if text == nil or #text == 0 then ncomp = math.fmod(ncomp - 1, #keywords) + 1 return keywords[ncomp], #keywords[ncomp] + 2 end -- Filter out only keywords starting with text local matches = {} for _, x in pairs(keywords) do if x:sub(1, #text) == text then table.insert(matches, x) end end -- if there are no matches just leave out with the current text and position if #matches == 0 then return text, #text + 1, matches end -- cycle around all matches ncomp = math.fmod(ncomp - 1, #matches) + 1 return matches[ncomp], #matches[ncomp] + 1, matches end return completion -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
CrazyEddieTK/Zero-K
gamedata/modularcomms/weapons/disruptor.lua
5
1481
local name = "commweapon_disruptor" local weaponDef = { name = [[Disruptor Pulse Beam]], areaOfEffect = 32, beamdecay = 0.9, beamTime = 1/30, beamttl = 30, coreThickness = 0.25, craterBoost = 0, craterMult = 0, customParams = { --timeslow_preset = [[module_disruptorbeam]], timeslow_damagefactor = [[2]], light_color = [[1.88 0.63 2.5]], light_radius = 320, }, damage = { default = 165, }, explosionGenerator = [[custom:flash2purple]], fireStarter = 30, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, largeBeamLaser = true, laserFlareSize = 4.33, minIntensity = 1, noSelfDamage = true, range = 310, reloadtime = 2, rgbColor = [[0.3 0 0.4]], soundStart = [[weapon/laser/heavy_laser5]], soundStartVolume = 3, soundTrigger = true, texture1 = [[largelaser]], texture2 = [[flare]], texture3 = [[flare]], texture4 = [[smallflare]], thickness = 8, tolerance = 18000, turret = true, weaponType = [[BeamLaser]], weaponVelocity = 500, } return name, weaponDef
gpl-2.0
czfshine/Don-t-Starve
data/DLC0001/scripts/components/lootdropper.lua
1
6267
local LootDropper = Class(function(self, inst) self.inst = inst self.numrandomloot = nil self.randomloot = nil self.chancerandomloot = nil self.totalrandomweight = nil self.chanceloot = nil self.ifnotchanceloot = nil self.droppingchanceloot = false self.loot = nil self.chanceloottable = nil self.trappable = true end) LootTables = {} function SetSharedLootTable(name, table) LootTables[name] = table end function LootDropper:SetChanceLootTable(name) self.chanceloottable = name end function LootDropper:SetLoot( loots ) self.loot = loots self.chanceloot = nil self.randomloot = nil self.numrandomloot = nil end function LootDropper:AddRandomLoot( prefab, weight) if not self.randomloot then self.randomloot = {} self.totalrandomweight = 0 end table.insert(self.randomloot, {prefab=prefab,weight=weight} ) self.totalrandomweight = self.totalrandomweight + weight end function LootDropper:AddChanceLoot( prefab, chance) if not self.chanceloot then self.chanceloot = {} end table.insert(self.chanceloot, {prefab=prefab,chance=chance} ) end function LootDropper:AddIfNotChanceLoot(prefab) if not self.ifnotchanceloot then self.ifnotchanceloot = {} end table.insert(self.ifnotchanceloot, {prefab=prefab}) end function LootDropper:PickRandomLoot() if self.totalrandomweight and self.totalrandomweight > 0 and self.randomloot then local rnd = math.random()*self.totalrandomweight for k,v in pairs(self.randomloot) do rnd = rnd - v.weight if rnd <= 0 then return v.prefab end end end end function LootDropper:GenerateLoot() local loots = {} if self.numrandomloot and math.random() <= (self.chancerandomloot or 1) then for k = 1, self.numrandomloot do local loot = self:PickRandomLoot() if loot then table.insert(loots, loot) end end end if self.chanceloot then for k,v in pairs(self.chanceloot) do if math.random() < v.chance then table.insert(loots, v.prefab) self.droppingchanceloot = true end end end if self.chanceloottable then local loot_table = LootTables[self.chanceloottable] if loot_table then for i, entry in ipairs(loot_table) do local prefab = entry[1] local chance = entry[2] if math.random() <= chance then table.insert(loots, prefab) self.droppingchanceloot = true end end end end if not self.droppingchanceloot and self.ifnotchanceloot then self.inst:PushEvent("ifnotchanceloot") for k,v in pairs(self.ifnotchanceloot) do table.insert(loots, v.prefab) end end if self.loot then for k,v in ipairs(self.loot) do table.insert(loots, v) end end local recipe = GetRecipe(self.inst.prefab) if recipe then local percent = 1 if self.inst.components.finiteuses then percent = self.inst.components.finiteuses:GetPercent() end for k,v in ipairs(recipe.ingredients) do local amt = math.ceil( (v.amount * TUNING.HAMMER_LOOT_PERCENT) * percent) if self.inst:HasTag("burnt") then amt = math.ceil( (v.amount * TUNING.BURNT_HAMMER_LOOT_PERCENT) * percent) end for n = 1, amt do table.insert(loots, v.type) end end if self.inst:HasTag("burnt") and math.random() < .4 then table.insert(loots, "charcoal") -- Add charcoal to loot for burnt structures end end return loots end function LootDropper:SpawnLootPrefab(lootprefab, pt) if lootprefab then local loot = SpawnPrefab(lootprefab) if loot then if not pt then pt = Point(self.inst.Transform:GetWorldPosition()) end loot.Transform:SetPosition(pt.x,pt.y,pt.z) local targetMoisture = 0 if self.inst.components.moisturelistener then targetMoisture = self.inst.components.moisturelistener:GetMoisture() elseif self.inst.components.moisture then targetMoisture = self.inst.components.moisture:GetMoisture() else targetMoisture = GetWorld().components.moisturemanager:GetWorldMoisture() end loot.targetMoisture = targetMoisture loot:DoTaskInTime(2*FRAMES, function() if loot.components.moisturelistener then loot.components.moisturelistener.moisture = loot.targetMoisture loot.targetMoisture = nil loot.components.moisturelistener:DoUpdate() end end) if loot.Physics then local angle = math.random()*2*PI local speed = math.random() loot.Physics:SetVel(speed*math.cos(angle), GetRandomWithVariance(8, 4), speed*math.sin(angle)) if loot and loot.Physics and self.inst and self.inst.Physics then pt = pt + Vector3(math.cos(angle), 0, math.sin(angle))*((loot.Physics:GetRadius() or 1) + (self.inst.Physics:GetRadius() or 1)) loot.Transform:SetPosition(pt.x,pt.y,pt.z) end loot:DoTaskInTime(1, function() if not (loot.components.inventoryitem and loot.components.inventoryitem:IsHeld()) then if not loot:IsOnValidGround() then local fx = SpawnPrefab("splash_ocean") local pos = loot:GetPosition() fx.Transform:SetPosition(pos.x, pos.y, pos.z) --PlayFX(loot:GetPosition(), "splash", "splash_ocean", "idle") if loot:HasTag("irreplaceable") then loot.Transform:SetPosition(GetPlayer().Transform:GetWorldPosition()) else loot:Remove() end end end end) end return loot end end end function LootDropper:DropLoot(pt) local prefabs = self:GenerateLoot() if not self.inst.components.fueled and self.inst.components.burnable and self.inst.components.burnable:IsBurning() then for k,v in pairs(prefabs) do local cookedAfter = v.."_cooked" local cookedBefore = "cooked"..v if PrefabExists(cookedAfter) then prefabs[k] = cookedAfter elseif PrefabExists(cookedBefore) then prefabs[k] = cookedBefore else prefabs[k] = "ash" end end end for k,v in pairs(prefabs) do self:SpawnLootPrefab(v, pt) end end return LootDropper
gpl-2.0
creationix/ts-git
deps/coro-channel.lua
1
3691
exports.name = "creationix/coro-channel" exports.version = "1.3.0" exports.homepage = "https://github.com/luvit/lit/blob/master/deps/coro-channel.lua" exports.description = "An adapter for wrapping uv streams as coro-streams and chaining filters." exports.tags = {"coro", "adapter"} exports.license = "MIT" exports.author = { name = "Tim Caswell" } local function wrapRead(socket, decode) local paused = true local queue = {} local tindex = 0 local dindex = 0 local function dispatch(data) if tindex > dindex then local thread = queue[dindex] queue[dindex] = nil dindex = dindex + 1 assert(coroutine.resume(thread, unpack(data))) else queue[dindex] = data dindex = dindex + 1 if not paused then paused = true assert(socket:read_stop()) end end end local buffer = "" local function onRead(err, chunk) if not decode or not chunk or err then return dispatch(err and {nil, err} or {chunk}) end buffer = buffer .. chunk while true do local item, extra = decode(buffer) if not extra then return end buffer = extra dispatch({item}) end end return function () if dindex > tindex then local data = queue[tindex] queue[tindex] = nil tindex = tindex + 1 return unpack(data) end if paused then paused = false assert(socket:read_start(onRead)) end queue[tindex] = coroutine.running() tindex = tindex + 1 return coroutine.yield() end, function (newDecode) decode = newDecode end end local function wrapWrite(socket, encode) local function wait() local thread = coroutine.running() return function (err) assert(coroutine.resume(thread, err)) end end local function shutdown() socket:shutdown(wait()) coroutine.yield() if not socket:is_closing() then socket:close() end end return function (chunk) if chunk == nil then return shutdown() end if encode then chunk = encode(chunk) end assert(socket:write(chunk, wait())) local err = coroutine.yield() return not err, err end, function (newEncode) encode = newEncode end end exports.wrapRead = wrapRead exports.wrapWrite = wrapWrite -- Given a raw uv_stream_t userdata, return coro-friendly read/write functions. function exports.wrapStream(socket, encode, decode) return wrapRead(socket, encode), wrapWrite(socket, decode) end function exports.chain(...) local args = {...} local nargs = select("#", ...) return function (read, write) local threads = {} -- coroutine thread for each item local waiting = {} -- flag when waiting to pull from upstream local boxes = {} -- storage when waiting to write to downstream for i = 1, nargs do threads[i] = coroutine.create(args[i]) waiting[i] = false local r, w if i == 1 then r = read else function r() local j = i - 1 if boxes[j] then local data = boxes[j] boxes[j] = nil assert(coroutine.resume(threads[j])) return unpack(data) else waiting[i] = true return coroutine.yield() end end end if i == nargs then w = write else function w(...) local j = i + 1 if waiting[j] then waiting[j] = false assert(coroutine.resume(threads[j], ...)) else boxes[i] = {...} coroutine.yield() end end end assert(coroutine.resume(threads[i], r, w)) end end end
mit
Rynoxx/gmod-addon-collection
team-gate/lua/weapons/weapon_team_gate_bypasser.lua
1
4010
--[[ Allows creation of walls/gates that are only certain players can go through. Copyright (C) 2017 Rynoxx This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] SWEP.PrintName = "Gate Bypasser" SWEP.Author = "Rynoxx" SWEP.Instructions = "Left click to start attempting to bypass the teamgate you're looking at.\nThe exceptions being gates where the bypassing has been disabled by an admin or if bypassing is disabled in the config." SWEP.Purpose = "Bypassing team gates" SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Primary.ClipSize = -1 SWEP.Primary.DefaultClip = -1 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "none" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" SWEP.Weight = 5 SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = true SWEP.Slot = 5 SWEP.SlotPos = 2 SWEP.DrawAmmo = false SWEP.DrawCrosshair = true SWEP.ViewModel = "" SWEP.WorldModel = "" SWEP.Dots = "" function SWEP:Deploy() if !RynGateConfig.SWEPBypassGates then self.Owner:ChatPrint("Gate bypassing has been disabled in the server configuration. This weapon is useless...") end end function SWEP:PrimaryAttack() --if CLIENT then return end local tr = self.Owner:GetEyeTrace() local gate = tr.Entity local hitPos = tr.HitPos if IsValid(gate) and gate:GetClass() == ent_gate_ClassName and RynGateConfig.SWEPBypassGates and self.Owner:EyePos():Distance(hitPos) <= RynGateConfig.SWEPBypassRange then if gate:GetIsServerOwned() and !RynGateConfig.SWEPBypassServerGates then self.Owner:ChatPrint("You can't bypass gates owned by the server with this weapon.") return end self.Owner:SetNWBool("RynGates_Bypassing", true) self.Owner:SetNWInt("RynGates_BypassStarted", CurTime()) self.Owner:SetNWEntity("RynGates_BypassEntity", gate) local ply = self.Owner timer.Simple(RynGateConfig.SWEPBypassWaitTime, function() if IsValid(ply) and ply:GetNWBool("RynGates_Bypassing", false) then ply:SetNWBool("RynGates_Bypassing", false) self.Owner:SetNWInt("RynGates_BypassFinished", CurTime()) end end) end end function SWEP:SecondaryAttack() end function SWEP:Think() if SERVER and IsValid(self.Owner) then if self.Owner:GetNWBool("RynGates_Bypassing", false) then if self.Owner:GetEyeTrace().Entity != self.Owner:GetNWEntity("RynGates_BypassEntity") then self.Owner:SetNWBool("RynGates_Bypassing", false) end end end end local draw = draw function SWEP:DrawHUD() if self.Owner:GetNWBool("RynGates_Bypassing", false) then local bypassStarted = self.Owner:GetNWInt("RynGates_BypassStarted", CurTime()) local timeLeft = CurTime() - bypassStarted local scrw, scrh = ScrW(), ScrH() local w, h = scrw * 0.2, scrh * 0.1 local offset = 4 draw.RoundedBox(6, scrw/2 - w/2 - offset/2, scrh/2 - h/2 - offset/2, w + offset, h + offset, Color(0, 0, 0, 200)) draw.RoundedBox(6, scrw/2 - w/2, scrh/2 - h/2, w * math.Clamp(timeLeft/RynGateConfig.SWEPBypassWaitTime, 0, 1), h, Color(0, 250, 0, 200)) if string.len(self.Dots) > 3 then self.Dots = "" end if (self.lastTime or 0) != os.time() then self.Dots = self.Dots .. "." self.lastTime = os.time() end draw.SimpleText("Bypassing" .. self.Dots .. " " .. math.floor(timeLeft) .. "/" .. RynGateConfig.SWEPBypassWaitTime, "BudgetLabel", scrw/2, scrh/2, color_white, TEXT_ALIGN_CENTER) end end
agpl-3.0
IRO-TEAM/iro-antispam
plugins/spammer.lua
1
15613
do function run(msg, matches) local tex = matches[1] local sps = matches[2] local sp = '' for i=1, tex, 1 do sp = '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'..sps..'\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'..sp i = i + 1 end return sp end end return { patterns = { "^[/!#]([Ii]ro) (.*) (.*)$" }, run = run, privileged = true, }
gpl-2.0
CrazyEddieTK/Zero-K
LuaRules/Gadgets/dbg_ceg_spawner.lua
13
1392
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if not gadgetHandler:IsSyncedCode() then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "CEG Spawner", desc = 'Spawn CEGs', author = "CarRepairer", date = "2010-11-07", license = "GNU GPL, v2 or later", layer = 0, enabled = true, } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:RecvLuaMsg(msg, playerID) if not Spring.IsCheatingEnabled() then return end local ceg_msg_prefix = "*" local ceg_msg = (msg:find(ceg_msg_prefix,1,true)) if ceg_msg then msg = msg:sub(2) msg = Spring.Utilities.ExplodeString('|', msg) Spring.Echo('Spawning CEG', msg[1] ) Spring.SpawnCEG( msg[1], --cegname msg[2], msg[3], msg[4], --pos msg[5], msg[6], msg[7], --dir msg[8] --radius ) end end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
czfshine/Don-t-Starve
data/scripts/map/static_layouts/sanity_wormhole_1.lua
1
5811
return { version = "1.1", luaversion = "5.1", orientation = "orthogonal", width = 16, height = 16, tilewidth = 16, tileheight = 16, properties = {}, tilesets = { { name = "tiles", firstgid = 1, tilewidth = 64, tileheight = 64, spacing = 0, margin = 0, image = "../../../../../Users/Alia McCutcheon/Documents/tiled/tiles.png", imagewidth = 512, imageheight = 128, properties = {}, tiles = {} } }, layers = { { type = "tilelayer", name = "BG_TILES", x = 0, y = 0, width = 16, height = 16, visible = true, opacity = 1, properties = {}, encoding = "lua", data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { type = "objectgroup", name = "FG_OBJECTS", visible = true, opacity = 1, properties = {}, objects = { { name = "", type = "sanityrock", shape = "rectangle", x = 32, y = 48, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 32, y = 96, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 32, y = 144, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 32, y = 192, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 64, y = 240, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 112, y = 240, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 160, y = 240, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 208, y = 240, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 224, y = 192, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 224, y = 144, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 224, y = 96, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 224, y = 48, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 160, y = 16, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 64, y = 16, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 208, y = 16, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "sanityrock", shape = "rectangle", x = 112, y = 16, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "wormhole", shape = "rectangle", x = 128, y = 128, width = 0, height = 0, visible = true, properties = {} } } } } }
gpl-2.0
czfshine/Don-t-Starve
data/scripts/prefabs/woodie.lua
1
9318
local MakePlayerCharacter = require "prefabs/player_common" local Badge = require "widgets/badge" local easing = require "easing" require "stategraphs/SGwilson" require "stategraphs/SGwerebeaver" local prefabs= { "lucy", } local assets = { Asset("ANIM", "anim/woodie.zip"), Asset("SOUND", "sound/woodie.fsb"), Asset("ANIM", "anim/werebeaver_build.zip"), Asset("ANIM", "anim/werebeaver_basic.zip"), Asset("ANIM", "anim/player_woodie.zip"), Asset("ATLAS", "images/woodie.xml"), Asset("IMAGE", "images/woodie.tex"), Asset("IMAGE", "images/colour_cubes/beaver_vision_cc.tex"), } local function BeaverActionButton(inst) local action_target = FindEntity(inst, 6, function(guy) return (guy.components.edible and inst.components.eater:CanEat(guy)) or (guy.components.workable and inst.components.worker:CanDoAction(guy.components.workable.action)) end) if not inst.sg:HasStateTag("busy") and action_target then if (action_target.components.edible and inst.components.eater:CanEat(action_target)) then return BufferedAction(inst, action_target, ACTIONS.EAT) else return BufferedAction(inst, action_target, action_target.components.workable.action) end end end local function LeftClickPicker(inst, target_ent, pos) if inst.components.combat:CanTarget(target_ent) then return inst.components.playeractionpicker:SortActionList({ACTIONS.ATTACK}, target_ent, nil) end if target_ent and target_ent.components.edible and inst.components.eater:CanEat(target_ent) then return inst.components.playeractionpicker:SortActionList({ACTIONS.EAT}, target_ent, nil) end if target_ent and target_ent.components.workable and inst.components.worker:CanDoAction(target_ent.components.workable.action) then return inst.components.playeractionpicker:SortActionList({target_ent.components.workable.action}, target_ent, nil) end end local function RightClickPicker(inst, target_ent, pos) return {} end local BeaverBadge = Class(Badge, function(self, owner) Badge._ctor(self, "beaver_meter", owner) end) local function onbeavereat(inst, data) if data.food and data.food.components.edible.woodiness and inst.components.beaverness then inst.components.beaverness:DoDelta(data.food.components.edible.woodiness) end end local function beaveractionstring(inst, action) return STRINGS.ACTIONS.GNAW end local function beaverhurt(inst, delta) if delta < 0 then inst.sg:PushEvent("attacked") inst.components.beaverness:DoDelta(delta*.25) TheFrontEnd:GetSound():PlaySound("dontstarve/HUD/health_down") inst.HUD.controls.beaverbadge:PulseRed() if inst.HUD.bloodover then inst.HUD.bloodover:Flash() end end end local function SetHUDState(inst) if inst.HUD then if inst.components.beaverness:IsBeaver() and not inst.HUD.controls.beaverbadge then inst.HUD.controls.beaverbadge = GetPlayer().HUD.controls.sidepanel:AddChild(BeaverBadge(inst)) inst.HUD.controls.beaverbadge:SetPosition(0,-100,0) inst.HUD.controls.beaverbadge:SetPercent(1) inst.HUD.controls.beaverbadge.inst:ListenForEvent("beavernessdelta", function(_, data) inst.HUD.controls.beaverbadge:SetPercent(inst.components.beaverness:GetPercent(), inst.components.beaverness.max) if not data.overtime then if data.newpercent > data.oldpercent then inst.HUD.controls.beaverbadge:PulseGreen() TheFrontEnd:GetSound():PlaySound("dontstarve/HUD/health_up") elseif data.newpercent < data.oldpercent then TheFrontEnd:GetSound():PlaySound("dontstarve/HUD/health_down") inst.HUD.controls.beaverbadge:PulseRed() end end end, inst) inst.HUD.controls.crafttabs:Hide() inst.HUD.controls.inv:Hide() inst.HUD.controls.status:Hide() inst.HUD.controls.mapcontrols.minimapBtn:Hide() inst.HUD.beaverOL = inst.HUD.under_root:AddChild(Image("images/woodie.xml", "beaver_vision_OL.tex")) inst.HUD.beaverOL:SetVRegPoint(ANCHOR_MIDDLE) inst.HUD.beaverOL:SetHRegPoint(ANCHOR_MIDDLE) inst.HUD.beaverOL:SetVAnchor(ANCHOR_MIDDLE) inst.HUD.beaverOL:SetHAnchor(ANCHOR_MIDDLE) inst.HUD.beaverOL:SetScaleMode(SCALEMODE_FILLSCREEN) inst.HUD.beaverOL:SetClickable(false) elseif not inst.components.beaverness:IsBeaver() and inst.HUD.controls.beaverbadge then if inst.HUD.controls.beaverbadge then inst.HUD.controls.beaverbadge:Kill() inst.HUD.controls.beaverbadge = nil end if inst.HUD.beaverOL then inst.HUD.beaverOL:Kill() inst.HUD.beaverOL = nil end inst.HUD.controls.crafttabs:Show() inst.HUD.controls.inv:Show() inst.HUD.controls.status:Show() inst.HUD.controls.mapcontrols.minimapBtn:Show() end end end local function BecomeWoodie(inst) inst.beaver = false inst.ActionStringOverride = nil inst.AnimState:SetBank("wilson") inst.AnimState:SetBuild("woodie") inst:SetStateGraph("SGwilson") inst:RemoveTag("beaver") inst:RemoveComponent("worker") inst.components.talker:StopIgnoringAll() inst.components.locomotor.runspeed = TUNING.WILSON_RUN_SPEED inst.components.combat:SetDefaultDamage(TUNING.UNARMED_DAMAGE) inst.components.playercontroller.actionbuttonoverride = nil inst.components.playeractionpicker.leftclickoverride = nil inst.components.playeractionpicker.rightclickoverride = nil inst.components.eater:SetOmnivore() inst.components.hunger:Resume() inst.components.sanity.ignore = false inst.components.health.redirect = nil inst.components.beaverness:StartTimeEffect(2, -1) inst:RemoveEventCallback("oneatsomething", onbeavereat) inst.Light:Enable(false) inst.components.dynamicmusic:Enable() inst.SoundEmitter:KillSound("beavermusic") GetWorld().components.colourcubemanager:SetOverrideColourCube(nil) inst.components.temperature:SetTemp(nil) inst:DoTaskInTime(0, function() SetHUDState(inst) end) end local function onworked(inst, data) if not inst.components.beaverness:IsBeaver() and data.target and data.target.components.workable and data.target.components.workable.action == ACTIONS.CHOP then inst.components.beaverness:DoDelta(3) --local dist = easing.linear(inst.components.beaverness:GetPercent(), 0, .1, 1) --TheCamera:Shake("SIDE", .15, .05, dist*.66) --else --TheCamera:Shake("SIDE", .15, .05, .1) end end local function BecomeBeaver(inst) inst.beaver = true inst.ActionStringOverride = beaveractionstring inst:AddTag("beaver") inst.AnimState:SetBuild("werebeaver_build") inst.AnimState:SetBank("werebeaver") inst:SetStateGraph("SGwerebeaver") inst.components.talker:IgnoreAll() inst.components.combat:SetDefaultDamage(TUNING.BEAVER_DAMAGE) inst.components.locomotor.runspeed = TUNING.WILSON_RUN_SPEED*1.1 inst.components.inventory:DropEverything() inst.components.playercontroller.actionbuttonoverride = BeaverActionButton inst.components.playeractionpicker.leftclickoverride = LeftClickPicker inst.components.playeractionpicker.rightclickoverride = RightClickPicker inst.components.eater:SetBeaver() inst:AddComponent("worker") inst.components.worker:SetAction(ACTIONS.DIG, 1) inst.components.worker:SetAction(ACTIONS.CHOP, 4) inst.components.worker:SetAction(ACTIONS.MINE, 1) inst.components.worker:SetAction(ACTIONS.HAMMER, 1) inst:ListenForEvent("oneatsomething", onbeavereat) inst.components.sanity:SetPercent(1) inst.components.health:SetPercent(1) inst.components.hunger:SetPercent(1) inst.components.hunger:Pause() inst.components.sanity.ignore = true inst.components.health.redirect = beaverhurt inst.components.health.redirect_percent = .25 local dt = 3 local BEAVER_DRAIN_TIME = 120 inst.components.beaverness:StartTimeEffect(dt, (-100/BEAVER_DRAIN_TIME)*dt) inst.Light:Enable(true) inst.components.dynamicmusic:Disable() inst.SoundEmitter:PlaySound("dontstarve/music/music_hoedown", "beavermusic") GetWorld().components.colourcubemanager:SetOverrideColourCube("images/colour_cubes/beaver_vision_cc.tex") inst.components.temperature:SetTemp(20) inst:DoTaskInTime(0, function() SetHUDState(inst) end) end local fn = function(inst) --inst:ListenForEvent("transform", function() if inst.beaver then BecomeWoodie(inst) else BecomeBeaver(inst) end end) inst:AddComponent("beaverness") inst.components.beaverness.makeperson = BecomeWoodie inst.components.beaverness.makebeaver = BecomeBeaver inst.components.beaverness.onbecomeperson = function() inst:PushEvent("transform_person") end inst.components.beaverness.onbecomebeaver = function() inst:PushEvent("transform_werebeaver") --BecomeBeaver(inst) end inst.entity:AddLight() inst.Light:Enable(false) inst.Light:SetRadius(5) inst.Light:SetFalloff(.5) inst.Light:SetIntensity(.6) inst.Light:SetColour(245/255,40/255,0/255) inst:ListenForEvent("working", onworked) inst.components.inventory:GuaranteeItems(prefabs) BecomeWoodie(inst) inst:ListenForEvent("nighttime", function(global, data) if GetClock():GetMoonPhase() == "full" and not inst.components.beaverness:IsBeaver() and not inst.components.beaverness.ignoremoon then if not inst.components.beaverness.doing_transform then inst.components.beaverness:SetPercent(1) end end end, GetWorld()) end return MakePlayerCharacter("woodie", prefabs, assets, fn, prefabs)
gpl-2.0
starkos/premake-core
modules/gmake/gmake_utility.lua
15
1409
-- -- make_utility.lua -- Generate a C/C++ project makefile. -- Copyright (c) 2002-2014 Jason Perkins and the Premake project -- local p = premake p.make.utility = {} local make = p.make local utility = p.make.utility local project = p.project local config = p.config local fileconfig = p.fileconfig --- -- Add namespace for element definition lists for p.callarray() --- utility.elements = {} -- -- Generate a GNU make utility project makefile. -- utility.elements.makefile = { "header", "phonyRules", "utilityConfigs", "utilityTargetRules" } function make.utility.generate(prj) p.eol("\n") p.callarray(make, utility.elements.makefile, prj) end utility.elements.configuration = { "target", "preBuildCmds", "postBuildCmds", } function make.utilityConfigs(prj) for cfg in project.eachconfig(prj) do -- identify the toolset used by this configurations (would be nicer if -- this were computed and stored with the configuration up front) local toolset = p.tools[cfg.toolset or "gcc"] if not toolset then error("Invalid toolset '" .. cfg.toolset .. "'") end _x('ifeq ($(config),%s)', cfg.shortname) p.callarray(make, utility.elements.configuration, cfg, toolset) _p('endif') _p('') end end function make.utilityTargetRules(prj) _p('$(TARGET):') _p('\t$(PREBUILDCMDS)') _p('\t$(POSTBUILDCMDS)') _p('') end
bsd-3-clause
andywingo/snabbswitch
lib/ljsyscall/syscall/bsd/types.lua
24
9241
-- BSD shared types local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local function init(c, types) local abi = require "syscall.abi" local t, pt, s, ctypes = types.t, types.pt, types.s, types.ctypes local ffi = require "ffi" local bit = require "syscall.bit" local h = require "syscall.helpers" local addtype, addtype_var, addtype_fn, addraw2 = h.addtype, h.addtype_var, h.addtype_fn, h.addraw2 local ptt, reviter, mktype, istype, lenfn, lenmt, getfd, newfn = h.ptt, h.reviter, h.mktype, h.istype, h.lenfn, h.lenmt, h.getfd, h.newfn local ntohl, ntohl, ntohs, htons = h.ntohl, h.ntohl, h.ntohs, h.htons local mt = {} -- metatables local addtypes = { } local addstructs = { } for k, v in pairs(addtypes) do addtype(types, k, v) end for k, v in pairs(addstructs) do addtype(types, k, v, lenmt) end mt.sockaddr = { index = { len = function(sa) return sa.sa_len end, family = function(sa) return sa.sa_family end, }, newindex = { len = function(sa, v) sa.sa_len = v end, }, } addtype(types, "sockaddr", "struct sockaddr", mt.sockaddr) -- cast socket address to actual type based on family, defined later local samap_pt = {} mt.sockaddr_storage = { index = { len = function(sa) return sa.ss_len end, family = function(sa) return sa.ss_family end, }, newindex = { len = function(sa, v) sa.ss_len = v end, family = function(sa, v) sa.ss_family = c.AF[v] end, }, __index = function(sa, k) if mt.sockaddr_storage.index[k] then return mt.sockaddr_storage.index[k](sa) end local st = samap_pt[sa.ss_family] if st then local cs = st(sa) return cs[k] end error("invalid index " .. k) end, __newindex = function(sa, k, v) if mt.sockaddr_storage.newindex[k] then mt.sockaddr_storage.newindex[k](sa, v) return end local st = samap_pt[sa.ss_family] if st then local cs = st(sa) cs[k] = v return end error("invalid index " .. k) end, __new = function(tp, init) local ss = ffi.new(tp) local family if init and init.family then family = c.AF[init.family] end local st if family then st = samap_pt[family] ss.ss_family = family init.family = nil end if st then local cs = st(ss) for k, v in pairs(init) do cs[k] = v end end ss.len = #ss return ss end, -- netbsd likes to see the correct size when it gets a sockaddr; Linux was ok with a longer one __len = function(sa) if samap_pt[sa.family] then local cs = samap_pt[sa.family](sa) return #cs else return s.sockaddr_storage end end, } -- experiment, see if we can use this as generic type, to avoid allocations. addtype(types, "sockaddr_storage", "struct sockaddr_storage", mt.sockaddr_storage) mt.sockaddr_in = { index = { len = function(sa) return sa.sin_len end, family = function(sa) return sa.sin_family end, port = function(sa) return ntohs(sa.sin_port) end, addr = function(sa) return sa.sin_addr end, }, newindex = { len = function(sa, v) sa.sin_len = v end, family = function(sa, v) sa.sin_family = v end, port = function(sa, v) sa.sin_port = htons(v) end, addr = function(sa, v) sa.sin_addr = mktype(t.in_addr, v) end, }, __new = function(tp, port, addr) if type(port) == "table" then port.len = s.sockaddr_in return newfn(tp, port) end return newfn(tp, {len = s.sockaddr_in, family = c.AF.INET, port = port, addr = addr}) end, __len = function(tp) return s.sockaddr_in end, } addtype(types, "sockaddr_in", "struct sockaddr_in", mt.sockaddr_in) mt.sockaddr_in6 = { index = { len = function(sa) return sa.sin6_len end, family = function(sa) return sa.sin6_family end, port = function(sa) return ntohs(sa.sin6_port) end, addr = function(sa) return sa.sin6_addr end, }, newindex = { len = function(sa, v) sa.sin6_len = v end, family = function(sa, v) sa.sin6_family = v end, port = function(sa, v) sa.sin6_port = htons(v) end, addr = function(sa, v) sa.sin6_addr = mktype(t.in6_addr, v) end, flowinfo = function(sa, v) sa.sin6_flowinfo = v end, scope_id = function(sa, v) sa.sin6_scope_id = v end, }, __new = function(tp, port, addr, flowinfo, scope_id) -- reordered initialisers. if type(port) == "table" then port.len = s.sockaddr_in6 return newfn(tp, port) end return newfn(tp, {len = s.sockaddr_in6, family = c.AF.INET6, port = port, addr = addr, flowinfo = flowinfo, scope_id = scope_id}) end, __len = function(tp) return s.sockaddr_in6 end, } addtype(types, "sockaddr_in6", "struct sockaddr_in6", mt.sockaddr_in6) mt.sockaddr_un = { index = { family = function(sa) return sa.sun_family end, path = function(sa) return ffi.string(sa.sun_path) end, }, newindex = { family = function(sa, v) sa.sun_family = v end, path = function(sa, v) ffi.copy(sa.sun_path, v) end, }, __new = function(tp, path) return newfn(tp, {family = c.AF.UNIX, path = path, sun_len = s.sockaddr_un}) end, __len = function(sa) return 2 + #sa.path end, } addtype(types, "sockaddr_un", "struct sockaddr_un", mt.sockaddr_un) function t.sa(addr, addrlen) return addr end -- non Linux is trivial, Linux has odd unix handling -- TODO need to check in detail all this as ported from Linux and may differ mt.termios = { makeraw = function(termios) termios.c_iflag = bit.band(termios.iflag, bit.bnot(c.IFLAG["IGNBRK,BRKINT,PARMRK,ISTRIP,INLCR,IGNCR,ICRNL,IXON"])) termios.c_oflag = bit.band(termios.oflag, bit.bnot(c.OFLAG["OPOST"])) termios.c_lflag = bit.band(termios.lflag, bit.bnot(c.LFLAG["ECHO,ECHONL,ICANON,ISIG,IEXTEN"])) termios.c_cflag = bit.bor(bit.band(termios.cflag, bit.bnot(c.CFLAG["CSIZE,PARENB"])), c.CFLAG.CS8) termios.c_cc[c.CC.VMIN] = 1 termios.c_cc[c.CC.VTIME] = 0 return true end, index = { iflag = function(termios) return tonumber(termios.c_iflag) end, oflag = function(termios) return tonumber(termios.c_oflag) end, cflag = function(termios) return tonumber(termios.c_cflag) end, lflag = function(termios) return tonumber(termios.c_lflag) end, makeraw = function(termios) return mt.termios.makeraw end, ispeed = function(termios) return termios.c_ispeed end, ospeed = function(termios) return termios.c_ospeed end, }, newindex = { iflag = function(termios, v) termios.c_iflag = c.IFLAG(v) end, oflag = function(termios, v) termios.c_oflag = c.OFLAG(v) end, cflag = function(termios, v) termios.c_cflag = c.CFLAG(v) end, lflag = function(termios, v) termios.c_lflag = c.LFLAG(v) end, ispeed = function(termios, v) termios.c_ispeed = v end, ospeed = function(termios, v) termios.c_ospeed = v end, speed = function(termios, v) termios.c_ispeed = v termios.c_ospeed = v end, }, } for k, i in pairs(c.CC) do mt.termios.index[k] = function(termios) return termios.c_cc[i] end mt.termios.newindex[k] = function(termios, v) termios.c_cc[i] = v end end addtype(types, "termios", "struct termios", mt.termios) mt.kevent = { index = { size = function(kev) return tonumber(kev.data) end, fd = function(kev) return tonumber(kev.ident) end, signal = function(kev) return tonumber(kev.ident) end, }, newindex = { fd = function(kev, v) kev.ident = t.uintptr(getfd(v)) end, signal = function(kev, v) kev.ident = c.SIG[v] end, -- due to naming, use 'set' names TODO better naming scheme reads oddly as not a function setflags = function(kev, v) kev.flags = c.EV[v] end, setfilter = function(kev, v) kev.filter = c.EVFILT[v] end, }, __new = function(tp, tab) if type(tab) == "table" then tab.flags = c.EV[tab.flags] tab.filter = c.EVFILT[tab.filter] -- TODO this should also support extra ones via ioctl see man page tab.fflags = c.NOTE[tab.fflags] end local obj = ffi.new(tp) for k, v in pairs(tab or {}) do obj[k] = v end return obj end, } for k, v in pairs(c.NOTE) do mt.kevent.index[k] = function(kev) return bit.band(kev.fflags, v) ~= 0 end end for _, k in pairs{"FLAG1", "EOF", "ERROR"} do mt.kevent.index[k] = function(kev) return bit.band(kev.flags, c.EV[k]) ~= 0 end end addtype(types, "kevent", "struct kevent", mt.kevent) mt.kevents = { __len = function(kk) return kk.count end, __new = function(tp, ks) if type(ks) == 'number' then return ffi.new(tp, ks, ks) end local count = #ks local kks = ffi.new(tp, count, count) for n = 1, count do -- TODO ideally we use ipairs on both arrays/tables local v = mktype(t.kevent, ks[n]) kks.kev[n - 1] = v end return kks end, __ipairs = function(kk) return reviter, kk.kev, kk.count end } addtype_var(types, "kevents", "struct {int count; struct kevent kev[?];}", mt.kevents) -- this is declared above samap_pt = { [c.AF.UNIX] = pt.sockaddr_un, [c.AF.INET] = pt.sockaddr_in, [c.AF.INET6] = pt.sockaddr_in6, } return types end return {init = init}
apache-2.0
IRO-TEAM/iro-antispam
bot/utils.lua
473
24167
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")() JSON = (loadfile "./libs/dkjson.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 --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
unusualcrow/redead_reloaded
entities/effects/fire_tracer/init.lua
2
2070
EFFECT.Mat = Material( "trails/plasma" ) EFFECT.Sprite = Material( "effects/yellowflare" ) function EFFECT:Init( data ) self.Position = data:GetStart() self.WeaponEnt = data:GetEntity() self.Attachment = data:GetAttachment() self.StartPos = self:GetTracerShootPos( self.Position, self.WeaponEnt, self.Attachment ) self.EndPos = data:GetOrigin() local dir = self.StartPos - self.EndPos dir:Normalize() self.Dir = dir self.Entity:SetRenderBoundsWS( self.StartPos, self.EndPos ) self.Alpha = 100 self.Color = Color( 250, 150, 50, self.Alpha ) local dlight = DynamicLight( self:EntIndex() ) if dlight then dlight.Pos = self.StartPos dlight.r = 255 dlight.g = 150 dlight.b = 50 dlight.Brightness = 3 dlight.Decay = 256 dlight.size = 256 * math.Rand( 0.5, 1.0 ) dlight.DieTime = CurTime() + 5 end end function EFFECT:Think( ) self.Entity:SetRenderBoundsWS( self.StartPos, self.EndPos ) self.Alpha = self.Alpha - FrameTime() * 200 self.Color = Color( 250, 150, 50, self.Alpha ) return self.Alpha > 0 end function EFFECT:Render( ) if self.Alpha < 1 then return end --[[self.Length = ( self.StartPos - self.EndPos ):Length() render.SetMaterial( self.Mat ) render.DrawBeam( self.StartPos, self.EndPos, ( 100 / self.Alpha ) * 0.5 + 0.5, 0, 0, self.Color )]] if ( self.Alpha < 1 ) then return end self.Length = (self.StartPos - self.EndPos):Length() local texcoord = CurTime() * -0.2 for i = 1, 10 do render.SetMaterial( self.Mat ) texcoord = texcoord + i * 0.05 * texcoord render.DrawBeam( self.StartPos, self.EndPos, i * self.Alpha * 0.03, texcoord, texcoord + (self.Length / (128 + self.Alpha)), self.Color ) render.SetMaterial( self.Sprite ) render.DrawSprite( self.StartPos + self.Dir * i, i * 5, i * 5, Color( self.Color.r, self.Color.g, self.Color.b, self.Alpha ) ) render.DrawSprite( self.EndPos, i * 5, i * 5, Color( self.Color.r, self.Color.g, self.Color.b, self.Alpha ) ) end end
mit
AllAboutEE/nodemcu-firmware
lua_modules/redis/redis.lua
86
2621
------------------------------------------------------------------------------ -- Redis client module -- -- LICENCE: http://opensource.org/licenses/MIT -- Vladimir Dronnikov <dronnikov@gmail.com> -- -- Example: -- local redis = dofile("redis.lua").connect(host, port) -- redis:publish("chan1", foo") -- redis:subscribe("chan1", function(channel, msg) print(channel, msg) end) ------------------------------------------------------------------------------ local M do -- const local REDIS_PORT = 6379 -- cache local pairs, tonumber = pairs, tonumber -- local publish = function(self, chn, s) self._fd:send(("*3\r\n$7\r\npublish\r\n$%d\r\n%s\r\n$%d\r\n%s\r\n"):format( #chn, chn, #s, s )) -- TODO: confirmation? then queue of answers needed end local subscribe = function(self, chn, handler) -- TODO: subscription to all channels, with single handler self._fd:send(("*2\r\n$9\r\nsubscribe\r\n$%d\r\n%s\r\n"):format( #chn, chn )) self._handlers[chn] = handler -- TODO: confirmation? then queue of answers needed end local unsubscribe = function(self, chn) self._handlers[chn] = false end -- NB: pity we can not just augment what net.createConnection returns local close = function(self) self._fd:close() end local connect = function(host, port) local _fd = net.createConnection(net.TCP, 0) local self = { _fd = _fd, _handlers = { }, -- TODO: consider metatables? close = close, publish = publish, subscribe = subscribe, unsubscribe = unsubscribe, } _fd:on("connection", function() --print("+FD") end) _fd:on("disconnection", function() -- FIXME: this suddenly occurs. timeout? --print("-FD") end) _fd:on("receive", function(fd, s) --print("IN", s) -- TODO: subscription to all channels -- lookup message pattern to determine channel and payload -- NB: pairs() iteration gives no fixed order! for chn, handler in pairs(self._handlers) do local p = ("*3\r\n$7\r\nmessage\r\n$%d\r\n%s\r\n$"):format(#chn, chn) if s:find(p, 1, true) then -- extract and check message length -- NB: only the first TCP packet considered! local _, start, len = s:find("(%d-)\r\n", #p) if start and tonumber(len) == #s - start - 2 and handler then handler(chn, s:sub(start + 1, -2)) -- ends with \r\n end end end end) _fd:connect(port or REDIS_PORT, host) return self end -- expose M = { connect = connect, } end return M
mit
matthewhesketh/mattata
plugins/fileid.lua
2
1642
--[[ Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]] local fileid = {} local mattata = require('mattata') local id = require('plugins.id') function fileid:init() fileid.commands = mattata.commands(self.info.username):command('fileid'):command('fid').table fileid.help = '/fileid - Returns available information about the replied-to media. Alias: /fid.' end function fileid.on_message(_, message, _, language) if not message.reply or not message.reply.is_media then return mattata.send_reply(message, 'You must use this command in reply to a type of media!') end local info = mattata.unpack_file_id(message.reply.file_id, message.reply.media_type) if not next(info) then return mattata.send_reply(message, language.errors.generic) end local output = {} for k, v in pairs(info) do table.insert(output, k:gsub('_', ' '):gsub('^%l', string.upper) .. ': <code>' .. v .. '</code>') end if info.user_id then local lookup = id.resolve_chat(info.user_id, language, nil, nil, nil, true) if lookup then table.insert(output, '\nInfo I found about the user:\n') for _, line in pairs(lookup) do table.insert(output, line) end else table.insert(output, '\nI couldn\'t find information about that user because they haven\'t spoken to me before - try using another ID lookup bot!') end end output = table.concat(output, '\n') return mattata.send_reply(message, output, 'html') end return fileid
mit
blueyed/awesome
lib/beautiful/theme_assets.lua
3
8564
---------------------------------------------------------------------------- --- Generate vector assets using current colors. -- -- @author Yauhen Kirylau &lt;yawghen@gmail.com&gt; -- @copyright 2015 Yauhen Kirylau -- @module beautiful.theme_assets ---------------------------------------------------------------------------- local cairo = require("lgi").cairo local surface = require("gears.surface") local gears_color = require("gears.color") local recolor_image = gears_color.recolor_image local screen = screen local theme_assets = {} --- Generate selected taglist square. -- @tparam number size Size. -- @tparam color fg Background color. -- @return Image with the square. function theme_assets.taglist_squares_sel(size, fg) local img = cairo.ImageSurface(cairo.Format.ARGB32, size, size) local cr = cairo.Context(img) cr:set_source(gears_color(fg)) cr:paint() return img end --- Generate unselected taglist square. -- @tparam number size Size. -- @tparam color fg Background color. -- @return Image with the square. function theme_assets.taglist_squares_unsel(size, fg) local img = cairo.ImageSurface(cairo.Format.ARGB32, size, size) local cr = cairo.Context(img) cr:set_source(gears_color(fg)) cr:set_line_width(size/4) cr:rectangle(0, 0, size, size) cr:stroke() return img end local function make_letter(cr, n, lines, size, bg, fg, alt_fg) local letter_gap = size/6 local function make_line(coords) for i, coord in ipairs(coords) do if i == 1 then cr:rel_move_to(coord[1], coord[2]) else cr:rel_line_to(coord[1], coord[2]) end end cr:stroke() end lines = lines or {} local color = alt_fg or fg cr:set_source(gears_color(color)) cr:rectangle( 0, (size+letter_gap)*n, size, size ) cr:fill() if bg then cr:set_source(gears_color(bg)) else cr:set_operator(cairo.Operator.CLEAR) end for _, line in ipairs(lines) do cr:move_to(0, (size+letter_gap)*n) make_line(line) end cr:set_operator(cairo.Operator.OVER) end --- Put Awesome WM name onto cairo surface. -- @param cr Cairo surface. -- @tparam number height Height. -- @tparam color bg Background color. -- @tparam color fg Main foreground color. -- @tparam color alt_fg Accent foreground color. function theme_assets.gen_awesome_name(cr, height, bg, fg, alt_fg) local ls = height/10 -- letter_size local letter_line = ls/18 cr:set_line_width(letter_line) -- a make_letter(cr, 0, { { { 0, ls/3 }, { ls*2/3, 0 }, }, { { ls/3, ls*2/3 }, { ls/3, 0 }, { 0, ls/3 }, } }, ls, bg, fg, alt_fg) -- w make_letter(cr, 1, { { { ls/3, 0 }, { 0,ls*2/3 }, }, { { ls*2/3, 0 }, { 0,ls*2/3 }, } }, ls, bg, fg) -- e make_letter(cr, 2, { { { ls/3, ls/3 }, { ls*2/3, 0 }, }, { { ls/3, ls*2/3 }, { ls*2/3, 0 }, } }, ls, bg, fg) -- s make_letter(cr, 3, { { { ls/3, ls/3 }, { ls*2/3, 0 }, }, { { 0, ls*2/3 }, { ls*2/3, 0 }, } }, ls, bg, fg) -- o make_letter(cr, 4, { { { ls/2, ls/3 }, { 0, ls/3 }, } }, ls, bg, fg) -- m make_letter(cr, 5, { { { ls/3, ls/3 }, { 0,ls*2/3 }, }, { { ls*2/3, ls/3 }, { 0,ls*2/3 }, } }, ls, bg, fg) -- e make_letter(cr, 6, { { { ls/3, ls/3 }, { ls*2/3, 0 }, }, { { ls/3, ls*2/3 }, { ls*2/3, 0 }, } }, ls, bg, fg) end --- Put Awesome WM logo onto cairo surface. -- @param cr Cairo surface. -- @tparam number width Width. -- @tparam number height Height. -- @tparam color bg Background color. -- @tparam color fg Foreground color. function theme_assets.gen_logo(cr, width, height, bg, fg) local ls = math.min(width, height) local letter_line = ls/18 cr:set_line_width(letter_line) make_letter(cr, 0, { { { 0, ls/3 }, { ls*2/3, 0 }, }, { { ls/3, ls*2/3 }, { ls/3, 0 }, { 0, ls/3 }, } }, ls, bg, fg) end --- Generate Awesome WM logo. -- @tparam number size Size. -- @tparam color bg Background color. -- @tparam color fg Background color. -- @return Image with the logo. function theme_assets.awesome_icon(size, bg, fg) local img = cairo.ImageSurface(cairo.Format.ARGB32, size, size) local cr = cairo.Context(img) theme_assets.gen_logo(cr, size, size, fg, bg) return img end --- Generate Awesome WM wallpaper. -- @tparam color bg Background color. -- @tparam color fg Main foreground color. -- @tparam color alt_fg Accent foreground color. -- @tparam screen s Screen (to get wallpaper size). -- @return Wallpaper image. function theme_assets.wallpaper(bg, fg, alt_fg, s) s = s or screen.primary local height = s.geometry.height local width = s.geometry.width local img = cairo.RecordingSurface(cairo.Content.COLOR, cairo.Rectangle { x = 0, y = 0, width = width, height = height }) local cr = cairo.Context(img) local letter_start_x = width - width / 10 local letter_start_y = height / 10 cr:translate(letter_start_x, letter_start_y) -- background cr:set_source(gears_color(bg)) cr:paint() theme_assets.gen_awesome_name(cr, height, bg, fg, alt_fg) return img end --- Recolor titlebar icons. -- @tparam table theme Beautiful theme table. -- @tparam color color Icons' color. -- @tparam string state `"normal"` or `"focus"`. -- @tparam string postfix `nil`, `"hover"` or `"press"`. -- @treturn table Beautiful theme table with the images recolored. function theme_assets.recolor_titlebar(theme, color, state, postfix) if postfix then postfix='_'..postfix end for _, titlebar_icon_name in ipairs({ 'titlebar_close_button_'..state..'', 'titlebar_minimize_button_'..state..'', 'titlebar_ontop_button_'..state..'_inactive', 'titlebar_ontop_button_'..state..'_active', 'titlebar_sticky_button_'..state..'_inactive', 'titlebar_sticky_button_'..state..'_active', 'titlebar_floating_button_'..state..'_inactive', 'titlebar_floating_button_'..state..'_active', 'titlebar_maximized_button_'..state..'_inactive', 'titlebar_maximized_button_'..state..'_active', }) do local full_name = postfix and ( titlebar_icon_name .. postfix ) or titlebar_icon_name local image = theme[full_name] or theme[titlebar_icon_name] if image then image = surface.duplicate_surface(image) theme[full_name] = recolor_image(image, color) end end return theme end --- Recolor unfocused titlebar icons. -- This method is deprecated. Use a `beautiful.theme_assets.recolor_titlebar`. -- @tparam table theme Beautiful theme table -- @tparam color color Icons' color. -- @treturn table Beautiful theme table with the images recolored. -- @deprecated recolor_titlebar_normal function theme_assets.recolor_titlebar_normal(theme, color) return theme_assets.recolor_titlebar(theme, color, "normal") end --- Recolor focused titlebar icons. -- This method is deprecated. Use a `beautiful.theme_assets.recolor_titlebar`. -- @tparam table theme Beautiful theme table -- @tparam color color Icons' color. -- @treturn table Beautiful theme table with the images recolored. -- @deprecated recolor_titlebar_focus function theme_assets.recolor_titlebar_focus(theme, color) return theme_assets.recolor_titlebar(theme, color, "focus") end --- Recolor layout icons. -- @tparam table theme Beautiful theme table -- @tparam color color Icons' color. -- @treturn table Beautiful theme table with the images recolored. function theme_assets.recolor_layout(theme, color) for _, layout_name in ipairs({ 'layout_fairh', 'layout_fairv', 'layout_floating', 'layout_magnifier', 'layout_max', 'layout_fullscreen', 'layout_tilebottom', 'layout_tileleft', 'layout_tile', 'layout_tiletop', 'layout_spiral', 'layout_dwindle', 'layout_cornernw', 'layout_cornerne', 'layout_cornersw', 'layout_cornerse', }) do theme[layout_name] = recolor_image(theme[layout_name], color) end return theme end return theme_assets -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
CrazyEddieTK/Zero-K
effects/arch.lua
25
3934
-- archshells -- archplosion return { ["archshells"] = { shells = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 1 1 1 1 1]], directional = true, emitrot = 0, emitrotspread = 10, emitvector = [[dir]], gravity = [[0, -0.5, 0]], numparticles = 1, particlelife = 30, particlelifespread = 0, particlesize = 2.5, particlesizespread = 0, particlespeed = 9, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[shell]], }, }, }, ["archplosion"] = { burst = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 1 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 180, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 7, particlelifespread = 0, particlesize = 2, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 1, sizemod = 1.0, texture = [[kburst]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 12, ttl = 3, color = { [1] = 1, [2] = 0.69999998807907, [3] = 0, }, }, smoke = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.4 0.4 0.4 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 10, emitvector = [[dir]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 160, particlelifespread = 0, particlesize = 6, particlesizespread = 2, particlespeed = 0, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0.01, sizemod = 1.0, texture = [[smokesmall]], }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 180, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 40, particlelife = 7, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 0, particlespeedspread = 6, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, }
gpl-2.0
CrazyEddieTK/Zero-K
units/tankassault.lua
5
3337
unitDef = { unitname = [[tankassault]], name = [[Minotaur]], description = [[Assault Tank]], acceleration = 0.0237, brakeRate = 0.04786, buildCostMetal = 850, builder = false, buildPic = [[tankassault.png]], canGuard = true, canMove = true, canPatrol = true, category = [[LAND]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[50 50 50]], collisionVolumeType = [[ellipsoid]], corpse = [[DEAD]], customParams = { aimposoffset = [[0 0 0]], midposoffset = [[0 0 0]], modelradius = [[25]], }, explodeAs = [[BIG_UNITEX]], footprintX = 4, footprintZ = 4, iconType = [[tankassault]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, maxDamage = 6800, maxSlope = 18, maxVelocity = 2.45, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[TANK4]], noAutoFire = false, noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE SUB]], objectName = [[correap.s3o]], script = [[tankassault.cob]], selfDestructAs = [[BIG_UNITEX]], sfxtypes = { explosiongenerators = { [[custom:LARGE_MUZZLE_FLASH_FX]], }, }, sightDistance = 506, trackOffset = 8, trackStrength = 8, trackStretch = 1, trackType = [[StdTank]], trackWidth = 42, turninplace = 0, turnRate = 364, workerTime = 0, weapons = { { def = [[COR_REAP]], badTargetCategory = [[FIXEDWING GUNSHIP]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { COR_REAP = { name = [[Medium Plasma Cannon]], areaOfEffect = 32, burst = 2, burstRate = 0.2, craterBoost = 0, craterMult = 0, customParams = { reaim_time = 8, -- COB }, damage = { default = 320, planes = 320, subs = 16, }, explosionGenerator = [[custom:DEFAULT]], impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, noSelfDamage = true, range = 360, reloadtime = 4, soundHit = [[weapon/cannon/reaper_hit]], soundStart = [[weapon/cannon/cannon_fire5]], turret = true, weaponType = [[Cannon]], weaponVelocity = 255, }, }, featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 3, footprintZ = 3, object = [[correap_dead.s3o]], }, HEAP = { blocking = false, footprintX = 3, footprintZ = 3, object = [[debris3x3b.s3o]], }, }, } return lowerkeys({ tankassault = unitDef })
gpl-2.0
sigma-random/wireshark
test/lua/luatest.lua
35
4498
-- See Copyright Notice in the file LICENSE -- arrays: deep comparison local function eq (t1, t2, lut) if t1 == t2 then return true end if type(t1) ~= "table" or type(t2) ~= "table" or #t1 ~= #t2 then return false end lut = lut or {} -- look-up table: are these 2 arrays already compared? lut[t1] = lut[t1] or {} if lut[t1][t2] then return true end lut[t2] = lut[t2] or {} lut[t1][t2], lut[t2][t1] = true, true for k,v in ipairs (t1) do if not eq (t2[k], v, lut) then return false end -- recursion end return true end -- a "nil GUID", to be used instead of nils in datasets local NT = "b5f74fe5-46f4-483a-8321-e58ba2fa0e17" -- pack vararg in table, replacing nils with "NT" items local function packNT (...) local t = {} for i=1, select ("#", ...) do local v = select (i, ...) t[i] = (v == nil) and NT or v end return t end -- unpack table into vararg, replacing "NT" items with nils local function unpackNT (t) local len = #t local function unpack_from (i) local v = t[i] if v == NT then v = nil end if i == len then return v end return v, unpack_from (i+1) end if len > 0 then return unpack_from (1) end end -- print results (deep into arrays) local function print_results (val, indent, lut) indent = indent or "" lut = lut or {} -- look-up table local str = tostring (val) if type (val) == "table" then if lut[val] then io.write (indent, str, "\n") else lut[val] = true io.write (indent, str, "\n") for i,v in ipairs (val) do print_results (v, " " .. indent, lut) -- recursion end end else io.write (indent, val == NT and "nil" or str, "\n") end end -- returns: -- 1) true, if success; false, if failure -- 2) test results table or error_message local function test_function (test, func) local res local t = packNT (pcall (func, unpackNT (test[1]))) if t[1] then table.remove (t, 1) res = t if alien then local subject = test[1][1] local buf = alien.buffer (#subject) if #subject > 0 then alien.memmove (buf:topointer (), subject, #subject) end test[1][1] = buf local t = packNT (pcall (func, unpackNT (test[1]))) if t[1] then table.remove (t, 1) res = t else print "alien test failed" res = t[2] --> error_message end end else res = t[2] --> error_message end local how = (type (res) == type (test[2])) and (type (res) == "string" or eq (res, test[2])) -- allow error messages to differ return how, res end -- returns: -- 1) true, if success; false, if failure -- 2) test results table or error_message -- 3) test results table or error_message local function test_method (test, constructor, name) local res1, res2 local subject = test[2][1] local ok, r = pcall (constructor, unpackNT (test[1])) if ok then local t = packNT (pcall (r[name], r, unpackNT (test[2]))) if t[1] then table.remove (t, 1) res1, res2 = t else res1, res2 = 2, t[2] --> 2, error_message end else res1, res2 = 1, r --> 1, error_message end return eq (res1, test[3]), res1, res2 end -- returns: a list of failed tests local function test_set (set, lib, verbose) local list = {} if type (set.Func) == "function" then local func = set.Func for i,test in ipairs (set) do if verbose then io.write (" running function test "..i.."...") io.flush () end local ok, res = test_function (test, func) if not ok then if verbose then io.stdout:write("failed!\n") end table.insert (list, {i=i, test[2], res}) elseif verbose then io.write ("passed\n") io.flush () end end elseif type (set.Method) == "string" then for i,test in ipairs (set) do if verbose then io.write (" running method test "..i.."...") io.flush () end local ok, res1, res2 = test_method (test, lib.new, set.Method) if not ok then if verbose then io.stdout:write("failed!\n") end table.insert (list, {i=i, test[3], res1, res2}) elseif verbose then io.write ("passed\n") io.flush () end end else error ("neither set.Func nor set.Method is valid") end return list end return { eq = eq, NT = NT, print_results = print_results, test_function = test_function, test_method = test_method, test_set = test_set, }
gpl-2.0
czfshine/Don-t-Starve
data/scripts/brain.lua
1
4874
BrainWrangler = Class(function(self) self.instances = {} self.updaters = {} self.tickwaiters = {} self.hibernaters = {} end) BrainManager = BrainWrangler() function BrainWrangler:OnRemoveEntity(inst) --print ("onremove", inst, debugstack()) if inst.brain and self.instances[inst.brain] then self:RemoveInstance(inst.brain) end end function BrainWrangler:NameList(list) if not list then return "nil" elseif list == self.updaters then return "updaters" elseif list == self.hibernaters then return "hibernators" else for k,v in pairs(self.tickwaiters) do if list == v then return "tickwaiter "..tostring(k) end end end return "Unknown" end function BrainWrangler:SendToList(inst, list) local old_list = self.instances[inst] -- print ("HI!", inst.inst, self:NameList(old_list), self:NameList(list)) if old_list and old_list ~= list then if old_list then old_list[inst] = nil end self.instances[inst] = list if list then list[inst] = true end end end function BrainWrangler:Wake(inst) if self.instances[inst] then self:SendToList(inst, self.updaters) end end function BrainWrangler:Hibernate(inst) if self.instances[inst] then self:SendToList(inst, self.hibernaters) end end function BrainWrangler:Sleep(inst, time_to_wait) local sleep_ticks = time_to_wait/GetTickTime() if sleep_ticks == 0 then sleep_ticks = 1 end local target_tick = math.floor(GetTick() + sleep_ticks) if target_tick > GetTick() then local waiters = self.tickwaiters[target_tick] if not waiters then waiters = {} self.tickwaiters[target_tick] = waiters end --print ("BRAIN SLEEPS", inst.inst) self:SendToList(inst, waiters) end end function BrainWrangler:RemoveInstance(inst) self:SendToList(inst, nil) self.updaters[inst] = nil self.hibernaters[inst] = nil for k,v in pairs(self.tickwaiters) do v[inst] = nil end self.instances[inst] = nil end function BrainWrangler:AddInstance(inst) self.instances[inst] = self.updaters self.updaters[inst] = true end function BrainWrangler:Update(current_tick) --[[ local num = 0; local types = {} for k,v in pairs(self.instances) do num = num + 1 types[k.inst.prefab] = types[k.inst.prefab] and types[k.inst.prefab] + 1 or 1 end print ("NUM BRAINS:", num) for k,v in pairs(types) do print (" ",k,v) end --]] local waiters = self.tickwaiters[current_tick] if waiters then for k,v in pairs(waiters) do --print ("BRAIN COMES ONLINE", k.inst) self.updaters[k] = true self.instances[k] = self.updaters end self.tickwaiters[current_tick] = nil end for k,v in pairs(self.updaters) do if k.inst.entity:IsValid() and not k.inst:IsAsleep() then k:OnUpdate() local sleep_amount = k:GetSleepTime() if sleep_amount then if sleep_amount > GetTickTime() then self:Sleep(k, sleep_amount) else end else self:Hibernate(k) end end end end Brain = Class(function(self) self.inst = nil self.currentbehaviour = nil self.behaviourqueue = {} self.events = {} self.thinkperiod = nil self.lastthinktime = nil end) function Brain:ForceUpdate() if self.bt then self.bt:ForceUpdate() end BrainManager:Wake(self) end function Brain:__tostring() if self.bt then return string.format("--brain--\nsleep time: %2.2f\n%s", self:GetSleepTime(), tostring(self.bt)) end return "--brain--" end function Brain:AddEventHandler(event, fn) self.events[event] = fn end function Brain:GetSleepTime() if self.bt then return self.bt:GetSleepTime() end return 0 end function Brain:Start() if self.OnStart then self:OnStart() end self.stopped = false BrainManager:AddInstance(self) if self.OnInitializationComplete then self:OnInitializationComplete() end -- apply mods if self.modpostinitfns then for i,modfn in ipairs(self.modpostinitfns) do modfn(self) end end end function Brain:OnUpdate() if self.DoUpdate then self:DoUpdate() end if self.bt then self.bt:Update() end end function Brain:Stop() if self.OnStop then self:OnStop() end if self.bt then self.bt:Stop() end self.stopped = true BrainManager:RemoveInstance(self) end function Brain:PushEvent(event, data) local handler = self.events[event] if handler then handler(data) end end
gpl-2.0
kasperlewau/casketUI
BasicChatMods/Locales/frFR.lua
1
3590
if GetLocale() ~= "frFR" then return end local _, BCM = ... BCM["BCM_AutoLog"] = "Enregistre automatiquement le journal de discussion une fois connecté et enregistre automatiquement le journal de combat dans les instances de raid." -- Needs review BCM["BCM_ButtonHide"] = "Cache complètement les boutons latéraux de la fenêtre de discussion pour ceux qui n'en n'ont pas l'utilité." -- Needs review BCM["BCM_EditBox"] = "Personnalise la boîte de saisie (celle dans laquelle vous écrivez) afin de pouvoir la déplacer en haut, cacher l'arrière-plan et/ou augmenter sa taille." -- Needs review BCM["BCM_Fade"] = "Estompe complètement et non partiellement les cadres de discussion quand vous écartez votre pointeur de souris d'un cadre de discussion." -- Needs review BCM["BCM_Font"] = "Change le style, la taille et le nom de la police d'écriture de vos cadres de discussion & de la boîte de saisie." -- Needs review BCM["BCM_GMOTD"] = "Affiche à nouveau le message de guilde du jour dans la fenêtre de discussion principale après 10 secondes." -- Needs review BCM["BCM_Highlight"] = "Joue un son quand votre nom est mentionné dans une discussion et le colorie selon votre classe. Vous pouvez entrer la version courte de votre nom dans la saisie ci-dessous." -- Needs review BCM["BCM_InviteLinks"] = "Reste à l'affût du mot 'invite' et convertit ce dernier en un lien ALT-cliquable qui invite cette personne. Exemple : |cFFFF7256[invite]|r" -- Needs review BCM["BCM_Justify"] = "Justifie le texte des diverses fenêtres de discussion à droite, à gauche ou au centre de la fenêtre." -- Needs review BCM["BCM_Resize"] = "Vous permet de changer la taille du cadre de discussion dans des dimensions plus petites/plus grandes que celles autorisées par Blizzard." -- Needs review BCM["BCM_ScrollDown"] = "Créée une petite flèche cliquable sur vos fenêtres de discussion qui clignote quand vous n'êtes pas tout en bas." -- Needs review BCM["BCM_TellTarget"] = "Vous permet de chuchoter à votre cible actuelle en utilisant la commande /tt <message> ou /wt <message>." -- Needs review BCM["BCM_URLCopy"] = "Transforme les sites web mentionnés dans les cadres de discussion en liens cliquables afin d'être copiés facilement. Par exemple : |cFFFFFFFF[www.battle.net]|r" -- Needs review BCM["CENTER"] = "Centre" -- Needs review BCM["CHANNELNAME"] = "Nom de canal" -- Needs review BCM["CHANNELNUMBER"] = "Numéro de canal" -- Needs review BCM["CHATLOG"] = "Enregistre toujours le journal de discussion." -- Needs review BCM["COMBATLOG"] = "Enregistre le journal de combat dans une instance de raid." -- Needs review BCM["CUSTOMCHANNEL"] = "Canal personnalisé" -- Needs review BCM["FAKENAMES"] = "Remplace les noms réels avec les noms des personnages." -- Needs review BCM["GENERAL"] = "Général" BCM["GUILDRECRUIT"] = "RecrutementDeGuilde" BCM["LEFT"] = "Gauche" -- Needs review BCM["LFG"] = "RechercheDeGroupe" BCM["LOCALDEFENSE"] = "DéfenseLocale" BCM["OPTIONS"] = "<<Plus d'options peuvent être disponibles après l'activation de ce module>>" -- Needs review BCM["PLAYERBRACKETS"] = "Parenthèses de joueur :" -- Needs review BCM["RIGHT"] = "Droite" -- Needs review BCM["SHOWGROUP"] = "Groupe du joueur à côté du nom." -- Needs review BCM["SHOWLEVELS"] = "Niveau du joueur à côté du nom." -- Needs review BCM["SIZE"] = "Taille" -- Needs review BCM["TRADE"] = "Commerce" BCM["WARNING"] = "<<Les changements effectués nécessite un /reload pour prendre effet>>" -- Needs review BCM["WORLDDEFENSE"] = "DéfenseUniverselle"
mit
dani-sj/iman22
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
ioiasff/creawq
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0