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 |
|---|---|---|---|---|---|
jaambee/redis | deps/lua/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| bsd-3-clause |
a-pavlov/redis | deps/lua/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| bsd-3-clause |
Fenix-XI/Fenix | scripts/zones/Lower_Jeuno/npcs/Alrauverat.lua | 14 | 3677 | -----------------------------------
-- Area: Lower Jeuno
-- NPC:Alrauverat
-- @pos -101 0 -182 245
-------------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/conquest");
require("scripts/zones/Lower_Jeuno/TextIDs");
local guardnation = OTHER; -- SANDORIA, BASTOK, WINDURST, OTHER(Jeuno).
local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Menu1 = getArg1(guardnation,player);
local Menu3 = conquestRanking();
local Menu6 = getArg6(player);
local Menu7 = player:getCP();
player:startEvent(0x7ffb,Menu1,0,Menu3,0,0,Menu6,Menu7,0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
if (player:getNation() == 0) then
inventory = SandInv;
size = table.getn(SandInv);
elseif (player:getNation() == 1) then
inventory = BastInv;
size = table.getn(BastInv);
else
inventory = WindInv;
size = table.getn(WindInv);
end
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
CPVerify = 1;
if (player:getCP() >= inventory[Item + 1]) then
CPVerify = 0;
end;
player:updateEvent(2,CPVerify,inventory[Item + 2]); -- can't equip = 2 ?
break;
end;
end;
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
if (player:getFreeSlotsCount() >= 1) then
-- Logic to impose limits on exp bands
if (option >= 32933 and option <= 32935) then
if (checkConquestRing(player) > 0) then
player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]);
break;
else
player:setVar("CONQUEST_RING_TIMER",getConquestTally());
end
end
itemCP = inventory[Item + 1];
player:delCP(itemCP);
player:addItem(inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
break;
end;
end;
end;
end; | gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Promyvion-Mea/IDs.lua | 12 | 2553 | -----------------------------------
-- Area: Promyvion-Mea
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.PROMYVION_MEA] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
},
mob =
{
MEMORY_RECEPTACLES =
{
[16859151] = {1, 3, 16859451},
[16859198] = {2, 5, 16859454},
[16859205] = {2, 5, 16859458},
[16859212] = {2, 5, 16859459},
[16859219] = {2, 5, 16859460},
[16859271] = {3, 7, 16859452},
[16859280] = {3, 7, 16859453},
[16859289] = {3, 7, 16859455},
[16859347] = {4, 7, 16859456},
[16859356] = {4, 7, 16859457},
[16859365] = {4, 7, 16859461},
},
},
npc =
{
MEMORY_STREAMS =
{
[11] = {-122, -4, 197, -117, 4, 202, {46}}, -- floor 1 return
[21] = { -1, -4, -121, 2, 4, -118, {41}}, -- floor 2 return
[31] = {-161, -4, 158, -157, 4, 161, {30}}, -- floor 3 return
[32] = { 158, -4, -281, 161, 4, -278, {30}}, -- floor 3 return
[41] = { -82, -4, 358, -78, 4, 361, {33}}, -- floor 4 return
[16859451] = {-283, -4, 237, -276, 4, 242, {30}}, -- floor 1 MR1
[16859454] = { -82, -4, -42, -78, 4, -38, {33,37}}, -- floor 2 MR1
[16859458] = {-322, -4, -361, -318, 4, -357, {33,37}}, -- floor 2 MR2
[16859459] = { -42, -4, -321, -37, 4, -317, {33,37}}, -- floor 2 MR3
[16859460] = { 77, -4, -241, 81, 4, -238, {33,37}}, -- floor 2 MR4
[16859452] = {-321, -4, -42, -318, 4, -38, {31}}, -- floor 3 MR1
[16859453] = {-241, -4, -42, -238, 4, -37, {31}}, -- floor 3 MR2
[16859455] = { -42, -4, -2, -38, 4, 2, {31}}, -- floor 3 MR3
[16859456] = { 198, -4, -2, 201, 4, 2, {31}}, -- floor 3 MR4
[16859457] = { 358, -4, -41, 362, 4, -38, {31}}, -- floor 3 MR5
[16859461] = { 240, -4, -322, 244, 4, -317, {31}}, -- floor 3 MR6
},
},
}
return zones[dsp.zone.PROMYVION_MEA] | gpl-3.0 |
emender/emender | test/Test100Infos1FailLink.lua | 1 | 1955 | -- Test100Infos1FailLink.lua - check that graphs are rendered correctly.
-- Copyright (C) 2017 Pavel Tisnovsky
--
--
-- This file is part of Emender.
--
-- Emender 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 3 of the License.
--
-- Emender 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 Emender. If not, see <http://www.gnu.org/licenses/>.
--
Test100Infos1FailLink = {
-- required field
metadata = {
description = "Check that graphs are rendered correctly.",
authors = "Pavel Tisnovsky",
emails = "ptisnovs@redhat.com",
changed = "2017-05-02",
tags = {"BasicTest", "SmokeTest"},
},
}
--
-- This function calls pass() 100 times and fail() only once.
--
function Test100Infos1FailLink.testA()
-- call pass() 100 times
for i = 1, 100 do
warn("Info#" .. i)
end
-- call fail() once
fail("Failure", "https://github.com/emender/")
end
--
-- This function calls fail() once and pass() 100 times.
--
function Test100Infos1FailLink.testB()
-- call fail() once
fail("Failure", "https://github.com/emender/")
-- call pass() 100 times
for i = 1, 100 do
warn("Info#" .. i)
end
end
--
-- This function pass() 50 times, then fail() once and then pass() 50 times.
--
function Test100Infos1FailLink.testC()
-- call pass() 50 times
for i = 1, 50 do
warn("Info#" .. i)
end
-- call fail() once
fail("Failure", "https://github.com/emender/")
-- call pass() 50 times
for i = 1, 50 do
warn("Info#" .. (i+50))
end
end
| gpl-3.0 |
DarkstarProject/darkstar | scripts/globals/weaponskills/rudras_storm.lua | 10 | 1927 | -----------------------------------
-- Rudra's Storm
-- Dagger weapon skill
-- Skill level: N/A
-- Deals triple damage and weighs target down (duration: 60s). Damage varies with TP.
-- Aligned with the Aqua Gorget, Snow Gorget & Shadow Gorget.
-- Aligned with the Aqua Belt, Snow Belt & Shadow Belt.
-- Element: None
-- Modifiers: DEX:80%
-- 100%TP 200%TP 300%TP
-- 6 15 19.5
-----------------------------------
require("scripts/globals/aftermath")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 1
params.ftp100 = 3.25 params.ftp200 = 4.25 params.ftp300 = 5.25
params.str_wsc = 0.0 params.dex_wsc = 0.6 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.atk100 = 1; params.atk200 = 1; params.atk300 = 1;
if USE_ADOULIN_WEAPON_SKILL_CHANGES then
params.ftp100 = 5 params.ftp200 = 10.19 params.ftp300 = 13
params.dex_wsc = 0.8
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
-- dsp.effect.WEIGHT power value is equal to lead breath as per bg-wiki: http://www.bg-wiki.com/bg/Rudra%27s_Storm
if damage > 0 then
if not target:hasStatusEffect(dsp.effect.WEIGHT) then
target:addStatusEffect(dsp.effect.WEIGHT, 50, 0, 60)
end
-- Apply aftermath
dsp.aftermath.addStatusEffect(player, tp, dsp.slot.MAIN, dsp.aftermath.type.EMPYREAN)
end
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
Fenix-XI/Fenix | scripts/globals/weaponskills/geirskogul.lua | 1 | 1771 | -----------------------------------
-- Geirskogul
-- Polearm weapon skill
-- Skill Level: N/A
-- Gae Assail/Gungnir: Shock Spikes.
-- This weapon skill is only available with the stage 5 relic Polearm Gungnir, within Dynamis with the stage 4 Gae Assail, or by activating the latent effect on the Skogul Lance.
-- Aligned with the Light Gorget, Aqua Gorget & Snow Gorget.
-- Aligned with the Light Belt, Aqua Belt & Snow Belt.
-- Element: None
-- Modifiers: AGI:60%
-- 100%TP 200%TP 300%TP
-- 3.00 3.00 3.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.numHits = 2;
params.ftp100 = 2.25; params.ftp200 = 2.25; params.ftp300 = 2.25;
params.str_wsc = 0.20; params.dex_wsc = 0.60; 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.30; params.crit200 = 0.40; params.crit300 = 0.60;
params.canCrit = True;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1.2;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.dex_wsc = 0.8; params.agi_wsc = 0.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary);
-- TODO: Whoever codes those level 85 weapons with the latent that grants this WS needs to code a check to not give the aftermath effect.
if (damage > 0) then
player:addStatusEffect(EFFECT_AFTERMATH, 10, 0, 30, 0, 6);
end
return tpHits, extraHits, criticalHit, damage;
end | gpl-3.0 |
pizzotto/BolScripts | MrArticunoLaucher.lua | 23 | 3851 | --[[
_____ _____ __ .__
/ \_______ / _ \________/ |_|__| ____ __ __ ____ ____
/ \ / \_ __ \ / /_\ \_ __ \ __\ |/ ___\| | \/ \ / _ \
/ Y \ | \/ / | \ | \/| | | \ \___| | / | ( <_> )
\____|__ /__| \____|__ /__| |__| |__|\___ >____/|___| /\____/
\/ \/ \/ \/
Mechanics Series Laucher
]]
require 'mrLib'
_G.ScriptLoaded = false
_G.LibsChecked = false
local ScriptLink = {
SOW = { filename = "SOW.lua", host = "raw.github.com" , versionLink = "/Hellsing/BoL/master/common/SOW.lua" , isLib = true , forceUpdate = false },
VPrediction = { filename = "VPrediction.lua", host = "raw.github.com" , versionLink = "/Hellsing/BoL/master/common/VPrediction.lua" , isLib = true , forceUpdate = false },
Prodiction = { filename = "Prodiction.lua", host = "bitbucket.org" , versionLink = "/Klokje/public-klokjes-bol-scripts/raw/ec830facccefb3b52212dba5696c08697c3c2854/Test/Prodiction/Prodiction.lua" , isLib = true , forceUpdate = false },
Tristana = { filename = "TristanaMechanics.lua", host = "raw.github.com" , versionLink = "/gmlyra/BolScripts/master/TristanaMechanics.lua" , isLib = false , forceUpdate = true },
Elise = { filename = "EliseMechanics.lua", host = "raw.github.com" , versionLink = "/gmlyra/BolScripts/master/EliseMechanics.lua" , isLib = false , forceUpdate = true },
Lucian = { filename = "LucianMechanics.lua", host = "raw.github.com" , versionLink = "/gmlyra/BolScripts/master/LucianMechanics.lua" , isLib = false , forceUpdate = true },
Jinx = { filename = "JinxMechanics.lua", host = "raw.github.com" , versionLink = "/gmlyra/BolScripts/master/JinxMechanics.lua" , isLib = false , forceUpdate = true },
Gragas = { filename = "GragasMechanics.lua", host = "raw.github.com" , versionLink = "/gmlyra/BolScripts/master/GragasMechanics.lua" , isLib = false , forceUpdate = true },
Viktor = { filename = "ViktorMechanics.lua", host = "raw.github.com" , versionLink = "/gmlyra/BolScripts/master/ViktorMechanics.lua" , isLib = false , forceUpdate = true },
Chogath = { filename = "ChogathMechanics.lua", host = "raw.github.com" , versionLink = "/gmlyra/BolScripts/master/ChogathMechanics.lua" , isLib = false , forceUpdate = true },
Kayle = { filename = "KayleMechanics.lua", host = "raw.github.com" , versionLink = "/gmlyra/BolScripts/master/KayleMechanics.lua" , isLib = false , forceUpdate = true },
Karthus = { filename = "KarthusMechanics.lua", host = "raw.github.com" , versionLink = "/gmlyra/BolScripts/master/KarthusMechanics.lua" , isLib = false , forceUpdate = true },
}
function OnLoad()
if file_exists(LIB_PATH.."mrLib.lua") then
require 'mrLib'
else
print('You must have mrLib.lua to use this laucher')
return
end
checkLibs()
if not _G.ScriptLoaded then
if not ScriptLink[myHero.charName].forceUpdate then
if not file_exists(SCRIPT_PATH..ScriptLink[myHero.charName].filename) then
loadFromWeb(SCRIPT_PATH..ScriptLink[myHero.charName].filename, ScriptLink[myHero.charName].host, ScriptLink[myHero.charName].versionLink, true)
else
loadfile(SCRIPT_PATH..ScriptLink[myHero.charName].filename)()
end
else
loadFromWeb(SCRIPT_PATH..ScriptLink[myHero.charName].filename, ScriptLink[myHero.charName].host, ScriptLink[myHero.charName].versionLink, false)
end
end
end
function checkLibs()
for i,v in ipairs(ScriptLink) do
if ScriptLink[v].isLib then
if not file_exists(LIB_PATH..ScriptLink[v].filename) or ScriptLink[v].forceUpdate then
downloadLib(ScriptLink[v].filename, ScriptLink[v].host, ScriptLink[v].versionLink)
end
end
end
end
local io = require "io"
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- End of Laucher -- | gpl-2.0 |
ungarscool1/HL2RP | hl2rp/gamemode/libraries/fn.lua | 3 | 7654 | /*---------------------------------------------------------------------------
Functional library
by FPtje Atheos
---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
Function currying
Take a function with n parameters.
Currying is the procedure of storing k < n parameters "in the function"
in such a way that the remaining function can be called with n - k parameters
Example:
DebugPrint = fp{print, "[DEBUG]"}
DebugPrint("TEST")
> [DEBUG] TEST
---------------------------------------------------------------------------*/
function fp(tbl)
local func = tbl[1]
return function(...)
local fnArgs = {}
local arg = {...}
local tblN = table.maxn(tbl)
for i = 2, tblN do fnArgs[i - 1] = tbl[i] end
for i = 1, table.maxn(arg) do fnArgs[tblN + i - 1] = arg[i] end
return func(unpack(fnArgs, 1, table.maxn(fnArgs)))
end
end
local unpack = unpack
local table = table
local pairs = pairs
local ipairs = ipairs
local error = error
local math = math
local select = select
local _G = _G
local fp = fp
module("fn")
/*---------------------------------------------------------------------------
Parameter manipulation
---------------------------------------------------------------------------*/
Id = function(...) return ... end
Flip = function(f)
if not f then error("not a function") end
return function(b, a, ...)
return f(a, b, ...)
end
end
-- Definition from http://lua-users.org/wiki/CurriedLua
ReverseArgs = function(...)
--reverse args by building a function to do it, similar to the unpack() example
local function reverse_h(acc, v, ...)
if select('#', ...) == 0 then
return v, acc()
else
return reverse_h(function () return v, acc() end, ...)
end
end
-- initial acc is the end of the list
return reverse_h(function () return end, ...)
end
/*---------------------------------------------------------------------------
Misc functions
---------------------------------------------------------------------------*/
-- function composition
Compose = function(funcs)
return function(...)
local res = {...}
for i = #funcs, 1, -1 do
res = {funcs[i](unpack(res))}
end
return unpack(res)
end
end
_G.fc = Compose
-- Definition from http://lua-users.org/wiki/CurriedLua
Curry = function(func, num_args)
if not num_args then error("Missing argument #2: num_args") end
if not func then error("Function does not exist!", 2) end
-- helper
local function curry_h(argtrace, n)
if n == 0 then
-- reverse argument list and call function
return func(ReverseArgs(argtrace()))
else
-- "push" argument (by building a wrapper function) and decrement n
return function(x)
return curry_h(function() return x, argtrace() end, n - 1)
end
end
end
-- no sense currying for 1 arg or less
if num_args > 1 then
return curry_h(function() return end, num_args)
else
return func
end
end
-- Thanks Lexic!
Partial = function(func, ...)
local args = {...}
return function(...)
return func(unpack(table.Add( args, {...})))
end
end
Apply = function(f, ...) return f(...) end
Const = function(a, b) return a end
Until = function(cmp, fn, val)
if cmp(val) then
return val
end
return Until(cmp, fn, fn(val))
end
Seq = function(f, x) f(x) return x end
GetGlobalVar = function(key) return _G[key] end
/*---------------------------------------------------------------------------
Mathematical operators and functions
---------------------------------------------------------------------------*/
Add = function(a, b) return a + b end
Sub = function(a, b) return a - b end
Mul = function(a, b) return a * b end
Div = function(a, b) return a / b end
Mod = function(a, b) return a % b end
Neg = function(a) return -a end
Eq = function(a, b) return a == b end
Neq = function(a, b) return a ~= b end
Gt = function(a, b) return a > b end
Lt = function(a, b) return a < b end
Gte = function(a, b) return a >= b end
Lte = function(a, b) return a <= b end
Succ = Compose{Add, 1}
Pred = Compose{Flip(Sub), 1}
Even = Compose{fp{Eq, 0}, fp{Flip(Mod), 2}}
Odd = Compose{Not, Even}
/*---------------------------------------------------------------------------
Functional logical operators and conditions
---------------------------------------------------------------------------*/
FAnd = function(fns)
return function(...)
local val
for _, f in pairs(fns) do
val = {f(...)}
if not val[1] then return unpack(val) end
end
if val then return unpack(val) end
end
end
FOr = function(fns)
return function(...)
for _, f in pairs(fns) do
local val = {f(...)}
if val[1] then return unpack(val) end
end
return false
end
end
Not = function(x) return not x end
If = function(f, Then, Else)
return function(x)
if f(x) then
return Then
else
return Else
end
end
end
/*---------------------------------------------------------------------------
List operations
---------------------------------------------------------------------------*/
Map = function(f, xs)
for k, v in pairs(xs) do
xs[k] = f(v)
end
return xs
end
Append = function(xs, ys)
return table.Add(xs, ys)
end
Filter = function(f, xs)
local res = {}
for k,v in pairs(xs) do
if f(v) then res[k] = v end
end
return res
end
ForEach = function(f, xs)
for k,v in pairs(xs) do
local val = f(k, v)
if val ~= nil then return val end
end
end
Head = function(xs)
return table.GetFirstValue(xs)
end
Last = function(xs)
return xs[#xs] or table.GetLastValue(xs)
end
Tail = function(xs)
table.remove(xs, 1)
return xs
end
Init = function(xs)
xs[#xs] = nil
return xs
end
GetValue = function(i, xs)
return xs[i]
end
Null = function(xs)
for k, v in pairs(xs) do
return false
end
return true
end
Length = function(xs)
return #xs
end
Index = function(xs, i)
return xs[i]
end
Reverse = function(xs)
local res = {}
for i = #xs, 1, -1 do
res[#xs - i + 1] = xs[i]
end
return res
end
/*---------------------------------------------------------------------------
Folds
---------------------------------------------------------------------------*/
Foldr = function(func, val, xs)
for i = #xs, 1, -1 do
val = func(xs[i], val)
end
return val
end
Foldl = function(func, val, xs)
for k, v in ipairs(xs) do
val = func(val, v)
end
return val
end
And = function(xs)
for k, v in pairs(xs) do
if v ~= true then return false end
end
return true
end
Or = function(xs)
for k, v in pairs(xs) do
if v == true then return true end
end
return false
end
Any = function(func, xs)
for k, v in pairs(xs) do
if func(v) == true then return true end
end
return false
end
All = function(func, xs)
for k, v in pairs(xs) do
if func(v) ~= true then return false end
end
return true
end
Sum = _G.fp{Foldr, Add, 0}
Product = _G.fp{Foldr, Mul, 1}
Concat = _G.fp{Foldr, Append, {}}
Maximum = _G.fp{Foldl, math.Max, -math.huge}
Minimum = _G.fp{Foldl, math.Min, math.huge}
Snd = _G.fp{select, 2}
Thrd = _G.fp{select, 3}
| agpl-3.0 |
Fenix-XI/Fenix | scripts/globals/abilities/light_arts.lua | 7 | 1724 | -----------------------------------
-- Ability: Light Arts
-- Optimizes white magic capability while lowering black magic proficiency. Grants a bonus to divine, enhancing, enfeebling, and healing magic. Also grants access to Stratagems.
-- Obtained: Scholar Level 10
-- Recast Time: 1:00
-- Duration: 2:00:00
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if player:hasStatusEffect(EFFECT_LIGHT_ARTS) or player:hasStatusEffect(EFFECT_ADDENDUM_WHITE) then
return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0;
end
return 0,0;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
player:delStatusEffectSilent(EFFECT_DARK_ARTS);
player:delStatusEffect(EFFECT_ADDENDUM_BLACK);
player:delStatusEffect(EFFECT_PARSIMONY);
player:delStatusEffect(EFFECT_ALACRITY);
player:delStatusEffect(EFFECT_MANIFESTATION);
player:delStatusEffect(EFFECT_EBULLIENCE);
player:delStatusEffect(EFFECT_FOCALIZATION);
player:delStatusEffect(EFFECT_EQUANIMITY);
player:delStatusEffect(EFFECT_IMMANENCE);
local skillbonus = player:getMod(MOD_LIGHT_ARTS_SKILL);
local effectbonus = player:getMod(MOD_LIGHT_ARTS_EFFECT);
local regenbonus = 0;
if (player:getMainJob() == JOB_SCH and player:getMainLvl() >= 20) then
regenbonus = 3 * math.floor((player:getMainLvl() - 10) / 10);
end
player:addStatusEffect(EFFECT_LIGHT_ARTS,effectbonus,0,7200,0,regenbonus);
return EFFECT_LIGHT_ARTS;
end; | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Kazham/npcs/Kyun_Magopiteh.lua | 15 | 1054 | -----------------------------------
-- Area: Kazham
-- NPC: Kyun Magopiteh
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("BathedInScent") == 1) then
player:startEvent(0x00AE); -- scent from Blue Rafflesias
else
player:startEvent(0x0056);
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 |
DarkstarProject/darkstar | scripts/globals/mobskills/vortex.lua | 11 | 1053 | ---------------------------------------------------
-- Vortex
-- Creates a vortex that damages targets in an area of effect. Additional effect: Terror
---------------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 1
local accmod = 1
local dmgmod = 1.5
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.SLASHING,MOBPARAM_3_SHADOW)
MobPhysicalStatusEffectMove(mob, target, skill, dsp.effect.TERROR, 1, 0, 9)
MobPhysicalStatusEffectMove(mob, target, skill, dsp.effect.BIND, 1, 0, 30)
target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.SLASHING)
mob:resetEnmity(target)
return dmg
end
| gpl-3.0 |
lnattrass/lsyncd | bin2carray.lua | 22 | 1259 | #!/usr/bin/lua
--============================================================================
-- bin2carray.lua
--
-- License: GPLv2 (see COPYING) or any later version
--
-- Authors: Axel Kittenberger <axkibe@gmail.com>
--
-- Transforms a binary file (the compiled lsyncd runner script) in a c array
-- so it can be included into the executable in a portable way.
--============================================================================
if #arg < 3 then
error("Usage: "..arg[0].." [infile] [varname] [outfile]")
end
fin, err = io.open(arg[1], "rb")
if fin == nil then
error("Cannot open '"..arg[1].."' for reading: "..err)
end
fout, err = io.open(arg[3], "w")
if fout == nil then
error("Cannot open '"..arg[3].."'for writing: "..err)
end
fout:write("/* created by "..arg[0].." from file "..arg[1].." */\n")
fout:write("#include <stddef.h>\n")
fout:write("const char "..arg[2].."_out[] = {\n")
while true do
local block = fin:read(16)
if block == nil then
break
end
for i = 1, #block do
local val = string.format("%x", block:byte(i))
if #val < 2 then
val = "0" ..val
end
fout:write("0x",val,",")
end
fout:write("\n")
end
fout:write("};\n\nsize_t "..arg[2].."_size = sizeof("..arg[2].."_out);\n");
fin:close();
fout:close();
| gpl-2.0 |
Fenix-XI/Fenix | scripts/zones/La_Vaule_[S]/mobs/Lobison.lua | 12 | 1690 | -----------------------------------
-- Area: La Vaule (S)
-- NPC: Lobison
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setLocalVar("transformTime", os.time())
end;
-----------------------------------
-- onMobRoam Action
-----------------------------------
function onMobRoam(mob)
local spawnTime = mob:getLocalVar("transformTime");
local roamChance = math.random(1,100);
local roamMoonPhase = VanadielMoonPhase();
if (roamChance > 100-roamMoonPhase) then
if (mob:AnimationSub() == 0 and os.time() - transformTime > 300) then
mob:AnimationSub(1);
mob:setLocalVar("transformTime", os.time());
elseif (mob:AnimationSub() == 1 and os.time() - transformTime > 300) then
mob:AnimationSub(0);
mob:setLocalVar("transformTime", os.time());
end
end
end;
-----------------------------------
-- onMobEngaged
-- Change forms every 60 seconds
-----------------------------------
function onMobEngaged(mob,target)
local changeTime = mob:getLocalVar("changeTime");
local chance = math.random(1,100);
local moonPhase = VanadielMoonPhase();
if (chance > 100-moonPhase) then
if (mob:AnimationSub() == 0 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(1);
mob:setLocalVar("changeTime", mob:getBattleTime());
elseif (mob:AnimationSub() == 1 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(0);
mob:setLocalVar("changeTime", mob:getBattleTime());
end
end
end; | gpl-3.0 |
Fenix-XI/Fenix | scripts/globals/weaponskills/blast_arrow.lua | 9 | 1362 | -----------------------------------
-- Blast Arrow
-- Archery weapon skill
-- Skill level: 200
-- Delivers a melee-distance ranged attack. params.accuracy varies with TP.
-- Aligned with the Snow Gorget & Light Gorget.
-- Aligned with the Snow Belt & Light Belt.
-- Element: None
-- Modifiers: STR:16% ; AGI:25%
-- 100%TP 200%TP 300%TP
-- 2.00 2.00 2.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.numHits = 1;
params.ftp100 = 2; params.ftp200 = 2; params.ftp300 = 2;
params.str_wsc = 0.16; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.25; 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.8; params.acc200= 0.9; params.acc300= 1;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.20; params.agi_wsc = 0.50;
end
local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
oTibia/UnderLight-AK47 | data/npc/scripts/cityguard.lua | 2 | 2226 |
local target = 0
local prevTarget = 0
local maxChaseDistance = 20
local origPos = 0
local origDir = NORTH
local lastAttack = 0
local followTimeout = 10
local function isSkulled(cid)
local skullType = getPlayerSkullType(cid)
if(skullType >= 3) then
return true
end
return false
end
local function goToOrigPos()
target = 0
lastAttack = 0
selfFollow(0)
doTeleportThing(getNpcCid(), origPos)
end
local function updateTarget()
if(isPlayer(target) == false) then
goToOrigPos()
elseif(not isSkulled(target)) then
target = 0
selfSay("Now, behave in the future.")
end
if(target == 0) then
local list = getSpectators(getNpcPos(), 8, 8, false)
for i=1, table.getn(list) do
local _target = list[i]
if(_target ~= 0) then
if(isPlayer(_target) and isSkulled(_target)) then
if(selfFollow(_target)) then
target = _target
if(target ~= prevTarget) then
selfSay("We do not tolerate people like you here!")
end
prevTarget = target
break
end
end
end
end
end
end
function onCreatureAppear(cid)
if(cid == getNpcCid()) then
--Wake up call
origPos = getNpcPos()
--origLook = getCreatureDir(cid)
end
end
function onCreatureDisappear(cid)
if(target == cid) then
goToOrigPos()
end
end
function onCreatureMove(creature, oldPos, newPos)
--
end
function onThink()
updateTarget()
if(target == 0) then
return
end
local playerPos = getCreaturePosition(target)
local myPos = getNpcPos()
if(myPos.z ~= playerPos.z) then
goToOrigPos()
return
end
if(math.abs(myPos.x - origPos.x) > maxChaseDistance or math.abs(myPos.y - origPos.y) > maxChaseDistance) then
selfSay("I'll catch you next time.")
goToOrigPos()
return
end
if(lastAttack == 0) then
lastAttack = os.clock()
end
if(os.clock() - lastAttack > followTimeout) then
--To prevent bugging the npc by going to a place where he can't reach
selfSay("You got me this time, but just wait.")
goToOrigPos()
return
end
if( (math.abs(playerPos.x - myPos.x) <= 1) and (math.abs(playerPos.y - myPos.y) <= 1)) then
doTargetCombatHealth(getNpcCid(), target, COMBAT_LIFEDRAIN, -200, -300, CONST_ME_BLOCKHIT)
lastAttack = os.clock()
end
end
| gpl-2.0 |
lecram/segno | fx.lua | 1 | 1692 | local fx = {}
local core = require "core"
local osc = require "osc"
local op = require "op"
local dl = require "dl"
-- Tremolo(input, frequency, {depth})
function fx.Tremolo(args)
setmetatable(args, {__index=function() return {out=0.5} end})
local input = args[1]
local frq = args[2]
local dpt = args.depth
local lfo = osc.Sine(frq, dpt)
local mul = op.Mul(input, lfo)
local v = {out=0, frq=frq, dpt=dpt}
local function tick()
lfo.ofs.out = 1 - v.dpt.out
lfo.amp.out = v.dpt.out
lfo()
mul()
v.out = mul.out
end
return setmetatable(v, {__call=tick})
end
-- Flanger(input, frequency, {depth, tone, feedback, dry, wet})
function fx.Flanger(args)
setmetatable(args, {__index=function() return {out=0.5} end})
local input = args[1]
local frq = args[2]
local dpt = args.depth
local ton = args.tone
local fdb = args.feedback
local dry = args.dry
local wet = args.wet
local lfo = osc.Sine(frq)
local mul_dry = op.Mul(input, dry)
local add_fb = op.Add(input)
local dli = dl.DelayLineInterpolated(add_fb, lfo, 0.1*core.sec)
local mul_wet = op.Mul(dli, wet)
local mix = op.Add(mul_dry, mul_wet)
local mul_fb = op.Mul(dli, fdb)
add_fb.b = mul_fb
local v = {out=0, frq=frq, dpt=dpt, ton=ton, fdb=fdb, dry=dry, wet=wet}
local function tick()
lfo.ofs.out = v.ton.out * -0.005 + 0.01
lfo.amp.out = v.dpt.out * 0.005 * core.sec
lfo()
add_fb()
dli()
mul_fb()
mul_dry()
mul_wet()
mix()
v.out = mix.out
end
return setmetatable(v, {__call=tick})
end
return fx
| mit |
Fenix-XI/Fenix | scripts/globals/items/silken_siesta.lua | 18 | 1238 | -----------------------------------------
-- ID: 5626
-- Item: Silken Siesta
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP Recoverd while healing 2
-- MP Recovered while healing 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5626);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HPHEAL, 2);
target:addMod(MOD_MPHEAL, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HPHEAL, 2);
target:delMod(MOD_MPHEAL, 5);
end;
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/North_Gustaberg/npcs/Kuuwari-Aori_WW.lua | 13 | 3336 | -----------------------------------
-- Area: North Gustaberg
-- NPC: Kuuwari-Aori, W.W.
-- Type: Outpost Conquest Guards
-- @pos -584.687 39.107 54.281 106
-----------------------------------
package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/North_Gustaberg/TextIDs");
local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = GUSTABERG;
local csid = 0x7ff7;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/QuBia_Arena/TextIDs.lua | 15 | 1428 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6384; -- Obtained: <item>.
GIL_OBTAINED = 6385; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>.
-- Maat dialog
YOU_DECIDED_TO_SHOW_UP = 7620; -- So, you decided to show up.
LOOKS_LIKE_YOU_WERENT_READY = 7621; -- Looks like you weren't ready for me, were you?
YOUVE_COME_A_LONG_WAY = 7622; -- Hm. That was a mighty fine display of skill there, Player Name. You've come a long way...
TEACH_YOU_TO_RESPECT_ELDERS = 7623; -- I'll teach you to respect your elders!
TAKE_THAT_YOU_WHIPPERSNAPPER = 7624; -- Take that, you whippersnapper!
THAT_LL_HURT_IN_THE_MORNING = 7626; -- Ungh... That'll hurt in the morning...
-- trion dialog
FLAT_PREPARE = 7614; -- I am Trion, of San d'Oria
FLAT_LAND = 7615; -- Feel the fire of my forefathers
RLB_PREPARE = 7616; -- The darkness before me that shrouds the light of good...
RLB_LAND = 7617; -- ...Return to the hell you crawled out from
SAVAGE_PREPARE = 7618; -- The anger, the pain, and the will to survive... Let the spirit of San d'Oria converge within this blade
SAVAGE_LAND = 7619; -- And with this blade I will return the glory to my kingdom's people
-- conquest Base
CONQUEST_BASE = 7045; -- Tallying conquest results...
| gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Spire_of_Holla/bcnms/ancient_flames_beckon.lua | 9 | 2899 | -----------------------------------
-- Ancient Flames Beckon
-- Spire of Holla mission battlefield
-----------------------------------
local ID = require("scripts/zones/Spire_of_Holla/IDs")
require("scripts/globals/battlefield")
require("scripts/globals/teleports")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/status")
-----------------------------------
local function otherLights(player)
return (player:hasKeyItem(dsp.ki.LIGHT_OF_MEA) and 1 or 0) +
(player:hasKeyItem(dsp.ki.LIGHT_OF_DEM) and 1 or 0)
end
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
local arg8 = 1 + otherLights(player)
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 0, battlefield:getLocalVar("[cs]bit"), arg8)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32001 then
local teleportTo = dsp.teleport.id.EXITPROMHOLLA
local ki = dsp.ki.LIGHT_OF_HOLLA
-- first promyvion completed
if player:getCurrentMission(COP) == dsp.mission.id.cop.BELOW_THE_ARKS then
player:completeMission(COP, dsp.mission.id.cop.BELOW_THE_ARKS)
player:addMission(COP, dsp.mission.id.cop.THE_MOTHERCRYSTALS)
player:setCharVar("cspromy2", 1)
player:setCharVar("PromathiaStatus", 0)
player:addKeyItem(ki)
player:messageSpecial(ID.text.CANT_REMEMBER, ki)
elseif player:getCurrentMission(COP) == dsp.mission.id.cop.THE_MOTHERCRYSTALS and not player:hasKeyItem(ki) then
-- second promyvion completed
if otherLights(player) < 2 then
player:setCharVar("cspromy3", 1)
player:addKeyItem(ki)
player:messageSpecial(ID.text.CANT_REMEMBER, ki)
-- final promyvion completed
else
player:completeMission(COP, dsp.mission.id.cop.THE_MOTHERCRYSTALS)
player:setCharVar("PromathiaStatus", 0)
player:addMission(COP, dsp.mission.id.cop.AN_INVITATION_WEST)
player:addKeyItem(ki)
player:messageSpecial(ID.text.CANT_REMEMBER, ki)
teleportTo = dsp.teleport.id.LUFAISE
end
end
player:addExp(1500)
player:addStatusEffectEx(dsp.effect.TELEPORT, 0, teleportTo, 0, 1)
end
end
| gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Eastern_Altepa_Desert/npcs/qm2.lua | 9 | 1389 | -----------------------------------
-- Area: Eastern Altepa Desert
-- NPC: qm2 (???)
-- Involved In Quest: 20 in Pirate Years
-- !pos 47.852 -7.808 403.391 114
-----------------------------------
local ID = require("scripts/zones/Eastern_Altepa_Desert/IDs")
require("scripts/globals/keyitems")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local twentyInPirateYearsCS = player:getCharVar("twentyInPirateYearsCS")
local tsuchigumoKilled = player:getCharVar("TsuchigumoKilled")
if twentyInPirateYearsCS == 3 and tsuchigumoKilled <= 1 and not GetMobByID(ID.mob.TSUCHIGUMO_OFFSET):isSpawned() and not GetMobByID(ID.mob.TSUCHIGUMO_OFFSET + 1):isSpawned() then
player:messageSpecial(ID.text.SENSE_OF_FOREBODING)
SpawnMob(ID.mob.TSUCHIGUMO_OFFSET):updateClaim(player)
SpawnMob(ID.mob.TSUCHIGUMO_OFFSET + 1):updateClaim(player)
elseif twentyInPirateYearsCS == 3 and tsuchigumoKilled >= 2 then
player:addKeyItem(dsp.ki.TRICK_BOX)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.TRICK_BOX)
player:setCharVar("twentyInPirateYearsCS", 4)
player:setCharVar("TsuchigumoKilled", 0)
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end | gpl-3.0 |
8devices/carambola2-luci | applications/luci-firewall/luasrc/model/cbi/firewall/forwards.lua | 85 | 3942 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010-2012 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 ds = require "luci.dispatcher"
local ft = require "luci.tools.firewall"
m = Map("firewall", translate("Firewall - Port Forwards"),
translate("Port forwarding allows remote computers on the Internet to \
connect to a specific computer or service within the \
private LAN."))
--
-- Port Forwards
--
s = m:section(TypedSection, "redirect", translate("Port Forwards"))
s.template = "cbi/tblsection"
s.addremove = true
s.anonymous = true
s.sortable = true
s.extedit = ds.build_url("admin/network/firewall/forwards/%s")
s.template_addremove = "firewall/cbi_addforward"
function s.create(self, section)
local n = m:formvalue("_newfwd.name")
local p = m:formvalue("_newfwd.proto")
local E = m:formvalue("_newfwd.extzone")
local e = m:formvalue("_newfwd.extport")
local I = m:formvalue("_newfwd.intzone")
local a = m:formvalue("_newfwd.intaddr")
local i = m:formvalue("_newfwd.intport")
if p == "other" or (p and a) then
created = TypedSection.create(self, section)
self.map:set(created, "target", "DNAT")
self.map:set(created, "src", E or "wan")
self.map:set(created, "dest", I or "lan")
self.map:set(created, "proto", (p ~= "other") and p or "all")
self.map:set(created, "src_dport", e)
self.map:set(created, "dest_ip", a)
self.map:set(created, "dest_port", i)
self.map:set(created, "name", n)
end
if p ~= "other" then
created = nil
end
end
function s.parse(self, ...)
TypedSection.parse(self, ...)
if created then
m.uci:save("firewall")
luci.http.redirect(ds.build_url(
"admin/network/firewall/redirect", created
))
end
end
function s.filter(self, sid)
return (self.map:get(sid, "target") ~= "SNAT")
end
ft.opt_name(s, DummyValue, translate("Name"))
local function forward_proto_txt(self, s)
return "%s-%s" %{
translate("IPv4"),
ft.fmt_proto(self.map:get(s, "proto"),
self.map:get(s, "icmp_type")) or "TCP+UDP"
}
end
local function forward_src_txt(self, s)
local z = ft.fmt_zone(self.map:get(s, "src"), translate("any zone"))
local a = ft.fmt_ip(self.map:get(s, "src_ip"), translate("any host"))
local p = ft.fmt_port(self.map:get(s, "src_port"))
local m = ft.fmt_mac(self.map:get(s, "src_mac"))
if p and m then
return translatef("From %s in %s with source %s and %s", a, z, p, m)
elseif p or m then
return translatef("From %s in %s with source %s", a, z, p or m)
else
return translatef("From %s in %s", a, z)
end
end
local function forward_via_txt(self, s)
local a = ft.fmt_ip(self.map:get(s, "src_dip"), translate("any router IP"))
local p = ft.fmt_port(self.map:get(s, "src_dport"))
if p then
return translatef("Via %s at %s", a, p)
else
return translatef("Via %s", a)
end
end
match = s:option(DummyValue, "match", translate("Match"))
match.rawhtml = true
match.width = "50%"
function match.cfgvalue(self, s)
return "<small>%s<br />%s<br />%s</small>" % {
forward_proto_txt(self, s),
forward_src_txt(self, s),
forward_via_txt(self, s)
}
end
dest = s:option(DummyValue, "dest", translate("Forward to"))
dest.rawhtml = true
dest.width = "40%"
function dest.cfgvalue(self, s)
local z = ft.fmt_zone(self.map:get(s, "dest"), translate("any zone"))
local a = ft.fmt_ip(self.map:get(s, "dest_ip"), translate("any host"))
local p = ft.fmt_port(self.map:get(s, "dest_port")) or
ft.fmt_port(self.map:get(s, "src_dport"))
if p then
return translatef("%s, %s in %s", a, p, z)
else
return translatef("%s in %s", a, z)
end
end
ft.opt_enabled(s, Flag, translate("Enable")).width = "1%"
return m
| apache-2.0 |
stallboy/configgen | example/lua/cfg/_cfgs.lua | 1 | 1488 | local cfg = {}
cfg._mk = require "common.mkcfg"
local pre = cfg._mk.pretable
cfg.ai = {}
---@type cfg.ai.ai
cfg.ai.ai = pre("cfg.ai.ai")
---@type cfg.ai.ai_action
cfg.ai.ai_action = pre("cfg.ai.ai_action")
---@type cfg.ai.ai_condition
cfg.ai.ai_condition = pre("cfg.ai.ai_condition")
cfg.equip = {}
---@type cfg.equip.ability
cfg.equip.ability = pre("cfg.equip.ability")
---@type cfg.equip.equipconfig
cfg.equip.equipconfig = pre("cfg.equip.equipconfig")
---@type cfg.equip.jewelry
cfg.equip.jewelry = pre("cfg.equip.jewelry")
---@type cfg.equip.jewelryrandom
cfg.equip.jewelryrandom = pre("cfg.equip.jewelryrandom")
---@type cfg.equip.jewelrysuit
cfg.equip.jewelrysuit = pre("cfg.equip.jewelrysuit")
---@type cfg.equip.jewelrytype
cfg.equip.jewelrytype = pre("cfg.equip.jewelrytype")
---@type cfg.equip.rank
cfg.equip.rank = pre("cfg.equip.rank")
cfg.other = {}
---@type cfg.other.drop
cfg.other.drop = pre("cfg.other.drop")
---@type cfg.other.loot
cfg.other.loot = pre("cfg.other.loot")
---@type cfg.other.lootitem
cfg.other.lootitem = pre("cfg.other.lootitem")
---@type cfg.other.monster
cfg.other.monster = pre("cfg.other.monster")
---@type cfg.other.signin
cfg.other.signin = pre("cfg.other.signin")
cfg.task = {}
---@type cfg.task.completeconditiontype
cfg.task.completeconditiontype = pre("cfg.task.completeconditiontype")
---@type cfg.task.task
cfg.task.task = pre("cfg.task.task")
---@type cfg.task.taskextraexp
cfg.task.taskextraexp = pre("cfg.task.taskextraexp")
return cfg
| mit |
DarkstarProject/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Waoud.lua | 9 | 7704 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Waoud
-- Standard Info NPC
-- Involved in quests: An Empty Vessel (BLU flag), Beginnings (BLU AF1)
-- !pos 65 -6 -78 50
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/missions")
require("scripts/globals/quests")
require("scripts/globals/npc_util")
local ID = require("scripts/zones/Aht_Urhgan_Whitegate/IDs")
-----------------------------------
function onTrade(player,npc,trade)
local anEmptyVessel = player:getQuestStatus(AHT_URHGAN,dsp.quest.id.ahtUrhgan.AN_EMPTY_VESSEL)
local anEmptyVesselProgress = player:getCharVar("AnEmptyVesselProgress")
local StoneID = player:getCharVar("EmptyVesselStone")
-- AN EMPTY VESSEL (dangruf stone, valkurm sunsand, or siren's tear)
if anEmptyVessel == QUEST_ACCEPTED and anEmptyVesselProgress == 3 and trade:hasItemQty(StoneID,1) and trade:getItemCount() == 1 then
player:startEvent(67,StoneID) -- get the stone to Aydeewa
end
end
function onTrigger(player,npc)
local anEmptyVessel = player:getQuestStatus(AHT_URHGAN,dsp.quest.id.ahtUrhgan.AN_EMPTY_VESSEL)
local anEmptyVesselProgress = player:getCharVar("AnEmptyVesselProgress")
local divinationReady = vanaDay() > player:getCharVar("LastDivinationDay")
local beginnings = player:getQuestStatus(AHT_URHGAN,dsp.quest.id.ahtUrhgan.BEGINNINGS)
-- AN EMPTY VESSEL
if ENABLE_TOAU == 1 and anEmptyVessel == QUEST_AVAILABLE and anEmptyVesselProgress <= 1 and player:getMainLvl() >= ADVANCED_JOB_LEVEL then
if divinationReady then
player:setCharVar("SuccessfullyAnswered",0)
player:startEvent(60,player:getGil()) -- you must answer these 10 questions
else
player:startEvent(63) -- you failed, and must wait a gameday to try again
end
elseif anEmptyVesselProgress == 2 then
if divinationReady and not player:needToZone() then
player:startEvent(65) -- gives you a clue about the stone he wants (specific conditions)
else -- Have not zoned, or have not waited, or both.
player:startEvent(64) -- you have succeeded, but you need to wait a gameday and zone
end
elseif anEmptyVesselProgress == 3 then
player:startEvent(66) -- reminds you about the item he wants
elseif anEmptyVesselProgress == 4 then
player:startEvent(68) -- reminds you to bring the item to Aydeewa
elseif anEmptyVessel == QUEST_COMPLETED and beginnings == QUEST_AVAILABLE and player:getCharVar("BluAFBeginnings_Waoud") == 0 then
player:startEvent(69) -- closing cutscene
-- BEGINNINGS
elseif anEmptyVessel == QUEST_COMPLETED and beginnings == QUEST_AVAILABLE and player:getCurrentMission(TOAU) > dsp.mission.id.toau.IMMORTAL_SENTRIES
and player:getMainJob() == dsp.job.BLU and player:getMainLvl() >= ADVANCED_JOB_LEVEL then
if not divinationReady then
player:startEvent(63)
elseif player:needToZone() then
player:startEvent(78,player:getGil()) -- dummy questions, costs you 1000 gil
else
player:startEvent(705,player:getGil()) -- start AF1 quest
end
elseif beginnings == QUEST_ACCEPTED then
local brand1 = player:hasKeyItem(dsp.ki.BRAND_OF_THE_SPRINGSERPENT)
local brand2 = player:hasKeyItem(dsp.ki.BRAND_OF_THE_GALESERPENT)
local brand3 = player:hasKeyItem(dsp.ki.BRAND_OF_THE_FLAMESERPENT)
local brand4 = player:hasKeyItem(dsp.ki.BRAND_OF_THE_SKYSERPENT)
local brand5 = player:hasKeyItem(dsp.ki.BRAND_OF_THE_STONESERPENT)
if brand1 and brand2 and brand3 and brand4 and brand5 then
player:startEvent(707) -- reward immortal's scimitar
else
player:startEvent(706,player:getGil()) -- clue about the five staging points, costs you 1000 gil
end
-- DEFAULT DIALOG
else
player:startEvent(61)
end
end
function onEventUpdate(player,csid,option)
-- AN EMPTY VESSEL
if csid == 60 then
local success = player:getCharVar("SuccessfullyAnswered")
-- record correct answers
if option < 40 then
local correctAnswers = {2,6,9,12,13,18,21,24,26,30}
for k,v in pairs(correctAnswers) do
if (v == option) then
player:setCharVar("SuccessfullyAnswered", success + 1)
break
end
end
-- determine results
elseif option == 40 then
if success < 2 then player:updateEvent(player:getGil(),0,0,0,0,0,0,10) -- Springserpent
elseif success < 4 then player:updateEvent(player:getGil(),0,0,0,0,0,0,20) -- Stoneserpent
elseif success < 6 then player:updateEvent(player:getGil(),0,0,0,0,0,0,30) -- Galeserpent
elseif success < 8 then player:updateEvent(player:getGil(),0,0,0,0,0,0,40) -- Flameserpent
elseif success < 10 then player:updateEvent(player:getGil(),0,0,0,0,0,0,60) -- Skyserpent
else
local rand = math.random(1,3)
switch (rand): caseof {
[1] = function (x) player:setCharVar("EmptyVesselStone",576) end, -- (576) Siren's Tear (576)
[2] = function (x) player:setCharVar("EmptyVesselStone",503) end, -- (502) Valkurm Sunsand (502)
[3] = function (x) player:setCharVar("EmptyVesselStone",553) end -- (553) Dangruf Stone (553)
}
player:setCharVar("SuccessfullyAnswered", 0)
player:updateEvent(player:getGil(),0,0,0,0,0,rand,70) -- all 5 serpents / success!
end
end
elseif csid == 65 and option == 2 then
player:setCharVar("AnEmptyVesselProgress",3)
-- BEGINNINGS
elseif csid == 78 and option == 40 then
local serpent = math.random(1,5) * 10
player:updateEvent(player:getGil(),0,0,0,0,0,0,serpent)
end
end
function onEventFinish(player,csid,option)
-- AN EMPTY VESSEL
if csid == 60 then
if option == 0 then
player:setCharVar("AnEmptyVesselProgress", 1)
elseif option == 50 then
player:needToZone(true)
player:setCharVar("LastDivinationDay",vanaDay())
player:setCharVar("AnEmptyVesselProgress",2)
player:addQuest(AHT_URHGAN,dsp.quest.id.ahtUrhgan.AN_EMPTY_VESSEL)
else
player:setCharVar("LastDivinationDay",vanaDay())
player:setCharVar("AnEmptyVesselProgress",1)
player:delGil(1000)
player:messageSpecial(ID.text.PAY_DIVINATION) -- You pay 1000 gil for the divination.
end
elseif csid == 67 then -- Turn in stone, go to Aydeewa
player:setCharVar("AnEmptyVesselProgress",4)
elseif csid == 69 and option == 1 then
player:needToZone(true)
player:setCharVar("LastDivinationDay",vanaDay())
player:setCharVar("BluAFBeginnings_Waoud",1)
-- BEGINNINGS
elseif csid == 78 and option == 1 then
player:setCharVar("LastDivinationDay",vanaDay())
player:delGil(1000)
player:messageSpecial(ID.text.PAY_DIVINATION) -- You pay 1000 gil for the divination.
elseif csid == 705 and option == 1 then
player:addQuest(AHT_URHGAN,dsp.quest.id.ahtUrhgan.BEGINNINGS)
elseif csid == 706 and option == 1 then
player:delGil(1000)
player:messageSpecial(ID.text.PAY_DIVINATION) -- You pay 1000 gil for the divination.
elseif csid == 707 then
npcUtil.completeQuest(player, AHT_URHGAN, dsp.quest.id.ahtUrhgan.BEGINNINGS, {item=17717})
end
end | gpl-3.0 |
DarkstarProject/darkstar | scripts/globals/spells/bluemagic/seedspray.lua | 4 | 1921 | -----------------------------------------
-- Spell: Seedspray
-- Delivers a threefold attack. Additional effect: Weakens defense. Chance of effect varies with TP
-- Spell cost: 61 MP
-- Monster Type: Plantoids
-- Spell Type: Physical (Slashing)
-- Blue Magic Points: 2
-- Stat Bonus: VIT+1
-- Level: 61
-- Casting Time: 4 seconds
-- Recast Time: 35 seconds
-- Skillchain Element(s): Ice (Primary) and Wind (Secondary) - (can open Impaction, Compression, Fragmentation, Scission or Gravitation can close Induration or Detonation)
-- Combos: Beast Killer
-----------------------------------------
require("scripts/globals/bluemagic")
require("scripts/globals/status")
require("scripts/globals/magic")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local params = {}
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_CRITICAL
params.dmgtype = dsp.damageType.SLASHING
params.scattr = SC_GRAVITATION
params.numhits = 3
params.multiplier = 1.925
params.tp150 = 1.25
params.tp300 = 1.25
params.azuretp = 1.25
params.duppercap = 61
params.str_wsc = 0.0
params.dex_wsc = 0.30
params.vit_wsc = 0.0
params.agi_wsc = 0.0
params.int_wsc = 0.20
params.mnd_wsc = 0.0
params.chr_wsc = 0.0
damage = BluePhysicalSpell(caster, target, spell, params)
damage = BlueFinalAdjustments(caster, target, spell, damage, params)
local chance = math.random()
if (damage > 0 and chance > 1) then
local typeEffect = dsp.effect.DEFENSE_DOWN
target:delStatusEffect(typeEffect)
target:addStatusEffect(typeEffect,4,0,getBlueEffectDuration(caster,resist,typeEffect))
end
return damage
end
| gpl-3.0 |
tcatm/luci | applications/luci-app-radvd/luasrc/model/cbi/radvd/prefix.lua | 61 | 3557 | -- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local sid = arg[1]
local utl = require "luci.util"
m = Map("radvd", translatef("Radvd - Prefix"),
translate("Radvd is a router advertisement daemon for IPv6. " ..
"It listens to router solicitations and sends router advertisements " ..
"as described in RFC 4861."))
m.redirect = luci.dispatcher.build_url("admin/network/radvd")
if m.uci:get("radvd", sid) ~= "prefix" then
luci.http.redirect(m.redirect)
return
end
s = m:section(NamedSection, sid, "interface", translate("Prefix Configuration"))
s.addremove = false
s:tab("general", translate("General"))
s:tab("advanced", translate("Advanced"))
--
-- General
--
o = s:taboption("general", Flag, "ignore", translate("Enable"))
o.rmempty = false
function o.cfgvalue(...)
local v = Flag.cfgvalue(...)
return v == "1" and "0" or "1"
end
function o.write(self, section, value)
Flag.write(self, section, value == "1" and "0" or "1")
end
o = s:taboption("general", Value, "interface", translate("Interface"),
translate("Specifies the logical interface name this section belongs to"))
o.template = "cbi/network_netlist"
o.nocreate = true
o.optional = false
function o.formvalue(...)
return Value.formvalue(...) or "-"
end
function o.validate(self, value)
if value == "-" then
return nil, translate("Interface required")
end
return value
end
function o.write(self, section, value)
m.uci:set("radvd", section, "ignore", 0)
m.uci:set("radvd", section, "interface", value)
end
o = s:taboption("general", DynamicList, "prefix", translate("Prefixes"),
translate("Advertised IPv6 prefixes. If empty, the current interface prefix is used"))
o.optional = true
o.datatype = "ip6addr"
o.placeholder = translate("default")
function o.cfgvalue(self, section)
local l = { }
local v = m.uci:get_list("radvd", section, "prefix")
for v in utl.imatch(v) do
l[#l+1] = v
end
return l
end
o = s:taboption("general", Flag, "AdvOnLink", translate("On-link determination"),
translate("Indicates that this prefix can be used for on-link determination (RFC4861)"))
o.rmempty = false
o.default = "1"
o = s:taboption("general", Flag, "AdvAutonomous", translate("Autonomous"),
translate("Indicates that this prefix can be used for autonomous address configuration (RFC4862)"))
o.rmempty = false
o.default = "1"
--
-- Advanced
--
o = s:taboption("advanced", Flag, "AdvRouterAddr", translate("Advertise router address"),
translate("Indicates that the address of interface is sent instead of network prefix, as is required by Mobile IPv6"))
o = s:taboption("advanced", Value, "AdvValidLifetime", translate("Valid lifetime"),
translate("Advertises the length of time in seconds that the prefix is valid for the purpose of on-link determination."))
o.datatype = 'or(uinteger,"infinity")'
o.placeholder = 86400
o = s:taboption("advanced", Value, "AdvPreferredLifetime", translate("Preferred lifetime"),
translate("Advertises the length of time in seconds that addresses generated from the prefix via stateless address autoconfiguration remain preferred."))
o.datatype = 'or(uinteger,"infinity")'
o.placeholder = 14400
o = s:taboption("advanced", Value, "Base6to4Interface", translate("6to4 interface"),
translate("Specifies a logical interface name to derive a 6to4 prefix from. The interfaces public IPv4 address is combined with 2002::/3 and the value of the prefix option"))
o.template = "cbi/network_netlist"
o.nocreate = true
o.unspecified = true
return m
| apache-2.0 |
Fenix-XI/Fenix | scripts/zones/Quicksand_Caves/npcs/_5s1.lua | 13 | 1251 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Ornate Door
-- Door blocked by Weight system
-- @pos 21 0 -180 208
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local difX = player:getXPos()-(30);
local difZ = player:getZPos()-(-180);
local Distance = math.sqrt( math.pow(difX,2) + math.pow(difZ,2) );
if (Distance < 3) then
return -1;
end
player:messageSpecial(DOOR_FIRMLY_SHUT);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
wez2020/nwewew | plugins/Member_Manager.lua | 24 | 11556 | local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' '..member_id..' banned!')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'globalban' then
send_large_msg(receiver, 'User @'..member..' '..member_id..'globally banned!')
return banall_user(member_id, chat_id)
elseif get_cmd == 'globalunban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group " ..string.gsub(msg.to.print_name, "_", " ").. " ID:"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'globalban' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User '..user_id..' globally banned!'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'globalunban' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User '..user_id..' globally unbanned!'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "glbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Gg]lobalban) (.*)$",
"^[!/]([Gg]lobalban)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]lbanlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Gg]lobalunban) (.*)$",
"^[!/]([Gg]lobalunban)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
Fenix-XI/Fenix | scripts/zones/RuAun_Gardens/npcs/relic.lua | 13 | 1848 | -----------------------------------
-- Area: Ru'Aun Gardens
-- NPC: <this space intentionally left blank>
-- @pos -241 -12 332 130
-----------------------------------
package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/RuAun_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece
if (player:getVar("RELIC_IN_PROGRESS") == 18299 and trade:getItemCount() == 4 and trade:hasItemQty(18299,1) and
trade:hasItemQty(1578,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1451,1)) then
player:startEvent(60,18300);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 60) then
if (player:getFreeSlotsCount() < 2) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18300);
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1450);
else
player:tradeComplete();
player:addItem(18300);
player:addItem(1450,30);
player:messageSpecial(ITEM_OBTAINED,18300);
player:messageSpecial(ITEMS_OBTAINED,1450,30);
player:setVar("RELIC_IN_PROGRESS",0);
end
end
end; | gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Bhaflau_Thickets/npcs/Runic_Portal.lua | 9 | 1308 | -----------------------------------
-- Area: Bhaflau Thickets
-- NPC: Runic Portal
-- Mamook Ja Teleporter Back to Aht Urgan Whitegate
-- !pos -211 -11 -818 52
-----------------------------------
local ID = require("scripts/zones/Bhaflau_Thickets/IDs")
-----------------------------------
require("scripts/globals/besieged")
require("scripts/globals/missions")
require("scripts/globals/teleports")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
if player:getCurrentMission(TOAU) == dsp.mission.id.toau.IMMORTAL_SENTRIES and player:getCharVar("AhtUrganStatus") == 1 then
player:startEvent(111)
elseif player:getCurrentMission(TOAU) > dsp.mission.id.toau.IMMORTAL_SENTRIES then
if dsp.besieged.hasRunicPortal(player, dsp.teleport.runic_portal.MAMOOL) then
player:startEvent(109)
else
player:startEvent(111)
end
else
player:messageSpecial(ID.text.RESPONSE)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if option == 1 then
if csid == 111 then
dsp.besieged.addRunicPortal(player, dsp.teleport.runic_portal.MAMOOL)
end
dsp.teleport.toChamberOfPassage(player)
end
end | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Aht_Urhgan_Whitegate/npcs/Tateeya.lua | 7 | 2616 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Tateeya
-- Automaton Attachment Unlocks
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local tradeStatus = player:getVar('TateeyaTradeStatus');
local automatonName = player:getAutomatonName();
if (tradeStatus == 1) then
for i=0,7 do
local subid = trade:getItemSubId(i);
if (subid >= 0x2000 and subid < 0x2800) then
if (player:unlockAttachment(subid)) then
player:setVar('TateeyaUnlock', subid);
player:startEventString(0x028B, automatonName, automatonName, automatonName, automatonName, subid); --unlock attachment event
trade:confirmItem(i);
player:confirmTrade();
else
player:startEvent(0x028C); --already unlocked event
end
break;
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local tradeStatus = player:getVar('TateeyaTradeStatus');
local automatonName = player:getAutomatonName();
if (tradeStatus == 0) then
if (player:getMainJob() == JOB_PUP) then
player:startEventString(0x028A, automatonName, automatonName, automatonName, automatonName); --trade me to unlock attachments
else
player:startEvent(0x0102); --default no PUP CS
end
else
player:startEventString(0x028A, automatonName, automatonName, automatonName, automatonName, 1);
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 == 0x028A) then --unlocking attachments explanation
player:setVar('TateeyaTradeStatus', 1);
elseif (csid == 0x028B) then
local subid = player:getVar('TateeyaUnlock');
player:messageSpecial(AUTOMATON_ATTACHMENT_UNLOCK, subid);
player:setVar('TateeyaUnlock',0);
end
end;
| gpl-3.0 |
marcel-sch/luci | applications/luci-app-ddns/luasrc/model/cbi/ddns/overview.lua | 33 | 9247 | -- Copyright 2014 Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
-- Licensed to the public under the Apache License 2.0.
local NXFS = require "nixio.fs"
local CTRL = require "luci.controller.ddns" -- this application's controller
local DISP = require "luci.dispatcher"
local HTTP = require "luci.http"
local SYS = require "luci.sys"
local DDNS = require "luci.tools.ddns" -- ddns multiused functions
-- show hints ?
show_hints = not (DDNS.check_ipv6() -- IPv6 support
and DDNS.check_ssl() -- HTTPS support
and DDNS.check_proxy() -- Proxy support
and DDNS.check_bind_host() -- DNS TCP support
)
-- correct ddns-scripts version
need_update = DDNS.ipkg_ver_compare(DDNS.ipkg_ver_installed("ddns-scripts"), "<<", CTRL.DDNS_MIN)
-- html constants
font_red = [[<font color="red">]]
font_off = [[</font>]]
bold_on = [[<strong>]]
bold_off = [[</strong>]]
-- cbi-map definition -- #######################################################
m = Map("ddns")
-- first need to close <a> from cbi map template our <a> closed by template
m.title = [[</a><a href="javascript:alert(']]
.. translate("Version Information")
.. [[\n\nluci-app-ddns]]
.. [[\n\t]] .. translate("Version") .. [[:\t]] .. DDNS.ipkg_ver_installed("luci-app-ddns")
.. [[\n\nddns-scripts ]] .. translate("required") .. [[:]]
.. [[\n\t]] .. translate("Version") .. [[:\t]] .. CTRL.DDNS_MIN .. [[ ]] .. translate("or higher")
.. [[\n\nddns-scripts ]] .. translate("installed") .. [[:]]
.. [[\n\t]] .. translate("Version") .. [[:\t]] .. DDNS.ipkg_ver_installed("ddns-scripts")
.. [[\n\n]]
.. [[')">]]
.. translate("Dynamic DNS")
m.description = translate("Dynamic DNS allows that your router can be reached with " ..
"a fixed hostname while having a dynamically changing " ..
"IP address.")
m.on_after_commit = function(self)
if self.changed then -- changes ?
if SYS.init.enabled("ddns") then -- ddns service enabled, restart all
os.execute("/etc/init.d/ddns restart")
else -- ddns service disabled, send SIGHUP to running
os.execute("killall -1 dynamic_dns_updater.sh")
end
end
end
-- SimpleSection definiton -- ##################################################
-- with all the JavaScripts we need for "a good Show"
a = m:section( SimpleSection )
a.template = "ddns/overview_status"
-- SimpleSection definition -- #################################################
-- show Hints to optimize installation and script usage
-- only show if service not enabled
-- or no IPv6 support
-- or not GNU Wget and not cURL (for https support)
-- or not GNU Wget but cURL without proxy support
-- or not BIND's host
-- or ddns-scripts package need update
if show_hints or need_update or not SYS.init.enabled("ddns") then
s = m:section( SimpleSection, translate("Hints") )
-- ddns_scripts needs to be updated for full functionality
if need_update then
local dv = s:option(DummyValue, "_update_needed")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = font_red .. bold_on ..
translate("Software update required") .. bold_off .. font_off
dv.value = translate("The currently installed 'ddns-scripts' package did not support all available settings.") ..
"<br />" ..
translate("Please update to the current version!")
end
-- DDNS Service disabled
if not SYS.init.enabled("ddns") then
local dv = s:option(DummyValue, "_not_enabled")
dv.titleref = DISP.build_url("admin", "system", "startup")
dv.rawhtml = true
dv.title = bold_on ..
translate("DDNS Autostart disabled") .. bold_off
dv.value = translate("Currently DDNS updates are not started at boot or on interface events." .. "<br />" ..
"You can start/stop each configuration here. It will run until next reboot.")
end
-- Show more hints on a separate page
if show_hints then
local dv = s:option(DummyValue, "_separate")
dv.titleref = DISP.build_url("admin", "services", "ddns", "hints")
dv.rawhtml = true
dv.title = bold_on ..
translate("Show more") .. bold_off
dv.value = translate("Follow this link" .. "<br />" ..
"You will find more hints to optimize your system to run DDNS scripts with all options")
end
end
-- TableSection definition -- ##################################################
ts = m:section( TypedSection, "service",
translate("Overview"),
translate("Below is a list of configured DDNS configurations and their current state.")
.. "<br />"
.. translate("If you want to send updates for IPv4 and IPv6 you need to define two separate Configurations "
.. "i.e. 'myddns_ipv4' and 'myddns_ipv6'")
.. "<br />"
.. [[<a href="]] .. DISP.build_url("admin", "services", "ddns", "global") .. [[">]]
.. translate("To change global settings click here") .. [[</a>]] )
ts.sectionhead = translate("Configuration")
ts.template = "cbi/tblsection"
ts.addremove = true
ts.extedit = DISP.build_url("admin", "services", "ddns", "detail", "%s")
function ts.create(self, name)
AbstractSection.create(self, name)
HTTP.redirect( self.extedit:format(name) )
end
-- Domain and registered IP -- #################################################
dom = ts:option(DummyValue, "_domainIP",
translate("Hostname/Domain") .. "<br />" .. translate("Registered IP") )
dom.template = "ddns/overview_doubleline"
function dom.set_one(self, section)
local domain = self.map:get(section, "domain") or ""
if domain ~= "" then
return domain
else
return [[<em>]] .. translate("config error") .. [[</em>]]
end
end
function dom.set_two(self, section)
local domain = self.map:get(section, "domain") or ""
if domain == "" then return "" end
local dnsserver = self.map:get(section, "dnsserver") or ""
local use_ipv6 = tonumber(self.map:get(section, "use_ipv6") or 0)
local force_ipversion = tonumber(self.map:get(section, "force_ipversion") or 0)
local force_dnstcp = tonumber(self.map:get(section, "force_dnstcp") or 0)
local command = [[/usr/lib/ddns/dynamic_dns_lucihelper.sh]]
if not NXFS.access(command, "rwx", "rx", "rx") then
NXFS.chmod(command, 755)
end
command = command .. [[ get_registered_ip ]] .. domain .. [[ ]] .. use_ipv6 ..
[[ ]] .. force_ipversion .. [[ ]] .. force_dnstcp .. [[ ]] .. dnsserver
local ip = SYS.exec(command)
if ip == "" then ip = translate("no data") end
return ip
end
-- enabled
ena = ts:option( Flag, "enabled",
translate("Enabled"))
ena.template = "ddns/overview_enabled"
ena.rmempty = false
function ena.parse(self, section)
DDNS.flag_parse(self, section)
end
-- show PID and next update
upd = ts:option( DummyValue, "_update",
translate("Last Update") .. "<br />" .. translate("Next Update"))
upd.template = "ddns/overview_doubleline"
function upd.set_one(self, section) -- fill Last Update
-- get/validate last update
local uptime = SYS.uptime()
local lasttime = DDNS.get_lastupd(section)
if lasttime > uptime then -- /var might not be linked to /tmp and cleared on reboot
lasttime = 0
end
-- no last update happen
if lasttime == 0 then
return translate("never")
-- we read last update
else
-- calc last update
-- os.epoch - sys.uptime + lastupdate(uptime)
local epoch = os.time() - uptime + lasttime
-- use linux date to convert epoch
return DDNS.epoch2date(epoch)
end
end
function upd.set_two(self, section) -- fill Next Update
-- get enabled state
local enabled = tonumber(self.map:get(section, "enabled") or 0)
local datenext = translate("unknown error") -- formatted date of next update
-- get force seconds
local force_interval = tonumber(self.map:get(section, "force_interval") or 72)
local force_unit = self.map:get(section, "force_unit") or "hours"
local force_seconds = DDNS.calc_seconds(force_interval, force_unit)
-- get last update and get/validate PID
local uptime = SYS.uptime()
local lasttime = DDNS.get_lastupd(section)
if lasttime > uptime then -- /var might not be linked to /tmp and cleared on reboot
lasttime = 0
end
local pid = DDNS.get_pid(section)
-- calc next update
if lasttime > 0 then
local epoch = os.time() - uptime + lasttime + force_seconds
-- use linux date to convert epoch
datelast = DDNS.epoch2date(epoch)
end
-- process running but update needs to happen
if pid > 0 and ( lasttime + force_seconds - uptime ) < 0 then
datenext = translate("Verify")
-- run once
elseif force_seconds == 0 then
datenext = translate("Run once")
-- no process running and NOT enabled
elseif pid == 0 and enabled == 0 then
datenext = translate("Disabled")
-- no process running and NOT
elseif pid == 0 and enabled ~= 0 then
datenext = translate("Stopped")
end
return datenext
end
-- start/stop button
btn = ts:option( Button, "_startstop",
translate("Process ID") .. "<br />" .. translate("Start / Stop") )
btn.template = "ddns/overview_startstop"
function btn.cfgvalue(self, section)
local pid = DDNS.get_pid(section)
if pid > 0 then
btn.inputtitle = "PID: " .. pid
btn.inputstyle = "reset"
btn.disabled = false
elseif (self.map:get(section, "enabled") or "0") ~= "0" then
btn.inputtitle = translate("Start")
btn.inputstyle = "apply"
btn.disabled = false
else
btn.inputtitle = "----------"
btn.inputstyle = "button"
btn.disabled = true
end
return true
end
return m
| apache-2.0 |
0BRWUEN0/BRWUEEN | plugins/lock_bot.lua | 1 | 2482 | --[[
--@BRWUEN
--@vip_api
--]]
local function isAntiBotEnabled (chatId)
local hash = 'bot:lock:'..chatId
local lock = redis:get(hash)
return lock
end
local function enableAntiBot (chatId)
local hash = 'bot:lock:'..chatId
redis:set(hash, true)
end
local function disableAntiBot (chatId)
local hash = 'bot:lock:'..chatId
redis:del(hash)
end
local function isABot (user)
local binFlagIsBot = 4096
local result = bit32.band(user.flags, binFlagIsBot)
return result == binFlagIsBot
end
local function isABotBadWay (user)
local username = user.username or ''
return username:match("[Bb]ot$")
end
local function kickUser(userId, chatId)
local channel = 'channel#id'..chatId
local user = 'user#id'..userId
channel_kick_user(channel, user, function (data, success, result)
if success ~= 1 then
print('I can\'t kick '..data.user..' but should be kicked')
end
end, {chat=chat, user=user})
end
local function mohammed (msg, matches)
if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then
if msg.to.type ~= 'chat' and msg.to.type ~= 'channel' then
return nil
end
end
local chatId = msg.to.id
if matches[1] == 'قفل البوتات' then
enableAntiBot(chatId)
return 'تہٍـﮧ௸ِـِۣـّ̐ہٰمہ قفلـﮩﮨہٰٰہٰ ألـبـ℘ـِوُِتًأِِتً 🎈 💥۶ֆᵛ͢ᵎᵖ ⌯ '
end
if matches[1] == 'فتح البوتات' then
disableAntiBot(chatId)
return 'تہٍـﮧ௸ِـِۣـّ̐ہٰمہ فتہٍـﮧ௸ِـِۣـّ̐ہٰح ألـبـ℘ـِوُِتًأِِتً 🎈 💥۶ֆᵛ͢ᵎᵖ ⌯'
end
if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then
local user = msg.action.user or msg.from
if isABotBadWay(user) then
print("It' a bot!")
if isAntiBotEnabled(chatId) then
print('bot is locked')
local userId = user.id
if not isBotAllowed(userId, chatId) then
kickUser(userId, chatId)
else
print('')
end
end
end
end
end
return {
description = 'Anti bot create by Mustafa ip',
usage = {
'/bot lock: locked add bots to supergroup',
'/bot unlock: unlock add bots to supergroup'
},
patterns = {
'^(قفل البوتات)$',
'^(فتح البوتات)$',
'^!!tgservice (chat_add_user)$',
'^!!tgservice (chat_add_user_link)$'
},
run = mohammed
}
| gpl-2.0 |
Fenix-XI/Fenix | scripts/globals/weaponskills/shockwave.lua | 10 | 1454 | -----------------------------------
-- Shockwave
-- Great Sword weapon skill
-- Skill level: 150
-- Delivers an area of effect attack. Sleeps enemies. Duration of effect varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Aqua Gorget.
-- Aligned with the Aqua Belt.
-- Element: None
-- Modifiers: STR:30% ; MND: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, tp, primary)
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.3; 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, wsID, params, tp, primary);
if (damage > 0 and target:hasStatusEffect(EFFECT_SLEEP_I) == false) then
local duration = (tp/1000 * 60);
target:addStatusEffect(EFFECT_SLEEP_I, 1, 0, duration);
end
return tpHits, extraHits, criticalHit, damage;
end | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Windurst_Woods/npcs/Hae_Jakkya.lua | 13 | 1359 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Hae Jakkya
-- Working 100%
-----------------------------------
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
chasingStatus = player:getQuestStatus(WINDURST,CHASING_TALES);
if (player:hasKeyItem(126) ==true) then
player:startEvent(0x0196);
elseif (player:getVar("CHASING_TALES_TRACK_BOOK") == 1) then
player:startEvent(0x0193);
elseif (player:hasKeyItem(149)) then
player:startEvent(0x0192); -- Neeed CS here
else
player:startEvent(0x29);
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 == 0x0192) then
player:setVar("CHASING_TALES_TRACK_BOOK",1);
end
end;
| gpl-3.0 |
ungarscool1/HL2RP | hl2rp/gamemode/modules/fspectate/cl_init.lua | 1 | 14012 | local stopSpectating, startFreeRoam
local isSpectating = false
local specEnt
local thirdperson = true
local isRoaming = false
local roamPos -- the position when roaming free
local roamVelocity = Vector(0)
/*---------------------------------------------------------------------------
startHooks
FAdmin tab buttons
---------------------------------------------------------------------------*/
hook.Add("Initialize", "FSpectate", function()
if not FAdmin then return end
FAdmin.StartHooks["zzSpectate"] = function()
FAdmin.Commands.AddCommand("Spectate", nil, "<Player>")
-- Right click option
FAdmin.ScoreBoard.Main.AddPlayerRightClick("Spectate", function(ply)
if not IsValid(ply) then return end
RunConsoleCommand("FSpectate", ply:UserID())
end)
local canSpectate = false
CAMI.PlayerHasAccess(LocalPlayer(), "FSpectate", function(b, _)
canSpectate = true
end)
-- Spectate option in player menu
FAdmin.ScoreBoard.Player:AddActionButton("Spectate", "fadmin/icons/spectate", Color(0, 200, 0, 255), function(ply) return canSpectate and ply ~= LocalPlayer() end, function(ply)
if not IsValid(ply) then return end
RunConsoleCommand("FSpectate", ply:UserID())
end)
end
end)
/*---------------------------------------------------------------------------
Get the thirdperson position
---------------------------------------------------------------------------*/
local function getThirdPersonPos(ply)
local aimvector = LocalPlayer():GetAimVector()
local startPos = ply:GetShootPos()
local endpos = startPos - aimvector * 100
local tracer = {
start = startPos,
endpos = endpos,
filter = specEnt
}
local trace = util.TraceLine(tracer)
return trace.HitPos + trace.HitNormal * 10
end
/*---------------------------------------------------------------------------
Get the CalcView table
---------------------------------------------------------------------------*/
local view = {}
local function getCalcView()
if not isRoaming then
if thirdperson then
view.origin = getThirdPersonPos(specEnt)
view.angles = LocalPlayer():EyeAngles()
else
view.origin = specEnt:GetShootPos()
view.angles = specEnt:EyeAngles()
end
roamPos = view.origin
view.drawviewer = false
return view
end
view.origin = roamPos
view.angles = LocalPlayer():EyeAngles()
view.drawviewer = true
return view
end
/*---------------------------------------------------------------------------
specCalcView
Override the view for the player to look through the spectated player's eyes
---------------------------------------------------------------------------*/
local function specCalcView(ply, origin, angles, fov)
if not IsValid(specEnt) and not isRoaming then
startFreeRoam()
return
end
view = getCalcView()
if IsValid(specEnt) then
specEnt:SetNoDraw(not thirdperson)
end
return view
end
/*---------------------------------------------------------------------------
Find the right player to spectate
---------------------------------------------------------------------------*/
local function findNearestPlayer()
local aimvec = LocalPlayer():GetAimVector()
local foundPly, foundDot = nil, 0
for _, ply in pairs(player.GetAll()) do
if ply == LocalPlayer() then continue end
local pos = ply:GetShootPos()
local dot = (pos - roamPos):GetNormalized():Dot(aimvec)
-- Discard players you're not looking at
if dot < 0.97 then continue end
-- not a better alternative
if dot < foundDot then continue end
local trace = util.QuickTrace(roamPos, pos - roamPos, ply)
if trace.Hit then continue end
foundPly, foundDot = ply, dot
end
return foundPly
end
/*---------------------------------------------------------------------------
Spectate the person you're looking at while you're roaming
---------------------------------------------------------------------------*/
local function spectateLookingAt()
local foundPly = findNearestPlayer()
if not IsValid(foundPly) then return end
RunConsoleCommand("FSpectate", foundPly:SteamID())
end
/*---------------------------------------------------------------------------
specBinds
Change binds to perform spectate specific tasks
---------------------------------------------------------------------------*/
-- Manual keysDown table, so I can return true in plyBindPress and still detect key presses
local keysDown = {}
local function specBinds(ply, bind, pressed)
if bind == "+jump" then
stopSpectating()
return true
elseif bind == "+reload" and pressed then
local pos = getCalcView().origin - Vector(0, 0, 64)
RunConsoleCommand("FTPToPos", string.format("%d, %d, %d", pos.x, pos.y, pos.z),
string.format("%d, %d, %d", roamVelocity.x, roamVelocity.y, roamVelocity.z))
stopSpectating()
elseif bind == "+attack" and pressed then
if not isRoaming then
startFreeRoam()
else
spectateLookingAt()
end
return true
elseif bind == "+attack2" and pressed then
if isRoaming then
roamPos = roamPos + LocalPlayer():GetAimVector() * 500
return true
end
thirdperson = not thirdperson
return true
elseif isRoaming and not LocalPlayer():KeyDown(IN_USE) then
local key = string.lower(string.match(bind, "+([a-z A-Z 0-9]+)") or "")
if not key or key == "use" or key == "showscores" or string.find(bind, "messagemode") then return end
keysDown[key:upper()] = pressed
return true
end
-- Do not return otherwise, spectating admins should be able to move to avoid getting detected
end
/*---------------------------------------------------------------------------
Scoreboardshow
Set to main view when roaming, open on a player when spectating
---------------------------------------------------------------------------*/
local function fadminmenushow()
if isRoaming then
FAdmin.ScoreBoard.ChangeView("Main")
elseif IsValid(specEnt) and specEnt:IsPlayer() then
FAdmin.ScoreBoard.ChangeView("Main")
FAdmin.ScoreBoard.ChangeView("Player", specEnt)
end
end
/*---------------------------------------------------------------------------
RenderScreenspaceEffects
Draws the lines from players' eyes to where they are looking
---------------------------------------------------------------------------*/
local LineMat = Material("cable/new_cable_lit")
local linesToDraw = {}
local function lookingLines()
if not linesToDraw[0] then return end
render.SetMaterial(LineMat)
cam.Start3D(view.origin, view.angles)
for i = 0, #linesToDraw, 3 do
render.DrawBeam(linesToDraw[i], linesToDraw[i + 1], 4, 0.01, 10, linesToDraw[i + 2])
end
cam.End3D()
end
/*---------------------------------------------------------------------------
gunpos
Gets the position of a player's gun
---------------------------------------------------------------------------*/
local function gunpos(ply)
local wep = ply:GetActiveWeapon()
if not IsValid(wep) then return ply:EyePos() end
local att = wep:GetAttachment(1)
if not att then return ply:EyePos() end
return att.Pos
end
/*---------------------------------------------------------------------------
Spectate think
Free roaming position updates
---------------------------------------------------------------------------*/
local function specThink()
local ply = LocalPlayer()
-- Update linesToDraw
local pls = player.GetAll()
local lastPly = 0
local skip = 0
for i = 0, #pls - 1 do
local p = pls[i + 1]
if not isRoaming and p == specEnt and not thirdperson then skip = skip + 3 continue end
local tr = p:GetEyeTrace()
local sp = gunpos(p)
local pos = i * 3 - skip
linesToDraw[pos] = tr.HitPos
linesToDraw[pos + 1] = sp
linesToDraw[pos + 2] = team.GetColor(p:Team())
lastPly = i
end
-- Remove entries from linesToDraw that don't match with a player anymore
for i = #linesToDraw, lastPly * 3 + 3, -1 do linesToDraw[i] = nil end
if not isRoaming or keysDown["USE"] then return end
local roamSpeed = 1000
local aimVec = ply:GetAimVector()
local direction
local frametime = RealFrameTime()
if keysDown["FORWARD"] then
direction = aimVec
elseif keysDown["BACK"] then
direction = -aimVec
end
if keysDown["MOVELEFT"] then
local right = aimVec:Angle():Right()
direction = direction and (direction - right):GetNormalized() or -right
elseif keysDown["MOVERIGHT"] then
local right = aimVec:Angle():Right()
direction = direction and (direction + right):GetNormalized() or right
end
if keysDown["SPEED"] then
roamSpeed = 2500
elseif keysDown["WALK"] or keysDown["DUCK"] then
roamSpeed = 300
end
roamVelocity = (direction or Vector(0, 0, 0)) * roamSpeed
roamPos = roamPos + roamVelocity * frametime
end
/*---------------------------------------------------------------------------
Draw help on the screen
---------------------------------------------------------------------------*/
local uiForeground, uiBackground = Color(240, 240, 255, 255), Color(20, 20, 20, 120)
local red = Color(255, 0, 0, 255)
local function drawHelp()
local scrHalfH = math.floor(ScrH() / 2)
draw.WordBox(2, 10, scrHalfH, "Left click: (Un)select player to spectate", "UiBold", uiBackground, uiForeground)
draw.WordBox(2, 10, scrHalfH + 20, isRoaming and "Right click: quickly move forwards" or "Right click: toggle thirdperson", "UiBold", uiBackground, uiForeground)
draw.WordBox(2, 10, scrHalfH + 40, "Jump: Stop spectating", "UiBold", uiBackground, uiForeground)
draw.WordBox(2, 10, scrHalfH + 60, "Reload: Stop spectating and teleport", "UiBold", uiBackground, uiForeground)
if FAdmin then
draw.WordBox(2, 10, scrHalfH + 80, "Opening FAdmin's menu while spectating a player", "UiBold", uiBackground, uiForeground)
draw.WordBox(2, 10, scrHalfH + 100, "\twill open their page!", "UiBold", uiBackground, uiForeground)
end
local target = findNearestPlayer()
local pls = player.GetAll()
for i = 1, #pls do
local ply = pls[i]
if not isRoaming and ply == specEnt then continue end
local pos = ply:GetShootPos():ToScreen()
if not pos.visible then continue end
local x, y = pos.x, pos.y
draw.RoundedBox(2, x, y - 6, 12, 12, team.GetColor(ply:Team()))
draw.WordBox(2, x, y - 66, ply:Nick(), "UiBold", uiBackground, uiForeground)
draw.WordBox(2, x, y - 46, "Health: " .. ply:Health(), "UiBold", uiBackground, uiForeground)
draw.WordBox(2, x, y - 26, ply:GetUserGroup(), "UiBold", uiBackground, uiForeground)
if ply == target then
draw.WordBox(2, x, y - 86, "Left click to spectate!", "UiBold", uiBackground, uiForeground)
end
end
if not isRoaming then return end
if not IsValid(target) then return end
local mins, maxs = target:LocalToWorld(target:OBBMins()):ToScreen(), target:LocalToWorld(target:OBBMaxs()):ToScreen()
draw.RoundedBox(12, mins.x, mins.y, maxs.x - mins.x, maxs.y - mins.y, red)
end
/*---------------------------------------------------------------------------
Start roaming free, rather than spectating a given player
---------------------------------------------------------------------------*/
startFreeRoam = function()
if IsValid(specEnt) then
roamPos = thirdperson and getThirdPersonPos(specEnt) or specEnt:GetShootPos()
specEnt:SetNoDraw(false)
else
roamPos = isSpectating and roamPos or LocalPlayer():GetShootPos()
end
specEnt = nil
isRoaming = true
keysDown = {}
end
/*---------------------------------------------------------------------------
specEnt
Spectate a player
---------------------------------------------------------------------------*/
local function startSpectate(um)
isRoaming = net.ReadBool()
specEnt = net.ReadEntity()
specEnt = IsValid(specEnt) and specEnt:IsPlayer() and specEnt or nil
if isRoaming then
startFreeRoam()
end
isSpectating = true
keysDown = {}
hook.Add("CalcView", "FSpectate", specCalcView)
hook.Add("PlayerBindPress", "FSpectate", specBinds)
hook.Add("ShouldDrawLocalPlayer", "FSpectate", function() return isRoaming or thirdperson end)
hook.Add("Think", "FSpectate", specThink)
hook.Add("HUDPaint", "FSpectate", drawHelp)
hook.Add("FAdmin_ShowFAdminMenu", "FSpectate", fadminmenushow)
hook.Add("RenderScreenspaceEffects", "FSpectate", lookingLines)
timer.Create("FSpectatePosUpdate", 0.5, 0, function()
if not isRoaming then return end
RunConsoleCommand("_FSpectatePosUpdate", roamPos.x, roamPos.y, roamPos.z)
end)
end
net.Receive("FSpectate", startSpectate)
/*---------------------------------------------------------------------------
stopSpectating
Stop spectating a player
---------------------------------------------------------------------------*/
stopSpectating = function()
hook.Remove("CalcView", "FSpectate")
hook.Remove("PlayerBindPress", "FSpectate")
hook.Remove("ShouldDrawLocalPlayer", "FSpectate")
hook.Remove("Think", "FSpectate")
hook.Remove("HUDPaint", "FSpectate")
hook.Remove("FAdmin_ShowFAdminMenu", "FSpectate")
hook.Remove("RenderScreenspaceEffects", "FSpectate")
timer.Remove("FSpectatePosUpdate")
if IsValid(specEnt) then
specEnt:SetNoDraw(false)
end
RunConsoleCommand("FSpectate_StopSpectating")
isSpectating = false
end
| agpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Buburimu_Peninsula/npcs/Bonbavour_RK.lua | 13 | 3337 | -----------------------------------
-- Area: Buburimu Peninsula
-- NPC: Bonbavour, R.K.
-- Outpost Conquest Guards
-- @pos -481.164 -32.858 49.188 118
-----------------------------------
package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Buburimu_Peninsula/TextIDs");
local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = KOLSHUSHU;
local csid = 0x7ffb;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Windurst_Waters/npcs/Serukoko.lua | 13 | 1055 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Serukoko
-- Type: Standard NPC
-- @zone: 238
-- @pos -54.916 -7.499 114.855
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0175);
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 |
Giorox/AngelionOT-Repo | data/movements/scripts/alters/alterstpankrahmun.lua | 1 | 2503 | function onStepIn(cid, item, pos)
local ice = {x=32193, y=31419, z=2}
local earth = {x=32974, y=32224, z=7}
local fire = {x=32909, y=32338, z=15}
local energy = {x=33060, y=32711, z=5}
if getPlayerLookDir(cid) == 0 then
newdir = 2
newdir2 = 2
elseif getPlayerLookDir(cid) == 1 then
newdir = 3
newdir2 = 3
elseif getPlayerLookDir(cid) == 2 then
newdir = 0
newdir2 = 0
else
newdir = 1
newdir2 = 1
end
if item.actionid == 7829 then
if getPlayerVocation(cid) == 2 or getPlayerVocation(cid) == 6 and getPlayerLevel(cid) >= 30 and isPremium(cid) == TRUE then
doTeleportThing(cid,ice)
doSendMagicEffect(ice,10)
setPlayerStorageValue(cid, 15118, 1)
else
doCreatureSay(cid, "Only Premium Druids of level 30 or higher are able to enter this portal", TALKTYPE_ORANGE_1)
doMoveCreature(cid, newdir)
doMoveCreature(cid, newdir2)
doSendMagicEffect(getCreaturePosition(cid),10)
end
elseif item.actionid == 7830 then
if getPlayerVocation(cid) == 2 or getPlayerVocation(cid) == 6 and getPlayerLevel(cid) >= 30 and isPremium(cid) == TRUE then
doTeleportThing(cid,earth)
doSendMagicEffect(earth,10)
setPlayerStorageValue(cid, 15130, 1)
else
doCreatureSay(cid, "Only Premium Druids of level 30 or higher are able to enter this portal", TALKTYPE_ORANGE_1)
doMoveCreature(cid, newdir)
doMoveCreature(cid, newdir2)
doSendMagicEffect(getCreaturePosition(cid),10)
end
elseif item.actionid == 7831 then
if getPlayerVocation(cid) == 1 or getPlayerVocation(cid) == 5 and getPlayerLevel(cid) >= 30 and isPremium(cid) == TRUE then
doTeleportThing(cid,fire)
doSendMagicEffect(fire,10)
setPlayerStorageValue(cid, 15154, 1)
else
doCreatureSay(cid, "Only Premium Sorcerers of level 30 or higher are able to enter this portal", TALKTYPE_ORANGE_1)
doMoveCreature(cid, newdir)
doMoveCreature(cid, newdir2)
doSendMagicEffect(getCreaturePosition(cid),10)
end
elseif item.actionid == 7832 then
if getPlayerVocation(cid) == 1 or getPlayerVocation(cid) == 5 and getPlayerLevel(cid) >= 30 and isPremium(cid) == TRUE then
doTeleportThing(cid,energy)
doSendMagicEffect(energy,10)
setPlayerStorageValue(cid, 15142, 1)
else
doCreatureSay(cid, "Only Premium Sorcerers of level 30 or higher are able to enter this portal", TALKTYPE_ORANGE_1)
doMoveCreature(cid, newdir)
doMoveCreature(cid, newdir2)
doSendMagicEffect(getCreaturePosition(cid),10)
end
end
end | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Bastok_Markets/npcs/Zaira.lua | 17 | 1868 | -----------------------------------
-- Area: Batok Markets
-- NPC: Zaira
-- Standard Merchant NPC
--
-- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,ZAIRA_SHOP_DIALOG);
stock = {
0x12FE, 111,1, --Scroll of Blind
0x12E6, 360,2, --Scroll of Bio
0x12DC, 82,2, --Scroll of Poison
0x12FD, 2250,2, --Scroll of Sleep
0x129F, 61,3, --Scroll of Stone
0x12A9, 140,3, --Scroll of Water
0x129A, 324,3, --Scroll of Aero
0x1290, 837,3, --Scroll of Fire
0x1295, 1584,3, --Scroll of Blizzard
0x12A4, 3261,3, --Scroll of Thunder
0x12EF, 1363,3, --Scroll of Shock
0x12EE, 1827,3, --Scroll of Rasp
0x12ED, 2250,3, --Scroll of Choke
0x12EC, 3688,3, --Scroll of Frost
0x12EB, 4644,3, --Scroll of Burn
0x12F0, 6366,3, --Scroll of Drown
}
showNationShop(player, BASTOK, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Castle_Oztroja/npcs/_m72.lua | 13 | 2264 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _m72 (Torch Stand)
-- Notes: Opens door _477 when _m72 to _m75 are lit
-- @pos -60 -72 -139 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
DoorID = npc:getID() - 2;
Torch1 = npc:getID();
Torch2 = npc:getID() + 1;
Torch3 = npc:getID() + 2;
Torch4 = npc:getID() + 3;
DoorA = GetNPCByID(DoorID):getAnimation();
TorchStand1A = npc:getAnimation();
TorchStand2A = GetNPCByID(Torch2):getAnimation();
TorchStand3A = GetNPCByID(Torch3):getAnimation();
TorchStand4A = GetNPCByID(Torch4):getAnimation();
if (DoorA == 9 and TorchStand1A == 9) then
player:startEvent(0x000a);
else
player:messageSpecial(TORCH_LIT);
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
GetNPCByID(Torch1):openDoor(55);
if ((DoorA == 9)) then
GetNPCByID(DoorID):openDoor(35); -- confirmed retail tested
-- The lamps shouldn't go off here, but I couldn't get the torches to update animation times without turning them off first
-- They need to be reset to the door open time(35s) + 4s (39 seconds)
GetNPCByID(Torch1):setAnimation(9);
GetNPCByID(Torch2):setAnimation(9);
GetNPCByID(Torch3):setAnimation(9);
GetNPCByID(Torch4):setAnimation(9);
GetNPCByID(Torch1):openDoor(39); -- confirmed retail tested
GetNPCByID(Torch2):openDoor(39);
GetNPCByID(Torch3):openDoor(39);
GetNPCByID(Torch4):openDoor(39);
end
end
end; | gpl-3.0 |
maikerumine/extreme_survival_mini | mods/protector/init.lua | 1 | 12940 | minetest.register_privilege("delprotect","Ignore player protection")
protector = {}
protector.mod = "redo"
protector.radius = (tonumber(minetest.setting_get("protector_radius")) or 3)
protector.drop = minetest.setting_getbool("protector_drop") or false
protector.hurt = (tonumber(minetest.setting_get("protector_hurt")) or 0)
protector.get_member_list = function(meta)
return meta:get_string("members"):split(" ")
end
protector.set_member_list = function(meta, list)
meta:set_string("members", table.concat(list, " "))
end
protector.is_member = function (meta, name)
for _, n in pairs(protector.get_member_list(meta)) do
if n == name then
return true
end
end
return false
end
protector.add_member = function(meta, name)
if protector.is_member(meta, name) then
return
end
local list = protector.get_member_list(meta)
table.insert(list, name)
protector.set_member_list(meta, list)
end
protector.del_member = function(meta, name)
local list = protector.get_member_list(meta)
for i, n in pairs(list) do
if n == name then
table.remove(list, i)
break
end
end
protector.set_member_list(meta, list)
end
-- Protector Interface
protector.generate_formspec = function(meta)
local formspec = "size[8,7]"
.. default.gui_bg
.. default.gui_bg_img
.. default.gui_slots
.. "label[2.5,0;-- Protector interface --]"
.. "label[0,1;PUNCH node to show protected area or USE for area check]"
.. "label[0,2;Members: (type player name then press Enter to add)]"
.. "button_exit[2.5,6.2;3,0.5;close_me;Close]"
local members = protector.get_member_list(meta)
local npp = 12 -- max users added onto protector list
local i = 0
for _, member in pairs(members) do
if i < npp then
-- show username
formspec = formspec .. "button[" .. (i % 4 * 2)
.. "," .. math.floor(i / 4 + 3)
.. ";1.5,.5;protector_member;" .. member .. "]"
-- username remove button
.. "button[" .. (i % 4 * 2 + 1.25) .. ","
.. math.floor(i / 4 + 3)
.. ";.75,.5;protector_del_member_" .. member .. ";X]"
end
i = i + 1
end
if i < npp then
-- user name entry field
formspec = formspec .. "field[" .. (i % 4 * 2 + 1 / 3) .. ","
.. (math.floor(i / 4 + 3) + 1 / 3)
.. ";1.433,.5;protector_add_member;;]"
-- username add button
.."button[" .. (i % 4 * 2 + 1.25) .. ","
.. math.floor(i / 4 + 3) .. ";.75,.5;protector_submit;+]"
end
return formspec
end
-- Infolevel:
-- 0 for no info
-- 1 for "This area is owned by <owner> !" if you can't dig
-- 2 for "This area is owned by <owner>.
-- 3 for checking protector overlaps
protector.can_dig = function(r, pos, digger, onlyowner, infolevel)
if not digger
or not pos then
return false
end
-- Delprotect privileged users can override protections
if minetest.check_player_privs(digger, {delprotect = true})
and infolevel == 1 then
return true
end
if infolevel == 3 then infolevel = 1 end
-- Find the protector nodes
local positions = minetest.find_nodes_in_area(
{x = pos.x - r, y = pos.y - r, z = pos.z - r},
{x = pos.x + r, y = pos.y + r, z = pos.z + r},
{"protector:protect", "protector:protect2"})
local meta, owner, members
for _, pos in pairs(positions) do
meta = minetest.get_meta(pos)
owner = meta:get_string("owner")
members = meta:get_string("members")
if owner ~= digger then
if onlyowner
or not protector.is_member(meta, digger) then
if infolevel == 1 then
minetest.chat_send_player(digger,
"This area is owned by " .. owner .. " !")
elseif infolevel == 2 then
minetest.chat_send_player(digger,
"This area is owned by " .. owner .. ".")
minetest.chat_send_player(digger,
"Protection located at: " .. minetest.pos_to_string(pos))
if members ~= "" then
minetest.chat_send_player(digger,
"Members: " .. members .. ".")
end
end
return false
end
end
if infolevel == 2 then
minetest.chat_send_player(digger,
"This area is owned by " .. owner .. ".")
minetest.chat_send_player(digger,
"Protection located at: " .. minetest.pos_to_string(pos))
if members ~= "" then
minetest.chat_send_player(digger,
"Members: " .. members .. ".")
end
return false
end
end
if infolevel == 2 then
if #positions < 1 then
minetest.chat_send_player(digger,
"This area is not protected.")
end
minetest.chat_send_player(digger, "You can build here.")
end
return true
end
-- Can node be added or removed, if so return node else true (for protected)
protector.old_is_protected = minetest.is_protected
function minetest.is_protected(pos, digger)
if not protector.can_dig(protector.radius, pos, digger, false, 1) then
local player = minetest.get_player_by_name(digger)
-- hurt player if protection violated
if protector.hurt > 0
and player then
player:set_hp(player:get_hp() - protector.hurt)
end
-- drop tool/item if protection violated
if protector.drop == true
and player then
local holding = player:get_wielded_item()
if holding:to_string() ~= "" then
-- take stack
local sta = holding:take_item(holding:get_count())
player:set_wielded_item(holding)
-- incase of lag, reset stack
minetest.after(0.1, function()
player:set_wielded_item(holding)
-- drop stack
local obj = minetest.add_item(player:getpos(), sta)
obj:setvelocity({x = 0, y = 5, z = 0})
end)
end
end
return true
end
return protector.old_is_protected(pos, digger)
end
-- Make sure protection block doesn't overlap another protector's area
function protector.check_overlap(itemstack, placer, pointed_thing)
if pointed_thing.type ~= "node" then
return itemstack
end
if not protector.can_dig(protector.radius * 2, pointed_thing.above,
placer:get_player_name(), true, 3) then
minetest.chat_send_player(placer:get_player_name(),
"Overlaps into above players protected area")
return
end
return minetest.item_place(itemstack, placer, pointed_thing)
end
--= Protection Block
minetest.register_node("protector:protect", {
description = "Protection Block",
drawtype = "nodebox",
tiles = {
"moreblocks_circle_stone_bricks.png",
"moreblocks_circle_stone_bricks.png",
"moreblocks_circle_stone_bricks.png^protector_logo.png"
},
sounds = default.node_sound_stone_defaults(),
groups = {dig_immediate = 2, unbreakable = 1},
is_ground_content = false,
paramtype = "light",
light_source = 4,
node_box = {
type = "fixed",
fixed = {
{-0.5 ,-0.5, -0.5, 0.5, 0.5, 0.5},
}
},
on_place = protector.check_overlap,
after_place_node = function(pos, placer)
local meta = minetest.get_meta(pos)
meta:set_string("owner", placer:get_player_name() or "")
meta:set_string("infotext", "Protection (owned by " .. meta:get_string("owner") .. ")")
meta:set_string("members", "")
end,
on_use = function(itemstack, user, pointed_thing)
if pointed_thing.type ~= "node" then
return
end
protector.can_dig(protector.radius, pointed_thing.under, user:get_player_name(), false, 2)
end,
on_rightclick = function(pos, node, clicker, itemstack)
local meta = minetest.get_meta(pos)
if meta
and protector.can_dig(1, pos,clicker:get_player_name(), true, 1) then
minetest.show_formspec(clicker:get_player_name(),
"protector:node_" .. minetest.pos_to_string(pos), protector.generate_formspec(meta))
end
end,
on_punch = function(pos, node, puncher)
if not protector.can_dig(1, pos, puncher:get_player_name(), true, 1) then
return
end
minetest.add_entity(pos, "protector:display")
end,
can_dig = function(pos, player)
return protector.can_dig(1, pos, player:get_player_name(), true, 1)
end,
on_blast = function() end,
})
minetest.register_craft({
output = "protector:protect",
recipe = {
{"default:stone", "default:stone", "default:stone"},
{"default:stone", "default:mese", "default:stone"},
{"default:stone", "default:stone", "default:stone"},
}
})
--= Protection Logo
--[[
minetest.register_node("protector:protect2", {
description = "Protection Logo",
tiles = {"protector_logo.png"},
wield_image = "protector_logo.png",
inventory_image = "protector_logo.png",
sounds = default.node_sound_stone_defaults(),
groups = {dig_immediate = 2, unbreakable = 1},
paramtype = 'light',
paramtype2 = "wallmounted",
legacy_wallmounted = true,
light_source = 4,
drawtype = "nodebox",
sunlight_propagates = true,
walkable = true,
node_box = {
type = "wallmounted",
wall_top = {-0.375, 0.4375, -0.5, 0.375, 0.5, 0.5},
wall_bottom = {-0.375, -0.5, -0.5, 0.375, -0.4375, 0.5},
wall_side = {-0.5, -0.5, -0.375, -0.4375, 0.5, 0.375},
},
selection_box = {type = "wallmounted"},
on_place = protector.check_overlap,
after_place_node = function(pos, placer)
local meta = minetest.get_meta(pos)
meta:set_string("owner", placer:get_player_name() or "")
meta:set_string("infotext", "Protection (owned by " .. meta:get_string("owner") .. ")")
meta:set_string("members", "")
end,
on_use = function(itemstack, user, pointed_thing)
if pointed_thing.type ~= "node" then
return
end
protector.can_dig(protector.radius, pointed_thing.under, user:get_player_name(), false, 2)
end,
on_rightclick = function(pos, node, clicker, itemstack)
local meta = minetest.get_meta(pos)
if protector.can_dig(1, pos, clicker:get_player_name(), true, 1) then
minetest.show_formspec(clicker:get_player_name(),
"protector:node_" .. minetest.pos_to_string(pos), protector.generate_formspec(meta))
end
end,
on_punch = function(pos, node, puncher)
if not protector.can_dig(1, pos, puncher:get_player_name(), true, 1) then
return
end
minetest.add_entity(pos, "protector:display")
end,
can_dig = function(pos, player)
return protector.can_dig(1, pos, player:get_player_name(), true, 1)
end,
on_blast = function() end,
})
minetest.register_craft({
output = "protector:protect2",
recipe = {
{"default:stone", "default:stone", "default:stone"},
{"default:stone", "default:copper_ingot", "default:stone"},
{"default:stone", "default:stone", "default:stone"},
}
})
]]
-- If name entered or button press
minetest.register_on_player_receive_fields(function(player, formname, fields)
if string.sub(formname, 0, string.len("protector:node_")) == "protector:node_" then
local pos_s = string.sub(formname, string.len("protector:node_") + 1)
local pos = minetest.string_to_pos(pos_s)
local meta = minetest.get_meta(pos)
if not protector.can_dig(1, pos, player:get_player_name(), true, 1) then
return
end
if fields.protector_add_member then
for _, i in pairs(fields.protector_add_member:split(" ")) do
protector.add_member(meta, i)
end
end
for field, value in pairs(fields) do
if string.sub(field, 0, string.len("protector_del_member_")) == "protector_del_member_" then
protector.del_member(meta, string.sub(field,string.len("protector_del_member_") + 1))
end
end
if not fields.close_me then
minetest.show_formspec(player:get_player_name(), formname, protector.generate_formspec(meta))
end
end
end)
-- Display entity shown when protector node is punched
minetest.register_entity("protector:display", {
physical = false,
collisionbox = {0, 0, 0, 0, 0, 0},
visual = "wielditem",
-- wielditem seems to be scaled to 1.5 times original node size
visual_size = {x = 1.0 / 1.5, y = 1.0 / 1.5},
textures = {"protector:display_node"},
timer = 0,
on_activate = function(self, staticdata)
-- Xanadu server only
if mobs and mobs.entity and mobs.entity == false then
self.object:remove()
end
end,
on_step = function(self, dtime)
self.timer = self.timer + dtime
if self.timer > 5 then
self.object:remove()
end
end,
})
-- Display-zone node, Do NOT place the display as a node,
-- it is made to be used as an entity (see above)
local x = protector.radius
minetest.register_node("protector:display_node", {
tiles = {"protector_display.png"},
use_texture_alpha = true,
walkable = false,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
-- sides
{-(x+.55), -(x+.55), -(x+.55), -(x+.45), (x+.55), (x+.55)},
{-(x+.55), -(x+.55), (x+.45), (x+.55), (x+.55), (x+.55)},
{(x+.45), -(x+.55), -(x+.55), (x+.55), (x+.55), (x+.55)},
{-(x+.55), -(x+.55), -(x+.55), (x+.55), (x+.55), -(x+.45)},
-- top
{-(x+.55), (x+.45), -(x+.55), (x+.55), (x+.55), (x+.55)},
-- bottom
{-(x+.55), -(x+.55), -(x+.55), (x+.55), -(x+.45), (x+.55)},
-- middle (surround protector)
{-.55,-.55,-.55, .55,.55,.55},
},
},
selection_box = {
type = "regular",
},
paramtype = "light",
groups = {dig_immediate = 3, not_in_creative_inventory = 1},
drop = "",
})
dofile(minetest.get_modpath("protector") .. "/doors_chest.lua")
dofile(minetest.get_modpath("protector") .. "/pvp.lua")
dofile(minetest.get_modpath("protector") .. "/admin.lua")
print ("[MOD] Protector Redo loaded")
| lgpl-2.1 |
DarkstarProject/darkstar | scripts/globals/items/pipira.lua | 11 | 1406 | -----------------------------------------
-- ID: 5787
-- Item: pipira
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Mind -4
-- Attack % 14.5
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if (target:getRace() ~= dsp.race.MITHRA) then
result = dsp.msg.basic.CANNOT_EAT
end
if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then
result = 0
end
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,300,5787)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.DEX, 2)
target:addMod(dsp.mod.MND, -4)
target:addMod(dsp.mod.FOOD_ATTP, 14)
target:addMod(dsp.mod.FOOD_ATT_CAP, 60)
target:addMod(dsp.mod.FOOD_RATTP, 14)
target:addMod(dsp.mod.FOOD_RATT_CAP, 60)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.DEX, 2)
target:delMod(dsp.mod.MND, -4)
target:delMod(dsp.mod.FOOD_ATTP, 14)
target:delMod(dsp.mod.FOOD_ATT_CAP, 60)
target:delMod(dsp.mod.FOOD_RATTP, 14)
target:delMod(dsp.mod.FOOD_RATT_CAP, 60)
end
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Maze_of_Shakhrami/Zone.lua | 11 | 1906 | -----------------------------------
--
-- Zone: Maze_of_Shakhrami (198)
--
-----------------------------------
package.loaded["scripts/zones/Maze_of_Shakhrami/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/zones/Maze_of_Shakhrami/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local tomes = {17588784,17588785,17588786,17588787};
SetGroundsTome(tomes);
UpdateTreasureSpawnPoint(17588769);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-140.246,-12.738,160.709,63);
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
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 |
ollie27/openwrt_packages | net/prosody/files/prosody.cfg.lua | 147 | 7257 | -- Prosody Example Configuration File
--
-- Information on configuring Prosody can be found on our
-- website at http://prosody.im/doc/configure
--
-- Tip: You can check that the syntax of this file is correct
-- when you have finished by running: luac -p prosody.cfg.lua
-- If there are any errors, it will let you know what and where
-- they are, otherwise it will keep quiet.
--
-- The only thing left to do is rename this file to remove the .dist ending, and fill in the
-- blanks. Good luck, and happy Jabbering!
---------- Server-wide settings ----------
-- Settings in this section apply to the whole server and are the default settings
-- for any virtual hosts
-- This is a (by default, empty) list of accounts that are admins
-- for the server. Note that you must create the accounts separately
-- (see http://prosody.im/doc/creating_accounts for info)
-- Example: admins = { "user1@example.com", "user2@example.net" }
admins = { }
-- Enable use of libevent for better performance under high load
-- For more information see: http://prosody.im/doc/libevent
--use_libevent = true;
-- This is the list of modules Prosody will load on startup.
-- It looks for mod_modulename.lua in the plugins folder, so make sure that exists too.
-- Documentation on modules can be found at: http://prosody.im/doc/modules
modules_enabled = {
-- Generally required
"roster"; -- Allow users to have a roster. Recommended ;)
"saslauth"; -- Authentication for clients and servers. Recommended if you want to log in.
"tls"; -- Add support for secure TLS on c2s/s2s connections
"dialback"; -- s2s dialback support
"disco"; -- Service discovery
-- Not essential, but recommended
"private"; -- Private XML storage (for room bookmarks, etc.)
"vcard"; -- Allow users to set vCards
--"privacy"; -- Support privacy lists
--"compression"; -- Stream compression
-- Nice to have
"legacyauth"; -- Legacy authentication. Only used by some old clients and bots.
"version"; -- Replies to server version requests
"uptime"; -- Report how long server has been running
"time"; -- Let others know the time here on this server
"ping"; -- Replies to XMPP pings with pongs
"pep"; -- Enables users to publish their mood, activity, playing music and more
"register"; -- Allow users to register on this server using a client and change passwords
"adhoc"; -- Support for "ad-hoc commands" that can be executed with an XMPP client
-- Admin interfaces
"admin_adhoc"; -- Allows administration via an XMPP client that supports ad-hoc commands
--"admin_telnet"; -- Opens telnet console interface on localhost port 5582
-- Other specific functionality
"posix"; -- POSIX functionality, sends server to background, enables syslog, etc.
--"bosh"; -- Enable BOSH clients, aka "Jabber over HTTP"
--"httpserver"; -- Serve static files from a directory over HTTP
--"groups"; -- Shared roster support
--"announce"; -- Send announcement to all online users
--"welcome"; -- Welcome users who register accounts
--"watchregistrations"; -- Alert admins of registrations
--"motd"; -- Send a message to users when they log in
};
-- These modules are auto-loaded, should you
-- (for some mad reason) want to disable
-- them then uncomment them below
modules_disabled = {
-- "presence"; -- Route user/contact status information
-- "message"; -- Route messages
-- "iq"; -- Route info queries
-- "offline"; -- Store offline messages
};
-- Disable account creation by default, for security
-- For more information see http://prosody.im/doc/creating_accounts
allow_registration = false;
-- Only allow encrypted streams? Encryption is already used when
-- available. These options will cause Prosody to deny connections that
-- are not encrypted. Note that some servers do not support s2s
-- encryption or have it disabled, including gmail.com and Google Apps
-- domains.
--c2s_require_encryption = false
--s2s_require_encryption = false
-- Select the authentication backend to use. The 'internal' providers
-- use Prosody's configured data storage to store the authentication data.
-- To allow Prosody to offer secure authentication mechanisms to clients, the
-- default provider stores passwords in plaintext. If you do not trust your
-- server please see http://prosody.im/doc/modules/mod_auth_internal_hashed
-- for information about using the hashed backend.
-- See http://prosody.im/doc/authentication for other possibilities including
-- Cyrus SASL.
authentication = "internal_plain"
-- Select the storage backend to use. By default Prosody uses flat files
-- in its configured data directory, but it also supports more backends
-- through modules. An "sql" backend is included by default, but requires
-- additional dependencies. See http://prosody.im/doc/storage for more info.
--storage = "sql" -- Default is "internal"
-- For the "sql" backend, you can uncomment *one* of the below to configure:
--sql = { driver = "SQLite3", database = "prosody.sqlite" } -- Default. 'database' is the filename.
--sql = { driver = "MySQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" }
--sql = { driver = "PostgreSQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" }
-- Logging configuration
-- For advanced logging see http://prosody.im/doc/logging
log = {
info = "/var/log/prosody/prosody.log"; -- Change 'info' to 'debug' for verbose logging
error = "/var/log/prosody/prosody.err";
-- "*syslog"; -- Uncomment this for logging to syslog; needs mod_posix
-- "*console"; -- Log to the console, useful for debugging with daemonize=false
}
-- Pidfile, used by prosodyctl and the init.d script
pidfile = "/var/run/prosody/prosody.pid"
-- User and group, used for daemon
prosody_user = "prosody"
prosody_group = "prosody"
----------- Virtual hosts -----------
-- You need to add a VirtualHost entry for each domain you wish Prosody to serve.
-- Settings under each VirtualHost entry apply *only* to that host.
VirtualHost "localhost"
VirtualHost "example.com"
enabled = false -- Remove this line to enable this host
-- Assign this host a certificate for TLS, otherwise it would use the one
-- set in the global section (if any).
-- Note that old-style SSL on port 5223 only supports one certificate, and will always
-- use the global one.
ssl = {
key = "/etc/prosody/certs/example.com.key";
certificate = "/etc/prosody/certs/example.com.crt";
}
------ Components ------
-- You can specify components to add hosts that provide special services,
-- like multi-user conferences, and transports.
-- For more information on components, see http://prosody.im/doc/components
---Set up a MUC (multi-user chat) room server on conference.example.com:
--Component "conference.example.com" "muc"
-- Set up a SOCKS5 bytestream proxy for server-proxied file transfers:
--Component "proxy.example.com" "proxy65"
---Set up an external component (default component port is 5347)
--
-- External components allow adding various services, such as gateways/
-- transports to other networks like ICQ, MSN and Yahoo. For more info
-- see: http://prosody.im/doc/components#adding_an_external_component
--
--Component "gateway.example.com"
-- component_secret = "password"
| gpl-2.0 |
Fenix-XI/Fenix | scripts/zones/Meriphataud_Mountains/Zone.lua | 15 | 4569 | -----------------------------------
--
-- Zone: Meriphataud_Mountains (119)
--
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil;
package.loaded["scripts/globals/chocobo_digging"] = nil;
-----------------------------------
require("scripts/zones/Meriphataud_Mountains/TextIDs");
require("scripts/globals/icanheararainbow");
require("scripts/globals/zone");
require("scripts/globals/conquest");
require("scripts/globals/chocobo_digging");
-----------------------------------
-- Chocobo Digging vars
-----------------------------------
local itemMap = {
-- itemid, abundance, requirement
{ 646, 4, DIGREQ_NONE },
{ 845, 12, DIGREQ_NONE },
{ 640, 112, DIGREQ_NONE },
{ 768, 237, DIGREQ_NONE },
{ 893, 41, DIGREQ_NONE },
{ 748, 33, DIGREQ_NONE },
{ 846, 145, DIGREQ_NONE },
{ 869, 100, DIGREQ_NONE },
{ 17296, 162, DIGREQ_NONE },
{ 771, 21, DIGREQ_NONE },
{ 4096, 100, DIGREQ_NONE }, -- all crystals
{ 678, 5, DIGREQ_BURROW },
{ 645, 9, DIGREQ_BURROW },
{ 737, 5, DIGREQ_BURROW },
{ 643, 69, DIGREQ_BURROW },
{ 1650, 62, DIGREQ_BURROW },
{ 644, 31, DIGREQ_BURROW },
{ 736, 62, DIGREQ_BURROW },
{ 739, 5, DIGREQ_BURROW },
{ 678, 5, DIGREQ_BORE },
{ 645, 9, DIGREQ_BORE },
{ 737, 5, DIGREQ_BORE },
{ 738, 8, DIGREQ_BORE },
{ 4570, 10, DIGREQ_MODIFIER },
{ 4487, 11, DIGREQ_MODIFIER },
{ 4409, 12, DIGREQ_MODIFIER },
{ 1188, 10, DIGREQ_MODIFIER },
{ 4532, 12, DIGREQ_MODIFIER },
};
local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED };
-----------------------------------
-- onChocoboDig
-----------------------------------
function onChocoboDig(player, precheck)
return chocoboDig(player, itemMap, precheck, messageArray);
end;
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local manuals = {17265291,17265292,17265293};
SetFieldManual(manuals);
-- Waraxe Beak
SetRespawnTime(17264828, 900, 10800);
-- Coo Keja the Unseen
SetRespawnTime(17264946, 900, 10800);
SetRegionalConquestOverseers(zone:getRegionID())
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn( player, prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos( 752.632, -33.761, -40.035, 129);
end
if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow
cs = 0x001f;
elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then
cs = 0x0022; -- no update for castle oztroja (north)
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter( player, region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x001f) then
lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow
elseif (csid == 0x0022) then
if (player:getPreviousZone() == 120) then
player:updateEvent(0,0,0,0,0,2);
elseif (player:getPreviousZone() == 117) then
player:updateEvent(0,0,0,0,0,1);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x001f) then
lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow
end
end; | gpl-3.0 |
DarkstarProject/darkstar | scripts/globals/spells/impact.lua | 12 | 3140 | -----------------------------------------
-- Spell: Impact
-- Deals dark damage to an enemy and
-- decreases all 7 base stats by 20%
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local params = {}
params.attribute = dsp.mod.INT
params.bonus = 1.0
params.diff = caster:getStat(dsp.mod.INT)-target:getStat(dsp.mod.INT)
params.dmg = 939
params.effect = nil
params.hasMultipleTargetReduction = false
params.multiplier = 2.335
params.resistBonus = 1.0
params.skillType = 37
params.skillType = dsp.skill.ELEMENTAL_MAGIC
local resist = applyResistance(caster, target, spell, params)
local duration = 180 * resist -- BG wiki suggests only duration gets effected by resist, not stat amount.
-- Todo: loop to avoid repeatedly doing same thing for each stat
local STR_Loss = ((target:getStat(dsp.mod.STR) / 100) * 20) -- Should be 20%
local DEX_Loss = ((target:getStat(dsp.mod.DEX) / 100) * 20)
local VIT_Loss = ((target:getStat(dsp.mod.VIT) / 100) * 20)
local AGI_Loss = ((target:getStat(dsp.mod.AGI) / 100) * 20)
local INT_Loss = ((target:getStat(dsp.mod.INT) / 100) * 20)
local MND_Loss = ((target:getStat(dsp.mod.MND) / 100) * 20)
local CHR_Loss = ((target:getStat(dsp.mod.CHR) / 100) * 20)
if (target:hasStatusEffect(dsp.effect.STR_DOWN) == false) then
target:addStatusEffect(dsp.effect.STR_DOWN,STR_Loss,0,duration)
end
if (target:hasStatusEffect(dsp.effect.DEX_DOWN) == false) then
target:addStatusEffect(dsp.effect.DEX_DOWN,DEX_Loss,0,duration)
end
if (target:hasStatusEffect(dsp.effect.VIT_DOWN) == false) then
target:addStatusEffect(dsp.effect.VIT_DOWN,VIT_Loss,0,duration)
end
if (target:hasStatusEffect(dsp.effect.AGI_DOWN) == false) then
target:addStatusEffect(dsp.effect.AGI_DOWN,AGI_Loss,0,duration)
end
if (target:hasStatusEffect(dsp.effect.INT_DOWN) == false) then
target:addStatusEffect(dsp.effect.INT_DOWN,INT_Loss,0,duration)
end
if (target:hasStatusEffect(dsp.effect.MND_DOWN) == false) then
target:addStatusEffect(dsp.effect.MND_DOWN,MND_Loss,0,duration)
end
if (target:hasStatusEffect(dsp.effect.CHR_DOWN) == false) then
target:addStatusEffect(dsp.effect.CHR_DOWN,CHR_Loss,0,duration)
end
-- Diverting use of doElementalNuke till spellParams is implemented for this spell
-- local dmg = doElementalNuke(caster, target, spell, params)
-- Calculate raw damage
local dmg = calculateMagicDamage(caster, target, spell, params)
-- Get the resisted damage
dmg = dmg*resist
-- Add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster,spell,target,dmg)
-- Add in target adjustment
dmg = adjustForTarget(target,dmg,spell:getElement())
-- Add in final adjustments
dmg = finalMagicAdjustments(caster,target,spell,dmg)
return dmg
end
| gpl-3.0 |
crunchuser/prosody-modules | mod_component_client/mod_component_client.lua | 31 | 8204 | --[[
mod_component_client.lua
This module turns Prosody hosts into components of other XMPP servers.
Config:
VirtualHost "component.example.com"
component_client = {
host = "localhost";
port = 5347;
secret = "hunter2";
}
]]
local socket = require "socket"
local logger = require "util.logger";
local sha1 = require "util.hashes".sha1;
local st = require "util.stanza";
local jid_split = require "util.jid".split;
local new_xmpp_stream = require "util.xmppstream".new;
local uuid_gen = require "util.uuid".generate;
local core_process_stanza = prosody.core_process_stanza;
local hosts = prosody.hosts;
local log = module._log;
local config = module:get_option("component_client", {});
local server_host = config.host or "localhost";
local server_port = config.port or 5347;
local server_secret = config.secret or error("client_component.secret not provided");
local exit_on_disconnect = config.exit_on_disconnect;
local keepalive_interval = config.keepalive_interval or 3600;
local __conn;
local listener = {};
local session;
local xmlns_component = 'jabber:component:accept';
local stream_callbacks = { default_ns = xmlns_component };
local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
function stream_callbacks.error(session, error, data, data2)
if session.destroyed then return; end
module:log("warn", "Error processing component stream: %s", tostring(error));
if error == "no-stream" then
session:close("invalid-namespace");
elseif error == "parse-error" then
session.log("warn", "External component %s XML parse error: %s", tostring(session.host), tostring(data));
session:close("not-well-formed");
elseif error == "stream-error" then
local condition, text = "undefined-condition";
for child in data:children() do
if child.attr.xmlns == xmlns_xmpp_streams then
if child.name ~= "text" then
condition = child.name;
else
text = child:get_text();
end
if condition ~= "undefined-condition" and text then
break;
end
end
end
text = condition .. (text and (" ("..text..")") or "");
session.log("info", "Session closed by remote with error: %s", text);
session:close(nil, text);
end
end
function stream_callbacks.streamopened(session, attr)
-- TODO check id~=nil, from==module.host
module:log("debug", "Sending handshake");
local handshake = st.stanza("handshake"):text(sha1(attr.id..server_secret, true));
session.send(handshake);
session.notopen = nil;
end
function stream_callbacks.streamclosed(session)
session.log("debug", "Received </stream:stream>");
session:close();
end
module:hook("stanza/jabber:component:accept:handshake", function(event)
session.type = "component";
module:log("debug", "Handshake complete");
module:fire_event("component_client/connected", {});
return true; -- READY!
end);
module:hook("route/remote", function(event)
return session and session.send(event.stanza);
end);
function stream_callbacks.handlestanza(session, stanza)
-- Namespaces are icky.
if not stanza.attr.xmlns and stanza.name == "handshake" then
stanza.attr.xmlns = xmlns_component;
end
if not stanza.attr.xmlns or stanza.attr.xmlns == "jabber:client" then
if not stanza.attr.from then
session.log("warn", "Rejecting stanza with no 'from' address");
session.send(st.error_reply(stanza, "modify", "bad-request", "Components MUST get a 'from' address on stanzas"));
return;
end
local _, domain = jid_split(stanza.attr.to);
if not domain then
session.log("warn", "Rejecting stanza with no 'to' address");
session.send(st.error_reply(stanza, "modify", "bad-request", "Components MUST get a 'to' address on stanzas"));
return;
elseif domain ~= session.host then
session.log("warn", "Component received stanza with unknown 'to' address");
session.send(st.error_reply(stanza, "cancel", "not-allowed", "Component doesn't serve this JID"));
return;
end
end
return core_process_stanza(session, stanza);
end
local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
local function session_close(session, reason)
if session.destroyed then return; end
if session.conn then
if session.notopen then
session.send("<?xml version='1.0'?>");
session.send(st.stanza("stream:stream", default_stream_attr):top_tag());
end
if reason then
if type(reason) == "string" then -- assume stream error
module:log("info", "Disconnecting component, <stream:error> is: %s", reason);
session.send(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
elseif type(reason) == "table" then
if reason.condition then
local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
if reason.text then
stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
end
if reason.extra then
stanza:add_child(reason.extra);
end
module:log("info", "Disconnecting component, <stream:error> is: %s", tostring(stanza));
session.send(stanza);
elseif reason.name then -- a stanza
module:log("info", "Disconnecting component, <stream:error> is: %s", tostring(reason));
session.send(reason);
end
end
end
session.send("</stream:stream>");
session.conn:close();
listener.ondisconnect(session.conn, "stream error");
end
end
function listener.onconnect(conn)
session = { type = "component_unauthed", conn = conn, send = function (data) return conn:write(tostring(data)); end, host = module.host };
-- Logging functions --
local conn_name = "jcp"..tostring(session):match("[a-f0-9]+$");
session.log = logger.init(conn_name);
session.close = session_close;
session.log("info", "Outgoing Jabber component connection");
local stream = new_xmpp_stream(session, stream_callbacks);
session.stream = stream;
function session.data(conn, data)
local ok, err = stream:feed(data);
if ok then return; end
module:log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
session:close("not-well-formed");
end
session.dispatch_stanza = stream_callbacks.handlestanza;
session.notopen = true;
session.send(st.stanza("stream:stream", {
to = session.host;
["xmlns:stream"] = 'http://etherx.jabber.org/streams';
xmlns = xmlns_component;
}):top_tag());
--sessions[conn] = session;
end
function listener.onincoming(conn, data)
--local session = sessions[conn];
session.data(conn, data);
end
function listener.ondisconnect(conn, err)
--local session = sessions[conn];
if session then
(session.log or log)("info", "component disconnected: %s (%s)", tostring(session.host), tostring(err));
if session.on_destroy then session:on_destroy(err); end
--sessions[conn] = nil;
for k in pairs(session) do
if k ~= "log" and k ~= "close" then
session[k] = nil;
end
end
session.destroyed = true;
session = nil;
end
__conn = nil;
module:log("error", "connection lost");
module:fire_event("component_client/disconnected", { reason = err });
if exit_on_disconnect and not prosody.shutdown_reason then
prosody.shutdown("Shutdown by component_client disconnect");
end
end
-- send whitespace keep-alive one an hour
if keepalive_interval ~= 0 then
module:add_timer(keepalive_interval, function()
if __conn then
__conn:write(" ");
end
return keepalive_interval;
end);
end
function connect()
------------------------
-- Taken from net.http
local conn = socket.tcp ( )
conn:settimeout ( 10 )
local ok, err = conn:connect ( server_host , server_port )
if not ok and err ~= "timeout" then
return nil, err;
end
local handler , conn = server.wrapclient ( conn , server_host , server_port , listener , "*a")
__conn = handler;
------------------------
return true;
end
local s, err = connect();
if not s then
listener.ondisconnect(nil, err);
end
module:hook_global("server-stopping", function(event)
local reason = event.reason;
if session then
session:close{ condition = "system-shutdown", text = reason };
end
end, 1000);
| mit |
DeepLearning4BioSeqText/Paper12-PlosOne-DeepProteinMultitaskTagging | modelShare/viterbi/Viterbi.lua | 2 | 1086 | local Viterbi, parent = torch.class('nn.Viterbi','nn.Module')
function Viterbi:__init(size)
parent.__init(self)
self.transProb = torch.Tensor(size,size)
self.startProb = torch.Tensor(size)
self.gradTransProb = torch.Tensor(size,size)
self.gradStartProb = torch.Tensor(size)
self.alpha = torch.Tensor()
self.beta = torch.Tensor()
self:reset()
end
function Viterbi:reset()
self.transProb:fill(-math.log(self.transProb:size(1)))
self.startProb:fill(-math.log(self.startProb:size(1)))
end
function Viterbi:write(file)
parent.write(self, file)
file:writeObject(self.transProb)
file:writeObject(self.startProb)
file:writeObject(self.gradTransProb)
file:writeObject(self.gradStartProb)
file:writeObject(self.alpha)
file:writeObject(self.beta)
end
function Viterbi:read(file)
parent.read(self, file)
self.transProb = file:readObject()
self.startProb = file:readObject()
self.gradTransProb = file:readObject()
self.gradStartProb = file:readObject()
self.alpha = file:readObject()
self.beta = file:readObject()
end
| gpl-2.0 |
DarkstarProject/darkstar | scripts/zones/AlTaieu/npcs/qm2.lua | 12 | 1148 | -----------------------------------
-- Area: Al'Taieu
-- NPC: ??? (Jailer of Justice Spawn)
-- Allows players to spawn the Jailer of Justice by trading the Second Virtue, Deed of Moderation, and HQ Xzomit Organ to a ???.
-- !pos , -278 0 -463
-----------------------------------
local ID = require("scripts/zones/AlTaieu/IDs");
-----------------------------------
function onTrade(player,npc,trade)
--[[
-- JAILER OF JUSTICE
if (
not GetMobByID(ID.mob.JAILER_OF_JUSTICE):isSpawned() and
trade:hasItemQty(1853,1) and -- second_virtue
trade:hasItemQty(1854,1) and -- deed_of_moderation
trade:hasItemQty(1855,1) and -- hq_xzomit_organ
trade:getItemCount() == 3
) then
player:tradeComplete();
SpawnMob(ID.mob.JAILER_OF_JUSTICE):updateClaim(player);
end
--]]
end;
function onTrigger(player,npc)
end;
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
end;
| gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Phomiuna_Aqueducts/npcs/_0rs.lua | 12 | 1094 | -----------------------------------
-- Area: Phomiuna_Aqueducts
-- NPC: Oil lamp
-- !pos -60 -23 60 27
-----------------------------------
require("scripts/globals/missions");
local ID = require("scripts/zones/Phomiuna_Aqueducts/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local DoorOffset = npc:getID();
player:messageSpecial(ID.text.LAMP_OFFSET+1); -- earth lamp
npc:openDoor(7); -- lamp animation
local element = VanadielDayElement();
-- printf("element: %u",element);
if (element == 3) then -- wind day
if (GetNPCByID(DoorOffset+1):getAnimation() == 8) then -- lamp wind open?
GetNPCByID(DoorOffset-7):openDoor(15); -- Open Door _0rk
end
elseif (element == 1) then -- earth day
if (GetNPCByID(DoorOffset-3):getAnimation() == 8) then -- lamp lightning open?
GetNPCByID(DoorOffset-7):openDoor(15); -- Open Door _0rk
end
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end; | gpl-3.0 |
eugeneia/snabbswitch | lib/ljsyscall/syscall/osx/syscalls.lua | 18 | 1899 | -- OSX specific syscalls
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local abi = require "syscall.abi"
return function(S, hh, c, C, types)
local ret64, retnum, retfd, retbool, retptr = hh.ret64, hh.retnum, hh.retfd, hh.retbool, hh.retptr
local ffi = require "ffi"
local errno = ffi.errno
local h = require "syscall.helpers"
local istype, mktype, getfd = h.istype, h.mktype, h.getfd
local t, pt, s = types.t, types.pt, types.s
-- TODO lutimes is implemented using setattrlist(2) in OSX
function S.grantpt(fd) return S.ioctl(fd, "TIOCPTYGRANT") end
function S.unlockpt(fd) return S.ioctl(fd, "TIOCPTYUNLK") end
function S.ptsname(fd)
local buf = t.buffer(128)
local ok, err = S.ioctl(fd, "TIOCPTYGNAME", buf)
if not ok then return nil, err end
return ffi.string(buf)
end
function S.mach_absolute_time() return C.mach_absolute_time() end
function S.mach_task_self() return C.mach_task_self_ end
function S.mach_host_self() return C.mach_host_self() end
function S.mach_port_deallocate(task, name) return retbool(C.mach_port_deallocate(task or S.mach_task_self(), name)) end
function S.host_get_clock_service(host, clock_id, clock_serv)
clock_serv = clock_serv or t.clock_serv1()
local ok, err = C.host_get_clock_service(host or S.mach_host_self(), c.CLOCKTYPE[clock_id or "SYSTEM"], clock_serv)
if not ok then return nil, err end
return clock_serv[0]
end
-- TODO when mach ports do gc, can add 'clock_serv or S.host_get_clock_service()'
function S.clock_get_time(clock_serv, cur_time)
cur_time = cur_time or t.mach_timespec()
local ok, err = C.clock_get_time(clock_serv, cur_time)
if not ok then return nil, err end
return cur_time
end
return S
end
| apache-2.0 |
blackops97/boty.lua | libs/lua-redis.lua | 580 | 35599 | local redis = {
_VERSION = 'redis-lua 2.0.4',
_DESCRIPTION = 'A Lua client library for the redis key value storage system.',
_COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri',
}
-- The following line is used for backwards compatibility in order to keep the `Redis`
-- global module name. Using `Redis` is now deprecated so you should explicitly assign
-- the module to a local variable when requiring it: `local redis = require('redis')`.
Redis = redis
local unpack = _G.unpack or table.unpack
local network, request, response = {}, {}, {}
local defaults = {
host = '127.0.0.1',
port = 6379,
tcp_nodelay = true,
path = nil
}
local function merge_defaults(parameters)
if parameters == nil then
parameters = {}
end
for k, v in pairs(defaults) do
if parameters[k] == nil then
parameters[k] = defaults[k]
end
end
return parameters
end
local function parse_boolean(v)
if v == '1' or v == 'true' or v == 'TRUE' then
return true
elseif v == '0' or v == 'false' or v == 'FALSE' then
return false
else
return nil
end
end
local function toboolean(value) return value == 1 end
local function sort_request(client, command, key, params)
--[[ params = {
by = 'weight_*',
get = 'object_*',
limit = { 0, 10 },
sort = 'desc',
alpha = true,
} ]]
local query = { key }
if params then
if params.by then
table.insert(query, 'BY')
table.insert(query, params.by)
end
if type(params.limit) == 'table' then
-- TODO: check for lower and upper limits
table.insert(query, 'LIMIT')
table.insert(query, params.limit[1])
table.insert(query, params.limit[2])
end
if params.get then
if (type(params.get) == 'table') then
for _, getarg in pairs(params.get) do
table.insert(query, 'GET')
table.insert(query, getarg)
end
else
table.insert(query, 'GET')
table.insert(query, params.get)
end
end
if params.sort then
table.insert(query, params.sort)
end
if params.alpha == true then
table.insert(query, 'ALPHA')
end
if params.store then
table.insert(query, 'STORE')
table.insert(query, params.store)
end
end
request.multibulk(client, command, query)
end
local function zset_range_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_byscore_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.limit then
table.insert(opts, 'LIMIT')
table.insert(opts, options.limit.offset or options.limit[1])
table.insert(opts, options.limit.count or options.limit[2])
end
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_reply(reply, command, ...)
local args = {...}
local opts = args[4]
if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then
local new_reply = { }
for i = 1, #reply, 2 do
table.insert(new_reply, { reply[i], reply[i + 1] })
end
return new_reply
else
return reply
end
end
local function zset_store_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.weights and type(options.weights) == 'table' then
table.insert(opts, 'WEIGHTS')
for _, weight in ipairs(options.weights) do
table.insert(opts, weight)
end
end
if options.aggregate then
table.insert(opts, 'AGGREGATE')
table.insert(opts, options.aggregate)
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function mset_filter_args(client, command, ...)
local args, arguments = {...}, {}
if (#args == 1 and type(args[1]) == 'table') then
for k,v in pairs(args[1]) do
table.insert(arguments, k)
table.insert(arguments, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
local function hash_multi_request_builder(builder_callback)
return function(client, command, ...)
local args, arguments = {...}, { }
if #args == 2 then
table.insert(arguments, args[1])
for k, v in pairs(args[2]) do
builder_callback(arguments, k, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
end
local function parse_info(response)
local info = {}
local current = info
response:gsub('([^\r\n]*)\r\n', function(kv)
if kv == '' then return end
local section = kv:match('^# (%w+)$')
if section then
current = {}
info[section:lower()] = current
return
end
local k,v = kv:match(('([^:]*):([^:]*)'):rep(1))
if k:match('db%d+') then
current[k] = {}
v:gsub(',', function(dbkv)
local dbk,dbv = kv:match('([^:]*)=([^:]*)')
current[k][dbk] = dbv
end)
else
current[k] = v
end
end)
return info
end
local function load_methods(proto, commands)
local client = setmetatable ({}, getmetatable(proto))
for cmd, fn in pairs(commands) do
if type(fn) ~= 'function' then
redis.error('invalid type for command ' .. cmd .. '(must be a function)')
end
client[cmd] = fn
end
for i, v in pairs(proto) do
client[i] = v
end
return client
end
local function create_client(proto, client_socket, commands)
local client = load_methods(proto, commands)
client.error = redis.error
client.network = {
socket = client_socket,
read = network.read,
write = network.write,
}
client.requests = {
multibulk = request.multibulk,
}
return client
end
-- ############################################################################
function network.write(client, buffer)
local _, err = client.network.socket:send(buffer)
if err then client.error(err) end
end
function network.read(client, len)
if len == nil then len = '*l' end
local line, err = client.network.socket:receive(len)
if not err then return line else client.error('connection error: ' .. err) end
end
-- ############################################################################
function response.read(client)
local payload = client.network.read(client)
local prefix, data = payload:sub(1, -#payload), payload:sub(2)
-- status reply
if prefix == '+' then
if data == 'OK' then
return true
elseif data == 'QUEUED' then
return { queued = true }
else
return data
end
-- error reply
elseif prefix == '-' then
return client.error('redis error: ' .. data)
-- integer reply
elseif prefix == ':' then
local number = tonumber(data)
if not number then
if res == 'nil' then
return nil
end
client.error('cannot parse '..res..' as a numeric response.')
end
return number
-- bulk reply
elseif prefix == '$' then
local length = tonumber(data)
if not length then
client.error('cannot parse ' .. length .. ' as data length')
end
if length == -1 then
return nil
end
local nextchunk = client.network.read(client, length + 2)
return nextchunk:sub(1, -3)
-- multibulk reply
elseif prefix == '*' then
local count = tonumber(data)
if count == -1 then
return nil
end
local list = {}
if count > 0 then
local reader = response.read
for i = 1, count do
list[i] = reader(client)
end
end
return list
-- unknown type of reply
else
return client.error('unknown response prefix: ' .. prefix)
end
end
-- ############################################################################
function request.raw(client, buffer)
local bufferType = type(buffer)
if bufferType == 'table' then
client.network.write(client, table.concat(buffer))
elseif bufferType == 'string' then
client.network.write(client, buffer)
else
client.error('argument error: ' .. bufferType)
end
end
function request.multibulk(client, command, ...)
local args = {...}
local argsn = #args
local buffer = { true, true }
if argsn == 1 and type(args[1]) == 'table' then
argsn, args = #args[1], args[1]
end
buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n"
buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n"
local table_insert = table.insert
for _, argument in pairs(args) do
local s_argument = tostring(argument)
table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n")
end
client.network.write(client, table.concat(buffer))
end
-- ############################################################################
local function custom(command, send, parse)
command = string.upper(command)
return function(client, ...)
send(client, command, ...)
local reply = response.read(client)
if type(reply) == 'table' and reply.queued then
reply.parser = parse
return reply
else
if parse then
return parse(reply, command, ...)
end
return reply
end
end
end
local function command(command, opts)
if opts == nil or type(opts) == 'function' then
return custom(command, request.multibulk, opts)
else
return custom(command, opts.request or request.multibulk, opts.response)
end
end
local define_command_impl = function(target, name, opts)
local opts = opts or {}
target[string.lower(name)] = custom(
opts.command or string.upper(name),
opts.request or request.multibulk,
opts.response or nil
)
end
local undefine_command_impl = function(target, name)
target[string.lower(name)] = nil
end
-- ############################################################################
local client_prototype = {}
client_prototype.raw_cmd = function(client, buffer)
request.raw(client, buffer .. "\r\n")
return response.read(client)
end
-- obsolete
client_prototype.define_command = function(client, name, opts)
define_command_impl(client, name, opts)
end
-- obsolete
client_prototype.undefine_command = function(client, name)
undefine_command_impl(client, name)
end
client_prototype.quit = function(client)
request.multibulk(client, 'QUIT')
client.network.socket:shutdown()
return true
end
client_prototype.shutdown = function(client)
request.multibulk(client, 'SHUTDOWN')
client.network.socket:shutdown()
end
-- Command pipelining
client_prototype.pipeline = function(client, block)
local requests, replies, parsers = {}, {}, {}
local table_insert = table.insert
local socket_write, socket_read = client.network.write, client.network.read
client.network.write = function(_, buffer)
table_insert(requests, buffer)
end
-- TODO: this hack is necessary to temporarily reuse the current
-- request -> response handling implementation of redis-lua
-- without further changes in the code, but it will surely
-- disappear when the new command-definition infrastructure
-- will finally be in place.
client.network.read = function() return '+QUEUED' end
local pipeline = setmetatable({}, {
__index = function(env, name)
local cmd = client[name]
if not cmd then
client.error('unknown redis command: ' .. name, 2)
end
return function(self, ...)
local reply = cmd(client, ...)
table_insert(parsers, #requests, reply.parser)
return reply
end
end
})
local success, retval = pcall(block, pipeline)
client.network.write, client.network.read = socket_write, socket_read
if not success then client.error(retval, 0) end
client.network.write(client, table.concat(requests, ''))
for i = 1, #requests do
local reply, parser = response.read(client), parsers[i]
if parser then
reply = parser(reply)
end
table_insert(replies, i, reply)
end
return replies, #requests
end
-- Publish/Subscribe
do
local channels = function(channels)
if type(channels) == 'string' then
channels = { channels }
end
return channels
end
local subscribe = function(client, ...)
request.multibulk(client, 'subscribe', ...)
end
local psubscribe = function(client, ...)
request.multibulk(client, 'psubscribe', ...)
end
local unsubscribe = function(client, ...)
request.multibulk(client, 'unsubscribe')
end
local punsubscribe = function(client, ...)
request.multibulk(client, 'punsubscribe')
end
local consumer_loop = function(client)
local aborting, subscriptions = false, 0
local abort = function()
if not aborting then
unsubscribe(client)
punsubscribe(client)
aborting = true
end
end
return coroutine.wrap(function()
while true do
local message
local response = response.read(client)
if response[1] == 'pmessage' then
message = {
kind = response[1],
pattern = response[2],
channel = response[3],
payload = response[4],
}
else
message = {
kind = response[1],
channel = response[2],
payload = response[3],
}
end
if string.match(message.kind, '^p?subscribe$') then
subscriptions = subscriptions + 1
end
if string.match(message.kind, '^p?unsubscribe$') then
subscriptions = subscriptions - 1
end
if aborting and subscriptions == 0 then
break
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.pubsub = function(client, subscriptions)
if type(subscriptions) == 'table' then
if subscriptions.subscribe then
subscribe(client, channels(subscriptions.subscribe))
end
if subscriptions.psubscribe then
psubscribe(client, channels(subscriptions.psubscribe))
end
end
return consumer_loop(client)
end
end
-- Redis transactions (MULTI/EXEC)
do
local function identity(...) return ... end
local emptytable = {}
local function initialize_transaction(client, options, block, queued_parsers)
local table_insert = table.insert
local coro = coroutine.create(block)
if options.watch then
local watch_keys = {}
for _, key in pairs(options.watch) do
table_insert(watch_keys, key)
end
if #watch_keys > 0 then
client:watch(unpack(watch_keys))
end
end
local transaction_client = setmetatable({}, {__index=client})
transaction_client.exec = function(...)
client.error('cannot use EXEC inside a transaction block')
end
transaction_client.multi = function(...)
coroutine.yield()
end
transaction_client.commands_queued = function()
return #queued_parsers
end
assert(coroutine.resume(coro, transaction_client))
transaction_client.multi = nil
transaction_client.discard = function(...)
local reply = client:discard()
for i, v in pairs(queued_parsers) do
queued_parsers[i]=nil
end
coro = initialize_transaction(client, options, block, queued_parsers)
return reply
end
transaction_client.watch = function(...)
client.error('WATCH inside MULTI is not allowed')
end
setmetatable(transaction_client, { __index = function(t, k)
local cmd = client[k]
if type(cmd) == "function" then
local function queuey(self, ...)
local reply = cmd(client, ...)
assert((reply or emptytable).queued == true, 'a QUEUED reply was expected')
table_insert(queued_parsers, reply.parser or identity)
return reply
end
t[k]=queuey
return queuey
else
return cmd
end
end
})
client:multi()
return coro
end
local function transaction(client, options, coroutine_block, attempts)
local queued_parsers, replies = {}, {}
local retry = tonumber(attempts) or tonumber(options.retry) or 2
local coro = initialize_transaction(client, options, coroutine_block, queued_parsers)
local success, retval
if coroutine.status(coro) == 'suspended' then
success, retval = coroutine.resume(coro)
else
-- do not fail if the coroutine has not been resumed (missing t:multi() with CAS)
success, retval = true, 'empty transaction'
end
if #queued_parsers == 0 or not success then
client:discard()
assert(success, retval)
return replies, 0
end
local raw_replies = client:exec()
if not raw_replies then
if (retry or 0) <= 0 then
client.error("MULTI/EXEC transaction aborted by the server")
else
--we're not quite done yet
return transaction(client, options, coroutine_block, retry - 1)
end
end
local table_insert = table.insert
for i, parser in pairs(queued_parsers) do
table_insert(replies, i, parser(raw_replies[i]))
end
return replies, #queued_parsers
end
client_prototype.transaction = function(client, arg1, arg2)
local options, block
if not arg2 then
options, block = {}, arg1
elseif arg1 then --and arg2, implicitly
options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2
else
client.error("Invalid parameters for redis transaction.")
end
if not options.watch then
watch_keys = { }
for i, v in pairs(options) do
if tonumber(i) then
table.insert(watch_keys, v)
options[i] = nil
end
end
options.watch = watch_keys
elseif not (type(options.watch) == 'table') then
options.watch = { options.watch }
end
if not options.cas then
local tx_block = block
block = function(client, ...)
client:multi()
return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine.
end
end
return transaction(client, options, block)
end
end
-- MONITOR context
do
local monitor_loop = function(client)
local monitoring = true
-- Tricky since the payload format changed starting from Redis 2.6.
local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$'
local abort = function()
monitoring = false
end
return coroutine.wrap(function()
client:monitor()
while monitoring do
local message, matched
local response = response.read(client)
local ok = response:gsub(pattern, function(time, info, cmd, args)
message = {
timestamp = tonumber(time),
client = info:match('%d+.%d+.%d+.%d+:%d+'),
database = tonumber(info:match('%d+')) or 0,
command = cmd,
arguments = args:match('.+'),
}
matched = true
end)
if not matched then
client.error('Unable to match MONITOR payload: '..response)
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.monitor_messages = function(client)
return monitor_loop(client)
end
end
-- ############################################################################
local function connect_tcp(socket, parameters)
local host, port = parameters.host, tonumber(parameters.port)
local ok, err = socket:connect(host, port)
if not ok then
redis.error('could not connect to '..host..':'..port..' ['..err..']')
end
socket:setoption('tcp-nodelay', parameters.tcp_nodelay)
return socket
end
local function connect_unix(socket, parameters)
local ok, err = socket:connect(parameters.path)
if not ok then
redis.error('could not connect to '..parameters.path..' ['..err..']')
end
return socket
end
local function create_connection(parameters)
if parameters.socket then
return parameters.socket
end
local perform_connection, socket
if parameters.scheme == 'unix' then
perform_connection, socket = connect_unix, require('socket.unix')
assert(socket, 'your build of LuaSocket does not support UNIX domain sockets')
else
if parameters.scheme then
local scheme = parameters.scheme
assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme)
end
perform_connection, socket = connect_tcp, require('socket').tcp
end
return perform_connection(socket(), parameters)
end
-- ############################################################################
function redis.error(message, level)
error(message, (level or 1) + 1)
end
function redis.connect(...)
local args, parameters = {...}, nil
if #args == 1 then
if type(args[1]) == 'table' then
parameters = args[1]
else
local uri = require('socket.url')
parameters = uri.parse(select(1, ...))
if parameters.scheme then
if parameters.query then
for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do
if k == 'tcp_nodelay' or k == 'tcp-nodelay' then
parameters.tcp_nodelay = parse_boolean(v)
end
end
end
else
parameters.host = parameters.path
end
end
elseif #args > 1 then
local host, port = unpack(args)
parameters = { host = host, port = port }
end
local commands = redis.commands or {}
if type(commands) ~= 'table' then
redis.error('invalid type for the commands table')
end
local socket = create_connection(merge_defaults(parameters))
local client = create_client(client_prototype, socket, commands)
return client
end
function redis.command(cmd, opts)
return command(cmd, opts)
end
-- obsolete
function redis.define_command(name, opts)
define_command_impl(redis.commands, name, opts)
end
-- obsolete
function redis.undefine_command(name)
undefine_command_impl(redis.commands, name)
end
-- ############################################################################
-- Commands defined in this table do not take the precedence over
-- methods defined in the client prototype table.
redis.commands = {
-- commands operating on the key space
exists = command('EXISTS', {
response = toboolean
}),
del = command('DEL'),
type = command('TYPE'),
rename = command('RENAME'),
renamenx = command('RENAMENX', {
response = toboolean
}),
expire = command('EXPIRE', {
response = toboolean
}),
pexpire = command('PEXPIRE', { -- >= 2.6
response = toboolean
}),
expireat = command('EXPIREAT', {
response = toboolean
}),
pexpireat = command('PEXPIREAT', { -- >= 2.6
response = toboolean
}),
ttl = command('TTL'),
pttl = command('PTTL'), -- >= 2.6
move = command('MOVE', {
response = toboolean
}),
dbsize = command('DBSIZE'),
persist = command('PERSIST', { -- >= 2.2
response = toboolean
}),
keys = command('KEYS', {
response = function(response)
if type(response) == 'string' then
-- backwards compatibility path for Redis < 2.0
local keys = {}
response:gsub('[^%s]+', function(key)
table.insert(keys, key)
end)
response = keys
end
return response
end
}),
randomkey = command('RANDOMKEY', {
response = function(response)
if response == '' then
return nil
else
return response
end
end
}),
sort = command('SORT', {
request = sort_request,
}),
-- commands operating on string values
set = command('SET'),
setnx = command('SETNX', {
response = toboolean
}),
setex = command('SETEX'), -- >= 2.0
psetex = command('PSETEX'), -- >= 2.6
mset = command('MSET', {
request = mset_filter_args
}),
msetnx = command('MSETNX', {
request = mset_filter_args,
response = toboolean
}),
get = command('GET'),
mget = command('MGET'),
getset = command('GETSET'),
incr = command('INCR'),
incrby = command('INCRBY'),
incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
decr = command('DECR'),
decrby = command('DECRBY'),
append = command('APPEND'), -- >= 2.0
substr = command('SUBSTR'), -- >= 2.0
strlen = command('STRLEN'), -- >= 2.2
setrange = command('SETRANGE'), -- >= 2.2
getrange = command('GETRANGE'), -- >= 2.2
setbit = command('SETBIT'), -- >= 2.2
getbit = command('GETBIT'), -- >= 2.2
-- commands operating on lists
rpush = command('RPUSH'),
lpush = command('LPUSH'),
llen = command('LLEN'),
lrange = command('LRANGE'),
ltrim = command('LTRIM'),
lindex = command('LINDEX'),
lset = command('LSET'),
lrem = command('LREM'),
lpop = command('LPOP'),
rpop = command('RPOP'),
rpoplpush = command('RPOPLPUSH'),
blpop = command('BLPOP'), -- >= 2.0
brpop = command('BRPOP'), -- >= 2.0
rpushx = command('RPUSHX'), -- >= 2.2
lpushx = command('LPUSHX'), -- >= 2.2
linsert = command('LINSERT'), -- >= 2.2
brpoplpush = command('BRPOPLPUSH'), -- >= 2.2
-- commands operating on sets
sadd = command('SADD'),
srem = command('SREM'),
spop = command('SPOP'),
smove = command('SMOVE', {
response = toboolean
}),
scard = command('SCARD'),
sismember = command('SISMEMBER', {
response = toboolean
}),
sinter = command('SINTER'),
sinterstore = command('SINTERSTORE'),
sunion = command('SUNION'),
sunionstore = command('SUNIONSTORE'),
sdiff = command('SDIFF'),
sdiffstore = command('SDIFFSTORE'),
smembers = command('SMEMBERS'),
srandmember = command('SRANDMEMBER'),
-- commands operating on sorted sets
zadd = command('ZADD'),
zincrby = command('ZINCRBY'),
zrem = command('ZREM'),
zrange = command('ZRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrevrange = command('ZREVRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrangebyscore = command('ZRANGEBYSCORE', {
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zunionstore = command('ZUNIONSTORE', { -- >= 2.0
request = zset_store_request
}),
zinterstore = command('ZINTERSTORE', { -- >= 2.0
request = zset_store_request
}),
zcount = command('ZCOUNT'),
zcard = command('ZCARD'),
zscore = command('ZSCORE'),
zremrangebyscore = command('ZREMRANGEBYSCORE'),
zrank = command('ZRANK'), -- >= 2.0
zrevrank = command('ZREVRANK'), -- >= 2.0
zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0
-- commands operating on hashes
hset = command('HSET', { -- >= 2.0
response = toboolean
}),
hsetnx = command('HSETNX', { -- >= 2.0
response = toboolean
}),
hmset = command('HMSET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, k)
table.insert(args, v)
end),
}),
hincrby = command('HINCRBY'), -- >= 2.0
hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
hget = command('HGET'), -- >= 2.0
hmget = command('HMGET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, v)
end),
}),
hdel = command('HDEL'), -- >= 2.0
hexists = command('HEXISTS', { -- >= 2.0
response = toboolean
}),
hlen = command('HLEN'), -- >= 2.0
hkeys = command('HKEYS'), -- >= 2.0
hvals = command('HVALS'), -- >= 2.0
hgetall = command('HGETALL', { -- >= 2.0
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
}),
-- connection related commands
ping = command('PING', {
response = function(response) return response == 'PONG' end
}),
echo = command('ECHO'),
auth = command('AUTH'),
select = command('SELECT'),
-- transactions
multi = command('MULTI'), -- >= 2.0
exec = command('EXEC'), -- >= 2.0
discard = command('DISCARD'), -- >= 2.0
watch = command('WATCH'), -- >= 2.2
unwatch = command('UNWATCH'), -- >= 2.2
-- publish - subscribe
subscribe = command('SUBSCRIBE'), -- >= 2.0
unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0
psubscribe = command('PSUBSCRIBE'), -- >= 2.0
punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0
publish = command('PUBLISH'), -- >= 2.0
-- redis scripting
eval = command('EVAL'), -- >= 2.6
evalsha = command('EVALSHA'), -- >= 2.6
script = command('SCRIPT'), -- >= 2.6
-- remote server control commands
bgrewriteaof = command('BGREWRITEAOF'),
config = command('CONFIG', { -- >= 2.0
response = function(reply, command, ...)
if (type(reply) == 'table') then
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
return reply
end
}),
client = command('CLIENT'), -- >= 2.4
slaveof = command('SLAVEOF'),
save = command('SAVE'),
bgsave = command('BGSAVE'),
lastsave = command('LASTSAVE'),
flushdb = command('FLUSHDB'),
flushall = command('FLUSHALL'),
monitor = command('MONITOR'),
time = command('TIME'), -- >= 2.6
slowlog = command('SLOWLOG', { -- >= 2.2.13
response = function(reply, command, ...)
if (type(reply) == 'table') then
local structured = { }
for index, entry in ipairs(reply) do
structured[index] = {
id = tonumber(entry[1]),
timestamp = tonumber(entry[2]),
duration = tonumber(entry[3]),
command = entry[4],
}
end
return structured
end
return reply
end
}),
info = command('INFO', {
response = parse_info,
}),
}
-- ############################################################################
return redis
| gpl-2.0 |
DarkstarProject/darkstar | scripts/globals/spells/poison_ii.lua | 12 | 1441 | -----------------------------------------
-- Spell: Poison
-----------------------------------------
require("scripts/globals/magic")
require("scripts/globals/msg")
require("scripts/globals/status")
-----------------------------------------
function onMagicCastingCheck(caster, target, spell)
return 0
end
function onSpellCast(caster, target, spell)
local dINT = caster:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT)
local skill = caster:getSkillLevel(dsp.skill.ENFEEBLING_MAGIC)
local power = math.max(skill / 20, 4)
if skill > 400 then
power = math.floor(skill * 49 / 183 - 55) -- No cap can be reached yet
end
power = calculatePotency(power, spell:getSkillType(), caster, target)
local duration = calculateDuration(120, spell:getSkillType(), spell:getSpellGroup(), caster, target)
local params = {}
params.diff = dINT
params.skillType = dsp.skill.ENFEEBLING_MAGIC
params.bonus = 0
params.effect = dsp.effect.POISON
local resist = applyResistanceEffect(caster, target, spell, params)
if resist >= 0.5 then -- effect taken
if target:addStatusEffect(params.effect, power, 3, duration * resist) then
spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS)
else
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT)
end
else -- resist entirely.
spell:setMsg(dsp.msg.basic.MAGIC_RESIST)
end
return params.effect
end | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/RuLude_Gardens/npcs/Dabih_Jajalioh.lua | 12 | 1385 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Dabih Jajalioh
-- Standard Merchant NPC
-- Additional script for pereodical
-- goods needed.
-- Partitially implemented.
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/zones/RuLude_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,DABIHJAJALIOH_SHOP_DIALOG);
stock = {0x03b4,60, --Carnation
0x027c,119, --Chamomile
0x03be,120, --Marguerite
0x03b5,96, --Rain Lily
0x03ad,80, --Red Rose
0x03b7,110} --Wijnruit
-- Place for difficult script
showShop(player, STATIC, stock);
end;
-----------------------------------
-- 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 |
Ardavans/DSR | mbwrap/games/config/game_config.lua | 1 | 14481 | if not g_opts then g_opts = {} end
g_opts.multigames = {}
-------------------
--some shared RangeOpts
--current min, current max, min max, max max, increment
local mapH = torch.Tensor{5,10,5,10,1}
local mapW = torch.Tensor{5,10,5,10,1}
local blockspct = torch.Tensor{0,.2,0,.2,.01}
local waterpct = torch.Tensor{0,.2,0,.2,.01}
-------------------
--some shared StaticOpts
local sso = {}
-------------- costs:
sso.costs = {}
sso.costs.goal = 0
sso.costs.empty = 0.1
sso.costs.block = 1000
sso.costs.water = 0.2
sso.costs.corner = 0
sso.costs.step = 0.1
sso.costs.pushableblock = 1000
---------------------
sso.crumb_action = 0
sso.push_action = 1
sso.flag_visited = 1
sso.enable_boundary = 0
sso.enable_corners = 1
sso.max_attributes = g_opts.max_attributes or 6
-------------------------------------------------------
-- MultiGoals:
local MultiGoalsRangeOpts = {}
MultiGoalsRangeOpts.mapH = mapH:clone()
MultiGoalsRangeOpts.mapW = mapW:clone()
MultiGoalsRangeOpts.blockspct = blockspct:clone()
MultiGoalsRangeOpts.waterpct = waterpct:clone()
MultiGoalsRangeOpts.ngoals = torch.Tensor{2,6,3,6,1}
MultiGoalsRangeOpts.ngoals_active = torch.Tensor{1,3,1,3,1}
local MultiGoalsStaticOpts = {}
for i,j in pairs(sso) do MultiGoalsStaticOpts[i] = j end
MultiGoalsOpts ={}
MultiGoalsOpts.RangeOpts = MultiGoalsRangeOpts
MultiGoalsOpts.StaticOpts = MultiGoalsStaticOpts
g_opts.multigames.MultiGoals = MultiGoalsOpts
-------------------------------------------------------
-- CondGoals:
local CondGoalsRangeOpts = {}
CondGoalsRangeOpts.mapH = mapH:clone()
CondGoalsRangeOpts.mapW = mapW:clone()
CondGoalsRangeOpts.blockspct = blockspct:clone()
CondGoalsRangeOpts.waterpct = waterpct:clone()
CondGoalsRangeOpts.ngoals = torch.Tensor{2,6,3,6,1}
CondGoalsRangeOpts.ncolors = torch.Tensor{2,6,3,6,1}
local CondGoalsStaticOpts = {}
for i,j in pairs(sso) do CondGoalsStaticOpts[i] = j end
CondGoalsOpts ={}
CondGoalsOpts.RangeOpts = CondGoalsRangeOpts
CondGoalsOpts.StaticOpts = CondGoalsStaticOpts
g_opts.multigames.CondGoals = CondGoalsOpts
-------------------------------------------------------
-- Exclusion:
local ExclusionRangeOpts = {}
ExclusionRangeOpts.mapH = mapH:clone()
ExclusionRangeOpts.mapW = mapW:clone()
ExclusionRangeOpts.blockspct = blockspct:clone()
ExclusionRangeOpts.waterpct = waterpct:clone()
ExclusionRangeOpts.ngoals = torch.Tensor{2,6,3,6,1}
ExclusionRangeOpts.ngoals_active = torch.Tensor{1,3,1,3,0}
local ExclusionStaticOpts = {}
for i,j in pairs(sso) do ExclusionStaticOpts[i] = j end
ExclusionOpts ={}
ExclusionOpts.RangeOpts = ExclusionRangeOpts
ExclusionOpts.StaticOpts = ExclusionStaticOpts
g_opts.multigames.Exclusion = ExclusionOpts
-------------------------------------------------------
-- Switches:
local SwitchesRangeOpts = {}
SwitchesRangeOpts.mapH = mapH:clone()
SwitchesRangeOpts.mapW = mapW:clone()
SwitchesRangeOpts.blockspct = blockspct:clone()
SwitchesRangeOpts.waterpct = waterpct:clone()
SwitchesRangeOpts.nswitches = torch.Tensor{1,5,1,5,0}
SwitchesRangeOpts.ncolors = torch.Tensor{1,6,1,6,1}
local SwitchesStaticOpts = {}
for i,j in pairs(sso) do SwitchesStaticOpts[i] = j end
SwitchesOpts ={}
SwitchesOpts.RangeOpts = SwitchesRangeOpts
SwitchesOpts.StaticOpts = SwitchesStaticOpts
g_opts.multigames.Switches = SwitchesOpts
-------------------------------------------------------
-- LightKey:
local LightKeyRangeOpts = {}
LightKeyRangeOpts.mapH = mapH:clone()
LightKeyRangeOpts.mapW = mapW:clone()
LightKeyRangeOpts.blockspct = blockspct:clone()
LightKeyRangeOpts.waterpct = waterpct:clone()
local LightKeyStaticOpts = {}
for i,j in pairs(sso) do LightKeyStaticOpts[i] = j end
LightKeyOpts ={}
LightKeyOpts.RangeOpts = LightKeyRangeOpts
LightKeyOpts.StaticOpts = LightKeyStaticOpts
g_opts.multigames.LightKey = LightKeyOpts
-------------------------------------------------------
-- Goto:
local GotoRangeOpts = {}
GotoRangeOpts.mapH = mapH:clone()
GotoRangeOpts.mapW = mapW:clone()
GotoRangeOpts.blockspct = blockspct:clone()
GotoRangeOpts.waterpct = waterpct:clone()
local GotoStaticOpts = {}
for i,j in pairs(sso) do GotoStaticOpts[i] = j end
GotoOpts ={}
GotoOpts.RangeOpts = GotoRangeOpts
GotoOpts.StaticOpts = GotoStaticOpts
g_opts.multigames.Goto = GotoOpts
-------------------------------------------------------
-- GotoHidden:
local GotoHiddenRangeOpts = {}
GotoHiddenRangeOpts.mapH = mapH:clone()
GotoHiddenRangeOpts.mapW = mapW:clone()
GotoHiddenRangeOpts.blockspct = blockspct:clone()
GotoHiddenRangeOpts.waterpct = waterpct:clone()
GotoHiddenRangeOpts.ngoals = torch.Tensor{1,6,3,6,1}
local GotoHiddenStaticOpts = {}
for i,j in pairs(sso) do GotoHiddenStaticOpts[i] = j end
GotoHiddenOpts ={}
GotoHiddenOpts.RangeOpts = GotoHiddenRangeOpts
GotoHiddenOpts.StaticOpts = GotoHiddenStaticOpts
g_opts.multigames.GotoHidden = GotoHiddenOpts
-------------------------------------------------------
-- PushBlock:
--note: these are not the shared range opts!!!
local PushBlockRangeOpts = {}
PushBlockRangeOpts.mapH = torch.Tensor{3,7,3,7,1}
PushBlockRangeOpts.mapW = torch.Tensor{3,7,3,7,1}
PushBlockRangeOpts.blockspct = torch.Tensor{0,0.1,0,.1,.01}
PushBlockRangeOpts.waterpct = torch.Tensor{0,0.1,0,.1,.01}
local PushBlockStaticOpts = {}
for i,j in pairs(sso) do PushBlockStaticOpts[i] = j end
PushBlockOpts ={}
PushBlockOpts.RangeOpts = PushBlockRangeOpts
PushBlockOpts.StaticOpts = PushBlockStaticOpts
g_opts.multigames.PushBlock = PushBlockOpts
-------------------------------------------------------
-- PushBlockCardinal:
--note: these are not the shared range opts!!!
local PushBlockCardinalRangeOpts = {}
PushBlockCardinalRangeOpts.mapH = torch.Tensor{3,7,3,7,1}
PushBlockCardinalRangeOpts.mapW = torch.Tensor{3,7,3,7,1}
PushBlockCardinalRangeOpts.blockspct = torch.Tensor{0,0.1,0,.1,.01}
PushBlockCardinalRangeOpts.waterpct = torch.Tensor{0,0.1,0,.1,.01}
local PushBlockCardinalStaticOpts = {}
for i,j in pairs(sso) do PushBlockCardinalStaticOpts[i] = j end
PushBlockCardinalOpts ={}
PushBlockCardinalOpts.RangeOpts = PushBlockCardinalRangeOpts
PushBlockCardinalOpts.StaticOpts = PushBlockCardinalStaticOpts
g_opts.multigames.PushBlockCardinal = PushBlockCardinalOpts
-------------------------------------------------------
-- BlockedDoor:
local BlockedDoorRangeOpts = {}
BlockedDoorRangeOpts.mapH = mapH:clone()
BlockedDoorRangeOpts.mapW = mapW:clone()
BlockedDoorRangeOpts.blockspct = blockspct:clone()
BlockedDoorRangeOpts.waterpct = waterpct:clone()
local BlockedDoorStaticOpts = {}
for i,j in pairs(sso) do BlockedDoorStaticOpts[i] = j end
BlockedDoorOpts ={}
BlockedDoorOpts.RangeOpts = BlockedDoorRangeOpts
BlockedDoorOpts.StaticOpts = BlockedDoorStaticOpts
g_opts.multigames.BlockedDoor = BlockedDoorOpts
-------------------------------------------------------
-- MovingGoals:
sso.costs = {}
sso.costs.goal = 0
sso.costs.empty = 0.1
sso.costs.block = 1000
sso.costs.water = 0.2
sso.costs.corner = 0
sso.costs.step = 0.1
sso.costs.pushableblock = 1000
---------------------
sso.crumb_action = 0
sso.push_action = 0
sso.flag_visited = 0
sso.enable_boundary = 0
sso.enable_corners = 0
sso.max_attributes = g_opts.max_attributes or 6
local MovingGoalsRangeOpts = {}
MovingGoalsRangeOpts.mapH = mapH:clone()
MovingGoalsRangeOpts.mapW = mapW:clone()
MovingGoalsRangeOpts.blockspct = blockspct:clone()
MovingGoalsRangeOpts.waterpct = waterpct:clone()
local MovingGoalsStaticOpts = {}
for i,j in pairs(sso) do MovingGoalsStaticOpts[i] = j end
MovingGoalsOpts ={}
MovingGoalsOpts.RangeOpts = MovingGoalsRangeOpts
MovingGoalsOpts.StaticOpts = MovingGoalsStaticOpts
g_opts.multigames.MovingGoals = MovingGoalsOpts
-------------------------------------------------------
--Bottleneck:
sso.costs = {}
sso.costs.goal = 0
sso.costs.empty = 0.1
sso.costs.block = 1000
sso.costs.water = 0.2
sso.costs.corner = 0
sso.costs.step = 0.1
sso.costs.pushableblock = 1000
---------------------
sso.crumb_action = 0
sso.push_action = 0
sso.flag_visited = 0
sso.enable_boundary = 0
sso.enable_corners = 0
sso.max_attributes = g_opts.max_attributes or 6
local BottleneckRangeOpts = {}
BottleneckRangeOpts.mapH = mapH:clone()
BottleneckRangeOpts.mapW = mapW:clone()
BottleneckRangeOpts.blockspct = blockspct:clone()
BottleneckRangeOpts.waterpct = waterpct:clone()
local BottleneckStaticOpts = {}
for i,j in pairs(sso) do BottleneckStaticOpts[i] = j end
BottleneckOpts ={}
BottleneckOpts.RangeOpts = BottleneckRangeOpts
BottleneckOpts.StaticOpts = BottleneckStaticOpts
g_opts.multigames.Bottleneck = BottleneckOpts
-------------------------------------------------------
--Bottleneck2Rooms:
sso.costs = {}
sso.costs.goal = 0
sso.costs.empty = 0.1
sso.costs.block = 1000
sso.costs.water = 0.2
sso.costs.corner = 0
sso.costs.step = 0.1
sso.costs.pushableblock = 1000
---------------------
sso.crumb_action = 0
sso.push_action = 0
sso.flag_visited = 0
sso.enable_boundary = 0
sso.enable_corners = 0
sso.max_attributes = g_opts.max_attributes or 6
local Bottleneck2RoomsRangeOpts = {}
Bottleneck2RoomsRangeOpts.mapH = mapH:clone()
Bottleneck2RoomsRangeOpts.mapW = mapW:clone()
Bottleneck2RoomsRangeOpts.blockspct = blockspct:clone()
Bottleneck2RoomsRangeOpts.waterpct = waterpct:clone()
local Bottleneck2RoomsStaticOpts = {}
for i,j in pairs(sso) do Bottleneck2RoomsStaticOpts[i] = j end
Bottleneck2RoomsOpts ={}
Bottleneck2RoomsOpts.RangeOpts = Bottleneck2RoomsRangeOpts
Bottleneck2RoomsOpts.StaticOpts = Bottleneck2RoomsStaticOpts
g_opts.multigames.Bottleneck2Rooms = Bottleneck2RoomsOpts
-------------------------------------------------------
-- MovingGoalsEasy:
sso.costs = {}
sso.costs.goal = 1
sso.costs.empty = 0
sso.costs.block = 1000
sso.costs.water = -0.5
sso.costs.corner = 0
sso.costs.step = -0.5
sso.costs.pushableblock = 1000
---------------------
sso.crumb_action = 0
sso.push_action = 0
sso.flag_visited = 0
sso.enable_boundary = 0
sso.enable_corners = 0
sso.max_attributes = g_opts.max_attributes or 6
local MovingGoalsEasyRangeOpts = {}
MovingGoalsEasyRangeOpts.mapH = mapH:clone()
MovingGoalsEasyRangeOpts.mapW = mapW:clone()
MovingGoalsEasyRangeOpts.blockspct = blockspct:clone()
MovingGoalsEasyRangeOpts.waterpct = waterpct:clone()
local MovingGoalsEasyStaticOpts = {}
for i,j in pairs(sso) do MovingGoalsEasyStaticOpts[i] = j end
MovingGoalsEasyOpts ={}
MovingGoalsEasyOpts.RangeOpts = MovingGoalsEasyRangeOpts
MovingGoalsEasyOpts.StaticOpts = MovingGoalsEasyStaticOpts
g_opts.multigames.MovingGoalsEasy = MovingGoalsEasyOpts
-------------------------------------------------------
-- MovingGoalsMedium:
sso.costs = {}
sso.costs.goal = 1
sso.costs.empty = 0
sso.costs.block = 1000
sso.costs.water = -0.5
sso.costs.corner = 0
sso.costs.step = -0.5
sso.costs.pushableblock = 1000
---------------------
sso.crumb_action = 0
sso.push_action = 0
sso.flag_visited = 0
sso.enable_boundary = 0
sso.enable_corners = 0
sso.max_attributes = g_opts.max_attributes or 6
local MovingGoalsMediumRangeOpts = {}
MovingGoalsMediumRangeOpts.mapH = mapH:clone()
MovingGoalsMediumRangeOpts.mapW = mapW:clone()
MovingGoalsMediumRangeOpts.blockspct = blockspct:clone()
MovingGoalsMediumRangeOpts.waterpct = waterpct:clone()
local MovingGoalsMediumStaticOpts = {}
for i,j in pairs(sso) do MovingGoalsMediumStaticOpts[i] = j end
MovingGoalsMediumOpts ={}
MovingGoalsMediumOpts.RangeOpts = MovingGoalsMediumRangeOpts
MovingGoalsMediumOpts.StaticOpts = MovingGoalsMediumStaticOpts
g_opts.multigames.MovingGoalsMedium = MovingGoalsMediumOpts
-------------------------------------------------------
-- MovingGoalsHard:
sso.costs = {}
sso.costs.goal = 1
sso.costs.empty = 0
sso.costs.block = 1000
sso.costs.water = -0.5
sso.costs.corner = 0
sso.costs.step = -0.5
sso.costs.pushableblock = 1000
---------------------
sso.crumb_action = 0
sso.push_action = 0
sso.flag_visited = 0
sso.enable_boundary = 0
sso.enable_corners = 0
sso.max_attributes = g_opts.max_attributes or 6
local MovingGoalsHardRangeOpts = {}
MovingGoalsHardRangeOpts.mapH = mapH:clone()
MovingGoalsHardRangeOpts.mapW = mapW:clone()
MovingGoalsHardRangeOpts.blockspct = blockspct:clone()
MovingGoalsHardRangeOpts.waterpct = waterpct:clone()
local MovingGoalsHardStaticOpts = {}
for i,j in pairs(sso) do MovingGoalsHardStaticOpts[i] = j end
MovingGoalsHardOpts = {}
MovingGoalsHardOpts.RangeOpts = MovingGoalsHardRangeOpts
MovingGoalsHardOpts.StaticOpts = MovingGoalsHardStaticOpts
g_opts.multigames.MovingGoalsHard = MovingGoalsHardOpts
-------------------------------------------------------
-- MovingGoalsEasyMod:
sso.costs = {}
sso.costs.goal = 1
sso.costs.empty = 0
sso.costs.block = 1000
sso.costs.water = -0.5
sso.costs.corner = 0
sso.costs.step = -0.5
sso.costs.pushableblock = 1000
---------------------
sso.crumb_action = 0
sso.push_action = 0
sso.flag_visited = 0
sso.enable_boundary = 0
sso.enable_corners = 0
sso.max_attributes = g_opts.max_attributes or 6
local MovingGoalsEasyModRangeOpts = {}
MovingGoalsEasyModRangeOpts.mapH = mapH:clone()
MovingGoalsEasyModRangeOpts.mapW = mapW:clone()
MovingGoalsEasyModRangeOpts.blockspct = blockspct:clone()
MovingGoalsEasyModRangeOpts.waterpct = waterpct:clone()
local MovingGoalsEasyModStaticOpts = {}
for i,j in pairs(sso) do MovingGoalsEasyModStaticOpts[i] = j end
MovingGoalsEasyModOpts ={}
MovingGoalsEasyModOpts.RangeOpts = MovingGoalsEasyModRangeOpts
MovingGoalsEasyModOpts.StaticOpts = MovingGoalsEasyModStaticOpts
g_opts.multigames.MovingGoalsEasyMod = MovingGoalsEasyModOpts
-------------------------------------------------------
-- MovingGoalsMediumMod:
sso.costs = {}
sso.costs.goal = 1
sso.costs.empty = 0
sso.costs.block = 1000
sso.costs.water = -0.5
sso.costs.corner = 0
sso.costs.step = -0.5
sso.costs.pushableblock = 1000
---------------------
sso.crumb_action = 0
sso.push_action = 0
sso.flag_visited = 0
sso.enable_boundary = 0
sso.enable_corners = 0
sso.max_attributes = g_opts.max_attributes or 6
local MovingGoalsMediumModRangeOpts = {}
MovingGoalsMediumModRangeOpts.mapH = mapH:clone()
MovingGoalsMediumModRangeOpts.mapW = mapW:clone()
MovingGoalsMediumModRangeOpts.blockspct = blockspct:clone()
MovingGoalsMediumModRangeOpts.waterpct = waterpct:clone()
local MovingGoalsMediumModStaticOpts = {}
for i,j in pairs(sso) do MovingGoalsMediumModStaticOpts[i] = j end
MovingGoalsMediumModOpts ={}
MovingGoalsMediumModOpts.RangeOpts = MovingGoalsMediumModRangeOpts
MovingGoalsMediumModOpts.StaticOpts = MovingGoalsMediumModStaticOpts
g_opts.multigames.MovingGoalsMediumMod = MovingGoalsMediumModOpts
return g_opts
| mit |
nehz/slick | core/IndexRecorder.lua | 1 | 1354 | local IndexRecorder = {}
function IndexRecorder.new(type)
return setmetatable({type = type}, IndexRecorder)
end
function IndexRecorder:__index(name)
if rawget(self, 1) then
table.insert(self, name)
return self
end
local info = {type = self.type, args = {}}
return setmetatable({['$info'] = info, name}, IndexRecorder)
end
function IndexRecorder:__call(...)
assert(rawget(self, 1))
local args = table.pack(...)
if self == args[1] then
self['$info'].args = table.pack(table.unpack(args, 2, args.n))
self['$info'].id = table.remove(self)
else
self['$info'].args = args
end
return self
end
function IndexRecorder:__mod(value)
assert(rawget(self, 1))
self['$info'].init = value
return self
end
IndexRecorder.__bxor = IndexRecorder.__mod
function IndexRecorder:__tostring()
if #self > 0 then
return string.format('IndexRecorder(%s.%s)',
self['$info'].type, table.concat(self, '.'))
else
return string.format('IndexRecorder(%s)', self.type)
end
end
function IndexRecorder.info(i)
assert(getmetatable(i) == IndexRecorder)
assert(rawget(i, 1))
return i['$info']
end
function IndexRecorder.value(i)
assert(getmetatable(i) == IndexRecorder)
if #i == 0 then
return i.type
else
return i['$info'].type .. '.' .. table.concat(i, '.')
end
end
return IndexRecorder
| mit |
shirat74/sile | lua-libraries/std/optparse.lua | 6 | 22140 | --[=[--
Parse and process command line options.
local OptionParser = require "std.optparse"
local parser = OptionParser [[
any text VERSION
Additional lines of text to show when the --version
option is passed.
Several lines or paragraphs are permitted.
Usage: PROGNAME
Banner text.
Optional long description text to show when the --help
option is passed.
Several lines or paragraphs of long description are permitted.
Options:
-b a short option with no long option
--long a long option with no short option
--another-long a long option with internal hypen
-v, --verbose a combined short and long option
-n, --dryrun, --dry-run several spellings of the same option
-u, --name=USER require an argument
-o, --output=[FILE] accept an optional argument
--version display version information, then exit
--help display this help, then exit
Footer text. Several lines or paragraphs are permitted.
Please report bugs at bug-list@yourhost.com
]]
_G.arg, _G.opts = parser:parse (_G.arg)
Most often, everything else is handled automatically. After calling
`parser:parse` as shown above, `_G.arg` will contain unparsed arguments,
usually filenames or similar, and `_G.opts` will be a table of parsed
option values. The keys to the table are the long-options with leading
hyphens stripped, and non-word characters turned to `_`. For example
if `--another-long` had been found in `_G.arg` then `_G.opts` would
have a key named `another_long`. If there is no long option name, then
the short option is used, e.g. `_G.opts.b` will be set. The values
saved in those keys are controlled by the option handler, usually just
`true` or the option argument string as appropriate.
On those occasions where more complex processing is required, handlers
can be replaced or added using parser:@{on}. A good option to always
add, is to make `--` signal the end of processed options, so that any
options following `--` on the command line, even if they begin with a
hyphen and look like options otherwise, are not processed but instead
left in the modified `_G.arg` returned by `parser:parse`:
parser:on ('--', parser.finished)
See the documentation for @{std.optparse:on} for more details of how to
use this powerful method.
When writing your own handlers for @{std.optparse:on}, you only need
to deal with normalised arguments, because combined short arguments
(`-xyz`), equals separators to long options (`--long=ARG`) are fully
expanded before any handler is called.
Note that @{std.io.die} and @{std.io.warn} will only prefix messages
with `parser.program` if the parser options are assigned back to
`_G.opts` as shown in the example above.
@classmod std.optparse
]=]
local OptionParser -- forward declaration
------
-- Customized parser for your options.
--
-- This table is returned by @{OptionParser}, and most importantly has
-- the @{parse} method you call to fill the `opts` table according to
-- what command-line options were passed to your program.
-- @table parser
-- @string program the first word following `Usage:` in @{OptionParser}
-- spec string
-- @string version the last white-space delimited word on the first line
-- of text in the spec string
-- @string versiontext everything preceding `Usage:` in the spec string,
-- and which will be displayed by the @{version} @{on_handler}
-- @string helptext everything including and following `Usage:` in the
-- spec string and which will be displayed by the @{help}
-- @{on_handler}
-- @func parse see @{parse}
-- @func on see @{on}
--[[ ----------------- ]]--
--[[ Helper Functions. ]]--
--[[ ----------------- ]]--
local optional, required
--- Normalise an argument list.
-- Separate short options, remove `=` separators from
-- `--long-option=optarg` etc.
-- @local
-- @function normalise
-- @tparam table arglist list of arguments to normalise
-- @treturn table normalised argument list
local function normalise (self, arglist)
-- First pass: Normalise to long option names, without '=' separators.
local normal = {}
local i = 0
while i < #arglist do
i = i + 1
local opt = arglist[i]
-- Split '--long-option=option-argument'.
if opt:sub (1, 2) == "--" then
local x = opt:find ("=", 3, true)
if x then
table.insert (normal, opt:sub (1, x - 1))
table.insert (normal, opt:sub (x + 1))
else
table.insert (normal, opt)
end
elseif opt:sub (1, 1) == "-" and string.len (opt) > 2 then
local rest
repeat
opt, rest = opt:sub (1, 2), opt:sub (3)
table.insert (normal, opt)
-- Split '-xyz' into '-x -yz', and reiterate for '-yz'
if self[opt].handler ~= optional and
self[opt].handler ~= required then
if string.len (rest) > 0 then
opt = "-" .. rest
else
opt = nil
end
-- Split '-xshortargument' into '-x shortargument'.
else
table.insert (normal, rest)
opt = nil
end
until opt == nil
else
table.insert (normal, opt)
end
end
normal[-1], normal[0] = arglist[-1], arglist[0]
return normal
end
--- Store `value` with `opt`.
-- @local
-- @function set
-- @string opt option name
-- @param value option argument value
local function set (self, opt, value)
local key = self[opt].key
if type (self.opts[key]) == "table" then
table.insert (self.opts[key], value)
elseif self.opts[key] ~= nil then
self.opts[key] = { self.opts[key], value }
else
self.opts[key] = value
end
end
--[[ ============= ]]--
--[[ Option Types. ]]--
--[[ ============= ]]--
--- Option at `arglist[i]` can take an argument.
-- Argument is accepted only if there is a following entry that does not
-- begin with a '-'.
--
-- This is the handler automatically assigned to options that have
-- `--opt=[ARG]` style specifications in the @{OptionParser} spec
-- argument. You can also pass it as the `handler` argument to @{on} for
-- options you want to add manually without putting them in the
-- @{OptionParser} spec.
--
-- Like @{required}, this handler will store multiple occurrences of a
-- command-line option.
-- @static
-- @tparam table arglist list of arguments
-- @int i index of last processed element of `arglist`
-- @param[opt=true] value either a function to process the option
-- argument, or a default value if encountered without an optarg
-- @treturn int index of next element of `arglist` to process
function optional (self, arglist, i, value)
if i + 1 <= #arglist and arglist[i + 1]:sub (1, 1) ~= "-" then
return self:required (arglist, i, value)
end
if type (value) == "function" then
value = value (self, opt, nil)
elseif value == nil then
value = true
end
set (self, arglist[i], value)
return i + 1
end
--- Option at `arglist[i}` requires an argument.
--
-- This is the handler automatically assigned to options that have
-- `--opt=ARG` style specifications in the @{OptionParser} spec argument.
-- You can also pass it as the `handler` argument to @{on} for options
-- you want to add manually without putting them in the @{OptionParser}
-- spec.
--
-- Normally the value stored in the `opt` table by this handler will be
-- the string given as the argument to that option on the command line.
-- However, if the option is given on the command-line multiple times,
-- `opt["name"]` will end up with all those arguments stored in the
-- array part of a table:
--
-- $ cat ./prog
-- ...
-- parser:on ({"-e", "-exec"}, required)
-- _G.arg, _G.opt = parser:parse (_G.arg)
-- print std.string.tostring (_G.opt.exec)
-- ...
-- $ ./prog -e '(foo bar)' -e '(foo baz)' -- qux
-- {1=(foo bar),2=(foo baz)}
-- @static
-- @tparam table arglist list of arguments
-- @int i index of last processed element of `arglist`
-- @param[opt] value either a function to process the option argument,
-- or a forced value to replace the user's option argument.
-- @treturn int index of next element of `arglist` to process
function required (self, arglist, i, value)
local opt = arglist[i]
if i + 1 > #arglist then
self:opterr ("option '" .. opt .. "' requires an argument")
return i + 1
end
if type (value) == "function" then
value = value (self, opt, arglist[i + 1])
elseif value == nil then
value = arglist[i + 1]
end
set (self, opt, value)
return i + 2
end
--- Finish option processing
--
-- This is the handler automatically assigned to the option written as
-- `--` in the @{OptionParser} spec argument. You can also pass it as
-- the `handler` argument to @{on} if you want to manually add an end
-- of options marker without writing it in the @{OptionParser} spec.
--
-- This handler tells the parser to stop processing arguments, so that
-- anything after it will be an argument even if it otherwise looks
-- like an option.
-- @static
-- @tparam table arglist list of arguments
-- @int i index of last processed element of `arglist`
-- @treturn int index of next element of `arglist` to process
local function finished (self, arglist, i)
for opt = i + 1, #arglist do
table.insert (self.unrecognised, arglist[opt])
end
return 1 + #arglist
end
--- Option at `arglist[i]` is a boolean switch.
--
-- This is the handler automatically assigned to options that have
-- `--long-opt` or `-x` style specifications in the @{OptionParser} spec
-- argument. You can also pass it as the `handler` argument to @{on} for
-- options you want to add manually without putting them in the
-- @{OptionParser} spec.
--
-- Beware that, _unlike_ @{required}, this handler will store multiple
-- occurrences of a command-line option as a table **only** when given a
-- `value` function. Automatically assigned handlers do not do this, so
-- the option will simply be `true` if the option was given one or more
-- times on the command-line.
-- @static
-- @tparam table arglist list of arguments
-- @int i index of last processed element of `arglist`
-- @param[opt] value either a function to process the option argument,
-- or a value to store when this flag is encountered
-- @treturn int index of next element of `arglist` to process
local function flag (self, arglist, i, value)
local opt = arglist[i]
if type (value) == "function" then
set (self, opt, value (self, opt, true))
elseif value == nil then
local key = self[opt].key
self.opts[key] = true
end
return i + 1
end
--- Option should display help text, then exit.
--
-- This is the handler automatically assigned tooptions that have
-- `--help` in the specification, e.g. `-h, -?, --help`.
-- @static
-- @function help
local function help (self)
print (self.helptext)
os.exit (0)
end
--- Option should display version text, then exit.
--
-- This is the handler automatically assigned tooptions that have
-- `--version` in the specification, e.g. `-V, --version`.
-- @static
-- @function version
local function version (self)
print (self.versiontext)
os.exit (0)
end
--[[ =============== ]]--
--[[ Argument Types. ]]--
--[[ =============== ]]--
--- Map various option strings to equivalent Lua boolean values.
-- @table boolvals
-- @field false false
-- @field 0 false
-- @field no false
-- @field n false
-- @field true true
-- @field 1 true
-- @field yes true
-- @field y true
local boolvals = {
["false"] = false, ["true"] = true,
["0"] = false, ["1"] = true,
no = false, yes = true,
n = false, y = true,
}
--- Return a Lua boolean equivalent of various `optarg` strings.
-- Report an option parse error if `optarg` is not recognised.
--
-- Pass this as the `value` function to @{on} when you want various
-- *truthy* or *falsey* option arguments to be coerced to a Lua `true`
-- or `false` respectively in the options table.
-- @static
-- @string opt option name
-- @string[opt="1"] optarg option argument, must be a key in @{boolvals}
-- @treturn bool `true` or `false`
local function boolean (self, opt, optarg)
if optarg == nil then optarg = "1" end -- default to truthy
local b = boolvals[tostring (optarg):lower ()]
if b == nil then
return self:opterr (optarg .. ": Not a valid argument to " ..opt[1] .. ".")
end
return b
end
--- Report an option parse error unless `optarg` names an
-- existing file.
--
-- Pass this as the `value` function to @{on} when you want to accept
-- only option arguments that name an existing file.
-- @fixme this only checks whether the file has read permissions
-- @static
-- @string opt option name
-- @string optarg option argument, must be an existing file
-- @treturn `optarg`
local function file (self, opt, optarg)
local h, errmsg = io.open (optarg, "r")
if h == nil then
return self:opterr (optarg .. ": " .. errmsg)
end
h:close ()
return optarg
end
--[[ =============== ]]--
--[[ Option Parsing. ]]--
--[[ =============== ]]--
--- Report an option parse error, then exit with status 2.
--
-- Use this in your custom option handlers for consistency with the
-- error output from built-in `optparse` error messages.
-- @static
-- @string msg error message
local function opterr (self, msg)
local prog = self.program
-- Ensure final period.
if msg:match ("%.$") == nil then msg = msg .. "." end
io.stderr:write (prog .. ": error: " .. msg .. "\n")
io.stderr:write (prog .. ": Try '" .. prog .. " --help' for help.\n")
os.exit (2)
end
------
-- Function signature of an option handler for @{on}.
-- @function on_handler
-- @tparam table arglist list of arguments
-- @int i index of last processed element of `arglist`
-- @param[opt=nil] value additional `value` registered with @{on}
-- @treturn int index of next element of `arglist` to process
--- Add an option handler.
--
-- When the automatically assigned option handlers don't do everything
-- you require, or when you don't want to put an option into the
-- @{OptionParser} `spec` argument, use this function to specify custom
-- behaviour. If you write the option into the `spec` argument anyway,
-- calling this function will replace the automatically assigned handler
-- with your own.
--
-- parser:on ("--", parser.finished)
-- parser:on ("-V", parser.version)
-- parser:on ("--config-file", parser.required, parser.file)
-- parser:on ("--enable-nls", parser.optional, parser.boolean)
-- @function on
-- @tparam[string|table] opts name of the option, or list of option names
-- @tparam on_handler handler function to call when any of `opts` is
-- encountered
-- @param value additional value passed to @{on_handler}
local function on (self, opts, handler, value)
if type (opts) == "string" then opts = { opts } end
handler = handler or flag -- unspecified options behave as flags
normal = {}
for _, optspec in ipairs (opts) do
optspec:gsub ("(%S+)",
function (opt)
-- 'x' => '-x'
if string.len (opt) == 1 then
opt = "-" .. opt
-- 'option-name' => '--option-name'
elseif opt:match ("^[^%-]") ~= nil then
opt = "--" .. opt
end
if opt:match ("^%-[^%-]+") ~= nil then
-- '-xyz' => '-x -y -z'
for i = 2, string.len (opt) do
table.insert (normal, "-" .. opt:sub (i, i))
end
else
table.insert (normal, opt)
end
end)
end
-- strip leading '-', and convert non-alphanums to '_'
key = normal[#normal]:match ("^%-*(.*)$"):gsub ("%W", "_")
for _, opt in ipairs (normal) do
self[opt] = { key = key, handler = handler, value = value }
end
end
------
-- Parsed options table, with a key for each encountered option, each
-- with value set by that option's @{on_handler}. Where an option
-- has one or more long-options specified, the key will be the first
-- one of those with leading hyphens stripped and non-alphanumeric
-- characters replaced with underscores. For options that can only be
-- specified by a short option, the key will be the letter of the first
-- of the specified short options:
--
-- {"-e", "--eval-file"} => opts.eval_file
-- {"-n", "--dryrun", "--dry-run"} => opts.dryrun
-- {"-t", "-T"} => opts.t
--
-- Generally there will be one key for each previously specified
-- option (either automatically assigned by @{OptionParser} or
-- added manually with @{on}) containing the value(s) assigned by the
-- associated @{on_handler}. For automatically assigned handlers,
-- that means `true` for straight-forward flags and
-- optional-argument options for which no argument was given; or else
-- the string value of the argument passed with an option given only
-- once; or a table of string values of the same for arguments given
-- multiple times.
--
-- ./prog -x -n -x => opts = { x = true, dryrun = true }
-- ./prog -e '(foo bar)' -e '(foo baz)'
-- => opts = {eval_file = {"(foo bar)", "(foo baz)"} }
--
-- If you write your own handlers, or otherwise specify custom
-- handling of options with @{on}, then whatever value those handlers
-- return will be assigned to the respective keys in `opts`.
-- @table opts
--- Parse `arglist`.
-- @tparam table arglist list of arguments
-- @treturn table a list of unrecognised `arglist` elements
-- @treturn opts parsing results
local function parse (self, arglist)
self.unrecognised = {}
arglist = normalise (self, arglist)
local i = 1
while i > 0 and i <= #arglist do
local opt = arglist[i]
if self[opt] == nil then
table.insert (self.unrecognised, opt)
i = i + 1
-- Following non-'-' prefixed argument is an optarg.
if i <= #arglist and arglist[i]:match "^[^%-]" then
table.insert (self.unrecognised, arglist[i])
i = i + 1
end
-- Run option handler functions.
else
assert (type (self[opt].handler) == "function")
i = self[opt].handler (self, arglist, i, self[opt].value)
end
end
-- metatable allows `io.warn` to find `parser.program` when assigned
-- back to _G.opts.
return self.unrecognised, setmetatable (self.opts, {__index = self})
end
--- @export
local methods = {
boolean = boolean,
file = file,
finished = finished,
flag = flag,
help = help,
optional = optional,
required = required,
version = version,
on = on,
opterr = opterr,
parse = parse,
}
--- Take care not to register duplicate handlers.
-- @param current current handler value
-- @param new new handler value
-- @return `new` if `current` is nil
local function set_handler (current, new)
assert (current == nil, "only one handler per option")
return new
end
--- Instantiate a new parser.
-- Read the documented options from `spec` and return a new parser that
-- can be passed to @{parse} for parsing those options from an argument
-- list. Options are recognised as lines that begin with at least two
-- spaces, followed by a hyphen.
-- @static
-- @string spec option parsing specification
-- @treturn parser a parser for options described by `spec`
function OptionParser (spec)
local parser = setmetatable ({ opts = {} }, { __index = methods })
parser.versiontext, parser.version, parser.helptext, parser.program =
spec:match ("^([^\n]-(%S+)\n.-)%s*([Uu]sage: (%S+).-)%s*$")
if parser.versiontext == nil then
error ("OptionParser spec argument must match '<version>\\n" ..
"...Usage: <program>...'")
end
-- Collect helptext lines that begin with two or more spaces followed
-- by a '-'.
local specs = {}
parser.helptext:gsub ("\n %s*(%-[^\n]+)",
function (spec) table.insert (specs, spec) end)
-- Register option handlers according to the help text.
for _, spec in ipairs (specs) do
local options, handler = {}
-- Loop around each '-' prefixed option on this line.
while spec:sub (1, 1) == "-" do
-- Capture end of options processing marker.
if spec:match "^%-%-,?%s" then
handler = set_handler (handler, finished)
-- Capture optional argument in the option string.
elseif spec:match "^%-[%-%w]+=%[.+%],?%s" then
handler = set_handler (handler, optional)
-- Capture required argument in the option string.
elseif spec:match "^%-[%-%w]+=%S+,?%s" then
handler = set_handler (handler, required)
-- Capture any specially handled arguments.
elseif spec:match "^%-%-help,?%s" then
handler = set_handler (handler, help)
elseif spec:match "^%-%-version,?%s" then
handler = set_handler (handler, version)
end
-- Consume argument spec, now that it was processed above.
spec = spec:gsub ("^(%-[%-%w]+)=%S+%s", "%1 ")
-- Consume short option.
local _, c = spec:gsub ("^%-([-%w]),?%s+(.*)$",
function (opt, rest)
if opt == "-" then opt = "--" end
table.insert (options, opt)
spec = rest
end)
-- Be careful not to consume more than one option per iteration,
-- otherwise we might miss a handler test at the next loop.
if c == 0 then
-- Consume long option.
spec:gsub ("^%-%-([%-%w]+),?%s+(.*)$",
function (opt, rest)
table.insert (options, opt)
spec = rest
end)
end
end
-- Unless specified otherwise, treat each option as a flag.
parser:on (options, handler or flag)
end
return parser
end
-- Support calling the returned table:
return setmetatable (methods, {
__call = function (_, ...)
return OptionParser (...)
end,
})
| mit |
anshkumar/yugioh-glaze | assets/script/c64187086.lua | 9 | 1622 | --地縛神の復活
function c64187086.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c64187086.cost)
e1:SetTarget(c64187086.target)
e1:SetOperation(c64187086.activate)
c:RegisterEffect(e1)
end
function c64187086.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,e:GetHandler()) end
Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_COST+REASON_DISCARD)
end
function c64187086.filter1(c)
return c:IsSetCard(0x21) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand()
end
function c64187086.filter2(c)
return c:IsType(TYPE_FIELD) and c:IsAbleToHand()
end
function c64187086.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
if chk==0 then return Duel.IsExistingTarget(c64187086.filter1,tp,LOCATION_GRAVE,0,1,nil)
and Duel.IsExistingTarget(c64187086.filter2,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g1=Duel.SelectTarget(tp,c64187086.filter1,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g2=Duel.SelectTarget(tp,c64187086.filter2,tp,LOCATION_GRAVE,0,1,1,nil)
g1:Merge(g2)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g1,2,0,0)
end
function c64187086.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local sg=g:Filter(Card.IsRelateToEffect,nil,e)
if sg:GetCount()>0 then
Duel.SendtoHand(sg,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,sg)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c25290459.lua | 6 | 2028 | --レベルアップ!
function c25290459.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c25290459.cost)
e1:SetTarget(c25290459.target)
e1:SetOperation(c25290459.activate)
c:RegisterEffect(e1)
end
function c25290459.costfilter(c,e,tp)
if not c:IsSetCard(0x41) or not c:IsAbleToGraveAsCost() or not c:IsFaceup() then return false end
local code=c:GetCode()
local class=_G["c"..code]
if class==nil or class.lvupcount==nil then return false end
return Duel.IsExistingMatchingCard(c25290459.spfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil,class,e,tp)
end
function c25290459.spfilter(c,class,e,tp)
local code=c:GetCode()
for i=1,class.lvupcount do
if code==class.lvup[i] then return c:IsCanBeSpecialSummoned(e,0,tp,true,true) end
end
return false
end
function c25290459.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c25290459.costfilter,tp,LOCATION_MZONE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c25290459.costfilter,tp,LOCATION_MZONE,0,1,1,nil,e,tp)
Duel.SendtoGrave(g,REASON_COST)
e:SetLabel(g:GetFirst():GetCode())
end
function c25290459.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1 end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_DECK)
end
function c25290459.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local code=e:GetLabel()
local class=_G["c"..code]
if class==nil or class.lvupcount==nil then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c25290459.spfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil,class,e,tp)
local tc=g:GetFirst()
if tc then
Duel.SpecialSummon(tc,0,tp,tp,true,true,POS_FACEUP)
if tc:GetPreviousLocation()==LOCATION_DECK then Duel.ShuffleDeck(tp) end
end
end
| gpl-2.0 |
wvierber/hammerspoon | extensions/network/init.lua | 4 | 9882 | --- === hs.network ===
---
--- This module provides functions for inquiring about and monitoring changes to the network.
local USERDATA_TAG = "hs.network"
local module = {}
module.reachability = require(USERDATA_TAG..".reachability")
module.host = require(USERDATA_TAG..".host")
module.configuration = require(USERDATA_TAG..".configuration")
local inspect = require("hs.inspect")
local fnutils = require("hs.fnutils")
local log = require"hs.logger".new(USERDATA_TAG, require"hs.settings".get(USERDATA_TAG .. ".logLevel") or "error")
module.log = log
-- private variables and methods -----------------------------------------
-- Public interface ------------------------------------------------------
--- hs.network.interfaces() -> table
--- Function
--- Returns a list of interfaces currently active for the system.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A table containing a list of the interfaces active for the system. Logs an error and returns nil if there was a problem retrieving this information.
---
--- Notes:
--- * The names of the interfaces returned by this function correspond to the interface's BSD name, not the user defined name that shows up in the System Preferences's Network panel.
--- * This function returns *all* interfaces, even ones used by the system that are not directly manageable by the user.
module.interfaces = function()
local store = module.configuration.open()
if not store then
log.d("interfaces - unable to open system dynamic store")
return nil
end
local queryResult = store:contents("State:/Network/Interface")
local answer = queryResult and
queryResult["State:/Network/Interface"] and
queryResult["State:/Network/Interface"].Interfaces
if not answer then
log.df("interfaces - unexpected query results for State:/Network/Interface: %s", inspect(queryResult))
return nil
end
return answer
end
--- hs.network.interfaceDetails([interface | favorIPv6]) -> table
--- Function
--- Returns details about the specified interface or the primary interface if no interface is specified.
---
--- Parameters:
--- * interface - an optional string specifying the interface to retrieve details about. Defaults to the primary interface if not specified.
--- * favorIPv6 - an optional boolean specifying whether or not to prefer the primary IPv6 or the primary IPv4 interface if `interface` is not specified. Defaults to false.
---
--- Returns:
--- * A table containing key-value pairs describing interface details. Returns an empty table if no primary interface can be determined. Logs an error and returns nil if there was a problem retrieving this information.
---
--- Notes:
--- * When determining the primary interface, the `favorIPv6` flag only determines interface search order. If you specify true for this flag, but no primary IPv6 interface exists (i.e. your DHCP server only provides an IPv4 address an IPv6 is limited to local only traffic), then the primary IPv4 interface will be used instead.
module.interfaceDetails = function(interface)
if type(interface) == "boolean" then interface, favorIPv6 = nil, interface end
local store = module.configuration.open()
if not store then
log.d("interfaceDetails - unable to open system dynamic store")
return nil
end
if not interface then
local ipv4, ipv6 = module.primaryInterfaces()
interface = (favorIPv6 and ipv6 or ipv4) or (ipv4 or ipv6)
if not interface then
log.d("interfaceDetails - unable to determine a global primary IPv4 or IPv6 interface")
return nil
end
end
local prefix = "State:/Network/Interface/" .. interface .. "/"
local queryResult = store:contents(prefix .. ".*", true)
if not queryResult then
log.df("interfaceDetails - unexpected query results for State:/Network/Interface/%s/.*: %s", interface, inspect(queryResult))
return nil
end
local results = {}
for k, v in pairs(queryResult) do
local newK = k:match("^" .. prefix .. "(.*)$") or k
results[newK] = v
end
return results
end
--- hs.network.primaryInterfaces() -> ipv4Interface, ipv6Interface
--- Function
--- Returns the names of the primary IPv4 and IPv6 interfaces.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The name of the primary IPv4 interface or false if there isn't one, and the name of the IPv6 interface or false if there isn't one. Logs an error and returns a single nil if there was a problem retrieving this information.
---
--- Notes:
--- * The IPv4 and IPv6 interface names are often, but not always, the same.
module.primaryInterfaces = function()
local store = module.configuration.open()
if not store then
log.d("primaryInterfaces - unable to open system dynamic store")
return nil
end
local queryResult = store:contents("State:/Network/Global/IPv[46]", true)
if not queryResult then
log.df("primaryInterfaces - unexpected query results for State:/Network/Global/IPv[46]: %s", inspect(queryResult))
return nil
end
return
queryResult["State:/Network/Global/IPv4"] and queryResult["State:/Network/Global/IPv4"].PrimaryInterface or false,
queryResult["State:/Network/Global/IPv6"] and queryResult["State:/Network/Global/IPv6"].PrimaryInterface or false
end
--- hs.network.addresses([interface, ...]) -> table
--- Function
--- Returns a list of the IPv4 and IPv6 addresses for the specified interfaces, or all interfaces if no arguments are given.
---
--- Parameters:
--- * interface, ... - The interface names to return the IP addresses for. It should be specified as one of the following:
--- * one or more interface names, separated by a comma
--- * if the first argument is a table, it is assumes to be a table containing a list of interfaces and this list is used instead, ignoring any additional arguments that may be provided
--- * if no arguments are specified, then the results of [hs.network.interfaces](#interfaces) is used.
---
--- Returns:
--- * A table containing a list of the IP addresses for the interfaces as determined by the arguments provided.
---
--- Notes:
--- * The order of the IP addresses returned is undefined.
--- * If no arguments are provided, then this function returns the same results as `hs.host.addresses`, but does not block.
module.addresses = function(...)
local interfaces = table.pack(...)
if interfaces.n == 0 then interfaces = module.interfaces() end
if type(interfaces[1]) == "table" then interfaces = interfaces[1] end
local store = module.configuration.open()
if not store then
log.d("addresses - unable to open system dynamic store")
return nil
end
local queryResult = store:contents("State:/Network/Interface/.*/IPv[46]", true)
if not queryResult then
log.df("addresses - unexpected query results for State:/Network/Interface/.*/IPv[46]: %s", inspect(queryResult))
return nil
end
local results = {}
for k, v in pairs(queryResult) do
local intf, prot = k:match("^State:/Network/Interface/([^/]+)/(IPv[46])$")
if fnutils.contains(interfaces, intf) then
local suffix = (prot == "IPv6") and ("%" .. intf) or ""
for i2, v2 in ipairs(v.Addresses) do
table.insert(results, v2 .. suffix)
end
end
end
return results
end
--- hs.network.interfaceName([interface | favorIPv6]) -> string
--- Function
--- Returns the user defined name for the specified interface or the primary interface if no interface is specified.
--- * interface - an optional string specifying the interface to retrieve the name for. Defaults to the primary interface if not specified.
--- * favorIPv6 - an optional boolean specifying whether or not to prefer the primary IPv6 or the primary IPv4 interface if `interface` is not specified. Defaults to false.
---
--- Returns:
--- * A string containing the user defined name for the interface, if one exists, or false if the interface does not have a user defined name. Logs an error and returns nil if there was a problem retrieving this information.
---
--- Notes:
--- * Only interfaces which show up in the System Preferences Network panel will have a user defined name.
---
--- * When determining the primary interface, the `favorIPv6` flag only determines interface search order. If you specify true for this flag, but no primary IPv6 interface exists (i.e. your DHCP server only provides an IPv4 address an IPv6 is limited to local only traffic), then the primary IPv4 interface will be used instead.
module.interfaceName = function(interface, favorIPv6)
if type(interface) == "boolean" then interface, favorIPv6 = nil, interface end
local store = module.configuration.open()
if not store then
log.d("interfaceName - unable to open system dynamic store")
return nil
end
if not interface then
local ipv4, ipv6 = module.primaryInterfaces()
interface = (favorIPv6 and ipv6 or ipv4) or (ipv4 or ipv6)
if not interface then
log.d("interfaceName - unable to determine a global primary IPv4 or IPv6 interface")
return nil
end
end
local queryResult = store:contents("Setup:/Network/Service/.*/Interface", true)
if not queryResult then
log.df("interfaceName - unexpected query results for Setup:/Network/Service/.*/Interface: %s", inspect(queryResult))
return nil
end
local results = {}
for k, v in pairs(queryResult) do
if v.DeviceName == interface then return v.UserDefinedName end
end
return false
end
-- Return Module Object --------------------------------------------------
return module
| mit |
anshkumar/yugioh-glaze | assets/script/c73625877.lua | 9 | 2014 | --タイム・エスケーパー
function c73625877.initial_effect(c)
--remove
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(73625877,0))
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCategory(CATEGORY_REMOVE)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetRange(LOCATION_HAND)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c73625877.rmcost)
e1:SetTarget(c73625877.rmtg)
e1:SetOperation(c73625877.rmop)
c:RegisterEffect(e1)
end
function c73625877.rmcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsDiscardable() end
Duel.SendtoGrave(e:GetHandler(),REASON_COST+REASON_DISCARD)
end
function c73625877.filter(c)
return c:IsFaceup() and c:IsRace(RACE_PSYCHO) and c:IsAbleToRemove()
end
function c73625877.rmtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c73625877.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c73625877.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,c73625877.filter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0)
end
function c73625877.rmop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
if Duel.Remove(tc,0,REASON_EFFECT+REASON_TEMPORARY)==0 then return end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetCountLimit(1)
e1:SetLabelObject(tc)
e1:SetCondition(c73625877.retcon)
e1:SetOperation(c73625877.retop)
if Duel.GetTurnPlayer()==tp and Duel.GetCurrentPhase()==PHASE_DRAW then
e1:SetLabel(0)
else
e1:SetLabel(Duel.GetTurnCount())
end
Duel.RegisterEffect(e1,tp)
end
end
function c73625877.retcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp and Duel.GetTurnCount()~=e:GetLabel()
end
function c73625877.retop(e,tp,eg,ep,ev,re,r,rp)
Duel.ReturnToField(e:GetLabelObject())
e:Reset()
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c89258906.lua | 3 | 1424 | --BF-そよ風のブリーズ
function c89258906.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(89258906,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_TO_HAND)
e1:SetCondition(c89258906.condition)
e1:SetTarget(c89258906.target)
e1:SetOperation(c89258906.operation)
c:RegisterEffect(e1)
--synchro limit
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e2:SetValue(c89258906.synlimit)
c:RegisterEffect(e2)
end
function c89258906.synlimit(e,c)
if not c then return false end
return not c:IsSetCard(0x33)
end
function c89258906.condition(e,tp,eg,ep,ev,re,r,rp)
return bit.band(r,REASON_EFFECT)~=0 and e:GetHandler():IsPreviousLocation(LOCATION_DECK)
end
function c89258906.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsRelateToEffect(e) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c89258906.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
bshillingford/optim | lbfgs.lua | 5 | 9025 | --[[ An implementation of L-BFGS, heavily inspired by minFunc (Mark Schmidt)
This implementation of L-BFGS relies on a user-provided line
search function (state.lineSearch). If this function is not
provided, then a simple learningRate is used to produce fixed
size steps. Fixed size steps are much less costly than line
searches, and can be useful for stochastic problems.
The learning rate is used even when a line search is provided.
This is also useful for large-scale stochastic problems, where
opfunc is a noisy approximation of f(x). In that case, the learning
rate allows a reduction of confidence in the step size.
ARGS:
- `opfunc` : a function that takes a single input (X), the point of
evaluation, and returns f(X) and df/dX
- `x` : the initial point
- `state` : a table describing the state of the optimizer; after each
call the state is modified
- `state.maxIter` : Maximum number of iterations allowed
- `state.maxEval` : Maximum number of function evaluations
- `state.tolFun` : Termination tolerance on the first-order optimality
- `state.tolX` : Termination tol on progress in terms of func/param changes
- `state.lineSearch` : A line search function
- `state.learningRate` : If no line search provided, then a fixed step size is used
RETURN:
- `x*` : the new `x` vector, at the optimal point
- `f` : a table of all function values:
`f[1]` is the value of the function before any optimization and
`f[#f]` is the final fully optimized value, at `x*`
(Clement Farabet, 2012)
]]
function optim.lbfgs(opfunc, x, config, state)
-- get/update state
local config = config or {}
local state = state or config
local maxIter = tonumber(config.maxIter) or 20
local maxEval = tonumber(config.maxEval) or maxIter*1.25
local tolFun = config.tolFun or 1e-5
local tolX = config.tolX or 1e-9
local nCorrection = config.nCorrection or 100
local lineSearch = config.lineSearch
local lineSearchOpts = config.lineSearchOptions
local learningRate = config.learningRate or 1
local isverbose = config.verbose or false
state.funcEval = state.funcEval or 0
state.nIter = state.nIter or 0
-- verbose function
local verbose
if isverbose then
verbose = function(...) print('<optim.lbfgs> ', ...) end
else
verbose = function() end
end
-- import some functions
local abs = math.abs
local min = math.min
-- evaluate initial f(x) and df/dx
local f,g = opfunc(x)
local f_hist = {f}
local currentFuncEval = 1
state.funcEval = state.funcEval + 1
local p = g:size(1)
-- check optimality of initial point
state.tmp1 = state.tmp1 or g.new(g:size()):zero(); local tmp1 = state.tmp1
tmp1:copy(g):abs()
if tmp1:sum() <= tolFun then
-- optimality condition below tolFun
verbose('optimality condition below tolFun')
return x,f_hist
end
if not state.dir_bufs then
-- reusable buffers for y's and s's, and their histories
verbose('creating recyclable direction/step/history buffers')
state.dir_bufs = state.dir_bufs or g.new(nCorrection+1, p):split(1)
state.stp_bufs = state.stp_bufs or g.new(nCorrection+1, p):split(1)
for i=1,#state.dir_bufs do
state.dir_bufs[i] = state.dir_bufs[i]:squeeze(1)
state.stp_bufs[i] = state.stp_bufs[i]:squeeze(1)
end
end
-- variables cached in state (for tracing)
local d = state.d
local t = state.t
local old_dirs = state.old_dirs
local old_stps = state.old_stps
local Hdiag = state.Hdiag
local g_old = state.g_old
local f_old = state.f_old
-- optimize for a max of maxIter iterations
local nIter = 0
while nIter < maxIter do
-- keep track of nb of iterations
nIter = nIter + 1
state.nIter = state.nIter + 1
------------------------------------------------------------
-- compute gradient descent direction
------------------------------------------------------------
if state.nIter == 1 then
d = g:clone():mul(-1) -- -g
old_dirs = {}
old_stps = {}
Hdiag = 1
else
-- do lbfgs update (update memory)
local y = table.remove(state.dir_bufs) -- pop
local s = table.remove(state.stp_bufs)
y:add(g, -1, g_old) -- g - g_old
s:mul(d, t) -- d*t
local ys = y:dot(s) -- y*s
if ys > 1e-10 then
-- updating memory
if #old_dirs == nCorrection then
-- shift history by one (limited-memory)
local removed1 = table.remove(old_dirs, 1)
local removed2 = table.remove(old_stps, 1)
table.insert(state.dir_bufs, removed1)
table.insert(state.stp_bufs, removed2)
end
-- store new direction/step
table.insert(old_dirs, s)
table.insert(old_stps, y)
-- update scale of initial Hessian approximation
Hdiag = ys / y:dot(y) -- (y*y)
else
-- put y and s back into the buffer pool
table.insert(state.dir_bufs, y)
table.insert(state.stp_bufs, s)
end
-- compute the approximate (L-BFGS) inverse Hessian
-- multiplied by the gradient
local k = #old_dirs
-- need to be accessed element-by-element, so don't re-type tensor:
state.ro = state.ro or torch.Tensor(nCorrection); local ro = state.ro
for i = 1,k do
ro[i] = 1 / old_stps[i]:dot(old_dirs[i])
end
-- iteration in L-BFGS loop collapsed to use just one buffer
local q = tmp1 -- reuse tmp1 for the q buffer
-- need to be accessed element-by-element, so don't re-type tensor:
state.al = state.al or torch.zeros(nCorrection) local al = state.al
q:mul(g, -1) -- -g
for i = k,1,-1 do
al[i] = old_dirs[i]:dot(q) * ro[i]
q:add(-al[i], old_stps[i])
end
-- multiply by initial Hessian
r = d -- share the same buffer, since we don't need the old d
r:mul(q, Hdiag) -- q[1] * Hdiag
for i = 1,k do
local be_i = old_stps[i]:dot(r) * ro[i]
r:add(al[i]-be_i, old_dirs[i])
end
-- final direction is in r/d (same object)
end
g_old = g_old or g:clone()
g_old:copy(g)
f_old = f
------------------------------------------------------------
-- compute step length
------------------------------------------------------------
-- directional derivative
local gtd = g:dot(d) -- g * d
-- check that progress can be made along that direction
if gtd > -tolX then
break
end
-- reset initial guess for step size
if state.nIter == 1 then
tmp1:copy(g):abs()
t = min(1,1/tmp1:sum()) * learningRate
else
t = learningRate
end
-- optional line search: user function
local lsFuncEval = 0
if lineSearch and type(lineSearch) == 'function' then
-- perform line search, using user function
f,g,x,t,lsFuncEval = lineSearch(opfunc,x,t,d,f,g,gtd,lineSearchOpts)
table.insert(f_hist, f)
else
-- no line search, simply move with fixed-step
x:add(t,d)
if nIter ~= maxIter then
-- re-evaluate function only if not in last iteration
-- the reason we do this: in a stochastic setting,
-- no use to re-evaluate that function here
f,g = opfunc(x)
lsFuncEval = 1
table.insert(f_hist, f)
end
end
-- update func eval
currentFuncEval = currentFuncEval + lsFuncEval
state.funcEval = state.funcEval + lsFuncEval
------------------------------------------------------------
-- check conditions
------------------------------------------------------------
if nIter == maxIter then
-- no use to run tests
verbose('reached max number of iterations')
break
end
if currentFuncEval >= maxEval then
-- max nb of function evals
verbose('max nb of function evals')
break
end
tmp1:copy(g):abs()
if tmp1:sum() <= tolFun then
-- check optimality
verbose('optimality condition below tolFun')
break
end
tmp1:copy(d):mul(t):abs()
if tmp1:sum() <= tolX then
-- step size below tolX
verbose('step size below tolX')
break
end
if abs(f-f_old) < tolX then
-- function value changing less than tolX
verbose('function value changing less than tolX')
break
end
end
-- save state
state.old_dirs = old_dirs
state.old_stps = old_stps
state.Hdiag = Hdiag
state.g_old = g_old
state.f_old = f_old
state.t = t
state.d = d
-- return optimal x, and history of f(x)
return x,f_hist,currentFuncEval
end
| bsd-3-clause |
anshkumar/yugioh-glaze | assets/script/c706925.lua | 3 | 2460 | --海皇の狙撃兵
function c706925.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(706925,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetCode(EVENT_BATTLE_DAMAGE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCondition(c706925.spcon)
e1:SetTarget(c706925.sptg)
e1:SetOperation(c706925.spop)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(706925,1))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetCondition(c706925.descon)
e2:SetTarget(c706925.destg)
e2:SetOperation(c706925.desop)
c:RegisterEffect(e2)
end
function c706925.spcon(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp
end
function c706925.spfilter(c,e,tp)
return not c:IsCode(706925) and c:IsLevelBelow(4) and c:IsSetCard(0x77) and c:IsRace(RACE_SEASERPENT)
and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c706925.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c706925.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c706925.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c706925.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function c706925.descon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_COST) and re:IsHasType(0x7e0) and re:IsActiveType(TYPE_MONSTER)
and re:GetHandler():IsAttribute(ATTRIBUTE_WATER)
end
function c706925.desfilter(c)
return c:IsFacedown() and c:IsDestructable()
end
function c706925.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsControler(1-tp) and c706925.desfilter(chkc) end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c706925.desfilter,tp,0,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c706925.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) and tc:IsFacedown() then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
zwhfly/openwrt-luci | modules/admin-mini/luasrc/model/cbi/mini/network.lua | 82 | 6273 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local wa = require "luci.tools.webadmin"
local sys = require "luci.sys"
local fs = require "nixio.fs"
local has_pptp = fs.access("/usr/sbin/pptp")
local has_pppoe = fs.glob("/usr/lib/pppd/*/rp-pppoe.so")()
local network = luci.model.uci.cursor_state():get_all("network")
local netstat = sys.net.deviceinfo()
local ifaces = {}
for k, v in pairs(network) do
if v[".type"] == "interface" and k ~= "loopback" then
table.insert(ifaces, v)
end
end
m = Map("network", translate("Network"))
s = m:section(Table, ifaces, translate("Status"))
s.parse = function() end
s:option(DummyValue, ".name", translate("Network"))
hwaddr = s:option(DummyValue, "_hwaddr",
translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"), translate("Hardware Address"))
function hwaddr.cfgvalue(self, section)
local ix = self.map:get(section, "ifname") or ""
local mac = fs.readfile("/sys/class/net/" .. ix .. "/address")
if not mac then
mac = luci.util.exec("ifconfig " .. ix)
mac = mac and mac:match(" ([A-F0-9:]+)%s*\n")
end
if mac and #mac > 0 then
return mac:upper()
end
return "?"
end
s:option(DummyValue, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address"))
s:option(DummyValue, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"))
txrx = s:option(DummyValue, "_txrx",
translate("Traffic"), translate("transmitted / received"))
function txrx.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][1]
rx = rx and wa.byte_format(tonumber(rx)) or "-"
local tx = netstat and netstat[ix] and netstat[ix][9]
tx = tx and wa.byte_format(tonumber(tx)) or "-"
return string.format("%s / %s", tx, rx)
end
errors = s:option(DummyValue, "_err",
translate("Errors"), translate("TX / RX"))
function errors.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][3]
local tx = netstat and netstat[ix] and netstat[ix][11]
rx = rx and tostring(rx) or "-"
tx = tx and tostring(tx) or "-"
return string.format("%s / %s", tx, rx)
end
s = m:section(NamedSection, "lan", "interface", translate("Local Network"))
s.addremove = false
s:option(Value, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address"))
nm = s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"))
nm:value("255.255.255.0")
nm:value("255.255.0.0")
nm:value("255.0.0.0")
gw = s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway") .. translate(" (optional)"))
gw.rmempty = true
dns = s:option(Value, "dns", translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server") .. translate(" (optional)"))
dns.rmempty = true
s = m:section(NamedSection, "wan", "interface", translate("Internet Connection"))
s.addremove = false
p = s:option(ListValue, "proto", translate("Protocol"))
p.override_values = true
p:value("none", "disabled")
p:value("static", translate("manual"))
p:value("dhcp", translate("automatic"))
if has_pppoe then p:value("pppoe", "PPPoE") end
if has_pptp then p:value("pptp", "PPTP") end
function p.write(self, section, value)
-- Always set defaultroute to PPP and use remote dns
-- Overwrite a bad variable behaviour in OpenWrt
if value == "pptp" or value == "pppoe" then
self.map:set(section, "peerdns", "1")
self.map:set(section, "defaultroute", "1")
end
return ListValue.write(self, section, value)
end
if not ( has_pppoe and has_pptp ) then
p.description = translate("You need to install \"ppp-mod-pppoe\" for PPPoE or \"pptp\" for PPtP support")
end
ip = s:option(Value, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address"))
ip:depends("proto", "static")
nm = s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"))
nm:depends("proto", "static")
gw = s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway"))
gw:depends("proto", "static")
gw.rmempty = true
dns = s:option(Value, "dns", translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server"))
dns:depends("proto", "static")
dns.rmempty = true
usr = s:option(Value, "username", translate("Username"))
usr:depends("proto", "pppoe")
usr:depends("proto", "pptp")
pwd = s:option(Value, "password", translate("Password"))
pwd.password = true
pwd:depends("proto", "pppoe")
pwd:depends("proto", "pptp")
-- Allow user to set MSS correction here if the UCI firewall is installed
-- This cures some cancer for providers with pre-war routers
if fs.access("/etc/config/firewall") then
mssfix = s:option(Flag, "_mssfix",
translate("Clamp Segment Size"), translate("Fixes problems with unreachable websites, submitting forms or other unexpected behaviour for some ISPs."))
mssfix.rmempty = false
function mssfix.cfgvalue(self)
local value
m.uci:foreach("firewall", "forwarding", function(s)
if s.src == "lan" and s.dest == "wan" then
value = s.mtu_fix
end
end)
return value
end
function mssfix.write(self, section, value)
m.uci:foreach("firewall", "forwarding", function(s)
if s.src == "lan" and s.dest == "wan" then
m.uci:set("firewall", s[".name"], "mtu_fix", value)
m:chain("firewall")
end
end)
end
end
kea = s:option(Flag, "keepalive", translate("automatically reconnect"))
kea:depends("proto", "pppoe")
kea:depends("proto", "pptp")
kea.rmempty = true
kea.enabled = "10"
cod = s:option(Value, "demand", translate("disconnect when idle for"), "s")
cod:depends("proto", "pppoe")
cod:depends("proto", "pptp")
cod.rmempty = true
srv = s:option(Value, "server", translate("<abbr title=\"Point-to-Point Tunneling Protocol\">PPTP</abbr>-Server"))
srv:depends("proto", "pptp")
srv.rmempty = true
return m
| apache-2.0 |
anshkumar/yugioh-glaze | assets/script/c85255550.lua | 3 | 1252 | --異国の剣士
function c85255550.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(85255550,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_DAMAGE_STEP_END)
e1:SetCondition(c85255550.condition)
e1:SetOperation(c85255550.operation)
c:RegisterEffect(e1)
end
function c85255550.condition(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local bc=c:GetBattleTarget()
return c==Duel.GetAttacker() and bc and bc:IsRelateToBattle() and bc:IsFaceup()
end
function c85255550.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local bc=c:GetBattleTarget()
if bc:IsRelateToBattle() then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_MZONE)
e1:SetReset(RESET_EVENT+0x1fe0000)
e1:SetOperation(c85255550.desop)
e1:SetLabel(0)
e1:SetOwnerPlayer(tp)
bc:RegisterEffect(e1)
end
end
function c85255550.desop(e,tp,eg,ep,ev,re,r,rp)
local ct=e:GetLabel()
ct=ct+1
e:SetLabel(ct)
e:GetOwner():SetTurnCounter(ct)
if ct==5 then
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
end
| gpl-2.0 |
freifunk-gluon/luci | modules/admin-full/luasrc/controller/admin/index.lua | 79 | 1245 | --[[
LuCI - Lua Configuration Interface
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
$Id$
]]--
module("luci.controller.admin.index", package.seeall)
function index()
local root = node()
if not root.target then
root.target = alias("admin")
root.index = true
end
local page = node("admin")
page.target = firstchild()
page.title = _("Administration")
page.order = 10
page.sysauth = "root"
page.sysauth_authenticator = "htmlauth"
page.ucidata = true
page.index = true
-- Empty services menu to be populated by addons
entry({"admin", "services"}, firstchild(), _("Services"), 40).index = true
entry({"admin", "logout"}, call("action_logout"), _("Logout"), 90)
end
function action_logout()
local dsp = require "luci.dispatcher"
local sauth = require "luci.sauth"
if dsp.context.authsession then
sauth.kill(dsp.context.authsession)
dsp.context.urltoken.stok = nil
end
luci.http.header("Set-Cookie", "sysauth=; path=" .. dsp.build_url())
luci.http.redirect(luci.dispatcher.build_url())
end
| apache-2.0 |
anshkumar/yugioh-glaze | assets/script/c85893201.lua | 3 | 1626 | --連鎖誘爆
function c85893201.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(85893201,0))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetRange(LOCATION_SZONE)
e2:SetCode(EVENT_DESTROYED)
e2:SetCountLimit(1)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e2:SetCondition(c85893201.descon)
e2:SetTarget(c85893201.destg)
e2:SetOperation(c85893201.desop)
c:RegisterEffect(e2)
end
function c85893201.cfilter(c,tp)
return c:IsPreviousLocation(LOCATION_MZONE) and c:IsReason(REASON_EFFECT) and c:GetPreviousControler()==tp
end
function c85893201.descon(e,tp,eg,ep,ev,re,r,rp)
return rp~=tp and eg:IsExists(c85893201.cfilter,1,nil,1-tp)
end
function c85893201.filter(c)
return c:IsDestructable()
end
function c85893201.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and c85893201.filter(chkc) end
if chk==0 then return e:GetHandler():IsRelateToEffect(e)
and Duel.IsExistingTarget(c85893201.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c85893201.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c85893201.desop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
astog/cqui | Assets/UI/Panels/unitpanel.lua | 4 | 158744 | -- ===========================================================================
-- Unit Panel Screen
-- ===========================================================================
include( "InstanceManager" );
include( "SupportFunctions" );
include( "Colors" );
include( "CombatInfo" );
include( "PopupDialogSupport" );
include( "Civ6Common" );
include( "EspionageSupport" );
-- ===========================================================================
-- CONSTANTS
-- ===========================================================================
local ANIMATION_SPEED :number = 2;
local SECONDARY_ACTIONS_ART_PADDING :number = -4;
local MAX_BEFORE_TRUNC_STAT_NAME :number = 170;
-- ===========================================================================
-- MEMBERS / VARIABLES
-- ===========================================================================
hstructure DisabledByTutorial
kLockedHashes : table; -- Action hashes that the tutorial says shouldn't be enabled.
end
local m_standardActionsIM :table = InstanceManager:new( "UnitActionInstance", "UnitActionButton", Controls.StandardActionsStack );
local m_secondaryActionsIM :table = InstanceManager:new( "UnitActionInstance", "UnitActionButton", Controls.SecondaryActionsStack );
local m_groupArtIM :table = InstanceManager:new( "GroupArtInstance", "Top", Controls.PrimaryArtStack );
local m_buildActionsIM :table = InstanceManager:new( "BuildActionsColumnInstance", "Top", Controls.BuildActionsStack );
local m_earnedPromotionIM :table = InstanceManager:new( "EarnedPromotionInstance", "Top", Controls.EarnedPromotionsStack);
local m_PromotionListInstanceMgr:table = InstanceManager:new( "PromotionSelectionInstance", "PromotionSelection", Controls.PromotionList );
local m_subjectModifierIM :table = InstanceManager:new( "ModifierInstance", "ModifierContainer", Controls.SubjectModifierStack );
local m_targetModifierIM :table = InstanceManager:new( "ModifierInstance", "ModifierContainer", Controls.TargetModifierStack );
local m_interceptorModifierIM :table = InstanceManager:new( "ModifierInstance", "ModifierContainer", Controls.InterceptorModifierStack );
local m_antiAirModifierIM :table = InstanceManager:new( "ModifierInstance", "ModifierContainer", Controls.AntiAirModifierStack );
local m_subjectStatStackIM :table = InstanceManager:new( "StatInstance", "StatGrid", Controls.SubjectStatStack );
local m_targetStatStackIM :table = InstanceManager:new( "TargetStatInstance", "StatGrid", Controls.TargetStatStack );
local m_combatResults :table = nil;
local m_currentIconGroup :table = nil; -- Tracks the current icon group as they are built.
local m_isOkayToProcess :boolean= true;
local m_selectedPlayerId :number = -1;
local m_primaryColor :number = 0xdeadbeef;
local m_secondaryColor :number = 0xbaadf00d;
local m_UnitId :number = -1;
local m_numIconsInCurrentIconGroup :number = 0;
local m_bestValidImprovement :number = -1;
local m_kHotkeyActions :table = {};
local m_kHotkeyCV1 :table = {};
local m_kHotkeyCV2 :table = {};
local m_kSoundCV1 :table = {};
local m_kTutorialDisabled :table = {}; -- key = Unit Type, value = lockedHashes
local m_kTutorialAllDisabled :table = {}; -- hashes of actions disabled for all units
local m_attackerUnit = nil;
local m_locX = nil;
local m_locY = nil;
local INVALID_PLOT_ID :number = -1;
local m_plotId :number = INVALID_PLOT_ID;
local m_kPopupDialog :table;
local m_targetData :table;
local m_subjectData :table;
-- Defines the number of modifiers displayed per page in the combat preview
local m_maxModifiersPerPage :number = 5;
-- Defines the minimum unit panel size and resize padding used when resizing unit panel to fit action buttons
local m_minUnitPanelWidth :number = 340;
local m_resizeUnitPanelPadding :number = 18;
local pSpyInfo = GameInfo.Units["UNIT_SPY"];
local m_AttackHotkeyId = Input.GetActionId("Attack");
local m_DeleteHotkeyId = Input.GetActionId("DeleteUnit");
-- ===========================================================================
-- FUNCTIONS
-- ===========================================================================
function InitSubjectData()
m_subjectData =
{
Name = "",
Moves = 0,
InFormation = 0,
FormationMoves = 0,
FormationMaxMoves = 0,
MaxMoves = 0,
Combat = 0,
Damage = 0,
MaxDamage = 0,
PotentialDamage = 0,
WallDamage = 0,
MaxWallDamage = 0,
PotentialWallDamage = 0,
RangedCombat = 0,
BombardCombat = 0,
AntiAirCombat = 0,
Range = 0,
Owner = 0,
BuildCharges = 0,
SpreadCharges = 0,
GreatPersonActionCharges = 0,
GreatPersonPassiveName = "",
GreatPersonPassiveText = "",
ReligiousStrength = 0,
HasMovedIntoZOC = 0,
MilitaryFormation = 0,
UnitType = -1,
UnitID = 0,
UnitExperience = 0,
MaxExperience = 0,
UnitLevel = 0,
CurrentPromotions = {},
Actions = {},
IsSpy = false,
SpyOperation = -1,
SpyTargetOwnerID = -1,
SpyTargetCityName = "",
SpyRemainingTurns = 0,
SpyTotalTurns = 0,
StatData = nil,
IsTradeUnit = false,
TradeRouteName = "",
TradeRouteIcon = "",
TradeLandRange = 0,
TradeSeaRange = 0,
IsSettler = false;
};
end
function InitTargetData()
m_targetData =
{
Name = "",
Combat = 0,
RangedCombat = 0,
BombardCombat = 0,
ReligiousCombat = 0,
Range = 0,
Damage = 0,
MaxDamage = 0,
PotentialDamage = 0,
WallDamage = 0,
MaxWallDamage = 0,
PotentialWallDamage = 0,
BuildCharges = 0,
SpreadCharges = 0,
ReligiousStrength = 0,
GreatPersonActionCharges = 0,
Moves = 0,
MaxMoves = 0,
InterceptorName = "",
InterceptorCombat = 0,
InterceptorDamage = 0,
InterceptorMaxDamage = 0,
InterceptorPotentialDamage = 0,
AntiAirName = "",
AntiAirCombat = 0,
StatData = nil;
UnitType = -1,
UnitID = 0,
};
end
-- ===========================================================================
-- An action icon which will shows up immediately above the unit panel
-- ===========================================================================
function AddActionButton( instance:table, action:table )
instance.UnitActionIcon:SetIcon(action.IconId);
instance.UnitActionButton:SetDisabled( action.Disabled );
instance.UnitActionButton:SetAlpha( (action.Disabled and 0.7) or 1 );
instance.UnitActionButton:SetToolTipString( action.helpString );
instance.UnitActionButton:RegisterCallback( Mouse.eLClick,
function(void1,void2)
if action.Sound ~= nil and action.Sound ~= "" then
UI.PlaySound(action.Sound);
end
action.CallbackFunc(void1,void2);
end
);
instance.UnitActionButton:SetVoid1( action.CallbackVoid1 );
instance.UnitActionButton:SetVoid2( action.CallbackVoid2 );
instance.UnitActionButton:SetTag( action.userTag );
instance.UnitActionButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end);
-- Track # of icons added for whatever is the current group
m_numIconsInCurrentIconGroup = m_numIconsInCurrentIconGroup + 1;
end
-- ===========================================================================
function GetHashFromType( actionType:string )
local hash:number = 0;
if GameInfo.UnitCommands[actionType] ~= nil then
hash = GameInfo.UnitCommands[actionType].Hash;
elseif GameInfo.UnitOperations[actionType] ~= nil then
hash = GameInfo.UnitOperations[actionType].Hash;
end
return hash;
end
-- ===========================================================================
-- RETURNS true if tutorial is disabling this action.
-- ===========================================================================
function IsDisabledByTutorial( unitType:string, actionHash:number )
-- Any type of unit
for i,action in ipairs( m_kTutorialAllDisabled ) do
hash = GetHashFromType(action);
if actionHash == hash and hash ~= 0 then
return true;
end
end
-- Specific to a unit
if m_kTutorialDisabled[unitType] ~= nil then
-- In mode where all are enabled except for specific list
for i,hash in ipairs( m_kTutorialDisabled[unitType].kLockedHashes ) do
if actionHash == hash then
return true;
end
end
end
return false;
end
-- ===========================================================================
-- Add an action for the UI to display.
-- actionsTable Table holding actions via categories
-- action A command or operation
-- disabled Is the action disabled (tutorial may disable even if enabled)
-- toolTipString What the action does
-- actionHash The hash of the action.
-- ===========================================================================
function AddActionToTable( actionsTable:table, action:table, disabled:boolean, toolTipString:string, actionHash:number, callbackFunc:ifunction, callbackVoid1, callbackVoid2, overrideIcon:string)
local actionsCategoryTable:table;
if ( actionsTable[action.CategoryInUI] ~= nil ) then
actionsCategoryTable = actionsTable[action.CategoryInUI];
else
UI.DataError("Operation is in unsupported action category '" .. tostring(action.CategoryInUI) .. "'.");
actionsCategoryTable = actionsTable["SPECIFIC"];
end
-- Wrap every callback function with a call that guarantees the interface
-- mode is reset. It prevents issues such as selecting range attack and
-- then instead of attacking, choosing another action, which would leave
-- up the range attack lens layer.
local wrappedCallback:ifunction =
function(void1,void2)
if UI.GetInterfaceMode() ~= InterfaceModeTypes.SELECTION then
print("Unit panel forcing interface mode back to selection before performing operation/action"); --Debug
UI.SetInterfaceMode( InterfaceModeTypes.SELECTION );
end
callbackFunc(void1,void2);
end;
table.insert( actionsCategoryTable, {
IconId = (overrideIcon and overrideIcon) or action.Icon,
Disabled = disabled,
helpString = toolTipString,
userTag = actionHash,
CallbackFunc = wrappedCallback,
CallbackVoid1 = callbackVoid1,
CallbackVoid2 = callbackVoid2,
IsBestImprovement = action.IsBestImprovement,
Sound = action.Sound
});
-- Hotkey support
if (action.HotkeyId~=nil) and disabled==false then
local actionId = Input.GetActionId( action.HotkeyId );
if actionId ~= nil then
m_kHotkeyActions[actionId] = callbackFunc;
m_kHotkeyCV1[actionId] = callbackVoid1;
m_kHotkeyCV2[actionId] = callbackVoid2;
m_kSoundCV1[actionId] = action.Sound;
else
UI.DataError("Cannot set hotkey on Unitpanel for action with icon '"..action.IconId.."' because engine doesn't have actionId of '"..action.HotkeyId.."'.");
end
end
end
-- ===========================================================================
-- Refresh unit actions
-- Returns a table of unit actions.
-- ===========================================================================
function GetUnitActionsTable( pUnit )
-- Build action table; holds sub-tables of commands & operations based on UI categories set in DB.
-- Also defines order actions show in panel.
local actionsTable = {
ATTACK = {},
BUILD = {},
GAMEMODIFY = {},
MOVE = {},
OFFENSIVESPY = {},
INPLACE = {},
SECONDARY = {},
SPECIFIC = {},
displayOrder = {
primaryArea = {"ATTACK","OFFENSIVESPY","SPECIFIC","MOVE","INPLACE","GAMEMODIFY"}, -- How they appear in the UI
secondaryArea = {"SECONDARY"}
}
};
m_bestValidImprovement = -1;
if pUnit == nil then
UI.DataError("NIL unit when attempting to get action table.");
return;
end
local unitType :string = GameInfo.Units[pUnit:GetUnitType()].UnitType;
for commandRow in GameInfo.UnitCommands() do
if ( commandRow.VisibleInUI ) then
local actionHash :number = commandRow.Hash;
local isDisabled :boolean = IsDisabledByTutorial(unitType, actionHash );
if (actionHash == UnitCommandTypes.ENTER_FORMATION) then
--Check if there are any units in the same tile that this unit can create a formation with
--Call CanStartCommand asking for results
local bCanStart, tResults = UnitManager.CanStartCommand( pUnit, actionHash, nil, true);
if (bCanStart and tResults) then
if (tResults[UnitCommandResults.UNITS] ~= nil and #tResults[UnitCommandResults.UNITS] ~= 0) then
local tUnits = tResults[UnitCommandResults.UNITS];
for i, unit in ipairs(tUnits) do
local pUnitInstance = Players[unit.player]:GetUnits():FindID(unit.id);
if (pUnitInstance ~= nil) then
local toolTipString :string = Locale.Lookup(commandRow.Description, GameInfo.Units[pUnitInstance:GetUnitType()].Name);
local callback :ifunction = function() OnUnitActionClicked_EnterFormation(pUnitInstance) end
AddActionToTable( actionsTable, commandRow, isDisabled, toolTipString, actionHash, callback );
end
end
end
end
elseif (actionHash == UnitCommandTypes.PROMOTE) then
--Call CanStartCommand asking for a list of possible promotions for that unit
local bCanStart, tResults = UnitManager.CanStartCommand( pUnit, actionHash, true, true);
if (bCanStart and tResults) then
if (tResults[UnitCommandResults.PROMOTIONS] ~= nil and #tResults[UnitCommandResults.PROMOTIONS] ~= 0) then
local tPromotions = tResults[UnitCommandResults.PROMOTIONS];
local toolTipString = Locale.Lookup(commandRow.Description);
local callback = function() ShowPromotionsList(tPromotions); end
AddActionToTable( actionsTable, commandRow, isDisabled, toolTipString, actionHash, callback );
end
end
elseif (actionHash == UnitCommandTypes.NAME_UNIT) then
local bCanStart = UnitManager.CanStartCommand( pUnit, UnitCommandTypes.NAME_UNIT, true);
if (bCanStart) then
local toolTipString = Locale.Lookup(commandRow.Description);
AddActionToTable( actionsTable, commandRow, isDisabled, toolTipString, actionHash, OnNameUnit );
end
elseif (actionHash == UnitCommandTypes.DELETE) then
local bCanStart = UnitManager.CanStartCommand( pUnit, UnitCommandTypes.DELETE, true);
if (bCanStart) then
local toolTipString = Locale.Lookup(commandRow.Description);
AddActionToTable( actionsTable, commandRow, isDisabled, toolTipString, actionHash, OnPromptToDeleteUnit );
end
elseif (actionHash == UnitCommandTypes.CANCEL and GameInfo.Units[unitType].Spy) then
-- Route the cancel action for spies to the espionage popup for cancelling a mission
local bCanStart = UnitManager.CanStartCommand( pUnit, actionHash, true);
if (bCanStart) then
local bCanStartNow, tResults = UnitManager.CanStartCommand( pUnit, actionHash, false, true);
AddActionToTable( actionsTable, commandRow, isDisabled, Locale.Lookup("LOC_UNITPANEL_ESPIONAGE_CANCEL_MISSION"), actionHash, OnUnitActionClicked_CancelSpyMission, UnitCommandTypes.TYPE, actionHash );
end
else
if (actionHash == UnitCommandTypes.AIRLIFT) then
local foo = true;
end
-- The UI check of an operation is a loose check where it only fails if the unit could never do the command.
local bCanStart = UnitManager.CanStartCommand( pUnit, actionHash, true);
if (bCanStart) then
-- Check again if the operation can occur, this time for real.
local bCanStartNow, tResults = UnitManager.CanStartCommand( pUnit, actionHash, false, true);
local bDisabled = not bCanStartNow;
local toolTipString:string;
if (actionHash == UnitCommandTypes.UPGRADE) then
-- if it's a unit upgrade action, add the unit it will upgrade to in the tooltip as well as the upgrade cost
if (tResults ~= nil) then
if (tResults[UnitCommandResults.UNIT_TYPE] ~= nil) then
local upgradeUnitName = GameInfo.Units[tResults[UnitCommandResults.UNIT_TYPE]].Name;
toolTipString = Locale.Lookup(upgradeUnitName);
local upgradeCost = pUnit:GetUpgradeCost();
if (upgradeCost ~= nil) then
toolTipString = toolTipString .. ": " .. upgradeCost .. " " .. Locale.Lookup("LOC_TOP_PANEL_GOLD");
end
toolTipString = Locale.Lookup("LOC_UNITOPERATION_UPGRADE_INFO", upgradeUnitName, upgradeCost);
end
end
elseif (actionHash == UnitCommandTypes.FORM_CORPS) then
if (GameInfo.Units[unitType].Domain == "DOMAIN_SEA") then
toolTipString = Locale.Lookup("LOC_UNITCOMMAND_FORM_FLEET_DESCRIPTION");
else
toolTipString = Locale.Lookup(commandRow.Description);
end
elseif (actionHash == UnitCommandTypes.FORM_ARMY) then
if (GameInfo.Units[unitType].Domain == "DOMAIN_SEA") then
toolTipString = Locale.Lookup("LOC_UNITCOMMAND_FORM_ARMADA_DESCRIPTION");
else
toolTipString = Locale.Lookup(commandRow.Description);
end
else
toolTipString = Locale.Lookup(commandRow.Description);
end
if (tResults ~= nil) then
if (tResults[UnitOperationResults.ACTION_NAME] ~= nil and tResults[UnitOperationResults.ACTION_NAME] ~= "") then
toolTipString = Locale.Lookup(tResults[UnitOperationResults.ACTION_NAME]);
end
if (tResults[UnitOperationResults.ADDITIONAL_DESCRIPTION] ~= nil) then
for i,v in ipairs(tResults[UnitOperationResults.ADDITIONAL_DESCRIPTION]) do
toolTipString = toolTipString .. "[NEWLINE]" .. Locale.Lookup(v);
end
end
-- Are there any failure reasons?
if ( bDisabled ) then
if (tResults[UnitOperationResults.FAILURE_REASONS] ~= nil) then
-- Add the reason(s) to the tool tip
for i,v in ipairs(tResults[UnitOperationResults.FAILURE_REASONS]) do
toolTipString = toolTipString .. "[NEWLINE]" .. "[COLOR:Red]" .. Locale.Lookup(v) .. "[ENDCOLOR]";
end
end
end
end
isDisabled = bDisabled or isDisabled; -- Mix in tutorial disabledness
AddActionToTable( actionsTable, commandRow, isDisabled, toolTipString, actionHash, OnUnitActionClicked, UnitCommandTypes.TYPE, actionHash );
end
end
end
end
-- Loop over the UnitOperations (like commands but may take 1 to N turns to complete)
-- Only show the operations if the unit has moves left.
local isHasMovesLeft = pUnit:GetMovesRemaining() > 0;
if isHasMovesLeft then
for operationRow in GameInfo.UnitOperations() do
local actionHash :number = operationRow.Hash;
local isDisabled :boolean= IsDisabledByTutorial( unitType, actionHash );
local instance;
-- if unit can build an improvement, show all the buildable improvements for that tile
if (actionHash == UnitOperationTypes.BUILD_IMPROVEMENT) then
local tParameters = {};
tParameters[UnitOperationTypes.PARAM_X] = pUnit:GetX();
tParameters[UnitOperationTypes.PARAM_Y] = pUnit:GetY();
--Call CanStartOperation asking for results
local bCanStart, tResults = UnitManager.CanStartOperation( pUnit, UnitOperationTypes.BUILD_IMPROVEMENT, nil, tParameters, true);
if (bCanStart and tResults ~= nil) then
if (tResults[UnitOperationResults.IMPROVEMENTS] ~= nil and #tResults[UnitOperationResults.IMPROVEMENTS] ~= 0) then
m_bestValidImprovement = tResults[UnitOperationResults.BEST_IMPROVEMENT];
local tImprovements = tResults[UnitOperationResults.IMPROVEMENTS];
for i, eImprovement in ipairs(tImprovements) do
tParameters[UnitOperationTypes.PARAM_IMPROVEMENT_TYPE] = eImprovement;
local improvement = GameInfo.Improvements[eImprovement];
bCanStart, tResults = UnitManager.CanStartOperation(pUnit, actionHash, nil, tParameters, true);
local isDisabled = not bCanStart;
local toolTipString = Locale.Lookup(operationRow.Description) .. ": " .. Locale.Lookup(improvement.Name);
if tResults ~= nil then
if (tResults[UnitOperationResults.ADDITIONAL_DESCRIPTION] ~= nil) then
for i,v in ipairs(tResults[UnitOperationResults.ADDITIONAL_DESCRIPTION]) do
toolTipString = toolTipString .. "[NEWLINE]" .. Locale.Lookup(v);
end
end
-- Are there any failure reasons?
if isDisabled then
if (tResults[UnitOperationResults.FAILURE_REASONS] ~= nil) then
-- Add the reason(s) to the tool tip
for i,v in ipairs(tResults[UnitOperationResults.FAILURE_REASONS]) do
toolTipString = toolTipString .. "[NEWLINE]" .. "[COLOR:Red]" .. Locale.Lookup(v) .. "[ENDCOLOR]";
end
end
end
end
-- If this improvement is the same enum as what the game marked as "the best" for this plot, set this flag for the UI to use.
if ( m_bestValidImprovement ~= -1 and m_bestValidImprovement == eImprovement ) then
improvement["IsBestImprovement"] = true;
else
improvement["IsBestImprovement"] = false;
end
improvement["CategoryInUI"] = "BUILD"; -- TODO: Force improvement to be a type of "BUILD", this can be removed if CategoryInUI is added to "Improvements" in the database schema. ??TRON
AddActionToTable( actionsTable, improvement, isDisabled, toolTipString, actionHash, OnUnitActionClicked_BuildImprovement, improvement.Hash );
end
end
end
elseif (actionHash == UnitOperationTypes.MOVE_TO) then
local bCanStart :boolean= UnitManager.CanStartOperation( pUnit, UnitOperationTypes.MOVE_TO, nil, false, false); -- No exclusion test, no results
if (bCanStart) then
local toolTipString :string = Locale.Lookup(operationRow.Description);
AddActionToTable( actionsTable, operationRow, isDisabled, toolTipString, actionHash, OnUnitActionClicked_MoveTo );
end
elseif (operationRow.CategoryInUI == "OFFENSIVESPY") then
local bCanStart :boolean= UnitManager.CanStartOperation( pUnit, actionHash, nil, false, false); -- No exclusion test, no result
if (bCanStart) then
---- We only want a single offensive spy action which opens the EspionageChooser side panel
if actionsTable[operationRow.CategoryInUI] ~= nil and table.count(actionsTable[operationRow.CategoryInUI]) == 0 then
local toolTipString :string = Locale.Lookup("LOC_UNITPANEL_ESPIONAGE_CHOOSE_MISSION");
AddActionToTable( actionsTable, operationRow, isDisabled, toolTipString, actionHash, OnUnitActionClicked, UnitOperationTypes.TYPE, actionHash, "ICON_UNITOPERATION_SPY_MISSIONCHOOSER");
end
end
elseif (actionHash == UnitOperationTypes.SPY_COUNTERSPY) then
local bCanStart, tResults = UnitManager.CanStartOperation( pUnit, actionHash, nil, true );
if (bCanStart) then
local toolTipString = Locale.Lookup(operationRow.Description);
AddActionToTable( actionsTable, operationRow, isDisabled, toolTipString, actionHash, OnUnitActionClicked, UnitOperationTypes.TYPE, actionHash, "ICON_UNITOPERATION_SPY_COUNTERSPY_ACTION");
end
elseif (actionHash == UnitOperationTypes.FOUND_CITY) then
local bCanStart :boolean= UnitManager.CanStartOperation( pUnit, UnitOperationTypes.FOUND_CITY, nil, false, false); -- No exclusion test, no results
if (bCanStart) then
local toolTipString :string = Locale.Lookup(operationRow.Description);
AddActionToTable( actionsTable, operationRow, isDisabled, toolTipString, actionHash, OnUnitActionClicked_FoundCity );
end
elseif (actionHash == UnitOperationTypes.WMD_STRIKE) then
-- if unit can deploy a WMD, create a unit action for each type
-- first check if the unit is capable of deploying a WMD
local bCanStart = UnitManager.CanStartOperation( pUnit, UnitOperationTypes.WMD_STRIKE, nil, true);
if (bCanStart) then
for entry in GameInfo.WMDs() do
local tParameters = {};
tParameters[UnitOperationTypes.PARAM_WMD_TYPE] = entry.Index;
bCanStart, tResults = UnitManager.CanStartOperation(pUnit, actionHash, nil, tParameters, true);
local isWMDTypeDisabled:boolean = (not bCanStart) or isDisabled;
local toolTipString :string = Locale.Lookup(operationRow.Description);
local wmd = entry.Index;
toolTipString = toolTipString .. "[NEWLINE]" .. Locale.Lookup(entry.Name);
local callBack = function() OnUnitActionClicked_WMDStrike(wmd); end
-- Are there any failure reasons?
if ( not bCanStart ) then
if tResults ~= nil and (tResults[UnitOperationResults.FAILURE_REASONS] ~= nil) then
-- Add the reason(s) to the tool tip
for i,v in ipairs(tResults[UnitOperationResults.FAILURE_REASONS]) do
toolTipString = toolTipString .. "[NEWLINE]" .. "[COLOR:Red]" .. Locale.Lookup(v) .. "[ENDCOLOR]";
end
end
end
AddActionToTable( actionsTable, operationRow, isWMDTypeDisabled, toolTipString, actionHash, callBack );
end
end
else
-- Is this operation visible in the UI?
-- The UI check of an operation is a loose check where it only fails if the unit could never do the operation.
if ( operationRow.VisibleInUI ) then
local bCanStart, tResults = UnitManager.CanStartOperation( pUnit, actionHash, nil, true );
if (bCanStart) then
-- Check again if the operation can occur, this time for real.
bCanStart, tResults = UnitManager.CanStartOperation(pUnit, actionHash, nil, false, true);
local bDisabled = not bCanStart;
local toolTipString = Locale.Lookup(operationRow.Description);
if (tResults ~= nil) then
if (tResults[UnitOperationResults.ACTION_NAME] ~= nil and tResults[UnitOperationResults.ACTION_NAME] ~= "") then
toolTipString = Locale.Lookup(tResults[UnitOperationResults.ACTION_NAME]);
end
if (tResults[UnitOperationResults.FEATURE_TYPE] ~= nil) then
local featureName = GameInfo.Features[tResults[UnitOperationResults.FEATURE_TYPE]].Name;
toolTipString = toolTipString .. ": " .. Locale.Lookup(featureName);
end
if (tResults[UnitOperationResults.ADDITIONAL_DESCRIPTION] ~= nil) then
for i,v in ipairs(tResults[UnitOperationResults.ADDITIONAL_DESCRIPTION]) do
toolTipString = toolTipString .. "[NEWLINE]" .. Locale.Lookup(v);
end
end
-- Are there any failure reasons?
if ( bDisabled ) then
if (tResults[UnitOperationResults.FAILURE_REASONS] ~= nil) then
-- Add the reason(s) to the tool tip
for i,v in ipairs(tResults[UnitOperationResults.FAILURE_REASONS]) do
toolTipString = toolTipString .. "[NEWLINE]" .. "[COLOR:Red]" .. Locale.Lookup(v) .. "[ENDCOLOR]";
end
end
end
end
isDisabled = bDisabled or isDisabled;
AddActionToTable( actionsTable, operationRow, isDisabled, toolTipString, actionHash, OnUnitActionClicked, UnitOperationTypes.TYPE, actionHash );
end
end
end
end
end
return actionsTable;
end
-- ===========================================================================
function StartIconGroup()
if m_currentIconGroup ~= nil then
UI.DataError("Starting an icon group but a prior one wasn't completed!");
end
m_currentIconGroup = m_groupArtIM:GetInstance();
m_numIconsInCurrentIconGroup = 0;
end
-- ===========================================================================
function EndIconGroup()
if m_currentIconGroup == nil then
UI.DataError("Attempt to end an icon group, but their are no icons!");
return;
end
local instance :table = m_standardActionsIM:GetInstance();
local width :number = instance.UnitActionButton:GetSizeX();
m_standardActionsIM:ReleaseInstance( instance );
m_currentIconGroup.Top:SetSizeX( width * m_numIconsInCurrentIconGroup );
m_currentIconGroup = nil;
Controls.PrimaryArtStack:CalculateSize();
Controls.PrimaryArtStack:ReprocessAnchoring();
end
-- ===========================================================================
function GetPercentFromDamage( damage:number, maxDamage:number )
if damage > maxDamage then
damage = maxDamage;
end
return (damage / maxDamage);
end
-- ===========================================================================
-- Set the health meter
-- ===========================================================================
function RealizeHealthMeter( control:table, percent:number, controlShadow:table, shadowPercent:number )
if ( percent > 0.7 ) then
control:SetColor( COLORS.METER_HP_GOOD );
controlShadow:SetColor( COLORS.METER_HP_GOOD_SHADOW );
elseif ( percent > 0.4 ) then
control:SetColor( COLORS.METER_HP_OK );
controlShadow:SetColor( COLORS.METER_HP_OK_SHADOW );
else
control:SetColor( COLORS.METER_HP_BAD );
controlShadow:SetColor( COLORS.METER_HP_BAD_SHADOW );
end
-- Meter control is half circle, so add enough to start at half point and condence % into the half area
percent = (percent * 0.5) + 0.5;
shadowPercent = (shadowPercent * 0.5) + 0.5;
control:SetPercent( percent );
controlShadow:SetPercent( shadowPercent );
end
-- ===========================================================================
-- View(data)
-- Update the layout based on the view model
-- ===========================================================================
function View(data)
-- TODO: Explore what (if anything) could be done with prior values so Reset can be utilized instead of destory; this would gain LUA side pooling
m_buildActionsIM:DestroyInstances();
m_standardActionsIM:ResetInstances();
m_secondaryActionsIM:ResetInstances();
m_groupArtIM:ResetInstances();
m_buildActionsIM:ResetInstances();
---=======[ ACTIONS ]=======---
HidePromotionPanel();
-- Reset UnitPanelBaseContainer to minium size
Controls.UnitPanelBaseContainer:SetSizeX(m_minUnitPanelWidth);
-- First fill the primary area
if (table.count(data.Actions) > 0) then
for _,categoryName in ipairs(data.Actions.displayOrder.primaryArea) do
local categoryTable = data.Actions[categoryName];
if (categoryTable == nil ) then
local allNames :string = "";
for _,catName in ipairs(data.Actions) do allNames = allNames .. "'" .. catName .. "' "; end
print("ERROR: Unit panel's primary actions sort reference '"..categoryName.."' but no table of that name. Tables in actionsTable: " .. allNames);
Controls.ForceAnAssertDueToAboveCondition();
else
StartIconGroup();
for _,action in ipairs(categoryTable) do
local instance:table = m_standardActionsIM:GetInstance();
AddActionButton( instance, action );
end
EndIconGroup();
end
end
-- Next fill in secondardy actions area
local numSecondaryItems:number = 0;
for _,categoryName in ipairs(data.Actions.displayOrder.secondaryArea) do
local categoryTable = data.Actions[categoryName];
if (categoryTable == nil ) then
local allNames :string = "";
for _,catName in ipairs(data.Actions) do allNames = allNames .. "'" .. catName .. "' "; end
print("ERROR: Unit panel's secondary actions sort reference '"..categoryName.."' but no table of that name. Tables in actionsTable: " .. allNames);
Controls.ForceAnAssertDueToAboveCondition();
else
for _,action in ipairs(categoryTable) do
local instance:table = m_secondaryActionsIM:GetInstance();
AddActionButton( instance, action );
numSecondaryItems = numSecondaryItems + 1;
end
end
end
Controls.ExpandSecondaryActionGrid:SetHide( numSecondaryItems <=0 );
end
-- Build panel options (if any)
if ( data.Actions["BUILD"] ~= nil and #data.Actions["BUILD"] > 0 ) then
Controls.BuildActionsPanel:SetHide(false);
local bestBuildAction :table = nil;
-- Create columns (each able to hold x3 icons) and fill them top to bottom
local numBuildCommands = table.count(data.Actions["BUILD"]);
for i=1,numBuildCommands,3 do
local buildColumnInstance = m_buildActionsIM:GetInstance();
for iRow=1,3,1 do
if ( (i+iRow)-1 <= numBuildCommands ) then
local slotName = "Row"..tostring(iRow);
local action = data.Actions["BUILD"][(i+iRow)-1];
local instance = {};
ContextPtr:BuildInstanceForControl( "BuildActionInstance", instance, buildColumnInstance[slotName]);
instance.UnitActionIcon:SetTexture( IconManager:FindIconAtlas(action.IconId) );
instance.UnitActionButton:SetDisabled( action.Disabled );
instance.UnitActionButton:SetAlpha( (action.Disabled and 0.4) or 1 );
instance.UnitActionButton:SetToolTipString( action.helpString );
instance.UnitActionButton:RegisterCallback( Mouse.eLClick, action.CallbackFunc );
instance.UnitActionButton:SetVoid1( action.CallbackVoid1 );
instance.UnitActionButton:SetVoid2( action.CallbackVoid2 );
-- PLACEHOLDER, currently sets first non-disabled build command; change to best build command.
if ( action.IsBestImprovement ~= nil and action.IsBestImprovement == true ) then
bestBuildAction = action;
end
end
end
end
local BUILD_PANEL_ART_PADDING_X = 24;
local BUILD_PANEL_ART_PADDING_Y = 20;
Controls.BuildActionsStack:CalculateSize();
Controls.BuildActionsStack:ReprocessAnchoring();
local buildStackWidth :number = Controls.BuildActionsStack:GetSizeX();
local buildStackHeight :number = Controls.BuildActionsStack:GetSizeY();
Controls.BuildActionsPanel:SetSizeX( buildStackWidth + BUILD_PANEL_ART_PADDING_X);
Controls.RecommendedActionButton:ReprocessAnchoring();
Controls.RecommendedActionIcon:ReprocessAnchoring();
bestBuildAction = nil;
Controls.RecommendedActionFrame:SetHide( bestBuildAction == nil );
if ( bestBuildAction ~= nil ) then
Controls.RecommendedActionButton:SetHide(false);
Controls.BuildActionsPanel:SetSizeY( buildStackHeight + 20 + BUILD_PANEL_ART_PADDING_Y);
Controls.BuildActionsStack:SetOffsetY(26);
Controls.RecommendedActionIcon:SetTexture( IconManager:FindIconAtlas(bestBuildAction.IconId) );
Controls.RecommendedActionButton:SetDisabled( bestBuildAction.Disabled );
Controls.RecommendedActionIcon:SetAlpha( (bestBuildAction.Disabled and 0.4) or 1 );
local tooltipString:string = Locale.Lookup("LOC_HUD_UNIT_PANEL_RECOMMENDED") .. ":[NEWLINE]" .. bestBuildAction.helpString;
Controls.RecommendedActionButton:SetToolTipString( tooltipString );
Controls.RecommendedActionButton:RegisterCallback( Mouse.eLClick, bestBuildAction.CallbackFunc );
Controls.RecommendedActionButton:SetVoid1( bestBuildAction.CallbackVoid1 );
Controls.RecommendedActionButton:SetVoid2( bestBuildAction.CallbackVoid2 );
else
Controls.RecommendedActionButton:SetHide(true);
Controls.BuildActionsPanel:SetSizeY( buildStackHeight + BUILD_PANEL_ART_PADDING_Y);
Controls.BuildActionsStack:SetOffsetY(0);
end
else
Controls.BuildActionsPanel:SetHide(true);
end
Controls.StandardActionsStack:CalculateSize();
Controls.StandardActionsStack:ReprocessAnchoring();
Controls.SecondaryActionsStack:CalculateSize();
Controls.SecondaryActionsStack:ReprocessAnchoring();
ResizeUnitPanelToFitActionButtons();
---=======[ STATS ]=======---
ShowSubjectUnitStats(ReadTargetData());
TradeUnitView(data);
EspionageView(data);
-- Unit Name
local unitName = Locale.Lookup(data.Name);
-- Add suffix
if data.UnitType ~= -1 then
if (GameInfo.Units[data.UnitType].Domain == "DOMAIN_SEA") then
if (data.MilitaryFormation == MilitaryFormationTypes.CORPS_FORMATION) then
unitName = unitName .. " " .. Locale.Lookup("LOC_HUD_UNIT_PANEL_FLEET_SUFFIX");
elseif (data.MilitaryFormation == MilitaryFormationTypes.ARMY_FORMATION) then
unitName = unitName .. " " .. Locale.Lookup("LOC_HUD_UNIT_PANEL_ARMADA_SUFFIX");
end
else
if (data.MilitaryFormation == MilitaryFormationTypes.CORPS_FORMATION) then
unitName = unitName .. " " .. Locale.Lookup("LOC_HUD_UNIT_PANEL_CORPS_SUFFIX");
elseif (data.MilitaryFormation == MilitaryFormationTypes.ARMY_FORMATION) then
unitName = unitName .. " " .. Locale.Lookup("LOC_HUD_UNIT_PANEL_ARMY_SUFFIX");
end
end
end
Controls.UnitName:SetText( Locale.ToUpper( unitName ));
Controls.CombatPreviewUnitName:SetText( Locale.ToUpper( unitName ));
-- Portrait Icons
if(data.IconName ~= nil) then
Controls.UnitIcon:SetIcon(data.IconName);
end
if(data.CivIconName ~= nil) then
local darkerBackColor = DarkenLightenColor(m_primaryColor,(-85),238);
local brighterBackColor = DarkenLightenColor(m_primaryColor,90,255);
Controls.CircleBacking:SetColor(m_primaryColor);
Controls.CircleLighter:SetColor(brighterBackColor);
Controls.CircleDarker:SetColor(darkerBackColor);
Controls.CivIcon:SetColor(m_secondaryColor);
Controls.CivIcon:SetIcon(data.CivIconName);
Controls.CityIconArea:SetHide(false);
Controls.UnitIcon:SetHide(true);
else
Controls.CityIconArea:SetHide(true);
Controls.UnitIcon:SetHide(false);
end
-- Damage meters ---
if (data.MaxWallDamage > 0) then
local healthPercent :number = 1 - GetPercentFromDamage( data.Damage + data.PotentialDamage, data.MaxDamage );
local healthShadowPercent :number = 1 - GetPercentFromDamage( data.Damage, data.MaxDamage );
RealizeHealthMeter( Controls.CityHealthMeter, healthPercent, Controls.CityHealthMeterShadow, healthShadowPercent );
local wallsPercent :number = 1 - GetPercentFromDamage(data.WallDamage + data.PotentialWallDamage, data.MaxWallDamage);
local wallsShadowPercent :number = 1 - GetPercentFromDamage( data.WallDamage, data.MaxWallDamage );
local wallRealizedPercent = (wallsPercent * 0.5) + 0.5;
Controls.WallHealthMeter:SetPercent( wallRealizedPercent )
local wallShadowRealizedPercent = (wallsShadowPercent * 0.5) + 0.5;
Controls.WallHealthMeterShadow:SetPercent( wallShadowRealizedPercent )
Controls.UnitHealthMeter:SetHide(true);
Controls.CityHealthMeters:SetHide(false);
if(wallsPercent == 0) then
Controls.CityWallHealthMeters:SetHide(true);
else
Controls.CityWallHealthMeters:SetHide(false);
end
-- Update health tooltip
local tooltip:string = "";
if data.UnitType ~= -1 then
tooltip = Locale.Lookup(data.UnitTypeName);
end
tooltip = tooltip .. "[NEWLINE]" .. Locale.Lookup("LOC_HUD_UNIT_PANEL_HEALTH_TOOLTIP", data.MaxDamage - data.Damage, data.MaxDamage);
if (data.MaxWallDamage > 0) then
tooltip = tooltip .. "[NEWLINE]" .. Locale.Lookup("LOC_HUD_UNIT_PANEL_WALL_HEALTH_TOOLTIP", data.MaxWallDamage - data.WallDamage, data.MaxWallDamage);
end
Controls.CityHealthMeter:SetToolTipString(tooltip);
else
local percent :number = 1 - GetPercentFromDamage( data.Damage, data.MaxDamage );
RealizeHealthMeter( Controls.UnitHealthMeter, percent, Controls.UnitHealthMeterShadow, percent );
Controls.UnitHealthMeter:SetHide(false);
Controls.CityHealthMeters:SetHide(true);
-- Update health tooltip
local tooltip:string = Locale.Lookup(data.UnitTypeName);
tooltip = tooltip .. "[NEWLINE]" .. Locale.Lookup("LOC_HUD_UNIT_PANEL_HEALTH_TOOLTIP", data.MaxDamage - data.Damage, data.MaxDamage);
Controls.UnitHealthMeter:SetToolTipString(tooltip);
end
-- Populate Earned Promotions UI
if (not UILens.IsLensActive("Religion") and data.Combat > 0) then
Controls.XPArea:SetHide(false);
Controls.XPBar:SetPercent( data.UnitExperience / data.MaxExperience );
Controls.XPArea:SetToolTipString( Locale.Lookup("LOC_HUD_UNIT_PANEL_XP_TT", data.UnitExperience, data.MaxExperience, data.UnitLevel+1 ) );
else
Controls.XPArea:SetHide(true);
end
Controls.PromotionBanner:SetColor( m_primaryColor );
m_earnedPromotionIM:ResetInstances();
if (table.count(data.CurrentPromotions) > 0) then
for i, promotion in ipairs(data.CurrentPromotions) do
local promotionInst = m_earnedPromotionIM:GetInstance();
if (data.CurrentPromotions[i] ~= nil) then
local descriptionStr = Locale.Lookup(data.CurrentPromotions[i].Name);
descriptionStr = descriptionStr .. "[NEWLINE]" .. Locale.Lookup(data.CurrentPromotions[i].Desc);
promotionInst.Top:SetToolTipString(descriptionStr);
end
end
Controls.PromotionBanner:SetHide(false);
else
Controls.PromotionBanner:SetHide(true);
end
-- Great Person Passive Ability Info
if data.GreatPersonPassiveText ~= "" then
Controls.GreatPersonPassiveGrid:SetHide(false);
Controls.GreatPersonPassiveGrid:SetToolTipString(Locale.Lookup("LOC_HUD_UNIT_PANEL_GREAT_PERSON_PASSIVE_ABILITY_TOOLTIP", data.GreatPersonPassiveName, data.GreatPersonPassiveText));
else
Controls.GreatPersonPassiveGrid:SetHide(true);
end
-- Settler Water Availability Info
if data.IsSettler then
Controls.SettlementWaterContainer:SetHide(false);
else
Controls.SettlementWaterContainer:SetHide(true);
end
ContextPtr:SetHide(false);
-- Hide combat preview unless we have valid combat results
if m_combatResults == nil then
OnShowCombat(false);
end
-- Turn off any animation previously occuring on meter, otherwise it will animate up each time a new unit is selected.
Controls.UnitHealthMeter:SetAnimationSpeed( -1 );
end
-- ===========================================================================
function ViewTarget(data)
-- Unit Name
local targetName = data.Name;
-- Add suffix
if (data.UnitType ~= -1) then
if (GameInfo.Units[data.UnitType].Domain == "DOMAIN_SEA") then
if (data.MilitaryFormation == MilitaryFormationTypes.CORPS_FORMATION) then
targetName = targetName .. " " .. Locale.Lookup("LOC_HUD_UNIT_PANEL_FLEET_SUFFIX");
elseif (data.MilitaryFormation == MilitaryFormationTypes.ARMY_FORMATION) then
targetName = targetName .. " " .. Locale.Lookup("LOC_HUD_UNIT_PANEL_ARMADA_SUFFIX");
end
else
if (data.MilitaryFormation == MilitaryFormationTypes.CORPS_FORMATION) then
targetName = targetName .. " " .. Locale.Lookup("LOC_HUD_UNIT_PANEL_CORPS_SUFFIX");
elseif (data.MilitaryFormation == MilitaryFormationTypes.ARMY_FORMATION) then
targetName = targetName .. " " .. Locale.Lookup("LOC_HUD_UNIT_PANEL_ARMY_SUFFIX");
end
end
end
Controls.TargetUnitName:SetText( Locale.ToUpper( targetName ));
---=======[ STATS ]=======---
ShowTargetUnitStats();
-- Portrait Icons
if(data.IconName ~= nil) then
Controls.TargetUnitIcon:SetIcon(data.IconName);
end
if(data.CivIconName ~= nil) then
local darkerBackColor = DarkenLightenColor(m_primaryColor,(-85),238);
local brighterBackColor = DarkenLightenColor(m_primaryColor,90,255);
Controls.TargetCircleBacking:SetColor(m_primaryColor);
Controls.TargetCircleLighter:SetColor(brighterBackColor);
Controls.TargetCircleDarker:SetColor(darkerBackColor);
Controls.TargetCivIcon:SetColor(m_secondaryColor);
Controls.TargetCivIcon:SetIcon(data.CivIconName);
Controls.TargetCityIconArea:SetHide(false);
Controls.TargetUnitIcon:SetHide(true);
else
Controls.TargetCityIconArea:SetHide(true);
Controls.TargetUnitIcon:SetHide(false);
end
-- Damage meters ---
if (data.MaxWallDamage > 0) then
local healthPercent :number = 1 - GetPercentFromDamage( data.Damage + data.PotentialDamage, data.MaxDamage );
local healthShadowPercent :number = 1 - GetPercentFromDamage( data.Damage, data.MaxDamage );
RealizeHealthMeter( Controls.TargetCityHealthMeter, healthPercent, Controls.TargetCityHealthMeterShadow, healthShadowPercent );
local wallsPercent :number = 1 - GetPercentFromDamage(data.WallDamage + data.PotentialWallDamage, data.MaxWallDamage);
local wallsShadowPercent :number = 1 - GetPercentFromDamage( data.WallDamage, data.MaxWallDamage );
--RealizeHealthMeter( Controls.TargetWallHealthMeter, wallsPercent, Controls.TargetWallHealthMeterShadow, wallsShadowPercent );
local wallRealizedPercent = (wallsPercent * 0.5) + 0.5;
Controls.TargetWallHealthMeter:SetPercent( wallRealizedPercent );
local wallShadowRealizedPercent = (wallsShadowPercent * 0.5) + 0.5;
Controls.TargetWallHealthMeterShadow:SetPercent( wallShadowRealizedPercent );
Controls.TargetUnitHealthMeters:SetHide(true);
Controls.TargetCityHealthMeters:SetHide(false);
if(wallsPercent == 0) then
Controls.TargetCityWallsHealthMeters:SetHide(true);
else
Controls.TargetCityWallsHealthMeters:SetHide(false);
end
else
local percent :number = 1 - GetPercentFromDamage( data.Damage + data.PotentialDamage, data.MaxDamage );
local shadowPercent :number = 1 - GetPercentFromDamage( data.Damage, data.MaxDamage );
RealizeHealthMeter( Controls.TargetHealthMeter, percent, Controls.TargetHealthMeterShadow, shadowPercent );
Controls.TargetUnitHealthMeters:SetHide(false);
Controls.TargetCityHealthMeters:SetHide(true);
end
OnShowCombat(true);
end
-- ===========================================================================
function ShowDistrictStats(showCombat:boolean)
m_subjectStatStackIM:ResetInstances();
-- Make sure we have some subject data
if m_subjectData == nil then
return;
end
-- Ranged strength is always used as primary stat when attacking so hide stat in combat preview
if showCombat then
-- Show melee strength
AddDistrictStat(m_subjectData.Combat, "", "ICON_STRENGTH", -12);
Controls.SubjectStatContainer:SetOffsetVal(86,112);
Controls.SubjectStatContainer:SetSizeX(72);
else
-- Show range strength
AddDistrictStat(m_subjectData.RangedCombat, "LOC_HUD_UNIT_PANEL_RANGED_STRENGTH", "ICON_RANGED_STRENGTH", 0);
-- Show melee strength
AddDistrictStat(m_subjectData.Combat, "LOC_HUD_UNIT_PANEL_STRENGTH", "ICON_STRENGTH", -12);
Controls.SubjectStatContainer:SetOffsetVal(86,56);
Controls.SubjectStatContainer:SetParentRelativeSizeX(-105);
end
Controls.SubjectStatStack:CalculateSize();
Controls.SubjectStatStack:ReprocessAnchoring();
Controls.SubjectStatContainer:ReprocessAnchoring();
end
-- ===========================================================================
function ShowSubjectUnitStats(showCombat:boolean)
m_subjectStatStackIM:ResetInstances();
-- If we're in city or district attack mode reroute to ShowDistrictStats
if (UI.GetInterfaceMode() == InterfaceModeTypes.CITY_RANGE_ATTACK) or (UI.GetInterfaceMode() == InterfaceModeTypes.DISTRICT_RANGE_ATTACK) then
ShowDistrictStats(showCombat);
return;
end
-- If the subject is something like a city then ignore unit stats
if m_subjectData == nil or m_subjectData.UnitType == -1 then
return;
end
-- Don't display unit stats for these units
if m_subjectData.IsSpy then
return;
end
-- Show custom stats for trader units
if m_subjectData.IsTradeUnit then
-- Add stat for trade route name
local xOffset:number = 0;
if m_subjectData.TradeRouteName ~= "" then
AddCustomUnitStat(m_subjectData.TradeRouteIcon, "", m_subjectData.TradeRouteName, xOffset);
xOffset = xOffset - 12;
end
AddCustomUnitStat("ICON_STATS_LAND_TRADE", tostring(m_subjectData.TradeLandRange), "LOC_HUD_UNIT_PANEL_LAND_ROUTE_RANGE", xOffset);
-- If offset is still 0 then make sure to adjust it for the next stat
if xOffset == 0 then
xOffset = xOffset - 12;
end
AddCustomUnitStat("ICON_STATS_SEA_TRADE", tostring(m_subjectData.TradeSeaRange), "LOC_HUD_UNIT_PANEL_SEA_ROUTE_RANGE", xOffset);
return;
end
-- If we showing the combat preview we can only show three stats and
-- the main combat stat is shown separately above the normal stat stack
-- Never show combat for civilian units!!
local isCivilian :boolean = GameInfo.Units[m_subjectData.UnitType].FormationClass == "FORMATION_CLASS_CIVILIAN";
local isReligious :boolean = (m_subjectData.ReligiousStrength > 0 );
if showCombat and m_combatResults ~= nil and ((isCivilian==false) or (isCivilian and isReligious)) then
m_subjectData.StatData = FilterUnitStatsFromUnitData(m_subjectData, m_combatResults[CombatResultParameters.COMBAT_TYPE]);
local currentStatIndex:number = 0;
for i,entry in ipairs(m_subjectData.StatData) do
if currentStatIndex == 0 then
AddUnitStat(i, entry, m_subjectData, -12, false);
elseif currentStatIndex == 1 then
AddUnitStat(i, entry, m_subjectData, -12, false);
elseif currentStatIndex == 2 then
AddUnitStat(i, entry, m_subjectData, 0, false);
end
currentStatIndex = currentStatIndex + 1;
end
Controls.SubjectStatContainer:SetOffsetVal(86,112);
Controls.SubjectStatContainer:SetSizeX(72);
else
m_subjectData.StatData = FilterUnitStatsFromUnitData(m_subjectData);
local currentStatIndex:number = 0;
for i,entry in ipairs(m_subjectData.StatData) do
if currentStatIndex == 0 then
AddUnitStat(i, entry, m_subjectData, 0, true);
elseif currentStatIndex == 1 then
AddUnitStat(i, entry, m_subjectData, -12, true);
elseif currentStatIndex == 2 then
AddUnitStat(i, entry, m_subjectData, -12, true);
elseif currentStatIndex == 3 then
AddUnitStat(i, entry, m_subjectData, 0, true);
end
currentStatIndex = currentStatIndex + 1;
end
Controls.SubjectStatContainer:SetOffsetVal(86,56);
Controls.SubjectStatContainer:SetParentRelativeSizeX(-105);
end
Controls.SubjectStatStack:CalculateSize();
Controls.SubjectStatStack:ReprocessAnchoring();
Controls.SubjectStatContainer:ReprocessAnchoring();
end
-- ===========================================================================
function AddDistrictStat(value:number, name:string, icon:string, relativeSizeX:number)
local statInstance:table = m_subjectStatStackIM:GetInstance();
-- Set relative size x
statInstance.StatGrid:SetParentRelativeSizeX(relativeSizeX);
-- Update name
TruncateStringWithTooltip(statInstance.StatNameLabel, MAX_BEFORE_TRUNC_STAT_NAME, Locale.ToUpper(name));
--statInstance.StatNameLabel:SetText(Locale.ToUpper(name));
-- Update value
statInstance.StatValueLabel:SetText(value);
statInstance.StatValueSlash:SetHide(true);
statInstance.StatMaxValueLabel:SetHide(true);
-- Update icon
local textureOffsetX, textureOffsetY, textureSheet = IconManager:FindIconAtlas(icon,22);
statInstance.StatCheckBox:SetCheckTexture(textureSheet);
statInstance.StatCheckBox:SetCheckTextureOffsetVal(textureOffsetX,textureOffsetY);
statInstance.StatCheckBox:SetUnCheckTextureOffsetVal(textureOffsetX,textureOffsetY);
statInstance.StatGrid:ReprocessAnchoring();
end
-- ===========================================================================
function FilterUnitStatsFromUnitData( unitData:table, ignoreStatType:number )
if unitData == nil then
UI.DataError("Invalid unit hash passed to FilterUnitStatsFromUnitData");
return {};
end
local data:table = {};
-- Strength
if ( unitData.Combat > 0 and (ignoreStatType == nil or ignoreStatType ~= CombatTypes.MELEE)) then
table.insert(data, {Value = unitData.Combat, Type = "Combat", Label = "LOC_HUD_UNIT_PANEL_STRENGTH", FontIcon="[ICON_Strength_Large]", IconName="ICON_STRENGTH"});
end
if ( unitData.RangedCombat > 0 and (ignoreStatType == nil or ignoreStatType ~= CombatTypes.RANGED)) then
table.insert(data, {Value = unitData.RangedCombat, Label = "LOC_HUD_UNIT_PANEL_RANGED_STRENGTH", FontIcon="[ICON_RangedStrength_Large]", IconName="ICON_RANGED_STRENGTH"});
end
if (unitData.BombardCombat > 0 and (ignoreStatType == nil or ignoreStatType ~= CombatTypes.BOMBARD)) then
table.insert(data, {Value = unitData.BombardCombat, Label = "LOC_HUD_UNIT_PANEL_BOMBARD_STRENGTH", FontIcon="[ICON_Bombard_Large]", IconName="ICON_BOMBARD"});
end
if (unitData.ReligiousStrength > 0 and (ignoreStatType == nil or ignoreStatType ~= CombatTypes.RELIGIOUS)) then
table.insert(data, {Value = unitData.ReligiousStrength, Label = "LOC_HUD_UNIT_PANEL_RELIGIOUS_STRENGTH", FontIcon="[ICON_ReligionStat_Large]", IconName="ICON_RELIGION"});
end
if (unitData.AntiAirCombat > 0 and (ignoreStatType == nil or ignoreStatType ~= CombatTypes.AIR)) then
table.insert(data, {Value = unitData.AntiAirCombat, Label = "LOC_HUD_UNIT_PANEL_ANTI_AIR_STRENGTH", FontIcon="[ICON_AntiAir_Large]", IconName="ICON_STATS_ANTIAIR"});
end
-- Movement
if(unitData.MaxMoves > 0) then
table.insert(data, {Value = unitData.MaxMoves, Type = "BaseMoves", Label = "LOC_HUD_UNIT_PANEL_MOVEMENT", FontIcon="[ICON_Movement_Large]", IconName="ICON_MOVES"});
end
-- Range
if (unitData.Range > 0) then
table.insert(data, {Value = unitData.Range; Label = "LOC_HUD_UNIT_PANEL_ATTACK_RANGE", FontIcon="[ICON_Range_Large]", IconName="ICON_RANGE"});
end
-- Charges
if (unitData.SpreadCharges > 0) then
table.insert(data, {Value = unitData.SpreadCharges, Type = "SpreadCharges", Label = "LOC_HUD_UNIT_PANEL_SPREADS", FontIcon="[ICON_ReligionStat_Large]", IconName="ICON_RELIGION"});
end
if (unitData.BuildCharges > 0) then
table.insert(data, {Value = unitData.BuildCharges, Type = "BuildCharges", Label = "LOC_HUD_UNIT_PANEL_BUILDS", FontIcon="[ICON_Charges_Large]", IconName="ICON_BUILD_CHARGES"});
end
if (unitData.GreatPersonActionCharges > 0) then
table.insert(data, {Value = unitData.GreatPersonActionCharges, Type = "ActionCharges", Label = "LOC_HUD_UNIT_PANEL_GREAT_PERSON_ACTIONS", FontIcon="[ICON_Charges_Large]", IconName="ICON_GREAT_PERSON"});
end
-- If we have more than 4 stats then try to remove melee strength
if (table.count(data) > 4) then
for i,stat in ipairs(data) do
if stat.Type == "Combat" then
table.remove(data, i);
end
end
end
-- If we still have more than 4 stats through a data error
if (table.count(data) > 4) then
UI.DataError("More than four stats were picked to display for unit ".. tostring(unitData.UnitType));
end
return data;
end
-- ===========================================================================
function AddUnitStat(statType:number, statData:table, unitData:table, relativeSizeX:number, showName:boolean)
local statInstance:table = m_subjectStatStackIM:GetInstance();
-- Set relative size x
statInstance.StatGrid:SetParentRelativeSizeX(relativeSizeX);
-- Update name
TruncateStringWithTooltip(statInstance.StatNameLabel, MAX_BEFORE_TRUNC_STAT_NAME, Locale.ToUpper(statData.Label));
--statInstance.StatNameLabel:SetText(Locale.ToUpper(statData.Label));
-- Update values
if statData.Type ~= nil and statData.Type == "BaseMoves" then
statInstance.StatValueLabel:SetText(unitData.MovementMoves);
statInstance.StatMaxValueLabel:SetText(statData.Value);
statInstance.StatValueSlash:SetHide(false);
statInstance.StatMaxValueLabel:SetHide(false);
statInstance.StatValueStack:CalculateSize();
else
statInstance.StatValueLabel:SetText(statData.Value);
statInstance.StatValueSlash:SetHide(true);
statInstance.StatMaxValueLabel:SetHide(true);
end
-- Show/Hide stat name
if showName then
statInstance.StatNameLabel:SetHide(false);
else
statInstance.StatNameLabel:SetHide(true);
end
-- Update icon
local textureOffsetX, textureOffsetY, textureSheet = IconManager:FindIconAtlas(statData.IconName,22);
statInstance.StatCheckBox:SetCheckTexture(textureSheet);
statInstance.StatCheckBox:SetCheckTextureOffsetVal(textureOffsetX,textureOffsetY);
statInstance.StatCheckBox:SetUnCheckTextureOffsetVal(textureOffsetX,textureOffsetY);
statInstance.StatGrid:ReprocessAnchoring();
end
-- ===========================================================================
function AddCustomUnitStat(iconName:string, statValue:string, statDesc:string, relativeSizeX:number)
local statInstance:table = m_subjectStatStackIM:GetInstance();
-- Set relative size x
statInstance.StatGrid:SetParentRelativeSizeX(relativeSizeX);
-- Update name
TruncateStringWithTooltip(statInstance.StatNameLabel, MAX_BEFORE_TRUNC_STAT_NAME, Locale.ToUpper(statDesc));
-- Update values
statInstance.StatValueLabel:SetText(statValue);
statInstance.StatValueSlash:SetHide(true);
statInstance.StatMaxValueLabel:SetHide(true);
-- Update icon
local textureOffsetX, textureOffsetY, textureSheet = IconManager:FindIconAtlas(iconName,22);
statInstance.StatCheckBox:SetCheckTexture(textureSheet);
statInstance.StatCheckBox:SetUnCheckTexture(textureSheet);
statInstance.StatCheckBox:SetCheckTextureOffsetVal(textureOffsetX,textureOffsetY);
statInstance.StatCheckBox:SetUnCheckTextureOffsetVal(textureOffsetX,textureOffsetY);
statInstance.StatGrid:ReprocessAnchoring();
end
function AddTargetUnitStat(statData:table, relativeSizeX:number)
local statInstance:table = m_targetStatStackIM:GetInstance();
-- Set relative size x
statInstance.StatGrid:SetParentRelativeSizeX(relativeSizeX);
-- Update value
statInstance.StatValueLabel:SetText(statData.Value);
-- Update icon
local textureOffsetX, textureOffsetY, textureSheet = IconManager:FindIconAtlas(statData.IconName,22);
statInstance.StatCheckBox:SetCheckTexture(textureSheet);
statInstance.StatCheckBox:SetCheckTextureOffsetVal(textureOffsetX,textureOffsetY);
statInstance.StatCheckBox:SetUnCheckTextureOffsetVal(textureOffsetX,textureOffsetY);
statInstance.StatGrid:ReprocessAnchoring();
return statInstance;
end
-- ===========================================================================
function ShowTargetUnitStats()
m_targetStatStackIM:ResetInstances();
-- If unitType is 0 then we're probably attacking a city so don't show any unit stats
if m_targetData.UnitType > 0 then
-- Since the target unit is defending, the melee combat stat will always be the primary stat (except for Religious units). Show the ranged/bombard as secondary
if m_combatResults ~= nil and m_combatResults[CombatResultParameters.COMBAT_TYPE] == CombatTypes.RELIGIOUS then
m_targetData.StatData = FilterUnitStatsFromUnitData(m_targetData, CombatTypes.RELIGIOUS);
else
m_targetData.StatData = FilterUnitStatsFromUnitData(m_targetData, CombatTypes.MELEE);
end
local currentStatIndex:number = 0;
for i,entry in ipairs(m_targetData.StatData) do
if currentStatIndex == 0 then
AddTargetUnitStat(entry, -14);
elseif currentStatIndex == 1 then
AddTargetUnitStat(entry, -14);
elseif currentStatIndex == 2 then
AddTargetUnitStat(entry, 0);
end
currentStatIndex = currentStatIndex + 1;
end
Controls.TargetStatContainer:ReprocessAnchoring();
end
end
-- ===========================================================================
function TradeUnitView( viewData:table )
if viewData.IsTradeUnit then
local hideTradeYields:boolean = true;
local originPlayer:table = Players[Game.GetLocalPlayer()];
local originCities:table = originPlayer:GetCities();
for _, city in originCities:Members() do
local outgoingRoutes:table = city:GetTrade():GetOutgoingRoutes();
for i,route in ipairs(outgoingRoutes) do
if viewData.UnitID == route.TraderUnitID then
-- Add Origin Yields
Controls.TradeResourceList:DestroyAllChildren();
for j,yieldInfo in pairs(route.OriginYields) do
if yieldInfo.Amount > 0 then
local yieldDetails:table = GameInfo.Yields[yieldInfo.YieldIndex];
AddTradeResourceEntry(yieldDetails, yieldInfo.Amount);
hideTradeYields = false;
end
end
end
end
end
Controls.TradeYieldGrid:SetHide(hideTradeYields);
Controls.TradeUnitContainer:SetHide(false);
else
Controls.TradeUnitContainer:SetHide(true);
end
end
-- ===========================================================================
function AddTradeResourceEntry(yieldInfo:table, yieldValue:number)
local entryInstance:table = {};
ContextPtr:BuildInstanceForControl( "TradeResourceyInstance", entryInstance, Controls.TradeResourceList );
local icon:string, text:string = FormatTradeYieldText(yieldInfo, yieldValue);
entryInstance.ResourceEntryIcon:SetText(icon);
entryInstance.ResourceEntryText:SetText(text);
entryInstance.ResourceEntryStack:CalculateSize();
entryInstance.ResourceEntryStack:ReprocessAnchoring();
end
-- ===========================================================================
function FormatTradeYieldText(yieldInfo, yieldAmount)
local text:string = "";
local iconString = "";
if (yieldInfo.YieldType == "YIELD_FOOD") then
iconString = "[ICON_Food]";
elseif (yieldInfo.YieldType == "YIELD_PRODUCTION") then
iconString = "[ICON_Production]";
elseif (yieldInfo.YieldType == "YIELD_GOLD") then
iconString = "[ICON_Gold]";
elseif (yieldInfo.YieldType == "YIELD_SCIENCE") then
iconString = "[ICON_Science]";
elseif (yieldInfo.YieldType == "YIELD_CULTURE") then
iconString = "[ICON_Culture]";
elseif (yieldInfo.YieldType == "YIELD_FAITH") then
iconString = "[ICON_Faith]";
end
if (yieldAmount >= 0) then
text = text .. "+";
end
text = text .. yieldAmount;
return iconString, text;
end
-- ===========================================================================
function OnShowCombat( showCombat )
local bAttackerIsUnit :boolean = false;
local pAttacker :table;
if (UI.GetInterfaceMode() == InterfaceModeTypes.CITY_RANGE_ATTACK) then
local pAttackingCity = UI.GetHeadSelectedCity();
if (pAttacker == nil) then
pAttacker = GetDistrictFromCity(pAttackingCity);
if (pAttacker == nil) then
return;
end
end
elseif (UI.GetInterfaceMode() == InterfaceModeTypes.DISTRICT_RANGE_ATTACK) then
pAttacker = UI.GetHeadSelectedDistrict();
if (pAttacker == nil) then
return;
end
else
pAttacker = UI.GetHeadSelectedUnit();
if (pAttacker ~= nil) then
bAttackerIsUnit = true;
-- Never show combat for civilian units unless it's between two religious untis.
if showCombat then
if (GameInfo.Units[pAttacker:GetUnitType()].FormationClass == "FORMATION_CLASS_CIVILIAN")
and (IsAttackerReligiousCombat(pAttacker)==false) then
showCombat = false; -- All this showCombat logic, should be done before VIEW! :(
end
end
else
return;
end
end
if m_combatResults == nil then
showCombat = false;
end
if (showCombat) then
ShowCombatAssessment();
--scale the unit panels to accomodate combat details
Controls.UnitPanelBaseContainer:SetSizeY(190);
Controls.EnemyUnitPanelExtension:SetSizeY(97);
--Primary Combat Stat
--Set the icon
local combatType = m_combatResults[CombatResultParameters.COMBAT_TYPE];
local textureOffsetX:number, textureOffsetY:number, textureString:string;
if combatType == CombatTypes.MELEE then
textureOffsetX, textureOffsetY, textureString = IconManager:FindIconAtlas("ICON_STRENGTH",22);
elseif combatType == CombatTypes.RANGED then
textureOffsetX, textureOffsetY, textureString = IconManager:FindIconAtlas("ICON_RANGED_STRENGTH",22);
elseif combatType == CombatTypes.BOMBARD then
textureOffsetX, textureOffsetY, textureString = IconManager:FindIconAtlas("ICON_BOMBARD",22);
elseif combatType == CombatTypes.AIR then
textureOffsetX, textureOffsetY, textureString = IconManager:FindIconAtlas("ICON_STATS_ANTIAIR",22);
elseif combatType == CombatTypes.RELIGIOUS then
textureOffsetX, textureOffsetY, textureString = IconManager:FindIconAtlas("ICON_RELIGION",22);
end
if textureString ~= nil then
Controls.CombatPreview_CombatStatType:SetTexture(textureOffsetX, textureOffsetY, textureString);
end
-- Set Target Icon
if combatType == CombatTypes.RELIGIOUS then
textureOffsetX, textureOffsetY, textureString = IconManager:FindIconAtlas("ICON_RELIGION",22);
else
textureOffsetX, textureOffsetY, textureString = IconManager:FindIconAtlas("ICON_STRENGTH",22);
end
if textureString ~= nil then
Controls.CombatPreview_CombatStatFoeType:SetTexture(textureOffsetX, textureOffsetY, textureString);
end
--Set the numerical value
local attackerStrength = m_combatResults[CombatResultParameters.ATTACKER][CombatResultParameters.COMBAT_STRENGTH];
local attackerStrengthModifier = m_combatResults[CombatResultParameters.ATTACKER][CombatResultParameters.STRENGTH_MODIFIER];
local defenderStrength = m_combatResults[CombatResultParameters.DEFENDER][CombatResultParameters.COMBAT_STRENGTH];
local defenderStrengthModifier = m_combatResults[CombatResultParameters.DEFENDER][CombatResultParameters.STRENGTH_MODIFIER];
--Don't go below zero for final combat stat
local attackerTotal = (attackerStrength + attackerStrengthModifier);
if attackerTotal <= 0 then
attackerTotal = 0;
end
Controls.CombatPreview_CombatStatStrength:SetText(attackerTotal);
local defenderTotal = (defenderStrength + defenderStrengthModifier);
if defenderTotal <= 0 then
defenderTotal = 0;
end
Controls.CombatPreview_CombatStatFoeStrength:SetText(defenderTotal);
--Attacker's Damage meter
local attackerCurrentDamage = pAttacker:GetDamage();
local attackerMaxDamage = pAttacker:GetMaxDamage();
local attackerCombatDamage = m_combatResults[CombatResultParameters.ATTACKER][CombatResultParameters.DAMAGE_TO];
local percent :number = 1 - GetPercentFromDamage( attackerCurrentDamage + attackerCombatDamage, attackerMaxDamage);
local shadowPercent :number = 1 - GetPercentFromDamage( attackerCurrentDamage, attackerMaxDamage );
RealizeHealthMeter(Controls.UnitHealthMeter, percent, Controls.UnitHealthMeterShadow, shadowPercent);
-- Update combat preview panels
UpdateTargetModifiers(0);
Controls.CombatBreakdownPanel:SetHide(false);
UpdateCombatModifiers(0);
-- Hide Unit Selection Pulldown
Controls.UnitListPopup:SetHide(true);
else
--return unit panels to base sizes
Controls.UnitPanelBaseContainer:SetSizeY(160);
Controls.EnemyUnitPanelExtension:SetSizeY(67);
-- Hide any combat preview specific UI
Controls.CombatBreakdownPanel:SetHide(true);
-- Reset unit health when switching away from combat
local attackerCurrentDamage = pAttacker:GetDamage();
local attackerMaxDamage = pAttacker:GetMaxDamage();
local percent:number = 1 - GetPercentFromDamage( attackerCurrentDamage, attackerMaxDamage );
RealizeHealthMeter( Controls.UnitHealthMeter, percent, Controls.UnitHealthMeterShadow, percent );
-- Show Unit Selection Pulldown
Controls.UnitListPopup:SetHide(false);
end
ShowSubjectUnitStats(showCombat);
Controls.CombatPreview_CombatStat:SetHide(not showCombat);
Controls.CombatPreviewBanners:SetHide(not showCombat);
Controls.EnemyUnitPanel:SetHide(not showCombat);
if (bAttackerIsUnit) then
if (pAttacker:GetExperience():GetLevel() > 1) then
Controls.PromotionBanner:SetHide(showCombat);
end
end
end
-- Show/Hide Espionage Unit Elements
function EspionageView(data:table)
if (data.IsSpy) then
local operationType:number = data.SpyOperation;
if (operationType ~= -1) then
-- City Banner
local backColor:number, frontColor:number = UI.GetPlayerColors( data.SpyTargetOwnerID );
Controls.EspionageCityBanner:SetColor( backColor );
Controls.EspionageLocationPip:SetColor( frontColor );
Controls.EspionageCityName:SetColor( frontColor );
Controls.EspionageCityName:SetText(Locale.ToUpper(data.SpyTargetCityName));
-- Mission Name
local operationInfo:table = GameInfo.UnitOperations[operationType];
Controls.EspionageUnitStatusLabel:SetText(Locale.Lookup(operationInfo.Description));
-- Mission Icon
local textureOffsetX, textureOffsetY, textureSheet = IconManager:FindIconAtlas(operationInfo.Icon,40);
if textureSheet then
Controls.EspionageMissionIcon:SetTexture(textureOffsetX, textureOffsetY, textureSheet);
Controls.EspionageMissionIcon:SetHide(false);
else
UI.DataError("Unable to find icon for spy operation: " .. operationInfo.Icon);
Controls.EspionageMissionIcon:SetHide(true);
end
-- Turns Remaining
Controls.EspionageTurnsRemaining:SetText(Locale.Lookup("LOC_UNITPANEL_ESPIONAGE_MORE_TURNS", data.SpyRemainingTurns));
-- Update Turn Meter
local percentOperationComplete:number = (data.SpyTotalTurns - data.SpyRemainingTurns) / data.SpyTotalTurns;
local percentOperationCompleteNextTurn:number = (data.SpyTotalTurns - data.SpyRemainingTurns + 1) / data.SpyTotalTurns;
Controls.EspionageCompleteMeter:SetPercent(percentOperationComplete);
Controls.EspionageCompleteMeter_NextTurn:SetPercent(percentOperationCompleteNextTurn);
Controls.EspionageStack:CalculateSize();
Controls.EspionageStack:ReprocessAnchoring();
Controls.EspionageUnitContainer:SetHide(false);
Controls.EspionageIdleLabel:SetHide(true);
else
Controls.EspionageUnitContainer:SetHide(true);
Controls.EspionageIdleLabel:SetHide(false);
end
else
Controls.EspionageUnitContainer:SetHide(true);
Controls.EspionageIdleLabel:SetHide(true);
end
end
-- ===========================================================================
function UpdateInterceptorModifiers(startIndex:number)
local modifierList:table, modifierListSize:number = GetCombatModifierList(CombatResultParameters.INTERCEPTOR);
UpdateModifiers(startIndex, Controls.InterceptorModifierStack, Controls.InterceptorModifierStackAnim, UpdateInterceptorModifiers, m_interceptorModifierIM, modifierList, modifierListSize);
end
-- ===========================================================================
function UpdateAntiAirModifiers(startIndex:number)
local modifierList:table, modifierListSize:number = GetCombatModifierList(CombatResultParameters.ANTI_AIR);
UpdateModifiers(startIndex, Controls.AntiAirModifierStack, Controls.AntiAirModifierStackAnim, UpdateAntiAirModifiers, m_antiAirModifierIM, modifierList, modifierListSize);
end
-- ===========================================================================
function UpdateTargetModifiers(startIndex:number)
local modifierList:table, modifierListSize:number = GetCombatModifierList(CombatResultParameters.DEFENDER);
UpdateModifiers(startIndex, Controls.TargetModifierStack, Controls.TargetModifierStackAnim, UpdateTargetModifiers, m_targetModifierIM, modifierList, modifierListSize);
end
-- ===========================================================================
function UpdateCombatModifiers(startIndex:number)
local modifierList:table, modifierListSize:number = GetCombatModifierList(CombatResultParameters.ATTACKER);
UpdateModifiers(startIndex, Controls.SubjectModifierStack, Controls.SubjectModifierStackAnim, UpdateCombatModifiers, m_subjectModifierIM, modifierList, modifierListSize);
end
-- ===========================================================================
function UpdateModifiers(startIndex:number, stack:table, stackAnim:table, stackAnimCallback:ifunction, stackIM:table, modifierList:table, modifierCount:number)
-- Reset stack instances
stackIM:ResetInstances();
-- Reset anim to make sure the list isn't hidden
stackAnim:Stop();
stackAnim:SetToBeginning();
-- Add modifiers to stack
local shouldPlayAnim:boolean = false;
local nextIndex = 0;
for i=startIndex,modifierCount,1 do
if modifierList[i] ~= nil then
local modifierEntry = modifierList[i];
if not AddModifierToStack(stack, stackIM, modifierEntry["text"], modifierEntry["icon"], stackAnim:GetSizeY()) then
nextIndex = i;
break;
end
-- If we hit the end of the list then reset the next index
if i == modifierCount then
nextIndex = 0;
end
end
end
-- Calculate size and unhide panel
stack:CalculateSize();
-- Determine if we have other stat pages to display
if startIndex ~= 0 or nextIndex ~= 0 then
shouldPlayAnim = true;
end
-- Play anim if we have multiple pages
if shouldPlayAnim then
stackAnim:Play();
stackAnim:RegisterEndCallback(
function()
stackAnimCallback(nextIndex);
end
);
end
end
-- ===========================================================================
function GetCombatModifierList(combatantHash:number)
if (m_combatResults == nil) then
return;
end
local baseStrengthValue = 0;
local combatantResults = m_combatResults[combatantHash];
baseStrengthValue = combatantResults[CombatResultParameters.COMBAT_STRENGTH];
local baseStrengthText = baseStrengthValue .. " " .. Locale.Lookup("LOC_COMBAT_PREVIEW_BASE_STRENGTH");
local interceptorModifierText = combatantResults[CombatResultParameters.PREVIEW_TEXT_INTERCEPTOR];
local antiAirModifierText = combatantResults[CombatResultParameters.PREVIEW_TEXT_ANTI_AIR];
local healthModifierText = combatantResults[CombatResultParameters.PREVIEW_TEXT_HEALTH];
local terrainModifierText = combatantResults[CombatResultParameters.PREVIEW_TEXT_TERRAIN];
local opponentModifierText = combatantResults[CombatResultParameters.PREVIEW_TEXT_OPPONENT];
local modifierModifierText = combatantResults[CombatResultParameters.PREVIEW_TEXT_MODIFIER];
local flankingModifierText = combatantResults[CombatResultParameters.PREVIEW_TEXT_ASSIST];
local promotionModifierText = combatantResults[CombatResultParameters.PREVIEW_TEXT_PROMOTION];
local defenseModifierText = combatantResults[CombatResultParameters.PREVIEW_TEXT_DEFENSES];
local modifierList:table = {};
local modifierListSize:number = 0;
if (baseStrengthText ~= nil) then
modifierList, modifierListSize = AddModifierToList(modifierList, modifierListSize, baseStrengthText, "ICON_STRENGTH");
end
if (interceptorModifierText ~= nil) then
for i, item in ipairs(interceptorModifierText) do
modifierList, modifierListSize = AddModifierToList(modifierList, modifierListSize, Locale.Lookup(item), "ICON_MOVES");
end
end
if (antiAirModifierText ~= nil) then
for i, item in ipairs(antiAirModifierText) do
modifierList, modifierListSize = AddModifierToList(modifierList, modifierListSize, Locale.Lookup(item), "ICON_BOMBARD");
end
end
if (healthModifierText ~= nil) then
for i, item in ipairs(healthModifierText) do
modifierList, modifierListSize = AddModifierToList(modifierList, modifierListSize, Locale.Lookup(item), "ICON_DAMAGE");
end
end
if (terrainModifierText ~= nil) then
for i, item in ipairs(terrainModifierText) do
modifierList, modifierListSize = AddModifierToList(modifierList, modifierListSize, Locale.Lookup(item), "ICON_STATS_TERRAIN");
end
end
if (opponentModifierText ~= nil) then
for i, item in ipairs(opponentModifierText) do
modifierList, modifierListSize = AddModifierToList(modifierList, modifierListSize, Locale.Lookup(item), "ICON_STRENGTH");
end
end
if (modifierModifierText ~= nil) then
for i, item in ipairs(modifierModifierText) do
modifierList, modifierListSize = AddModifierToList(modifierList, modifierListSize, Locale.Lookup(item), "ICON_STRENGTH");
end
end
if (flankingModifierText ~= nil) then
for i, item in ipairs(flankingModifierText) do
modifierList, modifierListSize = AddModifierToList(modifierList, modifierListSize, Locale.Lookup(item), "ICON_POSITION");
end
end
if (promotionModifierText ~= nil) then
for i, item in ipairs(promotionModifierText) do
modifierList, modifierListSize = AddModifierToList(modifierList, modifierListSize, Locale.Lookup(item), "ICON_PROMOTION");
end
end
if (defenseModifierText ~= nil) then
for i, item in ipairs(defenseModifierText) do
modifierList, modifierListSize = AddModifierToList(modifierList, modifierListSize, Locale.Lookup(item), "ICON_STRENGTH");
end
end
return modifierList, modifierListSize;
end
-- ===========================================================================
function AddModifierToList(modifierList, modifierListSize, text, icon)
local modifierEntry:table = {}
modifierEntry["text"] = text;
modifierEntry["icon"] = icon;
modifierListSize = modifierListSize + 1;
modifierList[modifierListSize] = modifierEntry;
return modifierList, modifierListSize;
end
-- ===========================================================================
function AddModifierToStack(stackControl, stackIM, text, icon, maxHeight:number)
local kStat:table = stackIM:GetInstance();
kStat.ModifierText:SetText(text);
local textureOffsetX, textureOffsetY, textureSheet = IconManager:FindIconAtlas(icon,16);
kStat.ModifierIcon:SetTexture( textureOffsetX, textureOffsetY, textureSheet );
local leadingCharacter:string = string.sub(text, 0, 1);
if(string.find(text, "COLOR_GREEN") ~= nil) then
kStat.ModifierIcon:SetColorByName("StatGoodCS");
elseif(string.find(text, "COLOR_RED") ~= nil) then
kStat.ModifierIcon:SetColorByName("StatBadCS");
end
-- Determine if this instance overflows the container control
-- If so, remove instance so it can be shown on a different page
stackControl:CalculateSize();
if stackControl:GetSizeY() > maxHeight then
stackIM:ReleaseInstance(kStat);
return false;
end
return true;
end
-- ===========================================================================
function Hide()
ContextPtr:SetHide(true);
end
-- ===========================================================================
function HidePromotionPanel()
Controls.PromotionPanel:SetHide(true);
Controls.VeteranNamePanel:SetHide(true);
LuaEvents.UnitPanel_HideUnitPromotion();
end
--------------------------------------------------------------------------------
function HideVeteranNamePanel()
Controls.VeteranNamePanel:SetHide(true);
end
-- ===========================================================================
function OnToggleSecondRow()
local isHidden:boolean = Controls.SecondaryActionsStack:IsHidden();
if isHidden then
Controls.SecondaryActionsStack:SetHide(false);
Controls.ExpandSecondaryActionsButton:SetTextureOffsetVal(0,29);
else
Controls.SecondaryActionsStack:SetHide(true);
Controls.ExpandSecondaryActionsButton:SetTextureOffsetVal(0,0);
end
Controls.ExpandSecondaryActionStack:CalculateSize();
Controls.ExpandSecondaryActionStack:ReprocessAnchoring();
ResizeUnitPanelToFitActionButtons();
end
Controls.ExpandSecondaryActionsButton:RegisterCallback( Mouse.eLClick, OnToggleSecondRow );
-- ===========================================================================
function OnSecondaryActionStackMouseEnter()
Controls.ExpandSecondaryActionGrid:SetAlpha(1.0);
end
Controls.ExpandSecondaryActionsButton:RegisterMouseEnterCallback(OnSecondaryActionStackMouseEnter);
-- ===========================================================================
function OnSecondaryActionStackMouseExit()
-- If the secondary action stack is hidden then fade out the expand button
if Controls.SecondaryActionsStack:IsHidden() then
Controls.ExpandSecondaryActionGrid:SetAlpha(0.75);
end
end
Controls.ExpandSecondaryActionsButton:RegisterMouseExitCallback(OnSecondaryActionStackMouseExit);
-- ===========================================================================
function ResizeUnitPanelToFitActionButtons()
-- Resize the unit panel to fit all visible action buttons
Controls.ActionsStack:CalculateSize();
if Controls.ActionsStack:GetSizeX() > m_minUnitPanelWidth then
Controls.UnitPanelBaseContainer:SetSizeX(Controls.ActionsStack:GetSizeX() + m_resizeUnitPanelPadding);
else
Controls.UnitPanelBaseContainer:SetSizeX(m_minUnitPanelWidth);
end
-- Update unit stat size and anchoring
Controls.SubjectStatStack:CalculateSize();
Controls.SubjectStatStack:ReprocessAnchoring();
Controls.SubjectStatContainer:ReprocessAnchoring();
end
-- ===========================================================================
function GetUnitPortraitPrefix( playerID:number )
local iconPrefix:string = "ICON_";
-- Add civilization ethnicity
local playerConfig:table = PlayerConfigurations[playerID];
local civ:table = GameInfo.Civilizations[playerConfig:GetCivilizationTypeID()];
if civ then
-- Barbarians don't have an ethnicity field so make sure it exists
if civ.Ethnicity and civ.Ethnicity ~= "ETHNICITY_EURO" then
iconPrefix = iconPrefix .. civ.Ethnicity .. "_";
end
end
return iconPrefix;
end
-- ===========================================================================
function ReadUnitData( unit:table )
local unitExperience = unit:GetExperience();
local potentialDamage :number = 0;
InitSubjectData();
m_subjectData.Name = unit:GetName();
m_subjectData.UnitTypeName = GameInfo.Units[unit:GetUnitType()].Name;
m_subjectData.IconName = GetUnitPortraitPrefix(unit:GetOwner())..GameInfo.Units[unit:GetUnitType()].UnitType.."_PORTRAIT";
m_subjectData.Moves = unit:GetMovesRemaining();
m_subjectData.MovementMoves = unit:GetMovementMovesRemaining();
m_subjectData.InFormation = unit:GetFormationUnitCount() > 1;
m_subjectData.FormationMoves = unit:GetFormationMovesRemaining();
m_subjectData.FormationMaxMoves = unit:GetFormationMaxMoves();
m_subjectData.MaxMoves = unit:GetMaxMoves();
m_subjectData.Combat = unit:GetCombat();
m_subjectData.Damage = unit:GetDamage();
m_subjectData.MaxDamage = unit:GetMaxDamage();
m_subjectData.PotentialDamage = potentialDamage;
m_subjectData.RangedCombat = unit:GetRangedCombat();
m_subjectData.BombardCombat = unit:GetBombardCombat();
m_subjectData.AntiAirCombat = unit:GetAntiAirCombat();
m_subjectData.Range = unit:GetRange();
m_subjectData.Owner = unit:GetOwner();
m_subjectData.BuildCharges = unit:GetBuildCharges();
m_subjectData.SpreadCharges = unit:GetSpreadCharges();
m_subjectData.ReligiousStrength = unit:GetReligiousStrength();
m_subjectData.HasMovedIntoZOC = unit:HasMovedIntoZOC();
m_subjectData.MilitaryFormation = unit:GetMilitaryFormation();
m_subjectData.UnitType = unit:GetUnitType();
m_subjectData.UnitID = unit:GetID();
m_subjectData.UnitExperience = unitExperience:GetExperiencePoints();
m_subjectData.MaxExperience = unitExperience:GetExperienceForNextLevel();
m_subjectData.UnitLevel = unitExperience:GetLevel();
m_subjectData.CurrentPromotions = {};
m_subjectData.Actions = GetUnitActionsTable( unit );
-- Great person data
local unitGreatPerson = unit:GetGreatPerson();
if unitGreatPerson then
local individual = unitGreatPerson:GetIndividual();
local greatPersonInfo = GameInfo.GreatPersonIndividuals[individual];
local gpClass = GameInfo.GreatPersonClasses[unitGreatPerson:GetClass()];
if unitGreatPerson:HasPassiveEffect() then
m_subjectData.GreatPersonPassiveText = unitGreatPerson:GetPassiveEffectText();
m_subjectData.GreatPersonPassiveName = unitGreatPerson:GetPassiveNameText();
end
m_subjectData.GreatPersonActionCharges = unitGreatPerson:GetActionCharges();
end
local promotionList :table = unitExperience:GetPromotions();
local i=0;
for i, promotion in ipairs(promotionList) do
local promotionDef = GameInfo.UnitPromotions[promotion];
table.insert(m_subjectData.CurrentPromotions, {
Name = promotionDef.Name,
Desc = promotionDef.Description,
Level = promotionDef.Level
});
end
m_subjectData.StatData = FilterUnitStatsFromUnitData(m_subjectData);
-- Espionage Data
if (GameInfo.Units[m_subjectData.UnitType].Spy == true) then
m_subjectData.IsSpy = true;
local activityType:number = UnitManager.GetActivityType(unit);
if activityType == ActivityTypes.ACTIVITY_OPERATION then
m_subjectData.SpyOperation = unit:GetSpyOperation();
if (m_subjectData.SpyOperation ~= -1) then
local spyPlot:table = Map.GetPlot(unit:GetX(), unit:GetY());
local targetCity:table = Cities.GetPlotPurchaseCity(spyPlot);
if targetCity then
m_subjectData.SpyTargetCityName = targetCity:GetName();
m_subjectData.SpyTargetOwnerID = targetCity:GetOwner();
end
m_subjectData.SpyRemainingTurns = unit:GetSpyOperationEndTurn() - Game.GetCurrentGameTurn();
m_subjectData.SpyTotalTurns = UnitManager.GetTimeToComplete(m_subjectData.SpyOperation, unit);
end
end
end
if (GameInfo.Units[m_subjectData.UnitType].MakeTradeRoute == true) then
m_subjectData.IsTradeUnit = true;
-- Get trade route name
local owningPlayer:table = Players[unit:GetOwner()];
local cities:table = owningPlayer:GetCities();
for _, city in cities:Members() do
local outgoingRoutes:table = city:GetTrade():GetOutgoingRoutes();
for i,route in ipairs(outgoingRoutes) do
if m_subjectData.UnitID == route.TraderUnitID then
-- Find origin city
local originCity:table = cities:FindID(route.OriginCityID);
-- Find destination city
local destinationPlayer:table = Players[route.DestinationCityPlayer];
local destinationCities:table = destinationPlayer:GetCities();
local destinationCity:table = destinationCities:FindID(route.DestinationCityID);
-- Set origin to destination name
if originCity and destinationCity then
m_subjectData.TradeRouteName = Locale.Lookup("LOC_HUD_UNIT_PANEL_TRADE_ROUTE_NAME", originCity:GetName(), destinationCity:GetName());
local civID:number = PlayerConfigurations[destinationCity:GetOwner()]:GetCivilizationTypeID();
local civ:table = GameInfo.Civilizations[civID];
if civ then
m_subjectData.TradeRouteIcon = "ICON_" .. civ.CivilizationType;
end
end
end
end
end
local playerTrade:table = owningPlayer:GetTrade();
if playerTrade then
-- Get land range
m_subjectData.TradeLandRange = playerTrade:GetLandRangeRefuel();
-- Get sea range
m_subjectData.TradeSeaRange = playerTrade:GetWaterRangeRefuel();
end
end
-- Check if we're a settler
if (GameInfo.Units[m_subjectData.UnitType].FoundCity == true) then
m_subjectData.IsSettler = true;
end
View(m_subjectData);
end
-- ===========================================================================
function ReadDistrictData( pDistrict:table )
if (pDistrict ~= nil) then
InitSubjectData();
local parentCity = pDistrict:GetCity();
local districtName;
if (parentCity ~= nil) then
districtName = Locale.Lookup(parentCity:GetName());
end
local eDistrictType = pDistrict:GetType();
if (not GameInfo.Districts[eDistrictType].CityCenter) then
local districtTypeName = Locale.Lookup(GameInfo.Districts[eDistrictType].Name);
districtName = districtName .. " " .. districtTypeName;
end
-- district data
m_subjectData.Name = districtName;
m_subjectData.Combat = pDistrict:GetDefenseStrength();
m_subjectData.RangedCombat = pDistrict:GetAttackStrength();
m_subjectData.Damage = pDistrict:GetDamage(DefenseTypes.DISTRICT_GARRISON);
m_subjectData.MaxDamage = pDistrict:GetMaxDamage(DefenseTypes.DISTRICT_GARRISON);
m_subjectData.WallDamage = pDistrict:GetDamage(DefenseTypes.DISTRICT_OUTER);
m_subjectData.MaxWallDamage = pDistrict:GetMaxDamage(DefenseTypes.DISTRICT_OUTER);
m_primaryColor, m_secondaryColor = UI.GetPlayerColors( pDistrict:GetOwner() );
local leader:string = PlayerConfigurations[pDistrict:GetOwner()]:GetLeaderTypeName();
if GameInfo.CivilizationLeaders[leader] == nil then
UI.DataError("Banners found a leader \""..leader.."\" which is not/no longer in the game; icon may be whack.");
else
if(GameInfo.CivilizationLeaders[leader].CivilizationType ~= nil) then
local civIconName = "ICON_"..GameInfo.CivilizationLeaders[leader].CivilizationType;
m_subjectData.CivIconName = civIconName;
end
end
View(m_subjectData);
end
end
-- ===========================================================================
function Refresh(player, unitId)
if(player ~= nil and player ~= -1 and unitId ~= nil and unitId ~= -1) then
m_kHotkeyActions = {};
m_kHotkeyCV1 = {};
m_kHotkeyCV2 = {};
m_kSoundCV1 = {};
local units = Players[player]:GetUnits();
local unit = units:FindID(unitId);
if(unit ~= nil) then
ReadUnitData( unit, numUnits );
--CQUI auto-expando
if(GameConfiguration.GetValue("CQUI_AutoExpandUnitActions")) then
local isHidden:boolean = Controls.SecondaryActionsStack:IsHidden();
if isHidden then
Controls.SecondaryActionsStack:SetHide(false);
Controls.ExpandSecondaryActionsButton:SetTextureOffsetVal(0,29);
OnSecondaryActionStackMouseEnter();
Controls.ExpandSecondaryActionStack:CalculateSize();
Controls.ExpandSecondaryActionStack:ReprocessAnchoring();
end
ResizeUnitPanelToFitActionButtons();
end
-- UI.SetRenderGameObject( Controls.PortraitFrame ,unit);
else
Hide();
end
else
Hide();
end
end
-- ===========================================================================
function OnRefresh()
ContextPtr:ClearRequestRefresh(); -- Clear the refresh request, in case we got here from some other means. This cuts down on redundant updates.
Refresh(m_selectedPlayerId, m_UnitId);
local pSelectedUnit :table= UI.GetHeadSelectedUnit();
if pSelectedUnit ~= nil then
if not ( pSelectedUnit:GetMovesRemaining() > 0 ) then
UILens.ClearLayerHexes( LensLayers.MOVEMENT_RANGE );
UILens.ClearLayerHexes( LensLayers.MOVEMENT_ZONE_OF_CONTROL );
end
end
end
-- ===========================================================================
function OnBeginWonderReveal()
Hide();
end
-------------------------------------------------------------------------------
function OnUnitSelectionChanged(player, unitId, locationX, locationY, locationZ, isSelected, isEditable)
--print("UnitPanel::OnUnitSelectionChanged(): ",player,unitId,isSelected);
if (isSelected) then
m_selectedPlayerId = player;
m_UnitId = unitId;
m_primaryColor, m_secondaryColor = UI.GetPlayerColors( m_selectedPlayerId );
m_combatResults = nil;
Refresh(m_selectedPlayerId, m_UnitId)
Controls.UnitPanelAlpha:SetToBeginning();
Controls.UnitPanelAlpha:Play();
Controls.UnitPanelSlide:SetToBeginning();
Controls.UnitPanelSlide:Play();
else
m_selectedPlayerId = nil;
m_UnitId = nil;
m_primaryColor = 0xdeadbeef;
m_secondaryColor = 0xbaadf00d;
-- This event is raised on deselected units too; only hide if there
-- is no selected units left.
if (UI.GetHeadSelectedUnit() == nil) then
Hide();
end
end
end
-------------------------------------------------------------------------------
-- Additional events to listen to in order to invalidate the data.
function OnUnitDamageChanged(player, unitId, damage)
if(player == m_selectedPlayerId and unitId == m_UnitId) then
Controls.UnitHealthMeter:SetAnimationSpeed( ANIMATION_SPEED );
ContextPtr:RequestRefresh(); -- Set a refresh request, the UI will update on the next frame.
end
end
-------------------------------------------------------------------------------
function OnUnitMoveComplete(player, unitId, x, y)
if(player == m_selectedPlayerId and unitId == m_UnitId) then
ContextPtr:RequestRefresh(); -- Set a refresh request, the UI will update on the next frame.
end
end
-------------------------------------------------------------------------------
function OnUnitOperationDeactivated(player, unitId, hOperation, iData1)
if(player == m_selectedPlayerId and unitId == m_UnitId) then
ContextPtr:RequestRefresh(); -- Set a refresh request, the UI will update on the next frame.
end
end
-------------------------------------------------------------------------------
function OnUnitOperationsCleared(player, unitId, hOperation, iData1)
if(player == m_selectedPlayerId and unitId == m_UnitId) then
ContextPtr:RequestRefresh(); -- Set a refresh request, the UI will update on the next frame.
end
end
-------------------------------------------------------------------------------
function OnUnitOperationAdded(player, unitId, hOperation)
if(player == m_selectedPlayerId and unitId == m_UnitId) then
ContextPtr:RequestRefresh(); -- Set a refresh request, the UI will update on the next frame.
end
end
-------------------------------------------------------------------------------
function OnUnitCommandStarted(player, unitId, hCommand, iData1)
if(player == m_selectedPlayerId and unitId == m_UnitId) then
ContextPtr:RequestRefresh(); -- Set a refresh request, the UI will update on the next frame.
end
end
-------------------------------------------------------------------------------
function OnUnitChargesChanged(player, unitId)
if(player == m_selectedPlayerId and unitId == m_UnitId) then
ContextPtr:RequestRefresh(); -- Set a refresh request, the UI will update on the next frame.
end
end
-------------------------------------------------------------------------------
function OnUnitPromotionChanged(player, unitId)
if(player == m_selectedPlayerId and unitId == m_UnitId) then
ContextPtr:RequestRefresh(); -- Set a refresh request, the UI will update on the next frame.
end
end
--------------------------------------------------------------------------------
-- UnitAction<idx> was clicked.
--------------------------------------------------------------------------------
function OnUnitActionClicked( actionType:number, actionHash:number )
if m_isOkayToProcess then
local pSelectedUnit :table= UI.GetHeadSelectedUnit();
if (pSelectedUnit ~= nil) then
if (actionType == UnitCommandTypes.TYPE) then
local eInterfaceMode = InterfaceModeTypes.NONE;
local interfaceMode = GameInfo.UnitCommands[actionHash].InterfaceMode;
if (interfaceMode) then
eInterfaceMode = DB.MakeHash(interfaceMode);
end
if (eInterfaceMode ~= InterfaceModeTypes.NONE) then
-- Must change to the interface mode or if we are already in that mode, the user wants to cancel.
if (UI.GetInterfaceMode() == eInterfaceMode) then
UI.SetInterfaceMode(InterfaceModeTypes.SELECTION);
else
UI.SetInterfaceMode(eInterfaceMode);
end
else
-- No mode needed, just do the operation
UnitManager.RequestCommand( pSelectedUnit, actionHash );
end
else
if (actionType == UnitOperationTypes.TYPE) then
local eInterfaceMode = InterfaceModeTypes.NONE;
local interfaceMode = GameInfo.UnitOperations[actionHash].InterfaceMode;
if (interfaceMode) then
eInterfaceMode = DB.MakeHash(interfaceMode);
end
if (eInterfaceMode ~= InterfaceModeTypes.NONE) then
-- Must change to the interface mode or if we are already in that mode, the user wants to cancel.
if (UI.GetInterfaceMode() == eInterfaceMode) then
UI.SetInterfaceMode(InterfaceModeTypes.SELECTION);
else
local tParameters = {};
tParameters[UnitOperationTypes.PARAM_OPERATION_TYPE] = actionHash;
UI.SetInterfaceMode(eInterfaceMode, tParameters);
end
else
-- No mode needed, just do the operation
UnitManager.RequestOperation( pSelectedUnit, actionHash );
end
end
end
end
else
print("OnUnitActionClicked() but it's currently not okay to process. (Which is fine; unless it's the player's turn.)");
end
end
-- ===========================================================================
-- UnitAction<BuildImprovement> was clicked.
-- ===========================================================================
function OnUnitActionClicked_BuildImprovement( improvementHash, dummy )
if (m_isOkayToProcess) then
local pSelectedUnit = UI.GetHeadSelectedUnit();
if (pSelectedUnit ~= nil) then
local tParameters = {};
tParameters[UnitOperationTypes.PARAM_X] = pSelectedUnit:GetX();
tParameters[UnitOperationTypes.PARAM_Y] = pSelectedUnit:GetY();
tParameters[UnitOperationTypes.PARAM_IMPROVEMENT_TYPE] = improvementHash;
UnitManager.RequestOperation( pSelectedUnit, UnitOperationTypes.BUILD_IMPROVEMENT, tParameters );
end
ContextPtr:RequestRefresh();
end
end
-- ===========================================================================
-- UnitAction<WMDStrike> was clicked.
-- ===========================================================================
function OnUnitActionClicked_WMDStrike( eWMD, dummy )
if (m_isOkayToProcess) then
local pSelectedUnit = UI.GetHeadSelectedUnit();
if (pSelectedUnit ~= nil) then
local tParameters = {};
tParameters[UnitOperationTypes.PARAM_WMD_TYPE] = eWMD;
UI.SetInterfaceMode(InterfaceModeTypes.WMD_STRIKE, tParameters);
end
ContextPtr:RequestRefresh();
end
end
-- ===========================================================================
-- Cancel action button was clicked for a spy
-- ===========================================================================
function OnUnitActionClicked_CancelSpyMission( actionHash, dummy )
if (m_isOkayToProcess) then
local pSelectedUnit = UI.GetHeadSelectedUnit();
if (pSelectedUnit ~= nil) then
LuaEvents.UnitPanel_CancelMission(pSelectedUnit:GetID());
end
end
end
-- ===========================================================================
-- UnitAction<EnterFormation> was clicked.
-- ===========================================================================
function OnUnitActionClicked_EnterFormation( unitInstance )
if (m_isOkayToProcess) then
local pSelectedUnit = UI.GetHeadSelectedUnit();
if ( pSelectedUnit ~= nil and unitInstance ~= nil ) then
local tParameters = {};
tParameters[UnitCommandTypes.PARAM_UNIT_PLAYER] = unitInstance:GetOwner();
tParameters[UnitCommandTypes.PARAM_UNIT_ID] = unitInstance:GetID();
UnitManager.RequestCommand( pSelectedUnit, UnitCommandTypes.ENTER_FORMATION, tParameters );
end
end
end
-- ===========================================================================
-- UnitAction<MoveTo> was clicked.
-- ===========================================================================
function OnUnitActionClicked_MoveTo()
UI.SetInterfaceMode(InterfaceModeTypes.MOVE_TO);
end
-- ===========================================================================
-- UnitAction<FoundCity> was clicked.
-- ===========================================================================
function OnUnitActionClicked_FoundCity()
if (m_isOkayToProcess) then
local pSelectedUnit = UI.GetHeadSelectedUnit();
if ( pSelectedUnit ~= nil ) then
UnitManager.RequestOperation( pSelectedUnit, UnitOperationTypes.FOUND_CITY );
end
end
if UILens.IsLayerOn( LensLayers.HEX_COLORING_WATER_AVAILABLITY ) then
UILens.ToggleLayerOff(LensLayers.HEX_COLORING_WATER_AVAILABLITY);
end
UILens.SetActive("Default");
end
-- ===========================================================================
-- UnitAction<Promote> was clicked.
-- ===========================================================================
function ShowPromotionsList(tPromotions)
local pUnit :table = UI.GetHeadSelectedUnit();
if m_isOkayToProcess then
local unitType = pUnit:GetUnitType();
if GameInfo.Units[unitType].NumRandomChoices > 0 then
m_PromotionListInstanceMgr:ResetInstances();
for i, item in ipairs(tPromotions) do
local promotionInstance = m_PromotionListInstanceMgr:GetInstance();
local promotionDefinition = GameInfo.UnitPromotions[item];
if (promotionDefinition ~= nil) then
promotionInstance.PromotionName:SetText(Locale.Lookup(promotionDefinition.Name));
promotionInstance.PromotionDescription:SetText(Locale.Lookup(promotionDefinition.Description));
local promotionTierStr :string;
if (promotionDefinition.Level == 1) then
promotionTierStr = "I";
elseif (promotionDefinition.Level == 2) then
promotionTierStr = "II";
elseif (promotionDefinition.Level == 3) then
promotionTierStr = "III";
elseif (promotionDefinition.Level == 4) then
promotionTierStr = "IV";
elseif (promotionDefinition.Level == 5) then
promotionTierStr = "V";
end
promotionInstance.PromotionTier:SetText(promotionTierStr);
end
local ePromotion = item;
promotionInstance.PromotionSlot:RegisterCallback( Mouse.eLClick, OnPromoteUnit );
promotionInstance.PromotionSlot:SetVoid1( ePromotion );
end
Controls.PromotionList:CalculateSize();
Controls.PromotionScrollPanel:CalculateInternalSize();
Controls.PromotionList:ReprocessAnchoring();
Controls.PromotionPanel:SetHide(false);
local pUnit = UI.GetHeadSelectedUnit();
if (pUnit ~= nil) then
local bCanStart = UnitManager.CanStartCommand( pUnit, UnitCommandTypes.NAME_UNIT, true);
if (bCanStart) then
local yOffset = Controls.PromotionPanel:GetSizeY();
Controls.VeteranNamePanel:SetOffsetY(yOffset);
Controls.VeteranNamePanel:SetHide(false);
RandomizeName();
else
Controls.VeteranNamePanel:SetOffsetY(0);
Controls.VeteranNamePanel:SetHide(true);
end
end
else
LuaEvents.UnitPanel_PromoteUnit();
end
end
end
--------------------------------------------------------------------------------
-- Selected Promotion was clicked.
--------------------------------------------------------------------------------
function OnPromoteUnit(ePromotion)
if (m_isOkayToProcess) then
local pSelectedUnit = UI.GetHeadSelectedUnit();
if (pSelectedUnit ~= nil) then
local tParameters = {};
tParameters[UnitCommandTypes.PARAM_PROMOTION_TYPE] = ePromotion;
UnitManager.RequestCommand( pSelectedUnit, UnitCommandTypes.PROMOTE, tParameters );
end
end
end
-- ===========================================================================
-- Prompt if the player really wants to force remove a unit.
-- ===========================================================================
function OnPromptToDeleteUnit()
local pUnit :table = UI.GetHeadSelectedUnit();
if(pUnit) then
local unitName :string = GameInfo.Units[pUnit:GetUnitType()].Name;
local msg :string = Locale.Lookup("LOC_HUD_UNIT_PANEL_ARE_YOU_SURE_DELETE", unitName);
-- Pass the unit ID through, the user can take their time in the dialog and it is possible that the selected unit will change
local unitID = pUnit:GetComponentID();
OnDeleteUnit(unitID);
end
end
-- ===========================================================================
-- Delete the unit
-- Resets lens to turn off any that are for the unit (e.g., settler)
-- ===========================================================================
function OnDeleteUnit(unitID : table)
local pUnit :table = UnitManager.GetUnit(unitID.player, unitID.id);
if (pUnit ~= nil) then
UnitManager.RequestCommand( pUnit, UnitCommandTypes.DELETE );
end
-- TODO: Re-eval if below is needed, SelectedUnit may now handle this even with kUnit==nil there:
if UILens.IsLayerOn( LensLayers.HEX_COLORING_WATER_AVAILABLITY ) then
UILens.ToggleLayerOff( LensLayers.HEX_COLORING_WATER_AVAILABLITY );
elseif UILens.IsLayerOn( LensLayers.HEX_COLORING_GREAT_PEOPLE ) then
UILens.ToggleLayerOff( LensLayers.HEX_COLORING_GREAT_PEOPLE );
elseif UILens.IsLayerOn( LensLayers.HEX_COLORING_RELIGION ) then
UILens.ToggleLayerOff( LensLayers.HEX_COLORING_RELIGION );
end
UILens.SetActive("Default");
end
--------------------------------------------------------------------------------
-- Unit Veterancy / Unique name
---------------------------------------------------------------------------------
function OnNameUnit()
local pUnit = UI.GetHeadSelectedUnit();
if (pUnit ~= nil) then
Controls.VeteranNamePanel:SetOffsetY(0);
Controls.VeteranNamePanel:SetHide(false);
RandomizeName();
end
end
--------------------------------------------------------------------------------
function RandomizeName()
local pUnit = UI.GetHeadSelectedUnit();
if (pUnit ~= nil) then
m_namePrefix = GetRandomNamePrefix();
m_nameSuffix = GetRandomNameSuffix();
m_FullVeteranName = string.format("{LOC_UNITNAME_BASE_TEMPLATE << {%s} << {%s}}", m_namePrefix, m_nameSuffix);
Controls.VeteranNameField:SetText(Locale.Lookup(m_FullVeteranName));
end
end
--------------------------------------------------------------------------------
function RandomizeNamePrefix()
m_namePrefix = GetRandomNamePrefix();
m_FullVeteranName = string.format("{LOC_UNITNAME_BASE_TEMPLATE << {%s} << {%s}}", m_namePrefix, m_nameSuffix);
Controls.VeteranNameField:SetText(Locale.Lookup(m_FullVeteranName));
end
--------------------------------------------------------------------------------
function RandomizeNameSuffix()
local pUnit = UI.GetHeadSelectedUnit();
if (pUnit ~= nil) then
m_nameSuffix = GetRandomNameSuffix();
m_FullVeteranName = string.format("{LOC_UNITNAME_BASE_TEMPLATE << {%s} << {%s}}", m_namePrefix, m_nameSuffix);
Controls.VeteranNameField:SetText(Locale.Lookup(m_FullVeteranName));
end
end
--------------------------------------------------------------------------------
function GetRandomNamePrefix()
if (m_PrefixNames == nil) then
m_PrefixNames = MakeUnitNameTable( "PREFIX_ALL" );
end
local prefixIndex = math.random(#m_PrefixNames);
local prefixTextKey = m_PrefixNames[prefixIndex];
return prefixTextKey;
end
--------------------------------------------------------------------------------
function GetRandomNameSuffix()
if (m_SuffixNames == nil) then
m_SuffixNames = MakeUnitNameTable( "SUFFIX_ALL" );
end
local suffixIndex = math.random(#m_SuffixNames);
local suffixTextKey = m_SuffixNames[suffixIndex];
local pUnit = UI.GetHeadSelectedUnit();
if (pUnit ~= nil) then
local unitClass = GameInfo.Units[pUnit:GetUnitType()].PromotionClass;
local unitDomain = GameInfo.Units[pUnit:GetUnitType()].Domain;
if (unitDomain == "DOMAIN_LAND") then
if (unitClass == "PROMOTION_CLASS_RECON") then
if (m_SuffixNamesRecon == nil) then
m_SuffixNamesRecon = MakeUnitNameTable( "SUFFIX_RECON" );
end
suffixIndex = math.random(#m_SuffixNamesRecon);
suffixTextKey = m_SuffixNamesRecon[suffixIndex];
elseif (unitClass == "PROMOTION_CLASS_LIGHT_CAVALRY" or unitClass == "PROMOTION_CLASS_HEAVY_CAVALRY") then
if (m_SuffixNamesCavalry == nil) then
m_SuffixNamesCavalry = MakeUnitNameTable( "SUFFIX_CAVALRY" );
end
suffixIndex = math.random(#m_SuffixNamesCavalry);
suffixTextKey = m_SuffixNamesCavalry[suffixIndex];
elseif (unitClass == "PROMOTION_CLASS_RANGED" or unitClass == "PROMOTION_CLASS_SIEGE") then
if (m_SuffixNamesRanged == nil) then
m_SuffixNamesRanged = MakeUnitNameTable( "SUFFIX_RANGED" );
end
suffixIndex = math.random(#m_SuffixNamesRanged);
suffixTextKey = m_SuffixNamesRanged[suffixIndex];
end
elseif (unitDomain == "DOMAIN_SEA") then
if (m_SuffixNamesNaval == nil) then
m_SuffixNamesNaval = MakeUnitNameTable( "SUFFIX_NAVAL" );
end
suffixIndex = math.random(#m_SuffixNamesNaval);
suffixTextKey = m_SuffixNamesNaval[suffixIndex];
elseif (unitDomain == "DOMAIN_AIR") then
if (m_SuffixNamesAir == nil) then
m_SuffixNamesAir = MakeUnitNameTable( "SUFFIX_AIR" );
end
suffixIndex = math.random(#m_SuffixNamesAir);
suffixTextKey = m_SuffixNamesAir[suffixIndex];
end
end
return suffixTextKey;
end
--------------------------------------------------------------------------------
function ConfirmVeteranName()
local pSelectedUnit = UI.GetHeadSelectedUnit();
if (pSelectedUnit ~= nil) then
local tParameters = {};
tParameters[UnitCommandTypes.PARAM_NAME] = m_FullVeteranName;
if (m_FullVeteranName ~= "") then
UnitManager.RequestCommand( pSelectedUnit, UnitCommandTypes.NAME_UNIT, tParameters );
end
end
Controls.VeteranNamePanel:SetHide(true);
UI.PlaySound("Receive_Map_Boost");
end
--------------------------------------------------------------------------------
function EditCustomVeteranName()
m_FullVeteranName = Controls.VeteranNameField:GetText();
end
--------------------------------------------------------------------------------
function MakeUnitNameTable( nameType :string )
local unitNameTable :table = {};
for row in GameInfo.UnitNames() do
if ( row.NameType == nameType ) then
table.insert( unitNameTable, row.TextKey );
end
end
return unitNameTable;
end
-- ===========================================================================
function OnPlayerTurnDeactivated( ePlayer:number )
if ePlayer == Game.GetLocalPlayer() then
m_isOkayToProcess = false;
end
end
-- ===========================================================================
function OnPlayerTurnActivated( ePlayer:number, isFirstTime:boolean )
if ePlayer == Game.GetLocalPlayer() then
ShowHideSelectedUnit();
end
end
-- ===========================================================================
function OnPlayerChangeClose( ePlayer:number )
local isPaused:boolean = GameConfiguration.IsPaused();
print("OnPlayerChangeClose: " .. ePlayer .. ", GameConfiguration.IsPaused()=" .. tostring(isPaused));
if(isPaused) then
Events.GameConfigChanged.Add(OnGameConfigChanged_Hotseat_Paused);
end
end
-- ===========================================================================
function OnGameConfigChanged_Hotseat_Paused()
Events.GameConfigChanged.Remove(OnGameConfigChanged_Hotseat_Paused);
if(not GameConfiguration.IsPaused()) then
ShowHideSelectedUnit();
end
end
-- ===========================================================================
function ShowHideSelectedUnit()
m_isOkayToProcess = true;
local pSelectedUnit :table = UI.GetHeadSelectedUnit();
if pSelectedUnit ~= nil then
m_selectedPlayerId = pSelectedUnit:GetOwner();
m_UnitId = pSelectedUnit:GetID();
m_primaryColor, m_secondaryColor= UI.GetPlayerColors( m_selectedPlayerId );
Refresh( m_selectedPlayerId, m_UnitId );
else
Hide();
end
end
-- ===========================================================================
function OnPantheonFounded( ePlayer:number )
if(ePlayer == m_selectedPlayerId) then
ContextPtr:RequestRefresh(); -- Set a refresh request, the UI will update on the next frame.
end
end
-- ===========================================================================
function OnPhaseBegin()
ContextPtr:RequestRefresh();
end
-- ===========================================================================
function OnContextInitialize( isHotload : boolean)
if isHotload then
OnPlayerTurnActivated( Game.GetLocalPlayer(), true ) ; -- Fake player activated call.
end
end
-- ===========================================================================
function OnCitySelectionChanged(owner, ID, i, j, k, bSelected, bEditable)
Hide();
end
-- ===========================================================================
-- Game Engine Event
-- Called in response to when a religion unit activates a charge.
-- ===========================================================================
function OnCityReligionFollowersChanged( playerID: number, cityID : number, eVisibility : number, city)
--print("OnCityReligionFollowersChanged",playerID, cityID , eVisibility , city);
end
-- ===========================================================================
-- Game Engine Event
-- Called in response to when a Great Work is moved.
-- ===========================================================================
function OnGreatWorkMoved(fromCityOwner, fromCityID, toCityOwner, toCityID, buildingID, greatWorkType)
if(fromCityOwner == m_selectedPlayerId or toCityOwner == m_selectedPlayerId) then
ContextPtr:RequestRefresh(); -- Set a refresh request, the UI will update on the next frame.
end
end
-- ===========================================================================
-- Input Hotkey Event
-- ===========================================================================
function OnInputActionTriggered( actionId )
if ( not m_isOkayToProcess or ContextPtr:IsHidden() ) then
return;
end
-- If an entry with this actionId exists, call the function associated with it.
if m_kHotkeyActions[actionId] ~= nil then
UI.PlaySound("Play_UI_Click");
if m_kSoundCV1[actionId] ~= nil and m_kSoundCV1[actionId] ~= "" then
UI.PlaySound(m_kSoundCV1[actionId]);
end
m_kHotkeyActions[actionId](m_kHotkeyCV1[actionId], m_kHotkeyCV2[actionId]);
end
-- "Delete" Hotkey doesn't appear in UnitOperations.xml, we need to hotwire it here
if m_DeleteHotkeyId ~= nil and (actionId == m_DeleteHotkeyId) then
OnPromptToDeleteUnit();
end
-- "Attack" Hotkey is pressed; should only work if combat evaluation is displayed. There is no action for basic attacks, necissitating this special case.
if m_combatResults ~= nil and m_AttackHotkeyId ~= nil and (actionId == m_AttackHotkeyId) then
MoveUnitToPlot( UI.GetHeadSelectedUnit(), m_locX, m_locY );
end
end
-- ===========================================================================
function OnUnitRemovedFromMap( playerID: number, unitID : number )
if(playerID == m_selectedPlayerId and unitID == m_UnitId) then
Hide();
end
end
-- ===========================================================================
function ShowCombatAssessment( )
--visualize the combat differences
if (m_combatResults ~= nil) then
local attacker = m_combatResults[CombatResultParameters.ATTACKER];
local defender = m_combatResults[CombatResultParameters.DEFENDER];
local iAttackerCombatStrength = attacker[CombatResultParameters.COMBAT_STRENGTH];
local iDefenderCombatStrength = defender[CombatResultParameters.COMBAT_STRENGTH];
local iAttackerBonus = attacker[CombatResultParameters.STRENGTH_MODIFIER];
local iDefenderBonus = defender[CombatResultParameters.STRENGTH_MODIFIER];
local iAttackerStrength = iAttackerCombatStrength + iAttackerBonus;
local iDefenderStrength = iDefenderCombatStrength + iDefenderBonus;
local extraDamage;
local isSafe = false;
for row in GameInfo.GlobalParameters() do
if(row.Name == "COMBAT_MAX_EXTRA_DAMAGE") then
extraDamage = row.Value;
break;
end
end
if (attacker[CombatResultParameters.FINAL_DAMAGE_TO] + (extraDamage/2) < attacker[CombatResultParameters.MAX_HIT_POINTS]) then
isSafe = true;
end
local combatAssessmentStr :string = "";
local damageToDefender = defender[CombatResultParameters.DAMAGE_TO];
local defenseDamageToDefender = defender[CombatResultParameters.DEFENSE_DAMAGE_TO];
local defenderHitpoints = defender[CombatResultParameters.MAX_HIT_POINTS];
local damagePercentToDefender = (damageToDefender / defenderHitpoints) * 100;
local damageToAttacker = attacker[CombatResultParameters.DAMAGE_TO];
local attackerHitpoints = attacker[CombatResultParameters.MAX_HIT_POINTS];
local damagePercentToAttacker = (damageToAttacker / attackerHitpoints) * 100;
local combatType = m_combatResults[CombatResultParameters.COMBAT_TYPE];
if (damageToDefender > 0) then
-- BPF: if it's a ranged attack we want to display the outcome differently because there is no reciprocal attack
if ( combatType == CombatTypes.RANGED or combatType == CombatTypes.BOMBARD ) then
-- if attacking a defensible district, show a different outcome
if (defender[CombatResultParameters.MAX_DEFENSE_HIT_POINTS] > 0) then
if (damageToDefender > defenseDamageToDefender) then
if (defender[CombatResultParameters.FINAL_DAMAGE_TO] >= defenderHitpoints) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_TOTAL_CITY_DAMAGE");
ShowCombatVictoryBanner();
else
if (damagePercentToDefender < 25) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MINOR_CITY_DAMAGE");
ShowCombatStalemateBanner();
else
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MAJOR_CITY_DAMAGE");
ShowCombatVictoryBanner();
end
end
else
local defenseHitpoints = defender[CombatResultParameters.MAX_DEFENSE_HIT_POINTS];
local damagePercentToDefenses = (defenseDamageToDefender / defenseHitpoints) * 100;
if (defender[CombatResultParameters.FINAL_DEFENSE_DAMAGE_TO] >= defenseHitpoints) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_TOTAL_WALL_DAMAGE");
ShowCombatVictoryBanner();
else
if (damagePercentToDefenses < 25) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MINOR_WALL_DAMAGE");
ShowCombatStalemateBanner();
else
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MAJOR_WALL_DAMAGE");
ShowCombatVictoryBanner();
end
end
end
else
if (defender[CombatResultParameters.FINAL_DAMAGE_TO] >= defenderHitpoints) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_DECISIVE_VICTORY");
ShowCombatVictoryBanner();
else
if (damagePercentToDefender < 25) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MINOR_VICTORY");
ShowCombatStalemateBanner();
else
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MAJOR_VICTORY");
ShowCombatVictoryBanner();
end
end
end
else --non ranged attacks
if (defender[CombatResultParameters.FINAL_DAMAGE_TO] >= defenderHitpoints and isSafe) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_DECISIVE_VICTORY");
ShowCombatVictoryBanner();
else
-- if the defender is a defensible district
if (defender[CombatResultParameters.MAX_DEFENSE_HIT_POINTS] > 0) then
local attackingDamage = math.max(damageToDefender, defenseDamageToDefender);
local combatDifference = attackingDamage - damageToAttacker;
if (combatDifference > 0 ) then
if (combatDifference < 3) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_STALEMATE");
ShowCombatStalemateBanner();
else
if (combatDifference < 10) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MINOR_VICTORY");
ShowCombatVictoryBanner();
else
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MAJOR_VICTORY");
ShowCombatVictoryBanner();
end
end
else
if (combatDifference > -3) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_STALEMATE");
ShowCombatStalemateBanner();
else
if (combatDifference > -10) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MINOR_DEFEAT");
ShowCombatDefeatBanner();
else
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MAJOR_DEFEAT");
ShowCombatDefeatBanner();
end
end
end
else --it's a unit
local combatDifference = damageToDefender - damageToAttacker;
if (combatDifference > 0 ) then
if (combatDifference < 3) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_STALEMATE");
ShowCombatStalemateBanner();
else
if (combatDifference < 10) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MINOR_VICTORY");
ShowCombatVictoryBanner();
else
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MAJOR_VICTORY");
ShowCombatVictoryBanner();
end
end
else
if (combatDifference > -3) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_STALEMATE");
ShowCombatStalemateBanner();
else
if (combatDifference > -10) then
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MINOR_DEFEAT");
ShowCombatDefeatBanner();
else
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_MAJOR_DEFEAT");
ShowCombatDefeatBanner();
end
end
end
end
end
end
else
combatAssessmentStr = Locale.Lookup("LOC_HUD_UNIT_PANEL_OUTCOME_INEFFECTIVE");
ShowCombatStalemateBanner();
end
Controls.CombatAssessmentText:SetText(Locale.ToUpper(combatAssessmentStr));
-- Show interceptor information
if m_targetData.InterceptorName ~= "" then
Controls.InterceptorName:SetText(m_targetData.InterceptorName);
Controls.InterceptorStrength:SetText(m_targetData.InterceptorCombat);
UpdateInterceptorModifiers(0);
-- Update interceptor health meters
local percent :number = 1 - GetPercentFromDamage( m_targetData.InterceptorDamage + m_targetData.InterceptorPotentialDamage, m_targetData.InterceptorMaxDamage);
local shadowPercent :number = 1 - GetPercentFromDamage( m_targetData.InterceptorDamage, m_targetData.InterceptorMaxDamage );
RealizeHealthMeter( Controls.InterceptorHealthMeter, percent, Controls.InterceptorHealthMeterShadow, shadowPercent );
Controls.InterceptorGrid:SetHide(false);
else
Controls.InterceptorGrid:SetHide(true);
end
-- Show anit-air information
if m_targetData.AntiAirName ~= "" then
Controls.AAName:SetText(m_targetData.AntiAirName);
Controls.AAStrength:SetText(m_targetData.AntiAirCombat);
UpdateAntiAirModifiers(0);
Controls.AAGrid:SetHide(false);
else
Controls.AAGrid:SetHide(true);
end
end
end
-- ===========================================================================
function ShowCombatStalemateBanner()
Controls.BannerDefeat:SetHide(true);
Controls.BannerStalemate:SetHide(false);
Controls.BannerVictory:SetHide(true);
end
function ShowCombatVictoryBanner()
Controls.BannerDefeat:SetHide(true);
Controls.BannerStalemate:SetHide(true);
Controls.BannerVictory:SetHide(false);
end
function ShowCombatDefeatBanner()
Controls.BannerDefeat:SetHide(false);
Controls.BannerStalemate:SetHide(true);
Controls.BannerVictory:SetHide(true);
end
-- ===========================================================================
function OnHideCombat()
Refresh(m_selectedPlayerId, m_UnitId);
Controls.UnitPanelBaseContainer:SetHide(true);
end
-- ===========================================================================
function InspectWhatsBelowTheCursor()
local localPlayerID :number = Game.GetLocalPlayer();
if (localPlayerID == -1) then
return;
end
local pPlayerVis = PlayersVisibility[localPlayerID];
if (pPlayerVis == nil) then
return false;
end
-- do not show the combat preview for non-combat units
local selectedPlayerUnit :table = UI.GetHeadSelectedUnit();
if (selectedPlayerUnit ~= nil) then
if (selectedPlayerUnit:GetCombat() == 0 and selectedPlayerUnit:GetReligiousStrength() == 0) then
return;
end
end
local plotId = UI.GetCursorPlotID();
if (plotId ~= m_plotId) then
m_plotId = plotId;
local plot = Map.GetPlotByIndex(plotId);
if plot ~= nil then
local bIsVisible = pPlayerVis:IsVisible(m_plotId);
if (bIsVisible) then
InspectPlot(plot);
else
OnShowCombat(false);
end
end
end
end
-- ===========================================================================
function GetDistrictFromCity( pCity:table )
if (pCity ~= nil) then
local cityOwner = pCity:GetOwner();
local districtId = pCity:GetDistrictID();
local pPlayer = Players[cityOwner];
if (pPlayer ~= nil) then
local pDistrict = pPlayer:GetDistricts():FindID(districtId);
if (pDistrict ~= nil) then
return pDistrict;
end
end
end
return nil;
end
-- ===========================================================================
function ReInspectWhatsBelowTheCursor()
m_plotId = INVALID_PLOT_ID;
InspectWhatsBelowTheCursor();
end
-- ===========================================================================
-- LUA Event
-- ===========================================================================
-- If mouse/touch is giving focus to a unit flag, that takes precedence over
-- the hex which may be behind the flag (likey a hex "above" the current one)
function OnUnitFlagPointerEntered( playerID:number, unitID:number )
m_isFlagFocused = true; -- Some flag (could be own) is focused.
--make sure it's not one of our units
-- And Game Core is not busy, the simulation currently needs to run on the Game Core side for accurate results.
local isValidToShow :boolean = (playerID ~= Game.GetLocalPlayer() and not UI.IsGameCoreBusy());
if (isValidToShow) then
if (UI.GetInterfaceMode() == InterfaceModeTypes.CITY_RANGE_ATTACK) then
local attackingCity = UI.GetHeadSelectedCity();
if (attackingCity ~= nil) then
local pDistrict = GetDistrictFromCity(attackingCity);
if (pDistrict ~= nil) then
local pDefender = UnitManager.GetUnit(playerID, unitID);
if (pDefender ~= nil) then
m_combatResults = CombatManager.SimulateAttackVersus( pDistrict:GetComponentID(), pDefender:GetComponentID() );
isValidToShow = ReadTargetData();
end
end
end
elseif (UI.GetInterfaceMode() == InterfaceModeTypes.DISTRICT_RANGE_ATTACK) then
local pDistrict = UI.GetHeadSelectedDistrict();
if (pDistrict ~= nil) then
local pDefender = UnitManager.GetUnit(playerID, unitID);
if (pDefender ~= nil) then
m_combatResults = CombatManager.SimulateAttackVersus( pDistrict:GetComponentID(), pDefender:GetComponentID() );
isValidToShow = ReadTargetData();
end
end
else
local attackerUnit = UI.GetHeadSelectedUnit();
if (attackerUnit ~= nil) then
-- do not show the combat preview for non-combat or embarked units
if (attackerUnit:GetCombat() == 0 and attackerUnit:GetReligiousStrength() == 0) then
return;
end
local pDefender = UnitManager.GetUnit(playerID, unitID);
if (pDefender ~= nil) then
m_combatResults = CombatManager.SimulateAttackVersus( attackerUnit:GetComponentID(), pDefender:GetComponentID() );
isValidToShow = ReadTargetData(attackerUnit);
end
end
end
end
OnShowCombat( isValidToShow );
end
-- ===========================================================================
-- LUA Event
-- ===========================================================================
function OnUnitFlagPointerExited( playerID:number, unitID:number )
m_isFlagFocused = false;
ReInspectWhatsBelowTheCursor();
end
-- ===========================================================================
-- LUA Event
-- ===========================================================================
function OnCityRangeStrikeClicked( playerID:number, unitID:number )
end
-- ===========================================================================
-- plot The plot to inspect.
-- RETURNS tree if there is something to be shown.
function InspectPlot( plot:table )
local isValidToShow = false;
local localPlayerID = Game.GetLocalPlayer();
if (localPlayerID == -1) then
return;
end
if (UI.GetInterfaceMode() == InterfaceModeTypes.CITY_RANGE_ATTACK) then
local pCity = UI.GetHeadSelectedCity();
if (pCity == nil) then
return false;
end
local pDistrict = GetDistrictFromCity(pCity);
if (pDistrict == nil) then
return false;
end
GetCombatResults( pDistrict:GetComponentID(), plot:GetX(), plot:GetY() )
isValidToShow = ReadTargetData();
elseif (UI.GetInterfaceMode() == InterfaceModeTypes.DISTRICT_RANGE_ATTACK) then
local pDistrict = UI.GetHeadSelectedDistrict();
if (pDistrict == nil) then
return false;
end
GetCombatResults( pDistrict:GetComponentID(), plot:GetX(), plot:GetY() )
isValidToShow = ReadTargetData();
else
local pUnit = UI.GetHeadSelectedUnit();
if (pUnit == nil) then
return false;
end
GetCombatResults( pUnit:GetComponentID(), plot:GetX(), plot:GetY() )
isValidToShow = ReadTargetData(pUnit);
end
OnShowCombat( isValidToShow );
end
function IsTargetCombat(targetData)
if
(
(targetData.Combat > 0)
or (targetData.RangedCombat > 0)
or (targetData.BombardCombat > 0)
) then
return true;
end
return false;
end
function IsTargetReligiousCombat(targetData)
if ( targetData.ReligiousCombat > 0 ) then
return true;
end
return false;
end
function IsAttackerCombat(attacker)
if
(
(attacker:GetCombat() > 0)
or (attacker:GetRangedCombat() > 0)
or (attacker:GetBombardCombat() > 0)
) then
return true;
end
return false;
end
function IsAttackerReligiousCombat(attacker)
if ( attacker:GetReligiousStrength() > 0 ) then
return true;
end
return false;
end
-- ===========================================================================
function ReadTargetData(attacker)
if (m_combatResults ~= nil) then
-- initialize the target object data table
InitTargetData();
local bShowTarget = false;
-- grab the defender from the combat solution table
local targetObject = m_combatResults[CombatResultParameters.DEFENDER];
if (targetObject == nil) then
return false;
end
local defenderID = targetObject[CombatResultParameters.ID];
if (defenderID.type == ComponentType.UNIT) then
local pkDefender = UnitManager.GetUnit(defenderID.player, defenderID.id);
if (pkDefender ~= nil) then
local potentialDamage = m_combatResults[CombatResultParameters.DEFENDER][CombatResultParameters.DAMAGE_TO];
local unitGreatPerson = pkDefender:GetGreatPerson();
m_targetData.Name = Locale.Lookup( pkDefender:GetName() );
m_targetData.IconName = GetUnitPortraitPrefix( pkDefender:GetOwner() )..GameInfo.Units[pkDefender:GetUnitType()].UnitType.."_PORTRAIT";
m_targetData.Combat = pkDefender:GetCombat();
m_targetData.RangedCombat = pkDefender:GetRangedCombat();
m_targetData.BombardCombat = pkDefender:GetBombardCombat();
m_targetData.AntiAirCombat = pkDefender:GetAntiAirCombat();
m_targetData.ReligiousCombat = pkDefender:GetReligiousStrength();
m_targetData.Range = pkDefender:GetRange();
m_targetData.Damage = pkDefender:GetDamage();
m_targetData.MaxDamage = pkDefender:GetMaxDamage();
m_targetData.PotentialDamage = potentialDamage;
m_targetData.BuildCharges = pkDefender:GetBuildCharges();
m_targetData.SpreadCharges = pkDefender:GetSpreadCharges();
m_targetData.ReligiousStrength = pkDefender:GetReligiousStrength();
m_targetData.GreatPersonActionCharges = unitGreatPerson:GetActionCharges();
m_targetData.Moves = pkDefender:GetMovesRemaining();
m_targetData.MaxMoves = pkDefender:GetMaxMoves();
m_targetData.UnitType = pkDefender:GetUnitType();
m_targetData.UnitID = pkDefender:GetID();
-- Only display target data if the combat type of the attacker and target match
if (attacker ~= nil) then
if
(
(IsAttackerCombat(attacker) and IsTargetCombat(m_targetData))
or (IsAttackerReligiousCombat(attacker) and IsTargetReligiousCombat(m_targetData))
) then
bShowTarget = true;
else
bShowTarget = false;
end
else
bShowTarget = true;
end
end
elseif (defenderID.type == ComponentType.DISTRICT) then
local pDefendingPlayer = Players[defenderID.player];
if (pDefendingPlayer ~= nil) then
local pDistrict = pDefendingPlayer:GetDistricts():FindID(defenderID.id);
if (pDistrict ~= nil) then
local owningCity = pDistrict:GetCity();
local targetName :string = "";
if (owningCity ~= nil) then
targetName = owningCity:GetName();
end
local combat :number = pDistrict:GetBaseDefenseStrength();
local damage :number = pDistrict:GetDamage(DefenseTypes.DISTRICT_GARRISON);
local maxDamage :number = pDistrict:GetMaxDamage(DefenseTypes.DISTRICT_GARRISON);
local wallDamage :number = pDistrict:GetDamage(DefenseTypes.DISTRICT_OUTER)
local wallMaxDamage :number = pDistrict:GetMaxDamage(DefenseTypes.DISTRICT_OUTER);
local potentialDamage :number = m_combatResults[CombatResultParameters.DEFENDER][CombatResultParameters.DAMAGE_TO];
local potentialWallDamage :number = m_combatResults[CombatResultParameters.DEFENDER][CombatResultParameters.DEFENSE_DAMAGE_TO];
-- populate the target data table
m_targetData.Name = targetName;
m_targetData.Combat = combat;
m_targetData.RangedCombat = pDistrict:GetAttackStrength();
m_targetData.Damage = damage;
m_targetData.MaxDamage = maxDamage;
m_targetData.WallDamage = wallDamage;
m_targetData.MaxWallDamage = wallMaxDamage;
m_targetData.PotentialDamage = potentialDamage;
m_targetData.PotentialWallDamage = potentialWallDamage;
m_primaryColor, m_secondaryColor = UI.GetPlayerColors( pDistrict:GetOwner() );
local leader:string = PlayerConfigurations[pDistrict:GetOwner()]:GetLeaderTypeName();
if GameInfo.CivilizationLeaders[leader] == nil then
UI.DataError("Banners found a leader \""..leader.."\" which is not/no longer in the game; icon may be whack.");
else
if(GameInfo.CivilizationLeaders[leader].CivilizationType ~= nil) then
local civIconName = "ICON_"..GameInfo.CivilizationLeaders[leader].CivilizationType;
m_targetData.CivIconName = civIconName;
end
end
bShowTarget = true;
end
end
end
local interceptorCombatResults = m_combatResults[CombatResultParameters.INTERCEPTOR];
local interceptorID = interceptorCombatResults[CombatResultParameters.ID];
local pkInterceptor = UnitManager.GetUnit(interceptorID.player, interceptorID.id);
if (pkInterceptor ~= nil) then
m_targetData.InterceptorName = Locale.Lookup(pkInterceptor:GetName());
m_targetData.InterceptorCombat = pkInterceptor:GetCombat();
m_targetData.InterceptorDamage = pkInterceptor:GetDamage();
m_targetData.InterceptorMaxDamage = pkInterceptor:GetMaxDamage();
m_targetData.InterceptorPotentialDamage = m_combatResults[CombatResultParameters.INTERCEPTOR][CombatResultParameters.DAMAGE_TO];
end
local antiAirID = m_combatResults[CombatResultParameters.ANTI_AIR][CombatResultParameters.ID];
local pkAntiAir = UnitManager.GetUnit(antiAirID.player, antiAirID.id);
if (pkAntiAir ~= nil) then
m_targetData.AntiAirName = Locale.Lookup(pkAntiAir:GetName());
m_targetData.AntiAirCombat = pkAntiAir:GetAntiAirCombat();
end
if (bShowTarget) then
ViewTarget(m_targetData);
return true;
end
end
return false;
end
-- ===========================================================================
function OnInterfaceModeChanged( eOldMode:number, eNewMode:number )
if (eNewMode == InterfaceModeTypes.CITY_RANGE_ATTACK) then
ContextPtr:SetHide(false);
local isValidToShow :boolean = (playerID ~= Game.GetLocalPlayer());
if (isValidToShow) then
local attackingCity = UI.GetHeadSelectedCity();
if (attackingCity ~= nil) then
local attackingDistrict = GetDistrictFromCity(attackingCity);
ReadDistrictData(attackingDistrict);
end
end
OnShowCombat( isValidToShow );
elseif (eNewMode == InterfaceModeTypes.DISTRICT_RANGE_ATTACK) then
ContextPtr:SetHide(false);
local isValidToShow :boolean = (playerID ~= Game.GetLocalPlayer());
if (isValidToShow) then
local attackingDistrict = UI.GetHeadSelectedDistrict();
if (attackingDistrict ~= nil) then
ReadDistrictData(attackingDistrict);
end
end
end
-- Set Make Trade Route Button Selected
if (eNewMode == InterfaceModeTypes.MAKE_TRADE_ROUTE) then
SetStandardActionButtonSelected("INTERFACEMODE_MAKE_TRADE_ROUTE", true);
elseif (eOldMode == InterfaceModeTypes.MAKE_TRADE_ROUTE) then
SetStandardActionButtonSelected("INTERFACEMODE_MAKE_TRADE_ROUTE", false);
end
-- Set Teleport To City Button Selected
if (eNewMode == InterfaceModeTypes.TELEPORT_TO_CITY) then
SetStandardActionButtonSelected("INTERFACEMODE_TELEPORT_TO_CITY", true);
elseif (eOldMode == InterfaceModeTypes.TELEPORT_TO_CITY) then
SetStandardActionButtonSelected("INTERFACEMODE_TELEPORT_TO_CITY", false);
end
-- Set SPY_TRAVEL_TO_CITY Selected
if (eNewMode == InterfaceModeTypes.SPY_TRAVEL_TO_CITY) then
SetStandardActionButtonSelected("INTERFACEMODE_SPY_TRAVEL_TO_CITY", true);
elseif (eOldMode == InterfaceModeTypes.SPY_TRAVEL_TO_CITY) then
SetStandardActionButtonSelected("INTERFACEMODE_SPY_TRAVEL_TO_CITY", false);
end
-- Set SPY_CHOOSE_MISSION Selected
if (eNewMode == InterfaceModeTypes.SPY_CHOOSE_MISSION) then
SetStandardActionButtonSelected("INTERFACEMODE_SPY_CHOOSE_MISSION", true);
elseif (eOldMode == InterfaceModeTypes.SPY_CHOOSE_MISSION) then
SetStandardActionButtonSelected("INTERFACEMODE_SPY_CHOOSE_MISSION", false);
end
-- Set REBASE Selected
if (eNewMode == InterfaceModeTypes.REBASE) then
SetStandardActionButtonSelected("INTERFACEMODE_REBASE", true);
elseif (eOldMode == InterfaceModeTypes.REBASE) then
SetStandardActionButtonSelected("INTERFACEMODE_REBASE", false);
end
-- Set DEPLOY Selected
if (eNewMode == InterfaceModeTypes.DEPLOY) then
SetStandardActionButtonSelectedByOperation("UNITOPERATION_DEPLOY", true);
elseif (eOldMode == InterfaceModeTypes.DEPLOY) then
SetStandardActionButtonSelectedByOperation("UNITOPERATION_DEPLOY", false);
end
-- Set MOVE_TO Selected
if (eNewMode == InterfaceModeTypes.MOVE_TO) then
SetStandardActionButtonSelectedByOperation("UNITOPERATION_MOVE_TO", true);
elseif (eOldMode == InterfaceModeTypes.MOVE_TO) then
SetStandardActionButtonSelectedByOperation("UNITOPERATION_MOVE_TO", false);
end
-- Set RANGE_ATTACK Selected
if (eNewMode == InterfaceModeTypes.RANGE_ATTACK) then
SetStandardActionButtonSelectedByOperation("UNITOPERATION_RANGE_ATTACK", true);
elseif (eOldMode == InterfaceModeTypes.RANGE_ATTACK) then
SetStandardActionButtonSelectedByOperation("UNITOPERATION_RANGE_ATTACK", false);
end
-- Set AIR_ATTACK Selected
if (eNewMode == InterfaceModeTypes.AIR_ATTACK) then
SetStandardActionButtonSelectedByOperation("UNITOPERATION_AIR_ATTACK", true);
elseif (eOldMode == InterfaceModeTypes.AIR_ATTACK) then
SetStandardActionButtonSelectedByOperation("UNITOPERATION_AIR_ATTACK", false);
end
if (eOldMode == InterfaceModeTypes.CITY_RANGE_ATTACK or eOldMode == InterfaceModeTypes.DISTRICT_RANGE_ATTACK) then
ContextPtr:SetHide(true);
end
end
-- ===========================================================================
function SetStandardActionButtonSelected( interfaceModeString:string, isSelected:boolean )
for i=1,m_standardActionsIM.m_iCount,1 do
local instance:table = m_standardActionsIM:GetAllocatedInstance(i);
if instance then
local actionHash = instance.UnitActionButton:GetVoid2();
local unitOperation = GameInfo.UnitOperations[actionHash];
if unitOperation then
local interfaceMode = unitOperation.InterfaceMode;
if interfaceMode == interfaceModeString then
instance.UnitActionButton:SetSelected(isSelected);
end
end
end
end
end
-- ===========================================================================
function SetStandardActionButtonSelectedByOperation( operationString:string, isSelected:boolean )
for i=1,m_standardActionsIM.m_iCount,1 do
local instance:table = m_standardActionsIM:GetAllocatedInstance(i);
if instance then
local actionHash = instance.UnitActionButton:GetTag();
local unitOperation = GameInfo.UnitOperations[actionHash];
if unitOperation then
local operation = unitOperation.OperationType;
if operation == operationString then
instance.UnitActionButton:SetSelected(isSelected);
end
end
end
end
end
-- ===========================================================================
function GetCombatResults ( attacker, locX, locY )
-- We have to ask Game Core to do an evaluation, is it busy?
if (UI.IsGameCoreBusy() == true) then
return;
end
if ( attacker == m_attackerUnit and locX == m_locX and locY == m_locY) then
return;
end
m_attackerUnit = attacker;
m_locX = locX;
m_locY = locY;
if (locX ~= nil and locY ~= nil) then
m_combatResults = CombatManager.SimulateAttackInto( attacker, locX, locY );
end
end
-- ===========================================================================
-- Input Processing
-- ===========================================================================
function OnInputHandler( pInputStruct:table )
local uiMsg = pInputStruct:GetMessageType();
-- If not the current turn or current unit is dictated by cursor/touch
-- hanging over a flag
if ( not m_isOkayToProcess or m_isFlagFocused ) then
return false;
end
-- If moved, there is a possibility of moving into a new hex.
if( uiMsg == MouseEvents.MouseMove ) then
InspectWhatsBelowTheCursor();
end
return false;
end
-- ===========================================================================
function OnUnitListPopupClicked()
-- Only refresht the unit list when it's being opened
if Controls.UnitListPopup:IsOpen() then
RefreshUnitListPopup();
end
end
-- ===========================================================================
function RefreshUnitListPopup()
Controls.UnitListPopup:ClearEntries();
local pPlayer:table = Players[Game.GetLocalPlayer()];
local pPlayerUnits:table = pPlayer:GetUnits();
-- Sort units
local militaryUnits:table = {};
local navalUnits:table = {};
local airUnits:table = {};
local supportUnits:table = {};
local civilianUnits:table = {};
local tradeUnits:table = {};
for i, pUnit in pPlayerUnits:Members() do
local unitInfo:table = GameInfo.Units[pUnit:GetUnitType()];
if unitInfo.MakeTradeRoute == true then
table.insert(tradeUnits, pUnit);
elseif pUnit:GetCombat() == 0 and pUnit:GetRangedCombat() == 0 then
-- if we have no attack strength we must be civilian
table.insert(civilianUnits, pUnit);
elseif unitInfo.Domain == "DOMAIN_LAND" then
table.insert(militaryUnits, pUnit);
elseif unitInfo.Domain == "DOMAIN_SEA" then
table.insert(navalUnits, pUnit);
elseif unitInfo.Domain == "DOMAIN_AIR" then
table.insert(airUnits, pUnit);
end
end
-- Alphabetize groups
local sortFunc = function(a, b)
local aType:string = GameInfo.Units[a:GetUnitType()].UnitType;
local bType:string = GameInfo.Units[b:GetUnitType()].UnitType;
return aType < bType;
end
table.sort(militaryUnits, sortFunc);
table.sort(navalUnits, sortFunc);
table.sort(airUnits, sortFunc);
table.sort(civilianUnits, sortFunc);
table.sort(tradeUnits, sortFunc);
-- Add units by sorted groups
for _, pUnit in ipairs(militaryUnits) do AddUnitToUnitList( pUnit ); end
for _, pUnit in ipairs(navalUnits) do AddUnitToUnitList( pUnit ); end
for _, pUnit in ipairs(airUnits) do AddUnitToUnitList( pUnit ); end
for _, pUnit in ipairs(supportUnits) do AddUnitToUnitList( pUnit ); end
for _, pUnit in ipairs(civilianUnits) do AddUnitToUnitList( pUnit ); end
for _, pUnit in ipairs(tradeUnits) do AddUnitToUnitList( pUnit ); end
Controls.UnitListPopup:CalculateInternals();
end
-- ===========================================================================
function AddUnitToUnitList(pUnit:table)
-- Create entry
local unitEntry:table = {};
Controls.UnitListPopup:BuildEntry( "UnitListEntry", unitEntry );
local uniqueName = Locale.Lookup( pUnit:GetName() );
unitEntry.Button:SetText( Locale.ToUpper(uniqueName) );
unitEntry.Button:SetVoids(i, pUnit:GetID());
-- Update unit icon
local iconInfo:table, iconShadowInfo:table = GetUnitIconAndIconShadow(pUnit, 22, true);
if iconInfo.textureSheet then
unitEntry.UnitTypeIcon:SetTexture( iconInfo.textureOffsetX, iconInfo.textureOffsetY, iconInfo.textureSheet );
end
-- Update status icon
local activityType:number = UnitManager.GetActivityType(pUnit);
if activityType == ActivityTypes.ACTIVITY_SLEEP then
SetUnitEntryStatusIcon(unitEntry, "ICON_STATS_SLEEP");
elseif activityType == ActivityTypes.ACTIVITY_HOLD then
SetUnitEntryStatusIcon(unitEntry, "ICON_STATS_SKIP");
elseif activityType ~= ActivityTypes.ACTIVITY_AWAKE and pUnit:GetFortifyTurns() > 0 then
SetUnitEntryStatusIcon(unitEntry, "ICON_DEFENSE");
else
unitEntry.UnitStatusIcon:SetHide(true);
end
-- Update entry color if unit cannot take any action
if pUnit:IsReadyToMove() then
unitEntry.Button:GetTextControl():SetColorByName("UnitPanelTextCS");
unitEntry.UnitTypeIcon:SetColorByName("UnitPanelTextCS");
else
unitEntry.Button:GetTextControl():SetColorByName("UnitPanelTextDisabledCS");
unitEntry.UnitTypeIcon:SetColorByName("UnitPanelTextDisabledCS");
end
end
-- ===========================================================================
function SetUnitEntryStatusIcon(unitEntry:table, icon:string)
local textureOffsetX:number, textureOffsetY:number, textureSheet:string = IconManager:FindIconAtlas(icon,22);
unitEntry.UnitStatusIcon:SetTexture( textureOffsetX, textureOffsetY, textureSheet );
unitEntry.UnitStatusIcon:SetHide(false);
end
-- ===========================================================================
function OnUnitListSelection(index:number, unitID:number)
local unit:table = Players[Game.GetLocalPlayer()]:GetUnits():FindID(unitID);
if unit ~= nil then
UI.SelectUnit(unit);
local plot = Map.GetPlot( unit:GetX(), unit:GetY() );
UI.LookAtPlot( plot );
end
end
-- ===========================================================================
-- LUA Event
-- ===========================================================================
function OnSetTradeUnitStatus( text:string )
Controls.TradeUnitStatusLabel:SetText( Locale.Lookup(text) );
end
-- ===========================================================================
-- LUA Event
-- ===========================================================================
function OnTutorialDisableActionForAll( actionType:string )
table.insert(m_kTutorialAllDisabled, actionType)
end
-- ===========================================================================
-- LUA Event
-- ===========================================================================
function OnTutorialEnableActionForAll( actionType:string )
local count :number = #m_kTutorialAllDisabled;
for i=count,1,-1 do
if v==actionType then
table.remove(m_kTutorialAllDisabled, i)
end
end
end
-- ===========================================================================
-- LUA Event
-- Set action/operation to not be enabled for a certain unit type.
-- actionType String of the CommandType, or OperationType
-- unitType String of the "UnitType"
-- ===========================================================================
function OnTutorialDisableActions( actionType:string, unitType:string )
if m_kTutorialDisabled[unitType] == nil then
m_kTutorialDisabled[unitType] = hmake DisabledByTutorial
{
kLockedHashes = {}
};
end
local hash:number = GetHashFromType(actionType);
if hash ~= 0 then
table.insert(m_kTutorialDisabled[unitType].kLockedHashes, hash );
else
UI.DataError("Tutorial could not disable on the UnitPanel '"..actionType.."' as it wasn't found as a command or an operation.");
end
end
-- ===========================================================================
-- LUA Event
-- Set action/operation to be re-enabled for a certain unit type.
-- actionType String of the CommandType, or OperationType
-- unitType String of the "UnitType"
-- ===========================================================================
function OnTutorialEnableActions( actionType:string, unitType:string )
if m_kTutorialDisabled[unitType] == nil then
UI.DataError("There is no spoon, '"..unitType.."' never had a disable call.");
return;
end
local hash:number = GetHashFromType(actionType);
if hash ~= 0 then
local count:number = table.count(m_kTutorialDisabled[unitType].kLockedHashes);
for n = count,1,-1 do
if hash == m_kTutorialDisabled[unitType].kLockedHashes[n] then
table.remove( m_kTutorialDisabled[unitType].kLockedHashes, n );
end
end
else
UI.DataError("Tutorial could not re-enable on the UnitPanel '"..actionType.."' as it wasn't found as a command or an operation.");
end
end
function OnPortraitClick()
if m_selectedPlayerId ~= nil then
local pUnits :table = Players[m_selectedPlayerId]:GetUnits( );
local pUnit :table = pUnits:FindID( m_UnitId );
if pUnit ~= nil then
UI.LookAtPlot( pUnit:GetX( ), pUnit:GetY( ) );
end
end
end
function OnPortraitRightClick()
if m_selectedPlayerId ~= nil then
local pUnits :table = Players[m_selectedPlayerId]:GetUnits( );
local pUnit :table = pUnits:FindID( m_UnitId );
if (pUnit ~= nil) then
local unitType = GameInfo.Units[pUnit:GetUnitType()];
if(unitType) then
LuaEvents.OpenCivilopedia(unitType.UnitType);
end
end
end
end
-- ===========================================================================
function Initialize()
-- Events
ContextPtr:SetInitHandler( OnContextInitialize );
ContextPtr:SetInputHandler( OnInputHandler, true );
ContextPtr:SetRefreshHandler( OnRefresh );
--
Controls.RandomNameButton:RegisterCallback( Mouse.eLClick, RandomizeName );
Controls.RandomPrefixButton:RegisterCallback( Mouse.eLClick, RandomizeNamePrefix );
Controls.RandomSuffixButton:RegisterCallback( Mouse.eLClick, RandomizeNameSuffix );
Controls.ConfirmVeteranName:RegisterCallback( Mouse.eLClick, ConfirmVeteranName );
Controls.VeteranNameField:RegisterStringChangedCallback( EditCustomVeteranName ) ;
Controls.VeteranNameField:RegisterCommitCallback( ConfirmVeteranName );
Controls.VeteranNamingCancelButton:RegisterCallback( Mouse.eLClick, HideVeteranNamePanel );
Controls.PromotionCancelButton:RegisterCallback( Mouse.eLClick, HidePromotionPanel );
Controls.UnitName:RegisterCallback( Mouse.eLClick, OnUnitListPopupClicked );
Controls.UnitListPopup:RegisterSelectionCallback( OnUnitListSelection );
Controls.SelectionPanelUnitPortrait:RegisterCallback( Mouse.eLClick, OnPortraitClick );
Controls.SelectionPanelUnitPortrait:RegisterCallback( Mouse.eRClick, OnPortraitRightClick);
Events.BeginWonderReveal.Add( OnBeginWonderReveal );
Events.CitySelectionChanged.Add( OnCitySelectionChanged );
Events.CityReligionFollowersChanged.Add( OnCityReligionFollowersChanged );
Events.GreatWorkMoved.Add( OnGreatWorkMoved );
Events.InputActionTriggered.Add( OnInputActionTriggered );
Events.InterfaceModeChanged.Add( OnInterfaceModeChanged );
Events.PantheonFounded.Add( OnPantheonFounded );
Events.PhaseBegin.Add( OnPhaseBegin );
Events.PlayerTurnActivated.Add( OnPlayerTurnActivated );
Events.PlayerTurnDeactivated.Add( OnPlayerTurnDeactivated );
Events.UnitCommandStarted.Add( OnUnitCommandStarted );
Events.UnitDamageChanged.Add( OnUnitDamageChanged );
Events.UnitMoveComplete.Add( OnUnitMoveComplete );
Events.UnitChargesChanged.Add( OnUnitChargesChanged );
Events.UnitPromoted.Add( OnUnitPromotionChanged );
Events.UnitOperationsCleared.Add( OnUnitOperationsCleared );
Events.UnitOperationAdded.Add( OnUnitOperationAdded );
Events.UnitOperationDeactivated.Add( OnUnitOperationDeactivated );
Events.UnitRemovedFromMap.Add( OnUnitRemovedFromMap );
Events.UnitSelectionChanged.Add( OnUnitSelectionChanged );
LuaEvents.TradeOriginChooser_SetTradeUnitStatus.Add(OnSetTradeUnitStatus );
LuaEvents.TradeRouteChooser_SetTradeUnitStatus.Add( OnSetTradeUnitStatus );
LuaEvents.TutorialUIRoot_DisableActions.Add( OnTutorialDisableActions );
LuaEvents.TutorialUIRoot_DisableActionForAll.Add( OnTutorialDisableActionForAll );
LuaEvents.TutorialUIRoot_EnableActions.Add( OnTutorialEnableActions );
LuaEvents.TutorialUIRoot_EnableActionForAll.Add( OnTutorialEnableActionForAll );
LuaEvents.UnitFlagManager_PointerEntered.Add( OnUnitFlagPointerEntered );
LuaEvents.UnitFlagManager_PointerExited.Add( OnUnitFlagPointerExited );
LuaEvents.PlayerChange_Close.Add( OnPlayerChangeClose );
-- Popup setup
m_kPopupDialog = PopupDialog:new( "UnitPanelPopup" );
-- Setup settlement water guide colors
local FreshWaterColor:number = UI.GetColorValue("COLOR_BREATHTAKING_APPEAL");
Controls.SettlementWaterGrid_FreshWater:SetColor(FreshWaterColor);
local FreshWaterBonus:number = GlobalParameters.CITY_POPULATION_RIVER_LAKE - GlobalParameters.CITY_POPULATION_NO_WATER;
Controls.CapacityBonus_FreshWater:SetText("+" .. tostring(FreshWaterBonus));
local CoastalWaterColor:number = UI.GetColorValue("COLOR_CHARMING_APPEAL");
Controls.SettlementWaterGrid_CoastalWater:SetColor(CoastalWaterColor);
local CoastalWaterBonus:number = GlobalParameters.CITY_POPULATION_COAST - GlobalParameters.CITY_POPULATION_NO_WATER;
Controls.CapacityBonus_CoastalWater:SetText("+" .. tostring(CoastalWaterBonus));
local NoWaterColor:number = UI.GetColorValue("COLOR_AVERAGE_APPEAL");
Controls.SettlementWaterGrid_NoWater:SetColor(NoWaterColor);
local SettlementBlockedColor:number = UI.GetColorValue("COLOR_DISGUSTING_APPEAL");
Controls.SettlementWaterGrid_SettlementBlocked:SetColor(SettlementBlockedColor);
end
Initialize();
| mit |
anshkumar/yugioh-glaze | assets/script/c22419772.lua | 7 | 1372 | --ピクシーガーディアン
function c22419772.initial_effect(c)
--to deck
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(22419772,0))
e1:SetCategory(CATEGORY_TODECK)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c22419772.cost)
e1:SetTarget(c22419772.target)
e1:SetOperation(c22419772.operation)
c:RegisterEffect(e1)
end
function c22419772.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReleasable() end
Duel.Release(e:GetHandler(),REASON_COST)
end
function c22419772.filter(c,tp,tid)
return c:IsAbleToDeck() and c:IsType(TYPE_SPELL) and c:GetTurnID()==tid and c:GetReasonPlayer()==1-tp
end
function c22419772.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local tid=Duel.GetTurnCount()
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c22419772.filter(chkc,tp,tid) end
if chk==0 then return Duel.IsExistingTarget(c22419772.filter,tp,LOCATION_GRAVE,0,1,nil,tp,tid) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,c22419772.filter,tp,LOCATION_GRAVE,0,1,1,nil,tp,tid)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,1,0,0)
end
function c22419772.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoDeck(tc,nil,1,REASON_EFFECT)
end
end
| gpl-2.0 |
Tiger66639/premake-core | src/base/premake.lua | 1 | 8674 | --
-- premake.lua
-- High-level helper functions for the project exporters.
-- Copyright (c) 2002-2015 Jason Perkins and the Premake project
--
local p = premake
-- Store captured output text for later testing
local _captured
-- The string escaping function.
local _esc = function(v) return v end
-- The output settings and defaults
local _eol = "\n"
local _indentString = "\t"
local _indentLevel = 0
-- Set up the global configuration scope. There can be only one.
global("root")
---
-- Capture and store everything sent through the output stream functions
-- premake.w(), premake.x(), and premake.out(). Retrieve the captured
-- text using the premake.captured() function.
--
-- @param fn
-- A function to execute. Any output calls made during the execution
-- of the function will be captured.
-- @return
-- The captured output.
---
function premake.capture(fn)
-- start a new capture without forgetting the old one
local old = _captured
_captured = buffered.new()
-- capture
fn()
-- build the result
local captured = premake.captured()
-- free the capture buffer.
buffered.close(_captured)
-- restore the old capture and done
_captured = old
return captured
end
--
-- Returns the captured text and stops capturing.
--
function premake.captured()
if _captured then
return buffered.tostring(_captured)
else
return ""
end
end
---
-- Set the output stream end-of-line sequence.
--
-- @param s
-- The string to use to mark line ends, or nil to keep the existing
-- EOL sequence.
-- @return
-- The new EOL sequence.
---
function premake.eol(s)
_eol = s or _eol
return _eol
end
---
-- Handle escaping of strings for various outputs.
--
-- @param value
-- If this is a string: escape it and return the new value. If it is an
-- array, return a new array of escaped values.
-- @return
-- If the input was a single string, returns the escaped version. If it
-- was an array, returns an corresponding array of escaped strings.
---
function premake.esc(value)
if type(value) == "table" then
local result = {}
local n = #value
for i = 1, n do
table.insert(result, premake.esc(value[i]))
end
return result
end
return _esc(value or "")
end
---
-- Set a new string escaping function.
--
-- @param func
-- The new escaping function, which should take a single string argument
-- and return the escaped version of that string. If nil, uses a default
-- no-op function.
---
function premake.escaper(func)
_esc = func
if not _esc then
_esc = function (value) return value end
end
end
--
-- Open a file for output, and call a function to actually do the writing.
-- Used by the actions to generate workspace and project files.
--
-- @param obj
-- A workspace or project object; will be passed to the callback function.
-- @param ext
-- An optional extension for the generated file, with the leading dot.
-- @param callback
-- The function responsible for writing the file, should take a workspace
-- or project as a parameters.
--
function premake.generate(obj, ext, callback)
local output = premake.capture(function ()
_indentLevel = 0
callback(obj)
_indentLevel = 0
end)
local fn = premake.filename(obj, ext)
-- make sure output folder exists.
local dir = path.getdirectory(fn)
ok, err = os.mkdir(dir)
if not ok then
error(err, 0)
end
local f, err = os.writefile_ifnotequal(output, fn);
if (f < 0) then
error(err, 0)
elseif (f > 0) then
printf("Generated %s...", path.getrelative(os.getcwd(), fn))
end
end
---
-- Returns the full path a file generated from any of the project
-- objects (project, workspace, rule).
--
-- @param obj
-- The project object being generated.
-- @param ext
-- An optional extension for the generated file, with the leading dot.
-- @param callback
-- The function responsible for writing the file; will receive the
-- project object as its only argument.
---
function premake.filename(obj, ext)
local fname = obj.location or obj.basedir
if ext and not ext:startswith(".") then
fname = path.join(fname, ext)
else
fname = path.join(fname, obj.filename)
if ext then
fname = fname .. ext
end
end
return path.getabsolute(fname)
end
---
-- Sets the output indentation parameters.
--
-- @param s
-- The indentation string.
-- @param i
-- The new indentation level, or nil to reset to zero.
---
function premake.indent(s, i)
_indentString = s or "\t"
_indentLevel = i or 0
end
---
-- Write a simple, unformatted string to the output stream, with no indentation
-- or end of line sequence.
---
function premake.out(s)
if not _captured then
io.write(s)
else
buffered.write(_captured, s)
end
end
---
-- Write a simple, unformatted string to the output stream, with no indentation,
-- and append the current EOL sequence.
---
function premake.outln(s)
premake.out(s)
premake.out(_eol or "\n")
end
--
-- Output a UTF-8 signature.
--
function p.utf8()
premake.out('\239\187\191')
end
---
-- Write a formatted string to the exported file, after decreasing the
-- indentation level by one.
--
-- @param i
-- If set to a number, the indentation level will be decreased by
-- this amount. If nil, the indentation level is decremented and
-- no output is written. Otherwise, pass to premake.w() as the
-- formatting string, followed by any additional arguments.
---
function premake.pop(i, ...)
if i == nil or type(i) == "number" then
_indentLevel = _indentLevel - (i or 1)
else
_indentLevel = _indentLevel - 1
premake.w(i, ...)
end
end
---
-- Write a formatted string to the exported file, and increase the
-- indentation level by one.
--
-- @param i
-- If set to a number, the indentation level will be increased by
-- this amount. If nil, the indentation level is incremented and
-- no output is written. Otherwise, pass to premake.w() as the
-- formatting string, followed by any additional arguments.
---
function premake.push(i, ...)
if i == nil or type(i) == "number" then
_indentLevel = _indentLevel + (i or 1)
else
premake.w(i, ...)
_indentLevel = _indentLevel + 1
end
end
---
-- Wrap the provided value in double quotes if it contains spaces, or
-- if it contains a shell variable of the form $(...).
---
function premake.quoted(value)
local q = value:find(" ", 1, true)
if not q then
q = value:find("$%(.-%)", 1)
end
if q then
value = '"' .. value .. '"'
end
return value
end
--
-- Output a UTF-8 BOM to the exported file.
--
function premake.utf8()
if not _captured then
premake.out('\239\187\191')
end
end
---
-- Write a formatted string to the exported file, at the current
-- level of indentation, and appends an end of line sequence.
-- This gets called quite a lot, hence the very short name.
---
function premake.w(...)
if select("#", ...) > 0 then
premake.outln(string.rep(_indentString or "\t", _indentLevel) .. string.format(...))
else
premake.outln('');
end
end
---
-- Write a formatted string to the exported file, after passing all
-- arguments (except for the first, which is the formatting string)
-- through premake.esc().
---
function premake.x(msg, ...)
local arg = {...}
for i = 1, #arg do
arg[i] = premake.esc(arg[i])
end
premake.w(msg, unpack(arg))
end
---
-- Write a opening XML element for a UTF-8 encoded file. Used by
-- several different files for different actions, so makes sense
-- to have a common call for it.
--
-- @param upper
-- If true, the encoding is written in uppercase.
---
function premake.xmlUtf8(upper)
local encoding = iif(upper, "UTF-8", "utf-8")
premake.w('<?xml version="1.0" encoding="%s"?>', encoding)
end
--
-- These are the output shortcuts that I used before switching to the
-- indentation-aware calls above. They are still in use all over the
-- place, including lots of community code, so let's keep them around.
--
-- @param i
-- This will either be a printf-style formatting string suitable
-- for passing to string.format(), OR an integer number indicating
-- the desired level of indentation. If the latter, the formatting
-- string should be the next argument in the list.
-- @param ...
-- The values necessary to fill out the formatting string tokens.
--
function _p(i, ...)
if type(i) == "number" then
_indentLevel = i
premake.w(...)
else
_indentLevel = 0
premake.w(i, ...)
end
end
function _x(i, ...)
local arg = {...}
for i = 2, #arg do
arg[i] = premake.esc(arg[i])
end
_p(i, unpack(arg))
end
| bsd-3-clause |
anshkumar/yugioh-glaze | assets/script/c82003859.lua | 5 | 1034 | --通行税
function c82003859.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--attack cost
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_ATTACK_COST)
e2:SetRange(LOCATION_SZONE)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetTargetRange(1,1)
e2:SetCondition(c82003859.atcon)
e2:SetCost(c82003859.atcost)
e2:SetOperation(c82003859.atop)
c:RegisterEffect(e2)
--accumulate
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(0x10000000+82003859)
e3:SetRange(LOCATION_SZONE)
e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e3:SetTargetRange(1,1)
c:RegisterEffect(e3)
end
function c82003859.atcon(e)
c82003859[0]=false
return true
end
function c82003859.atcost(e,c,tp)
return Duel.CheckLPCost(tp,500)
end
function c82003859.atop(e,tp,eg,ep,ev,re,r,rp)
if c82003859[0] then return end
Duel.PayLPCost(tp,Duel.GetFlagEffect(tp,82003859)*500)
c82003859[0]=true
end
| gpl-2.0 |
hbomb79/DynaCode | src/Classes/Exceptions/ExceptionBase.lua | 2 | 2347 | local _
abstract class "ExceptionBase" {
exceptionOffset = 1;
levelOffset = 1;
title = "UNKNOWN_EXCEPTION";
subTitle = false;
message = nil;
level = 1;
raw = nil;
useMessageAsRaw = false;
stacktrace = "\nNo stacktrace has been generated\n"
}
function ExceptionBase:initialise( m, l, handle )
if l then self.level = l end
self.level = self.level ~= 0 and (self.level + (self.exceptionOffset * 3) + self.levelOffset) or self.level
self.message = m or "No error message provided"
if self.useMessageAsRaw then
self.raw = m
else
local ok, err = pcall( exceptionHook.getRawError(), m, self.level == 0 and 0 or self.level + 1 )
self.raw = err or m
end
self:generateStack( self.level == 0 and 0 or self.level + 4 )
self:generateDisplayName()
if not handle then
exceptionHook.throwSystemException( self )
end
end
function ExceptionBase:generateDisplayName()
local err = self.raw
local pre = self.title
local _, e, fileName, fileLine = err:find("(%w+%.?.-):(%d+).-[%s*]?[:*]?")
if not e then self.displayName = pre.." (?): "..err return end
self.displayName = pre.." ("..(fileName or "?")..":"..(fileLine or "?").."):"..tostring( err:sub( e + 1 ) )
end
function ExceptionBase:generateStack( level )
local oError = exceptionHook.getRawError()
if level == 0 then
log("w", "Cannot generate stacktrace for exception '"..tostring( self ).."'. Its level is zero")
return
end
local stack = "\n'"..tostring( self.title ).."' details\n##########\n\nError: \n"..self.message.." (Level: "..self.level..", pcall: "..tostring( self.raw )..")\n##########\n\nStacktrace: \n"
local currentLevel = level
local message = self.message
while true do
local _, err = pcall( oError, message, currentLevel )
if err:find("bios[%.lua]?.-:") or err:find("shell.-:") or err:find("xpcall.-:") then
stack = stack .. "-- End --\n"
break
end
local fileName, fileLine = err:match("(%w+%.?.-):(%d+).-")
stack = stack .. "> "..(fileName or "?")..":"..(fileLine or "?").."\n"
currentLevel = currentLevel + 1
end
if self.subTitle then
stack = stack .. "\n"..self.subTitle
end
self.stacktrace = stack
end
| mit |
anshkumar/yugioh-glaze | assets/script/c71279983.lua | 3 | 2075 | --U.A.ドレッドノートダンカー
function c71279983.initial_effect(c)
--special summon rule
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetRange(LOCATION_HAND)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetCountLimit(1,71279983)
e1:SetCondition(c71279983.spcon)
e1:SetOperation(c71279983.spop)
c:RegisterEffect(e1)
--pierce
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_PIERCE)
c:RegisterEffect(e2)
--destroy
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_DESTROY)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_BATTLE_DAMAGE)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetCondition(c71279983.descon)
e3:SetTarget(c71279983.destg)
e3:SetOperation(c71279983.desop)
c:RegisterEffect(e3)
end
function c71279983.spfilter(c)
return c:IsFaceup() and c:IsSetCard(0xb2) and not c:IsCode(71279983) and c:IsAbleToHandAsCost()
end
function c71279983.spcon(e,c)
if c==nil then return true end
return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>-1
and Duel.IsExistingMatchingCard(c71279983.spfilter,c:GetControler(),LOCATION_MZONE,0,1,nil)
end
function c71279983.spop(e,tp,eg,ep,ev,re,r,rp,c)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g=Duel.SelectMatchingCard(tp,c71279983.spfilter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SendtoHand(g,nil,REASON_COST)
end
function c71279983.descon(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp
end
function c71279983.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsDestructable() end
if chk==0 then return Duel.IsExistingTarget(Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c71279983.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
TurBoss/Zero-K-Infrastructure | Benchmarker/Benchmarks/games/ca-benchmark.sdd/LuaRules/main.lua | 12 | 2372 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- file:
-- brief:
-- author: jK
--
-- Copyright (C) 2007.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- SYNCED
--
local doStart = true;
local counter = 0
local testID = 0
local curBenchmark
local benchmarks = VFS.Include("LuaRules/Benchmarks/benchmarks.lua",nil, VFS.ZIP_ONLY)
function RecvLuaMsg(msg,playerID)
if msg == "StartBenchmark" then
testID=testID+1
StartBenchmark(testID)
end
end
function Shutdown()
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local mapconst = 64*Game.squareSize;
local mapX,mapY = Game.mapX*mapconst,Game.mapY*mapconst;
local groundMin, groundMax = Spring.GetGroundExtremes(); groundMin, groundMax = math.max(groundMin,0), math.max(groundMax,1);
function StartBenchmark(id)
curBenchmark = benchmarks[id]
if (not curBenchmark) then
Spring.GameOver({})
return
end
counter = curBenchmark.duration*30
SendToUnsynced("StartBenchmark",id)
end
function StopBenchmark(id)
SendToUnsynced("StopBenchmark",id)
if (curBenchmark ~= nil and curBenchmark.finish) then
curBenchmark.finish()
end
doStart = true;
curBenchmark = nil
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function GameFrame()
if (curBenchmark) then
if (doStart)and(curBenchmark.start) then
curBenchmark.start()
doStart = false
end
if (curBenchmark.gameframe) then
curBenchmark.gameframe()
end
end
if (counter>0) then
counter = counter-1
if (counter==0) then
StopBenchmark(testID)
end
end
SendToUnsynced("GameFrame")
end | gpl-3.0 |
qq2588258/floweers | libs/scripting/lua/script/DrawPrimitives.lua | 57 | 12038 | local dp_initialized = false
local dp_shader = nil
local dp_colorLocation = -1
local dp_color = { 1.0, 1.0, 1.0, 1.0 }
local dp_pointSizeLocation = -1
local dp_pointSize = 1.0
local SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor"
local targetPlatform = CCApplication:getInstance():getTargetPlatform()
local function lazy_init()
if not dp_initialized then
dp_shader = CCShaderCache:getInstance():getProgram(SHADER_NAME_POSITION_U_COLOR)
--dp_shader:retain()
if nil ~= dp_shader then
dp_colorLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_color")
dp_pointSizeLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_pointSize")
dp_Initialized = true
end
end
if nil == dp_shader then
print("Error:dp_shader is nil!")
return false
end
return true
end
local function setDrawProperty()
gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION )
dp_shader:use()
dp_shader:setUniformsForBuiltins()
dp_shader:setUniformLocationWith4fv(dp_colorLocation, dp_color, 1)
end
function ccDrawInit()
lazy_init()
end
function ccDrawFree()
dp_initialized = false
end
function ccDrawColor4f(r,g,b,a)
dp_color[1] = r
dp_color[2] = g
dp_color[3] = b
dp_color[4] = a
end
function ccPointSize(pointSize)
dp_pointSize = pointSize * CCDirector:getInstance():getContentScaleFactor()
end
function ccDrawColor4B(r,g,b,a)
dp_color[1] = r / 255.0
dp_color[2] = g / 255.0
dp_color[3] = b / 255.0
dp_color[4] = a / 255.0
end
function ccDrawPoint(point)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
local vertices = { point.x,point.y}
gl.bufferData(gl.ARRAY_BUFFER,2,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.POINTS,0,1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawPoints(points,numOfPoint)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoint do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoint * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.POINTS,0,numOfPoint)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawLine(origin,destination)
if not lazy_init() then
return
end
local vertexBuffer = {}
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = { origin.x, origin.y, destination.x, destination.y}
gl.bufferData(gl.ARRAY_BUFFER,4,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINES ,0,2)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawPoly(points,numOfPoints,closePolygon)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoints do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
if closePolygon then
gl.drawArrays(gl.LINE_LOOP , 0, numOfPoints)
else
gl.drawArrays(gl.LINE_STRIP, 0, numOfPoints)
end
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawSolidPoly(points,numOfPoints,color)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoints do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION )
dp_shader:use()
dp_shader:setUniformsForBuiltins()
dp_shader:setUniformLocationWith4fv(dp_colorLocation, color, 1)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_FAN , 0, numOfPoints)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawRect(origin,destination)
ccDrawLine(CCPoint:__call(origin.x, origin.y), CCPoint:__call(destination.x, origin.y))
ccDrawLine(CCPoint:__call(destination.x, origin.y), CCPoint:__call(destination.x, destination.y))
ccDrawLine(CCPoint:__call(destination.x, destination.y), CCPoint:__call(origin.x, destination.y))
ccDrawLine(CCPoint:__call(origin.x, destination.y), CCPoint:__call(origin.x, origin.y))
end
function ccDrawSolidRect( origin,destination,color )
local vertices = { origin, CCPoint:__call(destination.x, origin.y) , destination, CCPoint:__call(origin.x, destination.y) }
ccDrawSolidPoly(vertices,4,color)
end
function ccDrawCircleScale( center, radius, angle, segments,drawLineToCenter,scaleX,scaleY)
if not lazy_init() then
return
end
local additionalSegment = 1
if drawLineToCenter then
additionalSegment = additionalSegment + 1
end
local vertexBuffer = { }
local function initBuffer()
local coef = 2.0 * math.pi / segments
local i = 1
local vertices = {}
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
for i = 1, segments + 1 do
local rads = (i - 1) * coef
local j = radius * math.cos(rads + angle) * scaleX + center.x
local k = radius * math.sin(rads + angle) * scaleY + center.y
vertices[i * 2 - 1] = j
vertices[i * 2] = k
end
vertices[(segments + 2) * 2 - 1] = center.x
vertices[(segments + 2) * 2] = center.y
gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + additionalSegment)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawCircle(center, radius, angle, segments, drawLineToCenter)
ccDrawCircleScale(center, radius, angle, segments, drawLineToCenter, 1.0, 1.0)
end
function ccDrawSolidCircle(center, radius, angle, segments,scaleX,scaleY)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
local coef = 2.0 * math.pi / segments
local i = 1
local vertices = {}
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
for i = 1, segments + 1 do
local rads = (i - 1) * coef
local j = radius * math.cos(rads + angle) * scaleX + center.x
local k = radius * math.sin(rads + angle) * scaleY + center.y
vertices[i * 2 - 1] = j
vertices[i * 2] = k
end
vertices[(segments + 2) * 2 - 1] = center.x
vertices[(segments + 2) * 2] = center.y
gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_FAN , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawQuadBezier(origin, control, destination, segments)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
local vertices = { }
local i = 1
local t = 0.0
for i = 1, segments do
vertices[2 * i - 1] = math.pow(1 - t,2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x
vertices[2 * i] = math.pow(1 - t,2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y
t = t + 1.0 / segments
end
vertices[2 * (segments + 1) - 1] = destination.x
vertices[2 * (segments + 1)] = destination.y
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawCubicBezier(origin, control1, control2, destination, segments)
if not lazy_init then
return
end
local vertexBuffer = { }
local function initBuffer()
local vertices = { }
local t = 0
local i = 1
for i = 1, segments do
vertices[2 * i - 1] = math.pow(1 - t,3) * origin.x + 3.0 * math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x
vertices[2 * i] = math.pow(1 - t,3) * origin.y + 3.0 * math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y
t = t + 1.0 / segments
end
vertices[2 * (segments + 1) - 1] = destination.x
vertices[2 * (segments + 1)] = destination.y
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
| mit |
qq2588258/floweers | Resources/luaScript/util/DrawPrimitives.lua | 57 | 12038 | local dp_initialized = false
local dp_shader = nil
local dp_colorLocation = -1
local dp_color = { 1.0, 1.0, 1.0, 1.0 }
local dp_pointSizeLocation = -1
local dp_pointSize = 1.0
local SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor"
local targetPlatform = CCApplication:getInstance():getTargetPlatform()
local function lazy_init()
if not dp_initialized then
dp_shader = CCShaderCache:getInstance():getProgram(SHADER_NAME_POSITION_U_COLOR)
--dp_shader:retain()
if nil ~= dp_shader then
dp_colorLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_color")
dp_pointSizeLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_pointSize")
dp_Initialized = true
end
end
if nil == dp_shader then
print("Error:dp_shader is nil!")
return false
end
return true
end
local function setDrawProperty()
gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION )
dp_shader:use()
dp_shader:setUniformsForBuiltins()
dp_shader:setUniformLocationWith4fv(dp_colorLocation, dp_color, 1)
end
function ccDrawInit()
lazy_init()
end
function ccDrawFree()
dp_initialized = false
end
function ccDrawColor4f(r,g,b,a)
dp_color[1] = r
dp_color[2] = g
dp_color[3] = b
dp_color[4] = a
end
function ccPointSize(pointSize)
dp_pointSize = pointSize * CCDirector:getInstance():getContentScaleFactor()
end
function ccDrawColor4B(r,g,b,a)
dp_color[1] = r / 255.0
dp_color[2] = g / 255.0
dp_color[3] = b / 255.0
dp_color[4] = a / 255.0
end
function ccDrawPoint(point)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
local vertices = { point.x,point.y}
gl.bufferData(gl.ARRAY_BUFFER,2,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.POINTS,0,1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawPoints(points,numOfPoint)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoint do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoint * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.POINTS,0,numOfPoint)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawLine(origin,destination)
if not lazy_init() then
return
end
local vertexBuffer = {}
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = { origin.x, origin.y, destination.x, destination.y}
gl.bufferData(gl.ARRAY_BUFFER,4,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINES ,0,2)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawPoly(points,numOfPoints,closePolygon)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoints do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
if closePolygon then
gl.drawArrays(gl.LINE_LOOP , 0, numOfPoints)
else
gl.drawArrays(gl.LINE_STRIP, 0, numOfPoints)
end
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawSolidPoly(points,numOfPoints,color)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoints do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION )
dp_shader:use()
dp_shader:setUniformsForBuiltins()
dp_shader:setUniformLocationWith4fv(dp_colorLocation, color, 1)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_FAN , 0, numOfPoints)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawRect(origin,destination)
ccDrawLine(CCPoint:__call(origin.x, origin.y), CCPoint:__call(destination.x, origin.y))
ccDrawLine(CCPoint:__call(destination.x, origin.y), CCPoint:__call(destination.x, destination.y))
ccDrawLine(CCPoint:__call(destination.x, destination.y), CCPoint:__call(origin.x, destination.y))
ccDrawLine(CCPoint:__call(origin.x, destination.y), CCPoint:__call(origin.x, origin.y))
end
function ccDrawSolidRect( origin,destination,color )
local vertices = { origin, CCPoint:__call(destination.x, origin.y) , destination, CCPoint:__call(origin.x, destination.y) }
ccDrawSolidPoly(vertices,4,color)
end
function ccDrawCircleScale( center, radius, angle, segments,drawLineToCenter,scaleX,scaleY)
if not lazy_init() then
return
end
local additionalSegment = 1
if drawLineToCenter then
additionalSegment = additionalSegment + 1
end
local vertexBuffer = { }
local function initBuffer()
local coef = 2.0 * math.pi / segments
local i = 1
local vertices = {}
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
for i = 1, segments + 1 do
local rads = (i - 1) * coef
local j = radius * math.cos(rads + angle) * scaleX + center.x
local k = radius * math.sin(rads + angle) * scaleY + center.y
vertices[i * 2 - 1] = j
vertices[i * 2] = k
end
vertices[(segments + 2) * 2 - 1] = center.x
vertices[(segments + 2) * 2] = center.y
gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + additionalSegment)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawCircle(center, radius, angle, segments, drawLineToCenter)
ccDrawCircleScale(center, radius, angle, segments, drawLineToCenter, 1.0, 1.0)
end
function ccDrawSolidCircle(center, radius, angle, segments,scaleX,scaleY)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
local coef = 2.0 * math.pi / segments
local i = 1
local vertices = {}
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
for i = 1, segments + 1 do
local rads = (i - 1) * coef
local j = radius * math.cos(rads + angle) * scaleX + center.x
local k = radius * math.sin(rads + angle) * scaleY + center.y
vertices[i * 2 - 1] = j
vertices[i * 2] = k
end
vertices[(segments + 2) * 2 - 1] = center.x
vertices[(segments + 2) * 2] = center.y
gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_FAN , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawQuadBezier(origin, control, destination, segments)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
local vertices = { }
local i = 1
local t = 0.0
for i = 1, segments do
vertices[2 * i - 1] = math.pow(1 - t,2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x
vertices[2 * i] = math.pow(1 - t,2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y
t = t + 1.0 / segments
end
vertices[2 * (segments + 1) - 1] = destination.x
vertices[2 * (segments + 1)] = destination.y
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawCubicBezier(origin, control1, control2, destination, segments)
if not lazy_init then
return
end
local vertexBuffer = { }
local function initBuffer()
local vertices = { }
local t = 0
local i = 1
for i = 1, segments do
vertices[2 * i - 1] = math.pow(1 - t,3) * origin.x + 3.0 * math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x
vertices[2 * i] = math.pow(1 - t,3) * origin.y + 3.0 * math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y
t = t + 1.0 / segments
end
vertices[2 * (segments + 1) - 1] = destination.x
vertices[2 * (segments + 1)] = destination.y
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
| mit |
rickyHong/nn_lib_torch | init.lua | 1 | 3268 | require('torch')
require('libnn')
include('ErrorMessages.lua')
include('Module.lua')
include('Container.lua')
include('Concat.lua')
include('Parallel.lua')
include('Sequential.lua')
include('DepthConcat.lua')
include('Linear.lua')
include('SparseLinear.lua')
include('Reshape.lua')
include('View.lua')
include('Select.lua')
include('Narrow.lua')
include('Replicate.lua')
include('Transpose.lua')
include('BatchNormalization.lua')
include('Padding.lua')
include('Copy.lua')
include('Min.lua')
include('Max.lua')
include('Mean.lua')
include('Sum.lua')
include('CMul.lua')
include('Mul.lua')
include('MulConstant.lua')
include('Add.lua')
include('AddConstant.lua')
include('Dropout.lua')
include('SpatialDropout.lua')
include('CAddTable.lua')
include('CDivTable.lua')
include('CMulTable.lua')
include('CSubTable.lua')
include('Euclidean.lua')
include('WeightedEuclidean.lua')
include('PairwiseDistance.lua')
include('CosineDistance.lua')
include('DotProduct.lua')
include('Exp.lua')
include('Log.lua')
include('HardTanh.lua')
include('LogSigmoid.lua')
include('LogSoftMax.lua')
include('Sigmoid.lua')
include('SoftMax.lua')
include('SoftMin.lua')
include('SoftPlus.lua')
include('SoftSign.lua')
include('Tanh.lua')
include('TanhShrink.lua')
include('Abs.lua')
include('Power.lua')
include('Square.lua')
include('Sqrt.lua')
include('HardShrink.lua')
include('SoftShrink.lua')
include('Threshold.lua')
include('ReLU.lua')
include('PReLU.lua')
include('LookupTable.lua')
include('SpatialConvolution.lua')
include('SpatialFullConvolution.lua')
include('SpatialFullConvolutionMap.lua')
include('SpatialConvolutionMM.lua')
include('SpatialConvolutionMap.lua')
include('SpatialSubSampling.lua')
include('SpatialMaxPooling.lua')
include('SpatialLPPooling.lua')
include('SpatialAveragePooling.lua')
include('SpatialAdaptiveMaxPooling.lua')
include('TemporalConvolution.lua')
include('TemporalSubSampling.lua')
include('TemporalMaxPooling.lua')
include('SpatialSubtractiveNormalization.lua')
include('SpatialDivisiveNormalization.lua')
include('SpatialContrastiveNormalization.lua')
include('SpatialZeroPadding.lua')
include('SpatialUpSamplingNearest.lua')
include('SpatialBatchNormalization.lua')
include('VolumetricConvolution.lua')
include('VolumetricMaxPooling.lua')
include('ParallelTable.lua')
include('ConcatTable.lua')
include('SplitTable.lua')
include('JoinTable.lua')
include('SelectTable.lua')
include('MixtureTable.lua')
include('CriterionTable.lua')
include('FlattenTable.lua')
include('Identity.lua')
include('Criterion.lua')
include('MSECriterion.lua')
include('MarginCriterion.lua')
include('AbsCriterion.lua')
include('ClassNLLCriterion.lua')
include('DistKLDivCriterion.lua')
include('MultiCriterion.lua')
include('L1HingeEmbeddingCriterion.lua')
include('HingeEmbeddingCriterion.lua')
include('CosineEmbeddingCriterion.lua')
include('MarginRankingCriterion.lua')
include('MultiMarginCriterion.lua')
include('MultiLabelMarginCriterion.lua')
include('L1Cost.lua')
include('L1Penalty.lua')
include('WeightedMSECriterion.lua')
include('BCECriterion.lua')
include('CrossEntropyCriterion.lua')
include('StochasticGradient.lua')
include('MM.lua')
include('Jacobian.lua')
include('SparseJacobian.lua')
include('hessian.lua')
include('test.lua')
return nn
| bsd-3-clause |
anshkumar/yugioh-glaze | assets/script/c18426196.lua | 3 | 2245 | --聖騎士ジャンヌ
function c18426196.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetCondition(c18426196.condtion)
e1:SetValue(-300)
c:RegisterEffect(e1)
--salvage
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(18426196,0))
e1:SetCategory(CATEGORY_TOHAND)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY+EFFECT_FLAG_CVAL_CHECK)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c18426196.thcon)
e1:SetCost(c18426196.thcost)
e1:SetTarget(c18426196.thtg)
e1:SetOperation(c18426196.thop)
e1:SetValue(c18426196.valcheck)
c:RegisterEffect(e1)
end
function c18426196.condtion(e)
local ph=Duel.GetCurrentPhase()
return (ph==PHASE_DAMAGE or ph==PHASE_DAMAGE_CAL)
and Duel.GetAttacker()==e:GetHandler()
end
function c18426196.thcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_DESTROY) and e:GetHandler():GetReasonPlayer()==1-tp
end
function c18426196.thcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
if Duel.GetFlagEffect(tp,18426196)==0 then
Duel.RegisterFlagEffect(tp,18426196,RESET_CHAIN,0,1)
c18426196[0]=Duel.GetMatchingGroupCount(Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,nil)
c18426196[1]=0
end
return c18426196[0]-c18426196[1]>=1
end
Duel.DiscardHand(tp,Card.IsAbleToGraveAsCost,1,1,REASON_COST)
end
function c18426196.filter(c)
return c:IsLevelBelow(4) and c:IsRace(RACE_WARRIOR) and c:IsAbleToHand()
end
function c18426196.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c18426196.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c18426196.filter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c18426196.filter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,g:GetCount(),0,0)
end
function c18426196.thop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,tc)
end
end
function c18426196.valcheck(e)
c18426196[1]=c18426196[1]+1
end
| gpl-2.0 |
iranianboy/iran-bot | plugins/inpm.lua | 243 | 3007 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
m13790115/evill | plugins/inpm.lua | 243 | 3007 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c39439590.lua | 3 | 1078 | --サイバー・ダイナソー
function c39439590.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(39439590,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetRange(LOCATION_HAND)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(c39439590.spcon)
e1:SetTarget(c39439590.sptg)
e1:SetOperation(c39439590.spop)
c:RegisterEffect(e1)
end
function c39439590.cfilter(c,tp)
return c:GetSummonPlayer()==1-tp and c:IsPreviousLocation(LOCATION_HAND)
end
function c39439590.spcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c39439590.cfilter,1,nil,tp)
end
function c39439590.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c39439590.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
beko123/DEV_VIP | plugins/on_off.lua | 12 | 1983 | -- Checks if bot was disabled on specific chat
local function is_channel_disabled( receiver )
if not _config.disabled_channels then
return false
end
if _config.disabled_channels[receiver] == nil then
return false
end
return _config.disabled_channels[receiver]
end
local function enable_channel(receiver)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
if _config.disabled_channels[receiver] == nil then
return "ربات خاموش نمی باشد!"
end
_config.disabled_channels[receiver] = false
save_config()
return "ربات روشن شد!"
end
local function disable_channel( receiver )
if not _config.disabled_channels then
_config.disabled_channels = {}
end
_config.disabled_channels[receiver] = true
save_config()
return "ربات خاموش شد!"
end
local function pre_process(msg)
local receiver = get_receiver(msg)
-- If sender is moderator then re-enable the channel
--if is_sudo(msg) then
if is_owner(msg) then
if msg.text == "/bot on" or msg.text == "/Bot on" or msg.text == "!bot on" or msg.text == "!Bot on" then
enable_channel(receiver)
end
end
if is_channel_disabled(receiver) then
msg.text = ""
end
return msg
end
local function run(msg, matches)
local receiver = get_receiver(msg)
-- Enable a channel
local hash = 'usecommands:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
if not is_owner(msg) then
return 'شما صاحب گروه نمی باشید!'
end
if matches[1] == 'on' then
return enable_channel(receiver)
end
-- Disable a channel
if matches[1] == 'off' then
return disable_channel(receiver)
end
end
return {
description = "Plugin to manage channels. Enable or disable channel.",
usage = {
"/channel enable: enable current channel",
"/channel disable: disable current channel" },
patterns = {
"^[!/][Bb]ot (on)",
"^[!/][Bb]ot (off)" },
run = run,
--privileged = true,
moderated = true,
pre_process = pre_process
}
| agpl-3.0 |
anshkumar/yugioh-glaze | assets/script/c46848859.lua | 3 | 2078 | --ネイビィロイド
function c46848859.initial_effect(c)
--Negate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(46848859,0))
e1:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_CHAINING)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c46848859.condition)
e1:SetCost(c46848859.cost)
e1:SetTarget(c46848859.target)
e1:SetOperation(c46848859.operation)
c:RegisterEffect(e1)
end
function c46848859.cfilter(c)
return c:IsOnField() and c:IsType(TYPE_SPELL+TYPE_TRAP)
end
function c46848859.tgfilter(c,tp)
return c:IsOnField() and c:IsControler(tp) and c:IsType(TYPE_SPELL+TYPE_TRAP)
end
function c46848859.condition(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsStatus(STATUS_BATTLE_DESTROYED) or not Duel.IsChainNegatable(ev) then return false end
if not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return false end
local g=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
if not g or not g:IsExists(c46848859.tgfilter,1,nil,tp) then return false end
if re:IsHasCategory(CATEGORY_NEGATE)
and Duel.GetChainInfo(ev-1,CHAININFO_TRIGGERING_EFFECT):IsHasType(EFFECT_TYPE_ACTIVATE) then return false end
local ex,tg,tc=Duel.GetOperationInfo(ev,CATEGORY_DESTROY)
return ex and tg~=nil and tc+tg:FilterCount(c46848859.cfilter,nil)-tg:GetCount()>0
end
function c46848859.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,nil) end
Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_COST+REASON_DISCARD)
end
function c46848859.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0)
if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
end
function c46848859.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateActivation(ev)
if re:GetHandler():IsRelateToEffect(re) then
Duel.Destroy(eg,REASON_EFFECT)
end
end
| gpl-2.0 |
adan830/UpAndAway | code/brains/goosebrain.lua | 2 | 1674 | BindGlobal()
local CFG = TheMod:GetConfig()
require "behaviours/wander"
require "behaviours/runaway"
require "behaviours/doaction"
require "behaviours/panic"
local GooseBrain = Class(Brain, function(self, inst)
Brain._ctor(self, inst)
end)
local function EatFoodAction(inst)
local target = nil
if inst.components.inventory and inst.components.eater then
target = inst.components.inventory:FindItem(function(item) return inst.components.eater:CanEat(item) end)
end
if not target then
target = FindEntity(inst, CFG.GOOSE.SEE_FOOD_DIST, function(item) return inst.components.eater:CanEat(item) end)
if target then
--check for scary things near the food
local predator = GetClosestInstWithTag("scarytoprey", target, CFG.GOOSE.SEE_PLAYER_DIST)
if predator then target = nil end
end
end
if target then
local act = BufferedAction(inst, target, ACTIONS.EAT)
act.validfn = function() return not (target.components.inventoryitem and target.components.inventoryitem.owner and target.components.inventoryitem.owner ~= inst) end
return act
end
end
function GooseBrain:OnStart()
local clock = GetPseudoClock()
local root = PriorityNode(
{
WhileNode( function() return self.inst.components.health.takingfiredamage end, "OnFire", Panic(self.inst)),
DoAction(self.inst, EatFoodAction, "Eat Food"),
RunAway(self.inst, "scarytoprey", CFG.GOOSE.SEE_PLAYER_DIST, CFG.GOOSE.STOP_RUN_DIST),
Wander(self.inst, HomePos, CFG.GOOSE.MAX_WANDER_DIST),
}, .25)
self.bt = BT(self.inst, root)
end
return GooseBrain | gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c17086528.lua | 3 | 3748 | --相生の魔術師
function c17086528.initial_effect(c)
--pendulum summon
aux.AddPendulumProcedure(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--rank
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_PZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1)
e2:SetTarget(c17086528.rktg)
e2:SetOperation(c17086528.rkop)
c:RegisterEffect(e2)
--scale
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_CHANGE_LSCALE)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetRange(LOCATION_PZONE)
e3:SetCondition(c17086528.slcon)
e3:SetValue(4)
c:RegisterEffect(e3)
local e4=e3:Clone()
e4:SetCode(EFFECT_CHANGE_RSCALE)
c:RegisterEffect(e4)
--damage 0
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_SINGLE)
e5:SetCode(EFFECT_NO_BATTLE_DAMAGE)
c:RegisterEffect(e5)
--atk
local e6=Effect.CreateEffect(c)
e6:SetCategory(CATEGORY_ATKCHANGE)
e6:SetType(EFFECT_TYPE_IGNITION)
e6:SetRange(LOCATION_MZONE)
e6:SetProperty(EFFECT_FLAG_CARD_TARGET)
e6:SetCountLimit(1)
e6:SetTarget(c17086528.atktg)
e6:SetOperation(c17086528.atkop)
c:RegisterEffect(e6)
end
function c17086528.rkfilter(c,tp)
return c:IsFaceup() and c:IsType(TYPE_XYZ)
and Duel.IsExistingTarget(c17086528.lvfilter,tp,LOCATION_MZONE,0,1,c,c:GetRank())
end
function c17086528.lvfilter(c,rk)
return c:IsFaceup() and c:IsLevelAbove(5) and c:GetLevel()~=rk
end
function c17086528.rktg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
if chk==0 then return Duel.IsExistingTarget(c17086528.rkfilter,tp,LOCATION_MZONE,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
local g=Duel.SelectTarget(tp,c17086528.rkfilter,tp,LOCATION_MZONE,0,1,1,nil,tp)
e:SetLabelObject(g:GetFirst())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,c17086528.lvfilter,tp,LOCATION_MZONE,0,1,1,g:GetFirst(),g:GetFirst():GetRank())
end
function c17086528.rkop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local tc=e:GetLabelObject()
local tg=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local lc=tg:GetFirst()
if lc==tc then lc=tg:GetNext() end
if tc:IsRelateToEffect(e) and tc:IsFaceup() and lc:IsRelateToEffect(e) and lc:IsFaceup() and lc:IsLevelAbove(5) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_RANK)
e1:SetValue(lc:GetLevel())
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END)
tc:RegisterEffect(e1)
end
end
function c17086528.slcon(e)
local tp=e:GetHandlerPlayer()
return Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,0)>Duel.GetFieldGroupCount(tp,0,LOCATION_ONFIELD)
end
function c17086528.atkfilter(c,atk)
return c:IsFaceup() and c:GetAttack()~=atk
end
function c17086528.atktg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local c=e:GetHandler()
local atk=c:GetAttack()
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and chkc~=c and c17086528.atkfilter(chkc,atk) end
if chk==0 then return Duel.IsExistingTarget(c17086528.atkfilter,tp,LOCATION_MZONE,0,1,c,atk) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,c17086528.atkfilter,tp,LOCATION_MZONE,0,1,1,c,atk)
end
function c17086528.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
local atk=tc:GetAttack()
if tc:IsRelateToEffect(e) and tc:IsFaceup() and c:IsRelateToEffect(e) and c:IsFaceup() then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetValue(atk)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END)
c:RegisterEffect(e1)
end
end
| gpl-2.0 |
rickyHong/nn_lib_torch | Euclidean.lua | 1 | 5673 | local Euclidean, parent = torch.class('nn.Euclidean', 'nn.Module')
function Euclidean:__init(inputSize,outputSize)
parent.__init(self)
self.weight = torch.Tensor(inputSize,outputSize)
self.gradWeight = torch.Tensor(inputSize,outputSize)
-- state
self.gradInput:resize(inputSize)
self.output:resize(outputSize)
self.fastBackward = true
self:reset()
end
function Euclidean:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.weight:size(1))
end
if nn.oldSeed then
for i=1,self.weight:size(2) do
self.weight:select(2, i):apply(function()
return torch.uniform(-stdv, stdv)
end)
end
else
self.weight:uniform(-stdv, stdv)
end
end
local function view(res, src, ...)
local args = {...}
if src:isContiguous() then
res:view(src, unpack(args))
else
res:reshape(src, unpack(args))
end
end
function Euclidean:updateOutput(input)
-- lazy initialize buffers
self._input = self._input or input.new()
self._weight = self._weight or self.weight.new()
self._expand = self._expand or self.output.new()
self._expand2 = self._expand2 or self.output.new()
self._repeat = self._repeat or self.output.new()
self._repeat2 = self._repeat2 or self.output.new()
local inputSize, outputSize = self.weight:size(1), self.weight:size(2)
-- y_j = || w_j - x || = || x - w_j ||
if input:dim() == 1 then
view(self._input, input, inputSize, 1)
self._expand:expandAs(self._input, self.weight)
self._repeat:resizeAs(self._expand):copy(self._expand)
self._repeat:add(-1, self.weight)
self.output:norm(self._repeat, 2, 1)
self.output:resize(outputSize)
elseif input:dim() == 2 then
local batchSize = input:size(1)
view(self._input, input, batchSize, inputSize, 1)
self._expand:expand(self._input, batchSize, inputSize, outputSize)
-- make the expanded tensor contiguous (requires lots of memory)
self._repeat:resizeAs(self._expand):copy(self._expand)
self._weight:view(self.weight, 1, inputSize, outputSize)
self._expand2:expandAs(self._weight, self._repeat)
if torch.type(input) == 'torch.CudaTensor' then
-- requires lots of memory, but minimizes cudaMallocs and loops
self._repeat2:resizeAs(self._expand2):copy(self._expand2)
self._repeat:add(-1, self._repeat2)
else
self._repeat:add(-1, self._expand2)
end
self.output:norm(self._repeat, 2, 2)
self.output:resize(batchSize, outputSize)
else
error"1D or 2D input expected"
end
return self.output
end
function Euclidean:updateGradInput(input, gradOutput)
if not self.gradInput then
return
end
self._div = self._div or input.new()
self._output = self._output or self.output.new()
self._gradOutput = self._gradOutput or input.new()
self._expand3 = self._expand3 or input.new()
if not self.fastBackward then
self:updateOutput(input)
end
local inputSize, outputSize = self.weight:size(1), self.weight:size(2)
--[[
dy_j -2 * (w_j - x) x - w_j
---- = --------------- = -------
dx 2 || w_j - x || y_j
--]]
-- to prevent div by zero (NaN) bugs
self._output:resizeAs(self.output):copy(self.output):add(0.0000001)
view(self._gradOutput, gradOutput, gradOutput:size())
self._div:cdiv(gradOutput, self._output)
if input:dim() == 1 then
self._div:resize(1, outputSize)
self._expand3:expandAs(self._div, self.weight)
if torch.type(input) == 'torch.CudaTensor' then
self._repeat2:resizeAs(self._expand3):copy(self._expand3)
self._repeat2:cmul(self._repeat)
else
self._repeat2:cmul(self._repeat, self._expand3)
end
self.gradInput:sum(self._repeat2, 2)
self.gradInput:resizeAs(input)
elseif input:dim() == 2 then
local batchSize = input:size(1)
self._div:resize(batchSize, 1, outputSize)
self._expand3:expand(self._div, batchSize, inputSize, outputSize)
if torch.type(input) == 'torch.CudaTensor' then
self._repeat2:resizeAs(self._expand3):copy(self._expand3)
self._repeat2:cmul(self._repeat)
else
self._repeat2:cmul(self._repeat, self._expand3)
end
self.gradInput:sum(self._repeat2, 3)
self.gradInput:resizeAs(input)
else
error"1D or 2D input expected"
end
return self.gradInput
end
function Euclidean:accGradParameters(input, gradOutput, scale)
local inputSize, outputSize = self.weight:size(1), self.weight:size(2)
scale = scale or 1
--[[
dy_j 2 * (w_j - x) w_j - x
---- = --------------- = -------
dw_j 2 || w_j - x || y_j
--]]
-- assumes a preceding call to updateGradInput
if input:dim() == 1 then
self.gradWeight:add(-scale, self._repeat2)
elseif input:dim() == 2 then
self._sum = self._sum or input.new()
self._sum:sum(self._repeat2, 1)
self._sum:resize(inputSize, outputSize)
self.gradWeight:add(-scale, self._sum)
else
error"1D or 2D input expected"
end
end
function Euclidean:type(type)
if type then
-- prevent premature memory allocations
self._input = nil
self._output = nil
self._gradOutput = nil
self._weight = nil
self._div = nil
self._sum = nil
self._expand = nil
self._expand2 = nil
self._expand3 = nil
self._repeat = nil
self._repeat2 = nil
end
return parent.type(self, type)
end
| bsd-3-clause |
freifunk-gluon/luci | applications/luci-asterisk/luasrc/model/cbi/asterisk-iax-connections.lua | 80 | 2000 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
cbimap = Map("asterisk", "asterisk", "")
iax = cbimap:section(TypedSection, "iax", "IAX Connection", "")
iax.addremove = true
alwaysinternational = iax:option(Flag, "alwaysinternational", "Always Dial International", "")
alwaysinternational.optional = true
context = iax:option(ListValue, "context", "Context to use", "")
context.titleref = luci.dispatcher.build_url( "admin", "services", "asterisk", "dialplans" )
cbimap.uci:foreach( "asterisk", "dialplan", function(s) context:value(s['.name']) end )
cbimap.uci:foreach( "asterisk", "dialzone", function(s) context:value(s['.name']) end )
countrycode = iax:option(Value, "countrycode", "Country Code for connection", "")
countrycode.optional = true
extension = iax:option(Value, "extension", "Add as Extension", "")
extension.optional = true
host = iax:option(Value, "host", "Host name (or blank)", "")
host.optional = true
internationalprefix = iax:option(Value, "internationalprefix", "International Dial Prefix", "")
internationalprefix.optional = true
prefix = iax:option(Value, "prefix", "Dial Prefix (for external line)", "")
prefix.optional = true
secret = iax:option(Value, "secret", "Secret", "")
secret.optional = true
timeout = iax:option(Value, "timeout", "Dial Timeout (sec)", "")
timeout.optional = true
type = iax:option(ListValue, "type", "Option type", "")
type:value("friend", "Friend (outbound/inbound)")
type:value("user", "User (inbound - authenticate by \"from\")")
type:value("peer", "Peer (outbound - match by host)")
type.optional = true
username = iax:option(Value, "username", "User name", "")
username.optional = true
return cbimap
| apache-2.0 |
anshkumar/yugioh-glaze | assets/script/c8275702.lua | 5 | 1203 | --宝玉の契約
function c8275702.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c8275702.sptg)
e1:SetOperation(c8275702.spop)
c:RegisterEffect(e1)
end
function c8275702.filter(c,e,sp)
return c:IsFaceup() and c:IsSetCard(0x1034) and c:IsCanBeSpecialSummoned(e,0,sp,true,false)
end
function c8275702.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_SZONE) and chkc:IsControler(tp) and c8275702.filter(chkc,e,tp) end
if chk==0 then return Duel.IsExistingTarget(c8275702.filter,tp,LOCATION_SZONE,0,1,nil,e,tp)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c8275702.filter,tp,LOCATION_SZONE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c8275702.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,true,false,POS_FACEUP)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c14344682.lua | 3 | 1051 | --サムライソード・バロン
function c14344682.initial_effect(c)
--pos change
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(14344682,0))
e1:SetCategory(CATEGORY_POSITION)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetTarget(c14344682.target)
e1:SetOperation(c14344682.operation)
c:RegisterEffect(e1)
end
function c14344682.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and chkc:IsDefencePos() end
if chk==0 then return Duel.IsExistingTarget(Card.IsDefencePos,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DEFENCE)
local g=Duel.SelectTarget(tp,Card.IsDefencePos,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_POSITION,g,1,0,0)
end
function c14344682.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsDefencePos() then
Duel.ChangePosition(tc,POS_FACEUP_ATTACK)
end
end
| gpl-2.0 |
TurBoss/Zero-K-Infrastructure | Benchmarker/Benchmarks/games/path_test.sdd/Luaui/Widgets/cmd_path_test_creator.lua | 12 | 4474 | function widget:GetInfo()
return {
name = "Path test creator",
desc = "allows to easily create path test configs",
author = "BD",
license = "WTFPL",
layer = 0,
enabled = true
}
end
local TEST_PATH = "pathTests"
local mapModString = Game.mapName .. "-".. Game.modShortName .. " " .. Game.modVersion
local configFilePath = TEST_PATH .. "/config/" .. mapModString .. ".lua"
local GetSelectedUnits = Spring.GetSelectedUnits
local GetUnitCommands = Spring.GetUnitCommands
local GetUnitPosition = Spring.GetUnitPosition
local GetUnitDefID = Spring.GetUnitDefID
local RequestPath = Spring.RequestPath
local GetUnitTeam = Spring.GetUnitTeam
local SendCommands = Spring.SendCommands
local GiveOrderToUnit = Spring.GiveOrderToUnit
local Echo = Spring.Echo
local CMD_MOVE = CMD.MOVE
local CMD_FIRE_STATE = CMD.FIRE_STATE
local max = math.max
local ceil = math.ceil
local testScheduled = {}
include("savetable.lua")
function sqDist(posA,posB)
return (posA[1]-posB[1])^2+(posA[2]-posB[2])^2+(posA[3]-posB[3])^2
end
local function getPathDist(startPos,endPos, moveType, radius)
local path = RequestPath(moveType or 1, startPos[1],startPos[2],startPos[3],endPos[1],endPos[2],endPos[3], radius)
if not path then --startpoint is blocked
startPos,endPos = endPos,startPos
local path = RequestPath(moveType or 1, startPos[1],startPos[2],startPos[3],endPos[1],endPos[2],endPos[3], radius)
if not path then
return --if startpoint and endpoint is blocked path is not calculated
end
end
local dist = 0
local xyzs, iii = path.GetPathWayPoints(path)
for i,pxyz in ipairs(xyzs) do
local endPos = pxyz
dist = dist + sqDist(endPos,startPos)^0.5
startPos = endPos
end
return dist
end
function addTest(_,_,params)
local distTollerance = params[1] or 25
local nextTestDelay = params[2]
local arrivalTimeout = params[3]
local testEntry = {}
local maxSelfdTime = 0
testEntry.unitList = {}
testEntry.delayToNextTest = 0
for unitIndex, unitID in ipairs(GetSelectedUnits()) do
local unitPos = {GetUnitPosition(unitID)}
local unitDefID = GetUnitDefID(unitID)
local unitQueue = GetUnitCommands(unitID)
local unitDef = UnitDefs[unitDefID]
local teamID = GetUnitTeam(unitID)
local moveType, radius, speed,selfDTime = unitDef.moveData.id, unitDef.radius, unitDef.speed or 0, unitDef.selfDCountdown*30
local previousPos = unitPos
local donTProcess = false
local distance = 0
local destinations = {}
if unitQueue then
for pos, command in ipairs(unitQueue) do
if command.id == CMD_MOVE then
local wayPointPos = command.params
for _, coord in ipairs(wayPointPos) do
coord = ceil(coord)
end
distance = distance + (getPathDist(previousPos,wayPointPos, moveType, radius) or 0 )
previousPos = wayPointPos
table.insert(destinations,wayPointPos)
end
end
end
for _, coord in ipairs(unitPos) do
coord = ceil(coord)
end
local unitEntry = {}
unitEntry.unitName = UnitDefs[unitDefID].name
unitEntry.startCoordinates = unitPos
unitEntry.maxTargetDist = distTollerance
unitEntry.maxTravelTime = arrivalTimeout or ceil(distance / speed * 30 * 2)
unitEntry.destinationCoordinates = destinations
unitEntry.teamID = teamID
testEntry.delayToNextTest = nextTestDelay or max(testEntry.delayToNextTest,selfDTime*2.2)
table.insert(testEntry.unitList,unitEntry)
end
table.insert(testScheduled,testEntry)
--save result table to a file
table.save( testScheduled, LUAUI_DIRNAME .. "/" .. configFilePath )
Echo("added test " .. #testScheduled)
end
function deleteTest(_,_,params)
local index = tonumber(params[1])
if not index then
Echo("invalid test id")
return
end
if testScheduled[index] then
Echo("deleted test " .. index)
testScheduled[index] = nil
--save result table to a file
table.save( testScheduled, LUAUI_DIRNAME .. "/" .. configFilePath )
end
end
function file_exists(name)
local f = io.open(name,"r")
if f then
io.close(f)
return true
else
return false
end
end
function widget:UnitCreated(unitID,unitDefID, unitTeam)
--set hold fire
GiveOrderToUnit(unitID,CMD_FIRE_STATE,{0},{})
end
function widget:Initialize()
if file_exists(LUAUI_DIRNAME .. "/" .. configFilePath) then
testScheduled = include(configFilePath)
end
widgetHandler:AddAction("addpathtest", addTest, nil, "t")
widgetHandler:AddAction("delpathtest", deleteTest, nil, "t")
SendCommands({"cheat 1","godmode 1","globallos","spectator"})
end
| gpl-3.0 |
chenjiansnail/skynet | examples/watchdog.lua | 12 | 1173 | local skynet = require "skynet"
local netpack = require "netpack"
local CMD = {}
local SOCKET = {}
local gate
local agent = {}
function SOCKET.open(fd, addr)
skynet.error("New client from : " .. addr)
agent[fd] = skynet.newservice("agent")
skynet.call(agent[fd], "lua", "start", { gate = gate, client = fd, watchdog = skynet.self() })
end
local function close_agent(fd)
local a = agent[fd]
agent[fd] = nil
if a then
skynet.call(gate, "lua", "kick", fd)
-- disconnect never return
skynet.send(a, "lua", "disconnect")
end
end
function SOCKET.close(fd)
print("socket close",fd)
close_agent(fd)
end
function SOCKET.error(fd, msg)
print("socket error",fd, msg)
close_agent(fd)
end
function SOCKET.data(fd, msg)
end
function CMD.start(conf)
skynet.call(gate, "lua", "open" , conf)
end
function CMD.close(fd)
close_agent(fd)
end
skynet.start(function()
skynet.dispatch("lua", function(session, source, cmd, subcmd, ...)
if cmd == "socket" then
local f = SOCKET[subcmd]
f(...)
-- socket api don't need return
else
local f = assert(CMD[cmd])
skynet.ret(skynet.pack(f(subcmd, ...)))
end
end)
gate = skynet.newservice("gate")
end)
| mit |
Dith3r/FrameworkBenchmarks | frameworks/Lua/openresty/app.lua | 25 | 2311 | local mysql = mysql
local encode = encode
local random = math.random
local min = math.min
local insert = table.insert
local sort = table.sort
local template = require'resty.template'
local ngx = ngx
local ngx_print = ngx.print
template.caching(false)
-- Compile template, disable cache, enable plain text view to skip filesystem loading
local view = template.compile([[<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>{% for _,f in ipairs(fortunes) do %}<tr><td>{{ f.id }}</td><td>{{ f.message }}</td></tr>{% end %}</table></body></html>]], nil, true)
local mysqlconn = {
host = os.getenv("DBIP"),
port = 3306,
database = "hello_world",
user = "benchmarkdbuser",
password = "benchmarkdbpass"
}
local _M = {}
function _M.db()
local db = mysql:new()
assert(db:connect(mysqlconn))
ngx_print(encode(db:query('SELECT * FROM World WHERE id = '..random(1,10000))[1]))
db:set_keepalive(0, 256)
end
function _M.queries()
local db = mysql:new()
assert(db:connect(mysqlconn))
local num_queries = tonumber(ngx.var.arg_queries) or 1
-- May seem like a stupid branch, but since we know that
-- at a benchmark it will always be taken one way,
-- it doesn't matter. For me, after a small warmup, the performance
-- is identical to a version without the branch
-- http://wiki.luajit.org/Numerical-Computing-Performance-Guide
if num_queries < 2 then
ngx_print(encode({db:query('SELECT * FROM World WHERE id = '..random(1,10000))[1]}))
else
local worlds = {}
num_queries = min(500, num_queries)
for i=1, num_queries do
worlds[#worlds+1] = db:query('SELECT * FROM World WHERE id = '..random(1,10000))[1]
end
ngx_print( encode(worlds) )
end
db:set_keepalive(0, 256)
end
function _M.fortunes()
local db = mysql:new()
assert(db:connect(mysqlconn))
local fortunes = db:query('SELECT * FROM Fortune')
insert(fortunes, {
id = 0,
message = "Additional fortune added at request time."
})
sort(fortunes, function(a, b)
return a.message < b.message
end)
local res = view{fortunes=fortunes}
ngx.header['Content-Length'] = #res
ngx_print(res)
db:set_keepalive(0, 256)
end
return _M
| bsd-3-clause |
anshkumar/yugioh-glaze | assets/script/c97007933.lua | 3 | 2819 | --HSR魔剣ダーマ
function c97007933.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1)
c:EnableReviveLimit()
--pierce
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_PIERCE)
c:RegisterEffect(e1)
--damage
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(97007933,0))
e2:SetCategory(CATEGORY_DAMAGE)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,97007933)
e2:SetCost(c97007933.damcost)
e2:SetTarget(c97007933.damtg)
e2:SetOperation(c97007933.damop)
c:RegisterEffect(e2)
--spsummon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(97007933,1))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_GRAVE)
e3:SetCountLimit(1,97007934)
e3:SetCondition(c97007933.spcon)
e3:SetCost(c97007933.spcost)
e3:SetTarget(c97007933.sptg)
e3:SetOperation(c97007933.spop)
c:RegisterEffect(e3)
end
function c97007933.cfilter(c)
return c:IsRace(RACE_MACHINE) and c:IsAbleToRemoveAsCost()
end
function c97007933.damcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c97007933.cfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c97007933.cfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c97007933.damtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(500)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,500)
end
function c97007933.damop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Damage(p,d,REASON_EFFECT)
end
function c97007933.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,0)==0
end
function c97007933.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetActivityCount(tp,ACTIVITY_NORMALSUMMON)==0 end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_SUMMON)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e1:SetReset(RESET_PHASE+RESET_END)
e1:SetTargetRange(1,0)
Duel.RegisterEffect(e1,tp)
local e2=e1:Clone()
e2:SetCode(EFFECT_CANNOT_MSET)
Duel.RegisterEffect(e2,tp)
end
function c97007933.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c97007933.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c36042004.lua | 9 | 1187 | --ベビケラサウルス
function c36042004.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(36042004,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c36042004.condition)
e1:SetTarget(c36042004.target)
e1:SetOperation(c36042004.operation)
c:RegisterEffect(e1)
end
function c36042004.condition(e,tp,eg,ep,ev,re,r,rp)
return bit.band(r,0x41)==0x41
end
function c36042004.filter(c,e,tp)
return c:IsLevelBelow(4) and c:IsRace(RACE_DINOSAUR)
and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c36042004.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c36042004.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c36042004.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c13026402.lua | 3 | 1292 | --トラップ処理班 Aチーム
function c13026402.initial_effect(c)
--Negate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(13026402,0))
e1:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_CHAINING)
e1:SetCondition(c13026402.condition)
e1:SetCost(c13026402.cost)
e1:SetTarget(c13026402.target)
e1:SetOperation(c13026402.activate)
c:RegisterEffect(e1)
end
function c13026402.condition(e,tp,eg,ep,ev,re,r,rp)
return not e:GetHandler():IsStatus(STATUS_BATTLE_DESTROYED) and rp~=tp
and re:IsActiveType(TYPE_TRAP) and re:IsHasType(EFFECT_TYPE_ACTIVATE) and Duel.IsChainNegatable(ev)
end
function c13026402.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReleasable() end
Duel.Release(e:GetHandler(),REASON_COST)
end
function c13026402.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0)
if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
end
function c13026402.activate(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateActivation(ev)
if re:GetHandler():IsRelateToEffect(re) then
Duel.Destroy(eg,REASON_EFFECT)
end
end
| gpl-2.0 |
Ced-le-pingouin/microlua-sim | clp/mls/modules/wx/Font_Bitmap.lua | 2 | 26923 | -------------------------------------------------------------------------------
-- Micro Lua Font module simulation, based on wxWidgets.
--
-- @class module
-- @name clp.mls.modules.wx.Font_Bitmap
-- @author Ced-le-pingouin <Ced.le.pingouin@gmail.com>
-------------------------------------------------------------------------------
-- Copyright (C) 2009-2011 Cédric FLOQUET
--
-- This file is part of Micro Lua DS Simulator.
--
-- Micro Lua DS Simulator 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.
--
-- Micro Lua DS Simulator 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 Micro Lua DS Simulator. If not, see <http://www.gnu.org/licenses/>.
require "wx"
local Class = require "clp.Class"
local Sys = require "clp.mls.Sys"
local M = Class.new()
--- Module initialization function.
function M:initModule()
M.NUM_CHARS = 256
M.CACHE_MAX_STRINGS = 25
M.CACHE_MIN_STRING_LEN = 1
M._initDefaultFont()
end
--- Creates a new font from a font file (oslib and µLibray format) [ML 2+ API].
--
-- @param path (string) The path of the file to load
--
-- @return (Font) The loaded font. This is library/implementation dependent
function M.load(path)
Mls.logger:debug("loading font "..path, "font")
path = Sys.getFile(path)
local file = wx.wxFile(path, wx.wxFile.read)
assert(file:IsOpened(), "Unable to open file "..path)
local font = {}
font.strVersion = M._readString(file, 12)
assert(font.strVersion == "OSLFont v01\0", "Incorrect font file")
font.path = path
font.pixelFormat = M._readByte(file)
assert(font.pixelFormat == 1,
"Micro Lua Simulator only supports 1-bit fonts")
font.variableWidth = (M._readByte(file) == 1)
font.charWidth = M._readInt(file)
font.charHeight = M._readInt(file)
font.lineWidth = M._readInt(file)
font.addedSpace = M._readByte(file)
font.paletteCount = M._readShort(file)
font.cachedStrings = {}
font.cachedContent = {}
assert(font.paletteCount == 0,
"Micro Lua Simulator doesn't support palette info in fonts")
-- 29 unused bytes, makes 58 bytes total (why?)
M._readString(file, 29)
-- anyway it's incorrect, since C has probably added padding bytes to match
-- a 32 bit boundary, so there's more bytes in the header
local boundary = math.ceil(file:Tell() / 8) * 8
local paddingBytes = boundary - file:Tell()
M._readString(file, paddingBytes)
-- chars widths (variable or fixed)
local charsWidths = {}
if font.variableWidth then
for charNum = 1, M.NUM_CHARS do
charsWidths[charNum] = M._readByte(file)
end
else
for charNum = 1, M.NUM_CHARS do
charsWidths[charNum] = font.charWidth
end
end
font.charsWidths = charsWidths
-- chars raw data
local charsDataSize = M.NUM_CHARS * font.charHeight
* font.lineWidth
local charsRawData = {}
for i = 1, charsDataSize do
charsRawData[i] = M._readByte(file)
end
-- we should now read palette info if available, but I think it's never used
-- in Micro Lua fonts
file:Close()
M._createImageFromRawData(font, charsRawData)
return font
end
-- Destroys resources used by a font [ML 2+ API] NOT DOCUMENTED ? .
--
-- @param font (Font)
function M.destroy(font)
font._DC:delete()
font._DC = nil
font._bitmap:delete()
font._bitmap = nil
font._image:Destroy()
font._image = nil
end
--- Prints a text with a special font [ML 2+ API].
--
-- @param screenNum (number) The screen to draw to (SCREEN_UP or SCREEN_DOWN)
-- @param font (Font) The font to use
-- @param x (number) The x coordinate to draw to
-- @param y (number) The y coordinate to draw to
-- @param text (string) The text to print
-- @param color (Color) The color of the text
-- @param _useColor (boolean) This is an INTERNAL parameter to reproduce a ML
-- bug, where color is ignore when using Font.print,
-- but used when using the print functions in screen
function M.print(screenNum, font, x, y, text, color, _useColor)
if not _useColor then color = nil end
local offscreenDC = screen._getOffscreenDC(screenNum)
M._printNoClip(screenNum, font, x, screen.offset[screenNum] + y, text,
color)
end
--- Prints a text, without using clipping at screen limits.
--
-- @param screenNum (number) The screen to draw to (SCREEN_UP or SCREEN_DOWN)
-- @param font (Font) The font to use
-- @param x (number) The x coordinate to draw to
-- @param y (number) The y coordinate to draw to
-- @param text (string) The text to print
-- @param color (Color) The color of the text
--
-- @see print
--
-- @todo Since I use lua length operator and process *bytes* (NOT characters) to
-- display characters, only ASCII texts will work correctly
-- @todo Is this the correct use of addedSpace ?
function M._printNoClip(screenNum, font, x, y, text, color)
if type(text) == "number" then text = tostring(text) end
if #text == 0 then return end
if not color then color = Color.WHITE end
local offscreenDC = screen.offscreenDC
local stringBitmap
if not font.cachedStrings[text] then
--print(string.format("'%s' just CACHED", text))
stringBitmap = M._printToCache(font, text, color)
else
stringBitmap = font.cachedStrings[text]
end
local textDC = wx.wxMemoryDC()
textDC:SelectObject(stringBitmap)
screen._brush:SetColour(color)
textDC:SetBackground(screen._brush)
textDC:Clear()
textDC:delete()
offscreenDC:DrawBitmap(stringBitmap, x, y, true)
end
--- Renders a whole string to a bitmap then puts it in a cache.
--
-- This way, a new request to display the same string with the same font would
-- display the bitmap at once, rather than printing each character again.
--
-- The minimum number of characters for a string to be cached is configured with
-- CACHE_MIN_STRING_LEN.
-- You can also set the maximum number of cached string for one font with
-- CACHE_MAX_STRINGS.
--
-- @param font (Font)
-- @param text (string)
-- @param color (Color)
--
-- @return (wxBitmap) The rendered bitmap representing the text
--
-- @see _printNoClip
function M._printToCache(font, text, color)
local textBitmap = wx.wxBitmap(M.getStringWidth(font, text),
M.getCharHeight(font), Mls.DEPTH)
local textDC = wx.wxMemoryDC()
textDC:SelectObject(textBitmap)
textDC:SetBackground(wx.wxBLACK_BRUSH)
textDC:Clear()
local len = #text
local x, y = 0, 0
local fontDC = font._DC
local charsWidths, charHeight = font.charsWidths, font.charHeight
local charsPos = font.charsPos
local addedSpace = font.addedSpace
for i = 1, len do
local charNum = text:sub(i, i):byte() + 1
textDC:Blit(x, y,
charsWidths[charNum], charHeight,
fontDC,
charsPos[charNum].x, charsPos[charNum].y,
wx.wxCOPY, false)
x = x + charsWidths[charNum] + addedSpace
--if (x > SCREEN_WIDTH) then break end
end
textDC:delete()
textBitmap:SetMask(wx.wxMask(textBitmap, wx.wxBLACK))
if #text >= M.CACHE_MIN_STRING_LEN then
if #font.cachedContent >= M.CACHE_MAX_STRINGS then
font.cachedStrings[font.cachedContent[1]]:delete()
font.cachedStrings[font.cachedContent[1]] = nil
table.remove(font.cachedContent, 1)
end
font.cachedStrings[text] = textBitmap
font.cachedContent[#font.cachedContent+1] = text
end
return textBitmap
end
--- Gets the pixel height of the characters of a font [ML 2+ API].
--
-- @param font (Font) The font to use
--
-- @return (number)
function M.getCharHeight(font)
return font.charHeight
end
--- Gets the pixel width of a text with a specific font [ML 3+ API].
--
-- @param font (Font) The font to use
-- @param text (string)
--
-- @return (number)
--
-- @todo Since I use lua length operator and process *bytes* (NOT characters) to
-- display characters, only ASCII texts will work correctly
-- @todo Is this the correct use of addedSpace ?
function M.getStringWidth(font, text)
if #text == 0 then return 0 end
local width = 0
local len = #text
if not font.variableWidth then
return (font.charWidth * len) + (font.addedSpace * len)
end
local charsWidths, addedSpace = font.charsWidths, font.addedSpace
for i = 1, len do
local charNum = text:sub(i, i):byte() + 1
width = width + charsWidths[charNum] + addedSpace
end
return width
end
--- Reads a string from a binary file.
--
-- @param file (wxFile) A file handler
-- @param count (number) The number of bytes (=characters in this case) to read
--
-- @return (string)
function M._readString(file, count)
local _, str
_, str = file:Read(count)
return str
end
--- Reads a byte from a binary file.
--
-- @param file (wxFile) A file handler
--
-- @return (number)
function M._readByte(file)
local _, b
_, b = file:Read(1)
return b:byte(1)
end
--- Reads a short integer (2 bytes) from a binary file.
--
-- @param file (wxFile) A file handler
--
-- @return (number)
function M._readShort(file)
local hi, low
low = M._readByte(file)
hi = M._readByte(file)
return (hi * 256) + low
end
--- Reads an integer (4 bytes) from a binary file.
--
-- @param file (wxFile) A file handler
--
-- @return (number)
function M._readInt(file)
local hi, low
hi = M._readShort(file)
low = M._readShort(file)
return (hi * 65536) + low
end
--- Creates an internal image from "raw" font data.
--
-- @param font (Font) The font to use
-- @param rawData (table) The data used to create the font characters image.
-- This is library/implementation dependent
--
-- @todo Make the image as small as needed ?
function M._createImageFromRawData(font, rawData)
local maxImageWidth = 512
local maxCharWidth = font.charWidth
-- I could use the lineWidth info to get max char width, but it is less
-- precise
if font.variableWidth then
for i = 1, M.NUM_CHARS do
maxCharWidth = math.max(maxCharWidth, font.charsWidths[i])
end
end
local charsPerRow = math.floor(maxImageWidth / maxCharWidth)
local numLines = math.ceil(M.NUM_CHARS / charsPerRow)
local width, height = charsPerRow * maxCharWidth, numLines * font.charHeight
local image = wx.wxImage(width, height, true)
local indexRawData = 1
local r, g, b = 255, 255, 255
local imageX, imageY = 0, 0
local charsPos = {}
for charNum = 1, M.NUM_CHARS do
charsPos[charNum] = { x = imageX, y = imageY }
local charWidth = font.charsWidths[charNum]
for lineInChar = 1, font.charHeight do
local xInLine = 1
for byteNum = 1, font.lineWidth do
byte = rawData[indexRawData]
for bit = 1, 8 do
if M._hasBitSet(byte, bit - 1) then
image:SetRGB(imageX + xInLine - 1,
imageY + lineInChar - 1,
r, g, b)
end
xInLine = xInLine + 1
if xInLine > charWidth then break end
end
indexRawData = indexRawData + 1
end
end
imageX = imageX + charWidth
if imageX >= width then
imageX = 0
imageY = imageY + font.charHeight
end
end
local mr, mg, mb = 0, 0, 0
image:SetMaskColour(mr, mg, mb)
image:SetMask(true)
font._image = image
font.charsPos = charsPos
font._bitmap = wx.wxBitmap(image, Mls.DEPTH)
font._DC = wx.wxMemoryDC()
font._DC:SelectObject(font._bitmap)
font._lastColor = wx.wxWHITE
end
--- Checks whether a specific bit is set in a number.
--
-- @param number (number) The number
-- @param bit (number) The bit number to check
--
-- @return (boolean)
function M._hasBitSet(number, bit)
local bitValue = 2 ^ bit
return number % (bitValue * 2) >= bitValue
end
--- Initializes the ML default font, which is always available.
function M._initDefaultFont()
Mls.logger:info("initializing default font", "font")
local font = {}
font.path = "Default font"
font.pixelFormat = 1
font.variableWidth = false
font.charWidth = 6
font.charHeight = 8
font.lineWidth = 1
font.addedSpace = 0
font.paletteCount = 0
font.cachedStrings = {}
font.cachedContent = {}
local charsWidths = {}
for charNum = 1, M.NUM_CHARS do
charsWidths[charNum] = font.charWidth
end
font.charsWidths = charsWidths
M._createImageFromRawData(font, {
0x2a, 0x15, 0x2a, 0x15, 0x2a, 0x15, 0x2a, 0x15,
0xc, 0x2, 0x4, 0x28, 0x2e, 0x38, 0x28, 0x28,
0xc, 0x2, 0x4, 0x28, 0x2e, 0x10, 0x28, 0x28,
0xe, 0x2, 0x6, 0x2a, 0x2e, 0x10, 0x28, 0x28,
0xe, 0x2, 0x6, 0x2, 0x3e, 0x10, 0x10, 0x10,
0xe, 0x2, 0x6, 0x3a, 0x2e, 0x28, 0x18, 0x30,
0x4, 0xa, 0xe, 0xa, 0x2a, 0x18, 0x18, 0x28,
0x0, 0x8, 0x1c, 0x1c, 0x1c, 0x3e, 0x8, 0x0,
0x0, 0x38, 0x3c, 0x3e, 0x3c, 0x38, 0x0, 0x0,
0x20, 0x28, 0x38, 0x3e, 0x38, 0x28, 0x20, 0x0,
0x0, 0xe, 0x8, 0x8, 0x3e, 0x1c, 0x8, 0x0,
0x10, 0x28, 0x28, 0x2e, 0x1a, 0xe, 0x0, 0x0,
0x3e, 0x8, 0x1c, 0x3e, 0x8, 0x8, 0x8, 0x0,
0x20, 0x20, 0x28, 0x2c, 0x3e, 0xc, 0x8, 0x0,
0x1c, 0x22, 0x3e, 0x3e, 0x36, 0x36, 0x3e, 0x0,
0x0, 0x20, 0x10, 0xa, 0x4, 0x0, 0x0, 0x0,
0x0, 0x0, 0x1e, 0x1e, 0x1e, 0x1e, 0x0, 0x0,
0x0, 0x10, 0x18, 0x1c, 0x18, 0x10, 0x0, 0x0,
0x0, 0x4, 0xc, 0x1c, 0xc, 0x4, 0x0, 0x0,
0x0, 0x0, 0x8, 0x1c, 0x3e, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x3e, 0x1c, 0x8, 0x0, 0x0,
0x0, 0x8, 0x4, 0x3e, 0x4, 0x8, 0x0, 0x0,
0x0, 0x8, 0x10, 0x3e, 0x10, 0x8, 0x0, 0x0,
0x8, 0x1c, 0x2a, 0x8, 0x8, 0x8, 0x8, 0x0,
0x8, 0x8, 0x8, 0x8, 0x2a, 0x1c, 0x8, 0x0,
0x10, 0x18, 0x1c, 0x1e, 0x1e, 0x1c, 0x18, 0x10,
0x2, 0x6, 0xe, 0x1e, 0x1e, 0xe, 0x6, 0x2,
0x0, 0x8, 0x1c, 0x3e, 0x1c, 0x1c, 0x1c, 0x0,
0x0, 0x22, 0x22, 0x22, 0x22, 0x1c, 0x0, 0x0,
0x0, 0x1c, 0x22, 0x22, 0x22, 0x22, 0x0, 0x0,
0x0, 0x3c, 0x2, 0x2, 0x2, 0x3c, 0x0, 0x0,
0x0, 0x3c, 0x2, 0x3e, 0x2, 0x3c, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x8, 0x8, 0x8, 0x8, 0x0, 0x8, 0x8, 0x0,
0x14, 0x14, 0x14, 0x0, 0x0, 0x0, 0x0, 0x0,
0x14, 0x14, 0x3e, 0x14, 0x3e, 0x14, 0x14, 0x0,
0x8, 0x3c, 0xa, 0x1c, 0x28, 0x1e, 0x8, 0x0,
0x6, 0x26, 0x10, 0x8, 0x4, 0x32, 0x30, 0x0,
0x4, 0xa, 0xa, 0x4, 0x2a, 0x12, 0x2c, 0x0,
0x8, 0x8, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0,
0x10, 0x8, 0x4, 0x4, 0x4, 0x8, 0x10, 0x0,
0x4, 0x8, 0x10, 0x10, 0x10, 0x8, 0x4, 0x0,
0x0, 0x8, 0x2a, 0x1c, 0x2a, 0x8, 0x0, 0x0,
0x0, 0x8, 0x8, 0x3e, 0x8, 0x8, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xc, 0x8, 0x4,
0x0, 0x0, 0x0, 0x3e, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xc, 0xc, 0x0,
0x0, 0x20, 0x10, 0x8, 0x4, 0x2, 0x0, 0x0,
0x1c, 0x22, 0x22, 0x2a, 0x22, 0x22, 0x1c, 0x0,
0x8, 0xc, 0x8, 0x8, 0x8, 0x8, 0x1c, 0x0,
0x1c, 0x22, 0x20, 0x10, 0x8, 0x4, 0x3e, 0x0,
0x3e, 0x10, 0x8, 0x10, 0x20, 0x22, 0x1c, 0x0,
0x10, 0x18, 0x14, 0x12, 0x3e, 0x10, 0x10, 0x0,
0x3e, 0x2, 0x1e, 0x20, 0x20, 0x22, 0x1c, 0x0,
0x18, 0x4, 0x2, 0x1e, 0x22, 0x22, 0x1c, 0x0,
0x3e, 0x20, 0x10, 0x8, 0x4, 0x4, 0x4, 0x0,
0x1c, 0x22, 0x22, 0x1c, 0x22, 0x22, 0x1c, 0x0,
0x1c, 0x22, 0x22, 0x3c, 0x20, 0x10, 0xc, 0x0,
0x0, 0xc, 0xc, 0x0, 0xc, 0xc, 0x0, 0x0,
0x0, 0x0, 0xc, 0xc, 0x0, 0xc, 0x8, 0x4,
0x10, 0x8, 0x4, 0x2, 0x4, 0x8, 0x10, 0x0,
0x0, 0x0, 0x3e, 0x0, 0x3e, 0x0, 0x0, 0x0,
0x4, 0x8, 0x10, 0x20, 0x10, 0x8, 0x4, 0x0,
0x1c, 0x22, 0x20, 0x10, 0x8, 0x0, 0x8, 0x0,
0x1c, 0x22, 0x2a, 0x3a, 0xa, 0x2, 0x3c, 0x0,
0x1c, 0x22, 0x22, 0x3e, 0x22, 0x22, 0x22, 0x0,
0x1e, 0x22, 0x22, 0x1e, 0x22, 0x22, 0x1e, 0x0,
0x1c, 0x22, 0x2, 0x2, 0x2, 0x22, 0x1c, 0x0,
0x1e, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1e, 0x0,
0x3e, 0x2, 0x2, 0x1e, 0x2, 0x2, 0x3e, 0x0,
0x3e, 0x2, 0x2, 0x1e, 0x2, 0x2, 0x2, 0x0,
0x1c, 0x22, 0x2, 0x3a, 0x22, 0x22, 0x1c, 0x0,
0x22, 0x22, 0x22, 0x3e, 0x22, 0x22, 0x22, 0x0,
0x1c, 0x8, 0x8, 0x8, 0x8, 0x8, 0x1c, 0x0,
0x38, 0x10, 0x10, 0x10, 0x10, 0x12, 0xc, 0x0,
0x22, 0x12, 0xa, 0x6, 0xa, 0x12, 0x22, 0x0,
0x2, 0x2, 0x2, 0x2, 0x2, 0x2, 0x3e, 0x0,
0x22, 0x36, 0x2a, 0x2a, 0x22, 0x22, 0x22, 0x0,
0x22, 0x22, 0x26, 0x2a, 0x32, 0x22, 0x22, 0x0,
0x1c, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1c, 0x0,
0x1e, 0x22, 0x22, 0x1e, 0x2, 0x2, 0x2, 0x0,
0x1c, 0x22, 0x22, 0x22, 0x2a, 0x12, 0x2c, 0x0,
0x1e, 0x22, 0x22, 0x1e, 0xa, 0x12, 0x22, 0x0,
0x3c, 0x2, 0x2, 0x1c, 0x20, 0x20, 0x1e, 0x0,
0x3e, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x0,
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1c, 0x0,
0x22, 0x22, 0x22, 0x22, 0x22, 0x14, 0x8, 0x0,
0x22, 0x22, 0x22, 0x2a, 0x2a, 0x2a, 0x14, 0x0,
0x22, 0x22, 0x14, 0x8, 0x14, 0x22, 0x22, 0x0,
0x22, 0x22, 0x22, 0x14, 0x8, 0x8, 0x8, 0x0,
0x3e, 0x20, 0x10, 0x8, 0x4, 0x2, 0x3e, 0x0,
0x18, 0x8, 0x8, 0x8, 0x8, 0x8, 0x18, 0x0,
0x0, 0x2, 0x4, 0x8, 0x10, 0x20, 0x0, 0x0,
0x18, 0x10, 0x10, 0x10, 0x10, 0x10, 0x18, 0x0,
0x8, 0x14, 0x22, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3e, 0x0,
0x8, 0x8, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x1c, 0x20, 0x3c, 0x22, 0x3c, 0x0,
0x2, 0x2, 0x1a, 0x26, 0x22, 0x22, 0x1e, 0x0,
0x0, 0x0, 0x1c, 0x2, 0x2, 0x22, 0x1c, 0x0,
0x20, 0x20, 0x2c, 0x32, 0x22, 0x22, 0x3c, 0x0,
0x0, 0x0, 0x1c, 0x22, 0x3e, 0x2, 0x1c, 0x0,
0x18, 0x24, 0x4, 0xe, 0x4, 0x4, 0x4, 0x0,
0x0, 0x0, 0x3c, 0x22, 0x22, 0x3c, 0x20, 0x1c,
0x2, 0x2, 0x1a, 0x26, 0x22, 0x22, 0x22, 0x0,
0x8, 0x0, 0xc, 0x8, 0x8, 0x8, 0x1c, 0x0,
0x10, 0x0, 0x18, 0x10, 0x10, 0x10, 0x12, 0xc,
0x4, 0x4, 0x24, 0x14, 0xc, 0x14, 0x24, 0x0,
0xc, 0x8, 0x8, 0x8, 0x8, 0x8, 0x1c, 0x0,
0x0, 0x0, 0x16, 0x2a, 0x2a, 0x22, 0x22, 0x0,
0x0, 0x0, 0x1a, 0x26, 0x22, 0x22, 0x22, 0x0,
0x0, 0x0, 0x1c, 0x22, 0x22, 0x22, 0x1c, 0x0,
0x0, 0x0, 0x1e, 0x22, 0x22, 0x1e, 0x2, 0x2,
0x0, 0x0, 0x2c, 0x32, 0x22, 0x3c, 0x20, 0x20,
0x0, 0x0, 0x1a, 0x26, 0x2, 0x2, 0x2, 0x0,
0x0, 0x0, 0x1c, 0x2, 0x1c, 0x20, 0x1e, 0x0,
0x4, 0x4, 0xe, 0x4, 0x4, 0x24, 0x18, 0x0,
0x0, 0x0, 0x22, 0x22, 0x22, 0x32, 0x2c, 0x0,
0x0, 0x0, 0x22, 0x22, 0x22, 0x14, 0x8, 0x0,
0x0, 0x0, 0x22, 0x22, 0x2a, 0x2a, 0x14, 0x0,
0x0, 0x0, 0x22, 0x14, 0x8, 0x14, 0x22, 0x0,
0x0, 0x0, 0x22, 0x22, 0x22, 0x3c, 0x20, 0x1c,
0x0, 0x0, 0x3e, 0x10, 0x8, 0x4, 0x3e, 0x0,
0x30, 0x8, 0x8, 0x4, 0x8, 0x8, 0x30, 0x0,
0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x0,
0x6, 0x8, 0x8, 0x10, 0x8, 0x8, 0x6, 0x0,
0x0, 0x4, 0x2a, 0x10, 0x0, 0x0, 0x0, 0x0,
0x0, 0x8, 0x1c, 0x3e, 0x1c, 0x8, 0x0, 0x0,
0x0, 0x0, 0x2c, 0x12, 0x12, 0x12, 0x2c, 0x0,
0x18, 0x24, 0x24, 0x1c, 0x24, 0x24, 0x1a, 0x0,
0x3e, 0x22, 0x2, 0x2, 0x2, 0x2, 0x2, 0x0,
0x0, 0x0, 0x24, 0x2a, 0x10, 0x18, 0x18, 0x8,
0x0, 0x0, 0x0, 0x8, 0x14, 0x22, 0x3e, 0x0,
0x18, 0x4, 0x8, 0x14, 0x22, 0x22, 0x1c, 0x0,
0x0, 0x0, 0x1c, 0x2, 0xc, 0x2, 0x1c, 0x0,
0x34, 0x1c, 0x2, 0x2, 0x2, 0x1c, 0x20, 0x18,
0x18, 0x24, 0x22, 0x3e, 0x22, 0x12, 0xc, 0x0,
0x0, 0x4, 0x8, 0x10, 0x18, 0x24, 0x22, 0x0,
0x4, 0x18, 0x4, 0x18, 0x4, 0x4, 0x18, 0x8,
0x3e, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x0,
0x0, 0x0, 0x3e, 0x14, 0x14, 0x14, 0x32, 0x0,
0x0, 0x0, 0x8, 0x14, 0x14, 0xc, 0x4, 0x4,
0x3e, 0x4, 0x8, 0x10, 0x8, 0x4, 0x3e, 0x0,
0x0, 0x0, 0x3c, 0x12, 0x12, 0x12, 0xc, 0x0,
0x0, 0x0, 0x1c, 0xa, 0x8, 0x28, 0x10, 0x0,
0x0, 0x8, 0x8, 0x1c, 0x2a, 0x1c, 0x8, 0x8,
0x0, 0x0, 0x2a, 0x2a, 0x2a, 0x1c, 0x8, 0x8,
0x1c, 0x22, 0x22, 0x22, 0x14, 0x14, 0x36, 0x0,
0x0, 0x0, 0x14, 0x22, 0x2a, 0x2a, 0x14, 0x0,
0x0, 0x0, 0x3c, 0x4, 0x1c, 0x4, 0x3c, 0x0,
0x0, 0x0, 0x18, 0x24, 0x1e, 0x2, 0xc, 0x0,
0xc, 0x0, 0xc, 0xe, 0xc, 0x1c, 0xc, 0x0,
0x1a, 0x6, 0x2, 0x2, 0x0, 0x0, 0x0, 0x0,
0x1c, 0x8, 0x8, 0x8, 0x8, 0x0, 0x0, 0x0,
0x3e, 0x0, 0x22, 0x14, 0x8, 0x14, 0x22, 0x0,
0x3e, 0x0, 0x22, 0x22, 0x22, 0x3c, 0x20, 0x1c,
0x20, 0x18, 0x6, 0x18, 0x20, 0x0, 0x3e, 0x0,
0x10, 0x10, 0x3e, 0x8, 0x3e, 0x4, 0x4, 0x0,
0x2, 0xc, 0x30, 0xc, 0x2, 0x0, 0x3e, 0x0,
0x0, 0x0, 0x20, 0x10, 0x8, 0x4, 0x3e, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2a, 0x0,
0x8, 0x8, 0x0, 0x8, 0x8, 0x8, 0x8, 0x0,
0x0, 0x8, 0x1c, 0xa, 0xa, 0x2a, 0x1c, 0x8,
0x18, 0x24, 0x4, 0xe, 0x4, 0x24, 0x1e, 0x0,
0x0, 0x22, 0x1c, 0x14, 0x1c, 0x22, 0x0, 0x0,
0x22, 0x22, 0x14, 0x3e, 0x8, 0x3e, 0x8, 0x0,
0x8, 0x8, 0x8, 0x0, 0x8, 0x8, 0x8, 0x0,
0x1c, 0x2, 0x1c, 0x22, 0x1c, 0x20, 0x1c, 0x0,
0x38, 0x8, 0x8, 0x8, 0xa, 0xc, 0x8, 0x0,
0x1c, 0x22, 0x3a, 0x3a, 0x3a, 0x22, 0x1c, 0x0,
0x3c, 0x22, 0x22, 0x32, 0x2c, 0x0, 0x3e, 0x0,
0x0, 0x28, 0x14, 0xa, 0x5, 0xa, 0x14, 0x28,
0x0, 0x0, 0x3e, 0x20, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0,
0x1e, 0x31, 0x2d, 0x31, 0x35, 0x2d, 0x1e, 0x0,
0x0, 0xe, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xc, 0x12, 0x12, 0xc, 0x0, 0x0, 0x0, 0x0,
0x8, 0x8, 0x3e, 0x8, 0x8, 0x0, 0x3e, 0x0,
0xc, 0x10, 0x8, 0x4, 0x1c, 0x0, 0x0, 0x0,
0xc, 0x10, 0x8, 0x10, 0xc, 0x0, 0x0, 0x0,
0x10, 0x18, 0x16, 0x10, 0x38, 0x0, 0x0, 0x0,
0x0, 0x0, 0x12, 0x12, 0x12, 0x12, 0x2e, 0x2,
0x3c, 0x2a, 0x2a, 0x2a, 0x3c, 0x28, 0x28, 0x0,
0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0,
0x4, 0xe, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0,
0x8, 0xc, 0x8, 0x8, 0x1c, 0x0, 0x0, 0x0,
0x1c, 0x22, 0x22, 0x22, 0x1c, 0x0, 0x3e, 0x0,
0x0, 0x5, 0xa, 0x14, 0x28, 0x14, 0xa, 0x5,
0x30, 0x20, 0x2c, 0x12, 0x12, 0x1a, 0x34, 0x0,
0x10, 0x28, 0x8, 0x8, 0x8, 0xa, 0x4, 0x0,
0x0, 0x14, 0x2a, 0x2a, 0x14, 0x0, 0x0, 0x0,
0x8, 0x0, 0x8, 0x4, 0x2, 0x22, 0x1c, 0x0,
0x4, 0x8, 0x1c, 0x22, 0x3e, 0x22, 0x22, 0x0,
0x10, 0x8, 0x1c, 0x22, 0x3e, 0x22, 0x22, 0x0,
0x8, 0x14, 0x1c, 0x22, 0x3e, 0x22, 0x22, 0x0,
0x28, 0x14, 0x1c, 0x22, 0x3e, 0x22, 0x22, 0x0,
0x14, 0x0, 0x1c, 0x22, 0x3e, 0x22, 0x22, 0x0,
0x8, 0x14, 0x8, 0x1c, 0x22, 0x3e, 0x22, 0x0,
0x38, 0xc, 0xc, 0x3a, 0xe, 0xa, 0x3a, 0x0,
0x1c, 0x22, 0x2, 0x2, 0x22, 0x1c, 0x8, 0xc,
0x4, 0x8, 0x3e, 0x2, 0x1e, 0x2, 0x3e, 0x0,
0x10, 0x8, 0x3e, 0x2, 0x1e, 0x2, 0x3e, 0x0,
0x8, 0x14, 0x3e, 0x2, 0x1e, 0x2, 0x3e, 0x0,
0x14, 0x0, 0x3e, 0x2, 0x1e, 0x2, 0x3e, 0x0,
0x4, 0x8, 0x1c, 0x8, 0x8, 0x8, 0x1c, 0x0,
0x10, 0x8, 0x1c, 0x8, 0x8, 0x8, 0x1c, 0x0,
0x8, 0x14, 0x1c, 0x8, 0x8, 0x8, 0x1c, 0x0,
0x14, 0x0, 0x1c, 0x8, 0x8, 0x8, 0x1c, 0x0,
0x1e, 0x24, 0x24, 0x2e, 0x24, 0x24, 0x1e, 0x0,
0x28, 0x14, 0x22, 0x26, 0x2a, 0x32, 0x22, 0x0,
0x4, 0x8, 0x1c, 0x22, 0x22, 0x22, 0x1c, 0x0,
0x10, 0x8, 0x1c, 0x22, 0x22, 0x22, 0x1c, 0x0,
0x8, 0x14, 0x1c, 0x22, 0x22, 0x22, 0x1c, 0x0,
0x28, 0x14, 0x1c, 0x22, 0x22, 0x22, 0x1c, 0x0,
0x14, 0x0, 0x1c, 0x22, 0x22, 0x22, 0x1c, 0x0,
0x0, 0x0, 0x0, 0x14, 0x8, 0x14, 0x0, 0x0,
0x1c, 0x32, 0x32, 0x2a, 0x26, 0x26, 0x1c, 0x0,
0x4, 0x8, 0x22, 0x22, 0x22, 0x22, 0x1c, 0x0,
0x10, 0x8, 0x22, 0x22, 0x22, 0x22, 0x1c, 0x0,
0x8, 0x14, 0x0, 0x22, 0x22, 0x22, 0x1c, 0x0,
0x14, 0x0, 0x22, 0x22, 0x22, 0x22, 0x1c, 0x0,
0x10, 0x8, 0x22, 0x22, 0x14, 0x8, 0x8, 0x0,
0x2, 0x1e, 0x22, 0x22, 0x22, 0x1e, 0x2, 0x0,
0x18, 0x24, 0x14, 0x24, 0x24, 0x2c, 0x16, 0x0,
0x4, 0x8, 0x3c, 0x22, 0x22, 0x32, 0x2c, 0x0,
0x10, 0x8, 0x3c, 0x22, 0x22, 0x32, 0x2c, 0x0,
0x8, 0x14, 0x3c, 0x22, 0x22, 0x32, 0x2c, 0x0,
0x28, 0x14, 0x3c, 0x22, 0x22, 0x32, 0x2c, 0x0,
0x14, 0x0, 0x3c, 0x22, 0x22, 0x32, 0x2c, 0x0,
0x8, 0x14, 0x8, 0x3c, 0x22, 0x32, 0x2c, 0x0,
0x0, 0x0, 0x16, 0x28, 0x3c, 0xa, 0x34, 0x0,
0x0, 0x0, 0x1c, 0x2, 0x22, 0x1c, 0x8, 0x4,
0x4, 0x8, 0x1c, 0x22, 0x3e, 0x2, 0x1c, 0x0,
0x10, 0x8, 0x1c, 0x22, 0x3e, 0x2, 0x1c, 0x0,
0x8, 0x14, 0x1c, 0x22, 0x3e, 0x2, 0x1c, 0x0,
0x14, 0x0, 0x1c, 0x22, 0x3e, 0x2, 0x1c, 0x0,
0x4, 0x8, 0xc, 0x8, 0x8, 0x8, 0x1c, 0x0,
0x10, 0x8, 0xc, 0x8, 0x8, 0x8, 0x1c, 0x0,
0x8, 0x14, 0xc, 0x8, 0x8, 0x8, 0x1c, 0x0,
0x14, 0x0, 0xc, 0x8, 0x8, 0x8, 0x1c, 0x0,
0x14, 0x8, 0x14, 0x20, 0x3c, 0x22, 0x1c, 0x0,
0x28, 0x14, 0x0, 0x1a, 0x26, 0x22, 0x22, 0x0,
0x4, 0x8, 0x0, 0x1c, 0x22, 0x22, 0x1c, 0x0,
0x10, 0x8, 0x0, 0x1c, 0x22, 0x22, 0x1c, 0x0,
0x8, 0x14, 0x0, 0x1c, 0x22, 0x22, 0x1c, 0x0,
0x28, 0x14, 0x0, 0x1c, 0x22, 0x22, 0x1c, 0x0,
0x14, 0x0, 0x0, 0x1c, 0x22, 0x22, 0x1c, 0x0,
0x0, 0x8, 0x0, 0x3e, 0x0, 0x8, 0x0, 0x0,
0x0, 0x0, 0x1c, 0x32, 0x2a, 0x26, 0x1c, 0x0,
0x4, 0x8, 0x22, 0x22, 0x22, 0x32, 0x2c, 0x0,
0x10, 0x8, 0x22, 0x22, 0x22, 0x32, 0x2c, 0x0,
0x8, 0x14, 0x0, 0x22, 0x22, 0x32, 0x2c, 0x0,
0x14, 0x0, 0x22, 0x22, 0x22, 0x32, 0x2c, 0x0,
0x10, 0x8, 0x22, 0x22, 0x22, 0x3c, 0x20, 0x1c,
0x2, 0x1a, 0x26, 0x22, 0x22, 0x26, 0x1a, 0x2,
0x14, 0x0, 0x22, 0x22, 0x22, 0x3c, 0x20, 0x1c
})
M._defaultFont = font
end
return M
| gpl-3.0 |
RockySeven3161/UB | plugins/gnuplot.lua | 622 | 1813 | --[[
* Gnuplot plugin by psykomantis
* dependencies:
* - gnuplot 5.00
* - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html
*
]]
-- Gnuplot needs absolute path for the plot, so i run some commands to find where we are
local outputFile = io.popen("pwd","r")
io.input(outputFile)
local _pwd = io.read("*line")
io.close(outputFile)
local _absolutePlotPath = _pwd .. "/data/plot.png"
local _scriptPath = "./data/gnuplotScript.gpl"
do
local function gnuplot(msg, fun)
local receiver = get_receiver(msg)
-- We generate the plot commands
local formattedString = [[
set grid
set terminal png
set output "]] .. _absolutePlotPath .. [["
plot ]] .. fun
local file = io.open(_scriptPath,"w");
file:write(formattedString)
file:close()
os.execute("gnuplot " .. _scriptPath)
os.remove (_scriptPath)
return _send_photo(receiver, _absolutePlotPath)
end
-- Check all dependencies before executing
local function checkDependencies()
local status = os.execute("gnuplot -h")
if(status==true) then
status = os.execute("gnuplot -e 'set terminal png'")
if(status == true) then
return 0 -- OK ready to go!
else
return 1 -- missing libgd2-xpm-dev
end
else
return 2 -- missing gnuplot
end
end
local function run(msg, matches)
local status = checkDependencies()
if(status == 0) then
return gnuplot(msg,matches[1])
elseif(status == 1) then
return "It seems that this bot miss a dependency :/"
else
return "It seems that this bot doesn't have gnuplot :/"
end
end
return {
description = "use gnuplot through telegram, only plot single variable function",
usage = "!gnuplot [single variable function]",
patterns = {"^!gnuplot (.+)$"},
run = run
}
end
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.