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
uonline/debut
src/day2/act2/barracks_hall.room.lua
1
2654
barracks_hall = room { nam = 'Коридор штаба'; dsc = [[ Ты стоишь посреди просторного коридора, освещённого пламенем многочисленных факелов. Прямо перед тобой на стене висит знамя Режима Ремана. Ты делаешь неутешительный вывод, что тебя доставили прямиком в городской штаб Режима -- место с кучей солдат, богоизбранных магов и парой твоих портретов с подписью "розыск". ^ К счастью, сейчас ещё раннее утро; солдаты и богоизбранные спят, портреты мирно пылятся на стенах. ]]; obj = { 'barracks_hall_flag'; 'barracks_hall_doors'; }; way = { 'barracks_armory'; 'barracks'; 'barracks_dance_floor'; }; } barracks_hall_flag = obj { nam = 'Флаг Режима'; dsc = [[ Блики факелов покорно лижут тёмно-зелёную материю {флага}, на которой вышит символ Режима -- серебристое око с древом вместо зрачка. ]]; act = [[ Ты рассматриваешь изображение на знамени. Корни древа берут начало из раскрытой книги. С самого начала твоей службы в рядах армии Режима это древо напоминало тебе песочные часы. Тебе нравилось думать, что они отсчитывают время до конца твоей солдатской жизни. Ты представлял, как каждый всколох ткани от ветра сцеживает невидимые песчинки на дно часов. ]]; }; barracks_hall_doors = obj { nam = 'Двери'; dsc = [[ Прямо под флагом красуется дверь с репликой щита и меча. Помимо неё здесь ещё {несколько дверей}. ]]; act = [[ Ты рассматриваешь двери по очереди. Та со щитом и мечом наверняка ведёт в арсенал. Реплика в виде ряда шлемов обозначает солдатские казармы. Половник и тесак -- кухню. Флаг -- главный зал. Остальные двери никак не отмечены. ]]; };
gpl-3.0
darkdukey/sdkbox-facebook-sample-v2
samples/Lua/TestLua/Resources/luaScript/ZwoptexTest/ZwoptexTest.lua
8
4465
local scheduler = CCDirector:sharedDirector():getScheduler() -------------------------------------------------------------------- -- -- ZwoptexGenericTest -- -------------------------------------------------------------------- local function ZwoptexGenericTest() local ret = createTestLayer("Zwoptex Tests", "Coordinate Formats, Rotation, Trimming, flipX/Y") local spriteFrameIndex = 0 local counter = 0 local s = CCDirector:sharedDirector():getWinSize() local schedulerEntry = nil local schedulerFlipSpriteEntry = nil local sprite1 = nil local sprite2 = nil local function onEnter() CCSpriteFrameCache:sharedSpriteFrameCache():addSpriteFramesWithFile("zwoptex/grossini.plist") CCSpriteFrameCache:sharedSpriteFrameCache():addSpriteFramesWithFile("zwoptex/grossini-generic.plist") local layer1 = CCLayerColor:create(ccc4(255, 0, 0, 255), 85, 121) layer1:setPosition(ccp(s.width/2-80 - (85.0 * 0.5), s.height/2 - (121.0 * 0.5))) ret:addChild(layer1) sprite1 = CCSprite:createWithSpriteFrame(CCSpriteFrameCache:sharedSpriteFrameCache():spriteFrameByName("grossini_dance_01.png")) sprite1:setPosition(ccp( s.width/2-80, s.height/2)) ret:addChild(sprite1) sprite1:setFlipX(false) sprite1:setFlipY(false) local layer2 = CCLayerColor:create(ccc4(255, 0, 0, 255), 85, 121) layer2:setPosition(ccp(s.width/2+80 - (85.0 * 0.5), s.height/2 - (121.0 * 0.5))) ret:addChild(layer2) sprite2 = CCSprite:createWithSpriteFrame(CCSpriteFrameCache:sharedSpriteFrameCache():spriteFrameByName("grossini_dance_generic_01.png")) sprite2:setPosition(ccp( s.width/2 + 80, s.height/2)) ret:addChild(sprite2) sprite2:setFlipX(false) sprite2:setFlipY(false) local function flipSprites(dt) counter = counter + 1 local fx = false local fy = false local i = counter % 4 if i == 0 then fx = false fy = false elseif i == 1 then fx = true fy = false elseif i == 2 then fx = false fy = true elseif i == 3 then fx = true fy = true end sprite1:setFlipX(fx) sprite2:setFlipX(fx) sprite1:setFlipY(fy) sprite2:setFlipY(fy) spriteFrameIndex = spriteFrameIndex + 1 if spriteFrameIndex > 14 then spriteFrameIndex = 1 end local str1 = string.format("grossini_dance_%02d.png", spriteFrameIndex) local str2 = string.format("grossini_dance_generic_%02d.png", spriteFrameIndex) sprite1:setDisplayFrame(CCSpriteFrameCache:sharedSpriteFrameCache():spriteFrameByName(str1)) sprite2:setDisplayFrame(CCSpriteFrameCache:sharedSpriteFrameCache():spriteFrameByName(str2)) end sprite1:retain() sprite2:retain() counter = 0 local function startIn05Secs(dt) scheduler:unscheduleScriptEntry(schedulerEntry) schedulerFlipSpriteEntry = scheduler:scheduleScriptFunc(flipSprites, 0.5, false) end schedulerEntry = scheduler:scheduleScriptFunc(startIn05Secs, 1.0, false) end local function onExit() if schedulerEntry ~= nil then scheduler:unscheduleScriptEntry(schedulerEntry) end if schedulerFlipSpriteEntry ~= nil then scheduler:unscheduleScriptEntry(schedulerFlipSpriteEntry) end sprite1:release() sprite2:release() local cache = CCSpriteFrameCache:sharedSpriteFrameCache() cache:removeSpriteFramesFromFile("zwoptex/grossini.plist") cache:removeSpriteFramesFromFile("zwoptex/grossini-generic.plist") end local function onNodeEvent(event) if event == "enter" then onEnter() elseif event == "exit" then onExit() end end ret:registerScriptHandler(onNodeEvent) return ret end function ZwoptexTestMain() cclog("ZwoptexTestMain") Helper.index = 1 local scene = CCScene:create() Helper.createFunctionTable = { ZwoptexGenericTest } scene:addChild(ZwoptexGenericTest()) scene:addChild(CreateBackMenuItem()) return scene end
mit
BluePentagram/BP_Esper_Abilities
bp_esper_abilities/lua/weapons/esper_telepathy.lua
1
1379
if SERVER then AddCSLuaFile() SWEP.Weight = 5 SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false elseif CLIENT then SWEP.PrintName = "Telepathy - WIP" SWEP.Slot = 0 SWEP.SlotPos = 6 SWEP.DrawAmmo = false SWEP.DrawCrosshair = false end -- local ply = SWEP.Owner SWEP.Author = "Blue-Pentagram" SWEP.Instructions = "-To Be Added-" SWEP.Contact = "http://steamcommunity.com/workshop/filedetails/discussion/278185787/617330406650185272/" SWEP.Purpose = "Allow you to communicate to other people or all the other telepaths" SWEP.Category = "Esper Abilitys" SWEP.Spawnable = true SWEP.AdminOnly = true SWEP.ViewModel = "models/weapons/v_357.mdl" SWEP.WorldModel = "models/weapons/w_357.mdl" SWEP.Primary.ClipSize = -1 SWEP.Primary.DefaultClip = -1 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "none" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" SWEP.HoldType = "normal" function SWEP:Deploy() self.Owner:DrawViewModel(false) end function SWEP:DrawWorldModel() self:DrawModel() end function SWEP:Initialize() self:SetWeaponHoldType( self.HoldType ) end function SWEP:Reload() end function SWEP:Think() end function SWEP:PrimaryAttack(ply) LocalPlayer().TelepathyEnabled = true end function SWEP:SecondaryAttack(ply) LocalPlayer().TelepathyEnabled = true end
gpl-2.0
aminaleahmad/merbots
bot/utils.lua
15
14995
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- user has admins privileges function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- user has moderator privileges function is_mod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_banned(user_id, chat_id) return redis:get('banned:'..chat_id..':'..user_id) or false end function is_super_banned(user_id) return redis:get('superbanned:'..user_id) or false end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = '' --'This plugin requires privileged user.' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) -- If plugins moderated = true if plugin.moderated and not is_mod(msg) then -- Check if user is a mod if plugin.moderated and not is_admin(msg) then -- Check if user is an admin if plugin.moderated and not is_sudo(msg) then -- Check if user is a sudoer return false end end end -- If plugins privileged = true if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end
gpl-2.0
FastQuake/E410
data/scripts/ai.lua
2
7406
require "networkutils" local nodes = {} require "networkutils" local monsters = {} AIManager = {} bulletd = 300 wave = 1 function tablelength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end function tableContains(t,searchv) for k,v in pairs(t) do if v == searchv then return true end end return false end function getAiFromObj(obj) for k,v in pairs(monsters) do if v.model:getID() == obj:getID() then return v end end return nil end function removeMonster(obj) for k,v in pairs(monsters) do if v.model:getID() == obj:getID() then v.model:remove() __serverDelete(v.model:getID()) table.remove(monsters,k) end end end function AIManager.addNode(id,x,y,z) local node = {} node.pos = Vector.create(x,y,z) node.id = id node.neighbors = {} node.model = GO.loadIQM("cube.iqm","node"..id) node.model:setBoxBody() node.model:setVisible(false) node.model:setMass(0) node.model:setPos(node.pos:get()) nodes[id] = node end function AIManager.addNeighbors(id1,ids) for k,v in pairs(ids) do local node = nodes[id1] table.insert(node.neighbors,nodes[v]) end end function AIManager.getNode(id) return nodes[id] end function AIManager.getMonsters() return monsters end function AIManager.addMonster(numPlayers, pos) local monster = {} monster.model = GO.loadIQM("robit.iqm","monster") --monster.model:setBoxBody() monster.model:setExtBoxBody(-0.5,0,-0.5,0.5,2.5,0.5) monster.model:setActivation(true) monster.model:lockAxis(0,0,0) monster.model:setPos(pos:get()) monster.pos = pos monster.path = {} monster.targetPlayer = math.random(0,numPlayers-1) monster.bulletTimer = 0 monster.maxtime = (math.random()*0.5)+0.3 monster.hp = 100 table.insert(monsters,monster) end function AIManager.findVisibleNode(startPos) startPos.y = startPos.y + 2 local closestNode = {} local triedNodes = {} local out = {} local tries = 0 while true do local min = 9999 if tries > 15 then return nil end for k,v in pairs(nodes) do local distance = Vector.distance(startPos,v.pos) local seenAlready = 0 for l,w in pairs(triedNodes) do if w.id == v.id then seenAlready = 1 end end if (distance < min and seenAlready ~= 1) then min = distance closestNode = v end end local dir = closestNode.pos-startPos if dir == Vector.create(0,0,0) then out = closestNode return out else local dirx,diry,dirz = dir:get() local posx,posy,posz = startPos:get() local obj,x,y,z = GO.castRay(posx,posy,posz,dirx,diry,dirz,50,1) if obj ~= nil then if obj:getTag() ~= "floor" then out = closestNode return out end table.insert(triedNodes,closestNode) tries = tries+1 else table.insert(triedNodes,closestNode) tries = tries+1 end end end return 1 end function AIManager.buildMonsterPaths() for k,v in pairs(monsters) do local peer = Peer.getPeer(peers,v.targetPlayer) local pvec = Vector.create(peer.model:getPos()) v.path = {} local ignoreList = {} local nodehere = AIManager.findVisibleNode(v.pos) local nodethere = AIManager.findVisibleNode(pvec) --print(nodethere.model:getTag()) table.insert(v.path,nodehere) table.insert(ignoreList,nodehere) local pathComplete = false while pathComplete == false do local closestNode = {} local distance = 0 local min = 9999 local dead = 0 local endNode = v.path[#v.path] local neighbors = endNode.neighbors for l,w in pairs(neighbors) do local ignored = false if tableContains(ignoreList,w) == true then ignored = true end if ignored == true then dead = dead+1 if dead == tablelength(neighbors) then table.insert(ignoreList,v.path[#v.path]) table.remove(v.path) break end else distance = Vector.distance(w.pos,nodethere.pos) if distance < min then min = distance closestNode = w end end end if tableContains(ignoreList,closestNode) == false then table.insert(v.path,closestNode) table.insert(ignoreList,closestNode) end if v.path[#v.path] == nodethere then --print("PATH DONE") pathComplete = true end end v.targetNodeNum = 1 end end function AIManager.spawnWave() local numMonsters = math.ceil(0.5*wave) if numMonsters > 10 then numMonsters = 10 end for i=1,numMonsters do --local p = Vector.create(math.random(-4,4),0,math.random(-4,4)) local p = nodes[math.random(1,#nodes)].pos p.x = p.x + math.random()-0.5 p.y = p.y + 1 p.z = p.z + math.random()-0.5 AIManager.addMonster(#peers,p) end AIManager.buildMonsterPaths() end function AIManager.stepMonsters(peers, dt) if #monsters == 0 then wave = wave+1 network.sendPacket(-1, "wave") AIManager.spawnWave() end for k,v in pairs(monsters) do local targetPos = Vector.create(Peer.getPeer(peers,v.targetPlayer).model:getPos()) targetPos.y = targetPos.y+1 local dir = (targetPos-Vector.create(v.model:getPos())):normalize() local pp = Vector.create(v.model:getPos()) if math.abs(pp.x) > 50 or math.abs(pp.y) > 50 or math.abs(pp.z) > 50 then network.sendPacket(-1, "explode "..pp.x.." "..pp.y.." "..pp.z) removeMonster(v.model) break end pp.y = pp.y+1 pp = pp+dir local obj = GO.castRay(pp.x,pp.y,pp.z,dir.x,dir.y,dir.z,100,4) if obj ~= nil then if obj:getTag():sub(1,6) == "player" then local oldv = Vector.create(v.model:getVelocity()) local vel = dir:copy() vel.x = 3*vel.x vel.z = 3*vel.z vel.y = oldv.y v.model:setVelocity(Vector.scalarMul(1,vel):get()) if vel == Vector.create(0,0,0) then network.sendPacket(-1, "stopanimate "..v.model:getID()) else network.sendPacket(-1, "animate "..v.model:getID()) end end else if v.targetNodeNum < #v.path then local oldv = Vector.create(v.model:getVelocity()) v.pos = Vector.create(v.model:getPos()) local vel = (v.path[v.targetNodeNum].pos - v.pos):normalize() vel.x = 3*vel.x vel.z = 3*vel.z vel.y = oldv.y if vel == Vector.create(0,0,0) then network.sendPacket(-1, "stopanimate "..v.model:getID()) else network.sendPacket(-1, "animate "..v.model:getID()) end v.model:setVelocity(Vector.scalarMul(1,vel):get()) if Vector.distance(v.path[v.targetNodeNum].pos,v.pos) < 1.0 then v.targetNodeNum = v.targetNodeNum+1 end end end local p2 = Vector.create(v.model:getPos()) p2.y = p2.y+1.5 local dir = Vector.normalize(targetPos-p2) local dirx,diry,dirz = dir:get() local yaw = math.acos(Vector.dot(Vector.create(1,0,0),Vector.create(dirx,0,dirz))) yaw = math.deg(yaw) if dirz > 0 then yaw = -yaw end if v.bulletTimer > v.maxtime then local rx = (math.random()/3)-(1/6) local ry = (math.random()/3)-(1/6) local rz = (math.random()/3)-(1/6) local obj,x,y,z = GO.castRay(p2.x,p2.y,p2.z,dirx+rx,diry+ry,dirz+rz,100,4) v.model:setRot(0,yaw,0) if obj ~= nil then network.sendPacket(-1,"shoot "..p2.x.." "..p2.y.." "..p2.z.." "..x.." "..y.." "..z) if obj:getTag():sub(1,6) == "player" then local id = Peer.getIDFromObject(peers,obj) network.sendPacket(id,"hit") end else network.sendPacket(-1,"shoot "..p2.x.." "..p2.y.." "..p2.z.." "..bulletd*(dirx+rx).." "..bulletd*(diry+ry).." "..bulletd*(dirz+rz)) end v.bulletTimer = 0 end v.bulletTimer = v.bulletTimer + dt end end
gpl-2.0
cooljeanius/CEGUI
projects/premake/config.lua
1
7035
-- -- CEGUI premake configuration script -- --- These control whether certain build configurations will be available in the --- generated solutions. You can set to false (or comment) any build configs --- you will not be using. WANT_RELEASE_WITH_SYMBOLS_BUILD = true WANT_STATIC_BUILD = true --- This controls which version of the C/C++ runtime and which version of the --- dependencies are used when linking the static build configurations. --- --- false: use the static c/c++ runtime option and the 'static' dependencies. --- true: use the DLL c/c++ runtime option and the 'dynamic' dependencies. STATIC_BUILD_WITH_DYNAMIC_DEPS = false -- comment this to disable debug suffixes for dynamic module dlls -- if you want to use another suffix, just change the string :) -- all the debug cegui libraries are built with this suffix DEBUG_DLL_SUFFIX = "_d" -- Iterator debugging setting -- -- This controls the level of debugging and other checks done for STL iterators -- in the debug build for the MSVC++ compilers. -- Setting this to false can improve performance of debug builds at the expense -- of safety / debug checks on iterators. FULLY_CHECKED_DEBUG_ITERATORS = true -- SDK / dependency paths -- { base, include_suffix, library_suffix } -- base can be absolute or relative to the root cegui_mk2 dir IRRLICHT_PATHS = { "irrlicht-1.7.1", "include", "lib/Win32-visualstudio" } OGRE_PATHS = { "C:/OgreSDK", "include", "lib" } OIS_PATHS = { "C:/OgreSDK", "include/OIS", "lib" } -- Set this to where your RapidXML package headers are to be found RAPIDXML_PATHS = { "rapidxml-1.13", "", "" } -- Python / boost::python (required to build python extension modules) PYTHON_PATHS = { "C:/Python26", "include", "libs" } BOOST_PYTHON_PATHS = { "C:/Program Files/boost/boost_1_44", "", "lib" } -- Extra SDK / dependency paths. -- -- Here you can set up any additional paths you require for the various projects -- in CEGUI. This is useful if, for example, you are using some SDK that has -- additional external dependencies of it's own (for example, boost used with -- Ogre). All you need to do is add an entry in the following table to indicate -- the base directory, include sub-directory, library-subdirectory, and optionally -- the name of the CEGUI project to add the paths to (if no project is given, the -- paths are added to /all/ projects). -- -- NB: Each entry should be surrounded by curly braces, with each entry -- separated with a comma and appearing within the existing braces. -- -- For example, to add the OgreSDK boost paths to build for the Ogre renderer -- module and sample helper with Ogre support, you might have: -- -- CEGUI_EXTRA_PATHS = { -- { "../OgreSDK/boost_1_42", "", "lib", "CEGUIOgreRenderer" }, -- { "../OgreSDK/boost_1_42", "", "lib", "CEGUISampleHelper" } -- } -- CEGUI_EXTRA_PATHS = { } --- Irrlicht SDK Version --- 14 is means 1.4 or 1.5.x and 16 means 1.6 or 1.7.x (and above?) CEGUI_IRR_SDK_VERSION = 16 --- OIS API version to be used in the Ogre samples base app. --- true: use older numKeyboards / numMice --- false: use getNumberOfDevices CEGUI_OLD_OIS_API = false --- Lua version --- 51 is 5.1 (and above?) From 0.7.0 onwards, lua 5.0 is no longer supported. CEGUI_LUA_VER = 51 --- Freetype library --- CEGUI uses the freetype library for some of it's font support. To disable --- the use of freetype, set this to false. CEGUI_USE_FREETYPE = true --- PCRE library --- CEGUI uses the pcre library for it's regular expression based string --- validation as used in the Editbox (and derived classes, such as Spinner). --- To disable the use of PCRE (and therefore the validation factilities), set --- this to false. (Attempts to set validation string will throw). CEGUI_USE_PCRE_REGEX = true --- CEGUI::DefaultLogger --- To disable compilation and use of the CEGUI::DefaultLogger, set this to --- false. --- --- Note: If you disable this, you MUST provide an alternative CEGUI::Logger --- based class and instantiate it before creating the main CEGUI::System object. CEGUI_USE_DEFAULT_LOGGER = true --- BiDirectional text support. --- To enable support for bi-directional text in CEGUI, set CEGUI_BIDI_SUPPORT --- to true. --- With bidirectional support enabled, CEGUI_USE_MINIBIDI then controls whether --- that support is provided viaan embedded copy of minibidi (true) or an --- external copy of the fribidi library (false). CEGUI_BIDI_SUPPORT = false; CEGUI_USE_MINIBIDI = true; --- MinizipResourceProvider --- To enable compilation and inclusion into CEGUIBase of the MinizipResourceProvider --- set the following to true. --- --- The MinizipResourceProvider enables resources to be loaded from a zip compressed --- archive. MINIZIP_RESOURCE_PROVIDER = true ------------- -- Renderers -- this controls which renderer modules are built OPENGL_RENDERER = true DIRECT3D9_RENDERER = true DIRECT3D10_RENDERER = false DIRECT3D11_RENDERER = false IRRLICHT_RENDERER = false OGRE_RENDERER = false NULL_RENDERER = false ---------------- -- Image Codecs -- this controls which image codecs are built TGA_IMAGE_CODEC = true SILLY_IMAGE_CODEC = true DEVIL_IMAGE_CODEC = true FREEIMAGE_IMAGE_CODEC = true CORONA_IMAGE_CODEC = true STB_IMAGE_CODEC = true -- this setting selects the default image codec module -- can be either "tga", "silly", "devil", "freeimage", "stb" or "corona" -- SILLY was written for CEGUI DEFAULT_IMAGE_CODEC = "silly" --------------- -- Window Renderers -- controls window renderers built FALAGARD_WR = true -- default WR -- available: falagard DEFAULT_WINDOW_RENDERER = "falagard" --------------- -- XML parsers -- this controls which xml parser modules are built EXPAT_PARSER = true XERCES_PARSER = false TINYXML_PARSER = false RAPIDXML_PARSER = false LIBXML_PARSER = false -- this selects the default XML parser module -- can be either "expat", "xerces", "tinyxml", "rapidxml" or "libxml" DEFAULT_XML_PARSER = "expat" ------- -- Lua -- this controls whether CEGUILua is enabled LUA_SCRIPT_MODULE = true -- disable this for a smaller and faster, but less safe Lua module -- only affects Release builds. Debug and ReleaseWithSymbols always -- enable this LUA_SCRIPT_MODULE_SAFE = false -- enable this to build the bundled tolua++ as a static library TOLUA_STATIC = false ------- -- Python -- this controls whether building the Python extension modules is enabled PYTHON_EXTENSION_MODULE = false ----------- -- Samples -- remember you have to edit CEGUISamplesConfig.h as well this just controls -- dependencies etc. if the renderer is disabled this has no effect SAMPLES_GL = true SAMPLES_DX9 = true SAMPLES_DX10 = false SAMPLES_IRRLICHT = false SAMPLES_OGRE = false -- this setting controls if the samples should be included in the same -- solution as the core libraries. If this setting is disabled you can -- still generate a seperate solution for the samples -- -- due to a missing feature in premake enabling this will cause the -- output files to be placed in cegui_mk2/bin and not cegui_mk2/Samples/bin -- SAMPLES_INCLUDED = false
gpl-3.0
ncarlson/eiga
runtime/modules/graphics/graphics.lua
1
4586
-- Copyright (C) 2012 Nicholas Carlson -- -- 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. if not eiga.graphics then eiga.graphics = {} end local glfw = eiga.alias.glfw() local glew = eiga.alias.glew() local gl = eiga.alias.gl() local soil = eiga.ffi.soil local Effect = require 'graphics.effect' local ArrayBuffer = require 'graphics.arraybuffer' local IndexBuffer = require 'graphics.indexbuffer' local Mesh = require 'graphics.mesh' local ffi = require 'ffi' function eiga.graphics.init () assert( glfw.Init() ) -- disable automatic polling of events glfw.Disable( glfw.AUTO_POLL_EVENTS ) eiga.graphics.has_set_mode = false eiga.graphics.screen = { width = -1; height = -1; } end function eiga.graphics.window_resize_callback ( width, height ) eiga.event.push("resized", width, height) end function eiga.graphics.set_mode ( mode ) glfw.OpenWindowHint( glfw.FSAA_SAMPLES, mode.fsaa ) glfw.OpenWindow(mode.width, mode.height, mode.red, mode.green, mode.blue, mode.alpha, mode.depth, mode.stencil, mode.fullscreen and glfw.FULLSCREEN or glfw.WINDOW) glfw.SwapInterval( mode.vsync and 1 or 0 ) glfw.SetWindowTitle( mode.title or eiga._versionstring ) if not eiga.graphics.has_set_mode then jit.off( glfw.SetWindowSizeCallback( eiga.graphics.window_resize_callback ) ) glew.Init() eiga.graphics.has_set_mode = true end end function eiga.graphics.clear () gl.Clear( bit.bor( gl.COLOR_BUFFER_BIT, gl.DEPTH_BUFFER_BIT ) ) end function eiga.graphics.present () glfw.SwapBuffers() end function eiga.graphics.deinit () glfw.Terminate() end function eiga.graphics.newEffect( vertex_shader_path, fragment_shader_path ) local vs_src = eiga.filesystem.read( vertex_shader_path ) local fs_src = eiga.filesystem.read( fragment_shader_path ) return Effect( vs_src, fs_src ) end function eiga.graphics.newVertexArray () local vertex_array_name = ffi.new( "GLuint[1]" ) gl.GenVertexArrays( 1, vertex_array_name ) return vertex_array_name end function eiga.graphics.useVertexArray ( vertex_array_name ) gl.BindVertexArray( vertex_array_name ) end function eiga.graphics.newArrayBuffer ( format, size ) return ArrayBuffer( format, size ) end function eiga.graphics.newIndexBuffer ( size ) return IndexBuffer( size ) end function eiga.graphics.useEffect( effect ) gl.UseProgram( effect and effect.program or 0 ) end function eiga.graphics.draw ( primitive_type, index_count, index_type ) gl.DrawElements( primitive_type, index_count, index_type, nil); end function eiga.graphics.newMesh ( format ) return Mesh( format ) end function eiga.graphics.newTexture ( path, near_filter, far_filter ) local buffer, size = eiga.filesystem.read( path ) local tex_2d = soil.SOIL_load_OGL_texture_from_memory( buffer, size, soil.SOIL_LOAD_AUTO, soil.SOIL_CREATE_NEW_ID, 0 ); gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, near_filter) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, far_filter) return tex_2d end function eiga.graphics.newImage( path ) local buffer, size = eiga.filesystem.read( path ) local width, height = ffi.new("int[1]"), ffi.new("int[1]") local channels = ffi.new("int[1]") local image = soil.SOIL_load_image_from_memory( buffer, size, width, height, channels, 0 ) return { data = image; size = size; width = width; height = height; channels = channels; } end return eiga.graphics
mit
JarnoVgr/Mr.Green-MTA-Resources
resources/[race]/race/rankingboard_client.lua
4
9750
local sx,sy = guiGetScreenSize() RankingBoard = {} RankingBoard.__index = RankingBoard RankingBoard.instances = {} local screenWidth, screenHeight = guiGetScreenSize() local topDistance = 250 local bottomDistance = 0.26*screenHeight local posLeftDistance = 30 local nameLeftDistance = 60 local labelHeight = 16 local maxPositions = math.floor((screenHeight - topDistance - bottomDistance)/labelHeight) local RenderTarget = dxCreateRenderTarget(screenWidth * 0.248, screenHeight * 0.281,true) posLabel = {} playerLabel = {} function RankingBoard.create(id) -- RankingBoard.instances[id] = setmetatable({ id = id, direction = 'down', labels = {}, position = 0 }, RankingBoard) -- posLabel = {} -- playerLabel = {} end function RankingBoard.call(id, fn, ...) -- RankingBoard[fn](RankingBoard.instances[id], ...) end function RankingBoard:setDirection(direction, plrs) -- self.direction = direction -- if direction == 'up' then -- self.highestPos = plrs -- self.position = self.highestPos + 1 -- end end function RankingBoard:add(name, time) -- local position -- local y -- local doBoardScroll = false -- if self.direction == 'down' then -- self.position = self.position + 1 -- if self.position > maxPositions then -- return -- end -- y = topDistance + (self.position-1)*labelHeight -- elseif self.direction == 'up' then -- self.position = self.position - 1 -- local labelPosition = self.position -- if self.highestPos > maxPositions then -- labelPosition = labelPosition - (self.highestPos - maxPositions) -- if labelPosition < 1 then -- labelPosition = 0 -- doBoardScroll = true -- end -- elseif labelPosition < 1 then -- return -- end -- y = topDistance + (labelPosition-1)*labelHeight -- end -- posLabel[name], posLabelShadow = createShadowedLabelFromSpare(posLeftDistance, y, 20, labelHeight, tostring(self.position) .. ')', 'right') -- if time then -- if not self.firsttime then -- self.firsttime = time -- time = '' .. msToTimeStr(time) -- else -- time = '' .. msToTimeStr(time) -- end -- else -- time = '' -- end -- playerLabel[name], playerLabelShadow = createShadowedLabelFromSpare(nameLeftDistance, y, 250, labelHeight, name) -- table.insert(self.labels, posLabel[name]) -- table.insert(self.labels, posLabelShadow) -- table.insert(self.labels, playerLabel[name]) -- table.insert(self.labels, playerLabelShadow) -- playSoundFrontEnd(7) -- if doBoardScroll then -- -- guiSetAlpha(posLabel[name], 0) -- -- guiSetAlpha(posLabelShadow, 0) -- -- guiSetAlpha(playerLabel[name], 0) -- -- guiSetAlpha(playerLabelShadow, 0) -- -- local anim = Animation.createNamed('race.boardscroll', self) -- -- anim:addPhase({ from = 0, to = 1, time = 700, fn = RankingBoard.scroll, firstLabel = posLabel[name] }) -- -- anim:addPhase({ fn = RankingBoard.destroyLastLabel, firstLabel = posLabel[name] }) -- -- anim:play() -- end end function RankingBoard:scroll(param, phase) -- local firstLabelIndex = table.find(self.labels, phase.firstLabel) -- for i=firstLabelIndex,firstLabelIndex+3 do -- guiSetAlpha(self.labels[i], param) -- end -- local x, y -- for i=0,#self.labels/4-1 do -- for j=1,4 do -- x = (j <= 2 and posLeftDistance or nameLeftDistance) -- y = topDistance + ((maxPositions - i - 1) + param)*labelHeight -- if j % 2 == 0 then -- x = x + 1 -- y = y + 1 -- end -- guiSetPosition(self.labels[i*4+j], sx + x, y, false) -- end -- end -- for i=1,4 do -- guiSetAlpha(self.labels[i], 1 - param) -- end end function RankingBoard:destroyLastLabel(phase) -- for i=1,4 do -- destroyElementToSpare(self.labels[1]) -- guiSetVisible(self.labels[1],false) -- table.remove(self.labels, 1) -- end -- local firstLabelIndex = table.find(self.labels, phase.firstLabel) -- for i=firstLabelIndex,firstLabelIndex+3 do -- guiSetAlpha(self.labels[i], 1) -- end end function RankingBoard:addMultiple(items) -- for i,item in ipairs(items) do -- self:add(item.name, item.time) -- end end function RankingBoard:clear() -- table.each(self.labels, destroyElementToSpare) -- self.labels = {} end function RankingBoard:destroy() -- self:clear() -- RankingBoard.instances[self.id] = nil end -- -- Label cache -- local spareElems = {} local donePrecreate = false function RankingBoard.precreateLabels(count) -- donePrecreate = false -- while #spareElems/4 < count do -- local label, shadow = createShadowedLabel(10, 1, 20, 10, 'a' ) -- --guiSetAlpha(label,0) -- guiSetAlpha(shadow,0) -- guiSetVisible(label, false) -- guiSetVisible(shadow, false) -- destroyElementToSpare(label) -- destroyElementToSpare(shadow) -- end -- donePrecreate = true end function destroyElementToSpare(elem) -- table.insertUnique( spareElems, elem ) -- guiSetVisible(elem, false) end dxTextCache = {} dxTextShadowCache = {} function dxDrawColoredLabel(str, ax, ay, bx, by, color,tcolor,scale, font) -- local rax = ax -- if not dxTextShadowCache[str] then -- dxTextShadowCache[str] = string.gsub( str, '#%x%x%x%x%x%x', '' ) -- end -- dxDrawText(dxTextShadowCache[str], ax+1,ay+1,ax+1,by,tocolor(0,0,0, 0.8 * tcolor[4]),scale,font, "left", "center", false,false,false) -- if dxTextCache[str] then -- for id, text in ipairs(dxTextCache[str]) do -- local w = text[2] * ( scale / text[4] ) -- dxDrawText(text[1], ax + w, ay, ax + w, by, tocolor(text[3][1],text[3][2],text[3][3],tcolor[4]), scale, font, "left", "center", false,false,false) -- end -- else -- dxTextCache[str] = {} -- local pat = "(.-)#(%x%x%x%x%x%x)" -- local s, e, cap, col = str:find(pat, 1) -- local last = 1 -- local r = tcolor[1] -- local g = tcolor[2] -- local b = tcolor[3] -- local textalpha = tcolor[4] -- while s do -- if cap == "" and col then -- r = tonumber("0x"..col:sub(1, 2)) -- g = tonumber("0x"..col:sub(3, 4)) -- b = tonumber("0x"..col:sub(5, 6)) -- color = tocolor(r, g, b, textalpha) -- end -- if s ~= 1 or cap ~= "" then -- local w = dxGetTextWidth(cap, scale, font) -- dxDrawText(cap, ax, ay, ax + w, by, color, scale, font, "left", "center") -- table.insert(dxTextCache[str], { cap, ax-rax, {r,g,b}, scale } ) -- ax = ax + w -- r = tonumber("0x"..col:sub(1, 2)) -- g = tonumber("0x"..col:sub(3, 4)) -- b = tonumber("0x"..col:sub(5, 6)) -- color = tocolor( r, g, b, textalpha) -- end -- last = e + 1 -- s, e, cap, col = str:find(pat, last) -- end -- if last <= #str then -- cap = str:sub(last) -- local w = dxGetTextWidth(cap, scale, font) -- dxDrawText(cap, ax, ay, ax + w, by, color, scale, font, "left", "center") -- table.insert(dxTextCache[str], { cap, ax-rax, {r,g,b}, scale } ) -- end -- end end local scale = 1 local font = "default" function drawRankList() -- if not RenderTarget then return end -- dxSetRenderTarget(RenderTarget,true) -- for pos,playerLab in ipairs(playerLabel) do -- local xPos = pos * labelHeight -- dxDrawColoredLabel(guiGetText(playerLab),0,xPos,1000,xPos+labelHeight,tocolor(255,255,255,255),scale,font) -- end -- dxSetRenderTarget() -- dxDrawImage(screenW * 0.014, screenH * 0.394, screenW * 0.248, screenH * 0.281,RenderTarget) end addEventHandler("onClientRender", root, drawRankList) -- local font = "default" -- local scl = 1.2 -- addEventHandler("onClientRender", getRootElement(), -- function() -- for id, elem in pairs(playerLabel) do -- if guiGetVisible(elem) and string.len(guiGetText(elem)) > 4 then -- local x,y = guiGetPosition(elem, false) -- local a = guiGetAlpha(elem) * 255 -- if not getKeyState("tab") then -- dxDrawColoredLabel(string.gsub(guiGetText(elem)," ", " ",1), 50,y,200,y+20, tocolor(255,255,255,a*0.8),{255,255,255,a*0.8}, scl, font, "left", "center", false,false,false) -- end -- if x < 100 then guiSetPosition(elem, sx+100,y,false) end -- end -- end -- for id, elem in pairs(posLabel) do -- if guiGetVisible(elem) and string.len(guiGetText(elem)) <= 4 then -- local x,y = guiGetPosition(elem, false ) -- local a = guiGetAlpha(elem) * 255 -- if not getKeyState("tab") then -- dxDrawText(guiGetText(elem), 1,y+1,41,y+21, tocolor(0,0,0,math.floor(a*0.8)), scl, font, "right", "center", false,false,false) -- dxDrawText(guiGetText(elem), 0,y,40,y+20, tocolor(255,255,255,a*0.85), scl, font, "right", "center", false,false,false) -- end -- if x < 100 then guiSetPosition(elem, sx+100,y,false) end -- end -- end -- end) function createShadowedLabelFromSpare(x, y, width, height, text, align) -- if #spareElems < 2 then -- if not donePrecreate then -- outputDebug( 'OPTIMIZATION', 'createShadowedLabel' ) -- end -- return createShadowedLabel(x, y, width, height, text, align) -- else -- local shadow = table.popLast( spareElems ) -- guiSetSize(shadow, width, height, false) -- guiSetText(shadow, text) -- --guiLabelSetColor(shadow, 0, 0, 0) -- guiSetPosition(shadow, sx + x + 1, y + 1, false) -- guiSetVisible(shadow, false) -- local label = table.popLast( spareElems ) -- guiSetSize(label, width, height, false) -- guiSetText(label, text) -- --guiLabelSetColor(label, 255, 255, 255) -- guiSetPosition(label, sx + x, y, false) -- guiSetVisible(label, true) -- if align then -- guiLabelSetHorizontalAlign(shadow, align) -- guiLabelSetHorizontalAlign(label, align) -- else -- guiLabelSetHorizontalAlign(shadow, 'left') -- guiLabelSetHorizontalAlign(label, 'left') -- end -- return label, shadow -- end end -- fileDelete("rankingboard_client.lua")
mit
Zefiros-Software/ZPM
test/extern/luacov/stats.lua
4
2078
----------------------------------------------------- -- Manages the file with statistics (being) collected. -- @class module -- @name luacov.stats local stats = {} ----------------------------------------------------- -- Loads the stats file. -- @param statsfile path to the stats file. -- @return table with data or nil if couldn't load. -- The table maps filenames to stats tables. -- Per-file tables map line numbers to hits or nils when there are no hits. -- Additionally, .max field contains maximum line number -- and .max_hits contains maximum number of hits in the file. function stats.load(statsfile) local data = {} local fd = io.open(statsfile, "r") if not fd then return nil end while true do local max = fd:read("*n") if not max then break end if fd:read(1) ~= ":" then break end local filename = fd:read("*l") if not filename then break end data[filename] = { max = max, max_hits = 0 } for i = 1, max do local hits = fd:read("*n") if not hits then break end if fd:read(1) ~= " " then break end if hits > 0 then data[filename][i] = hits data[filename].max_hits = math.max(data[filename].max_hits, hits) end end end fd:close() return data end ----------------------------------------------------- -- Saves data to the stats file. -- @param statsfile path to the stats file. -- @param data data to store. function stats.save(statsfile, data) local fd = assert(io.open(statsfile, "w")) local filenames = {} for filename in pairs(data) do table.insert(filenames, filename) end table.sort(filenames) for _, filename in ipairs(filenames) do local filedata = data[filename] fd:write(filedata.max, ":", filename, "\n") for i = 1, filedata.max do fd:write(tostring(filedata[i] or 0), " ") end fd:write("\n") end fd:close() end return stats
mit
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/TextureCache.lua
2
5315
-------------------------------- -- @module TextureCache -- @extend Ref -- @parent_module cc -------------------------------- -- Reload texture from the image file.<br> -- If the file image hasn't loaded before, load it.<br> -- Otherwise the texture will be reloaded from the file image.<br> -- param fileName It's the related/absolute path of the file image.<br> -- return True if the reloading is succeed, otherwise return false. -- @function [parent=#TextureCache] reloadTexture -- @param self -- @param #string fileName -- @return bool#bool ret (return value: bool) -------------------------------- -- Unbind all bound image asynchronous load callbacks.<br> -- since v3.1 -- @function [parent=#TextureCache] unbindAllImageAsync -- @param self -- @return TextureCache#TextureCache self (return value: cc.TextureCache) -------------------------------- -- Deletes a texture from the cache given a its key name.<br> -- param key It's the related/absolute path of the file image.<br> -- since v0.99.4 -- @function [parent=#TextureCache] removeTextureForKey -- @param self -- @param #string key -- @return TextureCache#TextureCache self (return value: cc.TextureCache) -------------------------------- -- Purges the dictionary of loaded textures.<br> -- Call this method if you receive the "Memory Warning".<br> -- In the short term: it will free some resources preventing your app from being killed.<br> -- In the medium term: it will allocate more resources.<br> -- In the long term: it will be the same. -- @function [parent=#TextureCache] removeAllTextures -- @param self -- @return TextureCache#TextureCache self (return value: cc.TextureCache) -------------------------------- -- js NA<br> -- lua NA -- @function [parent=#TextureCache] getDescription -- @param self -- @return string#string ret (return value: string) -------------------------------- -- Output to CCLOG the current contents of this TextureCache.<br> -- This will attempt to calculate the size of each texture, and the total texture memory in use.<br> -- since v1.0 -- @function [parent=#TextureCache] getCachedTextureInfo -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @overload self, cc.Image, string -- @overload self, string -- @function [parent=#TextureCache] addImage -- @param self -- @param #cc.Image image -- @param #string key -- @return Texture2D#Texture2D ret (return value: cc.Texture2D) -------------------------------- -- Unbind a specified bound image asynchronous callback.<br> -- In the case an object who was bound to an image asynchronous callback was destroyed before the callback is invoked,<br> -- the object always need to unbind this callback manually.<br> -- param filename It's the related/absolute path of the file image.<br> -- since v3.1 -- @function [parent=#TextureCache] unbindImageAsync -- @param self -- @param #string filename -- @return TextureCache#TextureCache self (return value: cc.TextureCache) -------------------------------- -- Returns an already created texture. Returns nil if the texture doesn't exist.<br> -- param key It's the related/absolute path of the file image.<br> -- since v0.99.5 -- @function [parent=#TextureCache] getTextureForKey -- @param self -- @param #string key -- @return Texture2D#Texture2D ret (return value: cc.Texture2D) -------------------------------- -- Get the file path of the texture<br> -- param texture A Texture2D object pointer.<br> -- return The full path of the file. -- @function [parent=#TextureCache] getTextureFilePath -- @param self -- @param #cc.Texture2D texture -- @return string#string ret (return value: string) -------------------------------- -- Reload texture from a new file.<br> -- This function is mainly for editor, won't suggest use it in game for performance reason.<br> -- param srcName Original texture file name.<br> -- param dstName New texture file name.<br> -- since v3.10 -- @function [parent=#TextureCache] renameTextureWithKey -- @param self -- @param #string srcName -- @param #string dstName -- @return TextureCache#TextureCache self (return value: cc.TextureCache) -------------------------------- -- Removes unused textures.<br> -- Textures that have a retain count of 1 will be deleted.<br> -- It is convenient to call this method after when starting a new Scene.<br> -- since v0.8 -- @function [parent=#TextureCache] removeUnusedTextures -- @param self -- @return TextureCache#TextureCache self (return value: cc.TextureCache) -------------------------------- -- Deletes a texture from the cache given a texture. -- @function [parent=#TextureCache] removeTexture -- @param self -- @param #cc.Texture2D texture -- @return TextureCache#TextureCache self (return value: cc.TextureCache) -------------------------------- -- Called by director, please do not called outside. -- @function [parent=#TextureCache] waitForQuit -- @param self -- @return TextureCache#TextureCache self (return value: cc.TextureCache) -------------------------------- -- js ctor -- @function [parent=#TextureCache] TextureCache -- @param self -- @return TextureCache#TextureCache self (return value: cc.TextureCache) return nil
mit
LuaDist2/oil
lua/precompiler.lua
4
6261
#!/usr/bin/env lua -------------------------------------------------------------------------------- -- @script Lua Script Pre-Compiler -- @version 1.1 -- @author Renato Maia <maia@tecgraf.puc-rio.br> -- local assert = assert local error = error local ipairs = ipairs local loadfile = loadfile local pairs = pairs local select = select local io = require "io" local os = require "os" local package = require "package" local string = require "string" local table = require "table" module("precompiler", require "loop.compiler.Arguments") local FILE_SEP = "/" local FUNC_SEP = "_" local PATH_SEP = ";" local PATH_MARK = "?" help = false bytecodes = false names = false luapath = package.path output = "precompiled" prefix = "LUAOPEN_API" directory = "" _optpat = "^%-(%-?%w+)(=?)(.-)$" _alias = { ["-help"] = "help" } for name in pairs(_M) do _alias[name:sub(1, 1)] = name end local start, errmsg = _M(...) if not start or help then if errmsg then io.stderr:write("ERROR: ", errmsg, "\n") end io.stderr:write([[ Lua Script Pre-Compiler 1.1 Copyright (C) 2006-2008 Tecgraf, PUC-Rio Usage: ]],_NAME,[[.lua [options] [inputs] [inputs] is a sequence of names that may be file paths or package names, use the options described below to indicate how they should be interpreted. If no [inputs] is provided then such names are read from the standard input. Options: -b, -bytecodes Flag that indicates the provided [inputs] are files containing bytecodes (e.g. instead of source code), like the output of the 'luac' compiler. When this flag is used no compilation is performed by this script. -d, -directory Directory where the output files should be generated. Its default is the current directory. -l, -luapath Sequence os path templates used to infer package names from file paths and vice versa. These templates follows the same format of the 'package.path' field of Lua. Its default is the value of 'package.path' that currently is set to: "]],luapath,[[" -n, -names Flag that indicates provided input names are actually package names and the real file path should be inferred from the path defined by -luapath option. This flag can be used in conjunction with the -bytecodes flag to indicate that inferred file paths contains bytecodes instead of source code. -o, -output Name used to form the name of the files generated. Two files are generated: a source code file with the sufix '.c' with the pre-compiled scripts and a header file with the sufix '.h' with function signatures. Its default is ']],output,[['. -p, -prefix Prefix added to the signature of the functions generated. Its default is ']],prefix,[['. ]]) os.exit(1) end -------------------------------------------------------------------------------- local function escapepattern(pattern) return pattern:gsub("([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1") end local filesep = escapepattern(FILE_SEP) local pathsep = escapepattern(PATH_SEP) local pathmark = escapepattern(PATH_MARK) local function adjustpath(path) if path ~= "" and not path:find(filesep.."$") then return path..FILE_SEP end return path end local filepath = adjustpath(directory)..output -------------------------------------------------------------------------------- local function readinput(file, name) if bytecodes then file = assert(io.open(file, "rb")) file = file:read("*a"), file:close() else file = string.dump(assert(loadfile(file))) end return file end local template = "[^"..pathsep.."]+" local function getbytecodes(name) if names then local file = name:gsub("%.", FILE_SEP) local err = {} for path in luapath:gmatch(template) do path = path:gsub(pathmark, file) local file = io.open(path) if file then file:close() return readinput(path) end table.insert(err, string.format("\tno file '%s'", path)) end err = table.concat(err, "\n") error(string.format("module '%s' not found:\n%s", name, err)) end return readinput(name) end local function allequals(...) local name = ... for i = 2, select("#", ...) do if name ~= select(i, ...) then return nil end end return name end local function funcname(name) if not names then local result for path in luapath:gmatch(template) do path = path:gsub(pathmark, "\0") path = escapepattern(path) path = path:gsub("%z", "(.-)") path = string.format("^%s$", path) result = allequals(name:match(path)) or result end if not result then return nil, "unable to figure package name for file '"..name.."'" end return result:gsub(filesep, FUNC_SEP) end return name:gsub("%.", FUNC_SEP) end -------------------------------------------------------------------------------- local inputs = { select(start, ...) } if #inputs == 0 then for name in io.stdin:lines() do inputs[#inputs+1] = name end end local outc = assert(io.open(filepath..".c", "w")) local outh = assert(io.open(filepath..".h", "w")) local guard = output:upper():gsub("[^%w]", "_") outh:write([[ #ifndef __]],guard,[[__ #define __]],guard,[[__ #include <lua.h> #ifndef ]],prefix,[[ #define ]],prefix,[[ #endif ]]) outc:write([[ #include <lua.h> #include <lauxlib.h> #include "]],output,[[.h" ]]) for i, input in ipairs(inputs) do local bytecodes = getbytecodes(input) outc:write("static const unsigned char B",i,"[]={\n") for j = 1, #bytecodes do outc:write(string.format("%3u,", bytecodes:byte(j))) if j % 20 == 0 then outc:write("\n") end end outc:write("\n};\n\n") end for i, input in ipairs(inputs) do local func = assert(funcname(input)) outh:write(prefix," int luaopen_",func,"(lua_State *L);\n") outc:write( prefix,[[ int luaopen_]],func,[[(lua_State *L) { int arg = lua_gettop(L); luaL_loadbuffer(L,(const char*)B]],i,[[,sizeof(B]],i,[[),"]],input,[["); lua_insert(L,1); lua_call(L,arg,1); return 1; } ]]) end outh:write([[ #endif /* __]],guard,[[__ */ ]]) outh:close() outc:close()
mit
JarnoVgr/Mr.Green-MTA-Resources
resources/[race]/race_delay_indicator/textlib.lua
3
7856
dxText = {} dxText_mt = { __index = dxText } local idAssign,idPrefix = 0,"c" local g_screenX,g_screenY = guiGetScreenSize() local visibleText = {} ------ defaults = { fX = 0.5, fY = 0.5, bRelativePosition = true, strText = "", bVerticalAlign = "center", bHorizontalAlign = "center", tColor = {255,255,255,255}, fScale = 1, strFont = "default", strType = "normal", tAttributes = {}, bPostGUI = false, bClip = false, bWordWrap = true, bVisible = false, bColorCode = true, tBoundingBox = false, --If a bounding box is not set, it will not be used. bRelativeBoundingBox = true, } local validFonts = { default = true, ["default-bold"] = true, clear = true, arial = true, pricedown = true, bankgothic = true, diploma = true, beckett = true, } local validTypes = { normal = true, shadow = true, border = true, stroke = true, --Clone of border } local validAlignTypes = { center = true, left = true, right = true, } function dxText:create( text, x, y, relative, strFont, fScale, horzA ) assert(not self.fX, "attempt to call method 'create' (a nil value)") if ( type(text) ~= "string" ) or ( not tonumber(x) ) or ( not tonumber(y) ) then outputDebugString ( "dxText:create - Bad argument", 0, 112, 112, 112 ) return false end local new = {} setmetatable( new, dxText_mt ) --Add default settings for i,v in pairs(defaults) do new[i] = v end idAssign = idAssign + 1 new.id = idPrefix..idAssign new.strText = text or new.strText new.fX = x or new.fX new.fY = y or new.fY if type(relative) == "boolean" then new.bRelativePosition = relative end new:scale( fScale or new.fScale ) new:font( strFont or new.strFont ) new:align( horzA or new.bHorizontalAlign ) visibleText[new] = true return new end function dxText:text(text) if type(text) ~= "string" then return self.strText end self.strText = text return true end function dxText:position(x,y,relative) if not tonumber(x) then return self.fX, self.fY end self.fX = x self.fY = y if type(relative) == "boolean" then self.bRelativePosition = relative else self.bRelativePosition = true end return true end function dxText:color(r,g,b,a) if not tonumber(r) then return unpack(self.tColor) end g = g or self.tColor[2] b = b or self.tColor[3] a = a or self.tColor[4] self.tColor = { r,g,b,a } return true end function dxText:scale(scale) if not tonumber(scale) then return self.fScale end self.fScale = scale return true end function dxText:visible(bool) if type(bool) ~= "boolean" then return self.bVisible end if self.bVisible == bool then return end self.bVisible = bool if bool then visibleText[self] = true else visibleText[self] = nil end return true end function dxText:destroy() self.bDestroyed = true setmetatable( self, self ) return true end function dxText:font(font) if not validFonts[font] then return self.strFont end self.strFont = font return true end function dxText:postGUI(bool) if type(bool) ~= "boolean" then return self.bPostGUI end self.bPostGUI = bool return true end function dxText:clip(bool) if type(bool) ~= "boolean" then return self.bClip end self.bClip = bool return true end function dxText:wordWrap(bool) if type(bool) ~= "boolean" then return self.bWordWrap end self.bWordWrap = bool return true end function dxText:colorCode(bool) if type(bool) ~= "boolean" then return self.bColorCode end self.bColorCode = bool return true end function dxText:type(type,...) if not validTypes[type] then return self.strType, unpack(self.tAttributes) end self.strType = type self.tAttributes = {...} return true end function dxText:align(horzA, vertA) if not validAlignTypes[horzA] then return self.bHorizontalAlign, self.bVerticalAlign end vertA = vertA or self.bVerticalAlign self.bHorizontalAlign, self.bVerticalAlign = horzA, vertA return true end function dxText:boundingBox(left,top,right,bottom,relative) if left == nil then if self.tBoundingBox then return unpack(boundingBox) else return false end elseif tonumber(left) and tonumber(right) and tonumber(top) and tonumber(bottom) then self.tBoundingBox = {left,top,right,bottom} if type(relative) == "boolean" then self.bRelativeBoundingBox = relative else self.bRelativeBoundingBox = true end else self.tBoundingBox = false end return true end addEventHandler ( "onClientRender", getRootElement(), function() for self,_ in pairs(visibleText) do while true do if self.bDestroyed then visibleText[self] = nil break end if self.tColor[4] < 1 then break end local l,t,r,b --If we arent using a bounding box if not self.tBoundingBox then --Decide if we use relative or absolute local p_screenX,p_screenY = 1,1 if self.bRelativePosition then p_screenX,p_screenY = g_screenX,g_screenY end local fX,fY = (self.fX)*p_screenX,(self.fY)*p_screenY if self.bHorizontalAlign == "left" then l = fX r = fX + g_screenX elseif self.bHorizontalAlign == "right" then l = fX - g_screenX r = fX else l = fX - g_screenX r = fX + g_screenX end if self.bVerticalAlign == "top" then t = fY b = fY + g_screenY elseif self.bVerticalAlign == "bottom" then t = fY - g_screenY b = fY else t = fY - g_screenY b = fY + g_screenY end elseif type(self.tBoundingBox) == "table" then local b_screenX,b_screenY = 1,1 if self.bRelativeBoundingBox then b_screenX,b_screenY = g_screenX,g_screenY end l,t,r,b = self.tBoundingBox[1],self.tBoundingBox[2],self.tBoundingBox[3],self.tBoundingBox[4] l = l*b_screenX t = t*b_screenY r = r*b_screenX b = b*b_screenY end local type,att1,att2,att3,att4,att5 = self:type() if type == "border" or type == "stroke" then att2 = att2 or 0 att3 = att3 or 0 att4 = att4 or 0 att5 = att5 or self.tColor[4] outlinesize = att1 or 2 outlinesize = math.min(self.fScale,outlinesize) --Make sure the outline size isnt thicker than the size of the label if outlinesize > 0 then for offsetX=-outlinesize,outlinesize,outlinesize do for offsetY=-outlinesize,outlinesize,outlinesize do if not (offsetX == 0 and offsetY == 0) then dxDrawText(string.gsub(self.strText, "#%x%x%x%x%x%x", ""), l + offsetX, t + offsetY, r + offsetX, b + offsetY, tocolor(att2, att3, att4, att5), self.fScale, self.strFont, self.bHorizontalAlign, self.bVerticalAlign, self.bClip, self.bWordWrap, self.bPostGUI ) end end end end elseif type == "shadow" then local shadowDist = att1 att2 = att2 or 0 att3 = att3 or 0 att4 = att4 or 0 att5 = att5 or self.tColor[4] dxDrawText(string.gsub(self.strText, "#%x%x%x%x%x%x", ""), l + shadowDist, t + shadowDist, r + shadowDist, b + shadowDist, tocolor(att2, att3, att4, att5), self.fScale, self.strFont, self.bHorizontalAlign, self.bVerticalAlign, self.bClip, self.bWordWrap, self.bPostGUI ) end dxDrawText ( self.strText, l, t, r, b, tocolor(unpack(self.tColor)), self.fScale, self.strFont, self.bHorizontalAlign, self.bVerticalAlign, self.bClip, self.bWordWrap, self.bPostGUI, self.bColorCode ) break end end end ) if addEvent ( "updateDisplays", true ) then addEventHandler ( "updateDisplays", getRootElement(), function(self) setmetatable( self, dxText_mt ) --Remove any old ones with the same id for text,_ in pairs(visibleText) do if text.id == self.id then visibleText[text] = nil end end if self.bVisible and not self.bDestroyed then visibleText[self] = true end end ) end
mit
opentechinstitute/luci
protocols/ppp/luasrc/model/network/proto_ppp.lua
77
2695
--[[ LuCI - Network model - 3G, PPP, PPtP, PPPoE and PPPoA protocol extension Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local netmod = luci.model.network local _, p for _, p in ipairs({"ppp", "pptp", "pppoe", "pppoa", "3g", "l2tp"}) do local proto = netmod:register_protocol(p) function proto.get_i18n(self) if p == "ppp" then return luci.i18n.translate("PPP") elseif p == "pptp" then return luci.i18n.translate("PPtP") elseif p == "3g" then return luci.i18n.translate("UMTS/GPRS/EV-DO") elseif p == "pppoe" then return luci.i18n.translate("PPPoE") elseif p == "pppoa" then return luci.i18n.translate("PPPoATM") elseif p == "l2tp" then return luci.i18n.translate("L2TP") end end function proto.ifname(self) return p .. "-" .. self.sid end function proto.opkg_package(self) if p == "ppp" then return p elseif p == "3g" then return "comgt" elseif p == "pptp" then return "ppp-mod-pptp" elseif p == "pppoe" then return "ppp-mod-pppoe" elseif p == "pppoa" then return "ppp-mod-pppoa" elseif p == "l2tp" then return "xl2tpd" end end function proto.is_installed(self) if p == "pppoa" then return (nixio.fs.glob("/usr/lib/pppd/*/pppoatm.so")() ~= nil) elseif p == "pppoe" then return (nixio.fs.glob("/usr/lib/pppd/*/rp-pppoe.so")() ~= nil) elseif p == "pptp" then return (nixio.fs.glob("/usr/lib/pppd/*/pptp.so")() ~= nil) elseif p == "3g" then return nixio.fs.access("/lib/netifd/proto/3g.sh") elseif p == "l2tp" then return nixio.fs.access("/lib/netifd/proto/l2tp.sh") else return nixio.fs.access("/lib/netifd/proto/ppp.sh") end end function proto.is_floating(self) return (p ~= "pppoe") end function proto.is_virtual(self) return true end function proto.get_interfaces(self) if self:is_floating() then return nil else return netmod.protocol.get_interfaces(self) end end function proto.contains_interface(self, ifc) if self:is_floating() then return (netmod:ifnameof(ifc) == self:ifname()) else return netmod.protocol.contains_interface(self, ifc) end end netmod:register_pattern_virtual("^%s-%%w" % p) end
apache-2.0
minecraftgame-andrd/minecraftgame
plugins/linkpv.lua
46
31163
do local function check_member(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.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } 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) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(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.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } 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) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) end end local function check_member_modrem(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.members) 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) return send_large_msg(receiver, 'Group has been removed') end end end local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end 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 bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] 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.."\nBot protection : "..bots_protection return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end 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 get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" 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 "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end 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) if not is_momod(msg) then return "For moderators only!" end 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) if not is_owner(msg) then return "Only admins can do it for now" end 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) if not is_owner(msg) then return "Only admins can do it for now" end 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) if not is_momod(msg) then return "For moderators only!" end 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) if not is_momod(msg) then return "For moderators only!" end 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) if not is_momod(msg) then return "For moderators only!" end 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 set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end 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 modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end 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 rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' 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 local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local 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 local function callbackres(extra, success, result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name if success == -1 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' then print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'rem' then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local receiver = 'user#id'..msg.action.user.id local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return false end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id) send_large_msg(receiver, rules) end if matches[1] == 'chat_del_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") 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) return 'Please send me new group photo now' end if matches[1] == 'promote' and matches[2] then if not is_owner(msg) then return "Only owner can promote" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) 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] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(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] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(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] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(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] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(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] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end if matches[1] == 'newlink' then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'linkpv' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") send_large_msg('user#id'..msg.from.id, "Group link:\n"..group_link) end if matches[1] == 'setowner' then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = 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 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 group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" 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 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end 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 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") end if matches[2] == 'rules' then local data_cat = 'rules' 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") end if matches[2] == 'about' then local data_cat = 'description' 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") end end if matches[1] == 'help' then if not is_momod(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end end return { patterns = { "^[!/](linkpv)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end --Iwas Lazy So I Just Removed Patterns And Didn't Del Junk Items --https://github.com/ThisIsArman --Telegram.me/ThisIsArman
gpl-2.0
abasshacker/abbasone
plugins/inrealm.lua
287
25005
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end 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 set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" 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 return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) 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] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
HEYAHONG/nodemcu-firmware
lua_modules/ftp/ftpserver.lua
7
18436
--[[SPLIT MODULE ftp]] --[[ A simple ftp server This is my implementation of a FTP server using Github user Neronix's example as inspriration, but as a cleaner Lua implementation that is suitable for use in LFS. The coding style adopted here is more similar to best practice for normal (PC) module implementations, as using LFS enables me to bias towards clarity of coding over brevity. It includes extra logic to handle some of the edge case issues more robustly. It also uses a standard forward reference coding pattern to allow the code to be laid out in main routine, subroutine order. The app will only call one FTP.open() or FTP.createServer() at any time, with any multiple calls requected, so FTP is a singleton static object. However there is nothing to stop multiple clients connecting to the FTP listener at the same time, and indeed some FTP clients do use multiple connections, so this server can accept and create multiple cxt objects. Each cxt object can also have a single DATA connection. Note that FTP also exposes a number of really private properties (which could be stores in local / upvals) as FTP properties for debug purposes. Note that this version has now been updated to allow the main methods to be optionally loaded lazily, and SPILT comments allow the source to be preprocessed for loading as either components in the "fast" Cmodule or as LC files in SPIFFS. ]] --luacheck: read globals fast file net node tmr uart wifi FAST_ftp SPIFFS_ftp local FTP, FTPindex = {client = {}}, nil if FAST_ftp then function FTPindex(_, name) return fast.load('ftp-'..name) end elseif SPIFFS_ftp then function FTPindex(_, name) return loadfile('ftp-'..name..'.lc') end end if FTPindex then return setmetatable(FTP,{__index=FTPindex}) end function FTP.open(...) --[[SPLIT HERE ftp-open]] --------------------------- Set up the FTP object ---------------------------- -- FTP has three static methods: open, createServer and close ------------------------------------------------------------------------------ -- optional wrapper around createServer() which also starts the wifi session -- Lua: FTP:open(user, pass, ssid, pwd[, dbgFlag]) local this, user, pass, ssid, pwd, dbgFlag = ... if ssid then wifi.setmode(wifi.STATION, false) wifi.sta.config { ssid = ssid, pwd = pwd, save = false } end tmr.create():alarm(500, tmr.ALARM_AUTO, function(t) -- this: FTP, user, pass, dbgFlag if (wifi.sta.status() == wifi.STA_GOTIP) then t:unregister() print("Welcome to NodeMCU world", node.heap(), wifi.sta.getip()) return this:createServer(user, pass, dbgFlag) else uart.write(0,".") end end) end --[[SPLIT IGNORE]] function FTP.createServer(...) --[[SPLIT HERE ftp-createServer]] -- Lua: FTP:createServer(user, pass[, dbgFlag]) local this, user, pass, dbgFlag = ... local cnt = 0 this.user, this.pass, dbgFlag = user, pass, (dbgFlag and true or false) this.debug = (not dbgFlag) and type -- executing type(...) is in effect a NOOP or function(fmt, ...) -- upval: cnt if (...) then fmt = fmt:format(...) end print(node.heap(),fmt) cnt = cnt + 1 if cnt % 10 then tmr.wdclr() end end this.server = net.createServer(net.TCP, 180) _G.FTP = this this.debug("Server created: (userdata) %s", tostring(this.server)) this.server:listen(21, function(sock) -- upval: this -- since a server can have multiple connections, each connection -- has its own CXN object (table) to store connection-wide globals. local CXN; CXN = { validUser = false, cmdSocket = sock, debug = this.debug, FTP = this, send = function(rec, cb) -- upval: CXN CXN.debug("Sending: %s", rec) return CXN.cmdSocket:send(rec.."\r\n", cb) end, --- CXN. send() close = function(socket) -- upval: CXN CXN.debug("Closing CXN.cmdSocket=%s", tostring(CXN.cmdSocket)) for _,s in ipairs{'cmdSocket', 'dataServer', 'dataSocket'} do CXN.debug("closing CXN.%s=%s", s, tostring(CXN[s])) if type(CXN[s])=='userdata' then pcall(socket.close, CXN[s]) CXN[s]= nil end end CXN.FTP.client[socket] = nil end -- CXN.close() } local function validateUser(socket, data) -- upval: CXN -- validate the logon and if then switch to processing commands CXN.debug("Authorising: %s", data) local cmd, arg = data:match('([A-Za-z]+) *([^\r\n]*)') local msg = "530 Not logged in, authorization required" cmd = cmd:upper() if cmd == 'USER' then CXN.validUser = (arg == CXN.FTP.user) msg = CXN.validUser and "331 OK. Password required" or "530 user not found" elseif CXN.validUser and cmd == 'PASS' then if arg == CXN.FTP.pass then CXN.cwd = '/' socket:on("receive", function(soc, rec) -- upval: CXN assert(soc==CXN.cmdSocket) CXN.FTP.processCommand(CXN, rec) end) -- logged on so switch to command mode msg = "230 Login successful. Username & password correct; proceed." else msg = "530 Try again" end elseif cmd == 'AUTH' then msg = "500 AUTH not understood" end return CXN.send(msg) end local port,ip = sock:getpeer() -- luacheck: no unused --cxt.debug("Connection accepted: (userdata) %s client %s:%u", tostring(sock), ip, port) sock:on("receive", validateUser) sock:on("disconnection", CXN.close) this.client[sock]=CXN CXN.send("220 FTP server ready"); end) -- this.server:listen() end --[[SPLIT IGNORE]] function FTP.close(...) --[[SPLIT HERE ftp-close]] -- Lua: FTP:close() local this = ... -- this.client is a table of soc = cnx. The first (and usually only connection) is cleared -- immediately and next() used to do a post chain so we only close one client per task local function rollupClients(skt,cxt) -- upval: this, rollupClients if skt then this.debug("Client close: %s", tostring(skt)) cxt.close(skt) this.client[skt] = nil node.task.post(function() return rollupClients(next(this.client, skt)) end) -- upval: rollupClients, this, skt else -- we have emptied the open socket table, so can now shut the server this.debug("Server close: %s", tostring(this. server)) this.server:close() this.server:__gc() _G.FTP = nil end end rollupClients(next(this.client)) package.loaded.ftpserver = nil end --[[SPLIT IGNORE]] function FTP.processCommand(...) --[[SPLIT HERE ftp-processCommand]] ----------------------------- Process Command -------------------------------- -- This splits the valid commands into one of three categories: -- * bare commands (which take no arg) -- * simple commands (which take) a single arg; and -- * data commands which initiate data transfer to or from the client and -- hence need to use CBs. -- -- Find strings are used do this lookup and minimise long if chains. ------------------------------------------------------------------------------ local cxt, data = ... cxt.debug("Command: %s", data) data = data:gsub('[\r\n]+$', '') -- chomp trailing CRLF local cmd, arg = data:match('([a-zA-Z]+) *(.*)') cmd = cmd:upper() local _cmd_ = '_'..cmd..'_' if ('_CDUP_NOOP_PASV_PWD_QUIT_SYST_'):find(_cmd_) then cxt.FTP.processBareCmds(cxt, cmd) elseif ('_CWD_DELE_MODE_PORT_RNFR_RNTO_SIZE_TYPE_'):find(_cmd_) then cxt.FTP.processSimpleCmds(cxt, cmd, arg) elseif ('_LIST_NLST_RETR_STOR_'):find(_cmd_) then cxt.FTP.processDataCmds(cxt, cmd, arg) else cxt.send("500 Unknown error") end end --[[SPLIT IGNORE]] function FTP.processBareCmds(...) --[[SPLIT HERE ftp-processBareCmds]] -------------------------- Process Bare Commands ----------------------------- local cxt, cmd = ... local send = cxt.send if cmd == 'CDUP' then return send("250 OK. Current directory is "..cxt.cwd) elseif cmd == 'NOOP' then return send("200 OK") elseif cmd == 'PASV' then -- This FTP implementation ONLY supports PASV mode, and the passive port -- listener is opened on receipt of the PASV command. If any data xfer -- commands return an error if the PASV command hasn't been received. -- Note the listener service is closed on receipt of the next PASV or -- quit. local ip, port, pphi, pplo, i1, i2, i3, i4, _ _,ip = cxt.cmdSocket:getaddr() port = 2121 pplo = port % 256 pphi = (port-pplo)/256 i1,i2,i3,i4 = ip:match("(%d+).(%d+).(%d+).(%d+)") cxt.FTP.dataServer(cxt, port) return send( ('227 Entering Passive Mode(%d,%d,%d,%d,%d,%d)'):format( i1,i2,i3,i4,pphi,pplo)) elseif cmd == 'PWD' then return send('257 "/" is the current directory') elseif cmd == 'QUIT' then send("221 Goodbye", function() cxt.close(cxt.cmdSocket) end) -- upval: cxt return elseif cmd == 'SYST' then -- return send("215 UNKNOWN") return send("215 UNIX Type: L8") -- must be Unix so ls is parsed correctly else error('Oops. Missed '..cmd) end end --[[SPLIT IGNORE]] function FTP.processSimpleCmds(...) --[[SPLIT HERE ftp-processSimpleCmds]] ------------------------- Process Simple Commands ---------------------------- local cxt, cmd, arg = ... local send = cxt.send if cmd == 'MODE' then return send(arg == "S" and "200 S OK" or "504 Only S(tream) is suported") elseif cmd == 'PORT' then cxt.FTP.dataServer(cxt,nil) -- clear down any PASV setting return send("502 Active mode not supported. PORT not implemented") elseif cmd == 'TYPE' then if arg == "A" then cxt.xferType = 0 return send("200 TYPE is now ASII") elseif arg == "I" then cxt.xferType = 1 return send("200 TYPE is now 8-bit binary") else return send("504 Unknown TYPE") end end -- The remaining commands take a filename as an arg. Strip off leading / and ./ arg = arg:gsub('^%.?/',''):gsub('^%.?/','') cxt.debug("Filename is %s",arg) if cmd == 'CWD' then if arg:match('^[%./]*$') then return send("250 CWD command successful") end return send("550 "..arg..": No such file or directory") elseif cmd == 'DELE' then if file.exists(arg) then file.remove(arg) if not file.exists(arg) then return send("250 Deleted "..arg) end end return send("550 Requested action not taken") elseif cmd == 'RNFR' then cxt.from = arg send("350 RNFR accepted") return elseif cmd == 'RNTO' then local status = cxt.from and file.rename(cxt.from, arg) cxt.debug("rename('%s','%s')=%s", tostring(cxt.from), tostring(arg), tostring(status)) cxt.from = nil return send(status and "250 File renamed" or "550 Requested action not taken") elseif cmd == "SIZE" then local st = file.stat(arg) return send(st and ("213 "..st.size) or "550 Could not get file size.") else error('Oops. Missed '..cmd) end end --[[SPLIT IGNORE]] function FTP.processDataCmds(...) --[[SPLIT HERE ftp-processDataCmds]] -------------------------- Process Data Commands ----------------------------- local cxt, cmd, arg = ... local send, FTP = cxt.send, cxt.FTP -- luacheck: ignore FTP -- The data commands are only accepted if a PORT command is in scope if FTP.dataServer == nil and cxt.dataSocket == nil then return send("502 Active mode not supported. "..cmd.." not implemented") end cxt.getData, cxt.setData = nil, nil arg = arg:gsub('^%.?/',''):gsub('^%.?/','') if cmd == "LIST" or cmd == "NLST" then -- There are local fileSize, nameList, pattern = file.list(), {}, '.' arg = arg:gsub('^-[a-z]* *', '') -- ignore any Unix style command parameters arg = arg:gsub('^/','') -- ignore any leading / if #arg > 0 and arg ~= '.' then -- replace "*" by [^/%.]* that is any string not including / or . pattern = arg:gsub('*','[^/%%.]*') end for k, _ in pairs(fileSize) do if k:match(pattern) then nameList[#nameList+1] = k else fileSize[k] = nil end end table.sort(nameList) function cxt.getData(c) -- upval: cmd, fileSize, nameList local list, user = {}, c.FTP.user for i = 1,10 do -- luacheck: no unused if #nameList == 0 then break end local f = table.remove(nameList, 1) list[#list+1] = (cmd == "LIST") and ("-rw-r--r-- 1 %s %s %6u Jan 1 00:00 %s\r\n"):format(user, user, fileSize[f], f) or (f.."\r\n") end return table.concat(list) end elseif cmd == "RETR" then local f = file.open(arg, "r") if f then -- define a getter to read the file function cxt.getData(c) -- luacheck: ignore c -- upval: f local buf = f:read(1024) if not buf then f:close(); f = nil; end return buf end -- cxt.getData() end elseif cmd == "STOR" then local f = file.open(arg, "w") if f then -- define a setter to write the file function cxt.setData(c, rec) -- luacheck: ignore c -- upval: f (, arg) cxt.debug("writing %u bytes to %s", #rec, arg) return f:write(rec) end -- cxt.saveData(rec) function cxt.fileClose(c) -- luacheck: ignore c -- upval: f (,arg) cxt.debug("closing %s", arg) f:close(); f = nil end -- cxt.close() end end send((cxt.getData or cxt.setData) and "150 Accepted data connection" or "451 Can't open/create "..arg) if cxt.getData and cxt.dataSocket then cxt.debug ("poking sender to initiate first xfer") node.task.post(function() cxt.sender(cxt.dataSocket) end) -- upval: cxt end end --[[SPLIT IGNORE]] function FTP.dataServer(...) --[[SPLIT HERE ftp-dataServer]] ----------------------------- Data Port Routines ----------------------------- -- These are used to manage the data transfer over the data port. This is -- set up lazily either by a PASV or by the first LIST NLST RETR or STOR -- command that uses it. These also provide a sendData / receiveData cb to -- handle the actual xfer. Also note that the sending process can be primed in -- ---------------- Open a new data server and port --------------------------- local cxt, n = ... local dataSvr = cxt.dataServer if dataSvr then pcall(dataSvr.close, dataSrv) end -- luacheck: ignore -- close any existing listener if n then -- Open a new listener if needed. Note that this is only used to establish -- a single connection, so ftpDataOpen closes the server socket dataSvr = net.createServer(net.TCP, 300) cxt.dataServer = dataSvr dataSvr:listen(n, function(sock) -- upval: cxt cxt.FTP.ftpDataOpen(cxt,sock) end) cxt.debug("Listening on Data port %u, server %s",n, tostring(cxt.dataServer)) else cxt.dataServer = nil cxt.debug("Stopped listening on Data port",n) end end --[[SPLIT IGNORE]] function FTP.ftpDataOpen(...) --[[SPLIT HERE ftp-ftpDataOpen]] ----------------------- Connection on FTP data port ------------------------ local cxt, dataSocket = ... local sport,sip = dataSocket:getaddr() local cport,cip = dataSocket:getpeer() cxt.debug("Opened data socket %s from %s:%u to %s:%u", tostring(dataSocket),sip,sport,cip,cport ) cxt.dataSocket = dataSocket cxt.dataServer:close() cxt.dataServer = nil function cxt.cleardown(cxt, skt, cdtype) --luacheck: ignore cxt -- shadowing -- luacheck: ignore cdtype which cdtype = cdtype==1 and "disconnection" or "reconnection" local which = cxt.setData and "setData" or (cxt.getData and cxt.getData or "neither") cxt.debug("Cleardown entered from %s with %s", cdtype, which) if cxt.setData then cxt:fileClose() cxt.setData = nil cxt.send("226 Transfer complete.") else cxt.getData, cxt.sender = nil, nil end cxt.debug("Clearing down data socket %s", tostring(skt)) node.task.post(function() -- upval: cxt, skt pcall(skt.close, skt); skt=nil cxt.dataSocket = nil end) end local on_hold = false dataSocket:on("receive", function(skt, rec) -- upval: cxt, on_hold local rectype = cxt.setData and "setData" or (cxt.getData and cxt.getData or "neither") cxt.debug("Received %u data bytes with %s", #rec, rectype) if not cxt.setData then return end if not on_hold then -- Cludge to stop the client flooding the ESP SPIFFS on an upload of a -- large file. As soon as a record arrives assert a flow control hold. -- This can take up to 5 packets to come into effect at which point the -- low priority unhold task is executed releasing the flow again. cxt.debug("Issuing hold on data socket %s", tostring(skt)) skt:hold(); on_hold = true node.task.post(node.task.LOW_PRIORITY, function() -- upval: skt, on_hold cxt.debug("Issuing unhold on data socket %s", tostring(skt)) pcall(skt.unhold, skt); on_hold = false end) end if not cxt:setData(rec) then cxt.debug("Error writing to SPIFFS") cxt:fileClose() cxt.setData = nil cxt.send("552 Upload aborted. Exceeded storage allocation") end end) function cxt.sender(skt) -- upval: cxt cxt.debug ("entering sender") if not cxt.getData then return end skt = skt or cxt.dataSocket local rec = cxt:getData() if rec and #rec > 0 then cxt.debug("Sending %u data bytes", #rec) skt:send(rec) else cxt.debug("Send of data completed") skt:close() cxt.send("226 Transfer complete.") cxt.getData, cxt.dataSocket = nil, nil end end dataSocket:on("sent", cxt.sender) dataSocket:on("disconnection", function(skt) return cxt:cleardown(skt,1) end) -- upval: cxt dataSocket:on("reconnection", function(skt) return cxt:cleardown(skt,2) end) -- upval: cxt -- if we are sending to client then kick off the first send if cxt.getData then cxt.sender(cxt.dataSocket) end end --[[SPLIT HERE]] return FTP --[[SPLIT IGNORE]]
mit
maxrio/packages981213
net/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan/memberconfig.lua
110
1317
-- ------ extra functions ------ -- function cbi_add_interface(field) uci.cursor():foreach("mwan3", "interface", function (section) field:value(section[".name"]) end ) end -- ------ member configuration ------ -- dsp = require "luci.dispatcher" arg[1] = arg[1] or "" m5 = Map("mwan3", translate("MWAN Member Configuration - ") .. arg[1]) m5.redirect = dsp.build_url("admin", "network", "mwan", "configuration", "member") mwan_member = m5:section(NamedSection, arg[1], "member", "") mwan_member.addremove = false mwan_member.dynamic = false interface = mwan_member:option(Value, "interface", translate("Interface")) cbi_add_interface(interface) metric = mwan_member:option(Value, "metric", translate("Metric"), translate("Acceptable values: 1-1000. Defaults to 1 if not set")) metric.datatype = "range(1, 1000)" weight = mwan_member:option(Value, "weight", translate("Weight"), translate("Acceptable values: 1-1000. Defaults to 1 if not set")) weight.datatype = "range(1, 1000)" -- ------ currently configured interfaces ------ -- mwan_interface = m5:section(TypedSection, "interface", translate("Currently Configured Interfaces")) mwan_interface.addremove = false mwan_interface.dynamic = false mwan_interface.sortable = false mwan_interface.template = "cbi/tblsection" return m5
gpl-2.0
adamflott/wargus
scripts/ai/ai_nephrite_2013.lua
1
18820
-- _________ __ __ -- / _____// |_____________ _/ |______ ____ __ __ ______ -- \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/ -- / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ \ -- /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ > -- \/ \/ \//_____/ \/ -- ______________________ ______________________ -- T H E W A R B E G I N S -- Stratagus - A free fantasy real time strategy game engine -- -- ai_nephrite_2013.lua - Nephrite AI 2013 -- -- (c) Copyright 2012-2013 by Kyran Jackson -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -- -- This edition was started on 11/11/2013. local nephrite_build = {} -- What the AI is going to build. local nephrite_attackbuffer = {} -- The AI attacks when it has this many units. local nephrite_attackforce = {} local nephrite_wait = {} -- How long the AI waits for the next attack. local nephrite_increment = {} -- How large the attack force is increased by. local nephrite_modifier_cav = {} local nephrite_modifier_archer = {} function AiNephrite_Setup_2013() nephrite_build[AiPlayer()] = "Footman" nephrite_attackbuffer[AiPlayer()] = 8 nephrite_wait[AiPlayer()] = 100 nephrite_attackforce[AiPlayer()] = 1 nephrite_modifier_cav[AiPlayer()] = 1 nephrite_modifier_archer[AiPlayer()] = 1 nephrite_increment[AiPlayer()] = 0.1 end function AiNephrite_2013() if (nephrite_attackforce[AiPlayer()] ~= nil) then if ((nephrite_wait[AiPlayer()] < 3) or (nephrite_wait[AiPlayer()] == 11) or (nephrite_wait[AiPlayer()] == 21) or (nephrite_wait[AiPlayer()] == 21) or (nephrite_wait[AiPlayer()] == 31) or (nephrite_wait[AiPlayer()] == 41) or (nephrite_wait[AiPlayer()] == 51) or (nephrite_wait[AiPlayer()] == 61) or (nephrite_wait[AiPlayer()] == 71) or (nephrite_wait[AiPlayer()] == 81) or (nephrite_wait[AiPlayer()] == 91) or (nephrite_wait[AiPlayer()] == 101)) then AiNephrite_Flush_2013() end AiNephrite_Pick_2013() if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiFarm()) >= 1) then if ((GetPlayerData(AiPlayer(), "Resources", "gold") > 800) and (GetPlayerData(AiPlayer(), "Resources", "wood") > 200)) then if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiBetterCityCenter()) > 0) and (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) == 0)) then if ((GetPlayerData(AiPlayer(), "Resources", "gold") > 2500) and (GetPlayerData(AiPlayer(), "Resources", "wood") > 1200)) then AiNephrite_Train_2013() end else AiNephrite_Train_2013() end elseif (GameCycle >= 5000) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiWorker()) < 20) then AiSet(AiWorker(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiWorker()) + 1) end if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) > 0) then AiNephrite_Train_2013() end end end if (nephrite_wait[AiPlayer()] < 2) then AiNephrite_Attack_2013() --AiForce(0, {AiSoldier(), 2}) else nephrite_wait[AiPlayer()] = nephrite_wait[AiPlayer()] - 1 end AiNephrite_Research_2013() AiNephrite_Expand_2013() else AiNephrite_Setup_2013() end end function AiNephrite_Flush_2013() AiSet(AiBarracks(), 0) AiSet(AiCityCenter(), 0) AiSet(AiFarm(), 1) AiSet(AiBlacksmith(), 0) AiSet(AiLumberMill(), 0) AiSet(AiStables(), 0) AiSet(AiWorker(), 0) AiSet(AiCatapult(), 0) AiSet(AiShooter(), 0) AiSet(AiCavalry(), 0) AiSet(AiSoldier(), 0) end function AiNephrite_Pick_2013() -- What am I going to build next? nephrite_build[AiPlayer()] = SyncRand(4) if (nephrite_build[AiPlayer()] == 1) then if ((nephrite_modifier_archer[AiPlayer()] == 0) or ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiShooter())/2) > (GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry())))) then nephrite_build[AiPlayer()] = "Knight" else nephrite_build[AiPlayer()] = "Archer" end elseif (nephrite_build[AiPlayer()] == 2) then nephrite_build[AiPlayer()] = "Knight" elseif ((nephrite_build[AiPlayer()] == 3) and (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) >= 2)) then nephrite_build[AiPlayer()] = "Catapult" else nephrite_build[AiPlayer()] = "Knight" end if ((nephrite_modifier_cav[AiPlayer()] == 0) and (nephrite_build[AiPlayer()] == "Knight")) then nephrite_build[AiPlayer()] = "Footman" end if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiCityCenter()) > 0) then if ((((GetPlayerData(AiPlayer(), "UnitTypesCount", AiShooter()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry())) > ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiWorker())) * 2)) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiWorker()) < 10))) then AiSet(AiWorker(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiWorker()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiCityCenter())) end end end function AiNephrite_Attack_2013() if (nephrite_attackforce[AiPlayer()] ~= nil) then --AddMessage("It is time to attack.") if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiHeroRider()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiFodder()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiHeroShooter()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiFlyer()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiMage()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiHeroSoldier()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiCatapult()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiShooter()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry())) >= nephrite_attackbuffer[AiPlayer()]) then --AddMessage("Attacking with force 1.") AiForce(nephrite_attackforce[AiPlayer()], {AiFodder(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiFodder()), AiSuicideBomber(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiSuicideBomber()), AiDestroyer(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiDestroyer()), AiBattleship(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiBattleship()), AiTransporter(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiTransporter()), AiEliteSoldier(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiEliteSoldier()), AiHeroRider(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiHeroRider()), AiHeroSoldier(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiHeroSoldier()), AiMage(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiMage()), AiFlyer(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiFlyer()), AiBones(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiBones()), AiHeroShooter(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiHeroShooter()), AiCatapult(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiCatapult()), AiSoldier(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()), AiCavalry(), (GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalryMage()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry())), AiShooter(), (GetPlayerData(AiPlayer(), "UnitTypesCount", AiEliteShooter()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiShooter()))}, true) AiAttackWithForce(nephrite_attackforce[AiPlayer()]) nephrite_wait[AiPlayer()] = 150 if (nephrite_attackforce[AiPlayer()] >= 8) then nephrite_attackforce[AiPlayer()] = 1 nephrite_attackbuffer[AiPlayer()] = nephrite_attackbuffer[AiPlayer()] + nephrite_increment[AiPlayer()] AiForce(0, {AiEliteSoldier(), 0, AiHeroRider(), 0, AiHeroSoldier(), 0, AiMage(), 0, AiFlyer(), 0, AiBones(), 0, AiHeroShooter(), 0, AiCatapult(), 0, AiSoldier(), 0, AiCavalry(), 0, AiShooter(), 0}) AiForce(1, {AiEliteSoldier(), 0, AiHeroRider(), 0, AiHeroSoldier(), 0, AiMage(), 0, AiFlyer(), 0, AiBones(), 0, AiHeroShooter(), 0, AiCatapult(), 0, AiSoldier(), 0, AiCavalry(), 0, AiShooter(), 0}, true) AiForce(2, {AiEliteSoldier(), 0, AiHeroRider(), 0, AiHeroSoldier(), 0, AiMage(), 0, AiFlyer(), 0, AiBones(), 0, AiHeroShooter(), 0, AiCatapult(), 0, AiSoldier(), 0, AiCavalry(), 0, AiShooter(), 0}, true) AiForce(3, {AiEliteSoldier(), 0, AiHeroRider(), 0, AiHeroSoldier(), 0, AiMage(), 0, AiFlyer(), 0, AiBones(), 0, AiHeroShooter(), 0, AiCatapult(), 0, AiSoldier(), 0, AiCavalry(), 0, AiShooter(), 0}, true) AiForce(4, {AiEliteSoldier(), 0, AiHeroRider(), 0, AiHeroSoldier(), 0, AiMage(), 0, AiFlyer(), 0, AiBones(), 0, AiHeroShooter(), 0, AiCatapult(), 0, AiSoldier(), 0, AiCavalry(), 0, AiShooter(), 0}, true) AiForce(5, {AiEliteSoldier(), 0, AiHeroRider(), 0, AiHeroSoldier(), 0, AiMage(), 0, AiFlyer(), 0, AiBones(), 0, AiHeroShooter(), 0, AiCatapult(), 0, AiSoldier(), 0, AiCavalry(), 0, AiShooter(), 0}, true) AiForce(6, {AiEliteSoldier(), 0, AiHeroRider(), 0, AiHeroSoldier(), 0, AiMage(), 0, AiFlyer(), 0, AiBones(), 0, AiHeroShooter(), 0, AiCatapult(), 0, AiSoldier(), 0, AiCavalry(), 0, AiShooter(), 0}, true) AiForce(7, {AiEliteSoldier(), 0, AiHeroRider(), 0, AiHeroSoldier(), 0, AiMage(), 0, AiFlyer(), 0, AiBones(), 0, AiHeroShooter(), 0, AiCatapult(), 0, AiSoldier(), 0, AiCavalry(), 0, AiShooter(), 0}, true) AiForce(8, {AiEliteSoldier(), 0, AiHeroRider(), 0, AiHeroSoldier(), 0, AiMage(), 0, AiFlyer(), 0, AiBones(), 0, AiHeroShooter(), 0, AiCatapult(), 0, AiSoldier(), 0, AiCavalry(), 0, AiShooter(), 0}, true) AiForce(9, {AiEliteSoldier(), 0, AiHeroRider(), 0, AiHeroSoldier(), 0, AiMage(), 0, AiFlyer(), 0, AiBones(), 0, AiHeroShooter(), 0, AiCatapult(), 0, AiSoldier(), 0, AiCavalry(), 0, AiShooter(), 0}, true) else nephrite_attackforce[AiPlayer()] = nephrite_attackforce[AiPlayer()] + 1 end end else AiNephrite_Setup_2013() end end function AiNephrite_Expand_2013() -- New in Nephrite 2013 is the expand function. if (GetPlayerData(AiPlayer(), "Resources", "gold") < 4000) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiCityCenter()) == 0) then AiSet(AiCityCenter(), 1) end elseif (GetPlayerData(AiPlayer(), "Resources", "gold") < 8000) then if (GameCycle >= 6000) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiCityCenter()) < 2) then AiSet(AiCityCenter(), 2) end end end if (GetPlayerData(AiPlayer(), "Resources", "gold") > 1000) then if ((GetPlayerData(AiPlayer(), "TotalNumUnits") / GetPlayerData(AiPlayer(), "UnitTypesCount", AiFarm())) > 4.5) then AiSet(AiFarm(), (GetPlayerData(AiPlayer(), "UnitTypesCount", AiFarm()) + 1)) end end if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiFarm()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) == 0) then if (GetPlayerData(AiPlayer(), "Resources", "gold") > 1000) then AiSet(AiBarracks(), 1) end elseif (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) == 1) then if (GameCycle >= 5000) then if (GetPlayerData(AiPlayer(), "Resources", "gold") > 2000) then AiSet(AiWorker(), 12) AiSet(AiBarracks(), 2) end end elseif (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) == 2) then if (GetPlayerData(AiPlayer(), "Resources", "gold") > 4000) then AiSet(AiWorker(), 16) AiSet(AiBarracks(), 3) end elseif (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) == 3) then if (GameCycle >= 10000) then if (GetPlayerData(AiPlayer(), "Resources", "gold") > 12000) then AiSet(AiWorker(), 20) AiSet(AiBarracks(), 4) end end elseif (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) == 4) then if (GetPlayerData(AiPlayer(), "Resources", "gold") > 16000) then AiSet(AiWorker(), 25) AiSet(AiBarracks(), 5) end elseif (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) == 5) then if (GetPlayerData(AiPlayer(), "Resources", "gold") > 32000) then AiSet(AiWorker(), 30) AiSet(AiBarracks(), 6) end elseif (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) > 5) then if (((GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) / GetPlayerData(AiPlayer(), "TotalResources", "gold")) > 1200) and (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) < 8)) then AiSet(AiBarracks(), (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) + 1)) end end end end function AiNephrite_Research_2013() -- New in Nephrite 2013 is the research function. -- TODO: Add captapult if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry())) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBlacksmith()) == 0) then AiSet(AiBlacksmith(), 1) else if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) == 0) then AiUpgradeTo(AiBestCityCenter()) else if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiTemple()) == 0) then AiSet(AiTemple(), 1) else AiResearch(AiUpgradeCavalryMage()) AiResearch(AiCavalryMageSpell1()) end end if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry())) >= 1) then AiResearch(AiUpgradeWeapon1()) AiResearch(AiUpgradeArmor1()) if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry())) >= 2) then AiResearch(AiUpgradeArmor2()) AiResearch(AiUpgradeWeapon2()) end end if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiShooter()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiLumberMill()) == 0) then AiSet(AiLumberMill(), 1) else AiResearch(AiUpgradeMissile1()) AiResearch(AiUpgradeMissile2()) if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiStables()) == 0) then AiSet(AiStables(), 1) else if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) == 0) then AiUpgradeTo(AiBestCityCenter()) else AiResearch(AiUpgradeEliteShooter()) AiResearch(AiUpgradeEliteShooter2()) AiResearch(AiUpgradeEliteShooter3()) end end end end end end end function AiNephrite_Train_2013() AiSetReserve({0, 400, 0, 0, 0, 0, 0}) if (nephrite_build[AiPlayer()] == "Worker") then AiSet(AiWorker(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiWorker()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiCityCenter())) elseif (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) > 0) then if (nephrite_build[AiPlayer()] == "Footman") then AiSet(AiSoldier(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks())) elseif (nephrite_build[AiPlayer()] == "Catapult") then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBlacksmith()) > 0) then AiSet(AiCatapult(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiCatapult()) + 1) else AiSet(AiBlacksmith(), 1) end elseif (nephrite_build[AiPlayer()] == "Archer") then AiSet(AiShooter(), (GetPlayerData(AiPlayer(), "UnitTypesCount", AiShooter()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()))) elseif (nephrite_build[AiPlayer()] == "Knight") then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiStables()) > 0) then AiSet(AiCavalry(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks())) else AiSet(AiSoldier(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks())) if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiBetterCityCenter()) > 0) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) > 0)) then AiSet(AiStables(), 1) elseif (GetPlayerData(AiPlayer(), "UnitTypesCount", AiCityCenter()) > 0) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiLumberMill()) > 0) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBlacksmith()) > 0) then AiUpgradeTo(AiBetterCityCenter()) else AiSet(AiBlacksmith(), 1) end else AiSet(AiLumberMill(), 1) end else AiSet(AiCityCenter(), 1) end end end else AiSet(AiBarracks(), 1) end AiSetReserve({0, 0, 0, 0, 0, 0, 0}) end function AiNephrite_NoCav_2013() if (nephrite_attackforce[AiPlayer()] ~= nil) then AiNephrite_2013() if (nephrite_attackbuffer[AiPlayer()] > 20) then nephrite_attackbuffer[AiPlayer()] = 10 end else nephrite_attackforce[AiPlayer()] = 1 nephrite_build[AiPlayer()] = "Soldier" nephrite_attackbuffer[AiPlayer()] = 1 nephrite_wait[AiPlayer()] = 100 nephrite_modifier_cav[AiPlayer()] = 0 nephrite_modifier_archer[AiPlayer()] = 1 nephrite_increment[AiPlayer()] = 1 end end function AiNephrite_Level5() AiSet(AiLumberMill(), 1) if (nephrite_attackforce[AiPlayer()] ~= nil) then if (GetPlayerData(AiPlayer(), "Resources", "gold") > 1000) then AiNephrite_Train_2013() AiNephrite_Pick_2013() if (nephrite_wait[AiPlayer()] < 2) then AiNephrite_Attack_2013() else nephrite_wait[AiPlayer()] = nephrite_wait[AiPlayer()] - 1 end AiNephrite_Research_2013() if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBlacksmith()) > 0) then AiNephrite_Expand_2013() end else AiNephrite_Attack_2013() end else nephrite_attackforce[AiPlayer()] = 1 nephrite_build[AiPlayer()] = "Archer" nephrite_attackbuffer[AiPlayer()] = 6 nephrite_wait[AiPlayer()] = 100 nephrite_modifier_cav[AiPlayer()] = 0 nephrite_modifier_archer[AiPlayer()] = 1 nephrite_increment[AiPlayer()] = 0 end end DefineAi("ai_nephrite_2013", "*", "ai_nephrite_2013", AiNephrite_2013) DefineAi("ai_nephrite_nocav_2013", "*", "ai_nephrite_nocav_2013", AiNephrite_NoCav_2013)
gpl-2.0
AliKhodadad/zed-spam
plugins/help.lua
337
5009
do function pairsByKeys(t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end -- Returns true if is not empty local function has_usage_data(dict) if (dict.usage == nil or dict.usage == '') then return false end return true end -- Get commands for that plugin local function plugin_help(name,number,requester) local plugin = "" if number then local i = 0 for name in pairsByKeys(plugins) do if plugins[name].hidden then name = nil else i = i + 1 if i == tonumber(number) then plugin = plugins[name] end end end else plugin = plugins[name] if not plugin then return nil end end local text = "" if (type(plugin.usage) == "table") then for ku,usage in pairs(plugin.usage) do if ku == 'user' then -- usage for user if (type(plugin.usage.user) == "table") then for k,v in pairs(plugin.usage.user) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.user..'\n' end elseif ku == 'moderator' then -- usage for moderator if requester == 'moderator' or requester == 'admin' or requester == 'sudo' then if (type(plugin.usage.moderator) == "table") then for k,v in pairs(plugin.usage.moderator) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.moderator..'\n' end end elseif ku == 'admin' then -- usage for admin if requester == 'admin' or requester == 'sudo' then if (type(plugin.usage.admin) == "table") then for k,v in pairs(plugin.usage.admin) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.admin..'\n' end end elseif ku == 'sudo' then -- usage for sudo if requester == 'sudo' then if (type(plugin.usage.sudo) == "table") then for k,v in pairs(plugin.usage.sudo) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.sudo..'\n' end end else text = text..usage..'\n' end end text = text..'======================\n' elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage..'\n======================\n' end return text end -- !help command local function telegram_help() local i = 0 local text = "Plugins list:\n\n" -- Plugins names for name in pairsByKeys(plugins) do if plugins[name].hidden then name = nil else i = i + 1 text = text..i..'. '..name..'\n' end end text = text..'\n'..'There are '..i..' plugins help available.' text = text..'\n'..'Write "!help [plugin name]" or "!help [plugin number]" for more info.' text = text..'\n'..'Or "!help all" to show all info.' return text end -- !help all command local function help_all(requester) local ret = "" for name in pairsByKeys(plugins) do if plugins[name].hidden then name = nil else ret = ret .. plugin_help(name, nil, requester) end end return ret end local function run(msg, matches) if is_sudo(msg) then requester = "sudo" elseif is_admin(msg) then requester = "admin" elseif is_momod(msg) then requester = "moderator" else requester = "user" end if matches[1] == "!help" then return telegram_help() elseif matches[1] == "!help all" then return help_all(requester) else local text = "" if tonumber(matches[1]) then text = plugin_help(nil, matches[1], requester) else text = plugin_help(matches[1], nil, requester) end if not text then text = telegram_help() end return text end end return { description = "Help plugin. Get info from other plugins. ", usage = { "!help: Show list of plugins.", "!help all: Show all commands for every plugin.", "!help [plugin name]: Commands for that plugin.", "!help [number]: Commands for that plugin. Type !help to get the plugin number." }, patterns = { "^!help$", "^!help all", "^!help (.+)" }, run = run } end
gpl-2.0
ashkanpj/fire
plugins/help.lua
337
5009
do function pairsByKeys(t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end -- Returns true if is not empty local function has_usage_data(dict) if (dict.usage == nil or dict.usage == '') then return false end return true end -- Get commands for that plugin local function plugin_help(name,number,requester) local plugin = "" if number then local i = 0 for name in pairsByKeys(plugins) do if plugins[name].hidden then name = nil else i = i + 1 if i == tonumber(number) then plugin = plugins[name] end end end else plugin = plugins[name] if not plugin then return nil end end local text = "" if (type(plugin.usage) == "table") then for ku,usage in pairs(plugin.usage) do if ku == 'user' then -- usage for user if (type(plugin.usage.user) == "table") then for k,v in pairs(plugin.usage.user) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.user..'\n' end elseif ku == 'moderator' then -- usage for moderator if requester == 'moderator' or requester == 'admin' or requester == 'sudo' then if (type(plugin.usage.moderator) == "table") then for k,v in pairs(plugin.usage.moderator) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.moderator..'\n' end end elseif ku == 'admin' then -- usage for admin if requester == 'admin' or requester == 'sudo' then if (type(plugin.usage.admin) == "table") then for k,v in pairs(plugin.usage.admin) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.admin..'\n' end end elseif ku == 'sudo' then -- usage for sudo if requester == 'sudo' then if (type(plugin.usage.sudo) == "table") then for k,v in pairs(plugin.usage.sudo) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.sudo..'\n' end end else text = text..usage..'\n' end end text = text..'======================\n' elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage..'\n======================\n' end return text end -- !help command local function telegram_help() local i = 0 local text = "Plugins list:\n\n" -- Plugins names for name in pairsByKeys(plugins) do if plugins[name].hidden then name = nil else i = i + 1 text = text..i..'. '..name..'\n' end end text = text..'\n'..'There are '..i..' plugins help available.' text = text..'\n'..'Write "!help [plugin name]" or "!help [plugin number]" for more info.' text = text..'\n'..'Or "!help all" to show all info.' return text end -- !help all command local function help_all(requester) local ret = "" for name in pairsByKeys(plugins) do if plugins[name].hidden then name = nil else ret = ret .. plugin_help(name, nil, requester) end end return ret end local function run(msg, matches) if is_sudo(msg) then requester = "sudo" elseif is_admin(msg) then requester = "admin" elseif is_momod(msg) then requester = "moderator" else requester = "user" end if matches[1] == "!help" then return telegram_help() elseif matches[1] == "!help all" then return help_all(requester) else local text = "" if tonumber(matches[1]) then text = plugin_help(nil, matches[1], requester) else text = plugin_help(matches[1], nil, requester) end if not text then text = telegram_help() end return text end end return { description = "Help plugin. Get info from other plugins. ", usage = { "!help: Show list of plugins.", "!help all: Show all commands for every plugin.", "!help [plugin name]: Commands for that plugin.", "!help [number]: Commands for that plugin. Type !help to get the plugin number." }, patterns = { "^!help$", "^!help all", "^!help (.+)" }, run = run } end
gpl-2.0
JarnoVgr/Mr.Green-MTA-Resources
resources/[race]/race_traffic_sensor/trafficsensor_client.lua
4
7294
-- -- traffic_sensor_client.lua -- --------------------------------------------------------------------------- -- -- Handle events from Race -- --------------------------------------------------------------------------- addEventHandler('onClientResourceStart', g_ResRoot, function() -- Bigdar.setHotKey( 'F4' ) -- Uncommented by KaliBwoy, added to settings menu end ) addEvent('onClientMapStarting', true) addEventHandler('onClientMapStarting', getRootElement(), function(mapinfo) outputDebug( 'BIGDAR', 'onClientMapStarting' ) if mapinfo.modename == "Destruction derby" or mapinfo.modename == "Freeroam" then Bigdar.allowed = false else Bigdar.allowed = true end Bigdar.finishedPlayers = {} Bigdar.allPlayers = {} end ) addEvent('onClientMapStopping', true) addEventHandler('onClientMapStopping', getRootElement(), function() outputDebug( 'BIGDAR', 'onClientMapStopping' ) end ) addEvent('onClientPlayerFinish', true) addEventHandler('onClientPlayerFinish', getRootElement(), function() outputDebug( 'BIGDAR', 'onClientPlayerFinish' ) Bigdar.finishedPlayers[source] = true end ) --------------------------------------------------------------------------- -- Bigdar - Big radar --------------------------------------------------------------------------- Bigdar = {} Bigdar.smoothList = {} -- {player = rrz} Bigdar.allPlayers = {} Bigdar.finishedPlayers = {} Bigdar.lastSmoothSeconds = 0 Bigdar.beginValidSeconds = nil Bigdar.enabled = true -- Manual override Bigdar.allowed = true -- Map override Bigdar.hidden = false -- Black screen override Bigdar.hotkey = nil -- Current hotkey function Bigdar.setHotKey ( hotkey ) if Bigdar.hotkey then unbindKey ( Bigdar.hotkey, 'down', "showsensor" ) end if hotkey and Bigdar.hotkey and hotkey ~= Bigdar.hotkey then outputConsole( "Race Traffic Sensor hotkey is now '" .. tostring(hotkey) .. "'" ) end Bigdar.hotkey = hotkey if Bigdar.hotkey then bindKey ( Bigdar.hotkey, 'down', "showsensor" ) end end function Bigdar.toggle() Bigdar.enabled = not Bigdar.enabled outputChatBox( 'Traffic Sensor is now ' .. (Bigdar.enabled and 'on' or 'off') ) end function isPlayerFinished(player) return Bigdar.finishedPlayers[player] end function Bigdar.render() -- Ensure map allows it, and player not dead, and in a vehicle and not spectating local vehicle = getPedOccupiedVehicle(g_Me) if not Bigdar.allowed or isPedDead(g_Me) or isPlayerFinished(g_Me) or not vehicle or getCameraTarget() ~= vehicle then Bigdar.beginValidSeconds = nil return end -- Ensure at least 1 second since g_BeginValidSeconds was set local timeSeconds = getSecondCount() if not Bigdar.beginValidSeconds then Bigdar.beginValidSeconds = timeSeconds end if timeSeconds - Bigdar.beginValidSeconds < 1 then return end -- No draw if faded out or not enabled if Bigdar.hidden or not Bigdar.enabled then return end -- Icon definition local icon = { file='img/arrow_ts.png', w=80, h=56 } -- Calc smoothing vars local delta = timeSeconds - Bigdar.lastSmoothSeconds Bigdar.lastSmoothSeconds = timeSeconds local timeslice = math.clamp(0,delta*14,1) -- Get screen dimensions local screenX,screenY = guiGetScreenSize() local halfScreenX = screenX * 0.5 local halfScreenY = screenY * 0.5 -- Get my pos and rot local mx, my, mz = getElementPosition(g_Me) local _, _, mrz = getCameraRot() -- To radians mrz = math.rad(-mrz) if #Bigdar.allPlayers == 0 then Bigdar.allPlayers = getElementsByType('player') end -- For each 'other player' local dim = getElementData(localPlayer, "dim") for i,player in ipairs(Bigdar.allPlayers) do if player ~= g_Me and not isPedDead(player) and not isPlayerFinished(player) and (dim == getElementData(player, "dim")) then -- Get other pos local ox, oy, oz = getElementPosition(player) -- Only draw marker if other player it is close enough, and not on screen local maxDistance = 60 local alpha = 1 - getDistanceBetweenPoints3D( mx, my, mz, ox, oy, oz ) / maxDistance local onScreen = getScreenFromWorldPosition ( ox, oy, oz ) if onScreen or alpha <= 0 then -- If no draw, reset smooth position Bigdar.smoothList[player] = nil else -- Calc arrow color local r,g,b = 255,220,210 local team = getPlayerTeam(player) if team then r,g,b = getTeamColor(team) end -- Calc draw scale local scalex = alpha * 0.5 + 0.5 local scaley = alpha * 0.25 + 0.75 -- Calc dir to local dx = ox - mx local dy = oy - my -- Calc rotz to local drz = math.atan2(dx,dy) -- Calc relative rotz to local rrz = drz - mrz -- Add smoothing to the relative rotz local smooth = Bigdar.smoothList[player] or rrz smooth = math.wrapdifference(-math.pi, smooth, rrz, math.pi) if math.abs(smooth-rrz) > 1.57 then smooth = rrz -- Instant jump if more than 1/4 of a circle to go end smooth = math.lerp( smooth, rrz, timeslice ) Bigdar.smoothList[player] = smooth rrz = smooth -- Calc on screen pos for relative rotz local sx = math.sin(rrz) local sy = math.cos(rrz) -- Draw at edge of screen local X1 = halfScreenX local Y1 = halfScreenY local X2 = sx * halfScreenX + halfScreenX local Y2 = -sy * halfScreenY + halfScreenY local X local Y if math.abs(sx) > math.abs(sy) then -- Left or right if X2 < X1 then -- Left X = 32 Y = Y1+ (Y2-Y1)* (X-X1) / (X2-X1) else -- right X = screenX-32 Y = Y1+ (Y2-Y1)* (X-X1) / (X2-X1) end else -- Top or bottom if Y2 < Y1 then -- Top Y = 32 X = X1+ (X2-X1)* (Y-Y1) / (Y2 - Y1) else -- bottom Y = screenY-32 X = X1+ (X2-X1)* (Y-Y1) / (Y2 - Y1) end end dxDrawImage ( X-icon.w/2*scalex, Y-icon.h/2*scaley, icon.w*scalex, icon.h*scaley, icon.file, 180 + rrz * 180 / math.pi, 0, 0, tocolor(r,g,b,255*alpha), false ) end end end end addEventHandler('onClientRender', g_Root, Bigdar.render) --------------------------------------------------------------------------- -- Various events addEventHandler('onClientPlayerJoin', g_Root, function() table.insertUnique(Bigdar.allPlayers, source) end ) addEventHandler('onClientPlayerQuit', g_Root, function() table.removevalue(Bigdar.finishedPlayers,source) table.removevalue(Bigdar.allPlayers,source) Bigdar.smoothList[source] = nil end ) addEvent ( "onClientScreenFadedOut", true ) addEventHandler ( "onClientScreenFadedOut", g_Root, function() Bigdar.hidden = true end ) addEvent ( "onClientScreenFadedIn", true ) addEventHandler ( "onClientScreenFadedIn", g_Root, function() Bigdar.hidden = false end ) --------------------------------------------------------------------------- -- -- Commands and binds -- -- -- --------------------------------------------------------------------------- function onHotKey() Bigdar.toggle() end addCommandHandler ( "showsensor", onHotKey ) addCommandHandler('doF4', function(player,command,...) outputDebugString('doF4') Bigdar.toggle() end ) -- Exported function for settings menu, KaliBwoy function showTrafficSensor() Bigdar.enabled = true end function hideTrafficSensor() Bigdar.enabled = false end
mit
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/ImageView.lua
4
4394
-------------------------------- -- @module ImageView -- @extend Widget -- @parent_module ccui -------------------------------- -- Load texture for imageview.<br> -- param fileName file name of texture.<br> -- param texType @see `Widget::TextureResType` -- @function [parent=#ImageView] loadTexture -- @param self -- @param #string fileName -- @param #int texType -- @return ImageView#ImageView self (return value: ccui.ImageView) -------------------------------- -- -- @function [parent=#ImageView] init -- @param self -- @param #string imageFileName -- @param #int texType -- @return bool#bool ret (return value: bool) -------------------------------- -- Enable scale9 renderer.<br> -- param enabled Set to true will use scale9 renderer, false otherwise. -- @function [parent=#ImageView] setScale9Enabled -- @param self -- @param #bool enabled -- @return ImageView#ImageView self (return value: ccui.ImageView) -------------------------------- -- Updates the texture rect of the ImageView in points.<br> -- It will call setTextureRect:rotated:untrimmedSize with rotated = NO, and utrimmedSize = rect.size. -- @function [parent=#ImageView] setTextureRect -- @param self -- @param #rect_table rect -- @return ImageView#ImageView self (return value: ccui.ImageView) -------------------------------- -- Sets capInsets for imageview.<br> -- The capInsets affects the ImageView's renderer only if `setScale9Enabled(true)` is called.<br> -- param capInsets capinsets for imageview -- @function [parent=#ImageView] setCapInsets -- @param self -- @param #rect_table capInsets -- @return ImageView#ImageView self (return value: ccui.ImageView) -------------------------------- -- -- @function [parent=#ImageView] getRenderFile -- @param self -- @return ResourceData#ResourceData ret (return value: cc.ResourceData) -------------------------------- -- Get ImageView's capInsets size.<br> -- return Query capInsets size in Rect<br> -- see `setCapInsets(const Rect&)` -- @function [parent=#ImageView] getCapInsets -- @param self -- @return rect_table#rect_table ret (return value: rect_table) -------------------------------- -- Query whether button is using scale9 renderer or not.<br> -- return whether button use scale9 renderer or not. -- @function [parent=#ImageView] isScale9Enabled -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @overload self, string, int -- @overload self -- @function [parent=#ImageView] create -- @param self -- @param #string imageFileName -- @param #int texType -- @return ImageView#ImageView ret (return value: ccui.ImageView) -------------------------------- -- -- @function [parent=#ImageView] createInstance -- @param self -- @return Ref#Ref ret (return value: cc.Ref) -------------------------------- -- -- @function [parent=#ImageView] getVirtualRenderer -- @param self -- @return Node#Node ret (return value: cc.Node) -------------------------------- -- -- @function [parent=#ImageView] ignoreContentAdaptWithSize -- @param self -- @param #bool ignore -- @return ImageView#ImageView self (return value: ccui.ImageView) -------------------------------- -- -- @function [parent=#ImageView] getDescription -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ImageView] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ImageView] setGLProgram -- @param self -- @param #cc.GLProgram glProgram -- @return ImageView#ImageView self (return value: ccui.ImageView) -------------------------------- -- -- @function [parent=#ImageView] setGLProgramState -- @param self -- @param #cc.GLProgramState glProgramState -- @return ImageView#ImageView self (return value: ccui.ImageView) -------------------------------- -- -- @function [parent=#ImageView] getVirtualRendererSize -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- Default constructor<br> -- js ctor<br> -- lua new -- @function [parent=#ImageView] ImageView -- @param self -- @return ImageView#ImageView self (return value: ccui.ImageView) return nil
mit
JarnoVgr/Mr.Green-MTA-Resources
resources/[admin]/admin/client/gui/admin_stats.lua
7
5177
--[[********************************** * * Multi Theft Auto - Admin Panel * * gui\admin_stats.lua * * Original File by lil_Toady * **************************************]] aStatsForm = nil local aStatsGUI = {} function aPlayerStats ( player ) if ( aStatsForm == nil ) then local x, y = guiGetScreenSize() aStatsForm = guiCreateWindow ( x / 2 - 230, y / 2 - 200, 460, 400, "Player Stats Management", false ) guiCreateHeader ( 0.05, 0.06, 0.20, 0.05, "Weapon Skills:", true, aStatsForm ) local weapons = { "Pistol", "Silenced Pistol", "Desert Eagle", "Shotgun", "Sawn off", "Spaz12", "Uzi", "MP5", "AK47", "M4", "Sniper" } local weapon = 1 while weapon <= 11 do local stat = weapon + 68 aStatsGUI[stat] = {} local label = guiCreateLabel ( 0.05, 0.06 + 0.07 * weapon, 0.20, 0.07, weapons[weapon]..":", true, aStatsForm ) guiLabelSetHorizontalAlign ( label, "right", false ) aStatsGUI[stat]["value"] = guiCreateEdit ( 0.26, 0.05 + 0.07 * weapon, 0.11, 0.06, "0", true, aStatsForm ) guiEditSetMaxLength ( aStatsGUI[stat]["value"], 4 ) aStatsGUI[stat]["button"] = guiCreateButton ( 0.37, 0.05 + 0.07 * weapon, 0.10, 0.06, "Set", true, aStatsForm, "setstat" ) weapon = weapon + 1 end guiCreateStaticImage ( 0.50, 0.12, 0.0025, 0.75, "client\\images\\dot.png", true, aStatsForm ) guiCreateHeader ( 0.60, 0.06, 0.20, 0.05, "Body:", true, aStatsForm ) local bodys = { "Fat", "Stamina", "Muscles", "Health" } local body = 1 while body <= 4 do local stat = body + 20 aStatsGUI[stat] = {} local label = guiCreateLabel ( 0.50, 0.06 + 0.07 * body, 0.20, 0.07, bodys[body]..":", true, aStatsForm ) guiLabelSetHorizontalAlign ( label, "right", false ) aStatsGUI[stat]["value"] = guiCreateEdit ( 0.71, 0.05 + 0.07 * body, 0.11, 0.06, "0", true, aStatsForm ) guiEditSetMaxLength ( aStatsGUI[stat]["value"], 4 ) aStatsGUI[stat]["button"] = guiCreateButton ( 0.82, 0.05 + 0.07 * body, 0.10, 0.06, "Set", true, aStatsForm, "setstat" ) body = body + 1 end local label = guiCreateLabel ( 0.50, 0.61, 0.20, 0.07, "Fighting Style:", true, aStatsForm ) guiLabelSetHorizontalAlign ( label, "right", false ) aStatsGUI[300] = {} aStatsGUI[300]["value"] = guiCreateEdit ( 0.71, 0.60, 0.11, 0.06, "4", true, aStatsForm ) guiEditSetMaxLength ( aStatsGUI[300]["value"], 2 ) aStatsGUI[300]["button"] = guiCreateButton ( 0.82, 0.60, 0.10, 0.06, "Set", true, aStatsForm ) guiCreateLabel ( 0.55, 0.67, 0.35, 0.07, "Accepted values: 4-7, 15, 16", true, aStatsForm ) guiCreateLabel ( 0.05, 0.93, 0.60, 0.05, "* Only numerical values from 0 to 1000 accepted", true, aStatsForm ) aStatsClose = guiCreateButton ( 0.80, 0.90, 0.14, 0.09, "Close", true, aStatsForm ) addEventHandler ( "onClientGUIClick", aStatsForm, aClientStatsClick ) addEventHandler ( "onClientGUIChanged", aStatsForm, aClientStatsChanged ) addEventHandler ( "onClientGUIAccepted", aStatsForm, aClientStatsAccepted ) --Register With Admin Form aRegister ( "PlayerStats", aStatsForm, aPlayerStats, aPlayerStatsClose ) end aStatsSelect = player guiSetVisible ( aStatsForm, true ) guiBringToFront ( aStatsForm ) end function aPlayerStatsClose ( destroy ) if ( ( destroy ) or ( guiCheckBoxGetSelected ( aPerformanceStats ) ) ) then if ( aStatsForm ) then removeEventHandler ( "onClientGUIClick", aStatsForm, aClientStatsClick ) removeEventHandler ( "onClientGUIChanged", aStatsForm, aClientStatsChanged ) removeEventHandler ( "onClientGUIAccepted", aStatsForm, aClientStatsAccepted ) destroyElement ( aStatsForm ) aStatsForm = nil end else guiSetVisible ( aStatsForm, false ) end end function aClientStatsClick ( button ) if ( button == "left" ) then if ( source == aStatsClose ) then aPlayerStatsClose ( false ) else for id, element in pairs ( aStatsGUI ) do if ( element["button"] == source ) then local value = tonumber ( guiGetText ( element["value"] ) ) if ( ( value ) and ( value >= 0 ) and ( value <= 1000 ) ) then triggerServerEvent ( "aPlayer", getLocalPlayer(), aStatsSelect, "setstat", id, value ) else aMessageBox ( "error", "Not numerical value (0-1000)" ) end return end end end end end function aClientStatsChanged () for id, element in pairs ( aStatsGUI ) do if ( element["value"] == source ) then if ( guiGetText ( source ) ~= "" ) then local input = tonumber ( guiGetText ( source ) ) if ( not input ) then guiSetText ( source, string.gsub ( guiGetText ( source ), "[^%d]", "" ) ) elseif ( input > 1000 ) then guiSetText ( source, "1000" ) elseif ( input < 0 ) then guiSetText ( source, "0" ) end end return end end end function aClientStatsAccepted () for id, element in pairs ( aStatsGUI ) do if ( element["value"] == source ) then local value = tonumber ( guiGetText ( element["value"] ) ) if ( ( value ) and ( value >= 0 ) and ( value <= 1000 ) ) then triggerServerEvent ( "aPlayer", getLocalPlayer(), aStatsSelect, "setstat", id, value ) else aMessageBox ( "error", "Not numerical value (0-1000)" ) end return end end end
mit
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/tests/lua-tests/src/CocosDenshionTest/CocosDenshionTest.lua
6
7421
local EFFECT_FILE = "effect1.wav" local MUSIC_FILE = nil local targetPlatform = cc.Application:getInstance():getTargetPlatform() if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) then MUSIC_FILE = "background.caf" else MUSIC_FILE = "background.mp3" end local LINE_SPACE = 40 local function CocosDenshionTest() local ret = cc.Layer:create() local m_pItmeMenu = nil local m_tBeginPos = cc.p(0, 0) local m_nSoundId = 0 local testItems = { "play background music", "stop background music", "pause background music", "resume background music", "rewind background music", "is background music playing(output on the console)", "play effect", "play effect repeatly", "stop effect", "unload effect", "add background music volume", "sub background music volume", "add effects volume", "sub effects volume", "pause effect", "resume effect", "pause all effects", "resume all effects", "stop all effects" } local function menuCallback(tag, pMenuItem) local nIdx = pMenuItem:getLocalZOrder() - 10000 -- play background music if nIdx == 0 then AudioEngine.playMusic(MUSIC_FILE, true) elseif nIdx == 1 then -- stop background music AudioEngine.stopMusic() elseif nIdx == 2 then -- pause background music AudioEngine.pauseMusic() elseif nIdx == 3 then -- resume background music AudioEngine.resumeMusic() -- rewind background music elseif nIdx == 4 then AudioEngine.rewindMusic() elseif nIdx == 5 then -- is background music playing if AudioEngine.isMusicPlaying () then cclog("background music is playing") else cclog("background music is not playing") end elseif nIdx == 6 then -- play effect m_nSoundId = AudioEngine.playEffect(EFFECT_FILE) elseif nIdx == 7 then -- play effect m_nSoundId = AudioEngine.playEffect(EFFECT_FILE, true) elseif nIdx == 8 then -- stop effect AudioEngine.stopEffect(m_nSoundId) elseif nIdx == 9 then -- unload effect AudioEngine.unloadEffect(EFFECT_FILE) elseif nIdx == 10 then -- add bakcground music volume AudioEngine.setMusicVolume(AudioEngine.getMusicVolume() + 0.1) elseif nIdx == 11 then -- sub backgroud music volume AudioEngine.setMusicVolume(AudioEngine.getMusicVolume() - 0.1) elseif nIdx == 12 then -- add effects volume AudioEngine.setEffectsVolume(AudioEngine.getEffectsVolume() + 0.1) elseif nIdx == 13 then -- sub effects volume AudioEngine.setEffectsVolume(AudioEngine.getEffectsVolume() - 0.1) elseif nIdx == 14 then AudioEngine.pauseEffect(m_nSoundId) elseif nIdx == 15 then AudioEngine.resumeEffect(m_nSoundId) elseif nIdx == 16 then AudioEngine.pauseAllEffects() elseif nIdx == 17 then AudioEngine.resumeAllEffects() elseif nIdx == 18 then AudioEngine.stopAllEffects() end end -- add menu items for tests m_pItmeMenu = cc.Menu:create() m_nTestCount = table.getn(testItems) local i = 1 for i = 1, m_nTestCount do local label = cc.Label:createWithTTF(testItems[i], s_arialPath, 24) label:setAnchorPoint(cc.p(0.5, 0.5)) local pMenuItem = cc.MenuItemLabel:create(label) pMenuItem:registerScriptTapHandler(menuCallback) m_pItmeMenu:addChild(pMenuItem, i + 10000 -1) pMenuItem:setPosition( cc.p( VisibleRect:center().x, (VisibleRect:top().y - i * LINE_SPACE) )) end m_pItmeMenu:setContentSize(cc.size(VisibleRect:getVisibleRect().width, (m_nTestCount + 1) * LINE_SPACE)) m_pItmeMenu:setPosition(cc.p(0, 0)) ret:addChild(m_pItmeMenu) -- preload background music and effect AudioEngine.preloadMusic( MUSIC_FILE ) AudioEngine.preloadEffect( EFFECT_FILE ) -- set default volume AudioEngine.setEffectsVolume(0.5) AudioEngine.setMusicVolume(0.5) local function onNodeEvent(event) if event == "enter" then elseif event == "exit" then AudioEngine.destroyInstance() end end ret:registerScriptHandler(onNodeEvent) local prev = {x = 0, y = 0} local function onTouchEvent(eventType, x, y) if eventType == "began" then prev.x = x prev.y = y m_tBeginPos = cc.p(x, y) return true elseif eventType == "moved" then local touchLocation = cc.p(x, y) local nMoveY = touchLocation.y - m_tBeginPos.y local curPosX, curPosY = m_pItmeMenu:getPosition() local curPos = cc.p(curPosX, curPosY) local nextPos = cc.p(curPos.x, curPos.y + nMoveY) if nextPos.y < 0.0 then m_pItmeMenu:setPosition(cc.p(0, 0)) end if nextPos.y > ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height) then m_pItmeMenu:setPosition(cc.p(0, ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height))) end m_pItmeMenu:setPosition(nextPos) m_tBeginPos.x = touchLocation.x m_tBeginPos.y = touchLocation.y prev.x = x prev.y = y end end local function onTouchBegan(touch, event) local location = touch:getLocation() prev.x = location.x prev.y = location.y m_tBeginPos = location return true end local function onTouchMoved(touch, event) local location = touch:getLocation() local touchLocation = location local nMoveY = touchLocation.y - m_tBeginPos.y local curPosX, curPosY = m_pItmeMenu:getPosition() local curPos = cc.p(curPosX, curPosY) local nextPos = cc.p(curPos.x, curPos.y + nMoveY) if nextPos.y < 0.0 then m_pItmeMenu:setPosition(cc.p(0, 0)) end if nextPos.y > ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height) then m_pItmeMenu:setPosition(cc.p(0, ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height))) end m_pItmeMenu:setPosition(nextPos) m_tBeginPos.x = touchLocation.x m_tBeginPos.y = touchLocation.y prev.x = location.x prev.y = location.y end local listener = cc.EventListenerTouchOneByOne:create() listener:setSwallowTouches(true) listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN ) listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED ) local eventDispatcher = ret:getEventDispatcher() eventDispatcher:addEventListenerWithSceneGraphPriority(listener, ret) return ret end function CocosDenshionTestMain() cclog("CocosDenshionTestMain") local scene = cc.Scene:create() scene:addChild(CocosDenshionTest()) scene:addChild(CreateBackMenuItem()) return scene end
mit
JarnoVgr/Mr.Green-MTA-Resources
resources/[race]/race/_joiner.lua
4
6557
-- -- joiner.lua -- -- 1. Delay onPlayerJoin until client loaded -- 2. Patch the following calls to only use the joined players: -- getElementsByType('player') -- getDeadPlayers -- getPlayerCount -- getRandomPlayer -- 3. In any call that uses getRootElement() or g_Root to specify all players, use -- g_RootPlayers instead. Or use the function onlyJoined(element) to handle the choice. -- g_Root = getRootElement() g_ResRoot = getResourceRootElement(getThisResource()) addEvent('onPlayerJoining') -- Pre join addEvent('onPlayerJoined') -- Post join --------------------------------- -- -- Hook events -- --------------------------------- g_EventHandlers = { onPlayerJoin = {} -- { i = { elem = elem, fn = fn, getpropagated = bool } } } -- Divert 'onEventName' to '_onEventName' for eventName,_ in pairs(g_EventHandlers) do addEvent('_'..eventName) addEventHandler(eventName, g_Root, function(...) triggerEvent( '_'..eventName, source, ... ) end) end -- Catch addEventHandler calls here and save the ones listed in g_EventHandlers _addEventHandler = addEventHandler function addEventHandler(event, elem, fn, getPropagated) getPropagated = getPropagated==nil and true or getPropagated if g_EventHandlers[event] then table.insert(g_EventHandlers[event], { elem = elem, fn = fn, getpropagated = getPropagated }) else return _addEventHandler(event, elem, fn, getPropagated) end end -- Catch removeEventHandler calls here and remove saved ones listed in g_EventHandlers _removeEventHandler = removeEventHandler function removeEventHandler(event, elem, fn) if g_EventHandlers[event] then local handler for i=#g_EventHandlers[event],1,-1 do handler = g_EventHandlers[event][i] if handler.elem == elem and handler.fn == fn then table.remove(g_EventHandlers[event], i) end end else _removeEventHandler(event, elem, fn) end end -- call the saved handlers for 'onEventName' function callSavedEventHandlers(eventName, eventSource, ...) for _,handler in ipairs(g_EventHandlers[eventName]) do local triggeredElem = eventSource or g_Root if isElement(triggeredElem) then while true do if triggeredElem == handler.elem then source = eventSource handler.fn(...) break end if not handler.getpropagated or triggeredElem == g_Root then break end triggeredElem = getElementParent(triggeredElem) end end end end ---------------------------------------------------------------------------- -- -- Function patches -- Modify functions to act only on joined players -- ---------------------------------------------------------------------------- -- getElementsByType patch _getElementsByType = getElementsByType function getElementsByType( type, startat ) startat = startat or getRootElement() if type ~= 'player' then return _getElementsByType( type, startat ) else return _getElementsByType( type, onlyJoined(startat) ) end end -- getDeadPlayers patch _getDeadPlayers = getDeadPlayers function getDeadPlayers() local deadPlayers = _getDeadPlayers() for i,player in ipairs(getElementChildren(g_RootJoining)) do table.removevalue(deadPlayers,player) end return deadPlayers end -- getPlayerCount patch _getPlayerCount = getPlayerCount function getPlayerCount() return g_RootPlayers and getElementChildrenCount(g_RootPlayers) or 0 end -- getRandomPlayer patch function getRandomPlayer() if getPlayerCount() < 1 then return nil end return getElementChildren(g_RootPlayers)[ math.random(1,getPlayerCount()) ] end ---------------------------------------------------------------------------- -- -- Others functions -- ---------------------------------------------------------------------------- -- If g_Root, change to g_RootPlayers function onlyJoined(player) if player == g_Root then if not g_RootPlayers then return getResourceRootElement(getThisResource()) -- return an element which will have no players end return g_RootPlayers end return player end -- Number of players, both pending and joined function getTotalPlayerCount(player) return _getPlayerCount() end ---------------------------------------------------------------------------- -- -- Event handlers -- ---------------------------------------------------------------------------- -- onResourceStart -- Setup joining/joined containers and put all current players into g_RootJoining addEventHandler('onResourceStart', g_ResRoot, function() -- Create a joining player node and a joined player node table.each(getElementsByType('plrcontainer'), destroyElement) g_RootJoining = createElement( 'plrcontainer', 'plrs joining' ) g_RootPlayers = createElement( 'plrcontainer', 'plrs joined' ) -- Put all current players into 'joining' group for i,player in ipairs(_getElementsByType('player')) do setElementParent( player, g_RootJoining ) end end ) -- onResourceStop -- Clean up addEventHandler('onResourceStop', g_ResRoot, function() table.each(getElementsByType('plrcontainer'), destroyElement) g_RootJoining = nil g_RootPlayers = nil end ) -- Real onPlayerJoin event was fired -- Move player element to g_RootJoining addEventHandler('_onPlayerJoin', g_Root, function () setElementParent( source, g_RootJoining ) triggerEvent( 'onPlayerJoining', source ); end ) -- onPlayerQuit -- Clean up addEventHandler('onPlayerQuit', g_Root, function() end ) -- onLoadedAtClient -- Client says he is good to go. Move player element to g_RootPlayers and call deferred onPlayerJoin event handlers. addEvent('onLoadedAtClient', true) addEventHandler('onLoadedAtClient', resourceRoot, function( player ) if checkClient( false, player, 'onLoadedAtClient' ) then return end -- Tell other clients; join completed for this player triggerClientEvent( g_RootPlayers, 'onOtherJoinCompleteAtServer', resourceRoot, player ) setElementParent( player, g_RootPlayers ) -- Tell client; join completed; and send a list of all joined players triggerClientEvent( player, 'onMyJoinCompleteAtServer', resourceRoot, getElementChildren(g_RootPlayers) ) -- Call deferred onPlayerJoin event handlers callSavedEventHandlers( 'onPlayerJoin', player ) -- Custom event for joiner aware event handlers triggerEvent( 'onPlayerJoined', player ) end )
mit
JarnoVgr/Mr.Green-MTA-Resources
resources/[admin]/admin/client/gui/admin_moddetails.lua
7
2857
--[[********************************** * * Multi Theft Auto - Admin Panel * * gui\admin_moddetails.lua * **************************************]] aModdetailsForm = nil local modDetailsPlayer = nil function aViewModdetails ( player ) modDetailsPlayer = player if ( aModdetailsForm == nil ) then local x, y = guiGetScreenSize() aModdetailsForm = guiCreateWindow ( x / 2 - 250, y / 2 - 125, 350, 350, "View Moddetails", false ) guiWindowSetSizable( aModdetailsForm, false ) aModdetailsList = guiCreateGridList ( 0.02, 0.09, 0.72, 0.85, true, aModdetailsForm ) guiGridListAddColumn( aModdetailsList, "Id", 0.25 ) guiGridListAddColumn( aModdetailsList, "Name", 0.60 ) aModdetailsRefresh = guiCreateButton ( 0.76, 0.78, 0.32, 0.05, "Refresh", true, aModdetailsForm ) aModdetailsClose = guiCreateButton ( 0.76, 0.85, 0.32, 0.05, "Close", true, aModdetailsForm ) addEventHandler ( "aModdetails", resourceRoot, aModdetailsSync ) addEventHandler ( "onClientGUIClick", aModdetailsForm, aClientModdetailsClick ) --Register With Admin Form aRegister ( "Moddetails", aModdetailsForm, aViewModdetails, aViewModdetailsClose ) end guiSetText( aModdetailsForm, "Mod details for: '" .. tostring(getPlayerName(modDetailsPlayer)) .."'" ) aHideFloaters() guiSetVisible ( aModdetailsForm, true ) guiBringToFront ( aModdetailsForm ) triggerServerEvent ( "aModdetails", resourceRoot, "get", modDetailsPlayer ) end function aViewModdetailsClose ( destroy ) if ( ( destroy ) or ( guiCheckBoxGetSelected ( aPerformanceMessage ) ) ) then if ( aModdetailsForm ) then removeEventHandler ( "aModdetails", resourceRoot, aModdetailsSync ) removeEventHandler ( "onClientGUIClick", aModdetailsForm, aClientModdetailsClick ) destroyElement ( aModdetailsForm ) aModdetailsForm = nil end else guiSetVisible ( aModdetailsForm, false ) end end function aModdetailsSync ( action, list, player ) if player ~= modDetailsPlayer then return end if ( action == "get" ) then guiGridListClear ( aModdetailsList ) destroyElement ( aModdetailsList ) aModdetailsList = guiCreateGridList ( 0.02, 0.09, 0.72, 0.85, true, aModdetailsForm ) guiGridListAddColumn( aModdetailsList, "Id", 0.25 ) guiGridListAddColumn( aModdetailsList, "Name", 0.60 ) for id,mod in ipairs( list ) do local row = guiGridListAddRow ( aModdetailsList ) guiGridListSetItemText ( aModdetailsList, row, 1, tostring(mod.id), false, false ) guiGridListSetItemText ( aModdetailsList, row, 2, tostring(mod.name), false, false ) end end end function aClientModdetailsClick ( button ) if ( button == "left" ) then if ( source == aModdetailsClose ) then aViewModdetailsClose ( false ) elseif ( source == aModdetailsRefresh ) then triggerServerEvent ( "aModdetails", resourceRoot, "get", modDetailsPlayer ) end end end
mit
Zefiros-Software/ZPM
test/src/testLoad.lua
1
1353
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- 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. -- -- @endcond --]] dofile "common/testGithub.lua" dofile "common/testUtil.lua" dofile "common/testHttp.lua" dofile "common/testEnv.lua" dofile "testLoader.lua" dofile "testConfig.lua" --dofile "testInstall.lua"
mit
PlayFab/LuaSdk
PlayFabServerSDK/PlayFab/PlayFabEconomyApi.lua
3
21513
-- PlayFab Economy API -- This is the main file you should require in your game -- All api calls are documented here: https://docs.microsoft.com/gaming/playfab/api-references/ -- Example code: -- local PlayFabEconomyApi = require("PlayFab.PlayFabEconomyApi") -- PlayFabEconomyApi.<EconomyApiCall>(request, successCallbackFunc, errorCallbackFunc) local IPlayFabHttps = require("PlayFab.IPlayFabHttps") local PlayFabSettings = require("PlayFab.PlayFabSettings") local PlayFabEconomyApi = { settings = PlayFabSettings.settings } -- Creates a new item in the working catalog using provided metadata. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/createdraftitem -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/createdraftitem#createdraftitemrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/createdraftitem#createdraftitemresponse function PlayFabEconomyApi.CreateDraftItem(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/CreateDraftItem", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Creates one or more upload URLs which can be used by the client to upload raw file data. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/createuploadurls -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/createuploadurls#createuploadurlsrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/createuploadurls#createuploadurlsresponse function PlayFabEconomyApi.CreateUploadUrls(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/CreateUploadUrls", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Deletes all reviews, helpfulness votes, and ratings submitted by the entity specified. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/deleteentityitemreviews -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/deleteentityitemreviews#deleteentityitemreviewsrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/deleteentityitemreviews#deleteentityitemreviewsresponse function PlayFabEconomyApi.DeleteEntityItemReviews(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/DeleteEntityItemReviews", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Removes an item from working catalog and all published versions from the public catalog. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/deleteitem -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/deleteitem#deleteitemrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/deleteitem#deleteitemresponse function PlayFabEconomyApi.DeleteItem(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/DeleteItem", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Gets the configuration for the catalog. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getcatalogconfig -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getcatalogconfig#getcatalogconfigrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getcatalogconfig#getcatalogconfigresponse function PlayFabEconomyApi.GetCatalogConfig(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/GetCatalogConfig", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Retrieves an item from the working catalog. This item represents the current working state of the item. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getdraftitem -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getdraftitem#getdraftitemrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getdraftitem#getdraftitemresponse function PlayFabEconomyApi.GetDraftItem(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/GetDraftItem", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Retrieves a paginated list of the items from the draft catalog. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getdraftitems -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getdraftitems#getdraftitemsrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getdraftitems#getdraftitemsresponse function PlayFabEconomyApi.GetDraftItems(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/GetDraftItems", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Retrieves a paginated list of the items from the draft catalog created by the Entity. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getentitydraftitems -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getentitydraftitems#getentitydraftitemsrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getentitydraftitems#getentitydraftitemsresponse function PlayFabEconomyApi.GetEntityDraftItems(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/GetEntityDraftItems", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Gets the submitted review for the specified item by the authenticated entity. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getentityitemreview -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getentityitemreview#getentityitemreviewrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getentityitemreview#getentityitemreviewresponse function PlayFabEconomyApi.GetEntityItemReview(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/GetEntityItemReview", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Retrieves an item from the public catalog. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitem -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitem#getitemrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitem#getitemresponse function PlayFabEconomyApi.GetItem(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/GetItem", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Gets the moderation state for an item, including the concern category and string reason. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitemmoderationstate -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitemmoderationstate#getitemmoderationstaterequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitemmoderationstate#getitemmoderationstateresponse function PlayFabEconomyApi.GetItemModerationState(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/GetItemModerationState", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Gets the status of a publish of an item. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitempublishstatus -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitempublishstatus#getitempublishstatusrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitempublishstatus#getitempublishstatusresponse function PlayFabEconomyApi.GetItemPublishStatus(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/GetItemPublishStatus", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Get a paginated set of reviews associated with the specified item. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitemreviews -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitemreviews#getitemreviewsrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitemreviews#getitemreviewsresponse function PlayFabEconomyApi.GetItemReviews(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/GetItemReviews", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Get a summary of all reviews associated with the specified item. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitemreviewsummary -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitemreviewsummary#getitemreviewsummaryrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitemreviewsummary#getitemreviewsummaryresponse function PlayFabEconomyApi.GetItemReviewSummary(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/GetItemReviewSummary", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Retrieves items from the public catalog. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitems -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitems#getitemsrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/getitems#getitemsresponse function PlayFabEconomyApi.GetItems(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/GetItems", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Initiates a publish of an item from the working catalog to the public catalog. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/publishdraftitem -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/publishdraftitem#publishdraftitemrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/publishdraftitem#publishdraftitemresponse function PlayFabEconomyApi.PublishDraftItem(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/PublishDraftItem", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Submit a report for an item, indicating in what way the item is inappropriate. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/reportitem -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/reportitem#reportitemrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/reportitem#reportitemresponse function PlayFabEconomyApi.ReportItem(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/ReportItem", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Submit a report for a review -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/reportitemreview -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/reportitemreview#reportitemreviewrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/reportitemreview#reportitemreviewresponse function PlayFabEconomyApi.ReportItemReview(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/ReportItemReview", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Creates or updates a review for the specified item. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/reviewitem -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/reviewitem#reviewitemrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/reviewitem#reviewitemresponse function PlayFabEconomyApi.ReviewItem(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/ReviewItem", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Executes a search against the public catalog using the provided search parameters and returns a set of paginated -- results. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/searchitems -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/searchitems#searchitemsrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/searchitems#searchitemsresponse function PlayFabEconomyApi.SearchItems(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/SearchItems", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Sets the moderation state for an item, including the concern category and string reason. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/setitemmoderationstate -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/setitemmoderationstate#setitemmoderationstaterequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/setitemmoderationstate#setitemmoderationstateresponse function PlayFabEconomyApi.SetItemModerationState(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/SetItemModerationState", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Submit a vote for a review, indicating whether the review was helpful or unhelpful. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/submititemreviewvote -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/submititemreviewvote#submititemreviewvoterequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/submititemreviewvote#submititemreviewvoteresponse function PlayFabEconomyApi.SubmitItemReviewVote(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/SubmitItemReviewVote", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Submit a request to takedown one or more reviews. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/takedownitemreviews -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/takedownitemreviews#takedownitemreviewsrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/takedownitemreviews#takedownitemreviewsresponse function PlayFabEconomyApi.TakedownItemReviews(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/TakedownItemReviews", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Updates the configuration for the catalog. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/updatecatalogconfig -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/updatecatalogconfig#updatecatalogconfigrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/updatecatalogconfig#updatecatalogconfigresponse function PlayFabEconomyApi.UpdateCatalogConfig(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/UpdateCatalogConfig", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Update the metadata for an item in the working catalog. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/updatedraftitem -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/updatedraftitem#updatedraftitemrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/catalog/catalog/updatedraftitem#updatedraftitemresponse function PlayFabEconomyApi.UpdateDraftItem(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Catalog/UpdateDraftItem", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end return PlayFabEconomyApi
apache-2.0
maxrio/packages981213
net/luci-app-e2guardian/files/e2guardian-cbi.lua
55
18594
--[[ LuCI E2Guardian module Copyright (C) 2015, Itus Networks, Inc. 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 Author: Marko Ratkaj <marko.ratkaj@sartura.hr> Luka Perkov <luka.perkov@sartura.hr> ]]-- local fs = require "nixio.fs" local sys = require "luci.sys" m = Map("e2guardian", translate("E2Guardian")) m.on_after_commit = function() luci.sys.call("/etc/init.d/e2guardian restart") end s = m:section(TypedSection, "e2guardian") s.anonymous = true s.addremove = false s:tab("tab_general", translate("General Settings")) s:tab("tab_additional", translate("Additional Settings")) s:tab("tab_logs", translate("Logs")) ----------------- General Settings Tab ----------------------- filterip = s:taboption("tab_general", Value, "filterip", translate("IP that E2Guardian listens")) filterip.datatype = "ip4addr" filterports = s:taboption("tab_general", Value, "filterports", translate("Port that E2Guardian listens")) filterports.datatype = "portrange" filterports.placeholder = "0-65535" proxyip = s:taboption("tab_general", Value, "proxyip", translate("IP address of the proxy")) proxyip.datatype = "ip4addr" proxyip.default = "127.0.0.1" proxyport = s:taboption("tab_general", Value, "proxyport", translate("Port of the proxy")) proxyport.datatype = "portrange" proxyport.placeholder = "0-65535" languagedir = s:taboption("tab_general", Value, "languagedir", translate("Language dir")) languagedir.datatype = "string" languagedir.default = "/usr/share/e2guardian/languages" language = s:taboption("tab_general", Value, "language", translate("Language to use")) language.datatype = "string" language.default = "ukenglish" loglevel = s:taboption("tab_general", ListValue, "loglevel", translate("Logging Settings")) loglevel:value("0", translate("none")) loglevel:value("1", translate("just denied")) loglevel:value("2", translate("all text based")) loglevel:value("3", translate("all requests")) loglevel.default = "2" logexceptionhits = s:taboption("tab_general", ListValue, "logexceptionhits", translate("Log Exception Hits")) logexceptionhits:value("0", translate("never")) logexceptionhits:value("1", translate("log, but dont mark as exceptions")) logexceptionhits:value("2", translate("log and mark")) logexceptionhits.default = "2" logfileformat = s:taboption("tab_general", ListValue, "logfileformat", translate("Log File Format")) logfileformat:value("1", translate("DansgGuardian format, space delimited")) logfileformat:value("2", translate("CSV-style format")) logfileformat:value("3", translate("Squid Log File Format")) logfileformat:value("4", translate("Tab delimited")) logfileformat:value("5", translate("Protex format")) logfileformat:value("6", translate("Protex format with server field blanked")) logfileformat.default = "1" accessdeniedaddress = s:taboption("tab_general", Value, "accessdeniedaddress", translate("Access denied address"), translate("Server to which the cgi e2guardian reporting script was copied. Reporting levels 1 and 2 only")) accessdeniedaddress.datatype = "string" accessdeniedaddress.default = "http://YOURSERVER.YOURDOMAIN/cgi-bin/e2guardian.pl" usecustombannedimage = s:taboption("tab_general", ListValue, "usecustombannedimage", translate("Banned image replacement")) usecustombannedimage:value("on", translate("Yes")) usecustombannedimage:value("off", translate("No")) usecustombannedimage.default = "on" custombannedimagefile = s:taboption("tab_general", Value, "custombannedimagefile", translate("Custom banned image file")) custombannedimagefile.datatype = "string" custombannedimagefile.default = "/usr/share/e2guardian/transparent1x1.gif" usecustombannedflash = s:taboption("tab_general", ListValue, "usecustombannedflash", translate("Banned flash replacement")) usecustombannedflash:value("on", translate("Yes")) usecustombannedflash:value("off", translate("No")) usecustombannedflash.default = "on" custombannedflashfile = s:taboption("tab_general", Value, "custombannedflashfile", translate("Custom banned flash file")) custombannedflashfile.datatype = "string" custombannedflashfile.default = "/usr/share/e2guardian/blockedflash.swf" filtergroups = s:taboption("tab_general", Value, "filtergroups", translate("Number of filter groups")) filtergroups.datatype = "and(uinteger,min(1))" filtergroups.default = "1" filtergroupslist = s:taboption("tab_general", Value, "filtergroupslist", translate("List of filter groups")) filtergroupslist.datatype = "string" filtergroupslist.default = "/etc/e2guardian/lists/filtergroupslist" bannediplist = s:taboption("tab_general", Value, "bannediplist", translate("List of banned IPs")) bannediplist.datatype = "string" bannediplist.default = "/etc/e2guardian/lists/bannediplist" exceptioniplist = s:taboption("tab_general", Value, "exceptioniplist", translate("List of IP exceptions")) exceptioniplist.datatype = "string" exceptioniplist.default = "/etc/e2guardian/lists/exceptioniplist" perroomblockingdirectory = s:taboption("tab_general", Value, "perroomblockingdirectory", translate("Per-Room blocking definition directory")) perroomblockingdirectory.datatype = "string" perroomblockingdirectory.default = "/etc/e2guardian/lists/bannedrooms/" showweightedfound = s:taboption("tab_general", ListValue, "showweightedfound", translate("Show weighted phrases found")) showweightedfound:value("on", translate("Yes")) showweightedfound:value("off", translate("No")) showweightedfound.default = "on" weightedphrasemode = s:taboption("tab_general", ListValue, "weightedphrasemode", translate("Weighted phrase mode")) weightedphrasemode:value("0", translate("off")) weightedphrasemode:value("1", translate("on, normal operation")) weightedphrasemode:value("2", translate("on, phrase found only counts once on a page")) weightedphrasemode.default = "2" urlcachenumber = s:taboption("tab_general", Value, "urlcachenumber", translate("Clean result caching for URLs")) urlcachenumber.datatype = "and(uinteger,min(0))" urlcachenumber.default = "1000" urlcacheage = s:taboption("tab_general", Value, "urlcacheage", translate("Age before they should be ignored in seconds")) urlcacheage.datatype = "and(uinteger,min(0))" urlcacheage.default = "900" scancleancache = s:taboption("tab_general", ListValue, "scancleancache", translate("Cache for content (AV) scans as 'clean'")) scancleancache:value("on", translate("Yes")) scancleancache:value("off", translate("No")) scancleancache.default = "on" phrasefiltermode = s:taboption("tab_general", ListValue, "phrasefiltermode", translate("Filtering options")) phrasefiltermode:value("0", translate("raw")) phrasefiltermode:value("1", translate("smart")) phrasefiltermode:value("2", translate("both raw and smart")) phrasefiltermode:value("3", translate("meta/title")) phrasefiltermode.default = "2" preservecase = s:taboption("tab_general", ListValue, "perservecase", translate("Lower caseing options")) preservecase:value("0", translate("force lower case")) preservecase:value("1", translate("dont change")) preservecase:value("2", translate("scan fist in lower, then in original")) preservecase.default = "0" hexdecodecontent = s:taboption("tab_general", ListValue, "hexdecodecontent", translate("Hex decoding options")) hexdecodecontent:value("on", translate("Yes")) hexdecodecontent:value("off", translate("No")) hexdecodecontent.default = "off" forcequicksearch = s:taboption("tab_general", ListValue, "forcequicksearch", translate("Quick search")) forcequicksearch:value("on", translate("Yes")) forcequicksearch:value("off", translate("No")) forcequicksearch.default = "off" reverseaddresslookups= s:taboption("tab_general", ListValue, "reverseaddresslookups", translate("Reverse lookups for banned site and URLs")) reverseaddresslookups:value("on", translate("Yes")) reverseaddresslookups:value("off", translate("No")) reverseaddresslookups.default = "off" reverseclientiplookups = s:taboption("tab_general", ListValue, "reverseclientiplookups", translate("Reverse lookups for banned and exception IP lists")) reverseclientiplookups:value("on", translate("Yes")) reverseclientiplookups:value("off", translate("No")) reverseclientiplookups.default = "off" logclienthostnames = s:taboption("tab_general", ListValue, "logclienthostnames", translate("Perform reverse lookups on client IPs for successful requests")) logclienthostnames:value("on", translate("Yes")) logclienthostnames:value("off", translate("No")) logclienthostnames.default = "off" createlistcachefiles = s:taboption("tab_general", ListValue, "createlistcachefiles", translate("Build bannedsitelist and bannedurllist cache files")) createlistcachefiles:value("on",translate("Yes")) createlistcachefiles:value("off",translate("No")) createlistcachefiles.default = "on" prefercachedlists = s:taboption("tab_general", ListValue, "prefercachedlists", translate("Prefer cached list files")) prefercachedlists:value("on", translate("Yes")) prefercachedlists:value("off", translate("No")) prefercachedlists.default = "off" maxuploadsize = s:taboption("tab_general", Value, "maxuploadsize", translate("Max upload size (in Kbytes)")) maxuploadsize:value("-1", translate("no blocking")) maxuploadsize:value("0", translate("complete block")) maxuploadsize.default = "-1" maxcontentfiltersize = s:taboption("tab_general", Value, "maxcontentfiltersize", translate("Max content filter size"), translate("The value must not be higher than max content ram cache scan size or 0 to match it")) maxcontentfiltersize.datatype = "and(uinteger,min(0))" maxcontentfiltersize.default = "256" maxcontentramcachescansize = s:taboption("tab_general", Value, "maxcontentramcachescansize", translate("Max content ram cache scan size"), translate("This is the max size of file that DG will download and cache in RAM")) maxcontentramcachescansize.datatype = "and(uinteger,min(0))" maxcontentramcachescansize.default = "2000" maxcontentfilecachescansize = s:taboption("tab_general", Value, "maxcontentfilecachescansize", translate("Max content file cache scan size")) maxcontentfilecachescansize.datatype = "and(uinteger,min(0))" maxcontentfilecachescansize.default = "20000" proxytimeout = s:taboption("tab_general", Value, "proxytimeout", translate("Proxy timeout (5-100)")) proxytimeout.datatype = "range(5,100)" proxytimeout.default = "20" proxyexchange = s:taboption("tab_general", Value, "proxyexchange", translate("Proxy header excahnge (20-300)")) proxyexchange.datatype = "range(20,300)" proxyexchange.default = "20" pcontimeout = s:taboption("tab_general", Value, "pcontimeout", translate("Pconn timeout"), translate("How long a persistent connection will wait for other requests")) pcontimeout.datatype = "range(5,300)" pcontimeout.default = "55" filecachedir = s:taboption("tab_general", Value, "filecachedir", translate("File cache directory")) filecachedir.datatype = "string" filecachedir.default = "/tmp" deletedownloadedtempfiles = s:taboption("tab_general", ListValue, "deletedownloadedtempfiles", translate("Delete file cache after user completes download")) deletedownloadedtempfiles:value("on", translate("Yes")) deletedownloadedtempfiles:value("off", translate("No")) deletedownloadedtempfiles.default = "on" initialtrickledelay = s:taboption("tab_general", Value, "initialtrickledelay", translate("Initial Trickle delay"), translate("Number of seconds a browser connection is left waiting before first being sent *something* to keep it alive")) initialtrickledelay.datatype = "and(uinteger,min(0))" initialtrickledelay.default = "20" trickledelay = s:taboption("tab_general", Value, "trickledelay", translate("Trickle delay"), translate("Number of seconds a browser connection is left waiting before being sent more *something* to keep it alive")) trickledelay.datatype = "and(uinteger,min(0))" trickledelay.default = "10" downloadmanager = s:taboption("tab_general", Value, "downloadmanager", translate("Download manager")) downloadmanager.datatype = "string" downloadmanager.default = "/etc/e2guardian/downloadmanagers/default.conf" contentscannertimeout = s:taboption("tab_general", Value, "contentscannertimeout", translate("Content scanner timeout")) contentscannertimeout.datatype = "and(uinteger,min(0))" contentscannertimeout.default = "60" contentscanexceptions = s:taboption("tab_general", ListValue, "contentscanexceptions", translate("Content scan exceptions")) contentscanexceptions:value("on", translate("Yes")) contentscanexceptions:value("off", translate("No")) contentscanexceptions.default = "off" recheckreplacedurls = s:taboption("tab_general", ListValue, "recheckreplacedurls", translate("e-check replaced URLs")) recheckreplacedurls:value("on", translate("Yes")) recheckreplacedurls:value("off", translate("No")) recheckreplacedurls.default = "off" forwardedfor = s:taboption("tab_general", ListValue, "forwardedfor", translate("Misc setting: forwardedfor"), translate("If on, it may help solve some problem sites that need to know the source ip.")) forwardedfor:value("on", translate("Yes")) forwardedfor:value("off", translate("No")) forwardedfor.default = "off" usexforwardedfor = s:taboption("tab_general", ListValue, "usexforwardedfor", translate("Misc setting: usexforwardedfor"), translate("This is for when you have squid between the clients and E2Guardian")) usexforwardedfor:value("on", translate("Yes")) usexforwardedfor:value("off", translate("No")) usexforwardedfor.default = "off" logconnectionhandlingerrors = s:taboption("tab_general", ListValue, "logconnectionhandlingerrors", translate("Log debug info about log()ing and accept()ing")) logconnectionhandlingerrors:value("on", translate("Yes")) logconnectionhandlingerrors:value("off", translate("No")) logconnectionhandlingerrors.default = "on" logchildprocesshandling = s:taboption("tab_general", ListValue, "logchildprocesshandling", translate("Log child process handling")) logchildprocesshandling:value("on", translate("Yes")) logchildprocesshandling:value("off", translate("No")) logchildprocesshandling.default = "off" maxchildren = s:taboption("tab_general", Value, "maxchildren", translate("Max number of processes to spawn")) maxchildren.datatype = "and(uinteger,min(0))" maxchildren.default = "180" minchildren = s:taboption("tab_general", Value, "minchildren", translate("Min number of processes to spawn")) minchildren.datatype = "and(uinteger,min(0))" minchildren.default = "20" minsparechildren = s:taboption("tab_general", Value, "minsparechildren", translate("Min number of processes to keep ready")) minsparechildren.datatype = "and(uinteger,min(0))" minsparechildren.default = "16" preforkchildren = s:taboption("tab_general", Value, "preforkchildren", translate("Sets minimum nuber of processes when it runs out")) preforkchildren.datatype = "and(uinteger,min(0))" preforkchildren.default = "10" maxsparechildren = s:taboption("tab_general", Value, "maxsparechildren", translate("Sets the maximum number of processes to have doing nothing")) maxsparechildren.datatype = "and(uinteger,min(0))" maxsparechildren.default = "32" maxagechildren = s:taboption("tab_general", Value, "maxagechildren", translate("Max age of child process")) maxagechildren.datatype = "and(uinteger,min(0))" maxagechildren.default = "500" maxips = s:taboption("tab_general", Value, "maxips", translate("Max number of clinets allowed to connect")) maxips:value("0", translate("no limit")) maxips.default = "0" ipipcfilename = s:taboption("tab_general", Value, "ipipcfilename", translate("IP list IPC server directory and filename")) ipipcfilename.datatype = "string" ipipcfilename.default = "/tmp/.dguardianipc" urlipcfilename = s:taboption("tab_general", Value, "urlipcfilename", translate("Defines URL list IPC server directory and filename used to communicate with the URL cache process")) urlipcfilename.datatype = "string" urlipcfilename.default = "/tmp/.dguardianurlipc" ipcfilename = s:taboption("tab_general", Value, "ipcfilename", translate("Defines URL list IPC server directory and filename used to communicate with the URL cache process")) ipcfilename.datatype = "string" ipcfilename.default = "/tmp/.dguardianipipc" nodeamon = s:taboption("tab_general", ListValue, "nodeamon", translate("Disable deamoning")) nodeamon:value("on", translate("Yes")) nodeamon:value("off", translate("No")) nodeamon.default = "off" nologger = s:taboption("tab_general", ListValue, "nologger", translate("Disable logger")) nologger:value("on", translate("Yes")) nologger:value("off", translate("No")) nologger.default = "off" logadblock = s:taboption("tab_general", ListValue, "logadblock", translate("Enable logging of ADs")) logadblock:value("on", translate("Yes")) logadblock:value("off", translate("No")) logadblock.default = "off" loguseragent = s:taboption("tab_general", ListValue, "loguseragent", translate("Enable logging of client user agent")) loguseragent:value("on", translate("Yes")) loguseragent:value("off", translate("No")) loguseragent.default = "off" softrestart = s:taboption("tab_general", ListValue, "softrestart", translate("Enable soft restart")) softrestart:value("on", translate("Yes")) softrestart:value("off", translate("No")) softrestart.default = "off" ------------------------ Additional Settings Tab ---------------------------- e2guardian_config_file = s:taboption("tab_additional", TextValue, "_data", "") e2guardian_config_file.wrap = "off" e2guardian_config_file.rows = 25 e2guardian_config_file.rmempty = false function e2guardian_config_file.cfgvalue() local uci = require "luci.model.uci".cursor_state() file = "/etc/e2guardian/e2guardianf1.conf" if file then return fs.readfile(file) or "" else return "" end end function e2guardian_config_file.write(self, section, value) if value then local uci = require "luci.model.uci".cursor_state() file = "/etc/e2guardian/e2guardianf1.conf" fs.writefile(file, value:gsub("\r\n", "\n")) end end ---------------------------- Logs Tab ----------------------------- e2guardian_logfile = s:taboption("tab_logs", TextValue, "lines", "") e2guardian_logfile.wrap = "off" e2guardian_logfile.rows = 25 e2guardian_logfile.rmempty = true function e2guardian_logfile.cfgvalue() local uci = require "luci.model.uci".cursor_state() file = "/tmp/e2guardian/access.log" if file then return fs.readfile(file) or "" else return "Can't read log file" end end function e2guardian_logfile.write() return "" end return m
gpl-2.0
MmxBoy/newbot
plugins/anti-bot.lua
29
3063
local function isBotAllowed (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId local banned = redis:get(hash) return banned end local function allowBot (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId redis:set(hash, true) end local function disallowBot (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId redis:del(hash) end -- Is anti-bot enabled on chat local function isAntiBotEnabled (chatId) local hash = 'anti-bot:enabled:'..chatId local enabled = redis:get(hash) return enabled end local function enableAntiBot (chatId) local hash = 'anti-bot:enabled:'..chatId redis:set(hash, true) end local function disableAntiBot (chatId) local hash = 'anti-bot:enabled:'..chatId redis:del(hash) end local function isABot (user) -- Flag its a bot 0001000000000000 local binFlagIsBot = 4096 local result = bit32.band(user.flags, binFlagIsBot) return result == binFlagIsBot end local function kickUser(userId, chatId) local chat = 'chat#id'..chatId local user = 'user#id'..userId chat_del_user(chat, user, function (data, success, result) if success ~= 1 then print('I can\'t kick '..data.user..' but should be kicked') end end, {chat=chat, user=user}) end local function run (msg, matches) -- We wont return text if is a service msg if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' end end local chatId = msg.to.id if matches[1] == 'enable' then enableAntiBot(chatId) return 'Anti-bot enabled on this chat' end if matches[1] == 'disable' then disableAntiBot(chatId) return 'Anti-bot disabled on this chat' end if matches[1] == 'allow' then local userId = matches[2] allowBot(userId, chatId) return 'Bot '..userId..' allowed' end if matches[1] == 'disallow' then local userId = matches[2] disallowBot(userId, chatId) return 'Bot '..userId..' disallowed' end if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then local user = msg.action.user or msg.from if isABot(user) then print('It\'s a bot!') if isAntiBotEnabled(chatId) then print('Anti bot is enabled') local userId = user.id if not isBotAllowed(userId, chatId) then kickUser(userId, chatId) else print('This bot is allowed') end end end end end return { description = 'When bot enters group kick it.', usage = { '!antibot enable: Enable Anti-bot on current chat', '!antibot disable: Disable Anti-bot on current chat', '!antibot allow <botId>: Allow <botId> on this chat', '!antibot disallow <botId>: Disallow <botId> on this chat' }, patterns = { '^!antibot (allow) (%d+)$', '^!antibot (disallow) (%d+)$', '^!antibot (enable)$', '^!antibot (disable)$', '^!!tgservice (chat_add_user)$', '^!!tgservice (chat_add_user_link)$' }, run = run }
gpl-2.0
Frenzie/koreader-base
ffi/pic.lua
1
9880
local ffi = require("ffi") local BB = require("ffi/blitbuffer") local Png = require("ffi/png") local Jpeg = require("ffi/jpeg") require("ffi/giflib_h") local giflib if ffi.os == "Windows" then giflib = ffi.load("libs/libgif-7.dll") elseif ffi.os == "OSX" then giflib = ffi.load("libs/libgif.7.dylib") else giflib = ffi.load("libs/libgif.so.7") end local Pic = {} --[[ start of pic page type --]] local PicPage = {} function PicPage:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end function PicPage:getSize(dc) local zoom = dc:getZoom() return self.width * zoom, self.height * zoom end function PicPage:getUsedBBox() return 0.01, 0.01, -0.01, -0.01 end function PicPage:close() end --[[ -- NOTE: This is a plain table, that won't work on Lua 5.1/LuaJIT -- Comment this out since this a currently a no-op anyway. PicPage.__gc = PicPage.close --]] function PicPage:draw(dc, bb) local scaled_bb = self.image_bb:scale(bb:getWidth(), bb:getHeight()) bb:blitFullFrom(scaled_bb, 0, 0) scaled_bb:free() end --[[ start of pic document --]] local PicDocument = {} function PicDocument:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end function PicDocument:openPage() local page = PicPage:new{ width = self.width, height = self.height, image_bb = self.image_bb, doc = self, } return page end function PicDocument:getToc() return {} end function PicDocument:getPages() return 1 end function PicDocument:getCacheSize() return 0 end function PicDocument:cleanCache() end function PicDocument:getOriginalPageSize() return self.width, self.height, self.components end function PicDocument:close() if self.image_bb ~= nil then self.image_bb:free() self.image_bb = nil end end --[[ -- NOTE: Ditto, plain table, and essentially a no-op since BlitBuffer already handles the cdata finalizer. PicDocument.__gc = PicDocument.close --]] local GifPage = PicPage:new() function GifPage:close() -- with Gifs, the blitbuffers are per page if self.image_bb ~= nil then self.image_bb:free() self.image_bb = nil end end local GifDocument = PicDocument:new{ giffile = nil, } function GifDocument:getPages() return self.giffile.ImageCount end function GifDocument:getOriginalPageSize(number) -- subsequent frames may have a smaller size than 1 frame local i = self.giffile.SavedImages[0] return i.ImageDesc.Width, i.ImageDesc.Height, 4 -- components end function GifDocument:openPage(number) -- If there are multiple frames (animated GIF), a standalone -- frame may not be enough (it may be smaller than the first frame, -- and have some transparency): we need to paste it (and all the -- previous frames) over the first frame -- Here, because requesting a random number is possible, we redo all the -- pastes from first frame till requested frame number: it could be optimized local i = self.giffile.SavedImages[0] local width = i.ImageDesc.Width local height = i.ImageDesc.Height local bb = BB.new(width, height, BB.TYPE_BBRGB32) bb:fill(BB.COLOR_WHITE) -- fill with white in case first frame has transparency local gcb = ffi.new("GraphicsControlBlock") -- re-used with each frame local framenum = 1 while framenum <= number and framenum <= self.giffile.ImageCount do -- print("frame "..framenum) -- get transparency (index into palette) and disposal_mode (how to draw -- frame over previous ones) from Graphics Control Extension local transparent_color = nil local disposal_mode = nil if giflib.DGifSavedExtensionToGCB(self.giffile, framenum-1, gcb) == 1 then if gcb.TransparentColor ~= giflib.NO_TRANSPARENT_COLOR then transparent_color = gcb.TransparentColor end if gcb.DisposalMode ~= giflib.DISPOSAL_UNSPECIFIED then disposal_mode = gcb.DisposalMode end end -- See http://webreference.com/content/studio/disposal.html -- (not tested, all found animated gif have DISPOSE_DO_NOT if disposal_mode == giflib.DISPOSE_BACKGROUND then bb:fill(BB.COLOR_WHITE) -- fill with white -- elseif disposal_mode == giflib.DISPOSE_PREVIOUS then -- Rare (no sample to test with), and not supported for now: we should -- keep a copy of the last bb drawn widh DISPOSE_DO_NOT -- else: giflib.DISPOSE_DO_NOT or DISPOSAL_UNSPECIFIED: draw over previous frame end -- build palette from frame or global color map local cmap = i.ImageDesc.ColorMap ~= nil and i.ImageDesc.ColorMap or self.giffile.SColorMap local palette={} for c=0, cmap.ColorCount-1 do local color = cmap.Colors[c] palette[c] = BB.ColorRGB32(color.Red, color.Green, color.Blue, 0xFF) end -- Draw current frame on our bb local f_w, f_h = i.ImageDesc.Width, i.ImageDesc.Height local f_x, f_y = i.ImageDesc.Left, i.ImageDesc.Top local p = i.RasterBits for y = f_y, f_y+f_h-1 do for x = f_x, f_x+f_w-1 do if not transparent_color or p[0] ~= transparent_color then bb:setPixel(x, y, palette[p[0]]) end p = p + 1 end end framenum = framenum + 1 if framenum <= self.giffile.ImageCount then i = self.giffile.SavedImages[framenum-1] end end local page = GifPage:new{ width = width, height = height, image_bb = bb, doc = self, } return page end function GifDocument:close() local err = ffi.new("int[1]") if giflib.DGifCloseFile(self.giffile, err) ~= giflib.GIF_OK then error(string.format("error closing/deallocating GIF: %s", ffi.string(giflib.GifErrorString(err[0])))) end self.giffile = nil end function Pic.openGIFDocument(filename) local err = ffi.new("int[1]") local giffile = giflib.DGifOpenFileName(filename, err) if giffile == nil then error(string.format("Cannot read GIF file: %s", ffi.string(giflib.GifErrorString(err[0])))) end if giflib.DGifSlurp(giffile) ~= giflib.GIF_OK then giflib.DGifCloseFile(giffile, err) error(string.format("Cannot parse GIF file: %s", ffi.string(giflib.GifErrorString(giffile.Error)))) end return GifDocument:new{giffile = giffile} end function Pic.openGIFDocumentFromData(data, size) -- Create GIF from data pointer (from https://github.com/luapower/giflib) local function data_reader(r_data, r_size) r_data = ffi.cast('unsigned char*', r_data) return function(_, buf, sz) if sz < 1 or r_size < 1 then error('eof') end sz = math.min(r_size, sz) ffi.copy(buf, r_data, sz) r_data = r_data + sz r_size = r_size - sz return sz end end local read_cb = ffi.cast('InputFunc', data_reader(data, size)) local err = ffi.new("int[1]") local giffile = giflib.DGifOpen(nil, read_cb, err) if giffile == nil then read_cb:free() error(string.format("Cannot read GIF file: %s", ffi.string(giflib.GifErrorString(err[0])))) end if giflib.DGifSlurp(giffile) ~= giflib.GIF_OK then giflib.DGifCloseFile(giffile, err) read_cb:free() error(string.format("Cannot parse GIF file: %s", ffi.string(giflib.GifErrorString(giffile.Error)))) end read_cb:free() return GifDocument:new{giffile = giffile} end function Pic.openPNGDocument(filename) local req_n local bbtype if Pic.color then req_n = 3 else -- NOTE: LodePNG will NOT do RGB -> Grayscale conversions for us, for design reasons (multiple ways to do it, lossy). -- So we can only *ask* to keep grayscale PNGs as-is, but we might actually be getting fed back a RGB24 one ;). req_n = 1 end local ok, re = Png.decodeFromFile(filename, req_n) if not ok then error(re) end if re.ncomp == 1 then bbtype = BB.TYPE_BB8 elseif re.ncomp == 2 then bbtype = BB.TYPE_BB8A elseif re.ncomp == 3 then bbtype = BB.TYPE_BBRGB24 elseif re.ncomp == 4 then bbtype = BB.TYPE_BBRGB32 else if re.data then ffi.C.free(re.data) end error("unsupported number of color components") end local doc = PicDocument:new{width=re.width, height=re.height} doc.image_bb = BB.new(re.width, re.height, bbtype, re.data) doc.components = re.ncomp -- Mark buffer for freeing when Blitbuffer is freed: doc.image_bb:setAllocated(1) return doc end function Pic.openJPGDocument(filename) local image, w, h, components = Jpeg.openDocument(filename, Pic.color) local doc = PicDocument:new{width=w, height=h} doc.image_bb = image doc.components = components return doc end function Pic.openJPGDocumentFromMem(data) local image, w, h, components = Jpeg.openDocumentFromMem(data, Pic.color) local doc = PicDocument:new{width=w, height=h} doc.image_bb = image doc.components = components return doc end --[[ start of pic module API --]] function Pic.openDocument(filename) local extension = string.lower(string.match(filename, ".+%.([^.]+)") or "") if extension == "jpg" or extension == "jpeg" then return Pic.openJPGDocument(filename) elseif extension == "png" then return Pic.openPNGDocument(filename) elseif extension == "gif" then return Pic.openGIFDocument(filename) else error("Unsupported image format") end end return Pic
agpl-3.0
JarnoVgr/Mr.Green-MTA-Resources
resources/[gameplay]/-shaders-radial_blur/c_radial_blur.lua
4
14796
-- -- c_radial_blur.lua -- ----------------------------------------------------------------------------------- -- Settings for changing ----------------------------------------------------------------------------------- bSuspendSpeedEffectOnLowFPS = false -- true for auto FPS saving bSuspendRotateEffectOnLowFPS = false -- true for auto FPS saving ----------------------------------------------------------------------------------- -- Settings for not really changing ----------------------------------------------------------------------------------- local orderPriority = "-2.8" -- The lower this number, the later the effect is applied (Radial blur should be one of the last full screen effects) local bShowDebug = false ----------------------------------------------------------------------------------- -- Runtime variables ----------------------------------------------------------------------------------- local fpsScaler = 1 local scx, scy = guiGetScreenSize() ---------------------------------------------------------------- -- enableRadialBlur ---------------------------------------------------------------- function enableRadialBlur() if bEffectEnabled then return end -- Turn GTA blur off setBlurLevel(0) -- Create things myScreenSource = dxCreateScreenSource( scx/2, scy/2 ) radialMaskTexture = dxCreateTexture( "images/radial_mask.tga", "dxt5" ) radialBlurShader,tecName = dxCreateShader( "fx/radial_blur.fx" ) -- outputDebugString( "Radial blur is using technique " .. tostring(tecName) ) -- Get list of all elements used effectParts = { myScreenSource, radialBlurShader, radialMaskTexture, } -- Check list of all elements used bAllValid = true for _,part in ipairs(effectParts) do bAllValid = part and bAllValid end bEffectEnabled = true if not bAllValid then outputChatBox( "Radial blur: Could not create some things. Please use debugscript 3" ) disableRadialBlur() else dxSetShaderValue( radialBlurShader, "sSceneTexture", myScreenSource ) dxSetShaderValue( radialBlurShader, "sRadialMaskTexture", radialMaskTexture ) end end ---------------------------------------------------------------- -- disableRadialBlur ---------------------------------------------------------------- function disableRadialBlur() if not bEffectEnabled then return end -- Destroy all shaders for _,part in ipairs(effectParts) do if part then destroyElement( part ) end end effectParts = {} bAllValid = false -- Flag effect as stopped bEffectEnabled = false end ---------------------------------------------------------------- -- onClientHUDRender -- Effect is applied here ---------------------------------------------------------------- addEventHandler( "onClientHUDRender", root, function() if not bAllValid then return end local vars = getBlurVars() if not vars then return end -- Set settings dxSetShaderValue( radialBlurShader, "sLengthScale", vars.lengthScale ) dxSetShaderValue( radialBlurShader, "sMaskScale", vars.maskScale ) dxSetShaderValue( radialBlurShader, "sMaskOffset", vars.maskOffset ) dxSetShaderValue( radialBlurShader, "sVelZoom", vars.velDirForCam[2] ) dxSetShaderValue( radialBlurShader, "sVelDir", vars.velDirForCam[1]/2, -vars.velDirForCam[3]/2 ) dxSetShaderValue( radialBlurShader, "sAmount", vars.amount ) -- Update screen dxUpdateScreenSource( myScreenSource, true ) dxDrawImage( 0, 0, scx, scy, radialBlurShader ) end ,true ,"low" .. orderPriority ) ---------------------------------------------------------------- -- getBlurVars -- Choose which set to use ---------------------------------------------------------------- function getBlurVars() local vehVars = getVehicleSpeedBlurVars() local camVars = getCameraRotateBlurVars() if camVars and camVars.amount > 0.1 then return camVars end if vehVars then return vehVars end if camVars then return camVars end return false end ---------------------------------------------------------------- -- getVehicleSpeedBlurVars ---------------------------------------------------------------- local camMatPrev = matrix( {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}} ) function getVehicleSpeedBlurVars() -- Get velocity vector and speed local camTarget = getCameraTarget() if not camTarget then return false end local vx,vy,vz = getElementVelocity(camTarget) local vehSpeed = getDistanceBetweenPoints3D ( 0,0,0, vx,vy,vz ) -- Ramp blyr between these two speeds local amount = math.unlerpclamped(0.025,vehSpeed,1.22) if bSuspendSpeedEffectOnLowFPS then amount = amount * fpsScaler end if amount < 0.001 then return false end -- Calc inverse camera matrix local camMat = getRealCameraMatrix() local camMatInv = matrix.invert( camMat ) -- If invalid for some reason, use last valid matrix if not camMatInv then camMatInv = matrix.invert( camMatPrev ) else camMatPrev = matrix.copy( camMat ) end -- Calculate vehicle velocity direction as seen from the camera local velDir = Vector3D:new(vx,vy,vz) velDir:Normalize() local velDirForCam = matTransformNormal ( camMatInv, {velDir.x,velDir.y,velDir.z} ) local vars = {} vars.lengthScale = 1 vars.maskScale = {1,1.25} vars.maskOffset = {0,0.1} vars.velDirForCam = velDirForCam vars.amount = amount return vars end ---------------------------------------------------------------- -- getCameraRotateBlurVars ---------------------------------------------------------------- function getCameraRotateBlurVars() local camTarget = getCameraTarget() if not camTarget then return false end local bIsInVehicle = (getElementType(camTarget) == "vehicle") local obx, oby, obz = getCameraOrbitVelocity() local camSpeed = getDistanceBetweenPoints3D ( 0,0,0, obx,oby,obz ) local amount = math.unlerpclamped(4.20,camSpeed,8.52) if bIsInVehicle then amount = math.unlerpclamped(8.20,camSpeed,16.52) end if bSuspendRotateEffectOnLowFPS then amount = amount * fpsScaler end if amount < 0.001 then return end local velDir = Vector3D:new(-obz,oby,-obx) velDir:Normalize() local velDirForCam = {velDir.x,velDir.y,velDir.z*2} local vars = {} vars.lengthScale = 0.8 vars.maskScale = {3,1.25} vars.maskOffset = {0,-0.15} vars.velDirForCam = velDirForCam vars.amount = amount return vars end ----------------------------------------------------------------------------------- -- getCameraOrbitVelocity ----------------------------------------------------------------------------------- local prevOrbitX, prevOrbitY, prevOrbitZ = 0,0,0 local prevVel = 0 local prevVelX, prevVelY, prevVelZ = 0,0,0 function getCameraOrbitVelocity () -- Calc Rotational difference from last call local x,y,z = getCameraOrbitRotation() local vx = x - prevOrbitX local vy = y - prevOrbitY local vz = z - prevOrbitZ prevOrbitX,prevOrbitY,prevOrbitZ = x,y,z -- Check for z wrap-around vz = vz % 360 if vz > 180 then vz = vz - 360 end -- Check for big instant movements due to camera placement local newVel = getDistanceBetweenPoints3D ( 0,0,0, vx,vy,vz ) if prevVel < 0.01 then vx,vy,vz = 0,0,0 end prevVel = newVel -- Average with last frame to make it a bit smoother local avgX = (prevVelX + vx) * 0.5 local avgY = (prevVelY + vy) * 0.5 local avgZ = (prevVelZ + vz) * 0.5 prevVelX,prevVelY,prevVelZ = vx,vy,vz return avgX,avgY,avgZ end ----------------------------------------------------------------------------------- -- getCameraOrbitRotation ----------------------------------------------------------------------------------- function getCameraOrbitRotation () local px, py, pz, lx, ly, lz = getCameraMatrix() local camTarget = getCameraTarget() or localPlayer local tx,ty,tz = getElementPosition( camTarget ) local dx = tx - px local dy = ty - py local dz = tz - pz return getRotationFromDirection( dx, dy, dz ) end ----------------------------------------------------------------------------------- -- getRotationFromDirection ----------------------------------------------------------------------------------- function getRotationFromDirection ( dx, dy, dz ) local rotz = 6.2831853071796 - math.atan2 ( ( dx ), ( dy ) ) % 6.2831853071796 local rotx = math.atan2 ( dz, getDistanceBetweenPoints2D ( 0, 0, dx, dy ) ) rotx = math.deg(rotx) --Convert to degrees rotz = -math.deg(rotz) return rotx, 180, rotz end ----------------------------------------------------------------------------------- -- getRealCameraMatrix -- Returns 4x4 matrix -- Assumes up is up ----------------------------------------------------------------------------------- function getRealCameraMatrix() local px, py, pz, lx, ly, lz = getCameraMatrix() local fwd = Vector3D:new(lx - px, ly - py, lz - pz) local up = Vector3D:new(0, 0, 1) fwd:Normalize() local dot = fwd:Dot(up) -- Dot product of primary and secondary axis up = up:AddV( fwd:Mul(-dot) ) -- Adjust secondary axis up:Normalize() local right = fwd:CrossV(up) -- Calculate last axis return matrix{ {right.x, right.y, right.z, 0}, {fwd.x, fwd.y, fwd.z, 0}, {up.x, up.y, up.z, 0}, {px, py, pz, 1} } end ---------------------------------------------------------------- -- onClientResourceStart -- Used for auto FPS adjustment ---------------------------------------------------------------- addEventHandler( "onClientResourceStart", resourceRoot, function() triggerServerEvent("onResourceStartedAtClient",resourceRoot) end ) ---------------------------------------------------------------- -- onClientNotifyServerFPSLimit -- Used for auto FPS adjustment ---------------------------------------------------------------- addEvent("onClientNotifyServerFPSLimit",true) addEventHandler( "onClientNotifyServerFPSLimit", resourceRoot, function(fpsLimit) serverFPSLimit = fpsLimit end ) ----------------------------------------------------------------------------------- -- Auto FPS adjustment ----------------------------------------------------------------------------------- local ticksSmooth = 10 local tickCountPrev = 0 local FPSValue = 60 local fpsScalerRaw = 0 addEventHandler('onClientPreRender', root, function(ticks) local tickCount = getTickCount() ticks = tickCount - tickCountPrev ticks = math.min(ticks,100) tickCountPrev = tickCount ticksSmooth = math.lerp(ticksSmooth,0.025,ticks) FPSValue = math.lerp(FPSValue,0.05,1000 / ticksSmooth) serverFPSLimit = serverFPSLimit or 36 -- How much of the FPS limit is being used local MaxFPSPercent = 100 * FPSValue / serverFPSLimit -- Switch effect between 88% and 95% of FPS if fpsScalerRaw > 0 and MaxFPSPercent < 88 then fpsScalerRaw = 0 end if fpsScalerRaw == 0 and MaxFPSPercent > 95 then fpsScalerRaw = 1 end local dif = fpsScalerRaw - fpsScaler local maxDif = ticksSmooth/1000 dif = math.clamp ( -maxDif, dif, maxDif ) fpsScaler = fpsScaler + dif if bShowDebug then dxDrawDBTextPosStart(10,500) dxDrawDBText("serverFPSLimit: "..string.format("%1.2f", serverFPSLimit), 10) dxDrawDBText("FPSValue: "..string.format("%1.2f", FPSValue), 10) dxDrawDBText("ticksSmooth: "..string.format("%1.2f", ticksSmooth), 10) dxDrawDBText("fpsScalerRaw: "..string.format("%1.2f", fpsScalerRaw), 10) dxDrawDBText("fpsScaler: "..string.format("%1.2f", fpsScaler), 10) end end ) --------------------------------------------------------------------------- -- Math extentions --------------------------------------------------------------------------- function math.lerp(from,alpha,to) return from + (to-from) * alpha end function math.unlerp(from,pos,to) if ( to == from ) then return 1 end return ( pos - from ) / ( to - from ) end function math.clamp(low,value,high) return math.max(low,math.min(value,high)) end function math.unlerpclamped(from,pos,to) return math.clamp(0,math.unlerp(from,pos,to),1) end --------------------------------------------------------------------------- -- Matrix stuffs --------------------------------------------------------------------------- function matTransformVector( mat, vec ) local offX = vec[1] * mat[1][1] + vec[2] * mat[2][1] + vec[3] * mat[3][1] + mat[4][1] local offY = vec[1] * mat[1][2] + vec[2] * mat[2][2] + vec[3] * mat[3][2] + mat[4][2] local offZ = vec[1] * mat[1][3] + vec[2] * mat[2][3] + vec[3] * mat[3][3] + mat[4][3] return {offX, offY, offZ} end function matTransformNormal( mat, vec ) local offX = vec[1] * mat[1][1] + vec[2] * mat[2][1] + vec[3] * mat[3][1] local offY = vec[1] * mat[1][2] + vec[2] * mat[2][2] + vec[3] * mat[3][2] local offZ = vec[1] * mat[1][3] + vec[2] * mat[2][3] + vec[3] * mat[3][3] return {offX, offY, offZ} end --------------------------------------------------------------------------- -- Vector3D for somewhere --------------------------------------------------------------------------- Vector3D = { new = function(self, _x, _y, _z) local newVector = { x = _x or 0.0, y = _y or 0.0, z = _z or 0.0 } return setmetatable(newVector, { __index = Vector3D }) end, Copy = function(self) return Vector3D:new(self.x, self.y, self.z) end, Normalize = function(self) local mod = self:Module() if mod < 0.00001 then self.x, self.y, self.z = 0,0,1 else self.x = self.x / mod self.y = self.y / mod self.z = self.z / mod end end, Dot = function(self, V) return self.x * V.x + self.y * V.y + self.z * V.z end, Module = function(self) return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z) end, AddV = function(self, V) return Vector3D:new(self.x + V.x, self.y + V.y, self.z + V.z) end, SubV = function(self, V) return Vector3D:new(self.x - V.x, self.y - V.y, self.z - V.z) end, CrossV = function(self, V) return Vector3D:new(self.y * V.z - self.z * V.y, self.z * V.x - self.x * V.z, self.x * V.y - self.y * V.x) end, Mul = function(self, n) return Vector3D:new(self.x * n, self.y * n, self.z * n) end, Div = function(self, n) return Vector3D:new(self.x / n, self.y / n, self.z / n) end, } --------------------------------------------------------------------------- -- debug assist --------------------------------------------------------------------------- local dbypos = 200 local dbxpos = 200 function dxDrawDBTextPosStart(x,y) dbxpos = x dbypos = y end function dxDrawDBText(msg) local shadowColor = tocolor(0,0,0,255) local textColor = tocolor(255,255,0,255) local textScale = 1.5 local textFont = "default" dxDrawText(msg, dbxpos+1,dbypos+1, 200,20, shadowColor, textScale, textFont, "left", "top", false, false, true ) dxDrawText(msg, dbxpos,dbypos, 200,20, textColor, textScale, textFont, "left", "top", false, false, true ) dbypos = dbypos + 30 end
mit
Frenzie/koreader-base
ffi/sha2.lua
1
151394
-------------------------------------------------------------------------------------------------------------------------- -- sha2.lua -------------------------------------------------------------------------------------------------------------------------- -- VERSION: 9 (2020-05-10) -- AUTHOR: Egor Skriptunoff -- LICENSE: MIT (the same license as Lua itself) -- -- -- DESCRIPTION: -- This module contains functions to calculate SHA digest: -- MD5, SHA-1, -- SHA-224, SHA-256, SHA-512/224, SHA-512/256, SHA-384, SHA-512, -- SHA3-224, SHA3-256, SHA3-384, SHA3-512, SHAKE128, SHAKE256, -- HMAC -- Written in pure Lua. -- Compatible with: -- Lua 5.1, Lua 5.2, Lua 5.3, Lua 5.4, Fengari, LuaJIT 2.0/2.1 (any CPU endianness). -- Main feature of this module: it was heavily optimized for speed. -- For every Lua version the module contains particular implementation branch to get benefits from version-specific features. -- - branch for Lua 5.1 (emulating bitwise operators using look-up table) -- - branch for Lua 5.2 (using bit32/bit library), suitable for both Lua 5.2 with native "bit32" and Lua 5.1 with external library "bit" -- - branch for Lua 5.3/5.4 (using native 64-bit bitwise operators) -- - branch for Lua 5.3/5.4 (using native 32-bit bitwise operators) for Lua built with LUA_INT_TYPE=LUA_INT_INT -- - branch for LuaJIT without FFI library (useful in a sandboxed environment) -- - branch for LuaJIT x86 without FFI library (LuaJIT x86 has oddity because of lack of CPU registers) -- - branch for LuaJIT 2.0 with FFI library (bit.* functions work only with Lua numbers) -- - branch for LuaJIT 2.1 with FFI library (bit.* functions can work with "int64_t" arguments) -- -- -- USAGE: -- Input data should be provided as a binary string: either as a whole string or as a sequence of substrings (chunk-by-chunk loading, total length < 9*10^15 bytes). -- Result (SHA digest) is returned in hexadecimal representation as a string of lowercase hex digits. -- Simplest usage example: -- local sha = require("sha2") -- local your_hash = sha.sha256("your string") -- See file "sha2_test.lua" for more examples. -- -- -- CHANGELOG: -- version date description -- ------- ---------- ----------- -- 9 2020-05-10 Now works in OpenWrt's Lua (dialect of Lua 5.1 with "double" + "invisible int32") -- 8 2019-09-03 SHA3 functions added -- 7 2019-03-17 Added functions to convert to/from base64 -- 6 2018-11-12 HMAC added -- 5 2018-11-10 SHA-1 added -- 4 2018-11-03 MD5 added -- 3 2018-11-02 Bug fixed: incorrect hashing of long (2 GByte) data streams on Lua 5.3/5.4 built with "int32" integers -- 2 2018-10-07 Decreased module loading time in Lua 5.1 implementation branch (thanks to Peter Melnichenko for giving a hint) -- 1 2018-10-06 First release (only SHA-2 functions) ----------------------------------------------------------------------------- -- NOTE: This is https://github.com/Egor-Skriptunoff/pure_lua_SHA @ 304d4121f080e68ef209d3f5fe093e5a955a4978 local print_debug_messages = false -- set to true to view some messages about your system's abilities and implementation branch chosen for your system local unpack, table_concat, byte, char, string_rep, sub, gsub, gmatch, string_format, floor, ceil, math_min, math_max, tonumber, type = table.unpack or unpack, table.concat, string.byte, string.char, string.rep, string.sub, string.gsub, string.gmatch, string.format, math.floor, math.ceil, math.min, math.max, tonumber, type -------------------------------------------------------------------------------- -- EXAMINING YOUR SYSTEM -------------------------------------------------------------------------------- local function get_precision(one) -- "one" must be either float 1.0 or integer 1 -- returns bits_precision, is_integer -- This function works correctly with all floating point datatypes (including non-IEEE-754) local k, n, m, prev_n = 0, one, one while true do k, prev_n, n, m = k + 1, n, n + n + 1, m + m + k % 2 if k > 256 or n - (n - 1) ~= 1 or m - (m - 1) ~= 1 or n == m then return k, false -- floating point datatype elseif n == prev_n then return k, true -- integer datatype end end end -- Make sure Lua has "double" numbers local x = 2/3 local Lua_has_double = x * 5 > 3 and x * 4 < 3 and get_precision(1.0) >= 53 assert(Lua_has_double, "at least 53-bit floating point numbers are required") -- Q: -- SHA2 was designed for FPU-less machines. -- So, why floating point numbers are needed for this module? -- A: -- 53-bit "double" numbers are useful to calculate "magic numbers" used in SHA. -- I prefer to write 50 LOC "magic numbers calculator" instead of storing more than 200 constants explicitly in this source file. local int_prec, Lua_has_integers = get_precision(1) local Lua_has_int64 = Lua_has_integers and int_prec == 64 local Lua_has_int32 = Lua_has_integers and int_prec == 32 assert(Lua_has_int64 or Lua_has_int32 or not Lua_has_integers, "Lua integers must be either 32-bit or 64-bit") -- Q: -- Does it mean that almost all non-standard configurations are not supported? -- A: -- Yes. Sorry, too many problems to support all possible Lua numbers configurations. -- Lua 5.1/5.2 with "int32" will not work. -- Lua 5.1/5.2 with "int64" will not work. -- Lua 5.1/5.2 with "int128" will not work. -- Lua 5.1/5.2 with "float" will not work. -- Lua 5.1/5.2 with "double" is OK. (default config for Lua 5.1, Lua 5.2, LuaJIT) -- Lua 5.3/5.4 with "int32" + "float" will not work. -- Lua 5.3/5.4 with "int64" + "float" will not work. -- Lua 5.3/5.4 with "int128" + "float" will not work. -- Lua 5.3/5.4 with "int32" + "double" is OK. (config used by Fengari) -- Lua 5.3/5.4 with "int64" + "double" is OK. (default config for Lua 5.3, Lua 5.4) -- Lua 5.3/5.4 with "int128" + "double" will not work. -- Using floating point numbers better than "double" instead of "double" is OK (non-IEEE-754 floating point implementation are allowed). -- Using "int128" instead of "int64" is not OK: "int128" would require different branch of implementation for optimized SHA512. -- Check for LuaJIT and 32-bit bitwise libraries local is_LuaJIT = ({false, [1] = true})[1] and (type(jit) ~= "table" or jit.version_num >= 20000) -- LuaJIT 1.x.x is treated as vanilla Lua 5.1 local is_LuaJIT_21 -- LuaJIT 2.1+ local LuaJIT_arch local ffi -- LuaJIT FFI library (as a table) local b -- 32-bit bitwise library (as a table) local library_name if is_LuaJIT then -- Assuming "bit" library is always available on LuaJIT b = require"bit" library_name = "bit" -- "ffi" is intentionally disabled on some systems for safety reason local LuaJIT_has_FFI, result = pcall(require, "ffi") if LuaJIT_has_FFI then ffi = result end is_LuaJIT_21 = not not loadstring"b=0b0" LuaJIT_arch = type(jit) == "table" and jit.arch or ffi and ffi.arch or nil else -- For vanilla Lua, "bit"/"bit32" libraries are searched in global namespace only. No attempt is made to load a library if it's not loaded yet. for _, libname in ipairs(_VERSION == "Lua 5.2" and {"bit32", "bit"} or {"bit", "bit32"}) do if type(_G[libname]) == "table" and _G[libname].bxor then b = _G[libname] library_name = libname break end end end -------------------------------------------------------------------------------- -- You can disable here some of your system's abilities (for testing purposes) -------------------------------------------------------------------------------- -- is_LuaJIT = nil -- is_LuaJIT_21 = nil -- ffi = nil -- Lua_has_int32 = nil -- Lua_has_int64 = nil -- b, library_name = nil -------------------------------------------------------------------------------- if print_debug_messages then -- Printing list of abilities of your system print("Abilities:") print(" Lua version: "..(is_LuaJIT and "LuaJIT "..(is_LuaJIT_21 and "2.1 " or "2.0 ")..(LuaJIT_arch or "")..(ffi and " with FFI" or " without FFI") or _VERSION)) print(" Integer bitwise operators: "..(Lua_has_int64 and "int64" or Lua_has_int32 and "int32" or "no")) print(" 32-bit bitwise library: "..(library_name or "not found")) end -- Selecting the most suitable implementation for given set of abilities local method, branch if is_LuaJIT and ffi then method = "Using 'ffi' library of LuaJIT" branch = "FFI" elseif is_LuaJIT then method = "Using special code for FFI-less LuaJIT" branch = "LJ" elseif Lua_has_int64 then method = "Using native int64 bitwise operators" branch = "INT64" elseif Lua_has_int32 then method = "Using native int32 bitwise operators" branch = "INT32" elseif library_name then -- when bitwise library is available (Lua 5.2 with native library "bit32" or Lua 5.1 with external library "bit") method = "Using '"..library_name.."' library" branch = "LIB32" else method = "Emulating bitwise operators using look-up table" branch = "EMUL" end if print_debug_messages then -- Printing the implementation selected to be used on your system print("Implementation selected:") print(" "..method) end -------------------------------------------------------------------------------- -- BASIC 32-BIT BITWISE FUNCTIONS -------------------------------------------------------------------------------- local AND, OR, XOR, SHL, SHR, ROL, ROR, NOT, NORM, HEX, XOR_BYTE -- Only low 32 bits of function arguments matter, high bits are ignored -- The result of all functions (except HEX) is an integer inside "correct range": -- for "bit" library: (-2^31)..(2^31-1) -- for "bit32" library: 0..(2^32-1) if branch == "FFI" or branch == "LJ" or branch == "LIB32" then -- Your system has 32-bit bitwise library (either "bit" or "bit32") AND = b.band -- 2 arguments OR = b.bor -- 2 arguments XOR = b.bxor -- 2..5 arguments SHL = b.lshift -- second argument is integer 0..31 SHR = b.rshift -- second argument is integer 0..31 ROL = b.rol or b.lrotate -- second argument is integer 0..31 ROR = b.ror or b.rrotate -- second argument is integer 0..31 NOT = b.bnot -- only for LuaJIT NORM = b.tobit -- only for LuaJIT HEX = b.tohex -- returns string of 8 lowercase hexadecimal digits assert(AND and OR and XOR and SHL and SHR and ROL and ROR and NOT, "Library '"..library_name.."' is incomplete") XOR_BYTE = XOR -- XOR of two bytes (0..255) elseif branch == "EMUL" then -- Emulating 32-bit bitwise operations using 53-bit floating point arithmetic function SHL(x, n) return (x * 2^n) % 2^32 end function SHR(x, n) -- return (x % 2^32 - x % 2^n) / 2^n x = x % 2^32 / 2^n return x - x % 1 end function ROL(x, n) x = x % 2^32 * 2^n local r = x % 2^32 return r + (x - r) / 2^32 end function ROR(x, n) x = x % 2^32 / 2^n local r = x % 1 return r * 2^32 + (x - r) end local AND_of_two_bytes = {[0] = 0} -- look-up table (256*256 entries) local idx = 0 for y = 0, 127 * 256, 256 do for x = y, y + 127 do x = AND_of_two_bytes[x] * 2 AND_of_two_bytes[idx] = x AND_of_two_bytes[idx + 1] = x AND_of_two_bytes[idx + 256] = x AND_of_two_bytes[idx + 257] = x + 1 idx = idx + 2 end idx = idx + 256 end local function and_or_xor(x, y, operation) -- operation: nil = AND, 1 = OR, 2 = XOR local x0 = x % 2^32 local y0 = y % 2^32 local rx = x0 % 256 local ry = y0 % 256 local res = AND_of_two_bytes[rx + ry * 256] x = x0 - rx y = (y0 - ry) / 256 rx = x % 65536 ry = y % 256 res = res + AND_of_two_bytes[rx + ry] * 256 x = (x - rx) / 256 y = (y - ry) / 256 rx = x % 65536 + y % 256 res = res + AND_of_two_bytes[rx] * 65536 res = res + AND_of_two_bytes[(x + y - rx) / 256] * 16777216 if operation then res = x0 + y0 - operation * res end return res end function AND(x, y) return and_or_xor(x, y) end function OR(x, y) return and_or_xor(x, y, 1) end function XOR(x, y, z, t, u) -- 2..5 arguments if z then if t then if u then t = and_or_xor(t, u, 2) end z = and_or_xor(z, t, 2) end y = and_or_xor(y, z, 2) end return and_or_xor(x, y, 2) end function XOR_BYTE(x, y) return x + y - 2 * AND_of_two_bytes[x + y * 256] end end HEX = HEX or pcall(string_format, "%x", 2^31) and function (x) -- returns string of 8 lowercase hexadecimal digits return string_format("%08x", x % 4294967296) end or function (x) -- for OpenWrt's dialect of Lua return string_format("%08x", (x + 2^31) % 2^32 - 2^31) end local function XOR32A5(x) return XOR(x, 0xA5A5A5A5) % 4294967296 end local function create_array_of_lanes() return {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} end -------------------------------------------------------------------------------- -- CREATING OPTIMIZED INNER LOOP -------------------------------------------------------------------------------- -- Inner loop functions local sha256_feed_64, sha512_feed_128, md5_feed_64, sha1_feed_64, keccak_feed -- Arrays of SHA2 "magic numbers" (in "INT64" and "FFI" branches "*_lo" arrays contain 64-bit values) local sha2_K_lo, sha2_K_hi, sha2_H_lo, sha2_H_hi, sha3_RC_lo, sha3_RC_hi = {}, {}, {}, {}, {}, {} local sha2_H_ext256 = {[224] = {}, [256] = sha2_H_hi} local sha2_H_ext512_lo, sha2_H_ext512_hi = {[384] = {}, [512] = sha2_H_lo}, {[384] = {}, [512] = sha2_H_hi} local md5_K, md5_sha1_H = {}, {0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0} local md5_next_shift = {0, 0, 0, 0, 0, 0, 0, 0, 28, 25, 26, 27, 0, 0, 10, 9, 11, 12, 0, 15, 16, 17, 18, 0, 20, 22, 23, 21} local HEX64, XOR64A5, lanes_index_base -- defined only for branches that internally use 64-bit integers: "INT64" and "FFI" local common_W = {} -- temporary table shared between all calculations (to avoid creating new temporary table every time) local K_lo_modulo, hi_factor, hi_factor_keccak = 4294967296, 0, 0 local function build_keccak_format(elem) local keccak_format = {} for _, size in ipairs{1, 9, 13, 17, 18, 21} do keccak_format[size] = "<"..string_rep(elem, size) end return keccak_format end if branch == "FFI" then -- SHA256 implementation for "LuaJIT with FFI" branch local common_W_FFI_int32 = ffi.new"int32_t[80]" -- 64 is enough for SHA256, but 80 is needed for SHA-1 function sha256_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W, K = common_W_FFI_int32, sha2_K_hi for pos = offs, offs + size - 1, 64 do for j = 0, 15 do pos = pos + 4 local a, b, c, d = byte(str, pos - 3, pos) -- slow, but doesn't depend on endianness W[j] = OR(SHL(a, 24), SHL(b, 16), SHL(c, 8), d) end for j = 16, 63 do local a, b = W[j-15], W[j-2] W[j] = NORM( XOR(ROR(a, 7), ROL(a, 14), SHR(a, 3)) + XOR(ROL(b, 15), ROL(b, 13), SHR(b, 10)) + W[j-7] + W[j-16] ) end local a, b, c, d, e, f, g, h = H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8] for j = 0, 63, 8 do -- Thanks to Peter Cawley for this workaround (unroll the loop to avoid "PHI shuffling too complex" due to PHIs overlap) local z = NORM( XOR(g, AND(e, XOR(f, g))) + XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + (W[j] + K[j+1] + h) ) h, g, f, e = g, f, e, NORM( d + z ) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(g, AND(e, XOR(f, g))) + XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + (W[j+1] + K[j+2] + h) ) h, g, f, e = g, f, e, NORM( d + z ) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(g, AND(e, XOR(f, g))) + XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + (W[j+2] + K[j+3] + h) ) h, g, f, e = g, f, e, NORM( d + z ) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(g, AND(e, XOR(f, g))) + XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + (W[j+3] + K[j+4] + h) ) h, g, f, e = g, f, e, NORM( d + z ) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(g, AND(e, XOR(f, g))) + XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + (W[j+4] + K[j+5] + h) ) h, g, f, e = g, f, e, NORM( d + z ) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(g, AND(e, XOR(f, g))) + XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + (W[j+5] + K[j+6] + h) ) h, g, f, e = g, f, e, NORM( d + z ) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(g, AND(e, XOR(f, g))) + XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + (W[j+6] + K[j+7] + h) ) h, g, f, e = g, f, e, NORM( d + z ) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(g, AND(e, XOR(f, g))) + XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + (W[j+7] + K[j+8] + h) ) h, g, f, e = g, f, e, NORM( d + z ) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) end H[1], H[2], H[3], H[4] = NORM(a + H[1]), NORM(b + H[2]), NORM(c + H[3]), NORM(d + H[4]) H[5], H[6], H[7], H[8] = NORM(e + H[5]), NORM(f + H[6]), NORM(g + H[7]), NORM(h + H[8]) end end local common_W_FFI_int64 = ffi.new"int64_t[80]" local int64 = ffi.typeof"int64_t" local int32 = ffi.typeof"int32_t" local uint32 = ffi.typeof"uint32_t" hi_factor = int64(2^32) if is_LuaJIT_21 then -- LuaJIT 2.1 supports bitwise 64-bit operations local AND64, OR64, XOR64, NOT64, SHL64, SHR64, ROL64, ROR64 -- introducing synonyms for better code readability = AND, OR, XOR, NOT, SHL, SHR, ROL, ROR HEX64 = HEX -- SHA3 implementation for "LuaJIT 2.1 + FFI" branch local lanes_arr64 = ffi.typeof"int64_t[30]" -- 25 + 5 for temporary usage -- lanes array is indexed from 0 lanes_index_base = 0 hi_factor_keccak = int64(2^32) function create_array_of_lanes() return lanes_arr64() end function keccak_feed(lanes, _, str, offs, size, block_size_in_bytes) -- offs >= 0, size >= 0, size is multiple of block_size_in_bytes, block_size_in_bytes is positive multiple of 8 local RC = sha3_RC_lo local qwords_qty = SHR(block_size_in_bytes, 3) for pos = offs, offs + size - 1, block_size_in_bytes do for j = 0, qwords_qty - 1 do pos = pos + 8 local h, g, f, e, d, c, b, a = byte(str, pos - 7, pos) -- slow, but doesn't depend on endianness lanes[j] = XOR64(lanes[j], OR64(OR(SHL(a, 24), SHL(b, 16), SHL(c, 8), d) * int64(2^32), uint32(int32(OR(SHL(e, 24), SHL(f, 16), SHL(g, 8), h))))) end for round_idx = 1, 24 do for j = 0, 4 do lanes[25 + j] = XOR64(lanes[j], lanes[j+5], lanes[j+10], lanes[j+15], lanes[j+20]) end local D = XOR64(lanes[25], ROL64(lanes[27], 1)) lanes[1], lanes[6], lanes[11], lanes[16] = ROL64(XOR64(D, lanes[6]), 44), ROL64(XOR64(D, lanes[16]), 45), ROL64(XOR64(D, lanes[1]), 1), ROL64(XOR64(D, lanes[11]), 10) lanes[21] = ROL64(XOR64(D, lanes[21]), 2) D = XOR64(lanes[26], ROL64(lanes[28], 1)) lanes[2], lanes[7], lanes[12], lanes[22] = ROL64(XOR64(D, lanes[12]), 43), ROL64(XOR64(D, lanes[22]), 61), ROL64(XOR64(D, lanes[7]), 6), ROL64(XOR64(D, lanes[2]), 62) lanes[17] = ROL64(XOR64(D, lanes[17]), 15) D = XOR64(lanes[27], ROL64(lanes[29], 1)) lanes[3], lanes[8], lanes[18], lanes[23] = ROL64(XOR64(D, lanes[18]), 21), ROL64(XOR64(D, lanes[3]), 28), ROL64(XOR64(D, lanes[23]), 56), ROL64(XOR64(D, lanes[8]), 55) lanes[13] = ROL64(XOR64(D, lanes[13]), 25) D = XOR64(lanes[28], ROL64(lanes[25], 1)) lanes[4], lanes[14], lanes[19], lanes[24] = ROL64(XOR64(D, lanes[24]), 14), ROL64(XOR64(D, lanes[19]), 8), ROL64(XOR64(D, lanes[4]), 27), ROL64(XOR64(D, lanes[14]), 39) lanes[9] = ROL64(XOR64(D, lanes[9]), 20) D = XOR64(lanes[29], ROL64(lanes[26], 1)) lanes[5], lanes[10], lanes[15], lanes[20] = ROL64(XOR64(D, lanes[10]), 3), ROL64(XOR64(D, lanes[20]), 18), ROL64(XOR64(D, lanes[5]), 36), ROL64(XOR64(D, lanes[15]), 41) lanes[0] = XOR64(D, lanes[0]) lanes[0], lanes[1], lanes[2], lanes[3], lanes[4] = XOR64(lanes[0], AND64(NOT64(lanes[1]), lanes[2]), RC[round_idx]), XOR64(lanes[1], AND64(NOT64(lanes[2]), lanes[3])), XOR64(lanes[2], AND64(NOT64(lanes[3]), lanes[4])), XOR64(lanes[3], AND64(NOT64(lanes[4]), lanes[0])), XOR64(lanes[4], AND64(NOT64(lanes[0]), lanes[1])) lanes[5], lanes[6], lanes[7], lanes[8], lanes[9] = XOR64(lanes[8], AND64(NOT64(lanes[9]), lanes[5])), XOR64(lanes[9], AND64(NOT64(lanes[5]), lanes[6])), XOR64(lanes[5], AND64(NOT64(lanes[6]), lanes[7])), XOR64(lanes[6], AND64(NOT64(lanes[7]), lanes[8])), XOR64(lanes[7], AND64(NOT64(lanes[8]), lanes[9])) lanes[10], lanes[11], lanes[12], lanes[13], lanes[14] = XOR64(lanes[11], AND64(NOT64(lanes[12]), lanes[13])), XOR64(lanes[12], AND64(NOT64(lanes[13]), lanes[14])), XOR64(lanes[13], AND64(NOT64(lanes[14]), lanes[10])), XOR64(lanes[14], AND64(NOT64(lanes[10]), lanes[11])), XOR64(lanes[10], AND64(NOT64(lanes[11]), lanes[12])) lanes[15], lanes[16], lanes[17], lanes[18], lanes[19] = XOR64(lanes[19], AND64(NOT64(lanes[15]), lanes[16])), XOR64(lanes[15], AND64(NOT64(lanes[16]), lanes[17])), XOR64(lanes[16], AND64(NOT64(lanes[17]), lanes[18])), XOR64(lanes[17], AND64(NOT64(lanes[18]), lanes[19])), XOR64(lanes[18], AND64(NOT64(lanes[19]), lanes[15])) lanes[20], lanes[21], lanes[22], lanes[23], lanes[24] = XOR64(lanes[22], AND64(NOT64(lanes[23]), lanes[24])), XOR64(lanes[23], AND64(NOT64(lanes[24]), lanes[20])), XOR64(lanes[24], AND64(NOT64(lanes[20]), lanes[21])), XOR64(lanes[20], AND64(NOT64(lanes[21]), lanes[22])), XOR64(lanes[21], AND64(NOT64(lanes[22]), lanes[23])) end end end -- SHA512 implementation for "LuaJIT 2.1 + FFI" branch local A5_long = 0xA5A5A5A5 * int64(2^32 + 1) -- It's impossible to use constant 0xA5A5A5A5A5A5A5A5LL because it will raise syntax error on other Lua versions function XOR64A5(long) return XOR64(long, A5_long) end function sha512_feed_128(H, _, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 128 local W, K = common_W_FFI_int64, sha2_K_lo for pos = offs, offs + size - 1, 128 do for j = 0, 15 do pos = pos + 8 local a, b, c, d, e, f, g, h = byte(str, pos - 7, pos) -- slow, but doesn't depend on endianness W[j] = OR64(OR(SHL(a, 24), SHL(b, 16), SHL(c, 8), d) * int64(2^32), uint32(int32(OR(SHL(e, 24), SHL(f, 16), SHL(g, 8), h)))) end for j = 16, 79 do local a, b = W[j-15], W[j-2] W[j] = XOR64(ROR64(a, 1), ROR64(a, 8), SHR64(a, 7)) + XOR64(ROR64(b, 19), ROL64(b, 3), SHR64(b, 6)) + W[j-7] + W[j-16] end local a, b, c, d, e, f, g, h = H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8] for j = 0, 79, 8 do local z = XOR64(ROR64(e, 14), ROR64(e, 18), ROL64(e, 23)) + XOR64(g, AND64(e, XOR64(f, g))) + h + K[j+1] + W[j] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XOR64(AND64(XOR64(a, b), c), AND64(a, b)) + XOR64(ROR64(a, 28), ROL64(a, 25), ROL64(a, 30)) + z z = XOR64(ROR64(e, 14), ROR64(e, 18), ROL64(e, 23)) + XOR64(g, AND64(e, XOR64(f, g))) + h + K[j+2] + W[j+1] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XOR64(AND64(XOR64(a, b), c), AND64(a, b)) + XOR64(ROR64(a, 28), ROL64(a, 25), ROL64(a, 30)) + z z = XOR64(ROR64(e, 14), ROR64(e, 18), ROL64(e, 23)) + XOR64(g, AND64(e, XOR64(f, g))) + h + K[j+3] + W[j+2] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XOR64(AND64(XOR64(a, b), c), AND64(a, b)) + XOR64(ROR64(a, 28), ROL64(a, 25), ROL64(a, 30)) + z z = XOR64(ROR64(e, 14), ROR64(e, 18), ROL64(e, 23)) + XOR64(g, AND64(e, XOR64(f, g))) + h + K[j+4] + W[j+3] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XOR64(AND64(XOR64(a, b), c), AND64(a, b)) + XOR64(ROR64(a, 28), ROL64(a, 25), ROL64(a, 30)) + z z = XOR64(ROR64(e, 14), ROR64(e, 18), ROL64(e, 23)) + XOR64(g, AND64(e, XOR64(f, g))) + h + K[j+5] + W[j+4] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XOR64(AND64(XOR64(a, b), c), AND64(a, b)) + XOR64(ROR64(a, 28), ROL64(a, 25), ROL64(a, 30)) + z z = XOR64(ROR64(e, 14), ROR64(e, 18), ROL64(e, 23)) + XOR64(g, AND64(e, XOR64(f, g))) + h + K[j+6] + W[j+5] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XOR64(AND64(XOR64(a, b), c), AND64(a, b)) + XOR64(ROR64(a, 28), ROL64(a, 25), ROL64(a, 30)) + z z = XOR64(ROR64(e, 14), ROR64(e, 18), ROL64(e, 23)) + XOR64(g, AND64(e, XOR64(f, g))) + h + K[j+7] + W[j+6] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XOR64(AND64(XOR64(a, b), c), AND64(a, b)) + XOR64(ROR64(a, 28), ROL64(a, 25), ROL64(a, 30)) + z z = XOR64(ROR64(e, 14), ROR64(e, 18), ROL64(e, 23)) + XOR64(g, AND64(e, XOR64(f, g))) + h + K[j+8] + W[j+7] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XOR64(AND64(XOR64(a, b), c), AND64(a, b)) + XOR64(ROR64(a, 28), ROL64(a, 25), ROL64(a, 30)) + z end H[1] = a + H[1] H[2] = b + H[2] H[3] = c + H[3] H[4] = d + H[4] H[5] = e + H[5] H[6] = f + H[6] H[7] = g + H[7] H[8] = h + H[8] end end else -- LuaJIT 2.0 doesn't support 64-bit bitwise operations -- SHA512 implementation for "LuaJIT 2.0 + FFI" branch local union64 = ffi.typeof"union{int64_t i64; struct{int32_t lo, hi;} i32;}" do -- make sure the struct is endianness-compatible local u = union64(1) if u.i32.lo < u.i32.hi then union64 = ffi.typeof"union{int64_t i64; struct{int32_t hi, lo;} i32;}" end end local unions64 = ffi.typeof("$[?]", union64) local U = unions64(3) -- this array of unions is used for fast splitting int64 into int32_high and int32_low -- "xorrific" 64-bit functions :-) -- int64 input is splitted into two int32 parts, some bitwise 32-bit operations are performed, finally the result is converted to int64 -- these functions are needed because bit.* functions in LuaJIT 2.0 don't work with int64_t local function XORROR64_1(a) -- return XOR64(ROR64(a, 1), ROR64(a, 8), SHR64(a, 7)) U[0].i64 = a local a_lo, a_hi = U[0].i32.lo, U[0].i32.hi local t_lo = XOR(OR(SHR(a_lo, 1), SHL(a_hi, 31)), OR(SHR(a_lo, 8), SHL(a_hi, 24)), OR(SHR(a_lo, 7), SHL(a_hi, 25))) local t_hi = XOR(OR(SHR(a_hi, 1), SHL(a_lo, 31)), OR(SHR(a_hi, 8), SHL(a_lo, 24)), SHR(a_hi, 7)) return t_hi * int64(2^32) + uint32(int32(t_lo)) end local function XORROR64_2(b) -- return XOR64(ROR64(b, 19), ROL64(b, 3), SHR64(b, 6)) U[0].i64 = b local b_lo, b_hi = U[0].i32.lo, U[0].i32.hi local u_lo = XOR(OR(SHR(b_lo, 19), SHL(b_hi, 13)), OR(SHL(b_lo, 3), SHR(b_hi, 29)), OR(SHR(b_lo, 6), SHL(b_hi, 26))) local u_hi = XOR(OR(SHR(b_hi, 19), SHL(b_lo, 13)), OR(SHL(b_hi, 3), SHR(b_lo, 29)), SHR(b_hi, 6)) return u_hi * int64(2^32) + uint32(int32(u_lo)) end local function XORROR64_3(e) -- return XOR64(ROR64(e, 14), ROR64(e, 18), ROL64(e, 23)) U[0].i64 = e local e_lo, e_hi = U[0].i32.lo, U[0].i32.hi local u_lo = XOR(OR(SHR(e_lo, 14), SHL(e_hi, 18)), OR(SHR(e_lo, 18), SHL(e_hi, 14)), OR(SHL(e_lo, 23), SHR(e_hi, 9))) local u_hi = XOR(OR(SHR(e_hi, 14), SHL(e_lo, 18)), OR(SHR(e_hi, 18), SHL(e_lo, 14)), OR(SHL(e_hi, 23), SHR(e_lo, 9))) return u_hi * int64(2^32) + uint32(int32(u_lo)) end local function XORROR64_6(a) -- return XOR64(ROR64(a, 28), ROL64(a, 25), ROL64(a, 30)) U[0].i64 = a local b_lo, b_hi = U[0].i32.lo, U[0].i32.hi local u_lo = XOR(OR(SHR(b_lo, 28), SHL(b_hi, 4)), OR(SHL(b_lo, 30), SHR(b_hi, 2)), OR(SHL(b_lo, 25), SHR(b_hi, 7))) local u_hi = XOR(OR(SHR(b_hi, 28), SHL(b_lo, 4)), OR(SHL(b_hi, 30), SHR(b_lo, 2)), OR(SHL(b_hi, 25), SHR(b_lo, 7))) return u_hi * int64(2^32) + uint32(int32(u_lo)) end local function XORROR64_4(e, f, g) -- return XOR64(g, AND64(e, XOR64(f, g))) U[0].i64 = f U[1].i64 = g U[2].i64 = e local f_lo, f_hi = U[0].i32.lo, U[0].i32.hi local g_lo, g_hi = U[1].i32.lo, U[1].i32.hi local e_lo, e_hi = U[2].i32.lo, U[2].i32.hi local result_lo = XOR(g_lo, AND(e_lo, XOR(f_lo, g_lo))) local result_hi = XOR(g_hi, AND(e_hi, XOR(f_hi, g_hi))) return result_hi * int64(2^32) + uint32(int32(result_lo)) end local function XORROR64_5(a, b, c) -- return XOR64(AND64(XOR64(a, b), c), AND64(a, b)) U[0].i64 = a U[1].i64 = b U[2].i64 = c local a_lo, a_hi = U[0].i32.lo, U[0].i32.hi local b_lo, b_hi = U[1].i32.lo, U[1].i32.hi local c_lo, c_hi = U[2].i32.lo, U[2].i32.hi local result_lo = XOR(AND(XOR(a_lo, b_lo), c_lo), AND(a_lo, b_lo)) local result_hi = XOR(AND(XOR(a_hi, b_hi), c_hi), AND(a_hi, b_hi)) return result_hi * int64(2^32) + uint32(int32(result_lo)) end function XOR64A5(long) -- return XOR64(long, 0xA5A5A5A5A5A5A5A5) U[0].i64 = long local lo32, hi32 = U[0].i32.lo, U[0].i32.hi lo32 = XOR(lo32, 0xA5A5A5A5) hi32 = XOR(hi32, 0xA5A5A5A5) return hi32 * int64(2^32) + uint32(int32(lo32)) end function HEX64(long) U[0].i64 = long return HEX(U[0].i32.hi)..HEX(U[0].i32.lo) end function sha512_feed_128(H, _, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 128 local W, K = common_W_FFI_int64, sha2_K_lo for pos = offs, offs + size - 1, 128 do for j = 0, 15 do pos = pos + 8 local a, b, c, d, e, f, g, h = byte(str, pos - 7, pos) -- slow, but doesn't depend on endianness W[j] = OR(SHL(a, 24), SHL(b, 16), SHL(c, 8), d) * int64(2^32) + uint32(int32(OR(SHL(e, 24), SHL(f, 16), SHL(g, 8), h))) end for j = 16, 79 do W[j] = XORROR64_1(W[j-15]) + XORROR64_2(W[j-2]) + W[j-7] + W[j-16] end local a, b, c, d, e, f, g, h = H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8] for j = 0, 79, 8 do local z = XORROR64_3(e) + XORROR64_4(e, f, g) + h + K[j+1] + W[j] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XORROR64_5(a, b, c) + XORROR64_6(a) + z z = XORROR64_3(e) + XORROR64_4(e, f, g) + h + K[j+2] + W[j+1] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XORROR64_5(a, b, c) + XORROR64_6(a) + z z = XORROR64_3(e) + XORROR64_4(e, f, g) + h + K[j+3] + W[j+2] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XORROR64_5(a, b, c) + XORROR64_6(a) + z z = XORROR64_3(e) + XORROR64_4(e, f, g) + h + K[j+4] + W[j+3] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XORROR64_5(a, b, c) + XORROR64_6(a) + z z = XORROR64_3(e) + XORROR64_4(e, f, g) + h + K[j+5] + W[j+4] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XORROR64_5(a, b, c) + XORROR64_6(a) + z z = XORROR64_3(e) + XORROR64_4(e, f, g) + h + K[j+6] + W[j+5] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XORROR64_5(a, b, c) + XORROR64_6(a) + z z = XORROR64_3(e) + XORROR64_4(e, f, g) + h + K[j+7] + W[j+6] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XORROR64_5(a, b, c) + XORROR64_6(a) + z z = XORROR64_3(e) + XORROR64_4(e, f, g) + h + K[j+8] + W[j+7] h, g, f, e = g, f, e, z + d d, c, b, a = c, b, a, XORROR64_5(a, b, c) + XORROR64_6(a) + z end H[1] = a + H[1] H[2] = b + H[2] H[3] = c + H[3] H[4] = d + H[4] H[5] = e + H[5] H[6] = f + H[6] H[7] = g + H[7] H[8] = h + H[8] end end end -- MD5 implementation for "LuaJIT with FFI" branch function md5_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W, K = common_W_FFI_int32, md5_K for pos = offs, offs + size - 1, 64 do for j = 0, 15 do pos = pos + 4 local a, b, c, d = byte(str, pos - 3, pos) -- slow, but doesn't depend on endianness W[j] = OR(SHL(d, 24), SHL(c, 16), SHL(b, 8), a) end local a, b, c, d = H[1], H[2], H[3], H[4] for j = 0, 15, 4 do a, d, c, b = d, c, b, NORM(ROL(XOR(d, AND(b, XOR(c, d))) + (K[j+1] + W[j ] + a), 7) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(d, AND(b, XOR(c, d))) + (K[j+2] + W[j+1] + a), 12) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(d, AND(b, XOR(c, d))) + (K[j+3] + W[j+2] + a), 17) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(d, AND(b, XOR(c, d))) + (K[j+4] + W[j+3] + a), 22) + b) end for j = 16, 31, 4 do local g = 5*j a, d, c, b = d, c, b, NORM(ROL(XOR(c, AND(d, XOR(b, c))) + (K[j+1] + W[AND(g + 1, 15)] + a), 5) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(c, AND(d, XOR(b, c))) + (K[j+2] + W[AND(g + 6, 15)] + a), 9) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(c, AND(d, XOR(b, c))) + (K[j+3] + W[AND(g - 5, 15)] + a), 14) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(c, AND(d, XOR(b, c))) + (K[j+4] + W[AND(g , 15)] + a), 20) + b) end for j = 32, 47, 4 do local g = 3*j a, d, c, b = d, c, b, NORM(ROL(XOR(b, c, d) + (K[j+1] + W[AND(g + 5, 15)] + a), 4) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(b, c, d) + (K[j+2] + W[AND(g + 8, 15)] + a), 11) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(b, c, d) + (K[j+3] + W[AND(g - 5, 15)] + a), 16) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(b, c, d) + (K[j+4] + W[AND(g - 2, 15)] + a), 23) + b) end for j = 48, 63, 4 do local g = 7*j a, d, c, b = d, c, b, NORM(ROL(XOR(c, OR(b, NOT(d))) + (K[j+1] + W[AND(g , 15)] + a), 6) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(c, OR(b, NOT(d))) + (K[j+2] + W[AND(g + 7, 15)] + a), 10) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(c, OR(b, NOT(d))) + (K[j+3] + W[AND(g - 2, 15)] + a), 15) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(c, OR(b, NOT(d))) + (K[j+4] + W[AND(g + 5, 15)] + a), 21) + b) end H[1], H[2], H[3], H[4] = NORM(a + H[1]), NORM(b + H[2]), NORM(c + H[3]), NORM(d + H[4]) end end -- SHA-1 implementation for "LuaJIT with FFI" branch function sha1_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W = common_W_FFI_int32 for pos = offs, offs + size - 1, 64 do for j = 0, 15 do pos = pos + 4 local a, b, c, d = byte(str, pos - 3, pos) -- slow, but doesn't depend on endianness W[j] = OR(SHL(a, 24), SHL(b, 16), SHL(c, 8), d) end for j = 16, 79 do W[j] = ROL(XOR(W[j-3], W[j-8], W[j-14], W[j-16]), 1) end local a, b, c, d, e = H[1], H[2], H[3], H[4], H[5] for j = 0, 19, 5 do e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(d, AND(b, XOR(d, c))) + (W[j] + 0x5A827999 + e)) -- constant = floor(2^30 * sqrt(2)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(d, AND(b, XOR(d, c))) + (W[j+1] + 0x5A827999 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(d, AND(b, XOR(d, c))) + (W[j+2] + 0x5A827999 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(d, AND(b, XOR(d, c))) + (W[j+3] + 0x5A827999 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(d, AND(b, XOR(d, c))) + (W[j+4] + 0x5A827999 + e)) end for j = 20, 39, 5 do e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j] + 0x6ED9EBA1 + e)) -- 2^30 * sqrt(3) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+1] + 0x6ED9EBA1 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+2] + 0x6ED9EBA1 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+3] + 0x6ED9EBA1 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+4] + 0x6ED9EBA1 + e)) end for j = 40, 59, 5 do e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(AND(d, XOR(b, c)), AND(b, c)) + (W[j] + 0x8F1BBCDC + e)) -- 2^30 * sqrt(5) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(AND(d, XOR(b, c)), AND(b, c)) + (W[j+1] + 0x8F1BBCDC + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(AND(d, XOR(b, c)), AND(b, c)) + (W[j+2] + 0x8F1BBCDC + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(AND(d, XOR(b, c)), AND(b, c)) + (W[j+3] + 0x8F1BBCDC + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(AND(d, XOR(b, c)), AND(b, c)) + (W[j+4] + 0x8F1BBCDC + e)) end for j = 60, 79, 5 do e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j] + 0xCA62C1D6 + e)) -- 2^30 * sqrt(10) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+1] + 0xCA62C1D6 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+2] + 0xCA62C1D6 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+3] + 0xCA62C1D6 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+4] + 0xCA62C1D6 + e)) end H[1], H[2], H[3], H[4], H[5] = NORM(a + H[1]), NORM(b + H[2]), NORM(c + H[3]), NORM(d + H[4]), NORM(e + H[5]) end end end -- SHA3 implementation for "LuaJIT 2.0 + FFI" and "LuaJIT without FFI" branches if branch == "FFI" and not is_LuaJIT_21 or branch == "LJ" then if branch == "FFI" then local lanes_arr32 = ffi.typeof"int32_t[31]" -- 25 + 5 + 1 (due to 1-based indexing) function create_array_of_lanes() return lanes_arr32() end end function keccak_feed(lanes_lo, lanes_hi, str, offs, size, block_size_in_bytes) -- offs >= 0, size >= 0, size is multiple of block_size_in_bytes, block_size_in_bytes is positive multiple of 8 local RC_lo, RC_hi = sha3_RC_lo, sha3_RC_hi local qwords_qty = SHR(block_size_in_bytes, 3) for pos = offs, offs + size - 1, block_size_in_bytes do for j = 1, qwords_qty do local a, b, c, d = byte(str, pos + 1, pos + 4) lanes_lo[j] = XOR(lanes_lo[j], OR(SHL(d, 24), SHL(c, 16), SHL(b, 8), a)) pos = pos + 8 a, b, c, d = byte(str, pos - 3, pos) lanes_hi[j] = XOR(lanes_hi[j], OR(SHL(d, 24), SHL(c, 16), SHL(b, 8), a)) end for round_idx = 1, 24 do for j = 1, 5 do lanes_lo[25 + j] = XOR(lanes_lo[j], lanes_lo[j + 5], lanes_lo[j + 10], lanes_lo[j + 15], lanes_lo[j + 20]) end for j = 1, 5 do lanes_hi[25 + j] = XOR(lanes_hi[j], lanes_hi[j + 5], lanes_hi[j + 10], lanes_hi[j + 15], lanes_hi[j + 20]) end local D_lo = XOR(lanes_lo[26], SHL(lanes_lo[28], 1), SHR(lanes_hi[28], 31)) local D_hi = XOR(lanes_hi[26], SHL(lanes_hi[28], 1), SHR(lanes_lo[28], 31)) lanes_lo[2], lanes_hi[2], lanes_lo[7], lanes_hi[7], lanes_lo[12], lanes_hi[12], lanes_lo[17], lanes_hi[17] = XOR(SHR(XOR(D_lo, lanes_lo[7]), 20), SHL(XOR(D_hi, lanes_hi[7]), 12)), XOR(SHR(XOR(D_hi, lanes_hi[7]), 20), SHL(XOR(D_lo, lanes_lo[7]), 12)), XOR(SHR(XOR(D_lo, lanes_lo[17]), 19), SHL(XOR(D_hi, lanes_hi[17]), 13)), XOR(SHR(XOR(D_hi, lanes_hi[17]), 19), SHL(XOR(D_lo, lanes_lo[17]), 13)), XOR(SHL(XOR(D_lo, lanes_lo[2]), 1), SHR(XOR(D_hi, lanes_hi[2]), 31)), XOR(SHL(XOR(D_hi, lanes_hi[2]), 1), SHR(XOR(D_lo, lanes_lo[2]), 31)), XOR(SHL(XOR(D_lo, lanes_lo[12]), 10), SHR(XOR(D_hi, lanes_hi[12]), 22)), XOR(SHL(XOR(D_hi, lanes_hi[12]), 10), SHR(XOR(D_lo, lanes_lo[12]), 22)) local L, H = XOR(D_lo, lanes_lo[22]), XOR(D_hi, lanes_hi[22]) lanes_lo[22], lanes_hi[22] = XOR(SHL(L, 2), SHR(H, 30)), XOR(SHL(H, 2), SHR(L, 30)) D_lo = XOR(lanes_lo[27], SHL(lanes_lo[29], 1), SHR(lanes_hi[29], 31)) D_hi = XOR(lanes_hi[27], SHL(lanes_hi[29], 1), SHR(lanes_lo[29], 31)) lanes_lo[3], lanes_hi[3], lanes_lo[8], lanes_hi[8], lanes_lo[13], lanes_hi[13], lanes_lo[23], lanes_hi[23] = XOR(SHR(XOR(D_lo, lanes_lo[13]), 21), SHL(XOR(D_hi, lanes_hi[13]), 11)), XOR(SHR(XOR(D_hi, lanes_hi[13]), 21), SHL(XOR(D_lo, lanes_lo[13]), 11)), XOR(SHR(XOR(D_lo, lanes_lo[23]), 3), SHL(XOR(D_hi, lanes_hi[23]), 29)), XOR(SHR(XOR(D_hi, lanes_hi[23]), 3), SHL(XOR(D_lo, lanes_lo[23]), 29)), XOR(SHL(XOR(D_lo, lanes_lo[8]), 6), SHR(XOR(D_hi, lanes_hi[8]), 26)), XOR(SHL(XOR(D_hi, lanes_hi[8]), 6), SHR(XOR(D_lo, lanes_lo[8]), 26)), XOR(SHR(XOR(D_lo, lanes_lo[3]), 2), SHL(XOR(D_hi, lanes_hi[3]), 30)), XOR(SHR(XOR(D_hi, lanes_hi[3]), 2), SHL(XOR(D_lo, lanes_lo[3]), 30)) L, H = XOR(D_lo, lanes_lo[18]), XOR(D_hi, lanes_hi[18]) lanes_lo[18], lanes_hi[18] = XOR(SHL(L, 15), SHR(H, 17)), XOR(SHL(H, 15), SHR(L, 17)) D_lo = XOR(lanes_lo[28], SHL(lanes_lo[30], 1), SHR(lanes_hi[30], 31)) D_hi = XOR(lanes_hi[28], SHL(lanes_hi[30], 1), SHR(lanes_lo[30], 31)) lanes_lo[4], lanes_hi[4], lanes_lo[9], lanes_hi[9], lanes_lo[19], lanes_hi[19], lanes_lo[24], lanes_hi[24] = XOR(SHL(XOR(D_lo, lanes_lo[19]), 21), SHR(XOR(D_hi, lanes_hi[19]), 11)), XOR(SHL(XOR(D_hi, lanes_hi[19]), 21), SHR(XOR(D_lo, lanes_lo[19]), 11)), XOR(SHL(XOR(D_lo, lanes_lo[4]), 28), SHR(XOR(D_hi, lanes_hi[4]), 4)), XOR(SHL(XOR(D_hi, lanes_hi[4]), 28), SHR(XOR(D_lo, lanes_lo[4]), 4)), XOR(SHR(XOR(D_lo, lanes_lo[24]), 8), SHL(XOR(D_hi, lanes_hi[24]), 24)), XOR(SHR(XOR(D_hi, lanes_hi[24]), 8), SHL(XOR(D_lo, lanes_lo[24]), 24)), XOR(SHR(XOR(D_lo, lanes_lo[9]), 9), SHL(XOR(D_hi, lanes_hi[9]), 23)), XOR(SHR(XOR(D_hi, lanes_hi[9]), 9), SHL(XOR(D_lo, lanes_lo[9]), 23)) L, H = XOR(D_lo, lanes_lo[14]), XOR(D_hi, lanes_hi[14]) lanes_lo[14], lanes_hi[14] = XOR(SHL(L, 25), SHR(H, 7)), XOR(SHL(H, 25), SHR(L, 7)) D_lo = XOR(lanes_lo[29], SHL(lanes_lo[26], 1), SHR(lanes_hi[26], 31)) D_hi = XOR(lanes_hi[29], SHL(lanes_hi[26], 1), SHR(lanes_lo[26], 31)) lanes_lo[5], lanes_hi[5], lanes_lo[15], lanes_hi[15], lanes_lo[20], lanes_hi[20], lanes_lo[25], lanes_hi[25] = XOR(SHL(XOR(D_lo, lanes_lo[25]), 14), SHR(XOR(D_hi, lanes_hi[25]), 18)), XOR(SHL(XOR(D_hi, lanes_hi[25]), 14), SHR(XOR(D_lo, lanes_lo[25]), 18)), XOR(SHL(XOR(D_lo, lanes_lo[20]), 8), SHR(XOR(D_hi, lanes_hi[20]), 24)), XOR(SHL(XOR(D_hi, lanes_hi[20]), 8), SHR(XOR(D_lo, lanes_lo[20]), 24)), XOR(SHL(XOR(D_lo, lanes_lo[5]), 27), SHR(XOR(D_hi, lanes_hi[5]), 5)), XOR(SHL(XOR(D_hi, lanes_hi[5]), 27), SHR(XOR(D_lo, lanes_lo[5]), 5)), XOR(SHR(XOR(D_lo, lanes_lo[15]), 25), SHL(XOR(D_hi, lanes_hi[15]), 7)), XOR(SHR(XOR(D_hi, lanes_hi[15]), 25), SHL(XOR(D_lo, lanes_lo[15]), 7)) L, H = XOR(D_lo, lanes_lo[10]), XOR(D_hi, lanes_hi[10]) lanes_lo[10], lanes_hi[10] = XOR(SHL(L, 20), SHR(H, 12)), XOR(SHL(H, 20), SHR(L, 12)) D_lo = XOR(lanes_lo[30], SHL(lanes_lo[27], 1), SHR(lanes_hi[27], 31)) D_hi = XOR(lanes_hi[30], SHL(lanes_hi[27], 1), SHR(lanes_lo[27], 31)) lanes_lo[6], lanes_hi[6], lanes_lo[11], lanes_hi[11], lanes_lo[16], lanes_hi[16], lanes_lo[21], lanes_hi[21] = XOR(SHL(XOR(D_lo, lanes_lo[11]), 3), SHR(XOR(D_hi, lanes_hi[11]), 29)), XOR(SHL(XOR(D_hi, lanes_hi[11]), 3), SHR(XOR(D_lo, lanes_lo[11]), 29)), XOR(SHL(XOR(D_lo, lanes_lo[21]), 18), SHR(XOR(D_hi, lanes_hi[21]), 14)), XOR(SHL(XOR(D_hi, lanes_hi[21]), 18), SHR(XOR(D_lo, lanes_lo[21]), 14)), XOR(SHR(XOR(D_lo, lanes_lo[6]), 28), SHL(XOR(D_hi, lanes_hi[6]), 4)), XOR(SHR(XOR(D_hi, lanes_hi[6]), 28), SHL(XOR(D_lo, lanes_lo[6]), 4)), XOR(SHR(XOR(D_lo, lanes_lo[16]), 23), SHL(XOR(D_hi, lanes_hi[16]), 9)), XOR(SHR(XOR(D_hi, lanes_hi[16]), 23), SHL(XOR(D_lo, lanes_lo[16]), 9)) lanes_lo[1], lanes_hi[1] = XOR(D_lo, lanes_lo[1]), XOR(D_hi, lanes_hi[1]) lanes_lo[1], lanes_lo[2], lanes_lo[3], lanes_lo[4], lanes_lo[5] = XOR(lanes_lo[1], AND(NOT(lanes_lo[2]), lanes_lo[3]), RC_lo[round_idx]), XOR(lanes_lo[2], AND(NOT(lanes_lo[3]), lanes_lo[4])), XOR(lanes_lo[3], AND(NOT(lanes_lo[4]), lanes_lo[5])), XOR(lanes_lo[4], AND(NOT(lanes_lo[5]), lanes_lo[1])), XOR(lanes_lo[5], AND(NOT(lanes_lo[1]), lanes_lo[2])) lanes_lo[6], lanes_lo[7], lanes_lo[8], lanes_lo[9], lanes_lo[10] = XOR(lanes_lo[9], AND(NOT(lanes_lo[10]), lanes_lo[6])), XOR(lanes_lo[10], AND(NOT(lanes_lo[6]), lanes_lo[7])), XOR(lanes_lo[6], AND(NOT(lanes_lo[7]), lanes_lo[8])), XOR(lanes_lo[7], AND(NOT(lanes_lo[8]), lanes_lo[9])), XOR(lanes_lo[8], AND(NOT(lanes_lo[9]), lanes_lo[10])) lanes_lo[11], lanes_lo[12], lanes_lo[13], lanes_lo[14], lanes_lo[15] = XOR(lanes_lo[12], AND(NOT(lanes_lo[13]), lanes_lo[14])), XOR(lanes_lo[13], AND(NOT(lanes_lo[14]), lanes_lo[15])), XOR(lanes_lo[14], AND(NOT(lanes_lo[15]), lanes_lo[11])), XOR(lanes_lo[15], AND(NOT(lanes_lo[11]), lanes_lo[12])), XOR(lanes_lo[11], AND(NOT(lanes_lo[12]), lanes_lo[13])) lanes_lo[16], lanes_lo[17], lanes_lo[18], lanes_lo[19], lanes_lo[20] = XOR(lanes_lo[20], AND(NOT(lanes_lo[16]), lanes_lo[17])), XOR(lanes_lo[16], AND(NOT(lanes_lo[17]), lanes_lo[18])), XOR(lanes_lo[17], AND(NOT(lanes_lo[18]), lanes_lo[19])), XOR(lanes_lo[18], AND(NOT(lanes_lo[19]), lanes_lo[20])), XOR(lanes_lo[19], AND(NOT(lanes_lo[20]), lanes_lo[16])) lanes_lo[21], lanes_lo[22], lanes_lo[23], lanes_lo[24], lanes_lo[25] = XOR(lanes_lo[23], AND(NOT(lanes_lo[24]), lanes_lo[25])), XOR(lanes_lo[24], AND(NOT(lanes_lo[25]), lanes_lo[21])), XOR(lanes_lo[25], AND(NOT(lanes_lo[21]), lanes_lo[22])), XOR(lanes_lo[21], AND(NOT(lanes_lo[22]), lanes_lo[23])), XOR(lanes_lo[22], AND(NOT(lanes_lo[23]), lanes_lo[24])) lanes_hi[1], lanes_hi[2], lanes_hi[3], lanes_hi[4], lanes_hi[5] = XOR(lanes_hi[1], AND(NOT(lanes_hi[2]), lanes_hi[3]), RC_hi[round_idx]), XOR(lanes_hi[2], AND(NOT(lanes_hi[3]), lanes_hi[4])), XOR(lanes_hi[3], AND(NOT(lanes_hi[4]), lanes_hi[5])), XOR(lanes_hi[4], AND(NOT(lanes_hi[5]), lanes_hi[1])), XOR(lanes_hi[5], AND(NOT(lanes_hi[1]), lanes_hi[2])) lanes_hi[6], lanes_hi[7], lanes_hi[8], lanes_hi[9], lanes_hi[10] = XOR(lanes_hi[9], AND(NOT(lanes_hi[10]), lanes_hi[6])), XOR(lanes_hi[10], AND(NOT(lanes_hi[6]), lanes_hi[7])), XOR(lanes_hi[6], AND(NOT(lanes_hi[7]), lanes_hi[8])), XOR(lanes_hi[7], AND(NOT(lanes_hi[8]), lanes_hi[9])), XOR(lanes_hi[8], AND(NOT(lanes_hi[9]), lanes_hi[10])) lanes_hi[11], lanes_hi[12], lanes_hi[13], lanes_hi[14], lanes_hi[15] = XOR(lanes_hi[12], AND(NOT(lanes_hi[13]), lanes_hi[14])), XOR(lanes_hi[13], AND(NOT(lanes_hi[14]), lanes_hi[15])), XOR(lanes_hi[14], AND(NOT(lanes_hi[15]), lanes_hi[11])), XOR(lanes_hi[15], AND(NOT(lanes_hi[11]), lanes_hi[12])), XOR(lanes_hi[11], AND(NOT(lanes_hi[12]), lanes_hi[13])) lanes_hi[16], lanes_hi[17], lanes_hi[18], lanes_hi[19], lanes_hi[20] = XOR(lanes_hi[20], AND(NOT(lanes_hi[16]), lanes_hi[17])), XOR(lanes_hi[16], AND(NOT(lanes_hi[17]), lanes_hi[18])), XOR(lanes_hi[17], AND(NOT(lanes_hi[18]), lanes_hi[19])), XOR(lanes_hi[18], AND(NOT(lanes_hi[19]), lanes_hi[20])), XOR(lanes_hi[19], AND(NOT(lanes_hi[20]), lanes_hi[16])) lanes_hi[21], lanes_hi[22], lanes_hi[23], lanes_hi[24], lanes_hi[25] = XOR(lanes_hi[23], AND(NOT(lanes_hi[24]), lanes_hi[25])), XOR(lanes_hi[24], AND(NOT(lanes_hi[25]), lanes_hi[21])), XOR(lanes_hi[25], AND(NOT(lanes_hi[21]), lanes_hi[22])), XOR(lanes_hi[21], AND(NOT(lanes_hi[22]), lanes_hi[23])), XOR(lanes_hi[22], AND(NOT(lanes_hi[23]), lanes_hi[24])) end end end end if branch == "LJ" then -- SHA256 implementation for "LuaJIT without FFI" branch function sha256_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W, K = common_W, sha2_K_hi for pos = offs, offs + size - 1, 64 do for j = 1, 16 do pos = pos + 4 local a, b, c, d = byte(str, pos - 3, pos) W[j] = OR(SHL(a, 24), SHL(b, 16), SHL(c, 8), d) end for j = 17, 64 do local a, b = W[j-15], W[j-2] W[j] = NORM( NORM( XOR(ROR(a, 7), ROL(a, 14), SHR(a, 3)) + XOR(ROL(b, 15), ROL(b, 13), SHR(b, 10)) ) + NORM( W[j-7] + W[j-16] ) ) end local a, b, c, d, e, f, g, h = H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8] for j = 1, 64, 8 do -- Thanks to Peter Cawley for this workaround (unroll the loop to avoid "PHI shuffling too complex" due to PHIs overlap) local z = NORM( XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + XOR(g, AND(e, XOR(f, g))) + (K[j] + W[j] + h) ) h, g, f, e = g, f, e, NORM(d + z) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + XOR(g, AND(e, XOR(f, g))) + (K[j+1] + W[j+1] + h) ) h, g, f, e = g, f, e, NORM(d + z) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + XOR(g, AND(e, XOR(f, g))) + (K[j+2] + W[j+2] + h) ) h, g, f, e = g, f, e, NORM(d + z) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + XOR(g, AND(e, XOR(f, g))) + (K[j+3] + W[j+3] + h) ) h, g, f, e = g, f, e, NORM(d + z) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + XOR(g, AND(e, XOR(f, g))) + (K[j+4] + W[j+4] + h) ) h, g, f, e = g, f, e, NORM(d + z) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + XOR(g, AND(e, XOR(f, g))) + (K[j+5] + W[j+5] + h) ) h, g, f, e = g, f, e, NORM(d + z) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + XOR(g, AND(e, XOR(f, g))) + (K[j+6] + W[j+6] + h) ) h, g, f, e = g, f, e, NORM(d + z) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) z = NORM( XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + XOR(g, AND(e, XOR(f, g))) + (K[j+7] + W[j+7] + h) ) h, g, f, e = g, f, e, NORM(d + z) d, c, b, a = c, b, a, NORM( XOR(AND(a, XOR(b, c)), AND(b, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) + z ) end H[1], H[2], H[3], H[4] = NORM(a + H[1]), NORM(b + H[2]), NORM(c + H[3]), NORM(d + H[4]) H[5], H[6], H[7], H[8] = NORM(e + H[5]), NORM(f + H[6]), NORM(g + H[7]), NORM(h + H[8]) end end local function ADD64_4(a_lo, a_hi, b_lo, b_hi, c_lo, c_hi, d_lo, d_hi) local sum_lo = a_lo % 2^32 + b_lo % 2^32 + c_lo % 2^32 + d_lo % 2^32 local sum_hi = a_hi + b_hi + c_hi + d_hi local result_lo = NORM( sum_lo ) local result_hi = NORM( sum_hi + floor(sum_lo / 2^32) ) return result_lo, result_hi end if LuaJIT_arch == "x86" then -- Special trick is required to avoid "PHI shuffling too complex" on x86 platform -- SHA512 implementation for "LuaJIT x86 without FFI" branch function sha512_feed_128(H_lo, H_hi, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 128 -- W1_hi, W1_lo, W2_hi, W2_lo, ... Wk_hi = W[2*k-1], Wk_lo = W[2*k] local W, K_lo, K_hi = common_W, sha2_K_lo, sha2_K_hi for pos = offs, offs + size - 1, 128 do for j = 1, 16*2 do pos = pos + 4 local a, b, c, d = byte(str, pos - 3, pos) W[j] = OR(SHL(a, 24), SHL(b, 16), SHL(c, 8), d) end for jj = 17*2, 80*2, 2 do local a_lo, a_hi = W[jj-30], W[jj-31] local t_lo = XOR(OR(SHR(a_lo, 1), SHL(a_hi, 31)), OR(SHR(a_lo, 8), SHL(a_hi, 24)), OR(SHR(a_lo, 7), SHL(a_hi, 25))) local t_hi = XOR(OR(SHR(a_hi, 1), SHL(a_lo, 31)), OR(SHR(a_hi, 8), SHL(a_lo, 24)), SHR(a_hi, 7)) local b_lo, b_hi = W[jj-4], W[jj-5] local u_lo = XOR(OR(SHR(b_lo, 19), SHL(b_hi, 13)), OR(SHL(b_lo, 3), SHR(b_hi, 29)), OR(SHR(b_lo, 6), SHL(b_hi, 26))) local u_hi = XOR(OR(SHR(b_hi, 19), SHL(b_lo, 13)), OR(SHL(b_hi, 3), SHR(b_lo, 29)), SHR(b_hi, 6)) W[jj], W[jj-1] = ADD64_4(t_lo, t_hi, u_lo, u_hi, W[jj-14], W[jj-15], W[jj-32], W[jj-33]) end local a_lo, b_lo, c_lo, d_lo, e_lo, f_lo, g_lo, h_lo = H_lo[1], H_lo[2], H_lo[3], H_lo[4], H_lo[5], H_lo[6], H_lo[7], H_lo[8] local a_hi, b_hi, c_hi, d_hi, e_hi, f_hi, g_hi, h_hi = H_hi[1], H_hi[2], H_hi[3], H_hi[4], H_hi[5], H_hi[6], H_hi[7], H_hi[8] local zero = 0 for j = 1, 80 do local t_lo = XOR(g_lo, AND(e_lo, XOR(f_lo, g_lo))) local t_hi = XOR(g_hi, AND(e_hi, XOR(f_hi, g_hi))) local u_lo = XOR(OR(SHR(e_lo, 14), SHL(e_hi, 18)), OR(SHR(e_lo, 18), SHL(e_hi, 14)), OR(SHL(e_lo, 23), SHR(e_hi, 9))) local u_hi = XOR(OR(SHR(e_hi, 14), SHL(e_lo, 18)), OR(SHR(e_hi, 18), SHL(e_lo, 14)), OR(SHL(e_hi, 23), SHR(e_lo, 9))) local sum_lo = u_lo % 2^32 + t_lo % 2^32 + h_lo % 2^32 + K_lo[j] + W[2*j] % 2^32 local z_lo, z_hi = NORM( sum_lo ), NORM( u_hi + t_hi + h_hi + K_hi[j] + W[2*j-1] + floor(sum_lo / 2^32) ) zero = zero + zero -- this thick is needed to avoid "PHI shuffling too complex" due to PHIs overlap h_lo, h_hi, g_lo, g_hi, f_lo, f_hi = OR(zero, g_lo), OR(zero, g_hi), OR(zero, f_lo), OR(zero, f_hi), OR(zero, e_lo), OR(zero, e_hi) local sum_lo = z_lo % 2^32 + d_lo % 2^32 e_lo, e_hi = NORM( sum_lo ), NORM( z_hi + d_hi + floor(sum_lo / 2^32) ) d_lo, d_hi, c_lo, c_hi, b_lo, b_hi = OR(zero, c_lo), OR(zero, c_hi), OR(zero, b_lo), OR(zero, b_hi), OR(zero, a_lo), OR(zero, a_hi) u_lo = XOR(OR(SHR(b_lo, 28), SHL(b_hi, 4)), OR(SHL(b_lo, 30), SHR(b_hi, 2)), OR(SHL(b_lo, 25), SHR(b_hi, 7))) u_hi = XOR(OR(SHR(b_hi, 28), SHL(b_lo, 4)), OR(SHL(b_hi, 30), SHR(b_lo, 2)), OR(SHL(b_hi, 25), SHR(b_lo, 7))) t_lo = OR(AND(d_lo, c_lo), AND(b_lo, XOR(d_lo, c_lo))) t_hi = OR(AND(d_hi, c_hi), AND(b_hi, XOR(d_hi, c_hi))) local sum_lo = z_lo % 2^32 + t_lo % 2^32 + u_lo % 2^32 a_lo, a_hi = NORM( sum_lo ), NORM( z_hi + t_hi + u_hi + floor(sum_lo / 2^32) ) end H_lo[1], H_hi[1] = ADD64_4(H_lo[1], H_hi[1], a_lo, a_hi, 0, 0, 0, 0) H_lo[2], H_hi[2] = ADD64_4(H_lo[2], H_hi[2], b_lo, b_hi, 0, 0, 0, 0) H_lo[3], H_hi[3] = ADD64_4(H_lo[3], H_hi[3], c_lo, c_hi, 0, 0, 0, 0) H_lo[4], H_hi[4] = ADD64_4(H_lo[4], H_hi[4], d_lo, d_hi, 0, 0, 0, 0) H_lo[5], H_hi[5] = ADD64_4(H_lo[5], H_hi[5], e_lo, e_hi, 0, 0, 0, 0) H_lo[6], H_hi[6] = ADD64_4(H_lo[6], H_hi[6], f_lo, f_hi, 0, 0, 0, 0) H_lo[7], H_hi[7] = ADD64_4(H_lo[7], H_hi[7], g_lo, g_hi, 0, 0, 0, 0) H_lo[8], H_hi[8] = ADD64_4(H_lo[8], H_hi[8], h_lo, h_hi, 0, 0, 0, 0) end end else -- all platforms except x86 -- SHA512 implementation for "LuaJIT non-x86 without FFI" branch function sha512_feed_128(H_lo, H_hi, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 128 -- W1_hi, W1_lo, W2_hi, W2_lo, ... Wk_hi = W[2*k-1], Wk_lo = W[2*k] local W, K_lo, K_hi = common_W, sha2_K_lo, sha2_K_hi for pos = offs, offs + size - 1, 128 do for j = 1, 16*2 do pos = pos + 4 local a, b, c, d = byte(str, pos - 3, pos) W[j] = OR(SHL(a, 24), SHL(b, 16), SHL(c, 8), d) end for jj = 17*2, 80*2, 2 do local a_lo, a_hi = W[jj-30], W[jj-31] local t_lo = XOR(OR(SHR(a_lo, 1), SHL(a_hi, 31)), OR(SHR(a_lo, 8), SHL(a_hi, 24)), OR(SHR(a_lo, 7), SHL(a_hi, 25))) local t_hi = XOR(OR(SHR(a_hi, 1), SHL(a_lo, 31)), OR(SHR(a_hi, 8), SHL(a_lo, 24)), SHR(a_hi, 7)) local b_lo, b_hi = W[jj-4], W[jj-5] local u_lo = XOR(OR(SHR(b_lo, 19), SHL(b_hi, 13)), OR(SHL(b_lo, 3), SHR(b_hi, 29)), OR(SHR(b_lo, 6), SHL(b_hi, 26))) local u_hi = XOR(OR(SHR(b_hi, 19), SHL(b_lo, 13)), OR(SHL(b_hi, 3), SHR(b_lo, 29)), SHR(b_hi, 6)) W[jj], W[jj-1] = ADD64_4(t_lo, t_hi, u_lo, u_hi, W[jj-14], W[jj-15], W[jj-32], W[jj-33]) end local a_lo, b_lo, c_lo, d_lo, e_lo, f_lo, g_lo, h_lo = H_lo[1], H_lo[2], H_lo[3], H_lo[4], H_lo[5], H_lo[6], H_lo[7], H_lo[8] local a_hi, b_hi, c_hi, d_hi, e_hi, f_hi, g_hi, h_hi = H_hi[1], H_hi[2], H_hi[3], H_hi[4], H_hi[5], H_hi[6], H_hi[7], H_hi[8] for j = 1, 80 do local t_lo = XOR(g_lo, AND(e_lo, XOR(f_lo, g_lo))) local t_hi = XOR(g_hi, AND(e_hi, XOR(f_hi, g_hi))) local u_lo = XOR(OR(SHR(e_lo, 14), SHL(e_hi, 18)), OR(SHR(e_lo, 18), SHL(e_hi, 14)), OR(SHL(e_lo, 23), SHR(e_hi, 9))) local u_hi = XOR(OR(SHR(e_hi, 14), SHL(e_lo, 18)), OR(SHR(e_hi, 18), SHL(e_lo, 14)), OR(SHL(e_hi, 23), SHR(e_lo, 9))) local sum_lo = u_lo % 2^32 + t_lo % 2^32 + h_lo % 2^32 + K_lo[j] + W[2*j] % 2^32 local z_lo, z_hi = NORM( sum_lo ), NORM( u_hi + t_hi + h_hi + K_hi[j] + W[2*j-1] + floor(sum_lo / 2^32) ) h_lo, h_hi, g_lo, g_hi, f_lo, f_hi = g_lo, g_hi, f_lo, f_hi, e_lo, e_hi local sum_lo = z_lo % 2^32 + d_lo % 2^32 e_lo, e_hi = NORM( sum_lo ), NORM( z_hi + d_hi + floor(sum_lo / 2^32) ) d_lo, d_hi, c_lo, c_hi, b_lo, b_hi = c_lo, c_hi, b_lo, b_hi, a_lo, a_hi u_lo = XOR(OR(SHR(b_lo, 28), SHL(b_hi, 4)), OR(SHL(b_lo, 30), SHR(b_hi, 2)), OR(SHL(b_lo, 25), SHR(b_hi, 7))) u_hi = XOR(OR(SHR(b_hi, 28), SHL(b_lo, 4)), OR(SHL(b_hi, 30), SHR(b_lo, 2)), OR(SHL(b_hi, 25), SHR(b_lo, 7))) t_lo = OR(AND(d_lo, c_lo), AND(b_lo, XOR(d_lo, c_lo))) t_hi = OR(AND(d_hi, c_hi), AND(b_hi, XOR(d_hi, c_hi))) local sum_lo = z_lo % 2^32 + u_lo % 2^32 + t_lo % 2^32 a_lo, a_hi = NORM( sum_lo ), NORM( z_hi + u_hi + t_hi + floor(sum_lo / 2^32) ) end H_lo[1], H_hi[1] = ADD64_4(H_lo[1], H_hi[1], a_lo, a_hi, 0, 0, 0, 0) H_lo[2], H_hi[2] = ADD64_4(H_lo[2], H_hi[2], b_lo, b_hi, 0, 0, 0, 0) H_lo[3], H_hi[3] = ADD64_4(H_lo[3], H_hi[3], c_lo, c_hi, 0, 0, 0, 0) H_lo[4], H_hi[4] = ADD64_4(H_lo[4], H_hi[4], d_lo, d_hi, 0, 0, 0, 0) H_lo[5], H_hi[5] = ADD64_4(H_lo[5], H_hi[5], e_lo, e_hi, 0, 0, 0, 0) H_lo[6], H_hi[6] = ADD64_4(H_lo[6], H_hi[6], f_lo, f_hi, 0, 0, 0, 0) H_lo[7], H_hi[7] = ADD64_4(H_lo[7], H_hi[7], g_lo, g_hi, 0, 0, 0, 0) H_lo[8], H_hi[8] = ADD64_4(H_lo[8], H_hi[8], h_lo, h_hi, 0, 0, 0, 0) end end end -- MD5 implementation for "LuaJIT without FFI" branch function md5_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W, K = common_W, md5_K for pos = offs, offs + size - 1, 64 do for j = 1, 16 do pos = pos + 4 local a, b, c, d = byte(str, pos - 3, pos) W[j] = OR(SHL(d, 24), SHL(c, 16), SHL(b, 8), a) end local a, b, c, d = H[1], H[2], H[3], H[4] for j = 1, 16, 4 do a, d, c, b = d, c, b, NORM(ROL(XOR(d, AND(b, XOR(c, d))) + (K[j ] + W[j ] + a), 7) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(d, AND(b, XOR(c, d))) + (K[j+1] + W[j+1] + a), 12) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(d, AND(b, XOR(c, d))) + (K[j+2] + W[j+2] + a), 17) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(d, AND(b, XOR(c, d))) + (K[j+3] + W[j+3] + a), 22) + b) end for j = 17, 32, 4 do local g = 5*j-4 a, d, c, b = d, c, b, NORM(ROL(XOR(c, AND(d, XOR(b, c))) + (K[j ] + W[AND(g , 15) + 1] + a), 5) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(c, AND(d, XOR(b, c))) + (K[j+1] + W[AND(g + 5, 15) + 1] + a), 9) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(c, AND(d, XOR(b, c))) + (K[j+2] + W[AND(g + 10, 15) + 1] + a), 14) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(c, AND(d, XOR(b, c))) + (K[j+3] + W[AND(g - 1, 15) + 1] + a), 20) + b) end for j = 33, 48, 4 do local g = 3*j+2 a, d, c, b = d, c, b, NORM(ROL(XOR(b, c, d) + (K[j ] + W[AND(g , 15) + 1] + a), 4) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(b, c, d) + (K[j+1] + W[AND(g + 3, 15) + 1] + a), 11) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(b, c, d) + (K[j+2] + W[AND(g + 6, 15) + 1] + a), 16) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(b, c, d) + (K[j+3] + W[AND(g - 7, 15) + 1] + a), 23) + b) end for j = 49, 64, 4 do local g = j*7 a, d, c, b = d, c, b, NORM(ROL(XOR(c, OR(b, NOT(d))) + (K[j ] + W[AND(g - 7, 15) + 1] + a), 6) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(c, OR(b, NOT(d))) + (K[j+1] + W[AND(g , 15) + 1] + a), 10) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(c, OR(b, NOT(d))) + (K[j+2] + W[AND(g + 7, 15) + 1] + a), 15) + b) a, d, c, b = d, c, b, NORM(ROL(XOR(c, OR(b, NOT(d))) + (K[j+3] + W[AND(g - 2, 15) + 1] + a), 21) + b) end H[1], H[2], H[3], H[4] = NORM(a + H[1]), NORM(b + H[2]), NORM(c + H[3]), NORM(d + H[4]) end end -- SHA-1 implementation for "LuaJIT without FFI" branch function sha1_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W = common_W for pos = offs, offs + size - 1, 64 do for j = 1, 16 do pos = pos + 4 local a, b, c, d = byte(str, pos - 3, pos) W[j] = OR(SHL(a, 24), SHL(b, 16), SHL(c, 8), d) end for j = 17, 80 do W[j] = ROL(XOR(W[j-3], W[j-8], W[j-14], W[j-16]), 1) end local a, b, c, d, e = H[1], H[2], H[3], H[4], H[5] for j = 1, 20, 5 do e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(d, AND(b, XOR(d, c))) + (W[j] + 0x5A827999 + e)) -- constant = floor(2^30 * sqrt(2)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(d, AND(b, XOR(d, c))) + (W[j+1] + 0x5A827999 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(d, AND(b, XOR(d, c))) + (W[j+2] + 0x5A827999 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(d, AND(b, XOR(d, c))) + (W[j+3] + 0x5A827999 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(d, AND(b, XOR(d, c))) + (W[j+4] + 0x5A827999 + e)) end for j = 21, 40, 5 do e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j] + 0x6ED9EBA1 + e)) -- 2^30 * sqrt(3) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+1] + 0x6ED9EBA1 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+2] + 0x6ED9EBA1 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+3] + 0x6ED9EBA1 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+4] + 0x6ED9EBA1 + e)) end for j = 41, 60, 5 do e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(AND(d, XOR(b, c)), AND(b, c)) + (W[j] + 0x8F1BBCDC + e)) -- 2^30 * sqrt(5) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(AND(d, XOR(b, c)), AND(b, c)) + (W[j+1] + 0x8F1BBCDC + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(AND(d, XOR(b, c)), AND(b, c)) + (W[j+2] + 0x8F1BBCDC + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(AND(d, XOR(b, c)), AND(b, c)) + (W[j+3] + 0x8F1BBCDC + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(AND(d, XOR(b, c)), AND(b, c)) + (W[j+4] + 0x8F1BBCDC + e)) end for j = 61, 80, 5 do e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j] + 0xCA62C1D6 + e)) -- 2^30 * sqrt(10) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+1] + 0xCA62C1D6 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+2] + 0xCA62C1D6 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+3] + 0xCA62C1D6 + e)) e, d, c, b, a = d, c, ROR(b, 2), a, NORM(ROL(a, 5) + XOR(b, c, d) + (W[j+4] + 0xCA62C1D6 + e)) end H[1], H[2], H[3], H[4], H[5] = NORM(a + H[1]), NORM(b + H[2]), NORM(c + H[3]), NORM(d + H[4]), NORM(e + H[5]) end end end if branch == "INT64" then -- implementation for Lua 5.3/5.4 hi_factor = 4294967296 hi_factor_keccak = 4294967296 lanes_index_base = 1 HEX64, XOR64A5, XOR_BYTE, sha256_feed_64, sha512_feed_128, md5_feed_64, sha1_feed_64, keccak_feed = load[[ local md5_next_shift, md5_K, sha2_K_lo, sha2_K_hi, build_keccak_format, sha3_RC_lo = ... local string_format, string_unpack = string.format, string.unpack local function HEX64(x) return string_format("%016x", x) end local function XOR64A5(x) return x ~ 0xa5a5a5a5a5a5a5a5 end local function XOR_BYTE(x, y) return x ~ y end local common_W = {} local function sha256_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W, K = common_W, sha2_K_hi local h1, h2, h3, h4, h5, h6, h7, h8 = H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8] for pos = offs + 1, offs + size, 64 do W[1], W[2], W[3], W[4], W[5], W[6], W[7], W[8], W[9], W[10], W[11], W[12], W[13], W[14], W[15], W[16] = string_unpack(">I4I4I4I4I4I4I4I4I4I4I4I4I4I4I4I4", str, pos) for j = 17, 64 do local a = W[j-15] a = a<<32 | a local b = W[j-2] b = b<<32 | b W[j] = (a>>7 ~ a>>18 ~ a>>35) + (b>>17 ~ b>>19 ~ b>>42) + W[j-7] + W[j-16] & (1<<32)-1 end local a, b, c, d, e, f, g, h = h1, h2, h3, h4, h5, h6, h7, h8 for j = 1, 64 do e = e<<32 | e & (1<<32)-1 local z = (e>>6 ~ e>>11 ~ e>>25) + (g ~ e & (f ~ g)) + h + K[j] + W[j] h = g g = f f = e e = z + d d = c c = b b = a a = a<<32 | a & (1<<32)-1 a = z + ((a ~ c) & d ~ a & c) + (a>>2 ~ a>>13 ~ a>>22) end h1 = a + h1 h2 = b + h2 h3 = c + h3 h4 = d + h4 h5 = e + h5 h6 = f + h6 h7 = g + h7 h8 = h + h8 end H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8] = h1, h2, h3, h4, h5, h6, h7, h8 end local function sha512_feed_128(H, _, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 128 local W, K = common_W, sha2_K_lo local h1, h2, h3, h4, h5, h6, h7, h8 = H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8] for pos = offs + 1, offs + size, 128 do W[1], W[2], W[3], W[4], W[5], W[6], W[7], W[8], W[9], W[10], W[11], W[12], W[13], W[14], W[15], W[16] = string_unpack(">i8i8i8i8i8i8i8i8i8i8i8i8i8i8i8i8", str, pos) for j = 17, 80 do local a = W[j-15] local b = W[j-2] W[j] = (a >> 1 ~ a >> 7 ~ a >> 8 ~ a << 56 ~ a << 63) + (b >> 6 ~ b >> 19 ~ b >> 61 ~ b << 3 ~ b << 45) + W[j-7] + W[j-16] end local a, b, c, d, e, f, g, h = h1, h2, h3, h4, h5, h6, h7, h8 for j = 1, 80 do local z = (e >> 14 ~ e >> 18 ~ e >> 41 ~ e << 23 ~ e << 46 ~ e << 50) + (g ~ e & (f ~ g)) + h + K[j] + W[j] h = g g = f f = e e = z + d d = c c = b b = a a = z + ((a ~ c) & d ~ a & c) + (a >> 28 ~ a >> 34 ~ a >> 39 ~ a << 25 ~ a << 30 ~ a << 36) end h1 = a + h1 h2 = b + h2 h3 = c + h3 h4 = d + h4 h5 = e + h5 h6 = f + h6 h7 = g + h7 h8 = h + h8 end H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8] = h1, h2, h3, h4, h5, h6, h7, h8 end local function md5_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W, K, md5_next_shift = common_W, md5_K, md5_next_shift local h1, h2, h3, h4 = H[1], H[2], H[3], H[4] for pos = offs + 1, offs + size, 64 do W[1], W[2], W[3], W[4], W[5], W[6], W[7], W[8], W[9], W[10], W[11], W[12], W[13], W[14], W[15], W[16] = string_unpack("<I4I4I4I4I4I4I4I4I4I4I4I4I4I4I4I4", str, pos) local a, b, c, d = h1, h2, h3, h4 local s = 32-7 for j = 1, 16 do local F = (d ~ b & (c ~ d)) + a + K[j] + W[j] a = d d = c c = b b = ((F<<32 | F & (1<<32)-1) >> s) + b s = md5_next_shift[s] end s = 32-5 for j = 17, 32 do local F = (c ~ d & (b ~ c)) + a + K[j] + W[(5*j-4 & 15) + 1] a = d d = c c = b b = ((F<<32 | F & (1<<32)-1) >> s) + b s = md5_next_shift[s] end s = 32-4 for j = 33, 48 do local F = (b ~ c ~ d) + a + K[j] + W[(3*j+2 & 15) + 1] a = d d = c c = b b = ((F<<32 | F & (1<<32)-1) >> s) + b s = md5_next_shift[s] end s = 32-6 for j = 49, 64 do local F = (c ~ (b | ~d)) + a + K[j] + W[(j*7-7 & 15) + 1] a = d d = c c = b b = ((F<<32 | F & (1<<32)-1) >> s) + b s = md5_next_shift[s] end h1 = a + h1 h2 = b + h2 h3 = c + h3 h4 = d + h4 end H[1], H[2], H[3], H[4] = h1, h2, h3, h4 end local function sha1_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W = common_W local h1, h2, h3, h4, h5 = H[1], H[2], H[3], H[4], H[5] for pos = offs + 1, offs + size, 64 do W[1], W[2], W[3], W[4], W[5], W[6], W[7], W[8], W[9], W[10], W[11], W[12], W[13], W[14], W[15], W[16] = string_unpack(">I4I4I4I4I4I4I4I4I4I4I4I4I4I4I4I4", str, pos) for j = 17, 80 do local a = W[j-3] ~ W[j-8] ~ W[j-14] ~ W[j-16] W[j] = (a<<32 | a) << 1 >> 32 end local a, b, c, d, e = h1, h2, h3, h4, h5 for j = 1, 20 do local z = ((a<<32 | a & (1<<32)-1) >> 27) + (d ~ b & (c ~ d)) + 0x5A827999 + W[j] + e -- constant = floor(2^30 * sqrt(2)) e = d d = c c = (b<<32 | b & (1<<32)-1) >> 2 b = a a = z end for j = 21, 40 do local z = ((a<<32 | a & (1<<32)-1) >> 27) + (b ~ c ~ d) + 0x6ED9EBA1 + W[j] + e -- 2^30 * sqrt(3) e = d d = c c = (b<<32 | b & (1<<32)-1) >> 2 b = a a = z end for j = 41, 60 do local z = ((a<<32 | a & (1<<32)-1) >> 27) + ((b ~ c) & d ~ b & c) + 0x8F1BBCDC + W[j] + e -- 2^30 * sqrt(5) e = d d = c c = (b<<32 | b & (1<<32)-1) >> 2 b = a a = z end for j = 61, 80 do local z = ((a<<32 | a & (1<<32)-1) >> 27) + (b ~ c ~ d) + 0xCA62C1D6 + W[j] + e -- 2^30 * sqrt(10) e = d d = c c = (b<<32 | b & (1<<32)-1) >> 2 b = a a = z end h1 = a + h1 h2 = b + h2 h3 = c + h3 h4 = d + h4 h5 = e + h5 end H[1], H[2], H[3], H[4], H[5] = h1, h2, h3, h4, h5 end local keccak_format_i8 = build_keccak_format("i8") local function keccak_feed(lanes, _, str, offs, size, block_size_in_bytes) -- offs >= 0, size >= 0, size is multiple of block_size_in_bytes, block_size_in_bytes is positive multiple of 8 local RC = sha3_RC_lo local qwords_qty = block_size_in_bytes / 8 local keccak_format = keccak_format_i8[qwords_qty] for pos = offs + 1, offs + size, block_size_in_bytes do local qwords_from_message = {string_unpack(keccak_format, str, pos)} for j = 1, qwords_qty do lanes[j] = lanes[j] ~ qwords_from_message[j] end local L01, L02, L03, L04, L05, L06, L07, L08, L09, L10, L11, L12, L13, L14, L15, L16, L17, L18, L19, L20, L21, L22, L23, L24, L25 = lanes[1], lanes[2], lanes[3], lanes[4], lanes[5], lanes[6], lanes[7], lanes[8], lanes[9], lanes[10], lanes[11], lanes[12], lanes[13], lanes[14], lanes[15], lanes[16], lanes[17], lanes[18], lanes[19], lanes[20], lanes[21], lanes[22], lanes[23], lanes[24], lanes[25] for round_idx = 1, 24 do local C1 = L01 ~ L06 ~ L11 ~ L16 ~ L21 local C2 = L02 ~ L07 ~ L12 ~ L17 ~ L22 local C3 = L03 ~ L08 ~ L13 ~ L18 ~ L23 local C4 = L04 ~ L09 ~ L14 ~ L19 ~ L24 local C5 = L05 ~ L10 ~ L15 ~ L20 ~ L25 local D = C1 ~ C3<<1 ~ C3>>63 local T0 = D ~ L02 local T1 = D ~ L07 local T2 = D ~ L12 local T3 = D ~ L17 local T4 = D ~ L22 L02 = T1<<44 ~ T1>>20 L07 = T3<<45 ~ T3>>19 L12 = T0<<1 ~ T0>>63 L17 = T2<<10 ~ T2>>54 L22 = T4<<2 ~ T4>>62 D = C2 ~ C4<<1 ~ C4>>63 T0 = D ~ L03 T1 = D ~ L08 T2 = D ~ L13 T3 = D ~ L18 T4 = D ~ L23 L03 = T2<<43 ~ T2>>21 L08 = T4<<61 ~ T4>>3 L13 = T1<<6 ~ T1>>58 L18 = T3<<15 ~ T3>>49 L23 = T0<<62 ~ T0>>2 D = C3 ~ C5<<1 ~ C5>>63 T0 = D ~ L04 T1 = D ~ L09 T2 = D ~ L14 T3 = D ~ L19 T4 = D ~ L24 L04 = T3<<21 ~ T3>>43 L09 = T0<<28 ~ T0>>36 L14 = T2<<25 ~ T2>>39 L19 = T4<<56 ~ T4>>8 L24 = T1<<55 ~ T1>>9 D = C4 ~ C1<<1 ~ C1>>63 T0 = D ~ L05 T1 = D ~ L10 T2 = D ~ L15 T3 = D ~ L20 T4 = D ~ L25 L05 = T4<<14 ~ T4>>50 L10 = T1<<20 ~ T1>>44 L15 = T3<<8 ~ T3>>56 L20 = T0<<27 ~ T0>>37 L25 = T2<<39 ~ T2>>25 D = C5 ~ C2<<1 ~ C2>>63 T1 = D ~ L06 T2 = D ~ L11 T3 = D ~ L16 T4 = D ~ L21 L06 = T2<<3 ~ T2>>61 L11 = T4<<18 ~ T4>>46 L16 = T1<<36 ~ T1>>28 L21 = T3<<41 ~ T3>>23 L01 = D ~ L01 L01, L02, L03, L04, L05 = L01 ~ ~L02 & L03, L02 ~ ~L03 & L04, L03 ~ ~L04 & L05, L04 ~ ~L05 & L01, L05 ~ ~L01 & L02 L06, L07, L08, L09, L10 = L09 ~ ~L10 & L06, L10 ~ ~L06 & L07, L06 ~ ~L07 & L08, L07 ~ ~L08 & L09, L08 ~ ~L09 & L10 L11, L12, L13, L14, L15 = L12 ~ ~L13 & L14, L13 ~ ~L14 & L15, L14 ~ ~L15 & L11, L15 ~ ~L11 & L12, L11 ~ ~L12 & L13 L16, L17, L18, L19, L20 = L20 ~ ~L16 & L17, L16 ~ ~L17 & L18, L17 ~ ~L18 & L19, L18 ~ ~L19 & L20, L19 ~ ~L20 & L16 L21, L22, L23, L24, L25 = L23 ~ ~L24 & L25, L24 ~ ~L25 & L21, L25 ~ ~L21 & L22, L21 ~ ~L22 & L23, L22 ~ ~L23 & L24 L01 = L01 ~ RC[round_idx] end lanes[1] = L01 lanes[2] = L02 lanes[3] = L03 lanes[4] = L04 lanes[5] = L05 lanes[6] = L06 lanes[7] = L07 lanes[8] = L08 lanes[9] = L09 lanes[10] = L10 lanes[11] = L11 lanes[12] = L12 lanes[13] = L13 lanes[14] = L14 lanes[15] = L15 lanes[16] = L16 lanes[17] = L17 lanes[18] = L18 lanes[19] = L19 lanes[20] = L20 lanes[21] = L21 lanes[22] = L22 lanes[23] = L23 lanes[24] = L24 lanes[25] = L25 end end return HEX64, XOR64A5, XOR_BYTE, sha256_feed_64, sha512_feed_128, md5_feed_64, sha1_feed_64, keccak_feed ]](md5_next_shift, md5_K, sha2_K_lo, sha2_K_hi, build_keccak_format, sha3_RC_lo) end if branch == "INT32" then -- implementation for Lua 5.3/5.4 having non-standard numbers config "int32"+"double" (built with LUA_INT_TYPE=LUA_INT_INT) K_lo_modulo = 2^32 function HEX(x) -- returns string of 8 lowercase hexadecimal digits return string_format("%08x", x) end XOR32A5, XOR_BYTE, sha256_feed_64, sha512_feed_128, md5_feed_64, sha1_feed_64, keccak_feed = load[[ local md5_next_shift, md5_K, sha2_K_lo, sha2_K_hi, build_keccak_format, sha3_RC_lo, sha3_RC_hi = ... local string_unpack, floor = string.unpack, math.floor local function XOR32A5(x) return x ~ 0xA5A5A5A5 end local function XOR_BYTE(x, y) return x ~ y end local common_W = {} local function sha256_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W, K = common_W, sha2_K_hi local h1, h2, h3, h4, h5, h6, h7, h8 = H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8] for pos = offs + 1, offs + size, 64 do W[1], W[2], W[3], W[4], W[5], W[6], W[7], W[8], W[9], W[10], W[11], W[12], W[13], W[14], W[15], W[16] = string_unpack(">i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4", str, pos) for j = 17, 64 do local a, b = W[j-15], W[j-2] W[j] = (a>>7 ~ a<<25 ~ a<<14 ~ a>>18 ~ a>>3) + (b<<15 ~ b>>17 ~ b<<13 ~ b>>19 ~ b>>10) + W[j-7] + W[j-16] end local a, b, c, d, e, f, g, h = h1, h2, h3, h4, h5, h6, h7, h8 for j = 1, 64 do local z = (e>>6 ~ e<<26 ~ e>>11 ~ e<<21 ~ e>>25 ~ e<<7) + (g ~ e & (f ~ g)) + h + K[j] + W[j] h = g g = f f = e e = z + d d = c c = b b = a a = z + ((a ~ c) & d ~ a & c) + (a>>2 ~ a<<30 ~ a>>13 ~ a<<19 ~ a<<10 ~ a>>22) end h1 = a + h1 h2 = b + h2 h3 = c + h3 h4 = d + h4 h5 = e + h5 h6 = f + h6 h7 = g + h7 h8 = h + h8 end H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8] = h1, h2, h3, h4, h5, h6, h7, h8 end local function sha512_feed_128(H_lo, H_hi, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 128 -- W1_hi, W1_lo, W2_hi, W2_lo, ... Wk_hi = W[2*k-1], Wk_lo = W[2*k] local floor, W, K_lo, K_hi = floor, common_W, sha2_K_lo, sha2_K_hi local h1_lo, h2_lo, h3_lo, h4_lo, h5_lo, h6_lo, h7_lo, h8_lo = H_lo[1], H_lo[2], H_lo[3], H_lo[4], H_lo[5], H_lo[6], H_lo[7], H_lo[8] local h1_hi, h2_hi, h3_hi, h4_hi, h5_hi, h6_hi, h7_hi, h8_hi = H_hi[1], H_hi[2], H_hi[3], H_hi[4], H_hi[5], H_hi[6], H_hi[7], H_hi[8] for pos = offs + 1, offs + size, 128 do W[1], W[2], W[3], W[4], W[5], W[6], W[7], W[8], W[9], W[10], W[11], W[12], W[13], W[14], W[15], W[16], W[17], W[18], W[19], W[20], W[21], W[22], W[23], W[24], W[25], W[26], W[27], W[28], W[29], W[30], W[31], W[32] = string_unpack(">i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4", str, pos) for jj = 17*2, 80*2, 2 do local a_lo, a_hi, b_lo, b_hi = W[jj-30], W[jj-31], W[jj-4], W[jj-5] local tmp = (a_lo>>1 ~ a_hi<<31 ~ a_lo>>8 ~ a_hi<<24 ~ a_lo>>7 ~ a_hi<<25) % 2^32 + (b_lo>>19 ~ b_hi<<13 ~ b_lo<<3 ~ b_hi>>29 ~ b_lo>>6 ~ b_hi<<26) % 2^32 + W[jj-14] % 2^32 + W[jj-32] % 2^32 W[jj-1] = (a_hi>>1 ~ a_lo<<31 ~ a_hi>>8 ~ a_lo<<24 ~ a_hi>>7) + (b_hi>>19 ~ b_lo<<13 ~ b_hi<<3 ~ b_lo>>29 ~ b_hi>>6) + W[jj-15] + W[jj-33] + floor(tmp / 2^32) W[jj] = 0|((tmp + 2^31) % 2^32 - 2^31) end local a_lo, b_lo, c_lo, d_lo, e_lo, f_lo, g_lo, h_lo = h1_lo, h2_lo, h3_lo, h4_lo, h5_lo, h6_lo, h7_lo, h8_lo local a_hi, b_hi, c_hi, d_hi, e_hi, f_hi, g_hi, h_hi = h1_hi, h2_hi, h3_hi, h4_hi, h5_hi, h6_hi, h7_hi, h8_hi for j = 1, 80 do local jj = 2*j local z_lo = (e_lo>>14 ~ e_hi<<18 ~ e_lo>>18 ~ e_hi<<14 ~ e_lo<<23 ~ e_hi>>9) % 2^32 + (g_lo ~ e_lo & (f_lo ~ g_lo)) % 2^32 + h_lo % 2^32 + K_lo[j] + W[jj] % 2^32 local z_hi = (e_hi>>14 ~ e_lo<<18 ~ e_hi>>18 ~ e_lo<<14 ~ e_hi<<23 ~ e_lo>>9) + (g_hi ~ e_hi & (f_hi ~ g_hi)) + h_hi + K_hi[j] + W[jj-1] + floor(z_lo / 2^32) z_lo = z_lo % 2^32 h_lo = g_lo h_hi = g_hi g_lo = f_lo g_hi = f_hi f_lo = e_lo f_hi = e_hi e_lo = z_lo + d_lo % 2^32 e_hi = z_hi + d_hi + floor(e_lo / 2^32) e_lo = 0|((e_lo + 2^31) % 2^32 - 2^31) d_lo = c_lo d_hi = c_hi c_lo = b_lo c_hi = b_hi b_lo = a_lo b_hi = a_hi z_lo = z_lo + (d_lo & c_lo ~ b_lo & (d_lo ~ c_lo)) % 2^32 + (b_lo>>28 ~ b_hi<<4 ~ b_lo<<30 ~ b_hi>>2 ~ b_lo<<25 ~ b_hi>>7) % 2^32 a_hi = z_hi + (d_hi & c_hi ~ b_hi & (d_hi ~ c_hi)) + (b_hi>>28 ~ b_lo<<4 ~ b_hi<<30 ~ b_lo>>2 ~ b_hi<<25 ~ b_lo>>7) + floor(z_lo / 2^32) a_lo = 0|((z_lo + 2^31) % 2^32 - 2^31) end a_lo = h1_lo % 2^32 + a_lo % 2^32 h1_hi = h1_hi + a_hi + floor(a_lo / 2^32) h1_lo = 0|((a_lo + 2^31) % 2^32 - 2^31) a_lo = h2_lo % 2^32 + b_lo % 2^32 h2_hi = h2_hi + b_hi + floor(a_lo / 2^32) h2_lo = 0|((a_lo + 2^31) % 2^32 - 2^31) a_lo = h3_lo % 2^32 + c_lo % 2^32 h3_hi = h3_hi + c_hi + floor(a_lo / 2^32) h3_lo = 0|((a_lo + 2^31) % 2^32 - 2^31) a_lo = h4_lo % 2^32 + d_lo % 2^32 h4_hi = h4_hi + d_hi + floor(a_lo / 2^32) h4_lo = 0|((a_lo + 2^31) % 2^32 - 2^31) a_lo = h5_lo % 2^32 + e_lo % 2^32 h5_hi = h5_hi + e_hi + floor(a_lo / 2^32) h5_lo = 0|((a_lo + 2^31) % 2^32 - 2^31) a_lo = h6_lo % 2^32 + f_lo % 2^32 h6_hi = h6_hi + f_hi + floor(a_lo / 2^32) h6_lo = 0|((a_lo + 2^31) % 2^32 - 2^31) a_lo = h7_lo % 2^32 + g_lo % 2^32 h7_hi = h7_hi + g_hi + floor(a_lo / 2^32) h7_lo = 0|((a_lo + 2^31) % 2^32 - 2^31) a_lo = h8_lo % 2^32 + h_lo % 2^32 h8_hi = h8_hi + h_hi + floor(a_lo / 2^32) h8_lo = 0|((a_lo + 2^31) % 2^32 - 2^31) end H_lo[1], H_lo[2], H_lo[3], H_lo[4], H_lo[5], H_lo[6], H_lo[7], H_lo[8] = h1_lo, h2_lo, h3_lo, h4_lo, h5_lo, h6_lo, h7_lo, h8_lo H_hi[1], H_hi[2], H_hi[3], H_hi[4], H_hi[5], H_hi[6], H_hi[7], H_hi[8] = h1_hi, h2_hi, h3_hi, h4_hi, h5_hi, h6_hi, h7_hi, h8_hi end local function md5_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W, K, md5_next_shift = common_W, md5_K, md5_next_shift local h1, h2, h3, h4 = H[1], H[2], H[3], H[4] for pos = offs + 1, offs + size, 64 do W[1], W[2], W[3], W[4], W[5], W[6], W[7], W[8], W[9], W[10], W[11], W[12], W[13], W[14], W[15], W[16] = string_unpack("<i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4", str, pos) local a, b, c, d = h1, h2, h3, h4 local s = 32-7 for j = 1, 16 do local F = (d ~ b & (c ~ d)) + a + K[j] + W[j] a = d d = c c = b b = (F << 32-s | F>>s) + b s = md5_next_shift[s] end s = 32-5 for j = 17, 32 do local F = (c ~ d & (b ~ c)) + a + K[j] + W[(5*j-4 & 15) + 1] a = d d = c c = b b = (F << 32-s | F>>s) + b s = md5_next_shift[s] end s = 32-4 for j = 33, 48 do local F = (b ~ c ~ d) + a + K[j] + W[(3*j+2 & 15) + 1] a = d d = c c = b b = (F << 32-s | F>>s) + b s = md5_next_shift[s] end s = 32-6 for j = 49, 64 do local F = (c ~ (b | ~d)) + a + K[j] + W[(j*7-7 & 15) + 1] a = d d = c c = b b = (F << 32-s | F>>s) + b s = md5_next_shift[s] end h1 = a + h1 h2 = b + h2 h3 = c + h3 h4 = d + h4 end H[1], H[2], H[3], H[4] = h1, h2, h3, h4 end local function sha1_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W = common_W local h1, h2, h3, h4, h5 = H[1], H[2], H[3], H[4], H[5] for pos = offs + 1, offs + size, 64 do W[1], W[2], W[3], W[4], W[5], W[6], W[7], W[8], W[9], W[10], W[11], W[12], W[13], W[14], W[15], W[16] = string_unpack(">i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4i4", str, pos) for j = 17, 80 do local a = W[j-3] ~ W[j-8] ~ W[j-14] ~ W[j-16] W[j] = a << 1 ~ a >> 31 end local a, b, c, d, e = h1, h2, h3, h4, h5 for j = 1, 20 do local z = (a << 5 ~ a >> 27) + (d ~ b & (c ~ d)) + 0x5A827999 + W[j] + e -- constant = floor(2^30 * sqrt(2)) e = d d = c c = b << 30 ~ b >> 2 b = a a = z end for j = 21, 40 do local z = (a << 5 ~ a >> 27) + (b ~ c ~ d) + 0x6ED9EBA1 + W[j] + e -- 2^30 * sqrt(3) e = d d = c c = b << 30 ~ b >> 2 b = a a = z end for j = 41, 60 do local z = (a << 5 ~ a >> 27) + ((b ~ c) & d ~ b & c) + 0x8F1BBCDC + W[j] + e -- 2^30 * sqrt(5) e = d d = c c = b << 30 ~ b >> 2 b = a a = z end for j = 61, 80 do local z = (a << 5 ~ a >> 27) + (b ~ c ~ d) + 0xCA62C1D6 + W[j] + e -- 2^30 * sqrt(10) e = d d = c c = b << 30 ~ b >> 2 b = a a = z end h1 = a + h1 h2 = b + h2 h3 = c + h3 h4 = d + h4 h5 = e + h5 end H[1], H[2], H[3], H[4], H[5] = h1, h2, h3, h4, h5 end local keccak_format_i4i4 = build_keccak_format("i4i4") local function keccak_feed(lanes_lo, lanes_hi, str, offs, size, block_size_in_bytes) -- offs >= 0, size >= 0, size is multiple of block_size_in_bytes, block_size_in_bytes is positive multiple of 8 local RC_lo, RC_hi = sha3_RC_lo, sha3_RC_hi local qwords_qty = block_size_in_bytes / 8 local keccak_format = keccak_format_i4i4[qwords_qty] for pos = offs + 1, offs + size, block_size_in_bytes do local dwords_from_message = {string_unpack(keccak_format, str, pos)} for j = 1, qwords_qty do lanes_lo[j] = lanes_lo[j] ~ dwords_from_message[2*j-1] lanes_hi[j] = lanes_hi[j] ~ dwords_from_message[2*j] end local L01_lo, L01_hi, L02_lo, L02_hi, L03_lo, L03_hi, L04_lo, L04_hi, L05_lo, L05_hi, L06_lo, L06_hi, L07_lo, L07_hi, L08_lo, L08_hi, L09_lo, L09_hi, L10_lo, L10_hi, L11_lo, L11_hi, L12_lo, L12_hi, L13_lo, L13_hi, L14_lo, L14_hi, L15_lo, L15_hi, L16_lo, L16_hi, L17_lo, L17_hi, L18_lo, L18_hi, L19_lo, L19_hi, L20_lo, L20_hi, L21_lo, L21_hi, L22_lo, L22_hi, L23_lo, L23_hi, L24_lo, L24_hi, L25_lo, L25_hi = lanes_lo[1], lanes_hi[1], lanes_lo[2], lanes_hi[2], lanes_lo[3], lanes_hi[3], lanes_lo[4], lanes_hi[4], lanes_lo[5], lanes_hi[5], lanes_lo[6], lanes_hi[6], lanes_lo[7], lanes_hi[7], lanes_lo[8], lanes_hi[8], lanes_lo[9], lanes_hi[9], lanes_lo[10], lanes_hi[10], lanes_lo[11], lanes_hi[11], lanes_lo[12], lanes_hi[12], lanes_lo[13], lanes_hi[13], lanes_lo[14], lanes_hi[14], lanes_lo[15], lanes_hi[15], lanes_lo[16], lanes_hi[16], lanes_lo[17], lanes_hi[17], lanes_lo[18], lanes_hi[18], lanes_lo[19], lanes_hi[19], lanes_lo[20], lanes_hi[20], lanes_lo[21], lanes_hi[21], lanes_lo[22], lanes_hi[22], lanes_lo[23], lanes_hi[23], lanes_lo[24], lanes_hi[24], lanes_lo[25], lanes_hi[25] for round_idx = 1, 24 do local C1_lo = L01_lo ~ L06_lo ~ L11_lo ~ L16_lo ~ L21_lo local C1_hi = L01_hi ~ L06_hi ~ L11_hi ~ L16_hi ~ L21_hi local C2_lo = L02_lo ~ L07_lo ~ L12_lo ~ L17_lo ~ L22_lo local C2_hi = L02_hi ~ L07_hi ~ L12_hi ~ L17_hi ~ L22_hi local C3_lo = L03_lo ~ L08_lo ~ L13_lo ~ L18_lo ~ L23_lo local C3_hi = L03_hi ~ L08_hi ~ L13_hi ~ L18_hi ~ L23_hi local C4_lo = L04_lo ~ L09_lo ~ L14_lo ~ L19_lo ~ L24_lo local C4_hi = L04_hi ~ L09_hi ~ L14_hi ~ L19_hi ~ L24_hi local C5_lo = L05_lo ~ L10_lo ~ L15_lo ~ L20_lo ~ L25_lo local C5_hi = L05_hi ~ L10_hi ~ L15_hi ~ L20_hi ~ L25_hi local D_lo = C1_lo ~ C3_lo<<1 ~ C3_hi>>31 local D_hi = C1_hi ~ C3_hi<<1 ~ C3_lo>>31 local T0_lo = D_lo ~ L02_lo local T0_hi = D_hi ~ L02_hi local T1_lo = D_lo ~ L07_lo local T1_hi = D_hi ~ L07_hi local T2_lo = D_lo ~ L12_lo local T2_hi = D_hi ~ L12_hi local T3_lo = D_lo ~ L17_lo local T3_hi = D_hi ~ L17_hi local T4_lo = D_lo ~ L22_lo local T4_hi = D_hi ~ L22_hi L02_lo = T1_lo>>20 ~ T1_hi<<12 L02_hi = T1_hi>>20 ~ T1_lo<<12 L07_lo = T3_lo>>19 ~ T3_hi<<13 L07_hi = T3_hi>>19 ~ T3_lo<<13 L12_lo = T0_lo<<1 ~ T0_hi>>31 L12_hi = T0_hi<<1 ~ T0_lo>>31 L17_lo = T2_lo<<10 ~ T2_hi>>22 L17_hi = T2_hi<<10 ~ T2_lo>>22 L22_lo = T4_lo<<2 ~ T4_hi>>30 L22_hi = T4_hi<<2 ~ T4_lo>>30 D_lo = C2_lo ~ C4_lo<<1 ~ C4_hi>>31 D_hi = C2_hi ~ C4_hi<<1 ~ C4_lo>>31 T0_lo = D_lo ~ L03_lo T0_hi = D_hi ~ L03_hi T1_lo = D_lo ~ L08_lo T1_hi = D_hi ~ L08_hi T2_lo = D_lo ~ L13_lo T2_hi = D_hi ~ L13_hi T3_lo = D_lo ~ L18_lo T3_hi = D_hi ~ L18_hi T4_lo = D_lo ~ L23_lo T4_hi = D_hi ~ L23_hi L03_lo = T2_lo>>21 ~ T2_hi<<11 L03_hi = T2_hi>>21 ~ T2_lo<<11 L08_lo = T4_lo>>3 ~ T4_hi<<29 L08_hi = T4_hi>>3 ~ T4_lo<<29 L13_lo = T1_lo<<6 ~ T1_hi>>26 L13_hi = T1_hi<<6 ~ T1_lo>>26 L18_lo = T3_lo<<15 ~ T3_hi>>17 L18_hi = T3_hi<<15 ~ T3_lo>>17 L23_lo = T0_lo>>2 ~ T0_hi<<30 L23_hi = T0_hi>>2 ~ T0_lo<<30 D_lo = C3_lo ~ C5_lo<<1 ~ C5_hi>>31 D_hi = C3_hi ~ C5_hi<<1 ~ C5_lo>>31 T0_lo = D_lo ~ L04_lo T0_hi = D_hi ~ L04_hi T1_lo = D_lo ~ L09_lo T1_hi = D_hi ~ L09_hi T2_lo = D_lo ~ L14_lo T2_hi = D_hi ~ L14_hi T3_lo = D_lo ~ L19_lo T3_hi = D_hi ~ L19_hi T4_lo = D_lo ~ L24_lo T4_hi = D_hi ~ L24_hi L04_lo = T3_lo<<21 ~ T3_hi>>11 L04_hi = T3_hi<<21 ~ T3_lo>>11 L09_lo = T0_lo<<28 ~ T0_hi>>4 L09_hi = T0_hi<<28 ~ T0_lo>>4 L14_lo = T2_lo<<25 ~ T2_hi>>7 L14_hi = T2_hi<<25 ~ T2_lo>>7 L19_lo = T4_lo>>8 ~ T4_hi<<24 L19_hi = T4_hi>>8 ~ T4_lo<<24 L24_lo = T1_lo>>9 ~ T1_hi<<23 L24_hi = T1_hi>>9 ~ T1_lo<<23 D_lo = C4_lo ~ C1_lo<<1 ~ C1_hi>>31 D_hi = C4_hi ~ C1_hi<<1 ~ C1_lo>>31 T0_lo = D_lo ~ L05_lo T0_hi = D_hi ~ L05_hi T1_lo = D_lo ~ L10_lo T1_hi = D_hi ~ L10_hi T2_lo = D_lo ~ L15_lo T2_hi = D_hi ~ L15_hi T3_lo = D_lo ~ L20_lo T3_hi = D_hi ~ L20_hi T4_lo = D_lo ~ L25_lo T4_hi = D_hi ~ L25_hi L05_lo = T4_lo<<14 ~ T4_hi>>18 L05_hi = T4_hi<<14 ~ T4_lo>>18 L10_lo = T1_lo<<20 ~ T1_hi>>12 L10_hi = T1_hi<<20 ~ T1_lo>>12 L15_lo = T3_lo<<8 ~ T3_hi>>24 L15_hi = T3_hi<<8 ~ T3_lo>>24 L20_lo = T0_lo<<27 ~ T0_hi>>5 L20_hi = T0_hi<<27 ~ T0_lo>>5 L25_lo = T2_lo>>25 ~ T2_hi<<7 L25_hi = T2_hi>>25 ~ T2_lo<<7 D_lo = C5_lo ~ C2_lo<<1 ~ C2_hi>>31 D_hi = C5_hi ~ C2_hi<<1 ~ C2_lo>>31 T1_lo = D_lo ~ L06_lo T1_hi = D_hi ~ L06_hi T2_lo = D_lo ~ L11_lo T2_hi = D_hi ~ L11_hi T3_lo = D_lo ~ L16_lo T3_hi = D_hi ~ L16_hi T4_lo = D_lo ~ L21_lo T4_hi = D_hi ~ L21_hi L06_lo = T2_lo<<3 ~ T2_hi>>29 L06_hi = T2_hi<<3 ~ T2_lo>>29 L11_lo = T4_lo<<18 ~ T4_hi>>14 L11_hi = T4_hi<<18 ~ T4_lo>>14 L16_lo = T1_lo>>28 ~ T1_hi<<4 L16_hi = T1_hi>>28 ~ T1_lo<<4 L21_lo = T3_lo>>23 ~ T3_hi<<9 L21_hi = T3_hi>>23 ~ T3_lo<<9 L01_lo = D_lo ~ L01_lo L01_hi = D_hi ~ L01_hi L01_lo, L02_lo, L03_lo, L04_lo, L05_lo = L01_lo ~ ~L02_lo & L03_lo, L02_lo ~ ~L03_lo & L04_lo, L03_lo ~ ~L04_lo & L05_lo, L04_lo ~ ~L05_lo & L01_lo, L05_lo ~ ~L01_lo & L02_lo L01_hi, L02_hi, L03_hi, L04_hi, L05_hi = L01_hi ~ ~L02_hi & L03_hi, L02_hi ~ ~L03_hi & L04_hi, L03_hi ~ ~L04_hi & L05_hi, L04_hi ~ ~L05_hi & L01_hi, L05_hi ~ ~L01_hi & L02_hi L06_lo, L07_lo, L08_lo, L09_lo, L10_lo = L09_lo ~ ~L10_lo & L06_lo, L10_lo ~ ~L06_lo & L07_lo, L06_lo ~ ~L07_lo & L08_lo, L07_lo ~ ~L08_lo & L09_lo, L08_lo ~ ~L09_lo & L10_lo L06_hi, L07_hi, L08_hi, L09_hi, L10_hi = L09_hi ~ ~L10_hi & L06_hi, L10_hi ~ ~L06_hi & L07_hi, L06_hi ~ ~L07_hi & L08_hi, L07_hi ~ ~L08_hi & L09_hi, L08_hi ~ ~L09_hi & L10_hi L11_lo, L12_lo, L13_lo, L14_lo, L15_lo = L12_lo ~ ~L13_lo & L14_lo, L13_lo ~ ~L14_lo & L15_lo, L14_lo ~ ~L15_lo & L11_lo, L15_lo ~ ~L11_lo & L12_lo, L11_lo ~ ~L12_lo & L13_lo L11_hi, L12_hi, L13_hi, L14_hi, L15_hi = L12_hi ~ ~L13_hi & L14_hi, L13_hi ~ ~L14_hi & L15_hi, L14_hi ~ ~L15_hi & L11_hi, L15_hi ~ ~L11_hi & L12_hi, L11_hi ~ ~L12_hi & L13_hi L16_lo, L17_lo, L18_lo, L19_lo, L20_lo = L20_lo ~ ~L16_lo & L17_lo, L16_lo ~ ~L17_lo & L18_lo, L17_lo ~ ~L18_lo & L19_lo, L18_lo ~ ~L19_lo & L20_lo, L19_lo ~ ~L20_lo & L16_lo L16_hi, L17_hi, L18_hi, L19_hi, L20_hi = L20_hi ~ ~L16_hi & L17_hi, L16_hi ~ ~L17_hi & L18_hi, L17_hi ~ ~L18_hi & L19_hi, L18_hi ~ ~L19_hi & L20_hi, L19_hi ~ ~L20_hi & L16_hi L21_lo, L22_lo, L23_lo, L24_lo, L25_lo = L23_lo ~ ~L24_lo & L25_lo, L24_lo ~ ~L25_lo & L21_lo, L25_lo ~ ~L21_lo & L22_lo, L21_lo ~ ~L22_lo & L23_lo, L22_lo ~ ~L23_lo & L24_lo L21_hi, L22_hi, L23_hi, L24_hi, L25_hi = L23_hi ~ ~L24_hi & L25_hi, L24_hi ~ ~L25_hi & L21_hi, L25_hi ~ ~L21_hi & L22_hi, L21_hi ~ ~L22_hi & L23_hi, L22_hi ~ ~L23_hi & L24_hi L01_lo = L01_lo ~ RC_lo[round_idx] L01_hi = L01_hi ~ RC_hi[round_idx] end lanes_lo[1] = L01_lo lanes_hi[1] = L01_hi lanes_lo[2] = L02_lo lanes_hi[2] = L02_hi lanes_lo[3] = L03_lo lanes_hi[3] = L03_hi lanes_lo[4] = L04_lo lanes_hi[4] = L04_hi lanes_lo[5] = L05_lo lanes_hi[5] = L05_hi lanes_lo[6] = L06_lo lanes_hi[6] = L06_hi lanes_lo[7] = L07_lo lanes_hi[7] = L07_hi lanes_lo[8] = L08_lo lanes_hi[8] = L08_hi lanes_lo[9] = L09_lo lanes_hi[9] = L09_hi lanes_lo[10] = L10_lo lanes_hi[10] = L10_hi lanes_lo[11] = L11_lo lanes_hi[11] = L11_hi lanes_lo[12] = L12_lo lanes_hi[12] = L12_hi lanes_lo[13] = L13_lo lanes_hi[13] = L13_hi lanes_lo[14] = L14_lo lanes_hi[14] = L14_hi lanes_lo[15] = L15_lo lanes_hi[15] = L15_hi lanes_lo[16] = L16_lo lanes_hi[16] = L16_hi lanes_lo[17] = L17_lo lanes_hi[17] = L17_hi lanes_lo[18] = L18_lo lanes_hi[18] = L18_hi lanes_lo[19] = L19_lo lanes_hi[19] = L19_hi lanes_lo[20] = L20_lo lanes_hi[20] = L20_hi lanes_lo[21] = L21_lo lanes_hi[21] = L21_hi lanes_lo[22] = L22_lo lanes_hi[22] = L22_hi lanes_lo[23] = L23_lo lanes_hi[23] = L23_hi lanes_lo[24] = L24_lo lanes_hi[24] = L24_hi lanes_lo[25] = L25_lo lanes_hi[25] = L25_hi end end return XOR32A5, XOR_BYTE, sha256_feed_64, sha512_feed_128, md5_feed_64, sha1_feed_64, keccak_feed ]](md5_next_shift, md5_K, sha2_K_lo, sha2_K_hi, build_keccak_format, sha3_RC_lo, sha3_RC_hi) end if branch == "LIB32" or branch == "EMUL" then -- implementation for Lua 5.1/5.2 (with or without bitwise library available) function sha256_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W, K = common_W, sha2_K_hi local h1, h2, h3, h4, h5, h6, h7, h8 = H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8] for pos = offs, offs + size - 1, 64 do for j = 1, 16 do pos = pos + 4 local a, b, c, d = byte(str, pos - 3, pos) W[j] = ((a * 256 + b) * 256 + c) * 256 + d end for j = 17, 64 do local a, b = W[j-15], W[j-2] W[j] = XOR(ROR(a, 7), ROL(a, 14), SHR(a, 3)) + XOR(ROL(b, 15), ROL(b, 13), SHR(b, 10)) + W[j-7] + W[j-16] end local a, b, c, d, e, f, g, h = h1, h2, h3, h4, h5, h6, h7, h8 for j = 1, 64 do local z = XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + AND(e, f) + AND(-1-e, g) + h + K[j] + W[j] h = g g = f f = e e = z + d d = c c = b b = a a = z + AND(d, c) + AND(a, XOR(d, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10)) end h1, h2, h3, h4 = (a + h1) % 4294967296, (b + h2) % 4294967296, (c + h3) % 4294967296, (d + h4) % 4294967296 h5, h6, h7, h8 = (e + h5) % 4294967296, (f + h6) % 4294967296, (g + h7) % 4294967296, (h + h8) % 4294967296 end H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8] = h1, h2, h3, h4, h5, h6, h7, h8 end function sha512_feed_128(H_lo, H_hi, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 128 -- W1_hi, W1_lo, W2_hi, W2_lo, ... Wk_hi = W[2*k-1], Wk_lo = W[2*k] local W, K_lo, K_hi = common_W, sha2_K_lo, sha2_K_hi local h1_lo, h2_lo, h3_lo, h4_lo, h5_lo, h6_lo, h7_lo, h8_lo = H_lo[1], H_lo[2], H_lo[3], H_lo[4], H_lo[5], H_lo[6], H_lo[7], H_lo[8] local h1_hi, h2_hi, h3_hi, h4_hi, h5_hi, h6_hi, h7_hi, h8_hi = H_hi[1], H_hi[2], H_hi[3], H_hi[4], H_hi[5], H_hi[6], H_hi[7], H_hi[8] for pos = offs, offs + size - 1, 128 do for j = 1, 16*2 do pos = pos + 4 local a, b, c, d = byte(str, pos - 3, pos) W[j] = ((a * 256 + b) * 256 + c) * 256 + d end for jj = 17*2, 80*2, 2 do local a_lo, a_hi, b_lo, b_hi = W[jj-30], W[jj-31], W[jj-4], W[jj-5] local tmp1 = XOR(SHR(a_lo, 1) + SHL(a_hi, 31), SHR(a_lo, 8) + SHL(a_hi, 24), SHR(a_lo, 7) + SHL(a_hi, 25)) % 4294967296 + XOR(SHR(b_lo, 19) + SHL(b_hi, 13), SHL(b_lo, 3) + SHR(b_hi, 29), SHR(b_lo, 6) + SHL(b_hi, 26)) % 4294967296 + W[jj-14] + W[jj-32] local tmp2 = tmp1 % 4294967296 W[jj-1] = XOR(SHR(a_hi, 1) + SHL(a_lo, 31), SHR(a_hi, 8) + SHL(a_lo, 24), SHR(a_hi, 7)) + XOR(SHR(b_hi, 19) + SHL(b_lo, 13), SHL(b_hi, 3) + SHR(b_lo, 29), SHR(b_hi, 6)) + W[jj-15] + W[jj-33] + (tmp1 - tmp2) / 4294967296 W[jj] = tmp2 end local a_lo, b_lo, c_lo, d_lo, e_lo, f_lo, g_lo, h_lo = h1_lo, h2_lo, h3_lo, h4_lo, h5_lo, h6_lo, h7_lo, h8_lo local a_hi, b_hi, c_hi, d_hi, e_hi, f_hi, g_hi, h_hi = h1_hi, h2_hi, h3_hi, h4_hi, h5_hi, h6_hi, h7_hi, h8_hi for j = 1, 80 do local jj = 2*j local tmp1 = XOR(SHR(e_lo, 14) + SHL(e_hi, 18), SHR(e_lo, 18) + SHL(e_hi, 14), SHL(e_lo, 23) + SHR(e_hi, 9)) % 4294967296 + (AND(e_lo, f_lo) + AND(-1-e_lo, g_lo)) % 4294967296 + h_lo + K_lo[j] + W[jj] local z_lo = tmp1 % 4294967296 local z_hi = XOR(SHR(e_hi, 14) + SHL(e_lo, 18), SHR(e_hi, 18) + SHL(e_lo, 14), SHL(e_hi, 23) + SHR(e_lo, 9)) + AND(e_hi, f_hi) + AND(-1-e_hi, g_hi) + h_hi + K_hi[j] + W[jj-1] + (tmp1 - z_lo) / 4294967296 h_lo = g_lo h_hi = g_hi g_lo = f_lo g_hi = f_hi f_lo = e_lo f_hi = e_hi tmp1 = z_lo + d_lo e_lo = tmp1 % 4294967296 e_hi = z_hi + d_hi + (tmp1 - e_lo) / 4294967296 d_lo = c_lo d_hi = c_hi c_lo = b_lo c_hi = b_hi b_lo = a_lo b_hi = a_hi tmp1 = z_lo + (AND(d_lo, c_lo) + AND(b_lo, XOR(d_lo, c_lo))) % 4294967296 + XOR(SHR(b_lo, 28) + SHL(b_hi, 4), SHL(b_lo, 30) + SHR(b_hi, 2), SHL(b_lo, 25) + SHR(b_hi, 7)) % 4294967296 a_lo = tmp1 % 4294967296 a_hi = z_hi + (AND(d_hi, c_hi) + AND(b_hi, XOR(d_hi, c_hi))) + XOR(SHR(b_hi, 28) + SHL(b_lo, 4), SHL(b_hi, 30) + SHR(b_lo, 2), SHL(b_hi, 25) + SHR(b_lo, 7)) + (tmp1 - a_lo) / 4294967296 end a_lo = h1_lo + a_lo h1_lo = a_lo % 4294967296 h1_hi = (h1_hi + a_hi + (a_lo - h1_lo) / 4294967296) % 4294967296 a_lo = h2_lo + b_lo h2_lo = a_lo % 4294967296 h2_hi = (h2_hi + b_hi + (a_lo - h2_lo) / 4294967296) % 4294967296 a_lo = h3_lo + c_lo h3_lo = a_lo % 4294967296 h3_hi = (h3_hi + c_hi + (a_lo - h3_lo) / 4294967296) % 4294967296 a_lo = h4_lo + d_lo h4_lo = a_lo % 4294967296 h4_hi = (h4_hi + d_hi + (a_lo - h4_lo) / 4294967296) % 4294967296 a_lo = h5_lo + e_lo h5_lo = a_lo % 4294967296 h5_hi = (h5_hi + e_hi + (a_lo - h5_lo) / 4294967296) % 4294967296 a_lo = h6_lo + f_lo h6_lo = a_lo % 4294967296 h6_hi = (h6_hi + f_hi + (a_lo - h6_lo) / 4294967296) % 4294967296 a_lo = h7_lo + g_lo h7_lo = a_lo % 4294967296 h7_hi = (h7_hi + g_hi + (a_lo - h7_lo) / 4294967296) % 4294967296 a_lo = h8_lo + h_lo h8_lo = a_lo % 4294967296 h8_hi = (h8_hi + h_hi + (a_lo - h8_lo) / 4294967296) % 4294967296 end H_lo[1], H_lo[2], H_lo[3], H_lo[4], H_lo[5], H_lo[6], H_lo[7], H_lo[8] = h1_lo, h2_lo, h3_lo, h4_lo, h5_lo, h6_lo, h7_lo, h8_lo H_hi[1], H_hi[2], H_hi[3], H_hi[4], H_hi[5], H_hi[6], H_hi[7], H_hi[8] = h1_hi, h2_hi, h3_hi, h4_hi, h5_hi, h6_hi, h7_hi, h8_hi end function md5_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W, K, md5_next_shift = common_W, md5_K, md5_next_shift local h1, h2, h3, h4 = H[1], H[2], H[3], H[4] for pos = offs, offs + size - 1, 64 do for j = 1, 16 do pos = pos + 4 local a, b, c, d = byte(str, pos - 3, pos) W[j] = ((d * 256 + c) * 256 + b) * 256 + a end local a, b, c, d = h1, h2, h3, h4 local s = 32-7 for j = 1, 16 do local F = ROR(AND(b, c) + AND(-1-b, d) + a + K[j] + W[j], s) + b s = md5_next_shift[s] a = d d = c c = b b = F end s = 32-5 for j = 17, 32 do local F = ROR(AND(d, b) + AND(-1-d, c) + a + K[j] + W[(5*j-4) % 16 + 1], s) + b s = md5_next_shift[s] a = d d = c c = b b = F end s = 32-4 for j = 33, 48 do local F = ROR(XOR(XOR(b, c), d) + a + K[j] + W[(3*j+2) % 16 + 1], s) + b s = md5_next_shift[s] a = d d = c c = b b = F end s = 32-6 for j = 49, 64 do local F = ROR(XOR(c, OR(b, -1-d)) + a + K[j] + W[(j*7-7) % 16 + 1], s) + b s = md5_next_shift[s] a = d d = c c = b b = F end h1 = (a + h1) % 4294967296 h2 = (b + h2) % 4294967296 h3 = (c + h3) % 4294967296 h4 = (d + h4) % 4294967296 end H[1], H[2], H[3], H[4] = h1, h2, h3, h4 end function sha1_feed_64(H, str, offs, size) -- offs >= 0, size >= 0, size is multiple of 64 local W = common_W local h1, h2, h3, h4, h5 = H[1], H[2], H[3], H[4], H[5] for pos = offs, offs + size - 1, 64 do for j = 1, 16 do pos = pos + 4 local a, b, c, d = byte(str, pos - 3, pos) W[j] = ((a * 256 + b) * 256 + c) * 256 + d end for j = 17, 80 do W[j] = ROL(XOR(W[j-3], W[j-8], W[j-14], W[j-16]), 1) end local a, b, c, d, e = h1, h2, h3, h4, h5 for j = 1, 20 do local z = ROL(a, 5) + AND(b, c) + AND(-1-b, d) + 0x5A827999 + W[j] + e -- constant = floor(2^30 * sqrt(2)) e = d d = c c = ROR(b, 2) b = a a = z end for j = 21, 40 do local z = ROL(a, 5) + XOR(b, c, d) + 0x6ED9EBA1 + W[j] + e -- 2^30 * sqrt(3) e = d d = c c = ROR(b, 2) b = a a = z end for j = 41, 60 do local z = ROL(a, 5) + AND(d, c) + AND(b, XOR(d, c)) + 0x8F1BBCDC + W[j] + e -- 2^30 * sqrt(5) e = d d = c c = ROR(b, 2) b = a a = z end for j = 61, 80 do local z = ROL(a, 5) + XOR(b, c, d) + 0xCA62C1D6 + W[j] + e -- 2^30 * sqrt(10) e = d d = c c = ROR(b, 2) b = a a = z end h1 = (a + h1) % 4294967296 h2 = (b + h2) % 4294967296 h3 = (c + h3) % 4294967296 h4 = (d + h4) % 4294967296 h5 = (e + h5) % 4294967296 end H[1], H[2], H[3], H[4], H[5] = h1, h2, h3, h4, h5 end function keccak_feed(lanes_lo, lanes_hi, str, offs, size, block_size_in_bytes) -- This is an example of a Lua function having 79 local variables :-) -- offs >= 0, size >= 0, size is multiple of block_size_in_bytes, block_size_in_bytes is positive multiple of 8 local RC_lo, RC_hi = sha3_RC_lo, sha3_RC_hi local qwords_qty = block_size_in_bytes / 8 for pos = offs, offs + size - 1, block_size_in_bytes do for j = 1, qwords_qty do local a, b, c, d = byte(str, pos + 1, pos + 4) lanes_lo[j] = XOR(lanes_lo[j], ((d * 256 + c) * 256 + b) * 256 + a) pos = pos + 8 a, b, c, d = byte(str, pos - 3, pos) lanes_hi[j] = XOR(lanes_hi[j], ((d * 256 + c) * 256 + b) * 256 + a) end local L01_lo, L01_hi, L02_lo, L02_hi, L03_lo, L03_hi, L04_lo, L04_hi, L05_lo, L05_hi, L06_lo, L06_hi, L07_lo, L07_hi, L08_lo, L08_hi, L09_lo, L09_hi, L10_lo, L10_hi, L11_lo, L11_hi, L12_lo, L12_hi, L13_lo, L13_hi, L14_lo, L14_hi, L15_lo, L15_hi, L16_lo, L16_hi, L17_lo, L17_hi, L18_lo, L18_hi, L19_lo, L19_hi, L20_lo, L20_hi, L21_lo, L21_hi, L22_lo, L22_hi, L23_lo, L23_hi, L24_lo, L24_hi, L25_lo, L25_hi = lanes_lo[1], lanes_hi[1], lanes_lo[2], lanes_hi[2], lanes_lo[3], lanes_hi[3], lanes_lo[4], lanes_hi[4], lanes_lo[5], lanes_hi[5], lanes_lo[6], lanes_hi[6], lanes_lo[7], lanes_hi[7], lanes_lo[8], lanes_hi[8], lanes_lo[9], lanes_hi[9], lanes_lo[10], lanes_hi[10], lanes_lo[11], lanes_hi[11], lanes_lo[12], lanes_hi[12], lanes_lo[13], lanes_hi[13], lanes_lo[14], lanes_hi[14], lanes_lo[15], lanes_hi[15], lanes_lo[16], lanes_hi[16], lanes_lo[17], lanes_hi[17], lanes_lo[18], lanes_hi[18], lanes_lo[19], lanes_hi[19], lanes_lo[20], lanes_hi[20], lanes_lo[21], lanes_hi[21], lanes_lo[22], lanes_hi[22], lanes_lo[23], lanes_hi[23], lanes_lo[24], lanes_hi[24], lanes_lo[25], lanes_hi[25] for round_idx = 1, 24 do local C1_lo = XOR(L01_lo, L06_lo, L11_lo, L16_lo, L21_lo) local C1_hi = XOR(L01_hi, L06_hi, L11_hi, L16_hi, L21_hi) local C2_lo = XOR(L02_lo, L07_lo, L12_lo, L17_lo, L22_lo) local C2_hi = XOR(L02_hi, L07_hi, L12_hi, L17_hi, L22_hi) local C3_lo = XOR(L03_lo, L08_lo, L13_lo, L18_lo, L23_lo) local C3_hi = XOR(L03_hi, L08_hi, L13_hi, L18_hi, L23_hi) local C4_lo = XOR(L04_lo, L09_lo, L14_lo, L19_lo, L24_lo) local C4_hi = XOR(L04_hi, L09_hi, L14_hi, L19_hi, L24_hi) local C5_lo = XOR(L05_lo, L10_lo, L15_lo, L20_lo, L25_lo) local C5_hi = XOR(L05_hi, L10_hi, L15_hi, L20_hi, L25_hi) local D_lo = XOR(C1_lo, C3_lo * 2 + (C3_hi % 2^32 - C3_hi % 2^31) / 2^31) local D_hi = XOR(C1_hi, C3_hi * 2 + (C3_lo % 2^32 - C3_lo % 2^31) / 2^31) local T0_lo = XOR(D_lo, L02_lo) local T0_hi = XOR(D_hi, L02_hi) local T1_lo = XOR(D_lo, L07_lo) local T1_hi = XOR(D_hi, L07_hi) local T2_lo = XOR(D_lo, L12_lo) local T2_hi = XOR(D_hi, L12_hi) local T3_lo = XOR(D_lo, L17_lo) local T3_hi = XOR(D_hi, L17_hi) local T4_lo = XOR(D_lo, L22_lo) local T4_hi = XOR(D_hi, L22_hi) L02_lo = (T1_lo % 2^32 - T1_lo % 2^20) / 2^20 + T1_hi * 2^12 L02_hi = (T1_hi % 2^32 - T1_hi % 2^20) / 2^20 + T1_lo * 2^12 L07_lo = (T3_lo % 2^32 - T3_lo % 2^19) / 2^19 + T3_hi * 2^13 L07_hi = (T3_hi % 2^32 - T3_hi % 2^19) / 2^19 + T3_lo * 2^13 L12_lo = T0_lo * 2 + (T0_hi % 2^32 - T0_hi % 2^31) / 2^31 L12_hi = T0_hi * 2 + (T0_lo % 2^32 - T0_lo % 2^31) / 2^31 L17_lo = T2_lo * 2^10 + (T2_hi % 2^32 - T2_hi % 2^22) / 2^22 L17_hi = T2_hi * 2^10 + (T2_lo % 2^32 - T2_lo % 2^22) / 2^22 L22_lo = T4_lo * 2^2 + (T4_hi % 2^32 - T4_hi % 2^30) / 2^30 L22_hi = T4_hi * 2^2 + (T4_lo % 2^32 - T4_lo % 2^30) / 2^30 D_lo = XOR(C2_lo, C4_lo * 2 + (C4_hi % 2^32 - C4_hi % 2^31) / 2^31) D_hi = XOR(C2_hi, C4_hi * 2 + (C4_lo % 2^32 - C4_lo % 2^31) / 2^31) T0_lo = XOR(D_lo, L03_lo) T0_hi = XOR(D_hi, L03_hi) T1_lo = XOR(D_lo, L08_lo) T1_hi = XOR(D_hi, L08_hi) T2_lo = XOR(D_lo, L13_lo) T2_hi = XOR(D_hi, L13_hi) T3_lo = XOR(D_lo, L18_lo) T3_hi = XOR(D_hi, L18_hi) T4_lo = XOR(D_lo, L23_lo) T4_hi = XOR(D_hi, L23_hi) L03_lo = (T2_lo % 2^32 - T2_lo % 2^21) / 2^21 + T2_hi * 2^11 L03_hi = (T2_hi % 2^32 - T2_hi % 2^21) / 2^21 + T2_lo * 2^11 L08_lo = (T4_lo % 2^32 - T4_lo % 2^3) / 2^3 + T4_hi * 2^29 % 2^32 L08_hi = (T4_hi % 2^32 - T4_hi % 2^3) / 2^3 + T4_lo * 2^29 % 2^32 L13_lo = T1_lo * 2^6 + (T1_hi % 2^32 - T1_hi % 2^26) / 2^26 L13_hi = T1_hi * 2^6 + (T1_lo % 2^32 - T1_lo % 2^26) / 2^26 L18_lo = T3_lo * 2^15 + (T3_hi % 2^32 - T3_hi % 2^17) / 2^17 L18_hi = T3_hi * 2^15 + (T3_lo % 2^32 - T3_lo % 2^17) / 2^17 L23_lo = (T0_lo % 2^32 - T0_lo % 2^2) / 2^2 + T0_hi * 2^30 % 2^32 L23_hi = (T0_hi % 2^32 - T0_hi % 2^2) / 2^2 + T0_lo * 2^30 % 2^32 D_lo = XOR(C3_lo, C5_lo * 2 + (C5_hi % 2^32 - C5_hi % 2^31) / 2^31) D_hi = XOR(C3_hi, C5_hi * 2 + (C5_lo % 2^32 - C5_lo % 2^31) / 2^31) T0_lo = XOR(D_lo, L04_lo) T0_hi = XOR(D_hi, L04_hi) T1_lo = XOR(D_lo, L09_lo) T1_hi = XOR(D_hi, L09_hi) T2_lo = XOR(D_lo, L14_lo) T2_hi = XOR(D_hi, L14_hi) T3_lo = XOR(D_lo, L19_lo) T3_hi = XOR(D_hi, L19_hi) T4_lo = XOR(D_lo, L24_lo) T4_hi = XOR(D_hi, L24_hi) L04_lo = T3_lo * 2^21 % 2^32 + (T3_hi % 2^32 - T3_hi % 2^11) / 2^11 L04_hi = T3_hi * 2^21 % 2^32 + (T3_lo % 2^32 - T3_lo % 2^11) / 2^11 L09_lo = T0_lo * 2^28 % 2^32 + (T0_hi % 2^32 - T0_hi % 2^4) / 2^4 L09_hi = T0_hi * 2^28 % 2^32 + (T0_lo % 2^32 - T0_lo % 2^4) / 2^4 L14_lo = T2_lo * 2^25 % 2^32 + (T2_hi % 2^32 - T2_hi % 2^7) / 2^7 L14_hi = T2_hi * 2^25 % 2^32 + (T2_lo % 2^32 - T2_lo % 2^7) / 2^7 L19_lo = (T4_lo % 2^32 - T4_lo % 2^8) / 2^8 + T4_hi * 2^24 % 2^32 L19_hi = (T4_hi % 2^32 - T4_hi % 2^8) / 2^8 + T4_lo * 2^24 % 2^32 L24_lo = (T1_lo % 2^32 - T1_lo % 2^9) / 2^9 + T1_hi * 2^23 % 2^32 L24_hi = (T1_hi % 2^32 - T1_hi % 2^9) / 2^9 + T1_lo * 2^23 % 2^32 D_lo = XOR(C4_lo, C1_lo * 2 + (C1_hi % 2^32 - C1_hi % 2^31) / 2^31) D_hi = XOR(C4_hi, C1_hi * 2 + (C1_lo % 2^32 - C1_lo % 2^31) / 2^31) T0_lo = XOR(D_lo, L05_lo) T0_hi = XOR(D_hi, L05_hi) T1_lo = XOR(D_lo, L10_lo) T1_hi = XOR(D_hi, L10_hi) T2_lo = XOR(D_lo, L15_lo) T2_hi = XOR(D_hi, L15_hi) T3_lo = XOR(D_lo, L20_lo) T3_hi = XOR(D_hi, L20_hi) T4_lo = XOR(D_lo, L25_lo) T4_hi = XOR(D_hi, L25_hi) L05_lo = T4_lo * 2^14 + (T4_hi % 2^32 - T4_hi % 2^18) / 2^18 L05_hi = T4_hi * 2^14 + (T4_lo % 2^32 - T4_lo % 2^18) / 2^18 L10_lo = T1_lo * 2^20 % 2^32 + (T1_hi % 2^32 - T1_hi % 2^12) / 2^12 L10_hi = T1_hi * 2^20 % 2^32 + (T1_lo % 2^32 - T1_lo % 2^12) / 2^12 L15_lo = T3_lo * 2^8 + (T3_hi % 2^32 - T3_hi % 2^24) / 2^24 L15_hi = T3_hi * 2^8 + (T3_lo % 2^32 - T3_lo % 2^24) / 2^24 L20_lo = T0_lo * 2^27 % 2^32 + (T0_hi % 2^32 - T0_hi % 2^5) / 2^5 L20_hi = T0_hi * 2^27 % 2^32 + (T0_lo % 2^32 - T0_lo % 2^5) / 2^5 L25_lo = (T2_lo % 2^32 - T2_lo % 2^25) / 2^25 + T2_hi * 2^7 L25_hi = (T2_hi % 2^32 - T2_hi % 2^25) / 2^25 + T2_lo * 2^7 D_lo = XOR(C5_lo, C2_lo * 2 + (C2_hi % 2^32 - C2_hi % 2^31) / 2^31) D_hi = XOR(C5_hi, C2_hi * 2 + (C2_lo % 2^32 - C2_lo % 2^31) / 2^31) T1_lo = XOR(D_lo, L06_lo) T1_hi = XOR(D_hi, L06_hi) T2_lo = XOR(D_lo, L11_lo) T2_hi = XOR(D_hi, L11_hi) T3_lo = XOR(D_lo, L16_lo) T3_hi = XOR(D_hi, L16_hi) T4_lo = XOR(D_lo, L21_lo) T4_hi = XOR(D_hi, L21_hi) L06_lo = T2_lo * 2^3 + (T2_hi % 2^32 - T2_hi % 2^29) / 2^29 L06_hi = T2_hi * 2^3 + (T2_lo % 2^32 - T2_lo % 2^29) / 2^29 L11_lo = T4_lo * 2^18 + (T4_hi % 2^32 - T4_hi % 2^14) / 2^14 L11_hi = T4_hi * 2^18 + (T4_lo % 2^32 - T4_lo % 2^14) / 2^14 L16_lo = (T1_lo % 2^32 - T1_lo % 2^28) / 2^28 + T1_hi * 2^4 L16_hi = (T1_hi % 2^32 - T1_hi % 2^28) / 2^28 + T1_lo * 2^4 L21_lo = (T3_lo % 2^32 - T3_lo % 2^23) / 2^23 + T3_hi * 2^9 L21_hi = (T3_hi % 2^32 - T3_hi % 2^23) / 2^23 + T3_lo * 2^9 L01_lo = XOR(D_lo, L01_lo) L01_hi = XOR(D_hi, L01_hi) L01_lo, L02_lo, L03_lo, L04_lo, L05_lo = XOR(L01_lo, AND(-1-L02_lo, L03_lo)), XOR(L02_lo, AND(-1-L03_lo, L04_lo)), XOR(L03_lo, AND(-1-L04_lo, L05_lo)), XOR(L04_lo, AND(-1-L05_lo, L01_lo)), XOR(L05_lo, AND(-1-L01_lo, L02_lo)) L01_hi, L02_hi, L03_hi, L04_hi, L05_hi = XOR(L01_hi, AND(-1-L02_hi, L03_hi)), XOR(L02_hi, AND(-1-L03_hi, L04_hi)), XOR(L03_hi, AND(-1-L04_hi, L05_hi)), XOR(L04_hi, AND(-1-L05_hi, L01_hi)), XOR(L05_hi, AND(-1-L01_hi, L02_hi)) L06_lo, L07_lo, L08_lo, L09_lo, L10_lo = XOR(L09_lo, AND(-1-L10_lo, L06_lo)), XOR(L10_lo, AND(-1-L06_lo, L07_lo)), XOR(L06_lo, AND(-1-L07_lo, L08_lo)), XOR(L07_lo, AND(-1-L08_lo, L09_lo)), XOR(L08_lo, AND(-1-L09_lo, L10_lo)) L06_hi, L07_hi, L08_hi, L09_hi, L10_hi = XOR(L09_hi, AND(-1-L10_hi, L06_hi)), XOR(L10_hi, AND(-1-L06_hi, L07_hi)), XOR(L06_hi, AND(-1-L07_hi, L08_hi)), XOR(L07_hi, AND(-1-L08_hi, L09_hi)), XOR(L08_hi, AND(-1-L09_hi, L10_hi)) L11_lo, L12_lo, L13_lo, L14_lo, L15_lo = XOR(L12_lo, AND(-1-L13_lo, L14_lo)), XOR(L13_lo, AND(-1-L14_lo, L15_lo)), XOR(L14_lo, AND(-1-L15_lo, L11_lo)), XOR(L15_lo, AND(-1-L11_lo, L12_lo)), XOR(L11_lo, AND(-1-L12_lo, L13_lo)) L11_hi, L12_hi, L13_hi, L14_hi, L15_hi = XOR(L12_hi, AND(-1-L13_hi, L14_hi)), XOR(L13_hi, AND(-1-L14_hi, L15_hi)), XOR(L14_hi, AND(-1-L15_hi, L11_hi)), XOR(L15_hi, AND(-1-L11_hi, L12_hi)), XOR(L11_hi, AND(-1-L12_hi, L13_hi)) L16_lo, L17_lo, L18_lo, L19_lo, L20_lo = XOR(L20_lo, AND(-1-L16_lo, L17_lo)), XOR(L16_lo, AND(-1-L17_lo, L18_lo)), XOR(L17_lo, AND(-1-L18_lo, L19_lo)), XOR(L18_lo, AND(-1-L19_lo, L20_lo)), XOR(L19_lo, AND(-1-L20_lo, L16_lo)) L16_hi, L17_hi, L18_hi, L19_hi, L20_hi = XOR(L20_hi, AND(-1-L16_hi, L17_hi)), XOR(L16_hi, AND(-1-L17_hi, L18_hi)), XOR(L17_hi, AND(-1-L18_hi, L19_hi)), XOR(L18_hi, AND(-1-L19_hi, L20_hi)), XOR(L19_hi, AND(-1-L20_hi, L16_hi)) L21_lo, L22_lo, L23_lo, L24_lo, L25_lo = XOR(L23_lo, AND(-1-L24_lo, L25_lo)), XOR(L24_lo, AND(-1-L25_lo, L21_lo)), XOR(L25_lo, AND(-1-L21_lo, L22_lo)), XOR(L21_lo, AND(-1-L22_lo, L23_lo)), XOR(L22_lo, AND(-1-L23_lo, L24_lo)) L21_hi, L22_hi, L23_hi, L24_hi, L25_hi = XOR(L23_hi, AND(-1-L24_hi, L25_hi)), XOR(L24_hi, AND(-1-L25_hi, L21_hi)), XOR(L25_hi, AND(-1-L21_hi, L22_hi)), XOR(L21_hi, AND(-1-L22_hi, L23_hi)), XOR(L22_hi, AND(-1-L23_hi, L24_hi)) L01_lo = XOR(L01_lo, RC_lo[round_idx]) L01_hi = L01_hi + RC_hi[round_idx] -- RC_hi[] is either 0 or 0x80000000, so we could use fast addition instead of slow XOR end lanes_lo[1] = L01_lo lanes_hi[1] = L01_hi lanes_lo[2] = L02_lo lanes_hi[2] = L02_hi lanes_lo[3] = L03_lo lanes_hi[3] = L03_hi lanes_lo[4] = L04_lo lanes_hi[4] = L04_hi lanes_lo[5] = L05_lo lanes_hi[5] = L05_hi lanes_lo[6] = L06_lo lanes_hi[6] = L06_hi lanes_lo[7] = L07_lo lanes_hi[7] = L07_hi lanes_lo[8] = L08_lo lanes_hi[8] = L08_hi lanes_lo[9] = L09_lo lanes_hi[9] = L09_hi lanes_lo[10] = L10_lo lanes_hi[10] = L10_hi lanes_lo[11] = L11_lo lanes_hi[11] = L11_hi lanes_lo[12] = L12_lo lanes_hi[12] = L12_hi lanes_lo[13] = L13_lo lanes_hi[13] = L13_hi lanes_lo[14] = L14_lo lanes_hi[14] = L14_hi lanes_lo[15] = L15_lo lanes_hi[15] = L15_hi lanes_lo[16] = L16_lo lanes_hi[16] = L16_hi lanes_lo[17] = L17_lo lanes_hi[17] = L17_hi lanes_lo[18] = L18_lo lanes_hi[18] = L18_hi lanes_lo[19] = L19_lo lanes_hi[19] = L19_hi lanes_lo[20] = L20_lo lanes_hi[20] = L20_hi lanes_lo[21] = L21_lo lanes_hi[21] = L21_hi lanes_lo[22] = L22_lo lanes_hi[22] = L22_hi lanes_lo[23] = L23_lo lanes_hi[23] = L23_hi lanes_lo[24] = L24_lo lanes_hi[24] = L24_hi lanes_lo[25] = L25_lo lanes_hi[25] = L25_hi end end end -------------------------------------------------------------------------------- -- MAGIC NUMBERS CALCULATOR -------------------------------------------------------------------------------- -- Q: -- Is 53-bit "double" math enough to calculate square roots and cube roots of primes with 64 correct bits after decimal point? -- A: -- Yes, 53-bit "double" arithmetic is enough. -- We could obtain first 40 bits by direct calculation of p^(1/3) and next 40 bits by one step of Newton's method. do local function mul(src1, src2, factor, result_length) -- src1, src2 - long integers (arrays of digits in base 2^24) -- factor - small integer -- returns long integer result (src1 * src2 * factor) and its floating point approximation local result, carry, value, weight = {}, 0.0, 0.0, 1.0 for j = 1, result_length do for k = math_max(1, j + 1 - #src2), math_min(j, #src1) do carry = carry + factor * src1[k] * src2[j + 1 - k] -- "int32" is not enough for multiplication result, that's why "factor" must be of type "double" end local digit = carry % 2^24 result[j] = floor(digit) carry = (carry - digit) / 2^24 value = value + digit * weight weight = weight * 2^24 end return result, value end local idx, step, p, one, sqrt_hi, sqrt_lo = 0, {4, 1, 2, -2, 2}, 4, {1}, sha2_H_hi, sha2_H_lo repeat p = p + step[p % 6] local d = 1 repeat d = d + step[d % 6] if d*d > p then -- next prime number is found local root = p^(1/3) local R = root * 2^40 R = mul({R - R % 1}, one, 1.0, 2) local _, delta = mul(R, mul(R, R, 1.0, 4), -1.0, 4) local hi = R[2] % 65536 * 65536 + floor(R[1] / 256) local lo = R[1] % 256 * 16777216 + floor(delta * (2^-56 / 3) * root / p) if idx < 16 then root = p^(1/2) R = root * 2^40 R = mul({R - R % 1}, one, 1.0, 2) _, delta = mul(R, R, -1.0, 2) local hi = R[2] % 65536 * 65536 + floor(R[1] / 256) local lo = R[1] % 256 * 16777216 + floor(delta * 2^-17 / root) local idx = idx % 8 + 1 sha2_H_ext256[224][idx] = lo sqrt_hi[idx], sqrt_lo[idx] = hi, lo + hi * hi_factor if idx > 7 then sqrt_hi, sqrt_lo = sha2_H_ext512_hi[384], sha2_H_ext512_lo[384] end end idx = idx + 1 sha2_K_hi[idx], sha2_K_lo[idx] = hi, lo % K_lo_modulo + hi * hi_factor break end until p % d == 0 until idx > 79 end -- Calculating IVs for SHA512/224 and SHA512/256 for width = 224, 256, 32 do local H_lo, H_hi = {} if XOR64A5 then for j = 1, 8 do H_lo[j] = XOR64A5(sha2_H_lo[j]) end else H_hi = {} for j = 1, 8 do H_lo[j] = XOR32A5(sha2_H_lo[j]) H_hi[j] = XOR32A5(sha2_H_hi[j]) end end sha512_feed_128(H_lo, H_hi, "SHA-512/"..tostring(width).."\128"..string_rep("\0", 115).."\88", 0, 128) sha2_H_ext512_lo[width] = H_lo sha2_H_ext512_hi[width] = H_hi end -- Constants for MD5 do local sin, abs, modf = math.sin, math.abs, math.modf for idx = 1, 64 do -- we can't use formula floor(abs(sin(idx))*2^32) because its result may be beyond integer range on Lua built with 32-bit integers local hi, lo = modf(abs(sin(idx)) * 2^16) md5_K[idx] = hi * 65536 + floor(lo * 2^16) end end -- Constants for SHA3 do local sh_reg = 29 local function next_bit() local r = sh_reg % 2 sh_reg = XOR_BYTE((sh_reg - r) / 2, 142 * r) return r end for idx = 1, 24 do local lo, m = 0 for _ = 1, 6 do m = m and m * m * 2 or 1 lo = lo + next_bit() * m end local hi = next_bit() * m sha3_RC_hi[idx], sha3_RC_lo[idx] = hi, lo + hi * hi_factor_keccak end end -------------------------------------------------------------------------------- -- MAIN FUNCTIONS -------------------------------------------------------------------------------- local function sha256ext(width, message) -- Create an instance (private objects for current calculation) local H, length, tail = {unpack(sha2_H_ext256[width])}, 0.0, "" local function partial(message_part) if message_part then if tail then length = length + #message_part local offs = 0 if tail ~= "" and #tail + #message_part >= 64 then offs = 64 - #tail sha256_feed_64(H, tail..sub(message_part, 1, offs), 0, 64) tail = "" end local size = #message_part - offs local size_tail = size % 64 sha256_feed_64(H, message_part, offs, size - size_tail) tail = tail..sub(message_part, #message_part + 1 - size_tail) return partial else error("Adding more chunks is not allowed after receiving the result", 2) end else if tail then local final_blocks = {tail, "\128", string_rep("\0", (-9 - length) % 64 + 1)} tail = nil -- Assuming user data length is shorter than (2^53)-9 bytes -- Anyway, it looks very unrealistic that someone would spend more than a year of calculations to process 2^53 bytes of data by using this Lua script :-) -- 2^53 bytes = 2^56 bits, so "bit-counter" fits in 7 bytes length = length * (8 / 256^7) -- convert "byte-counter" to "bit-counter" and move decimal point to the left for j = 4, 10 do length = length % 1 * 256 final_blocks[j] = char(floor(length)) end final_blocks = table_concat(final_blocks) sha256_feed_64(H, final_blocks, 0, #final_blocks) local max_reg = width / 32 for j = 1, max_reg do H[j] = HEX(H[j]) end H = table_concat(H, "", 1, max_reg) end return H end end if message then -- Actually perform calculations and return the SHA256 digest of a message return partial(message)() else -- Return function for chunk-by-chunk loading -- User should feed every chunk of input data as single argument to this function and finally get SHA256 digest by invoking this function without an argument return partial end end local function sha512ext(width, message) -- Create an instance (private objects for current calculation) local length, tail, H_lo, H_hi = 0.0, "", {unpack(sha2_H_ext512_lo[width])}, not HEX64 and {unpack(sha2_H_ext512_hi[width])} local function partial(message_part) if message_part then if tail then length = length + #message_part local offs = 0 if tail ~= "" and #tail + #message_part >= 128 then offs = 128 - #tail sha512_feed_128(H_lo, H_hi, tail..sub(message_part, 1, offs), 0, 128) tail = "" end local size = #message_part - offs local size_tail = size % 128 sha512_feed_128(H_lo, H_hi, message_part, offs, size - size_tail) tail = tail..sub(message_part, #message_part + 1 - size_tail) return partial else error("Adding more chunks is not allowed after receiving the result", 2) end else if tail then local final_blocks = {tail, "\128", string_rep("\0", (-17-length) % 128 + 9)} tail = nil -- Assuming user data length is shorter than (2^53)-17 bytes -- 2^53 bytes = 2^56 bits, so "bit-counter" fits in 7 bytes length = length * (8 / 256^7) -- convert "byte-counter" to "bit-counter" and move floating point to the left for j = 4, 10 do length = length % 1 * 256 final_blocks[j] = char(floor(length)) end final_blocks = table_concat(final_blocks) sha512_feed_128(H_lo, H_hi, final_blocks, 0, #final_blocks) local max_reg = ceil(width / 64) if HEX64 then for j = 1, max_reg do H_lo[j] = HEX64(H_lo[j]) end else for j = 1, max_reg do H_lo[j] = HEX(H_hi[j])..HEX(H_lo[j]) end H_hi = nil end H_lo = sub(table_concat(H_lo, "", 1, max_reg), 1, width / 4) end return H_lo end end if message then -- Actually perform calculations and return the SHA512 digest of a message return partial(message)() else -- Return function for chunk-by-chunk loading -- User should feed every chunk of input data as single argument to this function and finally get SHA512 digest by invoking this function without an argument return partial end end local function md5(message) -- Create an instance (private objects for current calculation) local H, length, tail = {unpack(md5_sha1_H, 1, 4)}, 0.0, "" local function partial(message_part) if message_part then if tail then length = length + #message_part local offs = 0 if tail ~= "" and #tail + #message_part >= 64 then offs = 64 - #tail md5_feed_64(H, tail..sub(message_part, 1, offs), 0, 64) tail = "" end local size = #message_part - offs local size_tail = size % 64 md5_feed_64(H, message_part, offs, size - size_tail) tail = tail..sub(message_part, #message_part + 1 - size_tail) return partial else error("Adding more chunks is not allowed after receiving the result", 2) end else if tail then local final_blocks = {tail, "\128", string_rep("\0", (-9 - length) % 64)} tail = nil length = length * 8 -- convert "byte-counter" to "bit-counter" for j = 4, 11 do local low_byte = length % 256 final_blocks[j] = char(low_byte) length = (length - low_byte) / 256 end final_blocks = table_concat(final_blocks) md5_feed_64(H, final_blocks, 0, #final_blocks) for j = 1, 4 do H[j] = HEX(H[j]) end H = gsub(table_concat(H), "(..)(..)(..)(..)", "%4%3%2%1") end return H end end if message then -- Actually perform calculations and return the MD5 digest of a message return partial(message)() else -- Return function for chunk-by-chunk loading -- User should feed every chunk of input data as single argument to this function and finally get MD5 digest by invoking this function without an argument return partial end end local function sha1(message) -- Create an instance (private objects for current calculation) local H, length, tail = {unpack(md5_sha1_H)}, 0.0, "" local function partial(message_part) if message_part then if tail then length = length + #message_part local offs = 0 if tail ~= "" and #tail + #message_part >= 64 then offs = 64 - #tail sha1_feed_64(H, tail..sub(message_part, 1, offs), 0, 64) tail = "" end local size = #message_part - offs local size_tail = size % 64 sha1_feed_64(H, message_part, offs, size - size_tail) tail = tail..sub(message_part, #message_part + 1 - size_tail) return partial else error("Adding more chunks is not allowed after receiving the result", 2) end else if tail then local final_blocks = {tail, "\128", string_rep("\0", (-9 - length) % 64 + 1)} tail = nil -- Assuming user data length is shorter than (2^53)-9 bytes -- 2^53 bytes = 2^56 bits, so "bit-counter" fits in 7 bytes length = length * (8 / 256^7) -- convert "byte-counter" to "bit-counter" and move decimal point to the left for j = 4, 10 do length = length % 1 * 256 final_blocks[j] = char(floor(length)) end final_blocks = table_concat(final_blocks) sha1_feed_64(H, final_blocks, 0, #final_blocks) for j = 1, 5 do H[j] = HEX(H[j]) end H = table_concat(H) end return H end end if message then -- Actually perform calculations and return the SHA-1 digest of a message return partial(message)() else -- Return function for chunk-by-chunk loading -- User should feed every chunk of input data as single argument to this function and finally get SHA-1 digest by invoking this function without an argument return partial end end local function keccak(block_size_in_bytes, digest_size_in_bytes, is_SHAKE, message) -- "block_size_in_bytes" is multiple of 8 if type(digest_size_in_bytes) ~= "number" then -- arguments in SHAKE are swapped: -- NIST FIPS 202 defines SHAKE(message,num_bits) -- this module defines SHAKE(num_bytes,message) -- it's easy to forget about this swap, hence the check error("Argument 'digest_size_in_bytes' must be a number", 2) end -- Create an instance (private objects for current calculation) local tail, lanes_lo, lanes_hi = "", create_array_of_lanes(), hi_factor_keccak == 0 and create_array_of_lanes() local result --~ pad the input N using the pad function, yielding a padded bit string P with a length divisible by r (such that n = len(P)/r is integer), --~ break P into n consecutive r-bit pieces P0, ..., Pn-1 (last is zero-padded) --~ initialize the state S to a string of b 0 bits. --~ absorb the input into the state: For each block Pi, --~ extend Pi at the end by a string of c 0 bits, yielding one of length b, --~ XOR that with S and --~ apply the block permutation f to the result, yielding a new state S --~ initialize Z to be the empty string --~ while the length of Z is less than d: --~ append the first r bits of S to Z --~ if Z is still less than d bits long, apply f to S, yielding a new state S. --~ truncate Z to d bits local function partial(message_part) if message_part then if tail then local offs = 0 if tail ~= "" and #tail + #message_part >= block_size_in_bytes then offs = block_size_in_bytes - #tail keccak_feed(lanes_lo, lanes_hi, tail..sub(message_part, 1, offs), 0, block_size_in_bytes, block_size_in_bytes) tail = "" end local size = #message_part - offs local size_tail = size % block_size_in_bytes keccak_feed(lanes_lo, lanes_hi, message_part, offs, size - size_tail, block_size_in_bytes) tail = tail..sub(message_part, #message_part + 1 - size_tail) return partial else error("Adding more chunks is not allowed after receiving the result", 2) end else if tail then -- append the following bits to the message: for usual SHA3: 011(0*)1, for SHAKE: 11111(0*)1 local gap_start = is_SHAKE and 31 or 6 tail = tail..(#tail + 1 == block_size_in_bytes and char(gap_start + 128) or char(gap_start)..string_rep("\0", (-2 - #tail) % block_size_in_bytes).."\128") keccak_feed(lanes_lo, lanes_hi, tail, 0, #tail, block_size_in_bytes) tail = nil local lanes_used = 0 local total_lanes = floor(block_size_in_bytes / 8) local qwords = {} local function get_next_qwords_of_digest(qwords_qty) -- returns not more than 'qwords_qty' qwords ('qwords_qty' might be non-integer) -- doesn't go across keccak-buffer boundary -- block_size_in_bytes is a multiple of 8, so, keccak-buffer contains integer number of qwords if lanes_used >= total_lanes then keccak_feed(lanes_lo, lanes_hi, "\0\0\0\0\0\0\0\0", 0, 8, 8) lanes_used = 0 end qwords_qty = floor(math_min(qwords_qty, total_lanes - lanes_used)) if hi_factor_keccak ~= 0 then for j = 1, qwords_qty do qwords[j] = HEX64(lanes_lo[lanes_used + j - 1 + lanes_index_base]) end else for j = 1, qwords_qty do qwords[j] = HEX(lanes_hi[lanes_used + j])..HEX(lanes_lo[lanes_used + j]) end end lanes_used = lanes_used + qwords_qty return gsub(table_concat(qwords, "", 1, qwords_qty), "(..)(..)(..)(..)(..)(..)(..)(..)", "%8%7%6%5%4%3%2%1"), qwords_qty * 8 end local parts = {} -- digest parts local last_part, last_part_size = "", 0 local function get_next_part_of_digest(bytes_needed) -- returns 'bytes_needed' bytes, for arbitrary integer 'bytes_needed' bytes_needed = bytes_needed or 1 if bytes_needed <= last_part_size then last_part_size = last_part_size - bytes_needed local part_size_in_nibbles = bytes_needed * 2 local result = sub(last_part, 1, part_size_in_nibbles) last_part = sub(last_part, part_size_in_nibbles + 1) return result end local parts_qty = 0 if last_part_size > 0 then parts_qty = 1 parts[parts_qty] = last_part bytes_needed = bytes_needed - last_part_size end -- repeats until the length is enough while bytes_needed >= 8 do local next_part, next_part_size = get_next_qwords_of_digest(bytes_needed / 8) parts_qty = parts_qty + 1 parts[parts_qty] = next_part bytes_needed = bytes_needed - next_part_size end if bytes_needed > 0 then last_part, last_part_size = get_next_qwords_of_digest(1) parts_qty = parts_qty + 1 parts[parts_qty] = get_next_part_of_digest(bytes_needed) else last_part, last_part_size = "", 0 end return table_concat(parts, "", 1, parts_qty) end if digest_size_in_bytes < 0 then result = get_next_part_of_digest else result = get_next_part_of_digest(digest_size_in_bytes) end end return result end end if message then -- Actually perform calculations and return the SHA3 digest of a message return partial(message)() else -- Return function for chunk-by-chunk loading -- User should feed every chunk of input data as single argument to this function and finally get SHA3 digest by invoking this function without an argument return partial end end local hex2bin, bin2base64, base642bin do function hex2bin(hex_string) return (gsub(hex_string, "%x%x", function (hh) return char(tonumber(hh, 16)) end )) end local base64_symbols = { ['+'] = 62, ['-'] = 62, [62] = '+', ['/'] = 63, ['_'] = 63, [63] = '/', ['='] = -1, ['.'] = -1, [-1] = '=' } local symbol_index = 0 for j, pair in ipairs{'AZ', 'az', '09'} do for ascii = byte(pair), byte(pair, 2) do local ch = char(ascii) base64_symbols[ch] = symbol_index base64_symbols[symbol_index] = ch symbol_index = symbol_index + 1 end end function bin2base64(binary_string) local result = {} for pos = 1, #binary_string, 3 do local c1, c2, c3, c4 = byte(sub(binary_string, pos, pos + 2)..'\0', 1, -1) result[#result + 1] = base64_symbols[floor(c1 / 4)] ..base64_symbols[c1 % 4 * 16 + floor(c2 / 16)] ..base64_symbols[c3 and c2 % 16 * 4 + floor(c3 / 64) or -1] ..base64_symbols[c4 and c3 % 64 or -1] end return table_concat(result) end function base642bin(base64_string) local result, chars_qty = {}, 3 for pos, ch in gmatch(gsub(base64_string, '%s+', ''), '()(.)') do local code = base64_symbols[ch] if code < 0 then chars_qty = chars_qty - 1 code = 0 end local idx = pos % 4 if idx > 0 then result[-idx] = code else local c1 = result[-1] * 4 + floor(result[-2] / 16) local c2 = (result[-2] % 16) * 16 + floor(result[-3] / 4) local c3 = (result[-3] % 4) * 64 + code result[#result + 1] = sub(char(c1, c2, c3), 1, chars_qty) end end return table_concat(result) end end local block_size_for_HMAC -- this table will be initialized at the end of the module local function pad_and_xor(str, result_length, byte_for_xor) return gsub(str, ".", function(c) return char(XOR_BYTE(byte(c), byte_for_xor)) end )..string_rep(char(byte_for_xor), result_length - #str) end local function hmac(hash_func, key, message) -- Create an instance (private objects for current calculation) local block_size = block_size_for_HMAC[hash_func] if not block_size then error("Unknown hash function", 2) end if #key > block_size then key = hex2bin(hash_func(key)) end local append = hash_func()(pad_and_xor(key, block_size, 0x36)) local result local function partial(message_part) if not message_part then result = result or hash_func(pad_and_xor(key, block_size, 0x5C)..hex2bin(append())) return result elseif result then error("Adding more chunks is not allowed after receiving the result", 2) else append(message_part) return partial end end if message then -- Actually perform calculations and return the HMAC of a message return partial(message)() else -- Return function for chunk-by-chunk loading of a message -- User should feed every chunk of the message as single argument to this function and finally get HMAC by invoking this function without an argument return partial end end local sha = { md5 = md5, -- MD5 sha1 = sha1, -- SHA-1 -- SHA2 hash functions: sha224 = function (message) return sha256ext(224, message) end, -- SHA-224 sha256 = function (message) return sha256ext(256, message) end, -- SHA-256 sha512_224 = function (message) return sha512ext(224, message) end, -- SHA-512/224 sha512_256 = function (message) return sha512ext(256, message) end, -- SHA-512/256 sha384 = function (message) return sha512ext(384, message) end, -- SHA-384 sha512 = function (message) return sha512ext(512, message) end, -- SHA-512 -- SHA3 hash functions: sha3_224 = function (message) return keccak((1600 - 2 * 224) / 8, 224 / 8, false, message) end, -- SHA3-224 sha3_256 = function (message) return keccak((1600 - 2 * 256) / 8, 256 / 8, false, message) end, -- SHA3-256 sha3_384 = function (message) return keccak((1600 - 2 * 384) / 8, 384 / 8, false, message) end, -- SHA3-384 sha3_512 = function (message) return keccak((1600 - 2 * 512) / 8, 512 / 8, false, message) end, -- SHA3-512 shake128 = function (digest_size_in_bytes, message) return keccak((1600 - 2 * 128) / 8, digest_size_in_bytes, true, message) end, -- SHAKE128 shake256 = function (digest_size_in_bytes, message) return keccak((1600 - 2 * 256) / 8, digest_size_in_bytes, true, message) end, -- SHAKE256 -- misc utilities: hmac = hmac, -- HMAC(hash_func, key, message) is applicable to any hash function from this module except SHAKE* hex2bin = hex2bin, -- converts hexadecimal representation to binary string base642bin = base642bin, -- converts base64 representation to binary string bin2base64 = bin2base64, -- converts binary string to base64 representation } block_size_for_HMAC = { [sha.md5] = 64, [sha.sha1] = 64, [sha.sha224] = 64, [sha.sha256] = 64, [sha.sha512_224] = 128, [sha.sha512_256] = 128, [sha.sha384] = 128, [sha.sha512] = 128, [sha.sha3_224] = (1600 - 2 * 224) / 8, [sha.sha3_256] = (1600 - 2 * 256) / 8, [sha.sha3_384] = (1600 - 2 * 384) / 8, [sha.sha3_512] = (1600 - 2 * 512) / 8, } return sha
agpl-3.0
darkdukey/sdkbox-facebook-sample-v2
samples/Lua/TestLua/Resources/luaScript/ActionManagerTest/ActionManagerTest.lua
8
6444
local kTagNode = 0 local kTagGrossini = 1 local kTagSequence = 2 local scheduler = CCDirector:sharedDirector():getScheduler() -------------------------------------------------------------------- -- -- Test1 -- -------------------------------------------------------------------- local function CrashTest() local ret = createTestLayer("Test 1. Should not crash") local child = CCSprite:create(s_pPathGrossini) child:setPosition( VisibleRect:center() ) ret:addChild(child, 1) --Sum of all action's duration is 1.5 second. child:runAction(CCRotateBy:create(1.5, 90)) local arr = CCArray:create() arr:addObject(CCDelayTime:create(1.4)) arr:addObject(CCFadeOut:create(1.1)) child:runAction(CCSequence:create(arr)) arr = CCArray:create() arr:addObject(CCDelayTime:create(1.4)) local function removeThis() ret:getParent():removeChild(ret, true) Helper.nextAction() end arr:addObject(CCCallFunc:create(removeThis)) --After 1.5 second, self will be removed. ret:runAction( CCSequence:create(arr)) return ret end -------------------------------------------------------------------- -- -- LogicTest -- -------------------------------------------------------------------- local function LogicTest() local ret = createTestLayer("Logic test") local grossini = CCSprite:create(s_pPathGrossini) ret:addChild(grossini, 0, 2) grossini:setPosition(VisibleRect:center()) local arr = CCArray:create() arr:addObject(CCMoveBy:create(1, ccp(150,0))) local function bugMe(node) node:stopAllActions() --After this stop next action not working, if remove this stop everything is working node:runAction(CCScaleTo:create(2, 2)) end arr:addObject(CCCallFuncN:create(bugMe)) grossini:runAction( CCSequence:create(arr)); return ret end -------------------------------------------------------------------- -- -- PauseTest -- -------------------------------------------------------------------- local function PauseTest() local ret = createTestLayer("Pause Test") local schedulerEntry = nil local function unpause(dt) scheduler:unscheduleScriptEntry(schedulerEntry) schedulerEntry = nil local node = ret:getChildByTag( kTagGrossini ) local pDirector = CCDirector:sharedDirector() pDirector:getActionManager():resumeTarget(node) end local function onNodeEvent(event) if event == "enter" then local l = CCLabelTTF:create("After 3 seconds grossini should move", "Thonburi", 16) ret:addChild(l) l:setPosition( ccp(VisibleRect:center().x, VisibleRect:top().y-75) ) local grossini = CCSprite:create(s_pPathGrossini) ret:addChild(grossini, 0, kTagGrossini) grossini:setPosition(VisibleRect:center() ) local action = CCMoveBy:create(1, ccp(150,0)) local pDirector = CCDirector:sharedDirector() pDirector:getActionManager():addAction(action, grossini, true) schedulerEntry = scheduler:scheduleScriptFunc(unpause, 3.0, false) elseif event == "exit" then if schedulerEntry ~= nil then scheduler:unscheduleScriptEntry(schedulerEntry) end end end ret:registerScriptHandler(onNodeEvent) return ret end -------------------------------------------------------------------- -- -- RemoveTest -- -------------------------------------------------------------------- local function RemoveTest() local ret = createTestLayer("Remove Test") local l = CCLabelTTF:create("Should not crash", "Thonburi", 16) ret:addChild(l) l:setPosition( ccp(VisibleRect:center().x, VisibleRect:top().y - 75) ) local pMove = CCMoveBy:create(2, ccp(200, 0)) local function stopAction() local pSprite = ret:getChildByTag(kTagGrossini) pSprite:stopActionByTag(kTagSequence) end local pCallback = CCCallFunc:create(stopAction) local arr = CCArray:create() arr:addObject(pMove) arr:addObject(pCallback) local pSequence = CCSequence:create(arr) pSequence:setTag(kTagSequence) local pChild = CCSprite:create(s_pPathGrossini) pChild:setPosition( VisibleRect:center() ) ret:addChild(pChild, 1, kTagGrossini) pChild:runAction(pSequence) return ret end -------------------------------------------------------------------- -- -- ResumeTest -- -------------------------------------------------------------------- local function ResumeTest() local ret = createTestLayer("Resume Test") local schedulerEntry = nil local function resumeGrossini(time) scheduler:unscheduleScriptEntry(schedulerEntry) schedulerEntry = nil local pGrossini = ret:getChildByTag(kTagGrossini) local pDirector = CCDirector:sharedDirector() pDirector:getActionManager():resumeTarget(pGrossini) end local function onNodeEvent(event) if event == "enter" then local l = CCLabelTTF:create("Grossini only rotate/scale in 3 seconds", "Thonburi", 16) ret:addChild(l) l:setPosition( ccp(VisibleRect:center().x, VisibleRect:top().y - 75)) local pGrossini = CCSprite:create(s_pPathGrossini) ret:addChild(pGrossini, 0, kTagGrossini) pGrossini:setPosition(VisibleRect:center()) pGrossini:runAction(CCScaleBy:create(2, 2)) local pDirector = CCDirector:sharedDirector() pDirector:getActionManager():pauseTarget(pGrossini) pGrossini:runAction(CCRotateBy:create(2, 360)) schedulerEntry = scheduler:scheduleScriptFunc(resumeGrossini, 3.0, false) elseif event == "exit" then if schedulerEntry ~= nil then scheduler:unscheduleScriptEntry(schedulerEntry) end end end ret:registerScriptHandler(onNodeEvent) return ret end function ActionManagerTestMain() cclog("ActionManagerTestMain") Helper.index = 1 CCDirector:sharedDirector():setDepthTest(true) local scene = CCScene:create() Helper.createFunctionTable = { CrashTest, LogicTest, PauseTest, RemoveTest, ResumeTest } scene:addChild(CrashTest()) scene:addChild(CreateBackMenuItem()) return scene end
mit
dgcrouse/torch-rnn
test/VanillaRNN_test.lua
17
5462
require 'torch' require 'nn' local gradcheck = require 'util.gradcheck' require 'VanillaRNN' local tests = torch.TestSuite() local tester = torch.Tester() local function check_size(x, dims) tester:asserteq(x:dim(), #dims) for i, d in ipairs(dims) do tester:assert(x:size(i) == d) end end local function forwardTestFactory(N, T, D, H, dtype) dtype = dtype or 'torch.DoubleTensor' return function() local x = torch.randn(N, T, D):type(dtype) local h0 = torch.randn(N, H):type(dtype) local rnn = nn.VanillaRNN(D, H):type(dtype) local Wx = rnn.weight[{{1, D}}]:clone() local Wh = rnn.weight[{{D + 1, D + H}}]:clone() local b = rnn.bias:view(1, H):expand(N, H) local h_naive = torch.zeros(N, T, H):type(dtype) local prev_h = h0 for t = 1, T do local a = torch.mm(x[{{}, t}], Wx) a = a + torch.mm(prev_h, Wh) a = a + b local next_h = torch.tanh(a) h_naive[{{}, t}] = next_h:clone() prev_h = next_h end local h = rnn:forward{h0, x} tester:assertTensorEq(h, h_naive, 1e-7) end end tests.forwardDoubleTest = forwardTestFactory(3, 4, 5, 6) tests.forwardSingletonTest = forwardTestFactory(10, 1, 2, 3) tests.forwardFloatTest = forwardTestFactory(3, 4, 5, 6, 'torch.FloatTensor') function gradCheckTestFactory(N, T, D, H, dtype) dtype = dtype or 'torch.DoubleTensor' return function() local x = torch.randn(N, T, D) local h0 = torch.randn(N, H) local rnn = nn.VanillaRNN(D, H) local h = rnn:forward{h0, x} local dh = torch.randn(#h) rnn:zeroGradParameters() local dh0, dx = unpack(rnn:backward({h0, x}, dh)) local dw = rnn.gradWeight:clone() local db = rnn.gradBias:clone() local function fx(x) return rnn:forward{h0, x} end local function fh0(h0) return rnn:forward{h0, x} end local function fw(w) local old_w = rnn.weight rnn.weight = w local out = rnn:forward{h0, x} rnn.weight = old_w return out end local function fb(b) local old_b = rnn.bias rnn.bias = b local out = rnn:forward{h0, x} rnn.bias = old_b return out end local dx_num = gradcheck.numeric_gradient(fx, x, dh) local dh0_num = gradcheck.numeric_gradient(fh0, h0, dh) local dw_num = gradcheck.numeric_gradient(fw, rnn.weight, dh) local db_num = gradcheck.numeric_gradient(fb, rnn.bias, dh) local dx_error = gradcheck.relative_error(dx_num, dx) local dh0_error = gradcheck.relative_error(dh0_num, dh0) local dw_error = gradcheck.relative_error(dw_num, dw) local db_error = gradcheck.relative_error(db_num, db) tester:assert(dx_error < 1e-5) tester:assert(dh0_error < 1e-5) tester:assert(dw_error < 1e-5) tester:assert(db_error < 1e-5) end end tests.gradCheckTest = gradCheckTestFactory(2, 3, 4, 5) --[[ function tests.scaleTest() local N, T, D, H = 4, 5, 6, 7 local rnn = nn.VanillaRNN(D, H) rnn:zeroGradParameters() local h0 = torch.randn(N, H) local x = torch.randn(N, T, D) local dout = torch.randn(N, T, H) -- Run forward / backward with scale = 0 rnn:forward{h0, x} rnn:backward({h0, x}, dout, 0) tester:asserteq(rnn.gradWeight:sum(), 0) tester:asserteq(rnn.gradBias:sum(), 0) -- Run forward / backward with scale = 2.0 and record gradients rnn:forward{h0, x} rnn:backward({h0, x}, dout, 2.0) local dw2 = rnn.gradWeight:clone() local db2 = rnn.gradBias:clone() -- Run forward / backward with scale = 4.0 and record gradients rnn:zeroGradParameters() rnn:forward{h0, x} rnn:backward({h0, x}, dout, 4.0) local dw4 = rnn.gradWeight:clone() local db4 = rnn.gradBias:clone() -- Gradients after the 4.0 step should be twice as big tester:assertTensorEq(torch.cdiv(dw4, dw2), torch.Tensor(#dw2):fill(2), 1e-6) tester:assertTensorEq(torch.cdiv(db4, db2), torch.Tensor(#db2):fill(2), 1e-6) end --]] --[[ Check that everything works when we don't pass an initial hidden state. By default this should zero the hidden state on each forward pass. --]] function tests.noInitialStateTest() local N, T, D, H = 4, 5, 6, 7 local rnn = nn.VanillaRNN(D, H) -- Run multiple forward passes to make sure the state is zero'd each time for t = 1, 3 do local x = torch.randn(N, T, D) local dout = torch.randn(N, T, H) local out = rnn:forward(x) tester:assert(torch.isTensor(out)) check_size(out, {N, T, H}) local din = rnn:backward(x, dout) tester:assert(torch.isTensor(din)) check_size(din, {N, T, D}) tester:assert(rnn.h0:sum() == 0) end end --[[ If we set rnn.remember_states then the initial hidden state will the the final hidden state from the previous forward pass. Make sure this works! --]] function tests.rememberStateTest() local N, T, D, H = 5, 6, 7, 8 local rnn = nn.VanillaRNN(D, H) rnn.remember_states = true local final_h for t = 1, 3 do local x = torch.randn(N, T, D) local dout = torch.randn(N, T, H) local out = rnn:forward(x) local din = rnn:backward(x, dout) if t > 1 then tester:assertTensorEq(final_h, rnn.h0, 0) end final_h = out[{{}, T}]:clone() end -- After calling resetStates() the initial hidden state should be zero rnn:resetStates() local x = torch.randn(N, T, D) local dout = torch.randn(N, T, H) rnn:forward(x) rnn:backward(x, dout) tester:assertTensorEq(rnn.h0, torch.zeros(N, H), 0) end tester:add(tests) tester:run()
mit
PlayFab/LuaSdk
PlayFabServerSDK/PlayFab/PlayFabProfilesApi.lua
3
6818
-- PlayFab Profiles API -- This is the main file you should require in your game -- All api calls are documented here: https://docs.microsoft.com/gaming/playfab/api-references/ -- Example code: -- local PlayFabProfilesApi = require("PlayFab.PlayFabProfilesApi") -- PlayFabProfilesApi.<ProfilesApiCall>(request, successCallbackFunc, errorCallbackFunc) local IPlayFabHttps = require("PlayFab.IPlayFabHttps") local PlayFabSettings = require("PlayFab.PlayFabSettings") local PlayFabProfilesApi = { settings = PlayFabSettings.settings } -- Gets the global title access policy -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getglobalpolicy -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getglobalpolicy#getglobalpolicyrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getglobalpolicy#getglobalpolicyresponse function PlayFabProfilesApi.GetGlobalPolicy(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/GetGlobalPolicy", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Retrieves the entity's profile. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getprofile -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getprofile#getentityprofilerequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getprofile#getentityprofileresponse function PlayFabProfilesApi.GetProfile(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/GetProfile", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Retrieves the entity's profile. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getprofiles -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getprofiles#getentityprofilesrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getprofiles#getentityprofilesresponse function PlayFabProfilesApi.GetProfiles(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/GetProfiles", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Retrieves the title player accounts associated with the given master player account. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/gettitleplayersfrommasterplayeraccountids -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/gettitleplayersfrommasterplayeraccountids#gettitleplayersfrommasterplayeraccountidsrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/gettitleplayersfrommasterplayeraccountids#gettitleplayersfrommasterplayeraccountidsresponse function PlayFabProfilesApi.GetTitlePlayersFromMasterPlayerAccountIds(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/GetTitlePlayersFromMasterPlayerAccountIds", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Sets the global title access policy -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setglobalpolicy -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setglobalpolicy#setglobalpolicyrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setglobalpolicy#setglobalpolicyresponse function PlayFabProfilesApi.SetGlobalPolicy(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/SetGlobalPolicy", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Updates the entity's language. The precedence hierarchy for communication to the player is Title Player Account -- language, Master Player Account language, and then title default language if the first two aren't set or supported. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setprofilelanguage -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setprofilelanguage#setprofilelanguagerequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setprofilelanguage#setprofilelanguageresponse function PlayFabProfilesApi.SetProfileLanguage(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/SetProfileLanguage", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Sets the profiles access policy -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setprofilepolicy -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setprofilepolicy#setentityprofilepolicyrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setprofilepolicy#setentityprofilepolicyresponse function PlayFabProfilesApi.SetProfilePolicy(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/SetProfilePolicy", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end return PlayFabProfilesApi
apache-2.0
PlayFab/LuaSdk
PlayFabClientSDK/PlayFab/PlayFabProfilesApi.lua
3
6818
-- PlayFab Profiles API -- This is the main file you should require in your game -- All api calls are documented here: https://docs.microsoft.com/gaming/playfab/api-references/ -- Example code: -- local PlayFabProfilesApi = require("PlayFab.PlayFabProfilesApi") -- PlayFabProfilesApi.<ProfilesApiCall>(request, successCallbackFunc, errorCallbackFunc) local IPlayFabHttps = require("PlayFab.IPlayFabHttps") local PlayFabSettings = require("PlayFab.PlayFabSettings") local PlayFabProfilesApi = { settings = PlayFabSettings.settings } -- Gets the global title access policy -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getglobalpolicy -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getglobalpolicy#getglobalpolicyrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getglobalpolicy#getglobalpolicyresponse function PlayFabProfilesApi.GetGlobalPolicy(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/GetGlobalPolicy", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Retrieves the entity's profile. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getprofile -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getprofile#getentityprofilerequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getprofile#getentityprofileresponse function PlayFabProfilesApi.GetProfile(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/GetProfile", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Retrieves the entity's profile. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getprofiles -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getprofiles#getentityprofilesrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/getprofiles#getentityprofilesresponse function PlayFabProfilesApi.GetProfiles(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/GetProfiles", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Retrieves the title player accounts associated with the given master player account. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/gettitleplayersfrommasterplayeraccountids -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/gettitleplayersfrommasterplayeraccountids#gettitleplayersfrommasterplayeraccountidsrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/gettitleplayersfrommasterplayeraccountids#gettitleplayersfrommasterplayeraccountidsresponse function PlayFabProfilesApi.GetTitlePlayersFromMasterPlayerAccountIds(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/GetTitlePlayersFromMasterPlayerAccountIds", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Sets the global title access policy -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setglobalpolicy -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setglobalpolicy#setglobalpolicyrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setglobalpolicy#setglobalpolicyresponse function PlayFabProfilesApi.SetGlobalPolicy(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/SetGlobalPolicy", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Updates the entity's language. The precedence hierarchy for communication to the player is Title Player Account -- language, Master Player Account language, and then title default language if the first two aren't set or supported. -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setprofilelanguage -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setprofilelanguage#setprofilelanguagerequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setprofilelanguage#setprofilelanguageresponse function PlayFabProfilesApi.SetProfileLanguage(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/SetProfileLanguage", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end -- Sets the profiles access policy -- API Method Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setprofilepolicy -- Request Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setprofilepolicy#setentityprofilepolicyrequest -- Response Documentation: https://docs.microsoft.com/rest/api/playfab/profile/account-management/setprofilepolicy#setentityprofilepolicyresponse function PlayFabProfilesApi.SetProfilePolicy(request, onSuccess, onError) if (not PlayFabSettings.settings.titleId or not PlayFabSettings._internalSettings.entityToken) then error("Must call GetEntityToken first, to call this method") end IPlayFabHttps.MakePlayFabApiCall("/Profile/SetProfilePolicy", request, "X-EntityToken", PlayFabSettings._internalSettings.entityToken, onSuccess, onError) end return PlayFabProfilesApi
apache-2.0
opentechinstitute/luci
applications/luci-statistics/luasrc/statistics/rrdtool/definitions/processes.lua
78
2188
--[[ Luci statistics - processes plugin diagram definition (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.statistics.rrdtool.definitions.processes", package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { { title = "%H: Processes", vlabel = "Processes/s", data = { instances = { ps_state = { "sleeping", "running", "paging", "blocked", "stopped", "zombies" } }, options = { ps_state_sleeping = { color = "0000ff" }, ps_state_running = { color = "008000" }, ps_state_paging = { color = "ffff00" }, ps_state_blocked = { color = "ff5000" }, ps_state_stopped = { color = "555555" }, ps_state_zombies = { color = "ff0000" } } } }, { title = "%H: CPU time used by %pi", vlabel = "Jiffies", data = { sources = { ps_cputime = { "syst", "user" } }, options = { ps_cputime__user = { color = "0000ff", overlay = true }, ps_cputime__syst = { color = "ff0000", overlay = true } } } }, { title = "%H: Threads and processes belonging to %pi", vlabel = "Count", detail = true, data = { sources = { ps_count = { "threads", "processes" } }, options = { ps_count__threads = { color = "00ff00" }, ps_count__processes = { color = "0000bb" } } } }, { title = "%H: Page faults in %pi", vlabel = "Pagefaults", detail = true, data = { sources = { ps_pagefaults = { "minflt", "majflt" } }, options = { ps_pagefaults__minflt = { color = "ff0000" }, ps_pagefaults__majflt = { color = "ff5500" } } } }, { title = "%H: Virtual memory size of %pi", vlabel = "Bytes", detail = true, number_format = "%5.1lf%sB", data = { types = { "ps_rss" }, options = { ps_rss = { color = "0000ff" } } } } } end
apache-2.0
opentechinstitute/luci
modules/admin-mini/luasrc/model/cbi/mini/dhcp.lua
82
2998
--[[ 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$ ]]-- local uci = require "luci.model.uci".cursor() local sys = require "luci.sys" local wa = require "luci.tools.webadmin" local fs = require "nixio.fs" m = Map("dhcp", "DHCP") s = m:section(TypedSection, "dhcp", "DHCP-Server") s.anonymous = true s.addremove = false s.dynamic = false s:depends("interface", "lan") enable = s:option(ListValue, "ignore", translate("enable"), "") enable:value(0, translate("enable")) enable:value(1, translate("disable")) start = s:option(Value, "start", translate("First leased address")) start.rmempty = true start:depends("ignore", "0") limit = s:option(Value, "limit", translate("Number of leased addresses"), "") limit:depends("ignore", "0") function limit.cfgvalue(self, section) local value = Value.cfgvalue(self, section) if value then return tonumber(value) + 1 end end function limit.write(self, section, value) value = tonumber(value) - 1 return Value.write(self, section, value) end limit.rmempty = true time = s:option(Value, "leasetime") time:depends("ignore", "0") time.rmempty = true local leasefn, leasefp, leases uci:foreach("dhcp", "dnsmasq", function(section) leasefn = section.leasefile end ) local leasefp = leasefn and fs.access(leasefn) and io.lines(leasefn) if leasefp then leases = {} for lease in leasefp do table.insert(leases, luci.util.split(lease, " ")) end end if leases then v = m:section(Table, leases, translate("Active Leases")) name = v:option(DummyValue, 4, translate("Hostname")) function name.cfgvalue(self, ...) local value = DummyValue.cfgvalue(self, ...) return (value == "*") and "?" or value end ip = v:option(DummyValue, 3, translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address")) mac = v:option(DummyValue, 2, translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address")) ltime = v:option(DummyValue, 1, translate("Leasetime remaining")) function ltime.cfgvalue(self, ...) local value = DummyValue.cfgvalue(self, ...) return wa.date_format(os.difftime(tonumber(value), os.time())) end end s2 = m:section(TypedSection, "host", translate("Static Leases")) s2.addremove = true s2.anonymous = true s2.template = "cbi/tblsection" name = s2:option(Value, "name", translate("Hostname")) mac = s2:option(Value, "mac", translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address")) ip = s2:option(Value, "ip", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address")) sys.net.arptable(function(entry) ip:value(entry["IP address"]) mac:value( entry["HW address"], entry["HW address"] .. " (" .. entry["IP address"] .. ")" ) end) return m
apache-2.0
opentechinstitute/luci
libs/nixio/docsrc/nixio.UnifiedIO.lua
157
5891
--- Unified high-level I/O utility API for Files, Sockets and TLS-Sockets. -- These functions are added to the object function tables by doing <strong> -- require "nixio.util"</strong>, can be used on all nixio IO Descriptors and -- are based on the shared low-level read() and write() functions. -- @cstyle instance module "nixio.UnifiedIO" --- Test whether the I/O-Descriptor is a socket. -- @class function -- @name UnifiedIO.is_socket -- @return boolean --- Test whether the I/O-Descriptor is a TLS socket. -- @class function -- @name UnifiedIO.is_tls_socket -- @return boolean --- Test whether the I/O-Descriptor is a file. -- @class function -- @name UnifiedIO.is_file -- @return boolean --- Read a block of data and wait until all data is available. -- @class function -- @name UnifiedIO.readall -- @usage This function uses the low-level read function of the descriptor. -- @usage If the length parameter is ommited, this function returns all data -- that can be read before an end-of-file, end-of-stream, connection shutdown -- or similar happens. -- @usage If the descriptor is non-blocking this function may fail with EAGAIN. -- @param length Bytes to read (optional) -- @return data that was successfully read if no error occured -- @return - reserved for error code - -- @return - reserved for error message - -- @return data that was successfully read even if an error occured --- Write a block of data and wait until all data is written. -- @class function -- @name UnifiedIO.writeall -- @usage This function uses the low-level write function of the descriptor. -- @usage If the descriptor is non-blocking this function may fail with EAGAIN. -- @param block Bytes to write -- @return bytes that were successfully written if no error occured -- @return - reserved for error code - -- @return - reserved for error message - -- @return bytes that were successfully written even if an error occured --- Create a line-based iterator. -- Lines may end with either \n or \r\n, these control chars are not included -- in the return value. -- @class function -- @name UnifiedIO.linesource -- @usage This function uses the low-level read function of the descriptor. -- @usage <strong>Note:</strong> This function uses an internal buffer to read -- ahead. Do NOT mix calls to read(all) and the returned iterator. If you want -- to stop reading line-based and want to use the read(all) functions instead -- you can pass "true" to the iterator which will flush the buffer -- and return the bufferd data. -- @usage If the limit parameter is ommited, this function uses the nixio -- buffersize (8192B by default). -- @usage If the descriptor is non-blocking the iterator may fail with EAGAIN. -- @usage The iterator can be used as an LTN12 source. -- @param limit Line limit -- @return Line-based Iterator --- Create a block-based iterator. -- @class function -- @name UnifiedIO.blocksource -- @usage This function uses the low-level read function of the descriptor. -- @usage The blocksize given is only advisory and to be seen as an upper limit, -- if an underlying read returns less bytes the chunk is nevertheless returned. -- @usage If the limit parameter is ommited, the iterator returns data -- until an end-of-file, end-of-stream, connection shutdown or similar happens. -- @usage The iterator will not buffer so it is safe to mix with calls to read. -- @usage If the descriptor is non-blocking the iterator may fail with EAGAIN. -- @usage The iterator can be used as an LTN12 source. -- @param blocksize Advisory blocksize (optional) -- @param limit Amount of data to consume (optional) -- @return Block-based Iterator --- Create a sink. -- This sink will simply write all data that it receives and optionally -- close the descriptor afterwards. -- @class function -- @name UnifiedIO.sink -- @usage This function uses the writeall function of the descriptor. -- @usage If the descriptor is non-blocking the sink may fail with EAGAIN. -- @usage The iterator can be used as an LTN12 sink. -- @param close_when_done (optional, boolean) -- @return Sink --- Copy data from the current descriptor to another one. -- @class function -- @name UnifiedIO.copy -- @usage This function uses the blocksource function of the source descriptor -- and the sink function of the target descriptor. -- @usage If the limit parameter is ommited, data is copied -- until an end-of-file, end-of-stream, connection shutdown or similar happens. -- @usage If the descriptor is non-blocking the function may fail with EAGAIN. -- @param fdout Target Descriptor -- @param size Bytes to copy (optional) -- @return bytes that were successfully written if no error occured -- @return - reserved for error code - -- @return - reserved for error message - -- @return bytes that were successfully written even if an error occured --- Copy data from the current descriptor to another one using kernel-space -- copying if possible. -- @class function -- @name UnifiedIO.copyz -- @usage This function uses the sendfile() syscall to copy the data or the -- blocksource function of the source descriptor and the sink function -- of the target descriptor as a fallback mechanism. -- @usage If the limit parameter is ommited, data is copied -- until an end-of-file, end-of-stream, connection shutdown or similar happens. -- @usage If the descriptor is non-blocking the function may fail with EAGAIN. -- @param fdout Target Descriptor -- @param size Bytes to copy (optional) -- @return bytes that were successfully written if no error occured -- @return - reserved for error code - -- @return - reserved for error message - -- @return bytes that were successfully written even if an error occured --- Close the descriptor. -- @class function -- @name UnifiedIO.close -- @usage If the descriptor is a TLS-socket the underlying descriptor is -- closed without touching the TLS connection. -- @return true
apache-2.0
jithumon/Kochu
plugins/onmessage.lua
8
8605
local config = require 'config' local u = require 'utilities' local api = require 'methods' local plugin = {} local function max_reached(chat_id, user_id) local max = tonumber(db:hget('chat:'..chat_id..':warnsettings', 'mediamax')) or 2 local n = tonumber(db:hincrby('chat:'..chat_id..':mediawarn', user_id, 1)) if n >= max then return true, n, max else return false, n, max end end local function is_ignored(chat_id, msg_type) local hash = 'chat:'..chat_id..':floodexceptions' local status = (db:hget(hash, msg_type)) or 'no' if status == 'yes' then return true elseif status == 'no' then return false end end local function is_flooding_funct(msg) local spamhash = 'spam:'..msg.chat.id..':'..msg.from.id local msgs = tonumber(db:get(spamhash)) or 1 local max_msgs = tonumber(db:hget('chat:'..msg.chat.id..':flood', 'MaxFlood')) or 5 if msg.cb then max_msgs = 15 end local max_time = 5 db:setex(spamhash, max_time, msgs+1) if msgs > max_msgs then return true, msgs, max_msgs else return false end end local function is_blocked(id) if db:sismember('bot:blocked', id) then return true else return false end end local function is_whitelisted(chat_id, text) local set = ('chat:%d:whitelist'):format(chat_id) local links = db:smembers(set) if links and next(links) then for i=1, #links do if text:match(links[i]:gsub('%-', '%%-')) then --print('Whitelist:', links[i]) return true end end end end function plugin.onEveryMessage(msg) if not msg.inline then local msg_type = 'text' if msg.forward_from or msg.forward_from_chat then msg_type = 'forward' end if msg.media_type then msg_type = msg.media_type end if not is_ignored(msg.chat.id, msg_type) and not msg.edited then local is_flooding, msgs_sent, msgs_max = is_flooding_funct(msg) if is_flooding then local status = (db:hget('chat:'..msg.chat.id..':settings', 'Flood')) or config.chat_settings['settings']['Flood'] if status == 'on' and not msg.cb and not msg.from.mod then --if the status is on, and the user is not an admin, and the message is not a callback, then: local action = db:hget('chat:'..msg.chat.id..':flood', 'ActionFlood') local name = u.getname_final(msg.from) local res, message --try to kick or ban if action == 'ban' then res = api.banUser(msg.chat.id, msg.from.id) else res = api.kickUser(msg.chat.id, msg.from.id) end --if kicked/banned, send a message if res then local log_hammered = action if msgs_sent == (msgs_max + 1) then --send the message only if it's the message after the first message flood. Repeat after 5 if action == 'ban' then message = _("%s <b>banned</b> for flood!"):format(name) else message = _("%s <b>kicked</b> for flood!"):format(name) end api.sendMessage(msg.chat.id, message, 'html') u.logEvent('flood', msg, {hammered = log_hammered}) end end end if msg.cb then --api.answerCallbackQuery(msg.cb_id, _("‼️ Please don't abuse the keyboard, requests will be ignored")) --avoid to hit the limits with answerCallbackQuery end return false --if an user is spamming, don't go through plugins end end if msg.media and msg.chat.type ~= 'private' and not msg.cb and not msg.edited then local media = msg.media_type local hash = 'chat:'..msg.chat.id..':media' local media_status = (db:hget(hash, media)) or 'ok' local out if media_status ~= 'ok' then if not msg.from.mod then --ignore mods and above local whitelisted if media == 'link' then whitelisted = is_whitelisted(msg.chat.id, msg.text) end if not whitelisted then local status local name = u.getname_final(msg.from) local max_reached_var, n, max = max_reached(msg.chat.id, msg.from.id) if max_reached_var then --max num reached. Kick/ban the user status = (db:hget('chat:'..msg.chat.id..':warnsettings', 'mediatype')) or config.chat_settings['warnsettings']['mediatype'] --try to kick/ban if status == 'kick' then res = api.kickUser(msg.chat.id, msg.from.id) elseif status == 'ban' then res = api.banUser(msg.chat.id, msg.from.id) end if res then --kick worked db:hdel('chat:'..msg.chat.id..':mediawarn', msg.from.id) --remove media warns local message if status == 'ban' then message = _("%s <b>banned</b>: media sent not allowed!\n❗️ <code>%d/%d</code>"):format(name, n, max) else message = _("%s <b>kicked</b>: media sent not allowed!\n❗️ <code>%d/%d</code>"):format(name, n, max) end api.sendMessage(msg.chat.id, message, 'html') end else --max num not reached -> warn local message = _("%s, this type of media is <b>not allowed</b> in this chat.\n(<code>%d/%d</code>)"):format(name, n, max) api.sendReply(msg, message, 'html') end u.logEvent('mediawarn', msg, {warns = n, warnmax = max, media = _(media), hammered = status}) end end end end local rtl_status = (db:hget('chat:'..msg.chat.id..':char', 'Rtl')) or 'allowed' if rtl_status == 'kick' or rtl_status == 'ban' then local rtl = '‮' local last_name = 'x' if msg.from.last_name then last_name = msg.from.last_name end local check = msg.text:find(rtl..'+') or msg.from.first_name:find(rtl..'+') or last_name:find(rtl..'+') if check ~= nil and not msg.from.mod then local name = u.getname_final(msg.from) local res if rtl_status == 'kick' then res = api.kickUser(msg.chat.id, msg.from.id) elseif status == 'ban' then res = api.banUser(msg.chat.id, msg.from.id) end if res then local message = _("%s <b>kicked</b>: RTL character in names / messages not allowed!"):format(name) if rtl_status == 'ban' then message = _("%s <b>banned</b>: RTL character in names / messages not allowed!"):format(name) end api.sendMessage(msg.chat.id, message, 'html') return false -- not execute command already kicked out and not welcome him end end end if msg.text and msg.text:find('([\216-\219][\128-\191])') then local arab_status = (db:hget('chat:'..msg.chat.id..':char', 'Arab')) or 'allowed' if arab_status == 'kick' or arab_status == 'ban' then if not msg.from.mod then local name = u.getname_final(msg.from) local res if arab_status == 'kick' then res = api.kickUser(msg.chat.id, msg.from.id) elseif arab_status == 'ban' then res = api.banUser(msg.chat.id, msg.from.id) end if res then local message = _("%s <b>kicked</b>: arab/persian message detected!"):format(name) if arab_status == 'ban' then message = _("%s <b>banned</b>: arab/persian message detected!"):format(name) end api.sendMessage(msg.chat.id, message, 'html') return false end end end end end --if not msg.inline then [if statement closed] if is_blocked(msg.from.id) then --ignore blocked users return false --if an user is blocked, don't go through plugins end --don't return false for edited messages: the antispam need to process them return true end return plugin
gpl-2.0
mehrdadneyazy78/-S-Bot
plugins/isX.lua
605
2031
local https = require "ssl.https" local ltn12 = require "ltn12" local function request(imageUrl) -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://sphirelabs-advanced-porn-nudity-and-adult-content-detection.p.mashape.com/v1/get/index.php?" local parameters = "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local respbody = {} local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local body, code, headers, status = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" print(data) if jsonBody["Error Occured"] ~= nil then response = response .. jsonBody["Error Occured"] elseif jsonBody["Is Porn"] == nil or jsonBody["Reason"] == nil then response = response .. "I don't know if that has adult content or not." else if jsonBody["Is Porn"] == "True" then response = response .. "Beware!\n" end response = response .. jsonBody["Reason"] end return jsonBody["Is Porn"], response end local function run(msg, matches) local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end local isPorn, result = parseData(data) return result end return { description = "Does this photo contain adult content?", usage = { "!isx [url]", "!isporn [url]" }, patterns = { "^!is[x|X] (.*)$", "^!is[p|P]orn (.*)$" }, run = run }
gpl-2.0
mobarski/sandbox
scite/old/wscite_zzz/lexers/notused/ps.lua
5
1630
-- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE. -- Postscript LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local M = {_NAME = 'ps'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local comment = token(l.COMMENT, '%' * l.nonnewline^0) -- Strings. local arrow_string = l.delimited_range('<>') local nested_string = l.delimited_range('()', false, false, true) local string = token(l.STRING, arrow_string + nested_string) -- Numbers. local number = token(l.NUMBER, l.float + l.integer) -- Keywords. local keyword = token(l.KEYWORD, word_match{ 'pop', 'exch', 'dup', 'copy', 'roll', 'clear', 'count', 'mark', 'cleartomark', 'counttomark', 'exec', 'if', 'ifelse', 'for', 'repeat', 'loop', 'exit', 'stop', 'stopped', 'countexecstack', 'execstack', 'quit', 'start', 'true', 'false', 'NULL' }) -- Functions. local func = token(l.FUNCTION, word_match{ 'add', 'div', 'idiv', 'mod', 'mul', 'sub', 'abs', 'ned', 'ceiling', 'floor', 'round', 'truncate', 'sqrt', 'atan', 'cos', 'sin', 'exp', 'ln', 'log', 'rand', 'srand', 'rrand' }) -- Identifiers. local word = (l.alpha + '-') * (l.alnum + '-')^0 local identifier = token(l.IDENTIFIER, word) -- Operators. local operator = token(l.OPERATOR, S('[]{}')) -- Labels. local label = token(l.LABEL, '/' * word) M._rules = { {'whitespace', ws}, {'keyword', keyword}, {'function', func}, {'identifier', identifier}, {'string', string}, {'comment', comment}, {'number', number}, {'label', label}, {'operator', operator}, } return M
mit
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/script/framework/extends/UISlider.lua
57
1392
--[[ Copyright (c) 2011-2014 chukong-inc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local Slider = ccui.Slider function Slider:onEvent(callback) self:addEventListener(function(sender, eventType) local event = {} if eventType == 0 then event.name = "ON_PERCENTAGE_CHANGED" end event.target = sender callback(event) end) return self end
mit
aminaleahmad/merbots
plugins/id.lua
11
5732
--[[ Print user identification/informations by replying their post or by providing their username or print_name. !id <text> is the least reliable because it will scan trough all of members and print all member with <text> in their print_name. chat_info can be displayed on group, send it into PM, or save as file then send it into group or PM. --]] do local function scan_name(extra, success, result) local founds = {} for k,member in pairs(result.members) do if extra.name then gp_member = extra.name fields = {'first_name', 'last_name', 'print_name'} elseif extra.user then gp_member = string.gsub(extra.user, '@', '') fields = {'username'} end for k,field in pairs(fields) do if member[field] and type(member[field]) == 'string' then if member[field]:match(gp_member) then founds[tostring(member.id)] = member end end end end if next(founds) == nil then -- Empty table send_large_msg(extra.receiver, (extra.name or extra.user)..' not found on this chat.') else local text = '' for k,user in pairs(founds) do text = text..'Name: '..(user.first_name or '')..' '..(user.last_name or '')..'\n' ..'First name: '..(user.first_name or '')..'\n' ..'Last name: '..(user.last_name or '')..'\n' ..'User name: @'..(user.username or '')..'\n' ..'ID: '..(user.id or '')..'\n\n' end send_large_msg(extra.receiver, text) end end local function action_by_reply(extra, success, result) local text = 'Name: '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n' ..'First name: '..(result.from.first_name or '')..'\n' ..'Last name: '..(result.from.last_name or '')..'\n' ..'User name: @'..(result.from.username or '')..'\n' ..'ID: '..result.from.id send_large_msg(extra.receiver, text) end local function returnids(extra, success, result) local chat_id = extra.msg.to.id local text = '['..result.id..'] '..result.title..'.\n' ..result.members_num..' members.\n\n' i = 0 for k,v in pairs(result.members) do i = i+1 if v.username then user_name = ' @'..v.username else user_name = '' end text = text..i..'. ['..v.id..'] '..user_name..' '..(v.first_name or '')..(v.last_name or '')..'\n' end if extra.matches == 'pm' then send_large_msg('user#id'..extra.msg.from.id, text) elseif extra.matches == 'txt' or extra.matches == 'pmtxt' then local textfile = '/tmp/chat_info_'..chat_id..'_'..os.date("%y%m%d.%H%M%S")..'.txt' local file = io.open(textfile, 'w') file:write(text) file:flush() file:close() if extra.matches == 'txt' then send_document('chat#id'..chat_id, textfile, rmtmp_cb, {file_path=textfile}) elseif extra.matches == 'pmtxt' then send_document('user#id'..extra.msg.from.id, textfile, rmtmp_cb, {file_path=textfile}) end elseif not extra.matches then send_large_msg('chat#id'..chat_id, text) end end local function run(msg, matches) local receiver = get_receiver(msg) if is_chat_msg(msg) then if msg.text == '!id' then if msg.reply_id then if is_mod(msg) then msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver}) end else local text = 'Name: '..(msg.from.first_name or '')..' '..(msg.from.last_name or '')..'\n' ..'First name: '..(msg.from.first_name or '')..'\n' ..'Last name: '..(msg.from.last_name or '')..'\n' ..'User name: @'..(msg.from.username or '')..'\n' ..'ID: ' .. msg.from.id local text = text..'\n\nYou are in group ' ..msg.to.title..' (ID: '..msg.to.id..')' return text end elseif is_mod(msg) and matches[1] == 'chat' then if matches[2] == 'pm' or matches[2] == 'txt' or matches[2] == 'pmtxt' then chat_info(receiver, returnids, {msg=msg, matches=matches[2]}) else chat_info(receiver, returnids, {msg=msg}) end elseif is_mod(msg) and string.match(matches[1], '^@.+$') then chat_info(receiver, scan_name, {receiver=receiver, user=matches[1]}) elseif is_mod(msg) and string.gsub(matches[1], ' ', '_') then user = string.gsub(matches[1], ' ', '_') chat_info(receiver, scan_name, {receiver=receiver, name=matches[1]}) end else return 'You are not in a group.' end end return { description = 'Know your id or the id of a chat members.', usage = { user = { '!id: Return your ID and the chat id if you are in one.' }, moderator = { '!id : Return ID of replied user if used by reply.', '!id chat : Return the IDs of the current chat members.', '!id chat txt : Return the IDs of the current chat members and send it as text file.', '!id chat pm : Return the IDs of the current chat members and send it to PM.', '!id chat pmtxt : Return the IDs of the current chat members, save it as text file and then send it to PM.', '!id <id> : Return the IDs of the <id>.', '!id @<user_name> : Return the member @<user_name> ID from the current chat.', '!id <text> : Search for users with <text> on first_name, last_name, or print_name on current chat.' }, }, patterns = { "^!id$", "^!id (chat) (.*)$", "^!id (.*)$" }, run = run } end
gpl-2.0
Zefiros-Software/ZPM
src/cli/github.lua
1
1252
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- 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. -- -- @endcond --]] newoption { trigger = "github-token", description = "Uses the given GitHub token" }
mit
robbie-cao/mooncake
fs-detect.lua
1
1715
#!/usr/bin/env lua pl = require("pl") posix = require("posix") local uv = require("luv") local path = arg[1] or "." local fdir = posix.dir(path) local fset = Set(fdir) --[[ pretty.dump(fdir) pretty.dump(fset) --]] local fse = uv.new_fs_event() assert(uv.fs_event_start(fse, path, { -- "watch_entry" = true, -- "stat" = true, recursive = false }, function (err, fname, status) if err then print("Error " .. err) else --[[ print(string.format("Change detected in %s", uv.fs_event_getpath(fse))) --]] if status["change"] == true then --[[ print("change: " .. (fname and fname or "")) --]] elseif status["rename"] == true then --[[ print("rename: " .. (fname and fname or "")) --]] fdir2 = posix.dir(path) fset2 = Set(fdir2) removed = fset - fset2 added = fset2 - fset if #removed > 0 then print("Node removed:") --[[ pretty.dump(removed) --]] for i = 1, #removed do print(Set.values(removed)[i]) end end if #added > 0 then print("Node added:") --[[ pretty.dump(added) --]] for i = 1, #added do print(Set.values(added)[i]) end end -- Store current file nodes for next comparison fset = fset2 else print("unknow: " .. (fname and fname or "")) end end end)) uv.run("default") uv.loop_close()
mit
dmccuskey/dmc-facebook
dmc_corona/dmc_facebook.lua
4
25261
--====================================================================-- -- dmc_facebook.lua -- -- -- by David McCuskey -- Documentation: http://docs.davidmccuskey.com/display/docs/dmc_facebook.lua --====================================================================-- --[[ Copyright (C) 2013 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 = "1.0.0" --====================================================================-- -- Setup DMC Library Config --====================================================================-- local Utils = {} -- make copying from dmc_utils easier --== Start dmc_utils copies ==-- Utils.IO_ERROR = "io_error" Utils.IO_SUCCESS = "io_success" function Utils.extend( fromTable, toTable ) function _extend( fT, tT ) for k,v in pairs( fT ) do if type( fT[ k ] ) == "table" and type( tT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], tT[ k ] ) elseif type( fT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], {} ) else tT[ k ] = v end end return tT end return _extend( fromTable, toTable ) end function Utils.readFile( file_path, options ) -- print( "Utils.readFile", file_path ) options = options or {} if options.lines == nil then options.lines = true end local contents -- either string or table of strings local ret_val = {} -- an array, [ status, content ] if file_path == nil then local ret_val = { Utils.IO_ERROR, "file path is NIL" } else local fh, reason = io.open( file_path, "r" ) if fh == nil then print("ERROR: datastore load settings: " .. tostring( reason ) ) ret_val = { Utils.IO_ERROR, reason } else if options.lines == false then -- read contents in one big string contents = fh:read( '*all' ) else -- read all contents of file into a table contents = {} for line in fh:lines() do table.insert( contents, line ) end end ret_val = { Utils.IO_SUCCESS, contents } io.close( fh ) end -- fh == nil end -- file_path == nil return ret_val[1], ret_val[2] end function Utils.readConfigFile( file_path, options ) -- print( "Utils.readConfigFile", file_path ) options = options or {} options.lines = true options.default_section = options.default_section or nil -- no default here local status, contents = Utils.readFile( file_path, options ) if status == Utils.IO_ERROR then return nil end local data = {} local curr_section = options.default_section if curr_section ~= nil and not data[curr_section] then data[curr_section]={} end local function processSectionLine( line ) local key key = line:match( "%[([%w_]+)%]" ) key = string.lower( key ) -- use only lowercase inside of module return key end local function processKeyLine( line ) local k, v, key, val -- print( line ) k, v = line:match( "([%w_]+)%s*=%s*([%w_]+)" ) -- print( tostring( k ) .. " = " .. tostring( v ) ) key = string.lower( k ) -- use only lowercase inside of module val = tonumber( v ) if val == nil then val = v end return key, val end local is_valid = true local is_section local key, val for _, line in ipairs( contents ) do -- print( line ) is_section = ( string.find( line, '%[%w', 1, false ) == 1 ) is_key = ( string.find( line, '%w', 1, false ) == 1 ) -- print( is_section, is_key ) if is_section then curr_section = processSectionLine( line ) if not data[curr_section] then data[curr_section]={} end elseif is_key and curr_section ~= nil then key, val = processKeyLine( line ) data[curr_section][key] = val end end return data end --== End dmc_utils copies ==-- local DMC_LIBRARY_DEFAULTS = { location = '' } local dmc_lib_data, dmc_lib_info, dmc_lib_location -- no module has yet tried to read in a config file if _G.__dmc_library == nil then local config_file, file_path, config_data config_file = 'dmc_library.cfg' file_path = system.pathForFile( config_file, system.ResourceDirectory ) config_data = Utils.readConfigFile( file_path, { default_section='dmc_library' } ) if config_data == nil then _G.__dmc_library = {} else _G.__dmc_library = config_data end dmc_lib_data = _G.__dmc_library dmc_lib_info = dmc_lib_data.dmc_library or {} if dmc_lib_info.location ~= nil and dmc_lib_info.location ~= '' then dmc_lib_location = dmc_lib_info.location .. '.' else dmc_lib_location = '' end end dmc_lib_data = dmc_lib_data or _G.__dmc_library dmc_lib_info = dmc_lib_info or dmc_lib_data.dmc_library dmc_lib_location = dmc_lib_location or dmc_lib_info.location --====================================================================-- -- Setup DMC Facebook Config --====================================================================-- local DMC_FACEBOOK_DEFAULTS = { } local dmc_facebook_data = dmc_lib_data.dmc_facebook or {} dmc_facebook_data = Utils.extend( dmc_facebook_data, DMC_FACEBOOK_DEFAULTS ) --====================================================================-- -- Imports --====================================================================-- local UrlLib = require( 'socket.url' ) local json = require( 'json' ) local Objects = require( dmc_lib_location .. 'dmc_objects' ) -- only needed for debugging -- Utils = require( dmc_lib_location .. 'dmc_utils' ) --====================================================================-- -- Setup, Constants --====================================================================-- -- setup some aliases to make code cleaner local inheritsFrom = Objects.inheritsFrom local CoronaBase = Objects.CoronaBase local Facebook_Singleton -- ref to our singleton --====================================================================-- -- Support Methods --====================================================================-- --[[ the functions url_encode() and url_decode() are borrowed from: http://lua-users.org/wiki/StringRecipes --]] function url_encode(str) if (str) then str = string.gsub (str, "\n", "\r\n") str = string.gsub (str, "([^%w %-%_%.%~])", function (c) return string.format ("%%%02X", string.byte(c)) end) str = string.gsub (str, " ", "+") end return str end function url_decode(str) str = string.gsub (str, "+", " ") str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end) str = string.gsub (str, "\r\n", "\n") return str end -- parse_query() -- splits an HTTP query string (eg, 'one=1&two=2' ) into its components -- -- @param str string containing url-type key/value pairs -- @returns a table with the key/value pairs -- function parse_query(str) local t = {} if str ~= nil then for k, v in string.gmatch( str, "([^=&]+)=([^=&]+)") do t[k] = v end end return t end function create_query( tbl ) local str = '' for k,v in pairs( tbl ) do if str ~= '' then str = str .. '&' end str = str .. tostring( k ) .. '=' .. url_encode( tostring(v) ) end return str end --====================================================================-- -- Facebook Object --====================================================================-- local Facebook = inheritsFrom( CoronaBase ) --== General Constants ==-- Facebook.BASIC_PERMS = 'basic_info' -- Facebook basic permissions string Facebook.MOBILE_VIEW = 'mobile_web_view' Facebook.DESKTOP_VIEW = 'desktop_web_view' Facebook.VIEW_PARAMS = { x=0, y=0, w=display.contentWidth, h=display.contentHeight } Facebook.GRAPH_URL = 'https://graph.facebook.com' Facebook.AUTH_URLS = { desktop_web_view='https://www.facebook.com/dialog/oauth', mobile_web_view='https://m.facebook.com/dialog/oauth' } Facebook.LOGIN_URLS = { desktop_web_view='https://www.facebook.com/login.php', mobile_web_view='https://m.facebook.com/login.php' } Facebook.LOGOUT_URLS = { desktop_web_view='https://www.facebook.com/logout.php', mobile_web_view='https://m.facebook.com/logout.php' } -- list of errors which we can throw Facebook.DMC_ERROR_TYPE = 'dmc_facebook' Facebook.DMC_ERRORS = { no_login={ code=5, message='No Valid Login Available', } } --== Event Constants ==-- Facebook.EVENT = 'dmc_facebook_plugin_event' Facebook.LOGIN = 'login_query' Facebook.REQUEST = 'request_query' Facebook.GET_PERMISSIONS = 'get_permissions_query' Facebook.REQUEST_PERMISSIONS = 'request_permissions_query' Facebook.REMOVE_PERMISSIONS = 'remove_permissions_query' Facebook.POST_MESSAGE = 'post_message_query' Facebook.POST_LINK = 'post_link_query' Facebook.LOGOUT = 'logout_query' Facebook.POST_MESSAGE_PATH = 'me/feed' Facebook.ACCESS_TOKEN = 'acces_token_changed' --== Start: Setup DMC Objects function Facebook:_init( params ) --print( "Facebook:_init" ) self:superCall( "_init" ) --==-- --== Create Properties ==-- self._params = params self._view_type = '' -- the type of login view to request self._view_params = nil -- the parameters for the webview self._app_id = nil -- the ID of the Facebook app, string self._app_url = nil -- the URL for the Facebook app, string self._app_token_url = nil -- the URL to get app token self._app_url_parts = nil -- table of pieces, self._app_url -- login variables self._had_login = true -- if we had previous login state, in browser self._had_permissions = true -- if we had previous permissions, in browser -- the access token handed back from Facebook API -- this can be written internally via self._access_token -- or read EXTERNALLY via self.access_token self._token = nil --== Display Groups ==-- --== Object References ==-- self._webview = nil -- the webview created to display web login end --== END: Setup DMC Objects --== Public Methods / API ==-- function Facebook.__getters:has_login() -- print( "Facebook.__getters:has_login" ) return ( self._token ~= nil ) end function Facebook.__getters:access_token() -- print( "Facebook.__getters:access_token" ) return self._token end function Facebook:init( app_id, app_url, params ) -- print( "Facebook:init", app_id, app_url ) params = params or {} if params.view_type == nil then params.view_type = Facebook.MOBILE_VIEW end if params.view_params == nil then params.view_params = Facebook.VIEW_PARAMS end self._view_type = params.view_type self._view_params = params.view_params self._app_id = app_id self._app_url = app_url self._app_token_url = params.app_token_url self._app_url_parts = UrlLib.parse( self._app_url ) end -- login() -- login to facebook api service -- -- @param permissions: array of permission strings to request for user -- @param params: table with additional login parameters -- -- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/ -- function Facebook:login( permissions, params ) -- print( "Facebook:login" ) permissions = permissions or {} params = params or {} if params.view_type == nil then params.view_type = self._view_type end if params.view_params == nil then params.view_params = self._view_params end -- reset these for the login call self._had_login = true self._had_permissions = true -- make sure to set basic permissions, according to Facebook spec -- TODO: don't blindly add to front, do search in array to see if it exists if permissions[1] ~= Facebook.BASIC_PERMS then -- print( "adding basic permissions" ) table.insert( permissions, 1, Facebook.BASIC_PERMS ) end local url, callback, webview url = Facebook.AUTH_URLS[ params.view_type ] url = url .. '?' .. 'client_id=' .. self._app_id url = url .. '&' .. 'redirect_uri=' .. url_encode( self._app_url ) url = url .. '&' .. 'response_type=' .. 'token' url = url .. '&' .. 'display=' .. 'touch' if #permissions > 0 then url = url .. '&' .. 'scope=' .. table.concat( permissions, ",") end -- print( url ) callback = self:createCallback( self._loginRequest_handler ) webview = self:_createWebView( params.view_params, callback ) webview:request( url ) end function Facebook:cancelLogin() self:_removeWebView() end -- _loginRequest_handler() -- handler for the login request -- it's a private method, but placed here in file for convenience -- function Facebook:_loginRequest_handler( event ) -- print( "Facebook:_loginRequest_handler", event ) -- print( event.url, event.type ) -- print( event.type, event.errorMessage ) --== setup request handlers local success_f, error_f success_f = function( value ) -- print( "Login: Success Handler" ) self._access_token = value local evt = { access_token=value, had_login = self._had_login, had_permissions = self._had_permissions } self:_dispatchEvent( Facebook.LOGIN, evt ) end error_f = function( response ) -- print( "Login: Error Handler" ) self._access_token = nil local evt = { is_error = true, error = response.error, error_reason = response.error_reason, error_description = response.error_description, } self:_dispatchEvent( Facebook.LOGIN, evt ) end -- auth process has several redirects -- we're only interested in the one(s) which either -- 1. match facebook UI dialogs -- 2. match our app URL -- local url_parts, query_parts, fragment_parts url_parts = UrlLib.parse( event.url ) -- Utils.print( url_parts ) -- getting Facebook UI dialog, credentials if url_parts.path == '/login.php' and event.type == 'loaded' then self._webview.isVisible = true self._had_login = false return -- getting Facebook UI dialog, permissions elseif url_parts.path == '/dialog/oauth' and event.type == 'loaded' then self._webview.isVisible = true self._had_permissions = false return -- getting other elseif url_parts.host ~= self._app_url_parts.host then return end --== we're done with login/permissions dialogs, now do our stuff self:_removeWebView() -- let's see what we got back from FB query_parts = parse_query( url_parts.query ) fragment_parts = parse_query( url_parts.fragment ) -- print( 'URL Parts:' ) -- Utils.print( query_parts ) -- Utils.print( fragment_parts ) --== handle network response if query_parts.error == 'access_denied' then error_f( query_parts ) else success_f( fragment_parts.access_token ) end end --[[ https://developers.facebook.com/docs/facebook-login/permissions/ --]] function Facebook:getPermissions( params ) -- print( "Facebook:getPermissions" ) local g_params, success_f, error_f g_params = { fields='permissions' } success_f = function( data ) -- print( "postMessage: Success Handler" ) local d = nil if data ~= nil and data.data ~= nil and data.data[1] ~= nil then d = data.data[1] end local evt = { params = params, data = d } self:_dispatchEvent( Facebook.GET_PERMISSIONS, evt ) end error_f = function( response, net_params ) -- print( "postMessage: Error Handler" ) local evt = { params = params, is_error = true, data = response } self:_dispatchEvent( Facebook.GET_PERMISSIONS, evt ) end self:_makeFacebookGraphRequest( 'me/permissions', 'GET', g_params, success_f, error_f ) end function Facebook:requestPermissions( permissions, params ) -- print( "Facebook:requestPermissions", permissions, params ) end function Facebook:removePermission( permission, params ) -- print( "Facebook:removePermission", permission, params ) end function Facebook:postLink( link, params ) -- print( "Facebook:postLink", link, params ) params = params or {} params.link = link -- massage data in 'actions' if params.actions then params.actions = json.encode( params.actions ) end local success_f, error_f success_f = function( data ) -- print( "postLink: Success Handler" ) local evt = { params = params, data = data } self:_dispatchEvent( Facebook.POST_LINK, evt ) end error_f = function( response, net_params ) -- print( "postLink: Error Handler" ) local evt = { params = params, is_error = true, data = response } self:_dispatchEvent( Facebook.POST_LINK, evt ) end self:_makeFacebookGraphRequest( 'me/feed', 'POST', params, success_f, error_f ) end function Facebook:postMessage( text, params ) -- print( "Facebook:postMessage", text, params ) params = params or {} params.message = text local success_f, error_f success_f = function( data ) -- print( "postMessage: Success Handler" ) local evt = { params = params, data = data } self:_dispatchEvent( Facebook.POST_MESSAGE, evt ) end error_f = function( response, net_params ) -- print( "postMessage: Error Handler" ) local evt = { params = params, is_error = true, data = response } self:_dispatchEvent( Facebook.POST_MESSAGE, evt ) end self:_makeFacebookGraphRequest( 'me/feed', 'POST', params, success_f, error_f ) end function Facebook:request( path, method, params ) -- print( "Facebook:request", path, method, params ) method = method or 'GET' params = params or {} local success_f, error_f success_f = function( data ) -- print( "Request Success Handler" ) local evt = { path = path, method = method, params = params, data = data } self:_dispatchEvent( Facebook.REQUEST, evt ) end error_f = function( response, net_params ) -- print( "Request Error Handler" ) local evt = { path = path, method = method, params = params, is_error = true, data = response } self:_dispatchEvent( Facebook.REQUEST, evt ) end self:_makeFacebookGraphRequest( path, method, params, success_f, error_f ) end function Facebook:logout() -- print( "Facebook:logout" ) local params, url, webview, callback url = Facebook.LOGOUT_URLS[ self._view_type ] url = url .. '?' .. 'next=' .. url_encode( self._app_url ) url = url .. '&' .. 'access_token=' .. self._token -- print( url ) params = { x=0, y=0, w=200, h=200 } callback = self:createCallback( self._logoutRequest_handler ) webview = self:_createWebView( params, callback ) webview:request( url ) end -- _logoutRequest_handler() -- handler for the logout request -- it's a private method, but put here for convenience -- function Facebook:_logoutRequest_handler( event ) -- print( "Facebook:_logoutRequest_handler", event ) -- print( event.url ) -- print( event.type, event.errorMessage ) -- setup handlers -- local success_f, error_f success_f = function() -- print( "Request Success Handler" ) local evt = {} self._access_token = nil self:_dispatchEvent( Facebook.LOGOUT, evt ) end error_f = function( response ) -- print( "Request Error Handler" ) local evt = { is_error = true, error = 'error', error_reason = 'error_reason', error_description = 'error_description', } self:_dispatchEvent( Facebook.LOGOUT, evt ) end -- auth process has several redirects -- we're only interested in the one(s) which match our app url -- local url_parts, query_parts, fragment_parts url_parts = UrlLib.parse( event.url ) -- Utils.print( url_parts ) -- getting other if url_parts.host ~= self._app_url_parts.host then return end self:_removeWebView() query_parts = parse_query( url_parts.query ) fragment_parts = parse_query( url_parts.fragment ) -- print( 'URL Parts:' ) -- Utils.print( query_parts ) -- Utils.print( fragment_parts ) -- handle error/success -- if not query_parts.error then success_f() else -- TODO: figure what can go wrong here error_f( {} ) end end --== Private Methods ==-- -- _access_token() -- for internal use only, set new facebook token -- function Facebook.__setters:_access_token( value ) self._token = value self:_dispatchEvent( Facebook.ACCESS_TOKEN, { access_token=value } ) end --[[ function Facebook.__setters:_username( value ) self.__username = value end --]] function Facebook:_createWebView( params, listener ) -- print( "Facebook:_createWebView" ) -- Utils.print( params ) params = params or Facebook.VIEW_PARAMS local webview self:_removeWebView() webview = native.newWebView( params.x, params.y, params.w, params.h ) if listener then webview:addEventListener( "urlRequest", listener ) webview._f = listener end webview.isVisible = false self._webview = webview return webview end function Facebook:_removeWebView( params ) -- print( "Facebook:_removeWebView" ) local f if self._webview ~= nil then f = self._webview._f if f then self._webview._f = nil self._webview:removeEventListener( "urlRequest", f ) end self._webview:removeSelf() self._webview = nil end end -- _makeFacebookGraphRequest() -- this is the method which makes all FB Graph calls -- -- @param path string of path in FB, eg, 'me/friends' -- @param method string of HTTP method, eg 'GET' (default), 'POST' -- @param params table of other parameters for the call -- @param successHandler function to call on successful call -- @param errorHandler function to call on call error -- function Facebook:_makeFacebookGraphRequest( path, method, params, successHandler, errorHandler ) -- print( "Facebook:_makeFacebookGraphRequest", path, method ) -- make sure we have login already -- TODO: figure out how to better deal with this -- if not self.has_login then local err = Facebook.DMC_ERRORS[ 'no_login' ] local evt = { type = Facebook.DMC_ERROR_TYPE, code = err.code, message = err.message } errorHandler( evt, nil ) return end method = method or 'GET' params = params or {} local url, callback -- create our graph URL url = Facebook.GRAPH_URL url = url .. '/' .. path url = url .. '?' .. 'access_token=' .. self._token -- print( url ) -- create special network callback to better handle any situation -- callback = function( event ) local net_params = { -- to be able to reconstruct the call type = 'facebook_graph', -- internal usage path = path, method = method, params = params, -- callback handlers successHandler = successHandler, errorHandler = errorHandler } self:_networkRequest_handler( event, net_params ) end -- setup network request headers if necessary -- local net_params, headers if method == 'POST' then net_params = {} net_params.body = create_query( params ) -- print( net_params.body ) -- print( url ) headers = {} headers["Accept"] = "application/json" headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Content-Length"] = string.len( net_params.body ) net_params.headers = headers end network.request( url, method, callback, net_params ) end function Facebook:_networkRequest_handler( event, params ) -- print( "Facebook:_networkRequest_handler" ) local successHandler = params.successHandler local errorHandler = params.errorHandler if event.is_error then -- on Network Error, call error handler if errorHandler then errorHandler( event, params ) end else -- we got response back from server, check response -- print( event.response ) local response = json.decode( event.response ) -- on API Success if response and not response.error then if successHandler then successHandler( response ) end -- on API Error, handle appropriately else local err_data = response.error -- TODO: add API error recovery here -- https://developers.facebook.com/docs/reference/api/errors/ -- if err_data.code == 1 or err_data.code == 2 or err_data.code == 17 then -- server throttling, retry if params.type == 'facebook_graph' then self:_makeFacebookGraphRequest( params.path, params.method, params.params, params.successHandler, params.errorHandler ) else if errorHandler then errorHandler( response.error, params ) end end -- no special case to handle error, call error handler else if errorHandler then errorHandler( response.error, params ) end end end end end function Facebook:_dispatchEvent( e_type, data ) --print( "Facebook:_dispatchEvent" ) data = data or {} -- setup custom event local evt = { name = Facebook.EVENT, type = e_type, } -- layer in key/value pairs for k,v in pairs( data ) do -- print(k,v) evt[k] = v end self:dispatchEvent( evt ) end --====================================================================-- -- Facebook Singleton --====================================================================-- Facebook_Singleton = Facebook:new() return Facebook_Singleton
mit
RokaRoka/MistyWitches
hump/class.lua
25
3024
--[[ Copyright (c) 2010-2013 Matthias Richter 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. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local function include_helper(to, from, seen) if from == nil then return to elseif type(from) ~= 'table' then return from elseif seen[from] then return seen[from] end seen[from] = to for k,v in pairs(from) do k = include_helper({}, k, seen) -- keys might also be tables if to[k] == nil then to[k] = include_helper({}, v, seen) end end return to end -- deeply copies `other' into `class'. keys in `other' that are already -- defined in `class' are omitted local function include(class, other) return include_helper(class, other, {}) end -- returns a deep copy of `other' local function clone(other) return setmetatable(include({}, other), getmetatable(other)) end local function new(class) -- mixins local inc = class.__includes or {} if getmetatable(inc) then inc = {inc} end for _, other in ipairs(inc) do if type(other) == "string" then other = _G[other] end include(class, other) end -- class implementation class.__index = class class.init = class.init or class[1] or function() end class.include = class.include or include class.clone = class.clone or clone -- constructor call return setmetatable(class, {__call = function(c, ...) local o = setmetatable({}, c) o:init(...) return o end}) end -- interface for cross class-system compatibility (see https://github.com/bartbes/Class-Commons). if class_commons ~= false and not common then common = {} function common.class(name, prototype, parent) return new{__includes = {prototype, parent}} end function common.instance(class, ...) return class(...) end end -- the module return setmetatable({new = new, include = include, clone = clone}, {__call = function(_,...) return new(...) end})
mit
JarnoVgr/Mr.Green-MTA-Resources
resources/[gameplay]/joinquit/joinquit_server.lua
1
1972
addEventHandler("onPlayerJoin", root, function() local country = exports.geoloc:getPlayerCountryName(source) country = country and (' (' .. country .. ')') or '' local redirect = '' if getElementData(source, 'redirectedFrom') then redirect = ' from ' .. string.lower(getElementData(source, 'redirectedFrom')) removeElementData(source, 'redirectedFrom') end -- local joinstr = '* Joins: ' .. getPlayerName(source) .. ' #FF6464'.. country .. redirect local joinstr = '✶ Joined: ' .. getPlayerName(source) .. '#FF6464'.. country ..' joined the server'.. redirect for k,v in ipairs(getElementsByType"player")do if v ~= source then outputChatBox(joinstr, v, 255, 100, 100, true) end end outputServerLog( joinstr ) end ) addEventHandler('onPlayerQuit', root, function(quittype, reason, resp) if quittype == "Kicked" or quittype == "Banned" then local rstr = "" if reason and 0 < string.len(reason) then rstr = ' ('..reason..')' end -- outputChatBox('* ' .. quittype .. ': ' .. getPlayerName(source) .. '#FF6464 '..rstr, g_Root, 255, 100, 100, true) outputChatBox('✶ Quit: ' .. getPlayerName(source) .. '#FF6464 has been ' .. string.lower(quittype) .. ''..rstr, g_Root, 255, 100, 100, true) else if getElementData(source, 'gotomix') then quittype = 'switched to ' .. string.lower(get('interchat.other_server')) .. ' server' end if (quittype == 'Quit') then -- outputChatBox('* Quits: ' .. getPlayerName(source),root, 255, 100, 100, true) outputChatBox('✶ Quit: ' .. getPlayerName(source)..'#FF6464 left the server.',root, 255, 100, 100, true) else -- outputChatBox('* Quits: ' .. getPlayerName(source) .. '#FF6464 [' .. quittype .. ']',root, 255, 100, 100, true) outputChatBox('✶ Quit: ' .. getPlayerName(source) .. '#FF6464 ' .. quittype ,root, 255, 100, 100, true) end end end )
mit
LuaDist2/oil
lua/loop/simple.lua
13
3619
-------------------------------------------------------------------------------- ---------------------- ## ##### ##### ###### ----------------------- ---------------------- ## ## ## ## ## ## ## ----------------------- ---------------------- ## ## ## ## ## ###### ----------------------- ---------------------- ## ## ## ## ## ## ----------------------- ---------------------- ###### ##### ##### ## ----------------------- ---------------------- ----------------------- ----------------------- Lua Object-Oriented Programming ------------------------ -------------------------------------------------------------------------------- -- Project: LOOP - Lua Object-Oriented Programming -- -- Release: 2.3 beta -- -- Title : Simple Inheritance Class Model -- -- Author : Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- -- Exported API: -- -- class(class, super) -- -- new(class, ...) -- -- classof(object) -- -- isclass(class) -- -- instanceof(object, class) -- -- memberof(class, name) -- -- members(class) -- -- superclass(class) -- -- subclassof(class, super) -- -------------------------------------------------------------------------------- local require = require local rawget = rawget local pairs = pairs local table = require "loop.table" module "loop.simple" -------------------------------------------------------------------------------- local ObjectCache = require "loop.collection.ObjectCache" local base = require "loop.base" -------------------------------------------------------------------------------- table.copy(base, _M) -------------------------------------------------------------------------------- local DerivedClass = ObjectCache { retrieve = function(self, super) return base.class { __index = super, __call = new } end, } function class(class, super) if super then return DerivedClass[super](initclass(class)) else return base.class(class) end end -------------------------------------------------------------------------------- function isclass(class) local metaclass = classof(class) if metaclass then return metaclass == rawget(DerivedClass, metaclass.__index) or base.isclass(class) end end -------------------------------------------------------------------------------- function superclass(class) local metaclass = classof(class) if metaclass then return metaclass.__index end end -------------------------------------------------------------------------------- function subclassof(class, super) while class do if class == super then return true end class = superclass(class) end return false end -------------------------------------------------------------------------------- function instanceof(object, class) return subclassof(classof(object), class) end
mit
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/external/lua/luasocket/script/socket.lua
93
4451
----------------------------------------------------------------------------- -- LuaSocket helper module -- Author: Diego Nehab ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local string = require("string") local math = require("math") local socket = require("socket.core") local _M = socket ----------------------------------------------------------------------------- -- Exported auxiliar functions ----------------------------------------------------------------------------- function _M.connect4(address, port, laddress, lport) return socket.connect(address, port, laddress, lport, "inet") end function _M.connect6(address, port, laddress, lport) return socket.connect(address, port, laddress, lport, "inet6") end function _M.bind(host, port, backlog) if host == "*" then host = "0.0.0.0" end local addrinfo, err = socket.dns.getaddrinfo(host); if not addrinfo then return nil, err end local sock, res err = "no info on address" for i, alt in base.ipairs(addrinfo) do if alt.family == "inet" then sock, err = socket.tcp() else sock, err = socket.tcp6() end if not sock then return nil, err end sock:setoption("reuseaddr", true) res, err = sock:bind(alt.addr, port) if not res then sock:close() else res, err = sock:listen(backlog) if not res then sock:close() else return sock end end end return nil, err end _M.try = _M.newtry() function _M.choose(table) return function(name, opt1, opt2) if base.type(name) ~= "string" then name, opt1, opt2 = "default", name, opt1 end local f = table[name or "nil"] if not f then base.error("unknown key (".. base.tostring(name) ..")", 3) else return f(opt1, opt2) end end end ----------------------------------------------------------------------------- -- Socket sources and sinks, conforming to LTN12 ----------------------------------------------------------------------------- -- create namespaces inside LuaSocket namespace local sourcet, sinkt = {}, {} _M.sourcet = sourcet _M.sinkt = sinkt _M.BLOCKSIZE = 2048 sinkt["close-when-done"] = function(sock) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function(self, chunk, err) if not chunk then sock:close() return 1 else return sock:send(chunk) end end }) end sinkt["keep-open"] = function(sock) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function(self, chunk, err) if chunk then return sock:send(chunk) else return 1 end end }) end sinkt["default"] = sinkt["keep-open"] _M.sink = _M.choose(sinkt) sourcet["by-length"] = function(sock, length) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function() if length <= 0 then return nil end local size = math.min(socket.BLOCKSIZE, length) local chunk, err = sock:receive(size) if err then return nil, err end length = length - string.len(chunk) return chunk end }) end sourcet["until-closed"] = function(sock) local done return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function() if done then return nil end local chunk, err, partial = sock:receive(socket.BLOCKSIZE) if not err then return chunk elseif err == "closed" then sock:close() done = 1 return partial else return nil, err end end }) end sourcet["default"] = sourcet["until-closed"] _M.source = _M.choose(sourcet) return _M
mit
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/EaseBounceIn.lua
9
1242
-------------------------------- -- @module EaseBounceIn -- @extend EaseBounce -- @parent_module cc -------------------------------- -- brief Create the action with the inner action.<br> -- param action The pointer of the inner action.<br> -- return A pointer of EaseBounceIn action. If creation failed, return nil. -- @function [parent=#EaseBounceIn] create -- @param self -- @param #cc.ActionInterval action -- @return EaseBounceIn#EaseBounceIn ret (return value: cc.EaseBounceIn) -------------------------------- -- -- @function [parent=#EaseBounceIn] clone -- @param self -- @return EaseBounceIn#EaseBounceIn ret (return value: cc.EaseBounceIn) -------------------------------- -- -- @function [parent=#EaseBounceIn] update -- @param self -- @param #float time -- @return EaseBounceIn#EaseBounceIn self (return value: cc.EaseBounceIn) -------------------------------- -- -- @function [parent=#EaseBounceIn] reverse -- @param self -- @return EaseBounce#EaseBounce ret (return value: cc.EaseBounce) -------------------------------- -- -- @function [parent=#EaseBounceIn] EaseBounceIn -- @param self -- @return EaseBounceIn#EaseBounceIn self (return value: cc.EaseBounceIn) return nil
mit
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/script/cocostudio/CocoStudio.lua
62
9435
if nil == ccs then return end if not json then require "cocos.cocos2d.json" end require "cocos.cocostudio.StudioConstants" function ccs.sendTriggerEvent(event) local triggerObjArr = ccs.TriggerMng.getInstance():get(event) if nil == triggerObjArr then return end for i = 1, table.getn(triggerObjArr) do local triObj = triggerObjArr[i] if nil ~= triObj and triObj:detect() then triObj:done() end end end function ccs.registerTriggerClass(className, createFunc) ccs.TInfo.new(className,createFunc) end ccs.TInfo = class("TInfo") ccs.TInfo._className = "" ccs.TInfo._fun = nil function ccs.TInfo:ctor(c,f) -- @param {String|ccs.TInfo}c -- @param {Function}f if nil ~= f then self._className = c self._fun = f else self._className = c._className self._fun = c._fun end ccs.ObjectFactory.getInstance():registerType(self) end ccs.ObjectFactory = class("ObjectFactory") ccs.ObjectFactory._typeMap = nil ccs.ObjectFactory._instance = nil function ccs.ObjectFactory:ctor() self._typeMap = {} end function ccs.ObjectFactory.getInstance() if nil == ccs.ObjectFactory._instance then ccs.ObjectFactory._instance = ccs.ObjectFactory.new() end return ccs.ObjectFactory._instance end function ccs.ObjectFactory.destroyInstance() ccs.ObjectFactory._instance = nil end function ccs.ObjectFactory:createObject(classname) local obj = nil local t = self._typeMap[classname] if nil ~= t then obj = t._fun() end return obj end function ccs.ObjectFactory:registerType(t) self._typeMap[t._className] = t end ccs.TriggerObj = class("TriggerObj") ccs.TriggerObj._cons = {} ccs.TriggerObj._acts = {} ccs.TriggerObj._enable = false ccs.TriggerObj._id = 0 ccs.TriggerObj._vInt = {} function ccs.TriggerObj.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, TriggerObj) return target end function ccs.TriggerObj:ctor() self:init() end function ccs.TriggerObj:init() self._id = 0 self._enable = true self._cons = {} self._acts = {} self._vInt = {} end function ccs.TriggerObj:detect() if (not self._enable) or (table.getn(self._cons) == 0) then return true end local ret = true local obj = nil for i = 1 , table.getn(self._cons) do obj = self._cons[i] if nil ~= obj and nil ~= obj.detect then ret = ret and obj:detect() end end return ret end function ccs.TriggerObj:done() if (not self._enable) or (table.getn(self._acts) == 0) then return end local obj = nil for i = 1, table.getn(self._acts) do obj = self._acts[i] if nil ~= obj and obj.done then obj:done() end end end function ccs.TriggerObj:removeAll() local obj = nil for i=1, table.getn(self._cons) do obj = self._cons[i] if nil ~= obj then obj:removeAll() end end self._cons = {} for i=1, table.getn(self._acts) do obj = self._acts[i] if nil ~= obj then obj:removeAll() end end self._acts = {} end function ccs.TriggerObj:serialize(jsonValue) self._id = jsonValue["id"] local count = 0 --condition local cons = jsonValue["conditions"] if nil ~= cons then count = table.getn(cons) for i = 1, count do local subDict = cons[i] local className = subDict["classname"] if nil ~= className then local obj = ccs.ObjectFactory.getInstance():createObject(className) assert(nil ~= obj, string.format("class named %s can not implement!",className)) obj:serialize(subDict) obj:init() table.insert(self._cons, obj) end end end local actions = jsonValue["actions"] if nil ~= actions then count = table.getn(actions) for i = 1,count do local subAction = actions[i] local className = subAction["classname"] if nil ~= className then local act = ccs.ObjectFactory.getInstance():createObject(className) assert(nil ~= act ,string.format("class named %s can not implement!",className)) act:serialize(subAction) act:init() table.insert(self._acts,act) end end end local events = jsonValue["events"] if nil ~= events then count = table.getn(events) for i = 1, count do local subEveent = events[i] local eventID = subEveent["id"] if eventID >= 0 then table.insert(self._vInt,eventID) end end end end function ccs.TriggerObj:getId() return self._id end function ccs.TriggerObj:setEnable(enable) self._enable = enable end function ccs.TriggerObj:getEvents() return self._vInt end ccs.TriggerMng = class("TriggerMng") ccs.TriggerMng._eventTriggers = nil ccs.TriggerMng._triggerObjs = nil ccs.TriggerMng._movementDispatches = nil ccs.TriggerMng._instance = nil function ccs.TriggerMng:ctor() self._triggerObjs = {} self._movementDispatches = {} self._eventTriggers = {} end function ccs.TriggerMng.getInstance() if ccs.TriggerMng._instance == nil then ccs.TriggerMng._instance = ccs.TriggerMng.new() end return ccs.TriggerMng._instance end function ccs.TriggerMng.destroyInstance() if ccs.TriggerMng._instance ~= nil then ccs.TriggerMng._instance:removeAll() ccs.TriggerMng._instance = nil end end function ccs.TriggerMng:triggerMngVersion() return "1.0.0.0" end function ccs.TriggerMng:parse(jsonStr) local parseTable = json.decode(jsonStr,1) if nil == parseTable then return end local count = table.getn(parseTable) for i = 1, count do local subDict = parseTable[i] local triggerObj = ccs.TriggerObj.new() triggerObj:serialize(subDict) local events = triggerObj:getEvents() for j = 1, table.getn(events) do local event = events[j] self:add(event, triggerObj) end self._triggerObjs[triggerObj:getId()] = triggerObj end end function ccs.TriggerMng:get(event) return self._eventTriggers[event] end function ccs.TriggerMng:getTriggerObj(id) return self._triggerObjs[id] end function ccs.TriggerMng:add(event,triggerObj) local eventTriggers = self._eventTriggers[event] if nil == eventTriggers then eventTriggers = {} end local exist = false for i = 1, table.getn(eventTriggers) do if eventTriggers[i] == triggers then exist = true break end end if not exist then table.insert(eventTriggers,triggerObj) self._eventTriggers[event] = eventTriggers end end function ccs.TriggerMng:removeAll( ) for k in pairs(self._eventTriggers) do local triObjArr = self._eventTriggers[k] for j = 1, table.getn(triObjArr) do local obj = triObjArr[j] obj:removeAll() end end self._eventTriggers = {} end function ccs.TriggerMng:remove(event, obj) if nil ~= obj then return self:removeObjByEvent(event, obj) end assert(event >= 0,"event must be larger than 0") if nil == self._eventTriggers then return false end local triObjects = self._eventTriggers[event] if nil == triObjects then return false end for i = 1, table.getn(triObjects) do local triObject = triggers[i] if nil ~= triObject then triObject:remvoeAll() end end self._eventTriggers[event] = nil return true end function ccs.TriggerMng:removeObjByEvent(event, obj) assert(event >= 0,"event must be larger than 0") if nil == self._eventTriggers then return false end local triObjects = self._eventTriggers[event] if nil == triObjects then return false end for i = 1,table.getn(triObjects) do local triObject = triObjects[i] if nil ~= triObject and triObject == obj then triObject:remvoeAll() table.remove(triObjects, i) return true end end end function ccs.TriggerMng:removeTriggerObj(id) local obj = self.getTriggerObj(id) if nil == obj then return false end local events = obj:getEvents() for i = 1, table.getn(events) do self:remove(events[i],obj) end return true end function ccs.TriggerMng:isEmpty() return (not (nil == self._eventTriggers)) or table.getn(self._eventTriggers) <= 0 end function __onParseConfig(configType,jasonStr) if configType == cc.ConfigType.COCOSTUDIO then ccs.TriggerMng.getInstance():parse(jasonStr) end end function ccs.AnimationInfo(_name, _startIndex, _endIndex) assert(nil ~= _name and type(_name) == "string" and _startIndex ~= nil and type(_startIndex) == "number" and _endIndex ~= nil and type(_endIndex) == "number", "ccs.AnimationInfo() - invalid input parameters") return { name = _name, startIndex = _startIndex, endIndex = _endIndex} end
mit
kyuu/dynrpg-rpgss
assets/Scripts/extensions/inputmanager/InputManager.lua
1
5485
require "system" require "extensions.timer" InputManager = class { __name = "InputManager", listeners = {}, sortedListeners = {}, keyRepeat = { delay = 500, -- milliseconds before key repeat start interval = 50, -- milliseconds before next key repeat timer = 0, key = nil }, keys = {}, mbuttons = {}, onSceneDrawn = function(self, scene) self:update() end } function InputManager:fireKeyboardEvent(type, key, vkey) local e = { type = type, key = key, vkey = vkey, handled = false } for _, l in ipairs(self.sortedListeners) do if l.self.onKeyboardEvent ~= nil then l.self:onKeyboardEvent(e) if e.handled then break end end end end function InputManager:fireMouseButtonEvent(type, button) local e = { type = type, button = button, handled = false } for _, l in ipairs(self.sortedListeners) do if l.self.onMouseButtonEvent ~= nil then l.self:onMouseButtonEvent(e) if e.handled then break end end end end function InputManager:update() -- update key states local kb = keyboard.getState() for k, d in pairs(kb) do local o = self.keys[k] if o == nil then o = { key = k, vkey = keyboard.getVirtualKeyCode(k), down = false } self.keys[k] = o end -- if key was previously down and now is up if o.down == true and d == false then self:fireKeyboardEvent("key up", o.key, o.vkey) -- if this is the key repeat key, -- reset the key repeat state if k == self.keyRepeat.key then self.keyRepeat.timer = 0 self.keyRepeat.key = nil else -- it's not the key repeat key, so -- just reset the key repeat timer self.keyRepeat.timer = 0 end end -- if key was previously up and now is down if o.down == false and d == true then self:fireKeyboardEvent("key down", o.key, o.vkey) -- reset key repeat timer and set this -- key as the new key repeat key self.keyRepeat.timer = 0 self.keyRepeat.key = k end -- update key state o.down = d end -- update key repeat if enabled (delay > 0) if self.keyRepeat.delay > 0 and self.keyRepeat.key then -- for brevity local r = self.keyRepeat local o = self.keys[r.key] -- to be on the safe side, check if the -- key repeat key is really down if o.down then r.timer = r.timer + Timer:getTimeDelta() while r.timer >= r.delay do self:fireKeyboardEvent("key down", o.key, o.vkey) r.timer = r.timer - r.interval end else -- uh, something went wrong -- correct the mistake r.timer = 0 r.key = nil end end -- update mouse button states local mb = mouse.getState() for b, d in pairs(mb) do local o = self.mbuttons[b] if o == nil then o = { button = b, down = false } self.mbuttons[b] = o end -- if mouse button was previously down and now is up if o.down == true and d == false then self:fireMouseButtonEvent("button up", o.button) end -- if mouse button was previously up and now is down if o.down == false and d == true then self:fireMouseButtonEvent("button down", o.button) end -- update mouse button state o.down = d end end function InputManager:sortListeners() local t = {} for _, l in pairs(self.listeners) do table.insert(t, l) end table.sort( t, function(a, b) return a.prio > b.prio end ) self.sortedListeners = t end function InputManager:addListener(name, priority, listener) -- sanity checks assert(type(name) == "string" and #name > 0, "invalid name") assert(type(priority) == "number", "invalid priority") assert(type(listener) == "table", "invalid listener") assert(self.listeners[name] == nil, "listener '"..name.."' already exists") -- add listener self.listeners[name] = { name = name, prio = priority, self = listener } -- listeners table changed, re-sort self:sortListeners() end function InputManager:removeListener(name) -- sanity checks assert(type(name) == "string" and #name > 0, "invalid name") assert(self.listeners[name] ~= nil, "listener '"..´name.."' does not exist") -- remove listener self.listeners[name] = nil -- listeners table changed, re-sort self:sortListeners() end function InputManager:getKeyRepeatDelay() return self.keyRepeat.delay end function InputManager:setKeyRepeatDelay(delay) self.keyRepeat.delay = delay end -- register in callback manager CallbackManager:addListener("InputManager", -900, InputManager)
mit
cyanskies/OpenRA
mods/ra/maps/soviet-06a/soviet06a-reinforcements_teams.lua
12
1302
EnemyReinforcements = { easy = { { "e1", "e1", "e3" }, { "e1", "e3", "jeep" }, { "e1", "jeep", "1tnk" } }, normal = { { "e1", "e1", "e3", "e3" }, { "e1", "e3", "jeep", "jeep" }, { "e1", "jeep", "1tnk", "2tnk" } }, hard = { { "e1", "e1", "e3", "e3", "e1" }, { "e1", "e3", "jeep", "jeep", "1tnk" }, { "e1", "jeep", "1tnk", "2tnk", "arty" } } } EnemyAttackDelay = { easy = DateTime.Minutes(5), normal = DateTime.Minutes(2) + DateTime.Seconds(40), hard = DateTime.Minutes(1) + DateTime.Seconds(30) } EnemyPaths = { { EnemyEntry1.Location, EnemyRally1.Location }, { EnemyEntry2.Location, EnemyRally2.Location } } wave = 0 SendEnemies = function() Trigger.AfterDelay(EnemyAttackDelay[Map.LobbyOption("difficulty")], function() wave = wave + 1 if wave > 3 then wave = 1 end if wave == 1 then local units = Reinforcements.ReinforceWithTransport(enemy, "tran", EnemyReinforcements[Map.LobbyOption("difficulty")][wave], EnemyPaths[1], { EnemyPaths[1][1] })[2] Utils.Do(units, IdleHunt) else local units = Reinforcements.ReinforceWithTransport(enemy, "lst", EnemyReinforcements[Map.LobbyOption("difficulty")][wave], EnemyPaths[2], { EnemyPaths[2][1] })[2] Utils.Do(units, IdleHunt) end if not Dome.IsDead then SendEnemies() end end) end
gpl-3.0
cyanskies/OpenRA
mods/cnc/maps/gdi03/gdi03.lua
46
3709
SamSites = { Sam1, Sam2, Sam3, Sam4 } Sam4Guards = { Sam4Guard0, Sam4Guard1, Sam4Guard2, Sam4Guard3, Sam4Guard4, HiddenBuggy } NodInfantrySquad = { "e1", "e1", "e1", "e1", "e1" } NodAttackRoutes = { { AttackWaypoint }, { AttackWaypoint }, { AttackRallypoint1, AttackRallypoint2, AttackWaypoint } } InfantryReinforcements = { "e1", "e1", "e1", "e1", "e1", "e2", "e2", "e2", "e2", "e2" } JeepReinforcements = { "jeep", "jeep", "jeep" } AttackPlayer = function() if NodBarracks.IsDead or NodBarracks.Owner == player then return end local after = function(team) local count = 1 local route = Utils.Random(NodAttackRoutes) Utils.Do(team, function(actor) Trigger.OnIdle(actor, function() if actor.Location == route[count].Location then if not count == #route then count = count + 1 else Trigger.ClearAll(actor) Trigger.AfterDelay(0, function() Trigger.OnIdle(actor, actor.Hunt) end) end else actor.AttackMove(route[count].Location) end end) end) Trigger.OnAllKilled(team, function() Trigger.AfterDelay(DateTime.Seconds(15), AttackPlayer) end) end NodBarracks.Build(NodInfantrySquad, after) end SendReinforcements = function() Reinforcements.Reinforce(player, JeepReinforcements, { VehicleStart.Location, VehicleStop.Location }) Reinforcements.Reinforce(player, InfantryReinforcements, { InfantryStart.Location, InfantryStop.Location }, 5) Trigger.AfterDelay(DateTime.Seconds(3), function() Reinforcements.Reinforce(player, { "mcv" }, { VehicleStart.Location, MCVwaypoint.Location }) InitialUnitsArrived = true end) Media.PlaySpeechNotification(player, "Reinforce") end WorldLoaded = function() player = Player.GetPlayer("GDI") enemy = Player.GetPlayer("Nod") Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) nodObjective = enemy.AddPrimaryObjective("Destroy all GDI troops.") gdiMainObjective = player.AddPrimaryObjective("Eliminate all Nod forces in the area.") gdiAirSupportObjective = player.AddSecondaryObjective("Destroy the SAM sites to receive air support.") Trigger.OnPlayerLost(player, function() Media.PlaySpeechNotification(player, "Lose") end) Trigger.OnPlayerWon(player, function() Media.PlaySpeechNotification(player, "Win") end) Trigger.OnAllKilled(SamSites, function() player.MarkCompletedObjective(gdiAirSupportObjective) Actor.Create("airstrike.proxy", true, { Owner = player }) end) Utils.Do(Map.NamedActors, function(actor) if actor.Owner == enemy and actor.HasProperty("StartBuildingRepairs") then Trigger.OnDamaged(actor, function(building) if building.Owner == enemy and building.Health < 0.25 * building.MaxHealth then building.StartBuildingRepairs() end end) end end) Trigger.OnDamaged(Sam4, function() Utils.Do(Sam4Guards, function(sam4Guard) if not sam4Guard.IsDead then Trigger.OnIdle(sam4Guard, sam4Guard.Hunt) end end) end) InitialUnitsArrived = false SendReinforcements() Camera.Position = MCVwaypoint.CenterPosition Trigger.AfterDelay(DateTime.Seconds(15), AttackPlayer) end Tick = function() if InitialUnitsArrived then if player.HasNoRequiredUnits() then enemy.MarkCompletedObjective(nodObjective) end if enemy.HasNoRequiredUnits() then player.MarkCompletedObjective(gdiMainObjective) end end end
gpl-3.0
JarnoVgr/Mr.Green-MTA-Resources
resources/[race]/race_ghost_assist/playback_local_client.lua
2
19378
-- // =====================[ important variables ] ===================// g_Root = getRootElement() local nextNode = nil -- !!! local prev, curr local node1, node2 local lastNodeID = 1 -- gotta start at 1 local nextNodeID = 1 -- gotta start at 1 local id, idx local x, y, z local xx, yy, zz local xx2, yy2, zz2 local rx, ry, rz -- local fx, fy, fz local gx, gy, gz local ghost_speed local my_speed local my_dst local prev_dst = math.huge local dst = 0 local vehicle local vType -- local theType local color_r, color_g, color_b, color_a local my_weight = 1500 local arrowSize = 2 local drawRacingLine_HANDLER = nil local assistTimer = nil local recording = nil local img = dxCreateTexture("arrow.png") -- trying to buy some time local sin = math.sin local cos = math.cos local rad = math.rad local abs = math.abs -------------------------------------------------------------------------- -- // ================[ racing lines local/server mode] ============// function assistMode(player, mode) Settings["mode"] = mode -- outputDebug("racing assist mode: ".. inspect(Settings["mode"])) -- DEBUG saveSettings() end addCommandHandler('assistmode', assistMode) -- // =========================[ racing lines toggle on/off ] ======================================// function assistToggle(player, mode) -- mode = tonumber(mode) -- assist on/off if mode == "off" then outputChatBox("[Racing Assist] #ffffffby disabled.", 255, 170, 64, true) Settings["enable"] = "off" if recording then hide() end -- TODO: exports.messages:outputGameMessage("Racing assist disabled", g_Root, 2, 230, 220, 180) -- assist on else --if mode == anything outputChatBox("[Racing Assist] #ffffffby #ffaa40fak #ffffffstarted.", 255, 170, 64, true) Settings["enable"] = "on" if recording then show() else -- inform if no ghost is available when turning on outputChatBox("[Racing Assist] #ffffffLaunching on the next map.", 255, 170, 64, true) end -- TODO: exports.messages:outputGameMessage("Racing assist enabled", g_Root, 2, 230, 220, 180) end -- mode saveSettings() -- outputDebug("racing assist: ".. inspect(Settings["enable"])) -- DEBUG end -- assistToggle addCommandHandler('assist', assistToggle) -- // =============================[ resume/show ] ============================================// -- show the racing line function show() if not drawRacingLine_HANDLER then drawRacingLine_HANDLER = function() drawRacingLine() end addEventHandler("onClientPreRender", g_Root, drawRacingLine_HANDLER) -- outputDebug("Racingline showing") end end -- // =============================[ hide ] ============================================// -- hide the racing line for planes/when too far function hide() if drawRacingLine_HANDLER then removeEventHandler("onClientPreRender", g_Root, drawRacingLine_HANDLER) drawRacingLine_HANDLER = nil -- outputDebug("Racingline hidden") end end -- // =============================[ destroy ] ===================================// function destroy() -- who triggered it? outputDebug("@destroy, source: "..inspect(eventName)) -- must have if isTimer(assistTimer) then killTimer(assistTimer) assistTimer = nil end if drawRacingLine_HANDLER then removeEventHandler("onClientPreRender", g_Root, drawRacingLine_HANDLER) drawRacingLine_HANDLER = nil -- outputDebug("Racingline destroyed") end recording = nil end -- cleanup at finish/map change addEventHandler("onClientResourceStart", getRootElement(), function(startedRes) if startedRes == getThisResource() then -- !!! outputDebug("onClientResourceStart") loadSettings() addEventHandler("onClientPlayerFinish", g_Root, destroy) -- TODO: THIS DELETES MY GHOST AT THE WRONG TIME -- TODO: GHOST IS NOT DESTROYED WHEN MAP STOPS -- addEventHandler("onClientMapStopping", g_Root, destroy) end end ) -- // ====================================================[ load ghost ] ===========================================================// function loadGhost(mapName) -- race_ghost is required to run if not getResourceFromName("race_ghost") then outputChatBox("[Racing Assist] #ffffffPlease start the race_ghost resource.", 255, 170, 64, true) return false end -- local ghosts are in the "race_ghost" resource!!! local ghost = xmlLoadFile(":race_ghost/ghosts/" .. mapName .. ".ghost") outputDebug("@loadGhost: " .. inspect(ghost)) -- DEBUG if ghost then -- Construct a table local index = 0 local node = xmlFindChild(ghost, "n", index) local recording = {} while (node) do if type(node) ~= "userdata" then outputDebugString("race_ghost - playback_local_client.lua: Invalid node data while loading ghost: " .. type(node) .. ":" .. tostring(node), 1) break end local attributes = xmlNodeGetAttributes(node) local row = {} for k, v in pairs(attributes) do row[k] = convert(v) end -- !!! -- we only need "po" data if (row.ty == "po") then table.insert(recording, row) -- outputDebug("row: " .. inspect(row)) -- DEBUG end index = index + 1 node = xmlFindChild(ghost, "n", index) end -- while -- Retrieve info about the ghost -- outputDebug("Found a valid local ghost for " .. mapName) -- local info = xmlFindChild(ghost, "i", 0) -- outputChatBox("* Race assist loaded. (" ..xmlNodeGetAttribute(info, "r").. ") " ..FormatDate(xmlNodeGetAttribute(info, "timestamp")), 0, 255, 0) -- TODO: exports.messages:outputGameMessage("Racing assist loaded", g_Root, 2, 230, 220, 180, true) -- outputChatBox("* Racing assist loaded.", 230, 220, 180) xmlUnloadFile(ghost) return recording else outputDebug("loading ghost failed") -- DEBUG outputChatBox("[Racing Assist] #ffffffGhost for this map was not found.", 255, 170, 64, true) return false end -- ghost end -- loadGhost -- // =================[ setup ghost from your LOCAL FOLDERS, onClientMapStarting ] ==========================// addEventHandler("onClientMapStarting", g_Root, function (mapInfo) outputDebug("onClientMapStarting") -- DEBUG -- !!! if Settings["enable"] == "on" and Settings["mode"] == "local" then -- disable for NTS local currentGameMode = string.upper(mapInfo.modename) if currentGameMode == "NEVER THE SAME" then return end -- destroy any leftover stuff if recording then destroy() end -- !!! recording = loadGhost(mapInfo.resname) -- ghost was read successfully if recording then -- !!! lastNodeID = 1 nextNodeID = 1 -- start a assistTimer that updates raceline parameters assistTimer = setTimer(updateRacingLine, 150, 0) -- show racing line at race start show() outputDebug("ghost loaded, starting assist") -- DEBUG -- outputChatBox("[Racing Assist] #ffffffLocal ghost loaded.", 255, 170, 64, true) end -- rec end -- setting end -- function ) -- // =============================[ setup ghost received from SERVER, onClientGhostDataReceive ] ============================================// addEventHandler("onClientGhostDataReceive", g_Root, function(rec, bestTime, racer, _, _) outputDebug("onClientGhostDataReceive") -- DEBUG -- !!! if Settings["enable"] == "on" and Settings["mode"] == "top" then outputChatBox("[Racing Assist] #ffffffTop 1 ghost feature is disabled on Mr. Green.", 255, 170, 64, true) -- -- destroy any leftover stuff -- if recording then -- destroy() -- end -- -- ghost data from "race_ghost" folder must be converted -- recording = {} -- -- "While a table with three elements needs three rehashings, a table with one -- -- million elements needs only twenty" -- -- copy and filter things -- local i = 1 -- while(rec[i]) do -- -- only need po type -- if (rec[i].ty == "po") then -- table.insert(recording, rec[i]) -- end -- i = i + 1 -- end -- while -- lastNodeID = 1 -- nextNodeID = 1 -- -- !!! -- -- start a timer that updates raceline parameters -- assistTimer = setTimer(updateRacingLine, 150, 0) -- -- start drawing the racing line -- show() -- outputDebug("ghost loaded, starting assist") -- DEBUG -- outputChatBox("[Racing Assist] #ffffffGhost by " .. RemoveHEXColorCode(racer) .. " @".. msToTimeStr(bestTime).. " loaded.", 255, 170, 64, true) end -- if end -- function ) -- // ================[ convert ] ==============// function convert(value) if tonumber(value) ~= nil then return tonumber(value) else if tostring(value) == "true" then return true elseif tostring(value) == "false" then return false else return tostring(value) end end end -- // ============[ getPositionFromElementOffset ] =========================// local function getPositionFromElementOffset(x, y, z, rx, ry, rz, offZ) rx, ry, rz = rad(rx), rad(ry), rad(rz) local tx = offZ * (cos(rz)*sin(ry) + cos(ry)*sin(rz)*sin(rx)) + x local ty = offZ * (sin(rz)*sin(ry) - cos(rz)*cos(ry)*sin(rx)) + y local tz = offZ * (cos(rx)*cos(ry)) + z return tx, ty, tz end -- read more: -- https://wiki.multitheftauto.com/wiki/GetElementMatrix -- // =============================[ updateRacingLine, runs in assistTimer ] ============================================// function updateRacingLine() -- took me 0.02 ms to run -- start time measurement -------------------------------------// -- local eleje = getTickCount() local m = 1 for m=1, 500 do -------// ---------------------------------------------------------------// -- outputDebug("@updateRacingLine") -- TODO: DONT CALL THIS ON EVERY RUN vehicle = getPedOccupiedVehicle(getLocalPlayer()) -- keep this -- no need lines for air vehicles if Settings["enable"] == "on" and vehicle then vType = getVehicleType(vehicle) if (vType == "Plane" or vType == "Helicopter" or vType == "Boat") then hide() else show() end end -- // ====================[ Find the next valid ghostpoint ] ==========================// prev_dst = math.huge dst = 0 nextNode = nil -- looking for the first unvisited node within range -- search starts from the last visited node and then only looking forward! -- !!! -- save the last, before looking for a new one lastNodeID = nextNodeID -- remove this to see visited routes -- !!! id = lastNodeID while(recording[id]) do x, y, z = recording[id].x, recording[id].y, recording[id].z dst = getDistanceBetweenPoints3D(x, y, z, getElementPosition(getLocalPlayer())) -- get nearby unvisited points if (dst < 50 and id >= lastNodeID) then -- ugly constant here nextNode = id break end id = id + 1 end -- while -- // ====================[ Find the nearest valid ghostpoint ] ==========================// -- if a valid next node was found, scroll trough a few nodes and find one closest to player if (nextNode ~= nil) then prev_dst = math.huge dst = 0 if (vehicle) then x, y, z = getElementPosition(vehicle) -- looking for a node pair, where "i+1" is further than "i" -- move it one step closer to player on every iteration prev = recording[nextNode] idx = nextNode + 1 curr = recording[idx] if (curr and prev) then prev_dst = getDistanceBetweenPoints3D(prev.x, prev.y, prev.z, x, y, z) or 0 dst = getDistanceBetweenPoints3D(curr.x, curr.y, curr.z, x, y, z) or 0 if (prev_dst > dst) then -- !!! -- this will be the nearest valid node to player nextNodeID = idx -- !!! end -- DEBUG -- outputChatBox("i: "..id) -- DEBUG -- dxDrawText( inspect(prev), 200, 440, 250) -- dxDrawText( inspect("prev id: "..nextNode .." ".. prev_dst), 200, 420, 250) -- dxDrawText( inspect(curr), 400, 440, 250) -- dxDrawText( inspect("next id: "..idx .." ".. dst), 400, 420, 250) end -- if end -- vehicle -- old solution: not the nearest node, but grips nicely to the car -- nextNodeID = nextNode end -- nil -- // ========================[ Calculate arrow size] ==============================// -- resize arrow based on vehicle size my_weight = 1500 arrowSize = 2 if (vehicle) then my_weight = (getVehicleHandling(vehicle).mass) arrowSize = math.clamp(1, (0.04*my_weight+180)/200, 3) -- dirt 3 style arrow size -- arrowSize = math.clamp(1.5, (0.04*my_weight+180)/150, 5) -- forza style arrow size end -- -- stop time measurement -------------------------------------------------------------------------------// -- end local vege = getTickCount() outputDebug( "ms time spent: " .. vege-eleje) --// -- --------------------------------------------------------------------------------------------------------// end -- updateRacingLine -- // =============================[ drawRacingLine onClientPreRender ] ============================================// function drawRacingLine() -- took me about 0.6 - 1.2 ms to run -- -- start time measurement -------------------------------------// -- local eleje = getTickCount() local m = 1 for m=1, 40 do --------// -- ---------------------------------------------------------------// -- -- // ==================[ DEBUG: Show the full racing line, highlight nearby and next nodes ] =====================// -- -- local nearbyNodes = {} -- local i = 1 -- node1 = recording[i] -- node2 = recording[i+1] -- while(node1 and node2) do -- -- one piece of race line -- dxDrawLine3D (node1.x, node1.y, node1.z-0.4, node2.x, node2.y, node2.z-0.4, tocolor(255,255,255, 128), 8) -- dst = getDistanceBetweenPoints3D(node1.x, node1.y, node1.z, getElementPosition(getLocalPlayer())) -- if (dst < 50) then -- -- one nearby node -- dxDrawLine3D (node1.x, node1.y, node1.z-0.6, node1.x, node1.y, node1.z-0.4, tocolor (255,0,0, 255), 25) -- -- store nearby points -- -- table.insert(nearbyNodes, i, dst) -- end -- i = i + 1 -- node1 = recording[i] -- node2 = recording[i+1] -- end -- -- show the table of nearby nodes -- -- if (nearbyNodes) then -- -- dxDrawText(inspect(nearbyNodes), 200, 500, 250) -- -- end -- -- draw the next node -- node1 = recording[nextNodeID] -- if (node1) then -- dxDrawLine3D (node1.x, node1.y, node1.z-0.6, node1.x, node1.y, node1.z-0.4, tocolor(0,255,0, 255), 40) -- end -- DEBUG -- dxDrawText(getVehicleType(vehicle), 800, 440, 1920, 1080, tocolor(255, 128, 0, 255), 1, "pricedown") -- // =================================[ Draw racing line section near player ] =====================================// vehicle = getPedOccupiedVehicle(getLocalPlayer()) -- keep this local start = nextNodeID -- draw the next few nodes for i = start, start+Settings["linelength"], 1 do node1 = recording[i] -- need 2 valid nodes to make a line AND being in a vehicle to continue if (node1 and vehicle) then -- // =================[ get ghost and player speed at EVERY PIECE OF RACE LINE ] =======================// ghost_speed = getDistanceBetweenPoints3D(0, 0, 0, node1.vX, node1.vY, node1.vZ) my_speed = getDistanceBetweenPoints3D(0, 0, 0, getElementVelocity(vehicle)) my_dst = getDistanceBetweenPoints3D(node1.x, node1.y, node1.z, getElementPosition(vehicle)) -- !!! speed_err = Settings["sensitivity"] * ((my_speed - ghost_speed)/ghost_speed) -- relative speed error -- speed_err = (ghost_speed - my_speed) * 160 -- old: speed difference roughly in kmh -- DEBUG -- if i == start then dxDrawText ("speed error: "..math.floor(speed_err*100).. " %", 800, 440, 1920, 1080, tocolor(255, 128, 0, 255), 1, "pricedown") end -- if i == start then dxDrawText ("my speed: ".. math.floor(my_speed*160), 800, 480, 1920, 1080, tocolor(255, 128, 0, 255), 1, "pricedown") end -- if i == start then dxDrawText ("ghost speed: ".. math.floor(ghost_speed*160), 800, 520, 1920, 1080, tocolor(255, 128, 0, 255), 1, "pricedown") end -- // =========================[ Speed color coding ] ==============================// -- speed color coding FOR RELATIVE SPEED ERROR, red=too fast, green=okay, white=too slow -- scaled to [-50%, 50%] relative speed error interval -- speed_err = 0.5 means u go 50% faster than the ghost color_r = math.clamp(0, 510*math.abs(speed_err), 255) color_g = math.clamp(0, -510*speed_err + 255, 255) color_b = math.clamp(0, -510*speed_err, 255) color_a = math.clamp(0, 0.5*my_dst^2, 175) -- sharp fade -- -- speed color coding, red=too fast, green=normal, white=too slow -- -- scaled to [-25, 25] kmh speed diff interval -- color_r = math.clamp(0, math.abs(-10*speed_err), 255) -- color_g = math.clamp(0, 10*speed_err + 255, 255) -- color_b = math.clamp(0, 10*speed_err, 255) -- color_a = math.clamp(0, 0.5*my_dst^2, 175) -- sharper fade -- // =================================================[ Draw one line piece ]=================================================// -- looks better rx, ry, rz = node1.rX, node1.rY, node1.rZ if (rx > 180) then rx = rx - 360 end if (ry > 180) then ry = ry - 360 end -- (xx, yy, zz) <--> (node1.x, node1.y, node1.z) is perpendicular line under the car, used for facing arrows and collision check xx, yy, zz = getPositionFromElementOffset(node1.x, node1.y, node1.z, rx, ry, rz, -4) -- check hitpoints on the road _, gx, gy, gz, _ = processLineOfSight(node1.x, node1.y, node1.z, xx, yy, zz, true, false, false, true) -- plan b if there was no collision -- rx > 80: going straight up or upside down -- ry > 70 going sideways on a wall if not gx and abs(rx) < 80 and abs(ry) < 70 then gx, gy, gz = node1.x, node1.y, getGroundPosition(node1.x, node1.y, node1.z) -- dont snap to the road if too far if abs(gz - node1.z) > 15 then gx, gy, gz = nil end end -- there was collision under the car or node was simply snapped to ground if gx then -- push it above the road a little, works upside down too gx, gy, gz = getPositionFromElementOffset(gx, gy, gz, rx, ry, rz, 0.2) -- DEBUG: keep this -- one node and scanline -- dxDrawLine3D(gx, gy, gz-0.1, gx, gy, gz+0.1, tocolor(0,255,0, 255), 15) -- dxDrawLine3D(xx, yy, zz, node1.x, node1.y, node1.z) -- !!! if gx and xx2 and i ~= start then dxDrawMaterialLine3D( gx, gy, gz, xx2, yy2, zz2, img, arrowSize, tocolor(color_r, color_g, color_b, color_a), xx, yy, zz ) end -- xx2 -- !!! -- node1 and node1 from previous iteration are connected into a line xx2, yy2, zz2 = gx, gy, gz -- there was no collision else xx2, yy2, zz2 = nil, nil, nil -- DEBUG: keep this -- one node and scanline -- dxDrawLine3D(xx, yy, zz-0.1, xx, yy, zz+0.1, tocolor(255,0,0, 255), 15) -- dxDrawLine3D(xx, yy, zz, node1.x, node1.y, node1.z, tocolor(255,0,0, 255)) end -- gx end -- node check end -- for -- -- stop time measurement -------------------------------------------------------------------------------// -- end local vege = getTickCount() dxDrawText( inspect("ms time spent: " .. vege-eleje), 400, 420, 250) --// -- --------------------------------------------------------------------------------------------------------// end -- drawRacingLine -- read more: -- http://mathworld.wolfram.com/RelativeError.html -- https://www.lua.org/gems/sample.pdf
mit
maxrio/packages981213
net/smartsnmpd/files/mibs/system.lua
158
6428
-- -- This file is part of SmartSNMP -- Copyright (C) 2014, Credo Semiconductor Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License along -- with this program; if not, write to the Free Software Foundation, Inc., -- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -- local mib = require "smartsnmp" local uci = require "uci" -- System config local context = uci.cursor("/etc/config", "/tmp/.uci") -- scalar index local sysDesc = 1 local sysObjectID = 2 local sysUpTime = 3 local sysContact = 4 local sysName = 5 local sysLocation = 6 local sysServices = 7 local sysORLastChange = 8 -- table index local sysORTable = 9 -- entry index local sysOREntry = 1 -- list index local sysORIndex = 1 local sysORID = 2 local sysORDesc = 3 local sysORUpTime = 4 local startup_time = 0 local or_last_changed_time = 0 local function mib_system_startup(time) startup_time = time or_last_changed_time = time end mib_system_startup(os.time()) local sysGroup = {} local or_oid_cache = {} local or_index_cache = {} local or_table_cache = {} local or_table_reg = function (oid, desc) local row = {} row['oid'] = {} for i in string.gmatch(oid, "%d") do table.insert(row['oid'], tonumber(i)) end row['desc'] = desc row['uptime'] = os.time() table.insert(or_table_cache, row) or_last_changed_time = os.time() or_oid_cache[oid] = #or_table_cache or_index_cache = {} for i in ipairs(or_table_cache) do table.insert(or_index_cache, i) end end local or_table_unreg = function (oid) local or_idx = or_oid_cache[oid] if or_table_cache[or_idx] ~= nil then table.remove(or_table_cache, or_idx) or_last_changed_time = os.time() or_index_cache = {} for i in ipairs(or_table_cache) do table.insert(or_index_cache, i) end end end local last_load_time = os.time() local function need_to_reload() if os.difftime(os.time(), last_load_time) < 3 then return false else last_load_time = os.time() return true end end local function load_config() if need_to_reload() == true then context:load("smartsnmpd") end end context:load("smartsnmpd") local sysMethods = { ["or_table_reg"] = or_table_reg, ["or_table_unreg"] = or_table_unreg } mib.module_method_register(sysMethods) sysGroup = { rocommunity = 'public', [sysDesc] = mib.ConstString(function () load_config() return mib.sh_call("uname -a") end), [sysObjectID] = mib.ConstOid(function () load_config() local oid local objectid context:foreach("smartsnmpd", "smartsnmpd", function (s) objectid = s.objectid end) if objectid ~= nil then oid = {} for i in string.gmatch(objectid, "%d+") do table.insert(oid, tonumber(i)) end end return oid end), [sysUpTime] = mib.ConstTimeticks(function () load_config() return os.difftime(os.time(), startup_time) * 100 end), [sysContact] = mib.ConstString(function () load_config() local contact context:foreach("smartsnmpd", "smartsnmpd", function (s) contact = s.contact end) return contact end), [sysName] = mib.ConstString(function () load_config() return mib.sh_call("uname -n") end), [sysLocation] = mib.ConstString(function () load_config() local location context:foreach("smartsnmpd", "smartsnmpd", function (s) location = s.location end) return location end), [sysServices] = mib.ConstInt(function () load_config() local services context:foreach("smartsnmpd", "smartsnmpd", function (s) services = tonumber(s.services) end) return services end), [sysORLastChange] = mib.ConstTimeticks(function () load_config() return os.difftime(os.time(), or_last_changed_time) * 100 end), [sysORTable] = { [sysOREntry] = { [sysORIndex] = mib.UnaIndex(function () load_config() return or_index_cache end), [sysORID] = mib.ConstOid(function (i) load_config() return or_table_cache[i].oid end), [sysORDesc] = mib.ConstString(function (i) load_config() return or_table_cache[i].desc end), [sysORUpTime] = mib.ConstTimeticks(function (i) load_config() return os.difftime(os.time(), or_table_cache[i].uptime) * 100 end), } } } return sysGroup
gpl-2.0
LuaDist2/oil
lua/oil/kernel/lua/Dispatcher.lua
6
3727
-------------------------------------------------------------------------------- ------------------------------ ##### ## ------------------------------ ------------------------------ ## ## # ## ------------------------------ ------------------------------ ## ## ## ## ------------------------------ ------------------------------ ## ## # ## ------------------------------ ------------------------------ ##### ### ###### ------------------------------ -------------------------------- -------------------------------- ----------------------- An Object Request Broker in Lua ------------------------ -------------------------------------------------------------------------------- -- Project: OiL - ORB in Lua: An Object Request Broker in Lua -- -- Release: 0.5 -- -- Title : Object Request Dispatcher -- -- Authors: Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- -- dispatcher:Facet -- success:boolean, [except:table]|results... dispatch(key:string, operation:string|function, params...) -------------------------------------------------------------------------------- local unpack = unpack local oo = require "oil.oo" local Exception = require "oil.Exception" local Dispatcher = require "oil.kernel.base.Dispatcher" --[[VERBOSE]] local verbose = require "oil.verbose" module "oil.kernel.lua.Dispatcher" oo.class(_M, Dispatcher) -------------------------------------------------------------------------------- local Operations = { tostring = function(self) return tostring(self) end, unm = function(self) return -self end, len = function(self) return #self end, add = function(self, other) return self + other end, sub = function(self, other) return self - other end, mul = function(self, other) return self * other end, div = function(self, other) return self / other end, mod = function(self, other) return self % other end, pow = function(self, other) return self ^ other end, lt = function(self, other) return self < other end, eq = function(self, other) return self == other end, le = function(self, other) return self <= other end, concat = function(self, other) return self .. other end, call = function(self, ...) return self(...) end, index = function(self, field) return self[field] end, newindex = function(self, field, value) self[field] = value end, } -------------------------------------------------------------------------------- function dispatch(self, request) local object = self.servants:retrieve(request.objectkey) if object then local method = Operations[request.operation] if method then --[[VERBOSE]] verbose:dispatcher("dispatching operation ",object,":",request.operation,unpack(request, 1, request.n)) self:setresults(request, self.pcall(method, object, unpack(request, 1, request.n))) else self:setresults(request, false, Exception{ reason = "noimplement", message = "no implementation for operation of object with key", operation = operation, object = object, key = key, }) end else self:setresults(request, false, Exception{ reason = "badkey", message = "no object with key", key = key, }) end return true end
mit
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/Sprite.lua
1
17465
-------------------------------- -- @module Sprite -- @extend Node,TextureProtocol -- @parent_module cc -------------------------------- -- @overload self, cc.SpriteFrame -- @overload self, string -- @function [parent=#Sprite] setSpriteFrame -- @param self -- @param #string spriteFrameName -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- @overload self, cc.Texture2D -- @overload self, string -- @function [parent=#Sprite] setTexture -- @param self -- @param #string filename -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- Returns the Texture2D object used by the sprite. -- @function [parent=#Sprite] getTexture -- @param self -- @return Texture2D#Texture2D ret (return value: cc.Texture2D) -------------------------------- -- Sets whether the sprite should be flipped vertically or not.<br> -- param flippedY true if the sprite should be flipped vertically, false otherwise. -- @function [parent=#Sprite] setFlippedY -- @param self -- @param #bool flippedY -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- Sets whether the sprite should be flipped horizontally or not.<br> -- param flippedX true if the sprite should be flipped horizontally, false otherwise. -- @function [parent=#Sprite] setFlippedX -- @param self -- @param #bool flippedX -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] unregisterDrawScriptHandler -- @param self -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] registerDrawScriptHandler -- @param self -- @param #int handler -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] setDrawEnd -- @param self -- @param #function func -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- / @} -- @function [parent=#Sprite] getResourceType -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @overload self, cc.Texture2D, rect_table -- @overload self, cc.Texture2D -- @overload self, cc.Texture2D, rect_table, bool -- @function [parent=#Sprite] initWithTexture -- @param self -- @param #cc.Texture2D texture -- @param #rect_table rect -- @param #bool rotated -- @return bool#bool ret (return value: bool) -------------------------------- -- Returns the batch node object if this sprite is rendered by SpriteBatchNode.<br> -- return The SpriteBatchNode object if this sprite is rendered by SpriteBatchNode,<br> -- nullptr if the sprite isn't used batch node. -- @function [parent=#Sprite] getBatchNode -- @param self -- @return SpriteBatchNode#SpriteBatchNode ret (return value: cc.SpriteBatchNode) -------------------------------- -- Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex. -- @function [parent=#Sprite] getOffsetPosition -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- -- @function [parent=#Sprite] removeAllChildrenWithCleanup -- @param self -- @param #bool cleanup -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] setDrawBeg -- @param self -- @param #function func -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- @overload self, rect_table, bool, size_table -- @overload self, rect_table -- @function [parent=#Sprite] setTextureRect -- @param self -- @param #rect_table rect -- @param #bool rotated -- @param #size_table untrimmedSize -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- Initializes a sprite with an sprite frame name.<br> -- A SpriteFrame will be fetched from the SpriteFrameCache by name.<br> -- If the SpriteFrame doesn't exist it will raise an exception.<br> -- param spriteFrameName A key string that can fected a valid SpriteFrame from SpriteFrameCache.<br> -- return True if the sprite is initialized properly, false otherwise. -- @function [parent=#Sprite] initWithSpriteFrameName -- @param self -- @param #string spriteFrameName -- @return bool#bool ret (return value: bool) -------------------------------- -- Returns whether or not a SpriteFrame is being displayed. -- @function [parent=#Sprite] isFrameDisplayed -- @param self -- @param #cc.SpriteFrame frame -- @return bool#bool ret (return value: bool) -------------------------------- -- Returns the index used on the TextureAtlas. -- @function [parent=#Sprite] getAtlasIndex -- @param self -- @return long#long ret (return value: long) -------------------------------- -- -- @function [parent=#Sprite] setTextureScale -- @param self -- @param #float scale -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- Sets the batch node to sprite.<br> -- warning This method is not recommended for game developers. Sample code for using batch node<br> -- code<br> -- SpriteBatchNode *batch = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 15);<br> -- Sprite *sprite = Sprite::createWithTexture(batch->getTexture(), Rect(0, 0, 57, 57));<br> -- batch->addChild(sprite);<br> -- layer->addChild(batch);<br> -- endcode -- @function [parent=#Sprite] setBatchNode -- @param self -- @param #cc.SpriteBatchNode spriteBatchNode -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- js NA<br> -- lua NA -- @function [parent=#Sprite] getBlendFunc -- @param self -- @return BlendFunc#BlendFunc ret (return value: cc.BlendFunc) -------------------------------- -- / @{/ @name Animation methods<br> -- Changes the display frame with animation name and index.<br> -- The animation name will be get from the AnimationCache. -- @function [parent=#Sprite] setDisplayFrameWithAnimationName -- @param self -- @param #string animationName -- @param #long frameIndex -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- Sets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode. -- @function [parent=#Sprite] setTextureAtlas -- @param self -- @param #cc.TextureAtlas textureAtlas -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- Returns the current displayed frame. -- @function [parent=#Sprite] getSpriteFrame -- @param self -- @return SpriteFrame#SpriteFrame ret (return value: cc.SpriteFrame) -------------------------------- -- -- @function [parent=#Sprite] getResourceName -- @param self -- @return string#string ret (return value: string) -------------------------------- -- Whether or not the Sprite needs to be updated in the Atlas.<br> -- return True if the sprite needs to be updated in the Atlas, false otherwise. -- @function [parent=#Sprite] isDirty -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Sets the index used on the TextureAtlas.<br> -- warning Don't modify this value unless you know what you are doing. -- @function [parent=#Sprite] setAtlasIndex -- @param self -- @param #long atlasIndex -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- Makes the Sprite to be updated in the Atlas. -- @function [parent=#Sprite] setDirty -- @param self -- @param #bool dirty -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- Returns whether or not the texture rectangle is rotated. -- @function [parent=#Sprite] isTextureRectRotated -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Returns the rect of the Sprite in points. -- @function [parent=#Sprite] getTextureRect -- @param self -- @return rect_table#rect_table ret (return value: rect_table) -------------------------------- -- @overload self, string, rect_table -- @overload self, string -- @function [parent=#Sprite] initWithFile -- @param self -- @param #string filename -- @param #rect_table rect -- @return bool#bool ret (return value: bool) -------------------------------- -- / @{/ @name Functions inherited from TextureProtocol.<br> -- code<br> -- When this function bound into js or lua,the parameter will be changed.<br> -- In js: var setBlendFunc(var src, var dst).<br> -- In lua: local setBlendFunc(local src, local dst).<br> -- endcode -- @function [parent=#Sprite] setBlendFunc -- @param self -- @param #cc.BlendFunc blendFunc -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- Gets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode. -- @function [parent=#Sprite] getTextureAtlas -- @param self -- @return TextureAtlas#TextureAtlas ret (return value: cc.TextureAtlas) -------------------------------- -- Initializes a sprite with an SpriteFrame. The texture and rect in SpriteFrame will be applied on this sprite.<br> -- param spriteFrame A SpriteFrame object. It should includes a valid texture and a rect.<br> -- return True if the sprite is initialized properly, false otherwise. -- @function [parent=#Sprite] initWithSpriteFrame -- @param self -- @param #cc.SpriteFrame spriteFrame -- @return bool#bool ret (return value: bool) -------------------------------- -- Returns the flag which indicates whether the sprite is flipped horizontally or not.<br> -- It only flips the texture of the sprite, and not the texture of the sprite's children.<br> -- Also, flipping the texture doesn't alter the anchorPoint.<br> -- If you want to flip the anchorPoint too, and/or to flip the children too use:<br> -- sprite->setScaleX(sprite->getScaleX() * -1);<br> -- return true if the sprite is flipped horizontally, false otherwise. -- @function [parent=#Sprite] isFlippedX -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Return the flag which indicates whether the sprite is flipped vertically or not.<br> -- It only flips the texture of the sprite, and not the texture of the sprite's children.<br> -- Also, flipping the texture doesn't alter the anchorPoint.<br> -- If you want to flip the anchorPoint too, and/or to flip the children too use:<br> -- sprite->setScaleY(sprite->getScaleY() * -1);<br> -- return true if the sprite is flipped vertically, false otherwise. -- @function [parent=#Sprite] isFlippedY -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Returns the quad (tex coords, vertex coords and color) information.<br> -- js NA<br> -- lua NA -- @function [parent=#Sprite] getQuad -- @param self -- @return V3F_C4B_T2F_Quad#V3F_C4B_T2F_Quad ret (return value: cc.V3F_C4B_T2F_Quad) -------------------------------- -- Sets the vertex rect.<br> -- It will be called internally by setTextureRect.<br> -- Useful if you want to create 2x images from SD images in Retina Display.<br> -- Do not call it manually. Use setTextureRect instead. -- @function [parent=#Sprite] setVertexRect -- @param self -- @param #rect_table rect -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- @overload self, cc.Texture2D, rect_table, bool -- @overload self, cc.Texture2D -- @function [parent=#Sprite] createWithTexture -- @param self -- @param #cc.Texture2D texture -- @param #rect_table rect -- @param #bool rotated -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- Creates a sprite with an sprite frame name.<br> -- A SpriteFrame will be fetched from the SpriteFrameCache by spriteFrameName param.<br> -- If the SpriteFrame doesn't exist it will raise an exception.<br> -- param spriteFrameName A null terminated string which indicates the sprite frame name.<br> -- return An autoreleased sprite object. -- @function [parent=#Sprite] createWithSpriteFrameName -- @param self -- @param #string spriteFrameName -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- Creates a sprite with an sprite frame.<br> -- param spriteFrame A sprite frame which involves a texture and a rect.<br> -- return An autoreleased sprite object. -- @function [parent=#Sprite] createWithSpriteFrame -- @param self -- @param #cc.SpriteFrame spriteFrame -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- @overload self, cc.Node, int, string -- @overload self, cc.Node, int, int -- @function [parent=#Sprite] addChild -- @param self -- @param #cc.Node child -- @param #int zOrder -- @param #int tag -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] setAnchorPoint -- @param self -- @param #vec2_table anchor -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] setRotationSkewX -- @param self -- @param #float rotationX -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] setScaleY -- @param self -- @param #float scaleY -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- @overload self, float -- @overload self, float, float -- @function [parent=#Sprite] setScale -- @param self -- @param #float scaleX -- @param #float scaleY -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] isOpacityModifyRGB -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#Sprite] setOpacityModifyRGB -- @param self -- @param #bool modify -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#Sprite] setRotation -- @param self -- @param #float rotation -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] draw -- @param self -- @param #cc.Renderer renderer -- @param #mat4_table transform -- @param #unsigned int flags -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- / @{/ @name Functions inherited from Node. -- @function [parent=#Sprite] setScaleX -- @param self -- @param #float scaleX -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- js NA -- @function [parent=#Sprite] getDescription -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#Sprite] setRotationSkewY -- @param self -- @param #float rotationY -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] sortAllChildren -- @param self -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] reorderChild -- @param self -- @param #cc.Node child -- @param #int zOrder -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] ignoreAnchorPointForPosition -- @param self -- @param #bool value -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] setPositionZ -- @param self -- @param #float positionZ -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] removeChild -- @param self -- @param #cc.Node child -- @param #bool cleanup -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- Updates the quad according the rotation, position, scale values. -- @function [parent=#Sprite] updateTransform -- @param self -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] setSkewX -- @param self -- @param #float sx -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] setSkewY -- @param self -- @param #float sy -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- -- @function [parent=#Sprite] setVisible -- @param self -- @param #bool bVisible -- @return Sprite#Sprite self (return value: cc.Sprite) -------------------------------- -- js ctor -- @function [parent=#Sprite] Sprite -- @param self -- @return Sprite#Sprite self (return value: cc.Sprite) return nil
mit
opentechinstitute/luci
applications/luci-olsr/luasrc/model/cbi/olsr/olsrdhna6.lua
38
1176
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Manuel Munz <freifunk at somakoma dot de> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci".cursor() mh = Map("olsrd6", translate("OLSR - HNA6-Announcements"), translate("Hosts in a OLSR routed network can announce connecitivity " .. "to external networks using HNA6 messages.")) hna6 = mh:section(TypedSection, "Hna6", translate("Hna6"), translate("IPv6 network must be given in full notation, " .. "prefix must be in CIDR notation.")) hna6.addremove = true hna6.anonymous = true hna6.template = "cbi/tblsection" net6 = hna6:option(Value, "netaddr", translate("Network address")) net6.datatype = "ip6addr" net6.placeholder = "fec0:2200:106:0:0:0:0:0" net6.default = "fec0:2200:106:0:0:0:0:0" msk6 = hna6:option(Value, "prefix", translate("Prefix")) msk6.datatype = "range(0,128)" msk6.placeholder = "128" msk6.default = "128" return mh
apache-2.0
sebastianlis/OOP-Samples-for-Corona-SDK
classes/samples/Monetization/InAppPurchase.lua
1
4534
require "classes.constants.screen" InAppPurchase={} function InAppPurchase:new() local this = display.newGroup() local public = this local private = {} local widget = require("widget") local store = require("plugin.google.iap.v3") local background = display.newImageRect("img/backgroundMonetization.png", 360, 570) local eyes = display.newImageRect("img/eyes.png", 255, 180) local buttonSmallCoffee = widget.newButton({ id = "buttonSmallCoffee", x = screen.centerX - 108, y = screen.centerY + 122, width = 101, height = 198, defaultFile = "img/buttonCoffeeSmallDefault.png", overFile = "img/buttonCoffeeSmallPressed.png", onRelease = function(event) if event.phase == "ended" then private.onButtonSmallCoffee(event) end end }) local buttonStrongCoffee = widget.newButton({ id = "buttonStrongCoffee", x = screen.centerX-1, y = screen.centerY + 122, width = 101, height = 198, defaultFile = "img/buttonCoffeeStrongDefault.png", overFile = "img/buttonCoffeeStrongPressed.png", onRelease = function(event) if event.phase == "ended" then private.onButtonStrongCoffee(event) end end }) local buttonNightCoffee = widget.newButton({ id = "buttonNightCoffee", x = screen.centerX + 105, y = screen.centerY + 122, width = 101, height = 198, defaultFile = "img/buttonCoffeeNightDefault.png", overFile = "img/buttonCoffeeNightPressed.png", onRelease = function(event) if event.phase == "ended" then private.onButtonAllNightCoffee(event) end end }) local googleIAPv3 = false local platform = system.getInfo("platformName") local currentProductList = nil function private.InAppPurchase() background.x = screen.centerX background.y = screen.centerY eyes.x = screen.centerX eyes.y = screen.centerY-86 this:insert(background) this:insert(eyes) this:insert(buttonSmallCoffee) this:insert(buttonStrongCoffee) this:insert(buttonNightCoffee) store.init( "google", private.transactionCallback ) end function private.transactionCallback(event) local productID = event.transaction.productIdentifier if event.transaction.state == "purchased" then print("Product Purchased: ", productID) if productID == "com.yourcompany.coffeesmall" then timer.performWithDelay(1000, function() store.consumePurchase( "com.yourcompany.coffeesmall", private.transactionCallback) end ) elseif productID == "com.yourcompany.coffeestrong" then timer.performWithDelay(1000, function() store.consumePurchase( "com.yourcompany.coffeestrong", private.transactionCallback) end ) elseif productID == "com.yourcompany.coffeeallnight" then timer.performWithDelay(1000, function() store.consumePurchase( "com.yourcompany.coffeeallnight", private.transactionCallback) end ) end elseif event.transaction.state == "restored" then elseif event.transaction.state == "refunded" then elseif event.transaction.state == "cancelled" then elseif event.transaction.state == "failed" then else end store.finishTransaction(event.transaction) --Tell the store we are done with the transaction. If you are providing downloadable content, do not call this until the download has completed. end function private.onButtonSmallCoffee(event) store.purchase("com.yourcompany.coffeesmall") end function private.onButtonStrongCoffee(event) store.purchase("com.yourcompany.coffeestrong") end function private.onButtonAllNightCoffee(event) store.purchase("com.yourcompany.coffeeallnight") end function public:destroy() background:removeSelf() background = nil eyes:removeSelf() eyes = nil buttonSmallCoffee:removeSelf() buttonSmallCoffee = nil buttonStrongCoffee:removeSelf() buttonStrongCoffee = nil buttonNightCoffee:removeSelf() buttonNightCoffee = nil this:removeSelf() this = nil end private.InAppPurchase() return this end return InAppPurchase
mit
raymondtfr/forgottenserver
data/talkactions/scripts/deathlist.lua
43
2176
local function getArticle(str) return str:find("[AaEeIiOoUuYy]") == 1 and "an" or "a" end local function getMonthDayEnding(day) if day == "01" or day == "21" or day == "31" then return "st" elseif day == "02" or day == "22" then return "nd" elseif day == "03" or day == "23" then return "rd" else return "th" end end local function getMonthString(m) return os.date("%B", os.time{year = 1970, month = m, day = 1}) end function onSay(player, words, param) local resultId = db.storeQuery("SELECT `id`, `name` FROM `players` WHERE `name` = " .. db.escapeString(param)) if resultId ~= false then local targetGUID = result.getDataInt(resultId, "id") local targetName = result.getDataString(resultId, "name") result.free(resultId) local str = "" local breakline = "" local resultId = db.storeQuery("SELECT `time`, `level`, `killed_by`, `is_player` FROM `player_deaths` WHERE `player_id` = " .. targetGUID .. " ORDER BY `time` DESC") if resultId ~= false then repeat if str ~= "" then breakline = "\n" end local date = os.date("*t", result.getDataInt(resultId, "time")) local article = "" local killed_by = result.getDataString(resultId, "killed_by") if result.getDataInt(resultId, "is_player") == 0 then article = getArticle(killed_by) .. " " killed_by = string.lower(killed_by) end if date.day < 10 then date.day = "0" .. date.day end if date.hour < 10 then date.hour = "0" .. date.hour end if date.min < 10 then date.min = "0" .. date.min end if date.sec < 10 then date.sec = "0" .. date.sec end str = str .. breakline .. " " .. date.day .. getMonthDayEnding(date.day) .. " " .. getMonthString(date.month) .. " " .. date.year .. " " .. date.hour .. ":" .. date.min .. ":" .. date.sec .. " Died at Level " .. result.getDataInt(resultId, "level") .. " by " .. article .. killed_by .. "." until not result.next(resultId) result.free(resultId) end if str == "" then str = "No deaths." end player:popupFYI("Deathlist for player, " .. targetName .. ".\n\n" .. str) else player:sendCancelMessage("A player with that name does not exist.") end return false end
gpl-2.0
Craige/prosody-modules
mod_s2s_idle_timeout/mod_s2s_idle_timeout.lua
32
1590
local now = os.time; local s2smanager = require "core.s2smanager"; local timer = require "util.timer"; local s2s_sessions = setmetatable({}, { __mode = "kv" }); local idle_timeout = module:get_option("s2s_idle_timeout") or 300; local check_interval = math.ceil(idle_timeout * 0.75); local function install_checks(session) if not session.last_received_time then session.last_received_time = now(); if session.direction == "incoming" then local _data = session.data; function session.data(conn, data) session.last_received_time = now(); return _data(conn, data); end else local _sends2s = session.sends2s; function session.sends2s(data) session.last_received_time = now(); return _sends2s(data); end end s2s_sessions[session] = true; end end module:hook("s2s-authenticated", function (event) install_checks(event.session); end); function check_idle_sessions(time) time = time or now(); for session in pairs(s2s_sessions) do local last_received_time = session.last_received_time; if last_received_time and time - last_received_time > idle_timeout then module:log("debug", "Closing idle connection %s->%s", session.from_host or "(unknown)", session.to_host or "(unknown)"); session:close(); -- Close-on-idle isn't an error s2s_sessions[session] = nil; end end return check_interval; end timer.add_task(check_interval, check_idle_sessions); function module.save() return { s2s_sessions = s2s_sessions }; end function module.restore(data) s2s_sessions = setmetatable(data.s2s_sessions or {}, { __mode = "kv" }); end
mit
yuri/sfoto
lua/sputnik/actions/sfoto.lua
1
11748
----------------------------------------------------------------------------- -- Implements Sputnik actions for a photoalbum / blog combo. ----------------------------------------------------------------------------- module(..., package.seeall) local ITEMS_PER_ROW = 5 local imagegrid = require("sfoto.imagegrid") local wiki = require("sputnik.actions.wiki") local javascript = require("sfoto.javascript") require("sfoto") ----------------------------------------------------------------------------- -- A table of actions for export. ----------------------------------------------------------------------------- actions = {} ----------------------------------------------------------------------------- -- Returns the HTML (without the wrapper) for displaying a single photo, -- together with links to previous and next ones. ----------------------------------------------------------------------------- actions.show_photo_content = function(node, request, sputnik) -- find all photos in this album that the user is authorized to see local parent_id, short_id = node:get_parent_id() local parent = sputnik:get_node(parent_id) local user_access = sputnik.auth:get_metadata(request.user, "access") local photos = sfoto.visible_photos(parent.content.photos, request.user, sputnik) -- find the requested photo among them or post an error message local this_photo for i, photo in ipairs(photos) do if photo.id == short_id then this_photo = i node.title = parent.title.." #"..i end end if not this_photo then node:post_error("No such photo or access denied") return "" end -- format the photo display local link_notes = { [true] = "Click for the next photo", [false] = "This is the last photo photo, click to return" } local prev_photo, next_photo = "", "" if photos[this_photo-1] then prev_photo = photos[this_photo-1].id end if photos[this_photo+1] then next_photo = photos[this_photo+1].id end return cosmo.f(node.templates.SINGLE_PHOTO){ photo_url = sfoto.photo_url(node.id, "sized", sputnik.config), original_size = sfoto.photo_url(node.id, "original", sputnik.config), next_link = sputnik:make_url(parent_id.."/"..next_photo), prev_link = sputnik:make_url(parent_id.."/"..prev_photo), note = link_notes[photos[this_photo+1]~=nil] } end ----------------------------------------------------------------------------- -- Returns the HTML (complete page) for displaying a single photo. ----------------------------------------------------------------------------- actions.show_photo = function(node, request, sputnik) node.inner_html = actions.show_photo_content(node, request, sputnik) return node.wrappers.default(node, request, sputnik) end ----------------------------------------------------------------------------- -- Returns the HTML (without the wrapper) for displaying a blog post. ----------------------------------------------------------------------------- actions.show_entry_content = function(node, request, sputnik) -- figure out if we want to add a title local title = "" if request.params.show_title then title = "<h1>"..node.title.."</h1>\n\n" end -- handle image grids local gridder = imagegrid.new(node, photo_url, sputnik) local content = gridder:add_flexgrids(node.content or "") content = gridder:add_simplegrids(content) -- decide if we want to put a width-limited div around it -- (needed for generating page thumbnails) local html = title..node.markup.transform(content) if request.params.width then html = cosmo.f(node.templates.FOR_THUMB){ width = request.params.width, html = html } end return html end ----------------------------------------------------------------------------- -- Returns the HTML (complete page) for displaying a blog post. ----------------------------------------------------------------------------- actions.show_entry = function(node, request, sputnik) request.is_indexable = true node.inner_html = node.actions.show_content(node, request, sputnik) return node.wrappers.default(node, request, sputnik) end ----------------------------------------------------------------------------- -- Returns the HTML (without the wrapper) for displaying an album. ----------------------------------------------------------------------------- actions.show_album_content = function(node, request, sputnik, options) options = options or {} -- select viewable photos local user_access = sputnik.auth:get_metadata(request.user, "access") local photos, num_hidden = sfoto.visible_photos(node.content.photos, request.user, sputnik) -- attach URLs to them for i, photo in ipairs(photos) do photo.if_video = cosmo.c(photo.is_video){} photo.if_photo = cosmo.c(not photo.is_video){} for _, key in ipairs{"thumb", "video_thumb", "sized", "sized_video_frame", "original", "video_file"} do photo[key] = sfoto.photo_url(node.id.."/"..photo.id, key, sputnik.config) end end local first_photo_url = "" if #photos > 0 then first_photo_url = sfoto.photo_url(node.id.."/"..photos[1].id, "sized", sputnik.config) end -- group into rows local rows = sfoto.group(photos, "photos", options.items_per_row or ITEMS_PER_ROW) -- figure out if we need a title (for AHAH) local title = request.params.show_title and "<h1>"..node.title.."</h1>\n\n" or "" template = options.template or node.templates.ALBUM -- format the output return title..cosmo.f(template){ album_url = sputnik:make_url(node.id), title = node.title, rows = rows, first_photo_url = first_photo_url, if_has_hidden = cosmo.c(num_hidden > 0) { lock_icon_url = sputnik:make_url("sfoto/lock.png"), num_hidden = num_hidden, } } end ----------------------------------------------------------------------------- -- Returns the HTML (complete page) for displaying an album. ----------------------------------------------------------------------------- actions.show_album = function(node, request, sputnik) node.inner_html = actions.show_album_content(node, request, sputnik) return node.wrappers.default(node, request, sputnik) end ----------------------------------------------------------------------------- -- Returns the HTML for displaying an album inside a JS popup. ----------------------------------------------------------------------------- actions.show_album_for_js_viewer = function(node, request, sputnik) local options = { template=node.templates.ALBUM_FOR_VIEWER, items_per_row = 1, } return actions.show_album_content(node, request, sputnik, options) end function get_visible_items_by_tag(sputnik, user, id, tag) local function make_key(tag) return (user or "Anon").."/"..tag end if not TAG_CACHE then TAG_CACHE = {} if not TAG_CACHE[user] then local items = get_visible_nodes_lazily(sputnik, user, id) for i, item in ipairs(items) do if item.tags then for tag in item.tags:gmatch("%S*") do local key = make_key(tag) TAG_CACHE[key] = TAG_CACHE[key] or {} table.insert(TAG_CACHE[key], item) end end end TAG_CACHE[user] = true end end return TAG_CACHE[make_key(tag)] or {} end function get_visible_nodes_lazily(sputnik, user, id) if not SFOTO_NODE_CACHE then SFOTO_NODE_CACHE = {} end local key = (user or "Anon").."/"..id if SFOTO_NODE_CACHE[key] then return SFOTO_NODE_CACHE[key] else local nodes = wiki.get_visible_nodes(sputnik, user, id, {lazy=true}) SFOTO_NODE_CACHE[key] = nodes return nodes end end ----------------------------------------------------------------------------- -- Shows the HTML (just the content) for an index page. ----------------------------------------------------------------------------- function actions.show_index_content(node, request, sputnik) local items if node.id:match("/[a-z]") then local section, tag node.id, section, tag = node.id:match("(.-)/(.-)/(.*)") items = get_visible_items_by_tag(sputnik, request.user, node.id, tag) else items = get_visible_nodes_lazily(sputnik, request.user, node.id) end local months, url_for_reversing if request.params.ascending then url_for_reversing = sputnik:make_url(node.id, nil) months = sfoto.make_calendar(items, sputnik, true) else url_for_reversing = sputnik:make_url(node.id, nil, {ascending='1'}) months = sfoto.make_calendar(items, sputnik) end return cosmo.f(node.templates.INDEX){ reverse_url = url_for_reversing, months = months } end local TEMPLATE = [==[ <table> <style> td.tag_list_table {vertical-align: top} td.tag_list_table a {text-decoration: none; font-size: 200%} </style> $do_groups[=[ <tr><td colspan="2"><h2>$title</h2></td></tr> $items[[ <tr><td><a href="$make_url{$id}"> <img src="http://media.freewisdom.org/freewisdom/albums/$thumb.thumb.jpg"/> </a></td><td class='tag_list_table'><a href="$make_url{$id}">$title</a></td></tr> ]] ]=] </table> ]==] actions.show_tag_list = function(node, request, sputnik) node.inner_html = cosmo.f(TEMPLATE) { make_url = function(args) return sputnik:make_url(unpack(args)) end, do_groups = function() for _, group in ipairs(node.content.groups) do cosmo.yield(group) end end } return node.wrappers.default(node, request, sputnik) end --require"versium.sqlite3" --require"versium.filedir" --cache = versium.filedir.new{"/tmp/cache/"} --sqlite3.new{"/tmp/cache.db"} ----------------------------------------------------------------------------- -- Handles the basic "show" request with caching. ----------------------------------------------------------------------------- actions.show_index = function(node, request, sputnik) if sputnik.app_cache then --local tracker = sputnik.saci:get_node_info("sfoto_tracker") local key = node.id.."|"..request.query_string.."|"..(request.user or "Anon") cached_info = sputnik.app_cache:get_node_info(key) or {} --if (not cached_info.timestamp) or (cached_info.timestamp < tracker.timestamp) then if not cached_info.timestamp then node.inner_html = actions.show_index_content(node, request, sputnik) sputnik.app_cache:save_version(key, node.inner_html, "sfoto") else node.inner_html = sputnik.app_cache:get_node(key) end else node.inner_html = actions.show_index_content(node, request, sputnik) end node:add_javascript_snippet(cosmo.f(javascript.INDEX){}) node:add_javascript_link(sputnik:make_url("sfoto/dragscrollable.js")) node:add_javascript_link(sputnik.config.MEDIA_PLAYER_JS_URL) node:add_css_snippet(cosmo.f(node.templates.CSS_FOR_INDEX){}) return node.wrappers.default(node, request, sputnik) end
mit
gedads/Neodynamis
scripts/zones/Northern_San_dOria/npcs/Maurinne.lua
3
1039
----------------------------------- -- Area: Northern San d'Oria -- NPC: Maurinne -- Type: Standard Dialogue NPC -- @zone 231 -- !pos -127.185 0.000 179.193 -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,MAURINNE_DIALOG); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
starlightknight/darkstar
scripts/zones/Behemoths_Dominion/mobs/King_Behemoth.lua
11
1784
----------------------------------- -- Area: Behemoth's Dominion -- HNM: King Behemoth ----------------------------------- local ID = require("scripts/zones/Behemoths_Dominion/IDs") mixins = {require("scripts/mixins/rage")} require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/titles") require("scripts/globals/magic") ----------------------------------- function onMobInitialize(mob) mob:setMobMod(dsp.mobMod.MAGIC_COOL, 60) end function onMobSpawn(mob) if LandKingSystem_NQ > 0 or LandKingSystem_HQ > 0 then GetNPCByID(ID.npc.BEHEMOTH_QM):setStatus(dsp.status.DISAPPEAR) end mob:setLocalVar("[rage]timer", 3600) -- 60 minutes end function onSpellPrecast(mob, spell) if spell:getID() == 218 then spell:setAoE(dsp.magic.aoe.RADIAL) spell:setFlag(dsp.magic.spellFlag.HIT_ALL) spell:setRadius(30) spell:setAnimation(280) spell:setMPCost(1) end end function onMobDeath(mob, player, isKiller) player:addTitle(dsp.title.BEHEMOTH_DETHRONER) end function onMobDespawn(mob) -- Set King_Behemoth's Window Open Time if LandKingSystem_HQ ~= 1 then local wait = 72 * 3600 SetServerVariable("[POP]King_Behemoth", os.time() + wait) -- 3 days if LandKingSystem_HQ == 0 then -- Is time spawn only DisallowRespawn(mob:getID(), true) end end -- Set Behemoth's spawnpoint and respawn time (21-24 hours) if LandKingSystem_NQ ~= 1 then SetServerVariable("[PH]King_Behemoth", 0) DisallowRespawn(ID.mob.BEHEMOTH, false) UpdateNMSpawnPoint(ID.mob.BEHEMOTH) GetMobByID(ID.mob.BEHEMOTH):setRespawnTime(75600 + math.random(0, 6) * 1800) -- 21 - 24 hours with half hour windows end end
gpl-3.0
gedads/Neodynamis
scripts/zones/Port_Bastok/npcs/Synergy_Engineer.lua
3
1051
----------------------------------- -- Area: Port Bastok -- NPC: Synergy Engineer -- Type: Standard NPC -- @zone 236 -- !pos 37.700 -0.3 -50.500 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x2afa); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
hades2013/openwrt-mtk
package/ralink/ui/luci-mtk/src/applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-format.lua
80
3636
--[[ 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", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true format_au = module:option(ListValue, "format_au", "Sun Microsystems AU format (signed linear)", "") format_au:value("yes", "Load") format_au:value("no", "Do Not Load") format_au:value("auto", "Load as Required") format_au.rmempty = true format_g723 = module:option(ListValue, "format_g723", "G.723.1 Simple Timestamp File Format", "") format_g723:value("yes", "Load") format_g723:value("no", "Do Not Load") format_g723:value("auto", "Load as Required") format_g723.rmempty = true format_g726 = module:option(ListValue, "format_g726", "Raw G.726 (16/24/32/40kbps) data", "") format_g726:value("yes", "Load") format_g726:value("no", "Do Not Load") format_g726:value("auto", "Load as Required") format_g726.rmempty = true format_g729 = module:option(ListValue, "format_g729", "Raw G729 data", "") format_g729:value("yes", "Load") format_g729:value("no", "Do Not Load") format_g729:value("auto", "Load as Required") format_g729.rmempty = true format_gsm = module:option(ListValue, "format_gsm", "Raw GSM data", "") format_gsm:value("yes", "Load") format_gsm:value("no", "Do Not Load") format_gsm:value("auto", "Load as Required") format_gsm.rmempty = true format_h263 = module:option(ListValue, "format_h263", "Raw h263 data", "") format_h263:value("yes", "Load") format_h263:value("no", "Do Not Load") format_h263:value("auto", "Load as Required") format_h263.rmempty = true format_jpeg = module:option(ListValue, "format_jpeg", "JPEG (Joint Picture Experts Group) Image", "") format_jpeg:value("yes", "Load") format_jpeg:value("no", "Do Not Load") format_jpeg:value("auto", "Load as Required") format_jpeg.rmempty = true format_pcm = module:option(ListValue, "format_pcm", "Raw uLaw 8khz Audio support (PCM)", "") format_pcm:value("yes", "Load") format_pcm:value("no", "Do Not Load") format_pcm:value("auto", "Load as Required") format_pcm.rmempty = true format_pcm_alaw = module:option(ListValue, "format_pcm_alaw", "load => .so ; Raw aLaw 8khz PCM Audio support", "") format_pcm_alaw:value("yes", "Load") format_pcm_alaw:value("no", "Do Not Load") format_pcm_alaw:value("auto", "Load as Required") format_pcm_alaw.rmempty = true format_sln = module:option(ListValue, "format_sln", "Raw Signed Linear Audio support (SLN)", "") format_sln:value("yes", "Load") format_sln:value("no", "Do Not Load") format_sln:value("auto", "Load as Required") format_sln.rmempty = true format_vox = module:option(ListValue, "format_vox", "Dialogic VOX (ADPCM) File Format", "") format_vox:value("yes", "Load") format_vox:value("no", "Do Not Load") format_vox:value("auto", "Load as Required") format_vox.rmempty = true format_wav = module:option(ListValue, "format_wav", "Microsoft WAV format (8000hz Signed Line", "") format_wav:value("yes", "Load") format_wav:value("no", "Do Not Load") format_wav:value("auto", "Load as Required") format_wav.rmempty = true format_wav_gsm = module:option(ListValue, "format_wav_gsm", "Microsoft WAV format (Proprietary GSM)", "") format_wav_gsm:value("yes", "Load") format_wav_gsm:value("no", "Do Not Load") format_wav_gsm:value("auto", "Load as Required") format_wav_gsm.rmempty = true return cbimap
gpl-2.0
starlightknight/darkstar
scripts/globals/spells/bluemagic/plasma_charge.lua
12
1283
----------------------------------------- -- Spell: Plasma Charge -- Covers you with magical lightning spikes. Enemies that hit you take lightning damage -- Spell cost: 24 MP -- Monster Type: Luminians -- Spell Type: Magical (Lightning) -- Blue Magic Points: 5 -- Stat Bonus: STR+3 DEX+3 -- Level: 75 -- Casting Time: 3 seconds -- Recast Time: 60 seconds -- Duration: 60 seconds -- -- Combos: Auto Refresh ----------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/bluemagic") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local typeEffect = dsp.effect.SHOCK_SPIKES local power = 5 local duration = 60 if (caster:hasStatusEffect(dsp.effect.DIFFUSION)) then local diffMerit = caster:getMerit(dsp.merit.DIFFUSION) if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit end caster:delStatusEffect(dsp.effect.DIFFUSION) end if (target:addStatusEffect(typeEffect,power,0,duration) == false) then spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end return typeEffect end
gpl-3.0
starlightknight/darkstar
scripts/zones/Chateau_dOraguille/npcs/Chalvatot.lua
9
4381
----------------------------------- -- Area: Chateau d'Oraguille -- NPC: Chalvatot -- Finish Mission "The Crystal Spring" -- Start & Finishes Quests: Her Majesty's Garden -- Involved in Quest: Lure of the Wildcat (San d'Oria) -- !pos -105 0.1 72 233 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); local ID = require("scripts/zones/Chateau_dOraguille/IDs"); ----------------------------------- function onTrade(player,npc,trade) local herMajestysGarden = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.HER_MAJESTY_S_GARDEN); -- HER MAJESTY'S GARDEN (derfland humus) if (herMajestysGarden == QUEST_ACCEPTED and trade:hasItemQty(533,1) and trade:getItemCount() == 1) then player:startEvent(83); end; end; function onTrigger(player,npc) local currentMission = player:getCurrentMission(SANDORIA); local MissionStatus = player:getCharVar("MissionStatus"); local circleOfTime = player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.THE_CIRCLE_OF_TIME); local circleProgress = player:getCharVar("circleTime"); local lureOfTheWildcat = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.LURE_OF_THE_WILDCAT); local WildcatSandy = player:getCharVar("WildcatSandy"); local herMajestysGarden = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.HER_MAJESTY_S_GARDEN); -- THE CRYSTAL SPRING (San d'Oria 3-2) if (currentMission == dsp.mission.id.sandoria.THE_CRYSTAL_SPRING and MissionStatus == 3) then player:startEvent(556); -- LEAUTE'S LAST WISHES (San d'Oria 6-1) elseif (currentMission == dsp.mission.id.sandoria.LEAUTE_S_LAST_WISHES and MissionStatus == 4 and player:hasKeyItem(dsp.ki.DREAMROSE)) then player:startEvent(111); -- CIRCLE OF TIME (Bard AF3) elseif (circleOfTime == QUEST_ACCEPTED) then if (circleProgress == 5) then player:startEvent(99); elseif (circleProgress == 6) then player:startEvent(98); elseif (circleProgress == 7) then player:startEvent(97); elseif (circleProgress == 9) then player:startEvent(96); end; -- LURE OF THE WILDCAT elseif (lureOfTheWildcat == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,19) == false) then player:startEvent(561); -- HER MAJESTY'S GARDEN elseif (herMajestysGarden == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 4) then player:startEvent(84); elseif (herMajestysGarden == QUEST_ACCEPTED) then player:startEvent(82); -- DEFAULT DIALOG else player:startEvent(531); end; end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) -- SAN D'ORIA MISSIONS if (csid == 556 or csid == 111) then finishMissionTimeline(player,3,csid,option); -- CIRCLE OF TIME elseif (csid == 99 and option == 0) then player:setCharVar("circleTime",6); elseif ((csid == 98 or csid == 99) and option == 1) then player:setCharVar("circleTime",7); player:addKeyItem(dsp.ki.MOON_RING); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.MOON_RING); elseif (csid == 96) then if (player:getFreeSlotsCount() ~= 0) then player:addItem(12647); player:messageSpecial(ID.text.ITEM_OBTAINED,12647) player:completeQuest(JEUNO,dsp.quest.id.jeuno.THE_CIRCLE_OF_TIME); player:addTitle(dsp.title.PARAGON_OF_BARD_EXCELLENCE); player:setCharVar("circleTime",0); else player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED); end; -- LURE OF THE WILDCAT elseif (csid == 561) then player:setMaskBit(player:getCharVar("WildcatSandy"),"WildcatSandy",19,true); -- HER MAJESTY'S GARDEN elseif (csid == 84 and option == 1) then player:addQuest(SANDORIA,dsp.quest.id.sandoria.HER_MAJESTY_S_GARDEN); elseif (csid == 83) then player:tradeComplete(); player:addKeyItem(dsp.ki.MAP_OF_THE_NORTHLANDS_AREA); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.MAP_OF_THE_NORTHLANDS_AREA); player:addFame(SANDORIA,30); player:completeQuest(SANDORIA,dsp.quest.id.sandoria.HER_MAJESTY_S_GARDEN); end; end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Temple_of_Uggalepih/npcs/_4f3.lua
3
2093
----------------------------------- -- Area: Temple of Uggalepih -- NPC: _4f3 -- Notes: Tonberry Priest Room (Offers Tonberry Hate Reset) -- !pos 60.001 -1.653 -147.755 159 ----------------------------------- package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Temple_of_Uggalepih/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local killCount = player:getVar("EVERYONES_GRUDGE_KILLS"); if (player:hasKeyItem(291) == true) then if (killCount >= 1) then local payment = 250 * ((killCount/20)+1); player:startEvent(0x0042,0,payment); else player:messageSpecial(NO_HATE); -- Hate is already 0 end else player:messageSpecial(DOOR_SHUT); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); -- TODO: The Priest should cast a spell on the player at the end of the Cutscene. if (csid == 0x0042 and option == 1) then if (player:delGil(250 * ((player:getVar("EVERYONES_GRUDGE_KILLS")/20)+1))) then player:setVar("EVERYONES_GRUDGE_KILLS",0); player:messageSpecial(HATE_RESET); --GetNPCByID(17428933):castSpell(260); local mob = GetNPCByID( 17428933 ); if (mob ~= nil) then --mob:injectActionPacket( 43, 43 ); else printf( "MOB IS NULL! %d", 17428933 ); end end end end;
gpl-3.0
dimitarcl/premake-dev
tests/config/test_targetinfo.lua
2
5642
-- -- tests/config/test_targetinfo.lua -- Test the config object's build target accessor. -- Copyright (c) 2011-2013 Jason Perkins and the Premake project -- local suite = test.declare("config_targetinfo") local config = premake.config -- -- Setup and teardown -- local sln, prj function suite.setup() _ACTION = "test" sln, prj = test.createsolution() system "macosx" end local function prepare() local cfg = test.getconfig(prj, "Debug") return config.gettargetinfo(cfg) end -- -- Directory should be current (".") by default. -- function suite.directoryIsDot_onNoTargetDir() i = prepare() test.isequal(".", path.getrelative(os.getcwd(), i.directory)) end -- -- Directory uses targetdir() value if present. -- function suite.directoryIsTargetDir_onTargetDir() targetdir "../bin" i = prepare() test.isequal("../bin", path.getrelative(os.getcwd(), i.directory)) end -- -- Base name should use the project name by default. -- function suite.basenameIsProjectName_onNoTargetName() i = prepare() test.isequal("MyProject", i.basename) end -- -- Base name should use targetname() if present. -- function suite.basenameIsTargetName_onTargetName() targetname "MyTarget" i = prepare() test.isequal("MyTarget", i.basename) end -- -- Base name should use suffix if present. -- function suite.basenameUsesSuffix_onTargetSuffix() targetsuffix "-d" i = prepare() test.isequal("MyProject-d", i.basename) end -- -- Name should not have an extension for Posix executables. -- function suite.nameHasNoExtension_onMacOSXConsoleApp() system "MacOSX" i = prepare() test.isequal("MyProject", i.name) end function suite.nameHasNoExtension_onLinuxConsoleApp() system "Linux" i = prepare() test.isequal("MyProject", i.name) end function suite.nameHasNoExtension_onBSDConsoleApp() system "BSD" i = prepare() test.isequal("MyProject", i.name) end -- -- Name should use ".exe" for Windows executables. -- function suite.nameUsesExe_onWindowsConsoleApp() kind "ConsoleApp" system "Windows" i = prepare() test.isequal("MyProject.exe", i.name) end function suite.nameUsesExe_onWindowsWindowedApp() kind "WindowedApp" system "Windows" i = prepare() test.isequal("MyProject.exe", i.name) end -- -- Name should use ".dll" for Windows shared libraries. -- function suite.nameUsesDll_onWindowsSharedLib() kind "SharedLib" system "Windows" i = prepare() test.isequal("MyProject.dll", i.name) end -- -- Name should use ".lib" for Windows static libraries. -- function suite.nameUsesLib_onWindowsStaticLib() kind "StaticLib" system "Windows" i = prepare() test.isequal("MyProject.lib", i.name) end -- -- Name should use "lib and ".dylib" for Mac shared libraries. -- function suite.nameUsesLib_onMacSharedLib() kind "SharedLib" system "MacOSX" i = prepare() test.isequal("libMyProject.dylib", i.name) end -- -- Name should use "lib and ".a" for Mac static libraries. -- function suite.nameUsesLib_onMacStaticLib() kind "StaticLib" system "MacOSX" i = prepare() test.isequal("libMyProject.a", i.name) end -- -- Name should use "lib" and ".so" for Linux shared libraries. -- function suite.nameUsesLib_onLinuxSharedLib() kind "SharedLib" system "Linux" i = prepare() test.isequal("libMyProject.so", i.name) end -- -- Name should use "lib" and ".a" for Linux shared libraries. -- function suite.nameUsesLib_onLinuxStaticLib() kind "StaticLib" system "Linux" i = prepare() test.isequal("libMyProject.a", i.name) end -- -- Name should use ".elf" for PS3 executables. -- function suite.nameUsesElf_onPS3ConsoleApp() kind "ConsoleApp" system "PS3" i = prepare() test.isequal("MyProject.elf", i.name) end -- -- Name should use "lib" and ".a" for PS3 static libraries. -- function suite.nameUsesLib_onPS3StaticLib() kind "StaticLib" system "PS3" i = prepare() test.isequal("libMyProject.a", i.name) end -- -- Name should use ".exe" for Xbox360 executables. -- function suite.nameUsesExe_onWindowsConsoleApp() kind "ConsoleApp" system "Xbox360" i = prepare() test.isequal("MyProject.exe", i.name) end function suite.nameUsesLib_onXbox360StaticLib() kind "StaticLib" system "Xbox360" i = prepare() test.isequal("MyProject.lib", i.name) end -- -- Name should use a prefix if set. -- function suite.nameUsesPrefix_onTargetPrefix() targetprefix "sys" i = prepare() test.isequal("sysMyProject", i.name) end -- -- Bundle name should be set and use ".app" for Mac windowed applications. -- function suite.bundlenameUsesApp_onMacWindowedApp() kind "WindowedApp" system "MacOSX" i = prepare() test.isequal("MyProject.app", i.bundlename) end -- -- Bundle path should be set for Mac windowed applications. -- function suite.bundlepathSet_onMacWindowedApp() kind "WindowedApp" system "MacOSX" i = prepare() test.isequal("MyProject.app/Contents/MacOS", path.getrelative(os.getcwd(), i.bundlepath)) end -- -- Target extension is used if set. -- function suite.extensionSet_onTargetExtension() targetextension ".self" i = prepare() test.isequal("MyProject.self", i.name) end -- -- .NET executables should always default to ".exe" extensions. -- function suite.appUsesExe_onDotNet() _OS = "macosx" language "C#" i = prepare() test.isequal("MyProject.exe", i.name) end -- -- .NET libraries should always default to ".dll" extensions. -- function suite.appUsesExe_onDotNet() _OS = "macosx" language "C#" kind "SharedLib" i = prepare() test.isequal("MyProject.dll", i.name) end
bsd-3-clause
tommy3/Urho3D
bin/Data/LuaScripts/Utilities/Touch.lua
32
2209
-- Mobile framework for Android/iOS -- Gamepad from Ninja Snow War -- Touches patterns: -- - 1 finger touch = pick object through raycast -- - 1 or 2 fingers drag = rotate camera -- - 2 fingers sliding in opposite direction (up/down) = zoom in/out -- Setup: Call the update function 'UpdateTouches()' from HandleUpdate or equivalent update handler function local GYROSCOPE_THRESHOLD = 0.1 CAMERA_MIN_DIST = 1.0 CAMERA_MAX_DIST = 20.0 local zoom = false useGyroscope = false cameraDistance = 5.0 function UpdateTouches(controls) -- Called from HandleUpdate zoom = false -- reset bool -- Zoom in/out if input.numTouches == 2 then local touch1 = input:GetTouch(0) local touch2 = input:GetTouch(1) -- Check for zoom pattern (touches moving in opposite directions and on empty space) if not touch1.touchedElement and not touch2.touchedElement and ((touch1.delta.y > 0 and touch2.delta.y < 0) or (touch1.delta.y < 0 and touch2.delta.y > 0)) then zoom = true else zoom = false end -- Check for zoom direction (in/out) if zoom then if Abs(touch1.position.y - touch2.position.y) > Abs(touch1.lastPosition.y - touch2.lastPosition.y) then sens = -1 else sens = 1 end cameraDistance = cameraDistance + Abs(touch1.delta.y - touch2.delta.y) * sens * TOUCH_SENSITIVITY / 50 cameraDistance = Clamp(cameraDistance, CAMERA_MIN_DIST, CAMERA_MAX_DIST) -- Restrict zoom range to [1;20] end end -- Gyroscope (emulated by SDL through a virtual joystick) if useGyroscope and input.numJoysticks > 0 then -- numJoysticks = 1 on iOS & Android local joystick = input:GetJoystickByIndex(0) -- JoystickState if joystick.numAxes >= 2 then if joystick:GetAxisPosition(0) < -GYROSCOPE_THRESHOLD then controls:Set(CTRL_LEFT, true) end if joystick:GetAxisPosition(0) > GYROSCOPE_THRESHOLD then controls:Set(CTRL_RIGHT, true) end if joystick:GetAxisPosition(1) < -GYROSCOPE_THRESHOLD then controls:Set(CTRL_FORWARD, true) end if joystick:GetAxisPosition(1) > GYROSCOPE_THRESHOLD then controls:Set(CTRL_BACK, true) end end end end
mit
gedads/Neodynamis
scripts/zones/Selbina/npcs/Porter_Moogle.lua
3
1518
----------------------------------- -- Area: Selbina -- NPC: Porter Moogle -- Type: Storage Moogle -- @zone 248 -- !pos TODO ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/porter_moogle_util"); local e = { TALK_EVENT_ID = 1137, STORE_EVENT_ID = 1138, RETRIEVE_EVENT_ID = 1139, ALREADY_STORED_ID = 1140, MAGIAN_TRIAL_ID = 1141 }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) porterMoogleTrade(player, trade, e); end ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- No idea what the params are, other than event ID and gil. player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8); end ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED); end ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL); end
gpl-3.0
mishin/Algorithm-Implementations
Move_To_Front_Transform/Lua/Yonaba/mtf_test.lua
26
1524
-- Tests for mtf.lua local mtf = require 'mtf' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end -- Checks if t1 and t2 arrays are the same local function same(t1, t2) if #t1 ~= #t2 then return false end for r, row in ipairs(t1) do for v, value in ipairs(row) do if t2[r][v] ~= value then return false end end end return true end run('Encoding string tests', function() assert(mtf.encode('banana') == '98.98.110.2.2.2') assert(mtf.encode('1578rr') == '49.53.55.56.114.1') assert(mtf.encode('') == '') assert(mtf.encode(' ') == '32.1.1.1.1') assert(mtf.encode('mtf') == '109.116.104') assert(mtf.encode('M.T.F.') == '77.47.84.2.72.2') end) run('Decoding string tests', function() assert(mtf.decode(mtf.encode('banana')) == 'banana') assert(mtf.decode(mtf.encode('1578rr')) == '1578rr') assert(mtf.decode(mtf.encode(' ')) == ' ') assert(mtf.decode(mtf.encode('')) == '') assert(mtf.decode(mtf.encode('mtf')) == 'mtf') assert(mtf.decode(mtf.encode('M.T.F.')) == 'M.T.F.') end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
starlightknight/darkstar
scripts/globals/abilities/pets/attachments/mana_tank.lua
11
1151
----------------------------------- -- Attachment: Mana Tank ----------------------------------- require("scripts/globals/automaton") require("scripts/globals/status") ----------------------------------- function onEquip(pet) -- We do not have support to do a fraction of a percent so we rounded local frame = pet:getAutomatonFrame() if frame == dsp.frames.HARLEQUIN then pet:addMod(dsp.mod.MPP, 5) elseif frame == dsp.frames.STORMWAKER then pet:addMod(dsp.mod.MPP, 4) end end function onUnequip(pet) local frame = pet:getAutomatonFrame() if frame == dsp.frames.HARLEQUIN then pet:delMod(dsp.mod.MPP, 5) elseif frame == dsp.frames.STORMWAKER then pet:delMod(dsp.mod.MPP, 4) end end function onManeuverGain(pet, maneuvers) onUpdate(pet, maneuvers) end function onManeuverLose(pet, maneuvers) onUpdate(pet, maneuvers - 1) end function onUpdate(pet, maneuvers) local power = 0 if maneuvers > 0 then power = math.floor(maneuvers + (pet:getMaxMP() * (0.2 * maneuvers) / 100)) end updateModPerformance(pet, dsp.mod.REFRESH, 'mana_tank_mod', power) end
gpl-3.0
gedads/Neodynamis
scripts/globals/weaponskills/catastrophe.lua
19
2122
----------------------------------- -- Catastrophe -- Scythe weapon skill -- Skill Level: N/A -- Drain target's HP. Bec de Faucon/Apocalypse: Additional effect: Haste -- This weapon skill is available with the stage 5 relic Scythe Apocalypse or within Dynamis with the stage 4 Bec de Faucon. -- Also available without Aftermath effects with the Crisis Scythe. After 13 weapon skills have been used successfully, gives one "charge" of Catastrophe. -- Aligned with the Shadow Gorget & Soil Gorget. -- Aligned with the Shadow Belt & Soil Belt. -- Element: None -- Modifiers: INT:40% ; AGI:40% -- 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.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.4; params.int_wsc = 0.4; 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.4; params.agi_wsc = 0.0; params.int_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); -- TODO: Whoever codes those level 85 weapons with the latent that grants this WS needs to code a check to not give the aftermath effect. if (damage > 0) then local amDuration = 20 * math.floor(tp/1000); player:addStatusEffect(EFFECT_AFTERMATH, 100, 0, amDuration, 0, 6); end if (target:isUndead() == false) then local drain = (damage * 0.4); player:addHP(drain); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
gedads/Neodynamis
scripts/zones/Sauromugue_Champaign/mobs/Tabar_Beak.lua
3
1037
----------------------------------- -- Area: Sauromugue Champaign -- MOB: Tabar Beak ----------------------------------- require("scripts/globals/fieldsofvalor"); require("scripts/zones/Sauromugue_Champaign/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) checkRegime(player,mob,100,1); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); if (Deadly_Dodo_PH[mobID] ~= nil) then local ToD = GetServerVariable("[POP]Deadly_Dodo"); if (ToD <= os.time() and GetMobAction(Deadly_Dodo) == 0) then if (math.random(1,3) == 2) then UpdateNMSpawnPoint(Deadly_Dodo); GetMobByID(Deadly_Dodo):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Deadly_Dodo", mobID); DisallowRespawn(mobID, true); end end end end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Buburimu_Peninsula/npcs/Stone_Monument.lua
3
1303
----------------------------------- -- Area: Buburimu Peninsula -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- !pos 320.755 -4.000 368.722 118 ----------------------------------- package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Buburimu_Peninsula/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x02000); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
telergybot/zspam
plugins/quotes.lua
651
1630
local quotes_file = './data/quotes.lua' local quotes_table function read_quotes_file() local f = io.open(quotes_file, "r+") if f == nil then print ('Created a new quotes file on '..quotes_file) serialize_to_file({}, quotes_file) else print ('Quotes loaded: '..quotes_file) f:close() end return loadfile (quotes_file)() end function save_quote(msg) local to_id = tostring(msg.to.id) if msg.text:sub(11):isempty() then return "Usage: !addquote quote" end if quotes_table == nil then quotes_table = {} end if quotes_table[to_id] == nil then print ('New quote key to_id: '..to_id) quotes_table[to_id] = {} end local quotes = quotes_table[to_id] quotes[#quotes+1] = msg.text:sub(11) serialize_to_file(quotes_table, quotes_file) return "done!" end function get_quote(msg) local to_id = tostring(msg.to.id) local quotes_phrases quotes_table = read_quotes_file() quotes_phrases = quotes_table[to_id] return quotes_phrases[math.random(1,#quotes_phrases)] end function run(msg, matches) if string.match(msg.text, "!quote$") then return get_quote(msg) elseif string.match(msg.text, "!addquote (.+)$") then quotes_table = read_quotes_file() return save_quote(msg) end end return { description = "Save quote", description = "Quote plugin, you can create and retrieve random quotes", usage = { "!addquote [msg]", "!quote", }, patterns = { "^!addquote (.+)$", "^!quote$", }, run = run }
gpl-2.0
pedro-andrade-inpe/terrame
test/packages/load-wrong/tests/Tube.lua
30
1562
------------------------------------------------------------------------------------------- -- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling. -- Copyright (C) 2001-2014 INPE and TerraLAB/UFOP. -- -- This code is part of the TerraME framework. -- This framework is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library. -- -- The authors reassure the license terms regarding the warranties. -- They specifically disclaim any warranties, including, but not limited to, -- the implied warranties of merchantability and fitness for a particular purpose. -- The framework provided hereunder is on an "as is" basis, and the authors have no -- obligation to provide maintenance, support, updates, enhancements, or modifications. -- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct, -- indirect, special, incidental, or consequential damages arising out of the use -- of this library and its documentation. -- -- Authors: Tiago Garcia de Senna Carneiro (tiago@dpi.inpe.br) -- Pedro R. Andrade (pedro.andrade@inpe.br) ------------------------------------------------------------------------------------------- return{ Tube = function(unitTest) local t = Tube{} unitTest:assert(true) end }
lgpl-3.0
gedads/Neodynamis
scripts/globals/mobskills/chemical_bomb.lua
5
1128
--------------------------------------------- -- Chemical_Bomb -- -- Description: slow + elegy --------------------------------------------- require("scripts/globals/monstertpmoves"); require("scripts/globals/settings"); require("scripts/globals/status"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) -- skillList 54 = Omega -- skillList 727 = Proto-Omega -- skillList 728 = Ultima -- skillList 729 = Proto-Ultima local skillList = mob:getMobMod(MOBMOD_SKILL_LIST); local mobhp = mob:getHPP(); local phase = mob:getLocalVar("battlePhase"); if ((skillList == 729 and phase < 3) or ((skillList == 728 and mobhp >= 70 or mobhp < 40))) then return 0; end return 1; end; function onMobWeaponSkill(target, mob, skill) local typeEffectOne = EFFECT_ELEGY; local typeEffectTwo = EFFECT_SLOW; skill:setMsg(MobStatusEffectMove(mob, target, typeEffectOne, 512, 0, 120)); skill:setMsg(MobStatusEffectMove(mob, target, typeEffectTwo, 512, 0, 120)); -- This likely doesn't behave like retail. return typeEffectTwo; end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Port_Bastok/npcs/HomePoint#3.lua
3
1252
----------------------------------- -- Area: Port_Bastok -- NPC: HomePoint#3 -- !pos -126 -6 10 236 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Port_Bastok/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fe, 101); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fe) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Beadeaux/npcs/Haggleblix.lua
3
7234
----------------------------------- -- Area: Beadeaux -- NPC: Haggleblix -- Type: Dynamis NPC -- !pos -255.847 0.595 106.485 147 ----------------------------------- package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/dynamis"); require("scripts/zones/Beadeaux/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local count = trade:getItemCount(); local buying = false; local exchange; local gil = trade:getGil(); if (player:hasKeyItem(VIAL_OF_SHROUDED_SAND)) then if (count == 1 and gil == TIMELESS_HOURGLASS_COST) then -- Hourglass purchase player:startEvent(134); elseif (gil == 0) then if (count == 1 and trade:hasItemQty(4236,1)) then -- Bringing back a Timeless Hourglass player:startEvent(153); -- Currency Exchanges elseif (count == CURRENCY_EXCHANGE_RATE and trade:hasItemQty(1455,CURRENCY_EXCHANGE_RATE)) then -- Single -> Hundred player:startEvent(135,CURRENCY_EXCHANGE_RATE); elseif (count == CURRENCY_EXCHANGE_RATE and trade:hasItemQty(1456,CURRENCY_EXCHANGE_RATE)) then -- Hundred -> Ten thousand player:startEvent(136,CURRENCY_EXCHANGE_RATE); elseif (count == 1 and trade:hasItemQty(1457,1)) then -- Ten thousand -> 100 Hundreds player:startEvent(138,1457,1456,CURRENCY_EXCHANGE_RATE); -- Currency Shop elseif (count == 12 and trade:hasItemQty(1456,12)) then -- Cantarella (4246) buying = true; exchange = {12, 4246}; elseif (count == 33 and trade:hasItemQty(1456,33)) then -- Koh-I-Noor (1460) buying = true; exchange = {33,1460}; elseif (count == 20 and trade:hasItemQty(1456,20)) then -- Marksman's Oil (1468) buying = true; exchange = {20, 1468}; elseif (count == 7 and trade:hasItemQty(1456,7)) then -- Siren's Hair (1313) buying = true; exchange = {7, 1313}; elseif (count == 8 and trade:hasItemQty(1456,8)) then -- Slime Juice (1521) buying = true; exchange = {8,1521}; elseif (count == 25 and trade:hasItemQty(1456,25)) then -- Wootz Ingot (1461) buying = true; exchange = {25, 1461}; elseif (count == 9 and trade:hasItemQty(1456,9)) then -- Wootz Ore (1469) buying = true; exchange = {9, 1469}; end end end -- Handle the shop trades. -- Item obtained dialog appears before CS. Could be fixed with a non-local variable and onEventFinish, but meh. if (buying == true) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,exchange[2]); else player:startEvent(137,1456,exchange[1],exchange[2]); player:tradeComplete(); player:addItem(exchange[2]); player:messageSpecial(ITEM_OBTAINED,exchange[2]); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(VIAL_OF_SHROUDED_SAND) == true) then player:startEvent(133, 1455, CURRENCY_EXCHANGE_RATE, 1456, CURRENCY_EXCHANGE_RATE, 1457, TIMELESS_HOURGLASS_COST, 4236, TIMELESS_HOURGLASS_COST); else player:startEvent(130); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 133) then if (option == 11) then -- Main menu, and many others. Param1 = map bitmask, param2 = player's gil player:updateEvent(getDynamisMapList(player), player:getGil()); elseif (option == 10) then -- Final line of the ancient currency explanation. "I'll trade you param3 param2s for a param1." player:updateEvent(1457, 1456, CURRENCY_EXCHANGE_RATE); -- Map sales handling. elseif (option >= MAP_OF_DYNAMIS_SANDORIA and option <= MAP_OF_DYNAMIS_TAVNAZIA) then -- The returned option is actually the keyitem ID, making this much easier. -- The prices are set in the menu's dialog, so they cannot be (visibly) changed. if (option == MAP_OF_DYNAMIS_BEAUCEDINE) then -- 15k gil player:delGil(15000); elseif (option == MAP_OF_DYNAMIS_XARCABARD or option == MAP_OF_DYNAMIS_TAVNAZIA) then -- 20k gil player:delGil(20000); else -- All others 10k player:delGil(10000); end player:addKeyItem(option); player:updateEvent(getDynamisMapList(player),player:getGil()); -- Ancient Currency shop menu elseif (option == 2) then -- Hundreds sales menu Page 1 (price1 item1 price2 item2 price3 item3 price4 item4) player:updateEvent(12,4246,33,1460,20,1468,7,1313); elseif (option == 3) then -- Hundreds sales menu Page 2 (price1 item1 price2 item2 price3 item3) player:updateEvent(8,1521,25,1461,9,1469); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 134) then -- Buying an Hourglass if (player:getFreeSlotsCount() == 0 or player:hasItem(4236) == true) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4236); else player:tradeComplete(); player:addItem(4236); player:messageSpecial(ITEM_OBTAINED,4236); end elseif (csid == 153) then -- Bringing back an hourglass for gil. player:tradeComplete(); player:addGil(TIMELESS_HOURGLASS_COST); player:messageSpecial(GIL_OBTAINED,TIMELESS_HOURGLASS_COST); elseif (csid == 135) then -- Trading Singles for a Hundred if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1456); else player:tradeComplete(); player:addItem(1456); player:messageSpecial(ITEM_OBTAINED,1456); end elseif (csid == 136) then -- Trading 100 Hundreds for Ten thousand if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1457); else player:tradeComplete(); player:addItem(1457); player:messageSpecial(ITEM_OBTAINED,1457); end elseif (csid == 138) then -- Trading Ten thousand for 100 Hundreds if (player:getFreeSlotsCount() <= 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1456); else player:tradeComplete(); player:addItem(1456,CURRENCY_EXCHANGE_RATE); if (CURRENCY_EXCHANGE_RATE >= 100) then -- Turns out addItem cannot add > stackSize, so we need to addItem twice for quantities > 99. player:addItem(1456,CURRENCY_EXCHANGE_RATE - 99); end player:messageSpecial(ITEMS_OBTAINED,1456,CURRENCY_EXCHANGE_RATE); end end end;
gpl-3.0
canhnt/ingress
rootfs/etc/nginx/lua/util/split.lua
2
1955
local ipairs = ipairs local _M = {} -- splits strings into host and port local function parse_addr(addr) local _, _, host, port = addr:find("([^:]+):([^:]+)") if host and port then return {host=host, port=port} else return nil, "error in parsing upstream address!" end end function _M.get_first_value(var) local t = _M.split_upstream_var(var) or {} if #t == 0 then return nil end return t[1] end function _M.get_last_value(var) local t = _M.split_upstream_var(var) or {} if #t == 0 then return nil end return t[#t] end -- http://nginx.org/en/docs/http/ngx_http_upstream_module.html#example -- CAVEAT: nginx is giving out : instead of , so the docs are wrong -- 127.0.0.1:26157 : 127.0.0.1:26157 , ngx.var.upstream_addr -- 200 : 200 , ngx.var.upstream_status -- 0.00 : 0.00, ngx.var.upstream_response_time function _M.split_upstream_var(var) if not var then return nil, nil end local t = {} for v in var:gmatch("[^%s|,]+") do if v ~= ":" then t[#t+1] = v end end return t end -- Splits an NGINX $upstream_addr and returns an array of tables -- with a `host` and `port` key-value pair. function _M.split_upstream_addr(addrs_str) if not addrs_str then return nil, nil end local addrs = _M.split_upstream_var(addrs_str) local host_and_ports = {} for _, v in ipairs(addrs) do local a, err = parse_addr(v) if err then return nil, err end host_and_ports[#host_and_ports+1] = a end if #host_and_ports == 0 then return nil, "no upstream addresses to parse!" end return host_and_ports end -- Splits string by delimiter. Returns array of parsed values and the length of the array. function _M.split_string(what, delim) local result = {} local idx = 0 if what and delim and delim ~= "" then for chunk in what:gmatch("([^" .. delim .. "]+)") do idx = idx + 1 result[idx] = chunk end end return result, idx end return _M
apache-2.0
starlightknight/darkstar
scripts/globals/items/bowl_of_sopa_de_pez_blanco.lua
11
1259
----------------------------------------- -- ID: 4601 -- Item: Bowl of Sopa de Pez Blanco -- Food Effect: 180Min, All Races ----------------------------------------- -- Health 12 -- Dexterity 6 -- Mind -4 -- Accuracy 3 -- Ranged ACC % 7 -- Ranged ACC Cap 10 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,10800,4601) end function onEffectGain(target, effect) target:addMod(dsp.mod.HP, 12) target:addMod(dsp.mod.DEX, 6) target:addMod(dsp.mod.MND, -4) target:addMod(dsp.mod.ACC, 3) target:addMod(dsp.mod.FOOD_RACCP, 7) target:addMod(dsp.mod.FOOD_RACC_CAP, 10) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 12) target:delMod(dsp.mod.DEX, 6) target:delMod(dsp.mod.MND, -4) target:delMod(dsp.mod.ACC, 3) target:delMod(dsp.mod.FOOD_RACCP, 7) target:delMod(dsp.mod.FOOD_RACC_CAP, 10) end
gpl-3.0
gedads/Neodynamis
scripts/zones/Metalworks/npcs/Glarociquet_TK.lua
3
2890
----------------------------------- -- Area: Metalworks -- NPC: Glarociquet, T.K. -- !pos 19 -16 -28 237 -- X Grant Signet -- X Recharge Emperor Band, Empress Band, or Chariot Band -- X Accepts traded Crystals to fill up the Rank bar to open new Missions. -- X Sells items in exchange for Conquest Points -- X Start Supply Run Missions and offers a list of already-delivered supplies. -- Start an Expeditionary Force by giving an E.F. region insignia to you. ------------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/globals/common"); require("scripts/zones/Metalworks/TextIDs"); local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, JEUNO local guardtype = 2; -- 1: city, 2: foreign, 3: outpost, 4: border local size = #SandInv; local inventory = SandInv; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies." local region = player:getVar("supplyQuest_region"); player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region)); player:setVar("supplyQuest_started",0); player:setVar("supplyQuest_region",0); player:setVar("supplyQuest_fresh",0); else local Menu1 = getArg1(guardnation,player); local Menu2 = getExForceAvailable(guardnation,player); local Menu3 = conquestRanking(); local Menu4 = getSupplyAvailable(guardnation,player); local Menu5 = player:getNationTeleport(guardnation); local Menu6 = getArg6(player); local Menu7 = player:getCP(); local Menu8 = getRewardExForce(guardnation,player); player:startEvent(0x7ffb,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); updateConquestGuard(player,csid,option,size,inventory); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %u",option); finishConquestGuard(player,csid,option,size,inventory,guardnation); end;
gpl-3.0
Amorph/premake-stable
tests/actions/make/test_make_pch.lua
1
1860
-- -- tests/actions/make/test_make_pch.lua -- Validate the setup for precompiled headers in makefiles. -- Copyright (c) 2010 Jason Perkins and the Premake project -- T.make_pch = { } local suite = T.make_pch local _ = premake.make.cpp -- -- Setup and teardown -- local sln, prj, cfg function suite.setup() sln, prj = test.createsolution() end local function prepare() premake.bake.buildconfigs() cfg = premake.getconfig(prj, "Debug") end -- -- Configuration block tests -- function suite.NoConfig_OnNoHeaderSet() prepare() _.pchconfig(cfg) test.capture [[]] end function suite.NoConfig_OnHeaderAndNoPCHFlag() pchheader "include/myproject.h" flags { NoPCH } prepare() _.pchconfig(cfg) test.capture [[]] end function suite.ConfigBlock_OnPchEnabled() pchheader "include/myproject.h" prepare() _.pchconfig(cfg) test.capture [[ PCH = include/myproject.h GCH = $(OBJDIR)/myproject.h.gch ALL_CPPFLAGS += -I$(OBJDIR) -include $(OBJDIR)/myproject.h ]] end -- -- Build rule tests -- function suite.BuildRules_OnCpp() pchheader "include/myproject.h" prepare() _.pchrules(prj) test.capture [[ ifneq (,$(PCH)) $(GCH): $(PCH) @echo $(notdir $<) ifeq (posix,$(SHELLTYPE)) -$(SILENT) cp $< $(OBJDIR) else $(SILENT) xcopy /D /Y /Q "$(subst /,\,$<)" "$(subst /,\,$(OBJDIR))" 1>nul endif $(SILENT) $(CXX) $(ALL_CXXFLAGS) -o "$@" -MF $(@:%.gch=%.d) -c "$<" endif ]] end function suite.BuildRules_OnC() language "C" pchheader "include/myproject.h" prepare() _.pchrules(prj) test.capture [[ ifneq (,$(PCH)) $(GCH): $(PCH) @echo $(notdir $<) ifeq (posix,$(SHELLTYPE)) -$(SILENT) cp $< $(OBJDIR) else $(SILENT) xcopy /D /Y /Q "$(subst /,\,$<)" "$(subst /,\,$(OBJDIR))" 1>nul endif $(SILENT) $(CC) $(ALL_CFLAGS) -o "$@" -MF $(@:%.gch=%.d) -c "$<" endif ]] end
bsd-3-clause
dimitarcl/premake-dev
tests/base/test_override.lua
18
1484
-- -- tests/base/test_override.lua -- Verify function override support. -- Copyright (c) 2012 Jason Perkins and the Premake project -- T.premake_override = {} local suite = T.premake_override -- -- Setup -- local X = {} function suite.setup() X.testfunc = function(value) return value or "testfunc" end end -- -- Should be able to completely replace the function with one of my own. -- function suite.canOverride() premake.override(X, "testfunc", function() return "canOverride" end) test.isequal("canOverride", X.testfunc()) end -- -- Should be able to reference the original implementation. -- function suite.canCallOriginal() premake.override(X, "testfunc", function(base) return "canOverride > " .. base() end) test.isequal("canOverride > testfunc", X.testfunc()) end -- -- Arguments should pass through. -- function suite.canPassThroughArguments() premake.override(X, "testfunc", function(base, value) return value .. " > " .. base() end) test.isequal("testval > testfunc", X.testfunc("testval")) end -- -- Can override the same function multiple times. -- function suite.canOverrideMultipleTimes() premake.override(X, "testfunc", function(base, value) return string.format("[%s > %s]", value, base("base1")) end) premake.override(X, "testfunc", function(base, value) return string.format("{%s > %s}", value, base("base2")) end) test.isequal("{base3 > [base2 > base1]}", X.testfunc("base3")) end
bsd-3-clause
gedads/Neodynamis
scripts/zones/Silver_Sea_route_to_Nashmau/Zone.lua
17
1405
----------------------------------- -- -- Zone: Silver_Sea_route_to_Nashmau -- ----------------------------------- package.loaded["scripts/zones/Silver_Sea_route_to_Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Silver_Sea_route_to_Nashmau/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; return cs; end; ----------------------------------- -- onTransportEvent ----------------------------------- function onTransportEvent(player,transport) player:startEvent(0x0401); end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0401) then player:setPos(0,0,0,0,53); end end;
gpl-3.0
starlightknight/darkstar
scripts/zones/Horlais_Peak/bcnms/shooting_fish.lua
9
1062
----------------------------------- -- Shooting Fish -- Horlais Peak BCNM20, Cloudy Orb -- !additem 1551 ----------------------------------- require("scripts/globals/battlefield") ----------------------------------- function onBattlefieldInitialise(battlefield) battlefield:setLocalVar("loot", 1) end function onBattlefieldTick(battlefield, tick) dsp.battlefield.onBattlefieldTick(battlefield, tick) end function onBattlefieldRegister(player, battlefield) end function onBattlefieldEnter(player, battlefield) end function onBattlefieldLeave(player, battlefield, leavecode) if leavecode == dsp.battlefield.leaveCode.WON then local name, clearTime, partySize = battlefield:getRecord() player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 0) elseif leavecode == dsp.battlefield.leaveCode.LOST then player:startEvent(32002) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
gpl-3.0
Achain-Dev/Achain
src/Chain/libraries/glua/tests_lua/test_too_many_localvars.lua
1
1408
local M = {} function M:init() end function M:start() local a0 local a1 local a2 local a3 local a4 local a5 local a6 local a7 local a8 local a9 local a10 local a11 local a12 local a13 local a14 local a15 local a16 local a17 local a18 local a19 local a20 local a21 local a22 local a23 local a24 local a25 local a26 local a27 local a28 local a29 local a30 local a31 local a32 local a33 local a34 local a35 local a36 local a37 local a38 local a39 local a40 local a41 local a42 local a43 local a44 local a45 local a46 local a47 local a48 local a49 local a50 local a51 local a52 local a53 local a54 local a55 local a56 local a57 local a58 local a59 local a60 local a61 local a62 local a63 local a64 local a65 local a66 local a67 local a68 local a69 local a70 local a71 local a72 local a73 local a74 local a75 local a76 local a77 local a78 local a79 local a80 local a81 local a82 local a83 local a84 local a85 local a86 local a87 local a88 local a89 local a90 local a91 local a92 local a93 local a94 local a95 local a96 local a97 local a98 local a99 local a100 local a101 local a102 local a103 local a104 local a105 local a106 local a107 local a108 local a109 local a110 local a111 local a112 local a113 local a114 local a115 local a116 local a117 local a118 local a119 local a120 local a121 local a122 local a123 local a124 local a125 local a126 local a127 --local a128 --local a129 --local a130 end return M
mit
gedads/Neodynamis
scripts/zones/LaLoff_Amphitheater/bcnms/ark_angels_4.lua
2
3588
----------------------------------- -- Area: LaLoff Amphitheater -- Name: Ark Angels 4 (Elvaan) ----------------------------------- package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil; ----------------------------------- require("scripts/zones/LaLoff_Amphitheater/TextIDs"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); ----------------------------------- -- Death cutscenes: -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); -- Hume -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); -- taru -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,2,0); -- mithra -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); -- elvan -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0); -- galka -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,5,0); -- divine might -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,6,0); -- skip ending cs -- 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 local record = instance:getRecord(); local clearTime = record.clearTime; if (player:hasCompletedMission(ZILART,ARK_ANGELS)) then player:startEvent(0x7d01,instance:getEntrance(),clearTime,1,instance:getTimeInside(),180,3,1); -- winning CS (allow player to skip) else player:startEvent(0x7d01,instance:getEntrance(),clearTime,1,instance:getTimeInside(),180,3,0); -- winning CS (allow player to skip) end elseif (leavecode == 4) then player:startEvent(0x7d02, 0, 0, 0, 0, 0, instance:getEntrance(), 180); -- player lost 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 AAKeyitems = (player:hasKeyItem(SHARD_OF_APATHY) and player:hasKeyItem(SHARD_OF_COWARDICE) and player:hasKeyItem(SHARD_OF_ENVY) and player:hasKeyItem(SHARD_OF_RAGE)); if (csid == 0x7d01) then if (player:getCurrentMission(ZILART) == ARK_ANGELS and player:getVar("ZilartStatus") == 1) then player:addKeyItem(SHARD_OF_ARROGANCE); player:messageSpecial(KEYITEM_OBTAINED,SHARD_OF_ARROGANCE); if (AAKeyitems == true) then player:completeMission(ZILART,ARK_ANGELS); player:addMission(ZILART,THE_SEALED_SHRINE); player:setVar("ZilartStatus",0); end end end local AAKeyitems = (player:hasKeyItem(SHARD_OF_APATHY) and player:hasKeyItem(SHARD_OF_ARROGANCE) and player:hasKeyItem(SHARD_OF_COWARDICE) and player:hasKeyItem(SHARD_OF_ENVY) and player:hasKeyItem(SHARD_OF_RAGE)); if (AAKeyitems == true) then player:completeMission(ZILART,ARK_ANGELS); player:addMission(ZILART,THE_SEALED_SHRINE); player:setVar("ZilartStatus",0); end end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Temenos/mobs/Goblin_Fencer.lua
28
1132
----------------------------------- -- Area: Temenos N T -- NPC: Goblin_Fencer ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) GetMobByID(16928831):updateEnmity(target); GetMobByID(16928833):updateEnmity(target); GetMobByID(16928835):updateEnmity(target); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) if (IsMobDead(16928831)==true and IsMobDead(16928832)==true and IsMobDead(16928833)==true and IsMobDead(16928834)==true and IsMobDead(16928835)==true ) then GetNPCByID(16928768+39):setPos(-599,85,438); GetNPCByID(16928768+39):setStatus(STATUS_NORMAL); GetNPCByID(16928768+456):setStatus(STATUS_NORMAL); end end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Grand_Palace_of_HuXzoi/npcs/_iyc.lua
3
1036
----------------------------------- -- Area: Grand Palace of Hu'Xzoi -- NPC: Particle Gate -- !pos -39 0 -319 34 ----------------------------------- package.loaded["scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00ac); return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
dimitarcl/premake-dev
tests/actions/vstudio/vc200x/test_compiler_block.lua
1
12572
-- -- tests/actions/vstudio/vc200x/test_compiler_block.lua -- Validate generation the VCCLCompiler element in Visual Studio 200x C/C++ projects. -- Copyright (c) 2011-2013 Jason Perkins and the Premake project -- local suite = test.declare("vs200x_compiler_block") local vc200x = premake.vstudio.vc200x -- -- Setup/teardown -- local sln, prj function suite.setup() _ACTION = "vs2008" sln, prj = test.createsolution() end local function prepare() local cfg = test.getconfig(prj, "Debug") vc200x.VCCLCompilerTool(cfg) end -- -- Verify the basic structure of the compiler block with no flags or settings. -- function suite.looksGood_onDefaultSettings() prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- If include directories are specified, the <AdditionalIncludeDirectories> should be added. -- function suite.additionalIncludeDirs_onIncludeDirs() includedirs { "include/lua", "include/zlib" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="include\lua;include\zlib" ]] end -- -- Verify the handling of the Symbols flag. The format must be set, and the -- debug runtime library must be selected. -- function suite.looksGood_onSymbolsFlag() flags "Symbols" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="3" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="4" /> ]] end -- -- Verify the handling of the Symbols in conjunction with the Optimize flag. -- The release runtime library must be used. -- function suite.looksGood_onSymbolsAndOptimizeFlags() flags { "Symbols" } optimize "On" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="3" StringPooling="true" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="3" /> ]] end -- -- Verify the handling of the C7 debug information format. -- function suite.looksGood_onC7DebugFormat() flags "Symbols" debugformat "C7" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="3" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="1" /> ]] end --- -- Test precompiled header handling; the header should be treated as -- a plain string value, with no path manipulation applied, since it -- needs to match the value of the #include statement used in the -- project code. --- function suite.compilerBlock_OnPCH() location "build" pchheader "include/common.h" pchsource "source/common.cpp" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="2" PrecompiledHeaderThrough="include/common.h" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Floating point flag tests -- function suite.compilerBlock_OnFpFast() floatingpoint "Fast" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" FloatingPointModel="2" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end function suite.compilerBlock_OnFpStrict() floatingpoint "Strict" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" FloatingPointModel="1" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Check that the "minimal rebuild" flag is applied correctly. -- function suite.minimalRebuildFlagsSet_onMinimalRebuildAndSymbols() flags { "Symbols", "NoMinimalRebuild" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="3" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="4" /> ]] end -- -- Check that the "no buffer security check" flag is applied correctly. -- function suite.noBufferSecurityFlagSet_onBufferSecurityCheck() flags { "NoBufferSecurityCheck" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" BufferSecurityCheck="false" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Check that the CompileAs value is set correctly for C language projects. -- function suite.compileAsSet_onC() language "C" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" CompileAs="1" /> ]] end -- -- Verify the correct runtime library is used when symbols are enabled. -- function suite.runtimeLibraryIsDebug_onSymbolsNoOptimize() flags { "Symbols" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="3" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="4" /> ]] end -- -- Verify the correct warnings settings are used when extra warnings are enabled. -- function suite.runtimeLibraryIsDebug_onExtraWarnings() warnings "Extra" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="4" DebugInformationFormat="0" /> ]] end -- -- Verify the correct warnings settings are used when FatalWarnings are enabled. -- function suite.runtimeLibraryIsDebug_onFatalWarnings() flags { "FatalWarnings" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" WarnAsError="true" DebugInformationFormat="0" /> ]] end -- -- Verify the correct warnings settings are used when no warnings are enabled. -- function suite.runtimeLibraryIsDebug_onNoWarnings_whichDisablesAllOtherWarningsFlags() flags { "FatalWarnings" } warnings "Off" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="0" DebugInformationFormat="0" /> ]] end -- -- Verify the correct Detect64BitPortabilityProblems settings are used when _ACTION < "VS2008". -- function suite.runtimeLibraryIsDebug_onVS2005() _ACTION = "vs2005" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" Detect64BitPortabilityProblems="true" DebugInformationFormat="0" /> ]] end -- -- Verify the correct warnings settings are used when no warnings are enabled. -- function suite.runtimeLibraryIsDebug_onVS2005_NoWarnings() _ACTION = "vs2005" warnings "Off" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="0" DebugInformationFormat="0" /> ]] end -- -- Xbox 360 uses the same structure, but changes the element name. -- function suite.looksGood_onXbox360() system "Xbox360" prepare() test.capture [[ <Tool Name="VCCLX360CompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Check handling of forced includes. -- function suite.forcedIncludeFiles() forceincludes { "stdafx.h", "include/sys.h" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" ForcedIncludeFiles="stdafx.h;include\sys.h" ]] end function suite.forcedUsingFiles() forceusings { "stdafx.h", "include/sys.h" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" ForcedUsingFiles="stdafx.h;include\sys.h" ]] end -- -- Verify handling of the NoRuntimeChecks flag. -- function suite.onNoRuntimeChecks() flags { "NoRuntimeChecks" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" RuntimeLibrary="2" ]] end -- -- Check handling of the EnableMultiProcessorCompile flag. -- function suite.onMultiProcessorCompile() flags { "MultiProcessorCompile" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" AdditionalOptions="/MP" Optimization="0" BasicRuntimeChecks="3" ]] end -- -- Check handling of the ReleaseRuntime flag; should override the -- default behavior of linking the debug runtime when symbols are -- enabled with no optimizations. -- function suite.releaseRuntime_onFlag() flags { "Symbols", "ReleaseRuntime" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="2" ]] end function suite.releaseRuntime_onStaticAndReleaseRuntime() flags { "Symbols", "ReleaseRuntime", "StaticRuntime" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="0" ]] end -- -- Check the LinkTimeOptimization flag. -- function suite.flags_onLinkTimeOptimization() flags { "LinkTimeOptimization" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" WholeProgramOptimization="true" ]] end -- -- Check the optimization flags. -- function suite.optimization_onOptimize() optimize "On" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="3" StringPooling="true" ]] end function suite.optimization_onOptimizeSize() optimize "Size" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="1" StringPooling="true" ]] end function suite.optimization_onOptimizeSpeed() optimize "Speed" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="2" StringPooling="true" ]] end function suite.optimization_onOptimizeFull() optimize "Full" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="3" StringPooling="true" ]] end function suite.optimization_onOptimizeOff() optimize "Off" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" ]] end function suite.optimization_onOptimizeDebug() optimize "Debug" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" ]] end -- -- Check handling of the OmitDefaultLibrary flag. -- function suite.onOmitDefaultLibrary() flags { "OmitDefaultLibrary" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" OmitDefaultLibName="true" ]] end
bsd-3-clause
gedads/Neodynamis
scripts/zones/Port_San_dOria/npcs/HomePoint#1.lua
3
1272
----------------------------------- -- Area: Port San dOria -- NPC: HomePoint#1 -- !pos -67.963 -4.000 -105.023 232 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 6); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
starlightknight/darkstar
scripts/globals/items/serving_of_mille-feuille.lua
11
1191
----------------------------------------- -- ID: 5559 -- Item: Serving of Mille Feuille -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +8 -- MP +15 -- Intelligence +1 -- HP Recoverd while healing 1 -- MP Recovered while healing 1 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,10800,5559) end function onEffectGain(target, effect) target:addMod(dsp.mod.HP, 8) target:addMod(dsp.mod.MP, 15) target:addMod(dsp.mod.INT, 1) target:addMod(dsp.mod.HPHEAL, 1) target:addMod(dsp.mod.MPHEAL, 1) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 8) target:delMod(dsp.mod.MP, 15) target:delMod(dsp.mod.INT, 1) target:delMod(dsp.mod.HPHEAL, 1) target:delMod(dsp.mod.MPHEAL, 1) end
gpl-3.0