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 |
|---|---|---|---|---|---|
ahua/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 |
cburlacu/packages | net/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan/ruleconfig.lua | 82 | 4185 | -- ------ extra functions ------ --
function ruleCheck() -- determine if rule needs a protocol specified
local sourcePort = ut.trim(sys.exec("uci -p /var/state get mwan3." .. arg[1] .. ".src_port"))
local destPort = ut.trim(sys.exec("uci -p /var/state get mwan3." .. arg[1] .. ".dest_port"))
if sourcePort ~= "" or destPort ~= "" then -- ports configured
local protocol = ut.trim(sys.exec("uci -p /var/state get mwan3." .. arg[1] .. ".proto"))
if protocol == "" or protocol == "all" then -- no or improper protocol
error_protocol = 1
end
end
end
function ruleWarn() -- display warning message at the top of the page
if error_protocol == 1 then
return "<font color=\"ff0000\"><strong>WARNING: this rule is incorrectly configured with no or improper protocol specified! Please configure a specific protocol!</strong></font>"
else
return ""
end
end
function cbiAddPolicy(field)
uci.cursor():foreach("mwan3", "policy",
function (section)
field:value(section[".name"])
end
)
end
function cbiAddProtocol(field)
local protocols = ut.trim(sys.exec("cat /etc/protocols | grep ' # ' | awk '{print $1}' | grep -vw -e 'ip' -e 'tcp' -e 'udp' -e 'icmp' -e 'esp' | grep -v 'ipv6' | sort | tr '\n' ' '"))
for p in string.gmatch(protocols, "%S+") do
field:value(p)
end
end
-- ------ rule configuration ------ --
dsp = require "luci.dispatcher"
sys = require "luci.sys"
ut = require "luci.util"
arg[1] = arg[1] or ""
error_protocol = 0
ruleCheck()
m5 = Map("mwan3", translate("MWAN Rule Configuration - ") .. arg[1],
translate(ruleWarn()))
m5.redirect = dsp.build_url("admin", "network", "mwan", "configuration", "rule")
mwan_rule = m5:section(NamedSection, arg[1], "rule", "")
mwan_rule.addremove = false
mwan_rule.dynamic = false
src_ip = mwan_rule:option(Value, "src_ip", translate("Source address"),
translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes"))
src_ip.datatype = ipaddr
src_port = mwan_rule:option(Value, "src_port", translate("Source port"),
translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes"))
dest_ip = mwan_rule:option(Value, "dest_ip", translate("Destination address"),
translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes"))
dest_ip.datatype = ipaddr
dest_port = mwan_rule:option(Value, "dest_port", translate("Destination port"),
translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes"))
proto = mwan_rule:option(Value, "proto", translate("Protocol"),
translate("View the contents of /etc/protocols for protocol descriptions"))
proto.default = "all"
proto.rmempty = false
proto:value("all")
proto:value("ip")
proto:value("tcp")
proto:value("udp")
proto:value("icmp")
proto:value("esp")
cbiAddProtocol(proto)
sticky = mwan_rule:option(ListValue, "sticky", translate("Sticky"),
translate("Traffic from the same source IP address that previously matched this rule within the sticky timeout period will use the same WAN interface"))
sticky.default = "0"
sticky:value("1", translate("Yes"))
sticky:value("0", translate("No"))
timeout = mwan_rule:option(Value, "timeout", translate("Sticky timeout"),
translate("Seconds. Acceptable values: 1-1000000. Defaults to 600 if not set"))
timeout.datatype = "range(1, 1000000)"
ipset = mwan_rule:option(Value, "ipset", translate("IPset"),
translate("Name of IPset rule. Requires IPset rule in /etc/dnsmasq.conf (eg \"ipset=/youtube.com/youtube\")"))
use_policy = mwan_rule:option(Value, "use_policy", translate("Policy assigned"))
cbiAddPolicy(use_policy)
use_policy:value("unreachable", translate("unreachable (reject)"))
use_policy:value("blackhole", translate("blackhole (drop)"))
use_policy:value("default", translate("default (use main routing table)"))
-- ------ currently configured policies ------ --
mwan_policy = m5:section(TypedSection, "policy", translate("Currently Configured Policies"))
mwan_policy.addremove = false
mwan_policy.dynamic = false
mwan_policy.sortable = false
mwan_policy.template = "cbi/tblsection"
return m5
| gpl-2.0 |
Bew78LesellB/awesome | lib/awful/button.lua | 7 | 2130 | ---------------------------------------------------------------------------
--- Create easily new buttons objects ignoring certain modifiers.
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2009 Julien Danjou
-- @classmod awful.button
---------------------------------------------------------------------------
-- Grab environment we need
local setmetatable = setmetatable
local ipairs = ipairs
local capi = { button = button }
local gmath = require("gears.math")
local gtable = require("gears.table")
local button = { mt = {} }
--- Modifiers to ignore.
--
-- By default this is initialized as `{ "Lock", "Mod2" }`
-- so the `Caps Lock` or `Num Lock` modifier are not taking into account by awesome
-- when pressing keys.
--
-- @table ignore_modifiers
local ignore_modifiers = { "Lock", "Mod2" }
--- Create a new button to use as binding.
--
-- This function is useful to create several buttons from one, because it will use
-- the ignore_modifier variable to create more button with or without the ignored
-- modifiers activated.
--
-- For example if you want to ignore CapsLock in your buttonbinding (which is
-- ignored by default by this function), creating button binding with this function
-- will return 2 button objects: one with CapsLock on, and the other one with
-- CapsLock off.
--
-- @see button
-- @treturn table A table with one or several button objects.
function button.new(mod, _button, press, release)
local ret = {}
local subsets = gmath.subsets(ignore_modifiers)
for _, set in ipairs(subsets) do
ret[#ret + 1] = capi.button({ modifiers = gtable.join(mod, set),
button = _button })
if press then
ret[#ret]:connect_signal("press", function(_, ...) press(...) end)
end
if release then
ret[#ret]:connect_signal("release", function (_, ...) release(...) end)
end
end
return ret
end
function button.mt:__call(...)
return button.new(...)
end
return setmetatable(button, button.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
ToFran/ComputercraftPrograms | RainbowTreeChopper.lua | 1 | 6075 | --Rainbow Tree Farm [RTC] - Computer Craft Mining Turtles Program
--Post (info & stuff): http://www.computercraft.info/forums2/index.php?/topic/20411-rainbow-tree-farm-program-rtc/
--by ToFran
local function DigAndForward(times)
times = times or 1
for i = 1,times do
turtle.dig()
turtle.forward()
end
end
local function DigDownAndForward(times)
times = times or 1
for i = 1,times do
turtle.digDown()
turtle.dig()
turtle.forward()
end
end
local function DigUpDownAndForward(times)
times = times or 1
for i = 1,times do
turtle.digUp()
turtle.digDown()
turtle.dig()
turtle.forward()
end
end
local function Leftarino()
turtle.turnLeft()
DigAndForward()
turtle.turnLeft()
end
local function Rightarino()
turtle.turnRight()
DigAndForward()
turtle.turnRight()
end
local function SpecialRightarino()
turtle.digUp()
turtle.digDown()
turtle.turnRight()
DigUpDownAndForward()
turtle.turnRight()
DigUpDownAndForward()
end
local function clearConsole()
term.clear()
term.setCursorPos(1,1)
end
local function MineBase()
DigAndForward(2)
turtle.forward()
Rightarino()
DigDownAndForward(1)
DigUpDownAndForward(2)
DigDownAndForward(1)
Leftarino()
DigAndForward(1)
DigUpDownAndForward(4)
Rightarino()
DigAndForward(1)
DigUpDownAndForward(4)
Leftarino()
DigAndForward(1)
DigUpDownAndForward(4)
Rightarino()
DigAndForward(3)
-- 2 layer
turtle.up()
turtle.up()
turtle.turnRight()
DigAndForward(2)
turtle.turnLeft()
DigAndForward(1)
Rightarino()
DigAndForward(1)
turtle.turnLeft()
DigAndForward(1)
Rightarino()
DigAndForward(1)
turtle.turnLeft()
DigAndForward(1)
Rightarino()
DigAndForward(1)
turtle.turnLeft()
turtle.dig()
turtle.turnRight()
end
local function UpLoop(times)
times = times or 1
for i = 1,times do
turtle.digUp()
turtle.up()
turtle.dig()
end
end
local function DownLoop(times)
times = times or 1
for i = 1,times do
turtle.digDown()
turtle.down()
turtle.dig()
end
end
local function LoopDerivation()
turtle.turnLeft()
DigAndForward(3)
Rightarino()
DigAndForward(3)
end
local function MineDerivation()
turtle.digUp()
turtle.up()
LoopDerivation()
LoopDerivation()
LoopDerivation()
LoopDerivation()
end
local function GoToTheOtherSideOfTheLogOnTop()
turtle.turnRight()
DigAndForward()
turtle.turnLeft()
turtle.dig()
end
local function GoToTheOtherSideOfTheLogOnBottom()
turtle.turnLeft()
DigAndForward()
turtle.turnRight()
turtle.dig()
end
local function RemoveRootAndCreateItemCavity()
turtle.digDown()
turtle.down()
turtle.digDown()
turtle.down()
DigDownAndForward(2)
SpecialRightarino()
DigDownAndForward(2)
turtle.turnRight()
DigDownAndForward(3)
turtle.turnRight()
DigDownAndForward(3)
SpecialRightarino()
DigDownAndForward(2)
end
local function PlaceAndforward(times)
times = times or 1
for i = 1,times do
turtle.placeDown()
turtle.forward()
end
end
local function Replant()
turtle.up()
turtle.up()
turtle.turnLeft()
turtle.select(16) -- Select the dirt
PlaceAndforward(2)
turtle.turnLeft()
PlaceAndforward(3)
turtle.turnLeft()
PlaceAndforward(1)
turtle.turnLeft()
PlaceAndforward(2)
turtle.turnRight()
PlaceAndforward(1)
turtle.turnRight()
PlaceAndforward(2)
turtle.turnLeft()
PlaceAndforward(1)
turtle.turnLeft()
PlaceAndforward(3)
turtle.placeDown()
-- End of Placing Dirt, lets plant!
turtle.up()
turtle.turnLeft()
turtle.forward()
turtle.turnLeft()
turtle.forward()
turtle.select(15) -- Select The Saplings
PlaceAndforward(1)
turtle.turnRight()
PlaceAndforward(1)
turtle.turnRight()
PlaceAndforward(1)
turtle.placeDown()
end
local function GoToChest()
turtle.turnLeft()
DigAndForward(2)
turtle.turnLeft()
DigAndForward(8)
-- Drop The Wood
turtle.select(1)
turtle.drop()
turtle.select(2)
turtle.drop()
turtle.select(3)
turtle.drop()
turtle.select(4)
turtle.drop()
turtle.select(5)
turtle.drop() -- Drop remaining dirt
turtle.select(1)
-- Go to the chopping spot
turtle.turnRight()
turtle.turnRight()
DigAndForward(6)
turtle.down()
end
local function TreeCheck()
notreeWarning = 0
turtle.select(1)
while turtle.compare() do
sleep(1)
if notreeWarning==0 then
print("No tree detected, waiting...")
notreeWarning = 1
end
end
if notreeWarning==1 then
print("Detected! Chopping started.")
end
end
-- UI Stuff
clearConsole()
print("Rainbow Tree Chopper by ToFran\nChoose one of the following options:\n [1] Chop down the tree.\n [2] Start the tree farm.")
local input = read()
clearConsole()
if input=="1" then -- Chop down the tree.
if turtle.getFuelLevel() > 155 then
write("Fuel level is ")
write(turtle.getFuelLevel())
write("\n")
MineBase()
UpLoop(6)
MineDerivation()
UpLoop(4)
MineDerivation()
UpLoop(10)
GoToTheOtherSideOfTheLogOnTop()
DownLoop(27)
GoToTheOtherSideOfTheLogOnBottom()
UpLoop(2)
turtle.back()
else
print("Not enough fuel :(")
end
elseif input=="2" then
if turtle.getFuelLevel() > 200 then
print("Please place dirt on slot 16 and rainbow saplings on slot 15. \nPress enter to continue...")
local input = read()
while true do -- Its an farm, so its infinite :P
if turtle.getItemCount(15) < 4 or turtle.getItemCount(16) < 1 then
print("Unable to continue, lack of resources\nTerminating!")
print(turtle.getItemCount(15))
print(turtle.getItemCount(16))
return
end
clearConsole()
write("Fuel level is ")
write(turtle.getFuelLevel())
write("\n")
TreeCheck() -- Sleeps the program until a tree is detected
MineBase()
UpLoop(6)
MineDerivation()
UpLoop(4)
MineDerivation()
UpLoop(10)
GoToTheOtherSideOfTheLogOnTop()
DownLoop(24)
RemoveRootAndCreateItemCavity()
Replant()
GoToChest()
end
else
print("Not enough fuel :(")
end
end
write("Remaining fuel: ")
write(turtle.getFuelLevel())
write("\n")
--by ToFran | mit |
seem-sky/FrameworkBenchmarks | lapis/web.lua | 2 | 5594 | local lapis = require("lapis")
local db = require("lapis.db")
local Model
do
local _obj_0 = require("lapis.db.model")
Model = _obj_0.Model
end
local config
do
local _obj_0 = require("lapis.config")
config = _obj_0.config
end
local insert
do
local _obj_0 = table
insert = _obj_0.insert
end
local sort
do
local _obj_0 = table
sort = _obj_0.sort
end
local random
do
local _obj_0 = math
random = _obj_0.random
end
local Fortune
do
local _parent_0 = Model
local _base_0 = { }
_base_0.__index = _base_0
setmetatable(_base_0, _parent_0.__base)
local _class_0 = setmetatable({
__init = function(self, ...)
return _parent_0.__init(self, ...)
end,
__base = _base_0,
__name = "Fortune",
__parent = _parent_0
}, {
__index = function(cls, name)
local val = rawget(_base_0, name)
if val == nil then
return _parent_0[name]
else
return val
end
end,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
if _parent_0.__inherited then
_parent_0.__inherited(_parent_0, _class_0)
end
Fortune = _class_0
end
local World
do
local _parent_0 = Model
local _base_0 = { }
_base_0.__index = _base_0
setmetatable(_base_0, _parent_0.__base)
local _class_0 = setmetatable({
__init = function(self, ...)
return _parent_0.__init(self, ...)
end,
__base = _base_0,
__name = "World",
__parent = _parent_0
}, {
__index = function(cls, name)
local val = rawget(_base_0, name)
if val == nil then
return _parent_0[name]
else
return val
end
end,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
if _parent_0.__inherited then
_parent_0.__inherited(_parent_0, _class_0)
end
World = _class_0
end
local Benchmark
do
local _parent_0 = lapis.Application
local _base_0 = {
["/"] = function(self)
return {
json = {
message = "Hello, World!"
}
}
end,
["/db"] = function(self)
local num_queries = tonumber(self.params.queries) or 1
if num_queries < 2 then
local w = World:find(random(1, 10000))
return {
json = {
id = w.id,
randomNumber = w.randomnumber
}
}
end
local worlds = { }
for i = 1, num_queries do
local w = World:find(random(1, 10000))
insert(worlds, {
id = w.id,
randomNumber = w.randomnumber
})
end
return {
json = worlds
}
end,
["/fortunes"] = function(self)
self.fortunes = Fortune:select("")
insert(self.fortunes, {
id = 0,
message = "Additional fortune added at request time."
})
sort(self.fortunes, function(a, b)
return a.message < b.message
end)
return {
layout = false
}, self:html(function()
raw('<!DOCTYPE HTML>')
return html(function()
head(function()
return title("Fortunes")
end)
return body(function()
return element("table", function()
tr(function()
th(function()
return text("id")
end)
return th(function()
return text("message")
end)
end)
local _list_0 = self.fortunes
for _index_0 = 1, #_list_0 do
local fortune = _list_0[_index_0]
tr(function()
td(function()
return text(fortune.id)
end)
return td(function()
return text(fortune.message)
end)
end)
end
end)
end)
end)
end)
end,
["/update"] = function(self)
local num_queries = tonumber(self.params.queries) or 1
if num_queries == 0 then
num_queries = 1
end
local worlds = { }
for i = 1, num_queries do
local wid = random(1, 10000)
local world = World:find(wid)
world.randomnumber = random(1, 10000)
world:update("randomnumber")
insert(worlds, {
id = world.id,
randomNumber = world.randomnumber
})
end
if num_queries < 2 then
return {
json = worlds[1]
}
end
return {
json = worlds
}
end,
["/plaintext"] = function(self)
return {
content_type = "text/plain",
layout = false
}, "Hello, World!"
end
}
_base_0.__index = _base_0
setmetatable(_base_0, _parent_0.__base)
local _class_0 = setmetatable({
__init = function(self, ...)
return _parent_0.__init(self, ...)
end,
__base = _base_0,
__name = "Benchmark",
__parent = _parent_0
}, {
__index = function(cls, name)
local val = rawget(_base_0, name)
if val == nil then
return _parent_0[name]
else
return val
end
end,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
if _parent_0.__inherited then
_parent_0.__inherited(_parent_0, _class_0)
end
Benchmark = _class_0
return _class_0
end
| bsd-3-clause |
avr-aics-riken/hpcpfGUI | lib/excase.lua | 1 | 3790 |
local excase = {}
function generateTargetConf(args_table)
for i, k in pairs(args_table) do
--print(i, k);
if (i == 1) and next(k) then
for n, m in pairs(k) do
--print(n, m);
if n == "machine" then
return m;
end
end
end
end
end
function getProcs(args_table)
for i, k in pairs(args_table) do
if (i == 1) and next(k) then
for n, m in pairs(k) do
if n == "procs" then
return m;
end
end
end
end
return 1;
end
function getThreads(args_table)
for i, k in pairs(args_table) do
if (i == 1) and next(k) then
for n, m in pairs(k) do
if n == "threads" then
return m;
end
end
end
end
return 1;
end
function getCleanUp(args_table)
for i, k in pairs(args_table) do
if (i == 1) and next(k) then
for n, m in pairs(k) do
if n == "cleanup" then
return m == "true";
end
end
end
end
return false;
end
function getInputNodes(args_table)
local list = {}
for i, k in pairs(args_table) do
if (i == 3) then
for n, m in pairs(k) do
table.insert(list, m);
end
end
end
return list;
end
function getAuthKey(args_table)
for i, k in pairs(args_table) do
if (i == 4) then
return k;
end
end
return false;
end
function getOutputFiles(casename,cmd)
local result = nil;
if (cmd ~= nil) then
if (cmd.hpcpf.case_meta_data.outputs ~= nil) then
for i, v in pairs(cmd.hpcpf.case_meta_data.outputs) do
if v.file ~= nil then
v.file = '../' .. casename .. '/' .. v.file;
end
end
result = cmd.hpcpf.case_meta_data.outputs;
end
end
return result;
end
function getPollingFiles(cmd)
local result = nil;
if (cmd ~= nil) then
if (cmd.hpcpf.case_meta_data.polling_files ~= nil) then
result = cmd.hpcpf.case_meta_data.polling_files;
end
end
return result;
end
function getCollectionFiles(cmd)
local result = nil;
if (cmd ~= nil) then
if (cmd.hpcpf.case_meta_data.collection_files ~= nil) then
result = cmd.hpcpf.case_meta_data.collection_files;
end
end
return result;
end
function getCollectionJobFiles(cmd)
local result = nil;
if (cmd ~= nil) then
if (cmd.hpcpf.case_meta_data.collection_job_files ~= nil) then
result = cmd.hpcpf.case_meta_data.collection_job_files;
end
end
return result;
end
function getNodes(args_table)
for i, k in pairs(args_table) do
if (i == 1) and next(k) then
for n, m in pairs(k) do
if n == "nodes" then
return m;
end
end
end
end
return 1;
end
function isDryRun(args_table)
for i, k in pairs(args_table) do
if (i == 2) then
return k;
end
end
return false;
end
function excase(args_table)
local caseDir = getCurrentDir() .. getBasePath()
local projectDir
local upPath
local caseName
local projectName
projectDir, caseName = getDirAndName(caseDir)
projectDir = projectDir:sub(1, projectDir:len()-1) -- remove sparator
upPath, projectName = getDirAndName(projectDir)
--[[
print('-------------')
print('Case:', caseDir, '/', caseName)
print('Project:', projectDir, '/', projectName)
print('UpPath:', upPath)
print('-------------')
--]]
local cmdFile = 'cmd.json';
local cmd = readJSON(cmdFile);
local inst = {
targetConf = generateTargetConf(args_table),
procs = getProcs(args_table),
threads = getThreads(args_table),
nodes = getNodes(args_table),
cleanup = getCleanUp(args_table),
inputNodes = getInputNodes(args_table),
outputFiles = getOutputFiles(caseName, cmd),
pollingFiles = getPollingFiles(cmd),
collectionFiles = getCollectionFiles(cmd),
collectionJobFiles = getCollectionJobFiles(cmd),
authKey = getAuthKey(args_table),
isDryRun = isDryRun(args_table),
caseName = caseName,
caseDir = caseDir,
projectDir = projectDir,
projectName = projectName,
projectUpDir = upPath
}
return inst;
end
return excase;
| bsd-2-clause |
Anarchid/Zero-K | LuaUI/Widgets/chili/Skins/Robocracy/skin.lua | 8 | 6393 | --// =============================================================================
--// Skin
local skin = {
info = {
name = "Robocracy",
version = "0.3",
author = "jK",
}
}
--// =============================================================================
--//
skin.general = {
focusColor = {1.0, 0.7, 0.1, 0.8},
borderColor = {1.0, 1.0, 1.0, 1.0},
font = {
font = SKINDIR .. "fonts/n019003l.pfb",
color = {1, 1, 1, 1},
outlineColor = {0.05, 0.05, 0.05, 0.9},
outline = false,
shadow = true,
size = 14,
},
--padding = {5, 5, 5, 5}, --// padding: left, top, right, bottom
}
skin.icons = {
imageplaceholder = ":cl:placeholder.png",
}
skin.button = {
TileImageBK = ":cl:tech_button_bk.png",
TileImageFG = ":cl:tech_button_fg.png",
tiles = {22, 22, 22, 22}, --// tile widths: left, top, right, bottom
padding = {10, 10, 10, 10},
backgroundColor = {1, 1, 1, 0.7},
borderColor = {1, 1, 1, 0},
DrawControl = DrawButton,
}
skin.button_disabled = {
TileImageBK = ":cl:tech_button_bk.png",
TileImageFG = ":cl:tech_button_fg.png",
tiles = {22, 22, 22, 22}, --// tile widths: left, top, right, bottom
padding = {10, 10, 10, 10},
color = {0.3, .3, .3, 1},
backgroundColor = {0.1, 0.1, 0.1, 0.8},
borderColor = {1, 1, 1, 0},
DrawControl = DrawButton,
}
skin.combobox = {
TileImageBK = ":cl:combobox_ctrl.png",
TileImageFG = ":cl:combobox_ctrl_fg.png",
TileImageArrow = ":cl:combobox_ctrl_arrow.png",
tiles = {22, 22, 48, 22},
padding = {10, 10, 24, 10},
backgroundColor = {1, 1, 1, 0.7},
borderColor = {1, 1, 1, 0},
DrawControl = DrawComboBox,
}
skin.combobox_window = {
clone = "window";
TileImage = ":cl:combobox_wnd.png";
tiles = {10, 10, 10, 10};
padding = {4, 3, 3, 4};
}
skin.combobox_scrollpanel = {
clone = "scrollpanel";
borderColor = {1, 1, 1, 0};
padding = {0, 0, 0, 0};
}
skin.combobox_item = {
clone = "button";
borderColor = {1, 1, 1, 0};
}
skin.checkbox = {
TileImageFG = ":cl:tech_checkbox_checked.png",
TileImageBK = ":cl:tech_checkbox_unchecked.png",
tiles = {3, 3, 3, 3},
boxsize = 13,
DrawControl = DrawCheckbox,
}
skin.editbox = {
hintFont = table.merge({color = {1, 1, 1, 0.7}}, skin.general.font),
backgroundColor = {0.1, 0.1, 0.1, 0.7},
cursorColor = {1.0, 0.7, 0.1, 0.8},
TileImageBK = ":cl:panel2_bg.png",
TileImageFG = ":cl:panel2_border.png",
tiles = {14, 14, 14, 14},
DrawControl = DrawEditBox,
}
skin.textbox = {
hintFont = table.merge({color = {1, 1, 1, 0.7}}, skin.general.font),
TileImageBK = ":cl:panel2_bg.png",
TileImageFG = ":cl:panel2_border.png",
tiles = {14, 14, 14, 14},
borderColor = {0.0, 0.0, 0.0, 0.0},
focusColor = {0.0, 0.0, 0.0, 0.0},
DrawControl = DrawEditBox,
}
skin.imagelistview = {
imageFolder = "folder.png",
imageFolderUp = "folder_up.png",
--DrawControl = DrawBackground,
colorBK = {1, 1, 1, 0.3},
colorBK_selected = {1, 0.7, 0.1, 0.8},
colorFG = {0, 0, 0, 0},
colorFG_selected = {1, 1, 1, 1},
imageBK = ":cl:node_selected_bw.png",
imageFG = ":cl:node_selected.png",
tiles = {9, 9, 9, 9},
DrawItemBackground = DrawItemBkGnd,
}
--[[
skin.imagelistviewitem = {
imageFG = ":cl:glassFG.png",
imageBK = ":cl:glassBK.png",
tiles = {17, 15, 17, 20},
padding = {12, 12, 12, 12},
DrawSelectionItemBkGnd = DrawSelectionItemBkGnd,
}
--]]
skin.panel = {
TileImageBK = ":cl:tech_button.png",
TileImageFG = ":cl:empty.png",
tiles = {22, 22, 22, 22},
DrawControl = DrawPanel,
}
skin.progressbar = {
TileImageFG = ":cl:tech_progressbar_full.png",
TileImageBK = ":cl:tech_progressbar_empty.png",
tiles = {10, 10, 10, 10},
font = {
shadow = true,
},
backgroundColor = {1, 1, 1, 1},
DrawControl = DrawProgressbar,
}
skin.scrollpanel = {
BorderTileImage = ":cl:panel2_border.png",
bordertiles = {14, 14, 14, 14},
BackgroundTileImage = ":cl:panel2_bg.png",
bkgndtiles = {14, 14, 14, 14},
TileImage = ":cl:tech_scrollbar.png",
tiles = {7, 7, 7, 7},
KnobTileImage = ":cl:tech_scrollbar_knob.png",
KnobTiles = {6, 8, 6, 8},
HTileImage = ":cl:tech_scrollbar.png",
htiles = {7, 7, 7, 7},
HKnobTileImage = ":cl:tech_scrollbar_knob.png",
HKnobTiles = {6, 8, 6, 8},
KnobColorSelected = {1, 0.7, 0.1, 0.8},
padding = {5, 5, 5, 0},
scrollbarSize = 11,
DrawControl = DrawScrollPanel,
DrawControlPostChildren = DrawScrollPanelBorder,
}
skin.trackbar = {
TileImage = ":cn:trackbar.png",
tiles = {10, 14, 10, 14}, --// tile widths: left, top, right, bottom
ThumbImage = ":cl:trackbar_thumb.png",
StepImage = ":cl:trackbar_step.png",
hitpadding = {4, 4, 5, 4},
DrawControl = DrawTrackbar,
}
skin.treeview = {
--ImageNode = ":cl:node.png",
ImageNodeSelected = ":cl:node_selected.png",
tiles = {9, 9, 9, 9},
ImageExpanded = ":cl:treeview_node_expanded.png",
ImageCollapsed = ":cl:treeview_node_collapsed.png",
treeColor = {1, 1, 1, 0.1},
DrawNode = DrawTreeviewNode,
DrawNodeTree = DrawTreeviewNodeTree,
}
skin.window = {
TileImage = ":c:tech_dragwindow.png",
--TileImage = ":cl:tech_window.png",
--TileImage = ":cl:window_tooltip.png",
--tiles = {25, 25, 25, 25}, --// tile widths: left, top, right, bottom
tiles = {62, 62, 62, 62}, --// tile widths: left, top, right, bottom
padding = {13, 13, 13, 13},
hitpadding = {4, 4, 4, 4},
captionColor = {1, 1, 1, 0.45},
backgroundColor = {0.1, 0.1, 0.1, 0.7},
boxes = {
resize = {-21, -21, -10, -10},
drag = {0, 0, "100%", 10},
},
NCHitTest = NCHitTestWithPadding,
NCMouseDown = WindowNCMouseDown,
NCMouseDownPostChildren = WindowNCMouseDownPostChildren,
DrawControl = DrawWindow,
DrawDragGrip = function() end,
DrawResizeGrip = DrawResizeGrip,
}
skin.line = {
TileImage = ":cl:tech_line.png",
tiles = {0, 0, 0, 0},
TileImageV = ":cl:tech_line_vert.png",
tilesV = {0, 0, 0, 0},
DrawControl = DrawLine,
}
skin.tabbar = {
padding = {3, 1, 1, 0},
}
skin.tabbaritem = {
TileImageBK = ":cl:tech_tabbaritem_bk.png",
TileImageFG = ":cl:tech_tabbaritem_fg.png",
tiles = {10, 10, 10, 0}, --// tile widths: left, top, right, bottom
padding = {5, 3, 3, 2},
backgroundColor = {1, 1, 1, 1.0},
DrawControl = DrawTabBarItem,
}
skin.control = skin.general
--// =============================================================================
--//
return skin
| gpl-2.0 |
nnesse/b2l-tools | lgi/samples/gtk-demo/demo-dialogs.lua | 6 | 3451 | return function(parent, dir)
local lgi = require 'lgi'
local GObject = lgi.GObject
local Gtk = lgi.Gtk
local Gdk = lgi.Gdk
local GdkPixbuf = lgi.GdkPixbuf
local window = Gtk.Window {
title = "Dialogs",
border_width = 8,
Gtk.Frame {
label = "Dialogs",
Gtk.Box {
orientation = 'VERTICAL',
border_width = 8,
spacing = 8,
Gtk.Box {
orientation = 'HORIZONTAL',
spacing = 8,
Gtk.Button {
id = 'message_button',
label = "_Message Dialog",
use_underline = true,
},
},
Gtk.Separator { orientation = 'HORIZONTAL' },
Gtk.Box {
orientation = 'HORIZONTAL',
spacing = 8,
Gtk.Box {
orientation = 'VERTICAL',
Gtk.Button {
id = 'interactive_button',
label = "_Interactive Dialog",
use_underline = true,
},
},
Gtk.Grid {
row_spacing = 4,
column_spacing = 4,
{
left_attach = 0, top_attach = 0,
Gtk.Label {
label = "_Entry 1",
use_underline = true,
},
},
{
left_attach = 1, top_attach = 0,
Gtk.Entry {
id = 'entry1',
},
},
{
left_attach = 0, top_attach = 1,
Gtk.Label {
label = "E_ntry 2",
use_underline = true,
},
},
{
left_attach = 1, top_attach = 1,
Gtk.Entry {
id = 'entry2',
},
},
},
},
},
},
}
local popup_count = 1
function window.child.message_button:on_clicked()
local dialog = Gtk.MessageDialog {
transient_for = window,
modal = true,
destroy_with_parent = true,
message_type = 'INFO',
buttons = 'OK',
text = "This message box has been popped up the following\n"
.. "number of times:",
secondary_text = ('%d'):format(popup_count),
}
dialog:run()
dialog:destroy()
popup_count = popup_count + 1
end
function window.child.interactive_button:on_clicked()
local dialog = Gtk.Dialog {
title = "Interactive Dialog",
transient_for = window,
modal = true,
destroy_with_parent = true,
buttons = {
{ Gtk.STOCK_OK, Gtk.ResponseType.OK },
{ "_Non-stock Button", Gtk.ResponseType.CANCEL },
},
}
local hbox = Gtk.Box {
orientation = 'HORIZONTAL',
spacing = 8,
border_width = 8,
Gtk.Image {
stock = Gtk.STOCK_DIALOG_QUESTION,
icon_size = Gtk.IconSize.DIALOG,
},
Gtk.Grid {
row_spacing = 4,
column_spacing = 4,
{
left_attach = 0, top_attach = 0,
Gtk.Label {
label = "_Entry 1",
use_underline = true,
},
},
{
left_attach = 1, top_attach = 0,
Gtk.Entry {
id = 'entry1',
text = window.child.entry1.text,
},
},
{
left_attach = 0, top_attach = 1,
Gtk.Label {
label = "E_ntry 2",
use_underline = true,
},
},
{
left_attach = 1, top_attach = 1,
Gtk.Entry {
id = 'entry2',
text = window.child.entry2.text,
},
},
}
}
dialog:get_content_area():add(hbox)
hbox:show_all()
if dialog:run() == Gtk.ResponseType.OK then
window.child.entry1.text = hbox.child.entry1.text
window.child.entry2.text = hbox.child.entry2.text
end
dialog:destroy()
end
window:show_all()
return window
end,
"Dialog and Message Boxes",
table.concat {
"Dialog widgets are used to pop up a transient window for user feedback.",
}
| gpl-2.0 |
Anarchid/Zero-K | LuaRules/Gadgets/unit_mex_overdrive.lua | 4 | 65272 | -- $Id: unit_mex_overdrive.lua 4550 2009-05-05 18:07:29Z licho $
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
if not (gadgetHandler:IsSyncedCode()) then
return
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Mex Control with energy link",
desc = "Controls mex overload and energy link grid",
author = "Licho, Google Frog (pylon conversion), ashdnazg (quadField)",
date = "16.5.2008 (OD date)",
license = "GNU GPL, v2 or later",
layer = -4, -- OD grid circles must be drawn before lava drawing gadget some maps have (which has layer = -3)
enabled = true -- loaded by default?
}
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local sqrt = math.sqrt
local min = math.min
local max = math.max
local spValidUnitID = Spring.ValidUnitID
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitAllyTeam = Spring.GetUnitAllyTeam
local spGetUnitTeam = Spring.GetUnitTeam
local spGetUnitPosition = Spring.GetUnitPosition
local spGetUnitIsStunned = Spring.GetUnitIsStunned
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local spSetUnitRulesParam = Spring.SetUnitRulesParam
local spSetTeamRulesParam = Spring.SetTeamRulesParam
local spGetTeamResources = Spring.GetTeamResources
local spAddTeamResource = Spring.AddTeamResource
local spUseTeamResource = Spring.UseTeamResource
local spSetTeamResource = Spring.SetTeamResource
local spGetTeamInfo = Spring.GetTeamInfo
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local mexDefs = {}
--local energyDefs = {}
local pylonDefs = {}
local generatorDefs = {}
local isReturnOfInvestment = (Spring.GetModOptions().overdrivesharingscheme ~= "0")
local enableEnergyPayback = isReturnOfInvestment
local enableMexPayback = isReturnOfInvestment
include("LuaRules/Configs/constants.lua")
--[[ Set to be twice the largest link range except Pylon, so a regular linking building can be in 4 quads at most.
Pylons can belong to more quads but they are comparatively rare and would inflate this value too much.
A potential optimisation here would be to measure if limiting this value to Solar radius would help even further
since Solar/Wind/Mex make up the majority of linkables. ]]
local QUADFIELD_SQUARE_SIZE = 300
for i = 1, #UnitDefs do
local udef = UnitDefs[i]
if (udef.customParams.ismex) then
mexDefs[i] = true
end
local pylonRange = tonumber(udef.customParams.pylonrange) or 0
if pylonRange > 0 then
pylonDefs[i] = {
range = pylonRange,
neededLink = tonumber(udef.customParams.neededlink) or false,
keeptooltip = udef.customParams.keeptooltip or false,
}
end
local metalIncome = tonumber(udef.customParams.income_metal) or 0
local energyIncome = tonumber(udef.customParams.income_energy) or 0
local isWind = (udef.customParams.windgen and true) or false
if metalIncome > 0 or energyIncome > 0 or isWind then
generatorDefs[i] = {
metalIncome = metalIncome,
energyIncome = energyIncome,
sharedEnergyGenerator = udef.customParams.shared_energy_gen and true
}
end
end
local alliedTrueTable = {allied = true}
local inlosTrueTable = {inlos = true}
local sentErrorWarning = false
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local function paybackFactorFunction(repayRatio)
-- Must map [0,1) to (0,1]
-- Must not have any sequences on the domain that converge to 0 in the codomain.
local repay = 0.35 - repayRatio*0.25
if repay > 0.33 then
return 0.33
else
return repay
end
end
local FREE_STORAGE_LIMIT = 300
local MIN_STORAGE = 0.5
local PAYBACK_FACTOR = 0.5
local MEX_REFUND_SHARE = 0.5 -- refund starts at 50% of base income and linearly goes to 0% over time
local MEX_REFUND_VALUE = PAYBACK_FACTOR * UnitDefNames.staticmex.metalCost
local paybackDefs = { -- cost is how much to pay back
[UnitDefNames["energywind"].id] = {cost = UnitDefNames["energywind"].metalCost*PAYBACK_FACTOR},
[UnitDefNames["energysolar"].id] = {cost = UnitDefNames["energysolar"].metalCost*PAYBACK_FACTOR},
[UnitDefNames["energyfusion"].id] = {cost = UnitDefNames["energyfusion"].metalCost*PAYBACK_FACTOR},
[UnitDefNames["energysingu"].id] = {cost = UnitDefNames["energysingu"].metalCost*PAYBACK_FACTOR},
[UnitDefNames["energygeo"].id] = {cost = UnitDefNames["energygeo"].metalCost*PAYBACK_FACTOR},
[UnitDefNames["energyheavygeo"].id] = {cost = UnitDefNames["energyheavygeo"].metalCost*PAYBACK_FACTOR},
}
local spammedError = false
local debugGridMode = false
local debugAllyTeam = false
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local mexes = {} -- mexes[teamID][gridID][unitID] == mexMetal
local mexByID = {} -- mexByID[unitID] = {gridID, allyTeamID, refundTeamID, refundTime, refundTotal, refundSoFar}
local pylon = {} -- pylon[allyTeamID][unitID] = {gridID,mexes,mex[unitID],x,z,overdrive, attachedPylons = {[1] = size, [2] = unitID, ...}}
local pylonList = {} -- pylon[allyTeamID] = {data = {[1] = unitID, [2] = unitID, ...}, count = number}
local generator = {} -- generator[allyTeamID][teamID][unitID] = {generatorListID, metalIncome, energyIncome}
local generatorList = {} -- generator[allyTeamID][teamID] = {data = {[1] = unitID, [2] = unitID, ...}, count = number}
local resourceGenoratingUnit = {}
local pylonGridQueue = false -- pylonGridQueue[unitID] = true
local unitPaybackTeamID = {} -- indexed by unitID, tells unit which team gets it's payback.
local teamPayback = {} -- teamPayback[teamID] = {count = 0, toRemove = {}, data = {[1] = {unitID = unitID, cost = costOfUnit, repaid = howMuchHasBeenRepaid}}}
local allyTeamInfo = {}
local quadFields = {} -- quadFields[allyTeamID] = quadField object (see Utilities/quadField.lua)
do
local allyTeamList = Spring.GetAllyTeamList()
for i = 1, #allyTeamList do
local allyTeamID = allyTeamList[i]
pylon[allyTeamID] = {}
pylonList[allyTeamID] = {data = {}, count = 0}
generator[allyTeamID] = {}
generatorList[allyTeamID] = {}
mexes[allyTeamID] = {}
mexes[allyTeamID][0] = {}
quadFields[allyTeamID] = Spring.Utilities.QuadField(QUADFIELD_SQUARE_SIZE)
allyTeamInfo[allyTeamID] = {
grids = 0,
grid = {}, -- pylon[unitID]
nilGrid = {},
team = {},
teams = 0,
innateMetal = Spring.GetGameRulesParam("OD_allyteam_metal_innate_" .. allyTeamID) or 0,
innateEnergy = Spring.GetGameRulesParam("OD_allyteam_energy_innate_" .. allyTeamID) or 0,
}
local teamList = Spring.GetTeamList(allyTeamID)
for j = 1, #teamList do
local teamID = teamList[j]
allyTeamInfo[allyTeamID].teams = allyTeamInfo[allyTeamID].teams + 1
allyTeamInfo[allyTeamID].team[allyTeamInfo[allyTeamID].teams] = teamID
generator[allyTeamID][teamID] = {}
generatorList[allyTeamID][teamID] = {data = {}, count = 0}
end
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- Awards
GG.Overdrive_allyTeamResources = {}
local lastAllyTeamResources = {} -- 1 second lag for resource updates
local function sendAllyTeamInformationToAwards(allyTeamID, summedBaseMetal, summedOverdrive, allyTeamEnergyIncome, ODenergy, wasteEnergy)
local last = lastAllyTeamResources[allyTeamID] or {}
GG.Overdrive_allyTeamResources[allyTeamID] = {
baseMetal = summedBaseMetal,
overdriveMetal = last.overdriveMetal or 0,
baseEnergy = allyTeamEnergyIncome,
overdriveEnergy = last.overdriveEnergy or 0,
wasteEnergy = last.wasteEnergy or 0,
}
lastAllyTeamResources[allyTeamID] = {
overdriveMetal = summedOverdrive,
overdriveEnergy = ODenergy,
wasteEnergy = wasteEnergy,
}
end
GG.Overdrive_teamResources = {}
local lastTeamResources = {} -- 1 second lag for resource updates
local function sendTeamInformationToAwards(teamID, baseMetal, overdriveMetal, overdriveEnergyChange)
local last = lastTeamResources[teamID] or {}
GG.Overdrive_teamResources[teamID] = {
baseMetal = baseMetal,
overdriveMetal = last.overdriveMetal or 0,
overdriveEnergyChange = last.overdriveEnergyChange or 0,
}
lastTeamResources[teamID] = {
overdriveMetal = overdriveMetal,
overdriveEnergyChange = overdriveEnergyChange,
}
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- local functions
local function energyToExtraM(energy)
return sqrt(energy)*0.25
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- Information Sharing to Widget functions
local privateTable = {private = true}
local previousData = {}
local function SetTeamEconomyRulesParams(
teamID, resourceShares, -- TeamID of the team as well as number of active allies.
summedBaseMetal, -- AllyTeam base metal extrator income
summedOverdrive, -- AllyTeam overdrive income
allyTeamMiscMetalIncome, -- AllyTeam constructor income
allyTeamEnergyIncome, -- AllyTeam total energy generator income
allyTeamEnergyMisc, -- Team share innate and constructor energyIncome
overdriveEnergySpending, -- AllyTeam energy spent on overdrive
energyWasted, -- AllyTeam energy excess
baseShare, -- Team share of base metal extractor income
odShare, -- Team share of overdrive income
miscShare, -- Team share of constructor metal income
energyIncome, -- Total energy generator income
energyMisc, -- Team share innate and constructor energyIncome
overdriveEnergyNet, -- Amount of energy spent or recieved due to overdrive and income
overdriveEnergyChange) -- real change in energy due to overdrive
if previousData[teamID] then
local pd = previousData[teamID]
spSetTeamRulesParam(teamID, "OD_allies", pd.resourceShares, privateTable)
spSetTeamRulesParam(teamID, "OD_team_metalBase", pd.summedBaseMetal, privateTable)
spSetTeamRulesParam(teamID, "OD_team_metalOverdrive", pd.summedOverdrive, privateTable)
spSetTeamRulesParam(teamID, "OD_team_metalMisc", pd.allyTeamMiscMetalIncome, privateTable)
spSetTeamRulesParam(teamID, "OD_team_energyIncome", pd.allyTeamEnergyIncome, privateTable)
spSetTeamRulesParam(teamID, "OD_team_energyMisc", pd.allyTeamEnergyMisc, privateTable)
spSetTeamRulesParam(teamID, "OD_team_energyOverdrive", pd.overdriveEnergySpending, privateTable)
spSetTeamRulesParam(teamID, "OD_team_energyWaste", pd.energyWasted, privateTable)
spSetTeamRulesParam(teamID, "OD_metalBase", pd.baseShare, privateTable)
spSetTeamRulesParam(teamID, "OD_metalOverdrive", pd.odShare, privateTable)
spSetTeamRulesParam(teamID, "OD_metalMisc", pd.miscShare, privateTable)
spSetTeamRulesParam(teamID, "OD_energyIncome", pd.energyIncome, privateTable)
spSetTeamRulesParam(teamID, "OD_energyMisc", pd.energyMisc, privateTable)
spSetTeamRulesParam(teamID, "OD_energyOverdrive", pd.overdriveEnergyNet, privateTable)
spSetTeamRulesParam(teamID, "OD_energyChange", pd.overdriveEnergyChange, privateTable)
spSetTeamRulesParam(teamID, "OD_RoI_metalDue", teamPayback[teamID].metalDueOD, privateTable)
spSetTeamRulesParam(teamID, "OD_base_metalDue", teamPayback[teamID].metalDueBase, privateTable)
else
previousData[teamID] = {}
end
local pd = previousData[teamID]
pd.resourceShares = resourceShares
pd.summedBaseMetal = summedBaseMetal
pd.summedOverdrive = summedOverdrive
pd.allyTeamMiscMetalIncome = allyTeamMiscMetalIncome
pd.allyTeamEnergyIncome = allyTeamEnergyIncome
pd.allyTeamEnergyMisc = allyTeamEnergyMisc
pd.overdriveEnergySpending = overdriveEnergySpending
pd.energyWasted = energyWasted
pd.baseShare = baseShare
pd.odShare = odShare
pd.miscShare = miscShare
pd.energyIncome = energyIncome
pd.energyMisc = energyMisc
pd.overdriveEnergyNet = overdriveEnergyNet
pd.overdriveEnergyChange = overdriveEnergyChange
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- PYLONS
local function AddPylonToGrid(unitID)
local allyTeamID = spGetUnitAllyTeam(unitID)
local pX,_,pZ = spGetUnitPosition(unitID)
local ai = allyTeamInfo[allyTeamID]
if debugGridMode then
Spring.Echo("AddPylonToGrid " .. unitID)
end
local newGridID = 0
local attachedGrids = 0
local attachedGrid = {}
local attachedGridID = {}
--check for nearby pylons
local ownRange = pylon[allyTeamID][unitID].linkRange
local attachedPylons = pylon[allyTeamID][unitID].attachedPylons
for i = 2, attachedPylons[1] do
local pid = attachedPylons[i]
local pylonData = pylon[allyTeamID][pid]
if pylonData then
if pid ~= unitID and pylonData.gridID ~= 0 and pylonData.active then
if not attachedGridID[pylonData.gridID] then
attachedGrids = attachedGrids + 1
attachedGrid[attachedGrids] = pylonData.gridID
attachedGridID[pylonData.gridID] = true
end
end
elseif not spammedError then
Spring.Echo("Pylon problem detected in AddPylonToGrid.")
end
end
if attachedGrids == 0 then -- create a new grid
local foundSpot = false
for i = 1, ai.grids do
if ai.nilGrid[i] then
ai.grid[i] = {
pylon = {},
}
newGridID = i
ai.nilGrid[i] = false
foundSpot = true
break
end
end
if not foundSpot then
ai.grids = ai.grids + 1
newGridID = ai.grids
ai.grid[ai.grids] = {
pylon = {},
}
mexes[allyTeamID][newGridID] = {}
end
else -- add to an existing grid
newGridID = attachedGrid[1]
for i = 2, attachedGrids do -- merge grids if it attaches to 2 or more
local oldGridID = attachedGrid[i]
for pid,_ in pairs(ai.grid[oldGridID].pylon) do
local pylonData = pylon[allyTeamID][pid]
pylonData.gridID = newGridID
--NOTE: since mex became a pylon it no longer store list of mex, now only store itself as mex
if pylonData.mex then
local mid = pid
mexes[allyTeamID][newGridID][mid] = mexes[allyTeamID][oldGridID][mid]
mexByID[mid].gridID = newGridID
mexes[allyTeamID][oldGridID][mid] = nil
end
ai.grid[newGridID].pylon[pid] = true
spSetUnitRulesParam(pid,"gridNumber",newGridID,alliedTrueTable)
end
ai.nilGrid[oldGridID] = true
end
end
ai.grid[newGridID].pylon[unitID] = true
pylon[allyTeamID][unitID].gridID = newGridID
spSetUnitRulesParam(unitID,"gridNumber",newGridID,alliedTrueTable)
-- add econ to new grid
-- mexes
if pylon[allyTeamID][unitID].mex and mexes[allyTeamID][0][unitID] then
local mid = unitID
local orgMetal = mexes[allyTeamID][0][mid]
mexes[allyTeamID][newGridID][mid] = orgMetal
mexByID[mid].gridID = newGridID
mexes[allyTeamID][0][mid] = nil
end
end
local function QueueAddPylonToGrid(unitID)
if debugGridMode then
Spring.Echo("QueueAddPylonToGrid " .. unitID)
end
if not pylonGridQueue then
pylonGridQueue = {}
end
pylonGridQueue[unitID] = true
end
local function RemovePylonsFromGridQueue(unitID)
if debugGridMode then
Spring.Echo("RemovePylonsFromGridQueue " .. unitID)
end
if pylonGridQueue then
pylonGridQueue[unitID] = nil
end
end
local function AddPylon(unitID, unitDefID, range)
local allyTeamID = spGetUnitAllyTeam(unitID)
local pX,_,pZ = spGetUnitPosition(unitID)
local ai = allyTeamInfo[allyTeamID]
if pylon[allyTeamID][unitID] then
return
end
quadFields[allyTeamID]:Insert(unitID, pX, pZ, range)
local intersections = quadFields[allyTeamID]:GetIntersections(unitID)
pylon[allyTeamID][unitID] = {
gridID = 0,
--mexes = 0,
mex = (mexByID[unitID] and true) or false,
attachedPylons = intersections,
linkRange = range,
mexRange = 10,
--nearEnergy = {},
x = pX,
z = pZ,
neededLink = pylonDefs[unitDefID].neededLink,
active = true,
color = 0,
}
for i = 2, intersections[1] do
local pid = intersections[i]
local pylonData = pylon[allyTeamID][pid]
if pylonData then
local attachedPylons = pylonData.attachedPylons
attachedPylons[1] = attachedPylons[1] + 1
attachedPylons[attachedPylons[1]] = unitID
elseif not spammedError then
Spring.Echo("Pylon problem detected in AddPylonToGrid.")
end
end
local list = pylonList[allyTeamID]
list.count = list.count + 1
list.data[list.count] = unitID
pylon[allyTeamID][unitID].listID = list.count
if debugGridMode then
Spring.Echo("AddPylon " .. unitID)
Spring.Utilities.UnitEcho(unitID, list.count .. ", " .. unitID)
end
QueueAddPylonToGrid(unitID)
end
local function DestroyGrid(allyTeamID,oldGridID)
local ai = allyTeamInfo[allyTeamID]
if debugGridMode then
Spring.Echo("DestroyGrid " .. oldGridID)
end
for pid,_ in pairs(ai.grid[oldGridID].pylon) do
pylon[allyTeamID][pid].gridID = 0
if (pylon[allyTeamID][pid].mex) then
local mid = pid
local orgMetal = mexes[allyTeamID][oldGridID][mid]
mexes[allyTeamID][oldGridID][mid] = nil
mexes[allyTeamID][0][mid] = orgMetal
mexByID[mid].gridID = 0
end
end
ai.nilGrid[oldGridID] = true
end
local function ReactivatePylon(unitID)
local allyTeamID = spGetUnitAllyTeam(unitID)
local ai = allyTeamInfo[allyTeamID]
if debugGridMode then
Spring.Echo("ReactivatePylon " .. unitID)
end
pylon[allyTeamID][unitID].active = true
QueueAddPylonToGrid(unitID)
end
local function DeactivatePylon(unitID)
local allyTeamID = spGetUnitAllyTeam(unitID)
local ai = allyTeamInfo[allyTeamID]
if debugGridMode then
Spring.Echo("DeactivatePylon " .. unitID)
end
RemovePylonsFromGridQueue(unitID)
local oldGridID = pylon[allyTeamID][unitID].gridID
if oldGridID ~= 0 then
local pylonMap = ai.grid[oldGridID].pylon
local energyList = pylon[allyTeamID][unitID].nearEnergy
DestroyGrid(allyTeamID,oldGridID)
for pid,_ in pairs(pylonMap) do
if (pid ~= unitID) then
QueueAddPylonToGrid(pid)
end
end
end
pylon[allyTeamID][unitID].active = false
end
local function RemovePylon(unitID)
local allyTeamID = spGetUnitAllyTeam(unitID)
if debugGridMode then
Spring.Echo("RemovePylon start " .. unitID)
Spring.Utilities.TableEcho(pylonList[allyTeamID])
Spring.Utilities.TableEcho(pylon[allyTeamID])
end
RemovePylonsFromGridQueue(unitID)
if not pylon[allyTeamID][unitID] then
--Spring.Echo("RemovePylon not pylon[allyTeamID][unitID] " .. unitID)
return
end
local pX,_,pZ = spGetUnitPosition(unitID)
local ai = allyTeamInfo[allyTeamID]
local intersections = pylon[allyTeamID][unitID].attachedPylons
for i = 2, intersections[1] do
local pid = intersections[i]
local pylonData = pylon[allyTeamID][pid]
if pylonData then
local attachedPylons = pylonData.attachedPylons
for j = 2, attachedPylons[1] do
if attachedPylons[j] == unitID then
attachedPylons[j] = attachedPylons[attachedPylons[1]]
attachedPylons[1] = attachedPylons[1] - 1 -- no need to delete since we keep size
break
end
end
elseif not spammedError then
Spring.Echo("Pylon problem detected in AddPylonToGrid.")
end
end
quadFields[allyTeamID]:Remove(unitID)
local oldGridID = pylon[allyTeamID][unitID].gridID
local activeState = pylon[allyTeamID][unitID].active
local isMex = pylon[allyTeamID][unitID].mex
if activeState and oldGridID ~= 0 then
local pylonMap = ai.grid[oldGridID].pylon
local energyList = pylon[allyTeamID][unitID].nearEnergy
DestroyGrid(allyTeamID,oldGridID)
for pid,_ in pairs(pylonMap) do
if (pid ~= unitID) then
QueueAddPylonToGrid(pid)
end
end
end
local list = pylonList[allyTeamID]
local listID = pylon[allyTeamID][unitID].listID
list.data[listID] = list.data[list.count]
pylon[allyTeamID][list.data[listID]].listID = listID
list.data[list.count] = nil
list.count = list.count - 1
pylon[allyTeamID][unitID] = nil
-- mexes
if isMex then
local mid = unitID
local orgMetal = mexes[allyTeamID][0][mid]
mexes[allyTeamID][0][mid] = nil
local teamID = mexByID[unitID].refundTeamID
if teamID then
teamPayback[teamID].metalDueBase = teamPayback[teamID].metalDueBase - mexByID[unitID].refundTotal + mexByID[unitID].refundSoFar
end
mexByID[unitID] = nil
local mexGridID = oldGridID --Note: mexGridID is oldGridID of this pylon because mex is this pylon
-- takenMexId[unitID] = false
mexes[allyTeamID][mexGridID][mid] = orgMetal
mexByID[unitID].gridID = mexGridID
end
if debugGridMode then
Spring.Echo("RemovePylon end " .. unitID)
Spring.Utilities.TableEcho(pylonList[allyTeamID])
Spring.Utilities.TableEcho(pylon[allyTeamID])
end
end
local function AddPylonsInQueueToGrid()
if pylonGridQueue then
for pid,_ in pairs(pylonGridQueue) do
AddPylonToGrid(pid)
end
pylonGridQueue =false
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- PAYBACK
-- teamPayback[teamID] = {count = 0, toRemove = {}, data = {[1] = {unitID = unitID, cost = costOfUnit, repaid = howMuchHasBeenRepaid}}}
local function AddEnergyToPayback(unitID, unitDefID, unitTeam)
if unitPaybackTeamID[unitID] then
-- Only add units to payback once.
return
end
local def = paybackDefs[unitDefID]
unitPaybackTeamID[unitID] = unitTeam
local teamData = teamPayback[unitTeam]
teamData.count = teamData.count + 1
teamData.data[teamData.count] = {
unitID = unitID,
cost = def.cost,
repaid = 0,
}
teamData.metalDueOD = teamData.metalDueOD + def.cost
end
local function RemoveEnergyToPayback(unitID, unitDefID)
local unitTeam = unitPaybackTeamID[unitID]
if unitTeam then -- many energy pieces will not have a payback when destroyed
local teamData = teamPayback[unitTeam]
teamData.toRemove[unitID] = true
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- Overdrive and resource handling
local function OptimizeOverDrive(allyTeamID,allyTeamData,allyE,maxGridCapacity)
local summedMetalProduction = 0
local summedBaseMetal = 0
local summedOverdrive = 0
local maxedMetalProduction = 0
local maxedBaseMetal = 0
local maxedOverdrive = 0
local allyMetalSquared = 0
local allyTeamMexes = mexes[allyTeamID]
-- Calculate income squared sum each loop because mex income can change (eg handicap, slow damage)
local curMexIncomes = {}
local gridMexSquareSum = {}
for i = 1, allyTeamData.grids do -- loop through grids
gridMexSquareSum[i] = 0
for unitID, orgMetal in pairs(allyTeamMexes[i]) do -- loop mexes
local stunned_or_inbuld = spGetUnitIsStunned(unitID) or (spGetUnitRulesParam(unitID,"disarmed") == 1)
if stunned_or_inbuld then
orgMetal = 0
end
local incomeFactor = spGetUnitRulesParam(unitID, "resourceGenerationFactor") or 1
if incomeFactor then
orgMetal = orgMetal * incomeFactor
end
curMexIncomes[unitID] = orgMetal
allyMetalSquared = allyMetalSquared + orgMetal * orgMetal
gridMexSquareSum[i] = gridMexSquareSum[i] + orgMetal * orgMetal
end
end
local energyWasted = allyE
local gridEnergySpent = {}
local gridMetalGain = {}
local mexBaseMetal = {}
local privateBaseMetal = {}
local reCalc = true
local maxedGrid = {}
while reCalc do -- calculate overdrive for as long as a new grid is not maxed
reCalc = false
for i = 1, allyTeamData.grids do -- loop through grids
if not (maxedGrid[i] or allyTeamData.nilGrid[i]) then -- do not check maxed grids
gridEnergySpent[i] = 0
gridMetalGain[i] = 0
for unitID, _ in pairs(allyTeamMexes[i]) do -- loop mexes
local myMetalIncome = curMexIncomes[unitID]
local mexE = 0
if (allyMetalSquared > 0) then -- divide energy in ratio given by squared metal from mex
mexE = allyE * (myMetalIncome * myMetalIncome) / allyMetalSquared --the fraction of E to be consumed with respect to all other Mex
energyWasted = energyWasted - mexE -- leftover E minus Mex usage
gridEnergySpent[i] = gridEnergySpent[i] + mexE
-- if a grid is being too overdriven it has become maxed.
-- the grid's mexSqauredSum is used for best distribution
if gridEnergySpent[i] > maxGridCapacity[i] then --final Mex to be looped since we are out of E to OD the rest of the Mex
gridMetalGain[i] = 0
local gridE = maxGridCapacity[i]
local gridMetalSquared = gridMexSquareSum[i]
if gridMetalSquared <= 0 and not sentErrorWarning then
Spring.Echo("** Warning: gridMetalSquared <= 0 **")
Spring.Echo(gridMetalSquared)
sentErrorWarning = true
end
gridEnergySpent[i] = maxGridCapacity[i]
summedMetalProduction = 0
summedBaseMetal = 0
summedOverdrive = 0
maxedGrid[i] = true
reCalc = true
allyE = allyE - gridE
energyWasted = allyE
for unitID_inner, _ in pairs(allyTeamMexes[i]) do --re-distribute the grid energy to Mex (again! except taking account the limited energy of the grid)
myMetalIncome = curMexIncomes[unitID_inner]
mexE = gridE*(myMetalIncome * myMetalIncome) / gridMetalSquared
local metalMult = energyToExtraM(mexE)
local thisMexM = myMetalIncome + myMetalIncome * metalMult
spSetUnitRulesParam(unitID_inner, "overdrive", 1 + mexE / 5, inlosTrueTable)
spSetUnitRulesParam(unitID_inner, "overdrive_energyDrain", mexE, inlosTrueTable)
spSetUnitRulesParam(unitID_inner, "current_metalIncome", thisMexM, inlosTrueTable)
spSetUnitRulesParam(unitID_inner, "overdrive_proportion", metalMult, inlosTrueTable)
maxedMetalProduction = maxedMetalProduction + thisMexM
maxedBaseMetal = maxedBaseMetal + myMetalIncome
maxedOverdrive = maxedOverdrive + myMetalIncome * metalMult
allyMetalSquared = allyMetalSquared - myMetalIncome * myMetalIncome
gridMetalGain[i] = gridMetalGain[i] + myMetalIncome * metalMult
if mexByID[unitID_inner].refundTeamID then
mexBaseMetal[unitID_inner] = myMetalIncome
end
end
break --finish distributing energy to 1 grid, go to next grid
end
end
local metalMult = energyToExtraM(mexE)
local thisMexM = myMetalIncome + myMetalIncome * metalMult
spSetUnitRulesParam(unitID, "overdrive", 1 + mexE / 5, inlosTrueTable)
spSetUnitRulesParam(unitID, "overdrive_energyDrain", mexE, inlosTrueTable)
spSetUnitRulesParam(unitID, "current_metalIncome", thisMexM, inlosTrueTable)
spSetUnitRulesParam(unitID, "overdrive_proportion", metalMult, inlosTrueTable)
summedMetalProduction = summedMetalProduction + thisMexM
summedBaseMetal = summedBaseMetal + myMetalIncome
summedOverdrive = summedOverdrive + myMetalIncome * metalMult
gridMetalGain[i] = gridMetalGain[i] + myMetalIncome * metalMult
if mexByID[unitID].refundTeamID then
mexBaseMetal[unitID] = myMetalIncome
end
end
if reCalc then
break
end
end
end
end
for unitID, value in pairs(mexBaseMetal) do
local teamID = mexByID[unitID].refundTeamID
local private_share = value*MEX_REFUND_SHARE*mexByID[unitID].refundTime/mexByID[unitID].refundTimeTotal
privateBaseMetal[teamID] = (privateBaseMetal[teamID] or 0) + private_share
teamPayback[teamID].metalDueBase = teamPayback[teamID].metalDueBase - private_share
mexByID[unitID].refundTime = mexByID[unitID].refundTime - 1
mexByID[unitID].refundSoFar = mexByID[unitID].refundSoFar + private_share
if mexByID[unitID].refundTime <= 0 then
mexByID[unitID].refundTeamID = nil
mexByID[unitID].refundTime = nil
teamPayback[teamID].metalDueBase = teamPayback[teamID].metalDueBase - mexByID[unitID].refundTotal + mexByID[unitID].refundSoFar
end
end
if energyWasted < 0.01 then
energyWasted = 0
end
return energyWasted,
summedMetalProduction + maxedMetalProduction,
summedBaseMetal + maxedBaseMetal,
summedOverdrive + maxedOverdrive,
gridEnergySpent,
gridMetalGain,
privateBaseMetal
end
local function teamEcho(team, st)
if team == 0 then
Spring.Echo(st)
end
end
local lastTeamOverdriveNetLoss = {}
function gadget:GameFrame(n)
if not (GG.Lagmonitor and GG.Lagmonitor.GetResourceShares) then
Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Lag monitor doesn't work so Overdrive is STUFFED")
end
local allyTeamResourceShares, teamResourceShare = GG.Lagmonitor.GetResourceShares()
if (n % TEAM_SLOWUPDATE_RATE == 1) then
for allyTeamID, allyTeamData in pairs(allyTeamInfo) do
local debugMode = debugAllyTeam and debugAllyTeam[allyTeamID]
--// Check if pylons changed their active status (emp, reverse-build, ..)
local list = pylonList[allyTeamID]
for i = 1, list.count do
local unitID = list.data[i]
local pylonData = pylon[allyTeamID][unitID]
if pylonData then
if spValidUnitID(unitID) then
local stunned_or_inbuld = spGetUnitIsStunned(unitID) or
(spGetUnitRulesParam(unitID,"disarmed") == 1) or
(spGetUnitRulesParam(unitID,"morphDisable") == 1)
local activeState = Spring.Utilities.GetUnitActiveState(unitID)
local currentlyActive = (not stunned_or_inbuld) and (activeState or pylonData.neededLink)
if (currentlyActive) and (not pylonData.active) then
ReactivatePylon(unitID)
elseif (not currentlyActive) and (pylonData.active) then
DeactivatePylon(unitID)
end
end
elseif not spammedError then
Spring.Echo("Pylon problem detected in status check.")
end
end
AddPylonsInQueueToGrid()
--// Calculate personal and shared energy income, and shared constructor metal income.
-- Income is only from energy structures and constructors. Reclaim is always personal and unhandled by OD.
local resourceShares = allyTeamResourceShares[allyTeamID]
local splitByShare = true
if (not resourceShares) or resourceShares < 1 then
splitByShare = false
resourceShares = allyTeamData.teams
end
local allyTeamMiscMetalIncome = allyTeamData.innateMetal
local allyTeamSharedEnergyIncome = allyTeamData.innateEnergy
local teamEnergy = {}
for j = 1, allyTeamData.teams do
local teamID = allyTeamData.team[j]
-- Calculate total energy and misc. metal income from units and structures
local genList = generatorList[allyTeamID][teamID]
local gen = generator[allyTeamID][teamID]
local sumEnergy = 0
for i = 1, genList.count do
local unitID = genList.data[i]
local data = gen[unitID]
if spValidUnitID(unitID) then
if spGetUnitRulesParam(unitID, "isWind") then
local energy = spGetUnitRulesParam(unitID,"current_energyIncome") or 0
sumEnergy = sumEnergy + energy
else
local stunned_or_inbuld = spGetUnitIsStunned(unitID)
local currentlyActive = not stunned_or_inbuld
local metal, energy = 0, 0
if currentlyActive then
local incomeFactor = spGetUnitRulesParam(unitID,"resourceGenerationFactor") or 1
metal = data.metalIncome*incomeFactor
energy = data.energyIncome*incomeFactor
allyTeamMiscMetalIncome = allyTeamMiscMetalIncome + metal
if data.sharedEnergyGenerator then
allyTeamSharedEnergyIncome = allyTeamSharedEnergyIncome + energy
else
sumEnergy = sumEnergy + energy
end
end
spSetUnitRulesParam(unitID, "current_metalIncome", metal, inlosTrueTable)
spSetUnitRulesParam(unitID, "current_energyIncome", energy, inlosTrueTable)
end
end
end
teamEnergy[teamID] = {inc = sumEnergy}
end
if debugMode then
Spring.Echo("=============== Overdrive Debug " .. allyTeamID .. " ===============")
Spring.Echo("resourceShares", resourceShares, "teams", allyTeamData.teams, "metal", allyTeamMiscMetalIncome, "energy", allyTeamSharedEnergyIncome)
Spring.Echo("splitByShare", splitByShare, "innate metal", allyTeamData.innateMetal, "innate energy", allyTeamData.innateEnergy)
end
--// Calculate total energy and other metal income from structures and units
-- Does not include reclaim
local allyTeamEnergyIncome = 0
local allyTeamExpense = 0
local allyTeamEnergySpare = 0
local allyTeamPositiveSpare = 0
local allyTeamNegativeSpare = 0
local allyTeamEnergyCurrent = 0
local allyTeamEnergyMax = 0
local allyTeamEnergyMaxCurMax = 0
local holdBackEnergyFromOverdrive = 0
local energyProducerOrUserCount = 0
local sumInc = 0
for i = 1, allyTeamData.teams do
local teamID = allyTeamData.team[i]
-- Collect energy information and contribute to ally team data.
local te = teamEnergy[teamID]
local share = (splitByShare and teamResourceShare[teamID]) or 1
te.inc = te.inc + share*allyTeamSharedEnergyIncome/resourceShares
te.cur, te.max, te.pull, _, te.exp, _, te.sent, te.rec = spGetTeamResources(teamID, "energy")
te.exp = math.max(0, te.exp - (lastTeamOverdriveNetLoss[teamID] or 0))
te.max = math.max(MIN_STORAGE, te.max - HIDDEN_STORAGE) -- Caretakers spend in chunks of 0.33
allyTeamEnergyIncome = allyTeamEnergyIncome + te.inc
allyTeamEnergyCurrent = allyTeamEnergyCurrent + te.cur
allyTeamEnergyMax = allyTeamEnergyMax + te.max
allyTeamExpense = allyTeamExpense + te.exp
te.spare = te.inc - te.exp
if te.max == MIN_STORAGE and te.spare < MIN_STORAGE then
te.spare = 0
end
allyTeamEnergySpare = allyTeamEnergySpare + te.spare
allyTeamPositiveSpare = allyTeamPositiveSpare + max(0, te.spare)
allyTeamNegativeSpare = allyTeamNegativeSpare + max(0, -te.spare)
if debugMode then
Spring.Echo("--- Team Economy ---", teamID, "has share", teamResourceShare[teamID])
Spring.Echo("inc", te.inc, "exp", te.exp, "spare", te.spare, "pull", te.pull)
Spring.Echo("last spend", lastTeamOverdriveNetLoss[teamID], "cur", te.cur, "max", te.max)
end
if te.inc > 0 or te.exp > 0 then
-- Include expense in case someone has no economy at all (not even cons) and wants to run cloak.
te.energyProducerOrUser = true
energyProducerOrUserCount = energyProducerOrUserCount + 1
end
end
if energyProducerOrUserCount == 0 then
for i = 1, allyTeamData.teams do
local teamID = allyTeamData.team[i]
local te = teamEnergy[teamID]
te.energyProducerOrUser = true
end
energyProducerOrUserCount = allyTeamData.teams
if energyProducerOrUserCount == 0 then
energyProducerOrUserCount = 1
end
end
-- Allocate extra energy storage to teams with less energy income than the spare energy of their team.
-- This better allows teams to spend at the capacity supported by their team.
local averageSpare = allyTeamEnergySpare/energyProducerOrUserCount
if debugMode then
Spring.Echo("=========== Spare Energy ===========", allyTeamID)
Spring.Echo("averageSpare", averageSpare)
end
for i = 1, allyTeamData.teams do
local teamID = allyTeamData.team[i]
local te = teamEnergy[teamID]
if te.energyProducerOrUser then
te.extraFreeStorage = math.max(0, averageSpare - te.inc)
-- This prevents full overdrive until everyone has full energy storage.
allyTeamEnergyMaxCurMax = allyTeamEnergyMaxCurMax + math.max(te.max + te.extraFreeStorage, te.cur)
-- Save from energy from being sent to overdrive if we are stalling and have below average energy income.
local holdBack = math.max(0, te.extraFreeStorage - te.cur)
holdBackEnergyFromOverdrive = holdBackEnergyFromOverdrive + holdBack
if debugMode then
Spring.Echo(teamID, "extraFreeStorage", te.extraFreeStorage, "spare", te.spare, "held back", holdBack)
end
else
te.extraFreeStorage = 0
if debugMode then
Spring.Echo(teamID, "Not participating")
end
end
end
-- This is how much energy will be spent on overdrive. It remains to determine how much
-- is spent by each player.
local energyForOverdrive = max(0, allyTeamEnergySpare)*((allyTeamEnergyMaxCurMax > 0 and max(0, min(1, allyTeamEnergyCurrent/allyTeamEnergyMaxCurMax))) or 1)
energyForOverdrive = math.max(0, energyForOverdrive - holdBackEnergyFromOverdrive)
if debugMode then
Spring.Echo("=========== AllyTeam Economy ===========", allyTeamID)
Spring.Echo("inc", allyTeamEnergyIncome, "exp", allyTeamExpense, "spare", allyTeamEnergySpare)
Spring.Echo("+spare", allyTeamPositiveSpare, "-spare", allyTeamNegativeSpare, "cur", allyTeamEnergyCurrent, "max", allyTeamEnergyMax)
Spring.Echo("energyForOverdrive", energyForOverdrive, "heldBack", holdBackEnergyFromOverdrive)
Spring.Echo("maxCurMax", allyTeamEnergyMaxCurMax, "averageSpare", averageSpare)
end
-- The following inequality holds:
-- energyForOverdrive <= allyTeamEnergySpare <= allyTeamPositiveSpare
-- which means the redistribution is guaranteed to work
--// Spend energy on overdrive and redistribute energy to stallers.
for i = 1, allyTeamData.teams do
local teamID = allyTeamData.team[i]
local te = teamEnergy[teamID]
if te.spare > 0 then
-- Teams with spare energy spend their energy proportional to how much is needed for overdrive.
te.overdriveEnergyNet = -te.spare*energyForOverdrive/allyTeamPositiveSpare
-- Note that this value is negative
else
te.overdriveEnergyNet = 0
end
end
-- Check for consistency.
--local totalNet = 0
--for i = 1, allyTeamData.teams do
-- local teamID = allyTeamData.team[i]
-- local te = teamEnergy[teamID]
-- totalNet = totalNet + te.overdriveEnergyNet
--end
--teamEcho(allyTeamID, totalNet .. " " .. energyForOverdrive)
--// Calculate Per-Grid Energy
local maxGridCapacity = {}
for i = 1, allyTeamData.grids do
maxGridCapacity[i] = 0
if not allyTeamData.nilGrid[i] then
for unitID,_ in pairs(allyTeamData.grid[i].pylon) do
local stunned_or_inbuild = spGetUnitIsStunned(unitID) or (spGetUnitRulesParam(unitID,"disarmed") == 1) or (spGetUnitRulesParam(unitID,"morphDisable") == 1)
if (not stunned_or_inbuild) then
local income = spGetUnitRulesParam(unitID, "current_energyIncome") or 0
maxGridCapacity[i] = maxGridCapacity[i] + income
end
end
end
end
--// check if pylons disable due to low grid power (eg weapons)
for i = 1, list.count do
local unitID = list.data[i]
local pylonData = pylon[allyTeamID][unitID]
if pylonData then
if pylonData.neededLink then
if pylonData.gridID == 0 or pylonData.neededLink > maxGridCapacity[pylonData.gridID] then
spSetUnitRulesParam(unitID,"lowpower",1, inlosTrueTable)
GG.ScriptNotifyUnpowered(unitID, true)
else
spSetUnitRulesParam(unitID,"lowpower",0, inlosTrueTable)
GG.ScriptNotifyUnpowered(unitID, false)
end
end
elseif not spammedError then
Spring.Echo("Pylon problem detected in low power check.")
end
end
--// Use the free Grid-Energy for Overdrive
local energyWasted, summedMetalProduction, summedBaseMetal, summedOverdrive,
gridEnergySpent, gridMetalGain, privateBaseMetal =
OptimizeOverDrive(allyTeamID,allyTeamData,energyForOverdrive,maxGridCapacity)
local overdriveEnergySpending = energyForOverdrive - energyWasted
--// Refund excess energy from overdrive and overfull storages.
local totalFreeStorage = 0
local totalFreeStorageLimited = 0
local energyToRefund = energyWasted
for i = 1, allyTeamData.teams do
local teamID = allyTeamData.team[i]
local te = teamEnergy[teamID]
-- Storage capacing + eexpected spending is the maximun allowed storage.
-- Allow a refund up to the to the average spare energy contributed to the system. This allows
-- people with zero storage to build.
te.freeStorage = te.max + te.exp - te.cur + te.extraFreeStorage
if te.energyProducerOrUser then
te.freeStorage = te.freeStorage + allyTeamEnergySpare/energyProducerOrUserCount
end
if te.freeStorage > 0 then
if te.energyProducerOrUser then
totalFreeStorage = totalFreeStorage + te.freeStorage
totalFreeStorageLimited = totalFreeStorageLimited + min(FREE_STORAGE_LIMIT, te.freeStorage)
if debugMode then
Spring.Echo(teamID, "Free", te.freeStorage)
end
end
else
-- Even sides that do not produce or consume may have excess energy.
energyToRefund = energyToRefund - te.freeStorage
te.overdriveEnergyNet = te.overdriveEnergyNet + te.freeStorage
te.freeStorage = 0
if debugMode then
Spring.Echo(teamID, "Overflow", -te.freeStorage)
end
end
end
if debugMode then
Spring.Echo("AllyTeam totalFreeStorage", totalFreeStorage, "energyToRefund", energyToRefund)
end
if totalFreeStorageLimited > energyToRefund then
for i = 1, allyTeamData.teams do
local teamID = allyTeamData.team[i]
local te = teamEnergy[teamID]
if te.energyProducerOrUser then
te.overdriveEnergyNet = te.overdriveEnergyNet + energyToRefund*min(FREE_STORAGE_LIMIT, te.freeStorage)/totalFreeStorageLimited
end
end
energyWasted = 0
elseif totalFreeStorage > energyToRefund then
energyToRefund = energyToRefund - totalFreeStorageLimited -- Give everyone energy up to the free storage limit.
totalFreeStorage = totalFreeStorage - totalFreeStorageLimited
for i = 1, allyTeamData.teams do
local teamID = allyTeamData.team[i]
local te = teamEnergy[teamID]
if te.energyProducerOrUser then
if te.freeStorage > FREE_STORAGE_LIMIT then
te.overdriveEnergyNet = te.overdriveEnergyNet + FREE_STORAGE_LIMIT + energyToRefund*(te.freeStorage - FREE_STORAGE_LIMIT)/totalFreeStorage
else
te.overdriveEnergyNet = te.overdriveEnergyNet + te.freeStorage
end
end
end
energyWasted = 0
else
for i = 1, allyTeamData.teams do
local teamID = allyTeamData.team[i]
local te = teamEnergy[teamID]
if te.energyProducerOrUser then
te.overdriveEnergyNet = te.overdriveEnergyNet + te.freeStorage
end
end
energyWasted = energyToRefund - totalFreeStorage
end
if debugMode then
Spring.Echo("AllyTeam energyWasted", energyWasted)
end
--// Income For non-Gridded mexes
for unitID, orgMetal in pairs(mexes[allyTeamID][0]) do
local stunned_or_inbuld = spGetUnitIsStunned(unitID) or (spGetUnitRulesParam(unitID,"disarmed") == 1)
if stunned_or_inbuld then
orgMetal = 0
end
summedBaseMetal = summedBaseMetal + orgMetal
spSetUnitRulesParam(unitID, "overdrive", 1, inlosTrueTable)
spSetUnitRulesParam(unitID, "overdrive_energyDrain", 0, inlosTrueTable)
spSetUnitRulesParam(unitID, "current_metalIncome", orgMetal, inlosTrueTable)
spSetUnitRulesParam(unitID, "overdrive_proportion", 0, inlosTrueTable)
if mexByID[unitID].refundTeamID then
local teamID = mexByID[unitID].refundTeamID
local private_share = orgMetal*MEX_REFUND_SHARE*mexByID[unitID].refundTime/mexByID[unitID].refundTimeTotal
privateBaseMetal[teamID] = (privateBaseMetal[teamID] or 0) + private_share
teamPayback[teamID].metalDueBase = teamPayback[teamID].metalDueBase - private_share
mexByID[unitID].refundTime = mexByID[unitID].refundTime - 1
mexByID[unitID].refundSoFar = mexByID[unitID].refundSoFar + private_share
if mexByID[unitID].refundTime <= 0 then
mexByID[unitID].refundTeamID = nil
mexByID[unitID].refundTime = nil
teamPayback[teamID].metalDueBase = teamPayback[teamID].metalDueBase - mexByID[unitID].refundTotal + mexByID[unitID].refundSoFar
end
end
summedMetalProduction = summedMetalProduction + orgMetal
end
--// Update pylon tooltips
for i = 1, list.count do
local unitID = list.data[i]
local pylonData = pylon[allyTeamID][unitID]
if pylonData then
local grid = pylonData.gridID
local gridEfficiency = -1
if grid ~= 0 then
if gridMetalGain[grid] > 0 then
gridEfficiency = gridEnergySpent[grid]/gridMetalGain[grid]
else
gridEfficiency = 0
end
end
spSetUnitRulesParam(unitID, "gridefficiency", gridEfficiency, alliedTrueTable)
if not pylonData.mex then
local unitDefID = spGetUnitDefID(unitID)
if not unitDefID then
if not spammedError then
Spring.Log(gadget:GetInfo().name, LOG.ERROR, "unitDefID missing for pylon")
spammedError = true
end
else
if not pylonDefs[unitDefID].keeptooltip then
if grid ~= 0 then
spSetUnitRulesParam(unitID, "OD_gridCurrent", gridEnergySpent[grid], alliedTrueTable)
spSetUnitRulesParam(unitID, "OD_gridMaximum", maxGridCapacity[grid], alliedTrueTable)
spSetUnitRulesParam(unitID, "OD_gridMetal", gridMetalGain[grid], alliedTrueTable)
else
spSetUnitRulesParam(unitID, "OD_gridCurrent", -1, alliedTrueTable)
end
end
end
end
elseif not spammedError then
Spring.Echo("Pylon problem detected in tooltip update.")
end
end
-- Extra base share from mex production
local summedBaseMetalAfterPrivate = summedBaseMetal
for i = 1, allyTeamData.teams do -- calculate active team OD sum
local teamID = allyTeamData.team[i]
if privateBaseMetal[teamID] then
summedBaseMetalAfterPrivate = summedBaseMetalAfterPrivate - privateBaseMetal[teamID]
end
end
--Spring.Echo(allyTeamID .. " energy sum " .. teamODEnergySum)
sendAllyTeamInformationToAwards(allyTeamID, summedBaseMetal, summedOverdrive, allyTeamEnergyIncome, ODenergy, energyWasted)
-- Payback from energy production
local summedOverdriveMetalAfterPayback = summedOverdrive
local teamPaybackOD = {}
if enableEnergyPayback then
for i = 1, allyTeamData.teams do
local teamID = allyTeamData.team[i]
if teamResourceShare[teamID] then -- Isn't this always 1 or 0?
-- well it can technically be 2+ when comsharing (but shouldn't act as a multiplier because the debt should transfer)
local te = teamEnergy[teamID]
teamPaybackOD[teamID] = 0
local paybackInfo = teamPayback[teamID]
if paybackInfo then
local data = paybackInfo.data
local toRemove = paybackInfo.toRemove
local j = 1
while j <= paybackInfo.count do
local unitID = data[j].unitID
local removeNow = toRemove[unitID]
if not removeNow then
if spValidUnitID(unitID) then
local inc = spGetUnitRulesParam(unitID, "current_energyIncome") or 0
if inc > 0 then
local repayRatio = data[j].repaid/data[j].cost
if repayRatio < 1 then
local repayMetal = inc/allyTeamEnergyIncome * summedOverdrive * paybackFactorFunction(repayRatio)
data[j].repaid = data[j].repaid + repayMetal
summedOverdriveMetalAfterPayback = summedOverdriveMetalAfterPayback - repayMetal
teamPaybackOD[teamID] = teamPaybackOD[teamID] + repayMetal
paybackInfo.metalDueOD = paybackInfo.metalDueOD - repayMetal
--Spring.Echo("Repaid " .. data[j].repaid)
else
removeNow = true
end
end
else
-- This should never happen in theory
removeNow = true
end
end
if removeNow then
paybackInfo.metalDueOD = paybackInfo.metalDueOD + data[j].repaid - data[j].cost
data[j] = data[paybackInfo.count]
if toRemove[unitID] then
toRemove[unitID] = nil
end
data[paybackInfo.count] = nil
paybackInfo.count = paybackInfo.count - 1
else
j = j + 1
end
end
end
end
end
end
--// Share Overdrive Metal and Energy
-- Make changes to team resources
local shareToSend = {}
local metalStorageToSet = {}
local totalToShare = 0
local freeSpace = {}
local totalFreeSpace = 0
local totalMetalIncome = {}
for i = 1, allyTeamData.teams do
local teamID = allyTeamData.team[i]
local te = teamEnergy[teamID]
--// Energy
-- Inactive teams still interact normally with energy for a few reasons:
-- * Energy shared to them would disappear otherwise.
-- * If they have reclaim (somehow) then they could build up storage without sharing.
local energyChange = te.overdriveEnergyNet + te.inc
if energyChange > 0 then
spAddTeamResource(teamID, "e", energyChange)
lastTeamOverdriveNetLoss[teamID] = 0
elseif te.overdriveEnergyNet + te.inc < 0 then
spUseTeamResource(teamID, "e", -energyChange)
lastTeamOverdriveNetLoss[teamID] = -energyChange
else
lastTeamOverdriveNetLoss[teamID] = 0
end
if debugMode then
Spring.Echo("Team energy income", teamID, "change", energyChange, "inc", te.inc, "net", te.overdriveEnergyNet)
end
-- Metal
local odShare = 0
local baseShare = 0
local miscShare = 0
local energyMisc = 0
local share = (splitByShare and teamResourceShare[teamID]) or 1
if share > 0 then
odShare = ((share * summedOverdriveMetalAfterPayback / resourceShares) + (teamPaybackOD[teamID] or 0)) or 0
baseShare = ((share * summedBaseMetalAfterPrivate / resourceShares) + (privateBaseMetal[teamID] or 0)) or 0
miscShare = share * allyTeamMiscMetalIncome / resourceShares
energyMisc = share * allyTeamSharedEnergyIncome / resourceShares
end
sendTeamInformationToAwards(teamID, baseShare, odShare, te.overdriveEnergyNet)
local mCurr, mStor = spGetTeamResources(teamID, "metal")
mStor = math.max(MIN_STORAGE, mStor - HIDDEN_STORAGE) -- Caretakers spend in chunks of 0.33
if mCurr > mStor then
shareToSend[i] = mCurr - mStor
metalStorageToSet[i] = mStor
totalToShare = totalToShare + shareToSend[i]
end
local metalIncome = odShare + baseShare + miscShare
if share > 0 and mCurr + metalIncome < mStor then
freeSpace[i] = mStor - (mCurr + metalIncome)
end
totalMetalIncome[i] = metalIncome
--Spring.Echo(teamID .. " got odShare " .. odShare)
SetTeamEconomyRulesParams(
teamID, resourceShares, -- TeamID of the team as well as number of active allies.
summedBaseMetal, -- AllyTeam base metal extrator income
summedOverdrive, -- AllyTeam overdrive income
allyTeamMiscMetalIncome, -- AllyTeam constructor income
allyTeamEnergyIncome, -- AllyTeam total energy income (everything)
allyTeamSharedEnergyIncome,
overdriveEnergySpending, -- AllyTeam energy spent on overdrive
energyWasted, -- AllyTeam energy excess
baseShare, -- Team share of base metal extractor income
odShare, -- Team share of overdrive income
miscShare, -- Team share of constructor metal income
te.inc, -- Non-reclaim energy income for the team
energyMisc, -- Team share of innate and constructor income
te.overdriveEnergyNet, -- Amount of energy spent or recieved due to overdrive and income
te.overdriveEnergyNet + te.inc -- real change in energy due to overdrive
)
end
for i = 1, allyTeamData.teams do
local share = (splitByShare and teamResourceShare[teamID]) or 1
if share > 0 and freeSpace[i] then
freeSpace[i] = min(freeSpace[i], totalToShare * share)
totalFreeSpace = totalFreeSpace + freeSpace[i]
end
end
if totalToShare ~= 0 then
local excessFactor = 1 - min(1, totalFreeSpace/totalToShare)
local shareFactorPerSpace = (1 - excessFactor)/totalFreeSpace
for i = 1, allyTeamData.teams do
if shareToSend[i] then
local sendID = allyTeamData.team[i]
for j = 1, allyTeamData.teams do
if freeSpace[j] then
local recieveID = allyTeamData.team[j]
Spring.ShareTeamResource(sendID, recieveID, "metal", shareToSend[i] * freeSpace[j] * shareFactorPerSpace)
end
end
if excessFactor ~= 0 and GG.EndgameGraphs then
GG.EndgameGraphs.AddTeamMetalExcess(sendID, shareToSend[i] * excessFactor)
end
end
end
end
for i = 1, allyTeamData.teams do
local teamID = allyTeamData.team[i]
if metalStorageToSet[i] then
spSetTeamResource(teamID, "metal", metalStorageToSet[i])
end
spAddTeamResource(teamID, "m", totalMetalIncome[i])
end
end
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- MEXES
local function TransferMexRefund(unitID, newTeamID)
if newTeamID and mexByID[unitID].refundTeamID then
local oldTeamID = mexByID[unitID].refundTeamID
local remainingPayback = mexByID[unitID].refundTotal - mexByID[unitID].refundSoFar
mexByID[unitID].refundTeamID = newTeamID
teamPayback[oldTeamID].metalDueBase = teamPayback[oldTeamID].metalDueBase - remainingPayback
teamPayback[newTeamID].metalDueBase = teamPayback[newTeamID].metalDueBase + remainingPayback
end
end
local function AddMex(unitID, teamID, metalMake)
if (metalMake or 0) <= 0 then
return
end
local allyTeamID = spGetUnitAllyTeam(unitID)
if (allyTeamID) then
mexByID[unitID] = {gridID = 0, allyTeamID = allyTeamID}
if teamID and enableMexPayback then
-- share goes down to 0 linearly, so halved to average it over refund duration
local refundTime = MEX_REFUND_VALUE / ((MEX_REFUND_SHARE / 2) * metalMake)
mexByID[unitID].refundTeamID = teamID
mexByID[unitID].refundTime = refundTime
mexByID[unitID].refundTimeTotal = refundTime
mexByID[unitID].refundTotal = MEX_REFUND_VALUE
mexByID[unitID].refundSoFar = 0
teamPayback[teamID].metalDueBase = teamPayback[teamID].metalDueBase + mexByID[unitID].refundTotal
end
spSetUnitRulesParam(unitID, "current_metalIncome", metalMake, inlosTrueTable)
local mexGridID = 0
local pylonData = pylon[allyTeamID][unitID]
if pylonData then
pylonData.mex = true --in case some magical case where pylon was initialized as not mex, then became mex?
mexGridID = pylonData.gridID
end
mexes[allyTeamID][mexGridID][unitID] = metalMake
mexByID[unitID].gridID = mexGridID
end
end
local function RemoveMex(unitID)
local gridID = 0
local mex = mexByID[unitID]
if mex and mexes[mex.allyTeamID][mex.gridID][unitID] then
local orgMetal = mexes[mex.allyTeamID][mex.gridID][unitID]
local ai = allyTeamInfo[mex.allyTeamID]
local g = ai.grid[mex.gridID]
local pylonData = pylon[mex.allyTeamID][unitID]
if pylonData then
pylonData.mex = nil --for some magical case where mex is to be removed but the pylon not?
end
mexes[mex.allyTeamID][mex.gridID][unitID] = nil
local teamID = mexByID[unitID].refundTeamID
if teamID then
teamPayback[teamID].metalDueBase = teamPayback[teamID].metalDueBase - mexByID[unitID].refundTotal + mexByID[unitID].refundSoFar
end
mexByID[unitID] = nil
else
local x,_,z = spGetUnitPosition(unitID)
Spring.MarkerAddPoint(x,0,z,"inconsistent mex entry 124125_1")
end
for allyTeam, _ in pairs(mexes) do
for i = 0, allyTeamInfo[allyTeam].grids do
if (mexes[allyTeam][i][unitID] ~= nil) then
local x,_,z = spGetUnitPosition(unitID)
Spring.MarkerAddPoint(x,0,z,"inconsistent mex entry 124125_0")
end
end
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- RESOURCE GENERATORS
local function AddResourceGenerator(unitID, unitDefID, teamID, allyTeamID)
allyTeamID = allyTeamID or spGetUnitAllyTeam(unitID)
teamID = teamID or spGetUnitTeam(unitID)
--if generator[allyTeamID][teamID][unitID] then
--return
--end
if unitDefID and generatorDefs[unitDefID] then
local defData = generatorDefs[unitDefID]
if spGetUnitRulesParam(unitID, "isWind") then
generator[allyTeamID][teamID][unitID] = {
isWind = defData.isWind,
sharedEnergyGenerator = defData.sharedEnergyGenerator,
}
else
generator[allyTeamID][teamID][unitID] = {
metalIncome = spGetUnitRulesParam(unitID, "wanted_metalIncome") or defData.metalIncome,
energyIncome = spGetUnitRulesParam(unitID, "wanted_energyIncome") or defData.energyIncome,
sharedEnergyGenerator = defData.sharedEnergyGenerator,
}
end
else
generator[allyTeamID][teamID][unitID] = {
metalIncome = spGetUnitRulesParam(unitID, "wanted_metalIncome") or 0,
energyIncome = spGetUnitRulesParam(unitID, "wanted_energyIncome") or 0,
sharedEnergyGenerator = unitDefID and UnitDefs[unitDefID].customParams.shared_energy_gen and true,
}
end
local list = generatorList[allyTeamID][teamID]
list.count = list.count + 1
list.data[list.count] = unitID
generator[allyTeamID][teamID][unitID].listID = list.count
resourceGenoratingUnit[unitID] = true
end
local function RemoveResourceGenerator(unitID, unitDefID, teamID, allyTeamID)
allyTeamID = allyTeamID or spGetUnitAllyTeam(unitID)
teamID = teamID or spGetUnitTeam(unitID)
resourceGenoratingUnit[unitID] = false
--if not generator[allyTeamID][teamID][unitID] then
--return
--end
local list = generatorList[allyTeamID][teamID]
local listID = generator[allyTeamID][teamID][unitID].listID
list.data[listID] = list.data[list.count]
generator[allyTeamID][teamID][list.data[listID]].listID = listID
list.data[list.count] = nil
list.count = list.count - 1
generator[allyTeamID][teamID][unitID] = nil
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local function OverdriveDebugToggle()
if Spring.IsCheatingEnabled() then
debugGridMode = not debugGridMode
if debugGridMode then
local allyTeamList = Spring.GetAllyTeamList()
for i=1,#allyTeamList do
local allyTeamID = allyTeamList[i]
local list = pylonList[allyTeamID]
for j = 1, list.count do
local unitID = list.data[j]
Spring.Utilities.UnitEcho(unitID, j .. ", " .. unitID)
end
end
end
end
end
local function OverdriveDebugEconomyToggle(cmd, line, words, player)
if not Spring.IsCheatingEnabled() then
return
end
local allyTeamID = tonumber(words[1])
Spring.Echo("Debug priority for allyTeam " .. (allyTeamID or "nil"))
if allyTeamID then
if not debugAllyTeam then
debugAllyTeam = {}
end
if debugAllyTeam[allyTeamID] then
debugAllyTeam[allyTeamID] = nil
if #debugAllyTeam == 0 then
debugAllyTeam = {}
end
Spring.Echo("Disabled")
else
debugAllyTeam[allyTeamID] = true
Spring.Echo("Enabled")
end
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- External functions
local externalFunctions = {}
function externalFunctions.AddUnitResourceGeneration(unitID, metal, energy, sharedEnergyGenerator, override)
if not unitID then
return
end
local teamID = Spring.GetUnitTeam(unitID)
local allyTeamID = Spring.GetUnitAllyTeam(unitID)
if not teamID or not generator[allyTeamID] or not generator[allyTeamID][teamID] then
return
end
if not generator[allyTeamID][teamID][unitID] then
AddResourceGenerator(unitID, unitDefID, teamID, allyTeamID)
end
local genData = generator[allyTeamID][teamID][unitID]
local metalIncome = math.max(0, ((override and 0) or genData.metalIncome) + (metal * (Spring.GetModOptions().metalmult or 1)))
local energyIncome = math.max(0, ((override and 0) or genData.energyIncome) + (energy * (Spring.GetModOptions().energymult or 1)))
genData.metalIncome = metalIncome
genData.energyIncome = energyIncome
genData.sharedEnergyGenerator = sharedEnergyGenerator
spSetUnitRulesParam(unitID, "wanted_metalIncome", metalIncome, inlosTrueTable)
spSetUnitRulesParam(unitID, "wanted_energyIncome", energyIncome, inlosTrueTable)
end
function externalFunctions.AddInnateIncome(allyTeamID, metal, energy)
if not (allyTeamID and allyTeamInfo[allyTeamID]) then
return
end
if GG.allyTeamIncomeMult then
metal = metal * GG.allyTeamIncomeMult[allyTeamID]
energy = energy * GG.allyTeamIncomeMult[allyTeamID]
end
allyTeamInfo[allyTeamID].innateMetal = (allyTeamInfo[allyTeamID].innateMetal or 0) + metal
allyTeamInfo[allyTeamID].innateEnergy = (allyTeamInfo[allyTeamID].innateEnergy or 0) + energy
Spring.SetGameRulesParam("OD_allyteam_metal_innate_" .. allyTeamID, allyTeamInfo[allyTeamID].innateMetal)
Spring.SetGameRulesParam("OD_allyteam_energy_innate_" .. allyTeamID, allyTeamInfo[allyTeamID].innateEnergy)
end
function externalFunctions.RedirectTeamIncome(giveTeamID, recieveTeamID)
end
function externalFunctions.RemoveTeamIncomeRedirect(teamID)
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
function gadget:Initialize()
GG.Overdrive = externalFunctions
_G.pylon = pylon
for _, unitID in ipairs(Spring.GetAllUnits()) do
local unitDefID = spGetUnitDefID(unitID)
if (mexDefs[unitDefID]) then
local inc = spGetUnitRulesParam(unitID, "mexIncome")
AddMex(unitID, false, inc)
end
if (pylonDefs[unitDefID]) then
AddPylon(unitID, unitDefID, pylonDefs[unitDefID].range)
end
if (generatorDefs[unitDefID]) or spGetUnitRulesParam(unitID, "wanted_energyIncome") then
AddResourceGenerator(unitID, unitDefID)
end
end
local teamList = Spring.GetTeamList()
for i = 1, #teamList do
teamPayback[teamList[i]] = {
metalDueOD = 0,
metalDueBase = 0,
count = 0,
toRemove = {},
data = {},
}
end
gadgetHandler:AddChatAction("debuggrid", OverdriveDebugToggle, "Toggles grid debug mode for overdrive.")
gadgetHandler:AddChatAction("debugecon", OverdriveDebugEconomyToggle, "Toggles economy debug mode for overdrive.")
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
function gadget:UnitCreated(unitID, unitDefID, unitTeam)
if (mexDefs[unitDefID]) then
local inc = spGetUnitRulesParam(unitID, "mexIncome")
AddMex(unitID, unitTeam, inc)
end
if pylonDefs[unitDefID] then
AddPylon(unitID, unitDefID, pylonDefs[unitDefID].range)
end
if (generatorDefs[unitDefID]) or spGetUnitRulesParam(unitID, "wanted_energyIncome") then
AddResourceGenerator(unitID, unitDefID, unitTeam)
end
end
function gadget:UnitFinished(unitID, unitDefID, unitTeam)
if paybackDefs[unitDefID] and enableEnergyPayback then
AddEnergyToPayback(unitID, unitDefID, unitTeam)
end
end
function gadget:UnitGiven(unitID, unitDefID, teamID, oldTeamID)
local _,_,_,_,_,newAllyTeam = spGetTeamInfo(teamID, false)
local _,_,_,_,_,oldAllyTeam = spGetTeamInfo(oldTeamID, false)
if (newAllyTeam ~= oldAllyTeam) then
if (mexDefs[unitDefID]) then
local inc = spGetUnitRulesParam(unitID, "mexIncome")
AddMex(unitID, false, inc)
end
if pylonDefs[unitDefID] then
AddPylon(unitID, unitDefID, pylonDefs[unitDefID].range)
--Spring.Echo(spGetUnitAllyTeam(unitID) .. " " .. newAllyTeam)
end
else
if mexDefs[unitDefID] and mexByID[unitID] then
TransferMexRefund(unitID, teamID)
end
end
if (generatorDefs[unitDefID]) or spGetUnitRulesParam(unitID, "wanted_energyIncome") then
AddResourceGenerator(unitID, unitDefID, teamID, newAllyTeamID)
end
end
function gadget:UnitTaken(unitID, unitDefID, oldTeamID, teamID)
local _,_,_,_,_,newAllyTeam = spGetTeamInfo(teamID, false)
local _,_,_,_,_,oldAllyTeam = spGetTeamInfo(oldTeamID, false)
if (newAllyTeam ~= oldAllyTeam) then
if (mexDefs[unitDefID] and mexByID[unitID]) then
RemoveMex(unitID)
end
if pylonDefs[unitDefID] then
RemovePylon(unitID)
end
if paybackDefs[unitDefID] and enableEnergyPayback then
RemoveEnergyToPayback(unitID, unitDefID)
end
end
if generatorDefs[unitDefID] or resourceGenoratingUnit[unitID] then
RemoveResourceGenerator(unitID, unitDefID, oldTeamID, oldAllyTeamID)
end
end
function gadget:UnitDestroyed(unitID, unitDefID, unitTeam)
if (mexDefs[unitDefID] and mexByID[unitID]) then
RemoveMex(unitID)
end
if (pylonDefs[unitDefID]) then
RemovePylon(unitID)
end
if paybackDefs[unitDefID] and enableEnergyPayback then
RemoveEnergyToPayback(unitID, unitDefID)
end
if generatorDefs[unitDefID] or resourceGenoratingUnit[unitID] then
RemoveResourceGenerator(unitID, unitDefID, unitTeam)
end
end
-------------------------------------------------------------------------------------
| gpl-2.0 |
Anarchid/Zero-K | units/fakeunit_aatarget.lua | 4 | 1533 | return { fakeunit_aatarget = {
unitname = [[fakeunit_aatarget]],
name = [[Fake AA target]],
description = [[Used by the jumpjet script.]],
acceleration = 0,
activateWhenBuilt = false,
brakeRate = 0,
buildCostEnergy = 0.45,
buildCostMetal = 0.45,
builder = false,
buildPic = [[levelterra.png]],
buildTime = 0.45,
canFly = true,
canGuard = false,
canMove = false,
canPatrol = false,
canSubmerge = false,
category = [[FIXEDWING]],
cruiseAlt = 30,
explodeAs = [[TINY_BUILDINGEX]],
floater = true,
footprintX = 0,
footprintZ = 0,
idleAutoHeal = 10,
idleTime = 300,
initCloaked = false,
kamikaze = true,
kamikazeDistance = 64,
levelGround = false,
maxDamage = 900000,
maxVelocity = 0,
maxWaterDepth = 0,
noAutoFire = false,
noChaseCategory = [[FIXEDWING LAND SINK TURRET SHIP SATELLITE SWIM GUNSHIP FLOAT SUB HOVER]],
objectName = [[debris1x1b.s3o]],
onoffable = false,
script = [[nullscript.lua]],
selfDestructAs = [[TINY_BUILDINGEX]],
selfDestructCountdown = 0,
sightDistance = 0.2,
turnRate = 0,
workerTime = 0,
} }
| gpl-2.0 |
taha560/ir | libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| gpl-2.0 |
NUTIEisBADYT/NUTIEisBADYTS-PD2-Modpack | Full Speed Swarm/lua/blt_keybinds_manager.lua | 1 | 3089 | function BLTKeybind:_SetKey(idx, key)
if not idx then
return false
end
if key == '' then
self._key.idstring = nil
self._key.input = nil
elseif string.find(key, 'mouse ') == 1 then
self._key.idstring = Idstring(key:sub(7))
self._key.input = Input:mouse()
else
self._key.idstring = Idstring(key)
self._key.input = Input:keyboard()
end
log(string.format('[Keybind] Bound %s to %s', tostring(self:Id()), tostring(key)))
self._key[idx] = key
end
function BLTKeybindsManager:update(t, dt, state)
-- Don't run while chatting
if self.fs_editing then
return
end
-- Run keybinds
for _, bind in ipairs(self.fs_filtered_keybinds) do
local keys = bind._key
local kids = keys.idstring
if kids and keys.input:pressed(kids)then
bind:Execute()
end
end
end
local state = Global.load_level and BLTKeybind.StateGame or BLTKeybind.StateMenu
local fs_original_bltkeybindsmanager_registerkeybind = BLTKeybindsManager.register_keybind
function BLTKeybindsManager:register_keybind(...)
local bind = fs_original_bltkeybindsmanager_registerkeybind(self, ...)
if bind:CanExecuteInState(state) and bind:ParentMod():IsEnabled() then
table.insert(self.fs_filtered_keybinds, bind)
end
return bind
end
local BLT = BLT
local _state_menu = BLTKeybind.StateMenu
Hooks:Add('MenuUpdate', 'Base_Keybinds_MenuUpdate', function(t, dt)
BLT.Keybinds:update(t, dt, _state_menu)
end)
local _state_game = BLTKeybind.StateGame
Hooks:Add('GameSetupUpdate', 'Base_Keybinds_GameStateUpdate', function(t, dt)
BLT.Keybinds:update(t, dt, _state_game)
end)
local filtered_keybinds = {}
for _, bind in ipairs(BLT.Keybinds:keybinds()) do
local keys = bind._key
if keys.pc and keys.pc ~= '' then
if bind:CanExecuteInState(state) and bind:ParentMod():IsEnabled() then
bind:_SetKey('pc', keys.pc)
table.insert(filtered_keybinds, bind)
end
end
end
BLT.Keybinds.fs_filtered_keybinds = filtered_keybinds
BLT.Keybinds.fs_editor = {}
function BLTKeybindsManager:enter_edit(source)
self.fs_editor[source] = true
self.fs_editing = true
end
function BLTKeybindsManager:exit_edit(source)
self.fs_editor[source] = nil
self.fs_editing = table.size(self.fs_editor) > 0
end
DelayedCalls:Add('DelayedModFSS_keyboard_typing_stuff', 0, function()
if HUDManager then
Hooks:PostHook(HUDManager, 'set_chat_focus', 'HUDManagerSetChatFocus_FSS', function(self, focus)
if focus then
BLT.Keybinds:enter_edit('HUDChat')
else
BLT.Keybinds:exit_edit('HUDChat')
end
end)
end
Hooks:PostHook(MenuItemInput, '_set_enabled', 'MenuItemInputSetEnabled_FSS', function(self, enabled)
if enabled then
BLT.Keybinds:enter_edit('MenuItemInput')
else
BLT.Keybinds:exit_edit('MenuItemInput')
end
end)
Hooks:PostHook(MenuNodeGui, 'activate_customize_controller', 'MenuNodeGuiActivateCustomizeController_FSS', function(self)
BLT.Keybinds:enter_edit('MenuItemCustomizeController')
end)
Hooks:PostHook(MenuNodeGui, '_end_customize_controller', 'MenuNodeGuiEndCustomizeController_FSS', function(self)
BLT.Keybinds:exit_edit('MenuItemCustomizeController')
end)
end)
| mit |
jerizm/kong | kong/tools/timestamp.lua | 2 | 2046 | --- Module for timestamp support.
-- Based on the LuaTZ module.
-- @copyright Copyright 2016 Mashape Inc. All rights reserved.
-- @license [Apache 2.0](https://opensource.org/licenses/Apache-2.0)
-- @module kong.tools.timestamp
local luatz = require "luatz"
local _M = {}
--- Current UTC time
-- @return UTC time
function _M.get_utc()
return math.floor(luatz.time()) * 1000
end
function _M.get_timetable(now)
local timestamp = now and now or _M.get_utc()
if string.len(tostring(timestamp)) == 13 then
timestamp = timestamp / 1000
end
return luatz.timetable.new_from_timestamp(timestamp)
end
--- Creates a timestamp
-- @param now (optional) Time to generate a timestamp from, if omitted current UTC time will be used
-- @return Timestamp table containing fields; second, minute, hour, day, month, year
function _M.get_timestamps(now)
local timetable = _M.get_timetable(now)
local second = luatz.timetable.new(timetable.year, timetable.month,
timetable.day, timetable.hour,
timetable.min, timetable.sec)
local minute = luatz.timetable.new(timetable.year, timetable.month,
timetable.day, timetable.hour,
timetable.min, 0)
local hour = luatz.timetable.new(timetable.year, timetable.month,
timetable.day, timetable.hour,
0, 0)
local day = luatz.timetable.new(timetable.year, timetable.month,
timetable.day, 0, 0, 0)
local month = luatz.timetable.new(timetable.year, timetable.month,
1, 0, 0, 0)
local year = luatz.timetable.new(timetable.year, 1, 1, 0, 0, 0)
return {
second = math.floor(second:timestamp() * 1000),
minute = minute:timestamp() * 1000,
hour = hour:timestamp() * 1000,
day = day:timestamp() * 1000,
month = month:timestamp() * 1000,
year = year:timestamp() * 1000
}
end
return _M
| apache-2.0 |
jerizm/kong | kong/plugins/response-ratelimiting/dao/postgres.lua | 4 | 1591 | local PostgresDB = require "kong.dao.postgres_db"
local timestamp = require "kong.tools.timestamp"
local fmt = string.format
local concat = table.concat
local _M = PostgresDB:extend()
_M.table = "response_ratelimiting_metrics"
_M.schema = require("kong.plugins.response-ratelimiting.schema")
function _M:increment(api_id, identifier, current_timestamp, value, name)
local buf = {}
local periods = timestamp.get_timestamps(current_timestamp)
for period, period_date in pairs(periods) do
buf[#buf + 1] = fmt("SELECT increment_response_rate_limits('%s', '%s', '%s', to_timestamp('%s') at time zone 'UTC', %d)",
api_id, identifier, name.."_"..period, period_date/1000, value)
end
local queries = concat(buf, ";")
local res, err = self:query(queries)
if not res then
return false, err
end
return true
end
function _M:find(api_id, identifier, current_timestamp, period, name)
local periods = timestamp.get_timestamps(current_timestamp)
local q = fmt([[SELECT *, extract(epoch from period_date)*1000 AS period_date FROM response_ratelimiting_metrics WHERE
api_id = '%s' AND
identifier = '%s' AND
period_date = to_timestamp('%s') at time zone 'UTC' AND
period = '%s'
]], api_id, identifier, periods[period]/1000, name.."_"..period)
local res, err = self:query(q)
if not res or err then
return nil, err
end
return res[1]
end
function _M:count()
return _M.super.count(self, _M.table, nil, _M.schema)
end
return {response_ratelimiting_metrics = _M}
| apache-2.0 |
vincent178/dotfiles | .config/nvim/lua/keymap.lua | 1 | 3467 | -- use vim.keymap.set instead of vim.api.nvim_set_keymap, check more in https://github.com/neovim/neovim/commit/6d41f65aa45f10a93ad476db01413abaac21f27d
local noremap = { noremap = true }
local noremapsilent = { noremap = true, silent = true }
-- Save and exit
vim.keymap.set('n', '<Leader>w', ':w<CR>', noremap)
vim.keymap.set('n', '<Leader>q', ':q<CR>', noremap)
vim.keymap.set('n', '<Leader>qa', ':qa<CR>', noremap)
-- To turn off highlighting until the next search
vim.keymap.set('n', '<Leader>/', ':nohlsearch<CR>', noremapsilent)
-- Move cursor when insert mode
vim.keymap.set('i', "<C-A>", "<Home>", noremap)
vim.keymap.set('i', "<C-E>", "<End>", noremap)
vim.keymap.set('i', "<C-B>", "<Left>", noremap)
vim.keymap.set('i', "<C-F>", "<Right>", noremap)
-- map("n", "<C-j>", "<C-w>j<C-w>")
-- map("n", "<C-h>", "<C-w>h<C-w>")
-- map("n", "<C-k>", "<C-w>k<C-w>")
-- map("n", "<C-l>", "<C-w>l<C-w>")
vim.keymap.set('n', '<Leader>bp', ':bprevious<CR>', noremap)
vim.keymap.set('n', '<Leader>bn', ':bnext<CR>', noremap)
vim.keymap.set('n', '<Leader>bf', ':bfirst<CR>', noremap)
vim.keymap.set('n', '<Leader>bl', ':blast<CR>', noremap)
vim.keymap.set('n', '<Leader>bd', ':bdelete<CR>', noremap)
-- Clipboard
vim.keymap.set('v', '<Leader>y', '"+y', noremap)
vim.keymap.set('n', '<Leader>Y', '"+yg_', noremap)
vim.keymap.set('n', '<Leader>y', '"+y', noremap)
vim.keymap.set('n', '<Leader>yy', '"+yy', noremap)
vim.keymap.set('n', '<Leader>p', '"+p', noremap)
vim.keymap.set('n', '<Leader>P', '"+P', noremap)
vim.keymap.set('v', '<Leader>p', '"+p', noremap)
vim.keymap.set('v', '<Leader>P', '"+P', noremap)
-- Telescope
vim.keymap.set('n', '<Leader>ff', require('telescope.builtin').find_files, noremap)
vim.keymap.set("n", "<Leader>fg", require('telescope').extensions.live_grep_args.live_grep_args, noremap)
vim.keymap.set("n", "<Leader>fb", require('telescope.builtin').buffers, noremap)
vim.keymap.set("n", "<Leader>fh", require('telescope.builtin').help_tags, noremap)
vim.keymap.set("n", "<Leader>fp", require('telescope.builtin').pickers, noremap)
vim.keymap.set("n", "<Leader>fr", require('telescope.builtin').resume, noremap)
-- ToggleTerm
vim.keymap.set('n', '<Leader>t', ':ToggleTerm<CR>', noremap)
-- Dap
vim.keymap.set('n', '<Leader>db', require 'dap'.toggle_breakpoint, noremap)
vim.keymap.set('n', '<Leader>dn', require 'dap'.continue, noremap)
vim.keymap.set('n', '<Leader>ds', require 'dap'.step_over, noremap)
vim.keymap.set('n', '<Leader>di', require 'dap'.step_into, noremap)
vim.keymap.set('n', '<Leader>do', require 'dap'.step_out, noremap)
vim.keymap.set('n', '<Leader>lr', '<cmd>LspRestart<CR>', noremapsilent)
vim.keymap.set('n', 'gd', vim.lsp.buf.definition, noremapsilent)
vim.keymap.set('n', 'gD', vim.lsp.buf.declaration, noremapsilent)
vim.keymap.set('n', 'K', vim.lsp.buf.hover, noremapsilent)
vim.keymap.set('n', 'gi', require('telescope.builtin').lsp_implementations, noremapsilent)
vim.keymap.set('n', 'gr', require('telescope.builtin').lsp_references, noremapsilent)
vim.keymap.set('n', '<Leader>ca', vim.lsp.buf.code_action, noremapsilent)
vim.keymap.set('n', '<Leader>fd', '<cmd>lua vim.lsp.buf.formatting()<CR>', noremapsilent)
vim.keymap.set('n', 'rn', '<cmd>lua vim.lsp.buf.rename()<CR>', noremapsilent)
vim.keymap.set('n', '<Leader>e', vim.diagnostic.open_float, noremapsilent)
vim.keymap.set('n', '[d', vim.diagnostic.goto_prev, noremapsilent)
vim.keymap.set('n', ']d', vim.diagnostic.goto_next, noremapsilent)
| mit |
Mutos/StarsOfCall-NAEV | dat/events/start.lua | 1 | 10053 | -- Prepare variables
startupSystem = "Ek'In"
menuTitle = {}
menuComment = {}
menuText = {}
menuOptions = {}
ridiculousMoney = 100000000
-- localization stuff, translators would work here
lang = naev.lang()
if lang == "es" then
else -- default english
-- Character species menu
menuTitle ["Species"] = "Choose Player Character species"
menuComment ["Species"] = "You will first have to choose a species for your character among: \n\n\027bK'Rinns\0270: pacifist arthropoids specialized in AI and trade, \n\n\027bRithai\0270: warlike feline centauroids with a deep sense of honor, \n\n\027bHumans\0270: selfish primates with a crush on technology, \n\n\027bPupeteers\0270: respectful symbiots living on gengineered animals, \n\n\027bSshaads\0270: reptilo-avian anarchs split between multiple factions, \n\n\027bShapeshifters\0270: recent spacegoers, invaded by Sshaad factions."
menuText ["Species"] = "Which species do you want your character to be from? Please select a species from the list below:"
menuOptions ["Species"] = {}
menuOptions ["Species"]["Human"] = "Humans"
menuOptions ["Species"]["K'Rinn"] = "K'Rinns"
menuOptions ["Species"]["Pupeteer"] = "Pupeteers"
menuOptions ["Species"]["Rith"] = "Rithai"
menuOptions ["Species"]["Sshaad"] = "Sshaads"
menuOptions ["Species"]["Shapeshifter"] = "Shapeshifters"
-- Startup location menu
menuTitle ["Start"] = "Choose startup State"
menuComment ["Start"] = "You will then be asked for a starting location from one of the following States: \n\n\027bK'Rinn Council\0270: the K'Rinn major State, extending its dominion over 90% of the k'rinn species, \n\n\027bPlanetarist Alliance\0270: the progressive human State that won the war against the Political Corporations, \n\n\027bCore League\0270: the traditionalist and somewhat militaristic human State that comprises Sol with Earth and Mars."
menuText ["Start"] = "Where do you want to start the game ? Please select a State from the list below:"
menuOptions ["Start"] = {}
menuOptions ["Start"]["Sol"] = "Core League"
menuOptions ["Start"]["Sanctuary"] = "Planetarist Alliance"
menuOptions ["Start"]["Ek'In"] = "K'Rinn Council"
-- Ship type menu
menuTitle ["ShipType"] = "Choose a type of ship to start with"
menuComment ["ShipType"] = "You will now define which ship type you will begin with: \n\n\027bFighter\0270: small ship with weapons but next to no cargo space, \n\n\027bFreighter\0270: a larger ship with some cargo space, armed only in defense, \n\n\027bCourier\0270: a smaller and faster freighter made for quick runs."
menuText ["ShipType"] = "Which type of ship do you want your character to comandeer? Please select a ship type from the list below:"
menuOptions ["ShipType"] = {}
menuOptions ["ShipType"]["Fighter"] = "Fighter"
menuOptions ["ShipType"]["Freighter"] = "Freighter"
menuOptions ["ShipType"]["Courier"] = "Courier"
-- Warning on Alpha menu
menuTitle ["Alpha"] = "Alpha-testing options"
menuComment ["Alpha"] = "\n\nAre you a Lawful Good?\n\nWill you resist temptation?\n\nWarning : next (and last) two options are cheats! \n\nThey are intended for Alpha-testing only!\n\n"
-- Map menu
menuTitle ["Map"] = "Startup map"
menuText ["Map"] = ""
menuOptions ["Map"] = {}
menuOptions ["Map"]["Regular"] = "Regular startup map"
menuOptions ["Map"]["Complete"] = "DEBUG: complete map"
-- Money amount menu
menuTitle ["Money"] = "Startup money"
menuText ["Money"] = ""
menuOptions ["Money"] = {}
menuOptions ["Money"]["Regular"] = "Regular amount of money"
menuOptions ["Money"]["Ridiculous"] = "DEBUG : ridiculously high sum"
end
function name()
local names = {
"Pathfinder",
"Death Trap",
"Little Rascal",
"Gunboat Diplomat",
"Attitude Adjuster",
"Vagabond",
"Sky Cutter",
"Blind Jump",
"Terminal Velocity",
"Eclipse",
"Windjammer",
"Icarus",
"Heart of Lead",
"Exitprise",
"Commuter",
"Serendipity",
"Aluminum Mallard", -- Because we might as well allude to an existing parody. Proper spelling would be "Aluminium", by the way.
"Titanic MLXVII",
"Planet Jumper",
"Outward Bound",
"Shove Off",
"Opportunity",
"Myrmidon",
"Fire Hazard",
"Jord-Maogan",
"Armchair Traveller"
}
return names[rnd.rnd(1,#names)]
end
function create()
-- Ask the player with which species they want to play
tk.msgImg ( menuTitle ["Species"], menuComment ["Species"], "dialogues/startup/001-SpaceGoingSpecies.png" )
_, speciesSelection = tk.choice(menuTitle ["Species"], menuText ["Species"], menuOptions ["Species"]["K'Rinn"], menuOptions ["Species"]["Rith"], menuOptions ["Species"]["Human"], menuOptions ["Species"]["Pupeteer"], menuOptions ["Species"]["Sshaad"], menuOptions ["Species"]["Shapeshifter"])
-- Ask the player in which State they wish to begin the game
tk.msgImg ( menuTitle ["Start"], menuComment ["Start"], "dialogues/startup/002-States.png" )
_, selection = tk.choice(menuTitle ["Start"], menuText ["Start"], menuOptions ["Start"]["Ek'In"], menuOptions ["Start"]["Sanctuary"], menuOptions ["Start"]["Sol"])
-- Ask the player with which ship type they want
tk.msgImg ( menuTitle ["ShipType"], menuComment ["ShipType"], "dialogues/startup/003-Ships.png" )
_, shipType = tk.choice(menuTitle ["ShipType"], menuText ["ShipType"], menuOptions ["ShipType"]["Fighter"], menuOptions ["ShipType"]["Freighter"], menuOptions ["ShipType"]["Courier"])
-- Alpha-test choices: Money and Map
tk.msgImg ( menuTitle ["Alpha"], menuComment ["Alpha"], "dialogues/startup/004-LawfulGood.png" )
_, moneyAmount = tk.choice(menuTitle ["Money"], menuText ["Money"], menuOptions ["Money"]["Regular"], menuOptions ["Money"]["Ridiculous"])
_, mapType = tk.choice(menuTitle ["Map"], menuText ["Map"], menuOptions ["Map"]["Regular"], menuOptions ["Map"]["Complete"])
-- Store the player character's species
if (speciesSelection == menuOptions ["Species"]["Human"]) then
var.push ("pc_species", "Human")
elseif (speciesSelection == menuOptions ["Species"]["K'Rinn"]) then
var.push ("pc_species", "K'Rinn")
elseif (speciesSelection == menuOptions ["Species"]["Pupeteer"]) then
var.push ("pc_species", "Pupeteer")
elseif (speciesSelection == menuOptions ["Species"]["Rith"]) then
var.push ("pc_species", "Rith")
elseif (speciesSelection == menuOptions ["Species"]["Shapeshifter"]) then
var.push ("pc_species", "Shapeshifter")
elseif (speciesSelection == menuOptions ["Species"]["Sshaad"]) then
var.push ("pc_species", "Sshaad")
end
-- DEBUG : display the resulting results
-- tk.msg( "Selections", "Species: " .. var.peek("pc_species") .. " ; Ship type: " .. shipType .. " ; Money: " .. moneyAmount )
-- Select the starting faction and system
if (selection == menuOptions ["Start"]["Sol"]) then
stellarSystem = "Sol"
faction.get("Core League"):modPlayer( 25 )
elseif (selection == menuOptions ["Start"]["Sanctuary"]) then
stellarSystem = "Sanctuary"
faction.get("Alliance"):modPlayer( 25 )
elseif (selection == menuOptions ["Start"]["Ek'In"]) then
stellarSystem = "Ek'In"
faction.get("K'Rinn Council"):modPlayer( 25 )
end
-- Set the default startup system unknown
system.get( startupSystem ):setKnown( false )
-- Drop the pilot in the chosen stellar system
player.teleport(stellarSystem)
system.get(stellarSystem):setKnown(true, true)
-- Assign a random name to the player's ship.
player.pilot():rename( name() )
-- Assign a ship of the chosen ship type, in default configuration
-- Standard core systems,
-- Standard loadout modified from the species,
-- We reload weapons by hand to configure weapons groups,
-- No utilities installed.
if (shipType == menuOptions ["ShipType"]["Fighter"]) then
-- Fighter : small, fast and armed, but near to no cargo space
player.swapShip("Nelk'Tan", "Nelk'Tan", "Earth", true, true)
player.pilot():rmOutfit("all")
if (speciesSelection == menuOptions ["Species"]["K'Rinn"]) then
player.pilot():addOutfit("Fighter Ion Cannon", 4)
else
player.pilot():addOutfit("Fighter Laser Cannon", 4)
end
elseif (shipType == menuOptions ["ShipType"]["Freighter"]) then
-- Freighter : good cargo space and fair flak defense, but slow and high fuel consumption
if (var.peek("pc_species") == "Pupeteer") then
player.swapShip("Travellers' Breath", "Travellers' Breath", "Earth", true, true)
else
player.swapShip("Caravelle", "Caravelle", "Earth", true, true)
end
player.pilot():rmOutfit("all")
if (speciesSelection == menuOptions ["Species"]["K'Rinn"]) then
player.pilot():addOutfit("Small Ion Flak Turret", 2)
else
player.pilot():addOutfit("Small Flak Turret", 2)
end
elseif (shipType == menuOptions ["ShipType"]["Courier"]) then
-- Courier : fast cargo with less flak and less cargo, but more speed
player.swapShip("Alaith", "Alaith", "Earth", true, true)
player.pilot():rmOutfit("all")
if (speciesSelection == menuOptions ["Species"]["K'Rinn"]) then
player.pilot():addOutfit("Small Ion Flak Turret", 1)
else
player.pilot():addOutfit("Small Flak Turret", 1)
end
end
player.pilot():addOutfit("Small Fuel Tank", 1)
-- Give the player a ridiculous amount of money if they choose so
if (moneyAmount == menuOptions ["Money"]["Ridiculous"]) then
player.pay(ridiculousMoney-player.credits())
end
-- Add the prices on maps
player.addOutfit( "Prices Info" )
-- Add map of the startup State
if (mapType == menuOptions ["Map"]["Complete"]) then
player.addOutfit( "All Systems Map" )
else
if (stellarSystem == "Sol") then
player.addOutfit( "Main Routes - Core League" )
elseif (stellarSystem == "Sanctuary") then
player.addOutfit( "Main Routes - Planetarist Alliance" )
elseif (stellarSystem == "Ek'In") then
player.addOutfit( "Main Routes - K'Rinn Council" )
end
end
-- Terminate the event
evt.finish( true )
end
| gpl-3.0 |
Sannis/tarantool | test/box/fiber.test.lua | 6 | 8503 | fiber = require('fiber')
space = box.schema.space.create('tweedledum')
index = space:create_index('primary', { type = 'hash' })
-- A test case for a race condition between ev_schedule
-- and wal_schedule fiber schedulers.
-- The same fiber should not be scheduled by ev_schedule (e.g.
-- due to cancellation) if it is within th wal_schedule queue.
-- The test case is dependent on rows_per_wal, since this is when
-- we reopen the .xlog file and thus wal_scheduler takes a long
-- pause
box.cfg.rows_per_wal
space:insert{1, 'testing', 'lua rocks'}
space:delete{1}
space:insert{1, 'testing', 'lua rocks'}
space:delete{1}
space:insert{1, 'test box delete'}
space:delete{1}
space:insert{1, 'test box delete'}
space:delete{1}
space:insert{1684234849, 'test box delete'}
space:delete{1684234849}
space:insert{1684234849, 'test box delete'}
space:delete{1684234849}
space:insert{1684234849, 'test box.select()'}
space:replace{1684234849, 'hello', 'world'}
space:replace{1667655012, 'goodbye', 'universe'}
space:replace{1667655012, 'goodbye', 'universe'}
space:replace{1667655012, 'goodbye', 'universe'}
space:replace{1667655012, 'goodbye', 'universe'}
space:replace{1667655012, 'goodbye', 'universe'}
space:replace{1667655012, 'goodbye', 'universe'}
space:replace{1667655012, 'goodbye', 'universe'}
space:replace{1667655012, 'goodbye', 'universe'}
space:replace{1667655012, 'goodbye', 'universe'}
space:replace{1667655012, 'goodbye', 'universe'}
space:replace{1667655012, 'goodbye', 'universe'}
space:replace{1667655012, 'goodbye', 'universe'}
space:replace{1684234849}
space:delete{1684234849}
space:delete{1667655012}
space:insert{1953719668, 'old', 1684234849}
-- test that insert produces a duplicate key error
space:insert{1953719668, 'old', 1684234849}
space:update(1953719668, {{'=', 1, 1953719668}, {'=', 2, 'new'}})
space:update(1234567890, {{'+', 3, 1}})
space:update(1953719668, {{'+', 3, 1}})
space:update(1953719668, {{'-', 3, 1}})
space:update(1953719668, {{'-', 3, 1}})
space:update(1953719668, {{'+', 3, 1}})
space:delete{1953719668}
-- must be read-only
space:insert{1953719668}
space:insert{1684234849}
space:delete{1953719668}
space:delete{1684234849}
space:insert{1953719668, 'hello world'}
space:update(1953719668, {{'=', 2, 'bye, world'}})
space:delete{1953719668}
-- test tuple iterators
t = space:insert{1953719668}
t = space:replace{1953719668, 'another field'}
t = space:replace{1953719668, 'another field', 'one more'}
space:truncate()
-- test passing arguments in and out created fiber
--# setopt delimiter ';'
function y()
space = box.space['tweedledum']
while true do
space:replace{1953719668, os.time()}
fiber.sleep(0.001)
end
end;
f = fiber.create(y);
fiber.sleep(0.002);
fiber.cancel(f);
-- fiber garbage collection
n = 1000;
ch = fiber.channel(n);
for k = 1, n, 1 do
fiber.create(
function()
fiber.sleep(0)
ch:put(k)
end
)
end;
for k = 1, n, 1 do
ch:get()
end;
--# setopt delimiter ''
collectgarbage('collect')
-- check that these newly created fibers are garbage collected
fiber.find(900)
fiber.find(910)
fiber.find(920)
fiber.find()
fiber.find('test')
-- https://github.com/tarantool/tarantool/issues/131
-- fiber.resume(fiber.cancel()) -- hang
f = fiber.create(function() fiber.cancel(fiber.self()) end)
f = nil
-- https://github.com/tarantool/tarantool/issues/119
ftest = function() fiber.sleep(0.0001 * math.random() ) return true end
--# setopt delimiter ';'
result = 0;
for i = 1, 10 do
local res = {}
for j = 1, 300 do
fiber.create(function() table.insert(res, ftest()) end)
end
while #res < 300 do fiber.sleep(0) end
result = result + #res
end;
--# setopt delimiter ''
result
--
--
-- Test fiber.create()
--
-- This should try to infinitely create fibers,
-- but hit the fiber stack size limit and fail
-- with an error.
f = function() fiber.create(f) end
f()
--
-- Test argument passing
--
f = function(a, b) fiber.create(function(arg) result = arg end, a..b) end
f('hello ', 'world')
result
f('bye ', 'world')
result
--
-- Test that the created fiber is detached
--
local f = fiber.create(function() result = fiber.status() end)
result
-- A test case for Bug#933487
-- tarantool crashed during shutdown if non running LUA fiber
-- was created
f = fiber.create(function () fiber.sleep(1) return true end)
box.snapshot()
box.snapshot()
box.snapshot()
f = fiber.create(function () fiber.sleep(1) end)
-- Test fiber.sleep()
fiber.sleep(0)
fiber.sleep(0.01)
fiber.sleep(0.0001)
fiber.sleep('hello')
fiber.sleep(box, 0.001)
-- test fiber.self()
f = fiber.self()
old_id = f:id()
fiber.self():id() - old_id < 3
fiber.self():id() - old_id < 5
g = fiber.self()
f==g
-- arguments to fiber.create
f = fiber.create(print('hello'))
-- test passing arguments in and out created fiber
res = {}
function r(a, b) res = { a, b } end
f=fiber.create(r)
while f:status() == 'running' do fiber.sleep(0) end
res
f=fiber.create(r, 'hello')
while f:status() == 'running' do fiber.sleep(0) end
res
f=fiber.create(r, 'hello, world')
while f:status() == 'running' do fiber.sleep(0) end
res
f=fiber.create(r, 'hello', 'world', 'wide')
while f:status() == 'running' do fiber.sleep(0) end
res
-- test fiber.status functions: invalid arguments
fiber.status(1)
fiber.status('fafa-gaga')
fiber.status(nil)
-- test fiber.cancel
function r() fiber.sleep(1000) end
f = fiber.create(r)
fiber.cancel(f)
f:status()
-- Test fiber.name()
old_name = fiber.name()
fiber.name() == old_name
fiber.self():name() == old_name
fiber.name('hello fiber')
fiber.name()
fiber.self():name('bye fiber')
fiber.self():name()
fiber.self():name(old_name)
space:drop()
-- box.fiber test (create, resume, yield, status)
dofile("fiber.lua")
-- print run fiber's test
box_fiber_run_test()
-- various...
function testfun() while true do fiber.sleep(10) end end
f = fiber.create(testfun)
f:cancel()
fib_id = fiber.create(testfun):id()
fiber.find(fib_id):cancel()
fiber.find(fib_id)
--
-- Test local storage
--
type(fiber.self().storage)
fiber.self().storage.key = 48
fiber.self().storage.key
--# setopt delimiter ';'
function testfun(ch)
while fiber.self().storage.key == nil do
print('wait')
fiber.sleep(0)
end
ch:put(fiber.self().storage.key)
end;
--# setopt delimiter ''
ch = fiber.channel(1)
f = fiber.create(testfun, ch)
f.storage.key = 'some value'
ch:get()
ch:close()
ch = nil
fiber.self().storage.key -- our local storage is not affected by f
-- attempt to access local storage of dead fiber raises error
pcall(function(f) return f.storage end, f)
--
-- Test that local storage is garbage collected when fiber is died
--
ffi = require('ffi')
ch = fiber.channel(1)
--# setopt delimiter ';'
function testfun()
fiber.self().storage.x = ffi.gc(ffi.new('char[1]'),
function() ch:put('gc ok') end)
end;
--# setopt delimiter ''
f = fiber.create(testfun)
collectgarbage('collect')
ch:get()
ch:close()
ch = nil
--
-- Test that local storage is not garbage collected with fiber object
--
--# setopt delimiter ';'
function testfun(ch)
fiber.self().storage.x = 'ok'
collectgarbage('collect')
ch:put(fiber.self().storage.x or 'failed')
end;
--# setopt delimiter ''
ch = fiber.channel(1)
fiber.create(testfun, ch):status()
ch:get()
ch:close()
ch = nil
-- # gh-125 box.fiber.cancel() by numeric id
--
function y() while true do fiber.sleep(0.001) end end
f = fiber.create(y)
fiber.kill(f:id())
while f:status() ~= 'dead' do fiber.sleep(0.01) end
-- # gh-420 fiber.cancel() assertion `!(f->flags & (1 << 2))' failed
--
done = false
--# setopt delimiter ';'
function test()
fiber.name('gh-420')
local fun, errmsg = loadstring('fiber.cancel(fiber.self())')
xpcall(fun, function() end)
xpcall(fun, function() end)
done = true
fun()
end;
--# setopt delimiter ''
f = fiber.create(test)
done
-- # gh-536: fiber.info() doesn't list fibers with default names
--
function loop() while true do fiber.sleep(10) end end
f1 = fiber.create(loop)
f2 = fiber.create(loop)
f3 = fiber.create(loop)
info = fiber.info()
info[f1:id()] ~= nil
info[f2:id()] ~= nil
info[f3:id()] ~= nil
f1:cancel()
f2:cancel()
f3:cancel()
-- # gh-666: nulls in output
--
getmetatable(fiber.info())
zombie = false
for fid, i in pairs(fiber.info()) do if i.name == 'zombie' then zombie = true end end
zombie
-- test case for gh-778 - fiber.id() on a dead fiber
f = fiber.create(function() end)
id = f:id()
fiber.sleep(0)
f:status()
id == f:id()
fiber = nil
| bsd-2-clause |
PichotM/DarkRP | gamemode/modules/afk/sv_interface.lua | 6 | 2208 | DarkRP.hookStub{
name = "playerAFKDemoted",
description = "When a player is demoted for being AFK.",
parameters = {
{
name = "ply",
description = "The player being demoted.",
type = "Player"
}
},
returns = {
{
name = "shouldDemote",
description = "Prevent the player from being actually demoted.",
type = "boolean"
},
{
name = "team",
description = "The team the player is to be demoted to (shouldDemote must be true.)",
type = "number"
},
{
name = "suppressMessage",
description = "Suppress the demote message.",
type = "boolean"
},
{
name = "demoteMessage",
description = "Replacement of the demote message text.",
type = "string"
}
}
}
DarkRP.hookStub{
name = "playerSetAFK",
description = "When a player is set to AFK or returns from AFK.",
parameters = {
{
name = "ply",
description = "The player.",
type = "Player"
},
{
name = "afk",
description = "True when the player starts being AFK, false when the player stops being AFK.",
type = "boolean"
}
},
returns = {
}
}
DarkRP.hookStub{
name = "canGoAFK",
description = "When a player can MANUALLY start being AFK by entering the chat command. Note: this hook does NOT get called when a player is set to AFK automatically! That hook will not be added, because I don't want asshole server owners to make AFK rules not apply to admins.",
parameters = {
{
name = "ply",
description = "The player.",
type = "Player"
},
{
name = "afk",
description = "True when the player starts being AFK, false when the player stops being AFK.",
type = "boolean"
}
},
returns = {
{
name = "canGoAFK",
description = "Whether the player is allowed to go AFK",
type = "boolean"
}
}
}
| mit |
wesnoth/wesnoth | data/campaigns/World_Conquest/lua/map/postgeneration/6B_Maritime.lua | 7 | 10147 | -- Maritime
local images = {
dock_ship = "misc/blank-hex.png~BLIT(units/transport/boat.png~CROP(0,15,72,57))",
dock_ship_2 = "misc/blank-hex.png~BLIT(units/transport/boat.png~FL()~CROP(0,15,72,57))"
}
function get_possible_maritime_bridge()
return {
{
type = "Bsb|",
locs = map:find(f.all(
f.terrain("Ww"),
f.adjacent(f.terrain("Chw"), "s,n", nil),
f.adjacent(f.terrain("Ch,Kh"), "s,n", nil),
f.adjacent(f.terrain("*^B*"), nil, 0)
))
},
{
type = "Bsb\\",
locs = map:find(f.all(
f.terrain("Ww"),
f.adjacent(f.terrain("Chw"), "se,nw", nil),
f.adjacent(f.terrain("Ch,Kh"), "se,nw", nil),
f.adjacent(f.terrain("*^B*"), nil, 0)
))
},
{
type = "Bsb/",
locs = map:find(f.all(
f.terrain("Ww"),
f.adjacent(f.terrain("Chw"), "sw,ne", nil),
f.adjacent(f.terrain("Ch,Kh"), "sw,ne", nil),
f.adjacent(f.terrain("*^B*"), nil, 0)
))
}
}
end
function wct_maritime_bridges()
local pb = get_possible_maritime_bridge()
while #pb[1].locs > 0 or #pb[2].locs > 0 or #pb[3].locs > 0 do
pb = functional.filter(pb, function(t) return #t.locs >0 end)
local sel = pb[mathx.random(#pb)]
local loc = sel.locs[mathx.random(#sel.locs)]
map[loc] = "Ww^" .. sel.type
pb = get_possible_maritime_bridge()
end
end
function roads_to_dock(radius)
wct_iterate_roads_to_ex {
terrain_road = "Rp",
f_validpath = f.terrain("!,W*^*"),
f_src = f.terrain("Iwr^Vl"),
f_dest = f.terrain("Ch*,Kh*^*,Re"),
radius = radius
}
--old implementation: wct_iterate_roads_to(wct_roads_to_dock, 3, "Rp")
end
function wct_roads_to_dock(radius)
return map:find(f.all(
f.terrain("!,W*^*"),
f.adjacent(f.all(
f.terrain("Iwr^Vl,Rp"),
f.adjacent(f.all(
f.terrain("Rp"),
f.radius(radius, f.terrain("Ch*,Kh*^*,Re"), f.terrain("!,W*^*"))
), nil, 0),
f.none(
f.radius(radius, f.terrain("Ch*,Kh*^*,Re"), f.terrain("!,W*^*"))
)
)),
f.radius(radius, f.terrain("Ch*,Kh*^*,Re"), f.terrain("!,W*^*"))
))
end
function roads_to_river(radius)
wct_iterate_roads_to_ex {
terrain_road = "Rp",
f_validpath = f.terrain("!,W*^*"),
f_src = f.terrain("*^Vhc"),
f_dest = f.terrain("Ch*,Kh*^*,Re"),
radius = radius
}
--old implementation: wct_iterate_roads_to(wct_roads_to_river, 3, "Rp")
end
-- todo: the old code used
-- `wct_iterate_roads_to(wct_roads_to_river, 3, "Rp")`
-- but the new code uses roads_to_river(4) i guess
-- wct_iterate_roads_to_ex defeind radiosu differently thatn
-- wct_iterate_roads_to ?
-- anyway leavong this function in as a sekeltong on how
-- wct_iterate_roads_to worked. in particular if we want to convert the remaining cases to
-- wct_iterate_roads_to_ex
function wct_roads_to_river(radius)
local f_valid_path_tiles = f.terrain("!,W*^*")
local f_dest = f.terrain("Ch*,Kh*^*,Re")
local f_src = f.terrain("*^Vhc")
local f_path_taken = f.terrain("Rp")
return map:find(f.all(
f_valid_path_tiles,
-- adjacent to open ends or startign points.
f.adjacent(f.all(
-- tiles in your source or tiles that we alrady started building a road on.
f.any(f_src, f_path_taken),
-- exculde road tiles that are not open ends.
f.adjacent(f.all(
f_path_taken,
f.radius(radius, f_dest, f_valid_path_tiles)
), nil, 0),
-- exculde open ends tha are alreaqdy close enough to the target for this building step.
f.none(
f.radius(radius, f_dest, f_valid_path_tiles)
)
)),
-- tiles where we can actually get coloser to the target-
f.radius(radius, f_dest, f_valid_path_tiles)
))
end
function world_conquest_tek_map_decoration_6b()
-- rich terrain around rivers
set_terrain { "*^Vhc",
f.all(
f.terrain("H*^V*"),
f.adjacent(f.terrain("Ww"))
),
layer = "overlay",
}
set_terrain { "Rp^Vhc",
f.all(
f.terrain("G*^V*"),
f.adjacent(f.terrain("Ww"))
),
}
set_terrain { "Gg",
f.all(
f.terrain("G*^*"),
f.adjacent(f.terrain("Ww"))
),
layer = "base",
}
set_terrain { "Gg",
f.all(
f.terrain("Gs^*,Gd^*"),
f.radius(2, f.terrain("Ww"))
),
fraction = 3,
layer = "base",
}
set_terrain { "Gg",
f.all(
f.terrain("Gs^*,Gd^*"),
f.radius(3, f.terrain("Ww"))
),
fraction = 3,
layer = "base",
}
set_terrain { "Gs^*",
--set_terrain { "Gs*^*",
f.all(
f.terrain("Gd*^*"),
f.radius(3, f.terrain("Ww"))
),
layer = "base",
}
-- generate big docks villages
set_terrain { "Iwr^Vl",
f.all(
f.adjacent(f.terrain("W*^*"), nil, "1-5"),
f.adjacent(f.terrain("Wog,Wwg")),
f.terrain("*^V*"),
f.radius(4, f.terrain("Ch,Kh*^*"))
),
}
roads_to_dock(4)
roads_to_river(4)
if #map:find(f.terrain("Iwr^Vl")) == 0 then
local locs = map:find(f.all(
f.terrain("*^V*"),
f.adjacent(f.terrain("W*^*"), nil, "2-5"),
f.adjacent(f.terrain("Wog,Wwg"))
))
loc = locs[mathx.random(#locs)];
map[loc] = "Iwr^Vl"
end
set_terrain { "Wwg,Iwr,Wwg^Bw\\,Wwg^Bw\\,Wwg^Bw\\,Wwg^Bw\\",
f.all(
f.terrain("Wog,Wwg"),
f.adjacent(f.terrain("Wog,Wwg"), "se,nw", nil),
f.adjacent(f.terrain("Iwr^Vl"), "se,nw", nil)
),
}
set_terrain { "Wwg,Iwr,Wwg^Bw/,Wwg^Bw/,Wwg^Bw/,Wwg^Bw/",
f.all(
f.terrain("Wog,Wwg"),
f.adjacent(f.terrain("Wog,Wwg"), "sw,ne", nil),
f.adjacent(f.terrain("Iwr^Vl"), "sw,ne", nil)
),
}
set_terrain { "Wwg,Iwr,Wwg^Bw|,Wwg^Bw|,Wwg^Bw|,Wwg^Bw|",
f.all(
f.terrain("Wog,Wwg"),
f.adjacent(f.terrain("Wog,Wwg"), "s,n", nil),
f.adjacent(f.terrain("Iwr^Vl"), "s,n", nil)
),
}
set_terrain { "Wwg,Wwg^Bw\\",
f.all(
f.terrain("Wog,Wwg"),
f.adjacent(f.terrain("Wog,Wwg"), "se,nw", nil),
f.adjacent(f.terrain("Iwr"), "se,nw", nil)
),
}
set_terrain { "Wwg,Wwg^Bw/",
f.all(
f.terrain("Wog,Wwg"),
f.adjacent(f.terrain("Wog,Wwg"), "sw,ne", nil),
f.adjacent(f.terrain("Iwr"), "sw,ne", nil)
),
}
set_terrain { "Wwg,Wwg^Bw|",
f.all(
f.terrain("Wog,Wwg"),
f.adjacent(f.terrain("Wog,Wwg"), "s,n", nil),
f.adjacent(f.terrain("Iwr"), "s,n", nil)
),
}
local locs = map:find(f.terrain("Iwr"))
for ship_i, ship_loc in ipairs(locs) do
if mathx.random(2) == 1 then
table.insert(prestart_event, wml.tag.item {
x = ship_loc[1],
y = ship_loc[2],
image = images.dock_ship,
name = "wc2_dock_ship",
})
else
table.insert(prestart_event, wml.tag.item {
x = ship_loc[1],
y = ship_loc[2],
image = images.dock_ship_2,
name = "wc2_dock_ship",
})
end
end
set_terrain { "Ds^Edt",
f.all(
f.terrain("Ds"),
f.adjacent(f.terrain("Iwr"))
),
}
set_terrain { "Ds^Edt,Ds",
f.all(
f.terrain("Ds"),
f.adjacent(f.terrain("Iwr"))
),
}
set_terrain { "Ds^Edt",
f.all(
f.terrain("W*"),
f.adjacent(f.terrain("Iwr")),
f.adjacent(f.terrain("W*^*"), nil, 0)
),
}
-- some villages tweaks
set_terrain { "*^Vd",
f.terrain("M*^V*"),
fraction = 2,
layer = "overlay",
}
set_terrain { "*^Vo",
f.terrain("H*^Vhh"),
fraction = 2,
layer = "overlay",
}
set_terrain { "*^Ve",
f.all(
f.terrain("G*^Vh"),
f.adjacent(f.terrain("G*^F*"))
),
layer = "overlay",
}
set_terrain { "*^Vht",
f.all(
f.terrain("G*^Vh"),
f.adjacent(f.terrain("R*^*,C*^*,K*^*"), nil, 0),
f.adjacent(f.terrain("Ss"), nil, "2-6")
),
layer = "overlay",
}
-- fix badlooking dunes
set_terrain { "Hhd",
f.all(
f.terrain("Hd"),
f.adjacent(f.terrain("D*^*,Rd^*"), nil, 0)
),
}
-- expnad dock road
set_terrain { "Rp",
f.all(
f.terrain("G*,Ds"),
f.adjacent(f.terrain("*^Vl"))
),
}
-- contruction dirt near beach roads
set_terrain { "Hd,Ds^Dr",
f.all(
f.terrain("Ds"),
f.adjacent(f.terrain("W*^*,G*^*,S*^*"), nil, 0),
f.adjacent(f.terrain("Rp"))
),
}
-- rebuild some swamps far from rivers
set_terrain { "Gs,Ds,Ds",
f.all(
f.terrain("Ss"),
f.none(
f.radius(6, f.terrain("Ww,Wwf"))
)
),
fraction = 8,
}
set_terrain { "Gs^Fp,Hh^Fp,Hh,Mm,Gs^Fp,Ss^Tf,Ss^Tf,Ss^Tf",
f.all(
f.terrain("Ss"),
f.none(
f.radius(6, f.terrain("Ww,Wwf"))
)
),
fraction = 8,
}
-- some mushrooms on hills near river or caves
set_terrain { "Hh^Tf",
f.all(
f.terrain("Hh,Hh^F*"),
f.radius(5, f.terrain("Ww,Wwf,U*^*"))
),
fraction = 14,
}
-- reefs
set_terrain { "Wwrg",
f.all(
f.terrain("Wog"),
f.adjacent(f.terrain("Wwg")),
f.none(
f.radius(7, f.terrain("*^Vl"))
)
),
fraction = 6,
}
-- chance of expand rivers into sea
local r = tonumber(mathx.random_choice("0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3"))
for i = 1 , r do
local terrain_to_change = map:find(f.all(
f.terrain("Wog,Wwg,Wwrg"),
f.adjacent(f.terrain("Ww,Wwf,Wo"))
))
set_terrain { "Ww",
f.terrain("Wwg"),
locs = terrain_to_change
}
set_terrain { "Wo",
f.terrain("Wog"),
locs = terrain_to_change
}
set_terrain { "Wwr",
f.terrain("Wwrg"),
locs = terrain_to_change
}
end
wct_map_reduce_castle_expanding_recruit("Chw", "Wwf")
-- soft castle towards river defense
set_terrain { "Chw",
f.all(
f.terrain("Ww"),
f.adjacent(f.terrain("C*,K*"), nil, 0),
f.adjacent(f.terrain("W*^*"), nil, "2-6"),
f.adjacent(f.all(
f.terrain("Ww"),
f.adjacent(f.terrain("Ch,Kh"))
))
),
exact = false,
percentage = 83,
}
wct_maritime_bridges()
end
function world_conquest_tek_map_repaint_6b()
wct_reduce_wall_clusters("Uu,Uu^Tf,Uh,Uu^Tf,Uu,Uu^Tf,Uh,Ql,Qxu,Xu,Uu,Ur")
wct_fill_lava_chasms()
wct_volcanos()
world_conquest_tek_map_decoration_6b()
wct_volcanos_dirt()
-- volcanos dry mountains
set_terrain { "Md",
f.all(
f.terrain("Mm^*"),
f.radius(2, f.terrain("Mv"))
),
layer = "base",
}
-- lava dry mountains
set_terrain { "Md",
f.all(
f.terrain("Mm*^*"),
f.radius(1, f.terrain("Ql"))
),
layer = "base",
}
-- dirt beachs far from docks
set_terrain { "Ds^Esd",
f.all(
f.terrain("Ds"),
f.adjacent(f.terrain("Wwg,Wog")),
f.none(
f.radius(6, f.terrain("*^Vl"))
)
),
fraction = 10,
}
wct_map_cave_path_to("Rb")
wct_noise_snow_to("Rb")
end
local _ = wesnoth.textdomain 'wesnoth-wc'
return function()
set_map_name(_"Maritime")
wct_enemy_castle_expansion()
world_conquest_tek_map_noise_maritime()
world_conquest_tek_map_repaint_6b()
end
| gpl-2.0 |
Whit3Tig3R/bestspammbot2 | plugins/rss.lua | 700 | 5434 | local function get_base_redis(id, option, extra)
local ex = ''
if option ~= nil then
ex = ex .. ':' .. option
if extra ~= nil then
ex = ex .. ':' .. extra
end
end
return 'rss:' .. id .. ex
end
local function prot_url(url)
local url, h = string.gsub(url, "http://", "")
local url, hs = string.gsub(url, "https://", "")
local protocol = "http"
if hs == 1 then
protocol = "https"
end
return url, protocol
end
local function get_rss(url, prot)
local res, code = nil, 0
if prot == "http" then
res, code = http.request(url)
elseif prot == "https" then
res, code = https.request(url)
end
if code ~= 200 then
return nil, "Error while doing the petition to " .. url
end
local parsed = feedparser.parse(res)
if parsed == nil then
return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?"
end
return parsed, nil
end
local function get_new_entries(last, nentries)
local entries = {}
for k,v in pairs(nentries) do
if v.id == last then
return entries
else
table.insert(entries, v)
end
end
return entries
end
local function print_subs(id)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
local text = id .. ' are subscribed to:\n---------\n'
for k,v in pairs(subs) do
text = text .. k .. ") " .. v .. '\n'
end
return text
end
local function subscribe(id, url)
local baseurl, protocol = prot_url(url)
local prothash = get_base_redis(baseurl, "protocol")
local lasthash = get_base_redis(baseurl, "last_entry")
local lhash = get_base_redis(baseurl, "subs")
local uhash = get_base_redis(id)
if redis:sismember(uhash, baseurl) then
return "You are already subscribed to " .. url
end
local parsed, err = get_rss(url, protocol)
if err ~= nil then
return err
end
local last_entry = ""
if #parsed.entries > 0 then
last_entry = parsed.entries[1].id
end
local name = parsed.feed.title
redis:set(prothash, protocol)
redis:set(lasthash, last_entry)
redis:sadd(lhash, id)
redis:sadd(uhash, baseurl)
return "You had been subscribed to " .. name
end
local function unsubscribe(id, n)
if #n > 3 then
return "I don't think that you have that many subscriptions."
end
n = tonumber(n)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
if n < 1 or n > #subs then
return "Subscription id out of range!"
end
local sub = subs[n]
local lhash = get_base_redis(sub, "subs")
redis:srem(uhash, sub)
redis:srem(lhash, id)
local left = redis:smembers(lhash)
if #left < 1 then -- no one subscribed, remove it
local prothash = get_base_redis(sub, "protocol")
local lasthash = get_base_redis(sub, "last_entry")
redis:del(prothash)
redis:del(lasthash)
end
return "You had been unsubscribed from " .. sub
end
local function cron()
-- sync every 15 mins?
local keys = redis:keys(get_base_redis("*", "subs"))
for k,v in pairs(keys) do
local base = string.match(v, "rss:(.+):subs") -- Get the URL base
local prot = redis:get(get_base_redis(base, "protocol"))
local last = redis:get(get_base_redis(base, "last_entry"))
local url = prot .. "://" .. base
local parsed, err = get_rss(url, prot)
if err ~= nil then
return
end
local newentr = get_new_entries(last, parsed.entries)
local subscribers = {}
local text = '' -- Send only one message with all updates
for k2, v2 in pairs(newentr) do
local title = v2.title or 'No title'
local link = v2.link or v2.id or 'No Link'
text = text .. "[rss](" .. link .. ") - " .. title .. '\n'
end
if text ~= '' then
local newlast = newentr[1].id
redis:set(get_base_redis(base, "last_entry"), newlast)
for k2, receiver in pairs(redis:smembers(v)) do
send_msg(receiver, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
local id = "user#id" .. msg.from.id
if is_chat_msg(msg) then
id = "chat#id" .. msg.to.id
end
if matches[1] == "!rss"then
return print_subs(id)
end
if matches[1] == "sync" then
if not is_sudo(msg) then
return "Only sudo users can sync the RSS."
end
cron()
end
if matches[1] == "subscribe" or matches[1] == "sub" then
return subscribe(id, matches[2])
end
if matches[1] == "unsubscribe" or matches[1] == "uns" then
return unsubscribe(id, matches[2])
end
end
return {
description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.",
usage = {
"!rss: Get your rss (or chat rss) subscriptions",
"!rss subscribe (url): Subscribe to that url",
"!rss unsubscribe (id): Unsubscribe of that id",
"!rss sync: Download now the updates and send it. Only sudo users can use this option."
},
patterns = {
"^!rss$",
"^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (unsubscribe) (%d+)$",
"^!rss (uns) (%d+)$",
"^!rss (sync)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
amircheshme/megatron | plugins/rss.lua | 700 | 5434 | local function get_base_redis(id, option, extra)
local ex = ''
if option ~= nil then
ex = ex .. ':' .. option
if extra ~= nil then
ex = ex .. ':' .. extra
end
end
return 'rss:' .. id .. ex
end
local function prot_url(url)
local url, h = string.gsub(url, "http://", "")
local url, hs = string.gsub(url, "https://", "")
local protocol = "http"
if hs == 1 then
protocol = "https"
end
return url, protocol
end
local function get_rss(url, prot)
local res, code = nil, 0
if prot == "http" then
res, code = http.request(url)
elseif prot == "https" then
res, code = https.request(url)
end
if code ~= 200 then
return nil, "Error while doing the petition to " .. url
end
local parsed = feedparser.parse(res)
if parsed == nil then
return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?"
end
return parsed, nil
end
local function get_new_entries(last, nentries)
local entries = {}
for k,v in pairs(nentries) do
if v.id == last then
return entries
else
table.insert(entries, v)
end
end
return entries
end
local function print_subs(id)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
local text = id .. ' are subscribed to:\n---------\n'
for k,v in pairs(subs) do
text = text .. k .. ") " .. v .. '\n'
end
return text
end
local function subscribe(id, url)
local baseurl, protocol = prot_url(url)
local prothash = get_base_redis(baseurl, "protocol")
local lasthash = get_base_redis(baseurl, "last_entry")
local lhash = get_base_redis(baseurl, "subs")
local uhash = get_base_redis(id)
if redis:sismember(uhash, baseurl) then
return "You are already subscribed to " .. url
end
local parsed, err = get_rss(url, protocol)
if err ~= nil then
return err
end
local last_entry = ""
if #parsed.entries > 0 then
last_entry = parsed.entries[1].id
end
local name = parsed.feed.title
redis:set(prothash, protocol)
redis:set(lasthash, last_entry)
redis:sadd(lhash, id)
redis:sadd(uhash, baseurl)
return "You had been subscribed to " .. name
end
local function unsubscribe(id, n)
if #n > 3 then
return "I don't think that you have that many subscriptions."
end
n = tonumber(n)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
if n < 1 or n > #subs then
return "Subscription id out of range!"
end
local sub = subs[n]
local lhash = get_base_redis(sub, "subs")
redis:srem(uhash, sub)
redis:srem(lhash, id)
local left = redis:smembers(lhash)
if #left < 1 then -- no one subscribed, remove it
local prothash = get_base_redis(sub, "protocol")
local lasthash = get_base_redis(sub, "last_entry")
redis:del(prothash)
redis:del(lasthash)
end
return "You had been unsubscribed from " .. sub
end
local function cron()
-- sync every 15 mins?
local keys = redis:keys(get_base_redis("*", "subs"))
for k,v in pairs(keys) do
local base = string.match(v, "rss:(.+):subs") -- Get the URL base
local prot = redis:get(get_base_redis(base, "protocol"))
local last = redis:get(get_base_redis(base, "last_entry"))
local url = prot .. "://" .. base
local parsed, err = get_rss(url, prot)
if err ~= nil then
return
end
local newentr = get_new_entries(last, parsed.entries)
local subscribers = {}
local text = '' -- Send only one message with all updates
for k2, v2 in pairs(newentr) do
local title = v2.title or 'No title'
local link = v2.link or v2.id or 'No Link'
text = text .. "[rss](" .. link .. ") - " .. title .. '\n'
end
if text ~= '' then
local newlast = newentr[1].id
redis:set(get_base_redis(base, "last_entry"), newlast)
for k2, receiver in pairs(redis:smembers(v)) do
send_msg(receiver, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
local id = "user#id" .. msg.from.id
if is_chat_msg(msg) then
id = "chat#id" .. msg.to.id
end
if matches[1] == "!rss"then
return print_subs(id)
end
if matches[1] == "sync" then
if not is_sudo(msg) then
return "Only sudo users can sync the RSS."
end
cron()
end
if matches[1] == "subscribe" or matches[1] == "sub" then
return subscribe(id, matches[2])
end
if matches[1] == "unsubscribe" or matches[1] == "uns" then
return unsubscribe(id, matches[2])
end
end
return {
description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.",
usage = {
"!rss: Get your rss (or chat rss) subscriptions",
"!rss subscribe (url): Subscribe to that url",
"!rss unsubscribe (id): Unsubscribe of that id",
"!rss sync: Download now the updates and send it. Only sudo users can use this option."
},
patterns = {
"^!rss$",
"^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (unsubscribe) (%d+)$",
"^!rss (uns) (%d+)$",
"^!rss (sync)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
githubmereza/creed_plug | plugins/welcome.lua | 190 | 3526 | local add_user_cfg = load_from_file('data/add_user_cfg.lua')
local function template_add_user(base, to_username, from_username, chat_name, chat_id)
base = base or ''
to_username = '@' .. (to_username or '')
from_username = '@' .. (from_username or '')
chat_name = string.gsub(chat_name, '_', ' ') or ''
chat_id = "chat#id" .. (chat_id or '')
if to_username == "@" then
to_username = ''
end
if from_username == "@" then
from_username = ''
end
base = string.gsub(base, "{to_username}", to_username)
base = string.gsub(base, "{from_username}", from_username)
base = string.gsub(base, "{chat_name}", chat_name)
base = string.gsub(base, "{chat_id}", chat_id)
return base
end
function chat_new_user_link(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.from.username
local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')'
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
function chat_new_user(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.action.user.username
local from_username = msg.from.username
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
local function description_rules(msg, nama)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
local about = ""
local rules = ""
if data[tostring(msg.to.id)]["description"] then
about = data[tostring(msg.to.id)]["description"]
about = "\nAbout :\n"..about.."\n"
end
if data[tostring(msg.to.id)]["rules"] then
rules = data[tostring(msg.to.id)]["rules"]
rules = "\nRules :\n"..rules.."\n"
end
local sambutan = "Hi "..nama.."\nWelcome to '"..string.gsub(msg.to.print_name, "_", " ").."'\nYou can use /help for see bot commands\n"
local text = sambutan..about..rules.."\n"
local receiver = get_receiver(msg)
send_large_msg(receiver, text, ok_cb, false)
end
end
local function run(msg, matches)
if not msg.service then
return "Are you trying to troll me?"
end
--vardump(msg)
if matches[1] == "chat_add_user" then
if not msg.action.user.username then
nama = string.gsub(msg.action.user.print_name, "_", " ")
else
nama = "@"..msg.action.user.username
end
chat_new_user(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_add_user_link" then
if not msg.from.username then
nama = string.gsub(msg.from.print_name, "_", " ")
else
nama = "@"..msg.from.username
end
chat_new_user_link(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_del_user" then
local bye_name = msg.action.user.first_name
return 'Bye '..bye_name
end
end
return {
description = "Welcoming Message",
usage = "send message to new member",
patterns = {
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
"^!!tgservice (chat_del_user)$",
},
run = run
}
| gpl-2.0 |
Anarchid/Zero-K | LuaRules/Gadgets/unit_jugglenaut_juggle.lua | 5 | 9027 | function gadget:GetInfo()
return {
name = "Old Jugglenaut Juggle",
desc = "Implementes special weapon Juggling for Old Jugglenaut",
author = "Google Frog",
date = "1 April 2011",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = false -- loaded by default?
}
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
if (gadgetHandler:IsSyncedCode()) then -- synced
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local getMovetype = Spring.Utilities.getMovetype
local throwWeaponID = {}
local throwShooterID = {
-- [UnitDefNames["gorg"].id] = true
}
for i=1,#WeaponDefs do
local wd = WeaponDefs[i]
if wd.customParams and wd.customParams.massliftthrow then
throwWeaponID[wd.id] = true
Script.SetWatchExplosion(wd.id, true)
end
end
local moveTypeByID = {}
for i=1,#UnitDefs do
local ud = UnitDefs[i]
moveTypeByID[i] = getMovetype(ud)
end
------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local RISE_TIME = 25
local FLING_TIME = 35
local UPDATE_FREQUENCY = 2
local RISE_HEIGHT = 180
local COLLLECT_RADIUS = 260
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local gorgs = {}
local flying = {}
local flyingByID = {data = {}, count = 0}
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local function distance(x1,y1,z1,x2,y2,z2)
return math.sqrt((x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2)
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local function removeFlying(unitID)
flying[flyingByID.data[flyingByID.count] ].index = flying[unitID].index
flyingByID.data[flying[unitID].index] = flyingByID.data[flyingByID.count]
flyingByID.data[flyingByID.count] = nil
flying[unitID] = nil
flyingByID.count = flyingByID.count - 1
SendToUnsynced("removeFlying", unitID)
end
local function addFlying(unitID, frame, dx, dy, dz, height, parentDis)
if flying[unitID] then
removeFlying(unitID)
end
local unitDefID = Spring.GetUnitDefID(unitID)
local ux, uy, uz = Spring.GetUnitPosition(unitID)
if unitDefID and ux and moveTypeByID[unitDefID] and moveTypeByID[unitDefID] == 2 then
frame = frame or Spring.GetGameFrame()
local dis = distance(ux,uy,uz,dx,dy,dz)
local riseFrame = frame + RISE_TIME + dis*0.2
local flingFrame = frame + FLING_TIME + dis*0.2 + (dis - parentDis > -50 and (dis - parentDis + 50)*0.02 or 0)
local flingDuration = flingFrame - riseFrame
flyingByID.count = flyingByID.count + 1
flyingByID.data[flyingByID.count] = unitID
flying[unitID] = {
index = flyingByID.count,
riseFrame = riseFrame,
flingFrame = flingFrame,
flingDuration = flingDuration,
riseTimer = 3,
dx = dx, dy = dy, dz = dz,
fx = ux, fy = height, fz = uz,
}
SendToUnsynced("addFlying", unitID, unitDefID)
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
function gadget:Explosion(weaponID, px, py, pz, ownerID)
if throwWeaponID[weaponID] and ownerID then
local frame = Spring.GetGameFrame()
local sx,sy,sz = Spring.GetUnitPosition(ownerID)
local gy = Spring.GetGroundHeight(px,pz) + 20
Spring.SpawnCEG("riotballgrav", sx, sy, sz, 0, 1, 0, COLLLECT_RADIUS)
local units = Spring.GetUnitsInSphere(sx, sy, sz, COLLLECT_RADIUS)
local parentDis = distance(sx, sy, sz, px,gy,pz)
for i = 1, #units do
local unitID = units[i]
if unitID ~= ownerID then
local ux, uy, uz = Spring.GetUnitPosition(unitID)
local tx, ty, tz = px + (ux-sx)*0.4, gy + (uy-sy)*0.4, pz + (uz-sz)*0.4
local mag = distance(sx, sy, sz, tx, ty, tz)
tx, ty, tz = (tx-sx)*parentDis/mag + sx, (ty-sy)*parentDis/mag + sy, (tz-sz)*parentDis/mag + sz
addFlying(unitID, frame, tx, ty, tz, sy + RISE_HEIGHT, parentDis)
end
end
end
return false
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
function gadget:GameFrame(f)
if f%UPDATE_FREQUENCY == 0 then
local i = 1
while i <= flyingByID.count do
local unitID = flyingByID.data[i]
if Spring.ValidUnitID(unitID) then
local data = flying[unitID]
local vx, vy, vz = Spring.GetUnitVelocity(unitID)
local ux, uy, uz = Spring.GetUnitPosition(unitID)
if f < data.riseFrame then
Spring.AddUnitImpulse(unitID, -vx*0.02, (data.fy - uy)*0.01*(2-vy), -vz*0.02)
if data.riseTimer then
if data.riseTimer < 0 then
Spring.SetUnitRotation(unitID,math.random()*2-1,math.random()*0.2-0.1,math.random()*2-1)
data.riseTimer = false
else
data.riseTimer = data.riseTimer - 1
end
end
i = i + 1
elseif f < data.flingFrame then
local dis = distance(data.dx,data.dy,data.dz,ux,uy,uz)
local mult = ((data.flingFrame - f)*2/data.flingDuration)^1.8 * 2.5/dis
Spring.AddUnitImpulse(unitID, (data.dx - ux)*mult, (data.dy - uy)*mult, (data.dz - uz)*mult)
i = i + 1
else
removeFlying(unitID)
end
else
removeFlying(unitID)
end
end
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
function gadget:UnitCreated(unitID, unitDefID)
if throwShooterID[unitDefID] then
gorgs[unitID] = true
end
end
function gadget:UnitDestroyed(unitID, unitDefID)
if gorgs[unitID] then
gorgs[unitID] = nil
end
end
function gadget:Initialize()
for _, unitID in ipairs(Spring.GetAllUnits()) do
local unitDefID = Spring.GetUnitDefID(unitID)
local teamID = Spring.GetUnitTeam(unitID)
gadget:UnitCreated(unitID, unitDefID, teamID)
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
else --unsynced
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local Lups
local particleIDs = {}
local flyFX = {
--{class='UnitPieceLight', options={ delay=24, life=math.huge } },
{class='StaticParticles', options={
life = 30,
colormap = { {0.2, 0.1, 1, 0.01} },
texture = 'bitmaps/GPL/groundflash.tga',
sizeMod = 4,
repeatEffect = true,
}
},
--{class='SimpleParticles', options={ --FIXME
-- life = 50,
-- speed = 0.65,
-- colormap = { {0.2, 0.1, 1, 1} },
-- texture = 'bitmaps/PD/chargeparticles.tga',
-- partpos = "0,0,0",
-- count = 15,
-- rotSpeed = 1,
-- rotSpeedSpread = -2,
-- rotSpread = 360,
-- sizeGrowth = -0.05,
-- emitVector = {0,1,0},
-- emitRotSpread = 60,
-- delaySpread = 180,
-- sizeMod = 10,
-- }
--},
{class='ShieldSphere', options={
life = math.huge,
sizeMod = 1.5,
colormap1 = { {0.2, 0.1, 1, 0.4} },
colormap2 = { {0.2, 0.1, 1, 0.08} }
}
}
}
local function addFlying(_, unitID, unitDefID)
particleIDs[unitID] = {}
local teamID = Spring.GetUnitTeam(unitID)
local allyTeamID = Spring.GetUnitAllyTeam(unitID)
local radius = Spring.GetUnitRadius(unitID)
local height = Spring.GetUnitHeight(unitID)
for i,fx in pairs(flyFX) do
fx.options.unit = unitID
fx.options.unitDefID = unitDefID
fx.options.team = teamID
fx.options.allyTeam = allyTeamID
fx.options.size = radius * (fx.options.sizeMod or 1)
fx.options.pos = {0, height/2, 0}
particleIDs[unitID][#particleIDs[unitID] + 1] = Lups.AddParticles(fx.class,fx.options)
end
end
local function removeFlying(_, unitID)
for i=1,#particleIDs[unitID] do
Lups.RemoveParticles(particleIDs[unitID][i])
end
end
function gadget:Initialize()
gadgetHandler:AddSyncAction("addFlying", addFlying)
gadgetHandler:AddSyncAction("removeFlying", removeFlying)
end
function gadget:Update()
if (not Lups) then
Lups = GG['Lups']
end
end
function gadget:Shutdown()
gadgetHandler.RemoveSyncAction("addFlying")
gadgetHandler.RemoveSyncAction("removeFlying")
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
end
| gpl-2.0 |
ivendrov/nn | MM.lua | 46 | 2695 | --[[ Module to perform matrix multiplication on two minibatch inputs,
producing a minibatch.
]]
local MM, parent = torch.class('nn.MM', 'nn.Module')
--[[ The constructor takes two optional arguments, specifying whether or not transpose
any of the input matrices before perfoming the multiplication.
]]
function MM:__init(transA, transB)
parent.__init(self)
self.transA = transA or false
self.transB = transB or false
self.gradInput = {torch.Tensor(), torch.Tensor()}
end
function MM:updateOutput(input)
assert(#input == 2, 'input must be a pair of minibatch matrices')
local a, b = table.unpack(input)
assert(a:nDimension() == 2 or a:nDimension() == 3, 'input tensors must be 2D or 3D')
if a:nDimension() == 2 then
assert(b:nDimension() == 2, 'second input tensor must be 2D')
if self.transA then a = a:t() end
if self.transB then b = b:t() end
assert(a:size(2) == b:size(1), 'matrix sizes do not match')
self.output:resize(a:size(1), b:size(2))
self.output:mm(a, b)
else
assert(b:nDimension() == 3, 'second input tensor must be 3D')
assert(a:size(1) == b:size(1), 'inputs must contain the same number of minibatches')
if self.transA then a = a:transpose(2, 3) end
if self.transB then b = b:transpose(2, 3) end
assert(a:size(3) == b:size(2), 'matrix sizes do not match')
self.output:resize(a:size(1), a:size(2), b:size(3))
self.output:bmm(a, b)
end
return self.output
end
function MM:updateGradInput(input, gradOutput)
assert(#input == 2, 'input must be a pair of tensors')
local a, b = table.unpack(input)
self.gradInput[1]:resizeAs(a)
self.gradInput[2]:resizeAs(b)
assert(gradOutput:nDimension() == 2 or gradOutput:nDimension() == 3, 'arguments must be a 2D or 3D Tensor')
local h_dim, w_dim, f
if gradOutput:nDimension() == 2 then
assert(a:nDimension() == 2, 'first input tensor must be 2D')
assert(b:nDimension() == 2, 'second input tensor must be 2D')
h_dim, w_dim = 1, 2
f = "mm"
else
assert(a:nDimension() == 3, 'first input tensor must be 3D')
assert(b:nDimension() == 3, 'second input tensor must be 3D')
h_dim, w_dim = 2, 3
f = "bmm"
end
if self.transA == self.transB then
a = a:transpose(h_dim, w_dim)
b = b:transpose(h_dim, w_dim)
end
if self.transA then
self.gradInput[1][f](self.gradInput[1], b, gradOutput:transpose(h_dim, w_dim))
else
self.gradInput[1][f](self.gradInput[1], gradOutput, b)
end
if self.transB then
self.gradInput[2][f](self.gradInput[2], gradOutput:transpose(h_dim, w_dim), a)
else
self.gradInput[2][f](self.gradInput[2], a, gradOutput)
end
return self.gradInput
end
| bsd-3-clause |
Anarchid/Zero-K | scripts/factoryjump.lua | 4 | 3028 | include "constants.lua"
local spGetUnitTeam = Spring.GetUnitTeam
--------------------------------------------------------------------------------
-- pieces
--------------------------------------------------------------------------------
local base, center1, center2, side1, side2, pad = piece('base', 'center1', 'center2', 'side1', 'side2', 'pad')
local head1, head2, nano1, nano2, nano3, nano4 = piece('head1', 'head2', 'nano1', 'nano2', 'nano3', 'nano4')
--local vars
local nanoPieces = {nano1, nano2, nano3, nano4}
local nanoIdx = 1
local smokePiece = {base, head1, head2}
local SIG_Open = 1
--opening animation of the factory
local function Open()
Signal(SIG_Open)
SetSignalMask(SIG_Open)
Move(center1, z_axis, 0, 10)
Move(center2, z_axis, 0, 10)
Move(side1, z_axis, 0, 10)
Move(side2, z_axis, 0, 10)
WaitForMove(center1, z_axis)
WaitForMove(center2, z_axis)
--Sleep(500)
-- SetUnitValue(COB.YARD_OPEN, 1) --Tobi said its not necessary
SetUnitValue(COB.BUGGER_OFF, 1)
SetUnitValue(COB.INBUILDSTANCE, 1)
GG.Script.UnstickFactory(unitID)
end
--closing animation of the factory
local function Close()
Signal(SIG_Open) --kill the opening animation if it is in process
SetSignalMask(SIG_Open) --set the signal to kill the closing animation
-- SetUnitValue(COB.YARD_OPEN, 0)
SetUnitValue(COB.BUGGER_OFF, 0)
SetUnitValue(COB.INBUILDSTANCE, 0)
Move(center1, z_axis, 20, 10)
Move(center2, z_axis, 20, 10)
Move(side1, z_axis, 20, 10)
Move(side2, z_axis, 10, 10)
end
function script.Create()
Spring.SetUnitNanoPieces(unitID, nanoPieces)
Move(center1, z_axis, 20)
Move(center2, z_axis, 20)
Move(side1, z_axis, 20)
Move(side2, z_axis, 10)
while (GetUnitValue(COB.BUILD_PERCENT_LEFT) ~= 0) do Sleep(400) end
StartThread(GG.Script.SmokeUnit, unitID, smokePiece)
end
function script.QueryNanoPiece()
if (nanoIdx == 4) then
nanoIdx = 1
else
nanoIdx = nanoIdx + 1
end
local nano = nanoPieces[nanoIdx]
--// send to LUPS
GG.LUPS.QueryNanoPiece(unitID,unitDefID,spGetUnitTeam(unitID),nano)
return nano
end
function script.Activate ()
StartThread(Open) --animation needs its own thread because Sleep and WaitForTurn will not work otherwise
end
function script.Deactivate ()
StartThread(Close)
end
function script.QueryBuildInfo()
return pad
end
--death and wrecks
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage / maxHealth
if (severity <= .25) then
Explode(base, SFX.NONE)
Explode(center1, SFX.NONE)
Explode(center2, SFX.NONE)
Explode(head1, SFX.NONE)
Explode(head2, SFX.NONE)
return 1 -- corpsetype
elseif (severity <= .5) then
Explode(base, SFX.NONE)
Explode(center1, SFX.NONE)
Explode(center2, SFX.NONE)
Explode(head1, SFX.SHATTER)
Explode(head2, SFX.SHATTER)
return 1 -- corpsetype
else
Explode(base, SFX.SHATTER)
Explode(center1, SFX.SHATTER)
Explode(center2, SFX.SHATTER)
Explode(head1, SFX.SMOKE + SFX.FIRE + SFX.EXPLODE)
Explode(head2, SFX.SMOKE + SFX.FIRE + SFX.EXPLODE)
return 2 -- corpsetype
end
end
| gpl-2.0 |
Anarchid/Zero-K | LuaRules/Configs/MetalSpots/BlackStar.lua | 8 | 3040 | return {
spots = {
{x = 4136, z = 7528, metal = 1.5},
{x = 3944, z = 7528, metal = 1.5},
{x = 2360, z = 6568, metal = 1.5},
{x = 1864, z = 1192, metal = 1.5},
{x = 648, z = 5192, metal = 1.5},
{x = 5768, z = 6616, metal = 1.5},
{x = 2200, z = 6600, metal = 1.5},
{x = 856, z = 3256, metal = 1.5},
{x = 7176, z = 3256, metal = 1.5},
{x = 5928, z = 6408, metal = 1.5},
{x = 3848, z = 5320, metal = 1},
{x = 1048, z = 3272, metal = 1.5},
{x = 6888, z = 3384, metal = 1.5},
{x = 4280, z = 1064, metal = 1.5},
{x = 4136, z = 1288, metal = 1.5},
{x = 7016, z = 3480, metal = 1.5},
{x = 5032, z = 3720, metal = 1},
{x = 4312, z = 1224, metal = 1.5},
{x = 6328, z = 1320, metal = 1.5},
{x = 5640, z = 6536, metal = 1.5},
{x = 552, z = 5224, metal = 1.5},
{x = 3576, z = 4920, metal = 1},
{x = 1080, z = 3448, metal = 1.5},
{x = 5432, z = 4200, metal = 1},
{x = 4088, z = 1032, metal = 1.5},
{x = 2344, z = 6392, metal = 1.5},
{x = 3416, z = 4920, metal = 1},
{x = 5704, z = 6360, metal = 1.5},
{x = 3096, z = 3864, metal = 1},
{x = 4760, z = 3016, metal = 1},
{x = 2136, z = 6344, metal = 1.5},
{x = 5240, z = 4648, metal = 1},
{x = 4280, z = 5336, metal = 1},
{x = 2072, z = 6520, metal = 1.5},
{x = 5032, z = 3208, metal = 1},
{x = 7624, z = 5192, metal = 1.5},
{x = 7496, z = 5144, metal = 1.5},
{x = 6968, z = 3208, metal = 1.5},
{x = 2760, z = 4264, metal = 1},
{x = 4520, z = 4872, metal = 1},
{x = 792, z = 3400, metal = 1.5},
{x = 6200, z = 1224, metal = 1.5},
{x = 4008, z = 1192, metal = 1.5},
{x = 3416, z = 4760, metal = 1},
{x = 3576, z = 2760, metal = 1},
{x = 4664, z = 4680, metal = 1},
{x = 7192, z = 3432, metal = 1.5},
{x = 4888, z = 3672, metal = 1},
{x = 4184, z = 3240, metal = 1},
{x = 4680, z = 4888, metal = 1},
{x = 4088, z = 3064, metal = 1},
{x = 904, z = 3496, metal = 1.5},
{x = 5928, z = 6584, metal = 1.5},
{x = 3016, z = 3736, metal = 1},
{x = 3144, z = 3000, metal = 1},
{x = 2840, z = 4520, metal = 1},
{x = 3176, z = 3640, metal = 1},
{x = 1800, z = 1112, metal = 1.5},
{x = 3896, z = 3176, metal = 1},
{x = 4968, z = 3880, metal = 1},
}
}
| gpl-2.0 |
alexandrebarachant/openvibe | applications/demos/motor-imagery/bci-examples/motor-imagery/motor-imagery-bci-graz-stimulator.lua | 4 | 2314 |
function initialize(box)
dofile(box:get_config("${Path_Data}") .. "/plugins/stimulation/lua-stimulator-stim-codes.lua")
number_of_trials = box:get_setting(2)
first_class = _G[box:get_setting(3)]
second_class = _G[box:get_setting(4)]
baseline_duration = box:get_setting(5)
wait_for_beep_duration = box:get_setting(6)
wait_for_cue_duration = box:get_setting(7)
display_cue_duration = box:get_setting(8)
feedback_duration = box:get_setting(9)
end_of_trial_min_duration = box:get_setting(10)
end_of_trial_max_duration = box:get_setting(11)
-- initializes random seed
math.randomseed(os.time())
-- fill the sequence table with predifined order
sequence = {}
for i = 1, number_of_trials do
table.insert(sequence, 1, first_class)
table.insert(sequence, 1, second_class)
end
-- randomize the sequence
for i = 1, number_of_trials do
a = math.random(1, number_of_trials*2)
b = math.random(1, number_of_trials*2)
swap = sequence[a]
sequence[a] = sequence[b]
sequence[b] = swap
end
end
function process(box)
local t=0
-- manages baseline
box:send_stimulation(1, OVTK_StimulationId_ExperimentStart, t, 0)
t = t + 5
box:send_stimulation(1, OVTK_StimulationId_BaselineStart, t, 0)
box:send_stimulation(1, OVTK_StimulationId_Beep, t, 0)
t = t + baseline_duration
box:send_stimulation(1, OVTK_StimulationId_BaselineStop, t, 0)
box:send_stimulation(1, OVTK_StimulationId_Beep, t, 0)
t = t + 5
-- manages trials
for i = 1, number_of_trials*2 do
-- first display cross on screen
box:send_stimulation(1, OVTK_GDF_Start_Of_Trial, t, 0)
box:send_stimulation(1, OVTK_GDF_Cross_On_Screen, t, 0)
t = t + wait_for_beep_duration
-- warn the user the cue is going to appear
box:send_stimulation(1, OVTK_StimulationId_Beep, t, 0)
t = t + wait_for_cue_duration
-- display cue
box:send_stimulation(1, sequence[i], t, 0)
t = t + display_cue_duration
-- provide feedback
box:send_stimulation(1, OVTK_GDF_Feedback_Continuous, t, 0)
t = t + feedback_duration
-- ends trial
box:send_stimulation(1, OVTK_GDF_End_Of_Trial, t, 0)
t = t + math.random(end_of_trial_min_duration, end_of_trial_max_duration)
end
box:send_stimulation(1, OVTK_StimulationId_ExperimentStop, t, 0)
t = t + 5
box:send_stimulation(1, OVTK_StimulationId_Train, t, 0)
end
| agpl-3.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/armsam.lua | 1 | 3345 | return {
armsam = {
acceleration = 0.039599999785423,
airsightdistance = 800,
brakerate = 0.016499999910593,
buildcostenergy = 2027,
buildcostmetal = 140,
buildpic = "ARMSAM.DDS",
buildtime = 2945,
canmove = true,
category = "ALL TANK MOBILE WEAPON NOTSUB NOTSHIP NOTAIR NOTHOVER SURFACE",
corpse = "DEAD",
description = "Missile Truck",
energymake = 0.5,
energyuse = 0.5,
explodeas = "BIG_UNITEX",
footprintx = 3,
footprintz = 3,
idleautoheal = 5,
idletime = 1800,
leavetracks = true,
maxdamage = 700,
maxslope = 16,
maxvelocity = 1.7050000429153,
maxwaterdepth = 12,
movementclass = "TANK3",
name = "Samson",
objectname = "ARMSAM",
seismicsignature = 0,
selfdestructas = "BIG_UNIT",
sightdistance = 620,
trackoffset = -6,
trackstrength = 5,
tracktype = "StdTank",
trackwidth = 32,
turnrate = 497,
featuredefs = {
dead = {
blocking = true,
category = "corpses",
collisionvolumeoffsets = "1.01370239258 -1.0546875e-05 -0.0623321533203",
collisionvolumescales = "34.0520019531 26.7133789063 42.7676696777",
collisionvolumetype = "Box",
damage = 639,
description = "Samson Wreckage",
energy = 0,
featuredead = "HEAP",
featurereclamate = "SMUDGE01",
footprintx = 3,
footprintz = 3,
height = 20,
hitdensity = 100,
metal = 123,
object = "ARMSAM_DEAD",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
heap = {
blocking = false,
category = "heaps",
damage = 320,
description = "Samson Heap",
energy = 0,
featurereclamate = "SMUDGE01",
footprintx = 3,
footprintz = 3,
height = 4,
hitdensity = 100,
metal = 49,
object = "3X3D",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
},
sfxtypes = {
explosiongenerators = {
[1] = "custom:rocketflare",
},
},
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "varmmove",
},
select = {
[1] = "varmsel",
},
},
weapondefs = {
armtruck_missile = {
areaofeffect = 48,
burst = 2,
burstrate = 0.25,
craterboost = 0,
cratermult = 0,
explosiongenerator = "custom:FLASH2",
firestarter = 70,
flighttime = 3.5,
impulseboost = 0.12300000339746,
impulsefactor = 0.12300000339746,
metalpershot = 0,
model = "missile",
name = "Missiles",
noselfdamage = true,
range = 600,
reloadtime = 3.3399999141693,
smoketrail = true,
soundhit = "xplomed2",
soundstart = "rockhvy2",
soundtrigger = true,
startvelocity = 450,
texture2 = "armsmoketrail",
tolerance = 8000,
tracks = true,
turnrate = 63000,
turret = true,
weaponacceleration = 108,
weapontimer = 5,
weapontype = "MissileLauncher",
weaponvelocity = 540,
damage = {
bombers = 80,
default = 38,
fighters = 80,
subs = 5,
vtol = 80,
},
},
},
weapons = {
[1] = {
badtargetcategory = "NOTAIR",
def = "ARMTRUCK_MISSILE",
onlytargetcategory = "NOTSUB",
},
},
},
}
| gpl-2.0 |
Anarchid/Zero-K | LuaUI/Configs/unit_state_defaults.lua | 6 | 1493 | local alwaysHoldPos = {
[UnitDefNames["spidercrabe"].id] = true,
[UnitDefNames["vehsupport"].id] = true,
[UnitDefNames["tankheavyarty"].id] = true,
}
local holdPosException = {
[UnitDefNames["staticcon"].id] = true,
}
local dontFireAtRadarUnits = {
[UnitDefNames["cloaksnipe"].id] = true,
[UnitDefNames["hoverarty"].id] = true,
[UnitDefNames["turretantiheavy"].id] = true,
[UnitDefNames["vehheavyarty"].id] = true,
[UnitDefNames["shieldfelon"].id] = false,
[UnitDefNames["jumpskirm"].id] = false,
}
local factoryDefs = { -- Standard factories
[UnitDefNames["factorycloak"].id] = 0,
[UnitDefNames["factoryshield"].id] = 0,
[UnitDefNames["factoryspider"].id] = 0,
[UnitDefNames["factoryjump"].id] = 0,
[UnitDefNames["factoryveh"].id] = 0,
[UnitDefNames["factoryhover"].id] = 0,
[UnitDefNames["factoryamph"].id] = 0,
[UnitDefNames["factorytank"].id] = 0,
[UnitDefNames["factoryplane"].id] = 0,
[UnitDefNames["factorygunship"].id] = 0,
[UnitDefNames["factoryship"].id] = 0,
[UnitDefNames["platecloak"].id] = 0,
[UnitDefNames["plateshield"].id] = 0,
[UnitDefNames["platespider"].id] = 0,
[UnitDefNames["platejump"].id] = 0,
[UnitDefNames["plateveh"].id] = 0,
[UnitDefNames["platehover"].id] = 0,
[UnitDefNames["plateamph"].id] = 0,
[UnitDefNames["platetank"].id] = 0,
[UnitDefNames["plateplane"].id] = 0,
[UnitDefNames["plategunship"].id] = 0,
[UnitDefNames["plateship"].id] = 0,
}
return alwaysHoldPos, holdPosException, dontFireAtRadarUnits, factoryDefs
| gpl-2.0 |
Bew78LesellB/awesome | tests/test-awful-layout.lua | 10 | 4027 | -- This test hit the client layout code paths to see if there is errors.
-- it doesn't check if the layout are correct.
local awful = require("awful")
local gtable = require("gears.table")
local first_layout = nil
local t = nil
local has_spawned = false
local steps = {
-- Add enough clients
function(count)
if count <= 1 and not has_spawned then
for _=1, 5 do awful.spawn("xterm") end
has_spawned = true
elseif #client.get() >= 5 then
first_layout = client.focus:tags()[1].layout
t = client.focus:tags()[1]
return true
end
end,
}
-- Test if layouts are called
do
local c1, c2
local arrange_expected = false
local fake_layout = {
arrange = function()
assert(arrange_expected)
arrange_expected = false
end,
name = "fake",
}
table.insert(steps, function()
c1, c2 = client.get()[1], client.get()[2]
client.focus = c1
arrange_expected = true
awful.layout.set(fake_layout)
return true
end)
table.insert(steps, function()
assert(arrange_expected == false)
arrange_expected = false
client.focus = c2
return true
end)
table.insert(steps, function()
-- This sync is needed to avoid a race: Consider the code
-- client.focus = c2
-- gears.timer.start_new(0, function()
-- client.focus = c1
-- end)
-- The C code would focus c2, but Lua would then change the focus to c1
-- before the X11 server acknowledged the focus change (FocusIn event).
-- Thus, when that event comes in, the C code things that c1 currently
-- has the focus and thus would do c2:emit_signal("focus"). Then, when
-- the FocusIn event for c1 comes, it would do c1:emit_signal("focus").
awesome.sync()
return true
end)
table.insert(steps, function()
assert(arrange_expected == false)
arrange_expected = true
fake_layout.need_focus_update = true
client.focus = c1
return true
end)
table.insert(steps, function()
assert(arrange_expected == false)
awful.layout.set(awful.layout.suit.floating)
return true
end)
end
local function next_layout()
awful.layout.inc(1)
assert(client.focus:tags()[1].layout ~= first_layout)
return true
end
-- Test most properties for each layouts
local common_steps = {
function()
assert(#t:clients() == 5)
t.master_count = 2
return true
end,
function()
t.master_count = 0
return true
end,
function()
t.master_count = 6 --more than #client.get(1)
return true
end,
function()
t.master_count = 1
return true
end,
function()
t.column_count = 2
return true
end,
function()
t.column_count = 6 --more than #client.get(1)
return true
end,
function()
t.column_count = 1
return true
end,
function()
t.master_fill_policy = t.master_fill_policy == "master_width_factor" and
"expand" or "master_width_factor"
return true
end,
function()
t.master_width_factor = 0.75
return true
end,
function()
t.master_width_factor = 0
return true
end,
function()
t.master_width_factor = 1
return true
end,
function()
t.master_width_factor = 0.5
return true
end,
function()
t.gap = t.gap == 0 and 5 or 0
return true
end,
}
local first = false
for _ in ipairs(awful.layout.layouts) do
if not first then
first = true
else
gtable.merge(steps, {next_layout})
end
gtable.merge(steps, common_steps)
end
require("_runner").run_steps(steps)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
punisherbot/ma | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
mahdib9/mjk | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
OmarReaI/RealBot | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
Anarchid/Zero-K | scripts/jumpcon.lua | 4 | 19729 | include "constants.lua"
include "JumpRetreat.lua"
local jump = piece 'jump'
local torso = piece 'torso'
local flare = piece 'flare'
local pelvis = piece 'pelvis'
local rcalf = piece 'rcalf'
local lcalf = piece 'lcalf'
local lthigh = piece 'lthigh'
local rthigh = piece 'rthigh'
local larm = piece 'larm'
local rarm = piece 'rarm'
local rhand = piece 'rhand'
local lhand = piece 'lhand'
local head = piece 'head'
local thrust = piece 'Thrust'
local SIG_RESTORE = 16
local SIG_AIM = 8
local SIG_STOPBUILD = 4
local SIG_BUILD = 2
local SIG_WALK = 1
local RESTORE_DELAY = 1000
local smokePiece = {torso}
local nanoPiece = flare
local usingNano = false
local usingGun = false
--------------------------
-- MOVEMENT
local function walk()
Signal(SIG_WALK)
SetSignalMask(SIG_WALK)
while true do
Move(pelvis, y_axis, -0.250000)
Move(pelvis, z_axis, -0.600000)
Move(rcalf, y_axis, 0.000000)
Move(lcalf, y_axis, 0.639996)
Turn(pelvis, x_axis, math.rad(10.890110))
Turn(lthigh, x_axis, math.rad(-43.939560))
Turn(rthigh, x_axis, math.rad(4.208791))
Turn(rcalf, x_axis, math.rad(19.324176))
Turn(lcalf, x_axis, math.rad(43.598901))
if not usingNano and not usingGun then
Turn(torso, x_axis, math.rad(5.269231))
Turn(larm, x_axis, math.rad(-17.219780))
Turn(rarm, x_axis, math.rad(-9.840659))
Turn(rhand, x_axis, math.rad(-9.137363))
Turn(lhand, x_axis, math.rad(-36.565934))
end
Sleep(82)
Move(pelvis, y_axis, -0.119995)
Move(pelvis, z_axis, -0.500000)
Turn(lthigh, x_axis, math.rad(-57.302198))
Turn(rthigh, x_axis, math.rad(10.708791))
Turn(rcalf, x_axis, math.rad(21.093407))
Turn(lcalf, x_axis, math.rad(43.598901))
if not usingNano and not usingGun then
Turn(torso, x_axis, math.rad(2.626374))
Turn(larm, x_axis, math.rad(-8.598901))
Turn(rarm, x_axis, math.rad(-11.769231))
Turn(rhand, x_axis, math.rad(-14.230769))
Turn(lhand, x_axis, math.rad(-24.774725))
end
Sleep(56)
Move(pelvis, y_axis, 0.000000)
Move(pelvis, z_axis, -0.400000)
Turn(lthigh, x_axis, math.rad(-70.664835))
Turn(rthigh, x_axis, math.rad(17.219780))
Turn(rcalf, x_axis, math.rad(22.851648))
Turn(lcalf, x_axis, math.rad(43.598901))
if not usingNano and not usingGun then
Turn(torso, x_axis, 0)
Turn(larm, x_axis, 0)
Turn(rarm, x_axis, math.rad(-13.708791))
Turn(rhand, x_axis, math.rad(-19.324176))
Turn(lhand, x_axis, math.rad(-13.000000))
end
Sleep(56)
Move(pelvis, y_axis, 0.250000)
Move(pelvis, z_axis, -0.200000)
Move(lcalf, y_axis, 0.700000)
Turn(lthigh, x_axis, math.rad(-76.296703))
Turn(rthigh, x_axis, math.rad(18.983516))
Turn(rcalf, x_axis, math.rad(25.313187))
Turn(lcalf, x_axis, math.rad(37.263736))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(-4.038462))
Turn(torso, x_axis, math.rad(-2.626374))
Turn(larm, x_axis, math.rad(10.890110))
Turn(rarm, x_axis, math.rad(-14.928571))
Turn(rhand, x_axis, math.rad(-28.994505))
Turn(lhand, x_axis, math.rad(-12.818681))
end
Sleep(55)
Move(pelvis, y_axis, 0.500000)
Move(pelvis, z_axis, 0.000000)
Move(lcalf, y_axis, -0.500000)
Turn(lthigh, x_axis, math.rad(-81.917582))
Turn(rthigh, x_axis, math.rad(20.741758))
Turn(rcalf, x_axis, math.rad(27.774725))
Turn(lcalf, x_axis, math.rad(30.934066))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(-8.076923))
Turn(torso, x_axis, math.rad(-5.269231))
Turn(larm, x_axis, math.rad(21.791209))
Turn(rarm, x_axis, math.rad(-16.170330))
Turn(rhand, x_axis, math.rad(-38.675824))
Turn(lhand, x_axis, math.rad(-12.648352))
end
Sleep(59)
Move(pelvis, y_axis, 0.250000)
Move(pelvis, z_axis, 0.869995)
Move(lcalf, y_axis, -0.700000)
Turn(lthigh, x_axis, math.rad(-68.384615))
Turn(rthigh, x_axis, math.rad(29.357143))
Turn(rcalf, x_axis, math.rad(25.483516))
Turn(lcalf, x_axis, math.rad(26.010989))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(-7.901099))
Turn(torso, x_axis, math.rad(-2.626374))
Turn(larm, x_axis, math.rad(34.456044))
Turn(rarm, x_axis, math.rad(-22.851648))
Turn(rhand, x_axis, math.rad(-54.489011))
Turn(lhand, x_axis, math.rad(-20.912088))
end
Sleep(57)
Move(pelvis, y_axis, 0.000000)
Move(pelvis, z_axis, 1.739996)
Move(lcalf, y_axis, -0.900000)
Turn(lthigh, x_axis, math.rad(-54.851648))
Turn(rthigh, x_axis, math.rad(37.967033))
Turn(rcalf, x_axis, math.rad(23.203297))
Turn(lcalf, x_axis, math.rad(21.093407))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(-7.730769))
Turn(torso, x_axis, 0)
Turn(larm, x_axis, math.rad(47.109890))
Turn(rarm, x_axis, math.rad(-29.532967))
Turn(rhand, x_axis, math.rad(-70.324176))
Turn(lhand, x_axis, math.rad(-29.175824))
end
Sleep(26)
Move(pelvis, y_axis, -0.469995)
Move(pelvis, z_axis, 2.059998)
Move(rcalf, y_axis, 0.619995)
Move(lcalf, y_axis, 0.000000 - 0.000031)
Turn(pelvis, x_axis, math.rad(10.890110))
Turn(lthigh, x_axis, math.rad(-43.598901))
Turn(rthigh, x_axis, math.rad(18.104396))
Turn(rcalf, x_axis, math.rad(48.170330))
Turn(lcalf, x_axis, math.rad(21.263736))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(-3.857143))
Turn(torso, x_axis, math.rad(2.626374))
Turn(larm, x_axis, math.rad(48.868132))
Turn(rhand, x_axis, math.rad(-74.186813))
Turn(lhand, x_axis, math.rad(-23.730769))
end
Sleep(27)
Move(pelvis, y_axis, -0.939996)
Move(pelvis, z_axis, 2.400000)
Move(rcalf, y_axis, 1.239996)
Move(lcalf, y_axis, 0.800000)
Turn(lthigh, x_axis, math.rad(-32.346154))
Turn(rthigh, x_axis, math.rad(-1.747253))
Turn(rcalf, x_axis, math.rad(73.137363))
Turn(lcalf, x_axis, math.rad(21.434066))
if not usingNano and not usingGun then
Turn(head, x_axis, 0)
Turn(torso, x_axis, math.rad(5.269231))
Turn(larm, x_axis, math.rad(50.631868))
Turn(rhand, x_axis, math.rad(-78.054945))
Turn(lhand, x_axis, math.rad(-18.280220))
end
Sleep(56)
Move(pelvis, y_axis, -0.769995)
Move(pelvis, z_axis, 1.619995)
Move(rcalf, y_axis, 1.189996)
Move(lcalf, y_axis, 0.700000)
Turn(lthigh, x_axis, math.rad(-22.142857))
Turn(rthigh, x_axis, math.rad(-5.087912))
Turn(rcalf, x_axis, math.rad(58.362637))
Turn(lcalf, x_axis, math.rad(11.252747))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(4.736264))
Turn(torso, x_axis, math.rad(7.730769))
Turn(larm, x_axis, math.rad(30.406593))
Turn(rarm, x_axis, math.rad(-26.714286))
Turn(rhand, x_axis, math.rad(-61.703297))
Turn(lhand, x_axis, math.rad(-14.928571))
end
Sleep(55)
Move(pelvis, y_axis, -0.589996)
Move(pelvis, z_axis, 0.850000)
Move(rcalf, y_axis, 1.129999)
Move(lcalf, y_axis, 0.600000)
Turn(lthigh, x_axis, math.rad(-11.950549))
Turn(rthigh, x_axis, math.rad(-8.428571))
Turn(rcalf, x_axis, math.rad(43.598901))
Turn(lcalf, x_axis, math.rad(1.049451))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(9.489011))
Turn(torso, x_axis, math.rad(10.192308))
Turn(larm, x_axis, math.rad(10.192308))
Turn(rarm, x_axis, math.rad(-23.901099))
Turn(rhand, x_axis, math.rad(-45.357143))
Turn(lhand, x_axis, math.rad(-11.598901))
end
Sleep(58)
Move(pelvis, y_axis, -0.419995)
Move(pelvis, z_axis, 0.119995)
Move(rcalf, y_axis, 0.889996)
Move(lcalf, y_axis, 0.300000)
Turn(lthigh, x_axis, math.rad(-3.857143))
Turn(rthigh, x_axis, math.rad(-26.181319))
Turn(lcalf, x_axis, math.rad(10.192308))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(4.736264))
Turn(torso, x_axis, math.rad(7.730769))
Turn(larm, x_axis, math.rad(4.379121))
Turn(rarm, x_axis, math.rad(-16.340659))
Turn(rhand, x_axis, math.rad(-39.549451))
Turn(lhand, x_axis, math.rad(-11.071429))
end
Sleep(57)
Move(pelvis, y_axis, -0.250000)
Move(pelvis, z_axis, -0.600000)
Move(rcalf, y_axis, 0.639996)
Move(lcalf, y_axis, 0.000000)
Turn(pelvis, x_axis, math.rad(10.890110))
Turn(lthigh, x_axis, math.rad(4.208791))
Turn(rthigh, x_axis, math.rad(-43.950549))
Turn(lcalf, x_axis, math.rad(19.324176))
if not usingNano and not usingGun then
Turn(head, x_axis, 0)
Turn(torso, x_axis, math.rad(5.258242))
Turn(larm, x_axis, math.rad(-1.395604))
Turn(rarm, x_axis, math.rad(-8.769231))
Turn(rhand, x_axis, math.rad(-33.758242))
Turn(lhand, x_axis, math.rad(-10.538462))
end
Sleep(87)
Move(pelvis, y_axis, -0.119995)
Move(pelvis, z_axis, -0.500000)
Move(rcalf, y_axis, 0.639996)
Turn(lthigh, x_axis, math.rad(11.950549))
Turn(rthigh, x_axis, math.rad(-57.302198))
Turn(lcalf, x_axis, math.rad(21.093407))
if not usingNano and not usingGun then
Turn(torso, x_axis, math.rad(2.626374))
Turn(larm, x_axis, math.rad(-4.208791))
Turn(rarm, x_axis, math.rad(-4.379121))
Turn(rhand, x_axis, math.rad(-23.203297))
Turn(lhand, x_axis, math.rad(-16.873626))
end
Sleep(55)
Move(pelvis, y_axis, 0.000000)
Move(pelvis, z_axis, -0.400000)
Move(rcalf, y_axis, 0.639996)
Turn(lthigh, x_axis, math.rad(19.681319))
Turn(rthigh, x_axis, math.rad(-70.664835))
Turn(lcalf, x_axis, math.rad(22.851648))
if not usingNano and not usingGun then
Turn(torso, x_axis, 0)
Turn(larm, x_axis, math.rad(-7.027473))
Turn(rarm, x_axis, 0)
Turn(rhand, x_axis, math.rad(-12.648352))
Turn(lhand, x_axis, math.rad(-23.203297))
end
Sleep(56)
Move(pelvis, y_axis, 0.250000)
Move(pelvis, z_axis, -0.200000)
Move(rcalf, y_axis, 0.700000)
Move(lcalf, y_axis, 0.000000)
Turn(lthigh, x_axis, math.rad(19.851648))
Turn(rthigh, x_axis, math.rad(-76.296703))
Turn(rcalf, x_axis, math.rad(37.263736))
Turn(lcalf, x_axis, math.rad(25.313187))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(-4.038462))
Turn(torso, x_axis, math.rad(-2.626374))
Turn(larm, x_axis, math.rad(-11.950549))
Turn(rarm, x_axis, math.rad(7.901099))
Turn(rhand, x_axis, math.rad(-12.478022))
Turn(lhand, x_axis, math.rad(-24.252747))
end
Sleep(57)
Move(pelvis, y_axis, 0.500000)
Move(pelvis, z_axis, 0.000000)
Move(rcalf, y_axis, -0.500000)
Move(lcalf, y_axis, 0.000000)
Turn(lthigh, x_axis, math.rad(20.032967))
Turn(rthigh, x_axis, math.rad(-81.917582))
Turn(rcalf, x_axis, math.rad(30.934066))
Turn(lcalf, x_axis, math.rad(27.774725))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(-8.076923))
Turn(torso, x_axis, math.rad(-5.269231))
Turn(larm, x_axis, math.rad(-16.873626))
Turn(rarm, x_axis, math.rad(15.818681))
Turn(rhand, x_axis, math.rad(-12.302198))
Turn(lhand, x_axis, math.rad(-25.313187))
end
Sleep(59)
Move(pelvis, y_axis, 0.250000)
Move(pelvis, z_axis, 0.869995)
Move(rcalf, y_axis, -0.700000)
Move(lcalf, y_axis, 0.000000)
Turn(pelvis, x_axis, math.rad(10.890110))
Turn(lthigh, x_axis, math.rad(24.071429))
Turn(rthigh, x_axis, math.rad(-68.384615))
Turn(rcalf, x_axis, math.rad(26.010989))
Turn(lcalf, x_axis, math.rad(25.483516))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(-7.901099))
Turn(torso, x_axis, math.rad(-2.626374))
Turn(larm, x_axis, math.rad(-22.505495))
Turn(rarm, x_axis, math.rad(31.642857))
Turn(rhand, x_axis, math.rad(-20.741758))
Turn(lhand, x_axis, math.rad(-45.527473))
end
Sleep(55)
Move(pelvis, y_axis, 0.000000)
Move(pelvis, z_axis, 1.750000)
Move(rcalf, y_axis, -0.900000)
Move(lcalf, y_axis, 0.000000)
Turn(lthigh, x_axis, math.rad(28.126374))
Turn(rthigh, x_axis, math.rad(-54.851648))
Turn(rcalf, x_axis, math.rad(21.093407))
Turn(lcalf, x_axis, math.rad(23.203297))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(-7.730769))
Turn(torso, x_axis, 0)
Turn(larm, x_axis, math.rad(-28.126374))
Turn(rarm, x_axis, math.rad(47.461538))
Turn(rhand, x_axis, math.rad(-29.175824))
Turn(lhand, x_axis, math.rad(-65.741758))
end
Sleep(28)
Move(pelvis, y_axis, -0.469995)
Move(pelvis, z_axis, 2.059998)
Move(rcalf, y_axis, 0.000000 - 0.000031)
Move(lcalf, y_axis, 0.600000)
Turn(lthigh, x_axis, math.rad(13.181319))
Turn(rthigh, x_axis, math.rad(-43.598901))
Turn(rcalf, x_axis, math.rad(21.263736))
Turn(lcalf, x_axis, math.rad(48.159341))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(-3.857143))
Turn(torso, x_axis, math.rad(2.626374))
Turn(larm, x_axis, math.rad(-27.774725))
Turn(rarm, x_axis, math.rad(47.818681))
Turn(rhand, x_axis, math.rad(-24.071429))
Turn(lhand, x_axis, math.rad(-72.785714))
end
Sleep(27)
Move(pelvis, y_axis, -0.939996)
Move(pelvis, z_axis, 2.400000)
Move(rcalf, y_axis, 0.789996)
Move(lcalf, y_axis, 1.200000)
Turn(lthigh, x_axis, math.rad(-1.747253))
Turn(rthigh, x_axis, math.rad(-32.346154))
Turn(rcalf, x_axis, math.rad(21.445055))
Turn(lcalf, x_axis, math.rad(73.137363))
if not usingNano and not usingGun then
Turn(head, x_axis, 0)
Turn(torso, x_axis, math.rad(5.269231))
Turn(larm, x_axis, math.rad(-27.423077))
Turn(rarm, x_axis, math.rad(48.159341))
Turn(rhand, x_axis, math.rad(-18.983516))
Turn(lhand, x_axis, math.rad(-79.807692))
end
Sleep(56)
Move(pelvis, y_axis, -0.769995)
Move(pelvis, z_axis, 1.619995)
Move(rcalf, y_axis, 0.689996)
Move(lcalf, y_axis, 1.350000)
Turn(lthigh, x_axis, math.rad(-5.087912))
Turn(rthigh, x_axis, math.rad(-22.142857))
Turn(rcalf, x_axis, math.rad(11.252747))
Turn(lcalf, x_axis, math.rad(58.362637))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(4.736264))
Turn(torso, x_axis, math.rad(7.730769))
Turn(larm, x_axis, math.rad(-24.961538))
Turn(rarm, x_axis, math.rad(34.093407))
Turn(rhand, x_axis, math.rad(-16.340659))
Turn(lhand, x_axis, math.rad(-71.714286))
end
Sleep(55)
Move(pelvis, y_axis, -0.589996)
Move(pelvis, z_axis, 0.850000)
Move(rcalf, y_axis, 0.589996)
Move(lcalf, y_axis, 1.500000)
Turn(lthigh, x_axis, math.rad(-8.428571))
Turn(rthigh, x_axis, math.rad(-11.950549))
Turn(rcalf, x_axis, math.rad(1.049451))
Turn(lcalf, x_axis, math.rad(43.598901))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(9.489011))
Turn(torso, x_axis, math.rad(10.192308))
Turn(larm, x_axis, math.rad(-22.505495))
Turn(rarm, x_axis, math.rad(20.032967))
Turn(rhand, x_axis, math.rad(-13.708791))
Turn(lhand, x_axis, math.rad(-63.642857))
end
Sleep(58)
Move(pelvis, y_axis, -0.419995)
Move(pelvis, z_axis, 0.119995)
Move(rcalf, y_axis, 0.279999)
Move(lcalf, y_axis, 1.069995)
Turn(lthigh, x_axis, math.rad(-26.181319))
Turn(rthigh, x_axis, math.rad(-3.857143))
Turn(rcalf, x_axis, math.rad(10.192308))
if not usingNano and not usingGun then
Turn(head, x_axis, math.rad(4.736264))
Turn(torso, x_axis, math.rad(7.730769))
Turn(larm, x_axis, math.rad(-19.851648))
Turn(rarm, x_axis, math.rad(5.087912))
Turn(rhand, x_axis, math.rad(-11.417582))
Turn(lhand, x_axis, math.rad(-50.098901))
end
Sleep(55)
end
end
function script.StartMoving()
StartThread(walk)
end
function script.StopMoving()
Signal(SIG_WALK)
Turn(pelvis, x_axis, 0, math.rad(200.000000))
Turn(rthigh, x_axis, 0, math.rad(200.000000))
Turn(rcalf, x_axis, 0, math.rad(200.000000))
Turn(lthigh, x_axis, 0, math.rad(200.000000))
Turn(lcalf, x_axis, 0, math.rad(200.000000))
if not usingNano and not usingGun then
Turn(torso, y_axis, 0, math.rad(90.000000))
Turn(rhand, x_axis, 0, math.rad(200.000000))
Turn(rarm, x_axis, 0, math.rad(200.000000))
Turn(lhand, x_axis, 0, math.rad(200.000000))
Turn(larm, x_axis, 0, math.rad(200.000000))
end
end
--------------------------
-- NANO
function script.QueryNanoPiece()
GG.LUPS.QueryNanoPiece(unitID,unitDefID,Spring.GetUnitTeam(unitID),nanoPiece)
return nanoPiece
end
function script.StartBuilding(heading, pitch)
if GetUnitValue(COB.INBUILDSTANCE) == 0 then
Signal(SIG_STOPBUILD)
SetUnitValue(COB.INBUILDSTANCE, 1)
SetSignalMask(SIG_BUILD)
usingNano = true
if not usingGun then
Turn(torso, y_axis, heading, math.rad(250.000000))
end
Turn(larm, x_axis, -pitch-0.2, math.rad(150.000000))
Turn(lhand, x_axis, math.rad(-45), math.rad(150.000000))
end
end
function script.StopBuilding()
if GetUnitValue(COB.INBUILDSTANCE) == 1 then
Signal(SIG_BUILD)
SetUnitValue(COB.INBUILDSTANCE, 0)
SetSignalMask(SIG_STOPBUILD)
usingNano = false
Sleep(RESTORE_DELAY)
if not usingGun then
Turn(torso, y_axis, 0, math.rad(250.000000))
end
Turn(lhand, x_axis, 0, math.rad(150.000000))
Turn(larm, x_axis, 0, math.rad(150.000000))
end
end
--------------------------
-- WEAPON
function script.QueryWeapon(num)
return rhand
end
function script.AimFromWeapon(num)
return torso
end
local function RestoreAfterDelay()
Signal(SIG_RESTORE)
SetSignalMask(SIG_RESTORE)
Sleep(RESTORE_DELAY)
usingGun = false
Turn(torso, y_axis, 0, math.rad(250.000000))
Turn(rhand, x_axis, 0, math.rad(150.000000))
Turn(rarm, x_axis, 0, math.rad(150.000000))
end
function script.AimWeapon(num, heading, pitch)
Signal(SIG_AIM)
SetSignalMask(SIG_AIM)
usingGun = true
Turn(torso, y_axis, heading, math.rad(250.000000))
Turn(rarm, x_axis, -pitch-0.15, math.rad(150.000000))
Turn(rhand, x_axis, math.rad(-45), math.rad(150.000000))
WaitForTurn(torso, y_axis)
WaitForTurn(rarm, x_axis)
StartThread(RestoreAfterDelay)
return true
end
--------------------------
-- JUMP
function beginJump()
script.StopMoving()
EmitSfx(jump, GG.Script.UNIT_SFX2)
end
function jumping()
GG.PokeDecloakUnit(unitID, unitDefID)
EmitSfx(thrust, GG.Script.UNIT_SFX1)
end
function endJump()
script.StopMoving()
EmitSfx(jump, GG.Script.UNIT_SFX2)
end
--------------------------
-- CREATE AND DESTROY
function script.Create()
Hide(thrust)
Hide(jump)
Hide(flare)
Turn(thrust, x_axis, math.rad(70), math.rad(2000))
StartThread(GG.Script.SmokeUnit, unitID, smokePiece)
Spring.SetUnitNanoPieces(unitID, {nanoPiece})
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
Hide(flare)
if severity <= 0.25 then
Explode(head, SFX.NONE)
Explode(pelvis, SFX.NONE)
Explode(lhand, SFX.NONE)
Explode(lcalf, SFX.NONE)
Explode(larm, SFX.NONE)
Explode(lthigh, SFX.NONE)
Explode(rhand, SFX.NONE)
Explode(rcalf, SFX.NONE)
Explode(rarm, SFX.NONE)
Explode(rthigh, SFX.NONE)
Explode(thrust, SFX.NONE)
Explode(torso, SFX.NONE)
return 1
end
if severity <= 0.5 then
Explode(head, SFX.FALL)
Explode(pelvis, SFX.FALL)
Explode(lhand, SFX.FALL)
Explode(lcalf, SFX.FALL)
Explode(larm, SFX.FALL)
Explode(lthigh, SFX.FALL)
Explode(rhand, SFX.FALL)
Explode(rcalf, SFX.FALL)
Explode(rarm, SFX.FALL)
Explode(rthigh, SFX.FALL)
Explode(thrust, SFX.FALL)
Explode(torso, SFX.SHATTER)
return 1
end
Explode(head, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT)
Explode(pelvis, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT)
Explode(lhand, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT)
Explode(lcalf, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT)
Explode(larm, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT)
Explode(lthigh, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT)
Explode(rhand, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT)
Explode(rcalf, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT)
Explode(rarm, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT)
Explode(rthigh, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT)
Explode(thrust, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT)
Explode(torso, SFX.SHATTER)
return 2
end
| gpl-2.0 |
poculeka/IntWars | BinWars/Scripts/Heroes/Karthus.lua | 4 | 4297 | --[[
NotSingleTargetSpell = true
DoesntBreakShields = true
DoesntTriggerSpellCasts = false
CastingBreaksStealth = true
IsDamagingSpell = true
local R1 = {Function = BBPreloadParticle}
R1["Params"] = {Name = 'laywaste_point.troy'} --R2 = {} / R2["Name"] = "laywaste_point.troy" / R1["Params"] = R2
local R2 = {Function = BBPreloadParticle}
R2["Params"] = {Name = 'laywaste_tar.troy'} --R3 = {} / R3["Name"] = "laywaste_point.troy" / R2["Params"] = R3
local R3 = {Function = BBPreloadCharacter}
R3["Params"] = {Name = 'testcube'} --R4 = {} / R4["Name"] = "testcube" / R3["Params"] = R4
local R4 = {Function = BBPreloadCharacter}
R4["Params"] = {Name = 'spellbook1'} --R5 = {} / R5["Name"] = "testcube" / R4["Params"] = R5
local R0 = {R1,R2,R3,R4}
PreLoadBuildingBlocks = R0
]]
--[[ 35 [-]: SETLIST R0 4 1 ; R0[(1-1)*FPF+i] := R(0+i), 1 <= i <= 4
36 [-]: SETGLOBAL R0 K5 ; PreLoadBuildingBlocks := R0
37 [-]: RETURN R0 1 ; return ]]
--PreLoadBuildingBlocks = R1,R2,R3,R4;
function CastSpell(self,spellIndex,x,y)
if spellIndex == 0 then
spell = CSpellWork(self,spellIndex,x,y) --LayWaste
spell.updatePos = true
spell.stop = true
--local p1 = spell:AddParticle(self:GetParticle('LayWaste_point.troy'),spell.castTime) --Wind up 0.25
p1 = spell:AddParticle(self,'LayWaste_point.troy',0.25)
--p1.vision = true
--spell:AddParticle(self:GetParticle('LayWaste_tar.troy'),spell.castFrame/30) --burn time 0.6
p2 = spell:AddParticle(self,'LayWaste_tar.troy',0.6)
self:QueueSpell(spell)
--[[
local spell = CSpell('LayWaste',x,y) --LayWaste
spell.updatePos = true
spell.stop = true
--local p1 = spell:AddParticle(self:GetParticle('LayWaste_point.troy'),spell.castTime) --Wind up 0.25
local p1 = spell:AddParticle(self,'LayWaste_point.troy',0.25)
p1.vision = true
--spell:AddParticle(self:GetParticle('LayWaste_tar.troy'),spell.castFrame/30) --burn time 0.6
local p2 = spell:AddParticle(self,'LayWaste_tar.troy',0.6)
self:QueueSpell(spell)
]]
--self:SetupSpell() --send FE 0F
--self:CastSpell(spellIndex,x,y)
--MoveAns(self,...) --60
--Vision Spawn for the Q particle
--pe = ParticleEmiter()
--pe:AddParticle(self,nil,'LayWaste_point.troy')
--pe:Send(self)
--after 1 second
--KillParticle(self,...) --[40000063] 37
--pe:AddParticle(self,'LayWaste_tar.troy') --Applied to (null)
elseif spellIndex == 1 then
self:SetupSpell(15,1,1)
self:CastSpell(spellIndex,x,y)
--MoveAns(self,...) --60
pe = ParticleEmiter()
pe:AddParticle(self,nil,'wallofpain__new_beam.troy') --applied to hiu???
--pe:AddParticle(self,'wallofpain_new_post_green.troy') --Applied to (null)
--pe:AddParticle(self,'wallofpain_new_post_green.troy') --Applied to (null)
pe:Send(self)
elseif spellIndex == 2 then
--[[self:CastSpell(spellIndex,x,y)
--self:SetPosition(...) --4F sets face position
pe = ParticleEmiter()
pe:AddParticle(self,'Defile_green_cas.troy')
pe:Send(self)
self:ApplyBuff(2,'Defile',30000.000000) --Stacks: 1, Visible: 0]]
spell = CSpellWork(self,spellIndex,x,y) --LayWaste
spell.updatePos = true
spell.stop = true
p1 = spell:AddParticle(self,self,'Defile_green_cas.troy',0.25)
spell:AddBuff(2,'Defile',30000.000000,1) --Stacks: 1, Visible: 0]]
self:QueueSpell(spell)
elseif spellIndex == 3 then
self:CastSpell(spellIndex,x,y)--DisplaySpell() --B4
end
end | gpl-3.0 |
MinaciousGrace/Til-Death | Scripts/00 settings_system.lua | 2 | 6485 | local settings_prefix= "/" .. THEME:GetThemeDisplayName() .. "_settings/"
global_cur_game= GAMESTATE:GetCurrentGame():GetName():lower()
function force_table_elements_to_match_type(candidate, must_match, depth_remaining)
for k, v in pairs(candidate) do
if type(must_match[k]) ~= type(v) then
candidate[k]= nil
elseif type(v) == "table" and depth_remaining ~= 0 then
force_table_elements_to_match_type(v, must_match[k], depth_remaining-1)
end
end
for k, v in pairs(must_match) do
if type(candidate[k]) == "nil" then
if type(v) == "table" then
candidate[k]= DeepCopy(v)
else
candidate[k]= v
end
end
end
end
local function slot_to_prof_dir(slot, reason)
local prof_dir= "Save"
if slot and slot ~= "ProfileSlot_Invalid" then
prof_dir= PROFILEMAN:GetProfileDir(slot)
if not prof_dir or prof_dir == "" then
--Warn("Could not fetch profile dir to " .. reason .. ".")
return
end
end
return prof_dir
end
local function load_conf_file(fname)
local file= RageFileUtil.CreateRageFile()
local ret= {}
if file:Open(fname, 1) then
local data= loadstring(file:Read())
setfenv(data, {})
local success, data_ret= pcall(data)
if success then
ret= data_ret
end
file:Close()
end
file:destroy()
return ret
end
local setting_mt= {
__index= {
init= function(self, name, file, default, match_depth)
assert(type(default) == "table", "default for setting must be a table.")
self.name= name
self.file= file
self.default= default
self.match_depth= match_depth
self.dirty_table= {}
self.data_set= {}
return self
end,
load= function(self, slot)
slot= slot or "ProfileSlot_Invalid"
local prof_dir= slot_to_prof_dir(slot, "read " .. self.name)
if not prof_dir then
self.data_set[slot]= DeepCopy(self.default)
else
local fname= prof_dir .. settings_prefix .. self.file
if not FILEMAN:DoesFileExist(fname) then
self.data_set[slot]= DeepCopy(self.default)
else
local from_file= load_conf_file(fname)
if type(from_file) == "table" then
if self.match_depth and self.match_depth ~= 0 then
force_table_elements_to_match_type(
from_file, self.default, self.match_depth-1)
end
self.data_set[slot]= from_file
else
self.data_set[slot]= DeepCopy(self.default)
end
end
end
return self.data_set[slot]
end,
get_data= function(self, slot)
slot= slot or "ProfileSlot_Invalid"
return self.data_set[slot] or self.default
end,
set_data= function(self, slot, data)
slot= slot or "ProfileSlot_Invalid"
self.data_set[slot]= data
end,
set_dirty= function(self, slot)
slot= slot or "ProfileSlot_Invalid"
self.dirty_table[slot]= true
end,
check_dirty= function(self, slot)
slot= slot or "ProfileSlot_Invalid"
return self.dirty_table[slot]
end,
clear_slot= function(self, slot)
slot= slot or "ProfileSlot_Invalid"
self.dirty_table[slot]= nil
self.data_set[slot]= nil
end,
save= function(self, slot)
slot= slot or "ProfileSlot_Invalid"
if not self:check_dirty(slot) then return end
local prof_dir= slot_to_prof_dir(slot, "write " .. self.name)
if not prof_dir then return end
local fname= prof_dir .. settings_prefix .. self.file
local file_handle= RageFileUtil.CreateRageFile()
if not file_handle:Open(fname, 2) then
Warn("Could not open '" .. fname .. "' to write " .. self.name .. ".")
else
local output= "return " .. lua_table_to_string(self.data_set[slot])
file_handle:Write(output)
file_handle:Close()
file_handle:destroy()
end
end,
save_all= function(self)
for slot, data in pairs(self.data_set) do
self:save(slot)
end
end
}}
function create_setting(name, file, default, match_depth)
return setmetatable({}, setting_mt):init(name, file, default, match_depth)
end
function write_str_to_file(str, fname, str_name)
local file_handle= RageFileUtil.CreateRageFile()
if not file_handle:Open(fname, 2) then
Warn("Could not open '" .. fname .. "' to write " .. str_name .. ".")
else
file_handle:Write(str)
file_handle:Close()
file_handle:destroy()
end
end
function string_needs_escape(str)
if str:match("^[a-zA-Z_][a-zA-Z_0-9]*$") then
return false
else
return true
end
end
function lua_table_to_string(t, indent, line_pos)
indent= indent or ""
line_pos= (line_pos or #indent) + 1
local internal_indent= indent .. " "
local ret= "{"
local has_table= false
for k, v in pairs(t) do if type(v) == "table" then has_table= true end
end
if has_table then
ret= "{\n" .. internal_indent
line_pos= #internal_indent
end
local separator= ""
local function do_value_for_key(k, v, need_key_str)
if type(v) == "nil" then return end
local k_str= k
if type(k) == "number" then
k_str= "[" .. k .. "]"
else
if string_needs_escape(k) then
k_str= "[" .. ("%q"):format(k) .. "]"
else
k_str= k
end
end
if need_key_str then
k_str= k_str .. "= "
else
k_str= ""
end
local v_str= ""
if type(v) == "table" then
v_str= lua_table_to_string(v, internal_indent, line_pos + #k_str)
elseif type(v) == "string" then
v_str= ("%q"):format(v)
elseif type(v) == "number" then
if v ~= math.floor(v) then
v_str= ("%.6f"):format(v)
local last_nonz= v_str:reverse():find("[^0]")
if last_nonz then
v_str= v_str:sub(1, -last_nonz)
end
else
v_str= tostring(v)
end
else
v_str= tostring(v)
end
local to_add= k_str .. v_str
if type(v) == "table" then
if separator == "" then
to_add= separator .. to_add
else
to_add= separator .."\n" .. internal_indent .. to_add
end
else
if line_pos + #separator + #to_add > 80 then
line_pos= #internal_indent + #to_add
to_add= separator .. "\n" .. internal_indent .. to_add
else
to_add= separator .. to_add
line_pos= line_pos + #to_add
end
end
ret= ret .. to_add
separator= ", "
end
-- do the integer indices from 0 to n first, in order.
do_value_for_key(0, t[0], true)
for n= 1, #t do
do_value_for_key(n, t[n], false)
end
for k, v in pairs(t) do
local is_integer_key= (type(k) == "number") and (k == math.floor(k)) and k >= 0 and k <= #t
if not is_integer_key then
do_value_for_key(k, v, true)
end
end
ret= ret .. "}"
return ret
end
local slot_conversion= {
[PLAYER_1]= "ProfileSlot_Player1", [PLAYER_2]= "ProfileSlot_Player2",}
function pn_to_profile_slot(pn)
return slot_conversion[pn] or "ProfileSlot_Invalid"
end | mit |
samtaylorblack/black | plugins/mutetime.lua | 1 | 1315 |
local function pre_process(msg)
local hash = 'mute_time:'..msg.chat_id_
if redis:get(hash) and gp_type(msg.chat_id_) == 'channel' and not is_admin(msg) then
tdcli.deleteMessages(msg.chat_id_, {[0] = tonumber(msg.id_)})
end
end
local function run(msg, matches)
if matches[1]:lower() == 'mt' and is_admin(msg) then
local hash = 'mute_time:'..msg.chat_id_
if not matches[2] then
return "_لطفا ساعت و دقیقه را وارد نمایید🕔!_"
else
local hour = string.gsub(matches[2], 'h', '')
local num1 = tonumber(hour) * 3600
local minutes = string.gsub(matches[3], 'm', '')
local num2 = tonumber(minutes) * 60
local num4 = tonumber(num1 + num2)
redis:setex(hash, num4, true)
return "⛔️گروه به مدت: \n`"..matches[2].."` 🕔ساعت\n`"..matches[3].."` 🕔دقیقه \nتعطیل میباشد.️"
end
end
if matches[1]:lower() == 'unmt' and is_admin(msg) then
local hash = 'mute_time:'..msg.chat_id_
redis:del(hash)
return "*✅گروه برای ارسال پیام کاربران باز شد.*"
end
end
return {
patterns = {
'^[/!#]([Mm][Tt])$',
'^[/!#]([Uu][Nn][Mm][Tt])$',
'^[/!#]([Mm][Tt]) (%d+) (%d+)$',
},
run = run,
pre_process = pre_process
}
--end by #@GODILOVEYOUME2#
| gpl-3.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/lups/headers/mathenv.lua | 15 | 3508 | -- $Id: mathenv.lua 3345 2008-12-02 00:03:50Z jk $
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
--
-- file: mathenv.lua
-- brief: parses and processes custom lups effects params, i.e. for the positon: "x,y,z | x=1,y=2,z=x-y"
-- those params can contain any lua code like: "x,y,z | x=random(); if (x>0.5) then y=-0.5 else y=0.5 end; z=math.sin(y^2)"
-- authors: jK
-- last updated: Jan. 2008
--
-- Copyright (C) 2007,2008.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
local MathG = {math = math, rand = math.random, random = math.random, sin = math.sin, cos = math.cos, pi = math.pi,
deg = math.deg, loadstring = loadstring, assert = assert, echo = Spring.Echo};
--local cachedParsedFunctions = {}
local function Split(str, delim, maxNb)
--// Eliminate bad cases...
if str:find(delim) == nil then
return { str }
end
if maxNb == nil or maxNb < 1 then
maxNb = 0 -- No limit
end
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in str:gmatch(pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
if nb == maxNb then break end
end
--// Handle the last field
if nb ~= maxNb then
result[nb + 1] = str:sub(lastPos)
end
return result
end
local loadstring = loadstring
local char = string.char
local type = type
function ParseParamString(strfunc)
--if (cachedParsedFunctions[strfunc]) then
-- return cachedParsedFunctions[strfunc]
--end
local luaCode = "return function() "
local vec_defs,math_defs = {},{}
local params = Split(strfunc or "", "|") --//split math vector components and defintion of additional params (radius etc.)
if (type(params)=="table") then
vec_defs = Split(params[1], ",")
if (params[2]) then math_defs = Split(params[2], ",") end
else vec_defs = params end
--// set user variables (i.e. radius of the effect)
for i=1,#math_defs do
luaCode = luaCode .. math_defs[i] .. ";"
end
--// set return values
for i=1,#vec_defs do
luaCode = luaCode .. "local __" .. char(64+i) .. "=" .. vec_defs[i] .. ";"
end
--// and now insert the return code of those to returned values
luaCode = luaCode .. "return "
for i=1,#vec_defs do
luaCode = luaCode .. " __" .. char(64+i) .. ","
end
luaCode = luaCode .. "nil end"
local status, luaFunc = pcall(loadstring(luaCode))
if (not status) then
print(PRIO_MAJOR,'LUPS: Failed to parse custom param code: ' .. luaFunc);
return function() return 1,2,3,4 end
end;
--cachedParsedFunctions[strfunc] = luaFunc
return luaFunc
end
local setmetatable = setmetatable
local setfenv = setfenv
local pcall = pcall
local meta = {__index={}}
function ProcessParamCode(func, locals)
--// set up safe enviroment
meta.__index = locals
setmetatable( MathG, meta );
setfenv(func, MathG);
--// run generated code
local success,r1,r2,r3,r4 = pcall( func );
setmetatable( MathG, nil );
if (success) then
return r1,r2,r3,r4;
else
print(PRIO_MAJOR,'LUPS: Failed to run custom param code: ' .. r1);
return nil;
end
end | gpl-2.0 |
LanceJenkinZA/prosody-modules | mod_auth_external/mod_auth_external.lua | 31 | 4708 | --
-- Prosody IM
-- Copyright (C) 2010 Waqas Hussain
-- Copyright (C) 2010 Jeff Mitchell
-- Copyright (C) 2013 Mikael Nordfeldth
-- Copyright (C) 2013 Matthew Wild, finally came to fix it all
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local lpty = assert(require "lpty", "mod_auth_external requires lpty: https://code.google.com/p/prosody-modules/wiki/mod_auth_external#Installation");
local usermanager = require "core.usermanager";
local new_sasl = require "util.sasl".new;
local server = require "net.server";
local have_async, async = pcall(require, "util.async");
local log = module._log;
local host = module.host;
local script_type = module:get_option_string("external_auth_protocol", "generic");
local command = module:get_option_string("external_auth_command", "");
local read_timeout = module:get_option_number("external_auth_timeout", 5);
local blocking = module:get_option_boolean("external_auth_blocking", not(have_async and server.event and lpty.getfd));
local auth_processes = module:get_option_number("external_auth_processes", 1);
assert(script_type == "ejabberd" or script_type == "generic", "Config error: external_auth_protocol must be 'ejabberd' or 'generic'");
assert(not host:find(":"), "Invalid hostname");
if not blocking then
log("debug", "External auth in non-blocking mode, yay!")
waiter, guard = async.waiter, async.guarder();
elseif auth_processes > 1 then
log("warn", "external_auth_processes is greater than 1, but we are in blocking mode - reducing to 1");
auth_processes = 1;
end
local ptys = {};
local pty_options = { throw_errors = false, no_local_echo = true, use_path = false };
for i = 1, auth_processes do
ptys[i] = lpty.new(pty_options);
end
local curr_process = 0;
function send_query(text)
curr_process = (curr_process%auth_processes)+1;
local pty = ptys[curr_process];
local finished_with_pty
if not blocking then
finished_with_pty = guard(pty); -- Prevent others from crossing this line while we're busy
end
if not pty:hasproc() then
local status, ret = pty:exitstatus();
if status and (status ~= "exit" or ret ~= 0) then
log("warn", "Auth process exited unexpectedly with %s %d, restarting", status, ret or 0);
return nil;
end
local ok, err = pty:startproc(command);
if not ok then
log("error", "Failed to start auth process '%s': %s", command, err);
return nil;
end
log("debug", "Started auth process");
end
pty:send(text);
if blocking then
return pty:read(read_timeout);
else
local response;
local wait, done = waiter();
server.addevent(pty:getfd(), server.event.EV_READ, function ()
response = pty:read();
done();
return -1;
end);
wait();
finished_with_pty();
return response;
end
end
function do_query(kind, username, password)
if not username then return nil, "not-acceptable"; end
local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password);
local len = #query
if len > 1000 then return nil, "policy-violation"; end
if script_type == "ejabberd" then
local lo = len % 256;
local hi = (len - lo) / 256;
query = string.char(hi, lo)..query;
elseif script_type == "generic" then
query = query..'\n';
end
local response, err = send_query(query);
if not response then
log("warn", "Error while waiting for result from auth process: %s", err or "unknown error");
elseif (script_type == "ejabberd" and response == "\0\2\0\0") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "0") then
return nil, "not-authorized";
elseif (script_type == "ejabberd" and response == "\0\2\0\1") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "1") then
return true;
else
log("warn", "Unable to interpret data from auth process, %s", (response:match("^error:") and response) or ("["..#response.." bytes]"));
return nil, "internal-server-error";
end
end
local host = module.host;
local provider = {};
function provider.test_password(username, password)
return do_query("auth", username, password);
end
function provider.set_password(username, password)
return do_query("setpass", username, password);
end
function provider.user_exists(username)
return do_query("isuser", username);
end
function provider.create_user(username, password) return nil, "Account creation/modification not available."; end
function provider.get_sasl_handler()
local testpass_authentication_profile = {
plain_test = function(sasl, username, password, realm)
return usermanager.test_password(username, realm, password), true;
end,
};
return new_sasl(host, testpass_authentication_profile);
end
module:provides("auth", provider);
| mit |
Ractis/HookAndSlice | scripts/vscripts/DotaHS_MissionManager_CustomLevel.lua | 1 | 5823 |
require( "DotaHS_Common" )
require( "DotaHS_ItemManager" )
require( "DotaHS_GridNavMap" )
require( "DotaHS_SpawnManager" )
require( "DotaHS_SpawnDirector" )
--------------------------------------------------------------------------------
if MissionManager_CustomLevel == nil then
MissionManager_CustomLevel = class({})
end
--------------------------------------------------------------------------------
-- Pre-Initialize
--------------------------------------------------------------------------------
function MissionManager_CustomLevel:PreInitialize( gameConfig )
self._bufferMap = {} -- PlayerID : Array of buffer
self._kvMap = {} -- PlayerID : KV
self._globalConfig = gameConfig
local customLevelConfig = gameConfig.CustomLevel
-- Collect areas
self._areas = {}
for k,v in pairs(customLevelConfig.Areas) do
self._areas[tonumber(k)] = v
end
self:_Log( #self._areas .. " test areas found." )
-- Find StartEnt of Areas
self._startEntMap = {}
for _,v in pairs(Entities:FindAllByClassname( "info_target" )) do
local entName = v:GetName()
for areaID,area in pairs( self._areas ) do
if entName == area.StartFrom then
self._startEntMap[areaID] = v
self:_Log( "StartEntity for Area[" .. areaID .. "] found." )
break
end
end
end
-- Register Commands
Convars:RegisterCommand( "dotahs_custom_level_buffer", function ( _, packet )
self:_AddToBuffer( Convars:GetCommandClient():GetPlayerID(), packet )
end, "", 0 )
Convars:RegisterCommand( "dotahs_custom_level_buffer_end", function ( _ )
self:_EndBuffer( Convars:GetCommandClient():GetPlayerID() )
end, "", 0 )
Convars:RegisterCommand( "dotahs_play_custom_level", function ( _, areaID, difficulty )
self:_PlayLevel( Convars:GetCommandClient():GetPlayerID(), tonumber(areaID), tonumber(difficulty) )
end, "", 0 )
end
--------------------------------------------------------------------------------
-- Initialize
--------------------------------------------------------------------------------
function MissionManager_CustomLevel:Initialize( globalKV )
FireGameEvent( "dotahs_show_leveleditor", {} )
end
--------------------------------------------------------------------------------
-- Play the CustomLevel
--------------------------------------------------------------------------------
function MissionManager_CustomLevel:_PlayLevel( playerID, areaID, difficulty )
if DotaHS_GlobalVars.bGameInProgress then
self:_Log( "Game In Progress. PlayLevel Request has been denied." )
return
end
-- Grab the Start Entity
local startEnt = self._startEntMap[areaID]
if not startEnt then
self:_Log( "StartEntity for Area[" .. areaID .. "] is not found." )
return
end
-- Calculate NumMonsterPools
local levelData = self._kvMap[playerID]
local nMonsterPools = 0
for k,v in pairs(levelData.MonsterPools) do
nMonsterPools = nMonsterPools + 1
end
-- Merge level data
local config = {}
for k,v in pairs( self._globalConfig ) do
config[k] = v -- Shallow copy
end
for k,v in pairs( levelData ) do
config[k] = v -- Merge
end
config.AutoSplitPoolBy = nMonsterPools
if self._areas[areaID].DesiredEnemyDensity then
local oldDensity = config.DesiredEnemyDensity
local newDensity = oldDensity * self._areas[areaID].DesiredEnemyDensity
self:_Log( "EnemyDensity has been modified to " .. newDensity .. " from " .. oldDensity )
config.DesiredEnemyDensity = newDensity
else
self:_Log( "EnemyDensity for this area not found." )
end
--DeepPrintTable( self._globalConfig )
-- Set difficulty
GameRules:SetCustomGameDifficulty( difficulty )
-- Initialize modules
GridNavMap:Initialize( config, startEnt )
SpawnManager:Initialize( config )
SpawnDirector:Initialize( config )
DotaHS_GlobalVars.bGameInProgress = true
FireGameEvent( "dotahs_hide_leveleditor", {} )
-- Teleport to the Testing Area
DotaHS_RefreshPlayers()
DotaHS_ForEachPlayer( function ( playerID, hero )
FindClearSpaceForUnit( hero, startEnt:GetAbsOrigin(), true )
-- PlayerResource:SetCameraTarget( playerID, hero )
for i=hero:GetLevel(), config.StartingLevel-1 do
hero:HeroLevelUp( false )
end
end )
SendToConsole( "dota_camera_center" )
end
--------------------------------------------------------------------------------
-- Buffer
--------------------------------------------------------------------------------
function MissionManager_CustomLevel:_AddToBuffer( playerID, packet )
if not self._bufferMap[playerID] then
self._bufferMap[playerID] = {}
end
if self._kvMap[playerID] then
self._kvMap[playerID] = nil
end
table.insert( self._bufferMap[playerID], packet )
end
function MissionManager_CustomLevel:_EndBuffer( playerID )
if not self._bufferMap[playerID] then
self:_Log( "INVALID BUFFER! PlayerID = " .. playerID )
return
end
local str = table.concat( self._bufferMap[playerID] )
self._bufferMap[playerID] = nil
str = str:gsub( "'", '"' )
-- Save KV file
local timestamp = GetSystemDate() .. "-" .. GetSystemTime()
timestamp = timestamp:gsub(":",""):gsub("/","")
local steamID = PlayerResource:GetSteamAccountID( playerID )
local fileName = "addons/dotahs_custom_level/" .. timestamp .. "_player_" .. steamID .. ".txt"
InitLogFile( fileName, "" )
AppendToLogFile( fileName, str )
self:_Log( "Wrote KV file to " .. fileName )
-- Load KV file
local kv = LoadKeyValues( fileName )
-- print( str )
self:_Log( "BufferSize = " .. #str .. ", PlayerID = " .. playerID )
DeepPrintTable( kv )
self._kvMap[playerID] = kv
-- Play this LEVEL
-- self:_PlayLevel( 1, kv )
end
--------------------------------------------------------------------------------
-- UTILS
--------------------------------------------------------------------------------
function MissionManager_CustomLevel:_Log( text )
print( "[Mission/CustomLevel] " .. text )
end
| mit |
mnemnion/grym | lib/pl/List.lua | 1 | 15794 | --- Python-style list class.
--
-- **Please Note**: methods that change the list will return the list.
-- This is to allow for method chaining, but please note that `ls = ls:sort()`
-- does not mean that a new copy of the list is made. In-place (mutable) methods
-- are marked as returning 'the list' in this documentation.
--
-- See the Guide for further @{02-arrays.md.Python_style_Lists|discussion}
--
-- See <a href="http://www.python.org/doc/current/tut/tut.html">http://www.python.org/doc/current/tut/tut.html</a>, section 5.1
--
-- **Note**: The comments before some of the functions are from the Python docs
-- and contain Python code.
--
-- Written for Lua version Nick Trout 4.0; Redone for Lua 5.1, Steve Donovan.
--
-- Dependencies: `pl.utils`, `pl.tablex`, `pl.class`
-- @classmod pl.List
-- @pragma nostrip
local tinsert,tremove,concat,tsort = table.insert,table.remove,table.concat,table.sort
local setmetatable, getmetatable,type,tostring,string = setmetatable,getmetatable,type,tostring,string
local tablex = require 'pl.tablex'
local filter,imap,imap2,reduce,transform,tremovevalues = tablex.filter,tablex.imap,tablex.imap2,tablex.reduce,tablex.transform,tablex.removevalues
local tsub = tablex.sub
local utils = require 'pl.utils'
local class = require 'pl.class'
local array_tostring,split,assert_arg,function_arg = utils.array_tostring,utils.split,utils.assert_arg,utils.function_arg
local normalize_slice = tablex._normalize_slice
-- metatable for our list and map objects has already been defined..
local Multimap = utils.stdmt.MultiMap
local List = utils.stdmt.List
local iter
class(nil,nil,List)
-- we want the result to be _covariant_, i.e. t must have type of obj if possible
local function makelist (t,obj)
local klass = List
if obj then
klass = getmetatable(obj)
end
return setmetatable(t,klass)
end
local function simple_table(t)
return type(t) == 'table' and not getmetatable(t) and #t > 0
end
function List._create (src)
if simple_table(src) then return src end
end
function List:_init (src)
if self == src then return end -- existing table used as self!
if src then
for v in iter(src) do
tinsert(self,v)
end
end
end
--- Create a new list. Can optionally pass a table;
-- passing another instance of List will cause a copy to be created;
-- this will return a plain table with an appropriate metatable.
-- we pass anything which isn't a simple table to iterate() to work out
-- an appropriate iterator
-- @see List.iterate
-- @param[opt] t An optional list-like table
-- @return a new List
-- @usage ls = List(); ls = List {1,2,3,4}
-- @function List.new
List.new = List
--- Make a copy of an existing list.
-- The difference from a plain 'copy constructor' is that this returns
-- the actual List subtype.
function List:clone()
local ls = makelist({},self)
ls:extend(self)
return ls
end
---Add an item to the end of the list.
-- @param i An item
-- @return the list
function List:append(i)
tinsert(self,i)
return self
end
List.push = tinsert
--- Extend the list by appending all the items in the given list.
-- equivalent to 'a[len(a):] = L'.
-- @tparam List L Another List
-- @return the list
function List:extend(L)
assert_arg(1,L,'table')
for i = 1,#L do tinsert(self,L[i]) end
return self
end
--- Insert an item at a given position. i is the index of the
-- element before which to insert.
-- @int i index of element before whichh to insert
-- @param x A data item
-- @return the list
function List:insert(i, x)
assert_arg(1,i,'number')
tinsert(self,i,x)
return self
end
--- Insert an item at the begining of the list.
-- @param x a data item
-- @return the list
function List:put (x)
return self:insert(1,x)
end
--- Remove an element given its index.
-- (equivalent of Python's del s[i])
-- @int i the index
-- @return the list
function List:remove (i)
assert_arg(1,i,'number')
tremove(self,i)
return self
end
--- Remove the first item from the list whose value is given.
-- (This is called 'remove' in Python; renamed to avoid confusion
-- with table.remove)
-- Return nil if there is no such item.
-- @param x A data value
-- @return the list
function List:remove_value(x)
for i=1,#self do
if self[i]==x then tremove(self,i) return self end
end
return self
end
--- Remove the item at the given position in the list, and return it.
-- If no index is specified, a:pop() returns the last item in the list.
-- The item is also removed from the list.
-- @int[opt] i An index
-- @return the item
function List:pop(i)
if not i then i = #self end
assert_arg(1,i,'number')
return tremove(self,i)
end
List.get = List.pop
--- Return the index in the list of the first item whose value is given.
-- Return nil if there is no such item.
-- @function List:index
-- @param x A data value
-- @int[opt=1] idx where to start search
-- @return the index, or nil if not found.
local tfind = tablex.find
List.index = tfind
--- does this list contain the value?.
-- @param x A data value
-- @return true or false
function List:contains(x)
return tfind(self,x) and true or false
end
--- Return the number of times value appears in the list.
-- @param x A data value
-- @return number of times x appears
function List:count(x)
local cnt=0
for i=1,#self do
if self[i]==x then cnt=cnt+1 end
end
return cnt
end
--- Sort the items of the list, in place.
-- @func[opt='<'] cmp an optional comparison function
-- @return the list
function List:sort(cmp)
if cmp then cmp = function_arg(1,cmp) end
tsort(self,cmp)
return self
end
--- return a sorted copy of this list.
-- @func[opt='<'] cmp an optional comparison function
-- @return a new list
function List:sorted(cmp)
return List(self):sort(cmp)
end
--- Reverse the elements of the list, in place.
-- @return the list
function List:reverse()
local t = self
local n = #t
for i = 1,n/2 do
t[i],t[n] = t[n],t[i]
n = n - 1
end
return self
end
--- return the minimum and the maximum value of the list.
-- @return minimum value
-- @return maximum value
function List:minmax()
local vmin,vmax = 1e70,-1e70
for i = 1,#self do
local v = self[i]
if v < vmin then vmin = v end
if v > vmax then vmax = v end
end
return vmin,vmax
end
--- Emulate list slicing. like 'list[first:last]' in Python.
-- If first or last are negative then they are relative to the end of the list
-- eg. slice(-2) gives last 2 entries in a list, and
-- slice(-4,-2) gives from -4th to -2nd
-- @param first An index
-- @param last An index
-- @return a new List
function List:slice(first,last)
return tsub(self,first,last)
end
--- empty the list.
-- @return the list
function List:clear()
for i=1,#self do tremove(self) end
return self
end
local eps = 1.0e-10
--- Emulate Python's range(x) function.
-- Include it in List table for tidiness
-- @int start A number
-- @int[opt] finish A number greater than start; if absent,
-- then start is 1 and finish is start
-- @int[opt=1] incr an increment (may be less than 1)
-- @return a List from start .. finish
-- @usage List.range(0,3) == List{0,1,2,3}
-- @usage List.range(4) = List{1,2,3,4}
-- @usage List.range(5,1,-1) == List{5,4,3,2,1}
function List.range(start,finish,incr)
if not finish then
finish = start
start = 1
end
if incr then
assert_arg(3,incr,'number')
if math.ceil(incr) ~= incr then finish = finish + eps end
else
incr = 1
end
assert_arg(1,start,'number')
assert_arg(2,finish,'number')
local t = List()
for i=start,finish,incr do tinsert(t,i) end
return t
end
--- list:len() is the same as #list.
function List:len()
return #self
end
-- Extended operations --
--- Remove a subrange of elements.
-- equivalent to 'del s[i1:i2]' in Python.
-- @int i1 start of range
-- @int i2 end of range
-- @return the list
function List:chop(i1,i2)
return tremovevalues(self,i1,i2)
end
--- Insert a sublist into a list
-- equivalent to 's[idx:idx] = list' in Python
-- @int idx index
-- @tparam List list list to insert
-- @return the list
-- @usage l = List{10,20}; l:splice(2,{21,22}); assert(l == List{10,21,22,20})
function List:splice(idx,list)
assert_arg(1,idx,'number')
idx = idx - 1
local i = 1
for v in iter(list) do
tinsert(self,i+idx,v)
i = i + 1
end
return self
end
--- general slice assignment s[i1:i2] = seq.
-- @int i1 start index
-- @int i2 end index
-- @tparam List seq a list
-- @return the list
function List:slice_assign(i1,i2,seq)
assert_arg(1,i1,'number')
assert_arg(1,i2,'number')
i1,i2 = normalize_slice(self,i1,i2)
if i2 >= i1 then self:chop(i1,i2) end
self:splice(i1,seq)
return self
end
--- concatenation operator.
-- @within metamethods
-- @tparam List L another List
-- @return a new list consisting of the list with the elements of the new list appended
function List:__concat(L)
assert_arg(1,L,'table')
local ls = self:clone()
ls:extend(L)
return ls
end
--- equality operator ==. True iff all elements of two lists are equal.
-- @within metamethods
-- @tparam List L another List
-- @return true or false
function List:__eq(L)
if #self ~= #L then return false end
for i = 1,#self do
if self[i] ~= L[i] then return false end
end
return true
end
--- join the elements of a list using a delimiter.
-- This method uses tostring on all elements.
-- @string[opt=''] delim a delimiter string, can be empty.
-- @return a string
function List:join (delim)
delim = delim or ''
assert_arg(1,delim,'string')
return concat(array_tostring(self),delim)
end
--- join a list of strings. <br>
-- Uses `table.concat` directly.
-- @function List:concat
-- @string[opt=''] delim a delimiter
-- @return a string
List.concat = concat
local function tostring_q(val)
local s = tostring(val)
if type(val) == 'string' then
s = '"'..s..'"'
end
return s
end
--- how our list should be rendered as a string. Uses join().
-- @within metamethods
-- @see List:join
function List:__tostring()
return '{'..self:join(',',tostring_q)..'}'
end
--- call the function on each element of the list.
-- @func fun a function or callable object
-- @param ... optional values to pass to function
function List:foreach (fun,...)
fun = function_arg(1,fun)
for i = 1,#self do
fun(self[i],...)
end
end
local function lookup_fun (obj,name)
local f = obj[name]
if not f then error(type(obj).." does not have method "..name,3) end
return f
end
--- call the named method on each element of the list.
-- @string name the method name
-- @param ... optional values to pass to function
function List:foreachm (name,...)
for i = 1,#self do
local obj = self[i]
local f = lookup_fun(obj,name)
f(obj,...)
end
end
--- create a list of all elements which match a function.
-- @func fun a boolean function
-- @param[opt] arg optional argument to be passed as second argument of the predicate
-- @return a new filtered list.
function List:filter (fun,arg)
return makelist(filter(self,fun,arg),self)
end
--- split a string using a delimiter.
-- @string s the string
-- @string[opt] delim the delimiter (default spaces)
-- @return a List of strings
-- @see pl.utils.split
function List.split (s,delim)
assert_arg(1,s,'string')
return makelist(split(s,delim))
end
--- apply a function to all elements.
-- Any extra arguments will be passed to the function.
-- @func fun a function of at least one argument
-- @param ... arbitrary extra arguments.
-- @return a new list: {f(x) for x in self}
-- @usage List{'one','two'}:map(string.upper) == {'ONE','TWO'}
-- @see pl.tablex.imap
function List:map (fun,...)
return makelist(imap(fun,self,...),self)
end
--- apply a function to all elements, in-place.
-- Any extra arguments are passed to the function.
-- @func fun A function that takes at least one argument
-- @param ... arbitrary extra arguments.
-- @return the list.
function List:transform (fun,...)
transform(fun,self,...)
return self
end
--- apply a function to elements of two lists.
-- Any extra arguments will be passed to the function
-- @func fun a function of at least two arguments
-- @tparam List ls another list
-- @param ... arbitrary extra arguments.
-- @return a new list: {f(x,y) for x in self, for x in arg1}
-- @see pl.tablex.imap2
function List:map2 (fun,ls,...)
return makelist(imap2(fun,self,ls,...),self)
end
--- apply a named method to all elements.
-- Any extra arguments will be passed to the method.
-- @string name name of method
-- @param ... extra arguments
-- @return a new list of the results
-- @see pl.seq.mapmethod
function List:mapm (name,...)
local res = {}
for i = 1,#self do
local val = self[i]
local fn = lookup_fun(val,name)
res[i] = fn(val,...)
end
return makelist(res,self)
end
local function composite_call (method,f)
return function(self,...)
return self[method](self,f,...)
end
end
function List.default_map_with(T)
return function(self,name)
local m
if T then
local f = lookup_fun(T,name)
m = composite_call('map',f)
else
m = composite_call('mapn',name)
end
getmetatable(self)[name] = m -- and cache..
return m
end
end
List.default_map = List.default_map_with
--- 'reduce' a list using a binary function.
-- @func fun a function of two arguments
-- @return result of the function
-- @see pl.tablex.reduce
function List:reduce (fun)
return reduce(fun,self)
end
--- partition a list using a classifier function.
-- The function may return nil, but this will be converted to the string key '<nil>'.
-- @func fun a function of at least one argument
-- @param ... will also be passed to the function
-- @treturn MultiMap a table where the keys are the returned values, and the values are Lists
-- of values where the function returned that key.
-- @see pl.MultiMap
function List:partition (fun,...)
fun = function_arg(1,fun)
local res = {}
for i = 1,#self do
local val = self[i]
local klass = fun(val,...)
if klass == nil then klass = '<nil>' end
if not res[klass] then res[klass] = List() end
res[klass]:append(val)
end
return setmetatable(res,Multimap)
end
--- return an iterator over all values.
function List:iter ()
return iter(self)
end
--- Create an iterator over a seqence.
-- This captures the Python concept of 'sequence'.
-- For tables, iterates over all values with integer indices.
-- @param seq a sequence; a string (over characters), a table, a file object (over lines) or an iterator function
-- @usage for x in iterate {1,10,22,55} do io.write(x,',') end ==> 1,10,22,55
-- @usage for ch in iterate 'help' do do io.write(ch,' ') end ==> h e l p
function List.iterate(seq)
if type(seq) == 'string' then
local idx = 0
local n = #seq
local sub = string.sub
return function ()
idx = idx + 1
if idx > n then return nil
else
return sub(seq,idx,idx)
end
end
elseif type(seq) == 'table' then
local idx = 0
local n = #seq
return function()
idx = idx + 1
if idx > n then return nil
else
return seq[idx]
end
end
elseif type(seq) == 'function' then
return seq
elseif type(seq) == 'userdata' and io.type(seq) == 'file' then
return seq:lines()
end
end
iter = List.iterate
return List
| mit |
Anarchid/Zero-K | LuaUI/Widgets/unit_marker.lua | 4 | 4339 | function widget:GetInfo() return {
name = "Unit Marker Zero-K",
desc = "[v1.3.10] Marks spotted buildings of interest and commander corpse.",
author = "Sprung",
date = "2015-04-11",
license = "GNU GPL v2",
layer = -1,
enabled = true,
} end
local knownUnits = {}
local unitList = {}
local markingActive = false
if VFS.FileExists("LuaUI/Configs/unit_marker_local.lua", nil, VFS.RAW) then
unitList = VFS.Include("LuaUI/Configs/unit_marker_local.lua", nil, VFS.RAW)
else
unitList = VFS.Include("LuaUI/Configs/unit_marker.lua")
end
options_path = 'Settings/Interface/Unit Marker'
options_order = { 'enableAll', 'disableAll', 'unitslabel'}
options = {
enableAll = {
type='button',
name= "Enable All",
desc = "Marks all listed units.",
path = options_path .. "/Presets",
OnChange = function ()
for i = 1, #options_order do
local opt = options_order[i]
local find = string.find(opt, "_mark")
local name = find and string.sub(opt,0,find-1)
local ud = name and UnitDefNames[name]
if ud then
options[opt].value = true
end
end
for unitDefID,_ in pairs(unitList) do
unitList[unitDefID].active = true
end
if not markingActive then
widgetHandler:UpdateCallIn('UnitEnteredLos')
markingActive = true
end
end,
noHotkey = true,
},
disableAll = {
type='button',
name= "Disable All",
desc = "Mark nothing.",
path = options_path .. "/Presets",
OnChange = function ()
for i = 1, #options_order do
local opt = options_order[i]
local find = string.find(opt, "_mark")
local name = find and string.sub(opt,0,find-1)
local ud = name and UnitDefNames[name]
if ud then
options[opt].value = false
end
end
for unitDefID,_ in pairs(unitList) do
unitList[unitDefID].active = false
end
if markingActive then
widgetHandler:RemoveCallIn('UnitEnteredLos')
markingActive = false
end
end,
noHotkey = true,
},
unitslabel = {name = "unitslabel", type = 'label', value = "Individual Toggles", path = options_path},
}
for unitDefID,_ in pairs(unitList) do
local ud = (not unitDefID) or UnitDefs[unitDefID]
if ud then
options[ud.name .. "_mark"] = {
name = " " .. Spring.Utilities.GetHumanName(ud) or "",
type = 'bool',
value = false,
OnChange = function (self)
unitList[unitDefID].active = self.value
if self.value and not markingActive then
widgetHandler:UpdateCallIn('UnitEnteredLos')
markingActive = true
end
end,
noHotkey = true,
}
options_order[#options_order+1] = ud.name .. "_mark"
end
end
function widget:Initialize()
if not markingActive then
widgetHandler:RemoveCallIn("UnitEnteredLos")
end
if Spring.GetSpectatingState() then
widgetHandler:RemoveCallIn("UnitEnteredLos")
elseif markingActive then
widgetHandler:UpdateCallIn('UnitEnteredLos')
end
end
function widget:PlayerChanged ()
widget:Initialize ()
end
function widget:TeamDied ()
widget:Initialize ()
end
function widget:UnitEnteredLos (unitID, teamID)
if Spring.IsUnitAllied(unitID) or Spring.GetSpectatingState() then return end
local unitDefID = Spring.GetUnitDefID (unitID)
if not unitDefID then return end -- safety just in case
if unitList[unitDefID] and unitList[unitDefID].active and ((not knownUnits[unitID]) or (knownUnits[unitID] ~= unitDefID)) then
local x, y, z = Spring.GetUnitPosition(unitID)
local markerText = unitList[unitDefID].markerText or Spring.Utilities.GetHumanName(UnitDefs[unitDefID])
if not unitList[unitDefID].mark_each_appearance then
knownUnits[unitID] = unitDefID
end
if unitList[unitDefID].show_owner then
local _,playerID,_,isAI = Spring.GetTeamInfo(teamID, false)
local owner_name
if isAI then
local _,botName,_,botType = Spring.GetAIInfo(teamID)
owner_name = (botType or "AI") .." - " .. (botName or "unnamed")
else
owner_name = Spring.GetPlayerInfo(playerID, false) or "nobody"
end
markerText = markerText .. " (" .. owner_name .. ")"
end
local _, _, _, _, buildProgress = Spring.GetUnitHealth(unitID)
if buildProgress < 1 then
markerText = markerText .. " (" .. math.floor(100 * buildProgress) .. "%)"
end
Spring.MarkerAddPoint (x, y, z, markerText, true)
end
end
function widget:UnitDestroyed(unitID, unitDefID, unitTeam)
knownUnits[unitID] = nil
end
| gpl-2.0 |
futzle/MiOS-CombinationSwitch | L_CombinationSwitch1Plugin_WeatherCondition.lua | 1 | 3849 | module ("L_CombinationSwitch1Plugin_WeatherCondition", package.seeall)
local MAIN
local WEATHER_SERVICE_ID = "urn:upnp-micasaverde-com:serviceId:Weather1"
local WEATHER_VARIABLE_CONDITION = "Condition"
local INDEX_SWITCH_DEVICE_ID = "DeviceId"
local INDEX_SWITCH_CONDITION = "MatchCondition"
function initialize(main)
MAIN = main
local supportedDevices = MAIN.getDevicesWithService(nil, WEATHER_SERVICE_ID)
if (#supportedDevices == 0) then
return false
end
return true
end
function name()
return "Weather Conditons"
end
function configureState(combinationDeviceId, index)
local supportedDevices = MAIN.getDevicesWithService(combinationDeviceId, WEATHER_SERVICE_ID)
local jsSelectedDevice = MAIN.jsSetupState("selectedDevice", combinationDeviceId, MAIN.pluginId, index .. INDEX_SWITCH_DEVICE_ID, supportedDevices[1])
local jsMatchCondition = MAIN.jsSetupState("matchCondition", combinationDeviceId, MAIN.pluginId, index .. INDEX_SWITCH_CONDITION, [["Rain"]])
local result = "(function() {" ..
jsSelectedDevice ..
jsMatchCondition ..
"return selectedDevice + '=' + matchCondition; " ..
"})()"
return result;
end
function configureSelect(combinationDeviceId, index, state)
local selectedDevice, matchCondition = state:match("(%d+)=(.+)")
local supportedDevices = MAIN.getDevicesWithService(combinationDeviceId, WEATHER_SERVICE_ID)
local deviceSelectElement = MAIN.htmlSelectDevice(supportedDevices, selectedDevice, combinationDeviceId, MAIN.pluginId, index .. INDEX_SWITCH_DEVICE_ID)
local possibleConditions = {
"Chance of Showers",
"Chance of Snow",
"Chance of Storm",
"Clear",
"Cloudy",
"Drizzle",
"Flurries",
"Fog",
"Freezing Drizzle",
"Freezing Rain",
"Haze",
"Heavy Rain",
"Ice/Snow",
"Isolated Thunderstorms",
"Light Rain",
"Light Snow",
"Mostly Cloudy",
"Mostly Sunny",
"Overcast",
"Partly Cloudy",
"Partly Sunny",
"Rain",
"Rain and Snow",
"Rain Showers",
"Scattered Showers",
"Showers",
"Snow",
"Snow Showers",
"Snow Storm",
"Sunny",
"Thunderstorm",
"Windy"
}
local result = deviceSelectElement .. " is <select onchange='warnSave(); set_device_state(" .. combinationDeviceId .. ", \"" .. MAIN.pluginId .. "\", \"" .. index .. INDEX_SWITCH_CONDITION .. "\", jQuery(this).val(), 0);'>"
for i = 1, #possibleConditions do
result = result .. "<option value='" .. possibleConditions[i] .. "'"
if (possibleConditions[i] == matchCondition) then
result = result .. " selected='selected'"
end
result = result .. ">" .. possibleConditions[i] .. "</option>"
end
result = result .. "</select>"
return result
end
function register(combinationDeviceId, index)
MAIN.debug("Registering watch index " .. index)
local watchDeviceId = luup.variable_get(MAIN.pluginId, index .. INDEX_SWITCH_DEVICE_ID, combinationDeviceId)
if (watchDeviceId == nil) then return false end
local watchDeviceIdNum = tonumber(watchDeviceId)
if (watchDeviceIdNum >= 0 and luup.devices[watchDeviceIdNum]) then
local watchDeviceName = luup.devices[watchDeviceIdNum].description
local watchCondition = luup.variable_get(MAIN.pluginId, index .. INDEX_SWITCH_CONDITION, DEVICE_ID)
MAIN.debug("Watching " .. watchDeviceName .. " [" .. watchDeviceId .. "] " ..
" Weather condition: " .. watchCondition)
luup.variable_watch("watch_callback", WEATHER_SERVICE_ID, WEATHER_VARIABLE_CONDITION, watchDeviceIdNum)
end
return true
end
function count(combinationDeviceId, index)
local watchDeviceId = luup.variable_get(MAIN.pluginId, index .. INDEX_SWITCH_DEVICE_ID, combinationDeviceId)
local watchDeviceIdNum = tonumber(watchDeviceId)
local watchCondition = luup.variable_get(MAIN.pluginId, index .. INDEX_SWITCH_CONDITION, DEVICE_ID)
return luup.variable_get(WEATHER_SERVICE_ID, WEATHER_VARIABLE_CONDITION, watchDeviceIdNum) == watchCondition and 1 or 0
end
| gpl-2.0 |
chukong/sdkbox-facebook-sample-v2 | samples/Lua/TestLua/Resources/luaScript/LayerTest/LayerTest.lua | 6 | 22631 | local scheduler = CCDirector:sharedDirector():getScheduler()
local kTagLayer = 1
local function createLayerDemoLayer(title, subtitle)
local layer = CCLayer:create()
Helper.initWithLayer(layer)
local titleStr = title == nil and "No title" or title
local subTitleStr = subtitle == nil and "" or subtitle
Helper.titleLabel:setString(titleStr)
Helper.subtitleLabel:setString(subTitleStr)
-- local prev = {x = 0, y = 0}
-- local function onTouchEvent(eventType, x, y)
-- if eventType == "began" then
-- prev.x = x
-- prev.y = y
-- return true
-- elseif eventType == "moved" then
-- local node = layer:getChildByTag(kTagTileMap)
-- local newX = node:getPositionX()
-- local newY = node:getPositionY()
-- local diffX = x - prev.x
-- local diffY = y - prev.y
-- node:setPosition( ccpAdd(ccp(newX, newY), ccp(diffX, diffY)) )
-- prev.x = x
-- prev.y = y
-- end
-- end
-- layer:setTouchEnabled(true)
-- layer:registerScriptTouchHandler(onTouchEvent)
return layer
end
--#pragma mark - Cascading support extensions
local function setEnableRecursiveCascading(node, enable)
if node == nil then
-- cclog("node == nil, return directly")
return
end
if node.__CCRGBAProtocol__ ~= nil then
node.__CCRGBAProtocol__:setCascadeColorEnabled(enable)
node.__CCRGBAProtocol__:setCascadeOpacityEnabled(enable)
end
local obj = nil
local children = node:getChildren()
if children == nil then
-- cclog("children is nil")
return
end
local i = 0
local len = children:count()
for i = 0, len-1, 1 do
local child = tolua.cast(children:objectAtIndex(i), "CCNode")
setEnableRecursiveCascading(child, enable)
end
end
-- LayerTestCascadingOpacityA
local function LayerTestCascadingOpacityA()
local ret = createLayerDemoLayer("LayerRGBA: cascading opacity")
local s = CCDirector:sharedDirector():getWinSize()
local layer1 = CCLayerRGBA:create()
local sister1 = CCSprite:create("Images/grossinis_sister1.png")
local sister2 = CCSprite:create("Images/grossinis_sister2.png")
local label = CCLabelBMFont:create("Test", "fonts/bitmapFontTest.fnt")
layer1:addChild(sister1)
layer1:addChild(sister2)
layer1:addChild(label)
ret:addChild( layer1, 0, kTagLayer)
sister1:setPosition( ccp( s.width*1/3, s.height/2))
sister2:setPosition( ccp( s.width*2/3, s.height/2))
label:setPosition( ccp( s.width/2, s.height/2))
local arr = CCArray:create()
arr:addObject(CCFadeTo:create(4, 0))
arr:addObject(CCFadeTo:create(4, 255))
arr:addObject(CCDelayTime:create(1))
layer1:runAction(CCRepeatForever:create(CCSequence:create(arr)))
arr = CCArray:create()
arr:addObject(CCFadeTo:create(2, 0))
arr:addObject(CCFadeTo:create(2, 255))
arr:addObject(CCFadeTo:create(2, 0))
arr:addObject(CCFadeTo:create(2, 255))
arr:addObject(CCDelayTime:create(1))
sister1:runAction(CCRepeatForever:create(CCSequence:create(arr)))
-- Enable cascading in scene
setEnableRecursiveCascading(ret, true)
return ret
end
-- LayerTestCascadingOpacityB
local function LayerTestCascadingOpacityB()
local ret = createLayerDemoLayer("CCLayerColor: cascading opacity")
local s = CCDirector:sharedDirector():getWinSize()
local layer1 = CCLayerColor:create(ccc4(192, 0, 0, 255), s.width, s.height/2)
layer1:setCascadeColorEnabled(false)
layer1:setPosition( ccp(0, s.height/2))
local sister1 = CCSprite:create("Images/grossinis_sister1.png")
local sister2 = CCSprite:create("Images/grossinis_sister2.png")
local label = CCLabelBMFont:create("Test", "fonts/bitmapFontTest.fnt")
layer1:addChild(sister1)
layer1:addChild(sister2)
layer1:addChild(label)
ret:addChild( layer1, 0, kTagLayer)
sister1:setPosition( ccp( s.width*1/3, 0))
sister2:setPosition( ccp( s.width*2/3, 0))
label:setPosition( ccp( s.width/2, 0))
local arr = CCArray:create()
arr:addObject(CCFadeTo:create(4, 0))
arr:addObject(CCFadeTo:create(4, 255))
arr:addObject(CCDelayTime:create(1))
layer1:runAction(CCRepeatForever:create(CCSequence:create(arr)))
arr = CCArray:create()
arr:addObject(CCFadeTo:create(2, 0))
arr:addObject(CCFadeTo:create(2, 255))
arr:addObject(CCFadeTo:create(2, 0))
arr:addObject(CCFadeTo:create(2, 255))
arr:addObject(CCDelayTime:create(1))
sister1:runAction(CCRepeatForever:create(CCSequence:create(arr)))
-- Enable cascading in scene
setEnableRecursiveCascading(ret, true)
return ret
end
-- LayerTestCascadingOpacityC
local function LayerTestCascadingOpacityC()
local ret = createLayerDemoLayer("CCLayerColor: non-cascading opacity")
local s = CCDirector:sharedDirector():getWinSize()
local layer1 = CCLayerColor:create(ccc4(192, 0, 0, 255), s.width, s.height/2)
layer1:setCascadeColorEnabled(false)
layer1:setCascadeOpacityEnabled(false)
layer1:setPosition( ccp(0, s.height/2))
local sister1 = CCSprite:create("Images/grossinis_sister1.png")
local sister2 = CCSprite:create("Images/grossinis_sister2.png")
local label = CCLabelBMFont:create("Test", "fonts/bitmapFontTest.fnt")
layer1:addChild(sister1)
layer1:addChild(sister2)
layer1:addChild(label)
ret:addChild( layer1, 0, kTagLayer)
sister1:setPosition( ccp( s.width*1/3, 0))
sister2:setPosition( ccp( s.width*2/3, 0))
label:setPosition( ccp( s.width/2, 0))
local arr = CCArray:create()
arr:addObject(CCFadeTo:create(4, 0))
arr:addObject(CCFadeTo:create(4, 255))
arr:addObject(CCDelayTime:create(1))
layer1:runAction(
CCRepeatForever:create(
CCSequence:create(arr
)))
arr = CCArray:create()
arr:addObject(CCFadeTo:create(2, 0))
arr:addObject(CCFadeTo:create(2, 255))
arr:addObject(CCFadeTo:create(2, 0))
arr:addObject(CCFadeTo:create(2, 255))
arr:addObject(CCDelayTime:create(1))
sister1:runAction(
CCRepeatForever:create(
CCSequence:create(arr)))
return ret
end
--#pragma mark Example LayerTestCascadingColor
-- LayerTestCascadingColorA
local function LayerTestCascadingColorA()
local ret = createLayerDemoLayer("LayerRGBA: cascading color")
local s = CCDirector:sharedDirector():getWinSize()
local layer1 = CCLayerRGBA:create()
local sister1 = CCSprite:create("Images/grossinis_sister1.png")
local sister2 = CCSprite:create("Images/grossinis_sister2.png")
local label = CCLabelBMFont:create("Test", "fonts/bitmapFontTest.fnt")
layer1:addChild(sister1)
layer1:addChild(sister2)
layer1:addChild(label)
ret:addChild( layer1, 0, kTagLayer)
sister1:setPosition( ccp( s.width*1/3, s.height/2))
sister2:setPosition( ccp( s.width*2/3, s.height/2))
label:setPosition( ccp( s.width/2, s.height/2))
local arr = CCArray:create()
arr:addObject(CCTintTo:create(6, 255, 0, 255))
arr:addObject(CCTintTo:create(6, 255, 255, 255))
arr:addObject(CCDelayTime:create(1))
layer1:runAction(
CCRepeatForever:create(
CCSequence:create(arr
)))
arr = CCArray:create()
arr:addObject(CCTintTo:create(2, 255, 255, 0))
arr:addObject(CCTintTo:create(2, 255, 255, 255))
arr:addObject(CCTintTo:create(2, 0, 255, 255))
arr:addObject(CCTintTo:create(2, 255, 255, 255))
arr:addObject(CCTintTo:create(2, 255, 0, 255))
arr:addObject(CCTintTo:create(2, 255, 255, 255))
arr:addObject(CCDelayTime:create(1))
sister1:runAction(
CCRepeatForever:create(
CCSequence:create(
arr)))
-- Enable cascading in scene
setEnableRecursiveCascading(ret, true)
return ret
end
-- LayerTestCascadingColorB
local function LayerTestCascadingColorB()
local ret = createLayerDemoLayer("CCLayerColor: cascading color")
local s = CCDirector:sharedDirector():getWinSize()
local layer1 = CCLayerColor:create(ccc4(255, 255, 255, 255), s.width, s.height/2)
layer1:setPosition( ccp(0, s.height/2))
local sister1 = CCSprite:create("Images/grossinis_sister1.png")
local sister2 = CCSprite:create("Images/grossinis_sister2.png")
local label = CCLabelBMFont:create("Test", "fonts/bitmapFontTest.fnt")
layer1:addChild(sister1)
layer1:addChild(sister2)
layer1:addChild(label)
ret:addChild( layer1, 0, kTagLayer)
sister1:setPosition( ccp( s.width*1/3, 0))
sister2:setPosition( ccp( s.width*2/3, 0))
label:setPosition( ccp( s.width/2, 0))
local arr = CCArray:create()
arr:addObject(CCTintTo:create(6, 255, 0, 255))
arr:addObject(CCTintTo:create(6, 255, 255, 255))
arr:addObject(CCDelayTime:create(1))
layer1:runAction(
CCRepeatForever:create(
CCSequence:create(
arr)))
arr = CCArray:create()
arr:addObject(CCTintTo:create(2, 255, 255, 0))
arr:addObject(CCTintTo:create(2, 255, 255, 255))
arr:addObject(CCTintTo:create(2, 0, 255, 255))
arr:addObject(CCTintTo:create(2, 255, 255, 255))
arr:addObject(CCTintTo:create(2, 255, 0, 255))
arr:addObject(CCTintTo:create(2, 255, 255, 255))
arr:addObject(CCDelayTime:create(1))
sister1:runAction(
CCRepeatForever:create(
CCSequence:create(
arr)))
-- Enable cascading in scene
setEnableRecursiveCascading(ret, true)
return ret
end
-- LayerTestCascadingColorC
local function LayerTestCascadingColorC()
local ret = createLayerDemoLayer("CCLayerColor: non-cascading color")
local s = CCDirector:sharedDirector():getWinSize()
local layer1 = CCLayerColor:create(ccc4(255, 255, 255, 255), s.width, s.height/2)
layer1:setCascadeColorEnabled(false)
layer1:setPosition( ccp(0, s.height/2))
local sister1 = CCSprite:create("Images/grossinis_sister1.png")
local sister2 = CCSprite:create("Images/grossinis_sister2.png")
local label = CCLabelBMFont:create("Test", "fonts/bitmapFontTest.fnt")
layer1:addChild(sister1)
layer1:addChild(sister2)
layer1:addChild(label)
ret:addChild( layer1, 0, kTagLayer)
sister1:setPosition( ccp( s.width*1/3, 0))
sister2:setPosition( ccp( s.width*2/3, 0))
label:setPosition( ccp( s.width/2, 0))
local arr = CCArray:create()
arr:addObject(CCTintTo:create(6, 255, 0, 255))
arr:addObject(CCTintTo:create(6, 255, 255, 255))
arr:addObject(CCDelayTime:create(1))
layer1:runAction(
CCRepeatForever:create(
CCSequence:create(
arr)))
arr = CCArray:create()
arr:addObject(CCTintTo:create(2, 255, 255, 0))
arr:addObject(CCTintTo:create(2, 255, 255, 255))
arr:addObject(CCTintTo:create(2, 0, 255, 255))
arr:addObject(CCTintTo:create(2, 255, 255, 255))
arr:addObject(CCTintTo:create(2, 255, 0, 255))
arr:addObject(CCTintTo:create(2, 255, 255, 255))
arr:addObject(CCDelayTime:create(1))
sister1:runAction(
CCRepeatForever:create(
CCSequence:create(
arr)))
return ret
end
--------------------------------------------------------------------
--
-- LayerTest1
--
--------------------------------------------------------------------
local function LayerTest1()
local ret = createLayerDemoLayer("ColorLayer resize (tap & move)")
ret:setTouchEnabled(true)
local s = CCDirector:sharedDirector():getWinSize()
local layer = CCLayerColor:create( ccc4(0xFF, 0x00, 0x00, 0x80), 200, 200)
layer:ignoreAnchorPointForPosition(false)
layer:setPosition( ccp(s.width/2, s.height/2) )
ret:addChild(layer, 1, kTagLayer)
local function updateSize(x, y)
local s = CCDirector:sharedDirector():getWinSize()
local newSize = CCSizeMake( math.abs(x - s.width/2)*2, math.abs(y - s.height/2)*2)
local l = tolua.cast(ret:getChildByTag(kTagLayer), "CCLayerColor")
l:setContentSize( newSize )
end
local function onTouchEvent(eventType, x, y)
if eventType == "began" then
updateSize(x, y)
return true
else
updateSize(x, y)
end
end
ret:registerScriptTouchHandler(onTouchEvent)
return ret
end
--------------------------------------------------------------------
--
-- LayerTest2
--
--------------------------------------------------------------------
local function LayerTest2()
local ret = createLayerDemoLayer("ColorLayer: fade and tint")
local s = CCDirector:sharedDirector():getWinSize()
local layer1 = CCLayerColor:create( ccc4(255, 255, 0, 80), 100, 300)
layer1:setPosition(ccp(s.width/3, s.height/2))
layer1:ignoreAnchorPointForPosition(false)
ret:addChild(layer1, 1)
local layer2 = CCLayerColor:create( ccc4(0, 0, 255, 255), 100, 300)
layer2:setPosition(ccp((s.width/3)*2, s.height/2))
layer2:ignoreAnchorPointForPosition(false)
ret:addChild(layer2, 1)
local actionTint = CCTintBy:create(2, -255, -127, 0)
local actionTintBack = actionTint:reverse()
local arr = CCArray:create()
arr:addObject(actionTint)
arr:addObject(actionTintBack)
local seq1 = CCSequence:create(arr)
layer1:runAction(seq1)
local actionFade = CCFadeOut:create(2.0)
local actionFadeBack = actionFade:reverse()
arr = CCArray:create()
arr:addObject(actionFade)
arr:addObject(actionFadeBack)
local seq2 = CCSequence:create(arr)
layer2:runAction(seq2)
return ret
end
--------------------------------------------------------------------
--
-- LayerTestBlend
--
--------------------------------------------------------------------
local function LayerTestBlend()
local ret = createLayerDemoLayer("ColorLayer: blend")
local s = CCDirector:sharedDirector():getWinSize()
local layer1 = CCLayerColor:create( ccc4(255, 255, 255, 80) )
local sister1 = CCSprite:create(s_pPathSister1)
local sister2 = CCSprite:create(s_pPathSister2)
ret:addChild(sister1)
ret:addChild(sister2)
ret:addChild(layer1, 100, kTagLayer)
sister1:setPosition( ccp( s.width*1/3, s.height/2) )
sister2:setPosition( ccp( s.width*2/3, s.height/2) )
local function newBlend(dt)
local layer = tolua.cast(ret:getChildByTag(kTagLayer), "CCLayerColor")
local src = 0
local dst = 0
if layer:getBlendFunc().dst == GL_ZERO then
src = GL_SRC_ALPHA
dst = GL_ONE_MINUS_SRC_ALPHA
else
src = GL_ONE_MINUS_DST_COLOR
dst = GL_ZERO
end
local bf = ccBlendFunc()
bf.src = src
bf.dst = dst
layer:setBlendFunc( bf )
end
local schedulerEntry = nil
local function onNodeEvent(event)
if event == "enter" then
schedulerEntry = scheduler:scheduleScriptFunc(newBlend, 1.0, false)
elseif event == "exit" then
scheduler:unscheduleScriptEntry(schedulerEntry)
end
end
ret:registerScriptHandler(onNodeEvent)
return ret
end
--------------------------------------------------------------------
--
-- LayerGradient
--
--------------------------------------------------------------------
local function LayerGradient()
local ret = createLayerDemoLayer("LayerGradient", "Touch the screen and move your finger")
local layer1 = CCLayerGradient:create(ccc4(255,0,0,255), ccc4(0,255,0,255), ccp(0.9, 0.9))
ret:addChild(layer1, 0, kTagLayer)
ret:setTouchEnabled(true)
local label1 = CCLabelTTF:create("Compressed Interpolation: Enabled", "Marker Felt", 26)
local label2 = CCLabelTTF:create("Compressed Interpolation: Disabled", "Marker Felt", 26)
local item1 = CCMenuItemLabel:create(label1)
local item2 = CCMenuItemLabel:create(label2)
local item = CCMenuItemToggle:create(item1)
item:addSubItem(item2)
local function toggleItem(sender)
-- cclog("toggleItem")
local gradient = tolua.cast(ret:getChildByTag(kTagLayer), "CCLayerGradient")
gradient:setCompressedInterpolation(not gradient:isCompressedInterpolation())
end
item:registerScriptTapHandler(toggleItem)
local menu = CCMenu:createWithItem(item)
ret:addChild(menu)
local s = CCDirector:sharedDirector():getWinSize()
menu:setPosition(ccp(s.width / 2, 100))
local function onTouchEvent(eventType, x, y)
if eventType == "began" then
return true
elseif eventType == "moved" then
local s = CCDirector:sharedDirector():getWinSize()
local start = ccp(x, y)
local diff = ccpSub( ccp(s.width/2,s.height/2), start)
diff = ccpNormalize(diff)
local gradient = tolua.cast(ret:getChildByTag(1), "CCLayerGradient")
gradient:setVector(diff)
end
end
ret:registerScriptTouchHandler(onTouchEvent)
return ret
end
-- LayerIgnoreAnchorPointPos
local kLayerIgnoreAnchorPoint = 1000
local function LayerIgnoreAnchorPointPos()
local ret = createLayerDemoLayer("IgnoreAnchorPoint - Position", "Ignoring Anchor Point for position")
local s = CCDirector:sharedDirector():getWinSize()
local l = CCLayerColor:create(ccc4(255, 0, 0, 255), 150, 150)
l:setAnchorPoint(ccp(0.5, 0.5))
l:setPosition(ccp( s.width/2, s.height/2))
local move = CCMoveBy:create(2, ccp(100,2))
local back = tolua.cast(move:reverse(), "CCMoveBy")
local arr = CCArray:create()
arr:addObject(move)
arr:addObject(back)
local seq = CCSequence:create(arr)
l:runAction(CCRepeatForever:create(seq))
ret:addChild(l, 0, kLayerIgnoreAnchorPoint)
local child = CCSprite:create("Images/grossini.png")
l:addChild(child)
local lsize = l:getContentSize()
child:setPosition(ccp(lsize.width/2, lsize.height/2))
local function onToggle(pObject)
local pLayer = ret:getChildByTag(kLayerIgnoreAnchorPoint)
local ignore = pLayer:isIgnoreAnchorPointForPosition()
pLayer:ignoreAnchorPointForPosition(not ignore)
end
local item = CCMenuItemFont:create("Toggle ignore anchor point")
item:registerScriptTapHandler(onToggle)
local menu = CCMenu:createWithItem(item)
ret:addChild(menu)
menu:setPosition(ccp(s.width/2, s.height/2))
return ret
end
-- LayerIgnoreAnchorPointRot
local function LayerIgnoreAnchorPointRot()
local ret = createLayerDemoLayer("IgnoreAnchorPoint - Rotation", "Ignoring Anchor Point for rotations")
local s = CCDirector:sharedDirector():getWinSize()
local l = CCLayerColor:create(ccc4(255, 0, 0, 255), 200, 200)
l:setAnchorPoint(ccp(0.5, 0.5))
l:setPosition(ccp( s.width/2, s.height/2))
ret:addChild(l, 0, kLayerIgnoreAnchorPoint)
local rot = CCRotateBy:create(2, 360)
l:runAction(CCRepeatForever:create(rot))
local child = CCSprite:create("Images/grossini.png")
l:addChild(child)
local lsize = l:getContentSize()
child:setPosition(ccp(lsize.width/2, lsize.height/2))
local function onToggle(pObject)
local pLayer = ret:getChildByTag(kLayerIgnoreAnchorPoint)
local ignore = pLayer:isIgnoreAnchorPointForPosition()
pLayer:ignoreAnchorPointForPosition(not ignore)
end
local item = CCMenuItemFont:create("Toogle ignore anchor point")
item:registerScriptTapHandler(onToggle)
local menu = CCMenu:createWithItem(item)
ret:addChild(menu)
menu:setPosition(ccp(s.width/2, s.height/2))
return ret
end
-- LayerIgnoreAnchorPointScale
local function LayerIgnoreAnchorPointScale()
local ret = createLayerDemoLayer("IgnoreAnchorPoint - Scale", "Ignoring Anchor Point for scale")
local s = CCDirector:sharedDirector():getWinSize()
local l = CCLayerColor:create(ccc4(255, 0, 0, 255), 200, 200)
l:setAnchorPoint(ccp(0.5, 1.0))
l:setPosition(ccp( s.width/2, s.height/2))
local scale = CCScaleBy:create(2, 2)
local back = tolua.cast(scale:reverse(), "CCScaleBy")
local arr = CCArray:create()
arr:addObject(scale)
arr:addObject(back)
local seq = CCSequence:create(arr)
l:runAction(CCRepeatForever:create(seq))
ret:addChild(l, 0, kLayerIgnoreAnchorPoint)
local child = CCSprite:create("Images/grossini.png")
l:addChild(child)
local lsize = l:getContentSize()
child:setPosition(ccp(lsize.width/2, lsize.height/2))
local function onToggle(pObject)
local pLayer = ret:getChildByTag(kLayerIgnoreAnchorPoint)
local ignore = pLayer:isIgnoreAnchorPointForPosition()
pLayer:ignoreAnchorPointForPosition(not ignore)
return ret
end
local item = CCMenuItemFont:create("Toogle ignore anchor point")
item:registerScriptTapHandler(onToggle)
local menu = CCMenu:createWithItem(item)
ret:addChild(menu)
menu:setPosition(ccp(s.width/2, s.height/2))
return ret
end
local function LayerExtendedBlendOpacityTest()
local ret = createLayerDemoLayer("Extended Blend & Opacity", "You should see 3 layers")
local layer1 = CCLayerGradient:create(ccc4(255, 0, 0, 255), ccc4(255, 0, 255, 255))
layer1:setContentSize(CCSizeMake(80, 80))
layer1:setPosition(ccp(50,50))
ret:addChild(layer1)
local layer2 = CCLayerGradient:create(ccc4(0, 0, 0, 127), ccc4(255, 255, 255, 127))
layer2:setContentSize(CCSizeMake(80, 80))
layer2:setPosition(ccp(100,90))
ret:addChild(layer2)
local layer3 = CCLayerGradient:create()
layer3:setContentSize(CCSizeMake(80, 80))
layer3:setPosition(ccp(150,140))
layer3:setStartColor(ccc3(255, 0, 0))
layer3:setEndColor(ccc3(255, 0, 255))
layer3:setStartOpacity(255)
layer3:setEndOpacity(255)
local blend = ccBlendFunc()
blend.src = GL_SRC_ALPHA
blend.dst = GL_ONE_MINUS_SRC_ALPHA
layer3:setBlendFunc(blend)
ret:addChild(layer3)
return ret
end
function LayerTestMain()
cclog("LayerTestMain")
Helper.index = 1
CCDirector:sharedDirector():setDepthTest(true)
local scene = CCScene:create()
Helper.createFunctionTable = {
LayerTestCascadingOpacityA,
LayerTestCascadingOpacityB,
LayerTestCascadingOpacityC,
LayerTestCascadingColorA,
LayerTestCascadingColorB,
LayerTestCascadingColorC,
LayerTest1,
LayerTest2,
LayerTestBlend,
LayerGradient,
LayerIgnoreAnchorPointPos,
LayerIgnoreAnchorPointRot,
LayerIgnoreAnchorPointScale,
LayerExtendedBlendOpacityTest
}
scene:addChild(LayerTestCascadingOpacityA())
scene:addChild(CreateBackMenuItem())
return scene
end
| mit |
omid1212/telsed2 | plugins/owners.lua | 68 | 12477 |
local function lock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function show_group_settingsmod(msg, data, target)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function set_rules(target, rules)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function set_description(target, about)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function run(msg, matches)
if msg.to.type ~= 'chat' then
local chat_id = matches[1]
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
if matches[2] == 'ban' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't ban yourself"
end
ban_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3])
return 'User '..user_id..' banned'
end
if matches[2] == 'unban' then
if tonumber(matches[3]) == tonumber(our_id) then return false end
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't unban yourself"
end
local hash = 'banned:'..matches[1]..':'..user_id
redis:del(hash)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3])
return 'User '..user_id..' unbanned'
end
if matches[2] == 'kick' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't kick yourself"
end
kick_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3])
return 'User '..user_id..' kicked'
end
if matches[2] == 'clean' then
if matches[3] == 'modlist' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
for k,v in pairs(data[tostring(matches[1])]['moderators']) do
data[tostring(matches[1])]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist")
end
if matches[3] == 'rules' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'rules'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules")
end
if matches[3] == 'about' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'description'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned about")
end
end
if matches[2] == "setflood" then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[3]
data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]")
return 'Group flood has been set to '..matches[3]
end
if matches[2] == 'lock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
end
if matches[2] == 'unlock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
end
if matches[2] == 'new' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local function callback (extra , success, result)
local receiver = 'chat#'..matches[1]
vardump(result)
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return
end
local receiver = 'chat#'..matches[1]
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ")
export_chat_link(receiver, callback, true)
return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link"
end
end
if matches[2] == 'get' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local group_link = data[tostring(matches[1])]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
end
if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then
local target = matches[2]
local about = matches[3]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_description(target, about)
end
if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then
local rules = matches[3]
local target = matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rules(target, rules)
end
if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then
savelog(matches[2], "------")
send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false)
end
end
end
return {
patterns = {
"^[!/]owners (%d+) ([^%s]+) (.*)$",
"^[!/]owners (%d+) ([^%s]+)$",
"^[!/](changeabout) (%d+) (.*)$",
"^[!/](changerules) (%d+) (.*)$",
"^[!/](changename) (%d+) (.*)$",
"^[!/](loggroup) (%d+)$"
},
run = run
}
| gpl-2.0 |
Anarchid/Zero-K | LuaUI/Widgets/api_lag_monitor.lua | 6 | 4640 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Lag (AFK) monitor",
desc = "Monitors user presses and mouse moves",
author = "Licho",
date = "4.1.2012",
license = "GPLv2",
layer = -1000, -- so the indicator draws in front of Chili.
enabled = true, -- loaded by default?
handler = false,
api = true,
alwaysStart = true,
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spGetGameSeconds = Spring.GetGameSeconds
local GL_TRIANGLE_FAN = GL.TRIANGLE_FAN
local glBeginEnd = gl.BeginEnd
local glColor = gl.Color
local glPopMatrix = gl.PopMatrix
local glPushMatrix = gl.PushMatrix
local glScale = gl.Scale
local glTranslate = gl.Translate
local glVertex = gl.Vertex
local WARNING_SECONDS = 8
local pieColor = { 1.0, 0.3, 0.3, 1 }
local circleDivs = 80
local second
local secondSent
local lx, ly
local lagmonitorSeconds = Spring.GetGameRulesParam("lagmonitor_seconds")
local dangerZone = false
local supressDrawUntilNextFrame = false
local personallySucceptible = true
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:MousePress()
second = spGetGameSeconds()
end
function widget:KeyPress()
second = spGetGameSeconds()
end
function widget:GameFrame(f)
if f%51 == 0 or dangerZone then
local mx, my = Spring.GetMouseState()
if mx ~= lx or my ~= ly then
lx = mx
ly = my
second = spGetGameSeconds()
end
if second ~= secondSent then
Spring.SendLuaRulesMsg('AFK'..second)
secondSent = second
end
dangerZone = false
supressDrawUntilNextFrame = false
end
end
function widget:TextInput()
second = spGetGameSeconds()
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function DrawPie(fraction)
local radius = 100 * (WG.uiScale or 1)
local mouseX, mouseY = Spring.GetMouseState()
glPushMatrix()
glTranslate(mouseX, mouseY, 0)
glScale(radius, radius, 1)
if fraction < 1 then
pieColor[4] = 0.1 + 0.7 * fraction
else
pieColor[4] = 0.6 + 0.2 * math.cos(WARNING_SECONDS * 8 * (fraction - 1))
end
fraction = math.min(1, fraction)
glColor(pieColor)
glBeginEnd(GL_TRIANGLE_FAN, function()
glVertex(0, 0, 0)
for i = 0, math.floor(circleDivs * fraction) do
local r = 2.0 * math.pi * ( -i / circleDivs) + math.pi / 2
local cosv = math.cos(r)
local sinv = math.sin(r)
glVertex(cosv, sinv, 0)
end
local r = 2.0 * math.pi * ( -circleDivs * fraction / circleDivs) + math.pi / 2
local cosv = math.cos(r)
local sinv = math.sin(r)
glVertex(cosv, sinv, 0)
end)
glPopMatrix()
end
function widget:DrawScreen()
if not (lagmonitorSeconds and secondSent and personallySucceptible) then
return
end
if (supressDrawUntilNextFrame) then
return
end
local afkSeconds = Spring.GetGameSeconds() - secondSent
if afkSeconds > lagmonitorSeconds - WARNING_SECONDS then
DrawPie(1 - (lagmonitorSeconds - afkSeconds) / WARNING_SECONDS)
dangerZone = true
if select(3, Spring.GetGameSpeed()) then -- If game is paused.
supressDrawUntilNextFrame = true -- Hides AFK that is cancelled while pausd.
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function UpdateLagmonitorSucceptibility()
if Spring.GetSpectatingState() then
return false
end
local teamList = Spring.GetTeamList(Spring.GetMyAllyTeamID())
local myTeamID = Spring.GetMyTeamID()
for i = 1, #teamList do
local teamID = teamList[i]
if myTeamID ~= teamID then
local _, _, _, isAiTeam = Spring.GetTeamInfo(teamID)
if not isAiTeam then
if not Spring.GetTeamLuaAI(teamID) then
return true
end
end
end
end
return false
end
function widget:PlayerChanged()
personallySucceptible = UpdateLagmonitorSucceptibility()
end
function widget:Initialize()
personallySucceptible = UpdateLagmonitorSucceptibility()
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
hfjgjfg/sy | plugins/admin.lua | 230 | 6382 | local function set_bot_photo(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/bot.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
set_profile_photo(file, ok_cb, false)
send_large_msg(receiver, 'Photo changed!', ok_cb, false)
redis:del("bot:photo")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
return parsed_path[2]
end
local function get_contact_list_callback (cb_extra, success, result)
local text = " "
for k,v in pairs(result) do
if v.print_name and v.id and v.phone then
text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n"
end
end
local file = io.open("contact_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format
local file = io.open("contact_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format
end
local function user_info_callback(cb_extra, success, result)
result.access_hash = nil
result.flags = nil
result.phone = nil
if result.username then
result.username = '@'..result.username
end
result.print_name = result.print_name:gsub("_","")
local text = serpent.block(result, {comment=false})
text = text:gsub("[{}]", "")
text = text:gsub('"', "")
text = text:gsub(",","")
if cb_extra.msg.to.type == "chat" then
send_large_msg("chat#id"..cb_extra.msg.to.id, text)
else
send_large_msg("user#id"..cb_extra.msg.to.id, text)
end
end
local function get_dialog_list_callback(cb_extra, success, result)
local text = ""
for k,v in pairs(result) do
if v.peer then
if v.peer.type == "chat" then
text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")"
else
if v.peer.print_name and v.peer.id then
text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]"
end
if v.peer.username then
text = text.."("..v.peer.username..")"
end
if v.peer.phone then
text = text.."'"..v.peer.phone.."'"
end
end
end
if v.message then
text = text..'\nlast msg >\nmsg id = '..v.message.id
if v.message.text then
text = text .. "\n text = "..v.message.text
end
if v.message.action then
text = text.."\n"..serpent.block(v.message.action, {comment=false})
end
if v.message.from then
if v.message.from.print_name then
text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]"
end
if v.message.from.username then
text = text.."( "..v.message.from.username.." )"
end
if v.message.from.phone then
text = text.."' "..v.message.from.phone.." '"
end
end
end
text = text.."\n\n"
end
local file = io.open("dialog_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format
local file = io.open("dialog_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format
end
local function run(msg,matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local group = msg.to.id
if not is_admin(msg) then
return
end
if msg.media then
if msg.media.type == 'photo' and redis:get("bot:photo") then
if redis:get("bot:photo") == 'waiting' then
load_photo(msg.id, set_bot_photo, msg)
end
end
end
if matches[1] == "setbotphoto" then
redis:set("bot:photo", "waiting")
return 'Please send me bot photo now'
end
if matches[1] == "markread" then
if matches[2] == "on" then
redis:set("bot:markread", "on")
return "Mark read > on"
end
if matches[2] == "off" then
redis:del("bot:markread")
return "Mark read > off"
end
return
end
if matches[1] == "pm" then
send_large_msg("user#id"..matches[2],matches[3])
return "Msg sent"
end
if matches[1] == "block" then
if is_admin2(matches[2]) then
return "You can't block admins"
end
block_user("user#id"..matches[2],ok_cb,false)
return "User blocked"
end
if matches[1] == "unblock" then
unblock_user("user#id"..matches[2],ok_cb,false)
return "User unblocked"
end
if matches[1] == "import" then--join by group link
local hash = parsed_url(matches[2])
import_chat_link(hash,ok_cb,false)
end
if matches[1] == "contactlist" then
get_contact_list(get_contact_list_callback, {target = msg.from.id})
return "I've sent contact list with both json and text format to your private"
end
if matches[1] == "delcontact" then
del_contact("user#id"..matches[2],ok_cb,false)
return "User "..matches[2].." removed from contact list"
end
if matches[1] == "dialoglist" then
get_dialog_list(get_dialog_list_callback, {target = msg.from.id})
return "I've sent dialog list with both json and text format to your private"
end
if matches[1] == "whois" then
user_info("user#id"..matches[2],user_info_callback,{msg=msg})
end
return
end
return {
patterns = {
"^[!/](pm) (%d+) (.*)$",
"^[!/](import) (.*)$",
"^[!/](unblock) (%d+)$",
"^[!/](block) (%d+)$",
"^[!/](markread) (on)$",
"^[!/](markread) (off)$",
"^[!/](setbotphoto)$",
"%[(photo)%]",
"^[!/](contactlist)$",
"^[!/](dialoglist)$",
"^[!/](delcontact) (%d+)$",
"^[!/](whois) (%d+)$"
},
run = run,
}
--By @imandaneshi :)
--https://github.com/SEEDTEAM/TeleSeed/blob/master/plugins/admin.lua
| gpl-2.0 |
Anarchid/Zero-K | LuaUI/Widgets/chili/Skins/Carbon/skin.lua | 8 | 5888 | --// =============================================================================
--// Skin
local skin = {
info = {
name = "Carbon",
version = "1.0",
author = "luckywaldo7",
}
}
--// =============================================================================
--//
skin.general = {
focusColor = {0.0, 0.6, 1.0, 1.0},
borderColor = {1.0, 1.0, 1.0, 1.0},
font = {
--font = "FreeSansBold.ttf",
color = {1, 1, 1, 1},
outlineColor = {0.05, 0.05, 0.05, 0.9},
outline = false,
shadow = true,
size = 13,
},
}
skin.icons = {
imageplaceholder = ":cl:placeholder.png",
}
skin.button = {
TileImageBK = ":cl:tech_button.png",
TileImageFG = ":cl:empty.png",
tiles = {32, 32, 32, 32}, --// tile widths: left, top, right, bottom
padding = {10, 10, 10, 10},
backgroundColor = {1, 1, 1, 1.0},
DrawControl = DrawButton,
}
skin.button_disabled = {
TileImageBK = ":cl:tech_button.png",
TileImageFG = ":cl:empty.png",
tiles = {32, 32, 32, 32}, --// tile widths: left, top, right, bottom
padding = {10, 10, 10, 10},
color = {0.3, .3, .3, 1},
backgroundColor = {0.1, 0.1, 0.1, 0.8},
DrawControl = DrawButton,
}
skin.checkbox = {
TileImageFG = ":cl:tech_checkbox_checked.png",
TileImageBK = ":cl:tech_checkbox_unchecked.png",
tiles = {8, 8, 8, 8},
boxsize = 12,
DrawControl = DrawCheckbox,
}
skin.editbox = {
backgroundColor = {0.1, 0.1, 0.1, 0},
cursorColor = {1.0, 0.7, 0.1, 0.8},
focusColor = {1, 1, 1, 1},
borderColor = {1, 1, 1, 0.6},
padding = {6, 2, 2, 3},
TileImageBK = ":cl:panel2_bg.png",
TileImageFG = ":cl:panel2.png",
tiles = {8, 8, 8, 8},
DrawControl = DrawEditBox,
}
skin.imagelistview = {
imageFolder = "folder.png",
imageFolderUp = "folder_up.png",
--DrawControl = DrawBackground,
colorBK = {1, 1, 1, 0.3},
colorBK_selected = {1, 0.7, 0.1, 0.8},
colorFG = {0, 0, 0, 0},
colorFG_selected = {1, 1, 1, 1},
imageBK = ":cl:node_selected_bw.png",
imageFG = ":cl:node_selected.png",
tiles = {9, 9, 9, 9},
--tiles = {17, 15, 17, 20},
DrawItemBackground = DrawItemBkGnd,
}
--[[
skin.imagelistviewitem = {
imageFG = ":cl:glassFG.png",
imageBK = ":cl:glassBK.png",
tiles = {17, 15, 17, 20},
padding = {12, 12, 12, 12},
DrawSelectionItemBkGnd = DrawSelectionItemBkGnd,
}
--]]
skin.panel = {
--TileImageFG = ":cl:glassFG.png",
--TileImageBK = ":cl:glassBK.png",
--tiles = {17, 15, 17, 20},
TileImageBK = ":cl:tech_button.png",
TileImageFG = ":cl:empty.png",
tiles = {32, 32, 32, 32},
backgroundColor = {1, 1, 1, 0.8},
DrawControl = DrawPanel,
}
skin.panelSmall = {
--TileImageFG = ":cl:glassFG.png",
--TileImageBK = ":cl:glassBK.png",
--tiles = {17, 15, 17, 20},
TileImageBK = ":cl:tech_button.png",
TileImageFG = ":cl:empty.png",
tiles = {16, 16, 16, 16},
backgroundColor = {1, 1, 1, 0.8},
DrawControl = DrawPanel,
}
local fancyPanels = {
"0100",
"0110",
"1100",
"0011",
"1120",
"2100",
"0120",
"0001",
"0021",
"2001",
"2021",
"2120",
"1011",
"2011",
"1021",
}
local fancyPanelsSmall = {
"0011_small",
"1001_small",
"0001_small",
}
for i = 1, #fancyPanels do
local name = "panel_" .. fancyPanels[i]
skin[name] = Spring.Utilities.CopyTable(skin.panel)
skin[name].TileImageBK = ":cl:" .. name .. ".png"
end
for i = 1, #fancyPanelsSmall do
local name = "panel_" .. fancyPanelsSmall[i]
skin[name] = Spring.Utilities.CopyTable(skin.panelSmall)
skin[name].TileImageBK = ":cl:" .. name .. ".png"
end
skin.progressbar = {
TileImageFG = ":cl:tech_progressbar_full.png",
TileImageBK = ":cl:tech_progressbar_empty.png",
tiles = {16, 16, 16, 16},
fillPadding = {4, 3, 4, 3},
font = {
shadow = true,
},
DrawControl = DrawProgressbar,
}
skin.multiprogressbar = {
fillPadding = {4, 3, 4, 3},
}
skin.scrollpanel = {
BorderTileImage = ":cl:panel2_border.png",
bordertiles = {16, 16, 16, 16},
BackgroundTileImage = ":cl:panel2_bg.png",
bkgndtiles = {16, 16, 16, 16},
TileImage = ":cl:tech_scrollbar.png",
tiles = {8, 8, 8, 8},
KnobTileImage = ":cl:tech_scrollbar_knob.png",
KnobTiles = {8, 8, 8, 8},
HTileImage = ":cl:tech_scrollbar.png",
htiles = {8, 8, 8, 8},
HKnobTileImage = ":cl:tech_scrollbar_knob.png",
HKnobTiles = {8, 8, 8, 8},
KnobColorSelected = {0.0, 0.6, 1.0, 1.0},
padding = {2, 2, 2, 2},
scrollbarSize = 12,
DrawControl = DrawScrollPanel,
DrawControlPostChildren = DrawScrollPanelBorder,
}
skin.trackbar = {
TileImage = ":cl:trackbar.png",
tiles = {16, 16, 16, 16}, --// tile widths: left, top, right, bottom
ThumbImage = ":cl:trackbar_thumb.png",
StepImage = ":cl:trackbar_step.png",
hitpadding = {4, 4, 5, 4},
DrawControl = DrawTrackbar,
}
skin.treeview = {
--ImageNode = ":cl:node.png",
ImageNodeSelected = ":cl:node_selected.png",
tiles = {16, 16, 16, 16},
ImageExpanded = ":cl:treeview_node_expanded.png",
ImageCollapsed = ":cl:treeview_node_collapsed.png",
treeColor = {1, 1, 1, 0.1},
DrawNode = DrawTreeviewNode,
DrawNodeTree = DrawTreeviewNodeTree,
}
skin.window = {
TileImage = ":cl:tech_dragwindow.png",
--TileImage = ":cl:tech_window.png",
--TileImage = ":cl:window_tooltip.png",
--tiles = {25, 25, 25, 25}, --// tile widths: left, top, right, bottom
tiles = {64, 64, 64, 64}, --// tile widths: left, top, right, bottom
padding = {13, 13, 13, 13},
hitpadding = {4, 4, 4, 4},
color = {1, 1, 1, 1.0},
captionColor = {1, 1, 1, 0.45},
boxes = {
resize = {-21, -21, -10, -10},
drag = {0, 0, "100%", 10},
},
NCHitTest = NCHitTestWithPadding,
NCMouseDown = WindowNCMouseDown,
NCMouseDownPostChildren = WindowNCMouseDownPostChildren,
DrawControl = DrawWindow,
DrawDragGrip = function() end,
DrawResizeGrip = DrawResizeGrip,
}
skin.control = skin.general
--// =============================================================================
--//
return skin
| gpl-2.0 |
rollasoul/HaikuDenseCap | eval/eval_utils.lua | 4 | 10674 |
local cjson = require 'cjson'
local utils = require 'densecap.utils'
local box_utils = require 'densecap.box_utils'
local eval_utils = {}
--[[
Evaluate a DenseCapModel on a split of data from a DataLoader.
Input: An object with the following keys:
- model: A DenseCapModel object to evaluate; required.
- loader: A DataLoader object; required.
- split: Either 'val' or 'test'; default is 'val'
- max_images: Integer giving the number of images to use, or -1 to use the
entire split. Default is -1.
- id: ID for cross-validation; default is ''.
- dtype: torch datatype to which data should be cast before passing to the
model. Default is 'torch.FloatTensor'.
--]]
function eval_utils.eval_split(kwargs)
local model = utils.getopt(kwargs, 'model')
local loader = utils.getopt(kwargs, 'loader')
local split = utils.getopt(kwargs, 'split', 'val')
local max_images = utils.getopt(kwargs, 'max_images', -1)
local id = utils.getopt(kwargs, 'id', '')
local dtype = utils.getopt(kwargs, 'dtype', 'torch.FloatTensor')
assert(split == 'val' or split == 'test', 'split must be "val" or "test"')
local split_to_int = {val=1, test=2}
split = split_to_int[split]
print('using split ', split)
model:evaluate()
loader:resetIterator(split)
local evaluator = DenseCaptioningEvaluator{id=id}
local counter = 0
local all_losses = {}
while true do
counter = counter + 1
-- Grab a batch of data and convert it to the right dtype
local data = {}
local loader_kwargs = {split=split, iterate=true}
local img, gt_boxes, gt_labels, info, _ = loader:getBatch(loader_kwargs)
local data = {
image = img:type(dtype),
gt_boxes = gt_boxes:type(dtype),
gt_labels = gt_labels:type(dtype),
}
info = info[1] -- Since we are only using a single image
-- Call forward_backward to compute losses
model.timing = false
model.dump_vars = false
model.cnn_backward = false
local losses = model:forward_backward(data)
table.insert(all_losses, losses)
-- Call forward_test to make predictions, and pass them to evaluator
local boxes, logprobs, captions = model:forward_test(data.image)
local gt_captions = model.nets.language_model:decodeSequence(gt_labels[1])
evaluator:addResult(logprobs, boxes, captions, gt_boxes[1], gt_captions)
-- Print a message to the console
local msg = 'Processed image %s (%d / %d) of split %d, detected %d regions'
local num_images = info.split_bounds[2]
if max_images > 0 then num_images = math.min(num_images, max_images) end
local num_boxes = boxes:size(1)
print(string.format(msg, info.filename, counter, num_images, split, num_boxes))
-- Break out if we have processed enough images
if max_images > 0 and counter >= max_images then break end
if info.split_bounds[1] == info.split_bounds[2] then break end
end
local loss_results = utils.dict_average(all_losses)
print('Loss stats:')
print(loss_results)
print('Average loss: ', loss_results.total_loss)
local ap_results = evaluator:evaluate()
print(string.format('mAP: %f', 100 * ap_results.map))
local out = {
loss_results=loss_results,
ap_results=ap_results,
}
return out
end
function eval_utils.score_captions(records)
-- serialize records to json file
utils.write_json('eval/input.json', records)
-- invoke python process
os.execute('python eval/meteor_bridge.py')
-- read out results
local blob = utils.read_json('eval/output.json')
return blob
end
local function pluck_boxes(ix, boxes, text)
-- ix is a list (length N) of LongTensors giving indices to boxes/text. Use them to do merge
-- this is done because multiple ground truth annotations can be on top of each other, and
-- we want to instead group many overlapping boxes into one, with multiple caption references.
-- return boxes Nx4, and text[] of length N
local N = #ix
local new_boxes = torch.zeros(N, 4)
local new_text = {}
for i=1,N do
local ixi = ix[i]
local n = ixi:nElement()
local bsub = boxes:index(1, ixi)
local newbox = torch.mean(bsub, 1)
new_boxes[i] = newbox
local texts = {}
if text then
for j=1,n do
table.insert(texts, text[ixi[j]])
end
end
table.insert(new_text, texts)
end
return new_boxes, new_text
end
local DenseCaptioningEvaluator = torch.class('DenseCaptioningEvaluator')
function DenseCaptioningEvaluator:__init(opt)
self.all_logprobs = {}
self.records = {}
self.n = 1
self.npos = 0
self.id = utils.getopt(opt, 'id', '')
end
-- boxes is (B x 4) are xcycwh, logprobs are (B x 2), target_boxes are (M x 4) also as xcycwh.
-- these can be both on CPU or on GPU (they will be shipped to CPU if not already so)
-- predict_text is length B list of strings, target_text is length M list of strings.
function DenseCaptioningEvaluator:addResult(logprobs, boxes, text, target_boxes, target_text)
assert(logprobs:size(1) == boxes:size(1))
assert(logprobs:size(1) == #text)
assert(target_boxes:size(1) == #target_text)
assert(boxes:nDimension() == 2)
-- convert both boxes to x1y1x2y2 coordinate systems
boxes = box_utils.xcycwh_to_x1y1x2y2(boxes)
target_boxes = box_utils.xcycwh_to_x1y1x2y2(target_boxes)
-- make sure we're on CPU
boxes = boxes:float()
logprobs = logprobs[{ {}, 1 }]:double() -- grab the positives class (1)
target_boxes = target_boxes:float()
-- merge ground truth boxes that overlap by >= 0.7
local mergeix = box_utils.merge_boxes(target_boxes, 0.7) -- merge groups of boxes together
local merged_boxes, merged_text = pluck_boxes(mergeix, target_boxes, target_text)
-- 1. Sort detections by decreasing confidence
local Y,IX = torch.sort(logprobs,1,true) -- true makes order descending
local nd = logprobs:size(1) -- number of detections
local nt = merged_boxes:size(1) -- number of gt boxes
local used = torch.zeros(nt)
for d=1,nd do -- for each detection in descending order of confidence
local ii = IX[d]
local bb = boxes[ii]
-- assign the box to its best match in true boxes
local ovmax = 0
local jmax = -1
for j=1,nt do
local bbgt = merged_boxes[j]
local bi = {math.max(bb[1],bbgt[1]), math.max(bb[2],bbgt[2]),
math.min(bb[3],bbgt[3]), math.min(bb[4],bbgt[4])}
local iw = bi[3]-bi[1]+1
local ih = bi[4]-bi[2]+1
if iw>0 and ih>0 then
-- compute overlap as area of intersection / area of union
local ua = (bb[3]-bb[1]+1)*(bb[4]-bb[2]+1)+
(bbgt[3]-bbgt[1]+1)*(bbgt[4]-bbgt[2]+1)-iw*ih
local ov = iw*ih/ua
if ov > ovmax then
ovmax = ov
jmax = j
end
end
end
local ok = 1
if used[jmax] == 0 then
used[jmax] = 1 -- mark as taken
else
ok = 0
end
-- record the best box, the overlap, and the fact that we need to score the language match
local record = {}
record.ok = ok -- whether this prediction can be counted toward a true positive
record.ov = ovmax
record.candidate = text[ii]
record.references = merged_text[jmax] -- will be nil if jmax stays -1
-- Replace nil with empty table to prevent crash in meteor bridge
if record.references == nil then record.references = {} end
record.imgid = self.n
table.insert(self.records, record)
end
-- keep track of results
self.n = self.n + 1
self.npos = self.npos + nt
table.insert(self.all_logprobs, Y:double()) -- inserting the sorted logprobs as double
end
function DenseCaptioningEvaluator:evaluate(verbose)
if verbose == nil then verbose = true end
local min_overlaps = {0.3, 0.4, 0.5, 0.6, 0.7}
local min_scores = {-1, 0, 0.05, 0.1, 0.15, 0.2, 0.25}
-- concatenate everything across all images
local logprobs = torch.cat(self.all_logprobs, 1) -- concat all logprobs
-- call python to evaluate all records and get their BLEU/METEOR scores
local blob = eval_utils.score_captions(self.records, self.id) -- replace in place (prev struct will be collected)
local scores = blob.scores -- scores is a list of scores, parallel to records
collectgarbage()
collectgarbage()
-- prints/debugging
if verbose then
for k=1,#self.records do
local record = self.records[k]
if record.ov > 0 and record.ok == 1 and k % 1000 == 0 then
local txtgt = ''
assert(type(record.references) == "table")
for kk,vv in pairs(record.references) do txtgt = txtgt .. vv .. '. ' end
print(string.format('IMG %d PRED: %s, GT: %s, OK: %d, OV: %f SCORE: %f',
record.imgid, record.candidate, txtgt, record.ok, record.ov, scores[k]))
end
end
end
-- lets now do the evaluation
local y,ix = torch.sort(logprobs,1,true) -- true makes order descending
local ap_results = {}
local det_results = {}
for foo, min_overlap in pairs(min_overlaps) do
for foo2, min_score in pairs(min_scores) do
-- go down the list and build tp,fp arrays
local n = y:nElement()
local tp = torch.zeros(n)
local fp = torch.zeros(n)
for i=1,n do
-- pull up the relevant record
local ii = ix[i]
local r = self.records[ii]
if not r.references then
fp[i] = 1 -- nothing aligned to this predicted box in the ground truth
else
-- ok something aligned. Lets check if it aligned enough, and correctly enough
local score = scores[ii]
if r.ov >= min_overlap and r.ok == 1 and score > min_score then
tp[i] = 1
else
fp[i] = 1
end
end
end
fp = torch.cumsum(fp,1)
tp = torch.cumsum(tp,1)
local rec = torch.div(tp, self.npos)
local prec = torch.cdiv(tp, fp + tp)
-- compute max-interpolated average precision
local ap = 0
local apn = 0
for t=0,1,0.01 do
local mask = torch.ge(rec, t):double()
local prec_masked = torch.cmul(prec:double(), mask)
local p = torch.max(prec_masked)
ap = ap + p
apn = apn + 1
end
ap = ap / apn
-- store it
if min_score == -1 then
det_results['ov' .. min_overlap] = ap
else
ap_results['ov' .. min_overlap .. '_score' .. min_score] = ap
end
end
end
local map = utils.average_values(ap_results)
local detmap = utils.average_values(det_results)
-- lets get out of here
local results = {map = map, ap_breakdown = ap_results, detmap = detmap, det_breakdown = det_results}
return results
end
function DenseCaptioningEvaluator:numAdded()
return self.n - 1
end
return eval_utils
| mit |
Anarchid/Zero-K | effects/slam.lua | 6 | 38258 | -- slam
-- slam_sparks_smokejets
-- slam_flash
-- slam_ray
-- slam_heat_pillar
-- slam_landcloud
-- slam_landcloud_ring
-- slam_landcloud_topcap
-- slam_landcloud_cap
-- slam_landcloud_pillar
-- slam_landcloud_topsuction
-- slam_seacloud
-- slam_seacloud_topcap
-- slam_seacloud_ring
-- slam_seacloud_cap
-- slam_seacloud_pillar
-- slam_water_droplets
-- slam_water_pillar
-- slam_trail
-- slam_muzzle
-- slam_air_scrap
-- slam_air_scrap_fragments
-- slam_air_scrap_particles
-- slam_flash from gundam_xamelimpact (heavily modified)
-- slam_sparks_smokejets from klara (maybe unmodified)
-- slam_seacloud & slam_landcloud stuff from nuke_150 (heavily modified)
-- slam_water_droplets from nuke_150 (modified)
-- slam_trail from cruisetrail (modified)
-- slam_water_pillar from torpedo_hit_main_large (more growth)
-- slam_ray and slam_heat_pillar from galiblow.lua
return {
["slam"] = {
sboom = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
delay = [[0 i1]],
explosiongenerator = [[custom:SLAM_SPARKS_SMOKEJETS]],
pos = [[0, 0, 0]],
},
},
sflash = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
delay = [[0]],
explosiongenerator = [[custom:SLAM_FLASH]],
pos = [[0, 0, 0]],
},
},
sray = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
delay = [[0]],
explosiongenerator = [[custom:SLAM_RAY]],
pos = [[0, 0, 0]],
dir = [[dir]],
},
},
slandcloud = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
properties = {
delay = 4,
dir = [[dir]],
explosiongenerator = [[custom:SLAM_LANDCLOUD]],
pos = [[0, 0, 0]],
},
},
sseacloud = {
class = [[CExpGenSpawner]],
count = 1,
water = true,
underwater = true,
properties = {
delay = 0.5,
dir = [[dir]],
explosiongenerator = [[custom:SLAM_SEACLOUD]],
pos = [[0, 0, 0]],
},
},
swaterdroplets = {
class = [[CExpGenSpawner]],
count = 1,
water = true,
underwater = true,
properties = {
delay = 0,
dir = [[dir]],
explosiongenerator = [[custom:SLAM_WATER_DROPLETS]],
pos = [[0, 0, 0]],
},
},
swaterpillar = {
class = [[CExpGenSpawner]],
count = 1,
water = true,
underwater = true,
properties = {
delay = 0,
dir = [[dir]],
explosiongenerator = [[custom:SLAM_WATER_PILLAR]],
pos = [[0, 0, 0]],
},
},
sheatpillar = {
class = [[CExpGenSpawner]],
count = 32,
water = true,
underwater = true,
ground = true,
air = true,
properties = {
delay = [[i0.25]],
dir = [[-0.1 r0.2, 1 -0.1 r0.2, -0.1 r0.2]],
explosiongenerator = [[custom:SLAM_HEAT_PILLAR]],
pos = [[-4 r8, 0, r32]],
},
},
--~ sairrubble = {
--~ class = [[CExpGenSpawner]],
--~ count = 4,
--~ air = true,
--~ --ground = true,
--~ properties = {
--~ delay = [[0]],
--~ dir = [[dir]],
--~ explosiongenerator = [[custom:SLAM_AIR_RUBBLE]],
--~ pos = [[-3 r6, -3 r6, -3 r6]],
--~ },
--~ },
sairscrap = {
class = [[CExpGenSpawner]],
count = 8,
air = true,
--ground = true,
properties = {
delay = [[0]],
dir = [[dir]],
explosiongenerator = [[custom:SLAM_AIR_SCRAP]],
pos = [[-30 r60, 0, -30 r60]],
},
},
--~ sairdust = {
--~ class = [[CExpGenSpawner]],
--~ count = 1,
--~ air = true,
--~ --ground = true,
--~ properties = {
--~ delay = [[0]],
--~ dir = [[dir]],
--~ explosiongenerator = [[custom:SLAM_AIR_DUST]],
--~ pos = [[0, 0, 0]],
--~ },
--~ },
},
["slam_air_scrap"] = {
usedefaultexplosions = false,
particles = {
air = true,
--ground = true,
class = [[CExpGenSpawner]],
count = 1,
properties = {
delay = [[0]],
dir = [[dir]],
explosiongenerator = [[custom:SLAM_AIR_SCRAP_PARTICLES]],
pos = [[0, 0, 0]],
},
},
fragments = {
air = true,
--ground = true,
class = [[CExpGenSpawner]],
count = 1,
properties = {
delay = [[0]],
dir = [[dir]],
explosiongenerator = [[custom:SLAM_AIR_SCRAP_FRAGMENTS]],
pos = [[-3 r6, -3 r6, -3 r6]],
},
},
},
["slam_seacloud"] = {
usedefaultexplosions = false,
--~ cap = {
--~ air = true,
--~ class = [[CExpGenSpawner]],
--~ count = 1,
--~ ground = true,
--~ water = true,
--~ underwater = true,
--~ underwater = true,
--~ properties = {
--~ delay = 1.5,
--~ dir = [[dir]],
--~ explosiongenerator = [[custom:SLAM_SEACLOUD_CAP]],
--~ pos = [[0, 108, 0]],
--~ },
--~ },
pillar = {
air = true,
class = [[CExpGenSpawner]],
count = 4,
ground = true,
water = true,
underwater = true,
properties = {
delay = [[i2]],
dir = [[dir]],
explosiongenerator = [[custom:SLAM_SEACLOUD_PILLAR]],
pos = [[0, i32, 0]],
},
},
ring = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
delay = 16,
dir = [[dir]],
explosiongenerator = [[custom:SLAM_SEACLOUD_RING]],
pos = [[0, 48, 0]],
},
},
topcap = {
air = true,
class = [[CExpGenSpawner]],
count = 24,
ground = true,
water = true,
underwater = true,
properties = {
delay = [[12 i0.083333]],
dir = [[dir]],
explosiongenerator = [[custom:SLAM_SEACLOUD_TOPCAP]],
pos = [[0, 96 i0.083333, 0]],
},
},
},
["slam_landcloud"] = {
usedefaultexplosions = false,
cap = {
air = true,
class = [[CExpGenSpawner]],
count = 12,
ground = true,
water = true,
properties = {
delay = [[i0.5]],
dir = [[dir]],
explosiongenerator = [[custom:SLAM_LANDCLOUD_CAP]],
pos = [[0, i8, 0]],
},
},
pillar = {
air = true,
class = [[CExpGenSpawner]],
count = 16,
ground = true,
water = true,
properties = {
delay = [[i1.5]],
dir = [[dir]],
explosiongenerator = [[custom:SLAM_LANDCLOUD_PILLAR]],
pos = [[0, i8, 0]],
},
},
ring = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
properties = {
delay = 12,
dir = [[dir]],
explosiongenerator = [[custom:SLAM_LANDCLOUD_RING]],
pos = [[0, 80, 0]],
},
},
topcap = {
air = true,
class = [[CExpGenSpawner]],
count = 16,
ground = true,
water = true,
properties = {
delay = [[6 i0.5]],
dir = [[dir]],
explosiongenerator = [[custom:SLAM_LANDCLOUD_TOPCAP]],
pos = [[0, 96 i2, 0]],
},
},
topsuction = {
air = true,
class = [[CExpGenSpawner]],
count = 9,
ground = true,
water = true,
properties = {
delay = [[a0 r5 y0 a0 24 i1.5]],
dir = [[dir]],
explosiongenerator = [[custom:SLAM_TOPSUCTION]],
pos = [[0, 104, 0]],
},
},
},
["slam_landcloud_ring"] = {
land = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.93,
alwaysvisible = true,
colormap = [[0 0 0 0 1 1 0.75 1 0.8 0.75 0.7 0.8 0.6 0.565 0.55 0.6 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.05, 0]],
numparticles = 40,
particlelife = 75,
particlelifespread = 5,
particlesize = 6,
particlesizespread = 12,
particlespeed = 6,
particlespeedspread = 0,
pos = [[0, 0, 0]],
sizegrowth = 9,
sizemod = 0.7,
texture = [[smokesmall]],
},
},
},
["slam_landcloud_topcap"] = {
land = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.93,
alwaysvisible = true,
colormap = [[0 0 0 0 1 0.75 0.5 0.5 1 0.75 0.0 0.4 0.1 0.0 0.0 0.25 0 0 0 0.01]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 5,
particlelife = 60,
particlelifespread = 5,
particlesize = 12,
particlesizespread = 40,
particlespeed = 1,
particlespeedspread = 5,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1,
texture = [[fireball]],
},
},
},
["slam_landcloud_cap"] = {
land = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0 0 0 0 1 0.75 0.5 1 1 0.75 0.5 0.75 0.75 0.50 0.50 0.5 0 0 0 0.01]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 4,
particlelife = 15,
particlelifespread = 5,
particlesize = 2,
particlesizespread = 2,
particlespeed = 4,
particlespeedspread = 4,
pos = [[0, 0, 0]],
sizegrowth = 12,
sizemod = 0.6,
texture = [[fireball]],
},
},
},
["slam_seacloud_topcap"] = {
cloud = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0 0 0 0 1.0 0.8 0.6 0.8 1.0 1.0 0.8 0.7 0.8 0.8 1 0.6 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 1,
particlelife = 50,
particlelifespread = 10,
particlesize = 8,
particlesizespread = 48,
particlespeed = 1,
particlespeedspread = 4,
pos = [[r16 r-16, r16 r-16, r16 r-16]],
sizegrowth = -0.5,
sizemod = 1,
texture = [[smokesmall]],
},
},
},
["slam_seacloud_ring"] = {
cloud = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.95,
alwaysvisible = true,
colormap = [[0 0 0 0 1.0 1.0 0.8 0.1 1 1 0.8 0.08 0.8 1 1 0.04 0 0 0 0.001]],
directional = false,
emitrot = 70,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.05, 0]],
numparticles = 24,
particlelife = 50,
particlelifespread = 10,
particlesize = 9,
particlesizespread = 9,
particlespeed = 6,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 0.25,
sizemod = 1,
texture = [[smokesmall]],
},
},
},
["slam_seacloud_cap"] = {
cloud = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0 0 0 0 0.8 0.8 1 0.5 0.8 0.8 1 0.4 0.8 0.8 1 0.25 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 4,
particlelife = 15,
particlelifespread = 5,
particlesize = 6,
particlesizespread = 12,
particlespeed = 4,
particlespeedspread = 4,
pos = [[r16 r-16, r16 r-16, r16 r-16]],
sizegrowth = 12,
sizemod = 0.6,
texture = [[smokesmall]],
},
},
},
["slam_seacloud_pillar"] = {
cloud = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0 0 0 0 1.0 1.0 0.8 0.5 0.8 0.8 1 0.4 0.8 0.8 1 0.25 0 0 0 0]],
directional = false,
emitrot = 0,
emitrotspread = 90,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 1,
particlelife = 40,
particlelifespread = 10,
particlesize = 2,
particlesizespread = 2,
particlespeed = 1,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 6,
sizemod = 0.925,
texture = [[smokesmall]],
},
},
},
["slam_landcloud_pillar"] = {
land = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0 0 0 0 1 1 1 0.04 0.75 0.6 0.45 0.02 0.1 0.1 0 0.01 0.1 0 0 0.001]],
directional = false,
emitrot = 0,
emitrotspread = 90,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 1,
particlelife = 45,
particlelifespread = 10,
particlesize = 256,
particlesizespread = 64,
particlespeed = 1,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 24,
sizemod = 0.5,
texture = [[smokesmall]],
},
},
},
["slam_topsuction"] = {
land = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.5,
alwaysvisible = true,
colormap = [[0 0 0 0 1 1 1 0.04 0.75 0.6 0.45 0.02 0.1 0.1 0 0.01 0.1 0 0 0.001]],
directional = false,
emitrot = 0,
emitrotspread = 0,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 1,
particlelife = 15,
particlelifespread = 0,
particlesize = 96,
particlesizespread = 256,
particlespeed = 27,
particlespeedspread = 4,
pos = [[r32 r-32, r16 r-16, r32 r-32]],
sizegrowth = 32,
sizemod = 0.25,
texture = [[smokesmall]],
},
},
},
["slam_sparks_smokejets"] = {
intense_center1 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 20,
ground = true,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
airdrag = 1,
colormap = [[1 0.6 0 0.1 1.0 0.7 0.4 1 0.05 0.05 0.05 0.1]],
directional = false,
emitrot = 0,
emitrotspread = 10,
emitvector = [[0.5, 1, 0.5]],
gravity = [[0.015 i-0.0015, -0.3 i+0.015,0.015 i-0.0015]],
numparticles = 1,
particlelife = [[50 i-0.5]],
particlelifespread = 0,
particlesize = [[10 i0.8]],
particlesizespread = 0,
particlespeed = [[5 i-0.25]],
particlespeedspread = 2,
pos = [[0, 0, 0]],
sizegrowth = [[-0.1 i0.015]],
sizemod = 1.0,
texture = [[smokesmall]],
},
},
intense_center2 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 20,
ground = true,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
airdrag = 1,
colormap = [[1 0.6 0 0.1 1.0 0.7 0.4 1 0.05 0.05 0.05 0.1]],
directional = true,
emitrot = 0,
emitrotspread = 10,
emitvector = [[-0.8, 1, -0.2]],
gravity = [[-0.024 i+0.0024, -0.3 i+0.015,-0.006 i+0.0006]],
numparticles = 1,
particlelife = [[50 i-0.5]],
particlelifespread = 0,
particlesize = [[10 i0.8]],
particlesizespread = 0,
particlespeed = [[5 i-0.25]],
particlespeedspread = 2,
pos = [[0, 0, 0]],
sizegrowth = [[-0.1 i0.015]],
sizemod = 1.0,
texture = [[smokesmall]],
},
},
intense_center3 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 20,
ground = true,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
airdrag = 1,
colormap = [[1 0.6 0 0.1 1.0 0.7 0.4 1 0.05 0.05 0.05 0.1]],
directional = true,
emitrot = 0,
emitrotspread = 10,
emitvector = [[0.2, 1, -0.8]],
gravity = [[0.006 i-0.0006, -0.3 i+0.015,-0.024 i+0.0024]],
numparticles = 1,
particlelife = [[50 i-0.5]],
particlelifespread = 0,
particlesize = [[10 i0.8]],
particlesizespread = 0,
particlespeed = [[5 i-0.25]],
particlespeedspread = 2,
pos = [[0, 0, 0]],
sizegrowth = [[-0.1 i0.015]],
sizemod = 1.0,
texture = [[smokesmall]],
},
},
star1 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 5,
ground = true,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
airdrag = 1,
colormap = [[1 0.7 0.3 0.01 1 0.7 0.3 0.01 0.5 0.35 0.15 0.01 0.05 0.05 0.05 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 10,
emitvector = [[0.5, 1, 0.5]],
gravity = [[0.015 i-0.0015, -0.3 i+0.015,0.015 i-0.0015]],
numparticles = 2,
particlelife = [[50 i-0.5]],
particlelifespread = 0,
particlesize = [[10 i0.8]],
particlesizespread = 0,
particlespeed = [[5 i-0.25]],
particlespeedspread = 2,
pos = [[0, 0, 0]],
sizegrowth = [[-0.1 i0.015]],
sizemod = 1.0,
texture = [[plasma]],
},
},
star2 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 5,
ground = true,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
airdrag = 1,
colormap = [[1 0.7 0.3 0.01 1 0.7 0.3 0.01 0.5 0.35 0.15 0.01 0.05 0.05 0.05 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 10,
emitvector = [[-0.8, 1, -0.2]],
gravity = [[-0.024 i+0.0024, -0.3 i+0.015,-0.006 i+0.0006]],
numparticles = 2,
particlelife = [[50 i-0.5]],
particlelifespread = 0,
particlesize = [[10 i0.8]],
particlesizespread = 0,
particlespeed = [[5 i-0.25]],
particlespeedspread = 2,
pos = [[0, 0, 0]],
sizegrowth = [[-0.1 i0.015]],
sizemod = 1.0,
texture = [[plasma]],
},
},
star3 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 7,
ground = true,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
airdrag = 1,
colormap = [[1 0.7 0.3 0.01 1 0.7 0.3 0.01 0.5 0.35 0.15 0.01 0.05 0.05 0.05 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 10,
emitvector = [[0.2, 1, -0.8]],
gravity = [[0.006 i-0.0006, -0.3 i+0.015,-0.024 i+0.0024]],
numparticles = 2,
particlelife = [[50 i-0.5]],
particlelifespread = 0,
particlesize = [[10 i0.8]],
particlesizespread = 0,
particlespeed = [[5 i-0.25]],
particlespeedspread = 2,
pos = [[0, 0, 0]],
sizegrowth = [[-0.1 i0.015]],
sizemod = 1.0,
texture = [[plasma]],
},
},
},
["slam_flash"] = {
dirtg = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.875,
alwaysvisible = true,
colormap = [[1.0 0.75 0.0 0.0 0.0 0.075 0.1 0.75 0.0 0.075 0.1 0.4 0.0 0.0 0.0 0.01]],
directional = false,
emitrot = 80,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.2, 0]],
numparticles = 30,
particlelife = 10,
particlelifespread = 6,
particlesize = 30,
particlesizespread = 15,
particlespeed = 10,
particlespeedspread = 6,
pos = [[0, 5, 0]],
sizegrowth = -2.5,
sizemod = 1,
texture = [[dirt]],
},
},
groundflash = {
air = true,
alwaysvisible = true,
circlealpha = 0.0,
circlegrowth = 0,
flashalpha = 0.9,
flashsize = 85,
ground = true,
ttl = 13,
water = true,
underwater = true,
color = {
[1] = 1,
[2] = 0.5,
[3] = 0,
},
},
poof1 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.05,
alwaysvisible = true,
colormap = [[0.9 0.8 0.7 0.03 0.9 0.2 0.2 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 50,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 20,
particlelife = 4,
particlelifespread = 4,
particlesize = 10,
particlesizespread = 0,
particlespeed = 25,
particlespeedspread = 75,
pos = [[0, 2, 0]],
sizegrowth = 10,
sizemod = 1,
texture = [[flashside2]],
useairlos = false,
},
},
shock1 = {
air = true,
class = [[CSpherePartSpawner]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
alpha = 0.02,
ttl = 64,
expansionSpeed = 5,
color = [[1, 0.75, 0]],
},
},
shock2 = {
air = true,
class = [[CSpherePartSpawner]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
alpha = 0.02,
ttl = 32,
expansionSpeed = 10,
color = [[1, 0.75, 0]],
},
},
shock3 = {
air = true,
class = [[CSpherePartSpawner]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
alpha = 0.02,
ttl = 16,
expansionSpeed = 20,
color = [[1, 0.75, 0]],
},
},
pop1 = {
air = true,
class = [[heatcloud]],
count = 2,
ground = true,
water = true,
underwater = true,
properties = {
alwaysvisible = true,
heat = 375,
heatfalloff = 10,
maxheat = 4000,
pos = [[r35 r-35, 35 r-20, r60 r-60]],
size = 300,
sizegrowth = -1,
speed = [[0, 0, 0]],
texture = [[flare]],
},
},
heatglow = {
class = [[CSimpleGroundFlash]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
colorMap = [[1 0.9 0.8 1.0 1 0.4 0 0.9 0.0 0.0 0.0 0.01]],
size = 110,
sizegrowth = -0.025,
texture = [[groundflash]],
ttl = 125,
},
},
},
["slam_ray"] = {
gravspike1 = {
air = true,
class = [[CExploSpikeProjectile]],
count = 3,
ground = true,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
length = 250,
width = 50,
alpha = 0.375,
alphaDecay = 0.012,
dir = [[dir]],
color = [[1, 0.4, 0]],
pos = [[10 r-20, 0, 10 r-20]],
},
},
},
["slam_water_pillar"] = {
mainhit = {
class = [[CBitmapMuzzleFlame]],
count = 4,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
colormap = [[0.45 0.45 0.5 0.5 0.045 0.045 0.05 0.05]],
dir = [[-0.1 r0.2, 1, -0.1 r0.2]],
frontoffset = 0,
fronttexture = [[splashbase]],
length = [[48 r32]],
sidetexture = [[splashside]],
size = [[12 r8]],
sizegrowth = 1.8,
ttl = 24,
},
},
},
["slam_water_droplets"] = {
watermist = {
class = [[CSimpleParticleSystem]],
count = 1,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
airdrag = 0.99,
colormap = [[0.0 0 0.0 0.000
1.0 1 0.8 0.100
0.8 1 1.0 0.075
0.8 1 1.0 0.025
0.8 1 1.0 0.000]],
directional = false,
emitrot = 30,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.1, 0]],
numparticles = 48,
particlelife = 50,
particlelifespread = 0,
particlesize = 5,
particlesizespread = 15,
particlespeed = 6,
particlespeedspread = 0,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1,
texture = [[randdots]],
},
},
},
["slam_air_scrap_particles"] = {
scrap_particles = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
--ground = true,
properties = {
alwaysVisible = true,
airdrag = 0.989,
colormap = [[0.25 0.25 0.2 0.01
0.10 0.10 0.1 1.00
0.10 0.10 0.1 0.90
0.10 0.10 0.1 0.70
0.10 0.10 0.1 0.00]],
directional = false,
emitrot = 0,
emitrotspread = 0,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.2, 0]],
numparticles = 1,
particlelife = 40,
particlelifespread = 8,
particlesize = 16,
particlesizespread = 0,
particlespeed = 0,
particlespeedspread = 0,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1,
texture = [[randdots]],
},
},
},
["slam_air_scrap_fragments"] = {
scrap_fragments = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
--ground = true,
properties = {
alwaysVisible = true,
airdrag = 0.99,
colormap = [[0.25 0.25 0.20 0.0
0.15 0.15 0.15 1.0
0.15 0.15 0.15 0.9
0.15 0.15 0.15 0.7
0.15 0.15 0.15 0.0]],
directional = false,
emitrot = 0,
emitrotspread = 0,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.2, 0]],
numparticles = 6,
particlelife = 50,
particlelifespread = 10,
particlesize = 4,
particlesizespread = 8,
particlespeed = 0,
particlespeedspread = 0,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1,
texture = [[randdots]],
},
},
},
["slam_trail"] = {
alwaysvisible = false,
usedefaultexplosions = false,
smoke_front = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.6,
colormap = [[0.1 0.09 0.075 0.10
1.0 0.20 0.100 0.10
0.1 0.10 0.080 0.60
0.1 0.10 0.080 0.40
0.0 0.00 0.000 0.01]],
directional = false,
emitrot = 0,
emitrotspread = 5,
emitvector = [[dir]],
gravity = [[0.5 r-1, 0.5 r-1, 0.5 r-1]],
numparticles = 3,
particlelife = 22,
particlelifespread = 2,
particlesize = 7,
particlesizespread = 8,
particlespeed = 1,
particlespeedspread = 5,
pos = [[0, 1, 3]],
sizegrowth = 0,
sizemod = 1.05,
texture = [[smoke]],
},
},
},
["slam_heat_pillar"] = {
gravspike1 = {
air = true,
class = [[CExploSpikeProjectile]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
alwaysVisible = true,
length = 70,
width = 105,
alpha = 0.1,
alphaDecay = 0.001,
dir = [[dir]],
color = [[1, 0.4, 0]],
pos = [[0, 0, 0]],
},
},
},
["slam_muzzle"] = {
smoke = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
underwater = 1,
water = true,
properties = {
airdrag = 0.9,
colormap = [[0.12 0.1 0.1 0.80
0.12 0.1 0.1 0.60
0.12 0.1 0.1 0.60
0.00 0.0 0.0 0.01]],
directional = false,
dir = [[dir]],
emitrot = 15,
emitrotspread = 75,
emitvector = [[0, 1, 0]],
gravity = [[0.0, 0.01, 0.0]],
numparticles = 20,
particlelife = 25,
particlelifespread = 10,
particlesize = 21,
particlesizespread = 21,
particlespeed = 4,
particlespeedspread = 0,
pos = [[0.0, 4, 0.0]],
sizegrowth = 0,
sizemod = 1,
texture = [[smoke]],
useairlos = true,
},
},
},
}
| gpl-2.0 |
alisa-dolinsky/Thirst | src/thirst.lua | 3 | 5455 | if not table.unpack and unpack then table.unpack = unpack end -- polyfill
local sentinel = {}
local quote_sentinel = {}
local void = {}
local function exit (operands) print ('result', table.unpack (operands)) print ('exit') end
local function quote (operands) return operands end
local operator_prototype_base
local operator_prototype
operator_prototype_base = function (operators, execute, definitions)
local base
base = {
delimiter = sentinel,
delimit_counter = 1,
operands = {},
handle_operators = function (_) table.insert (operators, operator_prototype (operators, _, definitions)) end,
handle_operands = function (_) table.insert (base.operands, _) end,
run = function (...)
local args = {...}
local _
while (function () _ =
table.remove (args, 1)
if _ == base.delimiter then base.delimit_counter = base.delimit_counter - 1 end
return not (_ == nil or _ == void) and base.delimit_counter > 0 end) ()
do
if type (_) == 'function' then base.handle_operators (_) else base.handle_operands (_) end
end
-- debug
-- print (base.delimit_counter)
-- debug
if base.delimit_counter <= 0 then
for i = #operators, 1, -1 do -- remove self
if operators[i] == base.run then table.remove (operators, i) break end
end
local output = { execute (base.operands, operators, definitions) }
for i, v in ipairs (args) do table.insert (output, v) end
return output
end
end }
return base
end
operator_prototype = function (operators, execute, definitions)
local base = operator_prototype_base (operators, execute, definitions)
-- polymorphic dispatch
if execute == quote then -- suspend execution of quoted
base.delimiter = quote_sentinel
base.handle_operators = function (_)
if _ == quote_sentinel then base.delimit_counter = base.delimit_counter + 1 else base.handle_operands (_) end
end
elseif execute == exit then base.delimiter = exit end
return base.run
end
function eval (operands, operators, definitions)
for i, v in ipairs (operands) do
local _ = operators[#operators] (v)
while not (_ == nil or #operators == 0) do -- check!
local args = {}
for i, v in ipairs (_) do -- TODO: handle more than one returned function!
if type (v) == 'function' then table.insert (operators, operator_prototype (operators, v, definitions))
else table.insert (args, v) end
end
_ = operators[#operators] (table.unpack (args))
end
end
end
function processor_prototype ()
local definitions = {}
local operators = {}
table.insert (operators, operator_prototype (operators, exit, definitions))
return function (...) if #operators > 0 then eval ({...}, operators, definitions)
else
print ('the program had ended its execution, any further invocations are futile') end
end
end
function eval_quotes (operands, operators)
for i, v in ipairs (operands) do eval (v, operators) end
end
local function combinator_prototype (op)
return function (operands)
local _ = table.remove (operands, 1)
for i, v in ipairs (operands) do
-- debug
-- if type(v) == 'table' then print ('table', table.unpack (v)) end
-- debug
_ = op (_, v) end
return _
end
end
local add = combinator_prototype (function (x, y) return x + y end)
local sub = combinator_prototype (function (x, y) return x - y end)
local mul = combinator_prototype (function (x, y) return x * y end)
local div = combinator_prototype (function (x, y) return x / y end)
local loop
loop = function (operands, operators)
local idx = operands[1]
local limit = operands[2]
local step = operands[3]
print('loop', table.unpack (operands))
if idx < limit then return loop, idx + step, limit, step, sentinel else return void end
end
-- [ fork [ ] void true . ]
local fork = function (operands, operators)
-- table.insert (operators, operator_prototype (operators, eval_quotes))
local left = operands[1]
local right = operands[2]
local predicate = operands[3]
local evaluated
if predicate then evaluated = left else evaluated = right end
return eval_quotes, evaluated, sentinel -- evaluate right away
end
local define = function (operands, operators, definitions)
local symbol = operands[1]
local quotation = operands[2]
definitions[symbol] = quotation
return void
end
local refer = function (operands, operators, definitions)
local symbol = operands[1]
return definitions[symbol]
end
local app = processor_prototype ()
app (add, eval_quotes, quote, div, 1, 2, 3, add, 4, 5, 6, sentinel, sentinel, quote_sentinel, quote, div, 1, 2, 3, add, 4, 5, 6, sentinel, sentinel, quote_sentinel, sentinel, sentinel, exit)
app ()
app2 = processor_prototype ()
app2 (fork, quote, add, 1, 2, 3, sentinel, quote_sentinel, quote, sub, 1, 2, 3, sentinel, quote_sentinel, false, sentinel, exit)
app3 = processor_prototype ()
app3 (loop, 0, 10, 2, sentinel, exit)
app4 = processor_prototype ()
app4 (define, 'test', quote, add, 1, 2, 3, quote_sentinel, sentinel, eval_quotes, refer, 'test', sentinel, sentinel, 4, sentinel, exit) | mit |
LanceJenkinZA/prosody-modules | mod_muc_limits/mod_muc_limits.lua | 10 | 3327 |
local mod_muc = module:depends"muc";
local rooms = rawget(mod_muc, "rooms"); -- Old MUC API
if not rooms then
rooms = module:shared"muc/rooms"; -- New MUC API
end
local jid_split, jid_bare = require "util.jid".split, require "util.jid".bare;
local st = require "util.stanza";
local new_throttle = require "util.throttle".create;
local t_insert, t_concat = table.insert, table.concat;
local xmlns_muc = "http://jabber.org/protocol/muc";
local period = math.max(module:get_option_number("muc_event_rate", 0.5), 0);
local burst = math.max(module:get_option_number("muc_burst_factor", 6), 1);
local max_nick_length = module:get_option_number("muc_max_nick_length", 23); -- Default chosen through scientific methods
local dropped_count = 0;
local dropped_jids;
local function log_dropped()
module:log("warn", "Dropped %d stanzas from %d JIDs: %s", dropped_count, #dropped_jids, t_concat(dropped_jids, ", "));
dropped_count = 0;
dropped_jids = nil;
end
local function handle_stanza(event)
local origin, stanza = event.origin, event.stanza;
if stanza.name == "presence" and stanza.attr.type == "unavailable" then -- Don't limit room leaving
return;
end
local dest_room, dest_host, dest_nick = jid_split(stanza.attr.to);
local room = rooms[dest_room.."@"..dest_host];
if not room then return; end
local from_jid = stanza.attr.from;
local occupant = room._occupants[room._jid_nick[from_jid]];
if (occupant and occupant.affiliation) or (not(occupant) and room._affiliations[jid_bare(from_jid)]) then
module:log("debug", "Skipping stanza from affiliated user...");
return;
elseif dest_nick and max_nick_length and stanza.name == "presence" and not room._occupants[stanza.attr.to] and #dest_nick > max_nick_length then
module:log("debug", "Forbidding long (%d bytes) nick in %s", #dest_nick, dest_room)
origin.send(st.error_reply(stanza, "modify", "policy-violation", "Your nick name is too long, please use a shorter one")
:up():tag("x", { xmlns = xmlns_muc }));
return true;
end
local throttle = room.throttle;
if not room.throttle then
throttle = new_throttle(period*burst, burst);
room.throttle = throttle;
end
if not throttle:poll(1) then
module:log("debug", "Dropping stanza for %s@%s from %s, over rate limit", dest_room, dest_host, from_jid);
if not dropped_jids then
dropped_jids = { [from_jid] = true, from_jid };
module:add_timer(5, log_dropped);
elseif not dropped_jids[from_jid] then
dropped_jids[from_jid] = true;
t_insert(dropped_jids, from_jid);
end
dropped_count = dropped_count + 1;
if stanza.attr.type == "error" then -- We don't want to bounce errors
return true;
end
local reply = st.error_reply(stanza, "wait", "policy-violation", "The room is currently overactive, please try again later");
local body = stanza:get_child_text("body");
if body then
reply:up():tag("body"):text(body):up();
end
local x = stanza:get_child("x", xmlns_muc);
if x then
reply:add_child(st.clone(x));
end
origin.send(reply);
return true;
end
end
function module.unload()
for room_jid, room in pairs(rooms) do
room.throttle = nil;
end
end
module:hook("message/bare", handle_stanza, 501);
module:hook("message/full", handle_stanza, 501);
module:hook("presence/bare", handle_stanza, 501);
module:hook("presence/full", handle_stanza, 501);
| mit |
imashkan/ABCYAGOP | plugins/meme.lua | 637 | 5791 | local helpers = require "OAuth.helpers"
local _file_memes = './data/memes.lua'
local _cache = {}
local function post_petition(url, arguments)
local response_body = {}
local request_constructor = {
url = url,
method = "POST",
sink = ltn12.sink.table(response_body),
headers = {},
redirect = false
}
local source = arguments
if type(arguments) == "table" then
local source = helpers.url_encode_arguments(arguments)
end
request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded"
request_constructor.headers["Content-Length"] = tostring(#source)
request_constructor.source = ltn12.source.string(source)
local ok, response_code, response_headers, response_status_line = http.request(request_constructor)
if not ok then
return nil
end
response_body = json:decode(table.concat(response_body))
return response_body
end
local function upload_memes(memes)
local base = "http://hastebin.com/"
local pet = post_petition(base .. "documents", memes)
if pet == nil then
return '', ''
end
local key = pet.key
return base .. key, base .. 'raw/' .. key
end
local function analyze_meme_list()
local function get_m(res, n)
local r = "<option.*>(.*)</option>.*"
local start = string.find(res, "<option.*>", n)
if start == nil then
return nil, nil
end
local final = string.find(res, "</option>", n) + #"</option>"
local sub = string.sub(res, start, final)
local f = string.match(sub, r)
return f, final
end
local res, code = http.request('http://apimeme.com/')
local r = "<option.*>(.*)</option>.*"
local n = 0
local f, n = get_m(res, n)
local ult = {}
while f ~= nil do
print(f)
table.insert(ult, f)
f, n = get_m(res, n)
end
return ult
end
local function get_memes()
local memes = analyze_meme_list()
return {
last_time = os.time(),
memes = memes
}
end
local function load_data()
local data = load_from_file(_file_memes)
if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then
data = get_memes()
-- Upload only if changed?
link, rawlink = upload_memes(table.concat(data.memes, '\n'))
data.link = link
data.rawlink = rawlink
serialize_to_file(data, _file_memes)
end
return data
end
local function match_n_word(list1, list2)
local n = 0
for k,v in pairs(list1) do
for k2, v2 in pairs(list2) do
if v2:find(v) then
n = n + 1
end
end
end
return n
end
local function match_meme(name)
local _memes = load_data()
local name = name:lower():split(' ')
local max = 0
local id = nil
for k,v in pairs(_memes.memes) do
local n = match_n_word(name, v:lower():split(' '))
if n > 0 and n > max then
max = n
id = v
end
end
return id
end
local function generate_meme(id, textup, textdown)
local base = "http://apimeme.com/meme"
local arguments = {
meme=id,
top=textup,
bottom=textdown
}
return base .. "?" .. helpers.url_encode_arguments(arguments)
end
local function get_all_memes_names()
local _memes = load_data()
local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n'
for k, v in pairs(_memes.memes) do
text = text .. '- ' .. v .. '\n'
end
text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/'
return text
end
local function callback_send(cb_extra, success, data)
if success == 0 then
send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false)
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == 'list' then
local _memes = load_data()
return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link
elseif matches[1] == 'listall' then
if not is_sudo(msg) then
return "You can't list this way, use \"!meme list\""
else
return get_all_memes_names()
end
elseif matches[1] == "search" then
local meme_id = match_meme(matches[2])
if meme_id == nil then
return "I can't match that search with any meme."
end
return "With that search your meme is " .. meme_id
end
local searchterm = string.gsub(matches[1]:lower(), ' ', '')
local meme_id = _cache[searchterm] or match_meme(matches[1])
if not meme_id then
return 'I don\'t understand the meme name "' .. matches[1] .. '"'
end
_cache[searchterm] = meme_id
print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3])
local url_gen = generate_meme(meme_id, matches[2], matches[3])
send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen})
return nil
end
return {
description = "Generate a meme image with up and bottom texts.",
usage = {
"!meme search (name): Return the name of the meme that match.",
"!meme list: Return the link where you can see the memes.",
"!meme listall: Return the list of all memes. Only admin can call it.",
'!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.',
'!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.',
},
patterns = {
"^!meme (search) (.+)$",
'^!meme (list)$',
'^!meme (listall)$',
'^!meme (.+) "(.*)" "(.*)"$',
'^!meme "(.+)" "(.*)" "(.*)"$',
"^!meme (.+) %- (.*) %- (.*)$"
},
run = run
}
| gpl-2.0 |
lxl1140989/dmsdk | feeds/luci/protocols/ipv6/luasrc/model/network/proto_6x4.lua | 78 | 1602 | --[[
LuCI - Network model - 6to4, 6in4 & 6rd protocol extensions
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local netmod = luci.model.network
local _, p
for _, p in ipairs({"6in4", "6to4", "6rd"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "6in4" then
return luci.i18n.translate("IPv6-in-IPv4 (RFC4213)")
elseif p == "6to4" then
return luci.i18n.translate("IPv6-over-IPv4 (6to4)")
elseif p == "6rd" then
return luci.i18n.translate("IPv6-over-IPv4 (6rd)")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
return p
end
function proto.is_installed(self)
return nixio.fs.access("/lib/netifd/proto/" .. p .. ".sh")
end
function proto.is_floating(self)
return true
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
return nil
end
function proto.contains_interface(self, ifname)
return (netmod:ifnameof(ifc) == self:ifname())
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
| gpl-2.0 |
imashkan/ABCYAGOP | plugins/search_youtube.lua | 674 | 1270 | do
local google_config = load_from_file('data/google.lua')
local function httpsRequest(url)
print(url)
local res,code = https.request(url)
if code ~= 200 then return nil end
return json:decode(res)
end
local function searchYoutubeVideos(text)
local url = 'https://www.googleapis.com/youtube/v3/search?'
url = url..'part=snippet'..'&maxResults=4'..'&type=video'
url = url..'&q='..URL.escape(text)
if google_config.api_keys then
local i = math.random(#google_config.api_keys)
local api_key = google_config.api_keys[i]
if api_key then
url = url.."&key="..api_key
end
end
local data = httpsRequest(url)
if not data then
print("HTTP Error")
return nil
elseif not data.items then
return nil
end
return data.items
end
local function run(msg, matches)
local text = ''
local items = searchYoutubeVideos(matches[1])
if not items then
return "Error!"
end
for k,item in pairs(items) do
text = text..'http://youtu.be/'..item.id.videoId..' '..
item.snippet.title..'\n\n'
end
return text
end
return {
description = "Search video on youtube and send it.",
usage = "!youtube [term]: Search for a youtube video and send it.",
patterns = {
"^!youtube (.*)"
},
run = run
}
end
| gpl-2.0 |
Stepets/utf8.lua | begins/compiletime/vanilla.lua | 1 | 1078 | return function(utf8)
local matchers = {
sliding = function()
return [[
add(function(ctx) -- sliding
while ctx.pos <= ctx.len do
local clone = ctx:clone()
-- debug('starting from', clone, "start_pos", clone.pos)
clone.result.start = clone.pos
clone:next_function()
clone:get_function()(clone)
ctx:next_char()
end
ctx:terminate()
end)
]]
end,
fromstart = function(ctx)
return [[
add(function(ctx) -- fromstart
if ctx.byte_pos > ctx.len then
return
end
ctx.result.start = ctx.pos
ctx:next_function()
ctx:get_function()(ctx)
ctx:terminate()
end)
]]
end,
}
local function default()
return matchers.sliding()
end
local function parse(regex, c, bs, ctx)
if bs ~= 1 then return end
local functions
local skip = 0
if c == '^' then
functions = matchers.fromstart()
skip = 1
else
functions = matchers.sliding()
end
return functions, skip
end
return {
parse = parse,
default = default,
}
end
| mit |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/coreter.lua | 1 | 3088 | return {
coreter = {
acceleration = 0.040699999779463,
activatewhenbuilt = true,
brakerate = 0.019799999892712,
buildcostenergy = 1757,
buildcostmetal = 100,
buildpic = "CORETER.DDS",
buildtime = 6404,
canattack = false,
canmove = true,
category = "ALL TANK MOBILE NOTSUB NOWEAPON NOTSHIP NOTAIR NOTHOVER SURFACE",
collisionvolumeoffsets = [[0 -3 0]],
collisionvolumescales = [[25.5 26.5 47.5]],
collisionvolumetest = 1,
collisionvolumetype = "CylZ",
corpse = "DEAD",
description = "Radar Jammer Vehicle",
energyuse = 100,
explodeas = "SMALL_UNITEX",
footprintx = 3,
footprintz = 3,
idleautoheal = 5,
idletime = 1800,
leavetracks = true,
maxdamage = 520,
maxslope = 16,
maxvelocity = 1.4520000219345,
maxwaterdepth = 0,
movementclass = "TANK3",
name = "Deleter",
nochasecategory = "MOBILE",
objectname = "CORETER",
onoffable = true,
radardistancejam = 450,
seismicsignature = 0,
selfdestructas = "SMALL_UNIT",
sightdistance = 299,
trackoffset = 3,
trackstrength = 6,
tracktype = "StdTank",
trackwidth = 27,
turnrate = 619.29998779297,
featuredefs = {
dead = {
blocking = true,
category = "corpses",
collisionvolumeoffsets = "1.41645812988 -2.61718749996e-05 1.27348327637",
collisionvolumescales = "29.8956298828 22.6313476563 49.5100708008",
collisionvolumetype = "Box",
damage = 312,
description = "Deleter Wreckage",
energy = 0,
featuredead = "HEAP",
featurereclamate = "SMUDGE01",
footprintx = 3,
footprintz = 3,
height = 20,
hitdensity = 100,
metal = 65,
object = "CORETER_DEAD",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
heap = {
blocking = false,
category = "heaps",
damage = 156,
description = "Deleter Heap",
energy = 0,
featurereclamate = "SMUDGE01",
footprintx = 3,
footprintz = 3,
height = 4,
hitdensity = 100,
metal = 26,
object = "3X3F",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
},
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "vcormove",
},
select = {
[1] = "radjam2",
},
},
weapondefs = {
bogus_ground_missile = {
areaofeffect = 48,
craterboost = 0,
cratermult = 0,
impulseboost = 0,
impulsefactor = 0,
metalpershot = 0,
name = "Missiles",
range = 800,
reloadtime = 0.5,
startvelocity = 450,
tolerance = 9000,
turnrate = 33000,
turret = true,
weaponacceleration = 101,
weapontimer = 0.10000000149012,
weapontype = "Cannon",
weaponvelocity = 650,
damage = {
default = 0,
},
},
},
weapons = {
[1] = {
badtargetcategory = "MOBILE",
def = "BOGUS_GROUND_MISSILE",
onlytargetcategory = "NOTSUB",
},
},
},
}
| gpl-2.0 |
Anarchid/Zero-K | LuaUI/Widgets/unit_selectionblurryhalo.lua | 6 | 17502 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Selection BlurryHalo",
desc = "Shows a halo for selected, hovered ally-selected units.",
author = "CarRepairer, from jK's gfx_halo, modified by Shadowfury333 and aeonios",
date = "Jan, 2017",
version = "1.0",
license = "GNU GPL, v2 or later",
layer = -11,
enabled = false -- loaded by default?
}
end
local SafeWGCall = function(fnName, param1) if fnName then return fnName(param1) else return nil end end
local GetUnitUnderCursor = function(onlySelectable) return SafeWGCall(WG.PreSelection_GetUnitUnderCursor, onlySelectable) end
local IsSelectionBoxActive = function() return SafeWGCall(WG.PreSelection_IsSelectionBoxActive) end
local GetUnitsInSelectionBox = function() return SafeWGCall(WG.PreSelection_GetUnitsInSelectionBox) end
local IsUnitInSelectionBox = function(unitID) return SafeWGCall(WG.PreSelection_IsUnitInSelectionBox, unitID) end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
options_path = 'Settings/Interface/Selection/Blurry Halo Selections'
options_order = {
'showAlly',
'thickness',
'blur',
}
options = {
showAlly = {
name = 'Show Ally Selections',
type = 'bool',
desc = 'Highlight the units your allies currently have selected.',
value = true,
},
thickness = {
name = 'Outline Thickness',
desc = 'How thick the outline appears around objects',
type = 'number',
min = 1, max = 16, step = 1,
value = 10,
},
blur = {
name = 'Outline Blurriness',
desc = 'How smooth the outlines appear',
type = 'number',
min = 2, max = 16, step = 1,
value = 16,
},
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local blurtex1
local blurtex2
local masktex
local fbo
local featherShader_h
local featherShader_v
local blurShader_h
local blurShader_v
local maskGenShader
local maskApplyShader
local invRXloc, invRYloc, screenXloc, screenYloc
local radiusXloc, radiusYloc, thkXloc, thkYloc
local haloColorloc
local vsx, vsy = 1,1
local ivsx, ivsy = 1,1
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// speed ups
local ALL_UNITS = Spring.ALL_UNITS
local spGetMyTeamID = Spring.GetMyTeamID
local spGetUnitTeam = Spring.GetUnitTeam
local spValidUnitID = Spring.ValidUnitID
local ValidFeatureID = Spring.ValidFeatureID
local spIsUnitAllied = Spring.IsUnitAllied
local spIsUnitSelected = Spring.IsUnitSelected
local spGetMouseState = Spring.GetMouseState
local spTraceScreenRay = Spring.TraceScreenRay
local spGetCameraPosition = Spring.GetCameraPosition
local spGetGroundHeight = Spring.GetGroundHeight
local spGetPlayerControlledUnit = Spring.GetPlayerControlledUnit
local spGetVisibleUnits = Spring.GetVisibleUnits
local spIsUnitIcon = Spring.IsUnitIcon
local GL_FRONT = GL.FRONT
local GL_BACK = GL.BACK
local GL_MODELVIEW = GL.MODELVIEW
local GL_PROJECTION = GL.PROJECTION
local GL_COLOR_BUFFER_BIT = GL.COLOR_BUFFER_BIT
local GL_DEPTH_BUFFER_BIT = GL.DEPTH_BUFFER_BIT
local GL_COLOR_ATTACHMENT0_EXT = 0x8CE0
local GL_COLOR_ATTACHMENT1_EXT = 0x8CE1
local glCreateTexture = gl.CreateTexture
local glDeleteTexture = gl.DeleteTexture
local glUnit = gl.Unit
local glFeature = gl.Feature
local glRenderToTexture = gl.RenderToTexture
local glActiveFBO = gl.ActiveFBO
local glUseShader = gl.UseShader
local glUniform = gl.Uniform
local glUniformInt = gl.UniformInt
local glClear = gl.Clear
local glTexRect = gl.TexRect
local glColor = gl.Color
local glTexture = gl.Texture
local glDepthTest = gl.DepthTest
local glBlending = gl.Blending
local echo = Spring.Echo
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function GetVisibleUnits()
local units = spGetVisibleUnits(-1, 30, false)
local boxedUnits = GetUnitsInSelectionBox();
local visibleAllySelUnits = {}
local visibleSelected = {}
local visibleBoxed = {}
for i=1, #units do
local unitID = units[i]
if (spIsUnitSelected(unitID)) then
visibleSelected[#visibleSelected+1] = unitID
elseif options.showAlly.value and WG.allySelUnits and WG.allySelUnits[unitID] then
local team = spGetUnitTeam(unitID)
if team then
if not visibleAllySelUnits[team] then
visibleAllySelUnits[team] = {}
end
visibleAllySelUnits[team][unitID] = true
end
end
if IsUnitInSelectionBox(unitID) then
visibleBoxed[#visibleBoxed+1] = unitID
end
end
return visibleAllySelUnits, visibleSelected, visibleBoxed
end
local function DrawSelected(visibleAllySelUnits, visibleSelected, visibleBoxed)
local featureHoverColor = { 1, 0, 1, 1}
local myHoverColor = { 0, 1, 1, 1 }
local enemyHoverColor = { 1, 0, 0, 1 }
local selectColor = { 0, 1, 0, 1}
glUniform(haloColorloc, selectColor[1], selectColor[2], selectColor[3], selectColor[4])
for i=1,#visibleSelected do
local unitID = visibleSelected[i]
glUnit(unitID,true,-1)
end
for teamID, data in pairs(visibleAllySelUnits) do
local r, g, b = Spring.GetTeamColor(teamID)
glUniform(haloColorloc, r, g, b, 1)
for unitID, _ in pairs(data) do
glUnit(unitID,true,-1)
end
end
glUniform(haloColorloc, myHoverColor[1], myHoverColor[2], myHoverColor[3], myHoverColor[4])
for i=1, #visibleBoxed do
local unitID = visibleBoxed[i]
glUnit(unitID,true,-1)
end
local mx, my = spGetMouseState()
local pointedType, data = spTraceScreenRay(mx, my, false, true)
if pointedType == 'unit' then
data = GetUnitUnderCursor(false) --Does minimap check and handles selection box as well
end
if pointedType == 'unit' and data and spValidUnitID(data) then
local teamID = spGetUnitTeam(data)
if teamID == spGetMyTeamID() then
glUniform(haloColorloc, myHoverColor[1], myHoverColor[2], myHoverColor[3], myHoverColor[4])
elseif (teamID and Spring.AreTeamsAllied(teamID, Spring.GetMyTeamID()) ) then
glUniform(haloColorloc, myHoverColor[1], myHoverColor[2], myHoverColor[3], myHoverColor[4])
else
glUniform(haloColorloc, enemyHoverColor[1], enemyHoverColor[2], enemyHoverColor[3], enemyHoverColor[4])
end
glUnit(data, true,-1)
elseif (pointedType == 'feature') and ValidFeatureID(data) then
glUniform(haloColorloc, featureHoverColor[1], featureHoverColor[2], featureHoverColor[3], featureHoverColor[4])
glFeature(data, true)
end
end
local function renderToTextureFunc(tex, s, t)
glTexture(tex)
glTexRect(-1 * s, -1 * t, 1 * s, 1 * t)
glTexture(false)
end
local function mglRenderToTexture(FBOTex, tex, s, t)
glRenderToTexture(FBOTex, renderToTextureFunc, tex, s, t)
end
function widget:DrawWorldPreUnit()
if Spring.IsGUIHidden() then
return
end
glBlending(false)
glDepthTest(false)
glRenderToTexture(blurtex1, glClear, GL_COLOR_BUFFER_BIT,0,0,0,0)
glRenderToTexture(masktex, glClear, GL_COLOR_BUFFER_BIT,1,1,1,1)
local visibleAllySelUnits, visibleSelected, visibleBoxed = GetVisibleUnits()
glUseShader(maskGenShader)
glActiveFBO(fbo, DrawSelected, visibleAllySelUnits, visibleSelected, visibleBoxed)
glUseShader(0)
end
function widget:DrawScreenEffects()
if Spring.IsGUIHidden() then
return
end
local x, y, z = spGetCameraPosition()
local _, coords = spTraceScreenRay(vsx/2, vsy/2, true)
if (coords) then
y = y - coords[2]
else
local iy = spGetGroundHeight(x, z)
if iy then
y = y - iy
end
end
y = math.max(1, y)
glBlending(false)
-- apply feathering
local thickness = options.thickness.value * math.min(2.0, math.max(750/y, 0.2))
thickness = math.max(thickness, 1)
glUseShader(featherShader_h)
glUniform(screenXloc, ivsx)
glUniform(thkXloc, thickness)
mglRenderToTexture(blurtex2, blurtex1, 1, -1)
glUseShader(0)
glUseShader(featherShader_v)
glUniform(screenYloc, ivsy)
glUniform(thkYloc, thickness)
mglRenderToTexture(blurtex1, blurtex2, 1, -1)
glUseShader(0)
-- apply blur over two iterations to approximate a gaussian
local blur = options.blur.value * math.min(2.0, math.max(750/y, 0.2))
blur = math.max(1, blur)
glUseShader(blurShader_h)
glUniform(invRXloc, ivsx)
glUniform(radiusXloc, blur)
mglRenderToTexture(blurtex2, blurtex1, 1, -1)
glUseShader(0)
glUseShader(blurShader_v)
glUniform(invRYloc, ivsy)
glUniform(radiusYloc, blur)
mglRenderToTexture(blurtex1, blurtex2, 1, -1)
glUseShader(0)
-- apply the halos and mask to the screen
glBlending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA)
glTexture(0, blurtex1)
glTexture(1, masktex)
glUseShader(maskApplyShader)
glTexRect(0, 0, vsx, vsy, false, true)
glUseShader(0)
glTexture(0, false)
glTexture(1, false)
glBlending(false)
end
local function ShowSelectionSquares(state)
if state then
WG.widgets_handling_selection = (WG.widgets_handling_selection or 1) - 1
if WG.widgets_handling_selection > 0 then
return
end
else
WG.widgets_handling_selection = (WG.widgets_handling_selection or 0) + 1
end
local alpha = state and 1 or 0
local f = io.open('cmdcolors.tmp', 'w+')
if (f) then
f:write('unitBox 0 1 0 ' .. alpha)
f:close()
Spring.SendCommands({'cmdcolors cmdcolors.tmp'})
end
os.remove('cmdcolors.tmp')
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- initializers
function widget:Initialize()
if not gl.CreateShader or not gl.CreateFBO then
Spring.Echo("Blurry Halo Selections: your card does not support shaders!")
widgetHandler:RemoveWidget()
return
end
fbo = gl.CreateFBO()
self:ViewResize()
maskGenShader = gl.CreateShader({
fragment = [[
uniform vec4 color;
void main(void) {
gl_FragData[0] = color;
gl_FragData[1] = vec4(0.0, 0.0, 0.0, 0.0);
}
]],
})
if (maskGenShader == nil) then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "Halo selection widget: mask generation shader error: "..gl.GetShaderLog())
widgetHandler:RemoveWidget()
return false
end
featherShader_h = gl.CreateShader({
fragment = [[
uniform sampler2D tex0;
uniform float screenX;
uniform float thickness;
void main(void) {
vec2 texCoord = gl_TexCoord[0].st;
vec4 color = texture2D(tex0, texCoord);
for (int i = 1; i <= thickness; i++){
vec4 tmpcolor1 = texture2D(tex0, vec2(texCoord.s + i * screenX,texCoord.t));
vec4 tmpcolor2 = texture2D(tex0, vec2(texCoord.s - i * screenX,texCoord.t));
color.r = max(color.r, max(tmpcolor1.r, tmpcolor2.r));
color.g = max(color.g, max(tmpcolor1.g, tmpcolor2.g));
color.b = max(color.b, max(tmpcolor1.b, tmpcolor2.b));
color.a = max(color.a, max(tmpcolor1.a, tmpcolor2.a));
}
gl_FragColor = color;
}
]],
uniformInt = {
tex0 = 0,
},
})
if (featherShader_h == nil) then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "Halo selection widget: hfeather shader error: "..gl.GetShaderLog())
widgetHandler:RemoveWidget()
return false
end
featherShader_v = gl.CreateShader({
fragment = [[
uniform sampler2D tex0;
uniform float screenY;
uniform float thickness;
void main(void) {
vec2 texCoord = gl_TexCoord[0].st;
vec4 color = texture2D(tex0, texCoord);
for (int i = 1; i <= thickness; i++){
vec4 tmpcolor1 = texture2D(tex0, vec2(texCoord.s,texCoord.t + i * screenY));
vec4 tmpcolor2 = texture2D(tex0, vec2(texCoord.s,texCoord.t - i * screenY));
color.r = max(color.r, max(tmpcolor1.r, tmpcolor2.r));
color.g = max(color.g, max(tmpcolor1.g, tmpcolor2.g));
color.b = max(color.b, max(tmpcolor1.b, tmpcolor2.b));
color.a = max(color.a, max(tmpcolor1.a, tmpcolor2.a));
}
gl_FragColor = color;
}
]],
uniformInt = {
tex0 = 0,
},
})
if (featherShader_v == nil) then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "Halo selection widget: vfeather shader error: "..gl.GetShaderLog())
widgetHandler:RemoveWidget()
return false
end
blurShader_h = gl.CreateShader({
fragment = [[
uniform sampler2D texture0;
uniform float inverseRX;
uniform float fragKernelRadius;
float bloomSigma = fragKernelRadius / 2.0;
void main(void) {
vec2 C0 = vec2(gl_TexCoord[0]);
vec4 S = texture2D(texture0, C0);
float weight = 1.0 / (2.50663 * bloomSigma);
float total_weight = weight;
S *= weight;
for (float r = 1.5; r < fragKernelRadius; r += 2.0)
{
weight = exp(-((r*r)/(2.0 * bloomSigma * bloomSigma)))/(2.50663 * bloomSigma);
S += texture2D(texture0, C0 - vec2(r * inverseRX, 0.0)) * weight;
S += texture2D(texture0, C0 + vec2(r * inverseRX, 0.0)) * weight;
total_weight += 2.0 * weight;
}
gl_FragColor = S/total_weight;
}
]],
uniformInt = {
texture0 = 0,
},
})
if (blurShader_h == nil) then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "Halo selection widget: hblur shader error: "..gl.GetShaderLog())
widgetHandler:RemoveWidget()
return false
end
blurShader_v = gl.CreateShader({
fragment = [[
uniform sampler2D texture0;
uniform float inverseRY;
uniform float fragKernelRadius;
float bloomSigma = fragKernelRadius / 2.0;
void main(void) {
vec2 C0 = vec2(gl_TexCoord[0]);
vec4 S = texture2D(texture0, C0);
float weight = 1.0 / (2.50663 * bloomSigma);
float total_weight = weight;
S *= weight;
for (float r = 1.5; r < fragKernelRadius; r += 2.0)
{
weight = exp(-((r*r)/(2.0 * bloomSigma * bloomSigma)))/(2.50663 * bloomSigma);
S += texture2D(texture0, C0 - vec2(0.0, r * inverseRY)) * weight;
S += texture2D(texture0, C0 + vec2(0.0, r * inverseRY)) * weight;
total_weight += 2.0 * weight;
}
gl_FragColor = S/total_weight;
}
]],
uniformInt = {
texture0 = 0,
},
})
if (blurShader_v == nil) then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "Halo selection widget: vblur shader error: "..gl.GetShaderLog())
widgetHandler:RemoveWidget()
return false
end
maskApplyShader = gl.CreateShader({
fragment = [[
uniform sampler2D tex0;
uniform sampler2D tex1;
void main(void) {
vec2 coord = gl_TexCoord[0].st;
vec4 haloColor = texture2D(tex0, coord);
haloColor.a *= texture2D(tex1, coord).a;
gl_FragColor = haloColor;
}
]],
uniformInt = {
tex0 = 0,
tex1 = 1,
},
})
if (maskApplyShader == nil) then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "Blurry Halo Selections: mask application shader error: "..gl.GetShaderLog())
widgetHandler:RemoveWidget()
return false
end
screenXloc = gl.GetUniformLocation(featherShader_h, 'screenX')
screenYloc = gl.GetUniformLocation(featherShader_v, 'screenY')
thkXloc = gl.GetUniformLocation(featherShader_h, 'thickness')
thkYloc = gl.GetUniformLocation(featherShader_v, 'thickness')
invRXloc = gl.GetUniformLocation(blurShader_h, 'inverseRX')
invRYloc = gl.GetUniformLocation(blurShader_v, 'inverseRY')
radiusXloc = gl.GetUniformLocation(blurShader_h, 'fragKernelRadius')
radiusYloc = gl.GetUniformLocation(blurShader_v, 'fragKernelRadius')
haloColorloc = gl.GetUniformLocation(maskGenShader, 'color')
ShowSelectionSquares(false)
end
function widget:ViewResize()
vsx, vsy = gl.GetViewSizes()
ivsx = 1/vsx
ivsy = 1/vsy
fbo.color0 = nil
gl.DeleteTextureFBO(blurtex1 or "")
gl.DeleteTextureFBO(blurtex2 or "")
gl.DeleteTextureFBO(masktex or "")
blurtex1 = gl.CreateTexture(vsx,vsy, {
border = false,
min_filter = GL.LINEAR,
mag_filter = GL.LINEAR,
wrap_s = GL.CLAMP,
wrap_t = GL.CLAMP,
fbo = true,
})
blurtex2 = gl.CreateTexture(vsx,vsy, {
border = false,
min_filter = GL.LINEAR,
mag_filter = GL.LINEAR,
wrap_s = GL.CLAMP,
wrap_t = GL.CLAMP,
fbo = true,
})
masktex = gl.CreateTexture(vsx, vsy, {
border = false,
min_filter = GL.LINEAR,
mag_filter = GL.LINEAR,
wrap_s = GL.CLAMP,
wrap_t = GL.CLAMP,
fbo = true,
})
if not blurtex1 or not blurtex2 or not masktex then
Spring.Echo("Blurry Halo Selections: Failed to create offscreen textures!")
widgetHandler:RemoveWidget()
return
end
fbo.color0 = blurtex1
fbo.color1 = masktex
fbo.drawbuffers = {GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT}
end
function widget:Shutdown()
if (gl.DeleteTextureFBO) then
gl.DeleteTextureFBO(blurtex1 or "")
gl.DeleteTextureFBO(blurtex2 or "")
gl.DeleteTextureFBO(masktex or "")
end
if (gl.DeleteFBO) then
gl.DeleteFBO(fbo)
end
if (gl.DeleteShader) then
gl.DeleteShader(maskGenShader or 0)
gl.DeleteShader(featherShader_h or 0)
gl.DeleteShader(featherShader_v or 0)
gl.DeleteShader(blurShader_h or 0)
gl.DeleteShader(blurShader_v or 0)
gl.DeleteShader(maskApplyShader or 0)
end
ShowSelectionSquares(true)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
Mutos/StarsOfCall-NAEV | dat/ai/_commons/_baseCommonTasks/_land.lua | 1 | 1829 | -- =======================================================================================
--
-- TASK and SUBTASKs to handle landing.
--
-- =======================================================================================
-- =======================================================================================
--
-- Attempts to land on a random planet.
--
-- =======================================================================================
--
-- TASK
function land ()
local scriptName = "_land.lua"
-- Only want to land once, prevents guys from never leaving.
if mem.landed then
ai.poptask()
return
end
-- Set target if necessary
local target = ai.target()
if target ~= nil then
mem.land = target
end
-- Make sure mem.land is valid target
if mem.land == nil then
mem.land = ai.landplanet()
end
ai.pushsubtask( "__landgo" )
end
-- SUBTASK : approach the target planet on landing attempt.
function __landgo ()
local scriptName = "_land.lua"
local target = mem.land
local dir = ai.face( target )
local dist = ai.dist( target )
local bdist = ai.minbrakedist()
-- Need to get closer
if dir < 10 and dist > bdist then
ai.accel()
-- Need to start braking
elseif dist < bdist then
ai.pushsubtask( "__landstop" )
end
end
-- SUBTASK : stop a pilot on landing attempt.
function __landstop ()
local scriptName = "_land.lua"
ai.brake()
if ai.isstopped() then
ai.stop() -- Will stop the pilot if below err vel
if not ai.land() then
ai.popsubtask()
else
ai.poptask() -- Done, pop task
end
end
end
-- SUBTASK : try to land asap.
function __land ()
local scriptName = "_land.lua"
land()
end
--
-- =======================================================================================
| gpl-3.0 |
Sasu98/Nerd-Gaming-Public | resources/NGVIP/vip_s.lua | 2 | 4607 | print_ = print
print = outputChatBox
exports.scoreboard:scoreboardAddColumn ( "VIP", root, 50, "VIP", 10 )
for i, v in pairs ( getElementsByType ( "player" ) ) do
if ( not getElementData ( v, "VIP" ) ) then
setElementData ( v, "VIP", "None" )
end
end
addEventHandler ( "onPlayerJoin", root, function ( )
setElementData ( source, "VIP", "None" )
end )
-- VIP Chat --
addCommandHandler ( "vipchat", function ( p, cmd, ... )
if ( not isPlayerVIP ( p ) ) then
return exports.NGMessages:sendClientMessage ( "This command is for VIP users only", p, 255, 0, 0 )
end
if ( isPlayerMuted ( p ) ) then
return exports.NGMessages:sendClientMessage ( "This command is disabled when you're muted", p, 255, 255, 0 )
end
if ( not getElementData ( p, "userSettings" )['usersetting_display_vipchat'] ) then
return exports.NGMessages:sendClientMessage ( "Please enable VIP chat in your phone settings to use this command.", 0, 255, 255 )
end
local msg = table.concat ( { ... }, " " )
if ( msg:gsub ( " ", "" ) == "" ) then
return exports.NGMessages:sendClientMessage ( "Syntax: /"..tostring(cmd).." [message]", p, 255, 255, 0 )
end
local tags = "(VIP)"..tostring(exports.NGChat:getPlayerTags ( p ))
local msg = tags..getPlayerName ( p )..": #ffffff"..msg
for i,v in pairs ( getElementsByType ( 'player' ) ) do
if ( ( isPlayerVIP ( v ) or exports.NGAdministration:isPlayerStaff ( p ) ) and getElementData ( v, "userSettings" )['usersetting_display_vipchat'] ) then
outputChatBox ( msg, v, 200, 200, 0, true )
end
end
end )
function checkPlayerVipTime ( p )
local vip = getElementData ( p, "VIP" )
if ( vip == "None" ) then return end
local expDate = getElementData ( p, "NGVIP.expDate" ) or "0000-00-00" -- Format: YYYY-MM-DD
if ( isDatePassed ( expDate ) ) then
setElementData ( p, "VIP", "None" )
setElementData ( p, "NGVIP.expDate", "0000-00-00" )
exports.NGMessages:sendClientMessage ( "Your VIP time has been expired.", p, 255, 0, 0 )
end
end
function checkAllPlayerVIP ( )
for i, v in pairs ( getElementsByType ( "player" ) ) do
checkPlayerVipTime ( v )
end
end
function isPlayerVIP ( p )
checkPlayerVipTime ( p )
return tostring ( getElementData ( p, "VIP" ) ):lower ( ) ~= "none"
end
function getVipLevelFromName ( l )
local levels = { ['none'] = 0, ['bronze'] = 1, ['silver'] = 2, ['gold'] = 3, ['diamond'] = 4 }
return levels[l:lower()] or 0;
end
------------------------------------------
-- Give VIP players free cash --
------------------------------------------
local payments = { [1] = 500, [2] = 700, [3] = 1000, [4] = 1500 }
VipPayoutTimer = setTimer ( function ( )
exports.NGLogs:outputServerLog ( "Sending out VIP cash...." )
print_ ( "Sending out VIP cash...." )
outputDebugString ( "Sending VIP cash" )
for i, v in ipairs ( getElementsByType ( "player" ) ) do
if ( isPlayerVIP ( v ) ) then
local l = getVipLevelFromName ( getElementData ( v, "VIP" ) )
local money = payments [ l ]
givePlayerMoney ( v, money )
exports.NGMessages:sendClientMessage ( "Here is a free $"..money.." for being a VIP player!", v, 0, 255, 0 )
end
end
end, (60*60)*1000, 0 )
function getVipPayoutTimerDetails ( )
return getTimerDetails ( VipPayoutTimer )
end
function isDatePassed ( date )
-- date format: YYYY-MM-DD
local this = { }
local time = getRealTime ( );
this.year = time.year + 1900
this.month = time.month + 1
this.day = time.monthday
local old = { }
local data = split ( date, "-" )
old.year = data[1];
old.month = data[2];
old.day = data[3];
for i, v in pairs ( this ) do
this [ i ] = tonumber ( v )
end for i, v in pairs ( old ) do
old [ i ] = tonumber ( v )
end
if ( this.year > old.year ) then
return true
elseif ( this.year == old.year and this.month > old.month ) then
return true
elseif ( this.year == old.year and this.month == old.month and this.day > old.day ) then
return true
end
return false
end
addEventHandler( "onResourceStart", resourceRoot, function ( )
checkAllPlayerVIP ( )
setTimer ( checkAllPlayerVIP, 120000, 0 )
end )
--[[
Bronze:
- Laser
- Able to warp vehicle to you
- Additional 6 vehicles in spawners
- $500/hour
- 5% less jail time
Silver:
- Laser
- Able to warp your vehicle to you
- Additional 6 vehicles in spawners
- $700/hour
- 15% less jail time
Gold:
- Laser
- Able to warp your vehicle to you
- Additional 6 vehicles in spawner
- $1000/hour
- %25 less jail time
Diamond:
- Laser
- Able to warp your vehicle to you
- Additional 6 vehicles in spawners
- $1500/hour
- Half jail time
]]
| mit |
delram/yago | plugins/boobs.lua | 731 | 1601 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. 🔞",
"!butts: Get a butts NSFW image. 🔞"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
| gpl-2.0 |
mamaddeveloper/DeveloperMMD_bot | plugins/boobs.lua | 731 | 1601 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. 🔞",
"!butts: Get a butts NSFW image. 🔞"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
| gpl-2.0 |
ggcrunchy/Old-Love2D-Demo | Scripts/Utility/NumericOps.lua | 1 | 5074 | -- See TacoShell Copyright Notice in main folder of distribution
-- Standard library imports --
local max = math.max
local min = math.min
-- Cached routines --
local BoxesIntersect_
local SortPairs_
local SwapIf_
-- Export numericops namespace.
module "numericops"
--- Status.
-- @param x1 Box #1 x-coordinate.
-- @param y1 Box #1 y-coordinate.
-- @param w1 Box #1 width.
-- @param h1 Box #1 height.
-- @param x2 Box #2 x-coordinate.
-- @param y2 Box #2 y-coordinate.
-- @param w2 Box #2 width.
-- @param h2 Box #2 height.
-- @return If true, the boxes intersect.
function BoxesIntersect (x1, y1, w1, h1, x2, y2, w2, h2)
return not (x1 > x2 + w2 or x2 > x1 + w1 or y1 > y2 + h2 or y2 > y1 + h1)
end
-- Status.
-- @param bx Contained box x-coordinate.
-- @param by Contained box y-coordinate.
-- @param bw Contained box width.
-- @param bh Contained box height.
-- @param x Containing box x-coordinate.
-- @param y Containing box y-coordinate.
-- @param w Containing box width.
-- @param h Containing box height.
-- @return If true, the first box is contained by the second.
function BoxInBox (bx, by, bw, bh, x, y, w, h)
return not (bx < x or bx + bw > x + w or by < y or by + bh > y + h)
end
--- Variant of <b>BoxesIntersect</b> with intersection information.
-- @param x1 Box #1 x-coordinate.
-- @param y1 Box #1 y-coordinate.
-- @param w1 Box #1 width.
-- @param h1 Box #1 height.
-- @param x2 Box #2 x-coordinate.
-- @param y2 Box #2 y-coordinate.
-- @param w2 Box #2 width.
-- @param h2 Box #2 height.
-- @return If true, boxes intersect.
-- @return If the boxes intersect, the intersection x, y, w, h.
-- @see BoxesIntersect
function BoxIntersection (x1, y1, w1, h1, x2, y2, w2, h2)
if not BoxesIntersect_(x1, y1, w1, h1, x2, y2, w2, h2) then
return false
end
local sx, sy = max(x1, x2), max(y1, y2)
return true, sx, sy, min(x1 + w1, x2 + w2) - sx, min(y1 + h1, y2 + h2) - sy
end
--- Clamps a number between two bounds.<br><br>
-- The bounds are swapped if out of order.
-- @param number Number to clamp.
-- @param minb Minimum bound.
-- @param maxb Maximum bound.
-- @return Clamped number.
function ClampIn (number, minb, maxb)
minb, maxb = SwapIf_(minb > maxb, minb, maxb)
return min(max(number, minb), maxb)
end
--- Status.
-- @param px Point x-coordinate.
-- @param py Point y-coordinate.
-- @param x Box x-coordinate.
-- @param y Box y-coordinate.
-- @param w Box width.
-- @param h Box height.
-- @return If true, the point is contained by the box.
function PointInBox (px, py, x, y, w, h)
return px >= x and px < x + w and py >= y and py < y + h
end
-- start: Starting index of range
-- count: Count of items in range
-- size: Length of overlapping range
-- Returns: Overlap amount between [start, start + count) and [1, size]
------------------------------------------------------------------------
function RangeOverlap (start, count, size)
if start > size then
return 0
elseif start + count <= size + 1 then
return count
end
return size - start + 1
end
-- Converts coordinate pairs into a rectangle
-- x1, y1: First pair of coordinates
-- x2, y2: Second pair of coordinates
-- Returns: Rectangle coordinates and dimensions
-------------------------------------------------
function Rect (x1, y1, x2, y2)
x1, y1, x2, y2 = SortPairs_(x1, y1, x2, y2)
return x1, y1, x2 - x1, y2 - y1
end
-- index: Index to rotate
-- size: Array size
-- to_left: If true, rotate left
-- Returns: Rotated array index
--------------------------------
function RotateIndex (index, size, to_left)
if to_left then
return index > 1 and index - 1 or size
else
return index < size and index + 1 or 1
end
end
-- x1, y1: First pair of coordinates
-- x2, y2: Second pair of coordinates
-- Returns: The sorted coordinate pairs
----------------------------------------
function SortPairs (x1, y1, x2, y2)
x1, x2 = SwapIf_(x1 > x2, x1, x2)
y1, y2 = SwapIf_(y1 > y2, y1, y2)
return x1, y1, x2, y2
end
-- swap: If true, do a swap
-- a, b: Values to swap
-- Returns: Ordered (possibly swapped) pair
--------------------------------------------
function SwapIf (swap, a, b)
if swap then
return b, a
end
return a, b
end
-- x: Distance along the trapezoid (aligned to the x-axis)
-- grow_until: Distance at which flat part begins
-- flat_until: Distance at which flat part ends
-- drop_until: Distance at which x-axis is met again
-- Returns: Height at x, in [0, 1], if within the range
-----------------------------------------------------------
function Trapezoid (x, grow_until, flat_until, drop_until)
if x < 0 or x > drop_until then
return
elseif x <= grow_until then
return x / grow_until
elseif x <= flat_until then
return 1
else
return 1 - (x - flat_until) / (drop_until - flat_until)
end
end
--- Exclusive-ors two conditions
-- @param b1 Condition #1.
-- @param b2 Condition #2.
-- @return If true, one (and only one) of the conditions is true.
function XOR (b1, b2)
return not not ((b1 or b2) and not (b1 and b2))
end
-- Cache some routines.
BoxesIntersect_ = BoxesIntersect
SortPairs_ = SortPairs
SwapIf_ = SwapIf | mit |
Ractis/HookAndSlice | scripts/vscripts/DotaHS_AI_Follower_Kotl.lua | 1 | 8592 |
require( "DotaHS_AI_FollowerBase" )
--
-- TODO:
--
--------------------------------------------------------------------------------
-- AI / Kotl
--------------------------------------------------------------------------------
if AI_Kotl == nil then
AI_BehaviorTreeBuilder_Kotl = class({}, nil, AI_BehaviorTreeBuilder)
AI_Kotl = class({}, nil, AI_FollowerBase)
AI_Kotl.btreeBuilderClass = AI_BehaviorTreeBuilder_Kotl
-- Hero specific properties
AI_Kotl.unitClassname = "npc_dota_hero_keeper_of_the_light"
AI_Kotl.unitShortname = "Kotl"
AI_Kotl.vAbilityNameList = {
"keeper_of_the_light_illuminate", -- 1
"keeper_of_the_light_mana_leak", -- 2
"keeper_of_the_light_chakra_magic", -- 3
"keeper_of_the_light_recall",
"keeper_of_the_light_blinding_light",
"keeper_of_the_light_spirit_form", -- 6
"keeper_of_the_light_illuminate_end",
"keeper_of_the_light_spirit_form_illuminate",
"keeper_of_the_light_spirit_form_illuminate_end",
"attribute_bonus", -- 10
}
AI_Kotl.vAbilityUpgradeSequence = {
1, 3, 1, 3, 1,
6, 1, 3, 3, 2,
6, 2, 2, 2, 10,
6, 10, 10, 10, 10,
10, 10, 10, 10, 10,
}
AI_Kotl.vItemPropertyRating = {
damage = 2,
str = 1,
agi = 1,
int = 5,
as = 3,
armor = 3,
mr = 3,
hp = 3,
mana = 4,
hpreg = 3,
manareg = 3,
ms = 2,
}
end
--------------------------------------------------------------------------------
function AI_Kotl:constructor( unit )
AI_FollowerBase.constructor( self, unit )
-- Abilities
self.ABILITY_illuminate = self.vAbilities["keeper_of_the_light_illuminate"]
self.ABILITY_spirit_form_illuminate = self.vAbilities["keeper_of_the_light_spirit_form_illuminate"]
self.ABILITY_chakra_magic = self.vAbilities["keeper_of_the_light_chakra_magic"]
self.ABILITY_blinding_light = self.vAbilities["keeper_of_the_light_blinding_light"]
self.ABILITY_spirit_form = self.vAbilities["keeper_of_the_light_spirit_form"]
end
--------------------------------------------------------------------------------
function AI_Kotl:IsSpiritForm()
return self.entity:HasModifier( "modifier_keeper_of_the_light_spirit_form" )
end
--------------------------------------------------------------------------------
function AI_Kotl:GetActiveIlluminateAbility()
if self:IsSpiritForm() then
return self.ABILITY_spirit_form_illuminate
else
return self.ABILITY_illuminate
end
end
--------------------------------------------------------------------------------
-- CONDITIONS
--------------------------------------------------------------------------------
function AI_Kotl:COND_ReadyForIlluminate()
if not self:GetActiveIlluminateAbility():IsFullyCastable() then
return false
end
-- Good direction found?
local range = 1000 -- 1550
local radius = 250 -- 350
local enemies = self:FindEnemiesInRange( range )
if #enemies == 0 then
return false
end
local dir, score = DotaHS_FindGoodDirection( self.entity:GetAbsOrigin(), range, radius, enemies )
if not dir then
return false
end
if score < 2.25 then
return false
end
self.targetIlluminate = self.entity:GetAbsOrigin() + dir * ( range / 2 )
self.targetIlluminate = self:RandomPositionInRange( self.targetIlluminate, 75 )
return true
end
--------------------------------------------------------------------------------
function AI_Kotl:COND_ReadyForChakraMagic()
if not self.ABILITY_chakra_magic:IsFullyCastable() then
return false
end
local range = self.ABILITY_chakra_magic:GetCastRange()
local allies = self:FriendlyHeroesInRange( range )
local lowestManaPercent = 100
local lowestManaAlly = nil
for _,v in ipairs(allies) do
if v:entindex() ~= self.entity:entindex() then
-- Other hero
if v:IsAlive() then
local manaPercent = v:GetManaPercent()
if manaPercent < lowestManaPercent then
lowestManaPercent = manaPercent
lowestManaAlly = v
end
end
end
end
if lowestManaPercent > self.entity:GetManaPercent() * 0.75 then
lowestManaAlly = self.entity -- Cast to myself
end
if lowestManaAlly:GetManaPercent() > 90 then
return false
end
self.targetChakraMagic = lowestManaAlly
return true
end
--------------------------------------------------------------------------------
function AI_Kotl:COND_ReadyForBlindingLight()
if not self.ABILITY_blinding_light:IsFullyCastable() then
return false
end
if not self:IsSpiritForm() then
-- Can't cast this ability as normal form
return false
end
-- Find good position
local radius = DotaHS_GetAbilitySpecialValue( self.ABILITY_blinding_light, "radius" )
radius = radius * 0.75
local enemies = self:FindEnemiesInRange( 1000 )
local center, N = DotaHS_FindGoodCirclePosition( radius, enemies, self )
if not center then
return false
end
local minimumEnemies = 6
if N < minimumEnemies then
return false
end
self.targetBlindingLight = self:RandomPositionInRange( center, 75 )
return true
end
--------------------------------------------------------------------------------
function AI_Kotl:COND_ReadyForSpiritForm()
if not self.ABILITY_spirit_form:IsFullyCastable() then
return false
end
if self:IsSpiritForm() then
return false
end
return true
end
--------------------------------------------------------------------------------
-- ACTIONS
--------------------------------------------------------------------------------
function AI_Kotl:ACT_CastIlluminate()
local ability = self:GetActiveIlluminateAbility()
local s = self:GetCastingAbilityState( ability, function ()
self:CreateOrder( DOTA_UNIT_ORDER_CAST_POSITION, nil, ability, self.targetIlluminate )
end )
if self:IsSpiritForm() then
return BH_SUCCESS
else
return s
end
end
--------------------------------------------------------------------------------
function AI_Kotl:ACT_CastChakraMagic()
if not self.targetChakraMagic:IsAlive() then
return BH_FAILURE
end
return self:GetCastingAbilityState( self.ABILITY_chakra_magic, function ()
self:CreateOrder( DOTA_UNIT_ORDER_CAST_TARGET, self.targetChakraMagic, self.ABILITY_chakra_magic )
end )
end
--------------------------------------------------------------------------------
function AI_Kotl:ACT_CastBlindingLight()
return self:GetCastingAbilityState( self.ABILITY_blinding_light, function ()
self:CreateOrder( DOTA_UNIT_ORDER_CAST_POSITION, nil, self.ABILITY_blinding_light, self.targetBlindingLight )
end )
end
--------------------------------------------------------------------------------
function AI_Kotl:ACT_CastSpiritForm()
return self:GetCastingAbilityState( self.ABILITY_spirit_form, function ()
self:CreateOrder( DOTA_UNIT_ORDER_CAST_NO_TARGET, nil, self.ABILITY_spirit_form )
end )
end
--------------------------------------------------------------------------------
-- Behavior Tree Builder
--------------------------------------------------------------------------------
function AI_BehaviorTreeBuilder_Kotl:ARRAY_DecisionMakingChildren()
local array = AI_BehaviorTreeBuilder.ARRAY_DecisionMakingChildren( self )
-- Modify
self:InsertBefore( array, "Flee", self:NODE_SpiritForm() )
self:InsertBefore( array, "Flee", self.NODE_Illuminate() )
self:InsertBefore( array, "Flee", self.NODE_BlindingLight() )
self:InsertBefore( array, "Flee", self.NODE_ChakraMagic() )
return array
end
--------------------------------------------------------------------------------
function AI_BehaviorTreeBuilder_Kotl:NODE_SpiritForm()
return SequenceNode( "Spirit Form", {
ConditionNode( "Ready?", "COND_ReadyForSpiritForm" ),
ActionNode( "Cast Spirit Form", "ACT_CastSpiritForm" ),
} )
end
--------------------------------------------------------------------------------
function AI_BehaviorTreeBuilder_Kotl:NODE_Illuminate()
return Decorator_CooldownRandomAlsoFailure( 0.3, 0.6,
SequenceNode( "Illuminate", {
ConditionNode( "Ready?", "COND_ReadyForIlluminate" ),
ActionNode( "Cast Illuminate", "ACT_CastIlluminate" ),
} )
)
end
--------------------------------------------------------------------------------
function AI_BehaviorTreeBuilder_Kotl:NODE_BlindingLight()
return Decorator_CooldownRandomAlsoFailure( 1, 1.5,
SequenceNode( "Blinding Light", {
ConditionNode( "Ready?", "COND_ReadyForBlindingLight" ),
ActionNode( "Cast Blinding Light", "ACT_CastBlindingLight" ),
} )
)
end
--------------------------------------------------------------------------------
function AI_BehaviorTreeBuilder_Kotl:NODE_ChakraMagic()
return SequenceNode( "Chakra Magic", {
ConditionNode( "Ready?", "COND_ReadyForChakraMagic" ),
ActionNode( "Cast Chakra Magic", "ACT_CastChakraMagic" ),
} )
end
| mit |
LanceJenkinZA/prosody-modules | mod_auth_sql/mod_auth_sql.lua | 32 | 3498 | -- Simple SQL Authentication module for Prosody IM
-- Copyright (C) 2011 Tomasz Sterna <tomek@xiaoka.com>
-- Copyright (C) 2011 Waqas Hussain <waqas20@gmail.com>
--
local log = require "util.logger".init("auth_sql");
local new_sasl = require "util.sasl".new;
local DBI = require "DBI"
local connection;
local params = module:get_option("auth_sql", module:get_option("sql"));
local resolve_relative_path = require "core.configmanager".resolve_relative_path;
local function test_connection()
if not connection then return nil; end
if connection:ping() then
return true;
else
module:log("debug", "Database connection closed");
connection = nil;
end
end
local function connect()
if not test_connection() then
prosody.unlock_globals();
local dbh, err = DBI.Connect(
params.driver, params.database,
params.username, params.password,
params.host, params.port
);
prosody.lock_globals();
if not dbh then
module:log("debug", "Database connection failed: %s", tostring(err));
return nil, err;
end
module:log("debug", "Successfully connected to database");
dbh:autocommit(true); -- don't run in transaction
connection = dbh;
return connection;
end
end
do -- process options to get a db connection
params = params or { driver = "SQLite3" };
if params.driver == "SQLite3" then
params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite");
end
assert(params.driver and params.database, "Both the SQL driver and the database need to be specified");
assert(connect());
end
local function getsql(sql, ...)
if params.driver == "PostgreSQL" then
sql = sql:gsub("`", "\"");
end
if not test_connection() then connect(); end
-- do prepared statement stuff
local stmt, err = connection:prepare(sql);
if not stmt and not test_connection() then error("connection failed"); end
if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end
-- run query
local ok, err = stmt:execute(...);
if not ok and not test_connection() then error("connection failed"); end
if not ok then return nil, err; end
return stmt;
end
local function get_password(username)
local stmt, err = getsql("SELECT `password` FROM `authreg` WHERE `username`=? AND `realm`=?", username, module.host);
if stmt then
for row in stmt:rows(true) do
return row.password;
end
end
end
provider = {};
function provider.test_password(username, password)
return password and get_password(username) == password;
end
function provider.get_password(username)
return get_password(username);
end
function provider.set_password(username, password)
return nil, "Setting password is not supported.";
end
function provider.user_exists(username)
return get_password(username) and true;
end
function provider.create_user(username, password)
return nil, "Account creation/modification not supported.";
end
function provider.get_sasl_handler()
local profile = {
plain = function(sasl, username, realm)
local password = get_password(username);
if not password then return "", nil; end
return password, true;
end
};
return new_sasl(module.host, profile);
end
function provider.users()
local stmt, err = getsql("SELECT `username` FROM `authreg` WHERE `realm`=?", module.host);
if stmt then
local next, state = stmt:rows(true)
return function()
for row in next, state do
return row.username;
end
end
end
return stmt, err;
end
module:provides("auth", provider);
| mit |
Anarchid/Zero-K | LuaUI/Widgets/unit_building_starter.lua | 7 | 3993 | -- $Id$
function widget:GetInfo()
return {
name = "Building Starter",
desc = "v2 Hold Q to queue a building to be started and not continued.",
author = "Google Frog",
date = "Dec 13, 2008",
license = "GNU GPL, v2 or later",
layer = 5,
enabled = true -- loaded by default?
}
end
local buildings = {} -- {[1] = {x = posX, z = posZ, ud = unitID}} -- unitID is only set when building is created
local toClear = {} -- {[1] = {x = posX, z = posZ, unitID = unitID}} -- entries created in UnitCreated, iterated in GameFrame
local numBuildings = 0
local team = Spring.GetMyTeamID()
include("keysym.lua")
local _, ToKeysyms = include("Configs/integral_menu_special_keys.lua")
local CMD_REMOVE = CMD.REMOVE
local buildingStartKey = KEYSYMS.Q
local function HotkeyChangeNotification()
local key = WG.crude.GetHotkeyRaw("epic_building_starter_hotkey")
buildingStartKey = ToKeysyms(key and key[1])
end
options_order = {'hotkey'}
options_path = 'Hotkeys/Construction'
options = {
hotkey = {
name = 'Place Nanoframes',
desc = 'Hold this key during structure placement to queue structures which are to placed but not constructed.',
type = 'button',
hotkey = "Q",
bindWithAny = true,
dontRegisterAction = true,
OnHotkeyChange = HotkeyChangeNotification,
path = hotkeyPath,
},
}
-- Speedups
local spGiveOrderToUnit = Spring.GiveOrderToUnit
local spGetTeamUnits = Spring.GetTeamUnits
local spGetUnitCurrentCommand = Spring.GetUnitCurrentCommand
local spGetUnitPosition = Spring.GetUnitPosition
local spGetKeyState = Spring.GetKeyState
local spGetSelectedUnits = Spring.GetSelectedUnits
local abs = math.abs
function widget:Initialize()
if (Spring.GetSpectatingState() or Spring.IsReplay()) and (not Spring.IsCheatingEnabled()) then
Spring.Echo("<Building Starter>: disabled for spectators")
widgetHandler:RemoveWidget()
end
HotkeyChangeNotification()
end
function widget:CommandNotify(id, params, options)
if (id < 0) then
local ux = params[1]
local uz = params[3]
if buildingStartKey and spGetKeyState(buildingStartKey) then
buildings[numBuildings] = { x = ux, z = uz}
numBuildings = numBuildings+1
else
for j, i in pairs(buildings) do
if (i.x) then
if (i.x == ux) and (i.z == uz) then
buildings[j] = nil
end
end
end
end
end
end
function CheckBuilding(ux,uz,ud)
for index, i in pairs(buildings) do
if (i.x) then
if (abs(i.x - ux) < 16) and (abs(i.z - uz) < 16) then
i.ud = ud
return true
end
end
end
return false
end
function widget:GameFrame(f)
if f % 2 ~= 1 then
return
end
local newClear = {}
for i=1,#toClear do
local entry = toClear[i]
-- minimum progress requirement is there because otherwise a con can start multiple nanoframes in one gameframe
-- (probably as many as it can reach, in fact)
local health, _, _, _, buildProgress = Spring.GetUnitHealth(entry.unitID)
if health and health > 3 then
--if buildProgress > 0.01 then
local ux, uz = entry.x, entry.z
local units = spGetTeamUnits(team)
for _, unit_id in ipairs(units) do
local cmdID, cmdOpt, cmdTag, cx, cy, cz = spGetUnitCurrentCommand(unit_id)
if cmdID and cmdID < 0 then
if (abs(cx-ux) < 16) and (abs(cz-uz) < 16) then
spGiveOrderToUnit(unit_id, CMD_REMOVE, {cmdTag}, 0 )
end
end
end
else
newClear[#newClear + 1] = entry
end
end
toClear = newClear
end
function widget:UnitCreated(unitID, unitDefID, unitTeam)
if (unitTeam ~= team) then
return
end
local ux, uy, uz = spGetUnitPosition(unitID)
local check = CheckBuilding(ux,uz,unitID)
if check then
toClear[#toClear + 1] = {unitID = unitID, x = ux, z = uz}
end
end
function widget:UnitFinished(unitID, unitDefID, unitTeam)
for j, i in pairs(buildings) do
if (i.ud) then
buildings[j] = nil
end
end
end
function widget:UnitDestroyed(unitID, unitDefID, unitTeam)
for j, i in pairs(buildings) do
if (i.ud) then
buildings[j] = nil
end
end
end
| gpl-2.0 |
hinrik/layla | lib/layla/model.lua | 1 | 14859 | local M = {
db_file = "layla.sqlite",
caching = true,
new_db = true,
_order = 2,
_token_cache = {},
_expr_cache = {},
_link_cache = {},
_sth = {},
}
local M_mt = { __index = M }
local sqlite3 = require "lsqlite3"
local D = require "serpent".block
math.randomseed(os.time())
M._schema = [[
CREATE TABLE info (
attribute TEXT NOT NULL PRIMARY KEY,
text NOT NULL
);
CREATE TABLE tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
spacing INTEGER NOT NULL,
text TEXT NOT NULL
);
CREATE TABLE exprs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token1_id INTEGER NOT NULL REFERENCES tokens(id),
token2_id INTEGER NOT NULL REFERENCES tokens(id)
);
CREATE TABLE links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
prev_expr_id INTEGER NOT NULL REFERENCES exprs(id),
next_expr_id INTEGER NOT NULL REFERENCES exprs(id),
count INTEGER NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS get_token_id on tokens (text, spacing);
CREATE UNIQUE INDEX IF NOT EXISTS get_expr on exprs (token1_id, token2_id);
CREATE UNIQUE INDEX IF NOT EXISTS get_link ON links (prev_expr_id, next_expr_id);
CREATE INDEX IF NOT EXISTS get_link_by_next ON links (next_expr_id);
CREATE INDEX IF NOT EXISTS get_expr_by_token2 on exprs (token2_id);
]]
--[=[
-- speeds up learning (with a non-empty DB) and replying
M.create_learn_idx = [[
CREATE UNIQUE INDEX IF NOT EXISTS get_token_id on tokens (text, spacing);
CREATE UNIQUE INDEX IF NOT EXISTS get_expr on exprs (token1_id, token2_id);
]]
M.drop_learn_idx = [[
DROP INDEX get_token_id;
DROP INDEX get_expr;
]]
-- speeds up replying
M.create_reply_idx = [[
CREATE UNIQUE INDEX IF NOT EXISTS get_link ON links (prev_expr_id, next_expr_id);
CREATE INDEX IF NOT EXISTS get_link_by_next ON links (next_expr_id);
CREATE INDEX IF NOT EXISTS get_expr_by_token2 on exprs (token2_id);
]]
M.drop_reply_idx = [[
DROP INDEX get_link;
DROP INDEX get_link_by_next;
DROP INDEX get_expr_by_token2;
]]
--]=]
M._statements = {
add_token = "INSERT INTO tokens (spacing, text) VALUES (?, ?)",
token_spec = "SELECT spacing, text FROM tokens WHERE id = ?;",
token_id = "SELECT id FROM tokens WHERE spacing = ? AND text = ?;",
add_expr = "INSERT INTO exprs (token1_id, token2_id) VALUES (?, ?)",
get_expr = "SELECT id FROM exprs WHERE token1_id = ? AND token2_id = ?;",
add_link = [[INSERT INTO links (prev_expr_id, next_expr_id, count)
VALUES (?, ?, ?);]],
inc_link = [[UPDATE links SET count = count + ?
WHERE prev_expr_id = ? AND next_expr_id = ?]],
similar_token = [[SELECT id, spacing FROM tokens
WHERE text = ?
ORDER BY random()
LIMIT 1;]],
random_token = [[SELECT id, spacing, text FROM tokens
WHERE rowid = (abs(random()) % (
SELECT seq+1 FROM sqlite_sequence
WHERE name = 'tokens'));]],
random_expr = [[SELECT * FROM exprs
WHERE token1_id = :id OR token2_id = :id
ORDER BY random()
LIMIT 1;]],
prev_expr = [[SELECT id, token1_id, token2_id FROM exprs
WHERE exprs.id = (
SELECT prev_expr_id FROM links
WHERE next_expr_id = :last_expr_id
LIMIT 1
OFFSET abs(random()) % (
SELECT count(*) FROM links
WHERE next_expr_id = :last_expr_id))]],
next_expr = [[SELECT id, token1_id, token2_id FROM exprs
WHERE exprs.id = (
SELECT next_expr_id FROM links
WHERE prev_expr_id = :last_expr_id
LIMIT 1
OFFSET abs(random()) % (
SELECT count(*) FROM links
WHERE prev_expr_id = :last_expr_id))]],
}
function M:new(args)
args = args or {}
return setmetatable(args, M_mt)
end
function M:init()
local db = sqlite3.open(self.db_file)
self._db = db
db:execute("PRAGMA synchronous=OFF;")
db:execute("PRAGMA journal_mode=OFF;")
local result = {}
for a in db:rows("SELECT name FROM sqlite_master WHERE type ='table' AND name='tokens'") do
table.insert(result, a)
end
if #result == 0 then
db:execute(self._schema)
if db:error_code() ~= sqlite3.OK then
print("bar: "..db:error_message())
end
end
for name, statement in pairs(self._statements) do
self._sth[name] = self._db:prepare(statement)
if self._db:error_code() ~= sqlite3.OK then
print("baz: "..self._db:errmsg())
break
end
end
self._end_token_id = self:_get_or_add_token(0, '')
--print("id: "..boundary_token_id)
self._end_expr_id = self:_get_or_add_expr({self._end_token_id, self._end_token_id})
--print("hlagh: "..db:errmsg())
--if self.caching and self.new_db then
-- db:execute(self:_create_)
--end
end
function M:begin_transaction()
self._db:execute("BEGIN TRANSACTION;")
end
function M:end_transaction()
if self.caching then
self:_flush_cache()
end
self._db:execute("END TRANSACTION;")
end
function M:_flush_cache()
for link_key, count in pairs(self._link_cache) do
local prev_expr = string.match(link_key, '^%d*')
local next_expr = string.match(link_key, '%d*$')
--print(prev_expr.." and "..next_expr.." with "..count)
if self.new_db then
self:_add_link(prev_expr, next_expr, count)
else
self:_inc_or_add_link(prev_expr, next_expr, count)
end
end
self._link_cache = {}
self._token_cache = {}
self._expr_cache = {}
end
function M:learn(tokens)
if #tokens < self._order then
return
end
local token_cache = {}
if self.caching then
token_cache = self._token_cache
end
local expr_cache = {}
if self.caching then
expr_cache = self._expr_cache
end
local token_ids = {}
local expr_ids = {}
local db_ops = 0
-- resolve token ids
for _, token_spec in pairs(tokens) do
--print("token: "..token_spec[2])
local key = table.concat(token_spec)
local cached_id = token_cache[key]
if cached_id then
--print("got cached token "..cached_id)
table.insert(token_ids, cached_id)
else
db_ops = db_ops + 1
local new_id
if self.caching and self.new_db then
new_id = self:_add_token(unpack(token_spec))
else
new_id = self:_get_or_add_token(unpack(token_spec))
end
--print("new token id: "..new_id)
token_cache[key] = new_id
table.insert(token_ids, new_id)
end
end
--print(D(token_cache))
table.insert(token_ids, 1, self._end_token_id)
table.insert(token_ids, self._end_token_id)
--print(D(token_ids))
-- resolve expr ids
for i = 1, #token_ids - self._order+1 do
--print("foo: "..i)
local ids = {}
for j = i, i + self._order-1 do
table.insert(ids, token_ids[j])
end
--print("token_ids: "..D(ids))
local key = table.concat(ids, '_')
--print(key)
local cached_id = expr_cache[key]
if cached_id then
--print("got cached expr "..cached_id)
table.insert(expr_ids, cached_id)
else
local new_id
if self.caching and self.new_db then
new_id = self:_add_expr(ids)
else
new_id = self:_get_or_add_expr(ids)
end
db_ops = db_ops + 1
expr_cache[key] = new_id
--print("expr: "..key, new_id)
table.insert(expr_ids, new_id)
end
end
--print(D(expr_cache))
--print("expr_ids: "..D(expr_ids))
--for _, expr_id in pairs(expr_ids) do
-- print("expr_id: "..expr_id, expr_cache[expr_id])
--end
table.insert(expr_ids, self._end_expr_id)
table.insert(expr_ids, 1, self._end_expr_id)
-- create/update links
--print("count: "..#expr_ids)
for i = 1, #expr_ids - 2 do
--print(expr_ids[i], expr_ids[i+2])
--print("foo")
if self.caching then
--print("bar")
local link_key = expr_ids[i]..'_'..expr_ids[i+2]
if self._link_cache[link_key] then
self._link_cache[link_key] = self._link_cache[link_key] + 1
else
self._link_cache[link_key] = 1
end
else
self:_inc_or_add_link(expr_ids[i], expr_ids[i+2], 1)
end
db_ops = db_ops + 1
end
--inc_or_add_link(boundary_expr_id, expr_ids[2])
--db_ops = db_ops + 1
--inc_or_add_link(expr_ids[#expr_ids-1], boundary_expr_id)
--db_ops = db_ops + 1
--print("db ops: "..db_ops)
end
-- TODO: use an expression cache?
function M:reply(tokens)
local token_cache = self:_resolve_input_tokens(tokens)
--print("token_cache: "..D(token_cache))
local pivots = {}
for token_id, _ in pairs(token_cache) do
table.insert(pivots, token_id)
end
if #pivots == 0 then
random_tokens = self:_get_random_tokens(1) -- TODO: pick a number
for _, token in pairs(random_tokens) do
table.insert(pivots, token[1])
token_cache[token[1]] = {token[2], token[3]}
end
--table.insert(pivots, 7172)
--token_cache[7172] = {0, teryaki}
end
if #pivots == 0 then
return("I don't know enough to answer you yet!")
end
--print("pivots: "..D(pivots))
-- TODO: scoring
--for _, reply in pairs(self:_generate_replies(pivots)) do
local reply = self:_generate_replies(pivots)[1]
local final_reply = {}
--print(D(reply))
--print("reply: "..D(reply))
-- TODO: make this a method
for _, token_id in pairs(reply) do
local token_spec = token_cache[token_id]
if not token_spec then
--print("lookup")
token_spec = self:_get_token_spec(token_id)
token_cache[token_id] = token_spec
end
--print(D(token_id))
--print(D(token_spec))
table.insert(final_reply, token_spec)
end
return final_reply
--end
end
function M:_generate_replies(pivots)
local replies = {}
for _, pivot_id in pairs(pivots) do
local reply = {self:_get_random_expr(pivot_id)}
--print(D(reply))
--print("reply is: "..D(reply))
--print("making prev")
while reply[1][2] ~= self._end_token_id do
local prev = self:_get_connected_expr(reply[1][1], "prev")
table.insert(reply, 1, prev)
--print("adding "..D(prev))
--print("reply is: "..D(reply))
end
--print(D(reply))
--print("making next")
while reply[#reply][3] ~= self._end_token_id do
local next = self:_get_connected_expr(reply[#reply][1], "next")
--print(D(next))
table.insert(reply, next)
--print("adding "..D(next))
--print("reply is: "..D(reply))
end
--print("reply is: "..D(reply))
local token_ids = {}
for _, expr in pairs(reply) do
--print("expr is: "..D(expr))
table.remove(expr, 1)
for _, token_id in pairs(expr) do
if token_id ~= self._end_token_id then
table.insert(token_ids, token_id)
end
end
end
table.insert(replies, token_ids)
end
return replies
end
function M:_get_connected_expr(expr_id, direction)
local stmt
if direction == "prev" then
stmt = self._sth.prev_expr
else
stmt = self._sth.next_expr
end
stmt:bind_names({last_expr_id = expr_id})
local status = stmt:step()
if status == sqlite3.ROW then
local expr = stmt:get_values()
stmt:reset()
return expr
end
stmt:reset()
end
function M:_get_random_expr(token_id)
local stmt = self._sth.random_expr
stmt:bind_names({id = token_id})
local status = stmt:step()
if status == sqlite3.ROW then
local expr = stmt:get_values()
stmt:reset()
return expr
end
stmt:reset()
end
function M:_get_token_spec(token_id)
local stmt = self._sth.token_spec
stmt:bind_values(token_id)
local status = stmt:step()
if status == sqlite3.ROW then
local token_spec = stmt:get_values()
stmt:reset()
return token_spec
end
stmt:reset()
return tokens
end
function M:_get_random_tokens(amount)
local tokens = {}
local stmt = self._sth.random_token
stmt:bind_values()
for i = 1,amount do
local status = stmt:step()
while status == sqlite3.ROW do
table.insert(tokens, stmt:get_values())
status = stmt:step()
end
stmt:reset()
end
return tokens
end
function M:_resolve_input_tokens(tokens)
local token_cache = {}
if #tokens == 1 then
-- When there's just one token, we'll be a bit more lax and settle
-- for any token which matches that text, regardless of spacing.
local text = tokens[1][2]
local token_info = self:_get_similar_token(tokens[1][2])
if token_info then
local id, spacing = unpack(token_info)
token_cache[id] = {spacing, text}
end
else
for _, token_spec in pairs(tokens) do
local spacing, text = unpack(token_spec)
local id = self_:get_token_id(spacing, text)
if id then
token_cache[id] = token_spec
end
end
end
return token_cache
end
function M:_get_similar_token(text)
local stmt = self._sth.similar_token
stmt:bind_values(text)
local status = stmt:step()
if status == sqlite3.ROW then
local token_info = stmt:get_values()
stmt:reset()
return token_info
end
stmt:reset()
end
function M:_get_token_id(spacing, text)
local stmt = self._sth.token_id
stmt:bind_values(spacing, text)
local status = stmt:step()
if status == sqlite3.ROW then
local id = stmt:get_uvalues()
stmt:reset()
return id
end
stmt:reset()
end
function M:_add_token(spacing, text)
local stmt = self._sth.add_token
stmt:bind_values(spacing, text)
stmt:step()
stmt:reset()
return self._db:last_insert_rowid()
end
function M:_get_or_add_token(spacing, text)
local token_id = self:_get_token_id(spacing, text)
if token_id then
return token_id
end
return self:_add_token(spacing, text)
end
function M:_get_expr(token_ids)
local stmt = self._sth.get_expr
stmt:bind_values(unpack(token_ids))
local status = stmt:step()
if status == sqlite3.ROW then
local id = stmt:get_uvalues()
stmt:reset()
return id
end
stmt:reset()
end
function M:_add_expr(token_ids)
local stmt = self._sth.add_expr
stmt:bind_values(unpack(token_ids))
stmt:step()
stmt:reset()
return self._db:last_insert_rowid()
end
function M:_get_or_add_expr(token_ids)
local expr_id = self:_get_expr(token_ids)
if expr_id then
return expr_id
end
return self:_add_expr(token_ids)
end
function M:_add_link(prev_expr, next_expr, count)
local stmt = self._sth.add_link
stmt:bind_values(prev_expr, next_expr, count)
stmt:step()
stmt:reset()
end
function M:_inc_or_add_link(prev_expr, next_expr, count)
local stmt = self._sth.inc_link
stmt:bind_values(count, prev_expr, next_expr)
stmt:step()
stmt:reset()
if self._db:changes() == 0 then
self:_add_link(prev_expr, next_expr, count)
end
end
return M
| mit |
ComputerNerd/Retro-Graphics-Toolkit | level.lua | 1 | 19003 | --[[
This file is part of Retro Graphics Toolkit
Retro Graphics Toolkit 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 any later version.
Retro Graphics Toolkit 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 Retro Graphics Toolkit. If not, see <http://www.gnu.org/licenses/>.
Copyright Sega16 (or whatever you wish to call me) (2012-2020)
--]]
lvlCurLayer = 1
editX,editY=0,0
szX,szY=0,0
function setSizePer()
local p = projects.current
local info = p.level.layers[lvlCurLayer].info
local src = bit32.band(info.src, 3)
local plane = bit32.rshift(info.src, 2) + 1
local chunks = p.chunks
local tileW = p.tiles.width
local tileH = p.tiles.height
local tilemap = p.tilemaps[plane]
if src==level.TILES then
szX = tileW
szY = tileH
elseif src==level.BLOCKS then
szX = tilemap.width * tileW
szY = tilemap.height * tileH
elseif src==level.CHUNKS then
szX = chunks.width * tileW
szY = chunks.height * tileH
if chunks.useBlocks ~= false then
szX = szX * tilemap.width
szY = szY * tilemap.height
end
end
end
lvlZoom=1
scrollX,scrollY=0,0
xOff,yOff=168,72
function setScrollBounds()
local p = projects.current
local info = p.level.layers[lvlCurLayer].info
local w = szX * lvlZoom * info.w
local h = szY * lvlZoom * info.h
if w<rgt.w()-xOff then
lvlScrollx:hide()
scrollX = 0
else
lvlScrollx:show()
lvlScrollx:bounds(0, info.w)
end
if h<rgt.h()-yOff then
lvlScrolly:hide()
scrollY = 0
else
lvlScrolly:show()
lvlScrolly:bounds(0, info.h)
end
end
function lvlsetlayer(layerIDX)
local p = projects.current
local layer = p.level.layers[layerIDX]
if layer == nil then
print('lvlsetlayerl called with invalid index', layerIDX)
return
end
lvlCurLayer = layerIDX
layerNameInput:value(layer.name)
local curLayerInfo = layer.info
wLayer:value(curLayerInfo.w)
hLayer:value(curLayerInfo.h)
-- Cap editX and editY to the bounds of the level.
editX = math.max(0, math.min(editX, curLayerInfo.w - 1))
editY = math.max(0, math.min(editY, curLayerInfo.h - 1))
local layerSource = bit32.band(curLayerInfo.src, 3)
lvlSrc:value(lvlSrcOptions[layerSource + 1])
setScrollBounds()
setSizePer()
local objectsCount = #layer.objects
if objectsCount > 0 then
spriteSel:maximum(objectsCount)
updateSpriteSliders(layer.objects[spriteEdit])
end
end
function checkCurLayerBounds()
local maxLayer = #projects.current.level.layers
if lvlCurLayer > maxLayer then
lvlsetlayer(maxLayer)
end
end
function layerNameToIndex(layerName)
local layers = projects.current.level.layers
for i = 1, #layers do
local ln = layers[i].name
if ln == layerName then
return i
end
end
return -1 -- Not found.
end
function lvlsetLayerCB(choiceObj)
local layerIndex = layerNameToIndex(choiceObj:value())
lvlsetlayer(layerIndex)
rgt.damage()
end
function lvlappend(unused)
local layers = projects.current.level.layers
layers:amount(#layers + 1, true)
local newLayer = layers[#layers]
layerSel:add(newLayer.name)
rgt.redraw()
end
function lvldelete(unused)
local layers = projects.current.level.layers
if #layers > 1 then
layerSel:remove(layers[lvlCurLayer].name)
layers[lvlCurLayer].remove()
checkCurLayerBounds()
rgt.redraw()
else
fltk.alert("You must have a minimum of one layer. If do not want a level disable it via means of the have level option in project settings")
end
end
function lvlscrollCB(unused)
scrollX = lvlScrollx:value()
scrollY = lvlScrolly:value()
rgt.redraw()
end
showSprites = false
function lvlshowspirtes(unused)
showSprites=spriteBtn:value()~=0
rgt.damage()
end
function setLayerName(unused)
local layer = projects.current.level.layers[lvlCurLayer]
local newLayerName = layerNameInput:value()
layerSel:replace(layer.name, newLayerName)
layer.name = newLayerName
rgt.redraw()
end
function setLvlzoomCB(unused)
lvlZoom = tSizeScrl:value()
setScrollBounds()
rgt.damage()
end
function invalidSource(src)
fltk.alert(string.format("%d is not a valid source",src))
end
function selSlideUpdateMax(src)
local p = projects.current
local chunks = p.chunks
if src == level.TILES then
selSlide:maximum(#p.tiles - 1)
elseif src == level.BLOCKS then
local plane = bit32.band(curLayerInfo.src, 2) + 1
local tilemap = p.tilemaps[plane]
selSlide:maximum(math.floor(tilemap.hAll / tilemap.h) - 1)
elseif src == level.CHUNKS then
selSlide:maximum(#chunks - 1)
else
invalidSource(src)
end
end
editModeLevel=false
function drawLevel()
local p = projects.current
local layer = p.level.layers[lvlCurLayer]
if layer == nil then
print('drawLevel called with invalid layer index', lvlCurLayer)
return
end
local curLayerInfo = layer.info
xOff = 168 * math.floor(rgt.w() / 800)
yOff = 72 * math.floor(rgt.h() / 600)
setScrollBounds()
local xs = xOff
local ys = yOff
local src = bit32.band(curLayerInfo.src, 3)
for j = scrollY, curLayerInfo.h - 1 do
local xxs = xs
for i = scrollX, curLayerInfo.w - 1 do
local a = layer[j + 1][i + 1]
local plane = bit32.rshift(curLayerInfo.src, 2)
if src == level.TILES then
local tile = p.tiles[a.id]
if tile ~= nil then
tile:draw(xxs, ys, lvlZoom, bit32.band(bit32.rshift(a.dat, 2), 3) + 1, bit32.band(a.dat, 1), bit32.band(a.dat, 2), false, false) -- +1 for the palette row because the first pallete row in Lua is 1 wheras in the data it starts with zero.
end
elseif src == level.BLOCKS then
p.tilemaps[plane + 1].drawBlock(a.id, xxs, ys, bit32.band(a.dat, 3), lvlZoom)
elseif src == level.CHUNKS then
local chunks = p.chunks
if a.id <= #chunks then
chunks[a.id]:draw(xxs,ys,lvlZoom,0,0)
else
print('a.id > chunks.amt',a.id, #chunks)
end
else
invalidSource(src)
end
if editModeLevel and editX==i and editY==j then
fl.draw_box(--[[FL.EMBOSSED_FRAME--]]13,xxs,ys,szX*lvlZoom+1,szY*lvlZoom+1,0)
end
xxs=xxs+szX*lvlZoom
if xxs>=rgt.w() then
break
end
end
ys=ys+szY*lvlZoom
if ys>=rgt.h() then
break
end
end
if showSprites then
local objects = layer.objects
if #objects > 0 then
for i = 1, #objects do
local info = objects[i]
local ms = projects[info.prjid + 1].metasprites[info.metaid + 1]
local sg = ms[info.groupid + 1]
sg:draw((info.x*lvlZoom)+xOff-(szX*lvlZoom),(info.y*lvlZoom)+yOff-(szY*lvlZoom),lvlZoom,true)
end
end
end
selSlideUpdateMax(src)
if #layer.objects > 0 then
updateSpriteSliders(layer.objects[spriteEdit])
end
end
selectedIdx = 0
function selSlideCB(unused)
selectedIdx=selSlide:value()
if editModeLevel then
local layerItem = projects.current.level.layers[lvlCurLayer][editY + 1][editX + 1]
layerItem.id = selectedIdx
rgt.damage()
end
end
function idBondsChk(idraw)
if idraw<0 then
return 0
elseif idraw>selSlide:maximum() then
return selSlide:maximum()
else
return idraw
end
end
editSpriteMode=false
function editSpritesCB(unused)
editSpriteMode=editSpriteBtn:value()~=0
end
spriteEdit = 1
function updateSpriteSliders(info)
local layer = projects.current.level.layers[lvlCurLayer]
if #layer.objects > 0 then
spriteSel:show()
spritePrj:show()
spriteMeta:show()
spriteGroup:show()
local oldID = projects.currentIdx
spritePrj:maximum(#projects - 1)
if info.prjid~=oldID then
project.set(info.prjid)
end
local metasprites = projects.current.metasprites
spriteMeta:maximum(#metasprites - 1)
spriteGroup:maximum(#metasprites[spriteMeta:value() + 1] - 1)
if project.curProjectID~=oldID then
project.set(oldID)
end
spriteSel:value(spriteEdit)
spritePrj:value(info.prjid)
spriteMeta:value(info.metaid)
spriteGroup:value(info.groupid)
else
editSpriteMode=false
spriteSel:hide()
spritePrj:hide()
spriteMeta:hide()
spriteGroup:hide()
end
end
function setSpriteEditCB(unused)
spriteEdit=spriteSel:value()
updateSpriteSliders(level.getObj(lvlCurLayer,spriteEdit))
rgt.redraw()
end
prj,meta,group=0,0,0
function setSpritePrj(unused)
prj=spritePrj:value()
local info=level.getObj(lvlCurLayer,spriteEdit)
info.prjid=prj
updateSpriteSliders(info)
rgt.redraw()
end
function setSpriteMeta(unused)
meta=spriteMeta:value()
local info=level.getObj(lvlCurLayer,spriteEdit)
info.metaid=meta
updateSpriteSliders(info)
rgt.redraw()
end
function setSpriteGroup(unused)
group=spriteGroup:value()
local info=level.getObj(lvlCurLayer,spriteEdit)
info.groupid=group
updateSpriteSliders(info)
rgt.redraw()
end
function handleLevel(e)
local p = projects.current
local x, y
if editSpriteMode then
if e==FL.PUSH then
x,y=Fl.event_x()-xOff,Fl.event_y()-yOff
if x>=0 and y>=0 then
x= math.floor(x / lvlZoom) + (scrollX*szX)
y= math.floor(y / lvlZoom) + (scrollY*szY)
level.appendObj(lvlCurLayer)
spriteSel:maximum(level.objamt[lvlCurLayer+1]-1)
spriteEdit=level.objamt[lvlCurLayer+1]-1
spriteSel:value(spriteEdit)
local info=level.getObj(lvlCurLayer,spriteEdit)
updateSpriteSliders(info)
info.x=x
info.y=y
info.prjid=prj
info.metaid=meta
info.groupid=group
rgt.damage()
end
end
else
local shouldDamage = false
local curLayerInfo
local layer
if e == FL.PUSH or e == FL.SHORTCUT then
x,y=Fl.event_x(),Fl.event_y()
x = math.floor((x-xOff) / (szX*lvlZoom)) + scrollX
y = math.floor((y-yOff) / (szY*lvlZoom)) + scrollY
if x < 0 or y < 0 then
return
end
layer = p.level.layers[lvlCurLayer]
curLayerInfo = layer.info
if x >= curLayerInfo.w or y >= curLayerInfo.h then
return
end
end
if e == FL.PUSH then
if Fl.event_button()==FL.LEFT_MOUSE then
if not (editModeLevel and editX==x and editY==y) then
local info = layer[y + 1][x + 1]
info.id = selectedIdx + 1
end
editModeLevel=false
else
if editModeLevel then
editModeLevel=false
else
local info = layer[y + 1][x + 1]
selectedIdx=info.id
selSlide:value(info.id)
editX=x
editY=y
editModeLevel=true
end
end
rgt.damage()
elseif e==FL.SHORTCUT then
t=Fl.event_text()
local addT=0
if t=='a' then
addT=-1
shouldDamage = true
elseif t=='s' then
addT=1
shouldDamage = true
end
local info = layer[y + 1][x + 1]
if editModeLevel then
if t=='h' then
if editX>0 then
editX=editX-1
shouldDamage = true
end
elseif t=='j' then
if editY<(curLayerInfo.h-1) then
editY=editY+1
shouldDamage = true
end
elseif t=='k' then
if editY>0 then
editY=editY-1
shouldDamage = true
end
elseif t=='l' then
if editX<(curLayerInfo.w-1) then
editX=editX+1
shouldDamage = true
end
end
selectedIdx=idBondsChk(info.id + addT)
info.id=selectedIdx
selSlide:value(selectedIdx)
else
selectedIdx=idBondsChk(info.id + addT)
selSlide:value(selectedIdx)
end
end
if shouldDamage then
rgt.damage()
end
end
end
function setLayerSrc(valStr)
local p = projects.current
local curLayerInfo = p.level.layers[lvlCurLayer].info
local plane = bit32.rshift(curLayerInfo.src, 2) + 1
local val = lvlSrcLUT[valStr]
if val == level.BLOCKS and p.tilemaps[plane].useBlocks ~= true then
fltk.alert("You must first enable blocks in the plane editor")
lvlSrc:value(lvlSrcOptions[bit32.band(curLayerInfo.src, 3) + 1])
return
end
curLayerInfo.src = bit32.replace(curLayerInfo.src, val, 0, 2)
rgt.syncProject()--Needed for selSlideUpdateMax
selSlideUpdateMax(val)
setSizePer()
end
function setLayerSrcCB(unused)
setLayerSrc(lvlSrc:value())
rgt.damage()
end
function resizeLayerCB(unused)
local layer = projects.current.level.layers[lvlCurLayer]
layer:resize(wLayer:value(), hLayer:value())
lvlsetlayer(lvlCurLayer)
setScrollBounds()
rgt.redraw()
end
function loadS1layoutFname(fname)
local p = projects.current
if not (fname == nil or fname == '') then
local file=assert(io.open(fname,'rb'))
local str=file:read("*a")--Lua strings can have embedded zeros
io.close(file)
local w,h=str:byte(1)+1,str:byte(2)+1
local layer = p.level.layers[lvlCurLayer]
layer:resize(w, h)
lvlsetlayer(lvlCurLayer)
setLayerSrc('Chunks')
lvlSrc:value('Chunks')
wLayer:value(w)
hLayer:value(h)
local idx=3
for j = 1, h do
for i = 1, w do
local info = layer[j][i]
info.id = bit32.band(str:byte(idx), 127) + 1
info.dat = bit32.band(str:byte(idx), 128)
idx=idx+1
end
end
end
end
function loadS1layout(unused)
local p = projects.current
if p:have(project.levelMask + project.chunksMask) then
local fname = fl.file_chooser("Load layout")
loadS1layoutFname(fname)
else
project.haveMessage(project.levelMask + project.chunksMask)
end
end
function saveS1layout(unused)
rgt.syncProject()
local p = projects.current
if p:have(project.levelMask) then
local layer = p.level.layers[lvlCurLayer]
local curLayerInfo = layer.info
if curLayerInfo.w<=256 and curLayerInfo.h<=256 then
local fname=fl.file_chooser("Save layout")
if not (fname == nil or fname == '') then
local file=assert(io.open(fname,'wb'))
file:write(string.char(curLayerInfo.w-1))
file:write(string.char(curLayerInfo.h-1))
for j=1, curLayerInfo.h do
local layerRow = layer[j]
for i=1, curLayerInfo.w do
local info = layerRow[i]
file:write(string.char(bit32.bor(bit32.band(info.id - 1, 127), bit32.band(info.dat, 128))))
end
end
file:close()
end
else
fltk.alert("The header only allows one byte for width and height. The maximum width and height is 256")
end
else
p:haveMessage(project.levelMask)
end
end
function appendSpriteCB(unused)
local layer = projects.current.level.layers[lvlCurLayer]
local objects = layer.objects
objects:append()
spriteSel:maximum(#objects - 1)
updateSpriteSliders(objects[spriteEdit + 1])
rgt.redraw()
end
function deleteSpriteCB(unused)
if level.objamt[lvlCurLayer+1]>0 then
level.delObj(lvlCurLayer,spriteEdit)
if level.objamt[lvlCurLayer+1]>0 then
spriteSel:maximum(level.objamt[lvlCurLayer+1]-1)
if spriteEdit>=level.objamt[lvlCurLayer+1] then
spriteEdit=level.objamt[lvlCurLayer+1]-1
spriteSel:value(spriteEdit)
end
else
spriteSel:maximum(0)
spriteEdit=0
end
updateSpriteSliders(info)
else
editSpriteMode=false
spriteSel:hide()
spritePrj:hide()
spriteMeta:hide()
spriteGroup:hide()
end
rgt.redraw()
end
function initLevelEditor()
local p = projects.current
local level = p.level
local layer = level.layers[lvlCurLayer]
--Note Lua's scoping rules are different than C/C++. All these variables are in fact globals and thus you can access them in the callbacks
setSizePer()
layerSel=fltk.choice(4,64,136,24,"Layer selection:")
layerSel:align(FL.ALIGN_TOP)
layerSel:callback(lvlsetLayerCB)
layerSel:tooltip('Sets the current layer')
for i = 1, #level.layers do
layerSel:add(level.layers[i].name)
end
layerNameInput=fltk.input(4,108,136,24,"Layer name:")
layerNameInput:align(FL.ALIGN_TOP)
layerNameInput:tooltip('Sets the name for the current layer')
layerNameInput:callback(setLayerName)
layerNameInput:value(layer.name)
appendBtn=fltk.button(4,144,64,24,"Append layer")
appendBtn:callback(lvlappend)
appendBtn:labelsize(11)
appendSpriteBtn=fltk.button(72,144,64,24,"Append sprite")
appendSpriteBtn:callback(appendSpriteCB)
appendSpriteBtn:labelsize(11)
deleteBtn=fltk.button(4,176,64,24,"Delete layer")
deleteBtn:labelsize(11)
deleteBtn:callback(lvldelete)
deleteSpriteBtn=fltk.button(72,176,64,24,"Delete sprite")
deleteSpriteBtn:labelsize(11)
deleteSpriteBtn:callback(deleteSpriteCB)
spriteBtn=fltk.light_button(4,204,136,24,"Show sprites")
spriteBtn:box(FL.NO_BOX)
spriteBtn:down_box(3)--FL_DOWN_BOX and variables beyond that are read as nil for some reason even though functions such as print_r (the function I found here: https://gist.github.com/nrk/31175 ) display their value
spriteBtn:selection_color(FL.FOREGROUND_COLOR)
spriteBtn:callback(lvlshowspirtes)
spriteBtn:type(FL.TOGGLE_BUTTON)
spriteBtn:value(showSprites)
selSlide = fltk.value_slider(4,240,136,24,'Index selection')
selSlide:align(FL.ALIGN_TOP)
selSlide:tooltip('Sets current (tile|blocks|chunk)')
selSlide:callback(selSlideCB)
selSlide:step(1)
selSlide:maximum(0)
selSlide:type(FL.HOR_SLIDER)
tSizeScrl = fltk.value_slider(4,280,136,24,"Tile zoom factor")
tSizeScrl:align(FL.ALIGN_TOP)
tSizeScrl:tooltip('Sets the zoom of the tiles')
tSizeScrl:type(FL.HOR_SLIDER)
tSizeScrl:step(1)
tSizeScrl:maximum(16)
tSizeScrl:minimum(1)
tSizeScrl:value(1)
tSizeScrl:callback(setLvlzoomCB)
wLayer=fltk.int_input(48,308,92,24,"Width:")
wLayer:value(1)
wLayer:callback(resizeLayerCB)
hLayer=fltk.int_input(48,340,92,24,"Height:")
hLayer:value(1)
hLayer:callback(resizeLayerCB)
lvlSrc=fltk.choice(4, 380, 136, 24, "Source selection:")
lvlSrc:align(FL.ALIGN_TOP)
lvlSrcOptions = {'Tiles', 'Blocks', 'Chunks'}
lvlSrcLUT = generateLutFromList(lvlSrcOptions)
addItemsToChoice(lvlSrc, lvlSrcOptions)
lvlSrc:callback(setLayerSrcCB)
editSpriteBtn=fltk.light_button(4,404,136,24,"Click add sprites?")
editSpriteBtn:box(FL.NO_BOX)
editSpriteBtn:down_box(3)
editSpriteBtn:selection_color(FL.FOREGROUND_COLOR)
editSpriteBtn:callback(editSpritesCB)
editSpriteBtn:type(FL.TOGGLE_BUTTON)
spriteSel=fltk.value_slider(4,436,136,24,"Sprite selection")
spriteSel:align(FL.ALIGN_TOP)
spriteSel:type(FL.HOR_SLIDER)
spriteSel:step(1)
spriteSel:minimum(0)
spriteSel:maximum(0)
spriteSel:value(0)
spriteSel:callback(setSpriteEditCB)
spriteSel:hide()
spritePrj=fltk.value_slider(4,480,136,24,"Sprite's project ID")
spritePrj:align(FL.ALIGN_TOP)
spritePrj:type(FL.HOR_SLIDER)
spritePrj:step(1)
spritePrj:minimum(0)
spritePrj:maximum(0)
spritePrj:value(0)
spritePrj:callback(setSpritePrj)
spritePrj:hide()
spriteMeta=fltk.value_slider(4,524,136,24,"Sprite's meta ID")
spriteMeta:align(FL.ALIGN_TOP)
spriteMeta:type(FL.HOR_SLIDER)
spriteMeta:step(1)
spriteMeta:minimum(0)
spriteMeta:maximum(0)
spriteMeta:value(0)
spriteMeta:callback(setSpriteMeta)
spriteMeta:hide()
spriteGroup = fltk.value_slider(4,564,136,24,"Sprite's group ID")
spriteGroup:align(FL.ALIGN_TOP)
spriteGroup:type(FL.HOR_SLIDER)
spriteGroup:step(1)
spriteGroup:minimum(0)
spriteGroup:maximum(0)
spriteGroup:value(0)
spriteGroup:callback(setSpriteGroup)
spriteGroup:hide()
lvlScrolly=fltk.scrollbar(144,48,24,544)
lvlScrolly:callback(lvlscrollCB)
lvlScrolly:hide()
lvlScrolly:linesize(1)
lvlScrollx=fltk.scrollbar(168,48,624,24)
lvlScrollx:type(FL.HORIZONTAL)
lvlScrollx:callback(lvlscrollCB)
lvlScrollx:hide()
lvlScrollx:linesize(1)
end
| gpl-3.0 |
makefu/nodemcu-firmware | lua_examples/adc_rgb.lua | 73 | 1163 | --
-- Light sensor on ADC(0), RGB LED connected to gpio12(6) Green, gpio13(7) Blue & gpio15(8) Red.
-- This works out of the box on the typical ESP8266 evaluation boards with Battery Holder
--
-- It uses the input from the sensor to drive a "rainbow" effect on the RGB LED
-- Includes a very "pseudoSin" function
--
function led(r,Sg,b)
pwm.setduty(8,r)
pwm.setduty(6,g)
pwm.setduty(7,b)
end
-- this is perhaps the lightest weight sin function in existance
-- Given an integer from 0..128, 0..512 appximating 256 + 256 * sin(idx*Pi/256)
-- This is first order square approximation of sin, it's accurate around 0 and any multiple of 128 (Pi/2),
-- 92% accurate at 64 (Pi/4).
function pseudoSin (idx)
idx = idx % 128
lookUp = 32 - idx % 64
val = 256 - (lookUp * lookUp) / 4
if (idx > 64) then
val = - val;
end
return 256+val
end
pwm.setup(6,500,512)
pwm.setup(7,500,512)
pwm.setup(8,500,512)
pwm.start(6)
pwm.start(7)
pwm.start(8)
tmr.alarm(1,20,1,function()
idx = 3 * adc.read(0) / 2
r = pseudoSin(idx)
g = pseudoSin(idx + 43)
b = pseudoSin(idx + 85)
led(r,g,b)
idx = (idx + 1) % 128
end)
| mit |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/luaui/widgets/unit_stockpile_dynamic.lua | 1 | 4556 | -------------------------------------------------------------------------------
-- DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
-- Version 2, December 2004
--
--Copyright (C) 2009 BrainDamage
--Everyone is permitted to copy and distribute verbatim or modified
--copies of this license document, and changing it is allowed as long
--as the name is changed.
--
-- DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
-- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
--
-- 0. You just DO WHAT THE FUCK YOU WANT TO.
-------------------------------------------------------------------------------
local MaxStockpile = 5 -- set this to desired stockpile levels
function widget:GetInfo()
return {
name = "Stockpiler (dynamic)",
desc = "keeps stockpiled units at max " .. MaxStockpile .. " in storage",
author = "BD",
date = "tomorrow",
license = "WTFPL",
layer = 0,
enabled = true, -- loaded by default?
}
end
local GetTeamUnits = Spring.GetTeamUnits
local GetMyTeamID = Spring.GetMyTeamID
local SetUnitGroup = Spring.SetUnitGroup
local GetSpectatingState= Spring.GetSpectatingState
local GetUnitDefID = Spring.GetUnitDefID
local GetUnitStockpile = Spring.GetUnitStockpile
local GiveOrderToUnit = Spring.GiveOrderToUnit
function widget:SetConfigData(data)
MaxStockpile = data.MaxStockpile
return
end
function widget:GetConfigData()
return
{
MaxStockpile= MaxStockpile,
}
end
function ChangeMaxStockPile(_,_,words)
MaxStockpile = tonumber(words[1]) or MaxStockpile
Spring.Echo("Automatic stockpile set to" .. MaxStockpile)
UpdateStockPileAllUnits()
end
function widget:Initialize()
if GetSpectatingState() then
widgetHandler:RemoveWidget()
return
end
--Spring.SendCommands{"luaui disablewidget Stockpiler"} -- Disable the old stockpiler widget which could conflict
widgetHandler:AddAction("stockpilecount", ChangeMaxStockPile, nil, "t")
-- stockpile all existing units
UpdateStockPileAllUnits()
end
function UpdateStockPileAllUnits()
local allUnits = GetTeamUnits(GetMyTeamID())
for _, unitID in pairs(allUnits) do
local unitDefID = GetUnitDefID(unitID)
local ud = UnitDefs[unitDefID]
if ( ud and ud.canStockpile ) then
CancelExcessStockpile(unitID)
DoStockPile(unitID)
end
end
end
function widget:PlayerChanged(playerID)
if GetSpectatingState() then
widgetHandler:RemoveWidget()
return
end
end
function DoStockPile( unitID )
local stock,queued = GetUnitStockpile(unitID)
if ( queued and stock ) then
local count = stock + queued - MaxStockpile
while ( count < 0 ) do
if (count < -100) then
GiveOrderToUnit(unitID, CMD.STOCKPILE, {}, { "ctrl", "shift" })
count = count + 100
elseif (count < -20) then
GiveOrderToUnit(unitID, CMD.STOCKPILE, {}, { "ctrl" })
count = count + 20
elseif (count < -5) then
GiveOrderToUnit(unitID, CMD.STOCKPILE, {}, { "shift" })
count = count + 5
else
GiveOrderToUnit(unitID, CMD.STOCKPILE, {}, { "" })
count = count + 1
end
end
end
end
function CancelExcessStockpile( unitID )
local stock,queued = GetUnitStockpile(unitID)
if ( queued and stock ) then
local count = stock + queued - MaxStockpile
while ( count > 0 ) do
if (count > 100) then
GiveOrderToUnit(unitID, CMD.STOCKPILE, {}, { "right", "ctrl", "shift" })
count = count - 100
elseif (count > 20) then
GiveOrderToUnit(unitID, CMD.STOCKPILE, {}, { "right", "ctrl" })
count = count - 20
elseif (count > 5) then
GiveOrderToUnit(unitID, CMD.STOCKPILE, {}, { "right", "shift" })
count = count - 5
else
GiveOrderToUnit(unitID, CMD.STOCKPILE, {}, { "right" })
count = count - 1
end
end
end
end
function widget:UnitCreated(unitID, unitDefID, unitTeam)
local ud = UnitDefs[unitDefID]
if ((ud ~= nil) and (unitTeam == GetMyTeamID())) then
if (ud.canStockpile) then
CancelExcessStockpile( unitID ) -- theorically when a unit is created it should have no stockpiled items, but better be paranoid and add this, plus code can be reused for unit given and captured
DoStockPile( unitID )
end
end
end
function widget:UnitGiven(unitID, unitDefID, unitTeam)
widget:UnitCreated(unitID, unitDefID, unitTeam)
end
function widget:UnitCaptured(unitID, unitDefID, unitTeam)
widget:UnitCreated(unitID, unitDefID, unitTeam)
end
function widget:StockpileChanged(unitID, unitDefID, unitTeam, weaponNum, oldCount, newCount)
if ( unitTeam == GetMyTeamID() ) then
DoStockPile( unitID )
end
end
| gpl-2.0 |
MinaciousGrace/Til-Death | BGAnimations/ScreenSelectMusic decorations/songinfo.lua | 2 | 1273 | local update = false
local t = Def.ActorFrame{
BeginCommand=cmd(queuecommand,"Set");
OffCommand=cmd(bouncebegin,0.2;xy,-500,0;); -- visible(false) doesn't seem to work with sleep
OnCommand=cmd(bouncebegin,0.2;xy,0,0;);
SetCommand=function(self)
self:finishtweening()
if getTabIndex() == 0 then
self:queuecommand("On");
update = true
else
self:queuecommand("Off");
update = false
end;
end;
TabChangedMessageCommand=cmd(queuecommand,"Set");
PlayerJoinedMessageCommand=cmd(queuecommand,"Set");
};
t[#t+1] = Def.Banner{
InitCommand=cmd(x,10;y,61;halign,0;valign,0);
SetMessageCommand=function(self)
if update then
local top = SCREENMAN:GetTopScreen()
if top:GetName() == "ScreenSelectMusic" or top:GetName() == "ScreenNetSelectMusic" then
local song = GAMESTATE:GetCurrentSong()
local course = GAMESTATE:GetCurrentCourse()
local group = top:GetMusicWheel():GetSelectedSection()
if song then
self:LoadFromSong(song)
elseif course then
self:LoadFromCourse(song)
elseif group then
self:LoadFromSongGroup(group)
end;
end;
end;
self:scaletoclipped(capWideScale(get43size(384),384),capWideScale(get43size(120),120))
end;
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set");
};
return t | mit |
githubmereza/creed_plug | plugins/add_bot.lua | 189 | 1492 | --[[
Bot can join into a group by replying a message contain an invite link or by
typing !add [invite link].
URL.parse cannot parsing complicated message. So, this plugin only works for
single [invite link] in a post.
[invite link] may be preceeded but must not followed by another characters.
--]]
do
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
i = 0
for k,segment in pairs(parsed_path) do
i = i + 1
if segment == 'joinchat' then
invite_link = string.gsub(parsed_path[i+1], '[ %c].+$', '')
break
end
end
return invite_link
end
local function action_by_reply(extra, success, result)
local hash = parsed_url(result.text)
join = import_chat_link(hash, ok_cb, false)
end
function run(msg, matches)
if is_sudo(msg) then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
elseif matches[1] then
local hash = parsed_url(matches[1])
join = import_chat_link(hash, ok_cb, false)
end
end
end
return {
description = 'Invite the bot into a group chat via its invite link.',
usage = {
'!AddBot : Join a group by replying a message containing invite link.',
'!AddBot [invite_link] : Join into a group by providing their [invite_link].'
},
patterns = {
'^[/!](addBot)$',
'^[/!](ddBot) (.*)$'
},
run = run
}
end
| gpl-2.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/corcv.lua | 1 | 2550 | return {
corcv = {
acceleration = 0.057199999690056,
brakerate = 0.17820000648499,
buildcostenergy = 0,
buildcostmetal = 200,
builddistance = 112,
buildpic = "CORCV.DDS",
buildtime = 2000,
canmove = true,
category = "ALL TANK MOBILE NOTSUB NOWEAPON NOTSHIP NOTAIR NOTHOVER SURFACE",
corpse = "DEAD",
description = "Tech Level 1",
energymake = 0,
energystorage = 0,
energyuse = 0,
explodeas = "BIG_UNITEX",
footprintx = 3,
footprintz = 3,
idleautoheal = 5,
idletime = 1800,
leavetracks = true,
maxdamage = 1290,
maxslope = 16,
maxvelocity = 1.8150000572205,
maxwaterdepth = 19,
metalmake = 0,
metalstorage = 50,
movementclass = "TANK3",
name = "Construction Vehicle",
objectname = "CORCV",
radardistance = 50,
seismicsignature = 0,
selfdestructas = "BIG_UNIT",
sightdistance = 260,
terraformspeed = 450,
trackoffset = 3,
trackstrength = 6,
tracktype = "StdTank",
trackwidth = 32,
turnrate = 421,
workertime = 0,
transportcapacity = 10,
transportmass = 50000,
transportsize = 30,
loadingRadius = 5000,
featuredefs = {
dead = {
blocking = true,
category = "corpses",
collisionvolumeoffsets = "0.31364440918 1.09863281317e-06 0.657264709473",
collisionvolumescales = "32.9147644043 17.5585021973 49.4168548584",
collisionvolumetype = "Box",
damage = 774,
description = "Construction Vehicle Wreckage",
energy = 0,
featuredead = "HEAP",
featurereclamate = "SMUDGE01",
footprintx = 3,
footprintz = 3,
height = 20,
hitdensity = 100,
metal = 87,
object = "CORCV_DEAD",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
heap = {
blocking = false,
category = "heaps",
damage = 387,
description = "Construction Vehicle Heap",
energy = 0,
featurereclamate = "SMUDGE01",
footprintx = 3,
footprintz = 3,
height = 4,
hitdensity = 100,
metal = 35,
object = "3X3D",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
},
sounds = {
build = "nanlath2",
canceldestruct = "cancel2",
capture = "capture1",
repair = "repair2",
underattack = "warning1",
working = "reclaim1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "vcormove",
},
select = {
[1] = "vcorsel",
},
},
},
}
| gpl-2.0 |
PichotM/DarkRP | entities/entities/spawned_shipment/init.lua | 2 | 6643 | AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
include("commands.lua")
util.AddNetworkString("DarkRP_shipmentSpawn")
function ENT:Initialize()
local contents = CustomShipments[self:Getcontents() or ""]
self.Destructed = false
self:SetModel(contents and contents.shipmodel or "models/Items/item_item_crate.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:StartSpawning()
self.damage = 100
local phys = self:GetPhysicsObject()
phys:Wake()
-- Create a serverside gun model
-- it's required serverside to be able to get OBB information clientside
self:SetgunModel(IsValid(self:GetgunModel()) and self:GetgunModel() or ents.Create("prop_physics"))
self:GetgunModel():SetModel(contents.model)
self:GetgunModel():SetPos(self:GetPos())
self:GetgunModel():Spawn()
self:GetgunModel():Activate()
self:GetgunModel():SetSolid(SOLID_NONE)
self:GetgunModel():SetParent(self)
phys = self:GetgunModel():GetPhysicsObject()
if IsValid(phys) then
phys:EnableMotion(false)
end
-- The following code should not be reached
if self:Getcount() < 1 then
self.PlayerUse = false
SafeRemoveEntity(self)
if not contents then
DarkRP.error("Shipment created with zero or fewer elements.", 2)
else
DarkRP.error(string.format("Some smartass thought they were clever by setting the 'amount' of shipment '%s' to 0.\nWhat the fuck do you expect the use of an empty shipment to be?", contents.name), 2)
end
end
end
function ENT:StartSpawning()
self.locked = true
timer.Simple(0, function()
net.Start("DarkRP_shipmentSpawn")
net.WriteEntity(self)
net.Broadcast()
end)
timer.Simple(0, function() self.locked = true end) -- when spawning through pocket it might be unlocked
timer.Simple(GAMEMODE.Config.shipmentspawntime, function() if IsValid(self) then self.locked = false end end)
end
function ENT:OnTakeDamage(dmg)
self:TakePhysicsDamage(dmg)
if not self.locked then
self.damage = self.damage - dmg:GetDamage()
if self.damage <= 0 then
self:Destruct()
end
end
end
function ENT:SetContents(s, c)
self:Setcontents(s)
self:Setcount(c)
end
function ENT:Use(activator, caller)
if self.IsPocketed then return end
if type(self.PlayerUse) == "function" then
local val = self:PlayerUse(activator, caller)
if val ~= nil then return val end
elseif self.PlayerUse ~= nil then
return self.PlayerUse
end
if self.locked or self.USED then return end
self.locked = true -- One activation per second
self.USED = true
self.sparking = true
self:Setgunspawn(CurTime() + 1)
timer.Create(self:EntIndex() .. "crate", 1, 1, function()
if not IsValid(self) then return end
self.SpawnItem(self)
end)
end
function ENT:SpawnItem()
if not IsValid(self) then return end
timer.Remove(self:EntIndex() .. "crate")
self.sparking = false
local count = self:Getcount()
if count <= 1 then self:Remove() end
local contents = self:Getcontents()
if CustomShipments[contents] and CustomShipments[contents].spawn then self.USED = false return CustomShipments[contents].spawn(self, CustomShipments[contents]) end
local weapon = ents.Create("spawned_weapon")
local weaponAng = self:GetAngles()
local weaponPos = self:GetAngles():Up() * 40 + weaponAng:Up() * (math.sin(CurTime() * 3) * 8)
weaponAng:RotateAroundAxis(weaponAng:Up(), (CurTime() * 180) % 360)
if not CustomShipments[contents] then
weapon:Remove()
self:Remove()
return
end
local class = CustomShipments[contents].entity
local model = CustomShipments[contents].model
weapon:SetWeaponClass(class)
weapon:SetModel(model)
weapon.ammoadd = self.ammoadd or (weapons.Get(class) and weapons.Get(class).Primary.DefaultClip)
weapon.clip1 = self.clip1
weapon.clip2 = self.clip2
weapon:SetPos(self:GetPos() + weaponPos)
weapon:SetAngles(weaponAng)
weapon.nodupe = true
weapon:Spawn()
count = count - 1
self:Setcount(count)
self.locked = false
self.USED = nil
end
function ENT:Think()
if self.sparking then
local effectdata = EffectData()
effectdata:SetOrigin(self:GetPos())
effectdata:SetMagnitude(1)
effectdata:SetScale(1)
effectdata:SetRadius(2)
util.Effect("Sparks", effectdata)
end
end
function ENT:Destruct()
if self.Destructed then return end
self.Destructed = true
local vPoint = self:GetPos()
local contents = self:Getcontents()
local count = self:Getcount()
local class = nil
local model = nil
if CustomShipments[contents] then
class = CustomShipments[contents].entity
model = CustomShipments[contents].model
else
self:Remove()
return
end
local weapon = ents.Create("spawned_weapon")
weapon:SetModel(model)
weapon:SetWeaponClass(class)
weapon:SetPos(Vector(vPoint.x, vPoint.y, vPoint.z + 5))
weapon.ammoadd = self.ammoadd or (weapons.Get(class) and weapons.Get(class).Primary.DefaultClip)
weapon.clip1 = self.clip1
weapon.clip2 = self.clip2
weapon.nodupe = true
weapon:Spawn()
weapon.dt.amount = count
self:Remove()
end
function ENT:StartTouch(ent)
-- the .USED var is also used in other mods for the same purpose
if not ent.IsSpawnedShipment or
self:Getcontents() ~= ent:Getcontents() or
self.locked or ent.locked or
self.USED or ent.USED or
self.hasMerged or ent.hasMerged then return end
-- Both hasMerged and USED are used by third party mods. Keep both in.
ent.hasMerged = true
ent.USED = true
local selfCount, entCount = self:Getcount(), ent:Getcount()
local count = selfCount + entCount
self:Setcount(count)
-- Merge ammo information (avoid ammo exploits)
if self.clip1 or ent.clip1 then -- If neither have a clip, use default clip, otherwise merge the two
self.clip1 = math.floor(((ent.clip1 or 0) * entCount + (self.clip1 or 0) * selfCount) / count)
end
if self.clip2 or ent.clip2 then
self.clip2 = math.floor(((ent.clip2 or 0) * entCount + (self.clip2 or 0) * selfCount) / count)
end
if self.ammoadd or ent.ammoadd then
self.ammoadd = math.floor(((ent.ammoadd or 0) * entCount + (self.ammoadd or 0) * selfCount) / count)
end
ent:Remove()
end
| mit |
imashkan/ABCYAGOP | plugins/get.lua | 613 | 1067 | local function get_variables_hash(msg)
if msg.to.type == 'chat' then
return 'chat:'..msg.to.id..':variables'
end
if msg.to.type == 'user' then
return 'user:'..msg.from.id..':variables'
end
end
local function list_variables(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
text = text..names[i]..'\n'
end
return text
end
end
local function get_value(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return'Not found, use "!get" to list variables'
else
return var_name..' => '..value
end
end
end
local function run(msg, matches)
if matches[2] then
return get_value(msg, matches[2])
else
return list_variables(msg)
end
end
return {
description = "Retrieves variables saved with !set",
usage = "!get (value_name): Returns the value_name value.",
patterns = {
"^(!get) (.+)$",
"^!get$"
},
run = run
}
| gpl-2.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/gadg dev/battlestance0.9.lua | 1 | 4877 |
function gadget:GetInfo()
return {
name = "battlestance",
desc = "Toggle between Defensive, Assault and Sprint",
author = "Zealot",
date = "13th July 2013",
license = "GNU LGPL, v2.1 or later",
layer = 101, -------------------------What does this do?
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if (not gadgetHandler:IsSyncedCode()) then
return
end
local EditUnitCmdDesc = Spring.EditUnitCmdDesc
local FindUnitCmdDesc = Spring.FindUnitCmdDesc
local InsertUnitCmdDesc = Spring.InsertUnitCmdDesc
local GiveOrderToUnit = Spring.GiveOrderToUnit
local SetUnitNeutral = Spring.SetUnitNeutral
local GetUnitMoveTypeData = Spring.GetUnitMoveTypeData
local SetGroundMoveTypeData = Spring.MoveCtrl.SetGroundMoveTypeData
local SetUnitCloak = Spring.SetUnitCloak
local SetUnitArmored = Spring.SetUnitArmored
local GetUnitCmdDescs = Spring.GetUnitCmdDescs
-- constants
local ARMOUR_DEF = 0.2
local ARMOUR_ASS = 1.3
-----setup speedstealth command
-----The List of units who can change their stance. (units that get this gadget)
local STEALTHY = {
[UnitDefNames["armcv"].id] = true,
[UnitDefNames["corak"].id] = true,
[UnitDefNames["armpw"].id] = true,
[UnitDefNames["armwar"].id] = true,
[UnitDefNames["armrock"].id] = true,
[UnitDefNames["corstorm"].id] = true,
[UnitDefNames["corthud"].id] = true,
[UnitDefNames["armzeus"].id] = true,
[UnitDefNames["cornecro"].id] = true,
[UnitDefNames["corpyro"].id] = true,
[UnitDefNames["armsnipe"].id] = true,
[UnitDefNames["cormort"].id] = true,
}
local stealthyList = {}
local CMD_SPEEDSTEALTH = 34583
---- Create the button
local speedstealthCmdDesc = {
id = CMD_SPEEDSTEALTH,
name = "togglespeedstealth",
action = "togglespeedstealth",
type = CMDTYPE.ICON_MODE,
tooltip = 'Toggle between Defensive, Assault and Sprint.',
params = {1, "slow", "normal", "fast"}
}
---- Insert the button on the units who get it
function gadget:UnitCreated(unitID, unitDefID, teamID, builderID)
if STEALTHY[unitDefID] then
InsertUnitCmdDesc(unitID, 502, speedstealthCmdDesc)
local ms = UnitDefs[unitDefID].speed
stealthyList[unitID] = {orgspeed=ms}
end
end
---- Remove the button when a unit dies (as it is no longer needed)
function gadget:UnitDestroyed(unitID, unitDefID, unitTeam)
stealthyList[unitID] = nil
end
-----------enable the command
function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
if STEALTHY[unitDefID] then
if cmdID == CMD_SPEEDSTEALTH then
local cmdDescID = FindUnitCmdDesc(unitID, CMD_SPEEDSTEALTH)
--Spring.Echo("cmdparams[1]=" .. tostring(cmdParams[1]))
if not cmdDescID then return false end
if cmdParams[1] == 1 then --Assault stance
--units decloak range to 250
SetUnitCloak(unitID, true, 250)
--unit receives normal damage as in unitdef
SetUnitArmored(unitID, false)
--unit moves at normal speed as in unitdef
SetGroundMoveTypeData(unitID, {
maxSpeed=stealthyList[unitID].orgspeed * 1})
elseif
cmdParams[1] == 2 then --Sprint stance
--set units decloak range to 750
SetUnitCloak(unitID, true, 750)
--multiply damage received by ARMOUR_ASS amount (defined above)
SetUnitArmored(unitID, true, ARMOUR_ASS)
--unit moves at 1.6x unitdef speed
SetGroundMoveTypeData(unitID, {maxSpeed=stealthyList[unitID].orgspeed * 1.6 })
elseif
cmdParams[1] == 0 then -- Defensive stance
--set units decloak range to 125
SetUnitCloak(unitID, true, 125)
--multiply damage received by ARMOUR_DEF amount (defined above)
SetUnitArmored(unitID, true, ARMOUR_DEF)
--unit moves at 1/3 unitdef speed
SetGroundMoveTypeData(unitID, {maxSpeed=stealthyList[unitID].orgspeed / 3 })
end
--you can't edit a single value in the params table for
--editUnitCmdDesc, so we generate a new table
local updatedCmdParams = {
cmdParams[1],
speedstealthCmdDesc.params[2],
speedstealthCmdDesc.params[3],
speedstealthCmdDesc.params[4]
}
Spring.EditUnitCmdDesc(unitID, cmdDescID, { params = updatedCmdParams})
return false
end
return true
end
end
| gpl-2.0 |
sandeepthota/CydoPhenia | Training.lua | 1 | 1262 | require 'torch'
require 'nn'
require 'optim'
require 'LanguageModel'
require 'util.DataLoader'
local utils = require 'util.utils'
local unpack = unpack or table.unpack
local cmd = torch.CmdLine()
-- Dataset options
cmd:option('-input_h5', 'data/tiny-shakespeare.h5')
cmd:option('-input_json', 'data/tiny-shakespeare.json')
cmd:option('-batch_size', 50)
cmd:option('-seq_length', 50)
-- Output options
cmd:option('-print_every', 1)
cmd:option('-checkpoint_every', 1000)
cmd:option('-checkpoint_name', 'cv/checkpoint')
-- Set up GPU stuff
local dtype = 'torch.FloatTensor'
if opt.gpu >= 0 and opt.gpu_backend == 'cuda' then
require 'cutorch'
require 'cunn'
cutorch.setDevice(opt.gpu + 1)
dtype = 'torch.CudaTensor'
print(string.format('Running with CUDA on GPU %d', opt.gpu))
elseif opt.gpu >= 0 and opt.gpu_backend == 'opencl' then
-- Memory benchmarking is only supported in CUDA mode
-- TODO: Time benchmarking is probably wrong in OpenCL mode.
require 'cltorch'
require 'clnn'
cltorch.setDevice(opt.gpu + 1)
dtype = torch.Tensor():cl():type()
print(string.format('Running with OpenCL on GPU %d', opt.gpu))
else
-- Memory benchmarking is only supported in CUDA mode
opt.memory_benchmark = 0
print 'Running in CPU mode'
end
| mit |
rollasoul/HaikuDenseCap | test/evaluation_test.lua | 4 | 2353 |
local eval_utils = require 'eval.eval_utils'
local utils = require 'densecap.utils'
local tests = torch.TestSuite()
local tester = torch.Tester()
function tests.sanityCheckTest()
local records = {}
table.insert(records, {references={'an example ref', 'another ref', 'and one more'}, candidate='one words matches'})
table.insert(records, {references={'some sentence', 'one more for fun'}, candidate='nothing matches'})
table.insert(records, {references={'expecting perfect match', 'garbage sent', 'bleh one more'}, candidate='expecting perfect match'})
local blob = eval_utils.score_captions(records)
local scores = blob.scores
tester:asserteq(#scores, 3)
tester:assertgt(scores[1], 0.0)
tester:assertlt(scores[1], 1.0)
tester:asserteq(scores[2], 0, 'nothing should match')
tester:asserteq(scores[3], 1.0, 'exact match expected')
tester:assertgt(blob.average_score, 0.0, 'average score between 0 and 1')
tester:assertlt(blob.average_score, 1.0, 'average score between 0 and 1')
end
function tests.evaluatorTest()
-- run short test on DenseCapEvaluator to make sure it doesn't crash or something
local evaluator = DenseCaptioningEvaluator()
local B = 10
local M = 5
local logprobs = torch.randn(B,2)
local boxes = torch.rand(B,4)
local text = {"hello there", "how are you", "this is a string",
"this string is a bit longer", "short one", "another prediction",
"this is the 7th item", "here is an item", "one more", "last prediction"}
local target_boxes = torch.rand(M,4)
local target_text = {"one ground truth", "another one", "short", "fourth gt", "how are you"}
-- add to evaluator
evaluator:addResult(logprobs, boxes, text, target_boxes, target_text)
local B = 7
local M = 4
local logprobs = torch.randn(B,2)
local boxes = torch.rand(B,4)
local text = {"hello there number two", "how are you", "this is a string",
"this string is a bit longer", "short one", "another prediction",
"this is the 7th item lol"}
local target_boxes = torch.rand(M,4)
local target_text = {"one ground truth", "one two three", "short", "fourth gt"}
-- add again evaluator
evaluator:addResult(logprobs, boxes, text, target_boxes, target_text)
local results = evaluator:evaluate()
print(results)
end
tester:add(tests)
tester:run()
| mit |
lxl1140989/dmsdk | feeds/luci/applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-app.lua | 137 | 15546 | cbimap = Map("asterisk", "asterisk", "")
module = cbimap:section(TypedSection, "module", "Modules", "")
module.anonymous = true
app_alarmreceiver = module:option(ListValue, "app_alarmreceiver", "Alarm Receiver Application", "")
app_alarmreceiver:value("yes", "Load")
app_alarmreceiver:value("no", "Do Not Load")
app_alarmreceiver:value("auto", "Load as Required")
app_alarmreceiver.rmempty = true
app_authenticate = module:option(ListValue, "app_authenticate", "Authentication Application", "")
app_authenticate:value("yes", "Load")
app_authenticate:value("no", "Do Not Load")
app_authenticate:value("auto", "Load as Required")
app_authenticate.rmempty = true
app_cdr = module:option(ListValue, "app_cdr", "Make sure asterisk doesnt save CDR", "")
app_cdr:value("yes", "Load")
app_cdr:value("no", "Do Not Load")
app_cdr:value("auto", "Load as Required")
app_cdr.rmempty = true
app_chanisavail = module:option(ListValue, "app_chanisavail", "Check if channel is available", "")
app_chanisavail:value("yes", "Load")
app_chanisavail:value("no", "Do Not Load")
app_chanisavail:value("auto", "Load as Required")
app_chanisavail.rmempty = true
app_chanspy = module:option(ListValue, "app_chanspy", "Listen in on any channel", "")
app_chanspy:value("yes", "Load")
app_chanspy:value("no", "Do Not Load")
app_chanspy:value("auto", "Load as Required")
app_chanspy.rmempty = true
app_controlplayback = module:option(ListValue, "app_controlplayback", "Control Playback Application", "")
app_controlplayback:value("yes", "Load")
app_controlplayback:value("no", "Do Not Load")
app_controlplayback:value("auto", "Load as Required")
app_controlplayback.rmempty = true
app_cut = module:option(ListValue, "app_cut", "Cuts up variables", "")
app_cut:value("yes", "Load")
app_cut:value("no", "Do Not Load")
app_cut:value("auto", "Load as Required")
app_cut.rmempty = true
app_db = module:option(ListValue, "app_db", "Database access functions", "")
app_db:value("yes", "Load")
app_db:value("no", "Do Not Load")
app_db:value("auto", "Load as Required")
app_db.rmempty = true
app_dial = module:option(ListValue, "app_dial", "Dialing Application", "")
app_dial:value("yes", "Load")
app_dial:value("no", "Do Not Load")
app_dial:value("auto", "Load as Required")
app_dial.rmempty = true
app_dictate = module:option(ListValue, "app_dictate", "Virtual Dictation Machine Application", "")
app_dictate:value("yes", "Load")
app_dictate:value("no", "Do Not Load")
app_dictate:value("auto", "Load as Required")
app_dictate.rmempty = true
app_directed_pickup = module:option(ListValue, "app_directed_pickup", "Directed Call Pickup Support", "")
app_directed_pickup:value("yes", "Load")
app_directed_pickup:value("no", "Do Not Load")
app_directed_pickup:value("auto", "Load as Required")
app_directed_pickup.rmempty = true
app_directory = module:option(ListValue, "app_directory", "Extension Directory", "")
app_directory:value("yes", "Load")
app_directory:value("no", "Do Not Load")
app_directory:value("auto", "Load as Required")
app_directory.rmempty = true
app_disa = module:option(ListValue, "app_disa", "DISA (Direct Inward System Access) Application", "")
app_disa:value("yes", "Load")
app_disa:value("no", "Do Not Load")
app_disa:value("auto", "Load as Required")
app_disa.rmempty = true
app_dumpchan = module:option(ListValue, "app_dumpchan", "Dump channel variables Application", "")
app_dumpchan:value("yes", "Load")
app_dumpchan:value("no", "Do Not Load")
app_dumpchan:value("auto", "Load as Required")
app_dumpchan.rmempty = true
app_echo = module:option(ListValue, "app_echo", "Simple Echo Application", "")
app_echo:value("yes", "Load")
app_echo:value("no", "Do Not Load")
app_echo:value("auto", "Load as Required")
app_echo.rmempty = true
app_enumlookup = module:option(ListValue, "app_enumlookup", "ENUM Lookup", "")
app_enumlookup:value("yes", "Load")
app_enumlookup:value("no", "Do Not Load")
app_enumlookup:value("auto", "Load as Required")
app_enumlookup.rmempty = true
app_eval = module:option(ListValue, "app_eval", "Reevaluates strings", "")
app_eval:value("yes", "Load")
app_eval:value("no", "Do Not Load")
app_eval:value("auto", "Load as Required")
app_eval.rmempty = true
app_exec = module:option(ListValue, "app_exec", "Executes applications", "")
app_exec:value("yes", "Load")
app_exec:value("no", "Do Not Load")
app_exec:value("auto", "Load as Required")
app_exec.rmempty = true
app_externalivr = module:option(ListValue, "app_externalivr", "External IVR application interface", "")
app_externalivr:value("yes", "Load")
app_externalivr:value("no", "Do Not Load")
app_externalivr:value("auto", "Load as Required")
app_externalivr.rmempty = true
app_forkcdr = module:option(ListValue, "app_forkcdr", "Fork The CDR into 2 seperate entities", "")
app_forkcdr:value("yes", "Load")
app_forkcdr:value("no", "Do Not Load")
app_forkcdr:value("auto", "Load as Required")
app_forkcdr.rmempty = true
app_getcpeid = module:option(ListValue, "app_getcpeid", "Get ADSI CPE ID", "")
app_getcpeid:value("yes", "Load")
app_getcpeid:value("no", "Do Not Load")
app_getcpeid:value("auto", "Load as Required")
app_getcpeid.rmempty = true
app_groupcount = module:option(ListValue, "app_groupcount", "Group Management Routines", "")
app_groupcount:value("yes", "Load")
app_groupcount:value("no", "Do Not Load")
app_groupcount:value("auto", "Load as Required")
app_groupcount.rmempty = true
app_ices = module:option(ListValue, "app_ices", "Encode and Stream via icecast and ices", "")
app_ices:value("yes", "Load")
app_ices:value("no", "Do Not Load")
app_ices:value("auto", "Load as Required")
app_ices.rmempty = true
app_image = module:option(ListValue, "app_image", "Image Transmission Application", "")
app_image:value("yes", "Load")
app_image:value("no", "Do Not Load")
app_image:value("auto", "Load as Required")
app_image.rmempty = true
app_lookupblacklist = module:option(ListValue, "app_lookupblacklist", "Look up Caller*ID name/number from black", "")
app_lookupblacklist:value("yes", "Load")
app_lookupblacklist:value("no", "Do Not Load")
app_lookupblacklist:value("auto", "Load as Required")
app_lookupblacklist.rmempty = true
app_lookupcidname = module:option(ListValue, "app_lookupcidname", "Look up CallerID Name from local databas", "")
app_lookupcidname:value("yes", "Load")
app_lookupcidname:value("no", "Do Not Load")
app_lookupcidname:value("auto", "Load as Required")
app_lookupcidname.rmempty = true
app_macro = module:option(ListValue, "app_macro", "Extension Macros", "")
app_macro:value("yes", "Load")
app_macro:value("no", "Do Not Load")
app_macro:value("auto", "Load as Required")
app_macro.rmempty = true
app_math = module:option(ListValue, "app_math", "A simple math Application", "")
app_math:value("yes", "Load")
app_math:value("no", "Do Not Load")
app_math:value("auto", "Load as Required")
app_math.rmempty = true
app_md5 = module:option(ListValue, "app_md5", "MD5 checksum Application", "")
app_md5:value("yes", "Load")
app_md5:value("no", "Do Not Load")
app_md5:value("auto", "Load as Required")
app_md5.rmempty = true
app_milliwatt = module:option(ListValue, "app_milliwatt", "Digital Milliwatt (mu-law) Test Application", "")
app_milliwatt:value("yes", "Load")
app_milliwatt:value("no", "Do Not Load")
app_milliwatt:value("auto", "Load as Required")
app_milliwatt.rmempty = true
app_mixmonitor = module:option(ListValue, "app_mixmonitor", "Record a call and mix the audio during the recording", "")
app_mixmonitor:value("yes", "Load")
app_mixmonitor:value("no", "Do Not Load")
app_mixmonitor:value("auto", "Load as Required")
app_mixmonitor.rmempty = true
app_parkandannounce = module:option(ListValue, "app_parkandannounce", "Call Parking and Announce Application", "")
app_parkandannounce:value("yes", "Load")
app_parkandannounce:value("no", "Do Not Load")
app_parkandannounce:value("auto", "Load as Required")
app_parkandannounce.rmempty = true
app_playback = module:option(ListValue, "app_playback", "Trivial Playback Application", "")
app_playback:value("yes", "Load")
app_playback:value("no", "Do Not Load")
app_playback:value("auto", "Load as Required")
app_playback.rmempty = true
app_privacy = module:option(ListValue, "app_privacy", "Require phone number to be entered", "")
app_privacy:value("yes", "Load")
app_privacy:value("no", "Do Not Load")
app_privacy:value("auto", "Load as Required")
app_privacy.rmempty = true
app_queue = module:option(ListValue, "app_queue", "True Call Queueing", "")
app_queue:value("yes", "Load")
app_queue:value("no", "Do Not Load")
app_queue:value("auto", "Load as Required")
app_queue.rmempty = true
app_random = module:option(ListValue, "app_random", "Random goto", "")
app_random:value("yes", "Load")
app_random:value("no", "Do Not Load")
app_random:value("auto", "Load as Required")
app_random.rmempty = true
app_read = module:option(ListValue, "app_read", "Read Variable Application", "")
app_read:value("yes", "Load")
app_read:value("no", "Do Not Load")
app_read:value("auto", "Load as Required")
app_read.rmempty = true
app_readfile = module:option(ListValue, "app_readfile", "Read in a file", "")
app_readfile:value("yes", "Load")
app_readfile:value("no", "Do Not Load")
app_readfile:value("auto", "Load as Required")
app_readfile.rmempty = true
app_realtime = module:option(ListValue, "app_realtime", "Realtime Data Lookup/Rewrite", "")
app_realtime:value("yes", "Load")
app_realtime:value("no", "Do Not Load")
app_realtime:value("auto", "Load as Required")
app_realtime.rmempty = true
app_record = module:option(ListValue, "app_record", "Trivial Record Application", "")
app_record:value("yes", "Load")
app_record:value("no", "Do Not Load")
app_record:value("auto", "Load as Required")
app_record.rmempty = true
app_sayunixtime = module:option(ListValue, "app_sayunixtime", "Say time", "")
app_sayunixtime:value("yes", "Load")
app_sayunixtime:value("no", "Do Not Load")
app_sayunixtime:value("auto", "Load as Required")
app_sayunixtime.rmempty = true
app_senddtmf = module:option(ListValue, "app_senddtmf", "Send DTMF digits Application", "")
app_senddtmf:value("yes", "Load")
app_senddtmf:value("no", "Do Not Load")
app_senddtmf:value("auto", "Load as Required")
app_senddtmf.rmempty = true
app_sendtext = module:option(ListValue, "app_sendtext", "Send Text Applications", "")
app_sendtext:value("yes", "Load")
app_sendtext:value("no", "Do Not Load")
app_sendtext:value("auto", "Load as Required")
app_sendtext.rmempty = true
app_setcallerid = module:option(ListValue, "app_setcallerid", "Set CallerID Application", "")
app_setcallerid:value("yes", "Load")
app_setcallerid:value("no", "Do Not Load")
app_setcallerid:value("auto", "Load as Required")
app_setcallerid.rmempty = true
app_setcdruserfield = module:option(ListValue, "app_setcdruserfield", "CDR user field apps", "")
app_setcdruserfield:value("yes", "Load")
app_setcdruserfield:value("no", "Do Not Load")
app_setcdruserfield:value("auto", "Load as Required")
app_setcdruserfield.rmempty = true
app_setcidname = module:option(ListValue, "app_setcidname", "load => .so ; Set CallerID Name", "")
app_setcidname:value("yes", "Load")
app_setcidname:value("no", "Do Not Load")
app_setcidname:value("auto", "Load as Required")
app_setcidname.rmempty = true
app_setcidnum = module:option(ListValue, "app_setcidnum", "load => .so ; Set CallerID Number", "")
app_setcidnum:value("yes", "Load")
app_setcidnum:value("no", "Do Not Load")
app_setcidnum:value("auto", "Load as Required")
app_setcidnum.rmempty = true
app_setrdnis = module:option(ListValue, "app_setrdnis", "Set RDNIS Number", "")
app_setrdnis:value("yes", "Load")
app_setrdnis:value("no", "Do Not Load")
app_setrdnis:value("auto", "Load as Required")
app_setrdnis.rmempty = true
app_settransfercapability = module:option(ListValue, "app_settransfercapability", "Set ISDN Transfer Capability", "")
app_settransfercapability:value("yes", "Load")
app_settransfercapability:value("no", "Do Not Load")
app_settransfercapability:value("auto", "Load as Required")
app_settransfercapability.rmempty = true
app_sms = module:option(ListValue, "app_sms", "SMS/PSTN handler", "")
app_sms:value("yes", "Load")
app_sms:value("no", "Do Not Load")
app_sms:value("auto", "Load as Required")
app_sms.rmempty = true
app_softhangup = module:option(ListValue, "app_softhangup", "Hangs up the requested channel", "")
app_softhangup:value("yes", "Load")
app_softhangup:value("no", "Do Not Load")
app_softhangup:value("auto", "Load as Required")
app_softhangup.rmempty = true
app_stack = module:option(ListValue, "app_stack", "Stack Routines", "")
app_stack:value("yes", "Load")
app_stack:value("no", "Do Not Load")
app_stack:value("auto", "Load as Required")
app_stack.rmempty = true
app_system = module:option(ListValue, "app_system", "Generic System() application", "")
app_system:value("yes", "Load")
app_system:value("no", "Do Not Load")
app_system:value("auto", "Load as Required")
app_system.rmempty = true
app_talkdetect = module:option(ListValue, "app_talkdetect", "Playback with Talk Detection", "")
app_talkdetect:value("yes", "Load")
app_talkdetect:value("no", "Do Not Load")
app_talkdetect:value("auto", "Load as Required")
app_talkdetect.rmempty = true
app_test = module:option(ListValue, "app_test", "Interface Test Application", "")
app_test:value("yes", "Load")
app_test:value("no", "Do Not Load")
app_test:value("auto", "Load as Required")
app_test.rmempty = true
app_transfer = module:option(ListValue, "app_transfer", "Transfer", "")
app_transfer:value("yes", "Load")
app_transfer:value("no", "Do Not Load")
app_transfer:value("auto", "Load as Required")
app_transfer.rmempty = true
app_txtcidname = module:option(ListValue, "app_txtcidname", "TXTCIDName", "")
app_txtcidname:value("yes", "Load")
app_txtcidname:value("no", "Do Not Load")
app_txtcidname:value("auto", "Load as Required")
app_txtcidname.rmempty = true
app_url = module:option(ListValue, "app_url", "Send URL Applications", "")
app_url:value("yes", "Load")
app_url:value("no", "Do Not Load")
app_url:value("auto", "Load as Required")
app_url.rmempty = true
app_userevent = module:option(ListValue, "app_userevent", "Custom User Event Application", "")
app_userevent:value("yes", "Load")
app_userevent:value("no", "Do Not Load")
app_userevent:value("auto", "Load as Required")
app_userevent.rmempty = true
app_verbose = module:option(ListValue, "app_verbose", "Send verbose output", "")
app_verbose:value("yes", "Load")
app_verbose:value("no", "Do Not Load")
app_verbose:value("auto", "Load as Required")
app_verbose.rmempty = true
app_voicemail = module:option(ListValue, "app_voicemail", "Voicemail", "")
app_voicemail:value("yes", "Load")
app_voicemail:value("no", "Do Not Load")
app_voicemail:value("auto", "Load as Required")
app_voicemail.rmempty = true
app_waitforring = module:option(ListValue, "app_waitforring", "Waits until first ring after time", "")
app_waitforring:value("yes", "Load")
app_waitforring:value("no", "Do Not Load")
app_waitforring:value("auto", "Load as Required")
app_waitforring.rmempty = true
app_waitforsilence = module:option(ListValue, "app_waitforsilence", "Wait For Silence Application", "")
app_waitforsilence:value("yes", "Load")
app_waitforsilence:value("no", "Do Not Load")
app_waitforsilence:value("auto", "Load as Required")
app_waitforsilence.rmempty = true
app_while = module:option(ListValue, "app_while", "While Loops and Conditional Execution", "")
app_while:value("yes", "Load")
app_while:value("no", "Do Not Load")
app_while:value("auto", "Load as Required")
app_while.rmempty = true
return cbimap
| gpl-2.0 |
LanceJenkinZA/prosody-modules | mod_manifesto/mod_manifesto.lua | 32 | 6828 | -- mod_manifesto
local timer = require "util.timer";
local jid_split = require "util.jid".split;
local st = require "util.stanza";
local dm = require "util.datamanager";
local dataforms_new = require "util.dataforms".new;
local adhoc_initial = require "util.adhoc".new_initial_data_form;
local mm_reload = require "modulemanager".reload;
local s2s_destroy_session = require "core.s2smanager".destroy_session;
local config = require "core.configmanager";
local config_get = config.get;
local config_set = config.set;
local t_concat = table.concat;
local adhoc_new = module:require "adhoc".new;
local time = os.time;
local hosts = prosody.hosts;
local host = module.host;
local host_session = hosts[host];
local incoming_s2s = prosody.incoming_s2s;
local s2s_sessions = module:shared"/*/s2s/sessions";
local default_tpl = [[
Hello there.
This is a brief system message to let you know about some upcoming changes to the $HOST service.
Some of your contacts are on other Jabber/XMPP services that do not support encryption. As part of an initiative to increase the security of the Jabber/XMPP network, this service ($HOST) will be participating in a series of tests to discover the impact of our planned changes, and you may lose the ability to communicate with some of your contacts.
The test days will be on the following dates: January 4, February 22, March 22 and April 19. On these days we will require that all client and server connections are encrypted. Unless they enable encryption before that, you will be unable to communicate with your contacts that use these services:
$SERVICES
Your affected contacts are:
$CONTACTS
What can you do? You may tell your contacts to inform their service administrator about their lack of encryption. Your contacts may also switch to a more secure service. A list of public services can be found at https://xmpp.net/directory.php
For more information about the Jabber/XMPP security initiative that we are participating in, please read the announcement at https://stpeter.im/journal/1496.html
If you have any questions or concerns, you may contact us via $CONTACTVIA at $CONTACT
]];
local message = module:get_option_string("manifesto_contact_encryption_warning", default_tpl);
local contact = module:get_option_string("admin_contact_address", module:get_option_array("admins", {})[1]);
if not contact then
error("mod_manifesto needs you to set 'admin_contact_address' in your config file.", 0);
end
local contact_method = "Jabber/XMPP";
if select(2, contact:gsub("^mailto:", "")) > 0 then
contact_method = "email";
end
local notified;
module:hook("resource-bind", function (event)
local session = event.session;
local now = time();
local last_notify = notified[session.username] or 0;
if last_notify > ( now - 86400 * 7 ) then
return
end
timer.add_task(15, function ()
if session.type ~= "c2s" then return end -- user quit already
local bad_contacts, bad_hosts = {}, {};
for contact_jid, item in pairs(session.roster or {}) do
local _, contact_host = jid_split(contact_jid);
local bad = false;
local remote_host_session = host_session.s2sout[contact_host];
if remote_host_session and remote_host_session.type == "s2sout" then -- Only check remote hosts we have completed s2s connections to
if not remote_host_session.secure then
bad = true;
end
end
for session in pairs(incoming_s2s) do
if session.to_host == host and session.from_host == contact_host and session.type == "s2sin" then
if not session.secure then
bad = true;
end
end
end
if bad then
local contact_name = item.name;
if contact_name then
table.insert(bad_contacts, contact_name.." <"..contact_jid..">");
else
table.insert(bad_contacts, contact_jid);
end
if not bad_hosts[contact_host] then
bad_hosts[contact_host] = true;
table.insert(bad_hosts, contact_host);
end
end
end
if #bad_contacts > 0 then
local vars = {
HOST = host;
CONTACTS = " "..table.concat(bad_contacts, "\n ");
SERVICES = " "..table.concat(bad_hosts, "\n ");
CONTACTVIA = contact_method, CONTACT = contact;
};
session.send(st.message({ type = "headline", from = host }):tag("body"):text(message:gsub("$(%w+)", vars)));
notified[session.username] = now;
end
end);
end);
function module.load()
notified = dm.load(nil, host, module.name) or {};
end
function module.save()
dm.store(nil, host, module.name, notified);
return { notified = notified };
end
function module.restore(data)
notified = data.notified;
end
function module.unload()
dm.store(nil, host, module.name, notified);
end
function module.uninstall()
dm.store(nil, host, module.name, nil);
end
-- Ad-hoc command for switching to/from "manifesto mode"
local layout = dataforms_new {
title = "Configure manifesto mode";
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/manifesto" };
{ name = "state", type = "list-single", required = true, label = "Manifesto mode:"};
};
local adhoc_handler = adhoc_initial(layout, function()
local enabled = config_get(host, "c2s_require_encryption") and config_get(host, "s2s_require_encryption");
return { state = {
{ label = "Enabled", value = "enabled", default = enabled },
{ label = "Configuration settings", value = "config", default = not enabled },
}};
end, function(fields, err)
if err then
local errmsg = {};
for name, err in pairs(errors) do
errmsg[#errmsg + 1] = name .. ": " .. err;
end
return { status = "completed", error = { message = t_concat(errmsg, "\n") } };
end
local info;
if fields.state == "enabled" then
config_set(host, "c2s_require_encryption", true);
config_set(host, "s2s_require_encryption", true);
for _, session in pairs(s2s_sessions) do
if not session.secure then
(session.close or s2s_destroy_session)(session);
end
end
info = "Manifesto mode enabled";
else
local ok, err = prosody.reload_config();
if not ok then
return { status = "completed", error = { message = "Failed to reload config: " .. tostring(err) } };
end
info = "Reset to configuration settings";
end
local ok, err = mm_reload(host, "tls");
if not ok then return { status = "completed", error = { message = "Failed to reload mod_tls: " .. tostring(err) } }; end
ok, err = mm_reload(host, "s2s");
if not ok then return { status = "completed", error = { message = "Failed to reload mod_s2s: " .. tostring(err) } }; end
ok, err = mm_reload(host, "saslauth");
if not ok then return { status = "completed", error = { message = "Failed to reload mod_saslauth: " .. tostring(err) } }; end
return { status = "completed", info = info };
end);
module:provides("adhoc", adhoc_new("Configure manifesto mode", "http://prosody.im/protocol/manifesto", adhoc_handler, "admin"));
| mit |
LORgames/premake-core | modules/gmake/gmake_utility.lua | 15 | 1409 | --
-- make_utility.lua
-- Generate a C/C++ project makefile.
-- Copyright (c) 2002-2014 Jason Perkins and the Premake project
--
local p = premake
p.make.utility = {}
local make = p.make
local utility = p.make.utility
local project = p.project
local config = p.config
local fileconfig = p.fileconfig
---
-- Add namespace for element definition lists for p.callarray()
---
utility.elements = {}
--
-- Generate a GNU make utility project makefile.
--
utility.elements.makefile = {
"header",
"phonyRules",
"utilityConfigs",
"utilityTargetRules"
}
function make.utility.generate(prj)
p.eol("\n")
p.callarray(make, utility.elements.makefile, prj)
end
utility.elements.configuration = {
"target",
"preBuildCmds",
"postBuildCmds",
}
function make.utilityConfigs(prj)
for cfg in project.eachconfig(prj) do
-- identify the toolset used by this configurations (would be nicer if
-- this were computed and stored with the configuration up front)
local toolset = p.tools[cfg.toolset or "gcc"]
if not toolset then
error("Invalid toolset '" .. cfg.toolset .. "'")
end
_x('ifeq ($(config),%s)', cfg.shortname)
p.callarray(make, utility.elements.configuration, cfg, toolset)
_p('endif')
_p('')
end
end
function make.utilityTargetRules(prj)
_p('$(TARGET):')
_p('\t$(PREBUILDCMDS)')
_p('\t$(POSTBUILDCMDS)')
_p('')
end
| bsd-3-clause |
LightenPan/skynet-yule | datacenter/mysqlpool.lua | 1 | 1322 | local skynet = require "skynet"
local mysql = require "mysql"
local snax = require "snax"
local pool = {}
local maxconn
local index = 2
local function getconn(sync)
local db
if sync then
db = pool[1]
else
db = pool[index]
assert(db)
index = index + 1
if index > maxconn then
index = 2
end
end
return db
end
function response.start()
maxconn = tonumber(skynet.getenv("mysql_maxconn")) or 10
assert(maxconn >= 2)
for i = 1, maxconn do
local db = mysql.connect{
host = skynet.getenv("mysql_host"),
port = tonumber(skynet.getenv("mysql_port")),
database = skynet.getenv("mysql_db"),
user = skynet.getenv("mysql_user"),
password = skynet.getenv("mysql_pwd"),
max_packet_size = 1024 * 1024
}
if db then
table.insert(pool, db)
db:query("set names utf8")
else
skynet.error("mysql connect error")
end
end
end
-- sync为false或者nil,sql为读操作,如果sync为true用于数据变动时同步数据到mysql,sql为写操作
-- 写操作取连接池中的第一个连接进行操作
function response.execute(sql, sync)
local db = getconn(sync)
return db:query(sql)
end
function response.stop()
for _, db in pairs(pool) do
db:disconnect()
end
pool = {}
end
function init( ... )
snax.enablecluster() -- enable cluster call
end
function exit(...)
end
| mit |
Anarchid/Zero-K | LuaRules/Configs/StartBoxes/Bryce_Arena_fixed_2.lua | 17 | 1187 | return {
[0] = {
startpoints = {
{2785,1270},
},
boxes = {
{
{2212,655},
{3359,655},
{3359,1884},
{2212,1884},
},
},
},
[1] = {
startpoints = {
{5530,6840},
},
boxes = {
{
{4915,6226},
{6144,6226},
{6144,7455},
{4915,7455},
},
},
},
[2] = {
startpoints = {
{5530,1270},
},
boxes = {
{
{4915,655},
{6144,655},
{6144,1884},
{4915,1884},
},
},
},
[3] = {
startpoints = {
{7127,2785},
},
boxes = {
{
{6554,2212},
{7700,2212},
{7700,3359},
{6554,3359},
},
},
},
[4] = {
startpoints = {
{1270,2785},
},
boxes = {
{
{655,2212},
{1884,2212},
{1884,3359},
{655,3359},
},
},
},
[5] = {
startpoints = {
{2785,6840},
},
boxes = {
{
{2212,6226},
{3359,6226},
{3359,7455},
{2212,7455},
},
},
},
[6] = {
startpoints = {
{1270,5202},
},
boxes = {
{
{655,4588},
{1884,4588},
{1884,5816},
{655,5816},
},
},
},
[7] = {
startpoints = {
{7127,5202},
},
boxes = {
{
{6554,4588},
{7700,4588},
{7700,5816},
{6554,5816},
},
},
},
}
| gpl-2.0 |
DarkJaguar91/DJUI | libs/LibStub/LibStub.lua | 4 | 1534 | -- LibStub is a simple versioning stub meant for use in Libraries. http://www.wowace.com/wiki/LibStub for more info
-- LibStub is hereby placed in the Public Domain Credits: Kaelten, Cladhaire, ckknight, Mikk, Ammo, Nevcairiel, joshborke
-- LibStub developed for World of Warcraft by above members of the WowAce community.
-- Ported to Elder Scrolls Online by Seerah
local LIBSTUB_MAJOR, LIBSTUB_MINOR = "LibStub", 2 -- NEVER MAKE THIS AN SVN REVISION! IT NEEDS TO BE USABLE IN ALL REPOS!
local LibStub = _G[LIBSTUB_MAJOR]
local strformat = string.format
if not LibStub or LibStub.minor < LIBSTUB_MINOR then
LibStub = LibStub or {libs = {}, minors = {} }
_G[LIBSTUB_MAJOR] = LibStub
LibStub.minor = LIBSTUB_MINOR
function LibStub:NewLibrary(major, minor)
assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)")
minor = assert(tonumber(zo_strmatch(minor, "%d+")), "Minor version must either be a number or contain a number.")
local oldminor = self.minors[major]
if oldminor and oldminor >= minor then return nil end
self.minors[major], self.libs[major] = minor, self.libs[major] or {}
return self.libs[major], oldminor
end
function LibStub:GetLibrary(major, silent)
if not self.libs[major] and not silent then
error(strformat("Cannot find a library instance of %q.", tostring(major)), 2)
end
return self.libs[major], self.minors[major]
end
function LibStub:IterateLibraries() return pairs(self.libs) end
setmetatable(LibStub, { __call = LibStub.GetLibrary })
end
| apache-2.0 |
sbates130272/likwid | src/applications/likwid-pin.lua | 10 | 7605 | #!<PREFIX>/bin/likwid-lua
--[[
* =======================================================================================
*
* Filename: likwid-pin.lua
*
* Description: An application to pin a program including threads
*
* Version: <VERSION>
* Released: <DATE>
*
* Author: Thomas Roehl (tr), thomas.roehl@gmail.com
* Project: likwid
*
* Copyright (C) 2014 Thomas Roehl
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =======================================================================================]]
package.path = package.path .. ';<PREFIX>/share/lua/?.lua'
local likwid = require("likwid")
local function version()
print(string.format("likwid-pin.lua -- Version %d.%d",likwid.version,likwid.release))
end
local function examples()
print("Examples:")
print("There are three possibilities to provide a thread to processor list:")
print("1. Thread list with physical or logical thread numberings and physical cores first.")
print("Example usage thread list: likwid-pin.lua -c N:0,4-6 ./myApp")
print("You can pin with the following numberings:")
print("\t1. Physical numbering of OS.")
print("\t2. Logical numbering inside node. e.g. -c N:0-3")
print("\t3. Logical numbering inside socket. e.g. -c S0:0-3")
print("\t4. Logical numbering inside last level cache group. e.g. -c C0:0-3")
print("\t5. Logical numbering inside NUMA domain. e.g. -c M0:0-3")
print("\tYou can also mix domains separated by @, e.g. -c S0:0-3@S1:0-3")
print("2. Expressions based thread list generation with compact processor numbering.")
print("Example usage expression: likwid-pin.lua -c E:N:8 ./myApp")
print("This will generate a compact list of thread to processor mapping for the node domain")
print("with eight threads.")
print("The following syntax variants are available:")
print("\t1. -c E:<thread domain>:<number of threads>")
print("\t2. -c E:<thread domain>:<number of threads>:<chunk size>:<stride>")
print("\tFor two SMT threads per core on a SMT 4 machine use e.g. -c E:N:122:2:4")
print("3. Scatter policy among thread domain type.")
print("Example usage scatter: likwid-pin.lua -c M:scatter ./myApp")
print("This will generate a thread to processor mapping scattered among all memory domains")
print("with physical cores first. If you ommit the -c option likwid will use all processors")
print("available on the node with physical cores first. likwid-pin will also set ")
print("OMP_NUM_THREADS with as many threads as specified in your pin expression if")
print("OMP_NUM_THREADS is not present in your environment.")
end
local function usage()
version()
print("A tool to print power and clocking information on x86 CPUs.\n")
print("Options:")
print("-h\t\t Help message")
print("-v\t\t Version information")
print("-i\t\t Set numa interleave policy with all involved numa nodes")
print("-S\t\t Sweep memory in involved NUMA nodes")
print("-c <list>\t Comma separated processor IDs or expression")
print("-s <hex-mask>\t Bitmask with threads to skip")
print("-p\t\t Print available domains with mapping on physical IDs")
print("\t\t If used together with -p option outputs a physical processor IDs.")
print("-d <string>\t Delimiter used for using -p to output physical processor list, default is comma.")
print("-q\t\t Silent without output")
print("\n")
examples()
end
delimiter = ','
quiet = 0
sweep_sockets = false
interleaved_policy = false
print_domains = false
cpu_list = {}
skip_mask = "0x0"
affinity = nil
num_threads = 0
config = likwid.getConfiguration()
cputopo = likwid.getCpuTopology()
affinity = likwid.getAffinityInfo()
if (#arg == 0) then
usage()
os.exit(0)
end
for opt,arg in likwid.getopt(arg, "c:d:hipqs:St:v") do
if (opt == "h") then
usage()
os.exit(0)
elseif (opt == "v") then
version()
os.exit(0)
elseif (opt == "c") then
if (affinity ~= nil) then
num_threads,cpu_list = likwid.cpustr_to_cpulist(arg)
else
num_threads,cpu_list = likwid.cpustr_to_cpulist_physical(arg)
end
if (num_threads == 0) then
print("Failed to parse cpulist " .. arg)
os.exit(1)
end
elseif (opt == "d") then
delimiter = arg
elseif (opt == "S") then
if (affinity == nil) then
print("Option -S is not supported for unknown processor!")
os.exit(1)
end
sweep_sockets = true
elseif (opt == "i") then
interleaved_policy = true
elseif (opt == "p") then
print_domains = true
elseif (opt == "s") then
local s,e = arg:find("0x")
if s == nil then
print("Skip mask must be given in hex, hence start with 0x")
os.exit(1)
end
skip_mask = arg
elseif (opt == "q") then
likwid.setenv("LIKWID_SILENT","true")
quiet = 1
else
print("Unknown option -" .. opt .. "\n")
usage()
os.exit(0)
end
end
if print_domains and num_threads > 0 then
outstr = ""
for i, cpu in pairs(cpu_list) do
outstr = outstr .. delimiter .. cpu
end
print(outstr:sub(2,outstr:len()))
elseif print_domains then
for k,v in pairs(affinity["domains"]) do
print(string.format("Domain %d Tag %s:",k, v["tag"]))
print("\t" .. table.concat(v["processorList"], ","))
print()
end
os.exit(0)
end
if num_threads == 0 then
num_threads, cpu_list = likwid.cpustr_to_cpulist("N:0-"..cputopo["numHWThreads"]-1)
end
if interleaved_policy then
print("Set mem_policy to interleaved")
likwid.setMemInterleaved(num_threads, cpu_list)
end
if sweep_sockets then
print("Sweeping memory")
likwid.memSweep(num_threads, cpu_list)
end
local omp_threads = os.getenv("OMP_NUM_THREADS")
if omp_threads == nil then
likwid.setenv("OMP_NUM_THREADS",tostring(num_threads))
end
if num_threads > 1 then
local preload = os.getenv("LD_PRELOAD")
local pinString = tostring(cpu_list[2])
for i=3,likwid.tablelength(cpu_list) do
pinString = pinString .. "," .. cpu_list[i]
end
pinString = pinString .. "," .. cpu_list[1]
skipString = skip_mask
likwid.setenv("KMP_AFFINITY","disabled")
likwid.setenv("LIKWID_PIN", pinString)
likwid.setenv("LIKWID_SKIP",skipString)
if preload == nil then
likwid.setenv("LD_PRELOAD",likwid.pinlibpath)
else
likwid.setenv("LD_PRELOAD",likwid.pinlibpath .. ":" .. preload)
end
end
likwid.pinProcess(cpu_list[1], quiet)
local exec = table.concat(arg," ",1, likwid.tablelength(arg)-2)
local err
err = os.execute(exec)
if (err == false) then
print("Failed to execute command: ".. exec)
os.exit(1)
end
likwid.putAffinityInfo()
likwid.putTopology()
likwid.putConfiguration()
os.exit(0)
| gpl-3.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/tld/armlab/cornecro.lua | 1 | 2414 | return {
cornecro = {
acceleration = 0.20000000298023,
brakerate = 0.25,
buildcostenergy = 0,
buildcostmetal = 100,
builddistance = 96,
builder = true,
buildpic = "CORNECRO.DDS",
buildtime = 1000,
canassist = true,
canmove = true,
cancapture = true,
canresurrect = true,
canCloak = true,
mincloakdistance = 250,
cloakCost = 0.0,
stealth = true,
initCloaked = true,
category = "KBOT MOBILE ALL NOTSUB NOWEAPON NOTSHIP NOTAIR NOTHOVER SURFACE a1",
corpse = "DEAD",
description = "Combat Engineer and Medic",
energymake = 0,
energyuse = 0,
explodeas = "BIG_UNITEX",
footprintx = 2,
footprintz = 2,
idleautoheal = 5,
idletime = 60,
maxdamage = 140,
maxslope = 14,
maxvelocity = 2,
maxwaterdepth = 22,
movementclass = "KBOT2",
name = "Combat Engineer",
objectname = "CORNECRO",
radardistance = 0,
seismicsignature = 0,
selfdestructas = "BIG_UNIT",
sightdistance = 900,
smoothanim = true,
terraformspeed = 1000,
turnrate = 1118,
upright = true,
workertime = 30,
buildoptions =
{
[1] = "armgate",
[2] = "armmine1",},
featuredefs = {
dead = {
blocking = true,
category = "corpses",
collisionvolumeoffsets = "0.248977661133 -1.21184884033 0.586555480957",
collisionvolumescales = "33.9485473633 23.5305023193 36.0355987549",
collisionvolumetype = "Box",
damage = 794,
description = "Necro Wreckage",
featuredead = "HEAP",
featurereclamate = "SMUDGE01",
footprintx = 2,
footprintz = 2,
height = 20,
hitdensity = 100,
metal = 72,
object = "CORNECRO_DEAD",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
heap = {
blocking = false,
category = "heaps",
damage = 794,
description = "Necro Heap",
featurereclamate = "SMUDGE01",
footprintx = 2,
footprintz = 2,
height = 4,
hitdensity = 100,
metal = 26,
object = "2X2D",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
},
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "necrok2",
},
select = {
[1] = "necrsel2",
},
},
},
}
| gpl-2.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/luaui/widgets/unit_auto_group.lua | 1 | 8777 | -- $Id$
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local versionNum = '2.22'
function widget:GetInfo()
return {
name = "Auto group",
desc = "v".. (versionNum) .." Alt+0-9 sets autogroup# for selected unit type(s). Newly built units get added to group# equal to their autogroup#. Type '/luaui autogroup help' for help.",
author = "Licho",
date = "Mar 23, 2007",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
include("keysym.h.lua")
---- CHANGELOG -----
-- very_bad_solider, v2.22:
-- -- Ignores buildings and factories
-- -- Does not react when META (+ALT) is pressed
-- CarRepairer, v2:
-- -- Autogroups key is alt instead of alt+ctrl.
-- -- Added commands: help, loadgroups, cleargroups, verboseMode, addall
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local finiGroup = {}
local unit2group = {}
local myTeam
local selUnitDefs = {}
local loadGroups = false
local verboseMode = true
local addAll = false
local createdFrame = {}
local helpText = {
'Alt+0-9 sets autogroup# for selected unit type(s). Newly built units get added to group# equal to their autogroup#.',
'Alt+\~ deletes autogrouping for selected unit type(s).',
'Ctrl+~ removes nearest selected unit from its group and selects it. ',
'/luaui autogroup cleargroups -- Clears your autogroupings.',
'/luaui autogroup loadgroups -- Toggles whether your groups are re-loaded for all future games.',
'/luaui autogroup verbose -- Toggle whether a notification is made when adding/removing autogroups.',
'/luaui autogroup addall -- Toggle whether existing units are added to group# when setting autogroup#.',
--'Extra function: Ctrl+q picks single nearest unit from current selection.',
}
-- speedups
local SetUnitGroup = Spring.SetUnitGroup
local GetSelectedUnits = Spring.GetSelectedUnits
local GetUnitDefID = Spring.GetUnitDefID
local Echo = Spring.Echo
local GetAllUnits = Spring.GetAllUnits
local GetUnitHealth = Spring.GetUnitHealth
local GetMouseState = Spring.GetMouseState
local GetUnitTeam = Spring.GetUnitTeam
local SelectUnitArray = Spring.SelectUnitArray
local TraceScreenRay = Spring.TraceScreenRay
local GetUnitPosition = Spring.GetUnitPosition
local UDefTab = UnitDefs
function widget:Initialize()
local _, _, spec, team = Spring.GetPlayerInfo(Spring.GetMyPlayerID())
if spec then
widgetHandler:RemoveWidget()
return false
end
myTeam = team
end
function widget:UnitFinished(unitID, unitDefID, unitTeam)
if (unitTeam == myTeam and unitID ~= nil) then
if (createdFrame[unitID] == Spring.GetGameFrame()) then
local gr = unit2group[unitDefID]
if gr ~= nil then SetUnitGroup(unitID, gr) end
else
finiGroup[unitID] = 1
end
end
end
function widget:UnitCreated(unitID, unitDefID, unitTeam, builderID)
if (unitTeam == myTeam) then
createdFrame[unitID] = Spring.GetGameFrame()
end
end
function widget:UnitDestroyed(unitID, unitDefID, teamID)
finiGroup[unitID] = nil
createdFrame[unitID] = nil
end
function widget:UnitGiven(unitID, unitDefID, newTeamID, teamID)
if (newTeamID == myTeam) then
local gr = unit2group[unitDefID]
if gr ~= nil then SetUnitGroup(unitID, gr) end
end
createdFrame[unitID] = nil
finiGroup[unitID] = nil
end
function widget:UnitTaken(unitID, unitDefID, oldTeamID, teamID)
if (teamID == myTeam) then
local gr = unit2group[unitDefID]
if gr ~= nil then SetUnitGroup(unitID, gr) end
end
createdFrame[unitID] = nil
finiGroup[unitID] = nil
end
function widget:UnitIdle(unitID, unitDefID, unitTeam)
if (unitTeam == myTeam and finiGroup[unitID]~=nil) then
local gr = unit2group[unitDefID]
if gr ~= nil then SetUnitGroup(unitID, gr) end
finiGroup[unitID] = nil
end
end
function widget:KeyPress(key, modifier, isRepeat)
if ( modifier.alt and not modifier.meta ) then
local gr
if (key == KEYSYMS.N_0) then gr = 0 end
if (key == KEYSYMS.N_1) then gr = 1 end
if (key == KEYSYMS.N_2) then gr = 2 end
if (key == KEYSYMS.N_3) then gr = 3 end
if (key == KEYSYMS.N_4) then gr = 4 end
if (key == KEYSYMS.N_5) then gr = 5 end
if (key == KEYSYMS.N_6) then gr = 6 end
if (key == KEYSYMS.N_7) then gr = 7 end
if (key == KEYSYMS.N_8) then gr = 8 end
if (key == KEYSYMS.N_9) then gr = 9 end
if (key == KEYSYMS.BACKQUOTE) then gr = -1 end
if (gr ~= nil) then
if (gr == -1) then gr = nil end
selUnitDefIDs = {}
local exec = false --set to true when there is at least one unit to process
for _, uid in ipairs(GetSelectedUnits()) do
local udid = GetUnitDefID(uid)
if ( not UDefTab[udid]["isFactory"] and not UDefTab[udid]["isBuilding"] ) then
selUnitDefIDs[udid] = true
unit2group[udid] = gr
exec = true
end
end
if ( exec == false ) then
return false --nothing to do
end
for udid,_ in pairs(selUnitDefIDs) do
if verboseMode then
if gr then
Echo('Added '.. UnitDefs[udid].humanName ..' to autogroup #'.. gr ..'.')
else
Echo('Removed '.. UnitDefs[udid].humanName ..' from autogroups.')
end
end
end
if addAll then
local allUnits = GetAllUnits()
for _, unitID in pairs(allUnits) do
local unitTeam = GetUnitTeam(unitID)
if unitTeam == myTeam then
local curUnitDefID = GetUnitDefID(unitID)
if selUnitDefIDs[curUnitDefID] then
if gr then
local _, _, _, _, buildProgress = GetUnitHealth(unitID)
if buildProgress == 1 then
SetUnitGroup(unitID, gr)
SelectUnitArray({unitID}, true)
end
else
SetUnitGroup(unitID, -1)
end
end
end
end
end
return true --key was processed by widget
end
elseif (modifier.ctrl and not modifier.meta) then
if (key == KEYSYMS.BACKQUOTE) then
local mx,my = GetMouseState()
local _,pos = TraceScreenRay(mx,my,true)
local mindist = math.huge
local muid = nil
if (pos == nil) then return end
for _, uid in ipairs(GetSelectedUnits()) do
local x,_,z = GetUnitPosition(uid)
dist = (pos[1]-x)*(pos[1]-x) + (pos[3]-z)*(pos[3]-z)
if (dist < mindist) then
mindist = dist
muid = uid
end
end
if (muid ~= nil) then
SetUnitGroup(muid,-1)
SelectUnitArray({muid})
end
end
--[[
if (key == KEYSYMS.Q) then
for _, uid in ipairs(GetSelectedUnits()) do
SetUnitGroup(uid,-1)
end
end
--]]
end
return false
end
function widget:GetConfigData()
local groups = {}
for id, gr in pairs(unit2group) do
table.insert(groups, {UnitDefs[id].name, gr})
end
local ret =
{
version = versionNum,
groups = groups,
loadGroups = loadGroups,
verboseMode = verboseMode,
addAll = addAll,
}
return ret
end
function widget:SetConfigData(data)
if (data and type(data) == 'table' and data.version and (data.version+0) > 2.1) then
loadGroups = data.loadGroups
verbose = data.verboseMode
addAll = data.addAll
local groupData = data.groups
if loadGroups and groupData and type(groupData) == 'table' then
for _, nam in ipairs(groupData) do
if type(nam) == 'table' then
local gr = UnitDefNames[nam[1]]
if (gr ~= nil) then
unit2group[gr.id] = nam[2]
end
end
end
end
else --older ver
--[[
if (data ~= nil) then
for _, nam in ipairs(data) do
local gr = UnitDefNames[nam[1] ]
if (gr ~= nil) then
unit2group[gr.id] = nam[2]
end
end
end
--]]
end
end
function widget:TextCommand(command)
if command == "autogroup loadgroups" then
loadGroups = not loadGroups
Echo('Autogroup: your autogroups will '.. (loadGroups and '' or 'NOT') ..' be preserved for future games')
return true
elseif command == "autogroup cleargroups" then
unit2group = {}
Echo('Autogroup: All autogroups cleared.')
return true
elseif command == "autogroup verbose" then
verboseMode = not verboseMode
Echo('Autogroup: verbose mode '.. (verboseMode and 'ON' or 'OFF') ..'.')
return true
elseif command == "autogroup addall" then
addAll = not addAll
Echo('Autogroup: Existing units will '.. (addAll and '' or 'NOT') ..' be added to group# when setting autogroup#.')
return true
elseif command == "autogroup help" then
for i, text in ipairs(helpText) do
Echo('['.. i ..'] Autogroup: '.. text)
end
return true
end
return false
end
--------------------------------------------------------------------------------
| gpl-2.0 |
Anarchid/Zero-K | units/shieldcon.lua | 3 | 2762 | return { shieldcon = {
unitname = [[shieldcon]],
name = [[Convict]],
description = [[Shielded Construction Bot]],
acceleration = 1.5,
activateWhenBuilt = true,
brakeRate = 1.8,
buildCostMetal = 120,
buildDistance = 128,
builder = true,
buildoptions = {
},
buildPic = [[shieldcon.png]],
canMove = true,
canPatrol = true,
category = [[LAND UNARMED]],
selectionVolumeOffsets = [[0 0 0]],
selectionVolumeScales = [[30 30 30]],
selectionVolumeType = [[ellipsoid]],
corpse = [[DEAD]],
customParams = {
shield_emit_height = 17,
},
explodeAs = [[BIG_UNITEX]],
footprintX = 2,
footprintZ = 2,
iconType = [[builder]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 780,
maxSlope = 36,
maxVelocity = 2.05,
maxWaterDepth = 22,
movementClass = [[KBOT2]],
objectName = [[conbot.s3o]],
onoffable = false,
script = [[shieldcon.lua]],
selfDestructAs = [[BIG_UNITEX]],
showNanoSpray = false,
sightDistance = 375,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 22,
turnRate = 2640,
upright = true,
workerTime = 5,
weapons = {
{
def = [[SHIELD]],
},
},
weaponDefs = {
SHIELD = {
name = [[Energy Shield]],
damage = {
default = 10,
},
exteriorShield = true,
shieldAlpha = 0.2,
shieldBadColor = [[1 0.1 0.1 1]],
shieldGoodColor = [[0.1 0.1 1 1]],
shieldInterceptType = 3,
shieldPower = 900,
shieldPowerRegen = 11,
shieldPowerRegenEnergy = 0,
shieldRadius = 80,
shieldRepulser = false,
shieldStartingPower = 900,
smartShield = true,
visibleShield = false,
visibleShieldRepulse = false,
weaponType = [[Shield]],
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[conbot_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2a.s3o]],
},
},
} }
| gpl-2.0 |
Anarchid/Zero-K | LuaRules/Gadgets/api_subdir_gadgets.lua | 7 | 1280 | -- $Id$
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- author: jK
--
-- Copyright (C) 2010.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local SCRIPT_DIR = Script.GetName() .. '/'
local GADGETS_DIR = SCRIPT_DIR .. 'Gadgets/'
local gh = gadgetHandler.gadgetHandler
--// export GADGET_DIR, so gadgets can easily load e.g. config.lua
--// from the same dir where the main.lua is placed
local oldNewGadget = gh.NewGadget
local curdir = ""
gh.NewGadget = function(self,dir)
local gadget = oldNewGadget(self)
gadget.GADGET_DIR = curdir
return gadget
end
--// load all Gadgets/*/main.lua gadgets
local subdirs = VFS.SubDirs(GADGETS_DIR)
for i=1,#subdirs do
curdir = subdirs[i]
local gf = curdir .. "main.lua"
if (VFS.FileExists(gf)) then
local g = gh:LoadGadget(gf)
if g then
gh:InsertGadget(g)
local name = g.ghInfo.name
print(string.format("Loaded gadget: %-18s <%s>", name, gf))
end
end
end
--// reset
gh.NewGadget = oldNewGadget
| gpl-2.0 |
ggcrunchy/Old-Love2D-Demo | Scripts/Class/Control/Interpolator.lua | 1 | 7452 | -- See TacoShell Copyright Notice in main folder of distribution
-- Standard library imports --
local assert = assert
local type = type
-- Imports --
local Identity = funcops.Identity
local New = class.New
-- Resume commands --
local Commands = table_ex.MakeSet{ "continue", "flip", "forward", "reverse" }
-- Unique member keys --
local _context = {}
local _interp = {}
local _is_decreasing = {}
local _map = {}
local _mode = {}
local _t = {}
local _target1 = {}
local _target2 = {}
local _timer = {}
-- Common body for mode logic
-- I: Interpolator handle
-- lapse: Timer lapse
-- is_done: If true, terminate
-- Returns: Interpolation time
local function Body (I, lapse, is_done)
local t
-- Disable interpolation if complete.
if is_done then
t = 1
I[_mode] = nil
-- Suspend the timer.
I[_timer]:SetPause(true)
-- Otherwise, update the time properties.
else
t = I[_timer]:GetCounter(true)
I[_timer]:Update(lapse)
end
-- Supply the time, flipping if decreasing.
return I[_is_decreasing] and 1 - t or t
end
-- Handles oscillation reversals
-- I: Interpolator handle
-- count: Timeout count
local function DoAnyFlip (I, count)
if count % 2 == 1 then
I[_is_decreasing] = not I[_is_decreasing]
end
end
-- Interpolation mode logic --
local Modes = {}
-- 0-to-1 and finish --
function Modes:once (lapse, count)
return Body(self, lapse, count > 0)
end
-- 0-to-1, 1-to-0, and repeat --
function Modes:oscillate (lapse, count)
DoAnyFlip(self, count)
return Body(self, lapse)
end
-- 0-to-1, 1-to-0, and finish --
function Modes:oscillate_once (lapse, count)
local is_decreasing = self[_is_decreasing]
DoAnyFlip(self, count)
return Body(self, lapse, (is_decreasing and 1 or 0) + count >= 2)
end
-- Current time --
function Modes:suspended ()
return self[_t]
end
-- Interpolator class definition --
class.Define("Interpolator", function(Interpolator)
-- Performs an interpolation
-- I: Interpolator handle
-- lapse: Time lapse
local function Interpolate (I, lapse)
-- Find the time in the current mode. This also updates the decreasing boolean.
I[_t] = Modes[I[_mode] or "suspended"](I, lapse, I[_timer]:Check("continue"))
-- If a mapping exists, apply it to the current time and use the new result.
local t = (I[_map] or Identity)(I[_t], I[_is_decreasing])
-- Perform the interpolation.
I[_interp](t, I[_target1], I[_target2], I[_context])
end
--- Metamethod.<br><br>
-- Updates the interpolation.
-- @param lapse Time lapse.
function Interpolator:__call (lapse)
Interpolate(self, lapse)
end
--- Accessor.
-- @return Current interpolation mode, which may be one of: <b>"once"</b>, <b>"oscillate"
-- </b>, <b>"oscillate_once"</b>, or <b>"suspended"</b>.
function Interpolator:GetMode ()
return self[_mode] or "suspended"
end
--- Gets the current interpolation state.
-- @return Interpolation time, in [0, 1].
-- @return If true, the time is decreasing.
function Interpolator:GetState ()
return self[_t], not not self[_is_decreasing]
end
--- Runs, from 0, to a given time.
-- @param t Interpolation time. The final time will be in [0, 1].
function Interpolator:RunTo (t)
-- Reset interpolation data.
self[_is_decreasing] = nil
-- Find the initial value.
self[_timer]:SetCounter(t, true)
Interpolate(self, 0)
end
--- Accessor.
-- @param context User-defined context to assign.
-- @see Interpolator:SetTargets
function Interpolator:SetContext (context)
self[_context] = context
end
--- Sets the duration needed to interpolate from t = 0 to t = 1 (or vice versa).
-- @param duration Duration to assign.
function Interpolator:SetDuration (duration)
assert(type(duration) == "number" and duration > 0, "Invalid duration")
-- Set up a new duration, mapping the counter into it. Restore the pause state.
local is_paused = self[_timer]:IsPaused()
self[_timer]:Start(duration, self[_t] * duration)
self[_timer]:SetPause(is_paused)
end
--- Sets the time mapping, to be applied during interpolation.
-- @param map Map to assign, or <b>nil</b> to remove any mapping.<br><br>
-- A valid mapping function has signature<br><br>
--    <i><b>map(t, is_decreasing)</b></i>,<br><br>
-- where <i>t</i> is the raw interpolation time in [0, 1], and <i>is_decreasing</i>
-- is true if the time is decreasing. This function must return a new time, also
-- in [0, 1].
function Interpolator:SetMap (map)
self[_map] = map
end
--- Accessor.
-- @param target1 User-defined interpolation target to assign.
-- @param target2 User-defined interpolation target to assign.
-- @see Interpolator:SetContext
function Interpolator:SetTargets (target1, target2)
self[_target1] = target1
self[_target2] = target2
end
--- Starts an interpolation.
-- @param mode Interpolation mode, as per <b>Interpolator:GetMode</b>.
-- @param how Resume command.<br><br>
-- If this is <b>nil</b>, the interpolator is reset, i.e. the interpolation time is
-- set to 0 and decreasing.<br><br>
-- If this is <b>"flip"</b>, the flow of time is reversed, preserving the current
-- time.<br><br>
-- If this is <b>"forward"</b> or <b>"reverse"</b>, the flow of time is set as
-- increasing or decreasing, respectively, preserving the current time.<br><br>
-- Finally, if this is <b>"continue"</b>, the interpolation proceeds as it was when
-- it was created or stopped.
-- @see Interpolator:Stop
function Interpolator:Start (mode, how)
assert(mode ~= nil and mode ~= "suspended" and Modes[mode], "Invalid mode")
assert(how == nil or Commands[how], "Bad command")
-- Given no resume commands, reset the interpolator.
if how == nil then
self[_t] = 0
self[_is_decreasing] = false
-- Otherwise, apply the appropriate resume command.
elseif how == "flip" then
self[_is_decreasing] = not self[_is_decreasing]
elseif how ~= "continue" then
self[_is_decreasing] = how == "reverse"
end
-- Set the interpolation timer.
self[_timer]:SetCounter(self[_is_decreasing] and 1 - self[_t] or self[_t], true)
self[_timer]:SetPause(false)
-- Get the initial value.
self[_mode] = mode
Interpolate(self, 0)
end
--- Stops the interpolation.
-- @param reset If true, the interpolation time is set to 0 and increasing.
-- @see Interpolator:Start
function Interpolator:Stop (reset)
self[_mode] = nil
-- On reset, clear state.
if reset then
self[_t] = 0
self[_is_decreasing] = false
self[_timer]:SetPause(true)
end
end
end,
--- Class constructor.
-- @class function
-- @name Constructor
-- @param interp Interpolate function, which will perform some action, given the current
-- time. A valid interpolation function has signature<br><br>
--    <i><b>interp(t, target1, target2, context)</b></i>,<br><br>
-- where <i>t</i> is the current interpolation time, in [0, 1], and the remaining parameters
-- will take whatever has been assigned as the current targets and context.
-- @param duration Duration to interpolate from t = 0 to t = 1 (or vice versa).
-- @param target1 Optional user-defined interpolation target.
-- @param target2 Optional user-defined interpolation target.
-- @param context Optional user-defined ontext.
function(I, interp, duration, target1, target2, context)
I[_interp] = interp
I[_timer] = New("Timer")
I:SetContext(context)
I:SetTargets(target1, target2)
I:Stop(true)
-- Set up any default duration.
if duration then
I:SetDuration(duration)
end
end) | mit |
Mutos/StarsOfCall-NAEV | dat/scripts/cargo_common.lua | 1 | 7762 | include "jumpdist.lua"
include "nextjump.lua"
-- Find an inhabited planet in specified range.
-- Defaults are minDistance = 1 and maxDistance = 9
-- Mutos 2013/06/13 : use sigma distribution and rounds up
function cargo_selectMissionDistance (minDistance, maxDistance)
-- Declare local variables
local meanDistance, intervalDistance, missionDistance
-- Check arguments
if minDistance==nil then
minDistance = 1
end
if maxDistance==nil then
maxDistance = 9
end
if minDistance > maxDistance then
minDistance, maxDistance = maxDistance, minDistance
end
-- Compute a random distance
meanDistance = (minDistance+maxDistance)/2
intervalDistance = (maxDistance-minDistance)/2
missionDistance = meanDistance + intervalDistance * rnd.sigma()
return math.ceil(missionDistance)
end
-- Build a set of target lists {planet, system}
function cargo_selectPlanets(missdist, routepos)
local planets = {}
getsysatdistance(system.cur(), missdist, missdist,
function(s)
for i, v in ipairs(s:planets()) do
if v:services()["inhabited"] and v ~= planet.cur() and v:class() ~= 0 and
not (s==system.cur() and ( vec2.dist( v:pos(), routepos ) < 2500 ) ) and
v:canLand() then
planets[#planets + 1] = {v, s}
end
end
return true
end)
return planets
end
-- Build a set of target systems
-- Todo : instead of selecting landable planets, select systems with no landable planet
function cargo_selectSystems(missdist, routepos, landable)
if landable==nil then
landable = true
end
local systems = {}
getsysatdistance(system.cur(), missdist, missdist,
function(s)
-- System is current, not selectable
if s == system.cur() then
return true
end
-- Add the system to the list
systems[#systems + 1] = s
end
)
return systems
end
-- We have a destination, now we need to calculate how far away it is by simulating the journey there.
-- Assume shortest route with no interruptions.
-- This is used to calculate the reward.
function cargo_calculateDistance(routesys, routepos, destsys, destplanet)
local traveldist = 0
local tempList = getRouteList(routesys, destsys)
local tempString = ""
for i, j in pairs(tempList) do
if i==1 then
tempString = tempString .. j:name()
else
tempString = tempString .. ";" .. j:name()
end
end
-- print ( string.format( "Final route is : \"%s\"", tempString ) )
while routesys ~= destsys do
-- We're not in the destination system yet.
-- So, get the next system on the route, and the distance between our entry point and the jump point to the next system.
-- Then, set the exit jump point as the next entry point.
local tempsys = getNextSystem(routesys, destsys)
local j,r = jump.get( routesys, tempsys )
traveldist = traveldist + vec2.dist(routepos, j:pos())
routepos = r:pos()
routesys = tempsys
end
-- We ARE in the destination system now, so route from the entry point to the destination planet.
traveldist = traveldist + vec2.dist(routepos, destplanet:pos())
return traveldist
end
-- Compute a route
function cargo_calculateRoute ( bUseDestinationCommodities )
-- declare local variables
local origin_p = nil
local origin_s = nil
-- Check flag : if not specified, then false
if bUseDestinationCommodities==nil then
bUseDestinationCommodities = false
end
-- Planet of origin : if not specified, current planet
origin_p, origin_s = planet.cur()
local routesys = origin_s
local routepos = origin_p:pos()
-- Select mission tier.
local tier = rnd.rnd(0, 4)
-- Select a random distance
local missdist = cargo_selectMissionDistance(1, 10)
-- Find a possible planet at that distance
local planets = cargo_selectPlanets(missdist, routepos)
if #planets == 0 then
return
end
local index = rnd.rnd(1, #planets)
local destplanet = planets[index][1]
local destsys = planets[index][2]
-- We have a destination, now we need to calculate how far away it is by simulating the journey there.
-- Assume shortest route with no interruptions.
-- This is used to calculate the reward.
local numjumps = origin_s:jumpDist(destsys)
local traveldist = cargo_calculateDistance(routesys, routepos, destsys, destplanet)
-- We now know where. But we don't know what yet. Randomly choose a commodity type.
-- Mutos, 2012/11/11 : extract the cargo from the current planet's commodities list.
-- Mutos, 2013/06/12 : added a flag to use destination instead, used for economic events.
local availableCommodities
if bUseDestinationCommodities then
-- print ( string.format ( "\tcargo_calculateRoute : using destination planet : \"%s\".", destplanet:name() ) )
availableCommodities = destplanet:commoditiesSold()
else
-- print ( string.format ( "\tcargo_calculateRoute : using origin planet : \"%s\".", origin_p:name() ) )
availableCommodities = origin_p:commoditiesSold()
end
if #availableCommodities==0 then
-- No commodity sold on this planet, so no possible cargo mission can be available there
-- print ( string.format ( "\tcargo_calculateRoute : \tNo commodity sold on this planet." ) )
return
end
local cargoes = {}
for i,v in ipairs(availableCommodities) do
-- print ( string.format ( "\tcargo_calculateRoute : \tCommodity : \"%s\"", v:name() ) )
table.insert(cargoes,v:name())
end
local cargo = cargoes[rnd.rnd(1, #cargoes)]
-- Return lots of stuff
return destplanet, destsys, numjumps, traveldist, cargo, tier
end
-- Compute a route
function cargo_calculateSmugglerRoute ( )
-- declare local variables
local origin_p = nil
local origin_s = nil
-- Init startup position
origin_p, origin_s = planet.cur()
local routesys = origin_s
local routepos = origin_p:pos()
-- Select a random distance - longer trips than cargo missions
local missDistMid = cargo_selectMissionDistance(5, 9)
local missDistEnd = cargo_selectMissionDistance(12, 20)
-- Find a possible planet at that distance
local planets = cargo_selectPlanets(missdist, routepos)
if #planets == 0 then
return
end
local index = rnd.rnd(1, #planets)
local destplanet = planets[index][1]
local destsys = planets[index][2]
-- We have a destination, now we need to calculate how far away it is by simulating the journey there.
-- Assume shortest route with no interruptions.
-- This is used to calculate the reward.
local numjumps = origin_s:jumpDist(destsys)
local traveldist = cargo_calculateDistance(routesys, routepos, destsys, destplanet)
end
-- Construct the cargo mission description text
function buildCargoMissionDescription( desc, priority, amount, ctype, destplanet, destsys )
-- declare local variables
local origin_p = nil
local origin_s = nil
origin_p, origin_s = planet.cur()
local numjumps = origin_s:jumpDist(destsys)
local str = desc[rnd.rnd(1, #desc)]
if priority ~= nil then
str = priority .. " " .. str
end
if system.cur() ~= destsys then
str = string.format( "%s in %s", str, destsys:name() )
end
if amount == nil then
return string.format( "%s (%s jumps)", str:format( destplanet:name()), numjumps )
else
return string.format( "%s (%s tonnes, %s jumps)", str:format( destplanet:name()), amount, numjumps )
end
end
-- Calculates the minimum possible time taken for the player to reach a destination.
function cargoGetTransit( timelimit, numjumps, traveldist )
local pstats = player.pilot():stats()
local stuperpx = 1 / player.pilot():stats().speed_max * 30
local arrivalt = time.get() + time.create(0, 0, traveldist * stuperpx + numjumps * pstats.jump_delay + 10180 + 240 * numjumps)
return arrivalt
end
| gpl-3.0 |
pkumusic/AI | DeepMind-Atari-Deep-Q-Learner/dqn/initenv.lua | 5 | 4777 | --[[
Copyright (c) 2014 Google Inc.
See LICENSE file for full terms of limited license.
]]
dqn = {}
require 'torch'
require 'nn'
require 'nngraph'
require 'nnutils'
require 'image'
require 'Scale'
require 'NeuralQLearner'
require 'TransitionTable'
require 'Rectifier'
function torchSetup(_opt)
_opt = _opt or {}
local opt = table.copy(_opt)
assert(opt)
-- preprocess options:
--- convert options strings to tables
if opt.pool_frms then
opt.pool_frms = str_to_table(opt.pool_frms)
end
if opt.env_params then
opt.env_params = str_to_table(opt.env_params)
end
if opt.agent_params then
opt.agent_params = str_to_table(opt.agent_params)
opt.agent_params.gpu = opt.gpu
opt.agent_params.best = opt.best
opt.agent_params.verbose = opt.verbose
if opt.network ~= '' then
opt.agent_params.network = opt.network
end
end
--- general setup
opt.tensorType = opt.tensorType or 'torch.FloatTensor'
torch.setdefaulttensortype(opt.tensorType)
if not opt.threads then
opt.threads = 4
end
torch.setnumthreads(opt.threads)
if not opt.verbose then
opt.verbose = 10
end
if opt.verbose >= 1 then
print('Torch Threads:', torch.getnumthreads())
end
--- set gpu device
if opt.gpu and opt.gpu >= 0 then
require 'cutorch'
require 'cunn'
if opt.gpu == 0 then
local gpu_id = tonumber(os.getenv('GPU_ID'))
if gpu_id then opt.gpu = gpu_id+1 end
end
if opt.gpu > 0 then cutorch.setDevice(opt.gpu) end
opt.gpu = cutorch.getDevice()
print('Using GPU device id:', opt.gpu-1)
else
opt.gpu = -1
if opt.verbose >= 1 then
print('Using CPU code only. GPU device id:', opt.gpu)
end
end
--- set up random number generators
-- removing lua RNG; seeding torch RNG with opt.seed and setting cutorch
-- RNG seed to the first uniform random int32 from the previous RNG;
-- this is preferred because using the same seed for both generators
-- may introduce correlations; we assume that both torch RNGs ensure
-- adequate dispersion for different seeds.
math.random = nil
opt.seed = opt.seed or 1
torch.manualSeed(opt.seed)
if opt.verbose >= 1 then
print('Torch Seed:', torch.initialSeed())
end
local firstRandInt = torch.random()
if opt.gpu >= 0 then
cutorch.manualSeed(firstRandInt)
if opt.verbose >= 1 then
print('CUTorch Seed:', cutorch.initialSeed())
end
end
return opt
end
function setup(_opt)
assert(_opt)
--preprocess options:
--- convert options strings to tables
_opt.pool_frms = str_to_table(_opt.pool_frms)
_opt.env_params = str_to_table(_opt.env_params)
_opt.agent_params = str_to_table(_opt.agent_params)
if _opt.agent_params.transition_params then
_opt.agent_params.transition_params =
str_to_table(_opt.agent_params.transition_params)
end
--- first things first
local opt = torchSetup(_opt)
-- load training framework and environment
local framework = require(opt.framework)
assert(framework)
local gameEnv = framework.GameEnvironment(opt)
local gameActions = gameEnv:getActions()
-- agent options
_opt.agent_params.actions = gameActions
_opt.agent_params.gpu = _opt.gpu
_opt.agent_params.best = _opt.best
if _opt.network ~= '' then
_opt.agent_params.network = _opt.network
end
_opt.agent_params.verbose = _opt.verbose
if not _opt.agent_params.state_dim then
_opt.agent_params.state_dim = gameEnv:nObsFeature()
end
local agent = dqn[_opt.agent](_opt.agent_params)
if opt.verbose >= 1 then
print('Set up Torch using these options:')
for k, v in pairs(opt) do
print(k, v)
end
end
return gameEnv, gameActions, agent, opt
end
--- other functions
function str_to_table(str)
if type(str) == 'table' then
return str
end
if not str or type(str) ~= 'string' then
if type(str) == 'table' then
return str
end
return {}
end
local ttr
if str ~= '' then
local ttx=tt
loadstring('tt = {' .. str .. '}')()
ttr = tt
tt = ttx
else
ttr = {}
end
return ttr
end
function table.copy(t)
if t == nil then return nil end
local nt = {}
for k, v in pairs(t) do
if type(v) == 'table' then
nt[k] = table.copy(v)
else
nt[k] = v
end
end
setmetatable(nt, table.copy(getmetatable(t)))
return nt
end
| mit |
Anarchid/Zero-K | LuaUI/Configs/missionTipOverride.lua | 8 | 1046 |
text = [[You will face the fearsome, fire-spewing Dante strider in this battle. Use Aspis area shields to deflect the assault, and Racketeer artillery to disarm the Dante.]]
tips = {
{
image = "unitpics/shieldarty.png",
text = [[Racketeers use long range disarm missiles to disable the weapons and abilities of single enemy units. They don't do any real damage so make sure you have other units standing by to destroy the helpless enemy.]]
},
{
image = "unitpics/shieldshield.png",
text = [[The Aspis area shield projects a larger and more powerful shield than those carried by other Shieldbots. Shields only destroy projectiles that cross their surface so make sure to maintain a safe distance from enemy units. Aspis can morph to and from the Aegis, a slightly more efficient static version.]]
},
{
image = "unitpics/striderdante.png",
text = [[The Dante's heatrays and napalm rockets are most lethal at close range. Keep your distance until the Dante is disarmed or dead.]]
},
}
return tips, text
| gpl-2.0 |
cstroie/Pip | wx.lua | 1 | 2133 | -- Weather report from MQTT "wx/STATION/now|tod|tom..." "line1, line2"
require("config")
lcd = require("lcd")
local wx = {}
wx.wthr = {}
function wx:weather(id, msg)
msg = msg:gsub("\194\176", "\223") -- UTF8
msg = msg:gsub("\176", "\223") -- Latin1
local ln1, ln2 = string.match(msg, '^(.*), (.*)$')
self.wthr[id] = {ln1 = ln1, ln2 = ln2}
if id == "ton" then self.wthr["tod"] = nil
elseif id == "tod" then self.wthr["ton"] = nil
elseif id == "tmz" then timezone = tonumber(ln2) end
end
function wx:now()
local result = false
if self.wthr.now then
lcd:screen(string.format("Now% 13s", self.wthr.now.ln1), self.wthr.now.ln2)
result = true
end
return result
end
function wx:today()
local result = false
if self.wthr.tod then
lcd:screen(string.format("Today % 9s", self.wthr.tod.ln1), self.wthr.tod.ln2)
result = true
elseif self.wthr.ton then
lcd:screen(string.format("Tonight% 9s", self.wthr.ton.ln1), self.wthr.ton.ln2)
result = true
end
return result
end
function wx:tomorrow()
local result = false
if self.wthr.tom then
lcd:screen(string.format("Tmrrow % 9s", self.wthr.tom.ln1), self.wthr.tom.ln2)
result = true
end
return result
end
function wx:baro()
local result = false
if self.wthr.bar then
lcd:screen(string.format("Baro% 12s", self.wthr.bar.ln1), self.wthr.bar.ln2)
result = true
end
return result
end
function wx:sun()
local result = false
if self.wthr.sun then
lcd:screen(string.format("Sunrise % 8s", self.wthr.sun.ln1), string.format("Sunset % 8s", self.wthr.sun.ln2))
result = true
end
return result
end
function wx:moon()
local result = false
if self.wthr.mon then
local ph = math.floor((tonumber(self.wthr.mon.ln1)+1)*3/7)%12+1
local w1, w2 = string.match(self.wthr.mon.ln2, '^(.*) (.*)$')
if not w1 then
w1 = self.wthr.mon.ln2
w2 = "Moon"
end
lcd:screen(w1, w2)
bgmoon = require("bgmoon")
bgmoon:write(ph, 12)
unrequire("bgmoon")
result = true
end
return result
end
return wx
-- vim: set ft=lua ai ts=2 sts=2 et sw=2 sta nowrap nu :
| gpl-3.0 |
chiuan/slua | build/luajit-2.0.4/src/jit/dis_ppc.lua | 88 | 20319 | ----------------------------------------------------------------------------
-- LuaJIT PPC disassembler module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT/X license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
-- This is a helper module used by the LuaJIT machine code dumper module.
--
-- It disassembles all common, non-privileged 32/64 bit PowerPC instructions
-- plus the e500 SPE instructions and some Cell/Xenon extensions.
--
-- NYI: VMX, VMX128
------------------------------------------------------------------------------
local type = type
local sub, byte, format = string.sub, string.byte, string.format
local match, gmatch, gsub = string.match, string.gmatch, string.gsub
local concat = table.concat
local bit = require("bit")
local band, bor, tohex = bit.band, bit.bor, bit.tohex
local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift
------------------------------------------------------------------------------
-- Primary and extended opcode maps
------------------------------------------------------------------------------
local map_crops = {
shift = 1, mask = 1023,
[0] = "mcrfXX",
[33] = "crnor|crnotCCC=", [129] = "crandcCCC",
[193] = "crxor|crclrCCC%", [225] = "crnandCCC",
[257] = "crandCCC", [289] = "creqv|crsetCCC%",
[417] = "crorcCCC", [449] = "cror|crmoveCCC=",
[16] = "b_lrKB", [528] = "b_ctrKB",
[150] = "isync",
}
local map_rlwinm = setmetatable({
shift = 0, mask = -1,
},
{ __index = function(t, x)
local rot = band(rshift(x, 11), 31)
local mb = band(rshift(x, 6), 31)
local me = band(rshift(x, 1), 31)
if mb == 0 and me == 31-rot then
return "slwiRR~A."
elseif me == 31 and mb == 32-rot then
return "srwiRR~-A."
else
return "rlwinmRR~AAA."
end
end
})
local map_rld = {
shift = 2, mask = 7,
[0] = "rldiclRR~HM.", "rldicrRR~HM.", "rldicRR~HM.", "rldimiRR~HM.",
{
shift = 1, mask = 1,
[0] = "rldclRR~RM.", "rldcrRR~RM.",
},
}
local map_ext = setmetatable({
shift = 1, mask = 1023,
[0] = "cmp_YLRR", [32] = "cmpl_YLRR",
[4] = "twARR", [68] = "tdARR",
[8] = "subfcRRR.", [40] = "subfRRR.",
[104] = "negRR.", [136] = "subfeRRR.",
[200] = "subfzeRR.", [232] = "subfmeRR.",
[520] = "subfcoRRR.", [552] = "subfoRRR.",
[616] = "negoRR.", [648] = "subfeoRRR.",
[712] = "subfzeoRR.", [744] = "subfmeoRR.",
[9] = "mulhduRRR.", [73] = "mulhdRRR.", [233] = "mulldRRR.",
[457] = "divduRRR.", [489] = "divdRRR.",
[745] = "mulldoRRR.",
[969] = "divduoRRR.", [1001] = "divdoRRR.",
[10] = "addcRRR.", [138] = "addeRRR.",
[202] = "addzeRR.", [234] = "addmeRR.", [266] = "addRRR.",
[522] = "addcoRRR.", [650] = "addeoRRR.",
[714] = "addzeoRR.", [746] = "addmeoRR.", [778] = "addoRRR.",
[11] = "mulhwuRRR.", [75] = "mulhwRRR.", [235] = "mullwRRR.",
[459] = "divwuRRR.", [491] = "divwRRR.",
[747] = "mullwoRRR.",
[971] = "divwouRRR.", [1003] = "divwoRRR.",
[15] = "iselltRRR", [47] = "iselgtRRR", [79] = "iseleqRRR",
[144] = { shift = 20, mask = 1, [0] = "mtcrfRZ~", "mtocrfRZ~", },
[19] = { shift = 20, mask = 1, [0] = "mfcrR", "mfocrfRZ", },
[371] = { shift = 11, mask = 1023, [392] = "mftbR", [424] = "mftbuR", },
[339] = {
shift = 11, mask = 1023,
[32] = "mferR", [256] = "mflrR", [288] = "mfctrR", [16] = "mfspefscrR",
},
[467] = {
shift = 11, mask = 1023,
[32] = "mtxerR", [256] = "mtlrR", [288] = "mtctrR", [16] = "mtspefscrR",
},
[20] = "lwarxRR0R", [84] = "ldarxRR0R",
[21] = "ldxRR0R", [53] = "lduxRRR",
[149] = "stdxRR0R", [181] = "stduxRRR",
[341] = "lwaxRR0R", [373] = "lwauxRRR",
[23] = "lwzxRR0R", [55] = "lwzuxRRR",
[87] = "lbzxRR0R", [119] = "lbzuxRRR",
[151] = "stwxRR0R", [183] = "stwuxRRR",
[215] = "stbxRR0R", [247] = "stbuxRRR",
[279] = "lhzxRR0R", [311] = "lhzuxRRR",
[343] = "lhaxRR0R", [375] = "lhauxRRR",
[407] = "sthxRR0R", [439] = "sthuxRRR",
[54] = "dcbst-R0R", [86] = "dcbf-R0R",
[150] = "stwcxRR0R.", [214] = "stdcxRR0R.",
[246] = "dcbtst-R0R", [278] = "dcbt-R0R",
[310] = "eciwxRR0R", [438] = "ecowxRR0R",
[470] = "dcbi-RR",
[598] = {
shift = 21, mask = 3,
[0] = "sync", "lwsync", "ptesync",
},
[758] = "dcba-RR",
[854] = "eieio", [982] = "icbi-R0R", [1014] = "dcbz-R0R",
[26] = "cntlzwRR~", [58] = "cntlzdRR~",
[122] = "popcntbRR~",
[154] = "prtywRR~", [186] = "prtydRR~",
[28] = "andRR~R.", [60] = "andcRR~R.", [124] = "nor|notRR~R=.",
[284] = "eqvRR~R.", [316] = "xorRR~R.",
[412] = "orcRR~R.", [444] = "or|mrRR~R=.", [476] = "nandRR~R.",
[508] = "cmpbRR~R",
[512] = "mcrxrX",
[532] = "ldbrxRR0R", [660] = "stdbrxRR0R",
[533] = "lswxRR0R", [597] = "lswiRR0A",
[661] = "stswxRR0R", [725] = "stswiRR0A",
[534] = "lwbrxRR0R", [662] = "stwbrxRR0R",
[790] = "lhbrxRR0R", [918] = "sthbrxRR0R",
[535] = "lfsxFR0R", [567] = "lfsuxFRR",
[599] = "lfdxFR0R", [631] = "lfduxFRR",
[663] = "stfsxFR0R", [695] = "stfsuxFRR",
[727] = "stfdxFR0R", [759] = "stfduxFR0R",
[855] = "lfiwaxFR0R",
[983] = "stfiwxFR0R",
[24] = "slwRR~R.",
[27] = "sldRR~R.", [536] = "srwRR~R.",
[792] = "srawRR~R.", [824] = "srawiRR~A.",
[794] = "sradRR~R.", [826] = "sradiRR~H.", [827] = "sradiRR~H.",
[922] = "extshRR~.", [954] = "extsbRR~.", [986] = "extswRR~.",
[539] = "srdRR~R.",
},
{ __index = function(t, x)
if band(x, 31) == 15 then return "iselRRRC" end
end
})
local map_ld = {
shift = 0, mask = 3,
[0] = "ldRRE", "lduRRE", "lwaRRE",
}
local map_std = {
shift = 0, mask = 3,
[0] = "stdRRE", "stduRRE",
}
local map_fps = {
shift = 5, mask = 1,
{
shift = 1, mask = 15,
[0] = false, false, "fdivsFFF.", false,
"fsubsFFF.", "faddsFFF.", "fsqrtsF-F.", false,
"fresF-F.", "fmulsFF-F.", "frsqrtesF-F.", false,
"fmsubsFFFF~.", "fmaddsFFFF~.", "fnmsubsFFFF~.", "fnmaddsFFFF~.",
}
}
local map_fpd = {
shift = 5, mask = 1,
[0] = {
shift = 1, mask = 1023,
[0] = "fcmpuXFF", [32] = "fcmpoXFF", [64] = "mcrfsXX",
[38] = "mtfsb1A.", [70] = "mtfsb0A.", [134] = "mtfsfiA>>-A>",
[8] = "fcpsgnFFF.", [40] = "fnegF-F.", [72] = "fmrF-F.",
[136] = "fnabsF-F.", [264] = "fabsF-F.",
[12] = "frspF-F.",
[14] = "fctiwF-F.", [15] = "fctiwzF-F.",
[583] = "mffsF.", [711] = "mtfsfZF.",
[392] = "frinF-F.", [424] = "frizF-F.",
[456] = "fripF-F.", [488] = "frimF-F.",
[814] = "fctidF-F.", [815] = "fctidzF-F.", [846] = "fcfidF-F.",
},
{
shift = 1, mask = 15,
[0] = false, false, "fdivFFF.", false,
"fsubFFF.", "faddFFF.", "fsqrtF-F.", "fselFFFF~.",
"freF-F.", "fmulFF-F.", "frsqrteF-F.", false,
"fmsubFFFF~.", "fmaddFFFF~.", "fnmsubFFFF~.", "fnmaddFFFF~.",
}
}
local map_spe = {
shift = 0, mask = 2047,
[512] = "evaddwRRR", [514] = "evaddiwRAR~",
[516] = "evsubwRRR~", [518] = "evsubiwRAR~",
[520] = "evabsRR", [521] = "evnegRR",
[522] = "evextsbRR", [523] = "evextshRR", [524] = "evrndwRR",
[525] = "evcntlzwRR", [526] = "evcntlswRR",
[527] = "brincRRR",
[529] = "evandRRR", [530] = "evandcRRR", [534] = "evxorRRR",
[535] = "evor|evmrRRR=", [536] = "evnor|evnotRRR=",
[537] = "eveqvRRR", [539] = "evorcRRR", [542] = "evnandRRR",
[544] = "evsrwuRRR", [545] = "evsrwsRRR",
[546] = "evsrwiuRRA", [547] = "evsrwisRRA",
[548] = "evslwRRR", [550] = "evslwiRRA",
[552] = "evrlwRRR", [553] = "evsplatiRS",
[554] = "evrlwiRRA", [555] = "evsplatfiRS",
[556] = "evmergehiRRR", [557] = "evmergeloRRR",
[558] = "evmergehiloRRR", [559] = "evmergelohiRRR",
[560] = "evcmpgtuYRR", [561] = "evcmpgtsYRR",
[562] = "evcmpltuYRR", [563] = "evcmpltsYRR",
[564] = "evcmpeqYRR",
[632] = "evselRRR", [633] = "evselRRRW",
[634] = "evselRRRW", [635] = "evselRRRW",
[636] = "evselRRRW", [637] = "evselRRRW",
[638] = "evselRRRW", [639] = "evselRRRW",
[640] = "evfsaddRRR", [641] = "evfssubRRR",
[644] = "evfsabsRR", [645] = "evfsnabsRR", [646] = "evfsnegRR",
[648] = "evfsmulRRR", [649] = "evfsdivRRR",
[652] = "evfscmpgtYRR", [653] = "evfscmpltYRR", [654] = "evfscmpeqYRR",
[656] = "evfscfuiR-R", [657] = "evfscfsiR-R",
[658] = "evfscfufR-R", [659] = "evfscfsfR-R",
[660] = "evfsctuiR-R", [661] = "evfsctsiR-R",
[662] = "evfsctufR-R", [663] = "evfsctsfR-R",
[664] = "evfsctuizR-R", [666] = "evfsctsizR-R",
[668] = "evfststgtYRR", [669] = "evfststltYRR", [670] = "evfststeqYRR",
[704] = "efsaddRRR", [705] = "efssubRRR",
[708] = "efsabsRR", [709] = "efsnabsRR", [710] = "efsnegRR",
[712] = "efsmulRRR", [713] = "efsdivRRR",
[716] = "efscmpgtYRR", [717] = "efscmpltYRR", [718] = "efscmpeqYRR",
[719] = "efscfdR-R",
[720] = "efscfuiR-R", [721] = "efscfsiR-R",
[722] = "efscfufR-R", [723] = "efscfsfR-R",
[724] = "efsctuiR-R", [725] = "efsctsiR-R",
[726] = "efsctufR-R", [727] = "efsctsfR-R",
[728] = "efsctuizR-R", [730] = "efsctsizR-R",
[732] = "efststgtYRR", [733] = "efststltYRR", [734] = "efststeqYRR",
[736] = "efdaddRRR", [737] = "efdsubRRR",
[738] = "efdcfuidR-R", [739] = "efdcfsidR-R",
[740] = "efdabsRR", [741] = "efdnabsRR", [742] = "efdnegRR",
[744] = "efdmulRRR", [745] = "efddivRRR",
[746] = "efdctuidzR-R", [747] = "efdctsidzR-R",
[748] = "efdcmpgtYRR", [749] = "efdcmpltYRR", [750] = "efdcmpeqYRR",
[751] = "efdcfsR-R",
[752] = "efdcfuiR-R", [753] = "efdcfsiR-R",
[754] = "efdcfufR-R", [755] = "efdcfsfR-R",
[756] = "efdctuiR-R", [757] = "efdctsiR-R",
[758] = "efdctufR-R", [759] = "efdctsfR-R",
[760] = "efdctuizR-R", [762] = "efdctsizR-R",
[764] = "efdtstgtYRR", [765] = "efdtstltYRR", [766] = "efdtsteqYRR",
[768] = "evlddxRR0R", [769] = "evlddRR8",
[770] = "evldwxRR0R", [771] = "evldwRR8",
[772] = "evldhxRR0R", [773] = "evldhRR8",
[776] = "evlhhesplatxRR0R", [777] = "evlhhesplatRR2",
[780] = "evlhhousplatxRR0R", [781] = "evlhhousplatRR2",
[782] = "evlhhossplatxRR0R", [783] = "evlhhossplatRR2",
[784] = "evlwhexRR0R", [785] = "evlwheRR4",
[788] = "evlwhouxRR0R", [789] = "evlwhouRR4",
[790] = "evlwhosxRR0R", [791] = "evlwhosRR4",
[792] = "evlwwsplatxRR0R", [793] = "evlwwsplatRR4",
[796] = "evlwhsplatxRR0R", [797] = "evlwhsplatRR4",
[800] = "evstddxRR0R", [801] = "evstddRR8",
[802] = "evstdwxRR0R", [803] = "evstdwRR8",
[804] = "evstdhxRR0R", [805] = "evstdhRR8",
[816] = "evstwhexRR0R", [817] = "evstwheRR4",
[820] = "evstwhoxRR0R", [821] = "evstwhoRR4",
[824] = "evstwwexRR0R", [825] = "evstwweRR4",
[828] = "evstwwoxRR0R", [829] = "evstwwoRR4",
[1027] = "evmhessfRRR", [1031] = "evmhossfRRR", [1032] = "evmheumiRRR",
[1033] = "evmhesmiRRR", [1035] = "evmhesmfRRR", [1036] = "evmhoumiRRR",
[1037] = "evmhosmiRRR", [1039] = "evmhosmfRRR", [1059] = "evmhessfaRRR",
[1063] = "evmhossfaRRR", [1064] = "evmheumiaRRR", [1065] = "evmhesmiaRRR",
[1067] = "evmhesmfaRRR", [1068] = "evmhoumiaRRR", [1069] = "evmhosmiaRRR",
[1071] = "evmhosmfaRRR", [1095] = "evmwhssfRRR", [1096] = "evmwlumiRRR",
[1100] = "evmwhumiRRR", [1101] = "evmwhsmiRRR", [1103] = "evmwhsmfRRR",
[1107] = "evmwssfRRR", [1112] = "evmwumiRRR", [1113] = "evmwsmiRRR",
[1115] = "evmwsmfRRR", [1127] = "evmwhssfaRRR", [1128] = "evmwlumiaRRR",
[1132] = "evmwhumiaRRR", [1133] = "evmwhsmiaRRR", [1135] = "evmwhsmfaRRR",
[1139] = "evmwssfaRRR", [1144] = "evmwumiaRRR", [1145] = "evmwsmiaRRR",
[1147] = "evmwsmfaRRR",
[1216] = "evaddusiaawRR", [1217] = "evaddssiaawRR",
[1218] = "evsubfusiaawRR", [1219] = "evsubfssiaawRR",
[1220] = "evmraRR",
[1222] = "evdivwsRRR", [1223] = "evdivwuRRR",
[1224] = "evaddumiaawRR", [1225] = "evaddsmiaawRR",
[1226] = "evsubfumiaawRR", [1227] = "evsubfsmiaawRR",
[1280] = "evmheusiaawRRR", [1281] = "evmhessiaawRRR",
[1283] = "evmhessfaawRRR", [1284] = "evmhousiaawRRR",
[1285] = "evmhossiaawRRR", [1287] = "evmhossfaawRRR",
[1288] = "evmheumiaawRRR", [1289] = "evmhesmiaawRRR",
[1291] = "evmhesmfaawRRR", [1292] = "evmhoumiaawRRR",
[1293] = "evmhosmiaawRRR", [1295] = "evmhosmfaawRRR",
[1320] = "evmhegumiaaRRR", [1321] = "evmhegsmiaaRRR",
[1323] = "evmhegsmfaaRRR", [1324] = "evmhogumiaaRRR",
[1325] = "evmhogsmiaaRRR", [1327] = "evmhogsmfaaRRR",
[1344] = "evmwlusiaawRRR", [1345] = "evmwlssiaawRRR",
[1352] = "evmwlumiaawRRR", [1353] = "evmwlsmiaawRRR",
[1363] = "evmwssfaaRRR", [1368] = "evmwumiaaRRR",
[1369] = "evmwsmiaaRRR", [1371] = "evmwsmfaaRRR",
[1408] = "evmheusianwRRR", [1409] = "evmhessianwRRR",
[1411] = "evmhessfanwRRR", [1412] = "evmhousianwRRR",
[1413] = "evmhossianwRRR", [1415] = "evmhossfanwRRR",
[1416] = "evmheumianwRRR", [1417] = "evmhesmianwRRR",
[1419] = "evmhesmfanwRRR", [1420] = "evmhoumianwRRR",
[1421] = "evmhosmianwRRR", [1423] = "evmhosmfanwRRR",
[1448] = "evmhegumianRRR", [1449] = "evmhegsmianRRR",
[1451] = "evmhegsmfanRRR", [1452] = "evmhogumianRRR",
[1453] = "evmhogsmianRRR", [1455] = "evmhogsmfanRRR",
[1472] = "evmwlusianwRRR", [1473] = "evmwlssianwRRR",
[1480] = "evmwlumianwRRR", [1481] = "evmwlsmianwRRR",
[1491] = "evmwssfanRRR", [1496] = "evmwumianRRR",
[1497] = "evmwsmianRRR", [1499] = "evmwsmfanRRR",
}
local map_pri = {
[0] = false, false, "tdiARI", "twiARI",
map_spe, false, false, "mulliRRI",
"subficRRI", false, "cmpl_iYLRU", "cmp_iYLRI",
"addicRRI", "addic.RRI", "addi|liRR0I", "addis|lisRR0I",
"b_KBJ", "sc", "bKJ", map_crops,
"rlwimiRR~AAA.", map_rlwinm, false, "rlwnmRR~RAA.",
"oriNRR~U", "orisRR~U", "xoriRR~U", "xorisRR~U",
"andi.RR~U", "andis.RR~U", map_rld, map_ext,
"lwzRRD", "lwzuRRD", "lbzRRD", "lbzuRRD",
"stwRRD", "stwuRRD", "stbRRD", "stbuRRD",
"lhzRRD", "lhzuRRD", "lhaRRD", "lhauRRD",
"sthRRD", "sthuRRD", "lmwRRD", "stmwRRD",
"lfsFRD", "lfsuFRD", "lfdFRD", "lfduFRD",
"stfsFRD", "stfsuFRD", "stfdFRD", "stfduFRD",
false, false, map_ld, map_fps,
false, false, map_std, map_fpd,
}
------------------------------------------------------------------------------
local map_gpr = {
[0] = "r0", "sp", "r2", "r3", "r4", "r5", "r6", "r7",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
"r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
}
local map_cond = { [0] = "lt", "gt", "eq", "so", "ge", "le", "ne", "ns", }
-- Format a condition bit.
local function condfmt(cond)
if cond <= 3 then
return map_cond[band(cond, 3)]
else
return format("4*cr%d+%s", rshift(cond, 2), map_cond[band(cond, 3)])
end
end
------------------------------------------------------------------------------
-- Output a nicely formatted line with an opcode and operands.
local function putop(ctx, text, operands)
local pos = ctx.pos
local extra = ""
if ctx.rel then
local sym = ctx.symtab[ctx.rel]
if sym then extra = "\t->"..sym end
end
if ctx.hexdump > 0 then
ctx.out(format("%08x %s %-7s %s%s\n",
ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra))
else
ctx.out(format("%08x %-7s %s%s\n",
ctx.addr+pos, text, concat(operands, ", "), extra))
end
ctx.pos = pos + 4
end
-- Fallback for unknown opcodes.
local function unknown(ctx)
return putop(ctx, ".long", { "0x"..tohex(ctx.op) })
end
-- Disassemble a single instruction.
local function disass_ins(ctx)
local pos = ctx.pos
local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4)
local op = bor(lshift(b0, 24), lshift(b1, 16), lshift(b2, 8), b3)
local operands = {}
local last = nil
local rs = 21
ctx.op = op
ctx.rel = nil
local opat = map_pri[rshift(b0, 2)]
while type(opat) ~= "string" do
if not opat then return unknown(ctx) end
opat = opat[band(rshift(op, opat.shift), opat.mask)]
end
local name, pat = match(opat, "^([a-z0-9_.]*)(.*)")
local altname, pat2 = match(pat, "|([a-z0-9_.]*)(.*)")
if altname then pat = pat2 end
for p in gmatch(pat, ".") do
local x = nil
if p == "R" then
x = map_gpr[band(rshift(op, rs), 31)]
rs = rs - 5
elseif p == "F" then
x = "f"..band(rshift(op, rs), 31)
rs = rs - 5
elseif p == "A" then
x = band(rshift(op, rs), 31)
rs = rs - 5
elseif p == "S" then
x = arshift(lshift(op, 27-rs), 27)
rs = rs - 5
elseif p == "I" then
x = arshift(lshift(op, 16), 16)
elseif p == "U" then
x = band(op, 0xffff)
elseif p == "D" or p == "E" then
local disp = arshift(lshift(op, 16), 16)
if p == "E" then disp = band(disp, -4) end
if last == "r0" then last = "0" end
operands[#operands] = format("%d(%s)", disp, last)
elseif p >= "2" and p <= "8" then
local disp = band(rshift(op, rs), 31) * p
if last == "r0" then last = "0" end
operands[#operands] = format("%d(%s)", disp, last)
elseif p == "H" then
x = band(rshift(op, rs), 31) + lshift(band(op, 2), 4)
rs = rs - 5
elseif p == "M" then
x = band(rshift(op, rs), 31) + band(op, 0x20)
elseif p == "C" then
x = condfmt(band(rshift(op, rs), 31))
rs = rs - 5
elseif p == "B" then
local bo = rshift(op, 21)
local cond = band(rshift(op, 16), 31)
local cn = ""
rs = rs - 10
if band(bo, 4) == 0 then
cn = band(bo, 2) == 0 and "dnz" or "dz"
if band(bo, 0x10) == 0 then
cn = cn..(band(bo, 8) == 0 and "f" or "t")
end
if band(bo, 0x10) == 0 then x = condfmt(cond) end
name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+")
elseif band(bo, 0x10) == 0 then
cn = map_cond[band(cond, 3) + (band(bo, 8) == 0 and 4 or 0)]
if cond > 3 then x = "cr"..rshift(cond, 2) end
name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+")
end
name = gsub(name, "_", cn)
elseif p == "J" then
x = arshift(lshift(op, 27-rs), 29-rs)*4
if band(op, 2) == 0 then x = ctx.addr + pos + x end
ctx.rel = x
x = "0x"..tohex(x)
elseif p == "K" then
if band(op, 1) ~= 0 then name = name.."l" end
if band(op, 2) ~= 0 then name = name.."a" end
elseif p == "X" or p == "Y" then
x = band(rshift(op, rs+2), 7)
if x == 0 and p == "Y" then x = nil else x = "cr"..x end
rs = rs - 5
elseif p == "W" then
x = "cr"..band(op, 7)
elseif p == "Z" then
x = band(rshift(op, rs-4), 255)
rs = rs - 10
elseif p == ">" then
operands[#operands] = rshift(operands[#operands], 1)
elseif p == "0" then
if last == "r0" then
operands[#operands] = nil
if altname then name = altname end
end
elseif p == "L" then
name = gsub(name, "_", band(op, 0x00200000) ~= 0 and "d" or "w")
elseif p == "." then
if band(op, 1) == 1 then name = name.."." end
elseif p == "N" then
if op == 0x60000000 then name = "nop"; break end
elseif p == "~" then
local n = #operands
operands[n-1], operands[n] = operands[n], operands[n-1]
elseif p == "=" then
local n = #operands
if last == operands[n-1] then
operands[n] = nil
name = altname
end
elseif p == "%" then
local n = #operands
if last == operands[n-1] and last == operands[n-2] then
operands[n] = nil
operands[n-1] = nil
name = altname
end
elseif p == "-" then
rs = rs - 5
else
assert(false)
end
if x then operands[#operands+1] = x; last = x end
end
return putop(ctx, name, operands)
end
------------------------------------------------------------------------------
-- Disassemble a block of code.
local function disass_block(ctx, ofs, len)
if not ofs then ofs = 0 end
local stop = len and ofs+len or #ctx.code
stop = stop - stop % 4
ctx.pos = ofs - ofs % 4
ctx.rel = nil
while ctx.pos < stop do disass_ins(ctx) end
end
-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
local function create_(code, addr, out)
local ctx = {}
ctx.code = code
ctx.addr = addr or 0
ctx.out = out or io.write
ctx.symtab = {}
ctx.disass = disass_block
ctx.hexdump = 8
return ctx
end
-- Simple API: disassemble code (a string) at address and output via out.
local function disass_(code, addr, out)
create_(code, addr, out):disass()
end
-- Return register name for RID.
local function regname_(r)
if r < 32 then return map_gpr[r] end
return "f"..(r-32)
end
-- Public module functions.
module(...)
create = create_
disass = disass_
regname = regname_
| mit |
Anarchid/Zero-K | LuaRules/Configs/float_defs.lua | 6 | 5500 | -- initialRiseSpeed: Velocity which unit "pushes off" the bottom
-- riseAccel: Acceleration while trying to surface
-- riseUpDrag: Drag on negative velocity while trying to surface
-- riseDownDrag: Drag on positive velocity while trying to surface
-- sinkAccel: Acceleration while trying to sink
-- sinkUpDrag: Drag on negative velocity while trying to sink
-- sinkDownDrag: Drag on positive velocity while trying to sink
-- airAccel: Acceleration while out of water. aka gravity qhich is only active out of water
-- airDrag: Drag on speed while out of water
-- waterHitDrag: Reduction in speed upon hitting the water
-- floatPoint: Position of unit base that denotes the surface of the water
-- surfaceDampen: Distance over which to interpolate the effect of above and below water physics
-- depthRequirement: Max depth of sea floor that float can be enabled
-- sinkOnPara: If true the unit will set to sink if paralysed. In either mode state cannot be changed while paraed
-- stopSpeedLeeway: Below this speed the unit can snap to surface
-- stopPositionLeeway: Below this distance from the surface the unit can stnap to surface.
-- surfaceWaitPos: Modifier to what is considered the surface for the following two parametsr.
-- surfaceMinWait: Block sink acceleration until the unit has been on the surface this long.
-- surfaceMaxWait: Scale sink acceleration up to maximum between surfaceMinWait and surfaceMaxWait.
-- PHYSIC UPDATE (4 April 2013):
-- as in ZK version >= r9871 (>1.1.3.6) all "Drag" related constant now mean "dragCoefficient" from Physic's drag equation ( this equation here: http://en.wikipedia.org/wiki/Drag_equation ),
-- from this physic equation, the negative acceleration (the resistance) is defined by : resistiveAccel = 0.5*(currentVelocity*currentVelocity*dragCoefficient)
-- this mean faster unit has more drag, and bigger "Drag" cause more drag, while smaller "Drag" lead to less drag, while 0 "Drag" lead to 0 drag (and 0 drag will lead to infinite speed).
local floatDefs = {
-- This unit pushes off the floor and swims to the surface at fairly constant
-- velocity. It then treads water so sinks if EMPed. It is heavier than water
-- so sinks at a fairly constant velocity as well.
[UnitDefNames["amphaa"].id] = {
initialRiseSpeed = 3,
riseAccel = 0.12,
riseUpDrag = 0.9,
riseDownDrag = 0.7,
sinkAccel = -0.12,
sinkUpDrag = 0.9,
sinkDownDrag = 0.9,
airAccel = -0.1, -- aka gravity, only effective out of water
airDrag = 0.995,
waterHitDrag = 0.5,
floatPoint = -26,
surfaceDampen = 10,
depthRequirement = -30,
stopSpeedLeeway = 0.05,
stopPositionLeeway = 0.1,
},
[UnitDefNames["amphimpulse"].id] = {
initialRiseSpeed = 5,
riseAccel = 0.20,
riseUpDrag = 0.99,
riseDownDrag = 0.7,
sinkAccel = -0.12,
sinkUpDrag = 0.9,
sinkDownDrag = 0.9,
airAccel = -0.2, -- aka gravity, only effective out of water
airDrag = 0.92,
waterHitDrag = 0.5,
floatPoint = -18,
surfaceDampen = 10,
depthRequirement = -30,
sinkTankRequirement = false,
stopSpeedLeeway = 0.05,
stopPositionLeeway = 0.1,
},
[UnitDefNames["amphriot"].id] = {
initialRiseSpeed = 3,
riseAccel = 0.13,
riseUpDrag = 0.95,
riseDownDrag = 0.9,
sinkAccel = -0.12,
sinkUpDrag = 0.9,
sinkDownDrag = 0.85,
airAccel = -0.1, -- aka gravity, only effective out of water
airDrag = 0.99,
waterHitDrag = 0.7,
floatPoint = -18,
surfaceDampen = 10,
depthRequirement = -20,
stopSpeedLeeway = 0.05,
stopPositionLeeway = 0.1,
surfaceWaitPos = -30,
surfaceMinWait = 80,
surfaceMaxWait = 120,
},
[UnitDefNames["amphsupport"].id] = {
initialRiseSpeed = 2.2,
riseAccel = 0.1,
riseUpDrag = 0.92,
riseDownDrag = 0.9,
sinkAccel = -0.12,
sinkUpDrag = 0.9,
sinkDownDrag = 0.85,
airAccel = -0.1, -- aka gravity, only effective out of water
airDrag = 0.99,
waterHitDrag = 0.3,
floatPoint = -22,
surfaceDampen = 10,
depthRequirement = -20,
stopSpeedLeeway = 0.05,
stopPositionLeeway = 0.1,
surfaceWaitPos = -30,
surfaceMinWait = 80,
surfaceMaxWait = 120,
},
-- This unit expels water with an air tank to float. It results in high rise
-- acceleration with low drag. To sink the tank must be filled with water
-- which results in a delay and low sink acceleration.
[UnitDefNames["amphfloater"].id] = {
initialRiseSpeed = 2,
riseAccel = 0.10,
riseUpDrag = 0.97,
riseDownDrag = 0.9,
sinkAccel = -0.10,
sinkUpDrag = 0.9,
sinkDownDrag = 0.9,
airAccel = -0.1, -- aka gravity, only effective out of water
airDrag = 0.995,
waterHitDrag = 0.8,
floatPoint = -20,
surfaceDampen = 10,
depthRequirement = -15,
stopSpeedLeeway = 0.05,
stopPositionLeeway = 0.1,
surfaceWaitPos = -30,
surfaceMinWait = 80,
surfaceMaxWait = 120,
},
-- Big epic unit moves up and down about as quickly as Atlantis
[UnitDefNames["amphassault"].id] = {
initialRiseSpeed = 1.5,
riseAccel = 0.06,
riseUpDrag = 0.9,
riseDownDrag = 0.7,
sinkAccel = -0.06,
sinkUpDrag = 0.9,
sinkDownDrag = 0.9,
airAccel = -0.3, -- aka gravity, only effective out of water
airDrag = 1,
waterHitDrag = 0.5,
floatPoint = -45,
surfaceDampen = 10,
depthRequirement = -40,
stopSpeedLeeway = 0.05,
stopPositionLeeway = 0.1,
},
}
for id, def in pairs (floatDefs) do
def.sinkOnPara = (UnitDefs[id].customParams.sink_on_emp ~= '0')
end
return floatDefs
| gpl-2.0 |
Anarchid/Zero-K | LuaRules/Configs/StartBoxes/IcySea-v2.lua | 17 | 2057 | return {
[0] = {
startpoints = {
{5120,2253},
},
boxes = {
{
{4915,2048},
{5325,2048},
{5325,2458},
{4915,2458},
},
},
},
[1] = {
startpoints = {
{5018,7987},
},
boxes = {
{
{4813,7782},
{5222,7782},
{5222,8192},
{4813,8192},
},
},
},
[2] = {
startpoints = {
{2253,5120},
},
boxes = {
{
{2048,4915},
{2458,4915},
{2458,5325},
{2048,5325},
},
},
},
[3] = {
startpoints = {
{8090,5222},
},
boxes = {
{
{7885,5018},
{8294,5018},
{8294,5427},
{7885,5427},
},
},
},
[4] = {
startpoints = {
{7168,3072},
},
boxes = {
{
{6963,2867},
{7373,2867},
{7373,3277},
{6963,3277},
},
},
},
[5] = {
startpoints = {
{2970,7270},
},
boxes = {
{
{2765,7066},
{3174,7066},
{3174,7475},
{2765,7475},
},
},
},
[6] = {
startpoints = {
{3072,3174},
},
boxes = {
{
{2867,2970},
{3277,2970},
{3277,3379},
{2867,3379},
},
},
},
[7] = {
startpoints = {
{7168,7373},
},
boxes = {
{
{6963,7168},
{7373,7168},
{7373,7578},
{6963,7578},
},
},
},
[8] = {
startpoints = {
{205,205},
},
boxes = {
{
{0,0},
{410,0},
{410,410},
{0,410},
},
},
},
[9] = {
startpoints = {
{10035,10035},
},
boxes = {
{
{9830,9830},
{10240,9830},
{10240,10240},
{9830,10240},
},
},
},
[10] = {
startpoints = {
{10035,205},
},
boxes = {
{
{9830,0},
{10240,0},
{10240,410},
{9830,410},
},
},
},
[11] = {
startpoints = {
{205,10035},
},
boxes = {
{
{0,9830},
{410,9830},
{410,10240},
{0,10240},
},
},
},
[12] = {
startpoints = {
{205,5120},
},
boxes = {
{
{0,4915},
{410,4915},
{410,5325},
{0,5325},
},
},
},
[13] = {
startpoints = {
{10035,5120},
},
boxes = {
{
{9830,4915},
{10240,4915},
{10240,5325},
{9830,5325},
},
},
},
}
| gpl-2.0 |
amircheshme/megatron | plugins/img_google.lua | 660 | 3196 | do
local mime = require("mime")
local google_config = load_from_file('data/google.lua')
local cache = {}
--[[
local function send_request(url)
local t = {}
local options = {
url = url,
sink = ltn12.sink.table(t),
method = "GET"
}
local a, code, headers, status = http.request(options)
return table.concat(t), code, headers, status
end]]--
local function get_google_data(text)
local url = "http://ajax.googleapis.com/ajax/services/search/images?"
url = url.."v=1.0&rsz=5"
url = url.."&q="..URL.escape(text)
url = url.."&imgsz=small|medium|large"
if google_config.api_keys then
local i = math.random(#google_config.api_keys)
local api_key = google_config.api_keys[i]
if api_key then
url = url.."&key="..api_key
end
end
local res, code = http.request(url)
if code ~= 200 then
print("HTTP Error code:", code)
return nil
end
local google = json:decode(res)
return google
end
-- Returns only the useful google data to save on cache
local function simple_google_table(google)
local new_table = {}
new_table.responseData = {}
new_table.responseDetails = google.responseDetails
new_table.responseStatus = google.responseStatus
new_table.responseData.results = {}
local results = google.responseData.results
for k,result in pairs(results) do
new_table.responseData.results[k] = {}
new_table.responseData.results[k].unescapedUrl = result.unescapedUrl
new_table.responseData.results[k].url = result.url
end
return new_table
end
local function save_to_cache(query, data)
-- Saves result on cache
if string.len(query) <= 7 then
local text_b64 = mime.b64(query)
if not cache[text_b64] then
local simple_google = simple_google_table(data)
cache[text_b64] = simple_google
end
end
end
local function process_google_data(google, receiver, query)
if google.responseStatus == 403 then
local text = 'ERROR: Reached maximum searches per day'
send_msg(receiver, text, ok_cb, false)
elseif google.responseStatus == 200 then
local data = google.responseData
if not data or not data.results or #data.results == 0 then
local text = 'Image not found.'
send_msg(receiver, text, ok_cb, false)
return false
end
-- Random image from table
local i = math.random(#data.results)
local url = data.results[i].unescapedUrl or data.results[i].url
local old_timeout = http.TIMEOUT or 10
http.TIMEOUT = 5
send_photo_from_url(receiver, url)
http.TIMEOUT = old_timeout
save_to_cache(query, google)
else
local text = 'ERROR!'
send_msg(receiver, text, ok_cb, false)
end
end
function run(msg, matches)
local receiver = get_receiver(msg)
local text = matches[1]
local text_b64 = mime.b64(text)
local cached = cache[text_b64]
if cached then
process_google_data(cached, receiver, text)
else
local data = get_google_data(text)
process_google_data(data, receiver, text)
end
end
return {
description = "Search image with Google API and sends it.",
usage = "!img [term]: Random search an image with Google API.",
patterns = {
"^!img (.*)$"
},
run = run
}
end
| gpl-2.0 |
Anarchid/Zero-K | scripts/shiptorpraider.lua | 3 | 2342 | include "constants.lua"
include "pieceControl.lua"
local hull, torp, turret, sonar, wake1, wake2 = piece ('Hull', 'Torp', 'Turret', 'Sonar', 'Wake1', 'Wake2')
local SIG_Aim = 2
local stuns = {false, false, false}
local disarmed = false
local moving = false
local sfxNum = 2
function script.setSFXoccupy(num)
sfxNum = num
end
local function RestoreAfterDelay()
SetSignalMask(SIG_Aim)
Sleep (5000)
Turn (turret, y_axis, 0, math.rad(30))
end
local function MoveScript()
while true do
if moving and not Spring.GetUnitIsCloaked(unitID) and (sfxNum == 1 or sfxNum == 2) then
EmitSfx(wake1, 3)
EmitSfx(wake2, 3)
end
Sleep(150)
end
end
function script.StopMoving()
moving = false
end
function script.StartMoving()
moving = true
end
function script.Activate()
Spin(sonar, y_axis, math.rad(60))
end
function script.Deactivate()
StopSpin(sonar, y_axis)
end
local function StunThread ()
disarmed = true
Signal (SIG_Aim)
GG.PieceControl.StopTurn (turret, y_axis)
end
local function UnstunThread ()
disarmed = false
RestoreAfterDelay()
end
function Stunned (stun_type)
stuns[stun_type] = true
StartThread (StunThread)
end
function Unstunned (stun_type)
stuns[stun_type] = false
if not stuns[1] and not stuns[2] and not stuns[3] then
StartThread (UnstunThread)
end
end
function script.Create()
StartThread(MoveScript)
StartThread(GG.Script.SmokeUnit, unitID, {hull, sonar, turret})
end
function script.AimFromWeapon(id)
return turret
end
function script.QueryWeapon(id)
return torp
end
function script.AimWeapon(id, heading, pitch)
Signal(SIG_Aim)
SetSignalMask(SIG_Aim)
while disarmed do
Sleep(34)
end
local slowMult = (Spring.GetUnitRulesParam(unitID,"baseSpeedMult") or 1)
Turn (turret, y_axis, heading, math.rad(300 * slowMult))
WaitForTurn (turret, y_axis)
StartThread (RestoreAfterDelay)
return true
end
function script.BlockShot(num, targetID)
return GG.Script.OverkillPreventionCheck(unitID, targetID, 180, 240, 28, 0.05, true, 100)
end
local explodables = {sonar, turret}
function script.Killed(severity, health)
severity = severity / health
for i = 1, #explodables do
if (math.random() < severity) then
Explode (explodables[i], SFX.FALL + SFX.FIRE + SFX.SMOKE)
end
end
if severity <= 0.5 then
return 1
else
Explode (hull, SFX.SHATTER)
return 2
end
end
| gpl-2.0 |
helingping/Urho3D | bin/Data/LuaScripts/23_Water.lua | 15 | 9916 | -- Water example.
-- This sample demonstrates:
-- - Creating a large plane to represent a water body for rendering
-- - Setting up a second camera to render reflections on the water surface
require "LuaScripts/Utilities/Sample"
local reflectionCameraNode = nil
local waterNode = nil
local waterPlane = Plane()
local waterClipPlane = Plane()
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create the scene content
CreateScene()
-- Create the UI content
CreateInstructions()
-- Setup the viewport for displaying the scene
SetupViewport()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_RELATIVE)
-- Hook up to the frame update event
SubscribeToEvents()
end
function CreateScene()
scene_ = Scene()
-- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
scene_:CreateComponent("Octree")
-- Create a Zone component for ambient lighting & fog control
local zoneNode = scene_:CreateChild("Zone")
local zone = zoneNode:CreateComponent("Zone")
zone.boundingBox = BoundingBox(-1000.0, 1000.0)
zone.ambientColor = Color(0.15, 0.15, 0.15)
zone.fogColor = Color(1.0, 1.0, 1.0)
zone.fogStart = 500.0
zone.fogEnd = 750.0
-- Create a directional light to the world. Enable cascaded shadows on it
local lightNode = scene_:CreateChild("DirectionalLight")
lightNode.direction = Vector3(0.6, -1.0, 0.8)
local light = lightNode:CreateComponent("Light")
light.lightType = LIGHT_DIRECTIONAL
light.castShadows = true
light.shadowBias = BiasParameters(0.00025, 0.5)
light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
light.specularIntensity = 0.5;
-- Apply slightly overbright lighting to match the skybox
light.color = Color(1.2, 1.2, 1.2);
-- Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
-- illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
-- generate the necessary 3D texture coordinates for cube mapping
local skyNode = scene_:CreateChild("Sky")
skyNode:SetScale(500.0) -- The scale actually does not matter
local skybox = skyNode:CreateComponent("Skybox")
skybox.model = cache:GetResource("Model", "Models/Box.mdl")
skybox.material = cache:GetResource("Material", "Materials/Skybox.xml")
-- Create heightmap terrain
local terrainNode = scene_:CreateChild("Terrain")
terrainNode.position = Vector3(0.0, 0.0, 0.0)
local terrain = terrainNode:CreateComponent("Terrain")
terrain.patchSize = 64
terrain.spacing = Vector3(2.0, 0.5, 2.0) -- Spacing between vertices and vertical resolution of the height map
terrain.smoothing = true
terrain.heightMap = cache:GetResource("Image", "Textures/HeightMap.png")
terrain.material = cache:GetResource("Material", "Materials/Terrain.xml")
-- The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
-- terrain patches and other objects behind it
terrain.occluder = true
-- Create 1000 boxes in the terrain. Always face outward along the terrain normal
local NUM_OBJECTS = 1000
for i = 1, NUM_OBJECTS do
local objectNode = scene_:CreateChild("Box")
local position = Vector3(Random(2000.0) - 1000.0, 0.0, Random(2000.0) - 1000.0)
position.y = terrain:GetHeight(position) + 2.25
objectNode.position = position
-- Create a rotation quaternion from up vector to terrain normal
objectNode.rotation = Quaternion(Vector3(0.0, 1.0, 0.0), terrain:GetNormal(position))
objectNode:SetScale(5.0)
local object = objectNode:CreateComponent("StaticModel")
object.model = cache:GetResource("Model", "Models/Box.mdl")
object.material = cache:GetResource("Material", "Materials/Stone.xml")
object.castShadows = true
end
-- Create a water plane object that is as large as the terrain
waterNode = scene_:CreateChild("Water")
waterNode.scale = Vector3(2048.0, 1.0, 2048.0)
waterNode.position = Vector3(0.0, 5.0, 0.0)
local water = waterNode:CreateComponent("StaticModel")
water.model = cache:GetResource("Model", "Models/Plane.mdl")
water.material = cache:GetResource("Material", "Materials/Water.xml")
-- Set a different viewmask on the water plane to be able to hide it from the reflection camera
water.viewMask = 0x80000000
-- Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside
-- the scene, because we want it to be unaffected by scene load / save
cameraNode = Node()
local camera = cameraNode:CreateComponent("Camera")
camera.farClip = 750.0
-- Set an initial position for the camera scene node above the floor
cameraNode.position = Vector3(0.0, 7.0, -20.0)
end
function CreateInstructions()
-- Construct new Text object, set string to display and font to use
local instructionText = ui.root:CreateChild("Text")
instructionText:SetText("Use WASD keys and mouse to move")
instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
instructionText.textAlignment = HA_CENTER
-- Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER
instructionText.verticalAlignment = VA_CENTER
instructionText:SetPosition(0, ui.root.height / 4)
end
function SetupViewport()
-- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
renderer:SetViewport(0, viewport)
-- Create a mathematical plane to represent the water in calculations
waterPlane = Plane(waterNode.worldRotation * Vector3(0.0, 1.0, 0.0), waterNode.worldPosition)
-- Create a downward biased plane for reflection view clipping. Biasing is necessary to avoid too aggressive clipping
waterClipPlane = Plane(waterNode.worldRotation * Vector3(0.0, 1.0, 0.0), waterNode.worldPosition -
Vector3(0.0, 0.1, 0.0))
-- Create camera for water reflection
-- It will have the same farclip and position as the main viewport camera, but uses a reflection plane to modify
-- its position when rendering
reflectionCameraNode = cameraNode:CreateChild()
local reflectionCamera = reflectionCameraNode:CreateComponent("Camera")
reflectionCamera.farClip = 750.0
reflectionCamera.viewMask = 0x7fffffff -- Hide objects with only bit 31 in the viewmask (the water plane)
reflectionCamera.autoAspectRatio = false
reflectionCamera.useReflection = true
reflectionCamera.reflectionPlane = waterPlane
reflectionCamera.useClipping = true -- Enable clipping of geometry behind water plane
reflectionCamera.clipPlane = waterClipPlane
-- The water reflection texture is rectangular. Set reflection camera aspect ratio to match
reflectionCamera.aspectRatio = graphics.width / graphics.height
-- View override flags could be used to optimize reflection rendering. For example disable shadows
--reflectionCamera.viewOverrideFlags = VO_DISABLE_SHADOWS
-- Create a texture and setup viewport for water reflection. Assign the reflection texture to the diffuse
-- texture unit of the water material
local texSize = 1024
local renderTexture = Texture2D:new()
renderTexture:SetSize(texSize, texSize, Graphics:GetRGBFormat(), TEXTURE_RENDERTARGET)
renderTexture.filterMode = FILTER_BILINEAR
local surface = renderTexture.renderSurface
local rttViewport = Viewport:new(scene_, reflectionCamera)
surface:SetViewport(0, rttViewport)
local waterMat = cache:GetResource("Material", "Materials/Water.xml")
waterMat:SetTexture(TU_DIFFUSE, renderTexture)
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate")
end
function MoveCamera(timeStep)
-- Do not move if the UI has a focused element (the console)
if ui.focusElement ~= nil then
return
end
-- Movement speed as world units per second
local MOVE_SPEED = 20.0
-- Mouse sensitivity as degrees per pixel
local MOUSE_SENSITIVITY = 0.1
-- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
local mouseMove = input.mouseMove
yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
pitch = Clamp(pitch, -90.0, 90.0)
-- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
-- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if input:GetKeyDown(KEY_W) then
cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_S) then
cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_A) then
cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_D) then
cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
-- In case resolution has changed, adjust the reflection camera aspect ratio
local reflectionCamera = reflectionCameraNode:GetComponent("Camera")
reflectionCamera.aspectRatio = graphics.width / graphics.height
end
function HandleUpdate(eventType, eventData)
-- Take the frame time step, which is stored as a float
local timeStep = eventData["TimeStep"]:GetFloat()
-- Move the camera, scale movement with time step
MoveCamera(timeStep)
end
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.