content
stringlengths 5
1.05M
|
|---|
return {
id = 71,
furnitures_1 = {
{
id = 71111,
parent = 0,
y = 16,
dir = 1,
x = 16,
child = {}
},
{
id = 71001,
parent = 0,
y = 0,
dir = 1,
x = 0,
child = {}
},
{
id = 71106,
parent = 0,
y = 20,
dir = 1,
x = 21,
child = {}
},
{
id = 71107,
parent = 0,
y = 22,
dir = 1,
x = 17,
child = {}
},
{
id = 71108,
parent = 0,
y = 13,
dir = 2,
x = 21,
child = {}
},
{
id = 71101,
parent = 0,
y = 12,
dir = 1,
x = 13,
child = {}
},
{
id = 71002,
parent = 0,
y = 0,
dir = 1,
x = 0,
child = {}
}
},
furnitures_2 = {
{
id = 71104,
parent = 0,
y = 21,
dir = 1,
x = 10,
child = {}
},
{
id = 71105,
parent = 0,
y = 17,
dir = 1,
x = 12,
child = {}
},
{
id = 71106,
parent = 0,
y = 20,
dir = 1,
x = 21,
child = {}
},
{
id = 71107,
parent = 0,
y = 22,
dir = 1,
x = 16,
child = {}
},
{
id = 71108,
parent = 0,
y = 13,
dir = 2,
x = 20,
child = {}
},
{
id = 71301,
parent = 0,
y = 24,
dir = 1,
x = 12,
child = {}
},
{
id = 71111,
parent = 0,
y = 8,
dir = 1,
x = 8,
child = {}
},
{
id = 71113,
parent = 0,
y = 8,
dir = 1,
x = 22,
child = {}
},
{
id = 71002,
parent = 0,
y = 0,
dir = 1,
x = 0,
child = {}
},
{
id = 71001,
parent = 0,
y = 0,
dir = 1,
x = 0,
child = {}
},
{
id = 71110,
parent = 0,
y = 9,
dir = 1,
x = 8,
child = {}
}
},
furnitures_3 = {
{
id = 71104,
parent = 0,
y = 16,
dir = 1,
x = 16,
child = {}
},
{
id = 71105,
parent = 0,
y = 21,
dir = 1,
x = 10,
child = {}
},
{
id = 71106,
parent = 0,
y = 20,
dir = 1,
x = 21,
child = {}
},
{
id = 71107,
parent = 0,
y = 22,
dir = 1,
x = 15,
child = {}
},
{
id = 71108,
parent = 0,
y = 13,
dir = 2,
x = 20,
child = {}
},
{
id = 71110,
parent = 0,
y = 6,
dir = 1,
x = 7,
child = {}
},
{
id = 71111,
parent = 0,
y = 4,
dir = 1,
x = 4,
child = {}
},
{
id = 71113,
parent = 0,
y = 9,
dir = 1,
x = 22,
child = {}
},
{
id = 71114,
parent = 0,
y = 7,
dir = 1,
x = 21,
child = {}
},
{
id = 71001,
parent = 0,
y = 0,
dir = 1,
x = 0,
child = {}
},
{
id = 71002,
parent = 0,
y = 0,
dir = 1,
x = 0,
child = {}
},
{
id = 71101,
parent = 0,
y = 19,
dir = 1,
x = 6,
child = {}
},
{
id = 71102,
parent = 0,
y = 13,
dir = 1,
x = 8,
child = {}
}
},
furnitures_4 = {
{
id = 71104,
parent = 0,
y = 16,
dir = 1,
x = 3,
child = {}
},
{
id = 71105,
parent = 0,
y = 22,
dir = 2,
x = 17,
child = {}
},
{
id = 71106,
parent = 0,
y = 20,
dir = 1,
x = 21,
child = {}
},
{
id = 71107,
parent = 0,
y = 22,
dir = 1,
x = 7,
child = {}
},
{
id = 71108,
parent = 0,
y = 14,
dir = 2,
x = 21,
child = {}
},
{
id = 71001,
parent = 0,
y = 0,
dir = 1,
x = 0,
child = {}
},
{
id = 71110,
parent = 0,
y = 1,
dir = 1,
x = 0,
child = {}
},
{
id = 71111,
parent = 0,
y = 0,
dir = 1,
x = 0,
child = {}
},
{
id = 71112,
parent = 0,
y = 4,
dir = 1,
x = 12,
child = {}
},
{
id = 71113,
parent = 0,
y = 8,
dir = 1,
x = 22,
child = {}
},
{
id = 71114,
parent = 0,
y = 22,
dir = 2,
x = 12,
child = {}
},
{
id = 71115,
parent = 0,
y = 20,
dir = 1,
x = 0,
child = {}
},
{
id = 71002,
parent = 0,
y = 0,
dir = 1,
x = 0,
child = {}
},
{
id = 71101,
parent = 0,
y = 12,
dir = 1,
x = 1,
child = {}
},
{
id = 71102,
parent = 0,
y = 9,
dir = 1,
x = 4,
child = {}
}
}
}
|
val_one = 1
val_two = 'two'
val_three = nil
js_value = string.gsub(js_value, 'js_value', 'lua_value')
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf"
module('BcePropDataQuery_pb', package.seeall)
local BCEPROPDATAQUERY = protobuf.Descriptor();
local BCEPROPDATAQUERY_GIFTSTR_FIELD = protobuf.FieldDescriptor();
local BCEPROPDATAQUERY_GIFT_FIELD = protobuf.FieldDescriptor();
local BCEPROPDATAQUERY_WEAPONID_FIELD = protobuf.FieldDescriptor();
local BCEPROPDATAQUERY_PEW_FIELD = protobuf.FieldDescriptor();
local BCEPROPDATAQUERY_USERID_FIELD = protobuf.FieldDescriptor();
BCEPROPDATAQUERY_GIFTSTR_FIELD.name = "giftstr"
BCEPROPDATAQUERY_GIFTSTR_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BcePropDataQuery.giftstr"
BCEPROPDATAQUERY_GIFTSTR_FIELD.number = 1
BCEPROPDATAQUERY_GIFTSTR_FIELD.index = 0
BCEPROPDATAQUERY_GIFTSTR_FIELD.label = 1
BCEPROPDATAQUERY_GIFTSTR_FIELD.has_default_value = false
BCEPROPDATAQUERY_GIFTSTR_FIELD.default_value = ""
BCEPROPDATAQUERY_GIFTSTR_FIELD.type = 9
BCEPROPDATAQUERY_GIFTSTR_FIELD.cpp_type = 9
BCEPROPDATAQUERY_GIFT_FIELD.name = "gift"
BCEPROPDATAQUERY_GIFT_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BcePropDataQuery.gift"
BCEPROPDATAQUERY_GIFT_FIELD.number = 2
BCEPROPDATAQUERY_GIFT_FIELD.index = 1
BCEPROPDATAQUERY_GIFT_FIELD.label = 1
BCEPROPDATAQUERY_GIFT_FIELD.has_default_value = false
BCEPROPDATAQUERY_GIFT_FIELD.default_value = nil
BCEPROPDATAQUERY_GIFT_FIELD.message_type = GIFT_PB_GIFT
BCEPROPDATAQUERY_GIFT_FIELD.type = 11
BCEPROPDATAQUERY_GIFT_FIELD.cpp_type = 10
BCEPROPDATAQUERY_WEAPONID_FIELD.name = "weaponid"
BCEPROPDATAQUERY_WEAPONID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BcePropDataQuery.weaponid"
BCEPROPDATAQUERY_WEAPONID_FIELD.number = 3
BCEPROPDATAQUERY_WEAPONID_FIELD.index = 2
BCEPROPDATAQUERY_WEAPONID_FIELD.label = 1
BCEPROPDATAQUERY_WEAPONID_FIELD.has_default_value = false
BCEPROPDATAQUERY_WEAPONID_FIELD.default_value = ""
BCEPROPDATAQUERY_WEAPONID_FIELD.type = 9
BCEPROPDATAQUERY_WEAPONID_FIELD.cpp_type = 9
BCEPROPDATAQUERY_PEW_FIELD.name = "pew"
BCEPROPDATAQUERY_PEW_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BcePropDataQuery.pew"
BCEPROPDATAQUERY_PEW_FIELD.number = 4
BCEPROPDATAQUERY_PEW_FIELD.index = 3
BCEPROPDATAQUERY_PEW_FIELD.label = 1
BCEPROPDATAQUERY_PEW_FIELD.has_default_value = false
BCEPROPDATAQUERY_PEW_FIELD.default_value = 0
BCEPROPDATAQUERY_PEW_FIELD.type = 5
BCEPROPDATAQUERY_PEW_FIELD.cpp_type = 1
BCEPROPDATAQUERY_USERID_FIELD.name = "userid"
BCEPROPDATAQUERY_USERID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BcePropDataQuery.userid"
BCEPROPDATAQUERY_USERID_FIELD.number = 5
BCEPROPDATAQUERY_USERID_FIELD.index = 4
BCEPROPDATAQUERY_USERID_FIELD.label = 1
BCEPROPDATAQUERY_USERID_FIELD.has_default_value = false
BCEPROPDATAQUERY_USERID_FIELD.default_value = ""
BCEPROPDATAQUERY_USERID_FIELD.type = 9
BCEPROPDATAQUERY_USERID_FIELD.cpp_type = 9
BCEPROPDATAQUERY.name = "BcePropDataQuery"
BCEPROPDATAQUERY.full_name = ".com.xinqihd.sns.gameserver.proto.BcePropDataQuery"
BCEPROPDATAQUERY.nested_types = {}
BCEPROPDATAQUERY.enum_types = {}
BCEPROPDATAQUERY.fields = {BCEPROPDATAQUERY_GIFTSTR_FIELD, BCEPROPDATAQUERY_GIFT_FIELD, BCEPROPDATAQUERY_WEAPONID_FIELD, BCEPROPDATAQUERY_PEW_FIELD, BCEPROPDATAQUERY_USERID_FIELD}
BCEPROPDATAQUERY.is_extendable = false
BCEPROPDATAQUERY.extensions = {}
BcePropDataQuery = protobuf.Message(BCEPROPDATAQUERY)
_G.BCEPROPDATAQUERY_PB_BCEPROPDATAQUERY = BCEPROPDATAQUERY
|
Vector = {}
Vector_mt = {
__index = Vector,
__add = function(lhs, rhs)
return Vector:new(lhs.x + rhs.x, lhs.y + rhs.y)
end,
__sub = function(lhs, rhs)
return Vector:new(lhs.x - rhs.x, lhs.y - rhs.y)
end,
__mul = function(scalar, vector)
return Vector:new(scalar * vector.x, scalar * vector.y)
end,
__div = function(vector, scalar)
return Vector:new(vector.x / scalar, vector.y / scalar)
end
}
function Vector:new(x, y)
return setmetatable({x=x, y=y}, Vector_mt)
end
function Vector:dot(v)
return self.x * v.x + self.y * v.y
end
function Vector:magnitude()
return math.sqrt(self:dot(self))
end
function Vector:normalize()
return self / self:magnitude()
end
|
--
-- Please see the license.txt file included with this distribution for
-- attribution and copyright information.
--
rCombatantHasEffectCondition = nil;
rRemoveCombatantEffectAction = nil;
function onInit()
initializeConditions();
initializeActions()
end
function initializeConditions()
rCombatantHasEffectCondition = {
sName = "combatant_has_effect_condition",
fCondition = combatantHasEffectCondition,
aConfigurableParameters = {
TriggerData.rCombatantParameter,
{
sName = "sEffectName",
sDisplay = "effect_name_parameter",
sType = "string"
},
},
};
TriggerManager.defineCondition(rCombatantHasEffectCondition);
end
function initializeActions()
rRemoveCombatantEffectAction = {
sName = "remove_effect_from_combatant_action",
fAction = removeCombatantEffect,
aConfigurableParameters = {
TriggerData.rCombatantParameter,
{
sName = "sEffectName",
sDisplay = "effect_name_parameter",
sType = "string"
},
},
};
TriggerManager.defineAction(rRemoveCombatantEffectAction);
end
function combatantHasEffectCondition(rTriggerData, rEventData)
if rTriggerData.sCombatant == "source_subject" then
return EffectManager.hasEffect(rEventData.rSource, rTriggerData.sEffectName);
elseif rTriggerData.sCombatant == "target_subject" then
return EffectManager.hasEffect(rEventData.rTarget, rTriggerData.sEffectName);
end
return false;
end
function removeCombatantEffect(rTriggerData, rEventData)
if rTriggerData.sCombatant == "source_subject" then
EffectManager.removeEffect(ActorManager.getCTNode(rEventData.rSource), rTriggerData.sEffectName);
elseif rTriggerData.sCombatant == "target_subject" then
EffectManager.removeEffect(ActorManager.getCTNode(rEventData.rTarget), rTriggerData.sEffectName);
end
end
|
-- Copyright (C) Yichun Zhang (agentzh), CloudFlare Inc.
local escape_uri = ngx.escape_uri
local unescape_uri = ngx.unescape_uri
local match = string.match
local tcp = ngx.socket.tcp
local strlen = string.len
local concat = table.concat
local tab_insert = table.insert
local setmetatable = setmetatable
local type = type
local tab_clear = require "table.clear"
local cmd_tab = {}
local _M = {
_VERSION = '0.16'
}
local mt = { __index = _M }
local ok, new_tab = pcall(require, "table.new")
if not ok or type(new_tab) ~= "function" then
new_tab = function (narr, nrec) return {} end
end
local function _read_reply(sock, len)
local line, err
if len == nil then
line, err = sock:receive()
else
line, err = sock:receive(len)
end
if not line then
if err == "timeout" then
sock:close()
end
return nil, err
end
return line, nil
end
function _M.new(self, opts)
local sock, err = tcp()
if not sock then
return nil, err
end
local escape_key = escape_uri
local unescape_key = unescape_uri
if opts then
local key_transform = opts.key_transform
if key_transform then
escape_key = key_transform[1]
unescape_key = key_transform[2]
if not escape_key or not unescape_key then
return nil, "expecting key_transform = { escape, unescape } table"
end
end
end
return setmetatable({
sock = sock,
escape_key = escape_key,
unescape_key = unescape_key,
}, mt)
end
local function set_timeouts(self, connect, send, read)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
sock:settimeouts(connect, send, read)
return 1
end
_M.set_timeouts = set_timeouts
function _M.set_timeout(self, timeout)
return set_timeouts(self, timeout, timeout, timeout)
end
function _M.connect(self, ...)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:connect(...)
end
function _M.sslhandshake(self, ...)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:sslhandshake(...)
end
local function _multi_get(self, keys)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
local nkeys = #keys
if nkeys == 0 then
return {}, nil
end
local escape_key = self.escape_key
tab_clear(cmd_tab)
tab_insert(cmd_tab, "get")
for i = 1, nkeys do
tab_insert(cmd_tab, " ")
tab_insert(cmd_tab, escape_key(keys[i]))
end
tab_insert(cmd_tab, "\r\n")
-- print("multi get cmd: ", cmd_tab)
local bytes, err = sock:send(cmd_tab)
if not bytes then
return nil, err
end
local unescape_key = self.unescape_key
local results = {}
while true do
local line, err = sock:receive()
if not line then
if err == "timeout" then
sock:close()
end
return nil, err
end
if line == 'END' then
break
end
local key, flags, len = match(line, '^VALUE (%S+) (%d+) (%d+)$')
-- print("key: ", key, "len: ", len, ", flags: ", flags)
if not key then
return nil, line
end
local data, err = sock:receive(len)
if not data then
if err == "timeout" then
sock:close()
end
return nil, err
end
results[unescape_key(key)] = {data, flags}
data, err = sock:receive(2) -- discard the trailing CRLF
if not data then
if err == "timeout" then
sock:close()
end
return nil, err
end
end
return results
end
local function _get_reply(sock)
local line, err = _read_reply(sock)
if err then
return nil, nil, err
end
if line == 'END' then
return nil, nil, nil
end
local flags, len = match(line, '^VALUE %S+ (%d+) (%d+)$')
if not flags then
return nil, nil, line
end
-- print("len: ", len, ", flags: ", flags)
local data, err = _read_reply(sock, len)
if err then
return nil, nil, err
end
local _, err = _read_reply(sock, 7) -- discard the trailing "\r\nEND\r\n"
if err then
return nil, nil, err
end
return data, flags
end
function _M.get(self, key)
if type(key) == "table" then
return _multi_get(self, key)
end
local sock = self.sock
if not sock then
return nil, nil, "not initialized"
end
local reqs = rawget(self, "_reqs")
if reqs then
local readers = rawget(self, "_readers")
tab_insert(reqs, "get ")
tab_insert(reqs, self.escape_key(key))
tab_insert(reqs, "\r\n")
tab_insert(readers, _get_reply)
return 1
end
tab_clear(cmd_tab)
tab_insert(cmd_tab, "get ")
tab_insert(cmd_tab, self.escape_key(key))
tab_insert(cmd_tab, "\r\n")
local bytes, err = sock:send(cmd_tab)
if not bytes then
return nil, nil, err
end
return _get_reply(sock)
end
local function _multi_gets(self, keys)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
local nkeys = #keys
if nkeys == 0 then
return {}, nil
end
local escape_key = self.escape_key
tab_clear(cmd_tab)
tab_insert(cmd_tab, "gets")
for i = 1, nkeys do
tab_insert(cmd_tab, " ")
tab_insert(cmd_tab, escape_key(keys[i]))
end
tab_insert(cmd_tab, "\r\n")
-- print("multi get cmd: ", cmd_tab)
local bytes, err = sock:send(cmd_tab)
if not bytes then
return nil, err
end
local unescape_key = self.unescape_key
local results = {}
while true do
local line, err = _read_reply(sock)
if err then
return nil, err
end
if line == 'END' then
break
end
local key, flags, len, cas_uniq =
match(line, '^VALUE (%S+) (%d+) (%d+) (%d+)$')
-- print("key: ", key, "len: ", len, ", flags: ", flags)
if not key then
return nil, line
end
local data, err = _read_reply(sock, len)
if err then
return nil, err
end
results[unescape_key(key)] = {data, flags, cas_uniq}
data, err = _read_reply(sock, 2) -- discard the trailing CRLF
if err then
return nil, err
end
end
return results
end
function _M.gets(self, key)
if type(key) == "table" then
return _multi_gets(self, key)
end
local sock = self.sock
if not sock then
return nil, nil, nil, "not initialized"
end
tab_clear(cmd_tab)
tab_insert(cmd_tab, "gets ")
tab_insert(cmd_tab, self.escape_key(key))
tab_insert(cmd_tab, "\r\n")
local bytes, err = sock:send(cmd_tab)
if not bytes then
return nil, nil, nil, err
end
local line, err = _read_reply(sock)
if err then
return nil, nil, nil, err
end
if line == 'END' then
return nil, nil, nil, nil
end
local flags, len, cas_uniq = match(line, '^VALUE %S+ (%d+) (%d+) (%d+)$')
if not flags then
return nil, nil, nil, line
end
-- print("len: ", len, ", flags: ", flags)
local data, err = _read_reply(sock, len)
if not data then
return nil, nil, nil, err
end
line, err = _read_reply(sock, 7) -- discard the trailing "\r\nEND\r\n"
if not line then
return nil, nil, nil, err
end
return data, flags, cas_uniq
end
local function _expand_table(value)
local segs = {}
local nelems = #value
local nsegs = 0
for i = 1, nelems do
local seg = value[i]
nsegs = nsegs + 1
if type(seg) == "table" then
segs[nsegs] = _expand_table(seg)
else
segs[nsegs] = seg
end
end
return concat(segs)
end
local function _store_reply(sock)
local data, err = _read_reply(sock)
if err then
return nil, err
end
if data == "STORED" then
return 1
end
return nil, data
end
local function _store(self, cmd, key, value, exptime, flags)
if not exptime then
exptime = 0
end
if not flags then
flags = 0
end
local sock = self.sock
if not sock then
return nil, "not initialized"
end
if type(value) == "table" then
value = _expand_table(value)
end
local reqs = rawget(self, "_reqs")
if reqs then
local readers = rawget(self, "_readers")
tab_insert(reqs, cmd)
tab_insert(reqs, " ")
tab_insert(reqs, self.escape_key(key))
tab_insert(reqs, " ")
tab_insert(reqs, flags)
tab_insert(reqs, " ")
tab_insert(reqs, exptime)
tab_insert(reqs, " ")
tab_insert(reqs, strlen(value))
tab_insert(reqs, "\r\n")
tab_insert(reqs, value)
tab_insert(reqs, "\r\n")
tab_insert(readers, _store_reply)
return 1
end
tab_clear(cmd_tab)
tab_insert(cmd_tab, cmd)
tab_insert(cmd_tab, " ")
tab_insert(cmd_tab, self.escape_key(key))
tab_insert(cmd_tab, " ")
tab_insert(cmd_tab, flags)
tab_insert(cmd_tab, " ")
tab_insert(cmd_tab, exptime)
tab_insert(cmd_tab, " ")
tab_insert(cmd_tab, strlen(value))
tab_insert(cmd_tab, "\r\n")
tab_insert(cmd_tab, value)
tab_insert(cmd_tab, "\r\n")
local bytes, err = sock:send(cmd_tab)
if not bytes then
return nil, err
end
return _store_reply(sock)
end
function _M.set(self, ...)
return _store(self, "set", ...)
end
function _M.add(self, ...)
return _store(self, "add", ...)
end
function _M.replace(self, ...)
return _store(self, "replace", ...)
end
function _M.append(self, ...)
return _store(self, "append", ...)
end
function _M.prepend(self, ...)
return _store(self, "prepend", ...)
end
function _M.cas(self, key, value, cas_uniq, exptime, flags)
if not exptime then
exptime = 0
end
if not flags then
flags = 0
end
local sock = self.sock
if not sock then
return nil, "not initialized"
end
tab_clear(cmd_tab)
tab_insert(cmd_tab, "cas ")
tab_insert(cmd_tab, self.escape_key(key))
tab_insert(cmd_tab, " ")
tab_insert(cmd_tab, flags)
tab_insert(cmd_tab, " ")
tab_insert(cmd_tab, exptime)
tab_insert(cmd_tab, " ")
tab_insert(cmd_tab, strlen(value))
tab_insert(cmd_tab, " ")
tab_insert(cmd_tab, cas_uniq)
tab_insert(cmd_tab, "\r\n")
tab_insert(cmd_tab, value)
tab_insert(cmd_tab, "\r\n")
-- local cjson = require "cjson"
-- print("request: ", cjson.encode(cmd_tab))
local bytes, err = sock:send(cmd_tab)
if not bytes then
return nil, err
end
local line, err = _read_reply(sock)
if err then
return nil, err
end
-- print("response: [", line, "]")
if line == "STORED" then
return 1
end
return nil, line
end
local function _delete_reply(sock)
local res, err = _read_reply(sock)
if err then
return nil, err
end
if res ~= 'DELETED' then
return nil, res
end
return 1
end
function _M.delete(self, key)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
key = self.escape_key(key)
local reqs = rawget(self, "_reqs")
if reqs then
local readers = rawget(self, "_readers")
tab_insert(reqs, "delete ")
tab_insert(reqs, key)
tab_insert(reqs, "\r\n")
tab_insert(readers, _delete_reply)
return 1
end
tab_clear(cmd_tab)
tab_insert(cmd_tab, "delete ")
tab_insert(cmd_tab, key)
tab_insert(cmd_tab, "\r\n")
local bytes, err = sock:send(cmd_tab)
if not bytes then
return nil, err
end
return _delete_reply(sock)
end
function _M.set_keepalive(self, ...)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:setkeepalive(...)
end
function _M.get_reused_times(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:getreusedtimes()
end
function _M.flush_all(self, time)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
tab_clear(cmd_tab)
if time then
tab_insert(cmd_tab, "flush_all ")
tab_insert(cmd_tab, time)
tab_insert(cmd_tab, "\r\n")
else
tab_clear(cmd_tab)
tab_insert(cmd_tab, "flush_all\r\n")
end
local bytes, err = sock:send(cmd_tab)
if not bytes then
return nil, err
end
local res, err = _read_reply(sock)
if err then
return nil, err
end
if res ~= 'OK' then
return nil, res
end
return 1
end
local function _incr_decr_reply(sock)
local line, err = _read_reply(sock)
if err then
return nil, err
end
if not match(line, '^%d+$') then
return nil, line
end
return line
end
local function _incr_decr(self, cmd, key, value)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
local reqs = rawget(self, "_reqs")
local readers = rawget(self, "_readers")
if reqs then
tab_insert(reqs, cmd)
tab_insert(reqs, " ")
tab_insert(reqs, self.escape_key(key))
tab_insert(reqs, " ")
tab_insert(reqs, value)
tab_insert(reqs, "\r\n")
tab_insert(readers, _incr_decr_reply)
return 1
end
tab_clear(cmd_tab)
tab_insert(cmd_tab, cmd)
tab_insert(cmd_tab, " ")
tab_insert(cmd_tab, self.escape_key(key))
tab_insert(cmd_tab, " ")
tab_insert(cmd_tab, value)
tab_insert(cmd_tab, "\r\n")
local bytes, err = sock:send(cmd_tab)
if not bytes then
return nil, err
end
return _incr_decr_reply(sock)
end
function _M.incr(self, key, value)
return _incr_decr(self, "incr", key, value)
end
function _M.decr(self, key, value)
return _incr_decr(self, "decr", key, value)
end
local function _stats_reply(sock)
local lines = {}
local n = 0
while true do
local line, err = _read_reply(sock)
if err then
return nil, err
end
if line == 'END' then
return lines, nil
end
if not match(line, "ERROR") then
n = n + 1
lines[n] = line
else
return nil, line
end
end
-- cannot reach here...
return lines
end
function _M.stats(self, args)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
local reqs = rawget(self, "_reqs")
local readers = rawget(self, "_readers")
if reqs then
if args then
tab_insert(reqs, "stats ")
tab_insert(reqs, args)
tab_insert(reqs, "\r\n")
else
tab_insert(reqs, "stats\r\n")
end
tab_insert(readers, _stats_reply)
return 1
end
local bytes, err
if args then
tab_clear(cmd_tab)
tab_insert(cmd_tab, "stats ")
tab_insert(cmd_tab, args)
tab_insert(cmd_tab, "\r\n")
bytes, err = sock:send(cmd_tab)
else
bytes, err = sock:send("stats\r\n")
end
if not bytes then
return nil, err
end
return _stats_reply(sock)
end
local function _version_reply(sock)
local line, err = _read_reply(sock)
if err then
return nil, err
end
local ver = match(line, "^VERSION (.+)$")
if not ver then
return nil, ver
end
return ver
end
function _M.version(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
local bytes, err = sock:send("version\r\n")
if not bytes then
return nil, err
end
return _version_reply(sock)
end
function _M.quit(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
local bytes, err = sock:send("quit\r\n")
if not bytes then
return nil, err
end
return 1
end
local function _verbosity_reply(sock)
local line, err = _read_reply(sock)
if err then
return nil, err
end
if line ~= 'OK' then
return nil, line
end
return 1
end
function _M.verbosity(self, level)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
local reqs = rawget(self, "_reqs")
if reqs then
local readers = rawget(self, "_readers")
tab_insert(reqs, "verbosity ")
tab_insert(reqs, level)
tab_insert(reqs, "\r\n")
tab_insert(readers, _verbosity_reply)
return 1
end
tab_clear(cmd_tab)
tab_insert(cmd_tab, "verbosity ")
tab_insert(cmd_tab, level)
tab_insert(cmd_tab, "\r\n")
local bytes, err = sock:send(cmd_tab)
if not bytes then
return nil, err
end
return _verbosity_reply(sock)
end
local function _touch_reply(sock)
local line, err = _read_reply(sock)
if err then
return nil, err
end
-- moxi server from couchbase returned stored after touching
if line == "TOUCHED" or line =="STORED" then
return 1
end
return nil, line
end
function _M.touch(self, key, exptime)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
local reqs = rawget(self, "_reqs")
local readers = rawget(self, "_readers")
if reqs then
tab_insert(reqs, "touch ")
tab_insert(reqs, self.escape_key(key))
tab_insert(reqs, " ")
tab_insert(reqs, exptime)
tab_insert(reqs, "\r\n")
tab_insert(readers, _touch_reply)
return 1
end
tab_clear(cmd_tab)
tab_insert(cmd_tab, "touch ")
tab_insert(cmd_tab, self.escape_key(key))
tab_insert(cmd_tab, " ")
tab_insert(cmd_tab, exptime)
tab_insert(cmd_tab, "\r\n")
local bytes, err = sock:send(cmd_tab)
if not bytes then
return nil, err
end
return _touch_reply(sock)
end
function _M.close(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:close()
end
function _M.init_pipeline(self, n)
if self._reqs then
return "already init pipeline"
end
if n and type(n) ~= 'number' then
return "bad n arg: number expected, but got " .. type(n)
end
self._reqs = new_tab(n or 20, 0)
self._readers = new_tab(n or 4, 0)
return nil
end
function _M.cancel_pipeline(self)
self._reqs = nil
self._readers = nil
end
function _M.commit_pipeline(self)
local reqs = rawget(self, "_reqs")
local readers = rawget(self, "_readers")
self._reqs = nil
self._readers = nil
if not reqs or not readers then
return nil, "no pipeline"
end
local sock = self.sock
if not sock then
return nil, "not initialized"
end
if #readers == 0 then
return nil, "no more cmds"
end
local bytes, err = sock:send(reqs)
if not bytes then
return nil, err
end
local results = {}
for i, reader in ipairs(readers) do
results[i] = { reader(sock) }
end
return results, nil
end
return _M
|
-- See LICENSE for terms
local table = table
-- BuildingTemplates, ClassTemplates.Building
local MsgPopup = ChoGGi.ComFuncs.MsgPopup
local RetName = ChoGGi.ComFuncs.RetName
local Translate = ChoGGi.ComFuncs.Translate
local RetTemplateOrClass = ChoGGi.ComFuncs.RetTemplateOrClass
local Strings = ChoGGi.Strings
function ChoGGi.MenuFuncs.UnlockCrops()
local item_list = {}
local c = 0
local CropPresets = CropPresets
for id, crop in pairs(CropPresets) do
if crop.Locked then
c = c + 1
item_list[c] = {
text = Translate(crop.DisplayName),
value = id,
hint = Translate(crop.Desc),
icon = crop.icon,
}
end
end
local function CallBackFunc(choice)
if choice.nothing_selected then
return
end
local value = choice[1].value
if CropPresets[value] then
UnlockCrop(value)
MsgPopup(
ChoGGi.ComFuncs.SettingState(value),
Strings[302535920000423--[[Unlock Crops]]]
)
end
end
ChoGGi.ComFuncs.OpenInListChoice{
callback = CallBackFunc,
items = item_list,
title = Strings[302535920000423--[[Unlock Crops]]],
}
end
function ChoGGi.MenuFuncs.RotateDuringPlacement_Toggle()
local buildings = ClassTemplates.Building
if ChoGGi.UserSettings.RotateDuringPlacement then
-- used when starting/loading a game
ChoGGi.UserSettings.RotateDuringPlacement = nil
for _, bld in pairs(buildings) do
if bld.can_rotate_during_placement_ChoGGi_orig then
bld.can_rotate_during_placement = false
bld.can_rotate_during_placement_ChoGGi_orig = nil
end
end
else
-- used when starting/loading a game
ChoGGi.UserSettings.RotateDuringPlacement = true
for _, bld in pairs(buildings) do
if bld.can_rotate_during_placement == false then
bld.can_rotate_during_placement_ChoGGi_orig = true
bld.can_rotate_during_placement = true
end
end
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.RotateDuringPlacement),
Strings[302535920001407--[[Rotate During Placement]]]
)
end
function ChoGGi.MenuFuncs.SponsorBuildingLimits_Toggle()
local BuildingTechRequirements = BuildingTechRequirements
local BuildingTemplates = BuildingTemplates
if ChoGGi.UserSettings.SponsorBuildingLimits then
-- used when starting/loading a game
ChoGGi.UserSettings.SponsorBuildingLimits = nil
for _, bld in pairs(BuildingTemplates) do
-- set each status to false if it isn't
for i = 1, 3 do
local str = "sponsor_status" .. i .. "_ChoGGi_orig"
if bld[str] then
bld["sponsor_status" .. i] = bld[str]
bld[str] = nil
end
end
end
else
-- used when starting/loading a game
ChoGGi.UserSettings.SponsorBuildingLimits = true
for id, bld in pairs(BuildingTemplates) do
-- set each status to false if it isn't
for i = 1, 3 do
local str = "sponsor_status" .. i
local status = bld[str]
if status ~= false then
bld["sponsor_status" .. i .. "_ChoGGi_orig"] = status
bld[str] = false
end
end
-- and this bugger screws me over on GetBuildingTechsStatus
local name = id
if name:sub(1, 2) == "RC" and name:sub(-8) == "Building" then
name = name:gsub("Building", "")
end
local reqs = BuildingTechRequirements[id]
local idx = table.find(reqs, "check_supply", name)
if idx then
table.remove(reqs, idx)
end
end
end
ChoGGi.SettingFuncs.WriteSettings()
ChoGGi.ComFuncs.UpdateBuildMenu()
MsgPopup(
ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.SponsorBuildingLimits),
Strings[302535920001398--[[Remove Sponsor Limits]]]
)
end
function ChoGGi.MenuFuncs.SetTrainingPoints()
local obj = ChoGGi.ComFuncs.SelObject()
if not obj or not IsKindOf(obj, "TrainingBuilding") then
MsgPopup(
Strings[302535920001116--[[Select a %s.]]]:format(Translate(5443--[[Training Buildings]])),
T(5443, "Training Buildings")
)
return
end
local id = RetTemplateOrClass(obj)
local name = RetName(obj)
local default_setting = obj:GetClassValue("evaluation_points")
local UserSettings = ChoGGi.UserSettings
local item_list = {
{text = Translate(1000121--[[Default]]), value = default_setting},
{text = 10, value = 10},
{text = 15, value = 15},
{text = 20, value = 20},
{text = 25, value = 25},
{text = 50, value = 50},
{text = 75, value = 75},
{text = 100, value = 100},
{text = 250, value = 250},
{text = 500, value = 500},
{text = 1000, value = 1000},
}
if not UserSettings.BuildingSettings[id] then
UserSettings.BuildingSettings[id] = {}
end
local hint = default_setting
local setting = UserSettings.BuildingSettings[id]
if setting and setting.evaluation_points then
hint = setting.evaluation_points
end
local function CallBackFunc(choice)
if choice.nothing_selected then
return
end
local value = choice[1].value
if type(value) == "number" then
local objs = MapGet("map", obj.class)
if value == default_setting then
setting.evaluation_points = nil
for i = 1, #objs do
objs[i].evaluation_points = default_setting
end
else
setting.evaluation_points = value
for i = 1, #objs do
objs[i].evaluation_points = value
end
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
ChoGGi.ComFuncs.SettingState(value, name),
Strings[302535920001344--[[Points To Train]]]
)
end
end
ChoGGi.ComFuncs.OpenInListChoice{
callback = CallBackFunc,
items = item_list,
title = name .. ": " .. Strings[302535920001344--[[Points To Train]]],
hint = Strings[302535920000106--[[Current]]] .. ": " .. hint,
skip_sort = true,
}
end
function ChoGGi.MenuFuncs.SetServiceBuildingStats()
local obj = ChoGGi.ComFuncs.SelObject()
if not obj or not IsKindOf(obj, "StatsChange") then
MsgPopup(
Strings[302535920001116--[[Select a %s.]]]:format(Translate(5439--[[Service Buildings]])),
T(4810, "Service")
)
return
end
local r = const.ResourceScale
local id = RetTemplateOrClass(obj)
local ServiceInterestsList = table.concat(ServiceInterestsList, ", ")
local name = RetName(obj)
local is_service = obj:IsKindOf("Service")
local ReturnEditorType = ChoGGi.ComFuncs.ReturnEditorType
local hint_type = Strings[302535920000138--[[Value needs to be a %s.]]]
local item_list = {
{text = Translate(728--[[Health change on visit]]), value = obj:GetClassValue("health_change") / r, setting = "health_change", hint = hint_type:format(ReturnEditorType(obj.properties, "id", "health_change"))},
{text = Translate(729--[[Sanity change on visit]]), value = obj:GetClassValue("sanity_change") / r, setting = "sanity_change", hint = hint_type:format(ReturnEditorType(obj.properties, "id", "sanity_change"))},
{text = Translate(730--[[Service Comfort]]), value = obj:GetClassValue("service_comfort") / r, setting = "service_comfort", hint = hint_type:format(ReturnEditorType(obj.properties, "id", "service_comfort"))},
{text = Translate(731--[[Comfort increase on visit]]), value = obj:GetClassValue("comfort_increase") / r, setting = "comfort_increase", hint = hint_type:format(ReturnEditorType(obj.properties, "id", "comfort_increase"))},
}
local c = #item_list
if is_service then
c = c + 1
item_list[c] = {text = Translate(734--[[Visit duration]]), value = obj:GetClassValue("visit_duration"), setting = "visit_duration", hint = hint_type:format(ReturnEditorType(obj.properties, "id", "visit_duration"))}
-- bool
c = c + 1
item_list[c] = {text = Translate(735--[[Usable by children]]), value = obj:GetClassValue("usable_by_children"), setting = "usable_by_children", hint = hint_type:format(ReturnEditorType(obj.properties, "id", "usable_by_children"))}
c = c + 1
item_list[c] = {text = Translate(736--[[Children Only]]), value = obj:GetClassValue("children_only"), setting = "children_only", hint = hint_type:format(ReturnEditorType(obj.properties, "id", "children_only"))}
for i = 1, 11 do
local name = "interest" .. i
c = c + 1
item_list[c] = {
text = Translate(732--[[Service interest]]) .. " " .. i,
value = obj[name],
setting = name,
hint = hint_type:format(ReturnEditorType(obj.properties, "id", name)) .. "\n\n" .. ServiceInterestsList,
}
end
end
local BuildingSettings = ChoGGi.UserSettings.BuildingSettings
if not BuildingSettings[id] then
BuildingSettings[id] = {}
end
local bs_setting = BuildingSettings[id]
if not bs_setting.service_stats then
bs_setting.service_stats = {}
end
local function CallBackFunc(choice)
if choice.nothing_selected then
return
end
local set = Strings[302535920000129--[[Set]]]
if choice[1].check1 then
set = Translate(1000121--[[Default]])
bs_setting.service_stats = nil
-- get defaults
local temp = {
health_change = obj:GetClassValue("health_change"),
sanity_change = obj:GetClassValue("sanity_change"),
service_comfort = obj:GetClassValue("service_comfort"),
comfort_increase = obj:GetClassValue("comfort_increase"),
}
if is_service then
temp.visit_duration = obj:GetClassValue("visit_duration")
temp.usable_by_children = obj:GetClassValue("usable_by_children")
temp.children_only = obj:GetClassValue("children_only")
for i = 1, 11 do
local name = "interest" .. i
temp[name] = obj:GetClassValue(name)
end
end
-- reset existing to defaults
local objs = MapGet("map", id)
for i = 1, #objs do
local obj = objs[i]
obj:SetBase("health_change", temp.health_change)
obj:SetBase("sanity_change", temp.sanity_change)
obj:SetBase("service_comfort", temp.service_comfort)
obj:SetBase("comfort_increase", temp.comfort_increase)
if is_service then
obj:SetBase("visit_duration", temp.visit_duration)
obj:SetBase("usable_by_children", temp.usable_by_children)
obj:SetBase("children_only", temp.children_only)
for j = 1, 11 do
local name = "interest" .. j
obj:SetBase("name", temp[name])
end
end
end
else
-- build setting to save
for i = 1, #choice do
local setting = choice[i].setting
local value, value_type = ChoGGi.ComFuncs.RetProperType(choice[i].value)
-- check user added correct
local editor_type = ReturnEditorType(obj.properties, "id", setting)
if value_type == editor_type then
if editor_type == "number" then
bs_setting.service_stats[setting] = value * r
elseif value == "" then
bs_setting.service_stats[setting] = nil
else
bs_setting.service_stats[setting] = value
end
end
end
-- update existing buildings
local objs = MapGet("map", id)
local UpdateServiceComfortBld = ChoGGi.ComFuncs.UpdateServiceComfortBld
for i = 1, #objs do
UpdateServiceComfortBld(objs[i], bs_setting.service_stats)
end
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
ChoGGi.ComFuncs.SettingState(set),
Strings[302535920001114--[[Service Building Stats]]]
)
end
local custom_settings = false
if next(bs_setting.service_stats) then
custom_settings = true
end
ChoGGi.ComFuncs.OpenInListChoice{
callback = CallBackFunc,
items = item_list,
title = Strings[302535920000129--[[Set]]] .. " " .. name .. " " .. Strings[302535920001114--[[Service Building Stats]]],
hint = Strings[302535920001339--[[Are settings custom: %s]]]:format(custom_settings),
hint = Strings[302535920001340--[[Invalid settings will be skipped.]]] .. "\n\n" .. Strings[302535920001339--[[Are settings custom: %s]]]:format(custom_settings),
custom_type = 4,
skip_sort = true,
checkboxes = {
{
title = Translate(1000121--[[Default]]),
hint = Strings[302535920001338--[[Reset to default.]]],
},
},
}
end
function ChoGGi.MenuFuncs.SetExportWhenThisAmount()
local default_setting = Translate(1000121--[[Default]])
local UserSettings = ChoGGi.UserSettings
local id = "SpaceElevator"
local item_list = {
{text = default_setting, value = default_setting},
{text = 10, value = 10},
{text = 15, value = 15},
{text = 20, value = 20},
{text = 25, value = 25},
{text = 50, value = 50},
{text = 75, value = 75},
{text = 100, value = 100},
{text = 250, value = 250},
{text = 500, value = 500},
{text = 1000, value = 1000},
}
if not UserSettings.BuildingSettings[id] then
UserSettings.BuildingSettings[id] = {}
end
local hint = default_setting
local setting = UserSettings.BuildingSettings[id]
if setting and setting.export_when_this_amount then
hint = setting.export_when_this_amount
end
local function CallBackFunc(choice)
if choice.nothing_selected then
return
end
choice = choice[1]
local value = choice.value
if value == default_setting then
setting.export_when_this_amount = nil
else
setting.export_when_this_amount = value * const.ResourceScale
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
ChoGGi.ComFuncs.SettingState(choice.value),
Strings[302535920001336--[[Export When This Amount]]]
)
end
ChoGGi.ComFuncs.OpenInListChoice{
callback = CallBackFunc,
items = item_list,
title = Strings[302535920001336--[[Export When This Amount]]],
hint = Strings[302535920000106--[[Current]]] .. ": " .. hint,
skip_sort = true,
}
end
function ChoGGi.MenuFuncs.SetSpaceElevatorTransferAmount(action)
local setting_name = action.setting_name
local title = action.setting_msg
local r = const.ResourceScale
local default_setting = SpaceElevator[setting_name] / r
local UserSettings = ChoGGi.UserSettings
local id = "SpaceElevator"
local item_list = {
{text = Translate(1000121--[[Default]]) .. ": " .. default_setting, value = default_setting},
{text = 10, value = 10},
{text = 15, value = 15},
{text = 20, value = 20},
{text = 25, value = 25},
{text = 50, value = 50},
{text = 75, value = 75},
{text = 100, value = 100},
{text = 250, value = 250},
{text = 500, value = 500},
{text = 1000, value = 1000},
}
if not UserSettings.BuildingSettings[id] then
UserSettings.BuildingSettings[id] = {}
end
local hint = default_setting
local setting = UserSettings.BuildingSettings[id]
if setting and setting[setting_name] then
hint = setting[setting_name]
end
local function CallBackFunc(choice)
if choice.nothing_selected then
return
end
choice = choice[1]
local value = choice.value
if type(value) == "number" then
value = value * r
if value == default_setting * r then
setting[setting_name] = nil
else
setting[setting_name] = value
end
local objs = UICity.labels.SpaceElevator or ""
for i = 1, #objs do
ChoGGi.ComFuncs.SetTaskReqAmount(objs[i], value, "export_request", setting_name)
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
ChoGGi.ComFuncs.SettingState(choice.text),
title
)
end
end
ChoGGi.ComFuncs.OpenInListChoice{
callback = CallBackFunc,
items = item_list,
title = Strings[title],
hint = Strings[302535920000106--[[Current]]] .. ": " .. hint,
skip_sort = true,
}
end
function ChoGGi.MenuFuncs.SpaceElevatorExport_Toggle()
ChoGGi.UserSettings.SpaceElevatorToggleInstantExport = ChoGGi.ComFuncs.ToggleValue(ChoGGi.UserSettings.SpaceElevatorToggleInstantExport)
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.SpaceElevatorToggleInstantExport),
Strings[302535920001330--[[Instant Export On Toggle]]]
)
end
function ChoGGi.MenuFuncs.SetStorageAmountOfDinerGrocery()
local default_setting = 5
local UserSettings = ChoGGi.UserSettings
local r = const.ResourceScale
local item_list = {
{text = Translate(1000121--[[Default]]) .. ": " .. default_setting, value = default_setting},
{text = 10, value = 10},
{text = 15, value = 15},
{text = 20, value = 20},
{text = 25, value = 25},
{text = 50, value = 50},
{text = 75, value = 75},
{text = 100, value = 100},
{text = 250, value = 250},
{text = 500, value = 500},
}
-- other hint type
local hint = default_setting
if UserSettings.ServiceWorkplaceFoodStorage then
hint = UserSettings.ServiceWorkplaceFoodStorage
end
local function CallBackFunc(choice)
if choice.nothing_selected then
return
end
choice = choice[1]
local value = choice.value
if type(value) == "number" then
value = value * r
if value == default_setting * r then
UserSettings.ServiceWorkplaceFoodStorage = nil
else
UserSettings.ServiceWorkplaceFoodStorage = value
end
local function SetStor(cls)
local objs = ChoGGi.ComFuncs.MapGet(cls)
for i = 1, #objs do
local o = objs[i]
o.consumption_stored_resources = value
o.consumption_max_storage = value
end
end
SetStor("Diner")
SetStor("Grocery")
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
ChoGGi.ComFuncs.SettingState(choice.text),
Strings[302535920000164--[[Storage Amount Of Diner & Grocery]]]
)
end
end
ChoGGi.ComFuncs.OpenInListChoice{
callback = CallBackFunc,
items = item_list,
title = Strings[302535920000105--[[Set Food Storage]]],
hint = Strings[302535920000106--[[Current]]] .. ": " .. hint,
skip_sort = true,
}
end
function ChoGGi.MenuFuncs.AlwaysDustyBuildings_Toggle()
if ChoGGi.UserSettings.AlwaysDustyBuildings then
ChoGGi.UserSettings.AlwaysDustyBuildings = nil
-- dust clean up
local objs = UICity.labels.Building or ""
for i = 1, #objs do
objs[i].ChoGGi_AlwaysDust = nil
end
else
ChoGGi.UserSettings.AlwaysDustyBuildings = true
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000107--[[%s: I must not fear. Fear is the mind-killer. Fear is the little-death that brings total obliteration.
I will face my fear. I will permit it to pass over me and through me,
and when it has gone past I will turn the inner eye to see its path.
Where the fear has gone there will be nothing. Only I will remain.]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.AlwaysDustyBuildings)),
Strings[302535920000174--[[Always Dusty]]]
)
end
local function DustCleanUp(label)
for i = 1, #label do
ApplyToObjAndAttaches(label[i], SetObjDust, 0)
end
end
function ChoGGi.MenuFuncs.AlwaysCleanBuildings_Toggle()
if ChoGGi.UserSettings.AlwaysCleanBuildings then
ChoGGi.UserSettings.AlwaysCleanBuildings = nil
else
ChoGGi.UserSettings.AlwaysCleanBuildings = true
local labels = UICity.labels
DustCleanUp(labels.Building or "")
DustCleanUp(labels.GridElements or "")
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.AlwaysCleanBuildings),
Strings[302535920000037--[[Always Clean]]]
)
end
function ChoGGi.MenuFuncs.SetProtectionRadius()
local obj = ChoGGi.ComFuncs.SelObject()
if not obj or not obj.protect_range then
MsgPopup(
Strings[302535920000108--[[Select something with a protect_range (MDSLaser/DefenceTower).]]],
Strings[302535920000178--[[Protection Radius]]]
)
return
end
local id = RetTemplateOrClass(obj)
local cls_obj = g_Classes[id]
local default_setting = cls_obj.protect_range or cls_obj:GetClassValue("protect_range")
local item_list = {
{text = Translate(1000121--[[Default]]) .. ": " .. default_setting, value = default_setting},
{text = 40, value = 40},
{text = 80, value = 80},
{text = 160, value = 160},
{text = 320, value = 320, hint = Strings[302535920000111--[[Cover the entire map from the centre.]]]},
{text = 640, value = 640, hint = Strings[302535920000112--[[Cover the entire map from a corner.]]]},
}
if not ChoGGi.UserSettings.BuildingSettings[id] then
ChoGGi.UserSettings.BuildingSettings[id] = {}
end
local hint = default_setting
local setting = ChoGGi.UserSettings.BuildingSettings[id]
if setting and setting.protect_range then
hint = tostring(setting.protect_range)
end
local function CallBackFunc(choice)
if choice.nothing_selected then
return
end
local value = choice[1].value
if type(value) == "number" then
local objs = ChoGGi.ComFuncs.MapGet(id)
for i = 1, #objs do
local obj = objs[i]
obj.protect_range = value
obj.shoot_range = value * guim
end
if value == default_setting then
ChoGGi.UserSettings.BuildingSettings[id].protect_range = nil
else
ChoGGi.UserSettings.BuildingSettings[id].protect_range = value
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000113--[[%s range is now %s.]]]:format(RetName(obj), choice[1].text),
Strings[302535920000178--[[Protection Radius]]]
)
end
end
ChoGGi.ComFuncs.OpenInListChoice{
callback = CallBackFunc,
items = item_list,
title = Strings[302535920000114--[[Set Protection Radius]]],
hint = Strings[302535920000106--[[Current]]] .. ": " .. hint .. "\n\n" ..Strings[302535920000115--[[Toggle selection to update visible hex grid.]]],
skip_sort = true,
}
end
function ChoGGi.MenuFuncs.UnlockLockedBuildings()
local everything = Strings[302535920000306--[[Everything]]]
local item_list = {
{
text = " " .. everything,
value = everything,
},
}
local c = #item_list
local BuildingTemplates = BuildingTemplates
local GetBuildingTechsStatus = GetBuildingTechsStatus
for id, bld in pairs(BuildingTemplates) do
if not GetBuildingTechsStatus(id) then
c = c + 1
item_list[c] = {
text = Translate(bld.display_name),
value = id,
}
end
end
local function CallBackFunc(choice)
if choice.nothing_selected then
return
end
local UnlockBuilding = UnlockBuilding
-- If everything then ignore the choices and just use the itemlist
if table.find(choice, "value", everything) then
choice = item_list
end
for i = 1, #choice do
UnlockBuilding(choice[i].value)
end
ChoGGi.ComFuncs.UpdateBuildMenu()
MsgPopup(
Strings[302535920000116--[[%s: Buildings unlocked.]]]:format(#choice),
Strings[302535920000180--[[Unlock Locked Buildings]]]
)
end
ChoGGi.ComFuncs.OpenInListChoice{
callback = CallBackFunc,
items = item_list,
title = Strings[302535920000117--[[Unlock Buildings]]],
hint = Strings[302535920000118--[[Pick the buildings you want to unlock (use Ctrl/Shift for multiple).]]],
multisel = true,
}
end
function ChoGGi.MenuFuncs.PipesPillarsSpacing_Toggle()
ChoGGi.ComFuncs.SetConstsG("PipesPillarSpacing", ChoGGi.ComFuncs.ValueRetOpp(Consts.PipesPillarSpacing, 1000, ChoGGi.Consts.PipesPillarSpacing))
ChoGGi.ComFuncs.SetSavedConstSetting("PipesPillarSpacing")
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000119--[[%s: Is that a rocket in your pocket?]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.PipesPillarSpacing)),
T(4713, "Pipes pillar spacing")
)
end
function ChoGGi.MenuFuncs.UnlimitedConnectionLength_Toggle()
if ChoGGi.UserSettings.UnlimitedConnectionLength then
ChoGGi.UserSettings.UnlimitedConnectionLength = nil
GridConstructionController.max_hex_distance_to_allow_build = 20
const.PassageConstructionGroupMaxSize = 20
else
ChoGGi.UserSettings.UnlimitedConnectionLength = true
GridConstructionController.max_hex_distance_to_allow_build = 1000
const.PassageConstructionGroupMaxSize = 1000
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000119--[[%s: Is that a rocket in your pocket?]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.UnlimitedConnectionLength)),
Strings[302535920000184--[[Unlimited Connection Length]]]
)
end
local function BuildingConsumption_Toggle(type1, str1, type2, func1, func2, str2)
local obj = SelectedObj
if not obj or not obj[type1] then
MsgPopup(
str1,
T(3980, "Buildings")
)
return
end
local id = RetTemplateOrClass(obj)
local UserSettings = ChoGGi.UserSettings
if not UserSettings.BuildingSettings[id] then
UserSettings.BuildingSettings[id] = {}
end
local setting = UserSettings.BuildingSettings[id]
local which
if setting[type2] then
setting[type2] = nil
which = func1
else
setting[type2] = true
which = func2
end
local ComFuncs = ChoGGi.ComFuncs
local blds = ComFuncs.MapGet(id)
for i = 1, #blds do
ComFuncs[which](blds[i])
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
RetName(obj) .. " " .. str2,
which
)
end
function ChoGGi.MenuFuncs.BuildingPower_Toggle()
BuildingConsumption_Toggle(
"electricity_consumption",
Strings[302535920000120--[[You need to select a building that uses electricity.]]],
"nopower",
"AddBuildingElecConsump",
"RemoveBuildingElecConsump",
Translate(683--[[Power Consumption]])
)
end
function ChoGGi.MenuFuncs.BuildingWater_Toggle()
BuildingConsumption_Toggle(
"water_consumption",
Strings[302535920000121--[[You need to select a building that uses water.]]],
"nowater",
"AddBuildingWaterConsump",
"RemoveBuildingWaterConsump",
Translate(656--[[Water consumption]])
)
end
function ChoGGi.MenuFuncs.BuildingAir_Toggle()
BuildingConsumption_Toggle(
"air_consumption",
Strings[302535920001250--[[You need to select a building that uses oxygen.]]],
"noair",
"AddBuildingAirConsump",
"RemoveBuildingAirConsump",
Translate(657--[[Oxygen Consumption]])
)
end
function ChoGGi.MenuFuncs.SetMaxChangeOrDischarge()
local obj = SelectedObj
if not obj or obj and not obj:IsKindOfClasses{"ElectricityStorage", "AirStorage", "WaterStorage"} then
MsgPopup(
Strings[302535920000122--[[You need to select something that has capacity (air/water/elec).]]],
Strings[302535920000188--[[Set Charge & Discharge Rates]]]
)
return
end
local id = RetTemplateOrClass(obj)
local name = Translate(obj.display_name)
local r = const.ResourceScale
-- get type of capacity
local cap_type, charge, discharge
if obj:IsKindOf("ElectricityStorage") then
cap_type, charge, discharge = "electricity", "max_electricity_charge", "max_electricity_discharge"
elseif obj:IsKindOf("AirStorage") then
cap_type, charge, discharge = "air", "max_air_charge", "max_air_discharge"
elseif obj:IsKindOf("WaterStorage") then
cap_type, charge, discharge = "water", "max_water_charge", "max_water_discharge"
end
if not cap_type then
return
end
-- get default amount
local template = BuildingTemplates[id]
local default_settingC = template[charge] / r
local default_settingD = template[discharge] / r
local item_list = {
{text = Translate(1000121--[[Default]]), value = Translate(1000121--[[Default]]), hint = Strings[302535920000124--[[Charge]]]
.. ": " .. default_settingC .. " / " .. Strings[302535920000125--[[Discharge]]]
.. ": " .. default_settingD},
{text = 25, value = 25},
{text = 50, value = 50},
{text = 75, value = 75},
{text = 100, value = 100},
{text = 250, value = 250},
{text = 500, value = 500},
{text = 1000, value = 1000},
{text = 2500, value = 2500},
{text = 5000, value = 5000},
{text = 10000, value = 10000},
}
--check if there's an entry for building
if not ChoGGi.UserSettings.BuildingSettings[id] then
ChoGGi.UserSettings.BuildingSettings[id] = {}
end
local hint = Strings[302535920000124--[[Charge]]] .. ": " .. default_settingC .. " / " .. Strings[302535920000125--[[Discharge]]] .. ": " .. default_settingD
local setting = ChoGGi.UserSettings.BuildingSettings[id]
if setting then
if setting.charge and setting.discharge then
hint = Strings[302535920000124--[[Charge]]] .. ": " .. (setting.charge / r) .. " / " .. Strings[302535920000125--[[Discharge]]] .. ": " .. (setting.discharge / r)
elseif setting.charge then
hint = setting.charge / r
elseif setting.discharge then
hint = setting.discharge / r
end
end
local function CallBackFunc(choice)
if choice.nothing_selected then
return
end
local value = choice[1].value
local check1 = choice[1].check1
local check2 = choice[1].check2
if type(value) == "number" then
local numberC = value * r
local numberD = value * r
if value == Translate(1000121--[[Default]]) then
if check1 then
setting.charge = nil
numberC = default_settingC * r
end
if check2 then
setting.discharge = nil
numberD = default_settingD * r
end
else
if check1 then
setting.charge = numberC
end
if check2 then
setting.discharge = numberD
end
end
-- updating time
if cap_type == "electricity" then
local objs = UICity.labels.Power or ""
for i = 1, #objs do
local o = objs[i]
if RetTemplateOrClass(o) == id then
if check1 then
o[cap_type].max_charge = numberC
o[charge] = numberC
end
if check2 then
o[cap_type].max_discharge = numberD
o[discharge] = numberD
end
ChoGGi.ComFuncs.ToggleWorking(o)
end
end
else -- water and air
local objs = UICity.labels["Life-Support"] or ""
for i = 1, #objs do
local o = objs[i]
if RetTemplateOrClass(o) == id then
if check1 then
o[cap_type].max_charge = numberC
o[charge] = numberC
end
if check2 then
o[cap_type].max_discharge = numberD
o[discharge] = numberD
end
ChoGGi.ComFuncs.ToggleWorking(o)
end
end
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000128--[[%s rate is now: %s]]]:format(RetName(obj), choice[1].text),
Strings[302535920000188--[[Set Charge & Discharge Rates]]]
)
end
end
ChoGGi.ComFuncs.OpenInListChoice{
callback = CallBackFunc,
items = item_list,
title = Strings[302535920000129--[[Set]]] .. " " .. name .. " " .. Strings[302535920000130--[[Dis/Charge Rates]]],
hint = Strings[302535920000131--[[Current rate]]] .. ": " .. hint,
skip_sort = true,
checkboxes = {
at_least_one = true,
{
title = Strings[302535920000124--[[Charge]]],
hint = Strings[302535920000132--[[Change charge rate]]],
checked = true,
},
{
title = Strings[302535920000125--[[Discharge]]],
hint = Strings[302535920000133--[[Change discharge rate]]],
},
},
}
end
function ChoGGi.MenuFuncs.FarmShiftsAllOn()
local labels = UICity.labels
local objs = labels.BaseFarm or ""
for i = 1, #objs do
local obj = objs[i]
obj.closed_shifts[1] = false
obj.closed_shifts[2] = false
obj.closed_shifts[3] = false
end
--BaseFarm doesn't include FungalFarm...
objs = labels.FungalFarm or ""
for i = 1, #objs do
local obj = objs[i]
obj.closed_shifts[1] = false
obj.closed_shifts[2] = false
obj.closed_shifts[3] = false
end
MsgPopup(
Strings[302535920000135--[[Well, I been working in a coal mine
Going down, down
Working in a coal mine
Whew, about to slip down]]],
Strings[302535920000192--[[Farm Shifts All On]]]
)
end
function ChoGGi.MenuFuncs.SetProductionAmount()
local obj = SelectedObj
if not obj or obj and not obj:IsKindOfClasses{"WaterProducer", "AirProducer", "ElectricityProducer", "ResourceProducer"} then
MsgPopup(
Strings[302535920000136--[[Select something that produces (air, water, electricity, other).]]],
Strings[302535920000194--[[Production Amount Set]]]
)
return
end
local id = RetTemplateOrClass(obj)
local name = Translate(obj.display_name)
local r = const.ResourceScale
-- get type of producer/base amount
local prod_type, default_setting
if obj:IsKindOf("WaterProducer") then
prod_type, default_setting = "water", obj:GetClassValue("water_production") / r
elseif obj:IsKindOf("AirProducer") then
prod_type, default_setting = "air", obj:GetClassValue("air_production") / r
elseif obj:IsKindOf("ElectricityProducer") then
prod_type, default_setting = "electricity", obj:GetClassValue("electricity_production") / r
elseif obj:IsKindOf("ResourceProducer") then
prod_type, default_setting = "other", obj:GetClassValue("production_per_day1") / r
end
local item_list = {
{text = Translate(1000121--[[Default]]) .. ": " .. default_setting, value = default_setting},
{text = 25, value = 25},
{text = 50, value = 50},
{text = 75, value = 75},
{text = 100, value = 100},
{text = 250, value = 250},
{text = 500, value = 500},
{text = 1000, value = 1000},
{text = 2500, value = 2500},
{text = 5000, value = 5000},
{text = 10000, value = 10000},
{text = 25000, value = 25000},
{text = 50000, value = 50000},
{text = 100000, value = 100000},
}
-- check if there's an entry for building
if not ChoGGi.UserSettings.BuildingSettings[id] then
ChoGGi.UserSettings.BuildingSettings[id] = {}
end
local hint = default_setting
local setting = ChoGGi.UserSettings.BuildingSettings[id]
if setting and setting.production then
hint = tostring(setting.production / r)
end
local function CallBackFunc(choice)
if choice.nothing_selected then
return
end
local value = choice[1].value
if type(value) == "number" then
local amount = value * r
-- setting we use to actually update prod
if value == default_setting then
-- remove setting as we reset building type to default (we don't want to call it when we place a new building if nothing is going to be changed)
ChoGGi.UserSettings.BuildingSettings[id].production = nil
else
-- update/create saved setting
ChoGGi.UserSettings.BuildingSettings[id].production = amount
end
-- all this just to update the displayed amount :)
local function SetProd(label)
local objs = ChoGGi.ComFuncs.MapGet(label)
for i = 1, #objs do
local o = objs[i]
if RetTemplateOrClass(o) == id then
o[prod_type]:SetProduction(amount)
end
end
end
if prod_type == "electricity" then
-- electricity
SetProd("Power")
elseif prod_type == "water" or prod_type == "air" then
-- water/air
SetProd("Life-Support")
else -- other prod
local function SetProdOther(label)
local objs = ChoGGi.ComFuncs.MapGet(label)
for i = 1, #objs do
local o = objs[i]
if RetTemplateOrClass(o) == id then
o:GetProducerObj().production_per_day = amount
o:GetProducerObj():Produce(amount)
end
end
end
-- extractors/factories
SetProdOther("Production")
-- moholemine/theexvacator
SetProdOther("Wonders")
-- farms
if id:find("Farm") then
SetProdOther("BaseFarm")
SetProdOther("FungalFarm")
end
end
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000137--[[%s production is now: %s]]]:format(RetName(obj), choice[1].text),
Strings[302535920000194--[[Production Amount Set]]]
)
end
ChoGGi.ComFuncs.OpenInListChoice{
callback = CallBackFunc,
items = item_list,
title = Strings[302535920000129--[[Set]]] .. " " .. name .. " " .. Strings[302535920000139--[[Production Amount]]],
hint = Strings[302535920000140--[[Current production]]] .. ": " .. hint,
skip_sort = true,
}
end
function ChoGGi.MenuFuncs.SetFullyAutomatedBuildings()
local obj = SelectedObj
if not obj or not IsKindOf(obj, "Workplace") then
MsgPopup(
Strings[302535920000141--[[Select a building with workers.]]],
Strings[302535920000196--[[Fully Automated Building]]]
)
return
end
local id = RetTemplateOrClass(obj)
local item_list = {
{text = Translate(251103844022--[[Disable]]), value = "Disable"},
{text = 100, value = 100},
{text = 150, value = 150},
{text = 250, value = 250},
{text = 500, value = 500},
{text = 1000, value = 1000},
{text = 2500, value = 2500},
{text = 5000, value = 5000},
{text = 10000, value = 10000},
{text = 25000, value = 25000},
{text = 50000, value = 50000},
{text = 100000, value = 100000},
}
local function CallBackFunc(choice)
if choice.nothing_selected then
return
end
local value = choice[1].value
if value == "Disable" then
value = nil
if choice[1].check then
--~ obj.max_workers = obj:GetClassValue("max_workers")
obj.automation = obj:GetClassValue("automation")
obj.auto_performance = obj:GetClassValue("auto_performance")
ChoGGi.ComFuncs.ToggleWorking(obj)
else
local blds = ChoGGi.ComFuncs.MapGet(obj.class)
if blds[1] then
-- GetClassValue gets the metatable for the obj, so just grab the first one and use those values
--~ local max_workers = blds[1]:GetClassValue("max_workers")
local automation = blds[1]:GetClassValue("automation")
local auto_performance = blds[1]:GetClassValue("auto_performance")
for i = 1, #blds do
local bld = blds[i]
--~ bld.max_workers = max_workers
bld.automation = automation
bld.auto_performance = auto_performance
ChoGGi.ComFuncs.ToggleWorking(bld)
end
end
end
elseif type(value) == "number" then
if choice[1].check then
--~ obj.max_workers = 0
obj.automation = 1
obj.auto_performance = value
ChoGGi.ComFuncs.ToggleWorking(obj)
else
local blds = ChoGGi.ComFuncs.MapGet(obj.class)
for i = 1, #blds do
local bld = blds[i]
--~ bld.max_workers = 0
bld.automation = 1
bld.auto_performance = value
ChoGGi.ComFuncs.ToggleWorking(bld)
end
end
end
ChoGGi.UserSettings.BuildingSettings[id].auto_performance = value
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000143--[["%s
I presume the PM's in favour of the scheme because it'll reduce unemployment."]]]:format(choice[1].text),
Strings[302535920000196--[[Fully Automated Building]]]
)
end
-- check if there's an entry for building
if not ChoGGi.UserSettings.BuildingSettings[id] then
ChoGGi.UserSettings.BuildingSettings[id] = {}
end
local hint = "none"
local setting = ChoGGi.UserSettings.BuildingSettings[id]
if setting and setting.performance then
hint = tostring(setting.performance)
end
local name = RetName(obj)
ChoGGi.ComFuncs.OpenInListChoice{
callback = CallBackFunc,
items = item_list,
title = name .. ": " .. Strings[302535920000144--[[Automated Performance]]],
hint = Strings[302535920000145--[[Sets performance of all automated buildings of this type]]] .. "\n" .. Strings[302535920000106--[[Current]]] .. ": " .. hint,
skip_sort = true,
checkboxes = {
{
title = Strings[302535920000769--[[Selected]]],
hint = Strings[302535920000147--[[Only apply to selected object instead of all %s.]]]:format(name),
},
},
}
end
do -- SchoolTrainAll_Toggle/SanatoriumCureAll_Toggle
-- used to add or remove traits from schools/sanitariums
local function BuildingsSetAll_Traits(cls, traits, bool)
local objs = MapGet("map", cls)
for i = 1, #objs do
local obj = objs[i]
for j = 1, #traits do
if bool == true then
obj:SetTrait(j, nil)
else
obj:SetTrait(j, traits[j])
end
end
end
end
function ChoGGi.MenuFuncs.SchoolTrainAll_Toggle()
if ChoGGi.UserSettings.SchoolTrainAll then
ChoGGi.UserSettings.SchoolTrainAll = nil
BuildingsSetAll_Traits("School", ChoGGi.Tables.PositiveTraits, true)
else
ChoGGi.UserSettings.SchoolTrainAll = true
BuildingsSetAll_Traits("School", ChoGGi.Tables.PositiveTraits)
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000148--[["%s:
You keep your work station so clean, Jerome.
It's next to godliness. Isn't that what they say?"]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.SchoolTrainAll)),
Strings[302535920000200--[[Train All]]]
)
end
function ChoGGi.MenuFuncs.SanatoriumCureAll_Toggle()
if ChoGGi.UserSettings.SanatoriumCureAll then
ChoGGi.UserSettings.SanatoriumCureAll = nil
BuildingsSetAll_Traits("Sanatorium", ChoGGi.Tables.NegativeTraits, true)
else
ChoGGi.UserSettings.SanatoriumCureAll = true
BuildingsSetAll_Traits("Sanatorium", ChoGGi.Tables.NegativeTraits)
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000149--[[%s:
There's more vodka in this piss than there is piss.]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.SanatoriumCureAll)),
Strings[302535920000198--[[Cure All]]]
)
end
end -- do
function ChoGGi.MenuFuncs.ShowAllTraits_Toggle()
if ChoGGi.UserSettings.SanatoriumSchoolShowAllTraits then
ChoGGi.UserSettings.SanatoriumSchoolShowAllTraits = nil
g_SchoolTraits = table.copy(const.SchoolTraits)
g_SanatoriumTraits = table.copy(const.SanatoriumTraits)
else
ChoGGi.UserSettings.SanatoriumSchoolShowAllTraits = true
g_SchoolTraits = ChoGGi.Tables.PositiveTraits
g_SanatoriumTraits = ChoGGi.Tables.NegativeTraits
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000150--[[%s: Good for what ails you]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.SanatoriumSchoolShowAllTraits)),
Strings[302535920000202--[[Show All Traits]]]
)
end
function ChoGGi.MenuFuncs.SanatoriumSchoolShowAll()
ChoGGi.UserSettings.SanatoriumSchoolShowAll = ChoGGi.ComFuncs.ToggleValue(ChoGGi.UserSettings.SanatoriumSchoolShowAll)
Sanatorium.max_traits = ChoGGi.ComFuncs.ValueRetOpp(Sanatorium.max_traits, 3, #ChoGGi.Tables.NegativeTraits)
School.max_traits = ChoGGi.ComFuncs.ValueRetOpp(School.max_traits, 3, #ChoGGi.Tables.PositiveTraits)
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000150--[[%s: Good for what ails you]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.SanatoriumSchoolShowAll)),
Strings[302535920000204--[[Show Full List]]]
)
end
function ChoGGi.MenuFuncs.MaintenanceFreeBuildingsInside_Toggle()
ChoGGi.UserSettings.InsideBuildingsNoMaintenance = ChoGGi.ComFuncs.ToggleValue(ChoGGi.UserSettings.InsideBuildingsNoMaintenance)
local inside_main = ChoGGi.UserSettings.InsideBuildingsNoMaintenance
local objs = UICity.labels.InsideBuildings or ""
for i = 1, #objs do
local obj = objs[i]
if obj:IsKindOf("RequiresMaintenance") then
if inside_main then
obj.ChoGGi_InsideBuildingsNoMaintenance = true
obj.maintenance_build_up_per_hr = -10000
else
if not obj.ChoGGi_RemoveMaintenanceBuildUp then
obj.maintenance_build_up_per_hr = nil
end
obj.ChoGGi_InsideBuildingsNoMaintenance = nil
end
end
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000151--[[%s: The spice must flow!]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.InsideBuildingsNoMaintenance)),
Strings[302535920000206--[[Maintenance Free Inside]]]
)
end
function ChoGGi.MenuFuncs.MaintenanceFreeBuildings_Toggle()
ChoGGi.UserSettings.RemoveMaintenanceBuildUp = ChoGGi.ComFuncs.ToggleValue(ChoGGi.UserSettings.RemoveMaintenanceBuildUp)
local remove_build = ChoGGi.UserSettings.RemoveMaintenanceBuildUp
local objs = UICity.labels.Building or ""
for i = 1, #objs do
local obj = objs[i]
if obj:IsKindOf("RequiresMaintenance") then
if remove_build then
obj.ChoGGi_RemoveMaintenanceBuildUp = true
obj.maintenance_build_up_per_hr = -10000
elseif not obj.ChoGGi_InsideBuildingsNoMaintenance then
obj.ChoGGi_RemoveMaintenanceBuildUp = nil
obj.maintenance_build_up_per_hr = nil
end
end
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000151--[[%s: The spice must flow!]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.RemoveMaintenanceBuildUp)),
Strings[302535920000208--[[Maintenance Free]]]
)
end
function ChoGGi.MenuFuncs.MoistureVaporatorPenalty_Toggle()
const.MoistureVaporatorRange = ChoGGi.ComFuncs.NumRetBool(const.MoistureVaporatorRange, 0, ChoGGi.Consts.MoistureVaporatorRange)
const.MoistureVaporatorPenaltyPercent = ChoGGi.ComFuncs.NumRetBool(const.MoistureVaporatorPenaltyPercent, 0, ChoGGi.Consts.MoistureVaporatorPenaltyPercent)
ChoGGi.ComFuncs.SetSavedConstSetting("MoistureVaporatorRange")
ChoGGi.ComFuncs.SetSavedConstSetting("MoistureVaporatorRange")
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000152--[["%s: New penalty range"]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.MoistureVaporatorRange)),
Strings[302535920000210--[[Moisture Vaporator Penalty]]],
{expiration = 60}
)
end
function ChoGGi.MenuFuncs.CropFailThreshold_Toggle()
Consts.CropFailThreshold = ChoGGi.ComFuncs.NumRetBool(Consts.CropFailThreshold, 0, ChoGGi.Consts.CropFailThreshold)
ChoGGi.ComFuncs.SetSavedConstSetting("CropFailThreshold")
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000153--[["%s:
So, er, we the crew of the Eagle 5, if we do encounter, make first contact with alien beings,
it is a friendship greeting from the children of our small but great planet of Potatoho."]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.CropFailThreshold)),
T(4711, "Crop Fail Threshold")
)
end
function ChoGGi.MenuFuncs.CheapConstruction_Toggle()
local list = {
"Metals_cost_modifier",
"Metals_dome_cost_modifier",
"PreciousMetals_cost_modifier",
"PreciousMetals_dome_cost_modifier",
"Concrete_cost_modifier",
"Concrete_dome_cost_modifier",
"Polymers_dome_cost_modifier",
"Polymers_cost_modifier",
"Electronics_cost_modifier",
"Electronics_dome_cost_modifier",
"MachineParts_cost_modifier",
"MachineParts_dome_cost_modifier",
"rebuild_cost_modifier",
}
local Consts = Consts
local cConsts = ChoGGi.Consts
local SetConstsG = ChoGGi.ComFuncs.SetConstsG
local ValueRetOpp = ChoGGi.ComFuncs.ValueRetOpp
local SetSavedConstSetting = ChoGGi.ComFuncs.SetSavedConstSetting
for i = 1, #list do
local name = list[i]
SetConstsG(name, ValueRetOpp(Consts[name], -100, cConsts[name]))
SetSavedConstSetting(name, Consts[name])
end
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000154--[[%s:
Your home will not be a hut on some swampy outback planet your home will be the entire universe.]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.Metals_cost_modifier)),
Strings[302535920000214--[[Cheap Construction]]]
)
end
function ChoGGi.MenuFuncs.BuildingDamageCrime_Toggle()
ChoGGi.ComFuncs.SetConstsG("CrimeEventSabotageBuildingsCount", ChoGGi.ComFuncs.ToggleBoolNum(Consts.CrimeEventSabotageBuildingsCount))
ChoGGi.ComFuncs.SetConstsG("CrimeEventDestroyedBuildingsCount", ChoGGi.ComFuncs.ToggleBoolNum(Consts.CrimeEventDestroyedBuildingsCount))
ChoGGi.ComFuncs.SetSavedConstSetting("CrimeEventSabotageBuildingsCount")
ChoGGi.ComFuncs.SetSavedConstSetting("CrimeEventDestroyedBuildingsCount")
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000155--[[%s:
We were all feeling a bit shagged and fagged and fashed,
it having been an evening of some small energy expenditure, O my brothers.
So we got rid of the auto and stopped off at the Korova for a nightcap.]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.CrimeEventSabotageBuildingsCount)),
Strings[302535920000216--[[Building Damage Crime]]]
)
end
function ChoGGi.MenuFuncs.CablesAndPipesNoBreak_Toggle()
ChoGGi.UserSettings.CablesAndPipesNoBreak = not ChoGGi.UserSettings.CablesAndPipesNoBreak
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000156--[[%s: Aliens? We gotta deal with aliens too?]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.CablesAndPipesNoBreak)),
Strings[302535920000218--[[No Chance Of Break]]]
)
end
function ChoGGi.MenuFuncs.CablesAndPipesInstant_Toggle()
ChoGGi.ComFuncs.SetConstsG("InstantCables", ChoGGi.ComFuncs.ToggleBoolNum(Consts.InstantCables))
ChoGGi.ComFuncs.SetConstsG("InstantPipes", ChoGGi.ComFuncs.ToggleBoolNum(Consts.InstantPipes))
ChoGGi.ComFuncs.SetSavedConstSetting("InstantCables")
ChoGGi.ComFuncs.SetSavedConstSetting("InstantPipes")
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000156--[[%s: Aliens? We gotta deal with aliens too?]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.InstantCables)),
T(134, "Instant Build")
)
end
function ChoGGi.MenuFuncs.RemoveBuildingLimits_Toggle()
ChoGGi.UserSettings.RemoveBuildingLimits = ChoGGi.ComFuncs.ToggleValue(ChoGGi.UserSettings.RemoveBuildingLimits)
ChoGGi.ComFuncs.SetBuildingLimits(ChoGGi.UserSettings.RemoveBuildingLimits)
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.RemoveBuildingLimits),
Strings[302535920000230--[[Remove Building Limits]]]
)
end
function ChoGGi.MenuFuncs.Building_wonder_Toggle()
ChoGGi.UserSettings.Building_wonder = ChoGGi.ComFuncs.ToggleValue(ChoGGi.UserSettings.Building_wonder)
-- If the buildmenu is open
ChoGGi.ComFuncs.UpdateBuildMenu()
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.Building_wonder),
Strings[302535920000159--[[Unlimited Wonders]]]
)
end
function ChoGGi.MenuFuncs.Building_dome_spot_Toggle()
ChoGGi.UserSettings.Building_dome_spot = ChoGGi.ComFuncs.ToggleValue(ChoGGi.UserSettings.Building_dome_spot)
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000160--[[%s: Freedom for spires!]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.Building_dome_spot)),
Strings[302535920000226--[[Remove Spire Point Limit]]]
)
end
function ChoGGi.MenuFuncs.Building_instant_build_Toggle()
ChoGGi.UserSettings.Building_instant_build = ChoGGi.ComFuncs.ToggleValue(ChoGGi.UserSettings.Building_instant_build)
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
Strings[302535920000161--[[%s: Buildings Instant Build]]]:format(ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.Building_instant_build)),
Strings[302535920001241--[[Instant Build]]]
)
end
function ChoGGi.MenuFuncs.Building_hide_from_build_menu_Toggle()
local BuildingTemplates = BuildingTemplates
local bc = BuildCategories
if not table.find(bc, "id", "HiddenX") then
bc[#bc+1] = {
id = "HiddenX",
name = Translate(1000155--[[Hidden]]),
image = "UI/Icons/bmc_placeholder.tga",
highlight = "UI/Icons/bmc_placeholder_shine.tga",
}
end
if ChoGGi.UserSettings.Building_hide_from_build_menu then
ChoGGi.UserSettings.Building_hide_from_build_menu = nil
for _, bld in pairs(BuildingTemplates) do
if type(bld.hide_from_build_menu_ChoGGi) ~= "nil" then
bld.hide_from_build_menu = bld.hide_from_build_menu_ChoGGi
bld.hide_from_build_menu_ChoGGi = nil
end
if bld.group == "Hidden" then
bld.build_category = "Hidden"
end
end
else
ChoGGi.UserSettings.Building_hide_from_build_menu = true
for _, value in pairs(BuildMenuPrerequisiteOverrides) do
if value == "hide" then
value = true
end
end
BuildMenuPrerequisiteOverrides.StorageMysteryResource = true
BuildMenuPrerequisiteOverrides.MechanizedDepotMysteryResource = true
for _, bld in pairs(BuildingTemplates) do
if bld.id ~= "LifesupportSwitch" and bld.id ~= "ElectricitySwitch" then
bld.hide_from_build_menu_ChoGGi = bld.hide_from_build_menu
bld.hide_from_build_menu = false
end
if bld.group == "Hidden" and bld.id ~= "RocketLandingSite" and bld.id ~= "ForeignTradeRocket" then
bld.build_category = "HiddenX"
end
end
end
-- If the buildmenu is open
ChoGGi.ComFuncs.UpdateBuildMenu()
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
ChoGGi.ComFuncs.SettingState(ChoGGi.UserSettings.Building_hide_from_build_menu),
Strings[302535920000224--[[Show Hidden Buildings]]]
)
end
function ChoGGi.MenuFuncs.SetUIRangeBuildingRadius(action)
local id = action.bld_id
local msgpopup = action.bld_msg
local default_setting = g_Classes[id]:GetDefaultPropertyValue("UIRange")
local item_list = {
{text = Translate(1000121--[[Default]]) .. ": " .. default_setting, value = default_setting},
{text = 10, value = 10},
{text = 15, value = 15},
{text = 25, value = 25},
{text = 50, value = 50},
{text = 100, value = 100},
{text = 250, value = 250},
{text = 500, value = 500},
}
local UserSettings = ChoGGi.UserSettings
if not UserSettings.BuildingSettings[id] then
UserSettings.BuildingSettings[id] = {}
end
local hint = default_setting
if UserSettings.BuildingSettings[id].uirange then
hint = UserSettings.BuildingSettings[id].uirange
end
local function CallBackFunc(choice)
if choice.nothing_selected then
return
end
local value = choice[1].value
if type(value) == "number" then
if value == default_setting then
UserSettings.BuildingSettings[id].uirange = nil
else
UserSettings.BuildingSettings[id].uirange = value
end
-- find a better way to update radius...
local obj = SelectedObj
CreateRealTimeThread(function()
local SelectObj = SelectObj
local WaitMsg = WaitMsg
local objs = ChoGGi.ComFuncs.MapGet(id)
for i = 1, #objs do
local o = objs[i]
o:SetUIRange(value)
SelectObj(o)
WaitMsg("OnRender")
end
SelectObj(obj)
end)
ChoGGi.SettingFuncs.WriteSettings()
MsgPopup(
choice[1].text .. ":\n" .. msgpopup,
id
)
end
end
ChoGGi.ComFuncs.OpenInListChoice{
callback = CallBackFunc,
items = item_list,
title = Strings[302535920000129--[[Set]]] .. " " .. id .. " " .. Strings[302535920000163--[[Radius]]],
hint = Strings[302535920000106--[[Current]]] .. ": " .. hint,
skip_sort = true,
}
end
|
--------------------------------
-- @module TransitionProgressVertical
-- @extend TransitionProgress
-- @parent_module cc
--------------------------------
--
-- @function [parent=#TransitionProgressVertical] create
-- @param self
-- @param #float t
-- @param #cc.Scene scene
-- @return TransitionProgressVertical#TransitionProgressVertical ret (return value: cc.TransitionProgressVertical)
return nil
|
--this is a hack of the default nodes mod
-- Register stair
-- Node will be called nodes:stair_<subname>
--function nodes.register_stair(subname, recipeitem, groups, images, description,sounds, worldaligntex)
minetest.register_on_mods_loaded(function()
for name,def in pairs(minetest.registered_nodes) do
if string.gsub(name, "nodes:", "") ~= name and minetest.get_item_group(name, "notstairs") == 0 then --simple check for if a nodes node
local subname = string.gsub(name, "nodes:", "") --make it the name of the node
local recipeitem = name
local groups = def.groups
local images = def.tiles
local description = string.gsub(name, "nodes:", ""):gsub("^%l", string.upper).." Stair"
local sounds = def.sounds
local worldaligntex = false
-- Set backface culling and world-aligned textures
local stair_images = {}
for i, image in ipairs(images) do
if type(image) == "string" then
stair_images[i] = {
name = image,
backface_culling = true,
}
if worldaligntex then
stair_images[i].align_style = "world"
end
else
stair_images[i] = table.copy(image)
if stair_images[i].backface_culling == nil then
stair_images[i].backface_culling = true
end
if worldaligntex and stair_images[i].align_style == nil then
stair_images[i].align_style = "world"
end
end
end
local new_groups = table.copy(groups)
new_groups.stair = 1
minetest.register_node(":stairs:stair_" .. subname, {
description = description,
drawtype = "nodebox",
tiles = stair_images,
paramtype = "light",
paramtype2 = "facedir",
is_ground_content = false,
groups = new_groups,
sounds = sounds,
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0.0, 0.5},
{-0.5, 0.0, 0.0, 0.5, 0.5, 0.5},
},
},
})
if recipeitem then
-- Recipe matches appearence in inventory
minetest.register_craft({
output = 'stairs:stair_' .. subname .. ' 8',
recipe = {
{"", "", recipeitem},
{"", recipeitem, recipeitem},
{recipeitem, recipeitem, recipeitem},
},
})
minetest.register_craft({
output = 'stairs:stair_' .. subname .. ' 8',
recipe = {
{recipeitem, "", ""},
{recipeitem, recipeitem, ""},
{recipeitem, recipeitem, recipeitem},
},
})
-- Use nodes to craft full blocks again (1:1)
minetest.register_craft({
output = recipeitem .. ' 3',
recipe = {
{'stairs:stair_' .. subname, 'stairs:stair_' .. subname},
{'stairs:stair_' .. subname, 'stairs:stair_' .. subname},
},
})
-- Fuel
local baseburntime = minetest.get_craft_result({
method = "fuel",
width = 1,
items = {recipeitem}
}).time
if baseburntime > 0 then
minetest.register_craft({
type = "fuel",
recipe = 'stairs:stair_' .. subname,
burntime = math.floor(baseburntime * 0.75),
})
end
end
end
end
for name,def in pairs(minetest.registered_nodes) do
if string.gsub(name, "nodes:", "") ~= name and minetest.get_item_group(name, "notstairs") == 0 then --simple check for if a nodes node
local subname = string.gsub(name, "nodes:", "") --make it the name of the node
local recipeitem = name
local groups = def.groups
local images = def.tiles
local description = string.gsub(name, "nodes:", ""):gsub("^%l", string.upper).." Slab"
local sounds = def.sounds
local worldaligntex = false
-- Set world-aligned textures
local slab_images = {}
for i, image in ipairs(images) do
if type(image) == "string" then
slab_images[i] = {
name = image,
}
if worldaligntex then
slab_images[i].align_style = "world"
end
else
slab_images[i] = table.copy(image)
if worldaligntex and image.align_style == nil then
slab_images[i].align_style = "world"
end
end
end
local new_groups = table.copy(groups)
new_groups.slab = 1
minetest.register_node(":stairs:slab_" .. subname, {
description = description,
drawtype = "nodebox",
tiles = slab_images,
paramtype = "light",
paramtype2 = "wallmounted",
is_ground_content = false,
groups = new_groups,
sounds = sounds,
node_box = {
type = "fixed",
fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5},
},
after_place_node = function(pos, placer, itemstack, pointed_thing)
local sneak = placer:get_player_control().sneak
if sneak == true then
minetest.set_node(pointed_thing.above,{name="stairs:slab_" .. subname,param2=0})
else
local undernode = minetest.get_node(pointed_thing.under)
if undernode.name == "stairs:slab_" .. subname and undernode.param2 == 1 then
minetest.set_node(pointed_thing.under,{name=name})
minetest.remove_node(pointed_thing.above)
else
minetest.set_node(pointed_thing.above,{name="stairs:slab_" .. subname,param2=1})
end
end
end,
--turn into full node - doesn't let you when node above :(
on_construct = function(pos)
local pos_under = {x=pos.x,y=pos.y-1,z=pos.z}
if minetest.get_node(pos_under).name == "stairs:slab_" .. subname then
--minetest.set_node(pos_under,{name="stairs:slab_dirt",param2=0})
--minetest.remove_node(pos)
--minetest.set_node(pos_under,{name=name})
end
end,
})
if recipeitem then
minetest.register_craft({
output = 'stairs:slab_' .. subname .. ' 6',
recipe = {
{recipeitem, recipeitem, recipeitem},
},
})
-- Use 2 slabs to craft a full block again (1:1)
minetest.register_craft({
output = recipeitem,
recipe = {
{'stairs:slab_' .. subname},
{'stairs:slab_' .. subname},
},
})
-- Fuel
local baseburntime = minetest.get_craft_result({
method = "fuel",
width = 1,
items = {recipeitem}
}).time
if baseburntime > 0 then
minetest.register_craft({
type = "fuel",
recipe = 'stairs:slab_' .. subname,
burntime = math.floor(baseburntime * 0.5),
})
end
end
end
end
end)
|
--[[
Based on nick.lua, Copyright 2016 topkecleon <drew@otou.to>
This code is licensed under the GNU AGPLv3.
]]--
local nick = {}
local mattata = require('mattata')
local redis = require('mattata-redis')
function nick:init(configuration)
nick.arguments = 'nick <nickname>'
nick.commands = mattata.commands(self.info.username, configuration.commandPrefix):c('nick').table
nick.help = configuration.commandPrefix .. 'nick <nickname> - Set your nickname to the given value. If no value is given, your current nickname is sent instead.'
end
function setNickname(user, nickname)
local hash = mattata.getUserRedisHash(user, 'nickname')
if hash then
redis:hset(hash, 'nickname', nickname)
return user.first_name .. '\'s nickname has been set to \'' .. nickname .. '\'.'
end
end
function delNickname(user)
local hash = mattata.getUserRedisHash(user, 'nickname')
if redis:hexists(hash, 'nickname') == true then
redis:hdel(hash, 'nickname')
return 'Your nickname has successfully been deleted.'
else
return 'You don\'t currently have a nickname!'
end
end
function getNickname(user)
local hash = mattata.getUserRedisHash(user, 'nickname')
if hash then
local nickname = redis:hget(hash, 'nickname')
if not nickname or nickname == 'false' then
return 'You don\'t have a nickname set.'
else
return 'Your nickname is currently \'' .. nickname .. '\'.'
end
end
end
function nick:onMessage(message, configuration)
local input = mattata.input(message.text)
local output
if not input then
mattata.sendMessage(message.chat.id, getNickname(message.from), nil, true, false, message.message_id)
return
end
if message.text_lower == configuration.commandPrefix .. 'nick -del' then
mattata.sendMessage(message.chat.id, delNickname(message.from), nil, true, false, message.message_id)
return
end
mattata.sendMessage(message.chat.id, setNickname(message.from, input), nil, true, false, message.message_id)
end
return nick
|
local Original_ArmedObjectPrice = ArmedObjectPrice
function ArmedObjectPrice(object)
return Original_ArmedObjectPrice(object) / 75
end
|
--[[
# Element: SummonIndicator
Handles the visibility and updating of an indicator based on the unit's incoming summon status.
## Widget
SummonIndicator - A `Texture` used to display if the unit has an incoming summon.
## Notes
This element updates by changing the texture.
## Examples
-- Position and size
local SummonIndicator = self:CreateTexture(nil, 'OVERLAY')
SummonIndicator:SetSize(32, 32)
SummonIndicator:SetPoint('TOPRIGHT', self)
-- Register it with oUF
self.SummonIndicator = SummonIndicator
--]]
local _, ns = ...
local oUF = ns.oUF
if WOW_PROJECT_ID ~= WOW_PROJECT_MAINLINE then return end
-- sourced from Blizzard_APIDocumentation/IncomingSummonDocumentation.lua
local SUMMON_STATUS_NONE = Enum.SummonStatus.None or 0
local SUMMON_STATUS_PENDING = Enum.SummonStatus.Pending or 1
local SUMMON_STATUS_ACCEPTED = Enum.SummonStatus.Accepted or 2
local SUMMON_STATUS_DECLINED = Enum.SummonStatus.Declined or 3
local function Update(self, event, unit)
if(self.unit ~= unit) then return end
local element = self.SummonIndicator
--[[ Callback: SummonIndicator:PreUpdate()
Called before the element has been updated.
* self - the SummonIndicator element
--]]
if(element.PreUpdate) then
element:PreUpdate()
end
local status = C_IncomingSummon.IncomingSummonStatus(unit)
if(status ~= SUMMON_STATUS_NONE) then
if(status == SUMMON_STATUS_PENDING) then
element:SetAtlas('Raid-Icon-SummonPending')
elseif(status == SUMMON_STATUS_ACCEPTED) then
element:SetAtlas('Raid-Icon-SummonAccepted')
elseif(status == SUMMON_STATUS_DECLINED) then
element:SetAtlas('Raid-Icon-SummonDeclined')
end
element:Show()
else
element:Hide()
end
--[[ Callback: SummonIndicator:PostUpdate(status)
Called after the element has been updated.
* self - the SummonIndicator element
* status - the unit's incoming summon status (number)[0-3]
--]]
if(element.PostUpdate) then
return element:PostUpdate(status)
end
end
local function Path(self, ...)
--[[ Override: SummonIndicator.Override(self, event)
Used to completely override the internal update function.
* self - the parent object
* event - the event triggering the update (string)
* ... - the arguments accompanying the event
--]]
return (self.SummonIndicator.Override or Update) (self, ...)
end
local function ForceUpdate(element)
return Path(element.__owner, 'ForceUpdate', element.__owner.unit)
end
local function Enable(self)
local element = self.SummonIndicator
if(element) then
element.__owner = self
element.ForceUpdate = ForceUpdate
self:RegisterEvent('INCOMING_SUMMON_CHANGED', Path)
return true
end
end
local function Disable(self)
local element = self.SummonIndicator
if(element) then
element:Hide()
self:UnregisterEvent('INCOMING_SUMMON_CHANGED', Path)
end
end
oUF:AddElement('SummonIndicator', Path, Enable, Disable)
|
-- Dev impulse.lua for testing
function impulse00 ()
print("impulse00")
end
function newsurfcb (v_id)
print("New Surface -- In Lua callback")
end
xk_register_cb(XKEV_NEW_SURFACE, "newsurfcb")
|
-- This function initializes the game mode and is called before anyone loads into the game
-- It can be used to pre-initialize any values/tables that will be needed later
function GameMode:_InitGameMode()
if GameMode._reentrantCheck or GAMEMODE_INITIALIZATION_STATUS[1] then
return
end
GAMEMODE_INITIALIZATION_STATUS[1] = true
ListenToGameEvent('entity_killed', Dynamic_Wrap(GameMode, '_OnEntityKilled'), self)
ListenToGameEvent('player_connect_full', Dynamic_Wrap(GameMode, '_OnConnectFull'), self)
ListenToGameEvent('dota_item_picked_up', Dynamic_Wrap(GameMode, 'OnItemPickedUp'), self)
ListenToGameEvent('tree_cut', Dynamic_Wrap(GameMode, 'OnTreeCut'), self)
ListenToGameEvent('dota_player_used_ability', Dynamic_Wrap(GameMode, 'OnAbilityUsed'), self)
ListenToGameEvent('game_rules_state_change', Dynamic_Wrap(GameMode, '_OnGameRulesStateChange'), self)
ListenToGameEvent('npc_spawned', Dynamic_Wrap(GameMode, '_OnNPCSpawned'), self)
ListenToGameEvent('dota_team_kill_credit', Dynamic_Wrap(GameMode, 'OnTeamKillCredit'), self)
ListenToGameEvent("dota_item_combined", Dynamic_Wrap(GameMode, 'OnItemCombined'), self)
-- Change random seed
local timeTxt = string.gsub(string.gsub(GetSystemTime(), ':', ''), '^0+','')
math.randomseed(tonumber(timeTxt))
GameMode._reentrantCheck = true
GameMode:InitGameMode()
GameMode._reentrantCheck = false
end
|
require 'luacov'
local _ = require 'moses'
context('Array functions specs', function()
context('sample', function()
test('samples n values from array', function()
local array = _.range(1,20)
local sample = _.sample(array, 5)
assert_equal(#sample, 5)
_.each(sample, function(__,v)
assert_true(_.include(array, v))
end)
end)
test('when not given, n defaults to 1', function()
local array = _.range(1,20)
local sample = _.sample(array)
assert_true(_.include(array, sample))
end)
end)
context('sampleProb', function()
test('returns a sample of an array values', function()
local array = _.range(1,20)
local sample = _.sampleProb(array, 0.2)
_.each(sample, function(__,v)
assert_true(_.include(array, v))
end)
end)
end)
context('toArray', function()
test('converts a vararg list to an array', function()
assert_true(_.isArray(_.toArray(1,2,3,4)))
assert_true(_.isEqual(_.toArray(1,2,8,'d','a',0),{1,2,8,'d','a',0}))
end)
test('preserves input order', function()
local args = _.toArray(1,2,3,4,5)
for i = 1, 5 do assert_equal(args[i], i) end
end)
end)
context('find', function()
test('looks for a value in a given array and returns its position', function()
assert_equal(_.find({4,3,2,1},2), 3)
end)
test('uses _.isEqual to compare values', function()
assert_equal(_.find({{4},{3},{2},{1}},{3}), 2)
end)
test('returns the index of the first occurence', function()
assert_equal(_.find({4,4,3,3,2,2,1,1},2),5)
end)
test('can start the search at a specific position', function()
assert_equal(_.find({4,4,3,3,2,1,2,1,1},2,6),7)
end)
end)
context('reverse', function()
test('reverse values and objects in a given array', function()
assert_true(_.isEqual(_.reverse({1,2,3,'d'}),{'d',3,2,1}))
end)
end)
context('fill', function()
test('fills an array with a value', function()
local array = _.range(1,5)
assert_true(_.isEqual(_.fill(array,0),{0,0,0,0,0}))
end)
test('fills an array starting from an index', function()
local array = _.range(1,5)
assert_true(_.isEqual(_.fill(array,0,4),{1,2,3,0,0}))
end)
test('fills an array replacing values inside a range', function()
local array = _.range(1,5)
assert_true(_.isEqual(_.fill(array,0,3,4),{1,2,0,0,5}))
end)
test('enlarges the array when the last index is greater than array size', function()
local array = _.range(1,5)
assert_true(_.isEqual(_.fill(array,0,3,8),{1,2,0,0,0,0,0,0}))
end)
end)
context('selectWhile', function()
test('collect values from an array while they pass a thruth test', function()
assert_true(_.isEqual(_.selectWhile({2,4,6,8}, function(i,v)
return v%2==0
end),{2,4,6,8}))
end)
test('breaks as soon as one value do not pass the test', function()
assert_true(_.isEqual(_.selectWhile({2,4,6,8,9,10,12}, function(i,v)
return v%2==0
end),{2,4,6,8}))
end)
end)
context('dropWhile', function()
test('rejects values from an array while they pass a thruth test', function()
assert_true(_.isEqual(_.dropWhile({2,4,6,8}, function(i,v)
return v%2==0
end),{}))
end)
test('breaks as soon as one value do not pass the test', function()
assert_true(_.isEqual(_.dropWhile({2,4,6,8,9,10,12}, function(i,v)
return v%2==0
end),{9,10,12}))
end)
end)
context('sortedIndex', function()
test('returns the index at which a value should be inserted to preserve order', function()
local comp = function(a,b) return a<b end
assert_equal(_.sortedIndex({1,2,3},4,comp),4)
end)
test('the given array will be sorted before if boolean arg "sort" is given', function()
local comp = function(a,b) return a<b end
assert_equal(_.sortedIndex({0,10,3,-5},4,comp,true),4)
end)
test('when no comparison function is given, uses "<" operator', function()
assert_equal(_.sortedIndex({'a','d','e','z'},'b'),2)
end)
end)
context('indexOf', function()
test('returns the index of a value in an array', function()
assert_equal(_.indexOf({1,2,3},2),2)
end)
test('returns nil when value was not found', function()
assert_nil(_.indexOf({'a','b','c','d'},'e'))
end)
test('will always return the index of the first occurence', function()
assert_equal(_.indexOf({'a','d','d','z'},'d'),2)
end)
end)
context('lastIndexOf', function()
test('returns the index of the last occurence of a value in an array', function()
assert_equal(_.lastIndexOf({1,2,3},2),2)
assert_equal(_.lastIndexOf({'a','d','d','z'},'d'),3)
end)
test('returns nil when value was not found', function()
assert_nil(_.lastIndexOf({'a','b','c','d'},'e'))
end)
end)
context('findIndex', function()
test('returns the first index at which a predicate passes a truth test', function()
assert_equal(_.findIndex({1,2,3,4,5},function(__,v) return v%2==0 end),2)
end)
test('returns nil when nothing was found', function()
assert_nil(_.findIndex({1,2,3,4,5},function(_,v) return v>5 end))
end)
end)
context('findLastIndex', function()
test('returns the last index at which a predicate passes a truth test', function()
assert_equal(_.findLastIndex({1,2,3,4,5},function(_,v) return v%2==0 end),4)
end)
test('returns nil when nothing was found', function()
assert_nil(_.findLastIndex({1,2,3,4,5},function(_,v) return v>5 end))
end)
end)
context('addTop', function()
test('adds values at the top of an array', function()
assert_true(_.isEqual(_.addTop({},1,2,3),{3,2,1}))
assert_true(_.isEqual(_.addTop({},'a',true,3),{3,true,'a'}))
end)
test('preserves the existing elements', function()
assert_true(_.isEqual(_.addTop({1,2},1,2,3),{3,2,1,1,2}))
assert_true(_.isEqual(_.addTop({'i','j'},'a',true,3),{3,true,'a','i','j'}))
end)
end)
context('push', function()
test('appends values at the end of an array', function()
assert_true(_.isEqual(_.push({},1,2,3),{1,2,3}))
assert_true(_.isEqual(_.push({},'a',true,3),{'a',true,3}))
end)
test('preserves the existing elements', function()
assert_true(_.isEqual(_.push({1,2},1,2,3),{1,2,1,2,3}))
assert_true(_.isEqual(_.push({'i','j'},'a',true,3),{'i','j','a',true,3}))
end)
end)
context('pop', function()
test('returns the value at the top of a given array', function()
assert_equal(_.pop {1,7,9} ,1)
end)
test('also removes this value from the given array', function()
local array = {1,7,9}
assert_equal(_.pop(array),1)
assert_true(_.isEqual(array,{7,9}))
end)
end)
context('unshift', function()
test('returns the value at the end of a given array', function()
assert_equal(_.unshift {1,7,9} ,9)
end)
test('also removes this value from the given array', function()
local array = {1,7,9}
assert_equal(_.unshift(array),9)
assert_true(_.isEqual(array,{1,7}))
end)
end)
context('pull', function()
test('removes all listed values in a given array', function()
assert_true(_.same(_.pull({1,4,3,1,2,3},1),{4,3,2,3}))
assert_true(_.same(_.pull({1,4,3,1,2,3},1,3),{4,2}))
end)
end)
context('removeRange', function()
test('removes all values within "start" and "finish" indexes', function()
assert_true(_.isEqual(_.removeRange({1,2,3,4,5,6},2,4),{1,5,6}))
end)
test('arg "finish" defaults to the end of the array when not given ', function()
assert_true(_.isEqual(_.removeRange({1,2,3,4,5,6},3),{1,2}))
end)
test('arg "start" defaults to the initial index when not given ', function()
assert_true(_.isEqual(_.removeRange({1,2,3,4,5,6}),{}))
end)
test('args "start" and "finish" are be clamped to the array bound ', function()
assert_true(_.isEqual(_.removeRange({1,2,3,4,5,6},0,100),{}))
end)
test('leaves the array untouched when "finish" < "start"', function()
assert_true(_.isEqual(_.removeRange({1,2,3,4,5,6},4,2),{1,2,3,4,5,6}))
end)
end)
context('chunk', function()
test('chunks in blocks consecutive values returning the same value from a given function', function()
local t = {1,2,2,3,3,4,4}
local v = _.chunk(t, function(k,v) return v%2==0 end)
assert_equal(#v, 4)
_.each(v[1], function(k)
assert_equal(v[1][k],1)
end)
assert_equal(#v[1],1)
_.each(v[2], function(k)
assert_equal(v[2][k],2)
end)
assert_equal(#v[2],2)
_.each(v[3], function(k)
assert_equal(v[3][k],3)
end)
assert_equal(#v[3],2)
_.each(v[4], function(k)
assert_equal(v[4][k],4)
end)
assert_equal(#v[4],2)
end)
test('Returns the first argument in case it is not an array', function()
local t = {a = 1, b = 2}
assert_equal(_.chunk(t, function(k,v) return v%2==0 end), t)
end)
end)
context('slice',function()
test('slices a portion of an array',function()
assert_true(_.isEqual(_.slice({'a','b','c','d','e'},2,3),{'b','c'}))
end)
test('arg "right" bound defaults to the array length when not given',function()
assert_true(_.isEqual(_.slice({'a','b','c','d','e'},3),{'c','d','e'}))
end)
test('arg "left" bound defaults to the initial index when not given',function()
assert_true(_.isEqual(_.slice({'a','b','c','d','e'}),{'a','b','c','d','e'}))
end)
end)
context('first',function()
test('returns the n-first elements', function()
assert_true(_.isEqual(_.first({5,8,12,20},2),{5,8}))
end)
test('arg "n" defaults 1 when not given', function()
assert_true(_.isEqual(_.first({5,8,12,20}),{5}))
end)
end)
context('initial',function()
test('exludes the last N elements', function()
assert_true(_.isEqual(_.initial({5,8,12,20},3),{5}))
assert_true(_.isEqual(_.initial({5,8,12,20},4),{}))
end)
test('returns all values but the last one if arg "n" was not given', function()
assert_true(_.isEqual(_.initial({5,8,12,20}),{5,8,12}))
end)
test('passing "n" greather than the array size returns an empty', function()
assert_true(_.isEqual(_.initial({5,8,12,20},5),{}))
end)
test('returns the whole array when "n" equals 0', function()
assert_true(_.isEqual(_.initial({5,8,12,20},0),{5,8,12,20}))
end)
test('returns "nil" when arg "n" < 0', function()
assert_nil(_.initial({5,8,12,20},-1))
end)
end)
context('last',function()
test('returns the last N elements', function()
assert_true(_.isEqual(_.last({5,8,12,20},3),{8,12,20}))
assert_true(_.isEqual(_.last({5,8,12,20},1),{20}))
assert_true(_.isEqual(_.last({5,8,12,20},2),{12,20}))
assert_true(_.isEqual(_.last({5,8,12,20},4),{5,8,12,20}))
end)
test('returns all values but the first one if arg "n" was not given', function()
assert_true(_.isEqual(_.last({5,8,12,20}),{8,12,20}))
end)
test('if arg "n" is lower than the array size, returns all values', function()
assert_true(_.isEqual(_.last({5,8,12,20},5),{5,8,12,20}))
end)
test('returns "nil" when arg "n" <= 0', function()
assert_nil(_.last({5,8,12,20},0))
assert_nil(_.last({5,8,12,20},-1))
end)
end)
context('rest',function()
test('excludes all values before a given index', function()
assert_true(_.isEqual(_.rest({5,8,12,20},2),{8,12,20}))
assert_true(_.isEqual(_.rest({5,8,12,20},1),{5,8,12,20}))
assert_true(_.isEqual(_.rest({5,8,12,20},4),{20}))
end)
test('returns an empty array when arg "index" > #array', function()
assert_true(_.isEqual(_.rest({5,8,12,20},5),{}))
end)
test('returns all values if arg "index" <= 0', function()
assert_true(_.isEqual(_.rest({5,8,12,20},0),{5,8,12,20}))
assert_true(_.isEqual(_.rest({5,8,12,20},-1),{5,8,12,20}))
end)
end)
context('nth', function()
test('returns the value at "index"', function()
assert_equal(3, _.nth({1,2,3,4,5,6}, 3))
end)
end)
context('compact',function()
test('trims out all falsy values from an array', function()
assert_true(_.isEqual(_.compact({a,'a',false,'b',true}),{'a','b',true}))
end)
end)
context('flatten',function()
test('flattens nested arrays', function()
assert_true(_.isEqual(_.flatten({1,{2,3},{4,5,{6,7}}}),{1,2,3,4,5,6,7}))
end)
test('when given arg "shallow", flatten only first level', function()
assert_true(_.isEqual(_.flatten({1,{2,3},{4,5,{6,7}}},true),{1,2,3,4,5,{6,7}}))
end)
end)
context('difference',function()
test('returns values in the first array not present in the second array', function()
local array = {1,2,'a',4,5}
assert_true(_.isEqual(_.difference(array,{1,'a'}),{2,4,5}))
assert_true(_.isEqual(_.difference(array,{5}),{1,2,'a',4}))
end)
test('ignores values in the second array not found in the first array', function()
local array = {1,2,'a',4,5}
assert_true(_.isEqual(_.difference(array,{1,'a','b','c'}),{2,4,5}))
end)
test('leaves array untouched when given no extra-args', function()
assert_true(_.isEqual(_.difference({1,2,'a',4,5}),{1,2,'a',4,5}))
end)
end)
context('union',function()
test('returns the duplicate-free union of all passed-in arrays', function()
local a = {"a"}; local b = {1,2,3}; local c = {2,10}
assert_true(_.isEqual(_.union(a,b,c),{'a',1,2,3,10}))
end)
test('accepts nested arrays as well', function()
local a = {"a",{"b","c"}}; local b = {1,{2},3}; local c = {2,10}
assert_true(_.isEqual(_.union(a,b,c),{'a','b','c',1,2,3,10}))
end)
end)
context('intersection',function()
test('returns the intersection of all passed-in arrays', function()
local a = {1,3}; local b = {4,2,3}; local c = {2,3,10}
assert_true(_.isEqual(_.intersection(a,b,c),{3}))
end)
test('fails with nested arrays', function()
local a = {1,{3}}; local b = {4,2,3}; local c = {2,3,10}
assert_true(_.isEqual(_.intersection(a,b,c),{}))
end)
end)
context('symmetricDifference',function()
test('returns the symmetric difference from two arrays', function()
local a = {1,3}; local b = {4,2,3}; local c = {2,3,10}
assert_true(_.same(_.symmetricDifference(a, b), {1,4,2}))
assert_true(_.same(_.symmetricDifference(a, c), {1,2,10}))
assert_true(_.same(_.symmetricDifference(b, c), {4,10}))
end)
end)
context('unique',function()
test('returns a duplicate-free array',function()
assert_true(_.isEqual(_.unique({1,1,2,2,3,3,4,4,4,5}),{1,2,3,4,5}))
end)
end)
context('isunique',function()
test('Checks if a given array is duplicate-free',function()
assert_true(_.isunique({1,2,3,4,5}))
assert_false(_.isunique({1,2,3,4,4}))
end)
end)
context('zip',function()
test('zips together values from different arrays sharing the same index', function()
local names = {'Bob','Alice','James'}; local ages = {22, 23}
assert_true(_.isEqual(_.zip(names,ages),{{'Bob',22},{'Alice',23},{'James'}}))
end)
end)
context('append',function()
test('appends two arrays together', function()
assert_true(_.isEqual(_.append({1,2,3},{'a','b'}),{1,2,3,'a','b'}))
end)
end)
context('interleave',function()
test('interleaves values from passed-in arrays', function()
assert_true(_.isEqual(_.interleave({1,2,3},{'a','b','c'}),{1,'a',2,'b',3,'c'}))
assert_true(_.isEqual(_.interleave({1},{'a','b','c'}),{1,'a','b','c'}))
end)
end)
context('interpose',function()
test('interposes a value in-between values from a passed-in array', function()
assert_true(_.isEqual(_.interpose('a',{1,2,3}),{1,'a',2,'a',3}))
assert_true(_.isEqual(_.interpose(false,{5,5,5,5}),{5,false,5,false,5,false,5}))
end)
end)
context('range',function()
test('generate an arithmetic progression', function()
assert_true(_.isEqual(_.range(1,5,1),{1,2,3,4,5}))
assert_true(_.isEqual(_.range(-2,5,1),{-2,-1,0,1,2,3,4,5}))
assert_true(_.isEqual(_.range(1,5,2),{1,3,5}))
end)
test('arg "step" default to 1 when no given', function()
assert_true(_.isEqual(_.range(1,5),{1,2,3,4,5}))
end)
test('when a limit cannot be reached via "step", returns an empty array', function()
assert_true(_.isEqual(_.range(1,5,0),{}))
assert_true(_.isEqual(_.range(1,5,-1),{}))
end)
test('handles real values as well', function()
assert_true(_.isEqual(_.range(3.2,5,0.5),{3.2,3.7,4.2,4.7}))
end)
test('when only one arg is passed, counts from 0', function()
assert_true(_.isEqual(_.range(3),{0,1,2,3}))
end)
end)
context('rep',function()
test('generates a list of n repetitions of a value', function()
assert_true(_.isEqual(_.rep('a',4),{'a','a','a','a'}))
assert_true(_.isEqual(_.rep(false,3),{false, false, false}))
end)
end)
context('partition',function()
test('iterates on partitions of a given array', function()
local array = _.range(1,10)
local split5 = {_.range(1,5), _.range(6,10)}
local split3 = {_.range(1,3), _.range(4,6), _.range(7,9), {10}}
local i = 0
for p in _.partition(array,5) do
i = i + 1
assert_true(_.isEqual(p, split5[i]))
end
i = 0
for p in _.partition(array,3) do
i = i + 1
assert_true(_.isEqual(p, split3[i]))
end
end)
test('if a 3rd argument pad is supplied, will adjust the last partition', function()
local array = _.range(1,10)
local split4 = {{1,2,3,4},{5,6,7,8},{9,10,0,0}}
local i = 0
for p in _.partition(array,4,0) do
i = i + 1
assert_true(_.isEqual(p, split4[i]))
end
end)
end)
context('sliding',function()
test('returns overlapping subsequences', function()
local array = _.range(1,10)
local sliding2 = {{1,2},{2,3},{3,4},{4,5},{5,6},{6,7},{7,8},{8,9},{9,10}}
local sliding3 = {{1,2,3},{3,4,5},{5,6,7},{7,8,9},{9,10}}
local sliding5 = {{1,2,3,4,5},{5,6,7,8,9},{9,10}}
local i = 0
for p in _.sliding(array,2) do
i = i + 1
assert_true(_.isEqual(p, sliding2[i]))
end
i = 0
for p in _.sliding(array,3) do
i = i + 1
assert_true(_.isEqual(p, sliding3[i]))
end
i = 0
for p in _.sliding(array,5) do
i = i + 1
assert_true(_.isEqual(p, sliding5[i]))
end
end)
test('if a 3rd argument pad is supplied, will adjust the last subsequence', function()
local array = _.range(1,10)
local sliding3 = {{1,2,3},{3,4,5},{5,6,7},{7,8,9},{9,10,0}}
local sliding5 = {{1,2,3,4,5},{5,6,7,8,9},{9,10,0,0,0}}
local i = 0
for p in _.sliding(array,3,0) do
i = i + 1
assert_true(_.isEqual(p, sliding3[i]))
end
i = 0
for p in _.sliding(array,5,0) do
i = i + 1
assert_true(_.isEqual(p, sliding5[i]))
end
end)
end)
context('permutation',function()
test('iterates on permutations of a given array', function()
local array = {'a','b', 'c'}
local perm = {'abc','acb', 'bac', 'bca', 'cab', 'cba'}
for p in _.permutation(array) do
local strp = _.concat(p)
_.pull(perm, strp)
end
assert_true(#perm == 0)
end)
end)
context('invert',function()
test('switches key-values pairs', function()
assert_true(_.isEqual(_.invert({1,2,3}),{1,2,3}))
assert_true(_.isEqual(_.invert({'a','b','c'}),{a = 1,b = 2,c = 3}))
end)
end)
context('concat',function()
test('concatenates an array contents', function()
assert_equal(_.concat({1,2,3,4}),'1234')
assert_equal(_.concat({'a',1,0,1,'b'}),'a101b')
end)
test('handles boolean values', function()
assert_equal(_.concat({1,true,3,false}),'1true3false')
end)
test('when arg "sep" is given, uses "sep" as a separator', function()
assert_equal(_.concat({1,3,false,'A'},' '),'1 3 false A')
assert_equal(_.concat({1,3,false,'A'},', '),'1, 3, false, A')
end)
test('when args "i" and/or "j" are given, concats values within "i" and "j" indexes', function()
assert_equal(_.concat({1,3,false,'A'},' ',2,3),'3 false')
assert_equal(_.concat({1,3,false,'A'},', ',2,3),'3, false')
assert_equal(_.concat({1,3,false,'A','K'},' ',2),'3 false A K')
end)
end)
end)
|
{data={name="", author="Magnus siiftun1857 Frankline"}, blocks={
{1881000, {-4.444, 0}},
{1881001, {5.556, 0}},
{1881001, {5.556, 10}, 1.571},
{1881001, {5.556, -10}, -1.571},
{1881001, {-4.444, 10}, -1.571},
{1881001, {-4.444, -10}, 1.571},
{1881001, {5.556, -20}, 1.571},
{1881001, {5.556, 20}, -1.571},
{1881004, {-14.444, 0}, bindingId=0}}}
|
---[[
]]
function foo()
return 1,2,3
end
print(foo())
function add(...)
print(select('#',...))
local s = 0
for i,v in ipairs{...} do
s = s+ v
end
return s
end
print(add(3,4,534,56,7))
|
IncludeFile("Lib\\TOIR_SDK.lua")
Akali = class()
function OnLoad()
if GetChampName(GetMyChamp()) == "Akali" then
Akali:Assasin()
end
end
function Akali:Assasin()
self.Predc = VPrediction(true)
self:EveMenus()
self.Q = Spell(_Q, 600)
self.W = Spell(_W, 270)
self.E = Spell(_E, 300)
self.R = Spell(_R, 700)
self.QTime = 0
self.SpawW = 0
self.QMarked = false
self.QIsCard = { }
self.QSpawn = 0
self.Q:SetTargetted()
self.W:SetSkillShot(0.54, math.huge, 200, false)
self.E:SetActive()
self.R:SetTargetted()
Callback.Add("Tick", function() self:OnTick() end)
Callback.Add("Draw", function(...) self:OnDraw(...) end)
Callback.Add("DrawMenu", function(...) self:OnDrawMenu(...) end)
Callback.Add("UpdateBuff", function(...) self:OnUpdateBuff(...) end)
Callback.Add("RemoveBuff", function(...) self:OnRemoveBuff(...) end)
Callback.Add("CreateObject", function(...) self:OnCreateObject(...) end)
Callback.Add("DeleteObject", function(...) self:OnDeleteObject(...) end)
--Callback.Add("ProcessSpell", function(...) self:OnProcessSpell(...) end)
end
--SDK {{Toir+}}
function Akali:MenuBool(stringKey, bool)
return ReadIniBoolean(self.menu, stringKey, bool)
end
function Akali:MenuSliderInt(stringKey, valueDefault)
return ReadIniInteger(self.menu, stringKey, valueDefault)
end
function Akali:MenuKeyBinding(stringKey, valueDefault)
return ReadIniInteger(self.menu, stringKey, valueDefault)
end
function Akali:MenuComboBox(stringKey, valueDefault)
return ReadIniInteger(self.menu, stringKey, valueDefault)
end
function Akali:EveMenus()
self.menu = "Akali"
--Combo [[ Akali ]]
self.CQ = self:MenuBool("Combo Q", true)
self.CW = self:MenuBool("Combo W", true)
self.CE = self:MenuBool("Combo E", true)
--AutoQ
--self.AutoQ = self:MenuBool("Auto Q", true)
self.UseRmy = self:MenuSliderInt("Auto W %", 45)
--Lane
self.LQ = self:MenuBool("Lane Q", true)
self.LE = self:MenuBool("Lane E", true)
self.LMana = self:MenuSliderInt("Energy Lane %", 45)
--Dor
self.Modeself = self:MenuComboBox("Mode Self [R]", 1)
--Add R
self.CR = self:MenuBool("Combo R", true)
self.UseRLogic = self:MenuBool("Use Logic R", true)
self.ModeR = self:MenuComboBox("Mode [R]", 1)
self.UseRange = self:MenuSliderInt("Range Enemys", 2)
--KillSteal [[ Akali ]]
self.KQ = self:MenuBool("KillSteal > Q", true)
self.KE = self:MenuBool("KillSteal > E", true)
self.KR = self:MenuBool("KillSteal > R", true)
--Draws [[ Akali ]]
self.DQWER = self:MenuBool("Draw On/Off", true)
self.DQ = self:MenuBool("Draw Q", true)
self.DE = self:MenuBool("Draw E", true)
self.DR = self:MenuBool("Draw R", true)
--Misc [[ Akali ]]
--self.LogicR = self:MenuBool("Use Logic R?", true)]]
--KeyStone [[ Akali ]]
self.Combo = self:MenuKeyBinding("Combo", 32)
self.LaneClear = self:MenuKeyBinding("Lane Clear", 86)
end
function Akali:OnDrawMenu()
if Menu_Begin(self.menu) then
if Menu_Begin("Combo") then
self.CQ = Menu_Bool("Combo Q", self.CQ, self.menu)
--self.AutoQ = Menu_Bool("Combo Q", self.AutoQ, self.menu)
self.CW = Menu_Bool("Combo W", self.CW, self.menu)
self.CE = Menu_Bool("Combo E", self.CE, self.menu)
Menu_End()
end
if Menu_Begin("Lane") then
self.LQ = Menu_Bool("Lane Q", self.LQ, self.menu)
self.LMana = Menu_SliderInt("Energy %", self.LMana, 0, 100, self.menu)
Menu_End()
end
if Menu_Begin("Draws") then
self.DQWER = Menu_Bool("Draw On/Off", self.DQWER, self.menu)
self.DQ = Menu_Bool("Draw Q", self.DQ, self.menu)
self.DE = Menu_Bool("Draw E", self.DE, self.menu)
self.DR = Menu_Bool("Draw R", self.DR, self.menu)
Menu_End()
end
if Menu_Begin("Configuration [R]") then
self.CR = Menu_Bool("Combo R", self.CR, self.menu)
self.ModeR = Menu_ComboBox("Mode [R]", self.ModeR, "Always\0Marked\0\0", self.menu)
self.Modeself = Menu_ComboBox("Mode Self [R]", self.Modeself, "Always use Tower\0Safe\0\0", self.menu)
Menu_End()
end
if Menu_Begin("Logic [W]") then
self.UseRLogic = Menu_Bool("Logic W", self.UseRLogic, self.menu)
self.UseRmy = Menu_SliderInt("My HP Minimum %", self.UseRmy, 0, 100, self.menu)
self.UseRange = Menu_SliderInt("Range Enemys %", self.UseRange, 0, 5, self.menu)
Menu_End()
end
if Menu_Begin("KillSteal") then
self.KQ = Menu_Bool("KillSteal > Q", self.KQ, self.menu)
self.KE = Menu_Bool("KillSteal > E", self.KE, self.menu)
self.KR = Menu_Bool("KillSteal > R", self.KR, self.menu)
Menu_End()
end
if Menu_Begin("KeyStone") then
self.Combo = Menu_KeyBinding("Combo", self.Combo, self.menu)
self.LaneClear = Menu_KeyBinding("Lane Clear", self.LaneClear, self.menu)
Menu_End()
end
Menu_End()
end
end
function Akali:OnUpdateBuff(unit, buff)
if myHero then
--__PrintTextGame(buff.Name)
end
if unit.IsEnemy and buff.Name == "AkaliMota" then
self.QMarked = true
self.QTime = GetTimeGame()
end
end
function Akali:OnRemoveBuff(unit, buff)
if unit.IsEnemy and buff.Name == "AkaliMota" then
self.QMarked = false
self.QTime = 0
end
end
function Akali:IsAfterAttack()
if CanMove() and not CanAttack() then
return true
else
return false
end
end
local function GetDistanceSqr(p1, p2)
p2 = GetOrigin(p2) or GetOrigin(myHero)
return (p1.x - p2.x) ^ 2 + ((p1.z or p1.y) - (p2.z or p2.y)) ^ 2
end
function Akali:IsSafe(pos) --- SDK Toir+
GetAllUnitAroundAnObject(myHero.Addr, 2000)
local objects = pUnit
for k,v in pairs(objects) do
if IsTurret(v) and not IsDead(v) and IsEnemy(v) and GetTargetableToTeam(v) == 4 then
local turretPos = Vector(GetPosX(v), GetPosY(v), GetPosZ(v))
if GetDistanceSqr(turretPos,pos) < 915*915 then
return true
end
end
end
return false
end
function Akali:OnDraw()
if self.DQWER then
if self.DQ and self.Q:IsReady() then
DrawCircleGame(myHero.x, myHero.y, myHero.z,self.Q.range, Lua_ARGB(255,255,0,0))
end
if self.DE and self.E:IsReady() then
DrawCircleGame(myHero.x, myHero.y, myHero.z, self.E.range, Lua_ARGB(255,0,0,255))
end
if self.DR and self.R:IsReady() then
DrawCircleGame(myHero.x, myHero.y, myHero.z, self.R.range, Lua_ARGB(255,0,0,255))
end
end
end
function Akali:OnCreateObject(Obj)
if myHero then
--__PrintTextGame(obj.Name)
end
if string.find(Obj.Name, "Akali_Base_markOftheAssasin_marker_tar") and Obj.IsValid and not IsDead(Obj.Addr) then
self.QIsCard[Obj.NetworkId] = Obj
self.QSpawn = GetTickCount()
end
end
function Akali:OnDeleteObject(Obj)
if myHero then
--__PrintTextGame(obj.Name)
end
for _, AkaliQ in pairs(self.QIsCard) do
if AkaliQ.Addr == Obj.Addr then
table.remove(self.QIsCard, _)
self.QSpawn = 0
end
end
end
function Akali:EnemyMinionsTbl() --SDK Toir+
GetAllUnitAroundAnObject(myHero.Addr, 2000)
local result = {}
for i, obj in pairs(pUnit) do
if obj ~= 0 then
local minions = GetUnit(obj)
if IsEnemy(minions.Addr) and not IsDead(minions.Addr) and not IsInFog(minions.Addr) and GetType(minions.Addr) == 1 then
table.insert(result, minions)
end
end
end
return result
end
function Akali:FishEnemy()
local UseE = GetTargetSelector(self.E.range)
Enemy = GetAIHero(UseE)
if CanCast(_E) and self.KE and UseE ~= 0 and GetDistance(Enemy) < self.E.range and GetDamage("E", Enemy) > Enemy.HP then
CastSpellTarget(myHero.Addr, _E)
end
local UseR = GetTargetSelector(self.R.range)
Enemy = GetAIHero(UseR)
if CanCast(_R) and self.KR and UseR ~= 0 and GetDistance(Enemy) < self.R.range and GetDamage("R", Enemy) > Enemy.HP then
CastSpellTarget(Enemy.Addr, _R)
end
local UseQ = GetTargetSelector(self.Q.range)
Enemy = GetAIHero(UseQ)
if CanCast(_Q) and self.KQ and UseQ ~= 0 and GetDistance(Enemy) < self.Q.range and GetDamage("Q", Enemy) > Enemy.HP then
CastSpellTarget(Enemy.Addr, _Q)
end
end
function Akali:CastQ()
local UseQ = GetTargetSelector(self.Q.range)
Enemy = GetAIHero(UseQ)
if CanCast(_Q) and self.CQ and UseQ ~= 0 and IsValidTarget(Enemy, self.Q.range) then
CastSpellTarget(Enemy.Addr, _Q)
end
end
function Akali:CastW()
local UseW = GetTargetSelector(self.W.range)
Enemy = GetAIHero(UseW)
if CanCast(_W) and self.CW and UseW ~= 0 and IsValidTarget(Enemy, self.W.range) and self:IsAfterAttack() then
local CRPosition, HitChance, Position = self.Predc:GetCircularCastPosition(Enemy, self.W.delay, self.W.width, self.W.range, self.W.speed, myHero, false)
if HitChance >= 2 then
CastSpellToPos(CRPosition.x, CRPosition.z, _W)
end
end
end
function Akali:CastR()
local UseR = GetTargetSelector(self.R.range)
Enemy = GetAIHero(UseR)
if self.ModeR == 1 then
if CanCast(_R) and self.CR and self.QMarked and UseR ~= 0 and IsValidTarget(Enemy, self.R.range) then
CastSpellTarget(Enemy.Addr, _R)
end
end
if self.ModeR == 0 then
if CanCast(_R) and self.CR and UseR ~= 0 and IsValidTarget(Enemy, self.R.range) then
CastSpellTarget(Enemy.Addr, _R)
end
end
end
function Akali:CastLogicR()
local UseR = GetTargetSelector(self.R.range)
Enemy = GetAIHero(UseR)
if self.Modeself == 1 then
if CanCast(_R) and self.CR and UseR ~= 0 and IsValidTarget(Enemy, self.R.range) and not self:IsSafe(Enemy) then
CastSpellTarget(Enemy.Addr, _R)
end
end
if self.Modeself == 0 then
if CanCast(_R) and self.CR and UseR ~= 0 and IsValidTarget(Enemy, self.R.range) then
CastSpellTarget(Enemy.Addr, _R)
end
end
end
function Akali:CastE()
local UseE = GetTargetSelector(self.E.range)
Enemy = GetAIHero(UseE)
if CanCast(_E) and self.CE and UseE ~= 0 and GetDistance(Enemy) < self.E.range then
CastSpellTarget(myHero.Addr, _E)
end
end
function Akali:ComboAkali()
if self.CQ then
self:CastQ()
end
if self.CR then
self:CastR()
end
if self.CW then
self:CastW()
end
if self.CE then
self:CastE()
end
end
function Akali:EnemyRange()
local UseW = GetTargetSelector(self.W.range)
Enemy = GetAIHero(UseW)
if CanCast(W) and IsValidTarget(Enemy, 1000) and CountEnemyChampAroundObject(Enemy, 1000) < self.UseRange and GetPercentHP(myHero.Addr) < self.UseRmy then
local CRPosition, HitChance, Position = self.Predc:GetCircularCastPosition(Enemy, self.W.delay, self.W.width, self.W.range, self.W.speed, myHero, false)
if HitChance >= 2 then
CastSpellToPos(CRPosition.x, CRPosition.y, _W)
end
end
end
function Akali:Lang()
for i ,minion in pairs(self:EnemyMinionsTbl()) do
if minion ~= 0 then
if GetPercentMP(myHero.Addr) >= self.LMana and self.LQ and IsValidTarget(minion.Addr, self.Q.range) then
CastSpellTarget(minion.Addr, Q)
end
end
end
end
function Akali:OnTick()
if IsDead(myHero.Addr) or IsTyping() or IsDodging() then return end
self:FishEnemy()
self:EnemyRange()
--self:LogicRIsEnemy()
if GetKeyPress(self.LaneClear) > 0 then
self:Lang()
end
if GetKeyPress(self.Combo) > 0 then
self:ComboAkali()
end
end
|
local os = require "os"
local ffi = require "ffi"
local socket = require "socket"
local msgpack = require "MessagePack"
local cjson = require "cjson"
local uint32_a2 = ffi.typeof("uint32_t[2]")
local is_little_endian = ffi.abi("le")
local eventtime_metatable = {}
local function NewEventTime(timestamp_seconds)
local seconds = math.modf(timestamp_seconds)
local obj = { seconds = seconds, nano = math.modf((timestamp_seconds - seconds) * 1E9) }
return setmetatable(obj, eventtime_metatable )
end
local function connect(host, port)
local fluent = socket.tcp()
fluent:settimeout(timeout)
local ok, err = fluent:connect(host or "localhost", port or 24224)
return fluent, err
end
local function log(premature, plugin_name, conf, timestamp, payload)
if premature then
return
end
for key, value in pairs(payload) do
if type(value) == "table" then
payload[key] = cjson.encode(value)
end
end
-- ngx.log(ngx.ERR, "[" .. plugin_name .. "] log: ", cjson.encode(payload))
local fluent, err = connect(conf.hostname, conf.port)
if err then
ngx.log(ngx.ERR, "[" .. plugin_name .. "] error connecting to collector: ", err)
return
end
local _, err = fluent:send(msgpack.pack({"", NewEventTime(timestamp), payload}))
if err then
ngx.log(ngx.ERR, "[" .. plugin_name .. "] error sending log: ", err)
return
end
fluent:close()
end
local _M = {}
function _M.enqueue(plugin_name, conf, timestamp, payload)
local ok, err = ngx.timer.at(0, log, plugin_name, conf, timestamp, payload)
if not ok then
ngx.log(ngx.ERR, "[" .. plugin_name .. "] failed to create timer: ", err)
end
end
local original_table_packer = msgpack.packers["table"]
msgpack.packers["table"] = function (buffer, value)
if getmetatable(value) == eventtime_metatable then
local pieces = is_little_endian and {value.nano, value.seconds} or {value.nano, value.seconds}
local encoded_value = ffi.string(uint32_a2(pieces), 8)
if is_little_endian then
encoded_value = encoded_value:reverse()
end
msgpack.packers["fixext8"](buffer, 0, encoded_value)
else
original_table_packer(buffer, value)
end
end
return _M
|
#!/usr/bin/env lua
local test_module = require("test_module")
local test_child = require("test_grandparent.test_parent.test_child")
local datafile = require("datafile")
print("Path:", datafile.path("resources/greeting.txt"))
local fd = assert(datafile.open("resources/greeting.txt"))
local reply = fd:read("*a")
fd:close()
print(reply)
test_module.yo()
test_child.yo()
print("The next one will fail:")
local fderr, err = datafile.open("resources/nonexistant.txt")
assert(not fderr)
if err then
print(err)
end
|
local CreateConVar = CreateConVar
local RunConsoleCommand = RunConsoleCommand
local pairs = pairs
local LocalPlayer = LocalPlayer
local cvars = cvars
local tonumber = tonumber
--
CreateConVar('bgn_cl_draw_npc_path', bgNPC.cvar.bgn_cl_draw_npc_path,
{ FCVAR_ARCHIVE }, 'Draw the path of movement of the NPC.')
CreateConVar('bgn_cl_field_view_optimization', bgNPC.cvar.bgn_cl_field_view_optimization,
{ FCVAR_ARCHIVE }, 'Enable field of view optimization.')
CreateConVar('bgn_cl_field_view_optimization_range', bgNPC.cvar.bgn_cl_field_view_optimization_range,
{ FCVAR_ARCHIVE }, 'The minimum distance in which the check is not performed.')
CreateConVar('bgn_cl_ambient_sound', bgNPC.cvar.bgn_cl_ambient_sound,
{ FCVAR_ARCHIVE }, 'Plays a crowd sound based on the number of actors around you. (WARNING! Not recommended for use on weak PC!)')
CreateConVar('bgn_tool_draw_distance', bgNPC.cvar.bgn_tool_draw_distance,
{ FCVAR_ARCHIVE }, 'Distance to draw points in edit mode.')
CreateConVar('bgn_tool_point_editor_autoparent', bgNPC.cvar.bgn_tool_point_editor_autoparent,
{ FCVAR_ARCHIVE }, 'Enable automatic creation of nodes links.')
CreateConVar('bgn_tool_point_editor_autoalignment', bgNPC.cvar.bgn_tool_point_editor_autoalignment,
{ FCVAR_ARCHIVE }, 'Enable automatic height alignment.')
CreateConVar('bgn_tool_point_editor_show_parents', bgNPC.cvar.bgn_tool_point_editor_show_parents,
{ FCVAR_ARCHIVE }, 'Show global connections.')
CreateConVar('bgn_tool_seat_offset_pos_x', bgNPC.cvar.bgn_tool_seat_offset_pos_x,
{ FCVAR_ARCHIVE }, '')
CreateConVar('bgn_tool_seat_offset_pos_y', bgNPC.cvar.bgn_tool_seat_offset_pos_y,
{ FCVAR_ARCHIVE }, '')
CreateConVar('bgn_tool_seat_offset_pos_z', bgNPC.cvar.bgn_tool_seat_offset_pos_z,
{ FCVAR_ARCHIVE }, '')
CreateConVar('bgn_tool_seat_offset_angle_x', bgNPC.cvar.bgn_tool_seat_offset_angle_x,
{ FCVAR_ARCHIVE }, '')
CreateConVar('bgn_tool_seat_offset_angle_y', bgNPC.cvar.bgn_tool_seat_offset_angle_y,
{ FCVAR_ARCHIVE }, '')
CreateConVar('bgn_tool_seat_offset_angle_z', bgNPC.cvar.bgn_tool_seat_offset_angle_z,
{ FCVAR_ARCHIVE }, '')
concommand.Add('bgn_reset_cvars_to_factory_settings', function(ply, cmd, args)
if not ply:IsAdmin() and not ply:IsSuperAdmin() then return end
RunConsoleCommand('bgn_enable', bgNPC.cvar.bgn_enable)
RunConsoleCommand('bgn_debug', bgNPC.cvar.bgn_debug)
RunConsoleCommand('bgn_max_npc', bgNPC.cvar.bgn_max_npc)
RunConsoleCommand('bgn_spawn_radius', bgNPC.cvar.bgn_spawn_radius)
RunConsoleCommand('bgn_disable_logic_radius', bgNPC.cvar.bgn_disable_logic_radius)
RunConsoleCommand('bgn_spawn_radius_visibility', bgNPC.cvar.bgn_spawn_radius_visibility)
RunConsoleCommand('bgn_spawn_radius_raytracing', bgNPC.cvar.bgn_spawn_radius_raytracing)
RunConsoleCommand('bgn_spawn_block_radius', bgNPC.cvar.bgn_spawn_block_radius)
RunConsoleCommand('bgn_spawn_period', bgNPC.cvar.bgn_spawn_period)
-- RunConsoleCommand('bgn_ptp_distance_limit', bgNPC.cvar.bgn_ptp_distance_limit)
RunConsoleCommand('bgn_point_z_limit', bgNPC.cvar.bgn_point_z_limit)
RunConsoleCommand('bgn_enable_wanted_mode', bgNPC.cvar.bgn_enable_wanted_mode)
RunConsoleCommand('bgn_wanted_time', bgNPC.cvar.bgn_wanted_time)
RunConsoleCommand('bgn_wanted_level', bgNPC.cvar.bgn_wanted_level)
RunConsoleCommand('bgn_wanted_hud_text', bgNPC.cvar.bgn_wanted_hud_text)
RunConsoleCommand('bgn_wanted_hud_stars', bgNPC.cvar.bgn_wanted_hud_stars)
RunConsoleCommand('bgn_arrest_mode', bgNPC.cvar.bgn_arrest_mode)
RunConsoleCommand('bgn_arrest_time', bgNPC.cvar.bgn_arrest_time)
RunConsoleCommand('bgn_arrest_time_limit', bgNPC.cvar.bgn_arrest_time_limit)
RunConsoleCommand('bgn_ignore_another_npc', bgNPC.cvar.bgn_ignore_another_npc)
RunConsoleCommand('bgn_shot_sound_mode', bgNPC.cvar.bgn_shot_sound_mode)
RunConsoleCommand('bgn_cl_field_view_optimization', bgNPC.cvar.bgn_cl_field_view_optimization)
RunConsoleCommand('bgn_cl_field_view_optimization_range', bgNPC.cvar.bgn_cl_field_view_optimization_range)
RunConsoleCommand('bgn_cl_ambient_sound', bgNPC.cvar.bgn_cl_ambient_sound)
RunConsoleCommand('bgn_disable_citizens_weapons', bgNPC.cvar.bgn_disable_citizens_weapons)
RunConsoleCommand('bgn_disable_halo', bgNPC.cvar.bgn_disable_halo)
RunConsoleCommand('bgn_enable_dv_support', bgNPC.cvar.bgn_enable_dv_support)
RunConsoleCommand('bgn_disable_dialogues', bgNPC.cvar.bgn_disable_dialogues)
RunConsoleCommand('bgn_movement_checking_parts', bgNPC.cvar.bgn_movement_checking_parts)
for npcType, v in pairs(bgNPC.cfg.npcs_template) do
RunConsoleCommand('bgn_npc_type_' .. npcType, 1)
end
for npcType, v in pairs(bgNPC.cfg.npcs_template) do
RunConsoleCommand('bgn_npc_type_max_' .. npcType, bgNPC:GetFullness(npcType))
end
end)
local is_first_bgn_enable = false
cvars.AddChangeCallback('bgn_enable', function(cvar_name, old_value, new_value)
if is_first_bgn_enable or tonumber(new_value) ~= 1 then return end
is_first_bgn_enable = true
LocalPlayer():slibNotify('The first launch of "Background NPCs" can cause lags. '
.. 'Please wait until the end of the spawn.', NOTIFY_HINT, 10)
end)
|
local api = vim.api
local win, buf
local bin_path = vim.g.glow_binary_path
if bin_path == nil then
bin_path = vim.env.HOME .. "/.local/bin"
end
local use_path_glow = vim.g.glow_binary_path == nil and vim.fn.executable("glow") == 1
local glow_path = use_path_glow and "glow" or bin_path .. "/glow"
local glow_style = vim.g.glow_style or "dark"
local glow_border = vim.g.glow_border
local glow_width = vim.g.glow_width
local glow_use_pager = vim.g.glow_use_pager
local M = {}
local function has_value(tab, val)
for _, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
local function validate(path)
if vim.fn.executable(glow_path) == 0 then
return M.download_glow()
end
-- trim and get the full path
path = string.gsub(path, "%s+", "")
path = string.gsub(path, "\"", "")
path = path == "" and "%" or path
path = vim.fn.expand(path)
path = vim.fn.fnamemodify(path, ":p")
local file_exists = vim.fn.filereadable(path) == 1
-- check if file exists
if not file_exists then
api.nvim_err_writeln("file does not exists")
return
end
local ext = vim.fn.fnamemodify(path, ":e")
if not has_value({"md", "markdown", "mkd", "mkdn", "mdwn", "mdown", "mdtxt", "mdtext"}, ext) then
api.nvim_err_writeln("glow only support markdown files")
return
end
return path
end
local function install_glow()
local os, arch
local version = "1.4.1"
-- check pre-existence of required programs
if vim.fn.executable("curl") == 0 then
api.nvim_err_writeln("cURL is not installed!")
return
end
if vim.fn.executable("tar") == 0 then
api.nvim_err_writeln("tar is not installed!")
return
end
-- win install not supported for now
if vim.fn.has("win32") ~= 0 then
api.nvim_err_writeln(
"Install script not supported on Windows yet. Please install glow manually")
return
else
os = vim.fn.trim(vim.fn.system("uname"))
end
-- based on os value, detect architecture and format
if os == "Darwin" then
arch = vim.fn.trim(vim.fn.system("uname -m"))
if not has_value({"arm64", "x86_64"}, arch) then
api.nvim_err_writeln("Architecture not supported/recognized!")
return
end
elseif os == "Linux" then
-- linux releases have "linux" in the name instead of "Linux"
os = "linux"
arch = vim.fn.trim(vim.fn.system("uname -p"))
if arch == "unknown" then
arch = vim.fn.trim(vim.fn.system("uname -m"))
end
if not has_value({"armv6", "armv7", "i386", "x86_64"}, arch) then
api.nvim_err_writeln("Architecture not supported/recognized!")
return
end
else
api.nvim_err_writeln("OS not supported/recognized!")
return
end
-- create the url, filename based on os, arch, version
local filename = "glow_" .. version .. "_" .. os .. "_" .. arch .. ".tar.gz"
local url = "https://github.com/charmbracelet/glow/releases/download/v" .. version ..
"/" .. filename
local download_command = {"curl", "-sL", "-o", "glow.tar.gz", url}
local extract_command = {"tar", "-zxf", "glow.tar.gz", "-C", bin_path}
local output_filename = "glow.tar.gz"
-- check for existing files / folders
if vim.fn.isdirectory(bin_path) == 0 then
vim.fn.mkdir(bin_path, "p")
end
if vim.fn.empty(vim.fn.glob(bin_path .. "/glow")) ~= 1 then
local success = vim.loop.fs_unlink(bin_path .. "/glow")
if not success then
return api.nvim_err_writeln("Glow binary could not be removed!")
end
end
if vim.fn.empty(vim.fn.glob(output_filename)) ~= 1 then
local success = vim.loop.fs_unlink(output_filename)
if not success then
return api.nvim_err_writeln("Existing archive could not be removed!")
end
end
-- download and install the glow binary
local callbacks = {
on_sterr = vim.schedule_wrap(function(_, data, _)
local out = table.concat(data, "\n")
api.nvim_err_writeln(out)
end),
on_exit = vim.schedule_wrap(function(_, _, _)
vim.fn.system(extract_command)
-- remove the archive after completion
if vim.fn.empty(vim.fn.glob(output_filename)) ~= 1 then
local success = vim.loop.fs_unlink(output_filename)
if not success then
return api.nvim_err_writeln("Existing archive could not be removed!")
end
end
print("Glow installed successfully!")
end),
}
vim.fn.jobstart(download_command, callbacks)
end
function M.close_window()
api.nvim_win_close(win, true)
end
function M.download_glow()
if vim.fn.executable(bin_path .. "/glow") == 1 then
local answer = vim.fn.input(
"latest glow already installed in ".. bin_path .."/glow, do you want update? Y/n = ")
answer = string.lower(answer)
while answer ~= "y" and answer ~= "n" do
answer = vim.fn.input("please answer Y or n = ")
answer = string.lower(answer)
end
if answer == "n" then
return
end
print("updating glow..")
else
print("installing glow..")
end
install_glow()
end
-- open_window draws a custom window with the markdown contents
local function open_window(path)
-- window size
local width = api.nvim_get_option("columns")
local height = api.nvim_get_option("lines")
local win_height = math.ceil(height * 0.8 - 4)
local win_width = math.ceil(width * 0.8)
local row = math.ceil((height - win_height) / 2 - 1)
local col = math.ceil((width - win_width) / 2)
if glow_width and glow_width < win_width then
win_width = glow_width
end
local opts = {
style = "minimal",
relative = "editor",
width = win_width,
height = win_height,
row = row,
col = col,
border = glow_border or "shadow",
}
-- create preview buffer and set local options
buf = api.nvim_create_buf(false, true)
win = api.nvim_open_win(buf, true, opts)
api.nvim_buf_set_option(buf, "bufhidden", "wipe")
api.nvim_buf_set_option(buf, "filetype", "glowpreview")
api.nvim_win_set_option(win, "winblend", 0)
api.nvim_buf_set_keymap(buf, "n", "q", ":lua require('glow').close_window()<cr>",
{noremap = true, silent = true})
api.nvim_buf_set_keymap(buf, "n", "<Esc>", ":lua require('glow').close_window()<cr>",
{noremap = true, silent = true})
local use_pager = glow_use_pager and '-p' or ''
vim.fn.termopen(string.format("%s %s -s %s %s", glow_path, use_pager, glow_style, vim.fn.shellescape(path)))
end
function M.glow(file)
local current_win = vim.fn.win_getid()
if current_win == win then
M.close_window()
else
local path = validate(file)
if path == nil then
return
end
open_window(path)
end
end
return M
|
local main_gui = {}
local gui = require("__flib__.gui")
local constants = require("constants")
local player_data = require("scripts.player-data")
local tabs = {}
local tab_names = {"depots", "stations", "inventory", "history", "alerts"}
for _, name in ipairs(tab_names) do
tabs[name] = require("scripts.gui.main-tabs."..name)
end
local string_gsub = string.gsub
gui.add_templates{
pushers = {
horizontal = {type="empty-widget", style_mods={horizontally_stretchable=true}},
vertical = {type="empty-widget", style_mods={vertically_stretchable=true}},
both = {type="empty-widget", style_mods={horizontally_stretchable=true, vertically_stretchable=true}}
},
frame_action_button = {type="sprite-button", style="frame_action_button", mouse_button_filter={"left"}},
mock_frame_tab = {type="button", style="ltnm_mock_frame_tab", mouse_button_filter={"left"}, handlers="main.titlebar.frame_tab"},
status_indicator = function(name, color, value)
return {type="flow", style_mods={vertical_align="center"}, children={
{type="sprite", style="ltnm_status_icon", sprite="ltnm_indicator_"..color, save_as=name.."_circle"},
{type="label", style="ltnm_depot_button_label", caption=value, save_as=name.."_label"}
}}
end,
search_contents = function(name)
return {type="flow", name=name.."_contents", style="ltnm_search_content_flow", elem_mods={visible=false}, children=tabs[name].search_template}
end
}
gui.add_handlers{
main={
window = {
on_gui_closed = function(e)
local player_table = global.players[e.player_index]
if not player_table.settings.keep_gui_open and not player_table.flags.toggling_search then
main_gui.close(game.get_player(e.player_index), player_table)
end
end
},
titlebar = {
frame_tab = {
on_gui_click = function(e)
local name = e.default_tab or string_gsub(e.element.caption[1], "ltnm%-gui%.", "")
main_gui.update_active_tab(game.get_player(e.player_index), global.players[e.player_index], name)
end
},
search_button = {
on_gui_click = function(e)
main_gui.toggle_search(game.get_player(e.player_index), global.players[e.player_index])
end
},
pin_button = {
on_gui_click = function(e)
local player = game.get_player(e.player_index)
local player_table = global.players[e.player_index]
local window_data = player_table.gui.main.window
if player_table.settings.keep_gui_open then
e.element.style = "frame_action_button"
player_table.settings.keep_gui_open = false
window_data.frame.force_auto_center()
if player_table.flags.search_open then
local gui_data = player_table.gui.main
player.opened = gui_data.search.window
else
player.opened = window_data.frame
end
else
e.element.style = "ltnm_active_frame_action_button"
player_table.settings.keep_gui_open = true
window_data.frame.auto_center = false
player.opened = nil
end
end
},
refresh_button = {
on_gui_click = function(e)
if e.shift then
local settings = global.players[e.player_index].settings
if settings.auto_refresh then
player_data.set_setting(e.player_index, "auto-refresh", false)
e.element.style = "frame_action_button"
else
player_data.set_setting(e.player_index, "auto-refresh", true)
e.element.style = "ltnm_active_frame_action_button"
end
else
main_gui.update_active_tab(game.get_player(e.player_index), global.players[e.player_index])
end
end
},
close_button = {
on_gui_click = function(e)
main_gui.close(game.get_player(e.player_index), global.players[e.player_index])
end
},
},
open_train_button = {
on_gui_click = function(e)
local train_id = string_gsub(e.element.name, "ltnm_open_train__", "")
train_id = tonumber(train_id)
local train = global.data.trains[train_id]
if train then
game.get_player(e.player_index).opened = train.main_locomotive
else
game.get_player(e.player_index).print{"ltnm-message.train-invalid-refresh-gui"}
end
end
},
view_station_button = {
on_gui_click = function(e)
local station_id = string_gsub(e.element.name, "ltnm_view_station__", "")
local player = game.get_player(e.player_index)
local player_table = global.players[e.player_index]
-- check station validity
local station_data = global.data.stations[tonumber(station_id)]
if station_data and station_data.entity.valid then
if e.shift then
-- open LTN combinator
if not remote.call("ltn-combinator", "open_ltn_combinator", e.player_index, station_data.lamp_control, true) then
player.print{"ltnm-message.ltn-combinator-not-found"}
end
else
local entity = station_data.entity
-- view station on map
player.zoom_to_world(entity.position, 0.5)
rendering.draw_circle{
color = constants.station_indicator_color,
radius = 1.5,
width = 6,
filled = false,
target = entity,
surface = entity.surface,
time_to_live = 180,
players = {e.player_index}
}
if not player_table.gui.main.window.pinned then
main_gui.close(player, player_table)
end
end
else
player.print{"ltnm-message.station-invalid"}
end
end
},
material_button = {
on_gui_click = function(e)
local player_table = global.players[e.player_index]
local on_inventory_tab = player_table.gui.main.tabbed_pane.selected == "inventory"
main_gui.update(game.get_player(e.player_index), player_table, {
active_tab = (not on_inventory_tab) and "inventory",
inventory = string_gsub(e.element.sprite, "/", ",")}
)
end
}
},
search = {
window = {
on_gui_closed = function(e)
local player = game.get_player(e.player_index)
local player_table = global.players[e.player_index]
if not player_table.flags.toggling_search and not player_table.settings.keep_gui_open then
main_gui.close_search(player, player_table, player_table.gui.main)
end
end
}
}
}
function main_gui.create(player, player_table)
-- create base GUI structure
local gui_data = gui.build(player.gui.screen, {
{type="frame", style="invisible_frame", direction="vertical", handlers="main.window", save_as="window.frame", children={
{type="flow", children={
{template="pushers.horizontal"},
{type="frame", style="ltnm_search_frame", elem_mods={visible=false}, handlers="search.window", save_as="search.window", children={
gui.templates.search_contents("stations"),
gui.templates.search_contents("inventory"),
gui.templates.search_contents("history")
}},
}},
{type="flow", style_mods={horizontal_spacing=0, padding=0}, direction="horizontal", children={
-- TODO left side
{type="frame", style="ltnm_titlebar_tab_filler_frame", children={
{template="mock_frame_tab", caption={"ltnm-gui.depots"}, save_as="tabbed_pane.tabs.depots"},
{template="mock_frame_tab", caption={"ltnm-gui.stations"}, save_as="tabbed_pane.tabs.stations"},
{template="mock_frame_tab", caption={"ltnm-gui.inventory"}, save_as="tabbed_pane.tabs.inventory"},
{template="mock_frame_tab", caption={"ltnm-gui.history"}, save_as="tabbed_pane.tabs.history"},
{template="mock_frame_tab", caption={"ltnm-gui.alerts"}, save_as="tabbed_pane.tabs.alerts"},
}},
{type="frame", style="ltnm_titlebar_right_frame", children={
{type="empty-widget", style="ltnm_titlebar_drag_handle", save_as="titlebar.drag_handle"},
{template="frame_action_button", sprite="utility/search_white", hovered_sprite="utility/search_black", clicked_sprite="utility/search_black",
tooltip={"ltnm-gui.search-tooltip"}, handlers="main.titlebar.search_button", save_as="titlebar.search_button"},
{template="frame_action_button", sprite="ltnm_pin_white", hovered_sprite="ltnm_pin_black", clicked_sprite="ltnm_pin_black",
tooltip={"ltnm-gui.keep-open"}, handlers="main.titlebar.pin_button", save_as="titlebar.pin_button"},
{template="frame_action_button", sprite="ltnm_refresh_white", hovered_sprite="ltnm_refresh_black", clicked_sprite="ltnm_refresh_black",
tooltip={"ltnm-gui.refresh-button-tooltip"}, handlers="main.titlebar.refresh_button", save_as="titlebar.refresh_button"},
{template="frame_action_button", sprite="utility/close_white", hovered_sprite="utility/close_black", clicked_sprite="utility/close_black",
handlers="main.titlebar.close_button", save_as="titlebar.close_button"}
}}
}},
{type="frame", style="ltnm_main_content_frame", children={
tabs.depots.base_template,
tabs.stations.base_template,
tabs.inventory.base_template,
tabs.history.base_template,
tabs.alerts.base_template
}}
}}
})
-- other handlers
gui.update_filters("main.open_train_button", player.index, {"ltnm_open_train"}, "add")
gui.update_filters("main.view_station_button", player.index, {"ltnm_view_station"}, "add")
gui.update_filters("main.material_button", player.index, {"ltnm_view_material"}, "add")
gui.update_filters("alerts.clear_alert_button", player.index, {"ltnm_clear_alert"}, "add")
-- default settings
gui_data.window.pinned = false
gui_data.tabbed_pane.selected = "depots"
gui_data.depots.active_sort = "composition"
gui_data.depots.sort_composition = true
gui_data.depots.sort_status = true
gui_data.stations.active_sort = "name"
gui_data.stations.sort_name = true
gui_data.stations.sort_status = true
gui_data.stations.search.query = ""
gui_data.stations.search.network_id = -1
gui_data.inventory.search.query = ""
gui_data.inventory.search.network_id = -1
gui_data.history.active_sort = "finished"
gui_data.history.sort_depot = true
gui_data.history.sort_route = true
gui_data.history.sort_runtime = true
gui_data.history.sort_finished = false
gui_data.history.search.query = ""
gui_data.history.search.network_id = -1
gui_data.alerts.active_sort = "time"
gui_data.alerts.sort_time = false
gui_data.alerts.sort_id = true
gui_data.alerts.sort_route = true
gui_data.alerts.sort_type = true
gui_data.alerts.clear_all = false
-- auto-refresh
if player_table.settings.auto_refresh then
gui_data.titlebar.refresh_button.style = "ltnm_active_frame_action_button"
else
gui_data.titlebar.refresh_button.style = "frame_action_button"
end
-- pinned
if player_table.settings.keep_gui_open then
gui_data.titlebar.pin_button.style = "ltnm_active_frame_action_button"
else
gui_data.titlebar.pin_button.style = "frame_action_button"
-- center window
gui_data.window.frame.force_auto_center()
end
gui_data.titlebar.drag_handle.drag_target = gui_data.window.frame
gui_data.window.frame.visible = false
player_table.gui.main = gui_data
main_gui.update_active_tab(player, player_table, "depots")
end
function main_gui.destroy(player, player_table)
gui.update_filters("main", player.index, nil, "remove")
for _, name in ipairs(tab_names) do
gui.update_filters(name, player.index, nil, "remove")
end
player_table.gui.main.window.frame.destroy()
player_table.gui.main = nil
player_table.flags.gui_open = false
player_table.flags.can_open_gui = false
player.set_shortcut_available("ltnm-toggle-gui", false)
end
function main_gui.update(player, player_table, state_changes)
local gui_data = player_table.gui.main
local data = global.data
local material_translations = player_table.translations.materials
if state_changes.active_tab then
local tabbed_pane_data = gui_data.tabbed_pane
-- close previous tab, if there was a previous tab
if tabbed_pane_data.selected then
tabbed_pane_data.tabs[tabbed_pane_data.selected].enabled = true
tabbed_pane_data.contents[tabbed_pane_data.selected].visible = false
end
-- set new tab to focused
tabbed_pane_data.tabs[state_changes.active_tab].enabled = false
tabbed_pane_data.contents[state_changes.active_tab].visible = true
-- update selected tab in global
tabbed_pane_data.selected = state_changes.active_tab
local search_button = gui_data.titlebar.search_button
if tabs[state_changes.active_tab].search_template then
search_button.enabled = true
search_button.tooltip = {"ltnm-gui.search-tooltip"}
else
search_button.enabled = false
search_button.tooltip = {"ltnm-message.search-not-supported"}
end
end
-- active tab
local active_tab = state_changes.active_tab or gui_data.tabbed_pane.selected
tabs[active_tab].update(player, player_table, state_changes, gui_data, data, material_translations)
end
function main_gui.update_active_tab(player, player_table, name)
local changes
if name then
changes = {active_tab=name}
-- close search
if player_table.flags.search_open then
main_gui.close_search(player, player_table, player_table.gui.main, true)
end
else
name = player_table.gui.main.tabbed_pane.selected
changes = {}
end
if name == "depots" then
changes.depot_buttons = true
changes.selected_depot = player_table.gui.main.depots.selected or true
elseif name == "stations" then
changes.stations_list = true
elseif name == "inventory" then
changes.inventory = true
elseif name == "history" then
changes.history = true
elseif name == "alerts" then
changes.alerts = true
end
main_gui.update(player, player_table, changes)
end
function main_gui.open(player, player_table, skip_update)
if not skip_update then
main_gui.update_active_tab(player, player_table)
end
if not player_table.gui.main.window.pinned then
player.opened = player_table.gui.main.window.frame
end
player_table.flags.gui_open = true
player_table.gui.main.window.frame.visible = true
player.set_shortcut_toggled("ltnm-toggle-gui", true)
end
function main_gui.close(player, player_table)
player_table.flags.gui_open = false
player_table.gui.main.window.frame.visible = false
player.set_shortcut_toggled("ltnm-toggle-gui", false)
if player_table.flags.search_open then
main_gui.close_search(player, player_table, player_table.gui.main, true)
end
player.opened = nil
end
function main_gui.toggle(player, player_table)
if player_table.flags.gui_open then
main_gui.close(player, player_table)
else
main_gui.open(player, player_table)
end
end
function main_gui.open_search(player, player_table, gui_data, skip_update)
local selected_tab = gui_data.tabbed_pane.selected
gui_data.titlebar.search_button.style = "ltnm_active_frame_action_button"
-- set initial state
tabs[selected_tab].set_search_initial_state(player, player_table, gui_data)
-- set frame location offset
local main_window = gui_data.window.frame
local location = main_window.location
main_window.location = {x=location.x, y=(location.y - constants.search_frame_height)}
-- actually show the frame
local search_window = gui_data.search.window
search_window[selected_tab.."_contents"].visible = true
search_window.visible = true
-- opened logic
if not player_table.settings.keep_gui_open then
player_table.flags.toggling_search = true
player.opened = search_window
player_table.flags.toggling_search = false
end
player_table.flags.search_open = true
if not skip_update then
main_gui.update_active_tab(player, player_table)
end
end
function main_gui.close_search(player, player_table, gui_data, skip_update)
local search_window = gui_data.search.window
local selected_tab = gui_data.tabbed_pane.selected
search_window[selected_tab.."_contents"].visible = false
search_window.visible = false
-- set frame location offset
local main_window = gui_data.window.frame
local location = main_window.location
main_window.location = {x=location.x, y=(location.y + constants.search_frame_height)}
if not player_table.settings.keep_gui_open then
player_table.flags.toggling_search = true
player.opened = gui_data.window.frame
player_table.flags.toggling_search = false
end
gui_data.titlebar.search_button.style = "frame_action_button"
player_table.flags.search_open = false
if not skip_update then
main_gui.update_active_tab(player, player_table)
end
end
function main_gui.toggle_search(player, player_table)
local gui_data = player_table.gui.main
local active_tab = gui_data.tabbed_pane.selected
if player_table.flags.search_open then
main_gui.close_search(player, player_table, gui_data)
elseif tabs[active_tab].search_template then
main_gui.open_search(player, player_table, gui_data)
else
player.print{"ltnm-message.search-not-supported"}
end
end
return main_gui
|
function OnAbilityExecuted(keys)
local caster = keys.caster
local unit = keys.unit
local ability = keys.ability
local event_ability = keys.event_ability
if not event_ability:IsItem() then
unit:AddNewModifier(caster, ability, "modifier_silence", {duration = ability:GetAbilitySpecial("debuff_duration")})
local enemies = FindUnitsInRadius(caster:GetTeam(), caster:GetAbsOrigin(), nil, ability:GetAbilitySpecial("radius"), DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)
for _,v in ipairs(enemies) do
if v ~= unit then
v:AddNewModifier(caster, ability, "modifier_stunned", {duration = ability:GetAbilitySpecial("debuff_duration")})
end
end
end
end
|
setenv("ABCPY",myModuleVersion())
extensions("numpy/1.16.55,tornado/6.1,tornado/7.1")
help([[
This is the help message for python 2.7.14
]])
|
--I've pulled this from the ESX locales
Locales = {}
function _(str, ...) -- luacheck: no unused
if Locales[Config['locale']] ~= nil then
if Locales[Config['locale']][str] ~= nil then
return string.format(Locales[Config['locale']][str], ...)
else
return 'Translation [' .. Config['locale'] .. '][' .. str .. '] does not exist'
end
else
return 'Locale [' .. Config['locale'] .. '] does not exist'
end
end
function _U(str, ...) -- luacheck: no unused
return tostring(_(str, ...):gsub("^%l", string.upper))
end
|
--[[
/////// //////////////////
/////// PROJECT: MTA iLife - German Fun Reallife Gamemode
/////// VERSION: 1.7.2
/////// DEVELOPERS: See DEVELOPERS.md in the top folder
/////// LICENSE: See LICENSE.md in the top folder
/////// /////////////////
]]
--
-- Created by Noneatme
-- User: Noneatme
-- Date: 24.02.2015
-- Time: 15:42
-- Copyright(c) 2015 - iLife Team and Developers
--
cCorporationRole_ProductionManager = inherit(cSingleton);
--[[
]]
-- ///////////////////////////////
-- ///// hasPermissions //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cCorporationRole_ProductionManager:hasPermissions(uPlayer)
if(uPlayer:getCorporation() ~= 0) and (uPlayer:hasCorpRole(6)) then
return true;
else
return false;
end
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cCorporationRole_ProductionManager:onPlayerGUIOpen(uPlayer)
if(self:hasPermissions(uPlayer)) then
local id = uPlayer:getCorporation():getID();
uPlayer:getCorporation():updateBizes();
triggerClientEvent(uPlayer, "onClientPlayerCorporationProductionManagementGUIRefresh", uPlayer, uPlayer:getCorporation(), uPlayer:getCorporation():getBizes())
else
uPlayer:showInfoBox("error", "Dir fehlen die benoetigten Rechte!")
end
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cCorporationRole_ProductionManager:onPlayerBizAdd(uPlayer, iBizID)
iBizID = tonumber(iBizID)
if(self:hasPermissions(uPlayer)) and (uPlayer:hasCorpRole(1)) then
if(iBizID) and (tonumber(iBizID)) and (cBusinessManager:getInstance().m_uBusiness[iBizID]) then
local biz = cBusinessManager:getInstance().m_uBusiness[iBizID]
if(biz:getOwnerID() == 0) then
if(uPlayer:getCorporation().m_iCurBizes < uPlayer:getCorporation().m_iMaxBizes) then
if(uPlayer:getBankMoney() >= biz.m_iCost) then
if(biz.m_iLocked ~= 1) then
biz:setOwner(uPlayer:getCorporation():getID())
biz:setLagereinheiten(0)
biz:save()
local Corp = uPlayer:getCorporation()
uPlayer:showInfoBox("sucess", "Business erworben! Achte darauf, dass sich immer genug Lagereinheiten im Bestand befinden.")
Corp:sendFactionMessage("* "..uPlayer:getName().." hat ein Business hinzugefuegt.", 0, 200, 200);
Corp:updateBizes()
self:onPlayerGUIOpen(uPlayer)
uPlayer:addBankMoney(-biz.m_iCost)
logger:OutputPlayerLog(uPlayer, "Kaufte Business", uPlayer:getCorporation():getName(), biz.m_iID, "$"..biz.m_iCost);
Corp:addStatus(5);
else
uPlayer:showInfoBox("error", "Dieses Business kannst du nicht kaufen!")
end
else
uPlayer:showInfoBox("error", "Soviel Geld besitzt du nicht auf der Bank!")
end
else
uPlayer:showInfoBox("error", "Keine verfuegbaren Businessslots mehr frei! Du benoetigst erst ein Upgrade.")
end
else
uPlayer:showInfoBox("error", "Dieses Business wurde bereits erworben!")
end
else
uPlayer:showInfoBox("error", "Das Business wurde nicht gefunden!")
end
else
uPlayer:showInfoBox("error", "Keine Rechte!")
end
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cCorporationRole_ProductionManager:onPlayerBizRemove(uPlayer, iBizID)
iBizID = tonumber(iBizID)
if(self:hasPermissions(uPlayer)) and (uPlayer:hasCorpRole(1)) then
if(iBizID) and (tonumber(iBizID)) and (cBusinessManager:getInstance().m_uBusiness[iBizID]) then
local biz = cBusinessManager:getInstance().m_uBusiness[iBizID]
if(biz:getOwnerID() == uPlayer:getCorporation():getID()) then
local geld = math.floor(biz.m_iCost)*0.80;
uPlayer:addBankMoney(geld);
biz:setOwner(0)
biz:save()
local Corp = uPlayer:getCorporation()
uPlayer:showInfoBox("sucess", "Business verkauft. Du hast $"..geld.." erhalten!")
Corp:sendFactionMessage("* "..uPlayer:getName().." hat ein Business entfernt.", 0, 200, 200);
Corp:updateBizes()
self:onPlayerGUIOpen(uPlayer)
logger:OutputPlayerLog(uPlayer, "Verkaufte Business", uPlayer:getCorporation():getName(), biz.m_iID, "$"..geld);
Corp:addStatus(-2);
else
uPlayer:showInfoBox("error", "Dieses Business gehoert nicht deiner Corporation!")
end
else
uPlayer:showInfoBox("error", "Das Business wurde nicht gefunden!")
end
else
uPlayer:showInfoBox("error", "Du hast keine Rechte!")
end
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cCorporationRole_ProductionManager:onPlayerBizSlotAdd(uPlayer)
if(self:hasPermissions(uPlayer)) then
local Corp = Corporations[uPlayer:getCorporation():getID()]
if(Corp) then
local cost = _Gsettings.corporation.businessSlotCost[Corp.m_iMaxBizes+1];
if(cost) then
if(uPlayer:getBankMoney() >= cost) then
uPlayer:addBankMoney(-cost);
Corp.m_iMaxBizes = Corp.m_iMaxBizes+1;
Corp:save()
Corp:sendFactionMessage("* "..uPlayer:getName().." hat ein Businessupgrade gekauft. Maximale Bizes: "..Corp.m_iMaxBizes, 0, 200, 200);
uPlayer:showInfoBox("sucess", "Erfolg!")
self:onPlayerGUIOpen(uPlayer)
logger:OutputPlayerLog(uPlayer, "Kaufte Businessupgrade", uPlayer:getCorporation():getName());
else
uPlayer:showInfoBox("error", "Du hast nicht genug Geld auf dem Bankkonto!($"..cost.."");
end
else
uPlayer:showInfoBox("error", "Maximale Anzahl an Bizes erreicht!")
end
else
uPlayer:showInfoBox("error", "Keine Corporation!")
end
else
uPlayer:showInfoBox("error", "Du hast keine Rechte!")
end
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cCorporationRole_ProductionManager:constructor(...)
-- Klassenvariablen --
addEvent("onClientCorporationProductionManagerOpen", true)
addEvent("onPlayerCoroprationsManagementProductionBusinessAdd", true)
addEvent("onPlayerCoroprationsManagementProductionBusinessRemove", true)
addEvent("onPlayerCoroprationsManagementProductionBusinessSlotAdd", true)
-- Funktionen --
self.m_funcOnPlayerGuiOpen = function(...) self:onPlayerGUIOpen(client, ...) end
self.m_funcOnPlayerBizAdd = function(...) self:onPlayerBizAdd(client, ...) end
self.m_funcOnPlayerBizRemove = function(...) self:onPlayerBizRemove(client, ...) end
self.m_funcOnPlayerBizSlotAdd = function(...) self:onPlayerBizSlotAdd(client, ...) end
-- Events --
addEventHandler("onClientCorporationProductionManagerOpen", getRootElement(), self.m_funcOnPlayerGuiOpen)
addEventHandler("onPlayerCoroprationsManagementProductionBusinessAdd", getRootElement(), self.m_funcOnPlayerBizAdd)
addEventHandler("onPlayerCoroprationsManagementProductionBusinessRemove", getRootElement(), self.m_funcOnPlayerBizRemove)
addEventHandler("onPlayerCoroprationsManagementProductionBusinessSlotAdd", getRootElement(), self.m_funcOnPlayerBizSlotAdd)
end
-- EVENT HANDLER --
|
require "gfx"
require "random"
--works
--require "image"
-- make some data
x={}; sy={}; cy={};
for i=-3,4,0.05 do
sy[#sy+1]=math.cos(i); cy[#cy+1]=math.sin(i); x[#x+1]=i;
end
tests={1,0,0,0,0}
tests={1,1,0,0,0}
tests={1,1,1,0,0}
tests={1,1,1,1,0}
tests={1,1,1,1,1}
tests={1,0,0,0,0,0}
tests={0,0,0,0,1,0}
tests={1,1,1,1,1,1}
--tests={1,1,0,0,0,0}
if tests[1]==1 then
w1 = gfx.Window(500,500,'Torch LuaCairo Demo 1');
w1:axis(-2,3,-1.5,1.5);
w1:plot({-3,4},{-1,1},'r:')
w1:plot(x,sy,'m-')
w1:plot(x,cy,'k-o')
w1:title('Torch LuaCairo Demo 1');
w1:xlabel('data')
w1:ylabel('more data')
w1:legend('linear','sine','cosine')
w1:writePNG('demo1.png')
w1:writePDF('test1.pdf');
w1:writePS('test1.ps');
end
if tests[2]==1 then
w2 = gfx.Window(500,500,'Torch LuaCairo Demo 2');
w2:plot({1,2,3,5,8,10},{1,0,1,0,3,4},'m:x')
w2:title('Torch LuaCairo Demo 2');
-- w2:writePNG('demo2.png')
-- w2:writePDF('test2.pdf');
end
-- x=x:t();
--for i=0,1,0.05 do
x = gfx:tensorFromPNG('logo.png',4)
--print(x)
--os.exit(1)
if tests[3]==1 then
w3 = gfx.Window(250,230,'Torch -- Liberty For All 3');
w3:blit(x,3);
-- w3:writePDF('test3.pdf');
-- w3:writePS('test3.ps');
end
if tests[6]==1 then
w6 = gfx.Window(500,500,'Torch -- Liberty For All 6');
local methods=3;
local x=torch.Tensor(1000,methods)
for i=1,1000 do
for j=1,methods do
x[i][j]=random.normal();
end
end
w6:hist(x,20)
w6:title('Torch LuaCairo Demo 6');
--bins=torch.Tensor(10);
--for i=1,10 do bins[i]=i; end
--p=w6:hist(x,bins)
w6:legend('gauss1','gauss2','gauss3')
-- w6:writePNG('hist.png')
-- w6:writePDF('test6.pdf');
end
if tests[4]==1 then
w4 = gfx.Window(250,230,'Torch -- Liberty For All 4');
x4 = torch.Tensor(250,230,4);
x5 = torch.Tensor(250,230,4);
-- torch.image.scale(x,x4);
theta=0;
while w4:valid() == 1 do
--for i=1,20 do
-- torch.image.rotate(x4,x5,theta);
w4:blit(x+theta);
theta=theta+0.01;
-- os.execute("sleep 0.1")
end
end
if tests[5]==1 then
if torch.packageLuaPath("image") then
require "image"
w4 = gfx.Window(350,330,'Torch -- Liberty For All 5');
x4 = torch.Tensor(350,330,4);
x5 = torch.Tensor(350,330,4);
image.scale(x,x4);
theta=0;
while w4:valid() == 1 do
--for i=1,200 do
image.rotate(x4,x5,theta);
w4:blit(x5);
theta=theta+0.05;
end
else
print("example 5 not run because image library not installed")
end
end
-- w3:line(0,0,100,100);
--end
--w3:setPenColor({1,1,1});
--w3:text('(c) 2006 Torch Corporation',70,20,20)
--w3:writePNG('modified_logo.png')
--w3:writePdf('logo.pdf')
-- os.execute("Sleep 1")
|
--[[
When selected/all/clipboard text is being replaced, this file specifies how to transform it. Write here anything you
might need. This part is to improve text typographically with proper quotes, dashes and that.
]]
return function (input)
local val = input
local rus = regex:IsMatch(val, "[а-я]")
-- options
regex.IgnoreCase = true; -- to override locally, use :ReplaceIgnoreCase() or :ReplaceConsiderCase()
-- reset
val = regex:Replace(val, '[«»„“”]', '"')
val = regex:Replace(val, '[–—]', '-')
-- accent
val = regex:Replace(val, [[((?<=[eyuioaаеиоуыэюя]|◌)[`])]], "́")
-- punctuation
val = regex:Replace(val, [[(?<!\.)\.\.\.(?!\.)]], "…")
-- bullets
val = regex:Replace(val, [[((?<=[\n\r])(\s*)\*(?=\s))|\((?:bu|бу)\)]], "$1•")
val = regex:Replace(val, [[((?<=[\n\r])(\s*)>(?=\s))|\((?:tb|тб)\)]], "$1‣")
val = regex:Replace(val, [[((?<=[\n\r])(\s*)o(?=\s))|\((?:wb|бб)\)]], "$1◦")
val = regex:Replace(val, [[((?<=[\n\r])(\s*)-(?=\s))|\((?:hb|дб)\)]], "$1⁃")
-- arrows
val = regex:Replace(val, [[->]], '→')
val = regex:Replace(val, [[<-]], '←')
val = regex:Replace(val, [[=>]], '⇒')
val = regex:Replace(val, [[<=]], '⇐')
val = regex:Replace(val, [[<->]], '↔')
-- math
val = regex:Replace(val, [[\^0\b]], '°')
val = regex:Replace(val, [[\^1\b]], '¹')
val = regex:Replace(val, [[\^2\b]], '²')
val = regex:Replace(val, [[\^3\b]], '³')
val = regex:Replace(val, [[\b1/8\b]], '⅛')
val = regex:Replace(val, [[\b1/4\b]], '¼')
val = regex:Replace(val, [[\b1/3\b]], '⅓')
val = regex:Replace(val, [[\b3/8\b]], '⅜')
val = regex:Replace(val, [[\b1/2\b]], '½')
val = regex:Replace(val, [[\b5/8\b]], '⅝')
val = regex:Replace(val, [[\b2/3\b]], '⅔')
val = regex:Replace(val, [[\b3/4\b]], '¾')
val = regex:Replace(val, [[\b7/8\b]], '⅞')
-- special symbols
val = regex:Replace(val, [[\([cс]\)]], '©')
val = regex:Replace(val, [[\([rр]\)]], '®')
val = regex:Replace(val, [[\(tm|тм\)]], '™')
-- dashes
val = regex:Replace(val, [[([0-9])-([0-9])]], '$1–$2')
val = regex:Replace(val, [[(^|\s)-(\s|$)]], '$1—$2')
-- cool quotes
if rus then
val = regex:Replace(val, [["([a-zа-я0-9<>]([^"]|"[a-zа-я0-9<>][^"]*")*)"]], '«$1»')
val = regex:Replace(val, [["([a-zа-я0-9<>]([^"]|"[a-zа-я0-9<>][^"]*")*)"]], '„$1“')
else
val = regex:Replace(val, [["(\S(?:[\s\S]*?\S)?)?"]], '“$1”')
val = regex:Replace(val, [[([Ia-z])'(d|m|s|ll|ve|re)\b]], '$1’$2')
val = regex:Replace(val, [[([a-z]s)'(?=\s|$)]], '$1’')
val = regex:Replace(val, [[n't\b]], 'n’t')
end
return val
end
|
--[[NyaDraw Graphic Engine v1.07 for OpenOS
Standalone "Screen.lua" port from MineOS
More info on: https://github.com/Bs0Dd/OpenCompSoft/blob/master/NyaDraw/README.md
2015-2021 - ECS: https://github.com/IgorTimofeev
2021 - Bs0Dd: https://github.com/Bs0Dd
]]
local unicode = require("unicode")
local computer = require("computer")
local bit32 = require("bit32")
--------------------------------------------------------------------------------
local bufferWidth, bufferHeight
local currentFrameBackgrounds, currentFrameForegrounds, currentFrameSymbols, newFrameBackgrounds, newFrameForegrounds, newFrameSymbols
local drawLimitX1, drawLimitX2, drawLimitY1, drawLimitY2
local GPUProxy, GPUProxyGetResolution, GPUProxySetResolution, GPUProxyGetBackground, GPUProxyGetForeground, GPUProxySetBackground, GPUProxySetForeground, GPUProxyGet, GPUProxySet, GPUProxyFill
local mathCeil, mathFloor, mathModf, mathAbs, mathMin, mathMax = math.ceil, math.floor, math.modf, math.abs, math.min, math.max
local tableInsert, tableConcat = table.insert, table.concat
local colorIntegerToRGB, colorRGBToInteger, colorBlend
local unicodeLen, unicodeSub = unicode.len, unicode.sub
--------------------------------------------------------------------------------
local function getIndex(x, y)
return bufferWidth * (y - 1) + x
end
local function getCurrentFrameTables()
return currentFrameBackgrounds, currentFrameForegrounds, currentFrameSymbols
end
local function getNewFrameTables()
return newFrameBackgrounds, newFrameForegrounds, newFrameSymbols
end
--------------------------------------------------------------------------------
local function setDrawLimit(x1, y1, x2, y2)
drawLimitX1, drawLimitY1, drawLimitX2, drawLimitY2 = x1, y1, x2, y2
end
local function resetDrawLimit()
drawLimitX1, drawLimitY1, drawLimitX2, drawLimitY2 = 1, 1, bufferWidth, bufferHeight
end
local function getDrawLimit()
return drawLimitX1, drawLimitY1, drawLimitX2, drawLimitY2
end
--------------------------------------------------------------------------------
--Color Subsystem (Ported by Bs()Dd)
local palette = {0x000000, 0x000040, 0x000080, 0x0000BF, 0x0000FF, 0x002400, 0x002440, 0x002480, 0x0024BF, 0x0024FF, 0x004900, 0x004940,
0x004980, 0x0049BF, 0x0049FF, 0x006D00, 0x006D40, 0x006D80, 0x006DBF, 0x006DFF, 0x009200, 0x009240, 0x009280, 0x0092BF, 0x0092FF, 0x00B600,
0x00B640, 0x00B680, 0x00B6BF, 0x00B6FF, 0x00DB00, 0x00DB40, 0x00DB80, 0x00DBBF, 0x00DBFF, 0x00FF00, 0x00FF40, 0x00FF80, 0x00FFBF, 0x00FFFF,
0x0F0F0F, 0x1E1E1E, 0x2D2D2D, 0x330000, 0x330040, 0x330080, 0x3300BF, 0x3300FF, 0x332400, 0x332440, 0x332480, 0x3324BF, 0x3324FF, 0x334900,
0x334940, 0x334980, 0x3349BF, 0x3349FF, 0x336D00, 0x336D40, 0x336D80, 0x336DBF, 0x336DFF, 0x339200, 0x339240, 0x339280, 0x3392BF, 0x3392FF,
0x33B600, 0x33B640, 0x33B680, 0x33B6BF, 0x33B6FF, 0x33DB00, 0x33DB40, 0x33DB80, 0x33DBBF, 0x33DBFF, 0x33FF00, 0x33FF40, 0x33FF80, 0x33FFBF,
0x33FFFF, 0x3C3C3C, 0x4B4B4B, 0x5A5A5A, 0x660000, 0x660040, 0x660080, 0x6600BF, 0x6600FF, 0x662400, 0x662440, 0x662480, 0x6624BF, 0x6624FF,
0x664900, 0x664940, 0x664980, 0x6649BF, 0x6649FF, 0x666D00, 0x666D40, 0x666D80, 0x666DBF, 0x666DFF, 0x669200, 0x669240, 0x669280, 0x6692BF,
0x6692FF, 0x66B600, 0x66B640, 0x66B680, 0x66B6BF, 0x66B6FF, 0x66DB00, 0x66DB40, 0x66DB80, 0x66DBBF, 0x66DBFF, 0x66FF00, 0x66FF40, 0x66FF80,
0x66FFBF, 0x66FFFF, 0x696969, 0x787878, 0x878787, 0x969696, 0x990000, 0x990040, 0x990080, 0x9900BF, 0x9900FF, 0x992400, 0x992440, 0x992480,
0x9924BF, 0x9924FF, 0x994900, 0x994940, 0x994980, 0x9949BF, 0x9949FF, 0x996D00, 0x996D40, 0x996D80, 0x996DBF, 0x996DFF, 0x999200, 0x999240,
0x999280, 0x9992BF, 0x9992FF, 0x99B600, 0x99B640, 0x99B680, 0x99B6BF, 0x99B6FF, 0x99DB00, 0x99DB40, 0x99DB80, 0x99DBBF, 0x99DBFF, 0x99FF00,
0x99FF40, 0x99FF80, 0x99FFBF, 0x99FFFF, 0xA5A5A5, 0xB4B4B4, 0xC3C3C3, 0xCC0000, 0xCC0040, 0xCC0080, 0xCC00BF, 0xCC00FF, 0xCC2400, 0xCC2440,
0xCC2480, 0xCC24BF, 0xCC24FF, 0xCC4900, 0xCC4940, 0xCC4980, 0xCC49BF, 0xCC49FF, 0xCC6D00, 0xCC6D40, 0xCC6D80, 0xCC6DBF, 0xCC6DFF, 0xCC9200,
0xCC9240, 0xCC9280, 0xCC92BF, 0xCC92FF, 0xCCB600, 0xCCB640, 0xCCB680, 0xCCB6BF, 0xCCB6FF, 0xCCDB00, 0xCCDB40, 0xCCDB80, 0xCCDBBF, 0xCCDBFF,
0xCCFF00, 0xCCFF40, 0xCCFF80, 0xCCFFBF, 0xCCFFFF, 0xD2D2D2, 0xE1E1E1, 0xF0F0F0, 0xFF0000, 0xFF0040, 0xFF0080, 0xFF00BF, 0xFF00FF, 0xFF2400,
0xFF2440, 0xFF2480, 0xFF24BF, 0xFF24FF, 0xFF4900, 0xFF4940, 0xFF4980, 0xFF49BF, 0xFF49FF, 0xFF6D00, 0xFF6D40, 0xFF6D80, 0xFF6DBF, 0xFF6DFF,
0xFF9200, 0xFF9240, 0xFF9280, 0xFF92BF, 0xFF92FF, 0xFFB600, 0xFFB640, 0xFFB680, 0xFFB6BF, 0xFFB6FF, 0xFFDB00, 0xFFDB40, 0xFFDB80, 0xFFDBBF,
0xFFDBFF, 0xFFFF00, 0xFFFF40, 0xFFFF80, 0xFFFFBF, 0xFFFFFF}
local function to24Bit(color8Bit)
return palette[color8Bit + 1]
end
if computer.getArchitecture and computer.getArchitecture() == "Lua 5.3" then
colorIntegerToRGB, colorRGBToInteger, colorBlend = load([[return function(integerColor)
return integerColor >> 16, integerColor >> 8 & 0xFF, integerColor & 0xFF
end,
function(r, g, b)
return r << 16 | g << 8 | b
end,
function(color1, color2, transparency)
local invertedTransparency = 1 - transparency
return
((color2 >> 16) * invertedTransparency + (color1 >> 16) * transparency) // 1 << 16 |
((color2 >> 8 & 0xFF) * invertedTransparency + (color1 >> 8 & 0xFF) * transparency) // 1 << 8 |
((color2 & 0xFF) * invertedTransparency + (color1 & 0xFF) * transparency) // 1
end]])()
else
colorIntegerToRGB = function(integerColor)
local r = integerColor / 65536
r = r - r % 1
local g = (integerColor - r * 65536) / 256
g = g - g % 1
return r, g, integerColor - r * 65536 - g * 256
end
colorRGBToInteger = function(r, g, b)
return r * 65536 + g * 256 + b
end
colorBlend = function(color1, color2, transparency)
local invertedTransparency = 1 - transparency
local r1, r2 = color1 / 65536, color2 / 65536
r1, r2 = r1 - r1 % 1, r2 - r2 % 1
local g1, g2 = (color1 - r1 * 65536) / 256, (color2 - r2 * 65536) / 256
g1, g2 = g1 - g1 % 1, g2 - g2 % 1
local r, g, b = r2 * invertedTransparency + r1 * transparency, g2 * invertedTransparency + g1 * transparency,
(color2 - r2 * 65536 - g2 * 256) * invertedTransparency + (color1 - r1 * 65536 - g1 * 256) * transparency
return (r - r % 1) * 65536 + (g - g % 1) * 256 + (b - b % 1)
end
end
--------------------------------------------------------------------------------
--AdvancedRead Subsystem (Ported by Bs()Dd)
local function fold(init, op, ...)
local result = init
local args = table.pack(...)
for i = 1, args.n do
result = op(result, args[i])
end
return result
end
local function readUnicodeChar(file)
local byteArray = {string.byte(file:read(1))}
local nullBitPosition = 0
for i = 1, 7 do
if bit32.band(bit32.rshift(byteArray[1], 8 - i), 0x1) == 0x0 then
nullBitPosition = i
break
end
end
for i = 1, nullBitPosition - 2 do
table.insert(byteArray, string.byte(file:read(1)))
end
return string.char(table.unpack(byteArray))
end
local function readBytes(file, count)
local bytes, result = {string.byte(file:read(count) or "\x00", 1, 8)}, 0
for i = 1, #bytes do
result = bit32.bor(bit32.lshift(result, 8), bytes[i])
end
return result
end
--------------------------------------------------------------------------------
--ImageLoader Subsystem (Ported by Bs0Dd)
local function iset(picture, x, y, background, foreground, alpha, symbol)
local index = 4 * (picture[1] * (y - 1) + x) - 1
picture[index], picture[index + 1], picture[index + 2], picture[index + 3] = background, foreground, alpha, symbol
return picture
end
local function multiLoad(file, picture, ocif7, ocif8) --MultiLoader for OCIF6-8.
picture[1] = string.byte(file:read(1)) + ocif8
picture[2] = string.byte(file:read(1)) + ocif8
local currentAlpha, currentSymbol, currentBackground, currentForeground, currentY
for alpha = 1, string.byte(file:read(1)) + ocif7 do
currentAlpha = string.byte(file:read(1)) / 255
for symbol = 1, readBytes(file, 2) + ocif7 do
currentSymbol = readUnicodeChar(file)
for background = 1, string.byte(file:read(1)) + ocif7 do
currentBackground = to24Bit(string.byte(file:read(1)))
for foreground = 1, string.byte(file:read(1)) + ocif7 do
currentForeground = to24Bit(string.byte(file:read(1)))
for y = 1, string.byte(file:read(1)) + ocif7 do
currentY = string.byte(file:read(1))
for x = 1, string.byte(file:read(1)) + ocif7 do
iset(
picture,
string.byte(file:read(1)) + ocif8,
currentY + ocif8,
currentBackground,
currentForeground,
currentAlpha,
currentSymbol
)
end
end
end
end
end
end
end
local Loader = {}
Loader[5] = function(file, picture)
picture[1] = readBytes(file, 2)
picture[2] = readBytes(file, 2)
for i = 1, picture[1] * picture[2] do
table.insert(picture, to24Bit(string.byte(file:read(1))))
table.insert(picture, to24Bit(string.byte(file:read(1))))
table.insert(picture, string.byte(file:read(1)) / 255)
table.insert(picture, readUnicodeChar(file))
end
end
Loader[6] = function(file, picture)
multiLoad(file, picture, 0, 0)
end
Loader[7] = function(file, picture)
multiLoad(file, picture, 1, 0)
end
Loader[8] = function(file, picture)
multiLoad(file, picture, 1, 1)
end
local function loadImage(path)
local file, reason = io.open(path, "rb")
if file then
local readedSignature = file:read(4)
if readedSignature == "OCIF" then
local encodingMethod = string.byte(file:read(1))
if Loader[encodingMethod] then
local picture = {}
local result, reason = xpcall(Loader[encodingMethod], debug.traceback, file, picture)
file:close()
if result then
return picture
else
return false, "Failed to load OCIF image: " .. tostring(reason)
end
else
file:close()
return false, "Failed to load OCIF image: encoding method \"" .. tostring(encodingMethod) .. "\" is not supported"
end
else
file:close()
return false, "Failed to load OCIF image: binary signature \"" .. tostring(readedSignature) .. "\" is not valid"
end
else
return false, "Failed to open file \"" .. tostring(path) .. "\" for reading: " .. tostring(reason)
end
end
--------------------------------------------------------------------------------
local function flush(width, height)
if not width or not height then
width, height = GPUProxyGetResolution()
end
currentFrameBackgrounds, currentFrameForegrounds, currentFrameSymbols, newFrameBackgrounds, newFrameForegrounds, newFrameSymbols = {}, {}, {}, {}, {}, {}
bufferWidth = width
bufferHeight = height
resetDrawLimit()
for y = 1, bufferHeight do
for x = 1, bufferWidth do
tableInsert(currentFrameBackgrounds, 0x010101)
tableInsert(currentFrameForegrounds, 0xFEFEFE)
tableInsert(currentFrameSymbols, " ")
tableInsert(newFrameBackgrounds, 0x010101)
tableInsert(newFrameForegrounds, 0xFEFEFE)
tableInsert(newFrameSymbols, " ")
end
end
end
local function setResolution(width, height)
GPUProxySetResolution(width, height)
flush(width, height)
end
local function getResolution()
return bufferWidth, bufferHeight
end
local function getWidth()
return bufferWidth
end
local function getHeight()
return bufferHeight
end
local function bind(address, reset)
local success, reason = GPUProxy.bind(address, reset)
if success then
if reset then
setResolution(GPUProxy.maxResolution())
else
setResolution(bufferWidth, bufferHeight)
end
else
return success, reason
end
end
local function getGPUProxy()
return GPUProxy
end
local function updateGPUProxyMethods()
GPUProxyGet = GPUProxy.get
GPUProxyGetResolution = GPUProxy.getResolution
GPUProxyGetBackground = GPUProxy.getBackground
GPUProxyGetForeground = GPUProxy.getForeground
GPUProxySet = GPUProxy.set
GPUProxySetResolution = GPUProxy.setResolution
GPUProxySetBackground = GPUProxy.setBackground
GPUProxySetForeground = GPUProxy.setForeground
GPUProxyFill = GPUProxy.fill
end
local function setGPUProxy(proxy)
GPUProxy = proxy
updateGPUProxyMethods()
flush()
end
local function getScaledResolution(scale)
if not scale or scale > 1 then
scale = 1
elseif scale < 0.1 then
scale = 0.1
end
local aspectWidth, aspectHeight = component.proxy(GPUProxy.getScreen()).getAspectRatio()
local maxWidth, maxHeight = GPUProxy.maxResolution()
local proportion = 2 * (16 * aspectWidth - 4.5) / (16 * aspectHeight - 4.5)
local height = scale * mathMin(
maxWidth / proportion,
maxWidth,
math.sqrt(maxWidth * maxHeight / proportion)
)
return math.floor(height * proportion), math.floor(height)
end
--------------------------------------------------------------------------------
local function rawSet(index, background, foreground, symbol)
newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index] = background, foreground, symbol
end
local function rawGet(index)
return newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index]
end
local function get(x, y)
if x >= 1 and y >= 1 and x <= bufferWidth and y <= bufferHeight then
local index = bufferWidth * (y - 1) + x
return newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index]
else
return 0x000000, 0x000000, " "
end
end
local function set(x, y, background, foreground, symbol)
if x >= drawLimitX1 and y >= drawLimitY1 and x <= drawLimitX2 and y <= drawLimitY2 then
local index = bufferWidth * (y - 1) + x
newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index] = background, foreground, symbol
end
end
local function drawRectangle(x, y, width, height, background, foreground, symbol, transparency)
local temp
-- Clipping left
if x < drawLimitX1 then
width = width - drawLimitX1 + x
x = drawLimitX1
end
-- Right
temp = x + width - 1
if temp > drawLimitX2 then
width = width - temp + drawLimitX2
end
-- Top
if y < drawLimitY1 then
height = height - drawLimitY1 + y
y = drawLimitY1
end
-- Bottom
temp = y + height - 1
if temp > drawLimitY2 then
height = height - temp + drawLimitY2
end
temp = bufferWidth * (y - 1) + x
local indexStepOnEveryLine = bufferWidth - width
if transparency then
for j = 1, height do
for i = 1, width do
newFrameBackgrounds[temp],
newFrameForegrounds[temp] =
colorBlend(newFrameBackgrounds[temp], background, transparency),
colorBlend(newFrameForegrounds[temp], background, transparency)
temp = temp + 1
end
temp = temp + indexStepOnEveryLine
end
else
for j = 1, height do
for i = 1, width do
newFrameBackgrounds[temp],
newFrameForegrounds[temp],
newFrameSymbols[temp] = background, foreground, symbol
temp = temp + 1
end
temp = temp + indexStepOnEveryLine
end
end
end
local function blur(x, y, width, height, radius, color, transparency)
local temp
-- Clipping left
if x < drawLimitX1 then
width = width - drawLimitX1 + x
x = drawLimitX1
end
-- Right
temp = x + width - 1
if temp > drawLimitX2 then
width = width - temp + drawLimitX2
end
-- Top
if y < drawLimitY1 then
height = height - drawLimitY1 + y
y = drawLimitY1
end
-- Bottom
temp = y + height - 1
if temp > drawLimitY2 then
height = height - temp + drawLimitY2
end
local screenIndex, indexStepOnEveryLine, buffer, bufferIndex, rSum, gSum, bSum, rSumFg, gSumFg, bSumFg, r, g, b =
bufferWidth * (y - 1) + x,
bufferWidth - width,
{},
1
-- Copying
temp = screenIndex
if color then
for j = 1, height do
for i = 1, width do
buffer[bufferIndex] = colorBlend(newFrameBackgrounds[temp], color, transparency)
temp, bufferIndex = temp + 1, bufferIndex + 1
end
temp = temp + indexStepOnEveryLine
end
else
for j = 1, height do
for i = 1, width do
buffer[bufferIndex] = newFrameBackgrounds[temp]
temp, bufferIndex = temp + 1, bufferIndex + 1
end
temp = temp + indexStepOnEveryLine
end
end
-- Blurring
local rSum, gSum, bSum, count, r, g, b
for j = 1, height do
for i = 1, width do
rSum, gSum, bSum, count = 0, 0, 0, 0
for jr = mathMax(1, j - radius), mathMin(j + radius, height) do
for ir = mathMax(1, i - radius), mathMin(i + radius, width) do
r, g, b = colorIntegerToRGB(buffer[width * (jr - 1) + ir])
rSum, gSum, bSum, count = rSum + r, gSum + g, bSum + b, count + 1
end
end
-- Calculatin average channels value
r, g, b = rSum / count, gSum / count, bSum / count
-- Faster than math.floor
r, g, b = r - r % 1, g - g % 1, b - b % 1
newFrameBackgrounds[screenIndex] = colorRGBToInteger(r, g, b)
newFrameForegrounds[screenIndex] = 0x0
newFrameSymbols[screenIndex] = " "
screenIndex = screenIndex + 1
end
screenIndex = screenIndex + indexStepOnEveryLine
end
end
local function clear(color, transparency)
drawRectangle(1, 1, bufferWidth, bufferHeight, color or 0x0, 0x000000, " ", transparency)
end
local function copy(x, y, width, height)
local copyArray, index = { width, height }
for j = y, y + height - 1 do
for i = x, x + width - 1 do
if i >= 1 and j >= 1 and i <= bufferWidth and j <= bufferHeight then
index = bufferWidth * (j - 1) + i
tableInsert(copyArray, newFrameBackgrounds[index])
tableInsert(copyArray, newFrameForegrounds[index])
tableInsert(copyArray, newFrameSymbols[index])
else
tableInsert(copyArray, 0x0)
tableInsert(copyArray, 0x0)
tableInsert(copyArray, " ")
end
end
end
return copyArray
end
local function paste(startX, startY, picture)
local imageWidth = picture[1]
local screenIndex, pictureIndex, screenIndexStepOnReachOfImageWidth = bufferWidth * (startY - 1) + startX, 3, bufferWidth - imageWidth
for y = startY, startY + picture[2] - 1 do
if y >= drawLimitY1 and y <= drawLimitY2 then
for x = startX, startX + imageWidth - 1 do
if x >= drawLimitX1 and x <= drawLimitX2 then
newFrameBackgrounds[screenIndex] = picture[pictureIndex]
newFrameForegrounds[screenIndex] = picture[pictureIndex + 1]
newFrameSymbols[screenIndex] = picture[pictureIndex + 2]
end
screenIndex, pictureIndex = screenIndex + 1, pictureIndex + 3
end
screenIndex = screenIndex + screenIndexStepOnReachOfImageWidth
else
screenIndex, pictureIndex = screenIndex + bufferWidth, pictureIndex + imageWidth * 3
end
end
end
local function rasterizeLine(x1, y1, x2, y2, method)
local inLoopValueFrom, inLoopValueTo, outLoopValueFrom, outLoopValueTo, isReversed, inLoopValueDelta, outLoopValueDelta = x1, x2, y1, y2, false, mathAbs(x2 - x1), mathAbs(y2 - y1)
if inLoopValueDelta < outLoopValueDelta then
inLoopValueFrom, inLoopValueTo, outLoopValueFrom, outLoopValueTo, isReversed, inLoopValueDelta, outLoopValueDelta = y1, y2, x1, x2, true, outLoopValueDelta, inLoopValueDelta
end
if outLoopValueFrom > outLoopValueTo then
outLoopValueFrom, outLoopValueTo = outLoopValueTo, outLoopValueFrom
inLoopValueFrom, inLoopValueTo = inLoopValueTo, inLoopValueFrom
end
local outLoopValue, outLoopValueCounter, outLoopValueTriggerIncrement = outLoopValueFrom, 1, inLoopValueDelta / outLoopValueDelta
local outLoopValueTrigger = outLoopValueTriggerIncrement
for inLoopValue = inLoopValueFrom, inLoopValueTo, inLoopValueFrom < inLoopValueTo and 1 or -1 do
if isReversed then
method(outLoopValue, inLoopValue)
else
method(inLoopValue, outLoopValue)
end
outLoopValueCounter = outLoopValueCounter + 1
if outLoopValueCounter > outLoopValueTrigger then
outLoopValue, outLoopValueTrigger = outLoopValue + 1, outLoopValueTrigger + outLoopValueTriggerIncrement
end
end
end
local function rasterizeEllipse(centerX, centerY, radiusX, radiusY, method)
local function rasterizeEllipsePoints(XP, YP)
method(centerX + XP, centerY + YP)
method(centerX - XP, centerY + YP)
method(centerX - XP, centerY - YP)
method(centerX + XP, centerY - YP)
end
local x, y, changeX, changeY, ellipseError, twoASquare, twoBSquare = radiusX, 0, radiusY * radiusY * (1 - 2 * radiusX), radiusX * radiusX, 0, 2 * radiusX * radiusX, 2 * radiusY * radiusY
local stoppingX, stoppingY = twoBSquare * radiusX, 0
while stoppingX >= stoppingY do
rasterizeEllipsePoints(x, y)
y, stoppingY, ellipseError = y + 1, stoppingY + twoASquare, ellipseError + changeY
changeY = changeY + twoASquare
if (2 * ellipseError + changeX) > 0 then
x, stoppingX, ellipseError = x - 1, stoppingX - twoBSquare, ellipseError + changeX
changeX = changeX + twoBSquare
end
end
x, y, changeX, changeY, ellipseError, stoppingX, stoppingY = 0, radiusY, radiusY * radiusY, radiusX * radiusX * (1 - 2 * radiusY), 0, 0, twoASquare * radiusY
while stoppingX <= stoppingY do
rasterizeEllipsePoints(x, y)
x, stoppingX, ellipseError = x + 1, stoppingX + twoBSquare, ellipseError + changeX
changeX = changeX + twoBSquare
if (2 * ellipseError + changeY) > 0 then
y, stoppingY, ellipseError = y - 1, stoppingY - twoASquare, ellipseError + changeY
changeY = changeY + twoASquare
end
end
end
local function rasterizePolygon(centerX, centerY, startX, startY, countOfEdges, method)
local degreeStep = 360 / countOfEdges
local deltaX, deltaY = startX - centerX, startY - centerY
local radius = math.sqrt(deltaX ^ 2 + deltaY ^ 2)
local halfRadius = radius / 2
local startDegree = math.deg(math.asin(deltaX / radius))
local function round(num)
if num >= 0 then
return math.floor(num + 0.5)
else
return math.ceil(num - 0.5)
end
end
local function calculatePosition(degree)
local radDegree = math.rad(degree)
local deltaX2 = math.sin(radDegree) * radius
local deltaY2 = math.cos(radDegree) * radius
return round(centerX + deltaX2), round(centerY + (deltaY >= 0 and deltaY2 or -deltaY2))
end
local xOld, yOld, xNew, yNew = calculatePosition(startDegree)
for degree = (startDegree + degreeStep - 1), (startDegree + 360), degreeStep do
xNew, yNew = calculatePosition(degree)
rasterizeLine(xOld, yOld, xNew, yNew, method)
xOld, yOld = xNew, yNew
end
end
local function drawLine(x1, y1, x2, y2, background, foreground, symbol)
rasterizeLine(x1, y1, x2, y2, function(x, y)
set(x, y, background, foreground, symbol)
end)
end
local function drawEllipse(centerX, centerY, radiusX, radiusY, background, foreground, symbol)
rasterizeEllipse(centerX, centerY, radiusX, radiusY, function(x, y)
set(x, y, background, foreground, symbol)
end)
end
local function drawPolygon(centerX, centerY, radiusX, radiusY, background, foreground, countOfEdges, symbol)
rasterizePolygon(centerX, centerY, radiusX, radiusY, countOfEdges, function(x, y)
set(x, y, background, foreground, symbol)
end)
end
local function drawText(x, y, textColor, data, transparency)
if y >= drawLimitY1 and y <= drawLimitY2 then
local charIndex, screenIndex = 1, bufferWidth * (y - 1) + x
for charIndex = 1, unicodeLen(data) do
if x >= drawLimitX1 and x <= drawLimitX2 then
if transparency then
newFrameForegrounds[screenIndex] = colorBlend(newFrameBackgrounds[screenIndex], textColor, transparency)
else
newFrameForegrounds[screenIndex] = textColor
end
newFrameSymbols[screenIndex] = unicodeSub(data, charIndex, charIndex)
end
x, screenIndex = x + 1, screenIndex + 1
end
end
end
local function drawImage(x, y, picture, blendForeground)
local imageWidth, imageHeight, pictureIndex, temp = picture[1], picture[2], 3
local clippedImageWidth, clippedImageHeight = imageWidth, imageHeight
-- Clipping left
if x < drawLimitX1 then
temp = drawLimitX1 - x
clippedImageWidth, x, pictureIndex = clippedImageWidth - temp, drawLimitX1, pictureIndex + temp * 4
end
-- Right
temp = x + clippedImageWidth - 1
if temp > drawLimitX2 then
clippedImageWidth = clippedImageWidth - temp + drawLimitX2
end
-- Top
if y < drawLimitY1 then
temp = drawLimitY1 - y
clippedImageHeight, y, pictureIndex = clippedImageHeight - temp, drawLimitY1, pictureIndex + temp * imageWidth * 4
end
-- Bottom
temp = y + clippedImageHeight - 1
if temp > drawLimitY2 then
clippedImageHeight = clippedImageHeight - temp + drawLimitY2
end
local
screenIndex,
screenIndexStep,
pictureIndexStep,
background,
foreground,
alpha,
symbol = bufferWidth * (y - 1) + x, bufferWidth - clippedImageWidth, (imageWidth - clippedImageWidth) * 4
for j = 1, clippedImageHeight do
for i = 1, clippedImageWidth do
alpha, symbol = picture[pictureIndex + 2], picture[pictureIndex + 3]
-- If it's fully transparent pixel
if alpha == 0 then
newFrameBackgrounds[screenIndex], newFrameForegrounds[screenIndex] = picture[pictureIndex], picture[pictureIndex + 1]
-- If it has some transparency
elseif alpha > 0 and alpha < 1 then
newFrameBackgrounds[screenIndex] = colorBlend(newFrameBackgrounds[screenIndex], picture[pictureIndex], alpha)
if blendForeground then
newFrameForegrounds[screenIndex] = colorBlend(newFrameForegrounds[screenIndex], picture[pictureIndex + 1], alpha)
else
newFrameForegrounds[screenIndex] = picture[pictureIndex + 1]
end
-- If it's not transparent with whitespace
elseif symbol ~= " " then
newFrameForegrounds[screenIndex] = picture[pictureIndex + 1]
end
newFrameSymbols[screenIndex] = symbol
screenIndex, pictureIndex = screenIndex + 1, pictureIndex + 4
end
screenIndex, pictureIndex = screenIndex + screenIndexStep, pictureIndex + pictureIndexStep
end
end
local function drawFrame(x, y, width, height, color)
local stringUp, stringDown, x2 = "┌" .. string.rep("─", width - 2) .. "┐", "└" .. string.rep("─", width - 2) .. "┘", x + width - 1
drawText(x, y, color, stringUp); y = y + 1
for i = 1, height - 2 do
drawText(x, y, color, "│")
drawText(x2, y, color, "│")
y = y + 1
end
drawText(x, y, color, stringDown)
end
--------------------------------------------------------------------------------
local function semiPixelRawSet(index, color, yPercentTwoEqualsZero)
local upperPixel, lowerPixel, bothPixel = "▀", "▄", " "
local background, foreground, symbol = newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index]
if yPercentTwoEqualsZero then
if symbol == upperPixel then
if color == foreground then
newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index] = color, foreground, bothPixel
else
newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index] = color, foreground, symbol
end
elseif symbol == bothPixel then
if color ~= background then
newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index] = background, color, lowerPixel
end
else
newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index] = background, color, lowerPixel
end
else
if symbol == lowerPixel then
if color == foreground then
newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index] = color, foreground, bothPixel
else
newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index] = color, foreground, symbol
end
elseif symbol == bothPixel then
if color ~= background then
newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index] = background, color, upperPixel
end
else
newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index] = background, color, upperPixel
end
end
end
local function semiPixelSet(x, y, color)
local yFixed = mathCeil(y / 2)
if x >= drawLimitX1 and yFixed >= drawLimitY1 and x <= drawLimitX2 and yFixed <= drawLimitY2 then
semiPixelRawSet(bufferWidth * (yFixed - 1) + x, color, y % 2 == 0)
end
end
local function drawSemiPixelRectangle(x, y, width, height, color)
local index, evenYIndexStep, oddYIndexStep, realY, evenY =
bufferWidth * (mathCeil(y / 2) - 1) + x,
(bufferWidth - width),
width
for pseudoY = y, y + height - 1 do
realY = mathCeil(pseudoY / 2)
if realY >= drawLimitY1 and realY <= drawLimitY2 then
evenY = pseudoY % 2 == 0
for pseudoX = x, x + width - 1 do
if pseudoX >= drawLimitX1 and pseudoX <= drawLimitX2 then
semiPixelRawSet(index, color, evenY)
end
index = index + 1
end
else
index = index + width
end
if evenY then
index = index + evenYIndexStep
else
index = index - oddYIndexStep
end
end
end
local function drawSemiPixelLine(x1, y1, x2, y2, color)
rasterizeLine(x1, y1, x2, y2, function(x, y)
semiPixelSet(x, y, color)
end)
end
local function drawSemiPixelEllipse(centerX, centerY, radiusX, radiusY, color)
rasterizeEllipse(centerX, centerY, radiusX, radiusY, function(x, y)
semiPixelSet(x, y, color)
end)
end
--------------------------------------------------------------------------------
local function getPointTimedPosition(firstPoint, secondPoint, time)
return {
x = firstPoint.x + (secondPoint.x - firstPoint.x) * time,
y = firstPoint.y + (secondPoint.y - firstPoint.y) * time
}
end
local function getConnectionPoints(points, time)
local connectionPoints = {}
for point = 1, #points - 1 do
tableInsert(connectionPoints, getPointTimedPosition(points[point], points[point + 1], time))
end
return connectionPoints
end
local function getMainPointPosition(points, time)
if #points > 1 then
return getMainPointPosition(getConnectionPoints(points, time), time)
else
return points[1]
end
end
local function drawSemiPixelCurve(points, color, precision)
local linePoints = {}
for time = 0, 1, precision or 0.01 do
tableInsert(linePoints, getMainPointPosition(points, time))
end
for point = 1, #linePoints - 1 do
drawSemiPixelLine(mathFloor(linePoints[point].x), mathFloor(linePoints[point].y), mathFloor(linePoints[point + 1].x), mathFloor(linePoints[point + 1].y), color)
end
end
--------------------------------------------------------------------------------
local function update(force)
local index, indexStepOnEveryLine, changes = bufferWidth * (drawLimitY1 - 1) + drawLimitX1, (bufferWidth - drawLimitX2 + drawLimitX1 - 1), {}
local x, equalChars, equalCharsIndex, charX, charIndex, currentForeground
local currentFrameBackground, currentFrameForeground, currentFrameSymbol, changesCurrentFrameBackground, changesCurrentFrameBackgroundCurrentFrameForeground
local changesCurrentFrameBackgroundCurrentFrameForegroundIndex
for y = drawLimitY1, drawLimitY2 do
x = drawLimitX1
while x <= drawLimitX2 do
-- Determine if some pixel data was changed (or if <force> argument was passed)
if
currentFrameBackgrounds[index] ~= newFrameBackgrounds[index] or
currentFrameForegrounds[index] ~= newFrameForegrounds[index] or
currentFrameSymbols[index] ~= newFrameSymbols[index] or
force
then
-- Make pixel at both frames equal
currentFrameBackground, currentFrameForeground, currentFrameSymbol = newFrameBackgrounds[index], newFrameForegrounds[index], newFrameSymbols[index]
currentFrameBackgrounds[index] = currentFrameBackground
currentFrameForegrounds[index] = currentFrameForeground
currentFrameSymbols[index] = currentFrameSymbol
-- Look for pixels with equal chars from right of current pixel
equalChars, equalCharsIndex, charX, charIndex = {currentFrameSymbol}, 2, x + 1, index + 1
while charX <= drawLimitX2 do
-- Pixels becomes equal only if they have same background and (whitespace char or same foreground)
if
currentFrameBackground == newFrameBackgrounds[charIndex] and
(
newFrameSymbols[charIndex] == " " or
currentFrameForeground == newFrameForegrounds[charIndex]
)
then
-- Make pixel at both frames equal
currentFrameBackgrounds[charIndex] = newFrameBackgrounds[charIndex]
currentFrameForegrounds[charIndex] = newFrameForegrounds[charIndex]
currentFrameSymbols[charIndex] = newFrameSymbols[charIndex]
equalChars[equalCharsIndex], equalCharsIndex = currentFrameSymbols[charIndex], equalCharsIndex + 1
else
break
end
charX, charIndex = charX + 1, charIndex + 1
end
-- Group pixels that need to be drawn by background and foreground
changesCurrentFrameBackground = changes[currentFrameBackground] or {}
changes[currentFrameBackground] = changesCurrentFrameBackground
changesCurrentFrameBackgroundCurrentFrameForeground = changesCurrentFrameBackground[currentFrameForeground] or {index = 1}
changesCurrentFrameBackground[currentFrameForeground] = changesCurrentFrameBackgroundCurrentFrameForeground
changesCurrentFrameBackgroundCurrentFrameForegroundIndex = changesCurrentFrameBackgroundCurrentFrameForeground.index
changesCurrentFrameBackgroundCurrentFrameForeground[changesCurrentFrameBackgroundCurrentFrameForegroundIndex], changesCurrentFrameBackgroundCurrentFrameForegroundIndex = x, changesCurrentFrameBackgroundCurrentFrameForegroundIndex + 1
changesCurrentFrameBackgroundCurrentFrameForeground[changesCurrentFrameBackgroundCurrentFrameForegroundIndex], changesCurrentFrameBackgroundCurrentFrameForegroundIndex = y, changesCurrentFrameBackgroundCurrentFrameForegroundIndex + 1
changesCurrentFrameBackgroundCurrentFrameForeground[changesCurrentFrameBackgroundCurrentFrameForegroundIndex], changesCurrentFrameBackgroundCurrentFrameForegroundIndex = tableConcat(equalChars), changesCurrentFrameBackgroundCurrentFrameForegroundIndex + 1
x, index, changesCurrentFrameBackgroundCurrentFrameForeground.index = x + equalCharsIndex - 2, index + equalCharsIndex - 2, changesCurrentFrameBackgroundCurrentFrameForegroundIndex
end
x, index = x + 1, index + 1
end
index = index + indexStepOnEveryLine
end
-- Draw grouped pixels on screen
for background, foregrounds in pairs(changes) do
GPUProxySetBackground(background)
for foreground, pixels in pairs(foregrounds) do
if currentForeground ~= foreground then
GPUProxySetForeground(foreground)
currentForeground = foreground
end
for i = 1, #pixels, 3 do
GPUProxySet(pixels[i], pixels[i + 1], pixels[i + 2])
end
end
end
changes = nil
end
--------------------------------------------------------------------------------
return {
loadImage = loadImage,
getIndex = getIndex,
setDrawLimit = setDrawLimit,
resetDrawLimit = resetDrawLimit,
getDrawLimit = getDrawLimit,
flush = flush,
setResolution = setResolution,
bind = bind,
setGPUProxy = setGPUProxy,
getGPUProxy = getGPUProxy,
getScaledResolution = getScaledResolution,
getResolution = getResolution,
getWidth = getWidth,
getHeight = getHeight,
getCurrentFrameTables = getCurrentFrameTables,
getNewFrameTables = getNewFrameTables,
rawSet = rawSet,
rawGet = rawGet,
get = get,
set = set,
clear = clear,
copy = copy,
paste = paste,
rasterizeLine = rasterizeLine,
rasterizeEllipse = rasterizeEllipse,
rasterizePolygon = rasterizePolygon,
semiPixelRawSet = semiPixelRawSet,
semiPixelSet = semiPixelSet,
update = update,
drawRectangle = drawRectangle,
drawLine = drawLine,
drawEllipse = drawEllipse,
drawPolygon = drawPolygon,
drawText = drawText,
drawImage = drawImage,
drawFrame = drawFrame,
blur = blur,
drawSemiPixelRectangle = drawSemiPixelRectangle,
drawSemiPixelLine = drawSemiPixelLine,
drawSemiPixelEllipse = drawSemiPixelEllipse,
drawSemiPixelCurve = drawSemiPixelCurve,
}
|
local _, private = ...
-- Libs --
local oUF = private.oUF
-- RealUI --
local RealUI = private.RealUI
local db
local UnitFrames = RealUI:GetModule("UnitFrames")
UnitFrames.focus = {
create = function(self)
self.Name = self.overlay:CreateFontString(nil, "OVERLAY")
self.Name:SetPoint("BOTTOMLEFT", self, "BOTTOMRIGHT", 9, 2 - UnitFrames.layoutSize)
self.Name:SetFontObject("SystemFont_Shadow_Med1_Outline")
self:Tag(self.Name, "[realui:name]")
end,
health = {
leftVertex = 2,
rightVertex = 4,
point = "RIGHT"
},
hasCastBars = true,
}
-- Init
_G.tinsert(UnitFrames.units, function(...)
db = UnitFrames.db.profile
local focus = oUF:Spawn("focus", "RealUIFocusFrame")
focus:SetPoint("BOTTOMLEFT", "RealUIPlayerFrame", db.positions[UnitFrames.layoutSize].focus.x, db.positions[UnitFrames.layoutSize].focus.y)
end)
|
local path = (...):match("(.-)[^%.]+$")
local utils = require(path .. "utils")
---------------------------------------------------------
-- Mathematics
---------------------------------------------------------
local function round(n)
assert(n, "Required argument missing or nil")
return math.floor(n + 0.5)
end
local function magnitude(...)
local s = 0
for _, x in ipairs({...}) do
s = s + math.pow(x, 2)
end
return math.sqrt(s)
end
local function translate(point, translation)
assert(point and translation, "Required argument missing or nil")
for k, v in pairs(translation) do
point[k] = point[k] + v
end
return point
end
local function rotate_point(point, rot_point, angle)
assert(point and rot_point and angle, "Required argument missing or nil")
point = translate(point, {x=-rot_point.x, y=-rot_point.y})
local x = point.x*math.cos(angle) - point.y*math.sin(angle)
local y = point.x*math.sin(angle) + point.y*math.cos(angle)
return translate({x=x, y=y}, {x=rot_point.x, y=rot_point.y})
end
local function distance_from_point(a, b)
assert(a and b, "Required argument missing or nil")
local tbl = {}
for k, x in pairs(a) do
table.insert(tbl, a[k] - (b[k] or a[k]))
end
return magnitude(unpack(tbl))
end
local function distance_from_line(point, l1, l2)
assert(point and l1 and l2, "Required argument missing or nil")
local a = l2.y - l1.y
local b = l2.x - l1.x
local c = l2.x*l1.y - l2.y*l1.x
return (a*point.x - b*point.y + c) / magnitude(a, b)
end
local function center_of_line(a, b)
assert(a and b, "Required argument missing or nil")
local tbl = {}
local i = 0
for _, p in ipairs({a, b}) do
for k, v in pairs(p) do
if not tbl[k] then
tbl[k] = 0
i = i + 1
end
tbl[k] = tbl[k] + v
end
end
for k, v in pairs(tbl) do
tbl[k] = tbl[k] / i
end
return tbl
end
local function interpolate(i, start, ending)
assert(i and start and ending, "Required argument missing or nil")
return start + i*(ending - start)
end
---------------------------------------------------------
-- Transitions
---------------------------------------------------------
local transition = {}
transition.ease_in = function(x, exp, from, to)
assert(x, "Required argument missing or nil")
local from = from or 0
local to = to or 1
local exp = exp or 2
return interpolate(1 - math.sqrt(1 - math.pow(x, exp)), from, to)
end
transition.ease_in_out = function(x, exp, from, to)
assert(x, "Required argument missing or nil")
local from = from or 0
local to = to or 1
local exp = exp or 2
return interpolate(math.pow(x, exp) / (math.pow(x, exp) + math.pow(1 - x, exp)), from, to)
end
---------------------------------------------------------
-- Return
---------------------------------------------------------
return {
["transition"] = transition,
["magnitude"] = magnitude,
["round"] = round,
["distance_from_point"] = distance_from_point,
["distance_from_line"] = distance_from_line,
["center_of_line"] = center_of_line,
["rotate_point"] = rotate_point,
["interpolate"] = interpolate,
}
|
-- 通用组件
require "Common/define"
require "Common/functions"
require "Logic/CtrlManager"
require "Logic/MessageWatcher"
-- 控制器
CtrlNames = {
Prompt = "PromptCtrl",
Message = "MessageCtrl"
}
-- View
PanelNames = {
"PromptPanel",
"MessagePanel",
}
|
--! file: player.lua
--
-- Player file: Class to define the little hand of the player.
--
Player = Object:extend() -- #FIXME: #10 Implement the player little hand completely.
function Player:new(x, y)
self.type = "player"
self.image = love.graphics.newImage("assets/dummy_hand_open.png")
self.x = x-10
self.y = y
self.orginal_position_x = x
self.orginal_position_y = y
self.width = self.image:getWidth()
self.height = self.image:getHeight()
self.scale_x = GLOBAL.SCALE.FACTOR * 0.65
self.scale_y = GLOBAL.SCALE.FACTOR * 0.65
self.scaled_width = self.width * self.scale_x
self.scaled_height = self.height * self.scale_y
self.offset_x = (self.image:getWidth() / 2)
self.offset_y = (self.image:getHeight() / 2)
self.collision_shape = {
mode = "line",
x = self.x - (self.scaled_width/2),
y = self.y,
width = self.scaled_width,
height = self.scaled_height,
color = {255,0,0}
}
self.handling = {
grabbing = false,
grab_image = love.graphics.newImage("assets/dummy_hand_close.png"),
distx = 0,
disty = 0
}
end
function Player:is_grabbing()
is_grabbing = self.handling.grabbing
end
function Player:mouse_pressed(x, y, button, istouch)
if button == 1 then
self.handling.grabbing = true
end
--if button == 1
-- and x > self.collision_shape.x
-- and x < self.collision_shape.x + self.scaled_width
-- and y > self.collision_shape.y
-- and y < self.collision_shape.y + self.scaled_height then
-- self.handling.distx = x - self.x
-- self.handling.disty = y - self.y
--end
end
function Player:mouse_released(x, y, button)
if button == 1 then
self.handling.grabbing = false
end
end
function Player:update(dt)
self.x = love.mouse.getX()
self.y = love.mouse.getY()
self.collision_shape.x = self.x - (self.scaled_width/2)
self.collision_shape.y = self.y
end
function Player:draw(x, y)
if self.handling.grabbing then
love.graphics.draw(self.handling.grab_image, self.x-10, self.y-55, 0, self.scale_x, self.scale_y, self.offset_x)
else
love.graphics.draw(self.image, self.x-10, self.y-55, 0, self.scale_x, self.scale_y, self.offset_x)
end
if self.collision_shape.show then
love.graphics.setColor(self.collision_shape.color)
love.graphics.rectangle(self.collision_shape.mode, self.collision_shape.x, self.collision_shape.y, self.collision_shape.width, self.collision_shape.height)
love.graphics.setColor(GLOBAL.SCREEN.COLOR_RESET)
end
end
|
--[[
The MIT License
Copyright (C) 2021 Tony Wang
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
require 'libs/beCompilers/beCompilers'
-- Helper functions.
local function merge(first, second)
if first == nil and second == nil then
return nil
end
local result = { }
if first then
for k, v in pairs(first) do
result[k] = v
end
end
if second then
for k, v in pairs(second) do
result[k] = v
end
end
return result
end
-- Compile the particle system implementation.
local chunk, env = beCompilers.compileLuax(
-- Implementation source.
-- Credits:
-- pico-ps created by Maxwell Dexter
-- https://github.com/MaxwellDexter/pico-ps
-- https://maxwelldexter.itch.io/pico-ps
'libs/beParticles/pico-ps.lua',
-- Custom environment.
{
print = print, warn = warn, error = error,
ipairs = ipairs, pairs = pairs,
getmetatable = getmetatable, setmetatable = setmetatable,
math = math, table = table,
Color = Color,
DateTime = DateTime,
circ = circ, rect = rect, spr = spr
}
)
-- Inject the particle system to global scope.
chunk()
--[[
Exporting.
]]
beParticles = merge(
{
version = '1.0.1',
setup = function ()
local now = DateTime.toSeconds(DateTime.ticks())
env.prev_time = now
env.delta_time = now - env.prev_time
end
},
env
)
|
mapQuests = require "lib/mapQuests"
mapEffects = require "lib/mapEffects"
quest = target.get_quest(mapQuests.getID("KoCTut"))
if quest.record_ex_key("helper") == "" then
quest.update_ex("helper", "clear")
target.hire_tutor(true)
target.tutor_message("Welcome to Maple World! I'm Mimo. I'm in charge of guiding you until you reach Lv. 10 and become a Knight-In-Training. Double-click for further information!", 200, 7000)
end
|
include('shared.lua')
SWEP.DrawAmmo = true
SWEP.DrawWeaponInfoBox = true
SWEP.BounceWeaponIcon = true
SWEP.SwayScale = 1 -- The scale of the viewmodel sway
SWEP.BobScale = 0.5 -- The scale of the viewmodel bob
SWEP.IsACF = true
function SWEP:Initialize()
if not IsValid(self.Owner) then return end
self:SetWeaponHoldType( self.HoldType )
self.defaultFOV = self.Owner:GetFOV()
self.lastaccuracy = self.MaxInaccuracy
self.wasReloading = false
self.reloadBegin = 0
self.lastHUDDraw = CurTime()
self.timeDiff = 0
self.lastServRecv = CurTime() - 0.1
self.lastServInacc = self.MaxInaccuracy
self.curServInacc = self.MaxInaccuracy
self.curVisInacc = self.MaxInaccuracy
self.smoothFactor = 0
self.fromPos = Vector(0,0,0)
self.toPos = Vector(0,0,0)
self.fromAng = Angle(0,0,0)
self.toAng = Angle(0,0,0)
self.zoomProgress = 1
self:InitBulletData()
end
function SWEP:ZoomThink()
local zoomed = self:GetNetworkedBool("Zoomed")
//Msg(zoomed)
if zoomed != self.Zoomed then
//print(zoomed, "has changed!!11")
self.Zoomed = zoomed
if zoomed then
self.fromPos = self.curPos or Vector(0,0,0)
self.toPos = ACF.SWEP.IronSights and (self.IronSightsPos or Vector(0,0,0)) or (self.ZoomPos or Vector(2, 2, 2))
if ACF.SWEP.HalveSightPos then self.toPos = self.toPos / 2 end
self.fromAng = self.curAng or Angle(0,0,0)
self.toAng = self.IronSightsAng or Angle(0,0,0)
self.zoomProgress = 0
else
self.fromPos = self.curPos or Vector(0,0,0)
self.toPos = self.UnzoomedPos or Vector(0,0,0)
self.fromAng = self.curAng or Angle(0,0,0)
self.toAng = self.UnzoomedAng or Angle(0,0,0)
self.zoomProgress = 0
end
if self.Zoomed then
self.cachedmin = self.cachedmin or self.MinInaccuracy
self.cacheddecayin = self.cacheddecayin or self.InaccuracyDecay
self.cacheddecayac = self.cacheddecayac or self.AccuracyDecay
self.MinInaccuracy = self.MinInaccuracy * self.ZoomInaccuracyMod
self.InaccuracyDecay = self.InaccuracyDecay * self.ZoomDecayMod
self.AccuracyDecay = self.AccuracyDecay * self.ZoomDecayMod
else
if self.cachedmin then
self.MinInaccuracy = self.cachedmin
self.InaccuracyDecay = self.cacheddecayin
self.AccuracyDecay = self.cacheddecayac
self.cachedmin = nil
self.cacheddecayin = nil
self.cacheddecayac = nil
end
end
end
end
function SWEP:AdjustMouseSensitivity()
if not self.defaultFOV then self.defaultFOV = self.Owner:GetFOV() end
if self.HasZoom and self.Zoomed then
return self.ZoomFOV / self.defaultFOV
end
return 1
end
function SWEP:DrawScope()
if not (self.Zoomed and self.HasScope) then return false end
local scrw = ScrW()
local scrw2 = ScrW() / 2
local scrh = ScrH()
local scrh2 = ScrH() / 2
local traceargs = util.GetPlayerTrace(LocalPlayer())
traceargs.filter = {self.Owner, self.Owner:GetVehicle() or nil}
local trace = util.TraceLine(traceargs)
local scrpos = trace.HitPos:ToScreen()
local devx = scrw2 - scrpos.x - 0.5
local devy = scrh2 - scrpos.y - 0.5
surface.SetDrawColor(0, 0, 0, 255)
local rectsides = ((scrw - scrh) / 2) * 0.7
surface.SetDrawColor(0, 0, 0, 255)
local baselen = rectsides + scrw * 0.18
local basewide = scrh * 0.01
local basewide2 = basewide * 2
local centersep = scrh * 0.02
surface.DrawRect(0 - devx, scrh2 - basewide - devy, baselen, basewide2)
surface.DrawRect(scrw - baselen - devx, scrh2 - basewide - devy, baselen, basewide2)
surface.DrawRect(scrw2 - basewide - devx, scrh - (baselen - rectsides*1.5) - devy, basewide2, (baselen - rectsides*1.5))
surface.DrawLine(0 - devx, scrh2 - devy, scrw2 - centersep - devx, scrh2 - devy)
surface.DrawLine(scrw2 + centersep - devx, scrh2 - devy, scrw - devx, scrh2 - devy)
surface.DrawLine(scrw2 - devx, scrh - devy, scrw2 - devx, scrh2 + centersep - devy)
surface.SetDrawColor(0, 0, 0, 255)
surface.SetMaterial(Material("gmod/scope"))
surface.DrawTexturedRect(rectsides - devx, 0 - devy, scrw - rectsides * 2, scrh)
surface.DrawRect(0, 0, rectsides + 2 - devx, scrh)
surface.DrawRect(scrw - rectsides - 2 - devx, 0, rectsides + 2 + devx, scrh)
if math.abs(devy) >= 0.5 then
surface.DrawRect(rectsides + 2 - devx, 0, scrw - rectsides * 2, -devy)
surface.DrawRect(rectsides + 2 - devx, scrh - devy, scrw - rectsides * 2, devy)
end
return true
end
function SWEP:DrawReticule(screenpos, aimRadius, fillFraction, colourFade)
if not CLIENT then return end
ACF.SWEP.DrawReticule(self, screenpos, aimRadius, fillFraction, colourFade)
end
local function GetCurrentACFSWEP()
if not (LocalPlayer():Alive() or LocalPlayer():InVehicle()) then return end
local self = LocalPlayer():GetActiveWeapon()
if not self.IsACF then return end
if not (self.Owner:Alive() or self.Owner:InVehicle()) then return end
return self
end
hook.Add("HUDPaint", "ACFWep_HUD", function()
local self = GetCurrentACFSWEP()
if not self then return end
if not (self.Owner:Alive() or self.Owner:InVehicle()) then return end
local drawcircle = true
local scrpos
if drawcircle then
local traceargs = util.GetPlayerTrace(LocalPlayer())
traceargs.filter = {self.Owner, self.Owner:GetVehicle() or nil}
local trace = util.TraceLine(traceargs)
scrpos = trace.HitPos:ToScreen()
end
local isReloading = self.Weapon:GetNetworkedBool( "reloading", false )
local servstam = self.Weapon:GetNetworkedFloat("ServerStam", 0)
local servinacc = self.Weapon:GetNetworkedFloat("ServerInacc", self.MaxInaccuracy)
if servinacc ~= self.curServInacc then
self.timeDiff = CurTime() - self.lastServRecv
self.lastServRecv = CurTime()
self.lastServInacc = self.curServInacc
self.curServInacc = servinacc
self.curVisInacc = self.lastServInacc
self.smoothFactor = (self.curServInacc - self.lastServInacc) * self.timeDiff
end
self.curVisInacc = math.Clamp(self.curVisInacc + self.smoothFactor, math.min(self.lastServInacc, self.curServInacc), math.max(self.lastServInacc, self.curServInacc))
local aimRadius = drawcircle and ScrW() / 2 * self.curVisInacc / self.Owner:GetFOV()
local fractLeft = 1
if self.PressedTime then
local duration = CurTime() - self.PressedTime
fractLeft = math.Clamp(duration, 0, self.ChargeTime) / self.ChargeTime
end
if isReloading then
if not self.wasReloading then
self.reloadBegin = CurTime()
self.lastReloadTime = self.ReloadByRound and (self.ReloadTime * (self.Primary.ClipSize - self:Clip1()) + self.ReloadTime) or self.ReloadTime
end
if drawcircle then
fractLeft = math.Clamp(self.lastReloadTime - (CurTime() - self.reloadBegin), 0, self.lastReloadTime) / self.lastReloadTime
end
end
self.wasReloading = isReloading
if drawcircle then
self:DrawReticule(scrpos, aimRadius, fractLeft, servstam)
end
self:DrawScope()
self.lastHUDDraw = CurTime()
end)
function SWEP:ZoomTween(t)
local s = 1.7
if t < 0.5 then
t = t * 1.525
--s = s * 1.525
--return 0.5*(t*t*((s+1)*t - s))
return -math.cos(t * math.pi / 2) + 1
else
t = t * 2
t = t - 2
s = s * 1.525
return 0.5*(t*t*((s+1)*t+ s) + 2)
end
end
local lissax = 3
local lissay = 4
local lissasep = math.pi / 2
function SWEP:GetViewModelPosition( pos, ang )
if not CLIENT then return pos, ang end
self.lastViewMod = self.lastViewMod or RealTime()
self.lastaccuracy = self.lastaccuracy or self.MaxInaccuracy
local time = CurTime() * 0.33
local accuracy = (self.Inaccuracy * 0.02 + self.lastaccuracy * 0.98) * 0.25
ang = self.Owner:GetAimVector():Angle()
local trace = self.Owner:GetEyeTrace()
local x = accuracy * math.sin(lissax * time + lissasep + time*0.01)
local y = accuracy * math.sin(lissay * time)
if self:GetNetworkedBool("Zoomed") then
y = y / 2 + accuracy
else
end
local sway = Angle(y, x, 0)
self.lastaccuracy = accuracy * 4
local tween = self:ZoomTween(self.zoomProgress)
self.curPos = LerpVector(tween, self.fromPos, self.toPos)
local modpos = pos + self.curPos
self.curAng = LerpAngle(tween, self.fromAng, self.toAng)
sway = sway + self.curAng
local pos2, aim2 = LocalToWorld(self.curPos, sway, pos, ang)
self.zoomProgress = math.Clamp(self.zoomProgress + (RealTime() - self.lastViewMod) * 1 / (self.ZoomTime or 1), 0, 1)
self.lastViewMod = RealTime()
return pos2, aim2
end
hook.Add( "PreRender", "ACFWep_PreRender", function()
local self = GetCurrentACFSWEP()
if self then
local curTime = SysTime()
local axis = self.RecoilAxis
if axis then
local axisLength = axis:Length()
if axisLength < 0.001 then
self.RecoilAxis = Vector(0,0,0)
else
local recoilDamping = self.RecoilDamping * 18000
local timeDiff = curTime - (self.lastPreRender or curTime)
local decayTime = axisLength / recoilDamping
local timeDiff = math.min(timeDiff, decayTime)
local accumulatedRecoil = axisLength * timeDiff - (recoilDamping * timeDiff * timeDiff) / 2
local newAxisLength = -recoilDamping * timeDiff + axisLength
local ply = LocalPlayer()
local eye = ply:EyeAngles()
local roll = eye.r
local normAxis = axis:GetNormalized()
eye:RotateAroundAxis(normAxis, accumulatedRecoil)
eye.r = roll
ply:SetEyeAngles(eye)
self.RecoilAxis = normAxis * newAxisLength
end
end
self.lastPreRender = curTime
end
end )
|
Locales['en'] = {
['by_default'] = 'Stock',
['installed'] = 'Instalado!',
['already_own'] = 'Já és o dono: ',
['not_enough_money'] = 'Não tens dinheiro suficiente!',
['purchased'] = 'Comprado!',
['press_custom'] = 'Pressionar E para personalizar o veículo!',
['level'] = 'Nível ',
['neon'] = 'Neon',
['blip_name'] = 'Oficina Automóvel!',
-- License Plates
['blue_on_white_1'] = 'Azul no Branco 1',
['yellow_on_black'] = 'Amarelo no Preto',
['yellow_blue'] = 'Amarelo no Azul',
['blue_on_white_2'] = 'Azul no Branco 2',
['blue_on_white_3'] = 'Azul no Branco 3',
-- Upgrades
['upgrades'] = 'Performance',
['engine'] = 'Motor',
['brakes'] = 'Travões',
['transmission'] = 'Transmissão',
['suspension'] = 'Suspensão',
['armor'] = 'Armadura',
['turbo'] = 'Turbo',
['no_turbo'] = 'Sem Turbo',
-- Cosmetics
['cosmetics'] = 'Cósméticos',
-- Body Parts
['bodyparts'] = 'Cósmeticos',
['leftfender'] = 'Guarda-Lamas Esquerdo',
['rightfender'] = 'Guarda-Lamas Direito',
['spoilers'] = 'Aileron',
['sideskirt'] = 'Saias Laterais',
['cage'] = 'Jaula',
['hood'] = 'Capô',
['grille'] = 'Grelha',
['rearbumper'] = 'Pára-choque Traseiro',
['frontbumper'] = 'Pára-choque Dianteiro',
['exhaust'] = 'Tubo de Escape',
['roof'] = 'Teto',
-- Paint
['respray'] = 'Pintura',
['primary'] = 'Pintura Primária',
['secondary'] = 'Pintura Secundária',
['pearlescent'] = 'Perolado',
-- Misc
['headlights'] = 'Faróis',
['licenseplates'] = 'Matrícula',
['windowtint'] = 'Pintura dos Vidros!',
['horns'] = 'Buzinas',
-- Neon
['neons'] = 'Neons',
-- Wheels
['wheels'] = 'Rodas',
['tiresmoke'] = 'Fumo dos Pneus',
['wheel_type'] = 'Tipo de Roda',
['wheel_color'] = 'Cor da Roda',
['sport'] = 'Desportivo',
['muscle'] = 'Muscle',
['lowrider'] = 'Lowrider',
['suv'] = 'SUV',
['allterrain'] = 'Todo-O-Terreno',
['tuning'] = 'Tuning',
['motorcycle'] = 'Moto',
['highend'] = 'Exótico',
['modplateholder'] = 'Chapa - Traseira',
['modvanityplate'] = 'Chapa - Dianteira',
['interior'] = 'Interior',
['trim'] = 'Detalhes',
['dashboard'] = 'Tablier',
['speedometer'] = 'Contador de Velocidade',
['door_speakers'] = 'Colunas das Portas',
['seats'] = 'Assentos',
['steering_wheel'] = 'Volante',
['gear_lever'] = 'Nível de Equipamento',
['quarter_deck'] = 'Tombadilho',
['speakers'] = 'Colunas',
['trunk'] = 'Mala',
['hydraulic'] = 'Hidrálico',
['engine_block'] = 'Bloco do Motor',
['air_filter'] = 'Filtro do Ar',
['struts'] = 'Suportes',
['arch_cover'] = 'Cobertura do Arco',
['aerials'] = 'Aerodinamica',
['wings'] = 'Canards',
['fuel_tank'] = 'Tanque de Combustível',
['windows'] = 'Janelas',
['stickers'] = 'AutoColantes',
['leftNeon'] = 'Neon Lateral Esquerda',
['frontNeon'] = 'Neon Dianteira',
['rightNeon'] = 'Neon Lateral Direita',
['backNeon'] = 'Neon Traseira',
['metallic'] = 'Metálico',
['matte'] = 'Matte',
['util'] = 'Útil',
['worn'] = 'Gasto',
['brushed'] = 'Escovado',
['others'] = 'Outros',
['paintPart'] = 'Parte a Pintar',
['paintType'] = 'Tipo Pintura',
['tireSmoke'] = 'Fumo Pneus',
['tireSmokeColor'] = 'Cor Fumo Pneus',
['xenonColor'] = 'Cor Xénon',
['windowtint'] = 'Pelicula Vidros',
['personalize'] = 'Personalizar',
['primaryPaintFinish'] = 'Acabamento Primário',
['secondaryPaintFinish'] = 'Acabamento Secundário',
['noStock'] = 'Sem Stock!!',
['noStockTxt'] = 'Não Existe Stock!!',
['cart'] = 'Lista de Compras!',
['cartEmpty'] = 'Sem Items!!',
['cartEmptyTxt'] = 'Não Existem Items no Carrinho!!',
['finishPurchase'] = 'Passar Fatura!',
['shopProfit'] = 'Lucro para a Empresa:',
['shopProfitTotal'] = 'Valor Total Lucro:',
['shopProfitTotalTxt'] = 'Valor a ser Retirado da Conta da Empresa:',
['shopCosts'] = 'Custo para a Empresa:',
['shopCostsTxt'] = 'Valor a ser Retirado da Empresa:',
['valueTotal'] = 'Valor a Receber:',
['valueTotalPay'] = 'Valor a Pagar pelo Cliente:',
['primaryRgbPaint'] = 'Primário Personalizado',
['secondaryRgbPaint'] = 'Secundário Personalizado',
}
|
function find_entity(id)
for ii = 0,#df.global.world.entities.all - 1 do
if df.global.world.entities.all[ii].id == id then
return ii
end
end
return -1
end
function create_nemesis(unit)
hist_fig = df.historical_figure.find(unit.hist_figure_id)
civ_index = find_entity(df.global.ui.main.fortress_entity.entity_links[0].target)
new_nemesis_id = df.global.nemesis_next_id
new_nemesis = df.nemesis_record:new()
new_nemesis.id = new_nemesis_id
new_nemesis.figure = hist_fig
new_nemesis.unit = unit
new_nemesis.unit_id = unit.id
new_nemesis.save_file_id = df.global.world.entities.all[civ_index].save_file_id
new_nemesis.member_idx = df.global.world.entities.all[civ_index].next_member_idx
--group_leader_id = -1
new_nemesis.unk10, new_nemesis.unk11, new_nemesis.unk12 = -1, -1, -1
df.global.world.entities.all[civ_index].next_member_idx = df.global.world.entities.all[civ_index].next_member_idx + 1
df.global.world.nemesis.all:insert('#', new_nemesis)
df.global.nemesis_next_id = df.global.nemesis_next_id + 1
nemesis_link = df.general_ref_is_nemesisst:new()
nemesis_link.nemesis_id = new_nemesis_id
unit.general_refs:insert('#', nemesis_link)
new_nemesis_loc = df.global.world.nemesis.all[#df.global.world.nemesis.all - 1]
df.global.ui.main.fortress_entity.nemesis_ids:insert('#', new_nemesis_id)
df.global.ui.main.fortress_entity.nemesis:insert('#', new_nemesis_loc)
df.global.world.entities.all[civ_index].nemesis_ids:insert('#', new_nemesis_id)
df.global.world.entities.all[civ_index].nemesis:insert('#', new_nemesis_loc)
end
count = 0
for _,unit in pairs(df.global.world.units.active) do
if dfhack.units.isCitizen(unit) and unit.flags1.important_historical_figure then
nemesis = false
for _, ref in pairs (unit.general_refs) do
if df.general_ref_is_nemesisst:is_instance(ref) then
nemesis = true
end
end
if not nemesis then
create_nemesis(unit)
count = count + 1
end
end
end
if count > 0 then
print( string.format('fixed %i citizens without nemesis entries',count) )
end
|
local DCT_specCoolDownC = 0
local DCT_specTargetBuffFadeC = 0
function DCT_Opspec_OnShow2()
DCT_Opex_SetSaveP(DCT_Player)
DCT_OptionsFrame_Load(DCT_SpecCfg_Event2)
DCTSpecOptionBuffListEdit:SetText("")
end
function DCT_Opspec_TargetBuffListDDC_Initialize()
local k,v
local specbuffP = DCT_Get("DCT_SPECTARGETBUFF")
if not specbuffP then return;end
DCT_specTargetBuffC = 0
for k,v in pairs(specbuffP) do
info = {
text = k;
func = DCT_Opspec_TargetBuffListDDC_OnClick;
};
UIDropDownMenu_AddButton(info);
DCT_specTargetBuffC = DCT_specTargetBuffC + 1
end
if DCT_specTargetBuffC == 0 then
info = {
text = "none";
func = DCT_Opspec_TargetBuffListDDC_OnClick;
};
UIDropDownMenu_AddButton(info);
end
end
function DCT_Opspec_TargetBuffListDDC_OnShow(self)
local k,v
local i = 1
local specbuffP = DCT_Get("DCT_SPECTARGETBUFF")
UIDropDownMenu_Initialize(self, DCT_Opspec_TargetBuffListDDC_Initialize)
UIDropDownMenu_SetSelectedID(self, 1)
UIDropDownMenu_SetWidth(self,120)
for k,v in pairs(specbuffP) do
if i == 1 then
UIDropDownMenu_SetSelectedName(DCTSpecOption2TargetBuffListDDC, k)
end
i = i + 1
end
getglobal(self:GetName().."Label"):SetText(DCT_TEXT_OPSPEC_BUFFLISTDDC)
end
function DCT_Opspec_TargetBuffListDDC_OnClick(self)
local thisID = self:GetID()
UIDropDownMenu_SetSelectedID(DCTSpecOption2TargetBuffListDDC, thisID)
local thisText = self:GetText()
UIDropDownMenu_SetSelectedName(DCTSpecOption2TargetBuffListDDC, thisText)
end
function DCT_Opspec_TargetBuffDeleteClick()
local name = UIDropDownMenu_GetSelectedName(DCTSpecOption2TargetBuffListDDC)
if name == "none" then return;end
local specbuffP = DCT_Get("DCT_SPECTARGETBUFF")
if specbuffP[name] then
specbuffP[name] = nil
DCTSpecOption2:Hide()
DCTSpecOption2:Show()
end
end
function DCT_Opspec_TargetBuffAddClick()
if DCT_specTargetBuffC >= 30 then
DCT_Debug(DCT_TEXT_OPSPEC_ADD_ERROR3)
return
end
local name = DCTSpecOption2TargetBuffEdit:GetText()
if string.len(name) < 1 then
DCT_Debug(DCT_TEXT_OPSPEC_ADD_ERROR1)
return
end
local specbuffP = DCT_Get("DCT_SPECTARGETBUFF")
if specbuffP[name] then
DCT_Debug(DCT_TEXT_OPSPEC_ADD_ERROR2)
return
else
specbuffP[name] = 1
DCT_Debug(DCT_TEXT_OPSPEC_ADD_SUCCEED)
DCTSpecOption2:Hide()
DCTSpecOption2:Show()
end
end
function DCT_Opspec_TargetBuffFadeListDDC_Initialize()
local k,v
local specbuffP = DCT_Get("DCT_SPECTARGETBUFFFADE")
if not specbuffP then return;end
DCT_specTargetBuffFadeC = 0
for k,v in pairs(specbuffP) do
info = {
text = k;
func = DCT_Opspec_TargetBuffFadeListDDC_OnClick;
};
UIDropDownMenu_AddButton(info);
DCT_specTargetBuffFadeC = DCT_specTargetBuffFadeC + 1
end
if DCT_specTargetBuffFadeC == 0 then
info = {
text = "none";
func = DCT_Opspec_TargetBuffFadeListDDC_OnClick;
};
UIDropDownMenu_AddButton(info);
end
end
function DCT_Opspec_TargetBuffFadeListDDC_OnShow(self)
local k,v
local i = 1
local specbuffP = DCT_Get("DCT_SPECTARGETBUFFFADE")
UIDropDownMenu_Initialize(self, DCT_Opspec_TargetBuffFadeListDDC_Initialize)
UIDropDownMenu_SetSelectedID(self, 1)
UIDropDownMenu_SetWidth(self,120)
for k,v in pairs(specbuffP) do
if i == 1 then
UIDropDownMenu_SetSelectedName(DCTSpecOption2TargetBuffFadeListDDC, k)
end
i = i + 1
end
getglobal(self:GetName().."Label"):SetText(DCT_TEXT_OPSPEC_BUFFLISTDDC)
end
function DCT_Opspec_TargetBuffFadeListDDC_OnClick(self)
local thisID = self:GetID()
UIDropDownMenu_SetSelectedID(DCTSpecOption2TargetBuffFadeListDDC, thisID)
local thisText = self:GetText()
UIDropDownMenu_SetSelectedName(DCTSpecOption2TargetBuffFadeListDDC, thisText)
end
function DCT_Opspec_TargetBuffFadeDeleteClick()
local name = UIDropDownMenu_GetSelectedName(DCTSpecOption2TargetBuffFadeListDDC)
if name == "none" then return;end
local specbuffP = DCT_Get("DCT_SPECTARGETBUFFFADE")
if specbuffP[name] then
specbuffP[name] = nil
DCTSpecOption2:Hide()
DCTSpecOption2:Show()
end
end
function DCT_Opspec_TargetBuffFadeAddClick()
if DCT_specTargetBuffFadeC >= 30 then
DCT_Debug(DCT_TEXT_OPSPEC_ADD_ERROR3)
return
end
local name = DCTSpecOption2TargetBuffFadeEdit:GetText()
if string.len(name) < 1 then
DCT_Debug(DCT_TEXT_OPSPEC_ADD_ERROR1)
return
end
local specbuffP = DCT_Get("DCT_SPECTARGETBUFFFADE")
if specbuffP[name] then
DCT_Debug(DCT_TEXT_OPSPEC_ADD_ERROR2)
return
else
specbuffP[name] = 1
DCT_Debug(DCT_TEXT_OPSPEC_ADD_SUCCEED)
DCTSpecOption2:Hide()
DCTSpecOption2:Show()
end
end
|
_mod = {}
local modname = minetest.get_current_modname()
_mod.modname = modname
local modpath = minetest.get_modpath(modname).."/"
_mod.modpath = modpath
local basename = "com.github.thetaepsilon.minetest.libmt_node_network"
_mod.base = basename
dofile(modpath.."main.lua")
local export = dofile(modpath.."export.lua")
modns.register(basename, export)
_mod = nil
|
--[[
Luci statistics - df plugin diagram definition
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: df.lua 2274 2008-06-03 23:15:16Z jow $
]]--
module("luci.statistics.rrdtool.definitions.disk", package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
return {
{
title = "%H: Disk I/O operations on %pi",
vlabel = "Operations/s",
number_format = "%5.1lf%sOp/s",
data = {
types = { "disk_ops" },
sources = {
disk_ops = { "read", "write" },
},
options = {
disk_ops__read = {
title = "Reads",
color = "00ff00",
flip = false
},
disk_ops__write = {
title = "Writes",
color = "ff0000",
flip = true
}
}
}
},
{
title = "%H: Disk I/O bandwidth on %pi",
vlabel = "Bytes/s",
number_format = "%5.1lf%sB/s",
detail = true,
data = {
types = { "disk_octets" },
sources = {
disk_octets = { "read", "write" }
},
options = {
disk_octets__read = {
title = "Read",
color = "00ff00",
flip = false
},
disk_octets__write = {
title = "Write",
color = "ff0000",
flip = true
}
}
}
}
}
end
|
files {
-- "Vertex.fs",
"Buffer.fs",
"Shader.fs",
"GL_Texture.fs",
"GL_Material.fs",
"GL_Mesh.fs", -- workaround naming conflict. It's not allowed to have multiple files with the same name!
"SourceOrder.lua"
}
|
function createTrainerConversationTemplate(templateName, typeOfTrainer)
trainerConvoTemplate = ConvoTemplate:new {
initialScreen = "",
templateType = "Lua",
luaClassHandler = "trainerConvHandler",
screens = {}
}
trainerType = ConvoScreen:new {
id = "trainerType",
leftDialog = "trainerType", -- Storage for the type of trainer, so it can be pulled in the convo handler.
stopConversation = "false",
options = {
{ "trainerType" , typeOfTrainer }
}
}
trainerConvoTemplate:addScreen(trainerType);
intro = ConvoScreen:new {
id = "intro",
leftDialog = "",
stopConversation = "false",
options = {}
}
trainerConvoTemplate:addScreen(intro);
trainer_unknown = ConvoScreen:new {
id = "trainer_unknown",
leftDialog = "@skill_teacher:trainer_unknown",
stopConversation = "true",
options = {}
}
trainerConvoTemplate:addScreen(trainer_unknown);
topped_out = ConvoScreen:new {
id = "topped_out",
leftDialog = "",
stopConversation = "true",
options = {}
}
trainerConvoTemplate:addScreen(topped_out);
no_qualify = ConvoScreen:new {
id = "no_qualify",
leftDialog = "",
stopConversation = "true",
options = {}
}
trainerConvoTemplate:addScreen(no_qualify);
msg2_1 = ConvoScreen:new {
id = "msg2_1",
leftDialog = "",
stopConversation = "false",
options = {}
}
trainerConvoTemplate:addScreen(msg2_1);
msg2_2 = ConvoScreen:new {
id = "msg2_2",
leftDialog = "",
stopConversation = "false",
options = {}
}
trainerConvoTemplate:addScreen(msg2_2);
learn = ConvoScreen:new {
id = "learn",
leftDialog = "",
stopConversation = "false",
options = {}
}
trainerConvoTemplate:addScreen(learn);
confirm_learn = ConvoScreen:new {
id = "confirm_learn",
leftDialog = "",
stopConversation = "false",
options = {}
}
trainerConvoTemplate:addScreen(confirm_learn);
cancel_learn = ConvoScreen:new {
id = "cancel_learn",
leftDialog = "",
stopConversation = "false",
options = {
{"@skill_teacher:opt1_1", "msg2_1"}, -- I'm interested in learning a skill.
{"@skill_teacher:opt1_2", "msg2_2"} -- What skills will I be able to learn next?
}
}
trainerConvoTemplate:addScreen(cancel_learn);
info = ConvoScreen:new {
id = "info",
leftDialog = "",
stopConversation = "false",
options = {}
}
trainerConvoTemplate:addScreen(info);
nsf_skill_points = ConvoScreen:new {
id = "nsf_skill_points",
leftDialog = "",
stopConversation = "false",
options = {}
}
trainerConvoTemplate:addScreen(nsf_skill_points);
addConversationTemplate(templateName, trainerConvoTemplate);
end
createTrainerConversationTemplate("artisanTrainerConvoTemplate", "trainer_artisan")
createTrainerConversationTemplate("brawlerTrainerConvoTemplate", "trainer_brawler")
createTrainerConversationTemplate("entertainerTrainerConvoTemplate", "trainer_entertainer")
createTrainerConversationTemplate("marksmanTrainerConvoTemplate", "trainer_marksman")
createTrainerConversationTemplate("medicTrainerConvoTemplate", "trainer_medic")
createTrainerConversationTemplate("scoutTrainerConvoTemplate", "trainer_scout")
createTrainerConversationTemplate("1hswordTrainerConvoTemplate", "trainer_1hsword")
createTrainerConversationTemplate("2hswordTrainerConvoTemplate", "trainer_2hsword")
createTrainerConversationTemplate("architectTrainerConvoTemplate", "trainer_architect")
createTrainerConversationTemplate("armorsmithTrainerConvoTemplate", "trainer_armorsmith")
createTrainerConversationTemplate("bioengineerTrainerConvoTemplate", "trainer_bioengineer")
createTrainerConversationTemplate("bountyhunterTrainerConvoTemplate", "trainer_bountyhunter")
createTrainerConversationTemplate("carbineTrainerConvoTemplate", "trainer_carbine")
createTrainerConversationTemplate("chefTrainerConvoTemplate", "trainer_chef")
createTrainerConversationTemplate("combatmedicTrainerConvoTemplate", "trainer_combatmedic")
createTrainerConversationTemplate("commandoTrainerConvoTemplate", "trainer_commando")
createTrainerConversationTemplate("creaturehandlerTrainerConvoTemplate", "trainer_creaturehandler")
createTrainerConversationTemplate("dancerTrainerConvoTemplate", "trainer_dancer")
createTrainerConversationTemplate("doctorTrainerConvoTemplate", "trainer_doctor")
createTrainerConversationTemplate("droidengineerTrainerConvoTemplate", "trainer_droidengineer")
createTrainerConversationTemplate("imagedesignerTrainerConvoTemplate", "trainer_imagedesigner")
createTrainerConversationTemplate("merchantTrainerConvoTemplate", "trainer_merchant")
createTrainerConversationTemplate("musicianTrainerConvoTemplate", "trainer_musician")
createTrainerConversationTemplate("pistolTrainerConvoTemplate", "trainer_pistol")
createTrainerConversationTemplate("polearmTrainerConvoTemplate", "trainer_polearm")
createTrainerConversationTemplate("politicianTrainerConvoTemplate", "trainer_politician")
createTrainerConversationTemplate("rangerTrainerConvoTemplate", "trainer_ranger")
createTrainerConversationTemplate("riflemanTrainerConvoTemplate", "trainer_rifleman")
createTrainerConversationTemplate("shipwrightTrainerConvoTemplate", "trainer_shipwright")
createTrainerConversationTemplate("smugglerTrainerConvoTemplate", "trainer_smuggler")
createTrainerConversationTemplate("squadleaderTrainerConvoTemplate", "trainer_squadleader")
createTrainerConversationTemplate("tailorTrainerConvoTemplate", "trainer_tailor")
createTrainerConversationTemplate("unarmedTrainerConvoTemplate", "trainer_unarmed")
createTrainerConversationTemplate("weaponsmithTrainerConvoTemplate", "trainer_weaponsmith")
createTrainerConversationTemplate("mechanicTrainerConvoTemplate", "trainer_mechanic")
createTrainerConversationTemplate("spyTrainerConvoTemplate", "trainer_spy")
createTrainerConversationTemplate("meleebountyhunterTrainerConvoTemplate", "trainer_meleebountyhunter")
createTrainerConversationTemplate("gcwimperialTrainerConvoTemplate", "trainer_gcw_imperial")
createTrainerConversationTemplate("gcwrebelTrainerConvoTemplate", "trainer_gcw_rebel")
createTrainerConversationTemplate("combatjedigrayTrainerConvoTemplate", "trainer_combatjedigray")
createTrainerConversationTemplate("combatjedigrayelderTrainerConvoTemplate", "trainer_combatjedigrayelder")
createTrainerConversationTemplate("combatjedigrayelderrankTrainerConvoTemplate", "trainer_combatjedigrayelderrank")
createTrainerConversationTemplate("combatjedigrayelderrankcouncilTrainerConvoTemplate", "trainer_combatjedigrayelderrankcouncil")
createTrainerConversationTemplate("fsTrainerConvoTemplate", "trainer_fs")
createTrainerConversationTemplate("jediTrainerConvoTemplate", "trainer_jedi")
|
-- lfs_engine.lua
local M = require "lfs_message"
local F = far.Flags
local EditorGetString = editor.GetString
local EditorSetString = editor.SetString
local _lastclock
local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max
local function GetUserChoice (aTitle, s_found, s_rep)
s_found = s_found:gsub("%z", " ")
s_rep = s_rep:gsub("%z", " ")
local c = far.Message(
M.MUserChoiceReplace ..
"\n\"" .. s_found .. "\"\n" ..
M.MUserChoiceWith ..
"\n\"" .. s_rep .. "\"\n\001",
aTitle,
M.MUserChoiceButtons)
if c==1 or c==2 then
_lastclock = os.clock()
end
return c==1 and "yes" or c==2 and "all" or c==3 and "no" or "cancel"
end
local function GetReplaceFunction (aReplacePat)
if type(aReplacePat) == "function" then
return function(collect) return aReplacePat(unpack(collect, 2)) end
elseif type(aReplacePat) == "string" then
return function() return aReplacePat end
elseif type(aReplacePat) == "table" then
return function(collect, nReps)
local rep, stack = "", {}
local case, instant_case
for k,v in ipairs(aReplacePat) do
local instant_case_set = nil
---------------------------------------------------------------------
if v[1] == "case" then
if v[2] == "L" or v[2] == "U" then
stack[#stack+1], case = v[2], v[2]
elseif v[2] == "E" then
if stack[1] then table.remove(stack) end
case = stack[#stack]
else
instant_case, instant_case_set = v[2], true
end
---------------------------------------------------------------------
elseif v[1] == "counter" then
rep = rep .. ("%%0%dd"):format(v[3]):format(nReps+v[2])
---------------------------------------------------------------------
elseif v[1] == "hex" then
rep = rep .. v[2]
---------------------------------------------------------------------
elseif v[1] == "literal" or v[1] == "group" then
local c
if v[1] == "literal" then
c = v[2]
else -- group
c = collect[2 + v[2]]
assert (c ~= nil, "invalid capture index")
end
if c ~= false then -- a capture *can* equal false
if instant_case then
local d = c:sub(1,1)
rep = rep .. (instant_case=="l" and d:lower() or d:upper())
c = c:sub(2)
end
c = (case=="L" and c:lower()) or (case=="U" and c:upper()) or c
rep = rep .. c
end
---------------------------------------------------------------------
end
if not instant_case_set then
instant_case = nil
end
end
return rep
end
else
error("invalid type of replace pattern")
end
end
local function EditorSelect (b)
editor.Select(b.BlockType, b.StartLine, b.StartPos, b.EndPos - b.StartPos + 1,
b.EndLine - b.StartLine + 1)
end
local function CheckUserBreak (aTitle)
return (win.ExtractKey() == "ESCAPE") and
1 == far.Message(M.MUsrBrkPrompt, aTitle, ";YesNo", "w")
end
-- This function replaces the old 9-line function.
-- The reason for applying a new, much more complicated algorithm is that
-- the old algorithm has unacceptably poor performance on long subjects.
local function find_back (s, regex, init)
local out = regex:ufind(s, 1)
if out == nil or out[2]>=init then return nil end
local BEST = 1
local stage = 1
local MIN, MAX = 2, init
local start = ceil((MIN+MAX)/2)
--~ local function showinfo()
--~ far.Show("init="..init, "stage="..stage, "MIN="..MIN, "MAX="..MAX,
--~ "start="..start, "BEST="..BEST)
--~ end
while true do
local res = regex:ufind(s, start)
if res and res[2]>=init then res=nil end
local ok = false
---------------------------------------------------------------------------
if stage == 1 then -- maximize out[2]
--showinfo()
if res then
if res[2] > out[2] then
BEST, out, ok = start, res, true
elseif res[2] == out[2] then
ok = true
end
end
--far.Message("ok="..tostring(ok))
if MIN >= MAX then
stage = 2
MIN, MAX = 2, BEST-1
start = floor((MIN+MAX)/2)
elseif ok then
MIN = start+1
start = ceil((MIN+MAX)/2)
else
MAX = start-1
start = floor((MIN+MAX)/2)
end
---------------------------------------------------------------------------
else -- minimize out[1]
--showinfo()
if res and res[2] >= out[2] then
if res[1] < out[1] then
out, ok = res, true
elseif res[1] == out[1] then
ok = true
end
end
--far.Message("ok="..tostring(ok))
if MIN >= MAX then
break
elseif ok then
MAX = start-1
start = floor((MIN+MAX)/2)
else
MIN = start+1
start = ceil((MIN+MAX)/2)
end
end
---------------------------------------------------------------------------
end
return out
end
-- Note: argument 'row' can be nil (using current line)
local function ScrollToPosition (row, pos, from, to, scroll)
local editInfo = editor.GetInfo()
local LeftPos = editInfo.LeftPos
-- left-most (or right-most) char is not visible
if (from <= LeftPos) or (to > LeftPos + editInfo.WindowSizeX) then
if to - from + 1 >= editInfo.WindowSizeX then
LeftPos = from - 1
else
LeftPos = floor((to + from - 1 - editInfo.WindowSizeX) / 2)
if LeftPos < 0 then LeftPos = 0 end
end
end
-----------------------------------------------------------------------------
local top
local halfscreen = editInfo.WindowSizeY / 2
scroll = scroll or 0
row = row or editInfo.CurLine
if row < halfscreen - scroll then
top = 1
elseif row > halfscreen + scroll then
top = row - floor(halfscreen + scroll - 0.5)
else
top = row - floor(halfscreen - scroll - 0.5)
end
-----------------------------------------------------------------------------
editor.SetPosition { TopScreenLine=top, CurLine=row, LeftPos=LeftPos, CurPos=pos }
end
local function ShowCollectedLines (items, params)
if #items == 0 then return end
package.loaded["far2.custommenu"] = nil
local custommenu = require("far2.custommenu")
table.sort(items, function(a,b) return a.lineno < b.lineno end)
local maxno, n = 1, items[#items].lineno+1
while n >= 10 do maxno=maxno+1; n=n/10; end
local fmt = ("%%%dd%s %%s"):format(maxno, ("").char(9474))
for _, item in ipairs(items) do
local s = item.text:gsub("%z", " ") -- replace null bytes with spaces
:gsub("^%s*", -- delete leading spaces
function(c) -- adjust offsets for highlighting
local len_delete = min(c:len(), item.fr-1)
local n = maxno + 2 - len_delete
item.offset, item.fr, item.to = n, item.fr+n, item.to+n
return c:sub(len_delete + 1)
end)
item.text = fmt:format(item.lineno+1, s)
end
local bottom = #items..M.MLinesFound.." [F6,F7,Ctrl-C]"
local list = custommenu.NewList({
resizeScreen = true, -- make it the default for CustomMenu?
--~ col_highlight = 0x3A,
--~ col_selectedhighlight = 0x0A,
col_highlight = 0x6F,
col_selectedhighlight = 0x4F,
ellipsis = 3, -- position ellipsis at line end
searchstart = maxno + 3, -- needed for correct work of ellipsis
}, items)
local item = custommenu.Menu({
Title=M.MSearchResults.." ["..params.sSearchPat.."]",-- honored by CustomMenu
Bottom=bottom, -- honored by CustomMenu
Flags=F.FMENU_SHOWAMPERSAND, -- ignored by CustomMenu?
HelpTopic="Contents",
}, list)
if item then
local fr, to = item.fr-item.offset, item.to-item.offset
ScrollToPosition(item.lineno, to, fr, to)
editor.Select("BTYPE_STREAM", nil, fr, to-fr+1, 1)
editor.Redraw()
end
end
local function EditorSetCurString (text)
if not EditorSetString(nil, text) then error("EditorSetString failed") end
end
-- @aOp: "search", "replace", "count", "showall"
local function DoAction (aOp, aParams, aWithDialog, aChoiceFunc)
-----------------------------------------------------------------------------
local sTitle = (aOp == "replace") and M.MTitleReplace or M.MTitleSearch
local bForward = not aParams.bSearchBack
local bAllowEmpty = aWithDialog
local fFilter, Regex = aParams.FilterFunc, aParams.Regex
local fChoice = aChoiceFunc or GetUserChoice
local fReplace = (aOp == "replace") and GetReplaceFunction(aParams.ReplacePat)
local tItems = (aOp == "showall") and {}
local bFastCount = (aOp == "count") and bForward
local sChoice
local nFound, nReps, nLine = 0, 0, 0
local tInfo, tStartPos = editor.GetInfo(), editor.GetInfo()
local nOp, nOpMax, last_update = 0, 5, 0
local tBlockInfo
if aParams.sScope == "block" then
tBlockInfo = assert(editor.GetSelection(), "no selection")
end
local fLineInScope
if tBlockInfo then
fLineInScope = bForward
and function(y) return y <= tBlockInfo.EndLine end
or function(y) return y >= tBlockInfo.StartLine end
else
fLineInScope = bForward
and function(y) return y <= tInfo.TotalLines end
or function(y) return y >= 1 end
end
-- sLine must be set/modified only via set_sLine, in order to cache its length.
-- This gives a very noticeable performance gain on long lines.
local sLine, sLineLen
local function set_sLine(s) sLine, sLineLen = s, s:len(); end
local x, y, egs, part1, part3
local function SetStartBlockParam (y)
if aOp == "replace" then
if tBlockInfo then EditorSelect(tBlockInfo)
else editor.Select("BTYPE_NONE")
end
end
egs = EditorGetString(y, 1)
part1 = egs.StringText:sub(1, egs.SelStart-1)
if egs.SelEnd == -1 then
set_sLine(egs.StringText:sub(egs.SelStart))
part3 = ""
else
set_sLine(egs.StringText:sub(egs.SelStart, egs.SelEnd))
part3 = egs.StringText:sub(egs.SelEnd+1)
end
end
if aWithDialog and aParams.sOrigin == "scope" then
if tBlockInfo then
y = bForward and tBlockInfo.StartLine or tBlockInfo.EndLine
SetStartBlockParam(y)
x = bForward and 1 or sLineLen+1
else
y = bForward and 1 or tInfo.TotalLines
set_sLine(EditorGetString(y, 2))
x = bForward and 1 or sLineLen+1
part1, part3 = "", ""
end
else -- "cursor"
if tBlockInfo then
if tInfo.CurLine < tBlockInfo.StartLine then
y = tBlockInfo.StartLine
SetStartBlockParam(y)
x = bForward and 1 or sLineLen
elseif tInfo.CurLine > tBlockInfo.EndLine then
y = tBlockInfo.EndLine
SetStartBlockParam(y)
x = bForward and 1 or sLineLen
else
y = tInfo.CurLine
SetStartBlockParam(y)
x = tInfo.CurPos <= egs.SelStart and 1
or min(egs.SelEnd==-1 and sLineLen or egs.SelEnd,
tInfo.CurPos - egs.SelStart, sLineLen)
end
else
y = tInfo.CurLine
set_sLine(EditorGetString(y, 2))
x = min(tInfo.CurPos, sLineLen+1)
part1, part3 = "", ""
end
end
-----------------------------------------------------------------------------
local function update_y (bLineDeleted)
y = bForward and y+(bLineDeleted and 0 or 1) or y-1
if fLineInScope(y) then
if tBlockInfo then
SetStartBlockParam(y)
else
set_sLine(EditorGetString(y, 2))
end
x = bForward and 1 or sLineLen+1
bAllowEmpty = true
end
end
-----------------------------------------------------------------------------
local update_x = bForward
and function(fr, to, delta) x = to + (delta or 1) end
or function(fr, to) x = fr end
-----------------------------------------------------------------------------
local function update_info()
editor.SetTitle("found: " .. nFound)
end
local function check_and_update()
local currclock = os.clock()
local tm = currclock - _lastclock
if tm == 0 then tm = 0.01 end
nOpMax = nOpMax * 0.5 / tm
if nOpMax > 100 then nOpMax = 100 end
_lastclock = currclock
-------------------------------------------------
if currclock - last_update >= 0.5 then
update_info()
if CheckUserBreak(sTitle) then return true end
last_update = currclock
end
end
_lastclock = os.clock()
--===========================================================================
-- ITERATE ON LINES
--===========================================================================
while sChoice ~= "cancel" and sChoice ~= "broken" and fLineInScope(y) do
nLine = nLine + 1
local bLineDeleted
---------------------------------------------------------------------------
if not (fFilter and fFilter(sLine, nLine)) then
while bForward and x <= sLineLen+1 or not bForward and x >= 1 do
-- iterate on current line
-----------------------------------------------------------------------
nOp = nOp + 1
if nOp >= nOpMax then -- don't use "==" here (int vs floating point)
nOp = 0
if check_and_update() then sChoice = "broken"; break; end
end
-----------------------------------------------------------------------
if bFastCount then
local _, n = Regex:gsub(sLine:sub(x), "")
nFound = nFound + n
break
end
-----------------------------------------------------------------------
local collect, fr, to
if bForward then collect = Regex:ufind(sLine, x)
else collect = find_back(sLine, Regex, x)
end
if not collect then break end
fr, to = collect[1], collect[2]
-----------------------------------------------------------------------
if fr==x and to+1==x and not bAllowEmpty then
if bForward then
if x > sLineLen then break end
x = x + 1
collect = Regex:ufind(sLine, x)
else
if x == 1 then break end
x = x - 1
collect = find_back(sLine, Regex, x)
end
if not collect then break end
fr, to = collect[1], collect[2]
end
-----------------------------------------------------------------------
nFound = nFound + 1
bAllowEmpty = false
-----------------------------------------------------------------------
local function ShowFound (scroll)
--editor.SetPosition(y, x)
local p1 = part1:len()
ScrollToPosition (y, p1+x, fr, to, scroll)
editor.Select("BTYPE_STREAM", y, p1+fr, to-fr+1, 1)
editor.Redraw()
tStartPos = editor.GetInfo()
end
-----------------------------------------------------------------------
if aOp == "search" then
update_x(fr, to)
ShowFound()
return 1, 0
-----------------------------------------------------------------------
elseif aOp == "count" then
update_x(fr, to)
-----------------------------------------------------------------------
elseif aOp == "showall" then
update_x(fr, to)
if #tItems == 0 or y ~= tItems[#tItems].lineno then
table.insert(tItems, {lineno=y, text=sLine, fr=fr, to=to})
end
-----------------------------------------------------------------------
elseif aOp == "replace" then
collect[2] = sLine:sub(fr, to)
local sRepFinal = fReplace(collect, nReps)
if sRepFinal then
--=================================================================
local function Replace()
local bTraceSelection = tBlockInfo
and (tBlockInfo.BlockType == F.BTYPE_STREAM)
and (tBlockInfo.EndLine == y) and (tBlockInfo.EndPos ~= -1)
local sHead = sLine:sub(1, fr-1)
local sLastRep, sStartLine
local nAddedLines = 0
for txt, nl in sRepFinal:gmatch("([^\r\n]*)(\r?\n?)") do
sLastRep = txt
sHead = sHead .. txt
if nl == "" then break end
if nAddedLines == 0 then
sStartLine = sHead
sHead = part1 .. sHead
part1 = ""
end
EditorSetCurString(sHead)
editor.SetPosition(nil, sHead:len()+1)
editor.InsertString()
sHead = ""
nAddedLines = nAddedLines + 1
end
set_sLine(sHead .. sLine:sub(to+1))
local line = part1 .. sLine .. part3
bLineDeleted = aParams.bDelEmptyLine and line == ""
local nDeleted = bLineDeleted and 1 or 0
if bLineDeleted then editor.DeleteString()
else EditorSetCurString(line)
end
if bForward then
y = y + nAddedLines
x = sHead:len() + 1
else
if sStartLine then set_sLine(sStartLine) end
x = fr
editor.SetPosition(y, x)
end
if tBlockInfo then
tBlockInfo.EndLine = tBlockInfo.EndLine + nAddedLines - nDeleted
if bTraceSelection then
tBlockInfo.EndPos = bLineDeleted and -1
or tBlockInfo.EndPos + sLastRep:len() - (to-fr+1)
end
else
tInfo.TotalLines = tInfo.TotalLines + nAddedLines - nDeleted
end
if sChoice == "yes" then editor.Redraw() end
if tBlockInfo then EditorSelect(tBlockInfo) end
tStartPos = editor.GetInfo() -- save position
nReps = nReps + 1
return bLineDeleted
end
--=================================================================
if sChoice == "all" then
if Replace() then break end
editor.SetPosition(y, x)
tStartPos = editor.GetInfo()
else
ShowFound(14/2 + 2)
sChoice = fChoice(sTitle, sLine:sub(fr, to), sRepFinal)
-----------------------------------------------------------------
if sChoice == "yes" or sChoice == "all" then
if Replace() then break end
if sChoice == "yes" then ShowFound() end
-----------------------------------------------------------------
elseif sChoice == "no" then
update_x(fr, to)
-----------------------------------------------------------------
elseif sChoice == "cancel" then
break
-----------------------------------------------------------------
end
end
else
update_x(fr, to)
end
-----------------------------------------------------------------------
end
end -- Current Line loop
end -- Line Filter check
update_y(bLineDeleted)
end
--===========================================================================
editor.SetPosition(tStartPos)
if tBlockInfo then
EditorSelect(tBlockInfo)
end
editor.Redraw()
update_info()
if aOp == "showall" then
ShowCollectedLines(tItems, aParams)
end
return nFound, nReps, sChoice
end
return DoAction
|
function onStepIn(creature, item, position, fromPosition)
local player = creature:getPlayer()
if not player then
return true
end
if player:getStorageValue(Storage.BarbarianTest.Mission03) == 3 then
player:teleportTo(Position(32212, 31131, 5))
else
player:teleportTo(Position(32210, 31134, 7))
player:say('You have to be a honorary barbarian to access the roof. Talk to the Jarl about it.', TALKTYPE_MONSTER_SAY)
end
player:setDirection(DIRECTION_EAST)
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
return true
end
|
local utils = require "kong.tools.utils"
local log = require "kong.cmd.utils.log"
local Schema = require "kong.db.schema"
local Migration = require "kong.db.schema.others.migrations"
local pl_path = require "pl.path"
local pl_dir = require "pl.dir"
local Errors = require "kong.db.errors"
local MigrationSchema = Schema.new(Migration)
local fmt = string.format
local function prefix_err(db, err)
return "[" .. db.infos.strategy .. " error] " .. err
end
local function fmt_err(db, err, ...)
return prefix_err(db, fmt(err, ...))
end
local Migrations_mt = {
__tostring = function(t)
local subsystems = {}
for _, subsys in ipairs(t) do
local names = {}
for _, migration in ipairs(subsys.migrations) do
table.insert(names, migration.name)
end
table.insert(subsystems, fmt("%s: %s", subsys.subsystem,
table.concat(names, ", ")))
end
return table.concat(subsystems, "\n")
end,
}
local function load_subsystems(db, plugin_names)
if type(plugin_names) ~= "table" then
error("plugin_names must be a table", 2)
end
local namespace = "kong.db.migrations"
local core_namespace = fmt("%s.core", namespace)
local res = {
{
name = "core",
namespace = core_namespace,
migrations_index = require(core_namespace),
},
}
-- load core subsystems
local core_path = pl_path.package_path(core_namespace)
local dir_path, n = string.gsub(pl_path.abspath(core_path),
"core" .. pl_path.sep .. "init%.lua$", "")
if n ~= 1 then
return nil, prefix_err(db, "failed to substitute migrations path in "
.. dir_path)
end
local dirs = pl_dir.getdirectories(dir_path)
for _, dir in ipairs(dirs) do
if not string.find(dir, "core$") then
local name = pl_path.basename(dir)
local namespace = fmt("%s.%s", namespace, name)
local filepath = dir .. pl_path.sep .. "init.lua"
local index = assert(loadfile(filepath))
local mig_idx = index()
if type(mig_idx) ~= "table" then
return nil, fmt_err(db, "migrations index at '%s' must be a table",
filepath)
end
table.insert(res, {
name = name,
namespace = namespace,
migrations_index = mig_idx,
})
end
end
-- load plugins
for plugin_name in pairs(plugin_names) do
local namespace = "kong.plugins." .. plugin_name .. ".migrations"
local ok, mig_idx = utils.load_module_if_exists(namespace)
if ok then
if type(mig_idx) ~= "table" then
return nil, fmt_err(db, "migrations index from '%s' must be a table",
namespace)
end
table.insert(res, {
name = plugin_name,
namespace = namespace,
migrations_index = mig_idx,
})
end
end
for _, subsys in ipairs(res) do
subsys.migrations = {}
for _, mig_name in ipairs(subsys.migrations_index) do
local mig_module = fmt("%s.%s", subsys.namespace, mig_name)
local ok, migration = utils.load_module_if_exists(mig_module)
if not ok then
return nil, fmt_err(db, "failed to load migration '%s' of '%s' subsystem",
mig_module, subsys.name)
end
migration.name = mig_name
local ok, errors = MigrationSchema:validate(migration)
if not ok then
local err_t = Errors:schema_violation(errors)
return nil, fmt_err(db, "migration '%s' of '%s' subsystem is invalid: %s",
mig_module, subsys.name, tostring(err_t))
end
table.insert(subsys.migrations, migration)
end
end
return res
end
local State = {}
State.__index = State
function State.load(db)
log.debug("loading subsystems migrations...")
local subsystems, err = load_subsystems(db, db.kong_config.loaded_plugins)
if not subsystems then
return nil, prefix_err(db, err)
end
log.verbose("retrieving %s schema state...", db.infos.db_desc)
local ok, err = db.connector:connect_migrations({ no_keyspace = true })
if not ok then
return nil, prefix_err(db, err)
end
local rows, err = db.connector:schema_migrations()
if err then
db.connector:close()
return nil, prefix_err(db, "failed to check schema state: " .. err)
end
local legacy_res, err = db.connector:is_014(rows)
db.connector:close()
if err then
return nil, prefix_err(db, "failed to check legacy schema state: " ..
err)
end
log.verbose("schema state retrieved")
local schema_state = {
needs_bootstrap = false,
executed_migrations = nil,
pending_migrations = nil,
missing_migrations = nil,
new_migrations = nil,
legacy_is_014 = legacy_res.is_014,
}
if legacy_res.invalid_state then
schema_state.legacy_invalid_state = true
schema_state.legacy_missing_component = legacy_res.missing_component
schema_state.legacy_missing_migration = legacy_res.missing_migration
end
local rows_as_hash = {}
if not rows then
schema_state.needs_bootstrap = true
else
for _, row in ipairs(rows) do
rows_as_hash[row.subsystem] = {
last_executed = row.last_executed,
executed = row.executed or {},
pending = row.pending or {},
}
end
end
for _, subsystem in ipairs(subsystems) do
local subsystem_state = {
executed_migrations = {},
pending_migrations = {},
missing_migrations = {},
new_migrations = {},
}
if not rows_as_hash[subsystem.name] then
-- no migrations for this subsystem in DB, all migrations are 'new' (to
-- run)
for i, mig in ipairs(subsystem.migrations) do
subsystem_state.new_migrations[i] = mig
end
else
-- some migrations have previously ran for this subsystem
local n
for i, mig in ipairs(subsystem.migrations) do
if mig.name == rows_as_hash[subsystem.name].last_executed then
n = i + 1
end
local found
for _, db_mig in ipairs(rows_as_hash[subsystem.name].executed) do
if mig.name == db_mig then
found = true
table.insert(subsystem_state.executed_migrations, mig)
break
end
end
if not found then
for _, db_mig in ipairs(rows_as_hash[subsystem.name].pending) do
if mig.name == db_mig then
found = true
table.insert(subsystem_state.pending_migrations, mig)
break
end
end
end
if not found then
if not n or i >= n then
table.insert(subsystem_state.new_migrations, mig)
else
table.insert(subsystem_state.missing_migrations, mig)
end
end
end
end
for k, v in pairs(subsystem_state) do
if #v > 0 then
if not schema_state[k] then
schema_state[k] = setmetatable({}, Migrations_mt)
end
table.insert(schema_state[k], {
subsystem = subsystem.name,
namespace = subsystem.namespace,
migrations = v,
})
end
end
end
return setmetatable(schema_state, State)
end
function State:is_up_to_date()
return not self.needs_bootstrap and not self.new_migrations
end
function State:is_migration_executed(subsystem, migration_name)
local subsys = self[subsystem]
if not subsys or not subsys.executed_migrations then
return false
end
for _, migration in ipairs(subsys.executed_migrations) do
if migration.name == migration_name then
return true
end
end
return false
end
return State
|
-- Hooking functions of gmcompat
-- Exit if we don't have gmcompat loaded
if not gmcompat then return end
local log = gmcompat._internal.log
local err = gmcompat._internal.err
local hooklist = {
[gmcompat.NAME_SANDBOX] = {
["start"] = "",
["end"] = "",
},
[gmcompat.NAME_TTT] = {
["start"] = "TTTBeginRound",
["end"] = "TTTEndRound",
},
[gmcompat.NAME_TTT2] = {
["start"] = "TTTBeginRound",
["end"] = "TTTEndRound",
},
[gmcompat.NAME_MURDER] = {
["start"] = "OnStartRound",
["end"] = "OnEndRound",
},
[gmcompat.NAME_DARKRP] = {
["start"] = "",
["end"] = "",
},
}
local to_be_hooked = {}
hook.Add("Initialize", "gmcompat_add_hooks", function()
for _, value in ipairs(to_be_hooked) do
gmcompat.hook(value["target"], value["prefix"], value["func"])
end
to_be_hooked = {}
hook.Remove("Initialize", "gmcompat_add_hooks")
end)
-- `target` is the type of hook that should be added (either `start` or `end`)
-- `prefix` is the unique hook name prefix that should be used
-- `func` is the function that should be executed
function gmcompat.hook(target, prefix, func)
local gm_name
-- If the Gamemode hasn't initialized yet, delay hooking until Initialization is done
if gmod.GetGamemode() == nil then
to_be_hooked[#to_be_hooked+1] = {["target"] = target, ["prefix"] = prefix, ["func"] = func}
return
end
gm_name = gmod.GetGamemode().Name
if hooklist[gm_name] == nil then
err("hook: Unknown gamemode '"..gm_name.."'")
return
end
if hooklist[gm_name][target] == nil then
err("hook: Unknown hook '"..target.."' for gamemode '"..gm_name.."'")
return
end
-- Discard hook requests for known but non-existing hook names
if hooklist[gm_name][target] == "" then
return
end
hook.Add(hooklist[gm_name][target], prefix..hooklist[gm_name][target], func)
end
|
--[[
whiteRabbit.lua
Copyright (C) 2016 Kano Computing Ltd.
License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPLv2
This is an Npc with random behaviour that can just walk around.
]]--
local NpcPath = require 'game.gameWorld.characters.npcPath'
local WhiteRabbit = {}
WhiteRabbit.__index = WhiteRabbit
-- inherit from base class Character
setmetatable(WhiteRabbit, {__index = NpcPath})
function WhiteRabbit.create(objectManager, world, worldId, gameStates)
local self = NpcPath.create(objectManager, world, worldId, gameStates)
self = setmetatable(self, WhiteRabbit)
-- overriden from base class
self.collidable = false
-- custom Tiled properties
self.disappears = false
-- visibility
self.visible = true
return self
end
function WhiteRabbit:load(npcObject, map)
NpcPath.load(self, npcObject, map)
-- load the object properties
self.disappears = npcObject.properties.disappears
end
function WhiteRabbit:draw()
if self.visible then
NpcPath.draw(self)
end
end
-- AI Driver ----------------------------------------------------------------------------
function WhiteRabbit:behaviour()
NpcPath.behaviour(self)
-- check if the rabbit should disappear into thin air
if self.newPathIndex == nil and not self.loop and self.disappears then
self.visible = false -- TODO: ask world to remove me from objects table
end
end
return WhiteRabbit
|
local Bit32 = {}
if bit32 then -- check for lua 5.2 compat
Bit32.band = bit32.band
Bit32.bxor = bit32.bxor
Bit32.bor = bit32.bor
else -- application can overwrite
Bit32.band = function(a, b)
return
end
Bit32.bxor = function(a, b)
return
end
Bit32.bor = function(a, b)
return
end
end
Bit32.list = function(x)
local pos=1
local result={}
while pos <= x do
if bit32.band(pos, x) ~=0 then
table.insert(result, pos)
end
pos = pos*2
end
return r
end
return Bit32
|
// Copyright 2006-2013 Martin Morawetz. See LICENSE.
// Matlab LPeg lexer.
// Based off of lexer code by Mitchell.
var l = require('lexer');
var token, word_match = l.token, l.word_match;
var P, R, S = lpeg.P, lpeg.R, lpeg.S;
var M = {_NAME = 'matlab'};
// Whitespace.
var ws = token(l.WHITESPACE, l.space**1);
// Comments.
var line_comment = (P('%') + '#') * l.nonnewline**0;
var block_comment = '%{' * (l.any - '%}')**0 * P('%}')**-1;
var comment = token(l.COMMENT, block_comment + line_comment);
// Strings.
var sq_str = l.delimited_range("'", true);
var dq_str = l.delimited_range('"');
var bt_str = l.delimited_range('`');
var string = token(l.STRING, sq_str + dq_str + bt_str);
// Numbers.
var number = token(l.NUMBER, l.float + l.integer + l.dec_num + l.hex_num +
l.oct_num);
// Keywords.
var keyword = token(l.KEYWORD, word_match({
'break', 'case', 'catch', 'continue', 'do', 'else', 'elseif', 'end',
'end_try_catch', 'end_unwind_protect', 'endfor', 'endif', 'endswitch',
'endwhile', 'for', 'function', 'endfunction', 'global', 'if', 'otherwise',
'persistent', 'replot', 'return', 'static', 'switch', 'try', 'until',
'unwind_protect', 'unwind_protect_cleanup', 'varargin', 'varargout', 'while'
}, null, true));
// Functions.
var func = token(l.FUNCTION, word_match({
'abs', 'any', 'argv','atan2', 'axes', 'axis', 'ceil', 'cla', 'clear', 'clf',
'columns', 'cos', 'delete', 'diff', 'disp', 'doc', 'double', 'drawnow', 'exp',
'figure', 'find', 'fix', 'floor', 'fprintf', 'gca', 'gcf', 'get', 'grid',
'help', 'hist', 'hold', 'isempty', 'isnull', 'length', 'load', 'log', 'log10',
'loglog', 'max', 'mean', 'median', 'min', 'mod', 'ndims', 'numel', 'num2str',
'ones', 'pause', 'plot', 'printf', 'quit', 'rand', 'randn', 'rectangle',
'rem', 'repmat', 'reshape', 'round', 'rows', 'save', 'semilogx', 'semilogy',
'set', 'sign', 'sin', 'size', 'sizeof', 'size_equal', 'sort', 'sprintf',
'squeeze', 'sqrt', 'std', 'strcmp', 'subplot', 'sum', 'tan', 'tic', 'title',
'toc', 'uicontrol', 'who', 'xlabel', 'ylabel', 'zeros'
}));
// Constants.
var constant = token(l.CONSTANT, word_match({
'EDITOR', 'I', 'IMAGEPATH', 'INFO_FILE', 'J', 'LOADPATH', 'OCTAVE_VERSION',
'PAGER', 'PS1', 'PS2', 'PS4', 'PWD'
}));
// Variable.
var variable = token(l.VARIABLE, word_match({
'ans', 'automatic_replot', 'default_return_value', 'do_fortran_indexing',
'define_all_return_values', 'empty_list_elements_ok', 'eps', 'false',
'gnuplot_binary', 'ignore_function_time_stamp', 'implicit_str_to_num_ok',
'Inf', 'inf', 'NaN', 'nan', 'ok_to_lose_imaginary_part',
'output_max_field_width', 'output_precision', 'page_screen_output', 'pi',
'prefer_column_vectors', 'prefer_zero_one_indexing', 'print_answer_id_name',
'print_empty_dimensions', 'realmax', 'realmin', 'resize_on_range_error',
'return_last_computed_value', 'save_precision', 'silent_functions',
'split_long_rows', 'suppress_verbose_help_message', 'treat_neg_dim_as_zero',
'true', 'warn_assign_as_truth_value', 'warn_comma_in_global_decl',
'warn_divide_by_zero', 'warn_function_name_clash',
'whitespace_in_literal_matrix'
}));
// Identifiers.
var identifier = token(l.IDENTIFIER, l.word);
// Operators.
var operator = token(l.OPERATOR, S('!%^&*()[]{}-=+/\\|:;.,?<>~`´'));
M._rules = {
{'whitespace', ws},
{'keyword', keyword},
{'function', func},
{'constant', constant},
{'variable', variable},
{'identifier', identifier},
{'string', string},
{'comment', comment},
{'number', number},
{'operator', operator},
};
M._foldsymbols = {
_patterns = {'[a-z]+', '[%(%)%[%]]', '%%[{}]?', '#'},
[l.KEYWORD] = {
['if'] = 1, ['for'] = 1, ['while'] = 1, switch = 1, ['end'] = -1
},
[l.OPERATOR] = {['('] = 1, [')'] = -1, ['['] = 1, [']'] = -1},
[l.COMMENT] = {
['%{'] = 1, ['%}'] = -1, ['%'] = l.fold_line_comments('%'),
['#'] = l.fold_line_comments('#')
}
};
return M;
|
-- 10_MinuteAdRevenue
-- 7/27/2020
--[[
Implementation Example:
local import = require(game.ReplicatedStorage:WaitForChild("Import"))
-- [ SINGLE EXAMPLE ] --
local SomeModule = import "Module"
-- [ NESTED EXAMPLE ] --
local SomeModule = import "Folder/Module"
--[ INSTANCE EXAMPLE ] --
local SomeModule = import(ModuleScript)
-- [ FULL TREE EXAMPLE ] --
local SomeModule = import("Folder/Module", true)
-- [ OTHER USAGE ] --
local require = import
require("Folder/Module") or require("Module") or require(ModuleScript)
"Full Branch" Hierarchy:
{
contents = require(instance),
instance = instance,
details = {
path = path, --string, ex: "file", "folder/file"
ancestor = ancestor -- this is the "container" (example: ReplicatedStorage)
}
}
]]
local Map = require(script:WaitForChild("Map"))
local Directory = { Loaded = {} } do
Directory.__index = Directory
function Directory.new(container)
return setmetatable({Container = container}, Directory)
end;
function Directory:Implement(tree, meta)
tree.__index = tree
local newFile = setmetatable(tree, meta or {})
Directory.Loaded[newFile.details.path] = tree
end;
function Directory:Request(path, getFullContents)
local function getFile()
if self.Loaded[path] then
if getFullContents then
return self.Loaded[path]
else
return self.Loaded[path].contents
end;
end;
end;
return getFile() or error("Unable to find file from path:", path)
end;
function Directory:Pull(path, presetContainer)
local container = presetContainer or self.Container
local file = container do
local fileTree = string.split(path, "/")
for _, fileName in pairs(fileTree) do
file = file:WaitForChild(fileName)
end;
end;
return file, container
end;
function Directory:Load(path, container)
local branch = (function(dir)
local mod, ancestor = self:Pull(dir, container)
local success, contents = pcall(function()
return {
contents = require(mod),
instance = mod,
details = {
path = path,
ancestor = ancestor
}
};
end)
return (success and contents) or warn("Failed to load module:", mod:GetFullName(), contents)
end)(path)
return branch or nil
end;
function Directory:init()
if Map then
for _, hardcode in pairs(Map) do
local newDirectory = Directory.new(hardcode.container)
for _, path in next, hardcode.map do
local branch = newDirectory:Load(path)
if branch then
--local metatable = {}
self:Implement(branch) --, metatable)
else
warn(path, "Could not be preloaded into import")
end;
end;
end;
end;
end;
end;
Directory:init()
return function(dir, full)
local safeload = function(path, fullContents)
return pcall(function()
return (typeof(path) == "string" and Directory:Request(path, fullContents)) or
(path:IsA("ModuleScript") and require(path)) or
error("Couldn't import from:", path)
end)
end;
local success, file = safeload(dir, full)
return (success and file) or nil
end;
|
getmetatable("").__call = function (self, arg)
if type(arg) == "table" then
return self:sub(arg[1], arg[2] and arg[2]-1 or arg[1])
end
end
getmetatable("").__mul = function (self, count)
local out = ''
for i=1,count do out = out .. self end
return out
end
function string:trim()
return self:match'^()%s*$' and '' or self:match'^%s*(.*%S)'
end
function string:isdigit ()
local char = self:byte()
return char and (char >= 48 and char <= 57)
end
function string:isletter ()
local char = self:byte()
return char and ((char >= 65 and char <= 90) or (char >= 97 and char <= 122))
end
function string:isupper ()
return self == self:upper()
end
function string:islower ()
return self == self:lower()
end
function string:isspace ()
local char = self:byte()
return char and char == 32
end
function string:istab ()
local char = self:byte()
return char and char == 9
end
function string:iseol ()
local char = self:byte()
return char and (char == 10 or char == 13)
end
function string:split (delim)
local items = {}
local curr = self:find(delim, nil, true)
local last = 1
while curr do
items[#items+1] = self{last, curr}
last = curr+1
curr = self:find(delim, curr+1, true)
end
items[#items+1] = self{last, #self+1}
return items
end
function string:starts (sub)
return self:sub(1,#sub) == sub
end
function string:ends (sub)
return self:sub(-#sub) == sub
end
function string:similar (other)
local self = self:upper()
local other = other:upper()
if self:find(other) then return true end
if other:find(self) then return true end
local a,b
for i=1,#self do
a,b = other:find(self:sub(1,i-1) .. '.?' .. self:sub(i+1))
if a then return a,b end
end
if #self>3 then
for i=1,#self do
a,b = other:find(self:sub(1,i-1) .. '..' .. self:sub(i+2))
if a then return a,b end
end
end
end
function string:escape(chars)
return self:gsub(chars, '\\'..chars)
end
function string:chars (self)
local char = 0
return function ()
char = char + 1
if char > #self then return nil end
return char, self{char}
end
end
|
local unpack = unpack
local oo = require "oil.oo"
local giop = require "oil.corba.giop"
local Listener = require "oil.corba.giop.Listener" --[[VERBOSE]] local verbose = require "oil.verbose"
module "oil.corba.intercepted.Listener"
oo.class(_M, Listener)
--------------------------------------------------------------------------------
local LocationForwardTypes = { giop.IOR }
local ReplyID = giop.ReplyID
local Empty = {}
--------------------------------------------------------------------------------
function __init(self, ...)
self = oo.rawnew(self, ...)
local Request = self.Request
self.Request = oo.class({}, Request)
function self.Request.preinvoke(request, iface, member, object)
local objkey, opname = Request.preinvoke(request, iface, member)
request.interface = iface
request.member = member
request.target = object
self:interceptrequest(request, objkey == nil)
if request.success == nil then
return objkey, opname
end
end
return self
end
--------------------------------------------------------------------------------
function interceptrequest(self, request, failed)
local interceptor = self.interceptor
if interceptor then
local intercepted = {
service_context = request.service_context,
request_id = request.request_id,
response_expected = request.response_expected,
object_key = request.object_key,
operation_name = request.operation,
servant = request.target,
interface = request.interface,
interface_name = request.interface and request.interface.absolute_name,
operation = request.member,
parameters = not failed and {n=request.n,request:params()} or nil,
}
request.intercepted = intercepted
if interceptor.receiverequest then --[[VERBOSE]] verbose:interceptors(true, "intercepting request marshaling")
interceptor:receiverequest(intercepted)
if intercepted.success ~= nil then --[[VERBOSE]] verbose:interceptors("interception request was canceled")
request.success = intercepted.success
-- update returned values
local results = intercepted.results or {}
request.n = results.n or #results
for i = 1, request.n do
request[i] = results[i]
end
request.intercepted = nil -- this should cancel the reply interception
request.reply_service_context = intercepted.reply_service_context
elseif intercepted.forward_reference then --[[VERBOSE]] verbose:interceptors("interceptor forwarded the request")
request.success = false -- this should cancel the operation dispatch
request.intercepted = nil -- this should cancel the reply interception
request.reply_service_context = intercepted.reply_service_context
request.forward_reference = intercepted.forward_reference
else
-- update parameter values
local parameters = intercepted.parameters
if parameters then
request.n = parameters.n or #parameters
for i = 1, request.n do
request[i] = parameters[i]
end
end
-- update operation being invoked
if intercepted.operation ~= request.member then --[[VERBOSE]] verbose:interceptors("interceptor changed invoked operation")
local operation = intercepted.operation
request.operation = operation.name
request.inputs = operation.inputs
request.outputs = operation.outputs
request.exceptions = operation.exceptions
end
-- update GIOP message fields
request.service_context = intercepted.service_context
request.object_key = intercepted.object_key
end --[[VERBOSE]] verbose:interceptors(false, "interception ended")
end
end
end
--------------------------------------------------------------------------------
function interceptreply(self, request, body)
local intercepted = request.intercepted
if intercepted then
request.intercepted = nil
local interceptor = self.interceptor
if interceptor and interceptor.sendreply then
intercepted.reply_status = request.reply_status
intercepted.success = request.success
if request.reply_status == "SYSTEM_EXCEPTION" then
intercepted.results = { n = 1, body[1] }
else
intercepted.results = { n = request.n, unpack(request, 1, request.n) }
end --[[VERBOSE]] verbose:interceptors(true, "intercepting reply marshaling")
interceptor:sendreply(intercepted) --[[VERBOSE]] verbose:interceptors(false, "interception ended")
local reference = intercepted.forward_reference
if reference then
request.forward_reference = reference
else
request.success = intercepted.success
-- update returned values
local results = intercepted.results or {}
request.n = results.n or #results
for i = 1, request.n do
request[i] = results[i]
end
end
-- update GIOP message fields
request.reply_service_context = intercepted.reply_service_context
return true
end
end
end
function makereply(self, request)
local types, body
local reference = request.forward_reference
if reference then
request.reply_status = "LOCATION_FORWARD"
request.service_context = Empty
return LocationForwardTypes, { reference }
end
local header, types, body = Listener.handlereply(self, request)
if header ~= request then
request.reply_status = header.reply_status
request.service_context = header.service_context
end
return types, body
end
function handlereply(self, request)
local types, body = self:makereply(request)
if self:interceptreply(request, body) then
types, body = self:makereply(request)
if request.reply_service_context then
request.service_context = request.reply_service_context
end
end
return request, types, body
end
|
TheCamera = Engine:EntityClass('TheCamera')
function TheCamera:setup(data)
BasicEntSetup(self, data)
local width = 30 -- metres
self._worldSizeAtZoomScaleOne = Vec(width, width / 1920 * 1080) -- 10 metres by 10 metres (todo: match aspect ratio)
self._zoomScale = self._zoomScale or 1.0
self._worldSize = self._worldSize or nil
self:setZoomScale(self._zoomScale)
self.viewPos = self.viewPos or Vec(0, 0) -- not aligned to grid
end
function TheCamera:specialRender(dt)
Engine.DP:pushEvent('camera render')
if self.owner.player then
self:setPos(self.owner.player:getPos())
end
local dist = self:getPos():dist(self.viewPos)
if dist > 10.0 or GAMETIME < 0.1 then
self.viewPos = self:getPos()
end
local goalViewPos = self:getPos() --+ Vec(0.5, 0.5)
local viewDiff = goalViewPos - self.viewPos
local viewSpeed = math.remapClamp(viewDiff:mag(), 3, 7, 7.5, 25)
self.viewPos = self.viewPos + viewDiff:normalized() * math.clamp(dt * viewSpeed, 0, viewDiff:mag())
love.graphics.push()
love.graphics.applyTransform(self:getTransform())
-- find entities to render
local entsToRender = util.filterList(
Engine.entitiesList,
function(ent) return rawget(ent, '_pos') end
)
table.sort(entsToRender, function(a, b)
if a._pos.y ~= b._pos.y then
return a._pos.y < b._pos.y
end
local aDepth, bDepth = rawget(a, 'renderDepth') or 1, rawget(b, 'renderDepth') or 1
if aDepth ~= bDepth then return aDepth < bDepth end
return a.id < b.id
end)
-- debug draw
if Engine.debugDraw then
--
else
love.graphics.push()
WORLD:specialRender()
love.graphics.pop()
for _, ent in ipairs(entsToRender) do
Engine.DP:pushEvent(string.format('render %s', tostring(ent)))
love.graphics.push()
self:_renderEnt(dt, ent)
love.graphics.pop()
Engine.DP:popEvent()
end
WORLD:specialRenderAfter()
if IS_DEBUG then
love.graphics.setColor(1, 1, 1, 1)
for _, dti in ipairs(Engine.updateDebugText) do
if dti.type == 'world' then
local scale = 0.03
local text = tostring(dti.text)
local font = Engine:getAsset('devfont').handle
local sizeW, sizeH = font:getWidth(text) * scale, font:getHeight() * scale
love.graphics.print(text, font, dti.pos.x - sizeW / 2, dti.pos.y - sizeH / 2, 0, scale, scale)
end
end
end
end
love.graphics.pop()
local v = self.viewPos
love.audio.setPosition(v.x, v.y, 8)
-- being 8 units above the board softens stereo pans
-- but! we must set reference for dynamic sounds to match
Engine.DP:popEvent()
end
function TheCamera:_renderEnt(dt, ent)
local pos = ent:getPos()
local lastPos = ent._lastPos
local shiftDuration = pos:dist(lastPos) / 12.0
local shiftFrac = math.remapClamp(GAMETIME - ent._posChangeTime, 0, shiftDuration, 0, 1)
local displayPos = math.remapClamp(shiftFrac, 0, 1, lastPos, pos)
local isMoving = shiftFrac < 1.0
love.graphics.translate(displayPos:xy())
--love.graphics.translate(0.5, 0.5)
--love.graphics.rotate(math.cardinalToAng(ent:getRot()))
--love.graphics.translate(-0.5, -0.5)
Engine:callEntMethod(ent, 'render', nil, dt, isMoving)
end
function TheCamera:getTransform()
local trans = love.math.newTransform()
local pixelSize = Vec(love.graphics.getDimensions())
-- first we translate so the middle of the screen is 0,0
trans:translate(0.5 * pixelSize.x, 0.5 * pixelSize.y)
-- fixed downscale and screen bounds for debugging
--trans:scale(0.5)
--love.graphics.rectangle('line', -0.5 * pixelSize.x, -0.5 * pixelSize.y, pixelSize.x, pixelSize.y)
-- scale to cover screen camera rect with world camera rect
local scale
if (self._worldSize.x / self._worldSize.y) > (pixelSize.x / pixelSize.y) then
scale = pixelSize.y / self._worldSize.y
else
scale = pixelSize.x / self._worldSize.x
end
scale = math.floorTo(scale, 1)
trans:scale(scale)
--SCREENTEXT(scale)
--love.graphics.setColor(1, 0, 0, 1)
--love.graphics.setLineWidth(0.02)
--love.graphics.rectangle('line', -0.5 * self._worldSize.x, -0.5 * self._worldSize.y, self._worldSize.x, self._worldSize.y)
-- translate by camera's offset in world
--trans:translate((-self:getPos()):xy())
--local hmm = Vec(math.floorTo(self.viewPos.x, 1 / 16) + 1 / 8, math.floorTo(self.viewPos.y, 1 / 16) + 1 / 8)
--trans:translate((-hmm):xy())
trans:translate((-self.viewPos):xy())
return trans
end
function TheCamera:getViewBounds()
local extra = 5
return AABBfromXYWH(
math.floor(self:getPos().x - self._worldSize.x / 2) - extra,
math.floor(self:getPos().y - self._worldSize.y / 2) - extra,
math.floor(self._worldSize.x + 2 * extra),
math.floor(self._worldSize.y + 2 * extra)
)
end
function TheCamera:screenRender()
--love.graphics.setColor(1, 1, 1, 1)
--love.graphics.setFont(Engine:getAsset('devfont').handle)
--love.graphics.print(string.format("wtffff %s", tostring(self._pos)), 10, 50)
end
function TheCamera:getZoomScale()
return self._zoomScale
end
function TheCamera:setZoomScale(zoomScale)
self._zoomScale = zoomScale
self._worldSize = self._worldSizeAtZoomScaleOne * zoomScale
end
|
-- oUF_SimpleConfig: init
-- zork, 2016
-----------------------------
-- Variables
-----------------------------
local A, L = ...
--config container
L.C = {}
--tags and events
L.C.tagMethods = {}
L.C.tagEvents = {}
--make the config global
oUF_SimpleConfig = L.C
|
local screenWidth, screenHeight = guiGetScreenSize()
local relativeScale, relativeFontScale = math.min(math.max(screenWidth/1600, 0.5), 1), math.min(math.max(screenWidth/1600, 0.85), 1)
local killmessages = {}
killmessages.list = {}
killmessages.offset = math.floor(screenHeight * 0.8)
killmessages.padding = 5
killmessages.fontScale = 1
killmessages.font = dxCreateFont(":v_locale/fonts/Roboto-Regular.ttf", math.floor(10 * relativeFontScale))
killmessages.fontHeight = dxGetFontHeight(killmessages.fontScale, killmessages.font)
killmessages.height = math.floor(killmessages.fontHeight * 2)
killmessages.maximumToShow = 2
killmessages.interpolator = "InOutQuad"
killmessages.fadeOutTime = 5000
-- Optimization
local dxCreateRenderTarget = dxCreateRenderTarget
local dxSetRenderTarget = dxSetRenderTarget
local dxSetBlendMode = dxSetBlendMode
local dxDrawRectangle = dxDrawRectangle
local dxDrawText = dxDrawText
local dxDrawImage = dxDrawImage
local dxDrawImageSection = dxDrawImageSection
local unpack = unpack
local tocolor = tocolor
local math_min = math.min
local math_max = math.max
local math_floor = math.floor
local tableInsert = table.insert
local tableRemove = table.remove
local pairs = pairs
local interpolateBetween = interpolateBetween
addEventHandler("onClientResourceStart", resourceRoot,
function()
killmessages.maskShader = dxCreateShader("fx/mask.fx")
killmessages.maskTexture = dxCreateTexture("img/circle.png")
killmessages.defaultAvatar = dxCreateTexture(":v_avatars/img/default-avatar.png")
dxSetShaderValue(killmessages.maskShader, "maskTexture", killmessages.maskTexture)
end)
-- Add line
function createMessage(details)
local message = {}
message.player = details.player
message.action = details.action
if not isElement(message.player) or not message.action then
return
end
local text = message.action == "killed" and "You #00FF00killed #FFFFFF"..getPlayerName(message.player) or "You got #FF0000killed #FFFFFFby "..getPlayerName(message.player)
message.text = text
message.messageWidth = dxGetTextWidth(message.text:gsub("#%x%x%x%x%x%x", ""), killmessages.fontScale, killmessages.font) + killmessages.padding * 2
message.appearTick = getTickCount()
message.fadeTick = getTickCount()
message.progressFade = 0
message.progressFadeToGo = 1
message.alphaTick = 0
message.progressAlpha = 0
message.progressAlphaToGo = 0
message.display = true
message.width = message.messageWidth + killmessages.padding * 2
message.offsetX = (screenWidth - message.width)/2 - killmessages.height/2
local avatar = exports.v_avatars:getAvatarTexture(message.player)
if isElement(avatar) then
message.avatar = avatar
end
table.insert(killmessages.list, 1, message)
if #killmessages.list > killmessages.maximumToShow then
for i, message in pairs(killmessages.list) do
if i > killmessages.maximumToShow and message.display then
message.fadeTick = getTickCount()
message.alphaTick = getTickCount()
message.display = false
end
end
elseif #killmessages.list == 1 then
removeEventHandler("onClientRender", root, renderKillmessages)
addEventHandler("onClientRender", root, renderKillmessages, true, "low-2")
end
end
addEvent("killmessage:create", true)
addEventHandler("killmessage:create", localPlayer, createMessage)
-- Rendering
function renderKillmessages()
local currentTick = getTickCount()
local globalOffsetY = killmessages.offset
for i, message in pairs(killmessages.list) do
if currentTick - message.appearTick > killmessages.fadeOutTime and message.display then
message.fadeTick = getTickCount()
message.alphaTick = getTickCount()
message.display = false
end
local fadeTick = message.fadeTick or 0
message.progressFade = interpolateBetween(message.progressFade or 0, 0, 0, message.progressFadeToGo, 0, 0, math_min(500, currentTick - fadeTick)/500, killmessages.interpolator)
if message.display and message.progressFade >= 0.99 and message.progressAlphaToGo == 0 then
message.alphaTick = getTickCount()
message.progressAlphaToGo = 1
end
local alphaTick = message.alphaTick or 0
message.progressAlpha = interpolateBetween(message.progressAlpha or 0, 0, 0, message.display and message.progressAlphaToGo or 0, 0, 0, math_min(2000, currentTick - alphaTick)/2000, killmessages.interpolator)
if not message.display and message.progressAlpha <= 0.01 and message.progressFadeToGo == 1 then
message.fadeTick = getTickCount()
message.progressFadeToGo = 0
end
local x, y = message.offsetX, globalOffsetY
dxDrawCurvedRectangle(x, y , message.width, killmessages.height, tocolor(10, 10, 10, 185 * message.progressAlpha * message.progressFade), false)
local avatar = isElement(message.avatar) and message.avatar or killmessages.defaultAvatar
dxSetShaderValue(killmessages.maskShader, "imageTexture", avatar)
local distance = message.width * 0.1 * (1 - message.progressFade)
dxDrawImage(x + distance, y, killmessages.height, killmessages.height, "img/circle.png", 0, 0, 0, tocolor(10, 10, 10, 185 * message.progressFade), false)
dxDrawImage(x + distance, y, killmessages.height, killmessages.height, killmessages.maskShader, 0, 0, 0, tocolor(255, 255, 255, 255 * message.progressFade), false)
dxDrawText(message.text, x + killmessages.height + killmessages.padding, y, x + message.width, y + killmessages.height, tocolor(255, 255, 255, 255 * message.progressAlpha * message.progressFade), killmessages.fontScale, killmessages.font, "left", "center", false, false, false, true)
globalOffsetY = math.ceil(globalOffsetY - (killmessages.height + 5) * message.progressFade)
if not message.display and message.progressAlpha == 0 then
killmessages.list[i] = nil
if #killmessages.list == 0 then
removeEventHandler("onClientRender", root, renderKillmessages)
end
end
end
end
function dxDrawCurvedRectangle(x, y, width, height, color, postGUI)
if type(x) ~= "number" or type(y) ~= "number" or type(width) ~= "number" or type(height) ~= "number" then
return
end
local color = color or tocolor(25, 132, 109, 255)
local postGUI = type(postGUI) == "boolean" and postGUI or false
local edgeSize = height/2
dxDrawImageSection(x, y, edgeSize, edgeSize, 0, 0, 33, 33, "img/edge.png", 0, 0, 0, color, postGUI)
dxDrawImageSection(x, y + edgeSize, edgeSize, edgeSize, 0, 33, 33, 33, "img/edge.png", 0, 0, 0, color, postGUI)
dxDrawImageSection(x + width + edgeSize, y, edgeSize, edgeSize, 43, 0, 33, 33, "img/edge.png", 0, 0, 0, color, postGUI)
dxDrawImageSection(x + width + edgeSize, y + edgeSize, edgeSize, edgeSize, 43, 33, 33, 33, "img/edge.png", 0, 0, 0, color, postGUI)
if width > 0 then
dxDrawImageSection(x + edgeSize, y, width, height, 33, 0, 10, 66, "img/edge.png", 0, 0, 0, color, postGUI)
end
end
|
require "love.filesystem"
require "love.image"
require "love.audio"
require "love.sound"
local loader = {
_VERSION = 'love-loader v2.0.2',
_DESCRIPTION = 'Threaded resource loading for LÖVE',
_URL = 'https://github.com/kikito/love-loader',
_LICENSE = [[
MIT LICENSE
Copyright (c) 2014 Enrique García Cota, Tanner Rogalsky
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
}
local resourceKinds = {
image = {
requestKey = "imagePath",
resourceKey = "imageData",
constructor = function (path)
if love.image.isCompressed(path) then
return love.image.newCompressedData(path)
else
return love.image.newImageData(path)
end
end,
postProcess = function(data)
return love.graphics.newImage(data)
end
},
staticSource = {
requestKey = "staticPath",
resourceKey = "staticSource",
constructor = function(path)
return love.audio.newSource(path, "static")
end
},
font = {
requestKey = "fontPath",
resourceKey = "fontData",
constructor = function(path)
-- we don't use love.filesystem.newFileData directly here because there
-- are actually two arguments passed to this constructor which in turn
-- invokes the wrong love.filesystem.newFileData overload
return love.filesystem.newFileData(path)
end,
postProcess = function(data, resource)
local path, size = unpack(resource.requestParams)
return love.graphics.newFont(data, size)
end
},
BMFont = {
requestKey = "fontBMPath",
resourceKey = "fontBMData",
constructor = function(path)
return love.filesystem.newFileData(path)
end,
postProcess = function(data, resource)
local imagePath, glyphsPath = unpack(resource.requestParams)
local glyphs = love.filesystem.newFileData(glyphsPath)
return love.graphics.newFont(glyphs,data)
end
},
streamSource = {
requestKey = "streamPath",
resourceKey = "streamSource",
constructor = function(path)
return love.audio.newSource(path, "stream")
end
},
soundData = {
requestKey = "soundDataPathOrDecoder",
resourceKey = "soundData",
constructor = love.sound.newSoundData
},
imageData = {
requestKey = "imageDataPath",
resourceKey = "rawImageData",
constructor = love.image.newImageData
},
compressedData = {
requestKey = "compressedDataPath",
resourceKey = "rawCompressedData",
constructor = love.image.newCompressedData
}
}
local CHANNEL_PREFIX = "loader_"
local loaded = ...
if loaded == true then
local requestParams, resource
local done = false
local doneChannel = love.thread.getChannel(CHANNEL_PREFIX .. "is_done")
while not done do
for _,kind in pairs(resourceKinds) do
local loader = love.thread.getChannel(CHANNEL_PREFIX .. kind.requestKey)
requestParams = loader:pop()
if requestParams then
resource = kind.constructor(unpack(requestParams))
local producer = love.thread.getChannel(CHANNEL_PREFIX .. kind.resourceKey)
producer:push(resource)
end
end
done = doneChannel:pop()
end
else
local pending = {}
local callbacks = {}
local resourceBeingLoaded
local pathToThisFile = (...):gsub("%.", "/") .. ".lua"
local function shift(t)
return table.remove(t,1)
end
local function newResource(kind, holder, key, ...)
pending[#pending + 1] = {
kind = kind, holder = holder, key = key, requestParams = {...}
}
end
local function getResourceFromThreadIfAvailable()
local data, resource
for name,kind in pairs(resourceKinds) do
local channel = love.thread.getChannel(CHANNEL_PREFIX .. kind.resourceKey)
data = channel:pop()
if data then
resource = kind.postProcess and kind.postProcess(data, resourceBeingLoaded) or data
resourceBeingLoaded.holder[resourceBeingLoaded.key] = resource
loader.loadedCount = loader.loadedCount + 1
callbacks.oneLoaded(resourceBeingLoaded.kind, resourceBeingLoaded.holder, resourceBeingLoaded.key)
resourceBeingLoaded = nil
end
end
end
local function requestNewResourceToThread()
resourceBeingLoaded = shift(pending)
local requestKey = resourceKinds[resourceBeingLoaded.kind].requestKey
local channel = love.thread.getChannel(CHANNEL_PREFIX .. requestKey)
channel:push(resourceBeingLoaded.requestParams)
end
local function endThreadIfAllLoaded()
if not resourceBeingLoaded and #pending == 0 then
love.thread.getChannel(CHANNEL_PREFIX .. "is_done"):push(true)
callbacks.allLoaded()
end
end
-----------------------------------------------------
function loader.newImage(holder, key, path)
newResource('image', holder, key, path)
end
function loader.newFont(holder, key, path, size)
newResource('font', holder, key, path, size)
end
function loader.newBMFont(holder, key, path, glyphsPath)
newResource('font', holder, key, path, glyphsPath)
end
function loader.newSource(holder, key, path, sourceType)
local kind = (sourceType == 'static' and 'staticSource' or 'streamSource')
newResource(kind, holder, key, path)
end
function loader.newSoundData(holder, key, pathOrDecoder)
newResource('soundData', holder, key, pathOrDecoder)
end
function loader.newImageData(holder, key, path)
newResource('imageData', holder, key, path)
end
function loader.newCompressedData(holder, key, path)
newResource('compressedData', holder, key, path)
end
function loader.start(allLoadedCallback, oneLoadedCallback)
callbacks.allLoaded = allLoadedCallback or function() end
callbacks.oneLoaded = oneLoadedCallback or function() end
local thread = love.thread.newThread(pathToThisFile)
loader.loadedCount = 0
loader.resourceCount = #pending
thread:start(true)
loader.thread = thread
end
function loader.update()
if loader.thread then
if loader.thread:isRunning() then
if resourceBeingLoaded then
getResourceFromThreadIfAvailable()
elseif #pending > 0 then
requestNewResourceToThread()
else
endThreadIfAllLoaded()
loader.thread = nil
end
else
local errorMessage = loader.thread:getError()
assert(not errorMessage, errorMessage)
end
end
end
return loader
end
|
local window = {}
local api = vim.api
local current, buffer, border, cursor
local position = 0
local function create_buffer()
buffer = api.nvim_create_buf(false, true) --create new buffer
--set buffer options
api.nvim_buf_set_name(buffer, "ghubvious")
api.nvim_buf_set_option(buffer, "filetype", "ghubvious")
api.nvim_buf_set_option(buffer, "syntax", "ghubvious")
api.nvim_buf_set_option(buffer, 'swapfile', false)
api.nvim_buf_set_option(buffer, "buftype", "nofile")
api.nvim_buf_set_option(buffer, "bufhidden", "wipe")
--set buffer mappings
local mappingOpts = {noremap = true, silent = true }
api.nvim_buf_set_keymap(buffer, 'n', '<Plug>GhubviousStage', ':lua require\'ghubvious\'.stage()<cr>', mappingOpts)
api.nvim_buf_set_keymap(buffer, 'n', '<Plug>GhubviousUnstage', ':lua require\'ghubvious\'.unstage()<cr>', mappingOpts)
api.nvim_buf_set_keymap(buffer, 'n', '<Plug>GhubviousCommit', ':lua require\'ghubvious\'.commit("")<cr>', mappingOpts)
api.nvim_buf_set_keymap(buffer, 'n', '<Plug>GhubviousCommitAmend', ':lua require\'ghubvious\'.commit("amend")<cr>', mappingOpts)
api.nvim_buf_set_keymap(buffer, 'n', '<Plug>GhubviousCommitNoedit', ':lua require\'ghubvious\'.commit("noedit")<cr>', mappingOpts)
api.nvim_buf_set_keymap(buffer, 'n', '<Plug>GhubviousIgnore', ':lua require\'ghubvious\'.ignore()<cr>', mappingOpts)
api.nvim_buf_set_keymap(buffer, 'n', '<Plug>GhubviousRemove', ':lua require\'ghubvious\'.remove()<cr>', mappingOpts)
api.nvim_buf_set_keymap(buffer, 'n', 'h', ':lua require\'ghubvious\'.job.history()<cr>', mappingOpts)
api.nvim_buf_set_keymap(buffer, 'n', 'a', '<Plug>GhubviousStage', {})
api.nvim_buf_set_keymap(buffer, 'n', 'u', '<Plug>GhubviousUnstage', {})
api.nvim_buf_set_keymap(buffer, 'n', 'cm', '<Plug>GhubviousCommit', {})
api.nvim_buf_set_keymap(buffer, 'n', 'ca', '<Plug>GhubviousCommitAmend', {})
api.nvim_buf_set_keymap(buffer, 'n', 'ce', '<Plug>GhubviousCommitNoedit', {})
api.nvim_buf_set_keymap(buffer, 'n', 'i', '<Plug>GhubviousIgnor', {})
api.nvim_buf_set_keymap(buffer, 'n', 'r', '<Plug>GhubviousRemov', {})
end
local function create_border(win_height, win_width)
border = api.nvim_create_buf(false, true) --create border buffer
-- border Lines filling
local border_lines = { '╔' .. string.rep('═', win_width) .. '╗' }
local middle_line = '║' .. string.rep(' ', win_width) .. '║'
for i=1, win_height do
table.insert(border_lines, middle_line)
end
table.insert(border_lines, '╚' .. string.rep('═', win_width) .. '╝')
-- set bufer's (border_buf) lines from first line (0) to last (-1)
-- ignoring out-of-bounds error (false) with lines (border_lines)
api.nvim_buf_set_lines(border, 0, -1, false, border_lines)
end
local function get_opts()
local opts = {}
-- get dimensions
local width = api.nvim_get_option("columns")
local height = api.nvim_get_option("lines")
-- calculate our floating window size
local win_height = math.ceil(height * 0.5 - 4)
local win_width = math.ceil(width * 0.5)
-- and its starting position
local row = math.ceil((height - win_height) / 2 - 1)
local col = math.ceil((width - win_width) / 2)
-- set window options
opts["main"] = {
relative = "editor",
width = win_width,
height = win_height,
row = row,
col = col
}
--set border window options
opts["border"] = {
style = "minimal",
relative = "editor",
width = win_width + 2,
height = win_height + 2,
row = row - 1,
col = col - 1
}
return opts
end
function window.open()
local opts = get_opts()
create_buffer()
create_border(opts.main.height, opts.main.width)
api.nvim_open_win(border, true, opts.border)
current = api.nvim_open_win(buffer, true, opts.main)
api.nvim_command('au BufWipeout <buffer> exe "silent bwipeout! "'..border)
api.nvim_command('au BufWipeout <buffer> :silent lua require\'ghubvious\'.restore()')
--highlight current line
api.nvim_win_set_option(current, 'cursorline', true)
api.nvim_win_set_option(current, "winhighlight", "NormalFloat:Normal")
end
function window.update(direction, lines)
if api.nvim_buf_is_loaded(buffer) == false then
local count = #lines
for i=0, count do lines[i] = nil end
else
position = position + direction
cursor = api.nvim_win_get_cursor(window)
if position < 0 then position = 0 end
--set file as modifiable
api.nvim_buf_set_option(buffer, 'modifiable', true)
-- with small indentation results will look better
-- for k, v in pairs(lines) do
-- lines[k] = ' ' .. lines[k]
-- end
api.nvim_buf_set_lines(buffer, 0, -1, false, lines)
local count = #lines
for i=0, count do lines[i] = nil end
api.nvim_command('g/(.*/d')
api.nvim_command("noh")
api.nvim_command("normal! zR")
--set file as non modifiable
api.nvim_buf_set_option(buffer, 'modifiable', false)
api.nvim_win_set_cursor(current, cursor)
end
end
function window.close()
api.nvim_win_close(window, true)
end
return window
|
id = 'V-38528'
severity = 'low'
weight = 10.0
title = 'The system must log Martian packets.'
description = 'The presence of "martian" packets (which have impossible addresses) as well as spoofed packets, source-routed packets, and redirects could be a sign of nefarious network activity. Logging these packets enables this activity to be detected.'
fixtext = [==[To set the runtime status of the "net.ipv4.conf.all.log_martians" kernel parameter, run the following command:
# sysctl -w net.ipv4.conf.all.log_martians=1
If this is not the system's default value, add the following line to "/etc/sysctl.conf":
net.ipv4.conf.all.log_martians = 1]==]
checktext = [=[The status of the "net.ipv4.conf.all.log_martians" kernel parameter can be queried by running the following command:
$ sysctl net.ipv4.conf.all.log_martians
The output of the command should indicate a value of "1". If this value is not the default value, investigate how it could have been adjusted at runtime, and verify it is not set improperly in "/etc/sysctl.conf".
$ grep net.ipv4.conf.all.log_martians /etc/sysctl.conf
If the correct value is not returned, this is a finding.]=]
function test()
end
function fix()
end
|
local function drill_dig_it0 (pos,player)
if minetest.is_protected(pos, player:get_player_name()) then
minetest.record_protection_violation(pos, player:get_player_name())
return
end
local node=minetest.get_node(pos)
if node.name == "air" or node.name == "ignore" then return end
if node.name == "default:lava_source" then return end
if node.name == "default:lava_flowing" then return end
if node.name == "tutorial:stone_with_titan" then return end
if node.name == "tutorial:stone_with_rot" then return end
if node.name == "tutorial:stone_with_blau" then return end
if node.name == "default:water_source" then minetest.remove_node(pos) return end
if node.name == "default:water_flowing" then minetest.remove_node(pos) return end
minetest.node_dig(pos,node,player)
end
local function drill_dig_it1 (player)
local dir=player:get_look_dir()
if math.abs(dir.x)>math.abs(dir.z) then
if dir.x>0 then return 0 end
return 1
end
if dir.z>0 then return 2 end
return 3
end
local function drill_dig_it2 (pos,player)
drill_dig_it0 (pos,player)
pos.z=pos.z+1
drill_dig_it0 (pos,player)
pos.z=pos.z-2
drill_dig_it0 (pos,player)
pos.z=pos.z+1
pos.y=pos.y+1
drill_dig_it0 (pos,player)
pos.z=pos.z+1
drill_dig_it0 (pos,player)
pos.z=pos.z-2
drill_dig_it0 (pos,player)
pos.z=pos.z+1
pos.y=pos.y-2
drill_dig_it0 (pos,player)
pos.z=pos.z+1
drill_dig_it0 (pos,player)
pos.z=pos.z-2
drill_dig_it0 (pos,player)
end
local function drill_dig_it3 (pos,player)
drill_dig_it0 (pos,player)
pos.x=pos.x+1
drill_dig_it0 (pos,player)
pos.x=pos.x-2
drill_dig_it0 (pos,player)
pos.x=pos.x+1
pos.y=pos.y+1
drill_dig_it0 (pos,player)
pos.x=pos.x+1
drill_dig_it0 (pos,player)
pos.x=pos.x-2
drill_dig_it0 (pos,player)
pos.x=pos.x+1
pos.y=pos.y-2
drill_dig_it0 (pos,player)
pos.x=pos.x+1
drill_dig_it0 (pos,player)
pos.x=pos.x-2
drill_dig_it0 (pos,player)
end
local function drill_dig_it4 (pos,player)
drill_dig_it0 (pos,player)
pos.x=pos.x+1
drill_dig_it0 (pos,player)
pos.x=pos.x-2
drill_dig_it0 (pos,player)
pos.x=pos.x+1
pos.z=pos.z+1
drill_dig_it0 (pos,player)
pos.x=pos.x+1
drill_dig_it0 (pos,player)
pos.x=pos.x-2
drill_dig_it0 (pos,player)
pos.x=pos.x+1
pos.z=pos.z-2
drill_dig_it0 (pos,player)
pos.x=pos.x+1
drill_dig_it0 (pos,player)
pos.x=pos.x-2
drill_dig_it0 (pos,player)
end
local function drill_dig_it(pos, player, mode)
if mode == 1 then
drill_dig_it0(pos, player)
end
if mode == 2 then -- 3 deep
dir = drill_dig_it1(player)
if dir == 0 then -- x+
drill_dig_it0(pos, player)
pos.x = pos.x + 1
drill_dig_it0(pos, player)
pos.x = pos.x + 1
drill_dig_it0(pos, player)
end
if dir == 1 then -- x-
drill_dig_it0(pos, player)
pos.x=pos.x-1
drill_dig_it0 (pos,player)
pos.x=pos.x-1
drill_dig_it0 (pos,player)
end
if dir==2 then -- z+
drill_dig_it0 (pos,player)
pos.z=pos.z+1
drill_dig_it0 (pos,player)
pos.z=pos.z+1
drill_dig_it0 (pos,player)
end
if dir==3 then -- z-
drill_dig_it0 (pos,player)
pos.z=pos.z-1
drill_dig_it0 (pos,player)
pos.z=pos.z-1
drill_dig_it0 (pos,player)
end
end
if mode==3 then -- 3 wide
dir=drill_dig_it1(player)
if dir==0 or dir==1 then -- x
drill_dig_it0 (pos,player)
pos.z=pos.z+1
drill_dig_it0 (pos,player)
pos.z=pos.z-2
drill_dig_it0 (pos,player)
end
if dir==2 or dir==3 then -- z
drill_dig_it0 (pos,player)
pos.x=pos.x+1
drill_dig_it0 (pos,player)
pos.x=pos.x-2
drill_dig_it0 (pos,player)
end
end
if mode==4 then -- 3 tall, selected in the middle
drill_dig_it0 (pos,player)
pos.y=pos.y-1
drill_dig_it0 (pos,player)
pos.y=pos.y-1
drill_dig_it0 (pos,player)
end
if mode==5 then -- 3 x 3
local dir=player:get_look_dir()
if math.abs(dir.y)<0.5 then
dir=drill_dig_it1(player)
if dir==0 or dir==1 then -- x
drill_dig_it2(pos,player)
end
if dir==2 or dir==3 then -- z
drill_dig_it3(pos,player)
end
else
drill_dig_it4(pos,player)
end
end
minetest.sound_play("mining_drill", {pos = pos, gain = 1.0, max_hear_distance = 10,})
end
local function pos_is_pointable(pos)
local node = minetest.get_node(pos)
local nodedef = minetest.registered_nodes[node.name]
return nodedef and nodedef.pointable
end
function technic.mining_drill_setmode(user,itemstack)
local player_name=user:get_player_name()
local item=itemstack:to_table()
local meta=minetest.deserialize(item["metadata"])
if meta==nil then
meta={}
mode=0
end
if meta["mode"]==nil then
meta["mode"]=0
mode=0
end
mode=(meta["mode"])
local mode2 = mode
mode=mode+1
if mode>=6 then mode=1 end
local items = user:get_wielded_item():get_name()
text = items:sub(1, -3)
item["name"]=text.."_"..mode
meta["mode"]=mode
item["metadata"]=minetest.serialize(meta)
user:set_wielded_item(item)
end
local mining_drill_mode_text = {"single node","3 nodes deep","3 nodes wide","3 nodes tall","3x3 nodes"}
local mining_drill_list = {
-- {<num>, <max_charge>, <charge_per_shot>},
{"1", 10000, 5000},
{"2", 20000, 5000},
{"3", 30000, 5000},
{"4", 40000, 5000},
{"5", 50000, 5000},
{"6", 60000, 4500},
{"7", 70000, 4500},
{"8", 80000, 4500},
{"9", 90000, 4500},
{"10", 100000, 4500},
{"11", 120000, 4000},
{"12", 140000, 4000},
{"13", 160000, 4000},
{"14", 180000, 4000},
{"15", 200000, 4000},
{"16", 220000, 3500},
{"17", 240000, 3500},
{"18", 260000, 3500},
{"19", 280000, 3500},
{"20", 300000, 3500},
{"21", 330000, 3000},
{"22", 360000, 3000},
{"23", 390000, 3000},
{"24", 420000, 3000},
{"25", 450000, 3000},
{"26", 480000, 2500},
{"27", 510000, 2500},
{"28", 540000, 2500},
{"29", 570000, 2500},
{"30", 600000, 2500},
{"31", 640000, 2000},
{"32", 680000, 2000},
{"33", 720000, 2000},
{"34", 760000, 2000},
{"35", 800000, 2000},
{"36", 840000, 1500},
{"37", 880000, 1500},
{"38", 920000, 1500},
{"39", 960000, 1500},
{"40", 1000000, 1500},
{"41", 1050000, 1000},
{"42", 1100000, 1000},
{"43", 1150000, 1000},
{"44", 1200000, 1000},
{"45", 1250000, 1000},
{"46", 1300000, 500},
{"47", 1350000, 500},
{"48", 1400000, 500},
{"49", 1450000, 500},
{"50", 1500000, 500},
{"51", 1500000, 490},
{"52", 1500000, 480},
{"53", 1500000, 470},
{"54", 1500000, 460},
{"55", 1500000, 450},
{"56", 1500000, 440},
{"57", 1500000, 430},
{"58", 1500000, 420},
{"59", 1500000, 410},
{"60", 1500000, 400},
{"61", 1500000, 390},
{"62", 1500000, 380},
{"63", 1500000, 370},
{"64", 1500000, 360},
{"65", 1500000, 350},
{"66", 1500000, 340},
{"67", 1500000, 330},
{"68", 1500000, 320},
{"69", 1500000, 310},
{"70", 1500000, 300},
{"71", 1500000, 290},
{"72", 1500000, 280},
{"73", 1500000, 270},
{"74", 1500000, 260},
{"75", 1500000, 250},
{"76", 1500000, 240},
{"77", 1500000, 230},
{"78", 1500000, 220},
{"79", 1500000, 210},
{"80", 1500000, 200},
{"81", 1500000, 190},
{"82", 1500000, 180},
{"83", 1500000, 170},
{"84", 1500000, 160},
{"85", 1500000, 150},
{"86", 1500000, 140},
{"87", 1500000, 130},
{"88", 1500000, 120},
{"89", 1500000, 110},
{"90", 1500000, 100},
{"91", 1500000, 90},
{"92", 1500000, 80},
{"93", 1500000, 70},
{"94", 1500000, 60},
{"95", 1500000, 50},
{"96", 1500000, 40},
{"97", 1500000, 30},
{"98", 1500000, 20},
{"99", 1500000, 10},
{"100", 1500000, 10},
{"101", 1500000, 10},
{"102", 1500000, 10},
{"103", 1500000, 10},
{"104", 1500000, 10},
{"105", 1500000, 10},
{"106", 1500000, 10},
{"107", 1500000, 10},
{"108", 1500000, 10},
{"109", 1500000, 10},
{"110", 1500000, 10},
{"111", 1500000, 10},
{"112", 1500000, 10},
{"113", 1500000, 10},
{"114", 1500000, 10},
{"115", 1500000, 10},
{"116", 1500000, 10},
{"117", 1500000, 10},
{"118", 1500000, 10},
{"119", 1500000, 10},
{"120", 1500000, 10},
{"121", 1500000, 10},
{"122", 1500000, 10},
{"123", 1500000, 10},
{"124", 1500000, 10},
{"125", 1500000, 10},
{"126", 1500000, 10},
{"127", 1500000, 10},
{"128", 1500000, 10},
{"129", 1500000, 10},
{"130", 1500000, 10},
{"131", 1500000, 10},
{"132", 1500000, 10},
{"133", 1500000, 10},
{"134", 1500000, 10},
{"135", 1500000, 10},
{"136", 1500000, 10},
{"137", 1500000, 10},
{"138", 1500000, 10},
{"139", 1500000, 10},
{"140", 1500000, 10},
{"141", 1500000, 9},
{"142", 1500000, 8},
{"143", 1500000, 7},
{"144", 1500000, 6},
{"145", 1500000, 5},
{"146", 1600000, 4},
{"147", 1700000, 3},
{"148", 1800000, 2},
{"149", 1900000, 1},
{"150", 2000000, 1},
}
for _, m in pairs(mining_drill_list) do
for i=1,5,1 do
technic.register_power_tool("technic:drill_mkS"..m[1].."_"..i, m[2])
if tonumber(m[1]) < 150 then
minetest.register_tool("technic:drill_mkS"..m[1].."_"..i, {
description = "Spezial Mining drill lv."..m[1].." Mode "..i.." ("..mining_drill_mode_text[i]..")",
inventory_image = "technic_mining_drill_mkS"..m[1]..".png^technic_tool_mode"..i..".png",
wield_image = "technic_mining_drill_mkS"..m[1]..".png",
wear_represents = "technic_RE_charge",
on_refill = technic.refill_RE_charge,
groups = {not_in_creative_inventory=1},
on_use = function(itemstack, user, pointed_thing)
local player_name = user:get_player_name()
local meta = minetest.deserialize(itemstack:get_metadata())
if meta==nil then
meta={}
end
if meta["mode"]==nil then
meta["mode"]=1
end
if pointed_thing.type ~= "node" or not pos_is_pointable(pointed_thing.under) or not meta.charge then
return
end
local items = user:get_wielded_item():get_name()
local charge_to_take = m[3]
if meta.charge >= charge_to_take then
local pos = minetest.get_pointed_thing_position(pointed_thing, above)
drill_dig_it(pos, user, meta.mode)
meta.charge = meta.charge - charge_to_take
itemstack:set_metadata(minetest.serialize(meta))
technic.set_RE_wear(itemstack, meta.charge, m[2])
end
return itemstack
end,
})
else
local group = {not_in_creative_inventory=1}
if i == 1 then
group = {}
end
minetest.register_tool("technic:drill_mkS"..m[1].."_"..i, {
description = "Spezial Mining drill lv.MAX Mode "..i.." ("..mining_drill_mode_text[i]..")",
inventory_image = "technic_mining_drill_mkS"..m[1]..".png^technic_tool_mode"..i..".png",
wield_image = "technic_mining_drill_mkS"..m[1]..".png",
wear_represents = "technic_RE_charge",
on_refill = technic.refill_RE_charge,
groups = group,
on_use = function(itemstack, user, pointed_thing)
local player_name = user:get_player_name()
local meta = minetest.deserialize(itemstack:get_metadata())
if meta==nil then
meta={}
end
if meta["mode"]==nil then
meta["mode"]=1
end
if pointed_thing.type ~= "node" or not pos_is_pointable(pointed_thing.under) then
return
end
local items = user:get_wielded_item():get_name()
local pos = minetest.get_pointed_thing_position(pointed_thing, above)
drill_dig_it(pos, user, meta.mode)
return itemstack
end,
})
end
end
end
minetest.register_craft({
output = 'technic:drill_mkS1',
recipe = {
{'tutorial:coin2', 'tutorial:coin2', 'tutorial:coin2'},
{'', 'moreores:mithril_ingot', 'tutorial:admin'},
{'', '', 'moreores:mithril_ingot'},
}
})
for i=1,5,1 do
local creative = {not_in_creative_inventory=1}
if i == 1 then
creative = {}
end
technic.register_power_tool("technic:mining_drill_mkA1_"..i, 1)
minetest.register_tool("technic:mining_drill_mkA1_"..i, {
description = "Admin tool 8: Mining drill Mode "..i.." ("..mining_drill_mode_text[i]..")",
inventory_image = "technic_mining_drill_Admin1.png^technic_tool_mode"..i..".png",
wield_image = "technic_mining_drill_Admin1.png",
wear_represents = "technic_RE_charge",
on_refill = technic.refill_RE_charge,
groups = creative,
on_use = function(itemstack, user, pointed_thing)
local player_name = user:get_player_name()
local meta = minetest.deserialize(itemstack:get_metadata())
if meta==nil then
meta={}
end
if meta["mode"]==nil then
meta["mode"]=1
end
if pointed_thing.type ~= "node" or not pos_is_pointable(pointed_thing.under) then
return
end
local items = user:get_wielded_item():get_name()
local pos = minetest.get_pointed_thing_position(pointed_thing, above)
drill_dig_it(pos, user, meta.mode)
return itemstack
end,
})
end
|
file = io.open(minetest.get_worldpath().."/chat_record.txt", "a")
local separator = "\n-------------\n Separator\n-------------\n \n"
file:write(separator)
minetest.register_on_chat_message(function(name, message)
local time = os.date('%Y-%m-%d %H:%M:%S')
local text = string.format("%s: <%s> %s",tostring(time),name,message)
file:write(text.."\n")
end)
minetest.register_on_shutdown(function()
file:close()
end)
|
format_version = "1.0"
texts = {
["audioOutput"] = "Audio Output",
["alpha"] = "Leakage factor",
["alpha_short"] = "Leakage",
["alpha_shortest"] = "LEAK",
["exponent"] = "Exponent",
["exponent_short"] = "Exponent",
["exponent_shortest"] = "EXP",
["reload"] = "Reload",
["reload_short"] = "Reload",
["reload_shortest"] = "RELD",
["seed"] = "Randomisation seed",
["seed_short"] = "RND Seed",
["seed_shortest"] = "SEED",
["range"] = "Pitch Bend Range",
["range_short"] = "bndRange",
["range_shortest"] = "BRNG",
["mutate"] = "Mutation rate",
["mutate_short"] = "mutate",
["mutate_shortest"] = "MUT",
["mutateRange"] = "Mutation ranger",
["mutateRange_short"] = "mute-rng",
["mutateRange_shortest"] = "MUTR",
["note"] = "Note",
["volume"] = "Volume",
["left"] = "Full left",
["right"] = "Full right",
["pitchbend"] = "Pitch Bend",
["expression"] = "Expression",
["inMode"] = "Input Mode",
["outMode"] = "Output Mode",
["linear_template"] = "^0",
["zero"] = "0",
["one"] = "1",
["max"] = "max"
}
|
id = 'V-38633'
severity = 'medium'
weight = 10.0
title = 'The system must set a maximum audit log file size.'
description = 'The total storage for audit log files must be large enough to retain log information over the period required. This is a function of the maximum log file size and the number of logs retained.'
fixtext = [==[Determine the amount of audit data (in megabytes) which should be retained in each log file. Edit the file "/etc/audit/auditd.conf". Add or modify the following line, substituting the correct value for [STOREMB]:
max_log_file = [STOREMB]
Set the value to "6" (MB) or higher for general-purpose systems. Larger values, of course, support retention of even more audit data.]==]
checktext = [==[Inspect "/etc/audit/auditd.conf" and locate the following line to determine how much data the system will retain in each audit log file: "# grep max_log_file /etc/audit/auditd.conf"
max_log_file = 6
If the system audit data threshold hasn't been properly set up, this is a finding.]==]
function test()
end
function fix()
end
|
local scripts_override = {
{ old = "cyberpunk/main.lua", new = "cyberpunk_override/main.lua" },
{ old = "cyberpunk/drawing.lua", new = "cyberpunk_override/drawing.lua" },
{ old = "cyberpunk/radar.lua", new = "cyberpunk_override/radar.lua" },
{ old = "cyberpunk/healthbar.lua", new = "cyberpunk_override/healthbar.lua" },
{ old = "cyberpunk/stamina.lua", new = "cyberpunk_override/stamina.lua" },
{ old = "cyberpunk/weaponbar.lua", new = "cyberpunk_override/weaponbar.lua" },
{ old = "cyberpunk/selection.lua", new = "cyberpunk_override/selection.lua" },
}
if CLIENT then
CreateClientConVar("cl_cyberpunk_hud_repalce", "1", true, false)
local function include_replace_scripts()
MsgN("Hack cyberpunk HUD")
for i = 1, #scripts_override do
local value = scripts_override[i]
include(value.new)
end
end
local function include_original_scripts()
MsgN("Unhack cyberpunk HUD")
for i = 1, #scripts_override do
local value = scripts_override[i]
include(value.old)
end
end
hook.Add("InitPostEntity", "Cyberpunk_HUD_Scripts_Override", function()
if not GetConVar("cl_cyberpunk_hud_repalce"):GetBool() then return end
include_replace_scripts()
end)
cvars.AddChangeCallback("cl_cyberpunk_hud_repalce", function(_, _, value)
local is_replace = tobool(value)
if is_replace then
include_replace_scripts()
else
include_original_scripts()
end
end)
else
for i = 1, #scripts_override do
local value = scripts_override[i]
AddCSLuaFile(value.new)
end
end
|
--[[
panel 2 pushes panel 1 out of frame
Assume panel 1 and panel 2 exist
--]]
local PanelAnimator = require("PanelAnimator")
local PanAmPush = {}
setmetatable(PanAmPush, {
__index = PanelAnimation;
})
function PanAmPush.new(self, obj)
local obj = PanelAnimator:new(obj)
setmetatable(obj, PanAmPush_mt)
return obj;
end
function PanAmPush.update(self, u)
end
return PanAmPush
|
Class = require 'class'
push = require 'push'
require 'Animation'
require 'Map'
require 'Player'
require 'Bullet'
VIRTUAL_WIDTH = 432
VIRTUAL_HEIGHT = 243
WINDOW_WIDTH = 1280
WINDOW_HEIGHT = 720
math.randomseed(os.time())
love.graphics.setDefaultFilter('nearest', 'nearest')
map = Map()
function love.load()
listOfRectangles = {}
listOfERectangles = {}
love.graphics.setFont(love.graphics.newFont('fonts/font.ttf', 8))
push:setupScreen(VIRTUAL_WIDTH, VIRTUAL_HEIGHT, WINDOW_WIDTH, WINDOW_HEIGHT, {
fullscreen = false,
resizable = true
})
love.window.setTitle('2D Shooter')
love.keyboard.keysPressed = {}
love.keyboard.keysReleased = {}
end
function love.resize(w, h)
push:resize(w, h)
end
function creaEteRect()
recte = {}
recte.x = 500
recte.y = 205
recte.width = 4
recte.height = 1
recte.speed = 200
table.insert(listOfERectangles, recte)
end
function createRect()
rect = {}
rect.x = 220
rect.y = 205
rect.width = 4
rect.height = 1
rect.speed = 200
table.insert(listOfRectangles, rect)
end
function love.keyboard.wasPressed(key)
if (love.keyboard.keysPressed[key]) then
return true
else
return false
end
end
function love.keyboard.wasReleased(key)
if (love.keyboard.keysReleased[key]) then
return true
else
return false
end
end
function love.keypressed(key)
if key == 'escape' then
love.event.quit()
end
love.keyboard.keysPressed[key] = true
end
-- called whenever a key is released
function love.keyreleased(key)
love.keyboard.keysReleased[key] = true
end
function love.update(dt)
map:update(dt)
for i,v in ipairs(listOfRectangles) do
v.x = v.x + v.speed * dt
end
for i,v in ipairs(listOfERectangles) do
v.x = v.x - v.speed * dt
end
love.keyboard.keysPressed = {}
love.keyboard.keysReleased = {}
end
function love.draw()
push:apply('start')
love.graphics.clear(108/255, 140/255, 255/255, 255/255)
for i,v in ipairs(listOfRectangles) do
love.graphics.rectangle("line", v.x, v.y, v.width, v.height)
end
for i,v in ipairs(listOfERectangles) do
---love.graphics.rectangle("line", v.x, v.y, v.width, v.height)
love.graphics.rectangle("line", v.x, v.y, v.width, v.height)
end
love.graphics.translate(math.floor(-map.camX + 0.5), math.floor(-map.camY + 0.5))
map:render()
push:apply('end')
end
|
local L = pace.LanguageString
-- load only when hovered above
local function add_expensive_submenu_load(pnl, callback)
local old = pnl.OnCursorEntered
pnl.OnCursorEntered = function(...)
callback()
pnl.OnCursorEntered = old
return old(...)
end
end
function pace.WearParts(temp_wear_filter)
local allowed, reason = pac.CallHook("CanWearParts", pac.LocalPlayer)
if allowed == false then
pac.Message(reason or "the server doesn't want you to wear parts for some reason")
return
end
return pace.WearOnServer(temp_wear_filter)
end
function pace.OnCreatePart(class_name, name, mdl, no_parent)
local part
local parent = NULL
if no_parent then
if class_name ~= "group" then
local group
local parts = pac.GetLocalParts()
if table.Count(parts) == 1 then
local test = select(2, next(parts))
if test.ClassName == "group" then
group = test
end
else
group = pac.CreatePart("group")
end
part = pac.CreatePart(class_name)
part:SetParent(group)
parent = group
else
part = pac.CreatePart(class_name)
end
else
if class_name ~= "group" and not next(pac.GetLocalParts()) then
pace.Call("CreatePart", "group")
end
part = pac.CreatePart(class_name)
parent = pace.current_part
if parent:IsValid() then
part:SetParent(parent)
elseif class_name ~= "group" then
for _, v in pairs(pac.GetLocalParts()) do
if v.ClassName == "group" then
part:SetParent(v)
parent = v
break
end
end
end
end
if name then part:SetName(name) end
if part.SetModel then
if mdl then
part:SetModel(mdl)
elseif class_name == "model" or class_name == "model2" then
part:SetModel("models/pac/default.mdl")
end
end
local ply = pac.LocalPlayer
if part:GetPlayerOwner() == ply then
pace.SetViewPart(part)
end
if not input.IsControlDown() then
pace.Call("PartSelected", part)
end
part.newly_created = true
if parent.GetDrawPosition and parent:IsValid() and not parent:HasParent() and parent.OwnerName == "world" and part:GetPlayerOwner() == ply then
local data = ply:GetEyeTrace()
if data.HitPos:Distance(ply:GetPos()) < 1000 then
part:SetPosition(data.HitPos)
else
part:SetPosition(ply:GetPos())
end
end
pace.RefreshTree()
return part
end
function pace.OnPartSelected(part, is_selecting)
local parent = part:GetRootPart()
if parent:IsValid() and (parent.OwnerName == "viewmodel" or parent.OwnerName == "hands") then
pace.editing_viewmodel = parent.OwnerName == "viewmodel"
pace.editing_hands = parent.OwnerName == "hands"
elseif pace.editing_viewmodel or pace.editing_hands then
pace.editing_viewmodel = false
pace.editing_hands = false
end
pace.current_part = part
pace.PopulateProperties(part)
pace.mctrl.SetTarget(part)
pace.SetViewPart(part)
pace.Editor:InvalidateLayout()
pace.SafeRemoveSpecialPanel()
if pace.tree:IsValid() then
pace.tree:SelectPart(part)
end
pace.current_part_uid = part.UniqueID
if not is_selecting then
pace.StopSelect()
end
end
function pace.OnVariableChanged(obj, key, val, not_from_editor)
local valType = type(val)
if valType == 'Vector' then
val = Vector(val)
elseif valType == 'Angle' then
val = Angle(val)
end
if not not_from_editor then
timer.Create("pace_backup", 1, 1, pace.Backup)
if not pace.undo_release_varchange then
pace.RecordUndoHistory()
pace.undo_release_varchange = true
end
timer.Create("pace_undo", 0.25, 1, function()
pace.undo_release_varchange = false
pace.RecordUndoHistory()
end)
end
if key == "OwnerName" then
local owner_name = obj:GetProperty(key)
if val == "viewmodel" then
pace.editing_viewmodel = true
elseif val == "hands" then
pace.editing_hands = true
elseif owner_name == "hands" then
pace.editing_hands = false
elseif owner_name == "viewmodel" then
pace.editing_viewmodel = false
end
end
obj:SetProperty(key, val)
local node = obj.pace_tree_node
if IsValid(node) then
if key == "Event" then
pace.PopulateProperties(obj)
elseif key == "Name" then
if not obj:HasParent() then
pace.RemovePartOnServer(obj:GetUniqueID(), true, true)
end
node:SetText(val)
elseif key == "Model" and val and val ~= "" and type(val) == "string" then
node:SetModel(val)
elseif key == "Parent" then
local tree = obj.pace_tree_node
if IsValid(tree) then
node:Remove()
tree = tree:GetRoot()
if tree:IsValid() then
tree:SetSelectedItem(nil)
pace.RefreshTree(true)
end
end
end
if obj.Name == "" then
node:SetText(pace.pac_show_uniqueid:GetBool() and string.format("%s (%s)", obj:GetName(), obj:GetPrintUniqueID()) or obj:GetName())
end
end
if obj.ClassName:StartWith("sound", nil, true) then
timer.Create("pace_preview_sound", 0.25, 1, function()
obj:OnShow()
end)
end
timer.Simple(0, function()
if not IsValid(obj) then return end
local prop_panel = obj.pace_properties and obj.pace_properties[key]
if IsValid(prop_panel) then
local old = prop_panel.OnValueChanged
prop_panel.OnValueChanged = function() end
prop_panel:SetValue(val)
prop_panel.OnValueChanged = old
end
end)
end
pac.AddHook("pac_OnPartParent", "pace_parent", function(parent, child)
pace.Call("VariableChanged", parent, "Parent", child, true)
end)
function pace.GetRegisteredParts()
local out = {}
for class_name, PART in pairs(pac.GetRegisteredParts()) do
local cond = (not pace.IsInBasicMode() or pace.BasicParts[class_name]) and
not PART.ClassName:StartWith("base") and
PART.show_in_editor ~= false and
PART.is_deprecated ~= false
if cond then
table.insert(out, PART)
end
end
return out
end
do -- menu
function pace.AddRegisteredPartsToMenu(menu, parent)
local partsToShow = {}
local clicked = false
hook.Add('Think', menu, function()
local ctrl = input.IsControlDown()
if clicked and not ctrl then
menu:SetDeleteSelf(true)
RegisterDermaMenuForClose(menu)
CloseDermaMenus()
return
end
menu:SetDeleteSelf(not ctrl)
end)
hook.Add('CloseDermaMenus', menu, function()
clicked = true
if input.IsControlDown() then
menu:SetVisible(true)
RegisterDermaMenuForClose(menu)
end
end)
local function add_part(menu, part)
local newMenuEntry = menu:AddOption(L(part.FriendlyName or part.ClassName:Replace('_', ' ')), function()
pace.RecordUndoHistory()
pace.Call("CreatePart", part.ClassName, nil, nil, parent)
pace.RecordUndoHistory()
trap = true
end)
if part.Icon then
newMenuEntry:SetImage(part.Icon)
if part.Group == "legacy" then
local mat = Material(pace.GroupsIcons.experimental)
newMenuEntry.m_Image.PaintOver = function(_, w,h)
surface.SetMaterial(mat)
surface.DrawTexturedRect(2,6,13,13)
end
end
end
end
if pace.IsInBasicMode() then
for _, part in ipairs(pace.GetRegisteredParts()) do
add_part(menu, part)
end
else
local sortedTree = {}
for _, part in pairs(pace.GetRegisteredParts()) do
local group = part.Group or part.Groups or "other"
if type(group) == "string" then
group = {group}
end
for i, name in ipairs(group) do
if not sortedTree[name] then
sortedTree[name] = {}
sortedTree[name].parts = {}
sortedTree[name].icon = pace.GroupsIcons[name]
sortedTree[name].name = L(name)
end
partsToShow[part.ClassName] = nil
if name == part.ClassName or name == part.FriendlyName then
sortedTree[name].group_class_name = part.ClassName
else
table.insert(sortedTree[name].parts, part)
end
end
end
local other = sortedTree.other
sortedTree.other = nil
for group, groupData in pairs(sortedTree) do
local sub, pnl = menu:AddSubMenu(groupData.name, function()
if groupData.group_class_name then
pace.RecordUndoHistory()
pace.Call("CreatePart", groupData.group_class_name, nil, nil, parent)
pace.RecordUndoHistory()
end
end)
sub.GetDeleteSelf = function() return false end
if groupData.icon then
pnl:SetImage(groupData.icon)
end
local trap = false
table.sort(groupData.parts, function(a, b) return a.ClassName < b.ClassName end)
for i, part in ipairs(groupData.parts) do
add_part(sub, part)
end
hook.Add('Think', sub, function()
local ctrl = input.IsControlDown()
if clicked and not ctrl then
sub:SetDeleteSelf(true)
RegisterDermaMenuForClose(sub)
CloseDermaMenus()
return
end
sub:SetDeleteSelf(not ctrl)
end)
hook.Add('CloseDermaMenus', sub, function()
if input.IsControlDown() and trap then
trap = false
sub:SetVisible(true)
end
RegisterDermaMenuForClose(sub)
end)
end
for i,v in ipairs(other.parts) do
add_part(menu, v)
end
for class_name, part in pairs(partsToShow) do
local newMenuEntry = menu:AddOption(L((part.FriendlyName or part.ClassName):Replace('_', ' ')), function()
pace.RecordUndoHistory()
pace.Call("CreatePart", class_name, nil, nil, parent)
pace.RecordUndoHistory()
end)
if part.Icon then
newMenuEntry:SetImage(part.Icon)
end
end
end
end
function pace.OnAddPartMenu(obj)
local base = vgui.Create("EditablePanel")
base:SetPos(input.GetCursorPos())
base:SetSize(200, 300)
base:MakePopup()
function base:OnRemove()
pac.RemoveHook("VGUIMousePressed", "search_part_menu")
end
local edit = base:Add("DTextEntry")
edit:SetTall(20)
if pace.IsInBasicMode() then
edit:SetTall(0)
end
edit:Dock(TOP)
edit:RequestFocus()
edit:SetUpdateOnType(true)
local result = base:Add("DPanel")
result:Dock(FILL)
function edit:OnEnter()
if result.found[1] then
pace.RecordUndoHistory()
pace.Call("CreatePart", result.found[1].ClassName)
pace.RecordUndoHistory()
end
base:Remove()
end
edit.OnValueChange = function(_, str)
result:Clear()
result.found = {}
for _, part in ipairs(pace.GetRegisteredParts()) do
if (part.FriendlyName or part.ClassName):find(str, nil, true) then
table.insert(result.found, part)
end
end
table.sort(result.found, function(a, b) return #a.ClassName < #b.ClassName end)
for _, part in ipairs(result.found) do
local line = result:Add("DButton")
line:SetText("")
line:SetTall(20)
line.DoClick = function()
pace.RecordUndoHistory()
pace.Call("CreatePart", part.ClassName)
base:Remove()
pace.RecordUndoHistory()
end
local btn = line:Add("DImageButton")
btn:SetSize(16, 16)
btn:SetPos(4,0)
btn:CenterVertical()
btn:SetMouseInputEnabled(false)
if part.Icon then
btn:SetImage(part.Icon)
if part.Group == "legacy" then
local mat = Material(pace.GroupsIcons.experimental)
btn.m_Image.PaintOver = function(_, w,h)
surface.SetMaterial(mat)
surface.DrawTexturedRect(2,6,13,13)
end
end
end
local label = line:Add("DLabel")
label:SetTextColor(label:GetSkin().Colours.Category.Line.Text)
label:SetText(L((part.FriendlyName or part.ClassName):Replace('_', ' ')))
label:SizeToContents()
label:MoveRightOf(btn, 4)
label:SetMouseInputEnabled(false)
label:CenterVertical()
line:Dock(TOP)
end
base:SetHeight(20 * #result.found + edit:GetTall())
end
edit:OnValueChange("")
pac.AddHook("VGUIMousePressed", "search_part_menu", function(pnl, code)
if code == MOUSE_LEFT or code == MOUSE_RIGHT then
if not base:IsOurChild(pnl) then
base:Remove()
end
end
end)
end
function pace.Copy(obj)
pace.Clipboard = obj:ToTable()
end
function pace.Cut(obj)
pace.RecordUndoHistory()
pace.Copy(obj)
obj:Remove()
pace.RecordUndoHistory()
end
function pace.Paste(obj)
if not pace.Clipboard then return end
pace.RecordUndoHistory()
local newObj = pac.CreatePart(pace.Clipboard.self.ClassName)
newObj:SetTable(pace.Clipboard, true)
newObj:SetParent(obj)
pace.RecordUndoHistory()
end
function pace.PasteProperties(obj)
if not pace.Clipboard then return end
pace.RecordUndoHistory()
local tbl = pace.Clipboard
tbl.self.Name = nil
tbl.self.ParentUID = nil
tbl.self.UniqueID = nil
tbl.children = {}
obj:SetTable(tbl)
pace.RecordUndoHistory()
end
function pace.Clone(obj)
pace.RecordUndoHistory()
obj:Clone()
pace.RecordUndoHistory()
end
function pace.RemovePart(obj)
pace.RecordUndoHistory()
obj:Remove()
pace.RecordUndoHistory()
pace.RefreshTree()
if not obj:HasParent() and obj.ClassName == "group" then
pace.RemovePartOnServer(obj:GetUniqueID(), false, true)
end
end
function pace.OnPartMenu(obj)
local menu = DermaMenu()
menu:SetPos(input.GetCursorPos())
if obj then
if not obj:HasParent() then
menu:AddOption(L"wear", function() pace.SendPartToServer(obj) end):SetImage(pace.MiscIcons.wear)
end
menu:AddOption(L"copy", function() pace.Copy(obj) end):SetImage(pace.MiscIcons.copy)
menu:AddOption(L"paste", function() pace.Paste(obj) end):SetImage(pace.MiscIcons.paste)
menu:AddOption(L"cut", function() pace.Cut(obj) end):SetImage('icon16/cut.png')
menu:AddOption(L"paste properties", function() pace.PasteProperties(obj) end):SetImage(pace.MiscIcons.replace)
menu:AddOption(L"clone", function() pace.Clone(obj) end):SetImage(pace.MiscIcons.clone)
menu:AddSpacer()
end
pace.AddRegisteredPartsToMenu(menu, not obj)
menu:AddSpacer()
if obj then
local save, pnl = menu:AddSubMenu(L"save", function() pace.SaveParts() end)
pnl:SetImage(pace.MiscIcons.save)
add_expensive_submenu_load(pnl, function() pace.AddSaveMenuToMenu(save, obj) end)
end
local load, pnl = menu:AddSubMenu(L"load", function() pace.LoadParts() end)
add_expensive_submenu_load(pnl, function() pace.AddSavedPartsToMenu(load, false, obj) end)
pnl:SetImage(pace.MiscIcons.load)
if obj then
menu:AddSpacer()
menu:AddOption(L"remove", function() pace.RemovePart(obj) end):SetImage(pace.MiscIcons.clear)
end
menu:Open()
menu:MakePopup()
end
function pace.OnNewPartMenu()
pace.current_part = NULL
local menu = DermaMenu()
menu:MakePopup()
menu:SetPos(input.GetCursorPos())
pace.AddRegisteredPartsToMenu(menu)
menu:AddSpacer()
local load, pnl = menu:AddSubMenu(L"load", function() pace.LoadParts() end)
pnl:SetImage(pace.MiscIcons.load)
add_expensive_submenu_load(pnl, function() pace.AddSavedPartsToMenu(load, false, obj) end)
menu:AddOption(L"clear", function()
pace.ClearParts()
end):SetImage(pace.MiscIcons.clear)
end
end
do
pac.haloex = include("pac3/libraries/haloex.lua")
function pace.OnHoverPart(self)
local tbl = {}
local ent = self:GetOwner()
if ent:IsValid() then
table.insert(tbl, ent)
end
for _, child in ipairs(self:GetChildrenList()) do
local ent = self:GetOwner()
if ent:IsValid() then
table.insert(tbl, ent)
end
end
if #tbl > 0 then
local pulse = math.sin(pac.RealTime * 20) * 0.5 + 0.5
pulse = pulse * 255
pac.haloex.Add(tbl, Color(pulse, pulse, pulse, 255), 1, 1, 1, true, true, 5, 1, 1)
end
end
end
|
object_tangible_loot_creature_loot_collections_space_reactor_mark_01_freitek = object_tangible_loot_creature_loot_collections_space_shared_reactor_mark_01_freitek:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_space_reactor_mark_01_freitek, "object/tangible/loot/creature/loot/collections/space/reactor_mark_01_freitek.iff")
|
local vehicleDropPoints = {
-- x, y, z, rz
{ 2316.04, -2366.29, 13.55, 46.5 },
{ -1699.16, 401.86, 7.18, 230.3 },
{ 1639.13, 2193.94, 10.82 }
}
addEventHandler ( "onResourceStart", resourceRoot, function ( )
for i, v in ipairs ( vehicleDropPoints ) do
local x, y, z, rz = unpack ( v )
create3DText ( "Vehicle Recovery", { x, y, z }, { 255, 255, 255 } )
local marker = createMarker ( x, y, z-2, "cylinder", 5, 255, 255, 0, 80 )
setElementData ( marker, "NGJobs:Mechanic.DropPointRotation", rz )
addEventHandler ( "onMarkerHit", marker, function ( p )
if ( getElementType ( p ) == 'player' ) then
if ( isPedInVehicle ( p ) and getElementData ( p, "Job" ) == "Mechanic" and getElementModel ( getPedOccupiedVehicle ( p ) ) == 525 ) then
local car = getVehicleTowedByVehicle ( getPedOccupiedVehicle ( p ) )
if car then
local vehicleID = getElementData ( car, "NGVehicles:VehicleID" )
local vehicleOwner = getElementData ( car, "NGVehicles:VehicleAccountOwner" )
local name = getVehicleNameFromModel ( getElementModel ( car ) )
if vehicleID and vehicleOwner then
local owner = exports['NGPlayerFunctions']:getPlayerFromAcocunt ( vehicleOwner )
if owner then
exports['NGMessages']:sendClientMessage ( "Your "..name.." has been impounded.", owner, 255, 255, 0 )
end
exports['NGVehicles']:showVehicle ( vehicleID, false )
local cash = 1000 + math.random ( 0, 150 )
givePlayerMoney ( p, cash )
exports['NGMessages']:sendClientMessage ( "You have been paid $"..cash.." for impounding this vehicle.", p, 0, 255, 0 )
exports['NGSQL']:db_exec ( "UPDATE vehicles SET Impounded=? WHERE VehicleID=?", '1', vehicleID )
local acc = getAccountName ( getPlayerAccount ( p ) )
updateJobColumn ( acc, "TowedVehicles", "AddOne" )
else
exports['NGMessages']:sendClientMessage ( "This vehicle isn't owned.", p, 255, 255, 255 )
end
else
exports['NGMessages']:sendClientMessage ( "You require to be towing a vehicle to drop it.", p, 0, 255, 255 )
end
elseif ( not isPedInVehicle ( p ) ) then
local acc = getPlayerAccount ( p )
if isGuestAccount ( acc ) then return end
local cars = exports['NGSQL']:db_query ( "SELECT * FROM vehicles WHERE Owner=? AND Impounded=?", getAccountName ( acc ), '1' )
if ( #cars == 0 ) then
return exports['NGMessages']:sendClientMessage ( "You have no impounded vehicles!", p, 0, 255, 0 )
end
triggerClientEvent ( p, "NGJobs:Mechanic.OpenRecovery", p, cars, source )
end
end
end )
end
end )
addEvent ( "NGJobs:Mechanic.onPlayerRecoverVehicle", true )
addEventHandler ( "NGJobs:Mechanic.onPlayerRecoverVehicle", root, function ( id, marker, price )
if id and marker then
local x, y, z = getElementPosition ( marker )
local rz = getElementData ( marker, "NGJobs:Mechanic.DropPointRotation" ) or 0
veh = exports['NGVehicles']:showVehicle ( id, true )
setElementPosition ( veh, x, y, z + 3.5 )
setElementRotation ( veh, 0, 0, rz )
warpPedIntoVehicle ( source, veh )
exports['NGSQL']:db_exec ( "UPDATE vehicles SET Impounded=? WHERE VehicleID=?", '0', id )
takePlayerMoney ( source, price )
end
end )
local vehiclesBeingFixed = { }
local timer = { }
addEvent ( "NGJobs:Mechanic_AttemptFixVehicle", true )
addEventHandler ( "NGJobs:Mechanic_AttemptFixVehicle", root, function ( v )
if ( vehiclesBeingFixed[v] ) then
exports['NGMessages']:sendClientMessage ( "This vehicle is already being repaired.", source, 255, 0, 0 )
return triggerClientEvent ( source, "NGJobs:Mechanic_CancelFixingRequest", source, 'source', false )
end
local controller = getVehicleController ( v )
local price = (1000-(math.floor(getElementHealth(v))))
if ( getPlayerMoney ( controller ) >= price ) then
if ( price == 0 ) then
return exports['NGMessages']:sendClientMessage ( "This vehicle doesn't need to be fixed.", source, 255, 255, 0 )
end
exports['NGMessages']:sendClientMessage ( "Sending "..getPlayerName ( controller ).." a request that'll expire in 15 seconds.", source, 0, 255, 0 )
exports['NGMessages']:sendClientMessage ( getPlayerName ( source ).." wants to fix your vehicle for $"..tostring(price)..". Press 1 to accept, and 2 to deny", controller, 255, 255, 255 )
setElementFrozen ( v, true )
setElementFrozen ( source, true )
showCursor ( controller, true )
showCursor ( source, true )
vehiclesBeingFixed[v] = true
triggerClientEvent ( controller, "NGjobs:Mechanic_BindClientKeys", controller, source )
timer[v] = setTimer ( function ( s, p, v )
if ( isElement ( s ) ) then
triggerClientEvent ( s, "NGJobs:Mechanic_CancelFixingRequest", s, 'source' )
setElementFrozen ( s, false )
showCursor ( s, false )
end
if ( isElement ( p ) ) then
triggerClientEvent ( p, "NGJobs:Mechanic_CancelFixingRequest", p, 'client' )
setElementFrozen ( p, false )
showCursor ( p, false )
end
if ( isElement ( v ) ) then
setElementFrozen ( v, false )
vehiclesBeingFixed[v] = nil
end
end, 15000, 1, source, controller, v )
else
exports['NGMessages']:sendClientMessage ( "This player doesn't have enough money to pay you.", source, 255, 0, 0 )
end
end )
addEvent ( "NGJobs:Mech_OnClientAcceptFixing", true )
addEventHandler ( "NGJobs:Mech_OnClientAcceptFixing", root, function ( fixer )
local v = getPedOccupiedVehicle ( source )
if ( isTimer ( timer[v] ) ) then
killTimer ( timer[v] )
end
if ( isElement ( v ) and isElement ( fixer ) ) then
exports['NGMessages']:sendClientMessage ( "Your vehicle is beginning repairs by "..getPlayerName ( fixer )..".", source, 0, 255, 0 )
exports['NGMessages']:sendClientMessage ( "Beginning repairs...", fixer, 0, 255, 0 )
triggerClientEvent ( fixer, "NGMessages:Mechanic_OpenLoadingBar", fixer, source )
setVehicleDoorOpenRatio ( v, 0, 1 )
else
exports['NGMessages']:sendClientMessage ( "Failed!", source, 255, 0, 0 )
if ( isElement ( v ) ) then
setElementFrozen ( v, false )
end if ( isElement ( fixer ) ) then
setElementFrozen ( fixer, false )
showCursor ( fixer, false )
end
showCursor ( source, false )
vehiclesBeingFixed[v] = nil
end
end )
addEvent ( "NGJobs:Mech_OnClientDenyFixing", true )
addEventHandler ( "NGJobs:Mech_OnClientDenyFixing", root, function ( f )
setElementFrozen ( source, false )
setElementFrozen ( f, false )
showCursor ( source, false )
showCursor ( f, false )
local car = getPedOccupiedVehicle ( source )
if ( isElement ( car ) ) then
setElementFrozen ( car, false )
vehiclesBeingFixed[car] = nil
end
exports['NGMessages']:sendClientMessage ( getPlayerName ( source ).." has denied you to fix their vehicle.", f, 255, 0, 0 )
exports['NGMessages']:sendClientMessage ( "You denied "..getPlayerName ( f ).." to fix your vehicle.", source, 255, 255, 0 )
if ( isTimer ( timer[car] ) ) then
killTimer ( timer[car] )
end
triggerClientEvent ( f, 'NGJobs:Mechanic_onDenied', f )
end )
addEvent ( "NGJobs:Mechanic_onVehicleCompleteFinish", true )
addEventHandler ( "NGJobs:Mechanic_onVehicleCompleteFinish", root, function ( p )
-- p = client being fixed
if ( isElement ( p ) ) then
local car = getPedOccupiedVehicle ( p )
if ( isElement ( car ) ) then
local price = (1000-(math.floor(getElementHealth(car))))
fixVehicle ( car )
local rx, ry, rz = getElementRotation ( car )
setElementRotation ( car, rx, 0, rz )
takePlayerMoney ( p, price )
givePlayerMoney ( source, price )
exports['NGMessages']:sendClientMessage ( "Your vehicle has been fixed for $"..tostring ( price ).."!", p, 0, 255, 0 )
exports['NGMessages']:sendClientMessage ( "You fixed "..getPlayerName ( p ).."'s vehicle and earned $"..tostring ( price ), source, 0, 255, 0 )
mechanic_reset ( p, source, car )
updateJobColumn ( getAccountName ( getPlayerAccount ( source ) ), "FixedVehicles", "AddOne" )
else
exports['NGMessages']:sendClientMessage ( "Failed to fix the vehicle - the vehicle doesn't exist.", source, 255, 0, 0 )
mechanic_reset ( p, source, car )
end
else
exports['NGMessages']:sendClientMessage ( "Failed to fix the vehicle - the client doesn't exist.", source, 255, 0, 0 )
mechanic_reset ( p, source, car )
end
end )
function mechanic_reset ( p, s, car )
if ( isElement ( p ) ) then
showCursor ( p, false )
setElementFrozen ( p, false )
end
if ( isElement ( s ) ) then
showCursor ( s, false )
setElementFrozen ( s, false )
end
if ( isElement ( car ) ) then
setElementFrozen ( car, false )
vehiclesBeingFixed[car] = nil
end
end
-- Turn off lights and close doors
-- of vehicle being towed
addEventHandler ( "onTrailerAttach", root, function ( t )
if ( getVehicleName ( t ) == "Towtruck" ) then
setVehicleOverrideLights ( source, 1 );
for i = 0, 5 do
setVehicleDoorState ( source, i, 0 )
end
end
end );
|
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
lootcollectiontierdiamond = {
description = "",
minimumLevel = 0,
maximumLevel = 0,
lootItems = {
{groupTemplate = "theme_park_reward_rebel_mon_mothma", weight = 312500},
{groupTemplate = "jabba_theme_park_bib", weight = 312500},
{groupTemplate = "janta_common", weight = 312500},
{groupTemplate = "minor_gorax", weight = 312500},
{groupTemplate = "axkva_min", weight = 312500},
{groupTemplate = "krayt_tissue_rare", weight = 312500},
{groupTemplate = "peko_albatross", weight = 312500},
{groupTemplate = "rancor_common", weight = 312500},
{groupTemplate = "harrower_bone", weight = 312500},
{groupTemplate = "gurk_king_common", weight = 312500},
{groupTemplate = "giant_dune_kimo_common", weight = 312500},
{groupTemplate = "krayt_tissue_uncommon", weight = 312500},
{groupTemplate = "geonosian_cubes", weight = 312500},
{groupTemplate = "fire_breathing_spider", weight = 312500},
{groupTemplate = "acklay", weight = 312500},
{groupTemplate = "nightsister_common", weight = 312500},
{groupTemplate = "gorax_common", weight = 312500},
{groupTemplate = "theme_park_reward_rebel_qualdo_herm", weight = 312500},
{groupTemplate = "theme_park_reward_rebel_c_3po", weight = 312500},
{groupTemplate = "jabba_theme_park_reelo", weight = 312500},
{groupTemplate = "chemistry_component", weight = 312500},
{groupTemplate = "chemistry_component_advanced", weight = 312500},
{groupTemplate = "weapon_component", weight = 312500},
{groupTemplate = "weapon_component_advanced", weight = 312500},
{groupTemplate = "theme_park_reward_imperial_kaja", weight = 312500},
{groupTemplate = "theme_park_reward_imperial_kaja", weight = 312500},
{groupTemplate = "kimogila_common", weight = 312500},
{groupTemplate = "geonosian_common", weight = 312500},
{groupTemplate = "fire_breathing_spider", weight = 312500},
{groupTemplate = "junk", weight = 312500},
{groupTemplate = "nightsister_common", weight = 312500},
{groupTemplate = "mythosaur_common", weight = 312500},
}
}
addLootGroupTemplate("lootcollectiontierdiamond", lootcollectiontierdiamond)
|
--- Native Lua implementation of filesystem and platform abstractions,
-- using LuaFileSystem, LZLib, MD5 and LuaCurl.
module("luarocks.fs.lua", package.seeall)
local fs = require("luarocks.fs")
local cfg = require("luarocks.cfg")
local dir = require("luarocks.dir")
local util = require("luarocks.util")
local path = require("luarocks.path")
local socket_ok, http = pcall(require, "socket.http")
local _, ftp = pcall(require, "socket.ftp")
local zip_ok, lrzip = pcall(require, "luarocks.tools.zip")
local unzip_ok, luazip = pcall(require, "zip"); _G.zip = nil
local lfs_ok, lfs = pcall(require, "lfs")
local md5_ok, md5 = pcall(require, "md5")
local posix_ok, posix = pcall(require, "posix")
local tar = require("luarocks.tools.tar")
local patch = require("luarocks.tools.patch")
local dir_stack = {}
math.randomseed(os.time())
dir_separator = "/"
--- Quote argument for shell processing.
-- Adds single quotes and escapes.
-- @param arg string: Unquoted argument.
-- @return string: Quoted argument.
function Q(arg)
assert(type(arg) == "string")
-- FIXME Unix-specific
return "'" .. arg:gsub("\\", "\\\\"):gsub("'", "'\\''") .. "'"
end
local function normalize(name)
return name:gsub("\\", "/"):gsub("/$", "")
end
--- Test is file/dir is writable.
-- Warning: testing if a file/dir is writable does not guarantee
-- that it will remain writable and therefore it is no replacement
-- for checking the result of subsequent operations.
-- @param file string: filename to test
-- @return boolean: true if file exists, false otherwise.
function is_writable(file)
assert(file)
file = normalize(file)
local result
if fs.is_dir(file) then
local file2 = dir.path(file, '.tmpluarockstestwritable')
local fh = io.open(file2, 'wb')
result = fh ~= nil
if fh then fh:close() end
os.remove(file2)
else
local fh = io.open(file, 'r+b')
result = fh ~= nil
if fh then fh:close() end
end
return result
end
--- Create a temporary directory.
-- @param name string: name pattern to use for avoiding conflicts
-- when creating temporary directory.
-- @return string or nil: name of temporary directory or nil on failure.
function make_temp_dir(name)
assert(type(name) == "string")
name = normalize(name)
local temp_dir = (os.getenv("TMP") or "/tmp") .. "/luarocks_" .. name:gsub(dir.separator, "_") .. "-" .. tostring(math.floor(math.random() * 10000))
if fs.make_dir(temp_dir) then
return temp_dir
else
return nil
end
end
--- Run the given command, quoting its arguments.
-- The command is executed in the current directory in the dir stack.
-- @param command string: The command to be executed. No quoting/escaping
-- is applied.
-- @param ... Strings containing additional arguments, which are quoted.
-- @return boolean: true if command succeeds (status code 0), false
-- otherwise.
function execute(command, ...)
assert(type(command) == "string")
for _, arg in ipairs({...}) do
assert(type(arg) == "string")
command = command .. " " .. fs.Q(arg)
end
return fs.execute_string(command)
end
--- Check the MD5 checksum for a file.
-- @param file string: The file to be checked.
-- @param md5sum string: The string with the expected MD5 checksum.
-- @return boolean: true if the MD5 checksum for 'file' equals 'md5sum', false if not
-- or if it could not perform the check for any reason.
function check_md5(file, md5sum)
file = normalize(file)
local computed = fs.get_md5(file)
if not computed then
return false
end
if computed:match("^"..md5sum) then
return true
else
return false
end
end
---------------------------------------------------------------------
-- LuaFileSystem functions
---------------------------------------------------------------------
if lfs_ok then
--- Run the given command.
-- The command is executed in the current directory in the dir stack.
-- @param cmd string: No quoting/escaping is applied to the command.
-- @return boolean: true if command succeeds (status code 0), false
-- otherwise.
function execute_string(cmd)
local code = os.execute(cmd)
if code == 0 or code == true then
return true
else
return false
end
end
--- Obtain current directory.
-- Uses the module's internal dir stack.
-- @return string: the absolute pathname of the current directory.
function current_dir()
return lfs.currentdir()
end
--- Change the current directory.
-- Uses the module's internal dir stack. This does not have exact
-- semantics of chdir, as it does not handle errors the same way,
-- but works well for our purposes for now.
-- @param d string: The directory to switch to.
function change_dir(d)
table.insert(dir_stack, lfs.currentdir())
d = normalize(d)
lfs.chdir(d)
end
--- Change directory to root.
-- Allows leaving a directory (e.g. for deleting it) in
-- a crossplatform way.
function change_dir_to_root()
table.insert(dir_stack, lfs.currentdir())
lfs.chdir("/") -- works on Windows too
end
--- Change working directory to the previous in the dir stack.
-- @return true if a pop ocurred, false if the stack was empty.
function pop_dir()
local d = table.remove(dir_stack)
if d then
lfs.chdir(d)
return true
else
return false
end
end
--- Create a directory if it does not already exist.
-- If any of the higher levels in the path name does not exist
-- too, they are created as well.
-- @param directory string: pathname of directory to create.
-- @return boolean: true on success, false on failure.
function make_dir(directory)
assert(type(directory) == "string")
directory = normalize(directory)
local path = nil
if directory:sub(2, 2) == ":" then
path = directory:sub(1, 2)
directory = directory:sub(4)
else
if directory:match("^/") then
path = ""
end
end
for d in directory:gmatch("([^"..dir.separator.."]+)"..dir.separator.."*") do
path = path and path .. dir.separator .. d or d
local mode = lfs.attributes(path, "mode")
if not mode then
if not lfs.mkdir(path) then
return false
end
elseif mode ~= "directory" then
return false
end
end
return true
end
--- Remove a directory if it is empty.
-- Does not return errors (for example, if directory is not empty or
-- if already does not exist)
-- @param d string: pathname of directory to remove.
function remove_dir_if_empty(d)
assert(d)
d = normalize(d)
lfs.rmdir(d)
end
--- Remove a directory if it is empty.
-- Does not return errors (for example, if directory is not empty or
-- if already does not exist)
-- @param d string: pathname of directory to remove.
function remove_dir_tree_if_empty(d)
assert(d)
d = normalize(d)
for i=1,10 do
lfs.rmdir(d)
d = dir.dir_name(d)
end
end
--- Copy a file.
-- @param src string: Pathname of source
-- @param dest string: Pathname of destination
-- @param perms string or nil: Permissions for destination file,
-- or nil to use the source filename permissions
-- @return boolean or (boolean, string): true on success, false on failure,
-- plus an error message.
function copy(src, dest, perms)
assert(src and dest)
src = normalize(src)
dest = normalize(dest)
local destmode = lfs.attributes(dest, "mode")
if destmode == "directory" then
dest = dir.path(dest, dir.base_name(src))
end
if not perms then perms = fs.get_permissions(src) end
local src_h, err = io.open(src, "rb")
if not src_h then return nil, err end
local dest_h, err = io.open(dest, "w+b")
if not dest_h then src_h:close() return nil, err end
while true do
local block = src_h:read(8192)
if not block then break end
dest_h:write(block)
end
src_h:close()
dest_h:close()
fs.chmod(dest, perms)
return true
end
--- Implementation function for recursive copy of directory contents.
-- Assumes paths are normalized.
-- @param src string: Pathname of source
-- @param dest string: Pathname of destination
-- @return boolean or (boolean, string): true on success, false on failure
local function recursive_copy(src, dest)
local srcmode = lfs.attributes(src, "mode")
if srcmode == "file" then
local ok = fs.copy(src, dest)
if not ok then return false end
elseif srcmode == "directory" then
local subdir = dir.path(dest, dir.base_name(src))
fs.make_dir(subdir)
for file in lfs.dir(src) do
if file ~= "." and file ~= ".." then
local ok = recursive_copy(dir.path(src, file), subdir)
if not ok then return false end
end
end
end
return true
end
--- Recursively copy the contents of a directory.
-- @param src string: Pathname of source
-- @param dest string: Pathname of destination
-- @return boolean or (boolean, string): true on success, false on failure,
-- plus an error message.
function copy_contents(src, dest)
assert(src and dest)
src = normalize(src)
dest = normalize(dest)
assert(lfs.attributes(src, "mode") == "directory")
for file in lfs.dir(src) do
if file ~= "." and file ~= ".." then
local ok = recursive_copy(dir.path(src, file), dest)
if not ok then
return false, "Failed copying "..src.." to "..dest
end
end
end
return true
end
--- Implementation function for recursive removal of directories.
-- Assumes paths are normalized.
-- @param name string: Pathname of file
-- @return boolean or (boolean, string): true on success,
-- or nil and an error message on failure.
local function recursive_delete(name)
local mode = lfs.attributes(name, "mode")
if mode == "file" then
return os.remove(name)
elseif mode == "directory" then
for file in lfs.dir(name) do
if file ~= "." and file ~= ".." then
local ok, err = recursive_delete(dir.path(name, file))
if not ok then return nil, err end
end
end
local ok, err = lfs.rmdir(name)
if not ok then return nil, err end
end
return true
end
--- Delete a file or a directory and all its contents.
-- @param name string: Pathname of source
-- @return boolean: true on success, false on failure.
function delete(name)
name = normalize(name)
return recursive_delete(name) or false
end
--- List the contents of a directory.
-- @param at string or nil: directory to list (will be the current
-- directory if none is given).
-- @return table: an array of strings with the filenames representing
-- the contents of a directory.
function list_dir(at)
assert(type(at) == "string" or not at)
if not at then
at = fs.current_dir()
end
at = normalize(at)
if not fs.is_dir(at) then
return {}
end
local result = {}
for file in lfs.dir(at) do
if file ~= "." and file ~= ".." then
table.insert(result, file)
end
end
return result
end
--- Implementation function for recursive find.
-- Assumes paths are normalized.
-- @param cwd string: Current working directory in recursion.
-- @param prefix string: Auxiliary prefix string to form pathname.
-- @param result table: Array of strings where results are collected.
local function recursive_find(cwd, prefix, result)
for file in lfs.dir(cwd) do
if file ~= "." and file ~= ".." then
local item = prefix .. file
table.insert(result, item)
local pathname = dir.path(cwd, file)
if lfs.attributes(pathname, "mode") == "directory" then
recursive_find(pathname, item..dir_separator, result)
end
end
end
end
--- Recursively scan the contents of a directory.
-- @param at string or nil: directory to scan (will be the current
-- directory if none is given).
-- @return table: an array of strings with the filenames representing
-- the contents of a directory.
function find(at)
assert(type(at) == "string" or not at)
if not at then
at = fs.current_dir()
end
at = normalize(at)
if not fs.is_dir(at) then
return {}
end
local result = {}
recursive_find(at, "", result)
return result
end
--- Test for existance of a file.
-- @param file string: filename to test
-- @return boolean: true if file exists, false otherwise.
function exists(file)
assert(file)
file = normalize(file)
return type(lfs.attributes(file)) == "table"
end
--- Test is pathname is a directory.
-- @param file string: pathname to test
-- @return boolean: true if it is a directory, false otherwise.
function is_dir(file)
assert(file)
file = normalize(file)
return lfs.attributes(file, "mode") == "directory"
end
--- Test is pathname is a regular file.
-- @param file string: pathname to test
-- @return boolean: true if it is a file, false otherwise.
function is_file(file)
assert(file)
file = normalize(file)
return lfs.attributes(file, "mode") == "file"
end
function set_time(file, time)
file = normalize(file)
return lfs.touch(file, time)
end
end
---------------------------------------------------------------------
-- LuaZip functions
---------------------------------------------------------------------
if zip_ok then
function zip(zipfile, ...)
return lrzip.zip(zipfile, ...)
end
end
if unzip_ok then
--- Uncompress files from a .zip archive.
-- @param zipfile string: pathname of .zip archive to be extracted.
-- @return boolean: true on success, false on failure.
function unzip(zipfile)
local zipfile, err = luazip.open(zipfile)
if not zipfile then return nil, err end
local files = zipfile:files()
local file = files()
repeat
if file.filename:sub(#file.filename) == "/" then
fs.make_dir(dir.path(fs.current_dir(), file.filename))
else
local rf, err = zipfile:open(file.filename)
if not rf then zipfile:close(); return nil, err end
local contents = rf:read("*a")
rf:close()
local wf, err = io.open(dir.path(fs.current_dir(), file.filename), "wb")
if not wf then zipfile:close(); return nil, err end
wf:write(contents)
wf:close()
end
file = files()
until not file
zipfile:close()
return true
end
end
---------------------------------------------------------------------
-- LuaSocket functions
---------------------------------------------------------------------
if socket_ok then
local ltn12 = require("ltn12")
local luasec_ok, https = pcall(require, "ssl.https")
local redirect_protocols = {
http = http,
https = luasec_ok and https,
}
local function http_request(url, http, loop_control)
local result = {}
local res, status, headers, err = http.request { url = url, proxy = cfg.proxy, redirect = false, sink = ltn12.sink.table(result) }
if not res then
return nil, status
elseif status == 301 or status == 302 then
local location = headers.location
if location then
local protocol, rest = dir.split_url(location)
if redirect_protocols[protocol] then
if not loop_control then
loop_control = {}
elseif loop_control[location] then
return nil, "Redirection loop -- broken URL?"
end
loop_control[url] = true
return http_request(location, redirect_protocols[protocol], loop_control)
else
return nil, "URL redirected to unsupported protocol - install luasec to get HTTPS support."
end
end
return nil, err
elseif status ~= 200 then
return nil, err
else
return table.concat(result)
end
end
--- Download a remote file.
-- @param url string: URL to be fetched.
-- @param filename string or nil: this function attempts to detect the
-- resulting local filename of the remote file as the basename of the URL;
-- if that is not correct (due to a redirection, for example), the local
-- filename can be given explicitly as this second argument.
-- @return boolean: true on success, false on failure.
function download(url, filename)
assert(type(url) == "string")
assert(type(filename) == "string" or not filename)
filename = dir.path(fs.current_dir(), filename or dir.base_name(url))
local content, err
if util.starts_with(url, "http:") then
content, err = http_request(url, http)
elseif util.starts_with(url, "ftp:") then
content, err = ftp.get(url)
elseif util.starts_with(url, "https:") then
if luasec_ok then
content, err = http_request(url, https)
else
err = "Unsupported protocol - install luasec to get HTTPS support."
end
else
err = "Unsupported protocol"
end
if not content then
return false, tostring(err)
end
local file = io.open(filename, "wb")
if not file then return false end
file:write(content)
file:close()
return true
end
end
---------------------------------------------------------------------
-- MD5 functions
---------------------------------------------------------------------
if md5_ok then
--- Get the MD5 checksum for a file.
-- @param file string: The file to be computed.
-- @return string: The MD5 checksum
function get_md5(file)
file = fs.absolute_name(file)
local file = io.open(file, "rb")
if not file then return false end
local computed = md5.sumhexa(file:read("*a"))
file:close()
return computed
end
end
---------------------------------------------------------------------
-- POSIX functions
---------------------------------------------------------------------
if posix_ok then
local octal_to_rwx = {
["0"] = "---",
["1"] = "--x",
["2"] = "-w-",
["3"] = "-wx",
["4"] = "r--",
["5"] = "r-x",
["6"] = "rw-",
["7"] = "rwx",
}
function chmod(file, mode)
-- LuaPosix (as of 5.1.15) does not support octal notation...
if mode:sub(1,1) == "0" then
local new_mode = {}
for c in mode:sub(2):gmatch(".") do
table.insert(new_mode, octal_to_rwx[c])
end
mode = table.concat(new_mode)
end
local err = posix.chmod(file, mode)
return err == 0
end
function get_permissions(file)
return posix.stat(file, "mode")
end
end
---------------------------------------------------------------------
-- Other functions
---------------------------------------------------------------------
--- Apply a patch.
-- @param patchname string: The filename of the patch.
-- @param patchdata string or nil: The actual patch as a string.
function apply_patch(patchname, patchdata)
local p, all_ok = patch.read_patch(patchname, patchdata)
if not all_ok then
return nil, "Failed reading patch "..patchname
end
if p then
return patch.apply_patch(p, 1)
end
end
--- Move a file.
-- @param src string: Pathname of source
-- @param dest string: Pathname of destination
-- @return boolean or (boolean, string): true on success, false on failure,
-- plus an error message.
function move(src, dest)
assert(src and dest)
if fs.exists(dest) and not fs.is_dir(dest) then
return false, "File already exists: "..dest
end
local ok, err = fs.copy(src, dest)
if not ok then
return false, err
end
ok = fs.delete(src)
if not ok then
return false, "Failed move: could not delete "..src.." after copy."
end
return true
end
--- Check if user has write permissions for the command.
-- Assumes the configuration variables under cfg have been previously set up.
-- @param flags table: the flags table passed to run() drivers.
-- @return boolean or (boolean, string): true on success, false on failure,
-- plus an error message.
function check_command_permissions(flags)
local root_dir = path.root_dir(cfg.rocks_dir)
local ok = true
local err = ""
for _, dir in ipairs { cfg.rocks_dir, root_dir, dir.dir_name(root_dir) } do
if fs.exists(dir) and not fs.is_writable(dir) then
ok = false
err = "Your user does not have write permissions in " .. dir
break
end
end
if ok then
return true
else
if flags["local"] then
err = err .. " \n-- please check your permissions."
else
err = err .. " \n-- you may want to run as a privileged user or use your local tree with --local."
end
return nil, err
end
end
|
vim.lsp.handlers["textDocument/definition"] = function(_, _, result)
if not result or vim.tbl_isempty(result) then
print("[LSP] Could not find definition")
return
end
if vim.tbl_islist(result) then
vim.lsp.util.jump_to_location(result[1])
else
vim.lsp.util.jump_to_location(result)
end
end
|
-- Copyright 2016 The Charon Platform Authors.
-- All rights reserved.
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE file.
--
-- Helpers in charon platform follow similiar principle of Velocity Framework
-- http://stackoverflow.com/questions/4201142/rails-style-template-helpers-in-velocity
-- Examples:
-- <% local img = helper:img("pdf.png") -%>
-- <%= helper:floatField("total", {default = 0.0})
-- <%= helper:link{ text = 'cancel', url = {controller = "cancel"} } -%>
-- or
-- <a href="<%= helper:url{ action = 'cancel' } -%>">cancel</a>
local Form = require "charon.Helper.FormHelper"
local url = require "charon.net.url"
local toboolean = require "charon.toboolean"
local dispatcher = require 'charon.dispatcher'
local Helper = {}
local cache = {}
Helper.publicPath = "public"
function Helper:hiddenField(field, value)
value = value or ""
local html = [[<input type="hidden" id="%s" name="%s" value=%q>]]
return string.format(html, field:normalize(), field, value)
end
function Helper:textField(field, value, options)
local value = value or ""
local options = options or {}
local style = options.style or "width:250px"
local html = [[<input type="text" id="%s" name="%s" value=%q style=%q]]
local html = string.format(html, field:normalize(), field, value, style)
if options.onblur then
html = html .. string.format(" onblur=%q ", options.onblur)
end
if options.onfocus then
html = html .. string.format(" onfocus=%q ", options.onfocus)
end
if options.onkeypress then
html = html .. string.format(" onkeypress=%q ", options.onkeypress)
end
if options.onkeyup then
html = html .. string.format(" onkeyup=%q ", options.onkeyup)
end
if options.disabled then
html = html .. ' disabled'
end
return (html .. ' />')
end
function Helper:textArea(field, value, options)
local value = value or ""
local options = options or {}
local style = options.style or "width:250px;height:65px"
local html = [[<textarea id="%s" name="%s" style=%q]]
local html = string.format(html, field:normalize(), field, style)
if options.onblur then
html = html .. string.format(" onblur=%q ", options.onblur)
end
if options.onfocus then
html = html .. string.format(" onfocus=%q ", options.onfocus)
end
if options.onkeypress then
html = html .. string.format(" onkeypress=%q ", options.onkeypress)
end
if options.onkeyup then
html = html .. string.format(" onkeyup=%q ", options.onkeyup)
end
return html .. string.format('>%s</textarea>', value)
end
function Helper:floatField(field, value, options)
options = options or {}
options.onblur = options.onblur or "inputBlur( this )"
options.onfocus = options.onfocus or "inputFocus( this )"
options.onkeypress = options.onkeypress or "inputPress( this, event )"
options.onkeyup = options.onkeyup or "format_invert(this, '**.***.***,**')"
options.style = options.style or "width:95px;text-align:right"
return Helper:textField(field, value, options)
end
function Helper:intField(field, value, options)
options = options or {}
options.onblur = options.onblur or "inputBlur( this )"
options.onfocus = options.onfocus or "inputFocus( this )"
options.onkeypress = options.onkeypress or "inputPress( this, event )"
options.onkeyup = options.onkeyup or "format_invert(this, '***.***.***')"
options.style = options.style or "width:95px;text-align:right"
return Helper:textField(field, value, options)
end
function Helper:dateField(field, value, options)
options = options or {}
options.onblur = options.onblur or "inputBlur( this )"
options.onfocus = options.onfocus or "inputFocus( this )"
options.onkeypress = options.onkeypress or "inputPress( this, event )"
options.onkeyup = options.onkeyup or "format_invert(this, '**/**/****')"
options.style = options.style or "width:80px;text-align:right"
local html = Helper:textField(field, value, options)
local calendar = [[<script>jQuery.calendar('#%s')</script>]]
return html .. string.format(calendar, field:normalize(), options)
end
function Helper:negativeLabel()
return 'not'
end
function Helper:positiveLabel()
return 'yes'
end
function Helper:boolField(field, value, options)
local options = options or {}
local html = ""
local label = ""
local checked = ""
-- positive option
label = options.positive or self:positiveLabel()
if toboolean(value) == true then
checked = "checked"
else
checked = ""
end
html = html .. string.format([[<input type="radio" name=%q value="true" %s > %s ]], field, checked, label)
-- negative option
label = options.negative or self:negativeLabel()
if toboolean(value) == false then
checked = "checked"
else
checked = ""
end
html = html .. string.format([[<input type="radio" name=%q value="false" %s > %s ]], field, checked, label)
-- blank option
if options.blank ~= nil then
label = options.blank
if value == "" or value == nil then
checked = "checked"
else
checked = ""
end
html = html .. string.format([[<input type="radio" name=%q value="" %s > %s ]], field, checked, label)
end
return html
end
function Helper:selectList(field, list, field_value, field_description, value, options)
options = options or {}
local html = "<select "
local option = "<option value=%q %s >%s</option>"
local selected = ""
local style = options.style or "width:250px"
if options.multiple then
if options.multiple == true then
options.multiple = 5
end
html = html .. string.format([[ multiple="multiple" size=%q ]], options.multiple)
end
html = html .. [[ id=%q name=%q style=%q>]]
html = string.format(html, field:normalize(), field, style)
if options.blank then
local blank = ""
if type(options.blank) == 'string' then
blank = options.blank
end
html = html .. string.format(option, "", "", blank)
end
for row in list:each() do
if row[field_value] == value then
selected = 'selected'
else
selected = ''
end
html = html .. string.format(option, row[field_value], selected, row[field_description])
end
html = html .. "</select>"
return html
end
function Helper:selectHash(field, list, value, options)
options = options or {}
local html = "<select "
local option = "<option value=%q %s >%s</option>"
local selected = ""
if options.multiple then
if options.multiple == true then
options.multiple = 5
end
html = html .. string.format([[ multiple="multiple" size=%q ]], options.multiple)
end
html = html .. [[ id=%q name=%q style="width:250px;">]]
html = string.format(html, field:normalize(), field)
if options.blank then
local blank = ""
if type(options.blank) == 'string' then
blank = options.blank
end
html = html .. string.format(option, "", "", blank)
end
for k, v in pairs(list) do
if k == value then
selected = 'selected'
else
selected = ''
end
html = html .. string.format(option, k, selected, v)
end
html = html .. "</select>"
return html
end
function Helper:fileTimestamp(file_name)
if cache[file_name] == nil or CHARON_ENV ~= 'production' then
if os.exists(Helper.publicPath .. file_name) then
cache[file_name] = os.ctime(Helper.publicPath .. file_name)
else
cache[file_name] = 0
end
end
return cache[file_name]
end
function Helper:javascript(file_name)
local html = [[<script src="%s%s?%i" type="text/javascript"></script>]]
file_name = string.format("/javascripts/%s.js", file_name)
return string.format(html, self.controller.prefix, file_name, self:fileTimestamp(file_name))
end
function Helper:stylesheet(file_name)
local html = [[<link href="%s%s?%i" media="screen" rel="stylesheet" type="text/css" />]]
file_name = string.format("/stylesheets/%s.css", file_name)
return string.format(html, self.controller.prefix, file_name, self:fileTimestamp(file_name))
end
function Helper:img(file_name, options)
local options = options or {}
local title = options.title or file_name:left(file_name:lastIndexOf('.') - 1)
local html = [[<img src="%s%s?%i" title="%s" />]]
file_name = string.format("/images/%s", file_name)
return string.format(html, self.controller.prefix, file_name, self:fileTimestamp(file_name), title)
end
function Helper:imgPath(file_name)
local html = '%s?%i'
file_name = string.format("%s/images/%s", self.controller.prefix, file_name)
return string.format(html, file_name, self:fileTimestamp(file_name))
end
function Helper:formCreate(instance_or_name, name)
local data
if type(instance_or_name) == 'string' then
data = self.controller[instance_or_name]
else
data = instance_or_name
end
return Form.new{ data = data, name = (name or 'form'), controller = self.controller, helper = self }
end
function Helper:url(params)
if type(params) == 'string' then
return params
end
local controller = params.controller or self.controllerName or 'index'
local action = params.action or 'index'
if self.controller.prefix then
controller = self.controller.prefix .. '/' .. controller
end
params.action = nil
params.controller = nil
local result = params.path or (controller .. '/' .. action)
local query = url.buildQuery(params)
if #query > 0 then
result = result .. '?' .. query
end
return result
end
function Helper:urlPerform()
local action = self.actionName:gsub("Perform", "") .. "Perform"
return self:url{ action = action }
end
function Helper:link(params)
local html = [[<a href=%q]]
html = string.format(html, self:url(params.url))
if params.remote then
html = html .. string.format(" data-remote=%q ", "true")
end
if params.after then
html = html .. string.format(" data-after=%q ", params.after)
end
if params.click then
html = html .. string.format(" onclick=%q ", params.click )
end
if params.update then
html = html .. string.format(" data-update=%q ", params.update)
end
if params.confirm then
html = html .. string.format(" data-confirm=%q ", params.confirm)
end
if params.with and params.remote then
html = html .. string.format(" data-with=%q ", params.with)
end
if params.condition then
html = html .. string.format(" data-condition=%q ", params.condition)
end
if params.style then
html = html .. string.format(" style=%q ", params.style)
end
if params.class then
html = html .. string.format(" class=%q ", params.class)
end
if params.title then
html = html .. string.format(" title=%q ", params.title)
end
html = html .. '>'
if params.img then
html = html .. self:img(params.img, {title = params.title})
else
html = html .. params.text
end
html = html .. "</a>"
return html
end
-------------------------------------------------------------------------------
-- AUTO COMPLETE
-------------------------------------------------------------------------------
function Helper:autoComplete(field, resource, options)
local options = options or {}
local field_value = options.field_value or "value"
local field_description = options.field_description or "label"
local url = self:url(resource)
local style = options.style or "width:250px"
local html = [[<input type="text" id="%s" name="%s" style=%q>]]
local select = options.select or ""
html = string.format(html, field:normalize(), field, style)
html = html .. string.format([[
<script>
jQuery(function() {
jQuery( "#%s" ).autocomplete({
source: function(request, response) {
jQuery.ajax({
url: '%s',
dataType: 'jsonp',
jsonp: 'json_callback',
data: {
field: %q,
featureClass: 'P',
style: 'full',
limit: 10,
busca: request.term
},
success: function( data ){
response( jQuery.map( data, function( item ) {
return {
label: item.%s,
value: item.%s,
attributes: item
}
}));
},
error: function(params1, params2, params3) {
//alert(params1+' - '+params2+' - '+params3);
}
})
},
select: function(event, ui) { %s; },
minLength: 1
});
});
</script>]], field:normalize(), url, field, field_description, field_value, select)
return html
end
function Helper:dateFormat(value)
return value
end
function Helper:dateTimeFormat(value)
return value
end
function Helper:boolFormat(value, positive, negative)
if toboolean(value) then
return positive or 'yes'
else
return negative or 'no'
end
end
-- nl2br
-- converte em uma string todos os \n para <br>
function Helper:nl2br(value)
return tostring(value):replace('\n', '<br>')
end
return Helper
|
Wago = {}
Wago.LoadOptionToggle = function(option)
return '\z
<div class="WA-option col-sm-6 col-md-3">\z
<div class="input-group">\z
<span class="input-group-addon input-toggle" data-field="use_'..option.name..'" id="chk_use_'..option.name..'"><span class="icon-checkbox-unchecked"></span> '..option.display..'</span>\z
<input type="hidden" class="form-control" id="opt_use_'..option.name..'" data-field="use_'..option.name..'" >\z
</div>\z
</div>'
end
Wago.LoadOptionTristate = function(option)
return '\z
<div class="WA-option col-sm-6 col-md-3">\z
<div class="input-group">\z
<span class="input-group-addon input-tristate" data-field="use_'..option.name..'" id="chk_use_'..option.name..'"><span class="icon-checkbox-unchecked"></span> '..option.display..'</span>\z
<input type="hidden" class="form-control" id="opt_use_'..option.name..'" data-field="use_'..option.name..'" >\z
</div>\z
</div>'
end
Wago.LoadOptionString = function(option, lookup)
local lookup_class = ""
local lookup_attr = ""
if lookup then
lookup_class = "lookup-data"
lookup_attr = 'data-lookup="'..lookup..'"'
end
return '\z
<div class="WA-option col-sm-12 col-md-6">\z
<div class="input-group">\z
<span class="input-group-addon input-toggle-field" data-field="use_'..option.name..'" data-textfield="'..option.name..'" id="chk_use_'..option.name..'"><span class="icon-checkbox-unchecked"></span> '..option.display..'</span>\z
<input type="hidden" class="form-control" id="opt_use_'..option.name..'" data-field="use_'..option.name..'" >\z
<input type="text" class="form-control '..lookup_class..'" id="opt_'..option.name..'" '..lookup_attr..' disabled data-field="'..option.name..'" >\z
</div>\z
</div>'
end
Wago.LoadOptionNumber = function(option)
return '\z
<div class="WA-option col-sm-12 col-md-6">\z
<div class="input-group">\z
<span class="input-group-addon input-toggle-field" data-field="use_'..option.name..'" '..option.name..' data-textfield="'..option.name..'" data-opfield="op_'..option.name..'" id="chk_use_'..option.name..'"><span class="icon-checkbox-unchecked"></span> '..option.display..'</span>\z
<input type="hidden" class="form-control" id="opt_use_'..option.name..'" data-field="use_'..option.name..'" >\z
<div class="input-group-btn">\z
<a class="btn btn-secondary dropdown-toggle disabled" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">>\z
<input type="hidden" value=">" class="inputValue" data-field="'..option.name..'_operator" />\z
</a>\z
<div class="dropdown-menu">\z
<a class="dropdown-item" href="#">></a>\z
<a class="dropdown-item" href="#">>=</a>\z
<a class="dropdown-item" href="#">==</a>\z
<a class="dropdown-item" href="#"><=</a>\z
<a class="dropdown-item" href="#"><</a>\z
</div>\z
</div>\z
<input type="number" class="form-control" id="opt_'..option.name..'" disabled data-field="'..option.name..'" >\z
</div>\z
</div>'
end
Wago.LoadOptionMultiselect = function(option)
local values
if type(WeakAuras[option.values])=="function" then
values = WeakAuras[option.values]({})
else
values = WeakAuras[option.values]
end
local options = ""
local values2 = {}
if type(values)=="table" then
for i, v in pairs(values) do
if type(v)=="string" or type(v)=="number" then
if string.find(v, '|[cC][fF][fF]')==1 then -- if val starts with a color code then remove it
v = string.sub(v, 11, -3)
table.insert(values2, v)
end
options = options .. '<option value="'..i..'">'..v..#values2..'</option>'
end
end
-- if our table values were modified then sort new values and restart population
if #values2>0 then
table.sort(values2)
options = ""
for i, v in pairs(values2) do
if type(v)=="string" or type(v)=="number" then
options = options .. '<option value="'..i..'">'..v..'</option>'
end
end
end
end
local str = '\z
<div class="WA-option col-sm-12 col-md-6">\z
<div class="input-group">\z
<span class="input-group-addon input-toggle-field" data-field="use_'..option.name..'" data-selectfield="'..option.name..'" id="chk_use_'..option.name..'"><span class="icon-checkbox-unchecked"></span> '..option.display..'</span>\z
<input type="hidden" class="form-control" id="use_'..option.name..'">\z
<select name="categories[]" multiple id="opt_'..option.name..'" class="input-multiselect" disabled>'..options..'</select>\z
</div>\z
</div>'
return str
end
Wago.SetupLoadOptions = function(WeakAuras)
local window = js.global
local document = window.document
local panel = document:getElementById( 'load-editor' )
local L = WeakAuras.L
local function_strings = WeakAuras.function_strings
local anim_function_strings = WeakAuras.anim_function_strings
local anim_presets = WeakAuras.anim_presets
local load_prototype = WeakAuras.load_prototype
local event_prototypes = WeakAuras.event_prototypes
for index, arg in pairs(load_prototype.args) do
if arg.type=="toggle" then
panel.innerHTML = panel.innerHTML .. Wago.LoadOptionToggle(arg)
elseif arg.type=="tristate" then
panel.innerHTML = panel.innerHTML .. Wago.LoadOptionTristate(arg)
elseif arg.type=="string" then
panel.innerHTML = panel.innerHTML .. Wago.LoadOptionString(arg)
elseif arg.type=="spell" then
panel.innerHTML = panel.innerHTML .. Wago.LoadOptionString(arg, arg.type)
elseif arg.type=="number" then
panel.innerHTML = panel.innerHTML .. Wago.LoadOptionNumber(arg)
elseif arg.type=="multiselect" then
panel.innerHTML = panel.innerHTML .. Wago.LoadOptionMultiselect(arg)
else
panel.innerHTML = panel.innerHTML .. "<div class='col-sm-12'>"..arg.display.." ("..arg.type..")</div>"
end
end
end
|
assert(42 == 42)
|
--- Syntax sugar for event manipulation.
-- Along with the list of functions below, this module dynamically generates syntax-shortcuts for all @{defines.events}
-- events. These shortcuts are only to be used when registering a handler to a single event. To register a handler to
-- multiple events, use @{event.register}.
--
-- To use a shortcut, replace `event.register(defines.events.on_built_entity, handler, filters)` with
-- `event.on_built_entity(handler, filters)`. You can also deregister the handler using `event.on_built_entity(nil)`.
-- @module event
-- @alias flib_event
-- @usage local event = require("__flib__.event")
-- @see event.lua
local flib_event = {}
-- generate syntax shortcuts
for name, id in pairs(defines.events) do
flib_event[name] = function(handler, filters)
return script.on_event(id, handler, filters)
end
end
--- Functions
-- @section
--- Register or deregister a handler to be run during mod init.
-- @function on_init
-- @tparam function|nil handler The handler to register, or `nil` to deregister the registered handler.
-- @usage
-- -- register a handler to run during mod init
-- event.on_init(function() log("on_init") end)
-- -- deregister the registered handler, if one exists
-- event.on_init(nil)
flib_event.on_init = script.on_init
--- Register or deregister a handler to be run during mod load.
-- @function on_load
-- @tparam function|nil handler The handler to register, or `nil` to deregister the registered handler.
-- @usage
-- -- register a handler to run during mod load
-- event.on_load(function() log("on_load") end)
-- -- deregister the registered handler, if one exists
-- event.on_load(nil)
flib_event.on_load = script.on_load
--- Register or deregister a handler to be run when mod configuration changes.
-- @function on_configuration_changed
-- @tparam function|nil handler The handler to register, or `nil` to deregister the registered handler.
-- @usage
-- -- register a handler to run when mod configuration changes
-- event.on_configuration_changed(function() log("on_configuration_changed") end)
-- -- deregister the registered handler, if one exists
-- event.on_configuration_changed(nil)
flib_event.on_configuration_changed = script.on_configuration_changed
--- Register or deregister a handler to run every N ticks.
-- @function on_nth_tick
-- @tparam number nth_tick
-- @tparam function|nil handler The handler to register, or `nil` to deregister the registered handler.
-- @usage
-- -- register a handler to run every 30 ticks
-- event.on_nth_tick(30, function(e) log("30th tick!") end)
-- -- deregister the registered handler, if one exists
-- event.on_nth_tick(30, nil)
flib_event.on_nth_tick = script.on_nth_tick
-- TODO Nexela link EventFilters to https://lua-api.factorio.com/latest/Event-Filters.html
--- Register or deregister a handler to or from an event or group of events.
-- Unlike `script.on_event`, `event.register` supports adding compatible filters to multiple events at once.
-- Additionally, `event.register` supports registering to custom-inputs and other events simultaneously.
-- @tparam EventId|EventId[] ids
-- @tparam function|nil handler The handler to register, or `nil` to deregister the registered handler.
-- @tparam[opt] EventFilters filters
-- @usage
-- -- register a handler to a defines.events event that supports filters
-- event.register(defines.events.on_built_entity, function(e) log("ghost built!") end, {{filter="ghost"}})
-- -- register a handler to a custom-input
-- event.register("my-input", function(e) log("my-input pressed!") end)
-- -- register a handler to multiple events of different types
-- event.register({"my-input", defines.events.on_lua_shortcut}, function(e) log("do something!") end)
-- -- deregister a handler from a single event, if one is registered
-- event.register("my-input", nil)
-- -- deregister a handler from multiple events, if one is registered
-- event.register({"my-input", defines.events.on_lua_shortcut}, nil)
function flib_event.register(ids, handler, filters)
if type(ids) ~= "table" then
ids = {ids}
end
for i = 1, #ids do
-- the game doesn't like you passing filters to events that don't support them, even if they're `nil`
if filters then
script.on_event(ids[i], handler, filters)
else
script.on_event(ids[i], handler)
end
end
return
end
--- Register an entity to raise `on_entity_destroyed` when it's destroyed.
-- @function register_on_entity_destroyed
-- Once an entity is registered it's registered forever (until it's destroyed) and persists through save/load.
--
-- Registered is global across all mods: once an entity is registered the event will be fired for all mods when its
-- destroyed.
--
-- An entity registered multiple times will only fire the event once and gives back the same registration number.
--
-- Depending on when a given entity is destroyed on_entity_destroyed will be fired at the end of the current tick or end
-- of the next tick.
-- @tparam LuaEntity entity The entity to register.
-- @treturn number The registration number.
flib_event.register_on_entity_destroyed = script.register_on_entity_destroyed
--- Generate a new, unique event ID.
-- @function generate_id
-- @treturn number
-- @usage
-- -- generate a new event ID
-- local my_event = event.generate_id()
-- -- raise that event with custom parameters
-- event.raise(my_event, {whatever_you_want=true, ...})
flib_event.generate_id = script.generate_event_name
--- Retrieve the handler for an event, if one exists.
-- @function get_handler
-- @tparam EventId id
-- @treturn function The registered handler, or `nil` if one isn't registered.
flib_event.get_handler = script.get_event_handler
-- TODO Nexela link EventData to https://lua-api.factorio.com/latest/events.html
--- Raise an event as if it were actually called.
-- @function raise
-- This will only work for events that actually support being raised, and custom mod events.
-- @tparam EventId id
-- @tparam table event_data The event data that will be passed to the handlers.
-- @usage
-- event.raise(defines.events.on_gui_click, {player_index=e.player_index, element=my_button, ...})
flib_event.raise = script.raise_event
--- Retrieve the mod event order.
-- @function get_order
-- @treturn string
flib_event.get_order = script.get_event_order
--- Set the filters for the given event(s).
-- @tparam EventId|EventId[] ids
-- @tparam EventFilters filters The filters to set, or `nil` to clear the filters.
-- @usage
-- -- set the filters for a single event
-- event.set_filters(defines.events.on_built_entity, {
-- {filter="ghost"},
-- {filter="type", type="assembling-machine"}
-- })
-- -- set the filters for multiple events that have compatible formats
-- event.set_filters({defines.events.on_built_entity, defines.events.on_robot_built_entity}, {
-- {filter="ghost"},
-- {filter="type", type="assembling-machine"}
-- })
-- -- clear event filters if any are set
-- event.set_filters(defines.events.on_robot_built_entity, nil)
function flib_event.set_filters(ids, filters)
if type(ids) ~= "table" then
ids = {ids}
end
for i = 1, #ids do
script.set_event_filter(ids[i], filters)
end
return
end
--- Retrieve the filters for the given event.
-- @function get_filters
-- @tparam EventId id
-- @treturn EventFilters filters The filters, or `nil` if there are none defined.
flib_event.get_filter = script.get_event_filter
--- Concepts
-- @section
--- @Concept EventId
-- One of the following:
-- <ul>
-- <li>A member of @{defines.events}.</li>
-- <li>A positive @{number} corresponding to a custom event ID.</li>
-- <li>A @{string} corresponding to a custom-input name.</li>
-- </ul>
return flib_event
|
require 'csvigo'
dofile("Code/utils.lua")
function buildCNN(input_path, inputfile, outputpath)
mydata = csvigo.load({path = input_path .. inputfile , mode = "large", verbose = false})
print("data loaded and tokenized...")
-- Initialize padding length
pad_l = {}
for i = 1, #mydata[1] do
pad_l[i] = 0
end
for i=1, #mydata do
for j=1, #pad_l do
pad_l[j] = math.max( pad_l[j], #mydata[i][j]:split(" "))
end
end
print("beging sentence padding...")
spadlen = 0
for j= 4, 125 do
spadlen = math.max(spadlen, pad_l[j])
end
sentences = {}
for j = 1, 125 do
print(string.format("processing column %i with padding %i", j, pad_l[j]))
tmp = {}
for i = 2, #mydata do
tmp[i - 1] = mydata[i][j]:split(" ")
end
if j == 2 then
queries = torch.Tensor(padZeros(tmp, pad_l[2] ))
end
if j == 3 then
trueSummary = torch.Tensor(padZeros(tmp, pad_l[3] ))
end
if j > 3 then
-- # of sentence tokens
sentences[j - 3] = torch.Tensor(padZeros(tmp, spadlen))
end
end
print("...data exported to torch datafiles")
torch.save(outputpath .. "cnn_data_ss.dat", {queries, trueSummary, sentences} )
end
input_path = "/home/francisco/GitHub/DQN-Event-Summarization/data/cnn_tokenized_ss/"
outputpath = "/home/francisco/GitHub/DQN-Event-Summarization/data/training_ss/"
inputfile = 'cnn_data_ss.csv'
buildCNN(input_path, inputfile, outputpath)
|
--3L·苍空之舞-墨染之樱
local m=37564819
local cm=_G["c"..m]
if not pcall(function() require("expansions/script/c37564765") end) then require("script/c37564765") end
function cm.initial_effect(c)
senya.leff(c,m)
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(m,0))
e3:SetCategory(senya.fuscate())
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_HAND+LOCATION_MZONE)
e3:SetCountLimit(1,m)
e3:SetTarget(cm.sptg)
e3:SetOperation(cm.spop)
c:RegisterEffect(e3)
end
function cm.effect_operation_3L(c,ctlm)
local e=senya.icopy(c,ctlm)
e:SetReset(RESET_EVENT+0x1fe0000)
e:SetDescription(m*16+1)
e:SetCost(senya.desccost(e:GetCost()))
c:RegisterEffect(e,true)
return e
end
function cm.spfilter2(c,e,tp,m,f,gc,chkf)
return c:IsType(TYPE_FUSION) and (not f or f(c))
and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_FUSION,tp,false,false) and c:CheckFusionMaterial(m,gc,chkf) and senya.check_set_3L(c)
end
function cm.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then
local chkf=Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and PLAYER_NONE or tp
local mg1=senya.GetFusionMaterial(tp,nil,nil,nil,c)
local res=Duel.IsExistingMatchingCard(cm.spfilter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg1,nil,c,chkf)
if not res then
local ce=Duel.GetChainMaterial(tp)
if ce~=nil then
local fgroup=ce:GetTarget()
local mg2=fgroup(ce,e,tp)
local mf=ce:GetValue()
res=Duel.IsExistingMatchingCard(cm.spfilter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg2,mf,c,chkf)
end
end
return res
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function cm.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
local chkf=Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and PLAYER_NONE or tp
local mg1=senya.GetFusionMaterial(tp,nil,nil,nil,c,e)
local sg1=Duel.GetMatchingGroup(cm.spfilter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg1,nil,c,chkf)
local mg2=nil
local sg2=nil
local ce=Duel.GetChainMaterial(tp)
if ce~=nil then
local fgroup=ce:GetTarget()
mg2=fgroup(ce,e,tp)
local mf=ce:GetValue()
sg2=Duel.GetMatchingGroup(cm.spfilter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg2,mf,c,chkf)
end
if sg1:GetCount()>0 or (sg2~=nil and sg2:GetCount()>0) then
local sg=sg1:Clone()
if sg2 then sg:Merge(sg2) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local tg=sg:Select(tp,1,1,nil)
local tc=tg:GetFirst()
if sg1:IsContains(tc) and (sg2==nil or not sg2:IsContains(tc) or not Duel.SelectYesNo(tp,ce:GetDescription())) then
local mat1=Duel.SelectFusionMaterial(tp,tc,mg1,c,chkf)
tc:SetMaterial(mat1)
Duel.SendtoGrave(mat1,REASON_EFFECT+REASON_MATERIAL+REASON_FUSION)
Duel.BreakEffect()
Duel.SpecialSummon(tc,SUMMON_TYPE_FUSION,tp,tp,false,false,POS_FACEUP)
else
local mat2=Duel.SelectFusionMaterial(tp,tc,mg2,c,chkf)
local fop=ce:GetOperation()
fop(ce,e,tp,tc,mat2)
end
tc:CompleteProcedure()
end
end
|
goto room1 -- initial room
::room1:: do
local move = io.read()
if move == "south" then goto room3
elseif move == "east" then goto room2
else
print("invalid move")
goto room1 -- stay in the same room
end
end
::room2:: do
local move = io.read()
if move == "south" then goto room4
elseif move == "west" then goto room1
else
print("invalid move")
goto room2
end
end
::room3:: do
local move = io.read()
if move == "north" then goto room1
elseif move == "east" then goto room4
else
print("invalid move")
goto room3
end
end
::room4:: do
print("Congratulations, you won!")
end
|
local has_telescope, telescope = pcall(require, 'telescope')
local main = require('telescope._extensions.mapper.main')
local utils = require('telescope._extensions.mapper.utils')
if not has_telescope then
error('This plugins requires nvim-telescope/telescope.nvim')
end
return telescope.register_extension{
setup = main.setup,
exports = { mapper = main.mapper }
}
|
-- This is the main module. Use init.lua to auto start this module.
--
-- main.lua connects to wifi first. If that works then MQTT broker connection
-- is established. If all goes well you should see "subscribed to node-000000-in".
-- Now you can send commands to the devices input topic such as:
--
-- Echo hello to devices console:
--
-- echo:hello
-- Turn LED connected to pin 1 (D1) on:
--
-- gpio_write:1,0
--
-- Use mosquitto client to test on broker:
--
-- mosquitto_pub -h localhost -t node-000000-in -m "echo:hello" -p 8883 --cafile /etc/mosquitto/ca_certificates/ca.crt -u <user_name> -P <password>
require "config"
require "wifi_connect"
require "mqtt_connect"
--- Write to GPIO pin.
-- @param client mqtt.Client: MQTT client.
-- @param params table: First parameter is the pin number and the second is
-- the value to set the pin to.
-- @param data string: Raw command string.
function gpio_write(client, params, data)
gpio.write(params[1], params[2])
-- Send output topic hostname:data
client:publish(mqtt_topic_out, wifi.sta.gethostname() .. ":OK:" .. data, 0, 0)
end
-- Commands mapped to function.
command = {
["echo"] = function (client, params, data) print(params[1]) end,
["gpio_write"] = gpio_write,
}
--- Write to GPIO pin.
-- @param str string: String to parse.
-- @return table: Table of split values.
function split(str, delim)
local words = {}
for x in string.gmatch(str, '([^' .. delim .. ']+)') do
table.insert(words, x)
end
return words
end
--- mqtt.Client message callback for input topic. Parses payload into command
-- and parameters. The format is command:param1,param2, ... The command table
-- is used to map to functions. Think of it as a poor man's command pattern.
-- If the command is found in the command table then it is executed.
-- @param client mqtt.Client: MQTT client.
-- @param topic string: Broker topic.
-- @param data string: Raw command string.
function mqtt_message(client, topic, data)
if data ~= nil then
-- Parse payload into command and params
local words = split(data, ':')
if command[words[1]] ~= nil then
-- Call function with params parsed into a table
command[words[1]](client, split(words[2], ','), data)
else
-- Unknown command
client:publish(mqtt_topic_out, wifi.sta.gethostname() .. ":" .. words[1] .. ":ERROR:Command not found", 0, 0)
end
else
-- nil payload
client:publish(mqtt_topic_out, wifi.sta.gethostname() .. ":ERROR:nil message", 0, 0)
end
end
--- wifi_connect callback after wifi connection established. Broker
-- connection is attempted next. Set mqtt.Client message callback to
-- mqtt_message.
function wifi_started()
mqtt_topic_in = wifi.sta.gethostname() .. "-in"
-- Only create mqtt.Client once
if m_client == nil then
mqtt_client(wifi.sta.gethostname(), mqtt_keepalive, mqtt_user, mqtt_password)
end
mqtt_connect(mqtt_host, mqtt_port, mqtt_topic_in)
m_client:on("message", mqtt_message)
end
-- Connect to wifi
wifi_connect(wifi_ip, wifi_netmask, wifi_gateway, wifi_ssid, wifi_pwd, wifi_started)
|
local _PATH = (...)
require(_PATH..".InputManager")
|
-- shared by WoG, MMExtension and GameExtension
local type = type
local unpack = unpack
local assert = assert
local format = string.format
local next = next
local pairs = pairs
local ipairs = ipairs
local tonumber = tonumber
local tostring = tostring
local rawget = rawget
local rawset = rawset
local getfenv = getfenv
local setfenv = setfenv
local pcall = pcall
local xpcall = xpcall
local getmetatable = debug.getmetatable
local d_setmetatable = debug.setmetatable
local d_getinfo = debug.getinfo
local os_time = os.time
local loadfile = loadfile
local loadstring = loadstring
local require = require
local table_insert = table.insert
local table_remove = table.remove
local table_concat = table.concat
local floor = math.floor
local ceil = math.ceil
local abs = math.abs
local string_sub = string.sub
local string_gsub = string.gsub
local string_match = string.match
local string_lower = string.lower
local coroutine_create = coroutine.create
local coroutine_resume = coroutine.resume
local coroutine_running = coroutine.running
local coroutine_main = coroutine.main
local dofile = dofile
local ffi = require "ffi"
local _G = _G
local internal = debug.getregistry() -- internals
local CoreScriptsPath = internal.CoreScriptsPath
local nullpersist = internal.nullpersist
local function setmetatable(t, m)
d_setmetatable(t, m)
return t
end
----------- Error function ------------
local error = _G.error
local SetErrorLevel = internal.SetErrorLevel
local error = function(msg, level)
SetErrorLevel(level or 1)
return error(msg, level)
end
_G.error = error
-----------
local function nullsub()
end
local offsets = offsets or {}
dofile(CoreScriptsPath.."RSFunctions.lua")
local table_swap = table.swap
local table_move = table.move
local PrintToFileStd = PrintToFile
function PrintToFile(fname)
internal.LogFileInfo = PrintToFileStd(fname)
end
PrintToFile("InternalLog.txt") -- temporary
----------- No globals from this point ------------
local _NOGLOBALS
----------- General functions ------------
local function assertnum(v, level, msg)
local v1 = tonumber(v)
if v1 then
return v1
end
return error(msg or "number expected, got "..type(v), level or 1)
end
_G.assertnum = assertnum
local function pcall2_ret(ok, ...)
if not ok then
internal.ErrorMessage((...))
end
return ok, ...
end
local function pcall2(...)
return pcall2_ret(pcall(...))
end
_G.pcall2 = pcall2
function _G.xpcall2(...)
return pcall2_ret(xpcall(...))
end
function _G.dofile2(path, ...)
local chunk, err = loadfile(path)
if chunk == nil then
internal.ErrorMessage(err)
return false, err
else
return pcall2_ret(pcall(chunk, ...))
end
end
local function coroutine_resume2(...)
return pcall2_ret(coroutine_resume(...))
end
_G.coroutine.resume2 = coroutine_resume2
-- pause/unpause game, synchronize keys state
internal.PauseGame = function() end
internal.ResumeGame = function() end
----------- mem ------------
local mem_internal = _G.mem
internal.RSMem = mem_internal
local mem = mem_internal
mem.pcall2 = pcall2
mem.free = offsets.free or mem.free
mem.StaticAlloc = mem.malloc
mem.malloc = offsets.malloc or mem.malloc
mem.realloc = offsets.realloc or mem.realloc
mem.new = offsets.new or mem.new
do
-- compile Asm string into bytecode string
local CompileAsm = internal.CompileAsm
mem.AsmProlog = [[
use32
ptr equ
macro pushstr string
{
local ..after
call ..after
db string,0
..after:
}
_loadreg_ equ
_loadreg_end_ equ
macro savereg a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20
{
if a1 eq
else
push a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 a17 a18 a19 a20
end if
_loadreg_ equ pop a20 a19 a18 a17 a16 a15 a14 a13 a12 a11 a10 a9 a8 a7 a6 a5 a4 a3 a2 a1
_loadreg_end_ equ _loadreg_
}
macro loadreg
{
if _loadreg_ eq pop
else
_loadreg_
end if
_loadreg_end_ equ
}
]]
mem.AsmEpilog = [[
if _loadreg_end_ eq pop
else
_loadreg_end_
end if]]
local StartCode, StartLines
local function check(s, level)
if type(s) ~= "string" then
error("string expected, got "..type(s), level + 1)
end
if mem.AsmProlog ~= StartCode then
StartCode, StartLines = string_gsub(mem.AsmProlog, "\n", "\n")
end
return StartCode..s..mem.AsmEpilog, StartLines
end
function mem.CompileAsm(level, FromMem)
if FromMem then
local macro, MacroLines = string_gsub([[
absolute equ near -%d +
]], "\n", "\n")
return function(s)
local s, n = check(s, level + 1)
return function(p)
local r, err = CompileAsm(format(macro, p or 0)..s, n + MacroLines)
return r or (error(err, FromMem + 1))
end
end
else
return function(s)
local r, err = CompileAsm(check(s, level + 1))
return r or (error(err, level + 1))
end
end
end
end
function mem.struct_callback(t, class, fields, offs, rofields)
local meta = getmetatable(t)
meta.members = fields
meta.offsets = offs
meta.class = class
return t
end
dofile(CoreScriptsPath.."RSMem.lua")
local mem = _G.mem
_G.table.destructor = mem.general.table_destructor
mem.general.table_destructor = nil
_G.table.copy(mem.general, _G)
mem.general = nil
local call = mem.call
local malloc = mem.malloc
local StaticAlloc = mem.StaticAlloc
local free = mem.free
local i4, i2, i1, u8, u4, u2, u1, pchar = mem.i4, mem.i2, mem.i1, mem.u8, mem.u4, mem.u2, mem.u1, mem.pchar
local mem_string = mem.string
local mem_copy = mem.copy
local mem_fill = mem.fill
local IgnoreProtection = mem.IgnoreProtection
function mem.StaticAlloc(size)
local p = StaticAlloc(size)
mem_fill(p, size)
return p
end
mem.prot = mem.IgnoreProtection
_G.package.path = CoreScriptsPath.."?.lua"
-- mobdebug
do
-- function _G.print(s) -- report mobdebug errors
-- error(s)
-- end
local debug = _G.debug
local mobdebug = require("mobdebug")
debug.mobdebug = mobdebug
debug.start = debug.mobdebug.start
debug.on = debug.mobdebug.on
debug.off = debug.mobdebug.off
debug.done = debug.mobdebug.done
debug.stop = debug.mobdebug.done
mobdebug.connecttimeout = 0.001
local serv = mobdebug.connect("localhost", mobdebug.port)
if serv then
serv:close()
else
_G.jit.on()
end
end
dofile(CoreScriptsPath.."dump.lua")
--------- bit
local bit = require("bit")
local bit_And = bit.band
local bit_Not = bit.bnot
_G.bit = bit
bit.Or = bit.bor
bit.And = bit.band
bit.Xor = bit.bxor
bit.AndNot = function(a, b)
return bit_And(a, bit_Not(b))
end
bit.Not = bit.bnot
local numIndex = _G.table.copy(bit)
do
local n = 1
for i = 0,63 do
bit[i] = n
n = n*2
end
end
function bit.ToTable(x, t)
t = t or {}
if x < 0 then x = x + 4294967296 end
local i = 1
local b = 1 -- current bit
local d = 2 -- current divider
while x >= b do
if x % d >= b then
t[i] = true
end
b = d
d = d*2
i = i + 1
end
return t
end
function bit.FromTable(t)
local x = 0
local b = 1
for i = 1,32 do
if t[i] then
x = x + b
end
b = b*2
end
if x < 2147483648 then
return x
end
return x - 4294967296
end
--------- math
-- function _G.math.round(val)
-- if val >= 0 then
-- return floor(val + 0.5)
-- else
-- return ceil(val - 0.5)
-- end
-- end
_G.math.round = bit.tobit
--------- numIndex
function numIndex.ToHex(v)
return format("%X", v)
end
numIndex.tohex = numIndex.ToHex
function numIndex.Div(v1, v2)
return floor(v1/v2)
-- if v1 > v2 then
-- floor
-- else
-- end
end
numIndex.div = numIndex.Div
numIndex.round = _G.math.round
numIndex.floor = _G.math.floor
numIndex.ceil = _G.math.ceil
setmetatable(0, {__index = numIndex})
--------- color
--color = {}
--
--function color.ToRGB(c)
-- local r = floor(c:And(63488)*33/8192)
-- local g = floor(c:And(2016)*65/512)
-- local b = floor(c:And(31)*33/4)
-- return r, g, b
--end
--
--function color.RGB(r, g, b)
-- return r:And(248)*256 + g:And(252)*8 + floor(b/8)
--end
--
----local function Color16To24(c)
---- local r = floor(c:And(63488)*33/8192)
---- local g = (c:And(2016)*65/2):And(65280)
---- local b = (c:And(31)*540672):And(16711680)
---- return r + g + b
----end
--------- os
if offsets.exit then
function _G.os.exit(code)
call(offsets.exit, 0, code or 0)
end
end
local FindStruct = mem.struct(function(define)
define
.u4 'FileAttributes'
.alt.u8x 'CreationTime'
.u4 'CreationTimeLow'
.u4 'CreationTimeHigh'
.alt.u8x 'LastAccessTime'
.u4 'LastAccessTimeLow'
.u4 'LastAccessTimeHigh'
.alt.u8x 'LastWriteTime'
.u4 'LastWriteTimeLow'
.u4 'LastWriteTimeHigh'
.i8 'FileSize'
.skip(8)
.string(260) 'FileName'
.string(14) 'AlternateFileName'
end)
local function findNext(data)
if data then
local ret = internal.FindNext(data)
if ret then
local m = getmetatable(data)
return m.path..ret, m.struct
end
end
end
function _G.path.find(filter, dir)
local data, path, p = internal.FindStart(filter, not not dir)
if data == nil then
return nullsub
end
local m = getmetatable(data)
m.path = path
m.__gc = internal.FindClose
m.__persist = nullpersist
m.struct = FindStruct:new(p)
return findNext, data
end
_G.path.Find = _G.path.find
local function FindFirst(filter, dir) -- instead of FileExists/DirectoryExists
local data, path, p = internal.FindStart(filter, not not dir)
if data then
local r = internal.FindNext(data)
internal.FindClose(data)
return r and path..r
end
end
_G.path.FindFirst = FindFirst
_G.path.findfirst = FindFirst
local dirBuf
local function GetCurrentDirectory()
dirBuf = dirBuf or malloc(260)
u1[dirBuf] = 0
call(internal.GetCurrentDirectory, 0, 260, dirBuf)
return mem_string(dirBuf)
end
_G.path.GetCurrentDirectory = GetCurrentDirectory
function _G.path.SetCurrentDirectory(dir)
-- return call(internal.SetCurrentDirectory, 0, dir) ~= 0
local s = GetCurrentDirectory()
call(internal.SetCurrentDirectory, 0, dir)
return s
end
local path_noslash = _G.path.noslash
local path_dir = _G.path.dir
local CreateDirectoryPtr = internal.CreateDirectory
local GetLastErrorPtr = internal.GetLastErrorPtr
local function DoCreateDir(dir)
-- 183 = already exists
return call(CreateDirectoryPtr, 0, dir, 0) ~= 0 or GetLastErrorPtr and call(GetLastErrorPtr, 0, dir, 0) == 183
end
local function CreateDirectory(dir)
dir = path_noslash(dir)
if dir == "" or #dir == 2 and string_sub(dir, -1) == ":" or DoCreateDir(dir) then
return true
end
local dir1 = path_dir(dir)
if dir1 ~= dir then
CreateDirectory(dir1)
end
return DoCreateDir(dir)
end
_G.path.CreateDirectory = CreateDirectory
local oldSave = _G.io.SaveString
--!-
function _G.io.SaveString(path, ...)
CreateDirectory(path_dir(path))
return oldSave(path, ...)
end
ffi.cdef[[
typedef enum {
FO_MOVE = 0x0001,
FO_COPY = 0x0002,
FO_DELETE = 0x0003,
FO_RENAME = 0x0004,
__FILEOP_FUNC_size = 0xFFFFFFFF
} FILEOP_FUNC;
typedef enum {
FOF_MULTIDESTFILES = 0x0001,
FOF_CONFIRMMOUSE = 0x0002,
FOF_SILENT = 0x0004, // don't create progress/report
FOF_RENAMEONCOLLISION = 0x0008,
FOF_NOCONFIRMATION = 0x0010, // Don't prompt the user.
FOF_WANTMAPPINGHANDLE = 0x0020, // Fill in SHFILEOPSTRUCT.hNameMappings
// Must be freed using SHFreeNameMappings
FOF_ALLOWUNDO = 0x0040,
FOF_FILESONLY = 0x0080, // on *.*, do only files
FOF_SIMPLEPROGRESS = 0x0100, // means don't show names of files
FOF_NOCONFIRMMKDIR = 0x0200, // don't confirm making any needed dirs
FOF_NOERRORUI = 0x0400, // don't put up error UI
FOF_NOCOPYSECURITYATTRIBS = 0x0800, // dont copy NT file Security Attributes
FOF_NORECURSION = 0x1000 // don't recurse into directories.
} FILEOP_FLAGS;
typedef struct {
void * hwnd;
FILEOP_FUNC wFunc;
const char * pFrom;
const char * pTo;
FILEOP_FLAGS fFlags;
bool fAnyOperationsAborted;
void * hNameMappings;
const char * lpszProgressTitle; // only used if FOF_SIMPLEPROGRESS
} SHFILEOPSTRUCTA, *LPSHFILEOPSTRUCTA;
int __stdcall SHFileOperationA(LPSHFILEOPSTRUCTA lpFileOp);
bool __stdcall DeleteFileA(const char *lpFileName);
bool __stdcall MoveFileA(const char *lpExistingFileName, const char *lpNewFileName);
bool __stdcall CopyFileA(const char *lpExistingFileName, const char *lpNewFileName, bool bFailIfExists);
]]
local SHFileOperation = ffi.load("Shell32", true).SHFileOperationA
local SHDeleteFlags = ffi.C.FOF_NOCONFIRMATION + ffi.C.FOF_NOERRORUI + ffi.C.FOF_SILENT
local DeleteFile = ffi.C.DeleteFileA
function _G.path.DeleteFile(fname, NoRecycle)
if not NoRecycle then
local fos = ffi.new("SHFILEOPSTRUCTA")
fos.wFunc = "FO_DELETE"
fos.pFrom = path_noslash(fname).."\000"
fos.fFlags = SHDeleteFlags
return SHFileOperation(fos) == 0;
else
return DeleteFile(fname);
end
end
_G.path.MoveFile = ffi.C.MoveFileA
_G.path.CopyFile = ffi.C.CopyFileA
ffi.cdef[[
typedef enum {
FILE_ATTRIBUTE_READONLY = 0x00000001,
FILE_ATTRIBUTE_HIDDEN = 0x00000002,
FILE_ATTRIBUTE_SYSTEM = 0x00000004,
FILE_ATTRIBUTE_DIRECTORY = 0x00000010,
FILE_ATTRIBUTE_ARCHIVE = 0x00000020,
FILE_ATTRIBUTE_DEVICE = 0x00000040,
FILE_ATTRIBUTE_NORMAL = 0x00000080,
FILE_ATTRIBUTE_TEMPORARY = 0x00000100,
FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200,
FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400,
FILE_ATTRIBUTE_COMPRESSED = 0x00000800,
FILE_ATTRIBUTE_OFFLINE = 0x00001000,
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000,
FILE_ATTRIBUTE_ENCRYPTED = 0x00004000,
__FILE_ATTRIBUTES_size = 0xFFFFFFFF
} FILE_ATTRIBUTES;
bool __stdcall PathRelativePathToA(char *outPath, const char *pszFrom, FILE_ATTRIBUTES dwAttrFrom, const char *pszTo, FILE_ATTRIBUTES dwAttrTo);
]]
local PathRelativePathTo = ffi.load("Shlwapi", true).PathRelativePathToA
local PathBuf = ffi.new("char[260]")
local attrFile = ffi.C.FILE_ATTRIBUTE_NORMAL
local attrDir = ffi.C.FILE_ATTRIBUTE_DIRECTORY + attrFile
function _G.path.GetRelativePath(from, to, isDir)
from = string_gsub(from, "/", "\\")
to = string_gsub(to, "/", "\\")
if PathRelativePathTo(PathBuf, from, attrDir, to, isDir and attrDir or attrFile) then
return ffi.string(PathBuf)
end
end
local AppPath = _G.AppPath or _G.path.addslash(_G.path.GetCurrentDirectory())
_G.AppPath = AppPath
--------- debug, events
local function FunctionFile(f)
if type(f) == "number" then
f = f + 1
end
local s = d_getinfo(f, "S").source
return s:sub(1, 1) == '@' and s:sub(2) or ""
end
_G.debug.FunctionFile = FunctionFile
dofile(CoreScriptsPath.."EventsList.lua")
|
-- NetHack 3.6 Barb.des $NHDT-Date: 1432512784 2015/05/25 00:13:04 $ $NHDT-Branch: master $:$NHDT-Revision: 1.9 $
-- Copyright (c) 1989 by Jean-Christophe Collet
-- Copyright (c) 1991 by M. Stephenson
-- NetHack may be freely redistributed. See license for details.
--
des.level_init({ style = "solidfill", fg = " " });
des.level_flags("mazelevel", "hardfloor")
des.map([[
..........PPP.........................................
...........PP.......................................... .......
..........PP...........-----..........------------------ ..........
...........PP..........+...|..........|....S...........|.. ............
..........PPP..........|...|..........|-----...........|... .............
...........PPP.........-----..........+....+...........|... .............
..........PPPPPPPPP...................+....+...........S.................
........PPPPPPPPPPPPP.........-----...|-----...........|................
......PPPPPPPPPPPPPP..P.......+...|...|....S...........| ...
.....PPPPPPP......P..PPPP.....|...|...------------------.. ...
....PPPPPPP.........PPPPPP....-----........................ ........
...PPPPPPP..........PPPPPPP.................................. ..........
....PPPPPPP........PPPPPPP.................................... ..........
.....PPPPP........PPPPPPP.........-----........................ ........
......PPP..PPPPPPPPPPPP...........+...|......................... .....
..........PPPPPPPPPPP.............|...|......................... ....
..........PPPPPPPPP...............-----......................... .
..............PPP.................................................
...............PP....................................................
................PPP...................................................
]]);
-- Dungeon Description
des.region(selection.area(00,00,75,19), "lit")
des.region(selection.area(24,03,26,04), "unlit")
des.region(selection.area(31,08,33,09), "unlit")
des.region(selection.area(35,14,37,15), "unlit")
des.region(selection.area(39,03,54,08), "lit")
des.region(selection.area(56,00,75,08), "unlit")
des.region(selection.area(64,09,75,16), "unlit")
-- Doors
des.door("open",23,03)
des.door("open",30,08)
des.door("open",34,14)
des.door("locked",38,05)
des.door("locked",38,06)
des.door("closed",43,03)
des.door("closed",43,05)
des.door("closed",43,06)
des.door("closed",43,08)
des.door("locked",55,06)
-- Stairs
des.stair("up", 05,02)
des.stair("down", 70,13)
-- Objects
des.object({ x = 42, y = 03 })
des.object({ x = 42, y = 03 })
des.object({ x = 42, y = 03 })
des.object({ x = 41, y = 03 })
des.object({ x = 41, y = 03 })
des.object({ x = 41, y = 03 })
des.object({ x = 41, y = 03 })
des.object({ x = 41, y = 08 })
des.object({ x = 41, y = 08 })
des.object({ x = 42, y = 08 })
des.object({ x = 42, y = 08 })
des.object({ x = 42, y = 08 })
des.object({ x = 71, y = 13 })
des.object({ x = 71, y = 13 })
des.object({ x = 71, y = 13 })
-- Random traps
des.trap("spiked pit",10,13)
des.trap("spiked pit",21,07)
des.trap("spiked pit",67,08)
des.trap("spiked pit",68,09)
des.trap()
des.trap()
des.trap()
des.trap()
-- Random monsters.
des.monster({ id = "ogre", x=12, y=09, peaceful=0 })
des.monster({ id = "ogre", x=18, y=11, peaceful=0 })
des.monster({ id = "ogre", x=45, y=05, peaceful=0 })
des.monster({ id = "ogre", x=45, y=06, peaceful=0 })
des.monster({ id = "ogre", x=47, y=05, peaceful=0 })
des.monster({ id = "ogre", x=46, y=05, peaceful=0 })
des.monster({ id = "ogre", x=56, y=03, peaceful=0 })
des.monster({ id = "ogre", x=56, y=04, peaceful=0 })
des.monster({ id = "ogre", x=56, y=05, peaceful=0 })
des.monster({ id = "ogre", x=56, y=06, peaceful=0 })
des.monster({ id = "ogre", x=57, y=03, peaceful=0 })
des.monster({ id = "ogre", x=57, y=04, peaceful=0 })
des.monster({ id = "ogre", x=57, y=05, peaceful=0 })
des.monster({ id = "ogre", x=57, y=06, peaceful=0 })
des.monster({ id = "ogre", peaceful=0 })
des.monster({ id = "ogre", peaceful=0 })
des.monster({ id = "ogre", peaceful=0 })
des.monster({ class = "O", peaceful=0 })
des.monster({ class = "T", peaceful=0 })
des.monster({ id = "rock troll", x=46, y=06, peaceful=0 })
des.monster({ id = "rock troll", x=47, y=06, peaceful=0 })
des.monster({ id = "rock troll", x=56, y=07, peaceful=0 })
des.monster({ id = "rock troll", x=57, y=07, peaceful=0 })
des.monster({ id = "rock troll", x=70, y=13, peaceful=0 })
des.monster({ id = "rock troll", peaceful=0 })
des.monster({ id = "rock troll", peaceful=0 })
des.monster({ class = "T", peaceful=0 })
|
local mod = DBM:NewMod("Brawlers", "DBM-Brawlers")
local L = mod:GetLocalizedStrings()
mod:SetRevision("20190416205700")
--mod:SetCreatureID(60491)
--mod:SetModelID(41448)
mod:SetZone(DBM_DISABLE_ZONE_DETECTION)
mod:RegisterEvents(
"ZONE_CHANGED_NEW_AREA",
"CHAT_MSG_MONSTER_YELL"
)
local warnQueuePosition = mod:NewAnnounce("warnQueuePosition2", 2, 132639, true)
local warnOrgPortal = mod:NewCastAnnounce(135385, 1)--These are rare casts and linked to achievement.
local warnStormPortal = mod:NewCastAnnounce(135386, 1)--So warn for them being cast
local specWarnOrgPortal = mod:NewSpecialWarningSpell(135385, nil, nil, nil, 1, 7)
local specWarnStormPortal = mod:NewSpecialWarningSpell(135386, nil, nil, nil, 1, 7)
local specWarnYourNext = mod:NewSpecialWarning("specWarnYourNext")
local specWarnYourTurn = mod:NewSpecialWarning("specWarnYourTurn")
local specWarnRumble = mod:NewSpecialWarning("specWarnRumble")
local berserkTimer = mod:NewBerserkTimer(123)--all fights have a 2 min enrage to 134545. some fights have an earlier berserk though.
mod:AddBoolOption("SpectatorMode", true)
mod:AddBoolOption("SpeakOutQueue", true)
mod:AddBoolOption("NormalizeVolume", true, "misc")
local playerIsFighting = false
local currentFighter = nil
local currentZoneID = select(8, GetInstanceInfo())
local modsStopped = false
local eventsRegistered = false
local lastRank = 0
local QueuedBuff = DBM:GetSpellInfo(132639)
local function setDialog(self, set)
if not self.Options.NormalizeVolume then return end
if set then
local soundVolume = tonumber(GetCVar("Sound_SFXVolume"))
self.Options.SoundOption = tonumber(GetCVar("Sound_DialogVolume")) or 1
DBM:Debug("Setting normalized volume to SFX volume of: "..soundVolume)
SetCVar("Sound_DialogVolume", soundVolume)
else
DBM:Debug("Exiting Brawlers Area, checking Sound")
if self.Options.SoundOption then
DBM:Debug("Restoring Dialog volume to saved value of: "..self.Options.SoundOption)
SetCVar("Sound_DialogVolume", self.Options.SoundOption)
self.Options.SoundOption = nil
end
end
end
--Fix for not registering events on reloadui or login while already inside brawlers guild.
if currentZoneID == 369 or currentZoneID == 1043 then
eventsRegistered = true
mod:RegisterShortTermEvents(
"SPELL_CAST_START 135385 135386",
"PLAYER_REGEN_ENABLED",
"UNIT_DIED",
"UNIT_AURA player"
)
mod:Unschedule(setDialog)
mod:Schedule(1, setDialog, mod, true)
end
function mod:PlayerFighting() -- for external mods
return playerIsFighting
end
function mod:SPELL_CAST_START(args)
if args.spellId == 135385 then
if not playerIsFighting then--Do not distract player in arena with special warning
specWarnOrgPortal:Show()
specWarnOrgPortal:Play("newportal")
else
warnOrgPortal:Show()
end
elseif args.spellId == 135386 then
if not playerIsFighting then--Do not distract player in arena with special warning
specWarnStormPortal:Show()
specWarnStormPortal:Play("newportal")
else
warnStormPortal:Show()
end
end
end
function mod:CHAT_MSG_MONSTER_YELL(msg, npc, _, _, target)
if npc ~= L.Bizmo and npc ~= L.Bazzelflange then return end
local isMatchBegin = true
--Search is for Rank <n> to avoid lines like "x has risen through the ranks" or something else along those lines.
if msg:find(L.Rank1, 1, true) or msg:find(L.Rank2, 1, true) or msg:find(L.Rank3, 1, true) or msg:find(L.Rank4, 1, true) or msg:find(L.Rank5, 1, true) or msg:find(L.Rank6, 1, true) or msg:find(L.Rank7, 1, true) or msg:find(L.Rank8, 1, true) then -- fix for ruRU clients.
currentFighter = target
elseif msg:find(L.Rumbler) then
--self:SendSync("MatchEnd")--End any other matches in progress
--isMatchBegin = false--And start a new match instead?
specWarnRumble:Show()
--He's targeting current fighter but it's not a match begin yell, the only other times this happens is on match end and 10 second pre berserk warning.
--This tries to filter pre berserk warnings then pass match end in a way that will definitely catch them all
--but might also incorrectly cancel berserk timer at 10 second pre berserk warning if a message filter isn't localized yet
--But it's still better to cancel berserk 10 seconds early, than to fail to end a match at all.
elseif currentFighter and (target == currentFighter) and not (msg:find(L.BizmoIgnored) or msg == L.BizmoIgnored or msg:find(L.BizmoIgnored2) or msg == L.BizmoIgnored2 or msg:find(L.BizmoIgnored3) or msg == L.BizmoIgnored3 or msg:find(L.BizmoIgnored4) or msg == L.BizmoIgnored4 or msg:find(L.BizmoIgnored5) or msg == L.BizmoIgnored5 or msg:find(L.BizmoIgnored6) or msg == L.BizmoIgnored6 or msg:find(L.BizmoIgnored7) or msg == L.BizmoIgnored7 or msg:find(L.BazzelIgnored) or msg == L.BazzelIgnored or msg:find(L.BazzelIgnored2) or msg == L.BazzelIgnored2 or msg:find(L.BazzelIgnored3) or msg == L.BazzelIgnored3 or msg:find(L.BazzelIgnored4) or msg == L.BazzelIgnored4 or msg:find(L.BazzelIgnored5) or msg == L.BazzelIgnored5 or msg:find(L.BazzelIgnored6) or msg == L.BazzelIgnored6 or msg:find(L.BazzelIgnored7) or msg == L.BazzelIgnored7) then
self:SendSync("MatchEnd")
isMatchBegin = false
else
isMatchBegin = false
end
if isMatchBegin then
if target == UnitName("player") then
specWarnYourTurn:Show()
playerIsFighting = true
end
if self:LatencyCheck() or not IsInGroup() then--If not in group always send sync regardless of latency, better to start match late then never start it at all.
self:SendSync("MatchBegin")
end
end
--Only boss with a custom berserk timer. His is 1 minute, but starts at different yell than 2 min berserk, so it's not actually 60 sec shorter but more like 50-55 sec shorter
--Need the yells for meatball too i guess? he has a 1 minute berserk as well?
if msg == L.Proboskus or msg:find(L.Proboskus) or msg == L.Proboskus2 or msg:find(L.Proboskus2) then
self:Schedule(2, function()
berserkTimer:Cancel()
berserkTimer:Start(58)
end)
end
end
--TODO: Maybe add a PLAYE_REGEN_DISABLED event that checks current target for deciding what special bars to start on engage.
function mod:PLAYER_REGEN_ENABLED()
--Backup for failed match end detection. this only works if you're grouped with the fighter. This is for when npc doesn't yell on victory or wipe.
if playerIsFighting then--We check playerIsFighting to filter bar brawls, this should only be true if we were ported into ring.
playerIsFighting = false
self:SendSync("MatchEnd")
end
end
function mod:UNIT_DIED(args)
if not args.destName then return end
--Another backup for when npc doesn't yell. This is a way to detect a wipe at least.
if currentFighter and args.destName == currentFighter and args:IsDestTypePlayer() then--They wiped.
self:SendSync("MatchEnd")
end
end
function mod:ZONE_CHANGED_NEW_AREA()
currentZoneID = select(8, GetInstanceInfo())
if currentZoneID == 369 or currentZoneID == 1043 then
playerIsFighting = false
currentFighter = nil
lastRank = 0
modsStopped = false
eventsRegistered = true
self:RegisterShortTermEvents(
"SPELL_CAST_START 135385 135386",
"PLAYER_REGEN_ENABLED",
"UNIT_DIED",
"UNIT_AURA player"
)
self:Unschedule(setDialog)
self:Schedule(1, setDialog, mod, true)
return
end--We returned to arena, reset variable
if modsStopped then return end--Don't need this to fire every time you change zones after the first.
self:Stop()
self:UnregisterShortTermEvents()
eventsRegistered = false
for i = 1, 7 do
local mod2 = DBM:GetModByName("BrawlRank" .. i)
if mod2 then
mod2:Stop()--Stop all timers and warnings
end
end
local mod3 = DBM:GetModByName("BrawlChallenges")
if mod3 then
mod3:Stop()--Stop all timers and warnings
end
local mod4 = DBM:GetModByName("BrawlLegacy")
if mod4 then
mod4:Stop()--Stop all timers and warnings
end
local mod5 = DBM:GetModByName("BrawlRumble")
if mod5 then
mod5:Stop()--Stop all timers and warnings
end
setDialog(self)
modsStopped = true
end
local startCallbacks, endCallbacks = {}, {}
function mod:OnMatchStart(callback)
table.insert(startCallbacks, callback)
end
function mod:OnMatchEnd(callback)
table.insert(endCallbacks, callback)
end
--Most group up for this so they can buff eachother for matches. Syncing should greatly improve reliability, especially for match end since the person fighting definitely should detect that (probably missing yells still)
function mod:OnSync(msg)
if msg == "MatchBegin" then
if not (currentZoneID == 369 or currentZoneID == 1043) then return end
if not eventsRegistered then
eventsRegistered = true
self:RegisterShortTermEvents(
"SPELL_CAST_START 135385 135386",
"PLAYER_REGEN_ENABLED",
"UNIT_DIED",
"UNIT_AURA player"
)
end
self:Stop()--Sometimes NPC doesn't yell when a match ends too early, if a new match begins we stop on begin before starting new stuff
berserkTimer:Start()
for i, v in ipairs(startCallbacks) do
v()
end
elseif msg == "MatchEnd" then
if not (currentZoneID == 369 or currentZoneID == 1043) then return end
currentFighter = nil
self:Stop()
--Boss from any rank can be fought by any rank now, so we just need to always cancel them all
for i, v in ipairs(endCallbacks) do
v()
end
for i = 1, 7 do
local mod2 = DBM:GetModByName("BrawlRank" .. i)
if mod2 then
mod2:Stop()--Stop all timers and warnings
end
end
local mod2 = DBM:GetModByName("BrawlChallenges")
if mod2 then
mod2:Stop()--Stop all timers and warnings
end
mod2 = DBM:GetModByName("BrawlLegacy")
if mod2 then
mod2:Stop()--Stop all timers and warnings
end
mod2 = DBM:GetModByName("BrawlRumble")
if mod2 then
mod2:Stop()--Stop all timers and warnings
end
end
end
do
function mod:UNIT_AURA(uId)
local currentQueueRank = select(16, DBM:UnitBuff("player", QueuedBuff))
if currentQueueRank and currentQueueRank ~= lastRank then
lastRank = currentQueueRank
if currentQueueRank ~= 0 then
if currentQueueRank == 1 then
specWarnYourNext:Show()
else
warnQueuePosition:Show(currentQueueRank)
end
end
if self.Options.SpeakOutQueue then
DBM:PlayCountSound(currentQueueRank)
end
end
end
end
|
screwdriver = {}
local function nextrange(x, max)
x = x + 1
if x > max then
x = 0
end
return x
end
screwdriver.ROTATE_FACE = 1
screwdriver.ROTATE_AXIS = 2
screwdriver.disallow = function(pos, node, user, mode, new_param2)
return false
end
screwdriver.rotate_simple = function(pos, node, user, mode, new_param2)
if mode ~= screwdriver.ROTATE_FACE then
return false
end
end
local USES = 200
-- Handles rotation
local function screwdriver_handler(itemstack, user, pointed_thing, mode)
if pointed_thing.type ~= "node" then
return
end
local pos = pointed_thing.under
if minetest.is_protected(pos, user:get_player_name()) then
minetest.record_protection_violation(pos, user:get_player_name())
return
end
local node = minetest.get_node(pos)
local ndef = minetest.registered_nodes[node.name]
-- Compute param2
local rotationPart = node.param2 % 32 -- get first 4 bits
local preservePart = node.param2 - rotationPart
local axisdir = math.floor(rotationPart / 4)
local rotation = rotationPart - axisdir * 4
if mode == screwdriver.ROTATE_FACE then
rotationPart = axisdir * 4 + nextrange(rotation, 3)
elseif mode == screwdriver.ROTATE_AXIS then
rotationPart = nextrange(axisdir, 5) * 4
end
local new_param2 = preservePart + rotationPart
local should_rotate = true
if ndef and ndef.on_rotate then -- Node provides a handler, so let the handler decide instead if the node can be rotated
-- Copy pos and node because callback can modify it
local result = ndef.on_rotate(vector.new(pos),
{name = node.name, param1 = node.param1, param2 = node.param2},
user, mode, new_param2)
if result == false then -- Disallow rotation
return
elseif result == true then
should_rotate = false
end
else
if not ndef or not ndef.paramtype2 == "facedir" or
(ndef.drawtype == "nodebox" and
not ndef.node_box.type == "fixed") or
node.param2 == nil then
return
end
if ndef.can_dig and not ndef.can_dig(pos, user) then
return
end
end
if should_rotate then
node.param2 = new_param2
minetest.swap_node(pos, node)
end
if not minetest.setting_getbool("creative_mode") then
itemstack:add_wear(65535 / (USES - 1))
end
return itemstack
end
-- Screwdriver
minetest.register_tool("screwdriver:screwdriver", {
description = "Screwdriver (left-click rotates face, right-click rotates axis)",
inventory_image = "screwdriver.png",
on_use = function(itemstack, user, pointed_thing)
screwdriver_handler(itemstack, user, pointed_thing, screwdriver.ROTATE_FACE)
return itemstack
end,
on_place = function(itemstack, user, pointed_thing)
screwdriver_handler(itemstack, user, pointed_thing, screwdriver.ROTATE_AXIS)
return itemstack
end,
})
minetest.register_craft({
output = "screwdriver:screwdriver",
recipe = {
{"default:steel_ingot"},
{"group:stick"}
}
})
minetest.register_alias("screwdriver:screwdriver1", "screwdriver:screwdriver")
minetest.register_alias("screwdriver:screwdriver2", "screwdriver:screwdriver")
minetest.register_alias("screwdriver:screwdriver3", "screwdriver:screwdriver")
minetest.register_alias("screwdriver:screwdriver4", "screwdriver:screwdriver")
|
-- ROBOPORT RELATED TECHNOLOGIES
data:extend({
-- Advanced roboports
{
type = "technology",
name = "roboport-charge-pads-1",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/roboport-charge-pads.png",
effects = { },
prerequisites = {
"logistic-robotics",
"construction-robotics"
},
unit = {
count = 100,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
},
time = 30
},
upgrade = true,
order = "c-k-f-a",
},
{
type = "technology",
name = "roboport-charge-pads-2",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/roboport-charge-pads.png",
effects = { },
prerequisites = {
"roboport-charge-pads-1"
},
unit = {
count = 150,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"utility-science-pack", 1},
},
time = 30
},
upgrade = true,
order = "c-k-f-b",
},
{
type = "technology",
name = "roboport-charge-pads-3",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/roboport-charge-pads.png",
effects = { },
prerequisites = {
"roboport-charge-pads-2"
},
unit = {
count = 250,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1},
},
time = 60
},
upgrade = true,
order = "c-k-f-c",
},
{
type = "technology",
name = "roboport-charge-pads-4",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/roboport-charge-pads.png",
effects = { },
prerequisites = {
"roboport-charge-pads-3"
},
unit = {
count = 350,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1},
{"space-science-pack", 1}
},
time = 60
},
upgrade = true,
order = "c-k-f-d",
},
-- Roboport Sensor Array
{
type = "technology",
name = "charting-roboports-1",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/charting-roboports.png",
effects = { },
prerequisites = {
"roboport-charge-pads-1",
--"electric-energy-distribution-2",
"modules"
},
unit = {
count = 200,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
},
time = 30
},
upgrade = true,
order = "c-k-f-g",
},
{
type = "technology",
name = "charting-roboports-2",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/charting-roboports.png",
effects = { },
prerequisites = {
"charting-roboports-1",
"roboport-charge-pads-4"
},
unit = {
count = 500,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1},
{"space-science-pack", 1}
},
time = 30
},
upgrade = true,
order = "c-k-f-h",
}
})
if (settings.startup["betterbots-enable-wired-roboports"].value) then
data:extend({
-- Wired Roboports
{
type = "technology",
name = "wired-roboports",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/wired-roboports.png",
effects = { },
prerequisites = {
"roboport-charge-pads-2",
"electric-energy-distribution-2",
"modules"
},
unit = {
count = 250,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1},
},
time = 30
},
--upgrade = true,
order = "c-k-f-e",
},
{
type = "technology",
name = "roboport-power-field",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/wired-roboports.png",
effects = { },
prerequisites = {
"wired-roboports",
},
unit = {
count = 450,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1},
{"space-science-pack", 1}
},
time = 30
},
--upgrade = true,
order = "c-k-f-f",
}
})
end
-- BOTS RELATED TECHNOLOGIES
data:extend({
-- Worker Robot Power Cells
{
type = "technology",
name = "worker-robots-battery-1",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/worker-robots-battery.png",
effects = {
{
type = "worker-robot-battery",
modifier = 0.15
}
},
prerequisites = {
"robotics"
},
unit = {
count = 50,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1}
},
time = 30
},
upgrade = true,
order = "c-k-f-a",
},
{
type = "technology",
name = "worker-robots-battery-2",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/worker-robots-battery.png",
effects = {
{
type = "worker-robot-battery",
modifier = 0.2
}
},
prerequisites = {
"worker-robots-battery-1"
},
unit = {
count = 100,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1}
},
time = 30
},
upgrade = true,
order = "c-k-f-b"
},
{
type = "technology",
name = "worker-robots-battery-3",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/worker-robots-battery.png",
effects = {
{
type = "worker-robot-battery",
modifier = 0.25
}
},
prerequisites = {
"worker-robots-battery-2"
},
unit = {
count = 150,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"utility-science-pack", 1}
},
time = 60
},
upgrade = true,
order = "c-k-f-c"
},
{
type = "technology",
name = "worker-robots-battery-4",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/worker-robots-battery.png",
effects = {
{
type = "worker-robot-battery",
modifier = 0.35
}
},
prerequisites = {
"worker-robots-battery-3"
},
unit = {
count = 250,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"utility-science-pack", 1}
},
time = 60
},
upgrade = true,
order = "c-k-f-d"
},
{
type = "technology",
name = "worker-robots-battery-5",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/worker-robots-battery.png",
effects = {
{
type = "worker-robot-battery",
modifier = 0.35
}
},
prerequisites = {
"worker-robots-battery-4"
},
unit = {
count = 500,
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1}
},
time = 60
},
upgrade = true,
order = "c-k-f-e"
},
{
type = "technology",
name = "worker-robots-battery-6",
icon_size = 128,
icon = "__BetterBotsWLK__/graphics/technology/worker-robots-battery.png",
effects = {
{
type = "worker-robot-battery",
modifier = 0.45
}
},
prerequisites = {
"worker-robots-battery-5"
},
unit = {
count_formula = "2^(L-6)*1000",
ingredients = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1},
{"space-science-pack", 1}
},
time = 60
},
max_level = "infinite",
upgrade = true,
order = "c-k-f-e"
},
})
|
require("jackaudio")
chans = 2
o = jackaudio.BlockingAudioIO("jacklua",chans,chans)
--start our jack client
o:start()
--connect our two outputs to the soundcard outputs
--connect our two inputs to the soundcard inputs
for i=0,chans-1 do
o:connectToPhysical(i,i)
o:connectFromPhysical(i,i)
end
--make a sine wave
x = 0
mul = math.pi * 2.0 / o:getSampleRate()
while true do
val = math.sin(x * 440.0 * mul) * math.abs(math.sin(x * 0.5 * mul)) * 0.9
for i=0,chans - 1 do
o:write(i, val)
end
x = x + 1
end
--copy input to output
while true do
for i=0,chans - 1 do
o:write(i,o:read(i))
end
end
|
MODULE("filesyncmgr")
function filesyncmgr:ismatchfilter(filename, filterpattern)
if string.find(filename, filterpattern) then
return true
end
end
function filesyncmgr:get_searchrepo_overview()
local tosyncdata = {}
local repodir = core.envget("search_repo_dir")
local filterpattern = core.envget("search_file_filter")
local function querydir (relativepath)
local toquerydir = repodir
if relativepath then
toquerydir = repodir.."/"..relativepath
end
for entry in lfs.dir(toquerydir) do
local fullpath = toquerydir.."/"..entry
local attr = lfs.attributes(fullpath)
if (type(attr) == "table") then
if(attr.mode == "directory") then
core.debug(1, fullpath .." is a dir")
if entry ~= "." and entry ~= ".." then
if relativepath then
querydir(relativepath.."/"..entry)
else
querydir(entry)
end
end
elseif attr.mode=="file" then
local toreportfilename = entry
if relativepath then
toreportfilename = relativepath.."/"..entry
end
if self:ismatchfilter(toreportfilename, filterpattern) then
local modification = attr.modification
core.debug(1, fullpath.." is a match file, modification time is ", modification)
tosyncdata[toreportfilename] = modification
else
core.debug(1, fullpath.." is a mismatch file")
end
end
else
core.debug(2, "query "..fullpath.." failed")
end
end
end
core.debug(1, "ls dir:")
querydir()
return tosyncdata
end
function filesyncmgr:writedownfilecontent(fd, filename, filecontent)
local repodir = core.envget("search_repo_dir")
local fullpath = repodir.."/"..filename
local file = io.open(fullpath, "wb")
if not file then return end
file:write(filecontent)
file:close()
core.debug(1, "wrie down "..fullpath)
end
function filesyncmgr:getfilecontent(filename)
local repodir = core.envget("search_repo_dir")
local fullpath = repodir.."/"..filename
local file = io.open(fullpath, "rb")
if not file then
return
end
local filecontent = file:read("*a")
file:close()
return filecontent
end
|
#!/usr/local/bin/lua
print("hello world!")
print("chenjiamin")
|
function lang_switch_keys(lang)
local in_lang = {}
local langs =
{
[1] = {lang_key = "tr", lang_name = "Türkçe", script_name = "Satır Ölç", sub_menu = "Satır/Ölç"},
[2] = {lang_key = "en", lang_name = "English", script_name = "Measure Lines", sub_menu = "Lines/Measure"}
}
local lang_list = {}
local script_name_list = {}
local sub_menu_list = {}
for i = 1, #langs do
lang_list[langs[i].lang_key] = langs[i].lang_name
script_name_list[langs[i].lang_key] = langs[i].script_name
sub_menu_list[langs[i].lang_key] = langs[i].sub_menu
end
if lang == langs[1].lang_key then
in_lang["module_incompatible"] = "Mag modülünün kurulu sürümü bu lua dosyası ile uyumsuz!\n\nModül dosyasının en az \"%s\" sürümü veya daha üstü gerekiyor.\n\n\nŞimdi indirme sayfasına gitmek ister misiniz?"
in_lang["module_not_found"] = "Mag modülü bulunamadı!\n\nBu lua dosyasını kullanmak için Mag modülünü indirip Aegisub programı kapalıyken\n\"Aegisub/automation/include/\" dizinine taşımanız gerekiyor.\n\n\nŞimdi indirme sayfasına gitmek ister misiniz?"
in_lang["module_yes"] = "Git"
in_lang["module_no"] = "Daha Sonra"
in_lang["sub_menu"] = langs[1].sub_menu
in_lang["s_name"] = langs[1].script_name
in_lang["s_desc"] = "Uygulanan satırların efekt kutularına yüzde ekler. Çeviriyi paylaştırma açısından önemlidir."
in_lang["tabKey1"] = "Hesapla"
in_lang["tabKey2"] = "Kaldır"
in_lang["guiLabel1"] = "İsme göre böl:"
in_lang["guiLabel2"] = "Tam yüzde: %0.0"
in_lang["guiLabel3"] = "Satır sayıları: n / n"
in_lang["guiLabel4"] = "İsimler arasına virgül koyun."
in_lang["buttonKey1"] = "Hesapla"
in_lang["buttonKey2"] = "Kaldır"
in_lang["buttonKey3"] = "Kapat"
in_lang["out"] = "["..langs[1].script_name.."]"
elseif lang == langs[2].lang_key then
in_lang["module_incompatible"] = "The installed version of the Mag module is incompatible with this lua file!\n\nAt least \"%s\" version or higher of the module file is required.\n\n\nWould you like to go to the download page now?"
in_lang["module_not_found"] = "The module named Mag could not be found!\n\nTo use this file, you need to download the module named mag\nand move it to \"Aegisub/automation/include/\" directory when Aegisub is off.\n\n\nDo you want to go to download page now?"
in_lang["module_yes"] = "Go"
in_lang["module_no"] = "Later"
in_lang["sub_menu"] = langs[2].sub_menu
in_lang["s_name"] = langs[2].script_name
in_lang["s_desc"] = "Adds percentage to effect box of applied lines. It is important to share translation."
in_lang["tabKey1"] = "Calculate"
in_lang["tabKey2"] = "Remove"
in_lang["guiLabel1"] = "Separate by name:"
in_lang["guiLabel2"] = "Full percentage: %0.0"
in_lang["guiLabel3"] = "Line numbers: n / n"
in_lang["guiLabel4"] = "Put a comma between names."
in_lang["buttonKey1"] = "Calculate"
in_lang["buttonKey2"] = "Remove"
in_lang["buttonKey3"] = "Close"
in_lang["out"] = "["..langs[2].script_name.."]"
end
return in_lang, lang_list, script_name_list, sub_menu_list
end
c_lang_switch = "en"
c_lang,
c_lang_list,
c_script_name_list,
c_sub_name_list = lang_switch_keys(c_lang_switch)
script_name = c_lang.s_name
script_description = c_lang.s_desc
script_author = "Magnum357"
script_version = "2.2"
script_mag_version = "1.1.4.4"
script_file_name = "mag.measure_lines"
script_file_ext = ".lua"
include_unicode = true
mag_import, mag = pcall(require, "mag")
if mag_import then
mag.lang = c_lang_switch
c_out_message = c_lang.out
c_lock_gui = false
c_buttons1 = {c_lang.buttonKey1, c_lang.buttonKey3}
c_buttons2 = {c_lang.buttonKey2, c_lang.buttonKey3}
c = {}
c.titles = ""
c.comment_mode1 = true
c.empty_mode1 = true
c.comment_mode2 = true
c.empty_mode2 = true
c.percent_mode = true
c.number_mode = true
c.apply1 = mag.window.lang.message("select")
c.apply2 = mag.window.lang.message("select")
gui = {
main1 = {
{class = "label", x = 0, y = 0, width = 1, height = 1, label = c_lang.guiLabel1},
titles = {class = "edit", name = "u_titles", x = 1, y = 0, width = 1, height = 1},
{class = "label", x = 1, y = 1, width = 1, height = 1, label = c_lang.guiLabel4},
{class = "label", x = 0, y = 3, width = 1, height = 1, label = mag.window.lang.message("apply")},
apply1 = {class = "dropdown", name = "u_apply_lines1", x = 1, y = 3, width = 1, height = 1, hint = mag.window.lang.message("style_hint1")},
comment_mode1 = {class = "checkbox", name = "u_comment_mode1", x = 1, y = 4, width = 1, height = 1, label = mag.window.lang.message("comment_mode")},
empty_mode1 = {class = "checkbox", name = "u_empty_mode1", x = 1, y = 5, width = 1, height = 1, label = mag.window.lang.message("empty_mode")},
percent_mode = {class = "checkbox", name = "u_percent_mode", x = 1, y = 6, width = 1, height = 1, label = c_lang.guiLabel2},
number_mode = {class = "checkbox", name = "u_number_mode", x = 1, y = 7, width = 1, height = 1, label = c_lang.guiLabel3},
},
main2 = {
{class = "label", x = 0, y = 0, width = 1, height = 1, label = mag.window.lang.message("apply")},
apply2 = {class = "dropdown", name = "u_apply_lines2", x = 1, y = 0, width = 1, height = 1, hint = mag.window.lang.message("style_hint1")},
comment_mode2 = {class = "checkbox", name = "u_comment_mode2", x = 1, y = 1, width = 1, height = 1, label = mag.window.lang.message("comment_mode")},
empty_mode2 = {class = "checkbox", name = "u_empty_mode2", x = 1, y = 2, width = 1, height = 1, label = mag.window.lang.message("empty_mode")},
}
}
end
function add_measure_lines(subs,sel)
local line, index
local pcs = false
local lines_index = mag.line.index(subs, sel, c.apply1, c.comment_mode1, c.empty_mode1)
local titles_parts = {}
local title_mode = false
local titles
if mag.strip.space(c.titles) ~= "" then
title_mode = true
titles = mag.string.vars(c.titles)
for k = 1, #titles do
mag.array.insert(titles_parts, mag.floor(#lines_index / #titles))
end
local tlc_rest = #lines_index - (titles_parts[1] * #titles)
if tlc_rest > 0 then
local k = 0
repeat
k = k + 1
tlc_rest = tlc_rest - 1
titles_parts[k] = titles_parts[k] + 1
if k == #titles_parts then k = 0 end
until tlc_rest == 0
end
end
local tn = 0
local m = 1
for i = 1, #lines_index do
mag.window.progress(i, #lines_index)
if not pcs then pcs = true end
index = lines_index[i]
line = subs[index]
local result = ""
local collect = ""
if c.percent_mode then
collect = mag.convert.zero("00000", mag.convert.percent(#lines_index, i, false, "percent"))
else
collect = mag.convert.zero("00", mag.convert.percent(#lines_index, i, true, "percent"))
end
if c.number_mode then
collect = mag.string.combine(collect, mag.string.format("{%1} / {%2}", #lines_index, mag.convert.zero(#lines_index, i)), "{%1} - {%2}")
end
result = mag.string.format("({%s})", collect)
if title_mode then
collect = ""
tn = tn + 1
if tn > titles_parts[m] then
m = m + 1
tn = 1
end
if c.percent_mode then
collect = mag.convert.zero("00000", mag.convert.percent(titles_parts[m], tn, false, "percent"))
else
collect = mag.convert.zero("00", mag.convert.percent(titles_parts[m], tn, true, "percent"))
end
if c.number_mode then
collect = mag.string.combine(collect, mag.string.format("{%1} / {%2}", titles_parts[m], mag.convert.zero(titles_parts[m], tn)), "{%s} - {%s}")
end
result = mag.string.combine(result, mag.string.format("({%s}) *{%s}*", collect, titles[m]), "{%s} -> {%s}")
end
line.effect = mag.string.format("{%s} {%s}", c_out_message, result)
subs[index] = line
end
mag.show.no_op(pcs)
end
function remove_measure_lines(subs,sel)
local line, index
local pcs = false
local lines_index = mag.line.index(subs, sel, c.apply2, c.comment_mode2, c.empty_mode2)
for i = 1, #lines_index do
mag.window.progress(i, #lines_index)
index = lines_index[i]
line = subs[index]
if mag.match(line.effect, mag.convert.esc(c_out_message)) then
if not pcs then pcs = true end
line.effect = ""
subs[index] = line
end
end
mag.show.no_op(pcs, "effect", c_lang.out)
end
function add_macro1(subs,sel)
local apply_items = mag.list.full_apply(subs, sel, "comment")
c.apply1 = mag.array.search_apply(apply_items, c.apply1)
gui.main1.apply1.items = apply_items
local ok, config
repeat
gui.main1.titles.value = c.titles
gui.main1.apply1.value = c.apply1
gui.main1.comment_mode1.value = c.comment_mode1
gui.main1.empty_mode1.value = c.empty_mode1
gui.main1.percent_mode.value = c.percent_mode
gui.main1.number_mode.value = c.number_mode
ok, config = mag.window.dialog(gui.main1, c_buttons1)
c.titles = config.u_titles
c.apply1 = config.u_apply_lines1
c.comment_mode1 = config.u_comment_mode1
c.empty_mode1 = config.u_empty_mode1
c.percent_mode = config.u_percent_mode
c.number_mode = config.u_number_mode
until ok == mag.convert.ascii(c_buttons1[1]) and c.apply1 ~= mag.window.lang.message("select") or ok == mag.convert.ascii(c_buttons1[2])
if ok == mag.convert.ascii(c_buttons1[1]) then
add_measure_lines(subs, sel)
end
end
function add_macro2(subs,sel)
local apply_items = mag.list.full_apply(subs, sel, "comment")
c.apply2 = mag.array.search_apply(apply_items, c.apply2)
gui.main2.apply2.items = apply_items
local ok, config
repeat
gui.main2.apply2.value = c.apply2
gui.main2.comment_mode2.value = c.comment_mode2
gui.main2.empty_mode2.value = c.empty_mode2
ok, config = mag.window.dialog(gui.main2, c_buttons2)
c.apply2 = config.u_apply_lines2
c.comment_mode2 = config.u_comment_mode2
c.empty_mode2 = config.u_empty_mode2
until ok == mag.convert.ascii(c_buttons2[1]) and c.apply2 ~= mag.window.lang.message("select") or ok == mag.convert.ascii(c_buttons2[2])
if ok == mag.convert.ascii(c_buttons2[1]) then
remove_measure_lines(subs, sel)
end
end
function check_macro1(subs,sel)
if c_lock_gui then
mag.show.log(1, mag.window.lang.message("restart_aegisub"))
else
mag.config.get(c)
local fe, fee = pcall(add_macro1, subs, sel)
mag.window.funce(fe, fee)
mag.window.undo_point()
mag.config.set(c)
end
end
function check_macro2(subs,sel)
if c_lock_gui then
mag.show.log(1, mag.window.lang.message("restart_aegisub"))
else
mag.config.get(c)
local fe, fee = pcall(add_macro2, subs, sel)
mag.window.funce(fe, fee)
mag.window.undo_point()
mag.config.set(c)
end
end
function mag_redirect_gui()
local mag_module_link = "https://github.com/magnum357i/Magnum-s-Aegisub-Scripts"
local k = aegisub.dialog.display({{class = "label", label = mag_gui_message}}, {c_lang.module_yes, c_lang.module_no})
if k == c_lang.module_yes then os.execute("start "..mag_module_link) end
end
if mag_import then
if mag_module_version:gsub("%.", "") < script_mag_version:gsub("%.", "") then
mag_gui_message = string.format(c_lang.module_incompatible, script_mag_version)
aegisub.register_macro(script_name, script_desription, mag_redirect_gui)
else
mag.window.register(c_sub_name_list[c_lang_switch].."/"..c_lang.tabKey1, check_macro1)
mag.window.register(c_sub_name_list[c_lang_switch].."/"..c_lang.tabKey2, check_macro2)
mag.window.lang.register(c_sub_name_list[c_lang_switch])
end
else
mag_gui_message = c_lang.module_not_found
aegisub.register_macro(script_name, script_desription, mag_redirect_gui)
end
|
-- Copyright (C) 2011 - 2013 David Reid. See included LICENCE file.
function GTGUI.Element:ModelEditor_CDPanel(_internalPtr)
self:PanelGroupBox("Convex Decomposition");
self.ShowConvexDecomposition = GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' styleclass='checkbox' />");
self.ShowConvexDecomposition:SetTooltip("Show the convext decomposition. This will hide the main model");
GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' style='width:100%; height:1px; margin:0px 8px; background-color:#444;' />");
self.CompacityWeight = GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' styleclass='labeled-spinner' style='margin:0px 1px;' />");
self.VolumeWeight = GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' styleclass='labeled-spinner' style='margin:0px 1px;' />");
self.MinClusters = GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' styleclass='labeled-spinner' style='margin:0px 1px;' />");
self.VerticesPerCH = GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' styleclass='labeled-spinner' style='margin:0px 1px;' />");
self.Concavity = GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' styleclass='labeled-spinner' style='margin:0px 1px;' />");
self.SmallThreshold = GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' styleclass='labeled-spinner' style='margin:0px 1px;' />");
self.ConnectedDistance = GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' styleclass='labeled-spinner' style='margin:0px 1px;' />");
self.SimplifiedTriangleCount = GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' styleclass='labeled-spinner' style='margin:0px 1px;' />");
self.AddExtraDistPoints = GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' styleclass='checkbox' style='margin-bottom:4px; margin-top:4px;' />");
self.AddFacePoints = GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' styleclass='checkbox' />");
GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' style='width:100%; height:1px; margin:0px 8px; background-color:#444;' />");
self.BuildButton = GTGUI.Server.New("<div parentid='" .. self.Body:GetID() .. "' styleclass='button' style='width:100%;' />");
self.BuildButton:SetTooltip("Build the convex decomposition. This can take a while and the\neditor will appear to freeze.");
-- "Show in Viewport" CheckBox.
self.ShowConvexDecomposition:CheckBox("Show in Viewport");
self.ShowConvexDecomposition:OnChecked(function()
GTEngine.System.ModelEditor.ShowConvexDecomposition(_internalPtr);
end)
self.ShowConvexDecomposition:OnUnchecked(function()
GTEngine.System.ModelEditor.HideConvexDecomposition(_internalPtr);
end)
local settings = GTEngine.System.ModelEditor.GetConvexHullBuildSettings(_internalPtr);
self.CompacityWeight:LabeledSpinner( "Compacity Weight", 0, 1000000, 1, settings.compacityWeight);
self.VolumeWeight:LabeledSpinner( "Volume Weight", 0, 1000000, 1, settings.volumeWeight);
self.MinClusters:LabeledSpinner( "Min Clusters", 1, 1000000, 1, settings.minClusters);
self.VerticesPerCH:LabeledSpinner( "Vertices Per CH", 0, 1000000, 10, settings.verticesPerCH);
self.Concavity:LabeledSpinner( "Concavity", 0, 1000000, 1, settings.concavity);
self.SmallThreshold:LabeledSpinner( "Small Threshold", 0, 1000000, 1, settings.smallClusterThreshold);
self.ConnectedDistance:LabeledSpinner( "Connected Distance", 0, 1000000, 1 , settings.connectedComponentsDist);
self.SimplifiedTriangleCount:LabeledSpinner("Simplified Triangle Count", 0, 1000000, 100, settings.simplifiedTriangleCountTarget);
self.AddExtraDistPoints:CheckBox("Add Extra Distance Points");
self.AddFacePoints:CheckBox("Add Face Points");
function self:Refresh()
-- CD Settings
local settings = GTEngine.System.ModelEditor.GetConvexHullBuildSettings(_internalPtr);
self.CompacityWeight:SetValue( settings.compacityWeight);
self.VolumeWeight:SetValue( settings.volumeWeight);
self.MinClusters:SetValue( settings.minClusters);
self.VerticesPerCH:SetValue( settings.verticesPerCH);
self.Concavity:SetValue( settings.concavity);
self.SmallThreshold:SetValue( settings.smallClusterThreshold);
self.ConnectedDistance:SetValue( settings.connectedComponentsDist);
self.SimplifiedTriangleCount:SetValue(settings.simplifiedTriangleCountTarget);
if settings.addExtraDistPoints then
self.AddExtraDistPoints:Check();
end
if settings.addFacesPoints then
self.AddFacePoints:Check();
end
end
-- Build button.
self.BuildButton:Button("Build"):OnPressed(function()
self.BuildButton:Disable();
local compacityWeight = self.CompacityWeight:GetValue();
local volumeWeight = self.VolumeWeight:GetValue();
local minClusters = self.MinClusters:GetValue();
local verticesPerCH = self.VerticesPerCH:GetValue();
local concavity = self.Concavity:GetValue();
local smallThreshold = self.SmallThreshold:GetValue();
local connectedDistance = self.ConnectedDistance:GetValue();
local simplifiedTriangleCount = self.SimplifiedTriangleCount:GetValue();
local addExtraDistPoints = self.AddExtraDistPoints:IsChecked();
local addFacePoints = self.AddFacePoints:IsChecked();
GTEngine.System.ModelEditor.BuildConvexDecomposition(_internalPtr,
compacityWeight,
volumeWeight,
minClusters,
verticesPerCH,
concavity,
smallThreshold,
connectedDistance,
simplifiedTriangleCount,
addExtraDistPoints,
addFacePoints
);
self.BuildButton:Enable();
Editor.MarkFileAsModified(GTEngine.System.SubEditor.GetAbsolutePath(_internalPtr));
end);
return self;
end
|
local nerv = {
__version = '0.1.1',
__license = [[
The MIT License (MIT)
Copyright (c) 2014 Yang Xiya
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
}
nerv.__index = nerv
--can't take credit for the internal functions below
local function _in_quad(a,b,x) return a+(b-a)*x^2 end
local function _out_quad(a,b,x) return a+(b-a)*(1-(1-x)^2) end
local function _max(a,b) return a>b and a or b end
local function _findIndex(t,value)
for i,v in pairs(t) do
if v == value then return i end
end
end
local function _checkFn(fn)
if type(fn) == 'function' then
return true
else
local mt = getmetatable(fn)
if mt then return mt.__call end
end
return false
end
local function _clamp(x,min,max) return x<min and min or (x>max and max or x) end
local _nerv_num = 0
local _active_nerv_num = {}
local _nervTable = {}
function nerv.new( fn_onStart, fn_onFinished, maxPotential, refractoryPeriod, noiseFn )
_nerv_num = _nerv_num + 1
if fn_onStart~= nil then
assert( _checkFn(fn_onStart), 'fn_onStart (1st parameter) should be a function (or nil) but it is ' .. type(fn_onStart) )
end
if fn_onFinished~= nil then
assert( _checkFn(fn_onFinished), 'fn_onFinished (2nd parameter) should be a function (or nil) but it is ' .. type(fn_onFinished) )
end
if maxPotential~= nil then
assert( type(maxPotential) =='number' and maxPotential >= 1, ' maxPotential (3rd parameter) should be a number such that maxPotentials >= threshold potential(1) (or nil), but it is ' .. type(maxPotential) )
end
if refractoryPeriod~= nil then
assert( type(refractoryPeriod) == 'number' and refractoryPeriod >= 0, 'refractoryPeriod (4th parameter) should be a non-negative number (or nil)' )
end
local t = setmetatable( {
fn_onStart = fn_onStart or function() end,
fn_onFinished = fn_onFinished or function() end,
noise = noiseFn or love.math.noise,
rP = 0, --resting potential
tP = 1, --threshold potential
potential = 0,
recordedPotential = 0,
mP = maxPotential or 8,
rPe = refractoryPeriod or 1,
stRPe = nil,
isLocked = false,
timers = {love.math.random(1,10000)/100},
timerNum = 0,
nervNum = _nerv_num,
connectedNervs = {},
lagTime = {},
isFiredNervs = {}, --a table of booleans that indicate whether impulses have been transmitted to the nervs connected downstream
type = 'nerv'
}, {__index = nerv} )
_nervTable[_nerv_num] = t
return t
end
function nerv:update(dt)
if not self.isLocked and self.potential >= self.tP and self.rPe ~= 0 then
self.fn_onStart()
self.isLocked = true
end
for i = 1,#self.timers do
self.timers[i] = self.timers[i] + dt
end
self.recordedPotential = self.potential <= self.tP and self.potential or ( self.stRPe and not self.isSkipped and self.potential or ( self.rPe ~= 0 and self.tP or self.potential) ) --make sure the potential returned does not exceed threshold potential( because the potential can be so awefully large )
if not self.isLocked then
self.timerNum = 0
self.potential = self.rP
else
--tweening
self.stRPe = self.stRPe or love.timer.getTime() --stRPe: starting time of refractory period
local tDif = love.timer.getTime()-self.stRPe
if not self.isSkipped then
local tP,rP,mP,rPe = self.tP, self.rP, self.mP, self.rPe
if not self.isReverseMP then
local frac_tDif = (tDif%(self.rPe/2))/(self.rPe/2)
self.potential = tDif<rPe/2 and _out_quad(tP, mP, frac_tDif) or ( tDif<rPe and _in_quad(mP, rP, frac_tDif) or rP )
else
local frac_tDif = (tDif%(self.rPe/4))/(self.rPe/4)
self.potential = tDif<rPe/4 and _out_quad(tP, mP, frac_tDif) or ( tDif<rPe/2 and _in_quad(mP, rP, frac_tDif) or ( tDif<rPe*3/4 and _out_quad(rP, rP-(mP-rP), frac_tDif ) or ( tDif<rPe and _in_quad(rP-(mP-rP), rP, frac_tDif ) or rP ) ) )
end
end
--fire impulse to the connected nerv
for i, _nerv in pairs( self.connectedNervs ) do
if not self.isFiredNervs[i] then
if tDif > self.lagTime[i] then self.isFiredNervs[i] = true; _nerv:fire() end
end
end
--tidy up after potential changes back
if tDif > self.rPe then
self.fn_onFinished()
self.potential = self.rP --in case tweening is skipped
self.timerNum = 0
self.isLocked = false
self.stRPe = nil
for i = 1, #self.isFiredNervs do self.isFiredNervs[i] = false end
local i = _findIndex( _active_nerv_num, self.nervNum-1 )
if i then _active_nerv_num[i] = nil end
end
end
end
function nerv:send( strength )
assert( type(strength) == 'number', 'strength of stimulus sent needs to be a number, but it is ' .. type(strength) )
if not self.isLocked then
local strength = _max(strength,0)
self.timerNum = self.timerNum + 1
if self.timerNum > #self.timers then
self.timers[ #self.timers+1 ] = 0
end
--order is important
self.potential = _clamp( self.potential + self.noise( self.timers[self.timerNum] )*strength, self.rP-(self.mP-self.rP), self.mP )
end
end
function nerv:inhibit( strength )
assert( type(strength) == 'number', 'strength of inhibition needs to be a number, but it is ' .. type(strength) )
if not self.isLocked then
local strength = _max(strength,0)
self.timerNum = self.timerNum + 1
if self.timerNum > #self.timers then
self.timers[ #self.timers+1 ] = 0
end
self.potential = _clamp( self.potential - (.5+self.noise( self.timers[self.timerNum] )/2)*strength, self.rP-(self.mP-self.rP), self.mP )
end
end
function nerv:getPotential()
return self.recordedPotential
end
function nerv:setPotentials( maxPotential, restingPotential, thresholdPotential, isReverseMP )
if restingPotential ~= nil then
assert( type(restingPotential) =='number', ' restingPotential (2nd parameter of :setPotentials()) should be a number (or nil), but it is ' .. type(restingPotential) )
self.rP = restingPotential
self.potential = self.rP
end
if thresholdPotential ~= nil then
assert( type(thresholdPotential) =='number', ' thresholdPotential (3rd parameter of :setPotentials()) should be a number (or nil), but it is ' .. type(thresholdPotential) )
self.tP = thresholdPotential
end
if maxPotential ~= nil then
assert( type(maxPotential) =='number' and maxPotential >= self.tP, ' maxPotential (1st parameter of :setPotentials()) should be a number such that maxPotentials >= threshold potential(1) (or nil), but it is ' .. type(maxPotential) )
self.mP = maxPotential
end
if isReverseMP ~= nil then
assert( type(isReverseMP) == 'boolean', 'isReverseMP (4th parameter of :setPotentials()), should be a boolean (or nil), but it is ' .. type(isReverseMP) )
self.isReverseMP = isReverseMP --whether to let potential go down to -1*maxPotential after it drops from maxPotential to restingPotential
end
return self
end
function nerv:setFunctions( fn_onStart, fn_onFinished )
if fn_onStart ~= nil then
assert( _checkFn(fn_onStart), 'fn_onStart, 1st parameter of setFunctions() should be a function (or nil) but it is ' .. type(fn_onStart) )
self.fn_onStart = fn_onStart
end
if fn_onFinished ~= nil then
assert( _checkFn(fn_onFinished), 'fn_onFinished, 2nd parameter of setFunctions() should be a function (or nil) but it is ' .. type(fn_onFinished) )
self.fn_onFinished = fn_onFinished
end
return self
end
function nerv:setPeriod( refractoryPeriod ) --refractory period (during which massive change in potential happens)
assert( type(refractoryPeriod) == 'number' and refractoryPeriod >= 0, 'refractoryPeriod should be a non-negative number (or nil)' )
self.rPe = refractoryPeriod
return self
end
function nerv:setNoiseFn( noiseFn )
assert( _checkFn(noiseFn), 'noiseFn should be a function (or nil) but it is ' .. type(noiseFn) )
self.noise = noiseFn
return self
end
function nerv:sync() --used when creating many instances together
self.timers = {0}
return self
end
function nerv:setSkipped() --whether or not tweening should be skipped (faster by about one third)
self.isSkipped = true
return self
end
function nerv:connect(n,lagTime)
--lagTime(.1): time lag for firing of nerv impulse to the next nerv
assert( type(n) == 'table' and n.type == 'nerv', 'Only instances of nerv can be connected.' )
self.connectedNervs[#self.connectedNervs+1] = n
self.isFiredNervs[#self.isFiredNervs+1] = false
if lagTime ~= nil then
assert( type(lagTime) == 'number' and lagTime >= 0, 'lagTime, 2nd parameter of :connect(), should be a non-negative number (or nil)' )
self.lagTime[#self.lagTime+1] = lagTime
else
self.lagTime[#self.lagTime+1] = .1
end
return self
end
function nerv:fire() --for connected nervs upstream to fire off impulse on itself
if not self.isLocked then
self.fn_onStart()
self.isLocked = self.rPe ~= 0
end
end
setmetatable( nerv, {__call = function(_,...) return nerv.new(...) end } )
return nerv
|
local cutils = require 'libcutils'
local ffi = require 'ffi'
local stringify = require 'Q/CSERVER/src/lua/stringify'
local function mk_config(S)
assert(S)
S = ffi.cast("q_server_t *", S)
local config = require 'Q/CSERVER/src/lua/config'
assert(type(config) == "table")
--=========================
local port = assert(config.port)
assert(type(port) == "number")
assert(port > 1024)
S[0].port = port
--=========================
local sz_body = assert(config.sz_body)
assert(type(sz_body) == "number")
assert(port > 1024)
S[0].sz_body = sz_body
--=========================
local sz_rslt = assert(config.sz_rslt)
assert(type(sz_rslt) == "number")
assert(port > 1024)
S[0].sz_rslt = sz_rslt
--=========================
local chunk_size = assert(config.chunk_size)
assert(type(chunk_size) == "number")
assert(chunk_size >= 64)
assert( math.floor(chunk_size/64) == math.ceil(chunk_size/64) )
S[0].chunk_size = chunk_size
--=========================
local qc_flags = assert(config.qc_flags)
assert(type(qc_flags) == "string")
assert(#qc_flags > 0)
S[0].qc_flags = stringify(qc_flags)
--=========================
local q_data_dir = assert(config.q_data_dir)
assert(type(q_data_dir) == "string")
assert(#q_data_dir > 0)
assert(cutils.isdir(q_data_dir))
S[0].q_data_dir = stringify(q_data_dir)
--=========================
local q_root = assert(config.q_root)
assert(type(q_root) == "string")
assert(#q_root > 0)
assert(cutils.isdir(q_root))
S[0].q_root = stringify(q_root)
--=========================
local q_src_root = assert(config.q_src_root)
assert(type(q_src_root) == "string")
assert(#q_src_root > 0)
assert(cutils.isdir(q_src_root))
S[0].q_src_root = stringify(q_src_root)
--=========================
end
return mk_config
|
function MyService:Start()
local thisThing = {}
function thisThing:Start()
print("thisThing started")
end
function thisThing:Init()
print("thisThing initialized")
end
-- Transform 'thisThing' into a framework object:
self:WrapModule(thisThing)
end
|
--[[
-- Fade nameplates based on rules
--
-- Return values:
-- 1 = stop iterating, fade to 1
-- 0 = stop iterating, fade to 0
-- -1 = stop iterating, fade to mod.conditional_alpha
-- nil = continue to iterate fade rules table
-- end = fade to mod.non_target_alpha
--
-- Lower priority (1 < 100) = first execution.
-- Rules which result in fading nameplates OUT should generally be between
-- priority 20 and 100, as per the default fade rules set in :ResetFadeRules.
-- ]]
local addon = KuiNameplates
local kui = LibStub('Kui-1.0')
local mod = addon:NewPlugin('Fading')
local abs,pairs,ipairs,type,tinsert = math.abs,pairs,ipairs,type,tinsert
local kff,kffr = kui.frameFade, kui.frameFadeRemoveFrame
local UpdateFrame = CreateFrame('Frame')
local fade_rules,delayed_frames = {},{}
local target_exists
-- local functions #############################################################
local function ResetFrameFade(frame)
kffr(frame)
frame.fading_to = nil
end
local function FrameFade(frame,to)
if frame.fading_to and to == frame.fading_to then return end
ResetFrameFade(frame)
local cur_alpha = frame:GetAlpha()
if to == cur_alpha then return end
local alpha_change = to - cur_alpha
frame.fading_to = to
kff(frame, {
mode = alpha_change < 0 and 'OUT' or 'IN',
timeToFade = abs(alpha_change) * mod.fade_speed,
startAlpha = cur_alpha,
endAlpha = to,
finishedFunc = ResetFrameFade
})
end
local function GetDesiredAlpha(frame)
for _,f_t in ipairs(fade_rules) do
if f_t then
local a = f_t[2](frame)
if a then
if a < 0 then
return mod.conditional_alpha
else
return a
end
end
end
end
return mod.non_target_alpha
end
local function InstantUpdateFrame(f)
if not f:IsShown() then return end
if mod.fade_speed > 0 then
FrameFade(f,GetDesiredAlpha(f))
else
f:SetAlpha(GetDesiredAlpha(f))
end
end
-- update frame ################################################################
local function OnUpdate(self)
for f,_ in pairs(delayed_frames) do
delayed_frames[f] = nil
InstantUpdateFrame(f)
end
UpdateFrame:SetScript('OnUpdate',nil)
end
-- mod functions ###############################################################
function mod:UpdateFrame(f)
-- add frame to delayed update table
if not self.enabled then return end
delayed_frames[f] = true
UpdateFrame:SetScript('OnUpdate',OnUpdate)
end
function mod:UpdateAllFrames()
-- update alpha of all visible frames
for _,f in addon:Frames() do
if f:IsShown() then
self:UpdateFrame(f)
end
end
end
function mod:ResetFadeRules()
-- reset to default fade rules
fade_rules = {
-- don't fade the personal nameplate
{ 10, function(f) return f.state.personal and 1 end, 'avoid_personal' },
-- don't fade the target nameplate
{ 20, function(f) return f.handler:IsTarget() and 1 end, 'avoid_target' },
-- fade in all nameplates if there is no target
{ 100, function() return not target_exists and 1 end, 'no_target' },
}
-- let plugins re/add their own rules
mod:RunCallback('FadeRulesReset')
end
function mod:AddFadeRule(func,priority,uid)
if not self.enabled then return end
if type(func) ~= 'function' or not tonumber(priority) then
error('AddFadeRule expects function(function),priority(number)')
end
uid = uid and tostring(uid)
if uid and self:GetFadeRuleIndex(uid) then
addon:print('fade rule already exists:',uid)
return
end
local insert_tbl = {priority,func,uid}
local inserted
for k,f_t in ipairs(fade_rules) do
if priority < f_t[1] then
tinsert(fade_rules,k,insert_tbl)
inserted = true
break
end
end
if not inserted then
tinsert(fade_rules,insert_tbl)
end
return inserted
end
function mod:RemoveFadeRule(index)
if tonumber(index) then
if fade_rules[index] then
fade_rules[index] = nil
end
elseif type(index) == 'string' then
-- remove by uid
local i = self:GetFadeRuleIndex(index)
if i then
self:RemoveFadeRule(i)
end
end
end
function mod:GetFadeRuleIndex(uid)
if type(uid) ~= 'string' then return end
for i,f_t in ipairs(fade_rules) do
if f_t[3] and f_t[3] == uid then
return i
end
end
end
-- messages ####################################################################
function mod:TargetUpdate()
target_exists = UnitExists('target')
self:UpdateAllFrames()
end
function mod:Show(f)
f:SetAlpha(0)
self:UpdateFrame(f)
end
function mod:Hide(f)
ResetFrameFade(f)
end
-- register ####################################################################
function mod:OnEnable()
self:RegisterEvent('PLAYER_TARGET_CHANGED','TargetUpdate')
self:RegisterEvent('PLAYER_ENTERING_WORLD','TargetUpdate')
self:RegisterMessage('GainedTarget','TargetUpdate')
self:RegisterMessage('LostTarget','TargetUpdate')
self:RegisterMessage('Show')
self:RegisterMessage('Hide')
self:ResetFadeRules()
self:UpdateAllFrames()
end
function mod:OnDisable()
wipe(delayed_frames)
wipe(fade_rules)
UpdateFrame:SetScript('OnUpdate',nil)
for _,f in addon:Frames() do
f:SetAlpha(1)
end
end
function mod:Initialise()
self:RegisterCallback('FadeRulesReset')
self.non_target_alpha = .5
self.conditional_alpha = .3
self.fade_speed = .5
end
|
local postgresql_client = {}
pgmoon = require("pgmoon-mashape")
--PGClient Class
PGClient = {}
function PGClient.split_text(self, text, delimiter)
if text.find(text, delimiter) == nil then
return { text }
end
local splited_texts = {}
local last_position
for splited_text, position in text:gmatch("(.-)"..delimiter.."()") do
table.insert(splited_texts, splited_text)
last_position = position
end
table.insert(splited_texts, string.sub(text, last_position))
return splited_texts
end
function PGClient.parse_connection_spec(self, connection_spec)
parsed_connection_spec = {}
for number, connection_spec_value in pairs(self:split_text(connection_spec, " ")) do
key, value = connection_spec_value:match("(.-)=(.-)$")
parsed_connection_spec[key] = value
end
return parsed_connection_spec
end
function PGClient.save_xml(self, connection_spec, xml, source_html_path)
parsed_connection_spec = self:parse_connection_spec(connection_spec)
local pg = pgmoon.new(parsed_connection_spec)
assert(pg:connect())
assert(pg:query("CREATE TABLE IF NOT EXISTS converted_xml("..
"id serial,"..
"xml xml,"..
"source_html_path text"..
");"))
assert(pg:query("INSERT INTO converted_xml (xml, source_html_path)"..
"VALUES (XMLPARSE(DOCUMENT " .. pg:escape_literal(xml) .. "), "..
pg:escape_literal(source_html_path)..")"))
end
function PGClient.new(self)
local object = {}
setmetatable(object, object)
object.__index = self
return object
end
|
require("games/common2/mechine/mechineBase");
MatchMechine = class(MechineBase);
MatchMechine.getInstance = function()
if not MatchMechine.s_instance then
MatchMechine.s_instance = new(MatchMechine);
end
return MatchMechine.s_instance;
end
MatchMechine.releaseInstance = function()
delete(MatchMechine.s_instance);
MatchMechine.s_instance = nil;
end
--[[
比赛中的状态机
]]
MatchMechine.init = function(self)
self:addMatchStateOpt();
self:addMatchNoStateOpt();
end
-- 检测状态是否可以跳转
MatchMechine.checkStateValid = function(self,action,info,isFast,tag)
if self.m_onlookerMatchMechine and self.m_onlookerMatchMechine:checkAction(action) then
self.m_onlookerMatchMechine:checkStateValid(action,info,isFast,tag);
elseif self.m_reconnectMechine then
self.m_reconnectMechine:checkStateValid(action,info,isFast,tag);
elseif self.m_matchNoStateOpt:isNoStateAction(action) then
self.m_matchNoStateOpt:updateNoStateInfo(action,info,isFast,tag);
else
self.m_matchStateOpt:checkStateValid(action,info,isFast,tag);
end
end
MatchMechine.receiveAction = function(self,action,info,isFast,tag)
if action == MatchMechineConfig.ACTION_RECONNECT then
self:addReconnectMechine();
elseif action == MatchMechineConfig.ACTION_RESET then
self:removeReconnectMechine();
elseif action == MatchMechineConfig.ACTION_ENTER_ONLOOKER then
self:addOnlookerMechine();
info = table.verify(info);
self:removeMatchStateOpt();
self:addMatchStateOpt(info.userId);
self:removeMatchNoStateOpt();
self:addMatchNoStateOpt(info.userId);
end
self:checkStateValid(action,info,isFast,tag);
end
-- 获取当前状态和上一次的状态
MatchMechine.getStates = function(self)
if self.m_onlookerMatchMechine then
return self.m_onlookerMatchMechine:getStates();
else
local curState,lastSate,curSubState = self.m_matchStateOpt:getStates();
if self.m_reconnectMechine then
return MatchMechineConfig.STATUS_RECONNECT,curState,MatchMechineConfig.STATUS_RECONNECT;
else
return curState,lastSate,curSubState;
end
end
end
-- 重置状态机
MatchMechine.reset = function(self)
self.m_matchStateOpt:resetState();
end
MatchMechine.dtor = function(self)
self:removeMatchStateOpt();
self:removeMatchNoStateOpt();
self:removeReconnectMechine();
self:removeOnlookerMechine();
end
-------------------------------------------------------------------------------------
MatchMechine.addReconnectMechine = function(self)
local ReconnectMechine = require("games/common2/mechine/reconnectMechine");
self.m_reconnectMechine = new(ReconnectMechine);
end
MatchMechine.removeReconnectMechine = function(self)
delete(self.m_reconnectMechine);
self.m_reconnectMechine = nil;
end
MatchMechine.addMatchStateOpt = function(self,userId)
local MatchMechineOperation = require("games/common2/match/matchMechine/matchMechineOperation");
self.m_matchStateOpt = new(MatchMechineOperation,userId);
end
MatchMechine.removeMatchStateOpt = function(self)
delete(self.m_matchStateOpt);
self.m_matchStateOpt = nil;
end
MatchMechine.addMatchNoStateOpt = function(self,userId)
local MatchNoStateAction = require("games/common2/match/matchMechine/matchNoStateAction");
self.m_matchNoStateOpt = new(MatchNoStateAction,userId);
end
MatchMechine.removeMatchNoStateOpt = function(self)
delete(self.m_matchNoStateOpt);
self.m_matchNoStateOpt = nil;
end
MatchMechine.addOnlookerMechine = function(self)
local OnlookerMatchMechine = require("games/common2/match/matchMechine/onlookerMatchMechine");
self.m_onlookerMatchMechine = new(OnlookerMatchMechine);
end
MatchMechine.removeOnlookerMechine = function(self)
delete(self.m_onlookerMatchMechine);
self.m_onlookerMatchMechine = nil;
end
|
-- Symbol, Currency
local make_set = require 'parse.char.utf8.make.set'
return make_set {
S = '$'
.. '\u{58f}\u{60b}\u{9f2}\u{9f3}\u{9fb}\u{af1}\u{bf9}\u{e3f}'
.. '\u{17db}\u{a838}\u{fdfc}\u{fe69}\u{ff04}\u{ffe0}\u{ffe1}\u{ffe5}\u{ffe6}';
R = {"\u{a2}\u{a5}","\u{20a0}\u{20be}"};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.