repo_name
stringlengths
6
78
path
stringlengths
4
206
copies
stringclasses
281 values
size
stringlengths
4
7
content
stringlengths
625
1.05M
license
stringclasses
15 values
omidtarh/wezardbot
plugins/media.lua
376
1679
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
swiftgeek/packages
net/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan/rule.lua
80
4829
-- ------ extra functions ------ -- function ruleCheck() -- determine if rules needs a proper protocol configured uci.cursor():foreach("mwan3", "rule", function (section) local sourcePort = ut.trim(sys.exec("uci -p /var/state get mwan3." .. section[".name"] .. ".src_port")) local destPort = ut.trim(sys.exec("uci -p /var/state get mwan3." .. section[".name"] .. ".dest_port")) if sourcePort ~= "" or destPort ~= "" then -- ports configured local protocol = ut.trim(sys.exec("uci -p /var/state get mwan3." .. section[".name"] .. ".proto")) if protocol == "" or protocol == "all" then -- no or improper protocol error_protocol_list = error_protocol_list .. section[".name"] .. " " end end end ) end function ruleWarn() -- display warning messages at the top of the page if error_protocol_list ~= " " then return "<font color=\"ff0000\"><strong>WARNING: some rules have a port configured with no or improper protocol specified! Please configure a specific protocol!</strong></font>" else return "" end end -- ------ rule configuration ------ -- dsp = require "luci.dispatcher" sys = require "luci.sys" ut = require "luci.util" error_protocol_list = " " ruleCheck() m5 = Map("mwan3", translate("MWAN Rule Configuration"), translate(ruleWarn())) m5:append(Template("mwan/config_css")) mwan_rule = m5:section(TypedSection, "rule", translate("Traffic Rules"), translate("Rules specify which traffic will use a particular MWAN policy based on IP address, port or protocol<br />" .. "Rules are matched from top to bottom. Rules below a matching rule are ignored. Traffic not matching any rule is routed using the main routing table<br />" .. "Traffic destined for known (other than default) networks is handled by the main routing table. Traffic matching a rule, but all WAN interfaces for that policy are down will be blackholed<br />" .. "Names may contain characters A-Z, a-z, 0-9, _ and no spaces<br />" .. "Rules may not share the same name as configured interfaces, members or policies")) mwan_rule.addremove = true mwan_rule.anonymous = false mwan_rule.dynamic = false mwan_rule.sectionhead = "Rule" mwan_rule.sortable = true mwan_rule.template = "cbi/tblsection" mwan_rule.extedit = dsp.build_url("admin", "network", "mwan", "configuration", "rule", "%s") function mwan_rule.create(self, section) TypedSection.create(self, section) m5.uci:save("mwan3") luci.http.redirect(dsp.build_url("admin", "network", "mwan", "configuration", "rule", section)) end src_ip = mwan_rule:option(DummyValue, "src_ip", translate("Source address")) src_ip.rawhtml = true function src_ip.cfgvalue(self, s) return self.map:get(s, "src_ip") or "&#8212;" end src_port = mwan_rule:option(DummyValue, "src_port", translate("Source port")) src_port.rawhtml = true function src_port.cfgvalue(self, s) return self.map:get(s, "src_port") or "&#8212;" end dest_ip = mwan_rule:option(DummyValue, "dest_ip", translate("Destination address")) dest_ip.rawhtml = true function dest_ip.cfgvalue(self, s) return self.map:get(s, "dest_ip") or "&#8212;" end dest_port = mwan_rule:option(DummyValue, "dest_port", translate("Destination port")) dest_port.rawhtml = true function dest_port.cfgvalue(self, s) return self.map:get(s, "dest_port") or "&#8212;" end proto = mwan_rule:option(DummyValue, "proto", translate("Protocol")) proto.rawhtml = true function proto.cfgvalue(self, s) return self.map:get(s, "proto") or "all" end sticky = mwan_rule:option(DummyValue, "sticky", translate("Sticky")) sticky.rawhtml = true function sticky.cfgvalue(self, s) if self.map:get(s, "sticky") == "1" then stickied = 1 return "Yes" else stickied = nil return "No" end end timeout = mwan_rule:option(DummyValue, "timeout", translate("Sticky timeout")) timeout.rawhtml = true function timeout.cfgvalue(self, s) if stickied then local timeoutValue = self.map:get(s, "timeout") if timeoutValue then return timeoutValue .. "s" else return "600s" end else return "&#8212;" end end ipset = mwan_rule:option(DummyValue, "ipset", translate("IPset")) ipset.rawhtml = true function ipset.cfgvalue(self, s) return self.map:get(s, "ipset") or "&#8212;" end use_policy = mwan_rule:option(DummyValue, "use_policy", translate("Policy assigned")) use_policy.rawhtml = true function use_policy.cfgvalue(self, s) return self.map:get(s, "use_policy") or "&#8212;" end errors = mwan_rule:option(DummyValue, "errors", translate("Errors")) errors.rawhtml = true function errors.cfgvalue(self, s) if not string.find(error_protocol_list, " " .. s .. " ") then return "" else return "<span title=\"No protocol specified\"><img src=\"/luci-static/resources/cbi/reset.gif\" alt=\"error\"></img></span>" end end return m5
gpl-2.0
swiftgeek/packages
net/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan/interfaceconfig.lua
74
7228
-- ------ extra functions ------ -- function interfaceCheck() metricValue = ut.trim(sys.exec("uci -p /var/state get network." .. arg[1] .. ".metric")) if metricValue == "" then -- no metric errorNoMetric = 1 else -- if metric exists create list of interface metrics to compare against for duplicates uci.cursor():foreach("mwan3", "interface", function (section) local metricValue = ut.trim(sys.exec("uci -p /var/state get network." .. section[".name"] .. ".metric")) metricList = metricList .. section[".name"] .. " " .. metricValue .. "\n" end ) -- compare metric against list local metricDuplicateNumbers, metricDuplicates = sys.exec("echo '" .. metricList .. "' | awk '{print $2}' | uniq -d"), "" for line in metricDuplicateNumbers:gmatch("[^\r\n]+") do metricDuplicates = sys.exec("echo '" .. metricList .. "' | grep '" .. line .. "' | awk '{print $1}'") errorDuplicateMetricList = errorDuplicateMetricList .. metricDuplicates end if sys.exec("echo '" .. errorDuplicateMetricList .. "' | grep -w " .. arg[1]) ~= "" then errorDuplicateMetric = 1 end end -- check if this interface has a higher reliability requirement than track IPs configured local trackingNumber = tonumber(ut.trim(sys.exec("echo $(uci -p /var/state get mwan3." .. arg[1] .. ".track_ip) | wc -w"))) if trackingNumber > 0 then local reliabilityNumber = tonumber(ut.trim(sys.exec("uci -p /var/state get mwan3." .. arg[1] .. ".reliability"))) if reliabilityNumber and reliabilityNumber > trackingNumber then errorReliability = 1 end end -- check if any interfaces are not properly configured in /etc/config/network or have no default route in main routing table if ut.trim(sys.exec("uci -p /var/state get network." .. arg[1])) == "interface" then local interfaceDevice = ut.trim(sys.exec("uci -p /var/state get network." .. arg[1] .. ".ifname")) if interfaceDevice == "uci: Entry not found" or interfaceDevice == "" then errorNetConfig = 1 errorRoute = 1 else local routeCheck = ut.trim(sys.exec("route -n | awk '{if ($8 == \"" .. interfaceDevice .. "\" && $1 == \"0.0.0.0\" && $3 == \"0.0.0.0\") print $1}'")) if routeCheck == "" then errorRoute = 1 end end else errorNetConfig = 1 errorRoute = 1 end end function interfaceWarnings() -- display warning messages at the top of the page local warns, lineBreak = "", "" if errorReliability == 1 then warns = "<font color=\"ff0000\"><strong>WARNING: this interface has a higher reliability requirement than there are tracking IP addresses!</strong></font>" lineBreak = "<br /><br />" end if errorRoute == 1 then warns = warns .. lineBreak .. "<font color=\"ff0000\"><strong>WARNING: this interface has no default route in the main routing table!</strong></font>" lineBreak = "<br /><br />" end if errorNetConfig == 1 then warns = warns .. lineBreak .. "<font color=\"ff0000\"><strong>WARNING: this interface is configured incorrectly or not at all in /etc/config/network!</strong></font>" lineBreak = "<br /><br />" end if errorNoMetric == 1 then warns = warns .. lineBreak .. "<font color=\"ff0000\"><strong>WARNING: this interface has no metric configured in /etc/config/network!</strong></font>" elseif errorDuplicateMetric == 1 then warns = warns .. lineBreak .. "<font color=\"ff0000\"><strong>WARNING: this and other interfaces have duplicate metrics configured in /etc/config/network!</strong></font>" end return warns end -- ------ interface configuration ------ -- dsp = require "luci.dispatcher" sys = require "luci.sys" ut = require "luci.util" arg[1] = arg[1] or "" metricValue = "" metricList = "" errorDuplicateMetricList = "" errorNoMetric = 0 errorDuplicateMetric = 0 errorRoute = 0 errorNetConfig = 0 errorReliability = 0 interfaceCheck() m5 = Map("mwan3", translate("MWAN Interface Configuration - " .. arg[1]), translate(interfaceWarnings())) m5.redirect = dsp.build_url("admin", "network", "mwan", "configuration", "interface") mwan_interface = m5:section(NamedSection, arg[1], "interface", "") mwan_interface.addremove = false mwan_interface.dynamic = false enabled = mwan_interface:option(ListValue, "enabled", translate("Enabled")) enabled.default = "1" enabled:value("1", translate("Yes")) enabled:value("0", translate("No")) track_ip = mwan_interface:option(DynamicList, "track_ip", translate("Tracking IP"), translate("This IP address will be pinged to dermine if the link is up or down. Leave blank to assume interface is always online")) track_ip.datatype = "ipaddr" reliability = mwan_interface:option(Value, "reliability", translate("Tracking reliability"), translate("Acceptable values: 1-100. This many Tracking IP addresses must respond for the link to be deemed up")) reliability.datatype = "range(1, 100)" reliability.default = "1" count = mwan_interface:option(ListValue, "count", translate("Ping count")) count.default = "1" count:value("1") count:value("2") count:value("3") count:value("4") count:value("5") timeout = mwan_interface:option(ListValue, "timeout", translate("Ping timeout")) timeout.default = "2" timeout:value("1", translate("1 second")) timeout:value("2", translate("2 seconds")) timeout:value("3", translate("3 seconds")) timeout:value("4", translate("4 seconds")) timeout:value("5", translate("5 seconds")) timeout:value("6", translate("6 seconds")) timeout:value("7", translate("7 seconds")) timeout:value("8", translate("8 seconds")) timeout:value("9", translate("9 seconds")) timeout:value("10", translate("10 seconds")) interval = mwan_interface:option(ListValue, "interval", translate("Ping interval")) interval.default = "5" interval:value("1", translate("1 second")) interval:value("3", translate("3 seconds")) interval:value("5", translate("5 seconds")) interval:value("10", translate("10 seconds")) interval:value("20", translate("20 seconds")) interval:value("30", translate("30 seconds")) interval:value("60", translate("1 minute")) interval:value("300", translate("5 minutes")) interval:value("600", translate("10 minutes")) interval:value("900", translate("15 minutes")) interval:value("1800", translate("30 minutes")) interval:value("3600", translate("1 hour")) down = mwan_interface:option(ListValue, "down", translate("Interface down"), translate("Interface will be deemed down after this many failed ping tests")) down.default = "3" down:value("1") down:value("2") down:value("3") down:value("4") down:value("5") down:value("6") down:value("7") down:value("8") down:value("9") down:value("10") up = mwan_interface:option(ListValue, "up", translate("Interface up"), translate("Downed interface will be deemed up after this many successful ping tests")) up.default = "3" up:value("1") up:value("2") up:value("3") up:value("4") up:value("5") up:value("6") up:value("7") up:value("8") up:value("9") up:value("10") metric = mwan_interface:option(DummyValue, "metric", translate("Metric"), translate("This displays the metric assigned to this interface in /etc/config/network")) metric.rawhtml = true function metric.cfgvalue(self, s) if errorNoMetric == 0 then return metricValue else return "&#8212;" end end return m5
gpl-2.0
coderpunch/evolvemod
lua/evolve/plugins/sh_cexec.lua
1
1304
--[[----------------------------------------------------------------------------------------------------------------------- Run a console command on someone -----------------------------------------------------------------------------------------------------------------------]]-- local PLUGIN = {} PLUGIN.Title = "Client Exec" PLUGIN.Description = "Run a console command on someone." PLUGIN.Author = "Overv" PLUGIN.ChatCommand = "cexec" PLUGIN.Usage = "<player> <command> [args]" PLUGIN.Privileges = { "Client Exec" } function PLUGIN:Call( ply, args ) if ( ply:EV_HasPrivilege( "Client Exec" ) ) then local players = evolve:FindPlayer( args[1] ) if ( #players < 2 or !players[1] ) then if ( #players > 0 ) then local command = table.concat( args, " ", 2 ) if ( #command > 0 ) then players[1]:ConCommand( command ) else evolve:Notify( ply, evolve.colors.red, "No command specified." ) end else evolve:Notify( ply, evolve.colors.red, evolve.constants.noplayers ) end else evolve:Notify( ply, evolve.colors.white, "Did you mean ", evolve.colors.red, evolve:CreatePlayerList( players, true ), evolve.colors.white, "?" ) end else evolve:Notify( ply, evolve.colors.red, evolve.constants.notallowed ) end end evolve:RegisterPlugin( PLUGIN )
apache-2.0
Marcelo-Mk/StarWats-Api
bot/bot.lua
1
7279
package.path = package.path..';.luarocks/share/lua/5.2/?.lua;.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath..';.luarocks/lib/lua/5.2/?.so' bot_token = "TOKEN" --هنا تخلي التوكن send_api = "https://api.telegram.org/bot"..bot_token sudo_id = 370996919 --هنا تخلي الايدي http = require('socket.http') https = require('ssl.https') URL = require('socket.url') curl = require('cURL') ltn12 = require("ltn12") cUrl_Command = curl.easy{verbose = true} redis = (loadfile "./libs/redis.lua")() json = (loadfile "./libs/JSON.lua")() JSON = (loadfile "./libs/dkjson.lua")() serpent = (loadfile "./libs/serpent.lua")() require('./bot/methods') require('./bot/utils') -- @Mk_Team function bot_run() bot = nil while not bot do bot = send_req(send_api.."/getMe") end bot = bot.result local runlog = bot.first_name.." [@"..bot.username.."]\nis run in: "..os.date("%F - %H:%M:%S") print(runlog) send_msg(sudo_id, runlog) last_update = last_update or 0 last_cron = last_cron or os.time() startbot = true our_id = bot.id end function send_req(url) local dat, res = https.request(url) local tab = JSON.decode(dat) if res ~= 200 then return false end if not tab.ok then return false end return tab end function bot_updates(offset) local url = send_api.."/getUpdates?timeout=10" if offset then url = url.."&offset="..offset end return send_req(url) end function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end function msg_valid(msg) local msg_time = os.time() - 60 if msg.date < tonumber(msg_time) then print('\27[36m》》OLD MESSAGE《《\27[39m') return false end if is_silent_user(msg.from.id, msg.chat.id) then del_msg(msg.chat.id, tonumber(msg.message_id)) return false end if is_banned(msg.from.id, msg.chat.id) then del_msg(msg.chat.id, tonumber(msg.message_id)) kick_user(msg.from.id, msg.chat.id) return false end if is_gbanned(msg.from.id) then del_msg(msg.chat.id, tonumber(msg.message_id)) kick_user(msg.from.id, msg.chat.id) return false end return true 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 plugins = {} function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end function match_plugin(plugin, plugin_name, msg) -- Go over patterns. If one matches it's enough. if plugin.pre_process then --If plugin is for privileged users only local result = plugin.pre_process(msg) if result then print("pre process: ", plugin_name) end end for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text or msg.caption or msg.query) if matches then print("msg matches: ", pattern) -- Function exists if plugin.run then -- If plugin is for privileged users only local result = plugin.run(msg, matches) if result then send_msg(msg.chat.id, result, msg.message_id, "md") end end return end end end local function handle_inline_keyboards_cb(msg) msg.text = '###cb:'..msg.data msg.cb = true if msg.new_chat_member then msg.service = true msg.text = '###new_chat_member' end if msg.message then msg.old_text = msg.message.text msg.old_date = msg.message.date msg.message_id = msg.message.message_id msg.chat = msg.message.chat msg.message_id = msg.message.message_id msg.chat = msg.message.chat else -- if keyboard send via msg.chat = {type = 'inline', id = msg.from.id, title = msg.from.first_name} msg.message_id = msg.inline_message_id end msg.cb_id = msg.id msg.date = os.time() msg.message = nil msg.target_id = msg.data:match('.*:(-?%d+)') return get_var(msg) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Create a basic config.json file and saves it. function create_config( ) io.write('\n\27[1;33m>> Input your Telegram ID for set Sudo :\27[0;39;49m') local SUDO = tonumber(io.read()) if not tostring(SUDO):match('%d+') then SUDO = 157059515 end -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "plugins", "msg_checks", "groupmanager", "tools", "banhammer" }, sudo_users = {370996919, SUDO},--ايدي المطور master_id = SUDO, admins = {}, disabled_channels = {}, moderation = {data = './data/moderation.json'}, info_text = [[*Star Wars Api v2 [AR]* سورس Star Wars-Api يعمل على مجموعات تصل *10K* > [Star Wars-Api](https://github.com/Marcelo-Mk/StarWats-Api) The Developers > Star Wars-Api > [Marcelo Mk](t.me/iidii) >[Ali Programmer](t.me/xDrrr) >[Channel](T.me/mk_team) >[The Grouo support Star Wars-Api](https://t.me/joinchat/Fhz2t0IcBHGXM3_-5QNDvA) ]], } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Sudo user: " .. user) end return config end _config = load_config( ) -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end bot_run() load_plugins() while startbot do local res = bot_updates(last_update+1) if res then for i,v in ipairs(res.result) do last_update = v.update_id if v.edited_message then get_var(v.edited_message) elseif v.message then if msg_valid(v.message) then get_var(v.message) end elseif v.inline_query then get_var_inline(v.inline_query) elseif v.callback_query then handle_inline_keyboards_cb(v.callback_query) end end else print("error while") end if last_cron < os.time() - 30 then for name, plugin in pairs(plugins) do if plugin.cron then local res, err = pcall( function() plugin.cron() end ) end if not res then print('error: '..err) end end last_cron = os.time() end end
gpl-3.0
n0xus/darkstar
scripts/zones/Northern_San_dOria/npcs/Gulmama.lua
19
5104
----------------------------------- -- Area: Northern San d'Oria -- NPC: Gulmama -- Starts and Finishes Quest: Trial by Ice -- Involved in Quest: Class Reunion -- @pos -186 0 107 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TrialByIce = player:getQuestStatus(SANDORIA,TRIAL_BY_ICE); local WhisperOfFrost = player:hasKeyItem(WHISPER_OF_FROST); local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day local ClassReunion = player:getQuestStatus(WINDURST,CLASS_REUNION); local ClassReunionProgress = player:getVar("ClassReunionProgress"); ------------------------------------------------------------ -- Class Reunion if (ClassReunion == 1 and ClassReunionProgress == 4) then player:startEvent(0x02c9,0,1171,0,0,0,0,0,0); -- he gives you an ice pendulum and wants you to go to Cloister of Frost elseif (ClassReunion == 1 and ClassReunionProgress == 5 and player:hasItem(1171) == false) then player:startEvent(0x02c8,0,1171,0,0,0,0,0,0); -- lost the ice pendulum need another one ------------------------------------------------------------ elseif ((TrialByIce == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 6) or (TrialByIce == QUEST_COMPLETED and realday ~= player:getVar("TrialByIce_date"))) then player:startEvent(0x02c2,0,TUNING_FORK_OF_ICE); -- Start and restart quest "Trial by ice" elseif (TrialByIce == QUEST_ACCEPTED and player:hasKeyItem(TUNING_FORK_OF_ICE) == false and WhisperOfFrost == false) then player:startEvent(0x02ce,0,TUNING_FORK_OF_ICE); -- Defeat against Shiva : Need new Fork elseif (TrialByIce == QUEST_ACCEPTED and WhisperOfFrost == false) then player:startEvent(0x02c3,0,TUNING_FORK_OF_ICE,4); elseif (TrialByIce == QUEST_ACCEPTED and WhisperOfFrost) then local numitem = 0; if (player:hasItem(17492)) then numitem = numitem + 1; end -- Shiva's Claws if (player:hasItem(13242)) then numitem = numitem + 2; end -- Ice Belt if (player:hasItem(13561)) then numitem = numitem + 4; end -- Ice Ring if (player:hasItem(1207)) then numitem = numitem + 8; end -- Rust 'B' Gone if (player:hasSpell(302)) then numitem = numitem + 32; end -- Ability to summon Shiva player:startEvent(0x02c5,0,TUNING_FORK_OF_ICE,4,0,numitem); else player:startEvent(0x02c6); -- Standard dialog 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); if (csid == 0x02c2 and option == 1) then if (player:getQuestStatus(SANDORIA,TRIAL_BY_ICE) == QUEST_COMPLETED) then player:delQuest(SANDORIA,TRIAL_BY_ICE); end player:addQuest(SANDORIA,TRIAL_BY_ICE); player:setVar("TrialByIce_date", 0); player:addKeyItem(TUNING_FORK_OF_ICE); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_ICE); elseif (csid == 0x02ce) then player:addKeyItem(TUNING_FORK_OF_ICE); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_ICE); elseif (csid == 0x02c5) then local item = 0; if (option == 1) then item = 17492; -- Shiva's Claws elseif (option == 2) then item = 13242; -- Ice Belt elseif (option == 3) then item = 13561; -- Ice Ring elseif (option == 4) then item = 1207; -- Rust 'B' Gone end if (player:getFreeSlotsCount() == 0 and (option ~= 5 or option ~= 6)) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item); else if (option == 5) then player:addGil(GIL_RATE*10000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*10000); -- Gil elseif (option == 6) then player:addSpell(302); -- Avatar player:messageSpecial(SHIVA_UNLOCKED,0,0,4); else player:addItem(item); player:messageSpecial(ITEM_OBTAINED,item); -- Item end player:addTitle(HEIR_OF_THE_GREAT_ICE); player:delKeyItem(WHISPER_OF_FROST); --Whisper of Frost, as a trade for the above rewards player:setVar("TrialByIce_date", os.date("%j")); -- %M for next minute, %j for next day player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,TRIAL_BY_ICE); end elseif (csid == 0x02c9 or csid == 0x02c8) then if (player:getFreeSlotsCount() ~= 0) then player:addItem(1171); player:messageSpecial(ITEM_OBTAINED,1171); player:setVar("ClassReunionProgress",5); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1171); end; end; end;
gpl-3.0
n0xus/darkstar
scripts/globals/mobskills/Sickle_Slash.lua
12
1266
--------------------------------------------------- -- Sickle Slash -- Deals critical damage. Chance of critical hit varies with TP. --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- --------------------------------------------------- -- onMobSkillCheck -- Check for Grah Family id 122,123,124 -- if not in Spider form, then ignore. --------------------------------------------------- function onMobSkillCheck(target,mob,skill) if ((mob:getFamily() == 122 or mob:getFamily() == 123 or mob:getFamily() == 124) and mob:AnimationSub() ~= 2) then return 1; else return 0; end end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = math.random(2,5) + math.random(); local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_CRIT_VARIES,1,1.5,2); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); -- cap off damage around 600 if (dmg > 600) then dmg = dmg * 0.7; end target:delHP(dmg); return dmg; end;
gpl-3.0
dmccuskey/dmc-netstream
examples/dmc-netstream-basic/dmc_corona/lib/dmc_lua/lua_bytearray/pack_bytearray.lua
7
6402
--====================================================================-- -- dmc_lua/lua_bytearray/pack_bytearray.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014-2015 David McCuskey 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. --]] --[[ based off work from zrong(zengrong.net) https://github.com/zrong/lua#ByteArray https://github.com/zrong/lua/blob/master/lib/zrong/zr/utils/ByteArray.lua --]] --====================================================================-- --== DMC Lua Library: Lua Byte Array (pack) --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.0" --====================================================================-- --== Imports require 'pack' --====================================================================-- --== Pack Byte Array Class --====================================================================-- local ByteArray = {} ByteArray.ENDIAN_LITTLE = 'endian_little' ByteArray.ENDIAN_BIG = 'endian_big' --====================================================================-- --== Public Methods function ByteArray:readDouble() self:_checkAvailable(8) local _, val = string.unpack(self:readBuf(8), self:_getLC("d")) return val end function ByteArray:writeDouble( double ) local str = string.pack( self:_getLC("d"), double ) self:writeBuf( str ) return self end function ByteArray:readFloat() self:_checkAvailable(4) local _, val = string.unpack(self:readBuf(4), self:_getLC("f")) return val end function ByteArray:writeFloat( float ) local str = string.pack( self:_getLC("f"), float) self:writeBuf( str ) return self end function ByteArray:readInt() self:_checkAvailable(4) local _, val = string.unpack(self:readBuf(4), self:_getLC("i")) return val end function ByteArray:writeInt( int ) local str = string.pack( self:_getLC("i"), int ) self:writeBuf( str ) return self end function ByteArray:readLong() self:_checkAvailable(8) local _, val = string.unpack(self:readBuf(8), self:_getLC("l")) return val end function ByteArray:writeLong( long ) local str = string.pack( self:_getLC("l"), long ) self:writeBuf( str ) return self end function ByteArray:readMultiByte( len ) error("not implemented") return val end function ByteArray:writeMultiByte( int ) error("not implemented") return self end function ByteArray:readStringBytes( len ) assert( len , "Need a length of the string!") if len == 0 then return "" end self:_checkAvailable( len ) local __, __v = string.unpack(self:readBuf( len ), self:_getLC( "A".. len )) return __v end function ByteArray:writeStringBytes(__string) local __s = string.pack(self:_getLC("A"), __string) self:writeBuf(__s) return self end function ByteArray:readStringUnsignedShort() local len = self:readUShort() return self:readStringBytes( len ) end ByteArray.readStringUShort = ByteArray.readStringUnsignedShort function ByteArray:writeStringUnsignedShort( ustr ) local str = string.pack(self:_getLC("P"), ustr ) self:writeBuf( str ) return self end ByteArray.writeStringUShort = ByteArray.writeStringUnsignedShort function ByteArray:readShort() self:_checkAvailable(2) local _, val = string.unpack(self:readBuf(2), self:_getLC("h")) return val end function ByteArray:writeShort( short ) local str = string.pack( self:_getLC("h"), short ) self:writeBuf( str ) return self end function ByteArray:readUnsignedByte() self:_checkAvailable(1) local _, val = string.unpack(self:readChar(), "b") return val end ByteArray.readUByte = ByteArray.readUnsignedByte function ByteArray:writeUnsignedByte( ubyte ) local str = string.pack("b", ubyte ) self:writeBuf( str ) return self end ByteArray.writeUByte = ByteArray.writeUnsignedByte function ByteArray:readUInt() self:_checkAvailable(4) local _, val = string.unpack(self:readBuf(4), self:_getLC("I")) return val end ByteArray.readUInt = ByteArray.readUnsignedInt function ByteArray:writeUInt( uint ) local str = string.pack(self:_getLC("I"), uint ) self:writeBuf( str ) return self end ByteArray.writeUInt = ByteArray.writeUnsignedInt function ByteArray:readUnsignedLong() self:_checkAvailable(4) local _, val = string.unpack(self:readBuf(4), self:_getLC("L")) return val end ByteArray.readULong = ByteArray.readUnsignedLong function ByteArray:writeUnsignedLong( ulong ) local str = string.pack( self:_getLC("L"), ulong ) self:writeBuf( str ) return self end ByteArray.writeULong = ByteArray.writeUnsignedLong function ByteArray:readUnsignedShort() self:_checkAvailable(2) local _, val = string.unpack(self:readBuf(2), self:_getLC("H")) return val end ByteArray.readUShort = ByteArray.readUnsignedShort function ByteArray:writeUnsignedShort( ushort ) local str = string.pack(self:_getLC("H"), ushort ) self:writeBuf( str ) return self end ByteArray.writeUShort = ByteArray.writeUnsignedShort --====================================================================-- --== Private Methods function ByteArray:_getLC( format ) format = format or "" if self._endian == ByteArray.ENDIAN_LITTLE then return "<".. format elseif self._endian == ByteArray.ENDIAN_BIG then return ">".. format end return "=".. format end return ByteArray
mit
n0xus/darkstar
scripts/zones/Provenance/Zone.lua
17
1256
----------------------------------- -- -- Zone: Provenance (222) -- ----------------------------------- package.loaded["scripts/zones/Provenance/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Provenance/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) cs = -1; if ( player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-640,-20,-519.999,192); end return cs; 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); end;
gpl-3.0
davymai/CN-QulightUI
Interface/AddOns/QulightUI/Root/Fonts.lua
1
4243
do SetFontString = function(parent, fontName, fontHeight, fontStyle) local fs = parent:CreateFontString(nil, "OVERLAY") fs:SetFont(Qulight["media"].font, fontHeight, fontStyle) fs:SetJustifyH("LEFT") fs:SetShadowColor(0, 0, 0) fs:SetShadowOffset(1.25, -1.25) return fs end end --------------------- -- Font --------------------- local Fonts = CreateFrame("Frame", nil, UIParent) SetFont = function(obj, font, size, style, r, g, b, sr, sg, sb, sox, soy) obj:SetFont(font, size, style) if sr and sg and sb then obj:SetShadowColor(sr, sg, sb) end if sox and soy then obj:SetShadowOffset(sox, soy) end if r and g and b then obj:SetTextColor(r, g, b) elseif r then obj:SetAlpha(r) end end Fonts:RegisterEvent("ADDON_LOADED") Fonts:SetScript("OnEvent", function(self, event, addon) local NORMAL = Qulight["media"].font local COMBAT = Qulight["media"].font local NUMBER = Qulight["media"].font local _, editBoxFontSize, _, _, _, _, _, _, _, _ = GetChatWindowInfo(1) UIDROPDOWNMENU_DEFAULT_TEXT_HEIGHT = 12 CHAT_FONT_HEIGHTS = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20} UNIT_NAME_FONT = NORMAL NAMEPLATE_FONT = NORMAL DAMAGE_TEXT_FONT = COMBAT STANDARD_TEXT_FONT = NORMAL SetFont(GameTooltipHeader, NORMAL, Qulight["media"].fontsize) SetFont(NumberFont_OutlineThick_Mono_Small, NUMBER, Qulight["media"].fontsize, "OUTLINE") SetFont(NumberFont_Outline_Huge, NUMBER, 28, "THICKOUTLINE", 28) SetFont(NumberFont_Outline_Large, NUMBER, 15, "OUTLINE") SetFont(NumberFont_Outline_Med, Qulight["media"].font, Qulight["media"].fontsize, "OUTLINE") SetFont(NumberFont_Shadow_Med, NORMAL, Qulight["media"].fontsize+1) --chat editbox uses this SetFont(NumberFont_Shadow_Small, NORMAL, Qulight["media"].fontsize) SetFont(QuestFont, NORMAL, Qulight["media"].fontsize*0.9) SetFont(QuestFont_Large, NORMAL, 18) SetFont(SystemFont_Large, NORMAL, 15) SetFont(SystemFont_Shadow_Huge1, NORMAL, 20, "THINOUTLINE") -- Raid Warning, Boss emote frame too SetFont(SystemFont_Med1, NORMAL, Qulight["media"].fontsize) SetFont(SystemFont_Med3, NORMAL, Qulight["media"].fontsize*1.1) SetFont(SystemFont_OutlineThick_Huge2, NORMAL, 20, "THICKOUTLINE") SetFont(SystemFont_Outline_Small, NUMBER, Qulight["media"].fontsize, "OUTLINE") SetFont(SystemFont_Shadow_Large, NORMAL, 15) SetFont(SystemFont_Shadow_Med1, NORMAL, Qulight["media"].fontsize) SetFont(SystemFont_Shadow_Med3, NORMAL, Qulight["media"].fontsize*1.1) SetFont(SystemFont_Shadow_Outline_Huge2, NORMAL, 20, "OUTLINE") SetFont(SystemFont_Shadow_Small, NORMAL, Qulight["media"].fontsize*0.9) SetFont(SystemFont_Small, NORMAL, Qulight["media"].fontsize) SetFont(SystemFont_Tiny, NORMAL, Qulight["media"].fontsize) SetFont(Tooltip_Med, NORMAL, Qulight["media"].fontsize) SetFont(Tooltip_Small, NORMAL, Qulight["media"].fontsize) SetFont(ZoneTextString, NORMAL, 32, "OUTLINE") SetFont(SubZoneTextString, NORMAL, 25, "OUTLINE") SetFont(PVPInfoTextString, NORMAL, 22, "THINOUTLINE") SetFont(PVPArenaTextString, NORMAL, 22, "THINOUTLINE") SetFont(CombatTextFont, COMBAT, 100, "OUTLINE") -- number here just increase the font quality. SetFont(InvoiceFont_Med, NORMAL, 13) SetFont(InvoiceFont_Small, NORMAL, 10) SetFont(MailFont_Large, NORMAL, 15) SetFont(QuestFont_Shadow_Huge, NORMAL, 19) SetFont(QuestFont_Shadow_Small, NORMAL, 15) SetFont(ReputationDetailFont, NORMAL, 10) SetFont(SpellFont_Small, NORMAL, 10) SetFont(FriendsFont_Small, NORMAL, Qulight["media"].fontsize) SetFont(FriendsFont_Normal, NORMAL, Qulight["media"].fontsize) SetFont(FriendsFont_Large, NORMAL, Qulight["media"].fontsize) SetFont(FriendsFont_UserText, NORMAL, Qulight["media"].fontsize) SetFont(ChatBubbleFont, NORMAL, Qulight["media"].fontsize) SetFont = nil self:SetScript("OnEvent", nil) self:UnregisterAllEvents() self = nil end)
gpl-2.0
doublec/ponyc
premake5.lua
1
6608
local force_cpp = { } function cppforce(inFiles) for _, val in ipairs(inFiles) do for _, fname in ipairs(os.matchfiles(val)) do table.insert(force_cpp, path.getabsolute(fname)) end end end -- gmake premake.override(path, "iscfile", function(base, fname) if table.contains(force_cpp, fname) then return false else return base(fname) end end) -- Visual Studio premake.override(premake.vstudio.vc2010, "additionalCompileOptions", function(base, cfg, condition) if cfg.abspath then if table.contains(force_cpp, cfg.abspath) then _p(3,'<CompileAs %s>CompileAsCpp</CompileAs>', condition) end end return base(cfg, condition) end) function link_libponyc() configuration "gmake" linkoptions { llvm_config("--ldflags") } configuration "vs*" libdirs { llvm_config("--libdir") } configuration "*" links { "libponyc", "libponyrt" } local output = llvm_config("--libs") for lib in string.gmatch(output, "-l(%S+)") do links { lib } end end function llvm_config(opt) --expect symlink of llvm-config to your config version (e.g llvm-config-3.4) local stream = assert(io.popen("llvm-config " .. opt)) local output = "" --llvm-config contains '\n' while true do local curr = stream:read("*l") if curr == nil then break end output = output .. curr end stream:close() return output end function testsuite() kind "ConsoleApp" language "C++" links "gtest" configuration "gmake" buildoptions { "-std=gnu++11" } configuration "*" if (_OPTIONS["run-tests"]) then configuration "gmake" postbuildcommands { "$(TARGET)" } configuration "vs*" postbuildcommands { "\"$(TargetPath)\"" } configuration "*" end end solution "ponyc" configurations { "Debug", "Release", "Profile" } location( _OPTIONS["to"] ) flags { "FatalWarnings", "MultiProcessorCompile", "ReleaseRuntime" --for all configs } configuration "Debug" targetdir "build/debug" objdir "build/debug/obj" defines "DEBUG" flags { "Symbols" } configuration "Release" targetdir "build/release" objdir "build/release/obj" configuration "Profile" targetdir "build/profile" objdir "build/profile/obj" configuration "Release or Profile" defines "NDEBUG" optimize "Speed" --flags { "LinkTimeOptimization" } if not os.is("windows") then linkoptions { "-flto", "-fuse-ld=gold" } end configuration { "Profile", "gmake" } buildoptions "-pg" linkoptions "-pg" configuration { "Profile", "vs*" } buildoptions "/PROFILE" configuration "vs*" local version, exitcode = os.outputof("git describe --tags --always") if exitcode ~= 0 then version = os.outputof("type VERSION") end debugdir "." defines { -- disables warnings for vsnprintf "_CRT_SECURE_NO_WARNINGS", "PONY_VERSION=\"" .. string.gsub(version, "\n", "") .. "\"", "PLATFORM_TOOLS_VERSION=$(PlatformToolsetVersion)" } configuration { "not windows" } linkoptions { "-pthread" } configuration { "macosx", "gmake" } toolset "clang" buildoptions "-Qunused-arguments" linkoptions "-Qunused-arguments" configuration "gmake" buildoptions { "-march=native" } configuration "vs*" architecture "x64" project "libponyc" targetname "ponyc" kind "StaticLib" language "C" includedirs { llvm_config("--includedir"), "src/common" } files { "src/common/*.h", "src/libponyc/**.c*", "src/libponyc/**.h" } configuration "gmake" buildoptions{ "-std=gnu11" } defines { "__STDC_CONSTANT_MACROS", "__STDC_FORMAT_MACROS", "__STDC_LIMIT_MACROS" } excludes { "src/libponyc/**.cc" } configuration "vs*" characterset "MBCS" defines { "PONY_USE_BIGINT" } cppforce { "src/libponyc/**.c*" } configuration "*" project "libponyrt" targetname "ponyrt" kind "StaticLib" language "C" includedirs { "src/common/", "src/libponyrt/" } files { "src/libponyrt/**.c", "src/libponyrt/**.h" } configuration "gmake" buildoptions { "-std=gnu11" } configuration "vs*" characterset "MBCS" cppforce { "src/libponyrt/**.c" } configuration "*" project "ponyc" kind "ConsoleApp" language "C++" includedirs { llvm_config("--includedir"), "src/common/" } files { "src/ponyc/**.h", "src/ponyc/**.c" } configuration "gmake" buildoptions "-std=gnu11" configuration "vs*" characterset "MBCS" cppforce { "src/ponyc/**.c" } configuration "*" link_libponyc() if ( _OPTIONS["with-tests"] or _OPTIONS["run-tests"] ) then project "gtest" targetname "gtest" language "C++" kind "StaticLib" configuration "gmake" buildoptions { "-std=gnu++11" } configuration "vs*" characterset "MBCS" configuration "*" includedirs { "utils/gtest" } files { "lib/gtest/gtest-all.cc", "lib/gtest/gtest_main.cc" } project "testc" targetname "testc" testsuite() includedirs { llvm_config("--includedir"), "lib/gtest", "src/common", "src/libponyc" } files { "test/libponyc/**.h", "test/libponyc/**.cc" } configuration "vs*" characterset "MBCS" defines { "PONY_USE_BIGINT" } configuration "*" link_libponyc() project "testrt" targetname "testrt" testsuite() links "libponyrt" includedirs { "lib/gtest", "src/common", "src/libponyrt" } files { "test/libponyrt/**.cc" } configuration "vs*" characterset "MBCS" end if _ACTION == "clean" then os.rmdir("build") end -- Allow for out-of-source builds. newoption { trigger = "to", value = "path", description = "Set output location for generated files." } newoption { trigger = "with-tests", description = "Compile test suite for every build." } newoption { trigger = "run-tests", description = "Run the test suite on every successful build." }
bsd-2-clause
n0xus/darkstar
scripts/zones/PsoXja/npcs/Treasure_Chest.lua
19
2932
----------------------------------- -- Area: Pso'Xja -- NPC: Treasure Chest -- @zone 9 ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/zones/PsoXja/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1064,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1064,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); -- IMPORTANT ITEM: Map ----------- if (player:hasKeyItem(MAP_OF_PSOXJA) == false) then questItemNeeded = 1; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then player:addKeyItem(MAP_OF_PSOXJA); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_PSOXJA); -- Map of Pso'Xja else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1064); 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
chengyi818/openwrt
customer/packages/luci/applications/luci-asterisk/luasrc/model/cbi/asterisk/trunk_sip.lua
80
2561
--[[ LuCI - Lua Configuration Interface Copyright 2008 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ast = require("luci.asterisk") -- -- SIP trunk info -- if arg[2] == "info" then form = SimpleForm("asterisk", "SIP Trunk Information") form.reset = false form.submit = "Back to overview" local info, keys = ast.sip.peer(arg[1]) local data = { } for _, key in ipairs(keys) do data[#data+1] = { key = key, val = type(info[key]) == "boolean" and ( info[key] and "yes" or "no" ) or ( info[key] == nil or #info[key] == 0 ) and "(none)" or tostring(info[key]) } end itbl = form:section(Table, data, "SIP Trunk %q" % arg[1]) itbl:option(DummyValue, "key", "Key") itbl:option(DummyValue, "val", "Value") function itbl.parse(...) luci.http.redirect( luci.dispatcher.build_url("admin", "asterisk", "trunks") ) end return form -- -- SIP trunk config -- elseif arg[1] then cbimap = Map("asterisk", "Edit SIP Trunk") peer = cbimap:section(NamedSection, arg[1]) peer.hidden = { type = "peer", qualify = "yes", } back = peer:option(DummyValue, "_overview", "Back to trunk overview") back.value = "" back.titleref = luci.dispatcher.build_url("admin", "asterisk", "trunks") sipdomain = peer:option(Value, "host", "SIP Domain") sipport = peer:option(Value, "port", "SIP Port") function sipport.cfgvalue(...) return AbstractValue.cfgvalue(...) or "5060" end username = peer:option(Value, "username", "Authorization ID") password = peer:option(Value, "secret", "Authorization Password") password.password = true outboundproxy = peer:option(Value, "outboundproxy", "Outbound Proxy") outboundport = peer:option(Value, "outboundproxyport", "Outbound Proxy Port") register = peer:option(Flag, "register", "Register with peer") register.enabled = "yes" register.disabled = "no" regext = peer:option(Value, "registerextension", "Extension to register (optional)") regext:depends({register="1"}) didval = peer:option(ListValue, "_did", "Number of assigned DID numbers") didval:value("", "(none)") for i=1,24 do didval:value(i) end dialplan = peer:option(ListValue, "context", "Dialplan Context") dialplan:value(arg[1] .. "_inbound", "(default)") cbimap.uci:foreach("asterisk", "dialplan", function(s) dialplan:value(s['.name']) end) return cbimap end
gpl-2.0
n0xus/darkstar
scripts/zones/Northern_San_dOria/npcs/Fantarviont.lua
36
1430
----------------------------------- -- Area: Northern San d'Oria -- NPC: Fantarviont -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x029f); 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
ppriest/mame
3rdparty/genie/src/actions/vstudio/_vstudio.lua
4
7679
-- -- _vstudio.lua -- Define the Visual Studio 200x actions. -- Copyright (c) 2008-2011 Jason Perkins and the Premake project -- premake.vstudio = { } -- -- Set default toolset -- local toolsets = { vs2010 = "v100", vs2012 = "v110", vs2013 = "v120", vs2015 = "v140", vs15 = "v140", } premake.vstudio.toolset = toolsets[_ACTION] or "unknown?" premake.vstudio.splashpath = '' local vstudio = premake.vstudio -- -- Map Premake platform identifiers to the Visual Studio versions. Adds the Visual -- Studio specific "any" and "mixed" to make solution generation easier. -- vstudio.platforms = { any = "Any CPU", mixed = "Mixed Platforms", Native = "Win32", x86 = "x86", x32 = "Win32", x64 = "x64", PS3 = "PS3", Xbox360 = "Xbox 360", ARM = "ARM", Orbis = "Orbis", Durango = "Durango", } -- -- Returns the architecture identifier for a project. -- Used by the solutions. -- function vstudio.arch(prj) if (prj.language == "C#") then return "Any CPU" else return "Win32" end end function vstudio.iswinrt() return vstudio.storeapp ~= nil and vstudio.storeapp ~= '' end -- -- Process the solution's list of configurations and platforms, creates a list -- of build configuration/platform pairs in a Visual Studio compatible format. -- function vstudio.buildconfigs(sln) local cfgs = { } local platforms = premake.filterplatforms(sln, vstudio.platforms, "Native") -- Figure out what's in this solution local hascpp = premake.hascppproject(sln) local hasdotnet = premake.hasdotnetproject(sln) -- "Mixed Platform" solutions are generally those containing both -- C/C++ and .NET projects. Starting in VS2010, all .NET solutions -- also contain the Mixed Platform option. if hasdotnet and (_ACTION > "vs2008" or hascpp) then table.insert(platforms, 1, "mixed") end -- "Any CPU" is added to solutions with .NET projects. Starting in -- VS2010, only pure .NET solutions get this option. if hasdotnet and (_ACTION < "vs2010" or not hascpp) then table.insert(platforms, 1, "any") end -- In Visual Studio 2010, pure .NET solutions replace the Win32 platform -- with x86. In mixed mode solution, x86 is used in addition to Win32. if _ACTION > "vs2008" then local platforms2010 = { } for _, platform in ipairs(platforms) do if vstudio.platforms[platform] == "Win32" then if hascpp then table.insert(platforms2010, platform) end if hasdotnet then table.insert(platforms2010, "x86") end else table.insert(platforms2010, platform) end end platforms = platforms2010 end for _, buildcfg in ipairs(sln.configurations) do for _, platform in ipairs(platforms) do local entry = { } entry.src_buildcfg = buildcfg entry.src_platform = platform -- PS3 is funky and needs special handling; it's more of a build -- configuration than a platform from Visual Studio's point of view. -- This has been fixed in VS2010 as it now truly supports 3rd party -- platforms, so only do this fixup when not in VS2010 if platform ~= "PS3" or _ACTION > "vs2008" then entry.buildcfg = buildcfg entry.platform = vstudio.platforms[platform] else entry.buildcfg = platform .. " " .. buildcfg entry.platform = "Win32" end -- create a name the way VS likes it entry.name = entry.buildcfg .. "|" .. entry.platform -- flag the "fake" platforms added for .NET entry.isreal = (platform ~= "any" and platform ~= "mixed") table.insert(cfgs, entry) end end return cfgs end -- -- Clean Visual Studio files -- function vstudio.cleansolution(sln) premake.clean.file(sln, "%%.sln") premake.clean.file(sln, "%%.suo") premake.clean.file(sln, "%%.ncb") -- MonoDevelop files premake.clean.file(sln, "%%.userprefs") premake.clean.file(sln, "%%.usertasks") end function vstudio.cleanproject(prj) local fname = premake.project.getfilename(prj, "%%") os.remove(fname .. ".vcproj") os.remove(fname .. ".vcproj.user") os.remove(fname .. ".vcxproj") os.remove(fname .. ".vcxproj.user") os.remove(fname .. ".vcxproj.filters") os.remove(fname .. ".csproj") os.remove(fname .. ".csproj.user") os.remove(fname .. ".pidb") os.remove(fname .. ".sdf") end function vstudio.cleantarget(name) os.remove(name .. ".pdb") os.remove(name .. ".idb") os.remove(name .. ".ilk") os.remove(name .. ".vshost.exe") os.remove(name .. ".exe.manifest") end -- -- Assemble the project file name. -- function vstudio.projectfile(prj) local pattern if prj.language == "C#" then pattern = "%%.csproj" else if _ACTION == "vs15" then pattern = "%%.vcxproj" else pattern = iif(_ACTION > "vs2008", "%%.vcxproj", "%%.vcproj") end end local fname = premake.project.getbasename(prj.name, pattern) fname = path.join(prj.location, fname) return fname end -- -- Returns the Visual Studio tool ID for a given project type. -- function vstudio.tool(prj) if (prj.language == "C#") then return "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC" else return "8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942" end end -- -- Register Visual Studio 2008 -- newaction { trigger = "vs2008", shortname = "Visual Studio 2008", description = "Generate Microsoft Visual Studio 2008 project files", os = "windows", valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib" }, valid_languages = { "C", "C++", "C#" }, valid_tools = { cc = { "msc" }, dotnet = { "msnet" }, }, onsolution = function(sln) premake.generate(sln, "%%.sln", vstudio.sln2005.generate) end, onproject = function(prj) if premake.isdotnetproject(prj) then premake.generate(prj, "%%.csproj", vstudio.cs2005.generate) premake.generate(prj, "%%.csproj.user", vstudio.cs2005.generate_user) else premake.generate(prj, "%%.vcproj", vstudio.vc200x.generate) premake.generate(prj, "%%.vcproj.user", vstudio.vc200x.generate_user) end end, oncleansolution = vstudio.cleansolution, oncleanproject = vstudio.cleanproject, oncleantarget = vstudio.cleantarget, vstudio = { productVersion = "9.0.21022", solutionVersion = "10", toolsVersion = "3.5", supports64bitEditContinue = false, } } -- -- Register Visual Studio 2010 -- newaction { trigger = "vs2010", shortname = "Visual Studio 2010", description = "Generate Microsoft Visual Studio 2010 project files", os = "windows", valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib" }, valid_languages = { "C", "C++", "C#"}, valid_tools = { cc = { "msc" }, dotnet = { "msnet" }, }, onsolution = function(sln) premake.generate(sln, "%%.sln", vstudio.sln2005.generate) end, onproject = function(prj) if premake.isdotnetproject(prj) then premake.generate(prj, "%%.csproj", vstudio.cs2005.generate) premake.generate(prj, "%%.csproj.user", vstudio.cs2005.generate_user) else premake.generate(prj, "%%.vcxproj", premake.vs2010_vcxproj) premake.generate(prj, "%%.vcxproj.user", premake.vs2010_vcxproj_user) premake.generate(prj, "%%.vcxproj.filters", vstudio.vc2010.generate_filters) end end, oncleansolution = premake.vstudio.cleansolution, oncleanproject = premake.vstudio.cleanproject, oncleantarget = premake.vstudio.cleantarget, vstudio = { productVersion = "8.0.30703", solutionVersion = "11", targetFramework = "4.0", toolsVersion = "4.0", supports64bitEditContinue = false, } }
gpl-2.0
ianchia/gideros-untar
untar.lua
1
4757
--[[ -- Extract TAR files without compression for Gideros Mobile -- -- This module is based on tar.lua file on Kepler Project -- https://github.com/keplerproject/luarocks/blob/master/src/luarocks/tools/tar.lua -- -- @author decocaribe [at] gmail [dot] com --]] local blocksize = 512 local _ceil = math.ceil local _tonumber = tonumber local _ioOpen = io.open local function get_typeflag(flag) if flag == "0" or flag == "\0" then return "file" elseif flag == "1" then return "link" elseif flag == "2" then return "symlink" -- "reserved" in POSIX, "symlink" in GNU elseif flag == "3" then return "character" elseif flag == "4" then return "block" elseif flag == "5" then return "directory" elseif flag == "6" then return "fifo" elseif flag == "7" then return "contiguous" -- "reserved" in POSIX, "contiguous" in GNU elseif flag == "x" then return "next file" elseif flag == "g" then return "global extended header" elseif flag == "L" then return "long name" elseif flag == "K" then return "long link name" end return "unknown" end local function octal_to_number(octal) local exp = 0 local number = 0 for i = #octal,1,-1 do local digit = _tonumber(octal:sub(i,i)) if not digit then break end number = number + (digit * 8^exp) exp = exp + 1 end return number end local function checksum_header(block) local sum = 256 for i = 1,148 do sum = sum + block:byte(i) end for i = 157,500 do sum = sum + block:byte(i) end return sum end local function nullterm(s) return s:match("^[^%z]*") end local function read_header_block(block) local header = {} header.name = nullterm(block:sub(1,100)) header.mode = nullterm(block:sub(101,108)) header.uid = octal_to_number(nullterm(block:sub(109,116))) header.gid = octal_to_number(nullterm(block:sub(117,124))) header.size = octal_to_number(nullterm(block:sub(125,136))) header.mtime = octal_to_number(nullterm(block:sub(137,148))) header.chksum = octal_to_number(nullterm(block:sub(149,156))) header.typeflag = get_typeflag(block:sub(157,157)) header.linkname = nullterm(block:sub(158,257)) header.magic = block:sub(258,263) header.version = block:sub(264,265) header.uname = nullterm(block:sub(266,297)) header.gname = nullterm(block:sub(298,329)) header.devmajor = octal_to_number(nullterm(block:sub(330,337))) header.devminor = octal_to_number(nullterm(block:sub(338,345))) header.prefix = block:sub(346,500) if header.magic ~= "ustar " and header.magic ~= "ustar\0" then return false, "Invalid header magic "..header.magic end if header.version ~= "00" and header.version ~= " \0" then return false, "Unknown version "..header.version end if not checksum_header(block) == header.chksum then return false, "Failed header checksum" end return header end --[[ -- Extract tar file -- -- @param (string) file name -- @param (string) destination folder -- -- @return (boolean) true, if success -- @return (nil, string) --]] function untar(filename, destdir) assert(type(filename) == "string") assert(type(destdir) == "string") local tar_handle = io.open(filename, "r") if not tar_handle then return nil, "Error opening file " .. filename end local long_name, long_link_name while true do local block repeat block = tar_handle:read(blocksize) until (not block) or checksum_header(block) > 256 if not block then break end local header, err = read_header_block(block) if not header then print(err) end local file_data = tar_handle:read(math.ceil(header.size / blocksize) * blocksize):sub(1,header.size) if header.typeflag == "long name" then long_name = nullterm(file_data) elseif header.typeflag == "long link name" then long_link_name = nullterm(file_data) else if long_name then header.name = long_name long_name = nil end if long_link_name then header.name = long_link_name long_link_name = nil end end --local pathname = dir.path(destdir, header.name) local pathname = destdir .. "/" .. header.name if header.typeflag == "directory" then local ok, err = fs.make_dir(pathname) if not ok then return nil, err end elseif header.typeflag == "file" then --local dirname = dir.dir_name(pathname) --if dirname ~= "" then -- local ok, err = fs.make_dir(dirname) -- if not ok then return nil, err end --end local file_handle = io.open(pathname, "wb") file_handle:write(file_data) file_handle:close() --fs.set_time(pathname, header.mtime) --if fs.chmod then -- fs.chmod(pathname, header.mode) --end end --[[ for k,v in pairs(header) do print("[\""..tostring(k).."\"] = "..(type(v)=="number" and v or "\""..v:gsub("%z", "\\0").."\"")) end --]] end return true end
mit
Python1320/wire
lua/entities/gmod_wire_gpu/cl_gpuvm.lua
3
83679
-------------------------------------------------------------------------------- -- Override virtual machine functions and features -------------------------------------------------------------------------------- local VM = {} surface.CreateFont( "WireGPU_ErrorFont",{ font="Coolvetica", size = 26, weight = 200, antialias = true, additive = false }) function ENT:OverrideVM() -- Store VM calls that will be overriden self.VM.BaseReset = self.VM.Reset -- Add additional VM functionality for k,v in pairs(VM) do if k == "OpcodeTable" then for k2,v2 in pairs(v) do self.VM.OpcodeTable[k2] = v2 end else self.VM[k] = v end end self.VM.ErrorText = {} self.VM.ErrorText[2] = "Program ended unexpectedly" self.VM.ErrorText[3] = "Arithmetic division by zero" self.VM.ErrorText[4] = "Unknown instruction detected" self.VM.ErrorText[5] = "Internal GPU error" self.VM.ErrorText[6] = "Stack violation error" self.VM.ErrorText[7] = "Memory I/O fault" self.VM.ErrorText[13] = "General fault" self.VM.ErrorText[15] = "Address space violation" self.VM.ErrorText[16] = "Pants integrity violation" self.VM.ErrorText[17] = "Frame instruction limit" self.VM.ErrorText[23] = "Error reading string data" self.VM.Interrupt = function(self,interruptNo,interruptParameter,isExternal,cascadeInterrupt) if self.ASYNC == 1 then if self.EntryPoint5 > 0 then self.IP = self.EntryPoint5 self.LADD = interruptParameter self.LINT = interruptNo else -- Shutdown asynchronous thread self.Memory[65528] = 0 end else if self.EntryPoint3 > 0 then self.IP = self.EntryPoint3 self.LADD = interruptParameter self.LINT = interruptNo else if (interruptNo == 2) and (self.XEIP == 0) then self.INTR = 1 return end if self.RenderEnable == 1 then surface.SetTexture(0) surface.SetDrawColor(0,0,0,120) surface.DrawRect(0,0,self.ScreenWidth,self.ScreenHeight) draw.DrawText("Error in the instruction stream","WireGPU_ErrorFont",48,16,Color(255,255,255,255)) draw.DrawText((self.ErrorText[interruptNo] or "Unknown error").." (#"..interruptNo..")","WireGPU_ErrorFont",16,16+32*2,Color(255,255,255,255)) draw.DrawText("Parameter: "..interruptParameter,"WireGPU_ErrorFont",16,16+32*3,Color(255,255,255,255)) draw.DrawText("Address: "..self.XEIP,"WireGPU_ErrorFont",16,16+32*4,Color(255,255,255,255)) local errorPosition = CPULib.Debugger.PositionByPointer[self.XEIP] if errorPosition then local posText = HCOMP:formatPrefix(errorPosition.Line,errorPosition.Col,errorPosition.File) draw.DrawText("Debugging data present (may be invalid):","WireGPU_ErrorFont",16,16+32*6,Color(255,255,255,255)) draw.DrawText("Error at "..posText,"WireGPU_ErrorFont",16,16+32*7,Color(255,255,255,255)) draw.DrawText("Line: <not available>","WireGPU_ErrorFont",16,16+32*9,Color(255,255,255,255)) end end self.INTR = 1 end end end -- Override ports self.VM.WritePort = function(VM,Port,Value) VM:WriteCell(63488+Port,Value) end self.VM.ReadPort = function(VM,Port) return VM:ReadCell(63488+Port) end -- Override writecell self.VM.BaseWriteCell = self.VM.WriteCell self.VM.WriteCell = function(VM,Address,Value) VM:BaseWriteCell(Address,Value) if (Address >= 65536) and (Address <= 131071) then if VM.MemBusCount < 8 then VM.MemBusCount = VM.MemBusCount + 1 VM.MemBusBuffer[Address] = Value end elseif Address == 65534 then VM:HardReset() elseif Address == 65530 then VM.ROM = {} elseif Address == 65529 then VM.AsyncState = {} end end -- Add internal registers self.VM.InternalRegister[128] = "EntryPoint0" self.VM.InternalRegister[129] = "EntryPoint1" self.VM.InternalRegister[130] = "EntryPoint2" self.VM.InternalRegister[131] = "EntryPoint3" self.VM.InternalRegister[132] = "EntryPoint4" self.VM.InternalRegister[133] = "EntryPoint5" self.VM.InternalRegister[134] = "EntryPoint6" self.VM.InternalRegister[135] = "EntryPoint7" self.VM.InternalRegister[136] = "CoordinatePipe" self.VM.InternalRegister[137] = "VertexPipe" self.VM.InternalRegister[138] = "VertexBufZSort" self.VM.InternalRegister[139] = "VertexLighting" self.VM.InternalRegister[140] = "VertexBufEnabled" self.VM.InternalRegister[141] = "VertexCulling" self.VM.InternalRegister[142] = "DistanceCulling" self.VM.InternalRegister[143] = "Font" self.VM.InternalRegister[144] = "FontSize" self.VM.InternalRegister[145] = "WordWrapMode" self.VM.InternalRegister[146] = "ASYNC" self.VM.InternalRegister[147] = "INIT" -- Remove internal registers self.VM.InternalRegister[24] = nil --IDTR self.VM.InternalRegister[32] = nil --IF self.VM.InternalRegister[33] = nil --PF self.VM.InternalRegister[34] = nil --EF self.VM.InternalRegister[45] = nil --BusLock self.VM.InternalRegister[46] = nil --IDLE self.VM.InternalRegister[47] = nil --INTR self.VM.InternalRegister[52] = nil --NIDT -- Remove some instructions self.VM.OperandCount[16] = nil --RD self.VM.OperandCount[17] = nil --WD self.VM.OperandCount[28] = nil --SPG self.VM.OperandCount[29] = nil --CPG self.VM.OperandCount[37] = nil --HALT self.VM.OperandCount[41] = nil --IRET self.VM.OperandCount[42] = nil --STI self.VM.OperandCount[43] = nil --CLI self.VM.OperandCount[44] = nil --STP self.VM.OperandCount[45] = nil --CLP self.VM.OperandCount[46] = nil --STD self.VM.OperandCount[48] = nil --STEF self.VM.OperandCount[49] = nil --CLEF self.VM.OperandCount[70] = nil --EXTINT self.VM.OperandCount[95] = nil --ERPG self.VM.OperandCount[96] = nil --WRPG self.VM.OperandCount[97] = nil --RDPG self.VM.OperandCount[99] = nil --LIDTR self.VM.OperandCount[100] = nil --STATESTORE self.VM.OperandCount[109] = nil --STATERESTORE self.VM.OperandCount[110] = nil --EXTRET self.VM.OperandCount[113] = nil --RLADD self.VM.OperandCount[116] = nil --STD2 self.VM.OperandCount[118] = nil --STM self.VM.OperandCount[119] = nil --CLM self.VM.OperandCount[122] = nil --SPP self.VM.OperandCount[123] = nil --CPP self.VM.OperandCount[124] = nil --SRL self.VM.OperandCount[125] = nil --GRL self.VM.OperandCount[131] = nil --SMAP self.VM.OperandCount[132] = nil --GMAP -- Add some extra lookups self.VM.FontName = {} self.VM.FontName[0] = "Lucida Console" self.VM.FontName[1] = "Courier New" self.VM.FontName[2] = "Trebuchet" self.VM.FontName[3] = "Arial" self.VM.FontName[4] = "Times New Roman" self.VM.FontName[5] = "Coolvetica" self.VM.FontName[6] = "Akbar" self.VM.FontName[7] = "csd" -- Add text layouter self.VM.Layouter = MakeTextScreenLayouter() self.VM.Entity = self end -------------------------------------------------------------------------------- -- Switches to a font, creating it if it does not exist -------------------------------------------------------------------------------- local fontcache = {} function VM:SetFont() local name, size = self.FontName[self.Font], self.FontSize if not fontcache[name] or not fontcache[name][size] then if not fontcache[name] then fontcache[name] = {} end surface.CreateFont("WireGPU_"..name..size, { font = name, size = size, weight = 800, antialias = true, additive = false, }) fontcache[name][size] = true end surface.SetFont("WireGPU_"..name..size) end -------------------------------------------------------------------------------- -- Reset state each GPU frame -------------------------------------------------------------------------------- function VM:Reset() -- Reset VM self.IP = 0 -- Instruction pointer self.EAX = 0 -- General purpose registers self.EBX = 0 self.ECX = 0 self.EDX = 0 self.ESI = 0 self.EDI = 0 self.ESP = 32767 self.EBP = 0 self.CS = 0 -- Segment pointer registers self.SS = 0 self.DS = 0 self.ES = 0 self.GS = 0 self.FS = 0 self.KS = 0 self.LS = 0 -- Extended registers for reg=0,31 do self["R"..reg] = 0 end self.ESZ = 32768 -- Stack size register self.CMPR = 0 -- Compare register self.XEIP = 0 -- Current instruction address register self.LADD = 0 -- Last interrupt parameter self.LINT = 0 -- Last interrupt number self.BPREC = 48 -- Binary precision for integer emulation mode (default: 48) self.IPREC = 48 -- Integer precision (48 - floating point mode, 8, 16, 32, 64 - integer mode) self.VMODE = 2 -- Vector mode (2D, 3D) self.INTR = 0 -- Handling an interrupt self.BlockStart = 0 -- Start of the block self.BlockSize = 0 -- Size of the block -- Reset internal GPU registers -- [131072]..[2097151] - Extended GPU memory (2MB GPU) -- [131072]..[1048576] - Extended GPU memory (1MB GPU) -- [131072]..[524287] - Extended GPU memory (512K GPU) -- [131072]..[262143] - Extended GPU memory (256K GPU) -- No extended memory (128K GPU) -- [65536]..[131071] - MemBus mapped memory (read/write) -- No extra memory beyond 65536 (64K GPU) -- -- Hardware control registers: -- [65535] - CLK -- [65534] - RESET -- [65533] - HARDWARE CLEAR -- [65532] - Vertex mode (render vertex instead of RT) -- [65531] - HALT -- [65530] - RAM_RESET -- [65529] - Async thread reset -- [65528] - Async thread clk -- [65527] - Async thread frequency -- [65526] - Player index (0 to 31) -- -- Image control: -- [65525] - Horizontal image scale -- [65524] - Vertical image scale -- [65523] - Hardware scale -- [65522] - Rotation (0 - 0*, 1 - 90*, 2 - 180*, 3 - 270*) -- [65521] - Sprite/texture size -- [65520] - Pointer to texture data -- [65519] - Size of texture data -- [65518] - Raster quality -- [65517] - Texture buffer (1: sprite buffer, 0: front buffer) -- -- Vertex pipe controls: -- [65515] - Image width (800) -- [65514] - Image height (600) -- [65513] - Real screen ratio -- [65512] - Parameter list address (for dwritefmt) -- -- Cursor control: -- [65505] - Cursor X (0..1) -- [65504] - Cursor Y (0..1) -- [65503] - Cursor visible -- [65502] - Cursor buttons (bits) -- -- Brightness control: -- [65495] - Brightness W -- [65494] - Brightness R -- [65493] - Brightness G -- [65492] - Brightness B -- [65491] - Contrast W -- [65490] - Contrast R -- [65489] - Contrast G -- [65488] - Contrast B -- -- Rendering settings -- [65485] - Circle quality (3..128) -- [65484] - Offset Point X -- [65483] - Offset Point Y -- [65482] - Rotation (rad) -- [65481] - Scale -- [65480] - Center point X -- [65479] - Center point Y -- [65478] - Circle start (rad) -- [65477] - Circle end (rad) -- [65476] - Line width (1) -- [65475] - Scale X -- [65474] - Scale Y -- [65473] - Font horizontal align -- [65472] - ZOffset -- [65471] - Font vertical align -- [65470] - Culling distance -- [65469] - Culling mode (0: front, 1: back) -- [65468] - Single-side lighting (1: front, -1: back) -- [65467] - Memory offset of vertex data (non-zero means poly ops take indexes into this array) -- [65466] - Texture rotation (rad) -- [65465] - Texture scale -- [65464] - Texture center point U -- [65463] - Texture center point V -- [65462] - Texture offset U -- [65461] - Texture offset V -- -- Misc: -- [64512] - Last register -- [63488]..[64511] - External ports self.Memory[65535] = 1 self.Memory[65534] = 0 --self.Memory[65533] = 1 (value persists over reset) --self.Memory[65532] = 0 --self.Memory[65531] = 0 (value persists over reset) --self.Memory[65530] = 0 --self.Memory[65529] = 0 --self.Memory[65528] = 0 --self.Memory[65527] = 0 self.Memory[65526] = (LocalPlayer():UserID() % 32) ---------------------- self.Memory[65525] = 1 self.Memory[65524] = 1 self.Memory[65523] = 0 self.Memory[65522] = 0 self.Memory[65521] = 512 self.Memory[65520] = 0 self.Memory[65519] = 0 self.Memory[65518] = 0 self.Memory[65517] = 1 ---------------------- self.Memory[65515] = 800 self.Memory[65514] = 600 --self.Memory[65513] = 0 (set elsewhere) self.Memory[65512] = 0 ---------------------- --self.Memory[65505] = 0 (set elsewhere) --self.Memory[65504] = 0 (set elsewhere) self.Memory[65503] = 0 --self.Memory[65502] = 0 ---------------------- self.Memory[65495] = 1 self.Memory[65494] = 1 self.Memory[65493] = 1 self.Memory[65492] = 1 self.Memory[65491] = 0 self.Memory[65490] = 0 self.Memory[65489] = 0 self.Memory[65488] = 0 ---------------------- self.Memory[65485] = 32 self.Memory[65484] = 0 self.Memory[65483] = 0 self.Memory[65482] = 0 self.Memory[65481] = 1 self.Memory[65480] = 0 self.Memory[65479] = 0 self.Memory[65478] = 0 self.Memory[65477] = 6.28318530717 self.Memory[65476] = 1 self.Memory[65475] = 1 self.Memory[65474] = 1 self.Memory[65473] = 0 self.Memory[65472] = 0 self.Memory[65471] = 0 self.Memory[65470] = 0 self.Memory[65469] = 0 self.Memory[65468] = 0 self.Memory[65467] = 0 self.Memory[65466] = 0 self.Memory[65465] = 1 self.Memory[65464] = 0.5 self.Memory[65463] = 0.5 self.Memory[65462] = 0 self.Memory[65461] = 0 -- Coordinate pipe -- 0 - direct (0..512 or 0..1024 range) -- 1 - mapped to screen -- 2 - mapped to 0..1 range -- 3 - mapped to -1..1 range self.CoordinatePipe = 0 -- Vertex pipes: -- 0 - XY mapping -- 1 - YZ mapping -- 2 - XZ mapping -- 3 - XYZ projective mapping -- 4 - XY mapping + matrix -- 5 - XYZ projective mapping + matrix self.VertexPipe = 0 -- Flags that can be ddisable/ddenable-d -- 0 VERTEX_ZSORT Enable or disable ZSorting in vertex buffer (sorted on flush) self.VertexBufZSort = 0 -- 1 VERTEX_LIGHTING Enable or disable vertex lighting self.VertexLighting = 0 -- 2 VERTEX_BUFFER Enable or disable vertex buffer self.VertexBufEnabled = 0 -- 3 VERTEX_CULLING Enable or disable culling on faces self.VertexCulling = 0 -- 4 VERTEX_DCULLING Enable or disable distance culling self.DistanceCulling = 0 -- 5 VERTEX_TEXTURING Enable texturing from sprite buffer self.VertexTexturing = 0 -- Font layouter related self.Font = 0 self.FontSize = 12 self.TextBox = { x = 512, y = 512, z = 0, w = 0 } self.WordWrapMode = 0 -- Current color self.Color = {x = 0, y = 0, z = 0, w = 255} self.Material = nil self.Texture = 0 -- Model transform matrix self.ModelMatrix = self.ModelMatrix or {} self.ModelMatrix[0] = 1 self.ModelMatrix[1] = 0 self.ModelMatrix[2] = 0 self.ModelMatrix[3] = 0 self.ModelMatrix[4] = 0 self.ModelMatrix[5] = 1 self.ModelMatrix[6] = 0 self.ModelMatrix[7] = 0 self.ModelMatrix[8] = 0 self.ModelMatrix[9] = 0 self.ModelMatrix[10] = 1 self.ModelMatrix[11] = 0 self.ModelMatrix[12] = 0 self.ModelMatrix[13] = 0 self.ModelMatrix[14] = 0 self.ModelMatrix[15] = 1 --View transform matrix self.ProjectionMatrix = self.ProjectionMatrix or {} self.ProjectionMatrix[0] = 1 self.ProjectionMatrix[1] = 0 self.ProjectionMatrix[2] = 0 self.ProjectionMatrix[3] = 0 self.ProjectionMatrix[4] = 0 self.ProjectionMatrix[5] = 1 self.ProjectionMatrix[6] = 0 self.ProjectionMatrix[7] = 0 self.ProjectionMatrix[8] = 0 self.ProjectionMatrix[9] = 0 self.ProjectionMatrix[10] = 1 self.ProjectionMatrix[11] = 0 self.ProjectionMatrix[12] = 0 self.ProjectionMatrix[13] = 0 self.ProjectionMatrix[14] = 0 self.ProjectionMatrix[15] = 1 -- Reset buffers: self.StringCache = {} self.VertexBuffer = {} self.Lights = {} end -------------------------------------------------------------------------------- -- Save asynchronous thread state -------------------------------------------------------------------------------- local asyncPreservedVariables = { "IP","EAX","EBX","ECX","EDX","ESI","EDI","ESP","EBP","CS","SS","DS","ES","GS", "FS","KS","LS","ESZ","CMPR","XEIP","LADD","LINT","BPREC","IPREC","VMODE","INTR", "BlockStart","BlockSize","CoordinatePipe","VertexPipe","VertexBufZSort","VertexLighting", "VertexBufEnabled","VertexCulling","DistanceCulling","VertexTexturing","Font", "FontSize","WordWrapMode","Material","Texture","VertexBuffer","Lights", } for reg=0,31 do table.insert(asyncPreservedVariables,"R"..reg) end local asyncPreservedMemory = { 65525,65524,65523,65522,65521,65520,65519,65518,65517, 65515,65514,65512,65503,65495,65494,65493,65492,65491, 65490,65489,65488,65485,65484,65483,65482,65481,65480, 65479,65478,65477,65476,65475,65474,65473,65472,65471, 65470,65469,65468,65467,65466,65465,65464,65463,65462, 65461 } function VM:SaveAsyncThread_Util() for _,var in pairs(asyncPreservedVariables) do self.AsyncState[var] = self[var] end for _,mem in pairs(asyncPreservedMemory) do self.AsyncState[mem] = self.Memory[mem] end self.AsyncState.TextBox = { x = self.TextBox.x, y = self.TextBox.y, z = self.TextBox.z, w = self.TextBox.w } self.AsyncState.Color = { x = self.Color.x, y = self.Color.y, z = self.Color.z, w = self.Color.w } self.AsyncState.ModelMatrix = {} self.AsyncState.ProjectionMatrix = {} for k,v in pairs(self.ModelMatrix) do self.AsyncState.ModelMatrix[k] = v end for k,v in pairs(self.ProjectionMatrix) do self.AsyncState.ProjectionMatrix[k] = v end end function VM:SaveAsyncThread() if not self.AsyncState then self.AsyncState = {} self:Reset() self:SaveAsyncThread_Util() self.AsyncState.IP = self.EntryPoint4 return end self:SaveAsyncThread_Util() end -------------------------------------------------------------------------------- -- Restore asynchronous thread state -------------------------------------------------------------------------------- function VM:RestoreAsyncThread_Util() for _,var in pairs(asyncPreservedVariables) do self[var] = self.AsyncState[var] end for _,mem in pairs(asyncPreservedMemory) do self.Memory[mem] = self.AsyncState[mem] end self.TextBox = { x = self.AsyncState.TextBox.x, y = self.AsyncState.TextBox.y, z = self.AsyncState.TextBox.z, w = self.AsyncState.TextBox.w } self.Color = { x = self.AsyncState.Color.x, y = self.AsyncState.Color.y, z = self.AsyncState.Color.z, w = self.AsyncState.Color.w } self.ModelMatrix = {} self.ProjectionMatrix = {} for k,v in pairs(self.AsyncState.ModelMatrix) do self.ModelMatrix[k] = v end for k,v in pairs(self.AsyncState.ProjectionMatrix) do self.ProjectionMatrix[k] = v end end function VM:RestoreAsyncThread() if not self.AsyncState then self.AsyncState = {} self:Reset() self:SaveAsyncThread_Util() self.AsyncState.IP = self.EntryPoint4 end self:RestoreAsyncThread_Util() end -------------------------------------------------------------------------------- -- Reset GPU state and clear all persisting registers -------------------------------------------------------------------------------- function VM:HardReset() self:Reset() -- Reset registers that usually persist over normal reset self.Memory[65533] = 1 self.Memory[65532] = 0 self.Memory[65531] = 0 self.Memory[65535] = 1 self.Memory[65529] = 0 self.Memory[65528] = 0 self.Memory[65527] = 60000 self.Memory[65502] = 0 -- Entrypoints to special calls -- 0 DRAW Called when screen is being drawn -- 1 INIT Called when screen is hard reset -- 2 USE Called when screen is used -- 3 ERROR Called when GPU error has occured -- 4 ASYNC Asynchronous thread entrypoint self.EntryPoint0 = 0 self.EntryPoint1 = self.EntryPoint1 or 0 self.EntryPoint2 = 0 self.EntryPoint3 = 0 self.EntryPoint4 = 0 self.EntryPoint5 = 0 self.EntryPoint6 = 0 self.EntryPoint7 = 0 -- Is running asynchronous thread self.ASYNC = 0 -- Has initialized already self.INIT = 0 end -------------------------------------------------------------------------------- -- Compute UV -------------------------------------------------------------------------------- function VM:ComputeTextureUV(vertex,u,v) local texturesOnSide = math.floor(512/self.Memory[65521]) local textureX = (1/texturesOnSide) * (self.Texture % texturesOnSide) local textureY = (1/texturesOnSide) * math.floor(self.Texture / texturesOnSide) local uvStep = (1/512) local du,dv = u,v if (self.Memory[65466] ~= 0) or (self.Memory[65465] ~= 1) then local cu,cv = self.Memory[65464],self.Memory[65463] local tu,tv = u-cu,v-cv local angle,scale = self.Memory[65466],self.Memory[65465] du = scale*(tu*math.cos(angle) - tv*math.sin(angle)) + cu + self.Memory[65462] dv = scale*(tv*math.cos(angle) + tu*math.sin(angle)) + cv + self.Memory[65461] end vertex.u = textureX+(1/texturesOnSide)*du*(1-2*uvStep)+uvStep vertex.v = textureY+(1/texturesOnSide)*dv*(1-2*uvStep)+uvStep end -------------------------------------------------------------------------------- -- Transform coordinates through coordinate pipe -------------------------------------------------------------------------------- function VM:CoordinateTransform(x,y) -- Transformed coordinates local tX = x local tY = y -- Is rotation/scale register set if (self.Memory[65482] ~= 0) or (self.Memory[65481] ~= 1) then -- Centerpoint of rotation local cX = self.Memory[65480] local cY = self.Memory[65479] -- Calculate normalized direction to rotated point local vD = math.sqrt((x-cX)^2+(y-cY)^2) + 1e-7 local vX = x / vD local vY = y / vD -- Calculate angle of rotation for the point local A if self.RAMSize == 65536 then A = math.atan2(vX,vY) -- Old GPU else A = math.atan2(vY,vX) end -- Rotate point by a certain angle A = A + self.Memory[65482] -- Generate new coordinates tX = cX + math.cos(A) * vD * self.Memory[65481] * self.Memory[65475] tY = cY + math.sin(A) * vD * self.Memory[65481] * self.Memory[65474] end -- Apply DMOVE offset tX = tX + self.Memory[65484] tY = tY + self.Memory[65483] if self.CoordinatePipe == 0 then tX = self.ScreenWidth*(tX/512) tY = self.ScreenHeight*(tY/512) elseif self.CoordinatePipe == 1 then tX = self.ScreenWidth*tX/self.Memory[65515] tY = self.ScreenHeight*tY/self.Memory[65514] elseif self.CoordinatePipe == 2 then tX = tX*self.ScreenWidth tY = tY*self.ScreenHeight elseif self.CoordinatePipe == 3 then tX = 0.5*self.ScreenWidth*(1+tX) tY = 0.5*self.ScreenHeight*(1+tY) elseif self.CoordinatePipe == 4 then tX = 0.5*self.ScreenWidth+tX tY = 0.5*self.ScreenHeight+tY end -- Apply raster quality transform local transformedCoordinate = { x = tX, y = tY} local rasterQuality = self.Memory[65518] if rasterQuality > 0 then local W,H = self.ScreenWidth/2,self.ScreenHeight/2 transformedCoordinate.x = (tX-W)*(1-(rasterQuality/W))+W transformedCoordinate.y = (tY-H)*(1-(rasterQuality/H))+H end return transformedCoordinate end -------------------------------------------------------------------------------- -- Transform coordinate via vertex pipe -------------------------------------------------------------------------------- function VM:VertexTransform(inVertex,toScreen) -- Make sure the coordinate is complete local vertex = inVertex or {} vertex.x = vertex.x or 0 vertex.y = vertex.y or 0 vertex.z = vertex.z or 0 vertex.w = vertex.w or 1 vertex.u = vertex.u or 0 vertex.v = vertex.v or 0 -- Create the resulting coordinate local resultVertex = { x = vertex.x, y = vertex.y, z = vertex.z, w = vertex.w, u = vertex.u, v = vertex.v } -- Transformed world coordinates local worldVertex = { x = 0, y = 0, z = 0, w = 1, u = vertex.u, v = vertex.v } -- Add Z offset to input coordinate vertex.z = vertex.z + self.Memory[65472] -- Do the transformation if self.VertexPipe == 0 then -- XY plane local resultCoordinate = self:CoordinateTransform(vertex.x,vertex.y) resultVertex.x = resultCoordinate.x resultVertex.y = resultCoordinate.y elseif self.VertexPipe == 1 then -- YZ plane local resultCoordinate = self:CoordinateTransform(vertex.y,vertex.z) resultVertex.x = resultCoordinate.x resultVertex.y = resultCoordinate.y elseif self.VertexPipe == 2 then -- XZ plane local resultCoordinate = self:CoordinateTransform(vertex.x,vertex.z) resultVertex.x = resultCoordinate.x resultVertex.y = resultCoordinate.y elseif self.VertexPipe == 3 then -- Perspective transform local tX = (vertex.x + self.Memory[65512])/(vertex.z + self.Memory[65512]) local tY = (vertex.y + self.Memory[65512])/(vertex.z + self.Memory[65512]) local resultCoordinate = self:CoordinateTransform(tX,tY) resultVertex.x = resultCoordinate.x resultVertex.y = resultCoordinate.y elseif self.VertexPipe == 4 then -- 2D matrix local tX = self.ModelMatrix[0*4+0] * vertex.x + self.ModelMatrix[0*4+1] * vertex.y + self.ModelMatrix[0*4+2] * 0 + self.ModelMatrix[0*4+3] * 1 local tY = self.ModelMatrix[1*4+0] * vertex.x + self.ModelMatrix[1*4+1] * vertex.y + self.ModelMatrix[1*4+2] * 0 + self.ModelMatrix[1*4+3] * 1 local resultCoordinate = self:CoordinateTransform(tX,tY) resultVertex.x = resultCoordinate.x resultVertex.y = resultCoordinate.y elseif self.VertexPipe == 5 then -- 3D matrix local world if not toScreen then -- Transform into world coordinates world = {} for i=0,3 do world[i] = self.ModelMatrix[i*4+0] * vertex.x + self.ModelMatrix[i*4+1] * vertex.y + self.ModelMatrix[i*4+2] * vertex.z + self.ModelMatrix[i*4+3] * vertex.w end worldVertex.x = world[0] worldVertex.y = world[1] worldVertex.z = world[2] worldVertex.w = world[3] else worldVertex = vertex world = {} world[0] = vertex.x world[1] = vertex.y world[2] = vertex.z world[3] = vertex.w end -- Transform into screen coordinates local screen = {} for i=0,3 do screen[i] = self.ProjectionMatrix[i*4+0] * world[0] + self.ProjectionMatrix[i*4+1] * world[1] + self.ProjectionMatrix[i*4+2] * world[2] + self.ProjectionMatrix[i*4+3] * world[3] end -- Project to screen if screen[3] == 0 then screen[3] = 1 end for i=0,3 do screen[i] = screen[i] / screen[3] end -- Transform coordinates local resultCoordinate = self:CoordinateTransform(screen[0],screen[1]) resultVertex.x = resultCoordinate.x resultVertex.y = resultCoordinate.y resultVertex.z = screen[2] resultVertex.w = screen[3] end return resultVertex,worldVertex end -------------------------------------------------------------------------------- -- Transform color -------------------------------------------------------------------------------- function VM:ColorTransform(color) color.x = color.x * self.Memory[65495] * self.Memory[65494] color.y = color.y * self.Memory[65495] * self.Memory[65493] color.z = color.z * self.Memory[65495] * self.Memory[65492] return color end -------------------------------------------------------------------------------- -- Read a string by offset -------------------------------------------------------------------------------- function VM:ReadString(address) local charString = "" local charCount = 0 local currentChar = 255 while currentChar ~= 0 do currentChar = self:ReadCell(address + charCount) if currentChar and currentChar < 255 then charString = charString .. string.char(currentChar) else if currentChar ~= 0 then self:Interrupt(23,currentChar) return "" end end charCount = charCount + 1 if charCount > 8192 then self:Interrupt(23,0) return "" end end return charString end -------------------------------------------------------------------------------- -- Get text size (by sk89q) -------------------------------------------------------------------------------- function VM:TextSize(text) self:SetFont() if self.WordWrapMode == 1 then return self.Layouter:GetTextSize(text, self.TextBox.x, self.TextBox.y) else return surface.GetTextSize(text) end end -------------------------------------------------------------------------------- -- Output font to screen (word wrap update by sk89q) -------------------------------------------------------------------------------- function VM:FontWrite(posaddr,text) -- Read position local vertex = {} vertex.x = self:ReadCell(posaddr+0) vertex.y = self:ReadCell(posaddr+1) vertex = self:VertexTransform(vertex) self:SetFont() -- Draw text if self.RenderEnable == 1 then if self.WordWrapMode == 1 then surface.SetTextColor(self.Color.x,self.Color.y,self.Color.z,self.Color.w) self.Layouter:DrawText(tostring(text), vertex.x, vertex.y, self.TextBox.x, self.TextBox.y, self.Memory[65473], self.Memory[65471]) else draw.DrawText(text,"WireGPU_"..self.FontName[self.Font]..self.FontSize, vertex.x,vertex.y,Color(self.Color.x,self.Color.y,self.Color.z,self.Color.w), self.Memory[65473]) end end end -------------------------------------------------------------------------------- -- Draw line between two points -------------------------------------------------------------------------------- function VM:DrawLine(point1,point2,drawNow) -- Line centerpoint local cX = (point1.x + point2.x) / 2 local cY = (point1.y + point2.y) / 2 -- Line width local W = self.Memory[65476] -- Line length and angle local L = math.sqrt((point1.x-point2.x)^2+(point1.y-point2.y)^2) + 1e-7 local dX = (point2.x-point1.x) / L local dY = (point2.y-point1.y) / L local A = math.atan2(dY,dX) local dA = math.atan2(W,L/2) -- Generate vertexes local vertexBuffer = { {}, {}, {}, {} } vertexBuffer[1].x = cX - 0.5 * L * math.cos(A-dA) vertexBuffer[1].y = cY - 0.5 * L * math.sin(A-dA) vertexBuffer[1].u = 0 vertexBuffer[1].v = 0 vertexBuffer[2].x = cX + 0.5 * L * math.cos(A+dA) vertexBuffer[2].y = cY + 0.5 * L * math.sin(A+dA) vertexBuffer[2].u = 1 vertexBuffer[2].v = 1 vertexBuffer[3].x = cX + 0.5 * L * math.cos(A-dA) vertexBuffer[3].y = cY + 0.5 * L * math.sin(A-dA) vertexBuffer[3].u = 0 vertexBuffer[3].v = 1 vertexBuffer[4].x = cX - 0.5 * L * math.cos(A+dA) vertexBuffer[4].y = cY - 0.5 * L * math.sin(A+dA) vertexBuffer[4].u = 1 vertexBuffer[4].v = 0 -- Draw vertexes if drawNow then surface.DrawPoly(vertexBuffer) else self:DrawToBuffer(vertexBuffer) end end -------------------------------------------------------------------------------- -- Flush vertex buffer. Based on code by Nick -------------------------------------------------------------------------------- local function triangleSortFunction(triA,triB) local z1 = (triA.vertex[1].z + triA.vertex[2].z + triA.vertex[3].z) / 3 local z2 = (triB.vertex[1].z + triB.vertex[2].z + triB.vertex[3].z) / 3 return z1 < z2 end function VM:FlushBuffer() -- Projected vertex data: -- vertexData.transformedVertex [SCREEN SPACE] -- Vertex data in world space: -- vertexData.vertex [WORLD SPACE] -- Triangle color: -- vertexData.color -- -- Light positions: [WORLD SPACE] if self.VertexBufEnabled == 1 then -- Do not flush color-only buffer if (#self.VertexBuffer == 1) and (not self.VertexBuffer[1].vertex) then self.VertexBuffer = {} return end -- Sort triangles by distance if self.VertexBufZSort == 1 then table.sort(self.VertexBuffer,triangleSortFunction) end -- Render each triangle for vertexID,vertexData in ipairs(self.VertexBuffer) do -- Should this polygon be culled local cullVertex = false -- Generate output local resultTriangle local resultTriangle2 local resultColor = { x = vertexData.color.x, y = vertexData.color.y, z = vertexData.color.z, w = vertexData.color.w, } local resultMaterial = vertexData.material if vertexData.rt then WireGPU_matBuffer:SetTexture("$basetexture", vertexData.rt) resultMaterial = WireGPU_matBuffer end if vertexData.vertex then resultTriangle = {} resultTriangle[1] = {} resultTriangle[1].x = vertexData.transformedVertex[1].x resultTriangle[1].y = vertexData.transformedVertex[1].y resultTriangle[1].u = vertexData.transformedVertex[1].u resultTriangle[1].v = vertexData.transformedVertex[1].v resultTriangle[2] = {} resultTriangle[2].x = vertexData.transformedVertex[2].x resultTriangle[2].y = vertexData.transformedVertex[2].y resultTriangle[2].u = vertexData.transformedVertex[2].u resultTriangle[2].v = vertexData.transformedVertex[2].v resultTriangle[3] = {} resultTriangle[3].x = vertexData.transformedVertex[3].x resultTriangle[3].y = vertexData.transformedVertex[3].y resultTriangle[3].u = vertexData.transformedVertex[3].u resultTriangle[3].v = vertexData.transformedVertex[3].v -- Additional processing if (self.VertexCulling == 1) or (self.VertexLighting == 1) then -- Get vertices (world space) local v1 = vertexData.vertex[1] local v2 = vertexData.vertex[2] local v3 = vertexData.vertex[3] -- Compute barycenter (world space) local vpos = { x = (v1.x+v2.x) * 1/3, y = (v1.y+v2.y) * 1/3, z = (v1.z+v2.z) * 1/3 } -- Compute normal (world space) local x1 = v2.x - v1.x local y1 = v2.y - v1.y local z1 = v2.z - v1.z local x2 = v3.x - v1.x local y2 = v3.y - v1.y local z2 = v3.z - v1.z local normal = { x = y1*z2-y2*z1, y = z1*x2-z2*x1, z = x1*y2-x2*y1 } -- Normalize it local d = (normal.x^2 + normal.y^2 + normal.z^2)^(1/2)+1e-7 normal.x = normal.x / d normal.y = normal.y / d normal.z = normal.z / d -- Perform culling if self.VertexCulling == 1 then if self.Memory[65469] == 0 then cullVertex = (normal.x*v1.x + normal.y*v1.y + normal.z*v1.z) <= 0 else cullVertex = (normal.x*v1.x + normal.y*v1.y + normal.z*v1.z) >= 0 end end -- Perform vertex lighting if (self.VertexLighting == 1) and (not cullVertex) then -- Extra color generated by lights local lightColor = { x = 0, y = 0, z = 0, w = 255} -- Apply all lights (world space calculations) for i=0,7 do if self.Lights[i] then local lightPosition = { x = self.Lights[i].Position.x, y = self.Lights[i].Position.y, z = self.Lights[i].Position.z } local lightLength = (lightPosition.x^2+lightPosition.y^2+lightPosition.z^2)^(1/2)+1e-7 lightPosition.x = lightPosition.x / lightLength lightPosition.y = lightPosition.y / lightLength lightPosition.z = lightPosition.z / lightLength local lightDot if self.Memory[65468] == 0 then lightDot = math.abs(lightPosition.x*normal.x + lightPosition.y*normal.y + lightPosition.z*normal.z)*self.Lights[i].Color.w else lightDot = math.max(0,self.Memory[65468]*(lightPosition.x*normal.x + lightPosition.y*normal.y + lightPosition.z*normal.z))*self.Lights[i].Color.w end lightColor.x = math.min(lightColor.x + self.Lights[i].Color.x * lightDot,255) lightColor.y = math.min(lightColor.y + self.Lights[i].Color.y * lightDot,255) lightColor.z = math.min(lightColor.z + self.Lights[i].Color.z * lightDot,255) end end -- Modulate object color with light color resultColor.x = (1/255) * resultColor.x * lightColor.x resultColor.y = (1/255) * resultColor.y * lightColor.y resultColor.z = (1/255) * resultColor.z * lightColor.z end -- Perform distance culling if (self.DistanceCulling == 1) and (not cullVertex) then local Infront = {} local Behind = {} local frontCullDistance = self.Memory[65470] local K = -frontCullDistance -- Generate list of vertices which go behind the camera if v1.z - K >= 0 then Behind [#Behind + 1] = v1 else Infront[#Infront + 1] = v1 end if v2.z - K >= 0 then Behind [#Behind + 1] = v2 else Infront[#Infront + 1] = v2 end if v3.z - K >= 0 then Behind [#Behind + 1] = v3 else Infront[#Infront + 1] = v3 end if #Behind == 1 then local Point1 = Infront[1] local Point2 = Infront[2] local Point3 = Behind[1] local Point4 = {} local D1 = { x = Point3.x - Point1.x, y = Point3.y - Point1.y, z = Point3.z - Point1.z, } local D2 = { x = Point3.x - Point2.x, y = Point3.y - Point2.y, z = Point3.z - Point2.z, } local T1 = D1.z local T2 = D2.z if (T1 ~= 0) and (T2 ~= 0) then local S1 = (K - Point1.z)/T1 local S2 = (K - Point2.z)/T2 -- Calculate the new UV values Point4.u = Point2.u + S2 * (Point3.u - Point2.u) Point4.v = Point2.v + S2 * (Point3.v - Point2.v) Point3.u = Point1.u + S1 * (Point3.u - Point1.u) Point3.v = Point1.v + S1 * (Point3.v - Point1.v) -- Calculate new coordinates Point3.x = Point1.x + S1 * D1.x Point3.y = Point1.y + S1 * D1.y Point3.z = Point1.z + S1 * D1.z Point4.x = Point2.x + S2 * D2.x Point4.y = Point2.y + S2 * D2.y Point4.z = Point2.z + S2 * D2.z -- Transform the points (from world space to screen space) local P1t = self:VertexTransform(Point1,true) local P2t = self:VertexTransform(Point2,true) local P3t = self:VertexTransform(Point3,true) local P4t = self:VertexTransform(Point4,true) resultTriangle[1] = P1t resultTriangle[2] = P2t resultTriangle[3] = P3t resultTriangle2 = {} resultTriangle2[1] = P2t resultTriangle2[2] = P3t resultTriangle2[3] = P4t end elseif #Behind == 2 then local Point1 = Infront[1] local Point2 = Behind[1] local Point3 = Behind[2] local D1 = { x = Point2.x - Point1.x, y = Point2.y - Point1.y, z = Point2.z - Point1.z, } local D2 = { x = Point3.x - Point1.x, y = Point3.y - Point1.y, z = Point3.z - Point1.z, } local T1 = D1.z local T2 = D2.z if (T1 ~= 0) and (T2 ~= 0) then local S1 = (K - Point1.z)/T1 local S2 = (K - Point1.z)/T2 --Calculate the new UV values Point2.u = Point1.u + S1 * (Point2.u - Point1.u) Point2.v = Point1.v + S1 * (Point2.v - Point1.v) Point3.u = Point1.u + S2 * (Point3.u - Point1.u) Point3.v = Point1.v + S2 * (Point3.v - Point1.v) -- Calculate new coordinates Point2.x = Point1.x + S1 * D1.x Point2.y = Point1.y + S1 * D1.y Point2.z = Point1.z + S1 * D1.z Point3.x = Point1.x + S2 * D2.x Point3.y = Point1.y + S2 * D2.y Point3.z = Point1.z + S2 * D2.z -- Transform the points (from world space to screen space) local P1t = self:VertexTransform(Point1,true) local P2t = self:VertexTransform(Point2,true) local P3t = self:VertexTransform(Point3,true) resultTriangle[1] = P1t resultTriangle[2] = P2t resultTriangle[3] = P3t end elseif #Behind == 3 then cullVertex = true end end end -- End additional processing end if not cullVertex then -- self:FixDrawDirection(DrawInfo) if self.RenderEnable == 1 then if resultMaterial then surface.SetMaterial(resultMaterial) resultTriangle = { [1] = resultTriangle[3], [2] = resultTriangle[2], [3] = resultTriangle[1], } else surface.SetTexture(0) end surface.SetDrawColor(resultColor.x,resultColor.y,resultColor.z,resultColor.w) if vertexData.wireframe then if resultTriangle then for i=1,#resultTriangle do local point1 = resultTriangle[i] local point2 = resultTriangle[i+1] if not point2 then point2 = resultTriangle[1] end self:DrawLine(point1,point2,true) end end if resultTriangle2 then for i=1,#resultTriangle2 do local point1 = resultTriangle2[i] local point2 = resultTriangle2[i+1] if not point2 then point2 = resultTriangle2[1] end self:DrawLine(point1,point2,true) end end else if resultTriangle then surface.DrawPoly(resultTriangle) end if resultTriangle2 then surface.DrawPoly(resultTriangle2) end end end end end self.VertexBuffer = {} end end -------------------------------------------------------------------------------- -- Set current color -------------------------------------------------------------------------------- function VM:SetColor(color) if self.VertexBufEnabled == 1 then if #self.VertexBuffer > 0 then self.VertexBuffer[#self.VertexBuffer].color = self:ColorTransform(color) else self.VertexBuffer[1] = { color = self:ColorTransform(color), } end end self.Color = self:ColorTransform(color) end -------------------------------------------------------------------------------- -- Set current material -------------------------------------------------------------------------------- function VM:SetMaterial(material) if self.VertexBufEnabled == 1 then if #self.VertexBuffer > 0 then self.VertexBuffer[#self.VertexBuffer].material = material else self.VertexBuffer[1] = { material = material, } end end self.Material = material end -------------------------------------------------------------------------------- -- Bind rendering state (color, texture) -------------------------------------------------------------------------------- function VM:BindState() surface.SetDrawColor(self.Color.x,self.Color.y,self.Color.z,self.Color.w) if self.VertexTexturing == 1 then if self.Memory[65517] == 1 then --[@entities\gmod_wire_gpu\cl_gpuvm.lua:1276] bad argument #2 to 'SetTexture' (ITexture expected, got nil) self.Entity:AssertSpriteBufferExists() if self.Entity.SpriteGPU.RT then WireGPU_matBuffer:SetTexture("$basetexture", self.Entity.SpriteGPU.RT) end else if self.Entity.GPU.RT then WireGPU_matBuffer:SetTexture("$basetexture", self.Entity.GPU.RT) end end surface.SetMaterial(WireGPU_matBuffer) else if self.Material then surface.SetMaterial(self.Material) else surface.SetTexture(0) end end end -------------------------------------------------------------------------------- -- Draw a buffer (or add it to vertex buffer) -------------------------------------------------------------------------------- function VM:DrawToBuffer(vertexData,isWireframe) if self.VertexBufEnabled == 1 then -- Add new entry if (not self.VertexBuffer[#self.VertexBuffer]) or self.VertexBuffer[#self.VertexBuffer].vertex then self.VertexBuffer[#self.VertexBuffer+1] = { color = self.Color, material = self.Material, vertex = {}, transformedVertex = {}, wireframe = isWireframe, } else self.VertexBuffer[#self.VertexBuffer].vertex = {} self.VertexBuffer[#self.VertexBuffer].transformedVertex = {} self.VertexBuffer[#self.VertexBuffer].wireframe = isWireframe end -- Add RT material if required if self.VertexTexturing == 1 then if self.Memory[65517] == 1 then self.Entity:AssertSpriteBufferExists() self.VertexBuffer[#self.VertexBuffer].rt = self.Entity.SpriteGPU.RT else self.VertexBuffer[#self.VertexBuffer].rt = self.Entity.GPU.RT end end -- Add all vertices for _,vertex in ipairs(vertexData) do local screenVertex,worldVertex = self:VertexTransform(vertex) table.insert(self.VertexBuffer[#self.VertexBuffer].vertex,worldVertex) table.insert(self.VertexBuffer[#self.VertexBuffer].transformedVertex,screenVertex) end else local resultPoly = {} -- Transform vertices for _,vertex in ipairs(vertexData) do local screenVertex,worldVertex = self:VertexTransform(vertex) table.insert(resultPoly,screenVertex) end -- Draw if self.RenderEnable == 1 then self:BindState() if isWireframe then for i=1,#resultPoly do local point1 = resultPoly[i] local point2 = resultPoly[i+1] if not point2 then point2 = resultPoly[1] end self:DrawLine(point1,point2,true) end else surface.DrawPoly(resultPoly) end end end end -------------------------------------------------------------------------------- -- GPU instruction set implementation -------------------------------------------------------------------------------- VM.OpcodeTable = {} VM.OpcodeTable[98] = function(self) --TIMER self:Dyn_Emit("if VM.ASYNC == 1 then") self:Dyn_EmitOperand(1,"(VM.TIMER+"..(self.PrecompileInstruction or 0).."*VM.TimerDT)",true) self:Dyn_Emit("else") self:Dyn_EmitOperand(1,"VM.TIMER",true) self:Dyn_Emit("end") end VM.OpcodeTable[111] = function(self) --IDLE self:Dyn_Emit("VM.INTR = 1") self:Dyn_EmitBreak() self.PrecompileBreak = true end -------------------------------------------------------------------------------- VM.OpcodeTable[200] = function(self) --DRECT_TEST self:Dyn_Emit("if VM.RenderEnable == 1 then") self:Dyn_Emit("$L W = VM.ScreenWidth") self:Dyn_Emit("$L H = VM.ScreenHeight") self:Dyn_Emit("surface.SetTexture(0)") self:Dyn_Emit("surface.SetDrawColor(200,200,200,255)") self:Dyn_Emit("surface.DrawRect(W*0.125*0,0,W*0.125,H*0.80)") self:Dyn_Emit("surface.SetDrawColor(200,200,000,255)") self:Dyn_Emit("surface.DrawRect(W*0.125*1,0,W*0.125,H*0.80)") self:Dyn_Emit("surface.SetDrawColor(000,200,200,255)") self:Dyn_Emit("surface.DrawRect(W*0.125*2,0,W*0.125,H*0.80)") self:Dyn_Emit("surface.SetDrawColor(000,200,000,255)") self:Dyn_Emit("surface.DrawRect(W*0.125*3,0,W*0.125,H*0.80)") self:Dyn_Emit("surface.SetDrawColor(200,000,200,255)") self:Dyn_Emit("surface.DrawRect(W*0.125*4,0,W*0.125,H*0.80)") self:Dyn_Emit("surface.SetDrawColor(200,000,000,255)") self:Dyn_Emit("surface.DrawRect(W*0.125*5,0,W*0.125,H*0.80)") self:Dyn_Emit("surface.SetDrawColor(000,000,200,255)") self:Dyn_Emit("surface.DrawRect(W*0.125*6,0,W*0.125,H*0.80)") self:Dyn_Emit("for gray=0,7 do") self:Dyn_Emit("surface.SetDrawColor(31*gray,31*gray,31*gray,255)") self:Dyn_Emit("surface.DrawRect(W*0.125*gray,H*0.80,W*0.125,H*0.20)") self:Dyn_Emit("end") self:Dyn_Emit("end") end VM.OpcodeTable[201] = function(self) --DEXIT self:Dyn_Emit("VM.INTR = 1") self:Dyn_EmitBreak() self.PrecompileBreak = true end VM.OpcodeTable[202] = function(self) --DCLR self:Dyn_Emit("if VM.RenderEnable == 1 then") self:Dyn_Emit("surface.SetTexture(0)") self:Dyn_Emit("surface.SetDrawColor(0,0,0,255)") self:Dyn_Emit("surface.DrawRect(0,0,VM.ScreenWidth,VM.ScreenHeight)") self:Dyn_Emit("end") end VM.OpcodeTable[203] = function(self) --DCLRTEX self:Dyn_Emit("if VM.RenderEnable == 1 then") self:Dyn_Emit("VM:BindState()") self:Dyn_Emit("surface.SetDrawColor(255,255,255,255)") self:Dyn_Emit("surface.DrawTexturedRect(0,0,VM.ScreenWidth,VM.ScreenHeight)") self:Dyn_Emit("end") end VM.OpcodeTable[204] = function(self) --DVXFLUSH self:Dyn_Emit("VM:FlushBuffer()") end VM.OpcodeTable[205] = function(self) --DVXCLEAR self:Dyn_Emit("VM.VertexBuffer = {}") end VM.OpcodeTable[206] = function(self) --DSETBUF_VX self:Dyn_Emit("VM.Entity:SetRendertarget()") self:Dyn_Emit("VM.LastBuffer = 2") end VM.OpcodeTable[207] = function(self) --DSETBUF_SPR self:Dyn_Emit("VM.Entity:SetRendertarget(1)") self:Dyn_Emit("VM.LastBuffer = 1") end VM.OpcodeTable[208] = function(self) --DSETBUF_FBO self:Dyn_Emit("VM.Entity:SetRendertarget(0)") self:Dyn_Emit("VM.LastBuffer = 0") end VM.OpcodeTable[209] = function(self) --DSWAP self:Dyn_Emit("if VM.RenderEnable == 1 then") self:Dyn_Emit("VM.Entity:AssertSpriteBufferExists()") self:Dyn_Emit("if VM.Entity.SpriteGPU.RT and VM.Entity.GPU.RT then") self:Dyn_Emit("render.CopyTexture(VM.Entity.SpriteGPU.RT,VM.Entity.GPU.RT)") self:Dyn_Emit("end") self:Dyn_Emit("end") end -------------------------------------------------------------------------------- VM.OpcodeTable[210] = function(self) --DVXPIPE self:Dyn_Emit("VM.VertexPipe = $1") end VM.OpcodeTable[211] = function(self) --DCVXPIPE self:Dyn_Emit("VM.CoordinatePipe = $1") end VM.OpcodeTable[212] = function(self) --DENABLE self:Dyn_Emit("$L IDX = $1") self:Dyn_Emit("if IDX == 0 then VM.VertexBufEnabled = 1 end") self:Dyn_Emit("if IDX == 1 then VM.VertexBufZSort = 1 end") self:Dyn_Emit("if IDX == 2 then VM.VertexLighting = 1 end") self:Dyn_Emit("if IDX == 3 then VM.VertexCulling = 1 end") self:Dyn_Emit("if IDX == 4 then VM.DistanceCulling = 1 end") self:Dyn_Emit("if IDX == 5 then VM.VertexTexturing = 1 end") end VM.OpcodeTable[213] = function(self) --DDISABLE self:Dyn_Emit("$L IDX = $1") self:Dyn_Emit("if IDX == 0 then VM.VertexBufEnabled = 0 end") self:Dyn_Emit("if IDX == 1 then VM.VertexBufZSort = 0 end") self:Dyn_Emit("if IDX == 2 then VM.VertexLighting = 0 end") self:Dyn_Emit("if IDX == 3 then VM.VertexCulling = 0 end") self:Dyn_Emit("if IDX == 4 then VM.DistanceCulling = 0 end") self:Dyn_Emit("if IDX == 5 then VM.VertexTexturing = 0 end") end VM.OpcodeTable[214] = function(self) --DCLRSCR self:Dyn_Emit("if VM.RenderEnable == 1 then") self:Dyn_Emit("VM:SetColor(VM:ReadVector4f($1))") self:Dyn_Emit("VM:BindState()") self:Dyn_Emit("surface.SetTexture(0)") self:Dyn_Emit("surface.DrawRect(0,0,VM.ScreenWidth,VM.ScreenHeight)") self:Dyn_Emit("end") end VM.OpcodeTable[215] = function(self) --DCOLOR self:Dyn_Emit("VM:SetColor(VM:ReadVector4f($1))") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[216] = function(self) --DTEXTURE self:Dyn_Emit("VM.Texture = $1") end VM.OpcodeTable[217] = function(self) --DSETFONT self:Dyn_Emit("VM.Font = math.Clamp(math.floor($1),0,7)") end VM.OpcodeTable[218] = function(self) --DSETSIZE self:Dyn_Emit("VM.FontSize = math.floor(math.max(4,math.min($1,200)))") end VM.OpcodeTable[219] = function(self) --DMOVE self:Dyn_Emit("$L ADDR = $1") self:Dyn_Emit("if ADDR == 0 then") self:Dyn_Emit("VM:WriteCell(65484,0)") self:Dyn_Emit("VM:WriteCell(65483,0)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("else") self:Dyn_Emit("VM:WriteCell(65484,VM:ReadCell(ADDR+0))") self:Dyn_Emit("VM:WriteCell(65483,VM:ReadCell(ADDR+1))") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("end") end -------------------------------------------------------------------------------- VM.OpcodeTable[220] = function(self) --DVXDATA_2F self:Dyn_Emit("$L VD = {}") self:Dyn_Emit("$L ADDR = $1") self:Dyn_Emit("$L VDATA = VM:ReadCell(65467)") self:Dyn_Emit("for IDX=1,math.min(128,$2) do") self:Dyn_Emit("if VDATA > 0 then") self:Dyn_Emit("$L VIDX = VM:ReadCell(ADDR+IDX-1)") self:Dyn_Emit("VD[IDX] = {") self:Dyn_Emit(" x = VM:ReadCell(VDATA+VIDX*2+0),") self:Dyn_Emit(" y = VM:ReadCell(VDATA+VIDX*2+1),") self:Dyn_Emit("}") self:Dyn_Emit("else") self:Dyn_Emit("VD[IDX] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR+(IDX-1)*2+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR+(IDX-1)*2+1),") self:Dyn_Emit("}") self:Dyn_Emit("end") self:Dyn_Emit("VM:ComputeTextureUV(VD[IDX],VD[IDX].x/512,VD[IDX].y/512)") self:Dyn_Emit("end") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("VM:DrawToBuffer(VD)") end VM.OpcodeTable[221] = function(self) --DVXDATA_2F_TEX self:Dyn_Emit("$L VD = {}") self:Dyn_Emit("$L ADDR = $1") self:Dyn_Emit("$L VDATA = VM:ReadCell(65467)") self:Dyn_Emit("for IDX=1,math.min(128,$2) do") self:Dyn_Emit("if VDATA > 0 then") self:Dyn_Emit("$L VIDX = VM:ReadCell(ADDR+IDX-1)") self:Dyn_Emit("VD[IDX] = {") self:Dyn_Emit(" x = VM:ReadCell(VDATA+VIDX*4+0),") self:Dyn_Emit(" y = VM:ReadCell(VDATA+VIDX*4+1),") self:Dyn_Emit("}") self:Dyn_Emit("VM:ComputeTextureUV(VD[IDX],VM:ReadCell(VDATA+VIDX*4+2),VM:ReadCell(VDATA+VIDX*4+3))") self:Dyn_Emit("else") self:Dyn_Emit("VD[IDX] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR+(IDX-1)*4+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR+(IDX-1)*4+1),") self:Dyn_Emit("}") self:Dyn_Emit("VM:ComputeTextureUV(VD[IDX],VM:ReadCell(ADDR+(IDX-1)*4+2),VM:ReadCell(ADDR+(IDX-1)*4+3))") self:Dyn_Emit("end") self:Dyn_Emit("end") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("VM:DrawToBuffer(VD)") end VM.OpcodeTable[222] = function(self) --DVXDATA_3F self:Dyn_Emit("$L VD = {}") self:Dyn_Emit("$L ADDR = $1") self:Dyn_Emit("$L VDATA = VM:ReadCell(65467)") self:Dyn_Emit("for IDX=1,math.min(128,$2) do") self:Dyn_Emit("if VDATA > 0 then") self:Dyn_Emit("$L VIDX1 = VM:ReadCell(ADDR+(IDX-1)*3+0)") self:Dyn_Emit("$L VIDX2 = VM:ReadCell(ADDR+(IDX-1)*3+1)") self:Dyn_Emit("$L VIDX3 = VM:ReadCell(ADDR+(IDX-1)*3+2)") self:Dyn_Emit("VD[1] = {") self:Dyn_Emit(" x = VM:ReadCell(VDATA+VIDX1*3+0),") self:Dyn_Emit(" y = VM:ReadCell(VDATA+VIDX1*3+1),") self:Dyn_Emit(" z = VM:ReadCell(VDATA+VIDX1*3+2),") self:Dyn_Emit("}") self:Dyn_Emit("VD[2] = {") self:Dyn_Emit(" x = VM:ReadCell(VDATA+VIDX2*3+0),") self:Dyn_Emit(" y = VM:ReadCell(VDATA+VIDX2*3+1),") self:Dyn_Emit(" z = VM:ReadCell(VDATA+VIDX2*3+2),") self:Dyn_Emit("}") self:Dyn_Emit("VD[3] = {") self:Dyn_Emit(" x = VM:ReadCell(VDATA+VIDX3*3+0),") self:Dyn_Emit(" y = VM:ReadCell(VDATA+VIDX3*3+1),") self:Dyn_Emit(" z = VM:ReadCell(VDATA+VIDX3*3+2),") self:Dyn_Emit("}") self:Dyn_Emit("else") self:Dyn_Emit("VD[1] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR+(IDX-1)*9+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR+(IDX-1)*9+1),") self:Dyn_Emit(" z = VM:ReadCell(ADDR+(IDX-1)*9+2),") self:Dyn_Emit("}") self:Dyn_Emit("VD[2] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR+(IDX-1)*9+3),") self:Dyn_Emit(" y = VM:ReadCell(ADDR+(IDX-1)*9+4),") self:Dyn_Emit(" z = VM:ReadCell(ADDR+(IDX-1)*9+5),") self:Dyn_Emit("}") self:Dyn_Emit("VD[3] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR+(IDX-1)*9+6),") self:Dyn_Emit(" y = VM:ReadCell(ADDR+(IDX-1)*9+7),") self:Dyn_Emit(" z = VM:ReadCell(ADDR+(IDX-1)*9+8),") self:Dyn_Emit("}") self:Dyn_Emit("end") self:Dyn_Emit("VM:ComputeTextureUV(VD[1],0,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD[2],1,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD[3],1,1)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("VM:DrawToBuffer(VD)") self:Dyn_Emit("end") end VM.OpcodeTable[223] = function(self) --DVXDATA_3F_TEX self:Dyn_Emit("$L VD = {}") self:Dyn_Emit("$L ADDR = $1") self:Dyn_Emit("$L VDATA = VM:ReadCell(65467)") self:Dyn_Emit("for IDX=1,math.min(128,$2) do") self:Dyn_Emit("if VDATA > 0 then") self:Dyn_Emit("$L VIDX1 = VM:ReadCell(ADDR+(IDX-1)*3+0)") self:Dyn_Emit("$L VIDX2 = VM:ReadCell(ADDR+(IDX-1)*3+1)") self:Dyn_Emit("$L VIDX3 = VM:ReadCell(ADDR+(IDX-1)*3+2)") self:Dyn_Emit("VD[1] = {") self:Dyn_Emit(" x = VM:ReadCell(VDATA+VIDX1*5+0),") self:Dyn_Emit(" y = VM:ReadCell(VDATA+VIDX1*5+1),") self:Dyn_Emit(" z = VM:ReadCell(VDATA+VIDX1*5+2),") self:Dyn_Emit("}") self:Dyn_Emit("VD[2] = {") self:Dyn_Emit(" x = VM:ReadCell(VDATA+VIDX2*5+0),") self:Dyn_Emit(" y = VM:ReadCell(VDATA+VIDX2*5+1),") self:Dyn_Emit(" z = VM:ReadCell(VDATA+VIDX2*5+2),") self:Dyn_Emit("}") self:Dyn_Emit("VD[3] = {") self:Dyn_Emit(" x = VM:ReadCell(VDATA+VIDX3*5+0),") self:Dyn_Emit(" y = VM:ReadCell(VDATA+VIDX3*5+1),") self:Dyn_Emit(" z = VM:ReadCell(VDATA+VIDX3*5+2),") self:Dyn_Emit("}") self:Dyn_Emit("VM:ComputeTextureUV(VD[1],VM:ReadCell(VDATA+VIDX1*5+3),VM:ReadCell(VDATA+VIDX1*5+4))") self:Dyn_Emit("VM:ComputeTextureUV(VD[2],VM:ReadCell(VDATA+VIDX2*5+3),VM:ReadCell(VDATA+VIDX2*5+4))") self:Dyn_Emit("VM:ComputeTextureUV(VD[3],VM:ReadCell(VDATA+VIDX3*5+3),VM:ReadCell(VDATA+VIDX3*5+4))") self:Dyn_Emit("else") self:Dyn_Emit("VD[1] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR+(IDX-1)*15+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR+(IDX-1)*15+1),") self:Dyn_Emit(" z = VM:ReadCell(ADDR+(IDX-1)*15+2),") self:Dyn_Emit("}") self:Dyn_Emit("VD[2] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR+(IDX-1)*15+5),") self:Dyn_Emit(" y = VM:ReadCell(ADDR+(IDX-1)*15+6),") self:Dyn_Emit(" z = VM:ReadCell(ADDR+(IDX-1)*15+7),") self:Dyn_Emit("}") self:Dyn_Emit("VD[3] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR+(IDX-1)*15+10),") self:Dyn_Emit(" y = VM:ReadCell(ADDR+(IDX-1)*15+11),") self:Dyn_Emit(" z = VM:ReadCell(ADDR+(IDX-1)*15+12),") self:Dyn_Emit("}") self:Dyn_Emit("VM:ComputeTextureUV(VD[1],VM:ReadCell(ADDR+(IDX-1)*15+ 3),VM:ReadCell(ADDR+(IDX-1)*15+ 4))") self:Dyn_Emit("VM:ComputeTextureUV(VD[2],VM:ReadCell(ADDR+(IDX-1)*15+ 8),VM:ReadCell(ADDR+(IDX-1)*15+ 9))") self:Dyn_Emit("VM:ComputeTextureUV(VD[3],VM:ReadCell(ADDR+(IDX-1)*15+13),VM:ReadCell(ADDR+(IDX-1)*15+14))") self:Dyn_Emit("end") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("VM:DrawToBuffer(VD)") self:Dyn_Emit("end") end VM.OpcodeTable[224] = function(self) --DVXDATA_3F_WF self:Dyn_Emit("$L VD = {}") self:Dyn_Emit("$L ADDR = $1") self:Dyn_Emit("$L VDATA = VM:ReadCell(65467)") self:Dyn_Emit("for IDX=1,math.min(128,$2) do") self:Dyn_Emit("if VDATA > 0 then") self:Dyn_Emit("$L VIDX1 = VM:ReadCell(ADDR+(IDX-1)*3+0)") self:Dyn_Emit("$L VIDX2 = VM:ReadCell(ADDR+(IDX-1)*3+1)") self:Dyn_Emit("$L VIDX3 = VM:ReadCell(ADDR+(IDX-1)*3+2)") self:Dyn_Emit("VD[1] = {") self:Dyn_Emit(" x = VM:ReadCell(VDATA+VIDX1*3+0),") self:Dyn_Emit(" y = VM:ReadCell(VDATA+VIDX1*3+1),") self:Dyn_Emit(" z = VM:ReadCell(VDATA+VIDX1*3+2),") self:Dyn_Emit("}") self:Dyn_Emit("VD[2] = {") self:Dyn_Emit(" x = VM:ReadCell(VDATA+VIDX2*3+0),") self:Dyn_Emit(" y = VM:ReadCell(VDATA+VIDX2*3+1),") self:Dyn_Emit(" z = VM:ReadCell(VDATA+VIDX2*3+2),") self:Dyn_Emit("}") self:Dyn_Emit("VD[3] = {") self:Dyn_Emit(" x = VM:ReadCell(VDATA+VIDX3*3+0),") self:Dyn_Emit(" y = VM:ReadCell(VDATA+VIDX3*3+1),") self:Dyn_Emit(" z = VM:ReadCell(VDATA+VIDX3*3+2),") self:Dyn_Emit("}") self:Dyn_Emit("else") self:Dyn_Emit("VD[1] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR+(IDX-1)*9+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR+(IDX-1)*9+1),") self:Dyn_Emit(" z = VM:ReadCell(ADDR+(IDX-1)*9+2),") self:Dyn_Emit("}") self:Dyn_Emit("VD[2] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR+(IDX-1)*9+3),") self:Dyn_Emit(" y = VM:ReadCell(ADDR+(IDX-1)*9+4),") self:Dyn_Emit(" z = VM:ReadCell(ADDR+(IDX-1)*9+5),") self:Dyn_Emit("}") self:Dyn_Emit("VD[3] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR+(IDX-1)*9+6),") self:Dyn_Emit(" y = VM:ReadCell(ADDR+(IDX-1)*9+7),") self:Dyn_Emit(" z = VM:ReadCell(ADDR+(IDX-1)*9+8),") self:Dyn_Emit("}") self:Dyn_Emit("end") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("VM:DrawToBuffer(VD,true)") self:Dyn_Emit("end") end VM.OpcodeTable[225] = function(self) --DRECT self:Dyn_Emit("$L VD = {}") self:Dyn_Emit("$L ADDR1 = $1") self:Dyn_Emit("$L ADDR2 = $2") self:Dyn_Emit("VD[1] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR1+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR1+1)}") self:Dyn_Emit("VD[2] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR2+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR1+1)}") self:Dyn_Emit("VD[3] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR2+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR2+1)}") self:Dyn_Emit("VD[4] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR1+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR2+1)}") self:Dyn_Emit("VM:ComputeTextureUV(VD[1],0,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD[2],1,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD[3],1,1)") self:Dyn_Emit("VM:ComputeTextureUV(VD[4],0,1)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("VM:DrawToBuffer(VD)") end VM.OpcodeTable[226] = function(self) --DCIRCLE self:Dyn_Emit("$L VD = {}") self:Dyn_Emit("$L R = $2") self:Dyn_Emit("$L SIDES = math.max(3,math.min(64,VM:ReadCell(65485)))") self:Dyn_Emit("$L START = VM:ReadCell(65478)") self:Dyn_Emit("$L END = VM:ReadCell(65477)") self:Dyn_Emit("$L STEP = (END-START)/SIDES") self:Dyn_Emit("$L VEC = VM:ReadVector2f($1)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("for IDX=1,SIDES do") self:Dyn_Emit("VD[1] = {") self:Dyn_Emit(" x = VEC.x + R*math.sin(START+STEP*(IDX+0)),") self:Dyn_Emit(" y = VEC.y + R*math.cos(START+STEP*(IDX+0))}") self:Dyn_Emit("VD[2] = {") self:Dyn_Emit(" x = VEC.x,") self:Dyn_Emit(" y = VEC.y}") self:Dyn_Emit("VD[3] = {") self:Dyn_Emit(" x = VEC.x + R*math.sin(START+STEP*(IDX+1)),") self:Dyn_Emit(" y = VEC.y + R*math.cos(START+STEP*(IDX+1))}") self:Dyn_Emit("VM:ComputeTextureUV(VD[1],0,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD[2],1,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD[3],1,1)") self:Dyn_Emit("VM:DrawToBuffer(VD)") self:Dyn_Emit("end") end VM.OpcodeTable[227] = function(self) --DLINE self:Dyn_Emit("VM:DrawLine(VM:ReadVector2f($1),VM:ReadVector2f($2))") end VM.OpcodeTable[228] = function(self) --DRECTWH self:Dyn_Emit("$L VD = {}") self:Dyn_Emit("$L ADDR1 = $1") self:Dyn_Emit("$L ADDR2 = $2") self:Dyn_Emit("VD[1] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR1+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR1+1)}") self:Dyn_Emit("VD[2] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR1+0)+VM:ReadCell(ADDR2+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR1+1)}") self:Dyn_Emit("VD[3] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR1+0)+VM:ReadCell(ADDR2+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR1+1)+VM:ReadCell(ADDR2+1)}") self:Dyn_Emit("VD[4] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR1+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR1+1)+VM:ReadCell(ADDR2+1)}") self:Dyn_Emit("VM:ComputeTextureUV(VD[1],0,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD[2],1,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD[3],1,1)") self:Dyn_Emit("VM:ComputeTextureUV(VD[4],0,1)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("VM:DrawToBuffer(VD)") end VM.OpcodeTable[229] = function(self) --DORECT self:Dyn_Emit("$L VD = {}") self:Dyn_Emit("$L ADDR1 = $1") self:Dyn_Emit("$L ADDR2 = $2") self:Dyn_Emit("VD[1] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR1+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR1+1)}") self:Dyn_Emit("VD[2] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR2+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR1+1)}") self:Dyn_Emit("VD[3] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR2+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR2+1)}") self:Dyn_Emit("VD[4] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR1+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR2+1)}") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("VM:DrawLine(VD[1],VD[2])") self:Dyn_Emit("VM:DrawLine(VD[2],VD[3])") self:Dyn_Emit("VM:DrawLine(VD[3],VD[4])") self:Dyn_Emit("VM:DrawLine(VD[4],VD[1])") end -------------------------------------------------------------------------------- VM.OpcodeTable[230] = function(self) --DTRANSFORM2F self:Dyn_Emit("$L VEC = VM:ReadVector2f($2)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("VEC = VM:VertexTransform(VEC)") self:Dyn_Emit("VM:WriteVector2f($1,VEC)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[231] = function(self) --DTRANSFORM3F self:Dyn_Emit("$L VEC = VM:ReadVector3f($2)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("VEC = VM:VertexTransform(VEC)") self:Dyn_Emit("VM:WriteVector3f($1,VEC)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[232] = function(self) --DSCRSIZE self:Dyn_Emit("VM:WriteCell(65515,$1)") self:Dyn_Emit("VM:WriteCell(65514,$2)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[233] = function(self) --DROTATESCALE self:Dyn_Emit("VM:WriteCell(65482,$1)") self:Dyn_Emit("VM:WriteCell(65481,$2)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[234] = function(self) --DORECTWH self:Dyn_Emit("$L VD = {}") self:Dyn_Emit("$L ADDR1 = $1") self:Dyn_Emit("$L ADDR2 = $2") self:Dyn_Emit("VD[1] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR1+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR1+1)}") self:Dyn_Emit("VD[2] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR1+0)+VM:ReadCell(ADDR2+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR1+1)}") self:Dyn_Emit("VD[3] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR1+0)+VM:ReadCell(ADDR2+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR1+1)+VM:ReadCell(ADDR2+1)}") self:Dyn_Emit("VD[4] = {") self:Dyn_Emit(" x = VM:ReadCell(ADDR1+0),") self:Dyn_Emit(" y = VM:ReadCell(ADDR1+1)+VM:ReadCell(ADDR2+1)}") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("VM:DrawLine(VD[1],VD[2])") self:Dyn_Emit("VM:DrawLine(VD[2],VD[3])") self:Dyn_Emit("VM:DrawLine(VD[3],VD[4])") self:Dyn_Emit("VM:DrawLine(VD[4],VD[1])") end VM.OpcodeTable[235] = function(self) --DCULLMODE self:Dyn_Emit("VM:WriteCell(65469,$1)") self:Dyn_Emit("VM:WriteCell(65468,$2)") end VM.OpcodeTable[236] = function(self) --DARRAY end VM.OpcodeTable[237] = function(self) --DDTERMINAL end VM.OpcodeTable[238] = function(self) --DPIXEL self:Dyn_Emit("$L COLOR = VM:ColorTransform(VM:ReadVector4f($2))") self:Dyn_Emit("$L POS = VM:ReadVector2f($1)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("surface.SetTexture(0)") self:Dyn_Emit("surface.SetDrawColor(COLOR.x,COLOR.y,COLOR.z,COLOR.w)") self:Dyn_Emit("surface.DrawRect(math.floor(POS.x),math.floor(POS.y),1,1)") end VM.OpcodeTable[239] = function(self) --RESERVED end -------------------------------------------------------------------------------- VM.OpcodeTable[240] = function(self) --DWRITE self:Dyn_Emit("$L TEXT = VM:ReadString($2)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("VM:FontWrite($1,TEXT)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[241] = function(self) --DWRITEI self:Dyn_Emit("VM:FontWrite($1,math.floor($2))") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[242] = function(self) --DWRITEF self:Dyn_Emit("VM:FontWrite($1,$2)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[243] = function(self) --DENTRYPOINT self:Dyn_Emit("$L IDX = $1") self:Dyn_Emit("if IDX == 0 then VM.EntryPoint0 = $2 end") self:Dyn_Emit("if IDX == 1 then VM.EntryPoint1 = $2 end") self:Dyn_Emit("if IDX == 2 then VM.EntryPoint2 = $2 end") self:Dyn_Emit("if IDX == 3 then VM.EntryPoint3 = $2 end") self:Dyn_Emit("if IDX == 4 then VM.EntryPoint4 = $2 end") end VM.OpcodeTable[244] = function(self) --DSETLIGHT self:Dyn_Emit("$L IDX = math.floor($1)") self:Dyn_Emit("$L ADDR = $2") self:Dyn_Emit("if (IDX < 0) or (IDX > 7) then") self:Dyn_EmitInterrupt("19","0") self:Dyn_Emit("else") self:Dyn_Emit("VM.Lights[IDX] = {") self:Dyn_Emit(" Position = VM:ReadVector4f(ADDR+0),") self:Dyn_Emit(" Color = VM:ReadVector4f(ADDR+4)}") self:Dyn_Emit("end") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[245] = function(self) --DGETLIGHT self:Dyn_Emit("$L IDX = math.floor($1)") self:Dyn_Emit("$L ADDR = $2") self:Dyn_Emit("if (IDX < 0) or (IDX > 7) then") self:Dyn_EmitInterrupt("19","0") self:Dyn_Emit("else") self:Dyn_Emit("if VM.Lights[IDX] then") self:Dyn_Emit("VM:WriteVector4f(ADDR+0,VM.Lights[IDX].Position)") self:Dyn_Emit("VM:WriteVector4f(ADDR+4,VM.Lights[IDX].Color)") self:Dyn_Emit("else") self:Dyn_Emit("VM:WriteVector4f(ADDR+0,0)") self:Dyn_Emit("VM:WriteVector4f(ADDR+4,0)") self:Dyn_Emit("end") self:Dyn_Emit("end") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[246] = function(self) --DWRITEFMT string.format( self:Dyn_Emit("$L text = VM:ReadString($2)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("$L ptr = $2 + #text + 1") self:Dyn_Emit("$L ptr2 = VM.Memory[65512] or 0") self:Dyn_Emit("if ptr2 ~= 0 then ptr = ptr2 end") self:Dyn_Emit("local finaltext = \"\"") self:Dyn_Emit("local inparam = false") self:Dyn_Emit("local lengthmod = nil") self:Dyn_Emit("while (text ~= \"\") do") self:Dyn_Emit("local chr = string.sub(text,1,1)") self:Dyn_Emit("text = string.sub(text,2,65536)") self:Dyn_Emit("if (inparam == false) then") self:Dyn_Emit("if (chr == \"%\") then") self:Dyn_Emit("inparam = true") self:Dyn_Emit("else") self:Dyn_Emit("finaltext = finaltext .. chr") self:Dyn_Emit("end") self:Dyn_Emit("else") self:Dyn_Emit("if (chr == \".\") then") self:Dyn_Emit("chr = string.sub(text,1,1)") self:Dyn_Emit("text = string.sub(text,2,65536)") self:Dyn_Emit("if (tonumber(chr)) then") self:Dyn_Emit("lengthmod = tonumber(chr)") self:Dyn_Emit("end") self:Dyn_Emit("elseif (chr == \"i\") or (chr == \"d\") then") self:Dyn_Emit("if (lengthmod) then") self:Dyn_Emit("local digits = 0") self:Dyn_Emit("local num = math.floor(VM:ReadCell(ptr))") self:Dyn_Emit("local temp = num") self:Dyn_Emit("while (temp > 0) do") self:Dyn_Emit("digits = digits + 1") self:Dyn_Emit("temp = math.floor(temp / 10)") self:Dyn_Emit("end") self:Dyn_Emit("if (num == 0) then") self:Dyn_Emit("digits = 1") self:Dyn_Emit("end") self:Dyn_Emit("local fnum = tostring(num)") self:Dyn_Emit("while (digits < lengthmod) do") self:Dyn_Emit("digits = digits + 1") self:Dyn_Emit("fnum = \"0\"..fnum") self:Dyn_Emit("end") self:Dyn_Emit("finaltext = finaltext ..fnum") self:Dyn_Emit("else") self:Dyn_Emit("finaltext = finaltext .. math.floor(VM:ReadCell(ptr))") self:Dyn_Emit("end") self:Dyn_Emit("ptr = ptr + 1") self:Dyn_Emit("inparam = false") self:Dyn_Emit("lengthmod = nil") self:Dyn_Emit("elseif (chr == \"f\") then") self:Dyn_Emit("finaltext = finaltext .. VM:ReadCell(ptr)") self:Dyn_Emit("ptr = ptr + 1") self:Dyn_Emit("inparam = false") self:Dyn_Emit("lengthmod = nil") self:Dyn_Emit("elseif (chr == \"s\") then") self:Dyn_Emit("local addr = VM:ReadCell(ptr)") self:Dyn_Emit("local str = VM:ReadString(addr)") self:Dyn_Emit("finaltext = finaltext .. str") self:Dyn_Emit("ptr = ptr + 1") self:Dyn_Emit("inparam = false") self:Dyn_Emit("lengthmod = nil") self:Dyn_Emit("elseif (chr == \"t\") then") self:Dyn_Emit("while (string.len(finaltext) % (lengthmod or 6) != 0) do") self:Dyn_Emit("finaltext = finaltext..\" \"") self:Dyn_Emit("end") self:Dyn_Emit("inparam = false") self:Dyn_Emit("lengthmod = nil") self:Dyn_Emit("elseif (chr == \"%\") then") self:Dyn_Emit("finaltext = finaltext .. \"%\"") self:Dyn_Emit("inparam = false") self:Dyn_Emit("lengthmod = nil") self:Dyn_Emit("end") self:Dyn_Emit("end") self:Dyn_Emit("end") self:Dyn_Emit("VM:FontWrite($1,finaltext)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[247] = function(self) --DWRITEFIX self:Dyn_Emit("$L TEXT = $2") self:Dyn_Emit("if TEXT == math.floor(TEXT) then TEXT = TEXT .. \"0\" end") self:Dyn_Emit("VM:FontWrite($1,TEXT)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[248] = function(self) --DTEXTWIDTH self:Dyn_Emit("$L TEXT = VM:ReadString($2)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("$L W,H = VM:TextSize(TEXT)") self:Dyn_EmitOperand("W") end VM.OpcodeTable[249] = function(self) --DTEXTHEIGHT self:Dyn_Emit("$L TEXT = VM:ReadString($2)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("$L W,H = VM:TextSize(TEXT)") self:Dyn_EmitOperand("H") end -------------------------------------------------------------------------------- VM.OpcodeTable[271] = function(self) --MLOADPROJ self:Dyn_Emit("VM.ProjectionMatrix = VM:ReadMatrix($1)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[272] = function(self) --MREAD self:Dyn_Emit("VM:WriteMatrix($1,VM.ModelMatrix)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[274] = function(self) --DT self:Dyn_EmitOperand("VM.TimerDT") end VM.OpcodeTable[276] = function(self) --DSHADE self:Dyn_Emit("$L SHADE = $1") self:Dyn_Emit("VM.Color.x = VM.Color.x*SHADE") self:Dyn_Emit("VM.Color.y = VM.Color.y*SHADE") self:Dyn_Emit("VM.Color.z = VM.Color.z*SHADE") self:Dyn_Emit("VM:SetColor(VM.Color)") end VM.OpcodeTable[277] = function(self) --DSETWIDTH self:Dyn_Emit("VM:WriteCell(65476,$1)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[278] = function(self) --MLOAD self:Dyn_Emit("VM.ModelMatrix = VM:ReadMatrix($1)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[279] = function(self) --DSHADENORM self:Dyn_Emit("$L SHADE = $1") self:Dyn_Emit("VM.Color.x = math.Clamp(VM.Color.x*SHADE,0,255)") self:Dyn_Emit("VM.Color.y = math.Clamp(VM.Color.y*SHADE,0,255)") self:Dyn_Emit("VM.Color.z = math.Clamp(VM.Color.z*SHADE,0,255)") self:Dyn_Emit("VM:SetColor(VM.Color)") end -------------------------------------------------------------------------------- VM.OpcodeTable[280] = function(self) --DDFRAME self:Dyn_Emit("$L ADDR = $1") self:Dyn_Emit("$L V1 = VM:ReadVector2f(ADDR+0)") -- X,Y self:Dyn_Emit("$L V2 = VM:ReadVector2f(ADDR+2)") -- W,H self:Dyn_Emit("$L V3 = VM:ReadVector4f(ADDR+4)") -- C1,C2,C3,BorderSize self:Dyn_EmitInterruptCheck() self:Dyn_Emit("$L CSHADOW = VM:ReadVector3f(V3.x)") self:Dyn_Emit("$L CHIGHLIGHT = VM:ReadVector3f(V3.y)") self:Dyn_Emit("$L CFACE = VM:ReadVector3f(V3.z)") -- Shadow rectangle self:Dyn_Emit("$L VD1 = {}") self:Dyn_Emit("VD1[1] = {") self:Dyn_Emit(" x = V3.w + V1.x,") self:Dyn_Emit(" y = V3.w + V1.y}") self:Dyn_Emit("VD1[2] = {") self:Dyn_Emit(" x = V3.w + V1.x + V2.x,") self:Dyn_Emit(" y = V3.w + V1.y}") self:Dyn_Emit("VD1[3] = {") self:Dyn_Emit(" x = V3.w + V1.x + V2.x,") self:Dyn_Emit(" y = V3.w + V1.y + V2.y}") self:Dyn_Emit("VD1[4] = {") self:Dyn_Emit(" x = V3.w + V1.x,") self:Dyn_Emit(" y = V3.w + V1.y + V2.y}") -- Highlight rectangle self:Dyn_Emit("$L VD2 = {}") self:Dyn_Emit("VD2[1] = {") self:Dyn_Emit(" x = -V3.w + V1.x,") self:Dyn_Emit(" y = -V3.w + V1.y}") self:Dyn_Emit("VD2[2] = {") self:Dyn_Emit(" x = -V3.w + V1.x + V2.x,") self:Dyn_Emit(" y = -V3.w + V1.y}") self:Dyn_Emit("VD2[3] = {") self:Dyn_Emit(" x = -V3.w + V1.x + V2.x,") self:Dyn_Emit(" y = -V3.w + V1.y + V2.y}") self:Dyn_Emit("VD2[4] = {") self:Dyn_Emit(" x = -V3.w + V1.x,") self:Dyn_Emit(" y = -V3.w + V1.y + V2.y}") -- Face rectangle self:Dyn_Emit("$L VD3 = {}") self:Dyn_Emit("VD3[1] = {") self:Dyn_Emit(" x = V1.x,") self:Dyn_Emit(" y = V1.y}") self:Dyn_Emit("VD3[2] = {") self:Dyn_Emit(" x = V1.x + V2.x,") self:Dyn_Emit(" y = V1.y}") self:Dyn_Emit("VD3[3] = {") self:Dyn_Emit(" x = V1.x + V2.x,") self:Dyn_Emit(" y = V1.y + V2.y}") self:Dyn_Emit("VD3[4] = {") self:Dyn_Emit(" x = V1.x,") self:Dyn_Emit(" y = V1.y + V2.y}") self:Dyn_Emit("VM:ComputeTextureUV(VD1[1],0,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD1[2],1,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD1[3],1,1)") self:Dyn_Emit("VM:ComputeTextureUV(VD1[4],0,1)") self:Dyn_Emit("VM:ComputeTextureUV(VD2[1],0,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD2[2],1,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD2[3],1,1)") self:Dyn_Emit("VM:ComputeTextureUV(VD2[4],0,1)") self:Dyn_Emit("VM:ComputeTextureUV(VD3[1],0,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD3[2],1,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD3[3],1,1)") self:Dyn_Emit("VM:ComputeTextureUV(VD3[4],0,1)") self:Dyn_Emit("VM:SetColor(CSHADOW)") self:Dyn_Emit("VM:DrawToBuffer(VD1)") self:Dyn_Emit("VM:SetColor(CHIGHLIGHT)") self:Dyn_Emit("VM:DrawToBuffer(VD2)") self:Dyn_Emit("VM:SetColor(CFACE)") self:Dyn_Emit("VM:DrawToBuffer(VD3)") end VM.OpcodeTable[283] = function(self) --DRASTER self:Dyn_Emit("VM:WriteCell(65518,$1)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[285] = function(self) --DDTERRAIN self:Dyn_Emit("$L ADDR = $1") self:Dyn_Emit("$L W = VM:ReadCell(ADDR+0)") -- Total width/height of the terrain self:Dyn_Emit("$L H = VM:ReadCell(ADDR+1)") self:Dyn_Emit("$L R = math.Clamp(math.floor(VM:ReadCell(ADDR+2)),0,16)") -- Visibility radius self:Dyn_Emit("$L U = VM:ReadCell(ADDR+3)") -- Point around which terrain must be drawn self:Dyn_Emit("$L V = VM:ReadCell(ADDR+4)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("$L VD = {}") -- Terrain size self:Dyn_Emit("$L MinX = math.Clamp(math.floor(W/2 + U - R),1,W-1)") self:Dyn_Emit("$L MinY = math.Clamp(math.floor(H/2 + V - R),1,H-1)") self:Dyn_Emit("$L MaxX = math.Clamp(math.floor(W/2 + U + R),1,W-1)") self:Dyn_Emit("$L MaxY = math.Clamp(math.floor(H/2 + V + R),1,H-1)") -- Draw terrain self:Dyn_Emit("for X=MinX,MaxX do") self:Dyn_Emit("for Y=MinY,MaxY do") self:Dyn_Emit("$L XPOS = X - W/2 - U - 0.5") self:Dyn_Emit("$L YPOS = Y - H/2 - U - 0.5") self:Dyn_Emit("if (X > 0) and (X <= W-1) and (Y > 0) and (Y <= H-1) and (XPOS^2+YPOS^2 <= R^2) then") self:Dyn_Emit("$L Z1 = VM:ReadCell(ADDR+16+(Y-1)*W+(X-1)") self:Dyn_Emit("$L Z2 = VM:ReadCell(ADDR+16+(Y-1)*W+(X-0)") self:Dyn_Emit("$L Z3 = VM:ReadCell(ADDR+16+(Y-0)*W+(X-0)") self:Dyn_Emit("$L Z4 = VM:ReadCell(ADDR+16+(Y-0)*W+(X-1)") self:Dyn_Emit("VD[1] = {") self:Dyn_Emit(" x = XPOS,") self:Dyn_Emit(" y = YPOS,") self:Dyn_Emit(" y = Z1}") self:Dyn_Emit("VD[2] = {") self:Dyn_Emit(" x = XPOS+1,") self:Dyn_Emit(" y = YPOS,") self:Dyn_Emit(" y = Z2}") self:Dyn_Emit("VD[3] = {") self:Dyn_Emit(" x = XPOS+1,") self:Dyn_Emit(" y = YPOS+1,") self:Dyn_Emit(" y = Z3}") self:Dyn_Emit("VM:ComputeTextureUV(VD[1],0,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD[2],1,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD[3],1,1)") self:Dyn_Emit("VM:DrawToBuffer(VD)") self:Dyn_Emit("VD[1] = {") self:Dyn_Emit(" x = XPOS,") self:Dyn_Emit(" y = YPOS,") self:Dyn_Emit(" y = Z1}") self:Dyn_Emit("VD[2] = {") self:Dyn_Emit(" x = XPOS,") self:Dyn_Emit(" y = YPOS+1,") self:Dyn_Emit(" y = Z4}") self:Dyn_Emit("VD[3] = {") self:Dyn_Emit(" x = XPOS+1,") self:Dyn_Emit(" y = YPOS+1,") self:Dyn_Emit(" y = Z3}") self:Dyn_Emit("VM:ComputeTextureUV(VD[1],0,0)") self:Dyn_Emit("VM:ComputeTextureUV(VD[2],0,1)") self:Dyn_Emit("VM:ComputeTextureUV(VD[3],1,1)") self:Dyn_Emit("VM:DrawToBuffer(VD)") self:Dyn_Emit("end") self:Dyn_Emit("end") self:Dyn_Emit("end") end VM.OpcodeTable[288] = function(self) --DSETTEXTBOX self:Dyn_Emit("VM.Textbox = VM:ReadVector2f($1)") self:Dyn_EmitInterruptCheck() end VM.OpcodeTable[289] = function(self) --DSETTEXTWRAP self:Dyn_Emit("VM.WordWrapMode = $1") end -------------------------------------------------------------------------------- VM.OpcodeTable[294] = function(self) --DMULDT self:Dyn_EmitOperand("$2*VM.TimerDT") end VM.OpcodeTable[297] = function(self) --DMULDT self:Dyn_EmitOperand("$2*VM.TimerDT") end VM.OpcodeTable[298] = function(self) --DBEGIN self:Dyn_Emit("VM.Entity:SetRendertarget(1)") self:Dyn_Emit("VM.LastBuffer = 1") end VM.OpcodeTable[299] = function(self) --DEND self:Dyn_Emit("VM:FlushBuffer()") self:Dyn_Emit("VM.Entity:AssertSpriteBufferExists()") self:Dyn_Emit("if VM.Entity.SpriteGPU.RT and VM.Entity.GPU.RT then") self:Dyn_Emit("render.CopyTexture(VM.Entity.SpriteGPU.RT,VM.Entity.GPU.RT)") self:Dyn_Emit("end") self:Dyn_Emit("VM.Entity:SetRendertarget()") self:Dyn_Emit("VM.LastBuffer = 2") end -------------------------------------------------------------------------------- VM.OpcodeTable[303] = function(self) --DXTEXTURE self:Dyn_Emit("$L PTR = $1") self:Dyn_Emit("if PTR > 0 then") self:Dyn_Emit("$L NAME = VM:ReadString($1)") self:Dyn_EmitInterruptCheck() self:Dyn_Emit("VM:SetMaterial(GPULib.Material(NAME))") self:Dyn_Emit("else") self:Dyn_Emit("VM:SetMaterial(nil)") self:Dyn_Emit("end") end -------------------------------------------------------------------------------- --ENT._VM = {} --for k,v in pairs(VM) do ENT._VM[k] = v end --VM = nil
apache-2.0
n0xus/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Wyatt.lua
17
1982
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Wyatt -- @zone 80 -- @pos 124 0 84 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/titles"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 4 and trade:hasItemQty(2506,4)) then player:startEvent(0x0004); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local seeingSpots = player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS); if (seeingSpots == QUEST_AVAILABLE) then player:startEvent(0x0002); elseif (seeingSpots == QUEST_ACCEPTED) then player:startEvent(0x0003); else player:showText(npc, WYATT_DIALOG); 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); if (csid == 0x0002) then player:addQuest(CRYSTAL_WAR,SEEING_SPOTS); elseif (csid == 0x0004) then player:tradeComplete(); if (player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS) == QUEST_ACCEPTED) then player:addTitle(LADY_KILLER); player:addGil(GIL_RATE*3000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000); player:completeQuest(CRYSTAL_WAR,SEEING_SPOTS); else player:addTitle(LADY_KILLER); player:addGil(GIL_RATE*1500); player:messageSpecial(GIL_OBTAINED,GIL_RATE*1500); end end end;
gpl-3.0
davymai/CN-QulightUI
Interface/AddOns/DBM-Highmaul/localization.kr.lua
1
2753
if GetLocale() ~= "koKR" then return end local L --------------- -- Kargath Bladefist -- --------------- L= DBM:GetModLocalization(1128) L:SetTimerLocalization({ timerSweeperCD = DBM_CORE_AUTO_TIMER_TEXTS.next:format("높은망치 난동꾼") }) L:SetOptionLocalization({ timerSweeperCD = "다음 높은망치 난동꾼 바 보기", countdownSweeper = "높은망치 난동꾼 이전에 초읽기 듣기" }) --------------------------- -- The Butcher -- --------------------------- L= DBM:GetModLocalization(971) --------------------------- -- Tectus, the Living Mountain -- --------------------------- L= DBM:GetModLocalization(1195) L:SetMiscLocalization({ pillarSpawn = "산이여, 솟아라!" }) ------------------ -- Brackenspore, Walker of the Deep -- ------------------ L= DBM:GetModLocalization(1196) L:SetOptionLocalization({ InterruptCounter = "부패 시전 횟수 초기화", Two = "2회 시전 후", Three = "3회 시전 후", Four = "4회 시전 후" }) -------------- -- Twin Ogron -- -------------- L= DBM:GetModLocalization(1148) L:SetOptionLocalization({ PhemosSpecial = "페모스의 대기시간 초읽기 듣기", PolSpecial = "폴의 대기시간 초읽기 듣기", PhemosSpecialVoice = "펠모스의 주문을 선택한 음성안내 소리로 듣기", PolSpecialVoice = "폴의 주문을 선택한 음성안내 소리로 듣기" }) -------------------- --Koragh -- -------------------- L= DBM:GetModLocalization(1153) L:SetWarningLocalization({ specWarnExpelMagicFelFades = "5초 후 악마 사라짐 - 처음 지점으로 이동!" }) L:SetOptionLocalization({ specWarnExpelMagicFelFades = "$spell:172895 주문이 사라지기 전에 처음 지점 이동 특수 경고 보기" }) L:SetMiscLocalization({ supressionTarget1 = "박살내주마!", supressionTarget2 = "침묵!", supressionTarget3 = "닥쳐라!", supressionTarget4 = "으허허허, 반으로 찢어주마!" }) -------------------------- -- Imperator Mar'gok -- -------------------------- L= DBM:GetModLocalization(1197) L:SetTimerLocalization({ timerNightTwistedCD = "다음 뒤틀린 밤의 신봉자" }) L:SetOptionLocalization({ GazeYellType = "심연의 시선 대화 알림 방식 선택", Countdown = "남은시간 초세기", Stacks = "받을 때 중첩 수", timerNightTwistedCD = "다음 뒤틀린 밤의 신봉자 바 보기" }) L:SetMiscLocalization({ BrandedYell = "낙인(%d중첩): %dm", GazeYell = "%d초 후 시선 사라짐!", GazeYell2 = "%2$s에게 시선! (%1$d)", PlayerDebuffs = "광기의 눈길 가까움" }) ------------- -- Trash -- ------------- L = DBM:GetModLocalization("HighmaulTrash") L:SetGeneralLocalization({ name = "높은망치: 일반구간" })
gpl-2.0
n0xus/darkstar
scripts/zones/Lower_Jeuno/npcs/Gurdern.lua
34
1374
----------------------------------- -- Area: Lower Jeuno -- NPC: Gurdern -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Lower_Jeuno/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,14) == false) then player:startEvent(10052); else player:startEvent(0x0070); 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); if (csid == 10052) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",14,true); end end;
gpl-3.0
n0xus/darkstar
scripts/zones/South_Gustaberg/npcs/Cavernous_Maw.lua
58
1907
----------------------------------- -- Area: South Gustaberg -- NPC: Cavernous Maw -- @pos 340 -0.5 -680 -- Teleports Players to Abyssea - Altepa ----------------------------------- package.loaded["scripts/zones/South_Gustaberg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/abyssea"); require("scripts/zones/South_Gustaberg/TextIDs"); ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_ABYSSEA == 1 and player:getMainLvl() >= 30) then local HasStone = getTravStonesTotal(player); if (HasStone >= 1 and player:getQuestStatus(ABYSSEA, DAWN_OF_DEATH) == QUEST_ACCEPTED and player:getQuestStatus(ABYSSEA, A_BEAKED_BLUSTERER) == QUEST_AVAILABLE) then player:startEvent(0); else player:startEvent(914,0,1); -- No param = no entry. end else player:messageSpecial(NOTHING_HAPPENS); 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); if (csid == 0) then player:addQuest(ABYSSEA, A_BEAKED_BLUSTERER); elseif (csid == 1) then -- Killed Bennu elseif (csid == 914 and option == 1) then player:setPos(432, 0, 321, 125, 218); end end;
gpl-3.0
n0xus/darkstar
scripts/globals/items/dish_of_hydra_kofte.lua
21
1942
----------------------------------------- -- ID: 5602 -- Item: dish_of_hydra_kofte -- Food Effect: 180Min, All Races ----------------------------------------- -- Strength 7 -- Intelligence -3 -- Attack % 20 -- Attack Cap 150 -- Defense % 25 -- Defense Cap 70 -- Ranged ATT % 20 -- Ranged ATT Cap 150 -- Poison Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5602); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 7); target:addMod(MOD_INT, -3); target:addMod(MOD_FOOD_ATTP, 20); target:addMod(MOD_FOOD_ATT_CAP, 150); target:addMod(MOD_FOOD_DEFP, 25); target:addMod(MOD_FOOD_DEF_CAP, 70); target:addMod(MOD_FOOD_RATTP, 20); target:addMod(MOD_FOOD_RATT_CAP, 150); target:addMod(MOD_POISONRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 7); target:delMod(MOD_INT, -3); target:delMod(MOD_FOOD_ATTP, 20); target:delMod(MOD_FOOD_ATT_CAP, 150); target:delMod(MOD_FOOD_DEFP, 25); target:delMod(MOD_FOOD_DEF_CAP, 70); target:delMod(MOD_FOOD_RATTP, 20); target:delMod(MOD_FOOD_RATT_CAP, 150); target:delMod(MOD_POISONRES, 5); end;
gpl-3.0
davymai/CN-QulightUI
Interface/AddOns/Broker_Garrison/config.lua
1
47685
local ADDON_NAME, private = ... local Garrison = LibStub("AceAddon-3.0"):GetAddon(ADDON_NAME) local AceConfigRegistry = LibStub("AceConfigRegistry-3.0") local AceConfigDialog = LibStub("AceConfigDialog-3.0") local AceDBOptions = LibStub("AceDBOptions-3.0") local LSM = LibStub:GetLibrary("LibSharedMedia-3.0") local L = LibStub("AceLocale-3.0"):GetLocale(ADDON_NAME) local table, print, pairs, strsub, tonumber = _G.table, _G.print, _G.pairs, _G.strsub, _G.tonumber local garrisonDb, globalDb, configDb local debugPrint = Garrison.debugPrint local fonts = {} local sounds = {} local prefixSortValue = "sortValue" local prefixSortAscending = "sortAscending" local prefixDataOptionTooltip = "dataOptionTooltip" local prefixdataOptionNotification = "dataOptionNotification" local lenPrefixSortValue = _G.strlen(prefixSortValue) local lenPrefixSortAscending = _G.strlen(prefixSortAscending) local lenPrefixDataOptionTooltip = _G.strlen(prefixDataOptionTooltip) local lenPrefixDataOptionNotification = _G.strlen(prefixdataOptionNotification) local charLookupTable = {} local garrisonOptions function Garrison:returnchars() local a = {} for realmName,realmData in Garrison.pairsByKeys(globalDb.data) do for playerName,value in Garrison.pairsByKeys(realmData) do if (not (Garrison.charInfo.playerName == playerName and Garrison.charInfo.realmName == realmName)) then table.insert(a,playerName..":"..realmName) end end end table.sort(a) return a end function Garrison:GetFonts() for k in pairs(fonts) do fonts[k] = nil end for _, name in pairs(LSM:List(LSM.MediaType.FONT)) do fonts[name] = name end return fonts end function Garrison:GetSounds() for k in pairs(sounds) do sounds[k] = nil end for _, name in pairs(LSM:List(LSM.MediaType.SOUND)) do sounds[name] = name end return sounds end function Garrison:GetTemplates(paramType) local templates = {} for k,v in pairs(Garrison.ldbTemplate) do if not v.type or v.type == paramType then templates[k] = v.name end end templates["custom"] = L["Custom"] return templates end function Garrison:GetLDBVariables(paramType) local vars = {} for k,v in Garrison.sort(Garrison.ldbVars, "name,a") do if not v.type or v.type == paramType then vars[k] = v.name end end return vars end function Garrison:GetTooltipSortOptions(paramType) local vars = {} for k,v in pairs(Garrison.tooltipConfig) do if not v.type or v.type == paramType then vars[k] = v.name end end return vars end function Garrison:GetLDBText(paramType) local template = configDb.general[paramType].ldbTemplate local ldbText = "" if template == "custom" then ldbText = configDb.general[paramType].ldbText elseif Garrison.ldbTemplate and Garrison.ldbTemplate[template] then ldbText = Garrison.ldbTemplate[template].text end return ldbText end function Garrison:deletechar(realm_and_character) local playerName, realmName = (":"):split(realm_and_character, 2) if not realmName or realmName == nil or realmName == "" then return nil end if not playerName or playerName == nil or playerName == "" then return nil end globalDb.data[realmName][playerName] = nil local lastPlayer = true for realmName,realmData in pairs(globalDb.data[realmName]) do lastPlayer = false end if lastPlayer then globalDb.data[realmName] = nil end debugPrint(("%s deleted."):format(realm_and_character)) end -- Options function Garrison:GetOptions() local options = { name = L["Broker Garrison"], type = "group", childGroups = "tab", handler = self, args = { confdesc = { order = 1, type = "description", name = L["Garrison display for LDB\n"], cmdHidden = true, }, general = { order = 100, type = "group", name = L["General"], cmdHidden = true, args = { garrisonMinimapButton = { order = 100, type = "toggle", width = "full", name = L["Hide Garrison Minimap-Button"], desc = L["Hide Garrison Minimap-Button"], get = function() return configDb.general.hideGarrisonMinimapButton end, set = function(_,v) configDb.general.hideGarrisonMinimapButton = v Garrison:UpdateConfig() end, }, highAccuracy = { order = 110, type = "toggle", width = "double", name = L["High Accuracy"], desc = L["Update LDB/Tooltip every second"], get = function() return configDb.general.highAccuracy end, set = function(_,v) configDb.general.highAccuracy = v Garrison:UpdateLDB() end, }, showSeconds = { order = 115, type = "toggle", width = "double", name = L["Show seconds in LDB/Tooltip"], desc = L["Show seconds in LDB/Tooltip"], get = function() return configDb.general.showSeconds end, set = function(_,v) configDb.general.showSeconds = v Garrison:UpdateLDB() end, --disabled = function() return not configDb.general.highAccuracy end, }, updateInCombat = { order = 120, type = "toggle", width = "double", name = L["Run updates (LDB, data queries) in combat"], desc = L["Run updates (LDB, data queries) in combat"], get = function() return configDb.general.updateInCombat end, set = function(_,v) configDb.general.updateInCombat = v Garrison:UpdateLDB() end, --disabled = function() return not configDb.general.highAccuracy end, }, missionGroup = { order = 200, type = "group", name = L["Mission"], cmdHidden = true, args = { ldbHeader = { order = 100, type = "header", name = L["LDB Display"], cmdHidden = true, }, ldbLabelText = { order = 110, type = "input", width = "full", name = L["Custom LDB Text"], desc = L["Custom LDB Text"], get = function() return configDb.general.mission.ldbLabelText end, set = function(_,v) configDb.general.mission.ldbLabelText = v end, }, ldbTemplateSelect = { order = 120, type = "select", width = "full", name = L["LDB Text"], desc = L["LDB Text"], values = Garrison:GetTemplates(Garrison.TYPE_MISSION), get = function() return configDb.general.mission.ldbTemplate end, set = function(_,v) if v then if configDb.general.mission.ldbText == "custom" then configDb.general.mission.ldbText = Garrison:GetLDBText(Garrison.TYPE_MISSION) or "" configDb.general.mission.ldbTemplate = v else configDb.general.mission.ldbTemplate = v configDb.general.mission.ldbText = Garrison:GetLDBText(Garrison.TYPE_MISSION) or "" end end end, }, ldbText = { order = 130, type = "input", multiline = 5, width = "full", name = L["Custom LDB Text"], desc = L["Custom LDB Text"], get = function() return configDb.general.mission.ldbText end, set = function(_,v) configDb.general.mission.ldbText = v end, disabled = function() return not configDb.general.mission.ldbTemplate or not (configDb.general.mission.ldbTemplate == "custom") end, }, ldbVar = { order = 140, type = "select", width = "full", name = L["Add item to custom LDB Text"], name = L["Add item to custom LDB Text"], values = Garrison:GetLDBVariables(Garrison.TYPE_MISSION), get = function() return "" end, set = function(_,v) configDb.general.mission.ldbText = ("%s%%%s%%"):format(configDb.general.mission.ldbText or "", v or "") end, disabled = function() return not configDb.general.mission.ldbTemplate or not (configDb.general.mission.ldbTemplate == "custom") end, }, }, }, buildingGroup = { order = 200, type = "group", name = L["Building"], cmdHidden = true, args = { ldbHeader = { order = 100, type = "header", name = L["LDB Display"], cmdHidden = true, }, ldbLabelText = { order = 110, type = "input", width = "full", name = L["Label Text"], desc = L["Label Text"], get = function() return configDb.general.building.ldbLabelText end, set = function(_,v) configDb.general.building.ldbLabelText = v end, }, ldbTemplateSelect = { order = 120, type = "select", width = "full", name = L["LDB Text"], desc = L["LDB Text"], values = Garrison:GetTemplates(Garrison.TYPE_BUILDING), get = function() return configDb.general.building.ldbTemplate end, set = function(_,v) if v then if configDb.general.building.ldbText == "custom" then configDb.general.building.ldbText = Garrison:GetLDBText(Garrison.TYPE_BUILDING) or "" configDb.general.building.ldbTemplate = v else configDb.general.building.ldbTemplate = v configDb.general.building.ldbText = Garrison:GetLDBText(Garrison.TYPE_BUILDING) or "" end end end, }, ldbText = { order = 130, type = "input", width = "full", multiline = 5, name = L["Custom LDB Text"], desc = L["Custom LDB Text"], get = function() return configDb.general.building.ldbText end, set = function(_,v) configDb.general.building.ldbText = v end, disabled = function() return not configDb.general.building.ldbTemplate or not (configDb.general.building.ldbTemplate == "custom") end, }, ldbVar = { order = 140, type = "select", width = "full", name = L["Add item to custom LDB Text"], name = L["Add item to custom LDB Text"], values = Garrison:GetLDBVariables(Garrison.TYPE_BUILDING), get = function() return "" end, set = function(_,v) configDb.general.building.ldbText = ("%s%%%s%%"):format(configDb.general.building.ldbText or "", v or "") end, disabled = function() return not configDb.general.building.ldbTemplate or not (configDb.general.building.ldbTemplate == "custom") end, }, }, }, }, }, dataGroup = { order = 200, type = "group", name = L["Data"], cmdHidden = true, args = { }, }, notificationGroup = { order = 300, type = "group", name = L["Notifications"], cmdHidden = true, args = { notificationGeneral = { order = 10, type = "group", name = L["General"], cmdHidden = true, args = { disableInParty = { order = 100, type = "toggle", width = "full", name = L["Disable Notifications in Dungeon/Scenario"], desc = L["Disable Notifications in Dungeon/Scenario"], get = function() return configDb.notification.general.disableInParty end, set = function(_,v) configDb.notification.general.disableInParty = v end, }, disableInRaid = { order = 200, type = "toggle", width = "full", name = L["Disable Notifications in Raid"], desc = L["Disable Notifications in Raid"], get = function() return configDb.notification.general.disableInRaid end, set = function(_,v) configDb.notification.general.disableInRaid = v end, }, disableInPvP = { order = 300, type = "toggle", width = "full", name = L["Disable Notifications in PvP"], desc = L["Disable Notifications in Battleground/arena"], get = function() return configDb.notification.general.disableInPvP end, set = function(_,v) configDb.notification.general.disableInPvP = v end, }, }, }, notificationMissionGroup = { order = 100, type = "group", name = L["Mission"], cmdHidden = true, args = { notificationToggle = { order = 100, type = "toggle", width = "full", name = L["Enable Notifications"], desc = L["Enable Notifications"], get = function() return configDb.notification.mission.enabled end, set = function(_,v) configDb.notification.mission.enabled = v end, }, notificationRepeatOnLoad = { order = 200, type = "toggle", width = "full", name = L["Repeat on Load"], desc = L["Shows notification on each login/ui-reload"], get = function() return configDb.notification.mission.repeatOnLoad end, set = function(_,v) configDb.notification.mission.repeatOnLoad = v end, disabled = function() return not configDb.notification.mission.enabled end, }, toastHeader = { order = 300, type = "header", name = L["Toast Notifications"], cmdHidden = true, }, toastToggle = { order = 310, type = "toggle", width = "full", name = L["Enable Toasts"], desc = L["Enable Toasts"], get = function() return configDb.notification.mission.toastEnabled end, set = function(_,v) configDb.notification.mission.toastEnabled = v end, disabled = function() return not configDb.notification.mission.enabled end, }, notificationQueueEnabled = { order = 315, type = "toggle", width = "full", name = L["Summary on login"], desc = L["Summary on login"], get = function() return configDb.notification.mission.notificationQueueEnabled end, set = function(_,v) configDb.notification.mission.notificationQueueEnabled = v end, disabled = function() return not configDb.notification.mission.enabled or not configDb.notification.mission.toastEnabled end, }, toastPersistent = { order = 320, type = "toggle", width = "full", name = L["Persistent Toasts"], desc = L["Make Toasts persistent (no auto-hide)"], get = function() return configDb.notification.mission.toastPersistent end, set = function(_,v) configDb.notification.mission.toastPersistent = v end, disabled = function() return not configDb.notification.mission.enabled or not configDb.notification.mission.toastEnabled end, }, notificationExtendedToast = { order = 330, type = "toggle", width = "full", name = L["Advanced Toast controls"], desc = L["Adds OK/Dismiss Button to Toasts (Requires 'Repeat on Load')"], get = function() return configDb.notification.mission.extendedToast end, set = function(_,v) configDb.notification.mission.extendedToast = v end, disabled = function() return not configDb.notification.mission.enabled or not configDb.notification.mission.toastEnabled or not configDb.notification.mission.repeatOnLoad end, }, compactToast = { order = 340, type = "toggle", width = "full", name = L["Compact Toast"], desc = L["Compact Toast"], get = function() return configDb.notification.mission.compactToast end, set = function(_,v) configDb.notification.mission.compactToast = v end, }, miscHeader = { order = 400, type = "header", name = L["Misc"], cmdHidden = true, }, hideBlizzardNotification = { order = 410, type = "toggle", width = "full", name = L["Hide Blizzard notifications"], desc = L["Don't show the built-in notifications"], get = function() return configDb.notification.mission.hideBlizzardNotification end, set = function(_,v) configDb.notification.mission.hideBlizzardNotification = v Garrison:UpdateConfig() end, disabled = function() return not configDb.notification.mission.enabled end, }, garrisonMinimapButtonAnimation = { order = 420, type = "toggle", width = "full", name = L["Hide Minimap-Button animation"], desc = L["Don't play pulse/flash animations on Minimap-Button"], get = function() return configDb.notification.mission.hideMinimapPulse end, set = function(_,v) configDb.notification.mission.hideMinimapPulse = v end, disabled = function() return configDb.general.hideGarrisonMinimapButton end, }, playSound = { order = 430, type = "toggle", name = L["Play Sound"], desc = L["Play Sound"], get = function() return configDb.notification.mission.playSound end, set = function(_,v) configDb.notification.mission.playSound = v end, disabled = function() return not configDb.notification.mission.enabled end, }, playSoundOnMissionCompleteName = { order = 440, type = "select", name = L["Sound"], desc = L["Sound"], dialogControl = "LSM30_Sound", values = LSM:HashTable("sound"), get = function() return configDb.notification.mission.soundName end, set = function(_,v) configDb.notification.mission.soundName = v end, disabled = function() return not configDb.notification.mission.enabled or not configDb.notification.mission.playSound end, }, }, }, notificationBuildingGroup = { order = 200, type = "group", name = L["Building"], cmdHidden = true, args = { notificationToggle = { order = 100, type = "toggle", width = "full", name = L["Enable Notifications"], desc = L["Enable Notifications"], get = function() return configDb.notification.building.enabled end, set = function(_,v) configDb.notification.building.enabled = v Garrison:Update() end, }, notificationRepeatOnLoad = { order = 200, type = "toggle", width = "full", name = L["Repeat on Load"], desc = L["Shows notification on each login/ui-reload"], get = function() return configDb.notification.building.repeatOnLoad end, set = function(_,v) configDb.notification.building.repeatOnLoad = v Garrison:Update() end, disabled = function() return not configDb.notification.building.enabled end, }, toastHeader = { order = 300, type = "header", name = L["Toast Notifications"], cmdHidden = true, }, toastToggle = { order = 310, type = "toggle", width = "full", name = L["Enable Toasts"], desc = L["Enable Toasts"], get = function() return configDb.notification.building.toastEnabled end, set = function(_,v) configDb.notification.building.toastEnabled = v end, disabled = function() return not configDb.notification.building.enabled end, }, notificationQueueEnabled = { order = 315, type = "toggle", width = "full", name = L["Summary on login"], desc = L["Summary on login"], get = function() return configDb.notification.building.notificationQueueEnabled end, set = function(_,v) configDb.notification.building.notificationQueueEnabled = v end, disabled = function() return not configDb.notification.building.enabled or not configDb.notification.building.toastEnabled end, }, toastPersistent = { order = 320, type = "toggle", width = "full", name = L["Persistent Toasts"], desc = L["Make Toasts persistent (no auto-hide)"], get = function() return configDb.notification.building.toastPersistent end, set = function(_,v) configDb.notification.building.toastPersistent = v end, disabled = function() return not configDb.notification.building.enabled or not configDb.notification.building.toastEnabled end, }, notificationExtendedToast = { order = 330, type = "toggle", width = "full", name = L["Advanced Toast controls"], desc = L["Adds OK/Dismiss Button to Toasts (Requires 'Repeat on Load')"], get = function() return configDb.notification.building.extendedToast end, set = function(_,v) configDb.notification.building.extendedToast = v end, disabled = function() return not configDb.notification.building.enabled or not configDb.notification.building.toastEnabled or not configDb.notification.building.repeatOnLoad end, }, compactToast = { order = 340, type = "toggle", width = "full", name = L["Compact Toast"], desc = L["Compact Toast"], get = function() return configDb.notification.building.compactToast end, set = function(_,v) configDb.notification.building.compactToast = v end, }, miscHeader = { order = 400, type = "header", name = L["Misc"], cmdHidden = true, }, hideBlizzardNotification = { order = 410, type = "toggle", width = "full", name = L["Hide Blizzard notifications"], desc = L["Don't show the built-in notifications"], get = function() return configDb.notification.building.hideBlizzardNotification end, set = function(_,v) configDb.notification.building.hideBlizzardNotification = v Garrison:UpdateConfig() end, disabled = function() return not configDb.notification.building.enabled end, }, garrisonMinimapButtonAnimation = { order = 420, type = "toggle", width = "full", name = L["Hide Minimap-Button animation"], desc = L["Don't play pulse/flash animations on Minimap-Button"], get = function() return configDb.notification.building.hideMinimapPulse end, set = function(_,v) configDb.notification.building.hideMinimapPulse = v end, disabled = function() return configDb.general.hideGarrisonMinimapButton end, }, playSound = { order = 430, type = "toggle", name = L["Play Sound"], desc = L["Play Sound"], get = function() return configDb.notification.building.playSound end, set = function(_,v) configDb.notification.building.playSound = v end, disabled = function() return not configDb.notification.building.enabled end, }, playSoundOnMissionCompleteName = { order = 440, type = "select", name = L["Sound"], desc = L["Sound"], dialogControl = "LSM30_Sound", values = LSM:HashTable("sound"), get = function() return configDb.notification.building.soundName end, set = function(_,v) configDb.notification.building.soundName = v end, disabled = function() return not configDb.notification.building.enabled or not configDb.notification.building.playSound end, }, }, }, notificationShipmentGroup = { order = 300, type = "group", name = L["Shipment"], cmdHidden = true, args = { notificationToggle = { order = 100, type = "toggle", width = "full", name = L["Enable Notifications"], desc = L["Enable Notifications"], get = function() return configDb.notification.shipment.enabled end, set = function(_,v) configDb.notification.shipment.enabled = v Garrison:Update() end, }, notificationRepeatOnLoad = { order = 200, type = "toggle", width = "full", name = L["Repeat on Load"], desc = L["Shows notification on each login/ui-reload"], get = function() return configDb.notification.shipment.repeatOnLoad end, set = function(_,v) configDb.notification.shipment.repeatOnLoad = v Garrison:Update() end, disabled = function() return not configDb.notification.shipment.enabled end, }, toastHeader = { order = 300, type = "header", name = L["Toast Notifications"], cmdHidden = true, }, toastToggle = { order = 310, type = "toggle", width = "full", name = L["Enable Toasts"], desc = L["Enable Toasts"], get = function() return configDb.notification.shipment.toastEnabled end, set = function(_,v) configDb.notification.shipment.toastEnabled = v end, disabled = function() return not configDb.notification.shipment.enabled end, }, notificationQueueEnabled = { order = 315, type = "toggle", width = "full", name = L["Summary on login"], desc = L["Summary on login"], get = function() return configDb.notification.shipment.notificationQueueEnabled end, set = function(_,v) configDb.notification.shipment.notificationQueueEnabled = v end, disabled = function() return not configDb.notification.shipment.enabled or not configDb.notification.shipment.toastEnabled end, }, toastPersistent = { order = 320, type = "toggle", width = "full", name = L["Persistent Toasts"], desc = L["Make Toasts persistent (no auto-hide)"], get = function() return configDb.notification.shipment.toastPersistent end, set = function(_,v) configDb.notification.shipment.toastPersistent = v end, disabled = function() return not configDb.notification.shipment.enabled or not configDb.notification.shipment.toastEnabled end, }, notificationExtendedToast = { order = 330, type = "toggle", width = "full", name = L["Advanced Toast controls"], desc = L["Adds OK/Dismiss Button to Toasts (Requires 'Repeat on Load')"], get = function() return configDb.notification.shipment.extendedToast end, set = function(_,v) configDb.notification.shipment.extendedToast = v end, disabled = function() return not configDb.notification.shipment.enabled or not configDb.notification.shipment.toastEnabled or not configDb.notification.shipment.repeatOnLoad end, }, compactToast = { order = 340, type = "toggle", width = "full", name = L["Compact Toast"], desc = L["Compact Toast"], get = function() return configDb.notification.shipment.compactToast end, set = function(_,v) configDb.notification.shipment.compactToast = v end, }, miscHeader = { order = 400, type = "header", name = L["Misc"], cmdHidden = true, }, hideBlizzardNotification = { order = 410, type = "toggle", width = "full", name = L["Hide Blizzard notifications"], desc = L["Don't show the built-in notifications"], get = function() return configDb.notification.shipment.hideBlizzardNotification end, set = function(_,v) configDb.notification.shipment.hideBlizzardNotification = v Garrison:UpdateConfig() end, disabled = true --function() return not configDb.notification.shipment.enabled end, }, garrisonMinimapButtonAnimation = { order = 420, type = "toggle", width = "full", name = L["Hide Minimap-Button animation"], desc = L["Don't play pulse/flash animations on Minimap-Button"], get = function() return configDb.notification.shipment.hideMinimapPulse end, set = function(_,v) configDb.notification.shipment.hideMinimapPulse = v end, disabled = function() return configDb.general.hideGarrisonMinimapButton end, }, playSound = { order = 430, type = "toggle", name = L["Play Sound"], desc = L["Play Sound"], get = function() return configDb.notification.shipment.playSound end, set = function(_,v) configDb.notification.shipment.playSound = v end, disabled = function() return not configDb.notification.shipment.enabled end, }, playSoundOnMissionCompleteName = { order = 440, type = "select", name = L["Sound"], desc = L["Sound"], dialogControl = "LSM30_Sound", values = LSM:HashTable("sound"), get = function() return configDb.notification.shipment.soundName end, set = function(_,v) configDb.notification.shipment.soundName = v end, disabled = function() return not configDb.notification.shipment.enabled or not configDb.notification.shipment.playSound end, }, }, }, outputHeader = { order = 500, type = "header", name = L["Output"], cmdHidden = true, }, notificationLibSink = Garrison:GetSinkAce3OptionsDataTable(), }, }, displayGroup = { order = 500, type = "group", name = L["Display"], cmdHidden = true, args = { scale = { order = 110, type = "range", width = "full", name = L["Tooltip Scale"], min = 0.5, max = 2, step = 0.01, get = function() return configDb.display.scale or 1 end, set = function(info, value) configDb.display.scale = value end, }, autoHideDelay = { order = 120, type = "range", width = "full", name = L["Auto-Hide delay"], min = 0.1, max = 3, step = 0.01, get = function() return configDb.display.autoHideDelay or 0.25 end, set = function(info, value) configDb.display.autoHideDelay = value end, }, fontName = { order = 130, type = "select", name = L["Font"], desc = L["Font"], dialogControl = "LSM30_Font", values = LSM:HashTable("font"), get = function() return configDb.display.fontName end, set = function(_,v) configDb.display.fontName = v end, }, fontSize = { order = 140, type = "range", min = 5, max = 20, step = 1, width = "full", name = L["Font Size"], desc = L["Font Size"], get = function() return configDb.display.fontSize or 12 end, set = function(_,v) configDb.display.fontSize = v end, }, showIcon = { order = 150, type = "toggle", width = "full", name = L["Show Icons"], desc = L["Show Icons"], get = function() return configDb.display.showIcon end, set = function(_,v) configDb.display.showIcon = v end, }, backgroundColor = { order = 160, type = "range", width = "full", step = 1, min = 0, max = 255, name = L["Background Alpha"], desc = L["Background Alpha"], get = function() return math.floor(configDb.display.backgroundAlpha * 255) end, set = function(_,v) configDb.display.backgroundAlpha = (v / 255) end, }, }, }, tooltip = { order = 600, type = "group", name = L["Tooltip"], cmdHidden = true, args = { mission = { order = 100, type = "group", name = L["Mission"], cmdHidden = true, args = { miscHeader = { order = 10, type = "header", name = L["Misc"], cmdHidden = true, }, hideCharactersWithoutMissions = { order = 50, type = "toggle", width = "full", name = L["Hide characters without missions"], desc = L["Don't display characters without missions"], get = function() return configDb.general.mission.hideCharactersWithoutMissions end, set = function(_,v) configDb.general.mission.hideCharactersWithoutMissions = v Garrison:Update() end, }, showOnlyCurrentRealm = { order = 60, type = "toggle", width = "full", name = L["Show only current realm"], desc = L["Show only current realm"], get = function() return configDb.general.mission.showOnlyCurrentRealm end, set = function(_,v) configDb.general.mission.showOnlyCurrentRealm = v Garrison:Update() end, }, collapseOtherCharsOnLogin = { order = 70, type = "toggle", width = "full", name = L["Collapse all other characters on login"], desc = L["Collapse all other characters on login"], get = function() return configDb.general.mission.collapseOtherCharsOnLogin end, set = function(_,v) configDb.general.mission.collapseOtherCharsOnLogin = v Garrison:Update() end, }, compactTooltip = { order = 80, type = "toggle", width = "full", name = L["Compact Tooltip"], desc = L["Don't show empty newlines in tooltip"], get = function() return configDb.general.mission.compactTooltip end, set = function(_,v) configDb.general.mission.compactTooltip = v end, }, showFollowers = { order = 90, type = "toggle", width = "full", name = L["Show followers for each mission"], desc = L["Show followers for each mission"], get = function() return configDb.general.mission.showFollowers end, set = function(_,v) configDb.general.mission.showFollowers = v end, }, showRewards = { order = 91, type = "toggle", width = "full", name = L["Show rewards for each mission"], desc = L["Show rewards for each mission"], get = function() return configDb.general.mission.showRewards end, set = function(_,v) configDb.general.mission.showRewards = v end, }, showRewardXP = { order = 92, type = "toggle", width = "full", name = L["Show follower XP rewards"], desc = L["Show follower XP rewards"], get = function() return configDb.general.mission.showRewardsXP end, set = function(_,v) configDb.general.mission.showRewardsXP = v end, disabled = function() return not configDb.general.mission.showRewards end, }, showRewardsAmount = { order = 93, type = "toggle", width = "full", name = L["Show reward amount"], desc = L["Show reward amount"], get = function() return configDb.general.mission.showRewardsAmount end, set = function(_,v) configDb.general.mission.showRewardsAmount = v end, disabled = function() return not configDb.general.mission.showRewards end, }, groupHeader = { order = 100, type = "header", name = L["Group by"], cmdHidden = true, }, groupOptionValue = { order = 200, type = "select", width = "double", name = L["Group by"], desc = L["Group by"], values = Garrison:GetTooltipSortOptions(Garrison.TYPE_MISSION), get = function() return configDb.tooltip.mission.group[1].value end, set = function(_,v) configDb.tooltip.mission.group[1].value = v end, }, groupOptionAscending = { order = 201, type = "toggle", name = L["Sort ascending"], desc = L["Sort ascending"], get = function() return configDb.tooltip.mission.group[1].ascending end, set = function(_,v) configDb.tooltip.mission.group[1].ascending = v end, disabled = function() return (configDb.tooltip.mission.group[1].value or "-") == "-" end, }, groupOptionNewline = { order = 202, type = "description", name = "", width = "full", }, sortHeader = { order = 300, type = "header", name = L["Sort by"], cmdHidden = true, }, }, }, building = { order = 200, type = "group", name = L["Building"], cmdHidden = true, args = { miscHeader = { order = 10, type = "header", name = L["Misc"], cmdHidden = true, }, hideHeader = { order = 20, type = "toggle", width = "full", name = L["Hide column header"], desc = L["Hide column header"], get = function() return configDb.general.building.hideHeader end, set = function(_,v) configDb.general.building.hideHeader = v Garrison:Update() end, }, hideBuildingWithoutShipments = { order = 50, type = "toggle", width = "full", name = L["Hide buildings without shipments"], desc = L["Don't display buildings without shipments (barracks, stables, ...)"], get = function() return configDb.general.building.hideBuildingWithoutShipments end, set = function(_,v) configDb.general.building.hideBuildingWithoutShipments = v Garrison:Update() end, }, showOnlyCurrentRealm = { order = 60, type = "toggle", width = "full", name = L["Show only current realm"], desc = L["Show only current realm"], get = function() return configDb.general.building.showOnlyCurrentRealm end, set = function(_,v) configDb.general.building.showOnlyCurrentRealm = v Garrison:Update() end, }, collapseOtherCharsOnLogin = { order = 70, type = "toggle", width = "full", name = L["Collapse all other characters on login"], desc = L["Collapse all other characters on login"], get = function() return configDb.general.building.collapseOtherCharsOnLogin end, set = function(_,v) configDb.general.building.collapseOtherCharsOnLogin = v Garrison:Update() end, }, compactTooltip = { order = 80, type = "toggle", width = "full", name = L["Compact Tooltip"], desc = L["Don't show empty newlines in tooltip"], get = function() return configDb.general.building.compactTooltip end, set = function(_,v) configDb.general.building.compactTooltip = v end, }, groupHeader = { order = 100, type = "header", name = L["Group by"], cmdHidden = true, }, groupOptionValue = { order = 200, type = "select", width = "double", name = L["Group by"], desc = L["Group by"], values = Garrison:GetTooltipSortOptions(Garrison.TYPE_BUILDING), get = function() return configDb.tooltip.building.group[1].value end, set = function(_,v) configDb.tooltip.building.group[1].value = v end, }, groupOptionAscending = { order = 201, type = "toggle", name = L["Sort ascending"], desc = L["Sort ascending"], get = function() return configDb.tooltip.building.group[1].ascending end, set = function(_,v) configDb.tooltip.building.group[1].ascending = v end, disabled = function() return (configDb.tooltip.building.group[1].value or "-") == "-" end, }, groupOptionNewline = { order = 202, type = "description", name = "", width = "full", }, sortHeader = { order = 300, type = "header", name = L["Sort by"], cmdHidden = true, }, }, }, }, }, aboutGroup = { order = 900, type = "group", name = L["About"], cmdHidden = true, args = { aboutHeader = { order = 100, type = "header", name = L["Broker Garrison"], cmdHidden = true, }, version = { order = 200, type = "description", fontSize = "medium", name = ("Version: %s\n"):format(Garrison.versionString), cmdHidden = true, }, about = { order = 300, type = "description", fontSize = "medium", name = ("Author: %s <EU-Khaz'Goroth>\n\nLayout: %s %s / %s <EU-Khaz'Goroth> %s\n\nThanks to:\n\n%s"):format(Garrison.getColoredUnitName("Smb","PRIEST", "EU-Khaz'Goroth"), Garrison.getIconString(Garrison.ICON_PATH_ABOUT1, 20, false, false), Garrison.getColoredUnitName("Jarves","ROGUE", "EU-Khaz'Goroth"), Garrison.getColoredUnitName("Hotaruby","DRUID", "EU-Khaz'Goroth"), Garrison.getIconString(Garrison.ICON_PATH_ABOUT1, 20, false, false), "znf (Ideas)\nStanzilla (Ideas)\nTorhal (Ideas, LibQTip, Toaster, ...)\nMegalon (AILO, Lockouts)" ), cmdHidden = true, }, }, }, }, plugins = {}, } return options end function Garrison:SetSortOptionValue(info, value) local key = strsub(info[#info], lenPrefixSortValue + 1) configDb.tooltip[info[2]].sort[tonumber(key)].value = value end function Garrison:GetSortOptionValue(info, ...) local key = strsub(info[#info], lenPrefixSortValue + 1) return configDb.tooltip[info[2]].sort[tonumber(key)].value end function Garrison:SetSortOptionAscending(info, value) local key = strsub(info[#info], lenPrefixSortAscending + 1) configDb.tooltip[info[2]].sort[tonumber(key)].ascending = value end function Garrison:GetSortOptionAscending(info, ...) local key = strsub(info[#info], lenPrefixSortAscending + 1) return configDb.tooltip[info[2]].sort[tonumber(key)].ascending end function Garrison:GetDataOptionTooltip(info, ...) local key = strsub(info[#info], lenPrefixDataOptionTooltip + 1) local retVal = charLookupTable[tonumber(key)].tooltipEnabled if retVal == nil then charLookupTable[tonumber(key)].tooltipEnabled = true retVal = true end return retVal end function Garrison:GetDataOptionNotification(info, ...) local key = strsub(info[#info], lenPrefixDataOptionNotification + 1) local retVal = charLookupTable[tonumber(key)].notificationEnabled if retVal == nil then charLookupTable[tonumber(key)].notificationEnabled = true retVal = true end return retVal end function Garrison:SetDataOptionTooltip(info, value) local key = strsub(info[#info], lenPrefixDataOptionTooltip + 1) charLookupTable[tonumber(key)].tooltipEnabled = value end function Garrison:SetDataOptionNotification(info, value) local key = strsub(info[#info], lenPrefixDataOptionNotification + 1) charLookupTable[tonumber(key)].notificationEnabled = value end local function GetSortOptionTable(numOptions, paramType, baseOrder, sortTable) local i for i = 1, numOptions do sortTable[prefixSortValue..i] = { order = baseOrder + (i * 10) , type = "select", width = "double", name = (L["Sort order %i"]):format(i), desc = (L["Sort order %i"]):format(i), values = Garrison:GetTooltipSortOptions(paramType), get = "GetSortOptionValue", set = "SetSortOptionValue", } sortTable[prefixSortAscending..i] = { order = baseOrder + (i * 10) + 1, type = "toggle", name = L["Sort ascending"], desc = L["Sort ascending"], get = "GetSortOptionAscending", set = "SetSortOptionAscending", } sortTable["sortNewline"..i] = { order = baseOrder + (i * 10) + 2, type = "description", name = "", width = "full", } end return sortTable end function Garrison.getDataOptionTable() local baseOrder = 100 local i = 0 charLookupTable = {} local dataTable = {} dataTable.deletechar = { name = L["Delete char"], desc = L["Delete the selected char"], order = 10, type = "select", values = Garrison:returnchars(), set = function(info, val) local t=Garrison:returnchars(); Garrison:deletechar(t[val]) garrisonOptions.args.dataGroup.args = Garrison.getDataOptionTable() end, get = function(info) return nil end, width = "double", } --globalDb for realmName,realmData in Garrison.pairsByKeys(globalDb.data) do dataTable["dataRealmName"..baseOrder] = { order = baseOrder, type = "header", name = realmName, cmdHidden = true, } for playerName,playerData in Garrison.pairsByKeys(realmData) do dataTable["dataCharName"..(baseOrder + i)] = { order = baseOrder + (i * 10), type = "description", width = "normal", name = Garrison.getColoredUnitName(playerData.info.playerName, playerData.info.playerClass, realmName), cmdHidden = true, } dataTable[prefixDataOptionTooltip..(baseOrder + i)] = { order = baseOrder + (i * 10) + 1, type = "toggle", name = L["Tooltip"], get = "GetDataOptionTooltip", set = "SetDataOptionTooltip", cmdHidden = true, } dataTable[prefixdataOptionNotification..(baseOrder + i)] = { order = baseOrder + (i * 10) + 2, type = "toggle", name = L["Notifications"], get = "GetDataOptionNotification", set = "SetDataOptionNotification", cmdHidden = true, } dataTable["dataNewline"..(baseOrder + i)] = { order = baseOrder + (i * 10) + 3, type = "description", name = "", width = "full", cmdHidden = true, } charLookupTable[(baseOrder + i)] = playerData i = i + 1 end baseOrder = baseOrder + 200 end return dataTable end function Garrison:SetupOptions() garrisonDb = self.DB configDb = garrisonDb.profile globalDb = garrisonDb.global local options = Garrison:GetOptions() garrisonOptions = options AceConfigRegistry:RegisterOptionsTable(ADDON_NAME, options) Garrison.optionsFrame = AceConfigDialog:AddToBlizOptions(ADDON_NAME, Garrison.cleanName) -- Fix sink config options options.args.notificationGroup.args.notificationLibSink.order = 600 options.args.notificationGroup.args.notificationLibSink.inline = true options.args.notificationGroup.args.notificationLibSink.name = "" --options.args.notificationGroup.args.notificationLibSink.disabled = function() return not configDb.notification.enabled end options.plugins["profiles"] = { --profiles = AceDBOptions:GetOptionsTable(garrisonDb) } --options.plugins.profiles.profiles.order = 800 options.args.tooltip.args.building.args = GetSortOptionTable(7, Garrison.TYPE_BUILDING, 400, options.args.tooltip.args.building.args) options.args.tooltip.args.mission.args = GetSortOptionTable(7, Garrison.TYPE_MISSION, 400, options.args.tooltip.args.mission.args) options.args.dataGroup.args = Garrison.getDataOptionTable() --local sortedOptions = Garrison.sort(options.args, "order,a") --for k, v in sortedOptions do -- if v and v.type == "group" then -- print("AddOption "..k) -- AceConfigRegistry:RegisterOptionsTable(ADDON_NAME.."-"..k, v) -- AceConfigDialog:AddToBlizOptions(ADDON_NAME.."-"..k, v.name, Garrison.cleanName) -- end --end end
gpl-2.0
xjdrew/levent
levent/http/client.lua
1
1296
local socketUtil = require "levent.socket_util" local c = require "levent.http.c" local response = require "levent.http.response" local util = require "levent.http.util" local client = {} client.__index = client function client.new(host, port) local obj = { host = host, port = port, } return setmetatable(obj, client) end function client:send(request) if not self.conn then local conn, err = socketUtil.create_connection(self.host, self.port) if not conn then return false, err end self.conn = conn end local chunk = request:pack() local _, err = self.conn:sendall(chunk) if err then self:close() return false, err end return true end function client:get_response() assert(self.conn, "not connected") if not self.parser then self.parser = c.new(c.HTTP_RESPONSE) end local msg, left, raw = util.read_message(self.conn, self.parser, self.cached) if not msg then self.conn:close() return nil, left end msg.raw_response = raw self.cached = left return response.new(msg) end function client:close() if self.conn then self.conn:close() self.conn = nil end end return client
mit
n0xus/darkstar
scripts/globals/items/dragon_fruit.lua
36
1148
----------------------------------------- -- ID: 5662 -- Item: Dragon Fruit -- Food Effect: 5 Mins, All Races ----------------------------------------- -- Intelligence 4 -- Agility -6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5662); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_INT, 4); target:addMod(MOD_AGI, -6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_INT, 4); target:delMod(MOD_AGI, -6); end;
gpl-3.0
linmajia/dlbench
tools/torch/Data.lua
2
4996
local DataProvider = require 'DataProvider' local opt = opt or {} local Dataset = opt.dataset or 'Cifar10' local PreProcDir = opt.preProcDir or './' local Whiten = opt.whiten or false local DataPath = os.getenv("HOME").."/data/torch/" local normalization = opt.normalization or 'channel' local format = opt.format or 'rgb' local TestData local TrainData local Classes if Dataset =='Cifar100' then TrainData = torch.load(DataPath .. 'Cifar100/cifar100-train.t7') TestData = torch.load(DataPath .. 'Cifar100/cifar100-test.t7') TrainData.labelCoarse:add(1) TestData.labelCoarse:add(1) Classes = torch.linspace(1,100,100):storage():totable() elseif Dataset == 'Cifar10' then TrainData = torch.load(DataPath .. 'cifar10/cifar10-train.t7') TestData = torch.load(DataPath .. 'cifar10/cifar10-test.t7') Classes = {'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'} elseif Dataset == 'STL10' then TrainData = torch.load(DataPath .. 'STL10/stl10-train.t7') TestData = torch.load(DataPath .. 'STL10/stl10-test.t7') Classes = {'airplane', 'bird', 'car', 'cat', 'deer', 'dog', 'horse', 'monkey', 'ship', 'truck'} TestData.label = TestData.label:add(-1):byte() TrainData.label = TrainData.label:add(-1):byte() elseif Dataset == 'MNIST' then TrainData = torch.load(DataPath .. 'mnist/mnist-train.t7') TestData = torch.load(DataPath .. 'mnist/mnist-test.t7') Classes = {1,2,3,4,5,6,7,8,9,0} TestData.data = TestData.data:view(TestData.data:size(1),1,28,28) TrainData.data = TrainData.data:view(TrainData.data:size(1),1,28,28) TestData.label = TestData.labels:byte() TrainData.label = TrainData.labels:byte() elseif Dataset == 'mnist' then local util = require 'autograd.util' local Dataset = require 'dataset.Dataset' TrainData = Dataset(DataPath .. 'mnist/train.t7', { partition = opt.nodeIndex, partitions = opt.numNodes, }) TestData = Dataset(DataPath .. 'mnist/train.t7', { partition = opt.nodeIndex, partitions = opt.numNodes, }) Classes = {1,2,3,4,5,6,7,8,9,0} elseif Dataset == 'SVHN' then TrainData = torch.load(DataPath .. 'SVHN/train_32x32.t7','ascii') ExtraData = torch.load(DataPath .. 'SVHN/extra_32x32.t7','ascii') TrainData.X = torch.cat(TrainData.X, ExtraData.X,1) TrainData.y = torch.cat(TrainData.y[1], ExtraData.y[1],1) TrainData = {data = TrainData.X, label = TrainData.y} TrainData.label = TrainData.label:add(-1):byte() TrainData.X = nil TrainData.y = nil ExtraData = nil TestData = torch.load(DataPath .. 'SVHN/test_32x32.t7','ascii') TestData = {data = TestData.X, label = TestData.y[1]} TestData.label = TestData.label:add(-1):byte() Classes = {1,2,3,4,5,6,7,8,9,0} end TrainData.label:add(1) TestData.label:add(1) TrainData.data = TrainData.data:float() TestData.data = TestData.data:float() local TrainDataProvider = DataProvider.Container{ Name = 'TrainingData', CachePrefix = nil, CacheFiles = false, Source = {TrainData.data,TrainData.label}, MaxNumItems = 1e6, CopyData = false, TensorType = 'torch.FloatTensor', } local TestDataProvider = DataProvider.Container{ Name = 'TestData', CachePrefix = nil, CacheFiles = false, Source = {TestData.data, TestData.label}, MaxNumItems = 1e6, CopyData = false, TensorType = 'torch.FloatTensor', } --Preprocesss if format == 'yuv' then require 'image' TrainDataProvider:apply(image.rgb2yuv) TestDataProvider:apply(image.rgb2yuv) end if Whiten then require 'unsup' local meanfile = paths.concat(PreProcDir, format .. 'imageMean.t7') local mean, P, invP local Pfile = paths.concat(PreProcDir,format .. 'P.t7') local invPfile = paths.concat(PreProcDir,format .. 'invP.t7') if (paths.filep(Pfile) and paths.filep(invPfile) and paths.filep(meanfile)) then P = torch.load(Pfile) invP = torch.load(invPfile) mean = torch.load(meanfile) TrainDataProvider.Data = unsup.zca_whiten(TrainDataProvider.Data, mean, P, invP) else TrainDataProvider.Data, mean, P, invP = unsup.zca_whiten(TrainDataProvider.Data) torch.save(Pfile,P) torch.save(invPfile,invP) torch.save(meanfile,mean) end TestDataProvider.Data = unsup.zca_whiten(TestDataProvider.Data, mean, P, invP) else local meanfile = paths.concat(PreProcDir, format .. normalization .. 'Mean.t7') local stdfile = paths.concat(PreProcDir,format .. normalization .. 'Std.t7') local mean, std local loaded = false if paths.filep(meanfile) and paths.filep(stdfile) then mean = torch.load(meanfile) std = torch.load(stdfile) loaded = true end mean, std = TrainDataProvider:normalize(normalization, mean, std) TestDataProvider:normalize(normalization, mean, std) if not loaded then torch.save(meanfile,mean) torch.save(stdfile,std) end end return{ TrainData = TrainDataProvider, TestData = TestDataProvider, Classes = Classes }
mit
janlou2/TeleA
plugins/stats.lua
43
4082
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'کاربران داخل این گروه: \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'sbss' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /sbss ") return about end if matches[1]:lower() == "لیست امار" then if not is_momod(msg) then return "فقط برای مدیران !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "آمار" then if not matches[2] then if not is_momod(msg) then return "فقط برای مدیران !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "sbss" then -- Put everything you like :) if not is_admin(msg) then return "فقط برای ادمین ها !" else return bot_stats() end end if matches[2] == "گروه" then if not is_admin(msg) then return "فقط برای ادمین ها !" else return chat_stats(matches[3]) end end end end return { patterns = { "^(آمار)$", "^(لیست آمار)$", "^(امار) (گروه) (%d+)", "^(امار) (sbss)",-- Put everything you like :) "^[!/@#$%^&*()_+]([Ss]bss)"-- Put everything you like :) }, run = run } end
gpl-2.0
davymai/CN-QulightUI
Interface/AddOns/MBB/localization-deDE.lua
1
1120
if( GetLocale() == "deDE" ) then MBB_TOOLTIP1 = "Strg + Rechtsklick auf einen Button, um ihn aus der Leiste zu lösen."; MBB_OPTIONS_HEADER = "Einstellungen"; MBB_OPTIONS_OKBUTTON = "Ok"; MBB_OPTIONS_CANCELBUTTON = "Abbrechen"; MBB_OPTIONS_SLIDEROFF = "Aus"; MBB_OPTIONS_SLIDERSEK = "Sek."; MBB_OPTIONS_SLIDERLABEL = "Autom. ausblenden:"; MBB_OPTIONS_EXPANSIONLABEL = "Ausklappen nach:"; MBB_OPTIONS_EXPANSIONLEFT = "Links"; MBB_OPTIONS_EXPANSIONTOP = "Oben"; MBB_OPTIONS_EXPANSIONRIGHT = "Rechts"; MBB_OPTIONS_EXPANSIONBOTTOM = "Unten"; MBB_OPTIONS_MAXBUTTONSLABEL = "Max. Knöpfe/Zeile:"; MBB_OPTIONS_MAXBUTTONSINFO = "(0=unendlich)"; MBB_OPTIONS_ALTEXPANSIONLABEL = "Alt. Ausklappen nach:"; MBB_HELP1 = "Gib \"/mmbb <cmd>\" ein, wobei <cmd> folgendes sein kann:"; MBB_HELP2 = " |c00ffffffbuttons|r: Zeigt eine Liste aller Frames in der MBB Leiste"; MBB_HELP3 = " |c00ffffffreset position|r: Setzt den MBB Minimap Button an seine ursprüngliche Position"; MBB_HELP4 = " |c00ffffffreset all|r: Setzt alle Einstellungen auf ihre ursprünglichen Werte"; MBB_NOERRORS = "Keine Fehler gefunden!"; end
gpl-2.0
n0xus/darkstar
scripts/globals/mobskills/Tourbillion.lua
13
1381
--------------------------------------------- -- Tourbillion -- -- Description: Delivers an area attack. Additional effect duration varies with TP. Additional effect: Weakens defense. -- Type: Physical -- Shadow per hit -- Range: Unknown range --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1805) then return 0; else return 1; end end --[[TODO: Khimaira should only use this when its wings are up, which is animationsub() == 0. There's no system to put them "down" yet, so it's not really fair to leave it active. Tyger's fair game, though. :)]] return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 3; local accmod = 1; local dmgmod = 1.5; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); local duration = 20 * (skill:getTP() / 100); MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_DEFENSE_DOWN, 20, 0, duration); target:delHP(dmg); return dmg; end;
gpl-3.0
rekotc/game-engine-demo
Source/GCC4/3rdParty/luaplus51-all/Src/Modules/mk/src/mk/routes.lua
2
4539
local lpeg = require "lpeg" local re = require "re" local util = require "wsapi.util" local _M = {} _M._NAME = "mk.routes" _M._VERSION = "0.1" _M._COPYRIGHT = "Copyright (C) 2010 Kepler Project" _M._DESCRIPTION = "Default route parser/builder for MK" local function foldr(t, f, acc) for i = #t, 1, -1 do acc = f(t[i], acc) end return acc end local function foldl(t, f, acc) for i = 1, #t do acc = f(acc, t[i]) end return acc end local param = re.compile[[ {[/%.]} ':' {[%w_]+} &('/' / {'.'} / !.) ]] / function (prefix, name, dot) local extra = { inner = (lpeg.P(1) - lpeg.S("/" .. (dot or "")))^1, close = lpeg.P"/" + lpeg.P(dot or -1) + lpeg.P(-1) } return { cap = lpeg.Carg(1) * re.compile([[ [/%.] {%inner+} &(%close) ]], extra) / function (params, item, delim) params[name] = wsapi.util.url_decode(item) end, clean = re.compile([[ [/%.] %inner &(%close) ]], extra), tag = "param", name = name, prefix = prefix } end local opt_param = re.compile[[ {[/%.]} '?:' {[%w_]+} '?' &('/' / {'.'} / !.) ]] / function (prefix, name, dot) local extra = { inner = (lpeg.P(1) - lpeg.S("/" .. (dot or "")))^1, close = lpeg.P"/" + lpeg.P(dot or -1) + lpeg.P(-1) } return { cap = (lpeg.Carg(1) * re.compile([[ [/%.] {%inner+} &(%close) ]], extra) / function (params, item, delim) params[name] = wsapi.util.url_decode(item) end)^-1, clean = re.compile([[ [/%.] %inner &(%close) ]], extra)^-1, tag = "opt", name = name, prefix = prefix } end local splat = re.compile[[ {[/%.]} {'*'} &('/' / '.' / !.) ]] / function (prefix) return { cap = "*", tag = "splat", prefix = prefix } end local rest = lpeg.C((lpeg.P(1) - param - opt_param - splat)^1) local function fold_caps(cap, acc) if type(cap) == "string" then return { cap = lpeg.P(cap) * acc.cap, clean = lpeg.P(cap) * acc.clean } elseif cap.cap == "*" then return { cap = (lpeg.Carg(1) * (lpeg.P(cap.prefix) * lpeg.C((lpeg.P(1) - acc.clean)^0))^-1 / function (params, splat) if not params.splat then params.splat = {} end if splat and splat ~= "" then params.splat[#params.splat+1] = wsapi.util.url_decode(splat) end end) * acc.cap, clean = (lpeg.P(cap.prefix) * (lpeg.P(1) - acc.clean)^0)^-1 * acc.clean } else return { cap = cap.cap * acc.cap, clean = cap.clean * acc.clean } end end local function fold_parts(parts, cap) if type(cap) == "string" then parts[#parts+1] = { tag = "text", text = cap } else parts[#parts+1] = { tag = cap.tag, prefix = cap.prefix, name = cap.name } end return parts end local route = lpeg.Ct((param + opt_param + splat + rest)^1 * lpeg.P(-1)) / function (caps) return foldr(caps, fold_caps, { cap = lpeg.P("/")^-1 * lpeg.P(-1), clean = lpeg.P("/")^-1 * lpeg.P(-1) }), foldl(caps, fold_parts, {}) end local function build(parts, params) local res = {} local i = 1 params = params or {} params.splat = params.splat or {} for _, part in ipairs(parts) do if part.tag == "param" then if not params[part.name] then error("route parameter " .. part.name .. " does not exist") end local s = string.gsub (params[part.name], "([^%.@]+)", function (s) return wsapi.util.url_encode(s) end) res[#res+1] = part.prefix .. s elseif part.tag == "splat" then local s = string.gsub (params.splat[i] or "", "([^/%.@]+)", function (s) return wsapi.util.url_encode(s) end) res[#res+1] = part.prefix .. s i = i + 1 elseif part.tag == "opt" then if params and params[part.name] then local s = string.gsub (params[part.name], "([^%.@]+)", function (s) return wsapi.util.url_encode(s) end) res[#res+1] = part.prefix .. s end else res[#res+1] = part.text end end if #res > 0 then return table.concat(res) else return "/" end end function _M.R(path) local p, b = route:match(path) return setmetatable({ parser = p.cap, parts = b }, { __index = { match = function (t, s) local params = {} if t.parser:match(s, 1, params) then return params else return nil end end, build = function (t, params) return build(t.parts, params) end } }) end return setmetatable(_M, { __call = function (_, path) return _M.R(path) end })
lgpl-3.0
n0xus/darkstar
scripts/globals/spells/aspir.lua
18
1509
----------------------------------------- -- Spell: Aspir -- Drain functions only on skill level!! ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --calculate raw damage (unknown function -> only dark skill though) - using http://www.bluegartr.com/threads/44518-Drain-Calculations -- also have small constant to account for 0 dark skill local dmg = 5 + 0.375 * (caster:getSkillLevel(DARK_MAGIC_SKILL) + caster:getMod(79 + DARK_MAGIC_SKILL)); --get resist multiplier (1x if no resist) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),DARK_MAGIC_SKILL,1.0); --get the resisted damage dmg = dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg); --add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()); --add in final adjustments if (dmg < 0) then dmg = 0 end if (target:isUndead()) then spell:setMsg(75); -- No effect return dmg; end if (target:getMP() > dmg) then caster:addMP(dmg); target:delMP(dmg); else dmg = target:getMP(); caster:addMP(dmg); target:delMP(dmg); end return dmg; end;
gpl-3.0
kbehafarin/newfies-dialer
lua/libs/lfs_cache.lua
7
4040
-- -- Easily power a caching system based on Filesystem -- It's recommended to use ramdisk to get better performances -- @ mkdir -p /tmp/ram -- @ sudo mount -t tmpfs -o size=512M tmpfs /tmp/ram/ -- Set the CACHE_DIRECTORY setting to this directory -- -- -- Copyright (C) 2013 Arezqui Belaid <areski@gmail.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 oo = require "loop.simple" CACHE_DIRECTORY = '/tmp' LFS_Caching = oo.class{ -- default field values debugger = nil, } function LFS_Caching:__init(debugger) -- self is the class return oo.rawnew(self, { debugger = debugger, }) end -- -- Check file exists and readable function LFS_Caching:file_exists(path) local lfs = require "lfs" local attr = lfs.attributes(path) if (attr ~= nil) then return true else return false end end -- -- return a md5 file for the caching function LFS_Caching:key_filepath(key) local md5 = require "md5" return CACHE_DIRECTORY..'/'..md5.sumhexa(key) end -- get all lines from a file, returns an empty -- list/table if the file does not exist function LFS_Caching:read_from_file(file) if not self:file_exists(file) then return nil end local f = io.open(file, "rb") local content = f:read("*all") f:close() return content end -- -- Write content to file function LFS_Caching:write_to_file(path, content) local file = io.open(path, "w") file:write(content) file:close() return true end -- Creates a cache for the key with content -- key: value of the cache -- content: object # whatever is compatible function LFS_Caching:set(key, content) local path = self:key_filepath(key) local success = self:write_to_file(path, content) if not success then --print("Couldn't archive cache '%s' to '%s'", key, path) end end -- Returns contents of cache keys -- key: value of the cache -- ttl: number [optional] max age of file in seconds function LFS_Caching:get(key, ttl) local lfs = require "lfs" local path = self:key_filepath(key) if not self:file_exists(path) then return nil end if ttl then local cache_age = os.time() - lfs.attributes(path).modification if cache_age > ttl then return nil end end result = self:read_from_file(path) return result end -- -- run test -- -- if false then -- local inspect = require "inspect" -- caching = LFS_Caching(nil) -- local cmsgpack = require 'cmsgpack' -- local inspect = require 'inspect' -- value_test = {} -- value_test["1"] = "Orange" -- value_test["2"] = "Apple" -- value_test["3"] = "Carrot" -- msgpack = cmsgpack.pack(value_test) -- print(msgpack) -- print("Test Get Cache") -- res = caching:get('hashkeydb', 3) -- if not(res) then -- print("Set Cache") -- caching:set('hashkeydb', msgpack) -- else -- print(inspect(cmsgpack.unpack(res))) -- end -- end
mpl-2.0
italovieira/dotfiles
nvim/.config/nvim/lua/plugins/treesitter.lua
1
1065
require('nvim-treesitter.configs').setup { highlight = { enable = true, }, indent = { enable = true }, incremental_selection = { enable = true, }, textobjects = { select = { enable = true, lookahead = true, keymaps = { ['aa'] = '@parameter.outer', ['ia'] = '@parameter.inner', ['am'] = '@function.outer', ['im'] = '@function.inner', ['ac'] = '@class.outer', ['ic'] = '@class.inner', }, }, move = { enable = true, set_jumps = true, goto_next_start = { [']a'] = '@parameter.inner', [']]'] = '@class.outer', [']m'] = '@function.outer', }, goto_next_end = { [']M'] = '@function.outer', [']['] = '@class.outer', }, goto_previous_start = { ['[a'] = '@parameter.inner', ['[m'] = '@function.outer', ['[['] = '@class.outer', }, goto_previous_end = { ['[M'] = '@function.outer', ['[]'] = '@class.outer', }, }, }, }
mit
n0xus/darkstar
scripts/zones/Ilrusi_Atoll/Zone.lua
36
1453
----------------------------------- -- -- Zone: Ilrusi_Atoll -- zone 55 ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Ilrusi_Atoll/TextIDs"] = nil; require("scripts/zones/Ilrusi_Atoll/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; --------------RANDOMIZE COFFER------------------------ local correctcoffer = math.random(17002505,17002516); SetServerVariable("correctcoffer",correctcoffer); printf("corect_golden_salvage_coffer: %u",correctcoffer); --------------------------------------------------- return cs; 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); end;
gpl-3.0
n0xus/darkstar
scripts/globals/items/ca_cuong.lua
18
1329
----------------------------------------- -- ID: 5474 -- Item: Ca Cuong -- Food Effect: 5 Min, Mithra only ----------------------------------------- -- Dexterity +2 -- Mind -4 -- Agility +2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5474); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -4); target:addMod(MOD_AGI, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -4); target:delMod(MOD_AGI, 2); end;
gpl-3.0
n0xus/darkstar
scripts/zones/Outer_Horutoto_Ruins/npcs/_5e9.lua
17
1734
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: Gate: Magical Gizmo -- Involved In Mission: The Heart of the Matter -- @pos 584 0 -660 194 ----------------------------------- package.loaded["scripts/zones/Outer_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Outer_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Check if we are on Windurst Mission 1-2 if (player:getCurrentMission(WINDURST) == THE_HEART_OF_THE_MATTER and player:getVar("MissionStatus") == 3 and player:hasKeyItem(SOUTHEASTERN_STAR_CHARM)) then player:startEvent(0x002c); else player:messageSpecial(DOOR_FIRMLY_SHUT); end 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); -- If we just finished the cutscene for Windurst Mission 1-2 if (csid == 0x002c) then player:setVar("MissionStatus",4); player:messageSpecial(ALL_G_ORBS_ENERGIZED); -- Remove the charm that opens this door player:delKeyItem(SOUTHEASTERN_STAR_CHARM); end end;
gpl-3.0
n0xus/darkstar
scripts/zones/Al_Zahbi/npcs/Iphaaf.lua
38
1025
----------------------------------- -- Area: Al Zahbi -- NPC: Iphaaf -- Type: Mihli's Attendant -- @zone: 48 -- @pos -28.014 -7 64.371 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00fe); 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
misterdustinface/gamelib-common-polyglot
src/param-adjuster/layout-partials/color-editor.lua
1
14110
local datastore = require 'datastore' local constants = require 'constants' local widgets = require 'widgets' local style = require 'style' local fonts = require 'fonts' local rects = require 'rects' local icons = require 'icons' local new_action = require 'touch-action' local txtfield = require 'layout-partials.txt-field' local backend = require 'metasys.backend' local timers = require 'animation-timers' local text_hint = require 'layout-partials.text-hint' -- local editorTitle = { -- font = fonts["OpenSans 14"], -- text = 'hello world', -- justification = widgets.JUSTIFICATION.eCenter, -- horz_align__pct = 0.5, -- vert_align__pct = 0.5, -- } local colorName = { family = "OpenSans", size = 10, minsize = 8, -- font = fonts["OpenSans 10"], text = 'hello world', justification = widgets.JUSTIFICATION.eCenter, horz_align__pct = 0.5, vert_align__pct = 0.05, } local colorValue = { family = "OpenSans", size = 10, minsize = 8, -- font = fonts["OpenSans 10"], text = 'hello world', justification = widgets.JUSTIFICATION.eCenter, horz_align__pct = 0.5, vert_align__pct = 0.5, } local tab = {} local close_page_hintId = text_hint.register("Click to Remove Tab") local reset_value_hintId = text_hint.register("Click to Reset Value") local accept_value_hintId = text_hint.register("Click to Accept Value") local live_accept_value_hintId = text_hint.register("Right Click to Auto-Accept Values Live") local act_remove_from_editor = new_action { onPress = function(xIndex, xRelativeTouchx, xRelativeTouchy) datastore.editor_close_pressed = true local editor_index = datastore.editor_index table.remove(datastore.editor_partial_and_index, editor_index) datastore.params_by_type.color[xIndex].is_in_edit = false datastore.selectedTextField = constants.nulltextfield datastore.editor_index = math.min(#datastore.editor_partial_and_index, datastore.editor_index) datastore.has_acknowledged_hint[close_page_hintId] = true end, onRelease = function(xIndex, xRelativeTouchx, xRelativeTouchy) datastore.editor_close_pressed = false end, onInside = function(xIndex, xRelativeTouchx, xRelativeTouchy) datastore.editor_close_hover = true end, onOutside = function(xIndex) datastore.editor_close_hover = false datastore.editor_close_pressed = false text_hint.reset() end, } local act_reset_value = new_action { onPress = function(xIndex, xRelativeTouchx, xRelativeTouchy) datastore.editor_reset_pressed = true local thing = datastore.params_by_type.color[xIndex] thing.ptr.value = thing.initialval datastore.has_acknowledged_hint[reset_value_hintId] = true end, onRelease = function(xIndex, xRelativeTouchx, xRelativeTouchy) datastore.editor_reset_pressed = false end, onInside = function(xIndex, xRelativeTouchx, xRelativeTouchy) datastore.editor_reset_hover = true end, onOutside = function(xIndex) datastore.editor_reset_hover = false datastore.editor_reset_pressed = false text_hint.reset() end, } local act_accept_value = new_action { onPress = function(xIndex, xRelativeTouchx, xRelativeTouchy) datastore.editor_accept_pressed = true local thing = datastore.params_by_type.color[xIndex] local r, g, b = backend.toRGB(thing.ptr.value) thing.callback(xIndex, r, g, b) datastore.has_acknowledged_hint[accept_value_hintId] = true end, onRelease = function(xIndex, xRelativeTouchx, xRelativeTouchy) datastore.editor_accept_pressed = false end, onPressAlt = function(xIndex) datastore.editor_accept_pressed = true datastore.ACCEPT_ALL_CHANGES_LIVE = not datastore.ACCEPT_ALL_CHANGES_LIVE if datastore.has_acknowledged_hint[accept_value_hintId] then datastore.has_acknowledged_hint[live_accept_value_hintId] = true end end, onReleaseAlt = function() datastore.editor_accept_pressed = false end, onInside = function(xIndex, xRelativeTouchx, xRelativeTouchy) datastore.editor_accept_hover = true end, onOutside = function(xIndex) datastore.editor_accept_hover = false datastore.editor_accept_pressed = false text_hint.reset() end, } local act_progress_bar_red = new_action { onDrag = function(xIndex, xRelativeTouchx, xRelativeTouchy) local thing = datastore.params_by_type.color[xIndex] local range = datastore.ranges.color.r local r, g, b = backend.toRGB(thing.ptr.value) local r = math.floor(math.max(math.min(((xRelativeTouchx-10) / (rects.color_editor_r_progress_bar.w-20)), 1), 0) * (range.maxvalue - range.minvalue)) + range.minvalue if type(thing.ptr.value) == 'table' then thing.ptr.value[1] = r else thing.ptr.value = backend.toColor(r, g, b) end if datastore.ACCEPT_ALL_CHANGES_LIVE then thing.callback(xIndex, thing.ptr.value) end end, onInside = function() datastore.color_editor_red_hover = true end, onOutside = function() datastore.color_editor_red_hover = false end, } local act_progress_bar_green = new_action { onDrag = function(xIndex, xRelativeTouchx, xRelativeTouchy) local thing = datastore.params_by_type.color[xIndex] local range = datastore.ranges.color.g local g = math.floor(math.max(math.min(((xRelativeTouchx-10) / (rects.color_editor_g_progress_bar.w-20)), 1), 0) * (range.maxvalue - range.minvalue)) + range.minvalue if type(thing.ptr.value) == 'table' then thing.ptr.value[2] = g else thing.ptr.value = backend.toColor(r, g, b) end if datastore.ACCEPT_ALL_CHANGES_LIVE then thing.callback(xIndex, thing.ptr.value) end end, onInside = function() datastore.color_editor_green_hover = true end, onOutside = function() datastore.color_editor_green_hover = false end, } local act_progress_bar_blue = new_action { onDrag = function(xIndex, xRelativeTouchx, xRelativeTouchy) local thing = datastore.params_by_type.color[xIndex] local range = datastore.ranges.color.b local b = math.floor(math.max(math.min(((xRelativeTouchx-10) / (rects.color_editor_b_progress_bar.w-20)), 1), 0) * (range.maxvalue - range.minvalue)) + range.minvalue if type(thing.ptr.value) == 'table' then thing.ptr.value[3] = b else thing.ptr.value = backend.toColor(r, g, b) end if datastore.ACCEPT_ALL_CHANGES_LIVE then thing.callback(xIndex, thing.ptr.value) end end, onInside = function() datastore.color_editor_blue_hover = true end, onOutside = function() datastore.color_editor_blue_hover = false end, } tab.render = function(xTouchmap, index, x, y) if not index then return end local thing = datastore.params_by_type.color[index] love.graphics.setColor(unpack(style.element)) if thing.isPressed then love.graphics.setColor(unpack(style.selected)) end love.graphics.rectangle('fill', x, y, rects.editor.w, rects.editor.h) if datastore.paging_bar.isHovering then love.graphics.setColor(unpack(style.highlighted)) else love.graphics.setColor(unpack(style.background_separator)) end love.graphics.rectangle("fill", rects.editor_paging_bar.x, rects.editor_paging_bar.y, rects.editor_paging_bar.w, rects.editor_paging_bar.h) local value = thing.ptr.value local r, g, b = backend.toRGB(value) love.graphics.setColor(r, g, b) local demo_x = rects.color_editor_demo.x local demo_y = rects.color_editor_demo.y local demo_r = rects.color_editor_demo.h love.graphics.circle('fill', demo_x, demo_y, demo_r) local rect = rects.color_editor_r_progress_bar local range = datastore.ranges.color.r widgets.drawProgressBar( rect.x, rect.y, rect.w, rect.h, (r - range.minvalue) / (range.maxvalue - range.minvalue), style.progress_bar_red_background, style.progress_bar_red_foreground ) xTouchmap.append(rect.x, rect.y, rect.w, rect.h, act_progress_bar_red, index) if not datastore.color_editor_red_hover then love.graphics.setColor(style.progress_bar_red_background) love.graphics.rectangle("line", rect.x, rect.y, rect.w, rect.h) end local rect = rects.color_editor_g_progress_bar local range = datastore.ranges.color.g widgets.drawProgressBar( rect.x, rect.y, rect.w, rect.h, (g - range.minvalue) / (range.maxvalue - range.minvalue), style.progress_bar_green_background, style.progress_bar_green_foreground ) xTouchmap.append(rect.x, rect.y, rect.w, rect.h, act_progress_bar_green, index) if not datastore.color_editor_green_hover then love.graphics.setColor(style.progress_bar_green_background) love.graphics.rectangle("line", rect.x, rect.y, rect.w, rect.h) end local rect = rects.color_editor_b_progress_bar local range = datastore.ranges.color.b widgets.drawProgressBar( rect.x, rect.y, rect.w, rect.h, (b - range.minvalue) / (range.maxvalue - range.minvalue), style.progress_bar_blue_background, style.progress_bar_blue_foreground ) xTouchmap.append(rect.x, rect.y, rect.w, rect.h, act_progress_bar_blue, index) if not datastore.color_editor_blue_hover then love.graphics.setColor(style.progress_bar_blue_background) love.graphics.rectangle("line", rect.x, rect.y, rect.w, rect.h) end love.graphics.setColor(unpack(style.element_text)) colorName.text = thing.name widgets.drawTextWithin(colorName, x, y, rects.editor.w, rects.editor.h) -- colorValue.text = thing.ptr.value -- widgets.drawTextWithin(colorValue, x, y, rects.editor.w, rects.editor.h) -- txtfield.render(xTouchmap, 3, -- x + (rects.editor.w - txtfield.horizontal_offset()) / 2, -- y + (rects.editor.h - txtfield.vertical_offset()) / 2 + txtfield.vertical_offset(), colorValue -- ); love.graphics.setColor(unpack(style.element_text)) colorValue.text = r widgets.drawTextWithin(colorValue, rects.color_editor_r_text.x, rects.color_editor_r_text.y, rects.color_editor_r_text.w, rects.color_editor_r_text.h) colorValue.text = g widgets.drawTextWithin(colorValue, rects.color_editor_g_text.x, rects.color_editor_g_text.y, rects.color_editor_g_text.w, rects.color_editor_g_text.h) colorValue.text = b widgets.drawTextWithin(colorValue, rects.color_editor_b_text.x, rects.color_editor_b_text.y, rects.color_editor_b_text.w, rects.color_editor_b_text.h) if datastore.editor_close_pressed then love.graphics.setColor(unpack(style.editor_close_button_pressed)) elseif datastore.editor_close_hover then love.graphics.setColor(unpack(style.editor_close_button_hover)) else love.graphics.setColor(unpack(style.editor_close_button)) end love.graphics.rectangle('fill', rects.editor_close_button.x, rects.editor_close_button.y, rects.editor_close_button.w, rects.editor_close_button.h) love.graphics.setColor(unpack(style.element_text)) icons.drawX(rects.editor_close_button.x, rects.editor_close_button.y, rects.editor_close_button.w, rects.editor_close_button.h) if datastore.editor_reset_pressed then love.graphics.setColor(unpack(style.editor_reset_button_pressed)) elseif datastore.editor_reset_hover then love.graphics.setColor(unpack(style.editor_reset_button_hover)) else love.graphics.setColor(unpack(style.editor_reset_button)) end love.graphics.rectangle('fill', rects.editor_reset_button.x, rects.editor_reset_button.y, rects.editor_reset_button.w, rects.editor_reset_button.h) love.graphics.setColor(unpack(style.element_text)) icons.drawReset(rects.editor_reset_button.x, rects.editor_reset_button.y, rects.editor_reset_button.w, rects.editor_reset_button.h) if datastore.editor_accept_pressed then love.graphics.setColor(unpack(style.editor_accept_button_pressed)) elseif datastore.editor_accept_hover then love.graphics.setColor(unpack(style.editor_accept_button_hover)) else love.graphics.setColor(unpack(style.editor_accept_button)) end love.graphics.rectangle('fill', rects.editor_accept_button.x, rects.editor_accept_button.y, rects.editor_accept_button.w, rects.editor_accept_button.h) if datastore.ACCEPT_ALL_CHANGES_LIVE then love.graphics.setColor(unpack(style.editor_accept_button_hover)) love.graphics.rectangle('line', rects.editor_accept_button.x, rects.editor_accept_button.y, rects.editor_accept_button.w, rects.editor_accept_button.h) end love.graphics.setColor(unpack(style.element_text)) icons.drawCheck(rects.editor_accept_button.x, rects.editor_accept_button.y, rects.editor_accept_button.w, rects.editor_accept_button.h) if datastore.editor_close_hover then text_hint.render_left(xTouchmap, rects.editor_close_button.x, rects.editor_close_button.y, close_page_hintId) end if datastore.editor_reset_hover then text_hint.render_left(xTouchmap, rects.editor_reset_button.x, rects.editor_reset_button.y, reset_value_hintId) end if datastore.editor_accept_hover then if datastore.has_acknowledged_hint[accept_value_hintId] then text_hint.render_left(xTouchmap, rects.editor_accept_button.x, rects.editor_accept_button.y, live_accept_value_hintId) else text_hint.render_left(xTouchmap, rects.editor_accept_button.x, rects.editor_accept_button.y, accept_value_hintId) end end xTouchmap.append(rects.editor_close_button.x, rects.editor_close_button.y, rects.editor_close_button.w, rects.editor_close_button.h, act_remove_from_editor, index) xTouchmap.append(rects.editor_reset_button.x, rects.editor_reset_button.y, rects.editor_reset_button.w, rects.editor_reset_button.h, act_reset_value, index) xTouchmap.append(rects.editor_accept_button.x, rects.editor_accept_button.y, rects.editor_accept_button.w, rects.editor_accept_button.h, act_accept_value, index) end tab.vertical_offset = function() return rects.editor.h end tab.horizontal_offset = function() return rects.editor.w end return tab
gpl-2.0
n0xus/darkstar
scripts/globals/items/silkworm_egg.lua
36
1132
----------------------------------------- -- ID: 4526 -- Item: Silkworm Egg -- Food Effect: 5 Mins, All Races ----------------------------------------- -- HP 12 -- MP 12 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4526); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 12); target:addMod(MOD_MP, 12); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 12); target:delMod(MOD_MP, 12); end;
gpl-3.0
n0xus/darkstar
scripts/globals/spells/bluemagic/poison_breath.lua
18
2069
----------------------------------------- -- Spell: Poison Breath -- Deals water damage to enemies within a fan-shaped area originating from the caster. Additional effect: Poison -- Spell cost: 22 MP -- Monster Type: Hound -- Spell Type: Magical (Water) -- Blue Magic Points: 1 -- Stat Bonus: MND+1 -- Level: 22 -- Casting Time: 3 seconds -- Recast Time: 19.5 seconds -- Magic Bursts on: Reverberation, Distortion, and Darkness -- Combos: Clear Mind ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0); local multi = 1.08; local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.multiplier = multi; params.tMultiplier = 1.5; params.duppercap = 69; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0; damage = BlueMagicalSpell(caster, target, spell, params, MND_BASED); damage = BlueFinalAdjustments(caster, target, spell, damage, params); if (caster:hasStatusEffect(EFFECT_AZURE_LORE)) then multi = multi + 0.50; end if (damage > 0 and resist > 0.3) then local typeEffect = EFFECT_POISON; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,3,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
kurthuwig/faces
Watchfaces/mak_mark/x_ray/face.lua
1
1424
-- This file is part of the Watchfaces project. -- Read the file README.md for copyright and other information function about() local result = {} result.author = "Mak Mark" result.name = "X-Ray" return result end function init() local atlas = face:loadAtlas('all.atlas') face:add(atlas:createSprite('bottom_layer')) bigGear = atlas:createIndexedSprite('big_gear') bigGear:setPosition(115, 79) face:add(bigGear); middleGear = atlas:createIndexedSprite('middle_gear') middleGear:setPosition(47, 128) face:add(middleGear) littleGear = atlas:createIndexedSprite('little_gear') littleGear:setPosition(81, 35) face:add(littleGear) face:add(atlas:createSprite('top_layer')) hourHand = atlas:createSprite('hour_hand') hourHand:setPivot(11.4, 106) hourHand:setPosition(120, 120) face:add(hourHand) minuteHand = atlas:createSprite('minute_hand') minuteHand:setPivot(11.4, 106) minuteHand:setPosition(120, 120) face:add(minuteHand) end function update() local hour = time:get(Calendar.HOUR) local minute = time:get(Calendar.MINUTE) local second = time:get(Calendar.SECOND) bigGear :setIndex(second % 3) middleGear:setIndex(second % 3) littleGear:setIndex((second / 2) % 3) hourHand :setRotation(360 / 12 * (hour + minute / 60)) minuteHand:setRotation(360 / 60 * (minute + second / 60)) end
apache-2.0
tossp/lede-k3
package/lean/luci-app-n2n_v2/luasrc/model/cbi/n2n_v2.lua
2
3362
--[[ --N2N VPN(V2) configuration page. Made by 981213 -- ]] -- local fs = require "nixio.fs" function get_mask(v) v:value("16", "255.255.0.0(16)") v:value("17", "255.255.128.0(17)") v:value("18", "255.255.192.0(18)") v:value("19", "255.255.224.0(19)") v:value("20", "255.255.240.0(20)") v:value("21", "255.255.248.0(21)") v:value("22", "255.255.252.0(22)") v:value("23", "255.255.254.0(23)") v:value("24", "255.255.255.0(24)") v:value("25", "255.255.255.128(25)") v:value("26", "255.255.255.192(26)") v:value("27", "255.255.255.224(27)") v:value("28", "255.255.255.240(28)") v:value("29", "255.255.255.248(29)") v:value("30", "255.255.255.252(30)") end m = Map("n2n_v2", translate("N2N v2 VPN"), translatef( "n2n is a layer-two peer-to-peer virtual private network (VPN) which allows users to exploit features typical of P2P applications at network instead of application level.")) -- Basic config -- edge m:section(SimpleSection).template = "n2n_v2/status" s = m:section(TypedSection, "edge", translate("N2N Edge Settings")) s.anonymous = true s.addremove = true switch = s:option(Flag, "enabled", translate("Enable")) switch.rmempty = false tunname = s:option(Value, "tunname", translate("TUN desvice name")) tunname.optional = false mode = s:option(ListValue, "mode", translate("Interface mode")) mode:value("dhcp") mode:value("static") ipaddr = s:option(Value, "ipaddr", translate("Interface IP address")) ipaddr.optional = false ipaddr.datatype = "ip4addr" ipaddr:depends("mode", "static") prefix = s:option(ListValue, "prefix", translate("Interface netmask")) get_mask(prefix) prefix.optional = false prefix:depends("mode", "static") mtu = s:option(Value, "mtu", translate("MTU")) mtu.datatype = "range(1,1500)" mtu.optional = false supernode = s:option(Value, "supernode", translate("Supernode Host")) supernode.datatype = "host" supernode.optional = false port = s:option(Value, "port", translate("Supernode Port")) port.datatype = "port" port.optional = false community = s:option(Value, "community", translate("N2N Community name")) community.optional = false s:option(Value, "key", translate("Encryption key")) route = s:option(Flag, "route", translate("Enable packet forwarding")) route.rmempty = false -- supernode s = m:section(TypedSection, "supernode", translate("N2N Supernode Settings")) s.anonymous = true s.addremove = true switch = s:option(Flag, "enabled", translate("Enable")) switch.rmempty = false port = s:option(Value, "port", translate("Port")) port.datatype = "port" port.optional = false -- Static route s = m:section(TypedSection, "route", translate("N2N routes"), translate("Static route for n2n interface")) s.anonymous = true s.addremove = true s.template = "cbi/tblsection" ---- enable switch = s:option(Flag, "enabled", translate("Enable")) switch.rmempty = false ---- IP address o = s:option(Value, "ip", translate("IP")) o.optional = false o.datatype = "ip4addr" o.rmempty = false ---- IP mask o = s:option(ListValue, "mask", translate("Mask")) o.optional = false get_mask(o) o.default = "24" ---- Gateway o = s:option(Value, "gw", translate("Gateway")) o.optional = false o.datatype = "ip4addr" o.rmempty = false ---- Description o = s:option(Value, "desc", translate("Description")) o.optional = false return m
gpl-2.0
ppriest/mame
3rdparty/genie/tests/actions/codeblocks/codeblocks_files.lua
21
1664
-- -- tests/actions/codeblocks/codeblocks_files.lua -- Validate generation of files block in CodeLite C/C++ projects. -- Copyright (c) 2011 Jason Perkins and the Premake project -- T.codeblocks_files = { } local suite = T.codeblocks_files local codeblocks = premake.codeblocks -- -- Setup -- local sln, prj function suite.setup() sln = test.createsolution() end local function prepare() premake.bake.buildconfigs() prj = premake.solution.getproject(sln, 1) codeblocks.files(prj) end -- -- Test grouping and nesting -- function suite.SimpleSourceFile() files { "hello.cpp" } prepare() test.capture [[ <Unit filename="hello.cpp"> </Unit> ]] end function suite.SingleFolderLevel() files { "src/hello.cpp" } prepare() test.capture [[ <Unit filename="src/hello.cpp"> </Unit> ]] end function suite.MultipleFolderLevels() files { "src/greetings/hello.cpp" } prepare() test.capture [[ <Unit filename="src/greetings/hello.cpp"> </Unit> ]] end -- -- Test source file type handling -- function suite.CFileInCppProject() files { "hello.c" } prepare() test.capture [[ <Unit filename="hello.c"> <Option compilerVar="CC" /> </Unit> ]] end function suite.WindowsResourceFile() files { "hello.rc" } prepare() test.capture [[ <Unit filename="hello.rc"> <Option compilerVar="WINDRES" /> </Unit> ]] end function suite.PchFile() files { "hello.h" } pchheader "hello.h" prepare() test.capture [[ <Unit filename="hello.h"> <Option compilerVar="CPP" /> <Option compile="1" /> <Option weight="0" /> <Add option="-x c++-header" /> </Unit> ]] end
gpl-2.0
Python1320/wire
lua/entities/gmod_wire_screen.lua
4
6177
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Screen" ENT.WireDebugName = "Screen" function ENT:SetDisplayA( float ) self:SetNetworkedBeamFloat( 1, float, true ) end function ENT:SetDisplayB( float ) self:SetNetworkedBeamFloat( 2, float, true ) end function ENT:GetDisplayA( ) return self:GetNetworkedBeamFloat( 1 ) end function ENT:GetDisplayB( ) return self:GetNetworkedBeamFloat( 2 ) end -- Extra stuff for Wire Screen (TheApathetic) function ENT:SetSingleValue(singlevalue) self:SetNWBool("SingleValue",singlevalue) -- Change inputs if necessary if (singlevalue) then WireLib.AdjustInputs(self, {"A"}) else WireLib.AdjustInputs(self, {"A","B"}) end end function ENT:GetSingleValue() return self:GetNetworkedBool("SingleValue") end function ENT:SetSingleBigFont(singlebigfont) self:SetNWBool("SingleBigFont",singlebigfont) end function ENT:GetSingleBigFont() return self:GetNetworkedBool("SingleBigFont") end function ENT:SetTextA(text) self:SetNWString("TextA",text) end function ENT:GetTextA() return self:GetNetworkedString("TextA") end function ENT:SetTextB(text) self:SetNWString("TextB",text) end function ENT:GetTextB() return self:GetNWString("TextB") end function ENT:SetLeftAlign(leftalign) self:SetNWBool("LeftAlign",leftalign) end function ENT:GetLeftAlign() return self:GetNWBool("LeftAlign") end function ENT:SetFloor(Floor) self:SetNWBool("Floor",Floor) end function ENT:GetFloor() return self:GetNWBool("Floor") end function ENT:SetFormatNumber( FormatNumber ) self:SetNWBool( "FormatNumber", FormatNumber ) end function ENT:GetFormatNumber() return self:GetNWBool("FormatNumber") end function ENT:SetFormatTime( FormatTime ) self:SetNWBool( "FormatTime", FormatTime ) end function ENT:GetFormatTime() return self:GetNWBool("FormatTime") end if CLIENT then function ENT:Initialize() self.GPU = WireGPU(self, true) end function ENT:OnRemove() self.GPU:Finalize() end local header_color = Color(100,100,150,255) local text_color = Color(255,255,255,255) local background_color = Color(0,0,0,255) local large_font = "Trebuchet36" local small_font = "Trebuchet18" local value_large_font = "screen_font_single" local value_small_font = "screen_font" local small_height = 20 local large_height = 40 function ENT:DrawNumber( header, value, x,y,w,h ) local header_height = small_height local header_font = small_font local value_font = value_small_font if self:GetSingleValue() and self:GetSingleBigFont() then header_height = large_height header_font = large_font value_font = value_large_font end surface.SetDrawColor( header_color ) surface.DrawRect( x, y, w, header_height ) surface.SetFont( header_font ) surface.SetTextColor( text_color ) local _w,_h = surface.GetTextSize( header ) surface.SetTextPos( x + w / 2 - _w / 2, y + 2 ) surface.DrawText( header, header_font ) if self:GetFormatTime() then -- format as time, aka duration - override formatnumber and floor settings value = WireLib.nicenumber.nicetime( value ) elseif self:GetFormatNumber() then if self:GetFloor() then value = WireLib.nicenumber.format( math.floor( value ), 1 ) else value = WireLib.nicenumber.formatDecimal( value ) end elseif self:GetFloor() then value = "" .. math.floor( value ) else -- note: loses precision after ~7 decimals, so don't bother displaying more value = "" .. math.floor( value * 10000000 ) / 10000000 end local align = self:GetLeftAlign() and 0 or 1 surface.SetFont( value_font ) local _w,_h = surface.GetTextSize( value ) surface.SetTextPos( x + (w / 2 - _w / 2) * align, y + header_height ) surface.DrawText( value ) end function ENT:Draw() self:DrawModel() self.GPU:RenderToWorld(nil, 188, function(x, y, w, h) surface.SetDrawColor(background_color) surface.DrawRect(x, y, w, h) if self:GetSingleValue() then self:DrawNumber( self:GetTextA(), self:GetDisplayA(), x,y,w,h ) else local h = h/2 self:DrawNumber( self:GetTextA(), self:GetDisplayA(), x,y,w,h ) self:DrawNumber( self:GetTextB(), self:GetDisplayB(), x,y+h,w,h ) end end) Wire_Render(self) end function ENT:IsTranslucent() return true end local fontData = { font = "coolvetica", size = 64, weight = 400, antialias = false, additive = false, } surface.CreateFont("screen_font", fontData ) fontData.size = 128 surface.CreateFont("screen_font_single", fontData ) fontData.size = 36 surface.CreateFont("Trebuchet36", fontData ) return -- No more client end -- Server function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = WireLib.CreateInputs(self, { "A", "B" }) self.ValueA = 0 self.ValueB = 0 end function ENT:Think() if self.ValueA then self:SetDisplayA( self.ValueA ) self.ValueA = nil end if self.ValueB then self:SetDisplayB( self.ValueB ) self.ValueB = nil end self:NextThink(CurTime() + 0.05) return true end function ENT:TriggerInput(iname, value) if (iname == "A") then self.ValueA = value elseif (iname == "B") then self.ValueB = value end end function ENT:Setup(SingleValue, SingleBigFont, TextA, TextB, LeftAlign, Floor, FormatNumber, FormatTime) --for duplication self.SingleValue = SingleValue self.SingleBigFont = SingleBigFont self.TextA = TextA self.TextB = TextB self.LeftAlign = LeftAlign self.Floor = Floor self.FormatNumber = FormatNumber self.FormatTime = FormatTime -- Extra stuff for Wire Screen (TheApathetic) self:SetTextA(TextA) self:SetTextB(TextB) self:SetSingleBigFont(SingleBigFont) --LeftAlign (TAD2020) self:SetLeftAlign(LeftAlign) --Floor (TAD2020) self:SetFloor(Floor) --Put it here to update inputs if necessary (TheApathetic) self:SetSingleValue(SingleValue) -- Auto formatting (Divran) self:SetFormatNumber( FormatNumber ) self:SetFormatTime( FormatTime ) end duplicator.RegisterEntityClass("gmod_wire_screen", WireLib.MakeWireEnt, "Data", "SingleValue", "SingleBigFont", "TextA", "TextB", "LeftAlign", "Floor", "FormatNumber", "FormatTime")
apache-2.0
n0xus/darkstar
scripts/globals/spells/hojo_ni.lua
18
1160
----------------------------------------- -- Spell: Hojo:Ni -- Description: Inflicts Slow on target. -- Edited from slow.lua ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); --Power for Hojo is a flat 19.5% reduction local power = 200; --Duration and Resistance calculation local duration = 300 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0); --Calculates the resist chance from Resist Blind trait if (math.random(0,100) >= target:getMod(MOD_SLOWRES)) then -- Spell succeeds if a 1 or 1/2 resist check is achieved if (duration >= 150) then if (target:addStatusEffect(EFFECT_SLOW,power,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end else spell:setMsg(284); end return EFFECT_SLOW; end;
gpl-3.0
n0xus/darkstar
scripts/zones/West_Sarutabaruta_[S]/Zone.lua
28
1343
----------------------------------- -- -- Zone: West_Sarutabaruta_[S] (95) -- ----------------------------------- package.loaded["scripts/zones/West_Sarutabaruta_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/West_Sarutabaruta_[S]/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(320.018,-6.684,-45.166,189); end return cs; 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); end;
gpl-3.0
rekotc/game-engine-demo
Source/GCC4/3rdParty/luaplus51-all/Src/Modules/wsapi/src/wsapi/mock.lua
2
4329
----------------------------------------------------------------------------- -- Mock WSAPI handler for Unit testing -- -- Author: Norman Clarke -- Copyright (c) 2010 Kepler Project -- ----------------------------------------------------------------------------- module(..., package.seeall) local common = require "wsapi.common" local request = require "wsapi.request" -- Build a request that looks like something that would come from a real web -- browser. local function build_request(method, path, headers) local req = { GATEWAY_INTERFACE = "CGI/1.1", HTTP_ACCEPT = "application/xml,application/xhtml+xml,text/html;q=0.9," .. "text/plain;q=0.8,image/png,*/*;q=0.5", HTTP_ACCEPT_CHARSET = "ISO-8859-1,utf-8;q=0.7,*;q=0.3", HTTP_ACCEPT_ENCODING = "gzip,deflate,sdch", HTTP_ACCEPT_LANGUAGE = "en-US,en;q=0.8", HTTP_CACHE_CONTROL = "max-age=0", HTTP_CONNECTION = "keep-alive", HTTP_HOST = "127.0.0.1:80", HTTP_USER_AGENT = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X " .. "10_6_4; en-US) AppleWebKit/534.3 (KHTML, like Gecko) " .. "Chrome/6.0.472.55", HTTP_VERSION = "HTTP/1.1", REMOTE_ADDR = "127.0.0.1", REMOTE_HOST = "localhost", SCRIPT_NAME = "wsapi_test", SERVER_NAME = "localhost", SERVER_PORT = "80", SERVER_PROTOCOL = "HTTP/1.1" } req.PATH_INFO = path req.REQUEST_METHOD = method:upper() req.METHOD = req.REQUEST_METHOD req.REQUEST_PATH = "/" if req.PATH_INFO == "" then req.PATH_INFO = "/" end for k, v in pairs(headers or {}) do req[k] = v end -- allow case-insensitive table key access setmetatable(req, {__index = function(t, k) return rawget(t, string.upper(k)) end}) return req end -- Override common's output handler to avoid writing headers -- in the reponse body. function common.send_output(out, status, headers, res_iter, write_method,res_line) common.send_content(out, res_iter, out:write()) end -- Mock IO objects local function make_io_object(content) local receiver = { buffer = content or "", bytes_read = 0 } function receiver:write(content) self.buffer = self.buffer .. content end function receiver:read(len) len = len or (#self.buffer - self.bytes_read) if self.bytes_read >= #self.buffer then return nil end local s = self.buffer:sub(self.bytes_read + 1, len) self.bytes_read = self.bytes_read + len if self.bytes_read > #self.buffer then self.bytes_read = #self.buffer end return s end function receiver:clear() self.buffer = "" self.bytes_read = 0 end function receiver:reset() self.bytes_read = 0 end return receiver end -- Build a GET request local function build_get(path, params, headers) local req = build_request("GET", path, headers) req.QUERY_STRING = request.methods.qs_encode(nil, params) req.REQUEST_URI = "http://" .. req.HTTP_HOST .. req.PATH_INFO .. req.QUERY_STRING return { env = req, input = make_io_object(), output = make_io_object(), error = io.stderr } end local function build_post(path, params, headers) local req = build_request("POST", path, headers) local body = request.methods.qs_encode(nil, params):gsub("^?", "") req.REQUEST_URI = "http://" .. req.HTTP_HOST .. req.PATH_INFO req.CONTENT_TYPE = "x-www-form-urlencoded" req.CONTENT_LENGTH = #body return { env = req, input = make_io_object(body), output = make_io_object(), error = make_io_object() } end local function make_request(request_builder, app, path, params, headers) local wsapi_env = request_builder(path, params, headers) local response = {} response.code, response.headers = wsapi.common.run(app, wsapi_env) response.body = wsapi_env.output:read() return response, wsapi_env.env end local function get(self, path, params, headers) return make_request(build_get, self.app, path, params, headers) end local function post(self, path, params, headers) return make_request(build_post, self.app, path, params, headers) end --- Creates a WSAPI handler for testing. -- @param app The WSAPI application you want to test. function make_handler(app) return { app = app, get = get, post = post } end
lgpl-3.0
n0xus/darkstar
scripts/zones/Pashhow_Marshlands/npcs/Tahmasp.lua
17
1877
----------------------------------- -- Area: Pashhow Marshlands -- NPC: Tahmasp -- Type: Outpost Vendor -- @pos 464 24 416 109 ----------------------------------- package.loaded["scripts/zones/Pashhow_Marshlands/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); require("scripts/zones/Pashhow_Marshlands/TextIDs"); local region = DERFLAND; local csid = 0x7ff4; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local owner = GetRegionOwner(region); local arg1 = getArg1(owner,player); if (owner == player:getNation()) then nation = 1; elseif (arg1 < 1792) then nation = 2; else nation = 0; end player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP()); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if (option == 1) then ShowOPVendorShop(player); elseif (option == 2) then if (player:delGil(OP_TeleFee(player,region))) then toHomeNation(player); end elseif (option == 6) then player:delCP(OP_TeleFee(player,region)); toHomeNation(player); end end;
gpl-3.0
feiying1460/witi-openwrt
package/ramips/ui/luci-mtk/src/modules/admin-full/luasrc/controller/admin/uci.lua
85
1975
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.admin.uci", package.seeall) function index() local redir = luci.http.formvalue("redir", true) or luci.dispatcher.build_url(unpack(luci.dispatcher.context.request)) entry({"admin", "uci"}, nil, _("Configuration")) entry({"admin", "uci", "changes"}, call("action_changes"), _("Changes"), 40).query = {redir=redir} entry({"admin", "uci", "revert"}, call("action_revert"), _("Revert"), 30).query = {redir=redir} entry({"admin", "uci", "apply"}, call("action_apply"), _("Apply"), 20).query = {redir=redir} entry({"admin", "uci", "saveapply"}, call("action_apply"), _("Save &#38; Apply"), 10).query = {redir=redir} end function action_changes() local uci = luci.model.uci.cursor() local changes = uci:changes() luci.template.render("admin_uci/changes", { changes = next(changes) and changes }) end function action_apply() local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local changes = uci:changes() local reload = {} -- Collect files to be applied and commit changes for r, tbl in pairs(changes) do table.insert(reload, r) if path[#path] ~= "apply" then uci:load(r) uci:commit(r) uci:unload(r) end end luci.template.render("admin_uci/apply", { changes = next(changes) and changes, configs = reload }) end function action_revert() local uci = luci.model.uci.cursor() local changes = uci:changes() -- Collect files to be reverted for r, tbl in pairs(changes) do uci:load(r) uci:revert(r) uci:unload(r) end luci.template.render("admin_uci/revert", { changes = next(changes) and changes }) end
gpl-2.0
n0xus/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Kubhe_Ijyuhla.lua
17
2433
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Kubhe Ijyuhla -- Standard Info NPC -- @pos 23.257 0.000 21.532 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local threeMenProg = player:getVar("threemenandaclosetCS"); local threeMenQuest = player:getQuestStatus(AHT_URHGAN,THREE_MEN_AND_A_CLOSET); if (player:getQuestStatus(AHT_URHGAN,GOT_IT_ALL) == QUEST_COMPLETED and threeMenQuest == QUEST_AVAILABLE) then player:startEvent(0x0344); elseif (threeMenProg == 2) then player:startEvent(0x0345); elseif (threeMenProg == 3) then player:startEvent(0x0346); elseif (threeMenProg == 4) then player:startEvent(0x0347); elseif (threeMenProg == 5) then player:startEvent(0x034a); elseif (threeMenProg == 6) then player:startEvent(0x034d); elseif (threeMenQuest == QUEST_COMPLETED) then player:startEvent(0x034e); 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); if (csid == 0x0344) then player:addQuest(AHT_URHGAN,THREE_MEN_AND_A_CLOSET); player:setVar("threemenandaclosetCS",2); elseif (csid == 0x0346) then player:setVar("threemenandaclosetCS",4); elseif (csid == 0x034d) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2184); else player:setVar("threemenandaclosetCS",0); player:addItem(2184,1); player:messageSpecial(ITEM_OBTAINEDX,2184,1); player:completeQuest(AHT_URHGAN,THREE_MEN_AND_A_CLOSET); end end end;
gpl-3.0
n0xus/darkstar
scripts/zones/Cloister_of_Frost/mobs/Shiva_Prime.lua
18
1818
----------------------------------- -- Area: Cloister of Frost -- NPC: Shiva Prime -- Involved in Quest: Trial by Ice -- Involved in Mission: ASA-4 Sugar Coated Directive ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/status"); ----------------------------------- -- OnMobFight Action ----------------------------------- function onMobFight(mob, target) local mobId = mob:getID(); -- ASA-4: Astral Flow Behavior - Guaranteed to Use At Least 5 times before killable, at specified intervals. if (mob:getBattlefield():getBcnmID()==484 and GetMobAction(mobId) == ACTION_ATTACK) then local astralFlows = mob:getLocalVar("astralflows"); local hpPercent = math.floor(mob:getHP() / mob:getMaxHP() * 100); if ((astralFlows==0 and hpPercent <= 80) or (astralFlows==1 and hpPercent <= 60) or (astralFlows==2 and hpPercent <= 40) or (astralFlows==3 and hpPercent <= 20) or (astralFlows==4 and hpPercent <= 1)) then mob:useMobAbility(628); astralFlows = astralFlows + 1; mob:setLocalVar("astralflows",astralFlows); if (astralFlows>=5) then mob:setUnkillable(false); end end end end; ----------------------------------- -- OnMobSpawn Action ----------------------------------- function onMobSpawn(mob) -- ASA-4: Avatar is Unkillable Until Its Used Astral Flow At Least 5 times At Specified Intervals if (mob:getBattlefield():getBcnmID()==484) then mob:setLocalVar("astralflows","0"); mob:setUnkillable(true); end end; ----------------------------------- -- OnMobDeath Action ----------------------------------- function onMobDeath(mob,killer) end;
gpl-3.0
n0xus/darkstar
scripts/zones/Port_San_dOria/npcs/_6g7.lua
17
1145
----------------------------------- -- Area: Port San d'Oria -- NPC: Door: Arrivals Entrance -- @zone 232 -- @pos -24 -8 15 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getZPos() >= 12) then player:startEvent(0x0206); end 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
n0xus/darkstar
scripts/zones/Dynamis-Beaucedine/bcnms/dynamis_beaucedine.lua
16
1101
----------------------------------- -- Area: Dynamis Beaucedine -- Name: Dynamis Beaucedine ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[DynaBeaucedine]UniqueID",player:getDynamisUniqueID(1284)); SetServerVariable("[DynaBeaucedine]Already_Received",0); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("DynamisID",GetServerVariable("[DynaBeaucedine]UniqueID")); local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay) then player:setVar("dynaWaitxDay",realDay); end end; -- Leaving the Dynamis by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then SetServerVariable("[DynaBeaucedine]UniqueID",0); end end;
gpl-3.0
jwngr/rusticcitrus
corona_rc/gameList.lua
1
12528
----------------------------------------------------------------------------------------- -- -- gameList.lua -- -- A list of all the logged in user's multiplayer games -- ----------------------------------------------------------------------------------------- -- Include the necessary modules local storyboard = require("storyboard") local widget = require("widget") local json = require("json") --local facebook = require("facebook") -- Create a new storyboard scene local scene = storyboard.newScene() --local facebookAppId = "372025176196549" ----------------------------------------------------------------------------------------- ------------------------- -- SCENE TRANSITIONS -- ------------------------- --[[ Activates the game scoreboard scene when a game list item is tapped ]]-- local function activateGameScoreboard(event) -- If the event has ended, activate the game scoreboard scene if (event.phase == "ended") then local transitionOptions = { effect = "slideLeft", time = 500, params = { gameId = event.target.gameId } } -- Activate the game scoreboard scene storyboard.gotoScene("scoreboard", transitionOptions) -- Otherwise, if the finger has moved, pass focus to the scroll view elseif (event.phase == "moved") then local dx = math.abs(event.x - event.xStart) local dy = math.abs(event.y - event.yStart) if ((dx > 5) or (dy > 5)) then scrollView:takeFocus(event) end end -- Return true to indicate a successful touch return true end --[[ Activates the main menu scene when the "Main Menu" button is pressed ]]-- local function activateMainMenuScene(event) local transitionOptions = { effect = "slideRight", time = 500 } -- Activate the main menu scene storyboard.gotoScene("mainMenu", transitionOptions) -- Return true to indicate a successful touch return true end ----------------------------------------------------------------------------------------- ------------------------------- -- SCENE DRAWING FUNCTIONS -- ------------------------------- --[[ Draws the opponent picture ]]-- local function drawOpponentPicture(event) -- If there is an error, print it if (event.isError) then print ("Error: download failed in drawOpponentPicture()") -- Otherwise, draw the opponent picture else -- Get the downloaded opponent picture local opponentPicture = event.target -- Update the opponent picture's x- and y-coordinates opponentPicture.x = opponentPicture.x - (opponentPicture.width / 2) + 30 opponentPicture.y = opponentPicture.y - (opponentPicture.height / 2) + 30 -- Update the opponent picture's width and height opponentPicture.width, opponentPicture.height = 50, 50 -- Add the opponent picture to the scroll view scrollView:insert(opponentPicture) end end --[[ Draws a header for a list of games ]]-- local function drawGameListSectionHeader(text, yCoord) -- Section header rectangle local gameListSectionHeaderRectangle = display.newRoundedRect(10, yCoord, 150, 30, 5) gameListSectionHeaderRectangle:setFillColor(255, 140, 0) gameListSectionHeaderRectangle.strokeWidth = 1 gameListSectionHeaderRectangle:setStrokeColor(0, 0, 0) gameListSectionHeaderRectangle:setReferencePoint(display.CenterReferencePoint) -- Section header text local gameListSectionHeaderText = display.newText(text, 10, yCoord, "Helvetica", 20) gameListSectionHeaderText:setTextColor(0, 0, 0) gameListSectionHeaderText:setReferencePoint(display.CenterReferencePoint) gameListSectionHeaderText.x = gameListSectionHeaderRectangle.x gameListSectionHeaderText.y = gameListSectionHeaderRectangle.y -- Insert the section header rectangle and text into the scroll view scrollView:insert(gameListSectionHeaderRectangle) scrollView:insert(gameListSectionHeaderText) end --[[ Draws the list item for a single game ]]-- local function drawGameListItem(game, yCoord) -- Draw the background rectangle for the current game's list item local gameListItemRectangle = display.newRect(10, yCoord, display.contentWidth - 20, 60) gameListItemRectangle:setFillColor(200, 200, 200) gameListItemRectangle.strokeWidth = 1 gameListItemRectangle:setStrokeColor(0, 0, 0) gameListItemRectangle:setReferencePoint(display.TopLeftReferencePoint) -- Add the game ID to the game list item rectangle gameListItemRectangle.gameId = game.id -- Add a listener which will activate the game scoreboard when the game list item rectangle is tapped gameListItemRectangle:addEventListener("touch", activateGameScoreboard) -- Insert the game list item rectangle into the scroll view scrollView:insert(gameListItemRectangle) -- Draw the name of the current game's opponent local opponentNameText = display.newText(game.opponentName, 0, 0, "Helvetica", 18) opponentNameText:setTextColor(0, 0, 0) opponentNameText:setReferencePoint(display.TopLeftReferencePoint) opponentNameText.x = gameListItemRectangle.x + 65 opponentNameText.y = gameListItemRectangle.y + 5 -- Insert the opponent's name text into the scroll view scrollView:insert(opponentNameText) -- Determine the total scores for each player local loggedInUserTotal, opponentTotal if (game.loggedInUserIndex == 1) then loggedInUserTotal, opponentTotal = game.user1Total, game.user2Total else loggedInUserTotal, opponentTotal = game.user2Total, game.user1Total end -- Determine what the score text should say local scoreText if (loggedInUserTotal > opponentTotal) then if (game.currentRound == -1) then scoreText = "You won " .. loggedInUserTotal .. " to " .. opponentTotal else scoreText = "You are winning " .. loggedInUserTotal .. " to " .. opponentTotal end elseif (loggedInUserTotal < opponentTotal) then if (game.currentRound == -1) then scoreText = "You lost " .. loggedInUserTotal .. " to " .. opponentTotal else scoreText = "You are losing " .. loggedInUserTotal .. " to " .. opponentTotal end else scoreText = "You are tied " .. loggedInUserTotal .. " to " .. opponentTotal end if (game.currentRound - 1 == 1) then scoreText = scoreText .. " after 1 round" elseif (game.currentRound ~= -1) then scoreText = scoreText .. " after " .. (game.currentRound - 1) .. " rounds" end -- Display the score text scoreText = display.newText(scoreText, 0, 0, "Helvetica", 12) scoreText:setTextColor(0, 0, 0) scoreText:setReferencePoint(display.TopLeftReferencePoint) scoreText.x = gameListItemRectangle.x + 65 scoreText.y = gameListItemRectangle.y + 26 -- Insert the score text into the scroll view scrollView:insert(scoreText) -- Display the timestamp local timestampText = display.newText(game.timestamp, 0, 0, "Helvetica", 10) timestampText:setTextColor(0, 0, 0) timestampText:setReferencePoint(display.TopLeftReferencePoint) timestampText.x = gameListItemRectangle.x + 65 timestampText.y = gameListItemRectangle.y + 40 -- Insert the timestamp text into the scroll view scrollView:insert(timestampText) -- Load the opponent picture display.loadRemoteImage("http://developer.anscamobile.com/demo/hello.png", "GET", drawOpponentPicture, "helloCopy.png", system.TemporaryDirectory, 10, yCoord) end --[[ Draws the list of the logged in user's games ]]-- local function drawGameList(event) -- If there is an error, print it if (event.isError) then print ("Error: network error in drawGameList()") -- Otherwise, draw the list of games else -- Get the response JSON data local response = json.decode(event.response) -- Set the initial y-coordinate local yCoord = 60 -- Draw the "Your Turn" section header drawGameListSectionHeader("Your Turn", yCoord) -- Update the y-coordinate yCoord = yCoord + 30 -- Draw a list item for each game in which it is the logged in user's turn for i = 1, #response.games do game = response.games[i] if (game.turn == 1) then drawGameListItem(game, yCoord) yCoord = yCoord + 60 end end -- Update the y-coordinate yCoord = yCoord + 20 -- Draw the "Their Turn" section header drawGameListSectionHeader("Their Turn", yCoord) -- Update the y-coordinate yCoord = yCoord + 30 -- Draw a list item for each game in which it is not the logged in user's turn for i = 1, #response.games do game = response.games[i] if (game.turn == 2) then drawGameListItem(game, yCoord) yCoord = yCoord + 60 end end -- Update the y-coordinate yCoord = yCoord + 20 -- Draw the "Completed" section header drawGameListSectionHeader("Completed", yCoord) -- Update the y-coordinate yCoord = yCoord + 30 -- Draw a list item for each completed game for i = 1, #response.games do game = response.games[i] if (game.turn == -1) then drawGameListItem(game, yCoord) yCoord = yCoord + 60 end end end end --[[ function facebookListener(event) if ("session" == event.type) then if ("login" == event.phase) then facebook.request("me") end elseif ("request" == event.type) then local response = event.response print(response) end end local function onFacebookButtonClick(event) facebook.login(facebookAppId, facebookListener) end --]] ----------------------------------------------------------------------------------------- ----------------------- -- SCENE LISTENERS -- ----------------------- --[[ Called when the scene's view does not exist ]]-- function scene:createScene(event) -- Get the view's main group local group = self.view -- Create the scroll view scrollView = widget.newScrollView { width = display.contentWidth, height = display.contentHeight, hideBackground = true } -- Background image local background = display.newImageRect(group, "resources/images/landscapeBackground.jpg", display.contentWidth, display.contentHeight) background:setReferencePoint(display.TopLeftReferencePoint) background.x, background.y = 0, 0 -- Main menu/back button local mainMenuButton = widget.newButton { label = "Main Menu", labelColor = { default = {255}, over= {128} }, default = "resources/images/button.png", over = "resources/images/button-over.png", width = 154, height = 40, onRelease = activateMainMenuScene } mainMenuButton:setReferencePoint(display.TopLeftReferencePoint) mainMenuButton.x = 10 mainMenuButton.y = 10 -- Insert the main menu button into the scroll view scrollView:insert(mainMenuButton) -- Get the list of games for the current user and draw the game list network.request("http://127.0.0.1:8000/gameList/", "GET", drawGameList) -- Insert the scroll view into the view's main group group:insert(scrollView) --[[ -- Facebook button local facebookLoginButton = widget.newButton { default = "resources/images/facebookConnectButton.png", --width = 280, --height = 47, onRelease = onFacebookButtonClick } facebookLoginButton:setReferencePoint(display.CenterReferencePoint) facebookLoginButton.x = display.contentWidth / 2 facebookLoginButton.y = display.contentHeight / 2 --]] -- Insert the facebook button into the view's main group --group:insert(facebookLoginButton) end --[[ Called immediately after scene has moved onscreen ]]-- function scene:enterScene(event) end --[[ Called when scene is about to move offscreen ]]-- function scene:exitScene(event) end --[[ Called just prior to when scene's view is removed ]]-- function scene:destroyScene(event) end ----------------------------------------------------------------------------------------- -- END OF YOUR IMPLEMENTATION ----------------------------------------------------------------------------------------- -- "createScene" event is dispatched if scene's view does not exist scene:addEventListener("createScene", scene) -- "enterScene" event is dispatched whenever scene transition has finished scene:addEventListener("enterScene", scene) -- "exitScene" event is dispatched whenever before next scene's transition begins scene:addEventListener("exitScene", scene) -- "destroyScene" event is dispatched before view is unloaded, which can be -- automatically unloaded in low memory situations, or explicitly via a call to -- storyboard.purgeScene() or storyboard.removeScene(). scene:addEventListener("destroyScene", scene) ----------------------------------------------------------------------------------------- return scene
mit
n0xus/darkstar
scripts/globals/items/dhalmel_pie_+1.lua
35
1882
----------------------------------------- -- ID: 4322 -- Item: dhalmel_pie_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 25 -- Strength 4 -- Agility 2 -- Vitality 1 -- Intelligence -2 -- Mind 1 -- Attack % 25 -- Attack Cap 50 -- Ranged ATT % 25 -- Ranged ATT Cap 50 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4322); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 25); target:addMod(MOD_STR, 4); target:addMod(MOD_AGI, 2); target:addMod(MOD_VIT, 1); target:addMod(MOD_INT, -2); target:addMod(MOD_MND, 1); target:addMod(MOD_FOOD_ATTP, 25); target:addMod(MOD_FOOD_ATT_CAP, 50); target:addMod(MOD_FOOD_RATTP, 25); target:addMod(MOD_FOOD_RATT_CAP, 50); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 25); target:delMod(MOD_STR, 4); target:delMod(MOD_AGI, 2); target:delMod(MOD_VIT, 1); target:delMod(MOD_INT, -2); target:delMod(MOD_MND, 1); target:delMod(MOD_FOOD_ATTP, 25); target:delMod(MOD_FOOD_ATT_CAP, 50); target:delMod(MOD_FOOD_RATTP, 25); target:delMod(MOD_FOOD_RATT_CAP, 50); end;
gpl-3.0
n0xus/darkstar
scripts/globals/weaponskills/vidohunir.lua
18
4742
----------------------------------- -- Vidohunir -- Staff weapon skill -- Skill Level: N/A -- Lowers target's magic defense. Duration of effect varies with TP. Laevateinn: Aftermath effect varies with TP. -- Reduces enemy's magic defense by 10%. -- Available only after completing the Unlocking a Myth (Black Mage) quest. -- Aligned with the Breeze Gorget, Thunder Gorget, Aqua Gorget & Snow Gorget. -- Aligned with the Breeze Belt, Thunder Belt, Aqua Belt & Snow Belt. -- Element: Darkness -- Modifiers: INT:30% -- 100%TP 200%TP 300%TP -- 1.75 1.75 1.75 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.ftp100 = 1.75; params.ftp200 = 1.75; params.ftp300 = 1.75; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.3; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_DARK; params.skill = SKILL_STF; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.int_wsc = 0.8; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params); if damage > 0 then local tp = player:getTP(); local duration = (tp/100 * 60); if (target:hasStatusEffect(EFFECT_MAGIC_DEF_DOWN) == false) then target:addStatusEffect(EFFECT_MAGIC_DEF_DOWN, 10, 0, duration); end end if ((player:getEquipID(SLOT_MAIN) == 18994) and (player:getMainJob() == JOB_BLM)) then if (damage > 0) then -- AFTERMATH LV1 if ((player:getTP() >= 100) and (player:getTP() <= 110)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 2); elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 2); elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 2); elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 2); elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 2); elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 2); elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 2); elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 2); elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 2); elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 2); -- AFTERMATH LV2 elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 3); elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 3); elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 3); elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 3); elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 3); elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 3); elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 3); elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 3); elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 3); elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 3); -- AFTERMATH LV3 elseif ((player:getTP() == 300)) then player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 1); end end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
n0xus/darkstar
scripts/zones/Mhaura/npcs/Lacia.lua
17
3143
----------------------------------- -- Area: Mhaura -- NPC: Lacia -- Starts Quest: Trial Size Trial By Lightning -- The "TrialSizeLightning_date" still needs to be set at the BCNM/Mob level to reflect defeat by the Avatar ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/quests"); require("scripts/globals/teleports"); require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1548,1) == true and player:getQuestStatus(OTHER_AREAS,TRIAL_SIZE_TRIAL_BY_LIGHTNING) == QUEST_ACCEPTED and player:getMainJob() == JOB_SMN) then player:startEvent(0x272a,0,1548,5,20); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TrialSizeLightning = player:getQuestStatus(OTHER_AREAS,TRIAL_SIZE_TRIAL_BY_LIGHTNING); if (player:getMainLvl() >= 20 and player:getMainJob() == JOB_SMN and TrialSizeLightning == QUEST_AVAILABLE and player:getFameLevel(WINDURST) >= 2) then --Requires player to be Summoner at least lvl 20 player:startEvent(0x2729,0,1548,5,20); --mini tuning fork of lightning, zone, level elseif (TrialSizeLightning == QUEST_ACCEPTED) then local LightningFork = player:hasItem(1548); if (LightningFork == true) then player:startEvent(0x2722); --Dialogue given to remind player to be prepared elseif (LightningFork == false and tonumber(os.date("%j")) ~= player:getVar("TrialSizeLightning_date")) then player:startEvent(0x272d,0,1548,5,20); --Need another mini tuning fork end elseif (TrialSizeLightning == QUEST_COMPLETED) then player:startEvent(0x272c); --Defeated Ramuh else player:startEvent(0x2725); --Standard dialogue 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); if (csid == 0x2729 and option == 1) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1548); --Mini tuning fork else player:setVar("TrialSizeLightning_date", 0); player:addQuest(OTHER_AREAS,TRIAL_SIZE_TRIAL_BY_LIGHTNING); player:addItem(1548); player:messageSpecial(ITEM_OBTAINED,1548); end elseif (csid == 0x272d and option == 1) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1548); --Mini tuning fork else player:addItem(1548); player:messageSpecial(ITEM_OBTAINED,1548); end elseif (csid == 0x272a and option == 1) then toCloisterOfStorms(player); end end;
gpl-3.0
ArmanIr/loloamad
plugins/google.lua
722
1037
local function googlethat(query) local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" local parameters = "q=".. (URL.escape(query) or "") -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults="" for key,val in ipairs(results) do stringresults=stringresults..val[1].." - "..val[2].."\n" end return stringresults end local function run(msg, matches) local results = googlethat(matches[1]) return stringlinks(results) end return { description = "Searches Google and send results", usage = "!google [terms]: Searches Google and send results", patterns = { "^!google (.*)$", "^%.[g|G]oogle (.*)$" }, run = run }
gpl-2.0
davymai/CN-QulightUI
Interface/AddOns/QulightUI/Addons/Skins/skins/Omen.lua
1
2232
if IsAddOnLoaded("Omen") and Qulight["addonskins"].Omen then local Omen = LibStub("AceAddon-3.0"):GetAddon("Omen") Mod_AddonSkins:RegisterSkin("Omen",function(Skin, skin, Layout, layout, config) -- Skin Bar Texture Omen.UpdateBarTextureSettings_ = Omen.UpdateBarTextureSettings Omen.UpdateBarTextureSettings = function(self) for i, v in ipairs(self.Bars) do v.texture:SetTexture(Mod_AddonSkins.barTexture) end end -- Skin Bar fonts Omen.UpdateBarLabelSettings_ = Omen.UpdateBarLabelSettings Omen.UpdateBarLabelSettings = function(self) self:UpdateBarLabelSettings_() for i, v in ipairs(self.Bars) do v.Text1:SetFont(Qulight["media"].font,self.db.profile.Bar.FontSize) v.Text2:SetFont(Qulight["media"].font,self.db.profile.Bar.FontSize) v.Text3:SetFont(Qulight["media"].font,self.db.profile.Bar.FontSize) end end -- Skin Title Bar Omen.UpdateTitleBar_ = Omen.UpdateTitleBar Omen.UpdateTitleBar = function(self) Omen.db.profile.Scale = 1 Omen.db.profile.Background.EdgeSize = 1 Omen.db.profile.Background.BarInset = config.borderWidth Omen.db.profile.TitleBar.UseSameBG = true self:UpdateTitleBar_() self.TitleText:SetFont(Qulight["media"].font,self.db.profile.TitleBar.FontSize) self.BarList:SetPoint("TOPLEFT", self.Title, "BOTTOMLEFT",0,-1) end --Skin Title/Bars backgrounds Omen.UpdateBackdrop_ = Omen.UpdateBackdrop Omen.UpdateBackdrop = function(self) Omen.db.profile.Scale = 1 Omen.db.profile.Background.EdgeSize = 1 Omen.db.profile.Background.BarInset = config.borderWidth self:UpdateBackdrop_() skin:SkinBackgroundFrame(self.BarList) skin:SkinBackgroundFrame(self.Title) self.BarList:SetPoint("TOPLEFT", self.Title, "BOTTOMLEFT",0,-1) end -- Hook bar creation to apply settings local omen_mt = getmetatable(Omen.Bars) local oldidx = omen_mt.__index omen_mt.__index = function(self, barID) local bar = oldidx(self, barID) Omen:UpdateBarTextureSettings() Omen:UpdateBarLabelSettings() return bar end -- Option Overrides Omen.db.profile.Bar.Spacing = 2 -- Force updates Omen:UpdateBarTextureSettings() Omen:UpdateBarLabelSettings() Omen:UpdateTitleBar() Omen:UpdateBackdrop() Omen:ReAnchorBars() Omen:ResizeBars() end) end
gpl-2.0
Primordus/lua-quickcheck
spec/generators/string_spec.lua
2
3343
local random = require 'lqc.random' local str = require 'lqc.generators.string' local r = require 'lqc.report' local property = require 'lqc.property' local lqc = require 'lqc.quickcheck' local reduce = require 'lqc.helpers.reduce' local function is_string(s) return type(s) == 'string' end local function string_sum(s) local numbers = { string.byte(s, 1, #s) } return reduce(numbers, 0, function(x, acc) return x + acc end) end local function do_setup() random.seed() lqc.init(100, 100) lqc.properties = {} r.report = function() end end describe('string generator module', function() before_each(do_setup) describe('pick function', function() it('should pick an arbitrary length string if size not specified', function() local results = {} local spy_check = spy.new(function(x) table.insert(results, #x) return is_string(x) end) property 'string() should pick an arbitrary sized string' { generators = { str() }, check = spy_check } lqc.check() assert.spy(spy_check).was.called(lqc.numtests) -- If all lengths were equal: -- sum of lengths = first element times numtests local sum_lengths = reduce(results, 0, function(x, acc) return x + acc end) assert.not_equal(results[1] * lqc.numtests, sum_lengths) end) it('should pick a fixed size string if size is specified', function() local length = 3 local spy_check = spy.new(function(x) return is_string(x) and #x == length end) property 'string(len) should pick a fixed length string (size len)' { generators = { str(length) }, check = spy_check } lqc.check() assert.spy(spy_check).was.called(lqc.numtests) end) end) describe('shrink function', function() it('should shrink to a smaller string if no size specified', function() local generated_value, shrunk_value r.report_failed_property = function(_, generated_vals, shrunk_vals) generated_value = generated_vals[1] shrunk_value = shrunk_vals[1] end property 'string() should shrink to smaller and simpler string' { generators = { str() }, check = function(x) return not is_string(x) -- always fails! end } for _ = 1, 100 do shrunk_value, generated_value = nil, nil lqc.check() assert.is_true(#shrunk_value <= #generated_value) assert.is_true(string_sum(shrunk_value) <= string_sum(generated_value)) end end) it('should shrink to a simpler string of same size if size specified', function() local length = 5 local generated_value, shrunk_value r.report_failed_property = function(_, generated_vals, shrunk_vals) generated_value = generated_vals[1] shrunk_value = shrunk_vals[1] end property 'string(len) should shrink to simpler string of same size' { generators = { str(length) }, check = function(x) return not is_string(x) -- always fails! end } for _ = 1, 100 do generated_value, shrunk_value = nil, nil lqc.check() assert.is_equal(length, #shrunk_value) assert.is_true(string_sum(shrunk_value) <= string_sum(generated_value)) end end) end) end)
mit
n0xus/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Chemioue.lua
38
1044
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Chemioue -- Type: NPC Quest -- @zone: 26 -- @pos 82.041 -34.964 67.636 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0118); 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
davymai/CN-QulightUI
Interface/AddOns/DBM-Serpentshrine/localization.kr.lua
1
4570
if GetLocale() ~= "koKR" then return end local L --------------------------- -- Hydross the Unstable -- --------------------------- L = DBM:GetModLocalization("Hydross") L:SetGeneralLocalization{ name = "불안정한 히드로스" } L:SetWarningLocalization{ WarnMark = "%s : %s", WarnPhase = "%s 단계", SpecWarnMark = "%s : %s" } L:SetTimerLocalization{ TimerMark = "다음 %s : %s" } L:SetOptionLocalization{ WarnMark = "징표 알림 보기", WarnPhase = "단계 전환 알림 보기", SpecWarnMark = "징표 피해가 100%를 넘을 경우 특수 경고 보기", TimerMark = "다음 징표 바 보기" } L:SetMiscLocalization{ Frost = "냉기", Nature = "자연" } ----------------------- -- The Lurker Below -- ----------------------- L = DBM:GetModLocalization("LurkerBelow") L:SetGeneralLocalization{ name = "심연의 잠복꾼" } L:SetWarningLocalization{ WarnSubmerge = "잠수", WarnEmerge = "재등장" } L:SetTimerLocalization{ TimerSubmerge = "잠수", TimerEmerge = "재등장" } L:SetOptionLocalization{ WarnSubmerge = "잠수 알림 보기", WarnEmerge = "재등장 알림 보기", TimerSubmerge = "다음 잠수 바 보기", TimerEmerge = "다음 재등장 바 보기" } -------------------------- -- Leotheras the Blind -- -------------------------- L = DBM:GetModLocalization("Leotheras") L:SetGeneralLocalization{ name = "눈먼 레오테라스" } L:SetWarningLocalization{ WarnPhase = "%s 단계" } L:SetTimerLocalization{ TimerPhase = "다음 %s 단계" } L:SetOptionLocalization{ WarnPhase = "단계 전환 알림 보기", TimerPhase = "다음 단계 바 보기" } L:SetMiscLocalization{ Human = "인간", Demon = "악마", YellDemon = "꺼져라, 엘프 꼬맹이. 지금부터는 내가 주인이다!", YellPhase2 = "안 돼... 안 돼! 무슨 짓이냐? 내가 주인이야! 내 말 듣지 못해? 나란 말이야! 내가... 으아악! 놈을 억누를 수... 없...어." } ----------------------------- -- Fathom-Lord Karathress -- ----------------------------- L = DBM:GetModLocalization("Fathomlord") L:SetGeneralLocalization{ name = "심해군주 카라드레스" } L:SetMiscLocalization{ YellPull = "경비병! 여기 침입자들이 있다...", Caribdis = "심연의 경비병 카리브디스", Tidalvess = "심연의 경비병 타이달베스", Sharkkis = "심연의 경비병 샤르키스" } -------------------------- -- Morogrim Tidewalker -- -------------------------- L = DBM:GetModLocalization("Tidewalker") L:SetGeneralLocalization{ name = "겅둥파도 모로그림" } L:SetWarningLocalization{ WarnMurlocs = "멀록 소환", SpecWarnMurlocs = "멀록 소환!" } L:SetTimerLocalization{ TimerMurlocs = "다음 멀록 소환" } L:SetOptionLocalization{ WarnMurlocs = "멀록 소환 알림 보기", SpecWarnMurlocs = "멀록 소환 특수 경고 보기", TimerMurlocs = "다음 멀록 소환 바 보기" } ----------------- -- Lady Vashj -- ----------------- L = DBM:GetModLocalization("Vashj") L:SetGeneralLocalization{ name = "여군주 바쉬" } L:SetWarningLocalization{ WarnElemental = "곧 오염된 정령 등장 (%s)", WarnStrider = "곧 포자손 등장 (%s)", WarnNaga = "곧 나가 등장 (%s)", WarnShield = "보호막 %d/4 남음", WarnLoot = "오염된 핵: >%s<", SpecWarnElemental = "오염된 정령 - 대상 전환!" } L:SetTimerLocalization{ TimerElementalActive = "오염된 정령 활성화", TimerElemental = "오염된 정령 가능 (%d)", TimerStrider = "다음 포자손 (%d)", TimerNaga = "다음 나가 (%d)" } L:SetOptionLocalization{ WarnElemental = "오염된 정령 등장 이전에 알림 보기", WarnStrider = "포자손 등장 이전에 알림 보기", WarnNaga = "나가 등장 이전에 알림 보기", WarnShield = "보호막 사라짐 알림 보기", WarnLoot = "오염된 핵 획득 대상 알림 보기", TimerElementalActive = "오염된 정령 활성화 시간 바 보기", TimerElemental = "오염된 정령 대기시간 바 보기", TimerStrider = "다음 포자손 바 보기", TimerNaga = "다음 나가 바 보기", SpecWarnElemental = "오염된 정령 등장 특수 경고 보기", RangeFrame = "거리 창 보기", AutoChangeLootToFFA = "2 단계에서 전리품 획득 설정 자동으로 변경" } L:SetMiscLocalization{ DBM_VASHJ_YELL_PHASE2 = "때가 왔다! 한 놈도 살려두지 마라!", DBM_VASHJ_YELL_PHASE3 = "숨을 곳이나 마련해 둬라!", LootMsg = "([^%s]+).*Hitem:(%d+)" }
gpl-2.0
n0xus/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Parukoko.lua
38
1048
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Parukoko -- Type: Standard NPC -- @zone: 94 -- @pos -32.400 -3.5 -103.666 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01b4); 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
davymai/CN-QulightUI
Interface/AddOns/DBM-Firelands/Rhyolith.lua
1
5373
local mod = DBM:NewMod(193, "DBM-Firelands", nil, 78) local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 145 $"):sub(12, -3)) mod:SetCreatureID(52558)--or does 53772 die instead?didn't actually varify this fires right unit_died event yet so we'll see tonight mod:SetEncounterID(1204) mod:DisableEEKillDetection() mod:SetZone() mod:SetModelSound("Sound\\Creature\\RHYOLITH\\VO_FL_RHYOLITH_AGGRO.wav", "Sound\\Creature\\RHYOLITH\\VO_FL_RHYOLITH_KILL_02.wav") --Long: Blah blah blah Nuisances, Nuisances :) --Short: So Soft mod:RegisterCombat("combat") mod:RegisterEventsInCombat( "SPELL_AURA_APPLIED 99846", "SPELL_AURA_APPLIED_DOSE 98255", "SPELL_CAST_START 98034 97282", "SPELL_CAST_SUCCESS 98493 97225", "SPELL_SUMMON 98136 98552", "UNIT_HEALTH boss1" ) local warnHeatedVolcano = mod:NewSpellAnnounce(98493, 3) local warnFlameStomp = mod:NewSpellAnnounce(97282, 3, nil, "Melee")--According to journal only hits players within 20 yards of him, so melee by default? local warnMoltenArmor = mod:NewStackAnnounce(98255, 4, nil, "Tank|Healer") -- Would this be nice if we could show this in the infoFrame? (changed defaults to tanks/healers, if you aren't either it doesn't concern you unless you find stuff to stand in) local warnDrinkMagma = mod:NewSpellAnnounce(98034, 4) -- if you "kite" him to close to magma local warnFragments = mod:NewSpellAnnounce("ej2531", 2, 98136) local warnShard = mod:NewCountAnnounce("ej2532", 3, 98552) local warnMagmaFlow = mod:NewSpellAnnounce(97225, 4) local warnPhase2Soon = mod:NewPrePhaseAnnounce(2, 2) local warnPhase2 = mod:NewPhaseAnnounce(2, 3) local specWarnMagmaFlow = mod:NewSpecialWarningSpell(97225, nil, nil, nil, 2) local specWarnFlameStomp = mod:NewSpecialWarningSpell(97282, false) local timerFragmentCD = mod:NewNextTimer(22.5, "ej2531", nil, nil, nil, 98136) local timerSparkCD = mod:NewNextCountTimer(22.5, "ej2532", nil, nil, nil, 98552) local timerHeatedVolcano = mod:NewNextTimer(25.5, 98493) local timerFlameStomp = mod:NewNextTimer(30.5, 97282) local timerSuperheated = mod:NewNextTimer(10, 101304) --Add the 10 second party in later at some point if i remember to actually log it better local timerMoltenSpew = mod:NewNextTimer(6, 98034) --6secs after Drinking Magma local timerMagmaFlowActive = mod:NewBuffActiveTimer(10, 97225) --10 second buff volcano has, after which the magma line explodes. local countdownStomp = mod:NewCountdown(30.5, 97282, false) local spamAdds = 0 local phase2Started = false local sparkCount = 0 local fragmentCount = 0 local prewarnedPhase2 = false function mod:OnCombatStart(delay) timerFragmentCD:Start(-delay) timerHeatedVolcano:Start(30-delay) timerFlameStomp:Start(16-delay) countdownStomp:Start(16-delay) if self:IsDifficulty("heroic10", "heroic25") then timerSuperheated:Start(300-delay)--5 min on heroic else timerSuperheated:Start(360-delay)--6 min on normal end spamAdds = 0 phase2Started = false sparkCount = 0 fragmentCount = 1--Fight starts out 1 cycle in so only 1 more spawns before pattern reset. prewarnedPhase2 = false end function mod:SPELL_AURA_APPLIED(args) local spellId = args.spellId if spellId == 99846 and not phase2Started then phase2Started = true warnPhase2:Show() if timerFlameStomp:GetTime() > 0 then--This only happens if it was still on CD going into phase countdownStomp:Cancel() timerFlameStomp:Cancel() countdownStomp:Start(7) timerFlameStomp:Start(7) else--Else, he uses it right away timerFlameStomp:Start(1) end end end function mod:SPELL_AURA_APPLIED_DOSE(args) local spellId = args.spellId if spellId == 98255 and self:GetCIDFromGUID(args.destGUID) == 52558 and args.amount > 10 and self:AntiSpam(5, 1) then warnMoltenArmor:Show(args.destName, args.amount) end end function mod:SPELL_CAST_START(args) local spellId = args.spellId if spellId == 98034 then warnDrinkMagma:Show() timerMoltenSpew:Start() elseif spellId == 97282 then warnFlameStomp:Show() specWarnFlameStomp:Show() if not phase2Started then timerFlameStomp:Start() countdownStomp:Start(30.5) else--13sec cd in phase 2 timerFlameStomp:Start(13) countdownStomp:Start(13) end end end function mod:SPELL_CAST_SUCCESS(args) local spellId = args.spellId if spellId == 98493 then warnHeatedVolcano:Show() if self:IsDifficulty("heroic10", "heroic25") then timerHeatedVolcano:Start() else timerHeatedVolcano:Start(40) end elseif spellId == 97225 then warnMagmaFlow:Show() specWarnMagmaFlow:Show() timerMagmaFlowActive:Start() end end function mod:SPELL_SUMMON(args) local spellId = args.spellId if spellId == 98136 and self:AntiSpam(5, 2) then fragmentCount = fragmentCount + 1 warnFragments:Show() if fragmentCount < 2 then timerFragmentCD:Start() else--Spark is next start other CD bar and reset count. fragmentCount = 0 timerSparkCD:Start(22.5, sparkCount+1) end elseif spellId == 98552 then sparkCount = sparkCount + 1 warnShard:Show(sparkCount) timerFragmentCD:Start() end end function mod:UNIT_HEALTH(uId) if self:GetUnitCreatureId(uId) == 52558 then local h = UnitHealth(uId) / UnitHealthMax(uId) * 100 if h > 35 and prewarnedPhase2 then prewarnedPhase2 = false elseif h > 28 and h < 22 and not prewarnedPhase2 then prewarnedPhase2 = true warnPhase2Soon:Show() end end end
gpl-2.0
n0xus/darkstar
scripts/zones/Alzadaal_Undersea_Ruins/npcs/qm3.lua
16
1199
----------------------------------- -- Area: Alzadaal Undersea Ruins -- NPC: ??? (Spawn Armed Gears(ZNM T3)) -- @pos -42 -4 -169 72 ----------------------------------- package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(2574,1) and trade:getItemCount() == 1) then -- Trade Ferrite player:tradeComplete(); SpawnMob(17072178,180):updateClaim(player); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); 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
n0xus/darkstar
scripts/zones/Metalworks/npcs/Nogga.lua
34
1203
----------------------------------- -- Area: Metalworks -- NPC: Nogga -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,NOGGA_SHOP_DIALOG); stock = {0x43A4,675,2, -- Bomb Arm 0x43A1,1083,3, -- Grenade 0x0ae8,92,3} -- Catalytic Oil showNationShop(player, BASTOK, stock); 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
omidtarh/wezardbot
plugins/plugins.lua
325
6164
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'. '..v..' '..status..'\n' end end local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled' return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..v..' '..status..'\n' end end local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.' return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return 'Plugin '..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return 'Plugin '..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return 'Plugin '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return 'Plugin '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return 'Plugin '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return 'Plugin '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == 'enable' and matches[3] == 'chat' then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == 'disable' and matches[3] == 'chat' then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins enable [plugin] : enable plugin.", "!plugins disable [plugin] : disable plugin.", "!plugins reload : reloads all plugins." }, }, patterns = { "^!plugins$", "^!plugins? (enable) ([%w_%.%-]+)$", "^!plugins? (disable) ([%w_%.%-]+)$", "^!plugins? (enable) ([%w_%.%-]+) (chat)", "^!plugins? (disable) ([%w_%.%-]+) (chat)", "^!plugins? (reload)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
n0xus/darkstar
scripts/globals/weaponskills/trueflight.lua
18
4616
----------------------------------- -- Skill Level: N/A -- Description: Deals light elemental damage. Damage varies with TP. Gastraphetes: Aftermath effect varies with TP. -- Available only after completing the Unlocking a Myth (Ranger) quest. -- Does not work with Flashy Shot. -- Does not work with Stealth Shot. -- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget. -- Aligned with the Breeze Belt, Thunder Belt & Soil Belt. -- Properties -- Element: Light -- Skillchain Properties: Fragmentation/Scission -- Modifiers: AGI:30% -- Damage Multipliers by TP: -- 100%TP 200%TP 300%TP -- 4.0 4.25 4.75 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.ftp100 = 4; params.ftp200 = 4.25; params.ftp300 = 4.75; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_LIGHT; params.skill = SKILL_MRK; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 3.8906; params.ftp200 = 6.3906; params.ftp300 = 9.3906; params.agi_wsc = 1.0; end local damage, tpHits, extraHits = doMagicWeaponskill(player, target, params); if ((player:getEquipID(SLOT_RANGED) == 19001) and (player:getMainJob() == JOB_RNG)) then if (damage > 0) then -- AFTERMATH LV1 if ((player:getTP() >= 100) and (player:getTP() <= 110)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 3); elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 3); elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 3); elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 3); elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 3); elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 3); elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 3); elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 3); elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 3); elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 3); -- AFTERMATH LV2 elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 4); elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 4); elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 4); elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 4); elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 4); elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 4); elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 4); elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 4); elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 4); elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 4); -- AFTERMATH LV3 elseif ((player:getTP() == 300)) then player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 2); end end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end;
gpl-3.0
n0xus/darkstar
scripts/zones/Attohwa_Chasm/mobs/Sekhmet.lua
13
1842
----------------------------------- -- Area: Attohwa Chasm -- NM: Sekhmet ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); mob:setMod(MOD_DOUBLE_ATTACK, 10); mob:setMod(MOD_FASTCAST, 15); end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) mob:setRespawnTime(math.random(5400,7200)); -- 1.5 to 2 hours. UpdateNMSpawnPoint(mob:getID()); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob, killer) end; ----------------------------------- -- onAdditionalEffect ----------------------------------- function onAdditionalEffect(mob, player) local chance = 100; local resist = applyResistanceAddEffect(mob,player,ELE_DARK,EFFECT_ENASPIR); if (math.random(0,99) >= chance or resist <= 0.5) then return 0,0,0; else local mp = math.random(1,10); if (player:getMP() < mp) then mp = player:getMP(); end if (mp == 0) then return 0,0,0; else player:delMP(mp); mob:addMP(mp); return SUBEFFECT_MP_DRAIN, MSGBASIC_ADD_EFFECT_MP_DRAIN, mp; end end end;
gpl-3.0
GhoulofGSG9/BadgesPlus
lua/BadgesPlus/Badges_Server.lua
1
6830
Script.Load("lua/Badges_Shared.lua") --Queue for clients that still wait for their hive response local gBadgeClientRequestQueue = {} --Cache for changed badge names local gBadgeNameCache = {} --stores all badges each client owns local userId2OwnedBadges = {} --cache dev ids for the achievement local gClientIdDevs = {} --lookup table for connected clients via their userID local userId2ClientId = {} --stores arrays of the selected badges of each player local gClientId2Badges = {} --Assign badges to client based on the hive response function Badges_FetchBadges(clientId, response) local badges = response or {} local client = Server.GetClientById(clientId) if not client then return end local userId = client:GetUserId() for _, badgeid in ipairs(gDLCBadges) do local data = Badges_GetBadgeData(badgeid) if GetHasDLC(data.productId, client) then badges[#badges + 1] = gBadges[badgeid] end end userId2OwnedBadges[userId] = userId2OwnedBadges[userId] or {} for _, badge in ipairs(badges) do local badgeid = rawget(gBadges, badge) local badgedata = Badges_GetBadgeData(badgeid) userId2OwnedBadges[userId][badgeid] = badgedata.columns local queuedColumns = gBadgeClientRequestQueue[clientId] and gBadgeClientRequestQueue[clientId][badgeid] if queuedColumns then for i, queuedColumn in ipairs(queuedColumns) do if Badges_SetBadge(clientId, badgeid, queuedColumn) then table.remove(gBadgeClientRequestQueue[clientId][badgeid], i) end end end Server.SendNetworkMessage(client, "BadgeRows", BuildBadgeRowsMessage(badgeid, badgedata.columns), true) if (badge == "dev" or badge == "community_dev") then gClientIdDevs[userId] = true end end end function Badges_HasDevBadge(userId) return gClientIdDevs[userId] end function SetFormalBadgeName(badgename, name) local badgeid = gBadges[badgename] local setName = Badges_SetName(badgeid, name) if setName then local msg = { badge = badgeid, name = name} gBadgeNameCache[#gBadgeNameCache + 1] = msg Server.SendNetworkMessage("BadgeName", msg, true) return true end return false end function GiveBadge(userId, badgeName, column) local badgeid = rawget(gBadges, badgeName) if not badgeid then return false end local badgedata = Badges_GetBadgeData(badgeid) if not badgedata or badgedata.isOfficial then return false end local ownedBadges = userId2OwnedBadges[userId] or {} local columns = ownedBadges[badgeid] if not columns then columns = 0 end column = column and bit.lshift(1, (column-1)) or 16 columns = bit.bor(columns,column) ownedBadges[badgeid] = columns userId2OwnedBadges[userId] = ownedBadges local clientId = userId2ClientId[userId] local client = clientId and Server.GetClientById(clientId) if client then local queuedColumns = gBadgeClientRequestQueue[clientId] and gBadgeClientRequestQueue[clientId][badgeid] if queuedColumns then for i, queuedColumn in ipairs(queuedColumns) do if Badges_SetBadge(clientId, badgeid, queuedColumn) then table.remove(gBadgeClientRequestQueue[clientId][badgeid], i) end end end Server.SendNetworkMessage(client, "BadgeRows", BuildBadgeRowsMessage(badgeid, columns), true) end return true end function Badges_SetBadge(clientId, badgeid, column) local client = clientId and Server.GetClientById(clientId) local userId = client and client:GetUserId() if not userId or userId < 1 then --check for virtual clients return false end local ownedbadges = userId2OwnedBadges[userId] or {} column = column or 5 --verify ownership and column if badgeid > gBadges.none and (not ownedbadges[badgeid] or bit.band(ownedbadges[badgeid], bit.lshift(1, column - 1)) == 0) then return false end local changed = { column } local clientBadges = gClientId2Badges[clientId] if not clientBadges then clientBadges = {} for i = 1, 10 do clientBadges[i] = gBadges.none end end if badgeid > gBadges.none then for rowId, badge in ipairs(clientBadges) do if badge == badgeid then clientBadges[rowId] = gBadges.none changed[2] = rowId end end end clientBadges[column] = badgeid gClientId2Badges[clientId] = clientBadges for _, changedrow in ipairs(changed) do Server.SendNetworkMessage("DisplayBadge", BuildDisplayBadgeMessage(clientId, clientBadges[changedrow], changedrow) ,true) end return true end function Badges_OnClientBadgeRequest(clientId, msg) local result = Badges_SetBadge(clientId, msg.badge, msg.column) if not result then if not gBadgeClientRequestQueue[clientId] then gBadgeClientRequestQueue[clientId] = {} end if not gBadgeClientRequestQueue[clientId][msg.badge] then gBadgeClientRequestQueue[clientId][msg.badge] = { msg.column } else table.insert(gBadgeClientRequestQueue[clientId][msg.badge], msg.column) end end return result end Server.HookNetworkMessage("SelectBadge", function(client, msg) Badges_OnClientBadgeRequest(client:GetId() , msg) end) local function OnClientConnect(client) if not client or client:GetIsVirtual() then return end userId2ClientId[client:GetUserId()] = client:GetId() -- Send this client the badge info for all existing clients for clientId, badges in pairs(gClientId2Badges) do for column, badge in ipairs(badges) do if badge > gBadges.none then Server.SendNetworkMessage( client, "DisplayBadge", BuildDisplayBadgeMessage(clientId, badge, column), true ) end end end local ownedbadges = userId2OwnedBadges[client:GetUserId()] if ownedbadges then for badgeid, columns in pairs(ownedbadges) do Server.SendNetworkMessage(client, "BadgeRows", BuildBadgeRowsMessage(badgeid, columns), true) end end for _, msg in ipairs(gBadgeNameCache) do Server.SendNetworkMessage(client, "BadgeName", msg, true) end end local function OnClientDisconnect(client) if not client or client:GetIsVirtual() then return end userId2ClientId[client:GetUserId()] = nil gClientId2Badges[ client:GetId() ] = nil gBadgeClientRequestQueue[ client:GetId() ] = nil end Event.Hook("ClientConnect", OnClientConnect) Event.Hook("ClientDisconnect", OnClientDisconnect)
mit
davymai/CN-QulightUI
Interface/AddOns/QulightUI/Addons/LootRoll.lua
1
12785
if Qulight["loot"].rolllootframe ~= true then return end local backdrop = { bgFile = Qulight["media"].texture, tile = true, tileSize = 0, edgeFile = "Interface\\Buttons\\WHITE8x8", edgeSize = 1, insets = {left = -1, right = -1, top = -1, bottom = -1}, } local function ClickRoll(frame) RollOnLoot(frame.parent.rollid, frame.rolltype) end local function HideTip() GameTooltip:Hide() end local function HideTip2() GameTooltip:Hide(); ResetCursor() end local rolltypes = {"need", "greed", "disenchant", [0] = "pass"} local function SetTip(frame) GameTooltip:SetOwner(frame, "ANCHOR_RIGHT") GameTooltip:SetText(frame.tiptext) if frame:IsEnabled() == 0 then GameTooltip:AddLine("|cffff3333Cannot roll") end for name,roll in pairs(frame.parent.rolls) do if roll == rolltypes[frame.rolltype] then GameTooltip:AddLine(name, 1, 1, 1) end end GameTooltip:Show() end local function SetItemTip(frame) if not frame.link then return end GameTooltip:SetOwner(frame, "ANCHOR_TOPLEFT") GameTooltip:SetHyperlink(frame.link) if IsShiftKeyDown() then GameTooltip_ShowCompareItem() end if IsModifiedClick("DRESSUP") then ShowInspectCursor() else ResetCursor() end end local function ItemOnUpdate(self) if IsShiftKeyDown() then GameTooltip_ShowCompareItem() end CursorOnUpdate(self) end local function LootClick(frame) if IsControlKeyDown() then DressUpItemLink(frame.link) elseif IsShiftKeyDown() then ChatEdit_InsertLink(frame.link) end end local cancelled_rolls = {} local function OnEvent(frame, event, rollid) cancelled_rolls[rollid] = true if frame.rollid ~= rollid then return end frame.rollid = nil frame.time = nil frame:Hide() end local function StatusUpdate(frame) local t = GetLootRollTimeLeft(frame.parent.rollid) local perc = t / frame.parent.time frame.spark:SetPoint("CENTER", frame, "LEFT", perc * frame:GetWidth(), 0) frame:SetValue(t) end local function CreateRollButton(parent, ntex, ptex, htex, rolltype, tiptext, ...) local f = CreateFrame("Button", nil, parent) f:SetPoint(...) f:SetWidth(28) f:SetHeight(28) f:SetNormalTexture(ntex) if ptex then f:SetPushedTexture(ptex) end f:SetHighlightTexture(htex) f.rolltype = rolltype f.parent = parent f.tiptext = tiptext f:SetScript("OnEnter", SetTip) f:SetScript("OnLeave", HideTip) f:SetScript("OnClick", ClickRoll) f:SetMotionScriptsWhileDisabled(true) local txt = f:CreateFontString(nil, nil) txt:SetFont(Qulight["media"].font, 10, "OUTLINE") txt:SetPoint("CENTER", 0, rolltype == 2 and 1 or rolltype == 0 and -1.2 or 0) return f, txt end local function CreateRollFrame() local frame = CreateFrame("Frame", nil, UIParent) frame:SetWidth(328) frame:SetHeight(22) frame:SetBackdrop(backdrop) frame:SetBackdropColor(0.1, 0.1, 0.1, 1) frame:SetScript("OnEvent", OnEvent) frame:RegisterEvent("CANCEL_LOOT_ROLL") CreateStyle(frame, 4) frame:Hide() local button = CreateFrame("Button", nil, frame) button:SetPoint("LEFT", -24, 0) button:SetWidth(22) button:SetHeight(22) button:SetScript("OnEnter", SetItemTip) button:SetScript("OnLeave", HideTip2) button:SetScript("OnUpdate", ItemOnUpdate) button:SetScript("OnClick", LootClick) CreateStyle(button, 4) frame.button = button local buttonborder = CreateFrame("Frame", nil, button) buttonborder:SetWidth(22) buttonborder:SetHeight(22) buttonborder:SetPoint("CENTER", button, "CENTER") buttonborder:SetBackdrop(backdrop) buttonborder:SetBackdropColor(1, 1, 1, 0) local buttonborder2 = CreateFrame("Frame", nil, button) buttonborder2:SetWidth(24) buttonborder2:SetHeight(24) buttonborder2:SetFrameLevel(buttonborder:GetFrameLevel()+1) buttonborder2:SetPoint("CENTER", button, "CENTER") buttonborder2:SetBackdrop(backdrop) buttonborder2:SetBackdropColor(0, 0, 0, 0) buttonborder2:SetBackdropBorderColor(0,0,0,1) frame.buttonborder = buttonborder local tfade = frame:CreateTexture(nil, "BORDER") tfade:SetPoint("TOPLEFT", frame, "TOPLEFT", 4, 0) tfade:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -4, 0) tfade:SetTexture("Interface\\ChatFrame\\ChatFrameBackground") tfade:SetBlendMode("ADD") tfade:SetGradientAlpha("VERTICAL", .1, .1, .1, 0, .1, .1, .1, 0) local status = CreateFrame("StatusBar", nil, frame) status:SetWidth(326) status:SetHeight(20) status:SetPoint("CENTER", frame, "CENTER", 0, 0) status:SetScript("OnUpdate", StatusUpdate) status:SetFrameLevel(status:GetFrameLevel()-1) status:SetStatusBarTexture(Qulight["media"].texture) status:SetStatusBarColor(.8, .8, .8, .9) status.parent = frame frame.status = status local spark = frame:CreateTexture(nil, "OVERLAY") spark:SetWidth(14) spark:SetHeight(25) spark:SetTexture("Interface\\CastingBar\\UI-CastingBar-Spark") spark:SetBlendMode("ADD") status.spark = spark local need, needtext = CreateRollButton(frame, "Interface\\Buttons\\UI-GroupLoot-Dice-Up", "Interface\\Buttons\\UI-GroupLoot-Dice-Highlight", "Interface\\Buttons\\UI-GroupLoot-Dice-Down", 1, NEED, "LEFT", frame.button, "RIGHT", 5, -1) local greed, greedtext = CreateRollButton(frame, "Interface\\Buttons\\UI-GroupLoot-Coin-Up", "Interface\\Buttons\\UI-GroupLoot-Coin-Highlight", "Interface\\Buttons\\UI-GroupLoot-Coin-Down", 2, GREED, "LEFT", need, "RIGHT", 0, -1) local de, detext de, detext = CreateRollButton(frame, "Interface\\Buttons\\UI-GroupLoot-DE-Up", "Interface\\Buttons\\UI-GroupLoot-DE-Highlight", "Interface\\Buttons\\UI-GroupLoot-DE-Down", 3, ROLL_DISENCHANT, "LEFT", greed, "RIGHT", 0, -1) local pass, passtext = CreateRollButton(frame, "Interface\\Buttons\\UI-GroupLoot-Pass-Up", nil, "Interface\\Buttons\\UI-GroupLoot-Pass-Down", 0, PASS, "LEFT", de or greed, "RIGHT", 0, 2.2) frame.needbutt, frame.greedbutt, frame.disenchantbutt = need, greed, de frame.need, frame.greed, frame.pass, frame.disenchant = needtext, greedtext, passtext, detext local bind = frame:CreateFontString() bind:SetPoint("LEFT", pass, "RIGHT", 3, 1) bind:SetFont(Qulight["media"].font, 10, "OUTLINE") frame.fsbind = bind local loot = frame:CreateFontString(nil, "ARTWORK") loot:SetFont(Qulight["media"].font, 10, "OUTLINE") loot:SetPoint("LEFT", bind, "RIGHT", 0, 0) loot:SetPoint("RIGHT", frame, "RIGHT", -5, 0) loot:SetHeight(10) loot:SetWidth(200) loot:SetJustifyH("LEFT") frame.fsloot = loot frame.rolls = {} return frame end local anchor = CreateFrame("Button", "RollAnchor", UIParent) anchor:SetWidth(300) anchor:SetHeight(22) anchor:SetBackdrop(backdrop) anchor:SetBackdropColor(0.25, 0.25, 0.25, 1) local label = anchor:CreateFontString(nil, "ARTWORK") label:SetFont(Qulight["media"].font, 10, "OUTLINE") label:SetAllPoints(anchor) label:SetText("MoveRoll") anchor:SetMovable(true) anchor:EnableMouse(false) CreateStyle(anchor, 2) anchor:SetAlpha(0) anchor:SetBackdropBorderColor(1, 0, 0, 1) local frames = {} local f = CreateRollFrame() -- Create one for good measure f:SetPoint("BOTTOMLEFT", next(frames) and frames[#frames] or anchor, "TOPLEFT", 0, 4) table.insert(frames, f) local function GetFrame() for i,f in ipairs(frames) do if not f.rollid then return f end end local f = CreateRollFrame() f:SetPoint("BOTTOMLEFT", next(frames) and frames[#frames] or anchor, "TOPLEFT", 0, 4) table.insert(frames, f) return f end local function START_LOOT_ROLL(rollid, time) if cancelled_rolls[rollid] then return end local f = GetFrame() f.rollid = rollid f.time = time for i in pairs(f.rolls) do f.rolls[i] = nil end f.need:SetText("") f.greed:SetText("") f.pass:SetText("") f.disenchant:SetText("") local texture, name, count, quality, bop, canNeed, canGreed, canDisenchant = GetLootRollItemInfo(rollid) f.button:SetNormalTexture(texture) f.button.link = GetLootRollItemLink(rollid) if canNeed then f.needbutt:Enable() else f.needbutt:Disable() end if canGreed then f.greedbutt:Enable() else f.greedbutt:Disable() end if canDisenchant then f.disenchantbutt:Enable() else f.disenchantbutt:Disable() end SetDesaturation(f.needbutt:GetNormalTexture(), not canNeed) SetDesaturation(f.greedbutt:GetNormalTexture(), not canGreed) SetDesaturation(f.disenchantbutt:GetNormalTexture(), not canDisenchant) f.fsbind:SetText(bop and "BoP" or "BoE") f.fsbind:SetVertexColor(bop and 1 or .3, bop and .3 or 1, bop and .1 or .3) local color = ITEM_QUALITY_COLORS[quality] f.fsloot:SetVertexColor(color.r, color.g, color.b) f.fsloot:SetText(name) f:SetBackdropBorderColor(color.r, color.g, color.b, 1) f.buttonborder:SetBackdropBorderColor(color.r, color.g, color.b, 1) f.status:SetStatusBarColor(color.r, color.g, color.b, .7) f.status:SetMinMaxValues(0, time) f.status:SetValue(time) f:SetPoint("CENTER", WorldFrame, "CENTER") f:Show() end local locale = GetLocale() local rollpairs = locale == "deDE" and { ["(.*) passt automatisch bei (.+), weil [ersi]+ den Gegenstand nicht benutzen kann.$"] = "pass", ["(.*) würfelt nicht für: (.+|r)$"] = "pass", ["(.*) hat für (.+) 'Gier' ausgewählt"] = "greed", ["(.*) hat für (.+) 'Bedarf' ausgewählt"] = "need", ["(.*) hat für '(.+)' Entzauberung gewählt."] = "disenchant", } or locale == "frFR" and { ["(.*) a passé pour : (.+) parce qu'((il)|(elle)) ne peut pas ramasser cette objet.$"] = "pass", ["(.*) a passé pour : (.+)"] = "pass", ["(.*) a choisi Cupidité pour : (.+)"] = "greed", ["(.*) a choisi Besoin pour : (.+)"] = "need", ["(.*) a choisi Désenchantement pour : (.+)"] = "disenchant", } or locale == "zhTW" and { ["(.*)自動放棄:(.+),因為"] = "pass", ["(.*)放棄了:(.+)"] = "pass", ["(.*)選擇了貪婪優先:(.+)"] = "greed", ["(.*)選擇了需求優先:(.+)"] = "need", ["(.*)選擇分解:(.+)"] = "disenchant", } or locale == "zhCN" and { ["(.*)自动放弃了(.+),因为他无法拾取该物品。$"] = "pass", ["(.*)放弃了:(.+)"] = "pass", ["(.*)选择了贪婪取向:(.+)"] = "greed", ["(.*)选择了需求取向:(.+)"] = "need", ["(.*)选择了分解取向:(.+)"] = "disenchant", } or locale == "ruRU" and { ["(.*) автоматически передает предмет (.+), поскольку не может его забрать"] = "pass", ["(.*) пропускает розыгрыш предмета \"(.+)\", поскольку не может его забрать"] = "pass", ["(.*) отказывается от предмета (.+)%."] = "pass", ["Разыгрывается: (.+)%. (.*): \"Не откажусь\""] = "greed", ["Разыгрывается: (.+)%. (.*): \"Мне это нужно\""] = "need", ["Разыгрывается: (.+)%. (.*): \"Распылить\""] = "disenchant", } or locale == "koKR" and { ["(.+)님이 획득할 수 없는 아이템이어서 자동으로 주사위 굴리기를 포기했습니다: (.+)"] = "pass", ["(.+)님이 주사위 굴리기를 포기했습니다: (.+)"] = "pass", ["(.+)님이 차비를 선택했습니다: (.+)"] = "greed", ["(.+)님이 입찰을 선택했습니다: (.+)"] = "need", ["(.+)님이 마력 추출을 선택했습니다: (.+)"] = "disenchant", } or { ["^(.*) automatically passed on: (.+) because s?he cannot loot that item.$"] = "pass", ["^(.*) passed on: (.+|r)$"] = "pass", ["(.*) has selected Greed for: (.+)"] = "greed", ["(.*) has selected Need for: (.+)"] = "need", ["(.*) has selected Disenchant for: (.+)"] = "disenchant", } local function ParseRollChoice(msg) for i,v in pairs(rollpairs) do local _, _, playername, itemname = string.find(msg, i) if locale == "ruRU" and (v == "greed" or v == "need" or v == "disenchant") then local temp = playername playername = itemname itemname = temp end if playername and itemname and playername ~= "Everyone" then return playername, itemname, v end end end local function CHAT_MSG_LOOT(msg) local playername, itemname, rolltype = ParseRollChoice(msg) local num = 0 if playername and itemname and rolltype then for _,f in ipairs(frames) do if f.rollid and f.button.link == itemname and not f.rolls[playername] then f.rolls[playername] = rolltype f[rolltype]:SetText(tonumber(f[rolltype]:GetText()) + 1) return end end end end AnchorLootRoll = CreateFrame("Frame","Move_LootRoll",UIParent) --AnchorLootRoll:SetPoint("RIGHT", -100, 200) AnchorLootRoll:SetPoint("TOP", 0, -160) CreateAnchor(AnchorLootRoll, "Move LootRoll", 250, 25) anchor:RegisterEvent("ADDON_LOADED") anchor:SetScript("OnEvent", function(frame, event, addon) anchor:UnregisterEvent("ADDON_LOADED") anchor:RegisterEvent("START_LOOT_ROLL") anchor:RegisterEvent("CHAT_MSG_LOOT") UIParent:UnregisterEvent("START_LOOT_ROLL") UIParent:UnregisterEvent("CANCEL_LOOT_ROLL") anchor:SetScript("OnEvent", function(frame, event, ...) if event == "CHAT_MSG_LOOT" then return CHAT_MSG_LOOT(...) else return START_LOOT_ROLL(...) end end) anchor:SetPoint("BOTTOMRIGHT", AnchorLootRoll) end)
gpl-2.0
n0xus/darkstar
scripts/zones/Outer_Horutoto_Ruins/npcs/_5ef.lua
17
3319
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: Ancient Magical Gizmo #2 (F out of E, F, G, H, I, J) -- Involved In Mission: The Heart of the Matter ----------------------------------- package.loaded["scripts/zones/Outer_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Outer_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Check if we are on Windurst Mission 1-2 if (player:getCurrentMission(WINDURST) == THE_HEART_OF_THE_MATTER) then MissionStatus = player:getVar("MissionStatus"); if (MissionStatus == 2) then -- Entered a Dark Orb if (player:getVar("MissionStatus_orb2") == 1) then player:startEvent(0x002f); else player:messageSpecial(ORB_ALREADY_PLACED); end elseif (MissionStatus == 4) then -- Took out a Glowing Orb if (player:getVar("MissionStatus_orb2") == 2) then player:startEvent(0x002f); else player:messageSpecial(G_ORB_ALREADY_GOTTEN); end else player:messageSpecial(DARK_MANA_ORB_RECHARGER); end else player:messageSpecial(DARK_MANA_ORB_RECHARGER); end 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); if (csid == 0x002f) then orb_value = player:getVar("MissionStatus_orb2"); if (orb_value == 1) then player:setVar("MissionStatus_orb2",2); -- Push the text that the player has placed the orb player:messageSpecial(SECOND_DARK_ORB_IN_PLACE); --Delete the key item player:delKeyItem(SECOND_DARK_MANA_ORB); -- Check if all orbs have been placed or not if (player:getVar("MissionStatus_orb1") == 2 and player:getVar("MissionStatus_orb3") == 2 and player:getVar("MissionStatus_orb4") == 2 and player:getVar("MissionStatus_orb5") == 2 and player:getVar("MissionStatus_orb6") == 2) then player:messageSpecial(ALL_DARK_MANA_ORBS_SET); player:setVar("MissionStatus",3); end elseif (orb_value == 2) then player:setVar("MissionStatus_orb2",3); -- Time to get the glowing orb out player:addKeyItem(SECOND_GLOWING_MANA_ORB); player:messageSpecial(KEYITEM_OBTAINED,SECOND_GLOWING_MANA_ORB); -- Check if all orbs have been placed or not if (player:getVar("MissionStatus_orb1") == 3 and player:getVar("MissionStatus_orb3") == 3 and player:getVar("MissionStatus_orb4") == 3 and player:getVar("MissionStatus_orb5") == 3 and player:getVar("MissionStatus_orb6") == 3) then player:messageSpecial(RETRIEVED_ALL_G_ORBS); player:setVar("MissionStatus",5); end end end end;
gpl-3.0
mwgoldsmith/vlc
share/lua/playlist/pinkbike.lua
97
2080
--[[ $Id$ Copyright © 2009 the VideoLAN team Authors: Konstantin Pavlov (thresh@videolan.org) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "pinkbike.com/video/%d+" ) end -- Parse function. function parse() p = {} if string.match ( vlc.path, "pinkbike.com/video/%d+" ) then while true do line = vlc.readline() if not line then break end -- Try to find video id if string.match( line, "video_src.+swf.id=(.*)\"") then _,_,videoid = string.find( line, "video_src.+swf.id=(.*)\"") catalog = math.floor( tonumber( videoid ) / 10000 ) end -- Try to find the video's title if string.match( line, "<title>(.*)</title>" ) then _,_,name = string.find (line, "<title>(.*)</title>") end -- Try to find server which has our video if string.match( line, "<link rel=\"videothumbnail\" href=\"http://(.*)/vt/svt-") then _,_,server = string.find (line, '<link rel="videothumbnail" href="http://(.*)/vt/svt-' ) end if string.match( line, "<link rel=\"videothumbnail\" href=\"(.*)\" type=\"image/jpeg\"") then _,_,arturl = string.find (line, '<link rel="videothumbnail" href="(.*)" type="image/jpeg"') end end end table.insert( p, { path = "http://" .. server .. "/vf/" .. catalog .. "/pbvid-" .. videoid .. ".flv"; name = name; arturl = arturl } ) return p end
gpl-2.0
Primordus/lua-quickcheck
spec/quickcheck_spec.lua
2
4007
local lqc = require 'lqc.quickcheck' local r = require 'lqc.report' local property = require 'lqc.property' local function clear_properties() lqc.init(100, 100) lqc.properties = {} r.report = function(_) end end local function failing_gen() local gen = {} function gen.pick(_) return -2 end function gen.shrink(_, prev) if prev == 0 then return 0 end return prev + 1 end return gen end describe('quickcheck', function() before_each(clear_properties) describe('check function', function() it('should check every successful property X amount of times', function() local prop_amount = 5 local spy_check = spy.new(function() return true end) for _ = 1, prop_amount do property 'test property' { generators = {}, check = spy_check } end lqc.check() local expected = prop_amount * lqc.numtests assert.spy(spy_check).was.called(expected) end) it('should continue to check if a constraint of property is not met', function() local spy_check = spy.new(function() return true end) local spy_implies = spy.new(function() return false end) property 'test property' { generators = {}, check = spy_check, implies = spy_implies } lqc.check() local expected = lqc.numtests assert.spy(spy_check).was.not_called() assert.spy(spy_implies).was.called(expected) end) it('should stop checking a property after a failure', function() local x, iterations = 0, 10 property 'test property' { generators = {}, check = function() x = x + 1 return x < iterations end } lqc.check() local expected = iterations assert.equal(expected, x) end) end) describe('shrink function', function() it('should try to reduce failing properties to a simpler form (0 params)', function() local generated_values local shrunk_values r.report_failed_property = function(_, generated_vals, shrunk_vals) generated_values = generated_vals shrunk_values = shrunk_vals end property 'failing property' { generators = {}, check = function() return false end } lqc.check() assert.same(generated_values, {}) assert.same(shrunk_values, {}) end) it('should try to reduce failing properties to a simpler form (1 param)', function() local generated_values local shrunk_values r.report_failed_property = function(_, generated_vals, shrunk_vals) generated_values = generated_vals shrunk_values = shrunk_vals end property 'failing property' { generators = { failing_gen() }, check = function(x) return x >= 0 end } lqc.check() assert.same({ -2 }, generated_values) assert.same({ -1 }, shrunk_values) end) it('should try to reduce failing properties to a simpler form (2 params)', function() local generated_values local shrunk_values r.report_failed_property = function(_, generated_vals, shrunk_vals) generated_values = generated_vals shrunk_values = shrunk_vals end property 'failing property' { generators = { failing_gen(), failing_gen() }, check = function(x, y) return x > y end } lqc.check() assert.same({ -2, -2 }, generated_values) for i = 1, #generated_values do assert.is_true(generated_values[i] <= shrunk_values[i]) end assert.is_true(shrunk_values[1] >= shrunk_values[2]) end) end) describe('init function', function() it('should be called before quickcheck.check or it will raise an error', function() lqc.init(nil, nil) assert.is_false(pcall(function() lqc.check() end)) lqc.init(100, 100) assert.is_true(pcall(function() lqc.check() end)) end) end) end)
mit
n0xus/darkstar
scripts/zones/RuLude_Gardens/npcs/relic.lua
41
1848
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: <this space intentionally left blank> -- @pos 0 8 -40 243 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece if (player:getVar("RELIC_IN_PROGRESS") == 18293 and trade:getItemCount() == 4 and trade:hasItemQty(18293,1) and trade:hasItemQty(1576,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1457,1)) then player:startEvent(10035,18294); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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 == 10035) then if (player:getFreeSlotsCount() < 2) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18294); player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1456); else player:tradeComplete(); player:addItem(18294); player:addItem(1456,30); player:messageSpecial(ITEM_OBTAINED,18294); player:messageSpecial(ITEMS_OBTAINED,1456,30); player:setVar("RELIC_IN_PROGRESS",0); end end end;
gpl-3.0
aasare/aaku
nvim/lua/plugins/cmp.lua
1
3196
local require_safe = require("utils").require_safe local cmp = require_safe("cmp") local luasnip = require_safe("luasnip") require("luasnip/loaders/from_vscode").lazy_load() local has_words_before = function() local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil end local mappings = cmp.mapping.preset.insert({ ["<C-k>"] = cmp.mapping(cmp.mapping.select_prev_item(), { 'i', 'c' }), ["<C-j>"] = cmp.mapping(cmp.mapping.select_next_item(), { 'i', 'c' }), ['<C-b>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ["<CR>"] = cmp.mapping.confirm { behavior = cmp.ConfirmBehavior.Replace, select = false, }, ['<C-Space>'] = cmp.mapping.complete(), ["<C-y>"] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping. ["<C-e>"] = cmp.mapping { i = cmp.mapping.abort(), c = cmp.mapping.close(), }, -- Accept currently selected item. If none selected, `select` first item. -- Set `select` to `false` to only confirm explicitly selected items. ["<Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif luasnip.expandable() then luasnip.expand() elseif luasnip.expand_or_jumpable() then luasnip.expand_or_jump() elseif has_words_before() then fallback() else fallback() end end, { "i", "s", }), ["<S-Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() elseif luasnip.jumpable(-1) then luasnip.jump(-1) else fallback() end end, { "i", "s", }), }) cmp.setup { completion = { completeopt = "menu,menuone,noinsert", keyword_length = 2, }, snippet = { expand = function(args) luasnip.lsp_expand(args.body) -- For `luasnip` users. end, }, mapping = mappings, formatting = { fields = { "abbr", "menu" }, format = function(entry, vim_item) vim_item.menu = ({ nvim_lsp = "[LSP]", luasnip = "[Snippet]", buffer = "[Buffer]", path = "[Path]", })[entry.source.name] return vim_item end, }, sources = { { name = "nvim_lsp" }, { name = "luasnip" }, { name = "buffer" }, { name = "path" }, }, window = { completion = { border = 'rounded', winhighlight = 'NormalFloat:NormalFloat,FloatBorder:FloatBorder,CursorLine:PmenuSel', }, documentation = { border = 'rounded', winhighlight = 'NormalFloat:NormalFloat,FloatBorder:FloatBorder,CursorLine:PmenuSel', }, }, preselect = cmp.PreselectMode.None, confirmation = { get_commit_characters = function() return {} end, }, experimental = { native_menu = false, ghost_text = false, }, } cmp.setup.cmdline("/", { mapping = cmp.mapping.preset.cmdline(), sources = { { name = "buffer" }, }, }) cmp.setup.cmdline(":", { mapping = cmp.mapping.preset.cmdline(), sources = cmp.config.sources({ { name = "path" }, }, { { name = "cmdline" }, }), })
mit
n0xus/darkstar
scripts/zones/Northern_San_dOria/npcs/Villion.lua
14
1386
----------------------------------- -- Area: Northern San d'Oria -- NPC: Villion -- Type: Adventurer's Assistant NPC -- Involved in Quest: Flyers for Regine -- @zone: 231 -- @pos -157.524 4.000 263.818 -- ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) ==QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeVilion") == 0) then player:messageSpecial(11932); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradeVilion",1); player:messageSpecial(FLYER_ACCEPTED); trade:complete(); elseif (player:getVar("tradeVilion") ==1) then player:messageSpecial(11936); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0278); 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
n0xus/darkstar
scripts/zones/Metalworks/npcs/Abbudin.lua
34
1045
----------------------------------- -- Area: Metalworks -- NPC: Abbudin -- Type: Standard Info NPC -- @pos -56.338 2.777 -31.446 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x022E); 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
n0xus/darkstar
scripts/zones/Temenos/mobs/Water_Elemental.lua
16
1711
----------------------------------- -- Area: Temenos E T -- NPC: Water_Elemental ----------------------------------- 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) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); switch (mobID): caseof { -- 100 a 106 inclut (Temenos -Northern Tower ) [16928885] = function (x) GetNPCByID(16928768+277):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+277):setStatus(STATUS_NORMAL); end , [16928886] = function (x) GetNPCByID(16928768+190):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+190):setStatus(STATUS_NORMAL); end , [16928887] = function (x) GetNPCByID(16928768+127):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+127):setStatus(STATUS_NORMAL); end , [16928888] = function (x) GetNPCByID(16928768+69):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+69):setStatus(STATUS_NORMAL); end , [16929038] = function (x) if (IsMobDead(16929033)==false) then DespawnMob(16929033); SpawnMob(16929039); end end , } end;
gpl-3.0
n0xus/darkstar
scripts/zones/Metalworks/npcs/Franziska.lua
17
1172
----------------------------------- -- Area: Metalworks -- NPC: Franziska -- Type: Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("OptionalcsCornelia") ==1) then player:startEvent(0x0309); else player:startEvent(0x026C); 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); if (csid == 0x0309) then player:setVar("OptionalcsCornelia",0); end end;
gpl-3.0
feiying1460/witi-openwrt
package/ramips/ui/luci-mtk/src/applications/luci-statistics/luasrc/model/cbi/luci_statistics/ping.lua
80
1397
--[[ Luci configuration model for statistics - collectd ping plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("Ping Plugin Configuration"), translate( "The ping plugin will send icmp echo replies to selected " .. "hosts and measure the roundtrip time for each host." )) -- collectd_ping config section s = m:section( NamedSection, "collectd_ping", "luci_statistics" ) -- collectd_ping.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_ping.hosts (Host) hosts = s:option( Value, "Hosts", translate("Monitor hosts"), translate ("Add multiple hosts separated by space.")) hosts.default = "127.0.0.1" hosts:depends( "enable", 1 ) -- collectd_ping.ttl (TTL) ttl = s:option( Value, "TTL", translate("TTL for ping packets") ) ttl.isinteger = true ttl.default = 128 ttl:depends( "enable", 1 ) -- collectd_ping.interval (Interval) interval = s:option( Value, "Interval", translate("Interval for pings"), translate ("Seconds") ) interval.isinteger = true interval.default = 30 interval:depends( "enable", 1 ) return m
gpl-2.0
n0xus/darkstar
scripts/zones/Ship_bound_for_Mhaura/Zone.lua
34
1464
----------------------------------- -- -- Zone: Ship_bound_for_Mhaura (221) -- ----------------------------------- package.loaded["scripts/zones/Ship_bound_for_Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Ship_bound_for_Mhaura/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then local position = math.random(-2,2) + 0.150; player:setPos(position,-2.100,3.250,64); end return cs; end; ----------------------------------- -- onTransportEvent ----------------------------------- function onTransportEvent(player,transport) player:startEvent(0x0200); 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 == 0x0200) then player:setPos(0,0,0,0,249); end end;
gpl-3.0
n0xus/darkstar
scripts/zones/Open_sea_route_to_Mhaura/npcs/Pashi_Maccaleh.lua
17
1246
----------------------------------- -- Area: Open sea route to Mhaura -- NPC: Pashi Maccaleh -- Guild Merchant NPC: Fishing Guild -- @zone 4.986 -2.101 -12.026 47 ----------------------------------- package.loaded["scripts/zones/Open_sea_route_to_Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Open_sea_route_to_Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(523,1,23,5)) then player:showText(npc,PASHI_MACCALEH_SHOP_DIALOG); 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
n0xus/darkstar
scripts/zones/Cloister_of_Storms/bcnms/carbuncle_debacle.lua
19
1480
----------------------------------- -- Area: Cloister of Storms -- BCNM: Carbuncle Debacle ----------------------------------- package.loaded["scripts/zones/Cloister_of_Storms/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Cloister_of_Storms/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0,0); elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then player:setVar("CarbuncleDebacleProgress",4); end; end;
gpl-3.0
n0xus/darkstar
scripts/zones/RuLude_Gardens/npcs/Pakh_Jatalfih.lua
17
2737
----------------------------------- -- Area: Ru'Lud Gardens -- NPC: Pakh Jatalfih -- @pos 34 8 -35 243 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; package.loaded["scripts/globals/missions"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) pNation = player:getNation(); if (pNation == WINDURST) then currentMission = player:getCurrentMission(pNation); MissionStatus = player:getVar("MissionStatus"); if (currentMission == A_NEW_JOURNEY and MissionStatus == 1) then player:startEvent(0x002B); elseif (currentMission == A_NEW_JOURNEY and MissionStatus == 2) then player:startEvent(0x0044); elseif (currentMission == A_NEW_JOURNEY and MissionStatus == 3) then player:startEvent(0x008D); elseif (player:getRank() == 4 and MissionStatus == 0) then if (getMissionRankPoints(player,13) == 1) then player:startEvent(0x0032); else player:startEvent(0x0036); end elseif (player:getRank() == 4 and player:getCurrentMission(WINDURST) == 255 and MissionStatus ~= 0 and getMissionRankPoints(player,13) == 1) then player:startEvent(0x0086); elseif (currentMission == MAGICITE and MissionStatus == 2) then player:startEvent(0x0089); elseif (currentMission == MAGICITE and MissionStatus == 6) then player:startEvent(0x0025); elseif (player:hasKeyItem(MESSAGE_TO_JEUNO_WINDURST)) then player:startEvent(0x0039); elseif (player:getRank() >= 5) then player:startEvent(0x0039); else player:startEvent(0x006b); end elseif (pNation == SANDORIA) then player:startEvent(0x0034); elseif (pNation == BASTOK) then player:startEvent(0x0033); 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); if (csid == 0x002B) then player:setVar("MissionStatus",2); elseif (csid == 0x008D) then player:setVar("MissionStatus",4); elseif (csid == 0x0025) then finishMissionTimeline(player,1,csid,option); end end;
gpl-3.0
sam1i/Turres-Monacorum
love2d/layer/hud.lua
1
8556
energyColour = {255,127,0} energyLevelFillColour = {255,127,0,15} massColour ={ 0, 255, 127} massLevelFillColour ={ 0, 127, 255,15} laserColour = {0,127,255} alarmColour = {255,0,0} function love.turris.newHudLayer(player) local o = {} o.iconMass = G.newImage("gfx/hud/mass_icon.png") o.iconEnergy = G.newImage("gfx/hud/energy_icon.png") o.iconTower1 = G.newImage("gfx/hud/button_tower00.png") o.iconTower2 = G.newImage("gfx/hud/button_tower01.png") o.iconTower3 = G.newImage("gfx/hud/button_tower02.png") -- create gui elements o.guiGame = love.gui.newGui() o.btnTower1 = o.guiGame.newImageRadioButton(208 * 0 + 16, W.getHeight() - 75, 192, 57, o.iconTower1) o.btnTower2 = o.guiGame.newImageRadioButton(208 * 1 + 16, W.getHeight() - 75, 192, 57, o.iconTower2) o.btnTower3 = o.guiGame.newImageRadioButton(208 * 2 + 16, W.getHeight() - 75, 192, 57, o.iconTower3) -- config gui elements --o.btnTower1.setFontSize(16) --o.btnTower1.setText("Laser Tower (1)") o.btnTower1.setTextPosition(32, -32) o.btnTower1.setImagePosition(4, -11) o.btnTower1.setChecked(false) --o.btnTower2.setFontSize(16) --o.btnTower2.setText("Energy Tower (3)") o.btnTower2.setTextPosition(32, -32) o.btnTower2.setImagePosition(4, -13) --o.btnTower3.setFontSize(16) --o.btnTower3.setText("Mass Tower (4)") o.btnTower3.setTextPosition(32, -32) o.btnTower3.setImagePosition(4, -11) o.btnTower1.setColorNormal(0, 127, 255, 63) o.btnTower2.setColorNormal(255, 127, 0, 63) o.btnTower3.setColorNormal(0, 255, 127, 63) o.btnTower1.setColorHover(0, 127, 255, 255) o.btnTower2.setColorHover(255, 127, 0, 255) o.btnTower3.setColorHover(0, 255, 127, 255) -- set font o.fontTitle = G.newFont(24) o.fontDescription = G.newFont(16) o.player = player o.update = function(dt) o.guiGame.update(dt) if o.btnTower1.isHit() then love.turris.selectedtower = 1 elseif o.btnTower2.isHit() then love.turris.selectedtower = 3 elseif o.btnTower3.isHit() then love.turris.selectedtower = 4 end --TODO: ignore keyboard selection when towers are disabled. Leaving this in here for now for debugging if love.keyboard.isDown("1") then love.turris.selectedtower = 1 o.btnTower1.setChecked(true) --elseif love.keyboard.isDown("2") then --love.turris.selectedtower = 2 --2 would be the main base which should not be available for manual building --o.guiGame.flushRadioButtons() elseif love.keyboard.isDown("2") then love.turris.selectedtower = 3 o.btnTower2.setChecked(true) elseif love.keyboard.isDown("3") then love.turris.selectedtower = 4 o.guiGame.flushRadioButtons() o.btnTower3.setChecked(true) --elseif love.keyboard.isDown("5") then --love.turris.selectedtower = 5 --o.guiGame.flushRadioButtons() end end o.draw = function() local mass = o.player.mass local energy = o.player.energy G.setBlendMode("alpha") G.setLineWidth(4) if not lightWorld.optionGlow then G.setColor(0, 0, 0, 91) G.rectangle("line", W.getWidth() - 352, 16, 160, 36) G.printf(math.floor(mass), W.getWidth() - 352 + 2, 16 + 2, 128, "right") G.draw(o.iconMass, W.getWidth() - 208 + 2, 34 + 2, love.timer.getTime() * 0.5, 1, 1, 8, 8) G.rectangle("line", W.getWidth() - 176, 16, 160, 36) G.printf(math.floor(energy), W.getWidth() - 176 + 2, 16 + 2, 128, "right") G.setColor(0, 0, 0, 91 + math.sin(love.timer.getTime() * 5.0) * 63) G.draw(o.iconEnergy, W.getWidth() - 40 + 2, 16 + 2) end G.setFont(FONT) G.setLineWidth(2) -- mass level if not turGame.disableUI.massDisplayDisabled then G.setColor(massColour) G.rectangle("line", W.getWidth() - 352, 16, 160, 36) G.setColor(massLevelFillColour) G.rectangle("fill", W.getWidth() - 352, 16, 160, 36) G.setColor(massColour, 255) if mass <= 1 then G.setColor(alarmColour,255) end G.printf(math.floor(mass), W.getWidth() - 352, 16, 128, "right") G.draw(o.iconMass, W.getWidth() - 208, 34, love.timer.getTime() * 0.5, 1, 1, 8, 8) end -- energy level if not turGame.disableUI.energyDisplayDisabled then G.setColor(energyColour) G.rectangle("line", W.getWidth() - 176, 16, 160, 36) G.setColor(energyLevelFillColour) G.rectangle("fill", W.getWidth() - 176, 16, 160, 36) G.setColor(energyColour, 255) if energy <= 1 then G.setColor(alarmColour,255) end G.printf(math.floor(energy), W.getWidth() - 176, 16, 128, "right") G.setColor(energyColour, 191 + math.sin(love.timer.getTime() * 5.0) * 63) G.draw(o.iconEnergy, W.getWidth() - 40, 16) end -- buttons --laser tower if turGame.disableUI.laserTowerDisplayDisabled then o.btnTower1.visible = false o.btnTower1.enabled = false else o.btnTower1.visible = true o.btnTower1.enabled = true if o.btnTower1.isChecked() then G.setColor(laserColour, 127) else G.setColor(laserColour, 31) end G.rectangle("fill", 208 * 0 + 16, W.getHeight() - 108, 192, 28) G.setFont(o.fontTitle) G.setColor(0, 0, 0) G.printf("Laser Tower", 208 * 0 + 16, W.getHeight() - 108, 192, "center") G.setFont(o.fontDescription) -- laser tower text if o.btnTower1.isChecked() then G.setColor(laserColour, 255) else G.setColor(laserColour, 127) end G.print("Cost: "..tostring(laserTower.buildCost).." M", 208 * 0 + 88, W.getHeight() - 68) G.print("Shoots laser!", 208 * 0 + 88, W.getHeight() - 44) end if turGame.disableUI.energyTowerDisplayDisabled then o.btnTower2.visible = false o.btnTower2.enabled = false else o.btnTower2.visible = true o.btnTower2.enabled = true if o.btnTower2.isChecked() then G.setColor(energyColour, 127) else G.setColor(energyColour, 31) end G.rectangle("fill", 208 * 1 + 16, W.getHeight() - 108, 192, 28) G.setFont(o.fontTitle) G.setColor(0, 0, 0) G.printf("Energy Tower", 208 * 1 + 16, W.getHeight() - 108, 192, "center") -- energy tower text G.setFont(o.fontDescription) if o.btnTower2.isChecked() then G.setColor(energyColour, 255) else G.setColor(energyColour, 127) end G.print("Cost: "..tostring(energyTower.buildCost).." M", 208 * 1 + 88, W.getHeight() - 68) G.print("Gives energy", 208 * 1 + 88, W.getHeight() - 44) end if turGame.disableUI.massTowerDisplayDisabled then o.btnTower3.visible = false o.btnTower3.enabled = false else o.btnTower3.visible = true o.btnTower3.enabled = true if o.btnTower3.isChecked() then G.setColor(massColour, 127) else G.setColor(massColour, 31) end G.rectangle("fill", 208 * 2 + 16, W.getHeight() - 108, 192, 28) --button header titles G.setFont(o.fontTitle) G.setColor(0, 0, 0) G.printf("Mass Tower", 208 * 2 + 16, W.getHeight() - 108, 192, "center") -- mass tower text if o.btnTower3.isChecked() then G.setColor(massColour, 255) else G.setColor(massColour, 127) end G.setFont(o.fontDescription) G.print("Cost: "..tostring(massTower.buildCost).." M", 208 * 2 + 88, W.getHeight() - 68) G.print("Extracts M", 208 * 2 + 88, W.getHeight() - 44) end -- draws buttons o.guiGame.draw() -- minimap -- G.setColor(127, 191, 255, 31) -- G.rectangle("fill", 16, 16, turGame.map.width * 8, turGame.map.height * 8) -- -- for i = 1, turGame.map.width do -- for k = 1, turGame.map.height do -- if turGame.map.data[i][k].id >= 1 then -- if turGame.map.data[i][k].id <= 4 then -- G.setColor(0, 255, 0, 127) -- elseif turGame.map.data[i][k].id >= 6 and turGame.map.data[i][k].id <= 7 then -- G.setColor(255, 127, 0, 127) -- else -- G.setColor(255, 255, 255, 31) -- end -- -- G.rectangle("fill", 16 + (i - 1) * 8, 16 + (k - 1) * 8, 8, 8) -- end -- end -- end --minimap enemies for i = 1, #turGame.enemies do if not turGame.enemies[i].dead then G.setColor(255, 0, 0, 127) G.rectangle("fill", 16 + (turGame.enemies[i].ai.getX() - 1) * 8, 16 + (turGame.enemies[i].ai.getY() - 1) * 8, 8, 8) end end end return o end
mit
n0xus/darkstar
scripts/zones/Lower_Jeuno/TextIDs.lua
9
5200
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6384; -- Obtained: <item>. GIL_OBTAINED = 6385; -- Obtained <number> gil. KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>. NOT_HAVE_ENOUGH_GIL = 6391; -- You do not have enough gil. HOMEPOINT_SET = 6511; -- Home point set! FISHING_MESSAGE_OFFSET = 6904; -- You can't fish here. INVENTORY_INCREASED = 7757; -- Your inventory capacity has increased. ITS_LOCKED = 7562; -- It's locked. -- Other Texts ITEM_DELIVERY_DIALOG = 7758; -- Now offering quick and easy delivery of packages to residences everywhere! GUIDE_STONE = 7115; -- Up: Upper Jeuno (Selection Dialogfacing San d'Oria) Down: Port Jeuno (Selection Dialogfacing Windurst) STREETLAMP_EXAMINE = 7229; -- You examine the lamp. It seems that it must be lit manually. PARIKE_PORANKE_DIALOG = 8929; -- All these people running back and forth... There have to be a few that have munched down more mithkabobs than they can manage. WAYPOINT_EXAMINE = 10317; -- An enigmatic contrivance hovers in silence... NO_KEY = 9881; -- You do not have a usable key in your possession. ALDO_DIALOG = 7120; -- Hi. I'm Aldo, head of Tenshodo. We deal in things you can't buy anywhere else. Take your time and have a look around. CHOCOBO_DIALOG = 7294; -- Hmph. PARIKE_PORANKE_1 = 8930; -- Hey you! Belly bursting? Intestines inflating? Bladder bulging? I can tell by the notch on your belt that you've been overindulging yourself in culinary delights. PARIKE_PORANKE_2 = 8933; -- I mean, this is a new era. If somebody wants to go around with their flabby-flubber hanging out of their cloaks, they should have every right to do so. If someone wants to walk around town with breath reeking of Kazham pines and roasted sleepshrooms, who am I to stop them PARIKE_PORANKE_3 = 8934; -- What? You want me to tend to your tummy trouble? No problem! And don't worry, this won't hurt at all! I'm only going to be flushing your bowels with thousands of tiny lightning bolts. It's all perfectly safe! PARIKE_PORANKE_4 = 8935; -- Now stand still! You wouldn't want your pelvis to implode, would you? (Let's see... What were those magic words again...?) PARIKE_PORANKE_5 = 8936; -- Ready? No? Well, too bad! PARIKE_PORANKE_6 = 8944; -- digestive magic skill rises 0.1 points. PARIKE_PORANKE_7 = 8945; -- digestive magic skill rises one level. PARIKE_PORANKE_8 = 8946; -- Heh heh! I think I'm starting to get the hang of this spellcasting. PARIKE_PORANKE_9 = 8947; -- Consider this a petite present from your pal Parike-Poranke! PARIKE_PORANKE_10 = 8951; -- Wait a minute... Don't tell me you came to Parike-Poranke on an empty stomach! This is terrible! The minister will have my head! PARIKE_PORANKE_12 = 8953; -- Phew! That was close... What were you thinking, crazy adventurer! PARIKE_PORANKE_13 = 8956; -- Speaker Name's ll in the name of science skill rises 0.1 points. PARIKE_PORANKE_14 = 8957; -- Speaker Name's ll in the name of science skill rises one level. PARIKE_PORANKE_15 = 8958; -- You know, I've learned a lot from my mist--er, I mean, less-than-successful attempts at weight-loss consulting. PARIKE_PORANKE_16 = 8959; -- To show you my gratitude, let me try out this new spell I thought up yesterday while I was taking a nap! MERTAIRE_DIALOG = 7400; -- Who are you? Leave me alone! -- Conquest system CONQUEST = 8031; -- You've earned conquest points! -- Shop Texts CREEPSTIX_SHOP_DIALOG = 7106; -- Hey, how ya doin'? We got the best junk in town. STINKNIX_SHOP_DIALOG = 7106; -- Hey, how ya doin'? We got the best junk in town. HASIM_SHOP_DIALOG = 7107; -- Welcome to Waag-Deeg's Magic Shop. TAZA_SHOP_DIALOG = 7107; -- Welcome to Waag-Deeg's Magic Shop. SUSU_SHOP_DIALOG = 7107; -- Welcome to Waag-Deeg's Magic Shop. CHETAK_SHOP_DIALOG = 7108; -- Welcome to Othon's Garments. CHENOKIH_SHOP_DIALOG = 7108; -- Welcome to Othon's Garments. YOSKOLO_SHOP_DIALOG = 7109; -- Welcome to the Merry Minstrel's Meadhouse. What'll it be? ADELFLETE_SHOP_DIALOG = 7110; -- Here at Gems by Kshama, we aim to please. MOREFIE_SHOP_DIALOG = 7110; -- Here at Gems by Kshama, we aim to please. MATOAKA_SHOP_DIALOG = 7110; -- Here at Gems by Kshama, we aim to please. RHIMONNE_SHOP_DIALOG = 7113; -- Howdy! Thanks for visiting the Chocobo Shop! PAWKRIX_SHOP_DIALOG = 7610; -- Hey, we're fixin' up some stew. Gobbie food's good food! AMALASANDA_SHOP_DIALOG = 7658; -- Welcome to the Tenshodo. You want something, we got it. We got all kinds of special merchandise you won't find anywhere else! AKAMAFULA_SHOP_DIALOG = 7659; -- We ain't cheap, but you get what you pay for! Take your time, have a look around, see if there's somethin' you like. -- conquest Base CONQUEST_BASE = 6528; -- Tallying conquest results... -- Porter Moogle RETRIEVE_DIALOG_ID = 10161; -- You retrieve a <item> from the porter moogle's care.
gpl-3.0
n0xus/darkstar
scripts/zones/VeLugannon_Palace/TextIDs.lua
9
1036
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6384; -- Obtained: <item> GIL_OBTAINED = 6385; -- Obtained <number> gil KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem> -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7209; -- You unlock the chest! CHEST_FAIL = 7210; -- Fails to open the chest. CHEST_TRAP = 7211; -- The chest was trapped! CHEST_WEAK = 7212; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7213; -- The chest was a mimic! CHEST_MOOGLE = 7214; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7215; -- The chest was but an illusion... CHEST_LOCKED = 7216; -- The chest appears to be locked. -- Other dialog NOTHING_OUT_OF_ORDINARY = 6398; -- There is nothing out of the ordinary here. -- conquest Base CONQUEST_BASE = 7043; -- Tallying conquest results...
gpl-3.0
n0xus/darkstar
scripts/zones/Garlaige_Citadel/Zone.lua
17
3962
----------------------------------- -- -- Zone: Garlaige_Citadel (200) -- ----------------------------------- package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/zone"); require("scripts/zones/Garlaige_Citadel/TextIDs"); banishing_gates_base = 17596761; -- _5k0 (First banishing gate) ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local tomes = {17596852,17596853,17596854}; SetGroundsTome(tomes); -- Banishing Gate #1... zone:registerRegion(1,-208,-1,224,-206,1,227); zone:registerRegion(2,-208,-1,212,-206,1,215); zone:registerRegion(3,-213,-1,224,-211,1,227); zone:registerRegion(4,-213,-1,212,-211,1,215); -- Banishing Gate #2 zone:registerRegion(10,-51,-1,82,-49,1,84); zone:registerRegion(11,-151,-1,82,-149,1,84); zone:registerRegion(12,-51,-1,115,-49,1,117); zone:registerRegion(13,-151,-1,115,-149,1,117); -- Banishing Gate #3 zone:registerRegion(19,-190,-1,355,-188,1,357); zone:registerRegion(20,-130,-1,355,-128,1,357); zone:registerRegion(21,-190,-1,322,-188,1,324); zone:registerRegion(22,-130,-1,322,-128,1,324); -- Old Two-Wings SetRespawnTime(17596506, 900, 10800); -- Skewer Sam SetRespawnTime(17596507, 900, 10800); -- Serket SetRespawnTime(17596720, 900, 10800); UpdateTreasureSpawnPoint(17596808); UpdateTreasureSpawnPoint(17596809); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-380.035,-13.548,398.032,64); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) local regionID = region:GetRegionID(); local mylever = banishing_gates_base + regionID; GetNPCByID(mylever):setAnimation(8); if (regionID >= 1 and regionID <= 4) then gateid = banishing_gates_base; msg_offset = 0; elseif (regionID >= 10 and regionID <= 13) then gateid = banishing_gates_base + 9; msg_offset = 1; elseif (regionID >= 19 and regionID <= 22) then gateid = banishing_gates_base + 18; msg_offset = 2; end; -- Open Gate gate1 = GetNPCByID(gateid + 1); gate2 = GetNPCByID(gateid + 2); gate3 = GetNPCByID(gateid + 3); gate4 = GetNPCByID(gateid + 4); if (gate1:getAnimation() == 8 and gate2:getAnimation() == 8 and gate3:getAnimation() == 8 and gate4:getAnimation() == 8) then player:messageSpecial(BANISHING_GATES + msg_offset); -- Banishing gate opening GetNPCByID(gateid):openDoor(30); end end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) local regionID = region:GetRegionID(); local mylever = banishing_gates_base + regionID; GetNPCByID(mylever):setAnimation(9); 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
goblinor/BomBus1
libs/fakeredis.lua
650
40405
local unpack = table.unpack or unpack --- Bit operations local ok,bit if _VERSION == "Lua 5.3" then bit = (load [[ return { band = function(x, y) return x & y end, bor = function(x, y) return x | y end, bxor = function(x, y) return x ~ y end, bnot = function(x) return ~x end, rshift = function(x, n) return x >> n end, lshift = function(x, n) return x << n end, } ]])() else ok,bit = pcall(require,"bit") if not ok then bit = bit32 end end assert(type(bit) == "table", "module for bitops not found") --- default sleep local default_sleep do local ok, mod = pcall(require, "socket") if ok and type(mod) == "table" then default_sleep = mod.sleep else default_sleep = function(n) local t0 = os.clock() while true do local delta = os.clock() - t0 if (delta < 0) or (delta > n) then break end end end end end --- Helpers local xdefv = function(ktype) if ktype == "list" then return {head = 0, tail = 0} elseif ktype == "zset" then return { list = {}, set = {}, } else return {} end end local xgetr = function(self, k, ktype) if self.data[k] then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) assert(self.data[k].value) return self.data[k].value else return xdefv(ktype) end end local xgetw = function(self, k, ktype) if self.data[k] and self.data[k].value then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) else self.data[k] = {ktype = ktype, value = xdefv(ktype)} end return self.data[k].value end local empty = function(self, k) local v, t = self.data[k].value, self.data[k].ktype if t == nil then return true elseif t == "string" then return not v[1] elseif (t == "hash") or (t == "set") then for _,_ in pairs(v) do return false end return true elseif t == "list" then return v.head == v.tail elseif t == "zset" then if #v.list == 0 then for _,_ in pairs(v.set) do error("incoherent") end return true else for _,_ in pairs(v.set) do return(false) end error("incoherent") end else error("unsupported") end end local cleanup = function(self, k) if empty(self, k) then self.data[k] = nil end end local is_integer = function(x) return (type(x) == "number") and (math.floor(x) == x) end local overflows = function(n) return (n > 2^53-1) or (n < -2^53+1) end local is_bounded_integer = function(x) return (is_integer(x) and (not overflows(x))) end local is_finite_number = function(x) return (type(x) == "number") and (x > -math.huge) and (x < math.huge) end local toint = function(x) if type(x) == "string" then x = tonumber(x) end return is_bounded_integer(x) and x or nil end local tofloat = function(x) if type(x) == "number" then return x end if type(x) ~= "string" then return nil end local r = tonumber(x) if r then return r end if x == "inf" or x == "+inf" then return math.huge elseif x == "-inf" then return -math.huge else return nil end end local tostr = function(x) if is_bounded_integer(x) then return string.format("%d", x) else return tostring(x) end end local char_bitcount = function(x) assert( (type(x) == "number") and (math.floor(x) == x) and (x >= 0) and (x < 256) ) local n = 0 while x ~= 0 do x = bit.band(x, x-1) n = n+1 end return n end local chkarg = function(x) if type(x) == "number" then x = tostr(x) end assert(type(x) == "string") return x end local chkargs = function(n, ...) local arg = {...} assert(#arg == n) for i=1,n do arg[i] = chkarg(arg[i]) end return unpack(arg) end local getargs = function(...) local arg = {...} local n = #arg; assert(n > 0) for i=1,n do arg[i] = chkarg(arg[i]) end return arg end local getargs_as_map = function(...) local arg, r = getargs(...), {} assert(#arg%2 == 0) for i=1,#arg,2 do r[arg[i]] = arg[i+1] end return r end local chkargs_wrap = function(f, n) assert( (type(f) == "function") and (type(n) == "number") ) return function(self, ...) return f(self, chkargs(n, ...)) end end local lset_to_list = function(s) local r = {} for v,_ in pairs(s) do r[#r+1] = v end return r end local nkeys = function(x) local r = 0 for _,_ in pairs(x) do r = r + 1 end return r end --- Commands -- keys local del = function(self, ...) local arg = getargs(...) local r = 0 for i=1,#arg do if self.data[arg[i]] then r = r + 1 end self.data[arg[i]] = nil end return r end local exists = function(self, k) return not not self.data[k] end local keys = function(self, pattern) assert(type(pattern) == "string") -- We want to convert the Redis pattern to a Lua pattern. -- Start by escaping dashes *outside* character classes. -- We also need to escape percents here. local t, p, n = {}, 1, #pattern local p1, p2 while true do p1, p2 = pattern:find("%[.+%]", p) if p1 then if p1 > p then t[#t+1] = {true, pattern:sub(p, p1-1)} end t[#t+1] = {false, pattern:sub(p1, p2)} p = p2+1 if p > n then break end else t[#t+1] = {true, pattern:sub(p, n)} break end end for i=1,#t do if t[i][1] then t[i] = t[i][2]:gsub("[%%%-]", "%%%0") else t[i] = t[i][2]:gsub("%%", "%%%%") end end -- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]' -- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is. -- Wrap in '^$' to enforce bounds. local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0") :gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$" local r = {} for k,_ in pairs(self.data) do if k:match(lp) then r[#r+1] = k end end return r end local _type = function(self, k) return self.data[k] and self.data[k].ktype or "none" end local randomkey = function(self) local ks = lset_to_list(self.data) local n = #ks if n > 0 then return ks[math.random(1, n)] else return nil end end local rename = function(self, k, k2) assert((k ~= k2) and self.data[k]) self.data[k2] = self.data[k] self.data[k] = nil return true end local renamenx = function(self, k, k2) if self.data[k2] then return false else return rename(self, k, k2) end end -- strings local getrange, incrby, set local append = function(self, k, v) local x = xgetw(self, k, "string") x[1] = (x[1] or "") .. v return #x[1] end local bitcount = function(self, k, i1, i2) k = chkarg(k) local s if i1 or i2 then assert(i1 and i2, "ERR syntax error") s = getrange(self, k, i1, i2) else s = xgetr(self, k, "string")[1] or "" end local r, bytes = 0,{s:byte(1, -1)} for i=1,#bytes do r = r + char_bitcount(bytes[i]) end return r end local bitop = function(self, op, k, ...) assert(type(op) == "string") op = op:lower() assert( (op == "and") or (op == "or") or (op == "xor") or (op == "not"), "ERR syntax error" ) k = chkarg(k) local arg = {...} local good_arity = (op == "not") and (#arg == 1) or (#arg > 0) assert(good_arity, "ERR wrong number of arguments for 'bitop' command") local l, vals = 0, {} local s for i=1,#arg do s = xgetr(self, arg[i], "string")[1] or "" if #s > l then l = #s end vals[i] = s end if l == 0 then del(self, k) return 0 end local vector_mt = {__index=function() return 0 end} for i=1,#vals do vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt) end local r = {} if op == "not" then assert(#vals[1] == l) for i=1,l do r[i] = bit.band(bit.bnot(vals[1][i]), 0xff) end else local _op = bit["b" .. op] for i=1,l do local t = {} for j=1,#vals do t[j] = vals[j][i] end r[i] = _op(unpack(t)) end end set(self, k, string.char(unpack(r))) return l end local decr = function(self, k) return incrby(self, k, -1) end local decrby = function(self, k, n) n = toint(n) assert(n, "ERR value is not an integer or out of range") return incrby(self, k, -n) end local get = function(self, k) local x = xgetr(self, k, "string") return x[1] end local getbit = function(self, k, offset) k = chkarg(k) offset = toint(offset) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" if bytepos >= #s then return 0 end local char = s:sub(bytepos+1, bytepos+1):byte() return bit.band(bit.rshift(char, 7-bitpos), 1) end getrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetr(self, k, "string") x = x[1] or "" if i1 >= 0 then i1 = i1 + 1 end if i2 >= 0 then i2 = i2 + 1 end return x:sub(i1, i2) end local getset = function(self, k, v) local r = get(self, k) set(self, k, v) return r end local incr = function(self, k) return incrby(self, k, 1) end incrby = function(self, k, n) k, n = chkarg(k), toint(n) assert(n, "ERR value is not an integer or out of range") local x = xgetw(self, k, "string") local i = toint(x[1] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[1] = tostr(i) return i end local incrbyfloat = function(self, k, n) k, n = chkarg(k), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "string") local i = tofloat(x[1] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[1] = tostr(i) return i end local mget = function(self, ...) local arg, r = getargs(...), {} for i=1,#arg do r[i] = get(self, arg[i]) end return r end local mset = function(self, ...) local argmap = getargs_as_map(...) for k,v in pairs(argmap) do set(self, k, v) end return true end local msetnx = function(self, ...) local argmap = getargs_as_map(...) for k,_ in pairs(argmap) do if self.data[k] then return false end end for k,v in pairs(argmap) do set(self, k, v) end return true end set = function(self, k, v) self.data[k] = {ktype = "string", value = {v}} return true end local setbit = function(self, k, offset, b) k = chkarg(k) offset, b = toint(offset), toint(b) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) assert( (b == 0) or (b == 1), "ERR bit is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" local pad = {s} for i=2,bytepos+2-#s do pad[i] = "\0" end s = table.concat(pad) assert(#s >= bytepos+1) local before = s:sub(1, bytepos) local char = s:sub(bytepos+1, bytepos+1):byte() local after = s:sub(bytepos+2, -1) local old = bit.band(bit.rshift(char, 7-bitpos), 1) if b == 1 then char = bit.bor(bit.lshift(1, 7-bitpos), char) else char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char) end local r = before .. string.char(char) .. after set(self, k, r) return old end local setnx = function(self, k, v) if self.data[k] then return false else return set(self, k, v) end end local setrange = function(self, k, i, s) local k, s = chkargs(2, k, s) i = toint(i) assert(i and (i >= 0)) local x = xgetw(self, k, "string") local y = x[1] or "" local ly, ls = #y, #s if i > ly then -- zero padding local t = {} for i=1, i-ly do t[i] = "\0" end y = y .. table.concat(t) .. s else y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly) end x[1] = y return #y end local strlen = function(self, k) local x = xgetr(self, k, "string") return x[1] and #x[1] or 0 end -- hashes local hdel = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local r = 0 local x = xgetw(self, k, "hash") for i=1,#arg do if x[arg[i]] then r = r + 1 end x[arg[i]] = nil end cleanup(self, k) return r end local hget local hexists = function(self, k, k2) return not not hget(self, k, k2) end hget = function(self, k, k2) local x = xgetr(self, k, "hash") return x[k2] end local hgetall = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,v in pairs(x) do r[_k] = v end return r end local hincrby = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), toint(n) assert(n, "ERR value is not an integer or out of range") assert(type(n) == "number") local x = xgetw(self, k, "hash") local i = toint(x[k2] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[k2] = tostr(i) return i end local hincrbyfloat = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "hash") local i = tofloat(x[k2] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[k2] = tostr(i) return i end local hkeys = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,_ in pairs(x) do r[#r+1] = _k end return r end local hlen = function(self, k) local x = xgetr(self, k, "hash") return nkeys(x) end local hmget = function(self, k, k2s) k = chkarg(k) assert((type(k2s) == "table")) local r = {} local x = xgetr(self, k, "hash") for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end return r end local hmset = function(self, k, ...) k = chkarg(k) local arg = {...} if type(arg[1]) == "table" then assert(#arg == 1) local x = xgetw(self, k, "hash") for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end else assert(#arg % 2 == 0) local x = xgetw(self, k, "hash") local t = getargs(...) for i=1,#t,2 do x[t[i]] = t[i+1] end end return true end local hset = function(self, k, k2, v) local x = xgetw(self, k, "hash") local r = not x[k2] x[k2] = v return r end local hsetnx = function(self, k, k2, v) local x = xgetw(self, k, "hash") if x[k2] == nil then x[k2] = v return true else return false end end local hvals = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _,v in pairs(x) do r[#r+1] = v end return r end -- lists (head = left, tail = right) local _l_real_i = function(x, i) if i < 0 then return x.tail+i+1 else return x.head+i+1 end end local _l_len = function(x) return x.tail - x.head end local _block_for = function(self, timeout) if timeout > 0 then local sleep = self.sleep or default_sleep if type(sleep) == "function" then sleep(timeout) else error("sleep function unavailable", 0) end else error("operation would block", 0) end end local rpoplpush local blpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpoplpush = function(self, k1, k2, timeout) k1, k2 = chkargs(2, k1, k2) timeout = toint(timeout) if not self.data[k1] then _block_for(self, timeout) end return rpoplpush(self, k1, k2) end local lindex = function(self, k, i) k = chkarg(k) i = assert(toint(i)) local x = xgetr(self, k, "list") return x[_l_real_i(x, i)] end local linsert = function(self, k, mode, pivot, v) mode = mode:lower() assert((mode == "before") or (mode == "after")) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local p = nil for i=x.head+1, x.tail do if x[i] == pivot then p = i break end end if not p then return -1 end if mode == "after" then for i=x.head+1, p do x[i-1] = x[i] end x.head = x.head - 1 else for i=x.tail, p, -1 do x[i+1] = x[i] end x.tail = x.tail + 1 end x[p] = v return _l_len(x) end local llen = function(self, k) local x = xgetr(self, k, "list") return _l_len(x) end local lpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return r end local lpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x[x.head] = vs[i] x.head = x.head - 1 end return _l_len(x) end local lpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x[x.head] = v x.head = x.head - 1 return _l_len(x) end local lrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x, r = xgetr(self, k, "list"), {} i1 = math.max(_l_real_i(x, i1), x.head+1) i2 = math.min(_l_real_i(x, i2), x.tail) for i=i1,i2 do r[#r+1] = x[i] end return r end local _lrem_i = function(x, p) for i=p,x.tail do x[i] = x[i+1] end x.tail = x.tail - 1 end local _lrem_l = function(x, v, s) assert(v) if not s then s = x.head+1 end for i=s,x.tail do if x[i] == v then _lrem_i(x, i) return i end end return false end local _lrem_r = function(x, v, s) assert(v) if not s then s = x.tail end for i=s,x.head+1,-1 do if x[i] == v then _lrem_i(x, i) return i end end return false end local lrem = function(self, k, count, v) k, v = chkarg(k), chkarg(v) count = assert(toint(count)) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local n, last = 0, nil local op = (count < 0) and _lrem_r or _lrem_l local limited = (count ~= 0) count = math.abs(count) while true do last = op(x, v, last) if last then n = n+1 if limited then count = count - 1 if count == 0 then break end end else break end end return n end local lset = function(self, k, i, v) k, v = chkarg(k), chkarg(v) i = assert(toint(i)) if not self.data[k] then error("ERR no such key") end local x = xgetw(self, k, "list") local l = _l_len(x) if i >= l or i < -l then error("ERR index out of range") end x[_l_real_i(x, i)] = v return true end local ltrim = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetw(self, k, "list") i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2) for i=x.head+1,i1-1 do x[i] = nil end for i=i2+1,x.tail do x[i] = nil end x.head = math.max(i1-1, x.head) x.tail = math.min(i2, x.tail) assert( (x[x.head] == nil) and (x[x.tail+1] == nil) ) cleanup(self, k) return true end local rpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return r end rpoplpush = function(self, k1, k2) local v = rpop(self, k1) if not v then return nil end lpush(self, k2, v) return v end local rpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x.tail = x.tail + 1 x[x.tail] = vs[i] end return _l_len(x) end local rpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x.tail = x.tail + 1 x[x.tail] = v return _l_len(x) end -- sets local sadd = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if not x[arg[i]] then x[arg[i]] = true r = r + 1 end end return r end local scard = function(self, k) local x = xgetr(self, k, "set") return nkeys(x) end local _sdiff = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} for v,_ in pairs(x) do r[v] = true end for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = nil end end return r end local sdiff = function(self, k, ...) return lset_to_list(_sdiff(self, k, ...)) end local sdiffstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sdiff(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local _sinter = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} local y for v,_ in pairs(x) do r[v] = true for i=1,#arg do y = xgetr(self, arg[i], "set") if not y[v] then r[v] = nil; break end end end return r end local sinter = function(self, k, ...) return lset_to_list(_sinter(self, k, ...)) end local sinterstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sinter(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local sismember = function(self, k, v) local x = xgetr(self, k, "set") return not not x[v] end local smembers = function(self, k) local x = xgetr(self, k, "set") return lset_to_list(x) end local smove = function(self, k, k2, v) local x = xgetr(self, k, "set") if x[v] then local y = xgetw(self, k2, "set") x[v] = nil y[v] = true return true else return false end end local spop = function(self, k) local x, r = xgetw(self, k, "set"), nil local l = lset_to_list(x) local n = #l if n > 0 then r = l[math.random(1, n)] x[r] = nil end cleanup(self, k) return r end local srandmember = function(self, k, count) k = chkarg(k) local x = xgetr(self, k, "set") local l = lset_to_list(x) local n = #l if not count then if n > 0 then return l[math.random(1, n)] else return nil end end count = toint(count) if (count == 0) or (n == 0) then return {} end if count >= n then return l end local r = {} if count > 0 then -- distinct elements for i=0,count-1 do r[#r+1] = table.remove(l, math.random(1, n-i)) end else -- allow repetition for i=1,-count do r[#r+1] = l[math.random(1, n)] end end return r end local srem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if x[arg[i]] then x[arg[i]] = nil r = r + 1 end end cleanup(self, k) return r end local _sunion = function(self, ...) local arg = getargs(...) local r = {} local x for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = true end end return r end local sunion = function(self, k, ...) return lset_to_list(_sunion(self, k, ...)) end local sunionstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sunion(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end -- zsets local _z_p_mt = { __eq = function(a, b) if a.v == b.v then assert(a.s == b.s) return true else return false end end, __lt = function(a, b) if a.s == b.s then return (a.v < b.v) else return (a.s < b.s) end end, } local _z_pair = function(s, v) assert( (type(s) == "number") and (type(v) == "string") ) local r = {s = s, v = v} return setmetatable(r, _z_p_mt) end local _z_pairs = function(...) local arg = {...} assert((#arg > 0) and (#arg % 2 == 0)) local ps = {} for i=1,#arg,2 do ps[#ps+1] = _z_pair( assert(tofloat(arg[i])), chkarg(arg[i+1]) ) end return ps end local _z_insert = function(x, ix, p) assert( (type(x) == "table") and (type(ix) == "number") and (type(p) == "table") ) local l = x.list table.insert(l, ix, p) for i=ix+1,#l do x.set[l[i].v] = x.set[l[i].v] + 1 end x.set[p.v] = ix end local _z_remove = function(x, v) if not x.set[v] then return false end local l, ix = x.list, x.set[v] assert(l[ix].v == v) table.remove(l, ix) for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - 1 end x.set[v] = nil return true end local _z_remove_range = function(x, i1, i2) local l = x.list i2 = i2 or i1 assert( (i1 > 0) and (i2 >= i1) and (i2 <= #l) ) local ix, n = i1, i2-i1+1 for i=1,n do x.set[l[ix].v] = nil table.remove(l, ix) end for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - n end return n end local _z_update = function(x, p) local l = x.list local found = _z_remove(x, p.v) local ix = nil for i=1,#l do if l[i] > p then ix = i; break end end if not ix then ix = #l+1 end _z_insert(x, ix, p) return found end local _z_coherence = function(x) local l, s = x.list, x.set local found, n = {}, 0 for val,pos in pairs(s) do if found[pos] then return false end found[pos] = true n = n + 1 if not (l[pos] and (l[pos].v == val)) then return false end end if #l ~= n then return false end for i=1, n-1 do if l[i].s > l[i+1].s then return false end end return true end local _z_normrange = function(l, i1, i2) i1, i2 = assert(toint(i1)), assert(toint(i2)) if i1 < 0 then i1 = #l+i1 end if i2 < 0 then i2 = #l+i2 end i1, i2 = math.max(i1+1, 1), i2+1 if (i2 < i1) or (i1 > #l) then return nil end i2 = math.min(i2, #l) return i1, i2 end local _zrbs_opts = function(...) local arg = {...} if #arg == 0 then return {} end local ix, opts = 1, {} while type(arg[ix]) == "string" do if arg[ix] == "withscores" then opts.withscores = true ix = ix + 1 elseif arg[ix] == "limit" then opts.limit = { offset = assert(toint(arg[ix+1])), count = assert(toint(arg[ix+2])), } ix = ix + 3 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.withscores = opts.withscores or _o.withscores if _o.limit then opts.limit = { offset = assert(toint(_o.limit.offset or _o.limit[1])), count = assert(toint(_o.limit.count or _o.limit[2])), } end ix = ix + 1 end assert(arg[ix] == nil) if opts.limit then assert( (opts.limit.count >= 0) and (opts.limit.offset >= 0) ) end return opts end local _z_store_params = function(dest, numkeys, ...) dest = chkarg(dest) numkeys = assert(toint(numkeys)) assert(numkeys > 0) local arg = {...} assert(#arg >= numkeys) local ks = {} for i=1, numkeys do ks[i] = chkarg(arg[i]) end local ix, opts = numkeys+1,{} while type(arg[ix]) == "string" do if arg[ix] == "weights" then opts.weights = {} ix = ix + 1 for i=1, numkeys do opts.weights[i] = assert(toint(arg[ix])) ix = ix + 1 end elseif arg[ix] == "aggregate" then opts.aggregate = assert(chkarg(arg[ix+1])) ix = ix + 2 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.weights = opts.weights or _o.weights opts.aggregate = opts.aggregate or _o.aggregate ix = ix + 1 end assert(arg[ix] == nil) if opts.aggregate then assert( (opts.aggregate == "sum") or (opts.aggregate == "min") or (opts.aggregate == "max") ) else opts.aggregate = "sum" end if opts.weights then assert(#opts.weights == numkeys) for i=1,#opts.weights do assert(type(opts.weights[i]) == "number") end else opts.weights = {} for i=1, numkeys do opts.weights[i] = 1 end end opts.keys = ks opts.dest = dest return opts end local _zrbs_limits = function(x, s1, s2, descending) local s1_incl, s2_incl = true, true if s1:sub(1, 1) == "(" then s1, s1_incl = s1:sub(2, -1), false end s1 = assert(tofloat(s1)) if s2:sub(1, 1) == "(" then s2, s2_incl = s2:sub(2, -1), false end s2 = assert(tofloat(s2)) if descending then s1, s2 = s2, s1 s1_incl, s2_incl = s2_incl, s1_incl end if s2 < s1 then return nil end local l = x.list local i1, i2 local fst, lst = l[1].s, l[#l].s if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end for i=1,#l do if (i1 and i2) then break end if (not i1) then if l[i].s > s1 then i1 = i end if s1_incl and l[i].s == s1 then i1 = i end end if (not i2) then if l[i].s > s2 then i2 = i-1 end if (not s2_incl) and l[i].s == s2 then i2 = i-1 end end end assert(i1 and i2) if descending then return #l-i2, #l-i1 else return i1-1, i2-1 end end local dbg_zcoherence = function(self, k) local x = xgetr(self, k, "zset") return _z_coherence(x) end local zadd = function(self, k, ...) k = chkarg(k) local ps = _z_pairs(...) local x = xgetw(self, k, "zset") local n = 0 for i=1,#ps do if not _z_update(x, ps[i]) then n = n+1 end end return n end local zcard = function(self, k) local x = xgetr(self, k, "zset") return #x.list end local zcount = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return i2 - i1 + 1 end local zincrby = function(self, k, n, v) k,v = chkargs(2, k, v) n = assert(tofloat(n)) local x = xgetw(self, k, "zset") local p = x.list[x.set[v]] local s = p and (p.s + n) or n _z_update(x, _z_pair(s, v)) return s end local zinterstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local aggregate if params.aggregate == "sum" then aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then aggregate = math.min elseif params.aggregate == "max" then aggregate = math.max else error() end local y = xgetr(self, params.keys[1], "zset") local p1, p2 for j=1,#y.list do p1 = _z_pair(y.list[j].s, y.list[j].v) _z_update(x, p1) end for i=2,#params.keys do y = xgetr(self, params.keys[i], "zset") local to_remove, to_update = {}, {} for j=1,#x.list do p1 = x.list[j] if y.set[p1.v] then p2 = _z_pair( aggregate( p1.s, params.weights[i] * y.list[y.set[p1.v]].s ), p1.v ) to_update[#to_update+1] = p2 else to_remove[#to_remove+1] = p1.v end end for j=1,#to_remove do _z_remove(x, to_remove[j]) end for j=1,#to_update do _z_update(x, to_update[j]) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end local _zranger = function(descending) return function(self, k, i1, i2, opts) k = chkarg(k) local withscores = false if type(opts) == "table" then withscores = opts.withscores elseif type(opts) == "string" then assert(opts:lower() == "withscores") withscores = true else assert(opts == nil) end local x = xgetr(self, k, "zset") local l = x.list i1, i2 = _z_normrange(l, i1, i2) if not i1 then return {} end local inc = 1 if descending then i1 = #l - i1 + 1 i2 = #l - i2 + 1 inc = -1 end local r = {} if withscores then for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end else for i=i1, i2, inc do r[#r+1] = l[i].v end end return r end end local zrange = _zranger(false) local zrevrange = _zranger(true) local _zrangerbyscore = function(descending) return function(self, k, s1, s2, ...) k, s1, s2 = chkargs(3, k, s1, s2) local opts = _zrbs_opts(...) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, descending) if not (i1 and i2) then return {} end if opts.limit then if opts.limit.count == 0 then return {} end i1 = i1 + opts.limit.offset if i1 > i2 then return {} end i2 = math.min(i2, i1+opts.limit.count-1) end if descending then return zrevrange(self, k, i1, i2, opts) else return zrange(self, k, i1, i2, opts) end end end local zrangebyscore = _zrangerbyscore(false) local zrevrangebyscore = _zrangerbyscore(true) local zrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return r-1 else return nil end end local zrem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "zset"), 0 for i=1,#arg do if _z_remove(x, arg[i]) then r = r + 1 end end cleanup(self, k) return r end local zremrangebyrank = function(self, k, i1, i2) k = chkarg(k) local x = xgetw(self, k, "zset") i1, i2 = _z_normrange(x.list, i1, i2) if not i1 then cleanup(self, k) return 0 end local n = _z_remove_range(x, i1, i2) cleanup(self, k) return n end local zremrangebyscore = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return zremrangebyrank(self, k, i1, i2) end local zrevrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return #x.list-r else return nil end end local zscore = function(self, k, v) local x = xgetr(self, k, "zset") local p = x.list[x.set[v]] if p then return p.s else return nil end end local zunionstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local default_score, aggregate if params.aggregate == "sum" then default_score = 0 aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then default_score = math.huge aggregate = math.min elseif params.aggregate == "max" then default_score = -math.huge aggregate = math.max else error() end local y, p1, p2 for i=1,#params.keys do y = xgetr(self, params.keys[i], "zset") for j=1,#y.list do p1 = y.list[j] p2 = _z_pair( aggregate( params.weights[i] * p1.s, x.set[p1.v] and x.list[x.set[p1.v]].s or default_score ), p1.v ) _z_update(x, p2) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end -- connection local echo = function(self, v) return v end local ping = function(self) return true end -- server local flushdb = function(self) self.data = {} return true end --- Class local methods = { -- keys del = del, -- (...) -> #removed exists = chkargs_wrap(exists, 1), -- (k) -> exists? keys = keys, -- (pattern) -> list of keys ["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none] randomkey = randomkey, -- () -> [k|nil] rename = chkargs_wrap(rename, 2), -- (k,k2) -> true renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2 -- strings append = chkargs_wrap(append, 2), -- (k,v) -> #new bitcount = bitcount, -- (k,[start,end]) -> n bitop = bitop, -- ([and|or|xor|not],k,...) decr = chkargs_wrap(decr, 1), -- (k) -> new decrby = decrby, -- (k,n) -> new get = chkargs_wrap(get, 1), -- (k) -> [v|nil] getbit = getbit, -- (k,offset) -> b getrange = getrange, -- (k,start,end) -> string getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil] incr = chkargs_wrap(incr, 1), -- (k) -> new incrby = incrby, -- (k,n) -> new incrbyfloat = incrbyfloat, -- (k,n) -> new mget = mget, -- (k1,...) -> {v1,...} mset = mset, -- (k1,v1,...) -> true msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k) set = chkargs_wrap(set, 2), -- (k,v) -> true setbit = setbit, -- (k,offset,b) -> old setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?) setrange = setrange, -- (k,offset,val) -> #new strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0] -- hashes hdel = hdel, -- (k,sk1,...) -> #removed hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists? hget = chkargs_wrap(hget,2), -- (k,sk) -> v hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map hincrby = hincrby, -- (k,sk,n) -> new hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0] hmget = hmget, -- (k,{sk1,...}) -> {v1,...} hmset = hmset, -- (k,{sk1=v1,...}) -> true hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed? hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?) hvals = chkargs_wrap(hvals, 1), -- (k) -> values -- lists blpop = blpop, -- (k1,...) -> k,v brpop = brpop, -- (k1,...) -> k,v brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v lindex = lindex, -- (k,i) -> v linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after) llen = chkargs_wrap(llen, 1), -- (k) -> #list lpop = chkargs_wrap(lpop, 1), -- (k) -> v lpush = lpush, -- (k,v1,...) -> #list (after) lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after) lrange = lrange, -- (k,start,stop) -> list lrem = lrem, -- (k,count,v) -> #removed lset = lset, -- (k,i,v) -> true ltrim = ltrim, -- (k,start,stop) -> true rpop = chkargs_wrap(rpop, 1), -- (k) -> v rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v rpush = rpush, -- (k,v1,...) -> #list (after) rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after) -- sets sadd = sadd, -- (k,v1,...) -> #added scard = chkargs_wrap(scard, 1), -- (k) -> [n|0] sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...) sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0 sinter = sinter, -- (k1,...) -> set sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0 sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member? smembers = chkargs_wrap(smembers, 1), -- (k) -> set smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1) spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil] srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...] srem = srem, -- (k,v1,...) -> #removed sunion = sunion, -- (k1,...) -> set sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0 -- zsets zadd = zadd, -- (k,score,member,[score,member,...]) zcard = chkargs_wrap(zcard, 1), -- (k) -> n zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count zincrby = zincrby, -- (k,score,v) -> score zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank zrem = zrem, -- (k,v1,...) -> #removed zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card -- connection echo = chkargs_wrap(echo, 1), -- (v) -> v ping = ping, -- () -> true -- server flushall = flushdb, -- () -> true flushdb = flushdb, -- () -> true -- debug dbg_zcoherence = dbg_zcoherence, } local new = function() local r = {data = {}} return setmetatable(r,{__index = methods}) end return { new = new, }
gpl-2.0
Marcelo-Mk/StarWats-Api
libs/fakeredis.lua
650
40405
local unpack = table.unpack or unpack --- Bit operations local ok,bit if _VERSION == "Lua 5.3" then bit = (load [[ return { band = function(x, y) return x & y end, bor = function(x, y) return x | y end, bxor = function(x, y) return x ~ y end, bnot = function(x) return ~x end, rshift = function(x, n) return x >> n end, lshift = function(x, n) return x << n end, } ]])() else ok,bit = pcall(require,"bit") if not ok then bit = bit32 end end assert(type(bit) == "table", "module for bitops not found") --- default sleep local default_sleep do local ok, mod = pcall(require, "socket") if ok and type(mod) == "table" then default_sleep = mod.sleep else default_sleep = function(n) local t0 = os.clock() while true do local delta = os.clock() - t0 if (delta < 0) or (delta > n) then break end end end end end --- Helpers local xdefv = function(ktype) if ktype == "list" then return {head = 0, tail = 0} elseif ktype == "zset" then return { list = {}, set = {}, } else return {} end end local xgetr = function(self, k, ktype) if self.data[k] then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) assert(self.data[k].value) return self.data[k].value else return xdefv(ktype) end end local xgetw = function(self, k, ktype) if self.data[k] and self.data[k].value then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) else self.data[k] = {ktype = ktype, value = xdefv(ktype)} end return self.data[k].value end local empty = function(self, k) local v, t = self.data[k].value, self.data[k].ktype if t == nil then return true elseif t == "string" then return not v[1] elseif (t == "hash") or (t == "set") then for _,_ in pairs(v) do return false end return true elseif t == "list" then return v.head == v.tail elseif t == "zset" then if #v.list == 0 then for _,_ in pairs(v.set) do error("incoherent") end return true else for _,_ in pairs(v.set) do return(false) end error("incoherent") end else error("unsupported") end end local cleanup = function(self, k) if empty(self, k) then self.data[k] = nil end end local is_integer = function(x) return (type(x) == "number") and (math.floor(x) == x) end local overflows = function(n) return (n > 2^53-1) or (n < -2^53+1) end local is_bounded_integer = function(x) return (is_integer(x) and (not overflows(x))) end local is_finite_number = function(x) return (type(x) == "number") and (x > -math.huge) and (x < math.huge) end local toint = function(x) if type(x) == "string" then x = tonumber(x) end return is_bounded_integer(x) and x or nil end local tofloat = function(x) if type(x) == "number" then return x end if type(x) ~= "string" then return nil end local r = tonumber(x) if r then return r end if x == "inf" or x == "+inf" then return math.huge elseif x == "-inf" then return -math.huge else return nil end end local tostr = function(x) if is_bounded_integer(x) then return string.format("%d", x) else return tostring(x) end end local char_bitcount = function(x) assert( (type(x) == "number") and (math.floor(x) == x) and (x >= 0) and (x < 256) ) local n = 0 while x ~= 0 do x = bit.band(x, x-1) n = n+1 end return n end local chkarg = function(x) if type(x) == "number" then x = tostr(x) end assert(type(x) == "string") return x end local chkargs = function(n, ...) local arg = {...} assert(#arg == n) for i=1,n do arg[i] = chkarg(arg[i]) end return unpack(arg) end local getargs = function(...) local arg = {...} local n = #arg; assert(n > 0) for i=1,n do arg[i] = chkarg(arg[i]) end return arg end local getargs_as_map = function(...) local arg, r = getargs(...), {} assert(#arg%2 == 0) for i=1,#arg,2 do r[arg[i]] = arg[i+1] end return r end local chkargs_wrap = function(f, n) assert( (type(f) == "function") and (type(n) == "number") ) return function(self, ...) return f(self, chkargs(n, ...)) end end local lset_to_list = function(s) local r = {} for v,_ in pairs(s) do r[#r+1] = v end return r end local nkeys = function(x) local r = 0 for _,_ in pairs(x) do r = r + 1 end return r end --- Commands -- keys local del = function(self, ...) local arg = getargs(...) local r = 0 for i=1,#arg do if self.data[arg[i]] then r = r + 1 end self.data[arg[i]] = nil end return r end local exists = function(self, k) return not not self.data[k] end local keys = function(self, pattern) assert(type(pattern) == "string") -- We want to convert the Redis pattern to a Lua pattern. -- Start by escaping dashes *outside* character classes. -- We also need to escape percents here. local t, p, n = {}, 1, #pattern local p1, p2 while true do p1, p2 = pattern:find("%[.+%]", p) if p1 then if p1 > p then t[#t+1] = {true, pattern:sub(p, p1-1)} end t[#t+1] = {false, pattern:sub(p1, p2)} p = p2+1 if p > n then break end else t[#t+1] = {true, pattern:sub(p, n)} break end end for i=1,#t do if t[i][1] then t[i] = t[i][2]:gsub("[%%%-]", "%%%0") else t[i] = t[i][2]:gsub("%%", "%%%%") end end -- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]' -- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is. -- Wrap in '^$' to enforce bounds. local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0") :gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$" local r = {} for k,_ in pairs(self.data) do if k:match(lp) then r[#r+1] = k end end return r end local _type = function(self, k) return self.data[k] and self.data[k].ktype or "none" end local randomkey = function(self) local ks = lset_to_list(self.data) local n = #ks if n > 0 then return ks[math.random(1, n)] else return nil end end local rename = function(self, k, k2) assert((k ~= k2) and self.data[k]) self.data[k2] = self.data[k] self.data[k] = nil return true end local renamenx = function(self, k, k2) if self.data[k2] then return false else return rename(self, k, k2) end end -- strings local getrange, incrby, set local append = function(self, k, v) local x = xgetw(self, k, "string") x[1] = (x[1] or "") .. v return #x[1] end local bitcount = function(self, k, i1, i2) k = chkarg(k) local s if i1 or i2 then assert(i1 and i2, "ERR syntax error") s = getrange(self, k, i1, i2) else s = xgetr(self, k, "string")[1] or "" end local r, bytes = 0,{s:byte(1, -1)} for i=1,#bytes do r = r + char_bitcount(bytes[i]) end return r end local bitop = function(self, op, k, ...) assert(type(op) == "string") op = op:lower() assert( (op == "and") or (op == "or") or (op == "xor") or (op == "not"), "ERR syntax error" ) k = chkarg(k) local arg = {...} local good_arity = (op == "not") and (#arg == 1) or (#arg > 0) assert(good_arity, "ERR wrong number of arguments for 'bitop' command") local l, vals = 0, {} local s for i=1,#arg do s = xgetr(self, arg[i], "string")[1] or "" if #s > l then l = #s end vals[i] = s end if l == 0 then del(self, k) return 0 end local vector_mt = {__index=function() return 0 end} for i=1,#vals do vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt) end local r = {} if op == "not" then assert(#vals[1] == l) for i=1,l do r[i] = bit.band(bit.bnot(vals[1][i]), 0xff) end else local _op = bit["b" .. op] for i=1,l do local t = {} for j=1,#vals do t[j] = vals[j][i] end r[i] = _op(unpack(t)) end end set(self, k, string.char(unpack(r))) return l end local decr = function(self, k) return incrby(self, k, -1) end local decrby = function(self, k, n) n = toint(n) assert(n, "ERR value is not an integer or out of range") return incrby(self, k, -n) end local get = function(self, k) local x = xgetr(self, k, "string") return x[1] end local getbit = function(self, k, offset) k = chkarg(k) offset = toint(offset) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" if bytepos >= #s then return 0 end local char = s:sub(bytepos+1, bytepos+1):byte() return bit.band(bit.rshift(char, 7-bitpos), 1) end getrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetr(self, k, "string") x = x[1] or "" if i1 >= 0 then i1 = i1 + 1 end if i2 >= 0 then i2 = i2 + 1 end return x:sub(i1, i2) end local getset = function(self, k, v) local r = get(self, k) set(self, k, v) return r end local incr = function(self, k) return incrby(self, k, 1) end incrby = function(self, k, n) k, n = chkarg(k), toint(n) assert(n, "ERR value is not an integer or out of range") local x = xgetw(self, k, "string") local i = toint(x[1] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[1] = tostr(i) return i end local incrbyfloat = function(self, k, n) k, n = chkarg(k), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "string") local i = tofloat(x[1] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[1] = tostr(i) return i end local mget = function(self, ...) local arg, r = getargs(...), {} for i=1,#arg do r[i] = get(self, arg[i]) end return r end local mset = function(self, ...) local argmap = getargs_as_map(...) for k,v in pairs(argmap) do set(self, k, v) end return true end local msetnx = function(self, ...) local argmap = getargs_as_map(...) for k,_ in pairs(argmap) do if self.data[k] then return false end end for k,v in pairs(argmap) do set(self, k, v) end return true end set = function(self, k, v) self.data[k] = {ktype = "string", value = {v}} return true end local setbit = function(self, k, offset, b) k = chkarg(k) offset, b = toint(offset), toint(b) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) assert( (b == 0) or (b == 1), "ERR bit is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" local pad = {s} for i=2,bytepos+2-#s do pad[i] = "\0" end s = table.concat(pad) assert(#s >= bytepos+1) local before = s:sub(1, bytepos) local char = s:sub(bytepos+1, bytepos+1):byte() local after = s:sub(bytepos+2, -1) local old = bit.band(bit.rshift(char, 7-bitpos), 1) if b == 1 then char = bit.bor(bit.lshift(1, 7-bitpos), char) else char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char) end local r = before .. string.char(char) .. after set(self, k, r) return old end local setnx = function(self, k, v) if self.data[k] then return false else return set(self, k, v) end end local setrange = function(self, k, i, s) local k, s = chkargs(2, k, s) i = toint(i) assert(i and (i >= 0)) local x = xgetw(self, k, "string") local y = x[1] or "" local ly, ls = #y, #s if i > ly then -- zero padding local t = {} for i=1, i-ly do t[i] = "\0" end y = y .. table.concat(t) .. s else y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly) end x[1] = y return #y end local strlen = function(self, k) local x = xgetr(self, k, "string") return x[1] and #x[1] or 0 end -- hashes local hdel = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local r = 0 local x = xgetw(self, k, "hash") for i=1,#arg do if x[arg[i]] then r = r + 1 end x[arg[i]] = nil end cleanup(self, k) return r end local hget local hexists = function(self, k, k2) return not not hget(self, k, k2) end hget = function(self, k, k2) local x = xgetr(self, k, "hash") return x[k2] end local hgetall = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,v in pairs(x) do r[_k] = v end return r end local hincrby = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), toint(n) assert(n, "ERR value is not an integer or out of range") assert(type(n) == "number") local x = xgetw(self, k, "hash") local i = toint(x[k2] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[k2] = tostr(i) return i end local hincrbyfloat = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "hash") local i = tofloat(x[k2] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[k2] = tostr(i) return i end local hkeys = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,_ in pairs(x) do r[#r+1] = _k end return r end local hlen = function(self, k) local x = xgetr(self, k, "hash") return nkeys(x) end local hmget = function(self, k, k2s) k = chkarg(k) assert((type(k2s) == "table")) local r = {} local x = xgetr(self, k, "hash") for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end return r end local hmset = function(self, k, ...) k = chkarg(k) local arg = {...} if type(arg[1]) == "table" then assert(#arg == 1) local x = xgetw(self, k, "hash") for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end else assert(#arg % 2 == 0) local x = xgetw(self, k, "hash") local t = getargs(...) for i=1,#t,2 do x[t[i]] = t[i+1] end end return true end local hset = function(self, k, k2, v) local x = xgetw(self, k, "hash") local r = not x[k2] x[k2] = v return r end local hsetnx = function(self, k, k2, v) local x = xgetw(self, k, "hash") if x[k2] == nil then x[k2] = v return true else return false end end local hvals = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _,v in pairs(x) do r[#r+1] = v end return r end -- lists (head = left, tail = right) local _l_real_i = function(x, i) if i < 0 then return x.tail+i+1 else return x.head+i+1 end end local _l_len = function(x) return x.tail - x.head end local _block_for = function(self, timeout) if timeout > 0 then local sleep = self.sleep or default_sleep if type(sleep) == "function" then sleep(timeout) else error("sleep function unavailable", 0) end else error("operation would block", 0) end end local rpoplpush local blpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpoplpush = function(self, k1, k2, timeout) k1, k2 = chkargs(2, k1, k2) timeout = toint(timeout) if not self.data[k1] then _block_for(self, timeout) end return rpoplpush(self, k1, k2) end local lindex = function(self, k, i) k = chkarg(k) i = assert(toint(i)) local x = xgetr(self, k, "list") return x[_l_real_i(x, i)] end local linsert = function(self, k, mode, pivot, v) mode = mode:lower() assert((mode == "before") or (mode == "after")) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local p = nil for i=x.head+1, x.tail do if x[i] == pivot then p = i break end end if not p then return -1 end if mode == "after" then for i=x.head+1, p do x[i-1] = x[i] end x.head = x.head - 1 else for i=x.tail, p, -1 do x[i+1] = x[i] end x.tail = x.tail + 1 end x[p] = v return _l_len(x) end local llen = function(self, k) local x = xgetr(self, k, "list") return _l_len(x) end local lpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return r end local lpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x[x.head] = vs[i] x.head = x.head - 1 end return _l_len(x) end local lpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x[x.head] = v x.head = x.head - 1 return _l_len(x) end local lrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x, r = xgetr(self, k, "list"), {} i1 = math.max(_l_real_i(x, i1), x.head+1) i2 = math.min(_l_real_i(x, i2), x.tail) for i=i1,i2 do r[#r+1] = x[i] end return r end local _lrem_i = function(x, p) for i=p,x.tail do x[i] = x[i+1] end x.tail = x.tail - 1 end local _lrem_l = function(x, v, s) assert(v) if not s then s = x.head+1 end for i=s,x.tail do if x[i] == v then _lrem_i(x, i) return i end end return false end local _lrem_r = function(x, v, s) assert(v) if not s then s = x.tail end for i=s,x.head+1,-1 do if x[i] == v then _lrem_i(x, i) return i end end return false end local lrem = function(self, k, count, v) k, v = chkarg(k), chkarg(v) count = assert(toint(count)) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local n, last = 0, nil local op = (count < 0) and _lrem_r or _lrem_l local limited = (count ~= 0) count = math.abs(count) while true do last = op(x, v, last) if last then n = n+1 if limited then count = count - 1 if count == 0 then break end end else break end end return n end local lset = function(self, k, i, v) k, v = chkarg(k), chkarg(v) i = assert(toint(i)) if not self.data[k] then error("ERR no such key") end local x = xgetw(self, k, "list") local l = _l_len(x) if i >= l or i < -l then error("ERR index out of range") end x[_l_real_i(x, i)] = v return true end local ltrim = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetw(self, k, "list") i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2) for i=x.head+1,i1-1 do x[i] = nil end for i=i2+1,x.tail do x[i] = nil end x.head = math.max(i1-1, x.head) x.tail = math.min(i2, x.tail) assert( (x[x.head] == nil) and (x[x.tail+1] == nil) ) cleanup(self, k) return true end local rpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return r end rpoplpush = function(self, k1, k2) local v = rpop(self, k1) if not v then return nil end lpush(self, k2, v) return v end local rpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x.tail = x.tail + 1 x[x.tail] = vs[i] end return _l_len(x) end local rpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x.tail = x.tail + 1 x[x.tail] = v return _l_len(x) end -- sets local sadd = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if not x[arg[i]] then x[arg[i]] = true r = r + 1 end end return r end local scard = function(self, k) local x = xgetr(self, k, "set") return nkeys(x) end local _sdiff = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} for v,_ in pairs(x) do r[v] = true end for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = nil end end return r end local sdiff = function(self, k, ...) return lset_to_list(_sdiff(self, k, ...)) end local sdiffstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sdiff(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local _sinter = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} local y for v,_ in pairs(x) do r[v] = true for i=1,#arg do y = xgetr(self, arg[i], "set") if not y[v] then r[v] = nil; break end end end return r end local sinter = function(self, k, ...) return lset_to_list(_sinter(self, k, ...)) end local sinterstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sinter(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local sismember = function(self, k, v) local x = xgetr(self, k, "set") return not not x[v] end local smembers = function(self, k) local x = xgetr(self, k, "set") return lset_to_list(x) end local smove = function(self, k, k2, v) local x = xgetr(self, k, "set") if x[v] then local y = xgetw(self, k2, "set") x[v] = nil y[v] = true return true else return false end end local spop = function(self, k) local x, r = xgetw(self, k, "set"), nil local l = lset_to_list(x) local n = #l if n > 0 then r = l[math.random(1, n)] x[r] = nil end cleanup(self, k) return r end local srandmember = function(self, k, count) k = chkarg(k) local x = xgetr(self, k, "set") local l = lset_to_list(x) local n = #l if not count then if n > 0 then return l[math.random(1, n)] else return nil end end count = toint(count) if (count == 0) or (n == 0) then return {} end if count >= n then return l end local r = {} if count > 0 then -- distinct elements for i=0,count-1 do r[#r+1] = table.remove(l, math.random(1, n-i)) end else -- allow repetition for i=1,-count do r[#r+1] = l[math.random(1, n)] end end return r end local srem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if x[arg[i]] then x[arg[i]] = nil r = r + 1 end end cleanup(self, k) return r end local _sunion = function(self, ...) local arg = getargs(...) local r = {} local x for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = true end end return r end local sunion = function(self, k, ...) return lset_to_list(_sunion(self, k, ...)) end local sunionstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sunion(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end -- zsets local _z_p_mt = { __eq = function(a, b) if a.v == b.v then assert(a.s == b.s) return true else return false end end, __lt = function(a, b) if a.s == b.s then return (a.v < b.v) else return (a.s < b.s) end end, } local _z_pair = function(s, v) assert( (type(s) == "number") and (type(v) == "string") ) local r = {s = s, v = v} return setmetatable(r, _z_p_mt) end local _z_pairs = function(...) local arg = {...} assert((#arg > 0) and (#arg % 2 == 0)) local ps = {} for i=1,#arg,2 do ps[#ps+1] = _z_pair( assert(tofloat(arg[i])), chkarg(arg[i+1]) ) end return ps end local _z_insert = function(x, ix, p) assert( (type(x) == "table") and (type(ix) == "number") and (type(p) == "table") ) local l = x.list table.insert(l, ix, p) for i=ix+1,#l do x.set[l[i].v] = x.set[l[i].v] + 1 end x.set[p.v] = ix end local _z_remove = function(x, v) if not x.set[v] then return false end local l, ix = x.list, x.set[v] assert(l[ix].v == v) table.remove(l, ix) for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - 1 end x.set[v] = nil return true end local _z_remove_range = function(x, i1, i2) local l = x.list i2 = i2 or i1 assert( (i1 > 0) and (i2 >= i1) and (i2 <= #l) ) local ix, n = i1, i2-i1+1 for i=1,n do x.set[l[ix].v] = nil table.remove(l, ix) end for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - n end return n end local _z_update = function(x, p) local l = x.list local found = _z_remove(x, p.v) local ix = nil for i=1,#l do if l[i] > p then ix = i; break end end if not ix then ix = #l+1 end _z_insert(x, ix, p) return found end local _z_coherence = function(x) local l, s = x.list, x.set local found, n = {}, 0 for val,pos in pairs(s) do if found[pos] then return false end found[pos] = true n = n + 1 if not (l[pos] and (l[pos].v == val)) then return false end end if #l ~= n then return false end for i=1, n-1 do if l[i].s > l[i+1].s then return false end end return true end local _z_normrange = function(l, i1, i2) i1, i2 = assert(toint(i1)), assert(toint(i2)) if i1 < 0 then i1 = #l+i1 end if i2 < 0 then i2 = #l+i2 end i1, i2 = math.max(i1+1, 1), i2+1 if (i2 < i1) or (i1 > #l) then return nil end i2 = math.min(i2, #l) return i1, i2 end local _zrbs_opts = function(...) local arg = {...} if #arg == 0 then return {} end local ix, opts = 1, {} while type(arg[ix]) == "string" do if arg[ix] == "withscores" then opts.withscores = true ix = ix + 1 elseif arg[ix] == "limit" then opts.limit = { offset = assert(toint(arg[ix+1])), count = assert(toint(arg[ix+2])), } ix = ix + 3 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.withscores = opts.withscores or _o.withscores if _o.limit then opts.limit = { offset = assert(toint(_o.limit.offset or _o.limit[1])), count = assert(toint(_o.limit.count or _o.limit[2])), } end ix = ix + 1 end assert(arg[ix] == nil) if opts.limit then assert( (opts.limit.count >= 0) and (opts.limit.offset >= 0) ) end return opts end local _z_store_params = function(dest, numkeys, ...) dest = chkarg(dest) numkeys = assert(toint(numkeys)) assert(numkeys > 0) local arg = {...} assert(#arg >= numkeys) local ks = {} for i=1, numkeys do ks[i] = chkarg(arg[i]) end local ix, opts = numkeys+1,{} while type(arg[ix]) == "string" do if arg[ix] == "weights" then opts.weights = {} ix = ix + 1 for i=1, numkeys do opts.weights[i] = assert(toint(arg[ix])) ix = ix + 1 end elseif arg[ix] == "aggregate" then opts.aggregate = assert(chkarg(arg[ix+1])) ix = ix + 2 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.weights = opts.weights or _o.weights opts.aggregate = opts.aggregate or _o.aggregate ix = ix + 1 end assert(arg[ix] == nil) if opts.aggregate then assert( (opts.aggregate == "sum") or (opts.aggregate == "min") or (opts.aggregate == "max") ) else opts.aggregate = "sum" end if opts.weights then assert(#opts.weights == numkeys) for i=1,#opts.weights do assert(type(opts.weights[i]) == "number") end else opts.weights = {} for i=1, numkeys do opts.weights[i] = 1 end end opts.keys = ks opts.dest = dest return opts end local _zrbs_limits = function(x, s1, s2, descending) local s1_incl, s2_incl = true, true if s1:sub(1, 1) == "(" then s1, s1_incl = s1:sub(2, -1), false end s1 = assert(tofloat(s1)) if s2:sub(1, 1) == "(" then s2, s2_incl = s2:sub(2, -1), false end s2 = assert(tofloat(s2)) if descending then s1, s2 = s2, s1 s1_incl, s2_incl = s2_incl, s1_incl end if s2 < s1 then return nil end local l = x.list local i1, i2 local fst, lst = l[1].s, l[#l].s if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end for i=1,#l do if (i1 and i2) then break end if (not i1) then if l[i].s > s1 then i1 = i end if s1_incl and l[i].s == s1 then i1 = i end end if (not i2) then if l[i].s > s2 then i2 = i-1 end if (not s2_incl) and l[i].s == s2 then i2 = i-1 end end end assert(i1 and i2) if descending then return #l-i2, #l-i1 else return i1-1, i2-1 end end local dbg_zcoherence = function(self, k) local x = xgetr(self, k, "zset") return _z_coherence(x) end local zadd = function(self, k, ...) k = chkarg(k) local ps = _z_pairs(...) local x = xgetw(self, k, "zset") local n = 0 for i=1,#ps do if not _z_update(x, ps[i]) then n = n+1 end end return n end local zcard = function(self, k) local x = xgetr(self, k, "zset") return #x.list end local zcount = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return i2 - i1 + 1 end local zincrby = function(self, k, n, v) k,v = chkargs(2, k, v) n = assert(tofloat(n)) local x = xgetw(self, k, "zset") local p = x.list[x.set[v]] local s = p and (p.s + n) or n _z_update(x, _z_pair(s, v)) return s end local zinterstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local aggregate if params.aggregate == "sum" then aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then aggregate = math.min elseif params.aggregate == "max" then aggregate = math.max else error() end local y = xgetr(self, params.keys[1], "zset") local p1, p2 for j=1,#y.list do p1 = _z_pair(y.list[j].s, y.list[j].v) _z_update(x, p1) end for i=2,#params.keys do y = xgetr(self, params.keys[i], "zset") local to_remove, to_update = {}, {} for j=1,#x.list do p1 = x.list[j] if y.set[p1.v] then p2 = _z_pair( aggregate( p1.s, params.weights[i] * y.list[y.set[p1.v]].s ), p1.v ) to_update[#to_update+1] = p2 else to_remove[#to_remove+1] = p1.v end end for j=1,#to_remove do _z_remove(x, to_remove[j]) end for j=1,#to_update do _z_update(x, to_update[j]) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end local _zranger = function(descending) return function(self, k, i1, i2, opts) k = chkarg(k) local withscores = false if type(opts) == "table" then withscores = opts.withscores elseif type(opts) == "string" then assert(opts:lower() == "withscores") withscores = true else assert(opts == nil) end local x = xgetr(self, k, "zset") local l = x.list i1, i2 = _z_normrange(l, i1, i2) if not i1 then return {} end local inc = 1 if descending then i1 = #l - i1 + 1 i2 = #l - i2 + 1 inc = -1 end local r = {} if withscores then for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end else for i=i1, i2, inc do r[#r+1] = l[i].v end end return r end end local zrange = _zranger(false) local zrevrange = _zranger(true) local _zrangerbyscore = function(descending) return function(self, k, s1, s2, ...) k, s1, s2 = chkargs(3, k, s1, s2) local opts = _zrbs_opts(...) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, descending) if not (i1 and i2) then return {} end if opts.limit then if opts.limit.count == 0 then return {} end i1 = i1 + opts.limit.offset if i1 > i2 then return {} end i2 = math.min(i2, i1+opts.limit.count-1) end if descending then return zrevrange(self, k, i1, i2, opts) else return zrange(self, k, i1, i2, opts) end end end local zrangebyscore = _zrangerbyscore(false) local zrevrangebyscore = _zrangerbyscore(true) local zrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return r-1 else return nil end end local zrem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "zset"), 0 for i=1,#arg do if _z_remove(x, arg[i]) then r = r + 1 end end cleanup(self, k) return r end local zremrangebyrank = function(self, k, i1, i2) k = chkarg(k) local x = xgetw(self, k, "zset") i1, i2 = _z_normrange(x.list, i1, i2) if not i1 then cleanup(self, k) return 0 end local n = _z_remove_range(x, i1, i2) cleanup(self, k) return n end local zremrangebyscore = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return zremrangebyrank(self, k, i1, i2) end local zrevrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return #x.list-r else return nil end end local zscore = function(self, k, v) local x = xgetr(self, k, "zset") local p = x.list[x.set[v]] if p then return p.s else return nil end end local zunionstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local default_score, aggregate if params.aggregate == "sum" then default_score = 0 aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then default_score = math.huge aggregate = math.min elseif params.aggregate == "max" then default_score = -math.huge aggregate = math.max else error() end local y, p1, p2 for i=1,#params.keys do y = xgetr(self, params.keys[i], "zset") for j=1,#y.list do p1 = y.list[j] p2 = _z_pair( aggregate( params.weights[i] * p1.s, x.set[p1.v] and x.list[x.set[p1.v]].s or default_score ), p1.v ) _z_update(x, p2) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end -- connection local echo = function(self, v) return v end local ping = function(self) return true end -- server local flushdb = function(self) self.data = {} return true end --- Class local methods = { -- keys del = del, -- (...) -> #removed exists = chkargs_wrap(exists, 1), -- (k) -> exists? keys = keys, -- (pattern) -> list of keys ["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none] randomkey = randomkey, -- () -> [k|nil] rename = chkargs_wrap(rename, 2), -- (k,k2) -> true renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2 -- strings append = chkargs_wrap(append, 2), -- (k,v) -> #new bitcount = bitcount, -- (k,[start,end]) -> n bitop = bitop, -- ([and|or|xor|not],k,...) decr = chkargs_wrap(decr, 1), -- (k) -> new decrby = decrby, -- (k,n) -> new get = chkargs_wrap(get, 1), -- (k) -> [v|nil] getbit = getbit, -- (k,offset) -> b getrange = getrange, -- (k,start,end) -> string getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil] incr = chkargs_wrap(incr, 1), -- (k) -> new incrby = incrby, -- (k,n) -> new incrbyfloat = incrbyfloat, -- (k,n) -> new mget = mget, -- (k1,...) -> {v1,...} mset = mset, -- (k1,v1,...) -> true msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k) set = chkargs_wrap(set, 2), -- (k,v) -> true setbit = setbit, -- (k,offset,b) -> old setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?) setrange = setrange, -- (k,offset,val) -> #new strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0] -- hashes hdel = hdel, -- (k,sk1,...) -> #removed hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists? hget = chkargs_wrap(hget,2), -- (k,sk) -> v hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map hincrby = hincrby, -- (k,sk,n) -> new hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0] hmget = hmget, -- (k,{sk1,...}) -> {v1,...} hmset = hmset, -- (k,{sk1=v1,...}) -> true hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed? hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?) hvals = chkargs_wrap(hvals, 1), -- (k) -> values -- lists blpop = blpop, -- (k1,...) -> k,v brpop = brpop, -- (k1,...) -> k,v brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v lindex = lindex, -- (k,i) -> v linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after) llen = chkargs_wrap(llen, 1), -- (k) -> #list lpop = chkargs_wrap(lpop, 1), -- (k) -> v lpush = lpush, -- (k,v1,...) -> #list (after) lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after) lrange = lrange, -- (k,start,stop) -> list lrem = lrem, -- (k,count,v) -> #removed lset = lset, -- (k,i,v) -> true ltrim = ltrim, -- (k,start,stop) -> true rpop = chkargs_wrap(rpop, 1), -- (k) -> v rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v rpush = rpush, -- (k,v1,...) -> #list (after) rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after) -- sets sadd = sadd, -- (k,v1,...) -> #added scard = chkargs_wrap(scard, 1), -- (k) -> [n|0] sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...) sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0 sinter = sinter, -- (k1,...) -> set sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0 sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member? smembers = chkargs_wrap(smembers, 1), -- (k) -> set smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1) spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil] srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...] srem = srem, -- (k,v1,...) -> #removed sunion = sunion, -- (k1,...) -> set sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0 -- zsets zadd = zadd, -- (k,score,member,[score,member,...]) zcard = chkargs_wrap(zcard, 1), -- (k) -> n zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count zincrby = zincrby, -- (k,score,v) -> score zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank zrem = zrem, -- (k,v1,...) -> #removed zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card -- connection echo = chkargs_wrap(echo, 1), -- (v) -> v ping = ping, -- () -> true -- server flushall = flushdb, -- () -> true flushdb = flushdb, -- () -> true -- debug dbg_zcoherence = dbg_zcoherence, } local new = function() local r = {data = {}} return setmetatable(r,{__index = methods}) end return { new = new, }
gpl-3.0
LuffyPan/skynet
lualib/sharedata/corelib.lua
64
2453
local core = require "sharedata.core" local type = type local next = next local rawget = rawget local conf = {} conf.host = { new = core.new, delete = core.delete, getref = core.getref, markdirty = core.markdirty, incref = core.incref, decref = core.decref, } local meta = {} local isdirty = core.isdirty local index = core.index local needupdate = core.needupdate local len = core.len local function findroot(self) while self.__parent do self = self.__parent end return self end local function update(root, cobj, gcobj) root.__obj = cobj root.__gcobj = gcobj local children = root.__cache if children then for k,v in pairs(children) do local pointer = index(cobj, k) if type(pointer) == "userdata" then update(v, pointer, gcobj) else children[k] = nil end end end end local function genkey(self) local key = tostring(self.__key) while self.__parent do self = self.__parent key = self.__key .. "." .. key end return key end local function getcobj(self) local obj = self.__obj if isdirty(obj) then local newobj, newtbl = needupdate(self.__gcobj) if newobj then local newgcobj = newtbl.__gcobj local root = findroot(self) update(root, newobj, newgcobj) if obj == self.__obj then error ("The key [" .. genkey(self) .. "] doesn't exist after update") end obj = self.__obj end end return obj end function meta:__index(key) local obj = getcobj(self) local v = index(obj, key) if type(v) == "userdata" then local children = self.__cache if children == nil then children = {} self.__cache = children end local r = children[key] if r then return r end r = setmetatable({ __obj = v, __gcobj = self.__gcobj, __parent = self, __key = key, }, meta) children[key] = r return r else return v end end function meta:__len() return len(getcobj(self)) end function meta:__pairs() return conf.next, self, nil end function conf.next(obj, key) local cobj = getcobj(obj) local nextkey = core.nextkey(cobj, key) if nextkey then return nextkey, obj[nextkey] end end function conf.box(obj) local gcobj = core.box(obj) return setmetatable({ __parent = false, __obj = obj, __gcobj = gcobj, __key = "", } , meta) end function conf.update(self, pointer) local cobj = self.__obj assert(isdirty(cobj), "Only dirty object can be update") core.update(self.__gcobj, pointer, { __gcobj = core.box(pointer) }) end return conf
mit
kaltura/nginx-vod-module
tools/persist_proxy/status.lua
1
1330
--[[ outputs nginx stub status metrics in prom format --]] local log = ngx.log local ERR = ngx.ERR local capture = ngx.location.capture local gmatch = ngx.re.gmatch local say = ngx.say local _M = { _VERSION = '0.1' } -- order matching nginx stub status output local metrics = { 'nginx_connections_current{state="active"} ', 'nginx_connections_processed_total{stage="accepted"} ', 'nginx_connections_processed_total{stage="handled"} ', 'nginx_connections_processed_total{stage="any"} ', 'nginx_connections_current{state="reading"} ', 'nginx_connections_current{state="writing"} ', 'nginx_connections_current{state="waiting"} ', } function _M.format_status(uri) local res = capture(uri) if res.status ~= 200 then log(ERR, 'bad status: ', res.status) return end local iter, err = gmatch(res.body, '(\\d+)') if not iter then log(ERR, 'gmatch failed: ', err) return end local body = '' for _, cur in pairs(metrics) do local m, err = iter() if err then log(ERR, 'gmatch iterator failed: ', err) return end if not m then log(ERR, 'missing matches') return end body = body .. cur .. m[1] .. '\n' end return body end return _M
agpl-3.0
RockySeven3161/Unknown..
plugins/wiki.lua
735
4364
-- http://git.io/vUA4M local socket = require "socket" local JSON = require "cjson" local wikiusage = { "!wiki [text]: Read extract from default Wikipedia (EN)", "!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola", "!wiki search [text]: Search articles on default Wikipedia (EN)", "!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola", } local Wikipedia = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 300, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "en", } function Wikipedia:getWikiServer(lang) return string.format(self.wiki_server, lang or self.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function Wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(self.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else self.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(self.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) print(request['url']) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(JSON.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function Wikipedia:wikintro(text, lang) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then return text..": "..page.extract else local text = "Extract not found for "..text text = text..'\n'..table.concat(wikiusage, '\n') return text end else return "Sorry an error happened" end end -- search for term in wiki function Wikipedia:wikisearch(text, lang) local result = self:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "No results found" return titles else return "Sorry, an error occurred" end end local function run(msg, matches) -- TODO: Remember language (i18 on future version) -- TODO: Support for non Wikipedias but Mediawikis local search, term, lang if matches[1] == "search" then search = true term = matches[2] lang = nil elseif matches[2] == "search" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then local text = "Usage:\n" text = text..table.concat(wikiusage, '\n') return text end local result if search then result = Wikipedia:wikisearch(term, lang) else -- TODO: Show the link result = Wikipedia:wikintro(term, lang) end return result end return { description = "Searches Wikipedia and send results", usage = wikiusage, patterns = { "^![Ww]iki(%w+) (search) (.+)$", "^![Ww]iki (search) ?(.*)$", "^![Ww]iki(%w+) (.+)$", "^![Ww]iki ?(.*)$" }, run = run }
gpl-2.0
Primordus/lua-quickcheck
spec/fsm/state_spec.lua
2
1705
local state = require 'lqc.fsm.state' -- Helper function to make a state local function make_state(state_name, precond, next_state, postcond) local state_helper = state(state_name) local function do_make_state() return state_helper { precondition = precond, next_state = next_state, postcondition = postcond } end return do_make_state end describe('state helper object', function() it('is necessary to provide a name, next_state, pre- and postcondition', function() local name = 'state_name' local function next_state() end local function precondition() end local function postcondition() end assert.equal(false, pcall(make_state(nil, nil, nil, nil))) assert.equal(false, pcall(make_state(name, nil, nil, nil))) assert.equal(false, pcall(make_state(name, precondition, nil, nil))) assert.equal(false, pcall(make_state(name, precondition, next_state, nil))) assert.equal(true, pcall(make_state(name, precondition, next_state, postcondition))) assert.equal(false, pcall(function() state(name)(nil) end)) end) it('returns a table containing precondition, next_state and postcondition', function() local state_name = 'name of the state' local function precondition() end local function next_state() end local function postcondition() end local a_state = state 'name of the state' { precondition = precondition, next_state = next_state, postcondition = postcondition } assert.equal(state_name, a_state.name) assert.equal(precondition, a_state.precondition) assert.equal(next_state, a_state.next_state) assert.equal(postcondition, a_state.postcondition) end) end)
mit
n0xus/darkstar
scripts/globals/items/chocolate_cake.lua
36
1186
----------------------------------------- -- ID: 5633 -- Item: Chocolate Cake -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- MP +3% -- MP Recovered while healing +6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5633); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPP, 3); target:addMod(MOD_MPHEAL, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPP, 3); target:delMod(MOD_MPHEAL, 6); end;
gpl-3.0
notcake/quicktool
lua/quicktool/ui/imagecacheentry.lua
3
1135
local self = {} QuickTool.ImageCacheEntry = QuickTool.MakeConstructor (self) function self:ctor (image) self.Image = image self.Material = Material (image) if string.find (self.Material:GetShader (), "VertexLitGeneric") or string.find (self.Material:GetShader (), "Cable") then local baseTexture = self.Material:GetString ("$basetexture") if baseTexture then local newMaterial = { ["$basetexture"] = baseTexture, ["$vertexcolor"] = 1, ["$vertexalpha"] = 1 } self.Material = CreateMaterial (image .. "_DImage", "UnlitGeneric", newMaterial) end end self.Width = self.Material:GetTexture ("$basetexture"):Width () self.Height = self.Material:GetTexture ("$basetexture"):Height () end function self:Draw (x, y, r, g, b, a) surface.SetMaterial (self.Material) surface.SetDrawColor (r or 255, g or 255, b or 255, a or 255) surface.DrawTexturedRect (x or 0, y or 0, self.Width, self.Height) end function self:GetHeight () return self.Height end function self:GetSize () return self.Width, self.Height end function self:GetWidth () return self.Width end
gpl-3.0
n0xus/darkstar
scripts/globals/weaponskills/stringing_pummel.lua
18
4579
----------------------------------- -- Stringing Pummel -- Sword weapon skill -- Skill Level: N/A -- Delivers a sixfold attack. Damage varies with TP. Kenkonken: Aftermath effect varies with TP. -- Available only after completing the Unlocking a Myth (Puppetmaster) quest. -- Aligned with the Shadow Gorget, Soil Gorget & Flame Gorget. -- Aligned with the Shadow Belt, Soil Belt & Flame Belt. -- Element: Darkness -- Modifiers: STR:32% VIT:32% -- 100%TP 200%TP 300%TP -- 1 1 1 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 6; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.32; params.dex_wsc = 0.0; params.vit_wsc = 0.32; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.15; params.crit200 = 0.45; params.crit300 = 0.65; params.canCrit = true; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 0.75; params.ftp200 = 0.75; params.ftp300 = 0.75; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if ((player:getEquipID(SLOT_MAIN) == 19008) and (player:getMainJob() == JOB_PUP)) then if (damage > 0) then -- AFTERMATH LEVEL 1 if ((player:getTP() >= 100) and (player:getTP() <= 110)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 1); elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 1); elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 1); elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 1); elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 1); elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 1); elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 1); elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 1); elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 1); elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 1); -- AFTERMATH LEVEL 2 elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 1); elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 1); elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 1); elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 1); elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 1); elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 1); elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 1); elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 1); elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 1); elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 1); -- AFTERMATH LEVEL 3 elseif ((player:getTP() == 300)) then player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 1); end end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
ppriest/mame
3rdparty/genie/tests/actions/vstudio/cs2005/projectsettings.lua
47
3943
-- -- tests/actions/vstudio/cs2005/projectsettings.lua -- Validate generation of root <PropertyGroup/> in Visual Studio 2005+ .csproj -- Copyright (c) 2009-2011 Jason Perkins and the Premake project -- T.vstudio_cs2005_projectsettings = { } local suite = T.vstudio_cs2005_projectsettings local cs2005 = premake.vstudio.cs2005 -- -- Setup -- local sln, prj function suite.setup() sln = test.createsolution() language "C#" uuid "AE61726D-187C-E440-BD07-2556188A6565" end local function prepare() premake.bake.buildconfigs() prj = premake.solution.getproject(sln, 1) cs2005.projectsettings(prj) end -- -- Version Tests -- function suite.OnVs2005() _ACTION = "vs2005" prepare() test.capture [[ <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>8.0.50727</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>MyProject</RootNamespace> <AssemblyName>MyProject</AssemblyName> </PropertyGroup> ]] end function suite.OnVs2008() _ACTION = "vs2008" prepare() test.capture [[ <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>MyProject</RootNamespace> <AssemblyName>MyProject</AssemblyName> </PropertyGroup> ]] end function suite.OnVs2010() _ACTION = "vs2010" prepare() test.capture [[ <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>MyProject</RootNamespace> <AssemblyName>MyProject</AssemblyName> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkProfile></TargetFrameworkProfile> <FileAlignment>512</FileAlignment> </PropertyGroup> ]] end function suite.OnVs2012() _ACTION = "vs2012" prepare() test.capture [[ <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>MyProject</RootNamespace> <AssemblyName>MyProject</AssemblyName> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> ]] end -- -- Framework Tests -- function suite.OnFrameworkVersion() _ACTION = "vs2005" framework "3.0" prepare() test.capture [[ <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>8.0.50727</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>MyProject</RootNamespace> <AssemblyName>MyProject</AssemblyName> <TargetFrameworkVersion>v3.0</TargetFrameworkVersion> </PropertyGroup> ]] end
gpl-2.0
adamlerer/nn
SpatialAveragePooling.lua
37
1063
local SpatialAveragePooling, parent = torch.class('nn.SpatialAveragePooling', 'nn.Module') function SpatialAveragePooling:__init(kW, kH, dW, dH) parent.__init(self) self.kW = kW self.kH = kH self.dW = dW or 1 self.dH = dH or 1 self.divide = true end function SpatialAveragePooling:updateOutput(input) input.nn.SpatialAveragePooling_updateOutput(self, input) -- for backward compatibility with saved models -- which are not supposed to have "divide" field if not self.divide then self.output:mul(self.kW*self.kH) end return self.output end function SpatialAveragePooling:updateGradInput(input, gradOutput) if self.gradInput then input.nn.SpatialAveragePooling_updateGradInput(self, input, gradOutput) -- for backward compatibility if not self.divide then self.gradInput:mul(self.kW*self.kH) end return self.gradInput end end function SpatialAveragePooling:__tostring__() return string.format('%s(%d,%d,%d,%d)', torch.type(self), self.kW, self.kH, self.dW, self.dH) end
bsd-3-clause