content
stringlengths 5
1.05M
|
---|
local ffi = require 'ffi'
local dbg = require 'scripts.debugger'
local twig = require 'scripts/twig'
local hlpr = assert(loadfile("project/helpers.lua"))(cef)
local tinsert = table.insert
local tremove = table.remove
ffi.cdef[[
typedef struct lj_fpool_finfo {
char id[32];
char fname[1024];
char ext[8];
void * data;
char * body;
char mime_type[32];
int index;
int state;
int size;
int remaining;
} lj_fpool_finfo;
void * calloc( size_t count, size_t esize );
]]
-- Namespace caching is faster
local fpool_cef = ffi.C
-----------------------------------------------------------------------------------------------
-- File pool for loading multiple files
local max_htmlsize = 2 * 1024 * 1024
local mime_types = {}
mime_types["adf"] = "application/octet-stream"
mime_types["bin"] = "application/octet-stream"
mime_types["css"] = "text/css"
mime_types["gif"] = "image/gif"
mime_types["gltf"] = "model/gltf+json"
mime_types["glsl"] = "text/plain"
mime_types["html"] = "text/html"
mime_types["jpeg"] = "image/jpeg"
mime_types["jpg"] = "image/jpeg"
mime_types["js"] = "text/javascript"
mime_types["json"] = "application/json"
mime_types["mjs"] = "text/javascript"
mime_types["mpeg"] = "video/mpeg"
mime_types["obj"] = "text/plain"
mime_types["png"] = "image/png"
mime_types["svg"] = "image/svg+xml"
mime_types["tif"] = "image/tiff"
mime_types["tiff"] = "image/tiff"
mime_types["txt"] = "text/plain"
mime_types["weba"] = "audio/webm"
mime_types["webm"] = "video/webm"
mime_types["webp"] = "image/webp"
mime_types["woff"] = "font/woff"
mime_types["woff2"] = "font/woff2"
mime_types["xml"] = "text/xml"
mime_types["twig"] = "text/html"
local fpool = {}
local fpool_scheme = "custom"
-----------------------------------------------------------------------------------------------
local function init( www_paths )
twig.init( www_paths )
end
-----------------------------------------------------------------------------------------------
local function pool_loadfile( filename_in, command, data_in )
local mime_type_out = data_in[0].mime_type
local path_in = data_in[0].path
local finfo = nil
local id = tostring( ffi.string(filename_in) )
local cmd = ffi.string(command)
if(cmd == "load_data") then
-- if(fpool[id] == nil) then
finfo = ffi.new("struct lj_fpool_finfo[1]")
local filename = ffi.string(filename_in)
local pathname = ffi.string(path_in)
filename = string.sub( filename, #fpool_scheme + 4, -1 )
filename = string.match(filename, "([^%?]+)")
ffi.fill(finfo[0].fname, 1024 )
ffi.copy(finfo[0].fname, ffi.string(filename, #filename), #filename)
local ext = string.match(filename, "^.+%.(.+)")
-- print(ext, filename)
ffi.fill(finfo[0].ext, #fpool_scheme + 3 )
ffi.copy(finfo[0].ext, ffi.string(ext), #ext)
local mimet = mime_types[ext]
if(mimet == nil) then mimet = "text/html" end
local mime_type = ffi.string(mimet, #mimet)
ffi.fill(finfo[0].mime_type, 32)
ffi.copy(finfo[0].mime_type, mime_type, #mime_type)
-- print( newfile.mime_type, ext, fname )
-- print("Filename:", finfo.fname)
-- print("Extension:", finfo.ext)
local data = nil
local dsize = 0
local filename = ffi.string(finfo[0].fname)
local ext = ffi.string(finfo[0].ext)
if(ext == "twig") then
-- print("File Twig Load: ", filename)
data, dsize = twig.parse(filename)
else
-- print("File Load: ", filename)
-- Sometimes the filename is added as a "hostname". Usually because its a
-- relative file path from the document. Rebuild path if so.
if(#pathname > 0) then filename = pathname end
data, dsize = twig.readfile(filename)
end
finfo[0].remaining = dsize or 0
-- finfo[0].state = fpool_cef.FR_PENDINGFILE
finfo[0].size = dsize or 0
-- fpool_cef.ljq_datanew( finfo[0].data, dsize );
-- local rawdata = ffi.new("char[?]", dsize)
local filedata = ffi.cast("char *", ffi.string(data, dsize))
finfo[0].body = ffi.new("char[?]", dsize)
ffi.copy( finfo[0].body, filedata, dsize)
fpool[id] = finfo
-- else
-- finfo = fpool[id]
-- end
data_in[0].dsize = finfo[0].size
end
if( cmd == "copy_data") then
finfo = fpool[id]
if( finfo ) then
ffi.copy( data_in[0].data, finfo[0].body, finfo[0].size)
ffi.copy( mime_type_out, finfo[0].mime_type, 32)
end
end
end
-----------------------------------------------------------------------------------------------
return {
init = init,
pool_loadfile = pool_loadfile,
} |
local compe = require'compe'
local Source = {}
function Source.get_metadata(_)
return {
priority = 10,
dup = 0,
menu = '[Tmux]'
}
end
function Source.determine(_, context)
return compe.helper.determine(context)
end
function Source.complete(_, context)
vim.fn["tmuxcomplete#async#gather_candidates"](function (items)
context.callback({ items = items })
end)
end
return Source
|
local FCPM_ID = 1 -- 2 / 3 / 4 / 5
local telemetry = {}
function main()
local result = can.init(250, can_handler)
if result ~= 0 then
enapter.log("CAN init failed: "..result.." "..can.err_to_str(result), "error", true)
end
scheduler.add(30000, properties)
scheduler.add(1000, metrics)
end
function properties()
enapter.send_properties({ vendor = "Cummins", model = "HyPM HD FCPM" })
end
function metrics()
enapter.send_telemetry(telemetry)
end
function can_handler(msg_id, data)
if msg_id == 0x1D0 + FCPM_ID then
telemetry["cdr"] = toint16(data[1], "unsign")
elseif msg_id == 0x240 + FCPM_ID then
local all_states = {}
all_states[0x01] = "standby"
all_states[0x02] = "startup"
all_states[0x03] = "run"
all_states[0x04] = "shutdown"
all_states[0x05] = "fault"
all_states[0x06] = "cooldown"
all_states[0x07] = "cooldown_complete"
all_states[0x08] = "freeze_prep"
all_states[0x09] = "freeze_prep_complete"
all_states[0x0A] = "anode_purge"
all_states[0x0B] = "anode_purge_complete"
all_states[0x0C] = "leak_check"
all_states[0x0D] = "leak_check_complete"
all_states[0x0E] = "prime"
all_states[0x0F] = "prime_complete"
telemetry["state"] = all_states[data[1]]
telemetry["cda"] = toint16(data[3], "unsign")
telemetry["fc_stack_current"] = toint16(data[4], "sign")
telemetry["fc_stack_voltage"] = toint16(data[5], "unsign")
elseif msg_id == 0x2C0 + FCPM_ID then
telemetry["alerts"] = check_alerts(data)
elseif msg_id == 0x340 + FCPM_ID then
telemetry["coolant_temp"] = toint16(data[1], "unsign")
telemetry["coolant_setpoint"] = toint16(data[2], "unsign")
end
end
function toint16(data, fmt)
local perbitfactor = 10.0
if fmt == "unsign" then
local raw_str = string.pack("BB", data>>8, data&0xFF)
return string.unpack(">I2", raw_str) / perbitfactor
else
local raw_str = string.pack("bb", data>>8, data&0xFF)
return string.unpack(">i2", raw_str) / perbitfactor
end
end
function check_alerts(data)
local faults = {}
faults[0x01] = "stack_under_voltage_fault"
faults[0x02] = "coolant_over_temp_fault"
faults[0x10] = "comm_heartbeat_fault"
faults[0x40] = "internal_system_stop_fault"
faults[0x100] = "leak_check_failed_fault"
faults[0x200] = "freeze_mode_fault"
faults[0x400] = "coolant_low_flow_fault"
faults[0x800] = "idle_fault"
faults[0x1000] = "anode_purge_fault"
faults[0x2000] = "stack_current_fault"
faults[0x4000] = "h2_supply_over_pressure_fault"
faults[0x4000] = "h2_supply_under_pressure_fault"
local alarms = {}
alarms[0x01] = "h2_sensor_out_of_range_alarm"
alarms[0x02] = "air_flow_out_of_range_alarm"
alarms[0x04] = "current_sensor_out_of_range_alarm"
alarms[0x08] = "coolant_temp_high_alarm"
alarms[0x10] = "system_over_power_alarm"
alarms[0x20] = "air_flow_in_nonrun_state_alarm"
alarms[0x40] = "blower_low_flow_alarm"
alarms[0x80] = "anode_pump_speed_alarm" --
alarms[0x100] = "coolant_temp_out_of_range_alarm"
alarms[0x200] = "blower_low_voltage_alarm"
alarms[0x400] = "recovery_alarm"
alarms[0x800] = "coolant_low_flow_alarm"
alarms[0x1000] = "stack_low_current_alarm"
alarms[0x2000] = "eFCVM_bad_finger_alarm"
alarms[0x4000] = "EEPROM_Error_alarm"
alarms[0x8000] = "EMP_pump_alarm"
local all_alerts = {}
table.insert(all_alerts, faults[data[1]])
table.insert(all_alerts, alarms[data[5]])
return all_alerts
end
COMMAND_MSG_ID = 0x1c0 + FCPM_ID
function standby()
return can.send(COMMAND_MSG_ID, 0x01)
end
function run()
return can.send(COMMAND_MSG_ID, 0x02)
end
function cooldown()
return can.send(COMMAND_MSG_ID, 0x03)
end
function freeze_prep()
return can.send(COMMAND_MSG_ID, 0x04)
end
function anode_purge()
return can.send(COMMAND_MSG_ID, 0x05)
end
function leak_check()
return can.send(COMMAND_MSG_ID, 0x06)
end
function prime()
return can.send(COMMAND_MSG_ID, 0x07)
end
enapter.register_command_handler("standby", function(ctx)
if standby() ~= 0 then
ctx.error("CAN failed")
end
end)
enapter.register_command_handler("run", function(ctx)
if run() ~= 0 then
ctx.error("CAN failed")
end
end)
enapter.register_command_handler("cooldown", function(ctx)
if cooldown() ~= 0 then
ctx.error("CAN failed")
end
end)
enapter.register_command_handler("freeze_prep", function(ctx)
if freeze_prep() ~= 0 then
ctx.error("CAN failed")
end
end)
enapter.register_command_handler("anode_purge", function(ctx)
if anode_purge() ~= 0 then
ctx.error("CAN failed")
end
end)
enapter.register_command_handler("leak_check", function(ctx)
if leak_check() ~= 0 then
ctx.error("CAN failed")
end
end)
enapter.register_command_handler("prime", function(ctx)
if prime() ~= 0 then
ctx.error("CAN failed")
end
end)
main()
|
--[[
Configuration from default, moddir and worlddir, in that order.
See init.lua for license.
]]
-- change these for other mods
local M = thirsty
local modname = 'thirsty'
local fileroot = modname
-- make sure config exists; keep constant reference to it
local C = M.config or {}
M.config = C
local function try_config_file(filename)
--print("Config from "..filename)
local file, err = io.open(filename, 'r')
if file then
file:close() -- was just for checking existance
local confcode, err = loadfile(filename)
if confcode then
confcode()
if C ~= M.config then
-- M.config was overriden, merge
for key, value in pairs(M.config) do
if type(value) == 'table' and type(C[key]) == 'table' and not value.CLEAR then
for k, v in pairs(value) do
C[key][k] = value[k]
end
else
-- copy (not a table, or asked to clear)
C[key] = value
end
end
else
-- no override? Empty, or file knows what it is doing.
end
else
minetest.log("error", "Could not load " .. filename .. ": " .. err)
end
end
end
-- read starting configuration from <modname>.default.conf
try_config_file(minetest.get_modpath(modname) .. "/" .. fileroot .. ".default.conf")
-- next, install-specific copy in modpath
try_config_file(minetest.get_modpath(modname) .. "/" .. fileroot .. ".conf")
-- last, world-specific copy in worldpath
try_config_file(minetest.get_worldpath() .. "/" .. fileroot .. ".conf")
-- remove any special keys from tables
for key, value in pairs(C) do
if type(value) == 'table' then
value.CLEAR = nil
end
end
-- write back
M.config = C
|
local lsp_installer = require("nvim-lsp-installer")
local M = {}
M.lsp_map_keys = function(server, bufnr)
local function map_key(...)
-- Map to buffer if buffer number is supplied,
-- globally otherwise
if bufnr == nil then
vim.api.nvim_set_keymap(...)
else
vim.api.nvim_buf_set_keymap(bufnr, ...)
end
end
local keymapOpts = {noremap = true, silent = true}
map_key('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', keymapOpts)
map_key('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', keymapOpts)
map_key('n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', keymapOpts)
map_key('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', keymapOpts)
map_key('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>',
keymapOpts)
map_key('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>',
keymapOpts)
map_key('n', '<space>wr',
'<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', keymapOpts)
map_key('n', '<space>wl',
'<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>',
keymapOpts)
map_key('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>',
keymapOpts)
map_key('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', keymapOpts)
map_key('n', '<space>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>',
keymapOpts)
map_key('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', keymapOpts)
map_key('n', '<space>e',
'<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>',
keymapOpts)
map_key('n', '[d', '<cmd>lua vim.diagnostic.goto_prev()<CR>', keymapOpts)
map_key('n', ']d', '<cmd>lua vim.diagnostic.goto_next()<CR>', keymapOpts)
map_key('n', '<space>q', '<cmd>lua vim.diagnostic.set_loclist()<CR>',
keymapOpts)
map_key('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', keymapOpts)
end
-- Add additional capabilities supported by nvim-cmp
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities)
-- Register a handler that will be called for all installed servers.
lsp_installer.on_server_ready(function(server)
-- Don't setup jdtls here since it is done by nvim-jdtls
if server.name == "jdtls" then return end
local opts = {}
-- Lua specific settings
if server.name == "sumneko_lua" then
local runtime_path = vim.split(package.path, ';')
opts.settings = {
Lua = {
runtime = {
-- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
version = 'LuaJIT',
-- Setup your lua path
path = runtime_path
},
diagnostics = {
-- Get the language server to recognize the `vim` global
globals = {'vim'}
},
workspace = {
-- Make the server aware of Neovim runtime files
library = vim.api.nvim_get_runtime_file("", true)
},
-- Do not send telemetry data containing a randomized but unique identifier
telemetry = {enable = false}
}
}
end
opts.on_attach = M.lsp_map_keys
opts.capabilities = capabilities
server:setup(opts)
end)
return M
|
local common = require "upcache.common"
local console = common.console
local module = {}
local tagHeader = common.prefixHeader .. "-Tag"
-- monotonous version prefix - prevents key conflicts between nginx reboots
local MVP = ngx.time()
local function build_key(key, tags)
if tags == nil then return key end
local nkey = key
local mtags = ngx.shared.upcacheTags
local tagval
for i, tag in pairs(tags) do
tagval = mtags:get(tag)
if tagval == nil then tagval = MVP end
nkey = tag .. '=' .. tagval .. ' ' .. nkey
end
return nkey
end
function module.get(key)
return build_key(key, common.get_variants(key, 'tags'))
end
function module.set(key, headers)
local tags = headers[tagHeader];
if tags == nil then return nil end
if type(tags) ~= "table" then
tags = {tags}
end
local mtags = ngx.shared.upcacheTags
local tagval
for i, tag in pairs(tags) do
if (tag:sub(1,1) == '+') then
tag = tag:sub(2)
tags[i] = tag
tagval = mtags:get(tag)
if tagval == nil then
tagval = MVP
end
mtags:set(tag, tagval + 1)
end
end
table.sort(tags)
common.set_variants(key, 'tags', tags)
return build_key(key, tags)
end
return module;
|
--[[
# Control flow
--]]
-- #T# Table of contents
-- #C# Decision making
-- #C# - Conditional statements
-- #C# Loops
-- #C# - for loop
-- #C# - while loop
-- #C# - repeat-until loop
-- #T# Beginning of content
-- #C# Decision making
-- # |-------------------------------------------------------------
-- #T# decision making is made with the if, then, elseif, else, and end keywords
-- #T# in an if conditional statement a condition is checked and if it returns true, then the if block is executed, this also happens in an elseif conditional statement
-- #T# in an else conditional statement no condition is checked, but the else requires an if above it, the elseif also requires an if above it, the else block executes when the if and elseif blocks do not, and at the end of all this there must be the end keyword
-- #C# - Conditional statements
-- # |-----
-- #T# conditional statements are carried out with the following syntax
-- # SYNTAX if, elseif, else, conditional statements
-- # if condition1 then
-- # statements1
-- # elseif condition2 then
-- # statements2
-- # else
-- # statements3
-- # end
-- #T# if condition1 returns true then the statements1 are executed, else if condition2 returns true then statements2 are executed, else statements3 are executed. Decision making statements can be nested
int1 = false
if int1 then
int2 = 1
elseif not int1 then
if int1 == false then
int2 = 2
end
else
int2 = 3
end
-- # int2 == 2
-- #T# conditional statements can be made into a one liner
str1 = 'a'
if str1 == 'a' then print("in a one liner") elseif str1 == 'b' then print("in str1 = b") else print("in else") end -- # in a one liner
-- # |-----
-- # |-------------------------------------------------------------
-- #C# Loops
-- # |-------------------------------------------------------------
-- #T# loops are made with the for, while, and repeat-until constructs
-- #T# in a for loop, the loop is repeated for each element of an iterable, or for each number in an interval of numbers
-- #T# in a while loop, the loop is repeated as long as the while condition returns true
-- #T# in a repeat-until loop, the loop is repeated as long as the until condition returns false
-- #C# - for loop
-- # |-----
-- #T# the for loop is made with the following syntaxes
-- # SYNTAX for loop using an iterable
-- # for elem_i1 in iterable1 do
-- # statements1
-- # [break]
-- # end
-- #T# the loop executes the statements1 for each value in iterable1, said value is assigned to the iterator elem_i1 in each iteration
-- #T# the break keyword is used to skip all remaining iterations of the loop that contains the break, it must be placed at the end of its containing block
table1 = {'value1', 'value2', 'value3', 'unreachable1', 'unreachable2'}
for index1, val1 in ipairs(table1) do
print(val1)
if index1 == 3 then break end
end
-- #T# the former prints
-- # value1
-- # value2
-- # value3
-- # SYNTAX for loop using an interval of numbers
-- # for it1 = iniN, endN, stepN do
-- # statements1
-- # [break]
-- # end
-- #T# the loop executes statements1 for each value of it1, starting at iniN, ending at endN, and with a step of stepN, so iniN, endN, and stepN must be integers
for it1 = 1, 12, 3 do
print(it1)
end
-- #T# the former prints
-- # 1
-- # 4
-- # 7
-- # 10
-- # |-----
-- #C# - while loop
-- # |-----
-- #T# the while loop is made with the following syntax
-- # SYNTAX while loop
-- # while condition1 do
-- # statements1
-- # [break]
-- # end
-- #T# the statements1 are executed while condition1 returns true, (for the break keyword, see the for loop subsection)
int1 = 0
while (int1 < 80) do
int1 = int1 + 30
end
-- # int1 == 90
-- # |-----
-- #C# - repeat-until loop
-- # |-----
-- #T# the repeat-until loop is made with the following syntax
-- # SYNTAX repeat-until loop
-- # repeat
-- # statements1
-- # [break]
-- # until condition1
-- #T# the statements1 are executed as long as condition1 returns false, statements1 are executed at least one time (for the break keyword, see the for loop subsection)
int1 = 0
repeat
int1 = int1 + 30
until int1 > 80
-- # int1 == 90
-- # |-----
-- # |------------------------------------------------------------- |
-- General
vim.opt.autowrite = true
vim.opt.updatetime = 100 -- Faster updates, better UX
vim.opt.hidden = true -- Don't unload buffers when abandoned
vim.opt.encoding = "utf-8"
vim.opt.inccommand = "nosplit"
vim.opt.omnifunc = "syntaxcomplete#Complete"
vim.opt.mouse = "nv" -- Enable mouse support only for Normal and Visual modes
-- Dynamically toggle smartcase
-- ➤ Off when in a : command line
-- ➤ On when in a / command line
vim.opt.ignorecase = true
vim.opt.smartcase = true
vim.cmd [[
augroup DynamicSmartcase
autocmd!
autocmd CmdLineEnter * set nosmartcase
autocmd CmdLineLeave * set smartcase
augroup END
]]
-- Tabs & Indentation
vim.opt.tabstop = 4 -- Number of spaces that a <Tab> in the file counts for
vim.opt.shiftwidth = 4 -- Number of spaces to use for each step of indent
vim.opt.softtabstop = 4 -- Number of spaces that an inserted <Tab> counts for
vim.opt.expandtab = true -- Insert spaces when inserting a <Tab>
vim.opt.smarttab = true -- A <Tab> in front inserts according to 'shiftwidth'
vim.opt.autoindent = true -- Copy indent from current line on newline
vim.opt.cindent = true -- Automatic C program indenting
vim.opt.wrap = true -- Wrap long lines
vim.opt.breakindent = true -- Wrapped lines will be visually indented
vim.opt.showbreak = "…" .. string.rep(" ", 3)
vim.opt.linebreak = true -- Wrap lines on word boundaries (see :h breakat)
-- Splits {{{
vim.opt.splitright = true -- Splitting puts the new window on the right
-- Neovim Terminal
vim.cmd [[
" Enter terminal-mode automatically
autocmd TermOpen * startinsert
]]
-- UI
vim.opt.cursorline = true
vim.opt.colorcolumn = "80"
vim.opt.scrolloff = 8 -- Keep at least 8 lines above and below the cursor
vim.opt.pumblend = 17 -- Pseudo-transparency for the popup-menu
-- Hybrid line numbers
vim.opt.number = true
vim.opt.relativenumber = true
vim.cmd [[
augroup HybridLinenumber
autocmd!
autocmd BufEnter,FocusGained,InsertLeave * set relativenumber
autocmd BufLeave,FocusLost,InsertEnter * set norelativenumber
augroup END
]]
-- Highlight after yank
vim.cmd [[
augroup HighlightYank
autocmd!
autocmd TextYankPost * silent! lua require("vim.highlight").on_yank()
augroup END
]]
-- List mode symbols
-- ➤ Use `⇥ ` for tabs
-- ➤ Use `·` for trailing whitespaces
-- ➤ Use `⍽` for non-breaking spaces
-- ➤ Use `↵` for EOLs
vim.opt.list = true
vim.opt.listchars = { tab = "⇥ ", trail = "·", nbsp = "⍽", eol = "↵" }
-- Section Folding
vim.opt.foldenable = true
vim.opt.foldlevelstart = 10
vim.opt.foldnestmax = 10
vim.opt.foldmethod = "syntax"
-- Wildmenu
-- Ignore compiled files
vim.opt.wildignore = "__pycache__"
vim.opt.wildignore = vim.opt.wildignore + { "*.o", "*~", "*.pyc", "*pycache*" }
vim.opt.wildmode = "longest:full"
vim.opt.wildoptions = "pum"
-- Use the 'tex' filetype by default instead of 'plaintex'
vim.g.tex_flavor = "latex"
|
noble = {
"object/mobile/dressed_noble_bothan_female_01.iff",
"object/mobile/dressed_noble_bothan_male_01.iff",
"object/mobile/dressed_noble_fat_human_female_01.iff",
"object/mobile/dressed_noble_fat_human_female_02.iff",
"object/mobile/dressed_noble_fat_human_male_01.iff",
"object/mobile/dressed_noble_fat_human_male_02.iff",
"object/mobile/dressed_noble_fat_twilek_female_01.iff",
"object/mobile/dressed_noble_fat_twilek_female_02.iff",
"object/mobile/dressed_noble_fat_twilek_male_01.iff",
"object/mobile/dressed_noble_fat_twilek_male_02.iff",
"object/mobile/dressed_noble_fat_zabrak_female_01.iff",
"object/mobile/dressed_noble_fat_zabrak_female_02.iff",
"object/mobile/dressed_noble_fat_zabrak_male_01.iff",
"object/mobile/dressed_noble_fat_zabrak_male_02.iff",
"object/mobile/dressed_noble_human_female_01.iff",
"object/mobile/dressed_noble_human_female_02.iff",
"object/mobile/dressed_noble_human_female_03.iff",
"object/mobile/dressed_noble_human_female_04.iff",
"object/mobile/dressed_noble_human_male_01.iff",
"object/mobile/dressed_noble_human_male_02.iff",
"object/mobile/dressed_noble_human_male_03.iff",
"object/mobile/dressed_noble_human_male_04.iff",
"object/mobile/dressed_noble_old_human_female_01.iff",
"object/mobile/dressed_noble_old_human_female_02.iff",
"object/mobile/dressed_noble_old_human_male_01.iff",
"object/mobile/dressed_noble_old_human_male_02.iff",
"object/mobile/dressed_noble_old_twk_female_01.iff",
"object/mobile/dressed_noble_old_twk_female_02.iff",
"object/mobile/dressed_noble_old_twk_male_01.iff",
"object/mobile/dressed_noble_old_twk_male_02.iff",
"object/mobile/dressed_noble_old_zabrak_female_01.iff",
"object/mobile/dressed_noble_old_zabrak_female_02.iff",
"object/mobile/dressed_noble_old_zabrak_male_01.iff",
"object/mobile/dressed_noble_old_zabrak_male_02.iff",
"object/mobile/dressed_noble_rodian_female_01.iff",
"object/mobile/dressed_noble_rodian_male_01.iff",
"object/mobile/dressed_noble_trandoshan_female_01.iff",
"object/mobile/dressed_noble_trandoshan_male_01.iff",
"object/mobile/dressed_noble_twilek_female_01.iff",
"object/mobile/dressed_noble_twilek_male_01.iff",
"object/mobile/dressed_noble_zabrak_female_01.iff",
"object/mobile/dressed_noble_zabrak_male_01.iff"
}
addDressGroup("noble", noble)
|
local PlayerData = {}
local curMarker = nil
ESX = nil
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(0)
end
while ESX.GetPlayerData().job == nil do
Citizen.Wait(10)
end
PlayerData = ESX.GetPlayerData()
end)
function goToMarker(dest, veh)
local curPos = GetEntityCoords(p_Obj)
if veh then
local p_Obj = GetVehiclePedIsIn(PlayerPedId())
SetEntityCoords(p_Obj, dest.POS.x, dest.POS.y, dest.POS.z, dest.POS.h, 0, 0, 0)
else
local p_Obj = PlayerPedId()
SetEntityCoords(p_Obj, dest.POS.x, dest.POS.y, dest.POS.z, dest.POS.h, 0, 0, 0)
end
end
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
for _,markerIter in pairs(Config.Markers) do
local p_pos = GetEntityCoords(PlayerPedId())
local distance = GetDistanceBetweenCoords(p_pos, markerIter.POS.x, markerIter.POS.y, markerIter.POS.z, true)
if (distance < Config.DrawDistance) then
DrawMarker(1, markerIter.POS.x, markerIter.POS.y, markerIter.POS.z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, markerIter.Size.x, markerIter.Size.y, markerIter.Size.z, markerIter.Color.r, markerIter.Color.g, markerIter.Color.b, markerIter.Color.a, false, true, 2, false, false, false, false)
if distance < markerIter.Size.x and curMarker == nil then
curMarker = markerIter.Name
else
curMarker = nil
end
if IsControlJustReleased(1, 38) then
if curMarker ~= nil then
goToMarker(markerIter.Destination, markerIter.veh)
end
end
end
end
end
end) |
local LAvatar = class("LAvatar")
function LAvatar:ctor()
--静态数据
self._id = nil
self._card = nil -- enum.battle.card.skeletons
self._name = nil -- enum.battle.avatar.skeleton
self._moveType = nil -- enum.battle.moveType.land
self._side = enum.battle.side.red
self._hasSecondly = false --是否有二阶段,怪的类型
self._mass = 1
self._moveSpeed = 1
self._maxHp = 0
self._maxShieldHp = 0 --护盾值
self._deployCd = 1 --部署时间
self._attackSpeed = 1 --攻击速度
self._attackRange = 1 --攻击范围,半径
self._visualRange = 1 --视野范围,半径
--体积可能需要用多边形模拟
self._circle = 1.0
--动态数据
self._isDead = false
self._hp = 0
self._shieldHp = 0
self._pos = nil -- Vector2
self._nextPos = nil
self._buffers = {}
self._targetId = nil --目标单位
self._actionCd = 1 --下次攻击剩余多少帧
end
function LAvatar:init()
self._nextPos = self._pos
end
function LAvatar:posIn3D()
return Vector3(self._pos.x, self._moveType, self._pos.y)
end
function LAvatar:update()
if self._isDead then
return
end
-- 是否冰冻
if self:hasBuffer(enum.battle.buffer.stun) then
return
end
--移动,攻击
self._pos = self._nextPos
if self._actionCd > 0 then
self._actionCd = self._actionCd - 1
end
if self._targetId then
end
-- enum.battle.buffer.root
end
function LAvatar:isTargetInVisualRange()
end
function LAvatar:isTargetInAttackRange()
end
function LAvatar:isTargetValid()
end
function LAvatar:hasBuffer(name)
return self._buffers[name]
end
function LAvatar:appendBuffer(name)
self._buffers[name] = true --先设置成true
end
function LAvatar:removeBuffer(name)
self._buffers[name] = nil
end
return LAvatar
|
love.window.updateMode( 1000, 1000) |
return {
cbuilderlvl1 = {
acceleration = 0.04,
blocking = false,
brakerate = 0.4,
buildcostenergy = 13528,
buildcostmetal = 365,
builddistance = 100,
builder = true,
buildpic = "cbuilderlvl1.dds",
buildtime = 10000,
canfly = true,
canguard = true,
canmove = true,
canpatrol = true,
canreclaim = true,
canstop = 1,
category = "ALL MOBILE VTOL",
collide = false,
collisionvolumeoffsets = "0 0 0",
collisionvolumescales = "34 31 54",
collisionvolumetype = "ellipsoid",
cruisealt = 90,
description = "Tech Level 2",
dontland = 1,
energymake = 10,
energystorage = 50,
energyuse = 0,
explodeas = "BIG_UNITEX",
footprintx = 3,
footprintz = 3,
hoverattack = true,
icontype = "air",
idleautoheal = 5,
idletime = 1800,
losemitheight = 10,
mass = 365,
maxdamage = 705,
maxslope = 10,
maxvelocity = 7,
maxwaterdepth = 0,
metalmake = 0.1,
metalstorage = 25,
name = "Engineer Air",
objectname = "CBuilderLvl1.s3o",
radaremitheight = 27,
reclaimspeed = 22.5,
repairspeed = 22.5,
repairspeed = 35,
selfdestructas = "SMALL_UNIT_VTOL",
shownanospray = false,
sightdistance = 370,
turninplaceanglelimit = 360,
turninplacespeedlimit = 5.28,
turnrate = 353,
unitname = "cbuilderlvl1",
workertime = 45,
buildoptions = {
--[1] = "corsolar",
--[2] = "cormex",
--[3] = "coraap",
[4] = "cornanotc",
[5] = "coreyes",
[6] = "corshroud",
[7] = "corfort",
[8] = "corarad",
[9] = "cormine2",
[10] = "corhllt",
--[11] = "corvhlt",
[12] = "corvipe",
[13] = "cortoast",
[14] = "cordoom",
[15] = "corsam",
[16] = "corflak",
[17] = "corscreamer",
[18] = "cormds",
[19] = "cordl",
[20] = "corca",
[21] = "corhurc",
[22] = "corvamp",
},
customparams = {
buildpic = "cbuilderlvl1.dds",
faction = "CORE",
},
nanocolor = {
[1] = 0.12,
[2] = 0.47,
[3] = 0.47,
},
sfxtypes = {
pieceexplosiongenerators = {
[1] = "piecetrail0",
[2] = "piecetrail1",
[3] = "piecetrail2",
[4] = "piecetrail3",
[5] = "piecetrail4",
[6] = "piecetrail6",
},
},
},
}
|
--[[
Copyright 2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local tap = require('util/tap')
local test = tap.test
local path = require('path')
local fs = require('fs')
local Writable = require('stream').Writable
local text = [[Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.]]
local dirname = require('util').dirname()
test('fs.readstream length', function(expect)
local tmp_file = path.join(dirname, 'fixtures', 'test_readstream1.txt')
fs.writeFileSync(tmp_file, text)
local options = {
flags = 'r',
mode = '0644',
chunk_size = 65536,
offset = nil,
fd = nil,
length = 16, -- should stop at 16
}
local sink = Writable:new()
sink.str = {}
function sink:write(chunk) table.insert(self.str, chunk) end
local function onEnd()
local expected = string.sub(text, 1, options.length)
local readString = table.concat(sink.str, "")
console.log(expected, readString)
assert(expected == readString)
fs.unlinkSync(tmp_file)
end
local fp = fs.createReadStream(tmp_file, options)
fp:once('end', expect(onEnd))
fp:pipe(sink)
end)
test('fs.readstream offset and length', function(expect)
local tmp_file = path.join(dirname, 'fixtures', 'test_readstream2.txt')
fs.writeFileSync(tmp_file, text)
local options = {
flags = 'r',
mode = '0644',
chunk_size = 65536,
offset = 19,
fd = nil,
length = 16, -- should stop at 16
}
local sink = Writable:new()
sink.str = {}
function sink:write(chunk) table.insert(self.str, chunk) end
local function onEnd()
local expected = string.sub(text, options.offset + 1, options.length + options.offset)
local readString = table.concat(sink.str, "")
console.log(expected, readString)
assert(expected == readString)
fs.unlinkSync(tmp_file)
end
local fp = fs.createReadStream(tmp_file, options)
fp:once('end', expect(onEnd))
fp:pipe(sink)
end)
test('fs.readstream offset only', function(expect)
local tmp_file = path.join(dirname, 'test_readstream3.txt')
fs.writeFileSync(tmp_file, text)
local options = {
flags = 'r',
mode = '0644',
chunk_size = 65536,
offset = 16,
fd = nil,
length = nil,
}
local sink = Writable:new()
sink.str = {}
function sink:write(chunk) table.insert(self.str, chunk) end
local function onEnd()
assert(string.sub(text, options.offset + 1) == table.concat(sink.str, ""))
fs.unlinkSync(tmp_file)
end
local fp = fs.createReadStream(tmp_file, options)
fp:once('end', expect(onEnd))
fp:pipe(sink)
end)
tap.run()
|
data:extend({
{
type = "recipe",
name = "bery0zas-sparging-column",
category = "bery0zas-air-filtering-machine",
enabled = false,
energy_required = 10.0,
ingredients = {
{"electric-engine-unit", 3},
{"electronic-circuit", 3},
{"iron-plate", 10},
{"steel-plate", 10},
{"pipe", 10}
},
result = "bery0zas-sparging-column"
},
{
type = "recipe",
name = "bery0zas-spray-surface",
energy_required = 10,
category = "bery0zas-air-filtering-item",
enabled = false,
ingredients = {{"iron-plate", 2}, {"iron-stick", 6}},
icon = "__bery0zas-pure-it__/graphics/icons/spray-surface.png",
icon_size = 32,
subgroup = "intermediate-product",
results = {{ name = "bery0zas-spray-surface", amount = 1 }}
},
{
type = "recipe",
name = "bery0zas-iron-halite-extraction",
energy_required = 2,
category = "bery0zas-air-filtering-item",
enabled = false,
ingredients = {{"iron-ore", 20}},
icon = "__bery0zas-pure-it__/graphics/icons/recipe/iron-halite-extraction.png",
icon_size = 32,
subgroup = "raw-resource",
results =
{
{ name = "iron-ore", amount = 19 },
{ name = "bery0zas-halite", amount = 1 }
}
},
{
type = "recipe",
name = "bery0zas-copper-halite-extraction",
energy_required = 2,
category = "bery0zas-air-filtering-item",
enabled = false,
ingredients = {{"copper-ore", 20}},
icon = "__bery0zas-pure-it__/graphics/icons/recipe/copper-halite-extraction.png",
icon_size = 32,
subgroup = "raw-resource",
results =
{
{ name = "copper-ore", amount = 19 },
{ name = "bery0zas-halite", amount = 1 }
}
},
{
type = "recipe",
name = "bery0zas-adsorption-coil-mk1",
energy_required = 10,
category = "bery0zas-air-filtering-item",
enabled = false,
ingredients = {{"iron-plate", 3}, {"iron-stick", 8}},
icon = "__bery0zas-pure-it__/graphics/icons/adsorption-coil-mk1.png",
icon_size = 32,
subgroup = "intermediate-product",
results = {{ name = "bery0zas-adsorption-coil-mk1", amount = 1 }}
},
{
type = "recipe",
name = "bery0zas-adsorption-coil-mk2",
energy_required = 10,
category = "bery0zas-air-filtering-item",
enabled = false,
ingredients = {
{"steel-plate", 3},
{"iron-stick", 8}
},
icon = "__bery0zas-pure-it__/graphics/icons/adsorption-coil-mk2.png",
icon_size = 32,
subgroup = "intermediate-product",
results = {{ name = "bery0zas-adsorption-coil-mk2", amount = 1 }}
},
{
type = "recipe",
name = "bery0zas-adsorption-coil-mk1-with-activated-carbon",
energy_required = 3,
category = "bery0zas-air-filtering-item",
enabled = false,
ingredients =
{
{ name = "bery0zas-adsorption-coil-mk1", amount = 1},
{ name = "bery0zas-activated-carbon", amount = 1 }
},
icon = "__bery0zas-pure-it__/graphics/icons/adsorption-coil-mk1-with-activated-carbon.png",
icon_size = 32,
subgroup = "intermediate-product",
results = {{ name = "bery0zas-adsorption-coil-mk1-with-activated-carbon", amount = 1 }}
},
{
type = "recipe",
name = "bery0zas-adsorption-coil-mk2-with-cellular-carbon",
energy_required = 6,
category = "bery0zas-air-filtering-item",
enabled = false,
ingredients = {
{ name = "bery0zas-adsorption-coil-mk2", amount = 1 },
{ name = "bery0zas-cellular-carbon", amount = 1 }
},
icon = "__bery0zas-pure-it__/graphics/icons/adsorption-coil-mk2-with-cellular-carbon.png",
icon_size = 32,
subgroup = "intermediate-product",
results = {{ name = "bery0zas-adsorption-coil-mk2-with-cellular-carbon", amount = 1 }}
},
{
type = "recipe",
name = "bery0zas-spray-surface-recycling",
energy_required = 7,
category = "bery0zas-air-filtering-burning",
enabled = false,
ingredients = {{ name = "bery0zas-polluted-spray-surface", amount = 1 }},
icon = "__bery0zas-pure-it__/graphics/icons/recipe/polluted-spray-surface-recycling.png",
icon_size = 32,
subgroup = "smelting-machine",
results = {{ name = "bery0zas-spray-surface", amount = 1 }},
main_product = ""
},
{
type = "recipe",
name = "bery0zas-activated-carbon",
energy_required = 10,
category = "bery0zas-air-filtering-chemistry",
enabled = false,
ingredients =
{
{ type = "item", name = "coal", amount = 10 },
{ type = "fluid", name = "sulfuric-acid", amount = 20 }
},
icon = "__bery0zas-pure-it__/graphics/icons/activated-carbon.png",
icon_size = 32,
subgroup = "raw-resource",
results = {{ name = "bery0zas-activated-carbon", amount = 8 }}
},
{
type = "recipe",
name = "bery0zas-cellular-carbon",
energy_required = 10,
category = "bery0zas-air-filtering-chemistry",
enabled = false,
ingredients =
{
{ type = "item", name = "bery0zas-activated-carbon", amount = 10 },
{ type = "fluid", name = "petroleum-gas", amount = 20 }
},
icon = "__bery0zas-pure-it__/graphics/icons/cellular-carbon.png",
icon_size = 32,
subgroup = "raw-resource",
results = {{ name = "bery0zas-cellular-carbon", amount = 8 }}
},
{
type = "recipe",
name = "bery0zas-air-suction",
energy_required = 1,
category = "bery0zas-air-filtering-suction",
enabled = false,
ingredients = {{ type = "fluid", name = "bery0zas-pollution", amount = 1, fluidbox_index = 1 }},
icon = "__bery0zas-pure-it__/graphics/icons/fluid/steam.png",
icon_size = 32,
subgroup = "terrain",
results = {{ type = "fluid", name = "bery0zas-polluted-air", amount = 1 }},
main_product = ""
},
{
type = "recipe",
name = "bery0zas-water-absorption",
energy_required = 30,
category = "bery0zas-air-filtering-absorption",
enabled = false,
ingredients =
{
{ type = "fluid", name = "water", amount = 2, fluidbox_index = 1 },
{ type = "fluid", name = "bery0zas-polluted-air", amount = 2, fluidbox_index = 2 }
},
icon = "__bery0zas-pure-it__/graphics/icons/recipe/water-absorption.png",
icon_size = 32,
subgroup = "terrain",
results = {{type = "fluid", name = "bery0zas-polluted-water", amount = 4}},
main_product = ""
},
{
type = "recipe",
name = "bery0zas-oxygen-extraction",
energy_required = 10,
category = "bery0zas-air-filtering-chemistry",
enabled = false,
ingredients = {},
icon = "__bery0zas-pure-it__/graphics/icons/fluid/oxygen.png",
icon_size = 32,
subgroup = "fluid-recipes",
results = {{ type = "fluid", name = "bery0zas-oxygen", amount = 2 }},
main_product = ""
},
{
type = "recipe",
name = "bery0zas-oxygen-sparging",
energy_required = 20,
category = "bery0zas-air-filtering-sparging",
enabled = false,
ingredients =
{
{ type = "fluid", name = "water", amount = 10 },
{ type = "fluid", name = "bery0zas-oxygen", amount = 10 }
},
icon = "__bery0zas-pure-it__/graphics/icons/recipe/oxygen-sparging.png",
icon_size = 32,
subgroup = "fluid-recipes",
results = {
{
type = "fluid",
name = "bery0zas-oxygen-sparged-water",
amount = 20
}
},
main_product = ""
},
{
type = "recipe",
name = "bery0zas-oxygen-sparged-water-absorption",
energy_required = 20,
category = "bery0zas-air-filtering-absorption",
enabled = false,
ingredients =
{
{ type = "fluid", name = "bery0zas-oxygen-sparged-water", amount = 4, fluidbox_index = 1 },
{ type = "fluid", name = "bery0zas-polluted-air", amount = 4, fluidbox_index = 2 }
},
icon = "__bery0zas-pure-it__/graphics/icons/recipe/oxygen-sparged-water-absorption.png",
icon_size = 32,
subgroup = "terrain",
results = {{ type = "fluid", name = "bery0zas-polluted-water", amount = 8 }},
main_product = ""
},
{
type = "recipe",
name = "bery0zas-sodium-hydroxide-sparged-water-absorption",
energy_required = 15,
category = "bery0zas-air-filtering-absorption",
enabled = false,
ingredients =
{
{ type = "fluid", name = "bery0zas-sodium-hydroxide-sparged-water", amount = 12, fluidbox_index = 1 },
{ type = "fluid", name = "bery0zas-polluted-air", amount = 8, fluidbox_index = 2 }
},
icon = "__bery0zas-pure-it__/graphics/icons/recipe/sodium-hydroxide-sparged-water-absorption.png",
icon_size = 32,
subgroup = "terrain",
results = {{ type = "fluid", name = "bery0zas-polluted-water", amount = 16 }},
main_product = ""
},
{
type = "recipe",
name = "bery0zas-water-absorption-with-spraying",
energy_required = 20,
category = "bery0zas-air-filtering-absorption",
enabled = false,
ingredients =
{
{ type = "fluid", name = "water", amount = 2, fluidbox_index = 1 },
{ type = "fluid", name = "bery0zas-polluted-air", amount = 2, fluidbox_index = 2 },
{ type = "item", name = "bery0zas-spray-surface", amount = 2 }
},
icon = "__bery0zas-pure-it__/graphics/icons/recipe/water-absorption-with-spraying.png",
icon_size = 32,
subgroup = "terrain",
results =
{
{ type = "fluid", name = "bery0zas-polluted-water", amount = 4 },
{ type = "item", name = "bery0zas-polluted-spray-surface", amount = 2 }
}
},
{
type = "recipe",
name = "bery0zas-oxygen-sparged-water-absorption-with-spraying",
energy_required = 15,
category = "bery0zas-air-filtering-absorption",
enabled = false,
ingredients =
{
{ type = "fluid", name = "bery0zas-oxygen-sparged-water", amount = 4, fluidbox_index = 1},
{ type = "fluid", name = "bery0zas-polluted-air", amount = 4, fluidbox_index = 2 },
{ type = "item", name = "bery0zas-spray-surface", amount = 1 }
},
icon = "__bery0zas-pure-it__/graphics/icons/recipe/oxygen-sparged-water-absorption-with-spraying.png",
icon_size = 32,
subgroup = "terrain",
results =
{
{ type = "fluid", name = "bery0zas-polluted-water", amount = 8 },
{ type = "item", name = "bery0zas-polluted-spray-surface", amount = 1 }
}
},
{
type = "recipe",
name = "bery0zas-sodium-hydroxide",
energy_required = 10,
category = "bery0zas-air-filtering-chemistry",
enabled = false,
ingredients =
{
{ type = "fluid", name = "water", amount = 30 },
{ type = "item", name = "bery0zas-halite", amount = 3 }
},
icon = "__bery0zas-pure-it__/graphics/icons/fluid/sodium-hydroxide.png",
icon_size = 32,
subgroup = "fluid-recipes",
results = {
{
type = "fluid",
name = "bery0zas-sodium-hydroxide",
amount = 30
}
},
main_product = ""
},
{
type = "recipe",
name = "bery0zas-sodium-hydroxide-sparging",
energy_required = 20,
category = "bery0zas-air-filtering-sparging",
enabled = false,
ingredients =
{
{ type = "fluid", name = "water", amount = 10 },
{ type = "fluid", name = "bery0zas-sodium-hydroxide", amount = 10 }
},
icon = "__bery0zas-pure-it__/graphics/icons/recipe/sodium-hydroxide-sparging.png",
icon_size = 32,
subgroup = "fluid-recipes",
results = {
{
type = "fluid",
name = "bery0zas-sodium-hydroxide-sparged-water",
amount = 20
}
},
main_product = ""
},
{
type = "recipe",
name = "bery0zas-sodium-hydroxide-sparged-water-absorption-with-spraying",
energy_required = 10,
category = "bery0zas-air-filtering-absorption",
enabled = false,
ingredients =
{
{ type = "fluid", name = "bery0zas-sodium-hydroxide-sparged-water", amount = 8, fluidbox_index = 1 },
{ type = "fluid", name = "bery0zas-polluted-air", amount = 8, fluidbox_index = 2 },
{ type = "item", name = "bery0zas-spray-surface", amount = 1 }
},
icon = "__bery0zas-pure-it__/graphics/icons/recipe/sodium-hydroxide-sparged-water-absorption-with-spraying.png",
icon_size = 32,
subgroup = "terrain",
results =
{
{ type = "fluid", name = "bery0zas-polluted-water", amount = 16 },
{ type = "item", name = "bery0zas-polluted-spray-surface", amount = 1 }
}
},
{
type = "recipe",
name = "bery0zas-polluted-water-recycling",
energy_required = 10,
category = "bery0zas-air-filtering-chemistry",
enabled = false,
ingredients = {{ type = "fluid", name = "bery0zas-polluted-water", amount = 20 }},
icon = "__bery0zas-pure-it__/graphics/icons/recipe/polluted-water-recycling.png",
icon_size = 32,
subgroup = "fluid-recipes",
results =
{
{ type = "fluid", name = "water", amount = 15 },
{ type = "fluid", name = "crude-oil", probability = 0.05, amount = 20 },
{ type = "item", name = "coal", probability = 0.05, amount = 2 },
{ type = "item", name = "iron-ore", probability = 0.05, amount = 2 },
{ type = "item", name = "copper-ore", probability = 0.05, amount = 2 }
}
},
{
type = "recipe",
name = "bery0zas-coal-adsorption",
energy_required = 40,
category = "bery0zas-air-filtering-adsorption",
enabled = false,
ingredients =
{
{ type = "item", name = "coal", amount = 1 },
{ type = "fluid", name = "bery0zas-polluted-air", amount = 3, fluidbox_index = 2 }
},
icon = "__bery0zas-pure-it__/graphics/icons/coal.png",
icon_size = 32,
subgroup = "terrain",
results = {}
},
{
type = "recipe",
name = "bery0zas-coal-adsorption-with-steam",
energy_required = 40,
category = "bery0zas-air-filtering-adsorption",
enabled = false,
ingredients =
{
{ type = "item", name = "coal", amount = 2 },
{ type = "fluid", name = "steam", amount = 3, fluidbox_index = 1 },
{ type = "fluid", name = "bery0zas-polluted-air", amount = 5, fluidbox_index = 2 }
},
icon = "__bery0zas-pure-it__/graphics/icons/fluid/steam.png",
icon_size = 32,
subgroup = "terrain",
results = {}
},
{
type = "recipe",
name = "bery0zas-activated-carbon-adsorption",
energy_required = 40,
category = "bery0zas-air-filtering-adsorption",
enabled = false,
ingredients =
{
{ type = "item", name = "bery0zas-adsorption-coil-mk1-with-activated-carbon", amount = 1 },
{ type = "fluid", name = "bery0zas-polluted-air", amount = 8, fluidbox_index = 2 }
},
icon = "__bery0zas-pure-it__/graphics/icons/adsorption-coil-mk1-with-activated-carbon.png",
icon_size = 32,
subgroup = "terrain",
results =
{
{ type = "item", name = "bery0zas-adsorption-coil-mk1", amount = 1 }
},
main_product = ""
},
{
type = "recipe",
name = "bery0zas-cellular-carbon-adsorption",
energy_required = 40,
category = "bery0zas-air-filtering-adsorption",
enabled = false,
ingredients =
{
{ type = "item", name = "bery0zas-adsorption-coil-mk2-with-cellular-carbon", amount = 1 },
{ type = "fluid", name = "bery0zas-polluted-air", amount = 12, fluidbox_index = 2 }
},
icon = "__bery0zas-pure-it__/graphics/icons/adsorption-coil-mk2-with-cellular-carbon.png",
icon_size = 32,
subgroup = "terrain",
results = {{ type = "item", name = "bery0zas-adsorption-coil-mk2", amount = 1 }},
main_product = ""
}
})
|
XYZSettings.SettingsCache = {} -- or XYZSettings.SettingsCache or {}
XYZSettings.RegisteredSettings = {} -- or XYZSettings.SettingsCache or {}
-- Manage settings
function XYZSettings.GetSetting(setting, default)
if XYZSettings.SettingsCache[setting] ~= nil then
return XYZSettings.SettingsCache[setting]
end
return default or false
end
function XYZSettings.SetSetting(setting, value)
XYZSettings.Database.UpdateSetting(setting, value)
XYZSettings.SettingsCache[setting] = value
end
function XYZSettings.IsSetting(setting)
if XYZSettings.SettingsCache[setting] then
return true
end
return false
end
-- Types: 1 = text, 2 = number, 3 = dropdown options, 4 = toggle
-- Register settings
function XYZSettings.RegisterSetting(category, setting, type, name, desc, default, check, onComplete, options)
if not XYZSettings.RegisteredSettings[category] then
XYZSettings.RegisteredSettings[category] = {}
end
local cat = XYZSettings.RegisteredSettings[category]
if cat[setting] then return end
cat[setting] = {}
cat[setting].name = name
cat[setting].desc = desc
cat[setting].type = type
if type == 3 then
cat[setting].options = options
end
cat[setting].setting = setting
cat[setting].default = default
cat[setting].check = check
cat[setting].onComplete = onComplete
end
-- Extra stuff
list.Set("DesktopWindows", "Settings", {
title = "Settings Alias",
icon = "icon32/zoom_extend.png",
init = function()
XYZSettings.UI()
end
})
concommand.Add("xyz_settings_set", function(ply, cmd, args)
if not args[2] then return end
local value = args[2]
if value == "true" then
value = true
elseif value == "false" then
value = false
elseif isnumber(args[2]) then
value = tonumber(args[2])
elseif args[3] then
for k, v in pairs(args) do
if k < 3 then continue end
value = value.." "..v
end
end
XYZSettings.SetSetting(args[1], value)
end)
-- Existing configs
-- HUD
XYZSettings.RegisterSetting("HUD", "hud_show_master", 4, "Show HUD", "Show the entire HUD UI", true)
XYZSettings.RegisterSetting("HUD", "hud_show_license", 4, "Show License", "Show the license UI", true)
XYZSettings.RegisterSetting("HUD", "hud_show_wanted", 4, "Show Wanted", "Show the wanted UI", true)
XYZSettings.RegisterSetting("HUD", "hud_show_lockdown", 4, "Show Lockdown", "Show the lockdown UI", true)
XYZSettings.RegisterSetting("HUD", "hud_show_others", 4, "Show Player Overheads", "Show the overhead above players", true)
-- 911 System
XYZSettings.RegisterSetting("911", "911_show_marker", 4, "Show Marker", "Show the 911 location marker on screen", true)
XYZSettings.RegisterSetting("911", "911_show_minimap", 4, "Show Minimap", "Show the 911 location marker on minimap", true)
-- Cars
XYZSettings.RegisterSetting("Cars", "cars_customs_underglow", 4, "Render Underglow", "Show the underglow on cars", true)
-- EMS
XYZSettings.RegisterSetting("EMS", "ems_show_marker", 4, "Show Death Marker", "Show the death location marker on screen", true)
XYZSettings.RegisterSetting("EMS", "ems_show_bodybag_marker", 4, "Show Bodybag Marker", "Show the bodybag location marker on screen", true)
-- Event
XYZSettings.RegisterSetting("Event", "event_show_popup", 4, "Show Join Popup", "Show the join event popup", true)
-- Meeting
XYZSettings.RegisterSetting("Meeting", "meeting_show_overlay", 4, "Show Overlay", "Show the large meeting overlay", true)
-- Panic Button
XYZSettings.RegisterSetting("Panic Button", "panic_show_marker", 4, "Show Marker", "Show the panic location marker on screen", true)
XYZSettings.RegisterSetting("Panic Button", "panic_show_minimap", 4, "Show Minimap", "Show the panic location marker on minimap", true)
-- Partner System
XYZSettings.RegisterSetting("Partner", "partner_show_hud", 4, "Show HUD", "Show your partners HUD above your own", true)
XYZSettings.RegisterSetting("Partner", "partner_show_halo", 4, "Show Outline", "Show a outline around your partner", true)
XYZSettings.RegisterSetting("Partner", "partner_distance_halo", 2, "Outline Distance (Units)", "The point the outline stops rendering", 800000)
-- Robable NPC
XYZSettings.RegisterSetting("Robable Store", "rs_show_marker", 4, "Show Store Marker", "Show the store location marker on screen", true)
-- Playtime
XYZSettings.RegisterSetting("Playtime", "playtime_show_hud", 4, "Show Playtime HUD", "Show your playtime HUD", true)
XYZSettings.RegisterSetting("Playtime", "playtime_show_target_hud", 4, "Show Target's Playtime HUD", "Show the person you're looking at's playtime", true)
-- Voicechat
XYZSettings.RegisterSetting("Voice-Chat", "voicechat_show_hud", 4, "Show Voice-Chat HUD", "Show the voice-chat HUD", true)
-- Chat Box
XYZSettings.RegisterSetting("Chat Box", "textbox_show_rank_tags", 4, "Show Rank Tags", "Show user's rank tags on their messages (E.g: Staff, Elite, VIP...)", true)
XYZSettings.RegisterSetting("Chat Box", "textbox_show_custom_tags", 4, "Show Custom Tags", "Show user's custom tags on their messages", true)
XYZSettings.RegisterSetting("Chat Box", "textbox_history_length", 2, "Message History Length", "How many messages of history you can scroll back to", 50)
XYZSettings.RegisterSetting("Chat Box", "textbox_show_timestamps", 4, "Show Timestamps", "Show message timestamps", true)
-- Party
XYZSettings.RegisterSetting("Party", "party_show_hud", 4, "Show Party HUD", "Show your party's HUD", true)
XYZSettings.RegisterSetting("Party", "party_show_halo", 4, "Show Outline", "Show a outline around your party members", true)
XYZSettings.RegisterSetting("Party", "party_show_pings", 4, "Show Pings", "Show pings made by your party members (Concommand: xyz_party_ping)", true)
-- 3rd Person
XYZSettings.RegisterSetting("Camera", "cam_toggle", 4, "Toggle Third Person", "Toggles the third person view", false)
XYZSettings.RegisterSetting("Camera", "cam_type", 3, "Camera Type", "What type of camera to use", "Third Person", nil, nil, {"Third person", "Over the shoulder"})
XYZSettings.RegisterSetting("Camera", "cam_distance", 2, "Camera Distance", "The distance from the player", 50)
-- Rainbow Physgun
XYZSettings.RegisterSetting("Rainbow PhysGun", "rainbowphysgun_enable", 4, "Enable Rainbow", "Should physguns be rainbow (Where applicable)", true)
XYZSettings.RegisterSetting("Rainbow PhysGun", "rainbowphysgun_speed", 2, "Rainbow Speed", "The speed of the rainbow", 50)
-- NPC Overhead
XYZSettings.RegisterSetting("NPC Overhead", "overhead_toggle", 4, "Toggle Overhead", "Should NPC overheads be shown?", true)
XYZSettings.RegisterSetting("NPC Overhead", "overhead_position", 3, "Overhead Position", "The position style of NPC overheads", "Side", nil, nil, {"Side", "Top"})
XYZSettings.RegisterSetting("NPC Overhead", "overhead_distance", 2, "Overhead Distance", "The distance overhead shoudl stop rendering", 400000)
-- xAdmin
XYZSettings.RegisterSetting("xAdmin", "xadmin_chat_messages", 4, "Show Chat Messages", "Show chat messages like teleporting, cloaking ect...", true)
-- xSits
XYZSettings.RegisterSetting("xSits", "xsits_toggle_sound", 4, "Play Sound", "Show a sound play when a new sit is made", true)
XYZSettings.RegisterSetting("xSits", "xsits_sound", 3, "Alert Sound", "The sound to play when a sit comes in", "Voice 1", nil, nil, {"Voice 1", "Voice 2", "Voice 3", "Bell 1", "Bell 2", "Bell 3"})
XYZSettings.RegisterSetting("xSits", "xsits_show", 4, "Show Unclaimed Sits", "Show unclaimed sits menu (Staff-Lead+)", true)
-- Loading Intro
XYZSettings.RegisterSetting("Loading Intro", "intro_toggle_show", 4, "Show Loading Intro", "Show the loading card", true)
-- Rewards
XYZSettings.RegisterSetting("Rewards", "rewards_open_join", 4, "Show Rewards On Join", "Show the rewards UI on join", true)
-- Debug menu
XYZSettings.RegisterSetting("Staff", "staff_debug_menu", 4, "Show Debug Menu", "Show the debug menu when looking at items", true)
-- Speedometer
XYZSettings.RegisterSetting("Speedometer", "speedometer_toggle_show", 4, "Show Speedometer", "Show the speedometer", true)
-- Minimap
XYZSettings.RegisterSetting("Minimap", "minimap_toggle_hud", 4, "Show Minimap HUD", "Show the minimap on your HUD", true)
XYZSettings.RegisterSetting("Minimap", "minimap_show_overlay", 4, "Show Minimap Overlay", "Show the minimap on overlay when pressing M", true)
XYZSettings.RegisterSetting("Minimap", "minmap_show_icons", 4, "Show Minimap Icons", "Show the icons on the minimap", true)
XYZSettings.RegisterSetting("Minimap", "minmap_hud_zoom", 2, "HUD Minimap Zoom", "How zoomed the HUD minimap is", 4)
XYZSettings.RegisterSetting("Minimap", "minmap_clamp_icons", 4, "Clamp Minimap Icons", "Clamp Minimap icons to the edge", true)
-- Halloween
XYZSettings.RegisterSetting("Halloween", "halloween_pumpkin_show", 4, "Show Pumpkin Heads", "Show pumpkin heads on everyone", true)
-- Radio
XYZSettings.RegisterSetting("Car Radio", "cardradio_toggle_play", 4, "Play Car Radio", "Play the radio from a car", true)
XYZSettings.RegisterSetting("Car Radio", "cardradio_volume_cap", 2, "Max Volume", "The max volume to allow", 30)
-- PNC
XYZSettings.RegisterSetting("PNC", "pnc_pt_show_marker", 4, "Show Prisoner Transport Marker", "Show Prisoner Transport location marker on HUD", true)
XYZSettings.RegisterSetting("PNC", "pnc_pt_show_minimap", 4, "Show Prisoner Transport Minimap", "Show Prisoner Transport location marker on minimap", true)
|
local M = {}
local timers = {}
function M.frames(frames, callback)
if frames == 0 then
callback()
else
table.insert(timers, {frames = frames, callback = callback})
end
end
function M.seconds(seconds, callback)
table.insert(timers, {seconds = seconds, callback = callback})
end
function M.cancel_all()
timers = {}
end
function M.update(dt)
for k, timer in pairs(timers) do
if timer.frames then
timer.frames = timer.frames - 1
if timer.frames <= 0 then
timers[k] = nil
timer.callback()
end
elseif timer.seconds then
timer.seconds = timer.seconds - dt
if timer.seconds <= 0 then
timers[k] = nil
timer.callback()
end
end
end
end
return M
|
local materials = {
[9] = true,
[19] = true,
[21] = true,
[23] = true,
[24] = true,
[31] = true,
[32] = true,
[35] = true,
[38] = true,
[40] = true,
[43] = true,
[46] = true,
[47] = true,
[48] = true,
}
function Main.update:Mud()
if not IsDriver or not Materials then return end
local mudRatio = 0.0
local rainLevel = GetRainLevel()
local wheelType = GetVehicleWheelType(CurrentVehicle)
local isOffroad = wheelType == 4 --or classType == ?
for wheelIndex, material in pairs(Materials) do
if materials[material] then
mudRatio = mudRatio + (isOffroad and 0.5 or 1.0)
end
end
if mudRatio < 0.001 then return end
mudRatio = 1.0 / (mudRatio * (rainLevel * 0.5 + 0.5))
if mudRatio < 0.001 or mudRatio > 1.001 then return end
BrakeModifier = BrakeModifier * mudRatio
MaxFlatModifier = MaxFlatModifier * math.pow(mudRatio, 2.0)
TractionCurveModifier = TractionCurveModifier * (1.0 + mudRatio * 0.5)
TractionLossModifier = TractionLossModifier * mudRatio
end |
att.PrintName = "Power"
att.Icon = Material("snowysnowtime/2k/ico/h3/smg_sil.png")
att.Description = "Changing the internals allows the M7 SMG to be much more efficient. It has increased recoil due to this."
att.Desc_Pros = {
"+ Increased Rate of Fire (10%)"
}
att.Desc_Cons = {
"- Increased Recoil (15%)",
"- Reduced Damage (10%)"
}
att.SortOrder = 997
att.Slot = "variant_smgho"
att.Mult_Recoil = 1.3
att.AttachSound = "attch/snow/halo/h3/x_button.wav"
att.DetachSound = "attch/snow/halo/h3/b_button.wav"
att.ActivateElements = {"pwr_body"}
att.GivesFlags = {"pwr_body"} |
local GetVariable = BP.BaseClass(BP.Node)
function GetVariable:Constructor( graph )
self.is_updatable_bp_node = true
self.graph = graph
print('Cat:GetVariable.lua[5] graph', graph)
end
function GetVariable:Update( deltaTime )
print('Cat:GetVariable.lua[8] update')
end
return GetVariable |
--[[
Copyright (C) Udorn (Blackhand)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--]]
--[[
Cell object for rendering texts. Input for the cell is:
text
--]]
vendor.TextCell = {}
vendor.TextCell.prototype = {}
vendor.TextCell.metatable = {__index = vendor.TextCell.prototype}
setmetatable(vendor.TextCell.prototype, {__index = vendor.ItemTableCell.prototype})
--[[
Shows information if mouse is over the selected item
--]]
local function _OnEnterItem(but)
local self = but.obj
if (self.tooltip) then
GameTooltip:SetOwner(but, "ANCHOR_RIGHT")
GameTooltip:SetText(self.tooltip, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, 1, true)
end
end
--[[
Initializes the cell.
--]]
local function _Init(self)
local frame = CreateFrame("Button", nil, self.parent)
frame.obj = self
frame:EnableMouse(true)
frame:SetWidth(self.width)
frame:SetHeight(self.height)
frame:SetScript("OnEnter", _OnEnterItem)
frame:SetScript("OnLeave", function() GameTooltip:Hide() end)
local f = self.parent:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall")
f:SetAllPoints(frame)
if (self.align) then
f:SetJustifyH(self.align)
end
self.frame = frame
self.fontString = f
end
--[[
Creates a new instance.
--]]
function vendor.TextCell:new(parent, width, height, align)
local instance = setmetatable({}, self.metatable)
instance.parent = parent
instance.width = width
instance.height = height
instance.align = align
_Init(instance)
return instance
end
--[[
Updates the cell with the required input parameters of the cell.
--]]
function vendor.TextCell.prototype:Update(text, tooltip)
if (text and self.align == "LEFT") then
text = " "..text
end
self.fontString:SetText(text or "")
self.tooltip = tooltip
end
|
pace.StreamQueue = pace.StreamQueue or {}
local frame_number = 0
local last_frame
local ERROR_COLOR = Color(228, 37, 37)
local function catchError(err)
pac.Message(ERROR_COLOR, 'Error: ', err)
pac.Message(debug.traceback())
end
timer.Create("pac_check_stream_queue", 0.1, 0, function()
if not pace.BusyStreaming and #pace.StreamQueue ~= 0 then
xpcall(pace.SubmitPart, catchError, unpack(table.remove(pace.StreamQueue)))
end
frame_number = frame_number + 1
end)
local function make_copy(tbl, input)
if tbl.self.UniqueID then
tbl.self.UniqueID = pac.Hash(tbl.self.UniqueID .. input)
end
for key, val in pairs(tbl.children) do
make_copy(val, input)
end
end
local function net_write_table(tbl)
local buffer = pac.StringStream()
buffer:writeTable(tbl)
local data = buffer:getString()
local ok, err = pcall(net.WriteStream, data)
if not ok then
return ok, err
end
return #data
end
pace.dupe_ents = pace.dupe_ents or {}
local uid2key = include("legacy_network_dictionary_translate.lua")
local function translate_old_dupe(tableIn, target)
for key, value2 in pairs(tableIn) do
local value
if type(value2) == 'table' then
value = translate_old_dupe(value2, {})
else
value = value2
end
if type(key) == 'number' and key > 10000 then
local str = uid2key[key] or key
target[str] = value
else
target[key] = value
end
end
return target
end
duplicator.RegisterEntityModifier("pac_config", function(ply, ent, parts)
if parts.json then
parts = util.JSONToTable(parts.json)
parts = translate_old_dupe(parts, {})
end
local id = ent:EntIndex()
if parts.part then
parts = {[parts.part.self.UniqueID] = parts}
end
ent.pac_parts = parts
pace.dupe_ents[ent:EntIndex()] = {owner = ply, ent = ent}
-- give source engine time
timer.Simple(0, function()
for uid, data in pairs(parts) do
if type(data.part) == "table" then
make_copy(data.part, id)
data.part.self.Name = tostring(ent)
data.part.self.OwnerName = id
end
data.owner = ply
data.uid = pac.Hash(ply)
data.is_dupe = true
-- clientside sent variables cleanup for sanity
data.wear_filter = nil
data.partID = nil
data.totalParts = nil
data.transmissionID = nil
pace.SubmitPart(data)
end
end)
end)
function pace.SubmitPart(data, filter)
if type(data.part) == "table" then
if last_frame == frame_number then
table.insert(pace.StreamQueue, {data, filter})
pace.dprint("queuing part %q from %s", data.part.self.Name, tostring(data.owner))
return "queue"
end
end
-- last arg "true" is pac3 only in case you need to do your checking differnetly from pac2
local allowed, reason = hook.Run("PrePACConfigApply", data.owner, data, true)
if type(data.part) == "table" then
local ent = Entity(tonumber(data.part.self.OwnerName) or -1)
if ent:IsValid() then
if not pace.CanPlayerModify(data.owner, ent) then
allowed = false
reason = "you are not allowed to modify this entity: " .. tostring(ent) .. " owned by: " .. tostring(ent.CPPIGetOwner and ent:CPPIGetOwner() or "world")
else
if not data.is_dupe then
ent.pac_parts = ent.pac_parts or {}
ent.pac_parts[pac.Hash(data.owner)] = data
pace.dupe_ents[ent:EntIndex()] = {owner = data.owner, ent = ent}
duplicator.ClearEntityModifier(ent, "pac_config")
--duplicator.StoreEntityModifier(ent, "pac_config", ent.pac_parts)
--duplicator.StoreEntityModifier(ent, "pac_config", {json = util.TableToJSON(ent.pac_parts)})
-- fresh table copy
duplicator.StoreEntityModifier(ent, "pac_config", {json = util.TableToJSON(table.Copy(ent.pac_parts))})
end
ent:CallOnRemove("pac_config", function(ent)
if ent.pac_parts then
for _, data in pairs(ent.pac_parts) do
if type(data.part) == "table" then
data.part = data.part.self.UniqueID
end
pace.RemovePart(data)
end
end
end)
end
end
end
if data.uid ~= false then
if allowed == false then return allowed, reason end
if pace.IsBanned(data.owner) then return false, "you are banned from using pac" end
end
local uid = data.uid
pace.Parts[uid] = pace.Parts[uid] or {}
if type(data.part) == "table" then
pace.Parts[uid][data.part.self.UniqueID] = data
else
if data.part == "__ALL__" then
pace.Parts[uid] = {}
filter = true
for key, v in pairs(pace.dupe_ents) do
if v.owner:IsValid() and v.owner == data.owner then
if v.ent:IsValid() and v.ent.pac_parts then
v.ent.pac_parts = nil
duplicator.ClearEntityModifier(v.ent, "pac_config")
end
end
pace.dupe_ents[key] = nil
end
elseif data.part then
pace.Parts[uid][data.part] = nil
-- this doesn't work because the unique id is different for some reason
-- use clear for now if you wanna clear a dupes outfit
--[[for key, v in pairs(pace.dupe_ents) do
if v.owner:IsValid() and v.owner == data.owner then
if v.ent:IsValid() and v.ent.pac_parts then
local id = pac.Hash(data.part .. v.ent:EntIndex())
v.ent.pac_parts[id] = nil
duplicator.ClearEntityModifier(v.ent, "pac_config")
duplicator.StoreEntityModifier(v.ent, "pac_config", v.ent.pac_parts)
return
else
pace.dupe_ents[key] = nil
end
else
pace.dupe_ents[key] = nil
end
end]]
end
end
local players
if IsValid(data.temp_wear_filter) and type(data.temp_wear_filter) == "Player" then
players = {data.temp_wear_filter}
elseif type(data.wear_filter) == 'table' then
players = {}
for _, id in ipairs(data.wear_filter) do
local ply = pac.ReverseHash(id, "Player")
if ply:IsValid() then
table.insert(players, ply)
end
end
else
players = player.GetAll()
end
if filter == false then
filter = data.owner
elseif filter == true then
local tbl = {}
for k, v in pairs(players) do
if v ~= data.owner then
table.insert(tbl, v)
end
end
filter = tbl
end
if not data.server_only then
if data.owner:IsValid() then
data.player_uid = pac.Hash(data.owner)
end
local players = filter or players
if type(players) == "table" then
for key = #players, 1, -1 do
local ply = players[key]
if not ply.pac_requested_outfits and ply ~= data.owner then
table.remove(players, key)
end
end
if pace.GlobalBans and data.owner:IsValid() then
local owner_steamid = data.owner:SteamID()
for key, ply in pairs(players) do
local steamid = ply:SteamID()
for var, reason in pairs(pace.GlobalBans) do
if var == steamid or type(var) == "table" and (table.HasValue(var, steamid) or table.HasValue(var, util.CRC(ply:IPAddress():match("(.+):") or ""))) then
table.remove(players, key)
if owner_steamid == steamid then
pac.Message("Dropping data transfer request by '", ply:Nick(), "' due to a global PAC ban.")
return false, "You have been globally banned from using PAC. See global_bans.lua for more info."
end
end
end
end
end
elseif type(players) == "Player" and (not players.pac_requested_outfits and players ~= data.owner) then
data.transmissionID = nil
return true
end
if not players or type(players) == "table" and not next(players) then return true end
-- Alternative transmission system
local ret = hook.Run("pac_SendData", players, data)
if ret == nil then
net.Start("pac_submit")
local bytes, err = net_write_table(data)
if not bytes then
ErrorNoHalt("[PAC3] Outfit broadcast failed for " .. tostring(data.owner) .. ": " .. tostring(err) .. '\n')
if data.owner and data.owner:IsValid() then
data.owner:ChatPrint('[PAC3] ERROR: Could not broadcast your outfit: ' .. tostring(err))
end
else
net.Send(players)
end
end
if type(data.part) == "table" then
last_frame = frame_number
pace.CallHook("OnWoreOutfit", data.owner, data.part)
end
end
-- nullify transmission ID
data.transmissionID = nil
return true
end
function pace.SubmitPartNotify(data)
pace.dprint("submitted outfit %q from %s with %i number of children to set on %s", data.part.self.Name or "", data.owner:GetName(), table.Count(data.part.children), data.part.self.OwnerName or "")
local allowed, reason = pace.SubmitPart(data)
if data.owner:IsPlayer() then
if allowed == "queue" then return end
if not reason and allowed and type(data.part) == 'table' then
reason = string.format('Your part %q has been applied', data.part.self.Name or '<unknown>')
end
net.Start("pac_submit_acknowledged")
net.WriteBool(allowed)
net.WriteString(reason or "")
net.WriteString(data.part.self.Name or "no name")
net.Send(data.owner)
hook.Run("PACSubmitAcknowledged", data.owner, util.tobool(allowed), reason or "", data.part.self.Name or "no name", data)
end
end
function pace.RemovePart(data)
pace.dprint("%s is removed %q", data.owner and data.owner:IsValid() and data.owner:GetName(), data.part)
if data.part == "__ALL__" then
pace.CallHook("RemoveOutfit", data.owner)
end
pace.SubmitPart(data, data.filter)
end
function pace.HandleReceivedData(ply, data)
data.owner = ply
data.uid = pac.Hash(ply)
if data.wear_filter and #data.wear_filter > game.MaxPlayers() then
pac.Message("Player ", ply, " tried to submit extraordinary wear filter size of ", #data.wear_filter, ", dropping.")
data.wear_filter = nil
end
if type(data.part) == "table" and data.part.self then
if type(data.part.self) == "table" and not data.part.self.UniqueID then return end -- bogus data
pace.SubmitPartNotify(data)
elseif type(data.part) == "string" then
pace.RemovePart(data)
end
end
util.AddNetworkString("pac_submit")
timer.Create("pac_submit_spam", 3, 0, function()
for k, ply in ipairs(player.GetAll()) do
ply.pac_submit_spam = math.max((ply.pac_submit_spam or 0) - 5, 0)
ply.pac_submit_spam2 = math.max((ply.pac_submit_spam2 or 0) - 5, 0)
if ply.pac_submit_spam_msg then
ply.pac_submit_spam_msg = ply.pac_submit_spam >= 20
end
if ply.pac_submit_spam_msg2 then
ply.pac_submit_spam_msg2 = ply.pac_submit_spam2 >= 20
end
end
end)
local pac_submit_spam = CreateConVar('pac_submit_spam', '1', {FCVAR_NOTIFY, FCVAR_ARCHIVE}, 'Prevent users from spamming pac_submit')
local pac_submit_limit = CreateConVar('pac_submit_limit', '30', {FCVAR_NOTIFY, FCVAR_ARCHIVE}, 'pac_submit spam limit')
pace.PCallNetReceive(net.Receive, "pac_submit", function(len, ply)
if pac.CallHook("CanWearParts", ply) == false then
return
end
if pac_submit_spam:GetBool() and not game.SinglePlayer() then
-- data is too short, not even 8 bytes
if len < 64 then return end
ply.pac_submit_spam = ply.pac_submit_spam + 1
if ply.pac_submit_spam >= pac_submit_limit:GetInt() then
if not ply.pac_submit_spam_msg then
pac.Message("Player ", ply, " is spamming pac_submit!")
ply.pac_submit_spam_msg = true
end
return
end
end
net.ReadStream(ply, function(data)
if not data then
pac.Message("message from ", ply, " timed out")
return
end
if not ply:IsValid() then
pac.Message("received message from ", ply, " but player is no longer valid!")
return
end
local buffer = pac.StringStream(data)
pace.HandleReceivedData(ply, buffer:readTable())
end)
end)
function pace.ClearOutfit(ply)
local uid = pac.Hash(ply)
pace.SubmitPart({part = "__ALL__", uid = pac.Hash(ply), owner = ply})
pace.CallHook("RemoveOutfit", ply)
end
function pace.RequestOutfits(ply)
if not ply:IsValid() then return end
if ply.pac_requested_outfits_time and ply.pac_requested_outfits_time > RealTime() then return end
ply.pac_requested_outfits_time = RealTime() + 30
ply.pac_requested_outfits = true
ply.pac_gonna_receive_outfits = true
pace.UpdateWearFilters()
timer.Simple(6, function()
if not IsValid(ply) then return end
ply.pac_gonna_receive_outfits = false
for id, outfits in pairs(pace.Parts) do
local owner = pac.ReverseHash(id, "Player")
if owner:IsValid() and owner:IsPlayer() and owner.GetPos and id ~= pac.Hash(ply) then
for key, outfit in pairs(outfits) do
if not outfit.wear_filter or table.HasValue(outfit.wear_filter, pac.Hash(ply)) then
pace.SubmitPart(outfit, ply)
end
end
end
end
end)
end
concommand.Add("pac_request_outfits", pace.RequestOutfits)
|
local Tunnel = module("vrp", "lib/Tunnel")
local Proxy = module("vrp", "lib/Proxy")
vRP = Proxy.getInterface("vRP")
vRPclient = Tunnel.getInterface("vRP", "vrp_mugging")
cooldownlist = {}
RegisterServerEvent('vrp_mugging:giveMoney')
AddEventHandler('vrp_mugging:giveMoney', function()
local user_id = vRP.getUserId({source})
local amount = math.random(Config.MinMoney, Config.MaxMoney)
print('tring to add cash')
vRP.giveMoney({user_id,amount})
TriggerClientEvent('mythic_notify:client:SendAlert', source, { type = 'success', text = 'Du stjal '.. amount .. '$', length = '5000', style = {}})
end)
RegisterServerEvent('vrp_mugging:giveItems')
AddEventHandler('vrp_mugging:giveItems', function(itemName)
local user_id = vRP.getUserId({source})
vRP.giveInventoryItem({user_id,itemName,1})
end)
RegisterServerEvent("vrp_mugging:call")
AddEventHandler(
"vrp_mugging:call",
function( x, y)
local random = math.random(1, 4) -- Get a random number 3-10 (10%)
if random == 2 then -- If the number = 5, make a police call
call(x, y)
end
end
)
-------------------------------------
------------- Functions -------------
-------------------------------------
function call(x, y)
local answered = false -- Make sure the request isn't answered - predefined variable
local players = {} -- Table - Players with "police.service" permissions
local user_id = vRP.getUserId({source}) -- Get user_id - Not using it
local users = vRP.getUsers() -- Get all players
for k, v in pairs(users) do -- Loop - for each player
local player = vRP.getUserSource({tonumber(k)}) -- Get source of current player
if vRP.hasPermission({k, Config.RequiredPermission}) and player then -- If current player has permissions to "police.service"
table.insert(players, player) -- Insert current player into my table called "players"
end
end
for k, v in pairs(players) do -- Loop - for each player in my table called "players"
vRP.request({v, Config.Language.RequiredPermission, 30, function(v, ok) -- Make a request
if ok then -- If the player accept the request
if not answered then -- If it's not accepted
vRPclient.setGPS(v, {x, y}) -- Set GPS coordinates
answered = true -- accept the call
else
vRPclient.notify(v, {Config.Language.CallAlreadyTaken}) -- If the request already accepted
end
end
end})
end
end
|
-- sponsorblock.lua
--
-- This script skips sponsored segments of YouTube videos
-- using data from https://github.com/ajayyy/SponsorBlock
local ON_WINDOWS = package.config:sub(1,1) ~= '/'
local options = {
server_address = "https://api.sponsor.ajay.app",
python_path = ON_WINDOWS and "python" or "python3",
-- If true, sponsored segments will only be skipped once
skip_once = true,
-- Note that sponsored segments may ocasionally be inaccurate if this is turned off
-- see https://ajay.app/blog.html#voting-and-pseudo-randomness-or-sponsorblock-or-youtube-sponsorship-segment-blocker
local_database = true,
-- Update database on first run, does nothing if local_database is false
auto_update = true,
-- User ID used to submit sponsored segments, leave blank for random
user_id = "",
-- Name to display on the stats page https://sponsor.ajay.app/stats/ leave blank to keep current name
display_name = "",
-- Tell the server when a skip happens
report_views = true,
-- Auto upvote skipped sponsors
auto_upvote = true,
-- Use sponsor times from server if they're more up to date than our local database
server_fallback = true,
-- Minimum duration for sponsors (in seconds), segments under that threshold will be ignored
min_duration = 1,
-- Fade audio for smoother transitions
audio_fade = false,
-- Audio fade step, applied once every 100ms until cap is reached
audio_fade_step = 10,
-- Audio fade cap
audio_fade_cap = 0,
-- Fast forward through sponsors instead of skipping
fast_forward = false,
-- Playback speed modifier when fast forwarding, applied once every second until cap is reached
fast_forward_increase = .2,
-- Playback speed cap
fast_forward_cap = 2,
-- Pattern for video id in local files, ignored if blank
-- Recommended value for base youtube-dl is "-([%a%d%-_]+)%.[mw][kpe][v4b][m]?$"
local_pattern = ""
}
mp.options = require "mp.options"
mp.options.read_options(options, "sponsorblock")
local legacy = mp.command_native_async == nil
if legacy then
options.local_database = false
end
local utils = require "mp.utils"
local scripts_dir = mp.find_config_file("scripts")
local sponsorblock = utils.join_path(scripts_dir, "shared/sponsorblock.py")
local uid_path = utils.join_path(scripts_dir, "shared/sponsorblock.txt")
local database_file = options.local_database and utils.join_path(scripts_dir, "shared/sponsorblock.db") or ""
local youtube_id = nil
local ranges = {}
local init = false
local segment = {a = 0, b = 0, progress = 0}
local retrying = false
local last_skip = {uuid = "", dir = nil}
local speed_timer = nil
local fade_timer = nil
local fade_dir = nil
local volume_before = mp.get_property_number("volume")
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then io.close(f) return true else return false end
end
function t_count(t)
local count = 0
for _ in pairs(t) do count = count + 1 end
return count
end
function getranges(_, exists, db, more)
if type(exists) == "table" and exists["status"] == "1" then
if options.server_fallback then
mp.add_timeout(0, function() getranges(true, true, "") end)
else
return mp.osd_message("[sponsorblock] database update failed, gave up")
end
end
if db ~= "" and db ~= database_file then db = database_file end
if exists ~= true and not file_exists(db) then
if not retrying then
mp.osd_message("[sponsorblock] database update failed, retrying...")
retrying = true
end
return update()
end
if retrying then
mp.osd_message("[sponsorblock] database update succeeded")
retrying = false
end
local sponsors
local args = {
options.python_path,
sponsorblock,
"ranges",
db,
options.server_address,
youtube_id
}
if not legacy then
sponsors = mp.command_native({name = "subprocess", capture_stdout = true, playback_only = false, args = args})
else
sponsors = utils.subprocess({args = args})
end
if not string.match(sponsors.stdout, "^%s*(.*%S)") then return end
if string.match(sponsors.stdout, "error") then return getranges(true, true) end
local new_ranges = {}
local r_count = 0
if more then r_count = -1 end
for t in string.gmatch(sponsors.stdout, "[^:%s]+") do
uuid = string.match(t, '[^,]+$')
if ranges[uuid] then
new_ranges[uuid] = ranges[uuid]
else
start_time = tonumber(string.match(t, '[^,]+'))
end_time = tonumber(string.sub(string.match(t, ',[^,]+'), 2))
if end_time - start_time >= options.min_duration then
new_ranges[uuid] = {
start_time = start_time,
end_time = end_time,
skipped = false
}
end
end
r_count = r_count + 1
end
local c_count = t_count(ranges)
if c_count == 0 or r_count >= c_count then
ranges = new_ranges
end
end
function fast_forward()
local last_speed = mp.get_property_number("speed")
local new_speed = math.min(last_speed + options.fast_forward_increase, options.fast_forward_cap)
if new_speed <= last_speed then return end
mp.set_property("speed", new_speed)
end
function fade_audio(step)
local last_volume = mp.get_property_number("volume")
local new_volume = math.max(options.audio_fade_cap, math.min(last_volume + step, volume_before))
if new_volume == last_volume then
if step >= 0 then fade_dir = nil end
if fade_timer ~= nil then fade_timer:kill() end
fade_timer = nil
return
end
mp.set_property("volume", new_volume)
end
function skip_ads(name, pos)
if pos == nil then return end
local sponsor_ahead = false
for uuid, t in pairs(ranges) do
if (options.fast_forward == uuid or not options.skip_once or not t.skipped) and t.start_time <= pos and t.end_time > pos then
if options.fast_forward == uuid then return end
if options.fast_forward == false then
mp.osd_message("[sponsorblock] sponsor skipped")
mp.set_property("time-pos", t.end_time)
else
mp.osd_message("[sponsorblock] skipping sponsor")
end
t.skipped = true
last_skip = {uuid = uuid, dir = nil}
if options.report_views or options.auto_upvote then
local args = {
options.python_path,
sponsorblock,
"stats",
database_file,
options.server_address,
youtube_id,
uuid,
options.report_views and "1" or "",
uid_path,
options.user_id,
options.auto_upvote and "1" or ""
}
if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end)
else
utils.subprocess_detached({args = args})
end
end
if options.fast_forward ~= false then
options.fast_forward = uuid
speed_timer = mp.add_periodic_timer(1, fast_forward)
end
return
elseif (not options.skip_once or not t.skipped) and t.start_time <= pos + 1 and t.end_time > pos + 1 then
sponsor_ahead = true
end
end
if options.audio_fade then
if sponsor_ahead then
if fade_dir ~= false then
if fade_dir == nil then volume_before = mp.get_property_number("volume") end
if fade_timer ~= nil then fade_timer:kill() end
fade_dir = false
fade_timer = mp.add_periodic_timer(.1, function() fade_audio(-options.audio_fade_step) end)
end
elseif fade_dir == false then
fade_dir = true
if fade_timer ~= nil then fade_timer:kill() end
fade_timer = mp.add_periodic_timer(.1, function() fade_audio(options.audio_fade_step) end)
end
end
if options.fast_forward and options.fast_forward ~= true then
options.fast_forward = true
speed_timer:kill()
mp.set_property("speed", 1)
end
end
function vote(dir)
if last_skip.uuid == "" then return mp.osd_message("[sponsorblock] no sponsors skipped, can't submit vote") end
local updown = dir == "1" and "up" or "down"
if last_skip.dir == dir then return mp.osd_message("[sponsorblock] " .. updown .. "vote already submitted") end
last_skip.dir = dir
local args = {
options.python_path,
sponsorblock,
"stats",
database_file,
options.server_address,
youtube_id,
last_skip.uuid,
"",
uid_path,
options.user_id,
dir
}
if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end)
else
utils.subprocess({args = args})
end
mp.osd_message("[sponsorblock] " .. updown .. "vote submitted")
end
function update()
mp.command_native_async({name = "subprocess", playback_only = false, args = {
options.python_path,
sponsorblock,
"update",
database_file,
options.server_address
}}, getranges)
end
function file_loaded()
local initialized = init
ranges = {}
segment = {a = 0, b = 0, progress = 0}
last_skip = {uuid = "", dir = nil}
local video_path = mp.get_property("path")
local youtube_id1 = string.match(video_path, "https?://youtu%.be/([%a%d%-_]+).*")
local youtube_id2 = string.match(video_path, "https?://w?w?w?%.?youtube%.com/v/([%a%d%-_]+).*")
local youtube_id3 = string.match(video_path, "/watch%?v=([%a%d%-_]+).*")
local youtube_id4 = string.match(video_path, "/embed/([%a%d%-_]+).*")
local local_pattern = nil
if options.local_pattern ~= "" then
local_pattern = string.match(video_path, options.local_pattern)
end
youtube_id = youtube_id1 or youtube_id2 or youtube_id3 or youtube_id4 or local_pattern
if not youtube_id then return end
init = true
if not options.local_database then
getranges(true, true)
else
local exists = file_exists(database_file)
if exists and options.server_fallback then
getranges(true, true)
mp.add_timeout(0, function() getranges(true, true, "", true) end)
elseif exists then
getranges(true, true)
elseif options.server_fallback then
mp.add_timeout(0, function() getranges(true, true, "") end)
end
end
if initialized then return end
mp.observe_property("time-pos", "native", skip_ads)
if options.display_name ~= "" then
local args = {
options.python_path,
sponsorblock,
"username",
database_file,
options.server_address,
youtube_id,
"",
"",
uid_path,
options.user_id,
options.display_name
}
if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end)
else
utils.subprocess_detached({args = args})
end
end
if not options.local_database or (not options.auto_update and file_exists(database_file)) then return end
update()
end
function set_segment()
if not youtube_id then return end
local pos = mp.get_property_number("time-pos")
if pos == nil then return end
if segment.progress > 1 then
segment.progress = segment.progress - 2
end
if segment.progress == 1 then
segment.progress = 0
segment.b = pos
mp.osd_message("[sponsorblock] segment boundary B set, press again for boundary A", 3)
else
segment.progress = 1
segment.a = pos
mp.osd_message("[sponsorblock] segment boundary A set, press again for boundary B", 3)
end
end
function submit_segment()
if not youtube_id then return end
local start_time = math.min(segment.a, segment.b)
local end_time = math.max(segment.a, segment.b)
if end_time - start_time == 0 or end_time == 0 then
mp.osd_message("[sponsorblock] empty segment, not submitting")
elseif segment.progress <= 1 then
mp.osd_message(string.format("[sponsorblock] press Shift+G again to confirm: %.2d:%.2d:%.2d to %.2d:%.2d:%.2d", start_time/(60*60), start_time/60%60, start_time%60, end_time/(60*60), end_time/60%60, end_time%60), 5)
segment.progress = segment.progress + 2
else
mp.osd_message("[sponsorblock] submitting segment...", 30)
local submit
local args = {
options.python_path,
sponsorblock,
"submit",
database_file,
options.server_address,
youtube_id,
tostring(start_time),
tostring(end_time),
uid_path,
options.user_id
}
if not legacy then
submit = mp.command_native({name = "subprocess", capture_stdout = true, playback_only = false, args = args})
else
submit = utils.subprocess({args = args})
end
if string.match(submit.stdout, "success") then
segment = {a = 0, b = 0, progress = 0}
mp.osd_message("[sponsorblock] segment submitted")
elseif string.match(submit.stdout, "error") then
mp.osd_message("[sponsorblock] segment submission failed, server may be down. try again", 5)
elseif string.match(submit.stdout, "502") then
mp.osd_message("[sponsorblock] segment submission failed, server is down. try again", 5)
elseif string.match(submit.stdout, "400") then
mp.osd_message("[sponsorblock] segment submission failed, impossible inputs", 5)
segment = {a = 0, b = 0, progress = 0}
elseif string.match(submit.stdout, "429") then
mp.osd_message("[sponsorblock] segment submission failed, rate limited. try again", 5)
elseif string.match(submit.stdout, "409") then
mp.osd_message("[sponsorblock] segment already submitted", 3)
segment = {a = 0, b = 0, progress = 0}
else
mp.osd_message("[sponsorblock] segment submission failed", 5)
end
end
end
mp.register_event("file-loaded", file_loaded)
mp.add_key_binding("g", "sponsorblock_set_segment", set_segment)
mp.add_key_binding("G", "sponsorblock_submit_segment", submit_segment)
mp.add_key_binding("h", "sponsorblock_upvote", function() return vote("1") end)
mp.add_key_binding("H", "sponsorblock_downvote", function() return vote("0") end)
|
local PANEL = {}
local outpadding = 14
local padding = 5
local stripeW = 5
local MAT_FAILED = Material("lambda/failed.png")
local MAT_SUCCESS = Material("lambda/success.png")
function PANEL:Init()
self:SetTitle("")
self:SetPos(padding, ScrH() * 0.25)
self:SetDeleteOnClose(false)
self:ShowCloseButton(false)
self:SetDraggable(false)
self:SetVisible(true)
self.currentVote = nil
self.choiceScore = {}
self.smoothChoiceScore = {}
self.lastTimeLeft = 99999
self.totalPlayers = 0
end
function PANEL:UpdateVote(vote)
if self.currentVote ~= nil then
-- Only play when being updated.
surface.PlaySound("buttons/button16.wav")
end
self.currentVote = vote
self.choiceScore = {}
self.smoothChoiceScore = self.smoothChoiceScore or {}
for k,v in pairs(vote.options) do
self.choiceScore[k] = 0
self.smoothChoiceScore[k] = self.smoothChoiceScore[k] or 0
end
for k,v in pairs(vote.results) do
self.choiceScore[v] = self.choiceScore[v] + 1
end
end
function PANEL:SetVoteResults(vote)
if vote.failed == false then
surface.PlaySound("buttons/button14.wav")
else
surface.PlaySound("buttons/button19.wav")
end
end
function PANEL:Think()
local vote = self.currentVote
if vote == nil then
return
end
for k,v in pairs(self.choiceScore) do
self.smoothChoiceScore[k] = Lerp(FrameTime() * 20, self.smoothChoiceScore[k], self.choiceScore[k])
end
if vote.finished ~= true then
local totalTime = vote.endtime - vote.starttime
local timeLeft = math.Round(vote.endtime - GetSyncedTimestamp())
if timeLeft < self.lastTimeLeft and timeLeft > 0 and (timeLeft <= (totalTime * 0.5)) then
self.lastTimeLeft = timeLeft
surface.PlaySound("buttons/blip1.wav")
end
local plys = player.GetAll()
for _,v in pairs(vote.excluded) do
table.RemoveByValue(plys, v)
end
self.totalPlayers = #plys
end
end
function PANEL:Paint(w, h)
local text
local textW, textH = 0, 0
local padding = 5
local paddingChoice = 10
local x, y = 10, 5
local maxW = 10
local vote = self.currentVote
local ply = vote.issuer
local params = vote.params
local text = ""
surface.SetDrawColor(0, 0, 0, 230)
surface.DrawRect(0, 0, w, h)
surface.SetDrawColor(255, 147, 30, 230)
surface.DrawRect(0, 0, 5, h)
surface.SetFont("lambda_sb_def_sm")
-- Issuer
do
if IsValid(ply) then
text = "Vote called by " .. ply:Name()
else
text = "Vote called by host"
end
surface.SetTextColor(255, 255, 255, 230)
surface.SetTextPos(x, y)
surface.DrawText(text)
textW, textH = surface.GetTextSize(text)
y = y + textH + padding
maxW = math.max(maxW, textW)
end
surface.SetFont("lambda_sb_def")
local widthDesc = 0
-- Description.
do
if vote.finished ~= true then
local timeLeft = math.Round(vote.endtime - GetSyncedTimestamp())
if timeLeft < 0 then
timeLeft = 0
end
text = string.format("%02d - ", timeLeft)
else
if vote.failed ~= true then
local timeLeft = math.Round(vote.actionTime - GetSyncedTimestamp())
if timeLeft < 0 then
timeLeft = 0
end
text = string.format("%02d - ", timeLeft)
else
text = ""
end
end
if vote.type == VOTE_TYPE_KICK_PLAYER then
local kickingPlayer = params.Player
text = text .. "Kick player: " .. kickingPlayer:Name()
elseif vote.type == VOTE_TYPE_SKIP_MAP then
text = text .. "Skip to next map: " .. params.NextMap
elseif vote.type == VOTE_TYPE_RESTART_MAP then
text = text .. "Restart current map"
elseif vote.type == VOTE_TYPE_CHANGE_MAP then
text = text .. "Change to map: " .. params.Map
elseif vote.type == VOTE_TYPE_NEXT_MAP then
text = text .. "Choose next map"
end
surface.SetTextPos(x, y)
surface.SetTextColor(255, 147, 30, 230)
surface.DrawText(text)
textW, textH = surface.GetTextSize(text)
y = y + textH + padding
widthDesc = textW + padding + 100
maxW = math.max(maxW, widthDesc)
end
surface.SetFont("lambda_sb_def_sm")
local seperatorY = y
local seperatorX = x
-- Seperator.
do
y = y + 1 + padding
end
-- Info.
if vote.finished ~= true and vote.canVote == true then
do
text = "Press the corresponding number to vote."
surface.SetTextColor(255, 255, 255, 230)
surface.SetTextPos(x, y)
surface.DrawText(text)
textW, textH = surface.GetTextSize(text)
y = y + textH + paddingChoice
maxW = math.max(maxW, textW)
end
else
y = y + paddingChoice
end
-- Choices
local choiceMargin = 10
local maxChoiceW = 0
local choiceY = y
for k,v in pairs(vote.options) do
text = tostring(k) .. "."
if vote.finished ~= true then
surface.SetTextColor(255, 147, 30, 230)
else
if vote.winningOption == k then
surface.SetTextColor(255, 147, 30, 230)
else
surface.SetTextColor(100, 100, 100, 100)
end
end
surface.SetTextPos(x + choiceMargin, y)
surface.DrawText(text)
textW, textH = surface.GetTextSize(text)
local numberMargin = math.max(textW, 15)
text = v
if vote.finished ~= true then
if vote.choice == k then
surface.SetTextColor(255, 147, 30, 230)
else
surface.SetTextColor(255, 255, 255, 230)
end
else
if vote.winningOption == k then
surface.SetTextColor(255, 147, 30, 230)
else
surface.SetTextColor(100, 100, 100, 100)
end
end
surface.SetTextPos(x + choiceMargin + numberMargin, y)
surface.DrawText(text)
textW, textH = surface.GetTextSize(text)
maxChoiceW = math.max(maxChoiceW, textW + numberMargin)
y = y + textH + paddingChoice
maxW = math.max(maxW, textW + choiceMargin)
end
maxChoiceW = math.max(maxChoiceW, 100) + 20
local barWidth = 100
for k,v in pairs(vote.options) do
local score = self.choiceScore[k]
local smoothScore = self.smoothChoiceScore[k]
text = tostring(score)
if vote.finished ~= true then
surface.SetTextColor(255, 255, 255, 230)
else
if vote.winningOption == k and vote.failed ~= true then
surface.SetTextColor(255, 255, 255, 230)
else
surface.SetTextColor(100, 100, 100, 100)
end
end
surface.SetTextPos(x + choiceMargin + maxChoiceW + padding, choiceY)
surface.DrawText(text)
textW, textH = surface.GetTextSize(text)
local textSpace = math.max(textW, 15)
maxW = math.max(maxW, textW + choiceMargin + padding + maxChoiceW + textSpace + barWidth)
local barSize = (smoothScore / self.totalPlayers) * barWidth
if vote.finished ~= true then
surface.SetDrawColor(255, 147, 30, 230)
else
if vote.winningOption == k and vote.failed ~= true then
surface.SetDrawColor(255, 147, 30, 230)
else
surface.SetDrawColor(100, 100, 100, 100)
end
end
surface.DrawRect(x + choiceMargin + maxChoiceW + padding + textSpace, choiceY + 6, barSize, 5)
choiceY = choiceY + textH + paddingChoice
end
-- Seperator
do
surface.SetDrawColor(255, 255, 255, 155)
surface.DrawLine(seperatorX, seperatorY, seperatorX + maxW, seperatorY + 1)
end
-- Icon
if vote.finished == true then
do
if vote.failed == true then
surface.SetMaterial(MAT_FAILED)
else
surface.SetMaterial(MAT_SUCCESS)
end
surface.DrawTexturedRect(5 + maxW + padding - 32 - 5, 10, 32, 32)
end
end
self:SetSize(stripeW + padding + maxW + padding, y)
end
vgui.Register( "HudVote", PANEL, "DFrame" )
|
wrk.method = "POST"
wrk.body = string.rep("body", 1000000)
wrk.headers["Content-Type"] = "application/x-www-form-urlencoded"
|
-----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Sharin-Garin
-- Type: Adventurer's Assistant
-- !pos 122.658 -1.315 33.001 50
-----------------------------------
local ID = require("scripts/zones/Aht_Urhgan_Whitegate/IDs")
-----------------------------------
require("scripts/globals/besieged")
require("scripts/globals/keyitems")
require("scripts/globals/npc_util")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local mercRank = tpz.besieged.getMercenaryRank(player)
local hasPermit = player:hasKeyItem(tpz.ki.RUNIC_PORTAL_USE_PERMIT) and 1 or 0
local points = player:getCurrency("imperial_standing")
local hasAstral = tpz.besieged.getAstralCandescence()
local cost = 200 -- 200 IS to get a permit
local captain = mercRank == 11 and 1 or 0
player:startEvent(140, 0, mercRank, hasPermit, points, hasAstral, cost, captain)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 140 and option == 1 and npcUtil.giveKeyItem(player, tpz.ki.RUNIC_PORTAL_USE_PERMIT) then
player:delCurrency("imperial_standing", 200)
elseif csid == 140 and option == 2 then
npcUtil.giveKeyItem(player,tpz.ki.RUNIC_PORTAL_USE_PERMIT)
end
end
|
object_tangible_deed_pet_deed_droideka_deed = object_tangible_deed_pet_deed_shared_droideka_deed:new {
}
ObjectTemplates:addTemplate(object_tangible_deed_pet_deed_droideka_deed, "object/tangible/deed/pet_deed/droideka_deed.iff")
|
--------------------------------------------------------------------------------
-- TODO:
-- * Decide if use function calls in the style:
-- - string.len(s), or
-- - s:len()
-- It is in the first form now, check if it works in the second form and change
-- in all the code.
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- AUXILIARY
--------------------------------------------------------------------------------
-- An wallet of all variable that we must want to throw away when finished.
local ENV = {}
-- set global options. This is mostly during the main port that is necessary,
-- as all things inside ENV table.
ENV.debug = true
ENV.compatibility = false
function ENV.DEBUG (msg)
if ENV.debug then print ("[debug] " .. msg) end
end
ENV.DEBUG("BEGIN config")
ENV.DEBUG("lua version: " .. _VERSION)
ENV.DEBUG ("-- AUXILIARY")
-- workaround to call this script outside conky env.
function ENV.fake_conky_env()
if not conky then
ENV.DEBUG("Faking conky env")
conky = {text=nil, config={}}
end
end
-- FROM: http://stackoverflow.com/questions/9168058/lua-beginner-table-dump-to-console/22460068#22460068
-- SRC: https://gist.github.com/ripter/4270799
-- Print contents of `tbl`, with indentation.
-- `indent` sets the initial level of indentation.
function ENV.tprint(tbl, indent)
if not indent then indent = 0 end
for k, v in pairs(tbl) do
formatting = string.rep(" ", indent) .. k .. ": "
if type(v) == "table" then
print(formatting)
ENV.tprint(v, indent+1)
elseif type(v) == 'boolean' then
print(formatting .. tostring(v))
else
print(formatting .. v)
end
end
end
-- FROM: https://coronalabs.com/blog/2014/09/02/tutorial-printing-table-contents/
-- SRC: https://github.com/robmiracle/print_r
function ENV.print_r(t)
local print_r_cache={}
local function sub_print_r(t,indent)
if (print_r_cache[tostring(t)]) then
print(indent.."*"..tostring(t))
else
print_r_cache[tostring(t)]=true
if (type(t)=="table") then
for pos,val in pairs(t) do
if (type(val)=="table") then
print(indent.."["..pos.."] => "..tostring(t).." {")
sub_print_r(val,indent..string.rep(" ",string.len(pos)+8))
print(indent..string.rep(" ",string.len(pos)+6).."}")
elseif (type(val)=="string") then
print(indent.."["..pos..'] => "'..val..'"')
else
print(indent.."["..pos.."] => "..tostring(val))
end
end
else
print(indent..tostring(t))
end
end
end
if (type(t)=="table") then
print(tostring(t).." {")
sub_print_r(t," ")
print("}")
else
sub_print_r(t," ")
end
print()
end
-- split string per sep tokens suplied.
-- Default to split per space type (%s) chars.
-- Return a list of substrings.
function split_string(s, sep)
sep = sep or "%s"
local match = "[^" .. sep .. "]+"
local list = {}
for word in string.gmatch(s, match) do
table.insert(list, word)
end
return list
end
function table_contains(table, element)
for _, value in pairs(table) do
if value == element then
return true
end
end
return false
end
function array_contains(table, element)
for key, value in pairs(table) do
if type(key) == "number" and
value == element then
return true
end
end
return false
end
--------------------------------------------------------------------------------
-- INFO FUNCTIONS
--------------------------------------------------------------------------------
ENV.DEBUG ("-- INFO FUNCTIONS")
function get_hostname()
local hostname = io.popen('hostname'):read('l')
return hostname
end
function get_homepath()
local homepath = os.getenv("HOME")
return homepath
end
function get_cpu_count()
local syspath = '/sys/devices/system/cpu/present'
local cpu_present = io.input(syspath):read('l')
local count = tonumber(string.match(cpu_present, "%d+-(%d+)")) + 1
return count
end
function get_cpu_count1()
local count = 0
local proc_cpuinfo = io.input('/proc/cpuinfo'):read('a')
for cpu in string.gmatch(proc_cpuinfo, "processor") do
count = count + 1
end
return count
end
function get_cpu_count2()
local count = 0
for line in io.lines('/proc/cpuinfo') do
if string.find(line, 'processor', 1, true) then
count = count + 1
end
end
return count
end
function get_cpu_count3()
local count = 0
for line in io.lines('/proc/stat') do
if string.find(line, '^cpu%d+ ') then
count = count + 1
end
end
return count
end
function get_fstab_entries()
local entries = {}
for line in io.lines('/etc/fstab') do
local list = split_string(line)
if #list == 6 and string.sub(list[1], 1, 1) ~= "#" then
local mountline = {
filesystem = list[1],
mountpoint = list[2],
fstype = list[3],
options = split_string(list[4], ","),
dump = tonumber(list[5]),
pass = tonumber(list[6])
}
table.insert(entries, mountline)
end
end
return entries
end
function ip_parse_new_eth(line)
local id, name, anglebrackets, flags =
string.match(line, "^(%d+): (%w+): <(%g+)> (.*) ?$")
id = tonumber(id)
anglebrackets = split_string(anglebrackets, ",")
flags = split_string(flags)
local eth = {
id = id,
name = name,
anglebrackets = anglebrackets,
flags = flags,
raw = line
}
return eth
end
function ip_parse_cfg_linkether(line)
return split_string(line)
end
function ip_parse_cfg_inet(line)
return split_string(line)
end
function ip_parse_cfg_inet6(line)
return split_string(line)
end
function ip_parse_cfg_bridge(line)
return split_string(line)
end
function ip_parse_cfg_bridge_slave(line)
return split_string(line)
end
function ip_parse_cfg(line, eth)
local t = split_string(line)[1]
local cfg_list = nil
if t == "link/ether" then
cfg_list = ip_parse_cfg_linkether(line)
elseif t == "inet" then
cfg_list = ip_parse_cfg_inet(line)
elseif t == "int6" then
cfg_list = ip_parse_cfg_inet6(line)
elseif t == "bridge" then
cfg_list = ip_parse_cfg_bridge(line)
elseif t == "bridge_slave" then
cfg_list = ip_parse_cfg_bridge_slave(line)
else
cfg_list = split_string(line)
end
local cfg = {
id = t,
cfg = cfg_list,
raw = line
}
return cfg
end
function ip_parse_cfg_flags(line, eth, cfg)
local flags_list = split_string(line)
local flags = {
flags = flags_list,
raw = line
}
return flags
end
function get_eth_interfaces()
local interfaces = {}
local eth = nil
local cfg = nil
local flags = nil
for line in io.popen('ip -d addr'):lines() do
local prefix = string.match(line, '^ *')
if string.len(prefix) == 0 then
eth = ip_parse_new_eth(line)
interfaces[eth.id] = eth
elseif string.len(prefix) == 4 then
cfg = ip_parse_cfg(line, eth)
interfaces[eth.id][cfg.id] = cfg
elseif string.len(prefix) == 7 then
flags = ip_parse_cfg_flags(line, eth, cfg)
interfaces[eth.id][cfg.id].flags = flags
end
end
return interfaces
end
function select_mountpoints(remotefs)
remotefs = remotefs or true
local mountpoints = {}
local fstab = get_fstab_entries()
for index, entry in pairs(fstab) do
if entry.mountpoint ~= "none" and
entry.fstype ~= "swap" and
(remotefs or entry.fstype ~= "sshfs") and
(remotefs or entry.fstype ~= "nfs") and
(remotefs or string.sub(entry.filesystem, 1, 5) == "/dev/")
then
-- match mountpoint as a subpath of the user homepath.
-- If so, abreviate the path.
local pattern = "^" .. get_homepath() .. "/"
local label, matchs = string.gsub(entry.mountpoint, pattern, "~/")
local noauto = array_contains(entry.options, "noauto")
local mountpoint = entry.mountpoint
local mpoint = {
mountpoint = mountpoint,
label = label,
noauto = noauto
}
table.insert(mountpoints, mpoint)
end
end
return mountpoints
end
--------------------------------------------------------------------------------
-- SET DEFAULTS
--------------------------------------------------------------------------------
ENV.COMPATIBILITY_DEFAULTS = {
cpu_count = 8,
top_entries = 10,
network_interfaces = {"wlan0", "eth0", "ens1",
"enp3s0", "wlp16s0", "wlp2s0"
},
filesystems_mountpoints = {
{mountpoint = "/", label = "/", noauto = false},
{mountpoint = "/boot", label = "/boot", noauto = false},
{mountpoint = "/home", label = "/home", noauto = false},
{mountpoint = "/mnt/data", label = "/mnt/data", noauto = true},
{mountpoint = "/mnt/BRUNO", label = "/mnt/BRUNO", noauto = true}
}
}
ENV.STATIC_DEFAULTS = {
cpu_count = 8,
top_entries = 10,
network_interfaces = {"enp3s0", "wlp2s0", "br0"},
filesystems_mountpoints = {
{mountpoint = "/",
label = "/",
noauto = false
},
{mountpoint = "/boot",
label = "/boot",
noauto = false
},
{mountpoint = "/home",
label = "/home",
noauto = false
},
{mountpoint = "/mnt/data",
label = "/mnt/data",
noauto = true
},
{mountpoint = "/mnt/BRUNO",
label = "/mnt/BRUNO",
noauto = true
},
{mountpoint = "/home/raoni/mnt/lsc_maritaca.nfs",
label = "~/mnt/lsc_maritaca.nfs",
noauto = true
},
{mountpoint = "/home/raoni/mnt/phd_manaus.sshfs",
label = "~/mnt/phd_manaus.sshfs",
noauto = true
},
{mountpoint = "/home/raoni/mnt/msc_students.sshfs",
label = "~/mnt/msc_students.sshfs",
noauto = true
}
}
}
local DEFAULTS = {
cpu_count = get_cpu_count(),
top_entries = 10,
network_interfaces = {"br0"},
filesystems_mountpoints = select_mountpoints()
}
--------------------------------------------------------------------------------
-- TEST AREA
--------------------------------------------------------------------------------
ENV.DEBUG ("-- TEST AREA")
ENV.DEFAULTS = DEFAULTS
ENV.fake_conky_env()
G_ENV = ENV
--------------------------------------------------------------------------------
-- FORMAT FUNCTIONS
--------------------------------------------------------------------------------
ENV.DEBUG ("-- FORMAT FUNCTIONS")
function text_section_header()
local text = ENV.TEXT_STATIC_header
return text
end
function text_section_weather()
local text = ENV.TEXT_STATIC_weather
return text
end
function text_section_sensors()
local text = ENV.TEXT_STATIC_sensors
return text
end
function text_section_system()
local text = ENV.TEXT_STATIC_system
return text
end
function text_section_weather2()
local text = ENV.TEXT_STATIC_weather2
return text
end
function text_section_cpu(cpu_count)
cpu_count = cpu_count or DEFAULTS.cpu_count
local COMMENTED_header = [[
#${color1}CPU ${color0}${hr}
#${color0}Frequency: ${color1}${freq 1}${color0}MHz / ${color1}${freq_g 1}${color0}GHz
#${color0}CPU Usage:${color1} ${cpu cpu0}% ${cpubar 4}
#
#${color0}Frequency: ${color1}${freq 1}${color0}MHz / ${color1}${freq_g 1}${color0}GHz${alignr}\
#${color1}${freq 2}${color0}MHz / ${color1}${freq_g 2}${color0}GHz
#${color0}CPU Usage: ${color1}${cpu cpu1}% ${cpubar 4,100}${alignr}\
#${color1} ${cpu cpu2}% ${cpubar 4,100}
#
]]
local header = [[
${color1}CPU ${color0}${hr}
${font Ubuntu Mono:size=10}\
]]
local footnote = [[
#${alignr}${cpugraph 20,220 666666 666666}
${font}\
]]
-- format expect 5 integers of the same value.
local core_format = [[
${color0}core %d: ${color1}${freq %d}${color0}MHz (${color1}${freq_g %d}${color0}GHz)\
${alignr}${color1}${cpu cpu%d}%% ${cpubar cpu%d 4,100}
]]
local core_lines = ""
for c = 1, cpu_count do
core_lines = core_lines ..
string.format(core_format, c, c, c, c, c)
end
local text = COMMENTED_header .. header .. core_lines .. footnote
return text
end
function text_section_memory()
local text = ENV.TEXT_STATIC_memory
return text
end
function text_section_filesystems(mountpoints, truncate)
mountpoints = mountpoints or DEFAULTS.filesystems_mountpoints
local truncate = truncate or 10
local truncate_prefix = ">"
local header = [[
${color1}FILE SYSTEMS ${color0}${hr}
${font Ubuntu Mono:size=10}\
]]
local footnote = [[
${font}\
]]
local sda_graph = [[
/dev/sda
${voffset 8}\
${color0}read : ${color1}${diskio_read /dev/sda}\
${alignr}${voffset -8}${diskiograph_read /dev/sda 20,220 666666 666666}
${color0}write: ${color1}${diskio_write /dev/sda}\
${alignr}${voffset -8}${diskiograph_write /dev/sda 20,220 666666 666666}
]]
local mount_line_sep = [[
]]
-- format expect 7 strings representing:
-- 1: mount label (if size of label > 10 it may not fit the
-- horizontal space, see (5))
-- 5: a separator betwen left and right part. The ideia is to put
-- a \n to break the parts in two lines if the label is too big.
-- 2,3,4,6,7: mountpoint. Should be the same value.
local mount_format = [[
${color0}%-10s: \
${if_mounted %s}\
${color1}${fs_used %s}/${fs_size %s}%s${alignr}\
${color1}${fs_used_perc %s}%% ${fs_bar 4,100 %s}\
${else}\
${alignr}<unmounted>\
${endif}\
]]
-- format expect 8 strings representing:
-- 2,8: mount label (if size of label > 10 it may not fit the
-- horizontal space, see (5))
-- 5: a separator betwen left and right part. The ideia is to put
-- a \n to break the parts in two lines if the label is too big.
-- 1,3,4,6,7: mountpoint. Should be the same value.
local mount_noauto_format = [[
${if_mounted %s}\
${color2}%-10s: \
${color1}${fs_used %s}/${fs_size %s}%s${alignr}\
${color1}${fs_used_perc %s}%% ${fs_bar 4,100 %s}\
${else}\
${color0}%-10s: \
${alignr}<unmounted>\
${endif}\
]]
local mount_lines = {}
for index, entry in pairs(mountpoints) do
local l = entry.label
local m = entry.mountpoint
local s = ""
-- truncate large labels and add a indicater prefix
if truncate and #l > truncate then
local p = truncate_prefix
local length = truncate - #p
l = p .. string.sub(l, -1 * length)
end
-- break long lines in two, based on the size of the label.
if #l > 10 then s = "\n" end
local line = nil
if entry.noauto then
line = string.format(mount_noauto_format,
m, l, m, m, s, m, m, l)
else
line = string.format(mount_format,
l, m, m, m, s, m, m)
end
table.insert(mount_lines, line)
end
mount_lines = table.concat(mount_lines, mount_line_sep)
local text = header .. sda_graph .. mount_lines .. footnote
return text
end
function text_section_network(interfaces)
interfaces = interfaces or DEFAULTS.network_interfaces
local header = [[
${color1}NETWORK ${color0}${hr}
]]
local footnote = [[]]
-- format expect 7 strings of the same value.
local interface_format = [[
${if_up %s}\
${color0}${font Ubuntu Mono:size=10}\
%s (${addrs %s})
${voffset 8}\
${color0}Up : ${color1}${upspeed %s}\
${alignr}${voffset -8}${upspeedgraph %s 20,220 000000 ff0000}
${color0}Down: ${color1}${downspeed %s}\
${alignr}${voffset -8}${downspeedgraph %s 20,220 000000 00ff00}
${endif}\
${font}\
\
]]
local interface_lines = ""
for i, name in ipairs(interfaces) do
local n = name
local line = string.format(interface_format, n, n, n, n, n, n, n)
interface_lines = interface_lines .. line
end
local text = header .. interface_lines .. footnote
return text
end
function text_section_top()
entries = entries or DEFAULTS.top_entries
local header = [[
${color1}TOP ${color0}${hr}
${color0}Name PID CPU% ${offset 4}Name PID MEM%
${color1}${font Ubuntu Mono:size=10}\
]]
local footnote = [[
${font}\
]]
-- format expect 6 integers of the same value.
local top_format = [[
${top name %2d}${goto 98}${top pid %2d}${top cpu %2d}${goto 186}${top_mem name %2d}${goto 278}${top_mem pid %2d}${top_mem mem %2d}
]]
local top_lines = ""
for i = 1, entries do
top_lines = top_lines ..
string.format(top_format, i, i, i, i, i, i)
end
local text = header .. top_lines .. footnote
return text
end
function text_section_mixer()
local text = ENV.TEXT_STATIC_mixer
return text
end
function text_section_logging()
local text = ENV.TEXT_STATIC_logging
return text
end
function text_section_fortune()
local text = ENV.TEXT_STATIC_fortune
return text
end
function text_section_footnote()
local text = ENV.TEXT_STATIC_footnote
return text
end
--------------------------------------------------------------------------------
-- CONKY CONFIGURATION
--------------------------------------------------------------------------------
ENV.DEBUG ("-- CONKY CONFIGURATION")
ENV.TEXT_ORIGINAL = [[
${color1}${time %a, %d %b %Y}${alignr}${time %T %Z}
${font Ubuntu Mono:size=10}\
${color0}${alignc}$nodename - $sysname $kernel on $machine
${font}\
${color1}WEATHER ${color0}${hr}
${font Ubuntu Mono:size=10}\
${color0}Campinas: ${color1}${weather http://tgftp.nws.noaa.gov/pub/data/observations/metar/stations/ SBKP temperature}Celsius${font}
${color1}SENSORS ${color0}
${color0}${font Ubuntu Mono:size=10}\
${exec fmt-sensors.py -1}\
${font}\
${voffset -177}\
${goto 176}${color1}SYSTEM ${color0}${hr}
${font Ubuntu Mono:size=10}\
${goto 176}${color0}Uptime: ${color1}$uptime
${goto 176}${color0}Processes: ${color1}$processes${color0}+${color1}$running_processes
${if_existing /sys/class/power_supply/C23B/type Battery}\
${goto 176}${color0}Battery: ${color1}${battery C23B} ${color0}(${battery_time C23B})
${goto 176}${color1}${exec acpi -b}\
${endif}\
${font}\
${goto 176}${color1}WEATHER 02 ${color0}${hr}
${font Ubuntu Mono:size=10}\
${goto 176}${color0}Campinas: ${color1}${weather http://tgftp.nws.noaa.gov/pub/data/observations/metar/stations/ SBKP temperature}Celsius
${font}\
#${color1}CPU ${color0}${hr}
#${color0}Frequency: ${color1}${freq 1}${color0}MHz / ${color1}${freq_g 1}${color0}GHz
#${color0}CPU Usage:${color1} ${cpu cpu0}% ${cpubar 4}
#
#${color0}Frequency: ${color1}${freq 1}${color0}MHz / ${color1}${freq_g 1}${color0}GHz${alignr}\
#${color1}${freq 2}${color0}MHz / ${color1}${freq_g 2}${color0}GHz
#${color0}CPU Usage: ${color1}${cpu cpu1}% ${cpubar 4,100}${alignr}\
#${color1} ${cpu cpu2}% ${cpubar 4,100}
#
${color1}CPU ${color0}${hr}
${font Ubuntu Mono:size=10}\
${color0}core 1: ${color1}${freq 1}${color0}MHz (${color1}${freq_g 1}${color0}GHz)\
${alignr}${color1}${cpu cpu1}% ${cpubar cpu1 4,100}
${color0}core 2: ${color1}${freq 2}${color0}MHz (${color1}${freq_g 2}${color0}GHz)\
${alignr}${color1}${cpu cpu2}% ${cpubar cpu2 4,100}
${color0}core 3: ${color1}${freq 3}${color0}MHz (${color1}${freq_g 3}${color0}GHz)\
${alignr}${color1}${cpu cpu3}% ${cpubar cpu3 4,100}
${color0}core 4: ${color1}${freq 4}${color0}MHz (${color1}${freq_g 4}${color0}GHz)\
${alignr}${color1}${cpu cpu4}% ${cpubar cpu4 4,100}
${color0}core 5: ${color1}${freq 5}${color0}MHz (${color1}${freq_g 5}${color0}GHz)\
${alignr}${color1}${cpu cpu5}% ${cpubar cpu5 4,100}
${color0}core 6: ${color1}${freq 6}${color0}MHz (${color1}${freq_g 6}${color0}GHz)\
${alignr}${color1}${cpu cpu6}% ${cpubar cpu6 4,100}
${color0}core 7: ${color1}${freq 7}${color0}MHz (${color1}${freq_g 7}${color0}GHz)\
${alignr}${color1}${cpu cpu7}% ${cpubar cpu7 4,100}
${color0}core 8: ${color1}${freq 8}${color0}MHz (${color1}${freq_g 8}${color0}GHz)\
${alignr}${color1}${cpu cpu8}% ${cpubar cpu8 4,100}
#${alignr}${cpugraph 20,220 666666 666666}
${font}\
${color1}MEMORY ${color0}${hr}
${font Ubuntu Mono:size=10}\
${color0}RAM : ${color1}${mem}/${memmax}\
${alignr}${memperc}% ${membar 4,100}
${color0}Swap: ${color1}${swap}/${swapmax}\
${alignr}${swapperc}% ${swapbar 4,100}
${font}\
${color1}FILE SYSTEMS ${color0}${hr}
${font Ubuntu Mono:size=10}\
/dev/sda
${voffset 8}\
${color0}read : ${color1}${diskio_read /dev/sda}\
${alignr}${voffset -8}${diskiograph_read /dev/sda 20,220 666666 666666}
${color0}write: ${color1}${diskio_write /dev/sda}\
${alignr}${voffset -8}${diskiograph_write /dev/sda 20,220 666666 666666}
${color0}/ : \
${if_mounted /}\
${color1}${fs_used /}/${fs_size /}${alignr}\
${color1}${fs_used_perc /}% ${fs_bar 4,100 /}\
${else}\
${alignr}<unmounted>\
${endif}\
${color0}/boot : \
${if_mounted /boot}\
${color1}${fs_used /boot}/${fs_size /boot}${alignr}\
${color1}${fs_used_perc /boot}% ${fs_bar 4,100 /boot}\
${else}\
${alignr}<unmounted>\
${endif}\
${color0}/home : \
${if_mounted /home}\
${color1}${fs_used /home}/${fs_size /home}${alignr}\
${color1}${fs_used_perc /home}% ${fs_bar 4,100 /home}\
${else}\
${alignr}<unmounted>\
${endif}\
${if_mounted /mnt/data}\
${color2}/mnt/data : \
${color1}${fs_used /mnt/data}/${fs_size /mnt/data}${alignr}\
${color1}${fs_used_perc /mnt/data}% ${fs_bar 4,100 /mnt/data}\
${else}\
${color0}/mnt/data : \
${alignr}<unmounted>\
${endif}\
${if_mounted /mnt/BRUNO}\
${color2}/mnt/BRUNO: \
${color1}${fs_used /mnt/BRUNO}/${fs_size /mnt/BRUNO}${alignr}\
${color1}${fs_used_perc /mnt/BRUNO}% ${fs_bar 4,100 /mnt/BRUNO}\
${else}\
${color0}/mnt/BRUNO: \
${alignr}<unmounted>\
${endif}\
${font}\
${color1}NETWORK ${color0}${hr}
${if_up wlan0}\
${color0}${font Ubuntu Mono:size=10}\
wlan0 (${addrs wlan0})
${voffset 8}\
${color0}Up : ${color1}${upspeed wlan0}\
${alignr}${voffset -8}${upspeedgraph wlan0 20,220 000000 ff0000}
${color0}Down: ${color1}${downspeed wlan0}\
${alignr}${voffset -8}${downspeedgraph wlan0 20,220 000000 00ff00}
${endif}\
${font}\
\
${if_up eth0}\
${color0}${font Ubuntu Mono:size=10}\
eth0 (${addrs eth0})
${voffset 8}\
${color0}Up : ${color1}${upspeed eth0}\
${alignr}${voffset -8}${upspeedgraph eth0 20,220 000000 ff0000}
${color0}Down: ${color1}${downspeed eth0}\
${alignr}${voffset -8}${downspeedgraph eth0 20,220 000000 00ff00}
${endif}\
${font}\
\
${if_up ens1}\
${color0}${font Ubuntu Mono:size=10}\
ens1 (${addrs ens1})
${voffset 8}\
${color0}Up : ${color1}${upspeed ens1}\
${alignr}${voffset -8}${upspeedgraph ens1 20,220 000000 ff0000}
${color0}Down: ${color1}${downspeed ens1}\
${alignr}${voffset -8}${downspeedgraph ens1 20,220 000000 00ff00}
${endif}\
${font}\
\
${if_up enp3s0}\
${color0}${font Ubuntu Mono:size=10}\
enp3s0 (${addrs enp3s0})
${voffset 8}\
${color0}Up : ${color1}${upspeed enp3s0}\
${alignr}${voffset -8}${upspeedgraph enp3s0 20,220 000000 ff0000}
${color0}Down: ${color1}${downspeed enp3s0}\
${alignr}${voffset -8}${downspeedgraph enp3s0 20,220 000000 00ff00}
${endif}\
${font}\
\
${if_up wlp16s0}\
${color0}${font Ubuntu Mono:size=10}\
wlp16s0 (${addrs wlp16s0})
${voffset 8}\
${color0}Up : ${color1}${upspeed wlp16s0}\
${alignr}${voffset -8}${upspeedgraph wlp16s0 20,220 000000 ff0000}
${color0}Down: ${color1}${downspeed wlp16s0}\
${alignr}${voffset -8}${downspeedgraph wlp16s0 20,220 000000 00ff00}
${endif}\
${font}\
\
${if_up wlp2s0}\
${color0}${font Ubuntu Mono:size=10}\
wlp2s0 (${addrs wlp2s0})
${voffset 8}\
${color0}Up : ${color1}${upspeed wlp2s0}\
${alignr}${voffset -8}${upspeedgraph wlp2s0 20,220 000000 ff0000}
${color0}Down: ${color1}${downspeed wlp2s0}\
${alignr}${voffset -8}${downspeedgraph wlp2s0 20,220 000000 00ff00}
${endif}\
${font}\
\
${color1}TOP ${color0}${hr}
${color0}Name PID CPU% ${offset 4}Name PID MEM%
${color1}${font Ubuntu Mono:size=10}\
${top name 1}${goto 98}${top pid 1}${top cpu 1}${goto 186}${top_mem name 1}${goto 278}${top_mem pid 1}${top_mem mem 1}
${top name 2}${goto 98}${top pid 2}${top cpu 2}${goto 186}${top_mem name 2}${goto 278}${top_mem pid 2}${top_mem mem 2}
${top name 3}${goto 98}${top pid 3}${top cpu 3}${goto 186}${top_mem name 3}${goto 278}${top_mem pid 3}${top_mem mem 3}
${top name 4}${goto 98}${top pid 4}${top cpu 4}${goto 186}${top_mem name 4}${goto 278}${top_mem pid 4}${top_mem mem 4}
${top name 5}${goto 98}${top pid 5}${top cpu 5}${goto 186}${top_mem name 5}${goto 278}${top_mem pid 5}${top_mem mem 5}
${top name 6}${goto 98}${top pid 6}${top cpu 6}${goto 186}${top_mem name 6}${goto 278}${top_mem pid 6}${top_mem mem 6}
${top name 7}${goto 98}${top pid 7}${top cpu 7}${goto 186}${top_mem name 7}${goto 278}${top_mem pid 7}${top_mem mem 7}
${top name 8}${goto 98}${top pid 8}${top cpu 8}${goto 186}${top_mem name 8}${goto 278}${top_mem pid 8}${top_mem mem 8}
${top name 9}${goto 98}${top pid 9}${top cpu 9}${goto 186}${top_mem name 9}${goto 278}${top_mem pid 9}${top_mem mem 9}
${top name 10}${goto 98}${top pid 10}${top cpu 10}${goto 186}${top_mem name 10}${goto 278}${top_mem pid 10}${top_mem mem 10}
${font}\
#
#${if_mixer_mute}\
#${color1}MIXER ${color0}${hr}
#${color0}Volume: ${color1}${mixer}% ${mixerbar}
#${endif}\
#
#${color1}LOGGING ${color0}${hr}
#${color0}syslog:
#${color1}${font Ubuntu Mono:size=9}\
#${tail /var/log/syslog.log 3}\
#${font}
#
#${color0}messages:
#${color1}${font Ubuntu Mono:size=9}\
#${tail /var/log/messages.log 3}\
#${font}
#
#${color1}FORTUNE ${color0}${hr}
#${color0}${font Ubuntu Mono:size=10}\
#${execi 120 fortune -asc | grep -xv '%' | fold -s -w50}\
#${font}
${color0}${hr}
]]
ENV.TEXT_STATIC_header = [[
${color1}${time %a, %d %b %Y}${alignr}${time %T %Z}
${font Ubuntu Mono:size=10}\
${color0}${alignc}$nodename - $sysname $kernel on $machine
${font}\
]]
ENV.TEXT_STATIC_weather = [[
${color1}WEATHER ${color0}${hr}
${font Ubuntu Mono:size=10}\
${color0}Campinas: ${color1}${weather http://tgftp.nws.noaa.gov/data/observations/metar/stations/ SBKP temperature}Celsius${font}
]]
ENV.TEXT_STATIC_sensors = [[
${color1}SENSORS ${color0}
${color0}${font Ubuntu Mono:size=10}\
${exec fmt-sensors.py -1}\
${font}\
]]
ENV.TEXT_STATIC_system = [[
${voffset -177}\
${goto 176}${color1}SYSTEM ${color0}${hr}
${font Ubuntu Mono:size=10}\
${goto 176}${color0}Uptime: ${color1}$uptime
${goto 176}${color0}Processes: ${color1}$processes${color0}+${color1}$running_processes
#${if_existing /sys/class/power_supply/C23B/type Battery}\
#${goto 176}${color0}Battery: ${color1}${battery C23B} ${color0}(${battery_time C23B})
#${goto 176}${color1}${exec acpi -b}\
#${endif}\
${font}\
]]
ENV.TEXT_STATIC_weather2 = [[
${goto 176}${color1}WEATHER 02 ${color0}${hr}
${font Ubuntu Mono:size=10}\
${goto 176}${color0}Campinas: ${color1}${weather http://tgftp.nws.noaa.gov/data/observations/metar/stations/ SBKP temperature}Celsius
${font}\
]]
ENV.TEXT_STATIC_cpu = [[
#${color1}CPU ${color0}${hr}
#${color0}Frequency: ${color1}${freq 1}${color0}MHz / ${color1}${freq_g 1}${color0}GHz
#${color0}CPU Usage:${color1} ${cpu cpu0}% ${cpubar 4}
#
#${color0}Frequency: ${color1}${freq 1}${color0}MHz / ${color1}${freq_g 1}${color0}GHz${alignr}\
#${color1}${freq 2}${color0}MHz / ${color1}${freq_g 2}${color0}GHz
#${color0}CPU Usage: ${color1}${cpu cpu1}% ${cpubar 4,100}${alignr}\
#${color1} ${cpu cpu2}% ${cpubar 4,100}
#
${color1}CPU ${color0}${hr}
${font Ubuntu Mono:size=10}\
${color0}core 1: ${color1}${freq 1}${color0}MHz (${color1}${freq_g 1}${color0}GHz)\
${alignr}${color1}${cpu cpu1}% ${cpubar cpu1 4,100}
${color0}core 2: ${color1}${freq 2}${color0}MHz (${color1}${freq_g 2}${color0}GHz)\
${alignr}${color1}${cpu cpu2}% ${cpubar cpu2 4,100}
${color0}core 3: ${color1}${freq 3}${color0}MHz (${color1}${freq_g 3}${color0}GHz)\
${alignr}${color1}${cpu cpu3}% ${cpubar cpu3 4,100}
${color0}core 4: ${color1}${freq 4}${color0}MHz (${color1}${freq_g 4}${color0}GHz)\
${alignr}${color1}${cpu cpu4}% ${cpubar cpu4 4,100}
${color0}core 5: ${color1}${freq 5}${color0}MHz (${color1}${freq_g 5}${color0}GHz)\
${alignr}${color1}${cpu cpu5}% ${cpubar cpu5 4,100}
${color0}core 6: ${color1}${freq 6}${color0}MHz (${color1}${freq_g 6}${color0}GHz)\
${alignr}${color1}${cpu cpu6}% ${cpubar cpu6 4,100}
${color0}core 7: ${color1}${freq 7}${color0}MHz (${color1}${freq_g 7}${color0}GHz)\
${alignr}${color1}${cpu cpu7}% ${cpubar cpu7 4,100}
${color0}core 8: ${color1}${freq 8}${color0}MHz (${color1}${freq_g 8}${color0}GHz)\
${alignr}${color1}${cpu cpu8}% ${cpubar cpu8 4,100}
#${alignr}${cpugraph 20,220 666666 666666}
${font}\
]]
ENV.TEXT_STATIC_memory = [[
${color1}MEMORY ${color0}${hr}
${font Ubuntu Mono:size=10}\
${color0}RAM : ${color1}${mem}/${memmax}\
${alignr}${memperc}% ${membar 4,100}
${color0}Swap: ${color1}${swap}/${swapmax}\
${alignr}${swapperc}% ${swapbar 4,100}
${font}\
]]
ENV.TEXT_STATIC_filesystems = [[
${color1}FILE SYSTEMS ${color0}${hr}
${font Ubuntu Mono:size=10}\
/dev/sda
${voffset 8}\
${color0}read : ${color1}${diskio_read /dev/sda}\
${alignr}${voffset -8}${diskiograph_read /dev/sda 20,220 666666 666666}
${color0}write: ${color1}${diskio_write /dev/sda}\
${alignr}${voffset -8}${diskiograph_write /dev/sda 20,220 666666 666666}
${color0}/ : \
${if_mounted /}\
${color1}${fs_used /}/${fs_size /}${alignr}\
${color1}${fs_used_perc /}% ${fs_bar 4,100 /}\
${else}\
${alignr}<unmounted>\
${endif}\
${color0}/boot : \
${if_mounted /boot}\
${color1}${fs_used /boot}/${fs_size /boot}${alignr}\
${color1}${fs_used_perc /boot}% ${fs_bar 4,100 /boot}\
${else}\
${alignr}<unmounted>\
${endif}\
${color0}/home : \
${if_mounted /home}\
${color1}${fs_used /home}/${fs_size /home}${alignr}\
${color1}${fs_used_perc /home}% ${fs_bar 4,100 /home}\
${else}\
${alignr}<unmounted>\
${endif}\
${if_mounted /mnt/data}\
${color2}/mnt/data : \
${color1}${fs_used /mnt/data}/${fs_size /mnt/data}${alignr}\
${color1}${fs_used_perc /mnt/data}% ${fs_bar 4,100 /mnt/data}\
${else}\
${color0}/mnt/data : \
${alignr}<unmounted>\
${endif}\
${if_mounted /mnt/BRUNO}\
${color2}/mnt/BRUNO: \
${color1}${fs_used /mnt/BRUNO}/${fs_size /mnt/BRUNO}${alignr}\
${color1}${fs_used_perc /mnt/BRUNO}% ${fs_bar 4,100 /mnt/BRUNO}\
${else}\
${color0}/mnt/BRUNO: \
${alignr}<unmounted>\
${endif}\
${font}\
]]
ENV.TEXT_STATIC_network = [[
${color1}NETWORK ${color0}${hr}
${if_up wlan0}\
${color0}${font Ubuntu Mono:size=10}\
wlan0 (${addrs wlan0})
${voffset 8}\
${color0}Up : ${color1}${upspeed wlan0}\
${alignr}${voffset -8}${upspeedgraph wlan0 20,220 000000 ff0000}
${color0}Down: ${color1}${downspeed wlan0}\
${alignr}${voffset -8}${downspeedgraph wlan0 20,220 000000 00ff00}
${endif}\
${font}\
\
${if_up eth0}\
${color0}${font Ubuntu Mono:size=10}\
eth0 (${addrs eth0})
${voffset 8}\
${color0}Up : ${color1}${upspeed eth0}\
${alignr}${voffset -8}${upspeedgraph eth0 20,220 000000 ff0000}
${color0}Down: ${color1}${downspeed eth0}\
${alignr}${voffset -8}${downspeedgraph eth0 20,220 000000 00ff00}
${endif}\
${font}\
\
${if_up ens1}\
${color0}${font Ubuntu Mono:size=10}\
ens1 (${addrs ens1})
${voffset 8}\
${color0}Up : ${color1}${upspeed ens1}\
${alignr}${voffset -8}${upspeedgraph ens1 20,220 000000 ff0000}
${color0}Down: ${color1}${downspeed ens1}\
${alignr}${voffset -8}${downspeedgraph ens1 20,220 000000 00ff00}
${endif}\
${font}\
\
${if_up enp3s0}\
${color0}${font Ubuntu Mono:size=10}\
enp3s0 (${addrs enp3s0})
${voffset 8}\
${color0}Up : ${color1}${upspeed enp3s0}\
${alignr}${voffset -8}${upspeedgraph enp3s0 20,220 000000 ff0000}
${color0}Down: ${color1}${downspeed enp3s0}\
${alignr}${voffset -8}${downspeedgraph enp3s0 20,220 000000 00ff00}
${endif}\
${font}\
\
${if_up wlp16s0}\
${color0}${font Ubuntu Mono:size=10}\
wlp16s0 (${addrs wlp16s0})
${voffset 8}\
${color0}Up : ${color1}${upspeed wlp16s0}\
${alignr}${voffset -8}${upspeedgraph wlp16s0 20,220 000000 ff0000}
${color0}Down: ${color1}${downspeed wlp16s0}\
${alignr}${voffset -8}${downspeedgraph wlp16s0 20,220 000000 00ff00}
${endif}\
${font}\
\
${if_up wlp2s0}\
${color0}${font Ubuntu Mono:size=10}\
wlp2s0 (${addrs wlp2s0})
${voffset 8}\
${color0}Up : ${color1}${upspeed wlp2s0}\
${alignr}${voffset -8}${upspeedgraph wlp2s0 20,220 000000 ff0000}
${color0}Down: ${color1}${downspeed wlp2s0}\
${alignr}${voffset -8}${downspeedgraph wlp2s0 20,220 000000 00ff00}
${endif}\
${font}\
\
]]
ENV.TEXT_STATIC_top = [[
${color1}TOP ${color0}${hr}
${color0}Name PID CPU% ${offset 4}Name PID MEM%
${color1}${font Ubuntu Mono:size=10}\
${top name 1}${goto 98}${top pid 1}${top cpu 1}${goto 186}${top_mem name 1}${goto 278}${top_mem pid 1}${top_mem mem 1}
${top name 2}${goto 98}${top pid 2}${top cpu 2}${goto 186}${top_mem name 2}${goto 278}${top_mem pid 2}${top_mem mem 2}
${top name 3}${goto 98}${top pid 3}${top cpu 3}${goto 186}${top_mem name 3}${goto 278}${top_mem pid 3}${top_mem mem 3}
${top name 4}${goto 98}${top pid 4}${top cpu 4}${goto 186}${top_mem name 4}${goto 278}${top_mem pid 4}${top_mem mem 4}
${top name 5}${goto 98}${top pid 5}${top cpu 5}${goto 186}${top_mem name 5}${goto 278}${top_mem pid 5}${top_mem mem 5}
${top name 6}${goto 98}${top pid 6}${top cpu 6}${goto 186}${top_mem name 6}${goto 278}${top_mem pid 6}${top_mem mem 6}
${top name 7}${goto 98}${top pid 7}${top cpu 7}${goto 186}${top_mem name 7}${goto 278}${top_mem pid 7}${top_mem mem 7}
${top name 8}${goto 98}${top pid 8}${top cpu 8}${goto 186}${top_mem name 8}${goto 278}${top_mem pid 8}${top_mem mem 8}
${top name 9}${goto 98}${top pid 9}${top cpu 9}${goto 186}${top_mem name 9}${goto 278}${top_mem pid 9}${top_mem mem 9}
${top name 10}${goto 98}${top pid 10}${top cpu 10}${goto 186}${top_mem name 10}${goto 278}${top_mem pid 10}${top_mem mem 10}
${font}\
]]
ENV.TEXT_STATIC_mixer = [[
#
#${if_mixer_mute}\
#${color1}MIXER ${color0}${hr}
#${color0}Volume: ${color1}${mixer}% ${mixerbar}
#${endif}\
#
]]
ENV.TEXT_STATIC_logging = [[
#${color1}LOGGING ${color0}${hr}
#${color0}syslog:
#${color1}${font Ubuntu Mono:size=9}\
#${tail /var/log/syslog.log 3}\
#${font}
#
#${color0}messages:
#${color1}${font Ubuntu Mono:size=9}\
#${tail /var/log/messages.log 3}\
#${font}
#
]]
ENV.TEXT_STATIC_fortune = [[
#${color1}FORTUNE ${color0}${hr}
#${color0}${font Ubuntu Mono:size=10}\
#${execi 120 fortune -asc | grep -xv '%' | fold -s -w50}\
#${font}
]]
ENV.TEXT_STATIC_footnote = [[
${color0}${hr}
]]
ENV.TEXT_STATIC = ENV.TEXT_STATIC_header ..
ENV.TEXT_STATIC_weather ..
ENV.TEXT_STATIC_sensors ..
ENV.TEXT_STATIC_system ..
ENV.TEXT_STATIC_weather2 ..
ENV.TEXT_STATIC_cpu ..
ENV.TEXT_STATIC_memory ..
ENV.TEXT_STATIC_filesystems ..
ENV.TEXT_STATIC_network ..
ENV.TEXT_STATIC_top ..
ENV.TEXT_STATIC_mixer ..
ENV.TEXT_STATIC_logging ..
ENV.TEXT_STATIC_fortune ..
ENV.TEXT_STATIC_footnote
ENV.TEXT_COMPATIBILITY = text_section_header() ..
text_section_weather() ..
text_section_sensors() ..
text_section_system() ..
text_section_weather2() ..
text_section_cpu(ENV.COMPATIBILITY_DEFAULTS.cpu_count) ..
text_section_memory() ..
text_section_filesystems(ENV.COMPATIBILITY_DEFAULTS.filesystems_mountpoints) ..
text_section_network(ENV.COMPATIBILITY_DEFAULTS.network_interfaces) ..
text_section_top(ENV.COMPATIBILITY_DEFAULTS.top_entries) ..
text_section_mixer() ..
text_section_logging() ..
text_section_fortune() ..
text_section_footnote()
ENV.TEXT_NEW = text_section_header() ..
text_section_weather() ..
text_section_sensors() ..
text_section_system() ..
text_section_weather2() ..
text_section_cpu() ..
text_section_memory() ..
text_section_filesystems() ..
text_section_network() ..
text_section_top() ..
text_section_mixer() ..
text_section_logging() ..
text_section_fortune() ..
text_section_footnote()
if ENV.compatibility then
ENV.TEXT = ENV.TEXT_COMPATIBILITY
else
ENV.TEXT = ENV.TEXT_NEW
end
ENV.DEBUG("SECTIONS static x dinamic:")
local sections = {"header", "weather", "sensors", "system", "weather2",
"cpu", "memory", "filesystems", "network", "top",
"mixer", "logging", "fortune", "footnote"}
for i, name in ipairs(sections) do
local dinamic = _ENV["text_section_" .. name]()
local static = ENV["TEXT_STATIC_" .. name]
local result = "=="
if dinamic ~= static then
result = "~~"
end
ENV.DEBUG(string.format(" %s: %s", name, result))
-- dump the conflicting section.
if dinamic ~= static then
ENV.DEBUG("===== static:\n" .. static .. "===================")
ENV.DEBUG("===== dinamic:\n" .. dinamic .. "===================")
end
end
if ENV.TEXT_ORIGINAL == ENV.TEXT_STATIC then
ENV.DEBUG("TEXT original x static: ==")
else
ENV.DEBUG("TEXT original x static: ~~")
end
if ENV.TEXT_ORIGINAL == ENV.TEXT then
ENV.DEBUG("TEXT original x dinamic: ==")
else
ENV.DEBUG("TEXT original x dinamic: ~~")
end
if ENV.TEXT_STATIC == ENV.TEXT then
ENV.DEBUG("TEXT static x dinamic: ==")
else
ENV.DEBUG("TEXT static x dinamic: ~~")
end
conky.text = ENV.TEXT
conky.config = {
double_buffer = true,
own_window = true,
own_window_class = 'Conky',
-- own_window_type:
-- normal, desktop, dock, panel, override
own_window_type = 'override',
own_window_argb_visual = true,
own_window_transparent = true,
--own_window_colour = '505050',
own_window_hints = 'undecorated,below,sticky,skip_taskbar,skip_pager',
--own_window_title = 'raoni_conky',
use_spacer = 'right',
--use_spacer = 'none',
use_xft = true,
font = 'Ubuntu Mono:size=12',
--alignment = 'top_left',
xinerama_head = 2,
alignment = 'top_right',
gap_x = 10,
gap_y = 5,
minimum_width = 350,
minimum_height = 5,
maximum_width = 350,
background = false,
border_width = 1,
default_color = 'white',
default_outline_color = 'white',
default_shade_color = 'white',
draw_borders = false,
draw_graph_borders = true,
draw_outline = false,
draw_shades = false,
--draw_graph_borders = no,
stippled_borders = 0,
uppercase = false,
extra_newline = false,
no_buffers = true,
out_to_console = false,
out_to_stderr = false,
update_interval = 1.0,
show_graph_scale = false,
show_graph_range = false,
cpu_avg_samples = 2,
net_avg_samples = 2,
temperature_unit = 'celsius',
if_up_strictness = 'link',
--if_up_strictness = 'address',
top_name_width = 11,
color0 = 'grey',
color1 = 'white',
color2 = 'red',
color3 = 'blue',
color4 = 'green',
};
ENV.DEBUG("-- END config")
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
|
local S, L, O, U, D, E = unpack(select(2, ...));
local Module = S:NewNameplateModule('FactionIcon');
local ShouldShowName = S:GetNameplateModule('Handler').ShouldShowName;
-- Local Config
local ENABLED;
local factionIcons = {
['Alliance'] = 'Interface\\FriendsFrame\\PlusManz-Alliance',
['Horde'] = 'Interface\\FriendsFrame\\PlusManz-Horde',
};
local function Create(unitframe)
if unitframe.FactionIcon then
return;
end
local frame = CreateFrame('Frame', '$parentFactionIcon', unitframe);
frame:SetAllPoints(unitframe.healthBar);
frame.icon = frame:CreateTexture(nil, 'OVERLAY');
PixelUtil.SetPoint(frame.icon, 'RIGHT', unitframe.name, 'LEFT', -2, 0);
PixelUtil.SetSize(frame.icon, 12, 12);
frame:SetShown(false);
unitframe.FactionIcon = frame;
end
local function Update(unitframe)
if ENABLED and unitframe.data.commonUnitType == 'PLAYER' and ShouldShowName(unitframe) and factionIcons[unitframe.data.factionGroup] then
unitframe.FactionIcon.icon:SetTexture(factionIcons[unitframe.data.factionGroup]);
unitframe.FactionIcon:SetShown(true);
else
unitframe.FactionIcon:SetShown(false);
end
end
function Module:UnitAdded(unitframe)
Create(unitframe);
Update(unitframe);
end
function Module:UnitRemoved(unitframe)
if unitframe.FactionIcon then
unitframe.FactionIcon:SetShown(false);
end
end
function Module:Update(unitframe)
Update(unitframe);
end
function Module:UpdateLocalConfig()
ENABLED = O.db.faction_icon_enabled;
end
function Module:StartUp()
self:UpdateLocalConfig();
end |
--IupCanvas Example in IupLua
require( "iuplua" )
cv = iup.canvas {size="300x100", xmin=0, xmax=99, posx=0, dx=10}
dg = iup.dialog{iup.frame{cv}; title="IupCanvas"}
function cv:motion_cb(x, y, r)
print(x, y, r)
end
function cv:k_any(c)
print("c = ", c)
print(" XkeyBase(c) = ", iup.XkeyBase(c))
print(" isCtrlXkey(c)= ", iup.isCtrlXkey(c))
print(" isAltXkey(c) = ", iup.isAltXkey(c))
end
dg:showxy(iup.CENTER, iup.CENTER)
if (iup.MainLoopLevel()==0) then
iup.MainLoop()
end
|
return {
bot_api_key = '616471199:AAGcf24Ahby6-ld1whRTkkDJYIyu7key_yg',
admin = 607826953,
channel = '@Dragon_Wolf_Ch', --channel username with the '@'
plugins = {
'start.lua','aboutus.lua','contactus.lua',
},
api_errors = {
[101] = 'Not enough rights to kick participant', --SUPERGROUP: bot is not admin
[102] = 'USER_ADMIN_INVALID', --SUPERGROUP: trying to kick an admin
[103] = 'method is available for supergroup chats only', --NORMAL: trying to unban
[104] = 'Bad Request: Only creator of the group can kick admins from the group', --NORMAL: trying to kick an admin
[105] = 'Bad Request: Need to be inviter of the user to kick it from the group', --NORMAL: bot is not an admin or everyone is an admin
[106] = 'USER_NOT_PARTICIPANT', --NORMAL: trying to kick an user that is not in the group
[107] = 'CHAT_ADMIN_REQUIRED', --NORMAL: bot is not an admin or everyone is an admin
[400] = ':|',
[110] = 'PEER_ID_INVALID', --user never started the bot
[111] = 'Bad Request: message is not modified', --the edit message method hasn't modified the message
[112] = 'Bad Request: Can\'t parse message text: Can\'t find end of the entity starting at byte offset %d+', --the markdown is wrong and breaks the delivery
[113] = 'Bad Request: group chat is migrated to a supergroup chat', --group updated to supergroup
[114] = 'Bad Request: Message can\'t be forwarded', --unknown
[115] = 'Message text is empty', --empty message
[116] = 'message not found', --message id invalid, I guess
[120] = 'Can\'t parse reply keyboard markup JSON object', --keyboard table invalid
[121] = 'Field \\\"inline_keyboard\\\" of the InlineKeyboardMarkup should be an Array of Arrays', --inline keyboard is not an array of array
[122] = 'Can\'t parse inline keyboard button: InlineKeyboardButton should be an Object',
[123] = 'Bad Request: Object expected as reply markup', --empty inline keyboard table
[130] = 'Type of file to send mismatch', --tryin to send a media with the wrong method
[403] = 'Bot was blocked by the user', --user blocked the bot
[429] = 'Too many requests: retry later', --the bot is hitting api limits
}
}
|
local ser = require 'ser'
LevelDisplay = class("LevelDisplay")
function LevelDisplay:initialize()
self.walls = {} -- max 16
self.spawners = {} -- max 4
self.exits = {} -- max 4
self.starts = {} -- max 1
self.keys = {} -- max 4
self.treasures = {} -- max 3
self.changesMade = false
self.currentLevel = 0
self.infoString = ""
self.filename = "ENTER FILE NAME"
self.speed = 100
self.dragObj = nil
self.xoffset = 70
self.yoffset = 40
self.scale = 2
self.showGrid = true
self.buttons = {}
self.toolMode = "select"
local gui = self
local function resetButtons()
for k,v in pairs(self.buttons) do
v.highlighted = false
end
end
table.insert(self.buttons, Button(0, 0, "Select", function(self)
gui.infoString = "Select Tool\n\nUse the mouse to manipulate objects\nClick and drag an object to move it."
gui.toolMode = "select"
resetButtons()
self.highlighted = true
end))
table.insert(self.buttons, Button(200, 0, "Wall", function(self)
gui.infoString = "Add Wall\n\nClick to add a wall."
gui.toolMode = "wall"
resetButtons()
self.highlighted = true
end))
table.insert(self.buttons, Button(300, 0, "Spawner", function(self)
gui.infoString = "Add Spawner\n\nClick to add an enemy spawner."
gui.toolMode = "spawner"
resetButtons()
self.highlighted = true
end))
table.insert(self.buttons, Button(400, 0, "Exit", function(self)
gui.infoString = "Add Exit\n\nClick to add a level exit."
gui.toolMode = "exit"
resetButtons()
self.highlighted = true
end))
table.insert(self.buttons, Button(500, 0, "Start", function(self)
gui.infoString = "Add Start\n\nClick to add the level starting point."
gui.toolMode = "start"
resetButtons()
self.highlighted = true
end))
table.insert(self.buttons, Button(600, 0, "Key", function(self)
gui.infoString = "Add Key\n\nClick to add a key."
gui.toolMode = "key"
resetButtons()
self.highlighted = true
end))
table.insert(self.buttons, Button(700, 0, "Treasure", function(self)
gui.infoString = "Add Treasure\n\nClick to add treasure."
gui.toolMode = "treasure"
resetButtons()
self.highlighted = true
end))
self.buttons[1].highlighted = true
self:switchToLevel(0)
end
function LevelDisplay:update(dt)
if self.dialog then
if self.dialog.active then
self.dialog:update(dt)
return
else
if self.dialog.action == "save" then
self:save(self.dialog.filename)
elseif self.dialog.action == "load" then
self:load(self.dialog.filename)
elseif self.dialog.action == "export" then
self:export(self.dialog.filename)
end
self.dialog = nil
end
end
--[[
if love.keyboard.isDown("down") then
self.yoffset = self.yoffset - self.speed*dt
elseif love.keyboard.isDown("up") then
self.yoffset = self.yoffset + self.speed*dt
end
if love.keyboard.isDown("right") then
self.xoffset = self.xoffset - self.speed*dt
elseif love.keyboard.isDown("left") then
self.xoffset = self.xoffset + self.speed*dt
end
]]
if self.dragObj then
local mx, my = self:getMouseTile()
self.dragObj.x = mx
self.dragObj.y = my
end
end
local treasureLayouts = {
[0] = {{1}},
[1] = {{1},{1}},
[2] = {{1, 1}},
[3] = {{1, 0},{0, 1}},
[4] = {{0, 1},{1, 0}},
[5] = {{1, 0, 0},{0, 0, 1}},
[6] = {{1, 0},{0,0},{0,1}},
[7] = {{0,1},{0,0},{1,0}},
[8] = {{0,0,0},{1,0,0}},
[9] = {{1,1,0},{0,0,1}},
[10] = {{1,0,0},{0,1,0},{0,0,1}},
[11] = {{1,0},{1,0},{0,1}},
[12] = {{1},{},{1,0,1}},
[13] = {{0,1},{},{1,0,1}},
[14] = {{1,0,1},{},{0,1}},
[15] = {{0,1},{1},{0,1}}
}
function LevelDisplay:draw()
local ofx, ofy = self.xoffset, self.yoffset
for k,v in pairs(self.buttons) do
v:draw()
end
love.graphics.setColor(colors.white)
--local changeMadeSymbol = self.changesMade and " (Modified)" or ""
love.graphics.printf("Level " .. self.currentLevel, 0, 60, scrw, "center")
love.graphics.push()
love.graphics.scale(self.scale, self.scale)
love.graphics.rectangle("line", ofx, ofy, 8*32, 8*16)
if self.showGrid then
love.graphics.setLineWidth(.5)
love.graphics.line(ofx + 8*16, ofy, ofx + 8*16, ofy + 8*16)
love.graphics.line(ofx, ofy + 8*8, ofx + 8*32, ofy + 8*8)
love.graphics.setLineWidth(1)
end
local mtx, mty = self:getMouseTile()
love.graphics.rectangle("line", mtx*8+ofx, mty*8+ofy, 8, 8)
love.graphics.setColor(colors.white)
for k,v in pairs(self.walls) do
for x=0, v.w-1, 1 do
for y=0, v.h-1, 1 do
if v.style then
love.graphics.draw(images.wallB, 8*v.x+8*x+ofx, 8*v.y+8*y+ofy)
else
love.graphics.draw(images.wall, 8*v.x+8*x+ofx, 8*v.y+8*y+ofy)
end
end
end
end
for k,v in pairs(self.spawners) do
love.graphics.draw(images.spawner, 8*v.x+ofx, 8*v.y+ofy)
end
for k,v in pairs(self.exits) do
love.graphics.draw(images.exit, 8*v.x+ofx, 8*v.y+ofy)
end
for k,v in pairs(self.starts) do
love.graphics.draw(images.start, 8*v.x+ofx, 8*v.y+ofy)
end
for k,v in pairs(self.keys) do
love.graphics.draw(images.key, 8*v.x+ofx, 8*v.y+ofy)
end
for k,v in pairs(self.treasures) do
local image = images.none
if v.type == 1 then image = images.gold
elseif v.type == 2 then image = images.poo
elseif v.type == 3 then image = images.cup
elseif v.type == 4 then image = images.lemon
end
for y, row in ipairs(treasureLayouts[v.arrangement]) do
for x, col in ipairs(row) do
if col == 1 then
love.graphics.draw(image, 8*(v.x+x-1)+ofx, 8*(v.y+y-1)+ofy)
end
end
end
--[[
if v.arrangement == 0 then
love.graphics.draw(image, 8*v.x+ofx, 8*v.y+ofy)
elseif v.arrangement == 1 then
love.graphics.draw(image, 8*v.x+ofx, 8*v.y+ofy)
love.graphics.draw(image, 8*v.x+ofx, 8*(v.y+1)+ofy)
elseif v.arrangement == 2 then
love.graphics.draw(image, 8*v.x+ofx, 8*v.y+ofy)
love.graphics.draw(image, 8*(v.x+1)+ofx, 8*v.y+ofy)
elseif v.arrangement == 3 then
love.graphics.draw(image, 8*v.x+ofx, 8*v.y+ofy)
love.graphics.draw(image, 8*(v.x+1)+ofx, 8*(v.y+1)+ofy)
elseif v.arrangement == 4 then
love.graphics.draw(image, 8*v.x+ofx, 8*v.y+ofy)
love.graphics.draw(image, 8*v.x+ofx, 8*(v.y+1)+ofy)
love.graphics.draw(image, 8*v.x+ofx, 8*(v.y+2)+ofy)
elseif v.arrangement == 5 then
love.graphics.draw(image, 8*v.x+ofx, 8*v.y+ofy)
love.graphics.draw(image, 8*(v.x+1)+ofx, 8*v.y+ofy)
love.graphics.draw(image, 8*(v.x+2)+ofx, 8*v.y+ofy)
elseif v.arrangement == 6 then
love.graphics.draw(image, 8*v.x+ofx, 8*v.y+ofy)
love.graphics.draw(image, 8*(v.x+1)+ofx, 8*(v.y+1)+ofy)
love.graphics.draw(image, 8*(v.x+2)+ofx, 8*(v.y+2)+ofy)
elseif v.arrangement == 7 then
love.graphics.draw(image, 8*v.x+ofx, 8*v.y+ofy)
love.graphics.draw(image, 8*(v.x+1)+ofx, 8*v.y+ofy)
love.graphics.draw(image, 8*v.x+ofx, 8*(v.y+1)+ofy)
end
]]
end
love.graphics.pop()
if self.dialog then self.dialog:draw(); return end
love.graphics.rectangle("line", 100-4, 400-4, 600+8, 200-8)
love.graphics.printf(self.infoString, 100, 400, 600, "left")
end
function LevelDisplay:getMouseTile()
local x, y = love.mouse:getPosition()
local mx, my = math.floor((x-(self.xoffset*self.scale))/(8*self.scale)), math.floor((y-(self.yoffset*self.scale))/(8*self.scale))
mx = (mx < 0) and 0 or mx
mx = (mx > 31) and 31 or mx
my = (my < 0) and 0 or my
my = (my > 15) and 15 or my
return mx, my
end
function LevelDisplay:mousemoved(x, y, dx, dy)
if love.mouse.isDown(1) then return end
self:drawTileInfo()
end
function LevelDisplay:drawTileInfo()
if self.toolMode ~= "select" then return end
local x, y = self:getMouseTile()
local found, foundObj = self:getTileAt(x, y)
if found then
local str = "Object Info:"
str = str .. "\n" .. found
if found == "wall" then
str = str .. string.format(" (%d / 16 placed)", #self.walls)
str = str .. "\n\nPlayers and enemies can't pass through this!\nUse Mouse Wheel to change length, right-click to rotate, space to change style.\n"
elseif found == "exit" then
str = str .. string.format(" (%d / 4 placed)", #self.exits)
str = str .. "\n\nTouch this to clear the level. It can take the player to any level, or just the next level (level 0).\nUse Mouse Wheel to change destination level.\n"
elseif found == "key" then
str = str .. string.format(" (%d / 4 placed)", #self.keys)
str = str .. "\n\nTouching this will make the target wall disappear.\nUse Mouse Wheel to change target wall to delete when key is collected.\n"
elseif found == "spawner" then
str = str .. string.format(" (%d / 4 placed)", #self.spawners)
str = str .. "\n\nEnemies spawn from this at regular intervals.\n"
elseif found == "start" then
str = str .. string.format(" (%d / 1 placed)", #self.starts)
str = str .. "\n\nThis is the initial spawning location of the player.\n"
elseif found == "treasure" then
str = str .. string.format(" (%d / 3 placed)", #self.treasures)
str = str .. "\n\nTouching this gives a bonus.\nLemons recover 200 health, Chalice is worth 6pts, Gold is worth 10pts, Poo kills all the badguys.\nUse Mouse Wheel to change arrangement, right click to cycle type.\n"
end
str = str .. "\nID: " .. foundObj.id
str = str .. "\nX: " .. foundObj.x
str = str .. "\nY: " .. foundObj.y
if foundObj.dest then str = str .. "\nDestination: " .. foundObj.dest end
if foundObj.target then str = str .. "\nTarget: " .. foundObj.target end
if foundObj.type then str = str .. "\nType: " .. foundObj.type end
if foundObj.arrangement then str = str .. "\nArrangement: " .. foundObj.arrangement end
if foundObj.w then str = str .. "\nWidth: " .. foundObj.w end
if foundObj.h then str = str .. "\nHeight: " .. foundObj.h end
self.infoString = str
else
self.infoString = [[Editor Instructions:
Click an object type at the top to create a new object.
Move an object by dragging its anchor tile. In the case of a wall, that would be the top left tile.
The Level format requires the maximum number of each type of object is placed in the map.
Objects may overlap! Any object sharing a space with a wall will be hidden by the wall.
Hit backspace or delete to delete an object.
Keyboard Shortcuts:
LeftArrow to save and go to previous level
RightArrow to save and go to next level
Ctrl+Enter to export
F3 to toggle grid
]]
end
end
function LevelDisplay:getTileAt(x, y)
local found, foundObj
for k,v in pairs(self.walls) do if v.x == x and v.y == y then found = "wall"; foundObj = v; break end end
for k,v in pairs(self.spawners) do if v.x == x and v.y == y then found = "spawner"; foundObj = v; break end end
for k,v in pairs(self.starts) do if v.x == x and v.y == y then found = "start"; foundObj = v; break end end
for k,v in pairs(self.exits) do if v.x == x and v.y == y then found = "exit"; foundObj = v; break end end
for k,v in pairs(self.keys) do if v.x == x and v.y == y then found = "key"; foundObj = v; break end end
for k,v in pairs(self.treasures) do if v.x == x and v.y == y then found = "treasure"; foundObj = v; break end end
return found, foundObj
end
function LevelDisplay:mousepressed(x, y, button)
if self.dialog then self.dialog:mousepressed(x, y, button); return end
local buttonHit = false
for k,v in pairs(self.buttons) do
buttonHit = v:mousepressed(x, y, button)
if buttonHit then return end
end
local mx, my = self:getMouseTile()
self:clickTile(mx, my, button)
--self:clickTile((x-(self.xoffset*self.scale))/(8*self.scale), (y-(self.yoffset*self.scale))/(8*self.scale), button)
self:drawTileInfo()
end
function LevelDisplay:addTo(tab, limit, obj)
self.changesMade = true
for i=1, limit, 1 do
if tab[i] == nil then
tab[i] = obj
return i-1
end
end
return false
end
function LevelDisplay:clickTile(x, y, button)
self.changesMade = true
if self.toolMode == "wall" then
local newObj = {x=x, y=y, w=2, h=1, style=false}
newObj.id = self:addTo(self.walls, 16, newObj)
self.buttons[1]:func()
elseif self.toolMode == "spawner" then
local newObj = {x=x, y=y}
newObj.id = self:addTo(self.spawners, 4, newObj)
self.buttons[1]:func()
elseif self.toolMode == "exit" then
local newObj = {x=x, y=y, dest=0}
newObj.id = self:addTo(self.exits, 4, newObj)
self.buttons[1]:func()
elseif self.toolMode == "start" then
local newObj = {x=x, y=y}
newObj.id = self:addTo(self.starts, 1, newObj)
self.buttons[1]:func()
elseif self.toolMode == "key" then
local newObj = {x=x, y=y, target=0}
newObj.id = self:addTo(self.keys, 4, newObj)
self.buttons[1]:func()
elseif self.toolMode == "treasure" then
local newObj = {x=x, y=y, type=1, arrangement=0}
newObj.id = self:addTo(self.treasures, 3, newObj)
self.buttons[1]:func()
elseif self.toolMode == "select" then
tiletype, tileobj = self:getTileAt(x, y)
if button == 1 then
if not self.dragObj then
self.dragObj = tileobj
end
elseif tiletype == "wall" then
local dimension = (tileobj.w == 1) and "h" or "w"
if button == "wu" then
tileobj[dimension] = tileobj[dimension] + 1
tileobj[dimension] = (tileobj[dimension] > 32) and 32 or tileobj[dimension]
elseif button == "wd" then
tileobj[dimension] = tileobj[dimension] - 1
tileobj[dimension] = (tileobj[dimension] < 1) and 1 or tileobj[dimension]
elseif button == 2 then
local temp = tileobj.h
tileobj.h = tileobj.w
tileobj.w = temp
end
elseif tiletype == "exit" then
if button == "wu" then
tileobj.dest = tileobj.dest + 1
tileobj.dest = (tileobj.dest > 127) and 127 or tileobj.dest
elseif button == "wd" then
tileobj.dest = tileobj.dest - 1
tileobj.dest = (tileobj.dest < 0) and 0 or tileobj.dest
end
elseif tiletype == "key" then
if button == "wu" then
tileobj.target = tileobj.target + 1
tileobj.target = (tileobj.target > 15) and 15 or tileobj.target
elseif button == "wd" then
tileobj.target = tileobj.target - 1
tileobj.target = (tileobj.target < 0) and 0 or tileobj.target
end
elseif tiletype == "treasure" then
if button == "wu" then
tileobj.arrangement = tileobj.arrangement + 1
tileobj.arrangement = (tileobj.arrangement > 15) and 15 or tileobj.arrangement
elseif button == "wd" then
tileobj.arrangement = tileobj.arrangement - 1
tileobj.arrangement = (tileobj.arrangement < 0) and 0 or tileobj.arrangement
elseif button == 2 then
tileobj.type = tileobj.type + 1
tileobj.type = (tileobj.type > 4) and 0 or tileobj.type
end
end
end
end
function LevelDisplay:newLevel()
self.walls = {}
self.spawners = {}
self.exits = {}
self.starts = {}
self.keys = {}
self.treasures = {}
end
function LevelDisplay:mousereleased(x, y, button)
if self.dialog then self.dialog:mousereleased(x, y, button); return end
self.dragObj = nil
end
function LevelDisplay:keypressed(key, isRepeat)
if self.dialog then self.dialog:keypressed(key, isRepeat); return end
if key == "delete" or key == "backspace" then
tiletype, tileobj = self:getTileAt(self:getMouseTile())
if tiletype == "wall" then
self.walls[tileobj.id+1] = nil
elseif tiletype == "exit" then
self.exits[tileobj.id+1] = nil
elseif tiletype == "spawner" then
self.spawners[tileobj.id+1] = nil
elseif tiletype == "key" then
self.keys[tileobj.id+1] = nil
elseif tiletype == "start" then
self.starts[tileobj.id+1] = nil
elseif tiletype == "treasure" then
self.treasures[tileobj.id+1] = nil
end
end
if key == "s" and love.keyboard.isDown("lctrl") then
self:saveCurrentLevel()
--self:showSaveDialog()
elseif key == "o" and love.keyboard.isDown("lctrl") then
--self:showLoadDialog()
elseif key == "return" and love.keyboard.isDown("lctrl") then
--self:showExportDialog()
self:exportAll()
elseif key == "n" and love.keyboard.isDown("lctrl") then
self:newLevel()
elseif key == "space" then
tiletype, tileobj = self:getTileAt(self:getMouseTile())
if tiletype == "wall" then
self.changesMade = true
tileobj.style = not tileobj.style
end
elseif key == "f3" then
self.showGrid = not self.showGrid
elseif key == "f1" then
love.system.openURL("file://"..love.filesystem.getSaveDirectory())
end
if key == "right" then
self:nextLevel()
elseif key == "left" then
self:previousLevel()
end
end
function LevelDisplay:nextLevel()
if self.currentLevel < 50 then
self:switchToLevel(self.currentLevel + 1)
end
end
function LevelDisplay:previousLevel()
if self.currentLevel > 0 then
self:switchToLevel(self.currentLevel - 1)
end
end
function LevelDisplay:switchToLevel(level)
if self.changesMade then
self:saveCurrentLevel()
self.changesMade = false
end
self.currentLevel = level
if not self:load(tostring(level) .. ".lua") then
self:newLevel()
return false
end
return true
end
function LevelDisplay:showSaveDialog()
self.dialog = SaveDialog()
end
function LevelDisplay:showLoadDialog()
self.dialog = LoadDialog()
end
function LevelDisplay:showExportDialog()
self.dialog = ExportDialog()
end
function LevelDisplay:textinput(t)
if self.dialog then self.dialog:textinput(t) end
end
function LevelDisplay:load(filename)
if love.filesystem.exists(filename) then
local func = love.filesystem.load(filename)
local obj = func()
self.walls = obj.walls
self.exits = obj.exits
self.keys = obj.keys
self.spawners = obj.spawners
self.starts = obj.starts
self.treasures = obj.treasures
return true
end
return false
end
function LevelDisplay:exportAll()
local levelStrings = {
"/* Level Data Generated with GloveEdit 0.4 */\n",
"/* Paste into data.h */\n"
}
table.insert(levelStrings, "\nconst unsigned short levelData[] PROGMEM = {")
local levelCount = 0
for i=0, 30, 1 do
if self:switchToLevel(i) then
levelCount = levelCount + 1
table.insert(levelStrings, self:export())
else
break
end
end
table.insert(levelStrings, "};")
--[[
table.insert(levelStrings, "\nextern const unsigned short* const levelData[] PROGMEM = {")
for i=0,levelCount-1, 1 do
table.insert(levelStrings, "\n\tlevelData_" .. tostring(i) .. ",")
end
table.insert(levelStrings, "\n};\n\nextern const unsigned char numLevels = " .. levelCount .. ";\n")
]]
table.insert(levelStrings, "\n\nconst unsigned char numLevels = " .. levelCount .. ";\n")
local finalStr = table.concat(levelStrings)
love.filesystem.write("levels.h", finalStr)
end
function LevelDisplay:export()
--local filestr = string.sub(filename, 1, -3)
--local outStr = "extern const unsigned short level_" .. filestr .. "[] PROGMEM = {\n\t"
local outStr = "\n\t" --\n\t" .. tostring(self.currentLevel) .. "\n\n" --"extern const unsigned short levelData_" .. tostring(self.currentLevel) .. "[] PROGMEM = {\n\t"
--local outStr = "\t"
-- Each element is 2 bytes
-- First, the walls.
for k,v in ipairs(self.walls) do
local wallbyte = 0
local direction = v.w == 1 and 1 or 0
local width = (direction == 1) and v.h or v.w
wallbyte = wallbyte + bit.lshift(bit.band(v.x, 31), 11)
wallbyte = wallbyte + bit.lshift(bit.band(v.y, 15), 7)
wallbyte = wallbyte + bit.lshift(bit.band(width-1, 31), 2)
wallbyte = wallbyte + (v.style and 2 or 0)
wallbyte = wallbyte + direction
local nextLine = (k==8 or k==16) and "\n\t" or ""
outStr = outStr .. ("0x" .. bit.tohex(wallbyte, 4) .. ", " .. nextLine)
end
-- Next the Spawners
for k,v in ipairs(self.spawners) do
local wallbyte = 0
wallbyte = wallbyte + bit.lshift(bit.band(v.x, 31), 11)
wallbyte = wallbyte + bit.lshift(bit.band(v.y, 15), 7)
outStr = outStr .. ("0x" .. bit.tohex(wallbyte, 4) .. ", ")
end
-- Next the keys.
for k,v in ipairs(self.keys) do
local wallbyte = 0
wallbyte = wallbyte + bit.lshift(bit.band(v.x, 31), 11)
wallbyte = wallbyte + bit.lshift(bit.band(v.y, 15), 7)
wallbyte = wallbyte + bit.lshift(bit.band(v.target, 15), 3)
local nextLine = (k==4) and "\n\t" or ""
outStr = outStr .. ("0x" .. bit.tohex(wallbyte, 4) .. ", " .. nextLine)
end
-- Next the Starts
for k,v in ipairs(self.starts) do
local wallbyte = 0
wallbyte = wallbyte + bit.lshift(bit.band(v.x, 31), 11)
wallbyte = wallbyte + bit.lshift(bit.band(v.y, 15), 7)
outStr = outStr .. ("0x" .. bit.tohex(wallbyte, 4) .. ", ")
end
-- Finally the exits.
for k,v in ipairs(self.exits) do
local wallbyte = 0
wallbyte = wallbyte + bit.lshift(bit.band(v.x, 31), 11)
wallbyte = wallbyte + bit.lshift(bit.band(v.y, 15), 7)
wallbyte = wallbyte + bit.band(v.dest, 127)
outStr = outStr .. ("0x" .. bit.tohex(wallbyte, 4) .. ", ")
end
-- The Treasures!
for k,v in ipairs(self.treasures) do
local wallbyte = 0
wallbyte = wallbyte + bit.lshift(bit.band(v.x, 31), 11)
wallbyte = wallbyte + bit.lshift(bit.band(v.y, 15), 7)
wallbyte = wallbyte + bit.lshift(bit.band(v.type, 7), 4)
wallbyte = wallbyte + bit.band(v.arrangement, 15)
outStr = outStr .. ("0x" .. bit.tohex(wallbyte, 4) .. ", ")
end
outStr = outStr .. "\n"
--outStr = outStr .. "\n\n"
return outStr
--print(outStr)
--love.filesystem.write(filename, outStr)
end
function LevelDisplay:saveCurrentLevel()
self:save(tostring(self.currentLevel) .. ".lua")
self.changesMade = false
end
function LevelDisplay:save(filename)
local data = {
walls = self.walls,
spawners = self.spawners,
exits = self.exits,
starts = self.starts,
keys = self.keys,
treasures = self.treasures
}
love.filesystem.write(filename, ser(data))
end
LoadDialog = class("LoadDialog")
function LoadDialog:initialize()
self.w = 400
self.h = 300
self.x = love.window.getWidth()/2 - self.w/2
self.y = love.window.getHeight()/2 - self.h/2
self.filename = lvldisp.filename
self.active = true
end
function LoadDialog:update(dt)
end
function LoadDialog:draw()
love.graphics.setColor(colors.black)
love.graphics.rectangle("fill", self.x, self.y, self.w, self.h)
love.graphics.setColor(colors.white)
love.graphics.rectangle("line", self.x, self.y, self.w, self.h)
love.graphics.printf("Load File..", self.x, self.y + 20, self.w, "center")
love.graphics.printf("> " .. self.filename .. ".lua <", self.x, self.y + 100, self.w, "center")
love.graphics.printf("Hit ENTER to load\nHit ESCAPE to cancel", self.x, self.y + 200, self.w, "center")
end
function LoadDialog:keypressed(key, isRepeat)
if key == "escape" then self.active = false end
if key == "backspace" then
if love.keyboard.isDown("lctrl") then self.filename = ""
else self.filename = string.sub(self.filename, 1, -2) end
end
if key == "return" then
self.action = "load"
lvldisp.filename = self.filename
self.filename = self.filename .. ".lua"
self.active = false
end
end
function LoadDialog:textinput(t)
if self.filename == "ENTER FILE NAME" then self.filename = "" end
self.filename = self.filename .. t
end
function LoadDialog:mousepressed(x, y, button) end
function LoadDialog:mousereleased(x, y, button) end
function LoadDialog:keyreleased(key) end
SaveDialog = class("SaveDialog")
function SaveDialog:initialize()
self.w = 400
self.h = 300
self.x = love.window.getWidth()/2 - self.w/2
self.y = love.window.getHeight()/2 - self.h/2
self.filename = lvldisp.filename
self.areYouSure = false
self.active = true
end
function SaveDialog:update(dt)
end
function SaveDialog:draw()
love.graphics.setColor(colors.black)
love.graphics.rectangle("fill", self.x, self.y, self.w, self.h)
love.graphics.setColor(colors.white)
love.graphics.rectangle("line", self.x, self.y, self.w, self.h)
love.graphics.printf("Save As..", self.x, self.y + 20, self.w, "center")
love.graphics.printf("> " .. self.filename .. ".lua <", self.x, self.y + 100, self.w, "center")
love.graphics.printf("Hit ENTER to save\nHit ESCAPE to cancel", self.x, self.y + 200, self.w, "center")
if self.areYouSure then
love.graphics.printf("ARE YOU SURE YOU WANNA REPLACE IT!?", self.x, self.y + 150, self.w, "center")
end
end
function SaveDialog:keypressed(key, isRepeat)
if key == "escape" then
if self.areYouSure then
self.areYouSure = false
else
self.active = false
end
end
if key == "backspace" then
if love.keyboard.isDown("lctrl") then self.filename = ""
else self.filename = string.sub(self.filename, 1, -2) end
end
if key == "return" then
if self.areYouSure or not love.filesystem.exists(self.filename .. ".lua") then
self.action = "save"
lvldisp.filename = self.filename
self.filename = self.filename .. ".lua"
self.active = false
end
if love.filesystem.exists(self.filename .. ".lua") then
self.areYouSure = true
end
end
end
function SaveDialog:textinput(t)
if self.filename == "ENTER FILE NAME" then self.filename = "" end
self.filename = self.filename .. t
end
function SaveDialog:mousepressed(x, y, button) end
function SaveDialog:mousereleased(x, y, button) end
function SaveDialog:keyreleased(key) end
ExportDialog = class("ExportDialog")
function ExportDialog:initialize()
self.w = 400
self.h = 300
self.x = love.window.getWidth()/2 - self.w/2
self.y = love.window.getHeight()/2 - self.h/2
self.filename = lvldisp.filename
self.active = true
end
function ExportDialog:update(dt)
end
function ExportDialog:draw()
love.graphics.setColor(colors.black)
love.graphics.rectangle("fill", self.x, self.y, self.w, self.h)
love.graphics.setColor(colors.white)
love.graphics.rectangle("line", self.x, self.y, self.w, self.h)
love.graphics.printf("Export As..", self.x, self.y + 20, self.w, "center")
love.graphics.printf("> " .. self.filename .. ".h <", self.x, self.y + 100, self.w, "center")
love.graphics.printf("Hit ENTER to save\nHit ESCAPE to cancel", self.x, self.y + 200, self.w, "center")
end
function ExportDialog:keypressed(key, isRepeat)
if key == "escape" then self.active = false end
if key == "backspace" then
if love.keyboard.isDown("lctrl") then self.filename = ""
else self.filename = string.sub(self.filename, 1, -2) end
end
if key == "return" then
self.action = "export"
lvldisp.filename = self.filename
self.filename = self.filename .. ".h"
self.active = false
end
end
function ExportDialog:textinput(t)
if self.filename == "ENTER FILE NAME" then self.filename = "" end
self.filename = self.filename .. t
end
function ExportDialog:mousepressed(x, y, button) end
function ExportDialog:mousereleased(x, y, button) end
function ExportDialog:keyreleased(key) end |
--this is a desperate attempt to adjust the worms acid resistance to allow proper nest-battles during force transitions.
for key, turret in pairs(data.raw["turret"]) do
if string.match(turret.name, "worm") or string.match(turret.name, "Worm") then
resTable = turret.resistances
for _, resistance in pairs(resTable) do
if resistance.type == "acid" then
resistance.percent = 50
resistance.decrease = 5
end
end
end
end |
require("scripts.recipeOO")
recipePrototypes = {}
for x,typeVar in pairs(inserterTypes) do
for y,rangeVar in pairs(inserterRanges) do
table.insert(recipePrototypes, createRecipePrototype(typeVar, rangeVar))
end
end
data:extend(recipePrototypes) |
-- where the hallway ends
local max_width = 350
local quote_bmts = {}
local count = 1
local quotes = {
{
text="What happens when we get there, the place where the hallway ends?",
color={0.8, 0.666, 0.666, 0},
y=140,
},
{
text="For me anyway, it's a combination of understanding and being understood, forgiving and being forgiven.\n\nThe people I harmed are okay and better than ever, I forgive the man who hurts me in my dreams, and we all laugh about how silly it was to have held onto to so much pain for so long.",
color={0.666, 0.666, 0.8, 0},
y=70,
},
{
text="Will we find each other there?",
color={0.8, 0.666, 0.666, 0},
y=140,
},
{
text="If I found you there, I'd smile to finally see you as you are–your mind, your physical form, you, all at once, in color and motion, with sound and texture.",
color={0.666, 0.666, 0.8, 0},
y=70,
},
{
text="I look forward to it.",
color={0.8, 0.666, 0.666, 0},
y=140,
},
}
local af = Def.ActorFrame{
InitCommand=function(self) self:x(_screen.cx):diffusealpha(0) end,
OnCommand=function(self) self:smooth(1):diffusealpha(1) end,
InputEventCommand=function(self, event)
if event.type == "InputEventType_FirstPress" and (event.GameButton=="Start" or event.GameButton=="Back" or event.GameButton=="MenuRight") then
quote_bmts[count]:playcommand("FadeOut")
if quotes[count+1] then
count = count + 1
quote_bmts[count]:queuecommand("FadeIn")
else
self:sleep(1.5):queuecommand("Transition")
end
end
end,
TransitionCommand=function(self)
SCREENMAN:GetTopScreen():StartTransitioningScreen("SM_GoToNextScreen")
end
}
af[#af+1] = LoadActor("./I5.ogg")..{
OnCommand=function(self) self:play() end,
TransitionCommand=function(self) self:stop() end
}
for i=1, #quotes do
af[#af+1] = Def.BitmapText{
File=THEME:GetPathB("ScreenRabbitHole", "overlay/_shared/helvetica neue/_helvetica neue 20px.ini"),
Text=quotes[i].text,
InitCommand=function(self)
quote_bmts[i] = self
self:wrapwidthpixels(max_width)
:align(0,0)
:xy(-self:GetWidth()/2, 70)
:diffuse(quotes[i].color):y( quotes[i].y )
:visible(false)
:playcommand("Refresh")
end,
FadeInCommand=function(self) self:visible(true):sleep(0.5):smooth(0.65):diffusealpha(1) end,
FadeOutCommand=function(self) self:finishtweening():smooth(0.65):diffusealpha(0):queuecommand("Hide") end,
HideCommand=function(self) self:visible(false) end
}
if i==1 then
af[#af].OnCommand=function(self) self:visible(true):sleep(1.5):smooth(1):diffusealpha(1) end
end
end
return af |
local speedomulti = 2.236936
local speedtext = "MPH"
local mapon, checkvehclass = true, true
local speedfps = 125
local minimap = RequestScaleformMovie("minimap")
local speedBuffer, velBuffer = {}, {}
local Driving, Underwater, enableCruise, wasInCar, pedinVeh, beltOn = false, false, false, false, false, false
local lastjob, lastcash, lastbank, lastdirty, lastsociety, society, hunger, thirst, player, vehicle, vehicleIsOn
ESX = nil
Citizen.CreateThread(function()
while not ESX do
TriggerEvent('esx:getSharedObject', function(obj)
ESX = obj
end)
Wait(0)
end
while not ESX.GetPlayerData().job do
Wait(10)
end
ESX.PlayerData = ESX.GetPlayerData()
end)
RegisterNetEvent('esx:playerLoaded')
AddEventHandler('esx:playerLoaded', function(xPlayer)
ESX.PlayerData = xPlayer
ESX.PlayerLoaded = true
end)
RegisterNetEvent('esx:setJob')
AddEventHandler('esx:setJob', function(job)
ESX.PlayerData.job = job
end)
--[[Functions]]--
IsCar = function(veh)
local vc = GetVehicleClass(veh)
return (vc >= 0 and vc <= 7) or (vc >= 9 and vc <= 12) or (vc >= 17 and vc <= 20)
end
Fwv = function (entity)
local hr = GetEntityHeading(entity) + 90.0
if hr < 0.0 then hr = 360.0 + hr end
hr = hr * 0.0174533
return { x = math.cos(hr) * 2.0, y = math.sin(hr) * 2.0 }
end
isinvehicle = function()
Citizen.CreateThread(function()
while true do
Wait(125)
local veh = GetVehiclePedIsUsing(player, false)
local speed = math.floor(GetEntitySpeed(veh) * speedomulti)
local vehhash = GetEntityModel(veh)
local maxspeed = (GetVehicleModelMaxSpeed(vehhash) * speedomulti) + 50
if checkvehclass then
local vehicleClass = GetVehicleClass(GetVehiclePedIsIn(PlayerPedId()))
checkvehclass = false
if vehicleClass == 8 or vehicleClass == 13 or vehicleClass == 14 or vehicleClass == 15 or vehicleClass == 16 then
SendNUIMessage({hideseatbeltextra = true})
else
SendNUIMessage({hideseatbeltextra = false})
end
end
if Config.LegacyFuel then
local fuellevel = exports["LegacyFuel"]:GetFuel(veh)
SendNUIMessage({speed = speed, speedtext = speedtext, maxspeed = maxspeed, action = "update_fuel", fuel = fuellevel, showFuel = true})
else
local fuellevel = GetVehicleFuelLevel(veh)
SendNUIMessage({speed = speed, speedtext = speedtext, maxspeed = maxspeed, action = "update_fuel", fuel = fuellevel, showFuel = true})
end
if not Driving then
checkvehclass = true
break
end
end
end)
end
comma_value = function(amount)
local formatted = amount
while true do
if not formatted then
break
else
formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
end
if k == 0 then
break
end
end
return formatted
end
TriggerVehicleLoop = function()
if mapon then
Citizen.CreateThread(function()
ToggleRadar(true)
SetRadarBigmapEnabled(false, false)
end)
end
end
ToggleRadar = function(state)
DisplayRadar(state)
BeginScaleformMovieMethod(minimap, "SETUP_HEALTH_ARMOUR")
ScaleformMovieMethodAddParamInt(3)
EndScaleformMovieMethod()
end
Voicelevel = function(val)
SendNUIMessage({action = "voice_level", voicelevel = val})
end
exports('Voicelevel', Voicelevel)
--[[End of Functions]]--
--[[Threads]]--
Citizen.CreateThread(function()
while true do
Wait(1500)
player = PlayerPedId()
pedinVeh = IsPedInAnyVehicle(player, false)
vehicle = GetVehiclePedIsIn(player, false)
vehicleIsOn = GetIsVehicleEngineRunning(vehicle)
local hideseatbelt, showlimiter, showSpeedo = false, false, false
local mapoutline = false
if pedinVeh and vehicleIsOn then
hideseatbelt = true
showlimiter = true
showSpeedo = true
if mapon then
SetRadarZoom(1150)
ToggleRadar(true)
mapoutline = true
else
ToggleRadar(false)
end
if not Driving then
Driving = true
isinvehicle()
TriggerVehicleLoop()
end
SendNUIMessage({
hideseatbelt = hideseatbelt,
showlimiter = showlimiter,
showSpeedo = showSpeedo,
mapoutline = mapoutline
})
else
enableCruise = false
showlimiter = false
showSpeedo = false
ToggleRadar(false)
mapoutline = false
Driving = false
SendNUIMessage({
hideseatbelt = hideseatbelt,
showlimiter = showlimiter,
showSpeedo = showSpeedo,
mapoutline = mapoutline
})
end
if IsEntityInWater(PlayerPedId()) then -- doesn't work with player variable
Underwater = true
else
Underwater = false
end
if IsPauseMenuActive() then
showUi = false
else
showUi = true
end
if IsPedArmed(player, 4 | 2) then
showweap = true
else
showweap = false
end
SendNUIMessage({
showOxygen = Underwater,
showUi = showUi,
showweap = showweap
})
TriggerServerEvent('joehud:getServerInfo')
end
end)
Citizen.CreateThread(function()
while true do
local car = GetVehiclePedIsIn(player)
if car ~= 0 and (wasInCar or IsCar(car)) then
wasInCar = true
if beltOn then
DisableControlAction(0, 75)
end
speedBuffer[2] = speedBuffer[1]
speedBuffer[1] = GetEntitySpeed(car)
if speedBuffer[2] and not beltOn and GetEntitySpeedVector(car, true).y > 1.0 and speedBuffer[1] > 15 and (speedBuffer[2] - speedBuffer[1]) > (speedBuffer[1] * 0.255) then
local co = GetEntityCoords(player)
local fw = Fwv(player)
SetEntityCoords(player, co.x + fw.x, co.y + fw.y, co.z - 0.47, true, true, true)
SetEntityVelocity(PlayerPedId(), velBuffer[2].x, velBuffer[2].y, velBuffer[2].z)
Wait(500)
SetPedToRagdoll(player, 1000, 1000, 0, 0, 0, 0)
end
velBuffer[2] = velBuffer[1]
velBuffer[1] = GetEntityVelocity(car)
elseif wasInCar then
wasInCar = false
beltOn = false
speedBuffer[1], speedBuffer[2] = 0.0, 0.0
end
Wait(20)
end
end)
Citizen.CreateThread( function()
while true do
Wait(500)
local istalking = NetworkIsPlayerTalking(PlayerId()) -- doesn't work with player variable
SendNUIMessage({talking = istalking})
end
end)
--[[End of Threads]]--
--[[Status Event]]--
RegisterNetEvent('joehud:setInfo')
AddEventHandler('joehud:setInfo', function(info)
if ESX.PlayerData.job and ESX.PlayerData.job.grade_name and ESX.PlayerData.job.grade_name == 'boss' then
ESX.TriggerServerCallback('esx_society:getSocietyMoney', function(money)
society = money
end, ESX.PlayerData.job.name)
else
society = 0
end
TriggerEvent('esx_status:getStatus', 'hunger', function(status) hunger = status.val / 10000 end)
TriggerEvent('esx_status:getStatus', 'thirst', function(status) thirst = status.val / 10000 end)
if Config.rpRadio then
local radioStatus = exports["rp-radio"]:IsRadioOn()
SendNUIMessage({radio = radioStatus})
end
if (lastjob ~= info['job']) then
lastjob = info['job']
SendNUIMessage({job = info['job']})
end
if (lastcash ~= info['money']) then
lastcash = info['money']
SendNUIMessage({money = comma_value(info['money'])})
end
if (lastbank ~= info['bankMoney']) then
lastbank = info['bankMoney']
SendNUIMessage({bank = comma_value(info['bankMoney'])})
end
if (lastdirty ~= info['blackMoney']) then
lastdirty = info['blackMoney']
SendNUIMessage({blackMoney = comma_value(info['blackMoney'])})
end
if (lastsociety ~= society) then
lastsociety = society
SendNUIMessage({society = comma_value(society)})
end
SendNUIMessage({
action = "update_hud",
hp = GetEntityHealth(PlayerPedId()) - 100,
armor = GetPedArmour(PlayerPedId()),
stamina = 100 - GetPlayerSprintStaminaRemaining(PlayerId()), -- doesn't work with player variable
hunger = hunger,
thirst = thirst,
oxygen = GetPlayerUnderwaterTimeRemaining(PlayerId()) * 10 -- doesn't work with player variable
})
end)
--[[End of Status Event]]
--[[Map]]--
local x = -0.025
local y = -0.015
Citizen.CreateThread(function()
RequestStreamedTextureDict("circlemap", false)
while not HasStreamedTextureDictLoaded("circlemap") do
Wait(100)
end
AddReplaceTexture("platform:/textures/graphics", "radarmasksm", "circlemap", "radarmasksm")
SetMinimapClipType(1)
SetMinimapComponentPosition('minimap', 'L', 'B', -0.022, -0.026, 0.16, 0.245)
SetMinimapComponentPosition('minimap_mask', 'L', 'B', x + 0.21, y + 0.09, 0.071, 0.164)
SetMinimapComponentPosition('minimap_blur', 'L', 'B', -0.032, -0.04, 0.18, 0.22)
SetRadarBigmapEnabled(true, false)
Wait(150)
SetRadarBigmapEnabled(false, false)
end)
--[[End of Map]]--
--[[Command Events]]
RegisterNetEvent('joehud:devmode')
AddEventHandler('joehud:devmode', function()
SendNUIMessage({action = "devmode"})
end, false)
RegisterNetEvent('joehud:showjob')
AddEventHandler('joehud:showjob', function()
TriggerEvent('chat:addMessage', {
color = { 150, 75, 0},
multiline = true,
args = {"Job Center", "Your job is " .. lastjob}
})
end, false)
RegisterNetEvent('joehud:showcash')
AddEventHandler('joehud:showcash', function()
TriggerEvent('chat:addMessage', {
color = { 0, 240, 0},
multiline = true,
args = {"Wallet", "You have $" .. comma_value(lastcash)}
})
end, false)
RegisterNetEvent('joehud:showbank')
AddEventHandler('joehud:showbank', function()
TriggerEvent('chat:addMessage', {
color = { 240, 0, 0},
multiline = true,
args = {"Bank", "You have $" .. comma_value(lastbank)}
})
end, false)
RegisterNetEvent('joehud:showdirty')
AddEventHandler('joehud:showdirty', function()
TriggerEvent('chat:addMessage', {
color = { 128, 128, 128},
multiline = true,
args = {"Pocket", "You have $" .. comma_value(lastdirty)}
})
end, false)
RegisterNetEvent('joehud:showid')
AddEventHandler('joehud:showid', function()
TriggerEvent('chat:addMessage', {
color = { 0, 240, 0},
multiline = true,
args = {"Wallet", "Your state ID is: " .. GetPlayerServerId(PlayerId()) }
})
end, false)
RegisterNetEvent('joehud:showsociety')
AddEventHandler('joehud:showsociety', function()
TriggerEvent('chat:addMessage', {
color = { 150, 75, 0},
multiline = true,
args = {"Business", "The current business funds are $" .. comma_value(society) }
})
end, false)
RegisterNetEvent('joehud:hudmenu')
AddEventHandler('joehud:hudmenu', function()
SetNuiFocus(true, true)
SendNUIMessage({showhudmenu = true})
end, false)
--[[End of Command Events]]--
--[[Callbacks]]--
RegisterNUICallback('cancel', function()
SetNuiFocus(false, false)
SendNUIMessage({showhudmenu = false})
end)
RegisterNUICallback('getmap', function(data, cb)
mapon = data.mapon
cb(mapon)
end)
RegisterNUICallback('getspeedfps', function(data, cb)
speedfps = data.speedfps or 125
cb(speedfps)
end)
--[[End of Callbacks]]--
--[[Commands & KeyMappings]]--
RegisterCommand('uir', function()
ESX.UI.Menu.CloseAll()
TriggerEvent('wk:toggleMenuControlLock', false)
SendNUIMessage({showhudmenu = false})
SendNUIMessage({type = 'destroy'})
SendNUIMessage({toggleradarrc = true})
SendNUIMessage({action = 'closeMenu', namespace = namespace, name = name, data = data})
SendNUIMessage({type = 'closeAll'})
TriggerEvent("mdt:closeModal")
showMenu = false
SetNuiFocus(false, false)
ClearPedTasksImmediately(PlayerPedId())
end, false)
RegisterCommand('speedlimiter', function()
if pedinVeh and vehicleIsOn then
local vehicle = GetVehiclePedIsIn(player, false)
local vehicleModel = GetEntityModel(vehicle)
local speed = GetEntitySpeed(vehicle)
local Max = GetVehicleModelMaxSpeed(vehicleModel)
local vehicleClass = GetVehicleClass(GetVehiclePedIsIn(player))
if (GetPedInVehicleSeat(vehicle, -1) == player) then
if vehicleClass == 13 then
else
if not enableCruise then
SetVehicleMaxSpeed(vehicle, speed)
enableCruise = true
SendNUIMessage({
speedlimiter = true
})
elseif enableCruise then
SetVehicleMaxSpeed(vehicle, GetVehicleHandlingFloat(vehicle,"CHandlingData","fInitialDriveMaxFlatVel"))
enableCruise = false
SendNUIMessage({
speedlimiter = false
})
else
SetVehicleMaxSpeed(vehicle, Max)
enableCruise = false
SendNUIMessage({
speedlimiter = false
})
end
end
end
end
end, false)
RegisterCommand('seatbelt', function()
local vehicleClass = GetVehicleClass(GetVehiclePedIsIn(player))
if vehicleClass == 8 or vehicleClass == 13 or vehicleClass == 14 or vehicleClass == 21 then
print("You can't enable your seatbelt in this type of vehicle")
else
if pedinVeh then
beltOn = not beltOn
if beltOn then
SendNUIMessage({seatbelton = true})
else
SendNUIMessage({seatbelton = false})
end
end
end
end, false)
RegisterKeyMapping('speedlimiter', 'Activate Speedlimiter', 'keyboard', 'CAPITAL')
RegisterKeyMapping('seatbelt', 'Activate Seatbelt', 'keyboard', 'B')
--[[End of Commands & KeyMappings]]
--[[Single Checks]]--
if Config.Speed == "mph" or Config.Speed == "MPH" then
speedtext = "MPH"
speedomulti = 2.236936
else
speedtext = "KMH"
speedomulti = 3.6
end
--[[End of Single Checks]]--
|
local M = {}
local io = io
local string = string
local tostring = tostring
local ngx = ngx
local ffi = require "ffi"
local util = require "shuaicj.upload.util"
ffi.cdef[[
typedef unsigned long MD5_LONG;
enum {
MD5_CBLOCK = 64,
MD5_LBLOCK = MD5_CBLOCK/4
};
typedef struct MD5state_st
{
MD5_LONG A,B,C,D;
MD5_LONG Nl,Nh;
MD5_LONG data[MD5_LBLOCK];
unsigned int num;
} MD5_CTX;
int MD5_Init(MD5_CTX *c);
int MD5_Update(MD5_CTX *c, const void *data, size_t len);
int MD5_Final(unsigned char *md, MD5_CTX *c);
]]
M.header = "X-Checksum-MD5"
function M.check_headers(ctx, headers)
local v = headers[M.header]
if v and #v == 32 and string.match(v, "^%x+$") then
ctx.checksum.md5 = {
header = M.header,
client = v
}
return
end
local s = string.format("%s [%s] illegal", M.header, tostring(v))
ngx.log(ngx.WARN, s)
return util.exit(400, s)
end
function M.verify_checksum(ctx)
local md5_ctx = ffi.new("MD5_CTX")
if ffi.C.MD5_Init(md5_ctx) == 0 then
ngx.log(ngx.ERR, "MD5_Init failed")
return util.exit(500, "MD5_Init failed")
end
local f, e = io.open(ctx.file_path, "rb")
if not f then
ngx.log(ngx.ERR, e)
return util.exit(500, e)
end
while true do
local data = f:read(4096)
if not data then
f:close()
break
end
if ffi.C.MD5_Update(md5_ctx, data, #data) == 0 then
ngx.log(ngx.ERR, "MD5_Update failed")
return util.exit(500, "MD5_Update failed")
end
end
local checksum = ffi.new("char[16]")
if ffi.C.MD5_Final(checksum, md5_ctx) == 0 then
ngx.log(ngx.ERR, "MD5_Final failed")
return util.exit(500, "MD5_Final failed")
end
checksum = util.tohex(ffi.string(checksum, 16))
ctx.checksum.md5.server = checksum
if ctx.checksum.md5.client ~= checksum then
util.truncate_file(ctx.file_path)
ctx.real_size = 0
local s = string.format("MD5 conflict. file[%s] client [%s], server [%s]",
ctx.file_path, ctx.checksum.md5.client, checksum)
ngx.log(ngx.ERR, s)
return util.exit(409, s, ctx)
else
ngx.log(ngx.INFO, string.format("MD5 match. file[%s] MD5 [%s]", ctx.file_path, checksum))
end
end
return M
|
return {
include = function()
includedirs "../vendor/cpp-url/include/"
end,
run = function()
language "C++"
kind "StaticLib"
files {
"../vendor/cpp-url/src/**.cpp",
}
end
}
|
local menu = {} -- previously: Gamestate.new()
menu.name = "showCreepers"
function menu:enter(prev, cards, changes)
menu.prev = prev
menu.cards = cards
menu.changes = changes
end
local offsets = {
{ x = 621, y = 153 },
{ x = 373, y = 153 },
{ x = 869, y = 153 },
{ x = 124, y = 153 },
{ x = 1118, y = 153 },
{ x = 621, y = 460 },
{ x = 373, y = 460 },
{ x = 869, y = 460 },
{ x = 124, y = 460 },
{ x = 1118, y = 460 },
}
function menu:draw()
menu.prev:draw()
for i = 1, math.min(#offsets, #menu.cards) do
scripts.rendering.renderCard.renderCard(menu.cards[i], offsets[i].x, offsets[i].y, 0.5)
end
end
function menu:update()
scripts.rendering.renderUI.drawUpdates(menu.changes)
end
function menu:mousepressed(x, y, click)
for i = 1, math.min(#offsets, #menu.cards) do
for k, card in pairs(scripts.gameobjects.cards) do
if menu.cards[i] == card then
STATE.discardPile[#STATE.discardPile + 1] = k
end
end
end
Gamestate.pop()
end
return menu |
leveldb = require 'lualeveldb'
local opt = leveldb.options()
opt.createIfMissing = true
opt.errorIfExists = false
assert(type(tostring(opt)) == "string")
print(opt)
local db = leveldb.open (opt, 'tostring.db')
assert(type(tostring(db)) == "string")
print(db)
|
addNetworkString = util.AddNetworkString
addNetworkString("VBNET::Groups::RequestGroupPlayerList")
addNetworkString("VBNET::Groups::InvitePlayerToGroup")
addNetworkString("VBNET::Groups::PlayerJoinGroup")
addNetworkString("VBNET::Groups::PlayerQuitGroup")
addNetworkString("VBNET::Groups::KickPlayer")
addNetworkString("VBNET::Groups::RequestPlayerToJoinGroup")
addNetworkString("VBNET::Groups::PlayerChangePermission")
addNetworkString("VBNET::Groups::GetMembers")
addNetworkString("VBNET::Groups::SendMembers")
net.Receive("VBNET::Groups::PlayerQuitGroup", function(len, pl)
local currentGroup = pl:GetNWString("VB::NW::Organization::Name")
if currentGroup ~= "VB-Default-Organization" then
local steamid = pl:SteamID()
VBSQL:Query([[
UPDATE players SET organization_id = NULL WHERE steam_id = ']] .. VBSQL:Escape(steamid) .. [[';
]])
VBSQL:Query([[
UPDATE players SET group_permissions = 0 WHERE steam_id = ']] .. VBSQL:Escape(steamid) .. [[';
]])
pl:SetNWString("VB::NW::Organization::Name", "VB-Default-Organization")
pl:SetNWString("VB::NW::Organization::Color", "ffffff")
pl:SetDTGroupPermissionMask(0)
pl:SetDTGroupId(0)
pl:SetWeaponColor(HexToColorRGB(pl:GetNWString("VB::NW::Organization::Color")):ToVector())
end
end)
net.Receive("VBNET::Groups::GetMembers", function(len, pl)
local group = pl:GetDTGroupId()
local players = {}
local query = VBSQL:Query([[
SELECT first_name, last_name, group_permissions FROM players
WHERE organization_id = ]] .. group .. [[;
]])
query:wait()
local data = query:getData()
if data == nil then return false end
for k, v in ipairs(data) do
if v["first_name"] .. " " .. v["last_name"] == pl:GetCompleteName() then continue end
local completeName = string.format("%s %s", v["first_name"], v["last_name"])
players[completeName] = {
["online"] = IsOnline(completeName),
["permissions"] = tonumber(v["group_permissions"])
}
end
net.Start("VBNET::Groups::SendMembers")
net.WriteTable(players)
net.Send(pl)
end)
net.Receive("VBNET::Groups::KickPlayer", function(len, pl)
if not Permission:Can(pl:GetDTGroupPermissionMask(), Permission.KICK) then return false end
local playerToKick = net.ReadString()
if IsOnline(playerToKick) then
local playerEntity = nil
for k, v in pairs(player.GetAll()) do
if v:GetCompleteName() == playerToKick then
playerEntity = v
end
end
local steamid = playerEntity:SteamID()
VBSQL:Query([[
UPDATE players SET organization_id = NULL, group_permissions = 0 WHERE steam_id = ']] .. VBSQL:Escape(steamid) .. [[';
]])
playerEntity:SetNWString("VB::NW::Organization::Name", "VB-Default-Organization")
playerEntity:SetNWString("VB::NW::Organization::Color", "ffffff")
playerEntity:SetDTGroupPermissionMask(0)
playerEntity:SetDTGroupId(0)
playerEntity:SetWeaponColor(HexToColorRGB(playerEntity:GetNWString("VB::NW::Organization::Color")):ToVector())
else
local firstName, lastName = unpack(string.Explode(" ", playerToKick))
VBSQL:Query([[
UPDATE players SET organization_id = NULL, group_permissions = 0 WHERE first_name = ']] .. VBSQL:Escape(firstName) .. [[' AND last_name = ']] .. VBSQL:Escape(lastName) .. [[';
]])
end
end)
net.Receive("VBNET::Groups::PlayerChangePermission", function(len, pl)
if pl:GetNWString("VB::NW::Organization::Name") == "VB-Default-Organization" then return false end
local playerName = net.ReadString()
local bitMask = net.ReadInt(9)
local playerEntity = nil
for k, v in pairs(player.GetAll()) do
if v:GetCompleteName() == playerName then
playerEntity = v
end
end
-- If player is online
if Permission:Can(pl:GetDTGroupPermissionMask(), Permission.ADMIN) and playerEntity ~= nil then
local steamid = playerEntity:SteamID()
VBSQL:Query([[
UPDATE players SET group_permissions = ]] .. bitMask .. [[
WHERE steam_id = ']] .. VBSQL:Escape(steamid) .. [[';
]])
playerEntity:SetDTGroupPermissionMask(bitMask)
-- If player is offline
elseif Permission:Can(pl:GetDTGroupPermissionMask(), Permission.ADMIN) and playerEntity == nil then
local firstName, lastName = unpack(string.Explode(" ", playerName))
VBSQL:Query([[
UPDATE players SET group_permissions = ]] .. bitMask .. [[
WHERE first_name = ']] .. VBSQL:Escape(firstName) .. [[' AND last_name = ']] .. VBSQL:Escape(lastName) .. [[';
]])
end
end)
net.Receive("VBNET::Groups::InvitePlayerToGroup", function(len, pl)
if not Permission:Can(pl:GetDTGroupPermissionMask(), Permission.INVITE) then return false end
local name = net.ReadString()
local group = net.ReadString()
local playerToSendInvitation = nil
for k,v in pairs(player.GetAll()) do
if v:GetCompleteName() == name then
playerToSendInvitation = v
end
end
if playerToSendInvitation ~= nil then
net.Start("VBNET::Groups::RequestPlayerToJoinGroup")
net.WriteString(group)
net.Send(playerToSendInvitation)
end
end)
net.Receive("VBNET::Groups::PlayerJoinGroup", function(len, pl)
local group = net.ReadString()
local steamid = pl:SteamID()
local query = VBSQL:Query([[
SET @ID = (SELECT organization_id FROM organization
WHERE organization_name = ']] .. VBSQL:Escape(group) .. [[' );
UPDATE players
SET players.organization_id = @ID, players.group_permissions = 0
WHERE steam_id = ']] .. VBSQL:Escape(steamid) .. [[';
]])
local query2 = VBSQL:Query([[
SELECT organization_color, organization_id FROM organization
WHERE organization_name = ']] .. VBSQL:Escape(group) .. [[';
]])
query2:wait()
VBSQL:Query([[
UPDATE players SET group_permissions = 0 WHERE steam_id = ']] .. VBSQL:Escape(steamid) .. [[';
]])
local id = query2:getData()[1]["organization_id"]
local col = query2:getData()[1]["organization_color"]
pl:SetNWString("VB::NW::Organization::Name", group)
pl:SetNWString("VB::NW::Organization::Color", col)
pl:SetDTGroupPermissionMask(0)
pl:SetDTGroupId(id)
pl:SetWeaponColor(HexToColorRGB(pl:GetNWString("VB::NW::Organization::Color")):ToVector())
end) |
--
-- Info Definition Table format
--
--
-- These keywords must be lowercase for LuaParser to read them.
--
-- key: user defined or one of the SKIRMISH_AI_PROPERTY_* defines in
-- SSkirmishAILibrary.h
-- value: the value of the property
-- desc: the description (could be used as a tooltip)
--
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local infos = {
{
key = 'shortName',
value = 'BtEvaluator',
desc = 'machine conform name.',
},
{
key = 'version',
value = '0.0001', -- AI version - !This comment is used for parsing!
},
{
key = 'name',
value = 'BtEvaluator',
desc = 'human readable name.',
},
{
key = 'description',
value = 'This is part of BETS project, behaviour trees editing and debugging toolkit.',
desc = 'tooltip.',
},
{
key = 'url',
value = 'http://notalab.com/projects/bets/',
desc = 'URL with more detailed info about the AI',
},
{
key = 'loadSupported',
value = 'no',
desc = 'whether this AI supports loading or not',
},
{
key = 'interfaceShortName',
value = 'C', -- AI Interface name - !This comment is used for parsing!
desc = 'the shortName of the AI interface this AI needs',
},
{
key = 'interfaceVersion',
value = '0.1', -- AI Interface version - !This comment is used for parsing!
desc = 'the minimum version of the AI interface this AI needs',
},
}
return infos
|
function start (song)
print("Song: " .. song .. " @ " .. bpm .. " downscroll: " .. downscroll)
end
local defaultHudX = 0
local defaultHudY = 0
local defaultWindowX = 0
local defaultWindowY = 0
local lastStep = 0
local floatShit = 0
local dadMidpointX = 0
local dadMidpointY = 0
local eyeX = 0
local eyeY = 0
function update (elapsed)
local currentBeat = (songPos / 1000)*(bpm/60)
end
function beatHit (beat)
end
function stepHit (step)
--leaving this here to test stuff
if curStep == 1 then
end
if curStep == 190 then
changeDadCharacter('exe-revie', 250, -200)
end
if curStep == 260 then
changeBoyfriendCharacter('bf-sonic', 1140, 170)
end
if curStep == 320 then
changeDadCharacter('haachama', 240, -60)
end
if curStep == 384 then
changeBoyfriendCharacter('gura-amelia', 1290, 20)
end
if curStep == 446 then
changeDadCharacter('freddy', 230, -190)
end
if curStep == 512 then
changeBoyfriendCharacter('bf-cryingchild', 1320, 170)
end
if curStep == 576 then
changeDadCharacter('cc', 240, -120)
characterZoom('dad', 1.3)
end
if curStep == 704 then
changeBoyfriendCharacter('oswald-angry', 1340, 80)
end
if curStep == 768 then
changeDadCharacter('huggy', 240, -120)
followDadXOffset = -200
end
if curStep == 832 then
changeBoyfriendCharacter('beebz', 1260, 70)
end
if curStep == 896 then
changeDadCharacter('monster', 180, -90)
followDadXOffset = 0
end
if curStep == 1024 then
changeBoyfriendCharacter('spooky', 1290, 20)
end
if curStep == 1088 then
changeDadCharacter('yuri-crazy', 250, -50)
end
end |
local shipImg = actor.LoadSprite("image/ship.png", { 64, 64 })
local LEFT = 1
local RIGHT = 2
local UP = 3
local DOWN = 4
actor.Cage("Blocker", 1.0, 0.5)
actor.SimpleCollide("Blocker", "Player", actor.Blocker)
local animFPS = 64
local function AnimatePlayer(player, stop)
local start = eapi.GetFrame(player.tile)
local time = math.abs(stop - start) / animFPS
eapi.AnimateFrame(player.tile, eapi.ANIM_CLAMP, start, stop, nil, time)
end
local function Animate(player)
local vel = eapi.GetVel(player.body)
if vel.x == 0 then
AnimatePlayer(player, 16)
elseif vel.x > 0 then
AnimatePlayer(player, 8)
elseif vel.x < 0 then
AnimatePlayer(player, 24)
end
end
local function GetDirection(moves)
return { x = moves[RIGHT] - moves[LEFT], y = moves[UP] - moves[DOWN] }
end
local function SetSpeed(player, speed)
if speed then player.speed = speed end
eapi.SetVel(player.body, vector.Normalize(player.vel, player.speed))
end
local function EnableInput(player, Fn)
input.Bind("Left", false, Fn(player, LEFT))
input.Bind("Right", false, Fn(player, RIGHT))
input.Bind("Up", false, Fn(player, UP))
input.Bind("Down", false, Fn(player, DOWN))
return player
end
local function Move(player, axis)
return function(keyDown)
player.moves[axis] = (keyDown and 1) or 0
player.vel = GetDirection(player.moves)
SetSpeed(player)
Animate(player)
end
end
local function FirstMove(player, axis)
return function(keyDown)
Move(player, axis)(keyDown)
util.Map(eapi.Destroy, player.text)
EnableInput(player, Move)
actor.AddProgressCircle(player)
bomb.ResetTime()
timing.Start()
end
end
local function AddHeart(obj)
local speed = 0.2
local z = obj.z + 0.1
local animType = eapi.ANIM_LOOP
local size = { x = 16, y = 16 }
local offset = { x = -8, y = -3 }
obj.heart = eapi.NewTile(obj.body, offset, size, util.heart, z)
eapi.SetColor(obj.heart, { r = 0.25, g = 0.05, b = 0, a = 0.25 })
local dstSize = { x = 8, y = 8 }
local dstOffset = { x = -4, y = 1 }
eapi.AnimateSize(obj.heart, animType, dstSize, speed, 0)
eapi.AnimatePos(obj.heart, animType, dstOffset, speed, 0)
local dstColor = { r = 0.75, g = 0.15, b = 0, a = 1.0 }
eapi.AnimateColor(obj.heart, animType, dstColor, speed, 0)
end
local function Create()
local obj = { z = 0,
speed = 300,
class = "Player",
sprite = shipImg,
vel = vector.null,
moves = { 0, 0, 0, 0 },
pos = { x = 0, y = -200 },
offset = { x = -32, y = -32 },
bb = { l = -4, r = 4, b = 2, t = 10 }, }
local text = "\"Arrow Keys\" - Evade"
ribbons.ShowHelpText(obj, text)
obj = actor.Create(obj)
eapi.SetFrame(obj.tile, 16)
eapi.PlayMusic("sound/music.ogg", nil, 1.0, 1.0)
EnableInput(obj, FirstMove)
player.obj = obj
AddHeart(obj)
end
local function QuickFade(tile)
eapi.SetColor(tile, util.invisible)
end
player = {
Create = Create,
patternTime = 6.28,
}
return player
|
---------------------------------------------------------------------------------------------------
-- func: getcraftRank <craft skill or ID> {player}
-- desc: returns target's RANK of specified craft skill
---------------------------------------------------------------------------------------------------
require("scripts/globals/status")
cmdprops =
{
permission = 1,
parameters = "ss"
}
function error(player, msg)
player:PrintToPlayer(msg)
player:PrintToPlayer("!getcraftRank <craft skill or ID> {player}")
end
function onTrigger(player, craftName, target)
if craftName == nil then
error(player, "You must specify a craft skill to check!")
return
end
local skillID = tonumber(craftName) or tpz.skill[string.upper(craftName)]
local targ = nil
if skillID == nil or skillID < 48 or skillID > 57 then
error(player, "You must specify a valid craft skill.")
return
end
if target == nil then
if player:getCursorTarget() == nil then
targ = player
else
if player:getCursorTarget():isPC() then
targ = player:getCursorTarget()
else
error(player, "You must target a player or specify a name.")
return
end
end
else
targ = GetPlayerByName(target)
if targ == nil then
player:PrintToPlayer(string.format("Player named '%s' not found!", target))
return
end
end
player:PrintToPlayer(string.format("%s's current skillID '%s' rank: %u", targ:getName(), craftName, targ:getSkillRank(skillID)))
end
|
------------------------------------------------------------------------------------------------------
-- Initialise the variable we will be working with
------------------------------------------------------------------------------------------------------
Cryolysis3 = LibStub("AceAddon-3.0"):NewAddon("Cryolysis3", "AceConsole-3.0", "AceEvent-3.0", "AceTimer-3.0");
local L = LibStub("AceLocale-3.0"):GetLocale("Cryolysis3");
local AceConfig = LibStub("AceConfigDialog-3.0");
-- Don't move this!
Cryolysis3:SetDefaultModuleState(false);
------------------------------------------------------------------------------------------------------
-- Initialise the startup
------------------------------------------------------------------------------------------------------
local function InitStartup()
--Cryolysis3:RegisterChatCommand("cryo", "ChatCommand") --See function Cryolysis3:ChatCommand for details
--Cryolysis3:RegisterChatCommand("cryolysis", "ChatCommand")
Cryolysis3:RegisterChatCommand("cryo3", "ChatCommand")
Cryolysis3:RegisterChatCommand("cryolysis3", "ChatCommand")
-- Create the main sphere frame
Cryolysis3:CreateFrame(
"Button", "Sphere", UIParent, "SecureActionButtonTemplate",
58, 58, true,
nil, nil, nil,
"Interface\\AddOns\\Cryolysis3\\textures\\background",
nil,
Cryolysis3.db.char.hidden["Sphere"]
);
-- Make main sphere draggable
Cryolysis3Sphere:RegisterForDrag("LeftButton");
Cryolysis3Sphere:RegisterForClicks("LeftButtonUp", "RightButtonUp", "MiddleButtonUp");
-- Open the config menu when right-clicking the main sphere
Cryolysis3Sphere:SetAttribute("type2", "Menu");
Cryolysis3Sphere.Menu = function() LibStub("AceConfigDialog-3.0"):Open("Cryolysis3"); end
-- Handle main sphere dragging
Cryolysis3:AddScript("Sphere", "frame", "OnDragStart");
Cryolysis3:AddScript("Sphere", "frame", "OnDragStop");
-- Handle main sphere tooltip
Cryolysis3:AddScript("Sphere", "frame", "OnEnter");
Cryolysis3:AddScript("Sphere", "frame", "OnLeave");
-- Start tooltip data
Cryolysis3.Private.tooltips["Sphere"] = {};
-- Setup custom clicks, right left out cuz it's for the menu
Cryolysis3:UpdateButton("Sphere", "left");
Cryolysis3:UpdateButton("Sphere", "middle");
-- Start adding tooltip data
table.insert(Cryolysis3.Private.tooltips["Sphere"], L["Cryolysis"]);
-- Set mount region thingy
Cryolysis3.Private.mountRegion = IsFlyableArea();
-- Find our mounts
Cryolysis3:FindMounts();
-- Setup custom buttons
Cryolysis3:CreateCustomButtons();
-- Setup class-specific buttons
Cryolysis3.GetClassModule():CreateButtons();
-- Place the buttons where they're supposed to be
Cryolysis3:UpdateAllButtonPositions();
-- Update main sphere
Cryolysis3:UpdateSphere("outerSphere");
Cryolysis3:UpdateSphere("sphereText");
Cryolysis3:UpdateSphere("sphereAttribute");
end
------------------------------------------------------------------------------------------------------
-- Load all enabled modules
------------------------------------------------------------------------------------------------------
local function LoadModule(name)
-- Attempt to load the LoD module
local loaded, reason = Cryolysis3:EnableModule(name);
if not loaded then
-- We couldn't load it :(
local dialogueText = L["Cryolysis 3 cannot load the module:"].." Cryolysis3_"..name.."\n";
if (reason == "DISABLED") then
-- The class module was disabled
dialogueText = dialogueText.." "..L["The module is flagged as Disabled in the Blizzard AddOn interface."];
elseif (reason == "MISSING") then
-- The class module isn't there (most likely not installed)
dialogueText = dialogueText.." "..L["The module is missing. Please close the game and install it."];
elseif (reason == "INCOMPATIBLE") then
-- The class module is too old (most likely not updated)
dialogueText = dialogueText.." "..L["The module is too old. Please close the game and update it."];
end
-- Create the popup dialogue
StaticPopupDialogs["C3_LOD_ADDON_WARNING"] = {
text = dialogueText,
button1 = L["Okay"],
timeout = 0,
whileDead = 1,
hideOnEscape = 1
}
-- Display the dialogue
StaticPopup_Show("C3_LOD_ADDON_WARNING");
return false;
end
return true;
end
------------------------------------------------------------------------------------------------------
-- Check if items need to be cached and if so, display a warning.
------------------------------------------------------------------------------------------------------
function Cryolysis3:CacheItems(itemList)
local checkAgain = false;
if (itemList ~= nil) then
for i = 1, #(itemList), 1 do
if (GetItemInfo(itemList[i]) == nil or GetItemInfo(itemList[i]) == "") then
--print ('Item',i,GetItemInfo(itemList[i]))
StaticPopup_Show("ITEM_CACHE_WARNING");
GameTooltip:SetOwner(UIParent, "CENTER");
GameTooltip:SetHyperlink("item:"..itemList[i]..":0:0:0:0:0:0:0:0");
GameTooltip:Hide();
checkAgain = true;
end
end
end
if (checkAgain) then
return false
else
StaticPopup_Hide("ITEM_CACHE_WARNING");
return true
end
end
------------------------------------------------------------------------------------------------------
-- Load class module
------------------------------------------------------------------------------------------------------
local function LoadClassModule()
-- Detect what class we are playing and return English value, then load it
local classLoaded = LoadModule(Cryolysis3.className);
if (classLoaded == true) then
if (not Cryolysis3.db.char.silentMode) then
-- Only print this if we're not in silent mode
local classname = gsub(UnitClass("player"), "^.", function(s) return s:upper() end)
Cryolysis3:Print(classname.." "..L["Module"].." "..L["Loaded"]);
end
-- Cache here, since before this we don't have a spellList
Cryolysis3:CacheSpells();
end
end
------------------------------------------------------------------------------------------------------
-- Load all enabled modules
------------------------------------------------------------------------------------------------------
function Cryolysis3:LoadModules()
if (Cryolysis3:CacheItems(Cryolysis3.Private.cacheList)) then
-- Create reagent list for the mage
Cryolysis3.GetClassModule():CreateReagentList();
for k, v in pairs(Cryolysis3.db.char.modules) do
if (Cryolysis3.db.char.modules[k]) then
-- Load the module if it's enabled in the config
LoadModule(k);
end
end
InitStartup();
else
Cryolysis3:ScheduleTimer("LoadModules", 1)
end
end
------------------------------------------------------------------------------------------------------
-- What happens when the addon is first loaded
------------------------------------------------------------------------------------------------------
function Cryolysis3:OnInitialize()
-- Register the database
Cryolysis3.db = LibStub("AceDB-3.0"):New("Cryolysis3DB", Cryolysis3.defaults, "char");
-- Create the buttons array
Cryolysis3.buttons = {};
-- Add info to the Options array for the Profile Options
Cryolysis3.options.args.profile.args.options = LibStub("AceDBOptions-3.0"):GetOptionsTable(Cryolysis3.db);
Cryolysis3.options.args.profile.args.options.name = L["Options profile"];
Cryolysis3.options.args.profile.args.options.desc = L["Saved profile for Cryolysis 3 options"];
Cryolysis3.options.args.profile.args.options.order = 2;
-- Create options table and stuff
LibStub("AceConfig-3.0"):RegisterOptionsTable("Cryolysis3", Cryolysis3.options);
AceConfig:AddToBlizOptions("Cryolysis3", "Cryolysis3");
end
------------------------------------------------------------------------------------------------------
-- What happens when the addon is enabled
------------------------------------------------------------------------------------------------------
function Cryolysis3:OnEnable()
-- Store this since we use it so often
Cryolysis3.className = select(2, UnitClass("player"));
--print (Cryolysis3.className)
-- Register for some common events used by all modules
Cryolysis3:RegisterCommonEvents();
-- Create the popup dialogue
StaticPopupDialogs["ITEM_CACHE_WARNING"] = {
text = L["Cryolysis 3 is currently adding items to your game's item cache. The addon should finish loading and this dialog box should disappear once this is complete."],
timeout = 0,
whileDead = 1,
hideOnEscape = 1
}
-- Load the module for our class
LoadClassModule();
-- Load all enabled modules
Cryolysis3:LoadModules();
end
------------------------------------------------------------------------------------------------------
-- What happens when the addon is disabled
------------------------------------------------------------------------------------------------------
function Cryolysis3:OnDisable()
end
------------------------------------------------------------------------------------------------------
-- Get the class module
------------------------------------------------------------------------------------------------------
function Cryolysis3:GetClassModule()
-- Return the module that fits our class
return Cryolysis3.modules[Cryolysis3.className];
end
------------------------------------------------------------------------------------------------------
-- Having a function with msg being passed to it allows us to create /commands later if desired
-- If no msg is passed, open the GUI, else accept a chat command.
------------------------------------------------------------------------------------------------------
function Cryolysis3:ChatCommand(msg)
if not input or input:trim() == "" then
-- We're opening config dialogue
LibStub("AceConfigDialog-3.0"):Open("Cryolysis3");
else
-- We have a chat command
LibStub("AceConfigCmd-3.0").HandleCommand(Cryolysis3, "cryo", "cryolysis", "cryo3", "cryolysis3", msg);
end
end |
Locales ['pl'] = {
['voice'] = '~y~Głos: ~s~%s',
['normal'] = 'normalny',
['shout'] = 'krzyk',
['whisper'] = 'szept',
}
|
return {
postgres = {
up = [[
ALTER TABLE IF EXISTS ONLY "basicauth_credentials"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
-- Unique constraint on "username" already adds btree index
DROP INDEX IF EXISTS "basicauth_username_idx";
]],
},
cassandra = {
up = [[
]],
},
}
|
require("tokenize")
require("parse")
while true do
io.write("%> ")
local line = io.read("l")
if line == "exit" then break end
local tokens = Tokenize(line)
local ast = Parse(tokens)
end |
require "suproxy.utils.stringUtils"
local _M={}
local printFlag="___printted"
--format and print table in json style
function _M.printTableF(tab,options,layer,map)
options=options or {}
local printIndex=options.printIndex or false
local layer=layer or 1
local stopLayer=options.stopLayer or 0xffff
local inline=options.inline or false
local wrap= (not inline) and "\r\n" or ""
local tabb= (not inline) and "\t" or ""
local justLen=options.justLen or false
local ascii=options.ascii or true
local excepts=options.excepts or {}
local map=map or {}
local includes=options.includes
local logStr=""
if layer>stopLayer then return logStr end
if type(tab)=="table" and (not map[tostring(tab)]) then
map[tostring(tab)]=""
local i=1
local isList=true
local shortList=true
for k, v in pairs(tab) do
if k~=i then isList=false break end
if type(v)=="table" then shortList=false end
i=i+1
end
--no item in table
if i==1 then isList,shortList =false,false end
if not tab.__orderred then
for k, v in pairs(tab) do
local skip=false
k=tostring(k)
for _,e in ipairs(excepts) do
if k:match(e) then
skip=true
break
end
end
if includes then
local inWhiteList=false
for _,e in ipairs(includes) do
if k:match(e) then
inWhiteList=true
end
end
skip=not inWhiteList
end
if not skip then
if not isList or not shortList then logStr=logStr..wrap..string.rep(tabb,layer) end
if not isList then logStr=logStr.."\""..k.."\":" end
--print(string.rep(" ",layer),k,":",tostring(v))
logStr=logStr.._M.printTableF(v,options,layer+1,map)
logStr=logStr..","
end
end
else
for k, v in ipairs(tab) do
local skip=false
for _,e in ipairs(excepts) do
if v.key:match(e) then
skip=true
break
end
end
if includes then
local inWhiteList=false
for _,e in ipairs(includes) do
if v.key:match(e) then
inWhiteList=true
end
end
skip=not inWhiteList
end
if not skip then
if not isList or not shortList then logStr=logStr..wrap..string.rep(tabb,layer) end
if not isList then logStr=logStr.."\""..v.key.."\":" end
logStr=logStr.._M.printTableF(v.value,options,layer+1,map)
logStr=logStr..","
end
end
end
if printIndex and getmetatable(tab) and getmetatable(tab).__index then
if not isList or not shortList then logStr=logStr..wrap..string.rep(tabb,layer) end
if not isList then logStr=logStr.."\"__index\":" end
logStr=logStr.._M.printTableF(getmetatable(tab).__index,options,layer+1,map)..","
end
if #logStr >0 then logStr=logStr:sub(1,#logStr-1) end
logStr=(isList and "[" or "{")..logStr
if not isList or not shortList then logStr=logStr..wrap..string.rep(tabb,layer-1) end
logStr=logStr..(isList and "]" or "}")..tostring(tab)
elseif type(tab)=="string" then
logStr="[Len:"..tab:len().."]"..logStr
if not justLen then
if #tab<40 then
logStr=logStr.."\""..(ascii and tab:ascii(true) or tostring(tab)).."\"".."["..tab:hex().."]"
else
logStr=logStr..wrap..string.rep(tabb,layer-1).."\""..(ascii and tab:ascii(true) or tostring(tab)).."\""..wrap..string.rep(tabb,layer-1).."["..tab:hex().."]"
end
end
elseif type(tab)=="number" then
logStr=logStr..string.dec2hexF(tab)
else
logStr=logStr..tostring(tab)
end
return logStr
end
--nil and table compatible concat
function _M.concat(tab,splitter)
local rs={}
for i=1,#tab do
local v=tab[i]
v = v or "nil"
v=(type(v)=="table") and tostring(tab) or v
rs[#rs +1]=v
end
return table.concat(rs,splitter)
end
--add index to table, then you can use the index to get item
function _M.addIndex(tab,key)
local lookUps={}
for k,v in pairs(tab) do lookUps[v[key]]=v end
local index
local mt
repeat
mt=getmetatable(tab)
if mt then index=mt.__index tab=index end
until not index
setmetatable(tab,{__index=lookUps})
end
--imitate extends keyword in java
--copy parents method into subclass if not exists in subclass
--set __base as the base class
--limitation : any method add after extends method can't call sub class's override method
function _M.extends(o,parent)
assert(o,"object can not be null")
assert(parent,"parent can not be null")
for k,v in pairs(parent) do
if not o[k] then o[k]=v end
end
-- if not o.orderred then
-- setmetatable(o,{__index=parent})
-- else
-- local index=getmetatable(o).__index
-- setmetatable(index,{__index=parent})
-- end
o.__base=parent
return o
end
--order table: item key can not be Number
_M.OrderedTable={
new=function(self,o)
local o=o or {}
local k_i={}
local meta={
__index=self,
__newindex=function(t,k,v)
assert(type(k)~="number")
rawset(k_i,k,#t+1)
rawset(t,k,v)
rawset(t,#t+1,{key=k,value=v})
end,
__k_i=k_i
}
o.__orderred=true
return setmetatable(o,meta)
end,
getIndex=function(self,k)
assert(type(k)~="number")
local k_i=getmetatable(self).__k_i
return k_i[k]
end,
getKVTable=function(self)
local rs
for i,v in ipairs(self) do
rs[v.key]=v.value
end
return rs
end,
remove=function(self,k)
assert(type(k)~="number")
local k_i=getmetatable(self).__k_i
local removeIndex=k_i[k]
table.remove(self,removeIndex)
rawset(k_i,k,nil)
rawset(self,k,nil)
for i=removeIndex,#self do
k_i[self[i].key]=i
end
return
end
}
_M.unitTest={}
function _M.unitTest.OrderedTable()
local t=_M.OrderedTable:new()
t.A=1
t.B=2
t.C=3
t.D=4
t.E=5
print(_M.printTableF(t))
assert(t[1].key=="A",t[1].key)
assert(t[2].key=="B",t[2].key)
assert(t[3].key=="C",t[3].key)
assert(#t==5,#t)
t:remove("B")
print(_M.printTableF(t))
assert(t[1].key=="A",t[1].key)
assert(t[2].key=="C",t[2].key)
assert(t[3].key=="D",t[3].key)
assert(#t==4)
end
function _M.unitTest.concat()
local t={[1]=1,[2]="",[3]=nil,[4]="abc",[5]=4524354326}
assert(_M.concat(t,";")=="1;;nil;abc;4524354326",_M.concat(t,";"))
end
function _M.test()
for k,v in pairs(_M.unitTest) do
print("------------running "..k)
v()
print("------------"..k.." finished")
end
end
return _M |
storm_basic_attack = class({})
storm_ex_basic_attack = class({})
LinkLuaModifier("modifier_storm_basic_attack_cooldown", "abilities/heroes/storm/storm_basic_attack/modifier_storm_basic_attack_cooldown", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_storm_ex_basic_attack", "abilities/heroes/storm/storm_basic_attack/modifier_storm_ex_basic_attack", LUA_MODIFIER_MOTION_NONE)
function storm_basic_attack:GetCastPoint()
if IsServer() then
return self.BaseClass.GetCastPoint(self) + self:GetCaster():GetAttackAnimationPoint()
end
end
function storm_basic_attack:GetCooldown(iLevel)
if IsServer() then
local attacks_per_second = self:GetCaster():GetAttacksPerSecond()
local attack_speed = (1 / attacks_per_second)
return self.BaseClass.GetCooldown(self, self:GetLevel()) + attack_speed
end
end
function storm_basic_attack:GetCastAnimationCustom() return ACT_DOTA_ATTACK end
function storm_basic_attack:GetPlaybackRateOverride() return 1.5 end
function storm_basic_attack:GetCastPointSpeed() return 10 end
function storm_basic_attack:GetAnimationTranslate() return "overload" end
function storm_basic_attack:GetIntrinsicModifierName()
return "modifier_storm_basic_attack_cooldown"
end
function storm_basic_attack:OnSpellStart()
self:LaunchProjectile(self:GetCaster():GetOrigin(), CustomAbilitiesLegacy:GetCursorPosition(self))
end
function storm_basic_attack:LaunchProjectile(origin, point)
local caster = self:GetCaster()
local projectile_speed = self:GetSpecialValueFor("projectile_speed")
local projectile_direction = Direction2D(origin, point)
local mana_gain_pct = self:GetSpecialValueFor("mana_gain_pct")
local radius = self:GetSpecialValueFor("radius")
local fading_slow_duration = self:GetSpecialValueFor("fading_slow_duration")
local fading_slow_pct = self:GetSpecialValueFor("fading_slow_pct")
local is_charged = caster:FindModifierByName("modifier_storm_basic_attack_cooldown"):IsCooldownReady()
local projectile_particle = "particles/storm/storm_basic_attack.vpcf"
if is_charged then
projectile_particle = "particles/storm/storm_basic_attack_charged.vpcf"
end
local damage = caster:GetAverageTrueAttackDamage(caster)
local damage_table_aoe = {
damage = self:GetSpecialValueFor("aoe_damage"),
damage_type = DAMAGE_TYPE_PURE,
}
CustomEntitiesLegacy:ProjectileAttack(caster, {
bIsBasicAttack = true,
tProjectile = {
EffectName = projectile_particle,
vSpawnOrigin = origin + Vector(projectile_direction.x * 45, projectile_direction.y * 45, 96),
fDistance = self:GetSpecialValueFor("projectile_distance") ~= 0 and self:GetSpecialValueFor("projectile_distance") or self:GetCastRange(Vector(0,0,0), nil),
fStartRadius = 70,--self:GetSpecialValueFor("hitbox"),
Source = caster,
vVelocity = projectile_direction * projectile_speed,
UnitBehavior = PROJECTILES_DESTROY,
TreeBehavior = PROJECTILES_NOTHING,
WallBehavior = PROJECTILES_DESTROY,
GroundBehavior = PROJECTILES_NOTHING,
fGroundOffset = 0,
UnitTest = function(_self, unit) return unit:GetUnitName() ~= "npc_dummy_unit" and not CustomEntitiesLegacy:Allies(_self.Source, unit) end,
OnUnitHit = function(_self, unit)
CustomEntitiesLegacy:AttackWithBaseDamage(caster, {
hTarget = unit,
hAbility = self,
})
if _self.Source == caster then
if CustomEntitiesLegacy:ProvidesMana(unit) then
CustomEntitiesLegacy:GiveManaAndEnergyPercent(caster, mana_gain_pct, true)
end
if caster:HasModifier('modifier_storm_ultimate') then
local extra_mana_pct = mana_gain_pct * (caster:FindModifierByName('modifier_storm_ultimate'):GetManaMultiplier() - 1)
if CustomEntitiesLegacy:ProvidesMana(unit) then
CustomEntitiesLegacy:GiveManaPercent(caster, mana_gain_pct, true, true)
end
end
end
if is_charged then
local enemies = CustomEntitiesLegacy:FindUnitsInRadius(
_self.Source,
_self:GetPosition(),
radius,
DOTA_UNIT_TARGET_TEAM_ENEMY,
DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC,
DOTA_UNIT_TARGET_FLAG_NONE,
FIND_ANY_ORDER
)
damage_table_aoe.attacker = _self.Source
for _,enemy in pairs(enemies) do
enemy:AddNewModifier(_self.Source, self, "modifier_generic_fading_slow", {
duration = fading_slow_duration,
max_slow_pct = fading_slow_pct
})
damage_table_aoe.victim = enemy
ApplyDamage(damage_table_aoe)
end
local groundPosition = GetGroundPosition(_self:GetPosition(), _self.Source)
CreateRadiusMarker(_self.Source, groundPosition, radius, RADIUS_SCOPE_PUBLIC, 0.1)
ScreenShake(groundPosition, 100, 300, 0.45, 1000, 0, true)
EFX("particles/units/heroes/hero_void_spirit/voidspirit_overload_discharge.vpcf", PATTACH_WORLDORIGIN, _self.Source, {
cp0 = _self:GetPosition(),
release = true,
})
end
end,
OnFinish = function(_self, pos)
self:PlayEffectsOnFinish(pos)
end,
}
})
self:PlayEffectsOnCast(is_charged)
end
function storm_basic_attack:PlayEffectsOnCast(isCharged)
EmitSoundOn("Hero_StormSpirit.Attack", self:GetCaster())
if isCharged then
EmitSoundOn("Hero_StormSpirit.StaticRemnantExplode", self:GetCaster())
end
end
function storm_basic_attack:PlayEffectsOnFinish(pos)
local caster = self:GetCaster()
EmitSoundOnLocationWithCaster(pos, "Hero_StormSpirit.ProjectileImpact", caster)
local particle_cast = "particles/units/heroes/hero_stormspirit/stormspirit_base_attack_explosion.vpcf"
local effect_cast = ParticleManager:CreateParticle(particle_cast, PATTACH_ABSORIGIN, caster)
ParticleManager:SetParticleControl(effect_cast, 3, pos)
ParticleManager:ReleaseParticleIndex(effect_cast)
end
function storm_ex_basic_attack:OnSpellStart()
self:GetCaster():AddNewModifier(self:GetCaster(), self, 'modifier_storm_ex_basic_attack', {})
EmitSoundOn("Hero_StormSpirit.StaticRemnantPlant", self:GetCaster())
end
if IsClient() then require("wrappers/abilities") end
Abilities.Castpoint(storm_basic_attack)
Abilities.Castpoint(storm_ex_basic_attack)
|
require'tabline'.setup{}
|
local isLocating = false
local WAYPOINTLOC = { }
local DistToPoint = 0
local TRACKELEMENT = nil
function createWaypointLoc ( x, y, z )
TRACKELEMENT = nil
local px, py, pz = getElementPosition ( localPlayer )
local dist = getDistanceBetweenPoints2D ( px, py, x, y )
if ( dist <= 20 ) then
exports.NGMessages:sendClientMessage ( "You're only "..tostring(math.floor(dist)).." meters from that location.", 255, 255, 255 )
return false;
end
if ( isLocating ) then
waypointUnlocate ( )
end
isLocating = true
waypointBlip = exports.customblips:createCustomBlip ( x, y, 10, 10, "files/waypoint.png", 9999999999 )
WAYPOINTLOC = { x=x, y=y }
addEventHandler ( "onClientRender", root, onWaypointRender )
return true;
end
function waypointIsTracking ( )
return isLocating
end
local sx, sy = guiGetScreenSize ( )
local textY = sy/1.1
local waypointUpdateTick = getTickCount ( );
function waypointUnlocate ( )
if ( not isLocating ) then
return
end
WAYPOINTLOC = { }
DistToPoint = 0
isLocating = false
removeEventHandler ( "onClientRender", root, onWaypointRender )
exports.customblips:destroyCustomBlip ( waypointBlip )
TRACKELEMENT = nil
end
function setWaypointAttachedToElement ( element )
if ( not isElement ( element ) ) then return false end
TRACKELEMENT = element
return true
end
function onWaypointRender ( )
if ( not isLocating or not WAYPOINTLOC ) then
removeEventHandler ( "onClientRender", root, onWaypointRender )
return
end
local px, py, _ = getElementPosition ( localPlayer )
local x, y = WAYPOINTLOC.x, WAYPOINTLOC.y
if ( TRACKELEMENT ) then
if ( not isElement ( TRACKELEMENT ) ) then
waypointUnlocate ( )
exports.NGMessages:sendClientMessage ( "The player/thing you were tracking no longer exists.", 255, 0, 0 )
return
else
x, y, _ = getElementPosition ( TRACKELEMENT )
if ( getTickCount ( ) - waypointUpdateTick >= 2000 ) then
waypointUpdateTick = getTickCount ( );
exports.customblips:setCustomBlipPosition ( waypointBlip, x, y );
end
end
end
local dist = getDistanceBetweenPoints2D ( x, y, px, py )
if ( dist <= 15 ) then
waypointUnlocate ( )
exports.NGMessages:sendClientMessage ( "You have reached your destination!", 0, 255, 0 )
end
if ( isPedInVehicle ( localPlayer ) ) then
if ( textY > sy/1.2 ) then
textY = textY - 2
if ( textY < sy/1.2 ) then
textY = sy/1.2
end
end
else
if ( textY < sy/1.1 ) then
textY = textY + 2
if ( textY > sy/1.1 ) then
textY = sy/1.1
end
end
end
local dist = math.floor ( dist )
local t = "You're "..tostring(convertNumber(dist)).." meters from your destination"
dxDrawText ( t, 0, 0, sx/1.03+1, textY+1, tocolor ( 0, 0, 0, 255 ), 1, "default-bold", "right", "bottom" )
dxDrawText ( t, 0, 0, sx/1.03, textY, tocolor ( 255, 255, 255, 255 ), 1, "default-bold", "right", "bottom" )
end
function convertNumber ( number )
local formatted = number
while true do
formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
if ( k==0 ) then
break
end
end
return formatted
end |
-- s-300pmu2 92h6e tr (truck)
GT = {};
GT_t.ws = 0;
set_recursive_metatable(GT, GT_t.generic_stationary);
set_recursive_metatable(GT.chassis, GT_t.CH_t.STATIC);
GT.chassis.life = 4;
GT.visual.shape = "92n6_truck";
GT.visual.shape_dstr = "30h6_truck_d";
GT.visual.fire_pos[2] = 1;
GT.snd.radarRotation = "RadarRotation";
GT.sensor = {};
GT.sensor.max_range_finding_target = 270000;
GT.sensor.min_range_finding_target = 200;
GT.sensor.max_alt_finding_target = 90000;
GT.sensor.height = 9.63;
--Burning after hit
GT.visual.fire_size = 0.5; --relative burning size
GT.visual.fire_pos[1] = 0; -- center of burn at long axis shift(meters)
GT.visual.fire_pos[2] = 0; -- center of burn shift at vertical shift(meters)
GT.visual.fire_pos[3] = 0; -- center of burn at transverse axis shift(meters)
GT.visual.fire_time = 900; --burning time (seconds)
GT.CustomAimPoint = {0,1.5,0}
-- weapon systems
GT.WS = {};
GT.WS.maxTargetDetectionRange = 270000;
GT.WS.radar_type = 102;
-- We would like to engage targets using the radar without locking them up
-- But how can we do this?
-- It turns out that the beamWidth parameter of the LN object, when set to zero, will result in a target not
-- getting a lock or launch warning when engaged using command-guided (headValue = 8) missiles.
-- But then, we have a different problem: the radar has no detectable emissions at all!
-- To circumvent this issue, we can have the first WS on the unit be a dummy, which is not hooked up to the animations
-- and has an engagement area volume of zero (distanceMin = distanceMax)
-- The unit must also have the radar_rotation_type set to 0.
-- 0 tracker, dummy
local ws = GT_t.inc_ws();
GT.WS[ws] = {};
GT.WS[ws].pos = {0,5,0};
GT.WS[ws].angles = {
{math.rad(180), math.rad(-180), math.rad(-10), math.rad(80)},
};
GT.WS[ws].drawArgument1 = 0;
GT.WS[ws].omegaY = 0.174533;
GT.WS[ws].omegaZ = 0.174533;
GT.WS[ws].pidY = { p = 10, i = 0.1, d = 4};
GT.WS[ws].pidZ = { p = 10, i = 0.1, d = 4};
GT.WS[ws].LN = {};
GT.WS[ws].LN[1] = {};
GT.WS[ws].LN[1].depends_on_unit = {{{"S-300PMU1 54K6 cp"},},{{"S-300PS 54K6 cp"},},{{"S-300PMU2 54K6E2 cp"},},};
GT.WS[ws].LN[1].reactionTime = 0.1;
GT.WS[ws].LN[1].max_number_of_missiles_channels = 2;
GT.WS[ws].LN[1].type = 102;
GT.WS[ws].LN[1].distanceMin = 2000;
GT.WS[ws].LN[1].distanceMax = 270000;
GT.WS[ws].LN[1].reflection_limit = 0.02;
GT.WS[ws].LN[1].ECM_K = 0.4;
GT.WS[ws].LN[1].min_trg_alt = 25;
GT.WS[ws].LN[1].max_trg_alt = 90000;
GT.WS[ws].LN[1].beamWidth = math.rad(90);
-- "The S-300PMU-2 is referred in the West as SA-20B Gargoyle. The systems' fire control radar can detect 100 targets, track and engage 36 of them and guide 72 missiles.
-- It is worth noting that earlier radars of the S-300 family could simultaneously engage only 6 targets and guide 12 missiles."
for i = 1,35 do -- 35 tracker's
ws = GT_t.inc_ws();
GT.WS[ws] = {}
GT.WS[ws].base = 1
GT.WS[ws].pos = {0,0,0}
GT.WS[ws].angles = {
{math.rad(45), math.rad(-45), math.rad(-10), math.rad(80)},
};
GT.WS[ws].omegaY = 3
GT.WS[ws].omegaZ = 3
GT.WS[ws].LN = {}
GT.WS[ws].LN[1] = {}
set_recursive_metatable(GT.WS[ws].LN[1], GT.WS[1].LN[1])
end --for
GT.Name = "S-300PMU2 92H6E tr";
GT.DisplayName = _("SAM SA-20B S-300PMU2 Grave Stone(truck) TR");
GT.DisplayNameShort = _("SA-20B TR");
GT.Rate = 20;
GT.Sensors = { RADAR = "S-300PMU2 92H6E tr", };
GT.DetectionRange = GT.sensor.max_range_finding_target;
GT.ThreatRange = 0;
GT.mapclasskey = "P0091000083";
GT.attribute = {wsType_Ground,wsType_SAM,wsType_Radar,V_40B6M,
"LR SAM",
"SAM TR",
"RADAR_BAND1_FOR_ARM",
"CustomAimPoint",
};
GT.category = "Air Defence";
GT.tags = { "Air Defence", "Tracking Radar" };
|
-- Ctrl-Q in conemu to reload Clink Lua scripts
-- Clink match generators: https://github.com/mridgers/clink/blob/master/docs/clink.md#user-content-match-generators
-- Strings: http://lua-users.org/wiki/StringLibraryTutorial
-- Patterns: http://lua-users.org/wiki/PatternsTutorial
-- Escaping: http://www.lua.org/pil/20.2.html
-- local: http://www.lua.org/pil/4.2.html
-- git commands which will autocomplete branch names after them:
local git_commands = {"checkout", "co", "merge", "branch -d", "branch -D"}
function git_checkout_match_generator(text, first, last)
local commandLine = rl_state.line_buffer
--print("git_checkout_match_generator", text, first, last, "commandLine:", commandLine)--debug
-- match "git rebase" parameters
if commandLine:find("git rebase ", 1, true) == 1 then
local matchedRebaseParam = false
for _,rebaseParam in pairs({"--continue", "--skip", "--abort"}) do
if rebaseParam:find(text, 1, true) then
clink.add_match(rebaseParam)
matchedRebaseParam = true
end
end
if matchedRebaseParam then
return true
end
end
local matchedCommand = false
for _,command in pairs(git_commands) do
local commandFirst, commandLast = commandLine:find("git " .. command .. " ", 1, true) -- use plain-text find, so I don't have to escape "-" in the list of commands above
if commandFirst == 1 then -- the command must start at the beginning of the line (and I couldn't just use ^ in the pattern, since I used plain-text find)
matchedCommand = true
break
end
end
local matchedBranches = false
if matchedCommand then
for line in io.popen("git branch -a 2>nul"):lines() do
local branch = line:match("[%* ] (.+)$")
if not branch:find("HEAD", 1, true) then
branch = string.gsub(branch, "remotes/origin/", "")
if branch:find(text, 1, true) then
matchedBranches = true
clink.add_match(branch)
end
end
end
end
return matchedBranches
end
clink.register_match_generator(git_checkout_match_generator, 10) |
function widget:GetInfo()
return {
name = "Unit Stats",
desc = "Shows detailed unit stats",
author = "Niobium + Doo",
date = "Jan 11, 2009",
version = 1.7,
license = "GNU GPL, v2 or later",
layer = -9999999999,
enabled = true, -- loaded by default?
}
end
include("keysym.h.lua")
----v1.7 by Doo changes
-- Reverted "Added beamtime to oRld value to properly count dps of BeamLaser weapons" because reload starts at the beginning of the beamtime
-- Reduced the "minimal" reloadTime to properly calculate dps for low reloadtime weapons
-- Hid range from gui for explosion (death/selfd) as it is irrelevant.
----v1.6 by Doo changes
-- Fixed crashing when hovering some enemy units
----v1.5 by Doo changes
-- Fixed some issues with the add of BeamTime values
-- Added a 1/30 factor to stockpiling weapons (seems like the lua wDef.stockpileTime is in frames while the weaponDefs uses seconds) Probably the 1/30 value in older versions wasnt a "min reloadtime" but the 1/30 factor for stockpile weapons with a typo
----v1.4 by Doo changes
-- Added beamtime to oRld value to properly count dps of BeamLaser weapons
---- v1.3 changes
-- Fix for 87.0
-- Added display of experience effect (when experience >25%)
---- v1.2 changes
-- Fixed drains for burst weapons (Removed 0.125 minimum)
-- Show remaining costs for units under construction
---- v1.1 changes
-- Added extra text to help explain numbers
-- Added grouping of duplicate weapons
-- Added sonar radius
-- Fixed radar/jammer detection
-- Fixed stockpiling unit drains
-- Fixed turnrate/acceleration scale
-- Fixed very low reload times
------------------------------------------------------------------------------------
-- Globals
------------------------------------------------------------------------------------
local fontSize = 13
local useSelection = true
local customFontSize = 13
local textDistance = 0
local cX, cY
local vsx, vsy = gl.GetViewSizes()
local widgetScale = (0.60 + (vsx*vsy / 5000000))
local xOffset = (32 + (fontSize*0.9))*widgetScale
local yOffset = -((32 - (fontSize*0.9))*widgetScale)
local DAMAGE_PERIOD ,weaponInfo = VFS.Include('LuaRules/Configs/area_damage_defs.lua', nil, VFS.RAW_FIRST)
local oldUnitpicsDir = LUAUI_DIRNAME.."Images/oldunitpics/"
local OtaIconExist = {}
local onlytarget = {}
for i=1,#UnitDefs do
if VFS.FileExists(oldUnitpicsDir..UnitDefs[i].name..'.png') then
OtaIconExist[i] = oldUnitpicsDir..UnitDefs[i].name..'.png'
--Spring.Echo("Icon Path ",oldUnitpicsDir..UnitDefs[i].name..'.png')
end
end
local pos = nil
local dummyUnitID = nil
local dummyRange = {}
local modConfig, colorConfig = include("Configs/defensive_range_defs.lua")
local currentMod = string.upper(Game.modShortName or "")
local pplants = {
["aafus"] = true,
["talon_afus"] = true,
["talon_ckfus"] = true,
["talon_advsolar"] = true,
["talon_sfus"] = true,
["talon_efus"] = true,
["talon_ufus"] = true,
["talon_mohogeo"] = true,
["talon_pyroclastic"] = true,
["afusionplant"] = true,
["amgeo"] = true,
["armadvsol"] = true,
["armfor"] = true,
["armfus"] = true,
["armgeo"] = true,
["armgmm"] = true,
["armsolar"] = true,
["armtide"] = true,
["armuwfus"] = true,
["armuwfus1"] = true,
["armwin"] = true,
["cafus"] = true,
["cfusionplant"] = true,
["cmgeo"] = true,
["coradvsol"] = true,
["corbhmth"] = true,
["corfus"] = true,
["corgeo"] = true,
["corsolar"] = true,
["talon_solar"] = true,
["cortide"] = true,
["talon_tide"] = true,
["talon_tide1"] = true,
["talon_uwfus"] = true,
["coruwfus"] = true,
["corwin"] = true,
["talon_win"] = true,
["talon_win1"] = true,
["crnns"] = true,
["tlladvsolar"] = true,
["tllatidal"] = true,
["tllcoldfus"] = true,
["tllgeo"] = true,
["talon_geo"] = true,
["tllmedfusion"] = true,
["tllmegacoldfus"] = true,
["tllmohogeo"] = true,
["tllsolar"] = true,
["tlltide"] = true,
["tlluwfusion"] = true,
["tllwin"] = true,
["tllwin1"] = true,
["corawin"] = true,
["armawin"] = true,
["coratidal"] = true,
["armatidal"] = true,
["armlightfus"] = true,
["armuwlightfus"] = true,
["corlightfus"] = true,
["coruwlightfus"] = true,
["armgen"] = true,
["corgen"] = true,
["tllgen"] = true,
["talon_gen"] = true,
["corgeo_mini"] = true,
["armgeo_mini"] = true,
["tllgeo_mini"] = true,
["talon_geo_mini"] = true,
["armsolar"] = true,
["corsolar"] = true,
["crnns"] = true,
["tllsolar"] = true,
["tlladvsolar"] = true,
["armefus"] = true,
["corefus"] = true,
["tllefus"] = true,
["tllgeo_armored"] = true,
--T5
["corufus"] = true,
["armufus"] = true,
["tllufus"] = true,
["talon_ufus"] = true,
--Gok
["gok_solar"] = true,
["gok_advsolar"] = true,
["gok_fus"] = true,
["gok_gen"] = true,
["gok_geo_mini"] = true,
["gok_geo"] = true,
--["gok_gen"] = true,
}
local tidalStrength = Game.tidal
local windMin = Game.windMin
local windMax = Game.windMax
------------------------------------------------------------------------------------
-- Speedups
------------------------------------------------------------------------------------
local bgcorner = "LuaUI/Images/bgcorner.png"
local white = '\255\255\255\255'
local grey = '\255\190\190\190'
local green = '\255\1\255\1'
local yellow = '\255\255\255\1'
local orange = '\255\255\128\1'
local blue = '\255\128\128\255'
local metalColor = '\255\196\196\255' -- Light blue
local energyColor = '\255\255\255\128' -- Light yellow
local buildColor = '\255\128\255\128' -- Light green
local simSpeed = Game.gameSpeed
local max = math.max
local floor = math.floor
local ceil = math.ceil
local format = string.format
local char = string.char
local glColor = gl.Color
local glText = gl.Text
local glTexture = gl.Texture
local glRect = gl.Rect
local glTexRect = gl.TexRect
local spGetMyTeamID = Spring.GetMyTeamID
local spGetTeamResources = Spring.GetTeamResources
local spGetTeamInfo = Spring.GetTeamInfo
local spGetPlayerInfo = Spring.GetPlayerInfo
local spGetTeamColor = Spring.GetTeamColor
local spGetModKeyState = Spring.GetModKeyState
local spGetMouseState = Spring.GetMouseState
local spTraceScreenRay = Spring.TraceScreenRay
local spGetSelectedUnits = Spring.GetSelectedUnits
local spGetSelectedUnitsCount = Spring.GetSelectedUnitsCount
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitExp = Spring.GetUnitExperience
local spGetUnitHealth = Spring.GetUnitHealth
local spGetUnitTeam = Spring.GetUnitTeam
local spGetUnitExperience = Spring.GetUnitExperience
local spGetUnitSensorRadius = Spring.GetUnitSensorRadius
local spGetUnitWeaponState = Spring.GetUnitWeaponState
local uDefs = UnitDefs
local wDefs = WeaponDefs
local triggerKey = KEYSYMS.SPACE
local myTeamID = Spring.GetMyTeamID
local spGetTeamRulesParam = Spring.GetTeamRulesParam
local spGetTooltip = Spring.GetCurrentTooltip
local vsx, vsy = Spring.GetViewGeometry()
local maxWidth = 0
local textBuffer = {}
local textBufferCount = 0
local spec = Spring.GetSpectatingState()
------------------------------------------------------------------------------------
-- Functions
------------------------------------------------------------------------------------
function RectRound(px,py,sx,sy,cs)
local px,py,sx,sy,cs = math.floor(px),math.floor(py),math.floor(sx),math.floor(sy),math.floor(cs)
gl.Rect(px+cs, py, sx-cs, sy)
gl.Rect(sx-cs, py+cs, sx, sy-cs)
gl.Rect(px+cs, py+cs, px, sy-cs)
gl.Texture(bgcorner)
gl.TexRect(px, py+cs, px+cs, py) -- top left
gl.TexRect(sx, py+cs, sx-cs, py) -- top right
gl.TexRect(px, sy-cs, px+cs, sy) -- bottom left
gl.TexRect(sx, sy-cs, sx-cs, sy) -- bottom right
gl.Texture(false)
end
local function DrawText(t1, t2)
textBufferCount = textBufferCount + 1
textBuffer[textBufferCount] = {t1,t2,cX,cY}
cY = cY - fontSize
maxWidth = max(maxWidth, (gl.GetTextWidth(t1)*fontSize), (gl.GetTextWidth(t2)*fontSize)+(fontSize*6.5+textDistance))
end
local function DrawTextBuffer()
local num = #textBuffer
for i=1, num do
glText(textBuffer[i][1], textBuffer[i][3], textBuffer[i][4], fontSize, "o")
glText(textBuffer[i][2], textBuffer[i][3] + (fontSize*6.5)+textDistance, textBuffer[i][4], fontSize, "o")
end
end
local function GetTeamColorCode(teamID)
if not teamID then return "\255\255\255\255" end
local R, G, B = spGetTeamColor(teamID)
if not R then return "\255\255\255\255" end
R = floor(R * 255)
G = floor(G * 255)
B = floor(B * 255)
if (R < 11) then R = 11 end -- Note: char(10) terminates string
if (G < 11) then G = 11 end
if (B < 11) then B = 11 end
return "\255" .. char(R) .. char(G) .. char(B)
end
local function GetTeamName(teamID)
if not teamID then return 'Error:NoTeamID' end
local _, teamLeader = spGetTeamInfo(teamID)
if not teamLeader then return 'Error:NoLeader' end
local leaderName = spGetPlayerInfo(teamLeader)
return leaderName or 'Error:NoName'
end
local guishaderEnabled = false -- not a config var
function RemoveGuishader()
if guishaderEnabled and WG['guishader_api'] ~= nil then
WG['guishader_api'].RemoveRect('unit_stats_title')
WG['guishader_api'].RemoveRect('unit_stats_data')
guishaderEnabled = false
end
end
local darkOpacity = 0
function SetOpacity(dark,light)
darkOpacity = dark
end
------------------------------------------------------------------------------------
-- Code
------------------------------------------------------------------------------------
function widget:Initialize()
widgetHandler:RegisterGlobal('SetOpacity_Unit_Stats', SetOpacity)
if not WG["background_opacity_custom"] then
WG["background_opacity_custom"] = {0,0,0,0.5}
end
init()
end
function widget:Shutdown()
widgetHandler:DeregisterGlobal('SetOpacity_Unit_Stats', SetOpacity)
RemoveGuishader()
end
function widget:PlayerChanged()
spec = Spring.GetSpectatingState()
end
function init()
vsx, vsy = gl.GetViewSizes()
widgetScale = (0.60 + (vsx*vsy / 5000000))
fontSize = customFontSize * widgetScale
bgcornerSize = fontSize*0.45
bgpadding = fontSize*0.9
xOffset = (32 + bgpadding)*widgetScale
yOffset = -((32 + bgpadding)*widgetScale)
end
function widget:ViewResize(x,y)
init()
end
function widget:DrawScreen()
local alt, ctrl, meta, shift = spGetModKeyState()
if not meta then
--WG.hoverID = nil
dummyUnitID = nil
RemoveGuishader()
return
end
local mx, my = spGetMouseState()
local uID
local rType, unitID = spTraceScreenRay(mx, my)
if rType == 'unit' then
uID = unitID
end
--if spec and useSelection then
-- local selUnits = spGetSelectedUnits()
-- if #selUnits >= 1 then
-- uID = selUnits[1]
-- end
--end
local useHoverID = false
local morphID = false
dummyUnitID = nil
local _, activeID = Spring.GetActiveCommand()
local text = Spring.GetCurrentTooltip()
local expMorphPat = "UnitDefID (%d+)\n"
local morphDefID = tonumber(text:match(expMorphPat)) or nil
if not activeID then activeID = 0 end
if not uID then
if morphDefID then
uID = nil
useHoverID = false
morphID = true
local selUnits = spGetSelectedUnits()
if #selUnits >= 1 then
dummyUnitID = selUnits[1]
end
elseif (not WG.hoverID) and not (activeID < 0) then
RemoveGuishader() return
elseif WG.hoverID and WG.hoverID < 0 and not (activeID < 0) then
uID = nil
useHoverID = true
morphID = false
elseif activeID < 0 then
uID = nil
useHoverID = false
morphID = false
end
end
local useExp = ctrl
local uDefID = (uID and spGetUnitDefID(uID)) or (useHoverID and -WG.hoverID) or (UnitDefs[-activeID] and -activeID)
or (morphID and morphDefID)
if not uDefID then
RemoveGuishader() return
end
if uID then
textDistance = 0
local uDef = uDefs[uDefID]
local uCurHp, uMaxHp, _, _, buildProg = spGetUnitHealth(uID)
local uTeam = spGetUnitTeam(uID)
local _, xp = Spring.GetUnitExperience(uID)
maxWidth = 0
cX = mx + xOffset
cY = my + yOffset
cYstart = cY
local titleFontSize = fontSize*1.12
local cornersize = ceil(bgpadding*0.21)
cY = cY - 2 * titleFontSize
textBuffer = {}
textBufferCount = 0
if(WG.energyConversion) then
local makerTemp = WG.energyConversion.convertCapacities[uDefID]
local curAvgEffi = spGetTeamRulesParam(myTeamID(), 'mmAvgEffi')
local avgCR = 0.015
if(makerTemp) then
DrawText(orange .. "Metal maker properties", '')
DrawText("M- .:", makerTemp.c)
DrawText("M-Effi.:", format('%.2f m / 1000 e', makerTemp.e * 1000))
cY = cY - fontSize
end
if pplants[uDef.name] then
-- Powerplants
DrawText(orange .. "Powerplant properties", '')
DrawText("CR is metal maker conversion rate", '')
local totalEOut = uDef.energyMake
if (uDef.tidalGenerator > 0 and tidalStrength > 0) then
local mult = 1 -- DEFAULT
if uDef.customParams then
mult = uDef.customParams.energymultiplier or mult
end
totalEOut = totalEOut +(tidalStrength * mult)
end
if (uDef.windGenerator > 0) then
local mult = 1 -- DEFAULT
if uDef.customParams then
mult = uDef.customParams.energymultiplier or mult
end
local unitWindMin = math.min(windMin, uDef.windGenerator)
local unitWindMax = math.min(windMax, uDef.windGenerator)
totalEOut = totalEOut + (((unitWindMin + unitWindMax) / 2 ) * mult)
end
DrawText("Avg. E-Out.:", totalEOut)
DrawText("M-Cost.:", uDef.metalCost)
DrawText("Avg-Effi.:", format('%.2f%% e / (m + e * avg. CR) ', totalEOut * 100 / (uDef.metalCost + uDef.energyCost * avgCR)))
if(curAvgEffi>0) then
DrawText("Curr-Effi.:", format('%.2f%% e / (m + e * curr. CR) ', totalEOut * 100 / (uDef.metalCost + uDef.energyCost * curAvgEffi)))
end
cY = cY - fontSize
end
if not (#uDef.weapons>0) or uDef.isBuilding or pplants[uDef.name] then
if ((uDef.extractsMetal and uDef.extractsMetal > 0) or (uDef.metalMake and uDef.metalMake > 0) or (uDef.energyMake and uDef.energyMake>0) or (uDef.tidalGenerator and uDef.tidalGenerator > 0) or (uDef.windGenerator and uDef.windGenerator > 0)) then
-- Powerplants
--DrawText(metalColor .. "Total metal generation efficiency", '')
DrawText(metalColor .. "Estimated time of recovering 100% of cost:", '')
local totalMOut = uDef.metalMake or 0
local totalEOut = uDef.energyMake or 0
if (uDef.extractsMetal and uDef.extractsMetal > 0) then
local metalExtractor = {inc = 0, out = 0, passed= false}
local tooltip = spGetTooltip()
string.gsub(tooltip, 'Metal: ....%d+%.%d', function(x) string.gsub(x, "%d+%.%d", function(y) metalExtractor.inc = tonumber(y); end) end)
string.gsub(tooltip, 'Energy: ....%d+%.%d+..../....-%d+%.%d+', function(x) string.gsub(x, "%d+%.%d", function(y) if (metalExtractor.passed) then metalExtractor.out = tonumber(y); else metalExtractor.passed = true end; end) end)
totalMOut = totalMOut + metalExtractor.inc
totalEOut = totalEOut - metalExtractor.out
end
if (uDef.tidalGenerator > 0 and tidalStrength > 0) then
local mult = 1 -- DEFAULT
if uDef.customParams then
mult = uDef.customParams.energymultiplier or mult
end
totalEOut = totalEOut + tidalStrength * mult
end
if (uDef.windGenerator > 0) then
local mult = 1 -- DEFAULT
if uDef.customParams then
mult = uDef.customParams.energymultiplier or mult
end
local unitWindMin = math.min(windMin, uDef.windGenerator)
local unitWindMax = math.min(windMax, uDef.windGenerator)
totalEOut = totalEOut + ((unitWindMin + unitWindMax) / 2) * mult
end
if(totalEOut * avgCR + totalMOut > 0) then
local avgSec = (uDef.metalCost + uDef.energyCost * avgCR)/(totalEOut * avgCR + totalMOut)
local currSec = (uDef.metalCost + uDef.energyCost * curAvgEffi)/(totalEOut * curAvgEffi + totalMOut)
DrawText('Average: ', format('%i sec (%i min %i sec)', avgSec, avgSec/60, avgSec%60))
if(curAvgEffi>0) then
DrawText('Current: ', format('%i sec (%i min %i sec)', currSec, currSec/60, currSec%60))
end
else
DrawText('Average: ', "Unknown")
end
cY = cY - fontSize
end
end
end
------------------------------------------------------------------------------------
-- Units under construction
------------------------------------------------------------------------------------
if buildProg and buildProg < 1 then
local myTeamID = spGetMyTeamID()
local mCur, mStor, mPull, mInc, mExp, mShare, mSent, mRec = spGetTeamResources(myTeamID, 'metal')
local eCur, eStor, ePull, eInc, eExp, eShare, eSent, eRec = spGetTeamResources(myTeamID, 'energy')
local mTotal = uDef.metalCost
local eTotal = uDef.energyCost
local buildRem = 1 - buildProg
local mRem = mTotal * buildRem
local eRem = eTotal * buildRem
local mEta = (mRem - mCur) / (mInc + mRec)
local eEta = (eRem - eCur) / (eInc + eRec)
DrawText("Prog:", format("%d%%", 100 * buildProg))
DrawText("Metal:", format("%d / %d (" .. yellow .. "%d" .. white .. ", %ds)", mTotal * buildProg, mTotal, mRem, mEta))
DrawText("Energy:", format("%d / %d (" .. yellow .. "%d" .. white .. ", %ds)", eTotal * buildProg, eTotal, eRem, eEta))
--DrawText("MaxBP:", format(white .. '%d', buildRem * uDef.buildTime / math.max(mEta, eEta)))
cY = cY - fontSize
end
------------------------------------------------------------------------------------
-- Generic information, cost, move, class
------------------------------------------------------------------------------------
--DrawText('Height:', uDefs[spGetUnitDefID(uID)].height)
DrawText("Cost:", format(metalColor .. '%d' .. white .. ' / ' ..
energyColor .. '%d' .. white .. ' / ' ..
buildColor .. '%d', uDef.metalCost, uDef.energyCost, uDef.buildTime)
)
if not (uDef.isBuilding or uDef.isFactory) then
if not Spring.GetUnitMoveTypeData(uID) then
DrawText("Move:", format("%.1f / %.1f / %.0f (Speed / Accel / Turn)", uDef.speed, 900 * uDef.maxAcc, simSpeed * uDef.turnRate * (180 / 32767)))
else
local mData = Spring.GetUnitMoveTypeData(uID)
local mSpeed = mData.maxSpeed or uDef.speed
local mAccel = mData.accRate or uDef.maxAcc
local mTurnRate = mData.baseTurnRate or uDef.turnRate
DrawText("Move:", format("%.1f / %.1f / %.0f (Speed / Accel / Turn)", mSpeed, 900 * mAccel, simSpeed * mTurnRate * (180 / 32767)))
end
end
cY = cY - fontSize
DrawText('Build:', yellow .. uDef.buildSpeed)
cY = cY - fontSize
------------------------------------------------------------------------------------
-- Sensors and Jamming
------------------------------------------------------------------------------------
local losRadius = spGetUnitSensorRadius(uID, 'los') or 0
local airLosRadius = spGetUnitSensorRadius(uID, 'airLos') or 0
local radarRadius = spGetUnitSensorRadius(uID, 'radar') or 0
local sonarRadius = spGetUnitSensorRadius(uID, 'sonar') or 0
local jammingRadius = spGetUnitSensorRadius(uID, 'radarJammer') or 0
local sonarJammingRadius = spGetUnitSensorRadius(uID, 'sonarJammer') or 0
local seismicRadius = spGetUnitSensorRadius(uID, 'seismic') or 0
DrawText('Los:', losRadius .. (airLosRadius > losRadius and format(' (AirLos: %d)', airLosRadius) or ''))
if radarRadius > 0 then DrawText('Radar:', '\255\77\255\77' .. radarRadius) end
if sonarRadius > 0 then DrawText('Sonar:', '\255\128\128\255' .. sonarRadius) end
if jammingRadius > 0 then DrawText('Jam:' , '\255\255\77\77' .. jammingRadius) end
if sonarJammingRadius > 0 then DrawText('Sonar Jam:', '\255\255\77\77' .. sonarJammingRadius) end
if seismicRadius > 0 then DrawText('Seis:' , '\255\255\26\255' .. seismicRadius) end
if uDef.stealth then DrawText("Other:", "Stealth") end
cY = cY - fontSize
local uExp = spGetUnitExperience(uID)
------------------------------------------------------------------------------------
-- Armor
------------------------------------------------------------------------------------
DrawText("Armor:", "class " .. Game.armorTypes[uDef.armorType or 0] or '???')
local _, spMaxHP = Spring.GetUnitHealth(uID)
local maxHP = spMaxHP or uDef.health
if ctrl then
maxHP = uMaxHp or '???'
end
if uExp ~= 0 then
if uMaxHp then
DrawText("Exp:", format("+%d%% health", (uMaxHp/uDef.health-1)*100))
else
DrawText("Exp: unknown",'\255\255\77\77')
end
end
DrawText("Open:", format("maxHP: %d", maxHP) )
local _, armoredMultiple = Spring.GetUnitArmored(uID)
if armoredMultiple and armoredMultiple ~= 1 then
DrawText("Closed:", format(" +%d%%, maxHP: %d", (1/armoredMultiple-1) *100,maxHP/armoredMultiple))
elseif uDef.armoredMultiple ~= 1 then
DrawText("Closed:", format(" +%d%%, maxHP: %d", (1/uDef.armoredMultiple-1) *100,maxHP/uDef.armoredMultiple))
end
cY = cY - fontSize
------------------------------------------------------------------------------------
-- Weapons
------------------------------------------------------------------------------------
local wepCounts = {} -- wepCounts[wepDefID] = #
local wepsCompact = {} -- uWepsCompact[1..n] = wepDefID
local uWeps = uDef.weapons
local weaponNums = {}
for i = 1, #uWeps do
local wDefID = uWeps[i].weaponDef
local wCount = wepCounts[wDefID]
if wCount then
wepCounts[wDefID] = wCount + 1
else
wepCounts[wDefID] = 1
wepsCompact[#wepsCompact + 1] = wDefID
weaponNums[#wepsCompact] = i
end
end
local selfDWeaponID = WeaponDefNames[uDef.selfDExplosion].id
local deathWeaponID = WeaponDefNames[uDef.deathExplosion].id
local selfDWeaponIndex
local deathWeaponIndex
if shift then
wepCounts = {}
wepsCompact = {}
wepCounts[selfDWeaponID] = 1
wepCounts[deathWeaponID] = 1
deathWeaponIndex = #wepsCompact+1
wepsCompact[deathWeaponIndex] = deathWeaponID
selfDWeaponIndex = #wepsCompact+1
wepsCompact[selfDWeaponIndex] = selfDWeaponID
end
for i = 1, #wepsCompact do
local wDefId = wepsCompact[i]
local uWep = wDefs[wDefId]
if uWep.range > 0 and not uWep.name:find("teleport",1,true) then
local oBurst = uWep.salvoSize * uWep.projectiles
local oRld = max(0.00000000001,uWep.stockpile == true and uWep.stockpileTime/30 or uWep.reload)
if useExp and not ((uWep.stockpile and uWep.stockpileTime)) then
oRld = spGetUnitWeaponState(uID,weaponNums[i] or -1,"reloadTime") or oRld
end
local wepCount = wepCounts[wDefId]
local typeName = uWep.type
local wpnName = uWep.description
if i == deathWeaponIndex then
wpnName = "Death explosion"
oRld = 1
elseif i == selfDWeaponIndex then
wpnName = "Self Destruct"
oRld = uDef.selfDCountdown
end
if wepCount > 1 then
DrawText("Weap:", format(yellow .. "%dx" .. white .. " %s", wepCount, wpnName))
else
DrawText("Weap:", wpnName)
end
if uWep.coverageRange and uWep.stockpile then
DrawText("Anti:", format("%d Interceptor Range", uWep.coverageRange))
end
if uWep.coverageRange and uWep.interceptor == 16 then
DrawText("MDS:", format("%d Interceptor Range", uWep.coverageRange))
end
if uWep.coverageRange and uWep.interceptor == 4 then
DrawText("MDS:", format("%d Interceptor Range", uWep.coverageRange))
end
if uWep.targetable == 16 then
DrawText("MDS:","Is Targetable", '')
end
local reload = spGetUnitWeaponState(uID,weaponNums[i] or -1,"reloadTime") or uWep.reload
local accuracy = spGetUnitWeaponState(uID,weaponNums[i] or -1,"accuracy") or uWep.accuracy
local moveError = spGetUnitWeaponState(uID,weaponNums[i] or -1,"targetMoveError") or uWep.targetMoveError
local reloadBonus = reload ~= 0 and (uWep.reload/reload-1) or 0
local accuracyBonus = accuracy ~= 0 and (uWep.accuracy/accuracy-1) or 0
local moveErrorBonus = moveError ~= 0 and (uWep.targetMoveError/moveError-1) or 0
local range = spGetUnitWeaponState(uID,weaponNums[i] or -1,"range") or uWep.range
local rangeBonus = range ~= 0 and (range/uWep.range-1) or 0
if uExp ~= 0 then
DrawText("Exp:", format("+%d%% accuracy, +%d%% aim, +%d%% firerate, +%d%% range", accuracyBonus*100, moveErrorBonus*100, reloadBonus*100, rangeBonus*100 ))
end
local infoText = ""
if wpnName == "Death explosion" or wpnName == "Self Destruct" then
infoText = format("%d aoe, %d%% edge", uWep.damageAreaOfEffect, 100 * uWep.edgeEffectiveness)
else
infoText = format("%d range, %d aoe, %d%% edge", useExp and range or uWep.range, uWep.damageAreaOfEffect, 100 * uWep.edgeEffectiveness)
end
if uWep.damages.paralyzeDamageTime > 0 then
infoText = format("%s, %ds paralyze", infoText, uWep.damages.paralyzeDamageTime)
end
if uWep.damages.impulseBoost > 0 then
infoText = format("%s, %d impulse", infoText, uWep.damages.impulseBoost*100)
end
if uWep.damages.craterBoost > 0 then
infoText = format("%s, %d crater", infoText, uWep.damages.craterBoost*100)
end
DrawText("Info:", infoText)
local defaultDamage = uWep.damages[0]
for cat=0, #uWep.damages do
local oDmg = uWep.damages[cat]
local catName = Game.armorTypes[cat]
if catName and oDmg and (oDmg ~= defaultDamage or cat == 0) then
local dmgString
if oBurst > 1 then
dmgString = format(yellow .. "%d (x%d)" .. white .. " / " .. yellow .. "%.2f\s" .. white .. " = " .. yellow .. "%.2f \d\p\s", oDmg, oBurst, oRld, oBurst * oDmg / oRld)
else
dmgString = format(yellow .. "%d" .. white .. " / " .. yellow .. "%.2f\s" .. white .. " = " .. yellow .. "%.2f \d\p\s", oDmg, oRld, oDmg / oRld)
end
if wepCount > 1 then
dmgString = dmgString .. white .. " (Each)"
end
dmgString = dmgString .. white .. " (" .. catName .. ")"
DrawText("Dmg:", dmgString)
end
end
if uWep.metalCost > 0 or uWep.energyCost > 0 then
-- Stockpiling weapons are weird
-- They take the correct amount of resources overall
-- They take the correct amount of time
-- They drain ((simSpeed+2)/simSpeed) times more resources than they should (And the listed drain is real, having lower income than listed drain WILL stall you)
local drainAdjust = uWep.stockpile and (simSpeed+2)/simSpeed or 1
DrawText('Cost:', format(metalColor .. '%d' .. white .. ', ' ..
energyColor .. '%d' .. white .. ' = ' ..
metalColor .. '-%d' .. white .. ', ' ..
energyColor .. '-%d' .. white .. ' per second',
uWep.metalCost,
uWep.energyCost,
drainAdjust * uWep.metalCost / oRld,
drainAdjust * uWep.energyCost / oRld))
end
if (weaponInfo[wDefId]) then
local radius = weaponInfo[wDefId].radius
local damage = weaponInfo[wDefId].damage
local duration = weaponInfo[wDefId].duration
DrawText("Area Dmg:", format(white .. "%d aoe, %d max damage per second , %d seconds", radius, damage * 30 / DAMAGE_PERIOD, duration / 30 ))
end
cY = cY - fontSize
end
end
-- background
glColor(WG["background_opacity_custom"])
-- correct position when it goes below screen
if cY < 0 then
cYstart = cYstart - cY
local num = #textBuffer
for i=1, num do
textBuffer[i][4] = textBuffer[i][4] - (cY/2)
textBuffer[i][4] = textBuffer[i][4] - (cY/2)
end
cY = 0
end
-- correct position when it goes off screen
if cX + maxWidth+bgpadding+bgpadding > vsx then
local cXnew = vsx-maxWidth-bgpadding-bgpadding
local num = #textBuffer
for i=1, num do
textBuffer[i][3] = textBuffer[i][3] - ((cX-cXnew)/2)
textBuffer[i][3] = textBuffer[i][3] - ((cX-cXnew)/2)
end
cX = cXnew
end
-- title
local text = "\255\190\255\190" .. uDef.humanName .. " " .. grey .. uDef.name .. grey .. " #" .. uID .. " "..GetTeamColorCode(uTeam) .. GetTeamName(uTeam)
local iconHalfSize = titleFontSize*0.75
cornersize = 0
glColor(WG["background_opacity_custom"])
RectRound(cX-bgpadding+cornersize, cYstart-bgpadding+cornersize, cX+(gl.GetTextWidth(text)*titleFontSize)+iconHalfSize+iconHalfSize+bgpadding+(bgpadding/1.5)-cornersize, cYstart+(titleFontSize/2)+bgpadding-cornersize, bgcornerSize)
cornersize = ceil(bgpadding*0.21)
glColor(1,1,1,0.025)
RectRound(cX-bgpadding+cornersize, cYstart-bgpadding+cornersize, cX+(gl.GetTextWidth(text)*titleFontSize)+bgpadding-cornersize, cYstart+(titleFontSize/2)+bgpadding-cornersize, bgcornerSize)
if (WG['guishader_api'] ~= nil) then
guishaderEnabled = true
WG['guishader_api'].InsertRect(cX-bgpadding, cYstart-bgpadding, cX+(gl.GetTextWidth(text)*titleFontSize)+bgpadding, cYstart+(titleFontSize/2)+bgpadding, 'unit_stats_title')
end
-- icon
glColor(1,1,1,1)
if WG['OtaIcons'] and OtaIconExist[uDefID] then
gl.Texture(OtaIconExist[uDefID])
else
glTexture('#' .. uDefID)
end
glTexRect(cX, cYstart+cornersize-iconHalfSize, cX+iconHalfSize+iconHalfSize, cYstart+cornersize+iconHalfSize)
glTexture(false)
-- title text
glColor(1,1,1,1)
glText(text, cX+iconHalfSize+iconHalfSize+(bgpadding/1.5), cYstart, titleFontSize, "o")
-- stats
cornersize = 0
glColor(WG["background_opacity_custom"])
RectRound(floor(cX-bgpadding)+cornersize, ceil(cY+(fontSize/3)+bgpadding)+cornersize, ceil(cX+maxWidth+bgpadding)-cornersize, floor(cYstart-bgpadding)-cornersize, bgcornerSize)
cornersize = ceil(bgpadding*0.16)
glColor(1,1,1,0.025)
RectRound(floor(cX-bgpadding)+cornersize, ceil(cY+(fontSize/3)+bgpadding)+cornersize, ceil(cX+maxWidth+bgpadding)-cornersize, floor(cYstart-bgpadding)-cornersize, bgcornerSize)
DrawTextBuffer()
if (WG['guishader_api'] ~= nil) then
guishaderEnabled = true
WG['guishader_api'].InsertRect(cX-bgpadding, cY+(fontSize/3)+bgpadding, cX+maxWidth+bgpadding, cYstart-bgpadding, 'unit_stats_data')
end
else
local uDef = uDefs[uDefID]
local uMaxHp = uDef.health
local uTeam = Spring.GetMyTeamID()
maxWidth = 0
cX = mx + xOffset
cY = my + yOffset
cYstart = cY
local titleFontSize = fontSize*1.12
local cornersize = ceil(bgpadding*0.21)
cY = cY - 2 * titleFontSize
textBuffer = {}
textBufferCount = 0
------------------------------------------------------------------------------------
-- Generic information, cost, move, class
------------------------------------------------------------------------------------
--DrawText('Height:', uDefs[spGetUnitDefID(uID)].height)
DrawText("Cost:", format(metalColor .. '%d' .. white .. ' / ' ..
energyColor .. '%d' .. white .. ' / ' ..
buildColor .. '%d', uDef.metalCost, uDef.energyCost, uDef.buildTime)
)
if not (uDef.isBuilding or uDef.isFactory) then
DrawText("Move:", format("%.1f / %.1f / %.0f (Speed / Accel / Turn)", uDef.speed, 900 * uDef.maxAcc, simSpeed * uDef.turnRate * (180 / 32767)))
end
-- Buildoptions
cY = cY - fontSize
textDistance = customFontSize * 5
if (uDef.buildOptions and #uDef.buildOptions > 0) then
DrawText(orange .."Buildoption:",metalColor ..'Metal' .. white .. ' / ' .. energyColor .. 'Energy' .. white .. ' / ' ..
buildColor .. 'Build')
cY = cY - fontSize
for i=1, #uDef.buildOptions do
buildDefID = uDef.buildOptions[i]
local bDef = uDefs[buildDefID]
DrawText(bDef.humanName, format(metalColor .. '%d' .. white .. ' / ' ..
energyColor .. '%d' .. white .. ' / ' ..
buildColor .. '%d', bDef.metalCost, bDef.energyCost, bDef.buildTime))
end
end
cY = cY - fontSize
if uDef.buildSpeed > 0 then
DrawText('Build:', yellow .. uDef.buildSpeed)
end
cY = cY - fontSize
------------------------------------------------------------------------------------
-- Sensors and Jamming
------------------------------------------------------------------------------------
local losRadius = uDef.losRadius
local airLosRadius = uDef.airLosRadius
local radarRadius = uDef.radarRadius
local sonarRadius = uDef.sonarRadius
local jammingRadius = uDef.jammerRadius
local sonarJammingRadius = uDef.sonarJamRadius
local seismicRadius = uDef.seismicRadius
DrawText('Los:', losRadius .. (airLosRadius > losRadius and format(' (AirLos: %d)', airLosRadius) or ''))
if radarRadius > 0 then DrawText('Radar:', '\255\77\255\77' .. radarRadius) end
if sonarRadius > 0 then DrawText('Sonar:', '\255\128\128\255' .. sonarRadius) end
if jammingRadius > 0 then DrawText('Jam:' , '\255\255\77\77' .. jammingRadius) end
if sonarJammingRadius > 0 then DrawText('Sonar Jam:', '\255\255\77\77' .. sonarJammingRadius) end
if seismicRadius > 0 then DrawText('Seis:' , '\255\255\26\255' .. seismicRadius) end
if uDef.stealth then DrawText("Other:", "Stealth") end
cY = cY - fontSize
------------------------------------------------------------------------------------
-- Armor
------------------------------------------------------------------------------------
DrawText("Armor:", "class " .. Game.armorTypes[uDef.armorType or 0] or '???')
local maxHP = uDef.health
DrawText("Open:", format("maxHP: %d", maxHP) )
DrawText("Closed:", format(" +%d%%, maxHP: %d", (1/uDef.armoredMultiple-1) *100,maxHP/uDef.armoredMultiple))
cY = cY - fontSize
------------------------------------------------------------------------------------
-- Weapons
------------------------------------------------------------------------------------
local wepCounts = {} -- wepCounts[wepDefID] = #
local wepsCompact = {} -- uWepsCompact[1..n] = wepDefID
uWeps = uDef.weapons
local weaponNums = {}
local surface = nil
local air = nil
for i = 1, #uWeps do
surface = uWeps[i].onlyTargets["surface"]
air = uWeps[i].onlyTargets["vtol"]
local wDefID = uWeps[i].weaponDef
local wCount = wepCounts[wDefID]
if wCount then
wepCounts[wDefID] = wCount + 1
else
wepCounts[wDefID] = 1
wepsCompact[#wepsCompact + 1] = wDefID
weaponNums[#wepsCompact] = i
end
end
local selfDWeaponID = WeaponDefNames[uDef.selfDExplosion].id
local deathWeaponID = WeaponDefNames[uDef.deathExplosion].id
local selfDWeaponIndex
local deathWeaponIndex
if shift then
wepCounts = {}
wepsCompact = {}
wepCounts[selfDWeaponID] = 1
wepCounts[deathWeaponID] = 1
deathWeaponIndex = #wepsCompact+1
wepsCompact[deathWeaponIndex] = deathWeaponID
selfDWeaponIndex = #wepsCompact+1
wepsCompact[selfDWeaponIndex] = selfDWeaponID
end
for i = 1, #wepsCompact do
local wDefId = wepsCompact[i]
local uWep = wDefs[wDefId]
if uWep.range > 0 and not uWep.name:find("teleport",1,true) then
local oBurst = uWep.salvoSize * uWep.projectiles
local oRld = max(0.00000000001,uWep.stockpile == true and uWep.stockpileTime/30 or uWep.reload)
local wepCount = wepCounts[wDefId]
local typeName = uWep.type
local wpnName = uWep.description
if i == deathWeaponIndex then
wpnName = "Death explosion"
oRld = 1
elseif i == selfDWeaponIndex then
wpnName = "Self Destruct"
oRld = uDef.selfDCountdown
end
if wepCount > 1 then
DrawText("Weap:", format(yellow .. "%dx" .. white .. " %s", wepCount, wpnName))
else
DrawText("Weap:", wpnName)
end
DrawText("Info:", format("%d range, %d aoe, %d%% edge", uWep.range, uWep.damageAreaOfEffect, 100 * uWep.edgeEffectiveness))
if uWep.coverageRange and uWep.stockpile then
DrawText("Anti:", format("%d Interceptor Range", uWep.coverageRange))
end
if uWep.coverageRange and uWep.interceptor == 16 then
DrawText("MDS:", format("%d Interceptor Range", uWep.coverageRange))
end
if uWep.targetable == 16 then
DrawText("MDS:","Is Targetable", '')
end
local reload = uWep.reload
local accuracy = uWep.accuracy
local moveError = uWep.targetMoveError
local range = uWep.range or nil
dummyRange[i] = {range = range or false, defID = uDef.id ,name = uDef.name, index = i, surface = surface, air = air}
local infoText = ""
if wpnName == "Death explosion" or wpnName == "Self Destruct" then
infoText = format("%d aoe, %d%% edge", uWep.damageAreaOfEffect, 100 * uWep.edgeEffectiveness)
else
infoText = format("%d range, %d aoe, %d%% edge", useExp and range or uWep.range, uWep.damageAreaOfEffect, 100 * uWep.edgeEffectiveness)
end
if uWep.damages.paralyzeDamageTime > 0 then
infoText = format("%s, %ds paralyze", infoText, uWep.damages.paralyzeDamageTime)
end
if uWep.damages.impulseBoost > 0 then
infoText = format("%s, %d impulse", infoText, uWep.damages.impulseBoost*100)
end
if uWep.damages.craterBoost > 0 then
infoText = format("%s, %d crater", infoText, uWep.damages.craterBoost*100)
end
DrawText("Info:", infoText)
local defaultDamage = uWep.damages[0]
for cat=0, #uWep.damages do
local oDmg = uWep.damages[cat]
local catName = Game.armorTypes[cat]
if catName and oDmg and (oDmg ~= defaultDamage or cat == 0) then
local dmgString
if oBurst > 1 then
dmgString = format(yellow .. "%d (x%d)" .. white .. " / " .. yellow .. "%.2f\s" .. white .. " = " .. yellow .. "%.2f \d\p\s", oDmg, oBurst, oRld, oBurst * oDmg / oRld)
else
dmgString = format(yellow .. "%d" .. white .. " / " .. yellow .. "%.2f\s" .. white .. " = " .. yellow .. "%.2f \d\p\s", oDmg, oRld, oDmg / oRld)
end
if wepCount > 1 then
dmgString = dmgString .. white .. " (Each)"
end
dmgString = dmgString .. white .. " (" .. catName .. ")"
DrawText("Dmg:", dmgString)
end
end
if uWep.metalCost > 0 or uWep.energyCost > 0 then
-- Stockpiling weapons are weird
-- They take the correct amount of resources overall
-- They take the correct amount of time
-- They drain ((simSpeed+2)/simSpeed) times more resources than they should (And the listed drain is real, having lower income than listed drain WILL stall you)
local drainAdjust = uWep.stockpile and (simSpeed+2)/simSpeed or 1
DrawText('Cost:', format(metalColor .. '%d' .. white .. ', ' ..
energyColor .. '%d' .. white .. ' = ' ..
metalColor .. '-%d' .. white .. ', ' ..
energyColor .. '-%d' .. white .. ' per second',
uWep.metalCost,
uWep.energyCost,
drainAdjust * uWep.metalCost / oRld,
drainAdjust * uWep.energyCost / oRld))
end
if (weaponInfo[wDefId]) then
local radius = weaponInfo[wDefId].radius
local damage = weaponInfo[wDefId].damage
local duration = weaponInfo[wDefId].duration
DrawText("Area Dmg:", format(white .. "%d aoe, %d max damage per second , %d seconds", radius, damage * 30 / DAMAGE_PERIOD, duration / 30 ))
end
cY = cY - fontSize
end
end
-- background
glColor(WG["background_opacity_custom"])
-- correct position when it goes below screen
if cY < 0 then
cYstart = cYstart - cY
local num = #textBuffer
for i=1, num do
textBuffer[i][4] = textBuffer[i][4] - (cY/2)
textBuffer[i][4] = textBuffer[i][4] - (cY/2)
end
cY = 0
end
-- correct position when it goes off screen
if cX + maxWidth+bgpadding+bgpadding > vsx then
local cXnew = vsx-maxWidth-bgpadding-bgpadding
local num = #textBuffer
for i=1, num do
textBuffer[i][3] = textBuffer[i][3] - ((cX-cXnew)/2)
textBuffer[i][3] = textBuffer[i][3] - ((cX-cXnew)/2)
end
cX = cXnew
end
-- title
local text = "\255\190\255\190" .. uDef.humanName .. " " .. grey .. uDef.name .. grey
local iconHalfSize = titleFontSize*0.75
cornersize = 0
glColor(WG["background_opacity_custom"])
RectRound(cX-bgpadding+cornersize, cYstart-bgpadding+cornersize, cX+(gl.GetTextWidth(text)*titleFontSize)+iconHalfSize+iconHalfSize+bgpadding+(bgpadding/1.5)-cornersize, cYstart+(titleFontSize/2)+bgpadding-cornersize, bgcornerSize)
cornersize = ceil(bgpadding*0.21)
glColor(1,1,1,0.025)
RectRound(cX-bgpadding+cornersize, cYstart-bgpadding+cornersize, cX+(gl.GetTextWidth(text)*titleFontSize)+bgpadding-cornersize, cYstart+(titleFontSize/2)+bgpadding-cornersize, bgcornerSize)
if (WG['guishader_api'] ~= nil) then
guishaderEnabled = true
WG['guishader_api'].InsertRect(cX-bgpadding, cYstart-bgpadding, cX+(gl.GetTextWidth(text)*titleFontSize)+bgpadding, cYstart+(titleFontSize/2)+bgpadding, 'unit_stats_title')
end
-- icon
--glColor(1,1,1,1)
--glTexture('#' .. uDefID)
--glTexRect(cX, cYstart+cornersize-iconHalfSize, cX+iconHalfSize+iconHalfSize, cYstart+cornersize+iconHalfSize)
--glTexture(false)
-- title text
glColor(1,1,1,1)
--glText(text, cX+iconHalfSize+iconHalfSize+(bgpadding/1.5), cYstart, titleFontSize, "o")
glText(text, cX, cYstart, titleFontSize, "o")
-- stats
glColor(WG["background_opacity_custom"])
cornersize = 0
RectRound(floor(cX-bgpadding)+cornersize, ceil(cY+(fontSize/3)+bgpadding)+cornersize, ceil(cX+maxWidth+bgpadding)-cornersize, floor(cYstart-bgpadding)-cornersize, bgcornerSize)
cornersize = ceil(bgpadding*0.16)
glColor(1,1,1,0.025)
RectRound(floor(cX-bgpadding)+cornersize, ceil(cY+(fontSize/3)+bgpadding)+cornersize, ceil(cX+maxWidth+bgpadding)-cornersize, floor(cYstart-bgpadding)-cornersize, bgcornerSize)
DrawTextBuffer()
if (WG['guishader_api'] ~= nil) then
guishaderEnabled = true
WG['guishader_api'].InsertRect(cX-bgpadding, cY+(fontSize/3)+bgpadding, cX+maxWidth+bgpadding, cYstart-bgpadding, 'unit_stats_data')
end
end
end
function widget:DrawWorld()
if dummyUnitID then
for i, keys in pairs(dummyRange) do
local color = {1, 0, 0, darkOpacity}
--Spring.Echo(currentMod,keys.name,keys.defID,keys.index,keys.surface,keys.air)
if modConfig[currentMod]["unitList"][keys.name] then
local weapontype = modConfig[currentMod]["unitList"][keys.name]["weapons"][keys.index]
if ( weapontype == 1 or weapontype == 4 ) then -- show combo units with ground-dps-colors
color = colorConfig["ally"]["ground"]["min"]
elseif ( weapontype == 2 ) then
color = colorConfig["ally"]["air"]["min"]
elseif ( weapontype == 3 ) then -- antinuke
color = colorConfig["ally"]["nuke"]
end
else
if keys.surface then
color = colorConfig["ally"]["ground"]["min"]
elseif keys.air then
color = colorConfig["ally"]["air"]["min"]
end
end
gl.Color(color[1], color[2], color[3], darkOpacity)
gl.LineWidth(1.2)
x, y, z = Spring.GetUnitBasePosition(dummyUnitID)
gl.DrawGroundCircle(x, y, z, keys.range, 64)
gl.Color(1,1,1,1)
end
end
end
|
local parser = require "parser"
ngx.req.read_body()
local body = ngx.req.get_body_data()
local p, err = parser.new(body, ngx.var.http_content_type)
if not p then
ngx.say("failed to create parser: ", err)
return
end
local filePath, originFileName, extName
while true do
local part_body, name = p:parse_part()
if not part_body then
break
end
if name == 'fileUpload.path' then
filePath = part_body
end
if name == 'fileUpload.name' then
originFileName = part_body
end
end
os.execute('mkdir -p '..filePath..'.d/')
os.execute('mv '..filePath..' '..filePath..'.d/'..originFileName)
os.execute('mv '..filePath..'.d '..filePath)
ngx.header['Content-Type'] = 'text/plain'
ngx.header['X-Frame-Options'] = 'GOFORIT'
ngx.say(filePath:match('/opt/upload(.*)')..'/'..originFileName)
|
fx_version 'bodacious'
games { 'rdr3', 'gta5' }
author 'Kanersps'
description 'A MySQL plugin for EssentialMode'
--[[migration_files {
'migrations/0001_create_user.cs',
'migrations/0002_add_roles.cs'
}]]
server_scripts {
'@mysql-async/lib/MySQL.lua',
--'@fxmigrant/helper.lua',
'server.lua'
}
dependencies {
'essentialmode',
'mysql-async'
--'fxmigrant'
}
|
local hascrypto, crypto = pcall(require, 'crypto')
if hascrypto then
print "Using luacrypto"
return crypto.hmac.digest
end
local sha1 = require 'extern.sha1'
print "Using sha1.lua"
return function(hash, c, secret)
assert(hash == "sha1", "unsupported digest type")
return sha1.hmac_binary(secret, c)
end
|
--- Reading and writing strings using file-like objects. <br>
--
-- f = stringio.open(text)
-- l1 = f:read() -- read first line
-- n,m = f:read ('*n','*n') -- read two numbers
-- for line in f:lines() do print(line) end -- iterate over all lines
-- f = stringio.create()
-- f:write('hello')
-- f:write('dolly')
-- assert(f:value(),'hellodolly')
--
-- See @{03-strings.md.File_style_I_O_on_Strings|the Guide}.
-- @module pl.stringio
local unpack = rawget(_G, "unpack") or rawget(table, "unpack")
local tonumber = tonumber
local concat, append = table.concat, table.insert
local stringio = {}
-- Writer class
local SW = {}
SW.__index = SW
local function xwrite(self, ...)
local args = { ... } --arguments may not be nil!
for i = 1, #args do
append(self.tbl, args[i])
end
end
function SW:write(arg1, arg2, ...)
if arg2 then
xwrite(self, arg1, arg2, ...)
else
append(self.tbl, arg1)
end
end
function SW:writef(fmt, ...)
self:write(fmt:format(...))
end
function SW:value()
return concat(self.tbl)
end
function SW:__tostring()
return self:value()
end
function SW:close() -- for compatibility only
end
function SW:seek() end
-- Reader class
local SR = {}
SR.__index = SR
function SR:_read(fmt)
local i, str = self.i, self.str
local sz = #str
if i > sz then
return nil
end
local res
if fmt == "*l" or fmt == "*L" then
local idx = str:find("\n", i) or (sz + 1)
res = str:sub(i, fmt == "*l" and idx - 1 or idx)
self.i = idx + 1
elseif fmt == "*a" then
res = str:sub(i)
self.i = sz
elseif fmt == "*n" then
local _, i2, idx
_, idx = str:find("%s*%d+", i)
_, i2 = str:find("^%.%d+", idx + 1)
if i2 then
idx = i2
end
_, i2 = str:find("^[eE][%+%-]*%d+", idx + 1)
if i2 then
idx = i2
end
local val = str:sub(i, idx)
res = tonumber(val)
self.i = idx + 1
elseif type(fmt) == "number" then
res = str:sub(i, i + fmt - 1)
self.i = i + fmt
else
error("bad read format", 2)
end
return res
end
function SR:read(...)
if select("#", ...) == 0 then
return self:_read "*l"
else
local res, fmts = {}, { ... }
for i = 1, #fmts do
res[i] = self:_read(fmts[i])
end
return unpack(res)
end
end
function SR:seek(whence, offset)
local base
whence = whence or "cur"
offset = offset or 0
if whence == "set" then
base = 1
elseif whence == "cur" then
base = self.i
elseif whence == "end" then
base = #self.str
end
self.i = base + offset
return self.i
end
function SR:lines(...)
local n, args = select("#", ...)
if n > 0 then
args = { ... }
end
return function()
if n == 0 then
return self:_read "*l"
else
return self:read(unpack(args))
end
end
end
function SR:close() -- for compatibility only
end
--- create a file-like object which can be used to construct a string.
-- The resulting object has an extra `value()` method for
-- retrieving the string value. Implements `file:write`, `file:seek`, `file:lines`,
-- plus an extra `writef` method which works like `utils.printf`.
-- @usage f = create(); f:write('hello, dolly\n'); print(f:value())
function stringio.create()
return setmetatable({ tbl = {} }, SW)
end
--- create a file-like object for reading from a given string.
-- Implements `file:read`.
-- @string s The input string.
-- @usage fs = open '20 10'; x,y = f:read ('*n','*n'); assert(x == 20 and y == 10)
function stringio.open(s)
return setmetatable({ str = s, i = 1 }, SR)
end
function stringio.lines(s, ...)
return stringio.open(s):lines(...)
end
return stringio
|
local fs = require('fs')
local app = require('app')
local util = require('util')
local lnode = require('lnode')
local devices = require('devices')
local context = {}
local exports = {}
-- 检查指定的链接文件
---@param srcname string 链接文件名
---@param destname string 目标目录名
function exports.checkPathLink(srcname, destname)
fs.mkdirpSync(destname)
local result = fs.readlinkSync(srcname)
if (result == destname) then
return
end
local cmdline = 'rm -rf ' .. srcname
local ret, type, code = os.execute(cmdline)
if (not ret) then
-- console.log(cmdline, ret, type, code)
end
cmdline = 'ln -s ' .. destname .. ' ' .. srcname
ret, type, code = os.execute(cmdline)
if (not ret) then
-- console.log(cmdline, ret, type, code)
end
print("create link: " .. cmdline, type, code)
end
-- 创建所需的 /var/xxx 目录
function exports.initVarSubpaths()
exports.checkPathLink('/var/lock', '/tmp/lock/') -- 文件锁
exports.checkPathLink('/var/log', '/tmp/log/') -- 日志文件
exports.checkPathLink('/var/run', '/tmp/run/') -- 运行时临时文件
exports.checkPathLink('/var/sock', '/tmp/sock/') -- IPC 文件
end
-- 初始化 Node.lua 所需要的 init 脚本和配置文件
function exports.installInitFiles()
exports.saveInitFile('data/S87hidev', '/etc/init.d/S87hidev')
exports.saveInitFile('data/S88lnode', '/etc/init.d/S88lnode')
exports.saveInitFile('data/localtime', '/etc/localtime')
end
-- 初始化 pppd 所需的脚本和配置文件
function exports.installPppFiles()
fs.mkdirpSync('/tmp/ppp')
fs.mkdirpSync('/tmp/ppp/peers')
fs.mkdirpSync('/tmp/ppp/data')
exports.checkPathLink('/etc/ppp', '/tmp/ppp/')
-- 安装 pppd 所需要的脚本和配置文件
exports.saveBundleFile('data/ppp/peers/quectel-chat-connect', '/tmp/ppp/peers/quectel-chat-connect')
exports.saveBundleFile('data/ppp/peers/quectel-chat-disconnect', '/tmp/ppp/peers/quectel-chat-disconnect')
exports.saveBundleFile('data/ppp/peers/quectel-ppp', '/tmp/ppp/peers/quectel-ppp')
exports.saveBundleFile('data/ppp/peers/quectel-ppp-kill', '/tmp/ppp/peers/quectel-ppp-kill', 511)
exports.saveBundleFile('data/ppp/peers/quectel-pppd.sh', '/tmp/ppp/peers/quectel-pppd.sh', 511)
exports.saveBundleFile('data/ppp/data/chat-test', '/tmp/ppp/data/chat-test')
exports.saveBundleFile('data/ppp/data/quectel-chat-status', '/tmp/ppp/data/quectel-chat-status')
exports.saveBundleFile('data/ppp/ip-up', '/tmp/ppp/ip-up', 511)
fs.chmodSync('/tmp/ppp/ip-up', 511) -- 777
end
-- 从 lci.zip Zip 包中读取指定名称的文件的内容
---@param name string - Bundle file name path/to/file
---@return string - file data
---@return string - error
function exports.readBundleFile(name)
if (not name) then
return nil, 'Bad bundle file name'
end
local dirname = util.dirname()
if (dirname and dirname:startsWith('$app/')) then
local reader = package.apps and package.apps.lci
if (reader) then
return reader:readFile(name)
end
end
local rootPath = app.rootPath
local filename = rootPath .. '/app/lci/' .. name
-- check source
local stat, err = fs.statSync(filename)
if (err) then
return nil, err
end
local fileSize = stat and stat.size
local fileData
fileData, err = fs.readFileSync(filename)
if err or (not fileData) or (#fileData ~= fileSize) then
return nil, err
end
return fileData
end
-- 读取并保存 zip 包中的文件到文件系统中
---@param name string lci.zip 中文件的名称
---@param destname string 要保存的路径
---@param mode string
function exports.saveBundleFile(name, destname, mode)
local fileData, err
fileData, err = exports.readBundleFile(name)
if (err) then
return print(err)
elseif (not fileData) then
return print('File data is empty: ' .. name)
end
_, err = fs.writeFileSync(destname, fileData)
if (err) then
return print(err)
end
if (mode) then
fs.chmodSync(destname, mode)
end
return true
end
function exports.saveInitFile(srcname, destname)
-- check source
local fileData, err = exports.readBundleFile(srcname)
if err or (not fileData) then
print("saveInitFile: Bad source file", err)
return
end
-- console.log('Source file size: ' .. #fileData)
local position = string.find(fileData, '\r\n')
if (position ~= nil) then
print("saveInitFile: Bad source file line end", position)
return
end
-- check dest
local destData = fs.readFileSync(destname)
if (destData == fileData) then
-- print("saveInitFile: Same dest file!", destname)
return
end
-- write
_, err = fs.writeFileSync(destname .. '~', fileData)
if (err) then
return print("saveInitFile: write error: " .. tostring(err))
end
destData, err = fs.readFileSync(destname .. '~')
if err or (destData ~= fileData) then
if (err) then
return print("saveInitFile: check error: " .. tostring(err))
end
return
end
-- switch
fs.chmodSync(destname .. '~', 511) -- 777
os.remove(destname)
os.rename(destname .. '~', destname)
fs.chmodSync(destname, 511) -- 777
print('saveInitFile: ' .. destname)
end
-- --------------------
-- exports
function exports.start()
devices.init()
local borad = lnode.board
print('borad', borad)
exports.initVarSubpaths(borad)
if (borad == 'dt02') or (borad == 'dt02b') then
exports.installInitFiles(borad)
exports.installPppFiles(borad)
elseif (borad == 't31a') then
os.execute('lpm start lci wotc lpm > /tmp/log/lpm.log')
end
end
function exports.update(type)
if (not type) then
print('Usage: lci boot <board name>')
return
end
print('type: ' .. tostring(type))
local ret = exports.saveBundleFile('data/' .. type .. '.conf', '/usr/local/lnode/conf/device.conf')
if (ret) then
exports.installInitFiles()
end
end
return exports
|
/**
* General configuration
**/
hook.Add("InitPostEntity", "SH_SZ.InitPostEntity", function()
CAMI.RegisterPrivilege({
Name = "Safezone - edit",
MinAccess = "superadmin"
})
end)
-- Use Steam Workshop for the content instead of FastDL?
SH_SZ.UseWorkshop = true
-- Controls for the Editor camera.
-- See a full list here: http://wiki.garrysmod.com/page/Enums/KEY
SH_SZ.CameraControls = {
forward = KEY_W,
left = KEY_A,
back = KEY_S,
right = KEY_D,
}
/**
* HUD configuration
**/
-- Where to display the Safe Zone Indicator on the screen.
-- Possible options: topleft, top, topright, left, center, right, bottomleft, bottom, bottomright
SH_SZ.HUDAlign = "top"
-- Offset of the Indicator relative to its base position.
-- Use this if you want to move the indicator by a few pixels.
SH_SZ.HUDOffset = {
x = 0,
y = 0,
scale = false, -- Set to false/true to enable offset scaling depending on screen resolution.
}
/**
* Advanced configuration
* Edit at your own risk!
**/
SH_SZ.WindowSize = {w = 800, h = 300}
SH_SZ.DefaultOptions = {
name = "Safezone",
namecolor = "52,152,219",
hud = true,
noatk = true,
nonpc = true,
noprop = true,
ptime = 5,
entermsg = "",
leavemsg = "",
}
SH_SZ.MaximumSize = 2048
SH_SZ.DataDirName = "sh_safezones"
SH_SZ.ZoneHitboxesDeveloper = false
SH_SZ.TeleportIdealDistance = 512
/**
* Theme configuration
**/
-- Font to use for normal text throughout the interface.
SH_SZ.Font = "Circular Std Medium"
-- Font to use for bold text throughout the interface.
SH_SZ.FontBold = "Circular Std Bold"
-- Color sheet. Only modify if you know what you're doing
SH_SZ.Style = {
header = Color(52, 152, 219, 255),
bg = Color(52, 73, 94, 255),
inbg = Color(44, 62, 80, 255),
close_hover = Color(231, 76, 60, 255),
hover = Color(255, 255, 255, 10, 255),
hover2 = Color(255, 255, 255, 5, 255),
text = Color(255, 255, 255, 255),
text_down = Color(0, 0, 0),
textentry = Color(236, 240, 241),
menu = Color(127, 140, 141),
success = Color(46, 204, 113),
failure = Color(231, 76, 60),
}
/**
* Language configuration
**/
-- Various strings used throughout the chatbox. Change them to your language here.
-- %s and %d are special strings replaced with relevant info, keep them in the string!
SH_SZ.Language = {
safezone = "Безопасная зона",
safezone_type = "Тип безопасной зоны",
cube = "Куб",
sphere = "Сфера",
select_a_safezone = "Выбрать безопасную зону",
options = "Настройка",
name = "Имя",
name_color = "Цвет",
enable_hud_indicator = "Включить индикатор ХУД",
delete_non_admin_props = "Удаление не-админских элементов",
prevent_attacking_with_weapons = "Предотвращать атаки игроков",
automatically_remove_npcs = "Удалить НПС",
time_until_protection_enables = "Время до включения защиты",
enter_message = "Сообщение при входе",
leave_message = "Сообщение при выходе",
will_be_protected_in_x = "Вы будете защищены в течении %s секунд",
safe_from_damage = "Вы защищены от любого урона.",
place_point_x = "Нумеровать точку. %d с помощью мыши",
size = "Размер",
finalize_placement = "Выберите место для размещения и нажмите \"Подтвердить\"",
add = "Добавить",
edit = "Изменить",
fill_vertically = "Заполнить вертикально",
reset = "Восстановить",
confirm = "Подтвердить",
teleport_there = "Телепортироваться сюда",
save = "Сохранить",
delete = "Удалить",
cancel = "Отменить",
move_camera = "Двигать камеру",
rotate_camera = "Правый щелчок: вращение камерой",
an_error_has_occured = "Произошла ошибка, перезапустите сервер или повторите попытку",
not_allowed = "Вы не можете этого сделать!",
safe_zone_created = "Безопасная зона была успешна создана!",
safe_zone_edited = "Безопасная зона успешно изменена!",
safe_zone_deleted = "Безопасная зона успешно удалена!",
} |
ITEM.name = "Monolith Sunrise"
ITEM.description = "A basic Sunrise suit colored in favor of Monolith."
ITEM.category = "Outfit"
ITEM.model = "models/tnb/stalker/items/sunrise.mdl"
ITEM.width = 2
ITEM.height = 2
ITEM.outfitCategory = "model"
ITEM.pacData = {}
ITEM.newSkin = 3
ITEM.replacements = {"anorak", "sunrise"} |
-----------------------------------------------------------------------------------
--
-- Copyright (C) 1994 Narvik University College
-- Contact: GMlib Online Portal at http://episteme.hin.no
--
-- This file is part of the Geometric Modeling Library, GMlib.
--
-- GMlib is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- GMlib is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with GMlib. If not, see <http://www.gnu.org/licenses/>.
--
-----------------------------------------------------------------------------------
-- An evaluation function evaluating a parametric sphere
function eval ( u, v, d1, d2, lu, lv )
-- Set up return value - matrix[u][v]
local p = {}
for i = 0, d1 do
p[""..i] = {}
for j = 0, d2 do
p[""..i][""..j] = {}
p[""..i][""..j].x = 0
p[""..i][""..j].y = 0
p[""..i][""..j].z = 0
end
end
-- Compute help variables
radius = 5.0
cos_u = math.cos( u )
cos_v = radius * math.cos( v )
sin_u = math.sin( u )
sin_v = radius * math.sin( v )
cu_cv = cos_u * cos_v
cu_sv = cos_u * sin_v
su_cv = sin_u * cos_v
su_sv = sin_u * sin_v
-- Compute function values and derivatives
-- S
p['0']['0'].x = cos_u * cos_v
p['0']['0'].y = sin_u * cos_v
p['0']['0'].z = sin_v
-- S_u
if d1 > 0
then
p['1']['0'].x = -su_cv
p['1']['0'].y = cu_cv
p['1']['0'].z = 0.0
end
-- S_v
if d2 > 0
then
p['0']['1'].x = -cu_sv
p['0']['1'].y = -su_sv
p['0']['1'].z = cos_v
end
-- S_uv
if d1 > 0 and d2 > 0
then
p['1']['1'].x = su_sv
p['1']['1'].y = -cu_sv
p['1']['1'].z = 0.0
end
-- S_uu
if d1 > 1
then
p['2']['0'].x = -cu_cv
p['2']['0'].y = -su_cv
p['2']['0'].z = 0.0
end
-- S_vv
if d2 > 1
then
p['0']['2'].x = -cu_cv
p['0']['2'].y = -su_cv
p['0']['2'].z = -sin_v
end
-- S_uuv
if d1 > 1 and d2 > 0
then
p['2']['1'].x = cu_sv
p['2']['1'].y = su_sv
p['2']['1'].z = 0.0
end
-- S_uvv
if d1 > 0 and d2 > 1
then
p['1']['2'].x = su_cv
p['1']['2'].y = -cu_cv
p['1']['2'].z = 0.0
end
-- S_uuvv
if d1 > 1 and d2 > 1
then
p['2']['2'].x = cu_cv
p['2']['2'].y = su_cv
p['2']['2'].z = 0.0
end
-- S_uuu
if d1 > 2
then
p['3']['0'].x = su_cv
p['3']['0'].y = -cu_cv
p['3']['0'].z = 0.0
end
-- S_vvv
if d2 > 2
then
p['0']['3'].x = cu_sv
p['0']['3'].y = su_sv
p['0']['3'].z = -cos_v
end
-- S_uuuv
if d1 > 2 and d2 > 0
then
p['3']['1'].x = -su_sv
p['3']['1'].y = cu_sv
p['3']['1'].z = 0.0
end
-- S_uuuvv
if d1 > 2 and d2 > 1
then
p['3']['2'].x = -su_cv
p['3']['2'].y = cu_cv
p['3']['2'].z = 0.0
end
-- S_uvvv
if d1 and d2 > 2
then
p['1']['3'].x = -su_sv
p['1']['3'].y = cu_sv
p['1']['3'].z = 0.0
end
-- S_uuvvv
if d1 > 1 and d2 > 2
then
p['2']['3'].x = -cu_sv
p['2']['3'].y = -su_sv
p['2']['3'].z = 0.0
end
-- S_uuuvvv
if d1 > 2 and d2 > 2
then
p['3']['3'].x = su_sv
p['3']['3'].y = -cu_sv
p['3']['3'].z = 0.0
end
-- Return result
return p
end
|
return {
description = "softban (ban and unban) a member from the server.",
args = {{"user","Please specify a user."},{"string","Please state the softban reason."}},
permissions = {raw={"kickMembers"}},
category = "mod"
},
function(message,args,flags)
local user = args.myArgs[1]
local guild = message.guild
guild:banUser(user,7)
local result = guild:unbanUser(user)
if result then
respond:success("Successfully softbanned **"..user.username.."**")
modules.logger[1]:newModLog(guild,user,{
type = "Softban",
reason = args.myArgs[2],
mod = message.author.id
})
else
respond:error("Failed to softban **"..user.username.."**")
end
end |
data:extend({
{
type = "int-setting",
minimum_value = "1",
maximum_value = "1000",
default_value = "500",
name = "steelaxe-subscience-new-pack-count",
setting_type = "startup",
localised_name = "New science pack count",
localised_description = "Number of new science packs to generate. Integer between 1 and 1000.",
order = "1"
},
{
type = "int-setting",
minimum_value = "1",
maximum_value = "1000",
default_value = "25",
name = "steelaxe-subscience-first-medium",
setting_type = "startup",
localised_name = "First medium science pack",
localised_description = "Medium science packs have 2 low avg qty ingredients and 2 high avg qty ingredients. Ingredient challenge ranges from easy to medium.",
order = "2"
},
{
type = "int-setting",
minimum_value = "1",
maximum_value = "1000",
default_value = "50",
name = "steelaxe-subscience-first-hard",
setting_type = "startup",
localised_name = "First hard science pack",
localised_description = "Hard science packs have 2 low avg qty ingredients and 2 high avg qty ingredients. Ingredient challenge ranges from easy to hard.",
order = "3"
},
{
type = "int-setting",
minimum_value = "0",
maximum_value = "4294967295",
default_value = "0",
name = "steelaxe-subscience-random-seed",
setting_type = "startup",
localised_name = "Recipe random seed",
localised_description = "Seed for recipe randomization. Integer between 0 and 4294967295.",
order = "4"
},
{
type = "int-setting",
minimum_value = "1",
maximum_value = "10",
default_value = "5",
name = "steelaxe-subscience-subspertech",
setting_type = "startup",
localised_name = "Subs per tech",
localised_description = "For every X subs, Anti must unlock a new science pack via research. " ..
"This setting only affects the flavor text of science techs which indicate the point at which each tech should be researched.",
order = "5"
}
})
|
--# Monster converted using Devm monster converter #--
local mType = Game.createMonsterType("Draken Spellweaver")
local monster = {}
monster.description = "a draken spellweaver"
monster.experience = 3100
monster.outfit = {
lookType = 340,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.raceId = 618
monster.Bestiary = {
class = "Dragon",
race = BESTY_RACE_DRAGON,
toKill = 2500,
FirstUnlock = 100,
SecondUnlock = 1000,
CharmsPoints = 50,
Stars = 4,
Occurrence = 0,
Locations = "Zao Palace, Razzachai, and Zzaion."
}
monster.health = 5000
monster.maxHealth = 5000
monster.race = "blood"
monster.corpse = 10399
monster.speed = 336
monster.manaCost = 0
monster.maxSummons = 0
monster.changeTarget = {
interval = 4000,
chance = 10
}
monster.strategiesTarget = {
nearest = 100,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 70,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = true,
canWalkOnPoison = true,
pet = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
{text = "Kazzzzzzuuum!", yell = false},
{text = "Fissziss!", yell = false},
{text = "Zzzzzooom!", yell = false}
}
monster.loot = {
{id = 3006, chance = 370}, -- ring of the sky
{id = 3030, chance = 6910, maxCount = 5}, -- small ruby
{id = 3031, chance = 41000, maxCount = 100}, -- gold coin
{id = 3031, chance = 58000, maxCount = 100}, -- gold coin
{id = 3035, chance = 25510, maxCount = 5}, -- platinum coin
{id = 3038, chance = 970}, -- green gem
{id = 3071, chance = 1660}, -- wand of inferno
{id = 3577, chance = 30400}, -- meat
{id = 238, chance = 4970}, -- great mana potion
{id = 8043, chance = 1450}, -- focus cape
{id = 10386, chance = 1980}, -- Zaoan shoes
{id = 10397, chance = 19790}, -- weaver's wandtip
{id = 10398, chance = 10}, -- draken trophy
{id = 10438, chance = 620}, -- spellweaver's robe
{id = 10439, chance = 770}, -- Zaoan robe
{id = 11454, chance = 1980}, -- luminous orb
{id = 11658, chance = 3930}, -- draken sulphur
{id = 12307, chance = 30}, -- harness
{id = 12549, chance = 180} -- bamboo leaves
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -252},
{name ="combat", interval = 2000, chance = 10, type = COMBAT_FIREDAMAGE, minDamage = -240, maxDamage = -480, length = 4, spread = 3, effect = CONST_ME_EXPLOSIONHIT, target = false},
{name ="combat", interval = 2000, chance = 10, type = COMBAT_FIREDAMAGE, minDamage = -100, maxDamage = -250, range = 7, shootEffect = CONST_ANI_FIRE, effect = CONST_ME_FIREAREA, target = true},
{name ="combat", interval = 2000, chance = 10, type = COMBAT_ENERGYDAMAGE, minDamage = -150, maxDamage = -300, range = 7, shootEffect = CONST_ANI_ENERGY, effect = CONST_ME_ENERGYHIT, target = true},
{name ="combat", interval = 2000, chance = 10, type = COMBAT_EARTHDAMAGE, minDamage = -200, maxDamage = -380, radius = 4, effect = CONST_ME_POFF, target = true},
-- {name ="soulfire", interval = 2000, chance = 10, target = false},
-- poison
{name ="condition", type = CONDITION_POISON, interval = 2000, chance = 10, minDamage = -280, maxDamage = -360, shootEffect = CONST_ANI_POISON, target = true}
}
monster.defenses = {
defense = 25,
armor = 25,
{name ="invisible", interval = 2000, chance = 10, effect = CONST_ME_MAGIC_RED},
{name ="combat", interval = 2000, chance = 15, type = COMBAT_HEALING, minDamage = 270, maxDamage = 530, effect = CONST_ME_MAGIC_BLUE, target = false}
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = -10},
{type = COMBAT_ENERGYDAMAGE, percent = -10},
{type = COMBAT_EARTHDAMAGE, percent = 100},
{type = COMBAT_FIREDAMAGE, percent = 100},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = -10},
{type = COMBAT_HOLYDAMAGE , percent = -5},
{type = COMBAT_DEATHDAMAGE , percent = 75}
}
monster.immunities = {
{type = "paralyze", condition = false},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
|
#!/usr/bin/env lua
--[[ lptytest.lua
-
- test aspects of lpty
-
- Gunnar Zötl <[email protected]>, 2010-2015
- Released under MIT/X11 license. See file LICENSE for details.
--]]
lpty = require "lpty"
p = lpty.new()
ntests = 0
nfailed = 0
-- announce which test we are performing and what it tests
function announce(str)
str = str or ""
ntests = ntests + 1
print("Test " .. tostring(ntests) .. ": " .. str)
end
-- print that the test did not work out and optionally why
function fail(str)
local msg = " TEST FAILED"
nfailed = nfailed + 1
if str ~= nil then msg = msg .. ": " .. str end
print(msg)
end
-- just prints wether the test went ok or not. An optional reason for failure may be passed,
-- which will then be printed.
function check(ok, msg)
if ok==false then
fail(msg)
return false
else
print " TEST OK"
return true
end
end
-- wait for a fraction of a second
function waitabit(n)
n = n or 1
t0 = os.clock()
t1 = t0
while t1 - t0 < 0.1 * n do
t1 = os.clock()
end
end
-- 1
announce("starting test client")
ok, val = pcall(lpty.startproc, p, "lua", "testclient.lua")
if ok then
check(val)
else
fail(tostring(val))
end
-- 2
announce("checking whether pty has process, should return true")
ok, val = pcall(lpty.hasproc, p)
if ok then
check(val)
else
fail(tostring(val))
end
-- 3
announce("checking whether we can read from the pty, should return false")
ok, val = pcall(lpty.readok, p)
if ok then
check(val == false)
else
fail(tostring(val))
end
-- 4
announce("reading from pty with a timeout of 0.1 second, should return nil")
ok, val = pcall(lpty.read, p, 0.1)
if ok then
check(val == nil)
else
fail(tostring(val))
end
-- 5
announce("checking whether we can write to the pty, should return true")
ok, val = pcall(lpty.sendok, p)
if ok then
check(val)
else
fail(tostring(val))
end
-- 6
announce("writing data 'abcba\\n' to the pty, should return length of data -> 6")
ok, val = pcall(lpty.send, p, "abcba\n")
if ok then
check(val == 6)
else
fail(tostring(val))
end
-- allow the client to react
waitabit()
-- 7
announce("checking whether we can read from the pty, should return true")
ok, val = pcall(lpty.readok, p)
if ok then
check(val)
else
fail(tostring(val))
end
-- 8
announce("reading from pty, should return 'abcba\\n+abcba+\\n'")
ok, val = pcall(lpty.read, p, 1)
if ok then
val = string.gsub(val, "[\r\n]+", '.') -- normalize line endings
check(val == "abcba.+abcba+.")
else
fail(tostring(val))
end
-- 9
announce("terminating child process")
ok = pcall(lpty.endproc, p)
check(ok)
-- allow client to terminate
waitabit()
-- 10
announce("Checking whether pty has child process, should return false")
ok, val = pcall(lpty.hasproc, p)
if ok then
check(val == false)
else
fail(tostring(val))
end
-- 11
announce("checking whether we can read from pty, should return false")
ok, val = pcall(lpty.readok, p)
if ok then
check(val == false)
else
fail(tostring(val))
end
-- 12
announce("reading from pty with a timeout of 0.1 second, should return nil")
ok, val = pcall(lpty.read, p, 0.1)
if ok then
check(val == nil)
else
fail(tostring(val))
end
-- test timeout length. In order for this to work there may be no pending data in the pty to read.
function testto(to, tm)
local t0 = os.time()
local i
for i=1,10 do
p:read(to)
end
local t = os.time() - t0
-- allow for some deviation
return (tm - 1 < t and t < tm + 1)
end
-- 13
announce("testing timeout 0.1 second by running r:read(0.1) 10 times should take about 1 seconds")
check(testto(0.1, 1))
-- creating pty with no local echo for following tests
pn = lpty.new { no_local_echo = true }
-- 14
announce("checking for data from no_local_echo pty, should return false")
ok, val = pcall(lpty.readok, pn)
if ok then
check(val == false)
else
fail(tostring(val))
end
-- 15
announce("starting test client for no_local_echo pty")
ok, val = pcall(lpty.startproc, pn, "lua", "testclient.lua")
if ok then
check(val)
else
fail(tostring(val))
end
-- 16
announce("reading from no_local_echo pty, should now return '+abc+\\n'")
ok, val = pcall(lpty.send, pn, "abc\n")
ok, val = pcall(lpty.read, pn, 0.5)
if ok then
val = string.gsub(val, "[\r\n]+", '.') -- normalize line endings
check(val == "+abc+.")
else
fail(tostring(val))
end
-- 17
announce("sending 'xxx\\n' to pty, reading back, should return '+xxx+\\n'")
ok, val = pcall(lpty.send, pn, "xxx\n")
if not ok then
fail(tostring(val))
else
ok, val = pcall(lpty.read, pn, 0.5)
if ok then
val = string.gsub(val, "[\r\n]+", '.') -- normalize line endings
check(val == "+xxx+.")
else
fail(tostring(val))
end
end
-- 18
announce("testing exit status for current child, should return (false, nil)")
ok, val, code = pcall(lpty.exitstatus, pn)
if not ok then
fail(tostring(val))
else
check((val == false) and (code == nil))
end
-- 19
announce("quitting child then testing exit status, should return ('exit', 0)")
ok, val = pcall(lpty.send, pn, "quit\n")
if not ok then
fail(tostring(val))
else
while pn:hasproc() do end
ok, val, code = pcall(lpty.exitstatus, pn)
if not ok then
fail(tostring(val))
else
check((val == 'exit') and (code == 0))
end
end
-- 20
announce("starting child with invalid executable, then testing exit status, should return ('exit', 1)")
ok, val = pcall(lpty.startproc, pn, "./firsebrumf")
if not ok then
fail(tostring(val))
else
while pn:hasproc() do end
ok, val, code = pcall(lpty.exitstatus, pn)
if not ok then
fail(tostring(val))
else
check((val == 'exit') and (code == 1))
end
end
-- 21
announce("starting child process, then killing it, then testing exit status, should return ('sig', *) with *>0")
ok, val = pcall(lpty.startproc, pn, "lua")
term = 0
if not ok then
fail(tostring(val))
else
while not pn:hasproc() do end
ok, val = pcall(lpty.endproc, pn)
if not ok then
fail(tostring(val))
else
while pn:hasproc() do end
ok, val, code = pcall(lpty.exitstatus, pn)
if not ok then
fail(tostring(val))
else
term = code
check((val == 'sig') and (code > 0))
end
end
end
-- 22
announce("starting child process, then killing it with kill=true, then testing exit status, should return ('sig', *) with *>0 and also not equal to * from prev. test")
ok, val = pcall(lpty.startproc, pn, "lua")
if not ok then
fail(tostring(val))
else
while not pn:hasproc() do end
ok, val = pcall(lpty.endproc, pn, true)
if not ok then
fail(tostring(val))
else
while pn:hasproc() do end
ok, val, code = pcall(lpty.exitstatus, pn)
if not ok then
fail(tostring(val))
else
check((val == 'sig') and (code > 0) and (code ~= term))
end
end
end
-- cleanup
pn:flush()
-- 23
announce("reading environment from pty, should return a table with stuff in it")
ok, env = pcall(lpty.getenviron, pn)
envsiz = 0
if not ok then
fail(tostring(env))
else
ok = true
for k, v in pairs(env) do
envsiz = envsiz + 1
ok = ok and (type(k) == 'string') and (type(v) == 'string')
end
check(ok)
end
-- 24
announce("calling /usr/bin/env with an empty environment, then reading output, should return nothing at all")
ok, err = pcall(lpty.setenviron, pn, {})
if not ok then
fail(tostring(err))
else
ok, err = pcall(lpty.startproc, pn, '/usr/bin/env')
if not ok then
fail(tostring(err))
else
while pn:hasproc() do end
ok, val = pcall(lpty.read, pn, 1)
if not ok then
fail(tostring(val))
else
check(val == nil)
end
end
end
-- 25
announce("calling /usr/bin/env with {a=1} as its environment, then reading output, should return 'a=1\\n'")
ok, err = pcall(lpty.setenviron, pn, {a=1})
if not ok then
fail(tostring(err))
else
ok, err = pcall(lpty.startproc, pn, '/usr/bin/env')
if not ok then
fail(tostring(err))
else
while pn:hasproc() do end
ok, val = pcall(lpty.read, pn, 1)
if not ok then
fail(tostring(val))
else
val = string.gsub(tostring(val), "[\r\n]+", '.') -- normalize line endings
check(val == "a=1.")
end
end
end
-- 26
announce("resetting then reading environment from pty, should return a table with stuff in it, size as before we messed with it")
ok = pcall(lpty.setenviron, pn, nil)
ok, env = pcall(lpty.getenviron, pn)
mysiz = 0
if not ok then
fail(tostring(env))
else
ok = true
for k, v in pairs(env) do
mysiz = mysiz + 1
ok = ok and (type(k) == 'string') and (type(v) == 'string')
end
check(ok and (mysiz == envsiz))
end
-- 27
announce("calling /usr/bin/env on standard environment, should return as many lines as there are entries in the environment (as counted before)")
ok = pcall(lpty.startproc, pn, '/usr/bin/env')
if not ok then
fail(tostring(val))
else
while pn:hasproc() do end
val = ""
while pn:readok() do val = val .. pn:read() end
cnt = 0
string.gsub(val, ".-\n", function () cnt = cnt + 1 end)
check(cnt == envsiz)
end
-- cleanup
pn:endproc()
pn:flush()
-- 28
announce("testing readline on a standard pty")
pn=lpty.new()
ok, err = pcall(lpty.startproc, pn, "lua", "testclient.lua")
if not ok then
fail(tostring(err))
else
waitabit() -- wait for client to start
pn:send("abc\n")
pn:send("def\n")
waitabit() -- wait for all output to appear
ok, val = pcall(lpty.readline, pn)
if val == "abc" then
ok, val = pcall(lpty.readline, pn)
if val == "def" then
ok, val = pcall(lpty.readline, pn)
if val == "+abc+" then
ok, val = pcall(lpty.readline, pn)
check(val == "+def+")
else
fail()
end
else
fail()
end
else
fail()
end
end
pn:endproc()
-- 29
announce("testing readline on a raw mode pty")
pn=lpty.new{raw_mode = true}
ok, err = pcall(lpty.startproc, pn, "lua", "testclient.lua")
if not ok then
fail(tostring(err))
else
waitabit() -- wait for client to start
pn:send("abc\n")
pn:send("def\n")
waitabit() -- wait for all output to appear
ok, val = pcall(lpty.readline, pn)
if val == "+abc+" then
ok, val = pcall(lpty.readline, pn)
check(val == "+def+")
else
fail()
end
end
pn:endproc()
-- expect test
function expecttest(pn)
ok, err = pcall(lpty.startproc, pn, "lua")
if not ok then
fail(tostring(err))
return
end
ok, val = pcall(lpty.expect, pn, "> $", false, 1)
if not ok then
fail(tostring(val))
return
end
pn:send("loadfile('testclient.lua')()\n")
pn:send("abc\n")
ok, val = pcall(lpty.expect, pn, "%+([a-z]+)%+", false, 1)
if not ok then
fail(tostring(val))
else
check(val == "abc")
end
pn:endproc()
end
-- 30
announce("testing expect on a standard pty")
pn = lpty.new()
waitabit()
expecttest(pn)
-- 31
announce("testing expect on a no local echo pty")
pn = lpty.new{no_local_echo = true}
waitabit()
expecttest(pn)
-- 32
announce("testing expect on a raw mode pty")
pn = lpty.new{raw_mode = true}
waitabit()
expecttest(pn)
-- 33
announce("creating a pty, then setflag()ing it to no_local_echo mode, then back to default")
pn = lpty.new()
ok = pn:startproc("lua", "testclient.lua")
if ok then
pn:send("x\n")
waitabit()
val = pn:read(1)
val = string.gsub(val, "[\r\n]+", '.') -- normalize line endings
local ok, val1 = pcall(lpty.setflag, pn, 'no_local_echo', true)
if ok then
pn:send("x\n")
waitabit()
val1 = pn:read(1)
val1 = string.gsub(val1, "[\r\n]+", '.') -- normalize line endings
local ok, val2 = pcall(lpty.setflag, pn, 'no_local_echo', false)
if ok then
pn:send("x\n")
waitabit()
val2 = pn:read(1)
val2 = string.gsub(val2, "[\r\n]+", '.') -- normalize line endings
check(val == 'x.+x+.' and val1 == '+x+.' and val2 == 'x.+x+.', val .. ' vs '..val1..' vs '..val2)
else
fail(tostring(val2))
end
else
fail(tostring(val1))
end
else
fail(tostring(val))
end
pn:flush()
-- 34
announce("creating a pty, then setflag()ing it to raw mode, then back to default")
pn = lpty.new()
ok = pn:startproc("lua", "testclient.lua")
if ok then
pn:send("x\n")
waitabit()
val = pn:read(1)
val = string.gsub(val, "[\r\n]+", '.') -- normalize line endings
local ok, val1 = pcall(lpty.setflag, pn, 'raw_mode', true)
if ok then
pn:send("x\n")
waitabit()
val1 = pn:read(1)
val1 = string.gsub(val1, "[\r\n]+", '.') -- normalize line endings
local ok, val2 = pcall(lpty.setflag, pn, 'raw_mode', false)
if ok then
pn:send("x\n")
waitabit()
val2 = pn:read(1)
val2 = string.gsub(val2, "[\r\n]+", '.') -- normalize line endings
check(val == 'x.+x+.' and val1 == '+x+.' and val2 == 'x.+x+.', val .. ' vs '..val1..' vs '..val2)
else
fail(tostring(val2))
end
else
fail(tostring(val1))
end
else
fail(tostring(val))
end
pn:flush()
-- 35
announce("creating pty with separated stderr stream")
pn = lpty.new{separate_stderr = true}
check(pn)
-- 36
announce("forcing an error on pty with separated error stream. output should appear on readerr() not read()")
ok, err = pcall(lpty.startproc, pn, "/this must fail")
if not ok then
fail(tostring(err))
elseif pn:readok(1) == false then
check(pn:readerr(1) ~= nil, "readerr() returned no data")
else
fail("data appeared on pty")
end
pn:flush()
-- 37
announce("changing flag on pty to separate_stderr=false then forcing error. output should appear on pty.")
pn:setflag("separate_stderr", false)
ok, err = pcall(lpty.startproc, pn, "/this must fail")
if not ok then
fail(tostring(err))
elseif pn:readok(1) == true then
check(pn:readerr(1) == nil, "data appeared on readerr()")
else
fail("no data appeared on pty")
end
pn:flush()
-- 38
announce("changing flag on pty to separate_stderr=true then forcing error. output should appear on readerr() not read()")
pn:setflag("separate_stderr", true)
ok, err = pcall(lpty.startproc, pn, "/this must fail")
if not ok then
fail(tostring(err))
elseif pn:readok(1) == false then
check(pn:readerr(1) ~= nil, "readerr() returned no data")
else
fail("data appeared on pty")
end
pn:flush()
-- all done
print("Tests " .. tostring(ntests) .. " failed " .. tostring(nfailed))
|
-- 分成两个部分,一个部分涂颜色,一个部分扣文字
require "utf" -- 文件里面有数字好像加载会出错。。不知道为什么
BigSampleRate = 18
SmallSampleRate = 18
FontName = "STHUPO.TTF"
ImgName = "img.png"
function love.load()
file = io.open("src.txt", "r")
str = file:read("*a")
local sampleFunc = function ( gap )
drawdata = {}
img = love.graphics.newImage(ImgName)
local data = img:getData()
local w,h = img:getWidth(),img:getHeight()
-- local w,h = 200,200
local cnt = 0
for i=1,h-gap,gap do
local d = {}
for j=1,w-gap,gap do
local r, g, b, a = data:getPixel( j,i )
if a >128 and r+g+b < 20 then
table.insert(d,1)
cnt = cnt + 1
else
table.insert(d,0)
end
end
table.insert(drawdata,d)
end
return drawdata,cnt
end
bigsample,bigcnt = sampleFunc(BigSampleRate)
smallsample,smallcnt = sampleFunc(SmallSampleRate)
flag = math.floor(smallcnt/string.utf8len(str))
font = love.graphics.newFont(FontName, 20 )
love.graphics.setFont(font)
canvas = love.graphics.newCanvas()
canvas:renderTo(function()
love.graphics.setBackgroundColor(38,50,56)
-- draw back
-- love.graphics.setColor(255,95,86)
love.graphics.setColor(255,255,255,255)
local cnt = 1
for i=1,#bigsample do
d = bigsample[i]
for j=1,#d do
if d[j] == 1 then
love.graphics.circle( "fill", j*16+8, i*16+8, math.random(4,9) )
end
end
end
-- draw text
-- love.graphics.setColor(121,153,203)
-- love.graphics.setColor(237,237,237)
love.graphics.setColor(122,50,23)
local cnt = 1
for i=1,#smallsample do
d = smallsample[i]
for j=1,#d do
if d[j] == 1 then
local sign = ' '
if cnt % flag == 0 then
local t = math.floor(cnt/flag)
sign = str:utf8sub(t,t) or 'n'
love.graphics.print(sign,j*16,i*16)
-- love.graphics.printf(sign,j*16,i*16,20,"center",nil,1)
else
-- love.graphics.circle( "fill", j*16+10, i*16+10, 4 )
end
cnt = cnt + 1
end
end
end
end)
end
function love.draw()
love.graphics.setColor(255,255,255,255)
love.graphics.draw(canvas)
end
|
--[[
游戏逻辑常用的全局函数
]]
function message(message, ...)
local msg = GetTextByLanguageI(message, ...)
delay_call(0, function()
g_panel_mgr.show_multiple_in_top_scene('common.dlg_common_tips_panel', msg)
end)
end
function message_new(message, ...)
local msg = GetTextByLanguageI(message, ...)
delay_call(0, function()
g_panel_mgr.show_multiple_in_top_scene('common.dlg_common_tips_new_panel', msg)
end)
end
-- 显示确认面板
function confirm(content, callback, title, textYes, escFunc, notEscClosePanel, isClickClose, closePanelFunc)
return g_panel_mgr.show_multiple('common.dlg_confirm_panel', title, content , callback, textYes, escFunc, notEscClosePanel, isClickClose, closePanelFunc)
end
-- 显示确认取消面板
function confirm_yes_no(content, callback, title, textYes, textNo, noCallback, isClickClose)
return g_panel_mgr.show_multiple('common.dlg_confirm_yes_no_panel', title, content, callback, textYes, noCallback, textNo, isClickClose)
end
-- 显示确认取消面板(内容为scroll view)
function confirm_yes_no_scroll(content, callback, title, textYes, textNo, noCallback)
return g_panel_mgr.show_multiple('common.dlg_confirm_yes_no_scroll_panel', title, content, callback, textYes, noCallback, textNo)
end
-- 显示确认关闭面板
function confirm_yes_close(content, callback, title, textYes, escFunc)
return g_panel_mgr.show_multiple('common.dlg_confirm_yes_close_panel', title, content, callback, textYes, escFunc)
end
local _showLoadingPanels = {}
function show_loading_panel(id, time, closeCallback)
if _showLoadingPanels[id] then
_showLoadingPanels[id]:close_panel()
end
_showLoadingPanels[id] = g_panel_mgr.show_multiple('common.dlg_loading_panel', time, function()
_showLoadingPanels[id] = nil
if closeCallback then closeCallback() end
end)
end
function close_loading_panel(id)
local panel = _showLoadingPanels[id]
if panel then
panel:close_panel()
_showLoadingPanels[id] = nil
end
end
function is_loading_panel_exists(id)
return _showLoadingPanels[id] ~= nil
end
function GetServerTimeStamp()
return g_net_mgr.get_server_time_stamp()
end
-- dir:
function utils_test_upload_content2server(content, fileName, dir, callback)
local url = g_constant_conf['constant'].GAME_UPLOAD_LOG_FILE_URL .. '?filename=' .. fileName
if dir then
url = url ..'&dir=' .. dir
end
http_post(url, content, false, true).on_success = function()
if callback then
callback()
end
end
end
-- 当上传日志因为网络问题上传失败的时候会延时一段时间尝试重新发送
local _scheduleUploadContent = {}
local function _getWriteLogPath(type)
if _scheduleUploadContent[type] then
return g_fileUtils:getWritablePath() .. 'cache_upload_log_file_tmp_' .. type
else
return g_fileUtils:getWritablePath() .. 'cache_upload_log_file_' .. type
end
end
local function _tryUploadLog2Server(type)
print('_tryUploadLog2Server', type)
if _scheduleUploadContent[type] then
return
end
local filePath = _getWriteLogPath(type)
if g_fileUtils:isFileExist(filePath) then
local uploadContent = g_fileUtils:getStringFromFile(filePath)
local url = g_constant_conf['constant'].GAME_UPLOAD_HTTP_ERR_URL .. '?dir=' .. type
local handler = http_post(url, uploadContent, false, true)
_scheduleUploadContent[type] = true
handler.on_success = function()
local oldTempFilePath = _getWriteLogPath(type)
if g_fileUtils:isFileExist(oldTempFilePath) then
local tmpContent = g_fileUtils:getStringFromFile(oldTempFilePath)
g_fileUtils:removeFile(oldTempFilePath)
g_fileUtils:writeStringToFile(tmpContent, filePath)
elseif g_fileUtils:isFileExist(filePath) then
g_fileUtils:removeFile(filePath)
end
g_conf_mgr.set_native_conf_k_v('test_not_upload_log_type_list', type, nil)
_scheduleUploadContent[type] = nil
end
handler.on_fail = function()
_scheduleUploadContent[type] = nil
end
end
end
local _scheduleUpload = nil
function utils_test_schedule_upload_log2server(delay)
print('utils_test_schedule_upload_log2server', delay)
if _scheduleUpload then
return
end
_scheduleUpload = delay_call(5, function()
for tp, _ in pairs(table.copy(g_native_conf['test_not_upload_log_type_list'])) do
_tryUploadLog2Server(tp)
-- 一次一次地发
break
end
if table.is_empty(g_native_conf['test_not_upload_log_type_list']) then
return delay
else
_scheduleUpload = nil
end
end)
end
--
function utils_test_upload_log2server(type, info)
print('utils_test_upload_log2server')
assert(is_valid_str(type))
if not is_table(info) then
info = {content = info}
end
assert(is_table(info))
info['wifi_state'] = platform_get_network_type()
info['uuid'] = g_user_info.get_user_info() and g_user_info.get_user_info().uid or 0
info['version'] = string.format('%d.%d', utils_game_get_engine_sub_version(), utils_get_sdk_version())
info['channel'] = platform_get_app_channel_name()
info['sdk_name'] = g_native_conf['sdk_name']
info['cur_patch_version'] = g_native_conf['cur_patch_version']
info['platform'] = g_application:getTargetPlatform()
local uploadContent = luaext_json_encode(info) .. '\n'
local url = g_constant_conf['constant'].GAME_UPLOAD_HTTP_ERR_URL .. '?dir=' .. type
local handler = http_post(url, uploadContent, false, true)
-- test
-- handler.on_success = function()
-- message("upload success")
-- end
handler.on_fail = function()
-- 追加到文件尾端
local f = io.open(_getWriteLogPath(type), 'a')
if f then
f:write(uploadContent)
f:close()
g_conf_mgr.set_native_conf_k_v('test_not_upload_log_type_list', type, true)
end
utils_test_schedule_upload_log2server(3600)
end
end
function utils_remove_writable_path_folder_r(folderName)
local folder = g_fileUtils:getWritablePath() .. folderName .. '/'
if g_fileUtils:isDirectoryExist(folder) then
g_fileUtils:removeDirectory(folder)
end
end
--[[
websocket协程获取
@param net 需要绑定的网络对象
@param rsp 绑定的响应协议
@param reqFunc 请求的函数
]]
function coroutine_get_socket_rsp(net, rsp, reqFunc)
local co = coroutine.running()
local bResume = false
net:RegisterNetEvent(rsp, function(data)
if bResume == false then
bResume = true
coroutine.resume(co, data)
end
end, nil, true)
delay_call(1, function()
if net:IsConnected() and bResume == false then
return 1
elseif bResume == false then
bResume = true
coroutine.resume(co)
return
end
end)
if net:IsConnected() then
reqFunc()
elseif bResume == false then
bResume = true
delay_call(0.5, function()
coroutine.resume(co)
end)
end
return coroutine.yield()
end
function coroutine_wait_seconds(delay)
local co = coroutine.running()
delay_call(delay, function()
coroutine.resume(co)
end)
return coroutine.yield()
end
function coroutine_call_fun(fun,time)
local co = coroutine.running()
delay_call(time or 0, function()
fun()
coroutine.resume(co)
end)
return coroutine.yield()
end
local _listRandom = {''}
for i = string.byte('0'), string.byte('9') do
table.insert(_listRandom, string.char(i))
end
for i = string.byte('a'), string.byte('z') do
table.insert(_listRandom, string.char(i))
end
for i = string.byte('A'), string.byte('Z') do
table.insert(_listRandom, string.char(i))
end
function utils_get_uuid(num)
local ret = {}
math.randomseed(utils_get_tick())
for i = 1, num do
table.insert(ret, _listRandom[math.random(1, #_listRandom)])
end
return table.concat(ret)
end
local _costTime = {}
local _costTimes = {}
function profile(fun, name)
if _costTime[name] == nil then
_costTime[name] = 0
_costTimes[name] = 0
end
local cur = utils_get_tick()
fun()
local cost = utils_get_tick() - cur
local total = _costTime[name] + cost
local totalTimes = _costTimes[name] + 1
_costTime[name] = total
_costTimes[name] = totalTimes
printf('[%s] cost time:%f per cost time %f total cost time %f', name, cost,total/totalTimes, total)
end
--中文转换为当前选定语言
function T(desc)
local ret
pcall(function()
local multiLangConf = g_conf.info_scripts_multi_lang
ret = multiLangConf[desc]['lang']
end)
if ret == nil or ret == '' then
ret = desc
end
return ret
end
-- 用法:
-- GetTextByLanguageI(2, '111', '222', '333')
-- GetTextByLanguageI(asdf# {2} # {1} # {3} #sdfddd, '111', '222', '333')
function GetTextByLanguageI(s, ...)
if s == nil then
s = 'nil'
end
-- 多国处理
if is_number(s) then
local conf = g_conf.info_multi_language[s]
if conf then
s = conf.lang
else
s = tostring(s)
end
end
local args = {...}
if #args == 0 then
return s
else
local ret, _ = string.gsub(s, '%{(%d+)(.-)%}', function(num, decorator)
if decorator ~= '' then
return string.format(decorator, args[tonumber(num)])
else
return tostring(args[tonumber(num)])
end
end)
return ret
end
end
function logic_utils_can_use_spine()
local sub_engine_version = utils_game_get_engine_sub_version()
if sp ~= nil and sub_engine_version ~= 0 and sub_engine_version ~= 100000 then
return true
else
return false
end
end
function utils_coroutinue_download_split_res(res_names, upate_callback)
local downloader = import('logic.logic_data.split_res_downloader')
local co = coroutine.running()
delay_call(0, function()
downloader.download_split_res(res_names, function(status, cur_size, total_size, res_name)
if upate_callback then
upate_callback(status, cur_size, total_size, res_name)
end
if status == downloader.DOWNLOAD_SPLIT_RES_CALLBACK_STATUS.RES_STATUS_ERROR then --下载出错
coroutine.resume(co, false)
elseif status == downloader.DOWNLOAD_SPLIT_RES_CALLBACK_STATUS.RES_STATUS_GROUP_SUCCESSED then --下载成功了
if total_size == 0 then --版本为最新
coroutine.resume(co, true, false)
else
coroutine.resume(co, true, true)
end
elseif status == downloader.DOWNLOAD_SPLIT_RES_CALLBACK_STATUS.RES_STATUS_GROUP_CANCEL then --下载取消了
coroutine.resume(co, true, false)
end
end)
end)
return coroutine.yield()
end
function show_common_download_panel(gameType, callback)
local debug_control = g_native_conf['debug_control']
if debug_control.bSkipUpdate or debug_control.bSkipCheckSplitPackage then
if callback then
callback(true)
end
return
end
local split_res_names = import('logic.logic_data.split_res_manager').get_game_split_res(gameType)
show_common_download_panel_with_split_res_names(split_res_names, callback)
end
function show_common_download_panel_with_split_res_names(split_res_names, callback)
g_panel_mgr.show("common.dlg_common_download_panel", split_res_names, function()
if callback then
callback(true)
end
end)
end
function utils_get_hall_lang_split_res_name(lang)
if not lang then
local curLang = g_native_conf['cur_multilang_index']
lang = curLang
end
if lang == 'cn' then
return g_constant_conf['constant'].CHIINESE_SPLIT_RES_NAME
end
return 'hall_'..lang
end
--尝试初始化大厅的分包信息(主要是给以前的包一个初始的分包版本10000)
function utils_init_hall_lang_split_res_info(lang)
if not lang then
local curLang = g_native_conf['cur_multilang_index']
lang = curLang
end
local split_res_name = utils_get_hall_lang_split_res_name(lang)
if lang ~= 'cn' then
local constant = g_constant_conf['constant']
local sdk_version = utils_get_sdk_version()
local game_split_res_version_info = g_native_conf['game_split_res_version_info']
if sdk_version < constant.GAME_SUPPORT_HALL_SPLIT_RES_MIN_SDK_VERSION then --114 以前的版本是 各种语言的分包都放再一起。为了避免这些包去下载第一个分包,给个初始的版本号
if not game_split_res_version_info[split_res_name] then
game_split_res_version_info[split_res_name] = constant.GAME_SPLIT_RES_MIN_VERSION
end
end
end
end
|
local this = {}
this.uiType = "normal"
this.assetModel = "Test"
this.assetName = "TestUI"
local panel = require("TestUIPanel")
this.Awake = function(gameObject)
panel.Awake(gameObject)
UIEventListener.Get(panel.testBtn.gameObject).onClick = function(go, eventData)
this.TestBtnOnClick(go, eventData)
end
UIEventListener.Get(panel.testImg.gameObject).onDrag = function(go, pos, eventData)
this.TestImgOnDrag(go, pos, eventData)
end
UIEventListener.Get(panel.testRimg.gameObject).onEnter = function(go)
this.TestRimgOnEnter(go)
end
end
this.OnShowPage = function()
end
this.OnClose = function()
end
this.OnDispose = function()
end
this.TestBtnOnClick = function(go, eventData)
end
this.TestImgOnDrag = function(go, pos, eventData)
end
this.TestRimgOnEnter = function(go)
end
return this
|
local haml = require "haml"
local n = 5000
local template = [=[
!!! html
%html
%head
%title Test
%body
%h1 simple markup
%div#content
%ul
- for _, letter in ipairs({"a", "b", "c", "d", "e", "f", "g"}) do
%li= letter
]=]
if arg[1] then
local f = assert(io.open(arg[1]))
template = f:read('*a')
f:close()
end
if arg[2] then
n = tonumber(arg[2]) or n
end
local start = os.clock()
for i = 1,n do
local html = haml.render(template)
end
local done = os.clock()
print "Compile and render:"
print(("%s seconds"):format(done - start))
local phrases = haml.parse(template)
local compiled = haml.compile(phrases)
local start = os.clock()
for i = 1,n do
haml.render(compiled)
end
local done = os.clock()
print "Render:"
print(("%s seconds"):format(done - start)) |
jester.help_map.record = {}
jester.help_map.record.description_short = [[Record sound from a channel.]]
jester.help_map.record.description_long = [[This module provides actions which deal with recording sound from a channel.]]
jester.help_map.record.actions = {}
jester.help_map.record.actions.record = {}
jester.help_map.record.actions.record.description_short = [[Records sound from a channel.]]
jester.help_map.record.actions.record.description_long = [[This action records sound from a channel and stores it.
The recording is in .wav format.
The following variables/values related to the recording are put into Jester storage upon completion of the recording:
last_recording_name:
The name of the recording.
last_recording_path:
A full path to the recording.
last_recording_timestamp:
The timestamp of the recording (when it began).
last_recording_duration:
The duration of the recording in seconds.
]]
jester.help_map.record.actions.record.params = {
filename = [[(Optional) The name of the recorded file. Defaults to %Y-%m-%d_%H:%M:%S-${uuid}.wav]],
location = [[(Optional) Where to store the file. Default is /tmp.]],
append = [[(Optional) Append the recording to an existing file. Requires that the 'filename' parameter be set. If the named file does not exist, then it will be created. Default is false.]],
pre_record_sound = [[(Optional) Set to a file or phrase to play prior to beginning the recording, or to 'tone' to play a typical 'wait for the beep' tone. Default is to do nothing.]],
pre_record_delay = [[(Optional) Set to the number of milliseconds to delay just prior to beginning the recording. This happens after the pre_record_sound is played. This can be useful to tweak if trailing channel sounds are being recording at the beginning of the recording. Set to 0 for no delay. Default is 200 milliseconds.]],
max_length = [[(Optional) Maximum allowed length of the recording in seconds. Default is 180.]],
silence_threshold = [[(Optional) A number indicating the threshhold for what is considered silence. Higher numbers mean more noise will be tolerated. Default is 20. TODO: need to find doc on this.]],
silence_secs = [[(Optional) The number of consecutive seconds of silence to wait before considering the recording finished. Default is 5.]],
storage_area = [[(Optional) If set the 'last_recording' storage values are also stored in this storage area with the 'last_recording_' prefix stripped, eg. 'storage_area = "message"' would store 'name' in the 'message' storage area with the same value as 'last_recording_name'.]],
keys = [[(Optional) See 'help sequences keys'.]],
}
jester.help_map.record.actions.record_merge = {}
jester.help_map.record.actions.record_merge.description_short = [[Merges two recordings.]]
jester.help_map.record.actions.record_merge.description_long = [[This action merges two recorded files into one. The merge file may be appended or prepended to the base file.]]
jester.help_map.record.actions.record_merge.params = {
base_file = [[Full path to the base file for the merge. The will be the file that remains after the merge.]],
merge_file = [[Full path to the merge file for the merge. This file will not longer exist after the merge.]],
merge_type = [[(Optional) The type of merge to perform, valid values are 'append' and 'prepend'. Default is 'append'.]],
}
|
-- Gemeinschaft 5 module: ip calculation functions
-- (c) AMOOMA GmbH 2012-2013
--
module(...,package.seeall)
function ipv4_to_i(ip_address_str)
local octet4, octet3, octet2, octet1 = ip_address_str:match('(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)');
if octet4 and octet3 and octet2 and octet1 then
return (2^24*octet4 + 2^16*octet3 + 2^8*octet2 + octet1);
end
end
function ipv4_to_network_netmask(ip_address_str)
local octet4, octet3, octet2, octet1, netmask = ip_address_str:match('(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)/(%d%d?)');
if octet4 and octet3 and octet2 and octet1 and netmask then
return (2^24*octet4 + 2^16*octet3 + 2^8*octet2 + octet1), tonumber(netmask);
end
end
function ipv4_network(ip_address, netmask)
return math.floor(ip_address / 2^(32-netmask));
end
function ipv4_in_network(ip_address, network, netmask)
return ipv4_network(ip_address, netmask) == ipv4_network(network, netmask);
end
|
local t = require('luatest')
local log = require('log')
local fio = require('fio')
local Cluster = require('test.luatest_helpers.cluster')
local server = require('test.luatest_helpers.server')
local COUNT = 100
local pg = t.group('quorum_misc', {{engine = 'memtx'}, {engine = 'vinyl'}})
pg.before_each(function(cg)
local engine = cg.params.engine
cg.cluster = Cluster:new({})
local box_cfg = {
replication_timeout = 0.1;
replication_connect_timeout = 10;
replication_sync_lag = 0.01;
replication_connect_quorum = 3;
replication = {
server.build_instance_uri('quorum1');
server.build_instance_uri('quorum2');
server.build_instance_uri('quorum3');
};
}
cg.quorum1 = cg.cluster:build_server({alias = 'quorum1', engine = engine, box_cfg = box_cfg})
cg.quorum2 = cg.cluster:build_server({alias = 'quorum2', engine = engine, box_cfg = box_cfg})
cg.quorum3 = cg.cluster:build_server({alias = 'quorum3', engine = engine, box_cfg = box_cfg})
local box_cfg = {
replication_timeout = 0.05,
replication_connect_timeout = 10,
replication_connect_quorum = 1,
replication = {server.build_instance_uri('replica_quorum'),
server.build_instance_uri('replica_quorum1'),
server.build_instance_uri('replica_quorum2')}
}
cg.replica_quorum = cg.cluster:build_server({alias = 'replica_quorum', engine = engine, box_cfg = box_cfg})
pcall(log.cfg, {level = 6})
end)
pg.after_each(function(cg)
cg.cluster.servers = nil
cg.cluster:drop()
end)
pg.before_test('test_quorum_during_reconfiguration', function(cg)
cg.cluster:add_server(cg.replica_quorum)
end)
pg.after_test('test_quorum_during_reconfiguration', function(cg)
cg.cluster:drop({cg.replica_quorum})
end)
pg.test_quorum_during_reconfiguration = function(cg)
-- Test that quorum is not ignored neither during bootstrap, nor
-- during reconfiguration.
cg.replica_quorum:start()
local function cmd(args)
return (box.cfg{
replication = {
os.getenv("TARANTOOL_LISTEN"),
args.nonexistent_uri
}
})
end
local nonexistent_uri = server.build_instance_uri('replica_quorum1')
t.helpers.retrying({timeout = 10},
function()
-- If replication_connect_quorum was ignored here, the instance
-- would exit with an error.
-- XXX: box.cfg() returns nothing in either way, I don't see a
-- point to check it. box.cfg() may raise an error: will it be
-- re-raised here?
t.assert_equals(cg.replica_quorum:exec(cmd, {nonexistent_uri}), nil)
end
)
t.assert_equals(cg.replica_quorum:eval('return box.info.id'), 1)
end
pg.before_test('test_id_for_rebootstrapped_replica_with_removed_xlog',
function(cg)
cg.cluster:add_server(cg.quorum1)
cg.cluster:add_server(cg.quorum2)
cg.cluster:add_server(cg.quorum3)
cg.cluster:start()
local bootstrap_function = function()
box.schema.space.create('test', {engine = os.getenv('TARANTOOL_ENGINE')})
box.space.test:create_index('primary')
end
cg.cluster:exec_on_leader(bootstrap_function)
cg.cluster:wait_fullmesh()
t.helpers.retrying({timeout = 10},
function()
cg.quorum2:eval(
('for i = 1, %d do box.space.test:insert{i} end'):format(COUNT))
end
)
end)
pg.test_id_for_rebootstrapped_replica_with_removed_xlog = function(cg)
cg.quorum1:stop()
fio.rmtree(cg.quorum1.workdir)
fio.mktree(cg.quorum1.workdir)
-- The rebootstrapped replica will be assigned id = 4,
-- because ids 1..3 are busy.
cg.quorum1:start()
t.assert_equals(cg.quorum1.net_box.state, 'active',
'wrong state for server="%s"', cg.quorum1.alias)
t.helpers.retrying({timeout = 10}, function()
t.assert_equals(
cg.quorum1:eval('return box.space.test:count()'), COUNT)
t.assert_equals(
cg.quorum2:eval(
'return box.info.replication[4].upstream.status'), 'follow')
t.assert(cg.quorum3:eval('return box.info.replication ~= nil'))
t.assert_equals(
cg.quorum3:eval(
'return box.info.replication[4].upstream.status'), 'follow')
end)
t.assert_equals(
cg.quorum2:eval('return box.info.replication[4].upstream.status'),
'follow')
t.assert_equals(
cg.quorum3:eval('return box.info.replication[4].upstream.status'),
'follow')
end
|
-------------------------------------------------------------------------------
--
-- tek.lib.region
-- Written by Timm S. Mueller <tmueller at schulze-mueller.de>
-- See copyright notice in COPYRIGHT
--
-- OVERVIEW::
-- This library implements the management of regions, which are
-- collections of non-overlapping rectangles.
--
-- FUNCTIONS::
-- - Region:andRect() - ''And''s a rectangle to a region
-- - Region:andRegion() - ''And''s a region to a region
-- - Region:checkIntersect() - Checks if a rectangle intersects a region
-- - Region:forEach() - Calls a function for each rectangle in a region
-- - Region:get() - Get region's min/max extents
-- - Region.intersect() - Returns the intersection of two rectangles
-- - Region:isEmpty() - Checks if a Region is empty
-- - Region.new() - Creates a new Region
-- - Region:orRect() - ''Or''s a rectangle to a region
-- - Region:orRegion() - ''Or''s a region to a region
-- - Region:setRect() - Resets a region to the given rectangle
-- - Region:shift() - Displaces a region
-- - Region:subRect() - Subtracts a rectangle from a region
-- - Region:subRegion() - Subtracts a region from a region
-- - Region:xorRect() - ''Exclusive Or''s a rectangle to a region
--
-------------------------------------------------------------------------------
local insert = table.insert
local ipairs = ipairs
local max = math.max
local min = math.min
local setmetatable = setmetatable
local unpack = unpack or table.unpack
local Region = { }
Region._VERSION = "Region 11.3"
Region.__index = Region
-------------------------------------------------------------------------------
-- x0, y0, x1, y1 = Region.intersect(d1, d2, d3, d4, s1, s2, s3, s4):
-- Returns the coordinates of a rectangle where a rectangle specified by
-- the coordinates s1, s2, s3, s4 overlaps with the rectangle specified
-- by the coordinates d1, d2, d3, d4. The return value is '''nil''' if
-- the rectangles do not overlap.
-------------------------------------------------------------------------------
function Region.intersect(d1, d2, d3, d4, s1, s2, s3, s4)
if s3 >= d1 and s1 <= d3 and s4 >= d2 and s2 <= d4 then
return max(s1, d1), max(s2, d2), min(s3, d3), min(s4, d4)
end
end
-------------------------------------------------------------------------------
-- insertrect: insert rect to table, merging with an existing one if possible
-------------------------------------------------------------------------------
local function insertrect(d, s1, s2, s3, s4)
for i = 1, min(4, #d) do
local a = d[i]
local a1, a2, a3, a4 = a[1], a[2], a[3], a[4]
if a2 == s2 and a4 == s4 then
if a3 + 1 == s1 then
a[3] = s3
return
elseif a1 == s3 + 1 then
a[1] = s1
return
end
elseif a1 == s1 and a3 == s3 then
if a4 + 1 == s2 then
a[4] = s4
return
elseif a2 == s4 + 1 then
a[2] = s2
return
end
end
end
insert(d, 1, { s1, s2, s3, s4 })
end
-------------------------------------------------------------------------------
-- cutrect: cut rect d into table of new rects, using rect s as a punch
-------------------------------------------------------------------------------
local function cutrect(d1, d2, d3, d4, s1, s2, s3, s4)
if not Region.intersect(d1, d2, d3, d4, s1, s2, s3, s4) then
return { { d1, d2, d3, d4 } }
end
local r = { }
if d1 < s1 then
insertrect(r, d1, d2, s1 - 1, d4)
d1 = s1
end
if d2 < s2 then
insertrect(r, d1, d2, d3, s2 - 1)
d2 = s2
end
if d3 > s3 then
insertrect(r, s3 + 1, d2, d3, d4)
d3 = s3
end
if d4 > s4 then
insertrect(r, d1, s4 + 1, d3, d4)
end
return r
end
-------------------------------------------------------------------------------
-- cutregion: cut region d, using s as a punch
-------------------------------------------------------------------------------
local function cutregion(d, s1, s2, s3, s4)
local r = { }
for _, dr in ipairs(d) do
local d1, d2, d3, d4 = dr[1], dr[2], dr[3], dr[4]
for _, t in ipairs(cutrect(d1, d2, d3, d4, s1, s2, s3, s4)) do
insertrect(r, t[1], t[2], t[3], t[4])
end
end
return r
end
-------------------------------------------------------------------------------
-- region = Region.new(r1, r2, r3, r4): Creates a new region from the given
-- coordinates.
-------------------------------------------------------------------------------
function Region.new(r1, r2, r3, r4)
if r1 then
return setmetatable({ region = { { r1, r2, r3, r4 } } }, Region)
end
return setmetatable({ region = { } }, Region)
end
-------------------------------------------------------------------------------
-- self = region:setRect(r1, r2, r3, r4): Resets an existing region
-- to the specified rectangle.
-------------------------------------------------------------------------------
function Region:setRect(r1, r2, r3, r4)
self.region = { { r1, r2, r3, r4 } }
return self
end
-------------------------------------------------------------------------------
-- region:orRect(r1, r2, r3, r4): Logical ''or''s a rectangle to a region
-------------------------------------------------------------------------------
function Region:orRect(s1, s2, s3, s4)
self.region = cutregion(self.region, s1, s2, s3, s4)
insertrect(self.region, s1, s2, s3, s4)
end
-------------------------------------------------------------------------------
-- region:orRegion(region): Logical ''or''s another region to a region
-------------------------------------------------------------------------------
function Region:orRegion(s)
for _, r in ipairs(s) do
self:orRect(r[1], r[2], r[3], r[4])
end
end
-------------------------------------------------------------------------------
-- region:andRect(r1, r2, r3, r4): Logical ''and''s a rectange to a region
-------------------------------------------------------------------------------
function Region:andRect(s1, s2, s3, s4)
local r = { }
for _, d in ipairs(self.region) do
local t1, t2, t3, t4 =
Region.intersect(d[1], d[2], d[3], d[4], s1, s2, s3, s4)
if t1 then
insertrect(r, t1, t2, t3, t4)
end
end
self.region = r
end
-------------------------------------------------------------------------------
-- region:xorRect(r1, r2, r3, r4): Logical ''xor''s a rectange to a region
-------------------------------------------------------------------------------
function Region:xorRect(s1, s2, s3, s4)
local r1 = { }
local r2 = { { s1, s2, s3, s4 } }
for _, d in ipairs(self.region) do
local d1, d2, d3, d4 = d[1], d[2], d[3], d[4]
for _, t in ipairs(cutrect(d1, d2, d3, d4, s1, s2, s3, s4)) do
insertrect(r1, t[1], t[2], t[3], t[4])
end
r2 = cutregion(r2, d1, d2, d3, d4)
end
self.region = r1
self:orRegion(r2)
end
-------------------------------------------------------------------------------
-- self = region:subRect(r1, r2, r3, r4): Subtracts a rectangle from a region
-------------------------------------------------------------------------------
function Region:subRect(s1, s2, s3, s4)
local r1 = { }
for _, d in ipairs(self.region) do
local d1, d2, d3, d4 = d[1], d[2], d[3], d[4]
for _, t in ipairs(cutrect(d1, d2, d3, d4, s1, s2, s3, s4)) do
insertrect(r1, t[1], t[2], t[3], t[4])
end
end
self.region = r1
return self
end
-------------------------------------------------------------------------------
-- region:getRect - gets an iterator on the rectangles in a region [internal]
-------------------------------------------------------------------------------
function Region:getRects()
local index = 0
return function(object)
index = index + 1
if object[index] then
return unpack(object[index])
end
end, self.region
end
-------------------------------------------------------------------------------
-- success = region:checkIntersect(x0, y0, x1, y1): Returns a boolean
-- indicating whether a rectangle specified by its coordinates overlaps
-- with a region.
-------------------------------------------------------------------------------
function Region:checkIntersect(s1, s2, s3, s4)
for _, d in ipairs(self.region) do
if Region.intersect(d[1], d[2], d[3], d[4], s1, s2, s3, s4) then
return true
end
end
return false
end
-------------------------------------------------------------------------------
-- region:subRegion(region2): Subtracts {{region2}} from {{region}}.
-------------------------------------------------------------------------------
function Region:subRegion(region)
if region then
for r1, r2, r3, r4 in region:getRects() do
self:subRect(r1, r2, r3, r4)
end
end
end
-------------------------------------------------------------------------------
-- region:andRegion(r): Logically ''and''s a region to a region
-------------------------------------------------------------------------------
function Region:andRegion(s)
local r = { }
for _, s in ipairs(s.region) do
for _, d in ipairs(self.region) do
local t1, t2, t3, t4 =
Region.intersect(d[1], d[2], d[3], d[4],
s[1], s[2], s[3], s[4])
if t1 then
insertrect(r, t1, t2, t3, t4)
end
end
end
self.region = r
end
-------------------------------------------------------------------------------
-- region:forEach(func, obj, ...): For each rectangle in a region, calls the
-- specified function according the following scheme:
-- func(obj, x0, y0, x1, y1, ...)
-- Extra arguments are passed through to the function.
-------------------------------------------------------------------------------
function Region:forEach(func, obj, ...)
for x0, y0, x1, y1 in self:getRects() do
func(obj, x0, y0, x1, y1, ...)
end
end
-------------------------------------------------------------------------------
-- region:shift(dx, dy): Shifts a region by delta x and y.
-------------------------------------------------------------------------------
function Region:shift(dx, dy)
for _, r in ipairs(self.region) do
r[1] = r[1] + dx
r[2] = r[2] + dy
r[3] = r[3] + dx
r[4] = r[4] + dy
end
end
-------------------------------------------------------------------------------
-- region:isEmpty(): Returns '''true''' if a region is empty.
-------------------------------------------------------------------------------
function Region:isEmpty()
return #self.region == 0
end
-------------------------------------------------------------------------------
-- minx, miny, maxx, maxy = region:get(): Get region's min/max extents
-------------------------------------------------------------------------------
function Region:get()
if #self.region > 0 then
local minx = 1000000 -- ui.HUGE
local miny = 1000000
local maxx = 0
local maxy = 0
for _, r in ipairs(self.region) do
minx = min(minx, r[1])
miny = min(miny, r[2])
maxx = max(maxx, r[3])
maxy = max(maxy, r[4])
end
return minx, miny, maxx, maxy
end
end
return Region
|
-- Create the MF object --
if global.mobileFactory ~= nil then
global.upsysTickTable = {}
global.entsTable = {}
game.print("Mobile Factory to OOP Update")
-- Copy all variables --
global.MF = MF:new(global.mobileFactory)
local MF = global.MF
MF.fS = global.factorySurface
MF.ccS = global.controlSurface
MF.fChest = global.factoryChest
MF.internalEnergy = global.mfInternalEnergy
MF.maxInternalEnergy = global.mfInternalEnergyMax
MF.jumpTimer = global.mfJumpTimer
MF.baseJumpTimer = global.mfBaseJumpTimer
MF.laserRadiusMultiplier = global.mfEnergyRadiusMult
MF.laserDrainMultiplier = global.mfEnergyDrainMult
MF.laserNumberMultiplier = global.mfEnergyLaserMult
MF.energyLaserActivated = global.mfEnergyLaserActivated
MF.fluidLaserActivated = global.mfFluidDrainLaserActivated
MF.itemLaserActivated = global.mfItemDistributionActivated
MF.internalEnergyDistributionActivated = global.mfEnergyDistributionActivated
-- Set old variables to nil --
global.mobileFactory = nil
global.factorySurface = nil
global.controlSurface = nil
global.factoryChest = nil
global.mfInternalEnergy = nil
global.mfInternalEnergyMax = nil
global.mfJumpTimer = nil
global.mfBaseJumpTimer = nil
global.mfEnergyRadiusMult = nil
global.mfEnergyDrainMult = nil
global.mfEnergyLaserMult = nil
global.mfEnergyLaserActivated = nil
global.mfFluidDrainLaserActivated = nil
global.mfItemDistributionActivated = nil
global.mfEnergyDistributionActivated = nil
end |
-- @docclass
ProtocolLogin = extends(Protocol)
-- private functions
local function sendLoginPacket(protocol)
local msg = OutputMessage.create()
msg:addU8(ClientEnterAccount)
msg:addU16(1) -- todo: ClientOs
msg:addU16(g_game.getClientVersion())
msg:addU32(g_things.getDatSignature())
msg:addU32(g_sprites.getSprSignature())
msg:addU32(0) -- todo: pic signature
local paddingBytes = 128
msg:addU8(0) -- first RSA byte must be 0
paddingBytes = paddingBytes - 1
-- xtea key
protocol:generateXteaKey()
local xteaKey = protocol:getXteaKey()
msg:addU32(xteaKey[1])
msg:addU32(xteaKey[2])
msg:addU32(xteaKey[3])
msg:addU32(xteaKey[4])
paddingBytes = paddingBytes - 16
if g_game.getFeature(GameProtocolChecksum) then
protocol:enableChecksum()
end
if g_game.getFeature(GameAccountNames) then
msg:addString(protocol.accountName)
msg:addString(protocol.accountPassword)
paddingBytes = paddingBytes - (4 + string.len(protocol.accountName) + string.len(protocol.accountPassword))
else
msg:addU32(tonumber(protocol.accountName))
msg:addString(protocol.accountPassword)
paddingBytes = paddingBytes - (6 + string.len(protocol.accountPassword))
end
msg:addPaddingBytes(paddingBytes, 0)
msg:encryptRSA(128, OTSERV_RSA) -- todo: check whether to use cip or ot rsa
protocol:send(msg)
protocol:enableXteaEncryption()
protocol:recv()
end
-- events
function ProtocolLogin:onConnect()
self:connectCallback(self)
end
function ProtocolLogin:onRecv(msg)
while not msg:eof() do
local opcode = msg:getU8()
if opcode == LoginServerError then
self:parseError(msg)
elseif opcode == LoginServerMotd then
self:parseMotd(msg)
elseif opcode == LoginServerUpdateNeeded then
signalcall(self.onError, self, "Client needs update.")
elseif opcode == LoginServerCharacterList then
self:parseCharacterList(msg)
else
self:parseOpcode(opcode, msg)
end
end
self:disconnect()
end
-- public functions
function ProtocolLogin.create()
return ProtocolLogin.internalCreate()
end
function ProtocolLogin:login(host, port, accountName, accountPassword)
if string.len(accountName) == 0 or string.len(accountPassword) == 0 then
signalcall(self.onError, self, "You must enter an account name and password.")
return
end
self.accountName = accountName
self.accountPassword = accountPassword
self.connectCallback = sendLoginPacket
self:connect(host, port)
end
function ProtocolLogin:cancelLogin()
self:disconnect()
end
function ProtocolLogin:parseError(msg)
local errorMessage = msg:getString()
signalcall(self.onError, self, errorMessage)
end
function ProtocolLogin:parseMotd(msg)
local motd = msg:getString()
signalcall(self.onMotd, self, motd)
end
function ProtocolLogin:parseCharacterList(msg)
local characters = {}
local charactersCount = msg:getU8()
for i=1,charactersCount do
local character = {}
character[1] = msg:getString()
character[2] = msg:getString()
character[3] = iptostring(msg:getU32())
character[4] = msg:getU16()
characters[i] = character
end
local premDays = msg:getU16()
signalcall(self.onCharacterList, self, characters, premDays)
end
function ProtocolLogin:parseOpcode(opcode, msg)
signalcall(self.onOpcode, self, opcode, msg)
end
|
local pdk = require("apioak.pdk")
local table_name = "oak_upstreams"
local _M = {}
_M.table_name = table_name
function _M.all()
local sql = pdk.string.format("SELECT * FROM %s", table_name)
local res, err = pdk.database.execute(sql)
if err then
return nil, err
end
for i = 1, #res do
res[i].nodes = pdk.json.decode(res[i].nodes)
res[i].timeouts = pdk.json.decode(res[i].timeouts)
end
return res, nil
end
function _M.create(params)
local sql = pdk.string.format([[
INSERT INTO %s (
env,
host,
type,
project_id,
timeouts,
nodes
)
VALUES (%s, %s, %s, %s, %s, %s)
]], table_name,
ngx.quote_sql_str(params.env),
ngx.quote_sql_str(params.host),
ngx.quote_sql_str(params.type),
ngx.quote_sql_str(params.project_id),
ngx.quote_sql_str(pdk.json.encode(params.timeouts)),
ngx.quote_sql_str(pdk.json.encode(params.nodes)))
local res, err = pdk.database.execute(sql)
if err then
return nil, err
end
return res, nil
end
function _M.update_by_pid(pid, upstream)
local sql = pdk.string.format([[
UPDATE
%s
SET
host = %s, type = %s, timeouts = %s, nodes = %s
WHERE
id = %s AND project_id = %s
]], table_name,
ngx.quote_sql_str(upstream.host),
ngx.quote_sql_str(upstream.type),
ngx.quote_sql_str(pdk.json.encode(upstream.timeouts)),
ngx.quote_sql_str(pdk.json.encode(upstream.nodes)),
ngx.quote_sql_str(upstream.id),
ngx.quote_sql_str(pid))
local res, err = pdk.database.execute(sql)
if err then
return nil, err
end
return res, nil
end
function _M.query(upstream_id)
local sql = pdk.string.format("SELECT * FROM %s WHERE id = %s", table_name, ngx.quote_sql_str(upstream_id))
local res, err = pdk.database.execute(sql)
if err then
return nil, err
end
return res, nil
end
function _M.query_by_pid(project_id)
local sql = pdk.string.format("SELECT * FROM %s WHERE project_id = %s", table_name, ngx.quote_sql_str(project_id))
local res, err = pdk.database.execute(sql)
if err then
return nil, err
end
for i = 1, #res do
res[i].nodes = pdk.json.decode(res[i].nodes)
res[i].timeouts = pdk.json.decode(res[i].timeouts)
end
return res, nil
end
function _M.delete_by_pid(project_id)
local sql = pdk.string.format("DELETE FROM %s WHERE project_id = %s", table_name, ngx.quote_sql_str(project_id))
local res, err = pdk.database.execute(sql)
if err then
return nil, err
end
return res, nil
end
function _M.query_last_updated_hid()
local sql = pdk.string.format(
"SELECT MD5(updated_at) AS hash_id FROM %s ORDER BY updated_at DESC LIMIT 1", table_name)
local res, err = pdk.database.execute(sql)
if err then
return nil, err
end
if #res == 0 then
return res, nil
end
return res[1], nil
end
return _M
|
local backpack_qn_pin_map = require("qnFiles/qnPlist/hall/backpack_qn_pin");
local newObjectCase_pin_map = require("qnFiles/qnPlist/hall/newObjectCase_pin");
local newObjectCaseRecordNotice=
{
name="newObjectCaseRecordNotice",type=0,typeName="View",time=0,x=0,y=0,width=1280,height=720,visible=1,nodeAlign=kAlignTopLeft,fillParentWidth=1,fillParentHeight=1,
{
name="Image_mask",type=0,typeName="Image",time=108131269,x=165,y=286,width=1280,height=720,nodeAlign=kAlignTopLeft,visible=0,fillParentWidth=1,fillParentHeight=1,file="isolater/bg_shiled.png"
},
{
name="ImageBack",type=0,typeName="Image",time=108131298,x=0,y=0,width=723,height=720,nodeAlign=kAlignRight,visible=1,fillParentWidth=0,fillParentHeight=1,file=backpack_qn_pin_map['backpack_bg.png'],gridLeft=55,gridRight=55,gridTop=55,gridBottom=55,callbackfunc="onBindBlankFunc",varname="ImageBack",
{
name="Image_tittle_bg",type=1,typeName="Image",time=0,x=0,y=0,width=700,height=82,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopRight,file=backpack_qn_pin_map['backpack_tittle_bg.png'],
{
name="Image_tittle",type=4,typeName="Text",time=0,x=0,y=0,width=128,height=36,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=32,textAlign=kAlignLeft,colorRed=159,colorGreen=115,colorBlue=50,string=[[兑换成功]],colorA=1,varname="Image_tittle"
},
{
name="Image_tittle_shard",type=4,typeName="Text",time=0,x=0,y=0,width=128,height=36,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=32,textAlign=kAlignLeft,colorRed=159,colorGreen=115,colorBlue=50,string=[[合成成功]],colorA=1,varname="Image_tittle_shard"
},
{
name="Image_tittle__fail",type=4,typeName="Text",time=0,x=0,y=0,width=128,height=36,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=32,textAlign=kAlignLeft,colorRed=159,colorGreen=115,colorBlue=50,string=[[充值失败]],colorA=1,varname="Image_tittle__fail"
}
},
{
name="Image_bg2",type=1,typeName="Image",time=0,x=10,y=15,width=659,height=615,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom,file="hall/common/bg_blank.png",gridLeft=10,gridRight=10,gridTop=10,gridBottom=10,fillTopLeftX=40,fillBottomRightX=24,fillTopLeftY=90,fillBottomRightY=15,
{
name="describeFrame",type=0,typeName="Image",time=108131306,x=0,y=180,width=562,height=86,nodeAlign=kAlignBottom,visible=1,fillParentWidth=0,fillParentHeight=0,file=backpack_qn_pin_map['backpack_des_bg.png'],gridLeft=8,gridRight=8,gridTop=8,gridBottom=8,varname="describeFrame",
{
name="TextView_des",type=0,typeName="TextView",time=108131307,x=0,y=1,width=540,height=70,nodeAlign=kAlignCenter,visible=1,fillParentWidth=0,fillParentHeight=0,fontSize=26,textAlign=kAlignTopLeft,colorRed=143,colorGreen=92,colorBlue=31,colorA=1,varname="TextView_des",string=[[士大夫但是但是发射点犯得上反对撒法大沙发]]
},
{
name="View_forOrder",type=0,typeName="View",time=0,x=0,y=0,width=540,height=80,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,varname="View_forOrder",
{
name="Text_company",type=4,typeName="Text",time=0,x=0,y=-15,width=120,height=27,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,fontSize=20,textAlign=kAlignLeft,colorRed=143,colorGreen=92,colorBlue=31,string=[[承运公司:]],colorA=1,varname="Text_company"
},
{
name="View_orderFrame",type=0,typeName="View",time=0,x=100,y=10,width=300,height=30,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,varname="View_orderFrame",callbackfunc="onBindToCopyOrder"
},
{
name="Text_company25",type=4,typeName="Text",time=0,x=0,y=15,width=120,height=27,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,fontSize=20,textAlign=kAlignLeft,colorRed=143,colorGreen=92,colorBlue=31,string=[[运单编号:]],colorA=1
}
}
},
{
name="View_clientPhone",type=0,typeName="View",time=108131317,x=50,y=0,width=286,height=40,nodeAlign=kAlignBottomRight,visible=1,fillParentWidth=0,fillParentHeight=0,varname="View_clientPhone",callbackfunc="onBindToCallPhone",
{
name="phoneLogo",type=0,typeName="Image",time=108131318,x=0,y=5,width=20,height=21,nodeAlign=kAlignBottomRight,visible=1,fillParentWidth=0,fillParentHeight=0,file=newObjectCase_pin_map['newCase_greePhone.png'],varname="phoneLogo"
},
{
name="View_phoneNumber",type=0,typeName="View",time=0,x=0,y=5,width=10,height=10,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottomRight,varname="View_phoneNumber"
}
},
{
name="View33",type=0,typeName="View",time=0,x=151,y=216,width=659,height=345,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft,fillBottomRightY=270,fillTopLeftX=0,fillBottomRightX=0,fillTopLeftY=0,
{
name="Image_succes",type=1,typeName="Image",time=0,x=0,y=-43,width=529,height=278,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file=backpack_qn_pin_map['backpack_succes.png'],varname="Image_succes",
{
name="View_icon_bg",type=0,typeName="View",time=0,x=0,y=75,width=100,height=100,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom,varname="View_icon_bg"
}
},
{
name="Text_congratulation",type=4,typeName="Text",time=0,x=0,y=130,width=170,height=39,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=34,textAlign=kAlignCenter,colorRed=224,colorGreen=71,colorBlue=19,colorA=1,varname="Text_congratulation"
},
{
name="ImageFail",type=0,typeName="Image",time=108131050,x=0,y=-30,width=158,height=160,nodeAlign=kAlignCenter,visible=0,fillParentWidth=0,fillParentHeight=0,file=backpack_qn_pin_map['backpack_box.png'],varname="ImageFail",
{
name="Image_icon_fail",type=0,typeName="Image",time=108131051,x=0,y=0,width=130,height=130,nodeAlign=kAlignCenter,visible=1,fillParentWidth=0,fillParentHeight=0,file="hall/common/bg_blank.png",varname="Image_icon_fail"
},
{
name="Text_fail_name",type=4,typeName="Text",time=0,x=0,y=215,width=204,height=39,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,fontSize=34,textAlign=kAlignCenter,colorRed=224,colorGreen=71,colorBlue=19,colorA=1,varname="Text_fail_name"
},
{
name="Image32",type=1,typeName="Image",time=0,x=0,y=-40,width=198,height=58,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom,file=backpack_qn_pin_map['backpack_recharge_fail.png']
}
}
},
{
name="Button_share_friend",type=1,typeName="Button",time=0,x=50,y=70,width=265,height=80,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottomLeft,file=backpack_qn_pin_map['backpack_share_bg.png'],gridLeft=8,gridRight=8,gridTop=8,gridBottom=8,varname="Button_share_friend",callbackfunc="onBindToShareFried",
{
name="Image34",type=1,typeName="Image",time=0,x=24,y=0,width=62,height=48,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,file=backpack_qn_pin_map['backpack_share_friend.png']
},
{
name="Text35",type=4,typeName="Text",time=0,x=100,y=0,width=130,height=29,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,fontSize=26,textAlign=kAlignLeft,colorRed=143,colorGreen=92,colorBlue=31,string=[[分享给好友]],colorA=1
}
},
{
name="Button_share_circle",type=1,typeName="Button",time=0,x=50,y=70,width=265,height=80,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottomRight,file=backpack_qn_pin_map['backpack_share_bg.png'],gridLeft=8,gridRight=8,gridTop=8,gridBottom=8,varname="Button_share_circle",callbackfunc="onBindToCircle",
{
name="Image34",type=1,typeName="Image",time=0,x=18,y=0,width=62,height=48,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,file=backpack_qn_pin_map['backpack_share_circle.png']
},
{
name="Text35",type=4,typeName="Text",time=0,x=93,y=0,width=156,height=29,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,fontSize=26,textAlign=kAlignLeft,colorRed=143,colorGreen=92,colorBlue=31,string=[[分享到朋友圈]],colorA=1
}
}
},
{
name="closeBtn",type=0,typeName="Button",time=108131047,x=43,y=10,width=80,height=57,nodeAlign=kAlignTopLeft,visible=1,fillParentWidth=0,fillParentHeight=0,file="hall/backpack/backpack_btn_bg.png",gridLeft=20,gridRight=20,gridTop=20,gridBottom=20,varname="closeBtn",callbackfunc="oncloseBtnClick",
{
name="Image18",type=1,typeName="Image",time=0,x=0,y=0,width=39,height=39,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file=backpack_qn_pin_map['backpack_back.png']
}
}
}
}
return newObjectCaseRecordNotice; |
-- TokenRing.lua
local Computicle = require("Computicle");
local TokenRing = {
Messages = {
DELIVER = 101,
},
}
setmetatable(TokenRing, {
__call = function(self, ...)
return self:create(...);
end,
});
local TokenRing_mt = {
__index = TokenRing,
}
TokenRing.init = function(self, nodelist)
local obj = {
NodeList = nodelist;
}
setmetatable(obj, TokenRing_mt);
return obj;
end
TokenRing.create = function(self, nEntries)
print("TokenRing.create: ", nEntries);
local nodelist = {}
for i=1,nEntries do
local node = Computicle:load("comp_tokenring_node");
node.NodeId = i;
table.insert(nodelist, node);
-- connect the nodes together
if i > 1 then
nodelist[i-1].next = node;
end
-- link the ending node back to the beginning node
if i == nEntries then
node.next = nodelist[1];
end
end
return self:init(nodelist);
end
TokenRing.deliver = function(self, msg, nodeid)
nodeid = nodeid or 1;
self.NodeList[1]:receiveMessage(TokenRing.Messages.DELIVER, nodeid, msg)
end
TokenRing.awaitFinish = function(self)
return self.NodeList[1]:waitForFinish();
end
return TokenRing
|
--[[----------------------------------------------------------------------------
Application Name: 02_3dViewer
Summary:
Show the pointcloud that the camera acquired
Description:
Set up the camera to take live images continuously. React to the "OnNewImage"
event and show the pointcloud in an 3D viewer
How to run:
First set this app as main (right-click -> "Set as main").
Start by running the app (F5) or debugging (F7+F10).
Set a breakpoint on the first row inside the main function to debug step-by-step.
See the results in the different image viewer on the DevicePage.
More Information:
See the tutorial Visionary-T AP FirstSteps
------------------------------------------------------------------------------]]
-- Setup the camera
local camera = Image.Provider.Camera.create()
Image.Provider.Camera.stop(camera)
local cameraModel = Image.Provider.Camera.getInitialCameraModel(camera)
--setup the pointcloud converter
local pointCloudConverter = Image.PointCloudConverter.create(cameraModel)
--setup the view
local view3D = View.create('3DViewer')
local function main()
Image.Provider.Camera.start(camera)
end
--The following registration is part of the global scope which runs once after startup
--Registration of the 'main' function to the 'Engine.OnStarted' event
Script.register('Engine.OnStarted', main)
--@handleOnNewImage(image:Image,sensordata:SensorData)
local function handleOnNewImage(image)
-- Convert to point cloud, first argument is the distance image, second one is the intensity image
local convert =
Image.PointCloudConverter.convert(pointCloudConverter, image[1], image[2])
-- Add the point cloud to the viewer and then present
View.addPointCloud(view3D, convert)
View.present(view3D)
end
Image.Provider.Camera.register(camera, 'OnNewImage', handleOnNewImage)
|
local match = string.match
local G = ...
local id = G.ID("requireselectedmodule.requireselectedmodule")
local menuid
local function getEOLCharacter()
-- it would be nice if I could reference the
-- mode constants directly but AFAICT I can't
local EOLMode = GetEditor():GetEOLMode()
if EOLMode == 0 then
return "\r\n"
elseif EOLMode == 1 then
return "\r"
else
return "\n"
end
end
local function requireSelectedModule()
local editor = GetEditor()
local lineNumber = editor:GetCurrentLine()
local currentLine = editor:GetLine(lineNumber)
--scan upwards for any require statements
while lineNumber > 0
and not (match(currentLine, "require%s+%(?\"")) do
lineNumber = lineNumber - 1
currentLine = editor:GetLine(lineNumber)
end
local selection = editor:GetSelectedText()
local requireText = "local " .. selection .. " = require(\"" .. selection .. "\")" .. getEOLCharacter()
editor:GotoLine(lineNumber)
editor:InsertText(-1, requireText)
editor:LineEnd()
end
return {
name = "requireselectedmodule",
description = "require a module with a filename equal to selected fragment.",
author = "Ryan Wiedemann",
version = 0.1,
dependencies = 1.10, -- just the first thing I tested it on
onRegister = function(self)
-- add menu item that will activate popup menu
local menu = ide:GetMenuBar():GetMenu(ide:GetMenuBar():FindMenu(TR("&Edit")))
menuid = menu:Append(id, "Require selected module\tCtrl-M")
ide:GetMainFrame():Connect(id, wx.wxEVT_COMMAND_MENU_SELECTED, requireSelectedModule)
end,
onUnRegister = function(self)
-- remove added menu item when plugin is unregistered
local menu = ide:GetMenuBar():GetMenu(ide:GetMenuBar():FindMenu(TR("&Edit")))
ide:GetMainFrame():Disconnect(id, wx.wxID_ANY, wx.wxEVT_COMMAND_MENU_SELECTED)
if menuid then menu:Destroy(menuid) end
end,
onMenuEditor = function(self, menu, editor, event)
-- add a separator and a sample menu item to the popup menu
menu:AppendSeparator()
menu:Append(id, "Require selected module")
-- attach a function to the added menu item
editor:Connect(id, wx.wxEVT_COMMAND_MENU_SELECTED, requireSelectedModule)
end
}
|
package.path = "../../?.lua;" .. package.path
local Modern = require 'modern'
--
local M1 = Modern:extend()
function M1:new() print('M1:new') self:foo() end
function M1:foo() print('M1:foo') self:bar() end
function M1:bar() print('M1:bar') end
--
local M2 = Modern:extend()
function M2:new() print('M2:new') end
function M2:foo() print('M2:foo') end
function M2:bar() print('M1:bar') end
--
local MM = Modern:extend(M1, M2)
function MM:new() print('MM:new') end
function MM:foo() print('MM:foo') end
--
local mm = MM() |
--- AceConfigTab-3.0 provides support for tab-completion to AceConfig tables.
-- Note: This library is not yet finalized.
-- @class file
-- @name AceConfigTab-3.0
-- @release $Id: AceConfigTab-3.0.lua 769 2009-04-04 11:05:08Z nevcairiel $
local MAJOR, MINOR = "AceConfigTab-3.0", 1
local lib = LibStub:NewLibrary(MAJOR, MINOR)
if not lib then return end
local ac = LibStub("AceConsole-3.0")
local function printf(...)
DEFAULT_CHAT_FRAME:AddMessage(string.format(...))
end
-- getChildren(opt, ...)
--
-- Retrieve the next valid group args in an AceConfig table.
--
-- opt - AceConfig options table
-- ... - args following the slash command
--
-- opt will need to be determined by the slash-command
-- The args will be obtained using AceConsole:GetArgs() or something similar on the remainder of the line.
--
-- Returns arg1, arg2, ...
local function getLevel(opt, ...)
-- Walk down the options tree to the last arg in the commandline, or return if it does not follow the tree.
local path = ""
local lastChild
for i = 1, select('#', ...) do
local arg = select(i, ...)
if not arg or type(arg) == 'number' then break end
if opt.plugins then
for k in pairs(opt.plugins) do
if string.lower(k) == string.lower(arg) then
opt = opt.plugins[k]
path = path..arg.." "
lastChild = arg
break
end
end
elseif opt.args then
for k in pairs(opt.args) do
if string.lower(k) == string.lower(arg) then
opt = opt.args[k]
path = path..arg.." "
lastChild = arg
break
end
end
else
break
end
end
return opt, path
end
local function getChildren(opt, ...)
local lastChild, path
opt, path, lastChild = getLevel(opt, ...)
local args = {}
for _, field in ipairs({"args", "plugins"}) do
if type(opt[field]) == 'table' then
for k in pairs(opt[field]) do
if opt[field].type ~= 'header' then
table.insert(args, k)
end
end
end
end
return args, path
end
--LibStub("AceConfig-3.0"):RegisterOptionsTable("ag_UnitFrames", aUF.Options.table)
local function createWordlist(t, cmdline, pos)
local cmd = string.match(cmdline, "(/[^ \t\n]+)")
local argslist = string.sub(cmdline, pos, this:GetCursorPosition())
local opt -- TODO: figure out options table using cmd
opt = LibStub("AceConfigRegistry-3.0"):GetOptionsTable("ag_UnitFrames", "cmd", "AceTab-3.0") -- hardcoded temporarily for testing
if not opt then return end
local args, path = getChildren(opt, ac:GetArgs(argslist, #argslist/2)) -- largest # of args representable by a string of length #argslist, since they must be separated by spaces
for _, v in ipairs(args) do
table.insert(t, path..v)
end
end
local function usage(t, matches, _, cmdline)
local cmd = string.match(cmdline, "(/[^ \t\n]+)")
local argslist = string.sub(cmdline, #cmd, this:GetCursorPosition())
local opt -- TODO: figure out options table using cmd
opt = LibStub("AceConfigRegistry-3.0"):GetOptionsTable("ag_UnitFrames")("cmd", "AceTab-3.0") -- hardcoded temporarily for testing
if not opt then return end
local level = getLevel(opt, ac:GetArgs(argslist, #argslist/2)) -- largest # of args representable by a string of length #argslist, since they must be separated by spaces
local option
for _, m in pairs(matches) do
local tail = string.match(m, "([^ \t\n]+)$")
option = level.plugins and level.plugins[tail] or level.args and level.args[tail]
printf("%s - %s", tail, option.desc)
end
end
LibStub("AceTab-3.0"):RegisterTabCompletion("aguftest", "%/%w+ ", createWordlist, usage)
|
fugue.particles = {}
function fugue.initParticles()
for i = 1, 100, 1 do
fugue.particles[i] = {}
local p = fugue.particles[i]
p.pos = vec3d(0,0,0)
p.vel = vec3d(0,0,0)
p.active = false
end
end
fugue.initParticles()
function fugue.updateParticles()
local activationCountdown = 10
for i = 1,100,1 do
local p = fugue.particles[i]
if p.active == true then
p.pos = p.pos + p.vel * 0.3
p.vel = p.vel + vec3d(0,-1,0) * 0.2
if p.pos.y < 0 then
p.active = false
end
else
if activationCountdown > 0 and g_wrapItUp ~= 0 then
-- prime the particle
p.pos = cvec3d(fugue.demiurge[1])
p.pos = fugue.demiurge[math.random(2)] + vec3d(50,0,0)
--p.pos.y = 60
p.vel = vec3d(math.random(20) - 10, math.random(6)-3, math.random(6)-3)
p.active = true
activationCountdown = activationCountdown - 1
end
end
end
end
function fugue.renderParticles()
colorGL(200,180, 90)
for i = 1,100,1 do
local p = fugue.particles[i]
if p.active == true then
drawLine(p.pos.x,
p.pos.y,
p.pos.z,
p.pos.x + p.vel.x,
p.pos.y + p.vel.y,
p.pos.z + p.vel.z)
end
end
end
function fugue.renderDemiurge()
fugue.updateParticles()
fugue.updateParticles()
fugue.updateParticles()
fugue.renderParticles()
end
function fugue.renderSheet(nTotal, nAhead)
colorGL(50, 50, 150 + math.random(20))
beginQuadGL()
for i = 1, nTotal, 1 do
local nindex = fugue.currnote - i + nAhead
if nindex <= #fugue.lines[1] and nindex > 0 then
local note = fugue.lines[1][nindex]
if note.isRest == nil then
local pos = note.degree * 5 +
(note.octave + 2) * 35
vectorGL(i * 10, pos, 200)
vectorGL((i+1) * 10, pos, 200)
vectorGL((i+1) * 10, pos - 5, 200)
vectorGL(i * 10, pos - 5, 200)
end
end
end
endGL()
colorGL(150 + math.random(20),50,50)
beginQuadGL()
for i = 1, nTotal, 1 do
local nindex = fugue.currnote - i + nAhead
if nindex <= #fugue.lines[2] and nindex > 0 then
local note = fugue.lines[2][nindex]
if note.isRest == nil then
local pos = note.degree * 5 +
(note.octave + 2) * 35
vectorGL(i * 10, pos, 200)
vectorGL((i+1) * 10, pos, 200)
vectorGL((i+1) * 10, pos - 5, 200)
vectorGL(i * 10, pos - 5, 200)
end
end
end
endGL()
end
-- function fugue.render()
-- renderGear(50,50,50, 20, fugue.gpos)
-- renderGear(50,50,92, 20, -fugue.gpos+math.pi*0.05)
-- renderGear(92,50,50, 20, -fugue.gpos+math.pi*0.05)
-- fugue.gpos = fugue.gpos + math.pi*0.01
-- end
fugue.demiurge = {}
fugue.demiurge[1] = vec3d(0,0,0)
fugue.demiurge[2] = vec3d(0,0,0)
function fugue.renderGear(x, y, z, radius, trackNum, noteColor, nTotal, nAhead)
local nnotes = nTotal
local angstep = (math.pi * 2)/nnotes
--local angbegin = fugue.currnote * angstep * 1.0 * 0
local angbegin = nAhead * angstep * -1.0
if trackNum % 2 == 1 then
angbegin = angbegin * -1
angstep = angstep * -1
angbegin = angbegin + angstep * 0.5 + math.pi
end
local c = vec3d(x,y,z)
colorGL(noteColor.red, noteColor.green, noteColor.blue)
local ang = angbegin
beginQuadGL()
for i = 1, nnotes, 1 do
if i == nAhead then
colorGL(200, 200, 0)
else
colorGL(noteColor.red, noteColor.green, noteColor.blue)
end
local nindex = fugue.currnote - i + nAhead
if nindex <= #fugue.lines[trackNum] and nindex > 0 then
local note = fugue.lines[trackNum][nindex]
local npos = note.degree * 2 +
note.octave * 14 + 30
local p1 = rvec3d(radius-2, ang) + c
local p2 = rvec3d(radius-2, ang+angstep) + c
if i == nAhead then
fugue.demiurge[trackNum] = vec3d(c.x - 50, p1.y + npos - 1.5, p1.z)
vectorGL(c.x - 50, p1.y + npos - 2, p1.z)
vectorGL(c.x + 50, p2.y + npos - 2, p2.z)
vectorGL(c.x + 50, p2.y + npos, p2.z)
vectorGL(c.x - 50, p1.y + npos, p1.z)
else
vectorGL(p1.x, p1.y + npos - 2, p1.z)
vectorGL(p2.x, p2.y + npos - 2, p2.z)
vectorGL(p2.x, p2.y + npos, p2.z)
vectorGL(p1.x, p1.y + npos, p1.z)
end
end
ang = ang + angstep
end
endGL()
end
|
local BitBuffer = require("bitBuffer")
local buffer = BitBuffer()
local clock = os.clock
local specialized, generic
local generic_arg1, generic_arg2
local v = ...
if v == "u8" then
specialized = buffer.writeUInt8
generic = buffer.writeByte
elseif v == "u16" then
specialized = buffer.writeUInt16
generic = buffer.writeUnsigned
generic_arg1 = 16
elseif v == "u32" then
specialized = buffer.writeUInt32
generic = buffer.writeUnsigned
generic_arg1 = 32
elseif v == "i8" then
specialized = buffer.writeInt8
generic = buffer.writeSigned
generic_arg1 = 8
elseif v == "i16" then
specialized = buffer.writeInt16
generic = buffer.writeSigned
generic_arg1 = 16
elseif v == "i32" then
specialized = buffer.writeInt32
generic = buffer.writeSigned
generic_arg1 = 32
elseif v == "f16" then
specialized = buffer.writeFloat16
generic = buffer.writeFloat
generic_arg1 = 5
generic_arg2 = 10
elseif v == "f32" then
specialized = buffer.writeFloat32
generic = buffer.writeFloat
generic_arg1 = 8
generic_arg2 = 23
elseif v == "f64" then
specialized = buffer.writeFloat64
generic = buffer.writeFloat
generic_arg1 = 11
generic_arg2 = 52
end
if not specialized or not generic then
print("Argument must start with u, i, or f and end with 8, 16, 32, or 64 -- f8, u64, and i64 do not exist")
return
end
local i1, i2 = 0, 0
local t1 = clock()
while clock()-t1 <= 1 do
specialized(64)
i1 = i1+1
end
if generic_arg1 and generic_arg2 then
local t2 = clock()
while clock()-t2 <= 1 do
generic(generic_arg1, generic_arg2, 64)
i2 = i2+1
end
elseif generic_arg1 then
local t2 = clock()
while clock()-t2 <= 1 do
generic(generic_arg1, 64)
i2 = i2+1
end
else
local t2 = clock()
while clock()-t2 <= 1 do
generic(64)
i2 = i2+1
end
end
local ratio1 = math.floor((i1/i2)*100)
local ratio2 = math.floor((i2/i1)*100)
print(string.format("Iterations in 1s for %s:", v))
print(string.format(" Specialized: %i - %s", i1, string.format("%i%% of generic", ratio1)))
print(string.format(" Generic: %i - %s", i2, string.format("%i%% of specialized", ratio2))) |
--------------------------------------------------------------------------------
-- Handler.......... : onTestAchievements
-- Author........... :
-- Description...... :
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function SteamworksAI.onTestAchievements ( )
--------------------------------------------------------------------------------
log.message ( "Steamworks: *** Starting achievement tests ***" )
local sAchievementID = "ACH_WIN_ONE_GAME"
--local sAchievementID = "ACH_WIN_100_GAMES"
--local sAchievementID = "ACH_TRAVEL_FAR_ACCUM"
--local sAchievementID = "ACH_TRAVEL_FAR_SINGLE"
-------------------------------------------------------------------
-- Set an achievement
-------------------------------------------------------------------
local bOk = Steamworks.SetAchievement ( sAchievementID )
if ( bOk ) then
log.message ( "Steamworks: Achievement '"..sAchievementID.."' was set" )
else
log.warning ( "Steamworks: Achievement '"..sAchievementID.."' wasn't set" )
end
-------------------------------------------------------------------
-- Get the number of achievements
-------------------------------------------------------------------
local nNumAchievements = Steamworks.GetNumAchievements ( )
log.message ( "Steamworks: Number of achievements: "..nNumAchievements )
-------------------------------------------------------------------
-- Iterate over all achievements and show their status ordered by completion
-------------------------------------------------------------------
if ( nNumAchievements > 0 ) then
local nIndex, sName, nPercent, bAchieved, nOldIndex, sAchieved
for i = 0, nNumAchievements -1 do
if ( i == 0 ) then -- get the first achievement
nIndex, sName, nPercent, bAchieved = Steamworks.GetMostAchievedAchievementInfo ( )
else
nOldIndex = nIndex
nIndex, sName, nPercent, bAchieved = Steamworks.GetNextMostAchievedAchievementInfo ( nOldIndex )
end
if ( bAchieved ) then
sAchieved = "\t\tstatus: achieved"
else
sAchieved = "\t\tstatus: not yet achieved"
end
log.message ( "Steamworks: Achievement index: "..i.."\t\tname: "..sName.."\t\t\tperecent completed: "..nPercent..sAchieved )
end
end
-------------------------------------------------------------------
-- Let's see if a single achievement was achieved already
-------------------------------------------------------------------
local bAchieved = Steamworks.GetAchievement ( sAchievementID )
if ( bAchieved ) then
log.message ( "Steamworks: Achievement '"..sAchievementID.."' was achieved." )
else
log.message ( "Steamworks: Achievement '"..sAchievementID.."' was not yet achieved." )
end
-------------------------------------------------------------------
-- Get some info about an achievement
-------------------------------------------------------------------
local sName = Steamworks.GetAchievementName ( sAchievementID )
local sDescription = Steamworks.GetAchievementDescription ( sAchievementID )
local sIcon = Steamworks.GetAchievementIcon ( sAchievementID )
local nPercent = Steamworks.GetAchievementAchievedPercent ( sAchievementID )
log.message ( "Steamworks: Getting info for achievement ID '"..sAchievementID
.."\t\tname: "..sName
.."\t\tdescription: "..sDescription
.."\t\ticon: "..sIcon
.."\t\tpercent achieved: "..nPercent )
-------------------------------------------------------------------
-- Clear an achievement
-------------------------------------------------------------------
local bOk = Steamworks.ClearAchievement ( sAchievementID )
if ( bOk ) then
log.message ( "Steamworks: Achievement '"..sAchievementID.."' was cleared" )
else
log.warning ( "Steamworks: Achievement '"..sAchievementID.."' wasn't cleared" )
end
-------------------------------------------------------------------
-- Store our stats and achievements
-------------------------------------------------------------------
bOk = Steamworks.StoreStats ( )
if ( bOk ) then
log.message ( "Steamworks: Stats and achievements were stored" )
else
log.warning ( "Steamworks: Stats and achievements weren't stored" )
end
this.bAchievementTestRunning ( false )
log.message ( "Steamworks: *** Achievement tests finished***" )
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
|
object_tangible_holiday_empire_day_command_console_comscan_subcomponent_crate = object_tangible_holiday_empire_day_shared_command_console_comscan_subcomponent_crate:new {
}
ObjectTemplates:addTemplate(object_tangible_holiday_empire_day_command_console_comscan_subcomponent_crate, "object/tangible/holiday/empire_day/command_console_comscan_subcomponent_crate.iff")
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:25' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
local ZO_CampaignOverviewManager = ZO_Object:Subclass()
function ZO_CampaignOverviewManager:New(control)
local manager = ZO_Object.New(self)
manager.control = control
CAMPAIGN_OVERVIEW_SCENE = ZO_Scene:New("campaignOverview", SCENE_MANAGER)
CAMPAIGN_OVERVIEW_SCENE:RegisterCallback("StateChange", function(oldState, newState)
if newState == SCENE_SHOWING then
manager:ChangeCategory(manager.overviewType)
end
end)
manager.campaignName = GetControl(control, "CampaignName")
manager:InitializeCategories()
return manager
end
function ZO_CampaignOverviewManager:UpdateCampaignName(campaignId)
local campaignName = GetCampaignName(campaignId)
self.campaignName:SetText(campaignName)
end
function ZO_CampaignOverviewManager:SetCampaignAndQueryType(campaignId, queryType)
self:UpdateCampaignName(campaignId)
end
local CAMPAIGN_OVERVIEW_TYPE_SCORING = 1
local CAMPAIGN_OVERVIEW_TYPE_BONUSES = 2
local CAMPAIGN_OVERVIEW_TYPE_EMPEROR = 3
local CAMPAIGN_OVERVIEW_TYPE_INFO =
{
[CAMPAIGN_OVERVIEW_TYPE_SCORING] =
{
name = GetString(SI_CAMPAIGN_OVERVIEW_CATEGORY_SCORING),
up = "EsoUI/Art/Campaign/overview_indexIcon_scoring_up.dds",
down = "EsoUI/Art/Campaign/overview_indexIcon_scoring_down.dds",
over = "EsoUI/Art/Campaign/overview_indexIcon_scoring_over.dds",
},
[CAMPAIGN_OVERVIEW_TYPE_BONUSES] =
{
name = GetString(SI_CAMPAIGN_OVERVIEW_CATEGORY_BONUSES),
up = "EsoUI/Art/Campaign/overview_indexIcon_bonus_up.dds",
down = "EsoUI/Art/Campaign/overview_indexIcon_bonus_down.dds",
over = "EsoUI/Art/Campaign/overview_indexIcon_bonus_over.dds",
visible = function() return GetAssignedCampaignId() ~= 0 end,
},
[CAMPAIGN_OVERVIEW_TYPE_EMPEROR] =
{
name = GetString(SI_CAMPAIGN_OVERVIEW_CATEGORY_EMPERORSHIP),
up = "EsoUI/Art/Campaign/overview_indexIcon_emperor_up.dds",
down = "EsoUI/Art/Campaign/overview_indexIcon_emperor_down.dds",
over = "EsoUI/Art/Campaign/overview_indexIcon_emperor_over.dds",
},
}
function ZO_CampaignOverviewManager:InitializeCategories()
self.tree = ZO_Tree:New(GetControl(self.control, "Categories"), 60, -10, 280)
local function CategorySetup(node, control, overviewType, down)
local info = CAMPAIGN_OVERVIEW_TYPE_INFO[overviewType]
control.text:SetModifyTextType(MODIFY_TEXT_TYPE_UPPERCASE)
control.text:SetText(info.name)
control.overviewType = overviewType
control.icon:SetTexture(down and info.down or info.up)
control.iconHighlight:SetTexture(info.over)
ZO_IconHeader_Setup(control, down)
end
local function CategorySelected(control, overviewType, selected, reselectingDuringRebuild)
if selected then
self:ChangeCategory(overviewType)
end
CategorySetup(nil, control, overviewType, selected)
end
self.tree:AddTemplate("ZO_CampaignOverviewType", CategorySetup, CategorySelected, nil)
self.tree:SetExclusive(true)
self:RefreshCategories()
self.control:RegisterForEvent(EVENT_ASSIGNED_CAMPAIGN_CHANGED, function() self:RefreshCategories() end)
end
function ZO_CampaignOverviewManager:RefreshCategories()
self.tree:Reset()
for categoryType, categoryInfo in ipairs(CAMPAIGN_OVERVIEW_TYPE_INFO) do
if not categoryInfo.visible or categoryInfo.visible() then
self.tree:AddNode("ZO_CampaignOverviewType", categoryType)
end
end
self.tree:Commit()
end
function ZO_CampaignOverviewManager:ChangeCategory(overviewType)
self.overviewType = overviewType
if not CAMPAIGN_BONUSES_FRAGMENT or not CAMPAIGN_EMPEROR_FRAGMENT or not CAMPAIGN_SCORING_FRAGMENT then
return
end
if overviewType == CAMPAIGN_OVERVIEW_TYPE_SCORING then
CAMPAIGN_OVERVIEW_SCENE:RemoveFragment(CAMPAIGN_BONUSES_FRAGMENT)
CAMPAIGN_OVERVIEW_SCENE:RemoveFragment(CAMPAIGN_EMPEROR_FRAGMENT)
CAMPAIGN_OVERVIEW_SCENE:AddFragment(CAMPAIGN_SCORING_FRAGMENT)
elseif overviewType == CAMPAIGN_OVERVIEW_TYPE_BONUSES then
CAMPAIGN_OVERVIEW_SCENE:RemoveFragment(CAMPAIGN_SCORING_FRAGMENT)
CAMPAIGN_OVERVIEW_SCENE:RemoveFragment(CAMPAIGN_EMPEROR_FRAGMENT)
CAMPAIGN_OVERVIEW_SCENE:AddFragment(CAMPAIGN_BONUSES_FRAGMENT)
else
CAMPAIGN_OVERVIEW_SCENE:RemoveFragment(CAMPAIGN_SCORING_FRAGMENT)
CAMPAIGN_OVERVIEW_SCENE:RemoveFragment(CAMPAIGN_BONUSES_FRAGMENT)
CAMPAIGN_OVERVIEW_SCENE:AddFragment(CAMPAIGN_EMPEROR_FRAGMENT)
end
end
function ZO_CampaignOverview_OnInitialized(self)
CAMPAIGN_OVERVIEW = ZO_CampaignOverviewManager:New(self)
end
|
local cdecl = cdecl or ''
cdecl = cdecl..[[
// Helpers: UTF-8 <> wchar
int igImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count
int igImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // return input UTF-8 bytes count
int igImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_remaining); // return input UTF-8 bytes count
int igImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count)
int igImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string as UTF-8 code-points
]]
return cdecl |
local wibox = require("wibox")
local awful = require("awful")
-- Modules
local tasklist = require("widget.tasklist")
local M = {}
local bar = awful.wibar({ position = "top", screen = s, height = 20, bg = "#00000000" })
function M.bar(s)
-- Create the wibox
-- Add widgets to the wibox
bar:setup({
layout = wibox.layout.align.horizontal,
{
layout = wibox.layout.fixed.horizontal,
},
tasklist.widget(s),
{
layout = wibox.layout.fixed.horizontal,
},
})
return bar
end
function M.visible()
bar.visible = not bar.visible
end
return M
|
--************************
--name : SINGLE_DEL_NX_01.lua
--ver : 0.1
--author : Ferron
--date : 2004/09/08
--lang : de
--desc : terminal mission
--npc :
--************************
--changelog:
--2004/09/08(0.1): recheck(Ferron)
--YYYY/MM/DD(0.0)
--************************
function DIALOG()
NODE(0)
SAY("Next, wie kann ich Ihnen helfen, Sir?")
SAY("Next, wohin wollen Sie heute, Sir?")
SAY("Hallo. Kommen Sie wegen dem Botenjob?")
SAY("Willkommen bei Neocron Exploration Technology Inc. Wie kann ich behilflich sein?")
SAY("Hey. Sind Sie wegen dem Lieferauftrag hier?")
SAY("Tag. Wir von Next koennten Ihre Hilfe gebrauchen, wenn Sie interessiert sind.")
ANSWER("Ja, ich will diesen Lieferjob.",1)
ANSWER("Yeah, Sie brauchen einen Boten? Geben Sie mir einfach das Paket und die notwendigen Informationen...",1)
ANSWER("Ich komme wegen dem Lieferjob. Sagen Sie mir, was wann wohin muss und ich erledige das.",1)
ANSWER("Sorry, ich hab schon einen Job.",4)
ANSWER("Suchen Sie sich jemand anderen dafuer. Ich bin nicht hier, um Ihnen zu helfen.",4)
ANSWER("Hey Bruder, seh ich wie ein Laufbursche aus? Ich liefere nicht aus.",4)
NODE(1)
GIVEQUESTITEM(91)
SAY("Ok. Ich habe hier ein Paket fuer einen Kunden namens %NPC_NAME(1) in %NPC_WORLD(1). Erledigen Sie das so schnell wie moeglich, schliesslich sind wir vor allem ein Transportunternehmen. Viel Glueck.")
SAY("Alles klar, Runner. %NPC_NAME(1) wartet auf diese Lieferung. Versuchen Sie ihn in %NPC_WORLD(1) zu finden. Bitte versuchen Sie das schnell zu erledigen, schliesslich sind wir trotz allem immer noch ein Transportunternehmen.")
SAY("Hmmm, das ist das Falsche... Oh, ach ja, hoeren Sie zu. %NPC_NAME(1) von Bergen-Dahl Motor Company braucht dieses Paket. Liefern Sie es nach %NPC_WORLD(1) und das moeglichst schnell. Danach sehen wir uns hier wieder.")
ACTIVATEDIALOGTRIGGER(0)
SETNEXTDIALOGSTATE(2)
ENDDIALOG()
NODE(2)
ISMISSIONTARGETACCOMPLISHED(1)
if (result==0) then
SAY("Wo immer Sie auch hin wollen - NEXT bringt Sie hin. Das gleiche gilt auch fuer den Paketdienst. Also liefern Sie das Paket, wie es abgemacht war.")
SAY("%NPC_NAME(1) von Bergen-Dahl Motors rief an, schon wieder, und fragte nach seinem Paket. Beeilen Sie sich endlich mit der Lieferung.")
SAY("Na, etwas chaotisch veranlagt? Nun, Next ist das jedenfalls nicht. Hier wird gemacht, was einem gesagt wird. Liefern Sie das verdammte Paket aus!")
SAY("Hoeren Sie, ich habe keine Zeit zum Reden. %NPC_NAME(1) wartet immer noch auf sein Paket.")
ENDDIALOG()
else
SAY("Gut gemacht. Die Jungs von Bergen-Dahl riefen an und meinten, dass Sie das Paket erhalten haben. Der Lohn in Hoehe von %REWARD_MONEY() Credits wurde Ihrem Konto gutgeschrieben.")
SAY("Danke. %NPC_NAME(1) bestaetigte die Lieferung und %REWARD_MONEY() Credits wurden eben auf Ihr Konto ueberwiesen. Danke fuer die Hilfe.")
SAY("Hallo. Die Lieferung wurde bestaetigt und %REWARD_MONEY() Credits auf Ihr Konto ueberwiesen. Auf Wedersehen und bis zum naechsten Mal.")
SAY("Bergen-Dahl Motors rief an und bestaetigte die Lieferung. Ich habe %REWARD_MONEY() Credits auf Ihr Konto ueberwiesen. Wir danken Ihnen fuer die Unterstuetzung.")
SAY("Das war nicht sonderlich schnell... Aber letztlich haben die Leute von Bergen-Dahl Motors Ihr Paket erhalten. %REWARD_MONEY() Credits wurden Ihnen soeben ueberwiesen. Das ist alles, Sie koennen gehen.")
ACTIVATEDIALOGTRIGGER(2)
ENDDIALOG()
end
NODE(3)
TAKEQUESTITEM(91)
if (result==0) then
SAY("Hoer zu, Bruder. Wir von Bergen-Dahl lassen uns nicht verarschen. Sie haben ein Paket fuer mich, richtig? Also geben Sie es mir!")
SAY("Ich erwarte diese Lieferung schon lange. Ich hoffe fuer Sie, dass Sie es nicht vor mir zurueckhalten, Freund...")
SAY("Yeah, sicher, halt die Bergen-Dahl-Affen zum Narren. Warum auch nicht? Ich weiss, dass Sie mir was liefern sollten. Also wo ist es?")
ENDDIALOG()
else
SAY("Ah, gut. Das Paket von Next, richtig? %NPC_NAME(0) wird Sie fuer die Lieferung bezahlen.")
SAY("Sie haben das Paket von Next! Gut. %NPC_NAME(0) sollte Ihnen fuer den Job ein paar Credits geben.")
SAY("Ist das das Zeug, dass %NPC_NAME(0) von Next uns schickt? Ok. Sie werden auch deine Bezahlung regeln. Danke, Kumpel.")
SAY("Alles klar! Das Next Paket. Schon lustig, dass Bergen-Dahl Motors leider in dieser Angelegenheit auf Next angewiesen ist. %NPC_NAME(0) wird die Bezahlung regeln.")
SAY("Das hat ziemlich lange gedauert. %NPC_NAME(0) wird Sie bezahlen, ich wuerde es nicht machen.")
ACTIVATEDIALOGTRIGGER(1)
SETNEXTDIALOGSTATE(5)
ENDDIALOG()
end
NODE(4)
SAY("Ok, bitte gehen Sie, wenn Sie hier keine Geschaefte bei Next zu erledigen haben.")
SAY("Ich bin es, der mit Ihnen redet. Ich bin es auch, der Sie ignoriert...")
SAY("Next dankt fuer Ihren Besuch und wuenscht einen schoenen Tag. Bye.")
ENDDIALOG()
NODE(5)
SAY("Hey was machen Sie noch hier? Los gehen Sie zu %NPC_NAME(0) um Ihre Belohnung abzuholen.")
ENDDIALOG()
end
|
necklace_crushed_brooch = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/tangible/wearables/necklace/necklace_crushed_brooch.iff",
craftingValues = {
},
customizationStringNames = {},
customizationValues = {},
skillMods = {
{"force_assembly", 25},
{"force_experimentation", 25}
}
}
addLootItemTemplate("necklace_crushed_brooch", necklace_crushed_brooch)
|
-- Copyright (C) 2019 Miku AuahDark
--
-- 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 path = (...):sub(1, #(...) - #(".math.Math"))
local nvec = require(path..".3p.nvec")
---@class L2DF.Math
local KMath = {}
local min, max, atan2, sin, cos = math.min, math.max, (math.atan2 or math.atan), math.sin, math.cos
local pi = math.pi
---@param v number
---@param a number
---@param b number
---@return number
function KMath.range(v, a, b)
return min(max(v, a), b)
end
---@param t number
function KMath.lerp(v1, v2, t)
return v1 * (1 - t) + v2 * t
end
---@param v number
function KMath.getEasingSine(v)
return v < 0 and 0 or (v > 1 and 1 or (0.5 - 0.5 * cos(v * pi)))
end
---@param from NVec
---@param to NVec
---@return number
function KMath.directionToRadian(from, to)
return ((atan2(to.y, to.x) - atan2(from.y, from.x)) + pi) % (2 * pi) - pi
end
---@param from NVec
---@param to NVec
---@return number
function KMath.directionToDegrees(from, to)
local deg = KMath.directionToRadian(from, to) * 180 / pi
if (to.x - from.x) > 0 then
return -deg
else
return deg
end
end
---@param r number
---@return NVec
function KMath.radianToDirection(r)
return nvec(sin(r), cos(r))
end
return KMath
|
app = require("app_mhz19")
config = require("config")
setup = require("setup")
telnet = require("telnet")
setup.start() |
local t = Def.ActorFrame {
LoadActor("Backing");
};
if SCREENMAN:GetTopScreen() ~= "ScreenNetRoom" then
t[#t+1] = Def.ActorFrame{
--P1 Light--
Def.Sprite{
Texture=THEME:GetPathG("MusicWheelItem Song","NormalPart/score");
InitCommand=function(s)
if GAMESTATE:GetNumPlayersEnabled() == 2 then
s:x(-158):zoomx(0.5):diffuse(color("#00f0ff"))
elseif GAMESTATE:IsPlayerEnabled(PLAYER_1) then
s:x(-155):diffuse(color("#00f0ff"))
end;
end;
CurrentSongChangedMessageCommand=cmd(playcommand,"Set");
CurrentCourseChangedMessageCommand=cmd(playcommand,"Set");
CurrentStepsP1ChangedMessageCommand=cmd(playcommand,"Set");
CurrentTrailP1ChangedMessageCommand=cmd(playcommand,"Set");
SetCommand=function(self,params)
local SongOrCourse, StepsOrTrail;
if GAMESTATE:IsCourseMode() then
SongOrCourse = GAMESTATE:GetCurrentCourse();
StepsOrTrail = GAMESTATE:GetCurrentTrail(PLAYER_1);
else
SongOrCourse = GAMESTATE:GetCurrentSong();
StepsOrTrail = GAMESTATE:GetCurrentSteps(PLAYER_1);
end;
if SongOrCourse and StepsOrTrail then
local st = StepsOrTrail:GetStepsType();
local diff = StepsOrTrail:GetDifficulty();
local courseType = GAMESTATE:IsCourseMode() and SongOrCourse:GetCourseType() or nil;
if PROFILEMAN:IsPersistentProfile(PLAYER_1) then
-- player profile
profile = PROFILEMAN:GetProfile(PLAYER_1);
else
-- machine profile
profile = PROFILEMAN:GetMachineProfile();
end;
scorelist = profile:GetHighScoreList(SongOrCourse,StepsOrTrail);
assert(scorelist);
local scores = scorelist:GetHighScores();
local grade;
if scores[1] then
grade = scores[1]:GetGrade();
assert(grade);
if scores[1]:GetScore()>1 then
if grade=="Grade_Tier07" then
self:visible(true);
self:diffuse(color("#ff0000"));
self:draworder(1);
else
self:visible(true);
self:diffuse(color("#00f0ff"));
end;
else
self:visible(false);
end;
else
self:visible(false);
end;
else
self:visible(false);
end;
end;
};
--P2 Light--
Def.Sprite{
Texture=THEME:GetPathG("MusicWheelItem Song","NormalPart/score");
InitCommand=function(s)
if GAMESTATE:GetNumPlayersEnabled() == 2 then
s:x(-153):zoomx(0.5):diffuse(color("#ff00cf"))
elseif GAMESTATE:IsPlayerEnabled(PLAYER_2) then
s:x(-155):diffuse(color("#ff00cf"))
end;
end;
CurrentSongChangedMessageCommand=cmd(playcommand,"Set");
CurrentCourseChangedMessageCommand=cmd(playcommand,"Set");
CurrentStepsP1ChangedMessageCommand=cmd(playcommand,"Set");
CurrentTrailP1ChangedMessageCommand=cmd(playcommand,"Set");
SetCommand=function(self,params)
local SongOrCourse, StepsOrTrail;
if GAMESTATE:IsCourseMode() then
SongOrCourse = GAMESTATE:GetCurrentCourse();
StepsOrTrail = GAMESTATE:GetCurrentTrail(PLAYER_2);
else
SongOrCourse = GAMESTATE:GetCurrentSong();
StepsOrTrail = GAMESTATE:GetCurrentSteps(PLAYER_2);
end;
if SongOrCourse and StepsOrTrail then
local st = StepsOrTrail:GetStepsType();
local diff = StepsOrTrail:GetDifficulty();
local courseType = GAMESTATE:IsCourseMode() and SongOrCourse:GetCourseType() or nil;
if PROFILEMAN:IsPersistentProfile(PLAYER_2) then
-- player profile
profile = PROFILEMAN:GetProfile(PLAYER_2);
else
-- machine profile
profile = PROFILEMAN:GetMachineProfile();
end;
scorelist = profile:GetHighScoreList(SongOrCourse,StepsOrTrail);
assert(scorelist);
local scores = scorelist:GetHighScores();
local grade;
if scores[1] then
grade = scores[1]:GetGrade();
assert(grade);
if scores[1]:GetScore()>1 then
if grade=="Grade_Tier07" then
self:visible(true);
self:diffuse(color("#ff0000"));
self:draworder(1);
else
self:visible(true);
self:diffuse(color("#ff00cf"));
end;
else
self:visible(false);
end;
else
self:visible(false);
end;
else
self:visible(false);
end;
end;
};
};
end;
t[#t+1] = Def.RollingNumbers{
Font="ScreenSelectMusic score",
CurrentSongChangedMessageCommand=cmd(playcommand,"Set");
CurrentCourseChangedMessageCommand=cmd(playcommand,"Set");
CurrentStepsP1ChangedMessageCommand=cmd(playcommand,"Set");
CurrentTrailP1ChangedMessageCommand=cmd(playcommand,"Set");
InitCommand=cmd(x,40);
SetCommand= function(self)
local song =
local score =
self:Load("RollingNumbersMusic"):targetnumber(1000)
end;
};
if GAMESTATE:GetCoinMode() == 'CoinMode_Home' and SCREENMAN:GetTopScreen() ~= "ScreenNetRoom" then
t[#t+1] = Def.ActorFrame {
LoadActor("frame")..{
BeginCommand=function(self,param)
if not GAMESTATE:IsPlayerEnabled('PlayerNumber_P1') then
self:croptop(0.5)
elseif not GAMESTATE:IsPlayerEnabled('PlayerNumber_P2') then
self:cropbottom(0.5)
end
end;
};
};
end
return t; |
--------------------------------
-- @module AssetsManager
-- @extend Node
-- @parent_module cc
---@class cc.AssetsManager:cc.Node
local AssetsManager = {}
cc.AssetsManager = AssetsManager
--------------------------------
---
---@param storagePath string
---@return cc.AssetsManager
function AssetsManager:setStoragePath(storagePath)
end
--------------------------------
---
---@param packageUrl string
---@return cc.AssetsManager
function AssetsManager:setPackageUrl(packageUrl)
end
--------------------------------
---
---@return boolean
function AssetsManager:checkUpdate()
end
--------------------------------
---
---@return string
function AssetsManager:getStoragePath()
end
--------------------------------
---
---@return cc.AssetsManager
function AssetsManager:update()
end
--------------------------------
--- @brief Sets connection time out in seconds
---@param timeout number
---@return cc.AssetsManager
function AssetsManager:setConnectionTimeout(timeout)
end
--------------------------------
---
---@param versionFileUrl string
---@return cc.AssetsManager
function AssetsManager:setVersionFileUrl(versionFileUrl)
end
--------------------------------
---
---@return string
function AssetsManager:getPackageUrl()
end
--------------------------------
--- @brief Gets connection time out in seconds
---@return number
function AssetsManager:getConnectionTimeout()
end
--------------------------------
---
---@return string
function AssetsManager:getVersion()
end
--------------------------------
---
---@return string
function AssetsManager:getVersionFileUrl()
end
--------------------------------
---
---@return cc.AssetsManager
function AssetsManager:deleteVersion()
end
--------------------------------
---
---@param packageUrl string
---@param versionFileUrl string
---@param storagePath string
---@param errorCallback fun(arg0:number)
---@param progressCallback fun(arg0:number)
---@param successCallback fun()
---@return cc.AssetsManager
function AssetsManager:create(packageUrl, versionFileUrl, storagePath, errorCallback, progressCallback, successCallback)
end
--------------------------------
---
---@return cc.AssetsManager
function AssetsManager:AssetsManager()
end
return nil
|
--[[
Copyright 2016 Marek Vavrusa <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local ffi = require('ffi')
local bit = require('bit')
local cdef = require('bpf.cdef')
local BPF, HELPER = ffi.typeof('struct bpf'), ffi.typeof('struct bpf_func_id')
local const_width = {
[1] = BPF.B, [2] = BPF.H, [4] = BPF.W, [8] = BPF.DW,
}
local const_width_type = {
[1] = ffi.typeof('uint8_t'), [2] = ffi.typeof('uint16_t'), [4] = ffi.typeof('uint32_t'), [8] = ffi.typeof('uint64_t'),
}
-- Built-ins that will be translated into BPF instructions
-- i.e. bit.bor(0xf0, 0x0f) becomes {'alu64, or, k', reg(0xf0), reg(0x0f), 0, 0}
local builtins = {
[bit.lshift] = 'LSH',
[bit.rshift] = 'RSH',
[bit.band] = 'AND',
[bit.bnot] = 'NEG',
[bit.bor] = 'OR',
[bit.bxor] = 'XOR',
[bit.arshift] = 'ARSH',
-- Extensions and intrinsics
}
local function width_type(w)
-- Note: ffi.typeof doesn't accept '?' as template
return const_width_type[w] or ffi.typeof(string.format('uint8_t [%d]', w))
end
builtins.width_type = width_type
-- Return struct member size/type (requires LuaJIT 2.1+)
-- I am ashamed that there's no easier way around it.
local function sizeofattr(ct, name)
if not ffi.typeinfo then error('LuaJIT 2.1+ is required for ffi.typeinfo') end
local cinfo = ffi.typeinfo(ct)
while true do
cinfo = ffi.typeinfo(cinfo.sib)
if not cinfo then return end
if cinfo.name == name then break end
end
local size = math.max(1, ffi.typeinfo(cinfo.sib or ct).size - cinfo.size)
-- Guess type name
return size, builtins.width_type(size)
end
builtins.sizeofattr = sizeofattr
-- Byte-order conversions for little endian
local function ntoh(x, w)
if w then x = ffi.cast(const_width_type[w/8], x) end
return bit.bswap(x)
end
local function hton(x, w) return ntoh(x, w) end
builtins.ntoh = ntoh
builtins.hton = hton
builtins[ntoh] = function (e, dst, a, w)
-- This is trickery, but TO_LE means cpu_to_le(),
-- and we want exactly the opposite as network is always 'be'
w = w or ffi.sizeof(e.V[a].type)*8
if w == 8 then return end -- NOOP
assert(w <= 64, 'NYI: hton(a[, width]) - operand larger than register width')
-- Allocate registers and execute
e.vcopy(dst, a)
e.emit(BPF.ALU + BPF.END + BPF.TO_BE, e.vreg(dst), 0, 0, w)
end
builtins[hton] = function (e, dst, a, w)
w = w or ffi.sizeof(e.V[a].type)*8
if w == 8 then return end -- NOOP
assert(w <= 64, 'NYI: hton(a[, width]) - operand larger than register width')
-- Allocate registers and execute
e.vcopy(dst, a)
e.emit(BPF.ALU + BPF.END + BPF.TO_LE, e.vreg(dst), 0, 0, w)
end
-- Byte-order conversions for big endian are no-ops
if ffi.abi('be') then
ntoh = function (x, w)
return w and ffi.cast(const_width_type[w/8], x) or x
end
hton = ntoh
builtins[ntoh] = function(_, _, _) return end
builtins[hton] = function(_, _, _) return end
end
-- Other built-ins
local function xadd() error('NYI') end
builtins.xadd = xadd
builtins[xadd] = function (e, ret, a, b, off)
local vinfo = e.V[a].const
assert(vinfo and vinfo.__dissector, 'xadd(a, b[, offset]) called on non-pointer')
local w = ffi.sizeof(vinfo.__dissector)
-- Calculate structure attribute offsets
if e.V[off] and type(e.V[off].const) == 'string' then
local ct, field = vinfo.__dissector, e.V[off].const
off = ffi.offsetof(ct, field)
assert(off, 'xadd(a, b, offset) - offset is not valid in given structure')
w = sizeofattr(ct, field)
end
assert(w == 4 or w == 8, 'NYI: xadd() - 1 and 2 byte atomic increments are not supported')
-- Allocate registers and execute
local src_reg = e.vreg(b)
local dst_reg = e.vreg(a)
-- Set variable for return value and call
e.vset(ret)
e.vreg(ret, 0, true, ffi.typeof('int32_t'))
-- Optimize the NULL check away if provably not NULL
if not e.V[a].source or e.V[a].source:find('_or_null', 1, true) then
e.emit(BPF.JMP + BPF.JEQ + BPF.K, dst_reg, 0, 1, 0) -- if (dst != NULL)
end
e.emit(BPF.XADD + BPF.STX + const_width[w], dst_reg, src_reg, off or 0, 0)
end
local function probe_read() error('NYI') end
builtins.probe_read = probe_read
builtins[probe_read] = function (e, ret, dst, src, vtype, ofs)
e.reg_alloc(e.tmpvar, 1)
-- Load stack pointer to dst, since only load to stack memory is supported
-- we have to use allocated stack memory or create a new allocation and convert
-- to pointer type
e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 1, 10, 0, 0)
if not e.V[dst].const or not e.V[dst].const.__base > 0 then
builtins[ffi.new](e, dst, vtype) -- Allocate stack memory
end
e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 1, 0, 0, -e.V[dst].const.__base)
-- Set stack memory maximum size bound
e.reg_alloc(e.tmpvar, 2)
if not vtype then
vtype = cdef.typename(e.V[dst].type)
-- Dereference pointer type to pointed type for size calculation
if vtype:sub(-1) == '*' then vtype = vtype:sub(0, -2) end
end
local w = ffi.sizeof(vtype)
e.emit(BPF.ALU64 + BPF.MOV + BPF.K, 2, 0, 0, w)
-- Set source pointer
if e.V[src].reg then
e.reg_alloc(e.tmpvar, 3) -- Copy from original register
e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 3, e.V[src].reg, 0, 0)
else
e.vreg(src, 3)
e.reg_spill(src) -- Spill to avoid overwriting
end
if ofs and ofs > 0 then
e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 3, 0, 0, ofs)
end
-- Call probe read helper
ret = ret or e.tmpvar
e.vset(ret)
e.vreg(ret, 0, true, ffi.typeof('int32_t'))
e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, HELPER.probe_read)
e.V[e.tmpvar].reg = nil -- Free temporary registers
end
builtins[ffi.cast] = function (e, dst, ct, x)
assert(e.V[ct].const, 'ffi.cast(ctype, x) called with bad ctype')
e.vcopy(dst, x)
if e.V[x].const and type(e.V[x].const) == 'table' then
e.V[dst].const.__dissector = ffi.typeof(e.V[ct].const)
end
e.V[dst].type = ffi.typeof(e.V[ct].const)
-- Specific types also encode source of the data
-- This is because BPF has different helpers for reading
-- different data sources, so variables must track origins.
-- struct pt_regs - source of the data is probe
-- struct skb - source of the data is socket buffer
-- struct X - source of the data is probe/tracepoint
if ffi.typeof(e.V[ct].const) == ffi.typeof('struct pt_regs') then
e.V[dst].source = 'ptr_to_probe'
end
end
builtins[ffi.new] = function (e, dst, ct, x)
if type(ct) == 'number' then
ct = ffi.typeof(e.V[ct].const) -- Get ctype from variable
end
assert(not x, 'NYI: ffi.new(ctype, ...) - initializer is not supported')
assert(not cdef.isptr(ct, true), 'NYI: ffi.new(ctype, ...) - ctype MUST NOT be a pointer')
e.vset(dst, nil, ct)
e.V[dst].source = 'ptr_to_stack'
e.V[dst].const = {__base = e.valloc(ffi.sizeof(ct), true), __dissector = ct}
-- Set array dissector if created an array
-- e.g. if ct is 'char [2]', then dissector is 'char'
local elem_type = tostring(ct):match('ctype<(.+)%s%[(%d+)%]>')
if elem_type then
e.V[dst].const.__dissector = ffi.typeof(elem_type)
end
end
builtins[ffi.copy] = function (e, ret, dst, src)
assert(cdef.isptr(e.V[dst].type), 'ffi.copy(dst, src) - dst MUST be a pointer type')
assert(cdef.isptr(e.V[src].type), 'ffi.copy(dst, src) - src MUST be a pointer type')
-- Specific types also encode source of the data
-- struct pt_regs - source of the data is probe
-- struct skb - source of the data is socket buffer
if e.V[src].source and e.V[src].source:find('ptr_to_probe', 1, true) then
e.reg_alloc(e.tmpvar, 1)
-- Load stack pointer to dst, since only load to stack memory is supported
-- we have to either use spilled variable or allocated stack memory offset
e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 1, 10, 0, 0)
if e.V[dst].spill then
e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 1, 0, 0, -e.V[dst].spill)
elseif e.V[dst].const.__base then
e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 1, 0, 0, -e.V[dst].const.__base)
else error('ffi.copy(dst, src) - can\'t get stack offset of dst') end
-- Set stack memory maximum size bound
local dst_tname = cdef.typename(e.V[dst].type)
if dst_tname:sub(-1) == '*' then dst_tname = dst_tname:sub(0, -2) end
e.reg_alloc(e.tmpvar, 2)
e.emit(BPF.ALU64 + BPF.MOV + BPF.K, 2, 0, 0, ffi.sizeof(dst_tname))
-- Set source pointer
if e.V[src].reg then
e.reg_alloc(e.tmpvar, 3) -- Copy from original register
e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 3, e.V[src].reg, 0, 0)
else
e.vreg(src, 3)
e.reg_spill(src) -- Spill to avoid overwriting
end
-- Call probe read helper
e.vset(ret)
e.vreg(ret, 0, true, ffi.typeof('int32_t'))
e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, HELPER.probe_read)
e.V[e.tmpvar].reg = nil -- Free temporary registers
elseif e.V[src].const and e.V[src].const.__map then
error('NYI: ffi.copy(dst, src) - src is backed by BPF map')
elseif e.V[src].const and e.V[src].const.__dissector then
error('NYI: ffi.copy(dst, src) - src is backed by socket buffer')
else
-- TODO: identify cheap register move
-- TODO: identify copy to/from stack
error('NYI: ffi.copy(dst, src) - src is neither BPF map/socket buffer or probe')
end
end
-- print(format, ...) builtin changes semantics from Lua print(...)
-- the first parameter has to be format and only reduced set of conversion specificers
-- is allowed: %d %u %x %ld %lu %lx %lld %llu %llx %p %s
builtins[print] = function (e, ret, fmt, a1, a2, a3)
-- Load format string and length
e.reg_alloc(e.V[e.tmpvar], 1)
e.reg_alloc(e.V[e.tmpvar+1], 1)
if type(e.V[fmt].const) == 'string' then
local src = e.V[fmt].const
local len = #src + 1
local dst = e.valloc(len, src)
-- TODO: this is materialize step
e.V[fmt].const = {__base=dst}
e.V[fmt].type = ffi.typeof('char ['..len..']')
elseif e.V[fmt].const.__base then -- luacheck: ignore
-- NOP
else error('NYI: print(fmt, ...) - format variable is not literal/stack memory') end
-- Prepare helper call
e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 1, 10, 0, 0)
e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 1, 0, 0, -e.V[fmt].const.__base)
e.emit(BPF.ALU64 + BPF.MOV + BPF.K, 2, 0, 0, ffi.sizeof(e.V[fmt].type))
if a1 then
local args = {a1, a2, a3}
assert(#args <= 3, 'print(fmt, ...) - maximum of 3 arguments supported')
for i, arg in ipairs(args) do
e.vcopy(e.tmpvar, arg) -- Copy variable
e.vreg(e.tmpvar, 3+i-1) -- Materialize it in arg register
end
end
-- Call helper
e.vset(ret)
e.vreg(ret, 0, true, ffi.typeof('int32_t')) -- Return is integer
e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, HELPER.trace_printk)
e.V[e.tmpvar].reg = nil -- Free temporary registers
end
-- Implements bpf_perf_event_output(ctx, map, flags, var, vlen) on perf event map
local function perf_submit(e, dst, map_var, src)
-- Set R2 = map fd (indirect load)
local map = e.V[map_var].const
e.vcopy(e.tmpvar, map_var)
e.vreg(e.tmpvar, 2, true, ffi.typeof('uint64_t'))
e.LD_IMM_X(2, BPF.PSEUDO_MAP_FD, map.fd, ffi.sizeof('uint64_t'))
-- Set R1 = ctx
e.reg_alloc(e.tmpvar, 1) -- Spill anything in R1 (unnamed tmp variable)
e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 1, 6, 0, 0) -- CTX is always in R6, copy
-- Set R3 = flags
e.vset(e.tmpvar, nil, 0) -- BPF_F_CURRENT_CPU
e.vreg(e.tmpvar, 3, false, ffi.typeof('uint64_t'))
-- Set R4 = pointer to src on stack
assert(e.V[src].const.__base, 'NYI: submit(map, var) - variable is not on stack')
e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 4, 10, 0, 0)
e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 4, 0, 0, -e.V[src].const.__base)
-- Set R5 = src length
e.emit(BPF.ALU64 + BPF.MOV + BPF.K, 5, 0, 0, ffi.sizeof(e.V[src].type))
-- Set R0 = ret and call
e.vset(dst)
e.vreg(dst, 0, true, ffi.typeof('int32_t')) -- Return is integer
e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, HELPER.perf_event_output)
e.V[e.tmpvar].reg = nil -- Free temporary registers
end
-- Implements bpf_skb_load_bytes(ctx, off, var, vlen) on skb->data
local function load_bytes(e, dst, off, var)
-- Set R2 = offset
e.vset(e.tmpvar, nil, off)
e.vreg(e.tmpvar, 2, false, ffi.typeof('uint64_t'))
-- Set R1 = ctx
e.reg_alloc(e.tmpvar, 1) -- Spill anything in R1 (unnamed tmp variable)
e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 1, 6, 0, 0) -- CTX is always in R6, copy
-- Set R3 = pointer to var on stack
assert(e.V[var].const.__base, 'NYI: load_bytes(off, var, len) - variable is not on stack')
e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 3, 10, 0, 0)
e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 3, 0, 0, -e.V[var].const.__base)
-- Set R4 = var length
e.emit(BPF.ALU64 + BPF.MOV + BPF.K, 4, 0, 0, ffi.sizeof(e.V[var].type))
-- Set R0 = ret and call
e.vset(dst)
e.vreg(dst, 0, true, ffi.typeof('int32_t')) -- Return is integer
e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, HELPER.skb_load_bytes)
e.V[e.tmpvar].reg = nil -- Free temporary registers
end
-- Implements bpf_get_stack_id()
local function stack_id(e, ret, map_var, key)
-- Set R2 = map fd (indirect load)
local map = e.V[map_var].const
e.vcopy(e.tmpvar, map_var)
e.vreg(e.tmpvar, 2, true, ffi.typeof('uint64_t'))
e.LD_IMM_X(2, BPF.PSEUDO_MAP_FD, map.fd, ffi.sizeof('uint64_t'))
-- Set R1 = ctx
e.reg_alloc(e.tmpvar, 1) -- Spill anything in R1 (unnamed tmp variable)
e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 1, 6, 0, 0) -- CTX is always in R6, copy
-- Load flags in R2 (immediate value or key)
local imm = e.V[key].const
assert(tonumber(imm), 'NYI: stack_id(map, var), var must be constant number')
e.reg_alloc(e.tmpvar, 3) -- Spill anything in R2 (unnamed tmp variable)
e.LD_IMM_X(3, 0, imm, 8)
-- Return R0 as signed integer
e.vset(ret)
e.vreg(ret, 0, true, ffi.typeof('int32_t'))
e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, HELPER.get_stackid)
e.V[e.tmpvar].reg = nil -- Free temporary registers
end
-- table.insert(table, value) keeps semantics with the exception of BPF maps
-- map `perf_event` -> submit inserted value
builtins[table.insert] = function (e, dst, map_var, value)
assert(e.V[map_var].const.__map, 'NYI: table.insert() supported only on BPF maps')
return perf_submit(e, dst, map_var, value)
end
-- bpf_get_current_comm(buffer) - write current process name to byte buffer
local function comm() error('NYI') end
builtins[comm] = function (e, ret, dst)
-- Set R1 = buffer
assert(e.V[dst].const.__base, 'NYI: comm(buffer) - buffer variable is not on stack')
e.reg_alloc(e.tmpvar, 1) -- Spill
e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 1, 10, 0, 0)
e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 1, 0, 0, -e.V[dst].const.__base)
-- Set R2 = length
e.reg_alloc(e.tmpvar, 2) -- Spill
e.emit(BPF.ALU64 + BPF.MOV + BPF.K, 2, 0, 0, ffi.sizeof(e.V[dst].type))
-- Return is integer
e.vset(ret)
e.vreg(ret, 0, true, ffi.typeof('int32_t'))
e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, HELPER.get_current_comm)
e.V[e.tmpvar].reg = nil -- Free temporary registers
end
-- Math library built-ins
math.log2 = function () error('NYI') end
builtins[math.log2] = function (e, dst, x)
-- Classic integer bits subdivison algorithm to find the position
-- of the highest bit set, adapted for BPF bytecode-friendly operations.
-- https://graphics.stanford.edu/~seander/bithacks.html
-- r = 0
local r = e.vreg(dst, nil, true)
e.emit(BPF.ALU64 + BPF.MOV + BPF.K, r, 0, 0, 0)
-- v = x
e.vcopy(e.tmpvar, x)
local v = e.vreg(e.tmpvar, 2)
if cdef.isptr(e.V[x].const) then -- No pointer arithmetics, dereference
e.vderef(v, v, {const = {__dissector=ffi.typeof('uint64_t')}})
end
-- Invert value to invert all tests, otherwise we would need and+jnz
e.emit(BPF.ALU64 + BPF.NEG + BPF.K, v, 0, 0, 0) -- v = ~v
-- Unrolled test cases, converted masking to arithmetic as we don't have "if !(a & b)"
-- As we're testing inverted value, we have to use arithmetic shift to copy MSB
for i=4,0,-1 do
local k = bit.lshift(1, i)
e.emit(BPF.JMP + BPF.JGT + BPF.K, v, 0, 2, bit.bnot(bit.lshift(1, k))) -- if !upper_half(x)
e.emit(BPF.ALU64 + BPF.ARSH + BPF.K, v, 0, 0, k) -- v >>= k
e.emit(BPF.ALU64 + BPF.OR + BPF.K, r, 0, 0, k) -- r |= k
end
-- No longer constant, cleanup tmpvars
e.V[dst].const = nil
e.V[e.tmpvar].reg = nil
end
builtins[math.log10] = function (e, dst, x)
-- Compute log2(x) and transform
builtins[math.log2](e, dst, x)
-- Relationship: log10(v) = log2(v) / log2(10)
local r = e.V[dst].reg
e.emit(BPF.ALU64 + BPF.ADD + BPF.K, r, 0, 0, 1) -- Compensate round-down
e.emit(BPF.ALU64 + BPF.MUL + BPF.K, r, 0, 0, 1233) -- log2(10) ~ 1233>>12
e.emit(BPF.ALU64 + BPF.RSH + BPF.K, r, 0, 0, 12)
end
builtins[math.log] = function (e, dst, x)
-- Compute log2(x) and transform
builtins[math.log2](e, dst, x)
-- Relationship: ln(v) = log2(v) / log2(e)
local r = e.V[dst].reg
e.emit(BPF.ALU64 + BPF.ADD + BPF.K, r, 0, 0, 1) -- Compensate round-down
e.emit(BPF.ALU64 + BPF.MUL + BPF.K, r, 0, 0, 2839) -- log2(e) ~ 2839>>12
e.emit(BPF.ALU64 + BPF.RSH + BPF.K, r, 0, 0, 12)
end
-- Call-type helpers
local function call_helper(e, dst, h, vtype)
e.vset(dst)
e.vreg(dst, 0, true, vtype or ffi.typeof('uint64_t'))
e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, h)
e.V[dst].const = nil -- Target is not a function anymore
end
local function cpu() error('NYI') end
local function rand() error('NYI') end
local function time() error('NYI') end
local function pid_tgid() error('NYI') end
local function uid_gid() error('NYI') end
-- Export helpers and builtin variants
builtins.cpu = cpu
builtins.time = time
builtins.pid_tgid = pid_tgid
builtins.uid_gid = uid_gid
builtins.comm = comm
builtins.perf_submit = perf_submit
builtins.stack_id = stack_id
builtins.load_bytes = load_bytes
builtins[cpu] = function (e, dst) return call_helper(e, dst, HELPER.get_smp_processor_id) end
builtins[rand] = function (e, dst) return call_helper(e, dst, HELPER.get_prandom_u32, ffi.typeof('uint32_t')) end
builtins[time] = function (e, dst) return call_helper(e, dst, HELPER.ktime_get_ns) end
builtins[pid_tgid] = function (e, dst) return call_helper(e, dst, HELPER.get_current_pid_tgid) end
builtins[uid_gid] = function (e, dst) return call_helper(e, dst, HELPER.get_current_uid_gid) end
builtins[perf_submit] = function (e, dst, map, value) return perf_submit(e, dst, map, value) end
builtins[stack_id] = function (e, dst, map, key) return stack_id(e, dst, map, key) end
builtins[load_bytes] = function (e, dst, off, var, len) return load_bytes(e, dst, off, var, len) end
return builtins
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.