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 |
|---|---|---|---|---|---|
DiNaSoR/Angel_Arena | game/angel_arena/scripts/vscripts/mechanics/ai/boss/adp/adp_aicore.lua | 1 | 2653 | -- 初始化AI核心
AICore = AICore or {}
-- 获取随机目标
-- entity = 攻击者
-- range = 获取范围,下同
function AICore:RandomEnemyHeroInRange( entity, range )
local enemies = FindUnitsInRadius( entity:GetTeam(), entity:GetOrigin(), nil, range, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, 0, 0, false )
if #enemies > 0 then
local index = RandomInt( 1, #enemies )
return enemies[index]
else
return nil
end
end
-- 获取最弱目标
function AICore:WeakestEnemyHeroInRange( entity, range )
local enemies = FindUnitsInRadius( entity:GetTeam(), entity:GetOrigin(), nil, range, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, 0, 0, false )
local minHP = nil
local target = nil
for _,enemy in pairs(enemies) do
local distanceToEnemy = (entity:GetOrigin() - enemy:GetOrigin()):Length()
local HP = enemy:GetHealth()
if enemy:IsAlive() and (minHP == nil or HP < minHP) and distanceToEnemy < range then
minHP = HP
target = enemy
end
end
return target
end
-- 获取最强目标
function AICore:StrongestEnemyHeroInRange( entity, range )
local enemies = FindUnitsInRadius( entity:GetTeam(), entity:GetOrigin(), nil, range, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, 0, 0, false )
local maxHP = nil
local target = nil
for _,enemy in pairs(enemies) do
local distanceToEnemy = (entity:GetOrigin() - enemy:GetOrigin()):Length()
local HP = enemy:GetHealth()
if enemy:IsAlive() and (maxHP == nil or HP > maxHP) and distanceToEnemy < range then
maxHP = HP
target = enemy
end
end
return target
end
-- 获取最近目标
function AICore:NearestEnemyHeroInRange( entity, range )
local enemies = FindUnitsInRadius( entity:GetTeam(), entity:GetOrigin(), nil, range, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, 0, 0, false )
local minRange = 100000
local target = nil
for _,enemy in pairs(enemies) do
local distanceToEnemy = (entity:GetOrigin() - enemy:GetOrigin()):Length()
if distanceToEnemy < minRange then
minRange = distanceToEnemy
target = enemy
end
end
return target
end
-- 返回正在攻击的目标
function AICore:GetAttackingEnemy( entity )
return entity:GetAttackTarget()
end
-- BOSS放技能的警示
-- msg = 警示消息
-- dur = 持续时间
function AICore:ShowWarningMessage( msg , dur )
if not msg then return end
FireGameEvent('show_center_message',
{
message = msg,
duration = dur
})
end | mit |
ArnaudSiebens/AutoActionCam | Libs/AceGUI-3.0/widgets/AceGUIWidget-Heading.lua | 68 | 2216 | --[[-----------------------------------------------------------------------------
Heading Widget
-------------------------------------------------------------------------------]]
local Type, Version = "Heading", 20
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 pairs = pairs
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetText()
self:SetFullWidth()
self:SetHeight(18)
end,
-- ["OnRelease"] = nil,
["SetText"] = function(self, text)
self.label:SetText(text or "")
if text and text ~= "" then
self.left:SetPoint("RIGHT", self.label, "LEFT", -5, 0)
self.right:Show()
else
self.left:SetPoint("RIGHT", -3, 0)
self.right:Hide()
end
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
frame:Hide()
local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontNormal")
label:SetPoint("TOP")
label:SetPoint("BOTTOM")
label:SetJustifyH("CENTER")
local left = frame:CreateTexture(nil, "BACKGROUND")
left:SetHeight(8)
left:SetPoint("LEFT", 3, 0)
left:SetPoint("RIGHT", label, "LEFT", -5, 0)
left:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
left:SetTexCoord(0.81, 0.94, 0.5, 1)
local right = frame:CreateTexture(nil, "BACKGROUND")
right:SetHeight(8)
right:SetPoint("RIGHT", -3, 0)
right:SetPoint("LEFT", label, "RIGHT", 5, 0)
right:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
right:SetTexCoord(0.81, 0.94, 0.5, 1)
local widget = {
label = label,
left = left,
right = right,
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)
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/Port_Windurst/npcs/Gold_Skull.lua | 17 | 2228 | -----------------------------------
-- Area: Port Windurst
-- NPC: Gold Skull
-- Mission NPC
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(BASTOK) ~= 255) then
currentMission = player:getCurrentMission(BASTOK);
missionStatus = player:getVar("MissionStatus");
if (player:hasKeyItem(SWORD_OFFERING)) then
player:startEvent(0x0035);
elseif (player:hasKeyItem(KINDRED_REPORT)) then
player:startEvent(0x0044);
elseif (currentMission == THE_EMISSARY_WINDURST2) then
if (missionStatus == 7) then
player:startEvent(0x003e);
elseif (missionStatus == 8) then
player:showText(npc,GOLD_SKULL_DIALOG + 27);
elseif (missionStatus == 9) then
player:startEvent(0x0039);
end
elseif (currentMission == THE_EMISSARY_WINDURST) then
if (missionStatus == 2) then
player:startEvent(0x0032);
elseif (missionStatus == 12) then
player:startEvent(0x0036);
elseif (missionStatus == 14) then
player:showText(npc,GOLD_SKULL_DIALOG);
elseif (missionStatus == 15) then
player:startEvent(0x0039);
end
else
player:startEvent(0x002b);
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 == 0x0035) then
player:addKeyItem(DULL_SWORD);
player:messageSpecial(KEYITEM_OBTAINED,DULL_SWORD);
player:delKeyItem(SWORD_OFFERING);
end
end; | gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/Bastok_Mines/npcs/Abd-al-Raziq.lua | 42 | 2636 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Abd-al-Raziq
-- Type: Alchemy Guild Master
-- @pos 126.768 1.017 -0.234 234
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local newRank = tradeTestItem(player,npc,trade,SKILL_ALCHEMY);
if (newRank ~= 0) then
player:setSkillRank(SKILL_ALCHEMY,newRank);
player:startEvent(0x0079,0,0,0,0,newRank);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local getNewRank = 0;
local craftSkill = player:getSkillLevel(SKILL_ALCHEMY);
local testItem = getTestItem(player,npc,SKILL_ALCHEMY);
local guildMember = isGuildMember(player,1);
if (guildMember == 1) then guildMember = 150995375; end
if (canGetNewRank(player,craftSkill,SKILL_ALCHEMY) == 1) then getNewRank = 100; end
if (player:getCurrentMission(ASA) == THAT_WHICH_CURDLES_BLOOD
and guildMember == 150995375 and getNewRank ~= 100) then
local item = 0;
local asaStatus = player:getVar("ASA_Status");
-- TODO: Other Enfeebling Kits
if (asaStatus == 0) then
item = 2779;
else
printf("Error: Unknown ASA Status Encountered <%u>", asaStatus);
end
-- The Parameters are Item IDs for the Recipe
player:startEvent(0x024e, item, 2774, 929, 4103, 2777, 4103);
else
player:startEvent(0x0078,testItem,getNewRank,30,guildMember,44,0,0,0);
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 == 0x0078 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_ALCHEMY);
end
end
end; | gpl-3.0 |
fw867/ntopng | scripts/lua/get_flow_data.lua | 1 | 1797 | --
-- (C) 2013-14 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
require "flow_utils"
sendHTTPHeader('text/html; charset=utf-8')
local debug = debug_flow_data
flow_key = _GET["flow_key"]
if(flow_key == nil) then
flow = nil
else
interface.find(ifname)
flow = interface.findFlowByKey(tonumber(flow_key))
end
throughput_type = getThroughputType()
if(flow == nil) then
print('{}')
else
print ("{ \"column_duration\" : \"" .. secondsToTime(flow["duration"]))
print ("\", \"column_bytes\" : \"" .. bytesToSize(flow["bytes"]) .. "")
if ( (flow["throughput_trend_"..throughput_type] ~= nil) and
(flow["throughput_trend_"..throughput_type] > 0)
) then
if (throughput_type == "pps") then
print ("\", \"column_thpt\" : \"" .. pktsToSize(flow["throughput_pps"]).. " ")
else
print ("\", \"column_thpt\" : \"" .. bitsToSize(8*flow["throughput_bps"]).. " ")
end
if(flow["throughput_trend_"..throughput_type] == 1) then
print("<i class='fa fa-arrow-up'></i>")
elseif(flow["throughput_trend_"..throughput_type] == 2) then
print("<i class='fa fa-arrow-down'></i>")
elseif(flow["throughput_trend_"..throughput_type] == 3) then
print("<i class='fa fa-minus'></i>")
end
print("\"")
else
print ("\", \"column_thpt\" : \"0 "..throughput_type.." \"")
end
cli2srv = round((flow["cli2srv.bytes"] * 100) / flow["bytes"], 0)
print (", \"column_breakdown\" : \"<div class='progress'><div class='progress-bar progress-bar-warning' style='width: " .. cli2srv .."%;'>Client</div><div class='progress-bar progress-bar-info' style='width: " .. (100-cli2srv) .. "%;'>Server</div></div>")
print ("\" }")
end | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Port_Bastok/npcs/Talib.lua | 4 | 2754 | -----------------------------------
-- Area: Port Bastok
-- NPC: Talib
-- Starts Quest: Beauty and the Galka
-- Starts & Finishes Quest: Shady Business
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(BASTOK,SHADY_BUSINESS) >= QUEST_ACCEPTED) then
if(trade:hasItemQty(642,4) and trade:getItemCount() == 4) then
player:startEvent(0x005b);
end
elseif(player:getQuestStatus(BASTOK,BEAUTY_AND_THE_GALKA) == QUEST_ACCEPTED) then
if(trade:hasItemQty(642,1) and trade:getItemCount() == 1) then
player:startEvent(0x0003);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
BeautyAndTheGalka = player:getQuestStatus(BASTOK,BEAUTY_AND_THE_GALKA);
if(BeautyAndTheGalka == QUEST_COMPLETED) then
player:startEvent(0x005a);
elseif(BeautyAndTheGalka == QUEST_ACCEPTED or player:getVar("BeautyAndTheGalkaDenied") >= 1) then
player:startEvent(0x0004);
else
player:startEvent(0x0002);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x0002 and option == 0) then
player:addQuest(BASTOK,BEAUTY_AND_THE_GALKA);
elseif(csid == 0x0002 and option == 1) then
player:setVar("BeautyAndTheGalkaDenied",1);
elseif(csid == 0x0003) then
player:tradeComplete();
player:addKeyItem(PALBOROUGH_MINES_LOGS);
player:messageSpecial(KEYITEM_OBTAINED,PALBOROUGH_MINES_LOGS);
elseif(csid == 0x005a) then
ShadyBusiness = player:getQuestStatus(BASTOK,SHADY_BUSINESS);
if(ShadyBusiness == QUEST_AVAILABLE) then
player:addQuest(BASTOK,SHADY_BUSINESS);
end
elseif(csid == 0x005b) then
ShadyBusiness = player:getQuestStatus(BASTOK,SHADY_BUSINESS);
if(ShadyBusiness == QUEST_ACCEPTED) then
player:addFame(NORG,NORG_FAME*100);
player:completeQuest(BASTOK,SHADY_BUSINESS);
else
player:addFame(NORG,NORG_FAME*80);
end
player:tradeComplete();
player:addGil(GIL_RATE*350);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*350);
end
end; | gpl-3.0 |
projectbismark/luci-bismark | protocols/ppp/luasrc/model/cbi/admin_network/proto_pppoa.lua | 7 | 3925 | --[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local encaps, atmdev, vci, vpi, username, password
local ipv6, defaultroute, metric, peerdns, dns,
keepalive_failure, keepalive_interval, demand
encaps = section:taboption("general", ListValue, "encaps", translate("PPPoA Encapsulation"))
encaps:value("vc", "VC-Mux")
encaps:value("llc", "LLC")
atmdev = section:taboption("general", Value, "atmdev", translate("ATM device number"))
atmdev.default = "0"
atmdev.datatype = "uinteger"
vci = section:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vci.default = "35"
vci.datatype = "uinteger"
vpi = section:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
vpi.default = "8"
vpi.datatype = "uinteger"
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", Flag, "ipv6",
translate("Enable IPv6 negotiation on the PPP link"))
ipv6.default = ipv6.disabled
end
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure",
translate("LCP echo failure threshold"),
translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures"))
function keepalive_failure.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^(%d+)[ ,]+%d+") or v)
end
end
function keepalive_failure.write() end
function keepalive_failure.remove() end
keepalive_failure.placeholder = "0"
keepalive_failure.datatype = "uinteger"
keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval",
translate("LCP echo interval"),
translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold"))
function keepalive_interval.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^%d+[ ,]+(%d+)"))
end
end
function keepalive_interval.write(self, section, value)
local f = tonumber(keepalive_failure:formvalue(section)) or 0
local i = tonumber(value) or 5
if i < 1 then i = 1 end
if f > 0 then
m:set(section, "keepalive", "%d %d" %{ f, i })
else
m:del(section, "keepalive")
end
end
keepalive_interval.remove = keepalive_interval.write
keepalive_interval.placeholder = "5"
keepalive_interval.datatype = "min(1)"
demand = section:taboption("advanced", Value, "demand",
translate("Inactivity timeout"),
translate("Close inactive connection after the given amount of seconds, use 0 to persist connection"))
demand.placeholder = "0"
demand.datatype = "uinteger"
| apache-2.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Windurst_Walls/npcs/Tsuaora-Tsuora.lua | 5 | 1044 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Tsuaora-Tsuora
-- Type: Standard NPC
-- @zone: 239
-- @pos: 71.489 -3.418 -67.809
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x002a);
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 |
everslick/awesome | lib/beautiful/xresources.lua | 5 | 2635 | ----------------------------------------------------------------------------
--- Library for getting xrdb data.
--
-- @author Yauhen Kirylau <yawghen@gmail.com>
-- @copyright 2015 Yauhen Kirylau
-- @release @AWESOME_VERSION@
-- @module beautiful.xresources
----------------------------------------------------------------------------
-- Grab environment
local print = print
local awesome = awesome
local round = require("awful.util").round
local xresources = {}
local fallback = {
--black
color0 = '#000000',
color8 = '#465457',
--red
color1 = '#cb1578',
color9 = '#dc5e86',
--green
color2 = '#8ecb15',
color10 = '#9edc60',
--yellow
color3 = '#cb9a15',
color11 = '#dcb65e',
--blue
color4 = '#6f15cb',
color12 = '#7e5edc',
--purple
color5 = '#cb15c9',
color13 = '#b75edc',
--cyan
color6 = '#15b4cb',
color14 = '#5edcb4',
--white
color7 = '#888a85',
color15 = '#ffffff',
--
background = '#0e0021',
foreground = '#bcbcbc',
}
--- Get current base colorscheme from xrdb.
-- @treturn table Color table with keys 'background', 'foreground' and 'color0'..'color15'
function xresources.get_current_theme()
local keys = { 'background', 'foreground' }
for i=0,15 do table.insert(keys, "color"..i) end
local colors = {}
for _, key in ipairs(keys) do
colors[key] = awesome.xrdb_get_value("", key)
if not colors[key] then
print("W: beautiful: can't get colorscheme from xrdb (using fallback).")
return fallback
end
end
return colors
end
local dpi_per_screen = {}
--- Get global or per-screen DPI value falling back to xrdb.
-- @tparam[opt=focused] integer s The screen.
-- @treturn number DPI value.
function xresources.get_dpi(s)
if dpi_per_screen[s] then
return dpi_per_screen[s]
end
if not xresources.dpi then
xresources.dpi = tonumber(awesome.xrdb_get_value("", "Xft.dpi") or 96)
end
return xresources.dpi
end
--- Set DPI for a given screen (defaults to global).
-- @tparam number dpi DPI value.
-- @tparam[opt] integer s Screen.
function xresources.set_dpi(dpi, s)
if not s then
xresources.dpi = dpi
else
dpi_per_screen[s] = dpi
end
end
--- Compute resulting size applying current DPI value (optionally per screen).
-- @tparam number size Size
-- @tparam[opt] integer s The screen.
-- @treturn integer Resulting size (rounded to integer).
function xresources.apply_dpi(size, s)
return round(size / 96 * xresources.get_dpi(s))
end
return xresources
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
Sonicrich05/FFXI-Server | scripts/zones/Metalworks/npcs/Taulluque.lua | 38 | 1048 | -----------------------------------
-- Area: Metalworks
-- NPC: Taulluque
-- Type: Past Event Watcher
-- @zone: 237
-- @pos 39.907 -14.999 -21.083
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0303);
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 |
paulosalvatore/forgottenserver | data/spells/scripts/custom/polymorph.lua | 11 | 1084 | local condition = Condition(CONDITION_OUTFIT)
condition:setParameter(CONDITION_PARAM_TICKS, 20000)
condition:setOutfit(0, 230, 0, 0, 0, 0)
condition:setOutfit(0, 231, 0, 0, 0, 0)
condition:setOutfit(0, 232, 0, 0, 0, 0)
condition:setOutfit(0, 233, 0, 0, 0, 0)
condition:setOutfit(0, 234, 0, 0, 0, 0)
condition:setOutfit(0, 235, 0, 0, 0, 0)
condition:setOutfit(0, 236, 0, 0, 0, 0)
condition:setOutfit(0, 237, 0, 0, 0, 0)
condition:setOutfit(0, 238, 0, 0, 0, 0)
condition:setOutfit(0, 239, 0, 0, 0, 0)
condition:setOutfit(0, 240, 0, 0, 0, 0)
condition:setOutfit(0, 241, 0, 0, 0, 0)
condition:setOutfit(0, 242, 0, 0, 0, 0)
condition:setOutfit(0, 243, 0, 0, 0, 0)
condition:setOutfit(0, 244, 0, 0, 0, 0)
condition:setOutfit(0, 245, 0, 0, 0, 0)
condition:setOutfit(0, 246, 0, 0, 0, 0)
condition:setOutfit(0, 247, 0, 0, 0, 0)
local combat = Combat()
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_GREEN)
combat:setArea(createCombatArea(AREA_SQUARE1X1))
combat:setCondition(condition)
function onCastSpell(creature, variant, isHotkey)
return combat:execute(creature, variant)
end
| gpl-2.0 |
poelzi/ulatencyd | src/lua/string.lua | 2 | 1587 | --[[
Copyright 2010,2011 ulatencyd developers
This file is part of ulatencyd.
ulatencyd is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License,
or (at your option) any later version.
ulatencyd 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 ulatencyd. If not, see http://www.gnu.org/licenses/.
]]--
-------------------------------------------------------------------------------
--! @file
--! @ingroup lua_EXT
--! @brief extending lua type `string`
-------------------------------------------------------------------------------
--! @addtogroup lua_EXT
--! @{
--! @brief split string with seperator sep
--! @param sep seperator
--! @return new table with chunks
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
--! @brief remove trailing whitespace from string.
--! http://en.wikipedia.org/wiki/Trim_(8programming)
function string:rtrim()
local n = #self
while n > 0 and self:find("^%s", n) do n = n - 1 end
return self:sub(1, n)
end
--! @} End of "addtogroup lua_EXT" | gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/globals/abilities/divine_waltz.lua | 28 | 2373 | -----------------------------------
-- Ability: Divine Waltz
-- Heals party members within area of effect.
-- Obtained: Dancer Level 25
-- TP Required: 40%
-- Recast Time: 00:13
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (target:getHP() == 0) then
return MSGBASIC_CANNOT_ON_THAT_TARG,0;
elseif (player:hasStatusEffect(EFFECT_SABER_DANCE)) then
return MSGBASIC_UNABLE_TO_USE_JA2, 0;
elseif (player:hasStatusEffect(EFFECT_TRANCE)) then
return 0,0;
elseif (player:getTP() < 40) then
return MSGBASIC_NOT_ENOUGH_TP,0;
else
-- Apply waltz recast modifiers
if (player:getMod(MOD_WALTZ_RECAST)~=0) then
local recastMod = -130 * (player:getMod(MOD_WALTZ_RECAST)); -- 650 ms per 5% (per merit)
if (recastMod < 0) then
--TODO
end
end
return 0,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
-- Only remove TP if the player doesn't have Trance, and only deduct once instead of for each target.
if (player:getID() == target:getID() and player:hasStatusEffect(EFFECT_TRANCE) == false) then
player:delTP(40);
end;
-- Grabbing variables.
local vit = target:getStat(MOD_VIT);
local chr = player:getStat(MOD_CHR);
local mjob = player:getMainJob(); --19 for DNC main.
local sjob = player:getSubJob();
local cure = 0;
-- Performing sj mj check.
if (mjob == 19) then
cure = (vit+chr)*0.25+60;
end
if (sjob == 19) then
cure = (vit+chr)*0.125+60;
end
-- Apply waltz modifiers
cure = math.floor(cure * (1.0 + (player:getMod(MOD_WALTZ_POTENTCY)/100)));
-- Cap the final amount to max HP.
if ((target:getMaxHP() - target:getHP()) < cure) then
cure = (target:getMaxHP() - target:getHP());
end
-- Applying server mods....
cure = cure * CURE_POWER;
target:restoreHP(cure);
target:wakeUp();
player:updateEnmityFromCure(target,cure);
return cure;
end; | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Ship_bound_for_Selbina/npcs/Rajmonda.lua | 2 | 1039 | -----------------------------------
-- Area: Ship bound for Selbina
-- NPC: Rajmonda
-- Guild Merchant NPC: Fishing Guild
-----------------------------------
package.loaded["scripts/zones/Ship_bound_for_Selbina/TextIDs"] = nil;
require("scripts/zones/Ship_bound_for_Selbina/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:sendGuild(519,1,23,5)) then
player:showText(npc,RAJMONDA_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Dual-Boxing/Jamba | Libs/AceDB-3.0/AceDB-3.0.lua | 11 | 24711 | --- **AceDB-3.0** manages the SavedVariables of your addon.
-- It offers profile management, smart defaults and namespaces for modules.\\
-- Data can be saved in different data-types, depending on its intended usage.
-- The most common data-type is the `profile` type, which allows the user to choose
-- the active profile, and manage the profiles of all of his characters.\\
-- The following data types are available:
-- * **char** Character-specific data. Every character has its own database.
-- * **realm** Realm-specific data. All of the players characters on the same realm share this database.
-- * **class** Class-specific data. All of the players characters of the same class share this database.
-- * **race** Race-specific data. All of the players characters of the same race share this database.
-- * **faction** Faction-specific data. All of the players characters of the same faction share this database.
-- * **factionrealm** Faction and realm specific data. All of the players characters on the same realm and of the same faction share this database.
-- * **global** Global Data. All characters on the same account share this database.
-- * **profile** Profile-specific data. All characters using the same profile share this database. The user can control which profile should be used.
--
-- Creating a new Database using the `:New` function will return a new DBObject. A database will inherit all functions
-- of the DBObjectLib listed here. \\
-- If you create a new namespaced child-database (`:RegisterNamespace`), you'll get a DBObject as well, but note
-- that the child-databases cannot individually change their profile, and are linked to their parents profile - and because of that,
-- the profile related APIs are not available. Only `:RegisterDefaults` and `:ResetProfile` are available on child-databases.
--
-- For more details on how to use AceDB-3.0, see the [[AceDB-3.0 Tutorial]].
--
-- You may also be interested in [[libdualspec-1-0|LibDualSpec-1.0]] to do profile switching automatically when switching specs.
--
-- @usage
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("DBExample")
--
-- -- declare defaults to be used in the DB
-- local defaults = {
-- profile = {
-- setting = true,
-- }
-- }
--
-- function MyAddon:OnInitialize()
-- -- Assuming the .toc says ## SavedVariables: MyAddonDB
-- self.db = LibStub("AceDB-3.0"):New("MyAddonDB", defaults, true)
-- end
-- @class file
-- @name AceDB-3.0.lua
-- @release $Id: AceDB-3.0.lua 1115 2014-09-21 11:52:35Z kaelten $
local ACEDB_MAJOR, ACEDB_MINOR = "AceDB-3.0", 25
local AceDB, oldminor = LibStub:NewLibrary(ACEDB_MAJOR, ACEDB_MINOR)
if not AceDB then return end -- No upgrade needed
-- Lua APIs
local type, pairs, next, error = type, pairs, next, error
local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget
-- WoW APIs
local _G = _G
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: LibStub
AceDB.db_registry = AceDB.db_registry or {}
AceDB.frame = AceDB.frame or CreateFrame("Frame")
local CallbackHandler
local CallbackDummy = { Fire = function() end }
local DBObjectLib = {}
--[[-------------------------------------------------------------------------
AceDB Utility Functions
---------------------------------------------------------------------------]]
-- Simple shallow copy for copying defaults
local function copyTable(src, dest)
if type(dest) ~= "table" then dest = {} end
if type(src) == "table" then
for k,v in pairs(src) do
if type(v) == "table" then
-- try to index the key first so that the metatable creates the defaults, if set, and use that table
v = copyTable(v, dest[k])
end
dest[k] = v
end
end
return dest
end
-- Called to add defaults to a section of the database
--
-- When a ["*"] default section is indexed with a new key, a table is returned
-- and set in the host table. These tables must be cleaned up by removeDefaults
-- in order to ensure we don't write empty default tables.
local function copyDefaults(dest, src)
-- this happens if some value in the SV overwrites our default value with a non-table
--if type(dest) ~= "table" then return end
for k, v in pairs(src) do
if k == "*" or k == "**" then
if type(v) == "table" then
-- This is a metatable used for table defaults
local mt = {
-- This handles the lookup and creation of new subtables
__index = function(t,k)
if k == nil then return nil end
local tbl = {}
copyDefaults(tbl, v)
rawset(t, k, tbl)
return tbl
end,
}
setmetatable(dest, mt)
-- handle already existing tables in the SV
for dk, dv in pairs(dest) do
if not rawget(src, dk) and type(dv) == "table" then
copyDefaults(dv, v)
end
end
else
-- Values are not tables, so this is just a simple return
local mt = {__index = function(t,k) return k~=nil and v or nil end}
setmetatable(dest, mt)
end
elseif type(v) == "table" then
if not rawget(dest, k) then rawset(dest, k, {}) end
if type(dest[k]) == "table" then
copyDefaults(dest[k], v)
if src['**'] then
copyDefaults(dest[k], src['**'])
end
end
else
if rawget(dest, k) == nil then
rawset(dest, k, v)
end
end
end
end
-- Called to remove all defaults in the default table from the database
local function removeDefaults(db, defaults, blocker)
-- remove all metatables from the db, so we don't accidentally create new sub-tables through them
setmetatable(db, nil)
-- loop through the defaults and remove their content
for k,v in pairs(defaults) do
if k == "*" or k == "**" then
if type(v) == "table" then
-- Loop through all the actual k,v pairs and remove
for key, value in pairs(db) do
if type(value) == "table" then
-- if the key was not explicitly specified in the defaults table, just strip everything from * and ** tables
if defaults[key] == nil and (not blocker or blocker[key] == nil) then
removeDefaults(value, v)
-- if the table is empty afterwards, remove it
if next(value) == nil then
db[key] = nil
end
-- if it was specified, only strip ** content, but block values which were set in the key table
elseif k == "**" then
removeDefaults(value, v, defaults[key])
end
end
end
elseif k == "*" then
-- check for non-table default
for key, value in pairs(db) do
if defaults[key] == nil and v == value then
db[key] = nil
end
end
end
elseif type(v) == "table" and type(db[k]) == "table" then
-- if a blocker was set, dive into it, to allow multi-level defaults
removeDefaults(db[k], v, blocker and blocker[k])
if next(db[k]) == nil then
db[k] = nil
end
else
-- check if the current value matches the default, and that its not blocked by another defaults table
if db[k] == defaults[k] and (not blocker or blocker[k] == nil) then
db[k] = nil
end
end
end
end
-- This is called when a table section is first accessed, to set up the defaults
local function initSection(db, section, svstore, key, defaults)
local sv = rawget(db, "sv")
local tableCreated
if not sv[svstore] then sv[svstore] = {} end
if not sv[svstore][key] then
sv[svstore][key] = {}
tableCreated = true
end
local tbl = sv[svstore][key]
if defaults then
copyDefaults(tbl, defaults)
end
rawset(db, section, tbl)
return tableCreated, tbl
end
-- Metatable to handle the dynamic creation of sections and copying of sections.
local dbmt = {
__index = function(t, section)
local keys = rawget(t, "keys")
local key = keys[section]
if key then
local defaultTbl = rawget(t, "defaults")
local defaults = defaultTbl and defaultTbl[section]
if section == "profile" then
local new = initSection(t, section, "profiles", key, defaults)
if new then
-- Callback: OnNewProfile, database, newProfileKey
t.callbacks:Fire("OnNewProfile", t, key)
end
elseif section == "profiles" then
local sv = rawget(t, "sv")
if not sv.profiles then sv.profiles = {} end
rawset(t, "profiles", sv.profiles)
elseif section == "global" then
local sv = rawget(t, "sv")
if not sv.global then sv.global = {} end
if defaults then
copyDefaults(sv.global, defaults)
end
rawset(t, section, sv.global)
else
initSection(t, section, section, key, defaults)
end
end
return rawget(t, section)
end
}
local function validateDefaults(defaults, keyTbl, offset)
if not defaults then return end
offset = offset or 0
for k in pairs(defaults) do
if not keyTbl[k] or k == "profiles" then
error(("Usage: AceDBObject:RegisterDefaults(defaults): '%s' is not a valid datatype."):format(k), 3 + offset)
end
end
end
local preserve_keys = {
["callbacks"] = true,
["RegisterCallback"] = true,
["UnregisterCallback"] = true,
["UnregisterAllCallbacks"] = true,
["children"] = true,
}
local realmKey = GetRealmName()
local charKey = UnitName("player") .. " - " .. realmKey
local _, classKey = UnitClass("player")
local _, raceKey = UnitRace("player")
local factionKey = UnitFactionGroup("player")
local factionrealmKey = factionKey .. " - " .. realmKey
local localeKey = GetLocale():lower()
local regionTable = { "US", "KR", "EU", "TW", "CN" }
local regionKey = _G["GetCurrentRegion"] and regionTable[GetCurrentRegion()] or string.sub(GetCVar("realmList"), 1, 2):upper()
local factionrealmregionKey = factionrealmKey .. " - " .. regionKey
-- Actual database initialization function
local function initdb(sv, defaults, defaultProfile, olddb, parent)
-- Generate the database keys for each section
-- map "true" to our "Default" profile
if defaultProfile == true then defaultProfile = "Default" end
local profileKey
if not parent then
-- Make a container for profile keys
if not sv.profileKeys then sv.profileKeys = {} end
-- Try to get the profile selected from the char db
profileKey = sv.profileKeys[charKey] or defaultProfile or charKey
-- save the selected profile for later
sv.profileKeys[charKey] = profileKey
else
-- Use the profile of the parents DB
profileKey = parent.keys.profile or defaultProfile or charKey
-- clear the profileKeys in the DB, namespaces don't need to store them
sv.profileKeys = nil
end
-- This table contains keys that enable the dynamic creation
-- of each section of the table. The 'global' and 'profiles'
-- have a key of true, since they are handled in a special case
local keyTbl= {
["char"] = charKey,
["realm"] = realmKey,
["class"] = classKey,
["race"] = raceKey,
["faction"] = factionKey,
["factionrealm"] = factionrealmKey,
["factionrealmregion"] = factionrealmregionKey,
["profile"] = profileKey,
["locale"] = localeKey,
["global"] = true,
["profiles"] = true,
}
validateDefaults(defaults, keyTbl, 1)
-- This allows us to use this function to reset an entire database
-- Clear out the old database
if olddb then
for k,v in pairs(olddb) do if not preserve_keys[k] then olddb[k] = nil end end
end
-- Give this database the metatable so it initializes dynamically
local db = setmetatable(olddb or {}, dbmt)
if not rawget(db, "callbacks") then
-- try to load CallbackHandler-1.0 if it loaded after our library
if not CallbackHandler then CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0", true) end
db.callbacks = CallbackHandler and CallbackHandler:New(db) or CallbackDummy
end
-- Copy methods locally into the database object, to avoid hitting
-- the metatable when calling methods
if not parent then
for name, func in pairs(DBObjectLib) do
db[name] = func
end
else
-- hack this one in
db.RegisterDefaults = DBObjectLib.RegisterDefaults
db.ResetProfile = DBObjectLib.ResetProfile
end
-- Set some properties in the database object
db.profiles = sv.profiles
db.keys = keyTbl
db.sv = sv
--db.sv_name = name
db.defaults = defaults
db.parent = parent
-- store the DB in the registry
AceDB.db_registry[db] = true
return db
end
-- handle PLAYER_LOGOUT
-- strip all defaults from all databases
-- and cleans up empty sections
local function logoutHandler(frame, event)
if event == "PLAYER_LOGOUT" then
for db in pairs(AceDB.db_registry) do
db.callbacks:Fire("OnDatabaseShutdown", db)
db:RegisterDefaults(nil)
-- cleanup sections that are empty without defaults
local sv = rawget(db, "sv")
for section in pairs(db.keys) do
if rawget(sv, section) then
-- global is special, all other sections have sub-entrys
-- also don't delete empty profiles on main dbs, only on namespaces
if section ~= "global" and (section ~= "profiles" or rawget(db, "parent")) then
for key in pairs(sv[section]) do
if not next(sv[section][key]) then
sv[section][key] = nil
end
end
end
if not next(sv[section]) then
sv[section] = nil
end
end
end
end
end
end
AceDB.frame:RegisterEvent("PLAYER_LOGOUT")
AceDB.frame:SetScript("OnEvent", logoutHandler)
--[[-------------------------------------------------------------------------
AceDB Object Method Definitions
---------------------------------------------------------------------------]]
--- Sets the defaults table for the given database object by clearing any
-- that are currently set, and then setting the new defaults.
-- @param defaults A table of defaults for this database
function DBObjectLib:RegisterDefaults(defaults)
if defaults and type(defaults) ~= "table" then
error("Usage: AceDBObject:RegisterDefaults(defaults): 'defaults' - table or nil expected.", 2)
end
validateDefaults(defaults, self.keys)
-- Remove any currently set defaults
if self.defaults then
for section,key in pairs(self.keys) do
if self.defaults[section] and rawget(self, section) then
removeDefaults(self[section], self.defaults[section])
end
end
end
-- Set the DBObject.defaults table
self.defaults = defaults
-- Copy in any defaults, only touching those sections already created
if defaults then
for section,key in pairs(self.keys) do
if defaults[section] and rawget(self, section) then
copyDefaults(self[section], defaults[section])
end
end
end
end
--- Changes the profile of the database and all of it's namespaces to the
-- supplied named profile
-- @param name The name of the profile to set as the current profile
function DBObjectLib:SetProfile(name)
if type(name) ~= "string" then
error("Usage: AceDBObject:SetProfile(name): 'name' - string expected.", 2)
end
-- changing to the same profile, dont do anything
if name == self.keys.profile then return end
local oldProfile = self.profile
local defaults = self.defaults and self.defaults.profile
-- Callback: OnProfileShutdown, database
self.callbacks:Fire("OnProfileShutdown", self)
if oldProfile and defaults then
-- Remove the defaults from the old profile
removeDefaults(oldProfile, defaults)
end
self.profile = nil
self.keys["profile"] = name
-- if the storage exists, save the new profile
-- this won't exist on namespaces.
if self.sv.profileKeys then
self.sv.profileKeys[charKey] = name
end
-- populate to child namespaces
if self.children then
for _, db in pairs(self.children) do
DBObjectLib.SetProfile(db, name)
end
end
-- Callback: OnProfileChanged, database, newProfileKey
self.callbacks:Fire("OnProfileChanged", self, name)
end
--- Returns a table with the names of the existing profiles in the database.
-- You can optionally supply a table to re-use for this purpose.
-- @param tbl A table to store the profile names in (optional)
function DBObjectLib:GetProfiles(tbl)
if tbl and type(tbl) ~= "table" then
error("Usage: AceDBObject:GetProfiles(tbl): 'tbl' - table or nil expected.", 2)
end
-- Clear the container table
if tbl then
for k,v in pairs(tbl) do tbl[k] = nil end
else
tbl = {}
end
local curProfile = self.keys.profile
local i = 0
for profileKey in pairs(self.profiles) do
i = i + 1
tbl[i] = profileKey
if curProfile and profileKey == curProfile then curProfile = nil end
end
-- Add the current profile, if it hasn't been created yet
if curProfile then
i = i + 1
tbl[i] = curProfile
end
return tbl, i
end
--- Returns the current profile name used by the database
function DBObjectLib:GetCurrentProfile()
return self.keys.profile
end
--- Deletes a named profile. This profile must not be the active profile.
-- @param name The name of the profile to be deleted
-- @param silent If true, do not raise an error when the profile does not exist
function DBObjectLib:DeleteProfile(name, silent)
if type(name) ~= "string" then
error("Usage: AceDBObject:DeleteProfile(name): 'name' - string expected.", 2)
end
if self.keys.profile == name then
error("Cannot delete the active profile in an AceDBObject.", 2)
end
if not rawget(self.profiles, name) and not silent then
error("Cannot delete profile '" .. name .. "'. It does not exist.", 2)
end
self.profiles[name] = nil
-- populate to child namespaces
if self.children then
for _, db in pairs(self.children) do
DBObjectLib.DeleteProfile(db, name, true)
end
end
-- switch all characters that use this profile back to the default
if self.sv.profileKeys then
for key, profile in pairs(self.sv.profileKeys) do
if profile == name then
self.sv.profileKeys[key] = nil
end
end
end
-- Callback: OnProfileDeleted, database, profileKey
self.callbacks:Fire("OnProfileDeleted", self, name)
end
--- Copies a named profile into the current profile, overwriting any conflicting
-- settings.
-- @param name The name of the profile to be copied into the current profile
-- @param silent If true, do not raise an error when the profile does not exist
function DBObjectLib:CopyProfile(name, silent)
if type(name) ~= "string" then
error("Usage: AceDBObject:CopyProfile(name): 'name' - string expected.", 2)
end
if name == self.keys.profile then
error("Cannot have the same source and destination profiles.", 2)
end
if not rawget(self.profiles, name) and not silent then
error("Cannot copy profile '" .. name .. "'. It does not exist.", 2)
end
-- Reset the profile before copying
DBObjectLib.ResetProfile(self, nil, true)
local profile = self.profile
local source = self.profiles[name]
copyTable(source, profile)
-- populate to child namespaces
if self.children then
for _, db in pairs(self.children) do
DBObjectLib.CopyProfile(db, name, true)
end
end
-- Callback: OnProfileCopied, database, sourceProfileKey
self.callbacks:Fire("OnProfileCopied", self, name)
end
--- Resets the current profile to the default values (if specified).
-- @param noChildren if set to true, the reset will not be populated to the child namespaces of this DB object
-- @param noCallbacks if set to true, won't fire the OnProfileReset callback
function DBObjectLib:ResetProfile(noChildren, noCallbacks)
local profile = self.profile
for k,v in pairs(profile) do
profile[k] = nil
end
local defaults = self.defaults and self.defaults.profile
if defaults then
copyDefaults(profile, defaults)
end
-- populate to child namespaces
if self.children and not noChildren then
for _, db in pairs(self.children) do
DBObjectLib.ResetProfile(db, nil, noCallbacks)
end
end
-- Callback: OnProfileReset, database
if not noCallbacks then
self.callbacks:Fire("OnProfileReset", self)
end
end
--- Resets the entire database, using the string defaultProfile as the new default
-- profile.
-- @param defaultProfile The profile name to use as the default
function DBObjectLib:ResetDB(defaultProfile)
if defaultProfile and type(defaultProfile) ~= "string" then
error("Usage: AceDBObject:ResetDB(defaultProfile): 'defaultProfile' - string or nil expected.", 2)
end
local sv = self.sv
for k,v in pairs(sv) do
sv[k] = nil
end
local parent = self.parent
initdb(sv, self.defaults, defaultProfile, self)
-- fix the child namespaces
if self.children then
if not sv.namespaces then sv.namespaces = {} end
for name, db in pairs(self.children) do
if not sv.namespaces[name] then sv.namespaces[name] = {} end
initdb(sv.namespaces[name], db.defaults, self.keys.profile, db, self)
end
end
-- Callback: OnDatabaseReset, database
self.callbacks:Fire("OnDatabaseReset", self)
-- Callback: OnProfileChanged, database, profileKey
self.callbacks:Fire("OnProfileChanged", self, self.keys["profile"])
return self
end
--- Creates a new database namespace, directly tied to the database. This
-- is a full scale database in it's own rights other than the fact that
-- it cannot control its profile individually
-- @param name The name of the new namespace
-- @param defaults A table of values to use as defaults
function DBObjectLib:RegisterNamespace(name, defaults)
if type(name) ~= "string" then
error("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - string expected.", 2)
end
if defaults and type(defaults) ~= "table" then
error("Usage: AceDBObject:RegisterNamespace(name, defaults): 'defaults' - table or nil expected.", 2)
end
if self.children and self.children[name] then
error ("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - a namespace with that name already exists.", 2)
end
local sv = self.sv
if not sv.namespaces then sv.namespaces = {} end
if not sv.namespaces[name] then
sv.namespaces[name] = {}
end
local newDB = initdb(sv.namespaces[name], defaults, self.keys.profile, nil, self)
if not self.children then self.children = {} end
self.children[name] = newDB
return newDB
end
--- Returns an already existing namespace from the database object.
-- @param name The name of the new namespace
-- @param silent if true, the addon is optional, silently return nil if its not found
-- @usage
-- local namespace = self.db:GetNamespace('namespace')
-- @return the namespace object if found
function DBObjectLib:GetNamespace(name, silent)
if type(name) ~= "string" then
error("Usage: AceDBObject:GetNamespace(name): 'name' - string expected.", 2)
end
if not silent and not (self.children and self.children[name]) then
error ("Usage: AceDBObject:GetNamespace(name): 'name' - namespace does not exist.", 2)
end
if not self.children then self.children = {} end
return self.children[name]
end
--[[-------------------------------------------------------------------------
AceDB Exposed Methods
---------------------------------------------------------------------------]]
--- Creates a new database object that can be used to handle database settings and profiles.
-- By default, an empty DB is created, using a character specific profile.
--
-- You can override the default profile used by passing any profile name as the third argument,
-- or by passing //true// as the third argument to use a globally shared profile called "Default".
--
-- Note that there is no token replacement in the default profile name, passing a defaultProfile as "char"
-- will use a profile named "char", and not a character-specific profile.
-- @param tbl The name of variable, or table to use for the database
-- @param defaults A table of database defaults
-- @param defaultProfile The name of the default profile. If not set, a character specific profile will be used as the default.
-- You can also pass //true// to use a shared global profile called "Default".
-- @usage
-- -- Create an empty DB using a character-specific default profile.
-- self.db = LibStub("AceDB-3.0"):New("MyAddonDB")
-- @usage
-- -- Create a DB using defaults and using a shared default profile
-- self.db = LibStub("AceDB-3.0"):New("MyAddonDB", defaults, true)
function AceDB:New(tbl, defaults, defaultProfile)
if type(tbl) == "string" then
local name = tbl
tbl = _G[name]
if not tbl then
tbl = {}
_G[name] = tbl
end
end
if type(tbl) ~= "table" then
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'tbl' - table expected.", 2)
end
if defaults and type(defaults) ~= "table" then
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaults' - table expected.", 2)
end
if defaultProfile and type(defaultProfile) ~= "string" and defaultProfile ~= true then
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaultProfile' - string or true expected.", 2)
end
return initdb(tbl, defaults, defaultProfile)
end
-- upgrade existing databases
for db in pairs(AceDB.db_registry) do
if not db.parent then
for name,func in pairs(DBObjectLib) do
db[name] = func
end
else
db.RegisterDefaults = DBObjectLib.RegisterDefaults
db.ResetProfile = DBObjectLib.ResetProfile
end
end
| mit |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/weaponskills/victory_smite.lua | 4 | 1530 | -----------------------------------
-- Victory Smite
-- Hand-to-Hand Weapon Skill
-- Skill Level: N/A
-- Description: Delivers a fourfold attack. Chance of params.critical hit varies with TP.
-- Must have Verethragna (85)/(90)/(95)/(99)/(99-2) or Revenant Fists +1/+2/+3 equipped.
-- Aligned with the Light Gorget, Breeze Gorget & Thunder Gorget.
-- Aligned with the Light Belt, Breeze Belt & Thunder Belt.
-- Element: None
-- Skillchain Properties: Light, Fragmentation
-- Modifiers: STR:60%
-- Damage Multipliers by TP:
-- 100%TP 200%TP 300%TP
-- 2.25 2.25 2.25
-- params.critical Chance added with TP:
-- 100%TP 200%TP 300%TP
-- 10% 25% 45%
--
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 4;
params.ftp100 = 2.25; params.ftp200 = 2.25; params.ftp300 = 2.25;
params.str_wsc = 0.6; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.1; params.crit200 = 0.25; params.crit300 = 0.45;
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
return tpHits, extraHits, criticalHit, damage;
end | gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/Gusgen_Mines/npcs/_5g4.lua | 34 | 1102 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: _5g4 (Door E)
-- @pos 19.998 -22.4 174.506 196
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Gusgen_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (npc:getAnimation() == 9) then
player:messageSpecial(LOCK_OTHER_DEVICE)
else
return 0;
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 |
Sonicrich05/FFXI-Server | scripts/zones/Meriphataud_Mountains_[S]/npcs/Cavernous_Maw.lua | 29 | 1505 | -----------------------------------
-- Area: Meriphataud Mountains [S]
-- NPC: Cavernous Maw
-- @pos 597 -32 279 97
-- Teleports Players to Meriphataud Mountains
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/teleports");
require("scripts/globals/campaign");
require("scripts/zones/Meriphataud_Mountains_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (hasMawActivated(player,5) == false) then
player:startEvent(0x0066);
else
player:startEvent(0x0067);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (option == 1) then
if (csid == 0x0066) then
player:addNationTeleport(MAW,32);
end
toMaw(player,18);
end
end; | gpl-3.0 |
rlowrance/re | lua/Resampling-test.lua | 1 | 2319 | -- Resampling-test.lua
-- unit test of Resampling class
require 'Resampling'
require 'Tester'
myTests = {}
tester = Tester()
--------------------------------------------------------------------------------
-- utilities
--------------------------------------------------------------------------------
function assertNear(actual, expected, delta, msg)
trace = false
local me = 'assertNear: '
if math.abs(actual - expected) >= delta then
print(me .. 'actual', actual)
print(me .. 'expected', expected)
print(me .. 'delta', delta)
end
tester:assertlt(math.abs(actual - expected), delta, msg)
end
--------------------------------------------------------------------------------
-- test diff2MeansSig
--------------------------------------------------------------------------------
function myTests.diff2MeansConf()
group1 = {54, 51, 58, 44, 55, 52, 42, 47, 58, 46}
group2 = {54, 73, 53, 70, 73, 68, 52, 65, 65}
local low, high = Resampling.diff2MeansConf(group1, group2)
-- test vs. text book results
assertNear(low, -17.7, 1, 'lower bound on 90% conf interval')
assertNear(high, -6.7, 1, 'upper bound on 90% conf interval')
end
--------------------------------------------------------------------------------
-- test diff2MeansSig
--------------------------------------------------------------------------------
function myTests.diff2MeansSig()
group1 = {54, 51, 58, 44, 55, 52, 42, 47, 58, 46}
group2 = {54, 73, 53, 70, 73, 68, 52, 65, 65}
local prob = Resampling.diff2MeansSig(group1, group2)
-- test vs. text book results
tester:assertlt(prob, .01, 'probability')
end
--------------------------------------------------------------------------------
-- meanConf
--------------------------------------------------------------------------------
function myTests.meanConf()
data = {60.2, 63.1, 58.4, 58.9, 61.2, 67.0, 61.0, 59.7, 58.2, 59.8}
local low, high = Resampling.meanConf(data)
assertNear(low, 60, 1, 'lower bound on 90% confidence interval')
assertNear(high, 62, 1, 'upper bound on 90% confidence interval')
end
--------------------------------------------------------------------------------
-- RUN TESTS
--------------------------------------------------------------------------------
tester:add(myTests)
tester:run() | gpl-3.0 |
kyroskoh/kong | kong/plugins/hmac-auth/access.lua | 3 | 5256 | local cache = require "kong.tools.database_cache"
local stringy = require "stringy"
local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local math_abs = math.abs
local ngx_time = ngx.time
local ngx_gmatch = ngx.re.gmatch
local ngx_decode_base64 = ngx.decode_base64
local ngx_parse_time = ngx.parse_http_time
local ngx_sha1 = ngx.hmac_sha1
local ngx_set_header = ngx.req.set_header
local ngx_set_headers = ngx.req.get_headers
local split = stringy.split
local AUTHORIZATION = "authorization"
local PROXY_AUTHORIZATION = "proxy-authorization"
local DATE = "date"
local SIGNATURE_NOT_VALID = "HMAC signature cannot be verified"
local _M = {}
local function retrieve_hmac_fields(request, headers, header_name, conf)
local hmac_params = {}
local authorization_header = headers[header_name]
-- parse the header to retrieve hamc parameters
if authorization_header then
local iterator, iter_err = ngx_gmatch(authorization_header, "\\s*[Hh]mac\\s*username=\"(.+)\",\\s*algorithm=\"(.+)\",\\s*headers=\"(.+)\",\\s*signature=\"(.+)\"")
if not iterator then
ngx.log(ngx.ERR, iter_err)
return
end
local m, err = iterator()
if err then
ngx.log(ngx.ERR, err)
return
end
if m and #m >= 4 then
hmac_params.username = m[1]
hmac_params.algorithm = m[2]
hmac_params.hmac_headers = split(m[3], " ")
hmac_params.signature = m[4]
end
end
if conf.hide_credentials then
request.clear_header(header_name)
end
return hmac_params
end
local function create_hash(request, hmac_params, headers)
local signing_string = ""
local hmac_headers = hmac_params.hmac_headers
local count = #hmac_headers
for i = 1, count do
local header = hmac_headers[i]
local header_value = headers[header]
if not header_value then
if header == "request-line" then
-- request-line in hmac headers list
signing_string = signing_string..split(request.raw_header(), "\r\n")[1]
else
signing_string = signing_string..header..":"
end
else
signing_string = signing_string..header..":".." "..header_value
end
if i < count then
signing_string = signing_string.."\n"
end
end
return ngx_sha1(hmac_params.secret, signing_string)
end
local function validate_signature(request, hmac_params, headers)
local digest = create_hash(request, hmac_params, headers)
if digest then
return digest == ngx_decode_base64(hmac_params.signature)
end
end
local function hmacauth_credential_key(username)
return "hmacauth_credentials/"..username
end
local function load_secret(username)
local secret
if username then
secret = cache.get_or_set(hmacauth_credential_key(username), function()
local keys, err = dao.hmacauth_credentials:find_by_keys { username = username }
local result
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
elseif #keys > 0 then
result = keys[1]
end
return result
end)
end
return secret
end
local function validate_clock_skew(headers, allowed_clock_skew)
local date = headers[DATE]
if not date then
return false
end
local requestTime, err = ngx_parse_time(date)
if err then
return false
end
local skew = math_abs(ngx_time() - requestTime)
if skew > allowed_clock_skew then
return false
end
return true
end
function _M.execute(conf)
local headers = ngx_set_headers();
-- If both headers are missing, return 401
if not (headers[AUTHORIZATION] or headers[PROXY_AUTHORIZATION]) then
ngx.ctx.stop_phases = true
return responses.send_HTTP_UNAUTHORIZED()
end
-- validate clock skew
if not validate_clock_skew(headers, conf.clock_skew) then
responses.send_HTTP_FORBIDDEN("HMAC signature cannot be verified, a valid date field is required for HMAC Authentication")
end
-- retrieve hmac parameter from Proxy-Authorization header
local hmac_params = retrieve_hmac_fields(ngx.req, headers, PROXY_AUTHORIZATION, conf)
-- Try with the authorization header
if not hmac_params.username then
hmac_params = retrieve_hmac_fields(ngx.req, headers, AUTHORIZATION, conf)
end
if not (hmac_params.username and hmac_params.signature) then
responses.send_HTTP_FORBIDDEN(SIGNATURE_NOT_VALID)
end
-- validate signature
local secret = load_secret(hmac_params.username)
hmac_params.secret = secret.secret
if not validate_signature(ngx.req, hmac_params, headers) then
ngx.ctx.stop_phases = true -- interrupt other phases of this request
return responses.send_HTTP_FORBIDDEN("HMAC signature does not match")
end
-- Retrieve consumer
local consumer = cache.get_or_set(cache.consumer_key(secret.consumer_id), function()
local result, err = dao.consumers:find_by_primary_key({ id = secret.consumer_id })
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
return result
end)
ngx_set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
ngx_set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
ngx_set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
ngx.ctx.authenticated_entity = secret
end
return _M | apache-2.0 |
DrMelon/OpenRA | mods/ra/maps/soviet-01/soviet01.lua | 26 | 2150 | Yaks = { "yak", "yak", "yak" }
Airfields = { Airfield1, Airfield2, Airfield3 }
InsertYaks = function()
local i = 1
Utils.Do(Yaks, function(yakType)
local start = YakEntry.CenterPosition + WVec.New(0, (i - 1) * 1536, Actor.CruiseAltitude(yakType))
local dest = StartJeep.Location + CVec.New(0, 2 * i)
local yak = Actor.Create(yakType, true, { CenterPosition = start, Owner = player, Facing = (Map.CenterOfCell(dest) - start).Facing })
yak.Move(dest)
yak.ReturnToBase(Airfields[i])
i = i + i
end)
end
JeepDemolishingBridge = function()
StartJeep.Move(StartJeepMovePoint.Location)
Trigger.OnIdle(StartJeep, function()
Trigger.ClearAll(StartJeep)
if not BridgeBarrel.IsDead then
BridgeBarrel.Kill()
end
local bridge = Map.ActorsInBox(BridgeWaypoint.CenterPosition, Airfield1.CenterPosition,
function(self) return self.Type == "bridge1" end)[1]
if not bridge.IsDead then
bridge.Kill()
end
end)
end
WorldLoaded = function()
player = Player.GetPlayer("USSR")
france = Player.GetPlayer("France")
germany = Player.GetPlayer("Germany")
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
VillageRaidObjective = player.AddPrimaryObjective("Raze the village.")
Trigger.OnAllRemovedFromWorld(Airfields, function()
player.MarkFailedObjective(VillageRaidObjective)
end)
JeepDemolishingBridge()
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "MissionAccomplished")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "MissionFailed")
end)
Trigger.AfterDelay(DateTime.Seconds(2), InsertYaks)
end
Tick = function()
if france.HasNoRequiredUnits() and germany.HasNoRequiredUnits() then
player.MarkCompletedObjective(VillageRaidObjective)
end
end
| gpl-3.0 |
everslick/awesome | lib/awful/screen.lua | 7 | 4176 | ---------------------------------------------------------------------------
--- Screen module for awful
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008 Julien Danjou
-- @release @AWESOME_VERSION@
-- @module awful.screen
---------------------------------------------------------------------------
-- Grab environment we need
local capi =
{
mouse = mouse,
screen = screen,
client = client
}
local util = require("awful.util")
-- we use require("awful.client") inside functions to prevent circular dependencies.
local client
local screen = {}
local data = {}
data.padding = {}
---
-- Return Xinerama screen number corresponding to the given (pixel) coordinates.
-- The number returned can be used as an index into the global
-- `screen` table/object.
-- @param x The x coordinate
-- @param y The y coordinate
-- @param[opt] default The default return value. If unspecified, 1 is returned.
function screen.getbycoord(x, y, default)
for i = 1, capi.screen:count() do
local geometry = capi.screen[i].geometry
if((x < 0 or (x >= geometry.x and x < geometry.x + geometry.width))
and (y < 0 or (y >= geometry.y and y < geometry.y + geometry.height))) then
return i
end
end
-- No caller expects a nil result here, so just make something up
if default == nil then return 1 end
return default
end
--- Give the focus to a screen, and move pointer.
-- Keeps relative position of the pointer on the screen.
-- @param _screen Screen number (defaults / falls back to mouse.screen).
function screen.focus(_screen)
client = client or require("awful.client")
if _screen > capi.screen.count() then _screen = screen.focused() end
-- screen and pos for current screen
local s = capi.mouse.screen
local pos = capi.mouse.coords()
-- keep relative mouse position on the new screen
local relx = (pos.x - capi.screen[s].geometry.x) / capi.screen[s].geometry.width
local rely = (pos.y - capi.screen[s].geometry.y) / capi.screen[s].geometry.height
pos.x = capi.screen[_screen].geometry.x + relx * capi.screen[_screen].geometry.width
pos.y = capi.screen[_screen].geometry.y + rely * capi.screen[_screen].geometry.height
-- move cursor without triggering signals mouse::enter and mouse::leave
capi.mouse.coords(pos, true)
local c = client.focus.history.get(_screen, 0)
if c then
c:emit_signal("request::activate", "screen.focus", {raise=false})
end
end
--- Give the focus to a screen, and move pointer, by physical position relative to current screen.
-- @param dir The direction, can be either "up", "down", "left" or "right".
-- @param _screen Screen number.
function screen.focus_bydirection(dir, _screen)
local sel = _screen or screen.focused()
if sel then
local geomtbl = {}
for s = 1, capi.screen.count() do
geomtbl[s] = capi.screen[s].geometry
end
local target = util.get_rectangle_in_direction(dir, geomtbl, capi.screen[sel].geometry)
if target then
return screen.focus(target)
end
end
end
--- Give the focus to a screen, and move pointer, but relative to the current
-- focused screen.
-- @param i Value to add to the current focused screen index. 1 will focus next
-- screen, -1 would focus the previous one.
function screen.focus_relative(i)
return screen.focus(util.cycle(capi.screen.count(), screen.focused() + i))
end
--- Get or set the screen padding.
-- @param _screen The screen object to change the padding on
-- @param padding The padding, an table with 'top', 'left', 'right' and/or
-- 'bottom'. Can be nil if you only want to retrieve padding
function screen.padding(_screen, padding)
if padding then
data.padding[_screen] = padding
_screen:emit_signal("padding")
end
return data.padding[_screen]
end
--- Get the focused screen.
-- This can be replaced in a user's config.
-- @treturn integer
function screen.focused()
return capi.mouse.screen
end
capi.screen.add_signal("padding")
return screen
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/crawler_egg.lua | 3 | 1092 | -----------------------------------------
-- ID: 4357
-- Item: crawler_egg
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Health 10
-- Magic 10
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4357);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 10);
target:addMod(MOD_MP, 10);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 10);
target:delMod(MOD_MP, 10);
end;
| gpl-3.0 |
cloudflare/lua-resty-json | tests/test.lua | 1 | 2553 | package.cpath = package.cpath..";../?.so"
package.path = package.cpath..";../?.lua"
local ljson_decoder = require 'json_decoder'
local decoder = ljson_decoder.new()
local function cmp_lua_var(obj1, obj2)
if type(obj1) ~= type(obj2) then
return
end
if type(obj1) == "string" or
type(obj1) == "number" or
type(obj1) == "nil" or
type(obj1) == "boolean" then
return obj1 == obj2 and true or nil
end
if (type(obj1) ~= "table") then
print("unknown type", type(obj1));
return
end
-- compare table
for k, v in pairs(obj1) do
if not cmp_lua_var(v, obj2[k]) then
-- print(v," vs ", obj2[k])
return
end
end
for k, v in pairs(obj2) do
if not cmp_lua_var(v, obj1[k]) then
-- print(v," vs ", obj1[k])
return
end
end
return true
end
local test_fail_num = 0;
local test_total = 0;
local function ljson_test(test_id, parser, input, expect)
test_total = test_total + 1
io.write(string.format("Testing %s ...", test_id))
local result = decoder:decode(input)
if cmp_lua_var(result, expect) then
print("succ!")
else
test_fail_num = test_fail_num + 1
print("failed!")
--ljson_decoder.debug(result)
end
end
local json_parser = ljson_decoder.create()
-- Test 1
local input = [=[[1, 2, 3, {"key1":"value1", "key2":"value2"}, "lol"]]=]
local output = {1, 2, 3, {["key1"] = "value1", ["key2"] = "value2" }, "lol"}
ljson_test("test1", json_parser, input, output);
-- Test 2
input = [=[[]]=]
output = {}
ljson_test("test2", json_parser, input, output);
-- Test 3
input = [=[[{}]]=]
output = {{}}
ljson_test("test3", json_parser, input, output);
input = [=[[null]]=]
output = {nil}
ljson_test("test4", json_parser, input, output);
input = [=[[true, false]]=]
output = {true, false}
ljson_test("test5", json_parser, input, output);
input = "-" -- invalid input
output = nil
ljson_test("test6", json_parser, input, output);
-- The input string is "[\0265]", where char \0265 is illegal. The json decoder
-- once crash on this case.
input = string.format("[%c]", 181)
output = nil
ljson_test("test7", json_parser, input, output);
input = string.format("[ %c]", 181)
output = nil
ljson_test("test8", json_parser, input, output);
io.write(string.format(
"\n============================\nTotal test count %d, fail %d\n",
test_total, test_fail_num))
if test_fail_num == 0 then
os.exit(0)
else
os.exit(1)
end
| bsd-2-clause |
Sonicrich05/FFXI-Server | scripts/zones/Western_Altepa_Desert/npcs/_3h6.lua | 17 | 1870 | -----------------------------------
-- Area: Western Altepa Desert
-- NPC: _3h6 (Topaz Column)
-- Notes: Mechanism for Altepa Gate
-- @pos -260 10 -344 125
-----------------------------------
package.loaded["scripts/zones/Western_Altepa_Desert/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Western_Altepa_Desert/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local TopazID = npc:getID();
local Ruby = GetNPCByID(TopazID-1):getAnimation();
local Topaz = npc:getAnimation();
local Emerald = GetNPCByID(TopazID+1):getAnimation();
local Sapphire = GetNPCByID(TopazID+2):getAnimation();
if (Topaz ~= 8) then
npc:setAnimation(8);
GetNPCByID(TopazID-4):setAnimation(8);
else
player:messageSpecial(DOES_NOT_RESPOND);
end
if (Emerald == 8 and Ruby == 8 and Sapphire == 8) then
local rand = math.random(15,30);
local timeDoor = rand * 60;
-- Add timer for the door
GetNPCByID(TopazID-6):openDoor(timeDoor);
-- Add same timer for the 4 center lights
GetNPCByID(TopazID-5):openDoor(timeDoor);
GetNPCByID(TopazID-4):openDoor(timeDoor);
GetNPCByID(TopazID-3):openDoor(timeDoor);
GetNPCByID(TopazID-2):openDoor(timeDoor);
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 |
CSAILVision/sceneparsing | trainingCode/torch/DataLoader.lua | 1 | 3378 | require 'hdf5'
local utils = require 'utils'
local DataLoader = torch.class('DataLoader')
function DataLoader:__init(opt)
-- open the hdf5 file
print('DataLoader loading h5 file: ', opt.h5_file)
self.h5_file = hdf5.open(opt.h5_file, 'r')
self.info = utils.read_json(opt.json_file)
-- extract image size from dataset
local images_size = self.h5_file:read('/images'):dataspaceSize()
assert(#images_size == 4, '/images should be a 4D tensor')
assert(images_size[3] == images_size[4], 'width and height must match')
self.num_images = images_size[1]
self.num_channels = images_size[2]
self.max_image_size = images_size[3]
print(string.format('read %d images of size %dx%dx%d', self.num_images,
self.num_channels, self.max_image_size, self.max_image_size))
-- extract annotation size from dataset
local annotations_size = self.h5_file:read('/annotations'):dataspaceSize()
assert(#annotations_size == 3, '/annotations should be a 3D tensor')
assert(annotations_size[1] == images_size[1],'/images number should be equal to /annotations number')
-- separate out indexes for each of the provided splits
self.split_ix = {}
self.iterators = {}
for i,img in pairs(self.info.images) do
local split = img.split
if not self.split_ix[split] then
-- initialize new split
self.split_ix[split] = {}
self.iterators[split] = 1
end
table.insert(self.split_ix[split], i)
end
for k,v in pairs(self.split_ix) do
print(string.format('assigned %d images to split %s', #v, k))
end
end
function DataLoader:resetIterator(split)
self.iterators[split] = 1
end
function DataLoader:nextBatch(opt)
local split = opt.split
local batch_size = opt.batch_size
local split_ix = self.split_ix[split]
assert(split_ix, 'split ' .. split .. ' not found.')
-- pick an index of the datapoint to load next
local img_batch_raw = torch.ByteTensor(batch_size, 3, self.max_image_size, self.max_image_size)
local anno_batch_raw = torch.ByteTensor(batch_size, self.max_image_size, self.max_image_size)
local max_index = #split_ix
local wrapped = false
for i=1,batch_size do
local ri = self.iterators[split] -- get next index from iterator
local ri_next = ri + 1 -- increment iterator
if ri_next > max_index then ri_next = 1; wrapped = true end -- wrap back around
self.iterators[split] = ri_next
ix = split_ix[ri]
assert(ix ~= nil, 'bug: split ' .. split .. ' was accessed out of bounds with ' .. ri)
-- fetch the image from h5
local img = self.h5_file:read('/images'):partial({ix,ix},{1,self.num_channels},
{1,self.max_image_size},{1,self.max_image_size})
img = torch.squeeze(img)
-- fetch the annotation from h5
local anno = self.h5_file:read('/annotations'):partial({ix,ix},
{1,self.max_image_size},{1,self.max_image_size})
anno = torch.squeeze(anno)
-- data augmentation by flipping
if split == 'train' then
if math.random(2) > 1 then
image.hflip(img, img)
image.hflip(anno, anno)
end
end
img_batch_raw[i] = img
anno_batch_raw[i] = anno
end
local data = {}
data.images = img_batch_raw
data.annotations = anno_batch_raw
data.bounds = {it_pos_now = self.iterators[split], it_max = #split_ix, wrapped = wrapped}
return data
end
| bsd-3-clause |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Windurst_Walls/npcs/_6n2.lua | 4 | 5142 | -----------------------------------
-- Area: Windurst Walls
-- Door: House of the Hero
-- Involved in Mission 2-1
-- Involved In Quest: Know One's Onions, Onion Rings, The Puppet Master, Class Reunion
-- @pos -26 -13 260 239
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local ThePuppetMaster = player:getQuestStatus(WINDURST,THE_PUPPET_MASTER);
local ClassReunion = player:getQuestStatus(WINDURST,CLASS_REUNION);
local CarbuncleDebacle = player:getQuestStatus(WINDURST,CARBUNCLE_DEBACLE);
-- Check for Missions first (priority?)
if(player:getCurrentMission(WINDURST) == LOST_FOR_WORDS and player:getVar("MissionStatus") == 5) then
player:startEvent(0x0151);
else
----------------------------------------------------
-- Carbuncle Debacle
if(player:getMainLvl() >= AF2_QUEST_LEVEL and player:getMainJob() == 15 and ClassReunion == QUEST_COMPLETED and CarbuncleDebacle == QUEST_AVAILABLE and player:needToZone() == false) then
player:startEvent(0x019f); -- Carby begs for your help
----------------------------------------------------
-- Class Reunion
elseif(player:getMainLvl() >= AF2_QUEST_LEVEL and player:getMainJob() == 15 and ThePuppetMaster == QUEST_COMPLETED and ClassReunion == QUEST_AVAILABLE and player:needToZone() == false) then
player:startEvent(0x019d); -- Carby asks for your help again.
----------------------------------------------------
-- The Puppet Master
elseif(player:getMainLvl() >= AF1_QUEST_LEVEL and player:getMainJob() == 15 and ThePuppetMaster ~= QUEST_ACCEPTED and player:needToZone() == false and ClassReunion ~= QUEST_ACCEPTED and CarbuncleDebacle ~= QUEST_ACCEPTED) then -- you need to be on SMN as well to repeat the quest
player:startEvent(0x0192); -- Carby asks for your help, visit Juroro
elseif(player:getQuestStatus(WINDURST,THE_PUPPET_MASTER) == QUEST_ACCEPTED and player:getVar("ThePuppetMasterProgress") == 1) then
player:startEvent(0x0193); -- reminder to visit Juroro
----------------------------------------------------
elseif(player:hasKeyItem(JOKER_CARD)) then
player:startEvent(0x0183,0,JOKER_CARD);
elseif(player:getVar("WildCard") == 1) then
player:startEvent(0x0182);
elseif(player:getVar("OnionRings") == 1) then
player:startEvent(0x0121);
elseif(player:getVar("KnowOnesOnions") == 1) then
player:startEvent(0x0120,0,4387);
elseif(player:getQuestStatus(WINDURST,I_CAN_HEAR_A_RAINBOW) == QUEST_AVAILABLE and player:getMainLvl() >= 30 and player:hasItem(1125)) then
player:startEvent(0x0180,1125,1125,1125,1125,1125,1125,1125,1125);
elseif(player:getQuestStatus(WINDURST,I_CAN_HEAR_A_RAINBOW) == QUEST_ACCEPTED) then
player:startEvent(0x0181,1125,1125,1125,1125,1125,1125,1125,1125);
else
player:messageSpecial(7532); -- "The doors are firmly sealed shut."
end;
end;
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x0120) then
player:setVar("KnowOnesOnions",2);
elseif(csid == 0x0121) then
player:completeQuest(WINDURST,ONION_RINGS);
player:addFame(WINDURST,WIN_FAME*100);
player:addTitle(STAR_ONION_BRIGADIER);
player:delKeyItem(OLD_RING);
player:setVar("OnionRingsTime",0);
player:setVar("OnionRings",2);
elseif(csid == 0x0180) then
player:addQuest(WINDURST, I_CAN_HEAR_A_RAINBOW);
elseif(csid == 0x0182) then
player:setVar("WildCard",2);
elseif(csid == 0x0183) then
player:delKeyItem(JOKER_CARD);
player:addGil(GIL_RATE*8000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*8000);
elseif(csid == 0x0151) then
-- Mark the progress
player:setVar("MissionStatus",6);
elseif(csid == 0x0192) then
if (player:getQuestStatus(WINDURST,THE_PUPPET_MASTER) == QUEST_COMPLETED) then
player:delQuest(WINDURST,THE_PUPPET_MASTER);
player:addQuest(WINDURST,THE_PUPPET_MASTER); -- this needs only if you repeat this quest
end;
player:setVar("ThePuppetMasterProgress",1);
player:addQuest(WINDURST,THE_PUPPET_MASTER);
elseif(csid == 0x019d) then
player:setVar("ClassReunionProgress",1);
player:addQuest(WINDURST,CLASS_REUNION);
player:addKeyItem(CARBUNCLES_TEAR);
player:messageSpecial(KEYITEM_OBTAINED,CARBUNCLES_TEAR);
elseif(csid == 0x019f) then
player:addQuest(WINDURST,CARBUNCLE_DEBACLE);
player:setVar("CarbuncleDebacleProgress",1);
end;
end;
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Garlaige_Citadel/npcs/Mashira.lua | 2 | 2036 | -----------------------------------
-- Area: Garlaige Citadel
-- NPC: Mashira
-- Involved in Quests: Rubbish day, Making Amens!
-- @zone 200
-- @pos 141 -6 138
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Garlaige_Citadel/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getQuestStatus(JEUNO,RUBBISH_DAY) == QUEST_ACCEPTED and player:getVar("RubbishDayVar") == 0) then
player:startEvent(0x000b,1); -- For the quest "Rubbish day"
elseif (player:getQuestStatus(WINDURST,MAKING_AMENS) == QUEST_ACCEPTED) then
if (player:hasKeyItem(128) == true) then
player:startEvent(0x000b,3);
else player:startEvent(0x000b,0); -- Making Amens dialogue
end
else
player:startEvent(0x000b,3); -- Standard dialog and menu
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);
RubbishDay = player:getQuestStatus(JEUNO,RUBBISH_DAY);
MakingAmens = player:getQuestStatus(WINDURST,MAKING_AMENS);
if(csid == 0x000b and option == 1 and RubbishDay == QUEST_ACCEPTED) then
player:delKeyItem(MAGIC_TRASH);
player:setVar("RubbishDayVar",1);
elseif(csid == 0x000b and option == 0 and MakingAmens == QUEST_ACCEPTED) then
player:addKeyItem(128); --Broken Wand
player:messageSpecial(KEYITEM_OBTAINED,128);
player:tradeComplete();
end
end;
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/abilities/weapon_bash.lua | 2 | 1127 | -----------------------------------
-- Ability: Weapon Bash
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- OnUseAbility
-----------------------------------
function OnAbilityCheck(player,target,ability)
if (not player:isWeaponTwoHanded()) then
return MSGBASIC_NEEDS_2H_WEAPON,0;
else
return 0,0;
end
end;
function OnUseAbility(player, target, ability)
-- Applying Weapon Bash stun. Rate is said to be near 100%, so let's say 99%.
if(math.random()*100 < 99) then
target:addStatusEffect(EFFECT_STUN,1,0,6);
end
-- Weapon Bash deals damage dependant of Dark Knight level
local darkKnightLvl = 0;
if(player:getMainJob()==JOB_DRK) then
darkKnightLvl = player:getMainLvl(); -- Use Mainjob Lvl
elseif(player:getSubJob()==JOB_DRK) then
darkKnightLvl = player:getSubLvl(); -- Use Subjob Lvl
end
-- Calculating and applying Weapon Bash damage
local damage = math.floor(((darkKnightLvl + 11) / 4) + player:getMod(MOD_WEAPON_BASH));
target:delHP(damage);
target:updateEnmityFromDamage(player,damage);
end;
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Southern_San_dOria/npcs/Deraquien.lua | 2 | 2286 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Deraquien
-- Involved in Quest: Lure of the Wildcat (San d'Oria)
-- @pos -98 -2 31 230
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
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) then -- Trade Magicmart_flyer
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(player:getVar("wildcatSandy_var"),5) == false) then
player:startEvent(0x032b);
else
player:startEvent(0x012);
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 == 0x032b) then
player:setMaskBit(player:getVar("wildcatSandy_var"),"wildcatSandy_var",5,true);
end
end;
---------other CS
-- player:startEvent(0x028e) -- nothing to report
-- player:startEvent(0x0021)-- theif of royl sceptre
-- player:startEvent(0x002f)-- as again about the theif
-- player:startEvent(0x0022) -- reminder of theif in la thein
-- player:startEvent(0x0050) -- thief caught but phillone was there
-- player:startEvent(0x0014) -- go get reward for thief
-- player:startEvent(0x0057) -- vijrtall shows up and derq tells you go talk tho phillone
-- player:startEvent(0x001e) --reminder go talk to phillone
-- player:startEvent(0x0026) -- go help retrieve royal sceptre
-- player:startEvent(0x001b) -- the lady wanst involved in the theft :(
| gpl-3.0 |
Servius/tfa-sw-weapons-repository | In Development/servius_development/tfa_swrp_imperial_era_weapons_pack/lua/weapons/tfa_voxel_ee3/shared.lua | 1 | 10614 | SWEP.Gun = ("tfa_voxel_ee3") --Make sure this is unique. Specically, your folder name.
if (GetConVar(SWEP.Gun.."_allowed")) != nil then
if not (GetConVar(SWEP.Gun.."_allowed"):GetBool()) then SWEP.Base = "tfa_blacklisted" SWEP.PrintName = SWEP.Gun return end
end
SWEP.Base = "tfa_3dscoped_base"
SWEP.Category = "TFA Imperial Era Weapons" --The category. Please, just choose something generic or something I've already done if you plan on only doing like one swep..
SWEP.Manufacturer = "Blastech Industries" --Gun Manufactrer (e.g. Hoeckler and Koch )
SWEP.Author = "Teduken" --Author Tooltip
SWEP.Contact = "http://www.voxelservers.net/" --Contact Info Tooltip
SWEP.DrawCrosshair = true -- Draw the crosshair?
SWEP.DrawCrosshairIS = false --Draw the crosshair in ironsights?
SWEP.PrintName = "EE-3" -- Weapon name (Shown on HUD)
SWEP.DrawAmmo = true -- Should draw the default HL2 ammo counter if enabled in the GUI.
-- Iron and Run Sights --
SWEP.data = {}
SWEP.data.ironsights = 1 --Enable Ironsights
SWEP.Secondary.IronFOV = 55 -- How much you 'zoom' in. Less is more! Don't have this be <= 0. A good value for ironsights is like 70.
SWEP.IronSightsPos = Vector(-3.457, 3, 2.23)
SWEP.IronSightsAng = Vector(0, 0, 0)
SWEP.RunSightsPos = Vector (2.009, -3.217, -1.407) --Change this, using SWEP Creation Kit preferably
SWEP.RunSightsAng = Vector (-8.443, 18.995, -16.885) --Change this, using SWEP Creation Kit preferably
-- Primary Stuff --
SWEP.Primary.Sound = Sound ("weapons/synbf3/ee3_fire.wav");
SWEP.Primary.ReloadSound = Sound ("weapons/synbf3/ee3_reload.wav");
SWEP.Primary.SilencedSound = nil -- This is the sound of the weapon, when silenced.
SWEP.Primary.Damage = 49 -- Damage, in standard damage points.
SWEP.Primary.HullSize = 0 --Big bullets, increase this value. They increase the hull size of the hitscan bullet.
SWEP.DamageType = nil--See DMG enum. This might be DMG_SHOCK, DMG_BURN, DMG_BULLET, etc.
SWEP.Primary.NumShots = 1 --The number of shots the weapon fires. SWEP.Shotgun is NOT required for this to be >1.
SWEP.Primary.Automatic = false -- Automatic/Semi Auto
SWEP.Primary.RPM = nil -- This is in Rounds Per Minute / RPM
SWEP.Primary.RPM_Semi = 300 -- RPM for semi-automatic or burst fire. This is in Rounds Per Minute / RPM
SWEP.Primary.RPM_Burst = nil -- RPM for burst fire, overrides semi. This is in Rounds Per Minute / RPM
SWEP.Primary.BurstDelay = nil -- Delay between bursts, leave nil to autocalculate
SWEP.FiresUnderwater = true
-- Firemode Stuff--
SWEP.SelectiveFire = false --Allow selecting your firemode?
SWEP.DisableBurstFire = false --Only auto/single?
SWEP.OnlyBurstFire = false --No auto, only burst/single?
SWEP.DefaultFireMode = "single" --Default to auto or whatev
SWEP.FireModeName = nil --Change to a text value to override it
-- Ammo Stuff --
SWEP.Primary.ClipSize = 30 -- This is the size of a clip
SWEP.Primary.DefaultClip = 120 -- This is the number of bullets the gun gives you, counting a clip as defined directly above.
SWEP.Primary.Ammo = "ar2" -- What kind of ammo. Options, besides custom, include pistol, 357, smg1, ar2, buckshot, slam, SniperPenetratedRound, and AirboatGun.
SWEP.Primary.AmmoConsumption = 1 --Ammo consumed per shot
--Pistol, buckshot, and slam like to ricochet. Use AirboatGun for a light metal peircing shotgun pellets
-- Recoil Stuff --
SWEP.Primary.KickUp = 0.3 -- This is the maximum upwards recoil (rise)
SWEP.Primary.KickDown = 0 -- This is the maximum downwards recoil (skeet)
SWEP.Primary.KickHorizontal = 0.2 -- This is the maximum sideways recoil (no real term)
SWEP.Primary.StaticRecoilFactor = 0.5 --Amount of recoil to directly apply to EyeAngles. Enter what fraction or percentage (in decimal form) you want. This is also affected by a convar that defaults to 0.5.
SWEP.Primary.Spread = .07 --This is hip-fire acuracy. Less is more (1 is horribly awful, .0001 is close to perfect)
SWEP.Primary.IronAccuracy = .00000001 -- Ironsight accuracy, should be the same for shotguns
--Unless you can do this manually, autodetect it. If you decide to manually do these, uncomment this block and remove this line.
SWEP.Primary.SpreadMultiplierMax = 2.5 --How far the spread can expand when you shoot.
SWEP.Primary.SpreadIncrement = 1/2.5 --What percentage of the modifier is added on, per shot.
SWEP.Primary.SpreadRecovery = 0.5 --How much the spread recovers, per second.
SWEP.Primary.Range = -1 -- The distance the bullet can travel in source units. Set to -1 to autodetect based on damage/rpm.
SWEP.Primary.RangeFalloff = -1 -- The percentage of the range the bullet damage starts to fall off at. Set to 0.8, for example, to start falling off after 80% of the range.
SWEP.ProjectileEntity = nil --Entity to shoot
SWEP.ProjectileVelocity = 0 --Entity to shoot's velocity
SWEP.ProjectileModel = nil --Entity to shoot's model
-- Viewmodel Stuff --
SWEP.ViewModel = "models/weapons/synbf3/c_EE3.mdl" --Viewmodel path
SWEP.ViewModelFOV = 50 -- This controls how big the viewmodel looks. Less is more.
SWEP.ViewModelFlip = false -- Set this to true for CSS models, or false for everything else (with a righthanded viewmodel.)
SWEP.MaterialTable = nil --Make sure the viewmodel and the worldmodel have the same material ids. Next, fill this in with your desired submaterials.
SWEP.UseHands = true --Use gmod c_arms system.
SWEP.VMPos = Vector(0,0,0) --The viewmodel positional offset, constantly. Subtract this from any other modifications to viewmodel position.
SWEP.VMAng = Vector(0,0,0) --The viewmodel angular offset, constantly. Subtract this from any other modifications to viewmodel angle.
SWEP.VElements = {
["element_name"] = { type = "Model", model = "models/rtcircle.mdl", bone = "v_ee3_reference001", rel = "", pos = Vector(0, 0.44, 4.65), angle = Angle(0, 90, 0), size = Vector(0.23, 0.23, 0.23), color = Color(255, 255, 255, 255), surpresslightning = false, material = "!tfa_rtmaterial", skin = 0, bodygroup = {} }
}
-- Blowback Stuff --
SWEP.BlowbackEnabled = true --Enable Blowback?
SWEP.BlowbackVector = Vector(0,-0.5,0.1) --Vector to move bone <or root> relative to bone <or view> orientation.
SWEP.BlowbackCurrentRoot = 0 --Amount of blowback currently, for root
SWEP.BlowbackCurrent = 0 --Amount of blowback currently, for bones
SWEP.BlowbackBoneMods = nil --Viewmodel bone mods via SWEP Creation Kit
SWEP.Blowback_Only_Iron = true --Only do blowback on ironsights
SWEP.Blowback_PistolMode = false --Do we recover from blowback when empty?
SWEP.Blowback_Shell_Effect = "ShellEject"
--World Model Stuff
SWEP.WorldModel = "models/weapons/synbf3/w_ee3.mdl" -- Weapon world model path
SWEP.HoldType = "ar2" -- This is how others view you carrying the weapon. Options include:
-- Tracer and effect stuff--
SWEP.Tracer = 0 --Bullet tracer. TracerName overrides this.
SWEP.TracerName = "vox_sw_laser_red" --Change to a string of your tracer name. Can be custom. --There is a nice example at https://github.com/garrynewman/garrysmod/blob/master/garrysmod/gamemodes/base/entities/effects/tooltracer.lua
SWEP.TracerCount = 1 --0 disables, otherwise, 1 in X chance
SWEP.TracerLua = false --Use lua effect, TFA Muzzle syntax. Currently obsolete.
SWEP.TracerDelay = 0.01 --Delay for lua tracer effect
SWEP.ImpactEffect = "vox_sw_impact_2"--Impact Effect
SWEP.ImpactDecal = "FadingScorch"--Impact Decal
-- Recoil --
SWEP.Primary.KickUp = 0.2
SWEP.Primary.KickDown = 0.1
SWEP.Primary.KickHorizontal = 0.1
SWEP.Primary.KickRight = 0.1
SWEP.DisableChambering = true
-- Scope Stuff--
SWEP.RTScopeAttachment = -1
SWEP.Scoped_3D = true
SWEP.ScopeReticule = "scope/gdcw_elcanreticle"
SWEP.Secondary.ScopeZoom = 12
SWEP.ScopeReticule_Scale = {2.5,2.5}
if surface then
SWEP.Secondary.ScopeTable = nil --[[
{
scopetex = surface.GetTextureID("scope/gdcw_closedsight"),
reticletex = surface.GetTextureID("scope/gdcw_acogchevron"),
dottex = surface.GetTextureID("scope/gdcw_acogcross")
}
]]--
end
DEFINE_BASECLASS( SWEP.Base )
-- Precautionary stuff that mostly doesn't need to be edited --
SWEP.Spawnable = true --Can you, as a normal user, spawn this?
SWEP.AdminSpawnable = true --Can an adminstrator spawn this? Does not tie into your admin mod necessarily, unless its coded to allow for GMod's default ranks somewhere in its code. Evolve and ULX should work, but try to use weapon restriction rather than these.
SWEP.Primary.DamageType = DMG_BULLET
SWEP.DamageType = DMG_BULLET
SWEP.ThirdPersonReloadDisable=false
SWEP.DoMuzzleFlash = false --Do a muzzle flash?
SWEP.DisableChambering = true --Disable round-in-the-chamber
SWEP.Primary.PenetrationMultiplier = 0 --Change the amount of something this gun can penetrate through
function SWEP:DrawHands()
self.UseHandsDefault = self.UseHandsDefault or self.UseHands
if !self.UseHandsDefault then return end
if !IsValid(self) or !self:OwnerIsValid() then return end
local vm = self.OwnerViewModel
if !IsValid(vm) then return end
if !IsValid(self.Owner.SWHands) then
self.Owner.SWHands = ClientsideModel("models/weapons/c_clonearms.mdl")
self.Owner.SWHands:SetParent(vm)
self.Owner.SWHands:SetPos(self.Owner:GetShootPos())
self.Owner.SWHands:SetAngles(self.Owner:EyeAngles())
self.Owner.SWHands:AddEffects( EF_BONEMERGE )
self.Owner.SWHands:SetNoDraw(true)
self.Owner.SWHands.BoneMergedEnt = vm
elseif self.Owner.SWHands:GetParent() != vm then
self.Owner.SWHands:SetModel("models/weapons/c_clonearms.mdl")
self.Owner.SWHands:SetParent(vm)
self.Owner.SWHands:SetPos(self.Owner:GetShootPos())
self.Owner.SWHands:SetAngles(self.Owner:EyeAngles())
self.Owner.SWHands:AddEffects( EF_BONEMERGE )
elseif self.Owner.SWHands:GetModel()!="models/weapons/c_clonearms.mdl" then
self.Owner.SWHands:SetModel("models/weapons/c_clonearms.mdl")
end
if self.Owner.SWHands then
self.Owner.SWHands:DrawModel()
end
self.UseHands = false
end
| apache-2.0 |
Sonicrich05/FFXI-Server | scripts/zones/Northern_San_dOria/npcs/Prerivon.lua | 38 | 1025 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Prerivon
-- Type: Standard Dialogue NPC
-- @zone: 231
-- @pos 142.324 0.000 132.515
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,PRERIVON_DIALOG);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
rayaman/multi | oldversions/MultiManager(1.2.0).lua | 1 | 32750 | if not bin then
print('Warning the \'bin\' library wasn\'t required! multi:tofile(path) and the multi:fromfile(path,int) features will not work!')
end
if table.unpack then
unpack=table.unpack
end
function table.merge(t1, t2)
for k,v in pairs(t2) do
if type(v) == 'table' then
if type(t1[k] or false) == 'table' then
table.merge(t1[k] or {}, t2[k] or {})
else
t1[k] = v
end
else
t1[k] = v
end
end
return t1
end
multi = {}
multi.Version={'A',2,0}-- History: EventManager,EventManager+,MultiManager <-- Current After 6.3.0 Versioning scheme was altered. A.0.0
multi.help=[[
For a list of features do print(multi.Features)
For a list of changes do print(multi.changelog)
For current version do print(multi.Version)
For current stage do print(multi.stage)
For help do print(multi.help) :D
]]
multi.stage='stable'
multi.Features='Current Version: '..multi.Version[1]..'.'..multi.Version[2]..'.'..multi.Version[3]..' '..multi.stage..[[
MultiManager has 19 Objects: # indicates most commonly used 1-19 1 being the most used by me
+Events #7
+Alarms #2
+Loops #3
+Steps #4
+TSteps #6
+Triggers #16
+Tasks #12
+Connections #1 -- This is a rather new feature of this library, but has become the most useful for async handling. Knowing this is already 50% of this library
+Timers #14 -- this was tricky because these make up both Alarms and TSteps, but in purly using this standalone is almost non existent
+Jobs #11
+Process #10
+Conditions #15
+Ranges #8
+Threads #13
+Functions #5
+Queuers #17
+Updaters #9
+Watchers #18
+CustomObjects #19
Constructors [Runners]
---------------------- Note: multi is the main Processor Obj It cannot be paused or destroyed (kinda)
intObj=multi:newProcess([string: FILE defualt: nil])
intObj=multi:newQueuer([string: FILE defualt: nil])
Constructors [ACTORS]
--------------------- Note: everything is a multiObj!
eventObj=multi:newEvent([function: TASK defualt: function() end])
alarmObj=multi:newAlarm([number: SET defualt: 0])
loopObj=multi:newLoop([function: FUNC])
stepObj=multi:newStep([number: START defualt: 0],[number: RESET defualt: inf],[number: COUNT defualt: 1],[number: SKIP defualt: 0])
tstepObj=multi:newTStep([number: START defualt: 0],[number: RESET defualt: inf],[number: COUNT defualt: 1],[number: SET defualt: 1])
updaterObj=multi:newUpdater([number: SKIP defualt: 0])
watcherObj=multi:newWatcher(table: NAMESPACE,string: NAME)
multiObj=multi:newCustomObject([table: OBJREF],[string: T='process'])
void=multi:newThread(string: name,function: func)
Constructors [Semi-ACTORS]
--------------------------
multi:newJob(function: func,[string: name])
multi:newRange(number: a,number: b,[number: c])
multi:newCondition(func)
Constructors [NON-ACTORS]
-------------------------
multi:newTrigger(function: func)
multi:newTask(function: func)
multi:newConnection()
multi:newTimer()
multi:newFunction(function: func)
]]
multi.changelog=[[Changelog starts at Version A.0.0
New in A.0.0
Nothing really however a changelog will now be recorded! Feel free to remove this extra strings if space is a requriment
version.major.minor
New in A.1.0
Changed: multi:newConnection(protect) method
Changed the way you are able to interact with it by adding the __call metamethod
Old usage:
OnUpdate=multi:newConnection()
OnUpdate:connect(function(...)
print("Updating",...)
end)
OnUpdate:Fire(1,2,3)
New usage: notice that connect is no longer needed! Both ways still work! and always will work :)
OnUpdate=multi:newConnection()
OnUpdate(function(...)
print("Updating",...)
end)
OnUpdate:Fire(1,2,3)
New in A.2.0 (12/31/2016)
Added:
connectionobj.getConnection(name)
returns a list of an instance (or instances) of a single connect made with connectionobj:connect(func,name) or connectionobj(func,name)
if you can orginize data before hand you can route info to certain connections thus saving a lot of cpu time. NOTE: only one name per each connection... you can't have 2 of the same names in a dictonary... the last one will be used
Changed: obj=multi:newConnection()
obj:connect(func,name) and obj(func,name)
Added the name argument to allow indexing specific connection objects... Useful when creating an async library
]]
multi.__index = multi
multi.Mainloop={}
multi.Tasks={}
multi.Tasks2={}
multi.Garbage={}
multi.ender={}
multi.Children={}
multi.Paused={}
multi.Active=true
multi.fps=60
multi.Id=-1
multi.Type='mainprocess'
multi.Rest=0
multi._type=type
multi.Jobs={}
multi.queue={}
multi.jobUS=2
multi.clock=os.clock
multi.time=os.time
multi.LinkedPath=multi
multi.queuefinal=function(self)
self:Destroy()
if self.Parent.Mainloop[#self.Parent.Mainloop] then
self.Parent.Mainloop[#self.Parent.Mainloop]:Resume()
else
for i=1,#self.Parent.funcE do
self.Parent.funcE[i](self)
end
self.Parent:Remove()
end
end
--Do not change these ever...Any other number will not work (Unless you are using enablePriority2() then change can be made. Just ensure that Priority_Idle is the greatest and Priority_Core is 1!)
multi.Priority_Core=1
multi.Priority_High=4
multi.Priority_Above_Normal=16
multi.Priority_Normal=64
multi.Priority_Below_Normal=256
multi.Priority_Low=1024
multi.Priority_Idle=4096
multi.PList={multi.Priority_Core,multi.Priority_High,multi.Priority_Above_Normal,multi.Priority_Normal,multi.Priority_Below_Normal,multi.Priority_Low,multi.Priority_Idle}
multi.PStep=1
--^^^^
multi.PriorityTick=1 -- Between 1 and 4 any greater and problems arise
multi.Priority=multi.Priority_Core
function multi:setDomainName(name)
self[name]={}
end
function multi:linkDomain(name)
return self[name]
end
function multi:_Pause()
self.Active=false
end
function multi:setPriority(s)
if type(s)==number then
self.Priority=s
elseif type(s)=='string' then
if s:lower()=='core' or s:lower()=='c' then
self.Priority=self.Priority_Core
elseif s:lower()=='high' or s:lower()=='h' then
self.Priority=self.Priority_High
elseif s:lower()=='above' or s:lower()=='an' then
self.Priority=self.Priority_Above_Normal
elseif s:lower()=='normal' or s:lower()=='n' then
self.Priority=self.Priority_Normal
elseif s:lower()=='below' or s:lower()=='bn' then
self.Priority=self.Priority_Below_Normal
elseif s:lower()=='low' or s:lower()=='l' then
self.Priority=self.Priority_Low
elseif s:lower()=='idle' or s:lower()=='i' then
self.Priority=self.Priority_Idle
end
end
end
-- System
function os.getOS()
if package.config:sub(1,1)=='\\' then
return 'windows'
else
return 'unix'
end
end
if os.getOS()=='windows' then
function os.sleep(n)
if n > 0 then os.execute('ping -n ' .. tonumber(n+1) .. ' localhost > NUL') end
end
else
function os.sleep(n)
os.execute('sleep ' .. tonumber(n))
end
end
function multi:getParentProcess()
return self.Mainloop[self.CID]
end
function multi:Stop()
self.Active=false
end
function multi:condition(cond)
if not self.CD then
self:Pause()
self.held=true
self.CD=cond.condition
elseif not(cond.condition()) then
self.held=false
self:Resume()
self.CD=nil
return false
end
self.Parent:Do_Order()
return true
end
function multi:isHeld()
return self.held
end
function multi.executeFunction(name,...)
if type(_G[name])=='function' then
_G[name](...)
else
print('Error: Not a function')
end
end
function multi:waitFor(obj)
self:hold(function() return obj:isActive() end)
end
function multi:reboot(r)
local before=collectgarbage('count')
self.Mainloop={}
self.Tasks={}
self.Tasks2={}
self.Garbage={}
self.Children={}
self.Paused={}
self.Active=true
self.Id=-1
if r then
for i,v in pairs(_G) do
if type(i)=='table' then
if i.Parent and i.Id and i.Act then
i={}
end
end
end
end
collectgarbage()
local after=collectgarbage('count')
print([[Before rebooting total Ram used was ]]..before..[[Kb
After rebooting total Ram used is ]]..after..[[ Kb
A total of ]]..(before-after)..[[Kb was cleaned up]])
end
function multi:getChildren()
return self.Mainloop
end
--Processor
function multi:getError()
if self.error then
return self.error
end
end
function multi:Do_Order()
local Loop=self.Mainloop
_G.ID=0
for _D=#Loop,1,-1 do
if Loop[_D] then
if Loop[_D].Active then
Loop[_D].Id=_D
self.CID=_D
Loop[_D]:Act()
end
end
end
end
function multi:enablePriority()
function self:Do_Order()
local Loop=self.Mainloop
_G.ID=0
local PS=self
for _D=#Loop,1,-1 do
if Loop[_D] then
if (PS.PList[PS.PStep])%Loop[_D].Priority==0 then
if Loop[_D].Active then
Loop[_D].Id=_D
self.CID=_D
Loop[_D]:Act()
end
end
end
end
PS.PStep=PS.PStep+1
if PS.PStep>7 then
PS.PStep=1
end
end
end
function multi:enablePriority2()
function self:Do_Order()
local Loop=self.Mainloop
_G.ID=0
local PS=self
for _D=#Loop,1,-1 do
if Loop[_D] then
if (PS.PStep)%Loop[_D].Priority==0 then
if Loop[_D].Active then
Loop[_D].Id=_D
self.CID=_D
Loop[_D]:Act()
end
end
end
end
PS.PStep=PS.PStep+1
if PS.PStep>self.Priority_Idle then
PS.PStep=1
end
end
end
multi.disablePriority=multi.unProtect
function multi:fromfile(path,int)
int=int or self
local test2={}
local test=bin.load(path)
local tp=test:getBlock('s')
if tp=='event' then
test2=int:newEvent(test:getBlock('f'))
local t=test:getBlock('t')
for i=1,#t do
test2:OnEvent(t[i])
end
elseif tp=='alarm' then
test2=int:newAlarm(test:getBlock('n'))
elseif tp=='loop' then
test2=int:newLoop(test:getBlock('t')[1])
elseif tp=='step' or tp=='tstep' then
local func=test:getBlock('t')
local funcE=test:getBlock('t')
local funcS=test:getBlock('t')
local tab=test:getBlock('t')
test2=int:newStep()
table.merge(test2,tab)
test2.funcE=funcE
test2.funcS=funcS
test2.func=func
elseif tp=='trigger' then
test2=int:newTrigger(test:getBlock('f'))
elseif tp=='connector' then
test2=int:newConnection()
test2.func=test:getBlock('t')
elseif tp=='timer' then
test2=int:newTimer()
test2.count=tonumber(test:getBlock('n'))
else
print('Error: The file you selected is not a valid multi file object!')
return false
end
return test2
end
function multi:benchMark(sec,p)
local temp=self:newLoop(function(t,self)
if self.clock()-self.init>self.sec then
print(self.c..' steps in '..self.sec..' second(s)')
self.tt(self.sec)
self:Destroy()
else
self.c=self.c+1
end
end)
temp.Priority=p or 1
function temp:OnBench(func)
self.tt=func
end
self.tt=function() end
temp.sec=sec
temp.init=self.clock()
temp.c=0
return temp
end
function multi:tofile(path)
local items=self:getChildren()
io.mkDir(io.getName(path))
for i=1,#items do
items[i]:tofile(io.getName(path)..'\\item'..item[i]..'.dat')
end
local int=bin.new()
int:addBlock('process')
int:addBlock(io.getName(path))
int:addBlock(#self.Mainloop)
int:addBlock(self.Active)
int:addBlock(self.Rest)
int:addBlock(self.Jobs)
int:tofile()
end
function multi.startFPSMonitior()
if not multi.runFPS then
multi.doFPS(s)
multi.runFPS=true
end
end
function multi.doFPS(s)
multi:benchMark(1):OnBench(doFPS)
if s then
multi.fps=s
end
end
--Helpers
function multi:OnMainConnect(func)
table.insert(self.func,func)
end
function multi:protect()
function self:Do_Order()
local Loop=self.Mainloop
for _D=#Loop,1,-1 do
if Loop[_D]~=nil then
Loop[_D].Id=_D
self.CID=_D
local status, err=pcall(Loop[_D].Act,Loop[_D])
if err and not(Loop[_D].error) then
Loop[_D].error=err
self.OnError:Fire(err,Loop[_D])
end
end
end
end
end
function multi:unProtect()
local Loop=self.Mainloop
_G.ID=0
for _D=#Loop,1,-1 do
if Loop[_D] then
if Loop[_D].Active then
Loop[_D].Id=_D
self.CID=_D
Loop[_D]:Act()
end
end
end
end
function multi:setJobSpeed(n)
self.jobUS=n
end
function multi:hasJobs()
return #self.Jobs>0,#self.Jobs
end
function multi:getJobs()
return #self.Jobs
end
function multi:removeJob(name)
for i=#self.Jobs,1,-1 do
if self.Jobs[i][2]==name then
table.remove(self.Jobs,i)
end
end
end
function multi:FreeMainEvent()
self.func={}
end
function multi:connectFinal(func)
if self.Type=='event' then
self:OnEvent(func)
elseif self.Type=='alarm' then
self:OnRing(func)
elseif self.Type=='step' or self.Type=='tstep' then
self:OnEnd(func)
else
print("Warning!!! "..self.Type.." doesn't contain a Final Connection State! Use "..self.Type..":Break(function) to trigger it's final event!")
self:OnBreak(func)
end
end
function multi:Break()
self:Pause()
self.Active=nil
for i=1,#self.ender do
if self.ender[i] then
self.ender[i](self)
end
end
end
function multi:OnBreak(func)
table.insert(self.ender,func)
end
function multi:isPaused()
return not(self.Active)
end
function multi:isActive()
return self.Active
end
function multi:getType()
return self.Type
end
function multi:Sleep(n)
self:hold(n)
end
function multi:Pause()
if self.Type=='mainprocess' then
print("You cannot pause the main process. Doing so will stop all methods and freeze your program! However if you still want to use multi:_Pause()")
else
self.Active=false
if self.Parent.Mainloop[self.Id]~=nil then
table.remove(self.Parent.Mainloop,self.Id)
table.insert(self.Parent.Paused,self)
self.PId=#self.Parent.Paused
end
end
end
function multi:Resume()
if self.Type=='process' or self.Type=='mainprocess' then
self.Active=true
local c=self:getChildren()
for i=1,#c do
c[i]:Resume()
end
else
if self:isPaused() then
table.remove(self.Parent.Paused,self.PId)
table.insert(self.Parent.Mainloop,self)
self.Id=#self.Parent.Mainloop
self.Active=true
end
end
end
function multi:resurrect()
table.insert(self.Parent.Mainloop,self)
self.Active=true
end
function multi:Destroy()
if self.Type=='process' or self.Type=='mainprocess' then
local c=self:getChildren()
for i=1,#c do
self.OnObjectDestroyed:Fire(c[i])
c[i]:Destroy()
end
else
for i=1,#self.Parent.Mainloop do
if self.Parent.Mainloop[i]==self then
self.Parent.OnObjectDestroyed:Fire(self)
table.remove(self.Parent.Mainloop,i)
break
end
end
self.Active=false
end
end
function multi:hold(task)
self:Pause()
self.held=true
if type(task)=='number' then
local alarm=self.Parent:newAlarm(task)
while alarm.Active==true do
if love then
self.Parent:lManager()
else
self.Parent:Do_Order()
end
end
alarm:Destroy()
self:Resume()
self.held=false
elseif type(task)=='function' then
local env=self.Parent:newEvent(task)
env:OnEvent(function(envt) envt:Pause() envt.Active=false end)
while env.Active do
if love then
self.Parent:lManager()
else
self.Parent:Do_Order()
end
end
env:Destroy()
self:Resume()
self.held=false
else
print('Error Data Type!!!')
end
end
function multi:oneTime(func,...)
if not(self.Type=='mainprocess' or self.Type=='process') then
for _k=1,#self.Parent.Tasks2 do
if self.Parent.Tasks2[_k]==func then
return false
end
end
table.insert(self.Parent.Tasks2,func)
func(...)
return true
else
for _k=1,#self.Tasks2 do
if self.Tasks2[_k]==func then
return false
end
end
table.insert(self.Tasks2,func)
func(...)
return true
end
end
function multi:Reset(n)
self:Resume()
end
function multi:isDone()
return self.Active~=true
end
function multi:create(ref)
multi.OnObjectCreated:Fire(ref)
end
--Constructors [CORE]
function multi:newBase(ins)
if not(self.Type=='mainprocess' or self.Type=='process' or self.Type=='queue') then error('Can only create an object on multi or an interface obj') return false end
local c = {}
if self.Type=='process' or self.Type=='queue' then
setmetatable(c, self.Parent)
else
setmetatable(c, self)
end
c.Active=true
c.func={}
c.ender={}
c.Id=0
c.PId=0
c.Act=function() end
c.Parent=self
c.held=false
if ins then
table.insert(self.Mainloop,ins,c)
else
table.insert(self.Mainloop,c)
end
return c
end
function multi:newProcess(file)
if not(self.Type=='mainprocess') then error('Can only create an interface on the multi obj') return false end
local c = {}
setmetatable(c, self)
c.Parent=self
c.Active=true
c.func={}
c.Id=0
c.Type='process'
c.Mainloop={}
c.Tasks={}
c.Tasks2={}
c.Garbage={}
c.Children={}
c.Paused={}
c.Active=true
c.Id=-1
c.Rest=0
c.Jobs={}
c.queue={}
c.jobUS=2
function c:Start()
if self.l then
self.l:Resume()
else
self.l=self.Parent:newLoop(function(dt) c:uManager(dt) end)
end
end
function c:Pause()
if self.l then
self.l:Pause()
end
end
function c:Remove()
self:Destroy()
self.l:Destroy()
end
if file then
self.Cself=c
loadstring('local interface=multi.Cself '..io.open(file,'rb'):read('*all'))()
end
self:create(c)
return c
end
function multi:newQueuer(file)
local c=self:newProcess()
c.Type='queue'
c.last={}
c.funcE={}
function c:OnQueueCompleted(func)
table.insert(self.funcE,func)
end
if file then
self.Cself=c
loadstring('local queue=multi.Cself '..io.open(file,'rb'):read('*all'))()
end
self:create(c)
return c
end
--Constructors [ACTORS]
function multi:newCustomObject(objRef,t)
local c={}
if t=='process' then
if self.Type=='queue' then
c=self:newBase(1)
self.last=c
print("This Custom Object was created on a queue! Ensure that it has a way to end! All objects have a obj:Break() method!")
else
c=self:newBase()
end
if type(objRef)=='table' then
table.merge(c,objRef)
end
if not c.Act then
function c:Act()
-- Empty function
end
end
else
c=objRef or {}
end
if not c.Type then
c.Type='coustomObject'
end
if self.Type=='queue' then
if #self.Mainloop>1 then
c:Pause()
end
c:connectFinal(multi.queuefinal)
end
self:create(c)
return c
end
function multi:newEvent(task)
local c={}
if self.Type=='queue' then
c=self:newBase(1)
self.last=c
else
c=self:newBase()
end
c.Type='event'
c.Task=task or function() end
function c:Act()
if self.Task(self) then
self:Pause()
for _E=1,#self.func do
self.func[_E](self)
end
end
end
function c:OnEvent(func)
table.insert(self.func,func)
end
function c:tofile(path)
local m=bin.new()
m:addBlock(self.Type)
m:addBlock(self.Task)
m:addBlock(self.func)
m:addBlock(self.Active)
m:tofile(path)
end
if self.Type=='queue' then
if #self.Mainloop>1 then
c:Pause()
end
c:connectFinal(multi.queuefinal)
end
self:create(c)
return c
end
function multi:newAlarm(set)
local c={}
if self.Type=='queue' then
c=self:newBase(1)
self.last=c
else
c=self:newBase()
end
c.Type='alarm'
c.Priority=self.Priority_Low
c.timer=self:newTimer()
c.set=set or 0
function c:tofile(path)
local m=bin.new()
m:addBlock(self.Type)
m:addBlock(self.set)
m:addBlock(self.Active)
m:tofile(path)
end
function c:Act()
if self.timer:Get()>=self.set then
self:Pause()
self.Active=false
for i=1,#self.func do
self.func[i](self)
end
end
end
function c:Resume()
self.Parent.Resume(self)
self.timer:Resume()
end
function c:Reset(n)
if n then self.set=n end
self:Resume()
self.timer:Reset()
end
function c:OnRing(func)
table.insert(self.func,func)
end
function c:Pause()
self.timer:Pause()
self.Parent.Pause(self)
end
if self.Type=='queue' then
c:Pause()
c:connectFinal(multi.queuefinal)
else
c.timer:Start()
end
self:create(c)
return c
end
function multi:newLoop(func)
local c={}
if self.Type=='queue' then
c=self:newBase(1)
self.last=c
else
c=self:newBase()
end
c.Type='loop'
c.Start=self.clock()
if func then
c.func={func}
end
function c:tofile(path)
local m=bin.new()
m:addBlock(self.Type)
m:addBlock(self.func)
m:addBlock(self.Active)
m:tofile(path)
end
function c:Act()
for i=1,#self.func do
self.func[i](self.Parent.clock()-self.Start,self)
end
end
function c:OnLoop(func)
table.insert(self.func,func)
end
if self.Type=='queue' then
if #self.Mainloop>1 then
c:Pause()
end
c:connectFinal(multi.queuefinal)
end
self:create(c)
return c
end
function multi:newUpdater(skip)
local c={}
if self.Type=='queue' then
c=self:newBase(1)
self.last=c
else
c=self:newBase()
end
c.Type='updater'
c.pos=1
c.skip=skip or 1
function c:Act()
if self.pos>=self.skip then
self.pos=0
for i=1,#self.func do
self.func[i](self)
end
end
self.pos=self.pos+1
end
function c:setSkip(n)
self.skip=n
end
c.OnUpdate=self.OnMainConnect
if self.Type=='queue' then
if #self.Mainloop>1 then
c:Pause()
end
c:connectFinal(multi.queuefinal)
end
self:create(c)
return c
end
function multi:newStep(start,reset,count,skip)
local c={}
if self.Type=='queue' then
c=self:newBase(1)
self.last=c
else
c=self:newBase()
end
think=1
c.Type='step'
c.pos=start or 1
c.endAt=reset or math.huge
c.skip=skip or 0
c.spos=0
c.count=count or 1*think
c.funcE={}
c.funcS={}
c.start=start or 1
if start~=nil and reset~=nil then
if start>reset then
think=-1
end
end
function c:tofile(path)
local m=bin.new()
m:addBlock(self.Type)
m:addBlock(self.func)
m:addBlock(self.funcE)
m:addBlock(self.funcS)
m:addBlock({pos=self.pos,endAt=self.endAt,skip=self.skip,spos=self.spos,count=self.count,start=self.start})
m:addBlock(self.Active)
m:tofile(path)
end
function c:Act()
if self~=nil then
if self.spos==0 then
if self.pos==self.start then
for fe=1,#self.funcS do
self.funcS[fe](self)
end
end
for i=1,#self.func do
self.func[i](self.pos,self)
end
self.pos=self.pos+self.count
if self.pos-self.count==self.endAt then
self:Pause()
for fe=1,#self.funcE do
self.funcE[fe](self)
end
self.pos=self.start
end
end
end
self.spos=self.spos+1
if self.spos>=self.skip then
self.spos=0
end
end
c.Reset=c.Resume
function c:OnStart(func)
table.insert(self.funcS,func)
end
function c:OnStep(func)
table.insert(self.func,1,func)
end
function c:OnEnd(func)
table.insert(self.funcE,func)
end
function c:Break()
self.Active=nil
end
function c:Update(start,reset,count,skip)
self.start=start or self.start
self.endAt=reset or self.endAt
self.skip=skip or self.skip
self.count=count or self.count
self:Resume()
end
if self.Type=='queue' then
if #self.Mainloop>1 then
c:Pause()
end
c:connectFinal(multi.queuefinal)
end
self:create(c)
return c
end
function multi:newTStep(start,reset,count,set)
local c={}
if self.Type=='queue' then
c=self:newBase(1)
self.last=c
else
c=self:newBase()
end
think=1
c.Type='tstep'
c.Priority=self.Priority_Low
c.start=start or 1
local reset = reset or math.huge
c.endAt=reset
c.pos=start or 1
c.skip=skip or 0
c.count=count or 1*think
c.funcE={}
c.timer=self.clock()
c.set=set or 1
c.funcS={}
function c:Update(start,reset,count,set)
self.start=start or self.start
self.pos=self.start
self.endAt=reset or self.endAt
self.set=set or self.set
self.count=count or self.count or 1
self.timer=self.clock()
self:Resume()
end
function c:tofile(path)
local m=bin.new()
m:addBlock(self.Type)
m:addBlock(self.func)
m:addBlock(self.funcE)
m:addBlock(self.funcS)
m:addBlock({pos=self.pos,endAt=self.endAt,skip=self.skip,timer=self.timer,count=self.count,start=self.start,set=self.set})
m:addBlock(self.Active)
m:tofile(path)
end
function c:Act()
if self.clock()-self.timer>=self.set then
self:Reset()
if self.pos==self.start then
for fe=1,#self.funcS do
self.funcS[fe](self)
end
end
for i=1,#self.func do
self.func[i](self.pos,self)
end
self.pos=self.pos+self.count
if self.pos-self.count==self.endAt then
self:Pause()
for fe=1,#self.funcE do
self.funcE[fe](self)
end
self.pos=self.start
end
end
end
function c:OnStart(func)
table.insert(self.funcS,func)
end
function c:OnStep(func)
table.insert(self.func,func)
end
function c:OnEnd(func)
table.insert(self.funcE,func)
end
function c:Break()
self.Active=nil
end
function c:Reset(n)
if n then self.set=n end
self.timer=self.clock()
self:Resume()
end
if self.Type=='queue' then
if #self.Mainloop>1 then
c:Pause()
end
c:connectFinal(multi.queuefinal)
end
self:create(c)
return c
end
function multi:newWatcher(namespace,name)
local function WatcherObj(ns,n)
if self.Type=='queue' then
print("Cannot create a watcher on a queue! Creating on 'multi' instead!")
self=multi
end
local c=self:newBase()
c.Type='watcher'
c.ns=ns
c.n=n
c.cv=ns[n]
function c:OnValueChanged(func)
table.insert(self.func,func)
end
function c:Act()
if self.cv~=self.ns[self.n] then
for i=1,#self.func do
self.func[i](self,self.cv,self.ns[self.n])
end
self.cv=self.ns[self.n]
end
end
self:create(c)
return c
end
if type(namespace)~='table' and type(namespace)=='string' then
return WatcherObj(_G,namespace)
elseif type(namespace)=='table' and (type(name)=='string' or 'number') then
return WatcherObj(namespace,name)
else
print('Warning, invalid arguments! Nothing returned!')
end
end
function multi:newThread(name,func)
local c={}
c.ref={}
c.Name=name
c.thread=coroutine.create(func)
c.sleep=1
c.firstRunDone=false
c.timer=multi.scheduler:newTimer()
c.ref.Globals=self:linkDomain("Globals")
function c.ref:send(name,val)
ret=coroutine.yield({Name=name,Value=val})
self:syncGlobals(ret)
end
function c.ref:get(name)
return self.Globals[name]
end
function c.ref:kill()
err=coroutine.yield({"_kill_"})
if err then
error("Failed to kill a thread! Exiting...")
end
end
function c.ref:sleep(n)
n = tonumber(n) or 0
ret=coroutine.yield({"_sleep_",n})
self:syncGlobals(ret)
end
function c.ref:syncGlobals(v)
self.Globals=v
end
table.insert(self:linkDomain("Threads"),c)
if not multi.scheduler:isActive() then
multi.scheduler:Resume()
end
end
-- Constructors [SEMI-ACTORS]
function multi:newJob(func,name)
if not(self.Type=='mainprocess' or self.Type=='process') then error('Can only create an object on multi or an interface obj') return false end
local c = {}
if self.Type=='process' then
setmetatable(c, self.Parent)
else
setmetatable(c, self)
end
c.Active=true
c.func={}
c.Id=0
c.PId=0
c.Parent=self
c.Type='job'
c.trigfunc=func or function() end
function c:Act()
self:trigfunc(self)
end
table.insert(self.Jobs,{c,name})
if self.JobRunner==nil then
self.JobRunner=self:newAlarm(self.jobUS)
self.JobRunner:OnRing(function(self)
if #self.Parent.Jobs>0 then
if self.Parent.Jobs[1] then
self.Parent.Jobs[1][1]:Act()
table.remove(self.Parent.Jobs,1)
end
end
self:Reset(self.Parent.jobUS)
end)
end
end
function multi:newRange()
local selflink=self
local temp={
getN = function(self) selflink:Do_Order() self.n=self.n+self.c if self.n>self.b then self.Link.held=false self.Link:Resume() return nil end return self.n end,
}
setmetatable(temp,{
__call=function(self,a,b,c)
self.c=c or 1
self.n=a-self.c
self.a=a
self.b=b
self.Link=selflink--.Parent.Mainloop[selflink.CID] or
self.Link:Pause()
self.Link.held=true
return function() return self:getN() end
end
})
self:create(temp)
return temp
end
function multi:newCondition(func)
local c={['condition']=func}
self:create(c)
return c
end
-- Constructors [NON-ACTORS]
function multi:newFunction(func)
local c={}
c.func=func
mt={
__index=multi,
__call=function(self,...) if self.Active then return self:func(...) end local t={...} return "PAUSED" end
}
c.Parent=self
function c:Pause()
self.Active=false
end
function c:Resume()
self.Active=true
end
setmetatable(c,mt)
self:create(c)
return c
end
function multi:newTimer()
local c={}
c.Type='timer'
c.time=0
c.count=0
function c:Start()
self.time=os.clock()
end
function c:Get()
return (os.clock()-self.time)+self.count
end
c.Reset=c.Start
function c:Pause()
self.time=self:Get()
end
function c:Resume()
self.time=os.clock()-self.time
end
function c:tofile(path)
local m=bin.new()
self.count=self.count+self:Get()
m:addBlock(self.Type)
m:addBlock(self.count)
m:tofile(path)
end
self:create(c)
return c
end
function multi:newTask(func)
table.insert(self.Tasks,func)
end
function multi:newTrigger(func)
local c={}
c.Type='trigger'
c.trigfunc=func or function() end
function c:Fire(...)
self:trigfunc(self,...)
end
function c:tofile(path)
local m=bin.new()
m:addBlock(self.Type)
m:addBlock(self.trigfunc)
m:tofile(path)
end
self:create(c)
return c
end
function multi:newConnection(protect)
local c={}
setmetatable(c,{__call=function(self,...) self:connect(...) end})
c.Type='connector'
c.func={}
c.ID=0
c.protect=protect or true
c.connections={}
c.fconnections={}
c.FC=0
function c:fConnect(func)
local temp=self:connect(func)
table.insert(self.fconnections,temp)
self.FC=self.FC+1
end
function c:getConnection(name,ingore)
if ingore then
return self.connections[name] or {
Fire=function() end -- if the connection doesn't exist lets call all of them or silently ingore
}
else
return self.connections[name] or self
end
end
function c:Fire(...)
local ret={}
for i=#self.func,1,-1 do
if self.protect then
local temp={pcall(self.func[i][1],...)}
if temp[1] then
table.remove(temp,1)
table.insert(ret,temp)
else
print(temp[2])
end
else
table.insert(ret,{self.func[i][1](...)})
end
end
return ret
end
function c:bind(t)
self.func=t
end
function c:remove()
self.func={}
end
function c:connect(func,name)
self.ID=self.ID+1
table.insert(self.func,1,{func,self.ID})
local temp = {
Link=self.func,
func=func,
ID=self.ID,
Parent=self,
Fire=function(self,...)
if self.Parent.FC>0 then
for i=1,#self.Parent.FC do
self.Parent.FC[i]:Fire(...)
end
end
if self.Parent.protect then
local t=pcall(self.func,...)
if t then
return t
end
else
return self.func(...)
end
end,
remove=function(self)
for i=1,#self.Link do
if self.Link[i][2]~=nil then
if self.Link[i][2]==self.ID then
table.remove(self.Link,i)
self.remove=function() end
self.Link=nil
self.ID=nil
return true
end
end
end
end
}
if name then
self.connections[name]=temp
end
return temp
end
function c:tofile(path)
local m=bin.new()
m:addBlock(self.Type)
m:addBlock(self.func)
m:tofile(path)
end
return c
end
multi.OnObjectCreated=multi:newConnection()
multi.OnObjectDestroyed=multi:newConnection()
--Managers
function multi:mainloop()
for i=1,#self.Tasks do
self.Tasks[i](self)
end
rawset(self,'Start',self.clock())
while self.Active do
self:Do_Order()
end
print("Did you call multi:Stop()? This method should not be used when using multi:mainloop()! You now need to restart the multiManager, by using multi:reboot() and calling multi:mainloop() again or by using multi:uManager()")
end
function multi._tFunc(self,dt)
for i=1,#self.Tasks do
self.Tasks[i](self)
end
if dt then
self.pump=true
end
self.pumpvar=dt
rawset(self,'Start',self.clock())
end
function multi:uManager(dt)
if self.Active then
self:oneTime(self._tFunc,self,dt)
function self:uManager(dt)
self:Do_Order()
end
self:Do_Order()
end
end
--Thread Setup Stuff
multi:setDomainName("Threads")
multi:setDomainName("Globals")
-- Scheduler
multi.scheduler=multi:newUpdater()
multi.scheduler.Type="scheduler"
function multi.scheduler:setStep(n)
self.skip=tonumber(n) or 24
end
multi.scheduler.Threads=multi:linkDomain("Threads")
multi.scheduler.Globals=multi:linkDomain("Globals")
multi.scheduler:OnUpdate(function(self)
for i=#self.Threads,1,-1 do
ret={}
if coroutine.status(self.Threads[i].thread)=="dead" then
table.remove(self.Threads,i)
else
if self.Threads[i].timer:Get()>=self.Threads[i].sleep then
if self.Threads[i].firstRunDone==false then
self.Threads[i].firstRunDone=true
self.Threads[i].timer:Start()
_,ret=coroutine.resume(self.Threads[i].thread,self.Threads[i].ref)
else
_,ret=coroutine.resume(self.Threads[i].thread,self.Globals)
end
if ret==true or ret==false then
print("Thread Ended!!!")
ret={}
end
end
if ret then
if ret[1]=="_kill_" then
table.remove(self.Threads,i)
elseif ret[1]=="_sleep_" then
self.Threads[i].timer:Reset()
self.Threads[i].sleep=ret[2]
elseif ret.Name then
self.Globals[ret.Name]=ret.Value
end
end
end
end
end)
multi.scheduler:setStep()
multi.scheduler:Pause()
multi.OnError=multi:newConnection()
| mit |
RavenX8/osIROSE-new | scripts/npcs/ai/[referee]_pirre.lua | 2 | 1069 | registerNpc(1114, {
walk_speed = 0,
run_speed = 0,
scale = 120,
r_weapon = 0,
l_weapon = 161,
level = 10,
hp = 100,
attack = 100,
hit = 100,
def = 100,
res = 100,
avoid = 100,
attack_spd = 100,
is_magic_damage = 0,
ai_type = 232,
give_exp = 0,
drop_type = 70,
drop_money = 0,
drop_item = 0,
union_number = 0,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 200,
npc_type = 999,
hit_material_type = 0,
face_icon = 25,
summon_mob_type = 25,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end | apache-2.0 |
everslick/awesome | lib/menubar/utils.lua | 11 | 7630 | ---------------------------------------------------------------------------
--- Utility module for menubar
--
-- @author Antonio Terceiro
-- @copyright 2009, 2011-2012 Antonio Terceiro, Alexander Yakushev
-- @release @AWESOME_VERSION@
-- @module menubar.utils
---------------------------------------------------------------------------
-- Grab environment
local io = io
local table = table
local ipairs = ipairs
local string = string
local awful_util = require("awful.util")
local theme = require("beautiful")
local glib = require("lgi").GLib
local wibox = require("wibox")
local utils = {}
-- NOTE: This icons/desktop files module was written according to the
-- following freedesktop.org specifications:
-- Icons: http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-0.11.html
-- Desktop files: http://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-1.0.html
-- Options section
--- Terminal which applications that need terminal would open in.
utils.terminal = 'xterm'
--- The default icon for applications that don't provide any icon in
-- their .desktop files.
local default_icon = nil
--- Name of the WM for the OnlyShownIn entry in the .desktop file.
utils.wm_name = "awesome"
-- Private section
local all_icon_sizes = {
'128x128' ,
'96x96',
'72x72',
'64x64',
'48x48',
'36x36',
'32x32',
'24x24',
'22x22',
'16x16'
}
--- List of supported icon formats.
local icon_formats = { "png", "xpm", "svg" }
--- Check whether the icon format is supported.
-- @param icon_file Filename of the icon.
-- @return true if format is supported, false otherwise.
local function is_format_supported(icon_file)
for _, f in ipairs(icon_formats) do
if icon_file:match('%.' .. f) then
return true
end
end
return false
end
local icon_lookup_path = nil
local function get_icon_lookup_path()
if not icon_lookup_path then
icon_lookup_path = {}
local icon_theme_paths = {}
local icon_theme = theme.icon_theme
local paths = glib.get_system_data_dirs()
table.insert(paths, 1, glib.get_user_data_dir())
table.insert(paths, 1, glib.get_home_dir() .. '/.icons')
for k,dir in ipairs(paths)do
if icon_theme then
table.insert(icon_theme_paths, dir..'/icons/' .. icon_theme .. '/')
end
table.insert(icon_theme_paths, dir..'/icons/hicolor/') -- fallback theme
end
for i, icon_theme_directory in ipairs(icon_theme_paths) do
for j, size in ipairs(all_icon_sizes) do
table.insert(icon_lookup_path, icon_theme_directory .. size .. '/apps/')
end
end
for k,dir in ipairs(paths)do
-- lowest priority fallbacks
table.insert(icon_lookup_path, dir..'/pixmaps/')
table.insert(icon_lookup_path, dir..'/icons/')
end
end
return icon_lookup_path
end
--- Lookup an icon in different folders of the filesystem.
-- @param icon_file Short or full name of the icon.
-- @return full name of the icon.
function utils.lookup_icon(icon_file)
if not icon_file or icon_file == "" then
return default_icon
end
if icon_file:sub(1, 1) == '/' and is_format_supported(icon_file) then
-- If the path to the icon is absolute and its format is
-- supported, do not perform a lookup.
return awful_util.file_readable(icon_file) and icon_file or nil
else
for i, directory in ipairs(get_icon_lookup_path()) do
if is_format_supported(icon_file) and awful_util.file_readable(directory .. icon_file) then
return directory .. icon_file
else
-- Icon is probably specified without path and format,
-- like 'firefox'. Try to add supported extensions to
-- it and see if such file exists.
for _, format in ipairs(icon_formats) do
local possible_file = directory .. icon_file .. "." .. format
if awful_util.file_readable(possible_file) then
return possible_file
end
end
end
end
return default_icon
end
end
--- Parse a .desktop file.
-- @param file The .desktop file.
-- @return A table with file entries.
function utils.parse(file)
local program = { show = true, file = file }
local desktop_entry = false
-- Parse the .desktop file.
-- We are interested in [Desktop Entry] group only.
for line in io.lines(file) do
if line:find("^%s*#") then
-- Skip comments.
elseif not desktop_entry and line == "[Desktop Entry]" then
desktop_entry = true
else
if line:sub(1, 1) == "[" and line:sub(-1) == "]" then
-- A declaration of new group - stop parsing
break
end
-- Grab the values
for key, value in line:gmatch("(%w+)%s*=%s*(.+)") do
program[key] = value
end
end
end
-- In case [Desktop Entry] was not found
if not desktop_entry then return nil end
-- Don't show program if NoDisplay attribute is false
if program.NoDisplay and string.lower(program.NoDisplay) == "true" then
program.show = false
end
-- Only show the program if there is no OnlyShowIn attribute
-- or if it's equal to utils.wm_name
if program.OnlyShowIn ~= nil and not program.OnlyShowIn:match(utils.wm_name) then
program.show = false
end
-- Look up for a icon.
if program.Icon then
program.icon_path = utils.lookup_icon(program.Icon)
end
-- Split categories into a table. Categories are written in one
-- line separated by semicolon.
if program.Categories then
program.categories = {}
for category in program.Categories:gmatch('[^;]+') do
table.insert(program.categories, category)
end
end
if program.Exec then
-- Substitute Exec special codes as specified in
-- http://standards.freedesktop.org/desktop-entry-spec/1.1/ar01s06.html
if program.Name == nil then
program.Name = '['.. file:match("([^/]+)%.desktop$") ..']'
end
local cmdline = program.Exec:gsub('%%c', program.Name)
cmdline = cmdline:gsub('%%[fuFU]', '')
cmdline = cmdline:gsub('%%k', program.file)
if program.icon_path then
cmdline = cmdline:gsub('%%i', '--icon ' .. program.icon_path)
else
cmdline = cmdline:gsub('%%i', '')
end
if program.Terminal == "true" then
cmdline = utils.terminal .. ' -e ' .. cmdline
end
program.cmdline = cmdline
end
return program
end
--- Parse a directory with .desktop files
-- @param dir The directory.
-- @return A table with all .desktop entries.
function utils.parse_dir(dir)
local programs = {}
local files = io.popen('find '.. dir ..' -maxdepth 1 -name "*.desktop" 2>/dev/null')
for file in files:lines() do
local program = utils.parse(file)
if program then
table.insert(programs, program)
end
end
return programs
end
--- Compute text width.
-- @tparam str text Text.
-- @treturn int Text width.
function utils.compute_text_width(text)
local _, logical = wibox.widget.textbox(awful_util.escape(text))._layout:get_pixel_extents()
return logical.width
end
return utils
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
0xbs/premade-groups-filter | Dialog/Help.lua | 1 | 3960 | -------------------------------------------------------------------------------
-- Premade Groups Filter
-------------------------------------------------------------------------------
-- Copyright (C) 2022 Elotheon-Arthas-EU
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along
-- with this program; if not, write to the Free Software Foundation, Inc.,
-- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-------------------------------------------------------------------------------
local PGF = select(2, ...)
local L = PGF.L
local C = PGF.C
function PGF.GameTooltip_AddWhite(left)
GameTooltip:AddLine(left, 255, 255, 255)
end
function PGF.GameTooltip_AddDoubleWhite(left, right)
GameTooltip:AddDoubleLine(left, right, 255, 255, 255, 255, 255, 255)
end
function PGF.Dialog_InfoButton_OnEnter(self, motion)
local AddDoubleWhiteUsingKey = function (key)
PGF.GameTooltip_AddDoubleWhite(key, L["dialog.tooltip." .. key]) end
GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
GameTooltip:SetText(L["dialog.tooltip.title"])
GameTooltip:AddLine(" ")
GameTooltip:AddDoubleLine(L["dialog.tooltip.variable"], L["dialog.tooltip.description"])
AddDoubleWhiteUsingKey("ilvl")
AddDoubleWhiteUsingKey("myilvl")
AddDoubleWhiteUsingKey("hlvl")
AddDoubleWhiteUsingKey("pvprating")
AddDoubleWhiteUsingKey("mprating")
AddDoubleWhiteUsingKey("defeated")
AddDoubleWhiteUsingKey("members")
AddDoubleWhiteUsingKey("tanks")
AddDoubleWhiteUsingKey("heals")
AddDoubleWhiteUsingKey("dps")
AddDoubleWhiteUsingKey("partyfit")
AddDoubleWhiteUsingKey("age")
AddDoubleWhiteUsingKey("voice")
PGF.GameTooltip_AddDoubleWhite("autoinv", LFG_LIST_TOOLTIP_AUTO_ACCEPT)
AddDoubleWhiteUsingKey("myrealm")
AddDoubleWhiteUsingKey("noid")
AddDoubleWhiteUsingKey("matchingid")
AddDoubleWhiteUsingKey("warmode")
PGF.GameTooltip_AddWhite("boss/bossesmatching/... — " .. L["dialog.tooltip.seewebsite"])
PGF.GameTooltip_AddDoubleWhite("priests/warriors/...", L["dialog.tooltip.classes"])
PGF.GameTooltip_AddDoubleWhite("voti/sfo/sod/cn/...", L["dialog.tooltip.raids"])
PGF.GameTooltip_AddDoubleWhite("aa/av/bh/hoi/lot", L["dialog.tooltip.dungeons"])
PGF.GameTooltip_AddWhite("no/nt/rlp/hov/cos/sbg/tjs")
PGF.GameTooltip_AddDoubleWhite("cos/votw/nl/dht/eoa/brh", L["dialog.tooltip.timewalking"])
PGF.GameTooltip_AddDoubleWhite("arena2v2/arena3v3", L["dialog.tooltip.arena"])
GameTooltip:AddLine(" ")
GameTooltip:AddDoubleLine(L["dialog.tooltip.op.logic"], L["dialog.tooltip.example"])
PGF.GameTooltip_AddDoubleWhite("()", L["dialog.tooltip.ex.parentheses"])
PGF.GameTooltip_AddDoubleWhite("not", L["dialog.tooltip.ex.not"])
PGF.GameTooltip_AddDoubleWhite("and", L["dialog.tooltip.ex.and"])
PGF.GameTooltip_AddDoubleWhite("or", L["dialog.tooltip.ex.or"])
GameTooltip:AddLine(" ")
GameTooltip:AddDoubleLine(L["dialog.tooltip.op.number"], L["dialog.tooltip.example"])
PGF.GameTooltip_AddDoubleWhite("==", L["dialog.tooltip.ex.eq"])
PGF.GameTooltip_AddDoubleWhite("~=", L["dialog.tooltip.ex.neq"])
PGF.GameTooltip_AddDoubleWhite("<,>,<=,>=", L["dialog.tooltip.ex.lt"])
GameTooltip:Show()
end
function PGF.Dialog_InfoButton_OnLeave(self, motion)
GameTooltip:Hide()
end
function PGF.Dialog_InfoButton_OnClick(self, button, down)
PGF.StaticPopup_Show("PGF_COPY_URL_KEYWORDS")
end
| gpl-2.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Phomiuna_Aqueducts/npcs/_0rv.lua | 2 | 1026 | -----------------------------------
-- Area: Phomiuna_Aqueducts
-- NPC: Oil lamp
-- @pos -60 -23 60 27
-----------------------------------
package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Phomiuna_Aqueducts/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
GetNPCByID(16888051):openDoor(7);
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 |
shayanchabok555/teleparsyantispam | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
ahmedbrake/telegram-bot | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
DrMelon/OpenRA | mods/d2k/maps/atreides-01b/atreides01b.lua | 18 | 4800 |
HarkonnenReinforcements = { }
HarkonnenReinforcements["Easy"] =
{
{ "rifle", "rifle" }
}
HarkonnenReinforcements["Normal"] =
{
{ "rifle", "rifle" },
{ "rifle", "rifle", "rifle" },
{ "rifle", "trike" },
}
HarkonnenReinforcements["Hard"] =
{
{ "rifle", "rifle" },
{ "trike", "trike" },
{ "rifle", "rifle", "rifle" },
{ "rifle", "trike" },
{ "trike", "trike" }
}
HarkonnenEntryWaypoints = { HarkonnenWaypoint1.Location, HarkonnenWaypoint2.Location, HarkonnenWaypoint3.Location, HarkonnenWaypoint4.Location }
HarkonnenAttackDelay = DateTime.Seconds(30)
HarkonnenAttackWaves = { }
HarkonnenAttackWaves["Easy"] = 1
HarkonnenAttackWaves["Normal"] = 5
HarkonnenAttackWaves["Hard"] = 12
ToHarvest = { }
ToHarvest["Easy"] = 2500
ToHarvest["Normal"] = 3000
ToHarvest["Hard"] = 3500
AtreidesReinforcements = { "rifle", "rifle", "rifle", "rifle" }
AtreidesEntryPath = { AtreidesWaypoint.Location, AtreidesRally.Location }
Messages =
{
"Build a concrete foundation before placing your buildings.",
"Build a Wind Trap for power.",
"Build a Refinery to collect Spice.",
"Build a Silo to store additional Spice."
}
IdleHunt = function(actor)
if not actor.IsDead then
Trigger.OnIdle(actor, actor.Hunt)
end
end
Tick = function()
if HarkonnenArrived and harkonnen.HasNoRequiredUnits() then
player.MarkCompletedObjective(KillHarkonnen)
end
if player.Resources > ToHarvest[Map.Difficulty] - 1 then
player.MarkCompletedObjective(GatherSpice)
end
-- player has no Wind Trap
if (player.PowerProvided <= 20 or player.PowerState ~= "Normal") and DateTime.GameTime % DateTime.Seconds(32) == 0 then
HasPower = false
Media.DisplayMessage(Messages[2], "Mentat")
else
HasPower = true
end
-- player has no Refinery and no Silos
if HasPower and player.ResourceCapacity == 0 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[3], "Mentat")
end
if HasPower and player.Resources > player.ResourceCapacity * 0.8 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[4], "Mentat")
end
UserInterface.SetMissionText("Harvested resources: " .. player.Resources .. "/" .. ToHarvest[Map.Difficulty], player.Color)
end
WorldLoaded = function()
player = Player.GetPlayer("Atreides")
harkonnen = Player.GetPlayer("Harkonnen")
InitObjectives()
Trigger.OnRemovedFromWorld(AtreidesConyard, function()
local refs = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(actor)
return actor.Type == "refinery"
end)
if #refs == 0 then
harkonnen.MarkCompletedObjective(KillAtreides)
else
Trigger.OnAllRemovedFromWorld(refs, function()
harkonnen.MarkCompletedObjective(KillAtreides)
end)
end
end)
Media.DisplayMessage(Messages[1], "Mentat")
Trigger.AfterDelay(DateTime.Seconds(25), function()
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.Reinforce(player, AtreidesReinforcements, AtreidesEntryPath)
end)
WavesLeft = HarkonnenAttackWaves[Map.Difficulty]
SendReinforcements()
end
SendReinforcements = function()
local units = HarkonnenReinforcements[Map.Difficulty]
local delay = Utils.RandomInteger(HarkonnenAttackDelay - DateTime.Seconds(2), HarkonnenAttackDelay)
HarkonnenAttackDelay = HarkonnenAttackDelay - (#units * 3 - 3 - WavesLeft) * DateTime.Seconds(1)
if HarkonnenAttackDelay < 0 then HarkonnenAttackDelay = 0 end
Trigger.AfterDelay(delay, function()
Reinforcements.Reinforce(harkonnen, Utils.Random(units), { Utils.Random(HarkonnenEntryWaypoints) }, 10, IdleHunt)
WavesLeft = WavesLeft - 1
if WavesLeft == 0 then
Trigger.AfterDelay(DateTime.Seconds(1), function() HarkonnenArrived = true end)
else
SendReinforcements()
end
end)
end
InitObjectives = function()
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
KillAtreides = harkonnen.AddPrimaryObjective("Kill all Atreides units.")
GatherSpice = player.AddPrimaryObjective("Harvest " .. tostring(ToHarvest[Map.Difficulty]) .. " Solaris worth of Spice.")
KillHarkonnen = player.AddSecondaryObjective("Eliminate all Harkonnen units and reinforcements\nin the area.")
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerLost(player, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(player, "Lose")
end)
end)
Trigger.OnPlayerWon(player, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(player, "Win")
end)
end)
end
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/Lufaise_Meadows/mobs/Splinterspine_Grukjuk.lua | 37 | 1181 | -----------------------------------
-- Area: Lufaise Meadows (24)
-- Mob: Splinterspine_Grukjuk
-----------------------------------
package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Lufaise_Meadows/TextIDs");
-- require("scripts/zones/Lufaise_Meadows/MobIDs");
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
if (killer:getQuestStatus(OTHER_AREAS,A_HARD_DAY_S_KNIGHT) == QUEST_ACCEPTED) then
killer:setVar("SPLINTERSPINE_GRUKJUK",2);
end
end;
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/globals/items/divine_sword_+1.lua | 16 | 1039 | -----------------------------------------
-- ID: 16826
-- Item: Divine Sword +1
-- 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(7,21);
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 = 163;
if (dmg < 0) then
message = 167;
end
return SUBEFFECT_LIGHT_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/Behemoths_Dominion/npcs/Cermet_Headstone.lua | 17 | 2940 | -----------------------------------
-- Area: Behemoth's Dominion
-- NPC: Cermet Headstone
-- Involved in Mission: ZM5 Headstone Pilgrimage (Lightning Headstone)
-- @pos -74 -4 -87 127
-----------------------------------
package.loaded["scripts/zones/Behemoths_Dominion/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/missions");
require("scripts/zones/Behemoths_Dominion/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE) then
-- if requirements are met and 15 mins have passed since mobs were last defeated, spawn them
if (player:hasKeyItem(LIGHTNING_FRAGMENT) == false and GetServerVariable("[ZM4]Lightning_Headstone_Active") < os.time()) then
player:startEvent(0x00C8,LIGHTNING_FRAGMENT);
-- if 15 min window is open and requirements are met, recieve key item
elseif (player:hasKeyItem(LIGHTNING_FRAGMENT) == false and GetServerVariable("[ZM4]Lightning_Headstone_Active") > os.time()) then
player:addKeyItem(LIGHTNING_FRAGMENT);
-- Check and see if all fragments have been found (no need to check wind and dark frag)
if (player:hasKeyItem(ICE_FRAGMENT) and player:hasKeyItem(EARTH_FRAGMENT) and player:hasKeyItem(WATER_FRAGMENT) and
player:hasKeyItem(FIRE_FRAGMENT) and player:hasKeyItem(WIND_FRAGMENT) and player:hasKeyItem(LIGHT_FRAGMENT)) then
player:messageSpecial(FOUND_ALL_FRAGS,LIGHTNING_FRAGMENT);
player:addTitle(BEARER_OF_THE_EIGHT_PRAYERS);
player:completeMission(ZILART,HEADSTONE_PILGRIMAGE);
player:addMission(ZILART,THROUGH_THE_QUICKSAND_CAVES);
else
player:messageSpecial(KEYITEM_OBTAINED,LIGHTNING_FRAGMENT);
end
else
player:messageSpecial(ALREADY_OBTAINED_FRAG,LIGHTNING_FRAGMENT);
end
elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE)) then
player:messageSpecial(ZILART_MONUMENT);
else
player:messageSpecial(CANNOT_REMOVE_FRAG);
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 == 0x00C8 and option == 1) then
SpawnMob(17297450,300):updateClaim(player); -- Legendary Weapon
SpawnMob(17297449,300):updateClaim(player); -- Ancient Weapon
SetServerVariable("[ZM4]Lightning_Headstone_Active",0);
end
end; | gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/The_Shrine_of_RuAvitau/mobs/Kirin.lua | 23 | 3674 | -----------------------------------
-- Area: The Shrine of Ru'Avitau
-- NPC: Kirin
-----------------------------------
package.loaded[ "scripts/zones/The_Shrine_of_RuAvitau/TextIDs" ] = nil;
-----------------------------------
require( "scripts/zones/The_Shrine_of_RuAvitau/TextIDs" );
require( "scripts/globals/titles" );
require( "scripts/globals/ability" );
require( "scripts/globals/pets" );
require( "scripts/globals/status" );
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize( mob )
end
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMod(MOD_WINDRES, -64);
end
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight( mob, target )
if (mob:getHPP() < math.random(50,60) and mob:getLocalVar("astralFlow") == 0) then
mob:useMobAbility(478);
-- Spawn Avatar
mob:spawnPet();
mob:setLocalVar("astralFlow", 1);
end
if (mob:getBattleTime() ~= 0 and mob:getBattleTime() % 180 == 0) then
-- Ensure we have not spawned all pets yet..
local genbu = mob:getLocalVar("genbu");
local seiryu = mob:getLocalVar("seiryu");
local byakko = mob:getLocalVar("byakko");
local suzaku = mob:getLocalVar("suzaku");
if (genbu == 1 and seiryu == 1 and byakko == 1 and suzaku == 1) then
return;
end
-- Pick a pet to spawn at random..
local ChosenPet = nil;
local newVar = nil;
repeat
local rand = math.random( 0, 3 );
ChosenPet = 17506671 + rand;
switch (ChosenPet): caseof {
[17506671] = function (x) if ( genbu == 1) then ChosenPet = 0; else newVar = "genbu"; end end, -- Genbu
[17506672] = function (x) if (seiryu == 1) then ChosenPet = 0; else newVar = "seiryu"; end end, -- Seiryu
[17506673] = function (x) if (byakko == 1) then ChosenPet = 0; else newVar = "byakko"; end end, -- Byakko
[17506674] = function (x) if (suzaku == 1) then ChosenPet = 0; else newVar = "suzaku"; end end, -- Suzaku
}
until (ChosenPet ~= 0 and ChosenPet ~= nil)
-- Spawn the pet..
local pet = SpawnMob( ChosenPet );
pet:updateEnmity( target );
pet:setPos( mob:getXPos(), mob:getYPos(), mob:getZPos() );
-- Update Kirins extra vars..
mob:setLocalVar(newVar, 1);
end
-- Ensure all spawned pets are doing stuff..
for pets = 17506671, 17506674 do
if (GetMobAction( pets ) == 16) then
-- Send pet after current target..
GetMobByID( pets ):updateEnmity( target );
end
end
end
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath( mob, killer )
-- Award title and cleanup..
killer:addTitle( KIRIN_CAPTIVATOR );
killer:showText( mob, KIRIN_OFFSET + 1 );
GetNPCByID( 17506693 ):hideNPC( 900 );
-- Despawn pets..
DespawnMob( 17506671 );
DespawnMob( 17506672 );
DespawnMob( 17506673 );
DespawnMob( 17506674 );
end
-----------------------------------
-- OnMobDespawn
-----------------------------------
function onMobDespawn( mob )
-- Despawn pets..
DespawnMob( 17506671 );
DespawnMob( 17506672 );
DespawnMob( 17506673 );
DespawnMob( 17506674 );
end
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/Windurst_Woods/npcs/Ominous_Cloud.lua | 19 | 5257 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Ominous Cloud
-- Type: Traveling Merchant NPC
-- @zone: 241
-- @pos -20.632 -3.939 -40.554
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local wijinruit = trade:getItemQty(951)
local uchitake = (trade:getItemQty(1161) / 99)
local tsurara = (trade:getItemQty(1164) / 99)
local kawahori = (trade:getItemQty(1167) / 99)
local makibishi = (trade:getItemQty(1170) / 99)
local hiraishin = (trade:getItemQty(1173) / 99)
local mizu = (trade:getItemQty(1176) / 99)
local shihei = (trade:getItemQty(1179) / 99)
local jusatsu = (trade:getItemQty(1182) / 99)
local kaginawa = (trade:getItemQty(1185) / 99)
local sairui = (trade:getItemQty(1188) / 99)
local kodoku = (trade:getItemQty(1191) / 99)
local shinobi = (trade:getItemQty(1194) / 99)
local sanjaku = (trade:getItemQty(2553) / 99)
local soushi = (trade:getItemQty(2555) / 99)
local kabenro = (trade:getItemQty(2642) / 99)
local jinko = (trade:getItemQty(2643) / 99)
local mokujin = (trade:getItemQty(2970) / 99)
local inoshi = (trade:getItemQty(2971) / 99)
local shikan = (trade:getItemQty(2972) / 99)
local chono = (trade:getItemQty(2973) / 99)
local tools = (uchitake + tsurara + kawahori + makibishi + hiraishin + mizu + shihei + jusatsu + kaginawa + sairui + kodoku + shinobi + sanjaku + soushi + kabenro + jinko + mokujin + inoshi + shikan + chono)
if (((tools * 99) + wijinruit) == trade:getItemCount()) then
if ((tools == math.floor(tools)) and (tools == wijinruit) and (player:getFreeSlotsCount() >= wijinruit)) then
player:tradeComplete();
if (uchitake > 0) then
player:addItem(5308,uchitake);
player:messageSpecial(ITEM_OBTAINED,5308);
end
if (tsurara > 0) then
player:addItem(5309,tsurara);
player:messageSpecial(ITEM_OBTAINED,5309);
end
if (kawahori > 0) then
player:addItem(5310,kawahori);
player:messageSpecial(ITEM_OBTAINED,5310);
end
if (makibishi > 0) then
player:addItem(5311,makibishi);
player:messageSpecial(ITEM_OBTAINED,5311);
end
if (hiraishin > 0) then
player:addItem(5312,hiraishin);
player:messageSpecial(ITEM_OBTAINED,5312);
end
if (mizu > 0) then
player:addItem(5313,mizu);
player:messageSpecial(ITEM_OBTAINED,5313);
end
if (shihei > 0) then
player:addItem(5314,shihei);
player:messageSpecial(ITEM_OBTAINED,5314);
end
if (jusatsu > 0) then
player:addItem(5315,jusatsu);
player:messageSpecial(ITEM_OBTAINED,5315);
end
if (kaginawa > 0) then
player:addItem(5316,kaginawa);
player:messageSpecial(ITEM_OBTAINED,5316);
end
if (sairui > 0) then
player:addItem(5317,sairui);
player:messageSpecial(ITEM_OBTAINED,5317);
end
if (kodoku > 0) then
player:addItem(5318,kodoku);
player:messageSpecial(ITEM_OBTAINED,5318);
end
if (shinobi > 0) then
player:addItem(5319,shinobi);
player:messageSpecial(ITEM_OBTAINED,5319);
end
if (sanjaku > 0) then
player:addItem(5417,sanjaku);
player:messageSpecial(ITEM_OBTAINED,5417);
end
if (soushi > 0) then
player:addItem(5734,soushi);
player:messageSpecial(ITEM_OBTAINED,5734);
end
if (kabenro > 0) then
player:addItem(5863,kabenro);
player:messageSpecial(ITEM_OBTAINED,5863);
end
if (jinko > 0) then
player:addItem(5864,jinko);
player:messageSpecial(ITEM_OBTAINED,5864);
end
if (mokujin > 0) then
player:addItem(5866,mokujin);
player:messageSpecial(ITEM_OBTAINED,5866);
end
if (inoshi > 0) then
player:addItem(5867,inoshi);
player:messageSpecial(ITEM_OBTAINED,5867);
end
if (shikan > 0) then
player:addItem(5868,shikan);
player:messageSpecial(ITEM_OBTAINED,5868);
end
if (chono > 0) then
player:addItem(5869,chono);
player:messageSpecial(ITEM_OBTAINED,5869);
end
end
end
-- 951 Wijinruit
-- 1161 Uchitake 5308
-- 1164 Tsurara 5309
-- 1167 Kawahori-ogi 5310
-- 1170 Makibishi 5311
-- 1173 Hiraishin 5312
-- 1176 Mizu-deppo 5313
-- 1179 Shihei 5314
-- 1182 Jusatsu 5315
-- 1185 Kaginawa 5316
-- 1188 Sairui-ran 5317
-- 1191 Kodoku 5318
-- 1194 Shinobi-tabi 5319
-- 2553 Sanjaku-tengui 5417
-- 2555 Soshi 5734
-- 2642 Kabenro 5863
-- 2643 Jinko 5864
-- 2970 Mokujin 5866
-- 2971 Inoshishinofuda 5867
-- 2972 Shikanofuda 5868
-- 2973 Chonofuda 5869
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x02ba,npc:getID());
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 |
MrClash/Monsterb0t | plugins/filter.lua | 6 | 3623 | local function save_filter(msg, name, value)
local hash = nil
if msg.to.type == 'channel' then
hash = 'chat:'..msg.to.id..':filters'
end
if msg.to.type == 'user' then
return 'SUPERGROUPS only'
end
if hash then
redis:hset(hash, name, value)
return "Successfull!"
end
end
local function get_filter_hash(msg)
if msg.to.type == 'channel' then
return 'chat:'..msg.to.id..':filters'
end
end
local function list_filter(msg)
if msg.to.type == 'user' then
return 'SUPERGROUPS only'
end
local hash = get_filter_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'Sencured Wordes:\n\n'
for i=1, #names do
text = text..'➡️ '..names[i]..'\n'
end
return text
end
end
local function get_filter(msg, var_name)
local hash = get_filter_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if value == 'msg' then
delete_msg(msg.id, ok_cb, false)
return 'WARNING!\nDon\'nt Use it!'
elseif value == 'kick' then
send_large_msg('channel#id'..msg.to.id, "BBye xD")
channel_kick_user('channel#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true)
delete_msg(msg.id, ok_cb, false)
end
end
end
local function get_filter_act(msg, var_name)
local hash = get_filter_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if value == 'msg' then
return 'Warning'
elseif value == 'kick' then
return 'Kick YOU'
elseif value == 'none' then
return 'Out of filter'
end
end
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
if matches[1] == "ilterlist" then
return list_filter(msg)
elseif matches[1] == "ilter" and matches[2] == "war1324jadlkhrou2aisn" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "You Are Not MOD"
else
local value = 'msg'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "in" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "You Are Not MOD"
else
local value = 'kick'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "out" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "You Are Not MOD"
else
local value = 'none'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "clean" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "You Are Not MOD"
else
local value = 'none'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "about" then
return get_filter_act(msg, matches[3]:lower())
else
if is_sudo(msg) then
return
elseif is_admin(msg) then
return
elseif is_momod(msg) then
return
elseif tonumber(msg.from.id) == tonumber(our_id) then
return
else
return get_filter(msg, msg.text:lower())
end
end
end
return {
patterns = {
"^[!/][Ff](ilter) (.+) (.*)$",
"^[!/][Ff](ilterlist)$",
"(.*)",
},
run = run
}
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Bastok_Markets/npcs/Brygid.lua | 2 | 5767 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Brygid
-- Start & Finishes Quest: Brygid the Stylist & Brygid the Stylist Returns
-- Involved in Quests: Riding on the Clouds
-- @zone 235
-- @pos -90 -4 -108
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/keyitems");
require("scripts/globals/equipment");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Bastok_Markets/TextIDs");
body_list = {12554,13712,12594,13723,12603,13699,12610,13783,12572,12611,13796,12571,13750,12604,13752,12544,13730,12578,12553,12595}
legs_list = {12829,12800,12866,12809,12810,12850,12828,12859,12837,14243,12838,12867,12827,12836,12860,12851}
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local BrygidReturns = player:getQuestStatus(BASTOK,BRYGID_THE_STYLIST_RETURNS);
local wantsSubligar = player:getVar("BrygidWantsSubligar");
if(player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 3) then
if(trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_2",0);
player:tradeComplete();
player:addKeyItem(SMILING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE);
end
elseif(BrygidReturns == QUEST_ACCEPTED and wantsSubligar ~= 0) then
if(trade:getItemCount() == 1 and trade:hasItemQty(15374+wantsSubligar,1)) then
player:tradeComplete();
player:startEvent(383);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local BrygidTheStylist = player:getQuestStatus(BASTOK,BRYGID_THE_STYLIST);
local BrygidReturns = player:getQuestStatus(BASTOK,BRYGID_THE_STYLIST_RETURNS);
local head = player:getEquipID(SLOT_HEAD);
local body = player:getEquipID(SLOT_BODY);
local hands = player:getEquipID(SLOT_HANDS);
local legs = player:getEquipID(SLOT_LEGS);
local feet = player:getEquipID(SLOT_FEET);
local getBody = player:getVar("BrygidGetBody");
local getLegs = player:getVar("BrygidGetLegs");
local wantsSubligar = player:getVar("BrygidWantsSubligar");
local BrygidSet = 0;
if(body == 12600 and legs == 12832) then BrygidSet = 1 end;
if(BrygidTheStylist == QUEST_ACCEPTED and BrygidSet == 1) then
player:startEvent(0x0137);
elseif((BrygidReturns ~= QUEST_ACCEPTED and BrygidTheStylist == QUEST_COMPLETED) and
(isArtifactArmor(head) or isArtifactArmor(body) or isArtifactArmor(hands)
or isArtifactArmor(legs) or isArtifactArmor(feet))) then
-- Randomize and store sets here
repeat
getBody = body_list[math.random(1,20)];
until(player:canEquipItem(getBody,false))
repeat
getLegs = legs_list[math.random(1,16)];
until(player:canEquipItem(getLegs,false))
player:setVar("BrygidGetBody",getBody);
player:setVar("BrygidGetLegs",getLegs);
--printf("Body %u Legs %u\n",getBody,getLegs);
player:startEvent(380,BrygidSet,getBody,getLegs,player:getMainJob());
elseif(BrygidReturns == QUEST_ACCEPTED and body == getBody and legs == getLegs and wantsSubligar == 0) then
-- Have the right equips, proceed with quest
player:startEvent(382);
elseif(BrygidReturns == QUEST_ACCEPTED and wantsSubligar == 0) then
-- Remind player what they need to wear
player:startEvent(381,BrygidSet,getBody,getLegs,player:getMainJob());
elseif(BrygidReturns == QUEST_ACCEPTED and wantsSubligar ~= 0) then
-- Remind player what subligar they need to turn in and the reward
player:startEvent(385,0,14400+wantsSubligar,15374+wantsSubligar);
elseif(BrygidTheStylist ~= QUEST_COMPLETED) then
player:startEvent(0x0136);
else
player:startEvent(0x0077);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 382) then
local canEquip = 0;
local hasBody = 0;
if(player:canEquipItem(14400+option,true)) then canEquip = 1; end
if not(player:hasItem(14400+option)) then hasBody = 1; end
player:updateEvent(0,option-1,hasBody,canEquip);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
local wantsSubligar = player:getVar("BrygidWantsSubligar");
if(csid == 0x0136 and player:getQuestStatus(BASTOK,BRYGID_THE_STYLIST) == QUEST_AVAILABLE) then
player:addQuest(BASTOK,BRYGID_THE_STYLIST);
elseif(csid == 0x0137) then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12720);
else
player:addTitle(BRYGIDAPPROVED);
player:addItem(12720);
player:messageSpecial(ITEM_OBTAINED,12720);
player:addFame(BASTOK,BAS_FAME*30);
player:completeQuest(BASTOK,BRYGID_THE_STYLIST);
end
elseif(csid == 380) then
player:delQuest(BASTOK,BRYGID_THE_STYLIST_RETURNS);
player:addQuest(BASTOK,BRYGID_THE_STYLIST_RETURNS);
elseif(csid == 382 and option ~= 99) then
player:setVar("BrygidWantsSubligar",option);
elseif(csid == 383) then
player:setVar("BrygidGetBody",0);
player:setVar("BrygidGetLegs",0);
player:setVar("BrygidWantsSubligar",0);
player:addTitle(BASTOKS_SECOND_BEST_DRESSED);
player:addItem(14400+wantsSubligar);
player:messageSpecial(ITEM_OBTAINED,14400+wantsSubligar);
player:addFame(BASTOK,BAS_FAME*30);
player:completeQuest(BASTOK,BRYGID_THE_STYLIST_RETURNS);
end
end; | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/spells/gain-dex.lua | 2 | 2309 | --------------------------------------
-- Spell: Gain-DEX
-- Boosts targets DEX stat
--------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
enchanceSkill = caster:getSkillLevel(34);
duration = 300;
if(enchanceSkill <309)then
power = 5
elseif(enchanceSkill >=309 and enchanceSkill <=319)then
power = 6
elseif(enchanceSkill >=320 and enchanceSkill <=329)then
power = 7
elseif(enchanceSkill >=330 and enchanceSkill <=339)then
power = 8
elseif(enchanceSkill >=340 and enchanceSkill <=349)then
power = 9
elseif(enchanceSkill >=350 and enchanceSkill <=359)then
power = 10
elseif(enchanceSkill >=360 and enchanceSkill <=369)then
power = 11
elseif(enchanceSkill >=370 and enchanceSkill <=379)then
power = 12
elseif(enchanceSkill >=380 and enchanceSkill <=389)then
power = 13
elseif(enchanceSkill >=390 and enchanceSkill <=399)then
power = 14
elseif(enchanceSkill >=400 and enchanceSkill <=409)then
power = 15
elseif(enchanceSkill >=410 and enchanceSkill <=419)then
power = 16
elseif(enchanceSkill >=420 and enchanceSkill <=429)then
power = 17
elseif(enchanceSkill >=430 and enchanceSkill <=439)then
power = 18
elseif(enchanceSkill >=440 and enchanceSkill <=449)then
power = 19
elseif(enchanceSkill >=450 and enchanceSkill <=459)then
power = 20
elseif(enchanceSkill >=460 and enchanceSkill <=469)then
power = 21
elseif(enchanceSkill >=470 and enchanceSkill <=479)then
power = 22
elseif(enchanceSkill >=480 and enchanceSkill <=489)then
power = 23
elseif(enchanceSkill >=480 and enchanceSkill <=499)then
power = 24
else
power = 25
end
if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then
duration = duration * 3;
end
if(target:hasStatusEffect(EFFECT_DEX_DOWN) == true) then
target:delStatusEffect(EFFECT_DEX_DOWN);
else
target:addStatusEffect(EFFECT_DEX_BOOST,power,0,duration);
end
end;
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/Ordelles_Caves/npcs/_5d1.lua | 19 | 2616 | -----------------------------------
-- Area: Ordelle's Caves
-- NPC: Strange Apparatus
-- @pos: -294 28 -100 193
-----------------------------------
package.loaded["scripts/zones/Ordelles_Caves/TextIDs"] = nil;
require("scripts/zones/Ordelles_Caves/TextIDs");
require("scripts/globals/strangeapparatus");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local trade = tradeToStrApp(player, trade);
if (trade ~= nil) then
if ( trade == 1) then -- good trade
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
end
player:startEvent(0x0005, drop, dropQty, INFINITY_CORE, 0, 0, 0, docStatus, 0);
else -- wrong chip, spawn elemental nm
spawnElementalNM(player);
delStrAppDocStatus(player);
player:messageSpecial(SYS_OVERLOAD);
player:messageSpecial(YOU_LOST_THE, trade);
end
else -- Invalid trade, lose doctor status
delStrAppDocStatus(player);
player:messageSpecial(DEVICE_NOT_WORKING);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
else
player:setLocalVar( "strAppPass", 1);
end
player:startEvent(0x0003, docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u", option);
if (csid == 0x0003) then
if (hasStrAppDocStatus(player) == false) then
local docStatus = 1; -- Assistant
if ( option == strAppPass(player)) then -- Good password
docStatus = 0; -- Doctor
giveStrAppDocStatus(player);
end
player:updateEvent(docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, 0);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0005) then
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
if (drop ~= 0) then
if ( dropQty == 0) then
dropQty = 1;
end
player:addItem(drop, dropQty);
player:setLocalVar("strAppDrop", 0);
player:setLocalVar("strAppDropQty", 0);
end
end
end; | gpl-3.0 |
mandrav/moai_pex_editor | src/designer.lua | 1 | 24163 | module(..., package.seeall)
-- MOAIDebugLines.setStyle ( MOAIDebugLines.PROP_MODEL_BOUNDS, 2, 1, 1, 1 )
-- MOAIDebugLines.setStyle ( MOAIDebugLines.PROP_WORLD_BOUNDS, 2, 0.75, 0.75, 0.75 )
-- this function updates the slider's label with the current value while dragging the thumb
function defaultSliderChange(e)
local slider = e.target
local item = slider.item
-- during construction, 'item' may be invalid...
if not item then return end
local text = slider:getValue()--item.value.min + e.value * (item.value.max - item.value.min)
slider.displayLabel:setText(tostring(text))
item.currentValue = text
debughelper.debug(item.name, "=", text)
end
-- this function re-creates the particle system when the slider's thumb has been released
function defaultSliderEndChange(e)
local filename = os.tmpname()
save(filename)
MOAIFileSystem.deleteFile(filename)
end
local adjustables = {
{ name="conf_title", label = "Particle configuration" },
{ name="duration", label="Duration", value={min=0, max=10, step=0.1} },
{ name="maxParticles", label="Max particles", value={min=1, max=500, step=1} },
{ name="particleLifeSpan", label="Lifespan", value={min=0, max=10, step=0.1} },
{ name="particleLifespanVariance", label="Lifespan variance", value={min=0, max=10, step=0.1} },
{ name="startParticleSize", label="Start size", value={min=1, max=500, step=1} },
{ name="startParticleSizeVariance", label="Start size variance", value={min=0, max=500, step=1} },
{ name="finishParticleSize", label="End size", value={min=1, max=500, step=1} },
{ name="FinishParticleSizeVariance", label="End size variance", value={min=0, max=500, step=1} },
{ name="angle", label="Emitter angle", value={min=0, max=360, step=1} },
{ name="angleVariance", label="Emitter angle variance", value={min=0, max=360, step=1} },
{ name="rotationStart", label="Start rotation", value={min=0, max=360, step=1} },
{ name="rotationStartVariance", label="Start rotation variance",value={min=0, max=360, step=1} },
{ name="rotationEnd", label="End rotation", value={min=0, max=360, step=1} },
{ name="rotationEndVariance", label="End rotation variance", value={min=0, max=360, step=1} },
{ name="gravity_title", label = "Gravity emitter" },
{ name="sourcePositionVariance", {
{name="x", label="X variance", value={min=0, max=1000, step=10} },
{name="y", label="Y variance", value={min=0, max=1000, step=10} },
}},
{ name="speed", label="Speed", value={min=0, max=500, step=1} },
{ name="speedVariance", label="Speed variance", value={min=0, max=500, step=1} },
{ name="gravity", {
{name="x", label="Gravity X", value={min=-500,max=500, step=10} },
{name="y", label="Gravity Y", value={min=-500,max=500, step=10} },
}},
{ name="tangentialAcceleration", label="Tangential acceleration",value={min=-500,max=500, step=10} },
{ name="tangentialAccelVariance", label="Tangential accel. variance",value={min=0, max=500, step=1} },
{ name="radialAcceleration", label="Radial acceleration", value={min=-400,max=400, step=10} },
{ name="radialAccelVariance", label="Radial accel. variance", value={min=0, max=500, step=1} },
{ name="radial_title", label = "Radial emitter" },
{ name="maxRadius", label="Max radius", value={min=0, max=500, step=1} },
{ name="maxRadiusVariance", label="Max radius variance", value={min=0, max=500, step=1} },
{ name="minRadius", label="Min radius", value={min=0, max=500, step=1} },
{ name="rotatePerSecond", label="Degrees/second", value={min=-360,max=360, step=1} },
{ name="rotatePerSecondVariance", label="Degrees/second variance",value={min=0, max=360, step=1} },
{ name="color_title", label = "Particle color" },
{ name="startColor", {
{name="red", label="Start red", value={min=0, max=1, step=0.05} },
{name="green", label="Start green", value={min=0, max=1, step=0.05} },
{name="blue", label="Start blue", value={min=0, max=1, step=0.05} },
{name="alpha", label="Start alpha", value={min=0, max=1, step=0.05} },
}},
{ name="startColorVariance", {
{name="red", label="Start red variance", value={min=0, max=1, step=0.05} },
{name="green", label="Start green variance", value={min=0, max=1, step=0.05} },
{name="blue", label="Start blue variance", value={min=0, max=1, step=0.05} },
{name="alpha", label="Start alpha variance", value={min=0, max=1, step=0.05} },
}},
{ name="finishColor", {
{name="red", label="End red", value={min=0, max=1, step=0.05} },
{name="green", label="End green", value={min=0, max=1, step=0.05} },
{name="blue", label="End blue", value={min=0, max=1, step=0.05} },
{name="alpha", label="End alpha", value={min=0, max=1, step=0.05} },
}},
{ name="finishColorVariance", {
{name="red", label="End red variance", value={min=0, max=1, step=0.05} },
{name="green", label="End green variance", value={min=0, max=1, step=0.05} },
{name="blue", label="End blue variance", value={min=0, max=1, step=0.05} },
{name="alpha", label="End alpha variance", value={min=0, max=1, step=0.05} },
}},
}
function locateTextureInPath(file)
return ResourceManager:getFilePath(file)
end
function load(filename)
-- add pex dir in path
local lastSep = filename:find("/[^/]*$")
if lastSep then
lastSep = lastSep - 1
local path = filename:sub(1, lastSep)
local dir = MOAIFileSystem.getRelativePath(path)
ResourceManager:addPath(dir)
end
debughelper.log("Reading PEX file: " .. filename)
local pex = MOAIXmlParser.parseFile ( filename )
if pex.type == "particleEmitterConfig" and pex.children then
for k,v in pairs(pex.children) do
-- debughelper.debug("Node " .. k)
local node = v[1]
if node and node.attributes then
if k == "texture" then
texture = locateTextureInPath(node.attributes["name"])
elseif k == "duration" or
k == "maxParticles" or k == "particleLifeSpan" or k == "particleLifespanVariance" or
k == "startParticleSize" or k == "startParticleSizeVariance" or k == "finishParticleSize" or
k == "FinishParticleSizeVariance" or k == "angle" or k == "angleVariance" or
k == "rotationStart" or k == "rotationStartVariance" or k == "rotationEnd" or
k == "rotationEndVariance" or k == "speed" or k == "speedVariance" or
k == "tangentialAcceleration" or k == "tangentialAccelVariance" or k == "radialAcceleration" or
k == "radialAccelVariance" or k == "maxRadius" or k == "maxRadiusVariance" or
k == "minRadius" or k == "rotatePerSecond" or k == "rotatePerSecondVariance" then
findRowByName(adjustables, k).currentValue = node.attributes["value"]
elseif k == "sourcePositionVariance" or k == "gravity" then
local row = findRowByName(adjustables, k)
findRowByName(row[1], "x").currentValue = node.attributes["x"]
findRowByName(row[1], "y").currentValue = node.attributes["y"]
elseif k == "startColor" or k == "startColorVariance" or
k == "finishColor" or k == "finishColorVariance" then
local row = findRowByName(adjustables, k)
findRowByName(row[1], "red").currentValue = node.attributes["red"]
findRowByName(row[1], "green").currentValue = node.attributes["green"]
findRowByName(row[1], "blue").currentValue = node.attributes["blue"]
findRowByName(row[1], "alpha").currentValue = node.attributes["alpha"]
elseif k == "emitterType" then
emitterType = tonumber(node.attributes["value"])
elseif k == "blendFuncSource" then
blendFuncSource = tonumber(node.attributes["value"])
elseif k == "blendFuncDestination" then
blendFuncDestination = tonumber(node.attributes["value"])
else
debughelper.warn("Unknown node: " .. k)
end
end
end
debughelper.log("Finished reading PEX file: " .. filename)
else
debughelper.error("Not a PEX file or file empty: " .. filename)
end
applySliderValues()
showHideEmitterType()
recreateParticleSystem(filename)
openedFile = filename
end
-- helper for save()
local function _writeElement(f, name, ...)
f:write("<")
f:write(name)
f:write(" ")
for i=1,#arg,2 do
f:write(arg[i])
f:write("=\"")
f:write(arg[i+1])
f:write("\" ")
end
f:write("/>\n")
end
function save(filename)
if not filename then
debughelper.error("No filename given; aborting save")
return
end
debughelper.debug("Writing PEX file: " .. filename)
local f = io.open(filename, "w+")
if not f then
debughelper.error("Failed to open PEX file for writing: " .. filename)
return
end
local cwd = MOAIFileSystem.getWorkingDirectory()
local texAbs = MOAIFileSystem.getAbsoluteFilePath(texture)
local tmpAbs = string.sub(filename, 1, -string.find(string.reverse(filename), "/", 1, true))
MOAIFileSystem.setWorkingDirectory(tmpAbs)
local texName = MOAIFileSystem.getRelativePath(texAbs)-- .. "particles/cloudlet.png"
MOAIFileSystem.setWorkingDirectory(cwd)
-- print(texName)
-- debughelper.debug("Tmp path: " .. tmpAbs)
-- debughelper.debug("Tex path: " .. texAbs)
-- debughelper.debug("Rel path: " .. texName)
-- debughelper.debug("Cwd path: " .. cwd)
f:write("<particleEmitterConfig>\n")
_writeElement(f, "texture", "name", texName)
for _,v in ipairs(adjustables) do
if #v == 0 and v.currentValue then
_writeElement(f, v.name, "value", v.currentValue)
else
local attrs = {}
for _,c in ipairs(v[1]) do
attrs[#attrs + 1] = c.name
attrs[#attrs + 1] = c.currentValue
end
_writeElement(f, v.name, unpack(attrs))
end
end
_writeElement(f, "emitterType", "value", emitterType) -- (0: gravity, 1: radial)
_writeElement(f, "blendFuncSource", "value", blendFuncSource)
_writeElement(f, "blendFuncDestination", "value", blendFuncDestination)
f:write("</particleEmitterConfig>\n")
showHideEmitterType()
-- case 0: return Context3DBlendFactor.ZERO; break;
-- case 1: return Context3DBlendFactor.ONE; break;
-- case 0x300 768: return Context3DBlendFactor.SOURCE_COLOR; break;
-- case 0x301 769: return Context3DBlendFactor.ONE_MINUS_SOURCE_COLOR; break;
-- case 0x302 770: return Context3DBlendFactor.SOURCE_ALPHA; break;
-- case 0x303 771: return Context3DBlendFactor.ONE_MINUS_SOURCE_ALPHA; break;
-- case 0x304 772: return Context3DBlendFactor.DESTINATION_ALPHA; break;
-- case 0x305 773: return Context3DBlendFactor.ONE_MINUS_DESTINATION_ALPHA; break;
-- case 0x306 774: return Context3DBlendFactor.DESTINATION_COLOR; break;
-- case 0x307 775: return Context3DBlendFactor.ONE_MINUS_DESTINATION_COLOR; break;
-- debughelper.debug("Writing PEX file: " .. filename)
-- PEXWriter.write(filename, pex)
-- debughelper.debug("Done writing PEX file: " .. filename)
f:close()
debughelper.debug("PEX file written: " .. filename)
recreateParticleSystem(filename)
end
function findRowByName(tbl, name)
for _,r in ipairs(tbl) do
if r.name == name then
return r
end
end
return nil
end
function recreateParticleSystem(filename)
if particle ~= nil then
particle:stopParticle()
particle:stop()
pview:removeChild(particle)
particle = nil
end
local function protectedCall()
particle = Particles.fromPex(filename or "particles/deathBlossomCharge.pex")
end
if pcall(protectedCall) then
particle:setParent(pview)
particle.emitter:setLoc(PWIDTH * 0.5, Application.viewHeight * 0.5)
particle.emitter:forceUpdate()
particle:start()
particle:startParticle()
local duration = tonumber(findRowByName(adjustables, "duration").currentValue)
-- debughelper.debug("DURATION", duration)
restartButton:setEnabled(duration > 0)
else
showError("Failed to recreate the particle system!\nThe program will now exit.\nCheck console for details...", true)
end
end
function applySliderValues()
for _,v in ipairs(adjustables) do
if #v == 0 then
if v.slider then
-- print(v.label, v.currentValue)
v.slider:setValue(tonumber(v.currentValue))
end
else
for _,c in ipairs(v[1]) do
if c.slider then
-- print(v.label, v.currentValue)
c.slider:setValue(tonumber(c.currentValue))
end
end
end
end
end
-- show/hide gravity/radial emitter settings based on type
function showHideEmitterType()
local t = emitterType
local row = nil
findRowByName(adjustables, "gravity_title").hidden = t ~= 0
row = findRowByName(adjustables, "sourcePositionVariance")
findRowByName(row[1], "x").hidden = t ~= 0
findRowByName(row[1], "y").hidden = t ~= 0
findRowByName(adjustables, "speed").hidden = t ~= 0
findRowByName(adjustables, "speedVariance").hidden = t ~= 0
row = findRowByName(adjustables, "gravity")
findRowByName(row[1], "x").hidden = t ~= 0
findRowByName(row[1], "y").hidden = t ~= 0
findRowByName(adjustables, "tangentialAcceleration").hidden = t ~= 0
findRowByName(adjustables, "tangentialAccelVariance").hidden = t ~= 0
findRowByName(adjustables, "radialAcceleration").hidden = t ~= 0
findRowByName(adjustables, "radialAccelVariance").hidden = t ~= 0
findRowByName(adjustables, "radial_title").hidden = t == 0
findRowByName(adjustables, "maxRadius").hidden = t == 0
findRowByName(adjustables, "maxRadiusVariance").hidden = t == 0
findRowByName(adjustables, "minRadius").hidden = t == 0
findRowByName(adjustables, "rotatePerSecond").hidden = t == 0
findRowByName(adjustables, "rotatePerSecondVariance").hidden = t == 0
if group then
group:removeChildren()
for _,v in ipairs(adjustables) do
if #v == 0 then
v.group:setVisible(not hidden)
if v.group and not v.hidden then
group:addChild(v.group)
end
else
for _,c in ipairs(v[1]) do
c.group:setVisible(not hidden)
if c.group and not c.hidden then
group:addChild(c.group)
end
end
end
end
end
end
PWIDTH = 400 -- particle-view width
BWIDTH = 100 -- buttons width
BHEIGHT = 40 -- buttons height
BGAP = 5 -- gap between buttons
TWIDTH = BWIDTH + BGAP * 2 -- tools-view (buttons) width
function createParticleView()
--
-- particles view
--
pview = View {
scene = scene,
pos = {0, 0},
size = {PWIDTH, Application.viewHeight},
}
local bg = Mesh.newRect(0, 0, PWIDTH, Application.viewHeight, "#ffffff")
bg:setParent(pview)
pview:setColor(0.2, 0.2, 0.2, 1)
end
function createSlidersView()
--
-- main (sliders) view
--
view = View {
scene = scene,
pos = {PWIDTH, 0},
size = {Application.viewWidth - PWIDTH - TWIDTH, Application.viewHeight},
}
bg = Mesh.newRect(0, 0, Application.viewWidth - PWIDTH - TWIDTH, Application.viewHeight, "#444444")
bg:setParent(view)
scroller = Scroller {
parent = view,
layout = VBoxLayout {
align = {"left", "top"},
padding = {0, 0, 0, 0},
gap = {0, 0},
},
hBounceEnabled = false
}
Component = require "hp/gui/Component"
group = Component {
parent = scroller,
layout = VBoxLayout {
align = {"center", "top"},
padding = {0, 0, 0, 0},
gap = {0, 0},
},
}
for _,v in ipairs(adjustables) do
local has_children = #v > 0
local is_title = not has_children and v.value == nil
if not has_children then
createSlider(v, is_title)
else
for _,c in ipairs(v[1]) do
createSlider(c, c.value == nil)
end
end
end
end
function createSlider(adj, is_title)
local x = 10
local lw = 240
local vw = 60
local gap = 10
local pw = Application.viewWidth - PWIDTH - TWIDTH - lw - gap - vw - gap - gap - gap -- take all free space
local w = lw + gap + pw + gap + vw - gap
local h = 38
local localGroup = Group {
parent = group
}
if is_title then
local bg = Mesh.newRect(x, 0, w, h, {"#00aa00", "#004400", 90})
bg:setParent(localGroup)
TextLabel {
parent = localGroup,
text = adj.label,
pos = {x, 0},
size = {w, h},
textSize = 24,
font = "fonts/arialbd.ttf",
align = {"center", "center"},
}
else
TextLabel {
parent = localGroup,
text = adj.label,
pos = {x, 0},
size = {lw, h},
textSize = 16,
align = {"right", "center"},
}
local slider = Slider {
parent = localGroup,
pos = {x + lw + gap, 0},
size = {pw, h},
value = 0,
valueBounds = {adj.value.min, adj.value.max},
accuracy = adj.value.step,
onSliderChanged = defaultSliderChange,
onSliderEndChange = defaultSliderEndChange,
}
local label = TextLabel {
parent = localGroup,
text = tostring(tonumber(adj.currentValue)),
pos = {x + lw + gap + pw + gap, 0},
size = {vw, h},
textSize = 16,
align = {"left", "center"},
}
slider.item = adj
slider.displayLabel = label
adj.slider = slider
end
localGroup:resizeForChildren()
adj.group = localGroup
end
function createToolsView()
--
-- tools view (buttons)
--
bview = View {
scene = scene,
pos = {Application.viewWidth - TWIDTH, 0},
size = {TWIDTH, Application.viewHeight},
}
bg = Mesh.newRect(0, 0, TWIDTH, Application.viewHeight, {"#00aa00", "#004400", 90})
bg:setParent(bview)
tgroup = Component {
parent = bview,
layout = VBoxLayout {
align = {"center", "top"},
padding = {BGAP, 5, BGAP, 5},
gap = {BGAP, 5},
},
}
restartButton = Button {
parent = tgroup,
text = "Restart",
size = {BWIDTH, BHEIGHT * 2},
enabled = false,
onClick = function() particle:stopParticle() particle:startParticle() end,
}
Component { -- spacer
parent = tgroup,
size = {BWIDTH, BHEIGHT},
}
textureButton = Button {
parent = tgroup,
text = "Texture",
size = {BWIDTH, BHEIGHT},
onClick = selectTexture,
}
emitterButton = Button {
parent = tgroup,
text = "Emitter",
size = {BWIDTH, BHEIGHT},
onClick = selectEmitterType,
}
blendSrcButton = Button {
parent = tgroup,
text = "Blend src",
size = {BWIDTH, BHEIGHT},
onClick = selectBlendSrcMode,
}
blendDstButton = Button {
parent = tgroup,
text = "Blend dst",
size = {BWIDTH, BHEIGHT},
onClick = selectBlendDstMode,
}
Component { -- spacer
parent = tgroup,
size = {BWIDTH, BHEIGHT},
}
bgColorButton = Button {
parent = tgroup,
text = "BG color",
size = {BWIDTH, BHEIGHT},
onClick = selectBgColor,
}
Component { -- spacer
parent = tgroup,
size = {BWIDTH, BHEIGHT},
}
reloadButton = Button {
parent = tgroup,
text = "Reload",
size = {BWIDTH, BHEIGHT},
onClick = function()
confirm("Are you sure you want to reload?\nYou will lose <c:ff0000>ALL</c> modifications!",
function() -- yes
load(openedFile)
end)
end,
}
loadButton = Button {
parent = tgroup,
text = "Load",
size = {BWIDTH, BHEIGHT},
onClick = function()
if openedFile then
confirm("Are you sure you want to load another\nfile?\nYou will lose <c:ff0000>ALL</c> modifications!",
function() -- yes
loadPS()
end)
else
loadPS()
end
end,
}
saveButton = Button {
parent = tgroup,
text = "Save",
size = {BWIDTH, BHEIGHT},
onClick = function() save(openedFile) end,
}
end
function enableAll(en)
-- sliders
for _,v in ipairs(adjustables) do
if #v ~= 0 then
for _,c in ipairs(v[1]) do
if c.slider then
c.slider:setEnabled(en)
end
end
else
if v.slider then
v.slider:setEnabled(en)
end
end
end
-- buttons
-- restartButton:setEnabled(en)
textureButton:setEnabled(en)
emitterButton:setEnabled(en)
blendSrcButton:setEnabled(en)
blendDstButton:setEnabled(en)
bgColorButton:setEnabled(en)
reloadButton:setEnabled(en)
loadButton:setEnabled(en)
saveButton:setEnabled(en)
end
function onCreate(params)
-- init
for _,v in ipairs(adjustables) do
v.currentValue = 0
if #v ~= 0 then
for _,c in ipairs(v[1]) do
c.currentValue = 0
end
end
end
createParticleView()
createSlidersView()
createToolsView()
enableAll(false)
loadButton:setEnabled(true)
end
function onStart()
if APP_DEBUG then
debughelper.attach(scene)
end
-- load("particles/deathBlossomCharge.pex")
-- selectBgColor()
end
function onStop()
if APP_DEBUG then
debughelper.detach()
end
end
function loadPS()
SceneManager:openScene("file_dialog",
{
animation = "popIn",
size = {480, 640},
value = openedFile,
filter = {"%.pex$"},
onResult = onPS,
})
end
function onPS(value)
if value == nil then return end
load(value)
local success = particle ~= nil
enableAll(success)
end
function selectTexture()
SceneManager:openScene("file_dialog",
{
animation = "popIn",
size = {480, 640},
value = texture,
filter = {"%.png$", "%.jpg$", "%.jpeg$", "%.tga$", "%.bmp$"},
onResult = onTexture,
})
end
function onTexture(value)
if value == nil then return end
texture = MOAIFileSystem.getRelativePath(value)
particle:setTexture(texture)
print("FILE", texture)
end
function selectBgColor()
SceneManager:openScene("color_dialog",
{
animation = "popIn",
size = {480, 320},
value = {pview:getColor()},
onResult = onBgColor,
})
end
function onBgColor(value)
if not value then return end
pview:setColor(unpack(value))
end
function selectBlendSrcMode()
SceneManager:openScene("blendmode_dialog",
{
animation = "popIn",
value = blendFuncSource,
onResult = onBlendSrcMode,
})
end
function onBlendSrcMode(value)
if value == -1 then return end
blendFuncSource = value
particle:setBlendMode(blendFuncSource, blendFuncDestination)
end
function selectBlendDstMode()
SceneManager:openScene("blendmode_dialog",
{
animation = "popIn",
value = blendFuncDestination,
onResult = onBlendDstMode,
})
end
function onBlendDstMode(value)
if value == -1 then return end
blendFuncDestination = value
particle:setBlendMode(blendFuncSource, blendFuncDestination)
end
function selectEmitterType()
SceneManager:openScene("emitter_dialog",
{
animation = "popIn",
size = {740, 320},
type = DialogBox.TYPE_CONFIRM,
title = "Emitter Type Selection",
text = "Please select the emitter type to use. There are two available\ntypes to choose from: <c:ff0000>GRAVITY</c> and <c:ff0000>RADIAL</c>.\n\nMake your choice...",
buttons = {"Gravity", "Radial", "Cancel"},
onResult = onEmitterType,
})
end
function onEmitterType(e)
if e.resultIndex == 3 then
-- cancel
return
end
emitterType = e.resultIndex - 1
save(os.tmpname())
end
function showError(errorText, fatal)
SceneManager:openScene("generic_dialog",
{
animation = "popIn", backAnimation = "popOut",
size = {480, 240},
type = DialogBox.TYPE_ERROR,
title = "Error",
text = errorText,
buttons = {"OK"},
onResult = function() if fatal then os.exit() end end,
})
end
function confirm(text, yesCallback, noCallback)
SceneManager:openScene("generic_dialog",
{
animation = "popIn", backAnimation = "popOut",
size = {480, 240},
type = DialogBox.TYPE_CONFIRM,
title = "Confirmation",
text = text,
buttons = {"Yes", "No"},
onResult = function(e)
Executors.callLater(function()
if e.resultIndex == 1 and yesCallback then
yesCallback()
elseif e.resultIndex == 2 and noCallback then
noCallback()
end
end)
end,
})
end
| mit |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Windurst_Waters/npcs/Yung_Yaam.lua | 6 | 1666 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Yung Yaam
-- Involved In Quest: Wondering Minstrel
-- Working 100%
-- @zone = 238
-- @pos = -63 -4 27
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--player:addFame(WINDURST,WIN_FAME*100)
wonderingstatus = player:getQuestStatus(WINDURST,WONDERING_MINSTREL);
fame = player:getFameLevel(WINDURST)
if (wonderingstatus <= 1 and fame >= 5) then
player:startEvent(0x027d); -- WONDERING_MINSTREL: Quest Available / Quest Accepted
elseif (wonderingstatus == QUEST_COMPLETED and player:needToZone()) then
player:startEvent(0x0283); -- WONDERING_MINSTREL: Quest After
else
player:startEvent(0x0261); -- Standard Conversation
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 |
Sonicrich05/FFXI-Server | scripts/globals/weaponskills/tachi_ageha.lua | 30 | 1716 | -----------------------------------
-- Tachi Ageha
-- Great Katana weapon skill
-- Skill Level: 300
-- Lowers target's defense. Chance of lowering target's defense varies with TP.
-- 30% Defense Down
-- Duration of effect is exactly 3 minutes.
-- Aligned with the Shadow Gorget, Soil Gorget.
-- Aligned with the Shadow Belt, Soil Belt.
-- Element: None
-- Skillchain Properties: Compression/Scission
-- Modifiers: CHR:60% STR:40%
-- 100%TP 200%TP 300%TP
-- 2.625 2.625 2.625
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 2.80; params.ftp200 = 2.80; params.ftp300 = 2.80;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.50;
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 = 2.625; params.ftp200 = 2.625; params.ftp300 = 2.625;
params.str_wsc = 0.4; params.chr_wsc = 0.6;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
if damage > 0 and (target:hasStatusEffect(EFFECT_DEFENSE_DOWN) == false) then
target:addStatusEffect(EFFECT_DEFENSE_DOWN, 25, 0, 180);
end
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Mount_Zhayolm/npcs/_1p6.lua | 23 | 1050 | -----------------------------------
-- Area: Mount Zhayolm
-- NPC: Engraved Tablet
-- @pos 320 -15.35 -379 61
-----------------------------------
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:hasKeyItem(SILVER_SEA_SALT)) then
player:startEvent(0x000c);
else
player:startEvent(0x000e);
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 == 0x000c and option == 1) then
player:delKeyItem(SILVER_SEA_SALT);
end
end; | gpl-3.0 |
parsaghx/t | plugins/badword.lua | 17 | 2452 | --[[
#
# @WaderTGTeam
# @WaderTG
#
]]
local function addword(msg, name)
local hash = 'chat:'..msg.to.id..':badword'
redis:hset(hash, name, 'newword')
return "added the badword:\n\n>"..name
end
local function get_variables_hash(msg)
return 'chat:'..msg.to.id..':badword'
end
local function list_variablesbad(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'badword list:\n\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
else
return
end
end
function clear_commandbad(msg, var_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:del(hash, var_name)
return 'cleared'
end
local function list_variables2(msg, value)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(value, names[i]) and not is_momod(msg) then
if msg.to.type == 'channel' then
delete_msg(msg.id,ok_cb,false)
else
kick_user(msg.from.id, msg.to.id)
end
return
end
--text = text..names[i]..'\n'
end
end
end
local function get_valuebad(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
function clear_commandsbad(msg, cmd_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:hdel(hash, cmd_name)
return ''..cmd_name..' clear'
end
local function run(msg, matches)
if matches[2] == 'addword' then
if not is_momod(msg) then
return 'only for moderators'
end
local name = string.sub(matches[3], 1, 50)
local text = addword(msg, name)
return text
end
if matches[2] == 'badwords' then
return list_variablesbad(msg)
elseif matches[2] == 'clearbadwords' then
if not is_momod(msg) then return '_|_' end
local asd = '1'
return clear_commandbad(msg, asd)
elseif matches[2] == 'remword' or matches[2] == 'rw' then
if not is_momod(msg) then return '_|_' end
return clear_commandsbad(msg, matches[3])
else
local name = user_print_name(msg.from)
return list_variables2(msg, matches[1])
end
end
return {
patterns = {
"^([!/#])(rw) (.*)$",
"^([!/#])(addword) (.*)$",
"^([!/#])(remword) (.*)$",
"^([!/#])(badwords)$",
"^([!/#])(clearbadwords)$",
"^(.+)$",
},
run = run
}
| gpl-2.0 |
DiNaSoR/Angel_Arena | game/angel_arena/scripts/vscripts/mechanics/camps/creep_power.lua | 1 | 1195 | if CreepPower == nil then
CreepPower = class({})
end
function CreepPower:GetPowerForMinute (minute)
local multFactor = 1
--HP MANA DMG ARM GOLD EXP
if minute == 0 then
return { 1, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 * self.numPlayersXPFactor}
end
if minute > CREEP_GROWTH then
multFactor = 1.5 ^ (minute - CREEP_GROWTH)
end
return {
minute, -- minute
(15 * ((minute / 100) ^ 4) - 45 * ((minute/100) ^ 3) + 25 * ((minute/100) ^ 2) - 0 * (minute/100)) + 0.5, -- hp
(15 * ((minute / 100) ^ 4) - 45 * ((minute/100) ^ 3) + 25 * ((minute/100) ^ 2) - 0 * (minute/100)) + 0.5, -- mana
(80 * ((minute / 100) ^ 4) - 180 * ((minute/100) ^ 3) + 100 * ((minute/100) ^ 2) - 0 * (minute/100)) + 0.5, -- damage
(minute / 54) ^ 2 + minute / 20 + 0.5, -- armor
(13 * minute^2 + 375 * minute + 7116)/7116, -- gold
((25 * minute^2 + 67 * minute + 2500) / 2500) * self.numPlayersXPFactor * multFactor -- xp
}
end
function CreepPower:Init ()
local maxTeamPlayerCount = 10
self.numPlayersXPFactor = 1
end
| mit |
fruitwasp/DarkRP | gamemode/modules/logging/cl_init.lua | 8 | 1118 | --[[---------------------------------------------------------------------------
Log a message to console
---------------------------------------------------------------------------]]
local function AdminLog(um)
local colour = Color(um:ReadShort(), um:ReadShort(), um:ReadShort())
local text = DarkRP.deLocalise(um:ReadString() .. "\n")
MsgC(Color(255, 0, 0), "[" .. GAMEMODE.Name .. "] ", colour, text)
hook.Call("DarkRPLogPrinted", nil, text, colour)
end
usermessage.Hook("DRPLogMsg", AdminLog)
--[[---------------------------------------------------------------------------
Interface
---------------------------------------------------------------------------]]
DarkRP.hookStub{
name = "DarkRPLogPrinted",
description = "Called when a log has printed in console.",
realm = "Client",
parameters = {
{
name = "text",
description = "The actual log.",
type = "string"
},
{
name = "colour",
description = "The colour of the printed log.",
type = "Color"
}
},
returns = {}
}
| mit |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Gusgen_Mines/npcs/Clay.lua | 2 | 1167 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: Clay
-- involved in quest A Potter's Preference
-- pos x:117 y:-21 z:432
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/settings");
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
require("scripts/zones/Gusgen_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:addItem(569,1); --569 - dish_of_gusgen_clay
player:messageSpecial(ITEM_OBTAINED,569); -- dish_of_gusgen_clay
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/Northern_San_dOria/npcs/Tavourine.lua | 36 | 1864 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Tavourine
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,TAVOURINE_SHOP_DIALOG);
stock = {16584,37800,1, --Mythril Claymore
16466,2182,1, --Knife
17060,2386,1, --Rod
16640,284,2, --Bronze Axe
16465,147,2, --Bronze Knife
17081,621,2, --Brass Rod
16583,2448,2, --Claymore
17035,4363,2, --Mace
17059,90,3, --Bronze Rod
17034,169,3} --Bronze Mace
showNationShop(player, SANDORIA, 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 |
ShmooDude/ovale | dist/scripts/ovale_mage_spells.lua | 1 | 33046 | local __exports = LibStub:NewLibrary("ovale/scripts/ovale_mage_spells", 80000)
if not __exports then return end
local __Scripts = LibStub:GetLibrary("ovale/Scripts")
local OvaleScripts = __Scripts.OvaleScripts
__exports.register = function()
local name = "ovale_mage_spells"
local desc = "[8.0] Ovale: Mage spells"
local code = [[Define(ancestral_call 274738)
# Invoke the spirits of your ancestors, granting you their power for 15 seconds.
SpellInfo(ancestral_call cd=120 duration=15 gcd=0 offgcd=1)
SpellAddBuff(ancestral_call ancestral_call=1)
Define(arcane_barrage 44425)
# Launches bolts of arcane energy at the enemy target, causing (80 of Spell Power) Arcane damage. rnrnFor each Arcane Charge, deals 36032s2 additional damage?a231564[ and hits 36032s3 additional nearby Ltarget:targets; for s2 of its damage][].rnrn|cFFFFFFFFConsumes all Arcane Charges.|r
# Rank 2: Arcane Barrage hits s1 additional Ltarget:targets; within 44425s3 yds per Arcane Charge for 44425s2 damage.
SpellInfo(arcane_barrage cd=3)
Define(arcane_blast 30451)
# Blasts the target with energy, dealing (55.00000000000001 of Spell Power) Arcane damage.rnrnEach Arcane Charge increases damage by 36032s1 and mana cost by 36032s5, and reduces cast time by 36032s4.rnrn|cFFFFFFFFGenerates 1 Arcane Charge.|r
SpellInfo(arcane_blast arcanecharges=-1)
Define(arcane_explosion 1449)
# Causes an explosion of magic around the caster, dealing (60 of Spell Power) Arcane damage to all enemies within A2 yards.rnrn|cFFFFFFFFGenerates s1 Arcane Charge if any targets are hit.|r
SpellInfo(arcane_explosion arcanecharges=-1)
Define(arcane_familiar 205022)
# Summon a Familiar that attacks your enemies and increases your maximum mana by 210126s1 for 3600 seconds.
SpellInfo(arcane_familiar cd=10 duration=3600 talent=arcane_familiar_talent)
SpellAddTargetDebuff(arcane_familiar arcane_familiar=1)
Define(arcane_intellect 1459)
# Infuses the target with brilliance, increasing their Intellect by s1 for 3600 seconds. rnrnIf target is in your party or raid, all party and raid members will be affected.
SpellInfo(arcane_intellect duration=3600)
# Intellect increased by w1.
SpellAddTargetDebuff(arcane_intellect arcane_intellect=1)
Define(arcane_missiles 5143)
# Launches five waves of Arcane Missiles at the enemy over 2.5 seconds, causing a total of 5*(50 of Spell Power) Arcane damage.
SpellInfo(arcane_missiles duration=2.5 channel=2.5 tick=0.625)
SpellAddBuff(arcane_missiles arcane_missiles=1)
SpellAddTargetDebuff(arcane_missiles arcane_missiles=1)
Define(arcane_orb 153626)
# Launches an Arcane Orb forward from your position, traveling up to 40 yards, dealing (120 of Spell Power) Arcane damage to enemies it passes through.rnrn|cFFFFFFFFGrants 1 Arcane Charge when cast and every time it deals damage.|r
SpellInfo(arcane_orb cd=20 duration=2.5 arcanecharges=-1 talent=arcane_orb_talent)
Define(arcane_power 12042)
# For 10 seconds, you deal s1 more spell damage and your spells cost s2 less mana.
SpellInfo(arcane_power cd=90 duration=10)
# Spell damage increased by w1.rnMana costs of your damaging spells reduced by w2.
SpellAddBuff(arcane_power arcane_power=1)
Define(battle_potion_of_intellect 279151)
# Increases your Intellect by s1 for 25 seconds.
SpellInfo(battle_potion_of_intellect cd=1 duration=25 gcd=0 offgcd=1)
# Intellect increased by w1.
SpellAddBuff(battle_potion_of_intellect battle_potion_of_intellect=1)
Define(berserking 26297)
# Increases your haste by s1 for 10 seconds.
SpellInfo(berserking cd=180 duration=10 gcd=0 offgcd=1)
# Haste increased by s1.
SpellAddBuff(berserking berserking=1)
Define(berserking_buff 200953)
# Rampage and Execute have a chance to activate Berserking, increasing your attack speed and critical strike chance by 200953s1 every 200951t1 sec for 12 seconds.
SpellInfo(berserking_buff duration=3 max_stacks=12 gcd=0 offgcd=1)
# Attack speed and critical strike chance increased by s1.
SpellAddBuff(berserking_buff berserking_buff=1)
Define(blast_wave 157981)
# Causes an explosion around yourself, dealing (45 of Spell Power) Fire damage to all enemies within A1 yards, knocking them back, and reducing movement speed by s2 for 4 seconds.
SpellInfo(blast_wave cd=25 duration=4 talent=blast_wave_talent)
# Movement speed reduced by s2.
SpellAddTargetDebuff(blast_wave blast_wave=1)
Define(blink 1953)
# Teleports you forward A1 yds or until reaching an obstacle, and frees you from all stuns and bonds.
SpellInfo(blink cd=0.5 charge_cd=15 duration=0.3 channel=0.3)
# Blinking.
SpellAddBuff(blink blink=1)
Define(blizzard 190356)
# Ice shards pelt the target area, dealing 190357m1*8 Frost damage over 8 seconds and reducing movement speed by 205708s1 for 15 seconds.?a236662[rnrnEach time Blizzard deals damage, the cooldown of Frozen Orb is reduced by 236662s1/100.1 sec.][]
# Rank 2: Each time Blizzard deals damage, the cooldown of Frozen Orb is reduced by s1/100.1 sec.
SpellInfo(blizzard cd=8 duration=8)
Define(charged_up 205032)
# Immediately grants s1 Arcane Charges.
SpellInfo(charged_up cd=40 duration=10 arcanecharges=-4 talent=charged_up_talent)
SpellAddBuff(charged_up charged_up=1)
Define(clearcasting 79684)
# For each c*100/s1 mana you spend, you have a 1 chance to gain Clearcasting, making your next Arcane Missiles or Arcane Explosion free and channel 277726s1 faster.
SpellInfo(clearcasting channel=0 gcd=0 offgcd=1)
SpellAddBuff(clearcasting clearcasting=1)
Define(combustion 190319)
# Engulfs you in flames for 10 seconds, increasing your spells' critical strike chance by s1 and granting you Mastery equal to s3 your Critical Strike stat. Castable while casting other spells.
SpellInfo(combustion cd=120 duration=10 gcd=0 offgcd=1 tick=0.5)
# Critical Strike chance of your spells increased by w1.?a231630[rnMastery increased by w2.][]
SpellAddBuff(combustion combustion=1)
Define(comet_storm 153595)
# Calls down a series of 7 icy comets on and around the target, that deals up to 7*(45 of Spell Power) Frost damage to all enemies within 228601A1 yds of its impacts.
SpellInfo(comet_storm cd=30 talent=comet_storm_talent)
Define(cone_of_cold 120)
# Targets in a cone in front of you take (37.5 of Spell Power) Frost damage and have movement slowed by 212792m1 for 5 seconds.
SpellInfo(cone_of_cold cd=12)
Define(counterspell 2139)
# Counters the enemy's spellcast, preventing any spell from that school of magic from being cast for 6 seconds?s12598[ and silencing the target for 55021d][].
SpellInfo(counterspell cd=24 duration=6 gcd=0 offgcd=1 interrupt=1)
Define(dragons_breath 31661)
# Enemies in a cone in front of you take (58.25 of Spell Power) Fire damage and are disoriented for 4 seconds. Damage will cancel the effect.
SpellInfo(dragons_breath cd=20 duration=4)
# Disoriented.
SpellAddTargetDebuff(dragons_breath dragons_breath=1)
Define(ebonbolt 257537)
# Launch a bolt of ice at the enemy, dealing (200 of Spell Power) Frost damage and granting you Brain Freeze.
SpellInfo(ebonbolt cd=45 talent=ebonbolt_talent)
Define(evocation 12051)
# Increases your mana regeneration by s1 for 6 seconds.
# Rank 2: Evocation's cooldown is reduced by s1.
SpellInfo(evocation cd=180 duration=6 channel=6)
# Mana regeneration increased by s1.
SpellAddBuff(evocation evocation=1)
Define(fire_blast 108853)
# Blasts the enemy for (72 of Spell Power) Fire damage. Castable while casting other spells.?a231568[ Always deals a critical strike.][]
# Rank 2: Fire Blast always deals a critical strike.
SpellInfo(fire_blast cd=0.5 charge_cd=12 gcd=0 offgcd=1)
Define(fireball 133)
# Throws a fiery ball that causes (59 of Spell Power) Fire damage.
SpellInfo(fireball)
Define(fireblood 265221)
# Removes all poison, disease, curse, magic, and bleed effects and increases your ?a162700[Agility]?a162702[Strength]?a162697[Agility]?a162698[Strength]?a162699[Intellect]?a162701[Intellect][primary stat] by 265226s1*3 and an additional 265226s1 for each effect removed. Lasts 8 seconds.
SpellInfo(fireblood cd=120 gcd=0 offgcd=1)
Define(flamestrike 2120)
# Calls down a pillar of fire, burning all enemies within the area for s1 Fire damage and reducing their movement speed by (57.49999999999999 of Spell Power) for 8 seconds.
SpellInfo(flamestrike duration=8)
# Movement speed slowed by s2.
SpellAddTargetDebuff(flamestrike flamestrike=1)
Define(flurry 44614)
# Unleash a flurry of ice, striking the target s1 times for a total of (31.6 of Spell Power)*m1 Frost damage. Each hit reduces the target's movement speed by 228354s1 for 1 second.rnrnWhile Brain Freeze is active, Flurry applies Winter's Chill, causing your target to take damage from your spells as if it were frozen.
SpellInfo(flurry)
Define(frostbolt 116)
# Launches a bolt of frost at the enemy, causing (51.1 of Spell Power) Frost damage and slowing movement speed by 205708s1 for 15 seconds.
SpellInfo(frostbolt)
Define(frozen_orb 84714)
# Launches an orb of swirling ice up to s1 yards forward which deals up to 20*84721s2 Frost damage to all enemies it passes through. Grants 1 charge of Fingers of Frost when it first damages an enemy.rnrnEnemies damaged by the Frozen Orb are slowed by 205708s1 for 15 seconds.
SpellInfo(frozen_orb cd=60 duration=15 channel=15)
Define(glacial_spike 199786)
# Conjures a massive spike of ice, and merges your current Icicles into it. It impales your target, dealing (320 of Spell Power) damage plus all of the damage stored in your Icicles, and freezes the target in place for 4 seconds. Damage may interrupt the freeze effect.rnrnRequires 5 Icicles to cast.rnrn|cFFFFFFFFPassive:|r Ice Lance no longer launches Icicles.
SpellInfo(glacial_spike talent=glacial_spike_talent)
Define(ice_floes 108839)
# Makes your next Mage spell with a cast time shorter than s2 sec castable while moving. Unaffected by the global cooldown and castable while casting.
SpellInfo(ice_floes cd=20 duration=15 max_stacks=3 gcd=0 offgcd=1 talent=ice_floes_talent)
# Able to move while casting spells.
SpellAddBuff(ice_floes ice_floes=1)
Define(ice_lance 30455)
# Quickly fling a shard of ice at the target, dealing (35 of Spell Power) Frost damage?s56377[, and (35 of Spell Power)*56377m2/100 Frost damage to a second nearby target][].rnrnIce Lance damage is tripled against frozen targets.
SpellInfo(ice_lance)
SpellInfo(fire_blast replaced_by=ice_lance)
Define(ice_nova 157997)
# Causes a whirl of icy wind around the enemy, dealing (45 of Spell Power)*s3/100 Frost damage to the target and (45 of Spell Power) Frost damage to all other enemies within a2 yards, and freezing them in place for 2 seconds.
SpellInfo(ice_nova cd=25 duration=2 talent=ice_nova_talent)
# Frozen.
SpellAddTargetDebuff(ice_nova ice_nova=1)
Define(icy_veins 12472)
# Accelerates your spellcasting for 20 seconds, granting m1 haste and preventing damage from delaying your spellcasts.
SpellInfo(icy_veins cd=180 duration=20)
# Haste increased by w1 and immune to pushback.
SpellAddBuff(icy_veins icy_veins=1)
Define(lights_judgment 255647)
# Call down a strike of Holy energy, dealing <damage> Holy damage to enemies within A1 yards after 3 sec.
SpellInfo(lights_judgment cd=150)
Define(living_bomb 44457)
# The target becomes a Living Bomb, taking 217694o1 Fire damage over 4 seconds, and then exploding to deal an additional (14.000000000000002 of Spell Power) Fire damage to the target and all other enemies within 44461A2 yards.rnrnOther enemies hit by this explosion also become a Living Bomb, but this effect cannot spread further.
SpellInfo(living_bomb cd=12 talent=living_bomb_talent)
Define(meteor 117588)
# Call down a molten meteor on your target, dealing (75 of Spell Power) damage to all enemies within A1 yards of your target.
SpellInfo(meteor cd=60 gcd=0 offgcd=1)
Define(mirror_image 55342)
# Creates s2 copies of you nearby for 40 seconds, which cast spells and attack your enemies.
SpellInfo(mirror_image cd=120 duration=40 talent=mirror_image_talent)
SpellAddBuff(mirror_image mirror_image=1)
Define(nether_tempest 114923)
# Places a Nether Tempest on the target which deals 114923o1 Arcane damage over 12 seconds to the target and 114954m1*12/t1 to all enemies within 10 yards. Limit 1 target.rnrnDamage increased by 36032s1 per Arcane Charge.
SpellInfo(nether_tempest duration=12 tick=1 talent=nether_tempest_talent)
# Deals w1 Arcane damage and an additional w1 Arcane damage to all enemies within 114954A1 yards every t sec.
SpellAddTargetDebuff(nether_tempest nether_tempest=1)
Define(phoenix_flames 257541)
# Hurls a Phoenix that deals (75 of Spell Power) Fire damage to the target and splashes (20 of Spell Power) Fire damage to other nearby enemies. Always deals a critical strike.
SpellInfo(phoenix_flames cd=30 talent=phoenix_flames_talent)
Define(preheat 273331)
# Scorch increases the damage the target takes from your Fire Blast by s1 for 30 seconds.
SpellInfo(preheat channel=0 gcd=0 offgcd=1)
Define(presence_of_mind 205025)
# Causes your next n Arcane Blasts to be instant cast.
SpellInfo(presence_of_mind cd=60 gcd=0 offgcd=1)
# Arcane Blast is instant cast.
SpellAddBuff(presence_of_mind presence_of_mind=1)
Define(pyroblast 11366)
# Hurls an immense fiery boulder that causes (123.9 of Spell Power) Fire damage.
SpellInfo(pyroblast)
Define(pyroclasm 269650)
# Consuming Hot Streak has a s1 chance to make your next non-instant Pyroblast cast within 15 seconds deal 269651s1 additional damage.rnrnMaximum 2 charges.
SpellInfo(pyroclasm channel=0 gcd=0 offgcd=1 talent=pyroclasm_talent)
SpellAddBuff(pyroclasm pyroclasm=1)
Define(quaking_palm 107079)
# Strikes the target with lightning speed, incapacitating them for 4 seconds, and turns off your attack.
SpellInfo(quaking_palm cd=120 duration=4 gcd=1)
# Incapacitated.
SpellAddTargetDebuff(quaking_palm quaking_palm=1)
Define(ray_of_frost 205021)
# Channel an icy beam at the enemy for 5 seconds, dealing (120 of Spell Power) Frost damage every t2 sec and slowing movement by s4. Each time Ray of Frost deals damage, its damage and snare increases by 208141s1.rnrnGenerates s3 charges of Fingers of Frost over its duration.
SpellInfo(ray_of_frost cd=75 duration=5 channel=5 tick=1 talent=ray_of_frost_talent)
# Movement slowed by w1.rnTaking w2 Frost damage every t2 sec.
SpellAddTargetDebuff(ray_of_frost ray_of_frost=1)
Define(rising_death 252346)
# Chance to create multiple potions.
SpellInfo(rising_death gcd=0 offgcd=1)
Define(rule_of_threes 264354)
# When you gain your third Arcane Charge, the cost of your next Arcane Blast or Arcane Missiles is reduced by 264774s1.
SpellInfo(rule_of_threes channel=0 gcd=0 offgcd=1 talent=rule_of_threes_talent)
SpellAddBuff(rule_of_threes rule_of_threes=1)
Define(rune_of_power 116011)
# Places a Rune of Power on the ground for 10 seconds which increases your spell damage by 116014s1 while you stand within 8 yds.
SpellInfo(rune_of_power cd=10 charge_cd=40 duration=10 talent=rune_of_power_talent)
Define(scorch 2948)
# Scorches an enemy for (17.7 of Spell Power) Fire damage. Castable while moving.
SpellInfo(scorch)
Define(shimmer 212653)
# Teleports you A1 yards forward, unless something is in the way. Unaffected by the global cooldown and castable while casting.
SpellInfo(shimmer cd=0.5 charge_cd=20 duration=0.65 channel=0.65 gcd=0 offgcd=1 talent=shimmer_talent)
# Shimmering.
SpellAddBuff(shimmer shimmer=1)
Define(summon_water_elemental 31687)
# Summons a Water Elemental to follow and fight for you.
SpellInfo(summon_water_elemental cd=30)
Define(supernova 157980)
# Pulses arcane energy around the target enemy or ally, dealing (30 of Spell Power) Arcane damage to all enemies within A2 yards, and knocking them upward. A primary enemy target will take s1 increased damage.
SpellInfo(supernova cd=25 talent=supernova_talent)
Define(winters_reach 273347)
# Consuming Brain Freeze has a s2 chance to make your next non-instant Flurry cast within 15 seconds deal an additional s1 damage per hit.
SpellInfo(winters_reach duration=15 channel=15 gcd=0 offgcd=1)
# Damage of your next non-instant Flurry increased by w1 per hit.
SpellAddBuff(winters_reach winters_reach=1)
Define(alexstraszas_fury_talent 11) #22465
# Dragon's Breath always critically strikes and contributes to Hot Streak.
Define(amplification_talent 1) #22458
# When Clearcast, Arcane Missiles fires s2 additional lmissile:missiles;.
Define(arcane_familiar_talent 3) #22464
# Summon a Familiar that attacks your enemies and increases your maximum mana by 210126s1 for 3600 seconds.
Define(arcane_orb_talent 21) #21145
# Launches an Arcane Orb forward from your position, traveling up to 40 yards, dealing (120 of Spell Power) Arcane damage to enemies it passes through.rnrn|cFFFFFFFFGrants 1 Arcane Charge when cast and every time it deals damage.|r
Define(blast_wave_talent 6) #23074
# Causes an explosion around yourself, dealing (45 of Spell Power) Fire damage to all enemies within A1 yards, knocking them back, and reducing movement speed by s2 for 4 seconds.
Define(charged_up_talent 11) #22467
# Immediately grants s1 Arcane Charges.
Define(comet_storm_talent 18) #22473
# Calls down a series of 7 icy comets on and around the target, that deals up to 7*(45 of Spell Power) Frost damage to all enemies within 228601A1 yds of its impacts.
Define(ebonbolt_talent 12) #22469
# Launch a bolt of ice at the enemy, dealing (200 of Spell Power) Frost damage and granting you Brain Freeze.
Define(firestarter_talent 1) #22456
# Your Fireball and Pyroblast spells always deal a critical strike when the target is above s1 health.
Define(flame_patch_talent 16) #22451
# Flamestrike leaves behind a patch of flames which burns enemies within it for 8*(6 of Spell Power) Fire damage over 8 seconds.
Define(freezing_rain_talent 16) #22454
# Frozen Orb makes Blizzard instant cast and increases its damage done by 270232s2 for 12 seconds.
Define(glacial_spike_talent 21) #21634
# Conjures a massive spike of ice, and merges your current Icicles into it. It impales your target, dealing (320 of Spell Power) damage plus all of the damage stored in your Icicles, and freezes the target in place for 4 seconds. Damage may interrupt the freeze effect.rnrnRequires 5 Icicles to cast.rnrn|cFFFFFFFFPassive:|r Ice Lance no longer launches Icicles.
Define(ice_floes_talent 6) #23073
# Makes your next Mage spell with a cast time shorter than s2 sec castable while moving. Unaffected by the global cooldown and castable while casting.
Define(ice_nova_talent 3) #22463
# Causes a whirl of icy wind around the enemy, dealing (45 of Spell Power)*s3/100 Frost damage to the target and (45 of Spell Power) Frost damage to all other enemies within a2 yards, and freezing them in place for 2 seconds.
Define(kindling_talent 19) #21631
# Your Fireball, Pyroblast, Fire Blast, and Phoenix Flames critical strikes reduce the remaining cooldown on Combustion by s1 sec.
Define(living_bomb_talent 18) #22472
# The target becomes a Living Bomb, taking 217694o1 Fire damage over 4 seconds, and then exploding to deal an additional (14.000000000000002 of Spell Power) Fire damage to the target and all other enemies within 44461A2 yards.rnrnOther enemies hit by this explosion also become a Living Bomb, but this effect cannot spread further.
Define(mirror_image_talent 8) #22445
# Creates s2 copies of you nearby for 40 seconds, which cast spells and attack your enemies.
Define(nether_tempest_talent 18) #22474
# Places a Nether Tempest on the target which deals 114923o1 Arcane damage over 12 seconds to the target and 114954m1*12/t1 to all enemies within 10 yards. Limit 1 target.rnrnDamage increased by 36032s1 per Arcane Charge.
Define(overpowered_talent 19) #21630
# Arcane Power now increases damage by 30+s1 and reduces mana costs by 30-s2.
Define(phoenix_flames_talent 12) #22468
# Hurls a Phoenix that deals (75 of Spell Power) Fire damage to the target and splashes (20 of Spell Power) Fire damage to other nearby enemies. Always deals a critical strike.
Define(pyroclasm_talent 20) #22220
# Consuming Hot Streak has a s1 chance to make your next non-instant Pyroblast cast within 15 seconds deal 269651s1 additional damage.rnrnMaximum 2 charges.
Define(ray_of_frost_talent 20) #22309
# Channel an icy beam at the enemy for 5 seconds, dealing (120 of Spell Power) Frost damage every t2 sec and slowing movement by s4. Each time Ray of Frost deals damage, its damage and snare increases by 208141s1.rnrnGenerates s3 charges of Fingers of Frost over its duration.
Define(resonance_talent 10) #22453
# Arcane Barrage deals s1 increased damage per target it hits.
Define(rule_of_threes_talent 2) #22461
# When you gain your third Arcane Charge, the cost of your next Arcane Blast or Arcane Missiles is reduced by 264774s1.
Define(rune_of_power_talent 9) #22447
# Places a Rune of Power on the ground for 10 seconds which increases your spell damage by 116014s1 while you stand within 8 yds.
Define(searing_touch_talent 3) #22462
# Scorch deals s2 increased damage and is a guaranteed Critical Strike when the target is below s1 health.
Define(shimmer_talent 5) #22443
# Teleports you A1 yards forward, unless something is in the way. Unaffected by the global cooldown and castable while casting.
Define(splitting_ice_talent 17) #23176
# Your Ice Lance and Icicles now deal s3 increased damage, and hit a second nearby target for s2 of their damage.rnrnYour Ebonbolt and Glacial Spike also hit a second nearby target for s2 of its damage.
Define(supernova_talent 12) #22470
# Pulses arcane energy around the target enemy or ally, dealing (30 of Spell Power) Arcane damage to all enemies within A2 yards, and knocking them upward. A primary enemy target will take s1 increased damage.
Define(arcane_pummeling_trait 270669)
Define(preheat_trait 273331)
Define(winters_reach_trait 273346)
]]
code = code .. [[
# Mage spells and functions.
SpellRequire(arcane_intellect unusable 1=buff,arcane_intellect)
Define(arcane_affinity 166871)
SpellInfo(arcane_affinity duration=15)
SpellAddBuff(arcane_blast presence_of_mind_buff=0 if_spell=presence_of_mind)
SpellAddBuff(arcane_blast profound_magic_buff=0 itemset=T16_caster itemcount=2 specialization=arcane)
SpellAddBuff(arcane_blast ice_floes_buff=0 if_spell=ice_floes)
Define(arcane_brilliance 1459)
SpellAddBuff(arcane_brilliance arcane_brilliance_buff=1)
Define(arcane_brilliance_buff 1459)
SpellInfo(arcane_brilliance_buff duration=3600)
Define(arcane_charge 114664)
Define(arcane_charge_debuff 36032)
SpellInfo(arcane_charge_debuff duration=15 max_stacks=4)
Define(arcane_instability_buff 166872)
SpellInfo(arcane_instability_buff duration=15)
SpellInfo(arcane_missiles duration=2 travel_time=1 arcanecharges=-1)
SpellRequire(arcane_missiles unusable 1=buff,!arcane_missiles_buff)
SpellAddBuff(arcane_missiles arcane_instability_buff=0 itemset=T17 itemcount=4 specialization=arcane)
SpellAddBuff(arcane_missiles arcane_missiles_buff=-1)
SpellAddBuff(arcane_missiles arcane_power_buff=extend,2 if_spell=overpowered)
Define(arcane_missiles_buff 79683)
SpellInfo(arcane_missiles_buff duration=20 max_stacks=3)
SpellInfo(arcane_orb cd=15)
SpellInfo(arcane_power cd=90 gcd=0)
SpellAddBuff(arcane_power arcane_power_buff=1)
Define(arcane_power_buff 12042)
SpellInfo(arcane_power_buff duration=15)
Define(blazing_speed 108843)
SpellInfo(blazing_speed cd=25 gcd=0 offgcd=1)
SpellInfo(blink cd=15)
SpellInfo(blizzard cd=8 haste=spell)
SpellAddBuff(blizzard ice_floes_buff=0 if_spell=ice_floes)
Define(brain_freeze 44549)
Define(brain_freeze_buff 190446)
SpellInfo(brain_freeze_buff duration=15)
SpellInfo(charged_up arcanecharges=-4)
Define(cinderstorm 198929)
SpellInfo(cinderstorm cd=9)
Define(cold_snap 11958)
SpellInfo(cold_snap cd=180 gcd=0 offgcd=1)
SpellInfo(combustion cd=120 gcd=0)
SpellAddBuff(combustion combustion_buff=1)
Define(combustion_buff 190319)
SpellInfo(combustion_buff duration=10)
SpellInfo(comet_storm cd=30 travel_time=1)
SpellInfo(counterspell cd=24 gcd=0 interrupt=1)
Define(deep_freeze 44572)
SpellInfo(deep_freeze cd=30 interrupt=1)
SpellAddBuff(deep_freeze fingers_of_frost_buff=-1 if_spell=fingers_of_frost)
SpellInfo(dragons_breath cd=20)
SpellInfo(ebonbolt cd=45 tag=main)
SpellAddBuff(ebonbolt brain_freeze_buff=1)
Define(erupting_infernal_core_buff 248147)
SpellInfo(erupting_infernal_core_buff duration=30)
SpellInfo(evocation cd=120 channel=3 haste=spell)
SpellInfo(evocation add_cd=-30 if_spell=improved_evocation)
SpellAddBuff(evocation ice_floes_buff=0 if_spell=ice_floes)
Define(fingers_of_frost_buff 44544)
SpellInfo(fingers_of_frost_buff duration=15 max_stacks=2)
SpellInfo(fingers_of_frost_buff max_stacks=4 itemset=T18 itemcount=4)
SpellInfo(fire_blast gcd=0 offgcd=1 cd=12 charges=1)
SpellInfo(fire_blast cd=10 charges=2 talent=flame_on_talent)
SpellAddBuff(fireball erupting_infernal_core_buff=0)
SpellInfo(flamestrike cd=12)
SpellInfo(flamestrike cd=0 if_spell=improved_flamestrike)
SpellAddBuff(flamestrike ice_floes_buff=0 if_spell=ice_floes)
SpellAddTargetDebuff(flamestrike flamestrike_debuff=1)
SpellAddBuff(flamestrike hot_streak_buff=0)
Define(flamestrike_debuff 2120)
SpellInfo(flamestrike_debuff duration=8 haste=spell tick=2)
SpellInfo(flurry mana=4)
Define(freeze 33395)
Define(frost_bomb 112948)
SpellAddTargetDebuff(frost_bomb frost_bomb_debuff=1)
Define(frost_bomb_debuff 112948)
SpellInfo(frost_bomb_debuff duration=12)
Define(frost_nova 122)
SpellInfo(frostbolt travel_time=1)
SpellAddBuff(frostbolt ice_floes_buff=0 if_spell=ice_floes)
Define(frostfire_bolt 44614)
SpellInfo(frostfire_bolt travel_time=1)
SpellAddBuff(frostfire_bolt brain_freeze_buff=0 if_spell=brain_freeze)
SpellAddBuff(frostfire_bolt ice_floes_buff=0 if_spell=ice_floes)
SpellInfo(frozen_orb cd=60)
SpellAddBuff(frozen_orb frozen_mass_buff=1 itemset=T20 itemcount=2)
Define(frozen_orb_debuff 84721)
SpellInfo(frozen_orb_debuff duration=2)
Define(frozen_mass_buff 242253)
SpellInfo(frozen_mass_buff duration=10)
Define(frozen_touch 205030)
SpellInfo(frozen_touch cd=30)
SpellAddBuff(frozen_touch fingers_of_frost_buff=2)
SpellInfo(glacial_spike mana=1 unusable=1)
SpellRequire(glacial_spike unusable 0=buff,icicles_buff,5)
SpellAddBuff(glacial_spike icicles_buff=0)
Define(heating_up_buff 48107)
SpellInfo(heating_up_buff duration=10)
Define(hot_streak_buff 48108)
Define(ice_barrier 11426)
SpellInfo(ice_barrier cd=25)
SpellAddBuff(ice_floes ice_floes_buff=1)
Define(ice_floes_buff 108839)
SpellInfo(ice_floes_buff duration=15)
SpellInfo(ice_lance travel_time=1.3) # maximum observed travel time with a bit of padding
SpellAddBuff(ice_lance fingers_of_frost_buff=-1 if_spell=fingers_of_frost)
SpellAddBuff(ice_lance icy_veins_buff=extend,2 if_spell=thermal_void)
Define(ice_shard_buff 166869)
SpellInfo(ice_shard_buff duration=10 max_stacks=10)
Define(icicles_buff 205473)
SpellInfo(icicles_buff duration=60)
Define(icy_hand 220817)
SpellInfo(icy_veins cd=180)
SpellInfo(icy_veins add_cd=-90 itemset=T14 itemcount=4)
SpellAddBuff(icy_veins icy_veins_buff=1)
Define(icy_veins_buff 12472)
SpellInfo(icy_veins_buff duration=20)
Define(ignite_debuff 12654)
SpellInfo(ignite_debuff duration=5 tick=1)
Define(improved_evocation 157614)
Define(improved_flamestrike 157621)
Define(incanters_flow_buff 116267)
SpellInfo(incanters_flow_buff duration=25 max_stacks=5)
Define(inferno_blast 108853)
SpellInfo(inferno_blast cd=8)
SpellInfo(inferno_blast add_cd=-2 itemset=T17 itemcount=2)
Define(kaelthas_ultimate_ability_buff 209455)
SpellInfo(living_bomb gcd=1)
SpellAddTargetDebuff(living_bomb living_bomb_debuff=1)
Define(living_bomb_debuff 44457)
SpellInfo(living_bomb duration=12 haste=spell tick=3)
Define(mark_of_doom_debuff 184073)
SpellInfo(mark_of_doom_debuff duration=10)
Define(meteor 153561)
SpellInfo(meteor cd=45 travel_time=1)
SpellInfo(mirror_image cd=120)
SpellAddTargetDebuff(nether_tempest nether_tempest_debuff=1)
Define(nether_tempest_debuff 114923)
SpellInfo(nether_tempest_debuff duration=12 haste=spell tick=1)
Define(overpowered 155147)
Define(pet_freeze 33395)
Define(pet_water_jet 135029)
Define(pet_water_jet_debuff 135029)
Define(phoenixs_flames 194466)
Define(polymorph 118)
SpellAddBuff(polymorph presence_of_mind_buff=0)
SpellAddTargetDebuff(polymorph polymorph_debuff=1)
Define(polymorph_debuff 118)
SpellInfo(polymorph_debuff duration=50)
Define(potent_flames_buff 145254)
SpellInfo(potent_flames_buff duration=5 max_stacks=5)
SpellInfo(presence_of_mind cd=90 gcd=0)
SpellAddBuff(presence_of_mind presence_of_mind_buff=1)
Define(presence_of_mind_buff 205025)
Define(profound_magic_buff 145252)
SpellInfo(profound_magic_buff duration=10 max_stacks=4)
SpellInfo(pyroblast travel_time=1)
SpellInfo(pyroblast damage=FirePyroblastHitDamage specialization=fire)
SpellAddBuff(pyroblast ice_floes_buff=0 if_spell=ice_floes)
SpellAddBuff(pyroblast pyroblast_buff=0)
SpellAddTargetDebuff(pyroblast pyroblast_debuff=1)
SpellAddBuff(pyroblast hot_streak_buff=0)
SpellAddBuff(pyroblast erupting_infernal_core_buff=0)
Define(pyroblast_buff 48108)
SpellInfo(pyroblast_buff duration=15)
Define(pyroblast_debuff 11366)
SpellInfo(pyroblast_debuff duration=18 haste=spell tick=3)
Define(pyromaniac_buff 166868)
SpellInfo(pyromaniac_buff duration=4)
Define(quickening_buff 198924)
SpellAddBuff(arcane_barrage quickening_buff=0)
SpellInfo(ray_of_frost cd=60 channel=10 tag=main)
SpellInfo(rune_of_power buff_totem=rune_of_power_buff duration=180 max_totems=1 totem=1)
SpellAddBuff(rune_of_power ice_floes_buff=0 if_spell=ice_floes)
SpellAddBuff(rune_of_power presence_of_mind_buff=0 if_spell=presence_of_mind)
Define(rune_of_power_buff 116014)
SpellInfo(scorch travel_time=1)
Define(shard_of_the_exodar_warp 207970)
Define(spellsteal 30449)
Define(summon_arcane_familiar 205022)
SpellInfo(summon_arcane_familiar cd=10)
Define(t18_class_trinket 124516)
Define(temporal_displacement_debuff 80354)
SpellInfo(temporal_displacement_debuff duration=600)
Define(thermal_void 155149)
Define(time_warp 80353)
SpellInfo(time_warp cd=300 gcd=0)
SpellAddBuff(time_warp time_warp_buff=1)
SpellAddDebuff(time_warp temporal_displacement_debuff=1)
Define(time_warp_buff 80353)
SpellInfo(time_warp_buff duration=40)
Define(water_elemental 31687)
SpellInfo(water_elemental cd=60)
SpellInfo(water_elemental unusable=1 talent=lonely_winter_talent)
Define(water_elemental_freeze 33395)
SpellInfo(water_elemental_freeze cd=25 gcd=0 shared_cd=water_elemental_fingers_of_frost)
SpellInfo(water_elemental_freeze unusable=1 talent=lonely_winter_talent)
SpellAddBuff(water_elemental_freeze fingers_of_frost_buff=1 if_spell=fingers_of_frost)
Define(water_elemental_water_jet 135029)
SpellInfo(water_elemental_water_jet cd=25 gcd=0 shared_cd=water_elemental_fingers_of_frost)
SpellInfo(water_elemental_water_jet unusable=1 talent=lonely_winter_talent)
SpellAddBuff(water_elemental_water_jet brain_freeze_buff=1 itemset=T18 itemcount=2)
SpellAddTargetDebuff(water_elemental_water_jet water_elemental_water_jet_debuff=1)
Define(water_elemental_water_jet_debuff 135029)
SpellInfo(water_elemental_water_jet_debuff duration=4)
SpellInfo(water_elemental_water_jet_debuff add_duration=10 itemset=T18 itemcount=4)
Define(winters_chill_debuff 157997) # TODO ???
# Talents
Define(blazing_soul_talent 4)
Define(bone_chilling_talent 1)
Define(chain_reaction_talent 11)
Define(chrono_shift_talent 13)
Define(conflagration_talent 17)
Define(flame_on_talent 10)
Define(frenetic_speed_talent 13)
Define(frigid_winds_talent 13)
Define(frozen_touch_talent 10)
Define(glacial_insulation_talent 4)
Define(ice_ward_talent 14)
Define(incanters_flow_talent 7)
Define(lonely_winter_talent 2)
Define(mana_shield_talent 4)
Define(meteor_talent 21)
Define(pyromaniac_talent 2)
Define(reverberate_talent 16)
Define(ring_of_frost_talent 15)
Define(rule_of_threes_talent 2)
Define(slipstream_talent 6)
Define(thermal_void_talent 19)
Define(time_anomaly_talent 20)
Define(touch_of_the_magi_talent 17)
# Artifacts
Define(mark_of_aluneth 210726)
SpellInfo(mark_of_aluneth cd=60)
Define(mark_of_aluneth_debuff 210726) # ???
Define(phoenix_reborn 215773)
# Legendary items
Define(lady_vashjs_grasp 132411)
Define(rhonins_assaulting_armwraps_buff 208081)
Define(shard_of_the_exodar 132410)
Define(zannesu_journey_buff 226852)
SpellAddBuff(blizzard zannesu_journey_buff=-1)
# Non-default tags for OvaleSimulationCraft.
SpellInfo(arcane_orb tag=shortcd)
SpellInfo(arcane_power tag=cd)
SpellInfo(blink tag=shortcd)
SpellInfo(cone_of_cold tag=shortcd)
SpellInfo(dragons_breath tag=shortcd)
SpellInfo(frost_bomb tag=shortcd)
SpellInfo(ice_floes tag=shortcd)
SpellInfo(rune_of_power tag=shortcd)
### Pyroblast
AddFunction FirePyroblastHitDamage asValue=1 { 2.423 * Spellpower() * { BuffPresent(pyroblast_buff asValue=1) * 1.25 } }
]]
OvaleScripts:RegisterScript("MAGE", nil, name, desc, code, "include")
end
| gpl-2.0 |
Servius/tfa-sw-weapons-repository | Backups_Reworks/tfa_mega_rework/lua/weapons/tfa_swch_ll30_rework/shared.lua | 1 | 3368 | if ( SERVER ) then
AddCSLuaFile( "shared.lua" )
end
if ( CLIENT ) then
SWEP.PrintName = "LL-30"
SWEP.Author = "TFA, Servius"
SWEP.ViewModelFOV = 70
SWEP.Slot = 1
SWEP.SlotPos = 5
SWEP.WepSelectIcon = surface.GetTextureID("HUD/killicons/LL30")
killicon.Add( "weapon_752_ll30", "HUD/killicons/LL30", Color( 255, 80, 0, 255 ) )
end
SWEP.HoldType = "pistol"
SWEP.Base = "tfa_3dscoped_base"
SWEP.Category = "TFA Star Wars"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.ViewModel = "models/weapons/v_LL30.mdl"
SWEP.WorldModel = "models/weapons/w_LL30.mdl"
SWEP.Primary.Sound = Sound ("weapons/LL30_fire.wav");
SWEP.Primary.ReloadSound = Sound ("weapons/LL30_reload.wav");
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.Recoil = 0.5
SWEP.Primary.Damage = 50
SWEP.Primary.NumShots = 1
SWEP.Primary.Spread = 0.0125
SWEP.Primary.IronAccuracy = .001
SWEP.Primary.ClipSize = 25
SWEP.Primary.RPM = 60/0.2
SWEP.Primary.DefaultClip = 75
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "ar2"
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.IronSightsPos = Vector(-3.681, -6.755, 2.869)
SWEP.IronSightsAng = Vector(0, 0, 0)
SWEP.VElements = {
["element_name"] = { type = "Model", model = "models/rtcircle.mdl", bone = "Box01", rel = "", pos = Vector(-2.609, -2.51, -0.04), angle = Angle(0, 180, 90), size = Vector(0.259, 0.259, 0.259), color = Color(255, 255, 255, 255), surpresslightning = false, material = "!tfa_rtmaterial", skin = 0, bodygroup = {} }
}
SWEP.IronSightsSensitivity = 0.25 --Useful for a RT scope. Change this to 0.25 for 25% sensitivity. This is if normal FOV compenstaion isn't your thing for whatever reason, so don't change it for normal scopes.
SWEP.DoProceduralReload = true
SWEP.ProceduralReloadTime = 2
----Swft Base Code
SWEP.TracerCount = 1
SWEP.MuzzleFlashEffect = ""
SWEP.TracerName = "effect_sw_laser_red"
SWEP.Secondary.IronFOV = 70
SWEP.Primary.KickUp = 0.2
SWEP.Primary.KickDown = 0.1
SWEP.Primary.KickHorizontal = 0.1
SWEP.Primary.KickRight = 0.1
SWEP.DisableChambering = true
SWEP.ImpactDecal = "FadingScorch"
SWEP.ImpactEffect = "effect_sw_impact" --Impact Effect
SWEP.RunSightsPos = Vector(2.127, 0, 1.355)
SWEP.RunSightsAng = Vector(-15.775, 10.023, -5.664)
SWEP.BlowbackEnabled = true
SWEP.BlowbackVector = Vector(0,-3,0.1)
SWEP.Blowback_Shell_Enabled = false
SWEP.Blowback_Shell_Effect = ""
SWEP.ThirdPersonReloadDisable=false
SWEP.Primary.DamageType = DMG_SHOCK
SWEP.DamageType = DMG_SHOCK
--3dScopedBase stuff
SWEP.RTMaterialOverride = 0
SWEP.RTScopeAttachment = -1
SWEP.Scoped_3D = true
SWEP.ScopeReticule = "scope/gdcw_green_nobar"
SWEP.Secondary.ScopeZoom = 12
SWEP.ScopeReticule_Scale = {2,2}
SWEP.Secondary.UseACOG = false --Overlay option
SWEP.Secondary.UseMilDot = false --Overlay option
SWEP.Secondary.UseSVD = false --Overlay option
SWEP.Secondary.UseParabolic = false --Overlay option
SWEP.Secondary.UseElcan = false --Overlay option
SWEP.Secondary.UseGreenDuplex = false --Overlay option
if surface then
SWEP.Secondary.ScopeTable = nil --[[
{
scopetex = surface.GetTextureID("scope/gdcw_closedsight"),
reticletex = surface.GetTextureID("scope/gdcw_acogchevron"),
dottex = surface.GetTextureID("scope/gdcw_acogcross")
}
]]--
end
DEFINE_BASECLASS( SWEP.Base ) | apache-2.0 |
SimCMinMax/EasyRaid | HeroRotation_DemonHunter/Vengeance.lua | 1 | 15395 | --- ============================ HEADER ============================
--- ======= LOCALIZE =======
-- Addon
local addonName, addonTable = ...
-- HeroDBC
local DBC = HeroDBC.DBC
-- HeroLib
local HL = HeroLib
local Cache = HeroCache
local Unit = HL.Unit
local Player = Unit.Player
local Target = Unit.Target
local Pet = Unit.Pet
local Spell = HL.Spell
local Item = HL.Item
-- HeroRotation
local HR = HeroRotation
local AoEON = HR.AoEON
local CDsON = HR.CDsON
local Cast = HR.Cast
local CastSuggested = HR.CastSuggested
-- lua
--- ============================ CONTENT ===========================
--- ======= APL LOCALS =======
-- luacheck: max_line_length 9999
-- Define S/I for spell and item arrays
local S = Spell.DemonHunter.Vengeance
local I = Item.DemonHunter.Vengeance
-- Create table to exclude above trinkets from On Use function
local OnUseExcludes = {
I.PulsatingStoneheart:ID(),
I.DarkmoonDeckIndomitable:ID(),
}
-- Rotation Var
local ShouldReturn -- Used to get the return string
local SoulFragments, SoulFragmentsAdjusted, LastSoulFragmentAdjustment
local IsInMeleeRange, IsInAoERange
local ActiveMitigationNeeded
local IsTanking
local Enemies8yMelee
local EnemiesCount8yMelee
local VarBrandBuild = (S.AgonizingFlames:IsAvailable() and S.BurningAlive:IsAvailable() and S.CharredFlesh:IsAvailable())
local RazelikhsDefilementEquipped = Player:HasLegendaryEquipped(27)
-- GUI Settings
local Everyone = HR.Commons.Everyone
local Settings = {
General = HR.GUISettings.General,
Commons = HR.GUISettings.APL.DemonHunter.Commons,
Vengeance = HR.GUISettings.APL.DemonHunter.Vengeance
}
HL:RegisterForEvent(function()
VarBrandBuild = (S.AgonizingFlames:IsAvailable() and S.BurningAlive:IsAvailable() and S.CharredFlesh:IsAvailable())
end, "PLAYER_SPECIALIZATION_CHANGED", "PLAYER_TALENT_UPDATE")
HL:RegisterForEvent(function()
RazelikhsDefilementEquipped = Player:HasLegendaryEquipped(27)
end, "PLAYER_EQUIPMENT_CHANGED")
-- Soul Fragments function taking into consideration aura lag
local function UpdateSoulFragments()
SoulFragments = Player:BuffStack(S.SoulFragments)
-- Casting Spirit Bomb or Soul Cleave immediately updates the buff
if S.SpiritBomb:TimeSinceLastCast() < Player:GCD()
or S.SoulCleave:TimeSinceLastCast() < Player:GCD() then
SoulFragmentsAdjusted = 0
return
end
-- Check if we have cast Fracture or Shear within the last GCD and haven't "snapshot" yet
if SoulFragmentsAdjusted == 0 then
if S.Fracture:IsAvailable() then
if S.Fracture:TimeSinceLastCast() < Player:GCD() and S.Fracture.LastCastTime ~= LastSoulFragmentAdjustment then
SoulFragmentsAdjusted = math.min(SoulFragments + 2, 5)
LastSoulFragmentAdjustment = S.Fracture.LastCastTime
end
else
if S.Shear:TimeSinceLastCast() < Player:GCD() and S.Fracture.Shear ~= LastSoulFragmentAdjustment then
SoulFragmentsAdjusted = math.min(SoulFragments + 1, 5)
LastSoulFragmentAdjustment = S.Shear.LastCastTime
end
end
else
-- If we have a soul fragement "snapshot", see if we should invalidate it based on time
if S.Fracture:IsAvailable() then
if S.Fracture:TimeSinceLastCast() >= Player:GCD() then
SoulFragmentsAdjusted = 0
end
else
if S.Shear:TimeSinceLastCast() >= Player:GCD() then
SoulFragmentsAdjusted = 0
end
end
end
-- If we have a higher Soul Fragment "snapshot", use it instead
if SoulFragmentsAdjusted == nil then SoulFragmentsAdjusted = 0 end
if SoulFragmentsAdjusted > SoulFragments then
SoulFragments = SoulFragmentsAdjusted
elseif SoulFragmentsAdjusted > 0 then
-- Otherwise, the "snapshot" is invalid, so reset it if it has a value
-- Relevant in cases where we use a generator two GCDs in a row
SoulFragmentsAdjusted = 0
end
end
-- Melee Is In Range w/ Movement Handlers
local function UpdateIsInMeleeRange()
if S.Felblade:TimeSinceLastCast() < Player:GCD()
or S.InfernalStrike:TimeSinceLastCast() < Player:GCD() then
IsInMeleeRange = true
IsInAoERange = true
return
end
IsInMeleeRange = Target:IsInMeleeRange(5)
IsInAoERange = IsInMeleeRange or EnemiesCount8yMelee > 0
end
local function Precombat()
-- flask
-- augmentation
-- food
-- snapshot_stats
-- potion
if I.PotionofPhantomFire:IsReady() and Settings.Commons.Enabled.Potions then
if Cast(I.PotionofPhantomFire, nil, Settings.Commons.DisplayStyle.Potions) then return "potion_of_unbridled_fury 2"; end
end
-- First attacks
if S.InfernalStrike:IsCastable() and not IsInMeleeRange then
if Cast(S.InfernalStrike, nil, nil, not Target:IsInRange(30)) then return "infernal_strike 6"; end
end
if S.Fracture:IsCastable() and IsInMeleeRange then
if Cast(S.Fracture) then return "fracture 8"; end
end
end
local function Defensives()
-- Demon Spikes
if S.DemonSpikes:IsCastable() and Player:BuffDown(S.DemonSpikesBuff) and Player:BuffDown(S.MetamorphosisBuff) then
if S.DemonSpikes:ChargesFractional() > 1.9 then
if Cast(S.DemonSpikes, Settings.Vengeance.OffGCDasOffGCD.DemonSpikes) then return "demon_spikes defensives (Capped)"; end
elseif (ActiveMitigationNeeded or Player:HealthPercentage() <= Settings.Vengeance.DemonSpikesHealthThreshold) then
if Cast(S.DemonSpikes, Settings.Vengeance.OffGCDasOffGCD.DemonSpikes) then return "demon_spikes defensives (Danger)"; end
end
end
if I.DarkmoonDeckIndomitable:IsEquipped() and I.DarkmoonDeckIndomitable:IsReady() and Settings.Commons.Enabled.Trinkets and Player:HealthPercentage() <= 75 then
if Cast(I.DarkmoonDeckIndomitable, nil, Settings.Commons.DisplayStyle.Trinkets) then return "darkmoon_deck_indomitable defensives"; end
end
-- Metamorphosis,if=!buff.metamorphosis.up&(!covenant.venthyr.enabled|!dot.sinful_brand.ticking)|target.time_to_die<15
if S.Metamorphosis:IsCastable() and Player:HealthPercentage() <= Settings.Vengeance.MetamorphosisHealthThreshold and (Player:BuffDown(S.MetamorphosisBuff) and (not S.SinfulBrand:IsAvailable() or Target:DebuffDown(S.SinfulBrandDebuff)) or Target:TimeToDie() < 15) then
if Cast(S.Metamorphosis, nil, Settings.Commons.DisplayStyle.Metamorphosis) then return "metamorphosis defensives"; end
end
-- Fiery Brand
if S.FieryBrand:IsCastable() and Target:DebuffDown(S.FieryBrandDebuff) and (ActiveMitigationNeeded or Player:HealthPercentage() <= Settings.Vengeance.FieryBrandHealthThreshold) then
if Cast(S.FieryBrand, Settings.Vengeance.OffGCDasOffGCD.FieryBrand, nil, not Target:IsSpellInRange(S.FieryBrand)) then return "fiery_brand defensives"; end
end
-- Manual add: Door of Shadows with Enduring Gloom for the absorb shield
if S.DoorofShadows:IsCastable() and S.EnduringGloom:IsAvailable() and IsTanking then
if Cast(S.DoorofShadows, nil, Settings.Commons.DisplayStyle.Covenant) then return "door_of_shadows defensives"; end
end
end
local function Brand()
-- fiery_brand
if S.FieryBrand:IsCastable() and IsInMeleeRange then
if Cast(S.FieryBrand, Settings.Vengeance.OffGCDasOffGCD.FieryBrand, nil, not Target:IsSpellInRange(S.FieryBrand)) then return "fiery_brand 92"; end
end
-- immolation_aura,if=dot.fiery_brand.ticking
if S.ImmolationAura:IsCastable() and IsInMeleeRange and (Target:DebuffUp(S.FieryBrandDebuff)) then
if Cast(S.ImmolationAura) then return "immolation_aura 88"; end
end
end
local function Cooldowns()
-- potion
if I.PotionofPhantomFire:IsReady() and Settings.Commons.Enabled.Potions then
if Cast(I.PotionofPhantomFire, nil, Settings.Commons.DisplayStyle.Potions) then return "potion_of_unbridled_fury 60"; end
end
-- use_items
if Settings.Commons.Enabled.Trinkets then
local TrinketToUse = Player:GetUseableTrinkets(OnUseExcludes)
if TrinketToUse then
if Cast(TrinketToUse, nil, Settings.Commons.DisplayStyle.Trinkets) then return "Generic use_items for " .. TrinketToUse:Name(); end
end
end
-- sinful_brand,if=!dot.sinful_brand.ticking
if S.SinfulBrand:IsCastable() and (Target:BuffDown(S.SinfulBrandDebuff)) then
if Cast(S.SinfulBrand, nil, Settings.Commons.DisplayStyle.Covenant, not Target:IsSpellInRange(S.SinfulBrand)) then return "sinful_brand 74"; end
end
-- the_hunt
if S.TheHunt:IsCastable() then
if Cast(S.TheHunt, nil, Settings.Commons.DisplayStyle.Covenant, not Target:IsSpellInRange(S.TheHunt)) then return "the_hunt 76"; end
end
-- fodder_to_the_flame
if S.FoddertotheFlame:IsCastable() then
if Cast(S.FoddertotheFlame, nil, Settings.Commons.DisplayStyle.Covenant) then return "fodder_to_the_flame 78"; end
end
-- elysian_decree
if S.ElysianDecree:IsCastable() then
if Cast(S.ElysianDecree, nil, Settings.Commons.DisplayStyle.Covenant) then return "elysian_decree 80"; end
end
end
local function Normal()
-- infernal_strike
if S.InfernalStrike:IsCastable() and (not Settings.Vengeance.ConserveInfernalStrike or S.InfernalStrike:ChargesFractional() > 1.9) and (S.InfernalStrike:TimeSinceLastCast() > 2) then
if Cast(S.InfernalStrike, Settings.Vengeance.OffGCDasOffGCD.InfernalStrike, nil, not Target:IsInRange(30)) then return "infernal_strike 24"; end
end
-- bulk_extraction
if S.BulkExtraction:IsCastable() then
if Cast(S.BulkExtraction) then return "bulk_extraction 26"; end
end
-- spirit_bomb,if=((buff.metamorphosis.up&talent.fracture.enabled&soul_fragments>=3)|soul_fragments>=4)
if S.SpiritBomb:IsReady() and IsInAoERange and ((Player:BuffUp(S.Metamorphosis) and S.Fracture:IsAvailable() and SoulFragments >= 3) or SoulFragments >= 4) then
if Cast(S.SpiritBomb) then return "spirit_bomb 28"; end
end
-- fel_devastation
-- Manual add: ,if=talent.demonic.enabled&!buff.metamorphosis.up|!talent.demonic.enabled
-- This way we don't waste potential Meta uptime
if S.FelDevastation:IsReady() and (S.Demonic:IsAvailable() and Player:BuffDown(S.Metamorphosis) or not S.Demonic:IsAvailable()) then
if Cast(S.FelDevastation, Settings.Vengeance.GCDasOffGCD.FelDevastation, nil, not Target:IsInMeleeRange(20)) then return "fel_devastation 34"; end
end
-- soul_cleave,if=((talent.spirit_bomb.enabled&soul_fragments=0)|!talent.spirit_bomb.enabled)&((talent.fracture.enabled&fury>=55)|(!talent.fracture.enabled&fury>=70)|cooldown.fel_devastation.remains>target.time_to_die|(buff.metamorphosis.up&((talent.fracture.enabled&fury>=35)|(!talent.fracture.enabled&fury>=50))))
if S.SoulCleave:IsReady() and (((S.SpiritBomb:IsAvailable() and SoulFragments == 0) or not S.SpiritBomb:IsAvailable()) and ((S.Fracture:IsAvailable() and Player:Fury() >= 55) or (not S.Fracture:IsAvailable() and Player:Fury() >= 70) or S.FelDevastation:CooldownRemains() > Target:TimeToDie() or (Player:BuffUp(S.MetamorphosisBuff) and ((S.Fracture:IsAvailable() and Player:Fury() >= 35) or (not S.Fracture:IsAvailable() and Player:Fury() >= 50))))) then
if Cast(S.SoulCleave, nil, nil, not Target:IsSpellInRange(S.SoulCleave)) then return "soul_cleave 36"; end
end
-- immolation_aura,if=((variable.brand_build&cooldown.fiery_brand.remains>10)|!variable.brand_build)&fury<=90
if S.ImmolationAura:IsCastable() and (((VarBrandBuild and S.FieryBrand:CooldownRemains() > 10) or not VarBrandBuild) and Player:Fury() <= 90) then
if Cast(S.ImmolationAura) then return "immolation_aura 38"; end
end
-- felblade,if=fury<=60
if S.Felblade:IsCastable() and (Player:Fury() <= 60) then
if Cast(S.Felblade, nil, nil, not Target:IsSpellInRange(S.Felblade)) then return "felblade 40"; end
end
-- fracture,if=((talent.spirit_bomb.enabled&soul_fragments<=3)|(!talent.spirit_bomb.enabled&((buff.metamorphosis.up&fury<=55)|(buff.metamorphosis.down&fury<=70))))
if S.Fracture:IsCastable() and IsInMeleeRange and ((S.SpiritBomb:IsAvailable() and SoulFragments <= 3) or (not S.SpiritBomb:IsAvailable() and ((Player:BuffUp(S.MetamorphosisBuff) and Player:Fury() <= 55) or (Player:BuffDown(S.MetamorphosisBuff) and Player:Fury() <= 70)))) then
if Cast(S.Fracture) then return "fracture 42"; end
end
-- sigil_of_flame,if=!(covenant.kyrian.enabled&runeforge.razelikhs_defilement)
if S.SigilofFlame:IsCastable() and (IsInAoERange or not S.ConcentratedSigils:IsAvailable()) and Target:DebuffRemains(S.SigilofFlameDebuff) <= 3 and (not (Player:Covenant() == "Kyrian" and RazelikhsDefilementEquipped)) then
if S.ConcentratedSigils:IsAvailable() then
if Cast(S.SigilofFlame, nil, nil, not IsInAoERange) then return "sigil_of_flame 44 (Concentrated)"; end
else
if Cast(S.SigilofFlame, nil, nil, not Target:IsInRange(30)) then return "sigil_of_flame 44 (Normal)"; end
end
end
-- shear
if S.Shear:IsReady() and IsInMeleeRange then
if Cast(S.Shear) then return "shear 46"; end
end
-- Manually adding Fracture as a fallback filler
if S.Fracture:IsCastable() and IsInMeleeRange then
if Cast(S.Fracture) then return "fracture 48"; end
end
-- throw_glaive
if S.ThrowGlaive:IsCastable() then
if Cast(S.ThrowGlaive, nil, nil, not Target:IsSpellInRange(S.ThrowGlaive)) then return "throw_glaive 50 (OOR)"; end
end
end
-- APL Main
local function APL()
Enemies8yMelee = Player:GetEnemiesInMeleeRange(8)
if (AoEON()) then
EnemiesCount8yMelee = #Enemies8yMelee
else
EnemiesCount8yMelee = 1
end
UpdateSoulFragments()
UpdateIsInMeleeRange()
ActiveMitigationNeeded = Player:ActiveMitigationNeeded()
IsTanking = Player:IsTankingAoE(8) or Player:IsTanking(Target)
if Everyone.TargetIsValid() then
-- Precombat
if not Player:AffectingCombat() then
local ShouldReturn = Precombat(); if ShouldReturn then return ShouldReturn; end
end
-- auto_attack
-- variable,name=brand_build,value=talent.agonizing_flames.enabled&talent.burning_alive.enabled&talent.charred_flesh.enabled
-- Moved to Precombat, as talents can't change once in combat, so no need to continually check
-- disrupt (Interrupts)
local ShouldReturn = Everyone.Interrupt(10, S.Disrupt, Settings.Commons.OffGCDasOffGCD.Disrupt, false); if ShouldReturn then return ShouldReturn; end
-- consume_magic
-- throw_glaive,if=buff.fel_bombardment.stack=5&(buff.immolation_aura.up|!buff.metamorphosis.up)
if S.ThrowGlaive:IsCastable() and (Player:BuffStack(S.FelBombardmentBuff) == 5 and (Player:BuffUp(S.ImmolationAuraBuff) or Player:BuffDown(S.MetamorphosisBuff))) then
if Cast(S.ThrowGlaive, nil, nil, not Target:IsSpellInRange(S.ThrowGlaive)) then return "throw_glaive fel_bombardment"; end
end
-- call_action_list,name=brand,if=variable.brand_build
if VarBrandBuild then
local ShouldReturn = Brand(); if ShouldReturn then return ShouldReturn; end
end
-- call_action_list,name=defensives
if (IsTanking) then
local ShouldReturn = Defensives(); if ShouldReturn then return ShouldReturn; end
end
-- call_action_list,name=cooldowns
if (CDsON()) then
local ShouldReturn = Cooldowns(); if ShouldReturn then return ShouldReturn; end
end
-- call_action_list,name=normal
local ShouldReturn = Normal(); if ShouldReturn then return ShouldReturn; end
-- If nothing else to do, show the Pool icon
if HR.CastAnnotated(S.Pool, false, "WAIT") then return "Wait/Pool Resources"; end
end
end
local function Init()
end
HR.SetAPL(581, APL, Init);
| gpl-3.0 |
Servius/tfa-sw-weapons-repository | Live Addons/servius_uploader_legacy/tfa_swrp_expanded_weapons_pack/lua/weapons/tfa_swch_dc15a_memes_fray/shared.lua | 1 | 2810 |
if ( SERVER ) then
AddCSLuaFile( "shared.lua" )
end
if ( CLIENT ) then
SWEP.PrintName = "DC-15A Memes"
SWEP.Author = "TFA"
SWEP.ViewModelFOV = 50
SWEP.Slot = 2
SWEP.SlotPos = 3
SWEP.WepSelectIcon = surface.GetTextureID("HUD/killicons/DC15A")
killicon.Add( "weapon_752_dc15a", "HUD/killicons/DC15A", Color( 255, 80, 0, 255 ) )
end
SWEP.HoldType = "ar2"
SWEP.Base = "tfa_swsft_base_servius"
SWEP.Category = "TFA Fray SWEP's"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.HoldType = "ar2"
SWEP.ViewModelFOV = 56
SWEP.ViewModelFlip = false
SWEP.ViewModel = "models/weapons/cstrike/c_snip_awp.mdl"
SWEP.WorldModel = "models/weapons/w_irifle.mdl"
SWEP.ShowViewModel = true
SWEP.ShowWorldModel = false
SWEP.UseHands = true
SWEP.ViewModelBoneMods = {
["v_weapon.awm_parent"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["ValveBiped.Bip01_L_Clavicle"] = { scale = Vector(1, 1, 1), pos = Vector(0.338, 2.914, 0.18), angle = Angle(0, 0, 0) },
["ValveBiped.Bip01_L_Finger0"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 1.447, 0) }
}
SWEP.Primary.Sound = Sound ("weapons/dc15a/DC15A_fire.ogg");
SWEP.Primary.ReloadSound = Sound ("weapons/shared/standard_reload.ogg");
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.Recoil = 0.5
SWEP.Primary.Damage = 25
SWEP.Primary.NumShots = 1
SWEP.Primary.Spread = 0.0125
SWEP.Primary.IronAccuracy = .005 -- Ironsight accuracy, should be the same for shotguns
SWEP.Primary.ClipSize = 50
SWEP.Primary.RPM = 60/0.175
SWEP.Primary.DefaultClip = 150
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "ar2"
SWEP.TracerName = "effect_sw_laser_blue"
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.Secondary.IronFOV = 70
SWEP.IronSightsPos = Vector(-7.401, -18.14, 2.099)
SWEP.IronSightsAng = Vector(-1.89, 0.282, 0)
SWEP.VElements = {
["element_name"] = { type = "Model", model = "models/weapons/w_dc15a_neue2_memes.mdl", bone = "v_weapon.awm_parent", rel = "", pos = Vector(-0.011, -2.924, -5.414), angle = Angle(180, 0, -89.595), size = Vector(0.95, 0.95, 0.95), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.WElements = {
["element_name2"] = { type = "Model", model = "models/weapons/w_dc15a_neue2_memes.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(8.279, 0.584, -4.468), angle = Angle(0, -90, 160.731), size = Vector(0.884, 0.884, 0.884), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.BlowbackVector = Vector(0,-3,0.025)
SWEP.Blowback_Only_Iron = false
SWEP.DoProceduralReload = true
SWEP.ProceduralReloadTime = 2.5 | apache-2.0 |
cwarden/mysql-proxy | examples/tutorial-states.lua | 40 | 2935 | --[[ $%BEGINLICENSE%$
Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
--[[
--]]
function connect_server()
print("--> a client really wants to talk to a server")
end
function read_handshake( )
local con = proxy.connection
print("<-- let's send him some information about us")
print(" mysqld-version: " .. con.server.mysqld_version)
print(" thread-id : " .. con.server.thread_id)
print(" scramble-buf : " .. string.format("%q", con.server.scramble_buffer))
print(" server-addr : " .. con.server.dst.address)
print(" client-addr : " .. con.client.src.address)
-- lets deny clients from !127.0.0.1
if con.client.src.address ~= "127.0.0.1" then
proxy.response.type = proxy.MYSQLD_PACKET_ERR
proxy.response.errmsg = "only local connects are allowed"
print("we don't like this client");
return proxy.PROXY_SEND_RESULT
end
end
function read_auth( )
local con = proxy.connection
print("--> there, look, the client is responding to the server auth packet")
print(" username : " .. con.client.username)
print(" password : " .. string.format("%q", con.client.scrambled_password))
print(" default_db : " .. con.client.default_db)
if con.client.username == "evil" then
proxy.response.type = proxy.MYSQLD_PACKET_ERR
proxy.response.errmsg = "evil logins are not allowed"
return proxy.PROXY_SEND_RESULT
end
end
function read_auth_result( auth )
local state = auth.packet:byte()
if state == proxy.MYSQLD_PACKET_OK then
print("<-- auth ok");
elseif state == proxy.MYSQLD_PACKET_ERR then
print("<-- auth failed");
else
print("<-- auth ... don't know: " .. string.format("%q", auth.packet));
end
end
function read_query( packet )
print("--> someone sent us a query")
if packet:byte() == proxy.COM_QUERY then
print(" query: " .. packet:sub(2))
if packet:sub(2) == "SELECT 1" then
proxy.queries:append(1, packet)
end
end
end
function read_query_result( inj )
print("<-- ... ok, this only gets called when read_query() told us")
proxy.response = {
type = proxy.MYSQLD_PACKET_RAW,
packets = {
"\255" ..
"\255\004" .. -- errno
"#" ..
"12S23" ..
"raw, raw, raw"
}
}
return proxy.PROXY_SEND_RESULT
end
| gpl-2.0 |
Sonicrich05/FFXI-Server | scripts/globals/spells/vivacious_etude.lua | 45 | 1815 | -----------------------------------------
-- Spell: Vivacious Etude
-- Static VIT Boost, BRD 30
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 0;
if (sLvl+iLvl <= 181) then
power = 3;
elseif ((sLvl+iLvl >= 182) and (sLvl+iLvl <= 235)) then
power = 4;
elseif ((sLvl+iLvl >= 236) and (sLvl+iLvl <= 288)) then
power = 5;
elseif ((sLvl+iLvl >= 289) and (sLvl+iLvl <= 342)) then
power = 6;
elseif ((sLvl+iLvl >= 343) and (sLvl+iLvl <= 396)) then
power = 7;
elseif ((sLvl+iLvl >= 397) and (sLvl+iLvl <= 449)) then
power = 8;
elseif (sLvl+iLvl >= 450) then
power = 9;
end
local iBoost = caster:getMod(MOD_ETUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_ETUDE,power,0,duration,caster:getID(),MOD_VIT,1)) then
spell:setMsg(75);
end
return EFFECT_ETUDE;
end; | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/bowl_of_pea_soup.lua | 3 | 1277 | -----------------------------------------
-- ID: 4416
-- Item: bowl_of_pea_soup
-- Food Effect: 3Hrs, All Races
-----------------------------------------
-- Vitality -1
-- Agility 1
-- Ranged Accuracy 5
-- HP Recovered While Healing 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4416);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_VIT, -1);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_RACC, 5);
target:addMod(MOD_HPHEAL, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_VIT, -1);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_RACC, 5);
target:delMod(MOD_HPHEAL, 3);
end;
| gpl-3.0 |
everslick/awesome | lib/wibox/widget/imagebox.lua | 3 | 3899 | ---------------------------------------------------------------------------
-- @author Uli Schlachter
-- @copyright 2010 Uli Schlachter
-- @release @AWESOME_VERSION@
-- @classmod wibox.widget.imagebox
---------------------------------------------------------------------------
local base = require("wibox.widget.base")
local surface = require("gears.surface")
local setmetatable = setmetatable
local pairs = pairs
local type = type
local pcall = pcall
local print = print
local imagebox = { mt = {} }
--- Draw an imagebox with the given cairo context in the given geometry.
function imagebox:draw(context, cr, width, height)
if not self._image then return end
if width == 0 or height == 0 then return end
if not self.resize_forbidden then
-- Let's scale the image so that it fits into (width, height)
local w = self._image:get_width()
local h = self._image:get_height()
local aspect = width / w
local aspect_h = height / h
if aspect > aspect_h then aspect = aspect_h end
cr:scale(aspect, aspect)
end
cr:set_source_surface(self._image, 0, 0)
cr:paint()
end
--- Fit the imagebox into the given geometry
function imagebox:fit(context, width, height)
if not self._image then
return 0, 0
end
local w = self._image:get_width()
local h = self._image:get_height()
if w > width then
h = h * width / w
w = width
end
if h > height then
w = w * height / h
h = height
end
if h == 0 or w == 0 then
return 0, 0
end
if not self.resize_forbidden then
local aspect = width / w
local aspect_h = height / h
-- Use the smaller one of the two aspect ratios.
if aspect > aspect_h then aspect = aspect_h end
w, h = w * aspect, h * aspect
end
return w, h
end
--- Set an imagebox' image
-- @param image Either a string or a cairo image surface. A string is
-- interpreted as the path to a png image file.
function imagebox:set_image(image)
local image = image
if type(image) == "string" then
local success, result = pcall(surface.load, image)
if not success then
print("Error while reading '" .. image .. "': " .. result)
print(debug.traceback())
return false
end
image = result
end
image = surface.load(image)
if image then
local w = image.width
local h = image.height
if w <= 0 or h <= 0 then
return false
end
end
if self._image == image then
return
end
self._image = image
self:emit_signal("widget::redraw_needed")
self:emit_signal("widget::layout_changed")
return true
end
--- Should the image be resized to fit into the available space?
-- @param allowed If false, the image will be clipped, else it will be resized
-- to fit into the available space.
function imagebox:set_resize(allowed)
self.resize_forbidden = not allowed
self:emit_signal("widget::redraw_needed")
self:emit_signal("widget::layout_changed")
end
--- Returns a new imagebox
-- @param image the image to display, may be nil
-- @param resize_allowed If false, the image will be clipped, else it will be resized
-- to fit into the available space.
local function new(image, resize_allowed)
local ret = base.make_widget()
for k, v in pairs(imagebox) do
if type(v) == "function" then
ret[k] = v
end
end
if image then
ret:set_image(image)
end
if resize_allowed ~= nil then
ret:set_resize(resize_allowed)
end
return ret
end
function imagebox.mt:__call(...)
return new(...)
end
return setmetatable(imagebox, imagebox.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
projectbismark/luci-bismark | contrib/luadoc/lua/luadoc/init.lua | 172 | 1333 | -------------------------------------------------------------------------------
-- LuaDoc main function.
-- @release $Id: init.lua,v 1.4 2008/02/17 06:42:51 jasonsantos Exp $
-------------------------------------------------------------------------------
local require = require
local util = require "luadoc.util"
logger = {}
module ("luadoc")
-------------------------------------------------------------------------------
-- LuaDoc version number.
_COPYRIGHT = "Copyright (c) 2003-2007 The Kepler Project"
_DESCRIPTION = "Documentation Generator Tool for the Lua language"
_VERSION = "LuaDoc 3.0.1"
-------------------------------------------------------------------------------
-- Main function
-- @see luadoc.doclet.html, luadoc.doclet.formatter, luadoc.doclet.raw
-- @see luadoc.taglet.standard
function main (files, options)
logger = util.loadlogengine(options)
-- load config file
if options.config ~= nil then
-- load specified config file
dofile(options.config)
else
-- load default config file
require("luadoc.config")
end
local taglet = require(options.taglet)
local doclet = require(options.doclet)
-- analyze input
taglet.options = options
taglet.logger = logger
local doc = taglet.start(files)
-- generate output
doclet.options = options
doclet.logger = logger
doclet.start(doc)
end
| apache-2.0 |
RavenX8/osIROSE-new | scripts/mobs/ai/doonga_origin.lua | 2 | 1068 | registerNpc(153, {
walk_speed = 230,
run_speed = 700,
scale = 170,
r_weapon = 0,
l_weapon = 0,
level = 68,
hp = 30,
attack = 307,
hit = 161,
def = 200,
res = 138,
avoid = 102,
attack_spd = 95,
is_magic_damage = 0,
ai_type = 24,
give_exp = 56,
drop_type = 172,
drop_money = 12,
drop_item = 45,
union_number = 45,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 220,
npc_type = 1,
hit_material_type = 0,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end | apache-2.0 |
Sonicrich05/FFXI-Server | scripts/globals/items/istakoz.lua | 18 | 1338 | -----------------------------------------
-- ID: 5453
-- Item: Istakoz
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity -5
-- Vitality 3
-- Defense +15.4%
-----------------------------------------
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,5453);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, -5);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_DEFP, 16);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, -5);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_DEFP, 16);
end;
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Monastic_Cavern/npcs/Altar.lua | 2 | 1779 | -----------------------------------
-- Area: Monastic Cavern
-- NPC: Altar
-- Involved in Quests: The Circle of Time
-- @zone 112
-- @pos 109 -3 -145
-----------------------------------
package.loaded["scripts/zones/Monastic_Cavern/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/zones/Monastic_Cavern/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local circleOfTime = player:getQuestStatus(JEUNO,THE_CIRCLE_OF_TIME);
if (circleOfTime == QUEST_ACCEPTED and player:getVar("circleTime") >= 7) then
if (player:hasKeyItem(STAR_RING1) and player:hasKeyItem(MOON_RING)) then
if (player:getVar("circleTime") == 7) then
SpawnMob(17391804,180):updateEnmity(player); -- Spawn bugaboo
elseif (player:getVar("circleTime") == 8) then
player:startEvent(0x03); -- Show final CS
end
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 == 0x03) then
player:setVar("circleTime",9); -- After bugaboo is killed, and final CS shows up
player:delKeyItem(MOON_RING);
player:delKeyItem(STAR_RING1);
end
end; | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/spells/hailstorm.lua | 3 | 1092 | --------------------------------------
-- Spell: Hailstorm
-- Changes the weather around target party member to "snowy."
--------------------------------------
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)
target:delStatusEffectSilent(EFFECT_FIRESTORM);
target:delStatusEffectSilent(EFFECT_SANDSTORM);
target:delStatusEffectSilent(EFFECT_RAINSTORM);
target:delStatusEffectSilent(EFFECT_WINDSTORM);
target:delStatusEffectSilent(EFFECT_HAILSTORM);
target:delStatusEffectSilent(EFFECT_THUNDERSTORM);
target:delStatusEffectSilent(EFFECT_AURORASTORM);
target:delStatusEffectSilent(EFFECT_VOIDSTORM);
local merit = caster:getMerit(MERIT_STORMSURGE);
local power = 0;
if merit > 0 then
power = merit + caster:getMod(MOD_STORMSURGE_EFFECT) + 2;
end
target:addStatusEffect(EFFECT_HAILSTORM,power,0,180);
end; | gpl-3.0 |
DiNaSoR/Angel_Arena | game/angel_arena/scripts/vscripts/hero/hero_phantom_assassin.lua | 1 | 36442 | --[[
Author: sercankd
Date: 06.04.2017
Updated: 15.04.2017
]]
CreateEmptyTalents("phantom_assassin")
-------------------------------------------
-- Stifling Dagger
-------------------------------------------
imba_phantom_assassin_stifling_dagger = class({})
LinkLuaModifier("modifier_imba_stifling_dagger_slow", "hero/hero_phantom_assassin", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_stifling_dagger_silence", "hero/hero_phantom_assassin", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_stifling_dagger_bonus_damage", "hero/hero_phantom_assassin", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_stifling_dagger_dmg_reduction", "hero/hero_phantom_assassin", LUA_MODIFIER_MOTION_NONE)
function imba_phantom_assassin_stifling_dagger:GetAbilityTextureName()
return "phantom_assassin_stifling_dagger"
end
function imba_phantom_assassin_stifling_dagger:OnSpellStart()
local caster = self:GetCaster()
local ability = self
local target = self:GetCursorTarget()
local scepter = caster:HasScepter()
--ability specials
move_slow = ability:GetSpecialValueFor("move_slow")
dagger_speed = ability:GetSpecialValueFor("dagger_speed")
slow_duration = ability:GetSpecialValueFor("slow_duration")
silence_duration = ability:GetSpecialValueFor("silence_duration")
damage_reduction = ability:GetSpecialValueFor("damage_reduction")
dagger_vision = ability:GetSpecialValueFor("dagger_vision")
scepter_knives_interval = 0.3
cast_range = ability:GetCastRange() + GetCastRangeIncrease(caster)
playbackrate = 1 + scepter_knives_interval
--TALENT: +35 Stifling Dagger bonus damage
if caster:HasTalent("special_bonus_imba_phantom_assassin_1") then
bonus_damage = ability:GetSpecialValueFor("bonus_damage") + self:GetCaster():FindTalentValue("special_bonus_imba_phantom_assassin_1")
else
bonus_damage = ability:GetSpecialValueFor("bonus_damage")
end
--coup de grace variables
local ability_crit = caster:FindAbilityByName("modifier_imba_coup_de_grace")
local ps_coup_modifier = "modifier_imba_phantom_strike_coup_de_grace"
StartSoundEvent("Hero_PhantomAssassin.Dagger.Cast", caster)
local extra_data = {main_dagger = true}
local dagger_projectile
dagger_projectile = {
EffectName = "particles/units/heroes/hero_phantom_assassin/phantom_assassin_stifling_dagger.vpcf",
Dodgeable = true,
Ability = ability,
ProvidesVision = true,
VisionRadius = 600,
bVisibleToEnemies = true,
iMoveSpeed = dagger_speed,
Source = caster,
iVisionTeamNumber = caster:GetTeamNumber(),
Target = target,
iSourceAttachment = DOTA_PROJECTILE_ATTACHMENT_ATTACK_1,
bReplaceExisting = false,
ExtraData = extra_data
}
ProjectileManager:CreateTrackingProjectile( dagger_projectile )
-- Secondary knives
if scepter or caster:HasTalent("special_bonus_imba_phantom_assassin_3") then
local secondary_knives_thrown = 0
-- TALENT: +1 Stifling Dagger bonus dagger (like aghs)
if not scepter and caster:HasTalent("special_bonus_imba_phantom_assassin_3") then
scepter_dagger_count = self:GetCaster():FindTalentValue("special_bonus_imba_phantom_assassin_3")
secondary_knives_thrown = scepter_dagger_count
elseif scepter and caster:HasTalent("special_bonus_imba_phantom_assassin_3") then
scepter_dagger_count = ability:GetSpecialValueFor("scepter_dagger_count") + self:GetCaster():FindTalentValue("special_bonus_imba_phantom_assassin_3")
else
scepter_dagger_count = ability:GetSpecialValueFor("scepter_dagger_count")
end
-- Prepare extra_data
extra_data = {main_dagger = false}
-- Clear marks from all enemies
local enemies = FindUnitsInRadius(caster:GetTeamNumber(),
caster:GetAbsOrigin(),
nil,
cast_range,
DOTA_UNIT_TARGET_TEAM_ENEMY,
DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC,
DOTA_UNIT_TARGET_FLAG_NONE,
FIND_UNITS_EVERYWHERE,
false)
for _, enemy in pairs (enemies) do
enemy.hit_by_pa_dagger = false
end
-- Mark the main target, set variables
target.hit_by_pa_dagger = true
local dagger_target_found
-- Look for a secondary target to throw a knife at
Timers:CreateTimer(scepter_knives_interval, function()
-- Set variable for clear action
dagger_target_found = false
-- Look for a target in the cast range of the spell
local enemies = FindUnitsInRadius(caster:GetTeamNumber(),
caster:GetAbsOrigin(),
nil,
cast_range,
DOTA_UNIT_TARGET_TEAM_ENEMY,
DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC,
DOTA_UNIT_TARGET_FLAG_FOW_VISIBLE,
FIND_ANY_ORDER,
false)
-- Check if there's an enemy unit without a mark. Mark it and throw a dagger to it
for _, enemy in pairs (enemies) do
if not enemy.hit_by_pa_dagger then
enemy.hit_by_pa_dagger = true
dagger_target_found = true
caster:StartGestureWithPlaybackRate(ACT_DOTA_CAST_ABILITY_1, playbackrate)
dagger_projectile = {
EffectName = "particles/units/heroes/hero_phantom_assassin/phantom_assassin_stifling_dagger.vpcf",
Dodgeable = true,
Ability = ability,
ProvidesVision = true,
VisionRadius = 600,
bVisibleToEnemies = true,
iMoveSpeed = dagger_speed,
Source = caster,
iVisionTeamNumber = caster:GetTeamNumber(),
Target = enemy,
iSourceAttachment = DOTA_PROJECTILE_ATTACHMENT_ATTACK_1,
bReplaceExisting = false,
ExtraData = extra_data
}
ProjectileManager:CreateTrackingProjectile(dagger_projectile)
break -- only hit the first enemy found
end
end
-- If all enemies were found with a mark, clear all marks from everyone
if not dagger_target_found then
for _, enemy in pairs (enemies) do
enemy.hit_by_pa_dagger = false
end
-- Throw dagger at a random enemy
local enemy = enemies[RandomInt(1, #enemies)]
dagger_projectile = {
EffectName = "particles/units/heroes/hero_phantom_assassin/phantom_assassin_stifling_dagger.vpcf",
Dodgeable = true,
Ability = ability,
ProvidesVision = true,
VisionRadius = 600,
bVisibleToEnemies = true,
iMoveSpeed = dagger_speed,
Source = caster,
iVisionTeamNumber = caster:GetTeamNumber(),
Target = enemy,
iSourceAttachment = DOTA_PROJECTILE_ATTACHMENT_ATTACK_1,
bReplaceExisting = false,
ExtraData = extra_data
}
ProjectileManager:CreateTrackingProjectile(dagger_projectile)
end
-- Check if there are knives remaining
secondary_knives_thrown = secondary_knives_thrown + 1
if secondary_knives_thrown < scepter_dagger_count then
return scepter_knives_interval
else
return nil
end
end)
end
end
function imba_phantom_assassin_stifling_dagger:OnProjectileHit( target, location )
local caster = self:GetCaster()
if not target then
return nil
end
-- With 20 percentage play random stifling dagger response
local responses = {"phantom_assassin_phass_ability_stiflingdagger_01","phantom_assassin_phass_ability_stiflingdagger_02","phantom_assassin_phass_ability_stiflingdagger_03","phantom_assassin_phass_ability_stiflingdagger_04"}
caster:EmitCasterSound("npc_dota_hero_phantom_assassin",responses, 20, DOTA_CAST_SOUND_FLAG_NONE, 20,"stifling_dagger")
-- If the target possesses a ready Linken's Sphere, do nothing else
if target:GetTeamNumber() ~= caster:GetTeamNumber() then
if target:TriggerSpellAbsorb(self) then
return nil
end
end
-- Apply slow and silence modifiers
if not target:IsMagicImmune() then
target:AddNewModifier(caster, self, "modifier_imba_stifling_dagger_silence", {duration = silence_duration})
target:AddNewModifier(caster, self, "modifier_imba_stifling_dagger_slow", {duration = slow_duration})
end
caster:AddNewModifier(caster, self, "modifier_imba_stifling_dagger_dmg_reduction", {})
caster:AddNewModifier(caster, self, "modifier_imba_stifling_dagger_bonus_damage", {})
-- Attack (calculates on-hit procs)
local initial_pos = caster:GetAbsOrigin()
local target_pos = target:GetAbsOrigin()
-- Offset is necessary, because cleave from Battlefury doesn't work (in any direction) if you are exactly on top of the target unit
local offset = 100 --dotameters (default melee range is 150 dotameters)
-- Find the distance vector (distance, but as a vector rather than Length2D)
-- z is 0 to prevent any wonkiness due to height differences, we'll use the targets height, unmodified
local distance_vector = Vector(target_pos.x - initial_pos.x, target_pos.y - initial_pos.y, 0)
-- Normalize it, so the offset can be applied to x/y components, proportionally
distance_vector = distance_vector:Normalized()
-- Offset the caster 100 units in front of the target
target_pos.x = target_pos.x - offset * distance_vector.x
target_pos.y = target_pos.y - offset * distance_vector.y
caster:SetAbsOrigin(target_pos)
caster:PerformAttack(target, true, true, true, true, true, false, true)
caster:SetAbsOrigin(initial_pos)
caster:RemoveModifierByName( "modifier_imba_stifling_dagger_bonus_damage" )
caster:RemoveModifierByName( "modifier_imba_stifling_dagger_dmg_reduction" )
return true
end
function imba_phantom_assassin_stifling_dagger:GetCastRange()
return self:GetSpecialValueFor("cast_range")
end
-------------------------------------------
-- Stifling Dagger slow modifier
-------------------------------------------
modifier_imba_stifling_dagger_slow = class({})
function modifier_imba_stifling_dagger_slow:OnCreated()
if IsServer() then
local caster = self:GetCaster()
local ability = self:GetAbility()
local dagger_vision = ability:GetSpecialValueFor("dagger_vision")
local duration = ability:GetSpecialValueFor("slow_duration")
local stifling_dagger_modifier_slow_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_phantom_assassin/phantom_assassin_stifling_dagger_debuff.vpcf", PATTACH_ABSORIGIN_FOLLOW, self.target)
ParticleManager:ReleaseParticleIndex(stifling_dagger_modifier_slow_particle)
-- Add vision for the duration
AddFOWViewer(caster:GetTeamNumber(), self:GetParent():GetAbsOrigin(), dagger_vision, duration, false)
end
end
function modifier_imba_stifling_dagger_slow:DeclareFunctions()
local funcs = { MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE, MODIFIER_STATE_PROVIDES_VISION }
return funcs
end
function modifier_imba_stifling_dagger_slow:GetModifierMoveSpeedBonus_Percentage()
return self:GetAbility():GetSpecialValueFor("move_slow");
end
function modifier_imba_stifling_dagger_slow:GetModifierProvidesFOWVision() return true end
function modifier_imba_stifling_dagger_slow:IsDebuff() return true end
function modifier_imba_stifling_dagger_slow:IsPurgable() return true end
-------------------------------------------
-- Stifling Dagger silence modifier
-------------------------------------------
modifier_imba_stifling_dagger_silence = class({})
function modifier_imba_stifling_dagger_silence:OnCreated()
self.stifling_dagger_modifier_silence_particle = ParticleManager:CreateParticle("particles/generic_gameplay/generic_silenced.vpcf", PATTACH_OVERHEAD_FOLLOW, self.target)
ParticleManager:ReleaseParticleIndex(self.stifling_dagger_modifier_silence_particle)
end
function modifier_imba_stifling_dagger_silence:CheckState()
local states = { [MODIFIER_STATE_SILENCED] = true, }
return states
end
function modifier_imba_stifling_dagger_silence:IsDebuff() return true end
function modifier_imba_stifling_dagger_silence:IsPurgable() return true end
function modifier_imba_stifling_dagger_silence:IsHidden() return true end
-------------------------------------------
-- Stifling Dagger bonus damage modifier
-------------------------------------------
modifier_imba_stifling_dagger_bonus_damage = class({})
function modifier_imba_stifling_dagger_bonus_damage:DeclareFunctions()
local funcs = { MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE }
return funcs
end
function modifier_imba_stifling_dagger_bonus_damage:GetModifierPreAttack_BonusDamage()
local ability = self:GetAbility()
return ability:GetSpecialValueFor("bonus_damage");
end
function modifier_imba_stifling_dagger_bonus_damage:IsBuff() return true end
function modifier_imba_stifling_dagger_bonus_damage:IsPurgable() return false end
function modifier_imba_stifling_dagger_bonus_damage:IsHidden() return true end
-------------------------------------------
-- Stifling Dagger damage reduction modifier
-------------------------------------------
modifier_imba_stifling_dagger_dmg_reduction = class({})
function modifier_imba_stifling_dagger_dmg_reduction:OnCreated()
self.ability = self:GetAbility()
self.damage_reduction = self.ability:GetSpecialValueFor("damage_reduction")
end
function modifier_imba_stifling_dagger_dmg_reduction:DeclareFunctions()
local decFunc = {MODIFIER_PROPERTY_BASEDAMAGEOUTGOING_PERCENTAGE}
return decFunc
end
function modifier_imba_stifling_dagger_dmg_reduction:GetModifierBaseDamageOutgoing_Percentage()
return self.damage_reduction * (-1)
end
----------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------
-- Phantom Strike
-------------------------------------------
imba_phantom_assassin_phantom_strike = class({})
function imba_phantom_assassin_phantom_strike:GetAbilityTextureName()
return "phantom_assassin_phantom_strike"
end
LinkLuaModifier("modifier_imba_phantom_strike", "hero/hero_phantom_assassin", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_phantom_strike_coup_de_grace", "hero/hero_phantom_assassin", LUA_MODIFIER_MOTION_NONE)
function imba_phantom_assassin_phantom_strike:IsNetherWardStealable() return false end
function imba_phantom_assassin_phantom_strike:CastFilterResultTarget(target)
if IsServer() then
local caster = self:GetCaster()
local casterID = caster:GetPlayerOwnerID()
local targetID = target:GetPlayerOwnerID()
-- Can't cast on self (self blink!)
if target == caster then
return UF_FAIL_CUSTOM
end
local nResult = UnitFilter( target, self:GetAbilityTargetTeam(), self:GetAbilityTargetType(), self:GetAbilityTargetFlags(), self:GetCaster():GetTeamNumber() )
return nResult
end
end
function imba_phantom_assassin_phantom_strike:GetCustomCastErrorTarget(target)
return "dota_hud_error_cant_cast_on_self"
end
function imba_phantom_assassin_phantom_strike:OnSpellStart()
if IsServer() then
self.caster = self:GetCaster()
self.ability = self
self.target = self:GetCursorTarget()
--ability specials
self.bonus_attack_speed = self.ability:GetSpecialValueFor("bonus_attack_speed")
self.buff_duration = self.ability:GetSpecialValueFor("buff_duration")
self.projectile_speed = self.ability:GetSpecialValueFor("projectile_speed")
self.projectile_width = self.ability:GetSpecialValueFor("projectile_width")
self.attacks = self.ability:GetSpecialValueFor("attacks")
--TALENT: +30 Phantom Strike bonus attack speed
if self.caster:HasTalent("special_bonus_imba_phantom_assassin_2") then
self.bonus_attack_speed = self.ability:GetSpecialValueFor("bonus_attack_speed") + self.caster:FindTalentValue("special_bonus_imba_phantom_assassin_2")
else
self.bonus_attack_speed = self.ability:GetSpecialValueFor("bonus_attack_speed")
end
-- Trajectory calculations
self.caster_pos = self.target:GetAbsOrigin()
self.target_pos = self.target:GetAbsOrigin()
self.direction = ( self.target_pos - self.caster_pos ):Normalized()
self.distance = ( self.target_pos - self.caster_pos ):Length2D()
-- If the target possesses a ready Linken's Sphere, do nothing else
if self.target:GetTeamNumber() ~= self.caster:GetTeamNumber() then
if self.target:TriggerSpellAbsorb(self.ability) then
return nil
end
end
self.blink_projectile = {
Ability = self.ability,
vSpawnOrigin = self.caster_pos,
fDistance = self.distance,
fStartRadius = self.projectile_width,
fEndRadius = self.projectile_width,
Source = self.caster,
bHasFrontalCone = false,
bReplaceExisting = false,
iUnitTargetTeam = DOTA_UNIT_TARGET_TEAM_ENEMY,
iUnitTargetFlags = DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES + DOTA_UNIT_TARGET_FLAG_NO_INVIS,
iUnitTargetType = DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP,
bDeleteOnHit = false,
vVelocity = Vector(self.direction.x, self.direction.y, 0) * self.projectile_speed,
bProvidesVision = false,
}
ProjectileManager:CreateLinearProjectile(self.blink_projectile)
StartSoundEvent("Hero_PhantomAssassin.Strike.Start", self:GetCaster())
-- Blink
local distance = (self.target:GetAbsOrigin() - self.caster:GetAbsOrigin()):Length2D()
local direction = (self.target:GetAbsOrigin() - self.caster:GetAbsOrigin()):Normalized()
local blink_point = self.caster:GetAbsOrigin() + direction * (distance - 128)
self.caster:SetAbsOrigin(blink_point)
Timers:CreateTimer(FrameTime(), function()
FindClearSpaceForUnit(self.caster, blink_point, true)
end)
self.caster:SetForwardVector(direction)
-- Disjoint projectiles
ProjectileManager:ProjectileDodge(self.caster)
-- Fire blink particle
self.blink_pfx = ParticleManager:CreateParticle("particles/units/heroes/hero_phantom_assassin/phantom_assassin_phantom_strike_end.vpcf", PATTACH_ABSORIGIN_FOLLOW, self.caster)
ParticleManager:ReleaseParticleIndex(self.blink_pfx)
-- Fire blink end sound
self.target:EmitSound("Hero_PhantomAssassin.Strike.End")
-- Apply coup de grace modifier on caster it was an enemy
if self.target:GetTeamNumber() ~= self.caster:GetTeamNumber() then
-- Apply blink strike modifier on caster
self.caster:AddNewModifier(self.caster, self, "modifier_imba_phantom_strike", { duration= self.buff_duration })
-- Apply crit modifier
self.caster:AddNewModifier(self.caster, self, "modifier_imba_phantom_strike_coup_de_grace", { duration= self.buff_duration })
--Increased Coup de Grace chance for the next 4 attacks
--TALENT
if self.caster:HasTalent("special_bonus_imba_phantom_assassin_6") then
attacks_count = self.caster:FindTalentValue("special_bonus_imba_phantom_assassin_6") + 4
else
attacks_count = self.attacks
end
self.caster:SetModifierStackCount( "modifier_imba_phantom_strike_coup_de_grace", self.caster, attacks_count)
-- If cast on an enemy, immediately start attacking it
self.caster:MoveToTargetToAttack(self.target)
end
end
end
-------------------------------------------
-- Phantom Strike modifier
-------------------------------------------
modifier_imba_phantom_strike = class({})
function modifier_imba_phantom_strike:DeclareFunctions()
local funcs = { MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT }
return funcs
end
function modifier_imba_phantom_strike:GetModifierAttackSpeedBonus_Constant()
local caster = self:GetCaster()
local ability = self:GetAbility()
self.speed_bonus = ability:GetSpecialValueFor("bonus_attack_speed")
return self.speed_bonus
end
function modifier_imba_phantom_strike:IsBuff() return true end
function modifier_imba_phantom_strike:IsPurgable() return true end
-------------------------------------------
-- Phantom Strike coup de grace modifier
-------------------------------------------
modifier_imba_phantom_strike_coup_de_grace = class({})
function modifier_imba_phantom_strike_coup_de_grace:DeclareFunctions()
local funcs = { MODIFIER_EVENT_ON_ATTACK_LANDED }
return funcs
end
function modifier_imba_phantom_strike_coup_de_grace:OnAttackLanded(keys)
if IsServer() then
local caster = self:GetCaster()
local ability = self:GetAbility()
local owner = self:GetParent()
local modifier_speed = "modifier_imba_phantom_strike"
local stackcount = self:GetStackCount()
-- If attack was not performed by the modifier's owner, do nothing
if owner ~= keys.attacker then
return end
if stackcount == 1 then
self:Destroy()
if caster:HasModifier(modifier_speed) then
caster:RemoveModifierByName(modifier_speed)
end
else
self:DecrementStackCount()
end
end
end
function modifier_imba_phantom_strike_coup_de_grace:IsBuff() return true end
function modifier_imba_phantom_strike_coup_de_grace:IsPurgable() return true end
----------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------
-- Blur
-------------------------------------------
imba_phantom_assassin_blur = class({})
LinkLuaModifier("modifier_imba_blur", "hero/hero_phantom_assassin", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_blur_blur", "hero/hero_phantom_assassin", LUA_MODIFIER_MOTION_NONE) --wat
LinkLuaModifier("modifier_imba_blur_speed", "hero/hero_phantom_assassin", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_blur_opacity", "hero/hero_phantom_assassin", LUA_MODIFIER_MOTION_NONE)
function imba_phantom_assassin_blur:GetAbilityTextureName()
return "phantom_assassin_blur"
end
function imba_phantom_assassin_blur:GetIntrinsicModifierName()
return "modifier_imba_blur"
end
-------------------------------------------
-- Blur modifier
-------------------------------------------
modifier_imba_blur = class({})
function modifier_imba_blur:OnCreated()
if IsServer() then
-- Ability properties
self.caster = self:GetCaster()
self.ability = self:GetAbility()
self.parent = self:GetParent()
self.modifier_aura = "modifier_imba_blur_blur"
self.modifier_blur_transparent = "modifier_imba_blur_opacity"
self.modifier_speed = "modifier_imba_blur_speed"
-- Ability specials
self.radius = self.ability:GetSpecialValueFor("radius")
self.evasion = self.ability:GetSpecialValueFor("evasion")
self.ms_duration = self.ability:GetSpecialValueFor("speed_bonus_duration")
-- Start thinking
self:StartIntervalThink(0.2)
end
end
function modifier_imba_blur:OnRefresh()
self:OnCreated()
end
function modifier_imba_blur:OnIntervalThink()
if IsServer() then
-- Find nearby enemies
local nearby_enemies = FindUnitsInRadius(self.caster:GetTeamNumber(), self.caster:GetAbsOrigin(), nil, self.radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_ANY_ORDER, false)
-- If there is at least one, apply the blur modifier
if #nearby_enemies > 0 and self.caster:HasModifier(self.modifier_aura) then
self.caster:RemoveModifierByName(self.modifier_aura)
-- Make mortred transparent (wtf firetoad)
self.caster:AddNewModifier(self.caster, self, self.modifier_blur_transparent, {})
-- Else, if there are no enemies, remove the modifier
elseif #nearby_enemies == 0 and not self.caster:HasModifier(self.modifier_aura) then
self.caster:AddNewModifier(self.caster, self.ability, self.modifier_aura, {})
-- Make mortred not transparent (wtf firetoad)
self.caster:RemoveModifierByName(self.modifier_blur_transparent)
local responses = {"phantom_assassin_phass_ability_blur_01",
"phantom_assassin_phass_ability_blur_02",
"phantom_assassin_phass_ability_blur_03"
}
self.caster:EmitCasterSound("npc_dota_hero_phantom_assassin",responses, 10, DOTA_CAST_SOUND_FLAG_NONE, 50,"blur")
end
end
end
function modifier_imba_blur:DeclareFunctions()
local funcs = { MODIFIER_PROPERTY_EVASION_CONSTANT,
MODIFIER_EVENT_ON_ATTACK_FAIL,
MODIFIER_PROPERTY_INCOMING_DAMAGE_PERCENTAGE}
return funcs
end
function modifier_imba_blur:GetModifierEvasion_Constant()
return self.evasion
end
function modifier_imba_blur:GetModifierIncomingDamage_Percentage()
--TALENT: Blur now grants +30% chance to evade any damage
if RollPercentage(self.caster:FindTalentValue("special_bonus_imba_phantom_assassin_8")) then
SendOverheadEventMessage(nil, OVERHEAD_ALERT_EVADE, self.caster, 0, nil)
return -100
end
return nil
end
function modifier_imba_blur:OnAttackFail(keys)
if IsServer() then
if keys.target == self:GetParent() then
-- If the caster doesn't have the evasion speed modifier yet, give it to him
if not self.caster:HasModifier(self.modifier_speed) then
self.caster:AddNewModifier(self.caster, self.ability, self.modifier_speed, {duration = self.ms_duration})
end
-- Increment a stack and refresh
local modifier_speed_handler = self.caster:FindModifierByName(self.modifier_speed)
if modifier_speed_handler then
modifier_speed_handler:IncrementStackCount()
modifier_speed_handler:ForceRefresh()
end
end
end
end
function modifier_imba_blur:IsHidden() return true end
function modifier_imba_blur:IsBuff() return true end
function modifier_imba_blur:IsPurgable() return false end
-- Evasion speed buff modifier
modifier_imba_blur_speed = class({})
function modifier_imba_blur_speed:OnCreated()
-- Ability properties
self.caster = self:GetCaster()
self.ability = self:GetAbility()
self.parent = self:GetParent()
-- Ability specials
self.speed_bonus_duration = self.ability:GetSpecialValueFor("speed_bonus_duration")
self.blur_ms = self.ability:GetSpecialValueFor("blur_ms")
if IsServer() then
-- Initialize table
self.stacks_table = {}
-- Start thinking
self:StartIntervalThink(0.1)
end
end
function modifier_imba_blur_speed:OnIntervalThink()
if IsServer() then
-- Check if there are any stacks left on the table
if #self.stacks_table > 0 then
-- For each stack, check if it is past its expiration time. If it is, remove it from the table
for i = #self.stacks_table, 1, -1 do
if self.stacks_table[i] + self.speed_bonus_duration < GameRules:GetGameTime() then
table.remove(self.stacks_table, i)
end
end
-- If after removing the stacks, the table is empty, remove the modifier.
if #self.stacks_table == 0 then
self:Destroy()
-- Otherwise, set its stack count
else
self:SetStackCount(#self.stacks_table)
end
-- Recalculate bonus based on new stack count
self:GetParent():CalculateStatBonus()
-- If there are no stacks on the table, just remove the modifier.
else
self:Destroy()
end
end
end
function modifier_imba_blur_speed:OnRefresh()
if IsServer() then
-- Insert new stack values
table.insert(self.stacks_table, GameRules:GetGameTime())
end
end
function modifier_imba_blur_speed:IsHidden() return false end
function modifier_imba_blur_speed:IsPurgable() return true end
function modifier_imba_blur_speed:IsDebuff() return false end
function modifier_imba_blur_speed:DeclareFunctions()
local decFunc = {MODIFIER_PROPERTY_MOVESPEED_BONUS_CONSTANT}
return decFunc
end
function modifier_imba_blur_speed:GetModifierMoveSpeedBonus_Constant()
return self.blur_ms * self:GetStackCount()
end
-------------------------------------------
-- Blur blur modifier
-------------------------------------------
modifier_imba_blur_blur = class({})
function modifier_imba_blur_blur:OnCreated()
self.blur_particle = ParticleManager:CreateParticle( "particles/units/heroes/hero_phantom_assassin/phantom_assassin_blur.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetCaster())
end
function modifier_imba_blur_blur:GetStatusEffectName()
return "particles/hero/phantom_assassin/blur_status_fx.vpcf"
end
function modifier_imba_blur_blur:StatusEffectPriority() return 11 end
function modifier_imba_blur_blur:CheckState()
local states = { [MODIFIER_STATE_NOT_ON_MINIMAP_FOR_ENEMIES] = true, }
return states
end
function modifier_imba_blur_blur:OnRemoved()
ParticleManager:DestroyParticle(self.blur_particle, false)
end
function modifier_imba_blur_blur:OnDestroy()
ParticleManager:ReleaseParticleIndex(self.blur_particle)
end
function modifier_imba_blur_blur:IsHidden() return true end
function modifier_imba_blur_blur:IsDebuff() return false end
function modifier_imba_blur_blur:IsPurgable() return false end
-------------------------------------------
-- Blur opacity modifier
-------------------------------------------
modifier_imba_blur_opacity = class({})
function modifier_imba_blur_opacity:IsHidden() return false end
function modifier_imba_blur_opacity:IsDebuff() return false end
function modifier_imba_blur_opacity:IsPurgable()return false end
function modifier_imba_blur_opacity:DeclareFunctions()
return {MODIFIER_PROPERTY_INVISIBILITY_LEVEL}
end
function modifier_imba_blur_opacity:GetModifierInvisibilityLevel()
return 1
end
function modifier_imba_blur_opacity:IsHidden()
return true
end
----------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------
-- Coup De Grace
-------------------------------------------
imba_phantom_assassin_coup_de_grace = class({})
LinkLuaModifier("modifier_imba_coup_de_grace", "hero/hero_phantom_assassin", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_coup_de_grace_crit", "hero/hero_phantom_assassin", LUA_MODIFIER_MOTION_NONE)
function imba_phantom_assassin_coup_de_grace:GetIntrinsicModifierName()
return "modifier_imba_coup_de_grace"
end
function imba_phantom_assassin_coup_de_grace:GetAbilityTextureName()
return "phantom_assassin_coup_de_grace"
end
-------------------------------------------
-- Coup De Grace modifier
-------------------------------------------
modifier_imba_coup_de_grace = class({})
function modifier_imba_coup_de_grace:OnCreated()
-- Ability properties
self.caster = self:GetCaster()
self.ability = self:GetAbility()
self.parent = self:GetParent()
self.ps_coup_modifier = "modifier_imba_phantom_strike_coup_de_grace"
self.modifier_stacks = "modifier_imba_coup_de_grace_crit"
-- Ability specials
self.crit_chance = self.ability:GetSpecialValueFor("crit_chance")
self.crit_increase_duration = self.ability:GetSpecialValueFor("crit_increase_duration")
self.crit_bonus = self.ability:GetSpecialValueFor("crit_bonus")
end
function modifier_imba_coup_de_grace:OnRefresh()
self:OnCreated()
end
function modifier_imba_coup_de_grace:DeclareFunctions()
local funcs = {MODIFIER_PROPERTY_PREATTACK_CRITICALSTRIKE}
return funcs
end
function modifier_imba_coup_de_grace:GetModifierPreAttack_CriticalStrike(keys)
if IsServer() then
local target = keys.target
local crit_duration = self.crit_increase_duration
local crit_chance_total = self.crit_chance
-- Ignore crit for buildings
if target:IsBuilding() then
return end
-- if we have phantom strike modifier, apply bonus percentage to our crit_chance
if self.caster:HasModifier(self.ps_coup_modifier) then
local ps_coup_modifier_handler = self.caster:FindModifierByName(self.ps_coup_modifier)
if ps_coup_modifier_handler then
local bonus_coup_de_grace_chance = ps_coup_modifier_handler:GetAbility():GetSpecialValueFor("bonus_coup_de_grace")
-- TALENT: +5% Phantom Strike bonus crit chance
bonus_coup_de_grace_chance = bonus_coup_de_grace_chance + self:GetCaster():FindTalentValue("special_bonus_imba_phantom_assassin_4")
-- Calculate total crit chance
local crit_chance_total = crit_chance_total + bonus_coup_de_grace_chance
end
end
if RollPseudoRandom(crit_chance_total, self) then
local coup_pfx = ParticleManager:CreateParticle("particles/units/heroes/hero_phantom_assassin/phantom_assassin_crit_impact.vpcf", PATTACH_CUSTOMORIGIN, caster)
ParticleManager:SetParticleControlEnt(coup_pfx, 0, target, PATTACH_POINT_FOLLOW, "attach_hitloc", target:GetAbsOrigin(), true)
ParticleManager:SetParticleControlEnt(coup_pfx, 1, target, PATTACH_ABSORIGIN_FOLLOW, "attach_origin", target:GetAbsOrigin(), true)
ParticleManager:ReleaseParticleIndex(coup_pfx)
StartSoundEvent("Hero_PhantomAssassin.CoupDeGrace", target)
local responses = {"phantom_assassin_phass_ability_coupdegrace_01",
"phantom_assassin_phass_ability_coupdegrace_02",
"phantom_assassin_phass_ability_coupdegrace_03",
"phantom_assassin_phass_ability_coupdegrace_04"
}
self.caster:EmitCasterSound("npc_dota_hero_phantom_assassin",responses, 50, DOTA_CAST_SOUND_FLAG_BOTH_TEAMS, 20,"coup_de_grace")
--TALENT: +8 sec Coup de Grace bonus damage duration
crit_duration = crit_duration + self.caster:FindTalentValue("special_bonus_imba_phantom_assassin_7")
-- If the caster doesn't have the stacks modifier, give it to him
if not self.caster:HasModifier(self.modifier_stacks) then
self.caster:AddNewModifier(self.caster, self.ability, self.modifier_stacks, {duration = crit_duration})
end
-- Find the modifier, increase a stack and refresh it
local modifier_stacks_handler = self.caster:FindModifierByName(self.modifier_stacks)
if modifier_stacks_handler then
modifier_stacks_handler:IncrementStackCount()
modifier_stacks_handler:ForceRefresh()
end
-- TALENT: +100% Coup de Grace crit damage
local crit_bonus = self.crit_bonus + self.caster:FindTalentValue("special_bonus_imba_phantom_assassin_5")
return crit_bonus
end
return nil
end
end
function modifier_imba_coup_de_grace:IsPassive() return true end
function modifier_imba_coup_de_grace:IsHidden()
local stacks = self:GetStackCount()
if stacks > 0 then
return false
end
return true
end
modifier_imba_coup_de_grace_crit = class({})
function modifier_imba_coup_de_grace_crit:OnCreated()
-- Ability properties
self.caster = self:GetCaster()
self.ability = self:GetAbility()
self.parent = self:GetParent()
-- Ability specials
self.crit_increase_duration = self.ability:GetSpecialValueFor("crit_increase_duration")
self.crit_increase_damage = self.ability:GetSpecialValueFor("crit_increase_damage")
if IsServer() then
-- Initialize table
self.stacks_table = {}
-- Start thinking
self:StartIntervalThink(0.1)
end
end
function modifier_imba_coup_de_grace_crit:OnIntervalThink()
if IsServer() then
-- Check if there are any stacks left on the table
if #self.stacks_table > 0 then
-- For each stack, check if it is past its expiration time. If it is, remove it from the table
for i = #self.stacks_table, 1, -1 do
if self.stacks_table[i] + self.crit_increase_duration < GameRules:GetGameTime() then
table.remove(self.stacks_table, i)
end
end
-- If after removing the stacks, the table is empty, remove the modifier.
if #self.stacks_table == 0 then
self:Destroy()
-- Otherwise, set its stack count
else
self:SetStackCount(#self.stacks_table)
end
-- Recalculate bonus based on new stack count
self:GetParent():CalculateStatBonus()
-- If there are no stacks on the table, just remove the modifier.
else
self:Destroy()
end
end
end
function modifier_imba_coup_de_grace_crit:OnRefresh()
if IsServer() then
-- Insert new stack values
table.insert(self.stacks_table, GameRules:GetGameTime())
end
end
function modifier_imba_coup_de_grace_crit:IsHidden() return false end
function modifier_imba_coup_de_grace_crit:IsPurgable() return true end
function modifier_imba_coup_de_grace_crit:IsDebuff() return false end
function modifier_imba_coup_de_grace_crit:DeclareFunctions()
local decFunc = {MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE}
return decFunc
end
function modifier_imba_coup_de_grace_crit:GetModifierPreAttack_BonusDamage()
return self.crit_increase_damage * self:GetStackCount()
end | mit |
Sonicrich05/FFXI-Server | scripts/globals/weaponskills/iron_tempest.lua | 30 | 1350 | -----------------------------------
-- Iron Tempest
-- Great Axe weapon skill
-- Skill Level: 40
-- Delivers a single-hit attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Soil Gorget.
-- Aligned with the Soil Belt.
-- Element: None
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
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;
params.atkmulti = 1.25;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
Toeler/AuctionHouseRunes | GeminiAddon/GeminiAddon.lua | 9 | 24902 | --- GeminiAddon-1.1
-- Formerly DaiAddon
-- Inspired by AceAddon
-- Modules and packages embeds are based heavily on AceAddon's functionally, so credit goes their authors.
--
-- Allows the addon to have modules
-- Allows for packages to be embedded (if supported) into the addon and it's modules
--
-- The core callbacks have been "renamed" for consumption that are used when creating an addon:
-- OnLoad -> OnInitialize
--
-- New callback:
-- OnEnable - Called when the character has been loaded and is in the world. Called after OnInitialize and after Restore would have occured
--
-- General flow should be:
-- OnInitialize -> OnEnable
local MAJOR, MINOR = "Gemini:Addon-1.1", 4
local APkg = Apollo.GetPackage(MAJOR)
if APkg and (APkg.nVersion or 0) >= MINOR then
return -- no upgrade is needed
end
local GeminiAddon = APkg and APkg.tPackage or {}
-- Upvalues
local error, type, tostring, select, pairs = error, type, tostring, select, pairs
local setmetatable, getmetatable, xpcall = setmetatable, getmetatable, xpcall
local assert, loadstring, rawset, next, unpack = assert, loadstring, rawset, next, unpack
local tinsert, tremove, ostime = table.insert, table.remove, os.time
-- Package tables
GeminiAddon.Addons = GeminiAddon.Addons or {} -- addon collection
GeminiAddon.AddonStatus = GeminiAddon.AddonStatus or {} -- status of addons
GeminiAddon.Timers = GeminiAddon.Timers or {} -- Timers for OnEnable
local mtGenTable = { __index = function(tbl, key) tbl[key] = {} return tbl[key] end }
-- per addon lists
GeminiAddon.Embeds = GeminiAddon.Embeds or setmetatable({}, mtGenTable)
GeminiAddon.InitializeQueue = GeminiAddon.InitializeQueue or setmetatable({}, mtGenTable) -- addons that are new and not initialized
GeminiAddon.EnableQueue = GeminiAddon.EnableQueue or setmetatable({}, mtGenTable) -- addons awaiting to be enabled
-- Check if the player unit is available
local function IsPlayerInWorld()
return GameLib.GetPlayerUnit() ~= nil
end
local tLibError = Apollo.GetPackage("Gemini:LibError-1.0")
local fnErrorHandler = tLibError and tLibError.tPackage and tLibError.tPackage.Error or Print
-- xpcall safecall implementation
local function CreateDispatcher(argCount)
local code = [[
local xpcall, eh = ...
local method, ARGS
local function call() return method(ARGS) end
local function dispatch(func, ...)
method = func
if not method then return end
ARGS = ...
return xpcall(call, eh)
end
return dispatch
]]
local ARGS = {}
for i = 1, argCount do ARGS[i] = "arg"..i end
code = code:gsub("ARGS", table.concat(ARGS, ", "))
return assert(loadstring(code, "safecall Dispatcher[" .. argCount .. "]"))(xpcall, fnErrorHandler)
end
local Dispatchers = setmetatable({}, {__index=function(self, argCount)
local dispatcher = CreateDispatcher(argCount)
rawset(self, argCount, dispatcher)
return dispatcher
end})
Dispatchers[0] = function(func)
return xpcall(func, fnErrorHandler)
end
local function safecall(func, ...)
if type(func) == "function" then
return Dispatchers[select('#', ...)](func, ...)
end
end
local function AddonToString(self)
return self.Name
end
local Enable, Disable, Embed, GetName, SetEnabledState, AddonLog
local EmbedModule, EnableModule, DisableModule, NewModule, GetModule, SetDefaultModulePrototype, SetDefaultModuleState, SetDefaultModulePackages
-- delay the firing the OnEnable callback until after Character is in world
-- and OnRestore would have occured
local function DelayedEnable(oAddon)
local strName = oAddon:GetName()
if GameLib.GetPlayerUnit() == nil then
-- If the Player Unit doesn't exist we wait for the CharacterCreated event instead
GeminiAddon.Timers[strName] = nil
Apollo.RegisterEventHandler("CharacterCreated", "___OnDelayEnable", oAddon)
return
end
local tEnableQueue = GeminiAddon.EnableQueue[strName]
while #tEnableQueue > 0 do
local oAddonToEnable = tremove(tEnableQueue, 1)
GeminiAddon:EnableAddon(oAddonToEnable)
end
-- Cleanup
GeminiAddon.EnableQueue[strName] = nil
GeminiAddon.Timers[strName] = nil
Apollo.RemoveEventHandler("CharacterCreated", oAddon)
oAddon.___OnDelayEnable = nil
end
local function NewAddonProto(strInitAddon, oAddonOrName, oNilOrName)
local oAddon, strAddonName
-- get addon name
if type(oAddonOrName) == "table" then
oAddon = oAddonOrName
strAddonName = oNilOrName
else
strAddonName = oAddonOrName
end
oAddon = oAddon or {}
oAddon.Name = strAddonName
-- use existing metatable if exists
local addonmeta = {}
local oldmeta = getmetatable(oAddon)
if oldmeta then
for k,v in pairs(oldmeta) do addonmeta[k] = v end
end
addonmeta.__tostring = AddonToString
setmetatable(oAddon, addonmeta)
-- setup addon skeleton
GeminiAddon.Addons[strAddonName] = oAddon
oAddon.Modules = {}
oAddon.OrderedModules = {}
oAddon.DefaultModulePackages = {}
-- Embed any packages that are needed
Embed( oAddon )
-- Add to Queue of Addons to be Initialized during OnLoad
tinsert(GeminiAddon.InitializeQueue[strInitAddon], oAddon)
return oAddon
end
-- Create a new addon using GeminiAddon
-- The final addon object will be returned.
-- @paramsig [object, ] strAddonName, bOnConfigure[, tDependencies][, strPkgName, ...]
-- @param object Table to use as the base for the addon (optional)
-- @param strAddonName Name of the addon object to create
-- @param bOnConfigure Add a button to the options list and fire OnConfigure when clicked. Instead of issuing true, you can pass custom text for the button.
-- @param tDependencies List of dependencies for the addon
-- @param strPkgName List of packages to embed into the addon - requires the packages to be registered with Apollo.RegisterPackage and for the packages to support embedding
-- @usage
-- -- Create a simple addon
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon", false)
--
-- -- Create a simple addon with a configure button with custom text
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon", "Addon Options Button")
--
-- -- Create a simple addon with a configure button and a dependency on ChatLog / ChatLogEx
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon", true, { "ChatLog", "ChatLogEx" })
--
-- -- Create an addon with a base object
-- local tAddonBase = { config = { ... some default settings ... }, ... }
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon(tAddonBase, "MyAddon", false)
--
-- -- Create an addon with a base object with a dependency on ChatLog / ChatLogEx
-- local tAddonBase = { config = { ... some default settings ... }, ... }
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon(tAddonBase, "MyAddon", false, { "ChatLog", "ChatLogEx" })
function GeminiAddon:NewAddon(oAddonOrName, ...)
local oAddon, strAddonName
local oNilOrName = nil
local i = 1
-- get addon name
if type(oAddonOrName) == "table" then
strAddonName = ...
oNilOrName = strAddonName
i = 2
else
strAddonName = oAddonOrName
end
if type(strAddonName) ~= "string" then
error(("Usage: NewAddon([object, ] strAddonName, bOnConfigure[, tDependencies][, strPkgName, ...]): 'strAddonName' - string expected got '%s'."):format(type(strAddonName)), 2)
end
if self.Addons[strAddonName] then
error(("Usage: NewAddon([object, ] strAddonName, bOnConfigure[, tDependencies][, strPkgName, ...]): 'strAddonName' - Addon '%s' already registered in GeminiAddon."):format(strAddonName), 2)
end
-- get configure state
local strConfigBtnName = select(i, ...)
i = i + 1
local bConfigure = (strConfigBtnName == true or type(strConfigBtnName) == "string")
if bConfigure then
strConfigBtnName = type(strConfigBtnName) == "boolean" and strAddonName or strConfigBtnName
else
strConfigBtnName = ""
end
-- get dependencies
local tDependencies
if select(i,...) and type(select(i, ...)) == "table" then
tDependencies = select(i, ...)
i = i + 1
else
tDependencies = {}
end
local oAddon = NewAddonProto(strAddonName, oAddonOrName, oNilOrName)
self:EmbedPackages(oAddon, select(i, ...))
-- Setup callbacks for the addon
-- Setup the OnLoad callback handler to initialize the addon
-- and delay enable the addon
oAddon.OnLoad = function(self)
local strName = self:GetName()
local tInitQueue = GeminiAddon.InitializeQueue[strName]
while #tInitQueue > 0 do
local oAddonToInit = tremove(tInitQueue, 1)
local retVal = GeminiAddon:InitializeAddon(oAddonToInit)
if retVal ~= nil then
Apollo.AddAddonErrorText(self, retVal)
return retVal
end
tinsert(GeminiAddon.EnableQueue[strName], oAddonToInit)
end
GeminiAddon.InitializeQueue[strName] = nil
self.___OnDelayEnable = function() DelayedEnable(self) end
-- Wait 0 seconds (hah?) this allows OnRestore to have occured
GeminiAddon.Timers[strName] = ApolloTimer.Create(0, false, "___OnDelayEnable",self)
end
-- Register with Apollo
Apollo.RegisterAddon(oAddon, bConfigure, strConfigBtnName, tDependencies)
return oAddon
end
-- Get the addon object by its name from the internal GeminiAddon addon registry
-- Throws an error if the addon object cannot be found (except if silent is set)
-- @param strAddonName the addon name registered with GeminiAddon
-- @param bSilent return nil if addon is not found instead of throwing an error
-- @usage
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:GetAddon("MyAddon")
function GeminiAddon:GetAddon(strAddonName, bSilent)
if not bSilent and not self.Addons[strAddonName] then
error(("Usage: GetAddon(strAddonName): 'strAddonName' - Cannot find an GeminiAddon called '%s'."):format(tostring(strAddonName)), 2)
end
return self.Addons[strAddonName]
end
--- Enable the addon
-- Used internally when the player has entered the world
--
-- **Note:** do not call this manually
-- @param oAddon addon object to enable
function GeminiAddon:EnableAddon(oAddon)
if type(oAddon) == "string" then
oAddon = self:GetAddon(oAddon)
end
local strAddonName = AddonToString(oAddon)
if self.AddonStatus[strAddonName] or not oAddon.EnabledState then
return false
end
self.AddonStatus[strAddonName] = true
safecall(oAddon.OnEnable, oAddon)
if self.AddonStatus[strAddonName] then
-- embed packages
local tEmbeds = self.Embeds[oAddon]
for i = 1, #tEmbeds do
local APkg = Apollo.GetPackage(tEmbeds[i])
local oPkg = APkg and APkg.tPackage or nil
if oPkg then
safecall(oPkg.OnEmbedEnable, oPkg, oAddon)
end
end
-- enable modules
local tModules = oAddon.OrderedModules
for i = 1, #tModules do
self:EnableAddon(tModules[i])
end
end
return self.AddonStatus[strAddonName]
end
function GeminiAddon:DisableAddon(oAddon)
if type(oAddon) == "string" then
oAddon = self:GetAddon(oAddon)
end
local strAddonName = AddonToString(oAddon)
if not self.AddonStatus[strAddonName] then
return false
end
safecall( oAddon.OnDisable, oAddon )
if self.AddonStatus[strAddonName] then
local tEmbeds = self.Embeds[oAddon]
for i = 1, #tEmbeds do
local APkg = Apollo.GetPackage(tEmbeds[i])
local oPkg = APkg and APkg.tPackage or nil
if oPkg then
safecall(oPkg.OnEmbedDisable, oPkg, oAddon)
end
end
local tModules = oAddon.OrderedModules
for i = 1, #tModules do
oAddon:DisableModule(tModules[i])
end
end
return not self.AddonStatus[strAddonName]
end
--- Initialize the addon after creation
-- Used internally when OnLoad is called for the addon
--
-- **Note:** do not call this manually
-- @param oAddon addon object to initialize
function GeminiAddon:InitializeAddon(oAddon)
local _, retVal = safecall(oAddon.OnInitialize, oAddon)
if retVal ~= nil then return retVal end
local tEmbeds = self.Embeds[oAddon]
for i = 1, #tEmbeds do
local APkg = Apollo.GetPackage(tEmbeds[i])
local oPkg = APkg and APkg.tPackage or nil
if oPkg then
local _, retVal = safecall(oPkg.OnEmbedInitialize, oPkg, oAddon)
if retVal ~= nil then return retVal end
end
end
end
--- Embed packages into the specified addon
-- @paramsig oAddon[, strPkgName, ...]
-- @param oAddon The addon object to embed packages in
-- @param strPkgName List of packages to embed into the addon
function GeminiAddon:EmbedPackages(oAddon, ...)
for i = 1, select('#', ...) do
local strPkgName = select(i, ...)
self:EmbedPackage(oAddon, strPkgName, false, 4)
end
end
--- Embed a package into the specified addon
--
-- **Note:** This function is for internal use by :EmbedPackages
-- @paramsig strAddonName, strPkgName[, silent[, offset]]
-- @param oAddon addon object to embed the package in
-- @param strPkgName name of the package to embed
-- @param bSilent marks an embed to fail silently if the package doesn't exist (optional)
-- @param nOffset will push the error messages back to said offset, defaults to 2 (optional)
function GeminiAddon:EmbedPackage(oAddon, strPkgName, bSilent, nOffset)
local APkg = Apollo.GetPackage(strPkgName)
local oPkg = APkg and APkg.tPackage or nil
if not oPkg and not bSilent then
error(("Usage: EmbedPackage(oAddon, strPkgName, bSilent, nOffset): 'strPkgName' - Cannot find a package instance of '%s'."):format(tostring(strPkgName)), nOffset or 2)
elseif oPkg and type(oPkg.Embed) == "function" then
oPkg:Embed(oAddon)
tinsert(self.Embeds[oAddon], strPkgName)
return true
elseif oPkg then
error(("Usage: EmbedPackage(oAddon, strPkgName, bSilent, nOffset): Package '%s' is not Embed capable."):format(tostring(strPkgName)), nOffset or 2)
end
end
--- Return the specified module from an addon object.
-- Throws an error if the addon object cannot be found (except if silent is set)
-- @name //addon//:GetModule
-- @paramsig strModuleName[, bSilent]
-- @param strModuleName unique name of the module
-- @param bSilent if true, the module is optional, silently return nil if its not found (optional)
-- @usage
-- local MyModule = MyAddon:GetModule("MyModule")
function GetModule(self, strModuleName, bSilent)
if not self.Modules[strModuleName] and not bSilent then
error(("Usage: GetModule(strModuleName, bSilent): 'strModuleName' - Cannot find module '%s'."):format(tostring(strModuleName)), 2)
end
return self.Modules[strModuleName]
end
local function IsModuleTrue(self) return true end
--- Create a new module for the addon.
-- The new module can have its own embedded packages and/or use a module prototype to be mixed into the module.
-- @name //addon//:NewModule
-- @paramsig strName[, oPrototype|strPkgName[, strPkgName, ...]]
-- @param strName unique name of the module
-- @param oPrototype object to derive this module from, methods and values from this table will be mixed into the module (optional)
-- @param strPkgName List of packages to embed into the module
-- @usage
-- -- Create a module with some embeded packages
-- local MyModule = MyAddon:NewModule("MyModule", "PkgWithEmbed-1.0", "PkgWithEmbed2-1.0")
--
-- -- Create a module with a prototype
-- local oPrototype = { OnEnable = function(self) Print("OnEnable called!") end }
-- local MyModule = MyAddon:NewModule("MyModule", oPrototype, "PkgWithEmbed-1.0", "PkgWithEmbed2-1.0")
function NewModule(self, strName, oPrototype, ...)
if type(strName) ~= "string" then error(("Usage: NewModule(strName, [oPrototype, [strPkgName, strPkgName, strPkgName, ...]): 'strName' - string expected got '%s'."):format(type(strName)), 2) end
if type(oPrototype) ~= "string" and type(oPrototype) ~= "table" and type(oPrototype) ~= "nil" then error(("Usage: NewModule(strName, [oPrototype, [strPkgName, strPkgName, strPkgName, ...]): 'oPrototype' - table (oPrototype), string (strPkgName) or nil expected got '%s'."):format(type(oPrototype)), 2) end
if self.Modules[strName] then error(("Usage: NewModule(strName, [oPrototype, [strPkgName, strPkgName, strPkgName, ...]): 'strName' - Module '%s' already exists."):format(strName), 2) end
-- Go up the family tree to find the addon that started it all
local oCurrParent, oNextParent = self, self.Parent
while oNextParent do
oCurrParent = oNextParent
oNextParent = oCurrParent.Parent
end
local oModule = NewAddonProto(oCurrParent:GetName(), string.format("%s_%s", self:GetName() or tostring(self), strName))
oModule.IsModule = IsModuleTrue
oModule:SetEnabledState(self.DefaultModuleState)
oModule.ModuleName = strName
oModule.Parent = self
if type(oPrototype) == "string" then
GeminiAddon:EmbedPackages(oModule, oPrototype, ...)
else
GeminiAddon:EmbedPackages(oModule, ...)
end
GeminiAddon:EmbedPackages(oModule, unpack(self.DefaultModulePackages))
if not oPrototype or type(oPrototype) == "string" then
oPrototype = self.DefaultModulePrototype or nil
--self:_Log("Using Prototype type: " .. tostring(oPrototype))
end
if type(oPrototype) == "table" then
local mt = getmetatable(oModule)
mt.__index = oPrototype
setmetatable(oModule, mt)
end
safecall(self.OnModuleCreated, self, oModule)
self.Modules[strName] = oModule
tinsert(self.OrderedModules, oModule)
return oModule
end
--- returns the name of the addon or module without any prefix
-- @name //addon|module//:GetName
-- @paramsig
-- @usage
-- Print(MyAddon:GetName())
-- Print(MyAddon:GetModule("MyModule"):GetName())
function GetName(self)
return self.ModuleName or self.Name
end
-- Check if the addon is queued to be enabled
local function QueuedForInitialization(oAddon)
for strAddonName, tAddonList in pairs(GeminiAddon.EnableQueue) do
for nIndex = 1, #tAddonList do
if tAddonList[nIndex] == oAddon then
return true
end
end
end
return false
end
--- Enables the addon, if possible, returns true on success.
-- This internally calls GeminiAddon:EnableAddon(), thus dispatching the OnEnable callback
-- and enabling all modules on the addon (unless explicitly disabled)
-- :Enable() also sets the internal `enableState` variable to true.
-- @name //addon//:Enable
-- @paramsig
-- @usage
function Enable(self)
self:SetEnabledState(true)
if not QueuedForInitialization(self) then
return GeminiAddon:EnableAddon(self)
end
end
function Disable(self)
self:SetEnabledState(false)
return GeminiAddon:DisableAddon(self)
end
--- Enables the Module, if possible, return true or false depending on success.
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Enable` on the module object.
-- @name //addon//:EnableModule
-- @paramsig name
-- @usage
-- -- Enable MyModule using :GetModule
-- local MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Enable()
--
-- -- Enable MyModule using the short-hand
-- MyAddon:EnableModule("MyModule")
function EnableModule(self, strModuleName)
local oModule = self:GetModule(strModuleName)
return oModule:Enable()
end
--- Disables the Module, if possible, return true or false depending on success.
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Disable` on the module object.
-- @name //addon//:DisableModule
-- @paramsig name
-- @usage
-- -- Disable MyModule using :GetModule
-- local MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Disable()
--
-- -- Disable MyModule using the short-hand
-- local MyAddon:DisableModule("MyModule")
function DisableModule(self, strModuleName)
local oModule = self:GetModule(strModuleName)
return oModule:Disable()
end
--- Set the default packages to be mixed into all modules created by this object.
-- Note that you can only change the default module packages before any module is created.
-- @name //addon//:SetDefaultModulePackages
-- @paramsig strPkgName[, strPkgName, ...]
-- @param strPkgName List of Packages to embed into the addon
-- @usage
-- -- Create the addon object
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon")
-- -- Configure default packages for modules
-- MyAddon:SetDefaultModulePackages("MyEmbeddablePkg-1.0")
-- -- Create a module
-- local MyModule = MyAddon:NewModule("MyModule")
function SetDefaultModulePackages(self, ...)
if next(self.Modules) then
error("Usage: SetDefaultModulePackages(...): cannot change the module defaults after a module has been registered.", 2)
end
self.DefaultModulePackages = {...}
end
--- Set the default state in which new modules are being created.
-- Note that you can only change the default state before any module is created.
-- @name //addon//:SetDefaultModuleState
-- @paramsig state
-- @param state Default state for new modules, true for enabled, false for disabled
-- @usage
-- -- Create the addon object
-- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon")
-- -- Set the default state to "disabled"
-- MyAddon:SetDefaultModuleState(false)
-- -- Create a module and explicilty enable it
-- local MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
function SetDefaultModuleState(self, bState)
if next(self.Modules) then
error("Usage: SetDefaultModuleState(bState): cannot change the module defaults after a module has been registered.", 2)
end
self.DefaultModuleState = bState
end
--- Set the default prototype to use for new modules on creation.
-- Note that you can only change the default prototype before any module is created.
-- @name //addon//:SetDefaultModulePrototype
-- @paramsig prototype
-- @param prototype Default prototype for the new modules (table)
-- @usage
-- -- Define a prototype
-- local prototype = { OnEnable = function(self) Print("OnEnable called!") end }
-- -- Set the default prototype
-- MyAddon:SetDefaultModulePrototype(prototype)
-- -- Create a module and explicitly Enable it
-- local MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
-- -- should Print "OnEnable called!" now
-- @see NewModule
function SetDefaultModulePrototype(self, tPrototype)
if next(self.Modules) then
error("Usage: SetDefaultModulePrototype(tPrototype): cannot change the module defaults after a module has been registered.", 2)
end
if type(tPrototype) ~= "table" then
error(("Usage: SetDefaultModulePrototype(tPrototype): 'tPrototype' - table expected got '%s'."):format(type(tPrototype)), 2)
end
self.DefaultModulePrototype = tPrototype
end
--- Set the state of an addon or module
-- This should only be called before any enabling actually happened, e.g. in/before OnInitialize.
-- @name //addon|module//:SetEnabledState
-- @paramsig state
-- @param state the state of an addon or module (enabled = true, disabled = false)
function SetEnabledState(self, bState)
self.EnabledState = bState
end
--- Return an iterator of all modules associated to the addon.
-- @name //addon//:IterateModules
-- @paramsig
-- @usage
-- -- Enable all modules
-- for strModuleName, oModule in MyAddon:IterateModules() do
-- oModule:Enable()
-- end
local function IterateModules(self) return pairs(self.Modules) end
-- Returns an iterator of all embeds in the addon
-- @name //addon//:IterateEmbeds
-- @paramsig
local function IterateEmbeds(self) return pairs(GeminiAddon.Embeds[self]) end
--- Query the enabledState of an addon.
-- @name //addon//:IsEnabled
-- @paramsig
-- @usage
-- if MyAddon:IsEnabled() then
-- MyAddon:Disable()
-- end
local function IsEnabled(self) return self.EnabledState end
local function IsModule(self) return false end
function AddonLog(self, t)
self._DebugLog = self._DebugLog or {}
tinsert(self._DebugLog, { what = t, when = ostime() })
end
local tMixins = {
NewModule = NewModule,
GetModule = GetModule,
Enable = Enable,
Disable = Disable,
EnableModule = EnableModule,
DisableModule = DisableModule,
IsEnabled = IsEnabled,
SetDefaultModulePackages = SetDefaultModulePackages,
SetDefaultModuleState = SetDefaultModuleState,
SetDefaultModulePrototype = SetDefaultModulePrototype,
SetEnabledState = SetEnabledState,
IterateModules = IterateModules,
IterateEmbeds = IterateEmbeds,
GetName = GetName,
-- _Log = AddonLog,
DefaultModuleState = true,
EnabledState = true,
IsModule = IsModule,
}
-- Embed( target )
-- target (object) - target GeminiAddon object to embed in
--
-- **Note:** This is for internal use only. Do not call manually
function Embed(target)
for k, v in pairs(tMixins) do
target[k] = v
end
end
--- Get an iterator over all registered addons.
-- @usage
-- -- Print a list of all registered GeminiAddons
-- for name, addon in GeminiAddon:IterateAddons() do
-- Print("Addon: " .. name)
-- end
function GeminiAddon:IterateAddons() return pairs(self.Addons) end
--- Get an iterator over the internal status registry.
-- @usage
-- -- Print a list of all enabled addons
-- for name, status in GeminiAddon:IterateAddonStatus() do
-- if status then
-- Print("EnabledAddon: " .. name)
-- end
-- end
function GeminiAddon:IterateAddonStatus() return pairs(self.AddonStatus) end
function GeminiAddon:OnLoad() end
function GeminiAddon:OnDependencyError(strDep, strError) return false end
Apollo.RegisterPackage(GeminiAddon, MAJOR, MINOR, {})
| mit |
everslick/awesome | lib/gears/color.lua | 4 | 10697 | ---------------------------------------------------------------------------
-- @author Uli Schlachter
-- @copyright 2010 Uli Schlachter
-- @release @AWESOME_VERSION@
-- @module gears.color
---------------------------------------------------------------------------
local setmetatable = setmetatable
local string = string
local table = table
local unpack = unpack or table.unpack -- v5.1: unpack, v5.2: table.unpack
local tonumber = tonumber
local ipairs = ipairs
local pairs = pairs
local type = type
local cairo = require("lgi").cairo
local surface = require("gears.surface")
local color = { mt = {} }
local pattern_cache
--- Parse a HTML-color.
-- This function can parse colors like `#rrggbb` and `#rrggbbaa`.
-- Thanks to #lua for this. :)
--
-- @param col The color to parse
-- @return 4 values which each are in the range [0, 1].
-- @usage -- This will return 0, 1, 0, 1
-- gears.color.parse_color("#00ff00ff")
function color.parse_color(col)
local rgb = {}
for pair in string.gmatch(col, "[^#].") do
local i = tonumber(pair, 16)
if i then
table.insert(rgb, i / 255)
end
end
while #rgb < 4 do
table.insert(rgb, 1)
end
return unpack(rgb)
end
--- Find all numbers in a string
--
-- @tparam string s The string to parse
-- @return Each number found as a separate value
local function parse_numbers(s)
local res = {}
for k in string.gmatch(s, "-?[0-9]+[.]?[0-9]*") do
table.insert(res, tonumber(k))
end
return unpack(res)
end
--- Create a solid pattern
--
-- @param col The color for the pattern
-- @return A cairo pattern object
function color.create_solid_pattern(col)
local col = col
if col == nil then
col = "#000000"
elseif type(col) == "table" then
col = col.color
end
return cairo.Pattern.create_rgba(color.parse_color(col))
end
--- Create an image pattern from a png file
--
-- @param file The filename of the file
-- @return a cairo pattern object
function color.create_png_pattern(file)
local file = file
if type(file) == "table" then
file = file.file
end
local image = surface.load(file)
local pattern = cairo.Pattern.create_for_surface(image)
pattern:set_extend(cairo.Extend.REPEAT)
return pattern
end
--- Add stops to the given pattern.
-- @param p The cairo pattern to add stops to
-- @param iterator An iterator that returns strings. Each of those strings
-- should be in the form place,color where place is in [0, 1].
local function add_iterator_stops(p, iterator)
for k in iterator do
local sub = string.gmatch(k, "[^,]+")
local point, clr = sub(), sub()
p:add_color_stop_rgba(point, color.parse_color(clr))
end
end
--- Add a list of stops to a given pattern
local function add_stops_table(pat, arg)
for _, stop in ipairs(arg) do
pat:add_color_stop_rgba(stop[1], color.parse_color(stop[2]))
end
end
--- Create a pattern from a string
local function string_pattern(creator, arg)
local iterator = string.gmatch(arg, "[^:]+")
-- Create a table where each entry is a number from the original string
local args = { parse_numbers(iterator()) }
local to = { parse_numbers(iterator()) }
-- Now merge those two tables
for k, v in pairs(to) do
table.insert(args, v)
end
-- And call our creator function with the values
local p = creator(unpack(args))
add_iterator_stops(p, iterator)
return p
end
--- Create a linear pattern object.
-- The pattern is created from a string. This string should have the following
-- form: `"x0, y0:x1, y1:<stops>"`
-- Alternatively, the pattern can be specified as a table:
-- { type = "linear", from = { x0, y0 }, to = { x1, y1 },
-- stops = { <stops> } }
-- `x0,y0` and `x1,y1` are the start and stop point of the pattern.
-- For the explanation of `<stops>`, see `color.create_pattern`.
-- @tparam string|table arg The argument describing the pattern.
-- @return a cairo pattern object
function color.create_linear_pattern(arg)
local pat
if type(arg) == "string" then
return string_pattern(cairo.Pattern.create_linear, arg)
elseif type(arg) ~= "table" then
error("Wrong argument type: " .. type(arg))
end
pat = cairo.Pattern.create_linear(arg.from[1], arg.from[2], arg.to[1], arg.to[2])
add_stops_table(pat, arg.stops)
return pat
end
--- Create a radial pattern object.
-- The pattern is created from a string. This string should have the following
-- form: `"x0, y0, r0:x1, y1, r1:<stops>"`
-- Alternatively, the pattern can be specified as a table:
-- { type = "radial", from = { x0, y0, r0 }, to = { x1, y1, r1 },
-- stops = { <stops> } }
-- `x0,y0` and `x1,y1` are the start and stop point of the pattern.
-- `r0` and `r1` are the radii of the start / stop circle.
-- For the explanation of `<stops>`, see `color.create_pattern`.
-- @tparam string|table arg The argument describing the pattern
-- @return a cairo pattern object
function color.create_radial_pattern(arg)
local pat
if type(arg) == "string" then
return string_pattern(cairo.Pattern.create_radial, arg)
elseif type(arg) ~= "table" then
error("Wrong argument type: " .. type(arg))
end
pat = cairo.Pattern.create_radial(arg.from[1], arg.from[2], arg.from[3],
arg.to[1], arg.to[2], arg.to[3])
add_stops_table(pat, arg.stops)
return pat
end
--- Mapping of all supported color types. New entries can be added.
color.types = {
solid = color.create_solid_pattern,
png = color.create_png_pattern,
linear = color.create_linear_pattern,
radial = color.create_radial_pattern
}
--- Create a pattern from a given string.
-- For full documentation of this function, please refer to
-- `color.create_pattern`. The difference between `color.create_pattern`
-- and this function is that this function does not insert the generated
-- objects into the pattern cache. Thus, you are allowed to modify the
-- returned object.
-- @see create_pattern
-- @param col The string describing the pattern.
-- @return a cairo pattern object
function color.create_pattern_uncached(col)
-- If it already is a cairo pattern, just leave it as that
if cairo.Pattern:is_type_of(col) then
return col
end
local col = col or "#000000"
if type(col) == "string" then
local t = string.match(col, "[^:]+")
if color.types[t] then
local pos = string.len(t)
local arg = string.sub(col, pos + 2)
return color.types[t](arg)
end
elseif type(col) == "table" then
local t = col.type
if color.types[t] then
return color.types[t](col)
end
end
return color.create_solid_pattern(col)
end
--- Create a pattern from a given string.
-- This function can create solid, linear, radial and png patterns. In general,
-- patterns are specified as strings formatted as"type:arguments". "arguments"
-- is specific to the pattern used. For example, one can use
-- "radial:50,50,10:55,55,30:0,#ff0000:0.5,#00ff00:1,#0000ff"
-- Alternatively, patterns can be specified via tables. In this case, the
-- table's 'type' member specifies the type. For example:
-- { type = "radial", from = { 50, 50, 10 }, to = { 55, 55, 30 },
-- stops = { { 0, "#ff0000" }, { 0.5, "#00ff00" }, { 1, "#0000ff" } } }
-- Any argument that cannot be understood is passed to @{create_solid_pattern}.
--
-- Please note that you MUST NOT modify the returned pattern, for example by
-- calling :set_matrix() on it, because this function uses a cache and your
-- changes could thus have unintended side effects. Use @{create_pattern_uncached}
-- if you need to modify the returned pattern.
-- @see create_pattern_uncached, create_solid_pattern, create_png_pattern,
-- create_linear_pattern, create_radial_pattern
-- @param col The string describing the pattern.
-- @return a cairo pattern object
function color.create_pattern(col)
-- If it already is a cairo pattern, just leave it as that
if cairo.Pattern:is_type_of(col) then
return col
end
return pattern_cache:get(col or "#000000")
end
--- Check if a pattern is opaque.
-- A pattern is transparent if the background on which it gets drawn (with
-- operator OVER) doesn't influence the visual result.
-- @param col An argument that `create_pattern` accepts.
-- @return The pattern if it is surely opaque, else nil
function color.create_opaque_pattern(col)
local pattern = color.create_pattern(col)
local type = pattern:get_type()
local extend = pattern:get_extend()
if type == "SOLID" then
local status, r, g, b, a = pattern:get_rgba()
if a ~= 1 then
return
end
return pattern
elseif type == "SURFACE" then
local status, surface = pattern:get_surface()
if status ~= "SUCCESS" or surface.content ~= "COLOR" then
-- The surface has an alpha channel which *might* be non-opaque
return
end
-- Only the "NONE" extend mode is forbidden, everything else doesn't
-- introduce transparent parts
if pattern:get_extend() == "NONE" then
return
end
return pattern
elseif type == "LINEAR" then
local status, stops = pattern:get_color_stop_count()
-- No color stops or extend NONE -> pattern *might* contain transparency
if stops == 0 or pattern:get_extend() == "NONE" then
return
end
-- Now check if any of the color stops contain transparency
for i = 0, stops - 1 do
local status, offset, r, g, b, a = pattern:get_color_stop_rgba(i)
if a ~= 1 then
return
end
end
return pattern
end
-- Unknown type, e.g. mesh or raster source or unsupported type (radial
-- gradients can do weird self-intersections)
end
--- Fill non-transparent area of an image with a given color.
-- @param image Image or path to it.
-- @param new_color New color.
-- @return Recolored image.
function color.recolor_image(image, new_color)
if type(image) == 'string' then
image = surface.duplicate_surface(image)
end
local cr = cairo.Context.create(image)
cr:set_source(color.create_pattern(new_color))
cr:mask(cairo.Pattern.create_for_surface(image), 0, 0)
return image
end
function color.mt:__call(...)
return color.create_pattern(...)
end
pattern_cache = require("gears.cache").new(color.create_pattern_uncached)
return setmetatable(color, color.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
Sonicrich05/FFXI-Server | scripts/zones/FeiYin/npcs/Underground_Pool.lua | 17 | 2322 | -----------------------------------
-- Area: FeiYin
-- NPC: Underground Pool
-- Involved In Quest: Scattered into Shadow
-- @pos 7 0 32 204 (H-8)
-- @pos 7 0 247 204 (H-5)
-- @pos -168 0 247 204 (F-5)
-----------------------------------
package.loaded["scripts/zones/FeiYin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/FeiYin/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(JEUNO,SCATTERED_INTO_SHADOW) == QUEST_ACCEPTED) then
local npcID = npc:getID();
local aquaKI1 = player:hasKeyItem(AQUAFLORA1);
local aquaKI2 = player:hasKeyItem(AQUAFLORA2);
local aquaKI3 = player:hasKeyItem(AQUAFLORA3);
local Z = player:getZPos();
local X = player:getXPos();
if ((Z > 20 and Z < 40) and (X > -.3 and X < 19.7) and (aquaKI1)) then
player:startEvent(0x0015);
elseif ((Z > 242 and Z < 256) and (X > -2 and X < 16) and (aquaKI2)) then
player:startEvent(0x0014);
elseif ((Z > 239 and Z < 259) and (X > -180 and X < -160) and (aquaKI3)) then
if (player:getVar("DabotzKilled") == 1) then
player:startEvent(0x0012);
else
SpawnMob(17613129,300):updateClaim(player);
end
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
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);
if (csid == 0x0015) then
player:delKeyItem(AQUAFLORA1);
elseif (csid == 0x0014) then
player:delKeyItem(AQUAFLORA2);
elseif (csid == 0x0012) then
player:delKeyItem(AQUAFLORA3);
player:setVar("DabotzKilled",0);
end
end; | gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/globals/effects/dark_arts.lua | 74 | 1952 | -----------------------------------
--
--
--
-----------------------------------
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:recalculateAbilitiesTable();
local bonus = effect:getPower();
local helix = effect:getSubPower();
target:addMod(MOD_BLACK_MAGIC_COST, -bonus);
target:addMod(MOD_BLACK_MAGIC_CAST, -bonus);
target:addMod(MOD_BLACK_MAGIC_RECAST, -bonus);
if not (target:hasStatusEffect(EFFECT_TABULA_RASA)) then
target:addMod(MOD_BLACK_MAGIC_COST, -10);
target:addMod(MOD_BLACK_MAGIC_CAST, -10);
target:addMod(MOD_BLACK_MAGIC_RECAST, -10);
target:addMod(MOD_WHITE_MAGIC_COST, 20);
target:addMod(MOD_WHITE_MAGIC_CAST, 20);
target:addMod(MOD_WHITE_MAGIC_RECAST, 20);
target:addMod(MOD_HELIX_EFFECT, helix);
target:addMod(MOD_HELIX_DURATION, 72);
end
target:recalculateSkillsTable();
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
target:recalculateAbilitiesTable();
local bonus = effect:getPower();
local helix = effect:getSubPower();
target:delMod(MOD_BLACK_MAGIC_COST, -bonus);
target:delMod(MOD_BLACK_MAGIC_CAST, -bonus);
target:delMod(MOD_BLACK_MAGIC_RECAST, -bonus);
if not (target:hasStatusEffect(EFFECT_TABULA_RASA)) then
target:delMod(MOD_BLACK_MAGIC_COST, -10);
target:delMod(MOD_BLACK_MAGIC_CAST, -10);
target:delMod(MOD_BLACK_MAGIC_RECAST, -10);
target:delMod(MOD_WHITE_MAGIC_COST, 20);
target:delMod(MOD_WHITE_MAGIC_CAST, 20);
target:delMod(MOD_WHITE_MAGIC_RECAST, 20);
target:delMod(MOD_HELIX_EFFECT, helix);
target:delMod(MOD_HELIX_DURATION, 72);
end
target:recalculateSkillsTable();
end; | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/West_Ronfaure/npcs/qm1.lua | 2 | 1448 | -----------------------------------
-- Area: West Ronfaure
-- NPC: ???
-- @zone: 100
-- @pos: -453 -20 -230
--
-- Involved in Quest: The Dismayed Customer
-----------------------------------
package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/zones/West_Ronfaure/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(SANDORIA, THE_DISMAYED_CUSTOMER) == QUEST_ACCEPTED and player:getVar("theDismayedCustomer") == 1) then
player:addKeyItem(GULEMONTS_DOCUMENT);
player:messageSpecial(KEYITEM_OBTAINED, GULEMONTS_DOCUMENT);
player:setVar("theDismayedCustomer", 0);
else
player:messageSpecial(DISMAYED_CUSTOMER);
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 |
fw867/ntopng | scripts/lua/inc/sankey.lua | 1 | 8602 | --
-- (C) 2014 - ntop.org
--
ifstats = interface.getStats()
print [[
<div id = "alert_placeholder"></div>
<style>
#chart {
height: 380px;
}
.node rect {
cursor: move;
fill-opacity: .9;
shape-rendering: crispEdges;
}
.node text {
pointer-events: none;
text-shadow: 0 1px 0 #fff;
}
.link {
fill: none;
stroke: #000;
stroke-opacity: .2;
}
.link:hover {
stroke-opacity: .5;
}
</style>
<div id="chart"></div>
<script src="/js/sankey.js"></script>
<script>
]]
-- Create javascript vlan boolean variable
if (ifstats.iface_vlan) then print("var iface_vlan = true;") else print("var iface_vlan = false;") end
print [[
var margin = {top: 1, right: 1, bottom: 6, left: 1},
width = 800 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
function b2s(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return 'n/a';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};
function sankey() {
var formatNumber = d3.format(",.0f"),
format = function(sent, rcvd) { return "[sent: "+b2s(sent)+", rcvd: "+b2s(rcvd)+"]"; },
color = d3.scale.category20();
]]
-- Default value
active_sankey = "host"
local debug = false
if(_GET["sprobe"] ~= nil) then
print('d3.json("/lua/sprobe_hosts_data.lua"');
else
if(_GET["host"] ~= nil) then
print('d3.json("/lua/iface_flows_sankey.lua?ifname='..ifname..'&' ..hostinfo2url(host_info).. '"')
elseif((_GET["hosts"] ~= nil) and (_GET["aggregation"] ~= nil)) then
print('d3.json("/lua/hosts_comparison_sankey.lua?ifname='..ifname..'&'..'hosts='.._GET["hosts"] .. '&aggregation='.._GET["aggregation"] ..'"')
active_sankey = "comparison"
elseif(_GET["hosts"] ~= nil) then
print('d3.json("/lua/hosts_comparison_sankey.lua?ifname='..ifname..'&'..'hosts='.._GET["hosts"] ..'"')
active_sankey = "comparison"
else
print('d3.json("/lua/iface_flows_sankey.lua"')
end
end
if (debug) then io.write("Active sankey: "..active_sankey.."\n") end
print [[
, function(hosts) {
if ((hosts.links.length == 0) && (hosts.nodes.length == 0)) {
$('#alert_placeholder').html('<div class="alert alert-warning"><button type="button" class="close" data-dismiss="alert">x</button><strong>Warning: </strong>There are no talkers for the current host.</div>');
return;
}
d3.select("#chart").select("svg").remove();
var svg_sankey = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var sankey = d3.sankey()
.nodeWidth(15)
.nodePadding(10)
.size([width, height]);
var path = sankey.link();
sankey
.nodes(hosts.nodes)
.links(hosts.links)
.layout(32);
]]
if (active_sankey == "host") then
print [[
/* Color the link according to traffic prevalence */
var colorlink = function(d){
if (d.sent > d.rcvd) return color(d.source.name);
else return color(d.target.name);
}
var link = svg_sankey.append("g").selectAll(".link")
.data(hosts.links)
.enter().append("path")
.attr("class", "link")
.attr("d", path)
.style("stroke-width", function(d) { return Math.max(1, d.dy); })
.style("stroke", function(d){ return d.color = colorlink(d); })
.sort(function(a, b) { return b.dy - a.dy; })
.on("dblclick", function(d) {
url_ref = "/lua/hosts_comparison.lua?hosts="+escape(d.source.host);
if(iface_vlan )
url_ref += "@"+escape(d.source.vlan);
url_ref += ","+escape(d.target.host);
if(iface_vlan )
url_ref += "@"+escape(d.target.vlan);
window.location.href = url_ref;
});
link.append("title")
.text(function(d) { return d.source.name + " - " + d.target.name + "\n" + format(d.sent, d.rcvd) + "\n Double click to show more information about the flows between this two host." ; });
var node = svg_sankey.append("g").selectAll(".node")
.data(hosts.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.call(d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", function() { this.parentNode.appendChild(this); })
.on("drag", dragmove));
node.append("rect")
.attr("height", function(d) { return d.dy; })
.attr("width", sankey.nodeWidth())
.style("fill", function(d) { return d.color = color(d.name.replace(/ .*/, "")); })
.style("stroke", function(d) { return d3.rgb(d.color).darker(2); })
.append("title")
.text(function(d) { return d.name + "\n" + format(d.value); });
/* Hook for clicking on host name */
node.append("rect")
.attr("x", -4 -100)
.attr("y", function(d) { return (d.dy/2)-7; })
.attr("height", 12)
.attr("width", 150)
.style("opacity", "0")
.on("click", function(d) { window.location.href = "/lua/host_details.lua?host="+escape(d.host)+"@"+escape(d.vlan); })
.attr("transform", null)
.filter(function(d) { return d.x < width / 2; })
.attr("x", 4 + sankey.nodeWidth())
.append("title")
.text(function(d) { return "Host: " + d.host + "\nVlan: " + d.vlan});
node.append("text")
.attr("x", -6)
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "end")
.attr("transform", null)
.text(function(d) { return (d.name); })
.filter(function(d) { return d.x < width / 2; })
.attr("x", 6 + sankey.nodeWidth())
.attr("text-anchor", "start");
]]
elseif(active_sankey == "comparison") then
ifstats = interface.getStats()
if(ifstats.iface_sprobe) then
url = "/lua/sflows_stats.lua?"
else
url = "/lua/flows_stats.lua?"
end
print [[
/* Color the link according to traffic volume */
var colorlink = function(d){
return color(d.value);
}
var link = svg_sankey.append("g").selectAll(".link")
.data(hosts.links)
.enter().append("path")
.attr("class", "link")
.attr("d", path)
.style("stroke-width", function(d) { return Math.max(1, d.dy); })
.style("stroke", function(d){ return d.color = colorlink(d); })
.sort(function(a, b) { return b.dy - a.dy; })
.on("dblclick", function(d) { window.location.href = "]]
print(url.."hosts=".._GET["hosts"])
print [[&aggregation="+escape(d.aggregation)+"&key="+escape(d.target.name) ; });
link.append("title")
.text(function(d) { return d.source.name + " - " + d.target.name + "\n" + bytesToVolume(d.value)+ "\n Double click to show more information about this flows." ; });
var node = svg_sankey.append("g").selectAll(".node")
.data(hosts.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.call(d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", function() { this.parentNode.appendChild(this); })
.on("drag", dragmove));
node.append("rect")
.attr("height", function(d) { return d.dy; })
.attr("width", sankey.nodeWidth())
.style("fill", function(d) { return d.color = color(d.name.replace(/ .*/, "")); })
.style("stroke", function(d) { return d3.rgb(d.color).darker(2); })
.append("title")
.text(function(d) {
return (d.name);
});
/* Hook for clicking on host name */
node.append("rect")
.attr("x", -4 -100)
.attr("y", function(d) { return (d.dy/2)-7; })
.attr("height", 12)
.attr("width", 150)
.style("opacity", "0")
.attr("transform", null)
.filter(function(d) { return d.x < width / 2; })
.attr("x", 4 + sankey.nodeWidth())
.append("title")
.text(function(d) { return "Ip: " + d.ip + " Vlan: " + d.vlan});
node.append("text")
.attr("x", -6)
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "end")
.attr("transform", null)
.text(function(d) {
return (d.name);
})
.filter(function(d) { return d.x < width / 2; })
.attr("x", 6 + sankey.nodeWidth())
.attr("text-anchor", "start");
]]
end
print [[
function dragmove(d) {
d3.select(this).attr("transform", "translate(" + d.x + "," + (d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))) + ")");
sankey.relayout();
link.attr("d", path);
}
});
}
sankey();
// Refresh every 5 seconds
var sankey_interval = window.setInterval(sankey, 5000);
</script>]]
print [[
]] | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Port_Windurst/npcs/Pichichi.lua | 6 | 2580 | -----------------------------------
-- Area: Port Windurst
-- NPC: Pichichi
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY);
KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS);
InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET);
OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS);
CryingOverOnions = player:getQuestStatus(WINDURST,CRYING_OVER_ONIONS);
ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE);
if (ThePromise == QUEST_COMPLETED) then
Message = math.random(0,1)
if (Message == 1) then
player:startEvent(0x0212);
else
player:startEvent(0x0218);
end
elseif (CryingOverOnions == QUEST_COMPLETED) then
player:startEvent(0x01ff);
elseif (CryingOverOnions == QUEST_ACCEPTED) then
player:startEvent(0x01f7);
elseif (OnionRings == QUEST_COMPLETED) then
player:startEvent(0x01bd);
elseif (OnionRings == QUEST_ACCEPTED ) then
player:startEvent(0x01b6);
elseif (InspectorsGadget == QUEST_COMPLETED) then
player:startEvent(0x01a7);
elseif (InspectorsGadget == QUEST_ACCEPTED) then
player:startEvent(0x019f);
elseif (KnowOnesOnions == QUEST_COMPLETED) then
player:startEvent(0x019b);
elseif (KnowOnesOnions == QUEST_ACCEPTED) then
KnowOnesOnionsVar = player:getVar("KnowOnesOnions");
if (KnowOnesOnionsVar == 2) then
player:startEvent(0x019a);
else
player:startEvent(0x018b);
end
elseif (TruthJusticeOnionWay == QUEST_COMPLETED) then
player:startEvent(0x0181);
elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then
player:startEvent(0x0176);
else
player:startEvent(0x016c);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
fw867/ntopng | scripts/lua/sprobe_hosts_interactions_data.lua | 3 | 1516 | --
-- (C) 2013-14 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
sendHTTPHeader('application/json')
interface.find(ifname)
flows_stats = interface.getFlowsInfo()
links = {}
processes = {}
for key, value in pairs(flows_stats) do
flow = flows_stats[key]
if(flow["cli.host"] ~= nil) then c = flow["cli.host"] else c = flow["cli.ip"] end
if(flow["srv.host"] ~= nil) then s = flow["srv.host"] else s = flow["srv.ip"] end
c = c .. "@" .. flow["cli.source_id"]
s = s .. "@" .. flow["srv.source_id"]
if(flow["client_process"] ~= nil) then
if(links[c] == nil) then links[c] = {} end
links[c]["peer"] = s
if(links[c]["num"] == nil) then links[c]["num"] = 0 end
links[c]["num"] = links[c]["num"] + 1
end
if(flow["server_process"] ~= nil) then
if(links[s] == nil) then links[s] = {} end
links[s]["peer"] = c
if(links[s]["num"] == nil) then links[s]["num"] = 0 end
end
end
print("[")
n = 0
for key, value in pairs(links) do
if(n > 0) then print(",") end
print('\n{"source": "'..key..'", "source_num": '.. links[key]["num"]..', "source_type": "host", "source_pid": -1, "source_name": "'..ntop.getResolvedAddress(key)..'", "target": "'..value["peer"]..'", "target_num": '.. value["num"]..', "target_type": "host", "target_pid": -1, "target_name": "'.. ntop.getResolvedAddress(value["peer"])..'", "type": "host2host"}')
n = n + 1
end
print("\n]\n")
| gpl-3.0 |
projectbismark/luci-bismark | libs/core/luasrc/util.lua | 7 | 22046 | --[[
LuCI - Utility library
Description:
Several common useful Lua functions
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local io = require "io"
local math = require "math"
local table = require "table"
local debug = require "debug"
local ldebug = require "luci.debug"
local string = require "string"
local coroutine = require "coroutine"
local tparser = require "luci.template.parser"
local getmetatable, setmetatable = getmetatable, setmetatable
local rawget, rawset, unpack = rawget, rawset, unpack
local tostring, type, assert = tostring, type, assert
local ipairs, pairs, loadstring = ipairs, pairs, loadstring
local require, pcall, xpcall = require, pcall, xpcall
local collectgarbage, get_memory_limit = collectgarbage, get_memory_limit
--- LuCI utility functions.
module "luci.util"
--
-- Pythonic string formatting extension
--
getmetatable("").__mod = function(a, b)
if not b then
return a
elseif type(b) == "table" then
for k, _ in pairs(b) do if type(b[k]) == "userdata" then b[k] = tostring(b[k]) end end
return a:format(unpack(b))
else
if type(b) == "userdata" then b = tostring(b) end
return a:format(b)
end
end
--
-- Class helper routines
--
-- Instantiates a class
local function _instantiate(class, ...)
local inst = setmetatable({}, {__index = class})
if inst.__init__ then
inst:__init__(...)
end
return inst
end
--- Create a Class object (Python-style object model).
-- The class object can be instantiated by calling itself.
-- Any class functions or shared parameters can be attached to this object.
-- Attaching a table to the class object makes this table shared between
-- all instances of this class. For object parameters use the __init__ function.
-- Classes can inherit member functions and values from a base class.
-- Class can be instantiated by calling them. All parameters will be passed
-- to the __init__ function of this class - if such a function exists.
-- The __init__ function must be used to set any object parameters that are not shared
-- with other objects of this class. Any return values will be ignored.
-- @param base The base class to inherit from (optional)
-- @return A class object
-- @see instanceof
-- @see clone
function class(base)
return setmetatable({}, {
__call = _instantiate,
__index = base
})
end
--- Test whether the given object is an instance of the given class.
-- @param object Object instance
-- @param class Class object to test against
-- @return Boolean indicating whether the object is an instance
-- @see class
-- @see clone
function instanceof(object, class)
local meta = getmetatable(object)
while meta and meta.__index do
if meta.__index == class then
return true
end
meta = getmetatable(meta.__index)
end
return false
end
--
-- Scope manipulation routines
--
local tl_meta = {
__mode = "k",
__index = function(self, key)
local t = rawget(self, coxpt[coroutine.running()]
or coroutine.running() or 0)
return t and t[key]
end,
__newindex = function(self, key, value)
local c = coxpt[coroutine.running()] or coroutine.running() or 0
if not rawget(self, c) then
rawset(self, c, { [key] = value })
else
rawget(self, c)[key] = value
end
end
}
--- Create a new or get an already existing thread local store associated with
-- the current active coroutine. A thread local store is private a table object
-- whose values can't be accessed from outside of the running coroutine.
-- @return Table value representing the corresponding thread local store
function threadlocal(tbl)
return setmetatable(tbl or {}, tl_meta)
end
--
-- Debugging routines
--
--- Write given object to stderr.
-- @param obj Value to write to stderr
-- @return Boolean indicating whether the write operation was successful
function perror(obj)
return io.stderr:write(tostring(obj) .. "\n")
end
--- Recursively dumps a table to stdout, useful for testing and debugging.
-- @param t Table value to dump
-- @param maxdepth Maximum depth
-- @return Always nil
function dumptable(t, maxdepth, i, seen)
i = i or 0
seen = seen or setmetatable({}, {__mode="k"})
for k,v in pairs(t) do
perror(string.rep("\t", i) .. tostring(k) .. "\t" .. tostring(v))
if type(v) == "table" and (not maxdepth or i < maxdepth) then
if not seen[v] then
seen[v] = true
dumptable(v, maxdepth, i+1, seen)
else
perror(string.rep("\t", i) .. "*** RECURSION ***")
end
end
end
end
--
-- String and data manipulation routines
--
--- Escapes all occurrences of the given character in given string.
-- @param s String value containing unescaped characters
-- @param c String value with character to escape (optional, defaults to "\")
-- @return String value with each occurrence of character escaped with "\"
function escape(s, c)
c = c or "\\"
return s:gsub(c, "\\" .. c)
end
--- Create valid XML PCDATA from given string.
-- @param value String value containing the data to escape
-- @return String value containing the escaped data
function pcdata(value)
return value and tparser.sanitize_pcdata(tostring(value))
end
--- Strip HTML tags from given string.
-- @param value String containing the HTML text
-- @return String with HTML tags stripped of
function striptags(s)
return pcdata(tostring(s):gsub("</?[A-Za-z][A-Za-z0-9:_%-]*[^>]*>", " "):gsub("%s+", " "))
end
--- Splits given string on a defined separator sequence and return a table
-- containing the resulting substrings. The optional max parameter specifies
-- the number of bytes to process, regardless of the actual length of the given
-- string. The optional last parameter, regex, specifies whether the separator
-- sequence is interpreted as regular expression.
-- @param str String value containing the data to split up
-- @param pat String with separator pattern (optional, defaults to "\n")
-- @param max Maximum times to split (optional)
-- @param regex Boolean indicating whether to interpret the separator
-- pattern as regular expression (optional, default is false)
-- @return Table containing the resulting substrings
function split(str, pat, max, regex)
pat = pat or "\n"
max = max or #str
local t = {}
local c = 1
if #str == 0 then
return {""}
end
if #pat == 0 then
return nil
end
if max == 0 then
return str
end
repeat
local s, e = str:find(pat, c, not regex)
max = max - 1
if s and max < 0 then
t[#t+1] = str:sub(c)
else
t[#t+1] = str:sub(c, s and s - 1)
end
c = e and e + 1 or #str + 1
until not s or max < 0
return t
end
--- Remove leading and trailing whitespace from given string value.
-- @param str String value containing whitespace padded data
-- @return String value with leading and trailing space removed
function trim(str)
return (str:gsub("^%s*(.-)%s*$", "%1"))
end
--- Count the occurences of given substring in given string.
-- @param str String to search in
-- @param pattern String containing pattern to find
-- @return Number of found occurences
function cmatch(str, pat)
local count = 0
for _ in str:gmatch(pat) do count = count + 1 end
return count
end
--- Return a matching iterator for the given value. The iterator will return
-- one token per invocation, the tokens are separated by whitespace. If the
-- input value is a table, it is transformed into a string first. A nil value
-- will result in a valid interator which aborts with the first invocation.
-- @param val The value to scan (table, string or nil)
-- @return Iterator which returns one token per call
function imatch(v)
if v == nil then
v = ""
elseif type(v) == "table" then
v = table.concat(v, " ")
elseif type(v) ~= "string" then
v = tostring(v)
end
return v:gmatch("%S+")
end
--- Parse certain units from the given string and return the canonical integer
-- value or 0 if the unit is unknown. Upper- or lower case is irrelevant.
-- Recognized units are:
-- o "y" - one year (60*60*24*366)
-- o "m" - one month (60*60*24*31)
-- o "w" - one week (60*60*24*7)
-- o "d" - one day (60*60*24)
-- o "h" - one hour (60*60)
-- o "min" - one minute (60)
-- o "kb" - one kilobyte (1024)
-- o "mb" - one megabyte (1024*1024)
-- o "gb" - one gigabyte (1024*1024*1024)
-- o "kib" - one si kilobyte (1000)
-- o "mib" - one si megabyte (1000*1000)
-- o "gib" - one si gigabyte (1000*1000*1000)
-- @param ustr String containing a numerical value with trailing unit
-- @return Number containing the canonical value
function parse_units(ustr)
local val = 0
-- unit map
local map = {
-- date stuff
y = 60 * 60 * 24 * 366,
m = 60 * 60 * 24 * 31,
w = 60 * 60 * 24 * 7,
d = 60 * 60 * 24,
h = 60 * 60,
min = 60,
-- storage sizes
kb = 1024,
mb = 1024 * 1024,
gb = 1024 * 1024 * 1024,
-- storage sizes (si)
kib = 1000,
mib = 1000 * 1000,
gib = 1000 * 1000 * 1000
}
-- parse input string
for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
local num = spec:gsub("[^0-9%.]+$","")
local spn = spec:gsub("^[0-9%.]+", "")
if map[spn] or map[spn:sub(1,1)] then
val = val + num * ( map[spn] or map[spn:sub(1,1)] )
else
val = val + num
end
end
return val
end
-- also register functions above in the central string class for convenience
string.escape = escape
string.pcdata = pcdata
string.striptags = striptags
string.split = split
string.trim = trim
string.cmatch = cmatch
string.parse_units = parse_units
--- Appends numerically indexed tables or single objects to a given table.
-- @param src Target table
-- @param ... Objects to insert
-- @return Target table
function append(src, ...)
for i, a in ipairs({...}) do
if type(a) == "table" then
for j, v in ipairs(a) do
src[#src+1] = v
end
else
src[#src+1] = a
end
end
return src
end
--- Combines two or more numerically indexed tables and single objects into one table.
-- @param tbl1 Table value to combine
-- @param tbl2 Table value to combine
-- @param ... More tables to combine
-- @return Table value containing all values of given tables
function combine(...)
return append({}, ...)
end
--- Checks whether the given table contains the given value.
-- @param table Table value
-- @param value Value to search within the given table
-- @return Boolean indicating whether the given value occurs within table
function contains(table, value)
for k, v in pairs(table) do
if value == v then
return k
end
end
return false
end
--- Update values in given table with the values from the second given table.
-- Both table are - in fact - merged together.
-- @param t Table which should be updated
-- @param updates Table containing the values to update
-- @return Always nil
function update(t, updates)
for k, v in pairs(updates) do
t[k] = v
end
end
--- Retrieve all keys of given associative table.
-- @param t Table to extract keys from
-- @return Sorted table containing the keys
function keys(t)
local keys = { }
if t then
for k, _ in kspairs(t) do
keys[#keys+1] = k
end
end
return keys
end
--- Clones the given object and return it's copy.
-- @param object Table value to clone
-- @param deep Boolean indicating whether to do recursive cloning
-- @return Cloned table value
function clone(object, deep)
local copy = {}
for k, v in pairs(object) do
if deep and type(v) == "table" then
v = clone(v, deep)
end
copy[k] = v
end
return setmetatable(copy, getmetatable(object))
end
--- Create a dynamic table which automatically creates subtables.
-- @return Dynamic Table
function dtable()
return setmetatable({}, { __index =
function(tbl, key)
return rawget(tbl, key)
or rawget(rawset(tbl, key, dtable()), key)
end
})
end
-- Serialize the contents of a table value.
function _serialize_table(t, seen)
assert(not seen[t], "Recursion detected.")
seen[t] = true
local data = ""
local idata = ""
local ilen = 0
for k, v in pairs(t) do
if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then
k = serialize_data(k, seen)
v = serialize_data(v, seen)
data = data .. ( #data > 0 and ", " or "" ) ..
'[' .. k .. '] = ' .. v
elseif k > ilen then
ilen = k
end
end
for i = 1, ilen do
local v = serialize_data(t[i], seen)
idata = idata .. ( #idata > 0 and ", " or "" ) .. v
end
return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data
end
--- Recursively serialize given data to lua code, suitable for restoring
-- with loadstring().
-- @param val Value containing the data to serialize
-- @return String value containing the serialized code
-- @see restore_data
-- @see get_bytecode
function serialize_data(val, seen)
seen = seen or setmetatable({}, {__mode="k"})
if val == nil then
return "nil"
elseif type(val) == "number" then
return val
elseif type(val) == "string" then
return "%q" % val
elseif type(val) == "boolean" then
return val and "true" or "false"
elseif type(val) == "function" then
return "loadstring(%q)" % get_bytecode(val)
elseif type(val) == "table" then
return "{ " .. _serialize_table(val, seen) .. " }"
else
return '"[unhandled data type:' .. type(val) .. ']"'
end
end
--- Restore data previously serialized with serialize_data().
-- @param str String containing the data to restore
-- @return Value containing the restored data structure
-- @see serialize_data
-- @see get_bytecode
function restore_data(str)
return loadstring("return " .. str)()
end
--
-- Byte code manipulation routines
--
--- Return the current runtime bytecode of the given data. The byte code
-- will be stripped before it is returned.
-- @param val Value to return as bytecode
-- @return String value containing the bytecode of the given data
function get_bytecode(val)
local code
if type(val) == "function" then
code = string.dump(val)
else
code = string.dump( loadstring( "return " .. serialize_data(val) ) )
end
return code -- and strip_bytecode(code)
end
--- Strips unnescessary lua bytecode from given string. Information like line
-- numbers and debugging numbers will be discarded. Original version by
-- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
-- @param code String value containing the original lua byte code
-- @return String value containing the stripped lua byte code
function strip_bytecode(code)
local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
local subint
if endian == 1 then
subint = function(code, i, l)
local val = 0
for n = l, 1, -1 do
val = val * 256 + code:byte(i + n - 1)
end
return val, i + l
end
else
subint = function(code, i, l)
local val = 0
for n = 1, l, 1 do
val = val * 256 + code:byte(i + n - 1)
end
return val, i + l
end
end
local function strip_function(code)
local count, offset = subint(code, 1, size)
local stripped = { string.rep("\0", size) }
local dirty = offset + count
offset = offset + count + int * 2 + 4
offset = offset + int + subint(code, offset, int) * ins
count, offset = subint(code, offset, int)
for n = 1, count do
local t
t, offset = subint(code, offset, 1)
if t == 1 then
offset = offset + 1
elseif t == 4 then
offset = offset + size + subint(code, offset, size)
elseif t == 3 then
offset = offset + num
elseif t == 254 or t == 9 then
offset = offset + lnum
end
end
count, offset = subint(code, offset, int)
stripped[#stripped+1] = code:sub(dirty, offset - 1)
for n = 1, count do
local proto, off = strip_function(code:sub(offset, -1))
stripped[#stripped+1] = proto
offset = offset + off - 1
end
offset = offset + subint(code, offset, int) * int + int
count, offset = subint(code, offset, int)
for n = 1, count do
offset = offset + subint(code, offset, size) + size + int * 2
end
count, offset = subint(code, offset, int)
for n = 1, count do
offset = offset + subint(code, offset, size) + size
end
stripped[#stripped+1] = string.rep("\0", int * 3)
return table.concat(stripped), offset
end
return code:sub(1,12) .. strip_function(code:sub(13,-1))
end
--
-- Sorting iterator functions
--
function _sortiter( t, f )
local keys = { }
for k, v in pairs(t) do
keys[#keys+1] = k
end
local _pos = 0
table.sort( keys, f )
return function()
_pos = _pos + 1
if _pos <= #keys then
return keys[_pos], t[keys[_pos]]
end
end
end
--- Return a key, value iterator which returns the values sorted according to
-- the provided callback function.
-- @param t The table to iterate
-- @param f A callback function to decide the order of elements
-- @return Function value containing the corresponding iterator
function spairs(t,f)
return _sortiter( t, f )
end
--- Return a key, value iterator for the given table.
-- The table pairs are sorted by key.
-- @param t The table to iterate
-- @return Function value containing the corresponding iterator
function kspairs(t)
return _sortiter( t )
end
--- Return a key, value iterator for the given table.
-- The table pairs are sorted by value.
-- @param t The table to iterate
-- @return Function value containing the corresponding iterator
function vspairs(t)
return _sortiter( t, function (a,b) return t[a] < t[b] end )
end
--
-- System utility functions
--
--- Test whether the current system is operating in big endian mode.
-- @return Boolean value indicating whether system is big endian
function bigendian()
return string.byte(string.dump(function() end), 7) == 0
end
--- Execute given commandline and gather stdout.
-- @param command String containing command to execute
-- @return String containing the command's stdout
function exec(command)
local pp = io.popen(command)
local data = pp:read("*a")
pp:close()
return data
end
--- Return a line-buffered iterator over the output of given command.
-- @param command String containing the command to execute
-- @return Iterator
function execi(command)
local pp = io.popen(command)
return pp and function()
local line = pp:read()
if not line then
pp:close()
end
return line
end
end
-- Deprecated
function execl(command)
local pp = io.popen(command)
local line = ""
local data = {}
while true do
line = pp:read()
if (line == nil) then break end
data[#data+1] = line
end
pp:close()
return data
end
--- Returns the absolute path to LuCI base directory.
-- @return String containing the directory path
function libpath()
return require "nixio.fs".dirname(ldebug.__file__)
end
--
-- Coroutine safe xpcall and pcall versions modified for Luci
-- original version:
-- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
--
-- Copyright © 2005 Kepler Project.
-- 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 performResume, handleReturnValue
local oldpcall, oldxpcall = pcall, xpcall
coxpt = {}
setmetatable(coxpt, {__mode = "kv"})
-- Identity function for copcall
local function copcall_id(trace, ...)
return ...
end
--- This is a coroutine-safe drop-in replacement for Lua's "xpcall"-function
-- @param f Lua function to be called protected
-- @param err Custom error handler
-- @param ... Parameters passed to the function
-- @return A boolean whether the function call succeeded and the return
-- values of either the function or the error handler
function coxpcall(f, err, ...)
local res, co = oldpcall(coroutine.create, f)
if not res then
local params = {...}
local newf = function() return f(unpack(params)) end
co = coroutine.create(newf)
end
local c = coroutine.running()
coxpt[co] = coxpt[c] or c or 0
return performResume(err, co, ...)
end
--- This is a coroutine-safe drop-in replacement for Lua's "pcall"-function
-- @param f Lua function to be called protected
-- @param ... Parameters passed to the function
-- @return A boolean whether the function call succeeded and the returns
-- values of the function or the error object
function copcall(f, ...)
return coxpcall(f, copcall_id, ...)
end
-- Handle return value of protected call
function handleReturnValue(err, co, status, ...)
if not status then
return false, err(debug.traceback(co, (...)), ...)
end
if coroutine.status(co) ~= 'suspended' then
return true, ...
end
return performResume(err, co, coroutine.yield(...))
end
-- Resume execution of protected function call
function performResume(err, co, ...)
return handleReturnValue(err, co, coroutine.resume(co, ...))
end
| apache-2.0 |
Sonicrich05/FFXI-Server | scripts/zones/Buburimu_Peninsula/npcs/Hieroglyphics.lua | 17 | 2420 | -----------------------------------
-- Area: Buburimu_Peninsula
-- NPC: Hieroglyphics
-- Dynamis Buburimu_Dunes Enter
-- @pos 117 -10 133 172 118
-----------------------------------
package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/dynamis");
require("scripts/globals/missions");
require("scripts/zones/Buburimu_Peninsula/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasCompletedMission(COP,DARKNESS_NAMED) or FREE_COP_DYNAMIS == 1) then
local firstDyna = 0;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if (checkFirstDyna(player,8)) then
player:startEvent(0x002B);
elseif (player:getMainLvl() < DYNA_LEVEL_MIN) then
player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN);
elseif ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaBuburimu]UniqueID")) then
player:startEvent(0x0016,8,0,0,BETWEEN_2DYNA_WAIT_TIME,32,VIAL_OF_SHROUDED_SAND,4236,4237);
else
dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456);
--printf("dayRemaining : %u",dayRemaining );
player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,8);
end
else
player:messageSpecial(MYSTERIOUS_VOICE);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("updateRESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("finishRESULT: %u",option);
if (csid == 0x0021) then
if (checkFirstDyna(player,8)) then
player:setVar("Dynamis_Status",player:getVar("Dynamis_Status") + 256);
end
elseif (csid == 0x0016 and option == 0) then
player:setPos(155,-1,-169,170,0x28);
end
end; | gpl-3.0 |
projectbismark/luci-bismark | applications/luci-statistics/luasrc/model/cbi/luci_statistics/interface.lua | 2 | 1249 | --[[
Luci configuration model for statistics - collectd interface plugin configuration
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
m = Map("luci_statistics",
translate("Interface Plugin Configuration"),
translate(
"The interface plugin collects traffic statistics on " ..
"selected interfaces."
))
-- collectd_interface config section
s = m:section( NamedSection, "collectd_interface", "luci_statistics" )
-- collectd_interface.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_interface.interfaces (Interface)
interfaces = s:option( MultiValue, "Interfaces" )
interfaces.widget = "select"
interfaces.size = 5
interfaces:depends( "enable", 1 )
for k, v in pairs(luci.sys.net.devices()) do
interfaces:value(v)
end
-- collectd_interface.ignoreselected (IgnoreSelected)
ignoreselected = s:option( Flag, "IgnoreSelected" )
ignoreselected.default = 0
ignoreselected:depends( "enable", 1 )
return m
| apache-2.0 |
adminerror/erererererer | plugins/id.lua | 17 | 4403 | do
local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
local function scan_name(extra, success, result)
local founds = {}
for k,member in pairs(result.members) do
local fields = {'first_name', 'print_name', 'username'}
for k,field in pairs(fields) do
if member[field] and type(member[field]) == 'string' then
if member[field]:match(extra.user) then
local id = tostring(member.id)
founds[id] = member
end
end
end
end
if next(founds) == nil then -- Empty table
send_msg(extra.receiver, extra.user..' not found on this chat.', ok_cb, false)
else
local text = ''
for k,user in pairs(founds) do
local first_name = user.first_name or ''
local print_name = user.print_name or ''
local user_name = user.user_name or ''
local id = user.id or '' -- This would be funny
text = text..'First name: '..first_name..'\n'
..'Print name: '..print_name..'\n'
..'User name: '..user_name..'\n'
..'ID: '..id..'\n\n'
end
send_msg(extra.receiver, text, ok_cb, false)
end
end
local function res_user_callback(extra, success, result)
if success == 1 then
send_msg(extra.receiver, 'ID for '..extra.user..' is: '..result.id, ok_cb, false)
else
send_msg(extra.receiver, extra.user..' not found on this chat.', ok_cb, false)
end
end
local function action_by_reply(extra, success, result)
local text = 'Name : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n'
..'User name: @'..(result.from.username or '')..'\n'
..'ID : '..result.from.id
send_msg(extra.receiver, text, ok_cb, true)
end
local function returnids(extra, success, result)
local text = '['..result.id..'] '..result.title..'.\n'
..result.members_num..' members.\n\n'
i = 0
for k,v in pairs(result.members) do
i = i+1
if v.last_name then
last_name = ' '..v.last_name
else
last_name = ''
end
if v.username then
user_name = ' @'..v.username
else
user_name = ''
end
text = text..i..'. ['..v.id..'] '..user_name..' '..v.first_name..last_name..'\n'
end
send_large_msg(extra.receiver, text)
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local user = matches[1]
local text = 'ID for '..user..' is: '
if msg.to.type == 'chat' then
if msg.text == '!id' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver})
else
local text = 'Name : '..(msg.from.first_name or '')..' '..(msg.from.last_name or '')..'\n'
..'ID : ' .. msg.from.id
local text = text..'\n\nYou are in group '
..msg.to.title..' (ID: '..msg.to.id..')'
return text
end
elseif matches[1] == 'chat' then
if matches[2] and is_sudo(msg) then
local chat = 'chat#id'..matches[2]
chat_info(chat, returnids, {receiver=receiver})
else
chat_info(receiver, returnids, {receiver=receiver})
end
elseif string.match(user, '^@.+$') then
username = string.gsub(user, '@', '')
msgr = res_user(username, res_user_callback, {receiver=receiver, user=user, text=text})
else
user = string.gsub(user, ' ', '_')
chat_info(receiver, scan_name, {receiver=receiver, user=user, text=text})
end
else
return 'You are not in a group.'
end
end
return {
description = 'Know your id or the id of a chat members.',
usage = {
'!id: Return your ID and the chat id if you are in one.',
'!id: Return ID of replied user if used by reply.',
'!id chat: Return the IDs of the current chat members.',
'!id chat <chat_id>: Return the IDs of the current <chat_id> members.',
'!id <id>: Return the IDs of the <id>.',
'!id @<user_name>: Return the member @<user_name> ID from the current chat.',
'!id <text>: Search for users with <text> on print_name on current chat.'
},
patterns = {
"^!id$",
"^!id (chat) (%d+)$",
"^!id (.*)$",
"^!id (%d+)$"
},
moderated = true,
run = run
}
end
| gpl-2.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/abilities/pets/stone_iv.lua | 4 | 1119 | ---------------------------------------------------
-- Stone 4
---------------------------------------------------
require("/scripts/globals/settings");
require("/scripts/globals/status");
require("/scripts/globals/monstertpmoves");
require("/scripts/globals/magic");
---------------------------------------------------
function OnAbilityCheck(player, target, ability)
return 0,0;
end;
function OnPetAbility(target, pet, skill)
local spell = getSpell(162);
--calculate raw damage
local dmg = calculateMagicDamage(381,2,pet,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false);
--get resist multiplier (1x if no resist)
local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, 2);
--get the resisted damage
dmg = dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = mobAddBonuses(pet,spell,target,dmg, 2);
--add on TP bonuses
local tp = pet:getTP();
if tp < 100 then
tp = 100;
end
dmg = dmg * tp / 100;
--add in final adjustments
dmg = finalMagicAdjustments(pet,target,spell,dmg);
return dmg;
end | gpl-3.0 |
Servius/tfa-sw-weapons-repository | Live Addons/servius_uploader/[TFA] Extended Pack/lua/weapons/tfa_relby/shared.lua | 1 | 6055 | if ( SERVER ) then
AddCSLuaFile( "shared.lua" )
end
if ( CLIENT ) then
SWEP.PrintName = "Relby-V10"
SWEP.Author = "TFA, Servius"
SWEP.ViewModelFOV = 50
SWEP.Slot = 2
SWEP.SlotPos = 3
end
SWEP.Base = "tfa_3dscoped_base"
SWEP.Category = "TFA Star Wars"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.HoldType = "rpg"
SWEP.ViewModelFOV = 70
SWEP.ViewModelFlip = false
SWEP.ViewModel = "models/weapons/cstrike/c_snip_awp.mdl"
SWEP.WorldModel = "models/weapons/w_dc15sa.mdl"
SWEP.ShowViewModel = true
SWEP.ShowWorldModel = false
SWEP.UseHands = true
SWEP.Primary.Sound = Sound ("weapons/1misc_guns/WPN_LASER_BLASTER_SHOOT_01.ogg");
SWEP.Primary.ReloadSound = Sound ("weapons/shared/battlefront_standard_reload.ogg");
SWEP.Primary.KickUp = 2
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.Recoil = 0.4
SWEP.Primary.Damage = 50
SWEP.Primary.NumShots = 1
SWEP.Primary.Spread = 0.0225
SWEP.Primary.IronAccuracy = .001 -- Ironsight accuracy, should be the same for shotguns
SWEP.Primary.ClipSize = 40
SWEP.Primary.RPM = 325
SWEP.Primary.DefaultClip = 135
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "ar2"
SWEP.SelectiveFire = true --Allow selecting your firemode?
SWEP.DisableBurstFire = false --Only auto/single?
SWEP.OnlyBurstFire = false --No auto, only burst/single?
SWEP.DefaultFireMode = "" --Default to auto or whatev
SWEP.FireModes = {
"Auto",
"2Burst",
"Single"
}
SWEP.FireModeName = nil --Change to a text value to override it
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.Secondary.IronFOV = 70
SWEP.ViewModelBoneMods = {
["v_weapon.awm_parent"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) }
}
SWEP.IronSightsPos = Vector(-7.2, -2.412, 2.24)
SWEP.IronSightsAng = Vector(0, 0, 0)
SWEP.VElements = {
["element_scope"] = { type = "Model", model = "models/rtcircle.mdl", bone = "v_weapon.awm_parent", rel = "", pos = Vector(0, -6.571, 3), angle = Angle(90, 180, 90), size = Vector(0.36, 0.36, 0.36), color = Color(255, 255, 255, 255), surpresslightning = false, material = "!tfa_rtmaterial", skin = 0, bodygroup = {} },
["element_name"] = { type = "Model", model = "models/swbf3/outerrim/weapons/relby-v10.mdl", bone = "v_weapon.awm_parent", rel = "", pos = Vector(0, 4.8, -1.558), angle = Angle(-90, 90, 0), size = Vector(1.274, 1.274, 1.274), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.WElements = {
["element_name"] = { type = "Model", model = "models/swbf3/outerrim/weapons/relby-v10.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(4.675, 0.518, 3.635), angle = Angle(-170, 177, 0), size = Vector(1, 1, 1), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.BlowbackVector = Vector(0,-3,0.025)
SWEP.Blowback_Only_Iron = false
SWEP.DoProceduralReload = false
SWEP.ProceduralReloadTime = 2.5
----Swft Base Code
SWEP.TracerCount = 1
SWEP.MuzzleFlashEffect = ""
SWEP.TracerName = "rw_sw_laser_red"
SWEP.Secondary.IronFOV = 70
SWEP.Primary.KickUp = 0.2
SWEP.Primary.KickDown = 0.1
SWEP.Primary.KickHorizontal = 0.1
SWEP.Primary.KickRight = 0.1
SWEP.DisableChambering = true
SWEP.ImpactDecal = "FadingScorch"
SWEP.ImpactEffect = "effect_sw_impact" --Impact Effect
SWEP.RunSightsPos = Vector(2.127, 0, 1.355)
SWEP.RunSightsAng = Vector(-15.775, 10.023, -5.664)
SWEP.BlowbackEnabled = true
SWEP.BlowbackVector = Vector(0,-3,0.1)
SWEP.Blowback_Shell_Enabled = false
SWEP.Blowback_Shell_Effect = ""
SWEP.ThirdPersonReloadDisable=false
SWEP.Primary.DamageType = DMG_SHOCK
SWEP.DamageType = DMG_SHOCK
--3dScopedBase stuff
SWEP.RTMaterialOverride = 0
SWEP.RTScopeAttachment = -1
SWEP.Scoped_3D = true
SWEP.ScopeReticule = "scope/gdcw_vibrantred_nobar"
SWEP.Secondary.ScopeZoom = 8
SWEP.ScopeReticule_Scale = {2.5,2.5}
SWEP.Secondary.UseACOG = false --Overlay option
SWEP.Secondary.UseMilDot = false --Overlay option
SWEP.Secondary.UseSVD = false --Overlay option
SWEP.Secondary.UseParabolic = false --Overlay option
SWEP.Secondary.UseElcan = false --Overlay option
SWEP.Secondary.UseGreenDuplex = false --Overlay option
if surface then
SWEP.Secondary.ScopeTable = nil --[[
{
scopetex = surface.GetTextureID("scope/gdcw_closedsight"),
reticletex = surface.GetTextureID("scope/gdcw_acogchevron"),
dottex = surface.GetTextureID("scope/gdcw_acogcross")
}
]]--
end
DEFINE_BASECLASS( SWEP.Base )
--[[
SWEP.HoldType = "rpg"
SWEP.ViewModelFOV = 70
SWEP.ViewModelFlip = false
SWEP.UseHands = true
SWEP.ViewModel = "models/weapons/cstrike/c_snip_awp.mdl"
SWEP.WorldModel = "models/weapons/w_dc15sa.mdl"
SWEP.ShowViewModel = true
SWEP.ShowWorldModel = false
SWEP.ViewModelBoneMods = {
["v_weapon.awm_parent"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) }
}
SWEP.IronSightsPos = Vector(-7.401, -2.412, 2.24)
SWEP.IronSightsAng = Vector(0, 0, 0)
SWEP.VElements = {
["element_scope"] = { type = "Model", model = "models/rtcircle.mdl", bone = "v_weapon.awm_parent", rel = "", pos = Vector(0, -6.571, 3), angle = Angle(90, 180, 0), size = Vector(0.33, 0.33, 0.33), color = Color(255, 255, 255, 255), surpresslightning = false, material = "!tfa_rtmaterial", skin = 0, bodygroup = {} },
["element_name"] = { type = "Model", model = "models/swbf3/outerrim/weapons/relby-v10.mdl", bone = "v_weapon.awm_parent", rel = "", pos = Vector(0, 4.8, -1.558), angle = Angle(-90, 90, 0), size = Vector(1.274, 1.274, 1.274), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.WElements = {
["element_name"] = { type = "Model", model = "models/swbf3/outerrim/weapons/relby-v10.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(4.675, 0.518, 3.635), angle = Angle(-170, 177, 0), size = Vector(1, 1, 1), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
]] | apache-2.0 |
Sonicrich05/FFXI-Server | scripts/zones/Port_San_dOria/npcs/Leonora.lua | 17 | 1498 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Leonora
-- Involved in Quest:
-- @zone 232
-- @pos -24 -8 15
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getZPos() >= 12) then
player:startEvent(0x0206);
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 |
RavenX8/osIROSE-new | scripts/mobs/ai/yeti_captain.lua | 2 | 1073 | registerNpc(344, {
walk_speed = 235,
run_speed = 750,
scale = 170,
r_weapon = 1009,
l_weapon = 0,
level = 96,
hp = 41,
attack = 484,
hit = 237,
def = 422,
res = 165,
avoid = 153,
attack_spd = 120,
is_magic_damage = 0,
ai_type = 127,
give_exp = 144,
drop_type = 378,
drop_money = 0,
drop_item = 61,
union_number = 61,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 250,
npc_type = 8,
hit_material_type = 0,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end | apache-2.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/salmon_croute.lua | 3 | 1236 | -----------------------------------------
-- ID: 4551
-- Item: salmon_croute
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP 8
-- MP 8
-- Dexterity 2
-- MP recovered while healing 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,4551);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 8);
target:addMod(MOD_MP, 8);
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 8);
target:delMod(MOD_MP, 8);
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MPHEAL, 1);
end;
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/globals/items/slice_of_lynx_meat.lua | 18 | 1293 | -----------------------------------------
-- ID: 5667
-- Item: Slice of Lynx Meat
-- Food Effect: 5 Min, Galka only
-----------------------------------------
-- Strength 5
-- Intelligence -7
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 8) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_MEAT) == 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,5667);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 5);
target:addMod(MOD_INT, -7);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 5);
target:delMod(MOD_INT, -7);
end;
| gpl-3.0 |
Servius/tfa-sw-weapons-repository | Live Addons/servius_uploader/[TFA][AT] Expanded Pack/lua/weapons/tfa_dl44/shared.lua | 1 | 4797 | if ( SERVER ) then
AddCSLuaFile( "shared.lua" )
end
if ( CLIENT ) then
SWEP.PrintName = "Dl-44"
SWEP.Author = "TFA, Servius"
SWEP.ViewModelFOV = 60
SWEP.Slot = 2
SWEP.SlotPos = 3
end
SWEP.Base = "tfa_3dscoped_base"
SWEP.Category = "TFA Star Wars"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.HoldType = "pistol"
SWEP.ViewModelFOV = 60
SWEP.ViewModelFlip = false
SWEP.ViewModel = "models/weapons/synbf3/c_dh17.mdl"
SWEP.WorldModel = "models/weapons/w_dl44.mdl"
SWEP.ShowViewModel = true
SWEP.ShowWorldModel = false
SWEP.UseHands = true
SWEP.Primary.Sound = Sound ("weapons/dl44/dl44_fire.ogg");
SWEP.Primary.ReloadSound = Sound ("weapons/shared/standard_reload.ogg");
SWEP.Primary.KickUp = 2
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.Recoil = 0.3
SWEP.Primary.Damage = 60
SWEP.Primary.NumShots = 1
SWEP.Primary.Spread = 0.0125
SWEP.Primary.IronAccuracy = .01 -- Ironsight accuracy, should be the same for shotguns
SWEP.Primary.ClipSize = 15
SWEP.Primary.RPM = 200
SWEP.Primary.DefaultClip = 50
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "ar2"
--Fire Mode
SWEP.SelectiveFire = false --Allow selecting your firemode?
SWEP.DisableBurstFire = false --Only auto/single?
SWEP.OnlyBurstFire = false --No auto, only burst/single?
SWEP.DefaultFireMode = "" --Default to auto or whatev
SWEP.FireModeName = nil --Change to a text value to override it
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.Secondary.IronFOV = 70
SWEP.Primary.Range = -1 -- The distance the bullet can travel in source units. Set to -1 to autodetect based on damage/rpm.
SWEP.Primary.RangeFalloff = 0.8 -- The percentage of the range the bullet damage starts to fall off at. Set to 0.8, for example, to start falling off after 80% of the range.
SWEP.IronSightsPos = Vector(-5.4, 3, 2.6)
SWEP.IronSightsAng = Vector(0, 0, 0)
SWEP.ViewModelBoneMods = {
["v_dh17_reference001"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["ValveBiped.Bip01_R_Hand"] = { scale = Vector(1, 1, 1), pos = Vector(-0, 0, 0), angle = Angle(0, 0, 0) }
}
SWEP.WElements = {
["element_name"] = { type = "Model", model = "models/weapons/w_dl44.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(10, 0.4, -4.676), angle = Angle(-10.52, 5.843, 180), size = Vector(0.959, 0.959, 0.959), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.VElements = {
["element_scope"] = { type = "Model", model = "models/rtcircle.mdl", bone = "v_dh17_reference001", rel = "element_reference", pos = Vector(-8.921, 0.289, 1.639), angle = Angle(0, -180, 0), size = Vector(0.27, 0.27, 0.27), color = Color(255, 255, 255, 255), surpresslightning = false, material = "!tfa_rtmaterial", skin = 0, bodygroup = {} },
["element_reference"] = { type = "Model", model = "models/weapons/w_dl44.mdl", bone = "v_dh17_reference001", rel = "", pos = Vector(1, -5, 1.7), angle = Angle(0, 90, 0), size = Vector(0.82, 0.82, 0.82), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.BlowbackVector = Vector(0,-3,0.025)
SWEP.Blowback_Only_Iron = false
SWEP.DoProceduralReload = true
SWEP.ProceduralReloadTime = 2.5
----Swft Base Code
SWEP.TracerCount = 1
SWEP.MuzzleFlashEffect = ""
SWEP.TracerName = "rw_sw_laser_red"
SWEP.Secondary.IronFOV = 70
SWEP.Primary.KickUp = 0.2
SWEP.Primary.KickDown = 0.1
SWEP.Primary.KickHorizontal = 0.1
SWEP.Primary.KickRight = 0.1
SWEP.DisableChambering = true
SWEP.ImpactDecal = "FadingScorch"
SWEP.ImpactEffect = "effect_sw_impact" --Impact Effect
SWEP.RunSightsPos = Vector(2.127, 0, 1.355)
SWEP.RunSightsAng = Vector(-15.775, 10.023, -5.664)
SWEP.BlowbackEnabled = true
SWEP.BlowbackVector = Vector(0,-3,0.1)
SWEP.Blowback_Shell_Enabled = false
SWEP.Blowback_Shell_Effect = ""
SWEP.ThirdPersonReloadDisable=false
SWEP.Primary.DamageType = DMG_SHOCK
SWEP.DamageType = DMG_SHOCK
--3dScopedBase stuff
SWEP.RTMaterialOverride = 0
SWEP.RTScopeAttachment = -1
SWEP.Scoped_3D = true
SWEP.ScopeReticule = "scope/gdcw_red_nobar"
SWEP.Secondary.ScopeZoom = 8
SWEP.ScopeReticule_Scale = {2.5,2.5}
SWEP.Secondary.UseACOG = false --Overlay option
SWEP.Secondary.UseMilDot = false --Overlay option
SWEP.Secondary.UseSVD = false --Overlay option
SWEP.Secondary.UseParabolic = false --Overlay option
SWEP.Secondary.UseElcan = false --Overlay option
SWEP.Secondary.UseGreenDuplex = false --Overlay option
if surface then
SWEP.Secondary.ScopeTable = nil --[[
{
scopetex = surface.GetTextureID("scope/gdcw_closedsight"),
reticletex = surface.GetTextureID("scope/gdcw_acogchevron"),
dottex = surface.GetTextureID("scope/gdcw_acogcross")
}
]]--
end
DEFINE_BASECLASS( SWEP.Base ) | apache-2.0 |
rlowrance/re | parcels-impute-code.lua | 1 | 12504 | -- main program to predict imputed parcel codes
-- COMMAND LINE ARGS:
-- --mPerYear F : hyperparameter kilometers per year
-- --k N : hyperparamater number of neighbors (N >= 2)
-- --lambda F : hyperparameter importance of regularizer
-- --known S : filename for known pairs (apn | features, code)
-- ex: parcels-HEATING.CODE-known-train.pairs
-- --slice N : slice of stdin in to read
-- specify 'all' if running with Hadoop, as Hadoop has
-- already sliced the file
-- specify N if running under linux, to simulate slicing
-- --of M : number of slices --
-- FILES
-- stdin : pairs file (apn | features [,code])
-- code, if present, is ignored
-- can be a slice
-- ex: parcels-HEATING.CODE-known-val.pairs
-- stdout : pairs file (apn | mPerYear, k, lambda, predictedCode)
-- first 3 values are hyperparameters (see other args)
-- predictedCode is string predicted
-- -- parcels-impute-code-<mPerYear>-<k>-<lambda>-log.txt : log file
--
-- Copyright 2013 Roy E. Lowrance
-- Copying permission is given in the file COPYING
require 'distancesSurface'
require 'kernelEpanechnikovQuadraticKnn'
require 'localLogRegNn'
require 'Log'
require 'makeVp'
require 'parseCommandLine'
require 'SliceReader'
require 'standardize'
require 'Timer'
require 'viewAsColumnVector'
-------------------------------------------------------------------------------
-- LOCAL FUNCTIONS
-------------------------------------------------------------------------------
local function parse(arg)
local clArgs = {}
clArgs.mPerYear = tonumber(parseCommandLine(arg, 'value', '--mPerYear'))
validateAttributes(clArgs.mPerYear, 'number', '>=', 0)
clArgs.k = tonumber(parseCommandLine(arg, 'value', '--k'))
validateAttributes(clArgs.k, 'number', 'integer', '>=', 2)
clArgs.lambda = tonumber(parseCommandLine(arg, 'value', '--lambda'))
validateAttributes(clArgs.lambda, 'number', '>=', 0)
clArgs.known = parseCommandLine(arg, 'value', '--known')
validateAttributes(clArgs.known, 'string')
clArgs.slice = tonumber(parseCommandLine(arg, 'value', '--slice'))
validateAttributes(clArgs.slice, 'number', 'integer', '>=', 1)
clArgs.of= tonumber(parseCommandLine(arg, 'value', '--of'))
validateAttributes(clArgs.of, 'number', 'integer', '>=', clArgs.slice)
return clArgs
end
-- return open Log
local function makeLog(clArg, outputDir)
local vp = makeVp(0, 'makeLog')
validateAttributes(clArg, 'table')
validateAttributes(outputDir, 'string')
local args = string.format('%f-%d-%f-%d-%d',
clArg.mPerYear,
clArg.k,
clArg.lambda,
clArg.slice,
clArg.of)
local logFileName = string.format('parcels-imput-code-log-%s.txt',
args)
vp(1, 'logFileName', logFileName)
local log = Log(outputDir .. logFileName)
return log
end
-- extract first 8 numbers from string, return as 1D Tensor
local function extract8numbers(s)
local vp = makeVp(0, 'extract8numbers')
vp(1, 's', s)
local f1,f2,f3,f4,f5,f6,f7,f8 =
string.match(s, '^([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),.*$')
local result = torch.Tensor{tonumber(f1),
tonumber(f2),
tonumber(f3),
tonumber(f4),
tonumber(f5),
tonumber(f6),
tonumber(f7),
tonumber(f8)}
vp(1, 'result', result)
return result
end
-- extract the code (a string), which is in the last position
local function extractCode(s)
local vp = makeVp(0, 'extractCode')
vp(1, 's', s)
local result = string.match(s, '^.*,(.*)$')
vp(1, 'result', result)
return result
end
-- convert sequence of strings to 1D Tensor of integers 1, 2, ...
-- RETURNS
-- tensor : 1D Tensor of integers
-- codeMap : table such that codeMap[integer] = string
local function makeTargets(codes)
local vp = makeVp(0, 'makeTargets')
vp(1, 'codes', codes)
local u = unique(codes)
vp(2, 'u', u)
local map = {}
local codeMap = {}
for i, code in ipairs(u) do
map[code] = i
codeMap[i] = code
end
vp(2, 'map', map)
local result = torch.Tensor(#codes)
for i, code in ipairs(codes) do
result[i] = map[code]
end
vp(2, 'result', result)
vp(2, 'codeMap', codeMap)
return result, codeMap
end
-- split pair (key \t value) into its parts
local function splitPair(s)
local key, value = string.match(s, '^(.*)%\t(.*)$')
return key, value
end
-- read pairs (apn | 8 features [,code])
-- RETURNS
-- features : 2D Tensor
-- codes : sequence of strings
local function readKnown(path, readLimit)
local vp = makeVp(0, 'readKnown')
vp(1, 'path', path)
vp(1, 'readLimit', readLimit)
local nFeatures = 8 -- this is hard-coded later in string.match
local f = io.open(path, 'r')
assert(f, 'unable to open ' .. path)
-- do something with each line in the file
-- return number of records for which action performed
local function forEachLine(action)
local vp = makeVp(0, 'forEachLine')
vp(1, 'action', action)
local f = io.open(path, 'r')
assert(f, 'unable to open ' .. path)
vp(2, 'f', f)
local nRead = 0
local nProcessed = 0
for line in f:lines() do
nRead = nRead + 1
if readLimit > -1 and nRead > readLimit then
break
else
action(nRead, line)
nProcessed = nProcessed + 1
end
end
f:close()
return nProcessed
end
-- pass 1 : count lines == number of rows in result tensor
local nRead = forEachLine(function() end)
-- allocate result tensors
local features = torch.Tensor(nRead, nFeatures)
local codes = {}
vp(2, 'features size', features:size())
-- pass 2 : read and store values in features tensor
local function parseStore(nRead, line)
local vp = makeVp(0, 'parseStore')
vp(1, 'nRead', nRead)
vp(1, 'line', line)
local key, value = splitPair(line)
vp(2, 'key', key)
vp(2, 'value', value)
features[nRead] = extract8numbers(value)
table.insert(codes, extractCode(value))
end
forEachLine(parseStore)
vp(1, 'features', features)
vp(1, 'codes', codes)
return features, codes
end
-- determine if 1D Tensor has any zero values
local function hasNoZeroes(t)
local nZeroes = torch.sum(torch.eq(t, 0))
return nZeroes == 0
end
-- return 1D Tensor of weights
local function getWeights(known, query, clArgs, log)
local vp = makeVp(0, 'getWeights')
vp(1, 'query', query)
vp(1, 'clArgs', clArgs)
vp(1, 'log', log)
validateAttributes(known, 'Tensor', '2d')
validateAttributes(query, 'Tensor', '1d')
validateAttributes(clArgs, 'table') -- contains hyperparameters
validateAttributes(log, 'Log')
local nObs = known:size(1)
-- determine columns with certain features
local function checkColumns(t, columns)
assert(math.abs(t[columns['latitude']] - 33) < 2)
assert(math.abs(t[columns['longitude']] + 118) < 2)
assert(math.abs(t[columns['year']] - 1950) < 50)
end
vp(2,'known[1]', known[1])
local columns = {latitude = 1,
longitude = 2,
year = 3}
checkColumns(known[1], columns)
vp(2, 'query', query)
checkColumns(query, columns)
local distances = distancesSurface(query, known, clArgs.mPerYear, columns)
local weights = kernelEpanechnikovQuadraticKnn(distances, clArgs.k)
local weights = weights / torch.sum(weights) -- weights sum to 1.0
assert(weights:size(1) == nObs)
return weights
end
-- create output record (apns \t hyperparameters, prediction)
local function makeOutputRecord(clArgs, apn, predictionString)
local vp = makeVp(0, 'makeOutputRecord')
vp(1, 'clArgs', clArgs, 'apn', apn, 'predictionString', predictionString)
local s = string.format('%s\t%f,%d,%f,%s\n',
apn,
clArgs.mPerYear,
clArgs.k,
clArgs.lambda,
predictionString)
vp(1, 's', s)
return s
end
-- convert target integer into a code string
local function codeString(prediction, codeMap)
local vp = makeVp(0, 'codeString')
vp(1, 'prediction', prediction, 'codeMap', codeMap)
assert(prediction > 0)
assert(prediction <= #codeMap)
return codeMap[prediction]
end
-------------------------------------------------------------------------------
-- MAIN
-------------------------------------------------------------------------------
local function main()
local vp = makeVp(0, 'main')
torch.manualSeed(123)
local clArgs = parse(arg)
vp(1, 'clArgs', clArgs)
local outputDir = '../data/v6/output/'
local log = makeLog(clArgs, outputDir)
assert(log ~= nil)
log:logTable('clArgs', clArgs)
stop()
local readLimit = -1
--readLimit = 1000 -- while debugging
-- read features (2D Tensor) and targets (seq)
local known, codes = readKnown(clArgs.known, readLimit)
log:log('read %d known features and targets',
known:size(1))
local targets, codeMap = makeTargets(codes) -- convert seq of strings to 1D Tensor
log:log('there are %d unique codes', #codeMap)
vp(2, 'targets head', head(targets), 'codeMap', codeMap)
local targets2D = viewAsColumnVector(targets)
codes = nil
vp(2, 'known')
local stdKnown, means, stddevs = standardize(known) -- center values
vp(2, 'means', means, 'stddevs', stddevs)
assert(hasNoZeroes(stddevs), 'stddevs contain a zero value')
-- predict the code for a specific input record
local nPredictions = 0 -- to trigger garbage collection and reporting
local gcFrequency = 10
local reportFrequency = 10
local function predictCode(inputRecord)
local timerAll = Timer()
key, value = splitPair(inputRecord)
local query = extract8numbers(value)
vp(2, 'value', value, 'query', query)
local stdQuery = standardize(query, means, stddevs)
vp(2, 'stdQuery', stdQuery)
local timerWeights = Timer()
local weights = getWeights(known, query, clArgs, log)
local weights2D = viewAsColumnVector(weights)
local timeWeights = timerWeights:cpu()
local checkGradient = false -- check gradient in early debugging
local timerPredict = Timer()
-- predict target number in {1, 2, ..., nTargets}
local predicted = localLogRegNn(stdKnown,
targets2D,
weights2D,
viewAsColumnVector(stdQuery):t(),
clArgs.lambda,
checkGradient)
local timePredict = timerPredict:cpu()
local timerWrite = Timer()
local outputRecord = makeOutputRecord(clArgs,
key,
codeString(predicted, codeMap))
io.stdout:write(outputRecord)
log:log(outputRecord) -- at least while debugging
local timeWrite = timerWrite:cpu()
-- periodically collect garbage
local timerGarbage = Timer()
nPredictions = nPredictions + 1
if nPredictions % gcFrequency == 1 then
local used = memoryUsed()
log:log('memory used = %d', used)
end
local timeGarbage = timerGarbage:cpu()
local timeAll = timerAll:cpu()
if nPredictions % reportFrequency == 1 then
log:log('cpu secs: %0.2f weights %0.2f predict %0.2f write %0.2f gc %0.2f all',
timeWeights, timePredict, timeWrite, timeGarbage, timeAll)
end
if nPredictions == 1 then stop() end
end
-- predict code for each input record in slice
local sr = SliceReader(io.stdin, clArgs.slice, clArgs.of)
vp(2, 'sr', sr)
local nRecords = sr:forEachRecord(predictCode)
log:log('processed %d input records in the slice', nRecords)
end
main()
| gpl-3.0 |
fw867/ntopng | scripts/lua/host_get_json.lua | 1 | 1062 | --
-- (C) 2013-14 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
host_info = url2hostinfo(_GET)
if(host_info["host"] == nil) then
sendHTTPHeader('text/html; charset=utf-8')
ntop.dumpFile(dirs.installdir .. "/httpdocs/inc/header.inc")
dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua")
print("<div class=\"alert alert-danger\"><img src=/img/warning.png> Host parameter is missing (internal error ?)</div>")
return
end
interface.find(ifname)
host = interface.getHostInfo(host_info["host"], host_info["vlan"])
if(host == nil) then
sendHTTPHeader('text/html; charset=iso-8859-1')
ntop.dumpFile(dirs.installdir .. "/httpdocs/inc/header.inc")
dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua")
print("<div class=\"alert alert-danger\"><img src=/img/warning.png> Host ".. host_info["host"] .. " Vlan" ..host_info["vlan"].." cannot be found (expired ?)</div>")
return
else
sendHTTPHeader('application/json')
print(host["json"])
end | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/loaf_of_pain_de_neige.lua | 3 | 1094 | -----------------------------------------
-- ID: 4292
-- Item: loaf_of_pain_de_neige
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health 18
-- Vitality 4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,4292);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 18);
target:addMod(MOD_VIT, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 18);
target:delMod(MOD_VIT, 4);
end;
| gpl-3.0 |
Servius/tfa-sw-weapons-repository | In Development/servius_development/tfa_training_weapons/expanded_pack/lua/weapons/tfa_sw_westardual_training/shared.lua | 1 | 3839 | if ( SERVER ) then
AddCSLuaFile( "shared.lua" )
end
if ( CLIENT ) then
SWEP.PrintName = "Dual Westar"
SWEP.Author = "TFA, Servius"
SWEP.ViewModelFOV = 76
SWEP.Slot = 2
SWEP.SlotPos = 3
SWEP.WepSelectIcon = surface.GetTextureID("HUD/killicons/WESTAR34")
killicon.Add( "tfa_sw_westardual", "HUD/killicons/WESTAR34", Color( 255, 80, 0, 255 ) )
end
SWEP.Author = "Servius" --Author Tooltip
SWEP.Contact = "http://steamcommunity.com/profiles/76561198036188853/" --Contact Info Tooltip
SWEP.Purpose = "Shoot some people" --Purpose Tooltip
SWEP.Instructions = "Left click to shoot...dummy." --Instructions Tooltip
SWEP.HoldType = "duel"
SWEP.ViewModelFOV = 72.160804020101
SWEP.ViewModelFlip = false
SWEP.UseHands = true
SWEP.ViewModel = "models/weapons/cstrike/c_pist_elite.mdl"
SWEP.WorldModel = "models/weapons/w_WESTAR34.mdl"
SWEP.ShowViewModel = true
SWEP.ShowWorldModel = true
SWEP.Akimbo = true
SWEP.ViewModelBoneMods = {
["v_weapon.Hands_parent"] = { scale = Vector(0.961, 1.001, 0.961), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["v_weapon.elite_right"] = { scale = Vector(0.018, 0.018, 0.018), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["v_weapon.Left_Hand"] = { scale = Vector(1.016, 1.016, 1.016), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["v_weapon.Right_Arm"] = { scale = Vector(1, 1, 1), pos = Vector(-3.149, -1.297, 0.185), angle = Angle(0, 0, 0) },
["v_weapon.elite_left"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) }
}
SWEP.VElements = {
["westar"] = { type = "Model", model = "models/weapons/w_WESTAR34.mdl", bone = "v_weapon.elite_left", rel = "", pos = Vector(-0.519, -1.558, 4.675), angle = Angle(90, -99.351, 15.194), size = Vector(0.85, 0.85, 0.85), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["westar+"] = { type = "Model", model = "models/weapons/w_WESTAR34.mdl", bone = "v_weapon.elite_right", rel = "", pos = Vector(-0.519, -1.558, 4.675), angle = Angle(90, -99.351, 15.194), size = Vector(0.85, 0.85, 0.85), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.WElements = {
["westar"] = { type = "Model", model = "models/weapons/w_WESTAR34.mdl", bone = "ValveBiped.Bip01_L_Hand", rel = "", pos = Vector(9.362, 1.738, 3.665), angle = Angle(0, 0, 0), size = Vector(0.827, 0.827, 0.827), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.Base = "tfa_swsft_base_servius_training"
SWEP.Category = "TFA Star Wars"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.Primary.Sound = Sound("weapons/deathwatch_mando/westar34_fire.ogg") -- This is the sound of the weapon, when you shoot.
SWEP.Callback = {}
SWEP.Callback.ChooseProceduralReloadAnim = function(self)
self:EmitSound("weapons/shared/standard_reload.ogg")
end
SWEP.Primary.ReloadSound = Sound ("weapons/shared/standard_reload.ogg");
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.Recoil = 0.5
SWEP.Primary.Damage = 0
SWEP.Primary.NumShots = 1
SWEP.Primary.Spread = 0.0125
SWEP.Primary.IronAccuracy = .005 -- Ironsight accuracy, should be the same for shotguns
SWEP.Primary.ClipSize = 50
SWEP.Primary.Delay = 0.35
--= 75
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "battery"
SWEP.TracerName = "effect_sw_laser_red_akimbo_pu"
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.IronSightsPos = Vector(-1.16, 0, 1.09)
SWEP.IronSightsAng = Vector(-0.101, 1, -1.407)
SWEP.Akimbo = true
SWEP.ProceduralHolsterAng = Vector(-45,0,0)
SWEP.DoProceduralReload = true
SWEP.ProceduralReloadTime = 2
SWEP.LuaShellEject = true
SWEP.LuaShellEffect = ""
SWEP.BlowbackEnabled = false | apache-2.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/loach_gruel.lua | 2 | 1551 | -----------------------------------------
-- ID: 5670
-- Item: loach_gruel
-- Food Effect: 4Hour,Group Food, All Races
-----------------------------------------
-- Dexterity 2
-- Agility 2
-- Accuracy % 7
-- Accuracy Cap 30
-- HP % 7
-- HP Cap 30
-- Evasion 4
-- (Did Not Add Group Food Effect)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5670);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_AGI, 2);
target:addMod(MOD_FOOD_ACCP, 7);
target:addMod(MOD_FOOD_ACC_CAP, 30);
target:addMod(MOD_FOOD_HPP, 7);
target:addMod(MOD_FOOD_HP_CAP, 30);
target:addMod(MOD_EVA, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_AGI, 2);
target:delMod(MOD_FOOD_ACCP, 7);
target:delMod(MOD_FOOD_ACC_CAP, 30);
target:delMod(MOD_FOOD_HPP, 7);
target:delMod(MOD_FOOD_HP_CAP, 30);
target:delMod(MOD_EVA, 4);
end;
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/spells/knights_minne_iii.lua | 2 | 1385 | -----------------------------------------
-- Spell: Knight's Minne III
-- Grants Defense bonus to all allies.
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function OnMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sItem = caster:getEquipID(2);
local sLvl = caster:getSkillLevel(40); -- Gets skill level of Singing
if (sLvl < 118) then -- If your skill level is below 118 your stuck at the minimum
power = 26;
end
if (sLvl >= 118 and sLvl <= 186) then -- If your above 117 skill then you get the bonus of 1 more defense for every 5 skill
sBoost = math.floor((sLvl - 117)/5);
power = 26 + sBoost;
end
if(sLvl >= 187) then -- The bonus caps at skill 187
power = 40;
end
if(sItem == 17373 or sItem == 17354) then -- Maple Harp +1 or Harp will add 3 more
power = power + 3;
end
if(sItem == 17374) then -- Harp +1 gives 5 more
power = power + 5;
end
-- Until someone finds a way to delete Effects by tier we should not allow bard spells to stack.
-- Since all the tiers use the same effect buff it is hard to delete a specific one.
target:delStatusEffect(EFFECT_MINNE);
target:addStatusEffect(EFFECT_MINNE,power,0,120);
spell:setMsg(230);
return EFFECT_MINNE;
end; | gpl-3.0 |
rbowen/ponymail | site/api/lib/aaa.lua | 1 | 3266 | --[[
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- This is aaa.lua - AAA filter for ASF.
-- Get a list of PMCs the user is a part of
function getPMCs(r, uid)
local groups = {}
local ldapdata = io.popen( ([[ldapsearch -x -LLL "(|(memberUid=%s)(member=uid=%s,ou=people,dc=apache,dc=org))" cn]]):format(uid,uid) )
local data = ldapdata:read("*a")
for match in data:gmatch("dn: cn=([-a-zA-Z0-9]+),ou=pmc,ou=committees,ou=groups,dc=apache,dc=org") do
table.insert(groups, match)
end
return groups
end
-- Is $uid a member of the org?
function isMember(r, uid)
-- First, check the 30 minute cache
local nowish = math.floor(os.time() / 1800)
local t = r:ivm_get("isMember_" .. nowish .. "_" .. uid)
-- If cached, then just return the value
if t then
return tonumber(t) == 1
-- Otherwise, look in LDAP
else
local ldapdata = io.popen([[ldapsearch -x -LLL -b cn=member,ou=groups,dc=apache,dc=org]])
local data = ldapdata:read("*a")
for match in data:gmatch("memberUid: ([-a-z0-9_.]+)") do
-- Found it?
if match == uid then
-- Set cache
r:ivm_set("isMember_" .. nowish .. "_" .. uid, "1")
return true
end
end
end
-- Set cache
r:ivm_set("isMember_" .. nowish .. "_" .. uid, "0")
return false
end
-- Get a list of domains the user has private email access to (or wildcard if org member)
function getRights(r, usr)
local xuid = usr.uid or usr.email or "|||"
uid = xuid:match("([-a-zA-Z0-9._]+)") -- whitelist
local rights = {}
-- bad char in uid?
if not uid or xuid ~= uid then
return rights
end
-- check if oauth was through an oauth portal that can give privacy rights
local authority = false
for k, v in pairs(config.admin_oauth or {}) do
if r.strcmp_match(oauth_domain, v) then
authority = true
break
end
end
-- if not a 'good' oauth, then let's forget all about it
if not authority then
return rights
end
-- Check if uid has member (admin) rights
if usr.admin or isMember(r, uid) then
table.insert(rights, "*")
-- otherwise, get PMC list and construct array
else
local list = getPMCs(r, uid)
for k, v in pairs(list) do
table.insert(rights, v .. ".apache.org")
end
end
return rights
end
-- module defs
return {
rights = getRights
}
| apache-2.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/weaponskills/kings_justice.lua | 2 | 1439 | -----------------------------------
-- Kings Justice
-- Great Axe weapon skill
-- Skill Level: N/A
-- Delivers a threefold attack. Damage varies with TP. Conqueror: Aftermath effect varies with TP.
-- Available only after completing the Unlocking a Myth (Warrior) quest.
-- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget.
-- Aligned with the Breeze Belt, Thunder Belt & Soil Belt.
-- Element: None
-- Staff weapon skill Skill level: 10 Delivers a single-hit attack. Damage varies with TP. Element: Non
-- Modifiers: STR:50%
-- 100%TP 200%TP 300%TP
-- 1.00 1.25 1.50
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 3;
params.ftp100 = 1; params.ftp200 = 1.25; params.ftp300 = 1.5;
params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 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;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.