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
dafei2015/hugular_cstolua
Client/tools/netProtocal/parseErrorCode.lua
8
2038
require("helperFunction") io.input("protocal/error_code.txt") io.output("../../Assets/Lua/net/alertDataList.lua") function parseAlertData(startLine) local r = {} for i in string.gmatch(startLine, string.format('[^%s]+', '-')) do table.insert(r, i) end local alertCode = r[1] local alertKey = r[2] local alertDesc = r[3] local alertType = r[4] or 'Tip' if(alertCode == nil or alertKey == nil) then print("------------------invalid format-------") print(startLine) return end io.write("\n") io.write("\t\t-- ", alertDesc, " \n") io.write("\t\t", tostring(alertKey), " = 'LC_ALERT_", tostring(alertKey), "',\n") end function generateIndex(startLine) local r = {} for i in string.gmatch(startLine, string.format('[^%s]+', '-')) do table.insert(r, i) end local alertCode = r[1] local alertKey = r[2] local alertDesc = r[3] local alertType = r[4] or 'Tip' io.write(string.format("AlertDataList.CodeToKey[%s] = {\n\tkind = '%s',\n\ttext = '%s',\n}\n", tostring(alertCode), tostring(alertType), tostring(alertKey))) end io.write("------------------- AlertDataList ---------------\n") io.write("AlertDataList= { \n") io.write("\tDataList= { \n") local nextLine = getNextValidLine() while(nextLine ~= nil) do parseAlertData(nextLine) nextLine = getNextValidLine() end io.write("\t},\n") io.write("} \n") io.flush() io.input("protocal/error_code.txt") io.write("AlertDataList.CodeToKey = { }\n") local nextLine = getNextValidLine() while(nextLine ~= nil) do generateIndex(nextLine) nextLine = getNextValidLine() end io.write("\nfunction AlertDataList:GetTextId(key)\n") io.write("\treturn self.DataList[key]\n") io.write("end\n") io.write("\nfunction AlertDataList:GetTextIdFromCode(code)\n") io.write("\treturn self:GetTextId(self.CodeToKey[code].text)\n") io.write("end\n") io.write("\nfunction AlertDataList:GetTypeFromCode(code)\n") io.write("\treturn self.CodeToKey[code].kind\n") io.write("end\n")
mit
dinodeck/ninety_nine_days_of_dev
007_map_cure/code/CombatSelector.lua
2
2859
-- Give the target state returns a list of actors -- that are targets. local function WeakestActor(list, onlyCheckHurt) local target = nil local health = 99999 for k, v in ipairs(list) do local hp = v.mStats:Get("hp_now") local isHurt = hp < v.mStats:Get("hp_max") local skip = false if onlyCheckHurt and not isHurt then skip = true end if hp < health and not skip then health = hp target = v end end return { target or list[1] } end local function MostDrainedActor(list, onlyCheckDrained) local target = nil local magic = 99999 for k, v in ipairs(list) do local mp = v.mStats:Get("mp_now") local isHurt = mp < v.mStats:Get("mp_max") local skip = false if onlyCheckDrained and not isHurt then skip = true end if mp < magic and not skip then magic = mp target = v end end return { target or list[1] } end CombatSelector = { WeakestEnemy = function(state) return WeakestActor(state.mActors["enemy"], false) end, WeakestParty = function(state) return WeakestActor(state.mActors["party"], false) end, MostHurtEnemy = function(state) return WeakestActor(state.mActors["party"], true) end, MostHurtParty = function(state) print("Calling most hurt party") return WeakestActor(state.mActors["party"], true) end, MostDrainedParty = function(state) return MostDrainedActor(state.mActors["party"], true) end, DeadParty = function(state) local list = state.mActors["party"] for k, v in ipairs(list) do local hp = v.mStats:Get("hp_now") if hp == 0 then return { v } end end -- Just return the first return { list[1] } end, SideEnemy = function(state) return state.mActors["enemy"] end, SideParty = function(state) return state.mActors["party"] end, SelectAll = function(state) local targets = {} for k, v in ipairs(state.mActors["enemy"]) do table.insert(targets, v) end for k, v in ipairs(state.mActors["party"]) do table.insert(targets, v) end return targets end, RandomAlivePlayer = function(state) local aliveList = {} for k, v in ipairs(state.mActors["party"]) do if v.mStats:Get("hp_now") > 0 then table.insert(aliveList, v) end end local target = aliveList[math.random(#aliveList)] return { target } end, }
mit
chroteus/clay
class/region.lua
1
14595
Region = Base:subclass("Region") function Region:initialize(id, color, name, ...) self.id = id -- id which will link a region to a country self.color = color self.name = tostring(name) self.convex = true self.country = countries[self.id] self.selected = false local arg = {...} -- unpaired vertices are needed for drawing and triangulation (Löve2D doesn't accept paired ones) if type(arg[1]) == "table" then self.vertices = pairVertices(arg[1]) -- pairing for a cleaner code self.unpairedVertices = arg[1] elseif type(arg[1]) == "number" then self.vertices = pairVertices(arg) self.unpairedVertices = arg else error("Region only accepts a table or number as a polygon.") end if not love.math.isConvex(self.unpairedVertices) then self.convex = false end if #self.vertices >= 3 then self.triangles = love.math.triangulate(self.unpairedVertices) else error("Region cannot be a line. It must have atleast 3 corners.") end self.vertRadius = 10 self.border = {} -- filled after all regions are initialized self.neighbours = {} -- filled after all regions are initialized self.midpoint = self:_midpoint() end function Region:_midpoint() local trianglesXCenterSum = 0 local trianglesYCenterSum = 0 -- triangles triangulated by love2d have the following format: -- {x1, y1, x2, y2, x3, y3} for _,triangle in pairs(self.triangles) do local xCenter = (triangle[1] + triangle[3] + triangle[5]) / 3 local yCenter = (triangle[2] + triangle[4] + triangle[6]) / 3 trianglesXCenterSum = trianglesXCenterSum + xCenter trianglesYCenterSum = trianglesYCenterSum + yCenter end return {x = trianglesXCenterSum / #self.triangles, y = trianglesYCenterSum / #self.triangles} end function Region:mousereleased(x,y,button) if button == "l" then if PointWithinShape(self.vertices, mapMouse.x, mapMouse.y) then for _,region in pairs(map) do region.selected = false end if Player.country == self.country.name or self.country.name == "Sea" then self.selected = true game.neighbours = self.neighbours -- tutorial message if prefs.firstPlay then DialogBoxes:new( "Now that you've selected your region, try clicking on other countries' regions.", {"OK", function() end} ):show() end ------------------- else if not editMode.enabled then for _,mapNeighbour in pairs(game.neighbours) do if self.name == mapNeighbour then local battleFunc = function() startBattle(Player.country, self.country.name) battle.attackedRegion = self.name end if not Player:returnCountry():isFoe(self.country.name) then local dbox = DialogBoxes:new( "Declare war on "..self.country.name.."?", {"No", function() end}, {"Yes", function() Player:returnCountry():war(self.country.name); battleFunc() end} ) dbox:show() else battleFunc() end end end end end end elseif button == "r" then if PointWithinShape(self.vertices, mapMouse.x, mapMouse.y) then -- Switching to upgrade state if not editMode.enabled then if self.state then Gamestate.switch(self.state) end end end end if editMode.enabled then local radius = self.vertRadius/mapCam.scale local cp = editMode.currPoint local fp = editMode.firstPoint local hp1 = editMode.helpPoint1 local hp2 = editMode.helpPoint2 if button == "l" and not love.keyboard.isDown("lalt") or not love.keyboard.isDown("lshift") then for _,vertex in pairs(self.vertices) do if pointCollidesMouse(vertex.x, vertex.y, self.vertRadius) then cp.x,cp.y = vertex.x,vertex.y if fp.x < 0 and fp.y < 0 then fp.x,fp.y = vertex.x,vertex.y end end end end if love.keyboard.isDown("lshift") then if button == "r" then if PointWithinShape(self.vertices, mapMouse.x, mapMouse.y) then DialogBoxes:new( "Delete region?", {"Cancel", function() end}, {"Yes", function() for k,region in pairs(map) do if region.name == self.name then map[k] = nil end Regions.generateBorders() end end } ):show(function() love.mouse.setVisible(false) end) end end end end end function Region:draw() -- determining whether Region is visible, not drawing if not visible local drawRegion = false local camX, camY = mapCam:worldCoords(0,0) for _,vertex in pairs(self.vertices) do if checkCollision(camX, camY, the.screen.width, the.screen.height, vertex.x, vertex.y, self.vertRadius/mapCam.scale, self.vertRadius/mapCam.scale) then drawRegion = true break end end if drawRegion then if #self.unpairedVertices > 2 then self.color[4] = 255 -- opacity love.graphics.setColor(self.color) if self.country.name ~= "Sea" then if self.convex then love.graphics.polygon("fill", self.unpairedVertices) else for _,triangle in pairs(self.triangles) do love.graphics.polygon("fill", triangle) end end end if editMode.enabled then if self.country.name == editMode.country then love.graphics.setColor(255,255,255) love.graphics.polygon("line",self.unpairedVertices) end else if PointWithinShape(self.unpairedVertices, mapMouse.x, mapMouse.y) then if (self.color[1] >= 128 or self.color[2] >= 128 or self.color[3] >= 128) and self.country.name ~= "Sea" then love.graphics.setColor(0,0,0,100) else love.graphics.setColor(255,255,255,100) end if self.convex then love.graphics.polygon("fill", self.unpairedVertices) else for _,triangle in pairs(self.triangles) do love.graphics.polygon("fill", triangle) end end end end if self.selected then love.graphics.setColor(255,255,255,100) if self.convex then love.graphics.polygon("fill", self.unpairedVertices) else for _,triangle in pairs(self.triangles) do love.graphics.polygon("fill", triangle) end end love.graphics.setColor(255,255,255) end for _,neighbour in pairs(game.neighbours) do if self.name == neighbour then love.graphics.setColor(255,255,255,64) if self.convex then love.graphics.polygon("fill", self.unpairedVertices) else for _,triangle in pairs(self.triangles) do love.graphics.polygon("fill", triangle) end end love.graphics.setColor(255,255,255) end end elseif #self.unpairedVertices == 2 then love.graphics.line(self.unpairedVertices) end if editMode.enabled then local radius = self.vertRadius/mapCam.scale love.graphics.setColor(255,50,50) if PointWithinShape(self.unpairedVertices, mapMouse.x, mapMouse.y) then for _,vertex in pairs(self.vertices) do if pointCollidesMouse(vertex.x, vertex.y, self.vertRadius) then love.graphics.circle("line", vertex.x, vertex.y, radius+0.2, 100) else love.graphics.circle("line", vertex.x, vertex.y, radius, 100) end end end for _,vertex in pairs(self.vertices) do if pointCollidesMouse(vertex.x, vertex.y, self.vertRadius) then love.graphics.circle("line", vertex.x, vertex.y, radius+0.2, 100) end end end -- Borders if not editMode.enabled then if (self.country.name == "Sea" and PointWithinShape(self.unpairedVertices, mapMouse.x, mapMouse.y)) or self.country.name ~= "Sea" then local alpha = 20*mapCam.scale alpha = math.clamp(0,alpha,128) love.graphics.setLineWidth(1.2) love.graphics.setColor(self.color[1], self.color[2],self.color[3],alpha) love.graphics.polygon("line", self.unpairedVertices) love.graphics.setColor(255,255,255) love.graphics.setLineWidth(1) end end love.graphics.setColor(255,255,255) end end function Region:changeOwner(owner) local owner = owner if type(owner) == "string" then owner = nameToCountry(owner) end owner.midpoint = owner:_midpoint() self.country.midpoint = self.country:_midpoint() -- old country self.id = owner.id self.color = owner.color self.country = owner if owner.name == Player.country and not self.state then self:createUpgState() elseif owner.name ~= Player.country and self.state then self.state = nil end end function Region:hasSeaBorder() for _,n in pairs(self.neighbours) do if n:match("sea") then return true else return false end end end Regions = {} -- Table to hold functions which affect all regions. function Regions.generateNeighbours() -- Generating neighbours for regions -- NOTE: Must be called AFTER map's regions are loaded. -- It is checked if regions share points and add those who share it are added to neighbors table. -- Since multiple points can be shared, duplicates are removed later on. for _,region in pairs(map) do for _,vertex in pairs(region.vertices) do for _,regionB in pairs(map) do for _,vertexB in pairs(regionB.vertices) do if vertexB.x == vertex.x and vertexB.y == vertex.y then if region.name ~= regionB.name then table.insert(region.neighbours, regionB.name) end end end end end region.neighbours = removeDuplicates(region.neighbours) end end -- ############################################# -- ########## NOT TO BE USED.################### -- ############################################# -- Generates bad looking borders. function Regions.generateBorders() for _,region in pairs(map) do region.border = {} for _,neighbourName in pairs(region.neighbours) do local neighbour = getRegion(neighbourName) if neighbour ~= nil then if neighbourName ~= region.name then if neighbour.country.name ~= region.country.name then for _,region_vertex in pairs(region.vertices) do for _,neigh_vertex in pairs(neighbour.vertices) do if region_vertex.x == neigh_vertex.x and region_vertex.y == neigh_vertex.y then table.insert(region.border, region_vertex.x) table.insert(region.border, region_vertex.y) end end end end end end end end end function Region:createUpgState() self.state = {} local state = self.state function state.init() state.btn = GuiOrderedTable() for _,upg in pairs(upgrades) do state.btn:insert( Upgrade{name = upg.name, desc = upg.desc, cost = upg.cost, func = function(level) upg.upg_func(level,self) end, max_level = upg.max_level, width = upg.width, height = upg.height, } ) end end function state:enter() love.mouse.setVisible(true) end function state:update(dt) state.btn:update(dt) end function state:draw() state.btn:draw() end function state:mousereleased(x,y,btn) state.btn:mousereleased(x,y,btn) end function state:leave() love.mouse.setVisible(false) end function state:keypressed(key) if key == "escape" then Gamestate.switch(game) end end end --[[ #### POINT REMOVAL -- OLD CODE for i,vertex in ipairs(self.vertices) do if pointCollidesMouse(vertex.x, vertex.y, self.vertRadius) then table.remove(self.vertices, i) if #self.vertices > 3 then self.triangles = love.math.triangulate(self.vertices) end end end ]]--
gpl-2.0
Ninjistix/darkstar
scripts/zones/Ghelsba_Outpost/bcnms/wings_of_fury.lua
7
1494
----------------------------------- -- Area: Ghelsba Outpost -- Name: Wings of Fury BCNM20 -- !pos -162 -11 78 140 ----------------------------------- package.loaded["scripts/zones/Ghelsba_Outpost/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Ghelsba_Outpost/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print(leave code ..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:startEvent(32001,1,1,1,instance:getTimeInside(),2,2,2); elseif (leavecode == 4) then player:startEvent(32002); end end; function onEventUpdate(player,csid,option) -- print(bc update csid ..csid.. and option ..option); end; function onEventFinish(player,csid,option) -- print(bc finish csid ..csid.. and option ..option); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/mobskills/fiery_breath.lua
32
1245
--------------------------------------------- -- Fiery Breath -- -- Description: Deals Fire damage to enemies within a fan-shaped area. -- Type: Breath -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown cone -- Notes: Used only by Tiamat, Smok and Ildebrann --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/utils"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:hasStatusEffect(EFFECT_MIGHTY_STRIKES)) then return 1; elseif (target:isBehind(mob, 48) == true) then return 1; elseif (mob:AnimationSub() == 1) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local dmgmod = MobBreathMove(mob, target, 0.2, 1.25, ELE_FIRE, 1400); local angle = mob:getAngle(target); angle = mob:getRotPos() - angle; dmgmod = dmgmod * ((128-math.abs(angle))/128); dmgmod = utils.clamp(dmgmod, 50, 1600); local dmg = MobFinalAdjustments(dmgmod,mob,skill,target,MOBSKILL_BREATH,MOBPARAM_FIRE,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Spire_of_Dem/bcnms/ancient_flames_beckon.lua
3
4237
----------------------------------- -- Area: Spire_of_Dem -- Name: ancient_flames_backon -- KSNM30 ----------------------------------- package.loaded["scripts/zones/Spire_of_Dem/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/globals/teleports"); require("scripts/zones/Spire_of_Dem/TextIDs"); ----------------------------------- -- EXAMPLE SCRIPT -- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) print("instance code "); end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- printf("leavecode: %u",leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS) then if (player:hasKeyItem(LIGHT_OF_MEA) and player:hasKeyItem(LIGHT_OF_HOLLA)) then player:startEvent(32001,0,0,0,instance:getTimeInside(),0,0,0,3); elseif (player:hasKeyItem(LIGHT_OF_MEA) or player:hasKeyItem(LIGHT_OF_HOLLA)) then player:startEvent(32001,0,0,0,instance:getTimeInside(),0,0,0,2); end elseif (player:getCurrentMission(COP) == BELOW_THE_ARKS) then player:startEvent(32001,0,0,0,instance:getTimeInside(),0,0,0,1); else player:startEvent(32001,0,0,0,instance:getTimeInside(),0,0,1); -- can't tell which cs is playing when you're doing it again to help end elseif (leavecode == 4) then player:startEvent(32002); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 32001) then if (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS) then if (player:hasKeyItem(LIGHT_OF_MEA) and player:hasKeyItem(LIGHT_OF_HOLLA)) then player:addExp(1500); player:addKeyItem(LIGHT_OF_DEM); player:messageSpecial(CANT_REMEMBER,LIGHT_OF_DEM); player:completeMission(COP,THE_MOTHERCRYSTALS); player:setVar("PromathiaStatus",0) player:addMission(COP,AN_INVITATION_WEST); player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_LUFAISE,0,1); elseif (not(player:hasKeyItem(LIGHT_OF_DEM))) then player:setVar("cspromy3",1) player:addKeyItem(LIGHT_OF_DEM); player:addExp(1500); player:messageSpecial(CANT_REMEMBER,LIGHT_OF_DEM); player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_EXITPROMDEM,0,1); end elseif (player:getCurrentMission(COP) == BELOW_THE_ARKS) then player:addExp(1500); player:completeMission(COP,BELOW_THE_ARKS); player:addMission(COP,THE_MOTHERCRYSTALS) player:setVar("cspromy2",1) player:setVar("PromathiaStatus",0) player:addKeyItem(LIGHT_OF_DEM); player:messageSpecial(CANT_REMEMBER,LIGHT_OF_DEM); player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_EXITPROMDEM,0,1); else player:addExp(1500); player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_EXITPROMDEM,0,1); end end end;
gpl-3.0
zcold/cp-solver-lua
testb.lua
1
6125
--require "CSP" require "Ulti" -- Generate V and U local V = {} local U = {} local i = 1 local j = 1 while i <= 9 do j = 1 while j <= 9 do V["x_" .. i .. j] = "x_" .. i .. j U["x_" .. i .. j] = {1, 2, 3, 4, 5, 6, 7, 8, 9} j = j + 1 end i = i + 1 end -- U["x_11"] = {5} U["x_12"] = {6} U["x_14"] = {8} U["x_15"] = {4} U["x_16"] = {7} U["x_21"] = {3} U["x_23"] = {9} U["x_27"] = {6} U["x_33"] = {8} U["x_42"] = {1} U["x_45"] = {8} U["x_48"] = {4} U["x_51"] = {7} U["x_52"] = {9} U["x_54"] = {6} U["x_56"] = {2} U["x_58"] = {1} U["x_59"] = {8} U["x_62"] = {5} U["x_65"] = {3} U["x_68"] = {9} U["x_77"] = {2} U["x_83"] = {6} U["x_87"] = {8} U["x_89"] = {7} U["x_94"] = {3} U["x_95"] = {1} U["x_96"] = {6} U["x_98"] = {5} U["x_99"] = {9} -- -- Distinct -- return value -- 0: true -- 1: false -- 2: NA function Distinct(U) if Count(U) == 1 then return 0 end for i, ival in pairs(U) do if type(ival) == "table" then return 2 end end for i, ival in pairs(U) do for j, jval in pairs(U) do if i ~= j then if ival == jval then return 1 end end end end return 0 end -- -- Distinct a store -- return value -- 0: true, removed something from input values -- 1: false, the input values are bad -- 2: NA, values are not touched function DistinctStore(U) local avoid = {} -- Find some values should be avoid for k, v in pairs(U) do if Count(v) == 1 then for _, val in pairs(v) do avoid[k] = val end end end -- -- No variable is set -- Check if the ranges are distinct if Count(avoid) == 0 then for k, v in pairs(U) do for key, val in pairs(U) do if key == k then for _, value in pairs(val) do if table.contains(v, value) then return 2, "Need at least one variable to be set to distinct." end end end end end return 0, "Ranges are distinct" end -- if Distinct(avoid) ~= 0 then return 1, "Set variables are not distinct." end if Count(avoid) == Count(U) then return 0, "All variables are set." end -- some of the variables are set for k, v in pairs(U) do -- if current variable is not set if avoid[k] == nil then -- check if some variables should be avoided local index = 1 while index <= Count(v) do if table.contains(avoid, v[index]) then table.remove(v, index) if Count(v) == 0 then return 1, "Bad result" end else index = index + 1 end end end end -- return 0, "Values are filtered." end -- -- 0: true, good -- 1: false, bad function Branch(tree, var) local result = deepcopy(tree) if result[var] == nil then return 1, "No variable is in the current tree" end if type(result[var]) ~= "table" then return 1, "Tree[var] is not a subtree" end for k, v in pairs(result[var]) do result[var] = {v} tree[var][k] = nil break end return 0, result end -- --[[ local t = {a= {0,1}, b = {2, 3}} local a, b = Branch(t, "a") PrintTable(b, " ") PrintTable(t, " ") ]] -- Distinct a store -- return value -- 0: true, removed something from input values -- 1: false, the input values are bad -- 2: NA, values are not touched function DistinctSubStore(U, V) local subU ={} for _, v in pairs(V) do subU[v] = U[v] end --PrintTable(subU, " ") return DistinctStore(subU) end -- -- function DFS(V, treeTable, cutFuncSet) -- Stack local stack = { List = {}, pop = function(self) local temp = deepcopy(self.List[#self.List]) table.remove(self.List) return temp end, push = function(self, something) table.insert(self.List, something) end } -- local finalStore = {} -- Entire tree is to be examed stack:push(treeTable) return finalStore end -- --[[ local t = {a= {0,1,3}, b = {0,2,3}, c = {5}} local X = DFS(t, DistinctSubStore, {"a", "b"}) PrintTable(X, "") ]] -- -- function GenV(prefix, lx, ly, gx, gy) if lx > gx then local temp = lx lx = gx gx = temp end if ly > gy then local temp = ly ly = gy gy = temp end local V = {} local i = lx local j = ly while i <= gx do j = ly while j <= gy do V[prefix .. i .. j] = prefix .. i .. j j = j + 1 end i = i + 1 end -- return V end -- function MergeSameThing(t) for k, v in ipairs(t) do for key, val in ipairs(t) do if k ~= key then if table.equals(v, val) then t[key] = nil end end end end end -- local S = {} S = U i = 1 while i <= 9 do -- Vertical DistinctSubStore(S, GenV("x_", i, 1, i, 9)) --PrintTable(GenV("x_", i, 1, i, 9), " ") -- Horizontal DistinctSubStore(S, GenV("x_", 1, i, 9, i)) local xs, xd, ys, yd xs = ((i - 1) % 3 + 1) * 3 - 2 xd = xs + 2 if i <= 3 then ys = 1 else if i <= 6 then ys = 4 else ys = 7 end end yd = ys + 2 -- Square DistinctSubStore(S, GenV("x_", xs, ys, xd, yd)) i = i + 1 end -- S = deepcopy(U) S = {S} --print(Count(S)) i = 1 while i <=9 do local c = Count(S) local index = 1 while index <= c do local X = DFS(GenV("x_", i, 1, i, 9), S[index], DistinctSubStore, GenV("x_", i, 1, i, 9)) for k, v in pairs(X) do table.insert(S, v) end index = index + 1 end while index > 1 do table.remove(S, index - 1) index = index - 1 end i = i + 1 end i = 1 while i <=9 do local c = Count(S) local index = 1 while index <= c do local X = DFS(GenV("x_", 1, i, 9, i), S[index], DistinctSubStore, GenV("x_", 1, i, 9, i)) for k, v in pairs(X) do table.insert(S, v) end index = index + 1 end while index > 1 do table.remove(S, index - 1) index = index - 1 end i = i + 1 end --PrintTable(S[1]["x_91"], "") --PrintTable(S, "") --print(Count(S)) --local tf, msg = DistinctSubStore(U, GenV("x_", 1, 1, 1, 9)) --print(tf, msg) --print("x_13") --PrintTable(U["x_13"], " ") --PrintTable(S, " ") --X = MergeSolutions(X) --print(Count(X)) --[[ local c = Count(X) local index = 1 i = 1 while index <= c do while i <= 9 do local Y = DFS(GenV("x_", 1, i, 9, i), X[index], DistinctSubStore, GenV("x_", 1, i, 9, i)) for k, v in pairs(Y) do table.insert(X, v) end print(Count(Y)) i = i + 1 end X[index] = nil index = index + 1 end MergeSolutions(X) --PrintTable(X, "") print(Count(X)) ]]
mit
backburn/Probably
system/modules/combat_tracker.lua
1
6774
-- ProbablyEngine Rotations - https://probablyengine.com/ -- Released under modified BSD, see attached LICENSE. ProbablyEngine.module.register("combatTracker", { current = 0, expire = 15, friendly = { }, enemy = { }, dead = { }, named = { }, blacklist = { }, healthCache = { }, healthCacheCount = { }, }) ProbablyEngine.module.combatTracker.aquireHealth = function(guid, maxHealth, name) if maxHealth then health = UnitHealthMax else health = UnitHealth end local inGroup = GetNumPartyMembers() if inGroup then if GetNumRaidMembers() == 0 then for i=1,inGroup do if guid == UnitGUID("RAID".. i .. "TARGET") then return health("RAID".. i .. "TARGET") end end else for i=1,inGroup do if guid == UnitGUID("PARTY".. i .. "TARGET") then return health("PARTY".. i .. "TARGET") end end if guid == UnitGUID("PLAYERTARGET") then return health("PLAYERTARGET") end end else print(guid, UnitGUID("PLAYERTARGET")) if guid == UnitGUID("PLAYERTARGET") then return health("PLAYERTARGET") end if guid == UnitGUID("MOUSEOVER") then return health("MOUSEOVER") end end -- All health checks failed, do we have a cache of this units health ? if maxHealth then if ProbablyEngine.module.combatTracker.healthCache[name] ~= nil then return ProbablyEngine.module.combatTracker.healthCache[name] end end return false end ProbablyEngine.module.combatTracker.combatCheck = function() local inGroup = GetNumPartyMembers() local inCombat = false if inGroup then if GetNumRaidMembers() ~= 0 then for i = 1, inGroup do if UnitAffectingCombat("RAID".. i) then return true end end else for i = 1, inGroup do if UnitAffectingCombat("PARTY".. i) then return true end end end if UnitAffectingCombat("PLAYER") then return true end else if UnitAffectingCombat("PLAYER") then return true end end return false end ProbablyEngine.timer.register("updateCTHealth", function() if ProbablyEngine.module.combatTracker.combatCheck() then for guid,table in pairs(ProbablyEngine.module.combatTracker.enemy) do local health = ProbablyEngine.module.combatTracker.aquireHealth(guid) if health then -- attempt to aquire max health again if ProbablyEngine.module.combatTracker.enemy[guid]['maxHealth'] == false then local name = ProbablyEngine.module.combatTracker.enemy[guid]['name'] ProbablyEngine.module.combatTracker.enemy[guid]['maxHealth'] = ProbablyEngine.module.combatTracker.aquireHealth(guid, true, name) end ProbablyEngine.module.combatTracker.enemy[guid].health = health end end else ProbablyEngine.module.combatTracker.cleanCT() end end, 100) ProbablyEngine.module.combatTracker.damageUnit = function(guid, damage) if ProbablyEngine.module.combatTracker.enemy[guid] then if damage ~= nil and type(damage) == "number" then if ProbablyEngine.module.combatTracker.enemy[guid] and ProbablyEngine.module.combatTracker.enemy[guid]['health'] then local newHealth = ProbablyEngine.module.combatTracker.enemy[guid]['health'] - damage if newHealth >= 0 then ProbablyEngine.module.combatTracker.enemy[guid]['health'] = newHealth end elseif ProbablyEngine.module.combatTracker.enemy[guid] and ProbablyEngine.module.combatTracker.enemy[guid]['maxHealth'] then local newHealth = ProbablyEngine.module.combatTracker.enemy[guid]['maxHealth'] - damage if newHealth >= 0 then ProbablyEngine.module.combatTracker.enemy[guid]['health'] = newHealth end end if not ProbablyEngine.module.combatTracker.enemy[guid]['time'] then ProbablyEngine.module.combatTracker.enemy[guid]['time'] = time() end unit = ProbablyEngine.module.combatTracker.enemy[guid] if unit and unit['maxHealth'] and unit['health'] then local T = unit.time local N = time() local M = unit.maxHealth local H = unit.health local S = T - N local D = M - H local P = D / S local R = math.floor(math.abs(H / P)) if R > 3600 then R = 1 end ProbablyEngine.module.combatTracker.enemy[guid]['ttd'] = R end end end end ProbablyEngine.module.combatTracker.insert = function(guid, unitname, timestamp) if ProbablyEngine.module.combatTracker.enemy[guid] == nil then local maxHealth = ProbablyEngine.module.combatTracker.aquireHealth(guid, true, unitname) local health = ProbablyEngine.module.combatTracker.aquireHealth(guid) ProbablyEngine.module.combatTracker.enemy[guid] = { } ProbablyEngine.module.combatTracker.enemy[guid]['maxHealth'] = maxHealth ProbablyEngine.module.combatTracker.enemy[guid]['health'] = health ProbablyEngine.module.combatTracker.enemy[guid]['name'] = unitname ProbablyEngine.module.combatTracker.enemy[guid]['time'] = false if maxHealth then -- we got a health value from aquire, store it for later usage if ProbablyEngine.module.combatTracker.healthCacheCount[unitname] then -- we've alreadt seen this type, average it local currentAverage = ProbablyEngine.module.combatTracker.healthCache[unitname] local currentCount = ProbablyEngine.module.combatTracker.healthCacheCount[unitname] local newAverage = (currentAverage + maxHealth) / 2 ProbablyEngine.module.combatTracker.healthCache[unitname] = newAverage ProbablyEngine.module.combatTracker.healthCacheCount[unitname] = currentCount + 1 else -- this is new to use, save it ProbablyEngine.module.combatTracker.healthCache[unitname] = maxHealth ProbablyEngine.module.combatTracker.healthCacheCount[unitname] = 1 end end end end ProbablyEngine.module.combatTracker.cleanCT = function() -- clear tables but save the memory for k,_ in pairs(ProbablyEngine.module.combatTracker.enemy) do ProbablyEngine.module.combatTracker.enemy[k] = nil end for k,_ in pairs(ProbablyEngine.module.combatTracker.blacklist) do ProbablyEngine.module.combatTracker.blacklist[k] = nil end end ProbablyEngine.module.combatTracker.remove = function(guid) ProbablyEngine.module.combatTracker.enemy[guid] = nil end ProbablyEngine.module.combatTracker.tagUnit = function(guid, name) if not ProbablyEngine.module.combatTracker.blacklist[guid] then ProbablyEngine.module.combatTracker.insert(guid, name) end end ProbablyEngine.module.combatTracker.killUnit = function(guid) ProbablyEngine.module.combatTracker.remove(guid, name) ProbablyEngine.module.combatTracker.blacklist[guid] = true end
bsd-3-clause
Ninjistix/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Illeuse.lua
5
1345
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Illeuse -- @zone 80 -- !pos -44.203 2 -36.216 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 2) then local mask = player:getVar("GiftsOfGriffonPlumes"); if (trade:hasItemQty(2528,1) and trade:getItemCount() == 1 and not player:getMaskBit(mask,2)) then player:startEvent(31) -- Gifts of Griffon Trade end end end; function onTrigger(player,npc) player:startEvent(617); -- Default Dialogue end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 31) then -- Gifts of Griffon Trade player:tradeComplete(); local mask = player:getVar("GiftsOfGriffonPlumes"); player:setMaskBit(mask,"GiftsOfGriffonPlumes",2,true); end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Windurst_Walls/npcs/Hiwon-Biwon.lua
5
3500
----------------------------------- -- Area: Windurst Walls -- NPC: Hiwon-Biwon -- Involved In Quest: Making Headlines, Curses, Foiled...Again!? -- Working 100% ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) function testflag(set,flag) return (set % (2*flag) >= flag) end local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES); local CFA2 = player:getQuestStatus(WINDURST,CURSES_FOILED_AGAIN_2); -- Curses,Foiled ... Again!? if (CFA2 == QUEST_ACCEPTED and player:hasItem(552) == false) then player:startEvent(182); -- get Hiwon's hair elseif (CFA2 == QUEST_COMPLETED and MakingHeadlines ~= QUEST_ACCEPTED) then player:startEvent(185); -- New Dialog after CFA2 -- Making Headlines elseif (MakingHeadlines == 1) then prog = player:getVar("QuestMakingHeadlines_var"); -- Variable to track if player has talked to 4 NPCs and a door -- 1 = Kyume -- 2 = Yujuju -- 4 = Hiwom -- 8 = Umumu -- 16 = Mahogany Door if (testflag(tonumber(prog),4) == false) then if (player:getQuestStatus(WINDURST,CURSES_FOILED_AGAIN_1) == 1) then if (math.random(1,2) == 1) then player:startEvent(283); -- Give scoop while sick else player:startEvent(284); -- Give scoop while sick end else player:startEvent(281); -- Give scoop end else player:startEvent(282); -- "Getting back to the maater at hand-wand..." end else local rand = math.random(1,5); if (rand == 1) then print (rand); player:startEvent(305); -- Standard Conversation elseif (rand == 2) then print (rand); player:startEvent(306); -- Standard Conversation elseif (rand == 3) then print (rand); player:startEvent(168); -- Standard Conversation elseif (rand == 4) then print (rand); player:startEvent(170); -- Standard Conversation elseif (rand == 5) then print (rand); player:startEvent(169); -- Standard Conversation end end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); -- Making Headlines if (csid == 281 or csid == 283 or csid == 284) then prog = player:getVar("QuestMakingHeadlines_var"); player:addKeyItem(WINDURST_WALLS_SCOOP); player:messageSpecial(KEYITEM_OBTAINED,WINDURST_WALLS_SCOOP); player:setVar("QuestMakingHeadlines_var",prog+4); -- Curses,Foiled...Again!? elseif (csid == 182) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,552); -- Hiwon's hair else player:addItem(552); player:messageSpecial(ITEM_OBTAINED,552); -- Hiwon's hair end end end;
gpl-3.0
eugenesan/openwrt-luci
applications/luci-asterisk/luasrc/model/cbi/asterisk.lua
80
5333
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- cbimap = Map("asterisk", "asterisk", "") asterisk = cbimap:section(TypedSection, "asterisk", "Asterisk General Options", "") asterisk.anonymous = true agidir = asterisk:option(Value, "agidir", "AGI directory", "") agidir.rmempty = true cache_record_files = asterisk:option(Flag, "cache_record_files", "Cache recorded sound files during recording", "") cache_record_files.rmempty = true debug = asterisk:option(Value, "debug", "Debug Level", "") debug.rmempty = true dontwarn = asterisk:option(Flag, "dontwarn", "Disable some warnings", "") dontwarn.rmempty = true dumpcore = asterisk:option(Flag, "dumpcore", "Dump core on crash", "") dumpcore.rmempty = true highpriority = asterisk:option(Flag, "highpriority", "High Priority", "") highpriority.rmempty = true initcrypto = asterisk:option(Flag, "initcrypto", "Initialise Crypto", "") initcrypto.rmempty = true internal_timing = asterisk:option(Flag, "internal_timing", "Use Internal Timing", "") internal_timing.rmempty = true logdir = asterisk:option(Value, "logdir", "Log directory", "") logdir.rmempty = true maxcalls = asterisk:option(Value, "maxcalls", "Maximum number of calls allowed", "") maxcalls.rmempty = true maxload = asterisk:option(Value, "maxload", "Maximum load to stop accepting new calls", "") maxload.rmempty = true nocolor = asterisk:option(Flag, "nocolor", "Disable console colors", "") nocolor.rmempty = true record_cache_dir = asterisk:option(Value, "record_cache_dir", "Sound files Cache directory", "") record_cache_dir.rmempty = true record_cache_dir:depends({ ["cache_record_files"] = "true" }) rungroup = asterisk:option(Flag, "rungroup", "The Group to run as", "") rungroup.rmempty = true runuser = asterisk:option(Flag, "runuser", "The User to run as", "") runuser.rmempty = true spooldir = asterisk:option(Value, "spooldir", "Voicemail Spool directory", "") spooldir.rmempty = true systemname = asterisk:option(Value, "systemname", "Prefix UniquID with system name", "") systemname.rmempty = true transcode_via_sln = asterisk:option(Flag, "transcode_via_sln", "Build transcode paths via SLINEAR, not directly", "") transcode_via_sln.rmempty = true transmit_silence_during_record = asterisk:option(Flag, "transmit_silence_during_record", "Transmit SLINEAR silence while recording a channel", "") transmit_silence_during_record.rmempty = true verbose = asterisk:option(Value, "verbose", "Verbose Level", "") verbose.rmempty = true zone = asterisk:option(Value, "zone", "Time Zone", "") zone.rmempty = true hardwarereboot = cbimap:section(TypedSection, "hardwarereboot", "Reload Hardware Config", "") method = hardwarereboot:option(ListValue, "method", "Reboot Method", "") method:value("web", "Web URL (wget)") method:value("system", "program to run") method.rmempty = true param = hardwarereboot:option(Value, "param", "Parameter", "") param.rmempty = true iaxgeneral = cbimap:section(TypedSection, "iaxgeneral", "IAX General Options", "") iaxgeneral.anonymous = true iaxgeneral.addremove = true allow = iaxgeneral:option(MultiValue, "allow", "Allow Codecs", "") allow:value("alaw", "alaw") allow:value("gsm", "gsm") allow:value("g726", "g726") allow.rmempty = true canreinvite = iaxgeneral:option(ListValue, "canreinvite", "Reinvite/redirect media connections", "") canreinvite:value("yes", "Yes") canreinvite:value("nonat", "Yes when not behind NAT") canreinvite:value("update", "Use UPDATE rather than INVITE for path redirection") canreinvite:value("no", "No") canreinvite.rmempty = true static = iaxgeneral:option(Flag, "static", "Static", "") static.rmempty = true writeprotect = iaxgeneral:option(Flag, "writeprotect", "Write Protect", "") writeprotect.rmempty = true sipgeneral = cbimap:section(TypedSection, "sipgeneral", "Section sipgeneral", "") sipgeneral.anonymous = true sipgeneral.addremove = true allow = sipgeneral:option(MultiValue, "allow", "Allow codecs", "") allow:value("ulaw", "ulaw") allow:value("alaw", "alaw") allow:value("gsm", "gsm") allow:value("g726", "g726") allow.rmempty = true port = sipgeneral:option(Value, "port", "SIP Port", "") port.rmempty = true realm = sipgeneral:option(Value, "realm", "SIP realm", "") realm.rmempty = true moh = cbimap:section(TypedSection, "moh", "Music On Hold", "") application = moh:option(Value, "application", "Application", "") application.rmempty = true application:depends({ ["asterisk.moh.mode"] = "custom" }) directory = moh:option(Value, "directory", "Directory of Music", "") directory.rmempty = true mode = moh:option(ListValue, "mode", "Option mode", "") mode:value("system", "program to run") mode:value("files", "Read files from directory") mode:value("quietmp3", "Quite MP3") mode:value("mp3", "Loud MP3") mode:value("mp3nb", "unbuffered MP3") mode:value("quietmp3nb", "Quiet Unbuffered MP3") mode:value("custom", "Run a custom application") mode.rmempty = true random = moh:option(Flag, "random", "Random Play", "") random.rmempty = true return cbimap
apache-2.0
codedash64/Urho3D
bin/Data/LuaScripts/13_Ragdolls.lua
24
19430
-- Ragdoll example. -- This sample demonstrates: -- - Detecting physics collisions -- - Moving an AnimatedModel's bones with physics and connecting them with constraints -- - Using rolling friction to stop rolling objects from moving infinitely require "LuaScripts/Utilities/Sample" function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update and render post-update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) -- Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must -- exist before creating drawable components, the PhysicsWorld must exist before creating physics components. -- Finally, create a DebugRenderer component so that we can draw physics debug geometry scene_:CreateComponent("Octree") scene_:CreateComponent("PhysicsWorld") scene_:CreateComponent("DebugRenderer") -- Create a Zone component for ambient lighting & fog control local zoneNode = scene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.15, 0.15, 0.15) zone.fogColor = Color(0.5, 0.5, 0.7) zone.fogStart = 100.0 zone.fogEnd = 300.0 -- Create a directional light to the world. Enable cascaded shadows on it local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.castShadows = true light.shadowBias = BiasParameters(0.00025, 0.5) -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8) -- Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y local floorNode = scene_:CreateChild("Floor") floorNode.position = Vector3(0.0, -0.5, 0.0) floorNode.scale = Vector3(500.0, 1.0, 500.0) local floorObject = floorNode:CreateComponent("StaticModel") floorObject.model = cache:GetResource("Model", "Models/Box.mdl") floorObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml") -- Make the floor physical by adding RigidBody and CollisionShape components local body = floorNode:CreateComponent("RigidBody") -- We will be spawning spherical objects in this sample. The ground also needs non-zero rolling friction so that -- the spheres will eventually come to rest body.rollingFriction = 0.15 local shape = floorNode:CreateComponent("CollisionShape") -- Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the -- rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.) shape:SetBox(Vector3(1.0, 1.0, 1.0)) -- Create animated models for z = -1, 1 do for x = -4, 4 do local modelNode = scene_:CreateChild("Jack") modelNode.position = Vector3(x * 5.0, 0.0, z * 5.0) modelNode.rotation = Quaternion(0.0, 180.0, 0.0) local modelObject = modelNode:CreateComponent("AnimatedModel") modelObject.model = cache:GetResource("Model", "Models/Jack.mdl") modelObject.material = cache:GetResource("Material", "Materials/Jack.xml") modelObject.castShadows = true -- Set the model to also update when invisible to avoid staying invisible when the model should come into -- view, but does not as the bounding box is not updated modelObject.updateInvisible = true -- Create a rigid body and a collision shape. These will act as a trigger for transforming the -- model into a ragdoll when hit by a moving object local body = modelNode:CreateComponent("RigidBody") -- The trigger mode makes the rigid body only detect collisions, but impart no forces on the -- colliding objects body.trigger = true local shape = modelNode:CreateComponent("CollisionShape") -- Create the capsule shape with an offset so that it is correctly aligned with the model, which -- has its origin at the feet shape:SetCapsule(0.7, 2.0, Vector3(0.0, 1.0, 0.0)) -- Create a custom script object that reacts to collisions and creates the ragdoll modelNode:CreateScriptObject("CreateRagdoll") end end -- Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside -- the scene, because we want it to be unaffected by scene load / save cameraNode = Node() local camera = cameraNode:CreateComponent("Camera") camera.farClip = 300.0 -- Set an initial position for the camera scene node above the floor cameraNode.position = Vector3(0.0, 5.0, -20.0) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText( "Use WASD keys and mouse to move\n".. "LMB to spawn physics objects\n".. "F5 to save scene, F7 to load\n".. "Space to toggle physics debug geometry") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- The text has multiple rows. Center them in relation to each other instructionText.textAlignment = HA_CENTER -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request -- debug geometry SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate") end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- 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 between -90 and 90 degrees local mouseMove = input.mouseMove yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x pitch = pitch +MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end -- "Shoot" a physics object with left mousebutton if input:GetMouseButtonPress(MOUSEB_LEFT) then SpawnObject() end -- Check for loading/saving the scene. Save the scene to the file Data/Scenes/Physics.xml relative to the executable -- directory if input:GetKeyPress(KEY_F5) then scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/Ragdolls.xml") end if input:GetKeyPress(KEY_F7) then scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/Ragdolls.xml") end -- Toggle debug geometry with space if input:GetKeyPress(KEY_SPACE) then drawDebug = not drawDebug end end function SpawnObject() local boxNode = scene_:CreateChild("Sphere") boxNode.position = cameraNode.position boxNode.rotation = cameraNode.rotation boxNode:SetScale(0.25) local boxObject = boxNode:CreateComponent("StaticModel") boxObject.model = cache:GetResource("Model", "Models/Sphere.mdl") boxObject.material = cache:GetResource("Material", "Materials/StoneSmall.xml") boxObject.castShadows = true local body = boxNode:CreateComponent("RigidBody") body.mass = 1.0 body.rollingFriction = 0.15 local shape = boxNode:CreateComponent("CollisionShape") shape:SetSphere(1.0) local OBJECT_VELOCITY = 10.0 -- Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component -- to overcome gravity better body.linearVelocity = cameraNode.rotation * Vector3(0.0, 0.25, 1.0) * OBJECT_VELOCITY end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end function HandlePostRenderUpdate(eventType, eventData) -- If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret if drawDebug then scene_:GetComponent("PhysicsWorld"):DrawDebugGeometry(true) end end -- CreateRagdoll script object class CreateRagdoll = ScriptObject() function CreateRagdoll:Start() -- Subscribe physics collisions that concern this scene node self:SubscribeToEvent(self.node, "NodeCollision", "CreateRagdoll:HandleNodeCollision") end function CreateRagdoll:HandleNodeCollision(eventType, eventData) -- Get the other colliding body, make sure it is moving (has nonzero mass) local otherBody = eventData["OtherBody"]:GetPtr("RigidBody") if otherBody.mass > 0.0 then -- We do not need the physics components in the AnimatedModel's root scene node anymore self.node:RemoveComponent("RigidBody") self.node:RemoveComponent("CollisionShape") -- Create RigidBody & CollisionShape components to bones self:CreateRagdollBone("Bip01_Pelvis", SHAPE_BOX, Vector3(0.3, 0.2, 0.25), Vector3(0.0, 0.0, 0.0), Quaternion(0.0, 0.0, 0.0)) self:CreateRagdollBone("Bip01_Spine1", SHAPE_BOX, Vector3(0.35, 0.2, 0.3), Vector3(0.15, 0.0, 0.0), Quaternion(0.0, 0.0, 0.0)) self:CreateRagdollBone("Bip01_L_Thigh", SHAPE_CAPSULE, Vector3(0.175, 0.45, 0.175), Vector3(0.25, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_R_Thigh", SHAPE_CAPSULE, Vector3(0.175, 0.45, 0.175), Vector3(0.25, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_L_Calf", SHAPE_CAPSULE, Vector3(0.15, 0.55, 0.15), Vector3(0.25, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_R_Calf", SHAPE_CAPSULE, Vector3(0.15, 0.55, 0.15), Vector3(0.25, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_Head", SHAPE_BOX, Vector3(0.2, 0.2, 0.2), Vector3(0.1, 0.0, 0.0), Quaternion(0.0, 0.0, 0.0)) self:CreateRagdollBone("Bip01_L_UpperArm", SHAPE_CAPSULE, Vector3(0.15, 0.35, 0.15), Vector3(0.1, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_R_UpperArm", SHAPE_CAPSULE, Vector3(0.15, 0.35, 0.15), Vector3(0.1, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_L_Forearm", SHAPE_CAPSULE, Vector3(0.125, 0.4, 0.125), Vector3(0.2, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_R_Forearm", SHAPE_CAPSULE, Vector3(0.125, 0.4, 0.125), Vector3(0.2, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) -- Create Constraints between bones self:CreateRagdollConstraint("Bip01_L_Thigh", "Bip01_Pelvis", CONSTRAINT_CONETWIST, Vector3(0.0, 0.0, -1.0), Vector3(0.0, 0.0, 1.0), Vector2(45.0, 45.0), Vector2(0.0, 0.0), true) self:CreateRagdollConstraint("Bip01_R_Thigh", "Bip01_Pelvis", CONSTRAINT_CONETWIST, Vector3(0.0, 0.0, -1.0), Vector3(0.0, 0.0, 1.0), Vector2(45.0, 45.0), Vector2(0.0, 0.0), true) self:CreateRagdollConstraint("Bip01_L_Calf", "Bip01_L_Thigh", CONSTRAINT_HINGE, Vector3(0.0, 0.0, -1.0), Vector3(0.0, 0.0, -1.0), Vector2(90.0, 0.0), Vector2(0.0, 0.0), true) self:CreateRagdollConstraint("Bip01_R_Calf", "Bip01_R_Thigh", CONSTRAINT_HINGE, Vector3(0.0, 0.0, -1.0), Vector3(0.0, 0.0, -1.0), Vector2(90.0, 0.0), Vector2(0.0, 0.0), true) self:CreateRagdollConstraint("Bip01_Spine1", "Bip01_Pelvis", CONSTRAINT_HINGE, Vector3(0.0, 0.0, 1.0), Vector3(0.0, 0.0, 1.0), Vector2(45.0, 0.0), Vector2(-10.0, 0.0), true) self:CreateRagdollConstraint("Bip01_Head", "Bip01_Spine1", CONSTRAINT_CONETWIST, Vector3(-1.0, 0.0, 0.0), Vector3(-1.0, 0.0, 0.0), Vector2(0.0, 30.0), Vector2(0.0, 0.0), true) self:CreateRagdollConstraint("Bip01_L_UpperArm", "Bip01_Spine1", CONSTRAINT_CONETWIST, Vector3(0.0, -1.0, 0.0), Vector3(0.0, 1.0, 0.0), Vector2(45.0, 45.0), Vector2(0.0, 0.0), false) self:CreateRagdollConstraint("Bip01_R_UpperArm", "Bip01_Spine1", CONSTRAINT_CONETWIST, Vector3(0.0, -1.0, 0.0), Vector3(0.0, 1.0, 0.0), Vector2(45.0, 45.0), Vector2(0.0, 0.0), false) self:CreateRagdollConstraint("Bip01_L_Forearm", "Bip01_L_UpperArm", CONSTRAINT_HINGE, Vector3(0.0, 0.0, -1.0), Vector3(0.0, 0.0, -1.0), Vector2(90.0, 0.0), Vector2(0.0, 0.0), true) self:CreateRagdollConstraint("Bip01_R_Forearm", "Bip01_R_UpperArm", CONSTRAINT_HINGE, Vector3(0.0, 0.0, -1.0), Vector3(0.0, 0.0, -1.0), Vector2(90.0, 0.0), Vector2(0.0, 0.0), true) -- Disable keyframe animation from all bones so that they will not interfere with the ragdoll local model = self.node:GetComponent("AnimatedModel") local skeleton = model.skeleton for i = 0, skeleton.numBones - 1 do skeleton:GetBone(i).animated = false end -- Finally remove self (the ScriptInstance which holds this script object) from the scene node. Note that this must -- be the last operation performed in the function self.instance:Remove() end end function CreateRagdoll:CreateRagdollBone(boneName, type, size, position, rotation) -- Find the correct child scene node recursively local boneNode = self.node:GetChild(boneName, true) if boneNode == nil then print("Could not find bone " .. boneName .. " for creating ragdoll physics components\n") return end local body = boneNode:CreateComponent("RigidBody") -- Set mass to make movable body.mass = 1.0 -- Set damping parameters to smooth out the motion body.linearDamping = 0.05 body.angularDamping = 0.85 -- Set rest thresholds to ensure the ragdoll rigid bodies come to rest to not consume CPU endlessly body.linearRestThreshold = 1.5 body.angularRestThreshold = 2.5 local shape = boneNode:CreateComponent("CollisionShape") -- We use either a box or a capsule shape for all of the bones if type == SHAPE_BOX then shape:SetBox(size, position, rotation) else shape:SetCapsule(size.x, size.y, position, rotation) end end function CreateRagdoll:CreateRagdollConstraint(boneName, parentName, type, axis, parentAxis, highLimit, lowLimit, disableCollision) local boneNode = self.node:GetChild(boneName, true) local parentNode = self.node:GetChild(parentName, true) if boneNode == nil then print("Could not find bone " .. boneName .. " for creating ragdoll constraint\n") return end if parentNode == nil then print("Could not find bone " .. parentName .. " for creating ragdoll constraint\n") return end local constraint = boneNode:CreateComponent("Constraint") constraint.constraintType = type -- Most of the constraints in the ragdoll will work better when the connected bodies don't collide against each other constraint.disableCollision = disableCollision -- The connected body must be specified before setting the world position constraint.otherBody = parentNode:GetComponent("RigidBody") -- Position the constraint at the child bone we are connecting constraint.worldPosition = boneNode.worldPosition -- Configure axes and limits constraint.axis = axis constraint.otherAxis = parentAxis constraint.highLimit = highLimit constraint.lowLimit = lowLimit end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Spawn</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" .. " <attribute name=\"Text\" value=\"LEFT\" />" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"SPACE\" />" .. " </element>" .. " </add>" .. "</patch>" end
mit
Ninjistix/darkstar
scripts/zones/Metalworks/npcs/Cid.lua
5
11264
----------------------------------- -- Area: Metalworks -- NPC: Cid -- Starts & Finishes Quest: Cid's Secret, The Usual, Dark Puppet (start) -- Involved in Mission: Bastok 7-1 -- !pos -12 -12 1 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getCurrentMission(BASTOK) == THE_CRYSTAL_LINE and player:getVar("MissionStatus") == 1) then if (trade:getItemQty(613,1) and trade:getItemCount() == 1) then player:startEvent(506); end end end; function onTrigger(player,npc) local currentday = tonumber(os.date("%j")); local CidsSecret = player:getQuestStatus(BASTOK,CID_S_SECRET); local LetterKeyItem = player:hasKeyItem(UNFINISHED_LETTER); local currentMission = player:getCurrentMission(BASTOK); local currentCOPMission = player:getCurrentMission(COP); local UlmiaPath = player:getVar("COP_Ulmia_s_Path"); local TenzenPath = player:getVar("COP_Tenzen_s_Path"); local LouverancePath = player:getVar("COP_Louverance_s_Path"); local TreePathAv=0; if (currentCOPMission == DAWN and player:getVar("PromathiaStatus")==3 and player:getVar("Promathia_kill_day")~=currentday and player:getVar("COP_tenzen_story")== 0 ) then player:startEvent(897); -- COP event elseif (currentCOPMission == CALM_BEFORE_THE_STORM and player:hasKeyItem(LETTERS_FROM_ULMIA_AND_PRISHE) == false and player:getVar("COP_Dalham_KILL") == 2 and player:getVar("COP_Boggelmann_KILL") == 2 and player:getVar("Cryptonberry_Executor_KILL")==2) then player:startEvent(892); -- COP event elseif (currentCOPMission == FIRE_IN_THE_EYES_OF_MEN and player:getVar("PromathiaStatus")==2 and player:getVar("Promathia_CID_timer")~=VanadielDayOfTheYear()) then player:startEvent(890); -- COP event elseif (currentCOPMission == FIRE_IN_THE_EYES_OF_MEN and player:getVar("PromathiaStatus")==1) then player:startEvent(857); -- COP event elseif (currentCOPMission == ONE_TO_BE_FEARED and player:getVar("PromathiaStatus") == 0) then player:startEvent(856); -- COP event elseif (currentCOPMission == THREE_PATHS and LouverancePath == 6 ) then player:startEvent(852); -- COP event elseif (currentCOPMission == THREE_PATHS and LouverancePath == 9 ) then if (TenzenPath==11 and UlmiaPath==8) then TreePathAv=6; elseif (TenzenPath==11) then TreePathAv=2; elseif (UlmiaPath==8) then TreePathAv=4; else TreePathAv=1; end player:startEvent(853,TreePathAv); -- COP event elseif (currentCOPMission == THREE_PATHS and TenzenPath == 10 ) then if (UlmiaPath==8 and LouverancePath==10) then TreePathAv=5; elseif (LouverancePath==10) then TreePathAv=3; elseif (UlmiaPath==8) then TreePathAv=4; else TreePathAv=1; end player:startEvent(854,TreePathAv); -- COP event elseif (currentCOPMission == THREE_PATHS and UlmiaPath == 7 ) then if (TenzenPath==11 and LouverancePath==10) then TreePathAv=3; elseif (LouverancePath==10) then TreePathAv=1; elseif (TenzenPath==11) then TreePathAv=2; else TreePathAv=0; end player:startEvent(855,TreePathAv); -- COP event elseif (currentCOPMission == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus") > 8) then player:startEvent(850); -- COP event elseif (currentCOPMission == THE_ENDURING_TUMULT_OF_WAR and player:getVar("PromathiaStatus")==1) then player:startEvent(849); -- COP event elseif (currentCOPMission == THE_CALL_OF_THE_WYRMKING and player:getVar("PromathiaStatus")==1) then player:startEvent(845); -- COP event elseif (currentCOPMission == THE_ROAD_FORKS and player:getVar("EMERALD_WATERS_Status")== 7 and player:getVar("MEMORIES_OF_A_MAIDEN_Status")== 12) then --two paths are finished ? player:startEvent(847); -- COP event 3.3 elseif (player:getMainJob() == JOBS.DRK and player:getMainLvl() >= AF2_QUEST_LEVEL and player:getQuestStatus(BASTOK,DARK_LEGACY) == QUEST_COMPLETED and player:getQuestStatus(BASTOK,DARK_PUPPET) == QUEST_AVAILABLE) then player:startEvent(760); -- Start Quest "Dark Puppet" elseif (currentMission == GEOLOGICAL_SURVEY) then if (player:hasKeyItem(RED_ACIDITY_TESTER)) then player:startEvent(504); elseif (player:hasKeyItem(BLUE_ACIDITY_TESTER) == false) then player:startEvent(503); end elseif (currentMission == THE_CRYSTAL_LINE) then if (player:hasKeyItem(C_L_REPORTS)) then player:showText(npc,MISSION_DIALOG_CID_TO_AYAME); else player:startEvent(505); end elseif (currentMission == THE_FINAL_IMAGE and player:getVar("MissionStatus") == 0) then player:startEvent(763); -- Bastok Mission 7-1 elseif (currentMission == THE_FINAL_IMAGE and player:getVar("MissionStatus") == 2) then player:startEvent(764); -- Bastok Mission 7-1 (with Ki) --Begin Cid's Secret elseif (player:getFameLevel(BASTOK) >= 4 and CidsSecret == QUEST_AVAILABLE) then player:startEvent(507); elseif (CidsSecret == QUEST_ACCEPTED and LetterKeyItem == false and player:getVar("CidsSecret_Event") == 1) then player:startEvent(508); --After talking to Hilda, Cid gives information on the item she needs elseif (CidsSecret == QUEST_ACCEPTED and LetterKeyItem == false) then player:startEvent(502); --Reminder dialogue from Cid if you have not spoken to Hilda elseif (CidsSecret == QUEST_ACCEPTED and LetterKeyItem) then player:startEvent(509); --End Cid's Secret else player:startEvent(500); -- Standard Dialogue end end; -- 503 504 505 506 500 502 0x02d0 507 508 509 0x025b 0x02f3 760 0x03f2 763 764 -- 0x030c 0x030e 0x031b 0x031c 0x031d 0x031e 0x031f 0x035d 0x034e 0x0350 0x035e 0x035f 0x0353 0x035a 0x034d 0x034f -- 849 850 852 853 854 855 856 857 0x0364 0x0365 0x0373 0x0374 0x037a 0x037b 0x037c 0x037d -- 0x037e 0x037f 897 0x0382 function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- local currentday = tonumber(os.date("%j")); -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 897) then player:setVar("COP_tenzen_story",1); elseif (csid == 892) then player:addKeyItem(LETTERS_FROM_ULMIA_AND_PRISHE); player:messageSpecial(KEYITEM_OBTAINED,LETTERS_FROM_ULMIA_AND_PRISHE); elseif (csid == 890) then player:setVar("PromathiaStatus",0); player:setVar("Promathia_CID_timer",0); player:completeMission(COP,FIRE_IN_THE_EYES_OF_MEN); player:addMission(COP,CALM_BEFORE_THE_STORM); elseif (csid == 857) then player:setVar("PromathiaStatus",2); player:setVar("Promathia_CID_timer",VanadielDayOfTheYear()); elseif (csid == 855) then player:setVar("COP_Ulmia_s_Path",8); elseif (csid == 854) then player:setVar("COP_Tenzen_s_Path",11); elseif (csid == 853) then player:setVar("COP_Louverance_s_Path",10); elseif (csid == 852) then player:setVar("COP_Louverance_s_Path",7); elseif (csid == 850) then player:setVar("PromathiaStatus",0); player:completeMission(COP,DESIRES_OF_EMPTINESS); player:addMission(COP,THREE_PATHS); elseif (csid == 849) then player:setVar("PromathiaStatus",2); elseif (csid == 856) then player:setVar("PromathiaStatus",1); elseif (csid == 845) then player:setVar("PromathiaStatus",0); player:completeMission(COP,THE_CALL_OF_THE_WYRMKING); player:addMission(COP,A_VESSEL_WITHOUT_A_CAPTAIN); elseif (csid == 847) then -- finishing mission 3.3 and all sub missions player:setVar("EMERALD_WATERS_Status",0); player:setVar("MEMORIES_OF_A_MAIDEN_Status",0); player:completeMission(COP,THE_ROAD_FORKS); player:addMission(COP,DESCENDANTS_OF_A_LINE_LOST); player:completeMission(COP,DESCENDANTS_OF_A_LINE_LOST); player:addMission(COP,COMEDY_OF_ERRORS_ACT_I); player:completeMission(COP,COMEDY_OF_ERRORS_ACT_I); player:addMission(COP,TENDING_AGED_WOUNDS ); --starting 3.4 COP mission elseif (csid == 760) then player:addQuest(BASTOK,DARK_PUPPET); player:setVar("darkPuppetCS",1); elseif (csid == 503) then player:addKeyItem(BLUE_ACIDITY_TESTER); player:messageSpecial(KEYITEM_OBTAINED, BLUE_ACIDITY_TESTER); elseif (csid == 504 or csid == 764) then finishMissionTimeline(player,1,csid,option); elseif (csid == 505 and option == 0) then if (player:getVar("MissionStatus") == 0) then if (player:getFreeSlotsCount(0) >= 1) then crystal = math.random(4096,4103); player:addItem(crystal); player:messageSpecial(ITEM_OBTAINED, crystal); player:setVar("MissionStatus",1); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal); end end elseif (csid == 506 and option == 0) then player:tradeComplete(); player:addKeyItem(C_L_REPORTS); player:messageSpecial(KEYITEM_OBTAINED, C_L_REPORTS); elseif (csid == 763) then player:setVar("MissionStatus",1); elseif (csid == 507) then player:addQuest(BASTOK,CID_S_SECRET); elseif (csid == 509) then if (player:getFreeSlotsCount(0) >= 1) then player:delKeyItem(UNFINISHED_LETTER); player:setVar("CidsSecret_Event",0); player:addItem(13570); player:messageSpecial(ITEM_OBTAINED,13570); -- Ram Mantle player:addFame(BASTOK,30); player:completeQuest(BASTOK,CID_S_SECRET); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13570); end end -- complete chapter "tree path" if (csid == 853 or csid == 854 or csid == 855) then if (player:getVar("COP_Tenzen_s_Path")==11 and player:getVar("COP_Ulmia_s_Path")==8 and player:getVar("COP_Louverance_s_Path")==10) then player:completeMission(COP,THREE_PATHS); player:addMission(COP,FOR_WHOM_THE_VERSE_IS_SUNG); player:setVar("PromathiaStatus",0); end end end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/items/prized_angler_stewpot.lua
3
1751
----------------------------------------- -- ID: 5613 -- Item: Prized Angler's Stewpot -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10% (cap 200) -- MP +20 -- Dexterity 4 -- Agility 2 -- Mind 2 -- HP Recovered while healing 9 -- MP Recovered while healing 3 -- Accuracy 15% Cap 45 -- Ranged Accuracy 15% Cap 45 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5613); end; function onEffectGain(target, effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_FOOD_HP_CAP, 200); target:addMod(MOD_MP, 20); target:addMod(MOD_DEX, 4); target:addMod(MOD_AGI, 2); target:addMod(MOD_MND, 2); target:addMod(MOD_HPHEAL, 9); target:addMod(MOD_MPHEAL, 3); target:addMod(MOD_FOOD_ACCP, 15); target:addMod(MOD_FOOD_ACC_CAP, 45); target:addMod(MOD_FOOD_RACCP, 15); target:addMod(MOD_FOOD_RACC_CAP, 45); end; function onEffectLose(target, effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_FOOD_HP_CAP, 200); target:delMod(MOD_MP, 20); target:delMod(MOD_DEX, 4); target:delMod(MOD_AGI, 2); target:delMod(MOD_MND, 2); target:delMod(MOD_HPHEAL, 9); target:delMod(MOD_MPHEAL, 3); target:delMod(MOD_FOOD_ACCP, 15); target:delMod(MOD_FOOD_ACC_CAP, 45); target:delMod(MOD_FOOD_RACCP, 15); target:delMod(MOD_FOOD_RACC_CAP, 45); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/spells/sleep.lua
5
1264
----------------------------------------- -- Spell: Sleep I ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local duration = 60; if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then duration = duration * 2; end caster:delStatusEffect(EFFECT_SABOTEUR); local pINT = caster:getStat(MOD_INT); local mINT = target:getStat(MOD_INT); local dINT = (pINT - mINT); local params = {}; params.diff = nil; params.attribute = MOD_INT; params.skillType = ENFEEBLING_MAGIC_SKILL; params.bonus = 0; params.effect = EFFECT_SLEEP_I; resm = applyResistanceEffect(caster, target, spell, params); if (resm < 0.5) then spell:setMsg(msgBasic.MAGIC_RESIST); -- resist message return EFFECT_SLEEP_I; end duration = duration * resm; if (target:addStatusEffect(EFFECT_SLEEP_I,1,0,duration)) then spell:setMsg(msgBasic.MAGIC_ENFEEB_IS); else spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end return EFFECT_SLEEP_I; end;
gpl-3.0
flori/dynadns
dyna_client.lua
1
1484
#!/usr/bin/env lua -- dynadns client script, that can be run on a openwrt router -- Compute a md5 sum by calling out to md5sum shell command. Lame, I know. function md5(string) local filename = "/tmp/dynadns.tmp" local sum = io.popen("md5sum >" .. filename, "w") sum:write(string) sum:close() sum = io.open(filename, "r") local result = sum:read() sum:close() return result:match("([0-9a-f]+)") end -- Determine our IP on the side of our VPN endpoint using curl, ugh. function determine_ip() local ip = io.popen("curl -s -H 'Host: whatismyip.akamai.com' 80.239.148.8", "r") local addr = ip:read() ip:close() return addr end -- Setup our data for the challenge/response local address = arg[1] or determine_ip() local ping_host, ping_password = os.getenv("PING_HOST"), os.getenv("PING_PASSWORD") local host, port = "lilly.ping.de", 5353 -- Now, let's do this! local socket = require("socket") local ip = assert(socket.dns.toip(host)) local tcp = assert(socket.tcp()) tcp:settimeout(10) assert(tcp:connect(ip, port)) local challenge = tcp:receive() print(">>> " .. challenge) local challenge_token = string.match(challenge, "CHA=([0-9a-f]+)") assert(challenge_token) local md5_response = md5(table.concat({ "md5", ping_host, ping_password, challenge_token, address }, "")) local response = table.concat({ "RES=md5", md5_response, ping_host, address }, ",") print("<<< " .. response) tcp:send(response .. "\n") result = tcp:receive() print(">>> " .. result)
gpl-2.0
Ninjistix/darkstar
scripts/globals/items/twashtar.lua
3
3305
----------------------------------------- -- ID: 19457 -- Item: Twashtar ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/msg"); require("scripts/globals/weaponskills"); require("scripts/globals/weaponskillids"); ----------------------------------- local NAME_WEAPONSKILL = "AFTERMATH_TWASHTAR"; local NAME_EFFECT_LOSE = "AFTERMATH_LOST_TWASHSTAR"; -- https://www.bg-wiki.com/bg/Relic_Aftermath local aftermathTable = {}; -- Twashtar 85 aftermathTable[19457] = { { -- Tier 1 duration = 30, mods = { { id = MOD_REM_OCC_DO_DOUBLE_DMG, power = 30 } } }, { -- Tier 2 duration = 60, mods = { { id = MOD_REM_OCC_DO_DOUBLE_DMG, power = 40 } } }, { -- Tier 3 duration = 60, mods = { { id = MOD_REM_OCC_DO_DOUBLE_DMG, power = 50 } } } }; aftermathTable[19535] = aftermathTable[19457]; -- Twashtar (90) aftermathTable[19633] = aftermathTable[19457]; -- Twashtar (95) aftermathTable[19806] = aftermathTable[19457]; -- Twashtar (99) aftermathTable[19854] = aftermathTable[19457]; -- Twashtar (99/II) aftermathTable[20563] = aftermathTable[19457]; -- Twashtar (119) aftermathTable[20564] = aftermathTable[19457]; -- Twashtar (119/II) -- Twashtar (119/III) aftermathTable[20587] = { { -- Tier 1 duration = 60, mods = { { id = MOD_REM_OCC_DO_TRIPLE_DMG, power = 30 } } }, { -- Tier 2 duration = 120, mods = { { id = MOD_REM_OCC_DO_TRIPLE_DMG, power = 40 } } }, { -- Tier 3 duration = 180, mods = { { id = MOD_REM_OCC_DO_TRIPLE_DMG, power = 50 } } } }; function onWeaponskill(user, target, wsid, tp, action) if (wsid == WEAPONSKILL_RUDRAS_STORM) then -- Rudra's Storm onry local itemId = user:getEquipID(SLOT_MAIN); if (shouldApplyAftermath(user, tp)) then if (aftermathTable[itemId]) then -- Apply the effect and add mods addEmpyreanAftermathEffect(user, tp, aftermathTable[itemId]); -- Add a listener for when aftermath wears (to remove mods) user:addListener("EFFECT_LOSE", NAME_EFFECT_LOSE, aftermathLost); end end end end function aftermathLost(target, effect) if (effect:getType() == EFFECT_AFTERMATH) then local itemId = target:getEquipID(SLOT_MAIN); if (aftermathTable[itemId]) then -- Remove mods removeEmpyreanAftermathEffect(target, effect, aftermathTable[itemId]); -- Remove the effect listener target:removeListener(NAME_EFFECT_LOSE); end end end function onItemCheck(player, param, caster) if (param == ITEMCHECK_EQUIP) then player:addListener("WEAPONSKILL_USE", NAME_WEAPONSKILL, onWeaponskill); elseif (param == ITEMCHECK_UNEQUIP) then -- Make sure we clean up the effect and mods if (player:hasStatusEffect(EFFECT_AFTERMATH)) then aftermathLost(player, player:getStatusEffect(EFFECT_AFTERMATH)); end player:removeListener(NAME_WEAPONSKILL); end return 0; end
gpl-3.0
ocurr/hammerspoon
extensions/host/init.lua
14
1207
--- === hs.host === --- --- Inspect information about the machine Hammerspoon is running on --- --- Notes: --- * The network/hostname calls can be slow, as network resolution calls can be called, which are synchronous and will block Hammerspoon until they complete. local host = require "hs.host.internal" local fnutils = require "hs.fnutils" local __tostring_for_tables = function(self) local result = "" local width = 0 for i,v in fnutils.sortByKeys(self) do if type(i) == "string" and width < i:len() then width = i:len() end end for i,v in fnutils.sortByKeys(self) do if type(i) == "string" then result = result..string.format("%-"..tostring(width).."s %s\n", i, tostring(v)) end end return result end local vmStat = host.vmStat local cpuUsage = host.cpuUsage host.vmStat = function(...) return setmetatable(vmStat(...), {__tostring = __tostring_for_tables }) end host.cpuUsage = function(...) local result = cpuUsage(...) for i,v in pairs(result) do if tostring(i) ~= "n" then result[i] = setmetatable(v, { __tostring = __tostring_for_tables }) end end return result end return host
mit
codedash64/Urho3D
Source/ThirdParty/LuaJIT/src/jit/v.lua
42
5755
---------------------------------------------------------------------------- -- Verbose mode of the LuaJIT compiler. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module shows verbose information about the progress of the -- JIT compiler. It prints one line for each generated trace. This module -- is useful to see which code has been compiled or where the compiler -- punts and falls back to the interpreter. -- -- Example usage: -- -- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end" -- luajit -jv=myapp.out myapp.lua -- -- Default output is to stderr. To redirect the output to a file, pass a -- filename as an argument (use '-' for stdout) or set the environment -- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the -- module is started. -- -- The output from the first example should look like this: -- -- [TRACE 1 (command line):1 loop] -- [TRACE 2 (1/3) (command line):1 -> 1] -- -- The first number in each line is the internal trace number. Next are -- the file name ('(command line)') and the line number (':1') where the -- trace has started. Side traces also show the parent trace number and -- the exit number where they are attached to in parentheses ('(1/3)'). -- An arrow at the end shows where the trace links to ('-> 1'), unless -- it loops to itself. -- -- In this case the inner loop gets hot and is traced first, generating -- a root trace. Then the last exit from the 1st trace gets hot, too, -- and triggers generation of the 2nd trace. The side trace follows the -- path along the outer loop and *around* the inner loop, back to its -- start, and then links to the 1st trace. Yes, this may seem unusual, -- if you know how traditional compilers work. Trace compilers are full -- of surprises like this -- have fun! :-) -- -- Aborted traces are shown like this: -- -- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50] -- -- Don't worry -- trace aborts are quite common, even in programs which -- can be fully compiled. The compiler may retry several times until it -- finds a suitable trace. -- -- Of course this doesn't work with features that are not-yet-implemented -- (NYI error messages). The VM simply falls back to the interpreter. This -- may not matter at all if the particular trace is not very high up in -- the CPU usage profile. Oh, and the interpreter is quite fast, too. -- -- Also check out the -jdump module, which prints all the gory details. -- ------------------------------------------------------------------------------ -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local jutil = require("jit.util") local vmdef = require("jit.vmdef") local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo local type, format = type, string.format local stdout, stderr = io.stdout, io.stderr -- Active flag and output file handle. local active, out ------------------------------------------------------------------------------ local startloc, startex local function fmtfunc(func, pc) local fi = funcinfo(func, pc) if fi.loc then return fi.loc elseif fi.ffid then return vmdef.ffnames[fi.ffid] elseif fi.addr then return format("C:%x", fi.addr) else return "(?)" end end -- Format trace error message. local function fmterr(err, info) if type(err) == "number" then if type(info) == "function" then info = fmtfunc(info) end err = format(vmdef.traceerr[err], info) end return err end -- Dump trace states. local function dump_trace(what, tr, func, pc, otr, oex) if what == "start" then startloc = fmtfunc(func, pc) startex = otr and "("..otr.."/"..oex..") " or "" else if what == "abort" then local loc = fmtfunc(func, pc) if loc ~= startloc then out:write(format("[TRACE --- %s%s -- %s at %s]\n", startex, startloc, fmterr(otr, oex), loc)) else out:write(format("[TRACE --- %s%s -- %s]\n", startex, startloc, fmterr(otr, oex))) end elseif what == "stop" then local info = traceinfo(tr) local link, ltype = info.link, info.linktype if ltype == "interpreter" then out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n", tr, startex, startloc)) elseif ltype == "stitch" then out:write(format("[TRACE %3s %s%s %s %s]\n", tr, startex, startloc, ltype, fmtfunc(func, pc))) elseif link == tr or link == 0 then out:write(format("[TRACE %3s %s%s %s]\n", tr, startex, startloc, ltype)) elseif ltype == "root" then out:write(format("[TRACE %3s %s%s -> %d]\n", tr, startex, startloc, link)) else out:write(format("[TRACE %3s %s%s -> %d %s]\n", tr, startex, startloc, link, ltype)) end else out:write(format("[TRACE %s]\n", what)) end out:flush() end end ------------------------------------------------------------------------------ -- Detach dump handlers. local function dumpoff() if active then active = false jit.attach(dump_trace) if out and out ~= stdout and out ~= stderr then out:close() end out = nil end end -- Open the output file and attach dump handlers. local function dumpon(outfile) if active then dumpoff() end if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stderr end jit.attach(dump_trace, "trace") active = true end -- Public module functions. return { on = dumpon, off = dumpoff, start = dumpon -- For -j command line option. }
mit
Ninjistix/darkstar
scripts/zones/Beaucedine_Glacier/Zone.lua
5
2405
----------------------------------- -- -- Zone: Beaucedine_Glacier (111) -- ----------------------------------- package.loaded[ "scripts/zones/Beaucedine_Glacier/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Beaucedine_Glacier/TextIDs"); require("scripts/globals/missions"); require("scripts/globals/icanheararainbow"); require("scripts/globals/zone"); require("scripts/globals/conquest"); ----------------------------------- function onInitialize(zone) SetRegionalConquestOverseers(zone:getRegionID()) end; function onZoneIn( player, prevZone) local cs = -1; if (prevZone == 134) then -- warp player to a correct position after dynamis player:setPos(-284.751,-39.923,-422.948,235); end if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( -247.911, -82.165, 260.207, 248); end if (player:getCurrentMission( COP) == DESIRES_OF_EMPTINESS and player:getVar( "PromathiaStatus") == 9) then cs = 206; elseif (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow cs = 114; elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then cs = 116; end return cs; end; function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; function onRegionEnter( player, region) end; function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 114) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow elseif (csid == 116) then player:updateEvent(0,0,0,0,0,4); end end; function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 206) then player:setVar("PromathiaStatus",10); elseif (csid == 114) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow end end; function onZoneWeatherChange(weather) local mirrorPond = GetNPCByID(17232196); -- Quest: Love And Ice if (weather == WEATHER_GLOOM or weather == WEATHER_DARKNESS) then mirrorPond:setStatus(STATUS_NORMAL); else mirrorPond:setStatus(STATUS_DISAPPEAR); end end;
gpl-3.0
lukego/ljsyscall
include/headers.lua
1
29873
-- ffi definitions of Linux headers local ffi = require "ffi" -- currently used for x86, x64. arm has no differences. local ok, arch = pcall(require, "include.headers-" .. ffi.arch) -- architecture specific definitions if not ok then arch = {} end -- define C types ffi.cdef[[ static const int UTSNAME_LENGTH = 65; // typedefs for word size independent types // 16 bit typedef uint16_t in_port_t; // 32 bit typedef uint32_t mode_t; typedef uint32_t uid_t; typedef uint32_t gid_t; typedef uint32_t socklen_t; typedef uint32_t id_t; typedef int32_t pid_t; typedef int32_t clockid_t; typedef int32_t daddr_t; // 64 bit typedef uint64_t dev_t; typedef uint64_t loff_t; typedef uint64_t off64_t; typedef uint64_t rlim64_t; // posix standards typedef unsigned short int sa_family_t; // typedefs which are word length typedef unsigned long size_t; typedef long ssize_t; typedef long off_t; typedef long kernel_off_t; typedef long time_t; typedef long blksize_t; typedef long blkcnt_t; typedef long clock_t; typedef unsigned long ino_t; typedef unsigned long nlink_t; typedef unsigned long aio_context_t; typedef unsigned long nfds_t; // should be a word, but we use 32 bits as bitops are signed 32 bit in LuaJIT at the moment typedef int32_t fd_mask; typedef struct { int32_t val[1024 / (8 * sizeof (int32_t))]; } sigset_t; typedef int mqd_t; typedef int idtype_t; /* defined as enum */ // misc typedef void (*sighandler_t) (int); // structs struct timeval { long tv_sec; /* seconds */ long tv_usec; /* microseconds */ }; struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; struct itimerspec { struct timespec it_interval; struct timespec it_value; }; struct itimerval { struct timeval it_interval; struct timeval it_value; }; // for uname. struct utsname { char sysname[UTSNAME_LENGTH]; char nodename[UTSNAME_LENGTH]; char release[UTSNAME_LENGTH]; char version[UTSNAME_LENGTH]; char machine[UTSNAME_LENGTH]; char domainname[UTSNAME_LENGTH]; // may not exist }; struct iovec { void *iov_base; size_t iov_len; }; struct pollfd { int fd; short int events; short int revents; }; typedef struct { /* based on Linux/FreeBSD FD_SETSIZE = 1024, the kernel can do more, so can increase, but bad performance so dont! */ fd_mask fds_bits[1024 / (sizeof (fd_mask) * 8)]; } fd_set; struct ucred { /* this is Linux specific */ pid_t pid; uid_t uid; gid_t gid; }; struct rlimit64 { rlim64_t rlim_cur; rlim64_t rlim_max; }; struct sysinfo { /* Linux only */ long uptime; unsigned long loads[3]; unsigned long totalram; unsigned long freeram; unsigned long sharedram; unsigned long bufferram; unsigned long totalswap; unsigned long freeswap; unsigned short procs; unsigned short pad; unsigned long totalhigh; unsigned long freehigh; unsigned int mem_unit; char _f[20-2*sizeof(long)-sizeof(int)]; }; struct timex { unsigned int modes; long int offset; long int freq; long int maxerror; long int esterror; int status; long int constant; long int precision; long int tolerance; struct timeval time; long int tick; long int ppsfreq; long int jitter; int shift; long int stabil; long int jitcnt; long int calcnt; long int errcnt; long int stbcnt; int tai; int :32; int :32; int :32; int :32; int :32; int :32; int :32; int :32; int :32; int :32; int :32; }; typedef union sigval { int sival_int; void *sival_ptr; } sigval_t; struct msghdr { void *msg_name; socklen_t msg_namelen; struct iovec *msg_iov; size_t msg_iovlen; void *msg_control; size_t msg_controllen; int msg_flags; }; struct cmsghdr { size_t cmsg_len; int cmsg_level; int cmsg_type; //unsigned char cmsg_data[?]; /* causes issues with luaffi, pre C99 */ }; struct sockaddr { sa_family_t sa_family; char sa_data[14]; }; struct sockaddr_storage { sa_family_t ss_family; unsigned long int __ss_align; char __ss_padding[128 - 2 * sizeof(unsigned long int)]; /* total length 128 */ }; struct in_addr { uint32_t s_addr; }; struct in6_addr { unsigned char s6_addr[16]; }; struct sockaddr_in { sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr; unsigned char sin_zero[8]; /* padding, should not vary by arch */ }; struct sockaddr_in6 { sa_family_t sin6_family; in_port_t sin6_port; uint32_t sin6_flowinfo; struct in6_addr sin6_addr; uint32_t sin6_scope_id; }; struct sockaddr_un { sa_family_t sun_family; char sun_path[108]; }; struct sockaddr_nl { sa_family_t nl_family; unsigned short nl_pad; uint32_t nl_pid; uint32_t nl_groups; }; struct nlmsghdr { uint32_t nlmsg_len; uint16_t nlmsg_type; uint16_t nlmsg_flags; uint32_t nlmsg_seq; uint32_t nlmsg_pid; }; struct rtgenmsg { unsigned char rtgen_family; }; struct ifinfomsg { unsigned char ifi_family; unsigned char __ifi_pad; unsigned short ifi_type; int ifi_index; unsigned ifi_flags; unsigned ifi_change; }; struct rtattr { unsigned short rta_len; unsigned short rta_type; }; struct nlmsgerr { int error; struct nlmsghdr msg; }; struct rtmsg { unsigned char rtm_family; unsigned char rtm_dst_len; unsigned char rtm_src_len; unsigned char rtm_tos; unsigned char rtm_table; unsigned char rtm_protocol; unsigned char rtm_scope; unsigned char rtm_type; unsigned int rtm_flags; }; static const int IFNAMSIZ = 16; struct ifmap { unsigned long mem_start; unsigned long mem_end; unsigned short base_addr; unsigned char irq; unsigned char dma; unsigned char port; }; struct rtnl_link_stats { uint32_t rx_packets; uint32_t tx_packets; uint32_t rx_bytes; uint32_t tx_bytes; uint32_t rx_errors; uint32_t tx_errors; uint32_t rx_dropped; uint32_t tx_dropped; uint32_t multicast; uint32_t collisions; uint32_t rx_length_errors; uint32_t rx_over_errors; uint32_t rx_crc_errors; uint32_t rx_frame_errors; uint32_t rx_fifo_errors; uint32_t rx_missed_errors; uint32_t tx_aborted_errors; uint32_t tx_carrier_errors; uint32_t tx_fifo_errors; uint32_t tx_heartbeat_errors; uint32_t tx_window_errors; uint32_t rx_compressed; uint32_t tx_compressed; }; typedef struct { unsigned int clock_rate; unsigned int clock_type; unsigned short loopback; } sync_serial_settings; typedef struct { unsigned int clock_rate; unsigned int clock_type; unsigned short loopback; unsigned int slot_map; } te1_settings; typedef struct { unsigned short encoding; unsigned short parity; } raw_hdlc_proto; typedef struct { unsigned int t391; unsigned int t392; unsigned int n391; unsigned int n392; unsigned int n393; unsigned short lmi; unsigned short dce; } fr_proto; typedef struct { unsigned int dlci; } fr_proto_pvc; typedef struct { unsigned int dlci; char master[IFNAMSIZ]; } fr_proto_pvc_info; typedef struct { unsigned int interval; unsigned int timeout; } cisco_proto; struct if_settings { unsigned int type; unsigned int size; union { raw_hdlc_proto *raw_hdlc; cisco_proto *cisco; fr_proto *fr; fr_proto_pvc *fr_pvc; fr_proto_pvc_info *fr_pvc_info; sync_serial_settings *sync; te1_settings *te1; } ifs_ifsu; }; struct ifreq { union { char ifrn_name[IFNAMSIZ]; } ifr_ifrn; union { struct sockaddr ifru_addr; struct sockaddr ifru_dstaddr; struct sockaddr ifru_broadaddr; struct sockaddr ifru_netmask; struct sockaddr ifru_hwaddr; short ifru_flags; int ifru_ivalue; int ifru_mtu; struct ifmap ifru_map; char ifru_slave[IFNAMSIZ]; char ifru_newname[IFNAMSIZ]; void * ifru_data; struct if_settings ifru_settings; } ifr_ifru; }; struct ifaddrmsg { uint8_t ifa_family; uint8_t ifa_prefixlen; uint8_t ifa_flags; uint8_t ifa_scope; uint32_t ifa_index; }; struct ifa_cacheinfo { uint32_t ifa_prefered; uint32_t ifa_valid; uint32_t cstamp; uint32_t tstamp; }; struct rta_cacheinfo { uint32_t rta_clntref; uint32_t rta_lastuse; uint32_t rta_expires; uint32_t rta_error; uint32_t rta_used; uint32_t rta_id; uint32_t rta_ts; uint32_t rta_tsage; }; struct fdb_entry { uint8_t mac_addr[6]; uint8_t port_no; uint8_t is_local; uint32_t ageing_timer_value; uint8_t port_hi; uint8_t pad0; uint16_t unused; }; struct inotify_event { int wd; uint32_t mask; uint32_t cookie; uint32_t len; char name[?]; }; struct linux_dirent64 { uint64_t d_ino; int64_t d_off; unsigned short d_reclen; unsigned char d_type; char d_name[0]; }; struct stat { /* only used on 64 bit architectures */ unsigned long st_dev; unsigned long st_ino; unsigned long st_nlink; unsigned int st_mode; unsigned int st_uid; unsigned int st_gid; unsigned int __pad0; unsigned long st_rdev; long st_size; long st_blksize; long st_blocks; unsigned long st_atime; unsigned long st_atime_nsec; unsigned long st_mtime; unsigned long st_mtime_nsec; unsigned long st_ctime; unsigned long st_ctime_nsec; long __unused[3]; }; struct stat64 { /* only for 32 bit architectures */ unsigned long long st_dev; unsigned char __pad0[4]; unsigned long __st_ino; unsigned int st_mode; unsigned int st_nlink; unsigned long st_uid; unsigned long st_gid; unsigned long long st_rdev; unsigned char __pad3[4]; long long st_size; unsigned long st_blksize; unsigned long long st_blocks; unsigned long st_atime; unsigned long st_atime_nsec; unsigned long st_mtime; unsigned int st_mtime_nsec; unsigned long st_ctime; unsigned long st_ctime_nsec; unsigned long long st_ino; }; struct flock64 { short int l_type; short int l_whence; off64_t l_start; off64_t l_len; pid_t l_pid; }; typedef union epoll_data { void *ptr; int fd; uint32_t u32; uint64_t u64; } epoll_data_t; struct signalfd_siginfo { uint32_t ssi_signo; int32_t ssi_errno; int32_t ssi_code; uint32_t ssi_pid; uint32_t ssi_uid; int32_t ssi_fd; uint32_t ssi_tid; uint32_t ssi_band; uint32_t ssi_overrun; uint32_t ssi_trapno; int32_t ssi_status; int32_t ssi_int; uint64_t ssi_ptr; uint64_t ssi_utime; uint64_t ssi_stime; uint64_t ssi_addr; uint8_t __pad[48]; }; struct io_event { uint64_t data; uint64_t obj; int64_t res; int64_t res2; }; struct seccomp_data { int nr; uint32_t arch; uint64_t instruction_pointer; uint64_t args[6]; }; struct mq_attr { long mq_flags, mq_maxmsg, mq_msgsize, mq_curmsgs, __unused[4]; }; /* termios */ typedef unsigned char cc_t; typedef unsigned int speed_t; typedef unsigned int tcflag_t; struct termios { tcflag_t c_iflag; /* input mode flags */ tcflag_t c_oflag; /* output mode flags */ tcflag_t c_cflag; /* control mode flags */ tcflag_t c_lflag; /* local mode flags */ cc_t c_line; /* line discipline */ cc_t c_cc[32]; /* control characters */ speed_t c_ispeed; /* input speed */ speed_t c_ospeed; /* output speed */ }; ]] -- sigaction is a union on x86. note luajit supports anonymous unions, which simplifies usage -- it appears that there is no kernel sigaction in non x86 architectures? Need to check source. -- presumably does not care, but the types are a bit of a pain. -- temporarily just going to implement sighandler support if arch.sigaction then arch.sigaction() else ffi.cdef[[ struct sigaction { sighandler_t sa_handler; unsigned long sa_flags; void (*sa_restorer)(void); sigset_t sa_mask; }; ]] end -- Linux struct siginfo padding depends on architecture, also statfs if ffi.abi("64bit") then ffi.cdef[[ static const int SI_MAX_SIZE = 128; static const int SI_PAD_SIZE = (SI_MAX_SIZE / sizeof (int)) - 4; typedef long statfs_word; ]] else ffi.cdef[[ static const int SI_MAX_SIZE = 128; static const int SI_PAD_SIZE = (SI_MAX_SIZE / sizeof (int)) - 3; typedef uint32_t statfs_word; ]] end ffi.cdef[[ typedef struct siginfo { int si_signo; int si_errno; int si_code; union { int _pad[SI_PAD_SIZE]; struct { pid_t si_pid; uid_t si_uid; } kill; struct { int si_tid; int si_overrun; sigval_t si_sigval; } timer; struct { pid_t si_pid; uid_t si_uid; sigval_t si_sigval; } rt; struct { pid_t si_pid; uid_t si_uid; int si_status; clock_t si_utime; clock_t si_stime; } sigchld; struct { void *si_addr; } sigfault; struct { long int si_band; int si_fd; } sigpoll; } sifields; } siginfo_t; typedef struct { int val[2]; } kernel_fsid_t; struct statfs64 { statfs_word f_type; statfs_word f_bsize; uint64_t f_blocks; uint64_t f_bfree; uint64_t f_bavail; uint64_t f_files; uint64_t f_ffree; kernel_fsid_t f_fsid; statfs_word f_namelen; statfs_word f_frsize; statfs_word f_flags; statfs_word f_spare[4]; }; ]] -- epoll packed on x86_64 only (so same as x86) if arch.epoll then arch.epoll() else ffi.cdef[[ struct epoll_event { uint32_t events; epoll_data_t data; }; ]] end -- endian dependent if ffi.abi("le") then ffi.cdef[[ struct iocb { uint64_t aio_data; uint32_t aio_key, aio_reserved1; uint16_t aio_lio_opcode; int16_t aio_reqprio; uint32_t aio_fildes; uint64_t aio_buf; uint64_t aio_nbytes; int64_t aio_offset; uint64_t aio_reserved2; uint32_t aio_flags; uint32_t aio_resfd; }; ]] else ffi.cdef[[ struct iocb { uint64_t aio_data; uint32_t aio_reserved1, aio_key; uint16_t aio_lio_opcode; int16_t aio_reqprio; uint32_t aio_fildes; uint64_t aio_buf; uint64_t aio_nbytes; int64_t aio_offset; uint64_t aio_reserved2; uint32_t aio_flags; uint32_t aio_resfd; }; ]] end -- shared code ffi.cdef[[ int close(int fd); int open(const char *pathname, int flags, mode_t mode); int openat(int dirfd, const char *pathname, int flags, mode_t mode); int creat(const char *pathname, mode_t mode); int chdir(const char *path); int mkdir(const char *pathname, mode_t mode); int mkdirat(int dirfd, const char *pathname, mode_t mode); int rmdir(const char *pathname); int unlink(const char *pathname); int unlinkat(int dirfd, const char *pathname, int flags); int rename(const char *oldpath, const char *newpath); int renameat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath); int acct(const char *filename); int chmod(const char *path, mode_t mode); int chown(const char *path, uid_t owner, gid_t group); int fchown(int fd, uid_t owner, gid_t group); int lchown(const char *path, uid_t owner, gid_t group); int fchownat(int dirfd, const char *pathname, uid_t owner, gid_t group, int flags); int link(const char *oldpath, const char *newpath); int linkat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, int flags); int symlink(const char *oldpath, const char *newpath); int symlinkat(const char *oldpath, int newdirfd, const char *newpath); int chroot(const char *path); mode_t umask(mode_t mask); int uname(struct utsname *buf); int sethostname(const char *name, size_t len); int setdomainname(const char *name, size_t len); uid_t getuid(void); uid_t geteuid(void); pid_t getpid(void); pid_t getppid(void); gid_t getgid(void); gid_t getegid(void); int setuid(uid_t uid); int setgid(gid_t gid); int seteuid(uid_t euid); int setegid(gid_t egid); int setreuid(uid_t ruid, uid_t euid); int setregid(gid_t rgid, gid_t egid); int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid); int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid); int setresuid(uid_t ruid, uid_t euid, uid_t suid); int setresgid(gid_t rgid, gid_t egid, gid_t sgid); pid_t getsid(pid_t pid); pid_t setsid(void); int getgroups(int size, gid_t list[]); int setgroups(size_t size, const gid_t *list); pid_t fork(void); int execve(const char *filename, const char *argv[], const char *envp[]); pid_t wait(int *status); pid_t waitpid(pid_t pid, int *status, int options); int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options); void _exit(int status); int signal(int signum, int handler); /* although deprecated, just using to set SIG_ values */ int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact); int kill(pid_t pid, int sig); int gettimeofday(struct timeval *tv, void *tz); /* not even defining struct timezone */ int settimeofday(const struct timeval *tv, const void *tz); int getitimer(int which, struct itimerval *curr_value); int setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value); time_t time(time_t *t); int clock_getres(clockid_t clk_id, struct timespec *res); int clock_gettime(clockid_t clk_id, struct timespec *tp); int clock_settime(clockid_t clk_id, const struct timespec *tp); int clock_nanosleep(clockid_t clock_id, int flags, const struct timespec *request, struct timespec *remain); unsigned int alarm(unsigned int seconds); int sysinfo(struct sysinfo *info); void sync(void); int nice(int inc); int getpriority(int which, int who); int setpriority(int which, int who, int prio); int prctl(int option, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5); int sigprocmask(int how, const sigset_t *set, sigset_t *oldset); int sigpending(sigset_t *set); int sigsuspend(const sigset_t *mask); int signalfd(int fd, const sigset_t *mask, int flags); int timerfd_create(int clockid, int flags); int timerfd_settime(int fd, int flags, const struct itimerspec *new_value, struct itimerspec *old_value); int timerfd_gettime(int fd, struct itimerspec *curr_value); int mknod(const char *pathname, mode_t mode, dev_t dev); int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev); ssize_t read(int fd, void *buf, size_t count); ssize_t write(int fd, const void *buf, size_t count); ssize_t pread64(int fd, void *buf, size_t count, loff_t offset); ssize_t pwrite64(int fd, const void *buf, size_t count, loff_t offset); ssize_t send(int sockfd, const void *buf, size_t len, int flags); // for sendto and recvfrom use void pointer not const struct sockaddr * to avoid casting ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const void *dest_addr, socklen_t addrlen); ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags, void *src_addr, socklen_t *addrlen); ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags); ssize_t recv(int sockfd, void *buf, size_t len, int flags); ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags); ssize_t readv(int fd, const struct iovec *iov, int iovcnt); ssize_t writev(int fd, const struct iovec *iov, int iovcnt); // ssize_t preadv(int fd, const struct iovec *iov, int iovcnt, off_t offset); // ssize_t pwritev(int fd, const struct iovec *iov, int iovcnt, off_t offset); ssize_t preadv64(int fd, const struct iovec *iov, int iovcnt, loff_t offset); ssize_t pwritev64(int fd, const struct iovec *iov, int iovcnt, loff_t offset); int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen); int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen); int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); int poll(struct pollfd *fds, nfds_t nfds, int timeout); int ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout_ts, const sigset_t *sigmask); int pselect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timespec *timeout, const sigset_t *sigmask); ssize_t readlink(const char *path, char *buf, size_t bufsiz); int readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz); off_t lseek(int fd, off_t offset, int whence); // only for 64 bit, else use _llseek int epoll_create1(int flags); int epoll_create(int size); int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event); int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout); int epoll_pwait(int epfd, struct epoll_event *events, int maxevents, int timeout, const sigset_t *sigmask); ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count); int eventfd(unsigned int initval, int flags); ssize_t splice(int fd_in, loff_t *off_in, int fd_out, loff_t *off_out, size_t len, unsigned int flags); ssize_t vmsplice(int fd, const struct iovec *iov, unsigned long nr_segs, unsigned int flags); ssize_t tee(int fd_in, int fd_out, size_t len, unsigned int flags); int reboot(int cmd); int klogctl(int type, char *bufp, int len); int inotify_init1(int flags); int inotify_add_watch(int fd, const char *pathname, uint32_t mask); int inotify_rm_watch(int fd, uint32_t wd); int adjtimex(struct timex *buf); int sync_file_range(int fd, loff_t offset, loff_t count, unsigned int flags); int dup(int oldfd); int dup2(int oldfd, int newfd); int dup3(int oldfd, int newfd, int flags); int fchdir(int fd); int fsync(int fd); int fdatasync(int fd); int fcntl(int fd, int cmd, void *arg); /* arg is long or pointer */ int fchmod(int fd, mode_t mode); int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags); int truncate(const char *path, off_t length); int ftruncate(int fd, off_t length); int truncate64(const char *path, loff_t length); int ftruncate64(int fd, loff_t length); int pause(void); int prlimit64(pid_t pid, int resource, const struct rlimit64 *new_limit, struct rlimit64 *old_limit); int socket(int domain, int type, int protocol); int socketpair(int domain, int type, int protocol, int sv[2]); int bind(int sockfd, const void *addr, socklen_t addrlen); // void not struct int listen(int sockfd, int backlog); int connect(int sockfd, const void *addr, socklen_t addrlen); int accept(int sockfd, void *addr, socklen_t *addrlen); int accept4(int sockfd, void *addr, socklen_t *addrlen, int flags); int getsockname(int sockfd, void *addr, socklen_t *addrlen); int getpeername(int sockfd, void *addr, socklen_t *addrlen); int shutdown(int sockfd, int how); void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset); int munmap(void *addr, size_t length); int msync(void *addr, size_t length, int flags); int mlock(const void *addr, size_t len); int munlock(const void *addr, size_t len); int mlockall(int flags); int munlockall(void); void *mremap(void *old_address, size_t old_size, size_t new_size, int flags, void *new_address); int madvise(void *addr, size_t length, int advice); int posix_fadvise(int fd, off_t offset, off_t len, int advice); int fallocate(int fd, int mode, off_t offset, off_t len); ssize_t readahead(int fd, off64_t offset, size_t count); int pipe(int pipefd[2]); int pipe2(int pipefd[2], int flags); int mount(const char *source, const char *target, const char *filesystemtype, unsigned long mountflags, const void *data); int umount(const char *target); int umount2(const char *target, int flags); int nanosleep(const struct timespec *req, struct timespec *rem); int access(const char *pathname, int mode); int faccessat(int dirfd, const char *pathname, int mode, int flags); char *getcwd(char *buf, size_t size); int statfs(const char *path, struct statfs64 *buf); /* this is statfs64 syscall, but glibc wraps */ int fstatfs(int fd, struct statfs64 *buf); /* this too */ int futimens(int fd, const struct timespec times[2]); int utimensat(int dirfd, const char *pathname, const struct timespec times[2], int flags); ssize_t listxattr(const char *path, char *list, size_t size); ssize_t llistxattr(const char *path, char *list, size_t size); ssize_t flistxattr(int fd, char *list, size_t size); ssize_t getxattr(const char *path, const char *name, void *value, size_t size); ssize_t lgetxattr(const char *path, const char *name, void *value, size_t size); ssize_t fgetxattr(int fd, const char *name, void *value, size_t size); int setxattr(const char *path, const char *name, const void *value, size_t size, int flags); int lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags); int fsetxattr(int fd, const char *name, const void *value, size_t size, int flags); int removexattr(const char *path, const char *name); int lremovexattr(const char *path, const char *name); int fremovexattr(int fd, const char *name); int unshare(int flags); int setns(int fd, int nstype); int pivot_root(const char *new_root, const char *put_old); int syscall(int number, ...); int ioctl(int d, int request, void *argp); /* void* easiest here */ /* TODO from here to libc functions are not implemented yet */ int tgkill(int tgid, int tid, int sig); int brk(void *addr); void *sbrk(intptr_t increment); void exit_group(int status); /* these need their types adding or fixing before can uncomment */ /* int capget(cap_user_header_t hdrp, cap_user_data_t datap); int capset(cap_user_header_t hdrp, const cap_user_data_t datap); caddr_t create_module(const char *name, size_t size); int init_module(const char *name, struct module *image); int get_kernel_syms(struct kernel_sym *table); int getcpu(unsigned *cpu, unsigned *node, struct getcpu_cache *tcache); int getrusage(int who, struct rusage *usage); int get_thread_area(struct user_desc *u_info); long kexec_load(unsigned long entry, unsigned long nr_segments, struct kexec_segment *segments, unsigned long flags); int lookup_dcookie(u64 cookie, char *buffer, size_t len); int msgctl(int msqid, int cmd, struct msqid_ds *buf); int msgget(key_t key, int msgflg); long ptrace(enum __ptrace_request request, pid_t pid, void *addr, void *data); int quotactl(int cmd, const char *special, int id, caddr_t addr); int semget(key_t key, int nsems, int semflg); int shmctl(int shmid, int cmd, struct shmid_ds *buf); int shmget(key_t key, size_t size, int shmflg); int timer_create(clockid_t clockid, struct sigevent *sevp, timer_t *timerid); int timer_delete(timer_t timerid); int timer_getoverrun(timer_t timerid); int timer_settime(timer_t timerid, int flags, const struct itimerspec *new_value, struct itimerspec * old_value); int timer_gettime(timer_t timerid, struct itimerspec *curr_value); clock_t times(struct tms *buf); int utime(const char *filename, const struct utimbuf *times); */ int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); int delete_module(const char *name); int flock(int fd, int operation); int get_mempolicy(int *mode, unsigned long *nodemask, unsigned long maxnode, unsigned long addr, unsigned long flags); int mbind(void *addr, unsigned long len, int mode, unsigned long *nodemask, unsigned long maxnode, unsigned flags); long migrate_pages(int pid, unsigned long maxnode, const unsigned long *old_nodes, const unsigned long *new_nodes); int mincore(void *addr, size_t length, unsigned char *vec); long move_pages(int pid, unsigned long count, void **pages, const int *nodes, int *status, int flags); int mprotect(const void *addr, size_t len, int prot); int personality(unsigned long persona); int recvmmsg(int sockfd, struct mmsghdr *msgvec, unsigned int vlen, unsigned int flags, struct timespec *timeout); int remap_file_pages(void *addr, size_t size, int prot, ssize_t pgoff, int flags); int semctl(int semid, int semnum, int cmd, ...); int semop(int semid, struct sembuf *sops, unsigned nsops); int semtimedop(int semid, struct sembuf *sops, unsigned nsops, struct timespec *timeout); void *shmat(int shmid, const void *shmaddr, int shmflg); int shmdt(const void *shmaddr); int swapon(const char *path, int swapflags); int swapoff(const char *path); void syncfs(int fd); pid_t wait4(pid_t pid, int *status, int options, struct rusage *rusage); int setpgid(pid_t pid, pid_t pgid); pid_t getpgid(pid_t pid); pid_t getpgrp(pid_t pid); pid_t gettid(void); int setfsgid(uid_t fsgid); int setfsuid(uid_t fsuid); long keyctl(int cmd, ...); mqd_t mq_open(const char *name, int oflag, mode_t mode, struct mq_attr *attr); int mq_getsetattr(mqd_t mqdes, struct mq_attr *newattr, struct mq_attr *oldattr); ssize_t mq_timedreceive(mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned *msg_prio, const struct timespec *abs_timeout); int mq_timedsend(mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned msg_prio, const struct timespec *abs_timeout); int mq_notify(mqd_t mqdes, const struct sigevent *sevp); int mq_unlink(const char *name); // functions from libc ie man 3 not man 2 void exit(int status); int inet_pton(int af, const char *src, void *dst); const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); // functions from libc that could be exported as a convenience, used internally char *strerror(int); // env. dont support putenv, as does not copy which is an issue extern char **environ; int setenv(const char *name, const char *value, int overwrite); int unsetenv(const char *name); int clearenv(void); char *getenv(const char *name); int tcgetattr(int fd, struct termios *termios_p); int tcsetattr(int fd, int optional_actions, const struct termios *termios_p); int tcsendbreak(int fd, int duration); int tcdrain(int fd); int tcflush(int fd, int queue_selector); int tcflow(int fd, int action); void cfmakeraw(struct termios *termios_p); speed_t cfgetispeed(const struct termios *termios_p); speed_t cfgetospeed(const struct termios *termios_p); int cfsetispeed(struct termios *termios_p, speed_t speed); int cfsetospeed(struct termios *termios_p, speed_t speed); int cfsetspeed(struct termios *termios_p, speed_t speed); pid_t tcgetsid(int fd); int vhangup(void); ]]
mit
SPARKTEA/sparkteam1
plugins/msg_checks.lua
149
11202
--Begin msg_checks.lua --Begin pre_process function local function pre_process(msg) -- Begin 'RondoMsgChecks' text checks by @rondoozle if is_chat_msg(msg) or is_super_group(msg) then if msg and not is_momod(msg) and not is_whitelisted(msg.from.id) then --if regular user local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") -- get rid of rtl in names local name_log = print_name:gsub("_", " ") -- name for log local to_chat = msg.to.type == 'chat' if data[tostring(msg.to.id)] and data[tostring(msg.to.id)]['settings'] then settings = data[tostring(msg.to.id)]['settings'] else return end if settings.lock_arabic then lock_arabic = settings.lock_arabic else lock_arabic = 'no' end if settings.lock_rtl then lock_rtl = settings.lock_rtl else lock_rtl = 'no' end if settings.lock_tgservice then lock_tgservice = settings.lock_tgservice else lock_tgservice = 'no' end if settings.lock_link then lock_link = settings.lock_link else lock_link = 'no' end if settings.lock_member then lock_member = settings.lock_member else lock_member = 'no' end if settings.lock_spam then lock_spam = settings.lock_spam else lock_spam = 'no' end if settings.lock_sticker then lock_sticker = settings.lock_sticker else lock_sticker = 'no' end if settings.lock_contacts then lock_contacts = settings.lock_contacts else lock_contacts = 'no' end if settings.strict then strict = settings.strict else strict = 'no' end if msg and not msg.service and is_muted(msg.to.id, 'All: yes') or is_muted_user(msg.to.id, msg.from.id) and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then -- kick_user(msg.from.id, msg.to.id) end end if msg.text then -- msg.text checks local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') local _nl, real_digits = string.gsub(msg.text, '%d', '') if lock_spam == "yes" and string.len(msg.text) > 2049 or ctrl_chars > 40 or real_digits > 2000 then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local is_link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") local is_bot = msg.text:match("?[Ss][Tt][Aa][Rr][Tt]=") if is_link_msg and lock_link == "yes" and not is_bot then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if msg.service then if lock_tgservice == "yes" then delete_msg(msg.id, ok_cb, false) if to_chat then return end end end local is_squig_msg = msg.text:match("[\216-\219][\128-\191]") if is_squig_msg and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl = print_name:match("‮") or msg.text:match("‮") if is_rtl and lock_rtl == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, "Text: yes") and msg.text and not msg.media and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media then -- msg.media checks if msg.media.title then local is_link_title = msg.media.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.media.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.description then local is_link_desc = msg.media.description:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.description:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_desc and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_desc = msg.media.description:match("[\216-\219][\128-\191]") if is_squig_desc and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.caption then -- msg.media.caption checks local is_link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_caption and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_caption = msg.media.caption:match("[\216-\219][\128-\191]") if is_squig_caption and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_username_caption = msg.media.caption:match("^@[%a%d]") if is_username_caption and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if lock_sticker == "yes" and msg.media.caption:match("sticker.webp") then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.type:match("contact") and lock_contacts == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_photo_caption = msg.media.caption and msg.media.caption:match("photo")--".jpg", if is_muted(msg.to.id, 'Photo: yes') and msg.media.type:match("photo") or is_photo_caption and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end local is_gif_caption = msg.media.caption and msg.media.caption:match(".mp4") if is_muted(msg.to.id, 'Gifs: yes') and is_gif_caption and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Audio: yes') and msg.media.type:match("audio") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_video_caption = msg.media.caption and msg.media.caption:lower(".mp4","video") if is_muted(msg.to.id, 'Video: yes') and msg.media.type:match("video") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Documents: yes') and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.fwd_from then if msg.fwd_from.title then local is_link_title = msg.fwd_from.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.fwd_from.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.fwd_from.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if is_muted_user(msg.to.id, msg.fwd_from.peer_id) then delete_msg(msg.id, ok_cb, false) end end if msg.service then -- msg.service checks local action = msg.action.type if action == 'chat_add_user_link' then local user_id = msg.from.id local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') if string.len(msg.from.print_name) > 70 or ctrl_chars > 40 and lock_group_spam == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] joined and Service Msg deleted (#spam name)") delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then savelog(msg.to.id, name_log.." ["..msg.from.id.."] joined and kicked (#spam name)") kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "yes" then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] joined and kicked (#RTL char in name)") kick_user(user_id, msg.to.id) end if lock_member == 'yes' then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] joined and kicked (#lockmember)") kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end if action == 'chat_add_user' and not is_momod2(msg.from.id, msg.to.id) then local user_id = msg.action.user.id if string.len(msg.action.user.print_name) > 70 and lock_group_spam == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."]: Service Msg deleted (#spam name)") delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#spam name) ") delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local print_name = msg.action.user.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "yes" then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#RTL char in name)") kick_user(user_id, msg.to.id) end if msg.to.type == 'channel' and lock_member == 'yes' then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#lockmember)") kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end end end end -- End 'RondoMsgChecks' text checks by @Rondoozle return msg end --End pre_process function return { patterns = {}, pre_process = pre_process } --End msg_checks.lua --By @Rondoozle
gpl-3.0
blackman1380/antispam
plugins/msg_checks.lua
149
11202
--Begin msg_checks.lua --Begin pre_process function local function pre_process(msg) -- Begin 'RondoMsgChecks' text checks by @rondoozle if is_chat_msg(msg) or is_super_group(msg) then if msg and not is_momod(msg) and not is_whitelisted(msg.from.id) then --if regular user local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") -- get rid of rtl in names local name_log = print_name:gsub("_", " ") -- name for log local to_chat = msg.to.type == 'chat' if data[tostring(msg.to.id)] and data[tostring(msg.to.id)]['settings'] then settings = data[tostring(msg.to.id)]['settings'] else return end if settings.lock_arabic then lock_arabic = settings.lock_arabic else lock_arabic = 'no' end if settings.lock_rtl then lock_rtl = settings.lock_rtl else lock_rtl = 'no' end if settings.lock_tgservice then lock_tgservice = settings.lock_tgservice else lock_tgservice = 'no' end if settings.lock_link then lock_link = settings.lock_link else lock_link = 'no' end if settings.lock_member then lock_member = settings.lock_member else lock_member = 'no' end if settings.lock_spam then lock_spam = settings.lock_spam else lock_spam = 'no' end if settings.lock_sticker then lock_sticker = settings.lock_sticker else lock_sticker = 'no' end if settings.lock_contacts then lock_contacts = settings.lock_contacts else lock_contacts = 'no' end if settings.strict then strict = settings.strict else strict = 'no' end if msg and not msg.service and is_muted(msg.to.id, 'All: yes') or is_muted_user(msg.to.id, msg.from.id) and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then -- kick_user(msg.from.id, msg.to.id) end end if msg.text then -- msg.text checks local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') local _nl, real_digits = string.gsub(msg.text, '%d', '') if lock_spam == "yes" and string.len(msg.text) > 2049 or ctrl_chars > 40 or real_digits > 2000 then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local is_link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") local is_bot = msg.text:match("?[Ss][Tt][Aa][Rr][Tt]=") if is_link_msg and lock_link == "yes" and not is_bot then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if msg.service then if lock_tgservice == "yes" then delete_msg(msg.id, ok_cb, false) if to_chat then return end end end local is_squig_msg = msg.text:match("[\216-\219][\128-\191]") if is_squig_msg and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl = print_name:match("‮") or msg.text:match("‮") if is_rtl and lock_rtl == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, "Text: yes") and msg.text and not msg.media and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media then -- msg.media checks if msg.media.title then local is_link_title = msg.media.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.media.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.description then local is_link_desc = msg.media.description:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.description:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_desc and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_desc = msg.media.description:match("[\216-\219][\128-\191]") if is_squig_desc and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.caption then -- msg.media.caption checks local is_link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_caption and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_caption = msg.media.caption:match("[\216-\219][\128-\191]") if is_squig_caption and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_username_caption = msg.media.caption:match("^@[%a%d]") if is_username_caption and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if lock_sticker == "yes" and msg.media.caption:match("sticker.webp") then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.type:match("contact") and lock_contacts == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_photo_caption = msg.media.caption and msg.media.caption:match("photo")--".jpg", if is_muted(msg.to.id, 'Photo: yes') and msg.media.type:match("photo") or is_photo_caption and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end local is_gif_caption = msg.media.caption and msg.media.caption:match(".mp4") if is_muted(msg.to.id, 'Gifs: yes') and is_gif_caption and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Audio: yes') and msg.media.type:match("audio") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_video_caption = msg.media.caption and msg.media.caption:lower(".mp4","video") if is_muted(msg.to.id, 'Video: yes') and msg.media.type:match("video") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Documents: yes') and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.fwd_from then if msg.fwd_from.title then local is_link_title = msg.fwd_from.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.fwd_from.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.fwd_from.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if is_muted_user(msg.to.id, msg.fwd_from.peer_id) then delete_msg(msg.id, ok_cb, false) end end if msg.service then -- msg.service checks local action = msg.action.type if action == 'chat_add_user_link' then local user_id = msg.from.id local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') if string.len(msg.from.print_name) > 70 or ctrl_chars > 40 and lock_group_spam == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] joined and Service Msg deleted (#spam name)") delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then savelog(msg.to.id, name_log.." ["..msg.from.id.."] joined and kicked (#spam name)") kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "yes" then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] joined and kicked (#RTL char in name)") kick_user(user_id, msg.to.id) end if lock_member == 'yes' then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] joined and kicked (#lockmember)") kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end if action == 'chat_add_user' and not is_momod2(msg.from.id, msg.to.id) then local user_id = msg.action.user.id if string.len(msg.action.user.print_name) > 70 and lock_group_spam == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."]: Service Msg deleted (#spam name)") delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#spam name) ") delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local print_name = msg.action.user.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "yes" then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#RTL char in name)") kick_user(user_id, msg.to.id) end if msg.to.type == 'channel' and lock_member == 'yes' then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#lockmember)") kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end end end end -- End 'RondoMsgChecks' text checks by @Rondoozle return msg end --End pre_process function return { patterns = {}, pre_process = pre_process } --End msg_checks.lua --By @Rondoozle
gpl-2.0
dmekersa/create2Dmobilegames
ScreenJungleUltimate/main.lua
1
1689
----------------------------------------------------------------------------------------- -- -- main.lua -- ----------------------------------------------------------------------------------------- -- Your code here display.setStatusBar( display.HiddenStatusBar ) background = display.newImageRect( "ultimatebg.jpg", 900, 1425 ) background.x = display.contentCenterX background.y = display.contentCenterY redSquare = display.newRect( 0, 0, 50, 50 ) redSquare:setFillColor( 1,0,0 ) redSquare.strokeWidth = 1 redSquare:setStrokeColor( 0 ) redSquare.anchorX = 0 redSquare.x = 10 redSquare.y = display.contentCenterY blueSquare = display.newRect( 0, 0, 50, 50 ) blueSquare:setFillColor( 0,0,1 ) blueSquare.strokeWidth = 1 blueSquare:setStrokeColor( 0 ) blueSquare.anchorX = 1 blueSquare.x = display.contentWidth - 10 blueSquare.y = display.contentCenterY yellowSquare = display.newRect( 0, 0, 50, 50 ) yellowSquare:setFillColor( 1,1,0 ) yellowSquare.strokeWidth = 1 yellowSquare:setStrokeColor( 0 ) yellowSquare.anchorY = 0 yellowSquare.x = display.contentCenterX yellowSquare.y = 10 greenSquare = display.newRect( 0, 0, 50, 50 ) greenSquare:setFillColor( 0,1,0 ) greenSquare.strokeWidth = 1 greenSquare:setStrokeColor( 0 ) greenSquare.anchorY = 1 greenSquare.x = display.contentCenterX greenSquare.y = display.contentHeight - 10 print( "display.screenOriginX", display.screenOriginX ) print( "display.screenOriginY", display.screenOriginY ) print( "display.actualContentWidth", display.actualContentWidth ) print( "display.actualContentHeight", display.actualContentHeight ) print( "display.contentWidth", display.contentWidth ) print( "display.contentHeight", display.contentHeight )
unlicense
Ninjistix/darkstar
scripts/zones/Eastern_Altepa_Desert/npcs/Telepoint.lua
5
1360
----------------------------------- -- Area: Eastern Altepa Desert -- NPC: Telepoint ----------------------------------- package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Eastern_Altepa_Desert/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) item = trade:getItemId(); if (trade:getItemCount() == 1 and item > 4095 and item < 4104) then if (player:getFreeSlotsCount() > 0 and player:hasItem(613) == false) then player:tradeComplete(); player:addItem(613); player:messageSpecial(ITEM_OBTAINED,613); -- Faded Crystal else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,613); -- Faded Crystal end end end; function onTrigger(player,npc) if (player:hasKeyItem(ALTEPA_GATE_CRYSTAL) == false) then player:addKeyItem(ALTEPA_GATE_CRYSTAL); player:messageSpecial(KEYITEM_OBTAINED,ALTEPA_GATE_CRYSTAL); else player:messageSpecial(ALREADY_OBTAINED_TELE); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
blackman1380/antispam
plugins/filemanager.lua
11
5966
-- by negative local BASE_FOLDER = "/" local folder = "" local function download_file(extra, success, result) vardump(result) local file = "" local filename = "" if result.media.type == "photo" then file = result.id filename = "somepic.jpg" elseif result.media.type == "document" then file = result.id filename = result.media.caption elseif result.media.type == "audio" then filename = "somevoice.ogg" file = result.id else return end local url = BASE_URL .. '/getFile?file_id=' .. file local res = HTTPS.request(url) local jres = JSON.decode(res) if matches[2] then filename = matches[2] end local download = download_to_file("https://api.telegram.org/file/bot" .. bot_api_key .. "/" .. jres.result.file_path, filename) end function run(msg, matches) if is_sudo(msg) then receiver = get_receiver(msg) if matches[1]:lower() == 'cd' then if not matches[2] then return '🗂 شما در پوشه اصلی هستید' else folder = matches[2] return '📂 شما در این پوشه هستید : \n' .. BASE_FOLDER .. folder end end if matches[1]:lower() == 'ls' then local action = io.popen('ls "' .. BASE_FOLDER .. folder .. '"'):read("*all") send_large_msg(receiver, action) end if matches[1]:lower() == 'mkdir' and matches[2] then local action = io.popen('cd "' .. BASE_FOLDER .. folder .. '" && mkdir \'' .. matches[2] .. '\''):read("*all") return '✔️ پوشه ایجاد شد' end if matches[1]:lower() == 'rem' and matches[2] then local action = io.popen('cd "' .. BASE_FOLDER .. folder .. '" && rm -f \'' .. matches[2] .. '\''):read("*all") return '🚫 فایل حذف شد' end if matches[1]:lower() == 'cat' and matches[2] then local action = io.popen('cd "' .. BASE_FOLDER .. folder .. '" && cat \'' .. matches[2] .. '\''):read("*all") send_large_msg(receiver, action) end if matches[1]:lower() == 'rmdir' and matches[2] then local action = io.popen('cd "' .. BASE_FOLDER .. folder .. '" && rmdir \'' .. matches[2] .. '\''):read("*all") return '❌ پوشه حذف شد' end if matches[1]:lower() == 'touch' and matches[2] then local action = io.popen('cd "' .. BASE_FOLDER .. folder .. '" && touch \'' .. matches[2] .. '\''):read("*all") return 'ایجاد شد' end if matches[1]:lower() == 'tofile' and matches[2] and matches[3] then local file = io.open(BASE_FOLDER .. folder .. matches[2], "w") file:write(matches[3]) file:flush() file:close() send_large_msg(receiver, ('')) end if matches[1]:lower() == 'vps' and matches[2] then local text = io.popen('cd "' .. BASE_FOLDER .. folder .. '" && ' .. matches[2]:gsub('—', '--')):read('*all') send_large_msg(receiver, text) end if matches[1]:lower() == 'cp' and matches[2] and matches[3] then local action = io.popen('cd "' .. BASE_FOLDER .. folder .. '" && cp -r \'' .. matches[2] .. '\' \'' .. matches[3] .. '\''):read("*all") return '🔃 فایل مورد نظر کپی شد' end if matches[1]:lower() == 'mv' and matches[2] and matches[3] then local action = io.popen('cd "' .. BASE_FOLDER .. folder .. '" && mv \'' .. matches[2] .. '\' \'' .. matches[3] .. '\''):read("*all") return '✂️ فایل مورد نظر انتقال یافت' end if matches[1]:lower() == 'upload' and matches[2] then if io.popen('find ' .. BASE_FOLDER .. folder .. matches[2]):read("*all") == '' then return matches[2] .. ' ⁉️ درس سرور موجود نیست' else send_document(receiver, BASE_FOLDER .. folder .. matches[2], ok_cb, false) return 'در حال ارسال' end end if matches[1]:lower() == 'download' then if type(msg.reply_id) == "nil" then return 'یک فایل را ریپلی کنید تا من آن را دانلود کنم' else vardump(msg) get_message(msg.reply_id, download_file, false) return 'دانلود شد' end end else return 'فقط مخصوص سودو می باشد' end end return { description = "FILEMANAGER", usage = { "SUDO", "#cd [<directory>]: Sasha entra in <directory>, se non è specificata torna alla cartella base.", "#ls: Sasha manda la lista di file e cartelle della directory corrente.", "#mkdir <directory>: Sasha crea <directory>.", "#rmdir <directory>: Sasha elimina <directory>.", "#rm <file>: Sasha elimina <file>.", "#cat <file>: Sasha manda il contenuto di <file>.", "#tofile <file> <text>: Sasha crea <file> con <text> come contenuto.", "#vps <command>: Sasha esegue <command>.", "#cp <file> <directory>: Sasha copia <file> in <directory>.", "#mv <file> <directory>: Sasha sposta <file> in <directory>.", }, patterns = { "^([Cc][Dd])$", "^([Cc][Dd]) (.*)$", "^([Ll][Ss])$", "^([Mm][Kk][Dd][Ii][Rr]) (.*)$", "^([Rr][Mm][Dd][Ii][Rr]) (.*)$", "^([Rr][Ee][Mm]) (.*)$", "^([Cc][Aa][Tt]) (.*)$", "^([Vv][Pp][Ss]) (.*)$", "^([Cc][Pp]) (.*) (.*)$", "^([Mm][Vv]) (.*) (.*)$", "^([Uu][Pp][Ll][Oo][Aa][Dd]) (.*)$", "^([Dd][Oo][Ww][Nn][Ll][Oo][Aa][Dd]) (.*)", "^([Dd][Oo][Ww][Nn][Ll][Oo][Aa][Dd])" }, run = run, min_rank = 5 }
gpl-2.0
trixnz/lua-fmt
test/lua-5.3.4-tests/constructs.lua
13
7507
-- $Id: constructs.lua,v 1.41 2016/11/07 13:11:28 roberto Exp $ -- See Copyright Notice in file all.lua ;;print "testing syntax";; local debug = require "debug" local function checkload (s, msg) assert(string.find(select(2, load(s)), msg)) end -- testing semicollons do ;;; end ; do ; a = 3; assert(a == 3) end; ; -- invalid operations should not raise errors when not executed if false then a = 3 // 0; a = 0 % 0 end -- testing priorities assert(2^3^2 == 2^(3^2)); assert(2^3*4 == (2^3)*4); assert(2.0^-2 == 1/4 and -2^- -2 == - - -4); assert(not nil and 2 and not(2>3 or 3<2)); assert(-3-1-5 == 0+0-9); assert(-2^2 == -4 and (-2)^2 == 4 and 2*2-3-1 == 0); assert(-3%5 == 2 and -3+5 == 2) assert(2*1+3/3 == 3 and 1+2 .. 3*1 == "33"); assert(not(2+1 > 3*1) and "a".."b" > "a"); assert("7" .. 3 << 1 == 146) assert(10 >> 1 .. "9" == 0) assert(10 | 1 .. "9" == 27) assert(0xF0 | 0xCC ~ 0xAA & 0xFD == 0xF4) assert(0xFD & 0xAA ~ 0xCC | 0xF0 == 0xF4) assert(0xF0 & 0x0F + 1 == 0x10) assert(3^4//2^3//5 == 2) assert(-3+4*5//2^3^2//9+4%10/3 == (-3)+(((4*5)//(2^(3^2)))//9)+((4%10)/3)) assert(not ((true or false) and nil)) assert( true or false and nil) -- old bug assert((((1 or false) and true) or false) == true) assert((((nil and true) or false) and true) == false) local a,b = 1,nil; assert(-(1 or 2) == -1 and (1 and 2)+(-1.25 or -4) == 0.75); x = ((b or a)+1 == 2 and (10 or a)+1 == 11); assert(x); x = (((2<3) or 1) == true and (2<3 and 4) == 4); assert(x); x,y=1,2; assert((x>y) and x or y == 2); x,y=2,1; assert((x>y) and x or y == 2); assert(1234567890 == tonumber('1234567890') and 1234567890+1 == 1234567891) -- silly loops repeat until 1; repeat until true; while false do end; while nil do end; do -- test old bug (first name could not be an `upvalue') local a; function f(x) x={a=1}; x={x=1}; x={G=1} end end function f (i) if type(i) ~= 'number' then return i,'jojo'; end; if i > 0 then return i, f(i-1); end; end x = {f(3), f(5), f(10);}; assert(x[1] == 3 and x[2] == 5 and x[3] == 10 and x[4] == 9 and x[12] == 1); assert(x[nil] == nil) x = {f'alo', f'xixi', nil}; assert(x[1] == 'alo' and x[2] == 'xixi' and x[3] == nil); x = {f'alo'..'xixi'}; assert(x[1] == 'aloxixi') x = {f{}} assert(x[2] == 'jojo' and type(x[1]) == 'table') local f = function (i) if i < 10 then return 'a'; elseif i < 20 then return 'b'; elseif i < 30 then return 'c'; end; end assert(f(3) == 'a' and f(12) == 'b' and f(26) == 'c' and f(100) == nil) for i=1,1000 do break; end; n=100; i=3; t = {}; a=nil while not a do a=0; for i=1,n do for i=i,1,-1 do a=a+1; t[i]=1; end; end; end assert(a == n*(n+1)/2 and i==3); assert(t[1] and t[n] and not t[0] and not t[n+1]) function f(b) local x = 1; repeat local a; if b==1 then local b=1; x=10; break elseif b==2 then x=20; break; elseif b==3 then x=30; else local a,b,c,d=math.sin(1); x=x+1; end until x>=12; return x; end; assert(f(1) == 10 and f(2) == 20 and f(3) == 30 and f(4)==12) local f = function (i) if i < 10 then return 'a' elseif i < 20 then return 'b' elseif i < 30 then return 'c' else return 8 end end assert(f(3) == 'a' and f(12) == 'b' and f(26) == 'c' and f(100) == 8) local a, b = nil, 23 x = {f(100)*2+3 or a, a or b+2} assert(x[1] == 19 and x[2] == 25) x = {f=2+3 or a, a = b+2} assert(x.f == 5 and x.a == 25) a={y=1} x = {a.y} assert(x[1] == 1) function f(i) while 1 do if i>0 then i=i-1; else return; end; end; end; function g(i) while 1 do if i>0 then i=i-1 else return end end end f(10); g(10); do function f () return 1,2,3; end local a, b, c = f(); assert(a==1 and b==2 and c==3) a, b, c = (f()); assert(a==1 and b==nil and c==nil) end local a,b = 3 and f(); assert(a==1 and b==nil) function g() f(); return; end; assert(g() == nil) function g() return nil or f() end a,b = g() assert(a==1 and b==nil) print'+'; f = [[ return function ( a , b , c , d , e ) local x = a >= b or c or ( d and e ) or nil return x end , { a = 1 , b = 2 >= 1 , } or { 1 }; ]] f = string.gsub(f, "%s+", "\n"); -- force a SETLINE between opcodes f,a = load(f)(); assert(a.a == 1 and a.b) function g (a,b,c,d,e) if not (a>=b or c or d and e or nil) then return 0; else return 1; end; end function h (a,b,c,d,e) while (a>=b or c or (d and e) or nil) do return 1; end; return 0; end; assert(f(2,1) == true and g(2,1) == 1 and h(2,1) == 1) assert(f(1,2,'a') == 'a' and g(1,2,'a') == 1 and h(1,2,'a') == 1) assert(f(1,2,'a') ~= -- force SETLINE before nil nil, "") assert(f(1,2,'a') == 'a' and g(1,2,'a') == 1 and h(1,2,'a') == 1) assert(f(1,2,nil,1,'x') == 'x' and g(1,2,nil,1,'x') == 1 and h(1,2,nil,1,'x') == 1) assert(f(1,2,nil,nil,'x') == nil and g(1,2,nil,nil,'x') == 0 and h(1,2,nil,nil,'x') == 0) assert(f(1,2,nil,1,nil) == nil and g(1,2,nil,1,nil) == 0 and h(1,2,nil,1,nil) == 0) assert(1 and 2<3 == true and 2<3 and 'a'<'b' == true) x = 2<3 and not 3; assert(x==false) x = 2<1 or (2>1 and 'a'); assert(x=='a') do local a; if nil then a=1; else a=2; end; -- this nil comes as PUSHNIL 2 assert(a==2) end function F(a) assert(debug.getinfo(1, "n").name == 'F') return a,2,3 end a,b = F(1)~=nil; assert(a == true and b == nil); a,b = F(nil)==nil; assert(a == true and b == nil) ---------------------------------------------------------------- ------------------------------------------------------------------ -- sometimes will be 0, sometimes will not... _ENV.GLOB1 = math.floor(os.time()) % 2 -- basic expressions with their respective values local basiccases = { {"nil", nil}, {"false", false}, {"true", true}, {"10", 10}, {"(0==_ENV.GLOB1)", 0 == _ENV.GLOB1}, } print('testing short-circuit optimizations (' .. _ENV.GLOB1 .. ')') -- operators with their respective values local binops = { {" and ", function (a,b) if not a then return a else return b end end}, {" or ", function (a,b) if a then return a else return b end end}, } local cases = {} -- creates all combinations of '(cases[i] op cases[n-i])' plus -- 'not(cases[i] op cases[n-i])' (syntax + value) local function createcases (n) local res = {} for i = 1, n - 1 do for _, v1 in ipairs(cases[i]) do for _, v2 in ipairs(cases[n - i]) do for _, op in ipairs(binops) do local t = { "(" .. v1[1] .. op[1] .. v2[1] .. ")", op[2](v1[2], v2[2]) } res[#res + 1] = t res[#res + 1] = {"not" .. t[1], not t[2]} end end end end return res end -- do not do too many combinations for soft tests local level = _soft and 3 or 4 cases[1] = basiccases for i = 2, level do cases[i] = createcases(i) end print("+") local prog = [[if %s then IX = true end; return %s]] local i = 0 for n = 1, level do for _, v in pairs(cases[n]) do local s = v[1] local p = load(string.format(prog, s, s), "") IX = false assert(p() == v[2] and IX == not not v[2]) i = i + 1 if i % 60000 == 0 then print('+') end end end ------------------------------------------------------------------ -- testing some syntax errors (chosen through 'gcov') checkload("for x do", "expected") checkload("x:call", "expected") if not _soft then -- control structure too long local s = string.rep("a = a + 1\n", 2^18) s = "while true do " .. s .. "end" checkload(s, "too long") end print'OK'
mit
Ninjistix/darkstar
scripts/zones/Mine_Shaft_2716/npcs/_0d0.lua
5
2023
----------------------------------- -- Area: Mine_Shaft_2716 -- NPC: Shaft entrance ----------------------------------- package.loaded["scripts/zones/Mine_Shaft_2716/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Mine_Shaft_2716/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getCurrentMission(COP) == THREE_PATHS and ( player:getVar("COP_Louverance_s_Path") == 7 or player:getVar("COP_Louverance_s_Path") == 8 )) then if (trade:getItemCount() == 1 and trade:hasItemQty(1684,1)) then player:startEvent(3); end elseif (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) ==FIRE_IN_THE_EYES_OF_MEN and player:getVar("PromathiaStatus")==0) then player:startEvent(4); elseif (EventTriggerBCNM(player,npc)) then end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (csid ==3) then player:setVar("COP_Louverance_s_Path",9); player:tradeComplete(); elseif (csid ==4) then player:setVar("PromathiaStatus",1); elseif (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
Inorizushi/DDR-SN1HD
Scripts/02 MyGrooveRadar.lua
3
2462
--[[ 01 MyGrooveRadar.lua ]] --Load the setting we need for this. local mgrData = create_setting('MyGrooveRadar','MyGrooveRadar.lua',{ single={chaos=0,air=0,freeze=0,voltage=0,stream=0}, double={chaos=0,air=0,freeze=0,voltage=0,stream=0} }, 2, {}) local categoryToActorMappings = {'stream','voltage','air','freeze','chaos'} local savedCategoryToSMCategory = { stream='RadarCategory_Stream', voltage='RadarCategory_Voltage', air='RadarCategory_Air', freeze='RadarCategory_Freeze', chaos='RadarCategory_Chaos' } MyGrooveRadar = {} function MyGrooveRadar.PackageArbitraryRadarData(tbl, style) if tbl then local out = {} local myVals = tbl[style] if myVals then for idx, category in ipairs(categoryToActorMappings) do out[idx] = myVals[category] or 0 end return out end end --if we did not do this it would crash! return {0,0,0,0,0} end function MyGrooveRadar.GetRadarTable(ident) if not mgrData:is_loaded(ident) then mgrData:load(ident) end return mgrData:get_data(ident) end function MyGrooveRadar.GetRadarData(ident, style, category) local rData = MyGrooveRadar.GetRadarTable(ident) if rData[style] then return rData[style][category] or 0 end return 0 end function MyGrooveRadar.SetRadarData(ident, style, category, value) local rData = MyGrooveRadar.GetRadarTable(ident) if rData[style] then rData[style][category] = value mgrData:set_dirty(ident) end end function MyGrooveRadar.SaveAllRadarData() return mgrData:save_all() end function MyGrooveRadar.GetRadarDataPackaged(ident, style) local out = {} for idx, category in pairs(categoryToActorMappings) do out[idx] = MyGrooveRadar.GetRadarData(ident, style, category) end return out end function MyGrooveRadar.ApplyBonuses(ident, stageStats, styleName) local actualRadar = stageStats:GetRadarActual() local possibleRadar = stageStats:GetRadarPossible() for savedCat, stepsCat in pairs(savedCategoryToSMCategory) do local earnedValue = actualRadar:GetValue(stepsCat)*possibleRadar:GetValue(stepsCat) local savedValue = MyGrooveRadar.GetRadarData(ident, styleName, savedCat) if savedValue < earnedValue then MyGrooveRadar.SetRadarData(ident, styleName, savedCat, savedValue + (earnedValue-savedValue)/10) end end end
gpl-3.0
Ninjistix/darkstar
scripts/zones/Chamber_of_Oracles/bcnms/through_the_quicksand_caves.lua
5
1958
----------------------------------- -- Area: Qu'Bia Arena -- Name: Zilart Mission 6 -- !pos -221 -24 19 206 ----------------------------------- package.loaded["scripts/zones/Sacrificial_Chamber/TextIDs"] = nil; ------------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Sacrificial_Chamber/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:getCurrentMission(ZILART) == THROUGH_THE_QUICKSAND_CAVES) then player:startEvent(32001,1,1,1,instance:getTimeInside(),1,0,0); else player:startEvent(32001,1,1,1,instance:getTimeInside(),1,0,1); end elseif (leavecode == 4) then player:startEvent(32002); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 32001) then if (player:getCurrentMission(ZILART) == THROUGH_THE_QUICKSAND_CAVES) then player:completeMission(ZILART,THROUGH_THE_QUICKSAND_CAVES); player:addMission(ZILART,THE_CHAMBER_OF_ORACLES); end end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Despachiaire.lua
5
2356
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Despachiaire -- !pos 108 -40 -83 26 ----------------------------------- require("scripts/globals/missions"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local currentCOPMission = player:getCurrentMission(COP); local LouverancePathStatut = player:getVar("COP_Louverance_s_Path"); if (currentCOPMission == THE_LOST_CITY and player:getVar("PromathiaStatus") == 0) then player:startEvent(102); elseif (currentCOPMission == SHELTERING_DOUBT and player:getVar("PromathiaStatus") == 1) then player:startEvent(108); elseif (currentCOPMission == THE_ENDURING_TUMULT_OF_WAR and player:getVar("COP_optional_CS_Despachaire") == 0) then player:startEvent(117); --117 elseif (currentCOPMission == THREE_PATHS and LouverancePathStatut == 0) then player:startEvent(118); elseif (currentCOPMission == THREE_PATHS and LouverancePathStatut == 1 ) then player:startEvent(134); else player:startEvent(106); end end; --Despachiaire 102 ++ --Despachiaire 104 ++ --Despachiaire 106 ++ --Despachiaire 107 ++ --Despachiaire 108 ++ --Despachiaire 110 ++ --Despachiaire 112 ++ --Despachiaire 117 ++ --Despachiaire 118 ++ --Despachiaire 132 --Despachiaire 133 --Despachiaire 134 ?? --Despachiaire 139 --Despachiaire 144 chat --Despachiaire 149 XX --Despachiaire 315 chat --Despachiaire 317 chat --Despachiaire 318 chat --Despachiaire 505 CS --Despachiaire 517 CS (despachiaire's wife) --Despachiaire 518 CS (ulmia mother) --Despachiaire 576 CS --Despachiaire 577 chat --Despachiaire 578 chat --Despachiaire 579 chat --Despachiaire 617 XX --Despachiaire 618 XX function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 102 or csid == 108) then player:setVar("PromathiaStatus",2); elseif (csid == 117) then player:setVar("COP_optional_CS_Despachaire",1); elseif (csid == 118) then player:setVar("COP_Louverance_s_Path",1); end end;
gpl-3.0
mandersan/premake-core
tests/base/test_validation.lua
32
2642
-- -- tests/base/test_validation.lua -- Verify the project information sanity checking. -- Copyright (c) 2013-20124 Jason Perkins and the Premake project -- local suite = test.declare("premake_validation") local p = premake -- -- Setup -- local function validate() return pcall(function() p.container.validate(p.api.rootContainer()) end) end -- -- Validate should pass if the minimum requirements are met. -- function suite.passes_onSane() workspace("MyWorkspace") configurations { "Debug", "Release" } project "MyProject" kind "ConsoleApp" language "C++" test.istrue(validate()) end -- -- Fail if no configurations are present on the workspace. -- function suite.fails_onNoWorkspaceConfigs() workspace "MyWorkspace" project "MyProject" kind "ConsoleApp" language "C++" test.isfalse(validate()) end -- -- Fail on duplicate project UUIDs. -- function suite.fails_onDuplicateProjectIDs() workspace "MyWorkspace" configurations { "Debug", "Release" } kind "ConsoleApp" language "C++" project "MyProject1" uuid "D4110D7D-FB18-4A1C-A75B-CA432F4FE770" project "MyProject2" uuid "D4110D7D-FB18-4A1C-A75B-CA432F4FE770" test.isfalse(validate()) end -- -- Fail if no kind is set on the configuration. -- function suite.fails_onNoConfigKind() workspace "MyWorkspace" configurations { "Debug", "Release" } project "MyProject" language "C++" test.isfalse(validate()) end -- -- Warn if a configuration value is set in the wrong scope. -- function suite.warns_onWorkspaceStringField_inConfig() workspace "MyWorkspace" configurations { "Debug", "Release" } filter "Debug" startproject "MyProject" project "MyProject" kind "ConsoleApp" language "C++" validate() test.stderr("'startproject' on config") end function suite.warns_onProjectStringField_inConfig() workspace "MyWorkspace" configurations { "Debug", "Release" } project "MyProject" kind "ConsoleApp" language "C++" filter "Debug" location "MyProject" validate() test.stderr("'location' on config") end function suite.warns_onProjectListField_inConfig() workspace "MyWorkspace" configurations { "Debug", "Release" } project "MyProject" kind "ConsoleApp" language "C++" filter "Debug" configurations "Deployment" validate() test.stderr("'configurations' on config") end -- -- If a rule is specified for inclusion, it must have been defined. -- function suite.fails_onNoSuchRule() workspace "MyWorkspace" configurations { "Debug", "Release" } project "MyProject" rules { "NoSuchRule" } test.isfalse(validate()) end
bsd-3-clause
Ninjistix/darkstar
scripts/globals/spells/bluemagic/regurgitation.lua
3
2145
----------------------------------------- -- Spell: Regurgitation -- Deals Water damage to an enemy. Additional Effect: Bind -- Spell cost: 69 MP -- Monster Type: Lizards -- Spell Type: Magical (Water) -- Blue Magic Points: 1 -- Stat Bonus: INT+1 MND+1 MP+3 -- Level: 68 -- Casting Time: 5 seconds -- Recast Time: 24 seconds -- Magic Bursts on: Reverberation, Distortion, and Darkness -- Combos: Resist Gravity ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; params.multiplier = 1.83; params.tMultiplier = 2.0; params.duppercap = 69; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.30; params.chr_wsc = 0.0; damage = BlueMagicalSpell(caster, target, spell, params, INT_BASED); if (caster:isBehind(target, 15)) then -- guesstimating the angle at 15 degrees here damage = math.floor(damage * 1.25); -- printf("is behind mob") end; damage = BlueFinalAdjustments(caster, target, spell, damage, params); --TODO: Knockback? Where does that get handled? How much knockback does it have? local params = {}; params.diff = caster:getStat(MOD_INT) - target:getStat(MOD_INT); params.attribute = MOD_INT; params.skillType = BLUE_SKILL; params.bonus = 1.0; local resist = applyResistance(caster, target, spell, params); if (damage > 0 and resist > 0.125) then local typeEffect = EFFECT_BIND; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,1,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
dafei2015/hugular_cstolua
Client/Assets/Lua/core/listener.lua
15
1290
-- -------------------------------------------------------------------------------- -- FILE: listener.lua -- DESCRIPTION: protoc-gen-lua -- Google's Protocol Buffers project, ported to lua. -- https://code.google.com/p/protoc-gen-lua/ -- -- Copyright (c) 2010 , 林卓毅 (Zhuoyi Lin) netsnail@gmail.com -- All rights reserved. -- -- Use, modification and distribution are subject to the "New BSD License" -- as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. -- -- COMPANY: NetEase -- CREATED: 2010年08月02日 17时35分25秒 CST -------------------------------------------------------------------------------- -- local setmetatable = setmetatable module "listener" local _null_listener = { Modified = function() end } function NullMessageListener() return _null_listener end local _listener_meta = { Modified = function(self) if self.dirty then return end if self._parent_message then self._parent_message:_Modified() end end } _listener_meta.__index = _listener_meta function Listener(parent_message) local o = {} o.__mode = "v" o._parent_message = parent_message o.dirty = false return setmetatable(o, _listener_meta) end
mit
ahmetabdi/JC2-MP-Racing
server/sCourseFileLoader.lua
2
11655
-- Datablock names and their default values. class("INFO") function INFO:__init() self.datablockType = "INFO" self.name = "unnamed course" self.type = "linear" self.laps = 1 self.lapTimeMinutes = 0 self.lapTimeSeconds = 0 self.hourStart = 10 self.hourFinish = 14 self.checkpointRadiusMult = 1 self.weatherSeverity = -1 -- -1 = random self.constantCheckpointOffset = {} self.authors = {} end class("STARTGRID") function STARTGRID:__init() self.datablockType = "STARTGRID" self.path = {} -- Cubically interped curve that the vehicles spawn along. self.width = 12 self.numVehiclesPerRow = 2 self.rowSpacing = 24 self.vehicles = {} self.vehicleTemplates = {} self.vehicleDecals = {} self.fixedVehicleRotation = Angle(0 , 0 , 0) end class("CHECKPOINT") function CHECKPOINT:__init() self.datablockType = "CHECKPOINT" self.position = Vector3(0 , 0 , 0) self.vehicles = {} end ---------------------------------------------------------------------------------------------------- -- CourseFileLoader ---------------------------------------------------------------------------------------------------- CourseLoader = {} CourseLoader.Load = function(name) if settings.debugLevel >= 2 then print("Loading course file: "..name) end -- local path = settings.coursesPath..name..".course" local path = name hasError = false local PrintError = function(message) print() print("*ERROR*") print(path..": "..message) print() hasError = true end local PrintWarning = function(message) print() print("*WARNING*") print(path..": "..message) print() end -- -- Make sure file exists. -- if path == nil then print() print("*ERROR*") print("Course path is nil!") print() return nil end local tempFile , tempFileError = io.open(path , "r") if tempFile then io.close(tempFile) else print() print("*ERROR*") print(tempFileError) print() return nil end -- Final data retrieved from file. -- Includes instances of classes above. local datablocks = {} -- This will be added to datablocks multiple times. -- It is set to a new instance of a class above when -- a line with only capital letters is found. local currentDatablock = nil local lineNum = 0 -- -- Loop through all lines in the file, getting datablocks. -- for line in io.lines(path) do lineNum = lineNum + 1 line = CourseLoader.TrimCommentsFromLine(line) -- Make sure that the current line has stuff in it. if string.find(line , "%S") then -- If this line is entirely capital letters, change currentDatablock. if string.find(line , "%u") and not string.find(line , "%U") then -- TODO: error checking -- Add currentDatablock to datablocks if it's not null. if currentDatablock then table.insert(datablocks , currentDatablock) end -- Instantiate a class with name of line. currentDatablock = _G[line]() -- Lua less than three. -- Otherwise, add values to currentDatablock. elseif currentDatablock ~= nil then -- Split variable name and variable. local varName , rest = CourseLoader.TrimNameValueFromLine(line) -- Add the variable to the current datablock. if varName and rest then -- *** Special cases *** if currentDatablock.datablockType == "STARTGRID" and varName == "path" then table.insert( currentDatablock.path , CourseLoader.Cast( rest , "table" ) ) elseif currentDatablock.datablockType == "INFO" and varName == "author" then table.insert( currentDatablock.authors , rest ) elseif currentDatablock.datablockType == "CHECKPOINT" and varName == "vehicle" then table.insert( currentDatablock.vehicles , rest ) elseif currentDatablock.datablockType == "STARTGRID" and varName == "vehicle" then table.insert( currentDatablock.vehicles , tonumber(rest) ) elseif currentDatablock.datablockType == "STARTGRID" and varName == "vehicleTemplate" then table.insert( currentDatablock.vehicleTemplates , rest ) elseif currentDatablock.datablockType == "STARTGRID" and varName == "vehicleDecal" then table.insert( currentDatablock.vehicleDecals , rest ) else -- *** Generic cases *** Just add the variable. currentDatablock[varName] = CourseLoader.Cast( rest , type(currentDatablock[varName]) ) end else print() print("*PARSE ERROR*") print( "CourseFileLoader".. ": ".. path.. ":" ) print(lineNum..": "..'"'..line..'"') print() return nil end end end -- if string.find(line , "%S") then end -- for line in io.lines(path) do -- Add currentDatablock to datablocks if it's not null. if currentDatablock then table.insert(datablocks , currentDatablock) end -- -- Take datablocks and turn it into a Course to return at the end. -- local course = Course() local startGrids = {} local checkpointRadiusMult = 1 for n=1 , #datablocks do if datablocks[n].datablockType == "STARTGRID" then table.insert(startGrids , datablocks[n]) elseif datablocks[n].datablockType == "INFO" then local info = datablocks[n] course.name = info.name course.type = info.type course.numLaps = info.laps course.authors = info.authors local lapTimeSeconds = info.lapTimeMinutes * 60 + info.lapTimeSeconds course.weatherSeverity = info.weatherSeverity checkpointRadiusMult = info.checkpointRadiusMult elseif datablocks[n].datablockType == "CHECKPOINT" then local cp = CourseCheckpoint(course) table.insert(course.checkpoints , cp) cp.index = #course.checkpoints cp.position = datablocks[n].position cp.validVehicles = datablocks[n].vehicles cp.radius = cp.radius * checkpointRadiusMult end end -- Loop through startGrids and generate course.spawns. for index , startGrid in pairs(startGrids) do -- Get rough length first. local lengthRough = 0 -- Net distance between straight lines. local length = 0 -- Estimated distance along the interpolated curve. for n = 1 , #startGrid.path - 1 do lengthRough = ( lengthRough + Vector3.Distance(startGrid.path[n] , startGrid.path[n+1]) ) end local numSamples = math.floor(lengthRough / 8) -- Per line. local previousPoint = startGrid.path[1] local nextPoint = {} local sectionLengths = {} -- Like above, but divided by total length. Used in GetPointOnCurve. -- The last element should always be 1.0. for a = 1 , #startGrid.path - 1 do sectionLengths[a] = 0 for b = 1 , numSamples do nextPoint = Utility.VectorCuberp( startGrid.path[a-1] , startGrid.path[a+0] , startGrid.path[a+1] , startGrid.path[a+2] , b / numSamples ) sectionLengths[a] = ( sectionLengths[a] + Vector3.Distance( previousPoint , nextPoint ) ) previousPoint = nextPoint end length = length + sectionLengths[a] end local sectionDivides = {} -- Get sectionDivides from sectionLengths. local currentLength = 0 for n=1 , #sectionLengths do currentLength = currentLength + sectionLengths[n] sectionDivides[n] = currentLength / length end -- x should be between 0 and 1. local GetPointOnCurve = function(x) for n = 1 , #sectionDivides do -- print("SDs - "..self.sectionDivides[n]) if x <= sectionDivides[n] then return Utility.VectorCuberp( startGrid.path[n-1] , startGrid.path[n+0] , startGrid.path[n+1] , startGrid.path[n+2] , ( (x - (sectionDivides[n - 1] or 0)) / (sectionDivides[n] - (sectionDivides[n - 1] or 0)) ) ) end end print("This code shouldn't ever be reached!") assert(false) end -- This is the function used to get the vehicle's positions. -- x and y should be between 0 and 1. local GetPoint = function(x , y) local curvePos = GetPointOnCurve(y) -- We need the vector pointing right. This is found by -- rotating the direction of the forward vector by 90 degrees. local forward = {} local right = {} if y > 0.5 then forward = GetPointOnCurve(y - 0.02) if not curvePos then print("y = "..y) -- 0.769 end forward = curvePos - forward else forward = GetPointOnCurve(y + 0.02) forward = forward - curvePos end forward = forward:Normalized() -- forward rotated by 90 degrees to the right. right = Vector3(forward.z , forward.y , -forward.x) -- Get angle from forward vector. local angle = Angle.FromVectors(Vector3(0 , 0 , 1) , forward) angle.roll = 0 return curvePos + right * (startGrid.width * 0.5 * (x * 2 - 1)) , angle end local intervalX = 1 / (startGrid.numVehiclesPerRow - 1) local numRows = length / startGrid.rowSpacing local intervalY = 1 / numRows if startGrid.numVehiclesPerRow == 1 then intervalX = 2 end -- Set up course.spawns. for y = 0 , 1 , intervalY do for x = 0 , 1 , intervalX do if startGrid.numVehiclesPerRow == 1 then x = 0.5 end local position , angle = GetPoint(x , y) if startGrid.fixedVehicleRotation ~= Angle(0 , 0 , 0) then angle = startGrid.fixedVehicleRotation end local spawn = CourseSpawn(course) spawn.position = position spawn.angle = angle spawn.modelIds = startGrid.vehicles spawn.templates = startGrid.vehicleTemplates spawn.decals = startGrid.vehicleDecals table.insert(course.spawns , spawn) end end end -- for index , startGrid in pairs(startGrids) do if settings.debugLevel >= 2 then print("Course loaded: "..course.name) end return course end ---------------------------------------------------------------------------------------------------- -- Utility functions ---------------------------------------------------------------------------------------------------- -- name Awesome Course Name # What an awesome Course name! -- | -- v -- "name Awesome Course Name" CourseLoader.TrimCommentsFromLine = function(line) -- Holy balls, patterns are awesome. line = string.gsub(line , "%s*#.*" , "") -- *nix compatability. line = string.gsub(line, "\r", "") line = string.gsub(line, "\n", "") return line end -- name Awesome Course Name -- | -- v -- "name" , "Awesome Course Name" CourseLoader.TrimNameValueFromLine = function(line) local a , b = string.find(line , "%s+") if a and b then return string.sub(line , 1 , a-1) , string.sub(line , b+1) else -- error return nil end end -- Takes a string and converts it to a value. -- -- Examples: -- -- Cast("This is an awesome string!" , "string") --> "This is an awesome string!" -- Cast("42" , "number") --> 42 -- Cast("-31.5, 17, 1.0005" , "table") --> {-31.5 , 17 , 1.0005} -- CourseLoader.Cast = function(input , type) if type == "number" then return tonumber(input) end if type == "string" then return input end -- Return a vector or quat when the number of elements match. if type == "table" or type == "userdata" then local elementArray = {} for word in string.gmatch(input , "[^, ]+") do table.insert(elementArray , tonumber(word)) end if #elementArray == 3 then return Vector3(elementArray[1] , elementArray[2] , elementArray[3]) elseif #elementArray == 4 then return Angle( elementArray[1] , elementArray[2] , elementArray[3] , elementArray[4] ) else return elementArray end end end
mit
Ninjistix/darkstar
scripts/zones/Oldton_Movalpolos/Zone.lua
6
1734
----------------------------------- -- -- Zone: Oldton_Movalpolos (11) -- ----------------------------------- package.loaded["scripts/zones/Oldton_Movalpolos/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Oldton_Movalpolos/TextIDs"); require("scripts/zones/Oldton_Movalpolos/MobIDs"); require("scripts/globals/conquest"); require("scripts/globals/missions"); ----------------------------------- function onInitialize(zone) UpdateTreasureSpawnPoint(OLDTON_TREASURE_CHEST); SetRegionalConquestOverseers(zone:getRegionID()) end; function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; function onZoneIn(player,prevZone) local currentday = tonumber(os.date("%j")); local LouverancePath=player:getVar("COP_Louverance_s_Path"); local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(70.956,5.99,139.843,134); end if (player:getCurrentMission(COP) == THREE_PATHS and (LouverancePath == 3 or LouverancePath == 4)) then cs=1; elseif (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==3 and player:getVar("Promathia_kill_day")~=currentday and player:getVar("COP_jabbos_story")== 0 ) then cs=57; end return cs; end; function onRegionEnter(player,region) end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid==1) then player:setVar("COP_Louverance_s_Path",5); elseif (csid == 57) then player:setVar("COP_jabbos_story",1); end end;
gpl-3.0
davidbuzz/ardupilot
libraries/AP_Scripting/applets/VTOL-quicktune.lua
2
14525
--[[ fast tuning of VTOL gains for multirotors and quadplanes This should be used in QLOITER mode for quadplanes and LOITER mode for copters, although it will work in other VTOL modes --]] --[[ - TODO: - disable weathervaning while tuning? - possibly lower P XY gains during tuning? - bail out on a large angle error? --]] local MAV_SEVERITY_INFO = 6 local MAV_SEVERITY_NOTICE = 5 local MAV_SEVERITY_EMERGENCY = 0 local PARAM_TABLE_KEY = 8 local PARAM_TABLE_PREFIX = "QUIK_" local is_quadplane = false local atc_prefix = "ATC" -- bind a parameter to a variable function bind_param(name) local p = Parameter() assert(p:init(name), string.format('could not find %s parameter', name)) return p end -- add a parameter and bind it to a variable function bind_add_param(name, idx, default_value) assert(param:add_param(PARAM_TABLE_KEY, idx, name, default_value), string.format('could not add param %s', name)) return bind_param(PARAM_TABLE_PREFIX .. name) end -- setup quicktune specific parameters assert(param:add_table(PARAM_TABLE_KEY, PARAM_TABLE_PREFIX, 11), 'could not add param table') local QUIK_ENABLE = bind_add_param('ENABLE', 1, 0) local QUIK_AXES = bind_add_param('AXES', 2, 7) local QUIK_DOUBLE_TIME = bind_add_param('DOUBLE_TIME', 3, 10) local QUIK_GAIN_MARGIN = bind_add_param('GAIN_MARGIN', 4, 60) local QUIK_OSC_SMAX = bind_add_param('OSC_SMAX', 5, 5) local QUIK_YAW_P_MAX = bind_add_param('YAW_P_MAX', 6, 0.5) local QUIK_YAW_D_MAX = bind_add_param('YAW_D_MAX', 7, 0.01) local QUIK_RP_PI_RATIO = bind_add_param('RP_PI_RATIO', 8, 1.0) local QUIK_Y_PI_RATIO = bind_add_param('Y_PI_RATIO', 9, 10) local QUIK_AUTO_FILTER = bind_add_param('AUTO_FILTER', 10, 1) local QUIK_AUTO_SAVE = bind_add_param('AUTO_SAVE', 11, 0) local INS_GYRO_FILTER = bind_param("INS_GYRO_FILTER") local RCMAP_ROLL = bind_param("RCMAP_ROLL") local RCMAP_PITCH = bind_param("RCMAP_PITCH") local RCMAP_YAW = bind_param("RCMAP_YAW") local RCIN_ROLL = rc:get_channel(RCMAP_ROLL:get()) local RCIN_PITCH = rc:get_channel(RCMAP_PITCH:get()) local RCIN_YAW = rc:get_channel(RCMAP_YAW:get()) local UPDATE_RATE_HZ = 40 local STAGE_DELAY = 4.0 local PILOT_INPUT_DELAY = 4.0 local YAW_FLTE_MAX = 2.0 local FLTD_MUL = 0.5 local FLTT_MUL = 0.5 -- SMAX to set if none set at start local DEFAULT_SMAX = 50.0 -- work out vehicle type if param:get("Q_A_RAT_RLL_SMAX") then is_quadplane = true atc_prefix = "Q_A" gcs:send_text(MAV_SEVERITY_EMERGENCY, "Quicktune for quadplane loaded") elseif param:get("ATC_RAT_RLL_SMAX") then is_quadplane = false gcs:send_text(MAV_SEVERITY_EMERGENCY, "Quicktune for multicopter loaded") else gcs:send_text(MAV_SEVERITY_EMERGENCY, "Quicktune unknown vehicle") return end -- get time in seconds since boot function get_time() return millis():tofloat() * 0.001 end local axis_names = { "RLL", "PIT", "YAW" } local param_suffixes = { "FF", "P", "I", "D", "SMAX", "FLTT", "FLTD", "FLTE" } local stages = { "D", "P" } local stage = stages[1] local last_stage_change = get_time() local last_gain_report = get_time() local last_pilot_input = get_time() local last_notice = get_time() local tune_done_time = nil local slew_parm = nil local slew_target = 0 local slew_delta = 0 local axes_done = {} local filters_done = {} -- create params dictionary indexed by name, such as "RLL_P" local params = {} local param_saved = {} local param_changed = {} local need_restore = false for i, axis in ipairs(axis_names) do for j, suffix in ipairs(param_suffixes) do local pname = axis .. "_" .. suffix params[pname] = bind_param(atc_prefix .. "_" .. "RAT_" .. pname) param_changed[pname] = false end end -- reset to start function reset_axes_done() for i, axis in ipairs(axis_names) do axes_done[axis] = false filters_done[axis] = false end stage = stages[1] end -- get all current param values into param_saved dictionary function get_all_params() for pname in pairs(params) do param_saved[pname] = params[pname]:get() end end -- restore all param values from param_saved dictionary function restore_all_params() for pname in pairs(params) do local changed = param_changed[pname] and 1 or 0 if param_changed[pname] then params[pname]:set(param_saved[pname]) param_changed[pname] = false end end end -- save all param values to storage function save_all_params() for pname in pairs(params) do if param_changed[pname] then params[pname]:set_and_save(params[pname]:get()) param_saved[pname] = params[pname]:get() param_changed[pname] = false end end end -- setup a default SMAX if zero function setup_SMAX() for i, axis in ipairs(axis_names) do local smax = axis .. "_SMAX" if params[smax]:get() <= 0 then adjust_gain(smax, DEFAULT_SMAX) end end end -- setup filter frequencies function setup_filters(axis) local fltd = axis .. "_FLTD" local fltt = axis .. "_FLTT" local flte = axis .. "_FLTE" adjust_gain(fltt, INS_GYRO_FILTER:get() * FLTT_MUL) adjust_gain(fltd, INS_GYRO_FILTER:get() * FLTD_MUL) if axis == "YAW" then local FLTE = params[flte] if FLTE:get() <= 0.0 or FLTE:get() > YAW_FLTE_MAX then adjust_gain(flte, YAW_FLTE_MAX) end end filters_done[axis] = true end -- check for pilot input to pause tune function have_pilot_input() if (math.abs(RCIN_ROLL:norm_input_dz()) > 0 or math.abs(RCIN_PITCH:norm_input_dz()) > 0 or math.abs(RCIN_YAW:norm_input_dz()) > 0) then return true end return false end reset_axes_done() get_all_params() -- 3 position switch local quick_switch = nil function axis_enabled(axis) local axes = QUIK_AXES:get() for i = 1, #axis_names do local mask = (1 << (i-1)) local axis_name = axis_names[i] if axis == axis_name and (mask & axes) ~= 0 then return true end end return false end -- get the axis name we are working on, or nil for all done function get_current_axis() local axes = QUIK_AXES:get() for i = 1, #axis_names do local mask = (1 << (i-1)) local axis_name = axis_names[i] if (mask & axes) ~= 0 and axes_done[axis_name] == false then return axis_names[i] end end return nil end -- get slew rate for an axis function get_slew_rate(axis) local roll_srate, pitch_srate, yaw_srate = AC_AttitudeControl:get_rpy_srate() if axis == "RLL" then return roll_srate end if axis == "PIT" then return pitch_srate end if axis == "YAW" then return yaw_srate end return 0.0 end -- move to next stage of tune function advance_stage(axis) if stage == "D" then stage = "P" else axes_done[axis] = true gcs:send_text(5, string.format("Tuning: %s done", axis)) stage = "D" end end -- get param name, such as RLL_P, used as index into param dictionaries function get_pname(axis, stage) return axis .. "_" .. stage end -- get axis name from parameter name function param_axis(pname) return string.sub(pname, 1, 3) end -- get parameter suffix from parameter name function param_suffix(pname) return string.sub(pname, 4) end -- change a gain function adjust_gain(pname, value) local P = params[pname] need_restore = true param_changed[pname] = true P:set(value) if string.sub(pname, -2) == "_P" then -- also change I gain local iname = string.gsub(pname, "_P", "_I") local ffname = string.gsub(pname, "_P", "_FF") local I = params[iname] local FF = params[ffname] if FF:get() > 0 then -- if we have any FF on an axis then we don't couple I to P, -- usually we want I = FF for a one sectond time constant for trim return end param_changed[iname] = true -- work out ratio of P to I that we want local PI_ratio = QUIK_RP_PI_RATIO:get() if param_axis(pname) == "YAW" then PI_ratio = QUIK_Y_PI_RATIO:get() end if PI_ratio >= 1 then I:set(value/PI_ratio) end end end -- return gain multipler for one loop function get_gain_mul() return math.exp(math.log(2.0)/(UPDATE_RATE_HZ*QUIK_DOUBLE_TIME:get())) end function setup_slew_gain(pname, gain) slew_parm = pname slew_target = gain slew_steps = UPDATE_RATE_HZ/2 slew_delta = (gain - params[pname]:get()) / slew_steps end function update_slew_gain() if slew_parm ~= nil then local P = params[slew_parm] local axis = param_axis(slew_parm) local ax_stage = string.sub(slew_parm, -1) adjust_gain(slew_parm, P:get()+slew_delta) slew_steps = slew_steps - 1 logger.write('QUIK','SRate,Gain,Param', 'ffn', get_slew_rate(axis), P:get(), axis .. ax_stage) if slew_steps == 0 then gcs:send_text(MAV_SEVERITY_INFO, string.format("%s %.4f", slew_parm, P:get())) slew_parm = nil if get_current_axis() == nil then gcs:send_text(MAV_SEVERITY_NOTICE, string.format("Tuning: DONE")) tune_done_time = get_time() end end end end -- return gain limits on a parameter, or 0 for no limit function gain_limit(pname) if param_axis(pname) == "YAW" then local suffix = param_suffix(pname) if suffix == "_P" then return QUIK_YAW_P_MAX:get() end if suffix == "_D" then return QUIK_YAW_D_MAX:get() end end return 0.0 end function reached_limit(pname, gain) local limit = gain_limit(pname) if limit > 0.0 and gain >= limit then return true end return false end -- main update function local last_warning = get_time() function update() if quick_switch == nil then quick_switch = rc:find_channel_for_option(300) end if quick_switch == nil or QUIK_ENABLE:get() < 1 then return end if have_pilot_input() then last_pilot_input = get_time() end local sw_pos = quick_switch:get_aux_switch_pos() if sw_pos == 1 and (not arming:is_armed() or not vehicle:get_likely_flying()) and get_time() > last_warning + 5 then gcs:send_text(MAV_SEVERITY_EMERGENCY, string.format("Tuning: Must be flying to tune")) last_warning = get_time() return end if sw_pos == 0 or not arming:is_armed() or not vehicle:get_likely_flying() then -- abort, revert parameters if need_restore then need_restore = false restore_all_params() gcs:send_text(MAV_SEVERITY_EMERGENCY, string.format("Tuning: reverted")) tune_done_time = nil end reset_axes_done() return end if sw_pos == 2 then -- save all params if need_restore then need_restore = false save_all_params() gcs:send_text(MAV_SEVERITY_NOTICE, string.format("Tuning: saved")) end end if sw_pos ~= 1 then return end if get_time() - last_stage_change < STAGE_DELAY then update_slew_gain() return end axis = get_current_axis() if axis == nil then -- nothing left to do, check autosave time if tune_done_time ~= nil and QUIK_AUTO_SAVE:get() > 0 then if get_time() - tune_done_time > QUIK_AUTO_SAVE:get() then need_restore = false save_all_params() gcs:send_text(MAV_SEVERITY_NOTICE, string.format("Tuning: saved")) tune_done_time = nil end end return end if not need_restore then -- we are just starting tuning, get current values gcs:send_text(MAV_SEVERITY_NOTICE, string.format("Tuning: starting tune")) get_all_params() setup_SMAX() end if get_time() - last_pilot_input < PILOT_INPUT_DELAY then return end if not filters_done[axis] then gcs:send_text(MAV_SEVERITY_INFO, string.format("Starting %s tune", axis)) setup_filters(axis) end local srate = get_slew_rate(axis) local pname = get_pname(axis, stage) local P = params[pname] local oscillating = srate > QUIK_OSC_SMAX:get() local limited = reached_limit(pname, P:get()) if limited or oscillating then local reduction = (100.0-QUIK_GAIN_MARGIN:get())*0.01 if not oscillating then reduction = 1.0 end local new_gain = P:get() * reduction local limit = gain_limit(pname) if limit > 0.0 and new_gain > limit then new_gain = limit end local old_gain = param_saved[pname] if new_gain < old_gain and string.sub(pname,-2) == '_D' and param_axis(pname) ~= 'YAW' then -- we are lowering a D gain from the original gain. Also lower the P gain by the same amount -- so that we don't trigger P oscillation. We don't drop P by more than a factor of 2 local ratio = math.max(new_gain / old_gain, 0.5) local P_name = string.gsub(pname, "_D", "_P") local old_P = params[P_name]:get() local new_P = old_P * ratio gcs:send_text(MAV_SEVERITY_INFO, string.format("adjusting %s %.3f -> %.3f", P_name, old_P, new_P)) adjust_gain(P_name, new_P) end setup_slew_gain(pname, new_gain) logger.write('QUIK','SRate,Gain,Param', 'ffn', srate, P:get(), axis .. stage) gcs:send_text(6, string.format("Tuning: %s done", pname)) advance_stage(axis) last_stage_change = get_time() else local new_gain = P:get()*get_gain_mul() if new_gain <= 0.0001 then new_gain = 0.001 end adjust_gain(pname, new_gain) logger.write('QUIK','SRate,Gain,Param', 'ffn', srate, P:get(), axis .. stage) if get_time() - last_gain_report > 3 then last_gain_report = get_time() gcs:send_text(MAV_SEVERITY_INFO, string.format("%s %.4f sr:%.2f", pname, new_gain, srate)) end end end -- wrapper around update(). This calls update() at 10Hz, -- and if update faults then an error is displayed, but the script is not -- stopped function protected_wrapper() local success, err = pcall(update) if not success then gcs:send_text(MAV_SEVERITY_EMERGENCY, "Internal Error: " .. err) -- when we fault we run the update function again after 1s, slowing it -- down a bit so we don't flood the console with errors --return protected_wrapper, 1000 return end return protected_wrapper, 1000/UPDATE_RATE_HZ end -- start running update loop return protected_wrapper()
gpl-3.0
Ninjistix/darkstar
scripts/zones/Spire_of_Vahzl/npcs/_0n1.lua
66
1356
----------------------------------- -- Area: Spire_of_vahlz -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Vahzl/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Vahzl/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Spire_of_Vahzl/npcs/_0n2.lua
66
1356
----------------------------------- -- Area: Spire_of_vahlz -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Vahzl/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Vahzl/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
kylesusername/void-packages
srcpkgs/prosody/files/prosody.cfg.lua
97
7823
-- Prosody Example Configuration File -- -- Information on configuring Prosody can be found on our -- website at http://prosody.im/doc/configure -- -- Tip: You can check that the syntax of this file is correct -- when you have finished by running: luac -p prosody.cfg.lua -- If there are any errors, it will let you know what and where -- they are, otherwise it will keep quiet. -- -- The only thing left to do is rename this file to remove the .dist ending, and fill in the -- blanks. Good luck, and happy Jabbering! ------ Void settings ------ daemonize = false; pidfile = "/run/prosody/prosody.pid" ---------- Server-wide settings ---------- -- Settings in this section apply to the whole server and are the default settings -- for any virtual hosts -- This is a (by default, empty) list of accounts that are admins -- for the server. Note that you must create the accounts separately -- (see http://prosody.im/doc/creating_accounts for info) -- Example: admins = { "user1@example.com", "user2@example.net" } admins = { } -- Enable use of libevent for better performance under high load -- For more information see: http://prosody.im/doc/libevent --use_libevent = true; -- This is the list of modules Prosody will load on startup. -- It looks for mod_modulename.lua in the plugins folder, so make sure that exists too. -- Documentation on modules can be found at: http://prosody.im/doc/modules modules_enabled = { -- Generally required "roster"; -- Allow users to have a roster. Recommended ;) "saslauth"; -- Authentication for clients and servers. Recommended if you want to log in. "tls"; -- Add support for secure TLS on c2s/s2s connections "dialback"; -- s2s dialback support "disco"; -- Service discovery -- Not essential, but recommended "private"; -- Private XML storage (for room bookmarks, etc.) "vcard"; -- Allow users to set vCards -- These are commented by default as they have a performance impact --"privacy"; -- Support privacy lists --"compression"; -- Stream compression -- Nice to have "version"; -- Replies to server version requests "uptime"; -- Report how long server has been running "time"; -- Let others know the time here on this server "ping"; -- Replies to XMPP pings with pongs "pep"; -- Enables users to publish their mood, activity, playing music and more "register"; -- Allow users to register on this server using a client and change passwords -- Admin interfaces "admin_adhoc"; -- Allows administration via an XMPP client that supports ad-hoc commands --"admin_telnet"; -- Opens telnet console interface on localhost port 5582 -- HTTP modules --"bosh"; -- Enable BOSH clients, aka "Jabber over HTTP" --"http_files"; -- Serve static files from a directory over HTTP -- Other specific functionality "posix"; -- POSIX functionality, sends server to background, enables syslog, etc. (Keep enabled for Void.) --"groups"; -- Shared roster support --"announce"; -- Send announcement to all online users --"welcome"; -- Welcome users who register accounts --"watchregistrations"; -- Alert admins of registrations --"motd"; -- Send a message to users when they log in --"legacyauth"; -- Legacy authentication. Only used by some old clients and bots. }; -- These modules are auto-loaded, but should you want -- to disable them then uncomment them here: modules_disabled = { -- "offline"; -- Store offline messages -- "c2s"; -- Handle client connections -- "s2s"; -- Handle server-to-server connections }; -- Disable account creation by default, for security -- For more information see http://prosody.im/doc/creating_accounts allow_registration = false; -- These are the SSL/TLS-related settings. If you don't want -- to use SSL/TLS, you may comment or remove this ssl = { key = "certs/localhost.key"; certificate = "certs/localhost.crt"; } -- Force clients to use encrypted connections? This option will -- prevent clients from authenticating unless they are using encryption. c2s_require_encryption = false -- Force certificate authentication for server-to-server connections? -- This provides ideal security, but requires servers you communicate -- with to support encryption AND present valid, trusted certificates. -- NOTE: Your version of LuaSec must support certificate verification! -- For more information see http://prosody.im/doc/s2s#security s2s_secure_auth = false -- Many servers don't support encryption or have invalid or self-signed -- certificates. You can list domains here that will not be required to -- authenticate using certificates. They will be authenticated using DNS. --s2s_insecure_domains = { "gmail.com" } -- Even if you leave s2s_secure_auth disabled, you can still require valid -- certificates for some domains by specifying a list here. --s2s_secure_domains = { "jabber.org" } -- Select the authentication backend to use. The 'internal' providers -- use Prosody's configured data storage to store the authentication data. -- To allow Prosody to offer secure authentication mechanisms to clients, the -- default provider stores passwords in plaintext. If you do not trust your -- server please see http://prosody.im/doc/modules/mod_auth_internal_hashed -- for information about using the hashed backend. authentication = "internal_plain" -- Select the storage backend to use. By default Prosody uses flat files -- in its configured data directory, but it also supports more backends -- through modules. An "sql" backend is included by default, but requires -- additional dependencies. See http://prosody.im/doc/storage for more info. --storage = "sql" -- Default is "internal" -- For the "sql" backend, you can uncomment *one* of the below to configure: --sql = { driver = "SQLite3", database = "prosody.sqlite" } -- Default. 'database' is the filename. --sql = { driver = "MySQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" } --sql = { driver = "PostgreSQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" } -- Logging configuration -- For advanced logging see http://prosody.im/doc/logging log = { -- info = "/var/log/prosody/prosody.log"; -- Change 'info' to 'debug' for verbose logging -- error = "/var/log/prosody/prosody.err"; "*syslog"; -- Uncomment this for logging to syslog -- "*console"; -- Log to the console, useful for debugging with daemonize=false } ----------- Virtual hosts ----------- -- You need to add a VirtualHost entry for each domain you wish Prosody to serve. -- Settings under each VirtualHost entry apply *only* to that host. VirtualHost "localhost" VirtualHost "example.com" enabled = false -- Remove this line to enable this host -- Assign this host a certificate for TLS, otherwise it would use the one -- set in the global section (if any). -- Note that old-style SSL on port 5223 only supports one certificate, and will always -- use the global one. ssl = { key = "certs/example.com.key"; certificate = "certs/example.com.crt"; } ------ Components ------ -- You can specify components to add hosts that provide special services, -- like multi-user conferences, and transports. -- For more information on components, see http://prosody.im/doc/components ---Set up a MUC (multi-user chat) room server on conference.example.com: --Component "conference.example.com" "muc" -- Set up a SOCKS5 bytestream proxy for server-proxied file transfers: --Component "proxy.example.com" "proxy65" ---Set up an external component (default component port is 5347) -- -- External components allow adding various services, such as gateways/ -- transports to other networks like ICQ, MSN and Yahoo. For more info -- see: http://prosody.im/doc/components#adding_an_external_component -- --Component "gateway.example.com" -- component_secret = "password"
bsd-2-clause
Ninjistix/darkstar
scripts/zones/Grand_Palace_of_HuXzoi/mobs/Jailer_of_Temperance.lua
5
4149
---------------------------------- -- Area: Grand Palace of Hu'Xzoi -- NM: Jailer of Temperance ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- function onMobSpawn(mob) -- Set AnimationSub to 0, put it in pot form -- Change it's damage resists. Pot for take -- Give it two hour mob:setMod(MOBMOD_MAIN_2HOUR, 1); -- Change animation to pot mob:AnimationSub(0); -- Set the damage resists mob:setMod(MOD_HTHRES,1000); mob:setMod(MOD_SLASHRES,0); mob:setMod(MOD_PIERCERES,0); mob:setMod(MOD_IMPACTRES,1000); -- Set the magic resists. It always takes no damage from direct magic for n =1,#resistMod,1 do mob:setMod(resistMod[n],0); end for n =1,#defenseMod,1 do mob:setMod(defenseMod[n],1000); end end; function onMobFight(mob) -- Forms: 0 = Pot 1 = Pot 2 = Poles 3 = Rings local randomTime = math.random(30,180); local changeTime = mob:getLocalVar("changeTime"); -- If we're in a pot form, but going to change to either Rings/Poles if ((mob:AnimationSub() == 0 or mob:AnimationSub() == 1) and mob:getBattleTime() - changeTime > randomTime) then local aniChange = math.random(2,3); mob:AnimationSub(aniChange); -- We changed to Poles. Make it only take piercing. if (aniChange == 2) then mob:setMod(MOD_HTHRES,0); mob:setMod(MOD_SLASHRES,0); mob:setMod(MOD_PIERCERES,1000); mob:setMod(MOD_IMPACTRES,0); mob:setLocalVar("changeTime", mob:getBattleTime()); else -- We changed to Rings. Make it only take slashing. mob:setMod(MOD_HTHRES,0); mob:setMod(MOD_SLASHRES,1000); mob:setMod(MOD_PIERCERES,0); mob:setMod(MOD_IMPACTRES,0); mob:setLocalVar("changeTime", mob:getBattleTime()); end -- We're in poles, but changing elseif (mob:AnimationSub() == 2 and mob:getBattleTime() - changeTime > randomTime) then local aniChange = math.random(0, 1); -- Changing to Pot, only take Blunt damage if (aniChange == 0) then mob:AnimationSub(0); mob:setMod(MOD_HTHRES,1000); mob:setMod(MOD_SLASHRES,0); mob:setMod(MOD_PIERCERES,0); mob:setMod(MOD_IMPACTRES,1000); mob:setLocalVar("changeTime", mob:getBattleTime()); else -- Going to Rings, only take slashing mob:AnimationSub(3); mob:setMod(MOD_HTHRES,0); mob:setMod(MOD_SLASHRES,1000); mob:setMod(MOD_PIERCERES,0); mob:setMod(MOD_IMPACTRES,0); mob:setLocalVar("changeTime", mob:getBattleTime()); end -- We're in rings, but going to change to pot or poles elseif (mob:AnimationSub() == 3 and mob:getBattleTime() - changeTime > randomTime) then local aniChange = math.random(0, 2); mob:AnimationSub(aniChange); -- We're changing to pot form, only take blunt damage. if (aniChange == 0 or aniChange == 1) then mob:setMod(MOD_HTHRES,1000); mob:setMod(MOD_SLASHRES,0); mob:setMod(MOD_PIERCERES,0); mob:setMod(MOD_IMPACTRES,1000); mob:setLocalVar("changeTime", mob:getBattleTime()); else -- Changing to poles, only take piercing mob:setMod(MOD_HTHRES,0); mob:setMod(MOD_SLASHRES,0); mob:setMod(MOD_PIERCERES,1000); mob:setMod(MOD_IMPACTRES,0); mob:setLocalVar("changeTime", mob:getBattleTime()); end end end; function onMobDeath(mob, player, isKiller) end; function onMobDespawn(mob) -- Set PH back to normal, then set respawn time local PH = GetServerVariable("[SEA]Jailer_of_Temperance_PH"); DisallowRespawn(mob:getID(), true); DisallowRespawn(PH, false); SetServerVariable("[SEA]Jailer_of_Temperance_POP", os.time() + 900); -- 15 mins GetMobByID(PH):setRespawnTime(GetMobRespawnTime(PH)); SetServerVariable("[SEA]Jailer_of_Temperance_PH", 0); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Jugner_Forest/npcs/Cavernous_Maw.lua
5
1102
----------------------------------- -- Area: Jugner Forest -- NPC: Cavernous Maw -- !pos -118 -8 -518 104 -- Teleports Players to Jugner Forest [S] ----------------------------------- package.loaded["scripts/zones/Jugner_Forest/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/campaign"); require("scripts/zones/Jugner_Forest/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) and hasMawActivated(player,3)) then player:startEvent(905); else player:messageSpecial(NOTHING_HAPPENS); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 905 and option == 1) then toMaw(player,13); end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Northern_San_dOria/npcs/Telmoda.lua
5
1331
----------------------------------- -- Area: Northern San d'Oria -- NPC: Telmoda -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; function onTrigger(player,npc) Telmoda_Madaline = player:getVar("Telmoda_Madaline_Event"); if (Telmoda_Madaline ~= 1) then player:setVar(player,"Telmoda_Madaline_Event",1); player:startEvent(531); else player:startEvent(616); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Gusgen_Mines/npcs/qm2.lua
5
1943
----------------------------------- -- Area: Gusgen Mines -- NPC: qm2 (???) -- Involved In Mission: Bastok 3-2 -- !pos 206 -60 -101 196 ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Gusgen_Mines/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getCurrentMission(BASTOK) == TO_THE_FORSAKEN_MINES and player:hasItem(563) == false) then if (trade:hasItemQty(4358,1) and trade:getItemCount() == 1) then -- Trade Hare Meat player:tradeComplete(); SpawnMob(17580038):updateClaim(player); end end if (player:getQuestStatus(BASTOK, BLADE_OF_DEATH) == QUEST_ACCEPTED and player:getVar("ChaosbringerKills") >= 200) then if (trade:hasItemQty(16607,1) and trade:getItemCount() == 1) then -- Trade Chaosbringer player:tradeComplete(); player:startEvent(10); end end end; function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 10) then if (player:getFreeSlotsCount() > 0) then player:addItem(16637); player:addTitle(BLACK_DEATH); player:setVar("ChaosbringerKills", 0); player:messageSpecial(ITEM_OBTAINED,16637); player:delKeyItem(LETTER_FROM_ZEID); player:completeQuest(BASTOK,BLADE_OF_DEATH); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16637); end end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Melleupaux.lua
5
1036
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Melleupaux -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:showText(npc,MELLEUPAUX_SHOP_DIALOG); local stock = { 0x4042,1867, --Dagger 0x40b6,8478, --Longsword 0x43B7,8, --Rusty Bolt 0x47C7,93240, --Falx (COP Chapter 4 Needed; not implemented yet) 0x4726,51905} --Voulge (COP Chapter 4 Needed; not implemented yet) showShop(player, STATIC, stock); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Southern_San_dOria/npcs/Celyddon.lua
5
1520
----------------------------------- -- Area: Southern San d'Oria -- NPC: Celyddon -- General Info NPC -- @zone 230 -- !pos -129 -6 90 ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; function onTrigger(player,npc) ASquiresTest = player:getQuestStatus(SANDORIA,A_SQUIRE_S_TEST) if ASquiresTest == (QUEST_AVAILABLE) then player:startEvent(618); -- im looking for the examiner elseif ASquiresTest == (QUEST_ACCEPTED) then player:startEvent(619) -- i found the examiner but said i had to use sword else player:startEvent(620) -- says i needs a revival tree root end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
yuryleb/osrm-backend
profiles/car.lua
1
14073
-- Car profile api_version = 4 Set = require('lib/set') Sequence = require('lib/sequence') Handlers = require("lib/way_handlers") Relations = require("lib/relations") find_access_tag = require("lib/access").find_access_tag limit = require("lib/maxspeed").limit Utils = require("lib/utils") Measure = require("lib/measure") function setup() return { properties = { max_speed_for_map_matching = 180/3.6, -- 180kmph -> m/s -- For routing based on duration, but weighted for preferring certain roads weight_name = 'routability', -- For shortest duration without penalties for accessibility -- weight_name = 'duration', -- For shortest distance without penalties for accessibility -- weight_name = 'distance', process_call_tagless_node = false, u_turn_penalty = 20, continue_straight_at_waypoint = true, use_turn_restrictions = true, left_hand_driving = false, traffic_light_penalty = 2, }, default_mode = mode.driving, default_speed = 10, oneway_handling = true, side_road_multiplier = 0.8, turn_penalty = 7.5, speed_reduction = 0.8, turn_bias = 1.075, cardinal_directions = false, -- Size of the vehicle, to be limited by physical restriction of the way vehicle_height = 2.0, -- in meters, 2.0m is the height slightly above biggest SUVs vehicle_width = 1.9, -- in meters, ways with narrow tag are considered narrower than 2.2m -- Size of the vehicle, to be limited mostly by legal restriction of the way vehicle_length = 4.8, -- in meters, 4.8m is the length of large or family car vehicle_weight = 2000, -- in kilograms -- a list of suffixes to suppress in name change instructions. The suffixes also include common substrings of each other suffix_list = { 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'North', 'South', 'West', 'East', 'Nor', 'Sou', 'We', 'Ea' }, barrier_whitelist = Set { 'cattle_grid', 'border_control', 'toll_booth', 'sally_port', 'gate', 'lift_gate', 'no', 'entrance', 'height_restrictor', 'arch' }, access_tag_whitelist = Set { 'yes', 'motorcar', 'motor_vehicle', 'vehicle', 'permissive', 'designated', 'hov' }, access_tag_blacklist = Set { 'no', 'agricultural', 'forestry', 'emergency', 'psv', 'customers', 'private', 'delivery', 'destination' }, -- tags disallow access to in combination with highway=service service_access_tag_blacklist = Set { 'private' }, restricted_access_tag_list = Set { 'private', 'delivery', 'destination', 'customers', }, access_tags_hierarchy = Sequence { 'motorcar', 'motor_vehicle', 'vehicle', 'access' }, service_tag_forbidden = Set { 'emergency_access' }, restrictions = Sequence { 'motorcar', 'motor_vehicle', 'vehicle' }, classes = Sequence { 'toll', 'motorway', 'ferry', 'restricted', 'tunnel' }, -- classes to support for exclude flags excludable = Sequence { Set {'toll'}, Set {'motorway'}, Set {'ferry'} }, avoid = Set { 'area', -- 'toll', -- uncomment this to avoid tolls 'reversible', 'impassable', 'hov_lanes', 'steps', 'construction', 'proposed' }, speeds = Sequence { highway = { motorway = 90, motorway_link = 45, trunk = 85, trunk_link = 40, primary = 65, primary_link = 30, secondary = 55, secondary_link = 25, tertiary = 40, tertiary_link = 20, unclassified = 25, residential = 25, living_street = 10, service = 15 } }, service_penalties = { alley = 0.5, parking = 0.5, parking_aisle = 0.5, driveway = 0.5, ["drive-through"] = 0.5, ["drive-thru"] = 0.5 }, restricted_highway_whitelist = Set { 'motorway', 'motorway_link', 'trunk', 'trunk_link', 'primary', 'primary_link', 'secondary', 'secondary_link', 'tertiary', 'tertiary_link', 'residential', 'living_street', 'unclassified', 'service' }, construction_whitelist = Set { 'no', 'widening', 'minor', }, route_speeds = { ferry = 5, shuttle_train = 10 }, bridge_speeds = { movable = 5 }, -- surface/trackype/smoothness -- values were estimated from looking at the photos at the relevant wiki pages -- max speed for surfaces surface_speeds = { asphalt = nil, -- nil mean no limit. removing the line has the same effect concrete = nil, ["concrete:plates"] = nil, ["concrete:lanes"] = nil, paved = nil, cement = 80, compacted = 80, fine_gravel = 80, paving_stones = 60, metal = 60, bricks = 60, grass = 40, wood = 40, sett = 40, grass_paver = 40, gravel = 40, unpaved = 40, ground = 40, dirt = 40, pebblestone = 40, tartan = 40, cobblestone = 30, clay = 30, earth = 20, stone = 20, rocky = 20, sand = 20, mud = 10 }, -- max speed for tracktypes tracktype_speeds = { grade1 = 60, grade2 = 40, grade3 = 30, grade4 = 25, grade5 = 20 }, -- max speed for smoothnesses smoothness_speeds = { intermediate = 80, bad = 40, very_bad = 20, horrible = 10, very_horrible = 5, impassable = 0 }, -- http://wiki.openstreetmap.org/wiki/Speed_limits maxspeed_table_default = { urban = 50, rural = 90, trunk = 110, motorway = 130 }, -- List only exceptions maxspeed_table = { ["at:rural"] = 100, ["at:trunk"] = 100, ["be:motorway"] = 120, ["be-bru:rural"] = 70, ["be-bru:urban"] = 30, ["be-vlg:rural"] = 70, ["by:urban"] = 60, ["by:motorway"] = 110, ["ch:rural"] = 80, ["ch:trunk"] = 100, ["ch:motorway"] = 120, ["cz:trunk"] = 0, ["cz:motorway"] = 0, ["de:living_street"] = 7, ["de:rural"] = 100, ["de:motorway"] = 0, ["dk:rural"] = 80, ["fr:rural"] = 80, ["gb:nsl_single"] = (60*1609)/1000, ["gb:nsl_dual"] = (70*1609)/1000, ["gb:motorway"] = (70*1609)/1000, ["nl:rural"] = 80, ["nl:trunk"] = 100, ['no:rural'] = 80, ['no:motorway'] = 110, ['pl:rural'] = 100, ['pl:trunk'] = 120, ['pl:motorway'] = 140, ["ro:trunk"] = 100, ["ru:living_street"] = 20, ["ru:urban"] = 60, ["ru:motorway"] = 110, ["uk:nsl_single"] = (60*1609)/1000, ["uk:nsl_dual"] = (70*1609)/1000, ["uk:motorway"] = (70*1609)/1000, ['za:urban'] = 60, ['za:rural'] = 100, ["none"] = 140 }, relation_types = Sequence { "route" }, -- classify highway tags when necessary for turn weights highway_turn_classification = { }, -- classify access tags when necessary for turn weights access_turn_classification = { } } end function process_node(profile, node, result, relations) -- parse access and barrier tags local access = find_access_tag(node, profile.access_tags_hierarchy) if access then if profile.access_tag_blacklist[access] and not profile.restricted_access_tag_list[access] then result.barrier = true end else local barrier = node:get_value_by_key("barrier") if barrier then -- check height restriction barriers local restricted_by_height = false if barrier == 'height_restrictor' then local maxheight = Measure.get_max_height(node:get_value_by_key("maxheight"), node) restricted_by_height = maxheight and maxheight < profile.vehicle_height end -- make an exception for rising bollard barriers local bollard = node:get_value_by_key("bollard") local rising_bollard = bollard and "rising" == bollard -- make an exception for lowered/flat barrier=kerb -- and incorrect tagging of highway crossing kerb as highway barrier local kerb = node:get_value_by_key("kerb") local highway = node:get_value_by_key("highway") local flat_kerb = kerb and ("lowered" == kerb or "flush" == kerb) local highway_crossing_kerb = barrier == "kerb" and highway and highway == "crossing" if not profile.barrier_whitelist[barrier] and not rising_bollard and not flat_kerb and not highway_crossing_kerb or restricted_by_height then result.barrier = true end end end -- check if node is a traffic light local tag = node:get_value_by_key("highway") if "traffic_signals" == tag then result.traffic_lights = true end end function process_way(profile, way, result, relations) -- the intial filtering of ways based on presence of tags -- affects processing times significantly, because all ways -- have to be checked. -- to increase performance, prefetching and intial tag check -- is done in directly instead of via a handler. -- in general we should try to abort as soon as -- possible if the way is not routable, to avoid doing -- unnecessary work. this implies we should check things that -- commonly forbids access early, and handle edge cases later. -- data table for storing intermediate values during processing local data = { -- prefetch tags highway = way:get_value_by_key('highway'), bridge = way:get_value_by_key('bridge'), route = way:get_value_by_key('route') } -- perform an quick initial check and abort if the way is -- obviously not routable. -- highway or route tags must be in data table, bridge is optional if (not data.highway or data.highway == '') and (not data.route or data.route == '') then return end handlers = Sequence { -- set the default mode for this profile. if can be changed later -- in case it turns we're e.g. on a ferry WayHandlers.default_mode, -- check various tags that could indicate that the way is not -- routable. this includes things like status=impassable, -- toll=yes and oneway=reversible WayHandlers.blocked_ways, WayHandlers.avoid_ways, WayHandlers.handle_height, WayHandlers.handle_width, WayHandlers.handle_length, WayHandlers.handle_weight, -- determine access status by checking our hierarchy of -- access tags, e.g: motorcar, motor_vehicle, vehicle WayHandlers.access, -- check whether forward/backward directions are routable WayHandlers.oneway, -- check a road's destination WayHandlers.destinations, -- check whether we're using a special transport mode WayHandlers.ferries, WayHandlers.movables, -- handle service road restrictions WayHandlers.service, -- handle hov WayHandlers.hov, -- compute speed taking into account way type, maxspeed tags, etc. WayHandlers.speed, WayHandlers.maxspeed, WayHandlers.surface, WayHandlers.penalties, -- compute class labels WayHandlers.classes, -- handle turn lanes and road classification, used for guidance WayHandlers.turn_lanes, WayHandlers.classification, -- handle various other flags WayHandlers.roundabouts, WayHandlers.startpoint, WayHandlers.driving_side, -- set name, ref and pronunciation WayHandlers.names, -- set weight properties of the way WayHandlers.weights, -- set classification of ways relevant for turns WayHandlers.way_classification_for_turn } WayHandlers.run(profile, way, result, data, handlers, relations) if profile.cardinal_directions then Relations.process_way_refs(way, relations, result) end end function process_turn(profile, turn) -- Use a sigmoid function to return a penalty that maxes out at turn_penalty -- over the space of 0-180 degrees. Values here were chosen by fitting -- the function to some turn penalty samples from real driving. local turn_penalty = profile.turn_penalty local turn_bias = turn.is_left_hand_driving and 1. / profile.turn_bias or profile.turn_bias if turn.has_traffic_light then turn.duration = profile.properties.traffic_light_penalty end if turn.number_of_roads > 2 or turn.source_mode ~= turn.target_mode or turn.is_u_turn then if turn.angle >= 0 then turn.duration = turn.duration + turn_penalty / (1 + math.exp( -((13 / turn_bias) * turn.angle/180 - 6.5*turn_bias))) else turn.duration = turn.duration + turn_penalty / (1 + math.exp( -((13 * turn_bias) * -turn.angle/180 - 6.5/turn_bias))) end if turn.is_u_turn then turn.duration = turn.duration + profile.properties.u_turn_penalty end end -- for distance based routing we don't want to have penalties based on turn angle if profile.properties.weight_name == 'distance' then turn.weight = 0 else turn.weight = turn.duration end if profile.properties.weight_name == 'routability' then -- penalize turns from non-local access only segments onto local access only tags if not turn.source_restricted and turn.target_restricted then turn.weight = constants.max_turn_weight end end end return { setup = setup, process_way = process_way, process_node = process_node, process_turn = process_turn }
bsd-2-clause
Ninjistix/darkstar
scripts/zones/AlTaieu/npcs/qm2.lua
6
1259
----------------------------------- -- Area: Al'Taieu -- NPC: ??? (Jailer of Justice Spawn) -- Allows players to spawn the Jailer of Justice by trading the Second Virtue, Deed of Moderation, and HQ Xzomit Organ to a ???. -- !pos , -278 0 -463 ----------------------------------- package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil; ----------------------------------- require("scripts/zones/AlTaieu/TextIDs"); require("scripts/zones/AlTaieu/MobIDs"); ----------------------------------- function onTrade(player,npc,trade) --[[ -- JAILER OF JUSTICE if ( not GetMobByID(JAILER_OF_JUSTICE):isSpawned() and trade:hasItemQty(1853,1) and -- second_virtue trade:hasItemQty(1854,1) and -- deed_of_moderation trade:hasItemQty(1855,1) and -- hq_xzomit_organ trade:getItemCount() == 3 ) then player:tradeComplete(); SpawnMob(JAILER_OF_JUSTICE):updateClaim(player); end --]] end; function onTrigger(player,npc) end; function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Windurst_Walls/npcs/Shantotto.lua
5
8070
----------------------------------- -- Area: Windurst Walls -- NPC: Shantotto -- !pos 122 -2 112 239 -- CSID's missing in autoEventID please check the old forums under resources for all of shantotto's csid's. I found them all manually. ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Walls/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); ----------------------------------- function onTrade(player,npc,trade) local count = trade:getItemCount(); -- Curses Foiled Again! if (player:getQuestStatus(WINDURST,CURSES_FOILED_AGAIN_1) == QUEST_ACCEPTED) then if (trade:hasItemQty(928,1) and trade:hasItemQty(880,2) and count == 3) then player:startEvent(173,0,0,0,0,0,0,928,880); -- Correct items given, complete quest. else player:startEvent(172,0,0,0,0,0,0,928,880); -- Incorrect or not enough items end -- Curses,Foiled ... Again!? elseif (player:getQuestStatus(WINDURST,CURSES_FOILED_AGAIN_2) == QUEST_ACCEPTED) then if (trade:hasItemQty(17316,2) and trade:hasItemQty(940,1) and trade:hasItemQty(552,1) and count == 4) then player:startEvent(183); -- Correct items given, complete quest. else player:startEvent(181,0,0,0,0,0,0,17316,940); -- Incorrect or not enough items end end end; function onTrigger(player,npc) local foiledAgain = player:getQuestStatus(WINDURST,CURSES_FOILED_AGAIN_1); local CFA2 = player:getQuestStatus(WINDURST,CURSES_FOILED_AGAIN_2); local CFAtimer = player:getVar("CursesFoiledAgain"); local FoiledAGolem = player:getQuestStatus(WINDURST,CURSES_FOILED_A_GOLEM); local golemdelivery = player:getVar("foiledagolemdeliverycomplete"); local WildcatWindurst = player:getVar("WildcatWindurst"); if (player:getCurrentMission(WINDURST) == THE_JESTER_WHO_D_BE_KING and player:getVar("MissionStatus") == 7) then player:startEvent(397,0,0,0,282); elseif (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,6) == false) then player:startEvent(498); elseif (player:getQuestStatus(WINDURST,CLASS_REUNION) == QUEST_ACCEPTED and player:getVar("ClassReunionProgress") == 3) then player:startEvent(409); -- she mentions that Sunny-Pabonny left for San d'Oria ------------------------------------------------------- -- Curses Foiled Again! elseif (foiledAgain == QUEST_AVAILABLE) then player:startEvent(171,0,0,0,0,0,0,928,880); elseif (foiledAgain == QUEST_ACCEPTED) then player:startEvent(172,0,0,0,0,0,0,928,880); elseif (foiledAgain == QUEST_COMPLETED and CFA2 == QUEST_AVAILABLE and CFAtimer == 0) then local cDay = VanadielDayOfTheYear(); local cYear = VanadielYear(); local dFinished = player:getVar("CursesFoiledAgainDay"); local yFinished = player:getVar("CursesFoiledAgainYear"); -- player:PrintToPlayer("Vana Day and year: "..cDay..", "..cYear); -- player:PrintToPlayer("Database Day and year: "..dFinished..", "..yFinished); if (cDay == dFinished and cYear == yFinished) then player:startEvent(174); elseif (cDay == dFinished + 1 and cYear == yFinished) then player:startEvent(178); elseif ((cDay >= dFinished + 2 and cYear == yFinished) or (cYear > yFinished)) then player:startEvent(179); end -- Curses,Foiled...Again!? elseif (foiledAgain == QUEST_COMPLETED and CFA2 == QUEST_AVAILABLE and player:getFameLevel(WINDURST) >= 2 and player:getMainLvl() >= 5 and CFAtimer == 1) then player:startEvent(180,0,0,0,0,928,880,17316,940); -- Quest Start elseif (CFA2 == QUEST_ACCEPTED) then player:startEvent(181,0,0,0,0,0,0,17316,940); -- Reminder dialog -- Curses,Foiled A-Golem!? elseif (CFA2 == QUEST_COMPLETED and FoiledAGolem == QUEST_AVAILABLE and player:getFameLevel(WINDURST) >= 4 and player:getMainLvl() >= 10) then player:startEvent(340); --quest start elseif (golemdelivery == 1) then player:startEvent(342); -- finish elseif (FoiledAGolem == QUEST_ACCEPTED) then player:startEvent(341); -- reminder dialog -- Standard dialog elseif (FoiledAGolem == QUEST_COMPLETED) then player:startEvent(343); -- new standard dialog after Curses,Foiled A-Golem!? elseif (CFA2 == QUEST_COMPLETED) then player:startEvent(184); -- New standard dialog after CFA2 elseif (player:hasCompletedMission(WINDURST,THE_JESTER_WHO_D_BE_KING) and player:getVar("ShantottoCS") == 1) then player:startEvent(399,0,0,282); else player:startEvent(164); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 173) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17081); else player:tradeComplete(); player:setVar("CursesFoiledAgainDay",VanadielDayOfTheYear()); player:setVar("CursesFoiledAgainYear",VanadielYear()); player:addFame(WINDURST,80); player:addItem(17081); player:messageSpecial(ITEM_OBTAINED,17081); player:completeQuest(WINDURST,CURSES_FOILED_AGAIN_1); end elseif (csid == 171 and option ~= 1) then player:addQuest(WINDURST,CURSES_FOILED_AGAIN_1); elseif (csid == 179) then player:setVar("CursesFoiledAgainDayFinished",0); player:setVar("CursesFoiledAgainYearFinished",0); player:setVar("CursesFoiledAgainDay",0); player:setVar("CursesFoiledAgainYear",0); player:setVar("CursesFoiledAgain",1); -- Used to acknowledge that the two days have passed, Use this to initiate next quest player:needToZone(true); elseif (csid == 180 and option == 3) then player:setVar("CursesFoiledAgain",0); player:addQuest(WINDURST,CURSES_FOILED_AGAIN_2); player:setTitle(TARUTARU_MURDER_SUSPECT); elseif (csid == 183) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17116); else player:tradeComplete(); player:setTitle(HEXER_VEXER); player:addItem(17116); player:messageSpecial(ITEM_OBTAINED,17116); player:completeQuest(WINDURST,CURSES_FOILED_AGAIN_2); player:needToZone(true); player:addFame(WINDURST,90); end elseif (csid == 340) then if (option == 1) then player:addQuest(WINDURST,CURSES_FOILED_A_GOLEM); else player:setTitle(TOTAL_LOSER); end elseif (csid == 342) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4870); else player:completeQuest(WINDURST,CURSES_FOILED_A_GOLEM); player:setVar("foiledagolemdeliverycomplete",0); player:addItem(4870); player:messageSpecial(ITEM_OBTAINED,4870); player:setTitle(DOCTOR_SHANTOTTOS_FLAVOR_OF_THE_MONTH); player:addFame(WINDURST,120); end elseif (csid == 409) then player:setVar("ClassReunionProgress",4); elseif (csid == 498) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",6,true); elseif (csid == 397) then player:addKeyItem(GLOVE_OF_PERPETUAL_TWILIGHT) player:messageSpecial(KEYITEM_OBTAINED,GLOVE_OF_PERPETUAL_TWILIGHT); player:setVar("MissionStatus",8) elseif (csid == 399) then player:setVar("ShantottoCS",0) end end;
gpl-3.0
karrots/nodemcu-firmware
lua_examples/ucglib/GT_pixel_and_lines.lua
30
1076
local M, module = {}, ... _G[module] = M function M.run() -- make this a volatile module: package.loaded[module] = nil print("Running component pixel_and_lines...") local mx local x, xx mx = disp:getWidth() / 2 --my = disp:getHeight() / 2 disp:setColor(0, 0, 0, 150) disp:setColor(1, 0, 60, 40) disp:setColor(2, 60, 0, 40) disp:setColor(3, 120, 120, 200) disp:drawGradientBox(0, 0, disp:getWidth(), disp:getHeight()) disp:setColor(255, 255, 255) disp:setPrintPos(2, 18) disp:setPrintDir(0) disp:print("Pix&Line") disp:drawPixel(0, 0) disp:drawPixel(1, 0) --disp:drawPixel(disp:getWidth()-1, 0) --disp:drawPixel(0, disp:getHeight()-1) disp:drawPixel(disp:getWidth()-1, disp:getHeight()-1) disp:drawPixel(disp:getWidth()-1-1, disp:getHeight()-1) x = 0 while x < mx do xx = ((x)*255)/mx disp:setColor(255, 255-xx/2, 255-xx) disp:drawPixel(x, 24) disp:drawVLine(x+7, 26, 13) x = x + 1 end print("...done") end return M
mit
dinodeck/ninety_nine_days_of_dev
004_stat_numbers/code/Blob.lua
10
6575
-- -- The important functions here are -- Blob:Encode([some table]) Returns a string blob of the serialized data. -- Blob:Decode([some encoded string]) Returns a lua table from a string blob. -- Blob = {} function Blob:Error(value) print('Cannot encode value') assert(false, 'Cannot encode value') end function Blob:PrintType(value, stack, output, dataType) local ReduceTypeMap = { ["number"] = "n", -- user type data may go here. (vectors) } local _type = ReduceTypeMap[type(value)] assert(_type, "Printing type problem.") table.insert(output, string.format("%s%s", _type, value)) end Blob.number = Blob.PrintType Blob['function'] = Blob.Error Blob.thread = Blob.Error function Blob:EscapeString(str) -- Escape escape character local _escapedStr = str:gsub("@", "@@") -- Find any non-ascii strings -- %w alphanumeric, %p punctuation ^ inverse and the space character local function expandForbiddenChars(str) local chars = {} for i = 1, #str do table.insert(chars, string.format("@%03d", str:byte(i))) end return table.concat(chars) end return _escapedStr:gsub("([^%w%p ]+)", expandForbiddenChars) end function Blob:string(str, stack, output, dataType) local _escapedStr = self:EscapeString(str) table.insert(output, string.format('s%d %s', _escapedStr:len(), _escapedStr)) end function Blob:boolean(value, stack, output, dataType) if value == true then table.insert(output, 't') else table.insert(output, 'f') end end function Blob:userdata(value, stack, output, dataType) -- An extra look up will be needed here using Type instead of type self:_printType(value, stack, output, dataType) end function Blob:OpenTable(t, stack, output, dataType) table.insert(output, string.format("[")) end function Blob:CloseTable(t, stack, output, dataType) table.insert(output, string.format("]")) end function Blob:KeyPairAssign(output) table.insert(output, ";") end function Blob:HitLoop(t, stack, output, dataType) print('Cannot print tables with loops.') assert(false, 'Cannot print tables with loops.') end function Blob:Encode(t) local tType = type(t) if tType ~= 'table' then out = {} self[tType](self, t, nil, out, tType) return out[1] end return IterTable(t, nil, nil, nil, self) end function Blob:DecodeTable(s, pos) local _tableValue = {} pos = pos + 1 -- skip the opening '[' local nextChar = s:sub(pos, pos) -- get whatever is next while nextChar ~= "]" do local key = nil local value, finish = self:Decode(s, pos) pos = finish nextChar = s:sub(pos, pos) if nextChar == ';' then key = value value, finish = self:Decode(s, pos + 1) pos = finish nextChar = s:sub(pos, pos) end if key ~= nil then _tableValue[key] = value elseif value ~= nil then table.insert(_tableValue, value) end end return _tableValue, pos + 1 end function Blob:DecodeNumber(s, pos) -- pos + 1 to skip 'n' local start, finish = s:find("-?%d+%.?%d*", pos) if start == nil then pos = s:len() print("Error failed to parse number") return end local number = tonumber(string.sub(s, start, finish)) return number, finish + 1 end function Blob:DecodeBoolean(s, pos) --pos = pos + 1 -- 1 - 'b', local _value = s:sub(pos, pos) == 't' return _value, pos + 1 end function Blob:ExpandString(str) local expandedStr = str:gsub("@@", "@") local function unescapeStr(str) return string.char(tonumber(str)) end return expandedStr:gsub("@(%d%d%d)", unescapeStr) end function Blob:DecodeString(s, pos) -- pos + 1 skips 's' local start, pos = s:find("%d+", pos + 1) if start == nil then pos = s:len() print('Error parsing string - couldnt find number') return end local _strLen = tonumber(string.sub(s, start, pos)) pos = pos + 1 local finish = pos + _strLen local _str = string.sub(s, pos + 1, finish) return self:ExpandString(_str), finish + 1 end Blob.DecodeMap = { ['['] = Blob.DecodeTable, ['n'] = Blob.DecodeNumber, ['t'] = Blob.DecodeBoolean, ['f'] = Blob.DecodeBoolean, ['s'] = Blob.DecodeString, } function Blob:Decode(s, pos) pos = pos or 1 local char = s:sub(pos, pos) assert(Blob.DecodeMap[char], "Decode failure") return Blob.DecodeMap[char](self, s, pos) end -- -- Testing (if you make changes go through these one by one to make sure they still hold.) -- -- TblToString = function(t) return IterTable(t) end -- print( "{} ->", TblToString(Blob:Decode(Blob:Encode({})))) -- print(Blob:Encode({})) -- print( "{{}} ->", TblToString(Blob:Decode(Blob:Encode( {{}}))) ) -- print( "{{}, {}, {}} ->", TblToString(Blob:Decode(Blob:Encode( {{}, {}, {}}))) ) -- print( "{{{}}, {{}, {}}, {{}, {}, {}}} ->", TblToString(Blob:Decode(Blob:Encode( {{{}}, {{},{}}, {{},{},{}}}))) ) -- print(Blob:Encode( {[{}] = {}})) -- print( "{[{}] = {}} ->", TblToString(Blob:Decode(Blob:Encode( {[{}] = {}}))) ) -- print( "{[{{}, {{}}}] = {}} ->", TblToString(Blob:Decode(Blob:Encode( {[{{}, {{}}}] = {}}))) ) -- print( "{true, true, false} ->", TblToString(Blob:Decode(Blob:Encode({true, true, false})))) -- print( "{[true] = true, true, false} ->", TblToString(Blob:Decode(Blob:Encode({[true] = true, true, false})))) -- print( "{[true] = {true, true, [{}] = true} ->", TblToString(Blob:Decode(Blob:Encode({[true] = {true, true, [{}] = true}})))) -- print( "{1, 2, 3} ->", TblToString(Blob:Decode(Blob:Encode({1, 2, 3})))) -- print( "{-1} ->", TblToString(Blob:Decode(Blob:Encode({-1})))) -- print(Blob:Encode( {1.1} )) -- print( "{1.1} ->", TblToString(Blob:Decode(Blob:Encode({1.1})))) -- print( "{1.0001, 0.333, -0.66745001} ->", TblToString(Blob:Decode(Blob:Encode({1.0001, 0.333, -0.66745001})))) -- print( "{'test'} ->", TblToString(Blob:Decode(Blob:Encode({'test'})))) -- print("{['test'] = 9, [8] = 'test2'}", TblToString(Blob:Decode(Blob:Encode({{['test'] = 9, [8] = 'test2'}})))) -- print(Blob:Encode( {[10] = 9, [-2] = 1} )) -- print("{[10] = 9, [-2] = 1}", TblToString(Blob:Decode(Blob:Encode({[10] = 9, [-2] = 1})))) -- -- This is to check it can handle encoding non-ascii characters -- print(Blob:Encode{["somet@\0hing"] = 5}) -- print("中") -- for i = 1, #"中" do -- print(string.byte("中", i)) -- end -- print("\228\184\173") -- print(Blob:Encode({"中"})) -- print(TblToString(Blob:Decode(Blob:Encode({"中"})))) -- print(TblToString(Blob:Decode(Blob:Encode{["some@\0thing"] = 5})))
mit
dinodeck/ninety_nine_days_of_dev
006_magic_menu/code/Blob.lua
10
6575
-- -- The important functions here are -- Blob:Encode([some table]) Returns a string blob of the serialized data. -- Blob:Decode([some encoded string]) Returns a lua table from a string blob. -- Blob = {} function Blob:Error(value) print('Cannot encode value') assert(false, 'Cannot encode value') end function Blob:PrintType(value, stack, output, dataType) local ReduceTypeMap = { ["number"] = "n", -- user type data may go here. (vectors) } local _type = ReduceTypeMap[type(value)] assert(_type, "Printing type problem.") table.insert(output, string.format("%s%s", _type, value)) end Blob.number = Blob.PrintType Blob['function'] = Blob.Error Blob.thread = Blob.Error function Blob:EscapeString(str) -- Escape escape character local _escapedStr = str:gsub("@", "@@") -- Find any non-ascii strings -- %w alphanumeric, %p punctuation ^ inverse and the space character local function expandForbiddenChars(str) local chars = {} for i = 1, #str do table.insert(chars, string.format("@%03d", str:byte(i))) end return table.concat(chars) end return _escapedStr:gsub("([^%w%p ]+)", expandForbiddenChars) end function Blob:string(str, stack, output, dataType) local _escapedStr = self:EscapeString(str) table.insert(output, string.format('s%d %s', _escapedStr:len(), _escapedStr)) end function Blob:boolean(value, stack, output, dataType) if value == true then table.insert(output, 't') else table.insert(output, 'f') end end function Blob:userdata(value, stack, output, dataType) -- An extra look up will be needed here using Type instead of type self:_printType(value, stack, output, dataType) end function Blob:OpenTable(t, stack, output, dataType) table.insert(output, string.format("[")) end function Blob:CloseTable(t, stack, output, dataType) table.insert(output, string.format("]")) end function Blob:KeyPairAssign(output) table.insert(output, ";") end function Blob:HitLoop(t, stack, output, dataType) print('Cannot print tables with loops.') assert(false, 'Cannot print tables with loops.') end function Blob:Encode(t) local tType = type(t) if tType ~= 'table' then out = {} self[tType](self, t, nil, out, tType) return out[1] end return IterTable(t, nil, nil, nil, self) end function Blob:DecodeTable(s, pos) local _tableValue = {} pos = pos + 1 -- skip the opening '[' local nextChar = s:sub(pos, pos) -- get whatever is next while nextChar ~= "]" do local key = nil local value, finish = self:Decode(s, pos) pos = finish nextChar = s:sub(pos, pos) if nextChar == ';' then key = value value, finish = self:Decode(s, pos + 1) pos = finish nextChar = s:sub(pos, pos) end if key ~= nil then _tableValue[key] = value elseif value ~= nil then table.insert(_tableValue, value) end end return _tableValue, pos + 1 end function Blob:DecodeNumber(s, pos) -- pos + 1 to skip 'n' local start, finish = s:find("-?%d+%.?%d*", pos) if start == nil then pos = s:len() print("Error failed to parse number") return end local number = tonumber(string.sub(s, start, finish)) return number, finish + 1 end function Blob:DecodeBoolean(s, pos) --pos = pos + 1 -- 1 - 'b', local _value = s:sub(pos, pos) == 't' return _value, pos + 1 end function Blob:ExpandString(str) local expandedStr = str:gsub("@@", "@") local function unescapeStr(str) return string.char(tonumber(str)) end return expandedStr:gsub("@(%d%d%d)", unescapeStr) end function Blob:DecodeString(s, pos) -- pos + 1 skips 's' local start, pos = s:find("%d+", pos + 1) if start == nil then pos = s:len() print('Error parsing string - couldnt find number') return end local _strLen = tonumber(string.sub(s, start, pos)) pos = pos + 1 local finish = pos + _strLen local _str = string.sub(s, pos + 1, finish) return self:ExpandString(_str), finish + 1 end Blob.DecodeMap = { ['['] = Blob.DecodeTable, ['n'] = Blob.DecodeNumber, ['t'] = Blob.DecodeBoolean, ['f'] = Blob.DecodeBoolean, ['s'] = Blob.DecodeString, } function Blob:Decode(s, pos) pos = pos or 1 local char = s:sub(pos, pos) assert(Blob.DecodeMap[char], "Decode failure") return Blob.DecodeMap[char](self, s, pos) end -- -- Testing (if you make changes go through these one by one to make sure they still hold.) -- -- TblToString = function(t) return IterTable(t) end -- print( "{} ->", TblToString(Blob:Decode(Blob:Encode({})))) -- print(Blob:Encode({})) -- print( "{{}} ->", TblToString(Blob:Decode(Blob:Encode( {{}}))) ) -- print( "{{}, {}, {}} ->", TblToString(Blob:Decode(Blob:Encode( {{}, {}, {}}))) ) -- print( "{{{}}, {{}, {}}, {{}, {}, {}}} ->", TblToString(Blob:Decode(Blob:Encode( {{{}}, {{},{}}, {{},{},{}}}))) ) -- print(Blob:Encode( {[{}] = {}})) -- print( "{[{}] = {}} ->", TblToString(Blob:Decode(Blob:Encode( {[{}] = {}}))) ) -- print( "{[{{}, {{}}}] = {}} ->", TblToString(Blob:Decode(Blob:Encode( {[{{}, {{}}}] = {}}))) ) -- print( "{true, true, false} ->", TblToString(Blob:Decode(Blob:Encode({true, true, false})))) -- print( "{[true] = true, true, false} ->", TblToString(Blob:Decode(Blob:Encode({[true] = true, true, false})))) -- print( "{[true] = {true, true, [{}] = true} ->", TblToString(Blob:Decode(Blob:Encode({[true] = {true, true, [{}] = true}})))) -- print( "{1, 2, 3} ->", TblToString(Blob:Decode(Blob:Encode({1, 2, 3})))) -- print( "{-1} ->", TblToString(Blob:Decode(Blob:Encode({-1})))) -- print(Blob:Encode( {1.1} )) -- print( "{1.1} ->", TblToString(Blob:Decode(Blob:Encode({1.1})))) -- print( "{1.0001, 0.333, -0.66745001} ->", TblToString(Blob:Decode(Blob:Encode({1.0001, 0.333, -0.66745001})))) -- print( "{'test'} ->", TblToString(Blob:Decode(Blob:Encode({'test'})))) -- print("{['test'] = 9, [8] = 'test2'}", TblToString(Blob:Decode(Blob:Encode({{['test'] = 9, [8] = 'test2'}})))) -- print(Blob:Encode( {[10] = 9, [-2] = 1} )) -- print("{[10] = 9, [-2] = 1}", TblToString(Blob:Decode(Blob:Encode({[10] = 9, [-2] = 1})))) -- -- This is to check it can handle encoding non-ascii characters -- print(Blob:Encode{["somet@\0hing"] = 5}) -- print("中") -- for i = 1, #"中" do -- print(string.byte("中", i)) -- end -- print("\228\184\173") -- print(Blob:Encode({"中"})) -- print(TblToString(Blob:Decode(Blob:Encode({"中"})))) -- print(TblToString(Blob:Decode(Blob:Encode{["some@\0thing"] = 5})))
mit
Ninjistix/darkstar
scripts/zones/Bastok_Mines/npcs/Quelle.lua
3
1632
----------------------------------- -- Area: Bastok Mines -- NPC: Quelle -- Type: Chocobo Renter ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/chocobo"); require("scripts/globals/status"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local level = player:getMainLvl(); local gil = player:getGil(); if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 15) then local price = getChocoboPrice(player); player:setLocalVar("chocoboPriceOffer",price); if (level >= 20) then level = 0; end player:startEvent(63,price,gil,level); else player:startEvent(66); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local price = player:getLocalVar("chocoboPriceOffer"); if (csid == 63 and option == 0) then if (player:delGil(price)) then updateChocoboPrice(player, price); if (player:getMainLvl() >= 20) then local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60) player:addStatusEffectEx(EFFECT_MOUNTED,EFFECT_MOUNTED,0,0,duration,true); else player:addStatusEffectEx(EFFECT_MOUNTED,EFFECT_MOUNTED,0,0,900,true); end player:setPos(580,0,-305,0x40,0x6B); end end end;
gpl-3.0
otservme/global1051
data/talkactions/scripts/create_item.lua
10
1097
function onSay(cid, words, param) local player = Player(cid) if not player:getGroup():getAccess() then return true end if player:getAccountType() < ACCOUNT_TYPE_GOD then return false end local split = param:split(",") local itemType = ItemType(split[1]) if itemType:getId() == 0 then itemType = ItemType(tonumber(split[1])) if itemType:getId() == 0 then player:sendCancelMessage("There is no item with that id or name.") return false end end local count = tonumber(split[2]) if count ~= nil then if itemType:isStackable() then count = math.min(10000, math.max(1, count)) elseif not itemType:hasSubType() then count = math.min(100, math.max(1, count)) else count = math.max(1, count) end else count = 1 end local result = player:addItem(itemType:getId(), count) if result ~= nil then if not itemType:isStackable() then if type(result) == "table" then for _, item in ipairs(result) do item:decay() end else result:decay() end end player:getPosition():sendMagicEffect(CONST_ME_MAGIC_GREEN) end return false end
gpl-2.0
Xamla/torch-ros
lua/std/StringVector.lua
1
2677
local ffi = require 'ffi' local torch = require 'torch' local ros = require 'ros.env' local utils = require 'ros.utils' local std = ros.std local StringVector = torch.class('std.StringVector', std) function init() local StringVector_method_names = { "new", "clone", "delete", "size", "getAt", "setAt", "push_back", "pop_back", "clear", "insert", "erase", "empty" } return utils.create_method_table("std_StringVector_", StringVector_method_names) end local f = init() function StringVector:__init(...) rawset(self, 'o', f.new()) if select("#", ...) > 0 then local x = ... if type(x) ~= 'table' then x = { ... } end self:insertFromTable(1, x) end end function StringVector:cdata() return self.o end function StringVector:clone() local c = torch.factory('std.StringVector')() rawset(c, 'o', f.clone(self.o)) return c end function StringVector:size() return f.size(self.o) end function StringVector:__len() return self:size() end function StringVector:__index(idx) local v = rawget(self, idx) if not v then v = StringVector[idx] if not v and type(idx) == 'number' then local o = rawget(self, 'o') v = ffi.string(f.getAt(o, idx-1)) end end return v end function StringVector:__newindex(idx, v) local o = rawget(self, 'o') if type(idx) == 'number' then f.setAt(o, idx-1, tostring(v)) else rawset(self, idx, v) end end function StringVector:push_back(value) f.push_back(self.o, tostring(value)) end function StringVector:pop_back() local last = self[#self] f.pop_back(self.o) return last end function StringVector:clear() f.clear(self.o) end function StringVector:insert(pos, value, n) if pos < 1 then pos = 1 elseif pos > #self+1 then pos = #self + 1 end f.insert(self.o, pos-1, n or 1, value) end function StringVector:insertFromTable(pos, t) if type(pos) == 'table' then t = pos pos = #self + 1 end pos = pos or #self + 1 for _,v in pairs(t) do self:insert(pos, v) pos = pos + 1 end end function StringVector:erase(begin_pos, end_pos) f.erase(self.o, begin_pos-1, (end_pos or begin_pos + 1)-1) end function StringVector:__pairs() return function (t, k) local i = k + 1 if i > #t then return nil else local v = t[i] return i, v end end, self, 0 end function StringVector:__ipairs() return self:__pairs() end function StringVector:totable() local t = {} for i,v in ipairs(self) do table.insert(t, v) end return t end function StringVector:__tostring() local t = self:totable() return table.concat(t, '\n') end
bsd-3-clause
amirb8/telepersian
plugins/supergroup.lua
33
75432
--Begin supergrpup.lua --Check members #Add supergroup local function check_member_super(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg if success == 0 then send_large_msg(receiver, "Promote me to admin first!") end for k,v in pairs(result) do local member_id = v.peer_id if member_id ~= our_id then -- SuperGroup configuration data[tostring(msg.to.id)] = { group_type = 'SuperGroup', long_id = msg.to.peer_id, moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.title, '_', ' '), lock_arabic = 'no', lock_link = "no", flood = 'yes', lock_spam = 'yes', lock_sticker = 'no', member = 'no', public = 'no', lock_rtl = 'no', lock_tgservice = 'yes', lock_contacts = 'no', strict = 'no' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) local text = 'SuperGroup has been added!' return reply_msg(msg.id, text, ok_cb, false) end end end --Check Members #rem supergroup local function check_member_superrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local text = 'SuperGroup has been removed' return reply_msg(msg.id, text, ok_cb, false) end end end --Function to Add supergroup local function superadd(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg}) end --Function to remove supergroup local function superrem(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg}) end --Get and output admins and bots in supergroup local function callback(cb_extra, success, result) local i = 1 local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ") local member_type = cb_extra.member_type local text = member_type.." for "..chat_name..":\n" for k,v in pairsByKeys(result) do if not v.first_name then name = " " else vname = v.first_name:gsub("‮", "") name = vname:gsub("_", " ") end text = text.."\n"..i.." - "..name.."["..v.peer_id.."]" i = i + 1 end send_large_msg(cb_extra.receiver, text) end local function callback_clean_bots (extra, success, result) local msg = extra.msg local receiver = 'channel#id'..msg.to.id local channel_id = msg.to.id for k,v in pairs(result) do local bot_id = v.peer_id kick_user(bot_id,channel_id) end end --Get and output info about supergroup local function callback_info(cb_extra, success, result) local title ="Info for SuperGroup: ["..result.title.."]\n\n" local admin_num = "Admin count: "..result.admins_count.."\n" local user_num = "User count: "..result.participants_count.."\n" local kicked_num = "Kicked user count: "..result.kicked_count.."\n" local channel_id = "ID: "..result.peer_id.."\n" if result.username then channel_username = "Username: @"..result.username else channel_username = "" end local text = title..admin_num..user_num..kicked_num..channel_id..channel_username send_large_msg(cb_extra.receiver, text) end --Get and output members of supergroup local function callback_who(cb_extra, success, result) local text = "Members for "..cb_extra.receiver local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then username = " @"..v.username else username = "" end text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n" --text = text.."\n"..username i = i + 1 end local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false) post_msg(cb_extra.receiver, text, ok_cb, false) end --Get and output list of kicked users for supergroup local function callback_kicked(cb_extra, success, result) --vardump(result) local text = "Kicked Members for SuperGroup "..cb_extra.receiver.."\n\n" local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then name = name.." @"..v.username end text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n" i = i + 1 end local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false) --send_large_msg(cb_extra.receiver, text) end --Begin supergroup locks local function lock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'Link posting is already locked' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'Link posting has been locked' end end local function unlock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'Link posting is not locked' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'Link posting has been unlocked' end end local function lock_group_spam(msg, data, target) if not is_momod(msg) then return end if not is_owner(msg) then return "Owners only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return 'SuperGroup spam is already locked' else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return 'SuperGroup spam has been locked' end end local function unlock_group_spam(msg, data, target) if not is_momod(msg) then return end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return 'SuperGroup spam is not locked' else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup spam has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Flood is already locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Flood has been unlocked' end end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic/Persian is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic/Persian has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'SuperGroup members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'SuperGroup members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'SuperGroup members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup members has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL has been unlocked' end end local function lock_group_tgservice(msg, data, target) if not is_momod(msg) then return end local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice'] if group_tgservice_lock == 'yes' then return 'Tgservice is already locked' else data[tostring(target)]['settings']['lock_tgservice'] = 'yes' save_data(_config.moderation.data, data) return 'Tgservice has been locked' end end local function unlock_group_tgservice(msg, data, target) if not is_momod(msg) then return end local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice'] if group_tgservice_lock == 'no' then return 'TgService Is Not Locked!' else data[tostring(target)]['settings']['lock_tgservice'] = 'no' save_data(_config.moderation.data, data) return 'Tgservice has been unlocked' end end local function lock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return 'Sticker posting is already locked' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'Sticker posting has been locked' end end local function unlock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return 'Sticker posting is already unlocked' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'Sticker posting has been unlocked' end end local function lock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'yes' then return 'Contact posting is already locked' else data[tostring(target)]['settings']['lock_contacts'] = 'yes' save_data(_config.moderation.data, data) return 'Contact posting has been locked' end end local function unlock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'no' then return 'Contact posting is already unlocked' else data[tostring(target)]['settings']['lock_contacts'] = 'no' save_data(_config.moderation.data, data) return 'Contact posting has been unlocked' end end local function enable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'yes' then return 'Settings are already strictly enforced' else data[tostring(target)]['settings']['strict'] = 'yes' save_data(_config.moderation.data, data) return 'Settings will be strictly enforced' end end local function disable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'no' then return 'Settings are not strictly enforced' else data[tostring(target)]['settings']['strict'] = 'no' save_data(_config.moderation.data, data) return 'Settings will not be strictly enforced' end end --End supergroup locks --'Set supergroup rules' function local function set_rulesmod(msg, data, target) if not is_momod(msg) then return end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'SuperGroup rules set' end --'Get supergroup rules' function local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local group_name = data[tostring(msg.to.id)]['settings']['set_name'] local rules = group_name..' rules:\n\n'..rules:gsub("/n", " ") return rules end --Set supergroup to public or not public function local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'SuperGroup is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' data[tostring(target)]['long_id'] = msg.to.long_id save_data(_config.moderation.data, data) return 'SuperGroup is now: not public' end end --Show supergroup settings; function function show_supergroup_settingsmod(msg, target) if not is_momod(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_tgservice'] then data[tostring(target)]['settings']['lock_tgservice'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "SuperGroup settings:\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nFlood sensitivity : "..NUM_MSG_MAX.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock Tgservice : "..settings.lock_tgservice.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict return text end local function promote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) end local function demote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' is not a moderator.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) end local function promote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return send_large_msg(receiver, 'SuperGroup is not added.') end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been promoted.') end local function demote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' is not a moderator.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been demoted.') end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'SuperGroup is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end -- Start by reply actions function get_message_callback(extra, success, result) local get_cmd = extra.get_cmd local msg = extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") if get_cmd == "id" and not result.action then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]") id1 = send_large_msg(channel, result.from.peer_id) elseif get_cmd == 'id' and result.action then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id else user_id = result.peer_id end local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]") id1 = send_large_msg(channel, user_id) end elseif get_cmd == "idfrom" then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]") id2 = send_large_msg(channel, result.fwd_from.peer_id) elseif get_cmd == 'channel_block' and not result.action then local member_id = result.from.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end --savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply") kick_user(member_id, channel_id) elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then local user_id = result.action.user.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.") kick_user(user_id, channel_id) elseif get_cmd == "del" then delete_msg(result.id, ok_cb, false) savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply") elseif get_cmd == "setadmin" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." set as an admin" else text = "[ "..user_id.." ]set as an admin" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "demoteadmin" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id if is_admin2(result.from.peer_id) then return send_large_msg(channel_id, "You can't demote global admins!") end channel_demote(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." has been demoted from admin" else text = "[ "..user_id.." ] has been demoted from admin" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "setowner" then local group_owner = data[tostring(result.to.peer_id)]['set_owner'] if group_owner then local channel_id = 'channel#id'..result.to.peer_id if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(channel_id, user, ok_cb, false) end local user_id = "user#id"..result.from.peer_id channel_set_admin(channel_id, user_id, ok_cb, false) data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply") if result.from.username then text = "@"..result.from.username.." [ "..result.from.peer_id.." ] added as owner" else text = "[ "..result.from.peer_id.." ] added as owner" end send_large_msg(channel_id, text) end elseif get_cmd == "promote" then local receiver = result.to.peer_id local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id if result.to.peer_type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply") promote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_set_mod(channel_id, user, ok_cb, false) end elseif get_cmd == "demote" then local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id --local user = "user#id"..result.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted mod: @"..member_username.."["..user_id.."] by reply") demote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_demote(channel_id, user, ok_cb, false) elseif get_cmd == 'mute_user' then if result.service then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id end end if action == 'chat_add_user_link' then if result.from then user_id = result.from.peer_id end end else user_id = result.from.peer_id end local receiver = extra.receiver local chat_id = msg.to.id print(user_id) print(chat_id) if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, "["..user_id.."] removed from the muted user list") elseif is_admin1(msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to the muted user list") end end end -- End by reply actions --By ID actions local function cb_user_info(extra, success, result) local receiver = extra.receiver local user_id = result.peer_id local get_cmd = extra.get_cmd local data = load_data(_config.moderation.data) --[[if get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" else text = "[ "..result.peer_id.." ] has been set as an admin" end send_large_msg(receiver, text)]] if get_cmd == "demoteadmin" then if is_admin2(result.peer_id) then return send_large_msg(receiver, "You can't demote global admins!") end local user_id = "user#id"..result.peer_id channel_demote(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(receiver, text) else text = "[ "..result.peer_id.." ] has been demoted from admin" send_large_msg(receiver, text) end elseif get_cmd == "promote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end promote2(receiver, member_username, user_id) elseif get_cmd == "demote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end demote2(receiver, member_username, user_id) end end -- Begin resolve username actions local function callbackres(extra, success, result) local member_id = result.peer_id local member_username = "@"..result.username local get_cmd = extra.get_cmd if get_cmd == "res" then local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local channel = 'channel#id'..extra.channelid send_large_msg(channel, user..'\n'..name) return user elseif get_cmd == "id" then local user = result.peer_id local channel = 'channel#id'..extra.channelid send_large_msg(channel, user) return user elseif get_cmd == "invite" then local receiver = extra.channel local user_id = "user#id"..result.peer_id channel_invite(receiver, user_id, ok_cb, false) --[[elseif get_cmd == "channel_block" then local user_id = result.peer_id local channel_id = extra.channelid local sender = extra.sender if member_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end kick_user(user_id, channel_id) elseif get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel channel_set_admin(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been set as an admin" send_large_msg(channel_id, text) end elseif get_cmd == "setowner" then local receiver = extra.channel local channel = string.gsub(receiver, 'channel#id', '') local from_id = extra.from_id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then local user = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(result.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username") if result.username then text = member_username.." [ "..result.peer_id.." ] added as owner" else text = "[ "..result.peer_id.." ] added as owner" end send_large_msg(receiver, text) end]] elseif get_cmd == "promote" then local receiver = extra.channel local user_id = result.peer_id --local user = "user#id"..result.peer_id promote2(receiver, member_username, user_id) --channel_set_mod(receiver, user, ok_cb, false) elseif get_cmd == "demote" then local receiver = extra.channel local user_id = result.peer_id local user = "user#id"..result.peer_id demote2(receiver, member_username, user_id) elseif get_cmd == "demoteadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel if is_admin2(result.peer_id) then return send_large_msg(channel_id, "You can't demote global admins!") end channel_demote(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been demoted from admin" send_large_msg(channel_id, text) end local receiver = extra.channel local user_id = result.peer_id demote_admin(receiver, member_username, user_id) elseif get_cmd == 'mute_user' then local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] removed from muted user list") elseif is_owner(extra.msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to muted user list") end end end --End resolve username actions --Begin non-channel_invite username actions local function in_channel_cb(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local msg = cb_extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(cb_extra.msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local member = cb_extra.username local memberid = cb_extra.user_id if member then text = 'No user @'..member..' in this SuperGroup.' else text = 'No user ['..memberid..'] in this SuperGroup.' end if get_cmd == "channel_block" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = v.peer_id local channel_id = cb_extra.msg.to.id local sender = cb_extra.msg.from.id if user_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(user_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(user_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end if v.username then text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]") else text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]") end kick_user(user_id, channel_id) return end end elseif get_cmd == "setadmin" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = "user#id"..v.peer_id local channel_id = "channel#id"..cb_extra.msg.to.id channel_set_admin(channel_id, user_id, ok_cb, false) if v.username then text = "@"..v.username.." ["..v.peer_id.."] has been set as an admin" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]") else text = "["..v.peer_id.."] has been set as an admin" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id) end if v.username then member_username = "@"..v.username else member_username = string.gsub(v.print_name, '_', ' ') end local receiver = channel_id local user_id = v.peer_id promote_admin(receiver, member_username, user_id) end send_large_msg(channel_id, text) return end elseif get_cmd == 'setowner' then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..v.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(v.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username") if result.username then text = member_username.." ["..v.peer_id.."] added as owner" else text = "["..v.peer_id.."] added as owner" end end elseif memberid and vusername ~= member and vpeer_id ~= memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end data[tostring(channel)]['set_owner'] = tostring(memberid) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username") text = "["..memberid.."] added as owner" end end end end send_large_msg(receiver, text) end --End non-channel_invite username actions --'Set supergroup photo' function local function set_supergroup_photo(msg, success, result) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return end local receiver = get_receiver(msg) if success then local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) channel_set_photo(receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end --Run function local function run(msg, matches) if msg.to.type == 'chat' then if matches[1] == 'tosuper' then if not is_admin1(msg) then return end local receiver = get_receiver(msg) chat_upgrade(receiver, ok_cb, false) end elseif msg.to.type == 'channel'then if matches[1] == 'tosuper' then if not is_admin1(msg) then return end return "Already a SuperGroup" end end if msg.to.type == 'channel' then local support_id = msg.from.id local receiver = get_receiver(msg) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local data = load_data(_config.moderation.data) if matches[1] == 'add' and not matches[2] then if not is_admin1(msg) and not is_support(support_id) then return end if is_super_group(msg) then return reply_msg(msg.id, 'SuperGroup is already added.', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup") superadd(msg) set_mutes(msg.to.id) channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false) end if matches[1] == 'rem' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then return reply_msg(msg.id, 'SuperGroup is not added.', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed") superrem(msg) rem_mutes(msg.to.id) end if not data[tostring(msg.to.id)] then return end if matches[1] == "info" then if not is_owner(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info") channel_info(receiver, callback_info, {receiver = receiver, msg = msg}) end if matches[1] == "admins" then if not is_owner(msg) and not is_support(msg.from.id) then return end member_type = 'Admins' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list") admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1] == "owner" then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your SuperGroup" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "SuperGroup owner is ["..group_owner..']' end if matches[1] == "modlist" then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) -- channel_get_admins(receiver,callback, {receiver = receiver}) end if matches[1] == "bots" and is_momod(msg) then member_type = 'Bots' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list") channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1] == "who" and not matches[2] and is_momod(msg) then local user_id = msg.from.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list") channel_get_users(receiver, callback_who, {receiver = receiver}) end if matches[1] == "kicked" and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list") channel_get_kicked(receiver, callback_kicked, {receiver = receiver}) end if matches[1] == 'del' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'del', msg = msg } delete_msg(msg.id, ok_cb, false) get_message(msg.reply_id, get_message_callback, cbreply_extra) end end if matches[1] == 'block' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'channel_block', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'block' and matches[2] and string.match(matches[2], '^%d+$') then --[[local user_id = matches[2] local channel_id = msg.to.id if is_momod2(user_id, channel_id) and not is_admin2(user_id) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]") kick_user(user_id, channel_id)]] local get_cmd = 'channel_block' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == "block" and matches[2] and not string.match(matches[2], '^%d+$') then --[[local cbres_extra = { channelid = msg.to.id, get_cmd = 'channel_block', sender = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'channel_block' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'id' then if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then local cbreply_extra = { get_cmd = 'id', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then local cbreply_extra = { get_cmd = 'idfrom', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif msg.text:match("@[%a%d]") then local cbres_extra = { channelid = msg.to.id, get_cmd = 'id' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username) resolve_username(username, callbackres, cbres_extra) else savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID") return "SuperGroup ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1] == 'kickme' then if msg.to.type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] left via kickme") channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if matches[1] == 'newlink' and is_momod(msg)then local function callback_link (extra , success, result) local receiver = get_receiver(msg) if success == 0 then send_large_msg(receiver, '*Error: Failed to retrieve link* \nReason: Not creator.\n\nIf you have the link, please use /setlink to set it') data[tostring(msg.to.id)]['settings']['set_link'] = nil save_data(_config.moderation.data, data) else send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link") export_channel_link(receiver, callback_link, false) end if matches[1] == 'setlink' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send the new group link now' end if msg.text then if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = msg.text save_data(_config.moderation.data, data) return "New link set" end end if matches[1] == 'link' then if not is_momod(msg) then return end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first!\n\nOr if I am not creator use /setlink to set your link" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == "invite" and is_sudo(msg) then local cbres_extra = { channel = get_receiver(msg), get_cmd = "invite" } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username) resolve_username(username, callbackres, cbres_extra) end if matches[1] == 'res' and is_owner(msg) then local cbres_extra = { channelid = msg.to.id, get_cmd = 'res' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username) resolve_username(username, callbackres, cbres_extra) end --[[if matches[1] == 'kick' and is_momod(msg) then local receiver = channel..matches[3] local user = "user#id"..matches[2] chaannel_kick(receiver, user, ok_cb, false) end]] if matches[1] == 'setadmin' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'setadmin', msg = msg } setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'setadmin' and matches[2] and string.match(matches[2], '^%d+$') then --[[] local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'setadmin' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]] local get_cmd = 'setadmin' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'setadmin' and matches[2] and not string.match(matches[2], '^%d+$') then --[[local cbres_extra = { channel = get_receiver(msg), get_cmd = 'setadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'setadmin' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'demoteadmin' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demoteadmin', msg = msg } demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'demoteadmin' and matches[2] and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demoteadmin' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'demoteadmin' and matches[2] and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demoteadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username) resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'setowner' and is_owner(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'setowner', msg = msg } setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'setowner' and matches[2] and string.match(matches[2], '^%d+$') then --[[ local group_owner = data[tostring(msg.to.id)]['set_owner'] if group_owner then local receiver = get_receiver(msg) local user_id = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user_id, ok_cb, false) end local user = "user#id"..matches[2] channel_set_admin(receiver, user, ok_cb, false) data[tostring(msg.to.id)]['set_owner'] = tostring(matches[2]) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = "[ "..matches[2].." ] added as owner" return text end]] local get_cmd = 'setowner' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'setowner' and matches[2] and not string.match(matches[2], '^%d+$') then local get_cmd = 'setowner' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'promote' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'promote', msg = msg } promote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'promote' and matches[2] and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'promote' and matches[2] and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'promote', } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'mp' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_set_mod(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'md' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_demote(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'demote' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner/support/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demote', msg = msg } demote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'demote' and matches[2] and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'demote' and matches[2] and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demote' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == "setname" and is_momod(msg) then local receiver = get_receiver(msg) local set_name = string.gsub(matches[2], '_', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2]) rename_channel(receiver, set_name, ok_cb, false) end if msg.service and msg.action.type == 'chat_rename' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title) data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title save_data(_config.moderation.data, data) end if matches[1] == "setabout" and is_momod(msg) then local receiver = get_receiver(msg) local about_text = matches[2] local data_cat = 'description' local target = msg.to.id data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text) channel_set_about(receiver, about_text, ok_cb, false) return "Description has been set.\n\nSelect the chat again to see the changes." end if matches[1] == "setusername" and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username Set.\n\nSelect the chat again to see the changes.") elseif success == 0 then send_large_msg(receiver, "Failed to set SuperGroup username.\nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.") end end local username = string.gsub(matches[2], '@', '') channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end if matches[1] == 'setrules' and is_momod(msg) then rules = matches[2] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]") return set_rulesmod(msg, data, target) end if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo") load_photo(msg.id, set_supergroup_photo, msg) return end end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo") return 'Please send the new group photo now' end if matches[1] == 'clean' then if not is_momod(msg) then return end if not is_momod(msg) then return "Only owner can clean" end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'No moderator(s) in this SuperGroup.' end for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") return 'Modlist has been cleaned' end if matches[2] == 'rules' then local data_cat = 'rules' if data[tostring(msg.to.id)][data_cat] == nil then return "Rules have not been set" end data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") return 'Rules have been cleaned' end if matches[2] == 'about' then local receiver = get_receiver(msg) local about_text = ' ' local data_cat = 'description' if data[tostring(msg.to.id)][data_cat] == nil then return 'About is not set' end data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") channel_set_about(receiver, about_text, ok_cb, false) return "About has been cleaned" end if matches[2] == 'mutelist' then chat_id = msg.to.id local hash = 'mute_user:'..chat_id redis:del(hash) return "Mutelist Cleaned" end if matches[2] == 'username' and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username cleaned.") elseif success == 0 then send_large_msg(receiver, "Failed to clean SuperGroup username.") end end local username = "" channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end if matches[2] == "bots" and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked all SuperGroup bots") channel_get_bots(receiver, callback_clean_bots, {msg = msg}) end end if matches[1] == 'lock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ") return lock_group_links(msg, data, target) end if matches[2] == 'spam' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ") return lock_group_spam(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_flood(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2]:lower() == 'rtl' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names") return lock_group_rtl(msg, data, target) end if matches[2] == 'tgservice' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked Tgservice Actions") return lock_group_tgservice(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting") return lock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting") return lock_group_contacts(msg, data, target) end if matches[2] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings") return enable_strict_rules(msg, data, target) end end if matches[1] == 'unlock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting") return unlock_group_links(msg, data, target) end if matches[2] == 'spam' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam") return unlock_group_spam(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood") return unlock_group_flood(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked Arabic") return unlock_group_arabic(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2]:lower() == 'rtl' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names") return unlock_group_rtl(msg, data, target) end if matches[2] == 'tgservice' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tgservice actions") return unlock_group_tgservice(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting") return unlock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting") return unlock_group_contacts(msg, data, target) end if matches[2] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings") return disable_strict_rules(msg, data, target) end end if matches[1] == 'setflood' then if not is_momod(msg) then return end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Flood has been set to: '..matches[2] end if matches[1] == 'public' and is_momod(msg) then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: not public") return unset_public_membermod(msg, data, target) end end if matches[1] == 'mute' and is_owner(msg) then local chat_id = msg.to.id if matches[2] == 'audio' then local msg_type = 'Audio' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'photo' then local msg_type = 'Photo' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'video' then local msg_type = 'Video' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'gifs' then local msg_type = 'Gifs' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." have been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'documents' then local msg_type = 'Documents' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." have been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'text' then local msg_type = 'Text' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "Mute "..msg_type.." is already on" end end if matches[2] == 'all' then local msg_type = 'All' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return "Mute "..msg_type.." has been enabled" else return "Mute "..msg_type.." is already on" end end end if matches[1] == 'unmute' and is_momod(msg) then local chat_id = msg.to.id if matches[2] == 'audio' then local msg_type = 'Audio' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'photo' then local msg_type = 'Photo' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'video' then local msg_type = 'Video' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'gifs' then local msg_type = 'Gifs' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'documents' then local msg_type = 'Documents' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'text' then local msg_type = 'Text' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute message") unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute text is already off" end end if matches[2] == 'all' then local msg_type = 'All' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return "Mute "..msg_type.." has been disabled" else return "Mute "..msg_type.." is already disabled" end end end if matches[1] == "muteuser" and is_momod(msg) then local chat_id = msg.to.id local hash = "mute_user"..chat_id local user_id = "" if type(msg.reply_id) ~= "nil" then local receiver = get_receiver(msg) local get_cmd = "mute_user" muteuser = get_message(msg.reply_id, get_message_callback, {receiver = receiver, get_cmd = get_cmd, msg = msg}) elseif matches[1] == "muteuser" and matches[2] and string.match(matches[2], '^%d+$') then local user_id = matches[2] if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list") return "["..user_id.."] removed from the muted users list" elseif is_owner(msg) then mute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list") return "["..user_id.."] added to the muted user list" end elseif matches[1] == "muteuser" and matches[2] and not string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local get_cmd = "mute_user" local username = matches[2] local username = string.gsub(matches[2], '@', '') resolve_username(username, callbackres, {receiver = receiver, get_cmd = get_cmd, msg=msg}) end end if matches[1] == "muteslist" and is_momod(msg) then local chat_id = msg.to.id if not has_mutes(chat_id) then set_mutes(chat_id) return mutes_list(chat_id) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist") return mutes_list(chat_id) end if matches[1] == "mutelist" and is_momod(msg) then local chat_id = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist") return muted_user_list(chat_id) end if matches[1] == 'settings' and is_momod(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ") return show_supergroup_settingsmod(msg, target) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'help' and not is_owner(msg) then text = "Message /superhelp to @Teleseed in private for SuperGroup help" reply_msg(msg.id, text, ok_cb, false) elseif matches[1] == 'help' and is_owner(msg) then local name_log = user_print_name(msg.from) savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp") return super_help() end if matches[1] == 'peer_id' and is_admin1(msg)then text = msg.to.peer_id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end if matches[1] == 'msg.to.id' and is_admin1(msg) then text = msg.to.id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end --Admin Join Service Message if msg.service then local action = msg.action.type if action == 'chat_add_user_link' then if is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.from.id) and not is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup") channel_set_mod(receiver, user, ok_cb, false) end end if action == 'chat_add_user' then if is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_mod(receiver, user, ok_cb, false) end end end if matches[1] == 'msg.to.peer_id' then post_large_msg(receiver, msg.to.peer_id) end end end local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end return { patterns = { "^[#!/]([Aa]dd)$", "^[#!/]([Rr]em)$", "^[#!/]([Mm]ove) (.*)$", "^[#!/]([Ii]nfo)$", "^[#!/]([Aa]dmins)$", "^[#!/]([Oo]wner)$", "^[#!/]([Mm]odlist)$", "^[#!/]([Bb]ots)$", "^[#!/]([Ww]ho)$", "^[#!/]([Kk]icked)$", "^[#!/]([Bb]lock) (.*)", "^[#!/]([Bb]lock)", "^[#!/]([Tt]osuper)$", "^[#!/]([Ii][Dd])$", "^[#!/]([Ii][Dd]) (.*)$", "^[#!/]([Kk]ickme)$", "^[#!/]([Kk]ick) (.*)$", "^[#!/]([Nn]ewlink)$", "^[#!/]([Ss]etlink)$", "^[#!/]([Ll]ink)$", "^[#!/]([Rr]es) (.*)$", "^[#!/]([Ss]etadmin) (.*)$", "^[#!/]([Ss]etadmin)", "^[#!/]([Dd]emoteadmin) (.*)$", "^[#!/]([Dd]emoteadmin)", "^[#!/]([Ss]etowner) (.*)$", "^[#!/]([Ss]etowner)$", "^[#!/]([Pp]romote) (.*)$", "^[#!/]([Pp]romote)", "^[#!/]([Dd]emote) (.*)$", "^[#!/]([Dd]emote)", "^[#!/]([Ss]etname) (.*)$", "^[#!/]([Ss]etabout) (.*)$", "^[#!/]([Ss]etrules) (.*)$", "^[#!/]([Ss]etphoto)$", "^[#!/]([Ss]etusername) (.*)$", "^[#!/]([Dd]el)$", "^[#!/]([Ll]ock) (.*)$", "^[#!/]([Uu]nlock) (.*)$", "^[#!/]([Mm]ute) ([^%s]+)$", "^[#!/]([Uu]nmute) ([^%s]+)$", "^[#!/]([Mm]uteuser)$", "^[#!/]([Mm]uteuser) (.*)$", "^[#!/]([Pp]ublic) (.*)$", "^[#!/]([Ss]ettings)$", "^[#!/]([Rr]ules)$", "^[#!/]([Ss]etflood) (%d+)$", "^[#!/]([Cc]lean) (.*)$", "^[#!/]([Hh]elp)$", "^[#!/]([Mm]uteslist)$", "^[#!/]([Mm]utelist)$", "[#!/](mp) (.*)", "[#!/](md) (.*)", "^(https://telegram.me/joinchat/%S+)$", "msg.to.peer_id", "%[(document)%]", "%[(photo)%]", "%[(video)%]", "%[(audio)%]", "%[(contact)%]", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process } --End supergrpup.lua --By @Rondoozle
gpl-2.0
Ninjistix/darkstar
scripts/zones/Apollyon/mobs/Carnagechief_Jackbodokk.lua
5
2095
----------------------------------- -- Area: Apollyon CS -- MOB: Carnagechief_Jackbodokk ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Apollyon/TextIDs"); require("scripts/globals/limbus"); ----------------------------------- function onMobSpawn(mob) mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; function onMobEngaged(mob,target) local mobID = mob:getID(); local X = mob:getXPos(); local Y = mob:getYPos(); local Z = mob:getZPos(); SpawnMob(16933130):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933131):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933132):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; function onMobFight(mob,target) local mobID = mob:getID(); local X = mob:getXPos(); local Y = mob:getYPos(); local Z = mob:getZPos(); local lifepourcent= ((mob:getHP()/mob:getMaxHP())*100); local instancetime = target:getSpecialBattlefieldLeftTime(5); if (lifepourcent < 50 and GetNPCByID(16933245):getAnimation() == 8) then SpawnMob(16933134):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933135):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933133):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933136):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetNPCByID(16933245):setAnimation(9); end if (instancetime < 13) then if (IsMobDead(16933144) == false) then --link dee wapa GetMobByID(16933144):updateEnmity(target); elseif (IsMobDead(16933137) == false) then --link na qba GetMobByID(16933137):updateEnmity(target); end end end; function onMobDeath(mob, player, isKiller) if ((IsMobDead(16933144) == false or IsMobDead(16933137) == false) and alreadyReceived(player,1,GetInstanceRegion(1294)) == false) then player:addTimeToSpecialBattlefield(5,5); addLimbusList(player,1,GetInstanceRegion(1294)); end end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/weaponskills/metatron_torment.lua
3
2176
----------------------------------- -- Metatron Torment -- Hand-to-Hand Skill level: 5 Description: Delivers a threefold attack. Damage varies wit weapon skill -- Great Axe Weapon Skill -- Skill Level: N/A -- Lowers target's defense. Additional effect: temporarily lowers damage taken from enemies. -- Defense Down effect is 18.5%, 1 minute duration. -- Damage reduced is 20.4% or 52/256. -- Lasts 20 seconds at 100TP, 40 seconds at 200TP and 60 seconds at 300TP. -- Available only when equipped with the Relic Weapons Abaddon Killer (Dynamis use only) or Bravura. -- Also available as a Latent effect on Barbarus Bhuj -- Since these Relic Weapons are only available to Warriors, only Warriors may use this Weapon Skill. -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: None -- Modifiers: STR:60% -- 100%TP 200%TP 300%TP -- 2.75 2.75 2.75 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 2.75; params.ftp200 = 2.75; params.ftp300 = 2.75; params.str_wsc = 0.6; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.8; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (damage > 0 and target:hasStatusEffect(EFFECT_ATTACK_DOWN) == false) then local duration = (tp/1000 * 20) * applyResistanceAddEffect(player,target,ELE_WIND,0); target:addStatusEffect(EFFECT_DEFENSE_DOWN, 19, 0, duration); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Ninjistix/darkstar
scripts/zones/QuBia_Arena/bcnms/heir_to_the_light.lua
5
1912
----------------------------------- -- Name: Mission 9-2 SANDO ----------------------------------- package.loaded["scripts/zones/Qubia_arena/TextIDs"] = nil; ------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/QuBia_Arena/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); local currentMission = player:getCurrentMission(SANDORIA); if (leavecode == 2) then --printf("win"); if (currentMission == THE_HEIR_TO_THE_LIGHT) then player:startEvent(32001,1,1,1,instance:getTimeInside(),1,4,0); else player:startEvent(32001,1,1,1,instance:getTimeInside(),1,4,1); end elseif (leavecode == 4) then player:startEvent(32002); end end; function onEventUpdate(player,csid,option) --print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) --print("bc finish csid "..csid.." and option "..option); local currentMission = player:getCurrentMission(SANDORIA); local MissionStatus = player:getVar("MissionStatus"); if (csid == 32001) then if (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 3) then player:setVar("MissionStatus",4); end end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Wyatt.lua
5
1728
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Wyatt -- @zone 80 -- !pos 124 0 84 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/titles"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 4 and trade:hasItemQty(2506,4)) then player:startEvent(4); end end; function onTrigger(player,npc) local seeingSpots = player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS); if (seeingSpots == QUEST_AVAILABLE) then player:startEvent(2); elseif (seeingSpots == QUEST_ACCEPTED) then player:startEvent(3); else player:showText(npc, WYATT_DIALOG); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 2) then player:addQuest(CRYSTAL_WAR,SEEING_SPOTS); elseif (csid == 4) then player:tradeComplete(); if (player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS) == QUEST_ACCEPTED) then player:addTitle(LADY_KILLER); player:addGil(GIL_RATE*3000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000); player:completeQuest(CRYSTAL_WAR,SEEING_SPOTS); else player:addTitle(LADY_KILLER); player:addGil(GIL_RATE*3000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000); end end end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/mobskills/hurricane_wing.lua
66
1332
--------------------------------------------- -- Hurricane Wing -- -- Description: Deals hurricane-force wind damage to enemies within a very wide area of effect. Additional effect: Blind -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: 30' radial. -- Notes: Used only by Dragua, Fafnir, Nidhogg, Cynoprosopi, Wyrm, and Odzmanouk. The blinding effect does not last long -- but is very harsh. The attack is wide enough to generally hit an entire alliance. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (target:isBehind(mob, 48) == true) then return 1; elseif (mob:AnimationSub() ~= 0) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_BLINDNESS; MobStatusEffectMove(mob, target, typeEffect, 60, 0, 30); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_WIND,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
istarIQ/Source
msg_checks.lua
37
10930
--Begin msg_checks.lua --Begin pre_process function local function pre_process(msg) -- Begin 'RondoMsgChecks' text checks by @rondoozle if is_chat_msg(msg) or is_super_group(msg) then if msg and not is_momod(msg) and not is_whitelisted(msg.from.id) then --if regular user local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") -- get rid of rtl in names local name_log = print_name:gsub("_", " ") -- name for log local to_chat = msg.to.type == 'chat' if data[tostring(msg.to.id)] and data[tostring(msg.to.id)]['settings'] then settings = data[tostring(msg.to.id)]['settings'] else return end if settings.lock_arabic then lock_arabic = settings.lock_arabic else lock_arabic = 'no' end if settings.lock_rtl then lock_rtl = settings.lock_rtl else lock_rtl = 'no' end if settings.lock_link then lock_link = settings.lock_link else lock_link = 'no' end if settings.lock_member then lock_member = settings.lock_member else lock_member = 'no' end if settings.lock_spam then lock_spam = settings.lock_spam else lock_spam = 'no' end if settings.lock_sticker then lock_sticker = settings.lock_sticker else lock_sticker = 'no' end if settings.lock_contacts then lock_contacts = settings.lock_contacts else lock_contacts = 'no' end if settings.strict then strict = settings.strict else strict = 'no' end if msg and not msg.service and is_muted(msg.to.id, 'All: yes') or is_muted_user(msg.to.id, msg.from.id) and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then -- kick_user(msg.from.id, msg.to.id) end end if msg.text then -- msg.text checks local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') local _nl, real_digits = string.gsub(msg.text, '%d', '') if lock_spam == "yes" and string.len(msg.text) > 2049 or ctrl_chars > 40 or real_digits > 2000 then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local is_link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") local is_bot = msg.text:match("?[Ss][Tt][Aa][Rr][Tt]=") if is_link_msg and lock_link == "yes" and not is_bot then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_msg = msg.text:match("[\216-\219][\128-\191]") if is_squig_msg and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl = print_name:match("‮") or msg.text:match("‮") if is_rtl and lock_rtl == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, "Text: yes") and msg.text and not msg.media and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media then -- msg.media checks if msg.media.title then local is_link_title = msg.media.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.media.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.description then local is_link_desc = msg.media.description:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.description:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_desc and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_desc = msg.media.description:match("[\216-\219][\128-\191]") if is_squig_desc and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.caption then -- msg.media.caption checks local is_link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_caption and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_caption = msg.media.caption:match("[\216-\219][\128-\191]") if is_squig_caption and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_username_caption = msg.media.caption:match("^@[%a%d]") if is_username_caption and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if lock_sticker == "yes" and msg.media.caption:match("sticker.webp") then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.type:match("contact") and lock_contacts == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_photo_caption = msg.media.caption and msg.media.caption:match("photo")--".jpg", if is_muted(msg.to.id, 'Photo: yes') and msg.media.type:match("photo") or is_photo_caption and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end local is_gif_caption = msg.media.caption and msg.media.caption:match(".mp4") if is_muted(msg.to.id, 'Gifs: yes') and is_gif_caption and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Audio: yes') and msg.media.type:match("audio") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_video_caption = msg.media.caption and msg.media.caption:lower(".mp4","video") if is_muted(msg.to.id, 'Video: yes') and msg.media.type:match("video") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Documents: yes') and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.fwd_from then if msg.fwd_from.title then local is_link_title = msg.fwd_from.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.fwd_from.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.fwd_from.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if is_muted_user(msg.to.id, msg.fwd_from.peer_id) then delete_msg(msg.id, ok_cb, false) end end if msg.service then -- msg.service checks local action = msg.action.type if action == 'chat_add_user_link' then local user_id = msg.from.id local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') if string.len(msg.from.print_name) > 70 or ctrl_chars > 40 and lock_group_spam == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] joined and Service Msg deleted (#spam name)") delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then savelog(msg.to.id, name_log.." ["..msg.from.id.."] joined and kicked (#spam name)") kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "yes" then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] joined and kicked (#RTL char in name)") kick_user(user_id, msg.to.id) end if lock_member == 'yes' then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] joined and kicked (#lockmember)") kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end if action == 'chat_add_user' and not is_momod2(msg.from.id, msg.to.id) then local user_id = msg.action.user.id if string.len(msg.action.user.print_name) > 70 and lock_group_spam == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."]: Service Msg deleted (#spam name)") delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#spam name) ") delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local print_name = msg.action.user.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "yes" then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#RTL char in name)") kick_user(user_id, msg.to.id) end if msg.to.type == 'channel' and lock_member == 'yes' then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#lockmember)") kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end end end end -- End 'RondoMsgChecks' text checks by @Rondoozle return msg end --End pre_process function return { patterns = {}, pre_process = pre_process } --End msg_checks.lua --By @Rondoozle
gpl-2.0
Ninjistix/darkstar
scripts/globals/spells/absorb-acc.lua
4
1539
-------------------------------------- -- Spell: Absorb-ACC -- Steals an enemy's accuracy. -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) if (caster:hasStatusEffect(EFFECT_ACCURACY_BOOST)) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); -- no effect else local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT); local params = {}; params.diff = nil; params.attribute = MOD_INT; params.skillType = 37; params.bonus = 0; params.effect = nil; local resist = applyResistance(caster, target, spell, params); if (resist <= 0.125) then spell:setMsg(msgBasic.MAGIC_RESIST); else spell:setMsg(msgBasic.MAGIC_ABSORB_ACC); caster:addStatusEffect(EFFECT_ACCURACY_BOOST,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_DISPELABLE); -- caster gains ACC target:addStatusEffect(EFFECT_ACCURACY_DOWN,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_ERASABLE); -- target loses ACC end end return EFFECT_ACCURACY_BOOST; end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/items/flask_of_panacea.lua
3
1585
----------------------------------------- -- ID: 4163 -- Item: Panacea -- Item Effect: Removes any number of status effects ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) return 0; end; function onItemUse(target) target:delStatusEffect(EFFECT_PARALYSIS); target:delStatusEffect(EFFECT_BIND); target:delStatusEffect(EFFECT_WEIGHT); target:delStatusEffect(EFFECT_ADDLE); target:delStatusEffect(EFFECT_BURN); target:delStatusEffect(EFFECT_FROST); target:delStatusEffect(EFFECT_CHOKE); target:delStatusEffect(EFFECT_RASP); target:delStatusEffect(EFFECT_SHOCK); target:delStatusEffect(EFFECT_DROWN); target:delStatusEffect(EFFECT_DIA); target:delStatusEffect(EFFECT_BIO); target:delStatusEffect(EFFECT_STR_DOWN); target:delStatusEffect(EFFECT_DEX_DOWN); target:delStatusEffect(EFFECT_VIT_DOWN); target:delStatusEffect(EFFECT_AGI_DOWN); target:delStatusEffect(EFFECT_INT_DOWN); target:delStatusEffect(EFFECT_MND_DOWN); target:delStatusEffect(EFFECT_CHR_DOWN); target:delStatusEffect(EFFECT_MAX_HP_DOWN); target:delStatusEffect(EFFECT_MAX_MP_DOWN); target:delStatusEffect(EFFECT_ATTACK_DOWN); target:delStatusEffect(EFFECT_EVASION_DOWN); target:delStatusEffect(EFFECT_DEFENSE_DOWN); target:delStatusEffect(EFFECT_MAGIC_DEF_DOWN); target:delStatusEffect(EFFECT_INHIBIT_TP); target:delStatusEffect(EFFECT_MAGIC_ACC_DOWN); target:delStatusEffect(EFFECT_MAGIC_ATK_DOWN); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/weaponskills/true_strike.lua
25
1495
----------------------------------- -- True Strike -- Club weapon skill -- Skill level: 175 -- Deals params.critical damage. params.accuracy varies with TP. -- 100% Critical Hit Rate. Has a substantial accuracy penalty at 100TP. http://www.bg-wiki.com/bg/True_Strike -- Will stack with Sneak Attack. -- Aligned with the Breeze Gorget & Thunder Gorget. -- Aligned with the Breeze Belt & Thunder Belt. -- Element: None -- Modifiers: STR:100% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 1.0; params.crit200 = 1.0; params.crit300 = 1.0; params.canCrit = true; params.acc100 = 0.5; params.acc200= 0.7; params.acc300= 1; params.atkmulti = 2; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 1.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
blackman1380/antispam
libs/feedparser.lua
543
11955
local LOM = assert(require("lxp.lom"), "LuaExpat doesn't seem to be installed. feedparser kind of needs it to work...") local XMLElement = (loadfile "./libs/XMLElement.lua")() local dateparser = (loadfile "./libs/dateparser.lua")() local URL = (loadfile "./libs/url.lua")() local tinsert, tremove, tconcat = table.insert, table.remove, table.concat local pairs, ipairs = pairs, ipairs --- feedparser, similar to the Universal Feed Parser for python, but a good deal weaker. -- see http://feedparser.org for details about the Universal Feed Parser local feedparser= { _DESCRIPTION = "RSS and Atom feed parser", _VERSION = "feedparser 0.71" } local blanky = XMLElement.new() --useful in a whole bunch of places local function resolve(url, base_url) return URL.absolute(base_url, url) end local function rebase(el, base_uri) local xml_base = el:getAttr('xml:base') if not xml_base then return base_uri end return resolve(xml_base, base_uri) end local function parse_entries(entries_el, format_str, base) local entries = {} for i, entry_el in ipairs(entries_el) do local entry = {enclosures={}, links={}, contributors={}} local entry_base = rebase(entry_el, base) for i, el in ipairs(entry_el:getChildren('*')) do local tag = el:getTag() local el_base = rebase(el, entry_base) --title if tag == 'title' or tag == 'dc:title' or tag =='rdf:title' then --'dc:title' doesn't occur in atom feeds, but whatever. entry.title=el:getText() --link(s) elseif format_str == 'rss' and tag=='link' then entry.link=resolve(el:getText(), el_base) tinsert(entry.links, {href=entry.link}) elseif (format_str=='atom' and tag == 'link') or (format_str == 'rss' and tag=='atom:link') then local link = {} for i, attr in ipairs{'rel','type', 'href','title'} do link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr) --uri end tinsert(entry.links, link) if link.rel=='enclosure' then tinsert(entry.enclosures, { href=link.href, length=el:getAttr('length'), type=el:getAttr('type') }) end --rss enclosures elseif format_str == 'rss' and tag=='enclosure' then tinsert(entry.enclosures, { url=el:getAttr('url'), length=el:getAttr('length'), type=el:getAttr('type') }) --summary elseif (format_str=='atom' and tag=='summary') or (format_str=='rss' and(tag=='description' or tag=='dc:description' or tag=='rdf:description')) then entry.summary=el:getText() --TODO: summary_detail --content elseif (format_str=='atom' and tag=='content') or (format_str=='rss' and (tag=='body' or tag=='xhtml:body' or tag == 'fullitem' or tag=='content:encoded')) then entry.content=el:getText() --TODO: content_detail --published elseif (format_str == 'atom' and (tag=='published' or tag=='issued')) or (format_str == 'rss' and (tag=='dcterms:issued' or tag=='atom:published' or tag=='atom:issued')) then entry.published = el:getText() entry.published_parsed=dateparser.parse(entry.published) --updated elseif (format_str=='atom' and (tag=='updated' or tag=='modified')) or (format_str=='rss' and (tag=='dc:date' or tag=='pubDate' or tag=='dcterms:modified')) then entry.updated=el:getText() entry.updated_parsed=dateparser.parse(entry.updated) elseif tag=='created' or tag=='atom:created' or tag=='dcterms:created' then entry.created=el:getText() entry.created_parsed=dateparser.parse(entry.created) --id elseif (format_str =='atom' and tag=='id') or (format_str=='rss' and tag=='guid') then entry.id=resolve(el:getText(), el_base) -- this is a uri, right?... --author elseif format_str=='rss' and (tag=='author' or tag=='dc:creator') then --author tag should give the author's email. should I respect this? entry.author=(el:getChild('name') or el):getText() entry.author_detail={ name=entry.author } elseif format_str=='atom' and tag=='author' then entry.author=(el:getChild('name') or el):getText() entry.author_detail = { name=entry.author, email=(el:getChild('email') or blanky):getText() } local author_url = (el:getChild('url') or blanky):getText() if author_url and author_url ~= "" then entry.author_detail.href=resolve(author_url, rebase(el:getChild('url'), el_base)) end elseif tag=='category' or tag=='dc:subject' then --todo elseif tag=='source' then --todo end end --wrap up rss guid if format_str == 'rss' and (not entry.id) and entry_el:getAttr('rdf:about') then entry.id=resolve(entry_el:getAttr('rdf:about'), entry_base) --uri end --wrap up entry.link for i, link in pairs(entry.links) do if link.rel=="alternate" or (not link.rel) or link.rel=="" then entry.link=link.href --already resolved. break end end if not entry.link and format_str=='rss' then entry.link=entry.id end tinsert(entries, entry) end return entries end local function atom_person_construct(person_el, base_uri) local dude ={ name= (person_el:getChild('name') or blanky):getText(), email=(person_el:getChild('email') or blanky):getText() } local url_el = person_el:getChild('url') if url_el then dude.href=resolve(url_el:getText(), rebase(url_el, base_uri)) end return dude end local function parse_atom(root, base_uri) local res = {} local feed = { links = {}, contributors={}, language = root:getAttr('lang') or root:getAttr('xml:lang') } local root_base = rebase(root, base_uri) res.feed=feed res.format='atom' local version=(root:getAttr('version') or ''):lower() if version=="1.0" or root:getAttr('xmlns')=='http://www.w3.org/2005/Atom' then res.version='atom10' elseif version=="0.3" then res.version='atom03' else res.version='atom' end for i, el in ipairs(root:getChildren('*')) do local tag = el:getTag() local el_base=rebase(el, root_base) if tag == 'title' or tag == 'dc:title' or tag == 'atom10:title' or tag == 'atom03:title' then feed.title=el:getText() --sanitize! --todo: feed.title_detail --link stuff elseif tag=='link' then local link = {} for i, attr in ipairs{'rel','type', 'href','title'} do link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr) end tinsert(feed.links, link) --subtitle elseif tag == 'subtitle' then feed.subtitle=el:getText() --sanitize! elseif not feed.subtitle and (tag == 'tagline' or tag =='atom03:tagline' or tag=='dc:description') then feed.subtitle=el:getText() --sanitize! --rights elseif tag == 'copyright' or tag == 'rights' then feed.rights=el:getText() --sanitize! --generator elseif tag == 'generator' then feed.generator=el:getText() --sanitize! elseif tag == 'admin:generatorAgent' then feed.generator = feed.generator or el:getAttr('rdf:resource') --info elseif tag == 'info' then --whatever, nobody cared, anyway. feed.info = el:getText() --id elseif tag=='id' then feed.id=resolve(el:getText(), el_base) --this is a url, right?.,, --updated elseif tag == 'updated' or tag == 'dc:date' or tag == 'modified' or tag=='rss:pubDate' then feed.updated = el:getText() feed.updated_parsed=dateparser.parse(feed.updated) --author elseif tag=='author' or tag=='atom:author' then feed.author_detail=atom_person_construct(el, el_base) feed.author=feed.author_detail.name --contributors elseif tag=='contributor' or tag=='atom:contributor' then tinsert(feed.contributors, atom_person_construct(el, el_base)) --icon elseif tag=='icon' then feed.icon=resolve(el:getText(), el_base) --logo elseif tag=='logo' then feed.logo=resolve(el:getText(), el_base) --language elseif tag=='language' or tag=='dc:language' then feed.language=feed.language or el:getText() --licence end end --feed.link (already resolved) for i, link in pairs(feed.links) do if link.rel=='alternate' or not link.rel or link.rel=='' then feed.link=link.href break end end res.entries=parse_entries(root:getChildren('entry'),'atom', root_base) return res end local function parse_rss(root, base_uri) local channel = root:getChild({'channel', 'rdf:channel'}) local channel_base = rebase(channel, base_uri) if not channel then return nil, "can't parse that." end local feed = {links = {}, contributors={}} local res = { feed=feed, format='rss', entries={} } --this isn't quite right at all. if root:getTag():lower()=='rdf:rdf' then res.version='rss10' else res.version='rss20' end for i, el in ipairs(channel:getChildren('*')) do local el_base=rebase(el, channel_base) local tag = el:getTag() if tag=='link' then feed.link=resolve(el:getText(), el_base) tinsert(feed.links, {href=feed.link}) --title elseif tag == 'title' or tag == 'dc:title' then feed.title=el:getText() --sanitize! --subtitle elseif tag == 'description' or tag =='dc:description' or tag=='itunes:subtitle' then feed.subtitle=el:getText() --sanitize! --rights elseif tag == 'copyright' or tag == 'dc:rights' then feed.rights=el:getText() --sanitize! --generator elseif tag == 'generator' then feed.generator=el:getText() elseif tag == 'admin:generatorAgent' then feed.generator = feed.generator or el:getAttr('rdf:resource') --info (nobody cares...) elseif tag == 'feedburner:browserFriendly' then feed.info = el:getText() --updated elseif tag == 'pubDate' or tag == 'dc:date' or tag == 'dcterms:modified' then feed.updated = el:getText() feed.updated_parsed = dateparser.parse(feed.updated) --author elseif tag=='managingEditor' or tag =='dc:creator' or tag=='itunes:author' or tag =='dc:creator' or tag=='dc:author' then feed.author=tconcat(el:getChildren('text()')) feed.author_details={name=feed.author} elseif tag=='atom:author' then feed.author_details = atom_person_construct(el, el_base) feed.author = feed.author_details.name --contributors elseif tag == 'dc:contributor' then tinsert(feed.contributors, {name=el:getText()}) elseif tag == 'atom:contributor' then tinsert(feed.contributors, atom_person_construct(el, el_base)) --image elseif tag=='image' or tag=='rdf:image' then feed.image={ title=el:getChild('title'):getText(), link=(el:getChild('link') or blanky):getText(), width=(el:getChild('width') or blanky):getText(), height=(el:getChild('height') or blanky):getText() } local url_el = el:getChild('url') if url_el then feed.image.href = resolve(url_el:getText(), rebase(url_el, el_base)) end --language elseif tag=='language' or tag=='dc:language' then feed.language=el:getText() --licence --publisher --tags end end res.entries=parse_entries(channel:getChildren('item'),'rss', channel_base) return res end --- parse feed xml -- @param xml_string feed xml, as a string -- @param base_url (optional) source url of the feed. useful when resolving relative links found in feed contents -- @return table with parsed feed info, or nil, error_message on error. -- the format of the returned table is much like that on http://feedparser.org, with the major difference that -- dates are parsed into unixtime. Most other fields are very much the same. function feedparser.parse(xml_string, base_url) local lom, err = LOM.parse(xml_string) if not lom then return nil, "couldn't parse xml. lxp says: " .. err or "nothing" end local rootElement = XMLElement.new(lom) local root_tag = rootElement:getTag():lower() if root_tag=='rdf:rdf' or root_tag=='rss' then return parse_rss(rootElement, base_url) elseif root_tag=='feed' then return parse_atom(rootElement, base_url) else return nil, "unknown feed format" end end --for the sake of backwards-compatibility, feedparser will export a global reference for lua < 5.3 if _VERSION:sub(-3) < "5.3" then _G.feedparser=feedparser end return feedparser
gpl-2.0
wounds1/zaza2
libs/feedparser.lua
543
11955
local LOM = assert(require("lxp.lom"), "LuaExpat doesn't seem to be installed. feedparser kind of needs it to work...") local XMLElement = (loadfile "./libs/XMLElement.lua")() local dateparser = (loadfile "./libs/dateparser.lua")() local URL = (loadfile "./libs/url.lua")() local tinsert, tremove, tconcat = table.insert, table.remove, table.concat local pairs, ipairs = pairs, ipairs --- feedparser, similar to the Universal Feed Parser for python, but a good deal weaker. -- see http://feedparser.org for details about the Universal Feed Parser local feedparser= { _DESCRIPTION = "RSS and Atom feed parser", _VERSION = "feedparser 0.71" } local blanky = XMLElement.new() --useful in a whole bunch of places local function resolve(url, base_url) return URL.absolute(base_url, url) end local function rebase(el, base_uri) local xml_base = el:getAttr('xml:base') if not xml_base then return base_uri end return resolve(xml_base, base_uri) end local function parse_entries(entries_el, format_str, base) local entries = {} for i, entry_el in ipairs(entries_el) do local entry = {enclosures={}, links={}, contributors={}} local entry_base = rebase(entry_el, base) for i, el in ipairs(entry_el:getChildren('*')) do local tag = el:getTag() local el_base = rebase(el, entry_base) --title if tag == 'title' or tag == 'dc:title' or tag =='rdf:title' then --'dc:title' doesn't occur in atom feeds, but whatever. entry.title=el:getText() --link(s) elseif format_str == 'rss' and tag=='link' then entry.link=resolve(el:getText(), el_base) tinsert(entry.links, {href=entry.link}) elseif (format_str=='atom' and tag == 'link') or (format_str == 'rss' and tag=='atom:link') then local link = {} for i, attr in ipairs{'rel','type', 'href','title'} do link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr) --uri end tinsert(entry.links, link) if link.rel=='enclosure' then tinsert(entry.enclosures, { href=link.href, length=el:getAttr('length'), type=el:getAttr('type') }) end --rss enclosures elseif format_str == 'rss' and tag=='enclosure' then tinsert(entry.enclosures, { url=el:getAttr('url'), length=el:getAttr('length'), type=el:getAttr('type') }) --summary elseif (format_str=='atom' and tag=='summary') or (format_str=='rss' and(tag=='description' or tag=='dc:description' or tag=='rdf:description')) then entry.summary=el:getText() --TODO: summary_detail --content elseif (format_str=='atom' and tag=='content') or (format_str=='rss' and (tag=='body' or tag=='xhtml:body' or tag == 'fullitem' or tag=='content:encoded')) then entry.content=el:getText() --TODO: content_detail --published elseif (format_str == 'atom' and (tag=='published' or tag=='issued')) or (format_str == 'rss' and (tag=='dcterms:issued' or tag=='atom:published' or tag=='atom:issued')) then entry.published = el:getText() entry.published_parsed=dateparser.parse(entry.published) --updated elseif (format_str=='atom' and (tag=='updated' or tag=='modified')) or (format_str=='rss' and (tag=='dc:date' or tag=='pubDate' or tag=='dcterms:modified')) then entry.updated=el:getText() entry.updated_parsed=dateparser.parse(entry.updated) elseif tag=='created' or tag=='atom:created' or tag=='dcterms:created' then entry.created=el:getText() entry.created_parsed=dateparser.parse(entry.created) --id elseif (format_str =='atom' and tag=='id') or (format_str=='rss' and tag=='guid') then entry.id=resolve(el:getText(), el_base) -- this is a uri, right?... --author elseif format_str=='rss' and (tag=='author' or tag=='dc:creator') then --author tag should give the author's email. should I respect this? entry.author=(el:getChild('name') or el):getText() entry.author_detail={ name=entry.author } elseif format_str=='atom' and tag=='author' then entry.author=(el:getChild('name') or el):getText() entry.author_detail = { name=entry.author, email=(el:getChild('email') or blanky):getText() } local author_url = (el:getChild('url') or blanky):getText() if author_url and author_url ~= "" then entry.author_detail.href=resolve(author_url, rebase(el:getChild('url'), el_base)) end elseif tag=='category' or tag=='dc:subject' then --todo elseif tag=='source' then --todo end end --wrap up rss guid if format_str == 'rss' and (not entry.id) and entry_el:getAttr('rdf:about') then entry.id=resolve(entry_el:getAttr('rdf:about'), entry_base) --uri end --wrap up entry.link for i, link in pairs(entry.links) do if link.rel=="alternate" or (not link.rel) or link.rel=="" then entry.link=link.href --already resolved. break end end if not entry.link and format_str=='rss' then entry.link=entry.id end tinsert(entries, entry) end return entries end local function atom_person_construct(person_el, base_uri) local dude ={ name= (person_el:getChild('name') or blanky):getText(), email=(person_el:getChild('email') or blanky):getText() } local url_el = person_el:getChild('url') if url_el then dude.href=resolve(url_el:getText(), rebase(url_el, base_uri)) end return dude end local function parse_atom(root, base_uri) local res = {} local feed = { links = {}, contributors={}, language = root:getAttr('lang') or root:getAttr('xml:lang') } local root_base = rebase(root, base_uri) res.feed=feed res.format='atom' local version=(root:getAttr('version') or ''):lower() if version=="1.0" or root:getAttr('xmlns')=='http://www.w3.org/2005/Atom' then res.version='atom10' elseif version=="0.3" then res.version='atom03' else res.version='atom' end for i, el in ipairs(root:getChildren('*')) do local tag = el:getTag() local el_base=rebase(el, root_base) if tag == 'title' or tag == 'dc:title' or tag == 'atom10:title' or tag == 'atom03:title' then feed.title=el:getText() --sanitize! --todo: feed.title_detail --link stuff elseif tag=='link' then local link = {} for i, attr in ipairs{'rel','type', 'href','title'} do link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr) end tinsert(feed.links, link) --subtitle elseif tag == 'subtitle' then feed.subtitle=el:getText() --sanitize! elseif not feed.subtitle and (tag == 'tagline' or tag =='atom03:tagline' or tag=='dc:description') then feed.subtitle=el:getText() --sanitize! --rights elseif tag == 'copyright' or tag == 'rights' then feed.rights=el:getText() --sanitize! --generator elseif tag == 'generator' then feed.generator=el:getText() --sanitize! elseif tag == 'admin:generatorAgent' then feed.generator = feed.generator or el:getAttr('rdf:resource') --info elseif tag == 'info' then --whatever, nobody cared, anyway. feed.info = el:getText() --id elseif tag=='id' then feed.id=resolve(el:getText(), el_base) --this is a url, right?.,, --updated elseif tag == 'updated' or tag == 'dc:date' or tag == 'modified' or tag=='rss:pubDate' then feed.updated = el:getText() feed.updated_parsed=dateparser.parse(feed.updated) --author elseif tag=='author' or tag=='atom:author' then feed.author_detail=atom_person_construct(el, el_base) feed.author=feed.author_detail.name --contributors elseif tag=='contributor' or tag=='atom:contributor' then tinsert(feed.contributors, atom_person_construct(el, el_base)) --icon elseif tag=='icon' then feed.icon=resolve(el:getText(), el_base) --logo elseif tag=='logo' then feed.logo=resolve(el:getText(), el_base) --language elseif tag=='language' or tag=='dc:language' then feed.language=feed.language or el:getText() --licence end end --feed.link (already resolved) for i, link in pairs(feed.links) do if link.rel=='alternate' or not link.rel or link.rel=='' then feed.link=link.href break end end res.entries=parse_entries(root:getChildren('entry'),'atom', root_base) return res end local function parse_rss(root, base_uri) local channel = root:getChild({'channel', 'rdf:channel'}) local channel_base = rebase(channel, base_uri) if not channel then return nil, "can't parse that." end local feed = {links = {}, contributors={}} local res = { feed=feed, format='rss', entries={} } --this isn't quite right at all. if root:getTag():lower()=='rdf:rdf' then res.version='rss10' else res.version='rss20' end for i, el in ipairs(channel:getChildren('*')) do local el_base=rebase(el, channel_base) local tag = el:getTag() if tag=='link' then feed.link=resolve(el:getText(), el_base) tinsert(feed.links, {href=feed.link}) --title elseif tag == 'title' or tag == 'dc:title' then feed.title=el:getText() --sanitize! --subtitle elseif tag == 'description' or tag =='dc:description' or tag=='itunes:subtitle' then feed.subtitle=el:getText() --sanitize! --rights elseif tag == 'copyright' or tag == 'dc:rights' then feed.rights=el:getText() --sanitize! --generator elseif tag == 'generator' then feed.generator=el:getText() elseif tag == 'admin:generatorAgent' then feed.generator = feed.generator or el:getAttr('rdf:resource') --info (nobody cares...) elseif tag == 'feedburner:browserFriendly' then feed.info = el:getText() --updated elseif tag == 'pubDate' or tag == 'dc:date' or tag == 'dcterms:modified' then feed.updated = el:getText() feed.updated_parsed = dateparser.parse(feed.updated) --author elseif tag=='managingEditor' or tag =='dc:creator' or tag=='itunes:author' or tag =='dc:creator' or tag=='dc:author' then feed.author=tconcat(el:getChildren('text()')) feed.author_details={name=feed.author} elseif tag=='atom:author' then feed.author_details = atom_person_construct(el, el_base) feed.author = feed.author_details.name --contributors elseif tag == 'dc:contributor' then tinsert(feed.contributors, {name=el:getText()}) elseif tag == 'atom:contributor' then tinsert(feed.contributors, atom_person_construct(el, el_base)) --image elseif tag=='image' or tag=='rdf:image' then feed.image={ title=el:getChild('title'):getText(), link=(el:getChild('link') or blanky):getText(), width=(el:getChild('width') or blanky):getText(), height=(el:getChild('height') or blanky):getText() } local url_el = el:getChild('url') if url_el then feed.image.href = resolve(url_el:getText(), rebase(url_el, el_base)) end --language elseif tag=='language' or tag=='dc:language' then feed.language=el:getText() --licence --publisher --tags end end res.entries=parse_entries(channel:getChildren('item'),'rss', channel_base) return res end --- parse feed xml -- @param xml_string feed xml, as a string -- @param base_url (optional) source url of the feed. useful when resolving relative links found in feed contents -- @return table with parsed feed info, or nil, error_message on error. -- the format of the returned table is much like that on http://feedparser.org, with the major difference that -- dates are parsed into unixtime. Most other fields are very much the same. function feedparser.parse(xml_string, base_url) local lom, err = LOM.parse(xml_string) if not lom then return nil, "couldn't parse xml. lxp says: " .. err or "nothing" end local rootElement = XMLElement.new(lom) local root_tag = rootElement:getTag():lower() if root_tag=='rdf:rdf' or root_tag=='rss' then return parse_rss(rootElement, base_url) elseif root_tag=='feed' then return parse_atom(rootElement, base_url) else return nil, "unknown feed format" end end --for the sake of backwards-compatibility, feedparser will export a global reference for lua < 5.3 if _VERSION:sub(-3) < "5.3" then _G.feedparser=feedparser end return feedparser
gpl-2.0
TEAMvirus/ViRuS
libs/feedparser.lua
543
11955
local LOM = assert(require("lxp.lom"), "LuaExpat doesn't seem to be installed. feedparser kind of needs it to work...") local XMLElement = (loadfile "./libs/XMLElement.lua")() local dateparser = (loadfile "./libs/dateparser.lua")() local URL = (loadfile "./libs/url.lua")() local tinsert, tremove, tconcat = table.insert, table.remove, table.concat local pairs, ipairs = pairs, ipairs --- feedparser, similar to the Universal Feed Parser for python, but a good deal weaker. -- see http://feedparser.org for details about the Universal Feed Parser local feedparser= { _DESCRIPTION = "RSS and Atom feed parser", _VERSION = "feedparser 0.71" } local blanky = XMLElement.new() --useful in a whole bunch of places local function resolve(url, base_url) return URL.absolute(base_url, url) end local function rebase(el, base_uri) local xml_base = el:getAttr('xml:base') if not xml_base then return base_uri end return resolve(xml_base, base_uri) end local function parse_entries(entries_el, format_str, base) local entries = {} for i, entry_el in ipairs(entries_el) do local entry = {enclosures={}, links={}, contributors={}} local entry_base = rebase(entry_el, base) for i, el in ipairs(entry_el:getChildren('*')) do local tag = el:getTag() local el_base = rebase(el, entry_base) --title if tag == 'title' or tag == 'dc:title' or tag =='rdf:title' then --'dc:title' doesn't occur in atom feeds, but whatever. entry.title=el:getText() --link(s) elseif format_str == 'rss' and tag=='link' then entry.link=resolve(el:getText(), el_base) tinsert(entry.links, {href=entry.link}) elseif (format_str=='atom' and tag == 'link') or (format_str == 'rss' and tag=='atom:link') then local link = {} for i, attr in ipairs{'rel','type', 'href','title'} do link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr) --uri end tinsert(entry.links, link) if link.rel=='enclosure' then tinsert(entry.enclosures, { href=link.href, length=el:getAttr('length'), type=el:getAttr('type') }) end --rss enclosures elseif format_str == 'rss' and tag=='enclosure' then tinsert(entry.enclosures, { url=el:getAttr('url'), length=el:getAttr('length'), type=el:getAttr('type') }) --summary elseif (format_str=='atom' and tag=='summary') or (format_str=='rss' and(tag=='description' or tag=='dc:description' or tag=='rdf:description')) then entry.summary=el:getText() --TODO: summary_detail --content elseif (format_str=='atom' and tag=='content') or (format_str=='rss' and (tag=='body' or tag=='xhtml:body' or tag == 'fullitem' or tag=='content:encoded')) then entry.content=el:getText() --TODO: content_detail --published elseif (format_str == 'atom' and (tag=='published' or tag=='issued')) or (format_str == 'rss' and (tag=='dcterms:issued' or tag=='atom:published' or tag=='atom:issued')) then entry.published = el:getText() entry.published_parsed=dateparser.parse(entry.published) --updated elseif (format_str=='atom' and (tag=='updated' or tag=='modified')) or (format_str=='rss' and (tag=='dc:date' or tag=='pubDate' or tag=='dcterms:modified')) then entry.updated=el:getText() entry.updated_parsed=dateparser.parse(entry.updated) elseif tag=='created' or tag=='atom:created' or tag=='dcterms:created' then entry.created=el:getText() entry.created_parsed=dateparser.parse(entry.created) --id elseif (format_str =='atom' and tag=='id') or (format_str=='rss' and tag=='guid') then entry.id=resolve(el:getText(), el_base) -- this is a uri, right?... --author elseif format_str=='rss' and (tag=='author' or tag=='dc:creator') then --author tag should give the author's email. should I respect this? entry.author=(el:getChild('name') or el):getText() entry.author_detail={ name=entry.author } elseif format_str=='atom' and tag=='author' then entry.author=(el:getChild('name') or el):getText() entry.author_detail = { name=entry.author, email=(el:getChild('email') or blanky):getText() } local author_url = (el:getChild('url') or blanky):getText() if author_url and author_url ~= "" then entry.author_detail.href=resolve(author_url, rebase(el:getChild('url'), el_base)) end elseif tag=='category' or tag=='dc:subject' then --todo elseif tag=='source' then --todo end end --wrap up rss guid if format_str == 'rss' and (not entry.id) and entry_el:getAttr('rdf:about') then entry.id=resolve(entry_el:getAttr('rdf:about'), entry_base) --uri end --wrap up entry.link for i, link in pairs(entry.links) do if link.rel=="alternate" or (not link.rel) or link.rel=="" then entry.link=link.href --already resolved. break end end if not entry.link and format_str=='rss' then entry.link=entry.id end tinsert(entries, entry) end return entries end local function atom_person_construct(person_el, base_uri) local dude ={ name= (person_el:getChild('name') or blanky):getText(), email=(person_el:getChild('email') or blanky):getText() } local url_el = person_el:getChild('url') if url_el then dude.href=resolve(url_el:getText(), rebase(url_el, base_uri)) end return dude end local function parse_atom(root, base_uri) local res = {} local feed = { links = {}, contributors={}, language = root:getAttr('lang') or root:getAttr('xml:lang') } local root_base = rebase(root, base_uri) res.feed=feed res.format='atom' local version=(root:getAttr('version') or ''):lower() if version=="1.0" or root:getAttr('xmlns')=='http://www.w3.org/2005/Atom' then res.version='atom10' elseif version=="0.3" then res.version='atom03' else res.version='atom' end for i, el in ipairs(root:getChildren('*')) do local tag = el:getTag() local el_base=rebase(el, root_base) if tag == 'title' or tag == 'dc:title' or tag == 'atom10:title' or tag == 'atom03:title' then feed.title=el:getText() --sanitize! --todo: feed.title_detail --link stuff elseif tag=='link' then local link = {} for i, attr in ipairs{'rel','type', 'href','title'} do link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr) end tinsert(feed.links, link) --subtitle elseif tag == 'subtitle' then feed.subtitle=el:getText() --sanitize! elseif not feed.subtitle and (tag == 'tagline' or tag =='atom03:tagline' or tag=='dc:description') then feed.subtitle=el:getText() --sanitize! --rights elseif tag == 'copyright' or tag == 'rights' then feed.rights=el:getText() --sanitize! --generator elseif tag == 'generator' then feed.generator=el:getText() --sanitize! elseif tag == 'admin:generatorAgent' then feed.generator = feed.generator or el:getAttr('rdf:resource') --info elseif tag == 'info' then --whatever, nobody cared, anyway. feed.info = el:getText() --id elseif tag=='id' then feed.id=resolve(el:getText(), el_base) --this is a url, right?.,, --updated elseif tag == 'updated' or tag == 'dc:date' or tag == 'modified' or tag=='rss:pubDate' then feed.updated = el:getText() feed.updated_parsed=dateparser.parse(feed.updated) --author elseif tag=='author' or tag=='atom:author' then feed.author_detail=atom_person_construct(el, el_base) feed.author=feed.author_detail.name --contributors elseif tag=='contributor' or tag=='atom:contributor' then tinsert(feed.contributors, atom_person_construct(el, el_base)) --icon elseif tag=='icon' then feed.icon=resolve(el:getText(), el_base) --logo elseif tag=='logo' then feed.logo=resolve(el:getText(), el_base) --language elseif tag=='language' or tag=='dc:language' then feed.language=feed.language or el:getText() --licence end end --feed.link (already resolved) for i, link in pairs(feed.links) do if link.rel=='alternate' or not link.rel or link.rel=='' then feed.link=link.href break end end res.entries=parse_entries(root:getChildren('entry'),'atom', root_base) return res end local function parse_rss(root, base_uri) local channel = root:getChild({'channel', 'rdf:channel'}) local channel_base = rebase(channel, base_uri) if not channel then return nil, "can't parse that." end local feed = {links = {}, contributors={}} local res = { feed=feed, format='rss', entries={} } --this isn't quite right at all. if root:getTag():lower()=='rdf:rdf' then res.version='rss10' else res.version='rss20' end for i, el in ipairs(channel:getChildren('*')) do local el_base=rebase(el, channel_base) local tag = el:getTag() if tag=='link' then feed.link=resolve(el:getText(), el_base) tinsert(feed.links, {href=feed.link}) --title elseif tag == 'title' or tag == 'dc:title' then feed.title=el:getText() --sanitize! --subtitle elseif tag == 'description' or tag =='dc:description' or tag=='itunes:subtitle' then feed.subtitle=el:getText() --sanitize! --rights elseif tag == 'copyright' or tag == 'dc:rights' then feed.rights=el:getText() --sanitize! --generator elseif tag == 'generator' then feed.generator=el:getText() elseif tag == 'admin:generatorAgent' then feed.generator = feed.generator or el:getAttr('rdf:resource') --info (nobody cares...) elseif tag == 'feedburner:browserFriendly' then feed.info = el:getText() --updated elseif tag == 'pubDate' or tag == 'dc:date' or tag == 'dcterms:modified' then feed.updated = el:getText() feed.updated_parsed = dateparser.parse(feed.updated) --author elseif tag=='managingEditor' or tag =='dc:creator' or tag=='itunes:author' or tag =='dc:creator' or tag=='dc:author' then feed.author=tconcat(el:getChildren('text()')) feed.author_details={name=feed.author} elseif tag=='atom:author' then feed.author_details = atom_person_construct(el, el_base) feed.author = feed.author_details.name --contributors elseif tag == 'dc:contributor' then tinsert(feed.contributors, {name=el:getText()}) elseif tag == 'atom:contributor' then tinsert(feed.contributors, atom_person_construct(el, el_base)) --image elseif tag=='image' or tag=='rdf:image' then feed.image={ title=el:getChild('title'):getText(), link=(el:getChild('link') or blanky):getText(), width=(el:getChild('width') or blanky):getText(), height=(el:getChild('height') or blanky):getText() } local url_el = el:getChild('url') if url_el then feed.image.href = resolve(url_el:getText(), rebase(url_el, el_base)) end --language elseif tag=='language' or tag=='dc:language' then feed.language=el:getText() --licence --publisher --tags end end res.entries=parse_entries(channel:getChildren('item'),'rss', channel_base) return res end --- parse feed xml -- @param xml_string feed xml, as a string -- @param base_url (optional) source url of the feed. useful when resolving relative links found in feed contents -- @return table with parsed feed info, or nil, error_message on error. -- the format of the returned table is much like that on http://feedparser.org, with the major difference that -- dates are parsed into unixtime. Most other fields are very much the same. function feedparser.parse(xml_string, base_url) local lom, err = LOM.parse(xml_string) if not lom then return nil, "couldn't parse xml. lxp says: " .. err or "nothing" end local rootElement = XMLElement.new(lom) local root_tag = rootElement:getTag():lower() if root_tag=='rdf:rdf' or root_tag=='rss' then return parse_rss(rootElement, base_url) elseif root_tag=='feed' then return parse_atom(rootElement, base_url) else return nil, "unknown feed format" end end --for the sake of backwards-compatibility, feedparser will export a global reference for lua < 5.3 if _VERSION:sub(-3) < "5.3" then _G.feedparser=feedparser end return feedparser
gpl-2.0
dail8859/LuaScript
examples/SessionManager.lua
1
6312
-- A very simplistic session manager. It opens previously open files and restores -- cursor position and scroll position. It is not perfect, for example it does -- not keep track of the order or in which view the files are in. This code must -- be ran during startup. This is just a demonstration of how to use the API -- and what can be done in a small amount of Lua. local opened_files = {} local is_shutting_down = false -- If a session is found, load it. Note this cannot be done directly during -- startup since N++ hasn't completely initialized yet. npp.AddEventHandler("OnReady", function() local files = table.load(npp:GetPluginsConfigDir() .. "\\session.lua") if files ~= nil then for i,v in pairs(files) do npp:DoOpen(v.name) if v.lang then npp.BufferLangType[npp.CurrentBufferID] = v.lang end editor.FirstVisibleLine = v.top or 0 editor.CurrentPos = v.pos or 0 editor.Anchor = v.anchor or 0 end end return false end) -- Remove any files that are closed npp.AddEventHandler("OnClose", function(f,i) -- If N++ is in the middle of shutting down, just ignore it if is_shutting_down then return false end opened_files[i] = nil return false end) -- This won't be called unless the user manually changes it, else it just -- defaults to whatever value N++ decides is best npp.AddEventHandler("OnLangChange", function() local i = npp.CurrentBufferID opened_files[i].lang = npp.BufferLangType[i] end) -- Keep track of some of the variables we want to restore in the file -- This event will also catch any files being opened for the first time npp.AddEventHandler("OnUpdateUI", function() local i = npp.CurrentBufferID if opened_files[i] == nil then opened_files[i] = {} opened_files[i].name = npp:GetFullCurrentPath() end opened_files[i].pos = editor.CurrentPos opened_files[i].anchor = editor.Anchor opened_files[i].top = editor.FirstVisibleLine return false end) npp.AddEventHandler("OnFileRenamed", function(f,i) opened_files[i].name = f -- update the name return false end) -- Set a flag so we know N++ is shutting down npp.AddEventHandler("OnBeforeShutdown", function() is_shutting_down = true return false end) -- The user could cancel the shutdown npp.AddEventHandler("OnCancelShutdown", function() is_shutting_down = false return false end) -- If it is actually shutting down, save the session file npp.AddEventHandler("OnShutdown", function() -- Remove any dummy files, e.g. "new 1" for id, tab in pairs(opened_files) do if tab.name:find("^new %d+$") ~= nil then opened_files[id] = nil end end table.save(opened_files, npp:GetPluginsConfigDir() .. "\\session.lua") return false end) -- These below are merely helper fuctions to serialize tables. They were found -- laying around on the Internet somewhere and worked for this case. function table.save(tbl,filename ) local function exportstring( s ) return string.format("%q", s) end local charS,charE = "\t","\n" local file,err = io.open( filename, "wb" ) if err then return err end -- initiate variables for save procedure local tables,lookup = { tbl },{ [tbl] = 1 } file:write( "return {"..charE ) for idx,t in ipairs( tables ) do file:write( "-- Table: {"..idx.."}"..charE ) file:write( "{"..charE ) local thandled = {} for i,v in ipairs( t ) do thandled[i] = true local stype = type( v ) -- only handle value if stype == "table" then if not lookup[v] then table.insert( tables, v ) lookup[v] = #tables end file:write( charS.."{"..lookup[v].."},"..charE ) elseif stype == "string" then file:write( charS..exportstring( v )..","..charE ) elseif stype == "number" then file:write( charS..tostring( v )..","..charE ) end end for i,v in pairs( t ) do -- escape handled values if (not thandled[i]) then local str = "" local stype = type( i ) -- handle index if stype == "table" then if not lookup[i] then table.insert( tables,i ) lookup[i] = #tables end str = charS.."[{"..lookup[i].."}]=" elseif stype == "string" then str = charS.."["..exportstring( i ).."]=" elseif stype == "number" then str = charS.."["..tostring( i ).."]=" end if str ~= "" then stype = type( v ) -- handle value if stype == "table" then if not lookup[v] then table.insert( tables,v ) lookup[v] = #tables end file:write( str.."{"..lookup[v].."},"..charE ) elseif stype == "string" then file:write( str..exportstring( v )..","..charE ) elseif stype == "number" then file:write( str..tostring( v )..","..charE ) end end end end file:write( "},"..charE ) end file:write( "}" ) file:close() end function table.load( sfile ) local ftables,err = loadfile( sfile ) if err then return _,err end local tables = ftables() for idx = 1,#tables do local tolinki = {} for i,v in pairs( tables[idx] ) do if type( v ) == "table" then tables[idx][i] = tables[v[1]] end if type( i ) == "table" and tables[i[1]] then table.insert( tolinki,{ i,tables[i[1]] } ) end end -- link indices for _,v in ipairs( tolinki ) do tables[idx][v[2]],tables[idx][v[1]] = tables[idx][v[1]],nil end end return tables[1] end
gpl-2.0
dinodeck/ninety_nine_days_of_dev
003_combat_numbers/code/StatusMenuState.lua
1
4151
StatusMenuState = {} StatusMenuState.__index = StatusMenuState function StatusMenuState:Create(parent, world) local layout = Layout:Create() layout:Contract('screen', 118, 40) layout:SplitHorz('screen', "title", "bottom", 0.12, 2) local this = { mParent = parent, mStateMachine = parent.mStateMachine, mStack = parent.mStack, mLayout = layout, mPanels = { layout:CreatePanel("title"), layout:CreatePanel("bottom"), }, } setmetatable(this, self) return this end function StatusMenuState:Enter(actor) self.mActor = actor self.mActorSummary = ActorSummary:Create(actor, { showXP = true}) self.mEquipMenu = Selection:Create { data = self.mActor.mActiveEquipSlots, columns = 1, rows = #self.mActor.mActiveEquipSlots, spacingY = 26, RenderItem = function(...) self.mActor:RenderEquipment(...) end } self.mEquipMenu:HideCursor() self.mActions = Selection:Create { data = self.mActor.mActions, columns = 1, rows = #self.mActor.mActions, spacingY = 18, RenderItem = function(self, renderer, x, y, item) local label = Actor.ActionLabels[item] renderer:ScaleText(1,1) Selection.RenderItem(self, renderer, x, y, label) end } self.mActions:HideCursor() end function StatusMenuState:Exit() end function StatusMenuState:Update(dt) if Keyboard.JustReleased(KEY_BACKSPACE) or Keyboard.JustReleased(KEY_ESCAPE) then self.mStateMachine:Change("frontmenu") end end function StatusMenuState:DrawStat(renderer, x, y, label, value) renderer:AlignText("right", "center") renderer:DrawText2d(x -5, y, label) gGame.Font.default:AlignText(renderer, "left", "center") gGame.Font.default:DrawText2d(renderer, x + 5, y + 3, tostring(value)) end function StatusMenuState:Render(renderer) local font = gGame.Font.default for k,v in ipairs(self.mPanels) do v:Render(renderer) end local titleX = self.mLayout:MidX("title") local titleY = self.mLayout:MidY("title") renderer:ScaleText(1.5, 1.5) renderer:AlignText("center", "center") renderer:DrawText2d(titleX, titleY, "Status") local left = self.mLayout:Left("bottom") + 10 local top = self.mLayout:Top("bottom") - 10 self.mActorSummary:SetPosition(left , top) self.mActorSummary:Render(renderer) renderer:AlignText("right", "top") renderer:DrawText2d(left + 258, top-58,"XP:") local xpStr = string.format("%d/%d", self.mActor.mXP, self.mActor.mNextLevelXP) font:AlignText(renderer, "left", "top") font:DrawText2d(renderer, left + 264, top - 58, xpStr) self.mEquipMenu:SetPosition(-10, -64) self.mEquipMenu:Render(renderer) local stats = self.mActor.mStats local x = left + 106 local y = 0 for k, v in ipairs(Actor.ActorStats) do local label = Actor.ActorStatLabels[k] self:DrawStat(renderer, x, y, label, stats:Get(v)) y = y - 16 end y = y - 16 for k, v in ipairs(Actor.ItemStats) do local label = Actor.ItemStatLabels[k] self:DrawStat(renderer, x, y, label, stats:Get(v)) y = y - 16 end renderer:AlignText("left", "top") local x = 80 local y = 36 local w = 100 local h = 84 -- this should be a panel - duh! local box = Textbox:Create { text = {""}, textScale = 1.5, size = { left = x, right = x + w, top = y, bottom = y - h, }, textbounds = { left = 10, right = -10, top = -10, bottom = 10 }, panelArgs = { texture = Texture.Find("gradient_panel.png"), size = 3, }, } box.mAppearTween = Tween:Create(1,1,0) box:Render(renderer) self.mActions:SetPosition(x - 14, y - 10) self.mActions:Render(renderer) end
mit
DGA-MI-SSI/YaCo
deps/swig-3.0.7/Examples/lua/embed3/runme.lua
6
1091
print "[lua] This is runme.lua" -- test program for embedded lua -- we do not need to load the library, as it was already in the interpreter -- but let's check anyway assert(type(example)=='table',"Don't appear to have loaded the example module. Do not run this file directly, run the embed3 executable") print "[lua] looking to see if we have a pointer to the engine" if type(pEngine)=="userdata" then print "[lua] looks good" else print "[lua] nope, no signs of it" end -- the embedded program expects a function void onEvent(Event) -- this is it function onEvent(e) print("[Lua] onEvent with event",e.mType) -- let's do something with the Engine -- nothing clever, but ... if e.mType==example.Event_STARTUP then pEngine:start() elseif e.mType==example.Event_KEYPRESS then pEngine:accelerate(0.4) elseif e.mType==example.Event_MOUSEPRESS then pEngine:decelerate(0.4) elseif e.mType==example.Event_SHUTDOWN then pEngine:stop() else error("unknown event type") end print("[Lua] ending onEvent") end
gpl-3.0
neofob/sile
packages/pullquote.lua
1
3614
SILE.require("packages/color") SILE.require("packages/raiselower") SILE.require("packages/rebox") SILE.registerCommand("pullquote:font", function (options, content) end, "The font chosen for the pullquote environment") SILE.registerCommand("pullquote:author-font", function (options, content) SILE.settings.set("font.style", "italic") end, "The font style with which to typeset the author attribution.") SILE.registerCommand("pullquote:mark-font", function (options, content) SILE.settings.set("font.family", "Linux Libertine O") end, "The font from which to pull the quotation marks.") local typesetMark = function (open, setback, scale, color, mark) SILE.settings.temporarily(function () SILE.call("pullquote:mark-font") local setwidth = SILE.length.new({ length = SILE.toPoints(setback) }) SILE.typesetter:pushGlue({ width = open and 0-setwidth or setwidth }) SILE.call("raise", { height = -(open and (scale+1) or scale) .. "ex" }, function () SILE.settings.set("font.size", SILE.settings.get("font.size")*scale) SILE.call("color", { color = color }, function () SILE.call("rebox", { width = 0, height = 0 }, { mark }) end) end) SILE.typesetter:pushGlue({width = open and setwidth or 0-setwidth }) end) end SILE.registerCommand("pullquote", function (options, content) local author = options.author or nil local setback = options.setback or "2em" local scale = options.scale or 3 local color = options.color or "#999999" SILE.settings.temporarily(function () SILE.settings.set("document.rskip", SILE.nodefactory.newGlue(setback)) SILE.settings.set("document.lskip", SILE.nodefactory.newGlue(setback)) SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) SILE.call("pullquote:font") typesetMark(true, setback, scale, color, "“") SILE.process(content) SILE.typesetter:pushGlue(SILE.nodefactory.hfillGlue) typesetMark(false, setback, scale, color, "”") if author then SILE.settings.temporarily(function () SILE.typesetter:leaveHmode() SILE.call("pullquote:author-font") SILE.call("raggedleft", {}, function () SILE.typesetter:typeset("— " .. author) end) end) else SILE.call("par") end end) end, "Typesets its contents in a formatted blockquote with decorative quotation\ marks in the margins.") return { documentation = [[\begin{document} The \code{pullquote} command formats longer quotations in an indented blockquote block with decorative quotation marks in the margins. Here is some text set in a pullquote environment: \begin[author=Anatole France]{pullquote} An education is not how much you have committed to memory, or even how much you know. It is being able to differentiate between what you do know and what you do not know. \end{pullquote} Optional values are available for: \listitem \code{author} to add an attribution line \listitem \code{setback} to set the bilateral margins around the block \listitem \code{color} to change the color of the quote marks \listitem \code{scale} to change the relative size of the quote marks If you want to specify what font the pullquote environment should use, you can redefine the \code{pullquote:font} command. By default it will be the same as the surrounding document. The font style used for the attribution line can likewise be set using \code{pullquote:author-font} and the font used for the quote marks can be set using \code{pullquote:mark-font}. \end{document}]] }
mit
Ninjistix/darkstar
scripts/zones/RuLude_Gardens/npcs/Dabih_Jajalioh.lua
5
1098
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: Dabih Jajalioh -- Standard Merchant NPC -- Additional script for pereodical -- goods needed. -- Partitially implemented. ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:showText(npc,DABIHJAJALIOH_SHOP_DIALOG); local stock = { 0x03b4,60, --Carnation 0x027c,119, --Chamomile 0x03be,120, --Marguerite 0x03b5,96, --Rain Lily 0x03ad,80, --Red Rose 0x03b7,110} --Wijnruit -- Place for difficult script showShop(player, STATIC, stock); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/items/fire_sword.lua
7
1033
----------------------------------------- -- ID: 16543 -- Item: Fire Sword -- Additional Effect: Fire Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(3,10); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0); dmg = adjustForTarget(target,dmg,ELE_FIRE); dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg); local message = msgBasic.ADD_EFFECT_DMG; if (dmg < 0) then message = msgBasic.ADD_EFFECT_HEAL; end return SUBEFFECT_FIRE_DAMAGE,message,dmg; end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Horlais_Peak/bcnms/dropping_like_flies.lua
5
1739
----------------------------------- -- Area: Horlias peak -- Name: Dropping Like Flies -- BCNM30 ----------------------------------- package.loaded["scripts/zones/Horlais_Peak/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Horlais_Peak/TextIDs"); ----------------------------------- -- EXAMPLE SCRIPT -- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:startEvent(32001,1,1,1,instance:getTimeInside(),1,10,0); elseif (leavecode == 4) then player:startEvent(32002); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Promyvion-Vahzl/npcs/_0m0.lua
7
1056
----------------------------------- -- Area: Promyvion vahzl -- NPC: Memory flux (3) ----------------------------------- package.loaded["scripts/zones/Promyvion-Vahzl/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Promyvion-Vahzl/TextIDs"); require("scripts/zones/Promyvion-Vahzl/MobIDs"); require("scripts/globals/missions"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==5 and not GetMobByID(PONDERER):isSpawned()) then SpawnMob(PONDERER):updateClaim(player); elseif (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==6) then player:startEvent(53); else player:messageSpecial(OVERFLOWING_MEMORIES); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 53) then player:setVar("PromathiaStatus",7); end end;
gpl-3.0
abbasgh12345/extremenew
plugins/owners.lua
1467
12478
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/logs/"..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
bluetomatoes/ExploreTimelines
CodeSamples/SnapShapes 2/SnapShapes_START/dmc_multitouch.lua
3
31111
--===================================================================-- -- dmc_multitouch.lua -- -- by David McCuskey -- Documentation: http://docs.davidmccuskey.com/display/docs/dmc_multitouch.lua --===================================================================-- --[[ Copyright (C) 2012 David McCuskey. All Rights Reserved. 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. --]] -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.3.0" --===================================================================-- -- Imports --===================================================================-- local TouchMgr = require( "dmc_touchmanager" ) --local Utils = require( "dmc_utils" ) --===================================================================-- -- Setup, Constants --===================================================================-- local MULTITOUCH_EVENT = "multitouch_event" local DEBUG = true local debugObjs = {} --===================================================================-- -- Triggr Class --===================================================================-- local Triggr = {} function Triggr:new() local o = {} local mt = { __index = Triggr } setmetatable( o, mt ) --== Set Properties ==-- o:reset() return o end function Triggr:reset() --print( "Triggr:reset" ) self.quad = 0 -- 1,2,3,4 self.quad_cnt = 0 -- +/- num self.direction = 0 -- -1, 0, 1 self.stateFunc = nil -- func to current state self.ang_base = 0 -- original angle self.ang_delta_base = 0 -- -ang/+ang self.ang_delta = 0 -- -ang/+ang self.ang_delta_sum = 0 -- -ang/+ang self.angle_sum = 0 -- -ang/+ang end function Triggr:start( x, y ) local ang self:reset() self.quad, self.ang_base = self:_getQuad( x, y ) if self.quad == 1 then self.stateFunc = self._quad_I elseif self.quad == 2 then self.stateFunc = self._quad_II elseif self.quad == 3 then self.stateFunc = self._quad_III elseif self.quad == 4 then self.stateFunc = self._quad_IV end end function Triggr:set( x, y ) local new_quad, refang = self:_getQuad( x, y ) self:stateFunc( new_quad, refang ) self.angle_sum = self.ang_delta_base + self.ang_delta_sum + self.ang_delta --print( new_quad, Triggr.direction, Triggr.quad_cnt ) --print( new_quad, Triggr.quad_cnt, ( Triggr.ang_delta_base + Triggr.ang_delta + Triggr.ang_delta_sum ), Triggr.ang_delta, Triggr.ang_delta_sum ) end --== Private Methods ==-- function Triggr:_getQuad( x, y ) --print( "Triggr:_getQuad", x, y ) local q, ang, refang ang = math.deg( math.atan2( y, x ) ) if x >= 0 and y >= 0 then q = 1 refang = ang elseif x < 0 and y >= 0 then q = 2 refang = 180 - ang elseif x < 0 and y < 0 then q = 3 --refang = ang - 180 refang = 180 + ang elseif x >= 0 and y < 0 then q = 4 --refang = 360 - ang refang = -ang end return q, refang end function Triggr:_quad_I( new_quad, refang ) local curr_quad = self.quad local curr_quad_cnt = self.quad_cnt local ang_base = self.ang_base -- back, negative if new_quad == 2 then self.quad_cnt = self.quad_cnt - 1 if curr_quad_cnt == 0 then self.ang_delta_base = self.ang_base - 90 self.ang_delta = 0 self.ang_delta_sum = 0 else self.ang_delta = 0 -- !!!!!!!!!!!!!!!!!!! if self.quad_cnt == 0 then self.ang_delta_sum = 0 else self.ang_delta_sum = self.direction * ( math.abs( self.quad_cnt ) - 1 ) * 90 end end --print( "I > II : ", math.abs( self.quad_cnt ), self.ang_delta_base, self.ang_delta_sum ) self.quad = new_quad self.stateFunc = self._quad_II self:stateFunc( new_quad, refang ) -- forward, positive elseif new_quad == 4 then self.quad_cnt = self.quad_cnt + 1 if curr_quad_cnt == 0 then self.ang_delta_base = self.ang_base self.ang_delta = 0 self.ang_delta_sum = 0 else if self.quad_cnt == 0 then self.ang_delta_sum = 0 else self.ang_delta_sum = self.direction * ( math.abs( self.quad_cnt ) - 1 ) * 90 end end --print( "I > IV : ", math.abs( self.quad_cnt ), self.ang_delta_base, self.ang_delta_sum ) self.quad = new_quad self.stateFunc = self._quad_IV self:stateFunc( new_quad, refang ) -- cross, positive elseif new_quad == 3 then -- current quadrant else -- we started here if curr_quad_cnt == 0 then self.ang_delta_base = 0 if refang > ang_base then self.direction = -1 self.ang_delta = self.ang_base - refang elseif refang < ang_base then self.direction = 1 self.ang_delta = self.ang_base - refang else self.direction = 0 self.ang_delta = 0 end else -- TODO -- back, negative if self.direction == -1 then self.ang_delta = -refang -- forward, positive elseif self.direction == 1 then -- TODO self.ang_delta = 90 - refang end end end end function Triggr:_quad_II( new_quad, refang ) local curr_quad = self.quad local curr_quad_cnt = self.quad_cnt local ang_base = self.ang_base local quad_multiple -- back, negative if new_quad == 3 then self.quad_cnt = self.quad_cnt - 1 if curr_quad_cnt == 0 then self.ang_delta_base = -self.ang_base self.ang_delta = 0 self.ang_delta_sum = 0 else self.ang_delta = 0 if self.quad_cnt == 0 then self.ang_delta_sum = 0 else self.ang_delta_sum = self.direction * ( math.abs( self.quad_cnt ) - 1 ) * 90 end end --print( "II > III : ", math.abs( self.quad_cnt ), self.ang_delta_base, self.ang_delta_sum ) self.quad = new_quad self.stateFunc = self._quad_III self:stateFunc( new_quad, refang ) -- forward, positive elseif new_quad == 1 then self.quad_cnt = self.quad_cnt + 1 if curr_quad_cnt == 0 then self.ang_delta_base = 90 - self.ang_base self.ang_delta = 0 self.ang_delta_sum = 0 else self.ang_delta = 0 if self.quad_cnt == 0 then self.ang_delta_sum = 0 else self.ang_delta_sum = self.direction * ( math.abs( self.quad_cnt ) - 1 ) * 90 end end --print( "II > I : ", math.abs( self.quad_cnt ), self.ang_delta_base, self.ang_delta_sum ) self.quad = new_quad self.stateFunc = self._quad_I self:stateFunc( new_quad, refang ) -- cross, positive elseif new_quad == 4 then -- current quadrant else -- we started here if curr_quad_cnt == 0 then self.ang_delta_base = 0 if refang < ang_base then self.direction = -1 self.ang_delta = -( self.ang_base - refang ) elseif refang > ang_base then self.direction = 1 self.ang_delta = -( self.ang_base - refang ) else self.direction = 0 self.ang_delta = 0 end else -- back, negative if self.direction == -1 then self.ang_delta = refang - 90 -- forward, positive elseif self.direction == 1 then self.ang_delta = refang end end end end function Triggr:_quad_III( new_quad, refang ) local curr_quad = self.quad local curr_quad_cnt = self.quad_cnt local ang_base = self.ang_base -- back, negative if new_quad == 4 then self.quad_cnt = self.quad_cnt - 1 if curr_quad_cnt == 0 then self.ang_delta_base = self.ang_base - 90 self.ang_delta = 0 self.ang_delta_sum = 0 else if self.quad_cnt == 0 then self.ang_delta_sum = 0 else self.ang_delta_sum = self.direction * ( math.abs( self.quad_cnt ) - 1 ) * 90 end end --print( "III > IV : ", math.abs( self.quad_cnt ), self.ang_delta_base, self.ang_delta_sum ) self.quad = new_quad self.stateFunc = self._quad_IV self:stateFunc( new_quad, refang ) -- forward, positive elseif new_quad == 2 then self.quad_cnt = self.quad_cnt + 1 if curr_quad_cnt == 0 then self.ang_delta_base = self.ang_base self.ang_delta = 0 self.ang_delta_sum = 0 else if self.quad_cnt == 0 then self.ang_delta_sum = 0 else self.ang_delta_sum = self.direction * ( math.abs( self.quad_cnt ) - 1 ) * 90 end end --print( "III > II : ", math.abs( self.quad_cnt ), self.ang_delta_base, self.ang_delta_sum ) self.quad = new_quad self.stateFunc = self._quad_II self:stateFunc( new_quad, refang ) -- cross, positive elseif new_quad == 1 then -- current quadrant else -- we started here if curr_quad_cnt == 0 then self.ang_delta_base = 0 if refang > ang_base then self.direction = -1 self.ang_delta = self.ang_base - refang elseif refang < ang_base then self.direction = 1 self.ang_delta = self.ang_base - refang else self.direction = 0 self.ang_delta = 0 end else -- back, negative if self.direction == -1 then self.ang_delta = -refang -- forward, positive elseif self.direction == 1 then -- TODO self.ang_delta = 90 - refang end end end end function Triggr:_quad_IV( new_quad, refang ) local curr_quad = self.quad local curr_quad_cnt = self.quad_cnt local ang_base = self.ang_base -- back, negative if new_quad == 1 then self.quad_cnt = self.quad_cnt - 1 if curr_quad_cnt == 0 then self.ang_delta_base = self.ang_base - 90 self.ang_delta = 0 self.ang_delta_sum = 0 else if self.quad_cnt == 0 then self.ang_delta_sum = 0 else self.ang_delta_sum = self.direction * ( math.abs( self.quad_cnt ) - 1 ) * 90 end end --print( "IV > I : ", math.abs( self.quad_cnt ), self.ang_delta_base, self.ang_delta_sum ) self.quad = new_quad self.stateFunc = self._quad_I self:stateFunc( new_quad, refang ) -- forward, positive elseif new_quad == 3 then self.quad_cnt = self.quad_cnt + 1 if curr_quad_cnt == 0 then -- TODO self.ang_delta_base = 90 - self.ang_base self.ang_delta = 0 self.ang_delta_sum = 0 else if self.quad_cnt == 0 then self.ang_delta_sum = 0 else self.ang_delta_sum = self.direction * ( math.abs( self.quad_cnt ) - 1 ) * 90 end end --print( "IV > III : ", math.abs( self.quad_cnt ), self.ang_delta_base, self.ang_delta_sum ) self.quad = new_quad self.stateFunc = self._quad_III self:stateFunc( new_quad, refang ) -- cross, positive elseif new_quad == 2 then -- current quadrant else -- we started here if curr_quad_cnt == 0 then self.ang_delta_base = 0 if refang < ang_base then self.direction = -1 self.ang_delta = -( self.ang_base - refang ) elseif refang > ang_base then self.direction = 1 self.ang_delta = -( self.ang_base - refang ) else self.direction = 0 self.ang_delta = 0 end else -- back, negative if self.direction == -1 then self.ang_delta = refang - 90 -- forward, positive elseif self.direction == 1 then self.ang_delta = refang end end end end --===================================================================-- -- Support Functions --===================================================================-- if DEBUG then local obj -- blue spot over center of main object obj = display.newRect( 0, 0, 16, 16 ) obj:setFillColor(0,0,255) obj:toFront() debugObjs["objCenter"] = obj -- green spot over midpoint center obj = display.newRect( 0, 0, 10, 10 ) obj:setFillColor(0,255,0) obj:toFront() debugObjs["touchCenter"] = obj -- red spot over calculated center obj = display.newRect( 0, 0, 10, 10 ) obj:setFillColor(255,0,0) obj:toFront() debugObjs["calcCenter"] = obj end -- angle in degrees function y_given_x_angle( x, angle ) --print( "y_given_x_angle" ) -- use negative angle to compensate for difference -- in trig angles and Corona angles return x * math.tan( math.rad( - angle ) ) end -- angle in degrees function x_given_y_angle( y, angle ) --print( "y_given_x_angle" ) -- use negative angle to compensate for difference -- in trig angles and Corona angles return y / math.tan( math.rad( - angle ) ) end function checkBounds( value, bounds ) local v = value if bounds[1] ~= nil and v < bounds[1] then v = bounds[1] elseif bounds[2] ~= nil and v > bounds[2] then v = bounds[2] end return v end -- createConstrainMoveFunc() -- -- create function closure use to constrain movement -- returns function to call -- functions return : -- ( xPos, yPos ) -- function createConstrainMoveFunc( dmc, params ) local p = params or {} local f local SIN_45DEG = 0.707 local xB = p.xBounds local yB = p.yBounds local cA = p.constrainAngle local sin_cA if cA then sin_cA = math.sin( math.rad( cA ) ) end if cA and xB then f = function( xPos, yPos ) local xDelta, yDelta xPos = checkBounds( xPos, xB ) xDelta = xPos - dmc.xOrig yDelta = y_given_x_angle( xDelta, cA ) yPos = yDelta + dmc.yOrig return xPos, yPos end elseif cA and yB then f = function( xPos, yPos ) local xDelta, yDelta yPos = checkBounds( yPos, yB ) yDelta = yPos - dmc.yOrig xDelta = x_given_y_angle( yDelta, cA ) xPos = xDelta + dmc.xOrig return xPos, yPos end elseif cA and sin_cA <= SIN_45DEG then f = function( xPos, yPos ) local xDelta, yDelta xDelta = xPos - dmc.xOrig yDelta = y_given_x_angle( xDelta, cA ) yPos = yDelta + dmc.yOrig return xPos, yPos end elseif cA and sin_cA > SIN_45DEG then f = function( xPos, yPos ) local xDelta, yDelta yDelta = yPos - dmc.yOrig xDelta = x_given_y_angle( yDelta, cA ) xPos = xDelta + dmc.xOrig return xPos, yPos end elseif xB and yB then f = function( xPos, yPos ) xPos = checkBounds( xPos, xB ) yPos = checkBounds( yPos, yB ) return xPos, yPos end elseif xB then f = function( xPos, yPos ) xPos = checkBounds( xPos, xB ) return xPos, yPos end elseif yB then f = function( xPos, yPos ) yPos = checkBounds( yPos, yB ) return xPos, yPos end elseif not xB and not yB and not cA then f = function( xPos, yPos ) return xPos, yPos end else print( "ERROR: you can't do that" ) end return f end -- createConstrainScaleFunc() -- -- create function closure use to constrain scaling -- returns function to call -- functions return either: -- ( "MIN", value ) -- if under minimum, and min value -- ( "MAX", value ) -- if over maximum, and max value -- nil -- if value passes -- function createConstrainScaleFunc( params ) local p = params or {} local f if p.maxScale and p.minScale then f = function( value ) if value < p.minScale then return "MIN", p.minScale elseif value > p.maxScale then return "MAX", p.maxScale end return nil end elseif p.minScale then f = function( value ) if value < p.minScale then return "MIN", p.minScale end return nil end elseif p.maxScale then f = function( value ) if value > p.maxScale then return "MAX", p.maxScale end return nil end else f = function( value ) return nil end end return f end -- createConstrainScaleFunc() -- -- create function closure use to constrain scaling -- returns function to call -- functions return either: -- ( "MIN", value ) -- if under minimum, and min value -- ( "MAX", value ) -- if over maximum, and max value -- nil -- if value passes -- function createConstrainRotateFunc( params ) local p = params or {} local f if p.maxAngle and p.minAngle then f = function( value ) if value < p.minAngle then return "MIN", p.minAngle elseif value > p.maxAngle then return "MAX", p.maxAngle end return nil end elseif p.minAngle then f = function( value ) if value < p.minAngle then return "MIN", p.minAngle end return nil end elseif p.maxAngle then f = function( value ) if value > p.maxAngle then return "MAX", p.maxAngle end return nil end else f = function( value ) return nil end end return f end local function getSingleCalcFunc( obj ) --print( "getSingleCalcFunc" ) local dmc = obj.__dmc.multitouch --print( "<<<<<<<<<< calculateDelta" ) local touches = dmc.touches local touchStack = dmc.touchStack local action local t1 = touches[ touchStack[1] ] local diff = { x=t1.x-obj.x, y=t1.y-obj.y } return function() local mid t1 = touches[ touchStack[1] ] -- only time when this is true action = dmc.actions[ 'move' ] if action and action[ 'single' ] == true then mid = { x=t1.x-diff.x, y=t1.y-diff.y } else mid = { x=obj.x, y=obj.y } end return t1, mid end end local function getMultiCalcFunc( obj ) --print( "getMultiCalcFunc" ) local dmc = obj.__dmc.multitouch --print( "<<<<<<<<<< calculateDelta" ) local touches = dmc.touches local touchStack = dmc.touchStack local t1, t2 return function() local dx, dy local mid t1 = touches[ touchStack[1] ] t2 = touches[ touchStack[2] ] dx = t1.x - t2.x dy = -( t1.y - t2.y ) mid = { x=t1.x-dx/2, y=t1.y+dy/2 } return t1, mid end end local function calculateBase( obj ) --print( "======== calculateBase" ) local dmc = obj.__dmc.multitouch local touches = dmc.touches local touchStack = dmc.touchStack local cO -- corona obj local dx, dy local x, y local midpoint, touch touch, midpoint = dmc.touchFunc() dmc.midpointTouch = midpoint if DEBUG then -- update touch center point cO = debugObjs["touchCenter"] cO.x = dmc.midpointTouch.x ; cO.y = dmc.midpointTouch.y --print( dmc.midpointTouch.x, dmc.midpointTouch.y ) end -- save current properties dmc.scaleOrig = obj.xScale dmc.angleOrig = -obj.rotation -- convert from Corona to trig angles dmc.xOrig = obj.x dmc.yOrig = obj.y -- save distance, angle between touches dx = touch.x - midpoint.x dy = -( touch.y - midpoint.y ) dmc.triggr:start( dx, dy ) --dmc.distanceTouch = math.sqrt( dx*dx + dy*dy ) dmc.distanceTouch = math.sqrt( dx*dx + dy*dy ) --print( dx, dy ) -- calculate direction dmc.lastRotation = 0 dmc.lastDirection = nil --print( 'distance ', dx, dy, dmc.distanceTouch ) --print( "angle ", dmc.angleOrig ) -- center point calculations dx = obj.x - dmc.midpointTouch.x dy = -( obj.y - dmc.midpointTouch.y ) --print( display.contentWidth, display.contentHeight ) --print( dmc.midpointTouch.x, obj.x ) dmc.distanceCenter = math.sqrt( dx*dx + dy*dy ) dmc.angleCenter = math.deg( math.atan2( dy, dx ) ) --print( "dco: ", dmc.distanceCenter ) --print( "aco: ", dmc.angleCenter ) -- trig angle --print( "obj: ", dmc.scaleOrig, obj.x, obj.y ) x = math.cos( math.rad( dmc.angleCenter ) ) * dmc.distanceCenter + dmc.midpointTouch.x y = math.sin( math.rad( -dmc.angleCenter ) ) * dmc.distanceCenter + dmc.midpointTouch.y --print( "objx.y: ", obj.x, obj.y ) --print( "x.y: ", x, y ) if DEBUG then cO = debugObjs["calcCenter"] cO.x = x ; cO.y = y end -- pack up results local ret = { scale = dmc.scaleOrig, rotation = obj.rotation, x = obj.x, y = obj.y, -- dispatch events direction = dmc.lastDirection, angleDelta = 0, -- convert to Corona angle distanceDelta = 0, xDelta = 0, yDelta = 0 } return ret end local function calculateDelta( obj ) local dmc = obj.__dmc.multitouch --print( "<<<<<<<<<< calculateDelta" ) local touches = dmc.touches local touchStack = dmc.touchStack local cO -- corona obj local dx, dy local x, y local action touch, midpoint = dmc.touchFunc() dmc.midpointTouch = midpoint if DEBUG then -- update touch center point cO = debugObjs["touchCenter"] cO.x = dmc.midpointTouch.x ; cO.y = dmc.midpointTouch.y --print( dmc.midpointTouch.x, dmc.midpointTouch.y ) end dx = touch.x - midpoint.x dy = -( touch.y - midpoint.y ) -- calculate new distance between touches and scale local d, scale, scaled action = dmc.actions[ 'scale' ] if action and not action[ dmc.activeTouch ] then scale = 1.0 scaled = dmc.scaleOrig else d = math.sqrt( dx*dx + dy*dy ) scale = d / dmc.distanceTouch scaled = scale * dmc.scaleOrig --print( 'distance ', scale, dx, dy, dmc.distanceTouch, d ) end -- calculate new angle dmc.triggr:set( dx, dy ) local angleDiff = -dmc.triggr.angle_sum -- negative is clockwise local rotation = -( dmc.angleOrig + angleDiff ) --print( "angle: ", angleDiff, dmc.triggr.angle_sum ) -- calculate direction local rotationDiff = dmc.lastRotation - angleDiff if rotationDiff < 0 then dmc.lastDirection = "counter_clockwise" elseif rotationDiff > 0 then dmc.lastDirection = "clockwise" end dmc.lastRotation = angleDiff -- calculate new position x = dmc.midpointTouch.x + math.cos( math.rad( -( dmc.angleCenter + angleDiff ) ) ) * ( dmc.distanceCenter * scale ) y = dmc.midpointTouch.y + math.sin( math.rad( -( dmc.angleCenter + angleDiff ) ) ) * ( dmc.distanceCenter * scale ) --print( "x.y: ", x, y ) local xDiff = x - dmc.xOrig local yDiff = y - dmc.yOrig if DEBUG then cO = debugObjs["calcCenter"] cO.x = x cO.y = y end -- pack up results local ret = { scale = scaled, rotation = rotation, x = x, y = y, -- dispatch events direction = dmc.lastDirection, angleDelta = -angleDiff, -- convert to Corona angle distanceDelta = d, xDelta = xDiff, yDelta = yDiff } return ret end function updateObject( obj, phase, params ) local dmc = obj.__dmc.multitouch local action, res, val --== move ==-- action = dmc.actions[ 'move' ] if action and action[ dmc.activeTouch ] then xPos, yPos = action.func( params.x, params.y ) obj.x = xPos ; obj.y = yPos end --== scale ==-- action = dmc.actions[ 'scale' ] if action and action[ dmc.activeTouch ] then res, val = action.func( params.scale ) if res == "MAX" then obj.xScale = val ; obj.yScale = val elseif res == "MIN" then obj.xScale = val ; obj.yScale = val else obj.xScale = params.scale ; obj.yScale = params.scale end end --== rotate ==-- action = dmc.actions[ 'rotate' ] if action and action[ dmc.activeTouch ] then res, val = action.func( params.rotation ) if res == "MAX" then obj.rotation = val elseif res == "MIN" then obj.rotation = val else obj.rotation = params.rotation end end end function multitouchTouchHandler( event ) --print( "multitouchTouchHandler", event.id ) local f, xPos, yPos, cO, calcs, beginPoints local obj = event.target local dmc = obj.__dmc.multitouch local touches = dmc.touches local touchStack = dmc.touchStack -- create our event to dispatch local e = { name = MULTITOUCH_EVENT, phase = event.phase, target = obj } --== Start processing the Corona touch event ==-- if event.phase == 'began' then -- check to see if we have room to add this new touch event if ( ( dmc.isSingleActive and #touchStack == 1 and not dmc.isMultiActive ) or ( dmc.isMultiActive and #touchStack == 2 ) ) then -- we're not doing anything with this touch event return false end touches[ event.id ] = event TouchMgr:setFocus( event.target, event.id ) table.insert( touchStack, 1, event.id ) --Utils.print( event ) --print( #touchStack ) -- create function to pre-process touch gestures if ( dmc.isSingleActive and #touchStack == 1 ) then dmc.touchFunc = getSingleCalcFunc( obj ) dmc.activeTouch = 'single' elseif ( dmc.isMultiActive and #touchStack == 2 ) then dmc.touchFunc = getMultiCalcFunc( obj ) dmc.activeTouch = 'multi' else dmc.touchFunc = nil dmc.activeTouch = nil end -- process the gesture if dmc.touchFunc then calcs = calculateBase( obj ) -- fill in event and dispatch e.direction = calcs.direction e.angleDelta = calcs.angleDelta e.distanceDelta = calcs.distanceDelta e.xDelta = calcs.xDelta ; e.yDelta = calcs.yDelta e.x = calcs.x ; e.y = calcs.y if obj.dispatchEvent ~= nil then obj:dispatchEvent( e ) end if DEBUG then cO = debugObjs["touchCenter"] cO.isVisible = true cO = debugObjs["calcCenter"] cO.isVisible = true end end return true elseif event.phase == 'moved' then -- if we are in control of this touch ID if event.isFocused then touches[ event.id ] = event -- process the gesture if dmc.touchFunc then calcs = calculateDelta( obj ) updateObject( obj, event.phase, calcs ) -- fill in event and dispatch e.direction = calcs.direction e.angleDelta = calcs.angleDelta e.distanceDelta = calcs.distanceDelta e.xDelta = calcs.xDelta ; e.yDelta = calcs.yDelta e.x = calcs.x ; e.y = calcs.y if obj.dispatchEvent ~= nil then obj:dispatchEvent( e ) end if DEBUG then --print( calcs.angleDelta ) cO = debugObjs["objCenter"] cO.x = obj.x ; cO.y = obj.y end end return true end elseif ( event.phase == 'ended' or event.phase == 'canceled' ) then if event.isFocused then touches[ event.id ] = event if dmc.touchFunc then calcs = calculateDelta( obj ) updateObject( obj, event.phase, calcs ) -- fill in event and dispatch e.direction = calcs.direction e.angleDelta = calcs.angleDelta e.distanceDelta = calcs.distanceDelta e.xDelta = calcs.xDelta ; e.yDelta = calcs.yDelta e.x = calcs.x ; e.y = calcs.y if obj.dispatchEvent ~= nil then obj:dispatchEvent( e ) end end TouchMgr:unsetFocus( event.target, event.id ) -- remove event from our structures touches[ event.id ] = nil local i = 1 while touchStack[i] do if touchStack[i] == event.id then table.remove (touchStack, i) break end i = i + 1 end -- create function to pre-process touch gestures if ( dmc.isSingleActive and #touchStack == 1 ) then dmc.touchFunc = getSingleCalcFunc( obj ) dmc.activeTouch = 'single' elseif ( dmc.isMultiActive and #touchStack == 2 ) then dmc.touchFunc = getMultiCalcFunc( obj ) dmc.activeTouch = 'multi' else dmc.touchFunc = nil dmc.activeTouch = nil end -- process the gesture if dmc.touchFunc then calculateBase( obj ) else if DEBUG then cO = debugObjs["touchCenter"] cO.isVisible = false cO = debugObjs["calcCenter"] cO.isVisible = false end end return true end -- event.isFocused end -- event.phase == ended return false end --===================================================================-- -- MultiTouch Object --===================================================================-- local MultiTouch = {} --== Constants ==-- MultiTouch.MULTITOUCH_EVENT = MULTITOUCH_EVENT --== Support Functions ==-- -- sets isSingleActive, isMultiActive -- returns table with keys: 'single', 'multi', 'func' -- function processParameters( dmc, action, touchtype, params ) --print( "processParameters", action ) local config = {} -- constrain function if action == 'move' then config.func = createConstrainMoveFunc( dmc, params ) elseif action == 'scale' then config.func = createConstrainScaleFunc( params ) elseif action == 'rotate' then config.func = createConstrainRotateFunc( params ) else print( "WARNING: unknown action: " .. action ) return nil end -- active touches config[ 'single' ] = false config[ 'multi' ] = false if type( touchtype ) == 'string' then config[ touchtype ] = true elseif type( touchtype ) == 'table' then for _, v in ipairs( touchtype ) do if type( v ) == 'string' then config[ v ] = true end end end return config end --== Main Functions ==-- -- move() -- -- blesses an object to have drag properties -- -- @param obj a Corona-type object -- @param params a Lua table with modifiers -- @return the object which has been blessed (original), or nil on error -- MultiTouch.activate = function( obj, action, touchtype, params ) params = params or {} -- create our fancy callback and set event listener TouchMgr:register( obj, multitouchTouchHandler ) --== Setup special dmc_touch variables ==-- local dmc if obj.__dmc == nil then obj.__dmc = {} end if obj.__dmc.multitouch then dmc = obj.__dmc.multitouch else dmc = { -- table to hold active touches, keyed on touch ID touches = {}, touchStack = {}, activeTouch = nil, -- 'multi', 'single', nil touchFunc = nil, -- calculates mid point and touch actions = {}, -- holds 'move', 'rotate', 'scale' configurations scaleOrig = nil, angleOrig = nil, xOrig = nil, yOrig = nil, midpointTouch = nil, distanceTouch = nil, distanceCenter = nil, angleCenter = nil, angleAgent = nil, -- to calculate direction in broadcast event lastRotation = nil, lastDirection = nil } dmc.triggr = Triggr:new() obj.__dmc.multitouch = dmc end --== Process Parameters ==-- local config = processParameters( dmc, action, touchtype, params ) local configIsOK = true local dmc_action -- check for conflics (with single touch actions) if action == 'move' and config[ 'single' ] then dmc_action = dmc.actions[ 'rotate' ] if dmc_action and dmc_action[ 'single' ] then configIsOK = false end; dmc_action = dmc.actions[ 'scale' ] if dmc_action and dmc_action[ 'single' ] then configIsOK = false end; elseif action == 'rotate' and config[ 'single' ] then dmc_action = dmc.actions[ 'move' ] if dmc_action and dmc_action[ 'single' ] then configIsOK = false end; elseif action == 'scale' and config[ 'single' ] then dmc_action = dmc.actions[ 'move' ] if dmc_action and dmc_action[ 'single' ] then configIsOK = false end; end if configIsOK then dmc.actions[ action ] = config else print( "\nERROR: '" .. action .. "' is not compatible with the current config: \n" ) end -- set isSingleActive, isMultiActive, after setting any new actions dmc.isSingleActive = false dmc.isMultiActive = false -- ['move']={ single, multi, func } for _, v in ipairs( { 'move', 'rotate', 'scale' } ) do if dmc.actions[ v ] then if dmc.actions[ v ][ 'single' ] == true then dmc.isSingleActive = true end if dmc.actions[ v ][ 'multi' ] == true then dmc.isMultiActive = true end end end return obj end MultiTouch.deactivate = function( obj ) local dmc = obj.__dmc.multitouch obj.__dmc.multitouch = nil TouchMgr:unregister( obj, multitouchTouchHandler ) end return MultiTouch
mit
Ninjistix/darkstar
scripts/zones/Windurst_Woods/TextIDs.lua
5
7430
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6539; -- Come back after sorting your inventory. ITEM_OBTAINED = 6545; -- Obtained: <<<Unknown Parameter (Type: 80) 1>>><<<Possible Special Code: 01>>><<<Possible Special Code: 05>>> GIL_OBTAINED = 6546; -- Obtained <<<Numeric Parameter 0>>> gil. KEYITEM_OBTAINED = 6548; -- Obtained key item: <<<Unknown Parameter (Type: 80) 1>>> KEYITEM_LOST = 6549; -- Lost key item: <<<Unknown Parameter (Type: 80) 1>>> NOT_HAVE_ENOUGH_GIL = 6552; -- You do not have enough gil. HOMEPOINT_SET = 6636; -- Home point set! MOG_LOCKER_OFFSET = 6998; -- Your Mog Locker lease is valid until <timestamp>, kupo. FISHING_MESSAGE_OFFSET = 7094; -- You can't fish here. IMAGE_SUPPORT = 7198; -- Your ?Multiple Choice (Parameter 1)?[fishing/woodworking/smithing/goldsmithing/clothcraft/leatherworking/bonecraft/alchemy/cooking] skills went up ... NO_MORE_GP_ELIGIBLE = 7227; -- You are not eligible to receive guild points at this time. GUILD_TERMINATE_CONTRACT = 7212; -- You have terminated your trading contract with the Multiple Choice (Parameter 1)[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild and formed a new one with the Multiple Choice (Parameter 0)[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild GUILD_NEW_CONTRACT = 7220; -- You have formed a new trading contract with the Multiple Choice (Parameter 0)[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild GP_OBTAINED = 7232; -- Obtained: ?Numeric Parameter 0? guild points. NOT_HAVE_ENOUGH_GP = 7233; -- You do not have enough guild points. -- Conquest System CONQUEST = 8926; -- You've earned conquest points! -- Other Texts ITEM_DELIVERY_DIALOG = 6826; -- We can deliver goods to your residence or to the residences of your friends. NOKKHI_BAD_COUNT = 9756; -- What kinda smart-alecky baloney is this!? I told you to bring me the same kinda ammunition in complete sets. And don't forget the flowers, neither. NOKKHI_GOOD_TRADE = 9758; -- And here you go! Come back soon, and bring your friends! NOKKHI_BAD_ITEM = 9759; -- I'm real sorry, but there's nothing I can do with those. CLOUD_BAD_COUNT = 10103; -- Well, don't just stand there like an idiot! I can't do any bundlin' until you fork over a set of 99 tools and CLOUD_GOOD_TRADE = 10107; -- Here, take 'em and scram. And don't say I ain't never did nothin' for you! CLOUD_BAD_ITEM = 10108; -- What the hell is this junk!? Why don't you try bringin' what I asked for before I shove one of my sandals up your...nose! CHOCOBO_DIALOG = 10408; -- Kweh! -- Mission Dialogs YOU_ACCEPT_THE_MISSION = 6729; -- You have accepted the mission. -- Shop Texts JU_KAMJA_DIALOG = 6826; -- We can deliver goods to your residence or to the residences of your friends. PEW_SAHBARAEF_DIALOG = 6826; -- We can deliver goods to your residence or to the residences of your friends. VALERIANO_SHOP_DIALOG = 7543; -- Halfling philosophers and heroine beauties, welcome to the Troupe Valeriano show! And how gorgeous and green this fair town is! RETTO_MARUTTO_DIALOG = 7956; -- Allo-allo! If you're after boneworking materials, then make sure you buy them herey in Windurst! We're the cheapest in the whole wide worldy! SHIH_TAYUUN_DIALOG = 7958; -- Oh, that Retto-Marutto... If he keeps carrying on while speaking to the customers, he'll get in trouble with the guildmaster again! KUZAH_HPIROHPON_DIALOG = 7967; -- want to get your paws on the top-quality materials as used in the Weaverrrs' Guild? MERIRI_DIALOG = 7969; -- If you're interested in buying some works of art from our Weavers' Guild, then you've come to the right placey-wacey. QUESSE_SHOP_DIALOG = 8509; -- Welcome to the Windurst Chocobo Stables. MONONCHAA_SHOP_DIALOG = 8510; -- , then hurry up and decide, then get the heck out of herrre! MANYNY_SHOP_DIALOG = 8511; -- Are you in urgent needy-weedy of anything? I have a variety of thingy-wingies you may be interested in. WIJETIREN_SHOP_DIALOG = 8516; -- From humble Mithran cold medicines to the legendary Windurstian ambrrrosia of immortality, we have it all... NHOBI_ZALKIA_OPEN_DIALOG = 8519; -- Psst... Interested in some rrreal hot property? From lucky chocobo digs to bargain goods that fell off the back of an airship...all my stuff is a rrreal steal! NHOBI_ZALKIA_CLOSED_DIALOG = 8520; -- You're interested in some cheap shopping, rrright? I'm real sorry. I'm not doing business rrright now. NYALABICCIO_OPEN_DIALOG = 8521; -- Ladies and gentlemen, kittens and cubs! Do we have the sale that you've been waiting forrr! NYALABICCIO_CLOSED_DIALOG = 8522; -- Sorry, but our shop is closed rrright now. Why don't you go to Gustaberg and help the situation out therrre? BIN_STEJIHNA_OPEN_DIALOG = 8523; -- Why don't you buy something from me? You won't regrrret it! I've got all sorts of goods from the Zulkheim region! BIN_STEJIHNA_CLOSED_DIALOG = 8524; -- I'm taking a brrreak from the saleswoman gig to give dirrrections. So...through this arrrch is the residential area. TARAIHIPERUNHI_OPEN_DIALOG = 8525; -- Ooh...do I have some great merchandise for you! Man...these are once-in-a-lifetime offers, so get them while you can. TARAIHIPERUNHI_CLOSED_DIALOG = 8526; -- I am but a poor merchant. Mate, but you just wait! Strife...one day I'll live the high life. Hey, that's my dream, anyway... MILLEROVIEUNET_OPEN_DIALOG = 9977; -- Please have a look at these wonderful products from Qufim Island! You won't regret it! MILLEROVIEUNET_CLOSED_DIALOG = 9978; -- Now that I've finally learned the language here, I'd like to start my own business. If I could only find a supplier... --Test RAKOHBUUMA_OPEN_DIALOG = 7640; -- To expel those who would subvert the law and order of Windurst Woods... -- Quest Dialog PERIH_VASHAI_DIALOG = 8255; -- You can now become a ranger! CATALIA_DIALOG = 8557; -- While we cannot break our promise to the Windurstians, to ensure justice is served, we would secretly like you to take two shields off of the Yagudo who you meet en route. FORINE_DIALOG = 8558; -- Act according to our convictions while fulfilling our promise with the Tarutaru. This is indeed a fitting course for us, the people of glorious San d'Oria. APURURU_DIALOG = 9489; -- There's no way Semih Lafihna will just hand it over for no good reason. Maybe if you try talking with Kupipi... -- Harvest Festival TRICK_OR_TREAT = 9734; -- Trick or treat... THANK_YOU_TREAT = 9735; -- And now for your treat... HERE_TAKE_THIS = 9736; -- Here, take this... IF_YOU_WEAR_THIS = 9737; -- If you put this on and walk around, something...unexpected might happen... THANK_YOU = 9738; -- Thank you... -- conquest Base CONQUEST_BASE = 0;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Southern_San_dOria/npcs/Cletae.lua
4
1147
----------------------------------- -- Area: Southern San d'Oria -- NPC: Cletae -- Guild Merchant NPC: Leathercrafting Guild -- !pos -189.142 -8.800 14.449 230 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/conquest"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; function onTrigger(player,npc) if (player:sendGuild(5292,3,18,4)) then player:showText(npc,CLETAE_DIALOG); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Lower_Jeuno/npcs/_l04.lua
3
2486
----------------------------------- -- Area: Lower Jeuno -- NPC: Streetlamp -- Involved in Quests: Community Service -- !pos -80 0 -111 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/NPCIDs"); require("scripts/zones/Lower_Jeuno/TextIDs"); -- lamp id vary from 17780881 to 17780892 -- lamp cs vary from 0x0078 to 0x0083 (120 to 131) local lampNum = 4; local lampId = lampIdOffset + lampNum; local cs = lampCsOffset + lampNum; function onTrade(player,npc,trade) end; function onTrigger(player,npc) local hour = VanadielHour(); local playerOnQuest = GetServerVariable("[JEUNO]CommService"); -- player is on the quest if playerOnQuest == player:getID() then if hour >= 20 and hour < 21 then player:startEvent(cs,4); -- It is too early to light it. You must wait until nine o'clock. elseif hour >= 21 or hour < 1 then if npc:getAnimation() == ANIMATION_OPEN_DOOR then player:startEvent(cs,2); -- The lamp is already lit. else player:startEvent(cs,1,lampNum); -- Light the lamp? Yes/No end else player:startEvent(cs,3); -- You have failed to light the lamps in time. end -- player is not on the quest else if npc:getAnimation() == ANIMATION_OPEN_DOOR then player:startEvent(cs,5); -- The lamp is lit. else player:startEvent(cs,6); -- You examine the lamp. It seems that it must be lit manually. end end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) if csid == cs and option == 1 then -- lamp is now lit GetNPCByID(lampId):setAnimation(ANIMATION_OPEN_DOOR); -- tell player how many remain local lampsRemaining = 12; for i=0,11 do local lamp = GetNPCByID(lampIdOffset + i); if lamp:getAnimation() == ANIMATION_OPEN_DOOR then lampsRemaining = lampsRemaining - 1; end end if lampsRemaining == 0 then player:messageSpecial(LAMP_MSG_OFFSET); else player:messageSpecial(LAMP_MSG_OFFSET+1,lampsRemaining); end end end;
gpl-3.0
blackman1380/antispam
plugins/info.lua
10
22224
local function callback_reply(extra, success, result) --icon & rank ------------------------------------------------------------------------------------------------ userrank = "Member" if tonumber(result.from.id) == 122774063 then userrank = "Master ⭐⭐⭐⭐" send_document(org_chat_id,"umbrella/stickers/master.webp", ok_cb, false) elseif is_sudo(result) then userrank = "Sudo ⭐⭐⭐⭐⭐" send_document(org_chat_id,"umbrella/stickers/sudo.webp", ok_cb, false) elseif is_admin1(result.from.id) then userrank = "Admin ⭐⭐⭐" send_document(org_chat_id,"umbrella/stickers/admin.webp", ok_cb, false) elseif is_owner(result.from.id, result.to.id) then userrank = "Leader ⭐⭐" send_document(org_chat_id,"umbrella/stickers/leader.webp", ok_cb, false) elseif is_momod(result.from.id, result.to.id) then userrank = "Moderator ⭐" send_document(org_chat_id,"umbrella/stickers/mod.webp", ok_cb, false) elseif tonumber(result.from.id) == tonumber(our_id) then userrank = "Umbrella-Cp ⭐⭐⭐⭐⭐⭐" send_document(org_chat_id,"umbrella/stickers/umb.webp", ok_cb, false) elseif result.from.username then if string.sub(result.from.username:lower(), -3) == "bot" then userrank = "API Bot" send_document(org_chat_id,"umbrella/stickers/apt.webp", ok_cb, false) end end --custom rank ------------------------------------------------------------------------------------------------ local file = io.open("./info/"..result.from.id..".txt", "r") if file ~= nil then usertype = file:read("*all") else usertype = "-----" end --cont ------------------------------------------------------------------------------------------------ local user_info = {} local uhash = 'user:'..result.from.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.from.id..':'..result.to.id user_info.msgs = tonumber(redis:get(um_hash) or 0) --msg type ------------------------------------------------------------------------------------------------ if result.media then if result.media.type == "document" then if result.media.text then msg_type = "استیکر" else msg_type = "ساير فايلها" end elseif result.media.type == "photo" then msg_type = "فايل عکس" elseif result.media.type == "video" then msg_type = "فايل ويدئويي" elseif result.media.type == "audio" then msg_type = "فايل صوتي" elseif result.media.type == "geo" then msg_type = "موقعيت مکاني" elseif result.media.type == "contact" then msg_type = "شماره تلفن" elseif result.media.type == "file" then msg_type = "فايل" elseif result.media.type == "webpage" then msg_type = "پیش نمایش سایت" elseif result.media.type == "unsupported" then msg_type = "فايل متحرک" else msg_type = "ناشناخته" end elseif result.text then if string.match(result.text, '^%d+$') then msg_type = "عدد" elseif string.match(result.text, '%d+') then msg_type = "شامل عدد و حروف" elseif string.match(result.text, '^@') then msg_type = "یوزرنیم" elseif string.match(result.text, '@') then msg_type = "شامل یوزرنیم" elseif string.match(result.text, '[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]') then msg_type = "لينک تلگرام" elseif string.match(result.text, '[Hh][Tt][Tt][Pp]') then msg_type = "لينک سايت" elseif string.match(result.text, '[Ww][Ww][Ww]') then msg_type = "لينک سايت" elseif string.match(result.text, '?') then msg_type = "پرسش" else msg_type = "متن" end end --hardware ------------------------------------------------------------------------------------------------ if result.text then inputtext = string.sub(result.text, 0,1) if result.text then if string.match(inputtext, "[a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z]") then hardware = "کامپیوتر" elseif string.match(inputtext, "[A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z]") then hardware = "موبایل" else hardware = "-----" end else hardware = "-----" end else hardware = "-----" end --phone ------------------------------------------------------------------------------------------------ if access == 1 then if result.from.phone then number = "0"..string.sub(result.from.phone, 3) if string.sub(result.from.phone, 0,2) == '98' then number = number.."\nکشور: جمهوری اسلامی ایران" if string.sub(result.from.phone, 0,4) == '9891' then number = number.."\nنوع سیمکارت: همراه اول" elseif string.sub(result.from.phone, 0,5) == '98932' then number = number.."\nنوع سیمکارت: تالیا" elseif string.sub(result.from.phone, 0,4) == '9893' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(result.from.phone, 0,4) == '9890' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(result.from.phone, 0,4) == '9892' then number = number.."\nنوع سیمکارت: رایتل" else number = number.."\nنوع سیمکارت: سایر" end else number = number.."\nکشور: خارج\nنوع سیمکارت: متفرقه" end else number = "-----" end elseif access == 0 then if result.from.phone then number = "شما مجاز نیستید" if string.sub(result.from.phone, 0,2) == '98' then number = number.."\nکشور: جمهوری اسلامی ایران" if string.sub(result.from.phone, 0,4) == '9891' then number = number.."\nنوع سیمکارت: همراه اول" elseif string.sub(result.from.phone, 0,5) == '98932' then number = number.."\nنوع سیمکارت: تالیا" elseif string.sub(result.from.phone, 0,4) == '9893' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(result.from.phone, 0,4) == '9890' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(result.from.phone, 0,4) == '9892' then number = number.."\nنوع سیمکارت: رایتل" else number = number.."\nنوع سیمکارت: سایر" end else number = number.."\nکشور: خارج\nنوع سیمکارت: متفرقه" end else number = "-----" end end --info ------------------------------------------------------------------------------------------------ info = "نام کامل: "..string.gsub(result.from.print_name, "_", " ").."\n" .."نام کوچک: "..(result.from.first_name or "-----").."\n" .."نام خانوادگی: "..(result.from.last_name or "-----").."\n\n" .."شماره موبایل: "..number.."\n" .."یوزرنیم: @"..(result.from.username or "-----").."\n" .."آی دی: "..result.from.id.."\n\n" .."مقام: "..usertype.."\n" .."جایگاه: "..userrank.."\n\n" .."رابط کاربری: "..hardware.."\n" .."تعداد پیامها: "..user_info.msgs.."\n" .."نوع پیام: "..msg_type.."\n\n" .."نام گروه: "..string.gsub(result.to.print_name, "_", " ").."\n" .."آی دی گروه: "..result.to.id send_large_msg(org_chat_id, info) end local function callback_res(extra, success, result) if success == 0 then return send_large_msg(org_chat_id, "یوزرنیم وارد شده اشتباه است") end --icon & rank ------------------------------------------------------------------------------------------------ if tonumber(result.id) == 122774063 then userrank = "Master ⭐⭐⭐⭐" send_document(org_chat_id,"umbrella/stickers/master.webp", ok_cb, false) elseif is_sudo(result) then userrank = "Sudo ⭐⭐⭐⭐⭐" send_document(org_chat_id,"umbrella/stickers/sudo.webp", ok_cb, false) elseif is_admin1(result.id) then userrank = "Admin ⭐⭐⭐" send_document(org_chat_id,"umbrella/stickers/admin.webp", ok_cb, false) elseif is_owner(result.id, extra.chat2) then userrank = "Leader ⭐⭐" send_document(org_chat_id,"umbrella/stickers/leader.webp", ok_cb, false) elseif is_momod(result.id, extra.chat2) then userrank = "Moderator ⭐" send_document(org_chat_id,"umbrella/stickers/mod.webp", ok_cb, false) elseif tonumber(result.id) == tonumber(our_id) then userrank = "Umbrella-Cp ⭐⭐⭐⭐⭐⭐" send_document(org_chat_id,"umbrella/stickers/umb.webp", ok_cb, false) elseif result.from.username then if string.sub(result.from.username:lower(), -3) == "bot" then userrank = "API Bot" send_document(org_chat_id,"umbrella/stickers/api.webp", ok_cb, false) else userrank = "Member" end end --custom rank ------------------------------------------------------------------------------------------------ local file = io.open("./info/"..result.id..".txt", "r") if file ~= nil then usertype = file:read("*all") else usertype = "-----" end --phone ------------------------------------------------------------------------------------------------ if access == 1 then if result.phone then number = "0"..string.sub(result.phone, 3) if string.sub(result.phone, 0,2) == '98' then number = number.."\nکشور: جمهوری اسلامی ایران" if string.sub(result.phone, 0,4) == '9891' then number = number.."\nنوع سیمکارت: همراه اول" elseif string.sub(result.phone, 0,5) == '98932' then number = number.."\nنوع سیمکارت: تالیا" elseif string.sub(result.phone, 0,4) == '9893' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(result.phone, 0,4) == '9890' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(result.phone, 0,4) == '9892' then number = number.."\nنوع سیمکارت: رایتل" else number = number.."\nنوع سیمکارت: سایر" end else number = number.."\nکشور: خارج\nنوع سیمکارت: متفرقه" end else number = "-----" end elseif access == 0 then if result.phone then number = "شما مجاز نیستید" if string.sub(result.phone, 0,2) == '98' then number = number.."\nکشور: جمهوری اسلامی ایران" if string.sub(result.phone, 0,4) == '9891' then number = number.."\nنوع سیمکارت: همراه اول" elseif string.sub(result.phone, 0,5) == '98932' then number = number.."\nنوع سیمکارت: تالیا" elseif string.sub(result.phone, 0,4) == '9893' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(result.phone, 0,4) == '9890' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(result.phone, 0,4) == '9892' then number = number.."\nنوع سیمکارت: رایتل" else number = number.."\nنوع سیمکارت: سایر" end else number = number.."\nکشور: خارج\nنوع سیمکارت: متفرقه" end else number = "-----" end end --info ------------------------------------------------------------------------------------------------ info = "نام کامل: "..string.gsub(result.print_name, "_", " ").."\n" .."نام کوچک: "..(result.first_name or "-----").."\n" .."نام خانوادگی: "..(result.last_name or "-----").."\n\n" .."شماره موبایل: "..number.."\n" .."یوزرنیم: @"..(result.username or "-----").."\n" .."آی دی: "..result.id.."\n\n" .."مقام: "..usertype.."\n" .."جایگاه: "..userrank.."\n\n" send_large_msg(org_chat_id, info) end local function callback_info(extra, success, result) if success == 0 then return send_large_msg(org_chat_id, "آی دی وارد شده اشتباه است") end --icon & rank ------------------------------------------------------------------------------------------------ if tonumber(result.id) == 122774063 then userrank = "Master ⭐⭐⭐⭐" send_document(org_chat_id,"umbrella/stickers/master.webp", ok_cb, false) elseif is_sudo(result) then userrank = "Sudo ⭐⭐⭐⭐⭐" send_document(org_chat_id,"umbrella/stickers/sudo.webp", ok_cb, false) elseif is_admin1(result.id) then userrank = "Admin ⭐⭐⭐" send_document(org_chat_id,"umbrella/stickers/admin.webp", ok_cb, false) elseif is_owner(result.id, extra.chat2) then userrank = "Leader ⭐⭐" send_document(org_chat_id,"umbrella/stickers/leader.webp", ok_cb, false) elseif is_momod(result.id, extra.chat2) then userrank = "Moderator ⭐" send_document(org_chat_id,"umbrella/stickers/mod.webp", ok_cb, false) elseif tonumber(result.id) == tonumber(our_id) then userrank = "Umbrella-Cp ⭐⭐⭐⭐⭐⭐" send_document(org_chat_id,"umbrella/stickers/umb.webp", ok_cb, false) elseif result.from.username then if string.sub(result.from.username:lower(), -3) == "bot" then userrank = "API Bot" send_document(org_chat_id,"umbrella/stickers/api.webp", ok_cb, false) else userrank = "Member" end end --custom rank ------------------------------------------------------------------------------------------------ local file = io.open("./info/"..result.id..".txt", "r") if file ~= nil then usertype = file:read("*all") else usertype = "-----" end --phone ------------------------------------------------------------------------------------------------ if access == 1 then if result.phone then number = "0"..string.sub(result.phone, 3) if string.sub(result.phone, 0,2) == '98' then number = number.."\nکشور: جمهوری اسلامی ایران" if string.sub(result.phone, 0,4) == '9891' then number = number.."\nنوع سیمکارت: همراه اول" elseif string.sub(result.phone, 0,5) == '98932' then number = number.."\nنوع سیمکارت: تالیا" elseif string.sub(result.phone, 0,4) == '9893' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(result.phone, 0,4) == '9890' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(result.phone, 0,4) == '9892' then number = number.."\nنوع سیمکارت: رایتل" else number = number.."\nنوع سیمکارت: سایر" end else number = number.."\nکشور: خارج\nنوع سیمکارت: متفرقه" end else number = "-----" end elseif access == 0 then if result.phone then number = "شما مجاز نیستید" if string.sub(result.phone, 0,2) == '98' then number = number.."\nکشور: جمهوری اسلامی ایران" if string.sub(result.phone, 0,4) == '9891' then number = number.."\nنوع سیمکارت: همراه اول" elseif string.sub(result.phone, 0,5) == '98932' then number = number.."\nنوع سیمکارت: تالیا" elseif string.sub(result.phone, 0,4) == '9893' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(result.phone, 0,4) == '9890' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(result.phone, 0,4) == '9892' then number = number.."\nنوع سیمکارت: رایتل" else number = number.."\nنوع سیمکارت: سایر" end else number = number.."\nکشور: خارج\nنوع سیمکارت: متفرقه" end else number = "-----" end end --name ------------------------------------------------------------------------------------------------ if string.len(result.print_name) > 15 then fullname = string.sub(result.print_name, 0,15).."..." else fullname = result.print_name end if result.first_name then if string.len(result.first_name) > 15 then firstname = string.sub(result.first_name, 0,15).."..." else firstname = result.first_name end else firstname = "-----" end if result.last_name then if string.len(result.last_name) > 15 then lastname = string.sub(result.last_name, 0,15).."..." else lastname = result.last_name end else lastname = "-----" end --info ------------------------------------------------------------------------------------------------ info = "نام کامل: "..string.gsub(result.print_name, "_", " ").."\n" .."نام کوچک: "..(result.first_name or "-----").."\n" .."نام خانوادگی: "..(result.last_name or "-----").."\n\n" .."شماره موبایل: "..number.."\n" .."یوزرنیم: @"..(result.username or "-----").."\n" .."آی دی: "..result.id.."\n\n" .."مقام: "..usertype.."\n" .."جایگاه: "..userrank.."\n\n" send_large_msg(org_chat_id, info) end local function run(msg, matches) local data = load_data(_config.moderation.data) org_chat_id = "chat#id"..msg.to.id if is_sudo(msg) then access = 1 else access = 0 end if matches[1] == '/infodel' and is_sudo(msg) then azlemagham = io.popen('rm ./info/'..matches[2]..'.txt'):read('*all') return 'از مقام خود عزل شد' elseif matches[1] == '/info' and is_sudo(msg) then local name = string.sub(matches[2], 1, 50) local text = string.sub(matches[3], 1, 10000000000) local file = io.open("./info/"..name..".txt", "w") file:write(text) file:flush() file:close() return "مقام ثبت شد" elseif #matches == 2 then local cbres_extra = {chatid = msg.to.id} if string.match(matches[2], '^%d+$') then return user_info('user#id'..matches[2], callback_info, cbres_extra) else return res_user(matches[2]:gsub("@",""), callback_res, cbres_extra) end else --custom rank ------------------------------------------------------------------------------------------------ local file = io.open("./info/"..msg.from.id..".txt", "r") if file ~= nil then usertype = file:read("*all") else usertype = "-----" end --hardware ------------------------------------------------------------------------------------------------ if matches[1] == "info" then hardware = "کامپیوتر" else hardware = "موبایل" end if not msg.reply_id then --contor ------------------------------------------------------------------------------------------------ local user_info = {} local uhash = 'user:'..msg.from.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..msg.from.id..':'..msg.to.id user_info.msgs = tonumber(redis:get(um_hash) or 0) --icon & rank ------------------------------------------------------------------------------------------------ if tonumber(msg.from.id) == 122774063 then userrank = "Master ⭐⭐⭐⭐" send_document("chat#id"..msg.to.id,"umbrella/stickers/master.webp", ok_cb, false) elseif is_sudo(msg) then userrank = "Sudo ⭐⭐⭐⭐⭐" send_document("chat#id"..msg.to.id,"umbrella/stickers/sudo.webp", ok_cb, false) elseif is_admin1(msg) then userrank = "Admin ⭐⭐⭐" send_document("chat#id"..msg.to.id,"umbrella/stickers/admin.webp", ok_cb, false) elseif is_owner(msg) then userrank = "Leader ⭐⭐" send_document("chat#id"..msg.to.id,"umbrella/stickers/leader.webp", ok_cb, false) elseif is_momod(msg) then userrank = "Moderator ⭐" send_document("chat#id"..msg.to.id,"umbrella/stickers/mod.webp", ok_cb, false) else userrank = "Member" end --number ------------------------------------------------------------------------------------------------ if msg.from.phone then numberorg = string.sub(msg.from.phone, 3) number = "****0"..string.sub(numberorg, 0,6) if string.sub(msg.from.phone, 0,2) == '98' then number = number.."\nکشور: جمهوری اسلامی ایران" if string.sub(msg.from.phone, 0,4) == '9891' then number = number.."\nنوع سیمکارت: همراه اول" elseif string.sub(msg.from.phone, 0,5) == '98932' then number = number.."\nنوع سیمکارت: تالیا" elseif string.sub(msg.from.phone, 0,4) == '9893' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(msg.from.phone, 0,4) == '9890' then number = number.."\nنوع سیمکارت: ایرانسل" elseif string.sub(msg.from.phone, 0,4) == '9892' then number = number.."\nنوع سیمکارت: رایتل" else number = number.."\nنوع سیمکارت: سایر" end else number = number.."\nکشور: خارج\nنوع سیمکارت: متفرقه" end else number = "-----" end --info ------------------------------------------------------------------------------------------------ local info = "نام کامل: "..string.gsub(msg.from.print_name, "_", " ").."\n" .."نام کوچک: "..(msg.from.first_name or "-----").."\n" .."نام خانوادگی: "..(msg.from.last_name or "-----").."\n\n" .."شماره موبایل: "..number.."\n" .."یوزرنیم: @"..(msg.from.username or "-----").."\n" .."آی دی: "..msg.from.id.."\n\n" .."مقام: "..usertype.."\n" .."جایگاه: "..userrank.."\n\n" .."رابط کاربری: "..hardware.."\n" .."تعداد پیامها: "..user_info.msgs.."\n\n" .."نام گروه: "..string.gsub(msg.to.print_name, "_", " ").."\n" .."آی دی گروه: "..msg.to.id return info else get_message(msg.reply_id, callback_reply, false) end end end return { description = "User Infomation", usagehtm = '<tr><td align="center">info</td><td align="right">اطلاعات کاملی را راجبه شما، گروهی که در آن هستید و مقامتان میدهد همچنین با رپلی کردن میتوانید اطلاعات فرد مورد نظر را نیز ببینید</td></tr>' ..'<tr><td align="center">/info مقام آیدی</td><td align="right">اعطای مقام به شخص به جر مقامهای اصلی</td></tr>' ..'<tr><td align="center">/infodel آیدی</td><td align="right">حذف مقام اعطا شده</td></tr>', usage = { user = { "info: اطلاعات شما", "info (reply): اطلاعات دیگران", }, sudo = { "/info (id) (txt) : اعطای مقام", "/infodel : حذف مقام", }, }, patterns = { "^(infodel) (.*)$", "^(info) ([^%s]+) (.*)$", "^([Ii]nfo) (.*)$", "^(info)$", "^(Info)$", }, run = run, }
gpl-2.0
PetarTilevRusev/EndlessWar
game/scripts/vscripts/addon_game_mode.lua
1
3207
-- This is the entry-point to your game mode and should be used primarily to precache models/particles/sounds/etc require('internal/util') require('gamemode') function Precache( context ) --[[ This function is used to precache resources/units/items/abilities that will be needed for sure in your game and that will not be precached by hero selection. When a hero is selected from the hero selection screen, the game will precache that hero's assets, any equipped cosmetics, and perform the data-driven precaching defined in that hero's precache{} block, as well as the precache{} block for any equipped abilities. See GameMode:PostLoadPrecache() in gamemode.lua for more information ]] -- Human units PrecacheUnitByNameSync("human_king", context) PrecacheUnitByNameSync("human_melee_guard", context) PrecacheUnitByNameSync("human_ranged_guard", context) PrecacheUnitByNameSync("footman", context) PrecacheUnitByNameSync("footman_4", context) PrecacheUnitByNameSync("knight", context) PrecacheUnitByNameSync("knight_4", context) PrecacheUnitByNameSync("human_siege_engine", context) PrecacheUnitByNameSync("rifleman", context) PrecacheUnitByNameSync("rifleman_4", context) PrecacheUnitByNameSync("sorcerer", context) PrecacheUnitByNameSync("sorcerer_4", context) PrecacheUnitByNameSync("priest", context) PrecacheUnitByNameSync("priest_4", context) -- Human buildings PrecacheUnitByNameSync("human_blacksmith", context) PrecacheUnitByNameSync("human_research_facility", context) PrecacheUnitByNameSync("human_melee_barracks", context) PrecacheUnitByNameSync("human_ranged_barracks", context) -- Undead units PrecacheUnitByNameSync("undead_king", context) PrecacheUnitByNameSync("undead_melee_guard", context) PrecacheUnitByNameSync("undead_ranged_guard", context) PrecacheUnitByNameSync("ghoul", context) PrecacheUnitByNameSync("ghoul_4", context) PrecacheUnitByNameSync("abomination", context) PrecacheUnitByNameSync("abomination_4", context) PrecacheUnitByNameSync("crypt_fiend", context) PrecacheUnitByNameSync("crypt_fiend_4", context) PrecacheUnitByNameSync("banshee", context) PrecacheUnitByNameSync("banshee_4", context) PrecacheUnitByNameSync("necromancer", context) PrecacheUnitByNameSync("necromancer_4", context) PrecacheUnitByNameSync("necromancer_melee_skeleton_4", context) PrecacheUnitByNameSync("necromancer_ranged_skeleton_4", context) -- Undead buildings PrecacheUnitByNameSync("undead_graveyard", context) PrecacheUnitByNameSync("undead_tample_of_the_damned", context) PrecacheUnitByNameSync("undead_melee_barracks", context) PrecacheUnitByNameSync("undead_ranged_barracks", context) -- Night Elf units PrecacheUnitByNameAsync("treant", context) PrecacheUnitByNameAsync("archer", context) -- Night Elf buildings -- Orc units PrecacheUnitByNameAsync("grund", context) PrecacheUnitByNameAsync("headhunter", context) --Orc buildings --Models PrecacheModel("models/items/hex/sheep_hex/sheep_hex.vmdl", context) end -- Create the game mode when we activate function Activate() GameRules.GameMode = GameMode() GameRules.GameMode:InitGameMode() end
mit
Ninjistix/darkstar
scripts/zones/Buburimu_Peninsula/npcs/Ishin_IM.lua
3
2971
----------------------------------- -- Area: Buburimu Peninsula -- NPC: Ishin, I.M. -- Outpost Conquest Guards -- !pos -481.164 -32.858 49.188 118 ----------------------------------- package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Buburimu_Peninsula/TextIDs"); local guardnation = NATION_BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = KOLSHUSHU; local csid = 0x7ff9; function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
hamrah12/hamrah_shoma
plugins/translate.lua
674
1637
--[[ -- Translate text using Google Translate. -- http://translate.google.com/translate_a/single?client=t&ie=UTF-8&oe=UTF-8&hl=en&dt=t&tl=en&sl=auto&text=hello --]] do function translate(source_lang, target_lang, text) local path = "http://translate.google.com/translate_a/single" -- URL query parameters local params = { client = "t", ie = "UTF-8", oe = "UTF-8", hl = "en", dt = "t", tl = target_lang or "en", sl = source_lang or "auto", text = URL.escape(text) } local query = format_http_params(params, true) local url = path..query local res, code = https.request(url) -- Return nil if error if code > 200 then return nil end local trans = res:gmatch("%[%[%[\"(.*)\"")():gsub("\"(.*)", "") return trans end function run(msg, matches) -- Third pattern if #matches == 1 then print("First") local text = matches[1] return translate(nil, nil, text) end -- Second pattern if #matches == 2 then print("Second") local target = matches[1] local text = matches[2] return translate(nil, target, text) end -- First pattern if #matches == 3 then print("Third") local source = matches[1] local target = matches[2] local text = matches[3] return translate(source, target, text) end end return { description = "Translate some text", usage = { "!translate text. Translate the text to English.", "!translate target_lang text.", "!translate source,target text", }, patterns = { "^!translate ([%w]+),([%a]+) (.+)", "^!translate ([%w]+) (.+)", "^!translate (.+)", }, run = run } end
gpl-2.0
LuaDist2/gntp
src/lua/gntp/utils.lua
2
10519
------------------------------------------------------------------ -- -- Author: Alexey Melnichuk <alexeymelnichuck@gmail.com> -- -- Copyright (C) 2015-2016 Alexey Melnichuk <alexeymelnichuck@gmail.com> -- -- Licensed according to the included 'LICENSE' document -- -- This file is part of lua-gntp library. -- ------------------------------------------------------------------ local function split(str, sep, plain) local b, res = 1, {} while b <= #str do local e, e2 = string.find(str, sep, b, plain) if e then res[#res + 1] = string.sub(str, b, e-1) b = e2 + 1 else res[#res + 1] = string.sub(str, b) break end end return res end local unpack = unpack or table.unpack local function usplit(...) return unpack(split(...)) end local function split_first(str, sep, plain) local e, e2 = string.find(str, sep, nil, plain) if e then return string.sub(str, 1, e - 1), string.sub(str, e2 + 1) end return str end local function slit_first_self_test() local s1, s2 = split_first("ab|cd", "|", true) assert(s1 == "ab") assert(s2 == "cd") local s1, s2 = split_first("|abcd", "|", true) assert(s1 == "") assert(s2 == "abcd") local s1, s2 = split_first("abcd|", "|", true) assert(s1 == "abcd") assert(s2 == "") local s1, s2 = split_first("abcd", "|", true) assert(s1 == "abcd") assert(s2 == nil) end local function class(base) local t = base and setmetatable({}, base) or {} t.__index = t t.__class = t t.__base = base function t.new(...) local o = setmetatable({}, t) if o.__init then if t == ... then -- we call as Class:new() return o:__init(select(2, ...)) else -- we call as Class.new() return o:__init(...) end end return o end return t end local function class_self_test() local A = class() function A:__init(a, b) assert(a == 1) assert(b == 2) end A:new(1, 2) A.new(1, 2) local B = class(A) function B:__init(a,b,c) assert(self.__base == A) A.__init(B, a, b) assert(c == 3) end B:new(1, 2, 3) B.new(1, 2, 3) end ------------------------------------------------------------------- local List = class() do function List:reset() self._first = 0 self._last = -1 self._t = {} return self end List.__init = List.reset function List:push_front(v) assert(v ~= nil) local first = self._first - 1 self._first, self._t[first] = first, v return self end function List:push_back(v) assert(v ~= nil) local last = self._last + 1 self._last, self._t[last] = last, v return self end function List:peek_front() return self._t[self._first] end function List:peek_back() return self._t[self._last] end function List:pop_front() local first = self._first if first > self._last then return end local value = self._t[first] self._first, self._t[first] = first + 1 return value end function List:pop_back() local last = self._last if self._first > last then return end local value = self._t[last] self._last, self._t[last] = last - 1 return value end function List:size() return self._last - self._first + 1 end function List:empty() return self._first > self._last end function List:find(fn, pos) pos = pos or 1 if type(fn) == "function" then for i = self._first + pos - 1, self._last do local n = i - self._first + 1 if fn(self._t[i]) then return n, self._t[i] end end else for i = self._first + pos - 1, self._last do local n = i - self._first + 1 if fn == self._t[i] then return n, self._t[i] end end end end function List.self_test() local q = List:new() assert(q:empty() == true) assert(q:size() == 0) assert(q:push_back(1) == q) assert(q:empty() == false) assert(q:size() == 1) assert(q:peek_back() == 1) assert(q:empty() == false) assert(q:size() == 1) assert(q:peek_front() == 1) assert(q:empty() == false) assert(q:size() == 1) assert(q:pop_back() == 1) assert(q:empty() == true) assert(q:size() == 0) assert(q:push_front(1) == q) assert(q:empty() == false) assert(q:size() == 1) assert(q:pop_front() == 1) assert(q:empty() == true) assert(q:size() == 0) assert(q:pop_back() == nil) assert(q:empty() == true) assert(q:size() == 0) assert(q:pop_front() == nil) assert(q:empty() == true) assert(q:size() == 0) assert(false == pcall(q.push_back, q)) assert(q:empty() == true) assert(q:size() == 0) assert(false == pcall(q.push_front, q)) assert(q:empty() == true) assert(q:size() == 0) q:push_back(1):push_back(2) assert(q:pop_back() == 2) assert(q:pop_back() == 1) q:push_back(1):push_back(2) assert(q:pop_front() == 1) assert(q:pop_front() == 2) q:reset() assert(nil == q:find(1)) q:push_back(1):push_back(2):push_front(3) assert(1 == q:find(3)) assert(2 == q:find(1)) assert(3 == q:find(2)) assert(nil == q:find(4)) assert(2 == q:find(1, 2)) assert(nil == q:find(1, 3)) end end ------------------------------------------------------------------- ------------------------------------------------------------------- local Buffer = class() do -- eol should ends with specific char. function Buffer:__init(eol, eol_is_rex) self._eol = eol or "\n" self._eol_plain = not eol_is_rex self._lst = List.new() return self end function Buffer:reset() self._lst:reset() return self end function Buffer:eol() return self._eol, self._eol_plain end function Buffer:set_eol(eol, eol_is_rex) self._eol = assert(eol) self._eol_plain = not eol_is_rex return self end function Buffer:append(data) if #data > 0 then self._lst:push_back(data) end return self end function Buffer:prepend(data) if #data > 0 then self._lst:push_front(data) end return self end function Buffer:read_line(eol, eol_is_rex) local plain if eol then plain = not eol_is_rex else eol, plain = self._eol, self._eol_plain end local lst = self._lst local ch = eol:sub(-1) local check = function(s) return not not string.find(s, ch, nil, true) end local t = {} while true do local i = self._lst:find(check) if not i then if #t > 0 then lst:push_front(table.concat(t)) end return end assert(i > 0) for i = i, 1, -1 do t[#t + 1] = lst:pop_front() end local line, tail -- try find EOL in last chunk if plain or (eol == ch) then line, tail = split_first(t[#t], eol, true) end if eol == ch then assert(tail) end if tail then -- we found EOL -- we can split just last chunk and concat t[#t] = line if #tail > 0 then lst:push_front(tail) end return table.concat(t) end -- we need concat whole string and then split -- for eol like `\r\n` this may not work well but for most cases it should work well -- e.g. for LuaSockets pattern `\r*\n` it work with one iteration but still we need -- concat->split because of case such {"aaa\r", "\n"} line, tail = split_first(table.concat(t), eol, plain) if tail then -- we found EOL if #tail > 0 then lst:push_front(tail) end return line end end end function Buffer:read_all() local t = {} local lst = self._lst while not lst:empty() do t[#t + 1] = self._lst:pop_front() end return table.concat(t) end function Buffer:read_some() if self._lst:empty() then return end return self._lst:pop_front() end function Buffer:read_n(n) n = math.floor(n) if n == 0 then if self._lst:empty() then return end return "" end local lst = self._lst local size, t = 0, {} while true do local chunk = lst:pop_front() if not chunk then -- buffer too small if #t > 0 then lst:push_front(table.concat(t)) end return end if (size + #chunk) >= n then assert(n > size) local pos = n - size local data = string.sub(chunk, 1, pos) if pos < #chunk then lst:push_front(string.sub(chunk, pos + 1)) end t[#t + 1] = data return table.concat(t) end t[#t + 1] = chunk size = size + #chunk end end function Buffer:read(pat, ...) if not pat then return self:read_some() end if pat == "*l" then return self:read_line(...) end if pat == "*a" then return self:read_all() end return self:read_n(pat) end function Buffer:empty() return self._lst:empty() end function Buffer:next_line(data, eol) eol = eol or self._eol or "\n" if data then self:append(data) end return self:read_line(eol, true) end function Buffer:next_n(data, n) if data then self:append(data) end return self:read_n(n) end function Buffer.self_test(EOL) local b = Buffer.new("\r\n") b:append("a\r") b:append("\nb") b:append("\r\n") b:append("c\r\nd\r\n") assert("a" == b:read_line()) assert("b" == b:read_line()) assert("c" == b:read_line()) assert("d" == b:read_line()) local b = Buffer:new(EOL) local eol = b:eol() -- test next_xxx assert("aaa" == b:next_line("aaa" .. eol .. "bbb")) assert("bbbccc" == b:next_line("ccc" .. eol .. "ddd" .. eol)) assert("ddd" == b:next_line(eol)) assert("" == b:next_line("")) assert(nil == b:next_line("")) assert(nil == b:next_line("aaa")) assert("aaa" == b:next_n("123456", 3)) assert(nil == b:next_n("", 8)) assert("123"== b:next_n("", 3)) assert("456" == b:next_n(nil, 3)) b:reset() assert(nil == b:next_line("aaa|bbb")) assert("aaa" == b:next_line(nil, "|")) b:reset() b:set_eol("\r*\n", true) :append("aaa\r\r\n\r\nbbb\nccc") assert("aaa" == b:read_line()) assert("" == b:read_line()) assert("bbb" == b:read_line()) assert(nil == b:read_line()) -- assert("ccc" == b:read_line("$", true)) b:reset() b:append("aaa\r\r") b:append("\r\r") assert(nil == b:read_line()) b:append("\nbbb\n") assert("aaa" == b:read_line()) assert("bbb" == b:read_line()) b:reset() b:set_eol("\n\0") b:append("aaa") assert(nil == b:read_line()) b:append("\n") assert(nil == b:read_line()) b:append("\0") assert("aaa" == b:read_line()) end end ------------------------------------------------------------------- local function self_test() Buffer.self_test() List.self_test() slit_first_self_test() class_self_test() end return { Buffer = Buffer; List = List; class = class; split_first = split_first; split = split; usplit = usplit; self_test = self_test; }
mit
Ninjistix/darkstar
scripts/zones/Bastok_Mines/npcs/Virnage.lua
5
2055
----------------------------------- -- Area: Bastok Mines -- NPC: Virnage -- Starts Quest: Altana's Sorrow -- @zone 234 -- !pos 0 0 51 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) AltanaSorrow = player:getQuestStatus(BASTOK,ALTANA_S_SORROW); if (AltanaSorrow == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >= 4 and player:getMainLvl() >= 10) then player:startEvent(141); -- Start quest "Altana's Sorrow" elseif (AltanaSorrow == QUEST_ACCEPTED) then if (player:hasKeyItem(BUCKET_OF_DIVINE_PAINT) == true) then player:startEvent(143); -- CS with Bucket of Divine Paint KI elseif (player:hasKeyItem(LETTER_FROM_VIRNAGE) == true) then --player:showText(npc,VIRNAGE_DIALOG_2); player:startEvent(144); -- During quest (after KI) else -- player:showText(npc,VIRNAGE_DIALOG_1); player:startEvent(142); -- During quest "Altana's Sorrow" (before KI) end elseif (AltanaSorrow == QUEST_COMPLETED) then player:startEvent(145); -- New standard dialog else player:startEvent(140); -- Standard dialog end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 141 and option == 0) then player:addQuest(BASTOK,ALTANA_S_SORROW); elseif (csid == 143) then player:delKeyItem(BUCKET_OF_DIVINE_PAINT); player:addKeyItem(LETTER_FROM_VIRNAGE); player:messageSpecial(KEYITEM_OBTAINED,LETTER_FROM_VIRNAGE); end end;
gpl-3.0
ccyphers/kong
spec/03-plugins/01-basic-auth/02-api_spec.lua
1
9356
local cjson = require "cjson" local helpers = require "spec.helpers" describe("Plugin: basic-auth (API)", function() local consumer, admin_client setup(function() assert(helpers.start_kong()) admin_client = helpers.admin_client() end) teardown(function() if admin_client then admin_client:close() end helpers.stop_kong() end) describe("/consumers/:consumer/basic-auth/", function() setup(function() consumer = assert(helpers.dao.consumers:insert { username = "bob" }) end) after_each(function() helpers.dao:truncate_table("basicauth_credentials") end) describe("POST", function() it("creates a basic-auth credential", function() local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/basic-auth", body = { username = "bob", password = "kong" }, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(201, res) local json = cjson.decode(body) assert.equal(consumer.id, json.consumer_id) assert.equal("bob", json.username) end) it("encrypts the password", function() local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/basic-auth", body = { username = "bob", password = "kong" }, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(201, res) local json = cjson.decode(body) assert.is_string(json.password) assert.not_equal("kong", json.password) local crypto = require "kong.plugins.basic-auth.crypto" local hash = crypto.encrypt { consumer_id = consumer.id, password = "kong" } assert.equal(hash, json.password) end) describe("errors", function() it("returns bad request", function() local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/basic-auth", body = {}, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(400, res) assert.equal([[{"username":"username is required"}]], body) end) it("cannot create two identical usernames", function() local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/basic-auth", body = { username = "bob", password = "kong" }, headers = { ["Content-Type"] = "application/json" } }) assert.res_status(201, res) local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/basic-auth", body = { username = "bob", password = "kong" }, headers = { ["Content-Type"] = "application/json" } }) assert.res_status(409, res) end) end) end) describe("PUT", function() it("creates a basic-auth credential", function() local res = assert(admin_client:send { method = "PUT", path = "/consumers/bob/basic-auth", body = { username = "bob", password = "kong" }, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(201, res) local json = cjson.decode(body) assert.equal(consumer.id, json.consumer_id) assert.equal("bob", json.username) end) describe("errors", function() it("returns bad request", function() local res = assert(admin_client:send { method = "PUT", path = "/consumers/bob/basic-auth", body = {}, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(400, res) assert.equal([[{"username":"username is required"}]], body) end) end) end) describe("GET", function() setup(function() for i = 1, 3 do assert(helpers.dao.basicauth_credentials:insert { username = "bob"..i, password = "kong", consumer_id = consumer.id }) end end) teardown(function() helpers.dao:truncate_table("basicauth_credentials") end) it("retrieves the first page", function() local res = assert(admin_client:send { method = "GET", path = "/consumers/bob/basic-auth" }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.is_table(json.data) assert.equal(3, #json.data) assert.equal(3, json.total) end) end) end) describe("/consumers/:consumer/basic-auth/:id", function() local credential before_each(function() helpers.dao:truncate_table("basicauth_credentials") credential = assert(helpers.dao.basicauth_credentials:insert { username = "bob", password = "kong", consumer_id = consumer.id }) end) describe("GET", function() it("retrieves basic-auth credential by id", function() local res = assert(admin_client:send { method = "GET", path = "/consumers/bob/basic-auth/"..credential.id }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal(credential.id, json.id) end) it("retrieves basic-auth credential by username", function() local res = assert(admin_client:send { method = "GET", path = "/consumers/bob/basic-auth/"..credential.username }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal(credential.id, json.id) end) it("retrieves credential by id only if the credential belongs to the specified consumer", function() assert(helpers.dao.consumers:insert { username = "alice" }) local res = assert(admin_client:send { method = "GET", path = "/consumers/bob/basic-auth/"..credential.id }) assert.res_status(200, res) res = assert(admin_client:send { method = "GET", path = "/consumers/alice/basic-auth/"..credential.id }) assert.res_status(404, res) end) end) describe("PATCH", function() it("updates a credential by id", function() local previous_hash = credential.password local res = assert(admin_client:send { method = "PATCH", path = "/consumers/bob/basic-auth/"..credential.id, body = { password = "4321" }, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.not_equal(previous_hash, json.password) end) it("updates a credential by username", function() local previous_hash = credential.password local res = assert(admin_client:send { method = "PATCH", path = "/consumers/bob/basic-auth/"..credential.username, body = { password = "upd4321" }, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.not_equal(previous_hash, json.password) end) describe("errors", function() it("handles invalid input", function() local res = assert(admin_client:send { method = "PATCH", path = "/consumers/bob/basic-auth/"..credential.id, body = { password = 123 }, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(400, res) assert.equal([[{"password":"password is not a string"}]], body) end) end) end) describe("DELETE", function() it("deletes a credential", function() local res = assert(admin_client:send { method = "DELETE", path = "/consumers/bob/basic-auth/"..credential.id, }) assert.res_status(204, res) end) describe("errors", function() it("returns 404 on missing username", function() local res = assert(admin_client:send { method = "DELETE", path = "/consumers/bob/basic-auth/blah" }) assert.res_status(404, res) end) it("returns 404 if not found", function() local res = assert(admin_client:send { method = "DELETE", path = "/consumers/bob/basic-auth/00000000-0000-0000-0000-000000000000" }) assert.res_status(404, res) end) end) end) end) end)
apache-2.0
LuaDist2/llui
src/kernel.lua
2
8141
-- There should be only one instance of this code -- running for a given lua state --[[ Queue --]] local Queue = {} setmetatable(Queue, { __call = function(self, ...) return self:create(...); end, }); local Queue_mt = { __index = Queue; } function Queue.init(self, first, last, name) first = first or 1; last = last or 0; local obj = { first=first, last=last, name=name}; setmetatable(obj, Queue_mt); return obj end function Queue.create(self, first, last, name) first = first or 1 last = last or 0 return self:init(first, last, name); end --[[ function Queue.new(name) return Queue:init(1, 0, name); end --]] function Queue:enqueue(value) --self.MyList:PushRight(value) local last = self.last + 1 self.last = last self[last] = value return value end function Queue:pushFront(value) -- PushLeft local first = self.first - 1; self.first = first; self[first] = value; end function Queue:dequeue(value) -- return self.MyList:PopLeft() local first = self.first if first > self.last then return nil, "list is empty" end local value = self[first] self[first] = nil -- to allow garbage collection self.first = first + 1 return value end function Queue:length() return self.last - self.first+1 end -- Returns an iterator over all the current -- values in the queue function Queue:entries(func, param) local starting = self.first-1; local len = self:length(); local closure = function() starting = starting + 1; return self[starting]; end return closure; end -- Task specifics local Task = {} setmetatable(Task, { __call = function(self, ...) return self:create(...); end, }); local Task_mt = { __index = Task, } function Task.init(self, aroutine, ...) local obj = { routine = coroutine.create(aroutine), } setmetatable(obj, Task_mt); obj:setParams({...}); return obj end function Task.create(self, aroutine, ...) -- The 'aroutine' should be something that is callable -- either a function, or a table with a meta '__call' -- implementation. Checking with type == 'function' -- is not good enough as it will miss the meta __call cases return self:init(aroutine, ...) end function Task.getStatus(self) return coroutine.status(self.routine); end -- A function that can be used as a predicate function Task.isFinished(self) return task:getStatus() == "dead" end function Task.setParams(self, params) self.params = params return self; end function Task.resume(self) --print("Task, RESUMING: ", unpack(self.params)); return coroutine.resume(self.routine, unpack(self.params)); end function Task.yield(self, ...) return coroutine.yield(...) end -- kernel state local ContinueRunning = true; local TaskID = 0; local TasksSuspendedForSignal = {}; local TasksReadyToRun = Queue(); local CurrentTask = nil; -- Scheduler Related local function tasksPending() return TasksReadyToRun:length(); end -- put a task on the ready list -- the 'task' should be something that can be executed, -- whether it's a function, functor, or something that has a '__call' -- metamethod implemented. -- The 'params' is a table of parameters which will be passed to the function -- when it's ready to run. local function scheduleTask(task, params) --print("Scheduler.scheduleTask: ", task, params) params = params or {} if not task then return false, "no task specified" end task:setParams(params); TasksReadyToRun:enqueue(task); task.state = "readytorun" return task; end local function removeTask(tsk) --print("REMOVING DEAD FIBER: ", fiber); return true; end local function inMainFiber() return coroutine.running() == nil; end local function getCurrentTask() return CurrentTask; end local function suspendCurrentTask(...) CurrentTask.state = "suspended" end local function SchedulerStep() -- Now check the regular fibers local task = TasksReadyToRun:dequeue() -- If no fiber in ready queue, then just return if task == nil then --print("Scheduler.step: NO TASK") return true end if task:getStatus() == "dead" then removeFiber(task) return true; end -- If the task we pulled off the active list is -- not dead, then perhaps it is suspended. If that's true -- then it needs to drop out of the active list. -- We assume that some other part of the system is responsible for -- keeping track of the task, and rescheduling it when appropriate. if task.state == "suspended" then --print("suspended task wants to run") return true; end -- If we have gotten this far, then the task truly is ready to -- run, and it should be set as the currentFiber, and its coroutine -- is resumed. CurrentTask = task; local results = {task:resume()}; -- once we get results back from the resume, one -- of two things could have happened. -- 1) The routine exited normally -- 2) The routine yielded -- -- In both cases, we parse out the results of the resume -- into a success indicator and the rest of the values returned -- from the routine --local pcallsuccess = results[1]; --table.remove(results,1); local success = results[1]; table.remove(results,1); --print("PCALL, RESUME: ", pcallsuccess, success) -- no task is currently executing CurrentTask = nil; if not success then print("RESUME ERROR") print(unpack(results)); end -- Again, check to see if the task is dead after -- the most recent resume. If it's dead, then don't -- bother putting it back into the readytorun queue -- just remove the task from the list of tasks if task:getStatus() == "dead" then removeTask(task) return true; end -- The only way the task will get back onto the readylist -- is if it's state is 'readytorun', otherwise, it will -- stay out of the readytorun list. if task.state == "readytorun" then scheduleTask(task, results); end end -- Kernel specific routines local function getNewTaskID() TaskID = TaskID + 1; return TaskID; end local function getCurrentTaskID() return getCurrentTask().TaskID; end local function spawn(func, ...) local task = Task(func, ...) task.TaskID = getNewTaskID(); scheduleTask(task, {...}); return task; end local function suspend(...) suspendCurrentTask(); return yield(...) end local function yield(...) return coroutine.yield(...); end local function signalOne(eventName, ...) if not TasksSuspendedForSignal[eventName] then return false, "event not registered", eventName end local nTasks = #TasksSuspendedForSignal[eventName] if nTasks < 1 then return false, "no tasks waiting for event" end local suspended = TasksSuspendedForSignal[eventName][1]; scheduleTask(suspended,{...}); table.remove(TasksSuspendedForSignal[eventName], 1); return true; end local function signalAll(eventName, ...) if not TasksSuspendedForSignal[eventName] then return false, "event not registered" end local nTasks = #TasksSuspendedForSignal[eventName] if nTasks < 1 then return false, "no tasks waiting for event" end for i=1,nTasks do scheduleTask(TasksSuspendedForSignal[eventName][1],{...}); table.remove(TasksSuspendedForSignal[eventName], 1); end return true; end local function waitForSignal(eventName) local cTask = getCurrentTask(); if cTask == nil then return false, "not currently in a running task" end if not TasksSuspendedForSignal[eventName] then TasksSuspendedForSignal[eventName] = {} end table.insert(TasksSuspendedForSignal[eventName], cTask); return suspend() end local function onSignal(self, func, eventName) local function closure() waitForSignal(eventName) func(); end return spawn(closure) end local function run(func, ...) if func ~= nil then spawn(func, ...) end while (ContinueRunning) do SchedulerStep(); end end local function halt(self) ContinueRunning = false; end local exports = { halt = halt; run = run; spawn = spawn; suspend = suspend; yield = yield; onSignal = onSignal; signalAll = signalAll; signalOne = signalOne; waitForSignal = waitForSignal; } -- put everything into the global namespace by default for k,v in pairs(exports) do _G[k] = v; end return exports;
mit
Ninjistix/darkstar
scripts/zones/QuBia_Arena/bcnms/rank_5_mission.lua
5
1961
----------------------------------- -- Area: Qu'Bia Arena -- NPC: Mission Rank 5 -- !pos -221 -24 19 206 ----------------------------------- package.loaded["scripts/zones/QuBia_Arena/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/QuBia_Arena/TextIDs"); ----------------------------------- require("scripts/globals/keyitems"); -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:hasKeyItem(NEW_FEIYIN_SEAL)) then player:startEvent(32001,1,1,1,instance:getTimeInside(),1,0,0); else -- Gives skip dialogue if previously completed player:startEvent(32001,1,1,1,instance:getTimeInside(),1,0,1); end elseif (leavecode == 4) then player:startEvent(32002); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 32001) then if (player:hasKeyItem(NEW_FEIYIN_SEAL)) then player:addKeyItem(BURNT_SEAL); player:messageSpecial(KEYITEM_OBTAINED,BURNT_SEAL); player:setVar("MissionStatus",12); player:delKeyItem(NEW_FEIYIN_SEAL); end; end; end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/The_Shrouded_Maw/bcnms/waking_dreams.lua
5
1875
----------------------------------- -- Area: The_Shrouded_Maw -- Name: waking_dreams ----------------------------------- package.loaded["scripts/zones/The_Shrouded_Maw/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Shrouded_Maw/TextIDs"); require("scripts/zones/The_Shrouded_Maw/MobIDs"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/status"); require("scripts/globals/titles"); -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) -- "close" all floor tiles local inst = player:getBattlefieldID(); local tile = DARKNESS_NAMED_TILE_OFFSET + (inst - 1) * 8; for i = tile, tile + 7 do GetNPCByID(i):setAnimation(ANIMATION_CLOSE_DOOR); end end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:hasKeyItem(VIAL_OF_DREAM_INCENSE)) then player:delKeyItem(VIAL_OF_DREAM_INCENSE); player:addKeyItem(WHISPER_OF_DREAMS); player:messageSpecial(KEYITEM_OBTAINED,WHISPER_OF_DREAMS); end player:addTitle(HEIR_TO_THE_REALM_OF_DREAMS); player:startEvent(32002); elseif (leavecode == 4) then player:startEvent(32002); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
gpl-3.0
mandersan/premake-core
binmodules/luasocket/test/httptest.lua
25
11462
-- 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))
bsd-3-clause
Ninjistix/darkstar
scripts/globals/spells/armys_paeon_v.lua
5
1338
----------------------------------------- -- Spell: Army's Paeon V -- Gradually restores target's HP. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 5; if (sLvl+iLvl > 350) then power = power + 1; end local iBoost = caster:getMod(MOD_PAEON_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_PAEON,power,0,duration,caster:getID(), 0, 5)) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end return EFFECT_PAEON; end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/spells/bluemagic/power_attack.lua
33
1732
----------------------------------------- -- Spell: Power Attack -- Deals critical damage. Chance of critical hit varies with TP -- Spell cost: 5 MP -- Monster Type: Vermin -- Spell Type: Physical (Blunt) -- Blue Magic Points: 1 -- Stat Bonus: MND+1 -- Level: 4 -- Casting Time: 0.5 seconds -- Recast Time: 7.25 seconds -- Skillchain property: Reverberation (Can open Impaction or Induration) -- Combos: Plantoid Killer ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_CRITICAL; params.dmgtype = DMGTYPE_BLUNT; params.scattr = SC_REVERBERATION; params.numhits = 1; params.multiplier = 1.125; params.tp150 = 0.5; params.tp300 = 0.7; params.azuretp = 0.8; params.duppercap = 11; -- guesstimated crit %s for TP params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.3; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Jugner_Forest_[S]/mobs/Lobison.lua
7
1454
----------------------------------- -- Area: Jugner Forest (S) -- NPC: Lobison ----------------------------------- function onMobSpawn(mob) mob:setLocalVar("transformTime", os.time()) end; function onMobRoam(mob) local changeTime = mob:getLocalVar("transformTime"); local roamChance = math.random(1,100); local roamMoonPhase = VanadielMoonPhase(); if (roamChance > 100-roamMoonPhase) then if (mob:AnimationSub() == 0 and os.time() - changeTime > 300) then mob:AnimationSub(1); mob:setLocalVar("transformTime", os.time()); elseif (mob:AnimationSub() == 1 and os.time() - changeTime > 300) then mob:AnimationSub(0); mob:setLocalVar("transformTime", os.time()); end end end; -- Change forms every 60 seconds function onMobEngaged(mob,target) local changeTime = mob:getLocalVar("changeTime"); local chance = math.random(1,100); local moonPhase = VanadielMoonPhase(); if (chance > 100-moonPhase) then if (mob:AnimationSub() == 0 and mob:getBattleTime() - changeTime > 45) then mob:AnimationSub(1); mob:setLocalVar("changeTime", mob:getBattleTime()); elseif (mob:AnimationSub() == 1 and mob:getBattleTime() - changeTime > 45) then mob:AnimationSub(0); mob:setLocalVar("changeTime", mob:getBattleTime()); end end end; function onMobDeath(mob, player, isKiller) end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Norg/npcs/Ranemaud.lua
5
3420
----------------------------------- -- Area: Norg -- NPC: Ranemaud -- Involved in Quest: Forge Your Destiny, The Sacred Katana -- !pos 15 0 23 252 ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Norg/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) questItem = player:getVar("ForgeYourDestiny_Event"); checkItem = testflag(tonumber(questItem),0x02); if (checkItem == true) then if (trade:hasItemQty(738,1) and trade:hasItemQty(737,2) and trade:getItemCount() == 3) then player:startEvent(43,0,0,738,737); -- Platinum Ore, Gold Ore end end if (player:getQuestStatus(OUTLANDS,THE_SACRED_KATANA) == QUEST_ACCEPTED and player:hasItem(17809) == false) then if (trade:getGil() == 30000 and trade:getItemCount() == 1 and player:getFreeSlotsCount() >= 1) then player:startEvent(145); end end end; ----------------------------------- -- Event Check ----------------------------------- function testflag(set,flag) return (set % (2*flag) >= flag) end; function onTrigger(player,npc) swordTimer = player:getVar("ForgeYourDestiny_timer") if (player:getQuestStatus(OUTLANDS,FORGE_YOUR_DESTINY) == QUEST_ACCEPTED and swordTimer == 0) then if (player:hasItem(1153)) then player:startEvent(48,1153); -- Sacred Branch elseif (player:hasItem(1198) == false) then questItem = player:getVar("ForgeYourDestiny_Event"); checkItem = testflag(tonumber(questItem),0x02); if (checkItem == false) then player:startEvent(40,1153,1198); -- Sacred Branch, Sacred Sprig elseif (checkItem == true) then player:startEvent(42,0,0,738,737); -- Platinum Ore, Gold Ore end elseif (player:hasItem(1198)) then -- Sacred Sprig player:startEvent(41); end elseif (player:getQuestStatus(OUTLANDS,THE_SACRED_KATANA) == QUEST_ACCEPTED and player:hasItem(17809) == false) then player:startEvent(144); else player:startEvent(68); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); questItem = player:getVar("ForgeYourDestiny_Event"); if (csid == 40) then if (player:getFreeSlotsCount(0) >= 1) then player:addItem(1198); player:messageSpecial(ITEM_OBTAINED, 1198); -- Sacred Sprig player:setVar("ForgeYourDestiny_Event",questItem + 0x02); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1151); -- Oriental Steel end elseif (csid == 43) then if (player:getFreeSlotsCount(0) >= 1) then player:tradeComplete(); player:addItem(1198); player:messageSpecial(ITEM_OBTAINED, 1198); -- Sacred Sprig else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1198); -- Sacred Sprig end elseif (csid == 145) then player:tradeComplete(); player:addItem(17809); player:messageSpecial(ITEM_OBTAINED,17809); -- Mumeito end end;
gpl-3.0
Xanthin/sea
seacobble/init.lua
1
5115
-- Boilerplate to support localized strings if intllib mod is installed. local S if minetest.get_modpath("intllib") then S = intllib.Getter() else S = function(s) return s end end -- NODES minetest.register_node("seacobble:seacobble", { description = S("Sea cobblestone"), tiles = {"seacobble_seacobble.png"}, is_ground_content = true, groups = {cracky=3, stone=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("seacobble:seacobble_cyan", { description = S("Sea cobblestone cyan"), tiles = {"seacobble_seacobble_cyan.png"}, is_ground_content = true, groups = {cracky=3, stone=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("seacobble:seacobble_magenta", { description = S("Sea cobblestone magenta"), tiles = {"seacobble_seacobble_magenta.png"}, is_ground_content = true, groups = {cracky=3, stone=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("seacobble:seacobble_lime", { description = S("Sea cobblestone lime"), tiles = {"seacobble_seacobble_lime.png"}, is_ground_content = true, groups = {cracky=3, stone=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("seacobble:seacobble_aqua", { description = S("Sea cobblestone aqua"), tiles = {"seacobble_seacobble_aqua.png"}, is_ground_content = true, groups = {cracky=3, stone=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("seacobble:seacobble_skyblue", { description = S("Sea cobblestone skyblue"), tiles = {"seacobble_seacobble_skyblue.png"}, is_ground_content = true, groups = {cracky=3, stone=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("seacobble:seacobble_redviolet", { description = S("Sea cobblestone redviolet"), tiles = {"seacobble_seacobble_redviolet.png"}, is_ground_content = true, groups = {cracky=3, stone=2}, sounds = default.node_sound_stone_defaults(), }) -- STAIRS stairs.register_stair_and_slab("seacobble", "seacobble:seacobble", {cracky=3, stone=2}, {"seacobble_seacobble.png"}, S("Seacobble stair"), S("Seacobble slab"), default.node_sound_stone_defaults()) stairs.register_stair_and_slab("seacobble_cyan", "seacobble:seacobble_cyan", {cracky=3, stone=2}, {"seacobble_seacobble_cyan.png"}, S("Seacobble stair cyan"), S("Seacobble slab cyan"), default.node_sound_stone_defaults()) stairs.register_stair_and_slab("seacobble_magenta", "seacobble:seacobble_magenta", {cracky=3, stone=2}, {"seacobble_seacobble_magenta.png"}, S("Seacobble stair magenta"), S("Seacobble slab magenta"), default.node_sound_stone_defaults()) stairs.register_stair_and_slab("seacobble_lime", "seacobble:seacobble_lime", {cracky=3, stone=2}, {"seacobble_seacobble_lime.png"}, S("Seacobble stair lime"), S("Seacobble slab lime"), default.node_sound_stone_defaults()) stairs.register_stair_and_slab("seacobble_aqua", "seacobble:seacobble_aqua", {cracky=3, stone=2}, {"seacobble_seacobble_aqua.png"}, S("Seacobble stair aqua"), S("Seacobble slab aqua"), default.node_sound_stone_defaults()) stairs.register_stair_and_slab("seacobble_skyblue", "seacobble:seacobble_skyblue", {cracky=3, stone=2}, {"seacobble_seacobble_skyblue.png"}, S("Seacobble stair skyblue"), S("Seacobble slab skyblue"), default.node_sound_stone_defaults()) stairs.register_stair_and_slab("seacobble_redviolet", "seacobble:seacobble_redviolet", {cracky=3, stone=2}, {"seacobble_seacobble_redviolet.png"}, S("Seacobble stair redviolet"), S("Seacobble slab redviolet"), default.node_sound_stone_defaults()) -- CRAFTING local register_seacobble_craft = function(output,recipe) minetest.register_craft({ type = 'shapeless', output = output, recipe = recipe, }) end register_seacobble_craft("seacobble:seacobble", {'clams:crushedwhite', 'default:cobble'}) register_seacobble_craft("seacobble:seacobble_cyan", {'seacobble:seacobble', 'dye:cyan'}) register_seacobble_craft("seacobble:seacobble_magenta", {'seacobble:seacobble', 'dye:magenta'}) register_seacobble_craft("seacobble:seacobble_lime", {'seacobble:seacobble', 'dye:lime'}) register_seacobble_craft("seacobble:seacobble_aqua", {'seacobble:seacobble', 'dye:aqua'}) register_seacobble_craft("seacobble:seacobble_skyblue", {'seacobble:seacobble', 'dye:skyblue'}) register_seacobble_craft("seacobble:seacobble_redviolet", {'seacobble:seacobble', 'dye:redviolet'}) register_seacobble_craft("seacobble:seacobble_cyan", {'clams:crushedwhite', 'default:cobble','dye:cyan'}) register_seacobble_craft("seacobble:seacobble_magenta", {'clams:crushedwhite', 'default:cobble','dye:magenta'}) register_seacobble_craft("seacobble:seacobble_lime", {'clams:crushedwhite', 'default:cobble','dye:lime'}) register_seacobble_craft("seacobble:seacobble_aqua", {'clams:crushedwhite', 'default:cobble','dye:aqua'}) register_seacobble_craft("seacobble:seacobble_skyblue", {'clams:crushedwhite', 'default:cobble','dye:skyblue'}) register_seacobble_craft("seacobble:seacobble_redviolet", {'clams:crushedwhite', 'default:cobble','dye:redviolet'})
gpl-3.0
Ninjistix/darkstar
scripts/zones/Port_Bastok/npcs/Evelyn.lua
5
1198
----------------------------------- -- Area: Port Bastok -- NPC: Evelyn -- Only sells when Bastok controlls Gustaberg Region -- Confirmed shop stock, August 2013 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_Bastok/TextIDs"); require("scripts/globals/conquest"); require("scripts/globals/shop"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local RegionOwner = GetRegionOwner(GUSTABERG); if (RegionOwner ~= NATION_BASTOK) then player:showText(npc,EVELYN_CLOSED_DIALOG); else player:showText(npc,EVELYN_OPEN_DIALOG); local stock = { 1108, 703, -- Sulfur 619, 43, -- Popoto 611, 36, -- Rye Flour 4388, 40 -- Eggplant } showShop(player,BASTOK,stock); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
neilbu/osrm-backend
profiles/lib/way_handlers.lua
1
20221
-- Profile handlers dealing with various aspects of tag parsing -- -- You can run a selection you find useful in your profile, -- or do you own processing if/when required. local get_turn_lanes = require("lib/guidance").get_turn_lanes local set_classification = require("lib/guidance").set_classification local get_destination = require("lib/destination").get_destination local Tags = require('lib/tags') WayHandlers = {} -- check that way has at least one tag that could imply routability- -- we store the checked tags in data, to avoid fetching again later function WayHandlers.tag_prefetch(profile,way,result,data) for key,v in pairs(profile.prefetch) do data[key] = way:get_value_by_key( key ) end return next(data) ~= nil end -- set default mode function WayHandlers.default_mode(profile,way,result,data) result.forward_mode = profile.default_mode result.backward_mode = profile.default_mode end -- handles name, including ref and pronunciation function WayHandlers.names(profile,way,result,data) -- parse the remaining tags local name = way:get_value_by_key("name") local pronunciation = way:get_value_by_key("name:pronunciation") local ref = way:get_value_by_key("ref") local exits = way:get_value_by_key("junction:ref") -- Set the name that will be used for instructions if name then result.name = name end if ref then result.ref = canonicalizeStringList(ref, ";") end if pronunciation then result.pronunciation = pronunciation end if exits then result.exits = canonicalizeStringList(exits, ";") end end -- junctions function WayHandlers.roundabouts(profile,way,result,data) local junction = way:get_value_by_key("junction"); if junction == "roundabout" then result.roundabout = true end -- See Issue 3361: roundabout-shaped not following roundabout rules. -- This will get us "At Strausberger Platz do Maneuver X" instead of multiple quick turns. -- In a new API version we can think of having a separate type passing it through to the user. if junction == "circular" then result.circular = true end end -- determine if this way can be used as a start/end point for routing function WayHandlers.startpoint(profile,way,result,data) -- if profile specifies set of allowed start modes, then check for that -- otherwise require default mode if profile.allowed_start_modes then result.is_startpoint = profile.allowed_start_modes[result.forward_mode] == true or profile.allowed_start_modes[result.backward_mode] == true else result.is_startpoint = result.forward_mode == profile.default_mode or result.backward_mode == profile.default_mode end end -- handle turn lanes function WayHandlers.turn_lanes(profile,way,result,data) local forward, backward = get_turn_lanes(way,data) if forward then result.turn_lanes_forward = forward end if backward then result.turn_lanes_backward = backward end end -- set the road classification based on guidance globals configuration function WayHandlers.classification(profile,way,result,data) set_classification(data.highway,result,way) end -- handle destination tags function WayHandlers.destinations(profile,way,result,data) if data.is_forward_oneway or data.is_reverse_oneway then local destination = get_destination(way, data.is_forward_oneway) result.destinations = canonicalizeStringList(destination, ",") end end -- handling ferries and piers function WayHandlers.ferries(profile,way,result,data) local route = data.route if route then local route_speed = profile.route_speeds[route] if route_speed and route_speed > 0 then local duration = way:get_value_by_key("duration") if duration and durationIsValid(duration) then result.duration = math.max( parseDuration(duration), 1 ) end result.forward_mode = mode.ferry result.backward_mode = mode.ferry result.forward_speed = route_speed result.backward_speed = route_speed end end end -- handling movable bridges function WayHandlers.movables(profile,way,result,data) local bridge = data.bridge if bridge then local bridge_speed = profile.bridge_speeds[bridge] if bridge_speed and bridge_speed > 0 then local capacity_car = way:get_value_by_key("capacity:car") if capacity_car ~= 0 then result.forward_mode = profile.default_mode result.backward_mode = profile.default_mode local duration = way:get_value_by_key("duration") if duration and durationIsValid(duration) then result.duration = math.max( parseDuration(duration), 1 ) else result.forward_speed = bridge_speed result.backward_speed = bridge_speed end end end end end -- service roads function WayHandlers.service(profile,way,result,data) local service = way:get_value_by_key("service") if service then -- Set don't allow access to certain service roads if profile.service_tag_forbidden[service] then result.forward_mode = mode.inaccessible result.backward_mode = mode.inaccessible return false end end end -- all lanes restricted to hov vehicles? function WayHandlers.has_all_designated_hov_lanes(lanes) if not lanes then return false end -- This gmatch call effectively splits the string on | chars. -- we append an extra | to the end so that we can match the final part for lane in (lanes .. '|'):gmatch("([^|]*)|") do if lane and lane ~= "designated" then return false end end return true end -- handle high occupancy vehicle tags function WayHandlers.hov(profile,way,result,data) -- respect user-preference for HOV if not profile.avoid.hov_lanes then return end local hov = way:get_value_by_key("hov") if "designated" == hov then result.forward_restricted = true result.backward_restricted = true end data.hov_lanes_forward, data.hov_lanes_backward = Tags.get_forward_backward_by_key(way,data,'hov:lanes') local all_hov_forward = WayHandlers.has_all_designated_hov_lanes(data.hov_lanes_forward) local all_hov_backward = WayHandlers.has_all_designated_hov_lanes(data.hov_lanes_backward) -- in this case we will use turn penalties instead of filtering out if profile.properties.weight_name == 'routability' then if (all_hov_forward) then result.forward_restricted = true end if (all_hov_backward) then result.backward_restricted = true end return end -- filter out ways where all lanes are hov only if all_hov_forward then result.forward_mode = mode.inaccessible end if all_hov_backward then result.backward_mode = mode.inaccessible end end -- check accessibility by traversing our access tag hierarchy function WayHandlers.access(profile,way,result,data) data.forward_access, data.backward_access = Tags.get_forward_backward_by_set(way,data,profile.access_tags_hierarchy) -- only allow a subset of roads that are marked as restricted if profile.restricted_highway_whitelist[data.highway] then if profile.restricted_access_tag_list[data.forward_access] then result.forward_restricted = true end if profile.restricted_access_tag_list[data.backward_access] then result.backward_restricted = true end end if profile.access_tag_blacklist[data.forward_access] and not result.forward_restricted then result.forward_mode = mode.inaccessible end if profile.access_tag_blacklist[data.backward_access] and not result.backward_restricted then result.backward_mode = mode.inaccessible end if result.forward_mode == mode.inaccessible and result.backward_mode == mode.inaccessible then return false end end -- handle speed (excluding maxspeed) function WayHandlers.speed(profile,way,result,data) if result.forward_speed ~= -1 then return -- abort if already set, eg. by a route end local key,value,speed = Tags.get_constant_by_key_value(way,profile.speeds) if speed then -- set speed by way type result.forward_speed = speed result.backward_speed = speed else -- Set the avg speed on ways that are marked accessible if profile.access_tag_whitelist[data.forward_access] then result.forward_speed = profile.default_speed elseif data.forward_access and not profile.access_tag_blacklist[data.forward_access] then result.forward_speed = profile.default_speed -- fallback to the avg speed if access tag is not blacklisted elseif not data.forward_access and data.backward_access then result.forward_mode = mode.inaccessible end if profile.access_tag_whitelist[data.backward_access] then result.backward_speed = profile.default_speed elseif data.backward_access and not profile.access_tag_blacklist[data.backward_access] then result.backward_speed = profile.default_speed -- fallback to the avg speed if access tag is not blacklisted elseif not data.backward_access and data.forward_access then result.backward_mode = mode.inaccessible end end if result.forward_speed == -1 and result.backward_speed == -1 and result.duration <= 0 then return false end end -- add class information function WayHandlers.classes(profile,way,result,data) local forward_toll, backward_toll = Tags.get_forward_backward_by_key(way, data, "toll") local forward_route, backward_route = Tags.get_forward_backward_by_key(way, data, "route") if forward_toll == "yes" then result.forward_classes["toll"] = true end if backward_toll == "yes" then result.backward_classes["toll"] = true end if forward_route == "ferry" then result.forward_classes["ferry"] = true end if backward_route == "ferry" then result.backward_classes["ferry"] = true end if result.forward_restricted then result.forward_classes["restricted"] = true end if result.backward_restricted then result.backward_classes["restricted"] = true end if data.highway == "motorway" or data.highway == "motorway_link" then result.forward_classes["motorway"] = true result.backward_classes["motorway"] = true end end -- reduce speed on bad surfaces function WayHandlers.surface(profile,way,result,data) local surface = way:get_value_by_key("surface") local tracktype = way:get_value_by_key("tracktype") local smoothness = way:get_value_by_key("smoothness") if surface and profile.surface_speeds[surface] then result.forward_speed = math.min(profile.surface_speeds[surface], result.forward_speed) result.backward_speed = math.min(profile.surface_speeds[surface], result.backward_speed) end if tracktype and profile.tracktype_speeds[tracktype] then result.forward_speed = math.min(profile.tracktype_speeds[tracktype], result.forward_speed) result.backward_speed = math.min(profile.tracktype_speeds[tracktype], result.backward_speed) end if smoothness and profile.smoothness_speeds[smoothness] then result.forward_speed = math.min(profile.smoothness_speeds[smoothness], result.forward_speed) result.backward_speed = math.min(profile.smoothness_speeds[smoothness], result.backward_speed) end end -- scale speeds to get better average driving times function WayHandlers.penalties(profile,way,result,data) -- heavily penalize a way tagged with all HOV lanes -- in order to only route over them if there is no other option local service_penalty = 1.0 local service = way:get_value_by_key("service") if service and profile.service_penalties[service] then service_penalty = profile.service_penalties[service] end local width_penalty = 1.0 local width = math.huge local lanes = math.huge local width_string = way:get_value_by_key("width") if width_string and tonumber(width_string:match("%d*")) then width = tonumber(width_string:match("%d*")) end local lanes_string = way:get_value_by_key("lanes") if lanes_string and tonumber(lanes_string:match("%d*")) then lanes = tonumber(lanes_string:match("%d*")) end local is_bidirectional = result.forward_mode ~= mode.inaccessible and result.backward_mode ~= mode.inaccessible if width <= 3 or (lanes <= 1 and is_bidirectional) then width_penalty = 0.5 end -- Handle high frequency reversible oneways (think traffic signal controlled, changing direction every 15 minutes). -- Scaling speed to take average waiting time into account plus some more for start / stop. local alternating_penalty = 1.0 if data.oneway == "alternating" then alternating_penalty = 0.4 end local sideroad_penalty = 1.0 data.sideroad = way:get_value_by_key("side_road") if "yes" == data.sideroad or "rotary" == data.sideroad then sideroad_penalty = profile.side_road_multiplier end local forward_penalty = math.min(service_penalty, width_penalty, alternating_penalty, sideroad_penalty) local backward_penalty = math.min(service_penalty, width_penalty, alternating_penalty, sideroad_penalty) if profile.properties.weight_name == 'routability' then if result.forward_speed > 0 then result.forward_rate = (result.forward_speed * forward_penalty) / 3.6 end if result.backward_speed > 0 then result.backward_rate = (result.backward_speed * backward_penalty) / 3.6 end if result.duration > 0 then result.weight = result.duration / forward_penalty end end end -- maxspeed and advisory maxspeed function WayHandlers.maxspeed(profile,way,result,data) local keys = Sequence { 'maxspeed:advisory', 'maxspeed' } local forward, backward = Tags.get_forward_backward_by_set(way,data,keys) forward = WayHandlers.parse_maxspeed(forward,profile) backward = WayHandlers.parse_maxspeed(backward,profile) if forward and forward > 0 then result.forward_speed = forward * profile.speed_reduction end if backward and backward > 0 then result.backward_speed = backward * profile.speed_reduction end end function WayHandlers.parse_maxspeed(source,profile) if not source then return 0 end local n = tonumber(source:match("%d*")) if n then if string.match(source, "mph") or string.match(source, "mp/h") then n = (n*1609)/1000 end else -- parse maxspeed like FR:urban source = string.lower(source) n = profile.maxspeed_table[source] if not n then local highway_type = string.match(source, "%a%a:(%a+)") n = profile.maxspeed_table_default[highway_type] if not n then n = 0 end end end return n end -- handle oneways tags function WayHandlers.oneway(profile,way,result,data) if not profile.oneway_handling then return end local oneway if profile.oneway_handling == true then oneway = Tags.get_value_by_prefixed_sequence(way,profile.restrictions,'oneway') or way:get_value_by_key("oneway") elseif profile.oneway_handling == 'specific' then oneway = Tags.get_value_by_prefixed_sequence(way,profile.restrictions,'oneway') elseif profile.oneway_handling == 'conditional' then -- Following code assumes that `oneway` and `oneway:conditional` tags have opposite values and takes weakest (always `no`). -- So if we will have: -- oneway=yes, oneway:conditional=no @ (condition1) -- oneway=no, oneway:conditional=yes @ (condition2) -- condition1 will be always true and condition2 will be always false. if way:get_value_by_key("oneway:conditional") then oneway = "no" else oneway = Tags.get_value_by_prefixed_sequence(way,profile.restrictions,'oneway') or way:get_value_by_key("oneway") end end data.oneway = oneway if oneway == "-1" then data.is_reverse_oneway = true result.forward_mode = mode.inaccessible elseif oneway == "yes" or oneway == "1" or oneway == "true" then data.is_forward_oneway = true result.backward_mode = mode.inaccessible elseif profile.oneway_handling == true then local junction = way:get_value_by_key("junction") if data.highway == "motorway" or junction == "roundabout" or junction == "circular" then if oneway ~= "no" then -- implied oneway data.is_forward_oneway = true result.backward_mode = mode.inaccessible end end end end function WayHandlers.weights(profile,way,result,data) if profile.properties.weight_name == 'distance' then result.weight = -1 -- set weight rates to 1 for the distance weight, edge weights are distance / rate if (result.forward_mode ~= mode.inaccessible and result.forward_speed > 0) then result.forward_rate = 1 end if (result.backward_mode ~= mode.inaccessible and result.backward_speed > 0) then result.backward_rate = 1 end end end -- handle various that can block access function WayHandlers.blocked_ways(profile,way,result,data) -- areas if profile.avoid.area and way:get_value_by_key("area") == "yes" then return false end -- toll roads if profile.avoid.toll and way:get_value_by_key("toll") == "yes" then return false end -- don't route over steps if profile.avoid.steps and data.highway == "steps" then return false end -- construction -- TODO if highway is valid then we shouldn't check railway, and vica versa if profile.avoid.construction and (data.highway == 'construction' or way:get_value_by_key('railway') == 'construction') then return false end -- In addition to the highway=construction tag above handle the construction=* tag -- http://wiki.openstreetmap.org/wiki/Key:construction -- https://taginfo.openstreetmap.org/keys/construction#values if profile.avoid.construction then local construction = way:get_value_by_key('construction') -- Of course there are negative tags to handle, too if construction and not profile.construction_whitelist[construction] then return false end end -- Not only are there multiple construction tags there is also a proposed=* tag. -- http://wiki.openstreetmap.org/wiki/Key:proposed -- https://taginfo.openstreetmap.org/keys/proposed#values if profile.avoid.proposed and way:get_value_by_key('proposed') then return false end -- Reversible oneways change direction with low frequency (think twice a day): -- do not route over these at all at the moment because of time dependence. -- Note: alternating (high frequency) oneways are handled below with penalty. if profile.avoid.reversible and way:get_value_by_key("oneway") == "reversible" then return false end -- impassables if profile.avoid.impassable then if way:get_value_by_key("impassable") == "yes" then return false end if way:get_value_by_key("status") == "impassable" then return false end end end function WayHandlers.driving_side(profile, way, result, data) local driving_side = way:get_value_by_key('driving_side') if driving_side == nil then driving_side = way:get_location_tag('driving_side') end if driving_side == 'left' then result.is_left_hand_driving = true elseif driving_side == 'right' then result.is_left_hand_driving = false else result.is_left_hand_driving = profile.properties.left_hand_driving end end -- Call a sequence of handlers, aborting in case a handler returns false. Example: -- -- handlers = Sequence { -- WayHandlers.tag_prefetch, -- WayHandlers.default_mode, -- WayHandlers.blocked_ways, -- WayHandlers.access, -- WayHandlers.speed, -- WayHandlers.names -- } -- -- WayHandlers.run(handlers,way,result,data,profile) -- -- Each method in the list will be called on the WayHandlers object. -- All handlers must accept the parameteres (profile, way, result, data, relations) and return false -- if the handler chain should be aborted. -- To ensure the correct order of method calls, use a Sequence of handler names. function WayHandlers.run(profile, way, result, data, handlers, relations) for i,handler in ipairs(handlers) do if handler(profile, way, result, data, relations) == false then return false end end end return WayHandlers
bsd-2-clause
Ninjistix/darkstar
scripts/zones/Selbina/npcs/Vuntar.lua
5
2895
----------------------------------- -- Area: Selbina -- NPC: Vuntar -- Starts and Finishes Quest: Cargo (R) -- !pos 7 -2 -15 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(OTHER_AREAS,CARGO) ~= QUEST_AVAILABLE) then realday = tonumber(os.date("%j")); -- %M for next minute, %j for next real day starttime = player:getVar("VuntarCanBuyItem_date"); if (realday ~= starttime) then if (trade:hasItemQty(4529,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then player:startEvent(52,1); -- Can Buy rolanberry (881 ce) elseif (trade:hasItemQty(4530,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then player:startEvent(52,2); -- Can Buy rolanberry (874 ce) elseif (trade:hasItemQty(4531,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then player:startEvent(52,3); -- Can Buy rolanberry (864 ce) end else player:startEvent(1134,4365); -- Can't buy rolanberrys end end end; function onTrigger(player,npc) if (player:getMainLvl() >= 20 and player:getQuestStatus(OTHER_AREAS,CARGO) == QUEST_AVAILABLE) then player:startEvent(50,4365); -- Start quest "Cargo" elseif (player:getMainLvl() < 20) then player:startEvent(53); -- Dialog for low level or low fame else player:startEvent(51,4365); -- During & after completed quest "Cargo" end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 50) then player:addQuest(OTHER_AREAS,CARGO); elseif (csid == 52) then player:setVar("VuntarCanBuyItem_date", os.date("%j")); -- %M for next minute, %j for next real day if (player:getQuestStatus(OTHER_AREAS,CARGO) == QUEST_ACCEPTED) then player:completeQuest(OTHER_AREAS,CARGO); player:addFame(OTHER_AREAS,30); end if (option == 1) then player:addGil(800); player:messageSpecial(GIL_OBTAINED,800); player:tradeComplete(); elseif (option == 2) then player:addGil(2000); player:messageSpecial(GIL_OBTAINED,2000); player:tradeComplete(); elseif (option == 3) then player:addGil(3000); player:messageSpecial(GIL_OBTAINED,3000); player:tradeComplete(); end end end;
gpl-3.0