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 |
|---|---|---|---|---|---|
caesarxuchao/contrib | ingress/controllers/nginx/lua/vendor/lua-resty-http/lib/resty/http_headers.lua | 69 | 1716 | local rawget, rawset, setmetatable =
rawget, rawset, setmetatable
local str_gsub = string.gsub
local str_lower = string.lower
local _M = {
_VERSION = '0.01',
}
-- Returns an empty headers table with internalised case normalisation.
-- Supports the same cases as in ngx_lua:
--
-- headers.content_length
-- headers["content-length"]
-- headers["Content-Length"]
function _M.new(self)
local mt = {
normalised = {},
}
mt.__index = function(t, k)
local k_hyphened = str_gsub(k, "_", "-")
local matched = rawget(t, k)
if matched then
return matched
else
local k_normalised = str_lower(k_hyphened)
return rawget(t, mt.normalised[k_normalised])
end
end
-- First check the normalised table. If there's no match (first time) add an entry for
-- our current case in the normalised table. This is to preserve the human (prettier) case
-- instead of outputting lowercased header names.
--
-- If there's a match, we're being updated, just with a different case for the key. We use
-- the normalised table to give us the original key, and perorm a rawset().
mt.__newindex = function(t, k, v)
-- we support underscore syntax, so always hyphenate.
local k_hyphened = str_gsub(k, "_", "-")
-- lowercase hyphenated is "normalised"
local k_normalised = str_lower(k_hyphened)
if not mt.normalised[k_normalised] then
mt.normalised[k_normalised] = k_hyphened
rawset(t, k_hyphened, v)
else
rawset(t, mt.normalised[k_normalised], v)
end
end
return setmetatable({}, mt)
end
return _M
| apache-2.0 |
ophal/core | includes/module.lua | 1 | 2228 | local xtable = seawolf.contrib.seawolf_table
do
local mt = {
register = function(t, module_name, module_definition)
ophal.modules[module_name] = module_definition
end
}
mt.__index = function(t, k)
if mt[k] ~= nil then
return mt[k]
end
end
setmetatable(ophal.modules, mt)
end
do
local order, group
local list = xtable{'system'}
--[[ Return the list of active modules by weight and name
]]
function module_list()
if nil == order then
local rawset = rawset
order, group = xtable(), xtable()
-- Force system module to stay first ALWAYS
settings.modules.system = nil
-- Group modules by their weight
for name, weight in pairs(settings.modules) do
-- Ignore disabled modules
if weight == false then break end
if weight == true then
weight = 1
end
if nil == group[weight] then
rawset(group, weight, xtable{name})
order:append(weight)
else
group[weight]:append(name)
end
end
-- Sort weights
order:sort()
-- Build list of module names
for k, weight in pairs(order) do
-- Sort alphabetically
group[weight]:sort()
-- Add modules in current group to the list of names
for j, name in pairs(group[weight]) do
list:append(name)
end
end
end
return list
end
end
function module_invoke_all(hook, ...)
local err
local result, r = {}
for _, name in pairs(module_list()) do
local m = ophal.modules[name]
if m and m[hook] then
r, err = m[hook](...) -- call hook implementation
if err then
return nil, err
end
if type(r) == 'table' then
for k, v in pairs(r) do
v.module = name -- register module name
result[k] = v
end
elseif r then
table.insert(result, r)
end
end
end
return result
end
function module_load(name)
local status, err = pcall(require, 'modules.' .. name .. '.init')
if not status then
print('bootstrap: ' .. err)
end
end
function module_load_all()
for _, name in pairs(module_list()) do
module_load(name)
end
end
| agpl-3.0 |
wonderwj/ffi-zmq | rpc/init.lua | 1 | 3377 | local zmq = require('zmq');
local core= require('core');
local utils= require('utils');
local timer= require('timer');
local encode = require('msgpack').encode;
local decode = require('msgpack').decode;
local rpc_svr = core.Emitter:extend();
-- linkaddr bind listen addr
-- dispaddr send response addr
function rpc_svr:initialize(linkaddr, dispaddr)
self._sock = zmq.bind_socket(zmq.PULL, linkaddr,
utils.bind(self._onData, self))
self._sendsock = zmq.bind_socket(zmq.PUB, dispaddr);
self._clients = {};
self._links = {};
self._cid_index = 1; --客户端ID记录
self._cnt = 0;
end
-- 请求参数
-- {ctx = {}, p = {}}
-- 其中ctx是保留信息,即请求的上下文
-- p当前调用的参数
-- ctx中的数据可能有
-- cid -- 客户端ID
-- cmd -- 调用的方法名称
-- rid -- 请求的上下文ID
function rpc_svr:_onData(d)
local cname = d[1];
local req = decode(d[2]);
self._cnt = self._cnt + 1;
if math.fmod(self._cnt, 1000) == 0 then
p(os.date(), 'call count->', self._cnt);
end
-- p(os.date(), 'call->', cname, req);
local ctx = req.ctx;
local p = req.p;
local fn = self[ctx.cmd];
local res= nil;
if fn then
local e = {
ctx = ctx;
cname = cname;
};
setfenv(fn, setmetatable(e, {__index = _G}));
local ret = {fn(self, unpack(p))};
ctx.ret = 0;
res = {
ctx = ctx;
r = ret;
};
else
ctx.ret = -1;
res = {
ctx = ctx;
};
end
if res then
self._sendsock:send({cname, encode(res)});
end
end
--连接请求
--cbaddr 回拨地址
function rpc_svr:_sys_connect(cbaddr)
p(os.date(), 'sys_connect->', cbaddr);
local cid = string.format('c_%d', self._cid_index);
self._cid_index = self._cid_index + 1;
ctx.cid = cid;
return cid;
end
exports.server = rpc_svr;
------------------ client class --------------------
local rpc_client = core.Emitter:extend();
function rpc_client:initialize(svraddr, resaddr, cname)
self._sock = zmq.socket(zmq.PUSH);
self._resock = zmq.socket(zmq.SUB);
self._resock:on('data', utils.bind(self._onData, self))
self._resock:connect(resaddr);
self._resock:setopt(zmq.SUBSCRIBE, cname)
self._sock:connect(svraddr);
self._name = cname;
self._rid = 1;
self._callback = {};
self:call('_sys_connect', function(cid)
self._cid = cid;
self:emit('connected')
end)
end
function rpc_client:close()
self._sock:close();
self._resock:close();
end
function rpc_client:_onData(d)
local cname = d[1];
if cname ~= self._name then
p(os.date(), 'is not my data->', cname);
end
local res = decode(d[2]);
local ctx = res.ctx;
local r = res.r;
--p('return ->', cname, res);
if ctx.ret == 0 then --suc
local f = self._callback[ctx.rid or 0];
if f then
f(unpack(r));
end
end
end
--远程调用
function rpc_client:call(name, ...)
local n = select('#', ...);
local arg = {...};
if type(arg[n]) == 'function' then
self._callback[self._rid] = arg[n];
table.remove(arg, n);
end
local ctx =
{
cmd = name;
rid = self._rid;
};
self._rid = self._rid + 1;
--self._sock:send({self._name, encode({ctx = ctx, p = arg})}, zmq.DONTWAIT);
self._sock:send({self._name, encode({ctx = ctx, p = arg})});
end
exports.client = rpc_client;
| mit |
mesosphere-mergebot/dcos | packages/adminrouter/extra/src/lib/cache.lua | 3 | 27876 | local cjson_safe = require "cjson.safe"
local shmlock = require "resty.lock"
local http = require "resty.http"
local resolver = require "resty.resolver"
local util = require "util"
-- In order to make caching code testable, these constants need to be
-- configurable/exposed through env vars.
--
-- Values assigned to these variable need to fulfil following condition:
--
-- CACHE_FIRST_POLL_DELAY << CACHE_EXPIRATION < CACHE_POLL_PERIOD < CACHE_MAX_AGE_SOFT_LIMIT < CACHE_MAX_AGE_HARD_LIMIT
--
-- There are 3 requests (2xMarathon + Mesos) made to upstream components.
-- The cache should be kept locked for the whole time until
-- the responses are received from all the components. Therefore,
-- 3 * (CACHE_BACKEND_REQUEST_TIMEOUT + 2) <= CACHE_REFRESH_LOCK_TIMEOUT
-- The 2s delay between requests is choosen arbitrarily.
-- On the other hand, the documentation
-- (https://github.com/openresty/lua-resty-lock#new) says that the
-- CACHE_REFRESH_LOCK_TIMEOUT should not exceed the expiration time, which
-- is equal to 3 * (CACHE_BACKEND_REQUEST_TIMEOUT + 2). Taking into account
-- both constraints, we would have to set CACHE_REFRESH_LOCK_TIMEOUT =
-- 3 * (CACHE_BACKEND_REQUEST_TIMEOUT + 2). We set it to
-- 3 * CACHE_BACKEND_REQUEST_TIMEOUT hoping that the 2 requests to Marathon and
-- 1 request to Mesos will be done immediately one after another.
-- Before changing CACHE_POLL_INTERVAL, please check the comment for resolver
-- CACHE_BACKEND_REQUEST_TIMEOUT << CACHE_REFRESH_LOCK_TIMEOUT
--
-- Before changing CACHE_POLL_PERIOD, please check the comment for resolver
-- statement configuration in includes/http/master.conf
--
-- Initial timer-triggered cache update early after nginx startup:
-- It makes sense to have this initial timer-triggered cache
-- update _early_ after nginx startup at all, and it makes sense to make it
-- very early, so that we reduce the likelihood for an HTTP request to be slowed
-- down when it is incoming _before_ the normally scheduled periodic cache
-- update (example: the HTTP request comes in 15 seconds after nginx startup,
-- and the first regular timer-triggered cache update is triggered only 25
-- seconds after nginx startup).
--
-- It makes sense to have this time window not be too narrow, especially not
-- close to 0 seconds: under a lot of load there *will* be HTTP requests
-- incoming before the initial timer-triggered update, even if the first
-- timer callback is scheduled to be executed after 0 seconds.
-- There is code in place for handling these HTTP requests, and that code path
-- must be kept explicit, regularly exercised, and well-tested. There is a test
-- harness test that tests/exercises it, but it overrides the default values
-- with the ones that allow for testability. So the idea is that we leave
-- initial update scheduled after 2 seconds, as opposed to 0 seconds.
--
-- All are in units of seconds. Below are the defaults:
local _CONFIG = {}
local env_vars = {CACHE_FIRST_POLL_DELAY = 2,
CACHE_POLL_PERIOD = 25,
CACHE_EXPIRATION = 20,
CACHE_MAX_AGE_SOFT_LIMIT = 75,
CACHE_MAX_AGE_HARD_LIMIT = 259200,
CACHE_BACKEND_REQUEST_TIMEOUT = 60,
CACHE_REFRESH_LOCK_TIMEOUT = 180,
}
for key, value in pairs(env_vars) do
-- yep, we are OK with key==nil, tonumber will just return nil
local env_var_val = tonumber(os.getenv(key))
if env_var_val == nil or env_var_val == value then
ngx.log(ngx.DEBUG, "Using default ".. key .. " value: `" .. value .. "` seconds")
_CONFIG[key] = value
else
ngx.log(ngx.NOTICE,
key .. " overridden by ENV to `" .. env_var_val .. "` seconds")
_CONFIG[key] = env_var_val
end
end
local function cache_data(key, value)
-- Store key/value pair to SHM cache (shared across workers).
-- Return true upon success, false otherwise.
-- Expected to run within lock context.
local cache = ngx.shared.cache
local success, err, forcible = cache:set(key, value)
if success then
return true
end
ngx.log(
ngx.ERR,
"Could not store " .. key .. " to state cache: " .. err
)
return false
end
local function request(url, accept_404_reply, auth_token)
-- We need to make sure that Nginx does not reuse the TCP connection here,
-- as i.e. during failover it could result in fetching data from e.g. Mesos
-- master which already abdicated. On top of that we also need to force
-- re-resolving leader.mesos address which happens during the setup of the
-- new connection.
local headers = {
["User-Agent"] = "Master Admin Router",
["Connection"] = "close",
}
if auth_token ~= nil then
headers["Authorization"] = "token=" .. auth_token
end
-- Use cosocket-based HTTP library, as ngx subrequests are not available
-- from within this code path (decoupled from nginx' request processing).
-- The timeout parameter is given in milliseconds. The `request_uri`
-- method takes care of parsing scheme, host, and port from the URL.
local httpc = http.new()
httpc:set_timeout(_CONFIG.CACHE_BACKEND_REQUEST_TIMEOUT * 1000)
local res, err = httpc:request_uri(url, {
method="GET",
headers=headers,
ssl_verify=true
})
if not res then
return nil, err
end
if res.status ~= 200 then
if accept_404_reply and res.status ~= 404 or not accept_404_reply then
return nil, "invalid response status: " .. res.status
end
end
ngx.log(
ngx.NOTICE,
"Request url: " .. url .. " " ..
"Response Body length: " .. string.len(res.body) .. " bytes."
)
return res, nil
end
local function is_container_network(app)
-- Networking mode for a Marathon application is defined in
-- app["networks"][1]["mode"].
local container = app["container"]
local network = app["networks"][1]
return container and network and (network["mode"] == "container")
end
local function fetch_and_store_marathon_apps(auth_token)
-- Access Marathon through localhost.
ngx.log(ngx.NOTICE, "Cache Marathon app state")
local appsRes, err = request(UPSTREAM_MARATHON .. "/v2/apps?embed=apps.tasks&label=DCOS_SERVICE_NAME",
false,
auth_token)
if err then
ngx.log(ngx.NOTICE, "Marathon app request failed: " .. err)
return
end
local apps, err = cjson_safe.decode(appsRes.body)
if not apps then
ngx.log(ngx.WARN, "Cannot decode Marathon apps JSON: " .. err)
return
end
local svcApps = {}
for _, app in ipairs(apps["apps"]) do
local appId = app["id"]
local labels = app["labels"]
if not labels then
ngx.log(ngx.NOTICE, "Labels not found in app '" .. appId .. "'")
goto continue
end
-- Service name should exist as we asked Marathon for it
local svcId = util.normalize_service_name(labels["DCOS_SERVICE_NAME"])
local scheme = labels["DCOS_SERVICE_SCHEME"]
if not scheme then
ngx.log(ngx.NOTICE, "Cannot find DCOS_SERVICE_SCHEME for app '" .. appId .. "'")
goto continue
end
local portIdx = labels["DCOS_SERVICE_PORT_INDEX"]
if not portIdx then
ngx.log(ngx.NOTICE, "Cannot find DCOS_SERVICE_PORT_INDEX for app '" .. appId .. "'")
goto continue
end
local portIdx = tonumber(portIdx)
if not portIdx then
ngx.log(ngx.NOTICE, "Cannot convert port to number for app '" .. appId .. "'")
goto continue
end
-- Lua arrays default starting index is 1 not the 0 of marathon
portIdx = portIdx + 1
local tasks = app["tasks"]
-- Process only tasks in TASK_RUNNING state.
-- From http://lua-users.org/wiki/TablesTutorial: "inside a pairs loop,
-- it's safe to reassign existing keys or remove them"
for i, t in ipairs(tasks) do
if t["state"] ~= "TASK_RUNNING" then
table.remove(tasks, i)
end
end
-- next() returns nil if table is empty.
local i, task = next(tasks)
if i == nil then
ngx.log(ngx.NOTICE, "No task in state TASK_RUNNING for app '" .. appId .. "'")
goto continue
end
ngx.log(
ngx.NOTICE,
"Reading state for appId '" .. appId .. "' from task with id '" .. task["id"] .. "'"
)
local host_or_ip = task["host"] --take host by default
-- In "container" networking mode the task/container will get its own IP
-- (ip-per-container).
-- The task will be reachable:
-- 1) through the container port defined in portMappings.
-- If the app is using DC/OS overlay network
-- it will be also reachable on
-- 2) task["host"]:task["ports"][portIdx] (<private agent IP>:<hostPort>).
-- However, in case of CNI networks (e.g. Calico), the task might not be
-- reachable on task["host"]:task["ports"][portIdx], so we choose option 2)
-- for routing.
if is_container_network(app) then
ngx.log(ngx.NOTICE, "app '" .. appId .. "' is in a container network")
-- override with the ip of the task
local task_ip_addresses = task["ipAddresses"]
if task_ip_addresses then
host_or_ip = task_ip_addresses[1]["ipAddress"]
else
ngx.log(ngx.NOTICE, "no ip address allocated yet for app '" .. appId .. "'")
goto continue
end
end
if not host_or_ip then
ngx.log(ngx.NOTICE, "Cannot find host or ip for app '" .. appId .. "'")
goto continue
end
-- In "container" mode we find the container port out from portMappings array
-- for the case when container port is fixed (non-zero value specified).
-- When container port is specified as 0 it will be set the same as the host port:
-- https://mesosphere.github.io/marathon/docs/ports.html#random-port-assignment
-- We do not override it with container port from the portMappings array
-- in that case.
-- In "container/bridge" and "host" networking modes we need to use the
-- host port for routing (available via task's ports array)
if is_container_network(app) and app["container"]["portMappings"][portIdx]["containerPort"] ~= 0 then
port = app["container"]["portMappings"][portIdx]["containerPort"]
else
port = task["ports"][portIdx]
end
if not port then
ngx.log(ngx.NOTICE, "Cannot find port at Marathon port index '" .. (portIdx - 1) .. "' for app '" .. appId .. "'")
goto continue
end
-- Details on how Admin Router interprets DCOS_SERVICE_REWRITE_REQUEST_URLS label:
-- https://github.com/dcos/dcos/blob/master/packages/adminrouter/extra/src/README.md#disabling-url-path-rewriting-for-selected-applications
local do_rewrite_req_url = labels["DCOS_SERVICE_REWRITE_REQUEST_URLS"]
if do_rewrite_req_url == false or do_rewrite_req_url == 'false' then
ngx.log(ngx.INFO, "DCOS_SERVICE_REWRITE_REQUEST_URLS for app '" .. appId .. "' set to 'false'")
do_rewrite_req_url = false
else
-- Treat everything else as true, i.e.:
-- * label is absent
-- * label is set to "true" (string) or true (bool)
-- * label is set to some random string
do_rewrite_req_url = true
end
-- Details on how Admin Router interprets DCOS_SERVICE_REQUEST_BUFFERING label:
-- https://github.com/dcos/dcos/blob/master/packages/adminrouter/extra/src/README.md#disabling-request-buffering-for-selected-applications
local do_request_buffering = labels["DCOS_SERVICE_REQUEST_BUFFERING"]
if do_request_buffering == false or do_request_buffering == 'false' then
ngx.log(ngx.INFO, "DCOS_SERVICE_REQUEST_BUFFERING for app '" .. appId .. "' set to 'false'")
do_request_buffering = false
else
-- Treat everything else as true, i.e.:
-- * label is absent
-- * label is set to "true" (string) or true (bool)
-- * label is set to some random string
do_request_buffering = true
end
local url = scheme .. "://" .. host_or_ip .. ":" .. port
svcApps[svcId] = {
scheme=scheme,
url=url,
do_rewrite_req_url=do_rewrite_req_url,
do_request_buffering=do_request_buffering,
}
::continue::
end
svcApps_json = cjson_safe.encode(svcApps)
ngx.log(ngx.DEBUG, "Storing Marathon apps data to SHM.")
if not cache_data("svcapps", svcApps_json) then
ngx.log(ngx.ERR, "Storing marathon apps cache failed")
return
end
ngx.update_time()
local time_now = ngx.now()
if cache_data("svcapps_last_refresh", time_now) then
ngx.log(ngx.INFO, "Marathon apps cache has been successfully updated")
end
return
end
function store_leader_data(leader_name, leader_ip)
if HOST_IP == 'unknown' or leader_ip == 'unknown' then
ngx.log(ngx.ERR,
"Private IP address of the host is unknown, aborting cache-entry creation for ".. leader_name .. " leader")
mleader = '{"is_local": "unknown", "leader_ip": null}'
elseif leader_ip == HOST_IP then
mleader = '{"is_local": "yes", "leader_ip": "'.. HOST_IP ..'"}'
ngx.log(ngx.INFO, leader_name .. " leader is local")
else
mleader = '{"is_local": "no", "leader_ip": "'.. leader_ip ..'"}'
ngx.log(ngx.INFO, leader_name .. " leader is non-local: `" .. leader_ip .. "`")
end
ngx.log(ngx.DEBUG, "Storing " .. leader_name .. " leader to SHM")
if not cache_data(leader_name .. "_leader", mleader) then
ngx.log(ngx.ERR, "Storing " .. leader_name .. " leader cache failed")
return
end
ngx.update_time()
local time_now = ngx.now()
if cache_data(leader_name .. "_leader_last_refresh", time_now) then
ngx.log(ngx.INFO, leader_name .. " leader cache has been successfully updated")
end
return
end
local function fetch_generic_leader(leaderAPI_url, leader_name, auth_token)
local mleaderRes, err = request(leaderAPI_url, true, auth_token)
if err then
ngx.log(ngx.WARN, leader_name .. " leader request failed: " .. err)
return nil
end
-- We need to translate 404 reply into a JSON that is easy to process for
-- endpoints. I.E.:
-- https://mesosphere.github.io/marathon/docs/rest-api.html#get-v2-leader
local res_body
if mleaderRes.status == 404 then
-- Just a hack in order to avoid using gotos - create a substitute JSON
-- that can be parsed and processed by normal execution path and at the
-- same time passes the information of a missing Marathon leader.
ngx.log(ngx.NOTICE, "Using empty " .. leader_name .. " leader JSON")
res_body = '{"leader": "unknown:0"}'
else
res_body = mleaderRes.body
end
local mleader, err = cjson_safe.decode(res_body)
if not mleader then
ngx.log(ngx.WARN, "Cannot decode " .. leader_name .. " leader JSON: " .. err)
return nil
end
return mleader['leader']:split(":")[1]
end
local function fetch_and_store_marathon_leader(auth_token)
leader_ip = fetch_generic_leader(
UPSTREAM_MARATHON .. "/v2/leader", "marathon", auth_token)
if leader_ip ~= nil then
store_leader_data("marathon", leader_ip)
end
end
local function fetch_and_store_state_mesos(auth_token)
-- Fetch state JSON summary from Mesos. If successful, store to SHM cache.
-- Expected to run within lock context.
local response, err = request(UPSTREAM_MESOS .. "/master/state-summary",
false,
auth_token)
if err then
ngx.log(ngx.NOTICE, "Mesos state request failed: " .. err)
return
end
local raw_state_summary, err = cjson_safe.decode(response.body)
if not raw_state_summary then
ngx.log(ngx.WARN, "Cannot decode Mesos state-summary JSON: " .. err)
return
end
local parsed_state_summary = {}
parsed_state_summary['f_by_id'] = {}
parsed_state_summary['f_by_name'] = {}
parsed_state_summary['agent_pids'] = {}
for _, framework in ipairs(raw_state_summary["frameworks"]) do
local f_id = framework["id"]
local f_name = util.normalize_service_name(framework["name"])
parsed_state_summary['f_by_id'][f_id] = {}
parsed_state_summary['f_by_id'][f_id]['webui_url'] = framework["webui_url"]
parsed_state_summary['f_by_id'][f_id]['name'] = f_name
parsed_state_summary['f_by_name'][f_name] = {}
parsed_state_summary['f_by_name'][f_name]['webui_url'] = framework["webui_url"]
end
for _, agent in ipairs(raw_state_summary["slaves"]) do
a_id = agent["id"]
parsed_state_summary['agent_pids'][a_id] = agent["pid"]
end
local parsed_state_summary_json = cjson_safe.encode(parsed_state_summary)
ngx.log(ngx.DEBUG, "Storing parsed Mesos state to SHM.")
if not cache_data("mesosstate", parsed_state_summary_json) then
ngx.log(ngx.WARN, "Storing parsed Mesos state to cache failed")
return
end
ngx.update_time()
local time_now = ngx.now()
if cache_data("mesosstate_last_refresh", time_now) then
ngx.log(ngx.INFO, "Mesos state cache has been successfully updated")
end
return
end
local function fetch_mesos_leader_state()
-- Lua forbids jumping over local variables definition, hence we define all
-- of them here.
local r, err, answers
-- We want to use Navstar's dual-dispatch approach and get the response
-- as fast as possible from any operational MesosDNS. If we set it to local
-- instance, its failure will break this part of the cache as well.
--
-- As for the DNS TTL - we're on purpose ignoring it and going with own
-- refresh cycle period. Assuming that Navstar and MesosDNS do not do
-- caching on their own, we just treat DNS as an interface to obtain
-- current mesos leader data. How long we cache it is just an internal
-- implementation detail of AR.
--
-- Also, see https://github.com/openresty/lua-resty-dns#limitations
r, err = resolver:new{
nameservers = {{"198.51.100.1", 53},
{"198.51.100.2", 53},
{"198.51.100.3", 53}},
retrans = 3, -- retransmissions on receive timeout
timeout = 2000, -- msec
}
if not r then
ngx.log(ngx.ERR, "Failed to instantiate the resolver: " .. err)
return nil
end
answers, err = r:query("leader.mesos")
if not answers then
ngx.log(ngx.ERR, "Failed to query the DNS server: " .. err)
return nil
end
if answers.errcode then
ngx.log(ngx.ERR,
"DNS server returned error code: " .. answers.errcode .. ": " .. answers.errstr)
return nil
end
if util.table_len(answers) == 0 then
ngx.log(ngx.ERR,
"DNS server did not return anything for leader.mesos")
return nil
end
-- Yes, we are assuming that leader.mesos will always be just one A entry.
-- AAAA support is a different thing...
return answers[1].address
end
local function fetch_and_store_mesos_leader()
leader_ip = fetch_mesos_leader_state()
if leader_ip ~= nil then
store_leader_data("mesos", leader_ip)
end
end
local function refresh_needed(ts_name)
-- ts_name (str): name of the '*_last_refresh' timestamp to check
local cache = ngx.shared.cache
local last_fetch_time = cache:get(ts_name)
-- Handle the special case of first invocation.
if not last_fetch_time then
ngx.log(ngx.INFO, "Cache `".. ts_name .. "` empty. Fetching.")
return true
end
ngx.update_time()
local cache_age = ngx.now() - last_fetch_time
if cache_age > _CONFIG.CACHE_EXPIRATION then
ngx.log(ngx.INFO, "Cache `".. ts_name .. "` expired. Refresh.")
return true
end
ngx.log(ngx.DEBUG, "Cache `".. ts_name .. "` populated and fresh. NOOP.")
return false
end
local function refresh_cache(from_timer, auth_token)
-- Refresh cache in case when it expired or has not been created yet.
-- Use SHM-based lock for synchronizing coroutines across worker processes.
--
-- This function can be invoked via two mechanisms:
--
-- * Via ngx.timer (in a coroutine), which is triggered
-- periodically in all worker processes for performing an
-- out-of-band cache refresh (this is the usual mode of operation).
-- In that case, perform cache invalidation only if no other timer
-- instance currently does so (abort if lock cannot immediately be
-- acquired).
--
-- * During HTTP request processing, when cache content is
-- required for answering the request but the cache was not
-- populated yet (i.e. usually early after nginx startup).
-- In that case, return from this function only after the cache
-- has been populated (block on lock acquisition).
--
-- Args:
-- from_timer: set to true if invoked from a timer
-- Acquire lock.
local lock
-- In order to avoid deadlocks, we are relying on `exptime` param of
-- resty.lock (https://github.com/openresty/lua-resty-lock#new)
--
-- It's value is maximum time it may take to fetch data from all the
-- backends (ATM 2xMarathon + Mesos) plus an arbitrary two seconds period
-- just to be on the safe side.
local lock_ttl = 3 * (_CONFIG.CACHE_BACKEND_REQUEST_TIMEOUT + 2)
if from_timer then
ngx.log(ngx.INFO, "Executing cache refresh triggered by timer")
-- Fail immediately if another worker currently holds
-- the lock, because a single timer-based update at any
-- given time suffices.
lock = shmlock:new("shmlocks", {timeout=0, exptime=lock_ttl})
local elapsed, err = lock:lock("cache")
if elapsed == nil then
ngx.log(ngx.INFO, "Timer-based update is in progress. NOOP.")
return
end
else
ngx.log(ngx.INFO, "Executing cache refresh triggered by request")
-- Cache content is required for current request
-- processing. Wait for lock acquisition, for at
-- most _CONFIG.CACHE_REFRESH_LOCK_TIMEOUT * 3 seconds (2xMarathon +
-- 1 Mesos request).
lock = shmlock:new("shmlocks", {timeout=_CONFIG.CACHE_REFRESH_LOCK_TIMEOUT,
exptime=lock_ttl })
local elapsed, err = lock:lock("cache")
if elapsed == nil then
ngx.log(ngx.ERR, "Could not acquire lock: " .. err)
-- Leave early (did not make sure that cache is populated).
return
end
end
if refresh_needed("mesosstate_last_refresh") then
fetch_and_store_state_mesos(auth_token)
end
if refresh_needed("svcapps_last_refresh") then
fetch_and_store_marathon_apps(auth_token)
end
if refresh_needed("marathon_leader_last_refresh") then
fetch_and_store_marathon_leader(auth_token)
end
if refresh_needed("mesos_leader_last_refresh") then
fetch_and_store_mesos_leader()
end
local ok, err = lock:unlock()
if not ok then
-- If this fails, an unlock happens automatically via `exptime` lock
-- param described earlier.
ngx.log(ngx.ERR, "Failed to unlock cache shmlock: " .. err)
end
end
local function periodically_refresh_cache(auth_token)
-- This function is invoked from within init_worker_by_lua code.
-- ngx.timer.every() is called here, a more robust alternative to
-- ngx.timer.at() as suggested by the openresty/lua-nginx-module
-- documentation:
-- https://github.com/openresty/lua-nginx-module/tree/v0.10.9#ngxtimerat
-- See https://jira.mesosphere.com/browse/DCOS-38248 for details on the
-- cache update problems caused by the recursive use of ngx.timer.at()
timerhandler = function(premature)
-- Handler for periodic timer invocation.
-- Premature timer execution: worker process tries to shut down.
if premature then
return
end
-- Invoke timer business logic.
refresh_cache(true, auth_token)
end
-- Trigger the initial cache update CACHE_FIRST_POLL_DELAY seconds after
-- Nginx startup.
local ok, err = ngx.timer.at(_CONFIG.CACHE_FIRST_POLL_DELAY, timerhandler)
if not ok then
ngx.log(ngx.ERR, "Failed to create timer: " .. err)
return
else
ngx.log(ngx.INFO, "Created initial timer for cache updating.")
end
-- Trigger the timer, every CACHE_POLL_PERIOD seconds after
-- Nginx startup.
local ok, err = ngx.timer.every(_CONFIG.CACHE_POLL_PERIOD, timerhandler)
if not ok then
ngx.log(ngx.ERR, "Failed to create timer: " .. err)
return
else
ngx.log(ngx.INFO, "Created periodic timer for cache updating.")
end
end
local function get_cache_entry(name, auth_token)
local cache = ngx.shared.cache
local name_last_refresh = name .. "_last_refresh"
-- Handle the special case of very early request - before the first
-- timer-based cache refresh
local entry_last_refresh = cache:get(name_last_refresh)
if entry_last_refresh == nil then
refresh_cache(false, auth_token)
entry_last_refresh = cache:get(name .. "_last_refresh")
if entry_last_refresh == nil then
-- Something is really broken, abort!
ngx.log(ngx.ERR, "Could not retrieve last refresh time for `" .. name .. "` cache entry")
return nil
end
end
-- Check the clock
ngx.update_time()
local cache_age = ngx.now() - entry_last_refresh
-- Cache is too old, we can't use it:
if cache_age > _CONFIG.CACHE_MAX_AGE_HARD_LIMIT then
ngx.log(ngx.ERR, "Cache entry `" .. name .. "` is too old, aborting request")
return nil
end
-- Cache is stale, but still usable:
if cache_age > _CONFIG.CACHE_MAX_AGE_SOFT_LIMIT then
ngx.log(ngx.NOTICE, "Cache entry `" .. name .. "` is stale")
end
local entry_json = cache:get(name)
if entry_json == nil then
ngx.log(ngx.ERR, "Could not retrieve `" .. name .. "` cache entry from SHM")
return nil
end
local entry, err = cjson_safe.decode(entry_json)
if entry == nil then
ngx.log(ngx.ERR, "Cannot decode JSON for entry `" .. entry_json .. "`: " .. err)
return nil
end
return entry
end
-- Expose Admin Router cache interface
local _M = {}
function _M.init(auth_token)
-- At some point auth_token passing will be refactored out in
-- favour of service accounts support.
local res = {}
if auth_token ~= nil then
-- auth_token variable is needed by a few functions which are
-- nested inside top-level ones. We can either define all the functions
-- inside the same lexical block, or we pass it around. Passing it
-- around seems cleaner.
res.get_cache_entry = function (name)
return get_cache_entry(name, auth_token)
end
res.periodically_refresh_cache = function()
return periodically_refresh_cache(auth_token)
end
else
res.get_cache_entry = get_cache_entry
res.periodically_refresh_cache = periodically_refresh_cache
end
return res
end
return _M
| apache-2.0 |
graydon/monotone | tests/db_check_(heights)/__driver__.lua | 1 | 1654 | -- -*-lua-*-
mtn_setup()
-- make two revisions
addfile("testfile", "A")
commit()
revA = base_revision()
writefile("testfile", "B")
commit()
revB = base_revision()
-- db should be ok
check(mtn("db", "check"), 0, false, false)
-- swap the two heights (by swapping their revs)
check(mtn("db", "execute", "update heights set revision='temp' where revision=x'" .. revA .. "';"), 0, false, false)
check(mtn("db", "execute", "update heights set revision=x'".. revA .. "' where revision=x'" .. revB .. "';"), 0, false, false)
check(mtn("db", "execute", "update heights set revision=x'".. revB .. "' where revision='temp';"), 0, false, false)
-- check
check(mtn("db", "check"), 1, false, true)
check(qgrep('1 incorrect heights', 'stderr'))
check(qgrep(revB, 'stderr'))
check(qgrep('serious problems detected', 'stderr'))
-- delete one of the heights
check(mtn("db", "execute", "delete from heights where revision=x'" .. revA .. "';"), 0, false, false)
-- check again
check(mtn("db", "check"), 1, false, true)
check(qgrep('1 missing heights', 'stderr'))
check(qgrep(revA, 'stderr'))
check(qgrep('serious problems detected', 'stderr'))
-- duplicate the remaining height
check(mtn("db", "execute", "insert into heights (revision, height) values (x'" .. revA .. "', (select height from heights where revision=x'" .. revB .. "'));"), 0, false, false)
-- check once more
check(mtn("db", "check"), 1, false, true)
check(qgrep('1 duplicate heights', 'stderr'))
--no check for the rev, because we don't know which one is reported first
check(qgrep('1 incorrect heights', 'stderr'))
check(qgrep(revB, 'stderr'))
check(qgrep('serious problems detected', 'stderr'))
| gpl-2.0 |
mohammad8/123456 | plugins/vote.lua | 615 | 2128 | do
local _file_votes = './data/votes.lua'
function read_file_votes ()
local f = io.open(_file_votes, "r+")
if f == nil then
print ('Created voting file '.._file_votes)
serialize_to_file({}, _file_votes)
else
print ('Values loaded: '.._file_votes)
f:close()
end
return loadfile (_file_votes)()
end
function clear_votes (chat)
local _votes = read_file_votes ()
_votes [chat] = {}
serialize_to_file(_votes, _file_votes)
end
function votes_result (chat)
local _votes = read_file_votes ()
local results = {}
local result_string = ""
if _votes [chat] == nil then
_votes[chat] = {}
end
for user,vote in pairs (_votes[chat]) do
if (results [vote] == nil) then
results [vote] = user
else
results [vote] = results [vote] .. ", " .. user
end
end
for vote,users in pairs (results) do
result_string = result_string .. vote .. " : " .. users .. "\n"
end
return result_string
end
function save_vote(chat, user, vote)
local _votes = read_file_votes ()
if _votes[chat] == nil then
_votes[chat] = {}
end
_votes[chat][user] = vote
serialize_to_file(_votes, _file_votes)
end
function run(msg, matches)
if (matches[1] == "ing") then
if (matches [2] == "reset") then
clear_votes (tostring(msg.to.id))
return "Voting statistics reset.."
elseif (matches [2] == "stats") then
local votes_result = votes_result (tostring(msg.to.id))
if (votes_result == "") then
votes_result = "[No votes registered]\n"
end
return "Voting statistics :\n" .. votes_result
end
else
save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2])))
return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2]))
end
end
return {
description = "Plugin for voting in groups.",
usage = {
"!voting reset: Reset all the votes.",
"!vote [number]: Cast the vote.",
"!voting stats: Shows the statistics of voting."
},
patterns = {
"^!vot(ing) (reset)",
"^!vot(ing) (stats)",
"^!vot(e) ([0-9]+)$"
},
run = run
}
end | gpl-2.0 |
ntop/ntopng | scripts/lua/modules/sys_utils.lua | 1 | 4668 | --
-- (C) 2013-22 - ntop.org
--
local sys_utils = {}
-- If false, some commands and config files are not executed/created really
-- This will be overwritten with the config value
local REAL_EXEC = ntop.getPref("ntopng.prefs.nedge_real_exec") == "1"
-- ################################################################
local FileMock = {}
FileMock.__index = FileMock
function FileMock.open(fname, mode)
local obj = {}
setmetatable(obj, FileMock)
traceError(TRACE_NORMAL, TRACE_CONSOLE, "[File::" .. fname .. "]")
return obj
end
function FileMock:write(data)
local lines = split(data, "\n")
for _, line in pairs(lines) do
if not isEmptyString(line) then
traceError(TRACE_NORMAL, TRACE_CONSOLE, "\t"..line)
end
end
return true
end
function FileMock:close()
traceError(TRACE_NORMAL, TRACE_CONSOLE, "[File::END]")
return true
end
-- ################################################################
function sys_utils.setRealExec(new_v)
REAL_EXEC = new_v
local v = ternary(REAL_EXEC, "1", "0")
if ntop.getPref("ntopng.prefs.nedge_real_exec") ~= v then
ntop.setPref("ntopng.prefs.nedge_real_exec", v)
end
end
-- ################################################################
function sys_utils.openFile(fname, mode)
local cls
if REAL_EXEC then
cls = io
else
cls = FileMock
end
return cls.open(fname, mode)
end
-- ################################################################
-- Execute a system command
function sys_utils.execCmd(cmd)
if(REAL_EXEC) then
-- traceError(TRACE_NORMAL, TRACE_CONSOLE, "[>] ".. cmd)
return(os.execute(cmd))
else
traceError(TRACE_NORMAL, TRACE_CONSOLE, "[execCmd] ".. cmd)
return 0
end
end
-- ################################################################
-- execCmd with command output
-- If input is specified, it is provided as stdin to the command
-- otherwise the command is executed with no input and the output returned
-- NOTE: no check for REAL_EXEC, the command will always be executed!
function sys_utils.execShellCmd(cmd, input)
local f, s
if input then
f = io.popen(cmd, 'w')
if f then
f:write(input)
s = true
else
s = false
end
else
f = assert(io.popen(cmd, 'r'))
s = assert(f:read('*a'))
end
if f then
f:close()
end
return s
end
-- ################################################################
local function _isServiceStatus(service_name, status)
require "lua_utils"
local check_cmd = "systemctl is-"..status.." " .. service_name
local is_active = sys_utils.execShellCmd(check_cmd)
return ternary(string.match(tostring(is_active), "^"..status), true, false)
end
function sys_utils.isActiveService(service_name)
return _isServiceStatus(service_name, "active")
end
function sys_utils.isEnabledService(service_name)
return _isServiceStatus(service_name, "enabled")
end
function sys_utils.isFailedService(service_name)
return _isServiceStatus(service_name, "failed")
end
function sys_utils.isActiveFailedService(service_name)
require "lua_utils"
local check_cmd = "systemctl is-active " .. service_name
local is_active = sys_utils.execShellCmd(check_cmd)
return ternary(string.match(tostring(is_active), "inactive"), false, true)
end
-- ################################################################
function sys_utils.enableService(service_name)
return sys_utils.execCmd("systemctl enable " .. service_name)
end
function sys_utils.disableService(service_name)
return sys_utils.execCmd("systemctl disable " .. service_name)
end
function sys_utils.restartService(service_name)
return sys_utils.execCmd("systemctl restart " .. service_name)
end
function sys_utils.stopService(service_name)
return sys_utils.execCmd("systemctl stop " .. service_name)
end
-- ################################################################
function sys_utils.rebootSystem()
local do_reboot = ternary(REAL_EXEC, "reboot", nil)
ntop.shutdown(do_reboot)
end
function sys_utils.shutdownSystem()
local do_shutdown = ternary(REAL_EXEC, "poweroff", nil)
ntop.shutdown(do_shutdown)
end
function sys_utils.restartSelf()
local do_restart_self = ternary(REAL_EXEC, "restart_self", nil)
ntop.shutdown(do_restart_self)
end
-- ################################################################
function sys_utils.loadConntrack()
local info = ntop.getInfo(false)
local os = info.OS
if not string.find(os, "Ubuntu 20%.") then
sys_utils.execCmd("modprobe nf_conntrack_ipv4")
end
end
-- ################################################################
return sys_utils
| gpl-3.0 |
eaufavor/AwesomeWM-powerarrow-dark | widgets/layout/desktopLayout.lua | 1 | 9262 | local setmetatable = setmetatable
local table = table
local type = type
local ipairs = ipairs
local print = print
local button = require( "awful.button" )
local beautiful = require( "beautiful" )
local naughty = require( "naughty" )
local tag = require( "awful.tag" )
local config = require( "forgotten" )
local util = require( "awful.util" )
local wibox = require( "awful.wibox" )
local widget = require( "awful.widget" )
local capi = { image = image ,
widget = widget ,
mouse = mouse ,
screen = screen ,
mousegrabber = mousegrabber }
local idCnt = 0
local columns = {}
local screens = {}
local activeCol = {}
local activeScreen = 1
local padding = {}
local reservedItem = {}
local autoItems = {}
local module = {}
local function usableSpace(s)
local h = capi.screen[(#capi.screen >= s) and s or 1].geometry.height - (padding.top or 0)-(padding.bottom or 0)
local w = capi.screen[(#capi.screen >= s) and s or 1].geometry.width - (padding.left or 0)-(padding.left or 0)
return {width = w, height = h}
end
local function new(args)
padding.top = args.padTop or args.padDef or 0
padding.bottom = args.padBottom or args.padDef or 0
padding.left = args.padLeft or args.padDef or 0
padding.right = args.padRight or args.padDef or 0
padding.item = args.padItem or 35
for i=1, #(capi.screen)+1 do
screens[i] = {}
screens[i].freeW = usableSpace(i).width
columns[i] = {}
columns[i][1] = {}
columns[i][1].freeH = usableSpace(i).height
columns[i][1].width = 0
activeCol[i] = 1
end
end
function registerSpace(args)
table.insert(autoItems, args)
end
local function shiftyBy(s,x,y,width,height)
local newX,newY = 0,0
for k,v in ipairs(reservedItem) do
if v.screen == s then
if not (v.x+v.width < x or x+width < v.x ) then
newX = v.x+v.width
end
if not (v.y+v.height < y or y+height < v.y) then
newY = v.y+v.height
end
end
end
return {x=newX, y=newY}
end
local function addCol(screen)
activeCol[screen] = activeCol[screen] + 1
columns[screen][activeCol[screen]] = {}
columns[screen][activeCol[screen]].width = 0
columns[screen][activeCol[screen]].freeH = usableSpace(screen).height
end
local function getCurrentX(s)
local xpos = 0
for i=1, (activeCol[s] or 2)-1 do
xpos = xpos + columns[s or 1][i].width
end
return xpos
end
local function registerSpace_real()
for k,v in ipairs(autoItems) do
local available = shiftyBy(v.screen,getCurrentX(v.screen),usableSpace(v.screen).height-columns[v.screen][activeCol[v.screen]].freeH,v.width,v.height)
while available.x ~= 0 and available.y ~= 0 do
columns[v.screen][activeCol[v.screen]].freeH = columns[v.screen][activeCol[v.screen]].freeH - available.x
if columns[v.screen][activeCol[v.screen]].freeH - v.height - padding.item < 0 then
addCol(v.screen)
end
available = shiftyBy(v.screen,getCurrentX(v.screen),usableSpace(v.screen).height-columns[v.screen][activeCol[v.screen]].freeH,v.width,v.height)
end
if columns[v.screen][activeCol[v.screen]].freeH - v.height - padding.item < 0 then
addCol(v.screen)
end
if columns[v.screen][activeCol[v.screen]].width + padding.item < v.width then
columns[v.screen][activeCol[v.screen]].width = v.width + padding.item
end
v.x = padding.left + getCurrentX(v.screen)
v.y = padding.top + usableSpace(v.screen).height-columns[v.screen][activeCol[v.screen]].freeH
columns[v.screen][activeCol[v.screen]].freeH = columns[v.screen][activeCol[v.screen]].freeH - v.height - padding.item
end
end
function reserveSpace(args)
table.insert(reservedItem,args)
end
local function genId()
idCnt = idCnt + 1
return "tmp_"..idCnt
end
function addCornerWidget(wdg,screen,corner,args)
local wdgSet = addWidget(wdg,args,true)
wdgSet.x = capi.screen[(screen <= capi.screen.count()) and screen or 1].geometry.x+usableSpace(screen).width - wdgSet.width
wdgSet.y = 30--usableSpace(screen).height - wdgSet.height
end
function module.addWidget(wdg,args,reserved)
local args = args or {}
local wdgSet = {}
local wb
if args.type == "wibox" then
wb = wdg
elseif type(wdg) == "widget" then
local aWb = wibox({position="free"})
wdgSet.height = (wdg.height ~=0) and wdg.height or nil
wdgSet.width = (wdg.width ~=0) and wdg.width or nil
aWb.widgets = {wdg, layout = widget.horizontal.leftrightcached}
wb = aWb
end
local saved = {}
if args.id and config.desktop.position[args.id] then
saved.height = config.desktop.position[args.id].height or nil
saved.width = config.desktop.position[args.id].width or nil
saved.x = config.desktop.position[args.id].x or nil
saved.y = config.desktop.position[args.id].y or nil
end
wdgSet.id = args.id or genId()
wdgSet.height = saved.height or args.height or wdgSet.height or wb:geometry().height
wdgSet.width = saved.width or args.width or wdgSet.width or wb:geometry().width
wdgSet.allowDrag = args.allowDrag or config.allowDrag or true
wdgSet.opacity = args.opacity or wb.opacity
wdgSet.transparency = args.transparency or wb.transparency
wdgSet.bg = args.bg or wb.bg
wdgSet.bg_image = args.bg_image or wb.bg_image
wdgSet.bg_resize = args.bg_resize or wb.bg_resize
wdgSet.screen = args.screen or 1
wdgSet.button1 = args.button1 or args.onclick
wdgSet.wibox = wb
for i=2,10 do
wdgSet["button"..i] = args["button"..i]
end
wb:buttons(util.table.join(
button({ }, 1 ,function (tab)
if wdgSet.allowDrag == true then
local curX = capi.mouse.coords().x
local curY = capi.mouse.coords().y
local moved = false
capi.mousegrabber.run(function(mouse)
if mouse.buttons[1] == false then
if moved == false then
wdgSet.button1()
end
capi.mousegrabber.stop()
return false
end
if mouse.x ~= curX and mouse.y ~= curY then
local height = wb:geometry().height
local width = wb:geometry().width
wb.x = mouse.x-(width/2)
wb.y = mouse.y-(height/2)
moved = true
end
return true
end,"fleur")
else
wdgSet.button1()
end
end),
button({ }, 2 ,function (tab) if wdgSet.button2 then wdgSet.button2 () end end),
button({ }, 3 ,function (tab) if wdgSet.button3 then wdgSet.button3 () end end),
button({ }, 4 ,function (tab) if wdgSet.button4 then wdgSet.button4 () end end),
button({ }, 5 ,function (tab) if wdgSet.button5 then wdgSet.button5 () end end),
button({ }, 6 ,function (tab) if wdgSet.button6 then wdgSet.button6 () end end),
button({ }, 7 ,function (tab) if wdgSet.button7 then wdgSet.button7 () end end),
button({ }, 8 ,function (tab) if wdgSet.button8 then wdgSet.button8 () end end),
button({ }, 9 ,function (tab) if wdgSet.button9 then wdgSet.button9 () end end),
button({ }, 10,function (tab) if wdgSet.button10 then wdgSet.button10() end end)
))
if saved.x or saved.y or reserved == true then
wdgSet.x = saved.x
wdgSet.y = saved.y
reserveSpace (wdgSet)
else
registerSpace(wdgSet)
end
return wdgSet
end
function module.draw()
registerSpace_real()
for k,v in ipairs(reservedItem) do
v.wibox.x = v.x
v.wibox.y = v.y
v.wibox.width = v.width
v.wibox.height=v.height
end
for k,v in ipairs(autoItems) do
v.wibox.x = v.x
v.wibox.y = v.y
v.wibox.width = v.width
v.wibox.height=v.height
end
end
return setmetatable(module, { __call = function(_, ...) return new(...) end })
| apache-2.0 |
dalab/deep-ed | utils/logger.lua | 1 | 4797 | --[[ Logger: a simple class to log symbols during training,
and automate plot generation
Example:
logger = optim.Logger('somefile.log') -- file to save stuff
for i = 1,N do -- log some symbols during
train_error = ... -- training/testing
test_error = ...
logger:add{['training error'] = train_error,
['test error'] = test_error}
end
logger:style{['training error'] = '-', -- define styles for plots
['test error'] = '-'}
logger:plot() -- and plot
---- OR ---
logger = optim.Logger('somefile.log') -- file to save stuff
logger:setNames{'training error', 'test error'}
for i = 1,N do -- log some symbols during
train_error = ... -- training/testing
test_error = ...
logger:add{train_error, test_error}
end
logger:style{'-', '-'} -- define styles for plots
logger:plot() -- and plot
]]
require 'xlua'
local Logger = torch.class('Logger')
function Logger:__init(filename, timestamp)
if filename then
self.name = filename
os.execute('mkdir ' .. (sys.uname() ~= 'windows' and '-p ' or '') .. ' "' .. paths.dirname(filename) .. '"')
if timestamp then
-- append timestamp to create unique log file
filename = filename .. '-'..os.date("%Y_%m_%d_%X")
end
self.file = io.open(filename,'w')
self.epsfile = self.name .. '.eps'
else
self.file = io.stdout
self.name = 'stdout'
print('<Logger> warning: no path provided, logging to std out')
end
self.empty = true
self.symbols = {}
self.styles = {}
self.names = {}
self.idx = {}
self.figure = nil
self.showPlot = false
self.plotRawCmd = nil
self.defaultStyle = '+'
end
function Logger:setNames(names)
self.names = names
self.empty = false
self.nsymbols = #names
for k,key in pairs(names) do
self.file:write(key .. '\t')
self.symbols[k] = {}
self.styles[k] = {self.defaultStyle}
self.idx[key] = k
end
self.file:write('\n')
self.file:flush()
end
function Logger:add(symbols)
-- (1) first time ? print symbols' names on first row
if self.empty then
self.empty = false
self.nsymbols = #symbols
for k,val in pairs(symbols) do
self.file:write(k .. '\t')
self.symbols[k] = {}
self.styles[k] = {self.defaultStyle}
self.names[k] = k
end
self.idx = self.names
self.file:write('\n')
end
-- (2) print all symbols on one row
for k,val in pairs(symbols) do
if type(val) == 'number' then
self.file:write(string.format('%11.4e',val) .. '\t')
elseif type(val) == 'string' then
self.file:write(val .. '\t')
else
xlua.error('can only log numbers and strings', 'Logger')
end
end
self.file:write('\n')
self.file:flush()
-- (3) save symbols in internal table
for k,val in pairs(symbols) do
table.insert(self.symbols[k], val)
end
end
function Logger:style(symbols)
for name,style in pairs(symbols) do
if type(style) == 'string' then
self.styles[name] = {style}
elseif type(style) == 'table' then
self.styles[name] = style
else
xlua.error('style should be a string or a table of strings','Logger')
end
end
end
function Logger:plot(ylabel, xlabel)
if not xlua.require('gnuplot') then
if not self.warned then
print('<Logger> warning: cannot plot with this version of Torch')
self.warned = true
end
return
end
local plotit = false
local plots = {}
local plotsymbol =
function(name,list)
if #list > 1 then
local nelts = #list
local plot_y = torch.Tensor(nelts)
for i = 1,nelts do
plot_y[i] = list[i]
end
for _,style in ipairs(self.styles[name]) do
table.insert(plots, {self.names[name], plot_y, style})
end
plotit = true
end
end
-- plot all symbols
for name,list in pairs(self.symbols) do
plotsymbol(name,list)
end
if plotit then
if self.showPlot then
self.figure = gnuplot.figure(self.figure)
gnuplot.plot(plots)
gnuplot.xlabel(xlabel)
gnuplot.ylabel(ylabel)
if self.plotRawCmd then gnuplot.raw(self.plotRawCmd) end
gnuplot.grid('on')
gnuplot.title(banner)
end
if self.epsfile then
os.execute('rm -f "' .. self.epsfile .. '"')
local epsfig = gnuplot.epsfigure(self.epsfile)
gnuplot.plot(plots)
gnuplot.xlabel(xlabel)
gnuplot.ylabel(ylabel)
if self.plotRawCmd then gnuplot.raw(self.plotRawCmd) end
gnuplot.grid('on')
gnuplot.title(banner)
gnuplot.plotflush()
gnuplot.close(epsfig)
end
end
end | apache-2.0 |
morcmarc/blackstar | assets/maps/map.lua | 1 | 2947 | return {
version = "1.1",
luaversion = "5.1",
tiledversion = "0.14.2",
orientation = "orthogonal",
renderorder = "right-down",
width = 100,
height = 10,
tilewidth = 32,
tileheight = 32,
nextobjectid = 12,
properties = {},
tilesets = {
{
name = "swamp1",
firstgid = 1,
tilewidth = 32,
tileheight = 32,
spacing = 0,
margin = 0,
image = "swamp1.png",
imagewidth = 32,
imageheight = 32,
tileoffset = {
x = 0,
y = 0
},
properties = {},
terrains = {},
tilecount = 1,
tiles = {
{
id = 0,
properties = {
["collidable"] = "true"
}
}
}
},
{
name = "swamp2",
firstgid = 2,
tilewidth = 32,
tileheight = 32,
spacing = 0,
margin = 0,
image = "swamp2.png",
imagewidth = 32,
imageheight = 32,
tileoffset = {
x = 0,
y = 0
},
properties = {},
terrains = {},
tilecount = 1,
tiles = {}
}
},
layers = {
{
type = "tilelayer",
name = "Background",
x = 0,
y = 0,
width = 100,
height = 10,
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {
["collidable"] = "true"
},
encoding = "base64",
compression = "gzip",
data = "H4sIAAAAAAAAA+3DsQkAAAgDsOr/R/uFdEggCQAAwI+x6lr1AI9DV/SgDwAA"
},
{
type = "objectgroup",
name = "Spawns",
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
objects = {
{
id = 2,
name = "theosophist_1",
type = "Theosophist",
shape = "rectangle",
x = 674.805,
y = 226.724,
width = 25.4897,
height = 25.4897,
rotation = 0,
visible = true,
properties = {}
},
{
id = 6,
name = "theosophist_2",
type = "Theosophist",
shape = "rectangle",
x = 322.646,
y = 226.053,
width = 25.4897,
height = 25.4897,
rotation = 0,
visible = true,
properties = {}
},
{
id = 10,
name = "player",
type = "Player",
shape = "ellipse",
x = 36.893,
y = 6.70779,
width = 20.1234,
height = 18.7819,
rotation = 0,
visible = true,
properties = {}
},
{
id = 11,
name = "anthropophagist_1",
type = "Anthropophagist",
shape = "rectangle",
x = 1122.89,
y = 227.395,
width = 25.4897,
height = 25.4897,
rotation = 0,
visible = true,
properties = {}
}
}
}
}
}
| mit |
immibis/wiremod | lua/entities/gmod_wire_light.lua | 10 | 7999 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Light"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "Light"
function ENT:SetupDataTables()
self:NetworkVar( "Bool", 0, "Glow" )
self:NetworkVar( "Float", 0, "Brightness" )
self:NetworkVar( "Float", 1, "Size" )
self:NetworkVar( "Int", 0, "R" )
self:NetworkVar( "Int", 1, "G" )
self:NetworkVar( "Int", 2, "B" )
end
if CLIENT then
local matLight = Material( "sprites/light_ignorez" )
local matBeam = Material( "effects/lamp_beam" )
function ENT:Initialize()
self.PixVis = util.GetPixelVisibleHandle()
--[[
This is some unused value which is used to activate the wire overlay.
We're not using it because we are using NetworkVars instead, since wire
overlays only update when you look at them, and we want to update the
sprite colors whenever the wire input changes. ]]
self:SetOverlayData({})
end
function ENT:GetMyColor()
return Color( self:GetR(), self:GetG(), self:GetB(), 255 )
end
function ENT:DrawTranslucent()
local up = self:GetAngles():Up()
local LightPos = self:GetPos()
render.SetMaterial( matLight )
local ViewNormal = self:GetPos() - EyePos()
local Distance = ViewNormal:Length()
ViewNormal:Normalize()
local Visible = util.PixelVisible( LightPos, 4, self.PixVis )
if not Visible or Visible < 0.1 then return end
local c = self:GetMyColor()
if self:GetModel() == "models/maxofs2d/light_tubular.mdl" then
render.DrawSprite( LightPos - up * 2, 8, 8, Color(255, 255, 255, 255), Visible )
render.DrawSprite( LightPos - up * 4, 8, 8, Color(255, 255, 255, 255), Visible )
render.DrawSprite( LightPos - up * 6, 8, 8, Color(255, 255, 255, 255), Visible )
render.DrawSprite( LightPos - up * 5, 128, 128, c, Visible )
else
render.DrawSprite( self:LocalToWorld( self:OBBCenter() ), 128, 128, c, Visible )
end
end
local wire_light_block = CreateClientConVar("wire_light_block", 0, false, false)
function ENT:Think()
if self:GetGlow() and not wire_light_block:GetBool() then
local dlight = DynamicLight(self:EntIndex())
if dlight then
dlight.Pos = self:GetPos()
local c = self:GetMyColor()
dlight.r = c.r
dlight.g = c.g
dlight.b = c.b
dlight.Brightness = self:GetBrightness()
dlight.Decay = self:GetSize() * 5
dlight.Size = self:GetSize()
dlight.DieTime = CurTime() + 1
end
end
end
local color_box_size = 64
function ENT:GetWorldTipBodySize()
-- text
local w_total,h_total = surface.GetTextSize( "Color:\n255,255,255,255" )
-- Color box width
w_total = math.max(w_total,color_box_size)
-- Color box height
h_total = h_total + 18 + color_box_size + 18/2
return w_total, h_total
end
local white = Color(255,255,255,255)
local black = Color(0,0,0,255)
local function drawColorBox( color, x, y )
surface.SetDrawColor( color )
surface.DrawRect( x, y, color_box_size, color_box_size )
local size = color_box_size
surface.SetDrawColor( black )
surface.DrawLine( x, y, x + size, y )
surface.DrawLine( x + size, y, x + size, y + size )
surface.DrawLine( x + size, y + size, x, y + size )
surface.DrawLine( x, y + size, x, y )
end
function ENT:DrawWorldTipBody( pos )
-- get color
local color = self:GetMyColor()
-- text
local color_text = string.format("Color:\n%d,%d,%d",color.r,color.g,color.b)
local w,h = surface.GetTextSize( color_text )
draw.DrawText( color_text, "GModWorldtip", pos.center.x, pos.min.y + pos.edgesize, white, TEXT_ALIGN_CENTER )
-- color box
drawColorBox( color, pos.center.x - color_box_size / 2, pos.min.y + pos.edgesize * 1.5 + h )
end
return -- No more client
end
-- Server
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = WireLib.CreateInputs(self, {"Red", "Green", "Blue", "RGB [VECTOR]"})
end
function ENT:Directional( On )
if On then
if IsValid( self.DirectionalComponent ) then return end
local flashlight = ents.Create( "env_projectedtexture" )
flashlight:SetParent( self )
-- The local positions are the offsets from parent..
flashlight:SetLocalPos( Vector( 0, 0, 0 ) )
flashlight:SetLocalAngles( Angle( -90, 0, 0 ) )
if self:GetModel() == "models/maxofs2d/light_tubular.mdl" then
flashlight:SetLocalAngles( Angle( 90, 0, 0 ) )
end
-- Looks like only one flashlight can have shadows enabled!
flashlight:SetKeyValue( "enableshadows", 1 )
flashlight:SetKeyValue( "farz", 1024 )
flashlight:SetKeyValue( "nearz", 12 )
flashlight:SetKeyValue( "lightfov", 90 )
local c = self:GetColor()
local b = self.brightness
flashlight:SetKeyValue( "lightcolor", Format( "%i %i %i 255", c.r * b, c.g * b, c.b * b ) )
flashlight:Spawn()
flashlight:Input( "SpotlightTexture", NULL, NULL, "effects/flashlight001" )
self.DirectionalComponent = flashlight
elseif IsValid( self.DirectionalComponent ) then
self.DirectionalComponent:Remove()
self.DirectionalComponent = nil
end
end
function ENT:Radiant( On )
if On then
if IsValid( self.RadiantComponent ) then
self.RadiantComponent:Fire( "TurnOn", "", "0" )
else
local dynlight = ents.Create( "light_dynamic" )
dynlight:SetPos( self:GetPos() )
local dynlightpos = dynlight:GetPos() + Vector( 0, 0, 10 )
dynlight:SetPos( dynlightpos )
dynlight:SetKeyValue( "_light", Format( "%i %i %i 255", self.R, self.G, self.B ) )
dynlight:SetKeyValue( "style", 0 )
dynlight:SetKeyValue( "distance", 255 )
dynlight:SetKeyValue( "brightness", 5 )
dynlight:SetParent( self )
dynlight:Spawn()
self.RadiantComponent = dynlight
end
elseif IsValid( self.RadiantComponent ) then
self.RadiantComponent:Fire( "TurnOff", "", "0" )
end
end
function ENT:UpdateLight()
self:SetR( self.R )
self:SetG( self.G )
self:SetB( self.B )
if IsValid( self.DirectionalComponent ) then self.DirectionalComponent:SetKeyValue( "lightcolor", Format( "%i %i %i 255", self.R * self.brightness, self.G * self.brightness, self.B * self.brightness ) ) end
if IsValid( self.RadiantComponent ) then self.RadiantComponent:SetKeyValue( "_light", Format( "%i %i %i 255", self.R, self.G, self.B ) ) end
end
function ENT:TriggerInput(iname, value)
if (iname == "Red") then
self.R = math.Clamp(value,0,255)
elseif (iname == "Green") then
self.G = math.Clamp(value,0,255)
elseif (iname == "Blue") then
self.B = math.Clamp(value,0,255)
elseif (iname == "RGB") then
self.R, self.G, self.B = math.Clamp(value[1],0,255), math.Clamp(value[2],0,255), math.Clamp(value[3],0,255)
elseif (iname == "GlowBrightness") then
if not game.SinglePlayer() then value = math.Clamp( value, 0, 10 ) end
self.brightness = value
self:SetBrightness( value )
elseif (iname == "GlowSize") then
if not game.SinglePlayer() then value = math.Clamp( value, 0, 1024 ) end
self.size = value
self:SetSize( value )
end
self:UpdateLight()
end
function ENT:Setup(directional, radiant, glow, brightness, size, r, g, b)
self.directional = directional or false
self.radiant = radiant or false
self.glow = glow or false
self.brightness = brightness or 2
self.size = size or 256
self.R = r or 255
self.G = g or 255
self.B = b or 255
if not game.SinglePlayer() then
self.brightness = math.Clamp( self.brightness, 0, 10 )
self.size = math.Clamp( self.size, 0, 1024 )
end
self:Directional( self.directional )
self:Radiant( self.radiant )
self:SetGlow( self.glow )
self:SetBrightness( self.brightness )
self:SetSize( self.size )
if self.glow then
WireLib.AdjustInputs(self, {"Red", "Green", "Blue", "RGB [VECTOR]", "GlowBrightness", "GlowSize"})
else
WireLib.AdjustInputs(self, {"Red", "Green", "Blue", "RGB [VECTOR]"})
end
self:UpdateLight()
end
duplicator.RegisterEntityClass("gmod_wire_light", WireLib.MakeWireEnt, "Data", "directional", "radiant", "glow", "brightness", "size", "R", "G", "B")
| apache-2.0 |
PicassoCT/Journeywar | LuaUI/Configs/lupsUnitFXs.lua | 1 | 20049 | -- note that the order of the MergeTable args matters for nested tables (such as colormaps)!
function randSign()
if math.random(0,1)==1 then return -1 else return 1 end
end
function randomStar(posmin,posmax, sizemin,sizemax)
return {class='ShieldSphere', options={life=math.huge,
pos={math.random(posmin,posmax)*randSign(),math.random(posmin,posmax),math.random(posmin,posmax)*randSign()},size=math.random(sizemin,sizemax),
colormap2 = {{0.9, 0.5, 0.01, 1}},
colormap1 = {{0.95, 0.2, 0.01 , 1}},
repeatEffect=true}}
end
local presets = {
commandAuraRed = {
{class='StaticParticles', options=commandCoronaRed},
{class='GroundFlash', options=MergeTable(groundFlashRed, {radiusFactor=3.5,mobile=true,life=60,
colormap={ {1, 0.2, 0.2, 1},{1, 0.2, 0.2, 0.85},{1, 0.2, 0.2, 1} }})},
},
commandAuraOrange = {
{class='StaticParticles', options=commandCoronaOrange},
{class='GroundFlash', options=MergeTable(groundFlashOrange, {radiusFactor=3.5,mobile=true,life=math.huge,
colormap={ {0.8, 0, 0.2, 1},{0.8, 0, 0.2, 0.85},{0.8, 0, 0.2, 1} }})},
},
commandAuraGreen = {
{class='StaticParticles', options=commandCoronaGreen},
{class='GroundFlash', options=MergeTable(groundFlashGreen, {radiusFactor=3.5,mobile=true,life=math.huge,
colormap={ {0.2, 1, 0.2, 1},{0.2, 1, 0.2, 0.85},{0.2, 1, 0.2, 1} }})},
},
commandAuraBlue = {
{class='StaticParticles', options=commandCoronaBlue},
{class='GroundFlash', options=MergeTable(groundFlashBlue, {radiusFactor=3.5,mobile=true,life=math.huge,
colormap={ {0.2, 0.2, 1, 1},{0.2, 0.2, 1, 0.85},{0.2, 0.2, 1, 1} }})},
},
commandAuraViolet = {
{class='StaticParticles', options=commandCoronaViolet},
{class='GroundFlash', options=MergeTable(groundFlashViolet, {radiusFactor=3.5,mobile=true,life=math.huge,
colormap={ {0.8, 0, 0.8, 1},{0.8, 0, 0.8, 0.85},{0.8, 0, 0.8, 1} }})},
},
commAreaShield = {
{class='ShieldJitter', options={delay=0, life=math.huge, heightFactor = 0.75, size=350, strength = .001, precision=50, repeatEffect=true, quality=4}},
},
commandShieldRed = {
{class='ShieldSphere', options=MergeTable({colormap1 = {{1, 0.1, 0.1, 0.6}}, colormap2 = {{1, 0.1, 0.1, 0.15}}}, commandShieldSphere)},
-- {class='StaticParticles', options=commandCoronaRed},
-- {class='GroundFlash', options=MergeTable(groundFlashRed, {radiusFactor=3.5,mobile=true,life=60,
-- colormap={ {1, 0.2, 0.2, 1},{1, 0.2, 0.2, 0.85},{1, 0.2, 0.2, 1} }})},
},
commandShieldOrange = {
{class='ShieldSphere', options=MergeTable({colormap1 = {{0.8, 0.3, 0.1, 0.6}}, colormap2 = {{0.8, 0.3, 0.1, 0.15}}}, commandShieldSphere)},
},
commandShieldGreen = {
{class='ShieldSphere', options=MergeTable({colormap1 = {{0.1, 1, 0.1, 0.6}}, colormap2 = {{0.1, 1, 0.1, 0.15}}}, commandShieldSphere)},
},
commandShieldBlue= {
{class='ShieldSphere', options=MergeTable({colormap1 = {{0.1, 0.1, 0.8, 0.6}}, colormap2 = {{0.1, 0.1, 1, 0.15}}}, commandShieldSphere)},
},
commandShieldViolet = {
{class='ShieldSphere', options=MergeTable({colormap1 = {{0.6, 0.1, 0.75, 0.6}}, colormap2 = {{0.6, 0.1, 0.75, 0.15}}}, commandShieldSphere)},
},
}
effectUnitDefs = {
--centrail
css = {
{class='Ribbon', options={color={.9,.4,0.1,1}, width=1.5, piece="jet2", onActive=false}},
{class='Ribbon', options={color={.9,.4,0.1,1}, width=1.5, piece="jet1", onActive=false}}
},
cvictory = {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,600,0}, size=125, precision=22, strength = 0.25, repeatEffect=true}}
},
cawilduniverseappears= {
{class='ShieldSphere', options={life=math.huge, pos={0,0,0}, size=103, colormap1 = {{1/255, 1/255, 50/255, 1.0}},colormap2 = {{150/255, 125/255, 230/255, 0.5}}, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,0,0}, size=108, precision=22, strength = 0.013, repeatEffect=true}},
},
citadell= {
{class='ShieldSphere', options={life=math.huge, pos={0,496,0}, size=1000, onActive=true, colormap1 = {{0.2, 0.8, 0.9, 0.8}}, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,496,0}, size=1024,onActive=true, precision=22, strength = 0.042, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,503,0}, size=5, precision=22, strength = 0.015, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,613,0}, size=100, precision=22, strength = 0.005, repeatEffect=true}},
},
cwallbuilder={
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,-25,0}, size=55, precision=22, strength = 0.015, repeatEffect=true}},
},
cairbase= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,0,0}, size=42, precision=22, strength = 0.001, repeatEffect=true}},
},
cfclvl1= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,35,10}, size=42, precision=22, strength = 0.003, repeatEffect=true}},
},
cwaterextractor= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,116,0}, size=25, precision=22, strength = 0.015, repeatEffect=true}},
},
cadvisor ={
{class='Ribbon', options={color={.1,.4,0.9,1}, width=2, size= 32, piece="flare1", onActive=false}} ,
{class='Ribbon', options={color={.1,.4,0.9,1}, width=2, size= 32, piece="flare2", onActive=false}} ,
{class='Ribbon', options={color={.1,.4,0.9,1}, width=2, size= 32, piece="flare3", onActive=false}} ,
{class='Ribbon', options={color={.1,.4,0.9,1}, width=2, size= 32, piece="flare4", onActive=false}} ,
},
cbbind= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,10,0}, size=96, precision=22, strength = 0.003, repeatEffect=true}},
},
cbuibaicity1= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,64,0}, size=80, precision=22, strength = 0.005, repeatEffect=true}},
},
cgunship= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={-2,5,-31}, size=20, precision=22, strength = 0.015, repeatEffect=true}},
},
cmdigg= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,24,-20}, size=30, precision=22, strength = 0.005, repeatEffect=true}},
},
cdefusordart= {
{class='Ribbon', options={color={.9,.1,0.1,1}, width=6.5, size= 32, piece="dart", onActive=false}},
},
--journeyman
jpoisonracedart= {
{class='Ribbon', options={color={.7,.9,0.1,1}, width=6.5, size= 32, piece="RaceDrone", onActive=false}},
},
ggluemine= {
{class='ShieldSphere', options={life=math.huge, pos={0,0,0}, size=10, colormap1 = {{0.36, 0.36, 0.9, 0.8}}, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,0,0}, size=10.5, precision=22, strength = 0.005, repeatEffect=true}}
},
jracedart= {
{class='ShieldSphere', options={life=math.huge, pos={0,0,0}, size=5, colormap1 = {{0.62, 0.9, 0.09, 0.8}}, repeatEffect=true}},
{class='Ribbon', options={color={.2,.8,0.9,1}, width=6.5, size= 32, piece="RaceDrone", onActive=false}},
},
jhoneypot= {
{class='Ribbon', options={color={.9,.4,0.1,1}, width=12.5, size= 32, piece="jhoney", onActive=false}},
},
jmotherofmercy ={
{class='Ribbon', options={color={.6,.9,0.0,1}, width=8, size= 32, piece="thrustemit", onActive=true}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=8, size= 32, piece="eye1", onActive=true}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=8, size= 32, piece="eye2", onActive=true}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=4, size= 32, piece="Kreis13", onActive=true}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=4, size= 32, piece="Kreis06", onActive=true}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=4, size= 32, piece="Kreis16", onActive=true}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=4, size= 32, piece="Kreis15", onActive=true}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=4, size= 32, piece="Kreis14", onActive=true}},
},
jstealthdrone ={
{class='Ribbon', options={color={.1,.4,0.9,1}, width=4, size= 32, piece="flare1", onActive=true}},
{class='Ribbon', options={color={.1,.4,0.9,1}, width=4, size= 32, piece="flare2", onActive=true}},
{class='Ribbon', options={color={.1,.4,0.9,1}, width=4, size= 32, piece="flare3", onActive=true}},
{class='Ribbon', options={color={.1,.4,0.9,1}, width=4, size= 32, piece="flare4", onActive=true}},
{class='Ribbon', options={color={.1,.4,0.9,1}, width=4, size= 32, piece="flare5", onActive=true}},
{class='Ribbon', options={color={.1,.4,0.9,1}, width=4, size= 32, piece="flare6", onActive=true}},
{class='Ribbon', options={color={.1,.4,0.9,1}, width=4, size= 32, piece="flare7", onActive=true}},
{class='Ribbon', options={color={.1,.4,0.9,1}, width=4, size= 32, piece="flare8", onActive=true}},
{class='Ribbon', options={color={.1,.4,0.9,1}, width=22.5, size= 10, piece="nanoemit", onActive=false}}
},
jrecycler ={
{class='Ribbon', options={color={.6,.9,0.0,1}, width=2, size= 32, piece="emit1", onActive=false}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=2, size= 32, piece="emit2", onActive=false}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=2, size= 32, piece="emit3", onActive=false}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=2, size= 32, piece="emit4", onActive=false}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=2, size= 32, piece="emit5", onActive=false}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=2, size= 32, piece="emit6", onActive=false}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=2, size= 32, piece="emit7", onActive=false}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=2, size= 32, piece="emit8", onActive=false}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=2, size= 32, piece="emit9", onActive=false}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=2, size= 32, piece="emit10",onActive=false}},
{class='Ribbon', options={color={.6,.9,0.0,1}, width=2, size= 32, piece="emit11",onActive=false}},
{class='Ribbon', options={color={.4,.9,.9,1}, width=4, size= 32, piece="emit12",onActive=false}}
},
jsunshipwater ={
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,0,0}, size=325, precision=22, strength = 0.00125, repeatEffect=true}}
},
jmeconverter ={
{class='ShieldSphere', options={life=math.huge, pos={0,35,0}, size=18, colormap1 = {{0.3, 0.9, 0.06, 0.8}}, repeatEffect=true}},
{class='ShieldJitter', options={life=math.huge, pos={0,35,0}, size=19.5, precision=22, strength = 0.001125, repeatEffect=true}},
},
jtiglil ={
{class='Ribbon', options={color={.1,.8,0.9,1}, width=3.5, piece="tlhairup", onActive=false}},
},
jghostdancer ={
{class='Ribbon', options={color={.1,.8,0.9,1}, width=3.5, piece="Tail05", onActive=false}},
},
jsunshipfire= {
{class='ShieldSphere', options={life=math.huge, pos={0,0,0},size=220,onActive=true, colormap2 = {{0.9, 0.5, 0.01, 0.9}},colormap1 = {{0.95, 0.2, 0.01 , 0.9}}, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,0,0}, size=1000, precision=22, strength = 0.005, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,0,0}, size=225, precision=22, strength = 0.005, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,0,0}, size=250, precision=22, strength = 0.029, repeatEffect=true}},
},
jshroudshrike={
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,15,0}, size=90, precision=22, strength = 0.015, repeatEffect=true}},
},
jmirrorbubble={
-- Sun
{class='ShieldSphere', options={ onActive=true, life=math.huge, pos={math.random(-5,5),115,math.random(-5,5)}, size=math.random(30,35), colormap1 = {{0.2, 0.5, 0.9, 0.1}},colormap2 = {{0.2, 0.9, 0.3 , 0.6}}, repeatEffect=true}},
-- Planets
{class='ShieldSphere', options={ onActive=true,life=math.huge, pos={math.random(-120,120),95, math.random(-120,120)}, size=math.random(2,10), colormap2 = {{0.2, 0.5, 0.9, 0.1}},colormap1 = {{0.2, 0.9, 0.3 , 0.3}}, repeatEffect=true}},
{class='ShieldSphere', options={ onActive=true, life=math.huge, pos={math.random(-120,120),110, math.random(-120,120)}, size=math.random(5,8), colormap2 = {{0.2, 0.5, 0.9, 0.1}},colormap1 = {{0.2, 0.9, 0.3 , 0.3}}, repeatEffect=true}},
{class='ShieldSphere', options={ onActive=true, life=math.huge, pos={math.random(-80,80),130, math.random(-80,80)}, size=math.random(2,10), colormap2 = {{0.2, 0.5, 0.9, 0.1}},colormap1 = {{0.2, 0.9, 0.3 , 0.3}}, repeatEffect=true}},
{class='ShieldSphere', options={ onActive=true, life=math.huge, pos={math.random(-200,200),90, math.random(-200,200)}, size=math.random(5,15), colormap2 = {{0.2, 0.5, 0.9, 0.1}},colormap1 = {{0.2, 0.9, 0.3 , 0.3}}, repeatEffect=true}},
{class='ShieldSphere', options={ onActive=true, life=math.huge, pos={math.random(-80,80),120, math.random(-80,80)}, size=math.random(5,15), colormap2 = {{0.2, 0.5, 0.9, 0.1}},colormap1 = {{0.2, 0.9, 0.3 , 0.3}}, repeatEffect=true}},
{class='ShieldSphere', options={ onActive=true, life=math.huge, pos={math.random(180,250)*-1,115, math.random(180,250)*-1}, size=math.random(15,22), colormap2 = {{0.2, 0.5, 0.9, 0.1}},colormap1 = {{0.2, 0.9, 0.3 , 0.3}}, repeatEffect=true}},
{class='ShieldSphere', options={life=math.huge, pos={0,0,0},size=750, onActive=true, colormap2 = {{0.2, 0.5, 0.9, 0.014}},colormap1 = {{0.2, 0.9, 0.3 , 0.3}}, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,0,0}, size=780, precision=22, strength = 0.00035, repeatEffect=true}},
},
gvolcano= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,70,0}, size=150, precision=22, strength = 0.01, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,1200,0}, size=250, precision=22, strength = 0.005, repeatEffect=true}},
-- {class='SphereDistortion', options={layer=1, worldspace = true, life=math.huge, pos={0,496,0}, growth=135.5, strength=0.15, repeatEffect=true, dieGameFrame = math.huge}},--size=1000 precision=22,piece="cishadersp"
},
glava= {
{class='ShieldSphere', options={ life=math.huge, pos={0,-5 ,0}, size=35,
colormap2 = {{0.9, 0.3, 0.0, 0.4}, {1, 0.3, 0, 0.0}},
colormap1 = {{0.5, 0.3, 0.0, 0.0}, {1, 0.3, 0, 0.0}},
repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,0,0}, size=42, precision=22, strength = 0.007, repeatEffect=true}},
},
jwatergate= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,45,0}, size=20, precision=22, strength = 0.015, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,15,0}, size=20, precision=28, strength = 0.007, repeatEffect=true}},
},
jharbour= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,35,0}, size=60, precision=28, strength = 0.007, repeatEffect=true}},
},
cegtest= {
{class='ShieldSphere', options={ life=math.huge, pos={0,30.1,0}, size=50,
colormap2 = {{0.9, 0.3, 0.0, 0.4}, {1, 0.3, 0, 0.0}},
colormap1 = {{0.5, 0.3, 0.0, 0.0}, {1, 0.3, 0, 0.0}},
repeatEffect=true}}
},
beanstalk= {
{class='Ribbon', options={color={.7,1,0.1,0.5}, width=12.5, piece="seed"}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,20,0}, size=55, precision=22, strength = 0.005, repeatEffect=true}},
-- outer ShieldSFX
{class='ShieldSphere', options={ onActive=true, life=math.huge, pos={0,30.1,0}, size=600,
colormap1 = {{227/255, 227/255, 125/255, 0.15}},
colormap2 = {{227/255, 250/255, 125/255, 0.15}},
repeatEffect=true}},
{class='ShieldSphere', options={ onActive=true, life=math.huge, pos={0,30.2,0}, size=605,
colormap1 = {{125/255, 250/255, 125/255, 0.15}}, --g
colormap2 = {{125/255, 227/255, 125/255, 0.15}}, --gb
repeatEffect=true}},
{class='ShieldSphere', options={ onActive=true, life=math.huge, pos={0,30.3,0}, size=615,
colormap1 = {{125/255, 227/255, 225/255, 0.15}}, --gb
colormap2 = {{125/255, 125/255, 250/255, 0.15}}, --b
repeatEffect=true}},
{class='ShieldSphere', options={ onActive=true, life=math.huge, pos={0,30.4,0}, size=625,
colormap1 = {{250/255, 125/255, 125/255, 0.25}}, --r
colormap2 = {{0.62, 0.9, 0.09, 0.45}}, --g
}, repeatEffect=true},
{class='ShieldJitter', options={ onActive=true, delay=0,life=math.huge, pos={0,25,0}, size=655, precision=0.1, strength = 0.0035, repeatEffect=true}},
},
jestorage= {
{class='ShieldSphere', options={life=math.huge, pos={0,18,2.3}, size=13.57, colormap1 = {{0.9, 0.6, 0.09, 0.8}}, repeatEffect=true}}
},
jglowworms= {
{class='Ribbon', options={color={.8,0.9,0,1}, width=5.5, piece="Glow2", onActive=false}},
{class='Ribbon', options={color={.8,0.9,0,1}, width=5.5, piece="Glow6", onActive=false}},
},
gcvehiccorpsemini= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,0,0}, size=5, precision=12, strength = 0.005, repeatEffect=true}},
},
gcvehiccorpse= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,0,0}, size=9, precision=22, strength = 0.005, repeatEffect=true}},
},
--{class='ShieldJitter', options={layer=-16, life=math.huge, pos={0,58.9,0}, size=100, precision=22, strength = 0.001, repeatEffect=true}},
jbeefeater= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,36,-12.5}, size=25, precision=22, strength = 0.015, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,36,-56 }, size=25, precision=22, strength = 0.015, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,36,-92}, size=25, precision=22, strength = 0.015, repeatEffect=true}},
},
jbeefeatertail= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,18,44}, size=25, precision=22, strength = 0.015, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,18,22}, size=25, precision=22, strength = 0.015, repeatEffect=true}},
},
jsempresequoia = {
{class='Ribbon', options={color={.4,.9,0.1,1},length=50, width=5.5, piece="truster1", onActive=false}},
{class='Ribbon', options={color={.4,.9,0.1,1},length=50, width=5.5, piece="truster2", onActive=false}},
{class='Ribbon', options={color={.4,.9,0.1,1},length=50, width=5.5, piece="truster3", onActive=false}},
{class='Ribbon', options={color={.4,.9,0.1,1},length=50, width=5.5, piece="truster4", onActive=false}}
},
jbeefeatermiddle= {
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,37,57}, size=25, precision=22, strength = 0.015, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,37,92}, size=25, precision=22, strength = 0.015, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,37,124}, size=25, precision=22, strength = 0.015, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,37,-37}, size=25, precision=22, strength = 0.015, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,37,-69}, size=25, precision=22, strength = 0.015, repeatEffect=true}},
{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,37,-101}, size=25, precision=22, strength = 0.015, repeatEffect=true}},
},
}
effectUnitDefsXmas = {}
local levelScale = {
1,
1.1,
1.2,
1.25,
1.3,
}
-- load presets from unitdefs
for i=1,#UnitDefs do
local unitDef = UnitDefs[i]
if unitDef.customParams and unitDef.customParams.commtype then
end
if unitDef.customParams then
local fxTableStr = unitDef.customParams.lups_unit_fxs
if fxTableStr then
local fxTableFunc = loadstring("return "..fxTableStr)
local fxTable = fxTableFunc()
effectUnitDefs[unitDef.name] = effectUnitDefs[unitDef.name] or {}
for i=1,#fxTable do -- for each item in preset table
local toAdd = presets[fxTable[i]]
for i=1,#toAdd do
table.insert(effectUnitDefs[unitDef.name],toAdd[i]) -- append to unit's lupsFX table
end
end
end
end
end | gpl-3.0 |
b03605079/darkstar | scripts/zones/Port_Bastok/npcs/Romilda.lua | 36 | 2365 | -----------------------------------
-- Area: Port Bastok
-- NPC: Romilda
-- Involved in Quest: Forever to Hold
-- Starts & Ends Quest: Till Death Do Us Part
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(12497,1) and trade:getItemCount() == 1) then -- Trade Brass Hairpin
if (player:getVar("ForevertoHold_Event") == 2) then
player:tradeComplete();
player:startEvent(0x7D);
player:setVar("ForevertoHold_Event",3);
end
elseif (trade:hasItemQty(12721,1) and trade:getItemCount() == 1) then -- Trade Cotton Gloves
if (player:getVar("ForevertoHold_Event") == 3) then
player:tradeComplete();
player:startEvent(0x81);
player:setVar("ForevertoHold_Event",4);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
pFame = player:getFameLevel(BASTOK);
ForevertoHold = player:getQuestStatus(BASTOK,FOREVER_TO_HOLD);
TilldeathdousPart = player:getQuestStatus(BASTOK,TILL_DEATH_DO_US_PART);
if (pFame >= 3 and ForevertoHold == QUEST_COMPLETED and TilldeathdousPart == QUEST_AVAILABLE and player:getVar("ForevertoHold_Event") == 3) then
player:startEvent(0x80);
else
player:startEvent(0x22);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x80) then
player:addQuest(BASTOK,TILL_DEATH_DO_US_PART);
elseif (csid == 0x81) then
player:addTitle(QIJIS_RIVAL);
player:addGil(GIL_RATE*2000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*2000);
player:addFame(BASTOK,BAS_FAME*160);
player:completeQuest(BASTOK,TILL_DEATH_DO_US_PART);
end
end; | gpl-3.0 |
b03605079/darkstar | scripts/zones/Southern_San_dOria/npcs/Foletta.lua | 36 | 1433 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Foletta
-- General Info NPC
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x29a);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Aquanim/Zero-K | LuaUI/Configs/lupsUnitFXs.lua | 6 | 24117 | -- note that the order of the MergeTable args matters for nested tables (such as colormaps)!
local presets = {
commandAuraRed = {
{class='StaticParticles', options=commandCoronaRed},
{class='GroundFlash', options=MergeTable(groundFlashRed, {radiusFactor=3.5,mobile=true,life=60,
colormap={ {1, 0.2, 0.2, 1},{1, 0.2, 0.2, 0.85},{1, 0.2, 0.2, 1} }})},
},
commandAuraOrange = {
{class='StaticParticles', options=commandCoronaOrange},
{class='GroundFlash', options=MergeTable(groundFlashOrange, {radiusFactor=3.5,mobile=true,life=math.huge,
colormap={ {0.8, 0, 0.2, 1},{0.8, 0, 0.2, 0.85},{0.8, 0, 0.2, 1} }})},
},
commandAuraGreen = {
{class='StaticParticles', options=commandCoronaGreen},
{class='GroundFlash', options=MergeTable(groundFlashGreen, {radiusFactor=3.5,mobile=true,life=math.huge,
colormap={ {0.2, 1, 0.2, 1},{0.2, 1, 0.2, 0.85},{0.2, 1, 0.2, 1} }})},
},
commandAuraBlue = {
{class='StaticParticles', options=commandCoronaBlue},
{class='GroundFlash', options=MergeTable(groundFlashBlue, {radiusFactor=3.5,mobile=true,life=math.huge,
colormap={ {0.2, 0.2, 1, 1},{0.2, 0.2, 1, 0.85},{0.2, 0.2, 1, 1} }})},
},
commandAuraViolet = {
{class='StaticParticles', options=commandCoronaViolet},
{class='GroundFlash', options=MergeTable(groundFlashViolet, {radiusFactor=3.5,mobile=true,life=math.huge,
colormap={ {0.8, 0, 0.8, 1},{0.8, 0, 0.8, 0.85},{0.8, 0, 0.8, 1} }})},
},
commAreaShield = {
--{class='ShieldJitter', options={delay=0, life=math.huge, heightFactor = 0.75, size=350, strength = .001, precision=50, repeatEffect=true, quality=4}},
},
commandShieldRed = {
{class='ShieldSphere', options=MergeTable({colormap1 = {{1, 0.1, 0.1, 0.6}}, colormap2 = {{1, 0.1, 0.1, 0.15}}}, commandShieldSphere)},
-- {class='StaticParticles', options=commandCoronaRed},
-- {class='GroundFlash', options=MergeTable(groundFlashRed, {radiusFactor=3.5,mobile=true,life=60,
-- colormap={ {1, 0.2, 0.2, 1},{1, 0.2, 0.2, 0.85},{1, 0.2, 0.2, 1} }})},
},
commandShieldOrange = {
{class='ShieldSphere', options=MergeTable({colormap1 = {{0.8, 0.3, 0.1, 0.6}}, colormap2 = {{0.8, 0.3, 0.1, 0.15}}}, commandShieldSphere)},
},
commandShieldGreen = {
{class='ShieldSphere', options=MergeTable({colormap1 = {{0.1, 1, 0.1, 0.6}}, colormap2 = {{0.1, 1, 0.1, 0.15}}}, commandShieldSphere)},
},
commandShieldBlue= {
{class='ShieldSphere', options=MergeTable({colormap1 = {{0.1, 0.1, 0.8, 0.6}}, colormap2 = {{0.1, 0.1, 1, 0.15}}}, commandShieldSphere)},
},
commandShieldViolet = {
{class='ShieldSphere', options=MergeTable({colormap1 = {{0.6, 0.1, 0.75, 0.6}}, colormap2 = {{0.6, 0.1, 0.75, 0.15}}}, commandShieldSphere)},
},
}
effectUnitDefs = {
--// FUSIONS //--------------------------
energysingu = {
{class='Bursts', options=energysinguBursts},
{class='StaticParticles', options=energysinguCorona},
--{class='ShieldSphere', options=energysinguShieldSphere},
--{class='ShieldJitter', options={layer=-16, life=math.huge, pos={0,58.9,0}, size=100, precision=22, strength = 0.001, repeatEffect=true}},
{class='GroundFlash', options=groundFlashOrange},
},
--// SHIELDS //---------------------------
-- Don't raise strength of ShieldJitter recklessly, it can really distort things (including unit icons) under it!
staticshield = {
{class='Bursts', options=staticshieldBursts},
{class='ShieldSphere', options=staticshieldBall},
--{class='Bursts',options=shieldBursts350, quality = 3},
--{class='ShieldJitter', options={delay = 0, life=math.huge, pos={0,15,0}, size=355, precision =0, strength = 0.001, repeatEffect = true, quality = 4, onActive = true}},
-- {class='ShieldSphere', options={piece="base", life=math.huge, size=350, pos={0,-15,0}, colormap1 = {{0.95, 0.1, 0.95, 0.2}}, repeatEffect=true}},
-- {class='GroundFlash', options=groundFlashShield},
-- {class='UnitPieceLight', options={piece="glow", colormap = {{0,0,1,0.2}},},},
},
shieldshield = {
{class='Bursts', options=staticshieldBursts},
{class='ShieldSphere', options= staticshieldBall},
--{class='Bursts',options=shieldBursts350, quality = 3},
--{class='ShieldJitter', options={delay = 0, life=math.huge, pos={0,15,0}, size=355, precision =0, strength = 0.001, repeatEffect = true, quality = 4, onActive = true}},
--{class='ShieldJitter', options={delay=0, life=math.huge, pos={0,15,0}, size=355, strength = .001, precision=50, repeatEffect=true, quality = 1, onActive = true}},
-- {class='ShieldSphere', options={piece="base", life=math.huge, size=360, pos={0,-15,0}, colormap1 = {{0.95, 0.1, 0.95, 0.2}}, repeatEffect=true}},
},
shieldfelon = {
--{class='Bursts', options=MergeTable({piece="lpilot"},staticshieldBursts)},
--{class='Bursts', options=MergeTable({piece="rpilot"},staticshieldBursts)},
--{class='ShieldJitter', options={delay=0, life=math.huge, pos={0,15,0}, size=100, strength = .001, precision=50, repeatEffect=true, quality = 5}},
},
striderfunnelweb = {
{class='Bursts', options=MergeTable(staticshieldBurstsBig, {piece="emitl", pos={2,14.3,0}, shieldRechargeDelay = tonumber(WeaponDefNames["striderfunnelweb_shield"].customParams.shield_recharge_delay), colormap = { {0.3, 0.3, 1, 0.8} }})},
{class='Bursts', options=MergeTable(staticshieldBurstsBig, {piece="emitr", pos={-2,14.3,0}, shieldRechargeDelay = tonumber(WeaponDefNames["striderfunnelweb_shield"].customParams.shield_recharge_delay), colormap = { {0.3, 0.3, 1, 0.8} }})},
{class='ShieldSphere', options={piece="emitl", life=math.huge, size=14.5, pos={2,14.3,0}, colormap1 = {{0.1, 0.85, 0.95, 0.9}}, colormap2 = {{0.5, 0.3, 0.95, 0.2}}, rechargingColor1 = {0.95, 0.4, 0.4, 1.0}, rechargingColor2 = {0.95, 0.1, 0.4, 0.2}, shieldRechargeDelay = 30*tonumber(WeaponDefNames["striderfunnelweb_shield"].customParams.shield_recharge_delay), shieldRechargeSize = 7, repeatEffect=true}},
{class='ShieldSphere', options={piece="emitr", life=math.huge, size=14.5, pos={-2,14.3,0}, colormap1 = {{0.1, 0.85, 0.95, 0.9}}, colormap2 = {{0.5, 0.3, 0.95, 0.2}}, rechargingColor1 = {0.95, 0.4, 0.4, 1.0}, rechargingColor2 = {0.95, 0.1, 0.4, 0.2}, shieldRechargeDelay = 30*tonumber(WeaponDefNames["striderfunnelweb_shield"].customParams.shield_recharge_delay), shieldRechargeSize = 7, repeatEffect=false}},
},
--// ENERGY STORAGE //--------------------
energypylon = {
{class='GroundFlash', options=groundFlashenergypylon},
},
--// FACTORIES //----------------------------
factoryship = {
{class='StaticParticles', options=MergeTable(blinkyLightRed, {piece="flash01"}) },
{class='StaticParticles', options=MergeTable(blinkyLightGreen, {piece="flash03", delay = 20,}) },
{class='StaticParticles', options=MergeTable(blinkyLightBlue, {piece="flash05", delay = 40,}) },
},
--// PYLONS // ----------------------------------
staticmex = {
{class='OverdriveParticles', options=staticmexGlow},
},
--// OTHER
roost = {
{class='SimpleParticles', options=roostDirt},
{class='SimpleParticles', options=MergeTable({delay=60},roostDirt)},
{class='SimpleParticles', options=MergeTable({delay=120},roostDirt)},
},
staticrearm= {
{class='StaticParticles', options=MergeTable(blinkyLightRed, {piece="light1"}) },
{class='StaticParticles', options=MergeTable(blinkyLightGreen, {piece="light2"}) },
},
staticheavyradar = {
{class='StaticParticles', options=MergeTable(blinkyLightWhite,{piece="point"})},
--{class='StaticParticles', options=MergeTable(blinkyLightBlue,{piece="point", delay=15})},
},
staticradar = {
{class='StaticParticles', options=MergeTable(radarBlink,{piece="head"})},
{class='StaticParticles', options=MergeTable(radarBlink,{piece="head", delay=15})},
},
spidercrabe = {
{class='StaticParticles', options=MergeTable(blinkyLightWhite, {piece="blight"}) },
},
jumpassault = {
--{class='StaticParticles', options=MergeTable(jackGlow, {piece="point"}) },
},
cloakheavyraid = {
{class='Ribbon', options={color={.3,.3,01,1}, width=5.5, piece="blade", onActive=false, noIconDraw = true, quality = 2}},
},
pw_warpgate = {
{class='StaticParticles', options=warpgateCorona},
-- {class='GroundFlash', options=groundFlashOrange},
},
pw_techlab = {
{class='StaticParticles', options=warpgateCorona},
-- {class='GroundFlash', options=groundFlashOrange},
},
pw_warpjammer = {
{class='StaticParticles', options=MergeTable(warpgateCoronaAlt, {onActive=true})},
},
zenith = {
{class='StaticParticles', options=zenithCorona},
},
amphtele = {
{class='ShieldSphere', options=MergeTable(teleShieldSphere, {piece="sphere"})},
{class='StaticParticles', options=MergeTable(teleCorona, {piece="sphere"})},
--{class='ShieldSphere', options=MergeTable(teleShieldSphere, {piece="sphere", onActive = true, size=18})},
{class='StaticParticles', options=MergeTable(teleCorona, {piece="sphere", onUnitRulesParam = "teleActive", size=100})},
{class='ShieldJitter', options={delay=0, life=math.huge, piece="sphere", size=50, strength = .005, precision=50, repeatEffect=true, onUnitRulesParam = "teleActive", noIconDraw = true, quality = 2,}},
},
amphlaunch = {
{class='ShieldSphere', options=MergeTable(throwShieldSphere, {piece="gunbase"})},
{class='StaticParticles', options=MergeTable(throwCorona, {piece="gunbase"})},
},
tele_beacon = {
{class='ShieldSphere', options=MergeTable(teleShieldSphere, {piece="sphere"})},
{class='StaticParticles', options=MergeTable(teleCorona, {piece="sphere"})},
{class='StaticParticles', options=MergeTable(teleCorona, {piece="sphere", onActive = true, size=50})},
{class='ShieldJitter', options={delay=0, life=math.huge, piece="sphere", size=20, strength = .005, precision=50, repeatEffect=true, onActive=true, noIconDraw = true, quality = 2,}},
},
striderbantha = {
{class='StaticParticles', options=MergeTable(blinkyLightBlue, {piece="light", delay = 20, size = 25}) },
},
striderdetriment = {
{class='StaticParticles', options=MergeTable(blinkyLightGreen, {piece="light", delay = 20, size = 30}) },
},
-- length tag does nothing
--// PLANES //----------------------------
bomberheavy = {
{class='AirJet', options={color={0.4,0.1,0.8}, width=3.5, length=30, piece="nozzle1", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.4,0.1,0.8}, width=3.5, length=30, piece="nozzle2", onActive=true, noIconDraw = true}},
},
gunshipheavyskirm = {
{class='AirJet', options={color={0.0,0.5,1.0}, width=5, length=15, piece="lfjet", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.0,0.5,1.0}, width=5, length=15, piece="rfjet", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.0,0.5,1.0}, width=2.5, length=10, piece="lrjet", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.0,0.5,1.0}, width=2.5, length=10, piece="rrjet", onActive=true, noIconDraw = true}},
},
bomberdisarm = {
{class='AirJet', options={color={0.1,0.4,0.6}, width=3.5, length=20, piece="Jet1", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=3.5, length=20, piece="Jet2", onActive=true, noIconDraw = true}},
{class='Ribbon', options={width=1, size=6, piece="LWingTip", noIconDraw = true}},
{class='Ribbon', options={width=1, size=6, piece="RWingTip", noIconDraw = true}},
--{class='StaticParticles', options=MergeTable(blinkyLightRed, {piece="LWingTip"}) },
--{class='StaticParticles', options=MergeTable(blinkyLightGreen, {piece="RWingTip"}) },
},
athena = {
{class='AirJet', options={color={0.45,0.45,0.9}, width=2.8, length=15, piece="enginel", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.45,0.45,0.9}, width=2.8, length=15, piece="enginer", onActive=true, noIconDraw = true}},
{class='Ribbon', options={width=1, size=12, piece="wingtipl", noIconDraw = true}},
{class='Ribbon', options={width=1, size=12, piece="wingtipr", noIconDraw = true}},
},
gunshipemp = {
{class='Ribbon', options={width=1, size=5, piece="ljet", noIconDraw = true}},
{class='Ribbon', options={width=1, size=5, piece="rjet", noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=3, length=14, piece="ljet", onActive=true, emitVector = {0, 1, 0}, noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=3, length=14, piece="rjet", onActive=true, emitVector = {0, 1, 0}, noIconDraw = true}},
},
gunshipraid = {
{class='Ribbon', options={width=1, size=10, piece="lfx", noIconDraw = true}},
{class='Ribbon', options={width=1, size=10, piece="rfx", noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=4, length=25, piece="lfx", onActive=true, emitVector = {0, 0, 1}, noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=4, length=25, piece="rfx", onActive=true, emitVector = {0, 0, 1}, noIconDraw = true}},
},
planecon = {
{class='Ribbon', options={width=1, size=10, piece="engine1", noIconDraw = true}},
{class='Ribbon', options={width=1, size=10, piece="engine2", noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=8, length=20, piece="body", onActive=true, emitVector = {0, 1, 0}, noIconDraw = true}},
},
gunshipaa = {
{class='AirJet', options={color={0.1,0.4,0.6}, width=4, length=32, piece="ljet", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=4, length=32, piece="rjet", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=4, length=32, piece="mjet", onActive=true, noIconDraw = true}},
},
bomberstrike = {
{class='AirJet', options={color={0.1,0.4,0.6}, width=3.5, length=25, piece="exhaustl", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=3.5, length=25, piece="exhaustr", onActive=true, noIconDraw = true}},
{class='Ribbon', options={width=1, size=10, piece="wingl", noIconDraw = true}},
{class='Ribbon', options={width=1, size=10, piece="wingr", noIconDraw = true}},
},
bomberassault = {
{class='AirJet', options={color={0.1,0.4,0.6}, width=5, length=40, piece="exhaustLeft", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=5, length=40, piece="exhaustRight", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=6, length=60, piece="exhaustTop", onActive=true, noIconDraw = true}},
},
bomberprec = {
{class='AirJet', options={color={0.2,0.4,0.8}, width=4, length=30, piece="thrustr", texture2=":c:bitmaps/gpl/lups/jet2.bmp", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.2,0.4,0.8}, width=4, length=30, piece="thrustl", texture2=":c:bitmaps/gpl/lups/jet2.bmp", onActive=true, noIconDraw = true}},
{class='Ribbon', options={width=1, piece="wingtipl", noIconDraw = true}},
{class='Ribbon', options={width=1, piece="wingtipr", noIconDraw = true}},
{class='StaticParticles', options=MergeTable(blinkyLightRed, {piece="wingtipl"}) },
{class='StaticParticles', options=MergeTable(blinkyLightGreen, {piece="wingtipr"}) },
},
planefighter = {
{class='AirJet', options={color={0.6,0.1,0.0}, width=3.5, length=55, piece="nozzle1", texture2=":c:bitmaps/gpl/lups/jet2.bmp", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.6,0.1,0.0}, width=3.5, length=55, piece="nozzle2", texture2=":c:bitmaps/gpl/lups/jet2.bmp", onActive=true, noIconDraw = true}},
{class='Ribbon', options={width=1, piece="wingtip1", noIconDraw = true}},
{class='Ribbon', options={width=1, piece="wingtip2", noIconDraw = true}},
},
gunshipcon = {
{class='AirJet', options={color={0.1,0.4,0.6}, width=4, length=25, piece="ExhaustForwardRight", onActive=true, emitVector = {0, 0, -1}, noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=4, length=25, piece="ExhaustForwardLeft", onActive=true, emitVector = {0, 0, -1}, noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=3, length=15, piece="ExhaustRearLeft", onActive=true, emitVector = {0, 0, -1}, noIconDraw = true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=3, length=15, piece="ExhaustRearRight", onActive=true, emitVector = {0, 0, -1}, noIconDraw = true}},
},
bomberriot = {
{class='AirJet', options={color={0.7,0.3,0.1}, width=5, length=40, piece="exhaust", onActive=true, noIconDraw = true}},
{class='Ribbon', options={width=1, piece="wingtipl", noIconDraw = true}},
{class='Ribbon', options={width=1, piece="wingtipr", noIconDraw = true}},
{class='StaticParticles', options=MergeTable(blinkyLightRed, {piece="wingtipr"}) },
{class='StaticParticles', options=MergeTable(blinkyLightGreen, {piece="wingtipl"}) },
},
planeheavyfighter = {
-- jets done in gadget
{class='Ribbon', options={width=1, size=8, piece="wingtip1", noIconDraw = true}},
{class='Ribbon', options={width=1, size=8, piece="wingtip2", noIconDraw = true}},
},
gunshipheavytrans = {
{class='ShieldSphere', options=MergeTable(teleShieldSphere, {piece="agrav1", onActive=true})},
{class='StaticParticles', options=MergeTable(teleCorona, {piece="agrav1", onActive=true})},
{class='ShieldSphere', options=MergeTable(teleShieldSphere, {piece="agrav2", onActive=true})},
{class='StaticParticles', options=MergeTable(teleCorona, {piece="agrav2", onActive=true})},
{class='ShieldSphere', options=MergeTable(teleShieldSphere, {piece="agrav3", onActive=true})},
{class='StaticParticles', options=MergeTable(teleCorona, {piece="agrav3", onActive=true})},
{class='ShieldSphere', options=MergeTable(teleShieldSphere, {piece="agrav4", onActive=true})},
{class='StaticParticles', options=MergeTable(teleCorona, {piece="agrav4", onActive=true})},
},
gunshiptrans = {
{class='AirJet', options={color={0.2,0.4,0.8}, width=3.5, length=22, piece="engineEmit", onActive=true}},
{class='ShieldSphere', options=MergeTable(valkShieldSphere, {piece="agrav1", onActive=true})},
{class='StaticParticles', options=MergeTable(valkCorona, {piece="agrav1", onActive=true})},
{class='ShieldSphere', options=MergeTable(valkShieldSphere, {piece="agrav2", onActive=true})},
{class='StaticParticles', options=MergeTable(valkCorona, {piece="agrav2", onActive=true})},
{class='ShieldSphere', options=MergeTable(valkShieldSphere, {piece="agrav3", onActive=true})},
{class='StaticParticles', options=MergeTable(valkCorona, {piece="agrav3", onActive=true})},
{class='ShieldSphere', options=MergeTable(valkShieldSphere, {piece="agrav4", onActive=true})},
{class='StaticParticles', options=MergeTable(valkCorona, {piece="agrav4", onActive=true})},
},
planescout = {
{class='AirJet', options={color={0.1,0.4,0.6}, width=3.5, length=25, piece="thrust", onActive=true}},
{class='Ribbon', options={width=1, size=8, piece="wingtipl"}},
{class='Ribbon', options={width=1, size=8, piece="wingtipr"}},
{class='StaticParticles', options=MergeTable(blinkyLightRed, {piece="wingtipr"}) },
{class='StaticParticles', options=MergeTable(blinkyLightGreen, {piece="wingtipl"}) },
},
planelightscout = {
{class='AirJet', options={color={0.1,0.4,0.6}, width=1.8, length=15, piece="exhaustl", onActive=true}},
{class='AirJet', options={color={0.1,0.4,0.6}, width=1.8, length=15, piece="exhaustr", onActive=true}},
{class='Ribbon', options={width=1, size=6, piece="wingtipl"}},
{class='Ribbon', options={width=1, size=6, piece="wingtipr"}},
--{class='StaticParticles', options=MergeTable(blinkyLightRed, {piece="wingtipr"}) },
--{class='StaticParticles', options=MergeTable(blinkyLightGreen, {piece="wingtipl"}) },
},
gunshipassault = {
{class='AirJet', options={color={0.8,0.1,0.0}, width=7, length=30, jitterWidthScale=2, distortion=0.01, piece="Lengine", texture2=":c:bitmaps/gpl/lups/jet2.bmp", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.8,0.1,0.0}, width=7, length=30, jitterWidthScale=2, distortion=0.01, piece="Rengine", texture2=":c:bitmaps/gpl/lups/jet2.bmp", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.8,0.1,0.0}, width=7, length=30, jitterWidthScale=2, distortion=0.01, piece="Lwingengine", texture2=":c:bitmaps/gpl/lups/jet2.bmp", onActive=true, noIconDraw = true}},
{class='AirJet', options={color={0.8,0.1,0.0}, width=7, length=30, jitterWidthScale=2, distortion=0.01, piece="Rwingengine", texture2=":c:bitmaps/gpl/lups/jet2.bmp", onActive=true, noIconDraw = true}},
},
gunshipkrow = {
{class='AirJet', options={color={0.0,0.5,1.0}, width=10, length=20, piece="jetrear", onActive=true, emitVector = {0, 0, 1}, noIconDraw = true}},
{class='AirJet', options={color={0.0,0.5,1.0}, width=10, length=20, piece="jetleft", onActive=true, emitVector = {0, 0, 1}, noIconDraw = true}},
{class='AirJet', options={color={0.0,0.5,1.0}, width=10, length=20, piece="jetright", onActive=true, emitVector = {0, 0, 1}, noIconDraw = true}},
},
nebula = {
{class='AirJet', options={color={0.0,0.5,1.0}, width=15, length=60, piece="exhaustmain", onActive=true}},
{class='AirJet', options={color={0.0,0.5,1.0}, width=8, length=25, piece="exhaust1", onActive=true, emitVector = {0, 1, 0}}},
{class='AirJet', options={color={0.0,0.5,1.0}, width=8, length=25, piece="exhaust2", onActive=true, emitVector = {0, 1, 0}}},
{class='AirJet', options={color={0.0,0.5,1.0}, width=8, length=25, piece="exhaust3", onActive=true, emitVector = {0, 1, 0}}},
{class='AirJet', options={color={0.0,0.5,1.0}, width=8, length=25, piece="exhaust4", onActive=true, emitVector = {0, 1, 0}}},
{class='StaticParticles', options=MergeTable(blinkyLightRed, {piece="light2"}) },
{class='StaticParticles', options=MergeTable(blinkyLightGreen, {piece="light1"}) },
},
dronefighter = {
--{class='AirJet', options={color={0.6,0.1,0.0}, width=3, length=40, piece="DroneMain", texture2=":c:bitmaps/gpl/lups/jet2.bmp", onActive=true}},
{class='Ribbon', options={width=1, size=24, piece="DroneMain"}},
},
}
effectUnitDefsXmas = {}
local levelScale = {
[0] = 1,
[1] = 1,
[2] = 1.1,
[3] = 1.2,
[4] = 1.25,
[5] = 1.3,
}
-- load presets from unitdefs
for i=1,#UnitDefs do
local unitDef = UnitDefs[i]
if unitDef.customParams and unitDef.customParams.commtype then
local s = levelScale[tonumber(unitDef.customParams.level) or 1]
if unitDef.customParams.commtype == "1" then
effectUnitDefsXmas[unitDef.name] = {
{class='SantaHat', options={pos={0.3*s,1.1*s,-6 - 3*s}, emitVector={-1,0,-0.08}, width=3.6*s, height=6.2*s, ballSize=0.9*s, piece="Head"}},
}
elseif unitDef.customParams.commtype == "2" then
effectUnitDefsXmas[unitDef.name] = {
{class='SantaHat', options={pos={0,6*s,2*s}, emitVector={0.4,1,0.2}, width=2.7*s, height=6*s, ballSize=0.7*s, piece="head"}},
}
elseif unitDef.customParams.commtype == "3" then
effectUnitDefsXmas[unitDef.name] = {
{class='SantaHat', options={color={0,0.7,0,1}, pos={1.5*s,4*s,0.5*s}, emitVector={0.7,1.6,0.2}, width=2.5*s, height=6*s, ballSize=0.7*s, piece="head"}},
}
elseif unitDef.customParams.commtype == "4" then
effectUnitDefsXmas[unitDef.name] = {
{class='SantaHat', options={pos={0,3.8*s,0.35*s}, emitVector={0,1,0}, width=2.7*s, height=6*s, ballSize=0.7*s, piece="head"}},
}
elseif unitDef.customParams.commtype == "5" then
effectUnitDefsXmas[unitDef.name] = {
{class='SantaHat', options={color={0,0.7,0,1}, pos={0,0,0}, emitVector={0,1,0.1}, width=2.7*s, height=6*s, ballSize=0.7*s, piece="hat"}},
}
elseif unitDef.customParams.commtype == "6" then
effectUnitDefsXmas[unitDef.name] = {
{class='SantaHat', options={color={0,0,0.7,1}, pos={0,0,0}, emitVector={0,1,-0.1}, width=4.05*s, height=9*s, ballSize=1.05*s, piece="hat"}},
}
end
end
if unitDef.customParams then
local fxTableStr = unitDef.customParams.lups_unit_fxs
if fxTableStr then
local fxTableFunc = loadstring("return "..fxTableStr)
local fxTable = fxTableFunc()
effectUnitDefs[unitDef.name] = effectUnitDefs[unitDef.name] or {}
for i=1,#fxTable do -- for each item in preset table
local toAdd = presets[fxTable[i]]
for i=1,#toAdd do
table.insert(effectUnitDefs[unitDef.name],toAdd[i]) -- append to unit's lupsFX table
end
end
end
end
end
| gpl-2.0 |
arychen/GlobalCall | feeds/luci/modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/network.lua | 48 | 2480 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
m = Map("network", translate("Interfaces"))
m.pageaction = false
m:section(SimpleSection).template = "admin_network/iface_overview"
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
m.pageaction = true
end
local network = require "luci.model.network"
if network:has_ipv6() then
local s = m:section(NamedSection, "globals", "globals", translate("Global network options"))
local o = s:option(Value, "ula_prefix", translate("IPv6 ULA-Prefix"))
o.datatype = "ip6addr"
o.rmempty = true
m.pageaction = true
end
return m
| gpl-2.0 |
immibis/wiremod | lua/entities/gmod_wire_user.lua | 9 | 1183 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire User"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "User"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "Fire"})
self:Setup(2048)
end
function ENT:Setup(Range)
if Range then self:SetBeamLength(Range) end
end
function ENT:TriggerInput(iname, value)
if (iname == "Fire") then
if (value ~= 0) then
local vStart = self:GetPos()
local trace = util.TraceLine( {
start = vStart,
endpos = vStart + (self:GetUp() * self:GetBeamLength()),
filter = { self },
})
if not IsValid(trace.Entity) then return false end
local ply = self:GetPlayer()
if not IsValid(ply) then ply = self end
if trace.Entity.Use then
trace.Entity:Use(ply,ply,USE_ON,0)
else
trace.Entity:Fire("use","1",0)
end
end
end
end
duplicator.RegisterEntityClass("gmod_wire_user", WireLib.MakeWireEnt, "Data", "Range")
| apache-2.0 |
Aquanim/Zero-K | ModelMaterials/255_features_fallback.lua | 8 | 1229 | local matTemplate = VFS.Include("ModelMaterials/Templates/defaultMaterialTemplate.lua")
local materials = {
featuresFallback = Spring.Utilities.MergeWithDefault(matTemplate, {
texUnits = {
[0] = "%%FEATUREDEFID:0",
[1] = "%%FEATUREDEFID:1",
},
feature = true,
deferredOptions = {
materialIndex = 255,
},
})
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local cusFeaturesMaterials = GG.CUS.featureMaterialDefs
local featureMaterials = {}
for id = 1, #FeatureDefs do
if not cusFeaturesMaterials[id] then
Spring.Log(gadget:GetInfo().name, LOG.WARNING, string.format("Assigning featuresFallback material to feature %s. This should never happen.", FeatureDefs[id].name))
featureMaterials[id] = {"featuresFallback"}
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
return materials, featureMaterials
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
stars2014/quick-ng | external/lua/luasocket/script/ltn12.lua | 71 | 8331 | -----------------------------------------------------------------------------
-- LTN12 - Filters, sources, sinks and pumps.
-- LuaSocket toolkit.
-- Author: Diego Nehab
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module
-----------------------------------------------------------------------------
local string = require("string")
local table = require("table")
local base = _G
local _M = {}
if module then -- heuristic for exporting a global package table
ltn12 = _M
end
local filter,source,sink,pump = {},{},{},{}
_M.filter = filter
_M.source = source
_M.sink = sink
_M.pump = pump
-- 2048 seems to be better in windows...
_M.BLOCKSIZE = 2048
_M._VERSION = "LTN12 1.0.3"
-----------------------------------------------------------------------------
-- Filter stuff
-----------------------------------------------------------------------------
-- returns a high level filter that cycles a low-level filter
function filter.cycle(low, ctx, extra)
base.assert(low)
return function(chunk)
local ret
ret, ctx = low(ctx, chunk, extra)
return ret
end
end
-- chains a bunch of filters together
-- (thanks to Wim Couwenberg)
function filter.chain(...)
local arg = {...}
local n = select('#',...)
local top, index = 1, 1
local retry = ""
return function(chunk)
retry = chunk and retry
while true do
if index == top then
chunk = arg[index](chunk)
if chunk == "" or top == n then return chunk
elseif chunk then index = index + 1
else
top = top+1
index = top
end
else
chunk = arg[index](chunk or "")
if chunk == "" then
index = index - 1
chunk = retry
elseif chunk then
if index == n then return chunk
else index = index + 1 end
else base.error("filter returned inappropriate nil") end
end
end
end
end
-----------------------------------------------------------------------------
-- Source stuff
-----------------------------------------------------------------------------
-- create an empty source
local function empty()
return nil
end
function source.empty()
return empty
end
-- returns a source that just outputs an error
function source.error(err)
return function()
return nil, err
end
end
-- creates a file source
function source.file(handle, io_err)
if handle then
return function()
local chunk = handle:read(_M.BLOCKSIZE)
if not chunk then handle:close() end
return chunk
end
else return source.error(io_err or "unable to open file") end
end
-- turns a fancy source into a simple source
function source.simplify(src)
base.assert(src)
return function()
local chunk, err_or_new = src()
src = err_or_new or src
if not chunk then return nil, err_or_new
else return chunk end
end
end
-- creates string source
function source.string(s)
if s then
local i = 1
return function()
local chunk = string.sub(s, i, i+_M.BLOCKSIZE-1)
i = i + _M.BLOCKSIZE
if chunk ~= "" then return chunk
else return nil end
end
else return source.empty() end
end
-- creates rewindable source
function source.rewind(src)
base.assert(src)
local t = {}
return function(chunk)
if not chunk then
chunk = table.remove(t)
if not chunk then return src()
else return chunk end
else
table.insert(t, chunk)
end
end
end
function source.chain(src, f)
base.assert(src and f)
local last_in, last_out = "", ""
local state = "feeding"
local err
return function()
if not last_out then
base.error('source is empty!', 2)
end
while true do
if state == "feeding" then
last_in, err = src()
if err then return nil, err end
last_out = f(last_in)
if not last_out then
if last_in then
base.error('filter returned inappropriate nil')
else
return nil
end
elseif last_out ~= "" then
state = "eating"
if last_in then last_in = "" end
return last_out
end
else
last_out = f(last_in)
if last_out == "" then
if last_in == "" then
state = "feeding"
else
base.error('filter returned ""')
end
elseif not last_out then
if last_in then
base.error('filter returned inappropriate nil')
else
return nil
end
else
return last_out
end
end
end
end
end
-- creates a source that produces contents of several sources, one after the
-- other, as if they were concatenated
-- (thanks to Wim Couwenberg)
function source.cat(...)
local arg = {...}
local src = table.remove(arg, 1)
return function()
while src do
local chunk, err = src()
if chunk then return chunk end
if err then return nil, err end
src = table.remove(arg, 1)
end
end
end
-----------------------------------------------------------------------------
-- Sink stuff
-----------------------------------------------------------------------------
-- creates a sink that stores into a table
function sink.table(t)
t = t or {}
local f = function(chunk, err)
if chunk then table.insert(t, chunk) end
return 1
end
return f, t
end
-- turns a fancy sink into a simple sink
function sink.simplify(snk)
base.assert(snk)
return function(chunk, err)
local ret, err_or_new = snk(chunk, err)
if not ret then return nil, err_or_new end
snk = err_or_new or snk
return 1
end
end
-- creates a file sink
function sink.file(handle, io_err)
if handle then
return function(chunk, err)
if not chunk then
handle:close()
return 1
else return handle:write(chunk) end
end
else return sink.error(io_err or "unable to open file") end
end
-- creates a sink that discards data
local function null()
return 1
end
function sink.null()
return null
end
-- creates a sink that just returns an error
function sink.error(err)
return function()
return nil, err
end
end
-- chains a sink with a filter
function sink.chain(f, snk)
base.assert(f and snk)
return function(chunk, err)
if chunk ~= "" then
local filtered = f(chunk)
local done = chunk and ""
while true do
local ret, snkerr = snk(filtered, err)
if not ret then return nil, snkerr end
if filtered == done then return 1 end
filtered = f(done)
end
else return 1 end
end
end
-----------------------------------------------------------------------------
-- Pump stuff
-----------------------------------------------------------------------------
-- pumps one chunk from the source to the sink
function pump.step(src, snk)
local chunk, src_err = src()
local ret, snk_err = snk(chunk, src_err)
if chunk and ret then return 1
else return nil, src_err or snk_err end
end
-- pumps all data from a source to a sink, using a step function
function pump.all(src, snk, step)
base.assert(src and snk)
step = step or pump.step
while true do
local ret, err = step(src, snk)
if not ret then
if err then return nil, err
else return 1 end
end
end
end
return _M
| mit |
Sakura-Winkey/LuCI | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/network.lua | 53 | 2738 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
m = Map("luci_statistics",
translate("Network Plugin Configuration"),
translate(
"The network plugin provides network based communication between " ..
"different collectd instances. Collectd can operate both in client " ..
"and server mode. In client mode locally collected data is " ..
"transferred to a collectd server instance, in server mode the " ..
"local instance receives data from other hosts."
))
-- collectd_network config section
s = m:section( NamedSection, "collectd_network", "luci_statistics" )
-- collectd_network.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_network_listen config section (Listen)
listen = m:section( TypedSection, "collectd_network_listen",
translate("Listener interfaces"),
translate(
"This section defines on which interfaces collectd will wait " ..
"for incoming connections."
))
listen.addremove = true
listen.anonymous = true
-- collectd_network_listen.host
listen_host = listen:option( Value, "host", translate("Listen host") )
listen_host.default = "0.0.0.0"
-- collectd_network_listen.port
listen_port = listen:option( Value, "port", translate("Listen port") )
listen_port.default = 25826
listen_port.isinteger = true
listen_port.optional = true
-- collectd_network_server config section (Server)
server = m:section( TypedSection, "collectd_network_server",
translate("server interfaces"),
translate(
"This section defines to which servers the locally collected " ..
"data is sent to."
))
server.addremove = true
server.anonymous = true
-- collectd_network_server.host
server_host = server:option( Value, "host", translate("Server host") )
server_host.default = "0.0.0.0"
-- collectd_network_server.port
server_port = server:option( Value, "port", translate("Server port") )
server_port.default = 25826
server_port.isinteger = true
server_port.optional = true
-- collectd_network.timetolive (TimeToLive)
ttl = s:option( Value, "TimeToLive", translate("TTL for network packets") )
ttl.default = 128
ttl.isinteger = true
ttl.optional = true
ttl:depends( "enable", 1 )
-- collectd_network.forward (Forward)
forward = s:option( Flag, "Forward", translate("Forwarding between listen and server addresses") )
forward.default = 0
forward.optional = true
forward:depends( "enable", 1 )
-- collectd_network.cacheflush (CacheFlush)
cacheflush = s:option( Value, "CacheFlush",
translate("Cache flush interval"), translate("Seconds") )
cacheflush.default = 86400
cacheflush.isinteger = true
cacheflush.optional = true
cacheflush:depends( "enable", 1 )
return m
| apache-2.0 |
b03605079/darkstar | scripts/globals/items/rice_ball.lua | 14 | 1508 | -----------------------------------------
-- ID: 4405
-- Item: rice_ball
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP 10, Vit +2, Dex -1, hHP +1 (Def +50)*enhances rice ball effect
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/equipment");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,RiceBalls(target),0,1800,4405);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
local power = effect:getPower();
target:addMod(MOD_HP, 10);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_DEX, -1);
target:addMod(MOD_DEF, 40*power);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
local power = effect:getPower();
target:delMod(MOD_HP, 10);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_DEX, -1);
target:delMod(MOD_DEF, 40*power);
end;
| gpl-3.0 |
b03605079/darkstar | scripts/zones/Al_Zahbi/npcs/Shihu-Danhu.lua | 19 | 2097 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Shihu-Danhu
-- Warp NPC
-- @pos 62.768 -1.98 -51.299 48
-----------------------------------
require("scripts/globals/besieged");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(getAstralCandescence() == 1) then
player:startEvent(0x0067);
else
player:messageSpecial(0); -- Missing the denied due to lack of Astral Candescence message.
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x0067 and option == 1) then
-- If you use TP, you need to wait 1 real day for using Kaduru TP
player:setVar("ShihuDanhu_TP_date",os.date("%j"));
-- Random TP positions
-- Coordinates marked {R} have been obtained by packet capture from retail. Don't change them.
-- TODO: if we have astral candesence, then
local warp = math.random(1,5);
if(warp == 1) then
player:setPos(-1.015, 8.999, -52.962, 192, 243); -- Ru Lude Gardens (H-9) {R}
elseif(warp == 2) then
player:setPos(382.398, 7.314, -106.298, 160, 105); -- Batallia Downs (K-8) {R}
elseif(warp == 3) then
player:setPos(-327.238, 2.914, 438.421, 130, 120); -- Sauromugue Champaign {R}
elseif(warp == 4) then
player:setPos(213.785, 16.356, 419.961, 218, 110); -- Rolanberry Fields (J-6) {R}
elseif(warp == 5) then
player:setPos(167.093, 18.095, -213.352, 73, 126); -- Qufim Island (I-9) {R}
end
-- TODO: elseif candesence is lost, then
-- tele to bat downs, rolanberry, qufim, sauro. POSITIONS ARE DIFFERENT. need packet captures.
end
end; | gpl-3.0 |
b03605079/darkstar | scripts/globals/items/yilanbaligi.lua | 18 | 1328 | -----------------------------------------
-- ID: 5458
-- Item: Yilanbaligi
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Mind -4
-- Evasion 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:getRace() ~= 7) then
result = 247;
end
if(target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5458);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MND, -4);
target:addMod(MOD_EVA, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MND, -4);
target:delMod(MOD_EVA, 5);
end;
| gpl-3.0 |
b03605079/darkstar | scripts/zones/Southern_San_dOria/npcs/HomePoint#3.lua | 12 | 1261 | -----------------------------------
-- Area: Southern San dOria
-- NPC: HomePoint#3
-- @pos 140 -2 123 230
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fe, 2);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x21fe) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
vejmelkam/optim | polyinterp.lua | 13 | 6321 | local function isreal(x)
return x == x
end
local function isnan(x)
return not x == x
end
local function roots(c)
local tol=1e-12
c[torch.lt(torch.abs(c),tol)]=0
local nonzero = torch.ne(c,0)
if nonzero:max() == 0 then
return 0
end
-- first non-zero
local _,pos = torch.max(nonzero,1)
pos = pos[1]
c=c[{ {pos,-1} }]
local nz = 0
for i=c:size(1),1,-1 do
if c[i] ~= 0 then
break
else
nz = nz + 1
end
end
c=c[{ {1,c:size(1)-nz} }]
local n = c:size(1)-1
if n == 1 then
local e = torch.Tensor({{-c[2]/c[1], 0}})
if nz > 0 then
return torch.cat(e, torch.zeros(nz, 2), 1)
else
return e
end
elseif n > 1 then
local A = torch.diag(torch.ones(n-1),-1)
A[1] = -c[{ {2,n+1} }]/c[1];
local e = torch.eig(A,'N')
if nz > 0 then
return torch.cat(e, torch.zeros(nz,2), 1)
else
return e
end
else
return torch.zeros(nz,2)
end
end
local function real(x)
if type(x) == number then return x end
return x[{ {} , 1}]
end
local function imag(x)
if type(x) == 'number' then return 0 end
if x:nDimension() == 1 then
return torch.zeros(x:size(1))
else
return x[{ {}, 2}]
end
end
local function polyval(p,x)
local pwr = p:size(1)
if type(x) == 'number' then
local val = 0
p:apply(function(pc) pwr = pwr-1; val = val + pc*x^pwr; return pc end)
return val
else
local val = x.new(x:size(1))
p:apply(function(pc) pwr = pwr-1; val:add(pc,torch.pow(x,pwr)); return pc end)
return val
end
end
----------------------------------------------------------------------
-- Minimum of interpolating polynomial based on function and
-- derivative values
--
-- ARGS:
-- points : N triplets (x,f,g), must be a Tensor
-- xmin : min value that brackets minimum (default: min of points)
-- xmax : max value that brackets maximum (default: max of points)
--
-- RETURN:
-- minPos : position of minimum
--
function optim.polyinterp(points,xminBound,xmaxBound)
-- locals
local sqrt = torch.sqrt
local mean = torch.mean
local Tensor = torch.Tensor
local zeros = torch.zeros
local max = math.max
local min = math.min
-- nb of points / order of polynomial
local nPoints = points:size(1)
local order = nPoints*2-1
-- returned values
local minPos
-- Code for most common case:
-- + cubic interpolation of 2 points w/ function and derivative values for both
-- + no xminBound/xmaxBound
if nPoints == 2 and order == 3 and not xminBound and not xmaxBound then
-- Solution in this case (where x2 is the farthest point):
-- d1 = g1 + g2 - 3*(f1-f2)/(x1-x2);
-- d2 = sqrt(d1^2 - g1*g2);
-- minPos = x2 - (x2 - x1)*((g2 + d2 - d1)/(g2 - g1 + 2*d2));
-- t_new = min(max(minPos,x1),x2);
local minVal,minPos = points[{ {},1 }]:min(1)
minVal = minVal[1] minPos = minPos[1]
local notMinPos = -minPos+3;
local d1 = points[{minPos,3}] + points[{notMinPos,3}]
- 3*(points[{minPos,2}]-points[{notMinPos,2}])
/ (points[{minPos,1}]-points[{notMinPos,1}]);
local d2 = sqrt(d1^2 - points[{minPos,3}]*points[{notMinPos,3}]);
if isreal(d2) then -- isreal()
local t = points[{notMinPos,1}] - (points[{notMinPos,1}]
- points[{minPos,1}]) * ((points[{notMinPos,3}] + d2 - d1)
/ (points[{notMinPos,3}] - points[{minPos,3}] + 2*d2))
minPos = min(max(t,points[{minPos,1}]),points[{notMinPos,1}])
else
minPos = mean(points[{{},1}])
end
return minPos
end
-- TODO: get the code below to work!
--error('<optim.polyinterp> extrapolation not implemented yet...')
-- Compute Bounds of Interpolation Area
local xmin = points[{{},1}]:min()
local xmax = points[{{},1}]:max()
xminBound = xminBound or xmin
xmaxBound = xmaxBound or xmax
-- Add constraints on function values
local A = zeros(nPoints*2,order+1)
local b = zeros(nPoints*2,1)
for i = 1,nPoints do
local constraint = zeros(order+1)
for j = order,0,-1 do
constraint[order-j+1] = points[{i,1}]^j
end
A[i] = constraint
b[i] = points[{i,2}]
end
-- Add constraints based on derivatives
for i = 1,nPoints do
local constraint = zeros(order+1)
for j = 1,order do
constraint[j] = (order-j+1)*points[{i,1}]^(order-j)
end
A[nPoints+i] = constraint
b[nPoints+i] = points[{i,3}]
end
-- Find interpolating polynomial
local res = torch.gels(b,A)
local params = res[{ {1,nPoints*2} }]:squeeze()
--print(A)
--print(b)
--print(params)
params[torch.le(torch.abs(params),1e-12)]=0
-- Compute Critical Points
local dParams = zeros(order);
for i = 1,params:size(1)-1 do
dParams[i] = params[i]*(order-i+1)
end
-- nan/inf?
local nans = false
if torch.ne(dParams,dParams):max() > 0 or torch.eq(dParams,math.huge):max() > 0 then
nans = true
end
-- for i = 1,dParams:size(1) do
-- if dParams[i] ~= dParams[i] or dParams[i] == math.huge then
-- nans = true
-- break
-- end
-- end
local cp = torch.cat(Tensor{xminBound,xmaxBound},points[{{},1}])
if not nans then
local cproots = roots(dParams)
local cpi = zeros(cp:size(1),2)
cpi[{ {1,cp:size(1)} , 1 }] = cp
cp = torch.cat(cpi,cproots,1)
end
--print(dParams)
--print(cp)
-- Test Critical Points
local fmin = math.huge
-- Default to Bisection if no critical points valid:
minPos = (xminBound+xmaxBound)/2
--print(minPos,fmin)
--print(xminBound,xmaxBound)
for i = 1,cp:size(1) do
local xCP = cp[{ {i,i} , {} }]
--print('xcp=')
--print(xCP)
local ixCP = imag(xCP)[1]
local rxCP = real(xCP)[1]
if ixCP == 0 and rxCP >= xminBound and rxCP <= xmaxBound then
local fCP = polyval(params,rxCP)
--print('fcp=')
--print(fCP)
--print(fCP < fmin)
if fCP < fmin then
minPos = rxCP
fmin = fCP
--print('u',minPos,fmin)
end
--print('v',minPos,fmin)
end
end
return minPos,fmin
end
| bsd-3-clause |
codedustgames/caress-framework | classeslib/Object/Sprite.lua | 1 | 1341 | -- Caress, a small framework for games in lua and love.
-- Copyright (C) 2016 Erivaldo Filho "desadoc@gmail.com"
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- 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 Lesser General Public License for more details.
-- You should have received a copy of the GNU Lesser General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--- Sprite class.
--
-- Represents a single sprite in a sprite sheet.
--
-- @classmod Object.Sprite
local _class = {}
local spriteSheet
local quad
local width
local height
function _class:init(_spriteSheet, _spriteData)
spriteSheet = _spriteSheet
quad = _spriteData.quad
width = _spriteData.width
height = _spriteData.height
end
function _class:getSpriteSheet()
return spriteSheet
end
function _class:getQuad()
return quad
end
function _class:getWidth()
return width
end
function _class:getHeight()
return height
end
return _class
| gpl-3.0 |
b03605079/darkstar | scripts/globals/items/serving_of_patriarch_sautee.lua | 36 | 1253 | -----------------------------------------
-- ID: 5677
-- Item: Serving of Patriarch Sautee
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- MP 60
-- Mind 7
-- MP Recovered While Healing 7
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5677);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 60);
target:addMod(MOD_MND, 7);
target:addMod(MOD_MPHEAL, 7);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 60);
target:delMod(MOD_MND, 7);
target:delMod(MOD_MPHEAL, 7);
end;
| gpl-3.0 |
b03605079/darkstar | scripts/zones/Fort_Karugo-Narugo_[S]/npcs/Mortimer.lua | 35 | 1055 | ----------------------------------
-- Area: Fort Karugo Narugo [S]
-- NPC: Mortimer
-- Type: Item Deliverer
-- @zone: 96
-- @pos -24.08 -68.508 93.88
--
-----------------------------------
package.loaded["scripts/zones/Fort_Karugo-Narugo_[S]/TextIDs"] = nil;
require("scripts/zones/Fort_Karugo-Narugo_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, ITEM_DELIVERY_DIALOG);
player:openSendBox();
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Tatuy/UAWebsite | account/LUA/TFS_03/talkaction shopsystem/znoteshop.lua | 1 | 2693 | -- Znote Shop v1.0 for Znote AAC on TFS 0.3.6+ Crying Damson.
function onSay(cid, words, param)
local storage = 54073 -- Make sure to select non-used storage. This is used to prevent SQL load attacks.
local cooldown = 15 -- in seconds.
if getPlayerStorageValue(cid, storage) <= os.time() then
setPlayerStorageValue(cid, storage, os.time() + cooldown)
local accid = getAccountNumberByPlayerName(getCreatureName(cid))
-- Create the query
local orderQuery = db.storeQuery("SELECT `id`, `type`, `itemid`, `count` FROM `znote_shop_orders` WHERE `account_id` = " .. accid .. " LIMIT 1;")
-- Detect if we got any results
if orderQuery ~= false then
-- Fetch order values
local q_id = result.getDataInt(orderQuery, "id")
local q_type = result.getDataInt(orderQuery, "type")
local q_itemid = result.getDataInt(orderQuery, "itemid")
local q_count = result.getDataInt(orderQuery, "count")
result.free(orderQuery)
-- ORDER TYPE 1 (Regular item shop products)
if q_type == 1 then
-- Get wheight
local playerCap = getPlayerFreeCap(cid)
local itemweight = getItemWeightById(q_itemid, q_count)
if playerCap >= itemweight and getTileInfo(getCreaturePosition(cid)).protection then
--backpack check
local backpack = getPlayerSlotItem(cid, 3)
local gotItem = false
if(backpack and backpack.itemid > 0) then
local received = doAddContainerItem(getPlayerSlotItem(cid, 3).uid, q_itemid,q_count)
if(received ~= false) then
db.executeQuery("DELETE FROM `znote_shop_orders` WHERE `id` = " .. q_id .. ";")
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, "Congratulations! You have recieved ".. q_count .." "..getItemNameById(q_itemid).."(s)!")
gotItem = true
end
end
if(not gotItem) then
doPlayerSendTextMessage(cid, MESSAGE_STATUS_WARNING, "You have no available space in backpack to receive that item.")
end
else
doPlayerSendTextMessage(cid, MESSAGE_STATUS_WARNING, "Need more CAP and Need ProtectZone!")
end
end
-- Add custom order types here
-- Type 2 is reserved for premium days and is handled on website, not needed here.
-- Type 3 is reserved for character gender(sex) change and is handled on website as well.
-- So use type 4+ for custom stuff, like etc packages.
-- if q_type == 4 then
-- end
else
doPlayerSendTextMessage(cid, MESSAGE_STATUS_WARNING, "You have no orders.")
end
else
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Can only be executed once every "..cooldown.." seconds. Remaining cooldown: ".. getPlayerStorageValue(cid, storage) - os.time())
end
return false
end | apache-2.0 |
b03605079/darkstar | scripts/globals/items/steamed_crayfish.lua | 35 | 1239 | -----------------------------------------
-- ID: 4338
-- Item: steamed_crayfish
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Defense % 30
-- Defense Cap 30
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,4338);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_DEFP, 30);
target:addMod(MOD_FOOD_DEF_CAP, 30);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_DEFP, 30);
target:delMod(MOD_FOOD_DEF_CAP, 30);
end;
| gpl-3.0 |
Whit3Tig3R/bot-telegram | plugins/anti-flood.lua | 281 | 2422 | local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds
local TIME_CHECK = 5
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, function (data, success, result)
if success ~= 1 then
local text = 'I can\'t kick '..data.user..' but should be kicked'
send_msg(data.chat, '', ok_cb, nil)
end
end, {chat=chat, user=user})
end
local function run (msg, matches)
if msg.to.type ~= 'chat' then
return 'Anti-flood works only on channels'
else
local chat = msg.to.id
local hash = 'anti-flood:enabled:'..chat
if matches[1] == 'enable' then
redis:set(hash, true)
return 'Anti-flood enabled on chat'
end
if matches[1] == 'disable' then
redis:del(hash)
return 'Anti-flood disabled on chat'
end
end
end
local function pre_process (msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
local hash_enable = 'anti-flood:enabled:'..msg.to.id
local enabled = redis:get(hash_enable)
if enabled then
print('anti-flood enabled')
-- Check flood
if msg.from.type == 'user' then
-- Increase the number of messages from the user on the chat
local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
local receiver = get_receiver(msg)
local user = msg.from.id
local text = 'User '..user..' is flooding'
local chat = msg.to.id
send_msg(receiver, text, ok_cb, nil)
if msg.to.type ~= 'chat' then
print("Flood in not a chat group!")
elseif user == tostring(our_id) then
print('I won\'t kick myself')
elseif is_sudo(msg) then
print('I won\'t kick an admin!')
else
-- Ban user
-- TODO: Check on this plugin bans
local bhash = 'banned:'..msg.to.id..':'..msg.from.id
redis:set(bhash, true)
kick_user(user, chat)
end
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
end
return msg
end
return {
description = 'Plugin to kick flooders from group.',
usage = {},
patterns = {
'^!antiflood (enable)$',
'^!antiflood (disable)$'
},
run = run,
privileged = true,
pre_process = pre_process
}
| gpl-2.0 |
dhlab-basel/Knora | sipi/scripts/delete_temp_file.lua | 1 | 2743 | -- * Copyright © 2021 - 2022 Swiss National Data and Service Center for the Humanities and/or DaSCH Service Platform contributors.
-- * SPDX-License-Identifier: Apache-2.0
--
-- Deletes a file from temporary storage.
--
require "send_response"
require "jwt"
-- Buffer the response (helps with error handling).
local success, error_msg = server.setBuffer()
if not success then
send_error(500, "server.setBuffer() failed: " .. error_msg)
return
end
-- Check that this request is really from Knora and that the user has permission
-- to delete the file.
local token = get_knora_token()
if token == nil then
return
end
local knora_data = token["knora-data"]
if knora_data == nil then
send_error(403, "No knora-data in token")
return
end
if knora_data["permission"] ~= "DeleteTempFile" then
send_error(403, "Token does not grant permission to store file")
return
end
local token_filename = knora_data["filename"]
if token_filename == nil then
send_error(401, "Token does not specify a filename")
return
end
-- Parse the URL to get the filename to be deleted.
local last_slash_pos = server.uri:match(".*/()")
if last_slash_pos == nil then
send_error(400, "Invalid path: " .. server.uri)
return
end
local filename = server.uri:sub(last_slash_pos)
if filename:len() == 0 or filename == "." or filename == ".." then
send_error(400, "Invalid filename: " .. filename)
return
end
-- Check that the filename matches the one in the token.
if filename ~= token_filename then
send_error(401, "Incorrect filename in token")
return
end
-- Check that the file exists in the temp directory.
local hashed_filename
success, hashed_filename = helper.filename_hash(filename)
if not success then
send_error(500, "helper.filename_hash() failed: " .. hashed_filename)
return
end
local temp_file_path = config.imgroot .. '/tmp/' .. hashed_filename
local exists
success, exists = server.fs.exists(temp_file_path)
if not success then
send_error(500, "server.fs.exists() failed: " .. exists)
return
end
if not exists then
send_error(404, filename .. " not found")
return
end
local filetype
success, filetype = server.fs.ftype(temp_file_path)
if not success then
send_error(500, "server.fs.ftype() failed: " .. filetype)
return
end
if filetype ~= "FILE" then
send_error(400, filename .. " is not a file")
return
end
-- Delete the file.
local errmsg
success, errmsg = server.fs.unlink(temp_file_path)
if not success then
send_error(500, "server.fs.unlink() failed: " .. errmsg)
return
end
server.log("delete_temp_file.lua: deleted " .. temp_file_path, server.loglevel.LOG_DEBUG)
local result = {
status = 0
}
send_success(result)
| agpl-3.0 |
arychen/GlobalCall | feeds/luci/build/luadoc/luadoc/taglet/standard/tags.lua | 46 | 5543 | -------------------------------------------------------------------------------
-- Handlers for several tags
-- @release $Id: tags.lua,v 1.8 2007/09/05 12:39:09 tomas Exp $
-------------------------------------------------------------------------------
local luadoc = require "luadoc"
local util = require "luadoc.util"
local string = require "string"
local table = require "table"
local assert, type, tostring, tonumber = assert, type, tostring, tonumber
module "luadoc.taglet.standard.tags"
-------------------------------------------------------------------------------
local function author (tag, block, text)
block[tag] = block[tag] or {}
if not text then
luadoc.logger:warn("author `name' not defined [["..text.."]]: skipping")
return
end
table.insert (block[tag], text)
end
-------------------------------------------------------------------------------
-- Set the class of a comment block. Classes can be "module", "function",
-- "table". The first two classes are automatic, extracted from the source code
local function class (tag, block, text)
block[tag] = text
end
-------------------------------------------------------------------------------
local function cstyle (tag, block, text)
block[tag] = text
end
-------------------------------------------------------------------------------
local function sort (tag, block, text)
block[tag] = tonumber(text) or 0
end
-------------------------------------------------------------------------------
local function copyright (tag, block, text)
block[tag] = text
end
-------------------------------------------------------------------------------
local function description (tag, block, text)
block[tag] = text
end
-------------------------------------------------------------------------------
local function field (tag, block, text)
if block["class"] ~= "table" then
luadoc.logger:warn("documenting `field' for block that is not a `table'")
end
block[tag] = block[tag] or {}
local _, _, name, desc = string.find(text, "^([_%w%.]+)%s+(.*)")
assert(name, "field name not defined")
table.insert(block[tag], name)
block[tag][name] = desc
end
-------------------------------------------------------------------------------
-- Set the name of the comment block. If the block already has a name, issue
-- an error and do not change the previous value
local function name (tag, block, text)
if block[tag] and block[tag] ~= text then
luadoc.logger:error(string.format("block name conflict: `%s' -> `%s'", block[tag], text))
end
block[tag] = text
end
-------------------------------------------------------------------------------
-- Processes a parameter documentation.
-- @param tag String with the name of the tag (it must be "param" always).
-- @param block Table with previous information about the block.
-- @param text String with the current line beeing processed.
local function param (tag, block, text)
block[tag] = block[tag] or {}
-- TODO: make this pattern more flexible, accepting empty descriptions
local _, _, name, desc = string.find(text, "^([_%w%.]+)%s+(.*)")
if not name then
luadoc.logger:warn("parameter `name' not defined [["..text.."]]: skipping")
return
end
local i = table.foreachi(block[tag], function (i, v)
if v == name then
return i
end
end)
if i == nil then
luadoc.logger:warn(string.format("documenting undefined parameter `%s'", name))
table.insert(block[tag], name)
end
block[tag][name] = desc
end
-------------------------------------------------------------------------------
local function release (tag, block, text)
block[tag] = text
end
-------------------------------------------------------------------------------
local function ret (tag, block, text)
tag = "ret"
if type(block[tag]) == "string" then
block[tag] = { block[tag], text }
elseif type(block[tag]) == "table" then
table.insert(block[tag], text)
else
block[tag] = text
end
end
-------------------------------------------------------------------------------
-- @see ret
local function see (tag, block, text)
-- see is always an array
block[tag] = block[tag] or {}
-- remove trailing "."
text = string.gsub(text, "(.*)%.$", "%1")
local s = util.split("%s*,%s*", text)
table.foreachi(s, function (_, v)
table.insert(block[tag], v)
end)
end
-------------------------------------------------------------------------------
-- @see ret
local function usage (tag, block, text)
if type(block[tag]) == "string" then
block[tag] = { block[tag], text }
elseif type(block[tag]) == "table" then
table.insert(block[tag], text)
else
block[tag] = text
end
end
-------------------------------------------------------------------------------
local handlers = {}
handlers["author"] = author
handlers["class"] = class
handlers["cstyle"] = cstyle
handlers["copyright"] = copyright
handlers["description"] = description
handlers["field"] = field
handlers["name"] = name
handlers["param"] = param
handlers["release"] = release
handlers["return"] = ret
handlers["see"] = see
handlers["sort"] = sort
handlers["usage"] = usage
-------------------------------------------------------------------------------
function handle (tag, block, text)
if not handlers[tag] then
luadoc.logger:error(string.format("undefined handler for tag `%s'", tag))
return
end
if text then
text = text:gsub("`([^\n]-)`", "<code>%1</code>")
text = text:gsub("`(.-)`", "<pre>%1</pre>")
end
-- assert(handlers[tag], string.format("undefined handler for tag `%s'", tag))
return handlers[tag](tag, block, text)
end
| gpl-2.0 |
b03605079/darkstar | scripts/zones/Pashhow_Marshlands_[S]/Zone.lua | 8 | 1309 | -----------------------------------
--
-- Zone: Pashhow_Marshlands_[S] (90)
--
-----------------------------------
package.loaded["scripts/zones/Pashhow_Marshlands_[S]/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Pashhow_Marshlands_[S]/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(547.841,23.192,696.323,134);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
stars2014/quick-ng | cocos/scripting/lua-bindings/auto/api/RepeatForever.lua | 7 | 1954 |
--------------------------------
-- @module RepeatForever
-- @extend ActionInterval
-- @parent_module cc
--------------------------------
-- Sets the inner action.<br>
-- param action The inner action.
-- @function [parent=#RepeatForever] setInnerAction
-- @param self
-- @param #cc.ActionInterval action
-- @return RepeatForever#RepeatForever self (return value: cc.RepeatForever)
--------------------------------
-- Gets the inner action.<br>
-- return The inner action.
-- @function [parent=#RepeatForever] getInnerAction
-- @param self
-- @return ActionInterval#ActionInterval ret (return value: cc.ActionInterval)
--------------------------------
-- Creates the action.<br>
-- param action The action need to repeat forever.<br>
-- return An autoreleased RepeatForever object.
-- @function [parent=#RepeatForever] create
-- @param self
-- @param #cc.ActionInterval action
-- @return RepeatForever#RepeatForever ret (return value: cc.RepeatForever)
--------------------------------
--
-- @function [parent=#RepeatForever] startWithTarget
-- @param self
-- @param #cc.Node target
-- @return RepeatForever#RepeatForever self (return value: cc.RepeatForever)
--------------------------------
--
-- @function [parent=#RepeatForever] clone
-- @param self
-- @return RepeatForever#RepeatForever ret (return value: cc.RepeatForever)
--------------------------------
--
-- @function [parent=#RepeatForever] isDone
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#RepeatForever] reverse
-- @param self
-- @return RepeatForever#RepeatForever ret (return value: cc.RepeatForever)
--------------------------------
-- param dt In seconds.
-- @function [parent=#RepeatForever] step
-- @param self
-- @param #float dt
-- @return RepeatForever#RepeatForever self (return value: cc.RepeatForever)
return nil
| mit |
DI3HARD139/dcb-everamzah- | mods/worldedit/worldedit/primitives.lua | 1 | 8249 | --- Functions for creating primitive shapes.
-- @module worldedit.primitives
local mh = worldedit.manip_helpers
--- Adds a sphere of `node_name` centered at `pos`.
-- @param pos Position to center sphere at.
-- @param radius Sphere radius.
-- @param node_name Name of node to make shere of.
-- @param hollow Whether the sphere should be hollow.
-- @return The number of nodes added.
function worldedit.sphere(pos, radius, node_name, hollow)
local manip, area = mh.init_radius(pos, radius)
local data = mh.get_empty_data(area)
-- Fill selected area with node
local node_id = minetest.get_content_id(node_name)
local min_radius, max_radius = radius * (radius - 1), radius * (radius + 1)
local offset_x, offset_y, offset_z = pos.x - area.MinEdge.x, pos.y - area.MinEdge.y, pos.z - area.MinEdge.z
local stride_z, stride_y = area.zstride, area.ystride
local count = 0
for z = -radius, radius do
-- Offset contributed by z plus 1 to make it 1-indexed
local new_z = (z + offset_z) * stride_z + 1
for y = -radius, radius do
local new_y = new_z + (y + offset_y) * stride_y
for x = -radius, radius do
local squared = x * x + y * y + z * z
if squared <= max_radius and (not hollow or squared >= min_radius) then
-- Position is on surface of sphere
local i = new_y + (x + offset_x)
data[i] = node_id
count = count + 1
end
end
end
end
mh.finish(manip, data)
return count
end
--- Adds a dome.
-- @param pos Position to center dome at.
-- @param radius Dome radius. Negative for concave domes.
-- @param node_name Name of node to make dome of.
-- @param hollow Whether the dome should be hollow.
-- @return The number of nodes added.
-- TODO: Add axis option.
function worldedit.dome(pos, radius, node_name, hollow)
local min_y, max_y = 0, radius
if radius < 0 then
radius = -radius
min_y, max_y = -radius, 0
end
local manip, area = mh.init_axis_radius(pos, "y", radius)
local data = mh.get_empty_data(area)
-- Add dome
local node_id = minetest.get_content_id(node_name)
local min_radius, max_radius = radius * (radius - 1), radius * (radius + 1)
local offset_x, offset_y, offset_z = pos.x - area.MinEdge.x, pos.y - area.MinEdge.y, pos.z - area.MinEdge.z
local stride_z, stride_y = area.zstride, area.ystride
local count = 0
for z = -radius, radius do
local new_z = (z + offset_z) * stride_z + 1 --offset contributed by z plus 1 to make it 1-indexed
for y = min_y, max_y do
local new_y = new_z + (y + offset_y) * stride_y
for x = -radius, radius do
local squared = x * x + y * y + z * z
if squared <= max_radius and (not hollow or squared >= min_radius) then
-- Position is in dome
local i = new_y + (x + offset_x)
data[i] = node_id
count = count + 1
end
end
end
end
mh.finish(manip, data)
return count
end
--- Adds a cylinder.
-- @param pos Position to center base of cylinder at.
-- @param axis Axis ("x", "y", or "z")
-- @param length Cylinder length.
-- @param radius Cylinder radius.
-- @param node_name Name of node to make cylinder of.
-- @param hollow Whether the cylinder should be hollow.
-- @return The number of nodes added.
function worldedit.cylinder(pos, axis, length, radius, node_name, hollow)
local other1, other2 = worldedit.get_axis_others(axis)
-- Handle negative lengths
local current_pos = {x=pos.x, y=pos.y, z=pos.z}
if length < 0 then
length = -length
current_pos[axis] = current_pos[axis] - length
end
-- Set up voxel manipulator
local manip, area = mh.init_axis_radius_length(current_pos, axis, radius, length)
local data = mh.get_empty_data(area)
-- Add cylinder
local node_id = minetest.get_content_id(node_name)
local min_radius, max_radius = radius * (radius - 1), radius * (radius + 1)
local stride = {x=1, y=area.ystride, z=area.zstride}
local offset = {
x = current_pos.x - area.MinEdge.x,
y = current_pos.y - area.MinEdge.y,
z = current_pos.z - area.MinEdge.z,
}
local min_slice, max_slice = offset[axis], offset[axis] + length - 1
local count = 0
for index2 = -radius, radius do
-- Offset contributed by other axis 1 plus 1 to make it 1-indexed
local new_index2 = (index2 + offset[other1]) * stride[other1] + 1
for index3 = -radius, radius do
local new_index3 = new_index2 + (index3 + offset[other2]) * stride[other2]
local squared = index2 * index2 + index3 * index3
if squared <= max_radius and (not hollow or squared >= min_radius) then
-- Position is in cylinder
-- Add column along axis
for index1 = min_slice, max_slice do
local vi = new_index3 + index1 * stride[axis]
data[vi] = node_id
end
count = count + length
end
end
end
mh.finish(manip, data)
return count
end
--- Adds a pyramid.
-- @param pos Position to center base of pyramid at.
-- @param axis Axis ("x", "y", or "z")
-- @param height Pyramid height.
-- @param node_name Name of node to make pyramid of.
-- @return The number of nodes added.
function worldedit.pyramid(pos, axis, height, node_name)
local other1, other2 = worldedit.get_axis_others(axis)
-- Set up voxel manipulator
local manip, area = mh.init_axis_radius(pos, axis,
height >= 0 and height or -height)
local data = mh.get_empty_data(area)
-- Handle inverted pyramids
local start_axis, end_axis, step
if height > 0 then
height = height - 1
step = 1
else
height = height + 1
step = -1
end
-- Add pyramid
local node_id = minetest.get_content_id(node_name)
local stride = {x=1, y=area.ystride, z=area.zstride}
local offset = {
x = pos.x - area.MinEdge.x,
y = pos.y - area.MinEdge.y,
z = pos.z - area.MinEdge.z,
}
local size = height * step
local count = 0
-- For each level of the pyramid
for index1 = 0, height, step do
-- Offset contributed by axis plus 1 to make it 1-indexed
local new_index1 = (index1 + offset[axis]) * stride[axis] + 1
for index2 = -size, size do
local new_index2 = new_index1 + (index2 + offset[other1]) * stride[other1]
for index3 = -size, size do
local i = new_index2 + (index3 + offset[other2]) * stride[other2]
data[i] = node_id
end
end
count = count + (size * 2 + 1) ^ 2
size = size - 1
end
mh.finish(manip, data)
return count
end
--- Adds a spiral.
-- @param pos Position to center spiral at.
-- @param length Spral length.
-- @param height Spiral height.
-- @param spacer Space between walls.
-- @param node_name Name of node to make spiral of.
-- @return Number of nodes added.
-- TODO: Add axis option.
function worldedit.spiral(pos, length, height, spacer, node_name)
local extent = math.ceil(length / 2)
local manip, area = mh.init_axis_radius_length(pos, "y", extent, height)
local data = mh.get_empty_data(area)
-- Set up variables
local node_id = minetest.get_content_id(node_name)
local stride = {x=1, y=area.ystride, z=area.zstride}
local offset_x, offset_y, offset_z = pos.x - area.MinEdge.x, pos.y - area.MinEdge.y, pos.z - area.MinEdge.z
local i = offset_z * stride.z + offset_y * stride.y + offset_x + 1
-- Add first column
local count = height
local column = i
for y = 1, height do
data[column] = node_id
column = column + stride.y
end
-- Add spiral segments
local stride_axis, stride_other = stride.x, stride.z
local sign = -1
local segment_length = 0
spacer = spacer + 1
-- Go through each segment except the last
for segment = 1, math.floor(length / spacer) * 2 do
-- Change sign and length every other turn starting with the first
if segment % 2 == 1 then
sign = -sign
segment_length = segment_length + spacer
end
-- Fill segment
for index = 1, segment_length do
-- Move along the direction of the segment
i = i + stride_axis * sign
local column = i
-- Add column
for y = 1, height do
data[column] = node_id
column = column + stride.y
end
end
count = count + segment_length * height
stride_axis, stride_other = stride_other, stride_axis -- Swap axes
end
-- Add shorter final segment
sign = -sign
for index = 1, segment_length do
i = i + stride_axis * sign
local column = i
-- Add column
for y = 1, height do
data[column] = node_id
column = column + stride.y
end
end
count = count + segment_length * height
mh.finish(manip, data)
return count
end
| gpl-3.0 |
immibis/wiremod | lua/entities/gmod_wire_expression2/core/compat.lua | 9 | 3207 | -- Functions in this file are retained purely for backwards-compatibility. They should not be used in new code and might be removed at any time.
e2function string number:teamName()
local str = team.GetName(this)
if not str then return "" end
return str
end
e2function number number:teamScore()
return team.GetScore(this)
end
e2function number number:teamPlayers()
return team.NumPlayers(this)
end
e2function number number:teamDeaths()
return team.TotalDeaths(this)
end
e2function number number:teamFrags()
return team.TotalFrags(this)
end
e2function void setColor(r, g, b)
self.entity:SetColor(Color(math.Clamp(r, 0, 255), math.Clamp(g, 0, 255), math.Clamp(b, 0, 255), 255))
end
__e2setcost(30) -- temporary
e2function void applyForce(vector force)
local phys = self.entity:GetPhysicsObject()
phys:ApplyForceCenter(Vector(force[1],force[2],force[3]))
end
e2function void applyOffsetForce(vector force, vector position)
local phys = self.entity:GetPhysicsObject()
phys:ApplyForceOffset(Vector(force[1],force[2],force[3]), Vector(position[1],position[2],position[3]))
end
e2function void applyAngForce(angle angForce)
if angForce[1] == 0 and angForce[2] == 0 and angForce[3] == 0 then return end
local ent = self.entity
local phys = ent:GetPhysicsObject()
-- assign vectors
local up = ent:GetUp()
local left = ent:GetRight() * -1
local forward = ent:GetForward()
-- apply pitch force
if angForce[1] ~= 0 then
local pitch = up * (angForce[1] * 0.5)
phys:ApplyForceOffset( forward, pitch )
phys:ApplyForceOffset( forward * -1, pitch * -1 )
end
-- apply yaw force
if angForce[2] ~= 0 then
local yaw = forward * (angForce[2] * 0.5)
phys:ApplyForceOffset( left, yaw )
phys:ApplyForceOffset( left * -1, yaw * -1 )
end
-- apply roll force
if angForce[3] ~= 0 then
local roll = left * (angForce[3] * 0.5)
phys:ApplyForceOffset( up, roll )
phys:ApplyForceOffset( up * -1, roll * -1 )
end
end
e2function void applyTorque(vector torque)
if torque[1] == 0 and torque[2] == 0 and torque[3] == 0 then return end
local phys = self.entity:GetPhysicsObject()
local tq = Vector(torque[1], torque[2], torque[3])
local torqueamount = tq:Length()
-- Convert torque from local to world axis
tq = phys:LocalToWorld( tq ) - phys:GetPos()
-- Find two vectors perpendicular to the torque axis
local off
if math.abs(tq.x) > torqueamount * 0.1 or math.abs(tq.z) > torqueamount * 0.1 then
off = Vector(-tq.z, 0, tq.x)
else
off = Vector(-tq.y, tq.x, 0)
end
off = off:GetNormal() * torqueamount * 0.5
local dir = ( tq:Cross(off) ):GetNormal()
phys:ApplyForceOffset( dir, off )
phys:ApplyForceOffset( dir * -1, off * -1 )
end
__e2setcost(10)
e2function number entity:height()
--[[ Old code (UGLYYYY)
if(!IsValid(this)) then return 0 end
if(this:IsPlayer() or this:IsNPC()) then
local pos = this:GetPos()
local up = this:GetUp()
return this:NearestPoint(Vector(pos.x+up.x*100,pos.y+up.y*100,pos.z+up.z*100)).z-this:NearestPoint(Vector(pos.x-up.x*100,pos.y-up.y*100,pos.z-up.z*100)).z
else return 0 end
]]
-- New code (Same as E:boxSize():z())
if(!IsValid(this)) then return 0 end
return (this:OBBMaxs() - this:OBBMins()).z
end
| apache-2.0 |
miralireza2/gpf23 | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru 🔞",
"!danboorud - random daily popular image 🔞",
"!danbooruw - random weekly popular image 🔞",
"!danboorum - random monthly popular image 🔞"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
kiarash14/bumpspm | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru 🔞",
"!danboorud - random daily popular image 🔞",
"!danbooruw - random weekly popular image 🔞",
"!danboorum - random monthly popular image 🔞"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
thesrinivas/rakshak | rakshak-probe/userspace/sysdig/chisels/httplog.lua | 10 | 1698 | --[[
Copyright (C) 2015 Luca Marturana
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
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/>.
--]]
-- Chisel description
description = "Show a log of all HTTP requests";
short_description = "HTTP requests log";
category = "Application";
args = {}
require "http"
-- Initialization callback
function on_init()
http_init()
-- The -pc or -pcontainer options was supplied on the cmd line
print_container = sysdig.is_print_container_data()
return true
end
function on_transaction(transaction)
if print_container then
container = " " .. transaction["container"] .. " "
else
container = " "
end
print(string.format("%s%s%s method=%s url=%s response_code=%d latency=%dms size=%dB",
evt.field(datetime_field),
container,
transaction["dir"],
transaction["request"]["method"],
transaction["request"]["url"],
transaction["response"]["code"],
(transaction["response"]["ts"] - transaction["request"]["ts"])/1000000,
transaction["response"]["length"]
))
end
function on_event()
run_http_parser(evt, on_transaction)
end
| gpl-2.0 |
b03605079/darkstar | scripts/zones/Windurst_Walls/npcs/Tsuaora-Tsuora.lua | 38 | 1043 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Tsuaora-Tsuora
-- Type: Standard NPC
-- @zone: 239
-- @pos 71.489 -3.418 -67.809
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x002a);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Aquanim/Zero-K | units/energyfusion.lua | 2 | 1786 | return { energyfusion = {
unitname = [[energyfusion]],
name = [[Fusion Reactor]],
description = [[Medium Powerplant (+35)]],
activateWhenBuilt = true,
buildCostMetal = 1000,
builder = false,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 6,
BuildingGroundDecalSizeY = 6,
BuildingGroundDecalType = [[energyfusion_ground.dds]],
buildPic = [[energyfusion.png]],
category = [[SINK UNARMED]],
corpse = [[DEAD]],
customParams = {
pylonrange = 150,
removewait = 1,
removestop = 1,
},
energyMake = 35,
energyUse = 0,
explodeAs = [[ATOMIC_BLAST]],
footprintX = 5,
footprintZ = 4,
iconType = [[energyfusion]],
maxDamage = 2200,
maxSlope = 18,
objectName = [[energyfusion.s3o]],
script = "energyfusion.lua",
selfDestructAs = [[ATOMIC_BLAST]],
sightDistance = 273,
useBuildingGroundDecal = true,
yardMap = [[ooooo ooooo ooooo ooooo]],
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 5,
footprintZ = 4,
object = [[energyfusion_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 5,
footprintZ = 4,
object = [[debris4x4b.s3o]],
},
},
} }
| gpl-2.0 |
b03605079/darkstar | scripts/zones/RuAun_Gardens/mobs/Seiryu.lua | 2 | 1215 | -----------------------------------
-- Area: Ru'Aun Gardens
-- NPC: Seiryu
-----------------------------------
require("scripts/zones/RuAun_Gardens/TextIDs");
require("scripts/globals/status");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function OnMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
killer:showText(mob,SKY_GOD_OFFSET + 10);
GetNPCByID(17310052):hideNPC(900);
end;
-----------------------------------
-- onMonsterMagicPrepare
-----------------------------------
function onMonsterMagicPrepare(mob,target)
-- For some reason, this returns false even when Hundred Fists is active, so... yeah.
-- Core does this:
-- m_PMob->StatusEffectContainer->AddStatusEffect(new CStatusEffect(EFFECT_HUNDRED_FISTS,0,1,0,45));
if (mob:hasStatusEffect(EFFECT_HUNDRED_FISTS,0) == false) then
local rnd = math.random();
if (rnd < 0.5) then
return 186; -- aeroga 3
elseif (rnd < 0.7) then
return 157; -- aero 4
elseif (rnd < 0.9) then
return 208; -- tornado
else
return 237; -- choke
end
end
end; | gpl-3.0 |
stevedonovan/Penlight | tests/test-url.lua | 1 | 1689 | local url = require 'pl.url'
local asserteq = require 'pl.test' . asserteq
asserteq(url.quote(''), '')
asserteq(url.quote('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
asserteq(url.quote('abcdefghijklmnopqrstuvwxyz'), 'abcdefghijklmnopqrstuvwxyz')
asserteq(url.quote('0123456789'), '0123456789')
asserteq(url.quote(' -_./'), '%20-_./')
asserteq(url.quote('`~!@#$%^&*()'), '%60%7E%21%40%23%24%25%5E%26%2A%28%29')
asserteq(url.quote('%2'), '%252')
asserteq(url.quote('2R%1%%'), '2R%251%25%25')
asserteq(url.quote('', true), '')
asserteq(url.quote('ABCDEFGHIJKLMNOPQRSTUVWXYZ', true), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
asserteq(url.quote('abcdefghijklmnopqrstuvwxyz', true), 'abcdefghijklmnopqrstuvwxyz')
asserteq(url.quote('0123456789'), '0123456789', true)
asserteq(url.quote(' -_./', true), '+-_.%2F')
asserteq(url.quote('`~!@#$%^&*()', true), '%60%7E%21%40%23%24%25%5E%26%2A%28%29')
asserteq(url.quote('%2', true), '%252')
asserteq(url.quote('2R%1%%', true), '2R%251%25%25')
asserteq(url.unquote(''), '')
asserteq(url.unquote('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
asserteq(url.unquote('abcdefghijklmnopqrstuvwxyz'), 'abcdefghijklmnopqrstuvwxyz')
asserteq(url.unquote('0123456789'), '0123456789')
asserteq(url.unquote(' -_./'), ' -_./')
asserteq(url.unquote('+-_.%2F'), ' -_./')
asserteq(url.unquote('%20-_./'), ' -_./')
asserteq(url.unquote('%60%7E%21%40%23%24%25%5E%26%2A%28%29'), '`~!@#$%^&*()')
asserteq(url.unquote('%252'), '%2')
asserteq(url.unquote('2%52%1%%'), '2R%1%%')
asserteq(url.unquote('2R%251%25%25'), '2R%1%%')
asserteq(url.quote(true), true)
asserteq(url.quote(42), 42)
asserteq(url.unquote(true), true)
asserteq(url.unquote(42), 42)
| mit |
b03605079/darkstar | scripts/zones/Port_Bastok/npcs/Tete.lua | 19 | 1293 | -----------------------------------
-- Area: Port Bastok
-- NPC: Tete
-- Continues Quest: The Wisdom Of Elders
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
------------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getQuestStatus(BASTOK,THE_WISDOM_OF_ELDERS) == QUEST_ACCEPTED) then
player:startEvent(0x00af);
else
player:startEvent(0x0023);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x00af) then
player:setVar("TheWisdomVar",2);
end
end; | gpl-3.0 |
b03605079/darkstar | scripts/globals/weaponskills/dark_harvest.lua | 29 | 1229 | -----------------------------------
-- Dark Harvest
-- Scythe weapon skill
-- Skill Level: 30
-- Delivers a dark elemental attack. Damage varies with TP.
-- Aligned with the Aqua Gorget.
-- Aligned with the Aqua Belt.
-- Element: Dark
-- Modifiers: STR:20% ; INT:20%
-- 100%TP 200%TP 300%TP
-- 1.00 2.00 2.50
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5;
params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.ele = ELE_DARK;
params.skill = SKILL_SYH;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4; params.int_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
xpol/luarocks | src/luarocks/unpack.lua | 6 | 6135 |
--- Module implementing the LuaRocks "unpack" command.
-- Unpack the contents of a rock.
local unpack = {}
package.loaded["luarocks.unpack"] = unpack
local fetch = require("luarocks.fetch")
local fs = require("luarocks.fs")
local util = require("luarocks.util")
local build = require("luarocks.build")
local dir = require("luarocks.dir")
local cfg = require("luarocks.cfg")
util.add_run_function(unpack)
unpack.help_summary = "Unpack the contents of a rock."
unpack.help_arguments = "[--force] {<rock>|<name> [<version>]}"
unpack.help = [[
Unpacks the contents of a rock in a newly created directory.
Argument may be a rock file, or the name of a rock in a rocks server.
In the latter case, the app version may be given as a second argument.
--force Unpack files even if the output directory already exists.
]]
--- Load a rockspec file to the given directory, fetches the source
-- files specified in the rockspec, and unpack them inside the directory.
-- @param rockspec_file string: The URL for a rockspec file.
-- @param dir_name string: The directory where to store and unpack files.
-- @return table or (nil, string): the loaded rockspec table or
-- nil and an error message.
local function unpack_rockspec(rockspec_file, dir_name)
assert(type(rockspec_file) == "string")
assert(type(dir_name) == "string")
local rockspec, err = fetch.load_rockspec(rockspec_file)
if not rockspec then
return nil, "Failed loading rockspec "..rockspec_file..": "..err
end
local ok, err = fs.change_dir(dir_name)
if not ok then return nil, err end
local ok, sources_dir = fetch.fetch_sources(rockspec, true, ".")
if not ok then
return nil, sources_dir
end
ok, err = fs.change_dir(sources_dir)
if not ok then return nil, err end
ok, err = build.apply_patches(rockspec)
fs.pop_dir()
if not ok then return nil, err end
return rockspec
end
--- Load a .rock file to the given directory and unpack it inside it.
-- @param rock_file string: The URL for a .rock file.
-- @param dir_name string: The directory where to unpack.
-- @param kind string: the kind of rock file, as in the second-level
-- extension in the rock filename (eg. "src", "all", "linux-x86")
-- @return table or (nil, string): the loaded rockspec table or
-- nil and an error message.
local function unpack_rock(rock_file, dir_name, kind)
assert(type(rock_file) == "string")
assert(type(dir_name) == "string")
local ok, err, errcode = fetch.fetch_and_unpack_rock(rock_file, dir_name)
if not ok then
return nil, "Failed unzipping rock "..rock_file, errcode
end
ok, err = fs.change_dir(dir_name)
if not ok then return nil, err end
local rockspec_file = dir_name..".rockspec"
local rockspec, err = fetch.load_rockspec(rockspec_file)
if not rockspec then
return nil, "Failed loading rockspec "..rockspec_file..": "..err
end
if kind == "src" then
if rockspec.source.file then
local ok, err = fs.unpack_archive(rockspec.source.file)
if not ok then
return nil, err
end
ok, err = fs.change_dir(rockspec.source.dir)
if not ok then return nil, err end
ok, err = build.apply_patches(rockspec)
fs.pop_dir()
if not ok then return nil, err end
end
end
return rockspec
end
--- Create a directory and perform the necessary actions so that
-- the sources for the rock and its rockspec are unpacked inside it,
-- laid out properly so that the 'make' command is able to build the module.
-- @param file string: A rockspec or .rock URL.
-- @return boolean or (nil, string): true if successful or nil followed
-- by an error message.
local function run_unpacker(file, force)
assert(type(file) == "string")
local base_name = dir.base_name(file)
local dir_name, kind, extension = base_name:match("(.*)%.([^.]+)%.(rock)$")
if not extension then
dir_name, extension = base_name:match("(.*)%.(rockspec)$")
kind = "rockspec"
end
if not extension then
return nil, file.." does not seem to be a valid filename."
end
local exists = fs.exists(dir_name)
if exists and not force then
return nil, "Directory "..dir_name.." already exists."
end
if not exists then
local ok, err = fs.make_dir(dir_name)
if not ok then return nil, err end
end
local rollback = util.schedule_function(fs.delete, fs.absolute_name(dir_name))
local rockspec, err
if extension == "rock" then
rockspec, err = unpack_rock(file, dir_name, kind)
elseif extension == "rockspec" then
rockspec, err = unpack_rockspec(file, dir_name)
end
if not rockspec then
return nil, err
end
if kind == "src" or kind == "rockspec" then
if rockspec.source.dir ~= "." then
local ok = fs.copy(rockspec.local_filename, rockspec.source.dir, cfg.perm_read)
if not ok then
return nil, "Failed copying unpacked rockspec into unpacked source directory."
end
end
util.printout()
util.printout("Done. You may now enter directory ")
util.printout(dir.path(dir_name, rockspec.source.dir))
util.printout("and type 'luarocks make' to build.")
end
util.remove_scheduled_function(rollback)
return true
end
--- Driver function for the "unpack" command.
-- @param name string: may be a rock filename, for unpacking a
-- rock file or the name of a rock to be fetched and unpacked.
-- @param version string or nil: if the name of a package is given, a
-- version may also be passed.
-- @return boolean or (nil, string): true if successful or nil followed
-- by an error message.
function unpack.command(flags, name, version)
assert(type(version) == "string" or not version)
if type(name) ~= "string" then
return nil, "Argument missing. "..util.see_help("unpack")
end
if name:match(".*%.rock") or name:match(".*%.rockspec") then
return run_unpacker(name, flags["force"])
else
local search = require("luarocks.search")
return search.act_on_src_or_rockspec(run_unpacker, name:lower(), version)
end
end
return unpack
| mit |
cosmy1/Urho3D | bin/Data/LuaScripts/16_Chat.lua | 18 | 7649 | -- Chat example
-- This sample demonstrates:
-- - Starting up a network server or connecting to it
-- - Implementing simple chat functionality with network messages
require "LuaScripts/Utilities/Sample"
-- Identifier for the chat network messages
local MSG_CHAT = 32
-- UDP port we will use
local CHAT_SERVER_PORT = 2345
local chatHistory = {}
local chatHistoryText = nil
local buttonContainer = nil
local textEdit = nil
local sendButton = nil
local connectButton = nil
local disconnectButton = nil
local startServerButton = nil
function Start()
-- Execute the common startup for samples
SampleStart()
-- Enable OS cursor
input.mouseVisible = true
-- Create the user interface
CreateUI()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_FREE)
-- Subscribe to UI and network events
SubscribeToEvents()
end
function CreateUI()
SetLogoVisible(false) -- We need the full rendering window
local uiStyle = cache:GetResource("XMLFile", "UI/DefaultStyle.xml")
-- Set style to the UI root so that elements will inherit it
ui.root.defaultStyle = uiStyle
local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf")
chatHistoryText = ui.root:CreateChild("Text")
chatHistoryText:SetFont(font, 12)
buttonContainer = ui.root:CreateChild("UIElement")
buttonContainer:SetFixedSize(graphics.width, 20)
buttonContainer:SetPosition(0, graphics.height - 20)
buttonContainer.layoutMode = LM_HORIZONTAL
textEdit = buttonContainer:CreateChild("LineEdit")
textEdit:SetStyleAuto()
sendButton = CreateButton("Send", 70)
connectButton = CreateButton("Connect", 90)
disconnectButton = CreateButton("Disconnect", 100)
startServerButton = CreateButton("Start Server", 110)
UpdateButtons()
local size = (graphics.height - 20) / chatHistoryText.rowHeight
for i = 1, size do
table.insert(chatHistory, "")
end
-- No viewports or scene is defined. However, the default zone's fog color controls the fill color
renderer.defaultZone.fogColor = Color(0.0, 0.0, 0.1)
end
function SubscribeToEvents()
-- Subscribe to UI element events
SubscribeToEvent(textEdit, "TextFinished", "HandleSend")
SubscribeToEvent(sendButton, "Released", "HandleSend")
SubscribeToEvent(connectButton, "Released", "HandleConnect")
SubscribeToEvent(disconnectButton, "Released", "HandleDisconnect")
SubscribeToEvent(startServerButton, "Released", "HandleStartServer")
-- Subscribe to log messages so that we can pipe them to the chat window
SubscribeToEvent("LogMessage", "HandleLogMessage")
-- Subscribe to network events
SubscribeToEvent("NetworkMessage", "HandleNetworkMessage")
SubscribeToEvent("ServerConnected", "HandleConnectionStatus")
SubscribeToEvent("ServerDisconnected", "HandleConnectionStatus")
SubscribeToEvent("ConnectFailed", "HandleConnectionStatus")
end
function CreateButton(text, width)
local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf")
local button = buttonContainer:CreateChild("Button")
button:SetStyleAuto()
button:SetFixedWidth(width)
local buttonText = button:CreateChild("Text")
buttonText:SetFont(font, 12)
buttonText:SetAlignment(HA_CENTER, VA_CENTER)
buttonText.text = text
return button
end
function ShowChatText(row)
table.remove(chatHistory, 1)
table.insert(chatHistory, row)
-- Concatenate all the rows in history
local allRows = ""
for i, r in ipairs(chatHistory) do
allRows = allRows .. r .. "\n"
end
chatHistoryText.text = allRows
end
function UpdateButtons()
local serverConnection = network.serverConnection
local serverRunning = network.serverRunning
-- Show and hide buttons so that eg. Connect and Disconnect are never shown at the same time
sendButton.visible = serverConnection ~= nil
connectButton.visible = (serverConnection == nil) and (not serverRunning)
disconnectButton.visible = (serverConnection ~= nil) or serverRunning
startServerButton.visible = (serverConnection == nil) and (not serverRunning)
end
function HandleLogMessage(eventType, eventData)
ShowChatText(eventData["Message"]:GetString())
end
function HandleSend(eventType, eventData)
local text = textEdit.text
if text == "" then
return -- Do not send an empty message
end
local serverConnection = network.serverConnection
if serverConnection ~= nil then
-- A VectorBuffer object is convenient for constructing a message to send
local msg = VectorBuffer()
msg:WriteString(text)
-- Send the chat message as in-order and reliable
serverConnection:SendMessage(MSG_CHAT, true, true, msg)
-- Empty the text edit after sending
textEdit.text = ""
end
end
function HandleConnect(eventType, eventData)
local address = textEdit.text
if address == "" then
address = "localhost" -- Use localhost to connect if nothing else specified
end
-- Empty the text edit after reading the address to connect to
textEdit.text = ""
-- Connect to server, do not specify a client scene as we are not using scene replication, just messages.
-- At connect time we could also send identity parameters (such as username) in a VariantMap, but in this
-- case we skip it for simplicity
network:Connect(address, CHAT_SERVER_PORT, nil)
UpdateButtons()
end
function HandleDisconnect(eventType, eventData)
local serverConnection = network.serverConnection
-- If we were connected to server, disconnect
if serverConnection ~= nil then
serverConnection:Disconnect()
-- Or if we were running a server, stop it
else
if network.serverRunning then
network:StopServer()
end
end
UpdateButtons()
end
function HandleStartServer(eventType, eventData)
network:StartServer(CHAT_SERVER_PORT)
UpdateButtons()
end
function HandleNetworkMessage(eventType, eventData)
local msgID = eventData["MessageID"]:GetInt()
if msgID == MSG_CHAT then
local msg = eventData["Data"]:GetBuffer()
local text = msg:ReadString()
-- If we are the server, prepend the sender's IP address and port and echo to everyone
-- If we are a client, just display the message
if network.serverRunning then
local sender = eventData["Connection"]:GetPtr("Connection")
text = sender:ToString() .. " " .. text
local sendMsg = VectorBuffer()
sendMsg:WriteString(text)
-- Broadcast as in-order and reliable
network:BroadcastMessage(MSG_CHAT, true, true, sendMsg)
end
ShowChatText(text)
end
end
function HandleConnectionStatus(eventType, eventData)
UpdateButtons()
end
-- Create XML patch instructions for screen joystick layout specific to this sample app
function GetScreenJoystickPatchString()
return
"<patch>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button2']]\">" ..
" <attribute name=\"Is Visible\" value=\"false\" />" ..
" </add>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" ..
" <attribute name=\"Is Visible\" value=\"false\" />" ..
" </add>" ..
"</patch>"
end
| mit |
Aquanim/Zero-K | effects/solange.lua | 7 | 1941 | -- solange
-- solange_pillar
return {
["solange"] = {
nw = {
air = true,
class = [[CExpGenSpawner]],
count = 150,
ground = true,
water = true,
underwater = true,
properties = {
delay = [[0 i4]],
explosiongenerator = [[custom:SOLANGE_PILLAR]],
pos = [[20 r40, i20, -20 r40]],
},
},
},
["solange_pillar"] = {
rocks = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.97,
alwaysvisible = true,
colormap = [[0.0 0.00 0.0 0.01
0.9 0.90 0.0 0.50
0.9 0.90 0.0 0.50
0.8 0.80 0.1 0.50
0.7 0.70 0.2 0.50
0.5 0.35 0.0 0.50
0.5 0.35 0.0 0.50
0.5 0.35 0.0 0.50
0.5 0.35 0.0 0.50
0.0 0.00 0.0 0.01]],
directional = true,
emitrot = 90,
emitrotspread = 10,
emitvector = [[0, 1, 0]],
gravity = [[0.001 r-0.002, 0.01 r-0.02, 0.001 r-0.002]],
numparticles = 1,
particlelife = 150,
particlelifespread = 150,
particlesize = 90,
particlesizespread = 90,
particlespeed = 3,
particlespeedspread = 3,
pos = [[0, 0, 0]],
sizegrowth = 0.05,
sizemod = 1.0,
texture = [[fireball]],
},
},
},
}
| gpl-2.0 |
stars2014/quick-ng | cocos/scripting/lua-bindings/auto/api/ActionScaleFrame.lua | 11 | 1744 |
--------------------------------
-- @module ActionScaleFrame
-- @extend ActionFrame
-- @parent_module ccs
--------------------------------
-- Changes the scale action scaleY.<br>
-- param rotation the scale action scaleY.
-- @function [parent=#ActionScaleFrame] setScaleY
-- @param self
-- @param #float scaleY
-- @return ActionScaleFrame#ActionScaleFrame self (return value: ccs.ActionScaleFrame)
--------------------------------
-- Changes the scale action scaleX.<br>
-- param the scale action scaleX.
-- @function [parent=#ActionScaleFrame] setScaleX
-- @param self
-- @param #float scaleX
-- @return ActionScaleFrame#ActionScaleFrame self (return value: ccs.ActionScaleFrame)
--------------------------------
-- Gets the scale action scaleY.<br>
-- return the the scale action scaleY.
-- @function [parent=#ActionScaleFrame] getScaleY
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Gets the scale action scaleX.<br>
-- return the scale action scaleX.
-- @function [parent=#ActionScaleFrame] getScaleX
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Gets the ActionInterval of ActionFrame.<br>
-- parame duration the duration time of ActionFrame<br>
-- return ActionInterval
-- @function [parent=#ActionScaleFrame] getAction
-- @param self
-- @param #float duration
-- @return ActionInterval#ActionInterval ret (return value: cc.ActionInterval)
--------------------------------
-- Default constructor
-- @function [parent=#ActionScaleFrame] ActionScaleFrame
-- @param self
-- @return ActionScaleFrame#ActionScaleFrame self (return value: ccs.ActionScaleFrame)
return nil
| mit |
cs-willian-silva/vlc | share/lua/modules/sandbox.lua | 28 | 4403 | --[==========================================================================[
sandbox.lua: Lua sandboxing facilities
--[==========================================================================[
Copyright (C) 2007 the VideoLAN team
$Id$
Authors: Antoine Cellerier <dionoea at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]==========================================================================]
module("sandbox",package.seeall)
-- See Programming in Lua (second edition) for sandbox examples
-- See http://lua-users.org/wiki/SandBoxes for a list of SAFE/UNSAFE variables
local sandbox_blacklist = {
collectgarbage = true,
dofile = true,
_G = true,
getfenv = true,
getmetatable = true,
load = true, -- Can be protected I guess
loadfile = true, -- Can be protected I guess
rawequal = true,
rawget = true,
rawset = true,
setfenv = true,
setmetatable = true,
module = true,
require = true,
package = true,
debug = true,
}
if _VERSION == "Lua 5.1" then
sandbox_blacklist["loadstring"] = true
end
function readonly_table_proxy(name,src,blacklist)
if type(src)=="nil" then return end
if type(src)~="table" then error("2nd argument must be a table (or nil)") end
local name = name
local t = src
local blist = {}
if blacklist then
for _, v in pairs(blacklist) do
blist[v] = true
end
end
local metatable_readonly = {
__index = function(self,key)
if blist[key] then
error("Sandbox: Access to `"..name.."."..key.."' is forbidden.")
end
return t[key]
end,
__newindex = function(self,key,value)
error("It is forbidden to modify elements of this table.")
end,
}
return setmetatable({},metatable_readonly)
end
-- Of course, all of this is useless if the sandbox calling code has
-- another reference to one of these tables in his global environement.
local sandbox_proxy = {
coroutine = readonly_table_proxy("coroutine",coroutine),
string = readonly_table_proxy("string",string,{"dump"}),
table = readonly_table_proxy("table",table),
math = readonly_table_proxy("math",math),
io = readonly_table_proxy("io",io),
os = readonly_table_proxy("os",os,{"exit","getenv","remove",
"rename","setlocale"}),
sandbox = readonly_table_proxy("sandbox",sandbox),
}
function sandbox(func,override)
local _G = getfenv(2)
local override = override or {}
local sandbox_metatable =
{
__index = function(self,key)
if override[key] then
return override[key]
end
if sandbox_blacklist[key] then
error( "Sandbox: Access to `"..key.."' is forbidden." )
end
--print(key,"not found in env. Looking in sandbox_proxy and _G")
local value = sandbox_proxy[key] or _G[key]
rawset(self,key,value) -- Keep a local copy
return value
end,
__newindex = function(self,key,value)
if override and override[key] then
error( "Sandbox: Variable `"..key.."' is read only." )
end
return rawset(self,key,value)
end,
}
local sandbox_env = setmetatable({},sandbox_metatable)
return function(...)
setfenv(func,sandbox_env)
local ret = {func(...)} -- Not perfect (if func returns nil before
-- another return value) ... but it's better
-- than nothing
setfenv(func,_G)
return unpack(ret)
end
end
| gpl-2.0 |
stars2014/quick-ng | cocos/scripting/lua-bindings/auto/api/GridBase.lua | 9 | 4540 |
--------------------------------
-- @module GridBase
-- @extend Ref
-- @parent_module cc
--------------------------------
-- Set the size of the grid.
-- @function [parent=#GridBase] setGridSize
-- @param self
-- @param #size_table gridSize
-- @return GridBase#GridBase self (return value: cc.GridBase)
--------------------------------
--
-- @function [parent=#GridBase] afterBlit
-- @param self
-- @return GridBase#GridBase self (return value: cc.GridBase)
--------------------------------
--
-- @function [parent=#GridBase] afterDraw
-- @param self
-- @param #cc.Node target
-- @return GridBase#GridBase self (return value: cc.GridBase)
--------------------------------
-- @{<br>
-- Init and reset the status when render effects by using the grid.
-- @function [parent=#GridBase] beforeDraw
-- @param self
-- @return GridBase#GridBase self (return value: cc.GridBase)
--------------------------------
-- Interface, Calculate the vertices used for the blit.
-- @function [parent=#GridBase] calculateVertexPoints
-- @param self
-- @return GridBase#GridBase self (return value: cc.GridBase)
--------------------------------
-- is texture flipped.
-- @function [parent=#GridBase] isTextureFlipped
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Size of the grid.
-- @function [parent=#GridBase] getGridSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- Pixels between the grids.
-- @function [parent=#GridBase] getStep
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
-- Change projection to 2D for grabbing.
-- @function [parent=#GridBase] set2DProjection
-- @param self
-- @return GridBase#GridBase self (return value: cc.GridBase)
--------------------------------
-- Get the pixels between the grids.
-- @function [parent=#GridBase] setStep
-- @param self
-- @param #vec2_table step
-- @return GridBase#GridBase self (return value: cc.GridBase)
--------------------------------
-- Set the texture flipped or not.
-- @function [parent=#GridBase] setTextureFlipped
-- @param self
-- @param #bool flipped
-- @return GridBase#GridBase self (return value: cc.GridBase)
--------------------------------
-- Interface used to blit the texture with grid to screen.
-- @function [parent=#GridBase] blit
-- @param self
-- @return GridBase#GridBase self (return value: cc.GridBase)
--------------------------------
--
-- @function [parent=#GridBase] setActive
-- @param self
-- @param #bool active
-- @return GridBase#GridBase self (return value: cc.GridBase)
--------------------------------
-- Get number of times that the grid will be reused.
-- @function [parent=#GridBase] getReuseGrid
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- @overload self, size_table
-- @overload self, size_table, cc.Texture2D, bool
-- @function [parent=#GridBase] initWithSize
-- @param self
-- @param #size_table gridSize
-- @param #cc.Texture2D texture
-- @param #bool flipped
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @{<br>
-- Interface for custom action when before or after draw.<br>
-- js NA
-- @function [parent=#GridBase] beforeBlit
-- @param self
-- @return GridBase#GridBase self (return value: cc.GridBase)
--------------------------------
-- Set number of times that the grid will be reused.
-- @function [parent=#GridBase] setReuseGrid
-- @param self
-- @param #int reuseGrid
-- @return GridBase#GridBase self (return value: cc.GridBase)
--------------------------------
-- @} @{<br>
-- Getter and setter of the active state of the grid.
-- @function [parent=#GridBase] isActive
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Interface, Reuse the grid vertices.
-- @function [parent=#GridBase] reuse
-- @param self
-- @return GridBase#GridBase self (return value: cc.GridBase)
--------------------------------
-- @overload self, size_table
-- @overload self, size_table, cc.Texture2D, bool
-- @function [parent=#GridBase] create
-- @param self
-- @param #size_table gridSize
-- @param #cc.Texture2D texture
-- @param #bool flipped
-- @return GridBase#GridBase ret (return value: cc.GridBase)
return nil
| mit |
b03605079/darkstar | scripts/globals/spells/valor_minuet_v.lua | 13 | 1535 | -----------------------------------------
-- Spell: Valor Minuet V
-- Grants Attack bonus to all allies.
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 32;
if (sLvl+iLvl > 500) then
power = power + math.floor((sLvl+iLvl-500) / 6);
end
if(power >= 62) then
power = 62;
end
local iBoost = caster:getMod(MOD_MINUET_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
if (iBoost > 0) then
power = power + 1 + (iBoost-1)*4;
end
power = power + caster:getMerit(MERIT_MINUET_EFFECT);
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_MINUET,power,0,duration,caster:getID(), 0, 5)) then
spell:setMsg(75);
end
return EFFECT_MINUET;
end; | gpl-3.0 |
b03605079/darkstar | scripts/globals/abilities/pets/sand_breath.lua | 6 | 1257 | ---------------------------------------------------
-- Sand Breath
---------------------------------------------------
require("/scripts/globals/settings");
require("/scripts/globals/status");
require("/scripts/globals/monstertpmoves");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill, master)
---------- Deep Breathing ----------
-- 0 for none
-- 1 for first merit
-- 0.25 for each merit after the first
-- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*)
local deep = 1;
if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then
deep = deep + 1 + (master:getMerit(MERIT_DEEP_BREATHING)-1)*0.25;
pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST);
end
local gear = master:getMod(MOD_WYVERN_BREATH)/256; -- Master gear that enhances breath
local dmgmod = MobBreathMove(pet, target, 0.185, pet:getMainLvl()*15, ELE_EARTH); -- Works out to (hp/6) + 15, as desired
dmgmod = (dmgmod * (1+gear))*deep;
local dmg = MobFinalAdjustments(dmgmod,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_EARTH,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end | gpl-3.0 |
Aquanim/Zero-K | LuaRules/Gadgets/api_custom_unit_shaders.lua | 2 | 29319 | -- $Id$
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- author: jK
--
-- Copyright (C) 2008,2009,2010.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "CustomUnitShaders",
desc = "allows to override the engine unit and feature shaders",
author = "jK, gajop, ivand",
date = "2008,2009,2010,2016, 2019",
license = "GNU GPL, v2 or later",
layer = 1,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Synced
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if (gadgetHandler:IsSyncedCode()) then
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Unsynced
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if (not gl.CreateShader) then
Spring.Log("CUS", LOG.WARNING, "Shaders not supported, disabling")
return false
end
-----------------------------------------------------------------
-- Constants
-----------------------------------------------------------------
local MATERIALS_DIR = "ModelMaterials/"
local LUASHADER_DIR = "LuaRules/Gadgets/Include/"
local DEFAULT_VERSION = "#version 150 compatibility"
local USE_OBJECT_DAMAGE = false
local BAR_COMPAT = Spring.Utilities.IsCurrentVersionNewerThan(105, 500)
-----------------------------------------------------------------
-- Includes and classes loading
-----------------------------------------------------------------
VFS.Include("LuaRules/Utilities/UnitRendering.lua", nil, VFS.MOD .. VFS.BASE)
local LuaShader = VFS.Include(LUASHADER_DIR .. "LuaShader.lua")
-----------------------------------------------------------------
-- Global Variables
-----------------------------------------------------------------
--these two have no callin to detect change of state
local advShading
local shadows
local sunChanged = false --always on on load/reload
local optionsChanged = false --just in case
local registeredOptions = {}
local idToDefID = {}
--- Main data structures:
-- rendering.objectList[objectID] = matSrc -- All units
-- rendering.drawList[objectID] = matSrc -- Lua Draw
-- rendering.materialInfos[objectDefID] = {matName, name = param, name1 = param1}
-- rendering.bufMaterials[objectDefID] = rendering.spGetMaterial("opaque") / luaMat
-- rendering.bufShadowMaterials[objectDefID] = rendering.spGetMaterial("shadow") / luaMat
-- rendering.materialDefs[matName] = matSrc
-- rendering.loadedTextures[texname] = true
---
local unitRendering = {
objectList = {},
drawList = {},
materialInfos = {},
bufMaterials = {},
bufShadowMaterials = {},
materialDefs = {},
loadedTextures = {},
shadowsPreDLs = {},
shadowsPostDL = nil,
spGetAllObjects = Spring.GetAllUnits,
spGetObjectPieceList = Spring.GetUnitPieceList,
spGetMaterial = Spring.UnitRendering.GetMaterial,
spSetMaterial = Spring.UnitRendering.SetMaterial,
spActivateMaterial = Spring.UnitRendering.ActivateMaterial,
spDeactivateMaterial = Spring.UnitRendering.DeactivateMaterial,
spSetObjectLuaDraw = Spring.UnitRendering.SetUnitLuaDraw,
spSetLODCount = Spring.UnitRendering.SetLODCount,
spSetPieceList = Spring.UnitRendering.SetPieceList,
DrawObject = "DrawUnit", --avoid, will kill CPU-side of performance!
ObjectCreated = "UnitCreated",
ObjectDestroyed = "UnitDestroyed",
ObjectDamaged = "UnitDamaged",
}
local featureRendering = {
objectList = {},
drawList = {},
materialInfos = {},
bufMaterials = {},
bufShadowMaterials = {},
materialDefs = {},
loadedTextures = {},
shadowsPreDLs = {},
shadowsPostDL = nil,
spGetAllObjects = Spring.GetAllFeatures,
spGetObjectPieceList = Spring.GetFeaturePieceList,
spGetMaterial = Spring.FeatureRendering.GetMaterial,
spSetMaterial = Spring.FeatureRendering.SetMaterial,
spActivateMaterial = Spring.FeatureRendering.ActivateMaterial,
spDeactivateMaterial = Spring.FeatureRendering.DeactivateMaterial,
spSetObjectLuaDraw = Spring.FeatureRendering.SetFeatureLuaDraw,
spSetLODCount = Spring.FeatureRendering.SetLODCount,
spSetPieceList = Spring.FeatureRendering.SetPieceList,
DrawObject = "DrawFeature", --avoid, will kill CPU-side of performance!
ObjectCreated = "FeatureCreated",
ObjectDestroyed = "FeatureDestroyed",
ObjectDamaged = "FeatureDamaged",
}
local allRendering = {
unitRendering,
featureRendering,
}
-----------------------------------------------------------------
-- Local Functions
-----------------------------------------------------------------
local function _CompileShader(shader, definitions, plugIns, addName)
definitions = definitions or {}
local hasVersion = false
if definitions[1] then -- #version must be 1st statement
hasVersion = string.find(definitions[1], "#version") == 1
end
if not hasVersion then
table.insert(definitions, 1, DEFAULT_VERSION)
end
shader.definitions = table.concat(definitions, "\n") .. "\n"
--// insert small pieces of code named `plugins`
--// this way we can use a basic shader and add some simple vertex animations etc.
do
local function InsertPlugin(str)
return (plugIns and plugIns[str]) or ""
end
if shader.vertex then
shader.vertex = shader.vertex:gsub("%%%%([%a_]+)%%%%", InsertPlugin)
end
if shader.fragment then
shader.fragment = shader.fragment:gsub("%%%%([%a_]+)%%%%", InsertPlugin)
end
if shader.geometry then
shader.geometry = shader.geometry:gsub("%%%%([%a_]+)%%%%", InsertPlugin)
end
end
local luaShader = LuaShader(shader, "Custom Unit Shaders. " .. addName)
local compilationResult = luaShader:Initialize()
return (compilationResult and luaShader) or nil
end
local engineUniforms = {
"viewMatrix",
"viewMatrixInv",
"projectionMatrix",
"projectionMatrixInv",
"viewProjectionMatrix",
"viewProjectionMatrixInv",
"shadowMatrix",
"shadowParams",
"cameraPos",
"cameraDir",
"sunDir",
"rndVec",
"simFrame",
"drawFrame", --visFrame
}
local function _FillUniformLocs(luaShader)
local uniformLocTbl = {}
for _, uniformName in ipairs(engineUniforms) do
local uniformNameLoc = string.lower(uniformName).."loc"
uniformLocTbl[uniformNameLoc] = luaShader:GetUniformLocation(uniformName)
end
return uniformLocTbl
end
local function _CompileMaterialShaders(rendering)
for matName, matSrc in pairs(rendering.materialDefs) do
matSrc.hasStandardShader = false
matSrc.hasDeferredShader = false
matSrc.hasShadowShader = false
if matSrc.shaderSource then
local luaShader = _CompileShader(
matSrc.shaderSource,
matSrc.shaderDefinitions,
matSrc.shaderPlugins,
string.format("MatName: \"%s\"(%s)", matName, "Standard")
)
if luaShader then
if matSrc.standardShader then
if matSrc.standardShaderObj then
matSrc.standardShaderObj:Finalize()
else
gl.DeleteShader(matSrc.standardShader)
end
end
matSrc.standardShaderObj = luaShader
matSrc.hasStandardShader = true
matSrc.standardShader = luaShader:GetHandle()
luaShader:SetUnknownUniformIgnore(true)
luaShader:ActivateWith( function()
matSrc.standardUniforms = _FillUniformLocs(luaShader)
end)
luaShader:SetActiveStateIgnore(true)
end
end
if matSrc.deferredSource then
local luaShader = _CompileShader(
matSrc.deferredSource,
matSrc.deferredDefinitions,
matSrc.shaderPlugins,
string.format("MatName: \"%s\"(%s)", matName, "Deferred")
)
if luaShader then
if matSrc.deferredShader then
if matSrc.deferredShaderObj then
matSrc.deferredShaderObj:Finalize()
else
gl.DeleteShader(matSrc.deferredShader)
end
end
matSrc.deferredShaderObj = luaShader
matSrc.hasDeferredShader = true
matSrc.deferredShader = luaShader:GetHandle()
luaShader:SetUnknownUniformIgnore(true)
luaShader:ActivateWith( function()
matSrc.deferredUniforms = _FillUniformLocs(luaShader)
end)
luaShader:SetActiveStateIgnore(true)
end
end
if matSrc.shadowSource then
-- work around AMD bug
matSrc.shadowSource.fragment = nil
local luaShader = _CompileShader(
matSrc.shadowSource,
matSrc.shadowDefinitions,
matSrc.shaderPlugins,
string.format("MatName: \"%s\"(%s)", matName, "Shadow")
)
if luaShader then
if matSrc.shadowShader then
if matSrc.shadowShaderObj then
matSrc.shadowShaderObj:Finalize()
else
gl.DeleteShader(matSrc.shadowShader)
end
end
matSrc.shadowShaderObj = luaShader
matSrc.hasShadowShader = true
matSrc.shadowShader = luaShader:GetHandle()
luaShader:SetUnknownUniformIgnore(true)
luaShader:ActivateWith( function()
matSrc.shadowUniforms = _FillUniformLocs(luaShader)
end)
luaShader:SetActiveStateIgnore(true)
end
end
if matSrc.Initialize then
matSrc.Initialize(matName, matSrc)
end
end
end
local function _ProcessOptions(optName, _, optValues, playerID)
if (playerID ~= Spring.GetMyPlayerID()) then
return
end
if type(optValues) ~= "table" then
optValues = {optValues}
end
--Spring.Utilities.TableEcho({optName, optValues, playerID}, "_ProcessOptions")
for _, rendering in ipairs(allRendering) do
for matName, matTable in pairs(rendering.materialDefs) do
if matTable.ProcessOptions then
local optCh = matTable.ProcessOptions(matTable, optName, optValues)
optionsChanged = optionsChanged or optCh
end
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local validTexturePrefixes = {
["%"] = true,
["#"] = true,
["!"] = true,
["$"] = true
}
local function GetObjectMaterial(rendering, objectDefID)
local mat = rendering.bufMaterials[objectDefID]
if mat then
return mat
end
local matInfo = rendering.materialInfos[objectDefID]
local mat = rendering.materialDefs[matInfo[1]]
if type(objectDefID) == "number" then
-- Non-number objectDefIDs are default material overrides. They will have
-- their textures defined in the unit materials files.
matInfo.UNITDEFID = objectDefID
matInfo.FEATUREDEFID = -objectDefID
end
--// find unitdef tex keyword and replace it
--// (a shader can be just for multiple unitdefs, so we support this keywords)
local texUnits = {}
for texid, tex in pairs(mat.texUnits or {}) do
local tex_ = tex
for varname, value in pairs(matInfo) do
tex_ = tex_:gsub("%%"..tostring(varname), value)
end
texUnits[texid] = {tex = tex_, enable = false}
end
--// materials don't load those textures themselves
local texdl = gl.CreateList(function() --this stupidity is required, because GetObjectMaterial() is called outside of GL enabled callins
for _, tex in pairs(texUnits) do
if not rendering.loadedTextures[tex.tex] then
local prefix = tex.tex:sub(1, 1)
if not validTexturePrefixes[prefix] then
gl.Texture(tex.tex)
rendering.loadedTextures[tex.tex] = true
end
end
end
end)
gl.DeleteList(texdl)
local luaMat = rendering.spGetMaterial("opaque", {
standardshader = mat.standardShader,
deferredshader = mat.deferredShader,
standarduniforms = mat.standardUniforms,
deferreduniforms = mat.deferredUniforms,
usecamera = mat.usecamera,
culling = mat.culling,
texunits = texUnits,
prelist = mat.predl,
postlist = mat.postdl,
})
rendering.bufMaterials[objectDefID] = luaMat
return luaMat
end
local function GetObjectShadowMaterial(rendering, objectDefID)
local mat = rendering.bufShadowMaterials[objectDefID]
if mat then
return mat
end
local matInfo = rendering.materialInfos[objectDefID]
local mat = rendering.materialDefs[matInfo[1]]
if type(objectDefID) == "number" then
-- Non-number objectDefIDs are default material overrides. They will have
-- their textures defined in the unit materials files.
matInfo.UNITDEFID = objectDefID
matInfo.FEATUREDEFID = -objectDefID
end
--// find unitdef tex keyword and replace it
--// (a shader can be just for multiple unitdefs, so we support this keywords)
local texUnits = {}
for texid, tex in pairs(mat.texUnits or {}) do
local tex_ = tex
for varname, value in pairs(matInfo) do
tex_ = tex_:gsub("%%"..tostring(varname), value)
end
texUnits[texid] = {tex = tex_, enable = false}
end
--// materials don't load those textures themselves
local texdl = gl.CreateList(function() --this stupidity is required, because GetObjectMaterial() is called outside of GL enabled callins
for _, tex in pairs(texUnits) do
if not rendering.loadedTextures[tex.tex] then
local prefix = tex.tex:sub(1, 1)
if validTexturePrefixes[prefix] then
gl.Texture(tex.tex)
rendering.loadedTextures[tex.tex] = true
end
end
end
end)
gl.DeleteList(texdl)
-- needs TEX2 to perform alpha tests
-- cannot do it in shader because of some weird bug with AMD
-- not accepting any frag shaders for shadow pass
local shadowAlphaTexNum = mat.shadowAlphaTexNum or 1
local shadowAlphaTex = texUnits[shadowAlphaTexNum].tex
if not rendering.shadowsPostDL then
rendering.shadowsPostDL = gl.CreateList(function()
gl.Texture(0, false)
end)
end
if shadowAlphaTex then
if not rendering.shadowsPreDLs[shadowAlphaTex] then
rendering.shadowsPreDLs[shadowAlphaTex] = gl.CreateList(function()
gl.Texture(0, shadowAlphaTex)
end)
end
end
local shadowsPreDL = rendering.shadowsPreDLs[shadowAlphaTex]
--No deferred statements are required
local luaShadowMat = rendering.spGetMaterial("shadow", {
standardshader = mat.shadowShader,
standarduniforms = mat.shadowUniforms,
usecamera = true,
culling = mat.shadowCulling,
--texunits = {[shadowAlphaTexNum] = {tex = texUnits[shadowAlphaTexNum].tex, enable = false}},
prelist = shadowsPreDL,
postlist = rendering.shadowsPostDL,
})
rendering.bufShadowMaterials[objectDefID] = luaShadowMat
return luaShadowMat
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function _ResetUnit(unitID)
local unitDefID = Spring.GetUnitDefID(unitID)
gadget:RenderUnitDestroyed(unitID, unitDefID)
if not select(3, Spring.GetUnitIsStunned(unitID)) then --// inbuild?
gadget:UnitFinished(unitID, unitDefID)
end
end
local function _ResetFeature(featureID)
gadget:FeatureDestroyed(featureID)
gadget:FeatureCreated(featureID)
end
local function _LoadMaterialConfigFiles(path)
local unitMaterialDefs = {}
local featureMaterialDefs = {}
GG.CUS.unitMaterialDefs = unitMaterialDefs
GG.CUS.featureMaterialDefs = featureMaterialDefs
local files = VFS.DirList(path)
table.sort(files)
for i = 1, #files do
local matNames, matObjects = VFS.Include(files[i])
for k, v in pairs(matNames) do
-- Spring.Echo(files[i],'is a feature?',v.feature)
local rendering
if v.feature then
rendering = featureRendering
else
rendering = unitRendering
end
if not rendering.materialDefs[k] then
rendering.materialDefs[k] = v
end
end
for k, v in pairs(matObjects) do
--// we check if the material is defined as a unit or as feature material (one namespace for both!!)
local materialDefs
if featureRendering.materialDefs[v[1]] then
materialDefs = featureMaterialDefs
else
materialDefs = unitMaterialDefs
end
if not materialDefs[k] then
materialDefs[k] = v
end
end
end
return unitMaterialDefs, featureMaterialDefs
end
local function _ProcessMaterials(rendering, materialDefsSrc)
local engineShaderTypes = {"3do", "s3o", "ass"}
for _, matSrc in pairs(rendering.materialDefs) do
if matSrc.shader ~= nil and engineShaderTypes[matSrc.shader] == nil then
matSrc.shaderSource = matSrc.shader
matSrc.shader = nil
end
if matSrc.deferred ~= nil and engineShaderTypes[matSrc.deferred] == nil then
matSrc.deferredSource = matSrc.deferred
matSrc.deferred = nil
end
if matSrc.shadow ~= nil and engineShaderTypes[matSrc.shadow] == nil then
matSrc.shadowSource = matSrc.shadow
matSrc.shadow = nil
end
end
_CompileMaterialShaders(rendering)
for objectDefID, materialInfo in pairs(materialDefsSrc) do --note not rendering.materialDefs
if (type(materialInfo) ~= "table") then
materialInfo = {materialInfo}
end
rendering.materialInfos[objectDefID] = materialInfo
end
end
local function BindMaterials()
local units = Spring.GetAllUnits()
for _, unitID in pairs(units) do
_ResetUnit(unitID)
end
local features = Spring.GetAllFeatures()
for _, featureID in pairs(features) do
_ResetFeature(featureID)
end
end
local function ToggleAdvShading()
unitRendering.drawList = {}
featureRendering.drawList = {}
BindMaterials()
end
local function GetShaderOverride(objectID, objectDefID)
if Spring.ValidUnitID(objectID) then
return Spring.GetUnitRulesParam(objectID, "comm_texture")
end
return false
end
local function ObjectFinished(rendering, objectID, objectDefID)
if not advShading then
return
end
objectDefID = GetShaderOverride(objectID, objectDefID) or objectDefID
local objectMat = rendering.materialInfos[objectDefID]
if objectMat then
local mat = rendering.materialDefs[objectMat[1]]
if mat.standardShader then
rendering.objectList[objectID] = mat
rendering.spActivateMaterial(objectID, 3)
rendering.spSetMaterial(objectID, 3, "opaque", GetObjectMaterial(rendering, objectDefID))
if mat.shadowShader then
rendering.spSetMaterial(objectID, 3, "shadow", GetObjectShadowMaterial(rendering, objectDefID))
end
for pieceID in ipairs(rendering.spGetObjectPieceList(objectID) or {}) do
rendering.spSetPieceList(objectID, 3, pieceID)
end
local _DrawObject = mat[rendering.DrawObject]
local _ObjectCreated = mat[rendering.ObjectCreated]
if _DrawObject then
rendering.spSetObjectLuaDraw(objectID, true)
rendering.drawList[objectID] = mat
end
if _ObjectCreated then
_ObjectCreated(objectID, objectDefID, mat)
end
end
end
end
local function ObjectDestroyed(rendering, objectID, objectDefID)
local mat = rendering.objectList[objectID]
if mat then
local _ObjectDestroyed = mat[rendering.ObjectDestroyed]
if _ObjectDestroyed then
_ObjectDestroyed(objectID, objectDefID, mat)
end
rendering.objectList[objectID] = nil
rendering.drawList[objectID] = nil
end
rendering.spDeactivateMaterial(objectID, 3)
end
local function ObjectDamaged(rendering, objectID, objectDefID)
local mat = rendering.objectList[objectID]
if mat then
local _ObjectDamaged = mat[rendering.ObjectDamaged]
if _ObjectDamaged then
_ObjectDamaged(objectID, objectDefID, mat)
end
end
end
local function DrawObject(rendering, objectID, objectDefID, drawMode)
local mat = rendering.drawList[objectID]
if not mat then
return
end
local _DrawObject = mat[rendering.DrawObject]
if _DrawObject then
return _DrawObject(objectID, objectDefID, mat, drawMode)
end
end
local function _CleanupEverything(rendering)
for objectID, mat in pairs(rendering.drawList) do
local _DrawObject = mat[rendering.DrawObject]
if _DrawObject then
rendering.spSetObjectLuaDraw(objectID, false)
end
end
for _, mat in pairs(rendering.materialDefs) do
if mat.Finalize then
mat.Finalize(matName, matSrc)
end
for _, shaderObject in pairs({mat.standardShaderObj, mat.deferredShaderObj, mat.shadowShaderObj}) do
if shaderObject then
shaderObject:Finalize()
end
end
end
for tex, _ in pairs(rendering.loadedTextures) do
local prefix = tex:sub(1, 1)
if not validTexturePrefixes[prefix] then
gl.DeleteTexture(tex)
end
end
for _, dl in pairs(rendering.shadowsPreDLs) do
gl.DeleteList(dl)
end
if rendering.shadowsPostDL then
gl.DeleteList(rendering.shadowsPostDL)
end
-- crashes system
--[[
for objectID, mat in pairs(rendering.objectList) do
ObjectDestroyed(rendering, objectID, nil)
end
]]--
for _, oid in ipairs(rendering.spGetAllObjects()) do
rendering.spSetLODCount(oid, 0)
end
for optName, _ in pairs(registeredOptions) do
gadgetHandler:RemoveChatAction(optName)
end
rendering.objectList = {}
rendering.drawList = {}
rendering.materialInfos = {}
rendering.bufMaterials = {}
rendering.bufShadowMaterials = {}
rendering.materialDefs = {}
rendering.loadedTextures = {}
rendering.shadowsPreDLs = {}
rendering.shadowsPostDL = nil
gadgetHandler:RemoveChatAction("updatesun")
--gadgetHandler:RemoveChatAction("cusreload")
--gadgetHandler:RemoveChatAction("reloadcus")
gadgetHandler:RemoveChatAction("disablecus")
gadgetHandler:RemoveChatAction("cusdisable")
collectgarbage()
end
-----------------------------------------------------------------
-- Gadget Functions
-----------------------------------------------------------------
function gadget:SunChanged()
sunChanged = true
end
function gadget:DrawGenesis()
for _, rendering in ipairs(allRendering) do
for _, mat in pairs(rendering.materialDefs) do
local SunChangedFunc = (sunChanged and mat.SunChanged) or nil
local DrawGenesisFunc = mat.DrawGenesis
local ApplyOptionsFunc = mat.ApplyOptions
if SunChangedFunc or DrawGenesisFunc or (optionsChanged and ApplyOptionsFunc) then
for key, shaderObject in pairs({mat.standardShaderObj, mat.deferredShaderObj, mat.shadowShaderObj}) do
if shaderObject then
shaderObject:ActivateWith( function ()
if optionsChanged and ApplyOptionsFunc then
ApplyOptionsFunc(shaderObject, mat, key)
end
if SunChangedFunc then
SunChangedFunc(shaderObject, mat)
end
if DrawGenesisFunc then
DrawGenesisFunc(shaderObject, mat)
end
end)
end
end
end
end
end
if sunChanged then
sunChanged = false
end
if optionsChanged then
optionsChanged = false
end
end
-----------------------------------------------------------------
-----------------------------------------------------------------
-- To be called once per CHECK_FREQ
local function _GameFrameSlow(gf)
for _, rendering in ipairs(allRendering) do
for _, mat in pairs(rendering.materialDefs) do
local gameFrameSlowFunc = mat.GameFrameSlow
if gameFrameSlowFunc then
gameFrameSlowFunc(gf, mat)
end
end
end
end
-- To be called every synced gameframe
local function _GameFrame(gf)
for _, rendering in ipairs(allRendering) do
for _, mat in pairs(rendering.materialDefs) do
local gameFrameFunc = mat.GameFrame
if gameFrameFunc then
gameFrameFunc(gf, mat)
end
end
end
end
local CHECK_FREQ = 30
function gadget:GameFrame(gf)
local gfMod = gf % CHECK_FREQ
if gfMod == 0 then
local advShadingNow = Spring.HaveAdvShading()
local shadowsNow = Spring.HaveShadows()
if (advShading ~= advShadingNow) then
advShading = advShadingNow
ToggleAdvShading()
end
if (shadows ~= shadowsNow) then
shadows = shadowsNow
_ProcessOptions("shadowmapping", nil, shadows, Spring.GetMyPlayerID())
end
elseif gfMod == 15 then --TODO change 15 to something less busy
_GameFrameSlow(gf)
end
_GameFrame(gf)
end
local slowTime = Spring.GetTimer()
local fastTime = Spring.GetTimer()
function gadget:Update()
local _, _, paused = Spring.GetGameSpeed()
local frame = Spring.GetGameFrame()
paused = paused or frame < 1
if not paused then
slowTime = false
fastTime = false
return
end
local currentTime = Spring.GetTimer()
slowTime = slowTime or currentTime
fastTime = fastTime or currentTime
if Spring.DiffTimers(currentTime, fastTime) > 0.0333 then
_GameFrame(frame)
fastTime = currentTime
end
if Spring.DiffTimers(currentTime, slowTime) > 1 then
_GameFrameSlow(frame)
slowTime = currentTime
end
end
-----------------------------------------------------------------
-----------------------------------------------------------------
function gadget:UnitFinished(unitID, unitDefID)
idToDefID[unitID] = unitDefID
ObjectFinished(unitRendering, unitID, unitDefID)
end
function gadget:FeatureCreated(featureID)
idToDefID[-featureID] = Spring.GetFeatureDefID(featureID)
ObjectFinished(featureRendering, featureID, idToDefID[-featureID])
end
function gadget:UnitDamaged(unitID, unitDefID)
ObjectDamaged(unitRendering, unitID, unitDefID)
end
function gadget:FeatureDamaged(featureID, featureDefID)
ObjectDamaged(featureRendering, featureID, featureDefID)
end
function gadget:RenderUnitDestroyed(unitID, unitDefID)
ObjectDestroyed(unitRendering, unitID, unitDefID)
idToDefID[unitID] = nil --not really required
end
function gadget:FeatureDestroyed(featureID)
ObjectDestroyed(featureRendering, featureID, idToDefID[-featureID])
idToDefID[-featureID] = nil --not really required
end
-----------------------------------------------------------------
-----------------------------------------------------------------
---------------------------
-- Draw{Unit, Feature}(id, drawMode)
-- With enum drawMode {
-- notDrawing = 0,
-- normalDraw = 1,
-- shadowDraw = 2,
-- reflectionDraw = 3,
-- refractionDraw = 4,
-- gameDeferredDraw = 5,
-- };
-----------------
function gadget:DrawUnit(unitID, drawMode)
return DrawObject(unitRendering, unitID, idToDefID[unitID], drawMode)
end
function gadget:DrawFeature(featureID, drawMode)
return DrawObject(featureRendering, featureID, idToDefID[-featureID], drawMode)
end
-----------------------------------------------------------------
-----------------------------------------------------------------
gadget.UnitReverseBuilt = gadget.RenderUnitDestroyed
gadget.UnitCloaked = gadget.RenderUnitDestroyed
gadget.UnitDecloaked = gadget.UnitFinished
-- NOTE: No feature equivalent (features can't change team)
function gadget:UnitGiven(unitID, ...)
_ResetUnit(unitID)
end
-----------------------------------------------------------------
-----------------------------------------------------------------
local function ReloadCUS(optName, _, _, playerID)
if (playerID ~= Spring.GetMyPlayerID()) then
return
end
Spring.Echo("Reloading CUS")
gadget:Shutdown()
gadget:Initialize()
end
local function DisableCUS(optName, _, _, playerID)
if (playerID ~= Spring.GetMyPlayerID()) then
return
end
Spring.Echo("Removing CUS")
gadget:Shutdown()
end
local function UpdateSun(optName, _, _, playerID)
sunChanged = true
end
-----------------------------------------------------------------
-----------------------------------------------------------------
function gadget:Initialize()
if BAR_COMPAT then
Spring.Echo("Removing CUS due to 105+")
gadgetHandler:RemoveGadget()
return
end
--// GG assignment
GG.CUS = {}
--// load the materials config files
local unitMaterialDefs, featureMaterialDefs = _LoadMaterialConfigFiles(MATERIALS_DIR)
--// process the materials (compile shaders, load textures, ...)
_ProcessMaterials(unitRendering, unitMaterialDefs)
_ProcessMaterials(featureRendering, featureMaterialDefs)
advShading = Spring.HaveAdvShading()
shadows = Spring.HaveShadows()
sunChanged = true --always on on load/reload
optionsChanged = true --just in case
local normalmapping = Spring.GetConfigInt("NormalMapping", 1) > 0
local treewind = Spring.GetConfigInt("TreeWind", 1) > 0
local commonOptions = {
shadowmapping = shadows,
normalmapping = normalmapping,
treewind = treewind,
}
for _, rendering in ipairs(allRendering) do
for matName, matTable in pairs(rendering.materialDefs) do
if matTable.GetAllOptions then
local allOptions = matTable.GetAllOptions()
for opt, _ in pairs(allOptions) do
if not registeredOptions[opt] then
registeredOptions[opt] = true
gadgetHandler:AddChatAction(opt, _ProcessOptions)
end
end
for optName, optValue in pairs(commonOptions) do
_ProcessOptions(optName, nil, optValue, Spring.GetMyPlayerID())
end
end
end
end
BindMaterials()
gadgetHandler:AddChatAction("updatesun", UpdateSun)
gadgetHandler:AddChatAction("cusreload", ReloadCUS)
gadgetHandler:AddChatAction("reloadcus", ReloadCUS)
gadgetHandler:AddChatAction("disablecus", DisableCUS)
gadgetHandler:AddChatAction("cusdisable", DisableCUS)
if not USE_OBJECT_DAMAGE then
gadgetHandler:RemoveCallIn("UnitDamaged")
--gadgetHandler:RemoveCallIn("FeatureDamaged")
end
end
function gadget:Shutdown()
for _, rendering in ipairs(allRendering) do
_CleanupEverything(rendering)
end
--// GG de-assignment
GG.CUS = nil
end
| gpl-2.0 |
cs-willian-silva/vlc | share/lua/intf/dumpmeta.lua | 98 | 2125 | --[==========================================================================[
dumpmeta.lua: dump a file's meta data on stdout/stderr
--[==========================================================================[
Copyright (C) 2010 the VideoLAN team
$Id$
Authors: Antoine Cellerier <dionoea at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]==========================================================================]
--[[ to dump meta data information in the debug output, run:
vlc -I luaintf --lua-intf dumpmeta coolmusic.mp3
Additional options can improve performance and output readability:
-V dummy -A dummy --no-video-title --no-media-library -q
--]]
local item
repeat
item = vlc.input.item()
until (item and item:is_preparsed())
-- preparsing doesn't always provide all the information we want (like duration)
repeat
until item:stats()["demux_read_bytes"] > 0
vlc.msg.info("name: "..item:name())
vlc.msg.info("uri: "..vlc.strings.decode_uri(item:uri()))
vlc.msg.info("duration: "..tostring(item:duration()))
vlc.msg.info("meta data:")
local meta = item:metas()
if meta then
for key, value in pairs(meta) do
vlc.msg.info(" "..key..": "..value)
end
else
vlc.msg.info(" no meta data available")
end
vlc.msg.info("info:")
for cat, data in pairs(item:info()) do
vlc.msg.info(" "..cat)
for key, value in pairs(data) do
vlc.msg.info(" "..key..": "..value)
end
end
vlc.misc.quit()
| gpl-2.0 |
Aquanim/Zero-K | scripts/benzcom.lua | 2 | 8712 | include "constants.lua"
--------------------------------------------------------------------------------
-- pieces
--------------------------------------------------------------------------------
local pieceMap = Spring.GetUnitPieceMap(unitID)
local HAS_GATTLING = pieceMap.rgattlingflare and true or false
local HAS_BONUS_CANNON = pieceMap.bonuscannonflare and true or false
local torso = piece 'torso'
local rcannon_flare= HAS_GATTLING and piece('rgattlingflare') or piece('rcannon_flare')
local barrels= HAS_GATTLING and piece 'barrels' or nil
local lcannon_flare = HAS_BONUS_CANNON and piece('bonuscannonflare') or piece('lnanoflare')
local lnanoflare = piece 'lnanoflare'
local lnanohand = piece 'lnanohand'
local larm = piece 'larm'
local rarm = piece 'rarm'
local pelvis = piece 'pelvis'
local rupleg = piece 'rupleg'
local lupleg = piece 'lupleg'
local rhand = piece 'rhand'
local lleg = piece 'lleg'
local lfoot = piece 'lfoot'
local rleg = piece 'rleg'
local rfoot = piece 'rfoot'
local smokePiece = {torso}
local nanoPieces = {lnanoflare}
--------------------------------------------------------------------------------
-- constants
--------------------------------------------------------------------------------
local SIG_WALK = 1
local SIG_LASER = 2
local SIG_DGUN = 4
local SIG_RESTORE_LASER = 8
local SIG_RESTORE_DGUN = 16
local TORSO_SPEED_YAW = math.rad(300)
local ARM_SPEED_PITCH = math.rad(180)
local PACE = 3.4
local BASE_VELOCITY = UnitDefNames.benzcom1.speed or 1.25*30
local VELOCITY = UnitDefs[unitDefID].speed or BASE_VELOCITY
PACE = PACE * VELOCITY/BASE_VELOCITY
local THIGH_FRONT_ANGLE = -math.rad(60)
local THIGH_FRONT_SPEED = math.rad(40) * PACE
local THIGH_BACK_ANGLE = math.rad(30)
local THIGH_BACK_SPEED = math.rad(40) * PACE
local SHIN_FRONT_ANGLE = math.rad(40)
local SHIN_FRONT_SPEED = math.rad(60) * PACE
local SHIN_BACK_ANGLE = math.rad(15)
local SHIN_BACK_SPEED = math.rad(60) * PACE
local ARM_FRONT_ANGLE = -math.rad(15)
local ARM_FRONT_SPEED = math.rad(14.5) * PACE
local ARM_BACK_ANGLE = math.rad(5)
local ARM_BACK_SPEED = math.rad(14.5) * PACE
local ARM_PERPENDICULAR = math.rad(90)
--[[
local FOREARM_FRONT_ANGLE = -math.rad(15)
local FOREARM_FRONT_SPEED = math.rad(40) * PACE
local FOREARM_BACK_ANGLE = -math.rad(10)
local FOREARM_BACK_SPEED = math.rad(40) * PACE
]]--
local TORSO_ANGLE_MOTION = math.rad(8)
local TORSO_SPEED_MOTION = math.rad(7)*PACE
local RESTORE_DELAY_LASER = 4000
local RESTORE_DELAY_DGUN = 2500
--------------------------------------------------------------------------------
-- vars
--------------------------------------------------------------------------------
local isLasering, isDgunning, gunLockOut, shieldOn = false, false, false, true
local restoreHeading, restorePitch = 0, 0
local starBLaunchers = {}
local wepTable = UnitDefs[unitDefID].weapons
wepTable.n = nil
for index, weapon in pairs(wepTable) do
local weaponDef = WeaponDefs[weapon.weaponDef]
if weaponDef.type == "StarburstLauncher" then
starBLaunchers[index] = true
end
end
--------------------------------------------------------------------------------
-- funcs
--------------------------------------------------------------------------------
local function Walk()
Signal(SIG_WALK)
SetSignalMask(SIG_WALK)
while true do
local speedMult = math.max(0.05, GG.att_MoveChange[unitID] or 1)
--left leg up, right leg back
Turn(lupleg, x_axis, THIGH_FRONT_ANGLE, THIGH_FRONT_SPEED * speedMult)
Turn(lleg, x_axis, SHIN_FRONT_ANGLE, SHIN_FRONT_SPEED * speedMult)
Turn(rupleg, x_axis, THIGH_BACK_ANGLE, THIGH_BACK_SPEED * speedMult)
Turn(rleg, x_axis, SHIN_BACK_ANGLE, SHIN_BACK_SPEED * speedMult)
if not(isLasering or isDgunning) then
--left arm back, right arm front
Turn(torso, y_axis, TORSO_ANGLE_MOTION, TORSO_SPEED_MOTION * speedMult)
end
WaitForTurn(rupleg, x_axis)
Sleep(0)
--right leg up, left leg back
Turn(lupleg, x_axis, THIGH_BACK_ANGLE, THIGH_BACK_SPEED * speedMult)
Turn(lleg, x_axis, SHIN_BACK_ANGLE, SHIN_BACK_SPEED * speedMult)
Turn(rupleg, x_axis, THIGH_FRONT_ANGLE, THIGH_FRONT_SPEED * speedMult)
Turn(rleg, x_axis, SHIN_FRONT_ANGLE, SHIN_FRONT_SPEED * speedMult)
if not(isLasering or isDgunning) then
--left arm front, right arm back
Turn(torso, y_axis, -TORSO_ANGLE_MOTION, TORSO_SPEED_MOTION * speedMult)
end
WaitForTurn(lupleg, x_axis)
Sleep(0)
end
end
local function RestoreLegs()
Signal(SIG_WALK)
SetSignalMask(SIG_WALK)
Move(pelvis, y_axis, 0, 1)
Turn(rupleg, x_axis, 0, math.rad(200))
Turn(rleg, x_axis, 0, math.rad(200))
Turn(lupleg, x_axis, 0, math.rad(200))
Turn(lleg, x_axis, 0, math.rad(200))
Turn(torso, y_axis, 0, math.rad(200))
Turn(larm, x_axis, 0, math.rad(200))
Turn(rarm, x_axis, 0, math.rad(200))
end
function script.Create()
Hide(rcannon_flare)
Hide(lnanoflare)
-- Turn(larm, x_axis, math.rad(30))
-- Turn(rarm, x_axis, math.rad(-10))
-- Turn(rhand, x_axis, math.rad(41))
-- Turn(lnanohand, x_axis, math.rad(36))
StartThread(GG.Script.SmokeUnit, unitID, smokePiece)
Spring.SetUnitNanoPieces(unitID, nanoPieces)
end
function script.StartMoving()
StartThread(Walk)
end
function script.StopMoving()
StartThread(RestoreLegs)
end
local function RestoreLaser()
Signal(SIG_RESTORE_LASER)
SetSignalMask(SIG_RESTORE_LASER)
Sleep(RESTORE_DELAY_LASER)
isLasering = false
Turn(larm, x_axis, 0, ARM_SPEED_PITCH)
Turn(lnanohand, x_axis, 0, ARM_SPEED_PITCH)
Turn(rarm, x_axis, restorePitch, ARM_SPEED_PITCH)
Turn(rhand, x_axis, 0, ARM_SPEED_PITCH)
Turn(torso, y_axis, restoreHeading, TORSO_SPEED_YAW)
if HAS_GATTLING then
Spin(barrels, z_axis, 100)
Sleep(200)
Turn(barrels, z_axis, 0, ARM_SPEED_PITCH)
end
end
local function RestoreDGun()
Signal(SIG_RESTORE_DGUN)
SetSignalMask(SIG_RESTORE_DGUN)
Sleep(RESTORE_DELAY_DGUN)
isDgunning = false
Turn(larm, x_axis, 0, ARM_SPEED_PITCH)
Turn(lnanohand, x_axis, 0, ARM_SPEED_PITCH)
Turn(rarm, x_axis, restorePitch, ARM_SPEED_PITCH)
Turn(rhand, x_axis, 0, ARM_SPEED_PITCH)
Turn(torso, y_axis, restoreHeading, TORSO_SPEED_YAW)
end
function script.AimWeapon(num, heading, pitch)
if num >= 5 then
Signal(SIG_LASER)
SetSignalMask(SIG_LASER)
isLasering = true
Turn(rarm, x_axis, math.rad(0) -pitch, ARM_SPEED_PITCH)
Turn(torso, y_axis, heading, TORSO_SPEED_YAW)
Turn(rhand, x_axis, math.rad(0), ARM_SPEED_PITCH)
WaitForTurn(torso, y_axis)
WaitForTurn(rarm, x_axis)
StartThread(RestoreLaser)
return true
elseif num == 3 then
if starBLaunchers[num] then
pitch = ARM_PERPENDICULAR
end
Signal(SIG_DGUN)
SetSignalMask(SIG_DGUN)
isDgunning = true
Turn(larm, x_axis, math.rad(0) -pitch, ARM_SPEED_PITCH)
Turn(torso, y_axis, heading, TORSO_SPEED_YAW)
Turn(lnanohand, x_axis, math.rad(0), ARM_SPEED_PITCH)
WaitForTurn(torso, y_axis)
WaitForTurn(rarm, x_axis)
StartThread(RestoreDGun)
return true
elseif num == 2 or num == 4 then
Sleep(100)
return (shieldOn)
end
return false
end
function script.FireWeapon(num)
if num == 5 then
EmitSfx(rcannon_flare, 1024)
elseif num == 3 then
EmitSfx(lcannon_flare, 1026)
end
end
function script.Shot(num)
if num == 5 then
EmitSfx(rcannon_flare, 1025)
elseif num == 3 then
EmitSfx(lcannon_flare, 1027)
end
end
function script.AimFromWeapon(num)
return torso
end
function script.QueryWeapon(num)
if num == 3 then
return lcannon_flare
elseif num == 2 or num == 4 then
return pelvis
end
return rcannon_flare
end
function script.StopBuilding()
SetUnitValue(COB.INBUILDSTANCE, 0)
Turn(larm, x_axis, 0, ARM_SPEED_PITCH)
restoreHeading, restorePitch = 0, 0
StartThread(RestoreDGun)
end
function script.StartBuilding(heading, pitch)
restoreHeading, restorePitch = heading, pitch
Turn(larm, x_axis, math.rad(-30) - pitch, ARM_SPEED_PITCH)
if not (isDgunning) then Turn(torso, y_axis, heading, TORSO_SPEED_YAW) end
SetUnitValue(COB.INBUILDSTANCE, 1)
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity < 0.5 then
Explode(torso, SFX.NONE)
Explode(larm, SFX.NONE)
Explode(rarm, SFX.NONE)
Explode(pelvis, SFX.NONE)
Explode(lupleg, SFX.NONE)
Explode(rupleg, SFX.NONE)
Explode(lnanoflare, SFX.NONE)
Explode(rhand, SFX.NONE)
Explode(lleg, SFX.NONE)
Explode(rleg, SFX.NONE)
return 1
else
Explode(torso, SFX.SHATTER)
Explode(larm, SFX.SMOKE + SFX.FIRE + SFX.EXPLODE)
Explode(rarm, SFX.SMOKE + SFX.FIRE + SFX.EXPLODE)
Explode(pelvis, SFX.SHATTER)
Explode(lupleg, SFX.SHATTER)
Explode(rupleg, SFX.SHATTER)
Explode(lnanoflare, SFX.SMOKE + SFX.FIRE + SFX.EXPLODE)
Explode(rhand, SFX.SMOKE + SFX.FIRE + SFX.EXPLODE)
Explode(lleg, SFX.SHATTER)
Explode(rleg, SFX.SHATTER)
return 2
end
end
| gpl-2.0 |
PicassoCT/Journeywar | gamedata/explosions/conDroneMedShadow.lua | 1 | 1041 | -- dirt
return {
["conDroneMedShadow"] = {
dirtg = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.7,
alwaysvisible = true,
colormap = [[0.5 0.5 0.5 1.0 0.5 0.5 0.5 1.0 0 0 0 0.0]],
directional = true,
emitrot = 90,
emitrotspread = 0,
emitvector = [[dir]],
gravity = [[0, 0.001, 0]],
numparticles = 4,
particlelife = 15,
particlelifespread = 20,
particlesize = [[12 r4]],
particlesizespread = 5,
particlespeed = 1,
particlespeedspread = 6,
pos = [[r-0.5 r0.5, 1 r2, r-0.5 r0.5]],
sizegrowth = 1.05,
sizemod = 0.999,
texture = [[SmokeAshCloud]],
useairlos = true,
},
},
},
}
| gpl-3.0 |
b03605079/darkstar | scripts/zones/Windurst-Jeuno_Airship/Zone.lua | 1 | 1370 | -----------------------------------
--
-- Zone: Windurst-Jeuno_Airship
--
-----------------------------------
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
if ((player:getXPos() == 0) or (player:getYPos() == 0) or (player:getZPos() == 0)) then
player:setPos(math.random(-4, 4),1,math.random(-23,-12));
end
return cs;
end;
-----------------------------------
-- onTransportEvent
-----------------------------------
function onTransportEvent(player,transport)
player:startEvent(0x0064);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0064) then
local prevzone = player:getPreviousZone();
if (prevzone == 246) then
player:setPos(0,0,0,0,240);
elseif (prevzone == 240) then
player:setPos(0,0,0,0,246);
end
end
end;
| gpl-3.0 |
Sakura-Winkey/LuCI | applications/luci-app-adkill/luasrc/model/cbi/adkill.lua | 4 | 2062 | --[[
adkill 配置页面
Copyright (C) 2015 GuoGuo <gch981213@gmail.com>
]]--
m = Map("adkill", translate("Ad-Killer"),
translatef("A kernel module which can be configured to remove advertisements in some video sites.")
)
s = m:section(TypedSection, "adkill_base", translate("Basic Settings"))
s.anonymous = true
o = s:option(Flag, "enabled", translate("Enable Ad-Killer"))
s = m:section(TypedSection, "rule_404", translate("Rules - 404"), translate("The requests which match the rule will be blocked with \"404 Not Found\" error."))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "host", translate("Host")).optional=false
s:option(Value, "url", translate("URL")).optional=false
s = m:section(TypedSection, "rule_502", translate("Rules - 502"), translate("The requests which match the rule will be blocked with \"502 Bad Gateway\" error."))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "host", translate("Host")).optional=false
s:option(Value, "url", translate("URL")).optional=false
s = m:section(TypedSection, "rule_302", translate("Rules - 302"), translate("The requests which match the source URL will be redirected to the destination URL.This rule is usually used to replace the flash player on the website."))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "shost", translate("Source Host")).optional=false
s:option(Value, "surl", translate("Source URL")).optional=false
s:option(Value, "dhost", translate("Destination Host")).optional=false
s:option(Value, "durl", translate("Destination URL")).optional=false
s = m:section(TypedSection, "rule_modify", translate("Rules - Modifying"), translate("A part of the request URL (after the Keyword) will be replaced with the Value."))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "host", translate("Host")).optional=false
s:option(Value, "mark", translate("Keyword")).optional=false
s:option(Value, "val", translate("Value")).optional=false
return m
| apache-2.0 |
MOSAVI17/Mosavi3 | plugins/admin.lua | 53 | 2402 | 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 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
local hash = parsed_url(matches[2])
import_chat_link(hash,ok_cb,false)
end
return
end
return {
patterns = {
"^[!/](pm) (%d+) (.*)$",
"^[!/](import) (.*)$",
"^[!/](unblock) (%d+)$",
"^[!/](block) (%d+)$",
"^[!/](markread) (on)$",
"^[!/](markread) (off)$",
"^[!/](setbotphoto)$",
"%[(photo)%]"
},
run = run,
} | gpl-2.0 |
b03605079/darkstar | scripts/globals/armor_upgrade.lua | 1 | 13910 |
-----------------------------------------------------------------------------------------------------------------------
-- Artefact Armor +1
------------------------------------------------------------------------------------------------------------------------
Artifact_Armor_Plus_one={
--A, {AF+1 ID, Relic_Armor ID , Relic_Armor_-1 ID, Crafted_Item ID, Currency ID, curencynNbr}
101 ,{ 15245 , 15072 , 2033 , 1990 , 1455 , 28 }, --war
102 ,{ 14500 , 15087 , 2034 , 1990 , 1455 , 28 },
103 ,{ 14909 , 15102 , 2035 , 1990 , 1455 , 28 },
104 ,{ 15580 , 15117 , 2036 , 1990 , 1455 , 28 },
105 ,{ 15665 , 15132 , 2037 , 1990 , 1455 , 28 },
106 ,{ 15246 , 15073 , 2038 , 2122 , 1455 , 26 },--mnk
107 ,{ 14501 , 15088 , 2039 , 1991 , 1455 , 26 },
108 ,{ 14910 , 15103 , 2040 , 2122 , 1455 , 26 },
109 ,{ 15581 , 15118 , 2041 , 2122 , 1455 , 26 },
110 ,{ 15666 , 15133 , 2042 , 2122 , 1455 , 26 },
111 ,{ 15247 , 15074 , 2043 , 1994 , 1452 , 28 },--whm
112 ,{ 14502 , 15089 , 2044 , 1992 , 1452 , 28 },
113 ,{ 14911 , 15104 , 2045 , 1993 , 1452 , 28 },
114 ,{ 15582 , 15119 , 2046 , 1996 , 1452 , 26 },
115 ,{ 15667 , 15134 , 2047 , 1995 , 1452 , 28 },
116 ,{ 15248 , 15075 , 2048 , 1993 , 1449 , 28 },--blm
117 ,{ 14503 , 15090 , 2049 , 1993 , 1449 , 28 },
118 ,{ 14912 , 15105 , 2050 , 1993 , 1449 , 28 },
119 ,{ 15583 , 15120 , 2051 , 1994 , 1449 , 28 },
120 ,{ 15668 , 15135 , 2052 , 1995 , 1449 , 28 },
121 ,{ 15249 , 15076 , 2053 , 1996 , 1452 , 22 },--rdm
122 ,{ 14504 , 15091 , 2054 , 1996 , 1452 , 22 },
123 ,{ 14913 , 15106 , 2055 , 1996 , 1452 , 22 },
124 ,{ 15584 , 15121 , 2056 , 1996 , 1452 , 22 },
125 ,{ 15669 , 15136 , 2057 , 2122 , 1452 , 26 },
126 ,{ 15250 , 15077 , 2058 , 1997 , 1449 , 26 },--thf
127 ,{ 14505 , 15092 , 2059 , 1997 , 1449 , 26 },
128 ,{ 14914 , 15107 , 2060 , 1998 , 1449 , 28 },
129 ,{ 15585 , 15122 , 2061 , 1997 , 1449 , 26 },
130 ,{ 15670 , 15137 , 2062 , 1998 , 1449 , 28 },
131 ,{ 15251 , 15078 , 2063 , 745 , 1452 , 20 },--pld
132 ,{ 14506 , 15093 , 2064 , 1999 , 1452 , 20 },
133 ,{ 14915 , 15108 , 2065 , 667 , 1452 , 30 },
134 ,{ 15586 , 15123 , 2066 , 667 , 1452 , 30 },
135 ,{ 15671 , 15138 , 2067 , 667 , 1452 , 30 },
136 ,{ 15252 , 15079 , 2068 , 664 , 1455 , 28 },--drk
137 ,{ 14507 , 15094 , 2069 , 2001 , 1455 , 20 },
138 ,{ 14916 , 15109 , 2070 , 664 , 1455 , 28 },
139 ,{ 15587 , 15124 , 2071 , 664 , 1455 , 28 },
140 ,{ 15672 , 15139 , 2072 , 664 , 1455 , 28 },
141 ,{ 15253 , 15080 , 2073 , 1458 , 1449 , 30 },--bst
142 ,{ 14508 , 15095 , 2074 , 2125 , 1449 , 26 },
143 ,{ 14917 , 15110 , 2075 , 2125 , 1449 , 26 },
144 ,{ 15588 , 15125 , 2076 , 2124 , 1449 , 26 },
145 ,{ 15673 , 15140 , 2077 , 2124 , 1449 , 26 },
146 ,{ 15254 , 15081 , 2078 , 823 , 1455 , 26 },--brd
147 ,{ 14509 , 15096 , 2079 , 1459 , 1455 , 28 },
148 ,{ 14918 , 15111 , 2080 , 1459 , 1455 , 28 },
149 ,{ 15589 , 15126 , 2081 , 1459 , 1455 , 28 },
150 ,{ 15674 , 15141 , 2082 , 1459 , 1455 , 28 },
151 ,{ 15255 , 15082 , 2083 , 2005 , 1449 , 30 },--rng
152 ,{ 14510 , 15097 , 2084 , 2005 , 1449 , 30 },
153 ,{ 14919 , 15112 , 2085 , 506 , 1449 , 30 },
154 ,{ 15590 , 15127 , 2086 , 506 , 1449 , 30 },
155 ,{ 15675 , 15142 , 2087 , 2122 , 1449 , 26 },
156 ,{ 15256 , 15083 , 2088 , 752 , 1455 , 24 },--sam
157 ,{ 14511 , 15098 , 2089 , 2006 , 1455 , 22 },
158 ,{ 14920 , 15113 , 2090 , 2007 , 1455 , 20 },
159 ,{ 15591 , 15128 , 2091 , 2007 , 1455 , 20 },
160 ,{ 15676 , 15143 , 2092 , 2007 , 1455 , 20 },
161 ,{ 15257 , 15084 , 2093 , 2008 , 1455 , 26 },--nin
162 ,{ 14512 , 15099 , 2094 , 2008 , 1455 , 26 },
163 ,{ 14921 , 15114 , 2095 , 2008 , 1455 , 26 },
164 ,{ 15592 , 15129 , 2096 , 2007 , 1455 , 20 },
165 ,{ 15677 , 15144 , 2097 , 2008 , 1455 , 26 },
166 ,{ 15258 , 15085 , 2098 , 2012 , 1452 , 30 },--drg
167 ,{ 14513 , 15100 , 2099 , 2012 , 1452 , 30 },
168 ,{ 14922 , 15115 , 2100 , 851 , 1452 , 30 },
169 ,{ 15593 , 15130 , 2101 , 851 , 1452 , 30 },
170 ,{ 15678 , 15145 , 2102 , 851 , 1452 , 30 },
171 ,{ 15259 , 15086 , 2103 , 2009 , 1449 , 30 },--smn
172 ,{ 14514 , 15101 , 2104 , 2010 , 1449 , 30 },
173 ,{ 14923 , 15116 , 2105 , 2010 , 1449 , 30 },
174 ,{ 15594 , 15131 , 2106 , 2010 , 1449 , 30 },
175 ,{ 15679 , 15146 , 2107 , 720 , 1449 , 28 },
176 ,{ 11466 , 11465 , 2662 , 2703 , 1452 , 26 },--blu
177 ,{ 11293 , 11292 , 2663 , 1702 , 1452 , 26 },
178 ,{ 15026 , 15025 , 2664 , 2703 , 1452 , 26 },
179 ,{ 16347 , 16346 , 2665 , 1702 , 1452 , 26 },
180 ,{ 11383 , 11382 , 2666 , 2703 , 1452 , 26 },
181 ,{ 11469 , 11468 , 2667 , 2122 , 1455 , 30 },--cor
182 ,{ 11296 , 11295 , 2668 , 2704 , 1455 , 30 },
183 ,{ 15029 , 15028 , 2669 , 2704 , 1455 , 30 },
184 ,{ 16350 , 16349 , 16349 , 2704 , 1455 , 30 },
185 ,{ 11386 , 11385 , 2671 , 2152 , 1455 , 30 },
186 ,{ 11472 , 11471 , 2672 , 2705 , 1449 , 26 },--pup
187 ,{ 11299 , 11298 , 2673 , 1999 , 1449 , 26 },
188 ,{ 15032 , 15031 , 2674 , 2705 , 1449 , 26 },
189 ,{ 28525 , 16352 , 2675 , 2705 , 1449 , 26 },
190 ,{ 28525 , 11388 , 2676 , 2538 , 1449 , 26 },
191 ,{ 11479 , 11478 , 2718 , 745 , 1452 , 30 },
192 ,{ 11306 , 11305 , 2719 , 2537 , 1452 , 30 },--dnc
193 ,{ 15039 , 15038 , 2720 , 745 , 1452 , 30 },
194 ,{ 16361 , 16360 , 2721 , 1702 , 1452 , 30 },
195 ,{ 11397 , 11396 , 2722 , 1992 , 1452 , 30 },
196 ,{ 11481 , 11480 , 2723 , 746 , 1455 , 28 },--sch
197 ,{ 11308 , 11307 , 2724 , 1699 , 1455 , 28 },
198 ,{ 15041 , 15040 , 2725 , 2530 , 1455 , 28 },
199 ,{ 16363 , 16362 , 2726 , 1993 , 1455 , 28 },
200 ,{ 11399 , 11398 , 2727 , 2424 , 1455 , 28 }
};
------------------------------------------------------------------------------------------------------------------------------
-- RELIC Armor +1
----------------------------------------------------------------------------------------------------------------------------
Relic_Armor_Plus_one={
--A AF+1 AF Temenos Apollyon craft item AB_Nbr
1 , { 15225 , 12511 , 1930 , 1931 , 1990 , 20 },-- Warrior--Fighter's_Armor_+1_
2 , { 14473 , 12638 , 1930 , 1931 , 1990 , 35 },--
3 , { 14890 , 13961 , 1930 , 1931 , 1990 , 15 },--
4 , { 15561 , 14214 , 1930 , 1931 , 1990 , 15 },--
5 , { 15352 , 14089 , 1930 , 1931 , 1990 , 25 },--
6 , { 15226 , 12512 , 1932 , 1933 , 1117 , 25 },-- Monk Temple_Attire_+1_
7 , { 14474 , 12639 , 1932 , 1933 , 1991 , 40 },--
8 , { 14891 , 13962 , 1932 , 1933 , 1117 , 20 },--
9 , { 15562 , 14215 , 1932 , 1933 , 1117 , 25 },--
10 , { 15353 , 14090 , 1932 , 1933 , 855 , 20 },--
11 , { 15227 , 13855 , 1934 , 1935 , 1994 , 30 },-- White_Mage--Healer's_Attire_+1_
12 , { 14475 , 12640 , 1934 , 1935 , 1992 , 40 },--
13 , { 14892 , 13963 , 1934 , 1935 , 1993 , 20 },--
14 , { 14892 , 14892 , 1934 , 1935 , 1996 , 25 },--
15 , { 15354 , 14091 , 1934 , 1935 , 1995 , 20 },--
16 , { 15228 , 13856 , 1936 , 1937 , 1993 , 25 },-- Black_Mage Wizard's_Attire_+1_
17 , { 14476 , 12641 , 1936 , 1937 , 1993 , 25 },--
18 , { 14893 , 13964 , 1936 , 1937 , 1993 , 15 },--
19 , { 15564 , 14217 , 1936 , 1937 , 1994 , 30 },--
20 , { 15355 , 14092 , 1936 , 1937 , 1995 , 20 },--
21 , { 15229 , 12513 , 1938 , 1939 , 1996 , 20 },-- Red_Mage--Warlock's_Armor_+1_
22 , { 14477 , 12642 , 1938 , 1939 , 1996 , 30 },--
23 , { 14894 , 13965 , 1938 , 1939 , 1996 , 15 },--
24 , { 15565 , 14218 , 1938 , 1939 , 1996 , 20 },--
25 , { 15356 , 14093 , 1938 , 1939 , 855 , 25 },--
26 , { 15230 , 12514 , 1940 , 1941 , 1997 , 30 },-- Thief--Rogue's_Attire_+1_
27 , { 14478 , 12643 , 1940 , 1941 , 1997 , 40 },--
28 , { 14895 , 13966 , 1940 , 1941 , 1998 , 20 },--
29 , { 15566 , 14219 , 1940 , 1941 , 1997 , 30 },--
30 , { 15357 , 14094 , 1940 , 1941 , 1998 , 20 },--
31 , { 15231 , 12515 , 1942 , 1943 , 745 , 25 },-- Paladin--Gallant_Armor_+1_
32 , { 14479 , 12644 , 1942 , 1943 , 1999 , 30 },--
33 , { 14896 , 13967 , 1942 , 1943 , 667 , 20 },--
34 , { 15567 , 14220 , 1942 , 1943 , 667 , 20 },--
35 , { 15358 , 14095 , 1942 , 1943 , 667 , 20 },--
36 , { 15232 , 12516 , 1944 , 1945 , 664 , 25 },-- Dark_Knight Chaos_Armor_+1_
37 , { 14480 , 12645 , 1944 , 1945 , 2001 , 30 },--
38 , { 14897 , 13968 , 1944 , 1945 , 664 , 15 },--
39 , { 15568 , 14221 , 1944 , 1945 , 664 , 20 },--
40 , { 15359 , 14096 , 1944 , 1945 , 664 , 20 },--
41 , { 15233 , 12517 , 1946 , 1947 , 2002 , 30 },-- BeastmasterBeast_Armor_+1_
42 , { 14481 , 12646 , 1946 , 1947 , 2003 , 40 },--
43 , { 14898 , 13969 , 1946 , 1947 , 2003 , 20 },--
44 , { 15569 , 14222 , 1946 , 1947 , 848 , 30 },--
45 , { 15360 , 14097 , 1946 , 1947 , 848 , 20 },--
46 , { 15234 , 13857 , 1948 , 1949 , 823 , 15 },-- Bard Choral_Attire_+1_
47 , { 14482 , 12647 , 1948 , 1949 , 1117 , 40 },--
48 , { 14899 , 13970 , 1948 , 1949 , 1117 , 25 },--
49 , { 15570 , 14223 , 1948 , 1949 , 1117 , 25 },--
50 , { 15361 , 14098 , 1948 , 1949 , 1117 , 25 },--
51 , { 15235 , 12518 , 1950 , 1951 , 2005 , 25 },-- Ranger--Hunter's_Attire_+1_
52 , { 14483 , 12648 , 1950 , 1951 , 2005 , 40 },--
53 , { 14900 , 13971 , 1950 , 1951 , 506 , 20 },--
54 , { 15571 , 14224 , 1950 , 1951 , 506 , 25 },--
55 , { 15362 , 14099 , 1950 , 1951 , 855 , 25 },--
56 , { 15236 , 13868 , 1952 , 1953 , 752 , 15 },-- Samurai--Myochin_Armor_+1_
57 , { 14484 , 13781 , 1952 , 1953 , 2006 , 25 },--
58 , { 14901 , 13972 , 1952 , 1953 , 2007 , 20 },--
59 , { 15572 , 14225 , 1952 , 1953 , 2007 , 30 },--
60 , { 15363 , 14100 , 1952 , 1953 , 2007 , 20 },--
61 , { 15237 , 13869 , 1954 , 1955 , 2008 , 20 },-- Ninja Ninja's_Garb_+1_
62 , { 14485 , 13782 , 1954 , 1955 , 2008 , 30 },--
63 , { 14902 , 13973 , 1954 , 1955 , 2008 , 15 },--
64 , { 15573 , 14226 , 1954 , 1955 , 2007 , 30 },--
65 , { 15364 , 14101 , 1954 , 1955 , 2008 , 15 },--
66 , { 15238 , 12519 , 1956 , 1957 , 2012 , 30 },-- Dragoon Drachen_Armor_+1_
67 , { 14486 , 12649 , 1956 , 1957 , 2012 , 40 },--
68 , { 14903 , 13974 , 1956 , 1957 , 851 , 20 },--
69 , { 15574 , 14227 , 1956 , 1957 , 851 , 25 },--
70 , { 15365 , 14102 , 1956 , 1957 , 851 , 20 },--
71 , { 15239 , 12520 , 1958 , 1959 , 2009 , 25 },-- Summoner--Evoker's_Attire_+1_
72 , { 14487 , 12650 , 1958 , 1959 , 2010 , 35 },--
73 , { 14904 , 13975 , 1958 , 1959 , 2010 , 20 },--
74 , { 15575 , 14228 , 1958 , 1959 , 2010 , 30 },--
75 , { 15366 , 14103 , 1958 , 1959 , 720 , 15 },--
76 , { 11464 , 15265 , 2656 , 2657 , 2703 , 20 },-- Blue_Mage Magus_Attire_+1_
77 , { 11291 , 14521 , 2656 , 2657 , 2289 , 30 },--
78 , { 15024 , 14928 , 2656 , 2657 , 2703 , 15 },--
79 , { 16345 , 15600 , 2656 , 2657 , 2289 , 30 },--
80 , { 11381 , 15684 , 2656 , 2657 , 2703 , 15 },--
81 , { 11467 , 15266 , 2658 , 2659 , 2012 , 30 },-- Corsair Corsair's_Attire_+1_
82 , { 11294 , 14522 , 2658 , 2659 , 2704 , 30 },--
83 , { 15027 , 14929 , 2658 , 2659 , 2704 , 20 },--
84 , { 16348 , 15601 , 2658 , 2659 , 2704 , 30 },--
85 , { 11384 , 15685 , 2658 , 2659 , 2152 , 25 },--
86 , { 11470 , 15267 , 2660 , 2661 , 2705 , 20 },-- Puppetmaster--Puppetry_Attire_+1_
87 , { 11297 , 14523 , 2660 , 2661 , 1699 , 30 },--
88 , { 15030 , 14930 , 2660 , 2661 , 2705 , 20 },--
89 , { 16351 , 15602 , 2660 , 2661 , 2705 , 20 },--
90 , { 11387 , 15686 , 2660 , 2661 , 1993 , 20 },--
91 , { 11475 , 16139 , 2714 , 2715 , 745 , 30 },-- Dancer Dancer's_Attire_+1_
92 , { 11302 , 14579 , 2714 , 2715 , 1699 , 35 },--
93 , { 15035 , 15003 , 2714 , 2715 , 745 , 25 },--
94 , { 16357 , 15660 , 2714 , 2715 , 2737 , 25 },--
95 , { 11393 , 15747 , 2714 , 2715 , 2737 , 20 },--
96 , { 11477 , 16140 , 2716 , 2717 , 2536 , 20 },-- Scholar--Scholar's_Attire_+1_
97 , { 11304 , 14580 , 2716 , 2717 , 2530 , 40 },--
98 , { 15037 , 15004 , 2716 , 2717 , 2530 , 25 },--
99 , { 16359 , 16311 , 2716 , 2717 , 1993 , 25 },--
100 , { 11395 , 11395 , 2716 , 2717 , 2288 , 25 }--
};
-- ------------------------------------------------------------------------------------------------
-- HOMAN NASHIRA ARMOR
-- ------------------------------------------------------------------------------------------------
LIMBUSARMOR={
1928,{15576}, -- Omega's Hindleg (Homam Cosciales)
1929,{15661}, -- Omega's Tail (Homam Gambieras)
1925,{15240}, -- Omega's Eye (Homam Zucchetto)
1927,{14905}, -- Omega's Foreleg (Homam Manopolas)
1926,{14488}, -- Omega's Heart (Homam Corazza)
1920,{15241}, -- Ultima's Cerebrum (Nashira Turban)
1921,{14489}, -- Ultima's Heart (Nashira Manteel)
1922,{14906}, -- Ultima's Claw (Nashira Gages)
1923,{15577}, -- Ultima's Leg (Nashira Seraweels)
1924,{15662} -- Ultima's Tail (Nashira Crackows)
}; | gpl-3.0 |
mrkulk/Unsupervised-Capsule-Network | eval.lua | 1 | 4636 | -- Tejas D Kulkarni
-- Usage: run this script and it will dump results into /tmp directory. Now you can use the ipython notebook to do further analysis
-- Please change 'src' variable to load respective network
require 'nn'
require 'Entity'
require 'optim'
require 'image'
require 'dataset-mnist'
require 'cutorch'
require 'xlua'
require 'Base'
require 'optim'
require 'image'
require 'sys'
require 'pl'
matio = require 'matio'
src = '/home/tejas/Documents/MIT/SequenceRender/slurm_logs/sr__num_entities_20_lr_0.005/'--'logs/'
plot = false
-- params = torch.load(src .. '/params.t7')
params = torch.load(src .. '/params.t7')
config = {
learningRate = params.lr,
momentumDecay = 0.1,
updateDecay = 0.01
}
require 'model'
testLogger = optim.Logger(paths.concat(params.save .. '/', 'test.log'))
if params.dataset == "omniglot" then
testData = {}; trainData = {}
trainData[1] = torch.load('dataset/omniglot_train_imgs.t7')
trainData[2] = torch.load('dataset/omniglot_train_labels.t7')
testData[1] = torch.load('dataset/omniglot_test_imgs.t7')
testData[2] = torch.load('dataset/omniglot_test_labels.t7')
else
--single mnist
-- create training set and normalize
trainData = mnist.loadTrainSet(nbTrainingPatches, geometry)
trainData.data = trainData.data/255
-- trainData:normalizeGlobal(mean, std)
-- create test set and normalize
testData = mnist.loadTestSet(nbTestingPatches, geometry)
testData.data = testData.data/255
-- testData:normalizeGlobal(mean, std)
-- trainData.data[torch.le(trainData.data,0.5)] = 0
-- trainData.data[torch.ge(trainData.data,0.5)] = 1
-- testData.data[torch.le(testData.data,0.5)] = 0
-- testData.data[torch.ge(testData.data,0.5)] = 1
end
setup(true, src)
function get_batch(t, data)
local inputs = torch.Tensor(params.bsize,1,32,32)
local targets = torch.Tensor(params.bsize)
local k = 1
for i = t,math.min(t+params.bsize-1,data:size()) do
-- load new sample
local sample = data[i]
local input = sample[1]:clone()
local _,target = sample[2]:clone():max(1)
inputs[{k,1,{},{}}] = input
targets[k] = target[1]
k = k + 1
end
inputs = inputs:cuda()
return inputs, targets
end
function init()
print("Network parameters:")
print(params)
reset_state(state)
local epoch = 0
local beginning_time = torch.tic()
local start_time = torch.tic()
end
function run(data, mode)
max_num = data:size()
bid = 1
for tt = 1, 1 do --max_num,params.bsize do
local inputs, targets = get_batch(tt, data)
local test_perp, test_output = fp(inputs)
local affines = {}
local entity_imgs = {}
-- local part_images = {}
for pp = 1,params.num_entities do
-- local p1_images = entities[pp].data.module.bias[1]:reshape(params.template_width, params.template_width)
-- part_images[pp] = p1_images
local tmp = extract_node(model.rnns[1], 'affines_' .. pp).data.module.output:double()
affines[pp] = torch.zeros(params.bsize, 7)
affines[pp][{{},{1,6}}] = tmp
affines[pp][{{},{7,7}}] = extract_node(model.rnns[1], 'intensity_' .. pp).data.module.output:double()
entity_imgs[pp] = extract_node(model.rnns[1], 'entity_' .. pp).data.module.output:double()
matio.save('tmp/'.. mode .. 'batch_aff_'.. pp ..'_' .. bid, {aff = affines[pp]})
matio.save('tmp/'.. mode .. 'batch_ent_'.. pp ..'_' .. bid, {entity = entity_imgs[pp]})
end
local en_imgs = {}
counter=1
for bb = 1,MAX_IMAGES_TO_DISPLAY do
for pp=1,params.num_entities do
en_imgs[counter] =entity_imgs[pp][bb]
counter = counter + 1
end
end
if plot then
window1=image.display({image=test_output[{{1,MAX_IMAGES_TO_DISPLAY},{},{},{}}], nrow=1, legend='Predictions', win=window1})
window2=image.display({image=inputs[{{1,MAX_IMAGES_TO_DISPLAY},{},{},{}}], nrow=1, legend='Targets', win=window2})
window3=image.display({image=en_imgs, nrow=params.num_entities, legend='Entities', win=window3})
-- window3 = image.display({image=part_images, nrow=3, legend='Strokes', win=window3})
end
-- testLogger:add{['% perp (test set)'] = test_perp}
-- testLogger:style{['% perp (test set)'] = '-'}
-- testLogger:plot()
matio.save('tmp/'.. mode .. 'batch_imgs_' .. bid, {imgs = inputs:double()})
matio.save('tmp/'.. mode .. 'batch_labels_' .. bid, {labels = targets})
bid = bid + 1
end
end
MAX_IMAGES_TO_DISPLAY = 20
plot = true
if plot then
max_num = 1
end
init()
-- run(trainData, 'train')
run(testData, 'test')
-- print(extract_node(model.rnns[1], 'entity_1').data.module.output[1][1]) | gpl-3.0 |
MTASZTAKI/ApertusVR | plugins/physics/bulletPhysics/3rdParty/bullet3/test/OpenCL/ParallelPrimitives/premake4.lua | 12 | 1456 | function createProject(vendor)
hasCL = findOpenCL(vendor)
if (hasCL) then
project ("Test_OpenCL_Primitives_" .. vendor)
initOpenCL(vendor)
language "C++"
kind "ConsoleApp"
includedirs {".","../../../src"}
files {
"main.cpp",
"../../../src/Bullet3OpenCL/Initialize/b3OpenCLInclude.h",
"../../../src/Bullet3OpenCL/Initialize/b3OpenCLUtils.cpp",
"../../../src/Bullet3OpenCL/Initialize/b3OpenCLUtils.h",
"../../../src/Bullet3OpenCL/ParallelPrimitives/b3FillCL.cpp",
"../../../src/Bullet3OpenCL/ParallelPrimitives/b3FillCL.h",
"../../../src/Bullet3OpenCL/ParallelPrimitives/b3BoundSearchCL.cpp",
"../../../src/Bullet3OpenCL/ParallelPrimitives/b3BoundSearchCL.h",
"../../../src/Bullet3OpenCL/ParallelPrimitives/b3PrefixScanCL.cpp",
"../../../src/Bullet3OpenCL/ParallelPrimitives/b3PrefixScanCL.h",
"../../../src/Bullet3OpenCL/ParallelPrimitives/b3RadixSort32CL.cpp",
"../../../src/Bullet3OpenCL/ParallelPrimitives/b3RadixSort32CL.h",
"../../../src/Bullet3OpenCL/ParallelPrimitives/b3LauncherCL.cpp",
"../../../src/Bullet3Common/b3AlignedAllocator.cpp",
"../../../src/Bullet3Common/b3AlignedAllocator.h",
"../../../src/Bullet3Common/b3AlignedObjectArray.h",
"../../../src/Bullet3Common/b3Logging.cpp",
"../../../src/Bullet3Common/b3Logging.h",
}
end
end
createProject("clew")
createProject("AMD")
createProject("Intel")
createProject("NVIDIA")
createProject("Apple")
| mit |
nagyistoce/google-diff-match-patch | lua/diff_match_patch.lua | 265 | 73869 | --[[
* Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* Based on the JavaScript implementation by Neil Fraser.
* Ported to Lua by Duncan Cross.
*
* 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.
--]]
--[[
-- Lua 5.1 and earlier requires the external BitOp library.
-- This library is built-in from Lua 5.2 and later as 'bit32'.
require 'bit' -- <http://bitop.luajit.org/>
local band, bor, lshift
= bit.band, bit.bor, bit.lshift
--]]
local band, bor, lshift
= bit32.band, bit32.bor, bit32.lshift
local type, setmetatable, ipairs, select
= type, setmetatable, ipairs, select
local unpack, tonumber, error
= unpack, tonumber, error
local strsub, strbyte, strchar, gmatch, gsub
= string.sub, string.byte, string.char, string.gmatch, string.gsub
local strmatch, strfind, strformat
= string.match, string.find, string.format
local tinsert, tremove, tconcat
= table.insert, table.remove, table.concat
local max, min, floor, ceil, abs
= math.max, math.min, math.floor, math.ceil, math.abs
local clock = os.clock
-- Utility functions.
local percentEncode_pattern = '[^A-Za-z0-9%-=;\',./~!@#$%&*%(%)_%+ %?]'
local function percentEncode_replace(v)
return strformat('%%%02X', strbyte(v))
end
local function tsplice(t, idx, deletions, ...)
local insertions = select('#', ...)
for i = 1, deletions do
tremove(t, idx)
end
for i = insertions, 1, -1 do
-- do not remove parentheses around select
tinsert(t, idx, (select(i, ...)))
end
end
local function strelement(str, i)
return strsub(str, i, i)
end
local function indexOf(a, b, start)
if (#b == 0) then
return nil
end
return strfind(a, b, start, true)
end
local htmlEncode_pattern = '[&<>\n]'
local htmlEncode_replace = {
['&'] = '&', ['<'] = '<', ['>'] = '>', ['\n'] = '¶<br>'
}
-- Public API Functions
-- (Exported at the end of the script)
local diff_main,
diff_cleanupSemantic,
diff_cleanupEfficiency,
diff_levenshtein,
diff_prettyHtml
local match_main
local patch_make,
patch_toText,
patch_fromText,
patch_apply
--[[
* The data structure representing a diff is an array of tuples:
* {{DIFF_DELETE, 'Hello'}, {DIFF_INSERT, 'Goodbye'}, {DIFF_EQUAL, ' world.'}}
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
--]]
local DIFF_DELETE = -1
local DIFF_INSERT = 1
local DIFF_EQUAL = 0
-- Number of seconds to map a diff before giving up (0 for infinity).
local Diff_Timeout = 1.0
-- Cost of an empty edit operation in terms of edit characters.
local Diff_EditCost = 4
-- At what point is no match declared (0.0 = perfection, 1.0 = very loose).
local Match_Threshold = 0.5
-- How far to search for a match (0 = exact location, 1000+ = broad match).
-- A match this many characters away from the expected location will add
-- 1.0 to the score (0.0 is a perfect match).
local Match_Distance = 1000
-- When deleting a large block of text (over ~64 characters), how close do
-- the contents have to be to match the expected contents. (0.0 = perfection,
-- 1.0 = very loose). Note that Match_Threshold controls how closely the
-- end points of a delete need to match.
local Patch_DeleteThreshold = 0.5
-- Chunk size for context length.
local Patch_Margin = 4
-- The number of bits in an int.
local Match_MaxBits = 32
function settings(new)
if new then
Diff_Timeout = new.Diff_Timeout or Diff_Timeout
Diff_EditCost = new.Diff_EditCost or Diff_EditCost
Match_Threshold = new.Match_Threshold or Match_Threshold
Match_Distance = new.Match_Distance or Match_Distance
Patch_DeleteThreshold = new.Patch_DeleteThreshold or Patch_DeleteThreshold
Patch_Margin = new.Patch_Margin or Patch_Margin
Match_MaxBits = new.Match_MaxBits or Match_MaxBits
else
return {
Diff_Timeout = Diff_Timeout;
Diff_EditCost = Diff_EditCost;
Match_Threshold = Match_Threshold;
Match_Distance = Match_Distance;
Patch_DeleteThreshold = Patch_DeleteThreshold;
Patch_Margin = Patch_Margin;
Match_MaxBits = Match_MaxBits;
}
end
end
-- ---------------------------------------------------------------------------
-- DIFF API
-- ---------------------------------------------------------------------------
-- The private diff functions
local _diff_compute,
_diff_bisect,
_diff_halfMatchI,
_diff_halfMatch,
_diff_cleanupSemanticScore,
_diff_cleanupSemanticLossless,
_diff_cleanupMerge,
_diff_commonPrefix,
_diff_commonSuffix,
_diff_commonOverlap,
_diff_xIndex,
_diff_text1,
_diff_text2,
_diff_toDelta,
_diff_fromDelta
--[[
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} opt_checklines Has no effect in Lua.
* @param {number} opt_deadline Optional time when the diff should be complete
* by. Used internally for recursive calls. Users should set DiffTimeout
* instead.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
--]]
function diff_main(text1, text2, opt_checklines, opt_deadline)
-- Set a deadline by which time the diff must be complete.
if opt_deadline == nil then
if Diff_Timeout <= 0 then
opt_deadline = 2 ^ 31
else
opt_deadline = clock() + Diff_Timeout
end
end
local deadline = opt_deadline
-- Check for null inputs.
if text1 == nil or text1 == nil then
error('Null inputs. (diff_main)')
end
-- Check for equality (speedup).
if text1 == text2 then
if #text1 > 0 then
return {{DIFF_EQUAL, text1}}
end
return {}
end
-- LUANOTE: Due to the lack of Unicode support, Lua is incapable of
-- implementing the line-mode speedup.
local checklines = false
-- Trim off common prefix (speedup).
local commonlength = _diff_commonPrefix(text1, text2)
local commonprefix
if commonlength > 0 then
commonprefix = strsub(text1, 1, commonlength)
text1 = strsub(text1, commonlength + 1)
text2 = strsub(text2, commonlength + 1)
end
-- Trim off common suffix (speedup).
commonlength = _diff_commonSuffix(text1, text2)
local commonsuffix
if commonlength > 0 then
commonsuffix = strsub(text1, -commonlength)
text1 = strsub(text1, 1, -commonlength - 1)
text2 = strsub(text2, 1, -commonlength - 1)
end
-- Compute the diff on the middle block.
local diffs = _diff_compute(text1, text2, checklines, deadline)
-- Restore the prefix and suffix.
if commonprefix then
tinsert(diffs, 1, {DIFF_EQUAL, commonprefix})
end
if commonsuffix then
diffs[#diffs + 1] = {DIFF_EQUAL, commonsuffix}
end
_diff_cleanupMerge(diffs)
return diffs
end
--[[
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function diff_cleanupSemantic(diffs)
local changes = false
local equalities = {} -- Stack of indices where equalities are found.
local equalitiesLength = 0 -- Keeping our own length var is faster.
local lastequality = nil
-- Always equal to diffs[equalities[equalitiesLength]][2]
local pointer = 1 -- Index of current position.
-- Number of characters that changed prior to the equality.
local length_insertions1 = 0
local length_deletions1 = 0
-- Number of characters that changed after the equality.
local length_insertions2 = 0
local length_deletions2 = 0
while diffs[pointer] do
if diffs[pointer][1] == DIFF_EQUAL then -- Equality found.
equalitiesLength = equalitiesLength + 1
equalities[equalitiesLength] = pointer
length_insertions1 = length_insertions2
length_deletions1 = length_deletions2
length_insertions2 = 0
length_deletions2 = 0
lastequality = diffs[pointer][2]
else -- An insertion or deletion.
if diffs[pointer][1] == DIFF_INSERT then
length_insertions2 = length_insertions2 + #(diffs[pointer][2])
else
length_deletions2 = length_deletions2 + #(diffs[pointer][2])
end
-- Eliminate an equality that is smaller or equal to the edits on both
-- sides of it.
if lastequality
and (#lastequality <= max(length_insertions1, length_deletions1))
and (#lastequality <= max(length_insertions2, length_deletions2)) then
-- Duplicate record.
tinsert(diffs, equalities[equalitiesLength],
{DIFF_DELETE, lastequality})
-- Change second copy to insert.
diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT
-- Throw away the equality we just deleted.
equalitiesLength = equalitiesLength - 1
-- Throw away the previous equality (it needs to be reevaluated).
equalitiesLength = equalitiesLength - 1
pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0
length_insertions1, length_deletions1 = 0, 0 -- Reset the counters.
length_insertions2, length_deletions2 = 0, 0
lastequality = nil
changes = true
end
end
pointer = pointer + 1
end
-- Normalize the diff.
if changes then
_diff_cleanupMerge(diffs)
end
_diff_cleanupSemanticLossless(diffs)
-- Find any overlaps between deletions and insertions.
-- e.g: <del>abcxxx</del><ins>xxxdef</ins>
-- -> <del>abc</del>xxx<ins>def</ins>
-- e.g: <del>xxxabc</del><ins>defxxx</ins>
-- -> <ins>def</ins>xxx<del>abc</del>
-- Only extract an overlap if it is as big as the edit ahead or behind it.
pointer = 2
while diffs[pointer] do
if (diffs[pointer - 1][1] == DIFF_DELETE and
diffs[pointer][1] == DIFF_INSERT) then
local deletion = diffs[pointer - 1][2]
local insertion = diffs[pointer][2]
local overlap_length1 = _diff_commonOverlap(deletion, insertion)
local overlap_length2 = _diff_commonOverlap(insertion, deletion)
if (overlap_length1 >= overlap_length2) then
if (overlap_length1 >= #deletion / 2 or
overlap_length1 >= #insertion / 2) then
-- Overlap found. Insert an equality and trim the surrounding edits.
tinsert(diffs, pointer,
{DIFF_EQUAL, strsub(insertion, 1, overlap_length1)})
diffs[pointer - 1][2] =
strsub(deletion, 1, #deletion - overlap_length1)
diffs[pointer + 1][2] = strsub(insertion, overlap_length1 + 1)
pointer = pointer + 1
end
else
if (overlap_length2 >= #deletion / 2 or
overlap_length2 >= #insertion / 2) then
-- Reverse overlap found.
-- Insert an equality and swap and trim the surrounding edits.
tinsert(diffs, pointer,
{DIFF_EQUAL, strsub(deletion, 1, overlap_length2)})
diffs[pointer - 1] = {DIFF_INSERT,
strsub(insertion, 1, #insertion - overlap_length2)}
diffs[pointer + 1] = {DIFF_DELETE,
strsub(deletion, overlap_length2 + 1)}
pointer = pointer + 1
end
end
pointer = pointer + 1
end
pointer = pointer + 1
end
end
--[[
* Reduce the number of edits by eliminating operationally trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function diff_cleanupEfficiency(diffs)
local changes = false
-- Stack of indices where equalities are found.
local equalities = {}
-- Keeping our own length var is faster.
local equalitiesLength = 0
-- Always equal to diffs[equalities[equalitiesLength]][2]
local lastequality = nil
-- Index of current position.
local pointer = 1
-- The following four are really booleans but are stored as numbers because
-- they are used at one point like this:
--
-- (pre_ins + pre_del + post_ins + post_del) == 3
--
-- ...i.e. checking that 3 of them are true and 1 of them is false.
-- Is there an insertion operation before the last equality.
local pre_ins = 0
-- Is there a deletion operation before the last equality.
local pre_del = 0
-- Is there an insertion operation after the last equality.
local post_ins = 0
-- Is there a deletion operation after the last equality.
local post_del = 0
while diffs[pointer] do
if diffs[pointer][1] == DIFF_EQUAL then -- Equality found.
local diffText = diffs[pointer][2]
if (#diffText < Diff_EditCost) and (post_ins == 1 or post_del == 1) then
-- Candidate found.
equalitiesLength = equalitiesLength + 1
equalities[equalitiesLength] = pointer
pre_ins, pre_del = post_ins, post_del
lastequality = diffText
else
-- Not a candidate, and can never become one.
equalitiesLength = 0
lastequality = nil
end
post_ins, post_del = 0, 0
else -- An insertion or deletion.
if diffs[pointer][1] == DIFF_DELETE then
post_del = 1
else
post_ins = 1
end
--[[
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
--]]
if lastequality and (
(pre_ins+pre_del+post_ins+post_del == 4)
or
(
(#lastequality < Diff_EditCost / 2)
and
(pre_ins+pre_del+post_ins+post_del == 3)
)) then
-- Duplicate record.
tinsert(diffs, equalities[equalitiesLength],
{DIFF_DELETE, lastequality})
-- Change second copy to insert.
diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT
-- Throw away the equality we just deleted.
equalitiesLength = equalitiesLength - 1
lastequality = nil
if (pre_ins == 1) and (pre_del == 1) then
-- No changes made which could affect previous entry, keep going.
post_ins, post_del = 1, 1
equalitiesLength = 0
else
-- Throw away the previous equality.
equalitiesLength = equalitiesLength - 1
pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0
post_ins, post_del = 0, 0
end
changes = true
end
end
pointer = pointer + 1
end
if changes then
_diff_cleanupMerge(diffs)
end
end
--[[
* Compute the Levenshtein distance; the number of inserted, deleted or
* substituted characters.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {number} Number of changes.
--]]
function diff_levenshtein(diffs)
local levenshtein = 0
local insertions, deletions = 0, 0
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if (op == DIFF_INSERT) then
insertions = insertions + #data
elseif (op == DIFF_DELETE) then
deletions = deletions + #data
elseif (op == DIFF_EQUAL) then
-- A deletion and an insertion is one substitution.
levenshtein = levenshtein + max(insertions, deletions)
insertions = 0
deletions = 0
end
end
levenshtein = levenshtein + max(insertions, deletions)
return levenshtein
end
--[[
* Convert a diff array into a pretty HTML report.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} HTML representation.
--]]
function diff_prettyHtml(diffs)
local html = {}
for x, diff in ipairs(diffs) do
local op = diff[1] -- Operation (insert, delete, equal)
local data = diff[2] -- Text of change.
local text = gsub(data, htmlEncode_pattern, htmlEncode_replace)
if op == DIFF_INSERT then
html[x] = '<ins style="background:#e6ffe6;">' .. text .. '</ins>'
elseif op == DIFF_DELETE then
html[x] = '<del style="background:#ffe6e6;">' .. text .. '</del>'
elseif op == DIFF_EQUAL then
html[x] = '<span>' .. text .. '</span>'
end
end
return tconcat(html)
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE DIFF FUNCTIONS
-- ---------------------------------------------------------------------------
--[[
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} checklines Has no effect in Lua.
* @param {number} deadline Time when the diff should be complete by.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_compute(text1, text2, checklines, deadline)
if #text1 == 0 then
-- Just add some text (speedup).
return {{DIFF_INSERT, text2}}
end
if #text2 == 0 then
-- Just delete some text (speedup).
return {{DIFF_DELETE, text1}}
end
local diffs
local longtext = (#text1 > #text2) and text1 or text2
local shorttext = (#text1 > #text2) and text2 or text1
local i = indexOf(longtext, shorttext)
if i ~= nil then
-- Shorter text is inside the longer text (speedup).
diffs = {
{DIFF_INSERT, strsub(longtext, 1, i - 1)},
{DIFF_EQUAL, shorttext},
{DIFF_INSERT, strsub(longtext, i + #shorttext)}
}
-- Swap insertions for deletions if diff is reversed.
if #text1 > #text2 then
diffs[1][1], diffs[3][1] = DIFF_DELETE, DIFF_DELETE
end
return diffs
end
if #shorttext == 1 then
-- Single character string.
-- After the previous speedup, the character can't be an equality.
return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}}
end
-- Check to see if the problem can be split in two.
do
local
text1_a, text1_b,
text2_a, text2_b,
mid_common = _diff_halfMatch(text1, text2)
if text1_a then
-- A half-match was found, sort out the return data.
-- Send both pairs off for separate processing.
local diffs_a = diff_main(text1_a, text2_a, checklines, deadline)
local diffs_b = diff_main(text1_b, text2_b, checklines, deadline)
-- Merge the results.
local diffs_a_len = #diffs_a
diffs = diffs_a
diffs[diffs_a_len + 1] = {DIFF_EQUAL, mid_common}
for i, b_diff in ipairs(diffs_b) do
diffs[diffs_a_len + 1 + i] = b_diff
end
return diffs
end
end
return _diff_bisect(text1, text2, deadline)
end
--[[
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_bisect(text1, text2, deadline)
-- Cache the text lengths to prevent multiple calls.
local text1_length = #text1
local text2_length = #text2
local _sub, _element
local max_d = ceil((text1_length + text2_length) / 2)
local v_offset = max_d
local v_length = 2 * max_d
local v1 = {}
local v2 = {}
-- Setting all elements to -1 is faster in Lua than mixing integers and nil.
for x = 0, v_length - 1 do
v1[x] = -1
v2[x] = -1
end
v1[v_offset + 1] = 0
v2[v_offset + 1] = 0
local delta = text1_length - text2_length
-- If the total number of characters is odd, then
-- the front path will collide with the reverse path.
local front = (delta % 2 ~= 0)
-- Offsets for start and end of k loop.
-- Prevents mapping of space beyond the grid.
local k1start = 0
local k1end = 0
local k2start = 0
local k2end = 0
for d = 0, max_d - 1 do
-- Bail out if deadline is reached.
if clock() > deadline then
break
end
-- Walk the front path one step.
for k1 = -d + k1start, d - k1end, 2 do
local k1_offset = v_offset + k1
local x1
if (k1 == -d) or ((k1 ~= d) and
(v1[k1_offset - 1] < v1[k1_offset + 1])) then
x1 = v1[k1_offset + 1]
else
x1 = v1[k1_offset - 1] + 1
end
local y1 = x1 - k1
while (x1 <= text1_length) and (y1 <= text2_length)
and (strelement(text1, x1) == strelement(text2, y1)) do
x1 = x1 + 1
y1 = y1 + 1
end
v1[k1_offset] = x1
if x1 > text1_length + 1 then
-- Ran off the right of the graph.
k1end = k1end + 2
elseif y1 > text2_length + 1 then
-- Ran off the bottom of the graph.
k1start = k1start + 2
elseif front then
local k2_offset = v_offset + delta - k1
if k2_offset >= 0 and k2_offset < v_length and v2[k2_offset] ~= -1 then
-- Mirror x2 onto top-left coordinate system.
local x2 = text1_length - v2[k2_offset] + 1
if x1 > x2 then
-- Overlap detected.
return _diff_bisectSplit(text1, text2, x1, y1, deadline)
end
end
end
end
-- Walk the reverse path one step.
for k2 = -d + k2start, d - k2end, 2 do
local k2_offset = v_offset + k2
local x2
if (k2 == -d) or ((k2 ~= d) and
(v2[k2_offset - 1] < v2[k2_offset + 1])) then
x2 = v2[k2_offset + 1]
else
x2 = v2[k2_offset - 1] + 1
end
local y2 = x2 - k2
while (x2 <= text1_length) and (y2 <= text2_length)
and (strelement(text1, -x2) == strelement(text2, -y2)) do
x2 = x2 + 1
y2 = y2 + 1
end
v2[k2_offset] = x2
if x2 > text1_length + 1 then
-- Ran off the left of the graph.
k2end = k2end + 2
elseif y2 > text2_length + 1 then
-- Ran off the top of the graph.
k2start = k2start + 2
elseif not front then
local k1_offset = v_offset + delta - k2
if k1_offset >= 0 and k1_offset < v_length and v1[k1_offset] ~= -1 then
local x1 = v1[k1_offset]
local y1 = v_offset + x1 - k1_offset
-- Mirror x2 onto top-left coordinate system.
x2 = text1_length - x2 + 1
if x1 > x2 then
-- Overlap detected.
return _diff_bisectSplit(text1, text2, x1, y1, deadline)
end
end
end
end
end
-- Diff took too long and hit the deadline or
-- number of diffs equals number of characters, no commonality at all.
return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}}
end
--[[
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} x Index of split point in text1.
* @param {number} y Index of split point in text2.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_bisectSplit(text1, text2, x, y, deadline)
local text1a = strsub(text1, 1, x - 1)
local text2a = strsub(text2, 1, y - 1)
local text1b = strsub(text1, x)
local text2b = strsub(text2, y)
-- Compute both diffs serially.
local diffs = diff_main(text1a, text2a, false, deadline)
local diffsb = diff_main(text1b, text2b, false, deadline)
local diffs_len = #diffs
for i, v in ipairs(diffsb) do
diffs[diffs_len + i] = v
end
return diffs
end
--[[
* Determine the common prefix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
--]]
function _diff_commonPrefix(text1, text2)
-- Quick check for common null cases.
if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, 1) ~= strbyte(text2, 1))
then
return 0
end
-- Binary search.
-- Performance analysis: http://neil.fraser.name/news/2007/10/09/
local pointermin = 1
local pointermax = min(#text1, #text2)
local pointermid = pointermax
local pointerstart = 1
while (pointermin < pointermid) do
if (strsub(text1, pointerstart, pointermid)
== strsub(text2, pointerstart, pointermid)) then
pointermin = pointermid
pointerstart = pointermin
else
pointermax = pointermid
end
pointermid = floor(pointermin + (pointermax - pointermin) / 2)
end
return pointermid
end
--[[
* Determine the common suffix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
--]]
function _diff_commonSuffix(text1, text2)
-- Quick check for common null cases.
if (#text1 == 0) or (#text2 == 0)
or (strbyte(text1, -1) ~= strbyte(text2, -1)) then
return 0
end
-- Binary search.
-- Performance analysis: http://neil.fraser.name/news/2007/10/09/
local pointermin = 1
local pointermax = min(#text1, #text2)
local pointermid = pointermax
local pointerend = 1
while (pointermin < pointermid) do
if (strsub(text1, -pointermid, -pointerend)
== strsub(text2, -pointermid, -pointerend)) then
pointermin = pointermid
pointerend = pointermin
else
pointermax = pointermid
end
pointermid = floor(pointermin + (pointermax - pointermin) / 2)
end
return pointermid
end
--[[
* Determine if the suffix of one string is the prefix of another.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of the first
* string and the start of the second string.
* @private
--]]
function _diff_commonOverlap(text1, text2)
-- Cache the text lengths to prevent multiple calls.
local text1_length = #text1
local text2_length = #text2
-- Eliminate the null case.
if text1_length == 0 or text2_length == 0 then
return 0
end
-- Truncate the longer string.
if text1_length > text2_length then
text1 = strsub(text1, text1_length - text2_length + 1)
elseif text1_length < text2_length then
text2 = strsub(text2, 1, text1_length)
end
local text_length = min(text1_length, text2_length)
-- Quick check for the worst case.
if text1 == text2 then
return text_length
end
-- Start by looking for a single character match
-- and increase length until no match is found.
-- Performance analysis: http://neil.fraser.name/news/2010/11/04/
local best = 0
local length = 1
while true do
local pattern = strsub(text1, text_length - length + 1)
local found = strfind(text2, pattern, 1, true)
if found == nil then
return best
end
length = length + found - 1
if found == 1 or strsub(text1, text_length - length + 1) ==
strsub(text2, 1, length) then
best = length
length = length + 1
end
end
end
--[[
* Does a substring of shorttext exist within longtext such that the substring
* is at least half the length of longtext?
* This speedup can produce non-minimal diffs.
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length substring within longtext.
* @return {?Array.<string>} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or nil if there was no match.
* @private
--]]
function _diff_halfMatchI(longtext, shorttext, i)
-- Start with a 1/4 length substring at position i as a seed.
local seed = strsub(longtext, i, i + floor(#longtext / 4))
local j = 0 -- LUANOTE: do not change to 1, was originally -1
local best_common = ''
local best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b
while true do
j = indexOf(shorttext, seed, j + 1)
if (j == nil) then
break
end
local prefixLength = _diff_commonPrefix(strsub(longtext, i),
strsub(shorttext, j))
local suffixLength = _diff_commonSuffix(strsub(longtext, 1, i - 1),
strsub(shorttext, 1, j - 1))
if #best_common < suffixLength + prefixLength then
best_common = strsub(shorttext, j - suffixLength, j - 1)
.. strsub(shorttext, j, j + prefixLength - 1)
best_longtext_a = strsub(longtext, 1, i - suffixLength - 1)
best_longtext_b = strsub(longtext, i + prefixLength)
best_shorttext_a = strsub(shorttext, 1, j - suffixLength - 1)
best_shorttext_b = strsub(shorttext, j + prefixLength)
end
end
if #best_common * 2 >= #longtext then
return {best_longtext_a, best_longtext_b,
best_shorttext_a, best_shorttext_b, best_common}
else
return nil
end
end
--[[
* Do the two texts share a substring which is at least half the length of the
* longer text?
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {?Array.<string>} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or nil if there was no match.
* @private
--]]
function _diff_halfMatch(text1, text2)
if Diff_Timeout <= 0 then
-- Don't risk returning a non-optimal diff if we have unlimited time.
return nil
end
local longtext = (#text1 > #text2) and text1 or text2
local shorttext = (#text1 > #text2) and text2 or text1
if (#longtext < 4) or (#shorttext * 2 < #longtext) then
return nil -- Pointless.
end
-- First check if the second quarter is the seed for a half-match.
local hm1 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 4))
-- Check again based on the third quarter.
local hm2 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 2))
local hm
if not hm1 and not hm2 then
return nil
elseif not hm2 then
hm = hm1
elseif not hm1 then
hm = hm2
else
-- Both matched. Select the longest.
hm = (#hm1[5] > #hm2[5]) and hm1 or hm2
end
-- A half-match was found, sort out the return data.
local text1_a, text1_b, text2_a, text2_b
if (#text1 > #text2) then
text1_a, text1_b = hm[1], hm[2]
text2_a, text2_b = hm[3], hm[4]
else
text2_a, text2_b = hm[1], hm[2]
text1_a, text1_b = hm[3], hm[4]
end
local mid_common = hm[5]
return text1_a, text1_b, text2_a, text2_b, mid_common
end
--[[
* Given two strings, compute a score representing whether the internal
* boundary falls on logical boundaries.
* Scores range from 6 (best) to 0 (worst).
* @param {string} one First string.
* @param {string} two Second string.
* @return {number} The score.
* @private
--]]
function _diff_cleanupSemanticScore(one, two)
if (#one == 0) or (#two == 0) then
-- Edges are the best.
return 6
end
-- Each port of this function behaves slightly differently due to
-- subtle differences in each language's definition of things like
-- 'whitespace'. Since this function's purpose is largely cosmetic,
-- the choice has been made to use each language's native features
-- rather than force total conformity.
local char1 = strsub(one, -1)
local char2 = strsub(two, 1, 1)
local nonAlphaNumeric1 = strmatch(char1, '%W')
local nonAlphaNumeric2 = strmatch(char2, '%W')
local whitespace1 = nonAlphaNumeric1 and strmatch(char1, '%s')
local whitespace2 = nonAlphaNumeric2 and strmatch(char2, '%s')
local lineBreak1 = whitespace1 and strmatch(char1, '%c')
local lineBreak2 = whitespace2 and strmatch(char2, '%c')
local blankLine1 = lineBreak1 and strmatch(one, '\n\r?\n$')
local blankLine2 = lineBreak2 and strmatch(two, '^\r?\n\r?\n')
if blankLine1 or blankLine2 then
-- Five points for blank lines.
return 5
elseif lineBreak1 or lineBreak2 then
-- Four points for line breaks.
return 4
elseif nonAlphaNumeric1 and not whitespace1 and whitespace2 then
-- Three points for end of sentences.
return 3
elseif whitespace1 or whitespace2 then
-- Two points for whitespace.
return 2
elseif nonAlphaNumeric1 or nonAlphaNumeric2 then
-- One point for non-alphanumeric.
return 1
end
return 0
end
--[[
* Look for single edits surrounded on both sides by equalities
* which can be shifted sideways to align the edit to a word boundary.
* e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function _diff_cleanupSemanticLossless(diffs)
local pointer = 2
-- Intentionally ignore the first and last element (don't need checking).
while diffs[pointer + 1] do
local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1]
if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then
-- This is a single edit surrounded by equalities.
local diff = diffs[pointer]
local equality1 = prevDiff[2]
local edit = diff[2]
local equality2 = nextDiff[2]
-- First, shift the edit as far left as possible.
local commonOffset = _diff_commonSuffix(equality1, edit)
if commonOffset > 0 then
local commonString = strsub(edit, -commonOffset)
equality1 = strsub(equality1, 1, -commonOffset - 1)
edit = commonString .. strsub(edit, 1, -commonOffset - 1)
equality2 = commonString .. equality2
end
-- Second, step character by character right, looking for the best fit.
local bestEquality1 = equality1
local bestEdit = edit
local bestEquality2 = equality2
local bestScore = _diff_cleanupSemanticScore(equality1, edit)
+ _diff_cleanupSemanticScore(edit, equality2)
while strbyte(edit, 1) == strbyte(equality2, 1) do
equality1 = equality1 .. strsub(edit, 1, 1)
edit = strsub(edit, 2) .. strsub(equality2, 1, 1)
equality2 = strsub(equality2, 2)
local score = _diff_cleanupSemanticScore(equality1, edit)
+ _diff_cleanupSemanticScore(edit, equality2)
-- The >= encourages trailing rather than leading whitespace on edits.
if score >= bestScore then
bestScore = score
bestEquality1 = equality1
bestEdit = edit
bestEquality2 = equality2
end
end
if prevDiff[2] ~= bestEquality1 then
-- We have an improvement, save it back to the diff.
if #bestEquality1 > 0 then
diffs[pointer - 1][2] = bestEquality1
else
tremove(diffs, pointer - 1)
pointer = pointer - 1
end
diffs[pointer][2] = bestEdit
if #bestEquality2 > 0 then
diffs[pointer + 1][2] = bestEquality2
else
tremove(diffs, pointer + 1, 1)
pointer = pointer - 1
end
end
end
pointer = pointer + 1
end
end
--[[
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function _diff_cleanupMerge(diffs)
diffs[#diffs + 1] = {DIFF_EQUAL, ''} -- Add a dummy entry at the end.
local pointer = 1
local count_delete, count_insert = 0, 0
local text_delete, text_insert = '', ''
local commonlength
while diffs[pointer] do
local diff_type = diffs[pointer][1]
if diff_type == DIFF_INSERT then
count_insert = count_insert + 1
text_insert = text_insert .. diffs[pointer][2]
pointer = pointer + 1
elseif diff_type == DIFF_DELETE then
count_delete = count_delete + 1
text_delete = text_delete .. diffs[pointer][2]
pointer = pointer + 1
elseif diff_type == DIFF_EQUAL then
-- Upon reaching an equality, check for prior redundancies.
if count_delete + count_insert > 1 then
if (count_delete > 0) and (count_insert > 0) then
-- Factor out any common prefixies.
commonlength = _diff_commonPrefix(text_insert, text_delete)
if commonlength > 0 then
local back_pointer = pointer - count_delete - count_insert
if (back_pointer > 1) and (diffs[back_pointer - 1][1] == DIFF_EQUAL)
then
diffs[back_pointer - 1][2] = diffs[back_pointer - 1][2]
.. strsub(text_insert, 1, commonlength)
else
tinsert(diffs, 1,
{DIFF_EQUAL, strsub(text_insert, 1, commonlength)})
pointer = pointer + 1
end
text_insert = strsub(text_insert, commonlength + 1)
text_delete = strsub(text_delete, commonlength + 1)
end
-- Factor out any common suffixies.
commonlength = _diff_commonSuffix(text_insert, text_delete)
if commonlength ~= 0 then
diffs[pointer][2] =
strsub(text_insert, -commonlength) .. diffs[pointer][2]
text_insert = strsub(text_insert, 1, -commonlength - 1)
text_delete = strsub(text_delete, 1, -commonlength - 1)
end
end
-- Delete the offending records and add the merged ones.
if count_delete == 0 then
tsplice(diffs, pointer - count_insert,
count_insert, {DIFF_INSERT, text_insert})
elseif count_insert == 0 then
tsplice(diffs, pointer - count_delete,
count_delete, {DIFF_DELETE, text_delete})
else
tsplice(diffs, pointer - count_delete - count_insert,
count_delete + count_insert,
{DIFF_DELETE, text_delete}, {DIFF_INSERT, text_insert})
end
pointer = pointer - count_delete - count_insert
+ (count_delete>0 and 1 or 0) + (count_insert>0 and 1 or 0) + 1
elseif (pointer > 1) and (diffs[pointer - 1][1] == DIFF_EQUAL) then
-- Merge this equality with the previous one.
diffs[pointer - 1][2] = diffs[pointer - 1][2] .. diffs[pointer][2]
tremove(diffs, pointer)
else
pointer = pointer + 1
end
count_insert, count_delete = 0, 0
text_delete, text_insert = '', ''
end
end
if diffs[#diffs][2] == '' then
diffs[#diffs] = nil -- Remove the dummy entry at the end.
end
-- Second pass: look for single edits surrounded on both sides by equalities
-- which can be shifted sideways to eliminate an equality.
-- e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
local changes = false
pointer = 2
-- Intentionally ignore the first and last element (don't need checking).
while pointer < #diffs do
local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1]
if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then
-- This is a single edit surrounded by equalities.
local diff = diffs[pointer]
local currentText = diff[2]
local prevText = prevDiff[2]
local nextText = nextDiff[2]
if strsub(currentText, -#prevText) == prevText then
-- Shift the edit over the previous equality.
diff[2] = prevText .. strsub(currentText, 1, -#prevText - 1)
nextDiff[2] = prevText .. nextDiff[2]
tremove(diffs, pointer - 1)
changes = true
elseif strsub(currentText, 1, #nextText) == nextText then
-- Shift the edit over the next equality.
prevDiff[2] = prevText .. nextText
diff[2] = strsub(currentText, #nextText + 1) .. nextText
tremove(diffs, pointer + 1)
changes = true
end
end
pointer = pointer + 1
end
-- If shifts were made, the diff needs reordering and another shift sweep.
if changes then
-- LUANOTE: no return value, but necessary to use 'return' to get
-- tail calls.
return _diff_cleanupMerge(diffs)
end
end
--[[
* loc is a location in text1, compute and return the equivalent location in
* text2.
* e.g. 'The cat' vs 'The big cat', 1->1, 5->8
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @param {number} loc Location within text1.
* @return {number} Location within text2.
--]]
function _diff_xIndex(diffs, loc)
local chars1 = 1
local chars2 = 1
local last_chars1 = 1
local last_chars2 = 1
local x
for _x, diff in ipairs(diffs) do
x = _x
if diff[1] ~= DIFF_INSERT then -- Equality or deletion.
chars1 = chars1 + #diff[2]
end
if diff[1] ~= DIFF_DELETE then -- Equality or insertion.
chars2 = chars2 + #diff[2]
end
if chars1 > loc then -- Overshot the location.
break
end
last_chars1 = chars1
last_chars2 = chars2
end
-- Was the location deleted?
if diffs[x + 1] and (diffs[x][1] == DIFF_DELETE) then
return last_chars2
end
-- Add the remaining character length.
return last_chars2 + (loc - last_chars1)
end
--[[
* Compute and return the source text (all equalities and deletions).
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Source text.
--]]
function _diff_text1(diffs)
local text = {}
for x, diff in ipairs(diffs) do
if diff[1] ~= DIFF_INSERT then
text[#text + 1] = diff[2]
end
end
return tconcat(text)
end
--[[
* Compute and return the destination text (all equalities and insertions).
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Destination text.
--]]
function _diff_text2(diffs)
local text = {}
for x, diff in ipairs(diffs) do
if diff[1] ~= DIFF_DELETE then
text[#text + 1] = diff[2]
end
end
return tconcat(text)
end
--[[
* Crush the diff into an encoded string which describes the operations
* required to transform text1 into text2.
* E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
* Operations are tab-separated. Inserted text is escaped using %xx notation.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Delta text.
--]]
function _diff_toDelta(diffs)
local text = {}
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if op == DIFF_INSERT then
text[x] = '+' .. gsub(data, percentEncode_pattern, percentEncode_replace)
elseif op == DIFF_DELETE then
text[x] = '-' .. #data
elseif op == DIFF_EQUAL then
text[x] = '=' .. #data
end
end
return tconcat(text, '\t')
end
--[[
* Given the original text1, and an encoded string which describes the
* operations required to transform text1 into text2, compute the full diff.
* @param {string} text1 Source string for the diff.
* @param {string} delta Delta text.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @throws {Errorend If invalid input.
--]]
function _diff_fromDelta(text1, delta)
local diffs = {}
local diffsLength = 0 -- Keeping our own length var is faster
local pointer = 1 -- Cursor in text1
for token in gmatch(delta, '[^\t]+') do
-- Each token begins with a one character parameter which specifies the
-- operation of this token (delete, insert, equality).
local tokenchar, param = strsub(token, 1, 1), strsub(token, 2)
if (tokenchar == '+') then
local invalidDecode = false
local decoded = gsub(param, '%%(.?.?)',
function(c)
local n = tonumber(c, 16)
if (#c ~= 2) or (n == nil) then
invalidDecode = true
return ''
end
return strchar(n)
end)
if invalidDecode then
-- Malformed URI sequence.
error('Illegal escape in _diff_fromDelta: ' .. param)
end
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_INSERT, decoded}
elseif (tokenchar == '-') or (tokenchar == '=') then
local n = tonumber(param)
if (n == nil) or (n < 0) then
error('Invalid number in _diff_fromDelta: ' .. param)
end
local text = strsub(text1, pointer, pointer + n - 1)
pointer = pointer + n
if (tokenchar == '=') then
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_EQUAL, text}
else
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_DELETE, text}
end
else
error('Invalid diff operation in _diff_fromDelta: ' .. token)
end
end
if (pointer ~= #text1 + 1) then
error('Delta length (' .. (pointer - 1)
.. ') does not equal source text length (' .. #text1 .. ').')
end
return diffs
end
-- ---------------------------------------------------------------------------
-- MATCH API
-- ---------------------------------------------------------------------------
local _match_bitap, _match_alphabet
--[[
* Locate the best instance of 'pattern' in 'text' near 'loc'.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
--]]
function match_main(text, pattern, loc)
-- Check for null inputs.
if text == nil or pattern == nil or loc == nil then
error('Null inputs. (match_main)')
end
if text == pattern then
-- Shortcut (potentially not guaranteed by the algorithm)
return 1
elseif #text == 0 then
-- Nothing to match.
return -1
end
loc = max(1, min(loc, #text))
if strsub(text, loc, loc + #pattern - 1) == pattern then
-- Perfect match at the perfect spot! (Includes case of null pattern)
return loc
else
-- Do a fuzzy compare.
return _match_bitap(text, pattern, loc)
end
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE MATCH FUNCTIONS
-- ---------------------------------------------------------------------------
--[[
* Initialise the alphabet for the Bitap algorithm.
* @param {string} pattern The text to encode.
* @return {Object} Hash of character locations.
* @private
--]]
function _match_alphabet(pattern)
local s = {}
local i = 0
for c in gmatch(pattern, '.') do
s[c] = bor(s[c] or 0, lshift(1, #pattern - i - 1))
i = i + 1
end
return s
end
--[[
* Locate the best instance of 'pattern' in 'text' near 'loc' using the
* Bitap algorithm.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
* @private
--]]
function _match_bitap(text, pattern, loc)
if #pattern > Match_MaxBits then
error('Pattern too long.')
end
-- Initialise the alphabet.
local s = _match_alphabet(pattern)
--[[
* Compute and return the score for a match with e errors and x location.
* Accesses loc and pattern through being a closure.
* @param {number} e Number of errors in match.
* @param {number} x Location of match.
* @return {number} Overall score for match (0.0 = good, 1.0 = bad).
* @private
--]]
local function _match_bitapScore(e, x)
local accuracy = e / #pattern
local proximity = abs(loc - x)
if (Match_Distance == 0) then
-- Dodge divide by zero error.
return (proximity == 0) and 1 or accuracy
end
return accuracy + (proximity / Match_Distance)
end
-- Highest score beyond which we give up.
local score_threshold = Match_Threshold
-- Is there a nearby exact match? (speedup)
local best_loc = indexOf(text, pattern, loc)
if best_loc then
score_threshold = min(_match_bitapScore(0, best_loc), score_threshold)
-- LUANOTE: Ideally we'd also check from the other direction, but Lua
-- doesn't have an efficent lastIndexOf function.
end
-- Initialise the bit arrays.
local matchmask = lshift(1, #pattern - 1)
best_loc = -1
local bin_min, bin_mid
local bin_max = #pattern + #text
local last_rd
for d = 0, #pattern - 1, 1 do
-- Scan for the best match; each iteration allows for one more error.
-- Run a binary search to determine how far from 'loc' we can stray at this
-- error level.
bin_min = 0
bin_mid = bin_max
while (bin_min < bin_mid) do
if (_match_bitapScore(d, loc + bin_mid) <= score_threshold) then
bin_min = bin_mid
else
bin_max = bin_mid
end
bin_mid = floor(bin_min + (bin_max - bin_min) / 2)
end
-- Use the result from this iteration as the maximum for the next.
bin_max = bin_mid
local start = max(1, loc - bin_mid + 1)
local finish = min(loc + bin_mid, #text) + #pattern
local rd = {}
for j = start, finish do
rd[j] = 0
end
rd[finish + 1] = lshift(1, d) - 1
for j = finish, start, -1 do
local charMatch = s[strsub(text, j - 1, j - 1)] or 0
if (d == 0) then -- First pass: exact match.
rd[j] = band(bor((rd[j + 1] * 2), 1), charMatch)
else
-- Subsequent passes: fuzzy match.
-- Functions instead of operators make this hella messy.
rd[j] = bor(
band(
bor(
lshift(rd[j + 1], 1),
1
),
charMatch
),
bor(
bor(
lshift(bor(last_rd[j + 1], last_rd[j]), 1),
1
),
last_rd[j + 1]
)
)
end
if (band(rd[j], matchmask) ~= 0) then
local score = _match_bitapScore(d, j - 1)
-- This match will almost certainly be better than any existing match.
-- But check anyway.
if (score <= score_threshold) then
-- Told you so.
score_threshold = score
best_loc = j - 1
if (best_loc > loc) then
-- When passing loc, don't exceed our current distance from loc.
start = max(1, loc * 2 - best_loc)
else
-- Already passed loc, downhill from here on in.
break
end
end
end
end
-- No hope for a (better) match at greater error levels.
if (_match_bitapScore(d + 1, loc) > score_threshold) then
break
end
last_rd = rd
end
return best_loc
end
-- -----------------------------------------------------------------------------
-- PATCH API
-- -----------------------------------------------------------------------------
local _patch_addContext,
_patch_deepCopy,
_patch_addPadding,
_patch_splitMax,
_patch_appendText,
_new_patch_obj
--[[
* Compute a list of patches to turn text1 into text2.
* Use diffs if provided, otherwise compute it ourselves.
* There are four ways to call this function, depending on what data is
* available to the caller:
* Method 1:
* a = text1, b = text2
* Method 2:
* a = diffs
* Method 3 (optimal):
* a = text1, b = diffs
* Method 4 (deprecated, use method 3):
* a = text1, b = text2, c = diffs
*
* @param {string|Array.<Array.<number|string>>} a text1 (methods 1,3,4) or
* Array of diff tuples for text1 to text2 (method 2).
* @param {string|Array.<Array.<number|string>>} opt_b text2 (methods 1,4) or
* Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
* @param {string|Array.<Array.<number|string>>} opt_c Array of diff tuples for
* text1 to text2 (method 4) or undefined (methods 1,2,3).
* @return {Array.<_new_patch_obj>} Array of patch objects.
--]]
function patch_make(a, opt_b, opt_c)
local text1, diffs
local type_a, type_b, type_c = type(a), type(opt_b), type(opt_c)
if (type_a == 'string') and (type_b == 'string') and (type_c == 'nil') then
-- Method 1: text1, text2
-- Compute diffs from text1 and text2.
text1 = a
diffs = diff_main(text1, opt_b, true)
if (#diffs > 2) then
diff_cleanupSemantic(diffs)
diff_cleanupEfficiency(diffs)
end
elseif (type_a == 'table') and (type_b == 'nil') and (type_c == 'nil') then
-- Method 2: diffs
-- Compute text1 from diffs.
diffs = a
text1 = _diff_text1(diffs)
elseif (type_a == 'string') and (type_b == 'table') and (type_c == 'nil') then
-- Method 3: text1, diffs
text1 = a
diffs = opt_b
elseif (type_a == 'string') and (type_b == 'string') and (type_c == 'table')
then
-- Method 4: text1, text2, diffs
-- text2 is not used.
text1 = a
diffs = opt_c
else
error('Unknown call format to patch_make.')
end
if (diffs[1] == nil) then
return {} -- Get rid of the null case.
end
local patches = {}
local patch = _new_patch_obj()
local patchDiffLength = 0 -- Keeping our own length var is faster.
local char_count1 = 0 -- Number of characters into the text1 string.
local char_count2 = 0 -- Number of characters into the text2 string.
-- Start with text1 (prepatch_text) and apply the diffs until we arrive at
-- text2 (postpatch_text). We recreate the patches one by one to determine
-- context info.
local prepatch_text, postpatch_text = text1, text1
for x, diff in ipairs(diffs) do
local diff_type, diff_text = diff[1], diff[2]
if (patchDiffLength == 0) and (diff_type ~= DIFF_EQUAL) then
-- A new patch starts here.
patch.start1 = char_count1 + 1
patch.start2 = char_count2 + 1
end
if (diff_type == DIFF_INSERT) then
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
patch.length2 = patch.length2 + #diff_text
postpatch_text = strsub(postpatch_text, 1, char_count2)
.. diff_text .. strsub(postpatch_text, char_count2 + 1)
elseif (diff_type == DIFF_DELETE) then
patch.length1 = patch.length1 + #diff_text
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
postpatch_text = strsub(postpatch_text, 1, char_count2)
.. strsub(postpatch_text, char_count2 + #diff_text + 1)
elseif (diff_type == DIFF_EQUAL) then
if (#diff_text <= Patch_Margin * 2)
and (patchDiffLength ~= 0) and (#diffs ~= x) then
-- Small equality inside a patch.
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
patch.length1 = patch.length1 + #diff_text
patch.length2 = patch.length2 + #diff_text
elseif (#diff_text >= Patch_Margin * 2) then
-- Time for a new patch.
if (patchDiffLength ~= 0) then
_patch_addContext(patch, prepatch_text)
patches[#patches + 1] = patch
patch = _new_patch_obj()
patchDiffLength = 0
-- Unlike Unidiff, our patch lists have a rolling context.
-- http://code.google.com/p/google-diff-match-patch/wiki/Unidiff
-- Update prepatch text & pos to reflect the application of the
-- just completed patch.
prepatch_text = postpatch_text
char_count1 = char_count2
end
end
end
-- Update the current character count.
if (diff_type ~= DIFF_INSERT) then
char_count1 = char_count1 + #diff_text
end
if (diff_type ~= DIFF_DELETE) then
char_count2 = char_count2 + #diff_text
end
end
-- Pick up the leftover patch if not empty.
if (patchDiffLength > 0) then
_patch_addContext(patch, prepatch_text)
patches[#patches + 1] = patch
end
return patches
end
--[[
* Merge a set of patches onto the text. Return a patched text, as well
* as a list of true/false values indicating which patches were applied.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @param {string} text Old text.
* @return {Array.<string|Array.<boolean>>} Two return values, the
* new text and an array of boolean values.
--]]
function patch_apply(patches, text)
if patches[1] == nil then
return text, {}
end
-- Deep copy the patches so that no changes are made to originals.
patches = _patch_deepCopy(patches)
local nullPadding = _patch_addPadding(patches)
text = nullPadding .. text .. nullPadding
_patch_splitMax(patches)
-- delta keeps track of the offset between the expected and actual location
-- of the previous patch. If there are patches expected at positions 10 and
-- 20, but the first patch was found at 12, delta is 2 and the second patch
-- has an effective expected position of 22.
local delta = 0
local results = {}
for x, patch in ipairs(patches) do
local expected_loc = patch.start2 + delta
local text1 = _diff_text1(patch.diffs)
local start_loc
local end_loc = -1
if #text1 > Match_MaxBits then
-- _patch_splitMax will only provide an oversized pattern in
-- the case of a monster delete.
start_loc = match_main(text,
strsub(text1, 1, Match_MaxBits), expected_loc)
if start_loc ~= -1 then
end_loc = match_main(text, strsub(text1, -Match_MaxBits),
expected_loc + #text1 - Match_MaxBits)
if end_loc == -1 or start_loc >= end_loc then
-- Can't find valid trailing context. Drop this patch.
start_loc = -1
end
end
else
start_loc = match_main(text, text1, expected_loc)
end
if start_loc == -1 then
-- No match found. :(
results[x] = false
-- Subtract the delta for this failed patch from subsequent patches.
delta = delta - patch.length2 - patch.length1
else
-- Found a match. :)
results[x] = true
delta = start_loc - expected_loc
local text2
if end_loc == -1 then
text2 = strsub(text, start_loc, start_loc + #text1 - 1)
else
text2 = strsub(text, start_loc, end_loc + Match_MaxBits - 1)
end
if text1 == text2 then
-- Perfect match, just shove the replacement text in.
text = strsub(text, 1, start_loc - 1) .. _diff_text2(patch.diffs)
.. strsub(text, start_loc + #text1)
else
-- Imperfect match. Run a diff to get a framework of equivalent
-- indices.
local diffs = diff_main(text1, text2, false)
if (#text1 > Match_MaxBits)
and (diff_levenshtein(diffs) / #text1 > Patch_DeleteThreshold) then
-- The end points match, but the content is unacceptably bad.
results[x] = false
else
_diff_cleanupSemanticLossless(diffs)
local index1 = 1
local index2
for y, mod in ipairs(patch.diffs) do
if mod[1] ~= DIFF_EQUAL then
index2 = _diff_xIndex(diffs, index1)
end
if mod[1] == DIFF_INSERT then
text = strsub(text, 1, start_loc + index2 - 2)
.. mod[2] .. strsub(text, start_loc + index2 - 1)
elseif mod[1] == DIFF_DELETE then
text = strsub(text, 1, start_loc + index2 - 2) .. strsub(text,
start_loc + _diff_xIndex(diffs, index1 + #mod[2] - 1))
end
if mod[1] ~= DIFF_DELETE then
index1 = index1 + #mod[2]
end
end
end
end
end
end
-- Strip the padding off.
text = strsub(text, #nullPadding + 1, -#nullPadding - 1)
return text, results
end
--[[
* Take a list of patches and return a textual representation.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {string} Text representation of patches.
--]]
function patch_toText(patches)
local text = {}
for x, patch in ipairs(patches) do
_patch_appendText(patch, text)
end
return tconcat(text)
end
--[[
* Parse a textual representation of patches and return a list of patch objects.
* @param {string} textline Text representation of patches.
* @return {Array.<_new_patch_obj>} Array of patch objects.
* @throws {Error} If invalid input.
--]]
function patch_fromText(textline)
local patches = {}
if (#textline == 0) then
return patches
end
local text = {}
for line in gmatch(textline, '([^\n]*)') do
text[#text + 1] = line
end
local textPointer = 1
while (textPointer <= #text) do
local start1, length1, start2, length2
= strmatch(text[textPointer], '^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@$')
if (start1 == nil) then
error('Invalid patch string: "' .. text[textPointer] .. '"')
end
local patch = _new_patch_obj()
patches[#patches + 1] = patch
start1 = tonumber(start1)
length1 = tonumber(length1) or 1
if (length1 == 0) then
start1 = start1 + 1
end
patch.start1 = start1
patch.length1 = length1
start2 = tonumber(start2)
length2 = tonumber(length2) or 1
if (length2 == 0) then
start2 = start2 + 1
end
patch.start2 = start2
patch.length2 = length2
textPointer = textPointer + 1
while true do
local line = text[textPointer]
if (line == nil) then
break
end
local sign; sign, line = strsub(line, 1, 1), strsub(line, 2)
local invalidDecode = false
local decoded = gsub(line, '%%(.?.?)',
function(c)
local n = tonumber(c, 16)
if (#c ~= 2) or (n == nil) then
invalidDecode = true
return ''
end
return strchar(n)
end)
if invalidDecode then
-- Malformed URI sequence.
error('Illegal escape in patch_fromText: ' .. line)
end
line = decoded
if (sign == '-') then
-- Deletion.
patch.diffs[#patch.diffs + 1] = {DIFF_DELETE, line}
elseif (sign == '+') then
-- Insertion.
patch.diffs[#patch.diffs + 1] = {DIFF_INSERT, line}
elseif (sign == ' ') then
-- Minor equality.
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, line}
elseif (sign == '@') then
-- Start of next patch.
break
elseif (sign == '') then
-- Blank line? Whatever.
else
-- WTF?
error('Invalid patch mode "' .. sign .. '" in: ' .. line)
end
textPointer = textPointer + 1
end
end
return patches
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE PATCH FUNCTIONS
-- ---------------------------------------------------------------------------
local patch_meta = {
__tostring = function(patch)
local buf = {}
_patch_appendText(patch, buf)
return tconcat(buf)
end
}
--[[
* Class representing one patch operation.
* @constructor
--]]
function _new_patch_obj()
return setmetatable({
--[[ @type {Array.<Array.<number|string>>} ]]
diffs = {};
--[[ @type {?number} ]]
start1 = 1; -- nil;
--[[ @type {?number} ]]
start2 = 1; -- nil;
--[[ @type {number} ]]
length1 = 0;
--[[ @type {number} ]]
length2 = 0;
}, patch_meta)
end
--[[
* Increase the context until it is unique,
* but don't let the pattern expand beyond Match_MaxBits.
* @param {_new_patch_obj} patch The patch to grow.
* @param {string} text Source text.
* @private
--]]
function _patch_addContext(patch, text)
if (#text == 0) then
return
end
local pattern = strsub(text, patch.start2, patch.start2 + patch.length1 - 1)
local padding = 0
-- LUANOTE: Lua's lack of a lastIndexOf function results in slightly
-- different logic here than in other language ports.
-- Look for the first two matches of pattern in text. If two are found,
-- increase the pattern length.
local firstMatch = indexOf(text, pattern)
local secondMatch = nil
if (firstMatch ~= nil) then
secondMatch = indexOf(text, pattern, firstMatch + 1)
end
while (#pattern == 0 or secondMatch ~= nil)
and (#pattern < Match_MaxBits - Patch_Margin - Patch_Margin) do
padding = padding + Patch_Margin
pattern = strsub(text, max(1, patch.start2 - padding),
patch.start2 + patch.length1 - 1 + padding)
firstMatch = indexOf(text, pattern)
if (firstMatch ~= nil) then
secondMatch = indexOf(text, pattern, firstMatch + 1)
else
secondMatch = nil
end
end
-- Add one chunk for good luck.
padding = padding + Patch_Margin
-- Add the prefix.
local prefix = strsub(text, max(1, patch.start2 - padding), patch.start2 - 1)
if (#prefix > 0) then
tinsert(patch.diffs, 1, {DIFF_EQUAL, prefix})
end
-- Add the suffix.
local suffix = strsub(text, patch.start2 + patch.length1,
patch.start2 + patch.length1 - 1 + padding)
if (#suffix > 0) then
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, suffix}
end
-- Roll back the start points.
patch.start1 = patch.start1 - #prefix
patch.start2 = patch.start2 - #prefix
-- Extend the lengths.
patch.length1 = patch.length1 + #prefix + #suffix
patch.length2 = patch.length2 + #prefix + #suffix
end
--[[
* Given an array of patches, return another array that is identical.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {Array.<_new_patch_obj>} Array of patch objects.
--]]
function _patch_deepCopy(patches)
local patchesCopy = {}
for x, patch in ipairs(patches) do
local patchCopy = _new_patch_obj()
local diffsCopy = {}
for i, diff in ipairs(patch.diffs) do
diffsCopy[i] = {diff[1], diff[2]}
end
patchCopy.diffs = diffsCopy
patchCopy.start1 = patch.start1
patchCopy.start2 = patch.start2
patchCopy.length1 = patch.length1
patchCopy.length2 = patch.length2
patchesCopy[x] = patchCopy
end
return patchesCopy
end
--[[
* Add some padding on text start and end so that edges can match something.
* Intended to be called only from within patch_apply.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {string} The padding string added to each side.
--]]
function _patch_addPadding(patches)
local paddingLength = Patch_Margin
local nullPadding = ''
for x = 1, paddingLength do
nullPadding = nullPadding .. strchar(x)
end
-- Bump all the patches forward.
for x, patch in ipairs(patches) do
patch.start1 = patch.start1 + paddingLength
patch.start2 = patch.start2 + paddingLength
end
-- Add some padding on start of first diff.
local patch = patches[1]
local diffs = patch.diffs
local firstDiff = diffs[1]
if (firstDiff == nil) or (firstDiff[1] ~= DIFF_EQUAL) then
-- Add nullPadding equality.
tinsert(diffs, 1, {DIFF_EQUAL, nullPadding})
patch.start1 = patch.start1 - paddingLength -- Should be 0.
patch.start2 = patch.start2 - paddingLength -- Should be 0.
patch.length1 = patch.length1 + paddingLength
patch.length2 = patch.length2 + paddingLength
elseif (paddingLength > #firstDiff[2]) then
-- Grow first equality.
local extraLength = paddingLength - #firstDiff[2]
firstDiff[2] = strsub(nullPadding, #firstDiff[2] + 1) .. firstDiff[2]
patch.start1 = patch.start1 - extraLength
patch.start2 = patch.start2 - extraLength
patch.length1 = patch.length1 + extraLength
patch.length2 = patch.length2 + extraLength
end
-- Add some padding on end of last diff.
patch = patches[#patches]
diffs = patch.diffs
local lastDiff = diffs[#diffs]
if (lastDiff == nil) or (lastDiff[1] ~= DIFF_EQUAL) then
-- Add nullPadding equality.
diffs[#diffs + 1] = {DIFF_EQUAL, nullPadding}
patch.length1 = patch.length1 + paddingLength
patch.length2 = patch.length2 + paddingLength
elseif (paddingLength > #lastDiff[2]) then
-- Grow last equality.
local extraLength = paddingLength - #lastDiff[2]
lastDiff[2] = lastDiff[2] .. strsub(nullPadding, 1, extraLength)
patch.length1 = patch.length1 + extraLength
patch.length2 = patch.length2 + extraLength
end
return nullPadding
end
--[[
* Look through the patches and break up any which are longer than the maximum
* limit of the match algorithm.
* Intended to be called only from within patch_apply.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
--]]
function _patch_splitMax(patches)
local patch_size = Match_MaxBits
local x = 1
while true do
local patch = patches[x]
if patch == nil then
return
end
if patch.length1 > patch_size then
local bigpatch = patch
-- Remove the big old patch.
tremove(patches, x)
x = x - 1
local start1 = bigpatch.start1
local start2 = bigpatch.start2
local precontext = ''
while bigpatch.diffs[1] do
-- Create one of several smaller patches.
local patch = _new_patch_obj()
local empty = true
patch.start1 = start1 - #precontext
patch.start2 = start2 - #precontext
if precontext ~= '' then
patch.length1, patch.length2 = #precontext, #precontext
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, precontext}
end
while bigpatch.diffs[1] and (patch.length1 < patch_size-Patch_Margin) do
local diff_type = bigpatch.diffs[1][1]
local diff_text = bigpatch.diffs[1][2]
if (diff_type == DIFF_INSERT) then
-- Insertions are harmless.
patch.length2 = patch.length2 + #diff_text
start2 = start2 + #diff_text
patch.diffs[#(patch.diffs) + 1] = bigpatch.diffs[1]
tremove(bigpatch.diffs, 1)
empty = false
elseif (diff_type == DIFF_DELETE) and (#patch.diffs == 1)
and (patch.diffs[1][1] == DIFF_EQUAL)
and (#diff_text > 2 * patch_size) then
-- This is a large deletion. Let it pass in one chunk.
patch.length1 = patch.length1 + #diff_text
start1 = start1 + #diff_text
empty = false
patch.diffs[#patch.diffs + 1] = {diff_type, diff_text}
tremove(bigpatch.diffs, 1)
else
-- Deletion or equality.
-- Only take as much as we can stomach.
diff_text = strsub(diff_text, 1,
patch_size - patch.length1 - Patch_Margin)
patch.length1 = patch.length1 + #diff_text
start1 = start1 + #diff_text
if (diff_type == DIFF_EQUAL) then
patch.length2 = patch.length2 + #diff_text
start2 = start2 + #diff_text
else
empty = false
end
patch.diffs[#patch.diffs + 1] = {diff_type, diff_text}
if (diff_text == bigpatch.diffs[1][2]) then
tremove(bigpatch.diffs, 1)
else
bigpatch.diffs[1][2]
= strsub(bigpatch.diffs[1][2], #diff_text + 1)
end
end
end
-- Compute the head context for the next patch.
precontext = _diff_text2(patch.diffs)
precontext = strsub(precontext, -Patch_Margin)
-- Append the end context for this patch.
local postcontext = strsub(_diff_text1(bigpatch.diffs), 1, Patch_Margin)
if postcontext ~= '' then
patch.length1 = patch.length1 + #postcontext
patch.length2 = patch.length2 + #postcontext
if patch.diffs[1]
and (patch.diffs[#patch.diffs][1] == DIFF_EQUAL) then
patch.diffs[#patch.diffs][2] = patch.diffs[#patch.diffs][2]
.. postcontext
else
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, postcontext}
end
end
if not empty then
x = x + 1
tinsert(patches, x, patch)
end
end
end
x = x + 1
end
end
--[[
* Emulate GNU diff's format.
* Header: @@ -382,8 +481,9 @@
* @return {string} The GNU diff string.
--]]
function _patch_appendText(patch, text)
local coords1, coords2
local length1, length2 = patch.length1, patch.length2
local start1, start2 = patch.start1, patch.start2
local diffs = patch.diffs
if length1 == 1 then
coords1 = start1
else
coords1 = ((length1 == 0) and (start1 - 1) or start1) .. ',' .. length1
end
if length2 == 1 then
coords2 = start2
else
coords2 = ((length2 == 0) and (start2 - 1) or start2) .. ',' .. length2
end
text[#text + 1] = '@@ -' .. coords1 .. ' +' .. coords2 .. ' @@\n'
local op
-- Escape the body of the patch with %xx notation.
for x, diff in ipairs(patch.diffs) do
local diff_type = diff[1]
if diff_type == DIFF_INSERT then
op = '+'
elseif diff_type == DIFF_DELETE then
op = '-'
elseif diff_type == DIFF_EQUAL then
op = ' '
end
text[#text + 1] = op
.. gsub(diffs[x][2], percentEncode_pattern, percentEncode_replace)
.. '\n'
end
return text
end
-- Expose the API
local _M = {}
_M.DIFF_DELETE = DIFF_DELETE
_M.DIFF_INSERT = DIFF_INSERT
_M.DIFF_EQUAL = DIFF_EQUAL
_M.diff_main = diff_main
_M.diff_cleanupSemantic = diff_cleanupSemantic
_M.diff_cleanupEfficiency = diff_cleanupEfficiency
_M.diff_levenshtein = diff_levenshtein
_M.diff_prettyHtml = diff_prettyHtml
_M.match_main = match_main
_M.patch_make = patch_make
_M.patch_toText = patch_toText
_M.patch_fromText = patch_fromText
_M.patch_apply = patch_apply
-- Expose some non-API functions as well, for testing purposes etc.
_M.diff_commonPrefix = _diff_commonPrefix
_M.diff_commonSuffix = _diff_commonSuffix
_M.diff_commonOverlap = _diff_commonOverlap
_M.diff_halfMatch = _diff_halfMatch
_M.diff_bisect = _diff_bisect
_M.diff_cleanupMerge = _diff_cleanupMerge
_M.diff_cleanupSemanticLossless = _diff_cleanupSemanticLossless
_M.diff_text1 = _diff_text1
_M.diff_text2 = _diff_text2
_M.diff_toDelta = _diff_toDelta
_M.diff_fromDelta = _diff_fromDelta
_M.diff_xIndex = _diff_xIndex
_M.match_alphabet = _match_alphabet
_M.match_bitap = _match_bitap
_M.new_patch_obj = _new_patch_obj
_M.patch_addContext = _patch_addContext
_M.patch_splitMax = _patch_splitMax
_M.patch_addPadding = _patch_addPadding
_M.settings = settings
return _M
| apache-2.0 |
felipeprov/premake-core | src/base/premake.lua | 1 | 8433 | --
-- premake.lua
-- High-level helper functions for the project exporters.
-- Copyright (c) 2002-2014 Jason Perkins and the Premake project
--
local p = premake
local solution = p.solution
local project = p.project
local config = p.config
local field = p.field
-- Store captured output text for later testing
local _captured
-- The string escaping function.
local _esc = function(v) return v end
-- The output settings and defaults
local _eol = "\n"
local _indentString = "\t"
local _indentLevel = 0
-- Set up the global configuration scope. There can be only one.
global("root")
---
-- Capture and store everything sent through the output stream functions
-- premake.w(), premake.x(), and premake.out(). Retrieve the captured
-- text using the premake.captured() function.
--
-- @param fn
-- A function to execute. Any output calls made during the execution
-- of the function will be captured.
-- @return
-- The captured output.
---
function premake.capture(fn)
-- start a new capture without forgetting the old one
local old = _captured
_captured = {}
-- capture
fn()
-- build the result
local captured = premake.captured()
-- restore the old capture and done
_captured = old
return captured
end
--
-- Returns the captured text and stops capturing.
--
function premake.captured()
if _captured then
return table.concat(_captured, _eol)
else
return ""
end
end
---
-- Set the output stream end-of-line sequence.
--
-- @param s
-- The string to use to mark line ends, or nil to keep the existing
-- EOL sequence.
-- @return
-- The new EOL sequence.
---
function premake.eol(s)
_eol = s or _eol
return _eol
end
---
-- Handle escaping of strings for various outputs.
--
-- @param value
-- If this is a string: escape it and return the new value. If it is an
-- array, return a new array of escaped values.
-- @return
-- If the input was a single string, returns the escaped version. If it
-- was an array, returns an corresponding array of escaped strings.
---
function premake.esc(value)
if type(value) == "table" then
local result = {}
local n = #value
for i = 1, n do
table.insert(result, premake.esc(value[i]))
end
return result
end
return _esc(value or "")
end
---
-- Set a new string escaping function.
--
-- @param func
-- The new escaping function, which should take a single string argument
-- and return the escaped version of that string. If nil, uses a default
-- no-op function.
---
function premake.escaper(func)
_esc = func
if not _esc then
_esc = function (value) return value end
end
end
--
-- Open a file for output, and call a function to actually do the writing.
-- Used by the actions to generate solution and project files.
--
-- @param obj
-- A solution or project object; will be passed to the callback function.
-- @param ext
-- An optional extension for the generated file, with the leading dot.
-- @param callback
-- The function responsible for writing the file, should take a solution
-- or project as a parameters.
--
function premake.generate(obj, ext, callback)
local fn = premake.filename(obj, ext)
printf("Generating %s...", path.getrelative(os.getcwd(), fn))
local f, err = io.open(fn, "wb")
if (not f) then
error(err, 0)
end
io.output(f)
_indentLevel = 0
callback(obj)
f:close()
_indentLevel = 0
end
---
-- Returns the full path a file generated from any of the project
-- objects (project, solution, rule).
--
-- @param obj
-- The project object being generated.
-- @param ext
-- An optional extension for the generated file, with the leading dot.
-- @param callback
-- The function responsible for writing the file; will receive the
-- project object as its only argument.
---
function premake.filename(obj, ext)
local fname = obj.location or obj.basedir
if ext and not ext:startswith(".") then
fname = path.join(fname, ext)
else
fname = path.join(fname, obj.filename)
if ext then
fname = fname .. ext
end
end
return path.getabsolute(fname)
end
---
-- Sets the output indentation parameters.
--
-- @param s
-- The indentation string.
-- @param i
-- The new indentation level, or nil to reset to zero.
---
function premake.indent(s, i)
_indentString = s or "\t"
_indentLevel = i or 0
end
---
-- Write a simple, unformatted string to the output stream, with no indentation
-- or end of line sequence.
---
function premake.out(s)
if not _captured then
io.write(s)
else
table.insert(_captured, s)
end
end
---
-- Write a simple, unformatted string to the output stream, with no indentation,
-- and append the current EOL sequence.
---
function premake.outln(s)
premake.out(s)
if not _captured then
io.write(_eol or "\n")
end
end
---
-- Write a formatted string to the exported file, after decreasing the
-- indentation level by one.
--
-- @param i
-- If set to a number, the indentation level will be decreased by
-- this amount. If nil, the indentation level is decremented and
-- no output is written. Otherwise, pass to premake.w() as the
-- formatting string, followed by any additional arguments.
---
function premake.pop(i, ...)
if i == nil or type(i) == "number" then
_indentLevel = _indentLevel - (i or 1)
else
_indentLevel = _indentLevel - 1
premake.w(i, ...)
end
end
---
-- Write a formatted string to the exported file, and increase the
-- indentation level by one.
--
-- @param i
-- If set to a number, the indentation level will be increased by
-- this amount. If nil, the indentation level is incremented and
-- no output is written. Otherwise, pass to premake.w() as the
-- formatting string, followed by any additional arguments.
---
function premake.push(i, ...)
if i == nil or type(i) == "number" then
_indentLevel = _indentLevel + (i or 1)
else
premake.w(i, ...)
_indentLevel = _indentLevel + 1
end
end
---
-- Wrap the provided value in double quotes if it contains spaces, or
-- if it contains a shell variable of the form $(...).
---
function premake.quoted(value)
local q = value:find(" ", 1, true)
if not q then
q = value:find("$%(.-%)", 1)
end
if q then
value = '"' .. value .. '"'
end
return value
end
--
-- Output a UTF-8 BOM to the exported file.
--
function premake.utf8()
if not _captured then
premake.out('\239\187\191')
end
end
---
-- Write a formatted string to the exported file, at the current
-- level of indentation, and appends an end of line sequence.
-- This gets called quite a lot, hence the very short name.
---
function premake.w(...)
if select("#", ...) > 0 then
premake.outln(string.rep(_indentString or "\t", _indentLevel) .. string.format(...))
else
premake.outln('');
end
end
---
-- Write a formatted string to the exported file, after passing all
-- arguments (except for the first, which is the formatting string)
-- through premake.esc().
---
function premake.x(msg, ...)
local arg = {...}
for i = 1, #arg do
arg[i] = premake.esc(arg[i])
end
premake.w(msg, unpack(arg))
end
---
-- Write a opening XML element for a UTF-8 encoded file. Used by
-- several different files for different actions, so makes sense
-- to have a common call for it.
--
-- @param upper
-- If true, the encoding is written in uppercase.
---
function premake.xmlUtf8(upper)
local encoding = iif(upper, "UTF-8", "utf-8")
premake.w('<?xml version="1.0" encoding="%s"?>', encoding)
end
--
-- These are the output shortcuts that I used before switching to the
-- indentation-aware calls above. They are still in use all over the
-- place, including lots of community code, so let's keep them around.
--
-- @param i
-- This will either be a printf-style formatting string suitable
-- for passing to string.format(), OR an integer number indicating
-- the desired level of indentation. If the latter, the formatting
-- string should be the next argument in the list.
-- @param ...
-- The values necessary to fill out the formatting string tokens.
--
function _p(i, ...)
if type(i) == "number" then
_indentLevel = i
premake.w(...)
else
_indentLevel = 0
premake.w(i, ...)
end
end
function _x(i, ...)
local arg = {...}
for i = 2, #arg do
arg[i] = premake.esc(arg[i])
end
_p(i, unpack(arg))
end
| bsd-3-clause |
Radseq/otclient | modules/corelib/ui/uiprogressbar.lua | 10 | 2673 | -- @docclass
UIProgressBar = extends(UIWidget, "UIProgressBar")
function UIProgressBar.create()
local progressbar = UIProgressBar.internalCreate()
progressbar:setFocusable(false)
progressbar:setOn(true)
progressbar.min = 0
progressbar.max = 100
progressbar.value = 0
progressbar.bgBorderLeft = 0
progressbar.bgBorderRight = 0
progressbar.bgBorderTop = 0
progressbar.bgBorderBottom = 0
return progressbar
end
function UIProgressBar:setMinimum(minimum)
self.minimum = minimum
if self.value < minimum then
self:setValue(minimum)
end
end
function UIProgressBar:setMaximum(maximum)
self.maximum = maximum
if self.value > maximum then
self:setValue(maximum)
end
end
function UIProgressBar:setValue(value, minimum, maximum)
if minimum then
self:setMinimum(minimum)
end
if maximum then
self:setMaximum(maximum)
end
self.value = math.max(math.min(value, self.maximum), self.minimum)
self:updateBackground()
end
function UIProgressBar:setPercent(percent)
self:setValue(percent, 0, 100)
end
function UIProgressBar:getPercent()
return self.value
end
function UIProgressBar:getPercentPixels()
return (self.maximum - self.minimum) / self:getWidth()
end
function UIProgressBar:getProgress()
if self.minimum == self.maximum then return 1 end
return (self.value - self.minimum) / (self.maximum - self.minimum)
end
function UIProgressBar:updateBackground()
if self:isOn() then
local width = math.round(math.max((self:getProgress() * (self:getWidth() - self.bgBorderLeft - self.bgBorderRight)), 1))
local height = self:getHeight() - self.bgBorderTop - self.bgBorderBottom
local rect = { x = self.bgBorderLeft, y = self.bgBorderTop, width = width, height = height }
self:setBackgroundRect(rect)
end
end
function UIProgressBar:onSetup()
self:updateBackground()
end
function UIProgressBar:onStyleApply(name, node)
for name,value in pairs(node) do
if name == 'background-border-left' then
self.bgBorderLeft = tonumber(value)
elseif name == 'background-border-right' then
self.bgBorderRight = tonumber(value)
elseif name == 'background-border-top' then
self.bgBorderTop = tonumber(value)
elseif name == 'background-border-bottom' then
self.bgBorderBottom = tonumber(value)
elseif name == 'background-border' then
self.bgBorderLeft = tonumber(value)
self.bgBorderRight = tonumber(value)
self.bgBorderTop = tonumber(value)
self.bgBorderBottom = tonumber(value)
end
end
end
function UIProgressBar:onGeometryChange(oldRect, newRect)
if not self:isOn() then
self:setHeight(0)
end
self:updateBackground()
end
| mit |
PicassoCT/Journeywar | LuaUI/widgets/chili/controls/button.lua | 18 | 1390 | --//=============================================================================
--- Button module
--- Button fields.
-- Inherits from Control.
-- @see control.Control
-- @table Button
-- @string[opt="button"] caption caption to be displayed
Button = Control:Inherit{
classname= "button",
caption = 'button',
defaultWidth = 70,
defaultHeight = 20,
}
local this = Button
local inherited = this.inherited
--//=============================================================================
--- Sets the caption of the button
-- @string caption new caption of the button
function Button:SetCaption(caption)
if (self.caption == caption) then return end
self.caption = caption
self:Invalidate()
end
--//=============================================================================
function Button:DrawControl()
--// gets overriden by the skin/theme
end
--//=============================================================================
function Button:HitTest(x,y)
return self
end
function Button:MouseDown(...)
self.state.pressed = true
inherited.MouseDown(self, ...)
self:Invalidate()
return self
end
function Button:MouseUp(...)
if (self.state.pressed) then
self.state.pressed = false
inherited.MouseUp(self, ...)
self:Invalidate()
return self
end
end
--//=============================================================================
| gpl-3.0 |
b03605079/darkstar | scripts/zones/Kazham/npcs/Lulupp.lua | 21 | 1844 | -----------------------------------
-- Area: Kazham
-- NPC: Lulupp
-- Type: Standard NPC
-- @zone: 250
-- @pos -26.567 -3.5 -3.544
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
-----------------------------------
local path = {
-27.457125, -3.043032, -22.057966,
-27.373426, -2.772481, -20.974442,
-27.103289, -2.500000, -17.846378,
-26.864126, -2.500000, -15.667570,
-26.532335, -2.500000, -16.636086,
-26.505196, -2.500000, -15.471632,
-26.509424, -2.500000, -14.359641,
-26.564587, -2.500000, -4.499783,
-26.574417, -2.500000, -5.523735,
-26.580530, -2.500000, -6.591716,
-26.583765, -2.500000, -8.555706,
-26.501217, -2.500000, -16.563267,
-26.504532, -2.500000, -15.427269,
-26.509769, -2.500000, -14.327281,
-26.565643, -2.500000, -4.247434,
-26.573967, -2.500000, -5.299402,
-26.579763, -2.500000, -6.379386,
-26.580465, -2.500000, -8.155381
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
onPath(npc);
end;
function onPath(npc)
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00c5);
npc:wait(-1);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
npc:wait(0);
end;
| gpl-3.0 |
PicassoCT/Journeywar | weapons/raiderarrow.lua | 1 | 1055 | local weaponName = "raiderarrow"
local weaponDef = {
weaponType = [[MissileLauncher]],
name = "raiderarrow",
areaOfEffect = 128,
avoidFeature = false,
avoidGround = false,
burst = 1,
burstrate = 0.1,
CegTag = "bluestripe",
craterBoost = 1,
craterMult = 2,
dance = 20,
edgeEffectiveness = 0.5,
explosionGenerator = "custom:ccatapultexpl",
fireStarter = 100,
flightTime = 8,
impulseBoost = 0,
impulseFactor = 0.4,
model = "ccatapultproj.s3o",
noSelfDamage = true,
projectiles = 2,
range = 1450,
reloadtime = 30,
smokeTrail = false,
--sound
soundHit = "cgatefortress/CatapultImpact.ogg",
soundStart = "cgatefortress/catapultFire.ogg",
startVelocity = 100,
tolerance = 512,
trajectoryHeight = 1,
turnRate = 2500,
turret = true,
weaponAcceleration = 100,
weaponType = [[MissileLauncher]],
weaponVelocity = 250,
wobble = 7000,
damage = {
default = 15,
},
}
return lowerkeys({ [weaponName] = weaponDef }) | gpl-3.0 |
immibis/wiremod | lua/entities/gmod_wire_eyepod.lua | 9 | 8963 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Eye Pod"
ENT.Purpose = "To control the player's view in a pod and output their mouse movements"
ENT.WireDebugName = "Eye Pod"
if CLIENT then
local enabled = false
local rotate90 = false
local freezePitch = true
local freezeYaw = true
local previousEnabled = false
usermessage.Hook("UpdateEyePodState", function(um)
if not um then return end
local eyeAng = um:ReadAngle()
enabled = um:ReadBool()
rotate90 = um:ReadBool()
freezePitch = um:ReadBool() and eyeAng.p
freezeYaw = um:ReadBool() and eyeAng.y
end)
hook.Add("CreateMove", "WireEyePodEyeControl", function(ucmd)
if enabled then
currentAng = ucmd:GetViewAngles()
if freezePitch then
currentAng.p = freezePitch
end
if freezeYaw then
currentAng.y = freezeYaw
end
currentAng.r = 0
ucmd:SetViewAngles(currentAng)
previousEnabled = true
elseif previousEnabled then
if rotate90 then
ucmd:SetViewAngles(Angle(0,90,0))
else
ucmd:SetViewAngles(Angle(0,0,0))
end
previousEnabled = false
end
end)
return -- No more client
end
-- Server
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetCollisionGroup(COLLISION_GROUP_WORLD)
self:DrawShadow(false)
-- Set wire I/O
self.Inputs = WireLib.CreateSpecialInputs(self, { "Enable", "SetPitch", "SetYaw", "SetViewAngle", "UnfreezePitch", "UnfreezeYaw" }, { "NORMAL", "NORMAL", "NORMAL", "ANGLE", "NORMAL", "NORMAL" })
self.Outputs = WireLib.CreateSpecialOutputs(self, { "X", "Y", "XY" }, { "NORMAL", "NORMAL", "VECTOR2" })
-- Initialize values
self.driver = nil
self.X = 0
self.Y = 0
self.enabled = false
self.pod = nil
self.eyeAng = Angle(0, 0, 0)
self.rotate90 = false
self.DefaultToZero = 1
self.ShowRateOfChange = 0
self.LastUpdateTime = CurTime()
-- clamps
self.ClampXMin = 0
self.ClampXMax = 0
self.ClampYMin = 0
self.ClampYMax = 0
self.ClampX = 0
self.ClampY = 0
self.freezePitch = true
self.freezeYaw = true
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:Wake()
end
end
function ENT:UpdateOverlay()
self:SetOverlayText(
string.format( "Default to Zero: %s\nCumulative: %s\nMin: %s,%s\nMax: %s,%s\n%s\n\nActivated: %s%s",
(self.DefaultToZero == 1) and "Yes" or "No",
(self.ShowRateOfChange == 0) and "Yes" or "No",
self.ClampXMin, self.ClampYMin,
self.ClampXMax, self.ClampYMax,
IsValid( self.pod ) and "Linked to: " .. self.pod:GetModel() or "Not linked",
self.enabled and "Yes" or "No",
(self.enabled == true and IsValid( self.driver )) and "\nIn use by: " .. self.driver:Nick() or ""
)
)
end
function ENT:Setup(DefaultToZero, RateOfChange, ClampXMin, ClampXMax, ClampYMin, ClampYMax, ClampX, ClampY)
self.DefaultToZero = DefaultToZero
self.ShowRateOfChange = RateOfChange
self.ClampXMin = ClampXMin
self.ClampXMax = ClampXMax
self.ClampYMin = ClampYMin
self.ClampYMax = ClampYMax
self.ClampX = ClampX
self.ClampY = ClampY
self:UpdateOverlay()
end
local Rotate90ModelList = {
["models/props_c17/furniturechair001a.mdl"] = true,
["models/airboat.mdl"] = true,
["models/props_c17/chair_office01a.mdl"] = true,
["models/nova/chair_office02.mdl"] = true,
["models/nova/chair_office01.mdl"] = true,
["models/props_combine/breenchair.mdl"] = true,
["models/nova/chair_wood01.mdl"] = true,
["models/nova/airboat_seat.mdl"] = true,
["models/nova/chair_plastic01.mdl"] = true,
["models/nova/jeep_seat.mdl"] = true,
["models/props_phx/carseat.mdl"] = true,
["models/props_phx/carseat2.mdl"] = true,
["models/props_phx/carseat3.mdl"] = true,
["models/buggy.mdl"] = true,
["models/vehicle.mdl"] = true
}
function ENT:PodLink(vehicle)
if not IsValid(vehicle) or not vehicle:IsVehicle() then
if IsValid(self.pod) then
self.pod.AttachedWireEyePod = nil
end
self.pod = nil
self:UpdateOverlay()
return false
end
self.pod = vehicle
self.rotate90 = false
self.eyeAng = Angle(0, 0, 0)
if IsValid(vehicle) and vehicle:IsVehicle() then
if Rotate90ModelList[string.lower(vehicle:GetModel())] then
self.rotate90 = true
self.eyeAng = Angle(0, 90, 0)
end
end
vehicle.AttachedWireEyePod = self
self:UpdateOverlay()
return true
end
function ENT:updateEyePodState(enabled)
umsg.Start("UpdateEyePodState", self.driver)
umsg.Angle(self.eyeAng)
umsg.Bool(enabled)
umsg.Bool(self.rotate90)
umsg.Bool(self.freezePitch)
umsg.Bool(self.freezeYaw)
umsg.End()
end
hook.Add("PlayerEnteredVehicle","gmod_wire_eyepod_entervehicle",function(ply,vehicle)
local eyepod = vehicle.AttachedWireEyePod
if eyepod ~= nil then
if IsValid(eyepod) then
eyepod.driver = vehicle:GetDriver()
eyepod:updateEyePodState(eyepod.enabled)
eyepod:UpdateOverlay()
else
vehicle.AttachedWireEyePod = nil
end
end
end)
hook.Add("PlayerLeaveVehicle","gmod_wire_eyepod_leavevehicle",function(ply,vehicle)
local eyepod = vehicle.AttachedWireEyePod
if eyepod ~= nil then
if IsValid(eyepod) then
eyepod:updateEyePodState(false)
eyepod.driver = nil
if (eyepod.X ~= 0 or eyepod.Y ~= 0) and eyepod.DefaultToZero == 1 then
eyepod.X = 0
eyepod.Y = 0
WireLib.TriggerOutput( eyepod, "X", 0 )
WireLib.TriggerOutput( eyepod, "Y", 0 )
WireLib.TriggerOutput( eyepod, "XY", {0,0} )
end
eyepod:UpdateOverlay()
else
vehicle.AttachedWireEyePod = nil
end
end
end)
function ENT:OnRemove()
if IsValid(self.pod) and self.pod:IsVehicle() then
self.pod.AttachedWireEyePod = nil
end
if IsValid(self.driver) then
self:updateEyePodState(false)
self.driver = nil
end
end
local function AngNorm(Ang)
return (Ang + 180) % 360 - 180
end
local function AngNorm90(Ang)
return (Ang + 90) % 180 - 90
end
function ENT:TriggerInput(iname, value)
-- Change variables to reflect input
if iname == "Enable" then
self.enabled = value ~= 0
if self.enabled == false and self.DefaultToZero == 1 and (self.X ~= 0 or self.Y ~= 0) then
self.X = 0
self.Y = 0
WireLib.TriggerOutput( self, "X", 0 )
WireLib.TriggerOutput( self, "Y", 0 )
WireLib.TriggerOutput( self, "XY", {0,0} )
end
self:UpdateOverlay()
elseif iname == "SetPitch" then
self.eyeAng = Angle(AngNorm90(value), self.eyeAng.y, self.eyeAng.r)
elseif iname == "SetYaw" then
if self.rotate90 == true then
self.eyeAng = Angle(AngNorm90(self.eyeAng.p), AngNorm(value+90), self.eyeAng.r)
else
self.eyeAng = Angle(AngNorm90(self.eyeAng.p), AngNorm(value), self.eyeAng.r)
end
elseif iname == "SetViewAngle" then
if self.rotate90 == true then
self.eyeAng = Angle(AngNorm90(value.p), AngNorm(value.y+90), 0)
else
self.eyeAng = Angle(AngNorm90(value.p), AngNorm(value.y), 0)
end
elseif iname == "UnfreezePitch" then
self.freezePitch = value == 0
elseif iname == "UnfreezeYaw" then
self.freezeYaw = value == 0
end
if IsValid(self.pod) and IsValid(self.driver) then
self:updateEyePodState(self.enabled)
end
end
hook.Add("SetupMove", "WireEyePodMouseControl", function(ply, movedata)
--is the player in a vehicle?
if not ply then return end
if not ply:InVehicle() then return end
local vehicle = ply:GetVehicle()
if not IsValid(vehicle) then return end
--get the EyePod
local eyePod = vehicle.AttachedWireEyePod
--is the vehicle linked to an EyePod?
if not IsValid(eyePod) then return end
if eyePod.enabled then
local cmd = ply:GetCurrentCommand()
local oldX = eyePod.X
local oldY = eyePod.Y
--reset the output so it is not cumualative if you want the rate of change
if eyePod.ShowRateOfChange == 1 then
eyePod.X = 0
eyePod.Y = 0
end
--update the cumualative output
eyePod.X = cmd:GetMouseX()/10 + eyePod.X
eyePod.Y = -cmd:GetMouseY()/10 + eyePod.Y
--clamp the output
if eyePod.ClampX == 1 then
eyePod.X = math.Clamp(eyePod.X, eyePod.ClampXMin, eyePod.ClampXMax)
end
if eyePod.ClampY == 1 then
eyePod.Y = math.Clamp(eyePod.Y, eyePod.ClampYMin, eyePod.ClampYMax)
end
if oldX ~= eyePod.X or oldY ~= eyePod.Y then
-- Update outputs
WireLib.TriggerOutput(eyePod, "X", eyePod.X)
WireLib.TriggerOutput(eyePod, "Y", eyePod.Y)
local XY_Vec = {eyePod.X, eyePod.Y}
WireLib.TriggerOutput(eyePod, "XY", XY_Vec)
end
--reset the mouse
cmd:SetMouseX(0)
cmd:SetMouseY(0)
end
end)
-- Advanced Duplicator Support
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
if IsValid(self.pod) then
info.pod = self.pod:EntIndex()
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self:PodLink(GetEntByID(info.pod))
end
duplicator.RegisterEntityClass("gmod_wire_eyepod", WireLib.MakeWireEnt, "Data", "DefaultToZero", "ShowRateOfChange" , "ClampXMin" , "ClampXMax" , "ClampYMin" , "ClampYMax" , "ClampX", "ClampY")
| apache-2.0 |
TorstenC/esp8266-devkit | Espressif/examples/nodemcu-firmware/tools/utils.lua | 48 | 11997 | -- Generic utility functions
module( ..., package.seeall )
local lfs = require "lfs"
local sf = string.format
-- Taken from Lake
dir_sep = package.config:sub( 1, 1 )
is_os_windows = dir_sep == '\\'
-- Converts a string with items separated by 'sep' into a table
string_to_table = function( s, sep )
if type( s ) ~= "string" then return end
sep = sep or ' '
if s:sub( -1, -1 ) ~= sep then s = s .. sep end
s = s:gsub( sf( "^%s*", sep ), "" )
local t = {}
local fmt = sf( "(.-)%s+", sep )
for w in s:gmatch( fmt ) do table.insert( t, w ) end
return t
end
-- Split a file name into 'path part' and 'extension part'
split_ext = function( s )
local pos
for i = #s, 1, -1 do
if s:sub( i, i ) == "." then
pos = i
break
end
end
if not pos or s:find( dir_sep, pos + 1 ) then return s end
return s:sub( 1, pos - 1 ), s:sub( pos )
end
-- Replace the extension of a given file name
replace_extension = function( s, newext )
local p, e = split_ext( s )
if e then
if newext and #newext > 0 then
s = p .. "." .. newext
else
s = p
end
end
return s
end
-- Return 'true' if building from Windows, false otherwise
is_windows = function()
return is_os_windows
end
-- Prepend each component of a 'pat'-separated string with 'prefix'
prepend_string = function( s, prefix, pat )
if not s or #s == 0 then return "" end
pat = pat or ' '
local res = ''
local st = string_to_table( s, pat )
foreach( st, function( k, v ) res = res .. prefix .. v .. " " end )
return res
end
-- Like above, but consider 'prefix' a path
prepend_path = function( s, prefix, pat )
return prepend_string( s, prefix .. dir_sep, pat )
end
-- full mkdir: create all the paths needed for a multipath
full_mkdir = function( path )
local ptables = string_to_table( path, dir_sep )
local p, res = ''
for i = 1, #ptables do
p = ( i ~= 1 and p .. dir_sep or p ) .. ptables[ i ]
res = lfs.mkdir( p )
end
return res
end
-- Concatenate the given paths to form a complete path
concat_path = function( paths )
return table.concat( paths, dir_sep )
end
-- Return true if the given array contains the given element, false otherwise
array_element_index = function( arr, element )
for i = 1, #arr do
if arr[ i ] == element then return i end
end
end
-- Linearize an array with (possibly) embedded arrays into a simple array
_linearize_array = function( arr, res, filter )
if type( arr ) ~= "table" then return end
for i = 1, #arr do
local e = arr[ i ]
if type( e ) == 'table' and filter( e ) then
_linearize_array( e, res, filter )
else
table.insert( res, e )
end
end
end
linearize_array = function( arr, filter )
local res = {}
filter = filter or function( v ) return true end
_linearize_array( arr, res, filter )
return res
end
-- Return an array with the keys of a table
table_keys = function( t )
local keys = {}
foreach( t, function( k, v ) table.insert( keys, k ) end )
return keys
end
-- Return an array with the values of a table
table_values = function( t )
local vals = {}
foreach( t, function( k, v ) table.insert( vals, v ) end )
return vals
end
-- Returns true if 'path' is a regular file, false otherwise
is_file = function( path )
return lfs.attributes( path, "mode" ) == "file"
end
-- Returns true if 'path' is a directory, false otherwise
is_dir = function( path )
return lfs.attributes( path, "mode" ) == "directory"
end
-- Return a list of files in the given directory matching a given mask
get_files = function( path, mask, norec, level )
local t = ''
level = level or 0
for f in lfs.dir( path ) do
local fname = path .. dir_sep .. f
if lfs.attributes( fname, "mode" ) == "file" then
local include
if type( mask ) == "string" then
include = fname:find( mask )
else
include = mask( fname )
end
if include then t = t .. ' ' .. fname end
elseif lfs.attributes( fname, "mode" ) == "directory" and not fname:find( "%.+$" ) and not norec then
t = t .. " " .. get_files( fname, mask, norec, level + 1 )
end
end
return level > 0 and t or t:gsub( "^%s+", "" )
end
-- Check if the given command can be executed properly
check_command = function( cmd )
local res = os.execute( cmd .. " > .build.temp 2>&1" )
os.remove( ".build.temp" )
return res
end
-- Execute a command and capture output
-- From: http://stackoverflow.com/a/326715/105950
exec_capture = function( cmd, raw )
local f = assert(io.popen(cmd, 'r'))
local s = assert(f:read('*a'))
f:close()
if raw then return s end
s = string.gsub(s, '^%s+', '')
s = string.gsub(s, '%s+$', '')
s = string.gsub(s, '[\n\r]+', ' ')
return s
end
-- Execute the given command for each value in a table
foreach = function ( t, cmd )
if type( t ) ~= "table" then return end
for k, v in pairs( t ) do cmd( k, v ) end
end
-- Generate header with the given #defines, return result as string
gen_header_string = function( name, defines )
local s = "// eLua " .. name:lower() .. " definition\n\n"
s = s .. "#ifndef __" .. name:upper() .. "_H__\n"
s = s .. "#define __" .. name:upper() .. "_H__\n\n"
for key,value in pairs(defines) do
s = s .. string.format("#define %-25s%-19s\n",key:upper(),value)
end
s = s .. "\n#endif\n"
return s
end
-- Generate header with the given #defines, save result to file
gen_header_file = function( name, defines )
local hname = concat_path{ "inc", name:lower() .. ".h" }
local h = assert( io.open( hname, "w" ) )
h:write( gen_header_string( name, defines ) )
h:close()
end
-- Remove the given elements from an array
remove_array_elements = function( arr, del )
del = istable( del ) and del or { del }
foreach( del, function( k, v )
local pos = array_element_index( arr, v )
if pos then table.remove( arr, pos ) end
end )
end
-- Remove a directory recusively
-- USE WITH CARE!! Doesn't do much checks :)
rmdir_rec = function ( dirname )
if lfs.attributes( dirname, "mode" ) ~= "directory" then return end
for f in lfs.dir( dirname ) do
local ename = string.format( "%s/%s", dirname, f )
local attrs = lfs.attributes( ename )
if attrs.mode == 'directory' and f ~= '.' and f ~= '..' then
rmdir_rec( ename )
elseif attrs.mode == 'file' or attrs.mode == 'named pipe' or attrs.mode == 'link' then
os.remove( ename )
end
end
lfs.rmdir( dirname )
end
-- Concatenates the second table into the first one
concat_tables = function( dst, src )
foreach( src, function( k, v ) dst[ k ] = v end )
end
-------------------------------------------------------------------------------
-- Color-related funtions
-- Currently disabled when running in Windows
-- (they can be enabled by setting WIN_ANSI_TERM)
local dcoltable = { 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' }
local coltable = {}
foreach( dcoltable, function( k, v ) coltable[ v ] = k - 1 end )
local _col_builder = function( col )
local _col_maker = function( s )
if is_os_windows and not os.getenv( "WIN_ANSI_TERM" ) then
return s
else
return( sf( "\027[%d;1m%s\027[m", coltable[ col ] + 30, s ) )
end
end
return _col_maker
end
col_funcs = {}
foreach( coltable, function( k, v )
local fname = "col_" .. k
_G[ fname ] = _col_builder( k )
col_funcs[ k ] = _G[ fname ]
end )
-------------------------------------------------------------------------------
-- Option handling
local options = {}
options.new = function()
local self = {}
self.options = {}
setmetatable( self, { __index = options } )
return self
end
-- Argument validator: boolean value
options._bool_validator = function( v )
if v == '0' or v:upper() == 'FALSE' then
return false
elseif v == '1' or v:upper() == 'TRUE' then
return true
end
end
-- Argument validator: choice value
options._choice_validator = function( v, allowed )
for i = 1, #allowed do
if v:upper() == allowed[ i ]:upper() then return allowed[ i ] end
end
end
-- Argument validator: choice map (argument value maps to something)
options._choice_map_validator = function( v, allowed )
for k, value in pairs( allowed ) do
if v:upper() == k:upper() then return value end
end
end
-- Argument validator: string value (no validation)
options._string_validator = function( v )
return v
end
-- Argument printer: boolean value
options._bool_printer = function( o )
return "true|false", o.default and "true" or "false"
end
-- Argument printer: choice value
options._choice_printer = function( o )
local clist, opts = '', o.data
for i = 1, #opts do
clist = clist .. ( i ~= 1 and "|" or "" ) .. opts[ i ]
end
return clist, o.default
end
-- Argument printer: choice map printer
options._choice_map_printer = function( o )
local clist, opts, def = '', o.data
local i = 1
for k, v in pairs( opts ) do
clist = clist .. ( i ~= 1 and "|" or "" ) .. k
if o.default == v then def = k end
i = i + 1
end
return clist, def
end
-- Argument printer: string printer
options._string_printer = function( o )
return nil, o.default
end
-- Add an option of the specified type
options._add_option = function( self, optname, opttype, help, default, data )
local validators =
{
string = options._string_validator, choice = options._choice_validator,
boolean = options._bool_validator, choice_map = options._choice_map_validator
}
local printers =
{
string = options._string_printer, choice = options._choice_printer,
boolean = options._bool_printer, choice_map = options._choice_map_printer
}
if not validators[ opttype ] then
print( sf( "[builder] Invalid option type '%s'", opttype ) )
os.exit( 1 )
end
table.insert( self.options, { name = optname, help = help, validator = validators[ opttype ], printer = printers[ opttype ], data = data, default = default } )
end
-- Find an option with the given name
options._find_option = function( self, optname )
for i = 1, #self.options do
local o = self.options[ i ]
if o.name:upper() == optname:upper() then return self.options[ i ] end
end
end
-- 'add option' helper (automatically detects option type)
options.add_option = function( self, name, help, default, data )
local otype
if type( default ) == 'boolean' then
otype = 'boolean'
elseif data and type( data ) == 'table' and #data == 0 then
otype = 'choice_map'
elseif data and type( data ) == 'table' then
otype = 'choice'
data = linearize_array( data )
elseif type( default ) == 'string' then
otype = 'string'
else
print( sf( "Error: cannot detect option type for '%s'", name ) )
os.exit( 1 )
end
self:_add_option( name, otype, help, default, data )
end
options.get_num_opts = function( self )
return #self.options
end
options.get_option = function( self, i )
return self.options[ i ]
end
-- Handle an option of type 'key=value'
-- Returns both the key and the value or nil for error
options.handle_arg = function( self, a )
local si, ei, k, v = a:find( "([^=]+)=(.*)$" )
if not k or not v then
print( sf( "Error: invalid syntax in '%s'", a ) )
return
end
local opt = self:_find_option( k )
if not opt then
print( sf( "Error: invalid option '%s'", k ) )
return
end
local optv = opt.validator( v, opt.data )
if optv == nil then
print( sf( "Error: invalid value '%s' for option '%s'", v, k ) )
return
end
return k, optv
end
-- Show help for all the registered options
options.show_help = function( self )
for i = 1, #self.options do
local o = self.options[ i ]
print( sf( "\n %s: %s", o.name, o.help ) )
local values, default = o.printer( o )
if values then
print( sf( " Possible values: %s", values ) )
end
print( sf( " Default value: %s", default or "none (changes at runtime)" ) )
end
end
-- Create a new option handler
function options_handler()
return options.new()
end
| gpl-3.0 |
b03605079/darkstar | scripts/zones/Qufim_Island/npcs/Pitoire_RK.lua | 8 | 2941 | -----------------------------------
-- Area: Qufim Island
-- NPC: Pitoire, R.K.
-- Type: Outpost Conquest Guards
-- @pos -245.366 -20.344 299.502 126
-----------------------------------
package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Qufim_Island/TextIDs");
local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = QUFIMISLAND;
local csid = 0x7ffb;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if(supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if(arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
if(option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif(option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if(hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif(option == 4) then
if(player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
Aquanim/Zero-K | LuaUI/Widgets/gui_lups_stats.lua | 6 | 4453 | -- $Id: gui_lups_stats.lua 3171 2008-11-06 09:06:29Z det $
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- orig-file: gui_clock.lua
-- orig-file: gui_lups_stats.lua
-- brief: displays the current game time
-- author: jK (on code by trepan)
--
-- Copyright (C) 2007.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "LupsStats",
desc = "Shows some LUPS stats",
author = "jK",
date = "Dec, 2007",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = false -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
include("colors.lua")
local floor = math.floor
local vsx, vsy = widgetHandler:GetViewSizes()
-- the 'f' suffixes are fractions (and can be nil)
local color = { 1.0, 1.0, 1.0 }
local xposf = 0.99
local xpos = xposf * vsx
local yposf = 0.010
local ypos = yposf * vsy + 40
local sizef = 0.015
local size = sizef * vsy
local font = "LuaUI/Fonts/FreeSansBold_14"
local format = "orn"
local fh = (font ~= nil)
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Rendering
--
function widget:DrawScreen()
gl.Color(color)
local fxcount, fxlayers, fx = WG['Lups'].GetStats()
local totalParticles = (((fx['SimpleParticles'] or {})[2])or 0) + (((fx['NanoParticles'] or {})[2])or 0) + (((fx['StaticParticles'] or {})[2])or 0)
gl.Text("-LUPS Stats-", xpos, ypos+112, size, format)
gl.Text("particles: " .. totalParticles, xpos, ypos+90, size, format)
gl.Text("layers: " .. fxlayers, xpos, ypos+70, size, format)
gl.Text("effects: " .. fxcount, xpos, ypos+50, size, format)
gl.Color(1,1,1,1)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Geometry Management
--
local function UpdateGeometry()
-- use the fractions if available
xpos = (xposf and (xposf * vsx)) or xpos
ypos = (yposf and (yposf * vsy)) or ypos
size = (sizef and (sizef * vsy)) or size
-- negative values reference the right/top edges
xpos = (xpos < 0) and (vsx + xpos) or xpos
ypos = (ypos < 0) and (vsy + ypos) or ypos
end
UpdateGeometry()
function widget:ViewResize(viewSizeX, viewSizeY)
vsx = viewSizeX
vsy = viewSizeY
UpdateGeometry()
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Configuration routines
--
local function StoreGeoPair(tbl, fName, fValue, pName, pValue)
if (fValue) then
tbl[pName] = nil
tbl[fName] = fValue
else
tbl[pName] = pValue
tbl[fName] = nil
end
return
end
function widget:GetConfigData()
local tbl = {
color = color,
format = format,
font = font
}
StoreGeoPair(tbl, 'xposf', xposf, 'xpos', xpos)
StoreGeoPair(tbl, 'yposf', yposf, 'ypos', ypos)
StoreGeoPair(tbl, 'sizef', sizef, 'size', size)
return tbl
end
--------------------------------------------------------------------------------
-- returns a fraction,pixel pair
local function LoadGeoPair(tbl, fName, pName, oldPixelValue)
if (tbl[fName]) then return tbl[fName], 1
elseif (tbl[pName]) then return nil, tbl[pName]
else return nil, oldPixelValue
end
end
function widget:SetConfigData(data)
color = data.color or color
format = data.format or format
font = data.font or font
if (font) then
fh = fontHandler.UseFont(font)
end
xposf, xpos = LoadGeoPair(data, 'xposf', 'xpos', xpos)
yposf, ypos = LoadGeoPair(data, 'yposf', 'ypos', ypos)
sizef, size = LoadGeoPair(data, 'sizef', 'size', size)
UpdateGeometry()
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
b03605079/darkstar | scripts/zones/Northern_San_dOria/npcs/_6fc.lua | 21 | 1890 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Papal Chambers
-- Finish Mission: The Davoi Report
-- @pos 131 -11 122 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
package.loaded["scripts/globals/missions"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/keyitems");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getCurrentMission(SANDORIA) == THE_DAVOI_REPORT and player:hasKeyItem(TEMPLE_KNIGHTS_DAVOI_REPORT)) then
player:startEvent(0x02b7); -- Finish Mission "The Davoi Report"
elseif(player:getCurrentMission(SANDORIA,PRESTIGE_OF_THE_PAPSQUE) and player:getVar("MissionStatus") == 0)then
player:startEvent(0x0007);
elseif(player:getCurrentMission(SANDORIA,PRESTIGE_OF_THE_PAPSQUE) and player:getVar("MissionStatus") == 1)then
player:startEvent(0x0009);
elseif(player:getCurrentMission(SANDORIA,PRESTIGE_OF_THE_PAPSQUE) and player:hasKeyItem(ANCIENT_SANDORIAN_TABLET))then
player:startEvent(0x0008);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x02b7 or csid == 0x0007 or csid == 0x0008) then
finishMissionTimeline(player,3,csid,option);
end
end; | gpl-3.0 |
b03605079/darkstar | scripts/zones/Temenos/bcnms/Central_Temenos_4th_Floor.lua | 13 | 1399 | -----------------------------------
-- Area: Temenos
-- Name:
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
SetServerVariable("[C_Temenos_4th]UniqueID",GenerateLimbusKey());
HideArmouryCrates(GetInstanceRegion(1306),TEMENOS);
HideTemenosDoor(GetInstanceRegion(1306));
player:setVar("Limbus_Trade_Item-T",0);
if(GetMobAction(16928986) > 0)then DespawnMob(16928986);end
if(GetMobAction(16928987) > 0)then DespawnMob(16928987);end
if(GetMobAction(16928988) > 0)then DespawnMob(16928988);end
for n=16928991,16929003,1 do
if(GetMobAction(n) > 0)then DespawnMob(n);end
end
--print("spawn_coffer");
SpawnCofferTemenosCFloor4();
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
player:setVar("limbusbitmap",0);
player:setVar("characterLimbusKey",GetServerVariable("[C_Temenos_4th]UniqueID"));
player:setVar("LimbusID",1306);
player:delKeyItem(COSMOCLEANSE);
player:delKeyItem(WHITE_CARD);
end;
-- Leaving by every mean possible, given by the LeaveCode
-- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3)
-- 4=Finish he dynamis
function onBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if(leavecode == 4) then
player:setPos(580,-1.5,4.452,192);
ResetPlayerLimbusVariable(player)
end
end; | gpl-3.0 |
stevedonovan/Penlight | tests/test-utils2.lua | 1 | 2335 | local path = require 'pl.path'
local utils = require 'pl.utils'
local asserteq = require 'pl.test'.asserteq
local echo_lineending = "\n"
if path.is_windows then
echo_lineending = " \n"
end
local function test_executeex(cmd, expected_successful, expected_retcode, expected_stdout, expected_stderr)
--print("\n"..cmd)
--print(os.execute(cmd))
--print(utils.executeex(cmd))
local successful, retcode, stdout, stderr = utils.executeex(cmd)
asserteq(successful, expected_successful)
asserteq(retcode, expected_retcode)
asserteq(stdout, expected_stdout)
asserteq(stderr, expected_stderr)
end
-- Check the return codes
if utils.is_windows then
test_executeex("exit", true, 0, "", "")
test_executeex("exit 0", true, 0, "", "")
test_executeex("exit 1", false, 1, "", "")
test_executeex("exit 13", false, 13, "", "")
test_executeex("exit 255", false, 255, "", "")
test_executeex("exit 256", false, 256, "", "")
test_executeex("exit 257", false, 257, "", "")
test_executeex("exit 3809", false, 3809, "", "")
test_executeex("exit -1", false, -1, "", "")
test_executeex("exit -13", false, -13, "", "")
test_executeex("exit -255", false, -255, "", "")
test_executeex("exit -256", false, -256, "", "")
test_executeex("exit -257", false, -257, "", "")
test_executeex("exit -3809", false, -3809, "", "")
else
test_executeex("exit", true, 0, "", "")
test_executeex("exit 0", true, 0, "", "")
test_executeex("exit 1", false, 1, "", "")
test_executeex("exit 13", false, 13, "", "")
test_executeex("exit 255", false, 255, "", "")
-- on posix anything other than 0-255 is undefined
test_executeex("exit 256", true, 0, "", "")
test_executeex("exit 257", false, 1, "", "")
test_executeex("exit 3809", false, 225, "", "")
end
-- Check output strings
test_executeex("echo stdout", true, 0, "stdout" .. echo_lineending, "")
test_executeex("(echo stderr 1>&2)", true, 0, "", "stderr" .. echo_lineending)
test_executeex("(echo stdout && (echo stderr 1>&2))", true, 0, "stdout" .. echo_lineending, "stderr" .. echo_lineending)
| mit |
b03605079/darkstar | scripts/zones/Caedarva_Mire/npcs/Nahshib.lua | 12 | 1969 | -----------------------------------
-- Area: Caedarva Mire
-- NPC: Nahshib
-- Type: Assault
-- @pos -274.334 -9.287 -64.255 79
-----------------------------------
package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/keyitems");
require("scripts/zones/Caedarva_Mire/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local IPpoint = player:getCurrency("imperial_standing");
if (player:getCurrentMission(TOAU) == IMMORTAL_SENTRIES) then
if(player:hasKeyItem(SUPPLIES_PACKAGE))then
player:startEvent(0x0005);
elseif(player:getVar("TOAUM2") == 1)then
player:startEvent(0x0006);
end
elseif(player:getCurrentMission(TOAU) >= PRESIDENT_SALAHEEM)then
if(player:hasKeyItem(PERIQIA_ASSAULT_ORDERS) and player:hasKeyItem(ASSAULT_ARMBAND) == false) then
player:startEvent(0x0094,50,IPpoint);
else
player:startEvent(0x0007);
-- player:delKeyItem(ASSAULT_ARMBAND);
end
else
player:startEvent(0x0004);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x0094 and option == 1) then
player:delCurrency("imperial_standing", 50);
player:addKeyItem(ASSAULT_ARMBAND);
player:messageSpecial(KEYITEM_OBTAINED,ASSAULT_ARMBAND);
elseif(csid == 0x0005 and option == 1)then
player:delKeyItem(SUPPLIES_PACKAGE);
player:setVar("TOAUM2",1);
end
end; | gpl-3.0 |
AitorATuin/exercism | bin/add_gitattributes.lua | 1 | 3184 | #!/bin/lua
local GIT_ATTR_FILE = ".gitattributes"
--
-- lang/exercise/exercise.lua filter=git-crypt diff=git-crypt
local GIT_ATTR_REGEX = "([^/]+)/([^/]+)/([^/]+)%.(%w+) filter%=git%-crypt diff%=git%-crypt"
local function file_to_gitattribute(file)
return string.format("%s/%s/%s.%s filter=git-crypt diff=git-crypt", file.lang,
file.exercise, file.filename, file.ext)
end
local function get_files_added()
local files_added = {}
local fd = io.open(GIT_ATTR_FILE, "r")
-- We search for pattern:
for line in fd:lines() do
line:gsub(GIT_ATTR_REGEX, function(lang, exercise, filename, ext)
file = {
lang = lang,
exercise = exercise,
filename = filename,
ext = ext
}
files_added[file_to_gitattribute(file)] = true
end)
end
fd:close()
return files_added
end
local function norm_str(filename)
return filename:gsub("-", "_")
end
local function get_files_in_exercise(lang, exercise)
return function()
local pipe = io.popen(string.format("ls %s/%s", lang, exercise))
local files_to_add = {}
for line in pipe:lines() do
for filename, ext in line:gmatch("([^%.]+).(%w+)") do
if norm_str(exercise) == norm_str(filename) then
local file = {
lang = lang,
exercise = exercise,
filename = filename,
ext = ext
}
coroutine.yield(file)
end
end
end
pipe:close()
end
end
local function get_exercises(lang)
return function()
local exercises = {}
local pipe = io.popen(string.format("ls %s", lang))
for line in pipe:lines() do
for exercise in line:gmatch("(%g+)") do
coroutine.yield(exercise)
end
end
pipe:close()
end
end
local co_iter = function(co)
local co = coroutine.create(co)
return function()
local code, value = coroutine.resume(co)
return value
end
end
local function stage_gitattributes(commit_msg, dry_run)
local f = os.execute
if dry_run then
f = print
end
f("git add " .. GIT_ATTR_FILE)
f("git commit -m \"Add gitattributes for:" .. commit_msg .. "\"")
end
local function add_to_gitattributes(fd, entry, dry_run)
if not dry_run then
fd:write(entry)
end
end
local function main(...)
local langs = arg
if #langs == 0 then
os.exit(1)
end
local DRY_RUN = os.getenv("DRY_RUN") ~= nil
local files_added = get_files_added()
local fd = io.open(GIT_ATTR_FILE, "a")
local commit_msg = ""
for _, lang in ipairs(langs) do
for exercise in co_iter(get_exercises(lang)) do
for file in co_iter(get_files_in_exercise(lang, exercise)) do
local file_gitattributed = file_to_gitattribute(file)
if not files_added[file_gitattributed] then
print(string.format("- Add: %s", file_gitattributed))
add_to_gitattributes(fd, file_gitattributed .. "\n", DRY_RUN)
commit_msg = string.format("%s\n - %s", commit_msg, file_gitattributed)
end
end
end
end
fd:close()
if #commit_msg > 0 then
print("Stagging " .. GIT_ATTR_FILE .. " ...")
stage_gitattributes(commit_msg, DRY_RUN)
end
end
main(...)
| gpl-3.0 |
b03605079/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Hadayah.lua | 10 | 1760 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Hadayah
-- Type: Alchemy Image Support
-- @pos -10.470 -6.25 -141.700 241
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/status");
require("scripts/globals/crafting");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,1);
local SkillLevel = player:getSkillLevel(2);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_ALCHEMY_IMAGERY) == false) then
player:startEvent(0x027E,4,SkillLevel,1,511,187,0,7,2184);
else
player:startEvent(0x027E,4,SkillLevel,1,511,5662,6955,7,2184);
end
else
player:startEvent(0x027E,0,0,0,0,0,0,7,0); -- Standard Dialogue
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x027E and option == 1) then
player:messageSpecial(ALCHEMY_SUPPORT,0,7,1);
player:addStatusEffect(EFFECT_ALCHEMY_IMAGERY,1,0,120);
end
end;
| gpl-3.0 |
felipeprov/premake-core | tests/base/test_table.lua | 18 | 1436 | --
-- tests/base/test_table.lua
-- Automated test suite for the new table functions.
-- Copyright (c) 2008-2013 Jason Perkins and the Premake project
--
local suite = test.declare("table")
local t
--
-- table.contains() tests
--
function suite.contains_OnContained()
t = { "one", "two", "three" }
test.istrue( table.contains(t, "two") )
end
function suite.contains_OnNotContained()
t = { "one", "two", "three" }
test.isfalse( table.contains(t, "four") )
end
--
-- table.flatten() tests
--
function suite.flatten_OnMixedValues()
t = { "a", { "b", "c" }, "d" }
test.isequal({ "a", "b", "c", "d" }, table.flatten(t))
end
--
-- table.implode() tests
--
function suite.implode()
t = { "one", "two", "three", "four" }
test.isequal("[one], [two], [three], [four]", table.implode(t, "[", "]", ", "))
end
--
-- table.indexof() tests
--
function suite.indexof_returnsIndexOfValueFound()
local idx = table.indexof({ "a", "b", "c" }, "b")
test.isequal(2, idx)
end
--
-- table.isempty() tests
--
function suite.isempty_ReturnsTrueOnEmpty()
test.istrue(table.isempty({}))
end
function suite.isempty_ReturnsFalseOnNotEmpty()
test.isfalse(table.isempty({ 1 }))
end
function suite.isempty_ReturnsFalseOnNotEmptyMap()
test.isfalse(table.isempty({ name = 'premake' }))
end
function suite.isempty_ReturnsFalseOnNotEmptyMapWithFalseKey()
test.isfalse(table.isempty({ [false] = 0 }))
end
| bsd-3-clause |
b03605079/darkstar | scripts/zones/AlTaieu/npcs/HomePoint#1.lua | 3 | 1161 | -----------------------------------
-- Area: AlTaieu
-- NPC: HomePoint#1
-- @pos
-----------------------------------
package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/AlTaieu/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 85);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
b03605079/darkstar | scripts/zones/Temenos/mobs/Airi.lua | 17 | 1277 | -----------------------------------
-- Area: Temenos Central 1floor
-- NPC: Airi
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if(IsMobDead(16929047)==true)then
mob:addStatusEffect(EFFECT_REGAIN,7,3,0);
mob:addStatusEffect(EFFECT_REGEN,50,3,0);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
if(IsMobDead(16929046)==true and IsMobDead(16929047)==true and IsMobDead(16929048)==true and IsMobDead(16929049)==true and IsMobDead(16929050)==true and IsMobDead(16929051)==true)then
GetNPCByID(16928768+71):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+71):setStatus(STATUS_NORMAL);
GetNPCByID(16928770+471):setStatus(STATUS_NORMAL);
end
end;
| gpl-3.0 |
b03605079/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Nivorajean.lua | 38 | 1048 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Nivorajean
-- Type: Standard NPC
-- @zone: 26
-- @pos 15.890 -22.999 13.322
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00dd);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
AdventureZ/mta_dayz_new_gamemode2015 | DayZ/group_system/gang_server.lua | 1 | 8482 |
invitations = {}
addEventHandler("onResourceStart", resourceRoot, function()
local columnName = get("column_name")
exports.scoreboard:scoreboardAddColumn("gang", root, columnName:len() * 12, columnName)
executeSQLCreateTable("gangs", "gang_name STRING, gang_leader STRING, gang_members, gang_subleaders STRING")
executeSQLCreateTable("gang_members", "gang_name STRING, member_account STRING, added_by STRING")
checkPlayerGroupDetails()
for index,player in ipairs(getElementsByType("player")) do
local gang = getAccountGang(getAccountName(getPlayerAccount(player)))
setElementData(player, "gang", gang)
end
end
)
addEventHandler("onPlayerLogin", root, function(_, account)
local gang = getAccountGang(getAccountName(account))
setElementData(source, "gang", gang)
end
)
showGangPanel = function(thePlayer)
local gangName = getElementData(thePlayer, "gang")
if gangName ~= "None" then
local memberList = getGangMembers(gangName)
triggerClientEvent(thePlayer, "gangSystem:openGangPanel", thePlayer, memberList)
end
end
addCommandHandler(get("gang_list_command"), function(thePlayer)
local gangList = getGangList()
if gangList and #gangList > 0 then
triggerClientEvent(thePlayer, "gangSystem:openGangList", thePlayer, gangList)
end
end
)
addEvent("gangSystem:invitePlayer", true)
addEventHandler("gangSystem:invitePlayer", root, function(playerName)
local gangName = getElementData(source, "gang")
local accountName = getAccountName(getPlayerAccount(source))
local player = getPlayerFromNamePart(playerName)
if getGangLeader(gangName) == accountName or isGangSubLeader(gangName, accountName) then
if player and isElement(player) then
local playerAccountName = getAccountName(getPlayerAccount(player))
if getAccountGang(gangName, playerAccountName) == "None" then
invitations[player] = {gangName, source}
outputChatBox("Gang system: You have invited " .. getPlayerName(player) .. " to the gang.", source, 0, 255, 0)
outputChatBox("Gang system: You have been invited to " .. gangName .. ", write /accept to join.", player, 0, 255, 0)
else
outputChatBox("Gang system: This player is already in a gang!", source, 255, 0, 0)
end
else
outputChatBox("Gang system: " .. playerName .. " matches no players!", source, 255, 0, 0)
end
else
outputChatBox("Gang system: You're not allowed to use this function.", source, 255, 0, 0)
end
end
)
addCommandHandler(get("gang_create_command"), function(thePlayer, command, ...)
local accountName = getAccountName(getPlayerAccount(thePlayer))
local gangName = table.concat({...}, " ")
if gangName and gangName ~= "" then
local added, errorMsg = addGang(gangName, accountName)
if added then
outputChatBox("Gang created: Gang name: " .. gangName .. "!", thePlayer, 0, 255, 0)
end
else
outputChatBox("Gang error: " .. errorMsg .. "!", thePlayer, 255, 0, 0)
end
end
)
addEvent("gangSystem:kickMember", true)
addEventHandler("gangSystem:kickMember", root, function(memberAccount)
local gangName = getElementData(source, "gang")
local accountName = getAccountName(getPlayerAccount(source))
-- DECOMPILER ERROR: unhandled construct in 'if'
if gangName ~= "None" and (getGangLeader(gangName) == accountName or isGangSubLeader(gangName, accountName)) and getGangLeader(gangName) ~= memberAccount and removeGangMember(gangName, memberAccount, getPlayerName(source)) then
outputChatBox("Gang system: You have kicked " .. memberAccount .. " from the gang.", source, 255, 50, 0)
end
do return end
outputChatBox("Gang system: You can't kick the gang leader.", source, 255, 0, 0)
do return end
outputChatBox("Gang system: You're not allowed to use this function.", source, 255, 0, 0)
end
)
addEvent("gangSystem:leaveGang", true)
addEventHandler("gangSystem:leaveGang", root, function()
local gangName = getElementData(source, "gang")
local accountName = getAccountName(getPlayerAccount(source))
-- DECOMPILER ERROR: unhandled construct in 'if'
if gangName ~= "None" and accountName ~= "Guest" and getGangLeader(gangName) ~= accountName and removeGangMember(gangName, accountName) then
outputChatBox("Gang system: You have left " .. gangName .. ".", source, 255, 50, 0)
end
do return end
outputChatBox("Gang system: You may not leave the gang as you're the leader of it.", source, 255, 0, 0)
end
)
addEvent("gangSystem:destroyGang", true)
addEventHandler("gangSystem:destroyGang", root, function()
local gangName = getElementData(source, "gang")
local accountName = getAccountName(getPlayerAccount(source))
-- DECOMPILER ERROR: unhandled construct in 'if'
if gangName ~= "None" and accountName ~= "Guest" and getGangLeader(gangName) == accountName and removeGang(gangName) then
outputChatBox("Gang system: You have destroyed the gang " .. gangName .. ".", source, 255, 50, 0)
end
do return end
outputChatBox("Gang system: You're not allowed to use this function.", source, 255, 0, 0)
end
)
addCommandHandler("accept", function(thePlayer)
local invited, theGang, inviter = isPlayerGangInvited(thePlayer)
if invited then
addGangMember(theGang, getAccountName(getPlayerAccount(thePlayer)), getAccountName(getPlayerAccount(inviter)))
outputChatBox("Gang system: Welcome to " .. tostring(theGang) .. "!", thePlayer, 0, 255, 0)
for index,player in pairs(getPlayersByGang(theGang)) do
outputChatBox("Gang system: " .. getPlayerName(thePlayer) .. " has joined the gang!", player, 0, 255, 0)
end
invitations[thePlayer] = false
end
end
)
addEvent("onPlayerJoinGang", true)
addEventHandler("onPlayerJoinGang", root, function(gangName)
if doesGangExists(gangName) then
executeSQLUpdate("gangs", "gang_members = '" .. #getGangMembers(gangName) + 1 .. "'", "gang_name = '" .. tostring(gangName) .. "'")
end
end
)
addEvent("onPlayerLeaveGang", true)
addEventHandler("onPlayerLeaveGang", root, function(gangName)
if doesGangExists(gangName) then
executeSQLUpdate("gangs", "gang_members = '" .. #getGangMembers(gangName) - 1 .. "'", "gang_name = '" .. tostring(gangName) .. "'")
end
end
)
addEvent("gangSystem:getSubLeaders", true)
addEventHandler("gangSystem:getSubLeaders", root, function()
local gangName = getElementData(source, "gang")
if gangName and gangName ~= "None" then
local subLeaders = getGangSubLeaders(gangName)
triggerClientEvent(source, "gangSystem:returnSubLeaders", source, subLeaders)
end
end
)
addEvent("gangSystem:addSubLeader", true)
addEventHandler("gangSystem:addSubLeader", root, function(memberAccount)
local gangName = getElementData(source, "gang")
local accountName = getAccountName(getPlayerAccount(source))
if gangName ~= "None" and accountName ~= "Guest" then
if getGangLeader(gangName) == accountName then
local isSubLeader, errorMsg = isGangSubLeader(gangName, memberAccount)
if not isSubLeader then
if editGangSubLeaders(gangName, memberAccount, true) then
outputChatBox("Gang system: You have added " .. memberAccount .. " as a sub leader.", source, 0, 255, 0)
end
else
outputChatBox("Gang system: " .. tostring(errorMsg), source, 255, 50, 0)
end
else
outputChatBox("Gang system: This member is already a sub leader.", source, 255, 50, 0)
end
else
outputChatBox("Gang system: You're not allowed to use this function.", source, 255, 0, 0)
end
end
)
addEvent("gangSystem:removeSubLeader", true)
addEventHandler("gangSystem:removeSubLeader", root, function(memberAccount)
local gangName = getElementData(source, "gang")
local accountName = getAccountName(getPlayerAccount(source))
if gangName ~= "None" and accountName ~= "Guest" then
if getGangLeader(gangName) == accountName then
local isSubLeader, errorMsg = isGangSubLeader(gangName, memberAccount)
if isSubLeader then
if editGangSubLeaders(gangName, memberAccount, false) then
triggerEvent("gangSystem:getSubLeaders", source)
outputChatBox("Gang system: You have removed " .. memberAccount .. " from a sub leaders.", source, 255, 50, 0)
end
else
outputChatBox("Gang system: " .. tostring(errorMsg), source, 255, 50, 0)
end
else
outputChatBox("Gang system: " .. tostring(errorMsg), source, 255, 50, 0)
end
else
outputChatBox("Gang system: You're not allowed to use this function.", source, 255, 0, 0)
end
end
)
| epl-1.0 |
b03605079/darkstar | scripts/zones/Korroloka_Tunnel/MobIDs.lua | 65 | 1094 | -----------------------------------
-- Area: Korroloka Tunnel (173)
-- Comments: -- posX, posY, posZ
-- (Taken from 'mob_spawn_points' table)
-----------------------------------
-- Cargo_Crab_Colin
Cargo_Crab_Colin=17485980;
Cargo_Crab_Colin_PH={
[17486002] = '1', -- -30.384, 1.000, -33.277
[17486095] = '1' -- -85.000, -0.500, -37.000
};
-- Dame_Blanche
Dame_Blanche=17486129;
Dame_Blanche_PH={
[17486128] = '1', -- -345.369, 0.716, 119.486
[17486127] = '1', -- -319.266, -0.244, 130.650
[17486126] = '1', -- -319.225, -0.146, 109.776
[17486124] = '1', -- -296.821, -3.207, 131.239
[17486125] = '1', -- -292.487, -5.993, 141.408
[17486119] = '1', -- -277.338, -9.352, 139.763
[17486118] = '1' -- -276.713, -9.954, 135.353
};
-- Falcatus_Aranei
Falcatus_Aranei=17486031;
Falcatus_Aranei_PH={
[17486033] = '1', -- -68.852, -5.029, 141.069
[17486032] = '1', -- -94.545, -6.095, 136.480
[17486034] = '1', -- -79.827, -6.046, 133.982
[17486027] = '1', -- -25.445, -6.073, 142.192
[17486028] = '1' -- -33.446, -6.038, 141.987
};
| gpl-3.0 |
lynnchurch/CocosLearning | HelloCC/cocos2d/plugin/luabindings/auto/api/lua_cocos2dx_pluginx_auto_api.lua | 146 | 1793 | --------------------------------
-- @module plugin
--------------------------------------------------------
-- the plugin PluginProtocol
-- @field [parent=#plugin] PluginProtocol#PluginProtocol PluginProtocol preloaded module
--------------------------------------------------------
-- the plugin PluginManager
-- @field [parent=#plugin] PluginManager#PluginManager PluginManager preloaded module
--------------------------------------------------------
-- the plugin ProtocolAnalytics
-- @field [parent=#plugin] ProtocolAnalytics#ProtocolAnalytics ProtocolAnalytics preloaded module
--------------------------------------------------------
-- the plugin ProtocolIAP
-- @field [parent=#plugin] ProtocolIAP#ProtocolIAP ProtocolIAP preloaded module
--------------------------------------------------------
-- the plugin ProtocolAds
-- @field [parent=#plugin] ProtocolAds#ProtocolAds ProtocolAds preloaded module
--------------------------------------------------------
-- the plugin ProtocolShare
-- @field [parent=#plugin] ProtocolShare#ProtocolShare ProtocolShare preloaded module
--------------------------------------------------------
-- the plugin ProtocolSocial
-- @field [parent=#plugin] ProtocolSocial#ProtocolSocial ProtocolSocial preloaded module
--------------------------------------------------------
-- the plugin ProtocolUser
-- @field [parent=#plugin] ProtocolUser#ProtocolUser ProtocolUser preloaded module
--------------------------------------------------------
-- the plugin AgentManager
-- @field [parent=#plugin] AgentManager#AgentManager AgentManager preloaded module
--------------------------------------------------------
-- the plugin FacebookAgent
-- @field [parent=#plugin] FacebookAgent#FacebookAgent FacebookAgent preloaded module
return nil
| apache-2.0 |
immibis/wiremod | lua/wire/stools/target_finder.lua | 9 | 7624 | WireToolSetup.setCategory( "Detection/Beacon" )
WireToolSetup.open( "target_finder", "Target Finder", "gmod_wire_target_finder", nil, "Target Finders" )
if CLIENT then
language.Add( "Tool.wire_target_finder.name", "Target Finder Beacon Tool (Wire)" )
language.Add( "Tool.wire_target_finder.desc", "Spawns a target finder beacon for use with the wire system." )
language.Add( "Tool.wire_target_finder.0", "Primary: Create/Update Target Finder Beacon" )
language.Add( "WireTargetFinderTool_minrange", "Minimum Range:" )
language.Add( "WireTargetFinderTool_maxrange", "Maximum Range:" )
language.Add( "WireTargetFinderTool_maxtargets", "Maximum number of targets to track:" )
language.Add( "WireTargetFinderTool_MaxBogeys", "Max number of bogeys (closest):" )
language.Add( "WireTargetFinderTool_MaxBogeys_desc", "Set to 0 for all within range, this needs to be atleast as many as Max Targets." )
language.Add( "WireTargetFinderTool_players", "Target players" )
language.Add( "WireTargetFinderTool_notowner", "Do not target owner" )
language.Add( "WireTargetFinderTool_notownersstuff", "Do not target owner's stuff" )
language.Add( "WireTargetFinderTool_npcs", "Target NPCs" )
language.Add( "WireTargetFinderTool_npcname", "NPC Filter:" )
language.Add( "WireTargetFinderTool_beacons", "Target Locators" )
language.Add( "WireTargetFinderTool_hoverballs", "Target Hoverballs" )
language.Add( "WireTargetFinderTool_thrusters", "Target Thrusters" )
language.Add( "WireTargetFinderTool_props", "Target Props" )
language.Add( "WireTargetFinderTool_propmodel", "Prop Model Filter:" )
language.Add( "WireTargetFinderTool_vehicles", "Target Vehicles" )
language.Add( "WireTargetFinderTool_rpgs", "Target RPGs" )
language.Add( "WireTargetFinderTool_PaintTarget", "Paint Target" )
language.Add( "WireTargetFinderTool_PaintTarget_desc", "Paints currently selected target(s)." )
language.Add( "WireTargetFinderTool_casesen", "Case Sensitive" )
language.Add( "WireTargetFinderTool_playername", "Name Filter:" )
language.Add( "WireTargetFinderTool_entity", "Entity Name:" )
language.Add( "WireTargetFinderTool_steamname", "SteamID Filter:" )
language.Add( "WireTargetFinderTool_colorcheck", "Color Filter")
language.Add( "WireTargetFinderTool_colortarget", "Color Target/Skip")
language.Add( "WireTargetFinderTool_pcolR", "Red:")
language.Add( "WireTargetFinderTool_pcolG", "Green:")
language.Add( "WireTargetFinderTool_pcolB", "Blue:")
language.Add( "WireTargetFinderTool_pcolA", "Alpha:")
language.Add( "WireTargetFinderTool_checkbuddylist", "Check Propprotection Buddy List (EXPERIMENTAL!)" )
language.Add( "WireTargetFinderTool_onbuddylist", "Target Only Buddys (EXPERIMENTAL!)" )
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax( 20 )
if SERVER then
ModelPlug_Register("Numpad")
CreateConVar("wire_target_finders_maxtargets",10)
CreateConVar("wire_target_finders_maxbogeys",30)
function TOOL:GetConVars()
return self:GetClientNumber("maxrange"), self:GetClientNumber("players") ~= 0, self:GetClientNumber("npcs") ~= 0, self:GetClientInfo("npcname"),
self:GetClientNumber("beacons") ~= 0, self:GetClientNumber("hoverballs") ~= 0, self:GetClientNumber("thrusters") ~= 0, self:GetClientNumber("props") ~= 0,
self:GetClientInfo("propmodel"), self:GetClientNumber("vehicles") ~= 0, self:GetClientInfo("playername"), self:GetClientNumber("casesen") ~= 0,
self:GetClientNumber("rpgs") ~= 0, self:GetClientNumber("painttarget") ~= 0, self:GetClientNumber("minrange"), self:GetClientNumber("maxtargets"),
self:GetClientNumber("maxbogeys"), self:GetClientNumber("notargetowner") != 0, self:GetClientInfo("entityfil"), self:GetClientNumber("notownersstuff") != 0,
self:GetClientInfo("steamname"), (self:GetClientNumber("colorcheck") ~= 0), (self:GetClientNumber("colortarget") ~= 0),
self:GetClientNumber("pcolR"), self:GetClientNumber("pcolG"), self:GetClientNumber("pcolB"), self:GetClientNumber("pcolA"),
self:GetClientNumber("checkbuddylist") != 0, self:GetClientNumber("onbuddylist") != 0
end
end
TOOL.ClientConVar = {
model = "models/beer/wiremod/targetfinder.mdl",
modelsize = "",
minrange = 1,
maxrange = 1000,
players = 0,
npcs = 1,
npcname = "",
beacons = 0,
hoverballs = 0,
thrusters = 0,
props = 0,
propmodel = "",
vehicles = 0,
playername = "",
steamname = "",
colorcheck = 0,
colortarget = 0,
pcolR = 255,
pcolG = 255,
pcolB = 255,
pcolA = 255,
casesen = 0,
rpgs = 0,
painttarget = 1,
maxtargets = 1,
maxbogeys = 1,
notargetowner = 0,
notownersstuff = 0,
entityfil = "",
checkbuddylist = 0,
onbuddylist = 0,
}
function TOOL:Reload(trace)
if trace.Entity:IsValid() then
self:GetOwner():ConCommand("wire_target_finder_entityfil "..trace.Entity:GetClass().."\n")
else
self:GetOwner():ConCommand("wire_target_finder_entityfil \n")
end
return true
end
function TOOL.BuildCPanel(panel)
WireToolHelpers.MakePresetControl(panel, "wire_target_finder")
WireToolHelpers.MakeModelSizer(panel, "wire_target_finder_modelsize")
ModelPlug_AddToCPanel(panel, "TargetFinder", "wire_target_finder", true, 1)
panel:NumSlider("#WireTargetFinderTool_minrange","wire_target_finder_minrange",1,10000,0)
panel:NumSlider("#WireTargetFinderTool_maxrange","wire_target_finder_maxrange",1,10000,0)
panel:NumSlider("#WireTargetFinderTool_maxtargets","wire_target_finder_maxtargets",1,10,0)
panel:NumSlider("#WireTargetFinderTool_MaxBogeys","wire_target_finder_maxbogeys",0,30,0)
panel:NumSlider("#WireTargetFinderTool_minrange","wire_target_finder_minrange",1,1000,0)
panel:CheckBox( "#WireTargetFinderTool_players","wire_target_finder_players")
panel:CheckBox( "#WireTargetFinderTool_notowner","wire_target_finder_notargetowner")
panel:CheckBox( "#WireTargetFinderTool_notownersstuff","wire_target_finder_notownersstuff")
panel:CheckBox( "#WireTargetFinderTool_npcs","wire_target_finder_npcs")
panel:TextEntry("#WireTargetFinderTool_npcname","wire_target_finder_npcname")
panel:CheckBox( "#WireTargetFinderTool_beacons","wire_target_finder_beacons")
panel:CheckBox( "#WireTargetFinderTool_hoverballs","wire_target_finder_hoverballs")
panel:CheckBox( "#WireTargetFinderTool_thrusters","wire_target_finder_thrusters")
panel:CheckBox( "#WireTargetFinderTool_props","wire_target_finder_props")
panel:TextEntry("#WireTargetFinderTool_propmodel","wire_target_finder_propmodel")
panel:CheckBox( "#WireTargetFinderTool_vehicles","wire_target_finder_vehicles")
panel:CheckBox( "#WireTargetFinderTool_rpgs","wire_target_finder_rpgs")
panel:CheckBox( "#WireTargetFinderTool_PaintTarget","wire_target_finder_painttarget")
panel:CheckBox( "#WireTargetFinderTool_casesen","wire_target_finder_casesen")
panel:TextEntry("#WireTargetFinderTool_playername","wire_target_finder_playername")
panel:TextEntry("#WireTargetFinderTool_entity","wire_target_finder_entityfil")
panel:TextEntry("#WireTargetFinderTool_steamname","wire_target_finder_steamname")
panel:CheckBox( "#WireTargetFinderTool_colorcheck","wire_target_finder_colorcheck")
panel:CheckBox( "#WireTargetFinderTool_colortarget","wire_target_finder_colortarget")
panel:NumSlider("#WireTargetFinderTool_pcolR","wire_target_finder_pcolR",0,255,0)
panel:NumSlider("#WireTargetFinderTool_pcolG","wire_target_finder_pcolG",0,255,0)
panel:NumSlider("#WireTargetFinderTool_pcolB","wire_target_finder_pcolB",0,255,0)
panel:NumSlider("#WireTargetFinderTool_pcolA","wire_target_finder_pcolA",0,255,0)
panel:CheckBox( "#WireTargetFinderTool_checkbuddylist","wire_target_finder_checkbuddylist")
panel:CheckBox( "#WireTargetFinderTool_onbuddylist","wire_target_finder_onbuddylist")
end
| apache-2.0 |
b03605079/darkstar | scripts/zones/Quicksand_Caves/npcs/_5sb.lua | 19 | 1272 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Ornate Door
-- Door blocked by Weight system
-- @pos -420 0 735 208
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local difX = player:getXPos()-(-420);
local difZ = player:getZPos()-(726);
local Distance = math.sqrt( math.pow(difX,2) + math.pow(difZ,2) );
if(Distance < 3) then
return -1;
end
player:messageSpecial(DOOR_FIRMLY_SHUT);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Aquanim/Zero-K | LuaUI/Widgets/gfx_bloom_shader.lua | 6 | 17756 | function widget:GetInfo()
return {
name = "Bloom Shader",
desc = "Sets Spring In Bloom",
author = "Floris", -- orginal bloom shader: Kloot
date = "24-9-2016",
license = "",
layer = 9,
enabled = false,
}
end
--------------------------------------------------------------------------------
-- config
--------------------------------------------------------------------------------
local basicAlpha = 0.4
local drawHighlights = false -- apply extra bloom bright spots (note: quite costly)
local highlightsAlpha = 0.35
local dbgDraw = 0 -- debug: draw only the bloom-mask?
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local drawWorldAlpha = 0
local drawWorldPreUnitAlpha = 0
local usedBasicAlpha = basicAlpha
local camX, camY, camZ = Spring.GetCameraPosition()
local camDirX,camDirY,camDirZ = Spring.GetCameraDirection()
-- shader and texture handles
local blurShaderH71 = nil
local blurShaderV71 = nil
local brightShader = nil
local brightTexture1 = nil
local brightTexture2 = nil
local brightTexture3 = nil
local brightTexture4 = nil
local combineShader = nil
local screenTexture = nil
local screenTextureQuarter = nil
local screenTextureSixteenth = nil
-- speedups
local glCreateTexture = gl.CreateTexture
local glActiveTexture = gl.ActiveTexture
local glCopyToTexture = gl.CopyToTexture
local glRenderToTexture = gl.RenderToTexture
local glTexture = gl.Texture
local glTexRect = gl.TexRect
local glUseShader = gl.UseShader
local glUniformInt = gl.UniformInt
local glUniform = gl.Uniform
local glGetUniformLocation = gl.GetUniformLocation
local glGetActiveUniforms = gl.GetActiveUniforms
local GL_RGBA32F_ARB = 0x8814
local GL_RGB32F_ARB = 0x8815
local GL_ALPHA32F_ARB = 0x8816
local GL_INTENSITY32F_ARB = 0x8817
local GL_LUMINANCE32F_ARB = 0x8818
local GL_LUMINANCE_ALPHA32F_ARB = 0x8819
local GL_RGBA16F_ARB = 0x881A
local GL_RGB16F_ARB = 0x881B
local GL_ALPHA16F_ARB = 0x881C
local GL_INTENSITY16F_ARB = 0x881D
local GL_LUMINANCE16F_ARB = 0x881E
local GL_LUMINANCE_ALPHA16F_ARB = 0x881F
local GL_TEXTURE_RED_TYPE_ARB = 0x8C10
local GL_TEXTURE_GREEN_TYPE_ARB = 0x8C11
local GL_TEXTURE_BLUE_TYPE_ARB = 0x8C12
local GL_TEXTURE_ALPHA_TYPE_ARB = 0x8C13
local GL_TEXTURE_LUMINANCE_TYPE_ARB = 0x8C14
local GL_TEXTURE_INTENSITY_TYPE_ARB = 0x8C15
local GL_TEXTURE_DEPTH_TYPE_ARB = 0x8C16
local GL_UNSIGNED_NORMALIZED_ARB = 0x8C17
-- shader uniform locations
local brightShaderText0Loc = nil
local brightShaderInvRXLoc = nil
local brightShaderInvRYLoc = nil
local brightShaderIllumLoc = nil
local blurShaderH51Text0Loc = nil
local blurShaderH51InvRXLoc = nil
local blurShaderH51FragLoc = nil
local blurShaderV51Text0Loc = nil
local blurShaderV51InvRYLoc = nil
local blurShaderV51FragLoc = nil
local blurShaderH71Text0Loc = nil
local blurShaderH71InvRXLoc = nil
local blurShaderH71FragLoc = nil
local blurShaderV71Text0Loc = nil
local blurShaderV71InvRYLoc = nil
local blurShaderV71FragLoc = nil
local combineShaderDebgDrawLoc = nil
local combineShaderTexture0Loc = nil
local combineShaderTexture1Loc = nil
local combineShaderIllumLoc = nil
local combineShaderFragLoc = nil
local illumThreshold = 0.33
local function SetIllumThreshold()
local ra, ga, ba = gl.GetSun("ambient")
local rd, gd, bd = gl.GetSun("diffuse")
local rs, gs, bs = gl.GetSun("specular")
local ambientIntensity = ra * 0.299 + ga * 0.587 + ba * 0.114
local diffuseIntensity = rd * 0.299 + gd * 0.587 + bd * 0.114
local specularIntensity = rs * 0.299 + gs * 0.587 + bs * 0.114
--Spring.Echo(ambientIntensity..' '..diffuseIntensity..' '..specularIntensity)
illumThreshold = (0.33 * ambientIntensity) + (0.05 * diffuseIntensity) + (0.05 * specularIntensity)
end
local function RemoveMe(msg)
Spring.Echo(msg)
--widgetHandler:RemoveWidget(self)
end
function reset()
--if not initialized then return end
if drawHighlights then
usedBasicAlpha = basicAlpha
drawWorldAlpha = 0.2 - (illumThreshold*0.4) + (usedBasicAlpha/11) + (0.018 * highlightsAlpha)
drawWorldPreUnitAlpha = 0.16 - (illumThreshold*0.4) + (usedBasicAlpha/6.2) + (0.023 * highlightsAlpha)
else
usedBasicAlpha = basicAlpha
drawWorldAlpha = 0.035 + (usedBasicAlpha/11)
drawWorldPreUnitAlpha = 0.2 - (illumThreshold*0.4) + (usedBasicAlpha/6)
end
gl.DeleteTexture(brightTexture1 or "")
gl.DeleteTexture(brightTexture2 or "")
if drawHighlights then
gl.DeleteTexture(brightTexture3 or "")
gl.DeleteTexture(brightTexture4 or "")
end
gl.DeleteTexture(screenTexture or "")
local btQuality = 4.6 -- high value creates flickering, but lower is more expensive
brightTexture1 = glCreateTexture(vsx/btQuality, vsy/btQuality, {
fbo = true, min_filter = GL.LINEAR, mag_filter = GL.LINEAR,
format = GL_RGB16F_ARB, wrap_s = GL.CLAMP, wrap_t = GL.CLAMP,
})
brightTexture2 = glCreateTexture(vsx/btQuality, vsy/btQuality, {
fbo = true, min_filter = GL.LINEAR, mag_filter = GL.LINEAR,
format = GL_RGB16F_ARB, wrap_s = GL.CLAMP, wrap_t = GL.CLAMP,
})
if drawHighlights then
btQuality = 3.2 -- high value creates flickering, but lower is more expensive
brightTexture3 = glCreateTexture(vsx/btQuality, vsy/btQuality, {
fbo = true, min_filter = GL.LINEAR, mag_filter = GL.LINEAR,
format = GL_RGB16F_ARB, wrap_s = GL.CLAMP, wrap_t = GL.CLAMP,
})
brightTexture4 = glCreateTexture(vsx/btQuality, vsy/btQuality, {
fbo = true, min_filter = GL.LINEAR, mag_filter = GL.LINEAR,
format = GL_RGB16F_ARB, wrap_s = GL.CLAMP, wrap_t = GL.CLAMP,
})
end
screenTexture = glCreateTexture(vsx, vsy, {
min_filter = GL.LINEAR, mag_filter = GL.LINEAR,
})
screenTextureQuarter = glCreateTexture(vsx/2, vsy/2, {
min_filter = GL.LINEAR, mag_filter = GL.LINEAR,
})
screenTextureSixteenth = glCreateTexture(vsx/4, vsy/4, {
min_filter = GL.LINEAR, mag_filter = GL.LINEAR,
})
end
function widget:ViewResize(viewSizeX, viewSizeY)
vsx,vsy = gl.GetViewSizes()
ivsx = 1.0 / vsx
ivsy = 1.0 / vsy
kernelRadius = vsy / 80.0
kernelRadius2 = vsy / 30.0
reset()
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Update(dt)
if initialized == false then
return
end
camX, camY, camZ = Spring.GetCameraPosition()
camDirX,camDirY,camDirZ = Spring.GetCameraDirection()
end
function widget:DrawWorldPreUnit()
if initialized == false or drawWorldPreUnitAlpha <= 0.05 then
return
end
gl.PushMatrix()
gl.Color(0,0,0,drawWorldPreUnitAlpha)
gl.Translate(camX+(camDirX*360),camY+(camDirY*360),camZ+(camDirZ*360))
gl.Billboard()
gl.Rect(-500, -500, 500, 500)
gl.PopMatrix()
end
function widget:DrawWorld()
if initialized == false or drawWorldAlpha <= 0.05 then
return
end
gl.PushMatrix()
gl.Color(0,0,0,drawWorldAlpha)
gl.Translate(camX+(camDirX*360),camY+(camDirY*360),camZ+(camDirZ*360))
gl.Billboard()
gl.Rect(-500, -500, 500, 500)
gl.PopMatrix()
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local initialized = false
function widget:Initialize()
SetIllumThreshold()
WG['bloom'] = {}
WG['bloom'].getAdvBloom = function()
return drawHighlights
end
WG['bloom'].setAdvBloom = function(value)
drawHighlights = value
reset()
if initialized == false then
Spring.Echo('Bloom shader doesnt work (enable shaders: \'ForceShaders = 1\' in springsettings.cfg)')
end
end
WG['bloom'].getBrightness = function()
return basicAlpha
end
WG['bloom'].setBrightness = function(value)
basicAlpha = value
reset()
if initialized == false then
Spring.Echo('Bloom shader doesnt work (enable shaders: \'ForceShaders = 1\' in springsettings.cfg)')
end
end
if (gl.CreateShader == nil) then
RemoveMe("[BloomShader::Initialize] no shader support")
return
end
widget:ViewResize(widgetHandler:GetViewSizes())
combineShader = gl.CreateShader({
fragment = [[
uniform sampler2D texture0;
uniform sampler2D texture1;
uniform float illuminationThreshold;
uniform float fragMaxBrightness;
uniform int debugDraw;
void main(void) {
vec2 C0 = vec2(gl_TexCoord[0]);
vec4 S0 = texture2D(texture0, C0);
vec4 S1 = texture2D(texture1, C0);
S1 = vec4(S1.rgb * fragMaxBrightness/max(1.0 - illuminationThreshold, 0.0001), 1.0);
gl_FragColor = bool(debugDraw) ? S1 : S0 + S1;
}
]],
uniformInt = { texture0 = 0, texture1 = 1, debugDraw = 0},
uniformFloat = {illuminationThreshold, fragMaxBrightness}
})
if (combineShader == nil) then
RemoveMe("[BloomShader::Initialize] combineShader compilation failed"); print(gl.GetShaderLog()); return
end
blurShaderH71 = gl.CreateShader({
fragment = [[
uniform sampler2D texture0;
uniform float inverseRX;
uniform float fragKernelRadius;
float bloomSigma = fragKernelRadius / 2.5;
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)
{
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*weight;
}
gl_FragColor = vec4(S.rgb/total_weight, 1.0);
}
]],
uniformInt = {texture0 = 0},
uniformFloat = {inverseRX, fragKernelRadius}
})
if (blurShaderH71 == nil) then
RemoveMe("[BloomShader::Initialize] blurShaderH71 compilation failed"); print(gl.GetShaderLog()); return
end
blurShaderV71 = gl.CreateShader({
fragment = [[
uniform sampler2D texture0;
uniform float inverseRY;
uniform float fragKernelRadius;
float bloomSigma = fragKernelRadius / 2.5;
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)
{
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*weight;
}
gl_FragColor = vec4(S.rgb/total_weight, 1.0);
}
]],
uniformInt = {texture0 = 0},
uniformFloat = {inverseRY, fragKernelRadius}
})
if (blurShaderV71 == nil) then
RemoveMe("[BloomShader::Initialize] blurShaderV71 compilation failed"); print(gl.GetShaderLog()); return
end
brightShader = gl.CreateShader({
fragment = [[
uniform sampler2D texture0;
uniform float illuminationThreshold;
uniform float inverseRX;
uniform float inverseRY;
void main(void) {
vec2 C0 = vec2(gl_TexCoord[0]);
vec3 color = vec3(texture2D(texture0, C0));
float illum = dot(color, vec3(0.2990, 0.5870, 0.1140));
if (illum > illuminationThreshold) {
gl_FragColor = vec4((color - color*(illuminationThreshold/max(illum, 0.00001))), 1.0);
} else {
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
}
}
]],
uniformInt = {texture0 = 0},
uniformFloat = {illuminationThreshold, inverseRX, inverseRY}
})
if (brightShader == nil) then
RemoveMe("[BloomShader::Initialize] brightShader compilation failed"); print(gl.GetShaderLog()); return
end
brightShaderText0Loc = glGetUniformLocation(brightShader, "texture0")
brightShaderInvRXLoc = glGetUniformLocation(brightShader, "inverseRX")
brightShaderInvRYLoc = glGetUniformLocation(brightShader, "inverseRY")
brightShaderIllumLoc = glGetUniformLocation(brightShader, "illuminationThreshold")
blurShaderH71Text0Loc = glGetUniformLocation(blurShaderH71, "texture0")
blurShaderH71InvRXLoc = glGetUniformLocation(blurShaderH71, "inverseRX")
blurShaderH71FragLoc = glGetUniformLocation(blurShaderH71, "fragKernelRadius")
blurShaderV71Text0Loc = glGetUniformLocation(blurShaderV71, "texture0")
blurShaderV71InvRYLoc = glGetUniformLocation(blurShaderV71, "inverseRY")
blurShaderV71FragLoc = glGetUniformLocation(blurShaderV71, "fragKernelRadius")
combineShaderDebgDrawLoc = glGetUniformLocation(combineShader, "debugDraw")
combineShaderTexture0Loc = glGetUniformLocation(combineShader, "texture0")
combineShaderTexture1Loc = glGetUniformLocation(combineShader, "texture1")
combineShaderIllumLoc = glGetUniformLocation(combineShader, "illuminationThreshold")
combineShaderFragLoc = glGetUniformLocation(combineShader, "fragMaxBrightness")
initialized = true
end
function widget:Shutdown()
if initialized then
gl.DeleteTexture(brightTexture1 or "")
gl.DeleteTexture(brightTexture2 or "")
if drawHighlights then
gl.DeleteTexture(brightTexture3 or "")
gl.DeleteTexture(brightTexture4 or "")
end
gl.DeleteTexture(screenTexture or "")
if (gl.DeleteShader) then
gl.DeleteShader(brightShader or 0)
gl.DeleteShader(blurShaderH71 or 0)
gl.DeleteShader(blurShaderV71 or 0)
gl.DeleteShader(combineShader or 0)
end
end
WG['bloom'] = nil
end
local function mglDrawTexture(texUnit, tex, w, h, flipS, flipT)
glTexture(texUnit, tex)
glTexRect(0, 0, w, h, flipS, flipT)
glTexture(texUnit, false)
end
local function mglDrawFBOTexture(tex)
glTexture(tex)
glTexRect(-1, -1, 1, 1)
glTexture(false)
end
local function activeTextureFunc(texUnit, tex, w, h, flipS, flipT)
glTexture(texUnit, tex)
glTexRect(0, 0, w, h, flipS, flipT)
glTexture(texUnit, false)
end
local function mglActiveTexture(texUnit, tex, w, h, flipS, flipT)
glActiveTexture(texUnit, activeTextureFunc, texUnit, tex, w, h, flipS, flipT)
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
local function Bloom()
gl.Color(1, 1, 1, 1)
glCopyToTexture(screenTexture, 0, 0, 0, 0, vsx, vsy)
-- global bloomin
glUseShader(brightShader)
glUniformInt(brightShaderText0Loc, 0)
glUniform( brightShaderInvRXLoc, ivsx)
glUniform( brightShaderInvRYLoc, ivsy)
glUniform( brightShaderIllumLoc, illumThreshold)
mglRenderToTexture(brightTexture1, screenTexture, 1, -1)
glUseShader(0)
for i = 1, 4 do
glUseShader(blurShaderH71)
glUniformInt(blurShaderH71Text0Loc, 0)
glUniform( blurShaderH71InvRXLoc, ivsx)
glUniform( blurShaderH71FragLoc, kernelRadius)
mglRenderToTexture(brightTexture2, brightTexture1, 1, -1)
glUseShader(0)
glUseShader(blurShaderV71)
glUniformInt(blurShaderV71Text0Loc, 0)
glUniform( blurShaderV71InvRYLoc, ivsy)
glUniform( blurShaderV71FragLoc, kernelRadius)
mglRenderToTexture(brightTexture1, brightTexture2, 1, -1)
glUseShader(0)
end
glUseShader(combineShader)
glUniformInt(combineShaderDebgDrawLoc, dbgDraw)
glUniformInt(combineShaderTexture0Loc, 0)
glUniformInt(combineShaderTexture1Loc, 1)
glUniform( combineShaderIllumLoc, illumThreshold)
glUniform( combineShaderFragLoc, usedBasicAlpha)
mglActiveTexture(0, screenTexture, vsx, vsy, false, true)
mglActiveTexture(1, brightTexture1, vsx, vsy, false, true)
glUseShader(0)
-- highlights
if drawHighlights then
glCopyToTexture(screenTexture, 0, 0, 0, 0, vsx, vsy)
glUseShader(brightShader)
glUniformInt(brightShaderText0Loc, 0)
glUniform( brightShaderInvRXLoc, ivsx)
glUniform( brightShaderInvRYLoc, ivsy)
glUniform( brightShaderIllumLoc, 0.5)
mglRenderToTexture(brightTexture3, screenTexture, 1, -1)
glUseShader(0)
for i = 1, 1 do
glUseShader(blurShaderH71)
glUniformInt(blurShaderH71Text0Loc, 0)
glUniform( blurShaderH71InvRXLoc, ivsx)
glUniform( blurShaderH71FragLoc, kernelRadius2)
mglRenderToTexture(brightTexture4, brightTexture3, 1, -1)
glUseShader(0)
glUseShader(blurShaderV71)
glUniformInt(blurShaderV71Text0Loc, 0)
glUniform( blurShaderV71InvRYLoc, ivsy)
glUniform( blurShaderV71FragLoc, kernelRadius2)
mglRenderToTexture(brightTexture3, brightTexture4, 1, -1)
glUseShader(0)
end
glUseShader(combineShader)
glUniformInt(combineShaderDebgDrawLoc, dbgDraw)
glUniformInt(combineShaderTexture0Loc, 0)
glUniformInt(combineShaderTexture1Loc, 1)
glUniform( combineShaderIllumLoc, illumThreshold*0.66)
glUniform( combineShaderFragLoc, highlightsAlpha)
mglActiveTexture(0, screenTexture, vsx, vsy, false, true)
mglActiveTexture(1, brightTexture3, vsx, vsy, false, true)
glUseShader(0)
end
end
function widget:DrawScreenEffects()
if initialized == false then return end
Bloom()
end
function widget:GetConfigData(data)
savedTable = {}
savedTable.basicAlpha = basicAlpha
savedTable.drawHighlights = drawHighlights
return savedTable
end
function widget:SetConfigData(data)
if data.basicAlpha ~= nil then
basicAlpha = data.basicAlpha
if data.highlightsAlpha ~= nil then
highlightsAlpha = data.highlightsAlpha
end
drawHighlights = data.drawHighlights
end
end
function widget:TextCommand(command)
if (string.find(command, "advbloom") == 1 and string.len(command) == 8) then
WG['bloom'].setAdvBloom(not drawHighlights)
if drawHighlights then
Spring.Echo('Adv bloom enabled')
else
Spring.Echo('Adv bloom disabled')
end
end
end
| gpl-2.0 |
Whit3Tig3R/bot-telegram | plugins/stats.lua | 458 | 4098 | -- Saves the number of messages from a user
-- Can check the number of messages with !stats
do
local NUM_MSG_MAX = 5
local TIME_CHECK = 4 -- seconds
local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
print('User '..msg.from.id..'is flooding '..msgs)
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nChats: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == "stats" then
if not matches[2] then
if msg.to.type == 'chat' then
local chat_id = msg.to.id
return chat_stats(chat_id)
else
return 'Stats works only on chats'
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return "Bot stats requires privileged user"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "This command requires privileged user"
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: Returns a list of Username [telegram_id]: msg_num",
"!stats chat <chat_id>: Show stats for chat_id",
"!stats bot: Shows bot stats (sudo users)"
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end | gpl-2.0 |
thesrinivas/rakshak | rakshak-probe.bkup/userspace/sysdig/chisels/flame.lua | 1 | 10064 | --[[
Copyright (C) 2013-2014 Draios inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
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/>.
--]]
-- Chisel description
disabled_description = "Flame graph generator";
short_description = "Sysdig trace flame graph builder";
category = "Performance";
-- Chisel argument list
args =
{
}
require "common"
json = require ("dkjson")
local CAPTURE_LOGS = true
local spans = {}
local fid
local flatency
local fcontname
local fexe
local fbuf
local fdir
local ftime
local MAX_DEPTH = 256
local avg_tree = {}
local full_tree = {}
local max_tree = {}
local min_tree = {}
local logs_tree = {}
local next = next -- make next faster
-- Argument notification callback
function on_set_arg(name, val)
return true
end
-- Initialization callback
function on_init()
-- Request the fields needed for this chisel
for j = 0, MAX_DEPTH do
local fname = "span.tag[" .. j .. "]"
local minfo = chisel.request_field(fname)
spans[j] = minfo
end
fid = chisel.request_field("span.id")
flatency = chisel.request_field("span.duration")
fcontname = chisel.request_field("container.name")
fexe = chisel.request_field("proc.exeline")
fbuf = chisel.request_field("evt.buffer")
fdir = chisel.request_field("evt.dir")
ftid = chisel.request_field("thread.tid")
ftime = chisel.request_field("evt.time")
-- set the filter
if CAPTURE_LOGS then
chisel.set_filter("(evt.type=tracer) or (evt.is_io_write=true and evt.dir=< and (fd.num=1 or fd.num=2 or fd.name contains log))")
else
chisel.set_filter("evt.type=tracer and evt.dir=<")
end
return true
end
-- Add a log entry into the proper place(s) in the log table
function collect_log(tid_tree)
for k,entry in pairs(tid_tree) do
while true do
local lastv = v
k,v = next(entry)
if v == nil then
if lastv.l == nil then
lastv.l = {}
end
local etime = evt.field(ftime)
local buf = evt.field(fbuf)
local tid = evt.field(ftid)
local hi, low = evt.get_ts()
local linedata = {t=etime, th=hi, tl=low, tid=tid, b=buf}
table.insert(lastv.l, linedata)
--print("*** " .. evt.get_num() .. " " .. linedata)
--print(st(logs_tree))
--print("***************************")
return
end
entry = v.ch
end
end
end
-- Parse a tracer enter event and update the logs_tree table
function parse_tracer_enter(logtable_cur, hr)
for j = 1, #hr do
local mv = hr[j]
if mv == nil then
break
end
if logtable_cur[mv] == nil then
logtable_cur[mv] = {ch={}}
end
if j == #hr then
logtable_cur[mv].r=true
end
logtable_cur = logtable_cur[mv].ch
end
end
-- Parse a tracer exit event and update the given transaction entry
function parse_tracer_exit(mrk_cur, logtable_cur, hr, latency, contname, exe, id)
local res = false
local parent_has_logs = false;
for j = 1, #hr do
local mv = hr[j]
if mv == nil or mrk_cur == nil then
break
end
local has_logtable_entry = (logtable_cur ~= nil and logtable_cur[mv] ~= nil)
--print("! " .. evt.get_num() .. " " .. j)
--print(parent_has_logs)
--print(logtable_cur[mv].r)
if j == #hr then
local llogs
if has_logtable_entry and logtable_cur[mv].l ~= nil then
llogs = logtable_cur[mv].l
else
llogs = nil
end
--print("################ " .. evt.get_num() .. " " .. st(logs_tree))
if mrk_cur[mv] == nil then
mrk_cur[mv] = {t=latency, tt=latency, cont=contname, exe=exe, c=1, logs=llogs}
if j == 1 then
mrk_cur[mv].n = 0
end
else
mrk_cur[mv]["tt"] = mrk_cur[mv]["tt"] + latency
mrk_cur[mv]["cont"] = contname
mrk_cur[mv]["exe"] = exe
mrk_cur[mv]["c"] = 1
mrk_cur[mv]["logs"] = llogs
end
--print("################ " .. evt.get_num())
--print(st(logs_tree))
--print("## " .. evt.get_num())
--print(st(logtable_cur[mv].r))
if has_logtable_entry and parent_has_logs == false then
res = true
else
logtable_cur[mv] = nil
has_logtable_entry = false
logtable_cur = nil
end
elseif j == (#hr - 1) then
if mrk_cur[mv] == nil then
mrk_cur[mv] = {tt=0}
if j == 1 then
mrk_cur[mv].n = 0
end
end
else
if mrk_cur[mv] == nil then
mrk_cur[mv] = {tt=0}
if j == 1 then
mrk_cur[mv].n = 0
mrk_cur[mv]["id"] = id
end
end
end
if mrk_cur[mv]["ch"] == nil then
mrk_cur[mv]["ch"] = {}
end
if #hr == 1 then
mrk_cur[mv].n = mrk_cur[mv].n + 1
end
-- end of node parsing, update pointers to movo to the child
if has_logtable_entry then
parent_has_logs = (logtable_cur[mv].r ~= nil)
end
mrk_cur = mrk_cur[mv].ch
if logtable_cur ~= nil then
logtable_cur = logtable_cur[mv].ch
end
end
return res
end
-- Event parsing callback
function on_event()
local etype = evt.get_type()
if etype ~= "tracer" then
local tid = evt.field(ftid)
if logs_tree[tid] == nil then
return
else
collect_log(logs_tree[tid])
end
return
end
local latency = evt.field(flatency)
local contname = evt.field(fcontname)
local id = evt.field(fid)
local exe = evt.field(fexe)
local hr = {}
local full_trs = nil
local dir = evt.field(fdir)
local tid = evt.field(ftid)
for j = 0, MAX_DEPTH do
hr[j + 1] = evt.field(spans[j])
end
if dir == ">" then
if logs_tree[tid] == nil then
logs_tree[tid] = {}
end
local idt = logs_tree[tid][id]
if idt == nil then
logs_tree[tid][id] = {}
idt = logs_tree[tid][id]
end
parse_tracer_enter(idt, hr)
return true
else
if latency == nil then
return true
end
if full_tree[id] == nil then
full_tree[id] = {}
end
-- find the logs for this transaction span
local logs
if logs_tree[tid] == nil then
logs = nil
else
if logs_tree[tid][id] == nil then
logs = nil
else
logs = logs_tree[tid][id]
end
end
if parse_tracer_exit(full_tree[id], logs, hr, latency, contname, exe, id) then
--print(st(logs_tree))
--print("------------ " .. evt.get_num())
--print(st(full_tree))
--print("---------------------------------------------------")
logs_tree[tid][id] = nil
if next(logs_tree[tid]) == nil then
logs_tree[tid] = nil
end
end
return true
end
end
function calculate_t_in_node(node)
local totchtime = 0
local maxchtime = 0
local nconc = 0
local ch_to_keep
if node.ch then
for k,d in pairs(node.ch) do
local nv = calculate_t_in_node(d)
totchtime = totchtime + nv
if nv > maxchtime then
maxchtime = nv
ch_to_keep = d
end
nconc = nconc + 1
end
end
if node.tt >= totchtime then
node.t = node.tt - totchtime
else
node.t = node.tt - maxchtime
node.nconc = nconc
for k,d in pairs(node.ch) do
if d ~= ch_to_keep then
node.ch[k] = nil
end
end
end
return node.tt
end
function normalize(node, factor)
node.t = node.t / factor
node.tt = node.tt / factor
if node.ch then
for k,d in pairs(node.ch) do
normalize(d, factor)
end
end
end
function is_transaction_complete(node)
if node.c ~= 1 then
return false
end
if node.ch then
for k,d in pairs(node.ch) do
if is_transaction_complete(d) == false then
return false
end
end
end
return true
end
function update_avg_tree(dsttree, key, val)
if dsttree[key] == nil then
dsttree[key] = copytable(val)
return
else
dsttree[key].tt = dsttree[key].tt + val.tt
if dsttree[key].n then
dsttree[key].n = dsttree[key].n + 1
end
if val.logs then
if dsttree[key].logs == nil then
dsttree[key].logs = {}
end
concattable(dsttree[key].logs, val.logs)
end
end
if val.ch then
if dsttree[key].ch == nil then
dsttree[key].ch = {}
end
for k,d in pairs(val.ch) do
update_avg_tree(dsttree[key].ch, k, d)
end
end
end
function update_max_tree(dsttree, key, val)
if dsttree[key] == nil then
dsttree[key] = val
return
else
if val.tt > dsttree[key].tt then
dsttree[key] = val
end
end
end
function update_min_tree(dsttree, key, val)
if dsttree[key] == nil then
dsttree[key] = val
return
else
if val.tt < dsttree[key].tt then
dsttree[key] = val
end
end
end
-- This processes the transaction list to extract and aggregate the transactions to emit
function collapse_tree()
-- scan the transaction list
for i,v in pairs(full_tree) do
local ttt = 0
for key,val in pairs(v) do
ttt = ttt + val.tt
if is_transaction_complete(val) then
update_avg_tree(avg_tree, key, val)
update_max_tree(max_tree, key, val)
update_min_tree(min_tree, key, val)
end
end
end
end
-- Called by the engine at the end of the capture (Ctrl-C)
function on_capture_end()
--print(st(full_tree))
-- Process the list and create the required transactions
collapse_tree()
-- calculate the unique time spent in each node
for i,v in pairs(avg_tree) do
calculate_t_in_node(v)
end
-- normalize each root span tree
for i,v in pairs(avg_tree) do
normalize(v, v.n)
end
print "var FlameData = {"
-- emit the average transaction
local AvgData = {}
AvgData[""] = {ch=avg_tree, t=0, tt=0}
local str = json.encode(AvgData, { indent = true })
print('"AvgData": ' .. str .. ",")
-- normalize the best transaction
for i,v in pairs(min_tree) do
calculate_t_in_node(v)
end
-- emit the best transaction
local tdata = {}
tdata[""] = {ch=min_tree, t=0, tt=0}
local str = json.encode(tdata, { indent = true })
print('"MinData": ' .. str .. ",")
-- normalize the worst transaction
for i,v in pairs(max_tree) do
calculate_t_in_node(v)
end
-- emit the worst transaction
local tdata = {}
tdata[""] = {ch=max_tree, t=0, tt=0}
local str = json.encode(tdata, { indent = true })
print('"MaxData": ' .. str .. ",")
print "};"
end
| gpl-2.0 |
b03605079/darkstar | scripts/zones/La_Theine_Plateau/Zone.lua | 2 | 3656 | -----------------------------------
--
-- Zone: La_Theine_Plateau (102)
--
-----------------------------------
package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/La_Theine_Plateau/TextIDs");
require("scripts/globals/zone");
require("scripts/globals/icanheararainbow");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/weather");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local manuals = {17195677,17195678};
SetFieldManual(manuals);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn( player, prevZone)
local cs = -1;
if( player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos( -272.118, 21.715, 98.859, 243);
end
if( triggerLightCutscene( player)) then -- Quest: I Can Hear A Rainbow
cs = 0x007b;
elseif( prevZone == 193 and player:getVar( "darkPuppetCS") == 5 and player:getFreeSlotsCount() >= 1) then
cs = 0x007a;
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter( player, region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate( player, csid, option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if( csid == 0x007b) then
lightCutsceneUpdate( player); -- Quest: I Can Hear A Rainbow
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish( player, csid, option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if( csid == 0x007b) then
lightCutsceneFinish( player); -- Quest: I Can Hear A Rainbow
elseif( csid == 0x007a) then
player:addItem( 14096);
player:messageSpecial( ITEM_OBTAINED, 14096); -- Chaos Sollerets
player:setVar( "darkPuppetCS", 0);
player:addFame( BASTOK, AF2_FAME);
player:completeQuest( BASTOK,DARK_PUPPET);
end
end;
function onZoneWeatherChange(weather)
local _2u0 = GetNPCByID(17195606);
local VanadielTOTD = VanadielTOTD();
local I_Can_Hear_a_Rainbow = GetServerVariable("I_Can_Hear_a_Rainbow");
if (I_Can_Hear_a_Rainbow == 1 and weather ~= WEATHER_RAIN and VanadielTOTD >= TIME_DAWN and VanadielTOTD <= TIME_EVENING and _2u0:getAnimation() == 9) then
_2u0:setAnimation(8);
elseif (I_Can_Hear_a_Rainbow == 1 and weather == WEATHER_RAIN and _2u0:getAnimation() == 8) then
_2u0:setAnimation(9);
SetServerVariable("I_Can_Hear_a_Rainbow", 0);
end
end;
function onTOTDChange(TOTD)
local _2u0 = GetNPCByID(17195606);
local I_Can_Hear_a_Rainbow = GetServerVariable("I_Can_Hear_a_Rainbow");
if (I_Can_Hear_a_Rainbow == 1 and TOTD >= TIME_DAWN and TOTD <= TIME_EVENING and _2u0:getAnimation() == 9) then
_2u0:setAnimation(8);
elseif (I_Can_Hear_a_Rainbow == 1 and TOTD < TIME_DAWN or TOTD > TIME_EVENING and _2u0:getAnimation() == 8) then
_2u0:setAnimation(9);
SetServerVariable("I_Can_Hear_a_Rainbow", 0);
end
end; | gpl-3.0 |
PicassoCT/Journeywar | gamedata/explosions/jeliahdeath.lua | 1 | 2459 | return {
["jeliadeath"] = {
rainbow = {
air = true,
class = [[CSimpleParticleSystem]],
count = 5,
ground = true,
properties = {
airdrag = 0.8,
alwaysvisible = true,
colormap = [[
0.1 0.8 0.9 0.01
0.9 0.1 0.1 0.05
0.7 0.5 0.1 0.05
0.1 0.8 0.9 0.05
0.1 0.1 0.1 0.001]],
directional = true,
emitrot = 1,
emitrotspread = 1,
emitvector = [[0,0.3r0.7,0]],
gravity = [[r0.25r-0.25, r0.3r-0.05, r0.25r-0.25]],
numparticles = 1,
particlelife = 50,
particlelifespread = 150,
particlesize = 6,
particlesizespread = 12,
particlespeed = 10,
particlespeedspread = 5,
pos = [[0r10r-10, 2, 0r10r-10]],
sizegrowth = [[0.0 0.0000000000000000001]],
sizemod = 0.99999999,
texture = [[jeliahbutterfly]],
useairlos = false,
},
},
rainbow2 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 5,
ground = true,
properties = {
airdrag = 0.8,
alwaysvisible = true,
colormap = [[
0.9 0.1 0.1 0.01
0.1 0.1 0.9 0.05
0.5 0.3 0.5 0.05
0.9 0.1 0.1 0.05
0.1 0.1 0.1 0.001]],
directional = true,
emitrot = 1,
emitrotspread = 1,
emitvector = [[r0.5r-1,0.3r0.7,r0.5r-1]],
gravity = [[r0.25r-0.25, r0.01r-0.005, r0.25r-0.25]],
numparticles = 1,
particlelife = 50,
particlelifespread = 150,
particlesize = 6,
particlesizespread = 12,
particlespeed = 10,
particlespeedspread = 5,
pos = [[0, 2, 0]],
sizegrowth = [[0.0 0.0000000000000000001]],
sizemod = 0.99999999,
texture = [[jeliahbutterfly]],
useairlos = false,
},
},
rainbow3 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 5,
ground = true,
properties = {
airdrag = 0.8,
alwaysvisible = true,
colormap = [[
0.9 0.1 0.1 0.01
0.1 0.6 0.9 0.05
0.7 0.5 0.1 0.05
0.9 0.1 0.1 0.05
0.1 0.1 0.1 0.001]],
directional = true,
emitrot = 1,
emitrotspread = 1,
emitvector = [[r0.5r-1,0.3r0.7,r0.5r-1]],
gravity = [[r0.25r-0.25, r0.01r-0.005, r0.25r-0.25]],
numparticles = 1,
particlelife = 50,
particlelifespread = 150,
particlesize = 6,
particlesizespread = 12,
particlespeed = 10,
particlespeedspread = 5,
pos = [[0, 2, 0]],
sizegrowth = [[0.0 0.0000000000000000001]],
sizemod = 0.99999999,
texture = [[jeliahbutterfly]],
useairlos = false,
},
},
}
} | gpl-3.0 |
PicassoCT/Journeywar | units/centrail/coperatrans.lua | 1 | 2272 | local unitName = "coperatrans"
local unitDef = {
--Internal settings
ObjectName = "operatrans.s3o",
name = "Operatransport",
Description= "Its not over before the fat lady sings. <Security Producing Tank Unit>",
Side = "CentrAIl",
script = "operatransscript.lua",
buildPic = "coperatrans.png",
--cost
buildCostMetal = 1200,
buildCostEnergy = 900,
BuildTime = 82,
--Health
maxDamage =3950,
idleAutoHeal = 0,
--Movement
Acceleration = 0.5,
BrakeRate = 0.4,
FootprintX = 4,
FootprintZ = 4,
TEDClass = [[VTOL]],
steeringmode = [[1]],
maneuverleashlength = 1380,
turnRadius = 8,
dontLand = false,
MaxVelocity = 2.5,
MaxWaterDepth = 20,
MovementClass = "Default2x2",
crashDrag = 0.02,
canCrash=true,
TurnRate = 250,
nanocolor=[[0 0.9 0.9]],
sightDistance = 500,
bankingAllowed = true,
hoverAttack =true,
verticalSpeed=1.0,
factoryHeadingTakeoff = true,
Builder = false,
canHover=true,
CanAttack = true,
CanGuard = true,
CanMove = true,
CanPatrol = true,
Canstop = true,--alt
upright = true,
airHoverFactor = 0.1,
cruiseAlt=65,--165,
CanFly = true,
CanLand = true,
canSubmerge = false,
--maxBank=0.4,
myGravity =0.5,
mass = 1225,
canSubmerge = false,
collide = true,
transportUnloadMethod = 0,
transportByEnemy = false,
transportCapacity = 5,
transportSize = 30000,
--Ressourcing
EnergyStorage = 800,
EnergyUse = 0,
MetalStorage = 0,
EnergyMake = 150,
MetalUse = 3,
MakesMetal = 0,
MetalMake = 0,
Category = [[LAND AIR]],
explodeAs="citadelldrone",
selfDestructAs="cartdarkmat",
ShowNanoSpray = false,
CanBeAssisted = false,
CanReclaim=false,
customParams = {},
--Hitbox
collisionVolumeOffsets = "0 0 0",
collisionVolumeScales = "35 60 90",
collisionVolumeTest = 1,
collisionVolumeType = "box",
customParams = {},
sfxtypes = {
explosiongenerators = {
"custom:factory_explosion",
},
},
--Weapons and related
weapons = {
[1]={name = "cOperaCannon",
onlyTargetCategory = [[ LAND ]],
},
[2]={name = "cOperaCannon",
onlyTargetCategory = [[ LAND ]],
},
[3]={name = "cwaterbombs",
onlyTargetCategory = [[ WATER]],
},
[4]={name = "cwaterbombs",
onlyTargetCategory = [[ WATER]],
},
},
}
return lowerkeys({ [unitName] = unitDef }) | gpl-3.0 |
thesrinivas/rakshak | rakshak-probe/userspace/elasticsearch-lua/src/elasticsearch/endpoints/Indices/Create.lua | 2 | 2686 | -------------------------------------------------------------------------------
-- Importing modules
-------------------------------------------------------------------------------
local IndicesEndpoint = require "elasticsearch.endpoints.Indices.IndicesEndpoint"
local parser = require "elasticsearch.parser"
-------------------------------------------------------------------------------
-- Declaring module
-------------------------------------------------------------------------------
local Create = IndicesEndpoint:new()
-------------------------------------------------------------------------------
-- Declaring Instance variables
-------------------------------------------------------------------------------
-- The parameters that are allowed to be used in params
Create.allowedParams = {
["timeout"] = true,
["master_timeout"] = true
}
-- Whether mappings is present in body or not
Create.mappings = false
-------------------------------------------------------------------------------
-- Function to set the body parameter
--
-- @param body The body to be set
-------------------------------------------------------------------------------
function Create:setBody(body)
if type(body) == "table" and body["mappings"] ~= nil then
self.mappings = true;
end
if self.bulkBody == false then
self.body = parser.jsonEncode(body)
return
end
-- Bulk body is present
local jsonEncodedBody = {}
for _id, item in pairs(body) do
table.insert(jsonEncodedBody, parser.jsonEncode(item))
end
self.body = table.concat(jsonEncodedBody, "\n") .. "\n"
end
-------------------------------------------------------------------------------
-- Function to calculate the http request method
--
-- @return string The HTTP request method
-------------------------------------------------------------------------------
function Create:getMethod()
if self.mappings then
return "POST"
else
return "PUT"
end
end
-------------------------------------------------------------------------------
-- Function to calculate the URI
--
-- @return string The URI
-------------------------------------------------------------------------------
function Create:getUri()
local uri = ""
if self.index == nil then
return nil, "index not specified for Create"
else
uri = uri .. "/" .. self.index
end
return uri
end
-------------------------------------------------------------------------------
-- Returns an instance of Create class
-------------------------------------------------------------------------------
function Create:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
return Create
| gpl-2.0 |
andyljones/rnn-initialization | usetools.lua | 1 | 1359 | local torch = require 'torch'
local gru = require 'gru'
local M = {}
function M.make_forward_backward(module, n_timesteps)
local modules = {}
for i = 1, n_timesteps do
modules[i] = module:clone('weight', 'bias', 'gradWeight', 'gradBias')
end
local states = {}
local last_inputs = {}
function forward(inputs, states)
local n_samples, _, n_symbols = unpack(torch.totable(inputs:size()))
last_inputs = inputs
states = states or {torch.zeros(n_samples, module.config.n_layers, module.config.n_neurons):cuda()}
local outputs = torch.zeros(n_samples, n_timesteps, n_symbols):cuda()
for i = 1, n_timesteps do
outputs[{{}, i}], states[i+1] = unpack(modules[i]:forward({last_inputs[{{}, i}], states[i]}))
end
return outputs, modules, states
end
function backward(output_grads, state_grads)
module.param_grads:zero()
local n_samples, _, n_symbols = unpack(torch.totable(last_inputs:size()))
local state_grads = state_grads or {[n_timesteps+1]=torch.zeros(n_samples, modules[1].config.n_layers, modules[1].config.n_neurons):cuda()}
for i = n_timesteps, 1, -1 do
input_grads, state_grads[i] = unpack(modules[i]:backward({last_inputs[{{}, i}], states[i]}, {output_grads[{{}, i}], state_grads[i+1]}))
end
return module.param_grads
end
return forward, backward
end
return M
| mit |
b03605079/darkstar | scripts/zones/Lower_Jeuno/npcs/Ruslan.lua | 37 | 2004 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Ruslan
-- Involved In Quest: Wondering Minstrel
-- Working 100%
-- @zone = 245
-- @pos = -19 -1 -58
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
wonderingstatus = player:getQuestStatus(WINDURST,WONDERING_MINSTREL);
if (wonderingstatus == QUEST_ACCEPTED) then
prog = player:getVar("QuestWonderingMin_var")
if (prog == 0) then -- WONDERING_MINSTREL + Rosewood Lumber: During Quest / Progression
player:startEvent(0x2719,0,718);
player:setVar("QuestWonderingMin_var",1);
elseif (prog == 1) then -- WONDERING_MINSTREL + Rosewood Lumber: Quest Objective Reminder
player:startEvent(0x271a,0,718);
end
elseif (wonderingstatus == QUEST_COMPLETED) then
rand = math.random(3);
if (rand == 1) then
player:startEvent(0x271b); -- WONDERING_MINSTREL: After Quest
else
player:startEvent(0x2718); -- Standard Conversation
end
else
player:startEvent(0x2718); -- Standard Conversation
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Sakura-Winkey/LuCI | applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo_mini.lua | 141 | 1031 | --[[
smap_devinfo - SIP Device Information
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.model.uci")
require("luci.controller.luci_diag.smap_common")
require("luci.controller.luci_diag.devinfo_common")
local debug = false
m = SimpleForm("luci-smap-to-devinfo", translate("Phone Information"), translate("Scan for supported SIP devices on specified networks."))
m.reset = false
m.submit = false
local outnets = luci.controller.luci_diag.smap_common.get_params()
luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function)
luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", true, debug)
luci.controller.luci_diag.smap_common.action_links(m, true)
return m
| apache-2.0 |
thesrinivas/rakshak | rakshak-probe.bkup/userspace/sysdig/chisels/v_mesos_tasks.lua | 6 | 2620 | --[[
Copyright (C) 2013-2014 Draios inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
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/>.
--]]
view_info =
{
id = "mesos_tasks",
name = "Mesos Tasks",
description = "List all Mesos tasks running on this machine, and the resources that each of them uses.",
tips = {"Select a task and click enter to drill down into it. At that point, you will be able to access several views that will show you the details of the selected task."},
view_type = "table",
applies_to = {"", "evt.res", "mesos.framework.id"},
filter = "mesos.task.id != ''",
use_defaults = true,
drilldown_target = "containers",
columns =
{
{
name = "NA",
field = "thread.tid",
is_key = true
},
{
name = "CPU",
field = "thread.cpu",
description = "Amount of CPU used by the task.",
colsize = 8,
aggregation = "AVG",
groupby_aggregation = "SUM",
is_sorting = true
},
{
name = "VIRT",
field = "thread.vmsize.b",
description = "Total virtual memory for the task.",
aggregation = "MAX",
groupby_aggregation = "SUM",
colsize = 9
},
{
name = "RES",
field = "thread.vmrss.b",
description = "Resident non-swapped memory for the task.",
aggregation = "MAX",
groupby_aggregation = "SUM",
colsize = 9
},
{
name = "FILE",
field = "evt.buflen.file",
description = "Total (input+output) file I/O bandwidth generated by the task, in bytes per second.",
colsize = 8,
aggregation = "TIME_AVG",
groupby_aggregation = "SUM"
},
{
name = "NET",
field = "evt.buflen.net",
description = "Total (input+output) network bandwidth generated by the task, in bytes per second.",
colsize = 8,
aggregation = "TIME_AVG",
groupby_aggregation = "SUM"
},
{
name = "NA",
field = "mesos.task.id",
is_groupby_key = true
},
{
name = "ID",
field = "mesos.task.id",
description = "Task name.",
colsize = 38
},
{
name = "NAME",
field = "mesos.task.name",
description = "Task name.",
colsize = 25
},
{
name = "LABELS",
field = "mesos.task.labels",
description = "Task labels.",
colsize = 0
},
}
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.