repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
UnfortunateFruit/darkstar
scripts/globals/spells/bluemagic/queasyshroom.lua
9
2026
----------------------------------------- -- Spell: Queasyshroom -- Additional effect: Poison. Duration of effect varies with TP -- Spell cost: 20 MP -- Monster Type: Plantoids -- Spell Type: Physical (Piercing) -- Blue Magic Points: 2 -- Stat Bonus: HP-5, MP+5 -- Level: 8 -- Casting Time: 2 seconds -- Recast Time: 15 seconds -- Skillchain Element(s): Dark (can open Transfixion or Detonation; can close Compression or Gravitation) -- Combos: None ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_CRITICAL; params.dmgtype = DMGTYPE_PIERCE; params.scattr = SC_DARK; params.numhits = 1; params.multiplier = 1.25; params.tp150 = 1.25; params.tp300 = 1.25; params.azuretp = 1.25; params.duppercap = 8; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.20; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); local chance = math.random(); if(damage > 0 and chance > 10) then local typeEffect = EFFECT_POISON; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,3,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/effects/mark_of_seed.lua
35
1826
----------------------------------- -- -- EFFECT_MARK_OF_SEED -- -- DO NOT try to use this anywhere else but Fei'Yin! ----------------------------------- package.loaded["scripts/zones/FeiYin/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/keyitems"); require("scripts/zones/FeiYin/TextIDs"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:setVar("SEED_AFTERGLOW_TIMER",1); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) local Half_Minutes = target:getVar("SEED_AFTERGLOW_TIMER"); if (Half_Minutes == 1) then target:setVar("SEED_AFTERGLOW_TIMER",(Half_Minutes+1)); target:messageSpecial(MARK_OF_SEED_FLICKERS); elseif (Half_Minutes == 40) then target:messageSpecial(MARK_OF_SEED_IS_ABOUT_TO_DISSIPATE); target:setVar("SEED_AFTERGLOW_TIMER",(Half_Minutes+1)); elseif (Half_Minutes == 20) then target:messageSpecial(MARK_OF_SEED_GROWS_FAINTER); target:setVar("SEED_AFTERGLOW_TIMER",(Half_Minutes+1)); elseif (Half_Minutes >= 2) then target:setVar("SEED_AFTERGLOW_TIMER",(Half_Minutes+1)); end end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) if (target:hasKeyItem(MARK_OF_SEED) == false and player:hasKeyItem(AZURE_KEY) == false) then target:messageSpecial(MARK_OF_SEED_HAS_VANISHED); end target:setVar("SEED_AFTERGLOW_TIMER",0); target:setVar("SEED_AFTERGLOW_MASK",0); target:setVar("SEED_AFTERGLOW_INTENSITY",0); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Mine_Shaft_2716/bcnms/century_of_hardship.lua
30
1774
----------------------------------- -- Area: Mine_Shaft_2716 -- Name: century_of_hardship -- bcnmID : 736 -- inst 2 -54 -1 -100 -- inst 3 425 -121 -99 ----------------------------------- package.loaded["scripts/zones/Mine_Shaft_2716/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Mine_Shaft_2716/TextIDs"); -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Louverance_s_Path") == 5) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); player:setVar("COP_Louverance_s_Path",6); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); end 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:addExp(1000); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/himesama_rice_ball.lua
15
1754
----------------------------------------- -- ID: 5928 -- Item: Himesama Rice Ball -- Food Effect: 30 Mins, All Races ----------------------------------------- -- HP 25 -- Dexterity 4 -- Vitality 4 -- Character 4 -- Effect with enhancing equipment -- Attack +60 -- Defense +40 -- Triple Attack 1 ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/equipment"); ----------------------------------------- -- 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,RiceBalls(target),0,1800,5928); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) local power = effect:getPower(); target:addMod(MOD_HP, 25); target:addMod(MOD_DEX, 4); target:addMod(MOD_VIT, 4); target:addMod(MOD_CHR, 4); target:addMod(MOD_ATT, 60*power); target:addMod(MOD_DEF, 40*power); target:addMod(MOD_TRIPLE_ATTACK,1*power); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) local power = effect:getPower(); target:delMod(MOD_HP, 25); target:delMod(MOD_DEX, 4); target:delMod(MOD_VIT, 4); target:delMod(MOD_CHR, 4); target:delMod(MOD_ATT, 60*power); target:delMod(MOD_DEF, 40*power); target:delMod(MOD_TRIPLE_ATTACK,1*power); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Aydeewa_Subterrane/npcs/qm3.lua
7
1217
----------------------------------- -- Area: Aydeewa Subterrane -- NPC: ??? (Spawn Chigre(ZNM T1)) -- @pos -217 35 12 68 ----------------------------------- package.loaded["scripts/zones/Aydeewa_Subterrane/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aydeewa_Subterrane/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(2602,1) and trade:getItemCount() == 1) then -- Trade Spoilt Blood player:tradeComplete(); SpawnMob(17056186,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
UnfortunateFruit/darkstar
scripts/zones/Nashmau/npcs/Nomad_Moogle.lua
34
1104
----------------------------------- -- -- Nomad Moogle -- ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,NOMAD_MOOGLE_DIALOG); player:sendMenu(1); end; ----------------------------------- -- onEventUpdate Action ----------------------------------- function onEventUpdate(player,csid,option) --print("onEventUpdate"); --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --print("onEventFinish"); --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
MuhammadWang/MCServer
lib/tolua++/src/bin/lua/namespace.lua
49
1180
-- tolua: namespace class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 2003 -- $Id: $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Namespace class -- Represents a namesapce definition. -- Stores the following fields: -- name = class name -- {i} = list of members classNamespace = { classtype = 'namespace', name = '', } classNamespace.__index = classNamespace setmetatable(classNamespace,classModule) -- Print method function classNamespace:print (ident,close) print(ident.."Namespace{") print(ident.." name = '"..self.name.."',") local i=1 while self[i] do self[i]:print(ident.." ",",") i = i+1 end print(ident.."}"..close) end -- Internal constructor function _Namespace (t) setmetatable(t,classNamespace) append(t) return t end -- Constructor -- Expects the name and the body of the namespace. function Namespace (n,b) local c = _Namespace(_Container{name=n}) push(c) c:parse(strsub(b,2,strlen(b)-1)) -- eliminate braces pop() end
apache-2.0
UnfortunateFruit/darkstar
scripts/globals/weaponskills/shark_bite.lua
30
1459
----------------------------------- -- Shark Bite -- Dagger weapon skill -- Skill level: 225 -- Delivers a twofold attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Will stack with Trick Attack. -- Aligned with the Breeze Gorget & Thunder Gorget. -- Aligned with the Breeze Belt & Thunder Belt. -- Element: None -- Modifiers: DEX:40% AGI:40% -- 100%TP 200%TP 300%TP -- 2.00 4 5.75 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 2; params.ftp100 = 2; params.ftp200 = 2.5; params.ftp300 = 3; params.str_wsc = 0.0; params.dex_wsc = 0.5; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp200 = 4; params.ftp300 = 5.75; params.dex_wsc = 0.4; params.agi_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
jj918160/cocos2d-x-samples
samples/KillBug/src/cocos/framework/extends/UIEditBox.lua
57
1442
--[[ Copyright (c) 2011-2014 chukong-inc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local EditBox = ccui.EditBox function EditBox:onEditHandler(callback) self:registerScriptEditBoxHandler(function(name, sender) local event = {} event.name = name event.target = sender callback(event) end) return self end function EditBox:removeEditHandler() self:unregisterScriptEditBoxHandler() return self end
mit
dylanleigh/dl-minetest
dltweaks/init.lua
1
4217
-- stone recipe creates 2 (sand)stonebrick from 4 (sand)stone (was 1:4) minetest.register_craft({ output = 'default:stonebrick 2', recipe = { {'default:stone', 'default:stone'}, {'default:stone', 'default:stone'}, } }) minetest.register_craft({ output = 'default:sandstonebrick 2', recipe = { {'default:sandstone', 'default:sandstone'}, {'default:sandstone', 'default:sandstone'}, } }) -- Craft clay from dirt minetest.register_craft({ output = 'default:clay_lump', recipe = { {'default:dirt', 'default:dirt', 'default:dirt'}, {'default:dirt', 'default:dirt', 'default:dirt'}, } }) -- Smelt (char)coal from a tree or jungletree minetest.register_craft({ type = "cooking", output = "default:coal_lump", recipe = "group:tree", }) -- Func for modifying already registered tools/etc taken from CasimirKaPazi's -- Stoneage mod, which is more realistic and difficult then regular minetest -- Get it from https://github.com/CasimirKaPazi/stoneage local entity local registered = function(case,name) local params = {} local list if case == "item" then list = minetest.registered_items end if case == "node" then list = minetest.registered_nodes end if case == "craftitem" then list = minetest.registered_craftitems end if case == "tool" then list = minetest.registered_tools end if case == "entity" then list = minetest.registered_entities end if list then for k,v in pairs(list[name]) do params[k] = v end end return params end -- Trees fall down when chopped - also for cacti/papyrus? -- FIXME TODO: Make this optional with a config entity = registered("node","default:tree") entity.groups = {tree=1,falling_node=1,choppy=2,oddly_breakable_by_hand=1,flammable=2} minetest.register_node(":default:tree", entity) entity = registered("node","default:jungletree") entity.groups = {tree=1,falling_node=1,choppy=2,oddly_breakable_by_hand=1,flammable=2}, minetest.register_node(":default:jungletree", entity) -- Axes more effective entity = registered("tool","default:axe_stone") entity.tool_capabilities = { full_punch_interval = 1.2, max_drop_level=0, groupcaps={ choppy={times={[1]=1.50, [2]=1.00, [3]=0.75}, uses=20, maxlevel=1}, }, damage_groups = {fleshy=3}, } minetest.register_tool(":default:axe_stone", entity) -- FIXME TODO other axes -- Modify: Wooden axe/pickaxe less effective and break quicker entity = registered("tool","default:axe_wood") entity.tool_capabilities = { full_punch_interval = 1.5, max_drop_level=0, groupcaps={ choppy = {times={[2]=3.00, [3]=2.00}, uses=2, maxlevel=1}, }, damage_groups = {fleshy=2}, } minetest.register_tool(":default:axe_wood", entity) entity = registered("tool","default:pick_wood") entity.tool_capabilities = { full_punch_interval = 2.4, max_drop_level=0, groupcaps={ cracky = {times={[3]=1.60}, uses=1, maxlevel=1}, }, damage_groups = {fleshy=2}, } minetest.register_tool(":default:pick_wood", entity) -- Lava sounds TODO: may be buggy? minetest.register_abm({ nodenames = {"default:lava_source"}, interval = 12, chance = 128, action = function(pos, node, active_object_count, active_object_count_wider) minetest.sound_play("fire_small", {pos = pos, gain = 0.05, max_hear_distance = 20}) end}) -- More items as fuel minetest.register_craft({ type = "fuel", recipe = "group:flower", burntime = 1, }) minetest.register_craft({ type = "fuel", recipe = "default:stick", burntime = 2, }) minetest.register_craft({ type = "fuel", recipe = "doors:door_wood", burntime = 10, }) minetest.register_craft({ type = "fuel", recipe = "default:ladder", burntime = 7, }) minetest.register_craft({ type = "fuel", recipe = "default:fence_wood", burntime = 4, }) minetest.register_craft({ type = "fuel", recipe = "default:bookshelf", burntime = 30, })
bsd-2-clause
ennis/autograph-pipelines
resources/scripts/pl/data.lua
2
20443
--- Reading and querying simple tabular data. -- -- data.read 'test.txt' -- ==> {{10,20},{2,5},{40,50},fieldnames={'x','y'},delim=','} -- -- Provides a way of creating basic SQL-like queries. -- -- require 'pl' -- local d = data.read('xyz.txt') -- local q = d:select('x,y,z where x > 3 and z < 2 sort by y') -- for x,y,z in q do -- print(x,y,z) -- end -- -- See @{06-data.md.Reading_Columnar_Data|the Guide} -- -- Dependencies: `pl.utils`, `pl.array2d` (fallback methods) -- @module pl.data local utils = require 'pl.utils' local _DEBUG = rawget(_G,'_DEBUG') local patterns,function_arg,usplit,array_tostring = utils.patterns,utils.function_arg,utils.split,utils.array_tostring local append,concat = table.insert,table.concat local gsub = string.gsub local io = io local _G,print,type,tonumber,ipairs,setmetatable,pcall,error = _G,print,type,tonumber,ipairs,setmetatable,pcall,error local data = {} local parse_select local function count(s,chr) chr = utils.escape(chr) local _,cnt = s:gsub(chr,' ') return cnt end local function rstrip(s) return (s:gsub('%s+$','')) end local function strip (s) return (rstrip(s):gsub('^%s*','')) end -- This gives `l` the standard List metatable, -- pulling in the List module. local function makelist(l) return setmetatable(l, require('pl.List')) end local function map(fun,t) local res = {} for i = 1,#t do res[i] = fun(t[i]) end return res end local function split(line,delim,csv,n) local massage -- CSV fields may be double-quoted and may contain commas! if csv and line:match '"' then line = line:gsub('"([^"]+)"',function(str) local s,cnt = str:gsub(',','\001') if cnt > 0 then massage = true end return s end) if massage then massage = function(s) return (s:gsub('\001',',')) end end end local res = (usplit(line,delim,false,n)) if csv then -- restore CSV commas-in-fields if massage then res = map(massage,res) end -- in CSV mode trailiing commas are significant! if line:match ',$' then append(res,'') end end return makelist(res) end local function find(t,v) for i = 1,#t do if v == t[i] then return i end end end local DataMT = { column_by_name = function(self,name) if type(name) == 'number' then name = '$'..name end local arr = {} for res in data.query(self,name) do append(arr,res) end return makelist(arr) end, copy_select = function(self,condn) condn = parse_select(condn,self) local iter = data.query(self,condn) local res = {} local row = makelist{iter()} while #row > 0 do append(res,row) row = makelist{iter()} end res.delim = self.delim return data.new(res,split(condn.fields,',')) end, column_names = function(self) return self.fieldnames end, } local array2d DataMT.__index = function(self,name) local f = DataMT[name] if f then return f end if not array2d then array2d = require 'pl.array2d' end return array2d[name] end --- return a particular column as a list of values (method). -- @param name either name of column, or numerical index. -- @function Data.column_by_name --- return a query iterator on this data (method). -- @string condn the query expression -- @function Data.select -- @see data.query --- return a row iterator on this data (method). -- @string condn the query expression -- @function Data.select_row --- return a new data object based on this query (method). -- @string condn the query expression -- @function Data.copy_select --- return the field names of this data object (method). -- @function Data.column_names --- write out a row (method). -- @param f file-like object -- @function Data.write_row --- write data out to file (method). -- @param f file-like object -- @function Data.write -- [guessing delimiter] We check for comma, tab and spaces in that order. -- [issue] any other delimiters to be checked? local delims = {',','\t',' ',';'} local function guess_delim (line) if line=='' then return ' ' end for _,delim in ipairs(delims) do if count(line,delim) > 0 then return delim == ' ' and '%s+' or delim end end return ' ' end -- [file parameter] If it's a string, we try open as a filename. If nil, then -- either stdin or stdout depending on the mode. Otherwise, check if this is -- a file-like object (implements read or write depending) local function open_file (f,mode) local opened, err local reading = mode == 'r' if type(f) == 'string' then if f == 'stdin' then f = io.stdin elseif f == 'stdout' then f = io.stdout else f,err = io.open(f,mode) if not f then return nil,err end opened = true end end if f and ((reading and not f.read) or (not reading and not f.write)) then return nil, "not a file-like object" end return f,nil,opened end local function all_n () end --- read a delimited file in a Lua table. -- By default, attempts to treat first line as separated list of fieldnames. -- @param file a filename or a file-like object -- @tab cnfg parsing options -- @string cnfg.delim a string pattern to split fields -- @array cnfg.fieldnames (i.e. don't read from first line) -- @bool cnfg.no_convert (default is to try conversion on first data line) -- @tab cnfg.convert table of custom conversion functions with column keys -- @int cnfg.numfields indices of columns known to be numbers -- @bool cnfg.last_field_collect only split as many fields as fieldnames. -- @int cnfg.thousands_dot thousands separator in Excel CSV is '.' -- @bool cnfg.csv fields may be double-quoted and contain commas; -- Also, empty fields are considered to be equivalent to zero. -- @return `data` object, or `nil` -- @return error message. May be a file error, 'not a file-like object' -- or a conversion error function data.read(file,cnfg) local err,opened,count,line local D = {} if not cnfg then cnfg = {} end local f,err,opened = open_file(file,'r') if not f then return nil, err end local thousands_dot = cnfg.thousands_dot local csv = cnfg.csv if csv then cnfg.delim = ',' end -- note that using dot as the thousands separator (@thousands_dot) -- requires a special conversion function! For CSV, _empty fields_ are -- considered to default to numerial zeroes. local tonumber = tonumber local function try_number(x) if thousands_dot then x = x:gsub('%.(...)','%1') end if csv and x == '' then x = '0' end local v = tonumber(x) if v == nil then return nil,"not a number" end return v end count = 1 line = f:read() if not line then return nil, "empty file" end -- first question: what is the delimiter? D.delim = cnfg.delim and cnfg.delim or guess_delim(line) local delim = D.delim local conversion local numfields = {} local function append_conversion (idx,conv) conversion = conversion or {} append(numfields,idx) append(conversion,conv) end if cnfg.numfields then for _,n in ipairs(cnfg.numfields) do append_conversion(n,try_number) end end -- some space-delimited data starts with a space. This should not be a column, -- although it certainly would be for comma-separated, etc. local stripper if delim == '%s+' and line:find(delim) == 1 then stripper = function(s) return s:gsub('^%s+','') end line = stripper(line) end -- first line will usually be field names. Unless fieldnames are specified, -- we check if it contains purely numerical values for the case of reading -- plain data files. if not cnfg.fieldnames then local fields,nums fields = split(line,delim,csv) if not cnfg.convert then nums = map(tonumber,fields) if #nums == #fields then -- they're ALL numbers! append(D,nums) -- add the first converted row -- and specify conversions for subsequent rows for i = 1,#nums do append_conversion(i,try_number) end else -- we'll try to check numbers just now.. nums = nil end else -- [explicit column conversions] (any deduced number conversions will be added) for idx,conv in pairs(cnfg.convert) do append_conversion(idx,conv) end end if nums == nil then cnfg.fieldnames = fields end line = f:read() count = count + 1 if stripper then line = stripper(line) end elseif type(cnfg.fieldnames) == 'string' then cnfg.fieldnames = split(cnfg.fieldnames,delim,csv) end local nfields -- at this point, the column headers have been read in. If the first -- row consisted of numbers, it has already been added to the dataset. if cnfg.fieldnames then D.fieldnames = cnfg.fieldnames -- [collecting end field] If @last_field_collect then we'll -- only split as many fields as there are fieldnames if cnfg.last_field_collect then nfields = #D.fieldnames end -- [implicit column conversion] unless @no_convert, we need the numerical field indices -- of the first data row. These can also be specified explicitly by @numfields. if not cnfg.no_convert then local fields = split(line,D.delim,csv,nfields) for i = 1,#fields do if not find(numfields,i) and try_number(fields[i]) then append_conversion(i,try_number) end end end end -- keep going until finished while line do if not line:find ('^%s*$') then -- [blank lines] ignore them! if stripper then line = stripper(line) end local fields = split(line,delim,csv,nfields) if conversion then -- there were field conversions... for k = 1,#numfields do local i,conv = numfields[k],conversion[k] local val,err = conv(fields[i]) if val == nil then return nil, err..": "..fields[i].." at line "..count else fields[i] = val end end end append(D,fields) end line = f:read() count = count + 1 end if opened then f:close() end if delim == '%s+' then D.delim = ' ' end if not D.fieldnames then D.fieldnames = {} end return data.new(D) end local function write_row (data,f,row,delim) data.temp = array_tostring(row,data.temp) f:write(concat(data.temp,delim),'\n') end function DataMT:write_row(f,row) write_row(self,f,row,self.delim) end --- write 2D data to a file. -- Does not assume that the data has actually been -- generated with `new` or `read`. -- @param data 2D array -- @param file filename or file-like object -- @tparam[opt] {string} fieldnames list of fields (optional) -- @string[opt='\t'] delim delimiter (default tab) -- @return true or nil, error function data.write (data,file,fieldnames,delim) local f,err,opened = open_file(file,'w') if not f then return nil, err end if not fieldnames then fieldnames = data.fieldnames end delim = delim or '\t' if fieldnames and #fieldnames > 0 then f:write(concat(fieldnames,delim),'\n') end for i = 1,#data do write_row(data,f,data[i],delim) end if opened then f:close() end return true end function DataMT:write(file) data.write(self,file,self.fieldnames,self.delim) end local function massage_fieldnames (fields,copy) -- fieldnames must be valid Lua identifiers; ignore any surrounding padding -- but keep the original fieldnames... for i = 1,#fields do local f = strip(fields[i]) copy[i] = f fields[i] = f:gsub('%W','_') end end --- create a new dataset from a table of rows. -- Can specify the fieldnames, else the table must have a field called -- 'fieldnames', which is either a string of delimiter-separated names, -- or a table of names. <br> -- If the table does not have a field called 'delim', then an attempt will be -- made to guess it from the fieldnames string, defaults otherwise to tab. -- @param d the table. -- @tparam[opt] {string} fieldnames optional fieldnames -- @return the table. function data.new (d,fieldnames) d.fieldnames = d.fieldnames or fieldnames or '' if not d.delim and type(d.fieldnames) == 'string' then d.delim = guess_delim(d.fieldnames) d.fieldnames = split(d.fieldnames,d.delim) end d.fieldnames = makelist(d.fieldnames) d.original_fieldnames = {} massage_fieldnames(d.fieldnames,d.original_fieldnames) setmetatable(d,DataMT) -- a query with just the fieldname will return a sequence -- of values, which seq.copy turns into a table. return d end local sorted_query = [[ return function (t) local i = 0 local v local ls = {} for i,v in ipairs(t) do if CONDITION then ls[#ls+1] = v end end table.sort(ls,function(v1,v2) return SORT_EXPR end) local n = #ls return function() i = i + 1 v = ls[i] if i > n then return end return FIELDLIST end end ]] -- question: is this optimized case actually worth the extra code? local simple_query = [[ return function (t) local n = #t local i = 0 local v return function() repeat i = i + 1 v = t[i] until i > n or CONDITION if i > n then return end return FIELDLIST end end ]] local function is_string (s) return type(s) == 'string' end local field_error local function fieldnames_as_string (data) return concat(data.fieldnames,',') end local function massage_fields(data,f) local idx if f:find '^%d+$' then idx = tonumber(f) else idx = find(data.fieldnames,f) end if idx then return 'v['..idx..']' else field_error = f..' not found in '..fieldnames_as_string(data) return f end end local function process_select (data,parms) --- preparing fields ---- local res,ret field_error = nil local fields = parms.fields local numfields = fields:find '%$' or #data.fieldnames == 0 if fields:find '^%s*%*%s*' then if not numfields then fields = fieldnames_as_string(data) else local ncol = #data[1] fields = {} for i = 1,ncol do append(fields,'$'..i) end fields = concat(fields,',') end end local idpat = patterns.IDEN if numfields then idpat = '%$(%d+)' else -- massage field names to replace non-identifier chars fields = rstrip(fields):gsub('[^,%w]','_') end local massage_fields = utils.bind1(massage_fields,data) ret = gsub(fields,idpat,massage_fields) if field_error then return nil,field_error end parms.fields = fields parms.proc_fields = ret parms.where = parms.where or 'true' if is_string(parms.where) then parms.where = gsub(parms.where,idpat,massage_fields) field_error = nil end return true end parse_select = function(s,data) local endp local parms = {} local w1,w2 = s:find('where ') local s1,s2 = s:find('sort by ') if w1 then -- where clause! endp = (s1 or 0)-1 parms.where = s:sub(w2+1,endp) end if s1 then -- sort by clause (must be last!) parms.sort_by = s:sub(s2+1) end endp = (w1 or s1 or 0)-1 parms.fields = s:sub(1,endp) local status,err = process_select(data,parms) if not status then return nil,err else return parms end end --- create a query iterator from a select string. -- Select string has this format: <br> -- FIELDLIST [ where LUA-CONDN [ sort by FIELD] ]<br> -- FIELDLIST is a comma-separated list of valid fields, or '*'. <br> <br> -- The condition can also be a table, with fields 'fields' (comma-sep string or -- table), 'sort_by' (string) and 'where' (Lua expression string or function) -- @param data table produced by read -- @param condn select string or table -- @param context a list of tables to be searched when resolving functions -- @param return_row if true, wrap the results in a row table -- @return an iterator over the specified fields, or nil -- @return an error message function data.query(data,condn,context,return_row) local err if is_string(condn) then condn,err = parse_select(condn,data) if not condn then return nil,err end elseif type(condn) == 'table' then if type(condn.fields) == 'table' then condn.fields = concat(condn.fields,',') end if not condn.proc_fields then local status,err = process_select(data,condn) if not status then return nil,err end end else return nil, "condition must be a string or a table" end local query, k if condn.sort_by then -- use sorted_query query = sorted_query else query = simple_query end local fields = condn.proc_fields or condn.fields if return_row then fields = '{'..fields..'}' end query,k = query:gsub('FIELDLIST',fields) if is_string(condn.where) then query = query:gsub('CONDITION',condn.where) condn.where = nil else query = query:gsub('CONDITION','_condn(v)') condn.where = function_arg(0,condn.where,'condition.where must be callable') end if condn.sort_by then local expr,sort_var,sort_dir local sort_by = condn.sort_by local i1,i2 = sort_by:find('%s+') if i1 then sort_var,sort_dir = sort_by:sub(1,i1-1),sort_by:sub(i2+1) else sort_var = sort_by sort_dir = 'asc' end if sort_var:match '^%$' then sort_var = sort_var:sub(2) end sort_var = massage_fields(data,sort_var) if field_error then return nil,field_error end if sort_dir == 'asc' then sort_dir = '<' else sort_dir = '>' end expr = ('%s %s %s'):format(sort_var:gsub('v','v1'),sort_dir,sort_var:gsub('v','v2')) query = query:gsub('SORT_EXPR',expr) end if condn.where then query = 'return function(_condn) '..query..' end' end if _DEBUG then print(query) end local fn,err = utils.load(query,'tmp') if not fn then return nil,err end fn = fn() -- get the function if condn.where then fn = fn(condn.where) end local qfun = fn(data) if context then -- [specifying context for condition] @context is a list of tables which are -- 'injected'into the condition's custom context append(context,_G) local lookup = {} utils.setfenv(qfun,lookup) setmetatable(lookup,{ __index = function(tbl,key) -- _G.print(tbl,key) for k,t in ipairs(context) do if t[key] then return t[key] end end end }) end return qfun end DataMT.select = data.query DataMT.select_row = function(d,condn,context) return data.query(d,condn,context,true) end --- Filter input using a query. -- @string Q a query string -- @param infile filename or file-like object -- @param outfile filename or file-like object -- @bool dont_fail true if you want to return an error, not just fail function data.filter (Q,infile,outfile,dont_fail) local err local d = data.read(infile or 'stdin') local out = open_file(outfile or 'stdout') local iter,err = d:select(Q) local delim = d.delim if not iter then err = 'error: '..err if dont_fail then return nil,err else utils.quit(1,err) end end while true do local res = {iter()} if #res == 0 then break end out:write(concat(res,delim),'\n') end end return data
mit
Cyumus/NutScript
plugins/crosshair.lua
5
2776
PLUGIN.name = "Crosshair" PLUGIN.author = "Black Tea" PLUGIN.desc = "A Crosshair." if (CLIENT) then local function drawdot( pos, size, col ) local color = col[2] surface.SetDrawColor(color.r, color.g, color.b, color.a) surface.DrawRect(pos[1] - size/2, pos[2] - size/2, size, size) local color = col[1] surface.SetDrawColor(color.r, color.g, color.b, color.a) surface.DrawOutlinedRect(pos[1] - size/2, pos[2] - size/2 , size, size) end local w, h, aimVector, punchAngle, ft, screen, scaleFraction, distance, entity local math_round = math.Round local curGap = 0 local curAlpha = 0 local maxDistance = 1000 ^ 2 local crossSize = 4 local crossGap = 0 local colors = {color_black} local filter = {} function PLUGIN:PostDrawHUD() local client = LocalPlayer() if (!client:getChar() or !client:Alive()) then return end local entity = Entity(client:getLocalVar("ragdoll", 0)) if (entity:IsValid()) then return end local wep = client:GetActiveWeapon() if (wep and wep:IsValid() and wep.HUDPaint) then return end if (hook.Run("ShouldDrawCrosshair") == false or g_ContextMenu:IsVisible() or nut.gui.char:IsVisible()) then return end aimVector = client:EyeAngles() punchAngle = client:GetPunchAngle() w, h = ScrW(), ScrH() ft = FrameTime() filter = {client} local vehicle = client:GetVehicle() if (vehicle and IsValid(vehicle)) then aimVector = aimVector + vehicle:GetAngles() table.insert(filter, vehicle) end local data = {} data.start = client:GetShootPos() data.endpos = data.start + (aimVector + punchAngle):Forward()*65535 data.filter = filter local trace = util.TraceLine(data) entity = trace.Entity distance = trace.StartPos:DistToSqr(trace.HitPos) scaleFraction = 1 - math.Clamp(distance / maxDistance, 0, .5) screen = trace.HitPos:ToScreen() crossSize = 4 crossGap = 25 * (scaleFraction - (client:isWepRaised() and 0 or .1)) if (IsValid(entity) and entity:GetClass() == "nut_item" and entity:GetPos():DistToSqr(data.start) <= 16384) then crossGap = 0 crossSize = 5 end curGap = Lerp(ft * 2, curGap, crossGap) curAlpha = Lerp(ft * 2, curAlpha, (!client:isWepRaised() and 255 or 150)) curAlpha = hook.Run("GetCrosshairAlpha", curAlpha) or curAlpha colors[2] = Color(255, curAlpha, curAlpha, curAlpha) drawdot( {math_round(screen.x), math_round(screen.y)}, crossSize, colors) drawdot( {math_round(screen.x + curGap), math_round(screen.y)}, crossSize, colors) drawdot( {math_round(screen.x - curGap), math_round(screen.y)}, crossSize, colors) drawdot( {math_round(screen.x), math_round(screen.y + curGap * .8)}, crossSize, colors) drawdot( {math_round(screen.x), math_round(screen.y - curGap * .8)}, crossSize, colors) end end
mit
nesstea/darkstar
scripts/zones/Cloister_of_Frost/TextIDs.lua
15
1042
-- 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> -- Quest dialog YOU_CANNOT_ENTER_THE_BATTLEFIELD = 7206; -- You cannot enter the battlefield at present. SHIVA_UNLOCKED = 7564; -- You are now able to summon -- ZM4 Dialog CANNOT_REMOVE_FRAG = 7654; -- It is an oddly shaped stone monument ALREADY_OBTAINED_FRAG = 7655; -- You have already obtained this monument ALREADY_HAVE_ALL_FRAGS = 7656; -- You have obtained all of the fragments FOUND_ALL_FRAGS = 7657; -- You have obtained ! You now have all 8 fragments of light! ZILART_MONUMENT = 7658; -- It is an ancient Zilart monument -- Other PROTOCRYSTAL = 7230; -- It is a giant crystal. -- conquest Base CONQUEST_BASE = 7045; -- Tallying conquest results...
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/The_Garden_of_RuHmet/bcnms/when_angels_fall.lua
13
2243
----------------------------------- -- Area: The_Garden_of_RuHmet -- Name: when_angels_fall ----------------------------------- package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/The_Garden_of_RuHmet/TextIDs"); ----------------------------------- -- EXAMPLE SCRIPT -- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if(player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==4)then player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0); player:setVar("PromathiaStatus",5); else player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,1); -- end elseif(leavecode == 4) then player:startEvent(0x7d02); end --printf("leavecode: %u",leavecode); 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:setPos(420,0,445,192); end end;
gpl-3.0
GccX11/spacship
main.lua
1
2898
ast_speed = 10 ast_size = 50 ship_speed = 10 ship_width = 60 ship_height = math.floor(2*ship_width/3) flame_size = 40 ast_x = nil ast_y = nil x = 130 y = math.floor(love.graphics.getHeight() / 2) score = 0 max_score = 0 lose = false last_ast_time = 0 time_between_asts = 0 function love.load() end function love.update(dt) -- move ship if love.keyboard.isDown("up") then if y - ship_speed > 0 then y = y - ship_speed end end if love.keyboard.isDown("down") then if y + ship_speed + ship_height < love.graphics.getHeight() then y = y + ship_speed end end if love.keyboard.isDown("down") or love.keyboard.isDown("up") then if last_ast_time == 0 then last_ast_time = love.timer.getTime() time_between_asts = (love.math.random() * 4) * 1000 + 1000 end end -- generate random asteroids if ast_x == nil and ast_y == nil then if love.timer.getTime() - last_ast_time - time_between_asts < 100 then ast_size = math.floor(love.math.random() * 60) + 50 ast_x = love.graphics.getWidth() ast_y = math.floor(love.math.random() * (love.graphics.getHeight() - ast_size)) last_ast_time = love.timer.getTime() time_between_asts = (love.math.random() * 10) * 1000 + 1000 end else if check_collision(x,y,ship_width,ship_height, ast_x,ast_y,ast_size,ast_size) then -- lose = true if score > max_score then max_score = score end score = 0 end if ast_x - ast_speed + ast_size > 0 then ast_x = ast_x - ast_speed else last_ast_time = love.timer.getTime() ast_x = nil ast_y = nil if not lose then score = score + 1 if score > max_score then max_score = score end end end end end function love.draw() if not lose then love.graphics.print(score, 10, 10, 0, 2, 2) love.graphics.print(max_score, 100, 10, 0, 2, 2) if ast_x ~= nil and ast_y ~= nil then love.graphics.setColor(0, 0, 255) love.graphics.rectangle("fill", ast_x, ast_y, ast_size, ast_size) end love.graphics.setColor(255, 0, 0) love.graphics.circle("fill", x-math.floor(ship_width/10), y+math.floor(ship_height/2), flame_size, 3) --flame love.graphics.setColor(0, 255, 0) love.graphics.rectangle("fill", x, y, ship_width, ship_height) --ship else love.graphics.print("You Lose - Score "..score, love.graphics.getWidth()/2-120, love.graphics.getHeight()/2-30, 0, 2, 2) end end function love.keypressed(key) if lose or key == "escape" then love.event.quit() end end function love.quit() end -- Collision detection function. -- Returns true if two boxes overlap, false if they don't -- x1,y1 are the left-top coords of the first box, while w1,h1 are its width and height -- x2,y2,w2 & h2 are the same, but for the second box function check_collision(x1,y1,w1,h1, x2,y2,w2,h2) return x1 < x2+w2 and x2 < x1+w1 and y1 < y2+h2 and y2 < y1+h1 end
gpl-3.0
nesstea/darkstar
scripts/globals/spells/cure.lua
26
4531
----------------------------------------- -- Spell: Cure -- Restores target's HP. -- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local divisor = 0; local constant = 0; local basepower = 0; local power = 0; local basecure = 0; local final = 0; local minCure = 10; if (USE_OLD_CURE_FORMULA == true) then power = getCurePowerOld(caster); divisor = 1; constant = -10; if (power > 100) then divisor = 57; constant = 29.125; elseif (power > 60) then divisor = 2; constant = 5; end else power = getCurePower(caster); if (power < 20) then divisor = 4; constant = 10; basepower = 0; elseif (power < 40) then divisor = 1.3333; constant = 15; basepower = 20; elseif (power < 125) then divisor = 8.5; constant = 30; basepower = 40; elseif (power < 200) then divisor = 15; constant = 40; basepower = 125; elseif (power < 600) then divisor = 20; constant = 40; basepower = 200; else divisor = 999999; constant = 65; basepower = 0; end end if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCure(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end final = getCureFinal(caster,spell,basecure,minCure,false); if (caster:hasStatusEffect(EFFECT_AFFLATUS_SOLACE) and target:hasStatusEffect(EFFECT_STONESKIN) == false) then local solaceStoneskin = 0; local equippedBody = caster:getEquipID(SLOT_BODY); if (equippedBody == 11186) then solaceStoneskin = math.floor(final * 0.30); elseif (equippedBody == 11086) then solaceStoneskin = math.floor(final * 0.35); else solaceStoneskin = math.floor(final * 0.25); end target:addStatusEffect(EFFECT_STONESKIN,solaceStoneskin,0,25); end; final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); --Applying server mods.... final = final * CURE_POWER; local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); else -- no effect if player casted on mob if (target:isUndead()) then spell:setMsg(2); local dmg = calculateMagicDamage(minCure,1,caster,spell,target,HEALING_MAGIC_SKILL,MOD_MND,false)*0.5; local resist = applyResistance(caster,spell,target,caster:getStat(MOD_MND)-target:getStat(MOD_MND),HEALING_MAGIC_SKILL,1.0); dmg = dmg*resist; dmg = addBonuses(caster,spell,target,dmg); dmg = adjustForTarget(target,dmg,spell:getElement()); dmg = finalMagicAdjustments(caster,target,spell,dmg); final = dmg; target:delHP(final); target:updateEnmityFromDamage(caster,final); elseif (caster:getObjType() == TYPE_PC) then spell:setMsg(75); else -- e.g. monsters healing themselves. if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCureOld(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end final = getCureFinal(caster,spell,basecure,minCure,false); local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); end end return final; end;
gpl-3.0
nesstea/darkstar
scripts/zones/Southern_San_dOria/npcs/Rosel.lua
13
3014
----------------------------------- -- Area: Southern San d'Oria -- NPC: Rosel -- Starts and Finishes Quest: Rosel the Armorer -- @zone 230 -- @pos ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- 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("tradeRosel") == 0) then player:messageSpecial(ROSEL_DIALOG); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradeRosel",1); player:messageSpecial(FLYER_ACCEPTED); player:tradeComplete(); elseif (player:getVar("tradeRosel") ==1) then player:messageSpecial(FLYER_ALREADY); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RoselTheArmorer = player:getQuestStatus(SANDORIA,ROSEL_THE_ARMORER); receiprForThePrince = player:hasKeyItem(RECEIPT_FOR_THE_PRINCE); if (player:getVar("RefuseRoselTheArmorerQuest") == 1 and RoselTheArmorer == QUEST_AVAILABLE) then player:startEvent(0x020c); elseif (RoselTheArmorer == QUEST_AVAILABLE) then player:startEvent(0x020b); player:setVar("RefuseRoselTheArmorerQuest",1); elseif (RoselTheArmorer == QUEST_ACCEPTED and receiprForThePrince) then player:startEvent(0x020c); elseif (RoselTheArmorer == QUEST_ACCEPTED and receiprForThePrince == false) then player:startEvent(0x020f); 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); -- Rosel the Armorer, get quest and receipt for prince if ((csid == 0x020b or csid == 0x020c) and option == 0) then player:addQuest(SANDORIA, ROSEL_THE_ARMORER); player:setVar("RefuseRoselTheArmorerQuest",0); player:addKeyItem(RECEIPT_FOR_THE_PRINCE); player:messageSpecial(KEYITEM_OBTAINED,RECEIPT_FOR_THE_PRINCE); -- Rosel the Armorer, finished quest, recieve 200gil elseif (csid == 0x020f) then npcUtil.completeQuest(player, SANDORIA, ROSEL_THE_ARMORER, { title= ENTRANCE_DENIED, gil= 200 }); end end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/frostreaper.lua
41
1063
----------------------------------------- -- ID: 16784 -- Item: Frostreaper -- Additional Effect: Ice Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(3,10); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_ICE, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_ICE,0); dmg = adjustForTarget(target,dmg,ELE_ICE); dmg = finalMagicNonSpellAdjustments(player,target,ELE_ICE,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_ICE_DAMAGE,message,dmg; end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/spells/bluemagic/screwdriver.lua
28
1906
----------------------------------------- -- Spell: Screwdriver -- Deals critical damage. Chance of critical hit varies with TP -- Spell cost: 21 MP -- Monster Type: Aquans -- Spell Type: Physical (Piercing) -- Blue Magic Points: 3 -- Stat Bonus: VIT+1, CHR+1, HP+10 -- Level: 26 -- Casting Time: 0.5 seconds -- Recast Time: 14 seconds -- Skillchain Element(s): Light (Primary) and Earth (Secondary) -- (can open Compression, Reverberation, Detonation, Liquefaction, or Distortion; can close Transfixion, Scission, or Distortion) -- Combos: Evasion Bonus ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_CRITICAL; params.dmgtype = DMGTYPE_PIERCE; params.scattr = SC_TRANSFIXION; params.scattr2 = SC_SCISSION; params.numhits = 1; params.multiplier = 1.375; params.tp150 = 1.375; params.tp300 = 1.375; params.azuretp = 1.375; params.duppercap = 27; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.2; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
nesstea/darkstar
scripts/zones/LaLoff_Amphitheater/mobs/Ark_Angel_TT.lua
8
1923
----------------------------------- -- Area: LaLoff Amphitheater -- MOB: Ark Angel TT ----------------------------------- package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil; ----------------------------------- require("scripts/zones/LaLoff_Amphitheater/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:addMod(MOD_UFASTCAST, 30); mob:setMobMod(MOBMOD_MAIN_2HOUR, 1); mob:setMobMod(MOBMOD_SUB_2HOUR, 1); end ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) local mobid = mob:getID() for member = mobid-5, mobid+2 do if (GetMobAction(member) == 16) then GetMobByID(member):updateEnmity(target); end end end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) if (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON) and bit.band(mob:getBehaviour(),BEHAVIOUR_STANDBACK) > 0) then mob:setBehaviour(bit.band(mob:getBehaviour(), bit.bnot(BEHAVIOUR_STANDBACK))) mob:setMobMod(MOBMOD_TELEPORT_TYPE,0); mob:setMobMod(MOBMOD_SPAWN_LEASH,0); mob:setSpellList(0); end if (not mob:hasStatusEffect(EFFECT_BLOOD_WEAPON) and bit.band(mob:getBehaviour(),BEHAVIOUR_STANDBACK) == 0) then mob:setBehaviour(bit.bor(mob:getBehaviour(), BEHAVIOUR_STANDBACK)) mob:setMobMod(MOBMOD_TELEPORT_TYPE,1); mob:setMobMod(MOBMOD_SPAWN_LEASH,22); mob:setSpellList(39); end end; ----------------------------------- -- onMobDeath Action ----------------------------------- function onMobDeath(mob,killer,ally) end;
gpl-3.0
plajjan/snabbswitch
lib/luajit/src/jit/dump.lua
10
19964
---------------------------------------------------------------------------- -- LuaJIT compiler dump module. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module can be used to debug the JIT compiler itself. It dumps the -- code representations and structures used in various compiler stages. -- -- Example usage: -- -- luajit -jdump -e "local x=0; for i=1,1e6 do x=x+i end; print(x)" -- luajit -jdump=im -e "for i=1,1000 do for j=1,1000 do end end" | less -R -- luajit -jdump=is myapp.lua | less -R -- luajit -jdump=-b myapp.lua -- luajit -jdump=+aH,myapp.html myapp.lua -- luajit -jdump=ixT,myapp.dump myapp.lua -- -- The first argument specifies the dump mode. The second argument gives -- the output file name. Default output is to stdout, unless the environment -- variable LUAJIT_DUMPFILE is set. The file is overwritten every time the -- module is started. -- -- Different features can be turned on or off with the dump mode. If the -- mode starts with a '+', the following features are added to the default -- set of features; a '-' removes them. Otherwise the features are replaced. -- -- The following dump features are available (* marks the default): -- -- * t Print a line for each started, ended or aborted trace (see also -jv). -- * b Dump the traced bytecode. -- * i Dump the IR (intermediate representation). -- r Augment the IR with register/stack slots. -- s Dump the snapshot map. -- * m Dump the generated machine code. -- x Print each taken trace exit. -- X Print each taken trace exit and the contents of all registers. -- a Print the IR of aborted traces, too. -- -- The output format can be set with the following characters: -- -- T Plain text output. -- A ANSI-colored text output -- H Colorized HTML + CSS output. -- -- The default output format is plain text. It's set to ANSI-colored text -- if the COLORTERM variable is set. Note: this is independent of any output -- redirection, which is actually considered a feature. -- -- You probably want to use less -R to enjoy viewing ANSI-colored text from -- a pipe or a file. Add this to your ~/.bashrc: export LESS="-R" -- ------------------------------------------------------------------------------ -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local jutil = require("jit.util") local vmdef = require("jit.vmdef") local funcinfo, funcbc = jutil.funcinfo, jutil.funcbc local traceinfo, traceir, tracek = jutil.traceinfo, jutil.traceir, jutil.tracek local tracemc, tracesnap = jutil.tracemc, jutil.tracesnap local traceexitstub, ircalladdr = jutil.traceexitstub, jutil.ircalladdr local bit = require("bit") local band, shl, shr, tohex = bit.band, bit.lshift, bit.rshift, bit.tohex local sub, gsub, format = string.sub, string.gsub, string.format local byte, char, rep = string.byte, string.char, string.rep local type, tostring = type, tostring local stdout, stderr = io.stdout, io.stderr -- Load other modules on-demand. local bcline, disass -- Active flag, output file handle and dump mode. local active, out, dumpmode -- Information about traces that is remembered for future reference. local info = {} ------------------------------------------------------------------------------ local symtabmt = { __index = false } local symtab = {} local nexitsym = 0 -- Fill nested symbol table with per-trace exit stub addresses. local function fillsymtab_tr(tr, nexit) local t = {} symtabmt.__index = t if jit.arch == "mips" or jit.arch == "mipsel" then t[traceexitstub(tr, 0)] = "exit" return end for i=0,nexit-1 do local addr = traceexitstub(tr, i) if addr < 0 then addr = addr + 2^32 end t[addr] = tostring(i) end local addr = traceexitstub(tr, nexit) if addr then t[addr] = "stack_check" end end -- Fill symbol table with trace exit stub addresses. local function fillsymtab(tr, nexit) local t = symtab if nexitsym == 0 then local ircall = vmdef.ircall for i=0,#ircall do local addr = ircalladdr(i) if addr ~= 0 then if addr < 0 then addr = addr + 2^32 end t[addr] = ircall[i] end end end if nexitsym == 1000000 then -- Per-trace exit stubs. fillsymtab_tr(tr, nexit) elseif nexit > nexitsym then -- Shared exit stubs. for i=nexitsym,nexit-1 do local addr = traceexitstub(i) if addr == nil then -- Fall back to per-trace exit stubs. fillsymtab_tr(tr, nexit) setmetatable(symtab, symtabmt) nexit = 1000000 break end if addr < 0 then addr = addr + 2^32 end t[addr] = tostring(i) end nexitsym = nexit end return t end local function dumpwrite(s) out:write(s) end -- Disassemble machine code. local function dump_mcode(tr) local info = traceinfo(tr) if not info then return end local mcode, addr, loop = tracemc(tr) if not mcode then return end if not disass then disass = require("jit.dis_"..jit.arch) end if addr < 0 then addr = addr + 2^32 end out:write("---- TRACE ", tr, " mcode ", #mcode, "\n") local ctx = disass.create(mcode, addr, dumpwrite) ctx.hexdump = 0 ctx.symtab = fillsymtab(tr, info.nexit) if loop ~= 0 then symtab[addr+loop] = "LOOP" ctx:disass(0, loop) out:write("->LOOP:\n") ctx:disass(loop, #mcode-loop) symtab[addr+loop] = nil else ctx:disass(0, #mcode) end end ------------------------------------------------------------------------------ local irtype_text = { [0] = "nil", "fal", "tru", "lud", "str", "p32", "thr", "pro", "fun", "p64", "cdt", "tab", "udt", "flt", "num", "i8 ", "u8 ", "i16", "u16", "int", "u32", "i64", "u64", "sfp", } local colortype_ansi = { [0] = "%s", "%s", "%s", "\027[36m%s\027[m", "\027[32m%s\027[m", "%s", "\027[1m%s\027[m", "%s", "\027[1m%s\027[m", "%s", "\027[33m%s\027[m", "\027[31m%s\027[m", "\027[36m%s\027[m", "\027[34m%s\027[m", "\027[34m%s\027[m", "\027[35m%s\027[m", "\027[35m%s\027[m", "\027[35m%s\027[m", "\027[35m%s\027[m", "\027[35m%s\027[m", "\027[35m%s\027[m", "\027[35m%s\027[m", "\027[35m%s\027[m", "\027[35m%s\027[m", } local function colorize_text(s, t) return s end local function colorize_ansi(s, t) return format(colortype_ansi[t], s) end local irtype_ansi = setmetatable({}, { __index = function(tab, t) local s = colorize_ansi(irtype_text[t], t); tab[t] = s; return s; end }) local html_escape = { ["<"] = "&lt;", [">"] = "&gt;", ["&"] = "&amp;", } local function colorize_html(s, t) s = gsub(s, "[<>&]", html_escape) return format('<span class="irt_%s">%s</span>', irtype_text[t], s) end local irtype_html = setmetatable({}, { __index = function(tab, t) local s = colorize_html(irtype_text[t], t); tab[t] = s; return s; end }) local header_html = [[ <style type="text/css"> background { background: #ffffff; color: #000000; } pre.ljdump { font-size: 10pt; background: #f0f4ff; color: #000000; border: 1px solid #bfcfff; padding: 0.5em; margin-left: 2em; margin-right: 2em; } span.irt_str { color: #00a000; } span.irt_thr, span.irt_fun { color: #404040; font-weight: bold; } span.irt_tab { color: #c00000; } span.irt_udt, span.irt_lud { color: #00c0c0; } span.irt_num { color: #4040c0; } span.irt_int, span.irt_i8, span.irt_u8, span.irt_i16, span.irt_u16 { color: #b040b0; } </style> ]] local colorize, irtype -- Lookup tables to convert some literals into names. local litname = { ["SLOAD "] = setmetatable({}, { __index = function(t, mode) local s = "" if band(mode, 1) ~= 0 then s = s.."P" end if band(mode, 2) ~= 0 then s = s.."F" end if band(mode, 4) ~= 0 then s = s.."T" end if band(mode, 8) ~= 0 then s = s.."C" end if band(mode, 16) ~= 0 then s = s.."R" end if band(mode, 32) ~= 0 then s = s.."I" end t[mode] = s return s end}), ["XLOAD "] = { [0] = "", "R", "V", "RV", "U", "RU", "VU", "RVU", }, ["CONV "] = setmetatable({}, { __index = function(t, mode) local s = irtype[band(mode, 31)] s = irtype[band(shr(mode, 5), 31)].."."..s if band(mode, 0x800) ~= 0 then s = s.." sext" end local c = shr(mode, 14) if c == 2 then s = s.." index" elseif c == 3 then s = s.." check" end t[mode] = s return s end}), ["FLOAD "] = vmdef.irfield, ["FREF "] = vmdef.irfield, ["FPMATH"] = vmdef.irfpm, ["BUFHDR"] = { [0] = "RESET", "APPEND" }, ["TOSTR "] = { [0] = "INT", "NUM", "CHAR" }, } local function ctlsub(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" else return format("\\%03d", byte(c)) end end local function fmtfunc(func, pc) local fi = funcinfo(func, pc) if fi.loc then return fi.loc elseif fi.ffid then return vmdef.ffnames[fi.ffid] elseif fi.addr then return format("C:%x", fi.addr) else return "(?)" end end local function formatk(tr, idx) local k, t, slot = tracek(tr, idx) local tn = type(k) local s if tn == "number" then if k == 2^52+2^51 then s = "bias" else s = format("%+.14g", k) end elseif tn == "string" then s = format(#k > 20 and '"%.20s"~' or '"%s"', gsub(k, "%c", ctlsub)) elseif tn == "function" then s = fmtfunc(k) elseif tn == "table" then s = format("{%p}", k) elseif tn == "userdata" then if t == 12 then s = format("userdata:%p", k) else s = format("[%p]", k) if s == "[0x00000000]" then s = "NULL" end end elseif t == 21 then -- int64_t s = sub(tostring(k), 1, -3) if sub(s, 1, 1) ~= "-" then s = "+"..s end else s = tostring(k) -- For primitives. end s = colorize(format("%-4s", s), t) if slot then s = format("%s @%d", s, slot) end return s end local function printsnap(tr, snap) local n = 2 for s=0,snap[1]-1 do local sn = snap[n] if shr(sn, 24) == s then n = n + 1 local ref = band(sn, 0xffff) - 0x8000 -- REF_BIAS if ref < 0 then out:write(formatk(tr, ref)) elseif band(sn, 0x80000) ~= 0 then -- SNAP_SOFTFPNUM out:write(colorize(format("%04d/%04d", ref, ref+1), 14)) else local m, ot, op1, op2 = traceir(tr, ref) out:write(colorize(format("%04d", ref), band(ot, 31))) end out:write(band(sn, 0x10000) == 0 and " " or "|") -- SNAP_FRAME else out:write("---- ") end end out:write("]\n") end -- Dump snapshots (not interleaved with IR). local function dump_snap(tr) out:write("---- TRACE ", tr, " snapshots\n") for i=0,1000000000 do local snap = tracesnap(tr, i) if not snap then break end out:write(format("#%-3d %04d [ ", i, snap[0])) printsnap(tr, snap) end end -- Return a register name or stack slot for a rid/sp location. local function ridsp_name(ridsp, ins) if not disass then disass = require("jit.dis_"..jit.arch) end local rid, slot = band(ridsp, 0xff), shr(ridsp, 8) if rid == 253 or rid == 254 then return (slot == 0 or slot == 255) and " {sink" or format(" {%04d", ins-slot) end if ridsp > 255 then return format("[%x]", slot*4) end if rid < 128 then return disass.regname(rid) end return "" end -- Dump CALL* function ref and return optional ctype. local function dumpcallfunc(tr, ins) local ctype if ins > 0 then local m, ot, op1, op2 = traceir(tr, ins) if band(ot, 31) == 0 then -- nil type means CARG(func, ctype). ins = op1 ctype = formatk(tr, op2) end end if ins < 0 then out:write(format("[0x%x](", tonumber((tracek(tr, ins))))) else out:write(format("%04d (", ins)) end return ctype end -- Recursively gather CALL* args and dump them. local function dumpcallargs(tr, ins) if ins < 0 then out:write(formatk(tr, ins)) else local m, ot, op1, op2 = traceir(tr, ins) local oidx = 6*shr(ot, 8) local op = sub(vmdef.irnames, oidx+1, oidx+6) if op == "CARG " then dumpcallargs(tr, op1) if op2 < 0 then out:write(" ", formatk(tr, op2)) else out:write(" ", format("%04d", op2)) end else out:write(format("%04d", ins)) end end end -- Dump IR and interleaved snapshots. local function dump_ir(tr, dumpsnap, dumpreg) local info = traceinfo(tr) if not info then return end local nins = info.nins out:write("---- TRACE ", tr, " IR\n") local irnames = vmdef.irnames local snapref = 65536 local snap, snapno if dumpsnap then snap = tracesnap(tr, 0) snapref = snap[0] snapno = 0 end for ins=1,nins do if ins >= snapref then if dumpreg then out:write(format(".... SNAP #%-3d [ ", snapno)) else out:write(format(".... SNAP #%-3d [ ", snapno)) end printsnap(tr, snap) snapno = snapno + 1 snap = tracesnap(tr, snapno) snapref = snap and snap[0] or 65536 end local m, ot, op1, op2, ridsp = traceir(tr, ins) local oidx, t = 6*shr(ot, 8), band(ot, 31) local op = sub(irnames, oidx+1, oidx+6) if op == "LOOP " then if dumpreg then out:write(format("%04d ------------ LOOP ------------\n", ins)) else out:write(format("%04d ------ LOOP ------------\n", ins)) end elseif op ~= "NOP " and op ~= "CARG " and (dumpreg or op ~= "RENAME") then local rid = band(ridsp, 255) if dumpreg then out:write(format("%04d %-6s", ins, ridsp_name(ridsp, ins))) else out:write(format("%04d ", ins)) end out:write(format("%s%s %s %s ", (rid == 254 or rid == 253) and "}" or (band(ot, 128) == 0 and " " or ">"), band(ot, 64) == 0 and " " or "+", irtype[t], op)) local m1, m2 = band(m, 3), band(m, 3*4) if sub(op, 1, 4) == "CALL" then local ctype if m2 == 1*4 then -- op2 == IRMlit out:write(format("%-10s (", vmdef.ircall[op2])) else ctype = dumpcallfunc(tr, op2) end if op1 ~= -1 then dumpcallargs(tr, op1) end out:write(")") if ctype then out:write(" ctype ", ctype) end elseif op == "CNEW " and op2 == -1 then out:write(formatk(tr, op1)) elseif m1 ~= 3 then -- op1 != IRMnone if op1 < 0 then out:write(formatk(tr, op1)) else out:write(format(m1 == 0 and "%04d" or "#%-3d", op1)) end if m2 ~= 3*4 then -- op2 != IRMnone if m2 == 1*4 then -- op2 == IRMlit local litn = litname[op] if litn and litn[op2] then out:write(" ", litn[op2]) elseif op == "UREFO " or op == "UREFC " then out:write(format(" #%-3d", shr(op2, 8))) else out:write(format(" #%-3d", op2)) end elseif op2 < 0 then out:write(" ", formatk(tr, op2)) else out:write(format(" %04d", op2)) end end end out:write("\n") end end if snap then if dumpreg then out:write(format(".... SNAP #%-3d [ ", snapno)) else out:write(format(".... SNAP #%-3d [ ", snapno)) end printsnap(tr, snap) end end ------------------------------------------------------------------------------ local recprefix = "" local recdepth = 0 -- Format trace error message. local function fmterr(err, info) if type(err) == "number" then if type(info) == "function" then info = fmtfunc(info) end err = format(vmdef.traceerr[err], info) end return err end -- Dump trace states. local function dump_trace(what, tr, func, pc, otr, oex) if what == "stop" or (what == "abort" and dumpmode.a) then if dumpmode.i then dump_ir(tr, dumpmode.s, dumpmode.r and what == "stop") elseif dumpmode.s then dump_snap(tr) end if dumpmode.m then dump_mcode(tr) end end if what == "start" then info[tr] = { func = func, pc = pc, otr = otr, oex = oex } if dumpmode.H then out:write('<pre class="ljdump">\n') end out:write("---- TRACE ", tr, " ", what) if otr then out:write(" ", otr, "/", oex) end out:write(" ", fmtfunc(func, pc), "\n") elseif what == "stop" or what == "abort" then out:write("---- TRACE ", tr, " ", what) if what == "abort" then out:write(" ", fmtfunc(func, pc), " -- ", fmterr(otr, oex), "\n") else local info = traceinfo(tr) local link, ltype = info.link, info.linktype if link == tr or link == 0 then out:write(" -> ", ltype, "\n") elseif ltype == "root" then out:write(" -> ", link, "\n") else out:write(" -> ", link, " ", ltype, "\n") end end if dumpmode.H then out:write("</pre>\n\n") else out:write("\n") end else if what == "flush" then symtab, nexitsym = {}, 0 end out:write("---- TRACE ", what, "\n\n") end out:flush() end -- Dump recorded bytecode. local function dump_record(tr, func, pc, depth, callee) if depth ~= recdepth then recdepth = depth recprefix = rep(" .", depth) end local line if pc >= 0 then line = bcline(func, pc, recprefix) if dumpmode.H then line = gsub(line, "[<>&]", html_escape) end else line = "0000 "..recprefix.." FUNCC \n" callee = func end if pc <= 0 then out:write(sub(line, 1, -2), " ; ", fmtfunc(func), "\n") else out:write(line) end if pc >= 0 and band(funcbc(func, pc), 0xff) < 16 then -- ORDER BC out:write(bcline(func, pc+1, recprefix)) -- Write JMP for cond. end end ------------------------------------------------------------------------------ -- Dump taken trace exits. local function dump_texit(tr, ex, ngpr, nfpr, ...) out:write("---- TRACE ", tr, " exit ", ex, "\n") if dumpmode.X then local regs = {...} if jit.arch == "x64" then for i=1,ngpr do out:write(format(" %016x", regs[i])) if i % 4 == 0 then out:write("\n") end end else for i=1,ngpr do out:write(" ", tohex(regs[i])) if i % 8 == 0 then out:write("\n") end end end if jit.arch == "mips" or jit.arch == "mipsel" then for i=1,nfpr,2 do out:write(format(" %+17.14g", regs[ngpr+i])) if i % 8 == 7 then out:write("\n") end end else for i=1,nfpr do out:write(format(" %+17.14g", regs[ngpr+i])) if i % 4 == 0 then out:write("\n") end end end end end ------------------------------------------------------------------------------ -- Detach dump handlers. local function dumpoff() if active then active = false jit.attach(dump_texit) jit.attach(dump_record) jit.attach(dump_trace) if out and out ~= stdout and out ~= stderr then out:close() end out = nil end end -- Open the output file and attach dump handlers. local function dumpon(opt, outfile) if active then dumpoff() end local colormode = os.getenv("COLORTERM") and "A" or "T" if opt then opt = gsub(opt, "[TAH]", function(mode) colormode = mode; return ""; end) end local m = { t=true, b=true, i=true, m=true, } if opt and opt ~= "" then local o = sub(opt, 1, 1) if o ~= "+" and o ~= "-" then m = {} end for i=1,#opt do m[sub(opt, i, i)] = (o ~= "-") end end dumpmode = m if m.t or m.b or m.i or m.s or m.m then jit.attach(dump_trace, "trace") end if m.b then jit.attach(dump_record, "record") if not bcline then bcline = require("jit.bc").line end end if m.x or m.X then jit.attach(dump_texit, "texit") end if not outfile then outfile = os.getenv("LUAJIT_DUMPFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stdout end m[colormode] = true if colormode == "A" then colorize = colorize_ansi irtype = irtype_ansi elseif colormode == "H" then colorize = colorize_html irtype = irtype_html out:write(header_html) else colorize = colorize_text irtype = irtype_text end active = true end -- Public module functions. return { on = dumpon, off = dumpoff, start = dumpon, -- For -j command line option. info = info }
apache-2.0
nesstea/darkstar
scripts/globals/spells/bluemagic/blank_gaze.lua
26
1389
----------------------------------------- -- Spell: Blank Gaze -- Removes one beneficial magic effect from an enemy -- Spell cost: 25 MP -- Monster Type: Beasts -- Spell Type: Magical (Light) -- Blue Magic Points: 2 -- Stat Bonus: None -- Level: 38 -- Casting Time: 3 seconds -- Recast Time: 10 seconds -- Magic Bursts on: Transfixion, Fusion, Light -- Combos: None ----------------------------------------- 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 dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); local resist = applyResistance(caster,spell,target,dINT,BLUE_SKILL); local effect = EFFECT_NONE; if (resist > 0.0625) then if (target:isFacing(caster)) then spell:setMsg(341); effect = target:dispelStatusEffect(); if (effect == EFFECT_NONE) then spell:setMsg(75); end; else spell:setMsg(75); end; else spell:setMsg(85); end return effect; end;
gpl-3.0
hhrhhr/Lua-utils-for-X-Rebirth
lua/catdat_unpack.lua
1
2698
package.path = "./?.lua;./lua/?.lua" local cat = assert(arg[1], "[ERR ] no input filename") local dat = string.gsub(cat, "(.+)%.cat", "%1.dat") local out = arg[2] or "." local ffi = require("ffi") ffi.cdef[[ int _mkdir(const char *path); char * strerror (int errnum); ]] local function mkdir(path) local err = ffi.C._mkdir(path) if err ~= 0 then local errno = ffi.errno() -- '(17) file exists' is OK assert(errno == 17, "[ERR ] mkdir failed, errno (" .. errno .. "): " .. ffi.string(ffi.C.strerror(errno))) end end local files = {} io.write("[LOG ] open cat...\n") for line in io.lines(cat) do local p = {} for l in string.gmatch(line, "%g+") do table.insert(p, l) end local t = {} t.hash = table.remove(p) t.time = tonumber(table.remove(p)) t.size = tonumber(table.remove(p)) local name = table.concat(p, " ") t.path = {} for s in string.gmatch(name, "([^//]+)") do table.insert(t.path, s) end t.name = table.remove(t.path) table.insert(files, t) end io.write("[LOG ] " .. #files .. " lines readed\n") -- collect uniq dirs io.write("[LOG ] collect all paths...") local dirs = {} local count = 0 for k, v in ipairs(files) do local d = table.concat(v.path, "\\") if not dirs[d] then dirs[d] = true count = count + 1 end end local dirs_sorted = {} for k, v in pairs(dirs) do table.insert(dirs_sorted, k) end io.write(" " .. count .." paths parsed...") -- make directory tree dirs = {} count = 0 for k, v in ipairs(dirs_sorted) do local dir = {} for s in string.gmatch(v, "[^\\]+") do table.insert(dir, s) end for i, _ in ipairs(dir) do local str = "" str = table.concat(dir, "\\", 1, i) if not dirs[str] then dirs[str] = true count = count + 1 end end end io.write(" founded " .. count .. " unique paths...") -- sort list again dirs_sorted = {} for k, v in pairs(dirs) do table.insert(dirs_sorted, k) end table.sort(dirs_sorted) io.write(" and sorted\n") -- make directories print("[LOG ] making " .. #dirs_sorted .. " directories...") for k, v in ipairs(dirs_sorted) do mkdir(out .. "\\" .. v) end -- unpack print("[LOG ] unpacking...") local r = assert(io.open(dat, "rb")) count = #files for k, v in ipairs(files) do if v.size > 0 then local fullpath = table.concat(v.path, "\\") .. "\\" .. v.name io.write(string.format("(%d/%d) %s\n", k, count, fullpath)) local w = assert(io.open(out .. "\\" .. fullpath, "w+b")) local data = r:read(v.size) w:write(data) w:close() end end r:close()
gpl-3.0
nesstea/darkstar
scripts/zones/Gusgen_Mines/npcs/Grounds_Tome.lua
30
1091
----------------------------------- -- Area: Gusgen Mines -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_GUSGEN_MINES,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,679,680,681,682,683,684,685,686,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,679,680,681,682,683,684,685,686,0,0,GOV_MSG_GUSGEN_MINES); end;
gpl-3.0
Badboy30/badboy30
plugins/location.lua
625
1564
-- Implement a command !loc [area] which uses -- the static map API to get a location image -- Not sure if this is the proper way -- Intent: get_latlong is in time.lua, we need it here -- loadfile "time.lua" -- Globals -- If you have a google api key for the geocoding/timezone api do local api_key = nil local base_api = "https://maps.googleapis.com/maps/api" function get_staticmap(area) local api = base_api .. "/staticmap?" -- Get a sense of scale local lat,lng,acc,types = get_latlong(area) local scale = types[1] if scale=="locality" then zoom=8 elseif scale=="country" then zoom=4 else zoom = 13 end local parameters = "size=600x300" .. "&zoom=" .. zoom .. "&center=" .. URL.escape(area) .. "&markers=color:red"..URL.escape("|"..area) if api_key ~=nil and api_key ~= "" then parameters = parameters .. "&key="..api_key end return lat, lng, api..parameters end function run(msg, matches) local receiver = get_receiver(msg) local lat,lng,url = get_staticmap(matches[1]) -- Send the actual location, is a google maps link send_location(receiver, lat, lng, ok_cb, false) -- Send a picture of the map, which takes scale into account send_photo_from_url(receiver, url) -- Return a link to the google maps stuff is now not needed anymore return nil end return { description = "Gets information about a location, maplink and overview", usage = "!loc (location): Gets information about a location, maplink and overview", patterns = {"^!loc (.*)$"}, run = run } end
gpl-2.0
ennis/autograph-pipelines
resources/scripts/pl/path.lua
2
11785
--- Path manipulation and file queries. -- -- This is modelled after Python's os.path library (10.1); see @{04-paths.md|the Guide}. -- -- Dependencies: `pl.utils`, `lfs` -- @module pl.path -- imports and locals local _G = _G local sub = string.sub local getenv = os.getenv local tmpnam = os.tmpname local attributes, currentdir, link_attrib local package = package local io = io local append, concat, remove = table.insert, table.concat, table.remove local ipairs = ipairs local utils = require 'pl.utils' local assert_arg,assert_string,raise = utils.assert_arg,utils.assert_string,utils.raise local attrib local path = {} local res,lfs = _G.pcall(_G.require,'lfs') if res then attributes = lfs.attributes currentdir = lfs.currentdir link_attrib = lfs.symlinkattributes else error("pl.path requires LuaFileSystem") end attrib = attributes path.attrib = attrib path.link_attrib = link_attrib --- Lua iterator over the entries of a given directory. -- Behaves like `lfs.dir` path.dir = lfs.dir --- Creates a directory. path.mkdir = lfs.mkdir --- Removes a directory. path.rmdir = lfs.rmdir ---- Get the working directory. path.currentdir = currentdir --- Changes the working directory. path.chdir = lfs.chdir --- is this a directory? -- @string P A file path function path.isdir(P) assert_string(1,P) if P:match("\\$") then P = P:sub(1,-2) end return attrib(P,'mode') == 'directory' end --- is this a file?. -- @string P A file path function path.isfile(P) assert_string(1,P) return attrib(P,'mode') == 'file' end -- is this a symbolic link? -- @string P A file path function path.islink(P) assert_string(1,P) if link_attrib then return link_attrib(P,'mode')=='link' else return false end end --- return size of a file. -- @string P A file path function path.getsize(P) assert_string(1,P) return attrib(P,'size') end --- does a path exist?. -- @string P A file path -- @return the file path if it exists, nil otherwise function path.exists(P) assert_string(1,P) return attrib(P,'mode') ~= nil and P end --- Return the time of last access as the number of seconds since the epoch. -- @string P A file path function path.getatime(P) assert_string(1,P) return attrib(P,'access') end --- Return the time of last modification -- @string P A file path function path.getmtime(P) return attrib(P,'modification') end ---Return the system's ctime. -- @string P A file path function path.getctime(P) assert_string(1,P) return path.attrib(P,'change') end local function at(s,i) return sub(s,i,i) end path.is_windows = utils.dir_separator == '\\' local other_sep -- !constant sep is the directory separator for this platform. if path.is_windows then path.sep = '\\'; other_sep = '/' path.dirsep = ';' else path.sep = '/' path.dirsep = ':' end local sep,dirsep = path.sep,path.dirsep --- are we running Windows? -- @class field -- @name path.is_windows --- path separator for this platform. -- @class field -- @name path.sep --- separator for PATH for this platform -- @class field -- @name path.dirsep --- given a path, return the directory part and a file part. -- if there's no directory part, the first value will be empty -- @string P A file path function path.splitpath(P) assert_string(1,P) local i = #P local ch = at(P,i) while i > 0 and ch ~= sep and ch ~= other_sep do i = i - 1 ch = at(P,i) end if i == 0 then return '',P else return sub(P,1,i-1), sub(P,i+1) end end --- return an absolute path. -- @string P A file path -- @string[opt] pwd optional start path to use (default is current dir) function path.abspath(P,pwd) assert_string(1,P) if pwd then assert_string(2,pwd) end local use_pwd = pwd ~= nil if not use_pwd and not currentdir then return P end P = P:gsub('[\\/]$','') pwd = pwd or currentdir() if not path.isabs(P) then P = path.join(pwd,P) elseif path.is_windows and not use_pwd and at(P,2) ~= ':' and at(P,2) ~= '\\' then P = pwd:sub(1,2)..P -- attach current drive to path like '\\fred.txt' end return path.normpath(P) end --- given a path, return the root part and the extension part. -- if there's no extension part, the second value will be empty -- @string P A file path -- @treturn string root part -- @treturn string extension part (maybe empty) function path.splitext(P) assert_string(1,P) local i = #P local ch = at(P,i) while i > 0 and ch ~= '.' do if ch == sep or ch == other_sep then return P,'' end i = i - 1 ch = at(P,i) end if i == 0 then return P,'' else return sub(P,1,i-1),sub(P,i) end end --- return the directory part of a path -- @string P A file path function path.dirname(P) assert_string(1,P) local p1,p2 = path.splitpath(P) return p1 end --- return the file part of a path -- @string P A file path function path.basename(P) assert_string(1,P) local p1,p2 = path.splitpath(P) return p2 end --- get the extension part of a path. -- @string P A file path function path.extension(P) assert_string(1,P) local p1,p2 = path.splitext(P) return p2 end --- is this an absolute path?. -- @string P A file path function path.isabs(P) assert_string(1,P) if path.is_windows then return at(P,1) == '/' or at(P,1)=='\\' or at(P,2)==':' else return at(P,1) == '/' end end --- return the path resulting from combining the individual paths. -- if the second (or later) path is absolute, we return the last absolute path (joined with any non-absolute paths following). -- empty elements (except the last) will be ignored. -- @string p1 A file path -- @string p2 A file path -- @string ... more file paths function path.join(p1,p2,...) assert_string(1,p1) assert_string(2,p2) if select('#',...) > 0 then local p = path.join(p1,p2) local args = {...} for i = 1,#args do assert_string(i,args[i]) p = path.join(p,args[i]) end return p end if path.isabs(p2) then return p2 end local endc = at(p1,#p1) if endc ~= path.sep and endc ~= other_sep and endc ~= "" then p1 = p1..path.sep end return p1..p2 end --- normalize the case of a pathname. On Unix, this returns the path unchanged; -- for Windows, it converts the path to lowercase, and it also converts forward slashes -- to backward slashes. -- @string P A file path function path.normcase(P) assert_string(1,P) if path.is_windows then return (P:lower():gsub('/','\\')) else return P end end --- normalize a path name. -- A//B, A/./B and A/foo/../B all become A/B. -- @string P a file path function path.normpath(P) assert_string(1,P) -- Split path into anchor and relative path. local anchor = '' if path.is_windows then if P:match '^\\\\' then -- UNC anchor = '\\\\' P = P:sub(3) elseif at(P, 1) == '/' or at(P, 1) == '\\' then anchor = '\\' P = P:sub(2) elseif at(P, 2) == ':' then anchor = P:sub(1, 2) P = P:sub(3) if at(P, 1) == '/' or at(P, 1) == '\\' then anchor = anchor..'\\' P = P:sub(2) end end P = P:gsub('/','\\') else -- According to POSIX, in path start '//' and '/' are distinct, -- but '///+' is equivalent to '/'. if P:match '^//' and at(P, 3) ~= '/' then anchor = '//' P = P:sub(3) elseif at(P, 1) == '/' then anchor = '/' P = P:match '^/*(.*)$' end end local parts = {} for part in P:gmatch('[^'..sep..']+') do if part == '..' then if #parts ~= 0 and parts[#parts] ~= '..' then remove(parts) else append(parts, part) end elseif part ~= '.' then append(parts, part) end end P = anchor..concat(parts, sep) if P == '' then P = '.' end return P end local function ATS (P) if at(P,#P) ~= path.sep then P = P..path.sep end return path.normcase(P) end --- relative path from current directory or optional start point -- @string P a path -- @string[opt] start optional start point (default current directory) function path.relpath (P,start) assert_string(1,P) if start then assert_string(2,start) end local split,normcase,min,append = utils.split, path.normcase, math.min, table.insert P = normcase(path.abspath(P,start)) start = start or currentdir() start = normcase(start) local startl, Pl = split(start,sep), split(P,sep) local n = min(#startl,#Pl) if path.is_windows and n > 0 and at(Pl[1],2) == ':' and Pl[1] ~= startl[1] then return P end local k = n+1 -- default value if this loop doesn't bail out! for i = 1,n do if startl[i] ~= Pl[i] then k = i break end end local rell = {} for i = 1, #startl-k+1 do rell[i] = '..' end if k <= #Pl then for i = k,#Pl do append(rell,Pl[i]) end end return table.concat(rell,sep) end --- Replace a starting '~' with the user's home directory. -- In windows, if HOME isn't set, then USERPROFILE is used in preference to -- HOMEDRIVE HOMEPATH. This is guaranteed to be writeable on all versions of Windows. -- @string P A file path function path.expanduser(P) assert_string(1,P) if at(P,1) == '~' then local home = getenv('HOME') if not home then -- has to be Windows home = getenv 'USERPROFILE' or (getenv 'HOMEDRIVE' .. getenv 'HOMEPATH') end return home..sub(P,2) else return P end end ---Return a suitable full path to a new temporary file name. -- unlike os.tmpnam(), it always gives you a writeable path (uses TEMP environment variable on Windows) function path.tmpname () local res = tmpnam() -- On Windows if Lua is compiled using MSVC14 os.tmpname -- already returns an absolute path within TEMP env variable directory, -- no need to prepend it. if path.is_windows and not res:find(':') then res = getenv('TEMP')..res end return res end --- return the largest common prefix path of two paths. -- @string path1 a file path -- @string path2 a file path function path.common_prefix (path1,path2) assert_string(1,path1) assert_string(2,path2) path1, path2 = path.normcase(path1), path.normcase(path2) -- get them in order! if #path1 > #path2 then path2,path1 = path1,path2 end for i = 1,#path1 do local c1 = at(path1,i) if c1 ~= at(path2,i) then local cp = path1:sub(1,i-1) if at(path1,i-1) ~= sep then cp = path.dirname(cp) end return cp end end if at(path2,#path1+1) ~= sep then path1 = path.dirname(path1) end return path1 --return '' end --- return the full path where a particular Lua module would be found. -- Both package.path and package.cpath is searched, so the result may -- either be a Lua file or a shared library. -- @string mod name of the module -- @return on success: path of module, lua or binary -- @return on error: nil,error string function path.package_path(mod) assert_string(1,mod) local res mod = mod:gsub('%.',sep) res = package.searchpath(mod,package.path) if res then return res,true end res = package.searchpath(mod,package.cpath) if res then return res,false end return raise 'cannot find module on path' end ---- finis ----- return path
mit
UnfortunateFruit/darkstar
scripts/globals/items/sazanbaligi.lua
18
1259
----------------------------------------- -- ID: 5459 -- Item: Sazanbaligi -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 4 -- Mind -6 ----------------------------------------- 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,5459); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 4); target:addMod(MOD_MND, -6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 4); target:delMod(MOD_MND, -6); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Windurst_Woods/npcs/Soni-Muni.lua
34
2634
----------------------------------- -- Area: Windurst Woods -- NPC: Soni-Muni -- Starts & Finishes Quest: The Amazin' Scorpio -- @pos -17.073 1.749 -59.327 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local AmazinScorpio = player:getQuestStatus(WINDURST,THE_AMAZIN_SCORPIO); if (AmazinScorpio == QUEST_ACCEPTED) then local count = trade:getItemCount(); local ScorpionStinger = trade:hasItemQty(1017,1); if (ScorpionStinger == true and count == 1) then player:startEvent(0x01e4); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local AmazinScorpio = player:getQuestStatus(WINDURST,THE_AMAZIN_SCORPIO); local Fame = player:getFameLevel(WINDURST); local WildcatWindurst = player:getVar("WildcatWindurst"); if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,0) == false) then player:startEvent(0x02df); elseif (AmazinScorpio == QUEST_COMPLETED) then player:startEvent(0x01e5); elseif (AmazinScorpio == QUEST_ACCEPTED) then player:startEvent(0x01e2,0,0,1017); elseif (AmazinScorpio == QUEST_AVAILABLE and Fame >= 2) then player:startEvent(0x01e1,0,0,1017); else player:startEvent(0x01a5); 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 == 0x01e1) then player:addQuest(WINDURST,THE_AMAZIN_SCORPIO); elseif (csid == 0x01e4) then player:completeQuest(WINDURST,THE_AMAZIN_SCORPIO); player:addFame(WINDURST,WIN_FAME*80); player:addTitle(GREAT_GRAPPLER_SCORPIO); player:addGil(GIL_RATE*1500); player:messageSpecial(GIL_OBTAINED,GIL_RATE*1500); player:tradeComplete(); elseif (csid == 0x02df) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",0,true); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Port_Bastok/npcs/Ilita.lua
16
1204
----------------------------------- -- Area: Port Bastok -- NPC: Ilita -- Linkshell merchant -- @pos -142 -1 -25 236 -- Confirmed shop stock, August 2013 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:showText(npc,ILITA_SHOP_DIALOG,513); stock = { 0x0200, 8000, --Linkshell 0x3F9D, 375 --Pendant Compass } showShop(player, STATIC, 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
nesstea/darkstar
scripts/globals/items/ca_cuong.lua
18
1386
----------------------------------------- -- 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
hamed9898/maxbot
plugins/weather.lua
351
1443
do local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local function get_weather(location) print("Finding weather in ", location) local url = BASE_URL url = url..'?q='..location url = url..'&units=metric' local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'The temperature in '..city ..' (' ..country..')' ..' is '..weather.main.temp..'°C' local conditions = 'Current conditions are: ' .. weather.weather[1].description if weather.weather[1].main == 'Clear' then conditions = conditions .. ' ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. ' ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. ' ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. ' ☔☔☔☔' end return temp .. '\n' .. conditions end local function run(msg, matches) local city = 'Yogyakarta' if matches[1] ~= '!weather' then city = matches[1] end local text = get_weather(city) if not text then text = 'Can\'t get weather from that city.' end return text end return { description = "weather in that city (Yogyakarta is default)", usage = "!weather (city)", patterns = { "^!weather$", "^!weather (.*)$" }, run = run } end
gpl-2.0
UnfortunateFruit/darkstar
scripts/zones/Kazham/npcs/Rauteinot.lua
19
3016
----------------------------------- -- Area: Kazham -- NPC: Rauteinot -- Starts and Finishes Quest: Missionary Man -- @zone 250 -- @pos -42 -10 -89 ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getVar("MissionaryManVar") == 1 and trade:hasItemQty(1146,1) == true and trade:getItemCount() == 1) then player:startEvent(0x008b); -- Trading elshimo marble end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) MissionaryMan = player:getQuestStatus(OUTLANDS,MISSIONARY_MAN); MissionaryManVar = player:getVar("MissionaryManVar"); if(MissionaryMan == QUEST_AVAILABLE and player:getFameLevel(KAZHAM) >= 3) then player:startEvent(0x0089,0,1146); -- Start quest "Missionary Man" elseif(MissionaryMan == QUEST_ACCEPTED and MissionaryManVar == 1) then player:startEvent(0x008a,0,1146); -- During quest (before trade marble) "Missionary Man" elseif(MissionaryMan == QUEST_ACCEPTED and (MissionaryManVar == 2 or MissionaryManVar == 3)) then player:startEvent(0x008c); -- During quest (after trade marble) "Missionary Man" elseif(MissionaryMan == QUEST_ACCEPTED and MissionaryManVar == 4) then player:startEvent(0x008d); -- Finish quest "Missionary Man" elseif(MissionaryMan == QUEST_COMPLETED) then player:startEvent(0x008e); -- New standard dialog else player:startEvent(0x0088); -- 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 == 0x0089 and option == 1) then player:addQuest(OUTLANDS,MISSIONARY_MAN); player:setVar("MissionaryManVar",1); elseif(csid == 0x008b) then player:setVar("MissionaryManVar",2); player:addKeyItem(RAUTEINOTS_PARCEL); player:messageSpecial(KEYITEM_OBTAINED,RAUTEINOTS_PARCEL); player:tradeComplete(); elseif(csid == 0x008d) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4728); else player:setVar("MissionaryManVar",0); player:delKeyItem(SUBLIME_STATUE_OF_THE_GODDESS); player:addItem(4728); player:messageSpecial(ITEM_OBTAINED,4728); player:addFame(WINDURST,WIN_FAME*30); player:completeQuest(OUTLANDS,MISSIONARY_MAN); end end end;
gpl-3.0
nesstea/darkstar
scripts/globals/mobskills/Megaflare.lua
37
1832
--------------------------------------------- -- Megaflare -- Family: Bahamut -- Description: Deals heavy Fire damage to enemies within a fan-shaped area. -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: -- Notes: Used by Bahamut every 10% of its HP (except at 10%), but can use at will when under 10%. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobhp = mob:getHPP(); if (mobhp <= 10 and mob:getLocalVar("GigaFlare") ~= 0) then -- make sure Gigaflare has happened first - don't want a random Megaflare to block it. mob:setLocalVar("MegaFlareQueue", 1); -- set up Megaflare for being called by the script again. end; return 1; end; function onMobWeaponSkill(target, mob, skill) local MegaFlareQueue = mob:getLocalVar("MegaFlareQueue") - 1; -- decrement the amount of queued Megaflares. mob:setLocalVar("MegaFlareQueue", MegaFlareQueue); mob:setLocalVar("FlareWait", 0); -- reset the variables for Megaflare. mob:setLocalVar("tauntShown", 0); mob:SetMobAbilityEnabled(true); -- re-enable the other actions on success mob:SetMagicCastingEnabled(true); mob:SetAutoAttackEnabled(true); if (bit.band(mob:getBehaviour(),BEHAVIOUR_NO_TURN) == 0) then -- re-enable noturn mob:setBehaviour(bit.bor(mob:getBehaviour(), BEHAVIOUR_NO_TURN)) end; local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*10,ELE_FIRE,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_FIRE,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
nesstea/darkstar
scripts/zones/RuLude_Gardens/npcs/Goggehn.lua
13
3129
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: Goggehn -- Involved in Mission: Bastok 3-3, 4-1 -- @zone 243 -- @pos 3 9 -76 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; package.loaded["scripts/globals/missions"] = nil; ----------------------------------- require("scripts/globals/settings"); 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(); currentMission = player:getCurrentMission(BASTOK); missionStatus = player:getVar("MissionStatus"); if (currentMission == JEUNO_MISSION and missionStatus == 1) then player:startEvent(0x0029); elseif (currentMission == JEUNO_MISSION and missionStatus == 2) then player:startEvent(0x0042); elseif (currentMission == JEUNO_MISSION and missionStatus == 3) then player:startEvent(0x0026); elseif (player:getRank() == 4 and player:getCurrentMission(BASTOK) == 255 and getMissionRankPoints(player,13) == 1) then if (player:hasKeyItem(ARCHDUCAL_AUDIENCE_PERMIT)) then player:startEvent(0x0081,1); else player:startEvent(0x0081); -- Start Mission 4-1 Magicite end elseif (currentMission == MAGICITE_BASTOK and missionStatus == 1) then player:startEvent(0x0084); elseif (currentMission == MAGICITE_BASTOK and missionStatus <= 5) then player:startEvent(0x0087); elseif (currentMission == MAGICITE_BASTOK and missionStatus == 6) then player:startEvent(0x0023); elseif (player:hasKeyItem(MESSAGE_TO_JEUNO_BASTOK)) then player:startEvent(0x0037); elseif (pNation == WINDURST) then player:startEvent(0x0004); elseif (pNation == SANDORIA) then player:startEvent(0x0002); else player:startEvent(0x0065); 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 == 0x0029) then player:setVar("MissionStatus",2); player:delKeyItem(LETTER_TO_THE_AMBASSADOR); elseif (csid == 0x0081 and option == 1) then player:setVar("MissionStatus",1); if (player:hasKeyItem(ARCHDUCAL_AUDIENCE_PERMIT) == false) then player:addKeyItem(ARCHDUCAL_AUDIENCE_PERMIT); player:messageSpecial(KEYITEM_OBTAINED,ARCHDUCAL_AUDIENCE_PERMIT); end elseif (csid == 0x0026 or csid == 0x0023) then finishMissionTimeline(player,1,csid,option); end end;
gpl-3.0
dpino/snabbswitch
src/lib/xsd_regexp.lua
9
19197
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local maxpc = require("lib.maxpc") local match, capture, combine = maxpc.import() -- ASCII only implementation of regular expressions as defined in Appendix G of -- "W3C XML Schema Definition Language (XSD) 1.1 Part 2: Datatypes", see: -- -- https://www.w3.org/TR/xmlschema11-2/#regexs -- -- The main entry function `regexp.compile' accepts a regular expression -- string, and returns a predicate function that tests whether a string is part -- of the language defined by the expression. -- -- Example: -- local is_identifier = regexp.compile("[a-zA-Z][a-zA-Z0-9]*") -- is_identifier("Foo3") -> true -- is_identifier("7up") -> false -- -- It uses a combinatory parsing library (MaxPC) to parse a regular expression -- in the format defined by the specification referenced above, and compiles -- the denoted regular language to a MaxPC grammar. -- -- NYI: Block escapes, Unicode handling. function compile (expr) local ast = parse(expr) local parser = compile_branches(ast.branches, 'toplevel') return function (str) local _, success, eof = maxpc.parse(str, parser) return success and eof end end local regExp_parser -- forward definition function parse (expr) local result, success, is_eof = maxpc.parse(expr, regExp_parser) if not (success and is_eof) then error("Unable to parse regular expression: " .. expr) else return result end end -- Parser rules: string -> AST function capture.regExp () return capture.unpack( capture.seq(capture.branch(), combine.any(capture.otherBranch())), function (branch, otherBranches) local branches = {branch} for _, branch in ipairs(otherBranches or {}) do table.insert(branches, branch) end return {branches=branches} end ) end function capture.branch () return capture.transform(combine.any(capture.piece()), function (pieces) return {pieces=pieces} end) end function capture.otherBranch () return capture.unpack( capture.seq(match.equal("|"), capture.branch()), function (_, branch) return branch end ) end function capture.piece () return capture.unpack( capture.seq(capture.atom(), combine.maybe(capture.quantifier())), function (atom, quantifier) return {atom=atom, quantifier=quantifier or nil} end ) end function capture.quantifier () return combine._or( capture.subseq(match.equal("?")), capture.subseq(match.equal("*")), capture.subseq(match.equal("+")), capture.unpack( capture.seq(match.equal("{"), capture.quantity(), match.equal("}")), function (_, quantity, _) return quantity end ) ) end function capture.quantity () return combine._or( capture.quantRange(), capture.quantMin(), capture.transform(capture.quantExact(), function (n) return {exactly=n} end) ) end function capture.quantRange () return capture.unpack( capture.seq(capture.quantExact(), match.equal(","), capture.quantExact()), function (min, _, max) return {min=min, max=max} end ) end function capture.quantMin () return capture.unpack( capture.seq(capture.quantExact(), match.equal(",")), function (min, _) return {min=min} end ) end function capture.quantExact () return capture.transform( capture.subseq(combine.some(match.digit())), tonumber ) end function capture.atom () return combine._or( capture.NormalChar(), capture.charClass(), capture.subExp() ) end local function regExp_binding (s) return regExp_parser(s) end function capture.subExp () return capture.unpack( capture.seq(match.equal('('), regExp_binding, match.equal(')')), function (_, expression, _) return expression end ) end function match.MetaChar () return match.satisfies(function (s) return member(s, ".\\?*+{}()|[]") end) end function match.NormalChar (s) return match._not(match.MetaChar()) end function capture.NormalChar () return capture.subseq(match.NormalChar()) end function capture.charClass () return combine._or( capture.SingleCharEsc(), capture.charClassEsc(), capture.charClassExpr(), capture.WildcardEsc() ) end function capture.charClassExpr () return capture.unpack( capture.seq(match.equal("["), capture.charGroup(), match.equal("]")), function (_, charGroup, _) return charGroup end ) end function capture.charGroup () return capture.unpack( capture.seq( combine._or(capture.negCharGroup(), capture.posCharGroup()), combine.maybe(capture.charClassSubtraction()) ), function (group, subtract) return {group=group, subtract=subtract or nil} end ) end local charClassExpr_parser -- forward declaration local function charClassExpr_binding (s) return charClassExpr_parser(s) end function capture.charClassSubtraction () return capture.unpack( capture.seq(match.equal("-"), charClassExpr_binding), function (_, charClassExpr, _) return charClassExpr end ) end function capture.posCharGroup () return capture.transform( combine.some(capture.charGroupPart()), function (parts) return {include=parts} end ) end function capture.negCharGroup () return capture.unpack( capture.seq(match.equal("^"), capture.posCharGroup()), function (_, group) return {exclude=group.include} end ) end function capture.charGroupPart () return combine._or( capture.charClassEsc(), capture.charRange(), capture.singleChar() ) end function capture.singleChar () return combine._or(capture.SingleCharEsc(), capture.singleCharNoEsc()) end function capture.charRange () local rangeChar = combine.diff(capture.singleChar(), match.equal("-")) return capture.unpack( capture.seq(rangeChar, match.equal("-"), rangeChar), function (from, _, to) return {range={from,to}} end ) end function capture.singleCharNoEsc () local function is_singleCharNoEsc (s) return not member(s, "[]") end return combine.diff( capture.subseq(match.satisfies(is_singleCharNoEsc)), -- don’t match the "-" leading a character class subtraction match.seq(match.equal("-"), match.equal("[")) ) end function capture.charClassEsc () return combine._or( capture.MultiCharEsc(), capture.catEsc(), capture.complEsc() ) end function capture.SingleCharEsc () local function is_SingleCharEsc (s) return member(s, "nrt\\|.?*+(){}-[]^") end return capture.unpack( capture.seq( match.equal("\\"), capture.subseq(match.satisfies(is_SingleCharEsc)) ), function (_, char) return {escape=char} end ) end function capture.catEsc () return capture.unpack( capture.seq(match.equal("\\"), match.equal("p"), match.equal("{"), capture.charProp(), match.equal("}")), function (_, _, _, charProp, _) return {property=charProp} end ) end function capture.complEsc () return capture.unpack( capture.seq(match.equal("\\"), match.equal("P"), match.equal("{"), capture.charProp(), match.equal("}")), function (_, _, _, charProp, _) return {complement=charProp} end ) end function capture.charProp () local nameChars = "-0123456789abcdefghijklmnopqrstiuvwxyzABCDEFGHIJKLMNOPQRSTIUVWXYZ" local function is_name (s) return member(s, nameChars) end return capture.subseq(combine.some(match.satisfies(is_name))) end function capture.MultiCharEsc () local function is_multiCharEsc (s) return member(s, "sSiIcCdDwW") end return capture.unpack( capture.seq( match.equal("\\"), capture.subseq(match.satisfies(is_multiCharEsc)) ), function (_, char) return {escape=char} end ) end function capture.WildcardEsc () return capture.transform( match.equal("."), function (_) return {escape="."} end ) end regExp_parser = capture.regExp() charClassExpr_parser = capture.charClassExpr() -- Compiler rules: AST -> MaxPC parser function compile_branches (branches, is_toplevel) local parsers = {} for _, branch in ipairs(branches) do if branch.pieces then local parser = compile_pieces(branch.pieces) if is_toplevel then parser = match.path(parser, match.eof()) end table.insert(parsers, parser) end end if #parsers == 0 then return match.eof() elseif #parsers == 1 then return parsers[1] elseif #parsers > 1 then return match.either(unpack(parsers)) end end function compile_pieces (pieces) local parsers = {} for _, piece in ipairs(pieces) do local atom_parser = compile_atom(piece.atom) if piece.quantifier then local quanitify = compile_quantifier(piece.quantifier) table.insert(parsers, quanitify(atom_parser)) else table.insert(parsers, atom_parser) end end return match.path(unpack(parsers)) end function compile_quantifier (quantifier) if quantifier == "?" then return match.optional elseif quantifier == "*" then return match.all elseif quantifier == "+" then return match.one_or_more elseif quantifier.min or quantifier.max then return function (parser) return match.range(parser, quantifier.min, quantifier.max) end elseif quantifier.exactly then return function (parser) return match.exactly_n(parser, quantifier.exactly) end else error("Invalid quantifier") end end function match.one_or_more (parser) return match.path(parser, match.all(parser)) end function match.exactly_n (parser, n) local ps = {} for i = 1, n do table.insert(ps, parser) end return match.seq(unpack(ps)) end function match.upto_n (parser, n) local p = match.seq() for i = 1, n do p = match.optional(match.plus(parser, p)) end return p end function match.range (parser, min, max) if min and max then assert(min <= max, "Invalid quanitity: "..min.."-"..max) return match.path(match.exactly_n(parser, min), match.upto_n(parser, max - min)) elseif min then return match.path(match.exactly_n(parser, min), match.all(parser)) elseif max then return match.upto_n(parser, max) else return match.all(parser) end end function compile_atom (atom) local function is_special_escape (s) return member(s, "\\|.-^?*+{}()[]") end local function match_wildcard (s) return not member(s, "\n\r") end local function is_space (s) return member(s, " \t\n\r") end local function is_NameStartChar (s) return GC.L(s:byte()) or member(s, ":_") end local function is_NameChar (s) return is_NameStartChar(s) or GC.Nd(s:byte()) or member(s, "-.") end local function is_digit (s) return GC.Nd(s:byte()) end local function is_word (s) return not (GC.P(s:byte()) or GC.Z(s:byte()) or GC.C(s:byte())) end if type(atom) == 'string' then return match.equal(atom) elseif atom.escape == "n" then return match.equal("\n") elseif atom.escape == "r" then return match.equal("\r") elseif atom.escape == "t" then return match.equal("\t") elseif atom.escape and is_special_escape(atom.escape) then return match.equal(atom.escape) elseif atom.escape == "." then return match.satisfies(match_wildcard) elseif atom.escape == "s" then return match.satisfies(is_space) elseif atom.escape == "S" then return match._not(match.satisfies(is_space)) elseif atom.escape == "i" then return match.satisfies(is_NameStartChar) elseif atom.escape == "I" then return match._not(match.satisfies(is_NameStartChar)) elseif atom.escape == "c" then return match.satisfies(is_NameChar) elseif atom.escape == "C" then return match._not(match.satisfies(is_NameChar)) elseif atom.escape == "d" then return match.satisfies(is_digit) elseif atom.escape == "D" then return match._not(match.satisfies(is_digit)) elseif atom.escape == "w" then return match.satisfies(is_word) elseif atom.escape == "W" then return match._not(match.satisfies(is_word)) elseif atom.group then return compile_class(atom.group, atom.subtract) elseif atom.range then return compile_range(unpack(atom.range)) elseif atom.property then return compile_category(atom.property) elseif atom.complement then return match._not(compile_category(atom.complement)) elseif atom.branches then return compile_branches(atom.branches) else error("Invalid atom") end end function compile_class (group, subtract) if not subtract then return compile_group(group) else return combine.diff( compile_group(group), compile_class(subtract.group, subtract.subtract) ) end end function compile_group (group) local function compile_group_atoms (atoms) local parsers = {} for _, atom in ipairs(atoms) do table.insert(parsers, compile_atom(atom)) end return match.either(unpack(parsers)) end if group.include then return compile_group_atoms(group.include) elseif group.exclude then return match._not(compile_group_atoms(group.exclude)) else error("Invalid group") end end function compile_range (start, stop) start, stop = start:byte(), stop:byte() local function in_range (s) return start <= s:byte() and s:byte() <= stop end return match.satisfies(in_range) end function compile_category (name) local predicate = assert(GC[name], "Invalid category: "..name) return match.satisfies(function (s) return predicate(s:byte()) end) end -- General category predicates for ASCII local function empty_category (c) return false end GC = {} GC.Lu = function (c) return 65 <= c and c <= 90 end GC.Ll = function (c) return 97 <= c and c <= 122 end GC.Lt = empty_category GC.Lm = empty_category GC.Lo = empty_category GC.L = function (c) return GC.Lu(c) or GC.Ll(c) end GC.Mn = empty_category GC.Mc = empty_category GC.Me = empty_category GC.M = empty_category GC.Nd = function (c) return 48 <= c and c <= 57 end GC.Nl = empty_category GC.No = empty_category GC.N = GC.Nd GC.Pc = function (c) return c == 95 end GC.Pd = function (c) return c == 45 end GC.Ps = function (c) return c == 40 or c == 91 or c == 123 end GC.Pe = function (c) return c == 41 or c == 93 or c == 125 end GC.Pi = empty_category GC.Pf = empty_category GC.Po = function (c) return (33 <= c and c <= 35) or (37 <= c and c <= 39) or c == 42 or c == 44 or (46 <= c and c <= 47) or (58 <= c and c <= 59) or (63 <= c and c <= 64) or c == 92 end GC.P = function (c) return GC.Pc(c) or GC.Pd(c) or GC.Ps(c) or GC.Pe(c) or GC.Po(c) end GC.Sm = function (c) return c == 43 or (60 <= c and c <= 62) or c == 124 or c == 126 end GC.Sc = function (c) return c == 36 end GC.Sk = function (c) return c == 94 or c == 96 end GC.So = empty_category GC.S = function (c) return GC.Sm(c) or GC.Sc(c) end GC.Zs = function (c) return c == 32 end GC.Zl = empty_category GC.Zp = empty_category GC.Z = GC.Zs GC.Cc = function (c) return 0 <= c and c <= 31 end GC.Cf = empty_category GC.Cs = empty_category GC.Co = empty_category GC.Cn = empty_category GC.C = GC.Cc -- Utilities function member (element, set) return set:find(element, 1, true) end -- Tests local function test (o) local match = compile(o.regexp) for _, input in ipairs(o.accept) do assert(match(input), o.regexp .. " should match " .. input) end for _, input in ipairs(o.reject) do assert(not match(input), o.regexp .. " should not match " .. input) end end function selftest () test {regexp="[a-zA-Z][a-zA-Z0-9]*", accept={"Foo3", "baz"}, reject={"7Up", "123", "äöü", ""}} test {regexp="", accept={""}, reject={"foo"}} test {regexp="abc", accept={"abc"}, reject={"abcd", "0abc", ""}} test {regexp="a[bc]", accept={"ab", "ac"}, reject={"abcd", "0abc", "aa", ""}} test {regexp="\\n+", accept={"\n", "\n\n\n"}, reject={"", "\n\n\t", "\naa"}} test {regexp="(foo|bar)?", accept={"foo", "bar", ""}, reject={"foobar"}} test {regexp="foo|bar|baz", accept={"foo", "bar", "baz"}, reject={"", "fo"}} test {regexp="\\]", accept={"]"}, reject={"", "\\]"}} test {regexp="\\d{3,}", accept={"123", "45678910"}, reject={"", "12", "foo"}} test {regexp="[^\\d]{3,5}", accept={"foo", "....", ".-.-."}, reject={"", "foobar", "123", "4567", "45678"}} test {regexp="[abc-[ab]]{3}", accept={"ccc"}, reject={"", "abc"}} test {regexp="[\\p{L}]", accept={"A", "b", "y", "Z"}, reject={"0", "-", " "}} test {regexp="[\\P{L}]", accept={"0", "-", " "}, reject={"A", "b", "y", "Z"}} test {regexp="\\P{Ps}", accept={"}", "]", ")", "A", "b", "y", "Z", "0", "-", " "}, reject={"(", "[", "{"}} test {regexp="\\P{Ps}", accept={"}", "]", ")", "A", "b", "y", "Z", "0", "-", " "}, reject={"(", "[", "{"}} test {regexp="\\w", accept={"F", "0", "a", "~"}, reject={"-", " ", ".", "\t"}} test {regexp="\\i", accept={"a", "B", "_", ":"}, reject={"-", "1", " ", "."}} test {regexp="\\C", accept={"~", " ", "\t", "\n"}, reject={"a", "B", "1", ".", "_", ":"}} test {regexp="a|aa", accept={"a", "aa"}, reject={"ab", ""}} test{regexp="([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])", accept={"0","12", "123", "192","168","178",}, reject={"a.a.a.", ""}} test{regexp="(aa|aaa|bb)*", accept={"", "aa", "aaa", "aaaa", "aabb", "aaabb", "bb"}, reject={"a", "b", "bbb", "aaaab"}} local ipv4_address = "(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}" .. "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])" .. "(%[\\p{N}\\p{L}]+)?" test {regexp=ipv4_address, accept={"192.168.0.1", "8.8.8.8%eth0"}, reject={"1.256.8.8", "1.2.3%foo", "1.1.1.1%~"}} local domain_name = "((([a-zA-Z0-9_]([a-zA-Z0-9\\-_]){0,61})?[a-zA-Z0-9]\\.)*" .. "([a-zA-Z0-9_]([a-zA-Z0-9\\-_]){0,61})?[a-zA-Z0-9]\\.?)" .. "|\\." test {regexp=domain_name, accept={"hello", "foo-z.bar.de", "123.com", "."}, reject={"___.com", "foo-.baz.de", ".."}} end
apache-2.0
nesstea/darkstar
scripts/globals/items/lucky_egg.lua
18
1246
----------------------------------------- -- ID: 4600 -- Item: lucky_egg -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 14 -- Magic 14 -- Evasion 10 ----------------------------------------- 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,4600); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 14); target:addMod(MOD_MP, 14); target:addMod(MOD_EVA, 10); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 14); target:delMod(MOD_MP, 14); target:delMod(MOD_EVA, 10); end;
gpl-3.0
nesstea/darkstar
scripts/globals/spells/hojo_san.lua
27
1246
----------------------------------------- -- Spell: Hojo:San -- 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 30% reduction local power = 300; --Duration and Resistance calculation local duration = 420 * 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 >= 210) 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
UnfortunateFruit/darkstar
scripts/zones/Horlais_Peak/npcs/relic.lua
42
1839
----------------------------------- -- Area: Horlais Peak -- NPC: <this space intentionally left blank> -- @pos 450 -40 -31 139 ----------------------------------- package.loaded["scripts/zones/Horlais_Peak/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Horlais_Peak/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") == 18317 and trade:getItemCount() == 4 and trade:hasItemQty(18317,1) and trade:hasItemQty(1580,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1454,1)) then player:startEvent(13,18318); 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 == 13) then if (player:getFreeSlotsCount() < 2) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18318); player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1453); else player:tradeComplete(); player:addItem(18318); player:addItem(1453,30); player:messageSpecial(ITEM_OBTAINED,18318); player:messageSpecial(ITEMS_OBTAINED,1453,30); player:setVar("RELIC_IN_PROGRESS",0); end end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Kazham/npcs/Hozie_Naharaf.lua
15
1053
----------------------------------- -- Area: Kazham -- NPC: Hozie Naharaf -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("BathedInScent") == 1) then player:startEvent(0x00B3); -- scent from Blue Rafflesias else player:startEvent(0x0059); 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
nesstea/darkstar
scripts/zones/The_Garden_of_RuHmet/npcs/_0z0.lua
13
1897
----------------------------------- -- Area: The_Garden_of_RuHmet -- NPC: _0z0 ----------------------------------- package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/The_Garden_of_RuHmet/TextIDs"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/globals/bcnm"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --player:addMission(COP, WHEN_ANGELS_FALL); --player:setVar("PromathiaStatus",3); if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==3) then player:startEvent(0x00CB); elseif (EventTriggerBCNM(player,npc)) then elseif (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==5) then player:startEvent(0x00CD); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return 1; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if ( csid == 0x00CB) then player:setVar("PromathiaStatus",4); elseif (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Marquis_Orias.lua
19
1252
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Marquis Orias ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger"); if(mob:isInBattlefieldList() == false) then mob:addInBattlefieldList(); Animate_Trigger = Animate_Trigger + 16; SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger); if(Animate_Trigger == 32767) then SpawnMob(17330911); -- 142 SpawnMob(17330912); -- 143 SpawnMob(17330183); -- 177 SpawnMob(17330184); -- 178 activateAnimatedWeapon(); -- Change subanim of all animated weapon end end if(Animate_Trigger == 32767) then killer:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Sashosho.lua
34
1033
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Sashosho -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00FA); 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
dpino/snabbswitch
src/lib/protocol/ethernet.lua
12
3198
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") local header = require("lib.protocol.header") local ipv6 = require("lib.protocol.ipv6") local band = require("bit").band local ntohs, htons = lib.ntohs, lib.htons local mac_addr_t = ffi.typeof("uint8_t[6]") local ethernet = subClass(header) -- Class variables ethernet._name = "ethernet" ethernet._ulp = { class_map = { [0x0800] = "lib.protocol.ipv4", [0x86dd] = "lib.protocol.ipv6", }, method = 'type' } ethernet:init( { [1] = ffi.typeof[[ struct { uint8_t ether_dhost[6]; uint8_t ether_shost[6]; uint16_t ether_type; } __attribute__((packed)) ]] }) -- Class methods function ethernet:new (config) local o = ethernet:superClass().new(self) o:dst(config.dst) o:src(config.src) o:type(config.type) return o end -- Convert printable address to numeric function ethernet:pton (p) local result = mac_addr_t() local i = 0 for v in p:split(":") do if string.match(v, '^%x%x$') then result[i] = tonumber("0x"..v) else error("invalid mac address "..p) end i = i+1 end assert(i == 6, "invalid mac address "..p) return result end -- Convert numeric address to printable function ethernet:ntop (n) local p = {} for i = 0, 5, 1 do table.insert(p, string.format("%02x", n[i])) end return table.concat(p, ":") end -- Mapping of an IPv6 multicast address to a MAC address per RFC2464, -- section 7 function ethernet:ipv6_mcast(ip) local result = self:pton("33:33:00:00:00:00") local n = ffi.cast("uint8_t *", ip) assert(n[0] == 0xff, "invalid multiast address: "..ipv6:ntop(ip)) ffi.copy(ffi.cast("uint8_t *", result)+2, n+12, 4) return result end -- Check whether a MAC address has its group bit set function ethernet:is_mcast (addr) return band(addr[0], 0x01) ~= 0 end local bcast_address = ethernet:pton("FF:FF:FF:FF:FF:FF") -- Check whether a MAC address is the broadcast address function ethernet:is_bcast (addr) return C.memcmp(addr, bcast_address, 6) == 0 end -- Instance methods function ethernet:src (a) local h = self:header() if a ~= nil then ffi.copy(h.ether_shost, a, 6) else return h.ether_shost end end function ethernet:src_eq (a) return C.memcmp(a, self:header().ether_shost, 6) == 0 end function ethernet:dst (a) local h = self:header() if a ~= nil then ffi.copy(h.ether_dhost, a, 6) else return h.ether_dhost end end function ethernet:dst_eq (a) return C.memcmp(a, self:header().ether_dhost, 6) == 0 end function ethernet:swap () local tmp = mac_addr_t() local h = self:header() ffi.copy(tmp, h.ether_dhost, 6) ffi.copy(h.ether_dhost, h.ether_shost,6) ffi.copy(h.ether_shost, tmp, 6) end function ethernet:type (t) local h = self:header() if t ~= nil then h.ether_type = htons(t) else return(ntohs(h.ether_type)) end end return ethernet
apache-2.0
nesstea/darkstar
scripts/globals/items/pixie_mace.lua
41
1075
----------------------------------------- -- ID: 17414 -- Item: Pixie Mace -- Additional Effect: Light Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(4,11); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0); dmg = adjustForTarget(target,dmg,ELE_LIGHT); dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_LIGHT_DAMAGE,message,dmg; end end;
gpl-3.0
NezzKryptic/Wire-Extras
lua/entities/gmod_wire_useholoemitter/cl_init.lua
1
6714
include( "shared.lua" ); CreateClientConVar("cl_wire_holoemitter_minfaderate",10,true,false); // mats local matbeam = Material( "tripmine_laser" ); local matpoint = Material( "sprites/gmdm_pickups/light" ); // init function ENT:Initialize( ) // point list self.PointList = {}; self.LastClear = self:GetNetworkedBool("Clear"); // active point self.ActivePoint = Vector( 0, 0, 0 ); // boundry. self.RBound = Vector(1024,1024,1024) end // calculate point function ENT:CalculatePixelPoint( pos, emitterPos, fwd, right, up ) // calculate point return emitterPos + ( up * pos.z ) + ( fwd * pos.x ) + ( right * pos.y ); end // think function ENT:Think( ) // read point. local point = Vector( self:GetNetworkedFloat( "X" ), self:GetNetworkedFloat( "Y" ), self:GetNetworkedFloat( "Z" ) ); lastclear = self:GetNetworkedInt("Clear") if(lastclear != self.LastClear) then self.PointList = {} self.LastClear = lastclear end -- To make it visible across the entire map local p = LocalPlayer():GetPos() self:SetRenderBoundsWS( p - self.RBound, p + self.RBound ) // did the point differ from active point? if( point != self.ActivePoint && self:GetNetworkedBool( "Active" ) ) then // fetch color. local a = self:GetColor().a; // store this point inside the point list local tempfaderate if (game.SinglePlayer()) then tempfaderate = math.Clamp( self:GetNetworkedFloat( "FadeRate" ), 0.1, 255 ) else -- Due to a request, in Multiplayer, the people can controle this with a CL side cvar (aVoN) local minfaderate = GetConVarNumber("cl_wire_holoemitter_minfaderate") or 10; tempfaderate = math.Clamp( self:GetNetworkedFloat( "FadeRate" ),minfaderate, 255 ) end table.insert( self.PointList, { pos = self.ActivePoint, alpha = a, faderate = tempfaderate } ); // store new active point self.ActivePoint = point; end end // draw function ENT:Draw( ) // render model self:DrawModel(); // are we rendering? if( !self:GetNetworkedBool( "Active" ) ) then return; end // read emitter. local emitter = self:GetNetworkedEntity( "grid" ); if( !emitter || !emitter:IsValid() ) then return; end // calculate emitter position. local fwd = emitter:GetForward(); local right = emitter:GetRight(); local up = emitter:GetUp(); local pos = emitter:GetPos() + up * 64; local usegps = emitter:GetNetworkedBool( "UseGPS" ) // draw beam? local drawbeam = self:GetNetworkedBool( "ShowBeam" ); local groundbeam = self:GetNetworkedBool( "GroundBeam" ); // read point size local size = self:GetNetworkedFloat( "PointSize" ); local beamsize = size * 0.25; // read color local color = self:GetColor(); // calculate pixel point. local pixelpos if (usegps == true) then pixelpos = self.ActivePoint; else pixelpos = self:CalculatePixelPoint( self.ActivePoint, pos, fwd, right, up ); end // draw active point - beam if( drawbeam && groundbeam) then render.SetMaterial( matbeam ); render.DrawBeam( self:GetPos(), pixelpos, beamsize, 0, 1, color ); end // draw active point - sprite render.SetMaterial( matpoint ); render.DrawSprite( pixelpos, size, size, color ); // draw fading points. local point, lastpos, i = nil, pixelpos; local newlist = {} for i = table.getn( self.PointList ), 1, -1 do // easy access local point = self.PointList[i]; // I'm doing this here, to remove that extra loop in ENT:Think. // fade away point.alpha = point.alpha - point.faderate * FrameTime(); // die? if( point.alpha <= 0 ) then table.remove( self.PointList, i ); else table.insert( newlist, { pos = point.pos, alpha = point.alpha, faderate = point.faderate } ); // calculate pixel point. local pixelpos if (usegps == true) then pixelpos = point.pos else pixelpos = self:CalculatePixelPoint( point.pos, pos, fwd, right, up ); end // calculate color. local color = Color( r, g, b, point.alpha ); // draw active point - beam if( drawbeam ) then if (groundbeam) then render.SetMaterial( matbeam ); render.DrawBeam( self:GetPos(), pixelpos, beamsize, 0, 1, color ); end render.SetMaterial( matbeam ) render.DrawBeam( lastpos, pixelpos, beamsize * 2, 0, 1, color ); lastpos = pixelpos; end // draw active point - sprite render.SetMaterial( matpoint ); render.DrawSprite( pixelpos, size, size, color ); end end self.PointList = newlist end function Player_EyeAngle(ply) EyeTrace = ply:GetEyeTrace() StartPos = EyeTrace.StartPos EndPos = EyeTrace.HitPos Distance = StartPos:Distance(EndPos) Temp = EndPos - StartPos return Temp:Angle() end local function HoloPressCheck( ply, key ) if (key == IN_USE) then ply_EyeAng = Player_EyeAngle(ply) ply_EyeTrace = ply:GetEyeTrace() ply_EyePos = ply_EyeTrace.StartPos emitters = ents.FindByClass("gmod_wire_useholoemitter") if (#emitters > 0) then local ShortestDistance = 200 local LastX = 0 local LastY = 0 local LastZ = 0 local LastEnt = 0 for _,v in ipairs( emitters ) do local emitter = v.Entity:GetNetworkedEntity( "grid" ); if (v.Entity:GetNetworkedBool( "Active" )) then local fwd = emitter:GetForward(); local right = emitter:GetRight(); local up = emitter:GetUp(); local pos = emitter:GetPos() + (up*64) count = table.getn( v.PointList ) for i = count,1,-1 do point = v.PointList[i]; if (v.Entity:GetNetworkedBool( "UseGPS" )) then pixelpos = point.pos else pixelpos = v:CalculatePixelPoint( point.pos, pos, fwd, right, up ); end ObjPos = Vector(pixelpos.x,pixelpos.y,pixelpos.z) AbsDist = ply_EyePos:Distance(ObjPos) if (AbsDist <= ShortestDistance) then TempPos = ObjPos - ply_EyePos AbsAng = TempPos:Angle() PitchDiff = math.abs(AbsAng.p - ply_EyeAng.p) YawDiff = math.abs(AbsAng.y - ply_EyeAng.y) if (YawDiff <= 5 && PitchDiff <= 5) then ShortestDistance = AbsDist LastX = point.pos.x LastY = point.pos.y LastZ = point.pos.z LastEnt = v:EntIndex() end end end end end if (LastEnt > 0) then RunConsoleCommand("HoloInteract",LastEnt,LastX,LastY,LastZ) end end end end hook.Add( "KeyPress", "HoloPress", HoloPressCheck )
gpl-3.0
FailcoderAddons/supervillain-ui
SVUI_!Core/libs/AceVillain-1.0/widgets/AceGUIWidget-CheckBox.lua
2
8211
--[[----------------------------------------------------------------------------- Checkbox Widget -------------------------------------------------------------------------------]] local Type, Version = "CheckBox", 999999 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local select, pairs = select, pairs -- WoW APIs local PlaySound = PlaySound local CreateFrame, UIParent = CreateFrame, UIParent -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: SetDesaturation, GameFontHighlight --[[----------------------------------------------------------------------------- Support functions -------------------------------------------------------------------------------]] local function AlignImage(self) local img = self.image:GetTexture() self.text:ClearAllPoints() if not img then self.text:SetPoint("LEFT", self.checkbg, "RIGHT") self.text:SetPoint("RIGHT") else self.text:SetPoint("LEFT", self.image,"RIGHT", 1, 0) self.text:SetPoint("RIGHT") end end --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function Control_OnEnter(frame) frame.obj:Fire("OnEnter") end local function Control_OnLeave(frame) frame.obj:Fire("OnLeave") end local function CheckBox_OnMouseDown(frame) local self = frame.obj if not self.disabled then if self.image:GetTexture() then self.text:SetPoint("LEFT", self.image,"RIGHT", 2, -1) else self.text:SetPoint("LEFT", self.checkbg, "RIGHT", 1, -1) end end AceGUI:ClearFocus() end local function CheckBox_OnMouseUp(frame) local self = frame.obj if not self.disabled then self:ToggleChecked() if self.checked then PlaySound(PlaySoundKitID and "igMainMenuOptionCheckBoxOn" or 856) else -- for both nil and false (tristate) PlaySound(PlaySoundKitID and "igMainMenuOptionCheckBoxOff" or 857) end self:Fire("OnValueChanged", self.checked) AlignImage(self) end end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self:SetType() self:SetValue(false) self:SetTriState(nil) -- height is calculated from the width and required space for the description self:SetWidth(320) self:SetImage() self:SetDisabled(nil) self:SetDescription(nil) end, -- ["OnRelease"] = nil, ["OnWidthSet"] = function(self, width) if self.desc then self.desc:SetWidth(width - 30) if self.desc:GetText() and self.desc:GetText() ~= "" then self:SetHeight(28 + self.desc:GetHeight()) end end end, ["SetDisabled"] = function(self, disabled) self.disabled = disabled if disabled then self.frame:Disable() self.text:SetTextColor(0.5, 0.5, 0.5) SetDesaturation(self.check, true) if self.desc then self.desc:SetTextColor(0.5, 0.5, 0.5) end else self.frame:Enable() self.text:SetTextColor(1, 1, 1) if self.tristate and self.checked == nil then SetDesaturation(self.check, true) else SetDesaturation(self.check, false) end if self.desc then self.desc:SetTextColor(1, 1, 1) end end end, ["SetValue"] = function(self,value) local check = self.check self.checked = value if value then SetDesaturation(self.check, false) self.check:Show() else --Nil is the unknown tristate value if self.tristate and value == nil then SetDesaturation(self.check, true) self.check:Show() else SetDesaturation(self.check, false) self.check:Hide() end end self:SetDisabled(self.disabled) end, ["GetValue"] = function(self) return self.checked end, ["SetTriState"] = function(self, enabled) self.tristate = enabled self:SetValue(self:GetValue()) end, ["SetType"] = function(self, type) local checkbg = self.checkbg local check = self.check local highlight = self.highlight local size if type == "radio" then size = 16 checkbg:SetTexture([[Interface\AddOns\SVUI_!Core\assets\buttons\RADIO]]) checkbg:SetTexCoord(0, 0.25, 0, 1) check:SetTexture([[Interface\AddOns\SVUI_!Core\assets\buttons\RADIO]]) check:SetTexCoord(0.25, 0.5, 0, 1) check:SetBlendMode("ADD") highlight:SetTexture([[Interface\AddOns\SVUI_!Core\assets\buttons\RADIO]]) highlight:SetTexCoord(0.5, 0.75, 0, 1) else size = 18 checkbg:SetTexture([[Interface\AddOns\SVUI_!Core\assets\buttons\CHECK-BG]]) checkbg:SetTexCoord(0, 1, 0, 1) check:SetTexture([[Interface\AddOns\SVUI_!Core\assets\buttons\CHECK]]) check:SetTexCoord(0, 1, 0, 1) check:SetBlendMode("BLEND") highlight:SetTexture([[Interface\AddOns\SVUI_!Core\assets\buttons\CHECK]]) highlight:SetTexCoord(0, 1, 0, 1) end checkbg:SetHeight(size) checkbg:SetWidth(size) end, ["SetPlusMinus"] = function(self, enabled) self.plusminus = enabled self:SetType() end, ["ToggleChecked"] = function(self) local value = self:GetValue() if self.tristate then --cycle in true, nil, false order if value then self:SetValue(nil) elseif value == nil then self:SetValue(false) else self:SetValue(true) end else self:SetValue(not self:GetValue()) end end, ["SetLabel"] = function(self, label) self.text:SetText(label) end, ["SetDescription"] = function(self, desc) if desc then if not self.desc then local desc = self.frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") desc:ClearAllPoints() desc:SetPoint("TOPLEFT", self.checkbg, "TOPRIGHT", 5, -21) desc:SetWidth(self.frame.width - 30) desc:SetJustifyH("LEFT") desc:SetJustifyV("TOP") self.desc = desc end self.desc:Show() --self.text:SetFontObject(GameFontNormal) self.desc:SetText(desc) self:SetHeight(28 + self.desc:GetHeight()) else if self.desc then self.desc:SetText("") self.desc:Hide() end --self.text:SetFontObject(GameFontHighlight) self:SetHeight(24) end end, ["SetImage"] = function(self, path, ...) local image = self.image image:SetTexture(path) if image:GetTexture() then local n = select("#", ...) if n == 4 or n == 8 then image:SetTexCoord(...) else image:SetTexCoord(0, 1, 0, 1) end end AlignImage(self) end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local frame = CreateFrame("Button", nil, UIParent) frame:Hide() frame:EnableMouse(true) frame:SetScript("OnEnter", Control_OnEnter) frame:SetScript("OnLeave", Control_OnLeave) frame:SetScript("OnMouseDown", CheckBox_OnMouseDown) frame:SetScript("OnMouseUp", CheckBox_OnMouseUp) local checkbg = frame:CreateTexture(nil, "ARTWORK") checkbg:SetWidth(18) checkbg:SetHeight(18) checkbg:SetPoint("TOPLEFT") checkbg:SetTexture([[Interface\AddOns\SVUI_!Core\assets\buttons\CHECK-BG]]) local check = frame:CreateTexture(nil, "OVERLAY") check:SetAllPoints(checkbg) check:SetTexture([[Interface\AddOns\SVUI_!Core\assets\buttons\CHECK]]) local text = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlight") text:SetJustifyH("LEFT") text:SetHeight(18) text:SetPoint("LEFT", checkbg, "RIGHT") text:SetPoint("RIGHT") local highlight = frame:CreateTexture(nil, "HIGHLIGHT") highlight:SetTexture([[Interface\AddOns\SVUI_!Core\assets\buttons\CHECK]]) highlight:SetBlendMode("ADD") highlight:SetAllPoints(checkbg) local image = frame:CreateTexture(nil, "OVERLAY") image:SetHeight(16) image:SetWidth(16) image:SetPoint("LEFT", checkbg, "RIGHT", 1, 0) local widget = { checkbg = checkbg, check = check, text = text, highlight = highlight, image = image, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
mit
UnfortunateFruit/darkstar
scripts/zones/Bastok_Markets/npcs/Reinberta.lua
42
2151
----------------------------------- -- Area: Bastok Markets -- NPC: Reinberta -- Type: Goldsmithing Guild Master -- @pos -190.605 -7.814 -59.432 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local newRank = tradeTestItem(player,npc,trade,SKILL_GOLDSMITHING); if (newRank ~= 0) then player:setSkillRank(SKILL_GOLDSMITHING,newRank); player:startEvent(0x012d,0,0,0,0,newRank); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local getNewRank = 0; local craftSkill = player:getSkillLevel(SKILL_GOLDSMITHING); local testItem = getTestItem(player,npc,SKILL_GOLDSMITHING); local guildMember = isGuildMember(player,6); if (guildMember == 1) then guildMember = 150995375; end if (canGetNewRank(player,craftSkill,SKILL_GOLDSMITHING) == 1) then getNewRank = 100; end player:startEvent(0x012c,testItem,getNewRank,30,guildMember,44,0,0,0); end; -- 0x012c 0x012d 0x0192 ----------------------------------- -- 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 == 0x012c and option == 1) then local crystal = math.random(4096,4101); if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal); else player:addItem(crystal); player:messageSpecial(ITEM_OBTAINED,crystal); signupGuild(player, SKILL_GOLDSMITHING); end end end;
gpl-3.0
hussian/hell_iraq
plugins/rebot.lua
8
1029
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY(@AHMED_ALOBIDE) ▀▄ ▄▀ ▀▄ ▄▀ BY(@hussian_9) ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ملف الترحيب ع خاص البوت ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do local function run(msg, matches) if ( msg.text ) then if ( msg.to.type == "user" ) then return "- Welcome to LAND💫 OF💫 HELL !\n\n- للمعلومات او الاستفسار على اليوزرات \n\n- 💠DEV : @AHMED_ALOBIDE \n\n- 💠DEV : @hussian_9 " end end end return { patterns = { "(.*)$" }, run = run } end
gpl-2.0
D3luxe/Dota-2-Building-Helper
game/dota_addons/samplerts/scripts/vscripts/buildings/upgrades.lua
5
4115
--[[ Replaces the building to the upgraded unit name ]]-- function UpgradeBuilding( event ) local caster = event.caster local new_unit = event.UnitName local position = caster:GetAbsOrigin() local hero = caster:GetPlayerOwner():GetAssignedHero() local playerID = hero:GetPlayerID() local player = PlayerResource:GetPlayer(playerID) local currentHealthPercentage = caster:GetHealthPercent() * 0.01 -- Keep the gridnav blockers and orientation local blockers = caster.blockers local angle = caster:GetAngles() -- New building local building = BuildingHelper:PlaceBuilding(player, new_unit, position, false, 0) building.blockers = blockers building:SetAngles(0, -angle.y, 0) -- If the building to ugprade is selected, change the selection to the new one if IsCurrentlySelected(caster) then AddUnitToSelection(building) end -- Remove the old building from the structures list if IsValidEntity(caster) then local buildingIndex = getIndex(player.structures, caster) table.remove(player.structures, buildingIndex) -- Remove old building entity caster:RemoveSelf() end local newRelativeHP = building:GetMaxHealth() * currentHealthPercentage if newRelativeHP == 0 then newRelativeHP = 1 end --just incase rounding goes wrong building:SetHealth(newRelativeHP) -- Add 1 to the buildings list for that name. The old name still remains if not player.buildings[new_unit] then player.buildings[new_unit] = 1 else player.buildings[new_unit] = player.buildings[new_unit] + 1 end -- Add the new building to the structures list table.insert(player.structures, building) -- Update the abilities of the units and structures for k,unit in pairs(player.units) do CheckAbilityRequirements( unit, player ) end for k,structure in pairs(player.structures) do CheckAbilityRequirements( structure, player ) end end --[[ Disable any queue-able ability that the building could have, because the caster will be removed when the channel ends A modifier from the ability can also be passed here to attach particle effects ]]-- function StartUpgrade( event ) local caster = event.caster local ability = event.ability local modifier_name = event.ModifierName local abilities = {} -- Check to not disable when the queue was full if #caster.queue < 5 then -- Iterate through abilities marking those to disable for i=0,15 do local abil = caster:GetAbilityByIndex(i) if abil then local ability_name = abil:GetName() -- Abilities to hide can be filtered to include the strings train_ and research_, and keep the rest available --if string.match(ability_name, "train_") or string.match(ability_name, "research_") then table.insert(abilities, abil) --end end end -- Keep the references to enable if the upgrade gets canceled caster.disabled_abilities = abilities for k,disable_ability in pairs(abilities) do disable_ability:SetHidden(true) end -- Pass a modifier with particle(s) of choice to show that the building is upgrading. Remove it on CancelUpgrade if modifier_name then ability:ApplyDataDrivenModifier(caster, caster, modifier_name, {}) caster.upgrade_modifier = modifier_name end end local hero = caster:GetPlayerOwner():GetAssignedHero() local playerID = hero:GetPlayerID() FireGameEvent( 'ability_values_force_check', { player_ID = playerID }) end --[[ Replaces the building to the upgraded unit name ]]-- function CancelUpgrade( event ) local caster = event.caster local abilities = caster.disabled_abilities for k,ability in pairs(abilities) do ability:SetHidden(false) end local upgrade_modifier = caster.upgrade_modifier if upgrade_modifier and caster:HasModifier(upgrade_modifier) then caster:RemoveModifierByName(upgrade_modifier) end local hero = caster:GetPlayerOwner():GetAssignedHero() local playerID = hero:GetPlayerID() FireGameEvent( 'ability_values_force_check', { player_ID = playerID }) end -- Forces an ability to level 0 function SetLevel0( event ) local ability = event.ability if ability:GetLevel() == 1 then ability:SetLevel(0) end end
gpl-3.0
Sravan2j/DIGITS
digits/standard-networks/torch/ImageNet-Training/alexnet.lua
1
1671
-- Copyright (c) 2015 Elad Hoffer require 'cudnn' require 'cunn' require 'ccn2' local SpatialConvolution = nn.SpatialConvolutionMM--lib[1] local SpatialMaxPooling = cudnn.SpatialMaxPooling--lib[2] local ReLU = nn.ReLU--lib[3] -- from https://code.google.com/p/cuda-convnet2/source/browse/layers/layers-imagenet-1gpu.cfg -- this is AlexNet that was presented in the One Weird Trick paper. http://arxiv.org/abs/1404.5997 local features = nn.Sequential() features:add(SpatialConvolution(3,64,11,11,4,4,2,2)) -- 224 -> 55 features:add(ReLU()) features:add(SpatialMaxPooling(3,3,2,2)) -- 55 -> 27 features:add(SpatialConvolution(64,192,5,5,1,1,2,2)) -- 27 -> 27 features:add(ReLU()) features:add(SpatialMaxPooling(3,3,2,2)) -- 27 -> 13 features:add(SpatialConvolution(192,384,3,3,1,1,1,1)) -- 13 -> 13 features:add(ReLU()) features:add(SpatialConvolution(384,256,3,3,1,1,1,1)) -- 13 -> 13 features:add(ReLU()) features:add(SpatialConvolution(256,256,3,3,1,1,1,1)) -- 13 -> 13 features:add(ReLU()) features:add(SpatialMaxPooling(3,3,2,2)) -- 13 -> 6 local classifier = nn.Sequential() classifier:add(nn.View(256*7*7)) classifier:add(nn.Dropout(0.5)) classifier:add(nn.Linear(256*7*7, 4096)) classifier:add(nn.Threshold(0, 1e-6)) classifier:add(nn.Dropout(0.5)) classifier:add(nn.Linear(4096, 4096)) classifier:add(nn.Threshold(0, 1e-6)) classifier:add(nn.Linear(4096, 20)) classifier:add(nn.LogSoftMax()) local model = nn.Sequential() model:add(features):add(classifier) return model
bsd-3-clause
Spartan322/finalfrontier
gamemode/sh_weapons.lua
3
5739
-- Copyright (c) 2014 James King [metapyziks@gmail.com] -- -- This file is part of Final Frontier. -- -- Final Frontier is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of -- the License, or (at your option) any later version. -- -- Final Frontier 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 Lesser General Public License -- along with Final Frontier. If not, see <http://www.gnu.org/licenses/>. if SERVER then AddCSLuaFile("sh_weapons.lua") end if not weapon then weapon = {} weapon._dict = {} weapon._spawnable = {} else return end local _mt = {} _mt.__index = _mt _mt._tier = 0 _mt.BaseName = nil _mt.Base = nil _mt.Name = nil _mt.MaxTier = 1 _mt.CanSpawn = false _mt.Frequency = 100 _mt.LaunchSound = "weapons/rpg/rocketfire1.wav" if CLIENT then _mt.Icon = Material("systems/noicon.png", "smooth") end function _mt:GetMaxPower() return 0 end function _mt:GetMaxCharge() return 0 end function _mt:GetShotCharge() return 0 end function _mt:GetTier() return self._tier end if SERVER then function _mt:OnHit(room) return end elseif CLIENT then function _mt:GetFullName() return "unnamed" end function _mt:GetTierName() return "Mk " .. tostring(self:GetTier()) end function _mt:GetColor() return Color(255, 255, 255, 255) end end MsgN("Loading weapons...") local files = file.Find("finalfrontier/gamemode/weapons/*.lua", "LUA") for i, file in ipairs(files) do local name = string.sub(file, 0, string.len(file) - 4) if SERVER then AddCSLuaFile("weapons/" .. file) end MsgN("- " .. name) WPN = { Name = name } WPN.__index = WPN WPN.Super = {} WPN.Super.__index = WPN.Super WPN.Super[name] = WPN include("weapons/" .. file) if not weapon._dict[name] and WPN.CanSpawn then table.insert(weapon._spawnable, WPN) end weapon._dict[name] = WPN WPN = nil end for _, WPN in pairs(weapon._dict) do if WPN.BaseName then WPN.Base = weapon._dict[WPN.BaseName] setmetatable(WPN, WPN.Base) setmetatable(WPN.Super, WPN.Base.Super) else setmetatable(WPN, _mt) end end function weapon.GetRandomName() local tot = 0 for _, wpn in ipairs(weapon._spawnable) do tot = tot + wpn.Frequency end local i = math.random() * tot for _, wpn in ipairs(weapon._spawnable) do i = i - wpn.Frequency if i <= 0 then return wpn.Name end end end function weapon.GetRandomTier(name) local wpn = weapon._dict[name] return 1 + math.floor(math.pow(math.random(), 3) * wpn.MaxTier) end function weapon.Create(name, tier) name = name or weapon.GetRandomName() local wpn = weapon._dict[name] if wpn then tier = tier or weapon.GetRandomTier(name) return setmetatable({ _tier = tier }, wpn) end return nil end if SERVER then local function missilePhysicsSimulate(ent, phys, delta) local dx, dy = 0, 0 if not IsValid(ent._target) then return Vector(0, 0, 0), Vector(0, 0, 0), SIM_GLOBAL_ACCELERATION end local speed = ent._weapon:GetSpeed() local mx, my = ent:GetCoordinates() local tx, ty = ent._target:GetCoordinates() dx, dy = universe:GetDifference(mx, my, tx, ty) if (ent._target ~= ent._owner:GetObject() or CurTime() - ent._shootTime > 1) and dx * dx + dy * dy < 1 / (64 * 64) then ent._weapon:Hit(ent._target, ent:GetCoordinates()) ent:Remove() return Vector(0, 0, 0), Vector(0, 0, 0), SIM_NOTHING end local vx, vy = ent._target:GetVel() local dist = math.sqrt(dx * dx + dy * dy) local dt = dist / speed dx = dx + (vx - ent._basedx) * dt dy = dy + (vy - ent._basedy) * dt local len = math.sqrt(dx * dx + dy * dy) if len > 0 then dx = dx / len * speed dy = dy / len * speed end vx, vy = ent:GetVel() vx = vx - ent._basedx vy = vy - ent._basedy ent:SetTargetRotation(math.atan2(vy, vx) / math.pi * 180) local a = ent._weapon:GetLateral() local ax = math.sign(dx - vx) * math.max(0, math.abs(dx - vx)) * a local ay = math.sign(dy - vy) * math.max(0, math.abs(dy - vy)) * a local acc = universe:GetWorldPos(ax, ay) - universe:GetWorldPos(0, 0) return Vector(0, 0, 0), acc, SIM_GLOBAL_ACCELERATION end function weapon.LaunchMissile(ship, wpn, target, rot) local vx, vy = ship:GetObject():GetVel() local missile = ents.Create("info_ff_object") missile._owner = ship missile._weapon = wpn missile._target = target missile._shootTime = CurTime() missile._basedx = vx missile._basedy = vy missile:SetObjectType(objtype.MISSILE) missile:SetCoordinates(ship:GetCoordinates()) missile.PhysicsSimulate = missilePhysicsSimulate missile:Spawn() local rad = rot * math.pi / 180 missile:SetRotation(rot) missile:SetMaxAngularVel(180) missile:SetVel(math.cos(rad) * wpn:GetSpeed() + vx, math.sin(rad) * wpn:GetSpeed() + vy) timer.Simple(wpn:GetLifeTime(), function() if IsValid(missile) then missile:Remove() end end) return missile end end
lgpl-3.0
nesstea/darkstar
scripts/globals/items/bowl_of_goblin_stew.lua
18
1490
----------------------------------------- -- ID: 4465 -- Item: bowl_of_goblin_stew -- Food Effect: 3Hrs, All Races ----------------------------------------- -- Dexterity -4 -- Attack % 15.5 -- Ranged Attack % 15.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,4465); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, -4); target:addMod(MOD_FOOD_ATTP, 15.5); target:addMod(MOD_FOOD_ATT_CAP, 80); target:addMod(MOD_FOOD_RATTP, 15.5); target:addMod(MOD_FOOD_RATT_CAP, 80); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, -4); target:delMod(MOD_FOOD_ATTP, 15.5); target:delMod(MOD_FOOD_ATT_CAP, 80); target:delMod(MOD_FOOD_RATTP, 15.5); target:delMod(MOD_FOOD_RATT_CAP, 80); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/La_Theine_Plateau/npcs/Cavernous_Maw.lua
58
1927
----------------------------------- -- Area: La Theine Plateau -- NPC: Cavernous Maw -- @pos -557.9 0.001 637.846 102 -- Teleports Players to Abyssea - La Theine ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/abyssea"); require("scripts/zones/La_Theine_Plateau/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_GOLDSTRUCK_GIGAS) == QUEST_AVAILABLE) then player:startEvent(9); else player:startEvent(218,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 == 9) then player:addQuest(ABYSSEA, A_GOLDSTRUCK_GIGAS); elseif (csid == 10) then -- Killed Briareus elseif (csid == 218 and option == 1) then player:setPos(-480,0,794,62,132); end end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/plate_of_dorado_sushi_+1.lua
18
1689
----------------------------------------- -- ID: 5179 -- Item: plate_of_dorado_sushi_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 5 -- Accuracy % 16 -- Accuracy Cap 76 -- Ranged ACC % 16 -- Ranged ACC Cap 76 -- Sleep Resist 5 -- Enmity 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,3600,5179); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_ENMITY, 5); target:addMod(MOD_DEX, 5); target:addMod(MOD_FOOD_ACCP, 16); target:addMod(MOD_FOOD_ACC_CAP, 76); target:addMod(MOD_FOOD_RACCP, 16); target:addMod(MOD_FOOD_RACC_CAP, 76); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_ENMITY, 5); target:delMod(MOD_DEX, 5); target:delMod(MOD_FOOD_ACCP, 16); target:delMod(MOD_FOOD_ACC_CAP, 76); target:delMod(MOD_FOOD_RACCP, 16); target:delMod(MOD_FOOD_RACC_CAP, 76); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
nesstea/darkstar
scripts/globals/effects/debilitation.lua
34
1335
----------------------------------- -- -- -- ----------------------------------- local stats_bits = {MOD_STR, MOD_DEX, MOD_VIT, MOD_AGI, MOD_INT, MOD_MND, MOD_CHR, MOD_HPP, MOD_MPP} ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) local power = effect:getPower(); for statbit,mod in ipairs(stats_bits) do if bit.band(bit.lshift(1, statbit - 1), power) > 0 then if mod == MOD_HPP or mod == MOD_MPP then target:addMod(mod, -40) else target:addMod(mod, -30) end end end target:setStatDebilitation(power) end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) local power = effect:getPower(); for statbit,mod in ipairs(stats_bits) do if bit.band(bit.lshift(1, statbit - 1), power) > 0 then if mod == MOD_HPP or mod == MOD_MPP then target:delMod(mod, -40) else target:delMod(mod, -30) end end end target:setStatDebilitation(0) end;
gpl-3.0
nesstea/darkstar
scripts/zones/Al_Zahbi/npcs/Falzuuk.lua
27
3041
----------------------------------- -- Area: Al Zahbi -- NPC: Falzuuk -- Type: Imperial Gate Guard -- @pos -60.486 0.999 105.397 48 ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/besieged"); require("scripts/zones/Al_Zahbi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local merc_rank = getMercenaryRank(player); if (merc_rank == 0) then player:startEvent(0x00D9,npc); else maps = getMapBitmask(player); if (getAstralCandescence() == 1) then maps = maps + 0x80000000; end x,y,z,w = getImperialDefenseStats(); player:startEvent(0x00D8,player:getCurrency("imperial_standing"),maps,merc_rank,0,x,y,z,w); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00D8 and option >= 1 and option <= 2049) then itemid = getISPItem(option); player:updateEvent(0,0,0,canEquip(player,itemid)); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00D8) then if (option == 0 or option == 16 or option == 32 or option == 48) then -- player chose sanction. if (option ~= 0) then player:delCurrency("imperial_standing", 100); end player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); local duration = getSanctionDuration(player); local subPower = 0; -- getImperialDefenseStats() player:addStatusEffect(EFFECT_SANCTION,option / 16,0,duration,subPower); -- effect size 1 = regen, 2 = refresh, 3 = food. player:messageSpecial(SANCTION); elseif (option % 256 == 17) then -- player bought one of the maps id = 1862 + (option - 17) / 256 player:addKeyItem(id); player:messageSpecial(KEYITEM_OBTAINED,id); player:delCurrency("imperial_standing", 1000); elseif (option <= 2049) then -- player bought item item, price = getISPItem(option) if (player:getFreeSlotsCount() > 0) then player:delCurrency("imperial_standing", price); player:addItem(item); player:messageSpecial(ITEM_OBTAINED,item); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item); end end end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Vunkerl_Inlet_[S]/npcs/Indescript_Markings.lua
12
1576
---------------------------------- -- Area: Meriphataud_Mountains_[S] -- NPC: Indescript Markings -- Type: Quest -- @pos -629.179 -49.002 -429.104 1 83 ----------------------------------- package.loaded["scripts/zones/Vunkerl_Inlet_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Vunkerl_Inlet_[S]/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local pantsQuestProgress = player:getVar("AF_SCH_PANTS"); player:delStatusEffect(EFFECT_SNEAK); -- SCH AF Quest - Legs if (pantsQuestProgress > 0 and pantsQuestProgress < 3 and player:hasKeyItem(DJINN_EMBER) == false) then player:addKeyItem(DJINN_EMBER); player:messageSpecial(KEYITEM_OBTAINED, DJINN_EMBER); player:setVar("AF_SCH_PANTS", pantsQuestProgress + 1); npc:hideNPC(60); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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
UnfortunateFruit/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Khoi_Gamduhla.lua
34
1038
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Khoi Gamduhla -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x034F); 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
nesstea/darkstar
scripts/zones/Oldton_Movalpolos/npcs/Treasure_Chest.lua
13
3526
----------------------------------- -- Area: Oldton Movalpolos -- NPC: Treasure Chest -- @zone 11 ----------------------------------- package.loaded["scripts/zones/Oldton_Movalpolos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/zones/Oldton_Movalpolos/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 43; local TreasureMinLvL = 33; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1062,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(1062,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_OLDTON_MOVALPOLOS) == 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_OLDTON_MOVALPOLOS); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_OLDTON_MOVALPOLOS); -- Map of Oldton Movalpolos 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,1062); 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
UnfortunateFruit/darkstar
scripts/zones/West_Ronfaure/npcs/Esca.lua
7
2816
----------------------------------- -- Area: West Ronfaure -- NPC: Esca -- Involved in Quest "The Pickpocket" -- @pos -624.231 -51.499 278.369 100 ----------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/West_Ronfaure/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "The Pickpocket" Quest status local thePickpocket = player:getQuestStatus(SANDORIA, THE_PICKPOCKET); -- "The Pickpocket" Trading Esca for Gilt Glasses local count = trade:getItemCount(); local freeSlot = player:getFreeSlotsCount(); local eagleButton = trade:hasItemQty(578, 1); local hasGiltGlasses = player:hasItem(579); if(eagleButton == true and hasGiltGlasses == false) then if (count == 1 and freeSlot > 0) then player:tradeComplete(); player:startEvent(0x0079); player:setVar("thePickpocketGiltGlasses", 1); -- used to get eventID 0x0080 else player:messageSpecial(6378, 579); -- CANNOT_OBTAIN_ITEM end; end; end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- "The Pickpocket" Quest status local thePickpocket = player:getQuestStatus(SANDORIA, THE_PICKPOCKET); local Quotas_Status = player:getVar("ChasingQuotas_Progress"); -- "The Pickpocket" Quest Dialog if (thePickpocket == 1 and player:getVar("thePickpocketGiltGlasses") == 1) then player:startEvent(0x0080); elseif (thePickpocket == 1) then player:startEvent(0x0078); elseif (thePickpocket == 2) then player:startEvent(0x007b); elseif (Quotas_Status == 4) then player:startEvent(137); -- My earring! I stole the last dragoon's armor. Chosen option does not matter. elseif (Quotas_Status == 5) then player:startEvent(138); -- Reminder for finding the armor. else player:startEvent(0x0077); 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); -- "The Pickpocket" recieving Gilt Glasses if (csid == 0x0079) then player:addItem(579); player:messageSpecial(ITEM_OBTAINED, 579); elseif (csid == 137) then player:setVar("ChasingQuotas_Progress",5); player:delKeyItem(SHINY_EARRING); end; end;
gpl-3.0
VurtualRuler98/kswep2-NWI
lua/entities/sent_kgrend_panzerfaust.lua
1
1647
ENT.Type = "Anim" ENT.Base = "sent_kgren_base" ENT.PrintName = "Grenade" ENT.Author = "VurtualRuler98" ENT.Contact = "steam" ENT.Purpose = "Getting more ammo!" ENT.Instructions = "Spawn. Use. Reload." ENT.Category = "Vurtual's base" ENT.DetFragMagnitude="150" ENT.DetFragRadius="384" ENT.Spawnable = false ENT.AdminSpawnable = false ENT.DetonateSound="Weapon_panzerfaust.explode" ENT.DeconstraintRadius=64 if (CLIENT) then function ENT:Draw() --AddWorldTip( self.Entity:EntIndex(), "ammo", 0.5, self.Entity:GetPos(),self.Entity) self.Entity:DrawModel() end end if (SERVER) then AddCSLuaFile() function ENT:SpawnFunction(ply, tr) if (!tr.HitWorld) then return end local ent = ents.Create("sent_kgrend_panzerfaust") ent:SetPos(tr.HitPos + Vector(0, 0, 15)) ent:Spawn() return ent end function ENT:Initialize() self.Entity:SetModel("models/weapons/w_missile_closed.mdl") self.Entity:PhysicsInit( SOLID_VPHYSICS) self.Entity:SetMoveType( MOVETYPE_VPHYSICS ) self.Entity:SetSolid( SOLID_VPHYSICS ) self.Entity:SetUseType(SIMPLE_USE) self.Entity:SetCollisionGroup(COLLISION_GROUP_PROJECTILE) local phys = self.Entity:GetPhysicsObject() if (phys:IsValid()) then phys:SetMass(6) phys:EnableGravity(true) phys:Wake() end end function ENT:PhysicsCollide(data,phys) self:SetNWFloat("Fuze",1) end end function ENT:Think() if (self:GetNWFloat("Fuze")==1 and not self.Detonated) then self.Detonated=true self:Detonate() end end function ENT:Detonate() if (not IsFirstTimePredicted()) then return end self:EmitSound(self.DetonateSound) self:EffectRocketBoom() self:DetConstraints() self:DetBoom() self:Remove() end
apache-2.0
UnfortunateFruit/darkstar
scripts/zones/Windurst_Woods/npcs/Wani_Casdohry.lua
36
1308
----------------------------------- -- Area: Windurst Woods -- NPC: Wani Casdohry ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) TwinstoneBonding = player:getQuestStatus(WINDURST,TWINSTONE_BONDING); if (TwinstoneBonding == QUEST_COMPLETED) then player:startEvent(0x01ec,0,13360); elseif (TwinstoneBonding == QUEST_ACCEPTED) then player:startEvent(0x01e9,0,13360); else player:startEvent(0x01a9); 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
nesstea/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Ozzmo-Mazmo.lua
13
1068
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Ozzmo-Mazmo -- Type: Standard NPC -- @zone: 94 -- @pos -61.677 -13.311 106.400 -- -- 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(0x01b0); 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
JustinZZzz/crtmpserver
configs/all.debug.lua
5
8440
-- Start of the configuration. This is the only node in the config file. -- The rest of them are sub-nodes configuration= { -- if true, the server will run as a daemon. -- NOTE: all console appenders will be ignored if this is a daemon daemon=false, -- the OS's path separator. Used in composing paths pathSeparator="/", -- this is the place where all the logging facilities are setted up -- you can add/remove any number of locations logAppenders= { { -- name of the appender. Not too important, but is mandatory name="console appender", -- type of the appender. We can have the following values: -- console, coloredConsole and file -- NOTE: console appenders will be ignored if we run the server -- as a daemon type="coloredConsole", -- the level of logging. 6 is the FINEST message, 0 is FATAL message. -- The appender will "catch" all the messages below or equal to this level -- bigger the level, more messages are recorded level=6 }, { name="file appender", type="file", level=6, -- the file where the log messages are going to land fileName="/tmp/crtmpserver.log" fileHistorySize=10, fileLength=1024*1024, singleLine=true } }, -- this node holds all the RTMP applications applications= { -- this is the root directory of all applications -- usually this is relative to the binary execuable rootDirectory="applications", --this is where the applications array starts { -- The name of the application. It is mandatory and must be unique name="appselector", -- Short description of the application. Optional description="Application for selecting the rest of the applications", -- The type of the application. Possible values are: -- dynamiclinklibrary - the application is a shared library protocol="dynamiclinklibrary", -- the complete path to the library. This is optional. If not provided, -- the server will try to load the library from here -- <rootDirectory>/<name>/lib<name>.{so|dll|dylib} -- library="/some/path/to/some/shared/library.so" -- Tells the server to validate the clien's handshake before going further. -- It is optional, defaulted to true validateHandshake=true, -- this is the folder from where the current application gets it's content. -- It is optional. If not specified, it will be defaulted to: -- <rootDirectory>/<name>/mediaFolder -- mediaFolder="/some/directory/where/media/files/are/stored" -- the application will also be known by that names. It is optional --aliases= --{ -- "simpleLive", -- "vod", -- "live", --}, -- This flag designates the default application. The default application -- is responsable of analyzing the "connect" request and distribute -- the future connection to the correct application. default=true, acceptors = { { ip="0.0.0.0", port=1935, protocol="inboundRtmp" }, { ip="0.0.0.0", port=8081, protocol="inboundRtmps", sslKey="server.key", sslCert="server.crt" }, { ip="0.0.0.0", port=8080, protocol="inboundRtmpt" }, } }, { description="FLV Playback Sample", name="flvplayback", protocol="dynamiclinklibrary", aliases= { "simpleLive", "vod", "live", "WeeklyQuest", "SOSample", "oflaDemo", }, acceptors = { { ip="0.0.0.0", port=6666, protocol="inboundLiveFlv", waitForMetadata=true, }, { ip="0.0.0.0", port=9999, protocol="inboundTcpTs" }, --[[{ ip="0.0.0.0", port=7654, protocol="inboundRawHttpStream", crossDomainFile="/tmp/crossdomain.xml" }, { ip="0.0.0.0", port=554, protocol="inboundRtsp" },]]-- }, externalStreams = { --[[ { uri="rtsp://82.177.67.61/axis-media/media.amp", localStreamName="stream4", forceTcp=false }, { uri="rtmp://edge01.fms.dutchview.nl/botr/bunny", localStreamName="stream6", emulateUserAgent="MAC 10,1,82,76", } { uri="rtmp://edge01.fms.dutchview.nl/botr/bunny", localStreamName="stream6", swfUrl="http://www.example.com/example.swf"; pageUrl="http://www.example.com/"; emulateUserAgent="MAC 10,1,82,76", } ]]-- }, validateHandshake=true, keyframeSeek=true, seekGranularity=1.5, --in seconds, between 0.1 and 600 clientSideBuffer=12, --in seconds, between 5 and 30 --generateMetaFiles=true, --this will generate seek/meta files on application startup --renameBadFiles=false, --[[authentication= { rtmp={ type="adobe", encoderAgents= { "FMLE/3.0 (compatible; FMSc/1.0)", }, usersFile="./users.lua" }, rtsp={ usersFile="./users.lua" } },]]-- }, { name="samplefactory", description="asdsadasdsa", protocol="dynamiclinklibrary", aliases= { "httpOutboundTest" }, acceptors = { { ip="0.0.0.0", port=8989, protocol="httpEchoProtocol" }, { ip="0.0.0.0", port=8988, protocol="echoProtocol" } } --validateHandshake=true, --default=true, }, { name="vptests", description="Variant protocol tests", protocol="dynamiclinklibrary", aliases= { "vptests_alias1", "vptests_alias2", "vptests_alias3", }, acceptors = { { ip="0.0.0.0", port=1111, protocol="inboundHttpXmlVariant" } } --validateHandshake=true, --default=true, }, { name="admin", description="Application for administering", protocol="dynamiclinklibrary", aliases= { "admin_alias1", "admin_alias2", "admin_alias3", }, acceptors = { { ip="0.0.0.0", port=1112, protocol="inboundJsonCli", useLengthPadding=true }, } --validateHandshake=true, --default=true, }, { name="proxypublish", description="Application for forwarding streams to another RTMP server", protocol="dynamiclinklibrary", acceptors = { { ip="0.0.0.0", port=6665, protocol="inboundLiveFlv" }, }, abortOnConnectError=true, targetServers = { --[[{ targetUri="rtmp://x.xxxxxxx.fme.ustream.tv/ustreamVideo/xxxxxxx", targetStreamName="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", localStreamName="gigi", emulateUserAgent="FMLE/3.0 (compatible; FMSc/1.0 http://www.rtmpd.com)" }]]--, { targetUri="rtmp://localhost/vod", targetStreamType="live", -- (live, record or append) emulateUserAgent="My user agent", localStreamName="stream1" }, }, --[[externalStreams = { { uri="rtsp://82.177.67.61/axis-media/media.amp", localStreamName="stream4", forceTcp=false }, { uri="rtmp://edge01.fms.dutchview.nl/botr/bunny", localStreamName="stream1" }, },]]-- --validateHandshake=true, --default=true, }, { name="stresstest", description="Application for stressing a streaming server", protocol="dynamiclinklibrary", targetServer="localhost", targetApp="vod", active=false, --[[streams = { "lg00","lg01","lg02","lg03","lg04","lg05","lg06","lg07","lg08", "lg09","lg10","lg11","lg12","lg13","lg14","lg15","lg16","lg17", "lg18","lg19","lg20","lg21","lg22","lg23","lg24","lg25","lg26", "lg27","lg28","lg29","lg30","lg31","lg32","lg33","lg34","lg35", "lg36","lg37","lg38","lg39","lg40","lg41","lg42","lg43","lg44", "lg45","lg46","lg47","lg48","lg49" },]]-- streams = { "mp4:lg.mp4" }, numberOfConnections=10, randomAccessStreams=false }, { name="applestreamingclient", description="Apple Streaming Client", protocol="dynamiclinklibrary", --[[acceptors = { { ip="0.0.0.0", port=5544, protocol="inboundRtsp" } },]]-- aliases= { "asc", }, --validateHandshake=true, --default=true, }, --[[{ name="vmapp", description="An application demonstrating the use of virtual machines", protocol="dynamiclinklibrary", vmType="lua", script="flvplayback.lua", aliases= { "flvplayback1", "vod1" }, acceptors= { { ip="0.0.0.0", port=6544, protocol="inboundTcpTs" } } },]]-- --#INSERTION_MARKER# DO NOT REMOVE THIS. USED BY appscaffold SCRIPT. } }
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Northern_San_dOria/npcs/Andreas.lua
10
2727
----------------------------------- -- Area: Northern San d'Oria -- NPC: Andreas -- Type: Guildworker's Union Representative -- @zone: 231 -- @pos -189.282 10.999 262.626 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/globals/keyitems"); require("scripts/globals/crafting"); require("scripts/zones/Northern_San_dOria/TextIDs"); local keyitems = { [0] = { id = WOOD_PURIFICATION, rank = 3, cost = 40000 }, [1] = { id = WOOD_ENSORCELLMENT, rank = 3, cost = 40000 }, [2] = { id = LUMBERJACK, rank = 3, cost = 10000 }, [3] = { id = BOLTMAKER, rank = 3, cost = 10000 }, [4] = { id = WAY_OF_THE_CARPENTER, rank = 9, cost = 20000 } }; local items = { [2] = { id = 15444, -- Carpenter's Belt rank = 1, cost = 10000 }, [3] = { id = 14830, -- Carpenter's Gloves rank = 5, cost = 70000 }, [4] = { id = 14392, -- Carpenter's Apron rank = 7, cost = 100000 }, [5] = { id = 28, -- Drawing Desk rank = 9, cost = 150000 }, [6] = { id = 341, -- Carpenter's Signboard rank = 9, cost = 200000 }, [7] = { id = 15819, -- Carpenter's Ring rank = 6, cost = 80000 }, [8] = { id = 3672, -- Carpenter's Kit rank = 8, cost = 50000 }, [9] = { id = 3331, -- Carpenter's Emblem rank = 9, cost = 15000 } }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) unionRepresentativeTrade(player, npc, trade, 0x02dc, 1); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) unionRepresentativeTrigger(player, 1, 0x02db, "guild_woodworking", keyitems); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,target) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x02db) then unionRepresentativeTriggerFinish(player, option, target, 1, "guild_woodworking", keyitems, items); elseif(csid == 0x02dc) then player:messageSpecial(GP_OBTAINED, option); end end;
gpl-3.0
ruisebastiao/nodemcu-firmware
lua_examples/onewire-ds18b20.lua
60
1505
--' -- 18b20 one wire example for NODEMCU -- NODEMCU TEAM -- LICENCE: http://opensource.org/licenses/MIT -- Vowstar <vowstar@nodemcu.com> --' pin = 9 ow.setup(pin) count = 0 repeat count = count + 1 addr = ow.reset_search(pin) addr = ow.search(pin) tmr.wdclr() until((addr ~= nil) or (count > 100)) if (addr == nil) then print("No more addresses.") else print(addr:byte(1,8)) crc = ow.crc8(string.sub(addr,1,7)) if (crc == addr:byte(8)) then if ((addr:byte(1) == 0x10) or (addr:byte(1) == 0x28)) then print("Device is a DS18S20 family device.") repeat ow.reset(pin) ow.select(pin, addr) ow.write(pin, 0x44, 1) tmr.delay(1000000) present = ow.reset(pin) ow.select(pin, addr) ow.write(pin,0xBE,1) print("P="..present) data = nil data = string.char(ow.read(pin)) for i = 1, 8 do data = data .. string.char(ow.read(pin)) end print(data:byte(1,9)) crc = ow.crc8(string.sub(data,1,8)) print("CRC="..crc) if (crc == data:byte(9)) then t = (data:byte(1) + data:byte(2) * 256) * 625 t1 = t / 10000 t2 = t % 10000 print("Temperature= "..t1.."."..t2.." Centigrade") end tmr.wdclr() until false else print("Device family is not recognized.") end else print("CRC is not valid!") end end
mit
UnfortunateFruit/darkstar
scripts/zones/AlTaieu/mobs/Absolute_Virtue.lua
23
2388
----------------------------------- -- Area: Al'Taieu -- HNM: Absolute Virtue ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) -- setMod mob:setMod(MOD_REGEN, 500); local JoL = GetMobByID(16912848); -- Special check for regen modification by JoL pets killed if (JoL:getLocalVar("JoL_Qn_xzomit_Killed") == 9) then mob:addMod(MOD_REGEN, -130) end if (JoL:getLocalVar("JoL_Qn_hpemde_Killed") == 9) then mob:addMod(MOD_REGEN, -130) end end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) end; ------------------------------------ -- onSpellPrecast ------------------------------------ function onSpellPrecast(mob, spell) if (spell:getID() == 218) then -- Meteor spell:setAoE(SPELLAOE_RADIAL); spell:setFlag(SPELLFLAG_HIT_ALL); spell:setRadius(30); spell:setAnimation(280); -- AoE Meteor Animation spell:setMPCost(1); end end; ------------------------------------ -- onMonsterMagicPrepare ------------------------------------ function onMonsterMagicPrepare(caster, target) end; ----------------------------------- -- onMagicHit ----------------------------------- function onMagicHit(caster, target, spell) local REGEN = target:getMod(MOD_REGEN); local DAY = VanadielDayElement(); local ELEM = spell:getElement(); if (GetServerVariable("AV_Regen_Reduction") < 60) then -- Had to serverVar the regen instead of localVar because localVar reset on claim loss. if (ELEM == DAY and (caster:isPC() or caster:isPet())) then SetServerVariable("AV_Regen_Reduction", 1+GetServerVariable("AV_Regen_Reduction")); target:addMod(MOD_REGEN, -2); end end return 1; end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) killer:addTitle(VIRTUOUS_SAINT); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/weaponskills/detonator.lua
30
1630
----------------------------------- -- Detonator -- Marksmanship weapon skill -- Skill Level: 250 -- Delivers a single-hit attack. Damage varies with TP. -- In order to obtain Detonator, the quest Shoot First, Ask Questions Later must be completed. -- Despite the lack of a STR weaponskill mod, STR is still the most potent stat for increasing this weaponskill's damage to the point at which fSTR2 is capped. -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: None -- Modifiers: AGI:30% -- 100%TP 200%TP 300%TP -- 1.50 2.00 2.50 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 1.5; params.ftp200 = 2; params.ftp300 = 2.5; 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.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 1.5; params.ftp200 = 2.5; params.ftp300 = 5.0; params.agi_wsc = 0.7; end local damage, tpHits, extraHits = doRangedWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
johnmccabe/dockercraft
world/Plugins/APIDump/Hooks/OnExploded.lua
22
2897
return { HOOK_EXPLODED = { CalledWhen = "An explosion has happened", DefaultFnName = "OnExploded", -- also used as pagename Desc = [[ This hook is called after an explosion has been processed in a world.</p> <p> See also {{OnExploding|HOOK_EXPLODING}} for a similar hook called before the explosion.</p> <p> The explosion carries with it the type of its source - whether it's a creeper exploding, or TNT, etc. It also carries the identification of the actual source. The exact type of the identification depends on the source kind: <table> <tr><th>Source</th><th>SourceData Type</th><th>Notes</th></tr> <tr><td>esPrimedTNT</td><td>{{cTNTEntity}}</td><td>An exploding primed TNT entity</td></tr> <tr><td>esCreeper</td><td>{{cCreeper}}</td><td>An exploding creeper or charged creeper</td></tr> <tr><td>esBed</td><td>{{Vector3i}}</td><td>A bed exploding in the Nether or in the End. The bed coords are given.</td></tr> <tr><td>esEnderCrystal</td><td>{{Vector3i}}</td><td>An ender crystal exploding upon hit. The block coords are given.</td></tr> <tr><td>esGhastFireball</td><td>{{cGhastFireballEntity}}</td><td>A ghast fireball hitting ground or an {{cEntity|entity}}.</td></tr> <tr><td>esWitherSkullBlack</td><td><i>TBD</i></td><td>A black wither skull hitting ground or an {{cEntity|entity}}.</td></tr> <tr><td>esWitherSkullBlue</td><td><i>TBD</i></td><td>A blue wither skull hitting ground or an {{cEntity|entity}}.</td></tr> <tr><td>esWitherBirth</td><td><i>TBD</i></td><td>A wither boss being created</td></tr> <tr><td>esOther</td><td><i>TBD</i></td><td>Any other previously unspecified type.</td></tr> <tr><td>esPlugin</td><td>object</td><td>An explosion created by a plugin. The plugin may specify any kind of data.</td></tr> </table></p> ]], Params = { { Name = "World", Type = "{{cWorld}}", Notes = "The world where the explosion happened" }, { Name = "ExplosionSize", Type = "number", Notes = "The relative explosion size" }, { Name = "CanCauseFire", Type = "bool", Notes = "True if the explosion has turned random air blocks to fire (such as a ghast fireball)" }, { Name = "X", Type = "number", Notes = "X-coord of the explosion center" }, { Name = "Y", Type = "number", Notes = "Y-coord of the explosion center" }, { Name = "Z", Type = "number", Notes = "Z-coord of the explosion center" }, { Name = "Source", Type = "eExplosionSource", Notes = "Source of the explosion. See the table above." }, { Name = "SourceData", Type = "varies", Notes = "Additional data for the source. The exact type varies by the source. See the table above." }, }, Returns = [[ If the function returns false or no value, the next plugin's callback is called. If the function returns true, no other callback is called for this event. There is no overridable behaviour. ]], }, -- HOOK_EXPLODED }
apache-2.0
UnfortunateFruit/darkstar
scripts/zones/Pashhow_Marshlands/npcs/Tahmasp.lua
17
1872
----------------------------------- -- 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
nesstea/darkstar
scripts/zones/Chateau_dOraguille/npcs/Chalvatot.lua
12
4783
----------------------------------- -- Area: Chateau d'Oraguille -- NPC: Chalvatot -- Finish Mission "The Crystal Spring" -- Start & Finishes Quests: Her Majesty's Garden -- Involved in Quest: Lure of the Wildcat (San d'Oria) -- @pos -105 0.1 72 233 ----------------------------------- package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Chateau_dOraguille/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then player:messageSpecial(FLYER_REFUSED); end elseif (trade:hasItemQty(533,1) and trade:getItemCount() == 1) then if (player:getQuestStatus(SANDORIA,HER_MAJESTY_S_GARDEN) == QUEST_ACCEPTED) then player:startEvent(0x0053); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local herMajestysGarden = player:getQuestStatus(SANDORIA,HER_MAJESTY_S_GARDEN); local currentMission = player:getCurrentMission(SANDORIA); local MissionStatus = player:getVar("MissionStatus"); local circleOfTime = player:getQuestStatus(JEUNO,THE_CIRCLE_OF_TIME); local WildcatSandy = player:getVar("WildcatSandy"); if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,19) == false) then player:startEvent(0x0231); elseif (player:getCurrentMission(SANDORIA) == THE_CRYSTAL_SPRING and player:getVar("MissionStatus") == 3) then player:startEvent(0x022c); elseif (herMajestysGarden == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 4) then player:startEvent(0x0054); elseif (currentMission == LEAUTE_S_LAST_WISHES and MissionStatus == 4 and player:hasKeyItem(DREAMROSE)) then player:startEvent(0x006f); elseif (herMajestysGarden == QUEST_ACCEPTED) then player:startEvent(0x0052); elseif (circleOfTime == QUEST_ACCEPTED) then if (player:getVar("circleTime") == 5) then player:startEvent(0x0063); elseif (player:getVar("circleTime") == 6) then player:startEvent(0x0062); elseif (player:getVar("circleTime") == 7) then player:startEvent(0x0061); elseif (player:getVar("circleTime") == 9) then player:startEvent(0x0060); end else player:startEvent(0x0213); 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 == 0x022c or csid == 0x006f) then finishMissionTimeline(player,3,csid,option); elseif (csid == 0x0231) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",19,true); elseif (csid == 0x0054 and option == 1) then player:addQuest(SANDORIA,HER_MAJESTY_S_GARDEN); elseif (csid == 0x0053) then player:tradeComplete(); player:addKeyItem(MAP_OF_THE_NORTHLANDS_AREA); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_NORTHLANDS_AREA); player:addFame(SANDORIA,30); player:completeQuest(SANDORIA,HER_MAJESTY_S_GARDEN); elseif (csid == 0x0063) then if (option == 1) then player:setVar("circleTime",7); player:addKeyItem(MOON_RING); player:messageSpecial(KEYITEM_OBTAINED,MOON_RING); else player:setVar("circleTime",6); end elseif (csid == 0x0062) then if (option == 1) then player:setVar("circleTime",7); player:addKeyItem(MOON_RING); player:messageSpecial(KEYITEM_OBTAINED,MOON_RING); end elseif (csid == 0x0060) then if (player:getFreeSlotsCount() ~= 0) then player:addItem(12647); player:messageSpecial(ITEM_OBTAINED,12647) player:completeQuest(JEUNO,THE_CIRCLE_OF_TIME); player:addTitle(PARAGON_OF_BARD_EXCELLENCE); player:setVar("circleTime",0); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED); end end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Yorcia_Weald/Zone.lua
16
1181
----------------------------------- -- -- Zone: Yorcia Weald -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Yorcia_Weald/TextIDs"] = nil; require("scripts/zones/Yorcia_Weald/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(254,6,64,219); 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
NezzKryptic/Wire-Extras
lua/entities/gmod_wire_expression2/core/custom/cl_holoanim.lua
1
1028
local poseParams = {} local function hologramPoseParams() if next(poseParams) then for ent, poses in pairs(poseParams) do if ent:IsValid() then for pose, value in pairs(poses) do ent:SetPoseParameter(pose, value) end end end else hook.Remove("Think","wire_hologram_poseparameters") end end net.Receive("wire_expression2_updateposeparameters", function() if not next(poseParams) then hook.Add("Think","wire_hologram_poseparameters", hologramPoseParams) end local ent = net.ReadEntity() while ent:IsValid() do local tbl = poseParams[ent] if not tbl then if table.Count(poseParams)==32 then return end --32 holograms max tbl = {} poseParams[ent] = tbl ent:CallOnRemove("cleanup_poseparameters", function() timer.Simple(0, function() if not ent:IsValid() then poseParams[ent] = nil end end) end) end local idx = net.ReadUInt(8) while idx ~= 255 do tbl[ent:GetPoseParameterName(idx)] = net.ReadFloat() idx = net.ReadUInt(8) end ent = net.ReadEntity() end end)
gpl-3.0
dpino/snabbswitch
lib/luajit/dynasm/dasm_arm.lua
30
34598
------------------------------------------------------------------------------ -- DynASM ARM module. -- -- Copyright (C) 2005-2017 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "arm", description = "DynASM ARM module", version = "1.4.0", vernum = 10400, release = "2015-10-18", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable, rawget = assert, setmetatable, rawget local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub local concat, sort, insert = table.concat, table.sort, table.insert local bit = bit or require("bit") local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift local ror, tohex = bit.ror, bit.tohex -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "IMM", "IMM12", "IMM16", "IMML8", "IMML12", "IMMV8", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n <= 0x000fffff then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") if n <= 0x000fffff then insert(actlist, pos+1, n) n = map_action.ESC * 0x10000 end actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. -- Ext. register name -> int. name. local map_archdef = { sp = "r13", lr = "r14", pc = "r15", } -- Int. register name -> ext. name. local map_reg_rev = { r13 = "sp", r14 = "lr", r15 = "pc", } local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) return map_reg_rev[s] or s end local map_shift = { lsl = 0, lsr = 1, asr = 2, ror = 3, } local map_cond = { eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7, hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14, hs = 2, lo = 3, } ------------------------------------------------------------------------------ -- Template strings for ARM instructions. local map_op = { -- Basic data processing instructions. and_3 = "e0000000DNPs", eor_3 = "e0200000DNPs", sub_3 = "e0400000DNPs", rsb_3 = "e0600000DNPs", add_3 = "e0800000DNPs", adc_3 = "e0a00000DNPs", sbc_3 = "e0c00000DNPs", rsc_3 = "e0e00000DNPs", tst_2 = "e1100000NP", teq_2 = "e1300000NP", cmp_2 = "e1500000NP", cmn_2 = "e1700000NP", orr_3 = "e1800000DNPs", mov_2 = "e1a00000DPs", bic_3 = "e1c00000DNPs", mvn_2 = "e1e00000DPs", and_4 = "e0000000DNMps", eor_4 = "e0200000DNMps", sub_4 = "e0400000DNMps", rsb_4 = "e0600000DNMps", add_4 = "e0800000DNMps", adc_4 = "e0a00000DNMps", sbc_4 = "e0c00000DNMps", rsc_4 = "e0e00000DNMps", tst_3 = "e1100000NMp", teq_3 = "e1300000NMp", cmp_3 = "e1500000NMp", cmn_3 = "e1700000NMp", orr_4 = "e1800000DNMps", mov_3 = "e1a00000DMps", bic_4 = "e1c00000DNMps", mvn_3 = "e1e00000DMps", lsl_3 = "e1a00000DMws", lsr_3 = "e1a00020DMws", asr_3 = "e1a00040DMws", ror_3 = "e1a00060DMws", rrx_2 = "e1a00060DMs", -- Multiply and multiply-accumulate. mul_3 = "e0000090NMSs", mla_4 = "e0200090NMSDs", umaal_4 = "e0400090DNMSs", -- v6 mls_4 = "e0600090DNMSs", -- v6T2 umull_4 = "e0800090DNMSs", umlal_4 = "e0a00090DNMSs", smull_4 = "e0c00090DNMSs", smlal_4 = "e0e00090DNMSs", -- Halfword multiply and multiply-accumulate. smlabb_4 = "e1000080NMSD", -- v5TE smlatb_4 = "e10000a0NMSD", -- v5TE smlabt_4 = "e10000c0NMSD", -- v5TE smlatt_4 = "e10000e0NMSD", -- v5TE smlawb_4 = "e1200080NMSD", -- v5TE smulwb_3 = "e12000a0NMS", -- v5TE smlawt_4 = "e12000c0NMSD", -- v5TE smulwt_3 = "e12000e0NMS", -- v5TE smlalbb_4 = "e1400080NMSD", -- v5TE smlaltb_4 = "e14000a0NMSD", -- v5TE smlalbt_4 = "e14000c0NMSD", -- v5TE smlaltt_4 = "e14000e0NMSD", -- v5TE smulbb_3 = "e1600080NMS", -- v5TE smultb_3 = "e16000a0NMS", -- v5TE smulbt_3 = "e16000c0NMS", -- v5TE smultt_3 = "e16000e0NMS", -- v5TE -- Miscellaneous data processing instructions. clz_2 = "e16f0f10DM", -- v5T rev_2 = "e6bf0f30DM", -- v6 rev16_2 = "e6bf0fb0DM", -- v6 revsh_2 = "e6ff0fb0DM", -- v6 sel_3 = "e6800fb0DNM", -- v6 usad8_3 = "e780f010NMS", -- v6 usada8_4 = "e7800010NMSD", -- v6 rbit_2 = "e6ff0f30DM", -- v6T2 movw_2 = "e3000000DW", -- v6T2 movt_2 = "e3400000DW", -- v6T2 -- Note: the X encodes width-1, not width. sbfx_4 = "e7a00050DMvX", -- v6T2 ubfx_4 = "e7e00050DMvX", -- v6T2 -- Note: the X encodes the msb field, not the width. bfc_3 = "e7c0001fDvX", -- v6T2 bfi_4 = "e7c00010DMvX", -- v6T2 -- Packing and unpacking instructions. pkhbt_3 = "e6800010DNM", pkhbt_4 = "e6800010DNMv", -- v6 pkhtb_3 = "e6800050DNM", pkhtb_4 = "e6800050DNMv", -- v6 sxtab_3 = "e6a00070DNM", sxtab_4 = "e6a00070DNMv", -- v6 sxtab16_3 = "e6800070DNM", sxtab16_4 = "e6800070DNMv", -- v6 sxtah_3 = "e6b00070DNM", sxtah_4 = "e6b00070DNMv", -- v6 sxtb_2 = "e6af0070DM", sxtb_3 = "e6af0070DMv", -- v6 sxtb16_2 = "e68f0070DM", sxtb16_3 = "e68f0070DMv", -- v6 sxth_2 = "e6bf0070DM", sxth_3 = "e6bf0070DMv", -- v6 uxtab_3 = "e6e00070DNM", uxtab_4 = "e6e00070DNMv", -- v6 uxtab16_3 = "e6c00070DNM", uxtab16_4 = "e6c00070DNMv", -- v6 uxtah_3 = "e6f00070DNM", uxtah_4 = "e6f00070DNMv", -- v6 uxtb_2 = "e6ef0070DM", uxtb_3 = "e6ef0070DMv", -- v6 uxtb16_2 = "e6cf0070DM", uxtb16_3 = "e6cf0070DMv", -- v6 uxth_2 = "e6ff0070DM", uxth_3 = "e6ff0070DMv", -- v6 -- Saturating instructions. qadd_3 = "e1000050DMN", -- v5TE qsub_3 = "e1200050DMN", -- v5TE qdadd_3 = "e1400050DMN", -- v5TE qdsub_3 = "e1600050DMN", -- v5TE -- Note: the X for ssat* encodes sat_imm-1, not sat_imm. ssat_3 = "e6a00010DXM", ssat_4 = "e6a00010DXMp", -- v6 usat_3 = "e6e00010DXM", usat_4 = "e6e00010DXMp", -- v6 ssat16_3 = "e6a00f30DXM", -- v6 usat16_3 = "e6e00f30DXM", -- v6 -- Parallel addition and subtraction. sadd16_3 = "e6100f10DNM", -- v6 sasx_3 = "e6100f30DNM", -- v6 ssax_3 = "e6100f50DNM", -- v6 ssub16_3 = "e6100f70DNM", -- v6 sadd8_3 = "e6100f90DNM", -- v6 ssub8_3 = "e6100ff0DNM", -- v6 qadd16_3 = "e6200f10DNM", -- v6 qasx_3 = "e6200f30DNM", -- v6 qsax_3 = "e6200f50DNM", -- v6 qsub16_3 = "e6200f70DNM", -- v6 qadd8_3 = "e6200f90DNM", -- v6 qsub8_3 = "e6200ff0DNM", -- v6 shadd16_3 = "e6300f10DNM", -- v6 shasx_3 = "e6300f30DNM", -- v6 shsax_3 = "e6300f50DNM", -- v6 shsub16_3 = "e6300f70DNM", -- v6 shadd8_3 = "e6300f90DNM", -- v6 shsub8_3 = "e6300ff0DNM", -- v6 uadd16_3 = "e6500f10DNM", -- v6 uasx_3 = "e6500f30DNM", -- v6 usax_3 = "e6500f50DNM", -- v6 usub16_3 = "e6500f70DNM", -- v6 uadd8_3 = "e6500f90DNM", -- v6 usub8_3 = "e6500ff0DNM", -- v6 uqadd16_3 = "e6600f10DNM", -- v6 uqasx_3 = "e6600f30DNM", -- v6 uqsax_3 = "e6600f50DNM", -- v6 uqsub16_3 = "e6600f70DNM", -- v6 uqadd8_3 = "e6600f90DNM", -- v6 uqsub8_3 = "e6600ff0DNM", -- v6 uhadd16_3 = "e6700f10DNM", -- v6 uhasx_3 = "e6700f30DNM", -- v6 uhsax_3 = "e6700f50DNM", -- v6 uhsub16_3 = "e6700f70DNM", -- v6 uhadd8_3 = "e6700f90DNM", -- v6 uhsub8_3 = "e6700ff0DNM", -- v6 -- Load/store instructions. str_2 = "e4000000DL", str_3 = "e4000000DL", str_4 = "e4000000DL", strb_2 = "e4400000DL", strb_3 = "e4400000DL", strb_4 = "e4400000DL", ldr_2 = "e4100000DL", ldr_3 = "e4100000DL", ldr_4 = "e4100000DL", ldrb_2 = "e4500000DL", ldrb_3 = "e4500000DL", ldrb_4 = "e4500000DL", strh_2 = "e00000b0DL", strh_3 = "e00000b0DL", ldrh_2 = "e01000b0DL", ldrh_3 = "e01000b0DL", ldrd_2 = "e00000d0DL", ldrd_3 = "e00000d0DL", -- v5TE ldrsb_2 = "e01000d0DL", ldrsb_3 = "e01000d0DL", strd_2 = "e00000f0DL", strd_3 = "e00000f0DL", -- v5TE ldrsh_2 = "e01000f0DL", ldrsh_3 = "e01000f0DL", ldm_2 = "e8900000oR", ldmia_2 = "e8900000oR", ldmfd_2 = "e8900000oR", ldmda_2 = "e8100000oR", ldmfa_2 = "e8100000oR", ldmdb_2 = "e9100000oR", ldmea_2 = "e9100000oR", ldmib_2 = "e9900000oR", ldmed_2 = "e9900000oR", stm_2 = "e8800000oR", stmia_2 = "e8800000oR", stmfd_2 = "e8800000oR", stmda_2 = "e8000000oR", stmfa_2 = "e8000000oR", stmdb_2 = "e9000000oR", stmea_2 = "e9000000oR", stmib_2 = "e9800000oR", stmed_2 = "e9800000oR", pop_1 = "e8bd0000R", push_1 = "e92d0000R", -- Branch instructions. b_1 = "ea000000B", bl_1 = "eb000000B", blx_1 = "e12fff30C", bx_1 = "e12fff10M", -- Miscellaneous instructions. nop_0 = "e1a00000", mrs_1 = "e10f0000D", bkpt_1 = "e1200070K", -- v5T svc_1 = "ef000000T", swi_1 = "ef000000T", ud_0 = "e7f001f0", -- VFP instructions. ["vadd.f32_3"] = "ee300a00dnm", ["vadd.f64_3"] = "ee300b00Gdnm", ["vsub.f32_3"] = "ee300a40dnm", ["vsub.f64_3"] = "ee300b40Gdnm", ["vmul.f32_3"] = "ee200a00dnm", ["vmul.f64_3"] = "ee200b00Gdnm", ["vnmul.f32_3"] = "ee200a40dnm", ["vnmul.f64_3"] = "ee200b40Gdnm", ["vmla.f32_3"] = "ee000a00dnm", ["vmla.f64_3"] = "ee000b00Gdnm", ["vmls.f32_3"] = "ee000a40dnm", ["vmls.f64_3"] = "ee000b40Gdnm", ["vnmla.f32_3"] = "ee100a40dnm", ["vnmla.f64_3"] = "ee100b40Gdnm", ["vnmls.f32_3"] = "ee100a00dnm", ["vnmls.f64_3"] = "ee100b00Gdnm", ["vdiv.f32_3"] = "ee800a00dnm", ["vdiv.f64_3"] = "ee800b00Gdnm", ["vabs.f32_2"] = "eeb00ac0dm", ["vabs.f64_2"] = "eeb00bc0Gdm", ["vneg.f32_2"] = "eeb10a40dm", ["vneg.f64_2"] = "eeb10b40Gdm", ["vsqrt.f32_2"] = "eeb10ac0dm", ["vsqrt.f64_2"] = "eeb10bc0Gdm", ["vcmp.f32_2"] = "eeb40a40dm", ["vcmp.f64_2"] = "eeb40b40Gdm", ["vcmpe.f32_2"] = "eeb40ac0dm", ["vcmpe.f64_2"] = "eeb40bc0Gdm", ["vcmpz.f32_1"] = "eeb50a40d", ["vcmpz.f64_1"] = "eeb50b40Gd", ["vcmpze.f32_1"] = "eeb50ac0d", ["vcmpze.f64_1"] = "eeb50bc0Gd", vldr_2 = "ed100a00dl|ed100b00Gdl", vstr_2 = "ed000a00dl|ed000b00Gdl", vldm_2 = "ec900a00or", vldmia_2 = "ec900a00or", vldmdb_2 = "ed100a00or", vpop_1 = "ecbd0a00r", vstm_2 = "ec800a00or", vstmia_2 = "ec800a00or", vstmdb_2 = "ed000a00or", vpush_1 = "ed2d0a00r", ["vmov.f32_2"] = "eeb00a40dm|eeb00a00dY", -- #imm is VFPv3 only ["vmov.f64_2"] = "eeb00b40Gdm|eeb00b00GdY", -- #imm is VFPv3 only vmov_2 = "ee100a10Dn|ee000a10nD", vmov_3 = "ec500a10DNm|ec400a10mDN|ec500b10GDNm|ec400b10GmDN", vmrs_0 = "eef1fa10", vmrs_1 = "eef10a10D", vmsr_1 = "eee10a10D", ["vcvt.s32.f32_2"] = "eebd0ac0dm", ["vcvt.s32.f64_2"] = "eebd0bc0dGm", ["vcvt.u32.f32_2"] = "eebc0ac0dm", ["vcvt.u32.f64_2"] = "eebc0bc0dGm", ["vcvtr.s32.f32_2"] = "eebd0a40dm", ["vcvtr.s32.f64_2"] = "eebd0b40dGm", ["vcvtr.u32.f32_2"] = "eebc0a40dm", ["vcvtr.u32.f64_2"] = "eebc0b40dGm", ["vcvt.f32.s32_2"] = "eeb80ac0dm", ["vcvt.f64.s32_2"] = "eeb80bc0GdFm", ["vcvt.f32.u32_2"] = "eeb80a40dm", ["vcvt.f64.u32_2"] = "eeb80b40GdFm", ["vcvt.f32.f64_2"] = "eeb70bc0dGm", ["vcvt.f64.f32_2"] = "eeb70ac0GdFm", -- VFPv4 only: ["vfma.f32_3"] = "eea00a00dnm", ["vfma.f64_3"] = "eea00b00Gdnm", ["vfms.f32_3"] = "eea00a40dnm", ["vfms.f64_3"] = "eea00b40Gdnm", ["vfnma.f32_3"] = "ee900a40dnm", ["vfnma.f64_3"] = "ee900b40Gdnm", ["vfnms.f32_3"] = "ee900a00dnm", ["vfnms.f64_3"] = "ee900b00Gdnm", -- NYI: Advanced SIMD instructions. -- NYI: I have no need for these instructions right now: -- swp, swpb, strex, ldrex, strexd, ldrexd, strexb, ldrexb, strexh, ldrexh -- msr, nopv6, yield, wfe, wfi, sev, dbg, bxj, smc, srs, rfe -- cps, setend, pli, pld, pldw, clrex, dsb, dmb, isb -- stc, ldc, mcr, mcr2, mrc, mrc2, mcrr, mcrr2, mrrc, mrrc2, cdp, cdp2 } -- Add mnemonics for "s" variants. do local t = {} for k,v in pairs(map_op) do if sub(v, -1) == "s" then local v2 = sub(v, 1, 2)..char(byte(v, 3)+1)..sub(v, 4, -2) t[sub(k, 1, -3).."s"..sub(k, -2)] = v2 end end for k,v in pairs(t) do map_op[k] = v end end ------------------------------------------------------------------------------ local function parse_gpr(expr) local tname, ovreg = match(expr, "^([%w_]+):(r1?[0-9])$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local r = match(expr, "^r(1?[0-9])$") if r then r = tonumber(r) if r <= 15 then return r, tp end end werror("bad register name `"..expr.."'") end local function parse_gpr_pm(expr) local pm, expr2 = match(expr, "^([+-]?)(.*)$") return parse_gpr(expr2), (pm == "-") end local function parse_vr(expr, tp) local t, r = match(expr, "^([sd])([0-9]+)$") if t == tp then r = tonumber(r) if r <= 31 then if t == "s" then return shr(r, 1), band(r, 1) end return band(r, 15), shr(r, 4) end end werror("bad register name `"..expr.."'") end local function parse_reglist(reglist) reglist = match(reglist, "^{%s*([^}]*)}$") if not reglist then werror("register list expected") end local rr = 0 for p in gmatch(reglist..",", "%s*([^,]*),") do local rbit = shl(1, parse_gpr(gsub(p, "%s+$", ""))) if band(rr, rbit) ~= 0 then werror("duplicate register `"..p.."'") end rr = rr + rbit end return rr end local function parse_vrlist(reglist) local ta, ra, tb, rb = match(reglist, "^{%s*([sd])([0-9]+)%s*%-%s*([sd])([0-9]+)%s*}$") ra, rb = tonumber(ra), tonumber(rb) if ta and ta == tb and ra and rb and ra <= 31 and rb <= 31 and ra <= rb then local nr = rb+1 - ra if ta == "s" then return shl(shr(ra,1),12)+shl(band(ra,1),22) + nr else return shl(band(ra,15),12)+shl(shr(ra,4),22) + nr*2 + 0x100 end end werror("register list expected") end local function parse_imm(imm, bits, shift, scale, signed) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = tonumber(imm) if n then local m = sar(n, scale) if shl(m, scale) == n then if signed then local s = sar(m, bits-1) if s == 0 then return shl(m, shift) elseif s == -1 then return shl(m + shl(1, bits), shift) end else if sar(m, bits) == 0 then return shl(m, shift) end end end werror("out of range immediate `"..imm.."'") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_imm12(imm) local n = tonumber(imm) if n then local m = band(n) for i=0,-15,-1 do if shr(m, 8) == 0 then return m + shl(band(i, 15), 8) end m = ror(m, 2) end werror("out of range immediate `"..imm.."'") else waction("IMM12", 0, imm) return 0 end end local function parse_imm16(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = tonumber(imm) if n then if shr(n, 16) == 0 then return band(n, 0x0fff) + shl(band(n, 0xf000), 4) end werror("out of range immediate `"..imm.."'") else waction("IMM16", 32*16, imm) return 0 end end local function parse_imm_load(imm, ext) local n = tonumber(imm) if n then if ext then if n >= -255 and n <= 255 then local up = 0x00800000 if n < 0 then n = -n; up = 0 end return shl(band(n, 0xf0), 4) + band(n, 0x0f) + up end else if n >= -4095 and n <= 4095 then if n >= 0 then return n+0x00800000 end return -n end end werror("out of range immediate `"..imm.."'") else waction(ext and "IMML8" or "IMML12", 32768 + shl(ext and 8 or 12, 5), imm) return 0 end end local function parse_shift(shift, gprok) if shift == "rrx" then return 3 * 32 else local s, s2 = match(shift, "^(%S+)%s*(.*)$") s = map_shift[s] if not s then werror("expected shift operand") end if sub(s2, 1, 1) == "#" then return parse_imm(s2, 5, 7, 0, false) + shl(s, 5) else if not gprok then werror("expected immediate shift operand") end return shl(parse_gpr(s2), 8) + shl(s, 5) + 16 end end end local function parse_label(label, def) local prefix = sub(label, 1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, sub(label, 3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[sub(label, 3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end end werror("bad label `"..label.."'") end local function parse_load(params, nparams, n, op) local oplo = band(op, 255) local ext, ldrd = (oplo ~= 0), (oplo == 208) local d if (ldrd or oplo == 240) then d = band(shr(op, 12), 15) if band(d, 1) ~= 0 then werror("odd destination register") end end local pn = params[n] local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$") local p2 = params[n+1] if not p1 then if not p2 then if match(pn, "^[<>=%-]") or match(pn, "^extern%s+") then local mode, n, s = parse_label(pn, false) waction("REL_"..mode, n + (ext and 0x1800 or 0x0800), s, 1) return op + 15 * 65536 + 0x01000000 + (ext and 0x00400000 or 0) end local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local d, tp = parse_gpr(reg) if tp then waction(ext and "IMML8" or "IMML12", 32768 + 32*(ext and 8 or 12), format(tp.ctypefmt, tailr)) return op + shl(d, 16) + 0x01000000 + (ext and 0x00400000 or 0) end end end werror("expected address operand") end if wb == "!" then op = op + 0x00200000 end if p2 then if wb == "!" then werror("bad use of '!'") end local p3 = params[n+2] op = op + shl(parse_gpr(p1), 16) local imm = match(p2, "^#(.*)$") if imm then local m = parse_imm_load(imm, ext) if p3 then werror("too many parameters") end op = op + m + (ext and 0x00400000 or 0) else local m, neg = parse_gpr_pm(p2) if ldrd and (m == d or m-1 == d) then werror("register conflict") end op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000) if p3 then op = op + parse_shift(p3) end end else local p1a, p2 = match(p1, "^([^,%s]*)%s*(.*)$") op = op + shl(parse_gpr(p1a), 16) + 0x01000000 if p2 ~= "" then local imm = match(p2, "^,%s*#(.*)$") if imm then local m = parse_imm_load(imm, ext) op = op + m + (ext and 0x00400000 or 0) else local p2a, p3 = match(p2, "^,%s*([^,%s]*)%s*,?%s*(.*)$") local m, neg = parse_gpr_pm(p2a) if ldrd and (m == d or m-1 == d) then werror("register conflict") end op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000) if p3 ~= "" then if ext then werror("too many parameters") end op = op + parse_shift(p3) end end else if wb == "!" then werror("bad use of '!'") end op = op + (ext and 0x00c00000 or 0x00800000) end end return op end local function parse_vload(q) local reg, imm = match(q, "^%[%s*([^,%s]*)%s*(.*)%]$") if reg then local d = shl(parse_gpr(reg), 16) if imm == "" then return d end imm = match(imm, "^,%s*#(.*)$") if imm then local n = tonumber(imm) if n then if n >= -1020 and n <= 1020 and n%4 == 0 then return d + (n >= 0 and n/4+0x00800000 or -n/4) end werror("out of range immediate `"..imm.."'") else waction("IMMV8", 32768 + 32*8, imm) return d end end else if match(q, "^[<>=%-]") or match(q, "^extern%s+") then local mode, n, s = parse_label(q, false) waction("REL_"..mode, n + 0x2800, s, 1) return 15 * 65536 end local reg, tailr = match(q, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local d, tp = parse_gpr(reg) if tp then waction("IMMV8", 32768 + 32*8, format(tp.ctypefmt, tailr)) return shl(d, 16) end end end werror("expected address operand") end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. local function parse_template(params, template, nparams, pos) local op = tonumber(sub(template, 1, 8), 16) local n = 1 local vr = "s" -- Process each character. for p in gmatch(sub(template, 9), ".") do local q = params[n] if p == "D" then op = op + shl(parse_gpr(q), 12); n = n + 1 elseif p == "N" then op = op + shl(parse_gpr(q), 16); n = n + 1 elseif p == "S" then op = op + shl(parse_gpr(q), 8); n = n + 1 elseif p == "M" then op = op + parse_gpr(q); n = n + 1 elseif p == "d" then local r,h = parse_vr(q, vr); op = op+shl(r,12)+shl(h,22); n = n + 1 elseif p == "n" then local r,h = parse_vr(q, vr); op = op+shl(r,16)+shl(h,7); n = n + 1 elseif p == "m" then local r,h = parse_vr(q, vr); op = op+r+shl(h,5); n = n + 1 elseif p == "P" then local imm = match(q, "^#(.*)$") if imm then op = op + parse_imm12(imm) + 0x02000000 else op = op + parse_gpr(q) end n = n + 1 elseif p == "p" then op = op + parse_shift(q, true); n = n + 1 elseif p == "L" then op = parse_load(params, nparams, n, op) elseif p == "l" then op = op + parse_vload(q) elseif p == "B" then local mode, n, s = parse_label(q, false) waction("REL_"..mode, n, s, 1) elseif p == "C" then -- blx gpr vs. blx label. if match(q, "^([%w_]+):(r1?[0-9])$") or match(q, "^r(1?[0-9])$") then op = op + parse_gpr(q) else if op < 0xe0000000 then werror("unconditional instruction") end local mode, n, s = parse_label(q, false) waction("REL_"..mode, n, s, 1) op = 0xfa000000 end elseif p == "F" then vr = "s" elseif p == "G" then vr = "d" elseif p == "o" then local r, wb = match(q, "^([^!]*)(!?)$") op = op + shl(parse_gpr(r), 16) + (wb == "!" and 0x00200000 or 0) n = n + 1 elseif p == "R" then op = op + parse_reglist(q); n = n + 1 elseif p == "r" then op = op + parse_vrlist(q); n = n + 1 elseif p == "W" then op = op + parse_imm16(q); n = n + 1 elseif p == "v" then op = op + parse_imm(q, 5, 7, 0, false); n = n + 1 elseif p == "w" then local imm = match(q, "^#(.*)$") if imm then op = op + parse_imm(q, 5, 7, 0, false); n = n + 1 else op = op + shl(parse_gpr(q), 8) + 16 end elseif p == "X" then op = op + parse_imm(q, 5, 16, 0, false); n = n + 1 elseif p == "Y" then local imm = tonumber(match(q, "^#(.*)$")); n = n + 1 if not imm or shr(imm, 8) ~= 0 then werror("bad immediate operand") end op = op + shl(band(imm, 0xf0), 12) + band(imm, 0x0f) elseif p == "K" then local imm = tonumber(match(q, "^#(.*)$")); n = n + 1 if not imm or shr(imm, 16) ~= 0 then werror("bad immediate operand") end op = op + shl(band(imm, 0xfff0), 4) + band(imm, 0x000f) elseif p == "T" then op = op + parse_imm(q, 24, 0, 0, false); n = n + 1 elseif p == "s" then -- Ignored. else assert(false) end end wputpos(pos, op) end map_op[".template__"] = function(params, template, nparams) if not params then return template:gsub("%x%x%x%x%x%x%x%x", "") end -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 3 positions. if secpos+3 > maxsecpos then wflush() end local pos = wpos() local lpos, apos, spos = #actlist, #actargs, secpos local ok, err for t in gmatch(template, "[^|]+") do ok, err = pcall(parse_template, params, t, nparams, pos) if ok then return end secpos = spos actlist[lpos+1] = nil actlist[lpos+2] = nil actlist[lpos+3] = nil actargs[apos+1] = nil actargs[apos+2] = nil actargs[apos+3] = nil end error(err, 0) end ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. map_op[".long_*"] = function(params) if not params then return "imm..." end for _,p in ipairs(params) do local n = tonumber(p) if not n then werror("bad immediate `"..p.."'") end if n < 0 then n = n + 2^32 end wputw(n) if secpos+2 > maxsecpos then wflush() end end end -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = function(t, k) local v = map_coreop[k] if v then return v end local k1, cc, k2 = match(k, "^(.-)(..)([._].*)$") local cv = map_cond[cc] if cv then local v = rawget(t, k1..k2) if type(v) == "string" then local scv = format("%x", cv) return gsub(scv..sub(v, 2), "|e", "|"..scv) end end end }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
apache-2.0
UnfortunateFruit/darkstar
scripts/globals/weaponskills/tachi_enpi.lua
30
1346
----------------------------------- -- Tachi Enpi -- Great Katana weapon skill -- Skill Level: 5 -- Delivers a two-hit attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Light Gorget & Soil Gorget. -- Aligned with the Light Belt & Soil Belt. -- Element: None -- Modifiers: STR:60% -- 100%TP 200%TP 300%TP -- 1.00 1.50 2.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 2; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.6; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Spartan322/finalfrontier
gamemode/weapons/empbase.lua
3
1431
-- Copyright (c) 2014 Alex Wlach (nightmarex91@gmail.com) -- -- This file is part of Final Frontier. -- -- Final Frontier is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of -- the License, or (at your option) any later version. -- -- Final Frontier 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 Lesser General Public License -- along with Final Frontier. If not, see <http://www.gnu.org/licenses/>. local BASE = "base" WPN.BaseName = BASE WPN.Projectile = true WPN.Homing = true WPN.Speed = { 1 / 8, 1 / 4 } WPN.Lateral = { 0.4, 1 } WPN.LifeTime = { 12, 24 } WPN.PersonnelMult = 0 WPN.LifeSupportModuleMult = 0 WPN.ShieldModuleMult = 4 WPN.PowerModuleMult = 0 function WPN:IsHoming() return self.Homing end function WPN:GetSpeed() return self:_FindValue(self.Speed) end function WPN:GetLateral() return self:_FindValue(self.Lateral) end function WPN:GetLifeTime() return self:_FindValue(self.LifeTime) end if SERVER then function WPN:OnShoot(ship, target, rot) weapon.LaunchMissile(ship, self, target, rot) end end
lgpl-3.0
dpino/snabbswitch
src/apps/vhost/vhost_user.lua
9
15452
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. -- -- See http://www.virtualopensystems.com/en/solutions/guides/snabbswitch-qemu/ module(...,package.seeall) local basic_apps= require("apps.basic.basic_apps") local pcap = require("apps.pcap.pcap") local app = require("core.app") local config = require("core.config") local lib = require("core.lib") local link = require("core.link") local main = require("core.main") local memory = require("core.memory") local pci = require("lib.hardware.pci") local net_device= require("lib.virtio.net_device") local timer = require("core.timer") local ffi = require("ffi") local C = ffi.C local syscall = require("syscall") -- for FFI vhost structs require("apps.vhost.vhost_h") require("apps.vhost.vhost_user_h") assert(ffi.sizeof("struct vhost_user_msg") == 276, "ABI error") VhostUser = {} function VhostUser:new (args) local o = { state = 'init', dev = nil, msg = ffi.new("struct vhost_user_msg"), nfds = ffi.new("int[1]"), fds = ffi.new("int[?]", C.VHOST_USER_MEMORY_MAX_NREGIONS), socket_path = args.socket_path, mem_table = {}, -- process qemu messages timer process_qemu_timer = timer.new( "process qemu timer", function () self:process_qemu_requests() end, 5e8,-- 500 ms 'non-repeating' ) } self = setmetatable(o, {__index = VhostUser}) self.dev = net_device.VirtioNetDevice:new(self, args.disable_mrg_rxbuf, args.disable_indirect_desc) if args.is_server then self.listen_socket = C.vhost_user_listen(self.socket_path) assert(self.listen_socket >= 0) self.qemu_connect = self.server_connect else self.qemu_connect = self.client_connect end return self end function VhostUser:stop() -- set state self.connected = false self.vhost_ready = false -- close the socket if self.socket then C.close(self.socket) self.socket = nil end -- clear the mmap-ed memory self:free_mem_table() if self.link_down_proc then self.link_down_proc() end end function VhostUser:pull () if not self.connected then self:connect() else if self.vhost_ready then self.dev:poll_vring_receive() end end end function VhostUser:push () if self.vhost_ready then self.dev:poll_vring_transmit() end end -- Try to connect to QEMU. function VhostUser:client_connect () return C.vhost_user_connect(self.socket_path) end function VhostUser:server_connect () return C.vhost_user_accept(self.listen_socket) end function VhostUser:connect () local res = self:qemu_connect() if res >= 0 then self.socket = res self.connected = true -- activate the process timer once timer.activate(self.process_qemu_timer) end end -- vhost_user protocol request handlers. -- Table of request code -> name of handler method handler_names = { [C.VHOST_USER_NONE] = 'none', [C.VHOST_USER_GET_FEATURES] = 'get_features', [C.VHOST_USER_SET_FEATURES] = 'set_features', [C.VHOST_USER_SET_OWNER] = 'set_owner', [C.VHOST_USER_RESET_OWNER] = 'reset_owner', [C.VHOST_USER_SET_MEM_TABLE] = 'set_mem_table', [C.VHOST_USER_SET_LOG_BASE] = 'set_log_base', [C.VHOST_USER_SET_LOG_FD] = 'set_log_fd', [C.VHOST_USER_SET_VRING_NUM] = 'set_vring_num', [C.VHOST_USER_SET_VRING_ADDR] = 'set_vring_addr', [C.VHOST_USER_SET_VRING_BASE] = 'set_vring_base', [C.VHOST_USER_GET_VRING_BASE] = 'get_vring_base', [C.VHOST_USER_SET_VRING_KICK] = 'set_vring_kick', [C.VHOST_USER_SET_VRING_CALL] = 'set_vring_call', [C.VHOST_USER_SET_VRING_ERR] = 'set_vring_err', [C.VHOST_USER_GET_PROTOCOL_FEATURES] = 'get_protocol_features', [C.VHOST_USER_SET_PROTOCOL_FEATURES] = 'set_protocol_features', [C.VHOST_USER_GET_QUEUE_NUM] = 'get_queue_num', [C.VHOST_USER_SET_VRING_ENABLE] = 'set_vring_enable' } -- Process all vhost_user requests from QEMU. function VhostUser:process_qemu_requests () local msg = self.msg local stop = false if not self.connected then return end repeat local ret = C.vhost_user_receive(self.socket, msg, self.fds, self.nfds) if ret > 0 then assert(msg.request >= 0 and msg.request <= C.VHOST_USER_MAX) debug("vhost_user: request", handler_names[msg.request], msg.request) local method = self[handler_names[msg.request]] if method then method(self, msg, self.fds, self.nfds[0]) else error(string.format("vhost_user: unrecognized request: %d", msg.request)) end msg.request = -1; else stop = true if ret == 0 then print("vhost_user: Connection went down: "..self.socket_path) self:stop() end end until stop -- if we're still connected activate the timer once again if self.connected then timer.activate(self.process_qemu_timer) end end function VhostUser:none (msg) error(string.format("vhost_user: unrecognized request: %d", msg.request)) end function VhostUser:get_features (msg) msg.u64 = self.dev:get_features() msg.size = ffi.sizeof("uint64_t") -- In future add TSO4/TSO6/UFO/ECN and control channel self:reply(msg) end function VhostUser:set_features (msg) -- Check if we have an up-to-date feature to override with local features = self:update_features(tonumber(msg.u64)) self.dev:set_features(features) end function VhostUser:get_protocol_features (msg) msg.u64 = 0ULL -- no extensions supported for now msg.size = ffi.sizeof("uint64_t") self:reply(msg) end function VhostUser:set_protocol_features (msg) -- ignore protocol features for now (FIXME) end function VhostUser:get_queue_num (msg) -- ignore for now (FIXME) end -- Handle VHOST_USER_SET_VRING_ENABLE, which explicitly enables/disables the -- ring (this msg is only used if VHOST_USER_F_PROTOCOL_FEATURES is used) function VhostUser:set_vring_enable (msg) self.vhost_ready = msg.u64 ~= 0 end -- Feature cache: A kludge to be compatible with a "QEMU reconnect" patch. -- -- QEMU upstream (circa 2015) does not support the vhost-user device -- (Snabb) reconnecting to QEMU. That is unfortunate because being -- able to reconnect after a restart of either the Snabb process or -- simply a vhost-user app is very practical. -- -- Reconnect support can however be enabled in QEMU with a small patch -- [1]. Caveat: Feature negotiation does not work reliably on the new -- connections and may provide an invalid feature list. Workaround: -- Cache the most recently negotiated features for each vhost-user -- socket and reuse those when available. -- -- This is far from perfect but it is better than nothing. -- Reconnecting to QEMU VMs is very practical and enables faster -- development, restart of the Snabb process for recovery or upgrade, -- and stop/start of vhost-user app instances e.g. due to -- configuration changes. -- -- QEMU upstream seem to be determined to solve the reconnect problem -- by requiring changes to the guest drivers so that the device could -- request a reset. However, this has the undesirable properties that -- it will not be transparent to the guest and nor will it work on -- existing guest drivers. -- -- And so for now we have this cache for people who want to patch -- reconnect support into their QEMU... -- -- 1: QEMU patch: -- https://github.com/SnabbCo/qemu/commit/f393aea2301734647fdf470724433f44702e3fb9.patch -- Consider using virtio-net feature cache to override negotiated features. function VhostUser:update_features (features) local stat = syscall.stat(self.socket_path) local mtime = ("%d.%d"):format(tonumber(stat.st_mtime), tonumber(stat.st_mtime_nsec)) local cachepath = "/tmp/vhost_features_"..string.gsub(self.socket_path, "/", "__") local f = io.open(cachepath, 'r') -- Use cached features when: -- Negotiating features for the first time for this app instance -- Cache is populated -- QEMU vhost-user socket file has same timestamp as cache if not self.have_negotiated_features and f then local file_features, file_mtime = f:read('*a'):match("features:(.*) mtime:(.*)\n") f:close() if file_mtime == mtime then print(("vhost_user: Read cached features (0x%s) from %s"):format( bit.tohex(file_features), cachepath)) return tonumber(file_features) else print(("vhost_user: Skipped old feature cache in %s"):format(cachepath)) end end -- Features are now negotiated for this app instance. If they are -- negotiated again it will presumably be due to guest driver -- restart and in that case we should trust the new features rather -- than overriding them with the cache. self.have_negotiated_features = true -- Cache features after they are negotiated f = io.open(cachepath, 'w') if f then print(("vhost_user: Caching features (0x%s) in %s"):format( bit.tohex(features), cachepath)) f:write(("features:%s mtime:%s\n"):format("0x"..bit.tohex(features), mtime)) f:close() else print(("vhost_user: Failed to open cache file - %s"):format(cachepath)) end io.flush() return features end function VhostUser:set_owner (msg) end function VhostUser:reset_owner (msg) -- Disable vhost processing until the guest reattaches. self.vhost_ready = false end function VhostUser:set_vring_num (msg) self.dev:set_vring_num(msg.state.index, msg.state.num) end function VhostUser:set_vring_call (msg, fds, nfds) local idx = tonumber(bit.band(msg.u64, C.VHOST_USER_VRING_IDX_MASK)) local validfd = bit.band(msg.u64, C.VHOST_USER_VRING_NOFD_MASK) == 0 assert(idx<42) if validfd then assert(nfds == 1) self.dev:set_vring_call(idx, fds[0]) end end function VhostUser:set_vring_kick (msg, fds, nfds) local idx = tonumber(bit.band(msg.u64, C.VHOST_USER_VRING_IDX_MASK)) local validfd = bit.band(msg.u64, C.VHOST_USER_VRING_NOFD_MASK) == 0 -- Kick enables processing in vhost-user protocol self.vhost_ready = true -- Compile a new optimized fast-path for the vring processing self.dev:rejit() assert(idx < 42) if validfd then assert(nfds == 1) self.dev:set_vring_kick(idx, fds[0]) else print("vhost_user: Should start polling on virtq "..tonumber(idx)) end end function VhostUser:set_vring_addr (msg) local desc = self.dev:map_from_qemu(msg.addr.desc_user_addr) local used = self.dev:map_from_qemu(msg.addr.used_user_addr) local avail = self.dev:map_from_qemu(msg.addr.avail_user_addr) local ring = { desc = ffi.cast("struct vring_desc *", desc), used = ffi.cast("struct vring_used *", used), avail = ffi.cast("struct vring_avail *", avail) } self.dev:set_vring_addr(msg.addr.index, ring) if self.dev:ready() then if not self.vhost_ready then print("vhost_user: Connected and initialized: "..self.socket_path) end self.vhost_ready = true end end function VhostUser:set_vring_base (msg) debug("vhost_user: set_vring_base", msg.state.index, msg.state.num) self.dev:set_vring_base(msg.state.index, msg.state.num) end function VhostUser:get_vring_base (msg) msg.state.num = self.dev:get_vring_base(msg.state.index) msg.size = ffi.sizeof("struct vhost_vring_state") -- get_vring_base disables vring processing in vhost-user protocol self.vhost_ready = false self:reply(msg) end function VhostUser:set_mem_table (msg, fds, nfds) assert(nfds == msg.memory.nregions) -- ensure the mem table is empty before we start self:free_mem_table() for i = 0, msg.memory.nregions - 1 do assert(fds[i] > 0) local guest = msg.memory.regions[i].guest_phys_addr local size = msg.memory.regions[i].memory_size local qemu = msg.memory.regions[i].userspace_addr local offset = msg.memory.regions[i].mmap_offset local mmap_fd = fds[i] local mmap_size = offset + size local mmap_pointer = C.vhost_user_map_guest_memory(mmap_fd, mmap_size) local pointer = ffi.cast("char *", mmap_pointer) pointer = pointer + offset -- advance to the offset self.mem_table[i] = { mmap_pointer = mmap_pointer, mmap_size = mmap_size, guest = guest, qemu = qemu, snabb = ffi.cast("int64_t", pointer), size = tonumber(size) } C.close(mmap_fd) end self.dev:set_mem_table(self.mem_table) end function VhostUser:free_mem_table () if table.getn(self.mem_table) == 0 then return end for i = 0, table.getn(self.mem_table) do local mmap_pointer = self.mem_table[i].mmap_pointer local mmap_size = lib.align(self.mem_table[i].mmap_size, memory.huge_page_size) C.vhost_user_unmap_guest_memory(mmap_pointer, mmap_size) end self.mem_table = {} end function VhostUser:reply (req) assert(self.socket) req.flags = 5 C.vhost_user_send(self.socket, req) end function VhostUser:report() if self.connected then self.dev:report() else print("Not connected.") end end function VhostUser:rx_buffers() return self.dev:rx_buffers() end function selftest () print("selftest: vhost_user") -- Create an app network that proxies packets between a vhost_user -- port (qemu) and a sink. Create -- separate pcap traces for packets received from vhost. -- -- schema for traffic from the VM: -- -- vhost -> tee -> sink -- | -- v -- vhost pcap -- local vhost_user_sock = os.getenv("SNABB_TEST_VHOST_USER_SOCKET") if not vhost_user_sock then print("SNABB_TEST_VHOST_USER_SOCKET was not set\nTest skipped") os.exit(app.test_skipped_code) end local server = os.getenv("SNABB_TEST_VHOST_USER_SERVER") local c = config.new() config.app(c, "vhost_user", VhostUser, {socket_path=vhost_user_sock, is_server=server}) --config.app(c, "vhost_dump", pcap.PcapWriter, "vhost_vm_dump.cap") config.app(c, "vhost_tee", basic_apps.Tee) config.app(c, "sink", basic_apps.Sink) config.app(c, "source", basic_apps.Source, "250") config.app(c, "source_tee", basic_apps.Tee) config.link(c, "vhost_user.tx -> vhost_tee.input") --config.link(c, "vhost_tee.dump -> vhost_dump.input") config.link(c, "vhost_tee.traffic -> sink.in") config.link(c, "source.tx -> source_tee.input") config.link(c, "source_tee.traffic -> vhost_user.rx") app.configure(c) local vhost_user = app.app_table.vhost_user vhost_user.link_down_proc = function() main.exit(0) end local source = app.app_table.source local fn = function () local vu = app.apps.vhost_user app.report() if vhost_user.vhost_ready then vhost_user:report() end end timer.activate(timer.new("report", fn, 10e9, 'repeating')) -- Check that vhost_user:report() works in unconnected state. vhost_user:report() app.main() end function ptr (x) return ffi.cast("void*",x) end function debug (...) if _G.developer_debug then print(...) end end
apache-2.0
UnfortunateFruit/darkstar
scripts/zones/Southern_San_dOria/npcs/Corua.lua
30
2262
----------------------------------- -- Area: Southern San d'Oria -- NPC: Corua -- Only sells when San d'Oria controlls Ronfaure Region -- @ zone 230 -- @pos -66 2 -11 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/events/harvest_festivals"); require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/globals/conquest"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == 1) then if (trade:hasItemQty(532,1) == true and trade:getItemCount() == 1) then player:messageSpecial(FLYER_REFUSED); end else onHalloweenTrade(player,trade,npc); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(RONFAURE); -- player:startEvent(0x0351) - are you the chicks owner if (RegionOwner ~= SANDORIA) then player:showText(npc,CORUA_CLOSED_DIALOG); else player:showText(npc,CORUA_OPEN_DIALOG); stock = {0x1125,29, -- San d'Orian Carrot 0x114f,69, -- San d'Orian Grape 0x027f,110, -- Chestnut 0x0262,55} -- San d'Orian Flour showShop(player,SANDORIA,stock); 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
UnfortunateFruit/darkstar
scripts/zones/Windurst_Woods/npcs/Perih_Vashai.lua
17
6983
----------------------------------- -- Area: Windurst Woods -- NPC: Parih Vashai -- Starts and Finishes Quest: The Fanged One -- @zone 241 -- @pos 117 -3 92 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Windurst_Woods/TextIDs"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(1113,1) and trade:getItemCount() == 1) then -- Trade old earring (complete Rng AF2 quest) local FireAndBrimstoneCS = player:getVar("fireAndBrimstone"); if (FireAndBrimstoneCS == 5) then player:startEvent(0x0219, 0, 13360); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TheFangedOne = player:getQuestStatus(WINDURST,THE_FANGED_ONE); -- RNG flag quest local SinHunting = player:getQuestStatus(WINDURST,SIN_HUNTING); -- RNG AF1 local SinHuntingCS = player:getVar("sinHunting"); local FireAndBrimstone = player:getQuestStatus(WINDURST,FIRE_AND_BRIMSTONE); -- RNG AF2 local FireAndBrimstoneCS = player:getVar("fireAndBrimstone"); local UnbridledPassion = player:getQuestStatus(WINDURST,UNBRIDLED_PASSION); -- RNG AF3 local UnbridledPassionCS = player:getVar("unbridledPassion"); local LvL = player:getMainLvl(); local Job = player:getMainJob(); -- COP mission if(player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Louverance_s_Path") == 1) then player:startEvent(0x02AE); -- the fanged one elseif(TheFangedOne ~= QUEST_COMPLETED) then if(TheFangedOne == QUEST_AVAILABLE and player:getMainLvl() >= ADVANCED_JOB_LEVEL) then player:startEvent(0x015f); elseif(TheFangedOne == QUEST_ACCEPTED and player:hasKeyItem(OLD_TIGERS_FANG) == false) then player:startEvent(0x0160); elseif(player:hasKeyItem(OLD_TIGERS_FANG) and player:getVar("TheFangedOne_Event") ~= 1) then player:startEvent(0x0165); elseif(player:getVar("TheFangedOne_Event") == 1) then player:startEvent(0x0166); end -- sin hunting elseif(SinHunting == QUEST_AVAILABLE and Job == 11 and LvL >= 40 and SinHuntingCS == 0) then player:startEvent(0x020b); -- start RNG AF1 elseif(SinHuntingCS > 0 and SinHuntingCS < 5) then player:startEvent(0x020c); -- during quest RNG AF1 elseif(SinHuntingCS == 5) then player:startEvent(0x020f); -- complete quest RNG AF1 -- fire and brimstone elseif(SinHunting == QUEST_COMPLETED and Job == 11 and FireAndBrimstone == QUEST_AVAILABLE and FireAndBrimstoneCS == 0) then player:startEvent(0x0213); -- start RNG AF2 elseif(FireAndBrimstoneCS > 0 and FireAndBrimstoneCS < 4) then player:startEvent(0x0214); -- during RNG AF2 elseif(FireAndBrimstoneCS == 4) then player:startEvent(0x0217,0,13360,1113); -- second part RNG AF2 elseif(FireAndBrimstoneCS == 5) then player:startEvent(0x0218); -- during second part RNG AF2 -- Unbridled Passion elseif(FireAndBrimstone == QUEST_COMPLETED and Job == 11 and UnbridledPassion == QUEST_AVAILABLE and UnbridledPassion == 0) then player:startEvent(0x021d, 0, 13360); -- start RNG AF3 elseif(UnbridledPassionCS > 0 and UnbridledPassionCS < 3) then player:startEvent(0x021e); -- during RNG AF3 elseif(UnbridledPassionCS >= 3 and UnbridledPassionCS < 7) then player:startEvent(0x021e); -- during RNG AF3 elseif(UnbridledPassionCS == 7) then player:startEvent(0x0222, 0, 14099); -- complete RNG AF3 -- standard dialog else player:startEvent(0x0152); 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 == 0x015f) then player:addQuest(WINDURST,THE_FANGED_ONE); elseif(csid == 0x0165 or csid == 0x0166) then if(player:getFreeSlotsCount(0) >= 1 and player:hasItem(13117) == false) then player:delKeyItem(OLD_TIGERS_FANG); player:setVar("TheFangedOne_Event",0); player:setVar("TheFangedOne_Died",0); player:addTitle(THE_FANGED_ONE); player:addItem(13117); player:messageSpecial(ITEM_OBTAINED,13117); player:unlockJob(11); player:messageSpecial(PERIH_VASHAI_DIALOG); player:addFame(WINDURST, WIN_FAME* 30); player:completeQuest(WINDURST,THE_FANGED_ONE); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13117); player:setVar("TheFangedOne_Event",1); end elseif(csid == 0x020b) then -- start quest RNG AF1 player:addQuest(WINDURST,SIN_HUNTING); player:addKeyItem(CHIEFTAINNESS_TWINSTONE_EARRING); player:messageSpecial(KEYITEM_OBTAINED,CHIEFTAINNESS_TWINSTONE_EARRING); player:setVar("sinHunting",1); elseif(csid == 0x020f) then -- complete quest RNG AF1 if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17188); else player:addItem(17188); player:messageSpecial(ITEM_OBTAINED,17188); player:completeQuest(WINDURST,SIN_HUNTING); player:delKeyItem(CHIEFTAINNESS_TWINSTONE_EARRING); player:delKeyItem(PERCHONDS_ENVELOPE); player:setVar("sinHunting",0); end elseif(csid == 0x0213) then -- start RNG AF2 player:addQuest(WINDURST,FIRE_AND_BRIMSTONE); player:setVar("fireAndBrimstone",1); elseif(csid == 0x0217) then -- start second part RNG AF2 player:setVar("fireAndBrimstone",5); elseif(csid == 0x0219) then -- complete quest RNG AF2 if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12518); else player:tradeComplete(); player:addItem(12518); player:messageSpecial(ITEM_OBTAINED,12518); player:completeQuest(WINDURST,FIRE_AND_BRIMSTONE); player:setVar("fireAndBrimstone",0); end elseif(csid == 0x021d) then -- start RNG AF3 player:addQuest(WINDURST,UNBRIDLED_PASSION); player:setVar("unbridledPassion",1); elseif(csid == 0x0222) then -- complete quest RNG AF3 if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14099); else player:addItem(14099); player:messageSpecial(ITEM_OBTAINED,14099); player:completeQuest(WINDURST,UNBRIDLED_PASSION); player:delKeyItem(KOHS_LETTER); player:setVar("unbridledPassion",0); end elseif(csid == 0x02AE) then player:setVar("COP_Louverance_s_Path",2); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Windurst_Woods/npcs/Samigo-Pormigo.lua
13
2594
----------------------------------- -- Area: Windurst Woods -- NPC: Samigo-Pormigo -- Type: Guildworker's Union Representative -- @zone: 241 -- @pos -9.782 -5.249 -134.432 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; require("scripts/globals/keyitems"); require("scripts/globals/crafting"); require("scripts/zones/Windurst_Woods/TextIDs"); local keyitems = { [0] = { id = BONE_PURIFICATION, rank = 3, cost = 40000 }, [1] = { id = BONE_ENSORCELLMENT, rank = 3, cost = 40000 }, [2] = { id = FILING, rank = 3, cost = 10000 }, [3] = { id = WAY_OF_THE_BONEWORKER, rank = 9, cost = 20000 } }; local items = { [2] = { id = 15449, rank = 3, cost = 10000 }, [3] = { id = 13947, rank = 6, cost = 70000 }, [4] = { id = 14397, rank = 7, cost = 100000 }, [5] = { id = 142, -- Drogaroga's Fang rank = 9, cost = 150000 }, [6] = { id = 336, -- Boneworker's Signboard rank = 9, cost = 200000 }, [7] = { id = 15824, -- Bonecrafter's Ring rank = 6, cost = 80000 }, [8] = { id = 3663, -- Bonecraft Tools rank = 7, cost = 50000 }, [9] = { id = 3326, -- Boneworker's Emblem rank = 9, cost = 15000 } }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) unionRepresentativeTrade(player, npc, trade, 0x2727, 6); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) unionRepresentativeTrigger(player, 6, 0x2726, "guild_bonecraft", keyitems); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,target) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x2726) then unionRepresentativeTriggerFinish(player, option, target, 6, "guild_bonecraft", keyitems, items); elseif (csid == 0x2727) then player:messageSpecial(GP_OBTAINED, option); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Alzadaal_Undersea_Ruins/npcs/Runic_Portal.lua
17
2017
----------------------------------- -- Area: Alzadaal Undersea Ruins -- NPC: Runic Portal -- Arrapago Reef Teleporter Back to Aht Urgan Whitegate -- @pos 206.500 -1.220 33.500 72 -- @pos 206.500 -1.220 6.500 72 ----------------------------------- package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/besieged"); require("scripts/globals/teleports"); require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Z = player:getZPos(); if (Z > 27.5 and Z > 39.5) then -- Northern Stage point. if(player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES)then if(hasRunicPortal(player,6) == 1) then player:startEvent(0x0075); else player:startEvent(0x0079); end else player:messageSpecial(RESPONSE); end else if(player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES)then if(hasRunicPortal(player,6) == 1) then player:startEvent(0x0076); else player:startEvent(0x007a); end else player:messageSpecial(RESPONSE); end 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 == 0x0079 or csid == 0x007a) and option == 1) then player:addNationTeleport(AHTURHGAN,64); toChamberOfPassage(player); elseif((csid == 0x0075 or csid == 0x0076) and option == 1) then toChamberOfPassage(player); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Rabao/npcs/Maryoh_Comyujah.lua
19
2011
----------------------------------- -- Area: Rabao -- NPC: Maryoh Comyujah -- Involved in Mission: The Mithra and the Crystal (Zilart 12) -- @pos 0 8 73 247 ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Rabao/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(ZILART) == THE_MITHRA_AND_THE_CRYSTAL) then if(player:getVar("ZilartStatus") == 0) then player:startEvent(0x0051); -- Start elseif(player:hasKeyItem(SCRAP_OF_PAPYRUS)) then player:startEvent(0x0053); -- Finish elseif(player:getVar("ZilartStatus") == 2) then player:startEvent(0x0054); -- Go to hall of the gods else player:startEvent(0x0052); end elseif(player:hasCompletedMission(ZILART,THE_MITHRA_AND_THE_CRYSTAL)) then player:startEvent(0x0055); -- New standard dialog after ZM12 else player:startEvent(0x002b); -- 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 == 0x0051 and option == 1) then player:setVar("ZilartStatus",1); elseif(csid == 0x0053) then player:setVar("ZilartStatus",2); player:delKeyItem(SCRAP_OF_PAPYRUS); player:addKeyItem(CERULEAN_CRYSTAL); player:messageSpecial(KEYITEM_OBTAINED,CERULEAN_CRYSTAL); end end;
gpl-3.0
Ale32bit/Osmium
sdk/build.lua
1
1139
local args = {...} if #args < 2 then print("Usage: build <directory> <output>") return end local input = args[1] local output = args[2] -- functions readFile and explore took from Compress by Creator local function readFile(path) local file = fs.open(path,"r") local variable = file.readAll() file.close() return variable end local function explore(dir) local buffer = {} local sBuffer = fs.list(dir) for i,v in pairs(sBuffer) do if fs.isDir(dir.."/"..v) then if v ~= ".git" then buffer[v] = explore(dir.."/"..v) end else buffer[v] = readFile(dir.."/"..v) end end return buffer end local files = explore(input.."/files") local file = fs.open(input.."/config","r") local config = textutils.unserialise(file.readAll()) file.close() for k,v in pairs(config) do print(k..":"..v) end local out = {} out["config"] = config out["files"] = files out["opkData"] = { version = 1, builder = "OPK BUILDER", } if fs.exists(input.."/icon.nfp") then out["icon"] = paintutils.loadImage(input.."/icon.nfp") or nil end local f = fs.open(output,"w") f.write(textutils.serialise(out)) f.close() print("Built")
gpl-3.0
FailcoderAddons/supervillain-ui
SVUI_!Core/libs/LibArtifactData-1.0/LibArtifactData-1.0.lua
2
31293
local MAJOR, MINOR = "LibArtifactData-1.0", 21 assert(_G.LibStub, MAJOR .. " requires LibStub") local lib = _G.LibStub:NewLibrary(MAJOR, MINOR) if not lib then return end lib.callbacks = lib.callbacks or _G.LibStub("CallbackHandler-1.0"):New(lib) local Debug = function() end if _G.AdiDebug then Debug = _G.AdiDebug:Embed({}, MAJOR) end local artifactPowerData = { multiplier = { [1] = 1, [2] = 1.25, [3] = 1.5, [4] = 1.9, [5] = 2.4, [6] = 3, [7] = 3.75, [8] = 4.75, [9] = 6, [10] = 7.5, [11] = 9.5, [12] = 12, [13] = 15, [14] = 18.75, [15] = 23.5, [16] = 29.5, [17] = 37, [18] = 46.5, [19] = 58, [20] = 73, [21] = 91, [22] = 114, [23] = 143, [24] = 179, [25] = 224, [26] = 250, [27] = 1001, [28] = 1301, [29] = 1701, [30] = 2201, [31] = 2901, [32] = 3801, [33] = 4901, [34] = 6401, [35] = 8301, [36] = 10801, [37] = 14001, [38] = 18201, [39] = 23701, [40] = 30801, [41] = 40001, [42] = 160001, [43] = 208001, [44] = 270401, [45] = 351501, [46] = 457001, [47] = 594001, [48] = 772501, [49] = 1004001, [50] = 1305001, [51] = 1696501, [52] = 2205501, [53] = 2867501, [54] = 3727501, [55] = 4846001, [56] = 6300001, [57] = 6300001, [58] = 6300001, [59] = 6300001, [60] = 6300001, }, spells = { [179492] = 300, -- Libram of Divinity [179958] = 300, -- Artifact Power [179959] = 200, -- Artifact Quest Experience - Medium [179960] = 200, -- Drawn Power [181851] = 300, -- Artifact XP - Large Invasion [181852] = 200, -- Artifact XP - Small Invasion [181854] = 300, -- Artifact XP - Tomb Completion [187511] = 1000, -- XP [187536] = 300, -- Artifact Power [188542] = 7, -- Shard of Potentiation [188543] = 19, -- Crystal of Ensoulment [188627] = 19, -- Scroll of Enlightenment [188642] = 7, -- Treasured Coin [188656] = 79, -- Trembling Phylactery [190599] = 100, -- Artifact Power [192731] = 150, -- Scroll of Forgotten Knowledge [193823] = 250, -- Holy Prayer [196374] = 50, -- Artifact Shrine XP Boost [196461] = 5, -- Latent Power [196493] = 50, -- Channel Magic - Small Artifact XP [196499] = 75, -- Channel Magic - Medium Artifact XP [196500] = 100, -- Channel Magic - Large Artifact XP [199685] = 1000, -- Purified Ashbringer [201742] = 100, -- Artifact Power [204695] = 1000, -- Purple Hills of Mac'Aree [205057] = 1, -- Hidden Power [207600] = 300, -- Crystalline Demonic Eye [216876] = 10, -- Empowering [217024] = 400, -- Empowering [217026] = 25, -- Empowering [217045] = 75, -- Empowering [217055] = 100, -- Empowering [217299] = 35, -- Empowering [217300] = 35, -- Empowering [217301] = 100, -- Empowering [217355] = 100, -- Empowering [217511] = 50, -- Empowering [217512] = 60, -- Empowering [217670] = 200, -- Empowering [217671] = 400, -- Empowering [217689] = 150, -- Empowering [220547] = 100, -- Empowering [220548] = 235, -- Empowering [220549] = 480, -- Empowering [220550] = 450, -- Empowering [220551] = 530, -- Empowering [220553] = 550, -- Empowering [220784] = 200, -- Stolen Book of Artifact Lore [224139] = 25, -- Light of Elune [224544] = 25, -- Light of Elune [224583] = 25, -- Light of Elune [224585] = 25, -- Light of Elune [224593] = 25, -- Light of Elune [224595] = 25, -- Light of Elune [224608] = 25, -- Light of Elune [224610] = 25, -- Light of Elune [224633] = 25, -- Light of Elune [224635] = 25, -- Light of Elune [224641] = 25, -- Light of Elune [224643] = 25, -- Light of Elune [225897] = 100, -- Empowering [227531] = 200, -- Empowering [227535] = 300, -- Empowering [227886] = 545, -- Empowering [227889] = 210, -- Empowering [227904] = 35, -- Empowering [227905] = 55, -- Empowering [227907] = 200, -- Empowering [227941] = 150, -- Empowering [227942] = 200, -- Empowering [227943] = 465, -- Empowering [227944] = 520, -- Empowering [227945] = 165, -- Empowering [227946] = 190, -- Empowering [227947] = 210, -- Empowering [227948] = 230, -- Empowering [227949] = 475, -- Empowering [227950] = 515, -- Empowering [228067] = 400, -- Empowering [228069] = 100, -- Empowering [228078] = 500, -- Empowering [228079] = 600, -- Empowering [228080] = 250, -- Empowering [228106] = 490, -- Empowering [228107] = 250, -- Empowering [228108] = 210, -- Empowering [228109] = 170, -- Empowering [228110] = 205, -- Empowering [228111] = 245, -- Empowering [228112] = 160, -- Empowering [228130] = 125, -- Empowering [228131] = 400, -- Empowering [228135] = 250, -- Empowering [228220] = 150, -- Empowering [228310] = 50, -- Empowering [228352] = 500, -- Empowering [228422] = 175, -- Empowering [228423] = 350, -- Empowering [228436] = 170, -- Empowering [228437] = 220, -- Empowering [228438] = 195, -- Empowering [228439] = 185, -- Empowering [228440] = 190, -- Empowering [228442] = 215, -- Empowering [228443] = 180, -- Empowering [228444] = 750, -- Empowering [228647] = 400, -- Empowering [228921] = 500, -- Empowering [228955] = 25, -- Empowering [228956] = 50, -- Empowering [228957] = 35, -- Empowering [228959] = 45, -- Empowering [228960] = 20, -- Empowering [228961] = 25, -- Empowering [228962] = 40, -- Empowering [228963] = 80, -- Empowering [228964] = 150, -- Empowering [229746] = 100, -- Empowering [229747] = 200, -- Empowering [229776] = 1000, -- Empowering [229778] = 100, -- Empowering [229779] = 300, -- Empowering [229780] = 350, -- Empowering [229781] = 300, -- Empowering [229782] = 500, -- Empowering [229783] = 100, -- Empowering [229784] = 150, -- Empowering [229785] = 800, -- Empowering [229786] = 350, -- Empowering [229787] = 300, -- Empowering [229788] = 600, -- Empowering [229789] = 250, -- Empowering [229790] = 2000, -- Empowering [229791] = 1000, -- Empowering [229792] = 4000, -- Empowering [229793] = 900, -- Empowering [229794] = 1000, -- Empowering [229795] = 650, -- Empowering [229796] = 450, -- Empowering [229798] = 750, -- Empowering [229799] = 1200, -- Empowering [229803] = 500, -- Empowering [229804] = 875, -- Empowering [229805] = 1250, -- Empowering [229806] = 2500, -- Empowering [229807] = 20, -- Empowering [229857] = 100, -- Empowering [229858] = 100, -- Empowering [229859] = 1000, -- Empowering [231035] = 100, -- Empowering [231041] = 100, -- Empowering [231047] = 1000, -- Empowering [231048] = 500, -- Empowering [231337] = 600, -- Empowering [231362] = 200, -- Empowering [231453] = 500, -- Empowering [231512] = 500, -- Empowering [231538] = 250, -- Empowering [231543] = 500, -- Empowering [231544] = 100, -- Empowering [231556] = 500, -- Empowering [231581] = 250, -- Empowering [231647] = 500, -- Empowering [231669] = 500, -- Empowering [231709] = 500, -- Empowering [231727] = 800, -- Empowering [232755] = 90, -- Empowering [232832] = 95, -- Empowering [232890] = 400, -- Empowering [232994] = 100, -- Empowering [232995] = 120, -- Empowering [232996] = 180, -- Empowering [232997] = 800, -- Empowering [233030] = 150, -- Empowering [233031] = 100, -- Empowering [233204] = 500, -- Empowering [233209] = 500, -- Empowering [233211] = 800, -- Empowering [233242] = 300, -- Empowering [233243] = 1000, -- Empowering [233244] = 250, -- Empowering [233245] = 250, -- Empowering [233348] = 3000, -- Empowering [233816] = 250, -- Empowering [234045] = 250, -- Empowering [234047] = 400, -- Empowering [234048] = 500, -- Empowering [234049] = 600, -- Empowering [235245] = 175, -- Empowering [235246] = 195, -- Empowering [235247] = 220, -- Empowering [235248] = 240, -- Empowering [235256] = 250, -- Empowering [235257] = 155, -- Empowering [235266] = 500, -- Empowering [237344] = 320, -- Empowering [237345] = 380, -- Empowering [238029] = 85, -- Empowering [238030] = 115, -- Empowering [238031] = 300, -- Empowering [238032] = 400, -- Empowering [238033] = 750, -- Empowering [238252] = 85, -- Jar of Ashes [239094] = 600, -- Empowering [239095] = 650, -- Empowering [239096] = 270, -- Empowering [239097] = 225, -- Empowering [239098] = 285, -- Empowering [240331] = 200, -- Empowering [240332] = 125, -- Empowering [240333] = 600, -- Empowering [240335] = 240, -- Empowering [240337] = 360, -- Empowering [240339] = 1600, -- Empowering [240483] = 2500, -- Empowering [241156] = 175, -- Empowering [241157] = 290, -- Empowering [241158] = 325, -- Empowering [241159] = 465, -- Empowering [241160] = 300, -- Empowering [241161] = 475, -- Empowering [241162] = 540, -- Empowering [241163] = 775, -- Empowering [241164] = 375, -- Empowering [241165] = 600, -- Empowering [241166] = 675, -- Empowering [241167] = 1000, -- Empowering [241471] = 750, -- Empowering [241476] = 1000, -- Empowering [241752] = 800, -- Empowering [241753] = 255, -- Empowering [242062] = 500, -- Empowering [242116] = 3125, -- Empowering [242117] = 2150, -- Empowering [242118] = 1925, -- Empowering [242119] = 1250, -- Empowering [242564] = 1200, -- Empowering [242572] = 725, -- Empowering [242573] = 1500, -- Empowering [242575] = 5000, -- Empowering [242884] = 625, -- Empowering [242886] = 125, -- Empowering [242887] = 100, -- Empowering [242890] = 50, -- Empowering [242891] = 500, -- Empowering [242893] = 250, -- Empowering [242911] = 2000, -- Empowering [242912] = 400, -- Empowering [244814] = 600, -- Empowering [246165] = 500, -- Empowering [246166] = 525, -- Empowering [246167] = 625, -- Empowering [246168] = 275, -- Empowering [247040] = 750, -- Empowering [247075] = 250, -- Empowering [247316] = 450, -- Empowering [247319] = 125, -- Empowering [247631] = 300, -- Empowering [247633] = 700, -- Empowering [247634] = 1000, -- Empowering [248047] = 800, -- Empowering [248841] = 20, -- Empowering [248842] = 30, -- Empowering [248843] = 40, -- Empowering [248844] = 50, -- Empowering [248845] = 60, -- Empowering [248846] = 70, -- Empowering [248847] = 80, -- Empowering [248848] = 90, -- Empowering [248849] = 100, -- Empowering [250374] = 550, -- Empowering [250375] = 590, -- Empowering [250376] = 575, -- Empowering [250377] = 625, -- Empowering [250378] = 610, -- Empowering [250379] = 650, -- Empowering [251039] = 3500, -- Empowering [252078] = 200, -- Empowering [253833] = 400, -- Empowering [253834] = 600, -- Empowering [253902] = 1200, -- Empowering [253931] = 875, -- Empowering [254000] = 10000, -- Empowering [254387] = 500, -- Empowering [254593] = 200, -- Empowering [254603] = 570, -- Empowering [254608] = 630, -- Empowering [254609] = 565, -- Empowering [254610] = 635, -- Empowering [254656] = 645, -- Empowering [254657] = 745, -- Empowering [254658] = 550, -- Empowering [254659] = 650, -- Empowering [254660] = 640, -- Empowering [254661] = 560, -- Empowering [254662] = 625, -- Empowering [254663] = 575, -- Empowering [254699] = 50, -- Empowering [254761] = 750, -- Empowering [255161] = 650, -- Empowering [255162] = 550, -- Empowering [255163] = 750, -- Empowering [255165] = 800, -- Empowering [255166] = 600, -- Empowering [255167] = 900, -- Empowering [255168] = 1000, -- Empowering [255169] = 1250, -- Empowering [255170] = 1000, -- Empowering [255171] = 450, -- Empowering [255172] = 600, -- Empowering [255173] = 750, -- Empowering [255175] = 850, -- Empowering [255176] = 600, -- Empowering [255177] = 520, -- Empowering [255178] = 550, -- Empowering [255179] = 535, -- Empowering [255180] = 305, -- Empowering [255181] = 315, -- Empowering [255182] = 330, -- Empowering [255183] = 345, -- Empowering [255184] = 350, -- Empowering [255185] = 555, -- Empowering [255186] = 60, -- Empowering [255187] = 90, -- Empowering [255188] = 75, -- Empowering }, items = { [127999] = 10, -- Shard of Potentiation [128000] = 25, -- Crystal of Ensoulment [128021] = 25, -- Scroll of Enlightenment [128022] = 10, -- Treasured Coin [128026] = 150, -- Trembling Phylactery [130144] = 50, -- Crystallized Fey Darter Egg [130149] = 100, -- Carved Smolderhide Figurines [130153] = 100, -- Godafoss Essence [130159] = 100, -- Ravencrest Shield [130160] = 100, -- Vial of Pure Moonrest Water [130165] = 75, -- Heathrow Keepsake [131728] = 75, -- Urn of Malgalor's Blood [131758] = 50, -- Oversized Acorn [131778] = 50, -- Woodcarved Rabbit [131784] = 50, -- Left Half of a Locket [131785] = 50, -- Right Half of a Locket [131789] = 75, -- Handmade Mobile [132361] = 50, -- Petrified Arkhana [132923] = 50, -- Hrydshal Etching [134118] = 150, -- Cluster of Potentiation [134133] = 150, -- Jewel of Brilliance [138726] = 10, -- Shard of Potentiation } } -- local store local artifacts = {} local equippedID, viewedID, activeID artifacts.knowledgeLevel = 0 artifacts.knowledgeMultiplier = 1 -- constants local _G = _G local BACKPACK_CONTAINER = _G.BACKPACK_CONTAINER local BANK_CONTAINER = _G.BANK_CONTAINER local INVSLOT_MAINHAND = _G.INVSLOT_MAINHAND local LE_ITEM_CLASS_ARMOR = _G.LE_ITEM_CLASS_ARMOR local LE_ITEM_CLASS_WEAPON = _G.LE_ITEM_CLASS_WEAPON local LE_ITEM_QUALITY_ARTIFACT = _G.LE_ITEM_QUALITY_ARTIFACT local NUM_BAG_SLOTS = _G.NUM_BAG_SLOTS local NUM_BANKBAGSLOTS = _G.NUM_BANKBAGSLOTS -- blizzard api local aUI = _G.C_ArtifactUI local Clear = aUI.Clear local GetArtifactInfo = aUI.GetArtifactInfo local GetArtifactKnowledgeLevel = aUI.GetArtifactKnowledgeLevel or _G.nop local GetArtifactKnowledgeMultiplier = aUI.GetArtifactKnowledgeMultiplier or _G.nop local GetContainerItemInfo = _G.GetContainerItemInfo local GetContainerNumSlots = _G.GetContainerNumSlots local GetCostForPointAtRank = aUI.GetCostForPointAtRank local GetEquippedArtifactInfo = aUI.GetEquippedArtifactInfo local GetInventoryItemEquippedUnusable = _G.GetInventoryItemEquippedUnusable local GetItemInfo = _G.GetItemInfo local GetItemSpell = _G.GetItemSpell local GetNumObtainedArtifacts = aUI.GetNumObtainedArtifacts local GetNumPurchasableTraits = _G.ArtifactBarGetNumArtifactTraitsPurchasableFromXP or _G.MainMenuBar_GetNumArtifactTraitsPurchasableFromXP local GetNumRelicSlots = aUI.GetNumRelicSlots local GetPowerInfo = aUI.GetPowerInfo local GetPowers = aUI.GetPowers local GetRelicInfo = aUI.GetRelicInfo local GetRelicLockedReason = aUI.GetRelicLockedReason local GetRelicSlotRankInfo = aUI.GetRelicSlotRankInfo or _G.nop local GetSpellInfo = _G.GetSpellInfo local HasArtifactEquipped = _G.HasArtifactEquipped local IsArtifactPowerItem = _G.IsArtifactPowerItem local IsAtForge = aUI.IsAtForge local IsViewedArtifactEquipped = aUI.IsViewedArtifactEquipped local SocketContainerItem = _G.SocketContainerItem local SocketInventoryItem = _G.SocketInventoryItem -- lua api local select = _G.select local strmatch = _G.string.match local tonumber = _G.tonumber local private = {} -- private space for the event handlers lib.frame = lib.frame or _G.CreateFrame("Frame") local frame = lib.frame frame:UnregisterAllEvents() -- deactivate old versions frame:SetScript("OnEvent", function(_, event, ...) private[event](event, ...) end) frame:RegisterEvent("PLAYER_ENTERING_WORLD") local function CopyTable(tbl) if not tbl then return {} end local copy = {}; for k, v in pairs(tbl) do if ( type(v) == "table" ) then copy[k] = CopyTable(v); else copy[k] = v; end end return copy; end local function PrepareForScan() frame:UnregisterEvent("ARTIFACT_UPDATE") _G.UIParent:UnregisterEvent("ARTIFACT_UPDATE") local ArtifactFrame = _G.ArtifactFrame if ArtifactFrame and not ArtifactFrame:IsShown() then ArtifactFrame:UnregisterEvent("ARTIFACT_UPDATE") ArtifactFrame:UnregisterEvent("ARTIFACT_CLOSE") ArtifactFrame:UnregisterEvent("ARTIFACT_MAX_RANKS_UPDATE") end end local function RestoreStateAfterScan() frame:RegisterEvent("ARTIFACT_UPDATE") _G.UIParent:RegisterEvent("ARTIFACT_UPDATE") local ArtifactFrame = _G.ArtifactFrame if ArtifactFrame and not ArtifactFrame:IsShown() then Clear() ArtifactFrame:RegisterEvent("ARTIFACT_UPDATE") ArtifactFrame:RegisterEvent("ARTIFACT_CLOSE") ArtifactFrame:RegisterEvent("ARTIFACT_MAX_RANKS_UPDATE") end end local function InformEquippedArtifactChanged(artifactID) if artifactID ~= equippedID then Debug("ARTIFACT_EQUIPPED_CHANGED", artifactID, equippedID) lib.callbacks:Fire("ARTIFACT_EQUIPPED_CHANGED", artifactID, equippedID) equippedID = artifactID end end local function InformActiveArtifactChanged(artifactID) local oldActiveID = activeID if artifactID and not GetInventoryItemEquippedUnusable("player", INVSLOT_MAINHAND) then activeID = artifactID else activeID = nil end if oldActiveID ~= activeID then Debug("ARTIFACT_ACTIVE_CHANGED", activeID, oldActiveID) lib.callbacks:Fire("ARTIFACT_ACTIVE_CHANGED", activeID, oldActiveID) end end local function InformTraitsChanged(artifactID) Debug("ARTIFACT_TRAITS_CHANGED", artifactID, artifacts[artifactID].traits) lib.callbacks:Fire("ARTIFACT_TRAITS_CHANGED", artifactID, CopyTable(artifacts[artifactID].traits)) end local function StoreArtifact(itemID, altItemID, name, icon, unspentPower, numRanksPurchased, numRanksPurchasable, power, maxPower, tier) local current, isNewArtifact = artifacts[itemID], false if not current then isNewArtifact = true artifacts[itemID] = { altItemID = altItemID, name = name, icon = icon, unspentPower = unspentPower, numRanksPurchased = numRanksPurchased, numRanksPurchasable = numRanksPurchasable, power = power, maxPower = maxPower, powerForNextRank = maxPower - power, traits = {}, relics = {}, tier = tier, } else current.unspentPower = unspentPower current.numRanksPurchased = numRanksPurchased -- numRanksPurchased does not include bonus traits from relics current.numRanksPurchasable = numRanksPurchasable current.power = power current.maxPower = maxPower current.powerForNextRank = maxPower - power current.tier = tier end return isNewArtifact end local function ScanTraits(artifactID) local traits = {} local powers = GetPowers() for i = 1, #powers do local traitID = powers[i] local info = GetPowerInfo(traitID) local spellID = info.spellID if (info.currentRank) > 0 then local name, _, icon = GetSpellInfo(spellID) traits[#traits + 1] = { traitID = traitID, spellID = spellID, name = name, icon = icon, currentRank = info.currentRank, maxRank = info.maxRank, bonusRanks = info.bonusRanks, isGold = info.isGoldMedal, isStart = info.isStart, isFinal = info.isFinal, maxRanksFromTier = info.numMaxRankBonusFromTier, tier = info.tier, } end end if artifactID then artifacts[artifactID].traits = traits end return traits end local function ScanRelics(artifactID, doNotInform) local relics = artifactID and artifacts[artifactID] and artifacts[artifactID].relics or {} local changedSlots = {} local numRelicSlots = GetNumRelicSlots() for i = 1, numRelicSlots do local isLocked, name, icon, slotType, link, itemID, rank, canAddTalent = GetRelicLockedReason(i) and true or false if not isLocked then name, icon, slotType, link = GetRelicInfo(i) rank, canAddTalent = GetRelicSlotRankInfo(i) if link then itemID = strmatch(link, "item:(%d+):") end end local current = relics[i] if current then if current.itemID ~= itemID or current.isLocked ~= isLocked or current.rank ~= rank or current.canAddTalent ~= canAddTalent then changedSlots[#changedSlots + 1] = i if current.itemID ~= itemID then current.name = name current.icon = icon current.itemID = itemID current.link = link current.talents = {} end current.isLocked = isLocked current.rank = rank current.canAddTalent = canAddTalent end else changedSlots[#changedSlots + 1] = i relics[i] = { type = slotType, isLocked = isLocked, name = name, icon = icon, itemID = itemID, link = link, rank = rank, canAddTalent = canAddTalent, talents = {}, } end end if not doNotInform then for i = 1, #changedSlots do local slot = changedSlots[i] Debug("ARTIFACT_RELIC_CHANGED", viewedID, slot, relics[slot]) lib.callbacks:Fire("ARTIFACT_RELIC_CHANGED", viewedID, slot, CopyTable(relics[slot])) end end if #changedSlots > 0 or numRelicSlots == 0 then ScanTraits(viewedID) if not doNotInform then InformTraitsChanged(viewedID) end end return relics end local function GetArtifactKnowledge() if viewedID == 133755 then return end -- exclude Underlight Angler local lvl = GetArtifactKnowledgeLevel() local mult = GetArtifactKnowledgeMultiplier() if artifacts.knowledgeMultiplier ~= mult or artifacts.knowledgeLevel ~= lvl then artifacts.knowledgeLevel = lvl artifacts.knowledgeMultiplier = mult Debug("ARTIFACT_KNOWLEDGE_CHANGED", lvl, mult) lib.callbacks:Fire("ARTIFACT_KNOWLEDGE_CHANGED", lvl, mult) end end local function GetViewedArtifactData() local itemID, altItemID, name, icon, unspentPower, numRanksPurchased, _, _, _, _, _, _, tier = GetArtifactInfo() if not itemID then Debug("|cffff0000ERROR:|r", "GetArtifactInfo() returned nil.") return end viewedID = itemID Debug("GetViewedArtifactData", name, itemID) local numRanksPurchasable, power, maxPower = GetNumPurchasableTraits(numRanksPurchased, unspentPower, tier) local isNewArtifact = StoreArtifact( itemID, altItemID, name, icon, unspentPower, numRanksPurchased, numRanksPurchasable, power, maxPower, tier ) ScanRelics(viewedID, isNewArtifact) if isNewArtifact then Debug("ARTIFACT_ADDED", itemID, name) lib.callbacks:Fire("ARTIFACT_ADDED", itemID) end if IsViewedArtifactEquipped() then InformEquippedArtifactChanged(itemID) InformActiveArtifactChanged(itemID) end GetArtifactKnowledge() end local function ScanEquipped() if HasArtifactEquipped() then PrepareForScan() SocketInventoryItem(INVSLOT_MAINHAND) GetViewedArtifactData() Clear() RestoreStateAfterScan() frame:UnregisterEvent("UNIT_INVENTORY_CHANGED") end end local function ScanContainer(container, numObtained) for slot = 1, GetContainerNumSlots(container) do local _, _, _, quality, _, _, _, _, _, itemID = GetContainerItemInfo(container, slot) if quality == LE_ITEM_QUALITY_ARTIFACT then local classID = select(12, GetItemInfo(itemID)) if classID == LE_ITEM_CLASS_WEAPON or classID == LE_ITEM_CLASS_ARMOR then Debug("ARTIFACT_FOUND", "in", container, slot) SocketContainerItem(container, slot) GetViewedArtifactData() Clear() if numObtained <= lib:GetNumObtainedArtifacts() then break end end end end end local function IterateContainers(from, to, numObtained) PrepareForScan() for container = from, to do ScanContainer(container, numObtained) if numObtained <= lib:GetNumObtainedArtifacts() then break end end RestoreStateAfterScan() end local function ScanBank(numObtained) if numObtained > lib:GetNumObtainedArtifacts() then PrepareForScan() ScanContainer(BANK_CONTAINER, numObtained) RestoreStateAfterScan() end if numObtained > lib:GetNumObtainedArtifacts() then IterateContainers(NUM_BAG_SLOTS + 1, NUM_BAG_SLOTS + NUM_BANKBAGSLOTS, numObtained) end end function private.PLAYER_ENTERING_WORLD(event) frame:UnregisterEvent(event) frame:RegisterUnitEvent("UNIT_INVENTORY_CHANGED", "player") frame:RegisterEvent("BAG_UPDATE_DELAYED") frame:RegisterEvent("BANKFRAME_OPENED") frame:RegisterEvent("PLAYER_EQUIPMENT_CHANGED") frame:RegisterEvent("ARTIFACT_CLOSE") frame:RegisterEvent("ARTIFACT_XP_UPDATE") frame:RegisterUnitEvent("PLAYER_SPECIALIZATION_CHANGED", "player") if _G.UnitLevel("player") < 110 then frame:RegisterEvent("PLAYER_LEVEL_UP") end end -- bagged artifact data becomes obtainable function private.BAG_UPDATE_DELAYED(event) local numObtained = GetNumObtainedArtifacts() if numObtained <= 0 then return end -- prevent double-scanning if UNIT_INVENTORY_CHANGED fired first -- UNIT_INVENTORY_CHANGED does not fire after /reload if not equippedID and HasArtifactEquipped() then ScanEquipped() end if numObtained > lib:GetNumObtainedArtifacts() then IterateContainers(BACKPACK_CONTAINER, NUM_BAG_SLOTS, numObtained) end frame:UnregisterEvent(event) end -- equipped artifact data becomes obtainable function private.UNIT_INVENTORY_CHANGED(event) ScanEquipped(event) end function private.ARTIFACT_CLOSE() viewedID = nil end function private.ARTIFACT_UPDATE(event, newItem) Debug(event, newItem) if newItem then GetViewedArtifactData() else if not GetNumRelicSlots() then Debug("|cffff0000ERROR:|r", "artifact data unobtainable.") return end ScanRelics(viewedID) end end function private.ARTIFACT_XP_UPDATE(event) -- at the forge the player can purchase traits even for unequipped artifacts local GetInfo = IsAtForge() and GetArtifactInfo or GetEquippedArtifactInfo local itemID, _, _, _, unspentPower, numRanksPurchased, _, _, _, _, _, _, tier = GetInfo() local numRanksPurchasable, power, maxPower = GetNumPurchasableTraits(numRanksPurchased, unspentPower, tier) local artifact = artifacts[itemID] if not artifact then return lib.ForceUpdate() end local diff = unspentPower - artifact.unspentPower if numRanksPurchased ~= artifact.numRanksPurchased then -- both learning traits and artifact respec trigger ARTIFACT_XP_UPDATE -- however respec has a positive diff and learning traits has a negative one ScanTraits(itemID) InformTraitsChanged(itemID) end if diff ~= 0 then artifact.unspentPower = unspentPower artifact.power = power artifact.maxPower = maxPower artifact.numRanksPurchased = numRanksPurchased artifact.numRanksPurchasable = numRanksPurchasable artifact.powerForNextRank = maxPower - power Debug(event, itemID, diff, unspentPower, power, maxPower, maxPower - power, numRanksPurchasable) lib.callbacks:Fire("ARTIFACT_POWER_CHANGED", itemID, diff, unspentPower, power, maxPower, maxPower - power, numRanksPurchasable) end end function private.BANKFRAME_OPENED() local numObtained = GetNumObtainedArtifacts() if numObtained > lib:GetNumObtainedArtifacts() then ScanBank(numObtained) end end function private.PLAYER_LEVEL_UP(event, level) if level < 110 then return end ScanEquipped() frame:UnregisterEvent(event) end function private.PLAYER_EQUIPMENT_CHANGED(event, slot) if slot == INVSLOT_MAINHAND then local itemID = GetEquippedArtifactInfo() if itemID and not artifacts[itemID] then ScanEquipped(event) end InformEquippedArtifactChanged(itemID) InformActiveArtifactChanged(itemID) end end -- needed in case the game fails to switch artifacts function private.PLAYER_SPECIALIZATION_CHANGED(event) local itemID = GetEquippedArtifactInfo() Debug(event, itemID) InformActiveArtifactChanged(itemID) end function lib.GetActiveArtifactID() return activeID end function lib.GetArtifactInfo(_, artifactID) artifactID = tonumber(artifactID) or equippedID return artifactID, CopyTable(artifacts[artifactID]) end function lib.GetAllArtifactsInfo() return CopyTable(artifacts) end function lib.GetNumObtainedArtifacts() local numArtifacts = 0 for artifact in pairs(artifacts) do if tonumber(artifact) then numArtifacts = numArtifacts + 1 end end return numArtifacts end function lib.GetArtifactTraitInfo(_, id, artifactID) artifactID = artifactID or equippedID local artifact = artifacts[artifactID] if id and artifact then local traits = artifact.traits for i = 1, #traits do local info = traits[i] if id == info.traitID or id == info.spellID then return CopyTable(info) end end end end function lib.GetArtifactTraits(_, artifactID) artifactID = tonumber(artifactID) or equippedID local artifact = artifacts[artifactID] if not artifact then return end return artifactID, CopyTable(artifact.traits) end function lib.GetArtifactRelics(_, artifactID) artifactID = tonumber(artifactID) or equippedID local artifact = artifacts[artifactID] if not artifact then return end return artifactID, CopyTable(artifact.relics) end function lib.GetArtifactPower(_, artifactID) artifactID = tonumber(artifactID) or equippedID local artifact = artifacts[artifactID] if not artifact then return end return artifactID, artifact.unspentPower, artifact.power, artifact.maxPower, artifact.powerForNextRank, artifact.numRanksPurchased, artifact.numRanksPurchasable end function lib.GetArtifactKnowledge() return artifacts.knowledgeLevel, artifacts.knowledgeMultiplier end function lib.GetAcquiredArtifactPower(_, artifactID) local total = 0 if artifactID then local data = artifacts[artifactID] total = total + data.unspentPower local rank = 1 while rank < data.numRanksPurchased do total = total + GetCostForPointAtRank(rank, data.tier) rank = rank + 1 end return total end for itemID, data in pairs(artifacts) do if tonumber(itemID) then total = total + data.unspentPower local rank = 1 while rank < data.numRanksPurchased do total = total + GetCostForPointAtRank(rank, data.tier) rank = rank + 1 end end end return total end function lib.GetArtifactPowerFromItem(_, item) local itemID, knowledgeLevel = tonumber(item), 1 if not itemID then itemID, knowledgeLevel = item:match("item:(%d+).-(%d*):::|h") if not itemID then return end knowledgeLevel = tonumber(knowledgeLevel) or 1 end if IsArtifactPowerItem(itemID) then local _, _, spellID = GetItemSpell(itemID) return artifactPowerData.multiplier[knowledgeLevel] * (artifactPowerData.spells[spellID] or 0) elseif artifactPowerData.items[itemID] then return artifactPowerData.multiplier[knowledgeLevel] * artifactPowerData.items[itemID] end end function lib.ForceUpdate() if _G.ArtifactFrame and _G.ArtifactFrame:IsShown() then Debug("ForceUpdate", "aborted because ArtifactFrame is open.") return end local numObtained = GetNumObtainedArtifacts() if numObtained > 0 then ScanEquipped("FORCE_UPDATE") IterateContainers(BACKPACK_CONTAINER, NUM_BAG_SLOTS, numObtained) end end local function TraitsIterator(traits, index) index = index and index + 1 or 1 local trait = traits[index] if trait then return index, trait.traitID, trait.spellID, trait.name, trait.icon, trait.currentRank, trait.maxRank, trait.bonusRanks, trait.isGold, trait.isStart, trait.isFinal end end function lib.IterateTraits(_, artifactID) artifactID = tonumber(artifactID) or equippedID local artifact = artifacts[artifactID] if not artifact then return function() return end end return TraitsIterator, artifact.traits end
mit
mouhb/cjdns
contrib/lua/cjdns/udp.lua
52
2682
-- Cjdns admin module for Lua -- Written by Philip Horger common = require 'cjdns/common' UDPInterface = {} UDPInterface.__index = UDPInterface common.UDPInterface = UDPInterface function UDPInterface.new(ai, config, ptype) properties = { ai = ai, config = config or ai.config, ptype = ptype or "ai" } return setmetatable(properties, UDPInterface) end function UDPInterface:call(name, args) local func = self[name .. "_" .. self.ptype] return func(self, unpack(args)) end function UDPInterface:newBind(...) return self:call("newBind", arg) end function UDPInterface:beginConnection(...) return self:call("beginConnection", arg) end function UDPInterface:newBind_ai(address) local response, err = self.ai:auth({ q = "UDPInterface_new", bindAddress = address }) if not response then return nil, err elseif response.error ~= "none" then return nil, response.error elseif response.interfaceNumber then return response.interfaceNumber else return nil, "bad response format" end end function UDPInterface:newBind_config(address) local udpif = self.config.contents.interfaces.UDPInterface local new_interface = { bind = address, connectTo = {} } table.insert(udpif, new_interface) return (#udpif - 1), new_interface end function UDPInterface:newBind_perm(...) return self:newBind_config(unpack(arg)), self:newBind_ai(unpack(arg)) end function UDPInterface:beginConnection_ai(pubkey, addr, password, interface) local request = { q = "UDPInterface_beginConnection", publicKey = pubkey, address = addr, password = password } if interface then request.interfaceNumber = interface end local response, err = self.ai:auth(request) if not response then return nil, err elseif response.error == "none" then -- Unfortunately, no real success indicator either. return "No error" else return nil, response.error end end function UDPInterface:beginConnection_config(pubkey, addr, password, interface) local udpif = self.config.contents.interfaces.UDPInterface local connections = udpif[(interface or 0) + 1].connectTo local this_conn = { password = password, publicKey = pubkey } connections[addr] = this_conn return this_conn -- allows adding metadata fields afterwards end function UDPInterface:beginConnection_perm(...) return self:beginConnection_config(unpack(arg)), self:beginConnection_ai(unpack(arg)) end
gpl-3.0
nesstea/darkstar
scripts/zones/GM_Home/Zone.lua
32
1198
----------------------------------- -- -- Zone: GM Home (210) -- -- Some cs event info: -- 0 = Abyssea Debug -- 1 = Mogsack Debug -- ... -- 139 = Janken challenges player to "Rock, Paper, Scissors" -- ... -- 140 = Camera test. -- 141 = "Press confirm button to proceed" nonworking test. -- ----------------------------------- package.loaded["scripts/zones/GM_Home/TextIDs"] = nil; ----------------------------------- require("scripts/zones/GM_Home/TextIDs"); require("scripts/globals/zone"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; return cs; 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
UnfortunateFruit/darkstar
scripts/globals/items/yogurt_cake.lua
36
1190
----------------------------------------- -- ID: 5627 -- Item: Yogurt Cake -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- Intelligence 1 -- 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,5627); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_INT, 1); target:addMod(MOD_MPHEAL, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_INT, 1); target:delMod(MOD_MPHEAL, 6); end;
gpl-3.0
nesstea/darkstar
scripts/zones/AlTaieu/mobs/Ru_aern.lua
8
2628
----------------------------------- -- Area: Al'Taieu -- MOB: Ru_aern ----------------------------------- require("scripts/globals/missions"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) if (ally:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and ally:getVar("PromathiaStatus") == 2) then switch (mob:getID()) : caseof { -- South Tower [16912829] = function (x) ally:setVar("Ru_aern_1-1KILL",1); end, [16912830] = function (x) ally:setVar("Ru_aern_1-2KILL",1); end, [16912831] = function (x) ally:setVar("Ru_aern_1-3KILL",1); end, -- West Tower [16912832] = function (x) ally:setVar("Ru_aern_2-1KILL",1); end, [16912833] = function (x) ally:setVar("Ru_aern_2-2KILL",1); end, [16912834] = function (x) ally:setVar("Ru_aern_2-3KILL",1); end, -- East Tower [16912835] = function (x) ally:setVar("Ru_aern_3-1KILL",1); end, [16912836] = function (x) ally:setVar("Ru_aern_3-2KILL",1); end, [16912837] = function (x) ally:setVar("Ru_aern_3-3KILL",1); end, } if (ally:getVar("Ru_aern_1-1KILL") == 1 and ally:getVar("Ru_aern_1-2KILL") == 1 and ally:getVar("Ru_aern_1-3KILL") == 1) then ally:setVar("[SEA][AlTieu]SouthTower",1); clearTowerVars(killer, 1); end if (ally:getVar("Ru_aern_2-1KILL") == 1 and ally:getVar("Ru_aern_2-2KILL") == 1 and ally:getVar("Ru_aern_2-3KILL") == 1) then ally:setVar("[SEA][AlTieu]WestTower",1); clearTowerVars(killer, 2); end if (ally:getVar("Ru_aern_3-1KILL") == 1 and ally:getVar("Ru_aern_3-2KILL") == 1 and ally:getVar("Ru_aern_3-3KILL") == 1) then ally:setVar("[SEA][AlTieu]EastTower",1); clearTowerVars(killer, 3); end end end; function clearTowerVars (player, towerNum) player:setVar("Ru_aern_"..towerNum.."-1KILL",0); player:setVar("Ru_aern_"..towerNum.."-2KILL",0); player:setVar("Ru_aern_"..towerNum.."-3KILL",0); end
gpl-3.0
nesstea/darkstar
scripts/globals/weaponskills/double_thrust.lua
11
1316
----------------------------------- -- Double Thrust -- Polearm weapon skill -- Skill Level: 5 -- Delivers a two-hit attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Light Gorget. -- Aligned with the Light Belt. -- Element: None -- Modifiers: STR:30% -- 100%TP 200%TP 300%TP -- 1.00 1.50 2.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; params.numHits = 2; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.dex_wsc = 0.3; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
nesstea/darkstar
scripts/zones/Nashmau/npcs/Yoyoroon.lua
13
1691
----------------------------------- -- Area: Nashmau -- NPC: Yoyoroon -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,YOYOROON_SHOP_DIALOG); stock = {0x08BF,4940, -- Tension Spring 0x08C0,9925, -- Inhibitor 0x08C2,9925, -- Mana Booster 0x08C3,4940, -- Loudspeaker 0x08C6,4940, -- Accelerator 0x08C7,9925, -- Scope 0x08CA,9925, -- Shock Absorber 0x08CB,4940, -- Armor Plate 0x08CE,4940, -- Stabilizer 0x08CF,9925, -- Volt Gun 0x08D2,4940, -- Mana Jammer 0x08D4,9925, -- Stealth Screen 0x08D6,4940, -- Auto-Repair Kit 0x08D8,9925, -- Damage Gauge 0x08DA,4940, -- Mana Tank 0x08DC,9925} -- Mana Conserver showShop(player, STATIC, 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
filnet/MINGW-packages
mingw-w64-lua-lsqlite3/lunit.lua
60
18036
--[[-------------------------------------------------------------------------- This file is part of lunit 0.4pre (alpha). For Details about lunit look at: http://www.nessie.de/mroth/lunit/ Author: Michael Roth <mroth@nessie.de> Copyright (c) 2004 Michael Roth <mroth@nessie.de> 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. --]]-------------------------------------------------------------------------- ----------------------- -- Intialize package -- ----------------------- local P = { } lunit = P -- Import local type = type local print = print local ipairs = ipairs local pairs = pairs local string = string local table = table local pcall = pcall local xpcall = xpcall local traceback = debug.traceback local error = error local setmetatable = setmetatable local rawset = rawset local orig_assert = assert local getfenv = getfenv local setfenv = setfenv local tostring = tostring -- Start package scope setfenv(1, P) -------------------------------- -- Private data and functions -- -------------------------------- local run_testcase local do_assert, check_msg local stats = { } local testcases = { } local stats_inc, tc_mt -------------------------- -- Type check functions -- -------------------------- function is_nil(x) return type(x) == "nil" end function is_boolean(x) return type(x) == "boolean" end function is_number(x) return type(x) == "number" end function is_string(x) return type(x) == "string" end function is_table(x) return type(x) == "table" end function is_function(x) return type(x) == "function" end function is_thread(x) return type(x) == "thread" end function is_userdata(x) return type(x) == "userdata" end ---------------------- -- Assert functions -- ---------------------- function assert(assertion, msg) stats_inc("assertions") check_msg("assert", msg) do_assert(not not assertion, "assertion failed (was: "..tostring(assertion)..")", msg) -- (convert assertion to bool) return assertion end function assert_fail(msg) stats_inc("assertions") check_msg("assert_fail", msg) do_assert(false, "failure", msg) end function assert_true(actual, msg) stats_inc("assertions") check_msg("assert_true", msg) do_assert(is_boolean(actual), "true expected but was a "..type(actual), msg) do_assert(actual == true, "true expected but was false", msg) return actual end function assert_false(actual, msg) stats_inc("assertions") check_msg("assert_false", msg) do_assert(is_boolean(actual), "false expected but was a "..type(actual), msg) do_assert(actual == false, "false expected but was true", msg) return actual end function assert_equal(expected, actual, msg) stats_inc("assertions") check_msg("assert_equal", msg) do_assert(expected == actual, "expected '"..tostring(expected).."' but was '"..tostring(actual).."'", msg) return actual end function assert_not_equal(unexpected, actual, msg) stats_inc("assertions") check_msg("assert_not_equal", msg) do_assert(unexpected ~= actual, "'"..tostring(expected).."' not expected but was one", msg) return actual end function assert_match(pattern, actual, msg) stats_inc("assertions") check_msg("assert_match", msg) do_assert(is_string(pattern), "assert_match expects the pattern as a string") do_assert(is_string(actual), "expected a string to match pattern '"..pattern.."' but was a '"..type(actual).."'", msg) do_assert(not not string.find(actual, pattern), "expected '"..actual.."' to match pattern '"..pattern.."' but doesn't", msg) return actual end function assert_not_match(pattern, actual, msg) stats_inc("assertions") check_msg("assert_not_match", msg) do_assert(is_string(actual), "expected a string to not match pattern '"..pattern.."' but was a '"..type(actual).."'", msg) do_assert(string.find(actual, pattern) == nil, "expected '"..actual.."' to not match pattern '"..pattern.."' but it does", msg) return actual end function assert_nil(actual, msg) stats_inc("assertions") check_msg("assert_nil", msg) do_assert(is_nil(actual), "nil expected but was a "..type(actual), msg) return actual end function assert_not_nil(actual, msg) stats_inc("assertions") check_msg("assert_not_nil", msg) do_assert(not is_nil(actual), "nil not expected but was one", msg) return actual end function assert_boolean(actual, msg) stats_inc("assertions") check_msg("assert_boolean", msg) do_assert(is_boolean(actual), "boolean expected but was a "..type(actual), msg) return actual end function assert_not_boolean(actual, msg) stats_inc("assertions") check_msg("assert_not_boolean", msg) do_assert(not is_boolean(actual), "boolean not expected but was one", msg) return actual end function assert_number(actual, msg) stats_inc("assertions") check_msg("assert_number", msg) do_assert(is_number(actual), "number expected but was a "..type(actual), msg) return actual end function assert_not_number(actual, msg) stats_inc("assertions") check_msg("assert_not_number", msg) do_assert(not is_number(actual), "number not expected but was one", msg) return actual end function assert_string(actual, msg) stats_inc("assertions") check_msg("assert_string", msg) do_assert(is_string(actual), "string expected but was a "..type(actual), msg) return actual end function assert_not_string(actual, msg) stats_inc("assertions") check_msg("assert_not_string", msg) do_assert(not is_string(actual), "string not expected but was one", msg) return actual end function assert_table(actual, msg) stats_inc("assertions") check_msg("assert_table", msg) do_assert(is_table(actual), "table expected but was a "..type(actual), msg) return actual end function assert_not_table(actual, msg) stats_inc("assertions") check_msg("assert_not_table", msg) do_assert(not is_table(actual), "table not expected but was one", msg) return actual end function assert_function(actual, msg) stats_inc("assertions") check_msg("assert_function", msg) do_assert(is_function(actual), "function expected but was a "..type(actual), msg) return actual end function assert_not_function(actual, msg) stats_inc("assertions") check_msg("assert_not_function", msg) do_assert(not is_function(actual), "function not expected but was one", msg) return actual end function assert_thread(actual, msg) stats_inc("assertions") check_msg("assert_thread", msg) do_assert(is_thread(actual), "thread expected but was a "..type(actual), msg) return actual end function assert_not_thread(actual, msg) stats_inc("assertions") check_msg("assert_not_thread", msg) do_assert(not is_thread(actual), "thread not expected but was one", msg) return actual end function assert_userdata(actual, msg) stats_inc("assertions") check_msg("assert_userdata", msg) do_assert(is_userdata(actual), "userdata expected but was a "..type(actual), msg) return actual end function assert_not_userdata(actual, msg) stats_inc("assertions") check_msg("assert_not_userdata", msg) do_assert(not is_userdata(actual), "userdata not expected but was one", msg) return actual end function assert_error(msg, func) stats_inc("assertions") if is_nil(func) then func, msg = msg, nil end check_msg("assert_error", msg) do_assert(is_function(func), "assert_error expects a function as the last argument but it was a "..type(func)) local ok, errmsg = pcall(func) do_assert(ok == false, "error expected but no error occurred", msg) end function assert_pass(msg, func) stats_inc("assertions") if is_nil(func) then func, msg = msg, nil end check_msg("assert_pass", msg) do_assert(is_function(func), "assert_pass expects a function as the last argument but it was a "..type(func)) local ok, errmsg = pcall(func) if not ok then do_assert(ok == true, "no error expected but error was: "..errmsg, msg) end end ----------------------------------------------------------- -- Assert implementation that assumes it was called from -- -- lunit code which was called directly from user code. -- ----------------------------------------------------------- function do_assert(assertion, base_msg, user_msg) orig_assert(is_boolean(assertion)) orig_assert(is_string(base_msg)) orig_assert(is_string(user_msg) or is_nil(user_msg)) if not assertion then if user_msg then error(base_msg..": "..user_msg, 3) else error(base_msg.."!", 3) end end end ------------------------------------------- -- Checks the msg argument in assert_xxx -- ------------------------------------------- function check_msg(name, msg) orig_assert(is_string(name)) if not (is_nil(msg) or is_string(msg)) then error("lunit."..name.."() expects the optional message as a string but it was a "..type(msg).."!" ,3) end end ------------------------------------- -- Creates a new TestCase 'Object' -- ------------------------------------- function TestCase(name) do_assert(is_string(name), "lunit.TestCase() needs a string as an argument") local tc = { __lunit_name = name; __lunit_setup = nil; __lunit_tests = { }; __lunit_teardown = nil; } setmetatable(tc, tc_mt) table.insert(testcases, tc) return tc end tc_mt = { __newindex = function(tc, key, value) rawset(tc, key, value) if is_string(key) and is_function(value) then local name = string.lower(key) if string.find(name, "^test") or string.find(name, "test$") then table.insert(tc.__lunit_tests, key) elseif name == "setup" then tc.__lunit_setup = value elseif name == "teardown" then tc.__lunit_teardown = value end end end } ----------------------------------------- -- Wrap Functions in a TestCase object -- ----------------------------------------- function wrap(name, ...) if is_function(name) then table.insert({...}, 1, name) name = "Anonymous Testcase" end local tc = TestCase(name) for index, test in ipairs({...}) do tc["Test #"..index] = test end return tc end ---------------------------------- -- Runs the complete Test Suite -- ---------------------------------- function run() --------------------------- -- Initialize statistics -- --------------------------- stats.testcases = 0 -- Total number of Test Cases stats.tests = 0 -- Total number of all Tests in all Test Cases stats.run = 0 -- Number of Tests run stats.notrun = 0 -- Number of Tests not run stats.failed = 0 -- Number of Tests failed stats.warnings = 0 -- Number of Warnings (teardown) stats.errors = 0 -- Number of Errors (setup) stats.passed = 0 -- Number of Test passed stats.assertions = 0 -- Number of all assertions made in all Test in all Test Cases -------------------------------- -- Count Test Cases and Tests -- -------------------------------- stats.testcases = table.getn(testcases) for _, tc in ipairs(testcases) do stats_inc("tests" , table.getn(tc.__lunit_tests)) end ------------------ -- Print Header -- ------------------ print() print("#### Test Suite with "..stats.tests.." Tests in "..stats.testcases.." Test Cases loaded.") ------------------------ -- Run all Test Cases -- ------------------------ for _, tc in ipairs(testcases) do run_testcase(tc) end ------------------ -- Print Footer -- ------------------ print() print("#### Test Suite finished.") local msg_assertions = stats.assertions.." Assertions checked. " local msg_passed = stats.passed == stats.tests and "All Tests passed" or stats.passed.." Tests passed" local msg_failed = stats.failed > 0 and ", "..stats.failed.." failed" or "" local msg_run = stats.notrun > 0 and ", "..stats.notrun.." not run" or "" local msg_warn = stats.warnings > 0 and ", "..stats.warnings.." warnings" or "" print() print(msg_assertions..msg_passed..msg_failed..msg_run..msg_warn.."!") ----------------- -- Return code -- ----------------- if stats.passed == stats.tests then return 0 else return 1 end end ----------------------------- -- Runs a single Test Case -- ----------------------------- function run_testcase(tc) orig_assert(is_table(tc)) orig_assert(is_table(tc.__lunit_tests)) orig_assert(is_string(tc.__lunit_name)) orig_assert(is_nil(tc.__lunit_setup) or is_function(tc.__lunit_setup)) orig_assert(is_nil(tc.__lunit_teardown) or is_function(tc.__lunit_teardown)) ---------------------------------- -- Protected call to a function -- ---------------------------------- local function call(errprefix, func) orig_assert(is_string(errprefix)) orig_assert(is_function(func)) local ok, errmsg = xpcall(function() func(tc) end, traceback) if not ok then print() print(errprefix..": "..errmsg) end return ok end ------------------------------------ -- Calls setup() on the Test Case -- ------------------------------------ local function setup(testname) if tc.__lunit_setup then return call("ERROR: "..testname..": setup() failed", tc.__lunit_setup) else return true end end ------------------------------------------ -- Calls a single Test on the Test Case -- ------------------------------------------ local function run(testname) orig_assert(is_string(testname)) orig_assert(is_function(tc[testname])) local ok = call("FAIL: "..testname, tc[testname]) if not ok then stats_inc("failed") else stats_inc("passed") end return ok end --------------------------------------- -- Calls teardown() on the Test Case -- --------------------------------------- local function teardown(testname) if tc.__lunit_teardown then if not call("WARNING: "..testname..": teardown() failed", tc.__lunit_teardown) then stats_inc("warnings") end end end --------------------------------- -- Run all Tests on a TestCase -- --------------------------------- print() print("#### Running '"..tc.__lunit_name.."' ("..table.getn(tc.__lunit_tests).." Tests)...") for _, testname in ipairs(tc.__lunit_tests) do if setup(testname) then run(testname) stats_inc("run") teardown(testname) else print("WARN: Skipping '"..testname.."'...") stats_inc("notrun") end end end --------------------- -- Import function -- --------------------- function import(name) do_assert(is_string(name), "lunit.import() expects a single string as argument") local user_env = getfenv(2) -------------------------------------------------- -- Installs a specific function in the user env -- -------------------------------------------------- local function install(funcname) user_env[funcname] = P[funcname] end ---------------------------------------------------------- -- Install functions matching a pattern in the user env -- ---------------------------------------------------------- local function install_pattern(pattern) for funcname, _ in pairs(P) do if string.find(funcname, pattern) then install(funcname) end end end ------------------------------------------------------------ -- Installs assert() and all assert_xxx() in the user env -- ------------------------------------------------------------ local function install_asserts() install_pattern("^assert.*") end ------------------------------------------- -- Installs all is_xxx() in the user env -- ------------------------------------------- local function install_tests() install_pattern("^is_.+") end if name == "asserts" or name == "assertions" then install_asserts() elseif name == "tests" or name == "checks" then install_tests() elseif name == "all" then install_asserts() install_tests() install("TestCase") elseif string.find(name, "^assert.*") and P[name] then install(name) elseif string.find(name, "^is_.+") and P[name] then install(name) elseif name == "TestCase" then install("TestCase") else error("luniit.import(): invalid function '"..name.."' to import", 2) end end -------------------------------------------------- -- Installs a private environment on the caller -- -------------------------------------------------- function setprivfenv() local new_env = { } local new_env_mt = { __index = getfenv(2) } setmetatable(new_env, new_env_mt) setfenv(2, new_env) end -------------------------------------------------- -- Increments a counter in the statistics table -- -------------------------------------------------- function stats_inc(varname, value) orig_assert(is_table(stats)) orig_assert(is_string(varname)) orig_assert(is_nil(value) or is_number(value)) if not stats[varname] then return end stats[varname] = stats[varname] + (value or 1) end
bsd-3-clause
JulioC/telegram-bot
plugins/twitter.lua
632
2555
local OAuth = require "OAuth" -- EDIT data/twitter.lua with the API keys local twitter_config = load_from_file('data/twitter.lua', { -- DON'T EDIT HERE. consumer_key = "", consumer_secret = "", access_token = "", access_token_secret = "" }) local client = OAuth.new(twitter_config.consumer_key, twitter_config.consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/twitter_config.access_token" }, { OAuthToken = twitter_config.access_token, OAuthTokenSecret = twitter_config.access_token_secret }) function run(msg, matches) if twitter_config.consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/twitter.lua" end if twitter_config.consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/twitter.lua" end if twitter_config.access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/twitter.lua" end if twitter_config.access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/twitter.lua" end local twitter_url = "https://api.twitter.com/1.1/statuses/show/" .. matches[1] .. ".json" local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url) local response = json:decode(response_body) local header = "Tweet from " .. response.user.name .. " (@" .. response.user.screen_name .. ")\n" local text = response.text -- replace short URLs if response.entities.url then for k, v in pairs(response.entities.urls) do local short = v.url local long = v.expanded_url text = text:gsub(short, long) end end -- remove images local images = {} if response.extended_entities and response.extended_entities.media then for k, v in pairs(response.extended_entities.media) do local url = v.url local pic = v.media_url text = text:gsub(url, "") table.insert(images, pic) end end -- send the parts local receiver = get_receiver(msg) send_msg(receiver, header .. "\n" .. text, ok_cb, false) send_photos_from_url(receiver, images) return nil end return { description = "When user sends twitter URL, send text and images to origin. Requires OAuth Key.", usage = "", patterns = { "https://twitter.com/[^/]+/status/([0-9]+)" }, run = run }
gpl-2.0
UnfortunateFruit/darkstar
scripts/zones/Cape_Teriggan/Zone.lua
28
2719
----------------------------------- -- -- Zone: Cape_Teriggan (113) -- ----------------------------------- package.loaded[ "scripts/zones/Cape_Teriggan/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Cape_Teriggan/TextIDs"); require("scripts/globals/icanheararainbow"); require("scripts/globals/weather"); require("scripts/globals/zone"); require("scripts/globals/conquest"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17240513,17240514}; SetFieldManual(manuals); -- Kreutzet SetRespawnTime(17240413, 900, 10800); SetRegionalConquestOverseers(zone:getRegionID()) 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; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( 315.644, -1.517, -60.633, 108); end if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow cs = 0x0002; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter( player, region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0002) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0002) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow end end; ----------------------------------- -- onZoneWeatherChange ----------------------------------- function onZoneWeatherChange(weather) if (GetMobAction(17240413) == 24 and (weather == WEATHER_WIND or weather == WEATHER_GALES)) then SpawnMob(17240413); -- Kreutzet elseif (GetMobAction(17240413) == 16 and (weather ~= WEATHER_WIND and weather ~= WEATHER_GALES)) then DespawnMob(17240413); end end;
gpl-3.0
dpino/snabbswitch
src/apps/ipfix/template.lua
7
13917
-- This module implements the flow metering app, which records -- IP flows as part of an IP flow export program. module(..., package.seeall) local bit = require("bit") local ffi = require("ffi") local pf = require("pf") local consts = require("apps.lwaftr.constants") local lib = require("core.lib") local ntohs = lib.ntohs local htonl, htons = lib.htonl, lib.htons local function htonq(v) return bit.bswap(v + 0ULL) end local function ptr_to(ctype) return ffi.typeof('$*', ctype) end local debug = lib.getenv("FLOW_EXPORT_DEBUG") local IP_PROTO_TCP = 6 local IP_PROTO_UDP = 17 local IP_PROTO_SCTP = 132 -- These constants are taken from the lwaftr constants module, which -- is maybe a bad dependency but sharing code is good -- TODO: move constants somewhere else? lib? local ethertype_ipv4 = consts.ethertype_ipv4 local ethertype_ipv6 = consts.ethertype_ipv6 local ethernet_header_size = consts.ethernet_header_size local ipv6_fixed_header_size = consts.ipv6_fixed_header_size local o_ethernet_ethertype = consts.o_ethernet_ethertype local o_ipv4_total_length = consts.o_ipv4_total_length local o_ipv4_ver_and_ihl = consts.o_ipv4_ver_and_ihl local o_ipv4_proto = consts.o_ipv4_proto local o_ipv4_src_addr = consts.o_ipv4_src_addr local o_ipv4_dst_addr = consts.o_ipv4_dst_addr local o_ipv6_payload_len = consts.o_ipv6_payload_len local o_ipv6_next_header = consts.o_ipv6_next_header local o_ipv6_src_addr = consts.o_ipv6_src_addr local o_ipv6_dst_addr = consts.o_ipv6_dst_addr local function string_parser(str) local idx = 1 local quote = ('"'):byte() local ret = {} function ret.consume_upto(char) local start_idx = idx local byte = char:byte() while str:byte(idx) ~= byte do if str:byte(idx) == quote then idx = idx + 1 while str:byte(idx) ~= quote do idx = idx + 1 end end idx = idx + 1 end idx = idx + 1 return string.sub(str, start_idx, idx - 2) end function ret.is_done() return idx > str:len() end return ret end -- Parse out available IPFIX fields. local function make_ipfix_element_map() local elems = require("apps.ipfix.ipfix_information_elements_inc") local parser = string_parser(elems) local map = {} while not parser.is_done() do local id = parser.consume_upto(",") local name = parser.consume_upto(",") local data_type = parser.consume_upto(",") for i=1,8 do parser.consume_upto(",") end parser.consume_upto("\n") map[name] = { id = id, data_type = data_type } end return map end local ipfix_elements = make_ipfix_element_map() local swap_fn_env = { htons = htons, htonl = htonl, htonq = htonq } -- Create a table describing the information needed to create -- flow templates and data records. local function make_template_info(spec) -- Representations of IPFIX IEs. local ctypes = { unsigned8 = 'uint8_t', unsigned16 = 'uint16_t', unsigned32 = 'uint32_t', unsigned64 = 'uint64_t', ipv4Address = 'uint8_t[4]', ipv6Address = 'uint8_t[16]', dateTimeMilliseconds = 'uint64_t' } local bswap = { uint16_t='htons', uint32_t='htonl', uint64_t='htonq' } -- the contents of the template records we will send -- there is an ID & length for each field local length = 2 * (#spec.keys + #spec.values) local buffer = ffi.new("uint16_t[?]", length) -- octets in a data record local data_len = 0 local swap_fn = {} local function process_fields(buffer, fields, struct_def, types, swap_tmpl) for idx, name in ipairs(fields) do local entry = ipfix_elements[name] local ctype = assert(ctypes[entry.data_type], 'unimplemented: '..entry.data_type) data_len = data_len + ffi.sizeof(ctype) buffer[2 * (idx - 1)] = htons(entry.id) buffer[2 * (idx - 1) + 1] = htons(ffi.sizeof(ctype)) table.insert(struct_def, '$ '..name..';') table.insert(types, ffi.typeof(ctype)) if bswap[ctype] then table.insert(swap_fn, swap_tmpl:format(name, bswap[ctype], name)) end end end table.insert(swap_fn, 'return function(o)') local key_struct_def = { 'struct {' } local key_types = {} process_fields(buffer, spec.keys, key_struct_def, key_types, 'o.key.%s = %s(o.key.%s)') table.insert(key_struct_def, '} __attribute__((packed))') local value_struct_def = { 'struct {' } local value_types = {} process_fields(buffer + #spec.keys * 2, spec.values, value_struct_def, value_types, 'o.value.%s = %s(o.value.%s)') table.insert(value_struct_def, '} __attribute__((packed))') table.insert(swap_fn, 'end') local key_t = ffi.typeof(table.concat(key_struct_def, ' '), unpack(key_types)) local value_t = ffi.typeof(table.concat(value_struct_def, ' '), unpack(value_types)) local record_t = ffi.typeof( 'struct { $ key; $ value; } __attribute__((packed))', key_t, value_t) gen_swap_fn = loadstring(table.concat(swap_fn, '\n')) setfenv(gen_swap_fn, swap_fn_env) assert(ffi.sizeof(record_t) == data_len) return { id = spec.id, field_count = #spec.keys + #spec.values, buffer = buffer, buffer_len = length * 2, data_len = data_len, key_t = key_t, value_t = value_t, record_t = record_t, record_ptr_t = ptr_to(record_t), swap_fn = gen_swap_fn(), match = pf.compile_filter(spec.filter) } end local uint16_ptr_t = ffi.typeof('uint16_t *') local function get_ipv4_ihl(l3) return bit.band((l3 + o_ipv4_ver_and_ihl)[0], 0x0f) end local function get_ipv4_protocol(l3) return l3[o_ipv4_proto] end local function get_ipv6_next_header(l3) return l3[o_ipv6_next_header] end local function get_ipv4_src_addr_ptr(l3) return l3 + o_ipv4_src_addr end local function get_ipv4_dst_addr_ptr(l3) return l3 + o_ipv4_dst_addr end local function get_ipv6_src_addr_ptr(l3) return l3 + o_ipv6_src_addr end local function get_ipv6_dst_addr_ptr(l3) return l3 + o_ipv6_dst_addr end local function read_ipv4_src_address(l3, dst) ffi.copy(dst, get_ipv4_src_addr_ptr(l3), 4) end local function read_ipv4_dst_address(l3, dst) ffi.copy(dst, get_ipv4_dst_addr_ptr(l3), 4) end local function read_ipv6_src_address(l3, dst) ffi.copy(dst, get_ipv6_src_addr_ptr(l3), 16) end local function read_ipv6_dst_address(l3, dst) ffi.copy(dst, get_ipv6_dst_addr_ptr(l3), 16) end local function get_tcp_src_port(l4) return ntohs(ffi.cast(uint16_ptr_t, l4)[0]) end local function get_tcp_dst_port(l4) return ntohs(ffi.cast(uint16_ptr_t, l4)[1]) end v4 = make_template_info { id = 256, filter = "ip", keys = { "sourceIPv4Address", "destinationIPv4Address", "protocolIdentifier", "sourceTransportPort", "destinationTransportPort" }, values = { "flowStartMilliseconds", "flowEndMilliseconds", "packetDeltaCount", "octetDeltaCount"} } function v4.extract(pkt, timestamp, entry) local l2 = pkt.data local l3 = l2 + ethernet_header_size local ihl = get_ipv4_ihl(l3) local l4 = l3 + ihl * 4 -- Fill key. -- FIXME: Try using normal Lua assignment. read_ipv4_src_address(l3, entry.key.sourceIPv4Address) read_ipv4_dst_address(l3, entry.key.destinationIPv4Address) local prot = get_ipv4_protocol(l3) entry.key.protocolIdentifier = prot if prot == IP_PROTO_TCP or prot == IP_PROTO_UDP or prot == IP_PROTO_SCTP then entry.key.sourceTransportPort = get_tcp_src_port(l4) entry.key.destinationTransportPort = get_tcp_dst_port(l4) else entry.key.sourceTransportPort = 0 entry.key.destinationTransportPort = 0 end -- Fill value. entry.value.flowStartMilliseconds = timestamp entry.value.flowEndMilliseconds = timestamp entry.value.packetDeltaCount = 1 -- Measure bytes starting with the IP header. entry.value.octetDeltaCount = pkt.length - ethernet_header_size end function v4.accumulate(dst, new) dst.value.flowEndMilliseconds = new.value.flowEndMilliseconds dst.value.packetDeltaCount = dst.value.packetDeltaCount + 1 dst.value.octetDeltaCount = dst.value.octetDeltaCount + new.value.octetDeltaCount end function v4.tostring(entry) local ipv4 = require("lib.protocol.ipv4") local key = entry.key local protos = { [IP_PROTO_TCP]='TCP', [IP_PROTO_UDP]='UDP', [IP_PROTO_SCTP]='SCTP' } return string.format( "%s (%d) -> %s (%d) [%s]", ipv4:ntop(key.sourceIPv4Address), key.sourceTransportPort, ipv4:ntop(key.destinationIPv4Address), key.destinationTransportPort, protos[key.protocolIdentifier] or tostring(key.protocolIdentifier)) end v6 = make_template_info { id = 257, filter = "ip6", keys = { "sourceIPv6Address", "destinationIPv6Address", "protocolIdentifier", "sourceTransportPort", "destinationTransportPort" }, values = { "flowStartMilliseconds", "flowEndMilliseconds", "packetDeltaCount", "octetDeltaCount" } } function v6.extract(pkt, timestamp, entry) local l2 = pkt.data local l3 = l2 + ethernet_header_size -- TODO: handle chained headers local l4 = l3 + ipv6_fixed_header_size -- Fill key. -- FIXME: Try using normal Lua assignment. read_ipv6_src_address(l3, entry.key.sourceIPv6Address) read_ipv6_dst_address(l3, entry.key.destinationIPv6Address) local prot = get_ipv6_next_header(l3) entry.key.protocolIdentifier = prot if prot == IP_PROTO_TCP or prot == IP_PROTO_UDP or prot == IP_PROTO_SCTP then entry.key.sourceTransportPort = get_tcp_src_port(l4) entry.key.destinationTransportPort = get_tcp_dst_port(l4) else entry.key.sourceTransportPort = 0 entry.key.destinationTransportPort = 0 end -- Fill value. entry.value.flowStartMilliseconds = timestamp entry.value.flowEndMilliseconds = timestamp entry.value.packetDeltaCount = 1 -- Measure bytes starting with the IP header. entry.value.octetDeltaCount = pkt.length - ethernet_header_size end function v6.accumulate(dst, new) dst.value.flowEndMilliseconds = new.value.flowEndMilliseconds dst.value.packetDeltaCount = dst.value.packetDeltaCount + 1 dst.value.octetDeltaCount = dst.value.octetDeltaCount + new.value.octetDeltaCount end function v6.tostring(entry) local ipv6 = require("lib.protocol.ipv6") local key = entry.key local protos = { [IP_PROTO_TCP]='TCP', [IP_PROTO_UDP]='UDP', [IP_PROTO_SCTP]='SCTP' } return string.format( "%s (%d) -> %s (%d) [%s]", ipv6:ntop(key.sourceIPv6Address), key.sourceTransportPort, ipv6:ntop(key.destinationIPv6Address), key.destinationTransportPort, protos[key.protocolIdentifier] or tostring(key.protocolIdentifier)) end function selftest() print('selftest: apps.ipfix.template') local datagram = require("lib.protocol.datagram") local ether = require("lib.protocol.ethernet") local ipv4 = require("lib.protocol.ipv4") local ipv6 = require("lib.protocol.ipv6") local udp = require("lib.protocol.udp") local packet = require("core.packet") local function test(src_ip, dst_ip, src_port, dst_port) local is_ipv6 = not not src_ip:match(':') local proto = is_ipv6 and ethertype_ipv6 or ethertype_ipv4 local eth = ether:new({ src = ether:pton("00:11:22:33:44:55"), dst = ether:pton("55:44:33:22:11:00"), type = proto }) local ip if is_ipv6 then ip = ipv6:new({ src = ipv6:pton(src_ip), dst = ipv6:pton(dst_ip), next_header = IP_PROTO_UDP, ttl = 64 }) else ip = ipv4:new({ src = ipv4:pton(src_ip), dst = ipv4:pton(dst_ip), protocol = IP_PROTO_UDP, ttl = 64 }) end local udp = udp:new({ src_port = src_port, dst_port = dst_port }) local dg = datagram:new() dg:push(udp) dg:push(ip) dg:push(eth) local pkt = dg:packet() assert(v4.match(pkt.data, pkt.length) == not is_ipv6) assert(v6.match(pkt.data, pkt.length) == is_ipv6) local templ = is_ipv6 and v6 or v4 local entry = templ.record_t() local timestamp = 13 templ.extract(pkt, 13, entry) if is_ipv6 then assert(ip:src_eq(entry.key.sourceIPv6Address)) assert(ip:dst_eq(entry.key.destinationIPv6Address)) else assert(ip:src_eq(entry.key.sourceIPv4Address)) assert(ip:dst_eq(entry.key.destinationIPv4Address)) end assert(entry.key.protocolIdentifier == IP_PROTO_UDP) assert(entry.key.sourceTransportPort == src_port) assert(entry.key.destinationTransportPort == dst_port) assert(entry.value.flowStartMilliseconds == timestamp) assert(entry.value.flowEndMilliseconds == timestamp) assert(entry.value.packetDeltaCount == 1) assert(entry.value.octetDeltaCount == pkt.length - ethernet_header_size) packet.free(pkt) end for i=1, 100 do local src_ip, dst_ip if math.random(1,2) == 1 then src_ip = string.format("192.168.1.%d", math.random(1, 254)) dst_ip = string.format("10.0.0.%d", math.random(1, 254)) else src_ip = string.format("2001:4860:4860::%d", math.random(1000, 9999)) dst_ip = string.format("2001:db8::ff00:42:%d", math.random(1000, 9999)) end local src_port, dst_port = math.random(1, 65535), math.random(1, 65535) test(src_ip, dst_ip, src_port, dst_port) end print("selftest ok") end
apache-2.0
ruisebastiao/nodemcu-firmware
lua_modules/mcp23008/mcp23008.lua
81
4973
--- -- @description Expands the ESP8266's GPIO to 8 more I/O pins via I2C with the MCP23008 I/O Expander -- MCP23008 Datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/21919e.pdf -- Tested on NodeMCU 0.9.5 build 20150213. -- @date March 02, 2015 -- @author Miguel -- GitHub: https://github.com/AllAboutEE -- YouTube: https://www.youtube.com/user/AllAboutEE -- Website: http://AllAboutEE.com -------------------------------------------------------------------------------- local moduleName = ... local M = {} _G[moduleName] = M -- Constant device address. local MCP23008_ADDRESS = 0x20 -- Registers' address as defined in the MCP23008's datashseet local MCP23008_IODIR = 0x00 local MCP23008_IPOL = 0x01 local MCP23008_GPINTEN = 0x02 local MCP23008_DEFVAL = 0x03 local MCP23008_INTCON = 0x04 local MCP23008_IOCON = 0x05 local MCP23008_GPPU = 0x06 local MCP23008_INTF = 0x07 local MCP23008_INTCAP = 0x08 local MCP23008_GPIO = 0x09 local MCP23008_OLAT = 0x0A -- Default value for i2c communication local id = 0 -- pin modes for I/O direction M.INPUT = 1 M.OUTPUT = 0 -- pin states for I/O i.e. on/off M.HIGH = 1 M.LOW = 0 -- Weak pull-up resistor state M.ENABLE = 1 M.DISABLE = 0 --- -- @name write -- @description Writes one byte to a register -- @param registerAddress The register where we'll write data -- @param data The data to write to the register -- @return void ---------------------------------------------------------- local function write(registerAddress, data) i2c.start(id) i2c.address(id,MCP23008_ADDRESS,i2c.TRANSMITTER) -- send MCP's address and write bit i2c.write(id,registerAddress) i2c.write(id,data) i2c.stop(id) end --- -- @name read -- @description Reads the value of a regsiter -- @param registerAddress The reigster address from which to read -- @return The byte stored in the register ---------------------------------------------------------- local function read(registerAddress) -- Tell the MCP which register you want to read from i2c.start(id) i2c.address(id,MCP23008_ADDRESS,i2c.TRANSMITTER) -- send MCP's address and write bit i2c.write(id,registerAddress) i2c.stop(id) i2c.start(id) -- Read the data form the register i2c.address(id,MCP23008_ADDRESS,i2c.RECEIVER) -- send the MCP's address and read bit local data = 0x00 data = i2c.read(id,1) -- we expect only one byte of data i2c.stop(id) return string.byte(data) -- i2c.read returns a string so we convert to it's int value end --- --! @name begin --! @description Sets the MCP23008 device address's last three bits. -- Note: The address is defined as binary 0100[A2][A1][A0] where -- A2, A1, and A0 are defined by the connection of the pins, -- e.g. if the pins are connected all to GND then the paramter address -- will need to be 0x0. -- @param address The 3 least significant bits (LSB) of the address -- @param pinSDA The pin to use for SDA -- @param pinSCL The pin to use for SCL -- @param speed The speed of the I2C signal -- @return void --------------------------------------------------------------------------- function M.begin(address,pinSDA,pinSCL,speed) MCP23008_ADDRESS = bit.bor(MCP23008_ADDRESS,address) i2c.setup(id,pinSDA,pinSCL,speed) end --- -- @name writeGPIO -- @description Writes a byte of data to the GPIO register -- @param dataByte The byte of data to write -- @return void ---------------------------------------------------------- function M.writeGPIO(dataByte) write(MCP23008_GPIO,dataByte) end --- -- @name readGPIO -- @description reads a byte of data from the GPIO register -- @return One byte of data ---------------------------------------------------------- function M.readGPIO() return read(MCP23008_GPIO) end --- -- @name writeIODIR -- @description Writes one byte of data to the IODIR register -- @param dataByte The byte of data to write -- @return void ---------------------------------------------------------- function M.writeIODIR(dataByte) write(MCP23008_IODIR,dataByte) end --- -- @name readIODIR -- @description Reads a byte from the IODIR register -- @return The byte of data in IODIR ---------------------------------------------------------- function M.readIODIR() return read(MCP23008_IODIR) end --- -- @name writeGPPU The byte to write to the GPPU -- @description Writes a byte of data to the -- PULL-UP RESISTOR CONFIGURATION (GPPU)REGISTER -- @param databyte the value to write to the GPPU register. -- each bit in this byte is assigned to an individual GPIO pin -- @return void ---------------------------------------------------------------- function M.writeGPPU(dataByte) write(MCP23008_GPPU,dataByte) end --- -- @name readGPPU -- @description Reads the GPPU (Pull-UP resistors register) byte -- @return The GPPU byte i.e. state of all internal pull-up resistors ------------------------------------------------------------------- function M.readGPPU() return read(MCP23008_GPPU) end return M
mit
akdor1154/awesome
lib/awful/hotkeys_popup/widget.lua
1
15107
--------------------------------------------------------------------------- --- Popup widget which shows current hotkeys and their descriptions. -- -- @author Yauheni Kirylau &lt;yawghen@gmail.com&gt; -- @copyright 2014-2015 Yauheni Kirylau -- @release @AWESOME_VERSION@ -- @module awful.hotkeys_popup.widget --------------------------------------------------------------------------- local capi = { screen = screen, client = client, keygrabber = keygrabber, } local awful = require("awful") local wibox = require("wibox") local beautiful = require("beautiful") local dpi = beautiful.xresources.apply_dpi local compute_textbox_width = require("menubar").utils.compute_textbox_width -- Stripped copy of this module https://github.com/copycat-killer/lain/blob/master/util/markup.lua: local markup = {} -- Set the font. function markup.font(font, text) return '<span font="' .. tostring(font) .. '">' .. tostring(text) ..'</span>' end -- Set the foreground. function markup.fg(color, text) return '<span foreground="' .. tostring(color) .. '">' .. tostring(text) .. '</span>' end -- Set the background. function markup.bg(color, text) return '<span background="' .. tostring(color) .. '">' .. tostring(text) .. '</span>' end local widget = { title_font = "Monospace Bold 9", description_font = "Monospace 8", width = dpi(1200), height = dpi(800), border_width = beautiful.border_width or dpi(2), modifiers_color = beautiful.bg_minimize or "#555555", group_margin = dpi(6), group_rules = {}, additional_hotkeys = {}, labels = { Mod4="Super", Mod1="Alt", Escape="Esc", Insert="Ins", Delete="Del", Backspace="BackSpc", Return="Enter", Next="PgDn", Prior="PgUp", ['#108']="Alt Gr", Left='←', Up='↑', Right='→', Down='↓', ['#67']="F1", ['#68']="F2", ['#69']="F3", ['#70']="F4", ['#71']="F5", ['#72']="F6", ['#73']="F7", ['#74']="F8", ['#75']="F9", ['#76']="F10", ['#95']="F11", ['#96']="F12", ['#10']="1", ['#11']="2", ['#12']="3", ['#13']="4", ['#14']="5", ['#15']="6", ['#16']="7", ['#17']="8", ['#18']="9", ['#19']="0", ['#20']="-", ['#21']="=", Control="Ctrl" }, } --- Don't show hotkeys without descriptions. widget.hide_without_description = true --- Merge hotkey records into one if they have the same modifiers and -- description. widget.merge_duplicates = true local cached_wiboxes = {} local cached_awful_keys = nil local colors_counter = {} local colors = beautiful.xresources.get_current_theme() local group_list = {} local function get_next_color(id) id = id or "default" if colors_counter[id] then colors_counter[id] = math.fmod(colors_counter[id] + 1, 15) + 1 else colors_counter[id] = 1 end return colors["color"..tostring(colors_counter[id], 15)] end local function join_plus_sort(modifiers) if #modifiers<1 then return "none" end table.sort(modifiers) return table.concat(modifiers, '+') end local function add_hotkey(key, data, target) if widget.hide_without_description and not data.description then return end local readable_mods = {} for _, mod in ipairs(data.mod) do table.insert(readable_mods, widget.labels[mod] or mod) end local joined_mods = join_plus_sort(readable_mods) local group = data.group or "none" group_list[group] = true if not target[group] then target[group] = {} end local new_key = { key = (widget.labels[key] or key), mod = joined_mods, description = data.description } local index = data.description or "none" -- or use its hash? if not target[group][index] then target[group][index] = new_key else if widget.merge_duplicates and joined_mods == target[group][index].mod then target[group][index].key = target[group][index].key .. "/" .. new_key.key else while target[group][index] do index = index .. " " end target[group][index] = new_key end end end local function sort_hotkeys(target) -- @TODO: add sort by 12345qwertyasdf etc for group, _ in pairs(group_list) do if target[group] then local sorted_table = {} for _, key in pairs(target[group]) do table.insert(sorted_table, key) end table.sort( sorted_table, function(a,b) return (a.mod or '')..a.key<(b.mod or '')..b.key end ) target[group] = sorted_table end end end local function import_awful_keys() if cached_awful_keys then return end cached_awful_keys = {} for _, data in pairs(awful.key.hotkeys) do add_hotkey(data.key, data, cached_awful_keys) end sort_hotkeys(cached_awful_keys) end local function group_label(group, color) local textbox = wibox.widget.textbox( markup.font(widget.title_font, markup.bg( color or (widget.group_rules[group] and widget.group_rules[group].color or get_next_color("group_title") ), markup.fg(beautiful.bg_normal or "#000000", " "..group.." ") ) ) ) local margin = wibox.layout.margin() margin:set_widget(textbox) margin:set_top(widget.group_margin) return margin end local function create_wibox(s, available_groups) local wa = capi.screen[s].workarea local height = (widget.height < wa.height) and widget.height or (wa.height - widget.border_width * 2) local width = (widget.width < wa.width) and widget.width or (wa.width - widget.border_width * 2) -- arrange hotkey groups into columns local line_height = beautiful.get_font_height(widget.title_font) local group_label_height = line_height + widget.group_margin -- -1 for possible pagination: local max_height_px = height - group_label_height local column_layouts = {} for _, group in ipairs(available_groups) do local keys = cached_awful_keys[group] or widget.additional_hotkeys[group] local joined_descriptions = "" for i, key in ipairs(keys) do joined_descriptions = joined_descriptions .. key.description .. (i~=#keys and "\n" or "") end -- +1 for group label: local items_height = awful.util.linecount(joined_descriptions) * line_height + group_label_height local current_column local available_height_px = max_height_px local add_new_column = true for i, column in ipairs(column_layouts) do if ((column.height_px + items_height) < max_height_px) or (i == #column_layouts and column.height_px < max_height_px / 2) then current_column = column add_new_column = false available_height_px = max_height_px - current_column.height_px break end end local overlap_leftovers if items_height > available_height_px then local new_keys = {} overlap_leftovers = {} -- +1 for group title and +1 for possible hyphen (v): local available_height_items = (available_height_px - group_label_height*2) / line_height for i=1,#keys do table.insert(((i<available_height_items) and new_keys or overlap_leftovers), keys[i]) end keys = new_keys table.insert(keys, {key=markup.fg(widget.modifiers_color, "▽"), description=""}) end if not current_column then current_column = {layout=wibox.layout.fixed.vertical()} end current_column.layout:add(group_label(group)) local function insert_keys(_keys, _add_new_column) local max_label_width = 0 local max_label_content = "" local joined_labels = "" for i, key in ipairs(_keys) do local length = string.len(key.key or '') + string.len(key.description or '') local modifiers = key.mod if not modifiers or modifiers == "none" then modifiers = "" else length = length + string.len(modifiers) + 1 -- +1 for "+" character modifiers = markup.fg(widget.modifiers_color, modifiers.."+") end local rendered_hotkey = markup.font(widget.title_font, modifiers .. (key.key or "") .. " " ) .. markup.font(widget.description_font, key.description or "" ) if length > max_label_width then max_label_width = length max_label_content = rendered_hotkey end joined_labels = joined_labels .. rendered_hotkey .. (i~=#_keys and "\n" or "") end current_column.layout:add(wibox.widget.textbox(joined_labels)) local max_width = compute_textbox_width(wibox.widget.textbox(max_label_content), s) + widget.group_margin if not current_column.max_width or max_width > current_column.max_width then current_column.max_width = max_width end -- +1 for group label: current_column.height_px = (current_column.height_px or 0) + awful.util.linecount(joined_labels)*line_height + group_label_height if _add_new_column then table.insert(column_layouts, current_column) end end insert_keys(keys, add_new_column) if overlap_leftovers then current_column = {layout=wibox.layout.fixed.vertical()} insert_keys(overlap_leftovers, true) end end -- arrange columns into pages local available_width_px = width local pages = {} local columns = wibox.layout.fixed.horizontal() for _, item in ipairs(column_layouts) do if item.max_width > available_width_px then columns.widgets[#columns.widgets]['widget']:add( group_label("PgDn - Next Page", beautiful.fg_normal) ) table.insert(pages, columns) columns = wibox.layout.fixed.horizontal() available_width_px = width - item.max_width local old_widgets = item.layout.widgets item.layout.widgets = {group_label("PgUp - Prev Page", beautiful.fg_normal)} awful.util.table.merge(item.layout.widgets, old_widgets) else available_width_px = available_width_px - item.max_width end local column_margin = wibox.layout.margin() column_margin:set_widget(item.layout) column_margin:set_left(widget.group_margin) columns:add(column_margin) end table.insert(pages, columns) local mywibox = wibox({ ontop = true, opacity = beautiful.notification_opacity or 1, border_width = widget.border_width, border_color = beautiful.fg_normal, }) mywibox:geometry({ x = wa.x + math.floor((wa.width - width - widget.border_width*2) / 2), y = wa.y + math.floor((wa.height - height - widget.border_width*2) / 2), width = width, height = height, }) mywibox:set_widget(pages[1]) mywibox:buttons(awful.util.table.join( awful.button({ }, 1, function () mywibox.visible=false end), awful.button({ }, 3, function () mywibox.visible=false end) )) local widget_obj = {} widget_obj.current_page = 1 widget_obj.wibox = mywibox function widget_obj:page_next() if self.current_page == #pages then return end self.current_page = self.current_page + 1 self.wibox:set_widget(pages[self.current_page]) end function widget_obj:page_prev() if self.current_page == 1 then return end self.current_page = self.current_page - 1 self.wibox:set_widget(pages[self.current_page]) end function widget_obj:show() self.wibox.visible = true end function widget_obj:hide() self.wibox.visible = false end return widget_obj end --- Show popup with hotkeys help. -- @tparam[opt] client c Client. -- @tparam[opt] screen s Screen. function widget.show_help(c, s) import_awful_keys() c = c or capi.client.focus s = s or (c and c.screen or awful.screen.focused()) local available_groups = {} for group, _ in pairs(group_list) do local need_match for group_name, data in pairs(widget.group_rules) do if group_name==group and ( data.rule or data.rule_any or data.except or data.except_any ) then if not c or not awful.rules.matches(c, { rule=data.rule, rule_any=data.rule_any, except=data.except, except_any=data.except_any }) then need_match = true break end end end if not need_match then table.insert(available_groups, group) end end local joined_groups = join_plus_sort(available_groups) if not cached_wiboxes[s] then cached_wiboxes[s] = {} end if not cached_wiboxes[s][joined_groups] then cached_wiboxes[s][joined_groups] = create_wibox(s, available_groups) end local help_wibox = cached_wiboxes[s][joined_groups] help_wibox:show() return capi.keygrabber.run(function(_, key, event) if event == "release" then return end if key then if key == "Next" then help_wibox:page_next() elseif key == "Prior" then help_wibox:page_prev() else capi.keygrabber.stop() help_wibox:hide() end end end) end --- Add hotkey descriptions for third-party applications. -- @tparam table hotkeys Table with bindings, -- see `awful.hotkeys_popup.key.vim` as an example. function widget.add_hotkeys(hotkeys) for group, bindings in pairs(hotkeys) do for _, binding in ipairs(bindings) do local modifiers = binding.modifiers local keys = binding.keys for key, description in pairs(keys) do add_hotkey(key, { mod=modifiers, description=description, group=group}, widget.additional_hotkeys ) end end end sort_hotkeys(widget.additional_hotkeys) end return widget -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
nesstea/darkstar
scripts/zones/Nashmau/npcs/Chichiroon.lua
13
1280
----------------------------------- -- Area: Nashmau -- NPC: Chichiroon -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CHICHIROON_SHOP_DIALOG); stock = {0x1579,99224, --Bolter's Die 0x157a,85500, --Caster's Die 0x157b,97350, --Courser's Die 0x157c,100650, --Blitzer's Die 0x157d,109440, --Tactician's Die 0x157e,116568} --Allies' Die showShop(player, STATIC, 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
DaemonSnake/vlc
share/lua/sd/fmc.lua
122
2554
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Fabio Ritrovato <sephiroth87 at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] require "simplexml" function descriptor() return { title="Free Music Charts" } end function main() local tree = simplexml.parse_url("http://www.archive.org/download/freemusiccharts.songs/fmc.xml") for _, show_node in ipairs( tree.children ) do simplexml.add_name_maps( show_node ) local node = vlc.sd.add_node( {title=show_node.children_map["description"][1].children[1]} ) if tonumber( show_node.children_map["songcount"][1].children[1] ) > 0 then local songs_node = node:add_node( {title="Songs"} ) for _, song_node in ipairs( show_node.children_map["songs"][1].children ) do _, _, artist, title = string.find( song_node.children_map["name"][1].children[1], "(.+)%s*-%s*(.+)" ) local rank = song_node.children_map["rank"][1].children[1] if rank ~= nil then rank = "Rank: " .. rank else rank = "Rank: N/A" end local votes = song_node.children_map["votes"][1].children[1] if votes ~= nil then votes = "Votes: " .. votes else votes = "Votes: N/A" end songs_node:add_subitem( {path=song_node.children_map["url"][1].children[1],title=title,artist=artist,description=rank .. ", " .. votes} ) end end node:add_subitem( {title=show_node.children_map["date"][1].children[1] .. " MP3 Podcast",path=show_node.children_map["podcastmp3"][1].children[1]} ) node:add_subitem( {title=show_node.children_map["date"][1].children[1] .. " OGG Podcast",path=show_node.children_map["podcastogg"][1].children[1]} ) end end
gpl-2.0
Bierbuikje/Mr.Green-MTA-Resources
resources/[gameplay]/-shaders-nitro/client.lua
4
1564
--------------------------------------------------------------------------------- -- -- Nitro shader -- -- --------------------------------------------------------------------------------- addEvent("e_ToggleNitroColor", true) function toggleNitroColor(bln,hex) if bln and hex then if not nitroShader then nitroShader = dxCreateShader("nitro.fx") end local alpha,red,green,blue = getColorFromString(hex) updateNitroColor(red,green,blue) elseif not bln then resetNitroColor() end end addEventHandler("e_ToggleNitroColor", resourceRoot, toggleNitroColor) addEventHandler("onClientResourceStart",resourceRoot, function() end) -- This function will set the new color of the nitro function updateNitroColor(r,g,b) if nitroShader then if r and g and b then engineApplyShaderToWorldTexture (nitroShader,"smoke") dxSetShaderValue (nitroShader, "gNitroColor", r/255, g/255, b/255 ) end end end -- This function will reset the nitro back to the original function resetNitroColor() if nitroShader then engineRemoveShaderFromWorldTexture(nitroShader,"smoke") end end -- Example command use addCommandHandler("nitro", function(command,r,g,b) if r and g and b then local r,g,b = tonumber(r),tonumber(g),tonumber(b) if r <= 255 and g <= 255 and b <= 255 then updateNitroColor(r,g,b) outputChatBox("Nitro color updated!",255,255,255,true) else outputChatBox("Colors must be between 0 and 255",255,255,255,true) end else resetNitroColor() outputChatBox("Nitro color reset to original!",255,255,255,true) end end)
mit
caohongtao/quick-cocos-demo
runtime/ios/PrebuiltRuntimeLua.app/src/cocos/cocostudio/DeprecatedCocoStudioFunc.lua
39
3421
--tip local function deprecatedTip(old_name,new_name) print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********") end --functions of GUIReader will be deprecated begin local GUIReaderDeprecated = { } function GUIReaderDeprecated.shareReader() deprecatedTip("GUIReader:shareReader","ccs.GUIReader:getInstance") return ccs.GUIReader:getInstance() end GUIReader.shareReader = GUIReaderDeprecated.shareReader function GUIReaderDeprecated.purgeGUIReader() deprecatedTip("GUIReader:purgeGUIReader","ccs.GUIReader:destroyInstance") return ccs.GUIReader:destroyInstance() end GUIReader.purgeGUIReader = GUIReaderDeprecated.purgeGUIReader --functions of GUIReader will be deprecated end --functions of SceneReader will be deprecated begin local SceneReaderDeprecated = { } function SceneReaderDeprecated.sharedSceneReader() deprecatedTip("SceneReader:sharedSceneReader","ccs.SceneReader:getInstance") return ccs.SceneReader:getInstance() end SceneReader.sharedSceneReader = SceneReaderDeprecated.sharedSceneReader function SceneReaderDeprecated.purgeSceneReader(self) deprecatedTip("SceneReader:purgeSceneReader","ccs.SceneReader:destroyInstance") return self:destroyInstance() end SceneReader.purgeSceneReader = SceneReaderDeprecated.purgeSceneReader --functions of SceneReader will be deprecated end --functions of ccs.GUIReader will be deprecated begin local CCSGUIReaderDeprecated = { } function CCSGUIReaderDeprecated.purgeGUIReader() deprecatedTip("ccs.GUIReader:purgeGUIReader","ccs.GUIReader:destroyInstance") return ccs.GUIReader:destroyInstance() end ccs.GUIReader.purgeGUIReader = CCSGUIReaderDeprecated.purgeGUIReader --functions of ccs.GUIReader will be deprecated end --functions of ccs.ActionManagerEx will be deprecated begin local CCSActionManagerExDeprecated = { } function CCSActionManagerExDeprecated.destroyActionManager() deprecatedTip("ccs.ActionManagerEx:destroyActionManager","ccs.ActionManagerEx:destroyInstance") return ccs.ActionManagerEx:destroyInstance() end ccs.ActionManagerEx.destroyActionManager = CCSActionManagerExDeprecated.destroyActionManager --functions of ccs.ActionManagerEx will be deprecated end --functions of ccs.SceneReader will be deprecated begin local CCSSceneReaderDeprecated = { } function CCSSceneReaderDeprecated.destroySceneReader(self) deprecatedTip("ccs.SceneReader:destroySceneReader","ccs.SceneReader:destroyInstance") return self:destroyInstance() end ccs.SceneReader.destroySceneReader = CCSSceneReaderDeprecated.destroySceneReader --functions of ccs.SceneReader will be deprecated end --functions of CCArmatureDataManager will be deprecated begin local CCArmatureDataManagerDeprecated = { } function CCArmatureDataManagerDeprecated.sharedArmatureDataManager() deprecatedTip("CCArmatureDataManager:sharedArmatureDataManager","ccs.ArmatureDataManager:getInstance") return ccs.ArmatureDataManager:getInstance() end CCArmatureDataManager.sharedArmatureDataManager = CCArmatureDataManagerDeprecated.sharedArmatureDataManager function CCArmatureDataManagerDeprecated.purge() deprecatedTip("CCArmatureDataManager:purge","ccs.ArmatureDataManager:destoryInstance") return ccs.ArmatureDataManager:destoryInstance() end CCArmatureDataManager.purge = CCArmatureDataManagerDeprecated.purge --functions of CCArmatureDataManager will be deprecated end
apache-2.0